c0d009cc1a2f749b10e69f6315fa9f81dbb27eeb
[alexxy/gromacs.git] / src / gromacs / pulling / pull_rotation.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-2008, 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 "pull_rotation.h"
40
41 #include "config.h"
42
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include <algorithm>
48
49 #include "gromacs/commandline/filenm.h"
50 #include "gromacs/compat/make_unique.h"
51 #include "gromacs/domdec/dlbtiming.h"
52 #include "gromacs/domdec/domdec_struct.h"
53 #include "gromacs/domdec/ga2la.h"
54 #include "gromacs/domdec/localatomset.h"
55 #include "gromacs/domdec/localatomsetmanager.h"
56 #include "gromacs/fileio/gmxfio.h"
57 #include "gromacs/fileio/xvgr.h"
58 #include "gromacs/gmxlib/network.h"
59 #include "gromacs/linearalgebra/nrjac.h"
60 #include "gromacs/math/functions.h"
61 #include "gromacs/math/utilities.h"
62 #include "gromacs/math/vec.h"
63 #include "gromacs/mdlib/groupcoord.h"
64 #include "gromacs/mdlib/mdrun.h"
65 #include "gromacs/mdlib/sim_util.h"
66 #include "gromacs/mdtypes/commrec.h"
67 #include "gromacs/mdtypes/inputrec.h"
68 #include "gromacs/mdtypes/md_enums.h"
69 #include "gromacs/mdtypes/state.h"
70 #include "gromacs/pbcutil/pbc.h"
71 #include "gromacs/timing/cyclecounter.h"
72 #include "gromacs/timing/wallcycle.h"
73 #include "gromacs/topology/mtop_lookup.h"
74 #include "gromacs/topology/mtop_util.h"
75 #include "gromacs/utility/basedefinitions.h"
76 #include "gromacs/utility/fatalerror.h"
77 #include "gromacs/utility/pleasecite.h"
78 #include "gromacs/utility/qsort_threadsafe.h"
79 #include "gromacs/utility/smalloc.h"
80
81 static char const *RotStr = {"Enforced rotation:"};
82
83 /* Set the minimum weight for the determination of the slab centers */
84 #define WEIGHT_MIN (10*GMX_FLOAT_MIN)
85
86 //! Helper structure for sorting positions along rotation vector
87 struct sort_along_vec_t
88 {
89     //! Projection of xc on the rotation vector
90     real xcproj;
91     //! Index of xc
92     int  ind;
93     //! Mass
94     real m;
95     //! Position
96     rvec x;
97     //! Reference position
98     rvec x_ref;
99 };
100
101
102 //! Enforced rotation / flexible: determine the angle of each slab
103 struct gmx_slabdata
104 {
105     //! Number of atoms belonging to this slab
106     int   nat;
107     /*! \brief The positions belonging to this slab.
108      *
109      * In general, this should be all positions of the whole
110      * rotation group, but we leave those away that have a small
111      * enough weight. */
112     rvec *x;
113     //! Same for reference
114     rvec *ref;
115     //! The weight for each atom
116     real *weight;
117 };
118
119
120 //! Helper structure for potential fitting
121 struct gmx_potfit
122 {
123     /*! \brief Set of angles for which the potential is calculated.
124      *
125      * The optimum fit is determined as the angle for with the
126      * potential is minimal. */
127     real   *degangle;
128     //! Potential for the different angles
129     real   *V;
130     //! Rotation matrix corresponding to the angles
131     matrix *rotmat;
132 };
133
134
135 //! Enforced rotation data for a single rotation group
136 struct gmx_enfrotgrp
137 {
138     //! Input parameters for this group
139     const t_rotgrp                    *rotg = nullptr;
140     //! Index of this group within the set of groups
141     int                                groupIndex;
142     //! Rotation angle in degrees
143     real                               degangle;
144     //! Rotation matrix
145     matrix                             rotmat;
146     //! The atoms subject to enforced rotation
147     std::unique_ptr<gmx::LocalAtomSet> atomSet;
148
149     //! The normalized rotation vector
150     rvec  vec;
151     //! Rotation potential for this rotation group
152     real  V;
153     //! Array to store the forces on the local atoms resulting from enforced rotation potential
154     rvec *f_rot_loc;
155
156     /* Collective coordinates for the whole rotation group */
157     //! Length of each x_rotref vector after x_rotref has been put into origin
158     real  *xc_ref_length;
159     //! Center of the rotation group positions, may be mass weighted
160     rvec   xc_center;
161     //! Center of the rotation group reference positions
162     rvec   xc_ref_center;
163     //! Current (collective) positions
164     rvec  *xc;
165     //! Current (collective) shifts
166     ivec  *xc_shifts;
167     //! Extra shifts since last DD step
168     ivec  *xc_eshifts;
169     //! Old (collective) positions
170     rvec  *xc_old;
171     //! Normalized form of the current positions
172     rvec  *xc_norm;
173     //! Reference positions (sorted in the same order as xc when sorted)
174     rvec  *xc_ref_sorted;
175     //! Where is a position found after sorting?
176     int   *xc_sortind;
177     //! Collective masses
178     real  *mc;
179     //! Collective masses sorted
180     real  *mc_sorted;
181     //! one over the total mass of the rotation group
182     real   invmass;
183
184     //! Torque in the direction of rotation vector
185     real torque_v;
186     //! Actual angle of the whole rotation group
187     real angle_v;
188     /* Fixed rotation only */
189     //! Weights for angle determination
190     real  weight_v;
191     //! Local reference coords, correctly rotated
192     rvec *xr_loc;
193     //! Local current coords, correct PBC image
194     rvec *x_loc_pbc;
195     //! Masses of the current local atoms
196     real *m_loc;
197
198     /* Flexible rotation only */
199     //! For this many slabs memory is allocated
200     int             nslabs_alloc;
201     //! Lowermost slab for that the calculation needs to be performed at a given time step
202     int             slab_first;
203     //! Uppermost slab ...
204     int             slab_last;
205     //! First slab for which ref. center is stored
206     int             slab_first_ref;
207     //! Last ...
208     int             slab_last_ref;
209     //! Slab buffer region around reference slabs
210     int             slab_buffer;
211     //! First relevant atom for a slab
212     int            *firstatom;
213     //! Last relevant atom for a slab
214     int            *lastatom;
215     //! Gaussian-weighted slab center
216     rvec           *slab_center;
217     //! Gaussian-weighted slab center for the reference positions
218     rvec           *slab_center_ref;
219     //! Sum of gaussian weights in a slab
220     real           *slab_weights;
221     //! Torque T = r x f for each slab. torque_v = m.v = angular momentum in the direction of v
222     real           *slab_torque_v;
223     //! min_gaussian from t_rotgrp is the minimum value the gaussian must have so that the force is actually evaluated. max_beta is just another way to put it
224     real            max_beta;
225     //! Precalculated gaussians for a single atom
226     real           *gn_atom;
227     //! Tells to which slab each precalculated gaussian belongs
228     int            *gn_slabind;
229     //! Inner sum of the flexible2 potential per slab; this is precalculated for optimization reasons
230     rvec           *slab_innersumvec;
231     //! Holds atom positions and gaussian weights of atoms belonging to a slab
232     gmx_slabdata   *slab_data;
233
234     /* For potential fits with varying angle: */
235     //! Used for fit type 'potential'
236     gmx_potfit *PotAngleFit;
237 };
238
239
240 //! Enforced rotation data for all groups
241 struct gmx_enfrot
242 {
243     //! Input parameters.
244     const t_rot               *rot = nullptr;
245     //! Output period for main rotation outfile
246     int                        nstrout;
247     //! Output period for per-slab data
248     int                        nstsout;
249     //! Output file for rotation data
250     FILE                      *out_rot = nullptr;
251     //! Output file for torque data
252     FILE                      *out_torque = nullptr;
253     //! Output file for slab angles for flexible type
254     FILE                      *out_angles = nullptr;
255     //! Output file for slab centers
256     FILE                      *out_slabs = nullptr;
257     //! Allocation size of buf
258     int                        bufsize = 0;
259     //! Coordinate buffer variable for sorting
260     rvec                      *xbuf = nullptr;
261     //! Masses buffer variable for sorting
262     real                      *mbuf = nullptr;
263     //! Buffer variable needed for position sorting
264     sort_along_vec_t          *data = nullptr;
265     //! MPI buffer
266     real                      *mpi_inbuf = nullptr;
267     //! MPI buffer
268     real                      *mpi_outbuf = nullptr;
269     //! Allocation size of in & outbuf
270     int                        mpi_bufsize = 0;
271     //! If true, append output files
272     gmx_bool                   appendFiles = false;
273     //! Used to skip first output when appending to avoid duplicate entries in rotation outfiles
274     gmx_bool                   bOut = false;
275     //! Stores working data per group
276     std::vector<gmx_enfrotgrp> enfrotgrp;
277     ~gmx_enfrot();
278 };
279
280 gmx_enfrot::~gmx_enfrot()
281 {
282     if (out_rot)
283     {
284         gmx_fio_fclose(out_rot);
285     }
286     if (out_slabs)
287     {
288         gmx_fio_fclose(out_slabs);
289     }
290     if (out_angles)
291     {
292         gmx_fio_fclose(out_angles);
293     }
294     if (out_torque)
295     {
296         gmx_fio_fclose(out_torque);
297     }
298 }
299
300 namespace gmx
301 {
302
303 class EnforcedRotation::Impl
304 {
305     public:
306         gmx_enfrot enforcedRotation_;
307 };
308
309 EnforcedRotation::EnforcedRotation() : impl_(new Impl)
310 {
311 }
312
313 EnforcedRotation::~EnforcedRotation() = default;
314
315 gmx_enfrot *EnforcedRotation::getLegacyEnfrot()
316 {
317     return &impl_->enforcedRotation_;
318 }
319
320 } // namespace
321
322 /* Activate output of forces for correctness checks */
323 /* #define PRINT_FORCES */
324 #ifdef PRINT_FORCES
325 #define PRINT_FORCE_J  fprintf(stderr, "f%d = %15.8f %15.8f %15.8f\n", erg->xc_ref_ind[j], erg->f_rot_loc[j][XX], erg->f_rot_loc[j][YY], erg->f_rot_loc[j][ZZ]);
326 #define PRINT_POT_TAU  if (MASTER(cr)) { \
327         fprintf(stderr, "potential = %15.8f\n" "torque    = %15.8f\n", erg->V, erg->torque_v); \
328 }
329 #else
330 #define PRINT_FORCE_J
331 #define PRINT_POT_TAU
332 #endif
333
334 /* Shortcuts for often used queries */
335 #define ISFLEX(rg) ( ((rg)->eType == erotgFLEX) || ((rg)->eType == erotgFLEXT) || ((rg)->eType == erotgFLEX2) || ((rg)->eType == erotgFLEX2T) )
336 #define ISCOLL(rg) ( ((rg)->eType == erotgFLEX) || ((rg)->eType == erotgFLEXT) || ((rg)->eType == erotgFLEX2) || ((rg)->eType == erotgFLEX2T) || ((rg)->eType == erotgRMPF) || ((rg)->eType == erotgRM2PF) )
337
338
339 /* Does any of the rotation groups use slab decomposition? */
340 static gmx_bool HaveFlexibleGroups(const t_rot *rot)
341 {
342     for (int g = 0; g < rot->ngrp; g++)
343     {
344         if (ISFLEX(&rot->grp[g]))
345         {
346             return TRUE;
347         }
348     }
349
350     return FALSE;
351 }
352
353
354 /* Is for any group the fit angle determined by finding the minimum of the
355  * rotation potential? */
356 static gmx_bool HavePotFitGroups(const t_rot *rot)
357 {
358     for (int g = 0; g < rot->ngrp; g++)
359     {
360         if (erotgFitPOT == rot->grp[g].eFittype)
361         {
362             return TRUE;
363         }
364     }
365
366     return FALSE;
367 }
368
369
370 static double** allocate_square_matrix(int dim)
371 {
372     int      i;
373     double** mat = nullptr;
374
375
376     snew(mat, dim);
377     for (i = 0; i < dim; i++)
378     {
379         snew(mat[i], dim);
380     }
381
382     return mat;
383 }
384
385
386 static void free_square_matrix(double** mat, int dim)
387 {
388     int i;
389
390
391     for (i = 0; i < dim; i++)
392     {
393         sfree(mat[i]);
394     }
395     sfree(mat);
396 }
397
398
399 /* Return the angle for which the potential is minimal */
400 static real get_fitangle(const gmx_enfrotgrp *erg)
401 {
402     int           i;
403     real          fitangle = -999.9;
404     real          pot_min  = GMX_FLOAT_MAX;
405     gmx_potfit   *fit;
406
407
408     fit = erg->PotAngleFit;
409
410     for (i = 0; i < erg->rotg->PotAngle_nstep; i++)
411     {
412         if (fit->V[i] < pot_min)
413         {
414             pot_min  = fit->V[i];
415             fitangle = fit->degangle[i];
416         }
417     }
418
419     return fitangle;
420 }
421
422
423 /* Reduce potential angle fit data for this group at this time step? */
424 static inline gmx_bool bPotAngle(const gmx_enfrot *er, const t_rotgrp *rotg, int64_t step)
425 {
426     return ( (erotgFitPOT == rotg->eFittype) && (do_per_step(step, er->nstsout) || do_per_step(step, er->nstrout)) );
427 }
428
429 /* Reduce slab torqe data for this group at this time step? */
430 static inline gmx_bool bSlabTau(const gmx_enfrot *er, const t_rotgrp *rotg, int64_t step)
431 {
432     return ( (ISFLEX(rotg)) && do_per_step(step, er->nstsout) );
433 }
434
435 /* Output rotation energy, torques, etc. for each rotation group */
436 static void reduce_output(const t_commrec *cr,
437                           gmx_enfrot *er, real t, int64_t step)
438 {
439     int             i, islab, nslabs = 0;
440     int             count; /* MPI element counter                               */
441     real            fitangle;
442     gmx_bool        bFlex;
443
444     /* Fill the MPI buffer with stuff to reduce. If items are added for reduction
445      * here, the MPI buffer size has to be enlarged also in calc_mpi_bufsize() */
446     if (PAR(cr))
447     {
448         count = 0;
449         for (auto &ergRef : er->enfrotgrp)
450         {
451             gmx_enfrotgrp  *erg  = &ergRef;
452             const t_rotgrp *rotg = erg->rotg;
453             nslabs                 = erg->slab_last - erg->slab_first + 1;
454             er->mpi_inbuf[count++] = erg->V;
455             er->mpi_inbuf[count++] = erg->torque_v;
456             er->mpi_inbuf[count++] = erg->angle_v;
457             er->mpi_inbuf[count++] = erg->weight_v; /* weights are not needed for flex types, but this is just a single value */
458
459             if (bPotAngle(er, rotg, step))
460             {
461                 for (i = 0; i < rotg->PotAngle_nstep; i++)
462                 {
463                     er->mpi_inbuf[count++] = erg->PotAngleFit->V[i];
464                 }
465             }
466             if (bSlabTau(er, rotg, step))
467             {
468                 for (i = 0; i < nslabs; i++)
469                 {
470                     er->mpi_inbuf[count++] = erg->slab_torque_v[i];
471                 }
472             }
473         }
474         if (count > er->mpi_bufsize)
475         {
476             gmx_fatal(FARGS, "%s MPI buffer overflow, please report this error.", RotStr);
477         }
478
479 #if GMX_MPI
480         MPI_Reduce(er->mpi_inbuf, er->mpi_outbuf, count, GMX_MPI_REAL, MPI_SUM, MASTERRANK(cr), cr->mpi_comm_mygroup);
481 #endif
482
483         /* Copy back the reduced data from the buffer on the master */
484         if (MASTER(cr))
485         {
486             count = 0;
487             for (auto &ergRef : er->enfrotgrp)
488             {
489                 gmx_enfrotgrp  *erg  = &ergRef;
490                 const t_rotgrp *rotg = erg->rotg;
491                 nslabs        = erg->slab_last - erg->slab_first + 1;
492                 erg->V        = er->mpi_outbuf[count++];
493                 erg->torque_v = er->mpi_outbuf[count++];
494                 erg->angle_v  = er->mpi_outbuf[count++];
495                 erg->weight_v = er->mpi_outbuf[count++];
496
497                 if (bPotAngle(er, rotg, step))
498                 {
499                     for (int i = 0; i < rotg->PotAngle_nstep; i++)
500                     {
501                         erg->PotAngleFit->V[i] = er->mpi_outbuf[count++];
502                     }
503                 }
504                 if (bSlabTau(er, rotg, step))
505                 {
506                     for (int i = 0; i < nslabs; i++)
507                     {
508                         erg->slab_torque_v[i] = er->mpi_outbuf[count++];
509                     }
510                 }
511             }
512         }
513     }
514
515     /* Output */
516     if (MASTER(cr))
517     {
518         /* Angle and torque for each rotation group */
519         for (auto &ergRef : er->enfrotgrp)
520         {
521             gmx_enfrotgrp  *erg  = &ergRef;
522             const t_rotgrp *rotg = erg->rotg;
523             bFlex = ISFLEX(rotg);
524
525             /* Output to main rotation output file: */
526             if (do_per_step(step, er->nstrout) )
527             {
528                 if (erotgFitPOT == rotg->eFittype)
529                 {
530                     fitangle = get_fitangle(erg);
531                 }
532                 else
533                 {
534                     if (bFlex)
535                     {
536                         fitangle = erg->angle_v; /* RMSD fit angle */
537                     }
538                     else
539                     {
540                         fitangle = (erg->angle_v/erg->weight_v)*180.0*M_1_PI;
541                     }
542                 }
543                 fprintf(er->out_rot, "%12.4f", fitangle);
544                 fprintf(er->out_rot, "%12.3e", erg->torque_v);
545                 fprintf(er->out_rot, "%12.3e", erg->V);
546             }
547
548             if (do_per_step(step, er->nstsout) )
549             {
550                 /* Output to torque log file: */
551                 if (bFlex)
552                 {
553                     fprintf(er->out_torque, "%12.3e%6d", t, erg->groupIndex);
554                     for (int i = erg->slab_first; i <= erg->slab_last; i++)
555                     {
556                         islab = i - erg->slab_first;  /* slab index */
557                         /* Only output if enough weight is in slab */
558                         if (erg->slab_weights[islab] > rotg->min_gaussian)
559                         {
560                             fprintf(er->out_torque, "%6d%12.3e", i, erg->slab_torque_v[islab]);
561                         }
562                     }
563                     fprintf(er->out_torque, "\n");
564                 }
565
566                 /* Output to angles log file: */
567                 if (erotgFitPOT == rotg->eFittype)
568                 {
569                     fprintf(er->out_angles, "%12.3e%6d%12.4f", t, erg->groupIndex, erg->degangle);
570                     /* Output energies at a set of angles around the reference angle */
571                     for (int i = 0; i < rotg->PotAngle_nstep; i++)
572                     {
573                         fprintf(er->out_angles, "%12.3e", erg->PotAngleFit->V[i]);
574                     }
575                     fprintf(er->out_angles, "\n");
576                 }
577             }
578         }
579         if (do_per_step(step, er->nstrout) )
580         {
581             fprintf(er->out_rot, "\n");
582         }
583     }
584 }
585
586
587 /* Add the forces from enforced rotation potential to the local forces.
588  * Should be called after the SR forces have been evaluated */
589 real add_rot_forces(gmx_enfrot *er,
590                     rvec f[], const t_commrec *cr, int64_t step, real t)
591 {
592     real            Vrot = 0.0; /* If more than one rotation group is present, Vrot
593                                    assembles the local parts from all groups         */
594
595     /* Loop over enforced rotation groups (usually 1, though)
596      * Apply the forces from rotation potentials */
597     for (auto &ergRef : er->enfrotgrp)
598     {
599         gmx_enfrotgrp *erg = &ergRef;
600         Vrot += erg->V;  /* add the local parts from the nodes */
601         const auto    &localRotationGroupIndex = erg->atomSet->localIndex();
602         for (gmx::index l = 0; l < localRotationGroupIndex.size(); l++)
603         {
604             /* Get the right index of the local force */
605             int ii = localRotationGroupIndex[l];
606             /* Add */
607             rvec_inc(f[ii], erg->f_rot_loc[l]);
608         }
609     }
610
611     /* Reduce energy,torque, angles etc. to get the sum values (per rotation group)
612      * on the master and output these values to file. */
613     if ( (do_per_step(step, er->nstrout) || do_per_step(step, er->nstsout)) && er->bOut)
614     {
615         reduce_output(cr, er, t, step);
616     }
617
618     /* When appending, er->bOut is FALSE the first time to avoid duplicate entries */
619     er->bOut = TRUE;
620
621     PRINT_POT_TAU
622
623     return Vrot;
624 }
625
626
627 /* The Gaussian norm is chosen such that the sum of the gaussian functions
628  * over the slabs is approximately 1.0 everywhere */
629 #define GAUSS_NORM   0.569917543430618
630
631
632 /* Calculate the maximum beta that leads to a gaussian larger min_gaussian,
633  * also does some checks
634  */
635 static double calc_beta_max(real min_gaussian, real slab_dist)
636 {
637     double sigma;
638     double arg;
639
640
641     /* Actually the next two checks are already made in grompp */
642     if (slab_dist <= 0)
643     {
644         gmx_fatal(FARGS, "Slab distance of flexible rotation groups must be >=0 !");
645     }
646     if (min_gaussian <= 0)
647     {
648         gmx_fatal(FARGS, "Cutoff value for Gaussian must be > 0. (You requested %f)");
649     }
650
651     /* Define the sigma value */
652     sigma = 0.7*slab_dist;
653
654     /* Calculate the argument for the logarithm and check that the log() result is negative or 0 */
655     arg = min_gaussian/GAUSS_NORM;
656     if (arg > 1.0)
657     {
658         gmx_fatal(FARGS, "min_gaussian of flexible rotation groups must be <%g", GAUSS_NORM);
659     }
660
661     return std::sqrt(-2.0*sigma*sigma*log(min_gaussian/GAUSS_NORM));
662 }
663
664
665 static inline real calc_beta(rvec curr_x, const gmx_enfrotgrp *erg, int n)
666 {
667     return iprod(curr_x, erg->vec) - erg->rotg->slab_dist * n;
668 }
669
670
671 static inline real gaussian_weight(rvec curr_x, const gmx_enfrotgrp *erg, int n)
672 {
673     const real norm = GAUSS_NORM;
674     real       sigma;
675
676
677     /* Define the sigma value */
678     sigma = 0.7*erg->rotg->slab_dist;
679     /* Calculate the Gaussian value of slab n for position curr_x */
680     return norm * exp( -0.5 * gmx::square( calc_beta(curr_x, erg, n)/sigma ) );
681 }
682
683
684 /* Returns the weight in a single slab, also calculates the Gaussian- and mass-
685  * weighted sum of positions for that slab */
686 static real get_slab_weight(int j, const gmx_enfrotgrp *erg,
687                             rvec xc[], const real mc[], rvec *x_weighted_sum)
688 {
689     rvec            curr_x;           /* The position of an atom                      */
690     rvec            curr_x_weighted;  /* The gaussian-weighted position               */
691     real            gaussian;         /* A single gaussian weight                     */
692     real            wgauss;           /* gaussian times current mass                  */
693     real            slabweight = 0.0; /* The sum of weights in the slab               */
694
695     clear_rvec(*x_weighted_sum);
696
697     /* Loop over all atoms in the rotation group */
698     for (int i = 0; i < erg->rotg->nat; i++)
699     {
700         copy_rvec(xc[i], curr_x);
701         gaussian = gaussian_weight(curr_x, erg, j);
702         wgauss   = gaussian * mc[i];
703         svmul(wgauss, curr_x, curr_x_weighted);
704         rvec_add(*x_weighted_sum, curr_x_weighted, *x_weighted_sum);
705         slabweight += wgauss;
706     }  /* END of loop over rotation group atoms */
707
708     return slabweight;
709 }
710
711
712 static void get_slab_centers(
713         gmx_enfrotgrp *erg,        /* Enforced rotation group working data */
714         rvec          *xc,         /* The rotation group positions; will
715                                       typically be enfrotgrp->xc, but at first call
716                                       it is enfrotgrp->xc_ref                      */
717         real          *mc,         /* The masses of the rotation group atoms       */
718         real           time,       /* Used for output only                         */
719         FILE          *out_slabs,  /* For outputting center per slab information   */
720         gmx_bool       bOutStep,   /* Is this an output step?                      */
721         gmx_bool       bReference) /* If this routine is called from
722                                       init_rot_group we need to store
723                                       the reference slab centers                   */
724 {
725     /* Loop over slabs */
726     for (int j = erg->slab_first; j <= erg->slab_last; j++)
727     {
728         int slabIndex    = j - erg->slab_first;
729         erg->slab_weights[slabIndex] = get_slab_weight(j, erg, xc, mc, &erg->slab_center[slabIndex]);
730
731         /* We can do the calculations ONLY if there is weight in the slab! */
732         if (erg->slab_weights[slabIndex] > WEIGHT_MIN)
733         {
734             svmul(1.0/erg->slab_weights[slabIndex], erg->slab_center[slabIndex], erg->slab_center[slabIndex]);
735         }
736         else
737         {
738             /* We need to check this here, since we divide through slab_weights
739              * in the flexible low-level routines! */
740             gmx_fatal(FARGS, "Not enough weight in slab %d. Slab center cannot be determined!", j);
741         }
742
743         /* At first time step: save the centers of the reference structure */
744         if (bReference)
745         {
746             copy_rvec(erg->slab_center[slabIndex], erg->slab_center_ref[slabIndex]);
747         }
748     } /* END of loop over slabs */
749
750     /* Output on the master */
751     if ( (nullptr != out_slabs) && bOutStep)
752     {
753         fprintf(out_slabs, "%12.3e%6d", time, erg->groupIndex);
754         for (int j = erg->slab_first; j <= erg->slab_last; j++)
755         {
756             int slabIndex = j - erg->slab_first;
757             fprintf(out_slabs, "%6d%12.3e%12.3e%12.3e",
758                     j, erg->slab_center[slabIndex][XX], erg->slab_center[slabIndex][YY], erg->slab_center[slabIndex][ZZ]);
759         }
760         fprintf(out_slabs, "\n");
761     }
762 }
763
764
765 static void calc_rotmat(
766         const rvec vec,
767         real       degangle,  /* Angle alpha of rotation at time t in degrees       */
768         matrix     rotmat)    /* Rotation matrix                                    */
769 {
770     real radangle;            /* Rotation angle in radians */
771     real cosa;                /* cosine alpha              */
772     real sina;                /* sine alpha                */
773     real OMcosa;              /* 1 - cos(alpha)            */
774     real dumxy, dumxz, dumyz; /* save computations         */
775     rvec rot_vec;             /* Rotate around rot_vec ... */
776
777
778     radangle = degangle * M_PI/180.0;
779     copy_rvec(vec, rot_vec );
780
781     /* Precompute some variables: */
782     cosa   = cos(radangle);
783     sina   = sin(radangle);
784     OMcosa = 1.0 - cosa;
785     dumxy  = rot_vec[XX]*rot_vec[YY]*OMcosa;
786     dumxz  = rot_vec[XX]*rot_vec[ZZ]*OMcosa;
787     dumyz  = rot_vec[YY]*rot_vec[ZZ]*OMcosa;
788
789     /* Construct the rotation matrix for this rotation group: */
790     /* 1st column: */
791     rotmat[XX][XX] = cosa  + rot_vec[XX]*rot_vec[XX]*OMcosa;
792     rotmat[YY][XX] = dumxy + rot_vec[ZZ]*sina;
793     rotmat[ZZ][XX] = dumxz - rot_vec[YY]*sina;
794     /* 2nd column: */
795     rotmat[XX][YY] = dumxy - rot_vec[ZZ]*sina;
796     rotmat[YY][YY] = cosa  + rot_vec[YY]*rot_vec[YY]*OMcosa;
797     rotmat[ZZ][YY] = dumyz + rot_vec[XX]*sina;
798     /* 3rd column: */
799     rotmat[XX][ZZ] = dumxz + rot_vec[YY]*sina;
800     rotmat[YY][ZZ] = dumyz - rot_vec[XX]*sina;
801     rotmat[ZZ][ZZ] = cosa  + rot_vec[ZZ]*rot_vec[ZZ]*OMcosa;
802
803 #ifdef PRINTMATRIX
804     int iii, jjj;
805
806     for (iii = 0; iii < 3; iii++)
807     {
808         for (jjj = 0; jjj < 3; jjj++)
809         {
810             fprintf(stderr, " %10.8f ",  rotmat[iii][jjj]);
811         }
812         fprintf(stderr, "\n");
813     }
814 #endif
815 }
816
817
818 /* Calculates torque on the rotation axis tau = position x force */
819 static inline real torque(const rvec rotvec, /* rotation vector; MUST be normalized!          */
820                           rvec       force,  /* force                                                */
821                           rvec       x,      /* position of atom on which the force acts             */
822                           rvec       pivot)  /* pivot point of rotation axis                         */
823 {
824     rvec vectmp, tau;
825
826
827     /* Subtract offset */
828     rvec_sub(x, pivot, vectmp);
829
830     /* position x force */
831     cprod(vectmp, force, tau);
832
833     /* Return the part of the torque which is parallel to the rotation vector */
834     return iprod(tau, rotvec);
835 }
836
837
838 /* Right-aligned output of value with standard width */
839 static void print_aligned(FILE *fp, char const *str)
840 {
841     fprintf(fp, "%12s", str);
842 }
843
844
845 /* Right-aligned output of value with standard short width */
846 static void print_aligned_short(FILE *fp, char const *str)
847 {
848     fprintf(fp, "%6s", str);
849 }
850
851
852 static FILE *open_output_file(const char *fn, int steps, const char what[])
853 {
854     FILE *fp;
855
856
857     fp = gmx_ffopen(fn, "w");
858
859     fprintf(fp, "# Output of %s is written in intervals of %d time step%s.\n#\n",
860             what, steps, steps > 1 ? "s" : "");
861
862     return fp;
863 }
864
865
866 /* Open output file for slab center data. Call on master only */
867 static FILE *open_slab_out(const char *fn,
868                            gmx_enfrot *er)
869 {
870     FILE *fp;
871
872     if (er->appendFiles)
873     {
874         fp = gmx_fio_fopen(fn, "a");
875     }
876     else
877     {
878         fp = open_output_file(fn, er->nstsout, "gaussian weighted slab centers");
879
880         for (auto &ergRef : er->enfrotgrp)
881         {
882             gmx_enfrotgrp *erg = &ergRef;
883             if (ISFLEX(erg->rotg))
884             {
885                 fprintf(fp, "# Rotation group %d (%s), slab distance %f nm, %s.\n",
886                         erg->groupIndex, erotg_names[erg->rotg->eType], erg->rotg->slab_dist,
887                         erg->rotg->bMassW ? "centers of mass" : "geometrical centers");
888             }
889         }
890
891         fprintf(fp, "# Reference centers are listed first (t=-1).\n");
892         fprintf(fp, "# The following columns have the syntax:\n");
893         fprintf(fp, "#     ");
894         print_aligned_short(fp, "t");
895         print_aligned_short(fp, "grp");
896         /* Print legend for the first two entries only ... */
897         for (int i = 0; i < 2; i++)
898         {
899             print_aligned_short(fp, "slab");
900             print_aligned(fp, "X center");
901             print_aligned(fp, "Y center");
902             print_aligned(fp, "Z center");
903         }
904         fprintf(fp, " ...\n");
905         fflush(fp);
906     }
907
908     return fp;
909 }
910
911
912 /* Adds 'buf' to 'str' */
913 static void add_to_string(char **str, char *buf)
914 {
915     int len;
916
917
918     len = strlen(*str) + strlen(buf) + 1;
919     srenew(*str, len);
920     strcat(*str, buf);
921 }
922
923
924 static void add_to_string_aligned(char **str, char *buf)
925 {
926     char buf_aligned[STRLEN];
927
928     sprintf(buf_aligned, "%12s", buf);
929     add_to_string(str, buf_aligned);
930 }
931
932
933 /* Open output file and print some general information about the rotation groups.
934  * Call on master only */
935 static FILE *open_rot_out(const char             *fn,
936                           const gmx_output_env_t *oenv,
937                           gmx_enfrot             *er)
938 {
939     FILE           *fp;
940     int             nsets;
941     const char    **setname;
942     char            buf[50], buf2[75];
943     gmx_bool        bFlex;
944     char           *LegendStr = nullptr;
945     const t_rot    *rot       = er->rot;
946
947     if (er->appendFiles)
948     {
949         fp = gmx_fio_fopen(fn, "a");
950     }
951     else
952     {
953         fp = xvgropen(fn, "Rotation angles and energy", "Time (ps)", "angles (degrees) and energies (kJ/mol)", oenv);
954         fprintf(fp, "# Output of enforced rotation data is written in intervals of %d time step%s.\n#\n", er->nstrout, er->nstrout > 1 ? "s" : "");
955         fprintf(fp, "# The scalar tau is the torque (kJ/mol) in the direction of the rotation vector v.\n");
956         fprintf(fp, "# To obtain the vectorial torque, multiply tau with the group's rot-vec.\n");
957         fprintf(fp, "# For flexible groups, tau(t,n) from all slabs n have been summed in a single value tau(t) here.\n");
958         fprintf(fp, "# The torques tau(t,n) are found in the rottorque.log (-rt) output file\n");
959
960         for (int g = 0; g < rot->ngrp; g++)
961         {
962             const t_rotgrp      *rotg = &rot->grp[g];
963             const gmx_enfrotgrp *erg  = &er->enfrotgrp[g];
964             bFlex = ISFLEX(rotg);
965
966             fprintf(fp, "#\n");
967             fprintf(fp, "# ROTATION GROUP %d, potential type '%s':\n", g, erotg_names[rotg->eType]);
968             fprintf(fp, "# rot-massw%d          %s\n", g, yesno_names[rotg->bMassW]);
969             fprintf(fp, "# rot-vec%d            %12.5e %12.5e %12.5e\n", g, erg->vec[XX], erg->vec[YY], erg->vec[ZZ]);
970             fprintf(fp, "# rot-rate%d           %12.5e degrees/ps\n", g, rotg->rate);
971             fprintf(fp, "# rot-k%d              %12.5e kJ/(mol*nm^2)\n", g, rotg->k);
972             if (rotg->eType == erotgISO || rotg->eType == erotgPM || rotg->eType == erotgRM || rotg->eType == erotgRM2)
973             {
974                 fprintf(fp, "# rot-pivot%d          %12.5e %12.5e %12.5e  nm\n", g, rotg->pivot[XX], rotg->pivot[YY], rotg->pivot[ZZ]);
975             }
976
977             if (bFlex)
978             {
979                 fprintf(fp, "# rot-slab-distance%d   %f nm\n", g, rotg->slab_dist);
980                 fprintf(fp, "# rot-min-gaussian%d   %12.5e\n", g, rotg->min_gaussian);
981             }
982
983             /* Output the centers of the rotation groups for the pivot-free potentials */
984             if ((rotg->eType == erotgISOPF) || (rotg->eType == erotgPMPF) || (rotg->eType == erotgRMPF) || (rotg->eType == erotgRM2PF
985                                                                                                             || (rotg->eType == erotgFLEXT) || (rotg->eType == erotgFLEX2T)) )
986             {
987                 fprintf(fp, "# ref. grp. %d center  %12.5e %12.5e %12.5e\n", g,
988                         erg->xc_ref_center[XX], erg->xc_ref_center[YY], erg->xc_ref_center[ZZ]);
989
990                 fprintf(fp, "# grp. %d init.center  %12.5e %12.5e %12.5e\n", g,
991                         erg->xc_center[XX], erg->xc_center[YY], erg->xc_center[ZZ]);
992             }
993
994             if ( (rotg->eType == erotgRM2) || (rotg->eType == erotgFLEX2) || (rotg->eType == erotgFLEX2T) )
995             {
996                 fprintf(fp, "# rot-eps%d            %12.5e nm^2\n", g, rotg->eps);
997             }
998             if (erotgFitPOT == rotg->eFittype)
999             {
1000                 fprintf(fp, "#\n");
1001                 fprintf(fp, "# theta_fit%d is determined by first evaluating the potential for %d angles around theta_ref%d.\n",
1002                         g, rotg->PotAngle_nstep, g);
1003                 fprintf(fp, "# The fit angle is the one with the smallest potential. It is given as the deviation\n");
1004                 fprintf(fp, "# from the reference angle, i.e. if theta_ref=X and theta_fit=Y, then the angle with\n");
1005                 fprintf(fp, "# minimal value of the potential is X+Y. Angular resolution is %g degrees.\n", rotg->PotAngle_step);
1006             }
1007         }
1008
1009         /* Print a nice legend */
1010         snew(LegendStr, 1);
1011         LegendStr[0] = '\0';
1012         sprintf(buf, "#     %6s", "time");
1013         add_to_string_aligned(&LegendStr, buf);
1014
1015         nsets = 0;
1016         snew(setname, 4*rot->ngrp);
1017
1018         for (int g = 0; g < rot->ngrp; g++)
1019         {
1020             sprintf(buf, "theta_ref%d", g);
1021             add_to_string_aligned(&LegendStr, buf);
1022
1023             sprintf(buf2, "%s (degrees)", buf);
1024             setname[nsets] = gmx_strdup(buf2);
1025             nsets++;
1026         }
1027         for (int g = 0; g < rot->ngrp; g++)
1028         {
1029             const t_rotgrp *rotg = &rot->grp[g];
1030             bFlex = ISFLEX(rotg);
1031
1032             /* For flexible axis rotation we use RMSD fitting to determine the
1033              * actual angle of the rotation group */
1034             if (bFlex || erotgFitPOT == rotg->eFittype)
1035             {
1036                 sprintf(buf, "theta_fit%d", g);
1037             }
1038             else
1039             {
1040                 sprintf(buf, "theta_av%d", g);
1041             }
1042             add_to_string_aligned(&LegendStr, buf);
1043             sprintf(buf2, "%s (degrees)", buf);
1044             setname[nsets] = gmx_strdup(buf2);
1045             nsets++;
1046
1047             sprintf(buf, "tau%d", g);
1048             add_to_string_aligned(&LegendStr, buf);
1049             sprintf(buf2, "%s (kJ/mol)", buf);
1050             setname[nsets] = gmx_strdup(buf2);
1051             nsets++;
1052
1053             sprintf(buf, "energy%d", g);
1054             add_to_string_aligned(&LegendStr, buf);
1055             sprintf(buf2, "%s (kJ/mol)", buf);
1056             setname[nsets] = gmx_strdup(buf2);
1057             nsets++;
1058         }
1059         fprintf(fp, "#\n");
1060
1061         if (nsets > 1)
1062         {
1063             xvgr_legend(fp, nsets, setname, oenv);
1064         }
1065         sfree(setname);
1066
1067         fprintf(fp, "#\n# Legend for the following data columns:\n");
1068         fprintf(fp, "%s\n", LegendStr);
1069         sfree(LegendStr);
1070
1071         fflush(fp);
1072     }
1073
1074     return fp;
1075 }
1076
1077
1078 /* Call on master only */
1079 static FILE *open_angles_out(const char *fn,
1080                              gmx_enfrot *er)
1081 {
1082     FILE        *fp;
1083     char         buf[100];
1084     const t_rot *rot = er->rot;
1085
1086     if (er->appendFiles)
1087     {
1088         fp = gmx_fio_fopen(fn, "a");
1089     }
1090     else
1091     {
1092         /* Open output file and write some information about it's structure: */
1093         fp = open_output_file(fn, er->nstsout, "rotation group angles");
1094         fprintf(fp, "# All angles given in degrees, time in ps.\n");
1095         for (int g = 0; g < rot->ngrp; g++)
1096         {
1097             const t_rotgrp      *rotg = &rot->grp[g];
1098             const gmx_enfrotgrp *erg  = &er->enfrotgrp[g];
1099
1100             /* Output for this group happens only if potential type is flexible or
1101              * if fit type is potential! */
1102             if (ISFLEX(rotg) || (erotgFitPOT == rotg->eFittype) )
1103             {
1104                 if (ISFLEX(rotg))
1105                 {
1106                     sprintf(buf, " slab distance %f nm, ", rotg->slab_dist);
1107                 }
1108                 else
1109                 {
1110                     buf[0] = '\0';
1111                 }
1112
1113                 fprintf(fp, "#\n# ROTATION GROUP %d '%s',%s fit type '%s'.\n",
1114                         g, erotg_names[rotg->eType], buf, erotg_fitnames[rotg->eFittype]);
1115
1116                 /* Special type of fitting using the potential minimum. This is
1117                  * done for the whole group only, not for the individual slabs. */
1118                 if (erotgFitPOT == rotg->eFittype)
1119                 {
1120                     fprintf(fp, "#    To obtain theta_fit%d, the potential is evaluated for %d angles around theta_ref%d\n", g, rotg->PotAngle_nstep, g);
1121                     fprintf(fp, "#    The fit angle in the rotation standard outfile is the one with minimal energy E(theta_fit) [kJ/mol].\n");
1122                     fprintf(fp, "#\n");
1123                 }
1124
1125                 fprintf(fp, "# Legend for the group %d data columns:\n", g);
1126                 fprintf(fp, "#     ");
1127                 print_aligned_short(fp, "time");
1128                 print_aligned_short(fp, "grp");
1129                 print_aligned(fp, "theta_ref");
1130
1131                 if (erotgFitPOT == rotg->eFittype)
1132                 {
1133                     /* Output the set of angles around the reference angle */
1134                     for (int i = 0; i < rotg->PotAngle_nstep; i++)
1135                     {
1136                         sprintf(buf, "E(%g)", erg->PotAngleFit->degangle[i]);
1137                         print_aligned(fp, buf);
1138                     }
1139                 }
1140                 else
1141                 {
1142                     /* Output fit angle for each slab */
1143                     print_aligned_short(fp, "slab");
1144                     print_aligned_short(fp, "atoms");
1145                     print_aligned(fp, "theta_fit");
1146                     print_aligned_short(fp, "slab");
1147                     print_aligned_short(fp, "atoms");
1148                     print_aligned(fp, "theta_fit");
1149                     fprintf(fp, " ...");
1150                 }
1151                 fprintf(fp, "\n");
1152             }
1153         }
1154         fflush(fp);
1155     }
1156
1157     return fp;
1158 }
1159
1160
1161 /* Open torque output file and write some information about it's structure.
1162  * Call on master only */
1163 static FILE *open_torque_out(const char *fn,
1164                              gmx_enfrot *er)
1165 {
1166     FILE        *fp;
1167     const t_rot *rot = er->rot;
1168
1169     if (er->appendFiles)
1170     {
1171         fp = gmx_fio_fopen(fn, "a");
1172     }
1173     else
1174     {
1175         fp = open_output_file(fn, er->nstsout, "torques");
1176
1177         for (int g = 0; g < rot->ngrp; g++)
1178         {
1179             const t_rotgrp      *rotg = &rot->grp[g];
1180             const gmx_enfrotgrp *erg  = &er->enfrotgrp[g];
1181             if (ISFLEX(rotg))
1182             {
1183                 fprintf(fp, "# Rotation group %d (%s), slab distance %f nm.\n", g, erotg_names[rotg->eType], rotg->slab_dist);
1184                 fprintf(fp, "# The scalar tau is the torque (kJ/mol) in the direction of the rotation vector.\n");
1185                 fprintf(fp, "# To obtain the vectorial torque, multiply tau with\n");
1186                 fprintf(fp, "# rot-vec%d            %10.3e %10.3e %10.3e\n", g, erg->vec[XX], erg->vec[YY], erg->vec[ZZ]);
1187                 fprintf(fp, "#\n");
1188             }
1189         }
1190         fprintf(fp, "# Legend for the following data columns: (tau=torque for that slab):\n");
1191         fprintf(fp, "#     ");
1192         print_aligned_short(fp, "t");
1193         print_aligned_short(fp, "grp");
1194         print_aligned_short(fp, "slab");
1195         print_aligned(fp, "tau");
1196         print_aligned_short(fp, "slab");
1197         print_aligned(fp, "tau");
1198         fprintf(fp, " ...\n");
1199         fflush(fp);
1200     }
1201
1202     return fp;
1203 }
1204
1205
1206 static void swap_val(double* vec, int i, int j)
1207 {
1208     double tmp = vec[j];
1209
1210
1211     vec[j] = vec[i];
1212     vec[i] = tmp;
1213 }
1214
1215
1216 static void swap_col(double **mat, int i, int j)
1217 {
1218     double tmp[3] = {mat[0][j], mat[1][j], mat[2][j]};
1219
1220
1221     mat[0][j] = mat[0][i];
1222     mat[1][j] = mat[1][i];
1223     mat[2][j] = mat[2][i];
1224
1225     mat[0][i] = tmp[0];
1226     mat[1][i] = tmp[1];
1227     mat[2][i] = tmp[2];
1228 }
1229
1230
1231 /* Eigenvectors are stored in columns of eigen_vec */
1232 static void diagonalize_symmetric(
1233         double **matrix,
1234         double **eigen_vec,
1235         double   eigenval[3])
1236 {
1237     int n_rot;
1238
1239
1240     jacobi(matrix, 3, eigenval, eigen_vec, &n_rot);
1241
1242     /* sort in ascending order */
1243     if (eigenval[0] > eigenval[1])
1244     {
1245         swap_val(eigenval, 0, 1);
1246         swap_col(eigen_vec, 0, 1);
1247     }
1248     if (eigenval[1] > eigenval[2])
1249     {
1250         swap_val(eigenval, 1, 2);
1251         swap_col(eigen_vec, 1, 2);
1252     }
1253     if (eigenval[0] > eigenval[1])
1254     {
1255         swap_val(eigenval, 0, 1);
1256         swap_col(eigen_vec, 0, 1);
1257     }
1258 }
1259
1260
1261 static void align_with_z(
1262         rvec* s,           /* Structure to align */
1263         int   natoms,
1264         rvec  axis)
1265 {
1266     int     i, j, k;
1267     rvec    zet         = {0.0, 0.0, 1.0};
1268     rvec    rot_axis    = {0.0, 0.0, 0.0};
1269     rvec   *rotated_str = nullptr;
1270     real    ooanorm;
1271     real    angle;
1272     matrix  rotmat;
1273
1274
1275     snew(rotated_str, natoms);
1276
1277     /* Normalize the axis */
1278     ooanorm = 1.0/norm(axis);
1279     svmul(ooanorm, axis, axis);
1280
1281     /* Calculate the angle for the fitting procedure */
1282     cprod(axis, zet, rot_axis);
1283     angle = acos(axis[2]);
1284     if (angle < 0.0)
1285     {
1286         angle += M_PI;
1287     }
1288
1289     /* Calculate the rotation matrix */
1290     calc_rotmat(rot_axis, angle*180.0/M_PI, rotmat);
1291
1292     /* Apply the rotation matrix to s */
1293     for (i = 0; i < natoms; i++)
1294     {
1295         for (j = 0; j < 3; j++)
1296         {
1297             for (k = 0; k < 3; k++)
1298             {
1299                 rotated_str[i][j] += rotmat[j][k]*s[i][k];
1300             }
1301         }
1302     }
1303
1304     /* Rewrite the rotated structure to s */
1305     for (i = 0; i < natoms; i++)
1306     {
1307         for (j = 0; j < 3; j++)
1308         {
1309             s[i][j] = rotated_str[i][j];
1310         }
1311     }
1312
1313     sfree(rotated_str);
1314 }
1315
1316
1317 static void calc_correl_matrix(rvec* Xstr, rvec* Ystr, double** Rmat, int natoms)
1318 {
1319     int i, j, k;
1320
1321
1322     for (i = 0; i < 3; i++)
1323     {
1324         for (j = 0; j < 3; j++)
1325         {
1326             Rmat[i][j] = 0.0;
1327         }
1328     }
1329
1330     for (i = 0; i < 3; i++)
1331     {
1332         for (j = 0; j < 3; j++)
1333         {
1334             for (k = 0; k < natoms; k++)
1335             {
1336                 Rmat[i][j] += Ystr[k][i] * Xstr[k][j];
1337             }
1338         }
1339     }
1340 }
1341
1342
1343 static void weigh_coords(rvec* str, real* weight, int natoms)
1344 {
1345     int i, j;
1346
1347
1348     for (i = 0; i < natoms; i++)
1349     {
1350         for (j = 0; j < 3; j++)
1351         {
1352             str[i][j] *= std::sqrt(weight[i]);
1353         }
1354     }
1355 }
1356
1357
1358 static real opt_angle_analytic(
1359         rvec      * ref_s,
1360         rvec      * act_s,
1361         real      * weight,
1362         int         natoms,
1363         const rvec  ref_com,
1364         const rvec  act_com,
1365         rvec        axis)
1366 {
1367     int      i, j, k;
1368     rvec    *ref_s_1 = nullptr;
1369     rvec    *act_s_1 = nullptr;
1370     rvec     shift;
1371     double **Rmat, **RtR, **eigvec;
1372     double   eigval[3];
1373     double   V[3][3], WS[3][3];
1374     double   rot_matrix[3][3];
1375     double   opt_angle;
1376
1377
1378     /* Do not change the original coordinates */
1379     snew(ref_s_1, natoms);
1380     snew(act_s_1, natoms);
1381     for (i = 0; i < natoms; i++)
1382     {
1383         copy_rvec(ref_s[i], ref_s_1[i]);
1384         copy_rvec(act_s[i], act_s_1[i]);
1385     }
1386
1387     /* Translate the structures to the origin */
1388     shift[XX] = -ref_com[XX];
1389     shift[YY] = -ref_com[YY];
1390     shift[ZZ] = -ref_com[ZZ];
1391     translate_x(ref_s_1, natoms, shift);
1392
1393     shift[XX] = -act_com[XX];
1394     shift[YY] = -act_com[YY];
1395     shift[ZZ] = -act_com[ZZ];
1396     translate_x(act_s_1, natoms, shift);
1397
1398     /* Align rotation axis with z */
1399     align_with_z(ref_s_1, natoms, axis);
1400     align_with_z(act_s_1, natoms, axis);
1401
1402     /* Correlation matrix */
1403     Rmat = allocate_square_matrix(3);
1404
1405     for (i = 0; i < natoms; i++)
1406     {
1407         ref_s_1[i][2] = 0.0;
1408         act_s_1[i][2] = 0.0;
1409     }
1410
1411     /* Weight positions with sqrt(weight) */
1412     if (nullptr != weight)
1413     {
1414         weigh_coords(ref_s_1, weight, natoms);
1415         weigh_coords(act_s_1, weight, natoms);
1416     }
1417
1418     /* Calculate correlation matrices R=YXt (X=ref_s; Y=act_s) */
1419     calc_correl_matrix(ref_s_1, act_s_1, Rmat, natoms);
1420
1421     /* Calculate RtR */
1422     RtR = allocate_square_matrix(3);
1423     for (i = 0; i < 3; i++)
1424     {
1425         for (j = 0; j < 3; j++)
1426         {
1427             for (k = 0; k < 3; k++)
1428             {
1429                 RtR[i][j] += Rmat[k][i] * Rmat[k][j];
1430             }
1431         }
1432     }
1433     /* Diagonalize RtR */
1434     snew(eigvec, 3);
1435     for (i = 0; i < 3; i++)
1436     {
1437         snew(eigvec[i], 3);
1438     }
1439
1440     diagonalize_symmetric(RtR, eigvec, eigval);
1441     swap_col(eigvec, 0, 1);
1442     swap_col(eigvec, 1, 2);
1443     swap_val(eigval, 0, 1);
1444     swap_val(eigval, 1, 2);
1445
1446     /* Calculate V */
1447     for (i = 0; i < 3; i++)
1448     {
1449         for (j = 0; j < 3; j++)
1450         {
1451             V[i][j]  = 0.0;
1452             WS[i][j] = 0.0;
1453         }
1454     }
1455
1456     for (i = 0; i < 2; i++)
1457     {
1458         for (j = 0; j < 2; j++)
1459         {
1460             WS[i][j] = eigvec[i][j] / std::sqrt(eigval[j]);
1461         }
1462     }
1463
1464     for (i = 0; i < 3; i++)
1465     {
1466         for (j = 0; j < 3; j++)
1467         {
1468             for (k = 0; k < 3; k++)
1469             {
1470                 V[i][j] += Rmat[i][k]*WS[k][j];
1471             }
1472         }
1473     }
1474     free_square_matrix(Rmat, 3);
1475
1476     /* Calculate optimal rotation matrix */
1477     for (i = 0; i < 3; i++)
1478     {
1479         for (j = 0; j < 3; j++)
1480         {
1481             rot_matrix[i][j] = 0.0;
1482         }
1483     }
1484
1485     for (i = 0; i < 3; i++)
1486     {
1487         for (j = 0; j < 3; j++)
1488         {
1489             for (k = 0; k < 3; k++)
1490             {
1491                 rot_matrix[i][j] += eigvec[i][k]*V[j][k];
1492             }
1493         }
1494     }
1495     rot_matrix[2][2] = 1.0;
1496
1497     /* In some cases abs(rot_matrix[0][0]) can be slighly larger
1498      * than unity due to numerical inacurracies. To be able to calculate
1499      * the acos function, we put these values back in range. */
1500     if (rot_matrix[0][0] > 1.0)
1501     {
1502         rot_matrix[0][0] = 1.0;
1503     }
1504     else if (rot_matrix[0][0] < -1.0)
1505     {
1506         rot_matrix[0][0] = -1.0;
1507     }
1508
1509     /* Determine the optimal rotation angle: */
1510     opt_angle = (-1.0)*acos(rot_matrix[0][0])*180.0/M_PI;
1511     if (rot_matrix[0][1] < 0.0)
1512     {
1513         opt_angle = (-1.0)*opt_angle;
1514     }
1515
1516     /* Give back some memory */
1517     free_square_matrix(RtR, 3);
1518     sfree(ref_s_1);
1519     sfree(act_s_1);
1520     for (i = 0; i < 3; i++)
1521     {
1522         sfree(eigvec[i]);
1523     }
1524     sfree(eigvec);
1525
1526     return static_cast<real>(opt_angle);
1527 }
1528
1529
1530 /* Determine angle of the group by RMSD fit to the reference */
1531 /* Not parallelized, call this routine only on the master */
1532 static real flex_fit_angle(gmx_enfrotgrp *erg)
1533 {
1534     rvec           *fitcoords = nullptr;
1535     rvec            center;     /* Center of positions passed to the fit routine */
1536     real            fitangle;   /* Angle of the rotation group derived by fitting */
1537     rvec            coord;
1538     real            scal;
1539
1540     /* Get the center of the rotation group.
1541      * Note, again, erg->xc has been sorted in do_flexible */
1542     get_center(erg->xc, erg->mc_sorted, erg->rotg->nat, center);
1543
1544     /* === Determine the optimal fit angle for the rotation group === */
1545     if (erg->rotg->eFittype == erotgFitNORM)
1546     {
1547         /* Normalize every position to it's reference length */
1548         for (int i = 0; i < erg->rotg->nat; i++)
1549         {
1550             /* Put the center of the positions into the origin */
1551             rvec_sub(erg->xc[i], center, coord);
1552             /* Determine the scaling factor for the length: */
1553             scal = erg->xc_ref_length[erg->xc_sortind[i]] / norm(coord);
1554             /* Get position, multiply with the scaling factor and save  */
1555             svmul(scal, coord, erg->xc_norm[i]);
1556         }
1557         fitcoords = erg->xc_norm;
1558     }
1559     else
1560     {
1561         fitcoords = erg->xc;
1562     }
1563     /* From the point of view of the current positions, the reference has rotated
1564      * backwards. Since we output the angle relative to the fixed reference,
1565      * we need the minus sign. */
1566     fitangle = -opt_angle_analytic(erg->xc_ref_sorted, fitcoords, erg->mc_sorted,
1567                                    erg->rotg->nat, erg->xc_ref_center, center, erg->vec);
1568
1569     return fitangle;
1570 }
1571
1572
1573 /* Determine actual angle of each slab by RMSD fit to the reference */
1574 /* Not parallelized, call this routine only on the master */
1575 static void flex_fit_angle_perslab(
1576         gmx_enfrotgrp *erg,
1577         double         t,
1578         real           degangle,
1579         FILE          *fp)
1580 {
1581     rvec            curr_x, ref_x;
1582     rvec            act_center; /* Center of actual positions that are passed to the fit routine */
1583     rvec            ref_center; /* Same for the reference positions */
1584     real            fitangle;   /* Angle of a slab derived from an RMSD fit to
1585                                  * the reference structure at t=0  */
1586     gmx_slabdata   *sd;
1587     real            OOm_av;     /* 1/average_mass of a rotation group atom */
1588     real            m_rel;      /* Relative mass of a rotation group atom  */
1589
1590
1591     /* Average mass of a rotation group atom: */
1592     OOm_av = erg->invmass*erg->rotg->nat;
1593
1594     /**********************************/
1595     /* First collect the data we need */
1596     /**********************************/
1597
1598     /* Collect the data for the individual slabs */
1599     for (int n = erg->slab_first; n <= erg->slab_last; n++)
1600     {
1601         int slabIndex = n - erg->slab_first; /* slab index */
1602         sd      = &(erg->slab_data[slabIndex]);
1603         sd->nat = erg->lastatom[slabIndex]-erg->firstatom[slabIndex]+1;
1604         int ind     = 0;
1605
1606         /* Loop over the relevant atoms in the slab */
1607         for (int l = erg->firstatom[slabIndex]; l <= erg->lastatom[slabIndex]; l++)
1608         {
1609             /* Current position of this atom: x[ii][XX/YY/ZZ] */
1610             copy_rvec(erg->xc[l], curr_x);
1611
1612             /* The (unrotated) reference position of this atom is copied to ref_x.
1613              * Beware, the xc coords have been sorted in do_flexible */
1614             copy_rvec(erg->xc_ref_sorted[l], ref_x);
1615
1616             /* Save data for doing angular RMSD fit later */
1617             /* Save the current atom position */
1618             copy_rvec(curr_x, sd->x[ind]);
1619             /* Save the corresponding reference position */
1620             copy_rvec(ref_x, sd->ref[ind]);
1621
1622             /* Maybe also mass-weighting was requested. If yes, additionally
1623              * multiply the weights with the relative mass of the atom. If not,
1624              * multiply with unity. */
1625             m_rel = erg->mc_sorted[l]*OOm_av;
1626
1627             /* Save the weight for this atom in this slab */
1628             sd->weight[ind] = gaussian_weight(curr_x, erg, n) * m_rel;
1629
1630             /* Next atom in this slab */
1631             ind++;
1632         }
1633     }
1634
1635     /******************************/
1636     /* Now do the fit calculation */
1637     /******************************/
1638
1639     fprintf(fp, "%12.3e%6d%12.3f", t, erg->groupIndex, degangle);
1640
1641     /* === Now do RMSD fitting for each slab === */
1642     /* We require at least SLAB_MIN_ATOMS in a slab, such that the fit makes sense. */
1643 #define SLAB_MIN_ATOMS 4
1644
1645     for (int n = erg->slab_first; n <= erg->slab_last; n++)
1646     {
1647         int slabIndex = n - erg->slab_first; /* slab index */
1648         sd    = &(erg->slab_data[slabIndex]);
1649         if (sd->nat >= SLAB_MIN_ATOMS)
1650         {
1651             /* Get the center of the slabs reference and current positions */
1652             get_center(sd->ref, sd->weight, sd->nat, ref_center);
1653             get_center(sd->x, sd->weight, sd->nat, act_center);
1654             if (erg->rotg->eFittype == erotgFitNORM)
1655             {
1656                 /* Normalize every position to it's reference length
1657                  * prior to performing the fit */
1658                 for (int i = 0; i < sd->nat; i++) /* Center */
1659                 {
1660                     rvec_dec(sd->ref[i], ref_center);
1661                     rvec_dec(sd->x[i], act_center);
1662                     /* Normalize x_i such that it gets the same length as ref_i */
1663                     svmul( norm(sd->ref[i])/norm(sd->x[i]), sd->x[i], sd->x[i] );
1664                 }
1665                 /* We already subtracted the centers */
1666                 clear_rvec(ref_center);
1667                 clear_rvec(act_center);
1668             }
1669             fitangle = -opt_angle_analytic(sd->ref, sd->x, sd->weight, sd->nat,
1670                                            ref_center, act_center, erg->vec);
1671             fprintf(fp, "%6d%6d%12.3f", n, sd->nat, fitangle);
1672         }
1673     }
1674     fprintf(fp, "\n");
1675
1676 #undef SLAB_MIN_ATOMS
1677 }
1678
1679
1680 /* Shift x with is */
1681 static inline void shift_single_coord(const matrix box, rvec x, const ivec is)
1682 {
1683     int tx, ty, tz;
1684
1685
1686     tx = is[XX];
1687     ty = is[YY];
1688     tz = is[ZZ];
1689
1690     if (TRICLINIC(box))
1691     {
1692         x[XX] += tx*box[XX][XX]+ty*box[YY][XX]+tz*box[ZZ][XX];
1693         x[YY] += ty*box[YY][YY]+tz*box[ZZ][YY];
1694         x[ZZ] += tz*box[ZZ][ZZ];
1695     }
1696     else
1697     {
1698         x[XX] += tx*box[XX][XX];
1699         x[YY] += ty*box[YY][YY];
1700         x[ZZ] += tz*box[ZZ][ZZ];
1701     }
1702 }
1703
1704
1705 /* Determine the 'home' slab of this atom which is the
1706  * slab with the highest Gaussian weight of all */
1707 #define round(a) (int)((a)+0.5)
1708 static inline int get_homeslab(
1709         rvec       curr_x,   /* The position for which the home slab shall be determined */
1710         const rvec rotvec,   /* The rotation vector */
1711         real       slabdist) /* The slab distance */
1712 {
1713     real dist;
1714
1715
1716     /* The distance of the atom to the coordinate center (where the
1717      * slab with index 0) is */
1718     dist = iprod(rotvec, curr_x);
1719
1720     return round(dist / slabdist);
1721 }
1722
1723
1724 /* For a local atom determine the relevant slabs, i.e. slabs in
1725  * which the gaussian is larger than min_gaussian
1726  */
1727 static int get_single_atom_gaussians(
1728         rvec           curr_x,
1729         gmx_enfrotgrp *erg)
1730 {
1731
1732     /* Determine the 'home' slab of this atom: */
1733     int homeslab = get_homeslab(curr_x, erg->vec, erg->rotg->slab_dist);
1734
1735     /* First determine the weight in the atoms home slab: */
1736     real g     = gaussian_weight(curr_x, erg, homeslab);
1737     int  count = 0;
1738     erg->gn_atom[count]    = g;
1739     erg->gn_slabind[count] = homeslab;
1740     count++;
1741
1742
1743     /* Determine the max slab */
1744     int slab = homeslab;
1745     while (g > erg->rotg->min_gaussian)
1746     {
1747         slab++;
1748         g = gaussian_weight(curr_x, erg, slab);
1749         erg->gn_slabind[count] = slab;
1750         erg->gn_atom[count]    = g;
1751         count++;
1752     }
1753     count--;
1754
1755     /* Determine the min slab */
1756     slab = homeslab;
1757     do
1758     {
1759         slab--;
1760         g = gaussian_weight(curr_x, erg, slab);
1761         erg->gn_slabind[count] = slab;
1762         erg->gn_atom[count]    = g;
1763         count++;
1764     }
1765     while (g > erg->rotg->min_gaussian);
1766     count--;
1767
1768     return count;
1769 }
1770
1771
1772 static void flex2_precalc_inner_sum(const gmx_enfrotgrp *erg)
1773 {
1774     rvec            xi;       /* positions in the i-sum                        */
1775     rvec            xcn, ycn; /* the current and the reference slab centers    */
1776     real            gaussian_xi;
1777     rvec            yi0;
1778     rvec            rin;     /* Helper variables                              */
1779     real            fac, fac2;
1780     rvec            innersumvec;
1781     real            OOpsii, OOpsiistar;
1782     real            sin_rin; /* s_ii.r_ii */
1783     rvec            s_in, tmpvec, tmpvec2;
1784     real            mi, wi;  /* Mass-weighting of the positions                 */
1785     real            N_M;     /* N/M                                             */
1786
1787
1788     N_M = erg->rotg->nat * erg->invmass;
1789
1790     /* Loop over all slabs that contain something */
1791     for (int n = erg->slab_first; n <= erg->slab_last; n++)
1792     {
1793         int slabIndex = n - erg->slab_first; /* slab index */
1794
1795         /* The current center of this slab is saved in xcn: */
1796         copy_rvec(erg->slab_center[slabIndex], xcn);
1797         /* ... and the reference center in ycn: */
1798         copy_rvec(erg->slab_center_ref[slabIndex+erg->slab_buffer], ycn);
1799
1800         /*** D. Calculate the whole inner sum used for second and third sum */
1801         /* For slab n, we need to loop over all atoms i again. Since we sorted
1802          * the atoms with respect to the rotation vector, we know that it is sufficient
1803          * to calculate from firstatom to lastatom only. All other contributions will
1804          * be very small. */
1805         clear_rvec(innersumvec);
1806         for (int i = erg->firstatom[slabIndex]; i <= erg->lastatom[slabIndex]; i++)
1807         {
1808             /* Coordinate xi of this atom */
1809             copy_rvec(erg->xc[i], xi);
1810
1811             /* The i-weights */
1812             gaussian_xi = gaussian_weight(xi, erg, n);
1813             mi          = erg->mc_sorted[i]; /* need the sorted mass here */
1814             wi          = N_M*mi;
1815
1816             /* Calculate rin */
1817             copy_rvec(erg->xc_ref_sorted[i], yi0); /* Reference position yi0   */
1818             rvec_sub(yi0, ycn, tmpvec2);           /* tmpvec2 = yi0 - ycn      */
1819             mvmul(erg->rotmat, tmpvec2, rin);      /* rin = Omega.(yi0 - ycn)  */
1820
1821             /* Calculate psi_i* and sin */
1822             rvec_sub(xi, xcn, tmpvec2);                /* tmpvec2 = xi - xcn       */
1823             cprod(erg->vec, tmpvec2, tmpvec);          /* tmpvec = v x (xi - xcn)  */
1824             OOpsiistar = norm2(tmpvec)+erg->rotg->eps; /* OOpsii* = 1/psii* = |v x (xi-xcn)|^2 + eps */
1825             OOpsii     = norm(tmpvec);                 /* OOpsii = 1 / psii = |v x (xi - xcn)| */
1826
1827             /*                           *         v x (xi - xcn)          */
1828             unitv(tmpvec, s_in);        /*  sin = ----------------         */
1829                                         /*        |v x (xi - xcn)|         */
1830
1831             sin_rin = iprod(s_in, rin); /* sin_rin = sin . rin             */
1832
1833             /* Now the whole sum */
1834             fac = OOpsii/OOpsiistar;
1835             svmul(fac, rin, tmpvec);
1836             fac2 = fac*fac*OOpsii;
1837             svmul(fac2*sin_rin, s_in, tmpvec2);
1838             rvec_dec(tmpvec, tmpvec2);
1839
1840             svmul(wi*gaussian_xi*sin_rin, tmpvec, tmpvec2);
1841
1842             rvec_inc(innersumvec, tmpvec2);
1843         } /* now we have the inner sum, used both for sum2 and sum3 */
1844
1845         /* Save it to be used in do_flex2_lowlevel */
1846         copy_rvec(innersumvec, erg->slab_innersumvec[slabIndex]);
1847     } /* END of loop over slabs */
1848 }
1849
1850
1851 static void flex_precalc_inner_sum(const gmx_enfrotgrp *erg)
1852 {
1853     rvec            xi;       /* position                                      */
1854     rvec            xcn, ycn; /* the current and the reference slab centers    */
1855     rvec            qin, rin; /* q_i^n and r_i^n                               */
1856     real            bin;
1857     rvec            tmpvec;
1858     rvec            innersumvec; /* Inner part of sum_n2                          */
1859     real            gaussian_xi; /* Gaussian weight gn(xi)                        */
1860     real            mi, wi;      /* Mass-weighting of the positions               */
1861     real            N_M;         /* N/M                                           */
1862
1863     N_M = erg->rotg->nat * erg->invmass;
1864
1865     /* Loop over all slabs that contain something */
1866     for (int n = erg->slab_first; n <= erg->slab_last; n++)
1867     {
1868         int slabIndex = n - erg->slab_first; /* slab index */
1869
1870         /* The current center of this slab is saved in xcn: */
1871         copy_rvec(erg->slab_center[slabIndex], xcn);
1872         /* ... and the reference center in ycn: */
1873         copy_rvec(erg->slab_center_ref[slabIndex+erg->slab_buffer], ycn);
1874
1875         /* For slab n, we need to loop over all atoms i again. Since we sorted
1876          * the atoms with respect to the rotation vector, we know that it is sufficient
1877          * to calculate from firstatom to lastatom only. All other contributions will
1878          * be very small. */
1879         clear_rvec(innersumvec);
1880         for (int i = erg->firstatom[slabIndex]; i <= erg->lastatom[slabIndex]; i++)
1881         {
1882             /* Coordinate xi of this atom */
1883             copy_rvec(erg->xc[i], xi);
1884
1885             /* The i-weights */
1886             gaussian_xi = gaussian_weight(xi, erg, n);
1887             mi          = erg->mc_sorted[i]; /* need the sorted mass here */
1888             wi          = N_M*mi;
1889
1890             /* Calculate rin and qin */
1891             rvec_sub(erg->xc_ref_sorted[i], ycn, tmpvec); /* tmpvec = yi0-ycn */
1892             mvmul(erg->rotmat, tmpvec, rin);              /* rin = Omega.(yi0 - ycn)  */
1893             cprod(erg->vec, rin, tmpvec);                 /* tmpvec = v x Omega*(yi0-ycn) */
1894
1895             /*                                *        v x Omega*(yi0-ycn)    */
1896             unitv(tmpvec, qin);              /* qin = ---------------------   */
1897                                              /*       |v x Omega*(yi0-ycn)|   */
1898
1899             /* Calculate bin */
1900             rvec_sub(xi, xcn, tmpvec);            /* tmpvec = xi-xcn          */
1901             bin = iprod(qin, tmpvec);             /* bin  = qin*(xi-xcn)      */
1902
1903             svmul(wi*gaussian_xi*bin, qin, tmpvec);
1904
1905             /* Add this contribution to the inner sum: */
1906             rvec_add(innersumvec, tmpvec, innersumvec);
1907         } /* now we have the inner sum vector S^n for this slab */
1908           /* Save it to be used in do_flex_lowlevel */
1909         copy_rvec(innersumvec, erg->slab_innersumvec[slabIndex]);
1910     }
1911 }
1912
1913
1914 static real do_flex2_lowlevel(
1915         gmx_enfrotgrp *erg,
1916         real           sigma, /* The Gaussian width sigma */
1917         rvec           x[],
1918         gmx_bool       bOutstepRot,
1919         gmx_bool       bOutstepSlab,
1920         matrix         box)
1921 {
1922     int             count, ii, iigrp;
1923     rvec            xj;          /* position in the i-sum                         */
1924     rvec            yj0;         /* the reference position in the j-sum           */
1925     rvec            xcn, ycn;    /* the current and the reference slab centers    */
1926     real            V;           /* This node's part of the rotation pot. energy  */
1927     real            gaussian_xj; /* Gaussian weight                               */
1928     real            beta;
1929
1930     real            numerator, fit_numerator;
1931     rvec            rjn, fit_rjn; /* Helper variables                              */
1932     real            fac, fac2;
1933
1934     real            OOpsij, OOpsijstar;
1935     real            OOsigma2; /* 1/(sigma^2)                                   */
1936     real            sjn_rjn;
1937     real            betasigpsi;
1938     rvec            sjn, tmpvec, tmpvec2, yj0_ycn;
1939     rvec            sum1vec_part, sum1vec, sum2vec_part, sum2vec, sum3vec, sum4vec, innersumvec;
1940     real            sum3, sum4;
1941     real            mj, wj;  /* Mass-weighting of the positions               */
1942     real            N_M;     /* N/M                                           */
1943     real            Wjn;     /* g_n(x_j) m_j / Mjn                            */
1944     gmx_bool        bCalcPotFit;
1945
1946     /* To calculate the torque per slab */
1947     rvec slab_force;         /* Single force from slab n on one atom          */
1948     rvec slab_sum1vec_part;
1949     real slab_sum3part, slab_sum4part;
1950     rvec slab_sum1vec, slab_sum2vec, slab_sum3vec, slab_sum4vec;
1951
1952     /* Pre-calculate the inner sums, so that we do not have to calculate
1953      * them again for every atom */
1954     flex2_precalc_inner_sum(erg);
1955
1956     bCalcPotFit = (bOutstepRot || bOutstepSlab) && (erotgFitPOT == erg->rotg->eFittype);
1957
1958     /********************************************************/
1959     /* Main loop over all local atoms of the rotation group */
1960     /********************************************************/
1961     N_M      = erg->rotg->nat * erg->invmass;
1962     V        = 0.0;
1963     OOsigma2 = 1.0 / (sigma*sigma);
1964     const auto &localRotationGroupIndex      = erg->atomSet->localIndex();
1965     const auto &collectiveRotationGroupIndex = erg->atomSet->collectiveIndex();
1966
1967     for (gmx::index j = 0; j < localRotationGroupIndex.size(); j++)
1968     {
1969         /* Local index of a rotation group atom  */
1970         ii = localRotationGroupIndex[j];
1971         /* Position of this atom in the collective array */
1972         iigrp = collectiveRotationGroupIndex[j];
1973         /* Mass-weighting */
1974         mj = erg->mc[iigrp];  /* need the unsorted mass here */
1975         wj = N_M*mj;
1976
1977         /* Current position of this atom: x[ii][XX/YY/ZZ]
1978          * Note that erg->xc_center contains the center of mass in case the flex2-t
1979          * potential was chosen. For the flex2 potential erg->xc_center must be
1980          * zero. */
1981         rvec_sub(x[ii], erg->xc_center, xj);
1982
1983         /* Shift this atom such that it is near its reference */
1984         shift_single_coord(box, xj, erg->xc_shifts[iigrp]);
1985
1986         /* Determine the slabs to loop over, i.e. the ones with contributions
1987          * larger than min_gaussian */
1988         count = get_single_atom_gaussians(xj, erg);
1989
1990         clear_rvec(sum1vec_part);
1991         clear_rvec(sum2vec_part);
1992         sum3 = 0.0;
1993         sum4 = 0.0;
1994         /* Loop over the relevant slabs for this atom */
1995         for (int ic = 0; ic < count; ic++)
1996         {
1997             int n = erg->gn_slabind[ic];
1998
1999             /* Get the precomputed Gaussian value of curr_slab for curr_x */
2000             gaussian_xj = erg->gn_atom[ic];
2001
2002             int slabIndex = n - erg->slab_first; /* slab index */
2003
2004             /* The (unrotated) reference position of this atom is copied to yj0: */
2005             copy_rvec(erg->rotg->x_ref[iigrp], yj0);
2006
2007             beta = calc_beta(xj, erg, n);
2008
2009             /* The current center of this slab is saved in xcn: */
2010             copy_rvec(erg->slab_center[slabIndex], xcn);
2011             /* ... and the reference center in ycn: */
2012             copy_rvec(erg->slab_center_ref[slabIndex+erg->slab_buffer], ycn);
2013
2014             rvec_sub(yj0, ycn, yj0_ycn);          /* yj0_ycn = yj0 - ycn      */
2015
2016             /* Rotate: */
2017             mvmul(erg->rotmat, yj0_ycn, rjn);     /* rjn = Omega.(yj0 - ycn)  */
2018
2019             /* Subtract the slab center from xj */
2020             rvec_sub(xj, xcn, tmpvec2);           /* tmpvec2 = xj - xcn       */
2021
2022             /* In rare cases, when an atom position coincides with a slab center
2023              * (tmpvec2 == 0) we cannot compute the vector product for sjn.
2024              * However, since the atom is located directly on the pivot, this
2025              * slab's contribution to the force on that atom will be zero
2026              * anyway. Therefore, we directly move on to the next slab.       */
2027             if (gmx_numzero(norm(tmpvec2))) /* 0 == norm(xj - xcn) */
2028             {
2029                 continue;
2030             }
2031
2032             /* Calculate sjn */
2033             cprod(erg->vec, tmpvec2, tmpvec);          /* tmpvec = v x (xj - xcn)  */
2034
2035             OOpsijstar = norm2(tmpvec)+erg->rotg->eps; /* OOpsij* = 1/psij* = |v x (xj-xcn)|^2 + eps */
2036
2037             numerator = gmx::square(iprod(tmpvec, rjn));
2038
2039             /*********************************/
2040             /* Add to the rotation potential */
2041             /*********************************/
2042             V += 0.5*erg->rotg->k*wj*gaussian_xj*numerator/OOpsijstar;
2043
2044             /* If requested, also calculate the potential for a set of angles
2045              * near the current reference angle */
2046             if (bCalcPotFit)
2047             {
2048                 for (int ifit = 0; ifit < erg->rotg->PotAngle_nstep; ifit++)
2049                 {
2050                     mvmul(erg->PotAngleFit->rotmat[ifit], yj0_ycn, fit_rjn);
2051                     fit_numerator              = gmx::square(iprod(tmpvec, fit_rjn));
2052                     erg->PotAngleFit->V[ifit] += 0.5*erg->rotg->k*wj*gaussian_xj*fit_numerator/OOpsijstar;
2053                 }
2054             }
2055
2056             /*************************************/
2057             /* Now calculate the force on atom j */
2058             /*************************************/
2059
2060             OOpsij = norm(tmpvec);    /* OOpsij = 1 / psij = |v x (xj - xcn)| */
2061
2062             /*                              *         v x (xj - xcn)          */
2063             unitv(tmpvec, sjn);            /*  sjn = ----------------         */
2064                                            /*        |v x (xj - xcn)|         */
2065
2066             sjn_rjn = iprod(sjn, rjn);     /* sjn_rjn = sjn . rjn             */
2067
2068
2069             /*** A. Calculate the first of the four sum terms: ****************/
2070             fac = OOpsij/OOpsijstar;
2071             svmul(fac, rjn, tmpvec);
2072             fac2 = fac*fac*OOpsij;
2073             svmul(fac2*sjn_rjn, sjn, tmpvec2);
2074             rvec_dec(tmpvec, tmpvec2);
2075             fac2 = wj*gaussian_xj; /* also needed for sum4 */
2076             svmul(fac2*sjn_rjn, tmpvec, slab_sum1vec_part);
2077             /********************/
2078             /*** Add to sum1: ***/
2079             /********************/
2080             rvec_inc(sum1vec_part, slab_sum1vec_part); /* sum1 still needs to vector multiplied with v */
2081
2082             /*** B. Calculate the forth of the four sum terms: ****************/
2083             betasigpsi = beta*OOsigma2*OOpsij; /* this is also needed for sum3 */
2084             /********************/
2085             /*** Add to sum4: ***/
2086             /********************/
2087             slab_sum4part = fac2*betasigpsi*fac*sjn_rjn*sjn_rjn; /* Note that fac is still valid from above */
2088             sum4         += slab_sum4part;
2089
2090             /*** C. Calculate Wjn for second and third sum */
2091             /* Note that we can safely divide by slab_weights since we check in
2092              * get_slab_centers that it is non-zero. */
2093             Wjn = gaussian_xj*mj/erg->slab_weights[slabIndex];
2094
2095             /* We already have precalculated the inner sum for slab n */
2096             copy_rvec(erg->slab_innersumvec[slabIndex], innersumvec);
2097
2098             /* Weigh the inner sum vector with Wjn */
2099             svmul(Wjn, innersumvec, innersumvec);
2100
2101             /*** E. Calculate the second of the four sum terms: */
2102             /********************/
2103             /*** Add to sum2: ***/
2104             /********************/
2105             rvec_inc(sum2vec_part, innersumvec); /* sum2 still needs to be vector crossproduct'ed with v */
2106
2107             /*** F. Calculate the third of the four sum terms: */
2108             slab_sum3part = betasigpsi * iprod(sjn, innersumvec);
2109             sum3         += slab_sum3part; /* still needs to be multiplied with v */
2110
2111             /*** G. Calculate the torque on the local slab's axis: */
2112             if (bOutstepRot)
2113             {
2114                 /* Sum1 */
2115                 cprod(slab_sum1vec_part, erg->vec, slab_sum1vec);
2116                 /* Sum2 */
2117                 cprod(innersumvec, erg->vec, slab_sum2vec);
2118                 /* Sum3 */
2119                 svmul(slab_sum3part, erg->vec, slab_sum3vec);
2120                 /* Sum4 */
2121                 svmul(slab_sum4part, erg->vec, slab_sum4vec);
2122
2123                 /* The force on atom ii from slab n only: */
2124                 for (int m = 0; m < DIM; m++)
2125                 {
2126                     slab_force[m] = erg->rotg->k * (-slab_sum1vec[m] + slab_sum2vec[m] - slab_sum3vec[m] + 0.5*slab_sum4vec[m]);
2127                 }
2128
2129                 erg->slab_torque_v[slabIndex] += torque(erg->vec, slab_force, xj, xcn);
2130             }
2131         } /* END of loop over slabs */
2132
2133         /* Construct the four individual parts of the vector sum: */
2134         cprod(sum1vec_part, erg->vec, sum1vec);      /* sum1vec =   { } x v  */
2135         cprod(sum2vec_part, erg->vec, sum2vec);      /* sum2vec =   { } x v  */
2136         svmul(sum3, erg->vec, sum3vec);              /* sum3vec =   { } . v  */
2137         svmul(sum4, erg->vec, sum4vec);              /* sum4vec =   { } . v  */
2138
2139         /* Store the additional force so that it can be added to the force
2140          * array after the normal forces have been evaluated */
2141         for (int m = 0; m < DIM; m++)
2142         {
2143             erg->f_rot_loc[j][m] = erg->rotg->k * (-sum1vec[m] + sum2vec[m] - sum3vec[m] + 0.5*sum4vec[m]);
2144         }
2145
2146 #ifdef SUM_PARTS
2147         fprintf(stderr, "sum1: %15.8f %15.8f %15.8f\n",    -erg->rotg->k*sum1vec[XX],    -erg->rotg->k*sum1vec[YY],    -erg->rotg->k*sum1vec[ZZ]);
2148         fprintf(stderr, "sum2: %15.8f %15.8f %15.8f\n",     erg->rotg->k*sum2vec[XX],     erg->rotg->k*sum2vec[YY],     erg->rotg->k*sum2vec[ZZ]);
2149         fprintf(stderr, "sum3: %15.8f %15.8f %15.8f\n",    -erg->rotg->k*sum3vec[XX],    -erg->rotg->k*sum3vec[YY],    -erg->rotg->k*sum3vec[ZZ]);
2150         fprintf(stderr, "sum4: %15.8f %15.8f %15.8f\n", 0.5*erg->rotg->k*sum4vec[XX], 0.5*erg->rotg->k*sum4vec[YY], 0.5*erg->rotg->k*sum4vec[ZZ]);
2151 #endif
2152
2153         PRINT_FORCE_J
2154
2155     } /* END of loop over local atoms */
2156
2157     return V;
2158 }
2159
2160
2161 static real do_flex_lowlevel(
2162         gmx_enfrotgrp *erg,
2163         real           sigma, /* The Gaussian width sigma                      */
2164         rvec           x[],
2165         gmx_bool       bOutstepRot,
2166         gmx_bool       bOutstepSlab,
2167         matrix         box)
2168 {
2169     int             count, iigrp;
2170     rvec            xj, yj0;                /* current and reference position                */
2171     rvec            xcn, ycn;               /* the current and the reference slab centers    */
2172     rvec            yj0_ycn;                /* yj0 - ycn                                     */
2173     rvec            xj_xcn;                 /* xj - xcn                                      */
2174     rvec            qjn, fit_qjn;           /* q_i^n                                         */
2175     rvec            sum_n1, sum_n2;         /* Two contributions to the rotation force       */
2176     rvec            innersumvec;            /* Inner part of sum_n2                          */
2177     rvec            s_n;
2178     rvec            force_n;                /* Single force from slab n on one atom          */
2179     rvec            force_n1, force_n2;     /* First and second part of force_n              */
2180     rvec            tmpvec, tmpvec2, tmp_f; /* Helper variables                              */
2181     real            V;                      /* The rotation potential energy                 */
2182     real            OOsigma2;               /* 1/(sigma^2)                                   */
2183     real            beta;                   /* beta_n(xj)                                    */
2184     real            bjn, fit_bjn;           /* b_j^n                                         */
2185     real            gaussian_xj;            /* Gaussian weight gn(xj)                        */
2186     real            betan_xj_sigma2;
2187     real            mj, wj;                 /* Mass-weighting of the positions               */
2188     real            N_M;                    /* N/M                                           */
2189     gmx_bool        bCalcPotFit;
2190
2191     /* Pre-calculate the inner sums, so that we do not have to calculate
2192      * them again for every atom */
2193     flex_precalc_inner_sum(erg);
2194
2195     bCalcPotFit = (bOutstepRot || bOutstepSlab) && (erotgFitPOT == erg->rotg->eFittype);
2196
2197     /********************************************************/
2198     /* Main loop over all local atoms of the rotation group */
2199     /********************************************************/
2200     OOsigma2 = 1.0/(sigma*sigma);
2201     N_M      = erg->rotg->nat * erg->invmass;
2202     V        = 0.0;
2203     const auto &localRotationGroupIndex      = erg->atomSet->localIndex();
2204     const auto &collectiveRotationGroupIndex = erg->atomSet->collectiveIndex();
2205
2206     for (gmx::index j = 0; j < localRotationGroupIndex.size(); j++)
2207     {
2208         /* Local index of a rotation group atom  */
2209         int ii = localRotationGroupIndex[j];
2210         /* Position of this atom in the collective array */
2211         iigrp = collectiveRotationGroupIndex[j];
2212         /* Mass-weighting */
2213         mj = erg->mc[iigrp];  /* need the unsorted mass here */
2214         wj = N_M*mj;
2215
2216         /* Current position of this atom: x[ii][XX/YY/ZZ]
2217          * Note that erg->xc_center contains the center of mass in case the flex-t
2218          * potential was chosen. For the flex potential erg->xc_center must be
2219          * zero. */
2220         rvec_sub(x[ii], erg->xc_center, xj);
2221
2222         /* Shift this atom such that it is near its reference */
2223         shift_single_coord(box, xj, erg->xc_shifts[iigrp]);
2224
2225         /* Determine the slabs to loop over, i.e. the ones with contributions
2226          * larger than min_gaussian */
2227         count = get_single_atom_gaussians(xj, erg);
2228
2229         clear_rvec(sum_n1);
2230         clear_rvec(sum_n2);
2231
2232         /* Loop over the relevant slabs for this atom */
2233         for (int ic = 0; ic < count; ic++)
2234         {
2235             int n = erg->gn_slabind[ic];
2236
2237             /* Get the precomputed Gaussian for xj in slab n */
2238             gaussian_xj = erg->gn_atom[ic];
2239
2240             int slabIndex = n - erg->slab_first; /* slab index */
2241
2242             /* The (unrotated) reference position of this atom is saved in yj0: */
2243             copy_rvec(erg->rotg->x_ref[iigrp], yj0);
2244
2245             beta = calc_beta(xj, erg, n);
2246
2247             /* The current center of this slab is saved in xcn: */
2248             copy_rvec(erg->slab_center[slabIndex], xcn);
2249             /* ... and the reference center in ycn: */
2250             copy_rvec(erg->slab_center_ref[slabIndex+erg->slab_buffer], ycn);
2251
2252             rvec_sub(yj0, ycn, yj0_ycn); /* yj0_ycn = yj0 - ycn */
2253
2254             /* In rare cases, when an atom position coincides with a reference slab
2255              * center (yj0_ycn == 0) we cannot compute the normal vector qjn.
2256              * However, since the atom is located directly on the pivot, this
2257              * slab's contribution to the force on that atom will be zero
2258              * anyway. Therefore, we directly move on to the next slab.       */
2259             if (gmx_numzero(norm(yj0_ycn))) /* 0 == norm(yj0 - ycn) */
2260             {
2261                 continue;
2262             }
2263
2264             /* Rotate: */
2265             mvmul(erg->rotmat, yj0_ycn, tmpvec2); /* tmpvec2= Omega.(yj0-ycn) */
2266
2267             /* Subtract the slab center from xj */
2268             rvec_sub(xj, xcn, xj_xcn);           /* xj_xcn = xj - xcn         */
2269
2270             /* Calculate qjn */
2271             cprod(erg->vec, tmpvec2, tmpvec); /* tmpvec= v x Omega.(yj0-ycn) */
2272
2273             /*                         *         v x Omega.(yj0-ycn)    */
2274             unitv(tmpvec, qjn);       /*  qjn = ---------------------   */
2275                                       /*        |v x Omega.(yj0-ycn)|   */
2276
2277             bjn = iprod(qjn, xj_xcn); /* bjn = qjn * (xj - xcn) */
2278
2279             /*********************************/
2280             /* Add to the rotation potential */
2281             /*********************************/
2282             V += 0.5*erg->rotg->k*wj*gaussian_xj*gmx::square(bjn);
2283
2284             /* If requested, also calculate the potential for a set of angles
2285              * near the current reference angle */
2286             if (bCalcPotFit)
2287             {
2288                 for (int ifit = 0; ifit < erg->rotg->PotAngle_nstep; ifit++)
2289                 {
2290                     /* As above calculate Omega.(yj0-ycn), now for the other angles */
2291                     mvmul(erg->PotAngleFit->rotmat[ifit], yj0_ycn, tmpvec2); /* tmpvec2= Omega.(yj0-ycn) */
2292                     /* As above calculate qjn */
2293                     cprod(erg->vec, tmpvec2, tmpvec);                        /* tmpvec= v x Omega.(yj0-ycn) */
2294                     /*                                                        *             v x Omega.(yj0-ycn)    */
2295                     unitv(tmpvec, fit_qjn);                                  /*  fit_qjn = ---------------------   */
2296                                                                              /*            |v x Omega.(yj0-ycn)|   */
2297                     fit_bjn = iprod(fit_qjn, xj_xcn);                        /* fit_bjn = fit_qjn * (xj - xcn) */
2298                     /* Add to the rotation potential for this angle */
2299                     erg->PotAngleFit->V[ifit] += 0.5*erg->rotg->k*wj*gaussian_xj*gmx::square(fit_bjn);
2300                 }
2301             }
2302
2303             /****************************************************************/
2304             /* sum_n1 will typically be the main contribution to the force: */
2305             /****************************************************************/
2306             betan_xj_sigma2 = beta*OOsigma2;  /*  beta_n(xj)/sigma^2  */
2307
2308             /* The next lines calculate
2309              *  qjn - (bjn*beta(xj)/(2sigma^2))v  */
2310             svmul(bjn*0.5*betan_xj_sigma2, erg->vec, tmpvec2);
2311             rvec_sub(qjn, tmpvec2, tmpvec);
2312
2313             /* Multiply with gn(xj)*bjn: */
2314             svmul(gaussian_xj*bjn, tmpvec, tmpvec2);
2315
2316             /* Sum over n: */
2317             rvec_inc(sum_n1, tmpvec2);
2318
2319             /* We already have precalculated the Sn term for slab n */
2320             copy_rvec(erg->slab_innersumvec[slabIndex], s_n);
2321             /*                                                             *          beta_n(xj)              */
2322             svmul(betan_xj_sigma2*iprod(s_n, xj_xcn), erg->vec, tmpvec); /* tmpvec = ---------- s_n (xj-xcn) */
2323                                                                          /*            sigma^2               */
2324
2325             rvec_sub(s_n, tmpvec, innersumvec);
2326
2327             /* We can safely divide by slab_weights since we check in get_slab_centers
2328              * that it is non-zero. */
2329             svmul(gaussian_xj/erg->slab_weights[slabIndex], innersumvec, innersumvec);
2330
2331             rvec_add(sum_n2, innersumvec, sum_n2);
2332
2333             /* Calculate the torque: */
2334             if (bOutstepRot)
2335             {
2336                 /* The force on atom ii from slab n only: */
2337                 svmul(-erg->rotg->k*wj, tmpvec2, force_n1);     /* part 1 */
2338                 svmul( erg->rotg->k*mj, innersumvec, force_n2); /* part 2 */
2339                 rvec_add(force_n1, force_n2, force_n);
2340                 erg->slab_torque_v[slabIndex] += torque(erg->vec, force_n, xj, xcn);
2341             }
2342         } /* END of loop over slabs */
2343
2344         /* Put both contributions together: */
2345         svmul(wj, sum_n1, sum_n1);
2346         svmul(mj, sum_n2, sum_n2);
2347         rvec_sub(sum_n2, sum_n1, tmp_f); /* F = -grad V */
2348
2349         /* Store the additional force so that it can be added to the force
2350          * array after the normal forces have been evaluated */
2351         for (int m = 0; m < DIM; m++)
2352         {
2353             erg->f_rot_loc[j][m] = erg->rotg->k*tmp_f[m];
2354         }
2355
2356         PRINT_FORCE_J
2357
2358     } /* END of loop over local atoms */
2359
2360     return V;
2361 }
2362
2363 static int projection_compare(const void *a, const void *b)
2364 {
2365     auto xca = reinterpret_cast<const sort_along_vec_t *>(a);
2366     auto xcb = reinterpret_cast<const sort_along_vec_t *>(b);
2367
2368     if (xca->xcproj < xcb->xcproj)
2369     {
2370         return -1;
2371     }
2372     else if (xca->xcproj > xcb->xcproj)
2373     {
2374         return 1;
2375     }
2376     else
2377     {
2378         return 0;
2379     }
2380 }
2381
2382
2383 static void sort_collective_coordinates(
2384         gmx_enfrotgrp    *erg,
2385         sort_along_vec_t *data) /* Buffer for sorting the positions */
2386 {
2387     /* The projection of the position vector on the rotation vector is
2388      * the relevant value for sorting. Fill the 'data' structure */
2389     for (int i = 0; i < erg->rotg->nat; i++)
2390     {
2391         data[i].xcproj = iprod(erg->xc[i], erg->vec);  /* sort criterium */
2392         data[i].m      = erg->mc[i];
2393         data[i].ind    = i;
2394         copy_rvec(erg->xc[i], data[i].x    );
2395         copy_rvec(erg->rotg->x_ref[i], data[i].x_ref);
2396     }
2397     /* Sort the 'data' structure */
2398     gmx_qsort(data, erg->rotg->nat, sizeof(sort_along_vec_t), projection_compare);
2399
2400     /* Copy back the sorted values */
2401     for (int i = 0; i < erg->rotg->nat; i++)
2402     {
2403         copy_rvec(data[i].x, erg->xc[i]           );
2404         copy_rvec(data[i].x_ref, erg->xc_ref_sorted[i]);
2405         erg->mc_sorted[i]  = data[i].m;
2406         erg->xc_sortind[i] = data[i].ind;
2407     }
2408 }
2409
2410
2411 /* For each slab, get the first and the last index of the sorted atom
2412  * indices */
2413 static void get_firstlast_atom_per_slab(const gmx_enfrotgrp *erg)
2414 {
2415     real beta;
2416
2417     /* Find the first atom that needs to enter the calculation for each slab */
2418     int n = erg->slab_first; /* slab */
2419     int i = 0;               /* start with the first atom */
2420     do
2421     {
2422         /* Find the first atom that significantly contributes to this slab */
2423         do /* move forward in position until a large enough beta is found */
2424         {
2425             beta = calc_beta(erg->xc[i], erg, n);
2426             i++;
2427         }
2428         while ((beta < -erg->max_beta) && (i < erg->rotg->nat));
2429         i--;
2430         int slabIndex             = n - erg->slab_first; /* slab index */
2431         erg->firstatom[slabIndex] = i;
2432         /* Proceed to the next slab */
2433         n++;
2434     }
2435     while (n <= erg->slab_last);
2436
2437     /* Find the last atom for each slab */
2438     n = erg->slab_last;   /* start with last slab */
2439     i = erg->rotg->nat-1; /* start with the last atom */
2440     do
2441     {
2442         do  /* move backward in position until a large enough beta is found */
2443         {
2444             beta = calc_beta(erg->xc[i], erg, n);
2445             i--;
2446         }
2447         while ((beta > erg->max_beta) && (i > -1));
2448         i++;
2449         int slabIndex            = n - erg->slab_first; /* slab index */
2450         erg->lastatom[slabIndex] = i;
2451         /* Proceed to the next slab */
2452         n--;
2453     }
2454     while (n >= erg->slab_first);
2455 }
2456
2457
2458 /* Determine the very first and very last slab that needs to be considered
2459  * For the first slab that needs to be considered, we have to find the smallest
2460  * n that obeys:
2461  *
2462  * x_first * v - n*Delta_x <= beta_max
2463  *
2464  * slab index n, slab distance Delta_x, rotation vector v. For the last slab we
2465  * have to find the largest n that obeys
2466  *
2467  * x_last * v - n*Delta_x >= -beta_max
2468  *
2469  */
2470 static inline int get_first_slab(
2471         const gmx_enfrotgrp *erg,
2472         rvec                 firstatom) /* First atom after sorting along the rotation vector v */
2473 {
2474     /* Find the first slab for the first atom */
2475     return static_cast<int>(ceil(static_cast<double>((iprod(firstatom, erg->vec) - erg->max_beta)/erg->rotg->slab_dist)));
2476 }
2477
2478
2479 static inline int get_last_slab(
2480         const gmx_enfrotgrp *erg,
2481         rvec                 lastatom) /* Last atom along v */
2482 {
2483     /* Find the last slab for the last atom */
2484     return static_cast<int>(floor(static_cast<double>((iprod(lastatom, erg->vec) + erg->max_beta)/erg->rotg->slab_dist)));
2485 }
2486
2487
2488 static void get_firstlast_slab_check(
2489         gmx_enfrotgrp   *erg,       /* The rotation group (data only accessible in this file) */
2490         rvec             firstatom, /* First atom after sorting along the rotation vector v */
2491         rvec             lastatom)  /* Last atom along v */
2492 {
2493     erg->slab_first = get_first_slab(erg, firstatom);
2494     erg->slab_last  = get_last_slab(erg, lastatom);
2495
2496     /* Calculate the slab buffer size, which changes when slab_first changes */
2497     erg->slab_buffer = erg->slab_first - erg->slab_first_ref;
2498
2499     /* Check whether we have reference data to compare against */
2500     if (erg->slab_first < erg->slab_first_ref)
2501     {
2502         gmx_fatal(FARGS, "%s No reference data for first slab (n=%d), unable to proceed.",
2503                   RotStr, erg->slab_first);
2504     }
2505
2506     /* Check whether we have reference data to compare against */
2507     if (erg->slab_last > erg->slab_last_ref)
2508     {
2509         gmx_fatal(FARGS, "%s No reference data for last slab (n=%d), unable to proceed.",
2510                   RotStr, erg->slab_last);
2511     }
2512 }
2513
2514
2515 /* Enforced rotation with a flexible axis */
2516 static void do_flexible(
2517         gmx_bool        bMaster,
2518         gmx_enfrot     *enfrot,       /* Other rotation data                        */
2519         gmx_enfrotgrp  *erg,
2520         rvec            x[],          /* The local positions                        */
2521         matrix          box,
2522         double          t,            /* Time in picoseconds                        */
2523         gmx_bool        bOutstepRot,  /* Output to main rotation output file        */
2524         gmx_bool        bOutstepSlab) /* Output per-slab data                       */
2525 {
2526     int             nslabs;
2527     real            sigma;    /* The Gaussian width sigma */
2528
2529     /* Define the sigma value */
2530     sigma = 0.7*erg->rotg->slab_dist;
2531
2532     /* Sort the collective coordinates erg->xc along the rotation vector. This is
2533      * an optimization for the inner loop. */
2534     sort_collective_coordinates(erg, enfrot->data);
2535
2536     /* Determine the first relevant slab for the first atom and the last
2537      * relevant slab for the last atom */
2538     get_firstlast_slab_check(erg, erg->xc[0], erg->xc[erg->rotg->nat-1]);
2539
2540     /* Determine for each slab depending on the min_gaussian cutoff criterium,
2541      * a first and a last atom index inbetween stuff needs to be calculated */
2542     get_firstlast_atom_per_slab(erg);
2543
2544     /* Determine the gaussian-weighted center of positions for all slabs */
2545     get_slab_centers(erg, erg->xc, erg->mc_sorted, t, enfrot->out_slabs, bOutstepSlab, FALSE);
2546
2547     /* Clear the torque per slab from last time step: */
2548     nslabs = erg->slab_last - erg->slab_first + 1;
2549     for (int l = 0; l < nslabs; l++)
2550     {
2551         erg->slab_torque_v[l] = 0.0;
2552     }
2553
2554     /* Call the rotational forces kernel */
2555     if (erg->rotg->eType == erotgFLEX || erg->rotg->eType == erotgFLEXT)
2556     {
2557         erg->V = do_flex_lowlevel(erg, sigma, x, bOutstepRot, bOutstepSlab, box);
2558     }
2559     else if (erg->rotg->eType == erotgFLEX2 || erg->rotg->eType == erotgFLEX2T)
2560     {
2561         erg->V = do_flex2_lowlevel(erg, sigma, x, bOutstepRot, bOutstepSlab, box);
2562     }
2563     else
2564     {
2565         gmx_fatal(FARGS, "Unknown flexible rotation type");
2566     }
2567
2568     /* Determine angle by RMSD fit to the reference - Let's hope this */
2569     /* only happens once in a while, since this is not parallelized! */
2570     if (bMaster && (erotgFitPOT != erg->rotg->eFittype) )
2571     {
2572         if (bOutstepRot)
2573         {
2574             /* Fit angle of the whole rotation group */
2575             erg->angle_v = flex_fit_angle(erg);
2576         }
2577         if (bOutstepSlab)
2578         {
2579             /* Fit angle of each slab */
2580             flex_fit_angle_perslab(erg, t, erg->degangle, enfrot->out_angles);
2581         }
2582     }
2583
2584     /* Lump together the torques from all slabs: */
2585     erg->torque_v = 0.0;
2586     for (int l = 0; l < nslabs; l++)
2587     {
2588         erg->torque_v += erg->slab_torque_v[l];
2589     }
2590 }
2591
2592
2593 /* Calculate the angle between reference and actual rotation group atom,
2594  * both projected into a plane perpendicular to the rotation vector: */
2595 static void angle(const gmx_enfrotgrp *erg,
2596                   rvec                 x_act,
2597                   rvec                 x_ref,
2598                   real                *alpha,
2599                   real                *weight) /* atoms near the rotation axis should count less than atoms far away */
2600 {
2601     rvec xp, xrp;                              /* current and reference positions projected on a plane perpendicular to pg->vec */
2602     rvec dum;
2603
2604
2605     /* Project x_ref and x into a plane through the origin perpendicular to rot_vec: */
2606     /* Project x_ref: xrp = x_ref - (vec * x_ref) * vec */
2607     svmul(iprod(erg->vec, x_ref), erg->vec, dum);
2608     rvec_sub(x_ref, dum, xrp);
2609     /* Project x_act: */
2610     svmul(iprod(erg->vec, x_act), erg->vec, dum);
2611     rvec_sub(x_act, dum, xp);
2612
2613     /* Retrieve information about which vector precedes. gmx_angle always
2614      * returns a positive angle. */
2615     cprod(xp, xrp, dum); /* if reference precedes, this is pointing into the same direction as vec */
2616
2617     if (iprod(erg->vec, dum) >= 0)
2618     {
2619         *alpha = -gmx_angle(xrp, xp);
2620     }
2621     else
2622     {
2623         *alpha = +gmx_angle(xrp, xp);
2624     }
2625
2626     /* Also return the weight */
2627     *weight = norm(xp);
2628 }
2629
2630
2631 /* Project first vector onto a plane perpendicular to the second vector
2632  * dr = dr - (dr.v)v
2633  * Note that v must be of unit length.
2634  */
2635 static inline void project_onto_plane(rvec dr, const rvec v)
2636 {
2637     rvec tmp;
2638
2639
2640     svmul(iprod(dr, v), v, tmp); /* tmp = (dr.v)v */
2641     rvec_dec(dr, tmp);           /* dr = dr - (dr.v)v */
2642 }
2643
2644
2645 /* Fixed rotation: The rotation reference group rotates around the v axis. */
2646 /* The atoms of the actual rotation group are attached with imaginary  */
2647 /* springs to the reference atoms.                                     */
2648 static void do_fixed(
2649         gmx_enfrotgrp  *erg,
2650         gmx_bool        bOutstepRot,  /* Output to main rotation output file        */
2651         gmx_bool        bOutstepSlab) /* Output per-slab data                       */
2652 {
2653     rvec            dr;
2654     rvec            tmp_f;     /* Force */
2655     real            alpha;     /* a single angle between an actual and a reference position */
2656     real            weight;    /* single weight for a single angle */
2657     rvec            xi_xc;     /* xi - xc */
2658     gmx_bool        bCalcPotFit;
2659     rvec            fit_xr_loc;
2660
2661     /* for mass weighting: */
2662     real      wi;              /* Mass-weighting of the positions */
2663     real      N_M;             /* N/M */
2664     real      k_wi;            /* k times wi */
2665
2666     gmx_bool  bProject;
2667
2668     bProject    = (erg->rotg->eType == erotgPM) || (erg->rotg->eType == erotgPMPF);
2669     bCalcPotFit = (bOutstepRot || bOutstepSlab) && (erotgFitPOT == erg->rotg->eFittype);
2670
2671     N_M = erg->rotg->nat * erg->invmass;
2672     const auto &collectiveRotationGroupIndex = erg->atomSet->collectiveIndex();
2673     /* Each process calculates the forces on its local atoms */
2674     for (size_t j = 0; j < erg->atomSet->numAtomsLocal(); j++)
2675     {
2676         /* Calculate (x_i-x_c) resp. (x_i-u) */
2677         rvec_sub(erg->x_loc_pbc[j], erg->xc_center, xi_xc);
2678
2679         /* Calculate Omega*(y_i-y_c)-(x_i-x_c) */
2680         rvec_sub(erg->xr_loc[j], xi_xc, dr);
2681
2682         if (bProject)
2683         {
2684             project_onto_plane(dr, erg->vec);
2685         }
2686
2687         /* Mass-weighting */
2688         wi = N_M*erg->m_loc[j];
2689
2690         /* Store the additional force so that it can be added to the force
2691          * array after the normal forces have been evaluated */
2692         k_wi = erg->rotg->k*wi;
2693         for (int m = 0; m < DIM; m++)
2694         {
2695             tmp_f[m]             = k_wi*dr[m];
2696             erg->f_rot_loc[j][m] = tmp_f[m];
2697             erg->V              += 0.5*k_wi*gmx::square(dr[m]);
2698         }
2699
2700         /* If requested, also calculate the potential for a set of angles
2701          * near the current reference angle */
2702         if (bCalcPotFit)
2703         {
2704             for (int ifit = 0; ifit < erg->rotg->PotAngle_nstep; ifit++)
2705             {
2706                 /* Index of this rotation group atom with respect to the whole rotation group */
2707                 int jj = collectiveRotationGroupIndex[j];
2708
2709                 /* Rotate with the alternative angle. Like rotate_local_reference(),
2710                  * just for a single local atom */
2711                 mvmul(erg->PotAngleFit->rotmat[ifit], erg->rotg->x_ref[jj], fit_xr_loc); /* fit_xr_loc = Omega*(y_i-y_c) */
2712
2713                 /* Calculate Omega*(y_i-y_c)-(x_i-x_c) */
2714                 rvec_sub(fit_xr_loc, xi_xc, dr);
2715
2716                 if (bProject)
2717                 {
2718                     project_onto_plane(dr, erg->vec);
2719                 }
2720
2721                 /* Add to the rotation potential for this angle: */
2722                 erg->PotAngleFit->V[ifit] += 0.5*k_wi*norm2(dr);
2723             }
2724         }
2725
2726         if (bOutstepRot)
2727         {
2728             /* Add to the torque of this rotation group */
2729             erg->torque_v += torque(erg->vec, tmp_f, erg->x_loc_pbc[j], erg->xc_center);
2730
2731             /* Calculate the angle between reference and actual rotation group atom. */
2732             angle(erg, xi_xc, erg->xr_loc[j], &alpha, &weight);  /* angle in rad, weighted */
2733             erg->angle_v  += alpha * weight;
2734             erg->weight_v += weight;
2735         }
2736         /* If you want enforced rotation to contribute to the virial,
2737          * activate the following lines:
2738             if (MASTER(cr))
2739             {
2740                Add the rotation contribution to the virial
2741               for(j=0; j<DIM; j++)
2742                 for(m=0;m<DIM;m++)
2743                   vir[j][m] += 0.5*f[ii][j]*dr[m];
2744             }
2745          */
2746
2747         PRINT_FORCE_J
2748
2749     } /* end of loop over local rotation group atoms */
2750 }
2751
2752
2753 /* Calculate the radial motion potential and forces */
2754 static void do_radial_motion(
2755         gmx_enfrotgrp  *erg,
2756         gmx_bool        bOutstepRot,  /* Output to main rotation output file        */
2757         gmx_bool        bOutstepSlab) /* Output per-slab data                       */
2758 {
2759     rvec            tmp_f;            /* Force */
2760     real            alpha;            /* a single angle between an actual and a reference position */
2761     real            weight;           /* single weight for a single angle */
2762     rvec            xj_u;             /* xj - u */
2763     rvec            tmpvec, fit_tmpvec;
2764     real            fac, fac2, sum = 0.0;
2765     rvec            pj;
2766     gmx_bool        bCalcPotFit;
2767
2768     /* For mass weighting: */
2769     real      wj;              /* Mass-weighting of the positions */
2770     real      N_M;             /* N/M */
2771
2772     bCalcPotFit = (bOutstepRot || bOutstepSlab) && (erotgFitPOT == erg->rotg->eFittype);
2773
2774     N_M = erg->rotg->nat * erg->invmass;
2775     const auto &collectiveRotationGroupIndex = erg->atomSet->collectiveIndex();
2776     /* Each process calculates the forces on its local atoms */
2777     for (size_t j = 0; j < erg->atomSet->numAtomsLocal(); j++)
2778     {
2779         /* Calculate (xj-u) */
2780         rvec_sub(erg->x_loc_pbc[j], erg->xc_center, xj_u);  /* xj_u = xj-u */
2781
2782         /* Calculate Omega.(yj0-u) */
2783         cprod(erg->vec, erg->xr_loc[j], tmpvec);  /* tmpvec = v x Omega.(yj0-u) */
2784
2785         /*                       *         v x Omega.(yj0-u)     */
2786         unitv(tmpvec, pj);      /*  pj = ---------------------   */
2787                                 /*       | v x Omega.(yj0-u) |   */
2788
2789         fac  = iprod(pj, xj_u); /* fac = pj.(xj-u) */
2790         fac2 = fac*fac;
2791
2792         /* Mass-weighting */
2793         wj = N_M*erg->m_loc[j];
2794
2795         /* Store the additional force so that it can be added to the force
2796          * array after the normal forces have been evaluated */
2797         svmul(-erg->rotg->k*wj*fac, pj, tmp_f);
2798         copy_rvec(tmp_f, erg->f_rot_loc[j]);
2799         sum += wj*fac2;
2800
2801         /* If requested, also calculate the potential for a set of angles
2802          * near the current reference angle */
2803         if (bCalcPotFit)
2804         {
2805             for (int ifit = 0; ifit < erg->rotg->PotAngle_nstep; ifit++)
2806             {
2807                 /* Index of this rotation group atom with respect to the whole rotation group */
2808                 int jj = collectiveRotationGroupIndex[j];
2809
2810                 /* Rotate with the alternative angle. Like rotate_local_reference(),
2811                  * just for a single local atom */
2812                 mvmul(erg->PotAngleFit->rotmat[ifit], erg->rotg->x_ref[jj], fit_tmpvec); /* fit_tmpvec = Omega*(yj0-u) */
2813
2814                 /* Calculate Omega.(yj0-u) */
2815                 cprod(erg->vec, fit_tmpvec, tmpvec); /* tmpvec = v x Omega.(yj0-u) */
2816                 /*                                     *         v x Omega.(yj0-u)     */
2817                 unitv(tmpvec, pj);                   /*  pj = ---------------------   */
2818                                                      /*       | v x Omega.(yj0-u) |   */
2819
2820                 fac  = iprod(pj, xj_u);              /* fac = pj.(xj-u) */
2821                 fac2 = fac*fac;
2822
2823                 /* Add to the rotation potential for this angle: */
2824                 erg->PotAngleFit->V[ifit] += 0.5*erg->rotg->k*wj*fac2;
2825             }
2826         }
2827
2828         if (bOutstepRot)
2829         {
2830             /* Add to the torque of this rotation group */
2831             erg->torque_v += torque(erg->vec, tmp_f, erg->x_loc_pbc[j], erg->xc_center);
2832
2833             /* Calculate the angle between reference and actual rotation group atom. */
2834             angle(erg, xj_u, erg->xr_loc[j], &alpha, &weight);  /* angle in rad, weighted */
2835             erg->angle_v  += alpha * weight;
2836             erg->weight_v += weight;
2837         }
2838
2839         PRINT_FORCE_J
2840
2841     } /* end of loop over local rotation group atoms */
2842     erg->V = 0.5*erg->rotg->k*sum;
2843 }
2844
2845
2846 /* Calculate the radial motion pivot-free potential and forces */
2847 static void do_radial_motion_pf(
2848         gmx_enfrotgrp  *erg,
2849         rvec            x[],          /* The positions                              */
2850         matrix          box,          /* The simulation box                         */
2851         gmx_bool        bOutstepRot,  /* Output to main rotation output file        */
2852         gmx_bool        bOutstepSlab) /* Output per-slab data                       */
2853 {
2854     rvec            xj;               /* Current position */
2855     rvec            xj_xc;            /* xj  - xc  */
2856     rvec            yj0_yc0;          /* yj0 - yc0 */
2857     rvec            tmp_f;            /* Force */
2858     real            alpha;            /* a single angle between an actual and a reference position */
2859     real            weight;           /* single weight for a single angle */
2860     rvec            tmpvec, tmpvec2;
2861     rvec            innersumvec;      /* Precalculation of the inner sum */
2862     rvec            innersumveckM;
2863     real            fac, fac2, V = 0.0;
2864     rvec            qi, qj;
2865     gmx_bool        bCalcPotFit;
2866
2867     /* For mass weighting: */
2868     real      mj, wi, wj;      /* Mass-weighting of the positions */
2869     real      N_M;             /* N/M */
2870
2871     bCalcPotFit = (bOutstepRot || bOutstepSlab) && (erotgFitPOT == erg->rotg->eFittype);
2872
2873     N_M = erg->rotg->nat * erg->invmass;
2874
2875     /* Get the current center of the rotation group: */
2876     get_center(erg->xc, erg->mc, erg->rotg->nat, erg->xc_center);
2877
2878     /* Precalculate Sum_i [ wi qi.(xi-xc) qi ] which is needed for every single j */
2879     clear_rvec(innersumvec);
2880     for (int i = 0; i < erg->rotg->nat; i++)
2881     {
2882         /* Mass-weighting */
2883         wi = N_M*erg->mc[i];
2884
2885         /* Calculate qi. Note that xc_ref_center has already been subtracted from
2886          * x_ref in init_rot_group.*/
2887         mvmul(erg->rotmat, erg->rotg->x_ref[i], tmpvec); /* tmpvec  = Omega.(yi0-yc0) */
2888
2889         cprod(erg->vec, tmpvec, tmpvec2);                /* tmpvec2 = v x Omega.(yi0-yc0) */
2890
2891         /*                                             *         v x Omega.(yi0-yc0)     */
2892         unitv(tmpvec2, qi);                           /*  qi = -----------------------   */
2893                                                       /*       | v x Omega.(yi0-yc0) |   */
2894
2895         rvec_sub(erg->xc[i], erg->xc_center, tmpvec); /* tmpvec = xi-xc */
2896
2897         svmul(wi*iprod(qi, tmpvec), qi, tmpvec2);
2898
2899         rvec_inc(innersumvec, tmpvec2);
2900     }
2901     svmul(erg->rotg->k*erg->invmass, innersumvec, innersumveckM);
2902
2903     /* Each process calculates the forces on its local atoms */
2904     const auto &localRotationGroupIndex      = erg->atomSet->localIndex();
2905     const auto &collectiveRotationGroupIndex = erg->atomSet->collectiveIndex();
2906     for (gmx::index j = 0; j < localRotationGroupIndex.size(); j++)
2907     {
2908         /* Local index of a rotation group atom  */
2909         int ii = localRotationGroupIndex[j];
2910         /* Position of this atom in the collective array */
2911         int iigrp = collectiveRotationGroupIndex[j];
2912         /* Mass-weighting */
2913         mj = erg->mc[iigrp];  /* need the unsorted mass here */
2914         wj = N_M*mj;
2915
2916         /* Current position of this atom: x[ii][XX/YY/ZZ] */
2917         copy_rvec(x[ii], xj);
2918
2919         /* Shift this atom such that it is near its reference */
2920         shift_single_coord(box, xj, erg->xc_shifts[iigrp]);
2921
2922         /* The (unrotated) reference position is yj0. yc0 has already
2923          * been subtracted in init_rot_group */
2924         copy_rvec(erg->rotg->x_ref[iigrp], yj0_yc0);   /* yj0_yc0 = yj0 - yc0      */
2925
2926         /* Calculate Omega.(yj0-yc0) */
2927         mvmul(erg->rotmat, yj0_yc0, tmpvec2); /* tmpvec2 = Omega.(yj0 - yc0)  */
2928
2929         cprod(erg->vec, tmpvec2, tmpvec);     /* tmpvec = v x Omega.(yj0-yc0) */
2930
2931         /*                     *         v x Omega.(yj0-yc0)     */
2932         unitv(tmpvec, qj);    /*  qj = -----------------------   */
2933                               /*       | v x Omega.(yj0-yc0) |   */
2934
2935         /* Calculate (xj-xc) */
2936         rvec_sub(xj, erg->xc_center, xj_xc); /* xj_xc = xj-xc */
2937
2938         fac  = iprod(qj, xj_xc);             /* fac = qj.(xj-xc) */
2939         fac2 = fac*fac;
2940
2941         /* Store the additional force so that it can be added to the force
2942          * array after the normal forces have been evaluated */
2943         svmul(-erg->rotg->k*wj*fac, qj, tmp_f); /* part 1 of force */
2944         svmul(mj, innersumveckM, tmpvec);       /* part 2 of force */
2945         rvec_inc(tmp_f, tmpvec);
2946         copy_rvec(tmp_f, erg->f_rot_loc[j]);
2947         V += wj*fac2;
2948
2949         /* If requested, also calculate the potential for a set of angles
2950          * near the current reference angle */
2951         if (bCalcPotFit)
2952         {
2953             for (int ifit = 0; ifit < erg->rotg->PotAngle_nstep; ifit++)
2954             {
2955                 /* Rotate with the alternative angle. Like rotate_local_reference(),
2956                  * just for a single local atom */
2957                 mvmul(erg->PotAngleFit->rotmat[ifit], yj0_yc0, tmpvec2); /* tmpvec2 = Omega*(yj0-yc0) */
2958
2959                 /* Calculate Omega.(yj0-u) */
2960                 cprod(erg->vec, tmpvec2, tmpvec); /* tmpvec = v x Omega.(yj0-yc0) */
2961                 /*                                  *         v x Omega.(yj0-yc0)     */
2962                 unitv(tmpvec, qj);                /*  qj = -----------------------   */
2963                                                   /*       | v x Omega.(yj0-yc0) |   */
2964
2965                 fac  = iprod(qj, xj_xc);          /* fac = qj.(xj-xc) */
2966                 fac2 = fac*fac;
2967
2968                 /* Add to the rotation potential for this angle: */
2969                 erg->PotAngleFit->V[ifit] += 0.5*erg->rotg->k*wj*fac2;
2970             }
2971         }
2972
2973         if (bOutstepRot)
2974         {
2975             /* Add to the torque of this rotation group */
2976             erg->torque_v += torque(erg->vec, tmp_f, xj, erg->xc_center);
2977
2978             /* Calculate the angle between reference and actual rotation group atom. */
2979             angle(erg, xj_xc, yj0_yc0, &alpha, &weight);  /* angle in rad, weighted */
2980             erg->angle_v  += alpha * weight;
2981             erg->weight_v += weight;
2982         }
2983
2984         PRINT_FORCE_J
2985
2986     } /* end of loop over local rotation group atoms */
2987     erg->V = 0.5*erg->rotg->k*V;
2988 }
2989
2990
2991 /* Precalculate the inner sum for the radial motion 2 forces */
2992 static void radial_motion2_precalc_inner_sum(const gmx_enfrotgrp *erg,
2993                                              rvec                 innersumvec)
2994 {
2995     int             i;
2996     rvec            xi_xc;     /* xj - xc */
2997     rvec            tmpvec, tmpvec2;
2998     real            fac;
2999     rvec            ri, si;
3000     real            siri;
3001     rvec            v_xi_xc;   /* v x (xj - u) */
3002     real            psii, psiistar;
3003     real            wi;        /* Mass-weighting of the positions */
3004     real            N_M;       /* N/M */
3005     rvec            sumvec;
3006
3007     N_M = erg->rotg->nat * erg->invmass;
3008
3009     /* Loop over the collective set of positions */
3010     clear_rvec(sumvec);
3011     for (i = 0; i < erg->rotg->nat; i++)
3012     {
3013         /* Mass-weighting */
3014         wi = N_M*erg->mc[i];
3015
3016         rvec_sub(erg->xc[i], erg->xc_center, xi_xc); /* xi_xc = xi-xc         */
3017
3018         /* Calculate ri. Note that xc_ref_center has already been subtracted from
3019          * x_ref in init_rot_group.*/
3020         mvmul(erg->rotmat, erg->rotg->x_ref[i], ri); /* ri  = Omega.(yi0-yc0) */
3021
3022         cprod(erg->vec, xi_xc, v_xi_xc);             /* v_xi_xc = v x (xi-u)  */
3023
3024         fac = norm2(v_xi_xc);
3025         /*                                 *                      1           */
3026         psiistar = 1.0/(fac + erg->rotg->eps); /* psiistar = --------------------- */
3027         /*            |v x (xi-xc)|^2 + eps */
3028
3029         psii = gmx::invsqrt(fac);         /*                 1                */
3030                                           /*  psii    = -------------         */
3031                                           /*            |v x (xi-xc)|         */
3032
3033         svmul(psii, v_xi_xc, si);         /*  si = psii * (v x (xi-xc) )     */
3034
3035         siri = iprod(si, ri);             /* siri = si.ri           */
3036
3037         svmul(psiistar/psii, ri, tmpvec);
3038         svmul(psiistar*psiistar/(psii*psii*psii) * siri, si, tmpvec2);
3039         rvec_dec(tmpvec, tmpvec2);
3040         cprod(tmpvec, erg->vec, tmpvec2);
3041
3042         svmul(wi*siri, tmpvec2, tmpvec);
3043
3044         rvec_inc(sumvec, tmpvec);
3045     }
3046     svmul(erg->rotg->k*erg->invmass, sumvec, innersumvec);
3047 }
3048
3049
3050 /* Calculate the radial motion 2 potential and forces */
3051 static void do_radial_motion2(
3052         gmx_enfrotgrp  *erg,
3053         rvec            x[],          /* The positions                              */
3054         matrix          box,          /* The simulation box                         */
3055         gmx_bool        bOutstepRot,  /* Output to main rotation output file        */
3056         gmx_bool        bOutstepSlab) /* Output per-slab data                       */
3057 {
3058     rvec            xj;               /* Position */
3059     real            alpha;            /* a single angle between an actual and a reference position */
3060     real            weight;           /* single weight for a single angle */
3061     rvec            xj_u;             /* xj - u */
3062     rvec            yj0_yc0;          /* yj0 -yc0 */
3063     rvec            tmpvec, tmpvec2;
3064     real            fac, fit_fac, fac2, Vpart = 0.0;
3065     rvec            rj, fit_rj, sj;
3066     real            sjrj;
3067     rvec            v_xj_u;    /* v x (xj - u) */
3068     real            psij, psijstar;
3069     real            mj, wj;    /* For mass-weighting of the positions */
3070     real            N_M;       /* N/M */
3071     gmx_bool        bPF;
3072     rvec            innersumvec;
3073     gmx_bool        bCalcPotFit;
3074
3075     bPF         = erg->rotg->eType == erotgRM2PF;
3076     bCalcPotFit = (bOutstepRot || bOutstepSlab) && (erotgFitPOT == erg->rotg->eFittype);
3077
3078     clear_rvec(yj0_yc0); /* Make the compiler happy */
3079
3080     clear_rvec(innersumvec);
3081     if (bPF)
3082     {
3083         /* For the pivot-free variant we have to use the current center of
3084          * mass of the rotation group instead of the pivot u */
3085         get_center(erg->xc, erg->mc, erg->rotg->nat, erg->xc_center);
3086
3087         /* Also, we precalculate the second term of the forces that is identical
3088          * (up to the weight factor mj) for all forces */
3089         radial_motion2_precalc_inner_sum(erg, innersumvec);
3090     }
3091
3092     N_M = erg->rotg->nat * erg->invmass;
3093
3094     /* Each process calculates the forces on its local atoms */
3095     const auto &localRotationGroupIndex      = erg->atomSet->localIndex();
3096     const auto &collectiveRotationGroupIndex = erg->atomSet->collectiveIndex();
3097     for (gmx::index j = 0; j < localRotationGroupIndex.size(); j++)
3098     {
3099         if (bPF)
3100         {
3101             /* Local index of a rotation group atom  */
3102             int ii = localRotationGroupIndex[j];
3103             /* Position of this atom in the collective array */
3104             int iigrp = collectiveRotationGroupIndex[j];
3105             /* Mass-weighting */
3106             mj = erg->mc[iigrp];
3107
3108             /* Current position of this atom: x[ii] */
3109             copy_rvec(x[ii], xj);
3110
3111             /* Shift this atom such that it is near its reference */
3112             shift_single_coord(box, xj, erg->xc_shifts[iigrp]);
3113
3114             /* The (unrotated) reference position is yj0. yc0 has already
3115              * been subtracted in init_rot_group */
3116             copy_rvec(erg->rotg->x_ref[iigrp], yj0_yc0);   /* yj0_yc0 = yj0 - yc0  */
3117
3118             /* Calculate Omega.(yj0-yc0) */
3119             mvmul(erg->rotmat, yj0_yc0, rj);         /* rj = Omega.(yj0-yc0)  */
3120         }
3121         else
3122         {
3123             mj = erg->m_loc[j];
3124             copy_rvec(erg->x_loc_pbc[j], xj);
3125             copy_rvec(erg->xr_loc[j], rj);           /* rj = Omega.(yj0-u)    */
3126         }
3127         /* Mass-weighting */
3128         wj = N_M*mj;
3129
3130         /* Calculate (xj-u) resp. (xj-xc) */
3131         rvec_sub(xj, erg->xc_center, xj_u);         /* xj_u = xj-u           */
3132
3133         cprod(erg->vec, xj_u, v_xj_u);              /* v_xj_u = v x (xj-u)   */
3134
3135         fac = norm2(v_xj_u);
3136         /*                                      *                      1           */
3137         psijstar = 1.0/(fac + erg->rotg->eps); /*  psistar = --------------------  */
3138         /*                                      *            |v x (xj-u)|^2 + eps  */
3139
3140         psij = gmx::invsqrt(fac);         /*                 1                */
3141                                           /*  psij    = ------------          */
3142                                           /*            |v x (xj-u)|          */
3143
3144         svmul(psij, v_xj_u, sj);          /*  sj = psij * (v x (xj-u) )       */
3145
3146         fac  = iprod(v_xj_u, rj);         /* fac = (v x (xj-u)).rj */
3147         fac2 = fac*fac;
3148
3149         sjrj = iprod(sj, rj);                        /* sjrj = sj.rj          */
3150
3151         svmul(psijstar/psij, rj, tmpvec);
3152         svmul(psijstar*psijstar/(psij*psij*psij) * sjrj, sj, tmpvec2);
3153         rvec_dec(tmpvec, tmpvec2);
3154         cprod(tmpvec, erg->vec, tmpvec2);
3155
3156         /* Store the additional force so that it can be added to the force
3157          * array after the normal forces have been evaluated */
3158         svmul(-erg->rotg->k*wj*sjrj, tmpvec2, tmpvec);
3159         svmul(mj, innersumvec, tmpvec2);  /* This is != 0 only for the pivot-free variant */
3160
3161         rvec_add(tmpvec2, tmpvec, erg->f_rot_loc[j]);
3162         Vpart += wj*psijstar*fac2;
3163
3164         /* If requested, also calculate the potential for a set of angles
3165          * near the current reference angle */
3166         if (bCalcPotFit)
3167         {
3168             for (int ifit = 0; ifit < erg->rotg->PotAngle_nstep; ifit++)
3169             {
3170                 if (bPF)
3171                 {
3172                     mvmul(erg->PotAngleFit->rotmat[ifit], yj0_yc0, fit_rj); /* fit_rj = Omega.(yj0-yc0) */
3173                 }
3174                 else
3175                 {
3176                     /* Position of this atom in the collective array */
3177                     int iigrp = collectiveRotationGroupIndex[j];
3178                     /* Rotate with the alternative angle. Like rotate_local_reference(),
3179                      * just for a single local atom */
3180                     mvmul(erg->PotAngleFit->rotmat[ifit], erg->rotg->x_ref[iigrp], fit_rj); /* fit_rj = Omega*(yj0-u) */
3181                 }
3182                 fit_fac = iprod(v_xj_u, fit_rj);                                            /* fac = (v x (xj-u)).fit_rj */
3183                 /* Add to the rotation potential for this angle: */
3184                 erg->PotAngleFit->V[ifit] += 0.5*erg->rotg->k*wj*psijstar*fit_fac*fit_fac;
3185             }
3186         }
3187
3188         if (bOutstepRot)
3189         {
3190             /* Add to the torque of this rotation group */
3191             erg->torque_v += torque(erg->vec, erg->f_rot_loc[j], xj, erg->xc_center);
3192
3193             /* Calculate the angle between reference and actual rotation group atom. */
3194             angle(erg, xj_u, rj, &alpha, &weight);  /* angle in rad, weighted */
3195             erg->angle_v  += alpha * weight;
3196             erg->weight_v += weight;
3197         }
3198
3199         PRINT_FORCE_J
3200
3201     } /* end of loop over local rotation group atoms */
3202     erg->V = 0.5*erg->rotg->k*Vpart;
3203 }
3204
3205
3206 /* Determine the smallest and largest position vector (with respect to the
3207  * rotation vector) for the reference group */
3208 static void get_firstlast_atom_ref(
3209         const gmx_enfrotgrp *erg,
3210         int                 *firstindex,
3211         int                 *lastindex)
3212 {
3213     int             i;
3214     real            xcproj;           /* The projection of a reference position on the
3215                                          rotation vector */
3216     real            minproj, maxproj; /* Smallest and largest projection on v */
3217
3218     /* Start with some value */
3219     minproj = iprod(erg->rotg->x_ref[0], erg->vec);
3220     maxproj = minproj;
3221
3222     /* This is just to ensure that it still works if all the atoms of the
3223      * reference structure are situated in a plane perpendicular to the rotation
3224      * vector */
3225     *firstindex = 0;
3226     *lastindex  = erg->rotg->nat-1;
3227
3228     /* Loop over all atoms of the reference group,
3229      * project them on the rotation vector to find the extremes */
3230     for (i = 0; i < erg->rotg->nat; i++)
3231     {
3232         xcproj = iprod(erg->rotg->x_ref[i], erg->vec);
3233         if (xcproj < minproj)
3234         {
3235             minproj     = xcproj;
3236             *firstindex = i;
3237         }
3238         if (xcproj > maxproj)
3239         {
3240             maxproj    = xcproj;
3241             *lastindex = i;
3242         }
3243     }
3244 }
3245
3246
3247 /* Allocate memory for the slabs */
3248 static void allocate_slabs(
3249         gmx_enfrotgrp *erg,
3250         FILE          *fplog,
3251         gmx_bool       bVerbose)
3252 {
3253     /* More slabs than are defined for the reference are never needed */
3254     int nslabs = erg->slab_last_ref - erg->slab_first_ref + 1;
3255
3256     /* Remember how many we allocated */
3257     erg->nslabs_alloc = nslabs;
3258
3259     if ( (nullptr != fplog) && bVerbose)
3260     {
3261         fprintf(fplog, "%s allocating memory to store data for %d slabs (rotation group %d).\n",
3262                 RotStr, nslabs, erg->groupIndex);
3263     }
3264     snew(erg->slab_center, nslabs);
3265     snew(erg->slab_center_ref, nslabs);
3266     snew(erg->slab_weights, nslabs);
3267     snew(erg->slab_torque_v, nslabs);
3268     snew(erg->slab_data, nslabs);
3269     snew(erg->gn_atom, nslabs);
3270     snew(erg->gn_slabind, nslabs);
3271     snew(erg->slab_innersumvec, nslabs);
3272     for (int i = 0; i < nslabs; i++)
3273     {
3274         snew(erg->slab_data[i].x, erg->rotg->nat);
3275         snew(erg->slab_data[i].ref, erg->rotg->nat);
3276         snew(erg->slab_data[i].weight, erg->rotg->nat);
3277     }
3278     snew(erg->xc_ref_sorted, erg->rotg->nat);
3279     snew(erg->xc_sortind, erg->rotg->nat);
3280     snew(erg->firstatom, nslabs);
3281     snew(erg->lastatom, nslabs);
3282 }
3283
3284
3285 /* From the extreme positions of the reference group, determine the first
3286  * and last slab of the reference. We can never have more slabs in the real
3287  * simulation than calculated here for the reference.
3288  */
3289 static void get_firstlast_slab_ref(gmx_enfrotgrp *erg,
3290                                    real mc[], int ref_firstindex, int ref_lastindex)
3291 {
3292     rvec dummy;
3293
3294     int  first      = get_first_slab(erg, erg->rotg->x_ref[ref_firstindex]);
3295     int  last       = get_last_slab(erg, erg->rotg->x_ref[ref_lastindex ]);
3296
3297     while (get_slab_weight(first, erg, erg->rotg->x_ref, mc, &dummy) > WEIGHT_MIN)
3298     {
3299         first--;
3300     }
3301     erg->slab_first_ref = first+1;
3302     while (get_slab_weight(last, erg, erg->rotg->x_ref, mc, &dummy) > WEIGHT_MIN)
3303     {
3304         last++;
3305     }
3306     erg->slab_last_ref  = last-1;
3307 }
3308
3309
3310 /* Special version of copy_rvec:
3311  * During the copy procedure of xcurr to b, the correct PBC image is chosen
3312  * such that the copied vector ends up near its reference position xref */
3313 static inline void copy_correct_pbc_image(
3314         const rvec   xcurr,  /* copy vector xcurr ...                */
3315         rvec         b,      /* ... to b ...                         */
3316         const rvec   xref,   /* choosing the PBC image such that b ends up near xref */
3317         const matrix box,
3318         int          npbcdim)
3319 {
3320     rvec  dx;
3321     int   d, m;
3322     ivec  shift;
3323
3324
3325     /* Shortest PBC distance between the atom and its reference */
3326     rvec_sub(xcurr, xref, dx);
3327
3328     /* Determine the shift for this atom */
3329     clear_ivec(shift);
3330     for (m = npbcdim-1; m >= 0; m--)
3331     {
3332         while (dx[m] < -0.5*box[m][m])
3333         {
3334             for (d = 0; d < DIM; d++)
3335             {
3336                 dx[d] += box[m][d];
3337             }
3338             shift[m]++;
3339         }
3340         while (dx[m] >= 0.5*box[m][m])
3341         {
3342             for (d = 0; d < DIM; d++)
3343             {
3344                 dx[d] -= box[m][d];
3345             }
3346             shift[m]--;
3347         }
3348     }
3349
3350     /* Apply the shift to the position */
3351     copy_rvec(xcurr, b);
3352     shift_single_coord(box, b, shift);
3353 }
3354
3355
3356 static void init_rot_group(FILE *fplog, const t_commrec *cr,
3357                            gmx_enfrotgrp *erg,
3358                            rvec *x, gmx_mtop_t *mtop, gmx_bool bVerbose, FILE *out_slabs, const matrix box,
3359                            t_inputrec *ir, gmx_bool bOutputCenters)
3360 {
3361     rvec            coord, xref, *xdum;
3362     gmx_bool        bFlex, bColl;
3363     int             ref_firstindex, ref_lastindex;
3364     real            mass, totalmass;
3365     real            start = 0.0;
3366     double          t_start;
3367     const t_rotgrp *rotg = erg->rotg;
3368
3369
3370     /* Do we have a flexible axis? */
3371     bFlex = ISFLEX(rotg);
3372     /* Do we use a global set of coordinates? */
3373     bColl = ISCOLL(rotg);
3374
3375     /* Allocate space for collective coordinates if needed */
3376     if (bColl)
3377     {
3378         snew(erg->xc, erg->rotg->nat);
3379         snew(erg->xc_shifts, erg->rotg->nat);
3380         snew(erg->xc_eshifts, erg->rotg->nat);
3381         snew(erg->xc_old, erg->rotg->nat);
3382
3383         if (erg->rotg->eFittype == erotgFitNORM)
3384         {
3385             snew(erg->xc_ref_length, erg->rotg->nat); /* in case fit type NORM is chosen */
3386             snew(erg->xc_norm, erg->rotg->nat);
3387         }
3388     }
3389     else
3390     {
3391         snew(erg->xr_loc, erg->rotg->nat);
3392         snew(erg->x_loc_pbc, erg->rotg->nat);
3393     }
3394
3395     copy_rvec(erg->rotg->inputVec, erg->vec);
3396     snew(erg->f_rot_loc, erg->rotg->nat);
3397
3398     /* Make space for the calculation of the potential at other angles (used
3399      * for fitting only) */
3400     if (erotgFitPOT == erg->rotg->eFittype)
3401     {
3402         snew(erg->PotAngleFit, 1);
3403         snew(erg->PotAngleFit->degangle, erg->rotg->PotAngle_nstep);
3404         snew(erg->PotAngleFit->V, erg->rotg->PotAngle_nstep);
3405         snew(erg->PotAngleFit->rotmat, erg->rotg->PotAngle_nstep);
3406
3407         /* Get the set of angles around the reference angle */
3408         start = -0.5 * (erg->rotg->PotAngle_nstep - 1)*erg->rotg->PotAngle_step;
3409         for (int i = 0; i < erg->rotg->PotAngle_nstep; i++)
3410         {
3411             erg->PotAngleFit->degangle[i] = start + i*erg->rotg->PotAngle_step;
3412         }
3413     }
3414     else
3415     {
3416         erg->PotAngleFit = nullptr;
3417     }
3418
3419     /* Copy the masses so that the center can be determined. For all types of
3420      * enforced rotation, we store the masses in the erg->mc array. */
3421     snew(erg->mc, erg->rotg->nat);
3422     if (bFlex)
3423     {
3424         snew(erg->mc_sorted, erg->rotg->nat);
3425     }
3426     if (!bColl)
3427     {
3428         snew(erg->m_loc, erg->rotg->nat);
3429     }
3430     totalmass = 0.0;
3431     int molb  = 0;
3432     for (int i = 0; i < erg->rotg->nat; i++)
3433     {
3434         if (erg->rotg->bMassW)
3435         {
3436             mass = mtopGetAtomMass(mtop, erg->rotg->ind[i], &molb);
3437         }
3438         else
3439         {
3440             mass = 1.0;
3441         }
3442         erg->mc[i] = mass;
3443         totalmass += mass;
3444     }
3445     erg->invmass = 1.0/totalmass;
3446
3447     /* Set xc_ref_center for any rotation potential */
3448     if ((erg->rotg->eType == erotgISO) || (erg->rotg->eType == erotgPM) || (erg->rotg->eType == erotgRM) || (erg->rotg->eType == erotgRM2))
3449     {
3450         /* Set the pivot point for the fixed, stationary-axis potentials. This
3451          * won't change during the simulation */
3452         copy_rvec(erg->rotg->pivot, erg->xc_ref_center);
3453         copy_rvec(erg->rotg->pivot, erg->xc_center    );
3454     }
3455     else
3456     {
3457         /* Center of the reference positions */
3458         get_center(erg->rotg->x_ref, erg->mc, erg->rotg->nat, erg->xc_ref_center);
3459
3460         /* Center of the actual positions */
3461         if (MASTER(cr))
3462         {
3463             snew(xdum, erg->rotg->nat);
3464             for (int i = 0; i < erg->rotg->nat; i++)
3465             {
3466                 int ii = erg->rotg->ind[i];
3467                 copy_rvec(x[ii], xdum[i]);
3468             }
3469             get_center(xdum, erg->mc, erg->rotg->nat, erg->xc_center);
3470             sfree(xdum);
3471         }
3472 #if GMX_MPI
3473         if (PAR(cr))
3474         {
3475             gmx_bcast(sizeof(erg->xc_center), erg->xc_center, cr);
3476         }
3477 #endif
3478     }
3479
3480     if (bColl)
3481     {
3482         /* Save the original (whole) set of positions in xc_old such that at later
3483          * steps the rotation group can always be made whole again. If the simulation is
3484          * restarted, we compute the starting reference positions (given the time)
3485          * and assume that the correct PBC image of each position is the one nearest
3486          * to the current reference */
3487         if (MASTER(cr))
3488         {
3489             /* Calculate the rotation matrix for this angle: */
3490             t_start       = ir->init_t + ir->init_step*ir->delta_t;
3491             erg->degangle = erg->rotg->rate * t_start;
3492             calc_rotmat(erg->vec, erg->degangle, erg->rotmat);
3493
3494             for (int i = 0; i < erg->rotg->nat; i++)
3495             {
3496                 int ii = erg->rotg->ind[i];
3497
3498                 /* Subtract pivot, rotate, and add pivot again. This will yield the
3499                  * reference position for time t */
3500                 rvec_sub(erg->rotg->x_ref[i], erg->xc_ref_center, coord);
3501                 mvmul(erg->rotmat, coord, xref);
3502                 rvec_inc(xref, erg->xc_ref_center);
3503
3504                 copy_correct_pbc_image(x[ii], erg->xc_old[i], xref, box, 3);
3505             }
3506         }
3507 #if GMX_MPI
3508         if (PAR(cr))
3509         {
3510             gmx_bcast(erg->rotg->nat*sizeof(erg->xc_old[0]), erg->xc_old, cr);
3511         }
3512 #endif
3513     }
3514
3515     if ( (erg->rotg->eType != erotgFLEX) && (erg->rotg->eType != erotgFLEX2) )
3516     {
3517         /* Put the reference positions into origin: */
3518         for (int i = 0; i < erg->rotg->nat; i++)
3519         {
3520             rvec_dec(erg->rotg->x_ref[i], erg->xc_ref_center);
3521         }
3522     }
3523
3524     /* Enforced rotation with flexible axis */
3525     if (bFlex)
3526     {
3527         /* Calculate maximum beta value from minimum gaussian (performance opt.) */
3528         erg->max_beta = calc_beta_max(erg->rotg->min_gaussian, erg->rotg->slab_dist);
3529
3530         /* Determine the smallest and largest coordinate with respect to the rotation vector */
3531         get_firstlast_atom_ref(erg, &ref_firstindex, &ref_lastindex);
3532
3533         /* From the extreme positions of the reference group, determine the first
3534          * and last slab of the reference. */
3535         get_firstlast_slab_ref(erg, erg->mc, ref_firstindex, ref_lastindex);
3536
3537         /* Allocate memory for the slabs */
3538         allocate_slabs(erg, fplog, bVerbose);
3539
3540         /* Flexible rotation: determine the reference centers for the rest of the simulation */
3541         erg->slab_first = erg->slab_first_ref;
3542         erg->slab_last  = erg->slab_last_ref;
3543         get_slab_centers(erg, erg->rotg->x_ref, erg->mc, -1, out_slabs, bOutputCenters, TRUE);
3544
3545         /* Length of each x_rotref vector from center (needed if fit routine NORM is chosen): */
3546         if (erg->rotg->eFittype == erotgFitNORM)
3547         {
3548             for (int i = 0; i < erg->rotg->nat; i++)
3549             {
3550                 rvec_sub(erg->rotg->x_ref[i], erg->xc_ref_center, coord);
3551                 erg->xc_ref_length[i] = norm(coord);
3552             }
3553         }
3554     }
3555 }
3556
3557 /* Calculate the size of the MPI buffer needed in reduce_output() */
3558 static int calc_mpi_bufsize(const gmx_enfrot *er)
3559
3560 {
3561     int count_total = 0;
3562     for (int g = 0; g < er->rot->ngrp; g++)
3563     {
3564         const t_rotgrp      *rotg = &er->rot->grp[g];
3565         const gmx_enfrotgrp *erg  = &er->enfrotgrp[g];
3566
3567         /* Count the items that are transferred for this group: */
3568         int count_group = 4; /* V, torque, angle, weight */
3569
3570         /* Add the maximum number of slabs for flexible groups */
3571         if (ISFLEX(rotg))
3572         {
3573             count_group += erg->slab_last_ref - erg->slab_first_ref + 1;
3574         }
3575
3576         /* Add space for the potentials at different angles: */
3577         if (erotgFitPOT == erg->rotg->eFittype)
3578         {
3579             count_group += erg->rotg->PotAngle_nstep;
3580         }
3581
3582         /* Add to the total number: */
3583         count_total += count_group;
3584     }
3585
3586     return count_total;
3587 }
3588
3589
3590 std::unique_ptr<gmx::EnforcedRotation>
3591 init_rot(FILE *fplog, t_inputrec *ir, int nfile, const t_filenm fnm[],
3592          const t_commrec *cr, gmx::LocalAtomSetManager * atomSets, const t_state *globalState, gmx_mtop_t *mtop, const gmx_output_env_t *oenv,
3593          const MdrunOptions &mdrunOptions)
3594 {
3595     int             nat_max = 0;       /* Size of biggest rotation group */
3596     rvec           *x_pbc   = nullptr; /* Space for the pbc-correct atom positions */
3597
3598     if (MASTER(cr) && mdrunOptions.verbose)
3599     {
3600         fprintf(stdout, "%s Initializing ...\n", RotStr);
3601     }
3602
3603     auto        enforcedRotation = gmx::compat::make_unique<gmx::EnforcedRotation>();
3604     gmx_enfrot *er               = enforcedRotation->getLegacyEnfrot();
3605     // TODO When this module implements IMdpOptions, the ownership will become more clear.
3606     er->rot         = ir->rot;
3607     er->appendFiles = mdrunOptions.continuationOptions.appendFiles;
3608
3609     /* When appending, skip first output to avoid duplicate entries in the data files */
3610     if (er->appendFiles)
3611     {
3612         er->bOut = FALSE;
3613     }
3614     else
3615     {
3616         er->bOut = TRUE;
3617     }
3618
3619     if (MASTER(cr) && er->bOut)
3620     {
3621         please_cite(fplog, "Kutzner2011");
3622     }
3623
3624     /* Output every step for reruns */
3625     if (mdrunOptions.rerun)
3626     {
3627         if (nullptr != fplog)
3628         {
3629             fprintf(fplog, "%s rerun - will write rotation output every available step.\n", RotStr);
3630         }
3631         er->nstrout = 1;
3632         er->nstsout = 1;
3633     }
3634     else
3635     {
3636         er->nstrout = er->rot->nstrout;
3637         er->nstsout = er->rot->nstsout;
3638     }
3639
3640     er->out_slabs = nullptr;
3641     if (MASTER(cr) && HaveFlexibleGroups(er->rot) )
3642     {
3643         er->out_slabs = open_slab_out(opt2fn("-rs", nfile, fnm), er);
3644     }
3645
3646     if (MASTER(cr))
3647     {
3648         /* Remove pbc, make molecule whole.
3649          * When ir->bContinuation=TRUE this has already been done, but ok. */
3650         snew(x_pbc, mtop->natoms);
3651         copy_rvecn(as_rvec_array(globalState->x.data()), x_pbc, 0, mtop->natoms);
3652         do_pbc_first_mtop(nullptr, ir->ePBC, globalState->box, mtop, x_pbc);
3653         /* All molecules will be whole now, but not necessarily in the home box.
3654          * Additionally, if a rotation group consists of more than one molecule
3655          * (e.g. two strands of DNA), each one of them can end up in a different
3656          * periodic box. This is taken care of in init_rot_group.  */
3657     }
3658
3659     /* Allocate space for the per-rotation-group data: */
3660     er->enfrotgrp.resize(er->rot->ngrp);
3661     int groupIndex = 0;
3662     for (auto &ergRef : er->enfrotgrp)
3663     {
3664         gmx_enfrotgrp *erg = &ergRef;
3665         erg->rotg       = &er->rot->grp[groupIndex];
3666         erg->atomSet    = gmx::compat::make_unique<gmx::LocalAtomSet>(atomSets->add({erg->rotg->ind, erg->rotg->ind + erg->rotg->nat}));
3667         erg->groupIndex = groupIndex;
3668
3669         if (nullptr != fplog)
3670         {
3671             fprintf(fplog, "%s group %d type '%s'\n", RotStr, groupIndex, erotg_names[erg->rotg->eType]);
3672         }
3673
3674         if (erg->rotg->nat > 0)
3675         {
3676             nat_max = std::max(nat_max, erg->rotg->nat);
3677
3678             init_rot_group(fplog, cr, erg, x_pbc, mtop, mdrunOptions.verbose, er->out_slabs, MASTER(cr) ? globalState->box : nullptr, ir,
3679                            !er->appendFiles); /* Do not output the reference centers
3680                                                * again if we are appending */
3681         }
3682         ++groupIndex;
3683     }
3684
3685     /* Allocate space for enforced rotation buffer variables */
3686     er->bufsize = nat_max;
3687     snew(er->data, nat_max);
3688     snew(er->xbuf, nat_max);
3689     snew(er->mbuf, nat_max);
3690
3691     /* Buffers for MPI reducing torques, angles, weights (for each group), and V */
3692     if (PAR(cr))
3693     {
3694         er->mpi_bufsize = calc_mpi_bufsize(er) + 100; /* larger to catch errors */
3695         snew(er->mpi_inbuf, er->mpi_bufsize);
3696         snew(er->mpi_outbuf, er->mpi_bufsize);
3697     }
3698     else
3699     {
3700         er->mpi_bufsize = 0;
3701         er->mpi_inbuf   = nullptr;
3702         er->mpi_outbuf  = nullptr;
3703     }
3704
3705     /* Only do I/O on the MASTER */
3706     er->out_angles  = nullptr;
3707     er->out_rot     = nullptr;
3708     er->out_torque  = nullptr;
3709     if (MASTER(cr))
3710     {
3711         er->out_rot = open_rot_out(opt2fn("-ro", nfile, fnm), oenv, er);
3712
3713         if (er->nstsout > 0)
3714         {
3715             if (HaveFlexibleGroups(er->rot) || HavePotFitGroups(er->rot) )
3716             {
3717                 er->out_angles  = open_angles_out(opt2fn("-ra", nfile, fnm), er);
3718             }
3719             if (HaveFlexibleGroups(er->rot) )
3720             {
3721                 er->out_torque  = open_torque_out(opt2fn("-rt", nfile, fnm), er);
3722             }
3723         }
3724
3725         sfree(x_pbc);
3726     }
3727     return enforcedRotation;
3728 }
3729
3730 /* Rotate the local reference positions and store them in
3731  * erg->xr_loc[0...(nat_loc-1)]
3732  *
3733  * Note that we already subtracted u or y_c from the reference positions
3734  * in init_rot_group().
3735  */
3736 static void rotate_local_reference(gmx_enfrotgrp *erg)
3737 {
3738     const auto &collectiveRotationGroupIndex = erg->atomSet->collectiveIndex();
3739     for (size_t i = 0; i < erg->atomSet->numAtomsLocal(); i++)
3740     {
3741         /* Index of this rotation group atom with respect to the whole rotation group */
3742         int ii = collectiveRotationGroupIndex[i];
3743         /* Rotate */
3744         mvmul(erg->rotmat, erg->rotg->x_ref[ii], erg->xr_loc[i]);
3745     }
3746 }
3747
3748
3749 /* Select the PBC representation for each local x position and store that
3750  * for later usage. We assume the right PBC image of an x is the one nearest to
3751  * its rotated reference */
3752 static void choose_pbc_image(rvec x[],
3753                              gmx_enfrotgrp *erg,
3754                              matrix box, int npbcdim)
3755 {
3756     const auto &localRotationGroupIndex = erg->atomSet->localIndex();
3757     for (gmx::index i = 0; i < localRotationGroupIndex.size(); i++)
3758     {
3759         /* Index of a rotation group atom  */
3760         int ii = localRotationGroupIndex[i];
3761
3762         /* Get the correctly rotated reference position. The pivot was already
3763          * subtracted in init_rot_group() from the reference positions. Also,
3764          * the reference positions have already been rotated in
3765          * rotate_local_reference(). For the current reference position we thus
3766          * only need to add the pivot again. */
3767         rvec xref;
3768         copy_rvec(erg->xr_loc[i], xref);
3769         rvec_inc(xref, erg->xc_ref_center);
3770
3771         copy_correct_pbc_image(x[ii], erg->x_loc_pbc[i], xref, box, npbcdim);
3772     }
3773 }
3774
3775
3776 void do_rotation(const t_commrec       *cr,
3777                  gmx_enfrot            *er,
3778                  matrix                 box,
3779                  rvec                   x[],
3780                  real                   t,
3781                  int64_t                step,
3782                  gmx_bool               bNS)
3783 {
3784     gmx_bool        outstep_slab, outstep_rot;
3785     gmx_bool        bColl;
3786     rvec            transvec;
3787     gmx_potfit     *fit = nullptr; /* For fit type 'potential' determine the fit
3788                                         angle via the potential minimum            */
3789
3790 #ifdef TAKETIME
3791     double t0;
3792 #endif
3793
3794     /* When to output in main rotation output file */
3795     outstep_rot  = do_per_step(step, er->nstrout) && er->bOut;
3796     /* When to output per-slab data */
3797     outstep_slab = do_per_step(step, er->nstsout) && er->bOut;
3798
3799     /* Output time into rotation output file */
3800     if (outstep_rot && MASTER(cr))
3801     {
3802         fprintf(er->out_rot, "%12.3e", t);
3803     }
3804
3805     /**************************************************************************/
3806     /* First do ALL the communication! */
3807     for (auto &ergRef : er->enfrotgrp)
3808     {
3809         gmx_enfrotgrp  *erg  = &ergRef;
3810         const t_rotgrp *rotg = erg->rotg;
3811
3812         /* Do we use a collective (global) set of coordinates? */
3813         bColl = ISCOLL(rotg);
3814
3815         /* Calculate the rotation matrix for this angle: */
3816         erg->degangle = rotg->rate * t;
3817         calc_rotmat(erg->vec, erg->degangle, erg->rotmat);
3818
3819         if (bColl)
3820         {
3821             /* Transfer the rotation group's positions such that every node has
3822              * all of them. Every node contributes its local positions x and stores
3823              * it in the collective erg->xc array. */
3824             communicate_group_positions(cr, erg->xc, erg->xc_shifts, erg->xc_eshifts, bNS,
3825                                         x, rotg->nat, erg->atomSet->numAtomsLocal(), erg->atomSet->localIndex().data(), erg->atomSet->collectiveIndex().data(), erg->xc_old, box);
3826         }
3827         else
3828         {
3829             /* Fill the local masses array;
3830              * this array changes in DD/neighborsearching steps */
3831             if (bNS)
3832             {
3833                 const auto &collectiveRotationGroupIndex = erg->atomSet->collectiveIndex();
3834                 for (gmx::index i = 0; i < collectiveRotationGroupIndex.size(); i++)
3835                 {
3836                     /* Index of local atom w.r.t. the collective rotation group */
3837                     int ii        = collectiveRotationGroupIndex[i];
3838                     erg->m_loc[i] = erg->mc[ii];
3839                 }
3840             }
3841
3842             /* Calculate Omega*(y_i-y_c) for the local positions */
3843             rotate_local_reference(erg);
3844
3845             /* Choose the nearest PBC images of the group atoms with respect
3846              * to the rotated reference positions */
3847             choose_pbc_image(x, erg, box, 3);
3848
3849             /* Get the center of the rotation group */
3850             if ( (rotg->eType == erotgISOPF) || (rotg->eType == erotgPMPF) )
3851             {
3852                 get_center_comm(cr, erg->x_loc_pbc, erg->m_loc, erg->atomSet->numAtomsLocal(), rotg->nat, erg->xc_center);
3853             }
3854         }
3855
3856     } /* End of loop over rotation groups */
3857
3858     /**************************************************************************/
3859     /* Done communicating, we can start to count cycles for the load balancing now ... */
3860     if (DOMAINDECOMP(cr))
3861     {
3862         ddReopenBalanceRegionCpu(cr->dd);
3863     }
3864
3865 #ifdef TAKETIME
3866     t0 = MPI_Wtime();
3867 #endif
3868
3869     for (auto &ergRef : er->enfrotgrp)
3870     {
3871         gmx_enfrotgrp  *erg  = &ergRef;
3872         const t_rotgrp *rotg = erg->rotg;
3873
3874         if (outstep_rot && MASTER(cr))
3875         {
3876             fprintf(er->out_rot, "%12.4f", erg->degangle);
3877         }
3878
3879         /* Calculate angles and rotation matrices for potential fitting: */
3880         if ( (outstep_rot || outstep_slab) && (erotgFitPOT == rotg->eFittype) )
3881         {
3882             fit = erg->PotAngleFit;
3883             for (int i = 0; i < rotg->PotAngle_nstep; i++)
3884             {
3885                 calc_rotmat(erg->vec, erg->degangle + fit->degangle[i], fit->rotmat[i]);
3886
3887                 /* Clear value from last step */
3888                 erg->PotAngleFit->V[i] = 0.0;
3889             }
3890         }
3891
3892         /* Clear values from last time step */
3893         erg->V        = 0.0;
3894         erg->torque_v = 0.0;
3895         erg->angle_v  = 0.0;
3896         erg->weight_v = 0.0;
3897
3898         switch (rotg->eType)
3899         {
3900             case erotgISO:
3901             case erotgISOPF:
3902             case erotgPM:
3903             case erotgPMPF:
3904                 do_fixed(erg, outstep_rot, outstep_slab);
3905                 break;
3906             case erotgRM:
3907                 do_radial_motion(erg, outstep_rot, outstep_slab);
3908                 break;
3909             case erotgRMPF:
3910                 do_radial_motion_pf(erg, x, box, outstep_rot, outstep_slab);
3911                 break;
3912             case erotgRM2:
3913             case erotgRM2PF:
3914                 do_radial_motion2(erg, x, box, outstep_rot, outstep_slab);
3915                 break;
3916             case erotgFLEXT:
3917             case erotgFLEX2T:
3918                 /* Subtract the center of the rotation group from the collective positions array
3919                  * Also store the center in erg->xc_center since it needs to be subtracted
3920                  * in the low level routines from the local coordinates as well */
3921                 get_center(erg->xc, erg->mc, rotg->nat, erg->xc_center);
3922                 svmul(-1.0, erg->xc_center, transvec);
3923                 translate_x(erg->xc, rotg->nat, transvec);
3924                 do_flexible(MASTER(cr), er, erg, x, box, t, outstep_rot, outstep_slab);
3925                 break;
3926             case erotgFLEX:
3927             case erotgFLEX2:
3928                 /* Do NOT subtract the center of mass in the low level routines! */
3929                 clear_rvec(erg->xc_center);
3930                 do_flexible(MASTER(cr), er, erg, x, box, t, outstep_rot, outstep_slab);
3931                 break;
3932             default:
3933                 gmx_fatal(FARGS, "No such rotation potential.");
3934         }
3935     }
3936
3937 #ifdef TAKETIME
3938     if (MASTER(cr))
3939     {
3940         fprintf(stderr, "%s calculation (step %d) took %g seconds.\n", RotStr, step, MPI_Wtime()-t0);
3941     }
3942 #endif
3943 }