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