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