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