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