Implement PaddedVector
[alexxy/gromacs.git] / src / gromacs / essentialdynamics / edsam.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,2018, 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.
10  *
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.
15  *
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.
20  *
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.
25  *
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.
33  *
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.
36  */
37 #include "gmxpre.h"
38
39 #include "edsam.h"
40
41 #include <cmath>
42 #include <cstdio>
43 #include <cstring>
44 #include <ctime>
45
46 #include "gromacs/commandline/filenm.h"
47 #include "gromacs/compat/make_unique.h"
48 #include "gromacs/domdec/domdec_struct.h"
49 #include "gromacs/fileio/gmxfio.h"
50 #include "gromacs/fileio/xvgr.h"
51 #include "gromacs/gmxlib/network.h"
52 #include "gromacs/gmxlib/nrnb.h"
53 #include "gromacs/linearalgebra/nrjac.h"
54 #include "gromacs/math/functions.h"
55 #include "gromacs/math/utilities.h"
56 #include "gromacs/math/vec.h"
57 #include "gromacs/math/vectypes.h"
58 #include "gromacs/mdlib/broadcaststructs.h"
59 #include "gromacs/mdlib/constr.h"
60 #include "gromacs/mdlib/groupcoord.h"
61 #include "gromacs/mdlib/mdrun.h"
62 #include "gromacs/mdlib/sim_util.h"
63 #include "gromacs/mdlib/update.h"
64 #include "gromacs/mdtypes/commrec.h"
65 #include "gromacs/mdtypes/edsamhistory.h"
66 #include "gromacs/mdtypes/inputrec.h"
67 #include "gromacs/mdtypes/md_enums.h"
68 #include "gromacs/mdtypes/observableshistory.h"
69 #include "gromacs/mdtypes/state.h"
70 #include "gromacs/pbcutil/pbc.h"
71 #include "gromacs/topology/mtop_lookup.h"
72 #include "gromacs/topology/topology.h"
73 #include "gromacs/utility/cstringutil.h"
74 #include "gromacs/utility/fatalerror.h"
75 #include "gromacs/utility/gmxassert.h"
76 #include "gromacs/utility/smalloc.h"
77 #include "gromacs/utility/strconvert.h"
78
79 namespace
80 {
81 /*! \brief Identifies the type of ED: none, normal ED, flooding. */
82 enum class EssentialDynamicsType
83 {
84     //! No essential dynamics
85     None,
86     //! Essential dynamics sampling
87     EDSampling,
88     //! Essential dynamics flooding
89     Flooding
90 };
91
92 /*! \brief Identify on which structure to operate. */
93 enum class EssentialDynamicsStructure
94 {
95     //! Reference structure
96     Reference,
97     //! Average Structure
98     Average,
99     //! Origin Structure
100     Origin,
101     //! Target Structure
102     Target
103 };
104
105 /*! \brief Essential dynamics vector.
106  * TODO: split into working data and input data
107  * NOTE: called eigvec, because traditionally eigenvectors from PCA analysis
108  * were used as essential dynamics vectors, however, vectors used for ED need
109  * not have any special properties
110  */
111 struct t_eigvec
112 {
113     //! nr of eigenvectors
114     int     neig = 0;
115     //! index nrs of eigenvectors
116     int    *ieig = nullptr;
117     //! stepsizes (per eigenvector)
118     real   *stpsz = nullptr;
119     //! eigenvector components
120     rvec  **vec = nullptr;
121     //! instantaneous x projections
122     real   *xproj = nullptr;
123     //! instantaneous f projections
124     real   *fproj = nullptr;
125     //! instantaneous radius
126     real    radius = 0.;
127     //! starting or target projections
128     real   *refproj = nullptr;
129 };
130
131 /*! \brief Essential dynamics vectors per method implementation.
132  */
133 struct t_edvecs
134 {
135     //! only monitored, no constraints
136     t_eigvec      mon = {};
137     //! fixed linear constraints
138     t_eigvec      linfix = {};
139     //! acceptance linear constraints
140     t_eigvec      linacc = {};
141     //! fixed radial constraints (exp)
142     t_eigvec      radfix = {};
143     //! acceptance radial constraints (exp)
144     t_eigvec      radacc = {};
145     //! acceptance rad. contraction constr.
146     t_eigvec      radcon = {};
147 };
148
149 /*! \brief Essential dynamics flooding parameters and work data.
150  * TODO: split into working data and input parameters
151  * NOTE: The implementation here follows:
152  * O.E. Lange, L.V. Schafer, and H. Grubmuller,
153  * “Flooding in GROMACS: Accelerated barrier crossings in molecular dynamics,”
154  *  J. Comp. Chem., 27 1693–1702 (2006)
155  */
156 struct t_edflood
157 {
158     /*! \brief Target destabilisation free energy.
159      * Controls the flooding potential strength.
160      * Linked to the expected speed-up of mean first passage time out of flooded minimum */
161     real     deltaF0 = 0;
162     //! Do not calculate a flooding potential, instead flood with a constant force
163     bool     bConstForce = false;
164     //! Relaxation time scale for slowest flooded degree of freedom
165     real     tau = 0;
166     //! Current estimated destabilisation free energy
167     real     deltaF = 0;
168     //! Flooding energy, acting as a proportionality factor for the flooding potential
169     real     Efl = 0;
170     //! Boltzmann constant times temperature, provided by user
171     real     kT = 0;
172     //! The flooding potential
173     real     Vfl = 0;
174     //! Integration time step
175     real     dt = 0;
176     //! Inital flooding strenth
177     real     constEfl = 0;
178     //! Empirical global scaling parameter of the essential dynamics vectors.
179     real     alpha2 = 0;
180     //! The forces from flooding in atom coordinate space (in contrast to projections onto essential dynamics vectors)
181     rvec    *forces_cartesian = nullptr;
182     //! The vectors along which to flood
183     t_eigvec vecs = {};
184     //! Use flooding for harmonic restraint on the eigenvector
185     bool     bHarmonic = false;
186     //! The initial reference projection of the flooding vectors. Only with harmonic restraint.
187     real    *initialReferenceProjection = nullptr;
188     //! The current reference projection is the initialReferenceProjection + step * slope. Only with harmonic restraint.
189     real    *referenceProjectionSlope = nullptr;
190 };
191 } // namespace
192
193
194 /* This type is for the average, reference, target, and origin structure    */
195 struct gmx_edx
196 {
197     int            nr         = 0;       /* number of atoms this structure contains  */
198     int            nr_loc     = 0;       /* number of atoms on local node            */
199     int           *anrs       = nullptr; /* atom index numbers                       */
200     int           *anrs_loc   = nullptr; /* local atom index numbers                 */
201     int            nalloc_loc = 0;       /* allocation size of anrs_loc              */
202     int           *c_ind      = nullptr; /* at which position of the whole anrs
203                                           * array is a local atom?, i.e.
204                                           * c_ind[0...nr_loc-1] gives the atom index
205                                           * with respect to the collective
206                                           * anrs[0...nr-1] array                     */
207     rvec          *x          = nullptr; /* positions for this structure             */
208     rvec          *x_old      = nullptr; /* Last positions which have the correct PBC
209                                             representation of the ED group. In
210                                             combination with keeping track of the
211                                             shift vectors, the ED group can always
212                                             be made whole                            */
213     real          *m          = nullptr; /* masses                                   */
214     real           mtot       = 0.;      /* total mass (only used in sref)           */
215     real          *sqrtm      = nullptr; /* sqrt of the masses used for mass-
216                                           * weighting of analysis (only used in sav) */
217 };
218
219
220 typedef struct edpar
221 {
222     int            nini       = 0;     /* total Nr of atoms                    */
223     gmx_bool       fitmas     = false; /* true if trans fit with cm            */
224     gmx_bool       pcamas     = false; /* true if mass-weighted PCA            */
225     int            presteps   = 0;     /* number of steps to run without any
226                                         *    perturbations ... just monitoring */
227     int            outfrq     = 0;     /* freq (in steps) of writing to edo    */
228     int            maxedsteps = 0;     /* max nr of steps per cycle            */
229
230     /* all gmx_edx datasets are copied to all nodes in the parallel case   */
231     gmx_edx             sref = {};        /* reference positions, to these fitting
232                                            * will be done                         */
233     gmx_bool            bRefEqAv = false; /* If true, reference & average indices
234                                            * are the same. Used for optimization  */
235     gmx_edx             sav      = {};    /* average positions                    */
236     gmx_edx             star = {};        /* target positions                     */
237     gmx_edx             sori = {};        /* origin positions                     */
238
239     t_edvecs            vecs = {};        /* eigenvectors                         */
240     real                slope = 0;        /* minimal slope in acceptance radexp   */
241
242     t_edflood           flood = {};       /* parameters especially for flooding   */
243     struct t_ed_buffer *buf = nullptr;    /* handle to local buffers              */
244 } t_edpar;
245
246
247 struct gmx_edsam
248 {
249     ~gmx_edsam();
250     //! The type of ED
251     EssentialDynamicsType eEDtype = EssentialDynamicsType::None;
252     //! output file pointer
253     FILE                 *edo     = nullptr;
254     std::vector<t_edpar>  edpar;
255     gmx_bool              bFirst  = false;
256 };
257 gmx_edsam::~gmx_edsam()
258 {
259     if (edo)
260     {
261         /* edo is opened sometimes with xvgropen, sometimes with
262          * gmx_fio_fopen, so we use the least common denominator for
263          * closing. */
264         gmx_fio_fclose(edo);
265     }
266 }
267
268 struct t_do_edsam
269 {
270     matrix old_rotmat;
271     real   oldrad;
272     rvec   old_transvec, older_transvec, transvec_compact;
273     rvec  *xcoll;                 /* Positions from all nodes, this is the
274                                      collective set we work on.
275                                      These are the positions of atoms with
276                                      average structure indices */
277     rvec    *xc_ref;              /* same but with reference structure indices */
278     ivec    *shifts_xcoll;        /* Shifts for xcoll  */
279     ivec    *extra_shifts_xcoll;  /* xcoll shift changes since last NS step */
280     ivec    *shifts_xc_ref;       /* Shifts for xc_ref */
281     ivec    *extra_shifts_xc_ref; /* xc_ref shift changes since last NS step */
282     gmx_bool bUpdateShifts;       /* TRUE in NS steps to indicate that the
283                                      ED shifts for this ED group need to
284                                      be updated */
285 };
286
287
288 /* definition of ED buffer structure */
289 struct t_ed_buffer
290 {
291     struct t_fit_to_ref *           fit_to_ref;
292     struct t_do_edfit *             do_edfit;
293     struct t_do_edsam *             do_edsam;
294     struct t_do_radcon *            do_radcon;
295 };
296
297 namespace gmx
298 {
299 class EssentialDynamics::Impl
300 {
301     public:
302         // TODO: move all fields from gmx_edsam here and remove gmx_edsam
303         gmx_edsam essentialDynamics_;
304 };
305 EssentialDynamics::EssentialDynamics() : impl_(new Impl)
306 {
307 }
308 EssentialDynamics::~EssentialDynamics() = default;
309
310 gmx_edsam *EssentialDynamics::getLegacyED()
311 {
312     return &impl_->essentialDynamics_;
313 }
314 } // namespace gmx
315
316 /* Function declarations */
317 static void fit_to_reference(rvec *xcoll, rvec transvec, matrix rotmat, t_edpar *edi);
318 static void translate_and_rotate(rvec *x, int nat, rvec transvec, matrix rotmat);
319 static real rmsd_from_structure(rvec *x, struct gmx_edx *s);
320 namespace
321 {
322 /*! \brief Read in the essential dynamics input file and return its contents.
323  * \param[in] fn the file name of the edi file to be read
324  * \param[in] nr_mdatoms the number of atoms in the simulation
325  * \returns A vector of containing the essentiail dyanmics parameters.
326  * NOTE: edi files may that it may contain several ED data sets from concatenated edi files.
327  * The standard case would be a single ED data set, though. */
328 std::vector<t_edpar> read_edi_file(const char *fn, int nr_mdatoms);
329 }
330 static void crosscheck_edi_file_vs_checkpoint(const gmx_edsam &ed, edsamhistory_t *EDstate);
331 static void init_edsamstate(const gmx_edsam &ed, edsamhistory_t *EDstate);
332 static void write_edo_legend(gmx_edsam * ed, int nED, const gmx_output_env_t *oenv);
333 /* End function declarations */
334
335 /* Define formats for the column width in the output file */
336 const char EDcol_sfmt[]         = "%17s";
337 const char EDcol_efmt[]         = "%17.5e";
338 const char EDcol_ffmt[]         = "%17f";
339
340 /* Define a formats for reading, otherwise cppcheck complains for scanf without width limits */
341 const char max_ev_fmt_d[]       = "%7d";             /* Number of eigenvectors. 9,999,999 should be enough */
342 const char max_ev_fmt_lf[]      = "%12lf";
343 const char max_ev_fmt_dlf[]     = "%7d%12lf";
344 const char max_ev_fmt_dlflflf[] = "%7d%12lf%12lf%12lf";
345 const char max_ev_fmt_lelele[]  = "%12le%12le%12le";
346
347 namespace
348 {
349 /*!\brief Determines whether to perform essential dynamics constraints other than flooding.
350  * \param[in] edi the essential dynamics parameters
351  * \returns true if essential dyanmics constraints need to be performed
352  */
353 bool bNeedDoEdsam(const t_edpar &edi)
354 {
355     return (edi.vecs.mon.neig != 0)
356            || (edi.vecs.linfix.neig != 0)
357            || (edi.vecs.linacc.neig != 0)
358            || (edi.vecs.radfix.neig != 0)
359            || (edi.vecs.radacc.neig != 0)
360            || (edi.vecs.radcon.neig != 0);
361 }
362 }  // namespace
363
364
365 /* Multiple ED groups will be labeled with letters instead of numbers
366  * to avoid confusion with eigenvector indices */
367 static char get_EDgroupChar(int nr_edi, int nED)
368 {
369     if (nED == 1)
370     {
371         return ' ';
372     }
373
374     /* nr_edi = 1 -> A
375      * nr_edi = 2 -> B ...
376      */
377     return 'A' + nr_edi - 1;
378 }
379
380 namespace
381 {
382 /*! \brief The mass-weighted inner product of two coordinate vectors.
383  * Does not subtract average positions, projection on single eigenvector is returned
384  * used by: do_linfix, do_linacc, do_radfix, do_radacc, do_radcon
385  * Average position is subtracted in ed_apply_constraints prior to calling projectx
386  * \param[in] edi Essential dynamics parameters
387  * \param[in] xcoll vector of atom coordinates
388  * \param[in] vec vector of coordinates to project onto
389  * \return mass-weighted projection.
390  */
391 real projectx(const t_edpar &edi, rvec *xcoll, rvec *vec)
392 {
393     int  i;
394     real proj = 0.0;
395
396
397     for (i = 0; i < edi.sav.nr; i++)
398     {
399         proj += edi.sav.sqrtm[i]*iprod(vec[i], xcoll[i]);
400     }
401
402     return proj;
403 }
404 /*!\brief Project coordinates onto vector after substracting average position.
405  * projection is stored in vec->refproj which is used for radacc, radfix,
406  * radcon and center of flooding potential.
407  * Average positions are first substracted from x, then added back again.
408  * \param[in] edi essential dynamics parameters with average position
409  * \param[in] x Coordinates to be projected
410  * \param[out] vec eigenvector, radius and refproj are overwritten here
411  */
412 void rad_project(const t_edpar &edi, rvec *x, t_eigvec *vec)
413 {
414     int  i;
415     real rad = 0.0;
416
417     /* Subtract average positions */
418     for (i = 0; i < edi.sav.nr; i++)
419     {
420         rvec_dec(x[i], edi.sav.x[i]);
421     }
422
423     for (i = 0; i < vec->neig; i++)
424     {
425         vec->refproj[i] = projectx(edi, x, vec->vec[i]);
426         rad            += gmx::square((vec->refproj[i]-vec->xproj[i]));
427     }
428     vec->radius = sqrt(rad);
429
430     /* Add average positions */
431     for (i = 0; i < edi.sav.nr; i++)
432     {
433         rvec_inc(x[i], edi.sav.x[i]);
434     }
435 }
436
437 /*!\brief Projects coordinates onto eigenvectors and stores result in vec->xproj.
438  * Mass-weighting is applied. Subtracts average positions prior to projection and add
439  * them afterwards to retain the unchanged vector.
440  * \param[in] x The coordinates to project to an eigenvector
441  * \param[in,out] vec The eigenvectors
442  * \param[in] edi essential dynamics parameters holding average structure and masses
443  */
444 void project_to_eigvectors(rvec *x, t_eigvec *vec, const t_edpar &edi)
445 {
446     if (!vec->neig)
447     {
448         return;
449     }
450
451     /* Subtract average positions */
452     for (int i = 0; i < edi.sav.nr; i++)
453     {
454         rvec_dec(x[i], edi.sav.x[i]);
455     }
456
457     for (int i = 0; i < vec->neig; i++)
458     {
459         vec->xproj[i] = projectx(edi, x, vec->vec[i]);
460     }
461
462     /* Add average positions */
463     for (int i = 0; i < edi.sav.nr; i++)
464     {
465         rvec_inc(x[i], edi.sav.x[i]);
466     }
467 }
468 } // namespace
469
470 /* Project vector x onto all edi->vecs (mon, linfix,...) */
471 static void project(rvec      *x,     /* positions to project */
472                     t_edpar   *edi)   /* edi data set */
473 {
474     /* It is not more work to subtract the average position in every
475      * subroutine again, because these routines are rarely used simultaneously */
476     project_to_eigvectors(x, &edi->vecs.mon, *edi);
477     project_to_eigvectors(x, &edi->vecs.linfix, *edi);
478     project_to_eigvectors(x, &edi->vecs.linacc, *edi);
479     project_to_eigvectors(x, &edi->vecs.radfix, *edi);
480     project_to_eigvectors(x, &edi->vecs.radacc, *edi);
481     project_to_eigvectors(x, &edi->vecs.radcon, *edi);
482 }
483
484 namespace
485 {
486 /*!\brief Evaluates the distance from reference to current eigenvector projection.
487  * \param[in] vec eigenvector
488  * \returns distance
489  */
490 real calc_radius(const t_eigvec &vec)
491 {
492     real rad = 0.0;
493
494     for (int i = 0; i < vec.neig; i++)
495     {
496         rad += gmx::square((vec.refproj[i]-vec.xproj[i]));
497     }
498
499     return rad = sqrt(rad);
500 }
501 }  // namespace
502
503 struct t_do_edfit {
504     double **omega;
505     double **om;
506 };
507
508 static void do_edfit(int natoms, rvec *xp, rvec *x, matrix R, t_edpar *edi)
509 {
510     /* this is a copy of do_fit with some modifications */
511     int                c, r, n, j, i, irot;
512     double             d[6], xnr, xpc;
513     matrix             vh, vk, u;
514     int                index;
515     real               max_d;
516
517     struct t_do_edfit *loc;
518     gmx_bool           bFirst;
519
520     if (edi->buf->do_edfit != nullptr)
521     {
522         bFirst = FALSE;
523     }
524     else
525     {
526         bFirst = TRUE;
527         snew(edi->buf->do_edfit, 1);
528     }
529     loc = edi->buf->do_edfit;
530
531     if (bFirst)
532     {
533         snew(loc->omega, 2*DIM);
534         snew(loc->om, 2*DIM);
535         for (i = 0; i < 2*DIM; i++)
536         {
537             snew(loc->omega[i], 2*DIM);
538             snew(loc->om[i], 2*DIM);
539         }
540     }
541
542     for (i = 0; (i < 6); i++)
543     {
544         d[i] = 0;
545         for (j = 0; (j < 6); j++)
546         {
547             loc->omega[i][j] = 0;
548             loc->om[i][j]    = 0;
549         }
550     }
551
552     /* calculate the matrix U */
553     clear_mat(u);
554     for (n = 0; (n < natoms); n++)
555     {
556         for (c = 0; (c < DIM); c++)
557         {
558             xpc = xp[n][c];
559             for (r = 0; (r < DIM); r++)
560             {
561                 xnr      = x[n][r];
562                 u[c][r] += xnr*xpc;
563             }
564         }
565     }
566
567     /* construct loc->omega */
568     /* loc->omega is symmetric -> loc->omega==loc->omega' */
569     for (r = 0; (r < 6); r++)
570     {
571         for (c = 0; (c <= r); c++)
572         {
573             if ((r >= 3) && (c < 3))
574             {
575                 loc->omega[r][c] = u[r-3][c];
576                 loc->omega[c][r] = u[r-3][c];
577             }
578             else
579             {
580                 loc->omega[r][c] = 0;
581                 loc->omega[c][r] = 0;
582             }
583         }
584     }
585
586     /* determine h and k */
587     jacobi(loc->omega, 6, d, loc->om, &irot);
588
589     if (irot == 0)
590     {
591         fprintf(stderr, "IROT=0\n");
592     }
593
594     index = 0; /* For the compiler only */
595
596     for (j = 0; (j < 3); j++)
597     {
598         max_d = -1000;
599         for (i = 0; (i < 6); i++)
600         {
601             if (d[i] > max_d)
602             {
603                 max_d = d[i];
604                 index = i;
605             }
606         }
607         d[index] = -10000;
608         for (i = 0; (i < 3); i++)
609         {
610             vh[j][i] = M_SQRT2*loc->om[i][index];
611             vk[j][i] = M_SQRT2*loc->om[i+DIM][index];
612         }
613     }
614
615     /* determine R */
616     for (c = 0; (c < 3); c++)
617     {
618         for (r = 0; (r < 3); r++)
619         {
620             R[c][r] = vk[0][r]*vh[0][c]+
621                 vk[1][r]*vh[1][c]+
622                 vk[2][r]*vh[2][c];
623         }
624     }
625     if (det(R) < 0)
626     {
627         for (c = 0; (c < 3); c++)
628         {
629             for (r = 0; (r < 3); r++)
630             {
631                 R[c][r] = vk[0][r]*vh[0][c]+
632                     vk[1][r]*vh[1][c]-
633                     vk[2][r]*vh[2][c];
634             }
635         }
636     }
637 }
638
639
640 static void rmfit(int nat, rvec *xcoll, const rvec transvec, matrix rotmat)
641 {
642     rvec   vec;
643     matrix tmat;
644
645
646     /* Remove rotation.
647      * The inverse rotation is described by the transposed rotation matrix */
648     transpose(rotmat, tmat);
649     rotate_x(xcoll, nat, tmat);
650
651     /* Remove translation */
652     vec[XX] = -transvec[XX];
653     vec[YY] = -transvec[YY];
654     vec[ZZ] = -transvec[ZZ];
655     translate_x(xcoll, nat, vec);
656 }
657
658
659 /**********************************************************************************
660  ******************** FLOODING ****************************************************
661  **********************************************************************************
662
663    The flooding ability was added later to edsam. Many of the edsam functionality could be reused for that purpose.
664    The flooding covariance matrix, i.e. the selected eigenvectors and their corresponding eigenvalues are
665    read as 7th Component Group. The eigenvalues are coded into the stepsize parameter (as used by -linfix or -linacc).
666
667    do_md clls right in the beginning the function init_edsam, which reads the edi file, saves all the necessary information in
668    the edi structure and calls init_flood, to initialise some extra fields in the edi->flood structure.
669
670    since the flooding acts on forces do_flood is called from the function force() (force.c), while the other
671    edsam functionality is hooked into md via the update() (update.c) function acting as constraint on positions.
672
673    do_flood makes a copy of the positions,
674    fits them, projects them computes flooding_energy, and flooding forces. The forces are computed in the
675    space of the eigenvectors and are then blown up to the full cartesian space and rotated back to remove the
676    fit. Then do_flood adds these forces to the forcefield-forces
677    (given as parameter) and updates the adaptive flooding parameters Efl and deltaF.
678
679    To center the flooding potential at a different location one can use the -ori option in make_edi. The ori
680    structure is projected to the system of eigenvectors and then this position in the subspace is used as
681    center of the flooding potential.   If the option is not used, the center will be zero in the subspace,
682    i.e. the average structure as given in the make_edi file.
683
684    To use the flooding potential as restraint, make_edi has the option -restrain, which leads to inverted
685    signs of alpha2 and Efl, such that the sign in the exponential of Vfl is not inverted but the sign of
686    Vfl is inverted. Vfl = Efl * exp (- .../Efl/alpha2*x^2...) With tau>0 the negative Efl will grow slowly
687    so that the restraint is switched off slowly. When Efl==0 and inverted flooding is ON is reached no
688    further adaption is applied, Efl will stay constant at zero.
689
690    To use restraints with harmonic potentials switch -restrain and -harmonic. Then the eigenvalues are
691    used as spring constants for the harmonic potential.
692    Note that eq3 in the flooding paper (J. Comp. Chem. 2006, 27, 1693-1702) defines the parameter lambda \
693    as the inverse of the spring constant, whereas the implementation uses lambda as the spring constant.
694
695    To use more than one flooding matrix just concatenate several .edi files (cat flood1.edi flood2.edi > flood_all.edi)
696    the routine read_edi_file reads all of theses flooding files.
697    The structure t_edi is now organized as a list of t_edis and the function do_flood cycles through the list
698    calling the do_single_flood() routine for every single entry. Since every state variables have been kept in one
699    edi there is no interdependence whatsoever. The forces are added together.
700
701    To write energies into the .edr file, call the function
702         get_flood_enx_names(char**, int *nnames) to get the Header (Vfl1 Vfl2... Vfln)
703    and call
704         get_flood_energies(real Vfl[],int nnames);
705
706    TODO:
707    - one could program the whole thing such that Efl, Vfl and deltaF is written to the .edr file. -- i dont know how to do that, yet.
708
709    Maybe one should give a range of atoms for which to remove motion, so that motion is removed with
710    two edsam files from two peptide chains
711  */
712
713 // TODO split this into multiple files
714 namespace
715 {
716 /*!\brief Output flooding simulation settings and results to file.
717  * \param[in] edi Essential dynamics input parameters
718  * \param[in] fp output file
719  * \param[in] rmsd rmsd to reference structure
720  */
721 void write_edo_flood(const t_edpar &edi, FILE *fp, real rmsd)
722 {
723     /* Output how well we fit to the reference structure */
724     fprintf(fp, EDcol_ffmt, rmsd);
725
726     for (int i = 0; i < edi.flood.vecs.neig; i++)
727     {
728         fprintf(fp, EDcol_efmt, edi.flood.vecs.xproj[i]);
729
730         /* Check whether the reference projection changes with time (this can happen
731          * in case flooding is used as harmonic restraint). If so, output the
732          * current reference projection */
733         if (edi.flood.bHarmonic && edi.flood.referenceProjectionSlope[i] != 0.0)
734         {
735             fprintf(fp, EDcol_efmt, edi.flood.vecs.refproj[i]);
736         }
737
738         /* Output Efl if we are doing adaptive flooding */
739         if (0 != edi.flood.tau)
740         {
741             fprintf(fp, EDcol_efmt, edi.flood.Efl);
742         }
743         fprintf(fp, EDcol_efmt, edi.flood.Vfl);
744
745         /* Output deltaF if we are doing adaptive flooding */
746         if (0 != edi.flood.tau)
747         {
748             fprintf(fp, EDcol_efmt, edi.flood.deltaF);
749         }
750         fprintf(fp, EDcol_efmt, edi.flood.vecs.fproj[i]);
751     }
752 }
753 } // namespace
754
755
756 /* From flood.xproj compute the Vfl(x) at this point */
757 static real flood_energy(t_edpar *edi, int64_t step)
758 {
759     /* compute flooding energy Vfl
760        Vfl = Efl * exp( - \frac {kT} {2Efl alpha^2} * sum_i { \lambda_i c_i^2 } )
761        \lambda_i is the reciprocal eigenvalue 1/\sigma_i
762          it is already computed by make_edi and stored in stpsz[i]
763        bHarmonic:
764        Vfl = - Efl * 1/2(sum _i {\frac 1{\lambda_i} c_i^2})
765      */
766     real sum;
767     real Vfl;
768     int  i;
769
770
771     /* Each time this routine is called (i.e. each time step), we add a small
772      * value to the reference projection. This way a harmonic restraint towards
773      * a moving reference is realized. If no value for the additive constant
774      * is provided in the edi file, the reference will not change. */
775     if (edi->flood.bHarmonic)
776     {
777         for (i = 0; i < edi->flood.vecs.neig; i++)
778         {
779             edi->flood.vecs.refproj[i] = edi->flood.initialReferenceProjection[i] + step * edi->flood.referenceProjectionSlope[i];
780         }
781     }
782
783     sum = 0.0;
784     /* Compute sum which will be the exponent of the exponential */
785     for (i = 0; i < edi->flood.vecs.neig; i++)
786     {
787         /* stpsz stores the reciprocal eigenvalue 1/sigma_i */
788         sum += edi->flood.vecs.stpsz[i]*(edi->flood.vecs.xproj[i]-edi->flood.vecs.refproj[i])*(edi->flood.vecs.xproj[i]-edi->flood.vecs.refproj[i]);
789     }
790
791     /* Compute the Gauss function*/
792     if (edi->flood.bHarmonic)
793     {
794         Vfl = -0.5*edi->flood.Efl*sum;  /* minus sign because Efl is negative, if restrain is on. */
795     }
796     else
797     {
798         Vfl = edi->flood.Efl != 0 ? edi->flood.Efl*std::exp(-edi->flood.kT/2/edi->flood.Efl/edi->flood.alpha2*sum) : 0;
799     }
800
801     return Vfl;
802 }
803
804
805 /* From the position and from Vfl compute forces in subspace -> store in edi->vec.flood.fproj */
806 static void flood_forces(t_edpar *edi)
807 {
808     /* compute the forces in the subspace of the flooding eigenvectors
809      * by the formula F_i= V_{fl}(c) * ( \frac {kT} {E_{fl}} \lambda_i c_i */
810
811     int  i;
812     real energy = edi->flood.Vfl;
813
814
815     if (edi->flood.bHarmonic)
816     {
817         for (i = 0; i < edi->flood.vecs.neig; i++)
818         {
819             edi->flood.vecs.fproj[i] = edi->flood.Efl* edi->flood.vecs.stpsz[i]*(edi->flood.vecs.xproj[i]-edi->flood.vecs.refproj[i]);
820         }
821     }
822     else
823     {
824         for (i = 0; i < edi->flood.vecs.neig; i++)
825         {
826             /* if Efl is zero the forces are zero if not use the formula */
827             edi->flood.vecs.fproj[i] = edi->flood.Efl != 0 ? edi->flood.kT/edi->flood.Efl/edi->flood.alpha2*energy*edi->flood.vecs.stpsz[i]*(edi->flood.vecs.xproj[i]-edi->flood.vecs.refproj[i]) : 0;
828         }
829     }
830 }
831
832 namespace
833 {
834 /*!\brief Raise forces from subspace into cartesian space.
835  * This function lifts the forces from the subspace to the cartesian space
836  * all the values not contained in the subspace are assumed to be zero and then
837  * a coordinate transformation from eigenvector to cartesian vectors is performed
838  * The nonexistent values don't have to be set to zero explicitly, they would occur
839  * as zero valued summands, hence we just stop to compute this part of the sum.
840  * For every atom we add all the contributions to this atom from all the different eigenvectors.
841  * NOTE: one could add directly to the forcefield forces, would mean we wouldn't have to clear the
842  * field forces_cart prior the computation, but we compute the forces separately
843  * to have them accessible for diagnostics
844  *
845  * \param[in] edi Essential dynamics input parameters
846  * \param[out] forces_cart The cartesian forces
847  */
848
849 void flood_blowup(const t_edpar &edi, rvec *forces_cart)
850 {
851     const real * forces_sub = edi.flood.vecs.fproj;
852     /* Calculate the cartesian forces for the local atoms */
853
854     /* Clear forces first */
855     for (int j = 0; j < edi.sav.nr_loc; j++)
856     {
857         clear_rvec(forces_cart[j]);
858     }
859
860     /* Now compute atomwise */
861     for (int j = 0; j < edi.sav.nr_loc; j++)
862     {
863         /* Compute forces_cart[edi.sav.anrs[j]] */
864         for (int eig = 0; eig < edi.flood.vecs.neig; eig++)
865         {
866             rvec addedForce;
867             /* Force vector is force * eigenvector (compute only atom j) */
868             svmul(forces_sub[eig], edi.flood.vecs.vec[eig][edi.sav.c_ind[j]], addedForce);
869             /* Add this vector to the cartesian forces */
870             rvec_inc(forces_cart[j], addedForce);
871         }
872     }
873 }
874
875 } // namespace
876
877
878 /* Update the values of Efl, deltaF depending on tau and Vfl */
879 static void update_adaption(t_edpar *edi)
880 {
881     /* this function updates the parameter Efl and deltaF according to the rules given in
882      * 'predicting unimolecular chemical reactions: chemical flooding' M Mueller et al,
883      * J. chem Phys. */
884
885     if ((edi->flood.tau < 0 ? -edi->flood.tau : edi->flood.tau ) > 0.00000001)
886     {
887         edi->flood.Efl = edi->flood.Efl+edi->flood.dt/edi->flood.tau*(edi->flood.deltaF0-edi->flood.deltaF);
888         /* check if restrain (inverted flooding) -> don't let EFL become positive */
889         if (edi->flood.alpha2 < 0 && edi->flood.Efl > -0.00000001)
890         {
891             edi->flood.Efl = 0;
892         }
893
894         edi->flood.deltaF = (1-edi->flood.dt/edi->flood.tau)*edi->flood.deltaF+edi->flood.dt/edi->flood.tau*edi->flood.Vfl;
895     }
896 }
897
898
899 static void do_single_flood(
900         FILE            *edo,
901         const rvec       x[],
902         rvec             force[],
903         t_edpar         *edi,
904         int64_t          step,
905         matrix           box,
906         const t_commrec *cr,
907         gmx_bool         bNS) /* Are we in a neighbor searching step? */
908 {
909     int                i;
910     matrix             rotmat;   /* rotation matrix */
911     matrix             tmat;     /* inverse rotation */
912     rvec               transvec; /* translation vector */
913     real               rmsdev;
914     struct t_do_edsam *buf;
915
916
917     buf = edi->buf->do_edsam;
918
919
920     /* Broadcast the positions of the AVERAGE structure such that they are known on
921      * every processor. Each node contributes its local positions x and stores them in
922      * the collective ED array buf->xcoll */
923     communicate_group_positions(cr, buf->xcoll, buf->shifts_xcoll, buf->extra_shifts_xcoll, bNS, x,
924                                 edi->sav.nr, edi->sav.nr_loc, edi->sav.anrs_loc, edi->sav.c_ind, edi->sav.x_old, box);
925
926     /* Only assembly REFERENCE positions if their indices differ from the average ones */
927     if (!edi->bRefEqAv)
928     {
929         communicate_group_positions(cr, buf->xc_ref, buf->shifts_xc_ref, buf->extra_shifts_xc_ref, bNS, x,
930                                     edi->sref.nr, edi->sref.nr_loc, edi->sref.anrs_loc, edi->sref.c_ind, edi->sref.x_old, box);
931     }
932
933     /* If bUpdateShifts was TRUE, the shifts have just been updated in get_positions.
934      * We do not need to update the shifts until the next NS step */
935     buf->bUpdateShifts = FALSE;
936
937     /* Now all nodes have all of the ED/flooding positions in edi->sav->xcoll,
938      * as well as the indices in edi->sav.anrs */
939
940     /* Fit the reference indices to the reference structure */
941     if (edi->bRefEqAv)
942     {
943         fit_to_reference(buf->xcoll, transvec, rotmat, edi);
944     }
945     else
946     {
947         fit_to_reference(buf->xc_ref, transvec, rotmat, edi);
948     }
949
950     /* Now apply the translation and rotation to the ED structure */
951     translate_and_rotate(buf->xcoll, edi->sav.nr, transvec, rotmat);
952
953     /* Project fitted structure onto supbspace -> store in edi->flood.vecs.xproj */
954     project_to_eigvectors(buf->xcoll, &edi->flood.vecs, *edi);
955
956     if (!edi->flood.bConstForce)
957     {
958         /* Compute Vfl(x) from flood.xproj */
959         edi->flood.Vfl = flood_energy(edi, step);
960
961         update_adaption(edi);
962
963         /* Compute the flooding forces */
964         flood_forces(edi);
965     }
966
967     /* Translate them into cartesian positions */
968     flood_blowup(*edi, edi->flood.forces_cartesian);
969
970     /* Rotate forces back so that they correspond to the given structure and not to the fitted one */
971     /* Each node rotates back its local forces */
972     transpose(rotmat, tmat);
973     rotate_x(edi->flood.forces_cartesian, edi->sav.nr_loc, tmat);
974
975     /* Finally add forces to the main force variable */
976     for (i = 0; i < edi->sav.nr_loc; i++)
977     {
978         rvec_inc(force[edi->sav.anrs_loc[i]], edi->flood.forces_cartesian[i]);
979     }
980
981     /* Output is written by the master process */
982     if (do_per_step(step, edi->outfrq) && MASTER(cr))
983     {
984         /* Output how well we fit to the reference */
985         if (edi->bRefEqAv)
986         {
987             /* Indices of reference and average structures are identical,
988              * thus we can calculate the rmsd to SREF using xcoll */
989             rmsdev = rmsd_from_structure(buf->xcoll, &edi->sref);
990         }
991         else
992         {
993             /* We have to translate & rotate the reference atoms first */
994             translate_and_rotate(buf->xc_ref, edi->sref.nr, transvec, rotmat);
995             rmsdev = rmsd_from_structure(buf->xc_ref, &edi->sref);
996         }
997
998         write_edo_flood(*edi, edo, rmsdev);
999     }
1000 }
1001
1002
1003 /* Main flooding routine, called from do_force */
1004 extern void do_flood(const t_commrec  *cr,
1005                      const t_inputrec *ir,
1006                      const rvec        x[],
1007                      rvec              force[],
1008                      gmx_edsam        *ed,
1009                      matrix            box,
1010                      int64_t           step,
1011                      gmx_bool          bNS)
1012 {
1013     /* Write time to edo, when required. Output the time anyhow since we need
1014      * it in the output file for ED constraints. */
1015     if (MASTER(cr) && do_per_step(step, ed->edpar.begin()->outfrq))
1016     {
1017         fprintf(ed->edo, "\n%12f", ir->init_t + step*ir->delta_t);
1018     }
1019
1020     if (ed->eEDtype != EssentialDynamicsType::Flooding)
1021     {
1022         return;
1023     }
1024
1025     for (auto &edi : ed->edpar)
1026     {
1027         /* Call flooding for one matrix */
1028         if (edi.flood.vecs.neig)
1029         {
1030             do_single_flood(ed->edo, x, force, &edi, step, box, cr, bNS);
1031         }
1032     }
1033 }
1034
1035
1036 /* Called by init_edi, configure some flooding related variables and structures,
1037  * print headers to output files */
1038 static void init_flood(t_edpar *edi, gmx_edsam * ed, real dt)
1039 {
1040     int i;
1041
1042
1043     edi->flood.Efl = edi->flood.constEfl;
1044     edi->flood.Vfl = 0;
1045     edi->flood.dt  = dt;
1046
1047     if (edi->flood.vecs.neig)
1048     {
1049         /* If in any of the ED groups we find a flooding vector, flooding is turned on */
1050         ed->eEDtype = EssentialDynamicsType::Flooding;
1051
1052         fprintf(stderr, "ED: Flooding %d eigenvector%s.\n", edi->flood.vecs.neig, edi->flood.vecs.neig > 1 ? "s" : "");
1053
1054         if (edi->flood.bConstForce)
1055         {
1056             /* We have used stpsz as a vehicle to carry the fproj values for constant
1057              * force flooding. Now we copy that to flood.vecs.fproj. Note that
1058              * in const force flooding, fproj is never changed. */
1059             for (i = 0; i < edi->flood.vecs.neig; i++)
1060             {
1061                 edi->flood.vecs.fproj[i] = edi->flood.vecs.stpsz[i];
1062
1063                 fprintf(stderr, "ED: applying on eigenvector %d a constant force of %g\n",
1064                         edi->flood.vecs.ieig[i], edi->flood.vecs.fproj[i]);
1065             }
1066         }
1067     }
1068 }
1069
1070
1071 #ifdef DEBUGHELPERS
1072 /*********** Energy book keeping ******/
1073 static void get_flood_enx_names(t_edpar *edi, char** names, int *nnames)  /* get header of energies */
1074 {
1075     t_edpar *actual;
1076     int      count;
1077     char     buf[STRLEN];
1078     actual = edi;
1079     count  = 1;
1080     while (actual)
1081     {
1082         srenew(names, count);
1083         sprintf(buf, "Vfl_%d", count);
1084         names[count-1] = gmx_strdup(buf);
1085         actual         = actual->next_edi;
1086         count++;
1087     }
1088     *nnames = count-1;
1089 }
1090
1091
1092 static void get_flood_energies(t_edpar *edi, real Vfl[], int nnames)
1093 {
1094     /*fl has to be big enough to capture nnames-many entries*/
1095     t_edpar *actual;
1096     int      count;
1097
1098
1099     actual = edi;
1100     count  = 1;
1101     while (actual)
1102     {
1103         Vfl[count-1] = actual->flood.Vfl;
1104         actual       = actual->next_edi;
1105         count++;
1106     }
1107     if (nnames != count-1)
1108     {
1109         gmx_fatal(FARGS, "Number of energies is not consistent with t_edi structure");
1110     }
1111 }
1112 /************* END of FLOODING IMPLEMENTATION ****************************/
1113 #endif
1114
1115
1116 /* This function opens the ED input and output files, reads in all datasets it finds
1117  * in the input file, and cross-checks whether the .edi file information is consistent
1118  * with the essential dynamics data found in the checkpoint file (if present).
1119  * gmx make_edi can be used to create an .edi input file.
1120  */
1121 static std::unique_ptr<gmx::EssentialDynamics> ed_open(
1122         int                     natoms,
1123         ObservablesHistory     *oh,
1124         const char             *ediFileName,
1125         const char             *edoFileName,
1126         gmx_bool                bAppend,
1127         const gmx_output_env_t *oenv,
1128         const t_commrec        *cr)
1129 {
1130     auto        edHandle = gmx::compat::make_unique<gmx::EssentialDynamics>();
1131     auto        ed       = edHandle->getLegacyED();
1132     /* We want to perform ED (this switch might later be upgraded to EssentialDynamicsType::Flooding) */
1133     ed->eEDtype = EssentialDynamicsType::EDSampling;
1134
1135     if (MASTER(cr))
1136     {
1137         // If we start from a checkpoint file, we already have an edsamHistory struct
1138         if (oh->edsamHistory == nullptr)
1139         {
1140             oh->edsamHistory = gmx::compat::make_unique<edsamhistory_t>(edsamhistory_t {});
1141         }
1142         edsamhistory_t *EDstate = oh->edsamHistory.get();
1143
1144         /* Read the edi input file: */
1145         ed->edpar = read_edi_file(ediFileName, natoms);
1146
1147         /* Make sure the checkpoint was produced in a run using this .edi file */
1148         if (EDstate->bFromCpt)
1149         {
1150             crosscheck_edi_file_vs_checkpoint(*ed, EDstate);
1151         }
1152         else
1153         {
1154             EDstate->nED = ed->edpar.size();
1155         }
1156         init_edsamstate(*ed, EDstate);
1157
1158         /* The master opens the ED output file */
1159         if (bAppend)
1160         {
1161             ed->edo = gmx_fio_fopen(edoFileName, "a+");
1162         }
1163         else
1164         {
1165             ed->edo = xvgropen(edoFileName,
1166                                "Essential dynamics / flooding output",
1167                                "Time (ps)",
1168                                "RMSDs (nm), projections on EVs (nm), ...", oenv);
1169
1170             /* Make a descriptive legend */
1171             write_edo_legend(ed, EDstate->nED, oenv);
1172         }
1173     }
1174     return edHandle;
1175 }
1176
1177
1178 /* Broadcasts the structure data */
1179 static void bc_ed_positions(const t_commrec *cr, struct gmx_edx *s, EssentialDynamicsStructure stype)
1180 {
1181     snew_bc(cr, s->anrs, s->nr   );    /* Index numbers     */
1182     snew_bc(cr, s->x, s->nr   );       /* Positions         */
1183     nblock_bc(cr, s->nr, s->anrs );
1184     nblock_bc(cr, s->nr, s->x    );
1185
1186     /* For the average & reference structures we need an array for the collective indices,
1187      * and we need to broadcast the masses as well */
1188     if (stype == EssentialDynamicsStructure::Average || stype == EssentialDynamicsStructure::Reference)
1189     {
1190         /* We need these additional variables in the parallel case: */
1191         snew(s->c_ind, s->nr   );       /* Collective indices */
1192         /* Local atom indices get assigned in dd_make_local_group_indices.
1193          * There, also memory is allocated */
1194         s->nalloc_loc = 0;              /* allocation size of s->anrs_loc */
1195         snew_bc(cr, s->x_old, s->nr);   /* To be able to always make the ED molecule whole, ...        */
1196         nblock_bc(cr, s->nr, s->x_old); /* ... keep track of shift changes with the help of old coords */
1197     }
1198
1199     /* broadcast masses for the reference structure (for mass-weighted fitting) */
1200     if (stype == EssentialDynamicsStructure::Reference)
1201     {
1202         snew_bc(cr, s->m, s->nr);
1203         nblock_bc(cr, s->nr, s->m);
1204     }
1205
1206     /* For the average structure we might need the masses for mass-weighting */
1207     if (stype == EssentialDynamicsStructure::Average)
1208     {
1209         snew_bc(cr, s->sqrtm, s->nr);
1210         nblock_bc(cr, s->nr, s->sqrtm);
1211         snew_bc(cr, s->m, s->nr);
1212         nblock_bc(cr, s->nr, s->m);
1213     }
1214 }
1215
1216
1217 /* Broadcasts the eigenvector data */
1218 static void bc_ed_vecs(const t_commrec *cr, t_eigvec *ev, int length)
1219 {
1220     int i;
1221
1222     snew_bc(cr, ev->ieig, ev->neig);     /* index numbers of eigenvector  */
1223     snew_bc(cr, ev->stpsz, ev->neig);    /* stepsizes per eigenvector     */
1224     snew_bc(cr, ev->xproj, ev->neig);    /* instantaneous x projection    */
1225     snew_bc(cr, ev->fproj, ev->neig);    /* instantaneous f projection    */
1226     snew_bc(cr, ev->refproj, ev->neig);  /* starting or target projection */
1227
1228     nblock_bc(cr, ev->neig, ev->ieig   );
1229     nblock_bc(cr, ev->neig, ev->stpsz  );
1230     nblock_bc(cr, ev->neig, ev->xproj  );
1231     nblock_bc(cr, ev->neig, ev->fproj  );
1232     nblock_bc(cr, ev->neig, ev->refproj);
1233
1234     snew_bc(cr, ev->vec, ev->neig);      /* Eigenvector components        */
1235     for (i = 0; i < ev->neig; i++)
1236     {
1237         snew_bc(cr, ev->vec[i], length);
1238         nblock_bc(cr, length, ev->vec[i]);
1239     }
1240
1241 }
1242
1243
1244 /* Broadcasts the ED / flooding data to other nodes
1245  * and allocates memory where needed */
1246 static void broadcast_ed_data(const t_commrec *cr, gmx_edsam * ed)
1247 {
1248     /* Master lets the other nodes know if its ED only or also flooding */
1249     gmx_bcast(sizeof(ed->eEDtype), &(ed->eEDtype), cr);
1250
1251     int numedis = ed->edpar.size();
1252     /* First let everybody know how many ED data sets to expect */
1253     gmx_bcast(sizeof(numedis), &numedis, cr);
1254     nblock_abc(cr, numedis, &(ed->edpar));
1255     /* Now transfer the ED data set(s) */
1256     for (auto &edi : ed->edpar)
1257     {
1258         /* Broadcast a single ED data set */
1259         block_bc(cr, edi);
1260
1261         /* Broadcast positions */
1262         bc_ed_positions(cr, &(edi.sref), EssentialDynamicsStructure::Reference); /* reference positions (don't broadcast masses)    */
1263         bc_ed_positions(cr, &(edi.sav ), EssentialDynamicsStructure::Average );  /* average positions (do broadcast masses as well) */
1264         bc_ed_positions(cr, &(edi.star), EssentialDynamicsStructure::Target);    /* target positions                                */
1265         bc_ed_positions(cr, &(edi.sori), EssentialDynamicsStructure::Origin);    /* origin positions                                */
1266
1267         /* Broadcast eigenvectors */
1268         bc_ed_vecs(cr, &edi.vecs.mon, edi.sav.nr);
1269         bc_ed_vecs(cr, &edi.vecs.linfix, edi.sav.nr);
1270         bc_ed_vecs(cr, &edi.vecs.linacc, edi.sav.nr);
1271         bc_ed_vecs(cr, &edi.vecs.radfix, edi.sav.nr);
1272         bc_ed_vecs(cr, &edi.vecs.radacc, edi.sav.nr);
1273         bc_ed_vecs(cr, &edi.vecs.radcon, edi.sav.nr);
1274         /* Broadcast flooding eigenvectors and, if needed, values for the moving reference */
1275         bc_ed_vecs(cr, &edi.flood.vecs,  edi.sav.nr);
1276
1277         /* For harmonic restraints the reference projections can change with time */
1278         if (edi.flood.bHarmonic)
1279         {
1280             snew_bc(cr, edi.flood.initialReferenceProjection, edi.flood.vecs.neig);
1281             snew_bc(cr, edi.flood.referenceProjectionSlope, edi.flood.vecs.neig);
1282             nblock_bc(cr, edi.flood.vecs.neig, edi.flood.initialReferenceProjection);
1283             nblock_bc(cr, edi.flood.vecs.neig, edi.flood.referenceProjectionSlope);
1284         }
1285     }
1286 }
1287
1288
1289 /* init-routine called for every *.edi-cycle, initialises t_edpar structure */
1290 static void init_edi(const gmx_mtop_t *mtop, t_edpar *edi)
1291 {
1292     int                   i;
1293     real                  totalmass = 0.0;
1294     rvec                  com;
1295
1296     /* NOTE Init_edi is executed on the master process only
1297      * The initialized data sets are then transmitted to the
1298      * other nodes in broadcast_ed_data */
1299
1300     /* evaluate masses (reference structure) */
1301     snew(edi->sref.m, edi->sref.nr);
1302     int molb = 0;
1303     for (i = 0; i < edi->sref.nr; i++)
1304     {
1305         if (edi->fitmas)
1306         {
1307             edi->sref.m[i] = mtopGetAtomMass(mtop, edi->sref.anrs[i], &molb);
1308         }
1309         else
1310         {
1311             edi->sref.m[i] = 1.0;
1312         }
1313
1314         /* Check that every m > 0. Bad things will happen otherwise. */
1315         if (edi->sref.m[i] <= 0.0)
1316         {
1317             gmx_fatal(FARGS, "Reference structure atom %d (sam.edi index %d) has a mass of %g.\n"
1318                       "For a mass-weighted fit, all reference structure atoms need to have a mass >0.\n"
1319                       "Either make the covariance analysis non-mass-weighted, or exclude massless\n"
1320                       "atoms from the reference structure by creating a proper index group.\n",
1321                       i, edi->sref.anrs[i]+1, edi->sref.m[i]);
1322         }
1323
1324         totalmass += edi->sref.m[i];
1325     }
1326     edi->sref.mtot = totalmass;
1327
1328     /* Masses m and sqrt(m) for the average structure. Note that m
1329      * is needed if forces have to be evaluated in do_edsam */
1330     snew(edi->sav.sqrtm, edi->sav.nr );
1331     snew(edi->sav.m, edi->sav.nr );
1332     for (i = 0; i < edi->sav.nr; i++)
1333     {
1334         edi->sav.m[i] = mtopGetAtomMass(mtop, edi->sav.anrs[i], &molb);
1335         if (edi->pcamas)
1336         {
1337             edi->sav.sqrtm[i] = sqrt(edi->sav.m[i]);
1338         }
1339         else
1340         {
1341             edi->sav.sqrtm[i] = 1.0;
1342         }
1343
1344         /* Check that every m > 0. Bad things will happen otherwise. */
1345         if (edi->sav.sqrtm[i] <= 0.0)
1346         {
1347             gmx_fatal(FARGS, "Average structure atom %d (sam.edi index %d) has a mass of %g.\n"
1348                       "For ED with mass-weighting, all average structure atoms need to have a mass >0.\n"
1349                       "Either make the covariance analysis non-mass-weighted, or exclude massless\n"
1350                       "atoms from the average structure by creating a proper index group.\n",
1351                       i, edi->sav.anrs[i] + 1, edi->sav.m[i]);
1352         }
1353     }
1354
1355     /* put reference structure in origin */
1356     get_center(edi->sref.x, edi->sref.m, edi->sref.nr, com);
1357     com[XX] = -com[XX];
1358     com[YY] = -com[YY];
1359     com[ZZ] = -com[ZZ];
1360     translate_x(edi->sref.x, edi->sref.nr, com);
1361
1362     /* Init ED buffer */
1363     snew(edi->buf, 1);
1364 }
1365
1366
1367 static void check(const char *line, const char *label)
1368 {
1369     if (!strstr(line, label))
1370     {
1371         gmx_fatal(FARGS, "Could not find input parameter %s at expected position in edsam input-file (.edi)\nline read instead is %s", label, line);
1372     }
1373 }
1374
1375
1376 static int read_checked_edint(FILE *file, const char *label)
1377 {
1378     char line[STRLEN+1];
1379     int  idum;
1380
1381     fgets2 (line, STRLEN, file);
1382     check(line, label);
1383     fgets2 (line, STRLEN, file);
1384     sscanf (line, max_ev_fmt_d, &idum);
1385     return idum;
1386 }
1387
1388 static bool read_checked_edbool(FILE *file, const char *label)
1389 {
1390     return read_checked_edint(file, label) != 0;
1391 }
1392
1393 static int read_edint(FILE *file, bool *bEOF)
1394 {
1395     char  line[STRLEN+1];
1396     int   idum;
1397     char *eof;
1398
1399
1400     eof = fgets2 (line, STRLEN, file);
1401     if (eof == nullptr)
1402     {
1403         *bEOF = TRUE;
1404         return -1;
1405     }
1406     eof = fgets2 (line, STRLEN, file);
1407     if (eof == nullptr)
1408     {
1409         *bEOF = TRUE;
1410         return -1;
1411     }
1412     sscanf (line, max_ev_fmt_d, &idum);
1413     *bEOF = FALSE;
1414     return idum;
1415 }
1416
1417
1418 static real read_checked_edreal(FILE *file, const char *label)
1419 {
1420     char   line[STRLEN+1];
1421     double rdum;
1422
1423
1424     fgets2 (line, STRLEN, file);
1425     check(line, label);
1426     fgets2 (line, STRLEN, file);
1427     sscanf (line, max_ev_fmt_lf, &rdum);
1428     return static_cast<real>(rdum); /* always read as double and convert to single */
1429 }
1430
1431
1432 static void read_edx(FILE *file, int number, int *anrs, rvec *x)
1433 {
1434     int    i, j;
1435     char   line[STRLEN+1];
1436     double d[3];
1437
1438
1439     for (i = 0; i < number; i++)
1440     {
1441         fgets2 (line, STRLEN, file);
1442         sscanf (line, max_ev_fmt_dlflflf, &anrs[i], &d[0], &d[1], &d[2]);
1443         anrs[i]--; /* we are reading FORTRAN indices */
1444         for (j = 0; j < 3; j++)
1445         {
1446             x[i][j] = d[j]; /* always read as double and convert to single */
1447         }
1448     }
1449 }
1450
1451 namespace
1452 {
1453 /*!\brief Read eigenvector coordinates for multiple eigenvectors from a file.
1454  * \param[in] in the file to read from
1455  * \param[in] numAtoms the number of atoms/coordinates for the eigenvector
1456  * \param[out] vec the eigen-vectors
1457  * \param[in] nEig the number of eigenvectors
1458  */
1459 void scan_edvec(FILE *in, int numAtoms, rvec ***vec, int nEig)
1460 {
1461     snew(*vec, nEig);
1462     for (int iEigenvector = 0; iEigenvector < nEig; iEigenvector++)
1463     {
1464         snew((*vec)[iEigenvector], numAtoms);
1465         for (int iAtom = 0; iAtom < numAtoms; iAtom++)
1466         {
1467             char   line[STRLEN+1];
1468             double x, y, z;
1469             fgets2(line, STRLEN, in);
1470             sscanf(line, max_ev_fmt_lelele, &x, &y, &z);
1471             (*vec)[iEigenvector][iAtom][XX] = x;
1472             (*vec)[iEigenvector][iAtom][YY] = y;
1473             (*vec)[iEigenvector][iAtom][ZZ] = z;
1474         }
1475     }
1476
1477 }
1478 /*!\brief Read an essential dynamics eigenvector and corresponding step size.
1479  * \param[in] in input file
1480  * \param[in] nrAtoms number of atoms/coordinates
1481  * \param[out] tvec the eigenvector
1482  */
1483 void read_edvec(FILE *in, int nrAtoms, t_eigvec *tvec)
1484 {
1485     tvec->neig = read_checked_edint(in, "NUMBER OF EIGENVECTORS");
1486     if (tvec->neig <= 0)
1487     {
1488         return;
1489     }
1490
1491     snew(tvec->ieig, tvec->neig);
1492     snew(tvec->stpsz, tvec->neig);
1493     for (int i = 0; i < tvec->neig; i++)
1494     {
1495         char      line[STRLEN+1];
1496         fgets2(line, STRLEN, in);
1497         int       numEigenVectors;
1498         double    stepSize;
1499         const int nscan = sscanf(line, max_ev_fmt_dlf, &numEigenVectors, &stepSize);
1500         if (nscan != 2)
1501         {
1502             gmx_fatal(FARGS, "Expected 2 values for flooding vec: <nr> <stpsz>\n");
1503         }
1504         tvec->ieig[i]  = numEigenVectors;
1505         tvec->stpsz[i] = stepSize;
1506     }   /* end of loop over eigenvectors */
1507
1508     scan_edvec(in, nrAtoms, &tvec->vec, tvec->neig);
1509 }
1510 /*!\brief Read an essential dynamics eigenvector and intial reference projections and slopes if available.
1511  *
1512  * Eigenvector and its intial reference and slope are stored on the
1513  * same line in the .edi format. To avoid re-winding the .edi file,
1514  * the reference eigen-vector and reference data are read in one go.
1515  *
1516  * \param[in] in input file
1517  * \param[in] nrAtoms number of atoms/coordinates
1518  * \param[out] tvec the eigenvector
1519  * \param[out] initialReferenceProjection The projection onto eigenvectors as read from file.
1520  * \param[out] referenceProjectionSlope The slope of the reference projections.
1521  */
1522 bool readEdVecWithReferenceProjection(FILE *in, int nrAtoms, t_eigvec *tvec, real ** initialReferenceProjection, real ** referenceProjectionSlope)
1523 {
1524     bool providesReference = false;
1525     tvec->neig = read_checked_edint(in, "NUMBER OF EIGENVECTORS");
1526     if (tvec->neig <= 0)
1527     {
1528         return false;
1529     }
1530
1531     snew(tvec->ieig, tvec->neig);
1532     snew(tvec->stpsz, tvec->neig);
1533     snew(*initialReferenceProjection, tvec->neig);
1534     snew(*referenceProjectionSlope, tvec->neig);
1535     for (int i = 0; i < tvec->neig; i++)
1536     {
1537         char      line[STRLEN+1];
1538         fgets2 (line, STRLEN, in);
1539         int       numEigenVectors;
1540         double    stepSize            = 0.;
1541         double    referenceProjection = 0.;
1542         double    referenceSlope      = 0.;
1543         const int nscan               = sscanf(line, max_ev_fmt_dlflflf, &numEigenVectors, &stepSize, &referenceProjection, &referenceSlope);
1544         /* Zero out values which were not scanned */
1545         switch (nscan)
1546         {
1547             case 4:
1548                 /* Every 4 values read, including reference position */
1549                 providesReference = true;
1550                 break;
1551             case 3:
1552                 /* A reference position is provided */
1553                 providesReference = true;
1554                 /* No value for slope, set to 0 */
1555                 referenceSlope = 0.0;
1556                 break;
1557             case 2:
1558                 /* No values for reference projection and slope, set to 0 */
1559                 referenceProjection = 0.0;
1560                 referenceSlope      = 0.0;
1561                 break;
1562             default:
1563                 gmx_fatal(FARGS, "Expected 2 - 4 (not %d) values for flooding vec: <nr> <spring const> <refproj> <refproj-slope>\n", nscan);
1564         }
1565         (*initialReferenceProjection)[i]            = referenceProjection;
1566         (*referenceProjectionSlope)[i]              = referenceSlope;
1567
1568         tvec->ieig[i]  = numEigenVectors;
1569         tvec->stpsz[i] = stepSize;
1570     }   /* end of loop over eigenvectors */
1571
1572     scan_edvec(in, nrAtoms, &tvec->vec, tvec->neig);
1573     return providesReference;
1574 }
1575
1576 /*!\brief Allocate working memory for the eigenvectors.
1577  * \param[in,out] tvec eigenvector for which memory will be allocated
1578  */
1579 void setup_edvec(t_eigvec *tvec)
1580 {
1581     snew(tvec->xproj, tvec->neig);
1582     snew(tvec->fproj, tvec->neig);
1583     snew(tvec->refproj, tvec->neig);
1584 }
1585 }  // namespace
1586
1587
1588 /* Check if the same atom indices are used for reference and average positions */
1589 static gmx_bool check_if_same(struct gmx_edx sref, struct gmx_edx sav)
1590 {
1591     int i;
1592
1593
1594     /* If the number of atoms differs between the two structures,
1595      * they cannot be identical */
1596     if (sref.nr != sav.nr)
1597     {
1598         return FALSE;
1599     }
1600
1601     /* Now that we know that both stuctures have the same number of atoms,
1602      * check if also the indices are identical */
1603     for (i = 0; i < sav.nr; i++)
1604     {
1605         if (sref.anrs[i] != sav.anrs[i])
1606         {
1607             return FALSE;
1608         }
1609     }
1610     fprintf(stderr, "ED: Note: Reference and average structure are composed of the same atom indices.\n");
1611
1612     return TRUE;
1613 }
1614
1615 namespace
1616 {
1617
1618 //! Oldest (lowest) magic number indicating unsupported essential dynamics input
1619 constexpr int c_oldestUnsupportedMagicNumber = 666;
1620 //! Oldest (lowest) magic number indicating supported essential dynamics input
1621 constexpr int c_oldestSupportedMagicNumber   = 669;
1622 //! Latest (highest) magic number indicating supported essential dynamics input
1623 constexpr int c_latestSupportedMagicNumber   = 670;
1624
1625 /*!\brief Set up essential dynamics work parameters.
1626  * \param[in] edi Essential dynamics working structure.
1627  */
1628 void setup_edi(t_edpar *edi)
1629 {
1630     snew(edi->sref.x_old, edi->sref.nr);
1631     edi->sref.sqrtm    = nullptr;
1632     snew(edi->sav.x_old, edi->sav.nr);
1633     if (edi->star.nr > 0)
1634     {
1635         edi->star.sqrtm    = nullptr;
1636     }
1637     if (edi->sori.nr > 0)
1638     {
1639         edi->sori.sqrtm    = nullptr;
1640     }
1641     setup_edvec(&edi->vecs.linacc);
1642     setup_edvec(&edi->vecs.mon);
1643     setup_edvec(&edi->vecs.linfix);
1644     setup_edvec(&edi->vecs.linacc);
1645     setup_edvec(&edi->vecs.radfix);
1646     setup_edvec(&edi->vecs.radacc);
1647     setup_edvec(&edi->vecs.radcon);
1648     setup_edvec(&edi->flood.vecs);
1649 }
1650
1651 /*!\brief Check if edi file version supports CONST_FORCE_FLOODING.
1652  * \param[in] magicNumber indicates the essential dynamics input file version
1653  * \returns true if CONST_FORCE_FLOODING is supported
1654  */
1655 bool ediFileHasConstForceFlooding(int magicNumber)
1656 {
1657     return magicNumber > c_oldestSupportedMagicNumber;
1658 };
1659
1660 /*!\brief Reports reading success of the essential dynamics input file magic number.
1661  * \param[in] in pointer to input file
1662  * \param[out] magicNumber determines the edi file version
1663  * \returns true if setting file version from input file was successful.
1664  */
1665 bool ediFileHasValidDataSet(FILE *in, int * magicNumber)
1666 {
1667     /* the edi file is not free format, so expect problems if the input is corrupt. */
1668     bool reachedEndOfFile = true;
1669     /* check the magic number */
1670     *magicNumber = read_edint(in, &reachedEndOfFile);
1671     /* Check whether we have reached the end of the input file */
1672     return !reachedEndOfFile;
1673 }
1674
1675 /*!\brief Trigger fatal error if magic number is unsupported.
1676  * \param[in] magicNumber A magic number read from the edi file
1677  * \param[in] fn name of input file for error reporting
1678  */
1679 void exitWhenMagicNumberIsInvalid(int magicNumber, const char * fn)
1680 {
1681
1682     if (magicNumber < c_oldestSupportedMagicNumber || magicNumber > c_latestSupportedMagicNumber)
1683     {
1684         if (magicNumber >= c_oldestUnsupportedMagicNumber && magicNumber < c_oldestSupportedMagicNumber)
1685         {
1686             gmx_fatal(FARGS, "Wrong magic number: Use newest version of make_edi to produce edi file");
1687         }
1688         else
1689         {
1690             gmx_fatal(FARGS, "Wrong magic number %d in %s", magicNumber, fn);
1691         }
1692     }
1693 }
1694
1695 /*!\brief reads an essential dynamics input file into a essential dynamics data structure.
1696  *
1697  * \param[in] in input file
1698  * \param[in] nr_mdatoms the number of md atoms, used for consistency checking
1699  * \param[in] hasConstForceFlooding determines if field "CONST_FORCE_FLOODING" is available in input file
1700  * \param[in] fn the file name of the input file for error reporting
1701  * \returns edi essential dynamics parameters
1702  */
1703 t_edpar read_edi(FILE* in, int nr_mdatoms, bool hasConstForceFlooding, const char *fn)
1704 {
1705     t_edpar edi;
1706     bool    bEOF;
1707     /* check the number of atoms */
1708     edi.nini = read_edint(in, &bEOF);
1709     if (edi.nini != nr_mdatoms)
1710     {
1711         gmx_fatal(FARGS, "Nr of atoms in %s (%d) does not match nr of md atoms (%d)", fn, edi.nini, nr_mdatoms);
1712     }
1713
1714     /* Done checking. For the rest we blindly trust the input */
1715     edi.fitmas          = read_checked_edbool(in, "FITMAS");
1716     edi.pcamas          = read_checked_edbool(in, "ANALYSIS_MAS");
1717     edi.outfrq          = read_checked_edint(in, "OUTFRQ");
1718     edi.maxedsteps      = read_checked_edint(in, "MAXLEN");
1719     edi.slope           = read_checked_edreal(in, "SLOPECRIT");
1720
1721     edi.presteps        = read_checked_edint(in, "PRESTEPS");
1722     edi.flood.deltaF0   = read_checked_edreal(in, "DELTA_F0");
1723     edi.flood.deltaF    = read_checked_edreal(in, "INIT_DELTA_F");
1724     edi.flood.tau       = read_checked_edreal(in, "TAU");
1725     edi.flood.constEfl  = read_checked_edreal(in, "EFL_NULL");
1726     edi.flood.alpha2    = read_checked_edreal(in, "ALPHA2");
1727     edi.flood.kT        = read_checked_edreal(in, "KT");
1728     edi.flood.bHarmonic = read_checked_edbool(in, "HARMONIC");
1729     if (hasConstForceFlooding)
1730     {
1731         edi.flood.bConstForce = read_checked_edbool(in, "CONST_FORCE_FLOODING");
1732     }
1733     else
1734     {
1735         edi.flood.bConstForce = FALSE;
1736     }
1737     edi.sref.nr         = read_checked_edint(in, "NREF");
1738
1739     /* allocate space for reference positions and read them */
1740     snew(edi.sref.anrs, edi.sref.nr);
1741     snew(edi.sref.x, edi.sref.nr);
1742     read_edx(in, edi.sref.nr, edi.sref.anrs, edi.sref.x);
1743
1744     /* average positions. they define which atoms will be used for ED sampling */
1745     edi.sav.nr = read_checked_edint(in, "NAV");
1746     snew(edi.sav.anrs, edi.sav.nr);
1747     snew(edi.sav.x, edi.sav.nr);
1748     read_edx(in, edi.sav.nr, edi.sav.anrs, edi.sav.x);
1749
1750     /* Check if the same atom indices are used for reference and average positions */
1751     edi.bRefEqAv = check_if_same(edi.sref, edi.sav);
1752
1753     /* eigenvectors */
1754
1755     read_edvec(in, edi.sav.nr, &edi.vecs.mon);
1756     read_edvec(in, edi.sav.nr, &edi.vecs.linfix);
1757     read_edvec(in, edi.sav.nr, &edi.vecs.linacc);
1758     read_edvec(in, edi.sav.nr, &edi.vecs.radfix);
1759     read_edvec(in, edi.sav.nr, &edi.vecs.radacc);
1760     read_edvec(in, edi.sav.nr, &edi.vecs.radcon);
1761
1762     /* Was a specific reference point for the flooding/umbrella potential provided in the edi file? */
1763     bool  bHaveReference = false;
1764     if (edi.flood.bHarmonic)
1765     {
1766         bHaveReference = readEdVecWithReferenceProjection(in, edi.sav.nr, &edi.flood.vecs, &edi.flood.initialReferenceProjection, &edi.flood.referenceProjectionSlope);
1767     }
1768     else
1769     {
1770         read_edvec(in, edi.sav.nr, &edi.flood.vecs);
1771     }
1772
1773     /* target positions */
1774     edi.star.nr = read_edint(in, &bEOF);
1775     if (edi.star.nr > 0)
1776     {
1777         snew(edi.star.anrs, edi.star.nr);
1778         snew(edi.star.x, edi.star.nr);
1779         read_edx(in, edi.star.nr, edi.star.anrs, edi.star.x);
1780     }
1781
1782     /* positions defining origin of expansion circle */
1783     edi.sori.nr = read_edint(in, &bEOF);
1784     if (edi.sori.nr > 0)
1785     {
1786         if (bHaveReference)
1787         {
1788             /* Both an -ori structure and a at least one manual reference point have been
1789              * specified. That's ambiguous and probably not intentional. */
1790             gmx_fatal(FARGS, "ED: An origin structure has been provided and a at least one (moving) reference\n"
1791                       "    point was manually specified in the edi file. That is ambiguous. Aborting.\n");
1792         }
1793         snew(edi.sori.anrs, edi.sori.nr);
1794         snew(edi.sori.x, edi.sori.nr);
1795         read_edx(in, edi.sori.nr, edi.sori.anrs, edi.sori.x);
1796     }
1797     return edi;
1798 }
1799
1800 std::vector<t_edpar> read_edi_file(const char *fn, int nr_mdatoms)
1801 {
1802     std::vector<t_edpar> essentialDynamicsParameters;
1803     FILE                *in;
1804     /* This routine is executed on the master only */
1805
1806     /* Open the .edi parameter input file */
1807     in = gmx_fio_fopen(fn, "r");
1808     fprintf(stderr, "ED: Reading edi file %s\n", fn);
1809
1810     /* Now read a sequence of ED input parameter sets from the edi file */
1811     int ediFileMagicNumber;
1812     while (ediFileHasValidDataSet(in, &ediFileMagicNumber))
1813     {
1814         exitWhenMagicNumberIsInvalid(ediFileMagicNumber, fn);
1815         bool hasConstForceFlooding = ediFileHasConstForceFlooding(ediFileMagicNumber);
1816         auto edi                   = read_edi(in, nr_mdatoms, hasConstForceFlooding, fn);
1817         setup_edi(&edi);
1818         essentialDynamicsParameters.emplace_back(edi);
1819
1820         /* Since we arrived within this while loop we know that there is still another data set to be read in */
1821         /* We need to allocate space for the data: */
1822     }
1823     if (essentialDynamicsParameters.empty())
1824     {
1825         gmx_fatal(FARGS, "No complete ED data set found in edi file %s.", fn);
1826     }
1827
1828     fprintf(stderr, "ED: Found %zu ED group%s.\n", essentialDynamicsParameters.size(), essentialDynamicsParameters.size() > 1 ? "s" : "");
1829
1830     /* Close the .edi file again */
1831     gmx_fio_fclose(in);
1832
1833     return essentialDynamicsParameters;
1834 }
1835 } // anonymous namespace
1836
1837
1838 struct t_fit_to_ref {
1839     rvec *xcopy;       /* Working copy of the positions in fit_to_reference */
1840 };
1841
1842 /* Fit the current positions to the reference positions
1843  * Do not actually do the fit, just return rotation and translation.
1844  * Note that the COM of the reference structure was already put into
1845  * the origin by init_edi. */
1846 static void fit_to_reference(rvec      *xcoll,    /* The positions to be fitted */
1847                              rvec       transvec, /* The translation vector */
1848                              matrix     rotmat,   /* The rotation matrix */
1849                              t_edpar   *edi)      /* Just needed for do_edfit */
1850 {
1851     rvec                 com;                     /* center of mass */
1852     int                  i;
1853     struct t_fit_to_ref *loc;
1854
1855
1856     /* Allocate memory the first time this routine is called for each edi group */
1857     if (nullptr == edi->buf->fit_to_ref)
1858     {
1859         snew(edi->buf->fit_to_ref, 1);
1860         snew(edi->buf->fit_to_ref->xcopy, edi->sref.nr);
1861     }
1862     loc = edi->buf->fit_to_ref;
1863
1864     /* We do not touch the original positions but work on a copy. */
1865     for (i = 0; i < edi->sref.nr; i++)
1866     {
1867         copy_rvec(xcoll[i], loc->xcopy[i]);
1868     }
1869
1870     /* Calculate the center of mass */
1871     get_center(loc->xcopy, edi->sref.m, edi->sref.nr, com);
1872
1873     transvec[XX] = -com[XX];
1874     transvec[YY] = -com[YY];
1875     transvec[ZZ] = -com[ZZ];
1876
1877     /* Subtract the center of mass from the copy */
1878     translate_x(loc->xcopy, edi->sref.nr, transvec);
1879
1880     /* Determine the rotation matrix */
1881     do_edfit(edi->sref.nr, edi->sref.x, loc->xcopy, rotmat, edi);
1882 }
1883
1884
1885 static void translate_and_rotate(rvec  *x,        /* The positions to be translated and rotated */
1886                                  int    nat,      /* How many positions are there? */
1887                                  rvec   transvec, /* The translation vector */
1888                                  matrix rotmat)   /* The rotation matrix */
1889 {
1890     /* Translation */
1891     translate_x(x, nat, transvec);
1892
1893     /* Rotation */
1894     rotate_x(x, nat, rotmat);
1895 }
1896
1897
1898 /* Gets the rms deviation of the positions to the structure s */
1899 /* fit_to_structure has to be called before calling this routine! */
1900 static real rmsd_from_structure(rvec           *x,  /* The positions under consideration */
1901                                 struct gmx_edx *s)  /* The structure from which the rmsd shall be computed */
1902 {
1903     real  rmsd = 0.0;
1904     int   i;
1905
1906
1907     for (i = 0; i < s->nr; i++)
1908     {
1909         rmsd += distance2(s->x[i], x[i]);
1910     }
1911
1912     rmsd /= static_cast<real>(s->nr);
1913     rmsd  = sqrt(rmsd);
1914
1915     return rmsd;
1916 }
1917
1918
1919 void dd_make_local_ed_indices(gmx_domdec_t *dd, struct gmx_edsam *ed)
1920 {
1921     if (ed->eEDtype != EssentialDynamicsType::None)
1922     {
1923         /* Loop over ED groups */
1924
1925         for (auto &edi : ed->edpar)
1926         {
1927             /* Local atoms of the reference structure (for fitting), need only be assembled
1928              * if their indices differ from the average ones */
1929             if (!edi.bRefEqAv)
1930             {
1931                 dd_make_local_group_indices(dd->ga2la, edi.sref.nr, edi.sref.anrs,
1932                                             &edi.sref.nr_loc, &edi.sref.anrs_loc, &edi.sref.nalloc_loc, edi.sref.c_ind);
1933             }
1934
1935             /* Local atoms of the average structure (on these ED will be performed) */
1936             dd_make_local_group_indices(dd->ga2la, edi.sav.nr, edi.sav.anrs,
1937                                         &edi.sav.nr_loc, &edi.sav.anrs_loc, &edi.sav.nalloc_loc, edi.sav.c_ind);
1938
1939             /* Indicate that the ED shift vectors for this structure need to be updated
1940              * at the next call to communicate_group_positions, since obviously we are in a NS step */
1941             edi.buf->do_edsam->bUpdateShifts = TRUE;
1942         }
1943     }
1944 }
1945
1946
1947 static inline void ed_unshift_single_coord(matrix box, const rvec x, const ivec is, rvec xu)
1948 {
1949     int tx, ty, tz;
1950
1951
1952     tx = is[XX];
1953     ty = is[YY];
1954     tz = is[ZZ];
1955
1956     if (TRICLINIC(box))
1957     {
1958         xu[XX] = x[XX]-tx*box[XX][XX]-ty*box[YY][XX]-tz*box[ZZ][XX];
1959         xu[YY] = x[YY]-ty*box[YY][YY]-tz*box[ZZ][YY];
1960         xu[ZZ] = x[ZZ]-tz*box[ZZ][ZZ];
1961     }
1962     else
1963     {
1964         xu[XX] = x[XX]-tx*box[XX][XX];
1965         xu[YY] = x[YY]-ty*box[YY][YY];
1966         xu[ZZ] = x[ZZ]-tz*box[ZZ][ZZ];
1967     }
1968 }
1969
1970 namespace
1971 {
1972 /*!\brief Apply fixed linear constraints to essential dynamics variable.
1973  * \param[in,out] xcoll The collected coordinates.
1974  * \param[in] edi the essential dynamics parameters
1975  * \param[in] step the current simulation step
1976  */
1977 void do_linfix(rvec *xcoll, const t_edpar &edi, int64_t step)
1978 {
1979     /* loop over linfix vectors */
1980     for (int i = 0; i < edi.vecs.linfix.neig; i++)
1981     {
1982         /* calculate the projection */
1983         real proj = projectx(edi, xcoll, edi.vecs.linfix.vec[i]);
1984
1985         /* calculate the correction */
1986         real preFactor = edi.vecs.linfix.refproj[i] + step*edi.vecs.linfix.stpsz[i] - proj;
1987
1988         /* apply the correction */
1989         preFactor /= edi.sav.sqrtm[i];
1990         for (int j = 0; j < edi.sav.nr; j++)
1991         {
1992             rvec differenceVector;
1993             svmul(preFactor, edi.vecs.linfix.vec[i][j], differenceVector);
1994             rvec_inc(xcoll[j], differenceVector);
1995         }
1996     }
1997 }
1998
1999 /*!\brief Apply acceptance linear constraints to essential dynamics variable.
2000  * \param[in,out] xcoll The collected coordinates.
2001  * \param[in] edi the essential dynamics parameters
2002  */
2003 void do_linacc(rvec *xcoll, t_edpar *edi)
2004 {
2005     /* loop over linacc vectors */
2006     for (int i = 0; i < edi->vecs.linacc.neig; i++)
2007     {
2008         /* calculate the projection */
2009         real proj = projectx(*edi, xcoll, edi->vecs.linacc.vec[i]);
2010
2011         /* calculate the correction */
2012         real preFactor = 0.0;
2013         if (edi->vecs.linacc.stpsz[i] > 0.0)
2014         {
2015             if ((proj-edi->vecs.linacc.refproj[i]) < 0.0)
2016             {
2017                 preFactor = edi->vecs.linacc.refproj[i] - proj;
2018             }
2019         }
2020         if (edi->vecs.linacc.stpsz[i] < 0.0)
2021         {
2022             if ((proj-edi->vecs.linacc.refproj[i]) > 0.0)
2023             {
2024                 preFactor = edi->vecs.linacc.refproj[i] - proj;
2025             }
2026         }
2027
2028         /* apply the correction */
2029         preFactor /= edi->sav.sqrtm[i];
2030         for (int j = 0; j < edi->sav.nr; j++)
2031         {
2032             rvec differenceVector;
2033             svmul(preFactor, edi->vecs.linacc.vec[i][j], differenceVector);
2034             rvec_inc(xcoll[j], differenceVector);
2035         }
2036
2037         /* new positions will act as reference */
2038         edi->vecs.linacc.refproj[i] = proj + preFactor;
2039     }
2040 }
2041 } // namespace
2042
2043
2044 static void do_radfix(rvec *xcoll, t_edpar *edi)
2045 {
2046     int   i, j;
2047     real *proj, rad = 0.0, ratio;
2048     rvec  vec_dum;
2049
2050
2051     if (edi->vecs.radfix.neig == 0)
2052     {
2053         return;
2054     }
2055
2056     snew(proj, edi->vecs.radfix.neig);
2057
2058     /* loop over radfix vectors */
2059     for (i = 0; i < edi->vecs.radfix.neig; i++)
2060     {
2061         /* calculate the projections, radius */
2062         proj[i] = projectx(*edi, xcoll, edi->vecs.radfix.vec[i]);
2063         rad    += gmx::square(proj[i] - edi->vecs.radfix.refproj[i]);
2064     }
2065
2066     rad                      = sqrt(rad);
2067     ratio                    = (edi->vecs.radfix.stpsz[0]+edi->vecs.radfix.radius)/rad - 1.0;
2068     edi->vecs.radfix.radius += edi->vecs.radfix.stpsz[0];
2069
2070     /* loop over radfix vectors */
2071     for (i = 0; i < edi->vecs.radfix.neig; i++)
2072     {
2073         proj[i] -= edi->vecs.radfix.refproj[i];
2074
2075         /* apply the correction */
2076         proj[i] /= edi->sav.sqrtm[i];
2077         proj[i] *= ratio;
2078         for (j = 0; j < edi->sav.nr; j++)
2079         {
2080             svmul(proj[i], edi->vecs.radfix.vec[i][j], vec_dum);
2081             rvec_inc(xcoll[j], vec_dum);
2082         }
2083     }
2084
2085     sfree(proj);
2086 }
2087
2088
2089 static void do_radacc(rvec *xcoll, t_edpar *edi)
2090 {
2091     int   i, j;
2092     real *proj, rad = 0.0, ratio = 0.0;
2093     rvec  vec_dum;
2094
2095
2096     if (edi->vecs.radacc.neig == 0)
2097     {
2098         return;
2099     }
2100
2101     snew(proj, edi->vecs.radacc.neig);
2102
2103     /* loop over radacc vectors */
2104     for (i = 0; i < edi->vecs.radacc.neig; i++)
2105     {
2106         /* calculate the projections, radius */
2107         proj[i] = projectx(*edi, xcoll, edi->vecs.radacc.vec[i]);
2108         rad    += gmx::square(proj[i] - edi->vecs.radacc.refproj[i]);
2109     }
2110     rad = sqrt(rad);
2111
2112     /* only correct when radius decreased */
2113     if (rad < edi->vecs.radacc.radius)
2114     {
2115         ratio = edi->vecs.radacc.radius/rad - 1.0;
2116     }
2117     else
2118     {
2119         edi->vecs.radacc.radius = rad;
2120     }
2121
2122     /* loop over radacc vectors */
2123     for (i = 0; i < edi->vecs.radacc.neig; i++)
2124     {
2125         proj[i] -= edi->vecs.radacc.refproj[i];
2126
2127         /* apply the correction */
2128         proj[i] /= edi->sav.sqrtm[i];
2129         proj[i] *= ratio;
2130         for (j = 0; j < edi->sav.nr; j++)
2131         {
2132             svmul(proj[i], edi->vecs.radacc.vec[i][j], vec_dum);
2133             rvec_inc(xcoll[j], vec_dum);
2134         }
2135     }
2136     sfree(proj);
2137 }
2138
2139
2140 struct t_do_radcon {
2141     real *proj;
2142 };
2143
2144 static void do_radcon(rvec *xcoll, t_edpar *edi)
2145 {
2146     int                 i, j;
2147     real                rad = 0.0, ratio = 0.0;
2148     struct t_do_radcon *loc;
2149     gmx_bool            bFirst;
2150     rvec                vec_dum;
2151
2152
2153     if (edi->buf->do_radcon != nullptr)
2154     {
2155         bFirst = FALSE;
2156     }
2157     else
2158     {
2159         bFirst = TRUE;
2160         snew(edi->buf->do_radcon, 1);
2161     }
2162     loc = edi->buf->do_radcon;
2163
2164     if (edi->vecs.radcon.neig == 0)
2165     {
2166         return;
2167     }
2168
2169     if (bFirst)
2170     {
2171         snew(loc->proj, edi->vecs.radcon.neig);
2172     }
2173
2174     /* loop over radcon vectors */
2175     for (i = 0; i < edi->vecs.radcon.neig; i++)
2176     {
2177         /* calculate the projections, radius */
2178         loc->proj[i] = projectx(*edi, xcoll, edi->vecs.radcon.vec[i]);
2179         rad         += gmx::square(loc->proj[i] - edi->vecs.radcon.refproj[i]);
2180     }
2181     rad = sqrt(rad);
2182     /* only correct when radius increased */
2183     if (rad > edi->vecs.radcon.radius)
2184     {
2185         ratio = edi->vecs.radcon.radius/rad - 1.0;
2186
2187         /* loop over radcon vectors */
2188         for (i = 0; i < edi->vecs.radcon.neig; i++)
2189         {
2190             /* apply the correction */
2191             loc->proj[i] -= edi->vecs.radcon.refproj[i];
2192             loc->proj[i] /= edi->sav.sqrtm[i];
2193             loc->proj[i] *= ratio;
2194
2195             for (j = 0; j < edi->sav.nr; j++)
2196             {
2197                 svmul(loc->proj[i], edi->vecs.radcon.vec[i][j], vec_dum);
2198                 rvec_inc(xcoll[j], vec_dum);
2199             }
2200         }
2201
2202     }
2203     else
2204     {
2205         edi->vecs.radcon.radius = rad;
2206     }
2207
2208 }
2209
2210
2211 static void ed_apply_constraints(rvec *xcoll, t_edpar *edi, int64_t step)
2212 {
2213     int i;
2214
2215
2216     /* subtract the average positions */
2217     for (i = 0; i < edi->sav.nr; i++)
2218     {
2219         rvec_dec(xcoll[i], edi->sav.x[i]);
2220     }
2221
2222     /* apply the constraints */
2223     if (step >= 0)
2224     {
2225         do_linfix(xcoll, *edi, step);
2226     }
2227     do_linacc(xcoll, edi);
2228     if (step >= 0)
2229     {
2230         do_radfix(xcoll, edi);
2231     }
2232     do_radacc(xcoll, edi);
2233     do_radcon(xcoll, edi);
2234
2235     /* add back the average positions */
2236     for (i = 0; i < edi->sav.nr; i++)
2237     {
2238         rvec_inc(xcoll[i], edi->sav.x[i]);
2239     }
2240 }
2241
2242
2243 namespace
2244 {
2245 /*!\brief Write out the projections onto the eigenvectors.
2246  * The order of output corresponds to ed_output_legend().
2247  * \param[in] edi The essential dyanmics parameters
2248  * \param[in] fp The output file
2249  * \param[in] rmsd the rmsd to the reference structure
2250  */
2251 void write_edo(const t_edpar &edi, FILE *fp, real rmsd)
2252 {
2253     /* Output how well we fit to the reference structure */
2254     fprintf(fp, EDcol_ffmt, rmsd);
2255
2256     for (int i = 0; i < edi.vecs.mon.neig; i++)
2257     {
2258         fprintf(fp, EDcol_efmt, edi.vecs.mon.xproj[i]);
2259     }
2260
2261     for (int i = 0; i < edi.vecs.linfix.neig; i++)
2262     {
2263         fprintf(fp, EDcol_efmt, edi.vecs.linfix.xproj[i]);
2264     }
2265
2266     for (int i = 0; i < edi.vecs.linacc.neig; i++)
2267     {
2268         fprintf(fp, EDcol_efmt, edi.vecs.linacc.xproj[i]);
2269     }
2270
2271     for (int i = 0; i < edi.vecs.radfix.neig; i++)
2272     {
2273         fprintf(fp, EDcol_efmt, edi.vecs.radfix.xproj[i]);
2274     }
2275     if (edi.vecs.radfix.neig)
2276     {
2277         fprintf(fp, EDcol_ffmt, calc_radius(edi.vecs.radfix)); /* fixed increment radius */
2278     }
2279
2280     for (int i = 0; i < edi.vecs.radacc.neig; i++)
2281     {
2282         fprintf(fp, EDcol_efmt, edi.vecs.radacc.xproj[i]);
2283     }
2284     if (edi.vecs.radacc.neig)
2285     {
2286         fprintf(fp, EDcol_ffmt, calc_radius(edi.vecs.radacc)); /* acceptance radius */
2287     }
2288
2289     for (int i = 0; i < edi.vecs.radcon.neig; i++)
2290     {
2291         fprintf(fp, EDcol_efmt, edi.vecs.radcon.xproj[i]);
2292     }
2293     if (edi.vecs.radcon.neig)
2294     {
2295         fprintf(fp, EDcol_ffmt, calc_radius(edi.vecs.radcon)); /* contracting radius */
2296     }
2297 }
2298 } // namespace
2299
2300
2301 /* Returns if any constraints are switched on */
2302 static bool ed_constraints(EssentialDynamicsType edtype, const t_edpar &edi)
2303 {
2304     if (edtype == EssentialDynamicsType::EDSampling || edtype == EssentialDynamicsType::Flooding)
2305     {
2306         return ((edi.vecs.linfix.neig != 0) || (edi.vecs.linacc.neig != 0) ||
2307                 (edi.vecs.radfix.neig != 0) || (edi.vecs.radacc.neig != 0) ||
2308                 (edi.vecs.radcon.neig != 0));
2309     }
2310     return false;
2311 }
2312
2313
2314 /* Copies reference projection 'refproj' to fixed 'initialReferenceProjection' variable for flooding/
2315  * umbrella sampling simulations. */
2316 static void copyEvecReference(t_eigvec* floodvecs, real * initialReferenceProjection)
2317 {
2318     int i;
2319
2320
2321     if (nullptr == initialReferenceProjection)
2322     {
2323         snew(initialReferenceProjection, floodvecs->neig);
2324     }
2325
2326     for (i = 0; i < floodvecs->neig; i++)
2327     {
2328         initialReferenceProjection[i] = floodvecs->refproj[i];
2329     }
2330 }
2331
2332
2333 /* Call on MASTER only. Check whether the essential dynamics / flooding
2334  * groups of the checkpoint file are consistent with the provided .edi file. */
2335 static void crosscheck_edi_file_vs_checkpoint(const gmx_edsam &ed, edsamhistory_t *EDstate)
2336 {
2337     if (nullptr == EDstate->nref || nullptr == EDstate->nav)
2338     {
2339         gmx_fatal(FARGS, "Essential dynamics and flooding can only be switched on (or off) at the\n"
2340                   "start of a new simulation. If a simulation runs with/without ED constraints,\n"
2341                   "it must also continue with/without ED constraints when checkpointing.\n"
2342                   "To switch on (or off) ED constraints, please prepare a new .tpr to start\n"
2343                   "from without a checkpoint.\n");
2344     }
2345
2346     for (size_t edinum = 0; edinum < ed.edpar.size(); ++edinum)
2347     {
2348         /* Check number of atoms in the reference and average structures */
2349         if (EDstate->nref[edinum] != ed.edpar[edinum].sref.nr)
2350         {
2351             gmx_fatal(FARGS, "The number of reference structure atoms in ED group %c is\n"
2352                       "not the same in .cpt (NREF=%d) and .edi (NREF=%d) files!\n",
2353                       get_EDgroupChar(edinum+1, 0), EDstate->nref[edinum], ed.edpar[edinum].sref.nr);
2354         }
2355         if (EDstate->nav[edinum] != ed.edpar[edinum].sav.nr)
2356         {
2357             gmx_fatal(FARGS, "The number of average structure atoms in ED group %c is\n"
2358                       "not the same in .cpt (NREF=%d) and .edi (NREF=%d) files!\n",
2359                       get_EDgroupChar(edinum+1, 0), EDstate->nav[edinum], ed.edpar[edinum].sav.nr);
2360         }
2361     }
2362
2363     if (static_cast<int>(ed.edpar.size()) != EDstate->nED)
2364     {
2365         gmx_fatal(FARGS, "The number of essential dynamics / flooding groups is not consistent.\n"
2366                   "There are %d ED groups in the .cpt file, but %zu in the .edi file!\n"
2367                   "Are you sure this is the correct .edi file?\n", EDstate->nED, ed.edpar.size());
2368     }
2369 }
2370
2371
2372 /* The edsamstate struct stores the information we need to make the ED group
2373  * whole again after restarts from a checkpoint file. Here we do the following:
2374  * a) If we did not start from .cpt, we prepare the struct for proper .cpt writing,
2375  * b) if we did start from .cpt, we copy over the last whole structures from .cpt,
2376  * c) in any case, for subsequent checkpoint writing, we set the pointers in
2377  * edsamstate to the x_old arrays, which contain the correct PBC representation of
2378  * all ED structures at the last time step. */
2379 static void init_edsamstate(const gmx_edsam &ed, edsamhistory_t *EDstate)
2380 {
2381     snew(EDstate->old_sref_p, EDstate->nED);
2382     snew(EDstate->old_sav_p, EDstate->nED);
2383
2384     /* If we did not read in a .cpt file, these arrays are not yet allocated */
2385     if (!EDstate->bFromCpt)
2386     {
2387         snew(EDstate->nref, EDstate->nED);
2388         snew(EDstate->nav, EDstate->nED);
2389     }
2390
2391     /* Loop over all ED/flooding data sets (usually only one, though) */
2392     for (int nr_edi = 0; nr_edi < EDstate->nED; nr_edi++)
2393     {
2394         const auto &edi = ed.edpar[nr_edi];
2395         /* We always need the last reference and average positions such that
2396          * in the next time step we can make the ED group whole again
2397          * if the atoms do not have the correct PBC representation */
2398         if (EDstate->bFromCpt)
2399         {
2400             /* Copy the last whole positions of reference and average group from .cpt */
2401             for (int i = 0; i < edi.sref.nr; i++)
2402             {
2403                 copy_rvec(EDstate->old_sref[nr_edi][i], edi.sref.x_old[i]);
2404             }
2405             for (int i = 0; i < edi.sav.nr; i++)
2406             {
2407                 copy_rvec(EDstate->old_sav [nr_edi][i], edi.sav.x_old [i]);
2408             }
2409         }
2410         else
2411         {
2412             EDstate->nref[nr_edi] = edi.sref.nr;
2413             EDstate->nav [nr_edi] = edi.sav.nr;
2414         }
2415
2416         /* For subsequent checkpoint writing, set the edsamstate pointers to the edi arrays: */
2417         EDstate->old_sref_p[nr_edi] = edi.sref.x_old;
2418         EDstate->old_sav_p [nr_edi] = edi.sav.x_old;
2419     }
2420 }
2421
2422
2423 /* Adds 'buf' to 'str' */
2424 static void add_to_string(char **str, const char *buf)
2425 {
2426     int len;
2427
2428
2429     len = strlen(*str) + strlen(buf) + 1;
2430     srenew(*str, len);
2431     strcat(*str, buf);
2432 }
2433
2434
2435 static void add_to_string_aligned(char **str, const char *buf)
2436 {
2437     char buf_aligned[STRLEN];
2438
2439     sprintf(buf_aligned, EDcol_sfmt, buf);
2440     add_to_string(str, buf_aligned);
2441 }
2442
2443
2444 static void nice_legend(const char ***setname, int *nsets, char **LegendStr, const char *value, const char *unit, char EDgroupchar)
2445 {
2446     auto tmp = gmx::formatString("%c %s", EDgroupchar, value);
2447     add_to_string_aligned(LegendStr, tmp.c_str());
2448     tmp               += gmx::formatString(" (%s)", unit);
2449     (*setname)[*nsets] = gmx_strdup(tmp.c_str());
2450     (*nsets)++;
2451 }
2452
2453
2454 static void nice_legend_evec(const char ***setname, int *nsets, char **LegendStr, t_eigvec *evec, char EDgroupChar, const char *EDtype)
2455 {
2456     int  i;
2457     char tmp[STRLEN];
2458
2459
2460     for (i = 0; i < evec->neig; i++)
2461     {
2462         sprintf(tmp, "EV%dprj%s", evec->ieig[i], EDtype);
2463         nice_legend(setname, nsets, LegendStr, tmp, "nm", EDgroupChar);
2464     }
2465 }
2466
2467
2468 /* Makes a legend for the xvg output file. Call on MASTER only! */
2469 static void write_edo_legend(gmx_edsam * ed, int nED, const gmx_output_env_t *oenv)
2470 {
2471     int          i;
2472     int          nr_edi, nsets, n_flood, n_edsam;
2473     const char **setname;
2474     char         buf[STRLEN];
2475     char        *LegendStr = nullptr;
2476
2477
2478     auto edi         = ed->edpar.begin();
2479
2480     fprintf(ed->edo, "# Output will be written every %d step%s\n", edi->outfrq, edi->outfrq != 1 ? "s" : "");
2481
2482     for (nr_edi = 1; nr_edi <= nED; nr_edi++)
2483     {
2484         fprintf(ed->edo, "#\n");
2485         fprintf(ed->edo, "# Summary of applied con/restraints for the ED group %c\n", get_EDgroupChar(nr_edi, nED));
2486         fprintf(ed->edo, "# Atoms in average structure: %d\n", edi->sav.nr);
2487         fprintf(ed->edo, "#    monitor  : %d vec%s\n", edi->vecs.mon.neig, edi->vecs.mon.neig    != 1 ? "s" : "");
2488         fprintf(ed->edo, "#    LINFIX   : %d vec%s\n", edi->vecs.linfix.neig, edi->vecs.linfix.neig != 1 ? "s" : "");
2489         fprintf(ed->edo, "#    LINACC   : %d vec%s\n", edi->vecs.linacc.neig, edi->vecs.linacc.neig != 1 ? "s" : "");
2490         fprintf(ed->edo, "#    RADFIX   : %d vec%s\n", edi->vecs.radfix.neig, edi->vecs.radfix.neig != 1 ? "s" : "");
2491         fprintf(ed->edo, "#    RADACC   : %d vec%s\n", edi->vecs.radacc.neig, edi->vecs.radacc.neig != 1 ? "s" : "");
2492         fprintf(ed->edo, "#    RADCON   : %d vec%s\n", edi->vecs.radcon.neig, edi->vecs.radcon.neig != 1 ? "s" : "");
2493         fprintf(ed->edo, "#    FLOODING : %d vec%s  ", edi->flood.vecs.neig, edi->flood.vecs.neig  != 1 ? "s" : "");
2494
2495         if (edi->flood.vecs.neig)
2496         {
2497             /* If in any of the groups we find a flooding vector, flooding is turned on */
2498             ed->eEDtype = EssentialDynamicsType::Flooding;
2499
2500             /* Print what flavor of flooding we will do */
2501             if (0 == edi->flood.tau) /* constant flooding strength */
2502             {
2503                 fprintf(ed->edo, "Efl_null = %g", edi->flood.constEfl);
2504                 if (edi->flood.bHarmonic)
2505                 {
2506                     fprintf(ed->edo, ", harmonic");
2507                 }
2508             }
2509             else /* adaptive flooding */
2510             {
2511                 fprintf(ed->edo, ", adaptive");
2512             }
2513         }
2514         fprintf(ed->edo, "\n");
2515
2516         ++edi;
2517     }
2518
2519     /* Print a nice legend */
2520     snew(LegendStr, 1);
2521     LegendStr[0] = '\0';
2522     sprintf(buf, "#     %6s", "time");
2523     add_to_string(&LegendStr, buf);
2524
2525     /* Calculate the maximum number of columns we could end up with */
2526     edi     = ed->edpar.begin();
2527     nsets   = 0;
2528     for (nr_edi = 1; nr_edi <= nED; nr_edi++)
2529     {
2530         nsets += 5 +edi->vecs.mon.neig
2531             +edi->vecs.linfix.neig
2532             +edi->vecs.linacc.neig
2533             +edi->vecs.radfix.neig
2534             +edi->vecs.radacc.neig
2535             +edi->vecs.radcon.neig
2536             + 6*edi->flood.vecs.neig;
2537         ++edi;
2538     }
2539     snew(setname, nsets);
2540
2541     /* In the mdrun time step in a first function call (do_flood()) the flooding
2542      * forces are calculated and in a second function call (do_edsam()) the
2543      * ED constraints. To get a corresponding legend, we need to loop twice
2544      * over the edi groups and output first the flooding, then the ED part */
2545
2546     /* The flooding-related legend entries, if flooding is done */
2547     nsets = 0;
2548     if (EssentialDynamicsType::Flooding == ed->eEDtype)
2549     {
2550         edi   = ed->edpar.begin();
2551         for (nr_edi = 1; nr_edi <= nED; nr_edi++)
2552         {
2553             /* Always write out the projection on the flooding EVs. Of course, this can also
2554              * be achieved with the monitoring option in do_edsam() (if switched on by the
2555              * user), but in that case the positions need to be communicated in do_edsam(),
2556              * which is not necessary when doing flooding only. */
2557             nice_legend(&setname, &nsets, &LegendStr, "RMSD to ref", "nm", get_EDgroupChar(nr_edi, nED) );
2558
2559             for (i = 0; i < edi->flood.vecs.neig; i++)
2560             {
2561                 sprintf(buf, "EV%dprjFLOOD", edi->flood.vecs.ieig[i]);
2562                 nice_legend(&setname, &nsets, &LegendStr, buf, "nm", get_EDgroupChar(nr_edi, nED));
2563
2564                 /* Output the current reference projection if it changes with time;
2565                  * this can happen when flooding is used as harmonic restraint */
2566                 if (edi->flood.bHarmonic && edi->flood.referenceProjectionSlope[i] != 0.0)
2567                 {
2568                     sprintf(buf, "EV%d ref.prj.", edi->flood.vecs.ieig[i]);
2569                     nice_legend(&setname, &nsets, &LegendStr, buf, "nm", get_EDgroupChar(nr_edi, nED));
2570                 }
2571
2572                 /* For flooding we also output Efl, Vfl, deltaF, and the flooding forces */
2573                 if (0 != edi->flood.tau) /* only output Efl for adaptive flooding (constant otherwise) */
2574                 {
2575                     sprintf(buf, "EV%d-Efl", edi->flood.vecs.ieig[i]);
2576                     nice_legend(&setname, &nsets, &LegendStr, buf, "kJ/mol", get_EDgroupChar(nr_edi, nED));
2577                 }
2578
2579                 sprintf(buf, "EV%d-Vfl", edi->flood.vecs.ieig[i]);
2580                 nice_legend(&setname, &nsets, &LegendStr, buf, "kJ/mol", get_EDgroupChar(nr_edi, nED));
2581
2582                 if (0 != edi->flood.tau) /* only output deltaF for adaptive flooding (zero otherwise) */
2583                 {
2584                     sprintf(buf, "EV%d-deltaF", edi->flood.vecs.ieig[i]);
2585                     nice_legend(&setname, &nsets, &LegendStr, buf, "kJ/mol", get_EDgroupChar(nr_edi, nED));
2586                 }
2587
2588                 sprintf(buf, "EV%d-FLforces", edi->flood.vecs.ieig[i]);
2589                 nice_legend(&setname, &nsets, &LegendStr, buf, "kJ/mol/nm", get_EDgroupChar(nr_edi, nED));
2590             }
2591
2592             ++edi;
2593         } /* End of flooding-related legend entries */
2594     }
2595     n_flood = nsets;
2596
2597     /* Now the ED-related entries, if essential dynamics is done */
2598     edi         = ed->edpar.begin();
2599     for (nr_edi = 1; nr_edi <= nED; nr_edi++)
2600     {
2601         if (bNeedDoEdsam(*edi))  /* Only print ED legend if at least one ED option is on */
2602         {
2603             nice_legend(&setname, &nsets, &LegendStr, "RMSD to ref", "nm", get_EDgroupChar(nr_edi, nED) );
2604
2605             /* Essential dynamics, projections on eigenvectors */
2606             nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.mon, get_EDgroupChar(nr_edi, nED), "MON"   );
2607             nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.linfix, get_EDgroupChar(nr_edi, nED), "LINFIX");
2608             nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.linacc, get_EDgroupChar(nr_edi, nED), "LINACC");
2609             nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.radfix, get_EDgroupChar(nr_edi, nED), "RADFIX");
2610             if (edi->vecs.radfix.neig)
2611             {
2612                 nice_legend(&setname, &nsets, &LegendStr, "RADFIX radius", "nm", get_EDgroupChar(nr_edi, nED));
2613             }
2614             nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.radacc, get_EDgroupChar(nr_edi, nED), "RADACC");
2615             if (edi->vecs.radacc.neig)
2616             {
2617                 nice_legend(&setname, &nsets, &LegendStr, "RADACC radius", "nm", get_EDgroupChar(nr_edi, nED));
2618             }
2619             nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.radcon, get_EDgroupChar(nr_edi, nED), "RADCON");
2620             if (edi->vecs.radcon.neig)
2621             {
2622                 nice_legend(&setname, &nsets, &LegendStr, "RADCON radius", "nm", get_EDgroupChar(nr_edi, nED));
2623             }
2624         }
2625         ++edi;
2626     } /* end of 'pure' essential dynamics legend entries */
2627     n_edsam = nsets - n_flood;
2628
2629     xvgr_legend(ed->edo, nsets, setname, oenv);
2630     sfree(setname);
2631
2632     fprintf(ed->edo, "#\n"
2633             "# Legend for %d column%s of flooding plus %d column%s of essential dynamics data:\n",
2634             n_flood, 1 == n_flood ? "" : "s",
2635             n_edsam, 1 == n_edsam ? "" : "s");
2636     fprintf(ed->edo, "%s", LegendStr);
2637     sfree(LegendStr);
2638
2639     fflush(ed->edo);
2640 }
2641
2642
2643 /* Init routine for ED and flooding. Calls init_edi in a loop for every .edi-cycle
2644  * contained in the input file, creates a NULL terminated list of t_edpar structures */
2645 std::unique_ptr<gmx::EssentialDynamics> init_edsam(
2646         const char             *ediFileName,
2647         const char             *edoFileName,
2648         const gmx_mtop_t       *mtop,
2649         const t_inputrec       *ir,
2650         const t_commrec        *cr,
2651         gmx::Constraints       *constr,
2652         const t_state          *globalState,
2653         ObservablesHistory     *oh,
2654         const gmx_output_env_t *oenv,
2655         gmx_bool                bAppend)
2656 {
2657     int      i, avindex;
2658     rvec    *x_pbc  = nullptr;                    /* positions of the whole MD system with pbc removed  */
2659     rvec    *xfit   = nullptr, *xstart = nullptr; /* dummy arrays to determine initial RMSDs  */
2660     rvec     fit_transvec;                        /* translation ... */
2661     matrix   fit_rotmat;                          /* ... and rotation from fit to reference structure */
2662     rvec    *ref_x_old = nullptr;                 /* helper pointer */
2663
2664
2665     if (MASTER(cr))
2666     {
2667         fprintf(stderr, "ED: Initializing essential dynamics constraints.\n");
2668
2669         if (oh->edsamHistory != nullptr && oh->edsamHistory->bFromCpt && !gmx_fexist(ediFileName) )
2670         {
2671             gmx_fatal(FARGS, "The checkpoint file you provided is from an essential dynamics or flooding\n"
2672                       "simulation. Please also set the .edi file on the command line with -ei.\n");
2673         }
2674     }
2675
2676     /* Open input and output files, allocate space for ED data structure */
2677     auto edHandle = ed_open(mtop->natoms, oh, ediFileName, edoFileName, bAppend, oenv, cr);
2678     auto ed       = edHandle->getLegacyED();
2679     GMX_RELEASE_ASSERT(constr != nullptr, "Must have valid constraints object");
2680     constr->saveEdsamPointer(ed);
2681
2682     /* Needed for initializing radacc radius in do_edsam */
2683     ed->bFirst = TRUE;
2684
2685     /* The input file is read by the master and the edi structures are
2686      * initialized here. Input is stored in ed->edpar. Then the edi
2687      * structures are transferred to the other nodes */
2688     if (MASTER(cr))
2689     {
2690         /* Initialization for every ED/flooding group. Flooding uses one edi group per
2691          * flooding vector, Essential dynamics can be applied to more than one structure
2692          * as well, but will be done in the order given in the edi file, so
2693          * expect different results for different order of edi file concatenation! */
2694         for (auto &edi : ed->edpar)
2695         {
2696             init_edi(mtop, &edi);
2697             init_flood(&edi, ed, ir->delta_t);
2698         }
2699     }
2700
2701     /* The master does the work here. The other nodes get the positions
2702      * not before dd_partition_system which is called after init_edsam */
2703     if (MASTER(cr))
2704     {
2705         edsamhistory_t *EDstate = oh->edsamHistory.get();
2706
2707         if (!EDstate->bFromCpt)
2708         {
2709             /* Remove PBC, make molecule(s) subject to ED whole. */
2710             snew(x_pbc, mtop->natoms);
2711             copy_rvecn(globalState->x.rvec_array(), x_pbc, 0, mtop->natoms);
2712             do_pbc_first_mtop(nullptr, ir->ePBC, globalState->box, mtop, x_pbc);
2713         }
2714         /* Reset pointer to first ED data set which contains the actual ED data */
2715         auto edi = ed->edpar.begin();
2716         GMX_ASSERT(!ed->edpar.empty(), "Essential dynamics parameters is undefined");
2717
2718         /* Loop over all ED/flooding data sets (usually only one, though) */
2719         for (int nr_edi = 1; nr_edi <= EDstate->nED; nr_edi++)
2720         {
2721             /* For multiple ED groups we use the output frequency that was specified
2722              * in the first set */
2723             if (nr_edi > 1)
2724             {
2725                 edi->outfrq = ed->edpar.begin()->outfrq;
2726             }
2727
2728             /* Extract the initial reference and average positions. When starting
2729              * from .cpt, these have already been read into sref.x_old
2730              * in init_edsamstate() */
2731             if (!EDstate->bFromCpt)
2732             {
2733                 /* If this is the first run (i.e. no checkpoint present) we assume
2734                  * that the starting positions give us the correct PBC representation */
2735                 for (i = 0; i < edi->sref.nr; i++)
2736                 {
2737                     copy_rvec(x_pbc[edi->sref.anrs[i]], edi->sref.x_old[i]);
2738                 }
2739
2740                 for (i = 0; i < edi->sav.nr; i++)
2741                 {
2742                     copy_rvec(x_pbc[edi->sav.anrs[i]], edi->sav.x_old[i]);
2743                 }
2744             }
2745
2746             /* Now we have the PBC-correct start positions of the reference and
2747                average structure. We copy that over to dummy arrays on which we
2748                can apply fitting to print out the RMSD. We srenew the memory since
2749                the size of the buffers is likely different for every ED group */
2750             srenew(xfit, edi->sref.nr );
2751             srenew(xstart, edi->sav.nr  );
2752             if (edi->bRefEqAv)
2753             {
2754                 /* Reference indices are the same as average indices */
2755                 ref_x_old = edi->sav.x_old;
2756             }
2757             else
2758             {
2759                 ref_x_old = edi->sref.x_old;
2760             }
2761             copy_rvecn(ref_x_old, xfit, 0, edi->sref.nr);
2762             copy_rvecn(edi->sav.x_old, xstart, 0, edi->sav.nr);
2763
2764             /* Make the fit to the REFERENCE structure, get translation and rotation */
2765             fit_to_reference(xfit, fit_transvec, fit_rotmat, &(*edi));
2766
2767             /* Output how well we fit to the reference at the start */
2768             translate_and_rotate(xfit, edi->sref.nr, fit_transvec, fit_rotmat);
2769             fprintf(stderr, "ED: Initial RMSD from reference after fit = %f nm",
2770                     rmsd_from_structure(xfit, &edi->sref));
2771             if (EDstate->nED > 1)
2772             {
2773                 fprintf(stderr, " (ED group %c)", get_EDgroupChar(nr_edi, EDstate->nED));
2774             }
2775             fprintf(stderr, "\n");
2776
2777             /* Now apply the translation and rotation to the atoms on which ED sampling will be performed */
2778             translate_and_rotate(xstart, edi->sav.nr, fit_transvec, fit_rotmat);
2779
2780             /* calculate initial projections */
2781             project(xstart, &(*edi));
2782
2783             /* For the target and origin structure both a reference (fit) and an
2784              * average structure can be provided in make_edi. If both structures
2785              * are the same, make_edi only stores one of them in the .edi file.
2786              * If they differ, first the fit and then the average structure is stored
2787              * in star (or sor), thus the number of entries in star/sor is
2788              * (n_fit + n_av) with n_fit the size of the fitting group and n_av
2789              * the size of the average group. */
2790
2791             /* process target structure, if required */
2792             if (edi->star.nr > 0)
2793             {
2794                 fprintf(stderr, "ED: Fitting target structure to reference structure\n");
2795
2796                 /* get translation & rotation for fit of target structure to reference structure */
2797                 fit_to_reference(edi->star.x, fit_transvec, fit_rotmat, &(*edi));
2798                 /* do the fit */
2799                 translate_and_rotate(edi->star.x, edi->star.nr, fit_transvec, fit_rotmat);
2800                 if (edi->star.nr == edi->sav.nr)
2801                 {
2802                     avindex = 0;
2803                 }
2804                 else /* edi->star.nr = edi->sref.nr + edi->sav.nr */
2805                 {
2806                     /* The last sav.nr indices of the target structure correspond to
2807                      * the average structure, which must be projected */
2808                     avindex = edi->star.nr - edi->sav.nr;
2809                 }
2810                 rad_project(*edi, &edi->star.x[avindex], &edi->vecs.radcon);
2811             }
2812             else
2813             {
2814                 rad_project(*edi, xstart, &edi->vecs.radcon);
2815             }
2816
2817             /* process structure that will serve as origin of expansion circle */
2818             if ( (EssentialDynamicsType::Flooding == ed->eEDtype) && (!edi->flood.bConstForce) )
2819             {
2820                 fprintf(stderr, "ED: Setting center of flooding potential (0 = average structure)\n");
2821             }
2822
2823             if (edi->sori.nr > 0)
2824             {
2825                 fprintf(stderr, "ED: Fitting origin structure to reference structure\n");
2826
2827                 /* fit this structure to reference structure */
2828                 fit_to_reference(edi->sori.x, fit_transvec, fit_rotmat, &(*edi));
2829                 /* do the fit */
2830                 translate_and_rotate(edi->sori.x, edi->sori.nr, fit_transvec, fit_rotmat);
2831                 if (edi->sori.nr == edi->sav.nr)
2832                 {
2833                     avindex = 0;
2834                 }
2835                 else /* edi->sori.nr = edi->sref.nr + edi->sav.nr */
2836                 {
2837                     /* For the projection, we need the last sav.nr indices of sori */
2838                     avindex = edi->sori.nr - edi->sav.nr;
2839                 }
2840
2841                 rad_project(*edi, &edi->sori.x[avindex], &edi->vecs.radacc);
2842                 rad_project(*edi, &edi->sori.x[avindex], &edi->vecs.radfix);
2843                 if ( (EssentialDynamicsType::Flooding == ed->eEDtype) && (!edi->flood.bConstForce) )
2844                 {
2845                     fprintf(stderr, "ED: The ORIGIN structure will define the flooding potential center.\n");
2846                     /* Set center of flooding potential to the ORIGIN structure */
2847                     rad_project(*edi, &edi->sori.x[avindex], &edi->flood.vecs);
2848                     /* We already know that no (moving) reference position was provided,
2849                      * therefore we can overwrite refproj[0]*/
2850                     copyEvecReference(&edi->flood.vecs, edi->flood.initialReferenceProjection);
2851                 }
2852             }
2853             else /* No origin structure given */
2854             {
2855                 rad_project(*edi, xstart, &edi->vecs.radacc);
2856                 rad_project(*edi, xstart, &edi->vecs.radfix);
2857                 if ( (EssentialDynamicsType::Flooding == ed->eEDtype) && (!edi->flood.bConstForce) )
2858                 {
2859                     if (edi->flood.bHarmonic)
2860                     {
2861                         fprintf(stderr, "ED: A (possibly changing) ref. projection will define the flooding potential center.\n");
2862                         for (i = 0; i < edi->flood.vecs.neig; i++)
2863                         {
2864                             edi->flood.vecs.refproj[i] = edi->flood.initialReferenceProjection[i];
2865                         }
2866                     }
2867                     else
2868                     {
2869                         fprintf(stderr, "ED: The AVERAGE structure will define the flooding potential center.\n");
2870                         /* Set center of flooding potential to the center of the covariance matrix,
2871                          * i.e. the average structure, i.e. zero in the projected system */
2872                         for (i = 0; i < edi->flood.vecs.neig; i++)
2873                         {
2874                             edi->flood.vecs.refproj[i] = 0.0;
2875                         }
2876                     }
2877                 }
2878             }
2879             /* For convenience, output the center of the flooding potential for the eigenvectors */
2880             if ( (EssentialDynamicsType::Flooding == ed->eEDtype) && (!edi->flood.bConstForce) )
2881             {
2882                 for (i = 0; i < edi->flood.vecs.neig; i++)
2883                 {
2884                     fprintf(stdout, "ED: EV %d flooding potential center: %11.4e", edi->flood.vecs.ieig[i], edi->flood.vecs.refproj[i]);
2885                     if (edi->flood.bHarmonic)
2886                     {
2887                         fprintf(stdout, " (adding %11.4e/timestep)", edi->flood.referenceProjectionSlope[i]);
2888                     }
2889                     fprintf(stdout, "\n");
2890                 }
2891             }
2892
2893             /* set starting projections for linsam */
2894             rad_project(*edi, xstart, &edi->vecs.linacc);
2895             rad_project(*edi, xstart, &edi->vecs.linfix);
2896
2897             /* Prepare for the next edi data set: */
2898             ++edi;
2899         }
2900         /* Cleaning up on the master node: */
2901         if (!EDstate->bFromCpt)
2902         {
2903             sfree(x_pbc);
2904         }
2905         sfree(xfit);
2906         sfree(xstart);
2907
2908     } /* end of MASTER only section */
2909
2910     if (PAR(cr))
2911     {
2912         /* Broadcast the essential dynamics / flooding data to all nodes */
2913         broadcast_ed_data(cr, ed);
2914     }
2915     else
2916     {
2917         /* In the single-CPU case, point the local atom numbers pointers to the global
2918          * one, so that we can use the same notation in serial and parallel case: */
2919         /* Loop over all ED data sets (usually only one, though) */
2920         for (auto edi = ed->edpar.begin(); edi != ed->edpar.end(); ++edi)
2921         {
2922             edi->sref.anrs_loc = edi->sref.anrs;
2923             edi->sav.anrs_loc  = edi->sav.anrs;
2924             edi->star.anrs_loc = edi->star.anrs;
2925             edi->sori.anrs_loc = edi->sori.anrs;
2926             /* For the same reason as above, make a dummy c_ind array: */
2927             snew(edi->sav.c_ind, edi->sav.nr);
2928             /* Initialize the array */
2929             for (i = 0; i < edi->sav.nr; i++)
2930             {
2931                 edi->sav.c_ind[i] = i;
2932             }
2933             /* In the general case we will need a different-sized array for the reference indices: */
2934             if (!edi->bRefEqAv)
2935             {
2936                 snew(edi->sref.c_ind, edi->sref.nr);
2937                 for (i = 0; i < edi->sref.nr; i++)
2938                 {
2939                     edi->sref.c_ind[i] = i;
2940                 }
2941             }
2942             /* Point to the very same array in case of other structures: */
2943             edi->star.c_ind = edi->sav.c_ind;
2944             edi->sori.c_ind = edi->sav.c_ind;
2945             /* In the serial case, the local number of atoms is the global one: */
2946             edi->sref.nr_loc = edi->sref.nr;
2947             edi->sav.nr_loc  = edi->sav.nr;
2948             edi->star.nr_loc = edi->star.nr;
2949             edi->sori.nr_loc = edi->sori.nr;
2950         }
2951     }
2952
2953     /* Allocate space for ED buffer variables */
2954     /* Again, loop over ED data sets */
2955     for (auto edi = ed->edpar.begin(); edi != ed->edpar.end(); ++edi)
2956     {
2957         /* Allocate space for ED buffer variables */
2958         snew_bc(cr, edi->buf, 1); /* MASTER has already allocated edi->buf in init_edi() */
2959         snew(edi->buf->do_edsam, 1);
2960
2961         /* Space for collective ED buffer variables */
2962
2963         /* Collective positions of atoms with the average indices */
2964         snew(edi->buf->do_edsam->xcoll, edi->sav.nr);
2965         snew(edi->buf->do_edsam->shifts_xcoll, edi->sav.nr);            /* buffer for xcoll shifts */
2966         snew(edi->buf->do_edsam->extra_shifts_xcoll, edi->sav.nr);
2967         /* Collective positions of atoms with the reference indices */
2968         if (!edi->bRefEqAv)
2969         {
2970             snew(edi->buf->do_edsam->xc_ref, edi->sref.nr);
2971             snew(edi->buf->do_edsam->shifts_xc_ref, edi->sref.nr);       /* To store the shifts in */
2972             snew(edi->buf->do_edsam->extra_shifts_xc_ref, edi->sref.nr);
2973         }
2974
2975         /* Get memory for flooding forces */
2976         snew(edi->flood.forces_cartesian, edi->sav.nr);
2977     }
2978
2979     /* Flush the edo file so that the user can check some things
2980      * when the simulation has started */
2981     if (ed->edo)
2982     {
2983         fflush(ed->edo);
2984     }
2985
2986     return edHandle;
2987 }
2988
2989
2990 void do_edsam(const t_inputrec *ir,
2991               int64_t           step,
2992               const t_commrec  *cr,
2993               rvec              xs[],
2994               rvec              v[],
2995               matrix            box,
2996               gmx_edsam        *ed)
2997 {
2998     int                i, edinr, iupdate = 500;
2999     matrix             rotmat;            /* rotation matrix */
3000     rvec               transvec;          /* translation vector */
3001     rvec               dv, dx, x_unsh;    /* tmp vectors for velocity, distance, unshifted x coordinate */
3002     real               dt_1;              /* 1/dt */
3003     struct t_do_edsam *buf;
3004     real               rmsdev    = -1;    /* RMSD from reference structure prior to applying the constraints */
3005     gmx_bool           bSuppress = FALSE; /* Write .xvg output file on master? */
3006
3007
3008     /* Check if ED sampling has to be performed */
3009     if (ed->eEDtype == EssentialDynamicsType::None)
3010     {
3011         return;
3012     }
3013
3014     dt_1 = 1.0/ir->delta_t;
3015
3016     /* Loop over all ED groups (usually one) */
3017     edinr = 0;
3018     for (auto &edi : ed->edpar)
3019     {
3020         edinr++;
3021         if (bNeedDoEdsam(edi))
3022         {
3023
3024             buf = edi.buf->do_edsam;
3025
3026             if (ed->bFirst)
3027             {
3028                 /* initialize radacc radius for slope criterion */
3029                 buf->oldrad = calc_radius(edi.vecs.radacc);
3030             }
3031
3032             /* Copy the positions into buf->xc* arrays and after ED
3033              * feed back corrections to the official positions */
3034
3035             /* Broadcast the ED positions such that every node has all of them
3036              * Every node contributes its local positions xs and stores it in
3037              * the collective buf->xcoll array. Note that for edinr > 1
3038              * xs could already have been modified by an earlier ED */
3039
3040             communicate_group_positions(cr, buf->xcoll, buf->shifts_xcoll, buf->extra_shifts_xcoll, PAR(cr) ? buf->bUpdateShifts : TRUE, xs,
3041                                         edi.sav.nr, edi.sav.nr_loc, edi.sav.anrs_loc, edi.sav.c_ind, edi.sav.x_old,  box);
3042
3043             /* Only assembly reference positions if their indices differ from the average ones */
3044             if (!edi.bRefEqAv)
3045             {
3046                 communicate_group_positions(cr, buf->xc_ref, buf->shifts_xc_ref, buf->extra_shifts_xc_ref, PAR(cr) ? buf->bUpdateShifts : TRUE, xs,
3047                                             edi.sref.nr, edi.sref.nr_loc, edi.sref.anrs_loc, edi.sref.c_ind, edi.sref.x_old, box);
3048             }
3049
3050             /* If bUpdateShifts was TRUE then the shifts have just been updated in communicate_group_positions.
3051              * We do not need to update the shifts until the next NS step. Note that dd_make_local_ed_indices
3052              * set bUpdateShifts=TRUE in the parallel case. */
3053             buf->bUpdateShifts = FALSE;
3054
3055             /* Now all nodes have all of the ED positions in edi.sav->xcoll,
3056              * as well as the indices in edi.sav.anrs */
3057
3058             /* Fit the reference indices to the reference structure */
3059             if (edi.bRefEqAv)
3060             {
3061                 fit_to_reference(buf->xcoll, transvec, rotmat, &edi);
3062             }
3063             else
3064             {
3065                 fit_to_reference(buf->xc_ref, transvec, rotmat, &edi);
3066             }
3067
3068             /* Now apply the translation and rotation to the ED structure */
3069             translate_and_rotate(buf->xcoll, edi.sav.nr, transvec, rotmat);
3070
3071             /* Find out how well we fit to the reference (just for output steps) */
3072             if (do_per_step(step, edi.outfrq) && MASTER(cr))
3073             {
3074                 if (edi.bRefEqAv)
3075                 {
3076                     /* Indices of reference and average structures are identical,
3077                      * thus we can calculate the rmsd to SREF using xcoll */
3078                     rmsdev = rmsd_from_structure(buf->xcoll, &edi.sref);
3079                 }
3080                 else
3081                 {
3082                     /* We have to translate & rotate the reference atoms first */
3083                     translate_and_rotate(buf->xc_ref, edi.sref.nr, transvec, rotmat);
3084                     rmsdev = rmsd_from_structure(buf->xc_ref, &edi.sref);
3085                 }
3086             }
3087
3088             /* update radsam references, when required */
3089             if (do_per_step(step, edi.maxedsteps) && step >= edi.presteps)
3090             {
3091                 project(buf->xcoll, &edi);
3092                 rad_project(edi, buf->xcoll, &edi.vecs.radacc);
3093                 rad_project(edi, buf->xcoll, &edi.vecs.radfix);
3094                 buf->oldrad = -1.e5;
3095             }
3096
3097             /* update radacc references, when required */
3098             if (do_per_step(step, iupdate) && step >= edi.presteps)
3099             {
3100                 edi.vecs.radacc.radius = calc_radius(edi.vecs.radacc);
3101                 if (edi.vecs.radacc.radius - buf->oldrad < edi.slope)
3102                 {
3103                     project(buf->xcoll, &edi);
3104                     rad_project(edi, buf->xcoll, &edi.vecs.radacc);
3105                     buf->oldrad = 0.0;
3106                 }
3107                 else
3108                 {
3109                     buf->oldrad = edi.vecs.radacc.radius;
3110                 }
3111             }
3112
3113             /* apply the constraints */
3114             if (step >= edi.presteps && ed_constraints(ed->eEDtype, edi))
3115             {
3116                 /* ED constraints should be applied already in the first MD step
3117                  * (which is step 0), therefore we pass step+1 to the routine */
3118                 ed_apply_constraints(buf->xcoll, &edi, step+1 - ir->init_step);
3119             }
3120
3121             /* write to edo, when required */
3122             if (do_per_step(step, edi.outfrq))
3123             {
3124                 project(buf->xcoll, &edi);
3125                 if (MASTER(cr) && !bSuppress)
3126                 {
3127                     write_edo(edi, ed->edo, rmsdev);
3128                 }
3129             }
3130
3131             /* Copy back the positions unless monitoring only */
3132             if (ed_constraints(ed->eEDtype, edi))
3133             {
3134                 /* remove fitting */
3135                 rmfit(edi.sav.nr, buf->xcoll, transvec, rotmat);
3136
3137                 /* Copy the ED corrected positions into the coordinate array */
3138                 /* Each node copies its local part. In the serial case, nat_loc is the
3139                  * total number of ED atoms */
3140                 for (i = 0; i < edi.sav.nr_loc; i++)
3141                 {
3142                     /* Unshift local ED coordinate and store in x_unsh */
3143                     ed_unshift_single_coord(box, buf->xcoll[edi.sav.c_ind[i]],
3144                                             buf->shifts_xcoll[edi.sav.c_ind[i]], x_unsh);
3145
3146                     /* dx is the ED correction to the positions: */
3147                     rvec_sub(x_unsh, xs[edi.sav.anrs_loc[i]], dx);
3148
3149                     if (v != nullptr)
3150                     {
3151                         /* dv is the ED correction to the velocity: */
3152                         svmul(dt_1, dx, dv);
3153                         /* apply the velocity correction: */
3154                         rvec_inc(v[edi.sav.anrs_loc[i]], dv);
3155                     }
3156                     /* Finally apply the position correction due to ED: */
3157                     copy_rvec(x_unsh, xs[edi.sav.anrs_loc[i]]);
3158                 }
3159             }
3160         } /* END of if ( bNeedDoEdsam(edi) ) */
3161
3162         /* Prepare for the next ED group */
3163
3164     } /* END of loop over ED groups */
3165
3166     ed->bFirst = FALSE;
3167 }