added os-specific defines from cmake required by memtestG80
[gromacs/qmmm-gamess-us.git] / src / mdlib / coupling.c
blobb2c75c7477490666149ffea89e8e450bdfc4e266
1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
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 * VERSION 3.2.0
10 * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
11 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
12 * Copyright (c) 2001-2004, The GROMACS development team,
13 * check out http://www.gromacs.org for more information.
15 * This program is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU General Public License
17 * as published by the Free Software Foundation; either version 2
18 * of the License, or (at your option) any later version.
20 * If you want to redistribute modifications, please consider that
21 * scientific software is very special. Version control is crucial -
22 * bugs must be traceable. We will be happy to consider code for
23 * inclusion in the official distribution, but derived work must not
24 * be called official GROMACS. Details are found in the README & COPYING
25 * files - if they are missing, get the official version at www.gromacs.org.
27 * To help us fund GROMACS development, we humbly ask that you cite
28 * the papers on the package - you can find them in the top README file.
30 * For more info, check our website at http://www.gromacs.org
32 * And Hey:
33 * GROwing Monsters And Cloning Shrimps
35 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
39 #include "typedefs.h"
40 #include "smalloc.h"
41 #include "update.h"
42 #include "vec.h"
43 #include "macros.h"
44 #include "physics.h"
45 #include "names.h"
46 #include "gmx_fatal.h"
47 #include "txtdump.h"
48 #include "nrnb.h"
49 #include "gmx_random.h"
51 #define NTROTTERCALLS 5
52 #define NTROTTERPARTS 3
54 /* these integration routines are only references inside this file */
55 static void NHC_trotter(t_grpopts *opts,int nvar, gmx_ekindata_t *ekind,real dtfull,
56 double xi[],double vxi[], double scalefac[], real *veta, t_extmass *MassQ, bool bEkinAveVel)
59 /* general routine for both barostat and thermostat nose hoover chains */
61 int i,j,mi,mj,jmax,nd;
62 double Ekin,Efac,reft,kT;
63 double dt;
64 t_grp_tcstat *tcstat;
65 double *ivxi,*ixi;
66 double *iQinv;
67 double *GQ;
68 bool bBarostat;
69 int mstepsi, mstepsj;
70 int ns = SUZUKI_YOSHIDA_NUM; /* set the degree of integration in the types/state.h file */
71 int nh = opts->nhchainlength;
73 snew(GQ,nh);
74 mstepsi = mstepsj = ns;
76 /* if scalefac is NULL, we are doing the NHC of the barostat */
78 bBarostat = FALSE;
79 if (scalefac == NULL) {
80 bBarostat = TRUE;
83 for (i=0; i<nvar; i++)
86 /* make it easier to iterate by selecting
87 out the sub-array that corresponds to this T group */
89 ivxi = &vxi[i*nh];
90 ixi = &xi[i*nh];
91 if (bBarostat) {
92 iQinv = &(MassQ->QPinv[i*nh]);
93 nd = 1; /* THIS WILL CHANGE IF NOT ISOTROPIC */
94 reft = max(0.0,opts->ref_t[0]);
95 Ekin = sqr(*veta)/MassQ->Winv;
96 } else {
97 iQinv = &(MassQ->Qinv[i*nh]);
98 tcstat = &ekind->tcstat[i];
99 nd = opts->nrdf[i];
100 reft = max(0.0,opts->ref_t[i]);
101 if (bEkinAveVel)
103 Ekin = 2*trace(tcstat->ekinf)*tcstat->ekinscalef_nhc;
104 } else {
105 Ekin = 2*trace(tcstat->ekinh)*tcstat->ekinscaleh_nhc;
108 kT = BOLTZ*reft;
110 for(mi=0;mi<mstepsi;mi++)
112 for(mj=0;mj<mstepsj;mj++)
114 /* weighting for this step using Suzuki-Yoshida integration - fixed at 5 */
115 dt = sy_const[ns][mj] * dtfull / mstepsi;
117 /* compute the thermal forces */
118 GQ[0] = iQinv[0]*(Ekin - nd*kT);
120 for (j=0;j<nh-1;j++)
122 if (iQinv[j+1] > 0) {
123 /* we actually don't need to update here if we save the
124 state of the GQ, but it's easier to just recompute*/
125 GQ[j+1] = iQinv[j+1]*((sqr(ivxi[j])/iQinv[j])-kT);
126 } else {
127 GQ[j+1] = 0;
131 ivxi[nh-1] += 0.25*dt*GQ[nh-1];
132 for (j=nh-1;j>0;j--)
134 Efac = exp(-0.125*dt*ivxi[j]);
135 ivxi[j-1] = Efac*(ivxi[j-1]*Efac + 0.25*dt*GQ[j-1]);
138 Efac = exp(-0.5*dt*ivxi[0]);
139 if (bBarostat) {
140 *veta *= Efac;
141 } else {
142 scalefac[i] *= Efac;
144 Ekin *= (Efac*Efac);
146 /* Issue - if the KE is an average of the last and the current temperatures, then we might not be
147 able to scale the kinetic energy directly with this factor. Might take more bookkeeping -- have to
148 think about this a bit more . . . */
150 GQ[0] = iQinv[0]*(Ekin - nd*kT);
152 /* update thermostat positions */
153 for (j=0;j<nh;j++)
155 ixi[j] += 0.5*dt*ivxi[j];
158 for (j=0;j<nh-1;j++)
160 Efac = exp(-0.125*dt*ivxi[j+1]);
161 ivxi[j] = Efac*(ivxi[j]*Efac + 0.25*dt*GQ[j]);
162 if (iQinv[j+1] > 0) {
163 GQ[j+1] = iQinv[j+1]*((sqr(ivxi[j])/iQinv[j])-kT);
164 } else {
165 GQ[j+1] = 0;
168 ivxi[nh-1] += 0.25*dt*GQ[nh-1];
172 sfree(GQ);
175 static void boxv_trotter(t_inputrec *ir, real *veta, real dt, tensor box,
176 gmx_ekindata_t *ekind, tensor vir, real pcorr, real ecorr, t_extmass *MassQ)
179 real pscal;
180 double alpha;
181 int i,j,d,n,nwall;
182 real T,GW,vol;
183 tensor Winvm,ekinmod,localpres;
185 /* The heat bath is coupled to a separate barostat, the last temperature group. In the
186 2006 Tuckerman et al paper., the order is iL_{T_baro} iL {T_part}
189 if (ir->epct==epctSEMIISOTROPIC)
191 nwall = 2;
193 else
195 nwall = 3;
198 /* eta is in pure units. veta is in units of ps^-1. GW is in
199 units of ps^-2. However, eta has a reference of 1 nm^3, so care must be
200 taken to use only RATIOS of eta in updating the volume. */
202 /* we take the partial pressure tensors, modify the
203 kinetic energy tensor, and recovert to pressure */
205 if (ir->opts.nrdf[0]==0)
207 gmx_fatal(FARGS,"Barostat is coupled to a T-group with no degrees of freedom\n");
209 /* alpha factor for phase space volume, then multiply by the ekin scaling factor. */
210 alpha = 1.0 + DIM/((double)ir->opts.nrdf[0]);
211 alpha *= ekind->tcstat[0].ekinscalef_nhc;
212 msmul(ekind->ekin,alpha,ekinmod);
214 /* for now, we use Elr = 0, because if you want to get it right, you
215 really should be using PME. Maybe print a warning? */
217 pscal = calc_pres(ir->ePBC,nwall,box,ekinmod,vir,localpres,0.0) + pcorr;
219 vol = det(box);
220 GW = (vol*(MassQ->Winv/PRESFAC))*(DIM*pscal - trace(ir->ref_p)); /* W is in ps^2 * bar * nm^3 */
222 *veta += 0.5*dt*GW;
226 * This file implements temperature and pressure coupling algorithms:
227 * For now only the Weak coupling and the modified weak coupling.
229 * Furthermore computation of pressure and temperature is done here
233 real calc_pres(int ePBC,int nwall,matrix box,tensor ekin,tensor vir,
234 tensor pres,real Elr)
236 int n,m;
237 real fac,Plr;
239 if (ePBC==epbcNONE || (ePBC==epbcXY && nwall!=2))
240 clear_mat(pres);
241 else {
242 /* Uitzoeken welke ekin hier van toepassing is, zie Evans & Morris - E.
243 * Wrs. moet de druktensor gecorrigeerd worden voor de netto stroom in
244 * het systeem...
247 /* Long range correction for periodic systems, see
248 * Neumann et al. JCP
249 * divide by 6 because it is multiplied by fac later on.
250 * If Elr = 0, no correction is made.
253 /* This formula should not be used with Ewald or PME,
254 * where the full long-range virial is calculated. EL 990823
256 Plr = Elr/6.0;
258 fac=PRESFAC*2.0/det(box);
259 for(n=0; (n<DIM); n++)
260 for(m=0; (m<DIM); m++)
261 pres[n][m]=(ekin[n][m]-vir[n][m]+Plr)*fac;
263 if (debug) {
264 pr_rvecs(debug,0,"PC: pres",pres,DIM);
265 pr_rvecs(debug,0,"PC: ekin",ekin,DIM);
266 pr_rvecs(debug,0,"PC: vir ",vir, DIM);
267 pr_rvecs(debug,0,"PC: box ",box, DIM);
270 return trace(pres)/DIM;
273 real calc_temp(real ekin,real nrdf)
275 if (nrdf > 0)
276 return (2.0*ekin)/(nrdf*BOLTZ);
277 else
278 return 0;
281 void parrinellorahman_pcoupl(FILE *fplog,gmx_large_int_t step,
282 t_inputrec *ir,real dt,tensor pres,
283 tensor box,tensor box_rel,tensor boxv,
284 tensor M,matrix mu,bool bFirstStep)
286 /* This doesn't do any coordinate updating. It just
287 * integrates the box vector equations from the calculated
288 * acceleration due to pressure difference. We also compute
289 * the tensor M which is used in update to couple the particle
290 * coordinates to the box vectors.
292 * In Nose and Klein (Mol.Phys 50 (1983) no 5., p 1055) this is
293 * given as
294 * -1 . . -1
295 * M_nk = (h') * (h' * h + h' h) * h
297 * with the dots denoting time derivatives and h is the transformation from
298 * the scaled frame to the real frame, i.e. the TRANSPOSE of the box.
299 * This also goes for the pressure and M tensors - they are transposed relative
300 * to ours. Our equation thus becomes:
302 * -1 . . -1
303 * M_gmx = M_nk' = b * (b * b' + b * b') * b'
305 * where b is the gromacs box matrix.
306 * Our box accelerations are given by
307 * .. ..
308 * b = vol/W inv(box') * (P-ref_P) (=h')
311 int d,n;
312 tensor winv;
313 real vol=box[XX][XX]*box[YY][YY]*box[ZZ][ZZ];
314 real atot,arel,change,maxchange,xy_pressure;
315 tensor invbox,pdiff,t1,t2;
317 real maxl;
319 m_inv_ur0(box,invbox);
321 if (!bFirstStep) {
322 /* Note that PRESFAC does not occur here.
323 * The pressure and compressibility always occur as a product,
324 * therefore the pressure unit drops out.
326 maxl=max(box[XX][XX],box[YY][YY]);
327 maxl=max(maxl,box[ZZ][ZZ]);
328 for(d=0;d<DIM;d++)
329 for(n=0;n<DIM;n++)
330 winv[d][n]=
331 (4*M_PI*M_PI*ir->compress[d][n])/(3*ir->tau_p*ir->tau_p*maxl);
333 m_sub(pres,ir->ref_p,pdiff);
335 if(ir->epct==epctSURFACETENSION) {
336 /* Unlike Berendsen coupling it might not be trivial to include a z
337 * pressure correction here? On the other hand we don't scale the
338 * box momentarily, but change accelerations, so it might not be crucial.
340 xy_pressure=0.5*(pres[XX][XX]+pres[YY][YY]);
341 for(d=0;d<ZZ;d++)
342 pdiff[d][d]=(xy_pressure-(pres[ZZ][ZZ]-ir->ref_p[d][d]/box[d][d]));
345 tmmul(invbox,pdiff,t1);
346 /* Move the off-diagonal elements of the 'force' to one side to ensure
347 * that we obey the box constraints.
349 for(d=0;d<DIM;d++) {
350 for(n=0;n<d;n++) {
351 t1[d][n] += t1[n][d];
352 t1[n][d] = 0;
356 switch (ir->epct) {
357 case epctANISOTROPIC:
358 for(d=0;d<DIM;d++)
359 for(n=0;n<=d;n++)
360 t1[d][n] *= winv[d][n]*vol;
361 break;
362 case epctISOTROPIC:
363 /* calculate total volume acceleration */
364 atot=box[XX][XX]*box[YY][YY]*t1[ZZ][ZZ]+
365 box[XX][XX]*t1[YY][YY]*box[ZZ][ZZ]+
366 t1[XX][XX]*box[YY][YY]*box[ZZ][ZZ];
367 arel=atot/(3*vol);
368 /* set all RELATIVE box accelerations equal, and maintain total V
369 * change speed */
370 for(d=0;d<DIM;d++)
371 for(n=0;n<=d;n++)
372 t1[d][n] = winv[0][0]*vol*arel*box[d][n];
373 break;
374 case epctSEMIISOTROPIC:
375 case epctSURFACETENSION:
376 /* Note the correction to pdiff above for surftens. coupling */
378 /* calculate total XY volume acceleration */
379 atot=box[XX][XX]*t1[YY][YY]+t1[XX][XX]*box[YY][YY];
380 arel=atot/(2*box[XX][XX]*box[YY][YY]);
381 /* set RELATIVE XY box accelerations equal, and maintain total V
382 * change speed. Dont change the third box vector accelerations */
383 for(d=0;d<ZZ;d++)
384 for(n=0;n<=d;n++)
385 t1[d][n] = winv[d][n]*vol*arel*box[d][n];
386 for(n=0;n<DIM;n++)
387 t1[ZZ][n] *= winv[d][n]*vol;
388 break;
389 default:
390 gmx_fatal(FARGS,"Parrinello-Rahman pressure coupling type %s "
391 "not supported yet\n",EPCOUPLTYPETYPE(ir->epct));
392 break;
395 maxchange=0;
396 for(d=0;d<DIM;d++)
397 for(n=0;n<=d;n++) {
398 boxv[d][n] += dt*t1[d][n];
400 /* We do NOT update the box vectors themselves here, since
401 * we need them for shifting later. It is instead done last
402 * in the update() routine.
405 /* Calculate the change relative to diagonal elements-
406 since it's perfectly ok for the off-diagonal ones to
407 be zero it doesn't make sense to check the change relative
408 to its current size.
411 change=fabs(dt*boxv[d][n]/box[d][d]);
413 if (change>maxchange)
414 maxchange=change;
417 if (maxchange > 0.01 && fplog) {
418 char buf[22];
419 fprintf(fplog,"\nStep %s Warning: Pressure scaling more than 1%%.\n",
420 gmx_step_str(step,buf));
424 preserve_box_shape(ir,box_rel,boxv);
426 mtmul(boxv,box,t1); /* t1=boxv * b' */
427 mmul(invbox,t1,t2);
428 mtmul(t2,invbox,M);
430 /* Determine the scaling matrix mu for the coordinates */
431 for(d=0;d<DIM;d++)
432 for(n=0;n<=d;n++)
433 t1[d][n] = box[d][n] + dt*boxv[d][n];
434 preserve_box_shape(ir,box_rel,t1);
435 /* t1 is the box at t+dt, determine mu as the relative change */
436 mmul_ur0(invbox,t1,mu);
439 void berendsen_pcoupl(FILE *fplog,gmx_large_int_t step,
440 t_inputrec *ir,real dt, tensor pres,matrix box,
441 matrix mu)
443 int d,n;
444 real scalar_pressure, xy_pressure, p_corr_z;
445 char *ptr,buf[STRLEN];
448 * Calculate the scaling matrix mu
450 scalar_pressure=0;
451 xy_pressure=0;
452 for(d=0; d<DIM; d++) {
453 scalar_pressure += pres[d][d]/DIM;
454 if (d != ZZ)
455 xy_pressure += pres[d][d]/(DIM-1);
457 /* Pressure is now in bar, everywhere. */
458 #define factor(d,m) (ir->compress[d][m]*dt/ir->tau_p)
460 /* mu has been changed from pow(1+...,1/3) to 1+.../3, since this is
461 * necessary for triclinic scaling
463 clear_mat(mu);
464 switch (ir->epct) {
465 case epctISOTROPIC:
466 for(d=0; d<DIM; d++)
468 mu[d][d] = 1.0 - factor(d,d)*(ir->ref_p[d][d] - scalar_pressure) /DIM;
470 break;
471 case epctSEMIISOTROPIC:
472 for(d=0; d<ZZ; d++)
473 mu[d][d] = 1.0 - factor(d,d)*(ir->ref_p[d][d]-xy_pressure)/DIM;
474 mu[ZZ][ZZ] =
475 1.0 - factor(ZZ,ZZ)*(ir->ref_p[ZZ][ZZ] - pres[ZZ][ZZ])/DIM;
476 break;
477 case epctANISOTROPIC:
478 for(d=0; d<DIM; d++)
479 for(n=0; n<DIM; n++)
480 mu[d][n] = (d==n ? 1.0 : 0.0)
481 -factor(d,n)*(ir->ref_p[d][n] - pres[d][n])/DIM;
482 break;
483 case epctSURFACETENSION:
484 /* ir->ref_p[0/1] is the reference surface-tension times *
485 * the number of surfaces */
486 if (ir->compress[ZZ][ZZ])
487 p_corr_z = dt/ir->tau_p*(ir->ref_p[ZZ][ZZ] - pres[ZZ][ZZ]);
488 else
489 /* when the compressibity is zero, set the pressure correction *
490 * in the z-direction to zero to get the correct surface tension */
491 p_corr_z = 0;
492 mu[ZZ][ZZ] = 1.0 - ir->compress[ZZ][ZZ]*p_corr_z;
493 for(d=0; d<DIM-1; d++)
494 mu[d][d] = 1.0 + factor(d,d)*(ir->ref_p[d][d]/(mu[ZZ][ZZ]*box[ZZ][ZZ])
495 - (pres[ZZ][ZZ]+p_corr_z - xy_pressure))/(DIM-1);
496 break;
497 default:
498 gmx_fatal(FARGS,"Berendsen pressure coupling type %s not supported yet\n",
499 EPCOUPLTYPETYPE(ir->epct));
500 break;
502 /* To fullfill the orientation restrictions on triclinic boxes
503 * we will set mu_yx, mu_zx and mu_zy to 0 and correct
504 * the other elements of mu to first order.
506 mu[YY][XX] += mu[XX][YY];
507 mu[ZZ][XX] += mu[XX][ZZ];
508 mu[ZZ][YY] += mu[YY][ZZ];
509 mu[XX][YY] = 0;
510 mu[XX][ZZ] = 0;
511 mu[YY][ZZ] = 0;
513 if (debug) {
514 pr_rvecs(debug,0,"PC: pres ",pres,3);
515 pr_rvecs(debug,0,"PC: mu ",mu,3);
518 if (mu[XX][XX]<0.99 || mu[XX][XX]>1.01 ||
519 mu[YY][YY]<0.99 || mu[YY][YY]>1.01 ||
520 mu[ZZ][ZZ]<0.99 || mu[ZZ][ZZ]>1.01) {
521 char buf2[22];
522 sprintf(buf,"\nStep %s Warning: pressure scaling more than 1%%, "
523 "mu: %g %g %g\n",
524 gmx_step_str(step,buf2),mu[XX][XX],mu[YY][YY],mu[ZZ][ZZ]);
525 if (fplog)
526 fprintf(fplog,"%s",buf);
527 fprintf(stderr,"%s",buf);
531 void berendsen_pscale(t_inputrec *ir,matrix mu,
532 matrix box,matrix box_rel,
533 int start,int nr_atoms,
534 rvec x[],unsigned short cFREEZE[],
535 t_nrnb *nrnb)
537 ivec *nFreeze=ir->opts.nFreeze;
538 int n,d,g=0;
540 /* Scale the positions */
541 for (n=start; n<start+nr_atoms; n++) {
542 if (cFREEZE)
543 g = cFREEZE[n];
545 if (!nFreeze[g][XX])
546 x[n][XX] = mu[XX][XX]*x[n][XX]+mu[YY][XX]*x[n][YY]+mu[ZZ][XX]*x[n][ZZ];
547 if (!nFreeze[g][YY])
548 x[n][YY] = mu[YY][YY]*x[n][YY]+mu[ZZ][YY]*x[n][ZZ];
549 if (!nFreeze[g][ZZ])
550 x[n][ZZ] = mu[ZZ][ZZ]*x[n][ZZ];
552 /* compute final boxlengths */
553 for (d=0; d<DIM; d++) {
554 box[d][XX] = mu[XX][XX]*box[d][XX]+mu[YY][XX]*box[d][YY]+mu[ZZ][XX]*box[d][ZZ];
555 box[d][YY] = mu[YY][YY]*box[d][YY]+mu[ZZ][YY]*box[d][ZZ];
556 box[d][ZZ] = mu[ZZ][ZZ]*box[d][ZZ];
559 preserve_box_shape(ir,box_rel,box);
561 /* (un)shifting should NOT be done after this,
562 * since the box vectors might have changed
564 inc_nrnb(nrnb,eNR_PCOUPL,nr_atoms);
567 void berendsen_tcoupl(t_grpopts *opts,gmx_ekindata_t *ekind,real dt)
569 int i;
571 real T,reft=0,lll;
573 for(i=0; (i<opts->ngtc); i++) {
574 T = ekind->tcstat[i].Th;
576 if ((opts->tau_t[i] > 0) && (T > 0.0)) {
578 reft = max(0.0,opts->ref_t[i]);
579 lll = sqrt(1.0 + (dt/opts->tau_t[i])*(reft/T-1.0));
580 ekind->tcstat[i].lambda = max(min(lll,1.25),0.8);
582 else {
583 ekind->tcstat[i].lambda = 1.0;
586 if (debug)
587 fprintf(debug,"TC: group %d: T: %g, Lambda: %g\n",
588 i,T,ekind->tcstat[i].lambda);
592 void nosehoover_tcoupl(t_grpopts *opts,gmx_ekindata_t *ekind,real dt,
593 double xi[],double vxi[], t_extmass *MassQ)
595 int i;
596 real reft,oldvxi;
598 /* note that this routine does not include Nose-hoover chains yet. Should be easy to add. */
600 for(i=0; (i<opts->ngtc); i++) {
601 reft = max(0.0,opts->ref_t[i]);
602 oldvxi = vxi[i];
603 vxi[i] += dt*MassQ->Qinv[i]*(ekind->tcstat[i].Th - reft);
604 xi[i] += dt*(oldvxi + vxi[i])*0.5;
608 t_state *init_bufstate(const t_state *template_state)
610 t_state *state;
611 int nc = template_state->nhchainlength;
612 snew(state,1);
613 snew(state->nosehoover_xi,nc*template_state->ngtc);
614 snew(state->nosehoover_vxi,nc*template_state->ngtc);
615 snew(state->therm_integral,template_state->ngtc);
616 snew(state->nhpres_xi,nc*template_state->nnhpres);
617 snew(state->nhpres_vxi,nc*template_state->nnhpres);
619 return state;
622 void destroy_bufstate(t_state *state)
624 sfree(state->x);
625 sfree(state->v);
626 sfree(state->nosehoover_xi);
627 sfree(state->nosehoover_vxi);
628 sfree(state->therm_integral);
629 sfree(state->nhpres_xi);
630 sfree(state->nhpres_vxi);
631 sfree(state);
634 void trotter_update(t_inputrec *ir,gmx_ekindata_t *ekind,
635 gmx_enerdata_t *enerd, t_state *state,
636 tensor vir, t_mdatoms *md,
637 t_extmass *MassQ, int *trotter_seq)
640 int n,i,j,d,ntgrp,ngtc,gc=0;
641 t_grp_tcstat *tcstat;
642 t_grpopts *opts;
643 real ecorr,pcorr,dvdlcorr;
644 real bmass,qmass,reft,kT,dt,nd;
645 tensor dumpres,dumvir;
646 double *scalefac;
647 rvec sumv,consk;
649 /* signal we are returning if nothing is going to be done in this routine */
650 if (trotter_seq[0] == etrtSKIPALL)
652 return;
654 opts = &(ir->opts); /* just for ease of referencing */
655 ngtc = opts->ngtc;
656 snew(scalefac,opts->ngtc);
657 for (i=0;i<ngtc;i++)
659 scalefac[i] = 1;
661 /* execute the series of trotter updates specified in the trotterpart array */
663 for (i=0;i<NTROTTERPARTS;i++){
664 /* allow for doubled intgrators by doubling dt instead of making 2 calls */
665 if ((trotter_seq[i] == etrtBAROV2) || (trotter_seq[i] == etrtBARONHC2) || (trotter_seq[i] == etrtNHC2))
667 dt = 2 * ir->delta_t;
669 else
671 dt = ir->delta_t;
674 switch (trotter_seq[i])
676 case etrtBAROV:
677 case etrtBAROV2:
678 boxv_trotter(ir,&(state->veta),dt,state->box,ekind,vir,
679 enerd->term[F_PDISPCORR],enerd->term[F_DISPCORR],MassQ);
680 break;
681 case etrtBARONHC:
682 case etrtBARONHC2:
683 NHC_trotter(opts,state->nnhpres,ekind,dt,state->nhpres_xi,
684 state->nhpres_vxi,NULL,&(state->veta),MassQ,FALSE);
685 break;
686 case etrtNHC:
687 case etrtNHC2:
688 NHC_trotter(opts,opts->ngtc,ekind,dt,state->nosehoover_xi,
689 state->nosehoover_vxi,scalefac,NULL,MassQ,(ir->eI==eiVV));
690 /* need to rescale the kinetic energies and velocities here. Could
691 scale the velocities later, but we need them scaled in order to
692 produce the correct outputs, so we'll scale them here. */
694 for (i=0; i<ngtc;i++)
696 tcstat = &ekind->tcstat[i];
697 tcstat->vscale_nhc = scalefac[i];
698 tcstat->ekinscaleh_nhc *= (scalefac[i]*scalefac[i]);
699 tcstat->ekinscalef_nhc *= (scalefac[i]*scalefac[i]);
701 /* now that we've scaled the groupwise velocities, we can add them up to get the total */
702 /* but do we actually need the total? */
704 /* modify the velocities as well */
705 for (n=md->start;n<md->start+md->homenr;n++)
707 if (md->cTC)
709 gc = md->cTC[n];
711 for (d=0;d<DIM;d++)
713 state->v[n][d] *= scalefac[gc];
716 if (debug)
718 for (d=0;d<DIM;d++)
720 sumv[d] += (state->v[n][d])/md->invmass[n];
724 break;
725 default:
726 break;
729 /* check for conserved momentum -- worth looking at this again eventually, but not working right now.*/
730 #if 0
731 if (debug)
733 if (bFirstHalf)
735 for (d=0;d<DIM;d++)
737 consk[d] = sumv[d]*exp((1 + 1.0/opts->nrdf[0])*((1.0/DIM)*log(det(state->box)/state->vol0)) + state->nosehoover_xi[0]);
739 fprintf(debug,"Conserved kappa: %15.8f %15.8f %15.8f\n",consk[0],consk[1],consk[2]);
742 #endif
743 sfree(scalefac);
746 int **init_npt_vars(t_inputrec *ir, t_state *state, t_extmass *MassQ, bool bTrotter)
748 int n,i,j,d,ntgrp,ngtc,nnhpres,nh,gc=0;
749 t_grp_tcstat *tcstat;
750 t_grpopts *opts;
751 real ecorr,pcorr,dvdlcorr;
752 real bmass,qmass,reft,kT,dt,ndj,nd;
753 tensor dumpres,dumvir;
754 int **trotter_seq;
756 opts = &(ir->opts); /* just for ease of referencing */
757 ngtc = state->ngtc;
758 nnhpres = state->nnhpres;
759 nh = state->nhchainlength;
761 if (ir->eI == eiMD) {
762 snew(MassQ->Qinv,ngtc);
763 for(i=0; (i<ngtc); i++)
765 if ((opts->tau_t[i] > 0) && (opts->ref_t[i] > 0))
767 MassQ->Qinv[i]=1.0/(sqr(opts->tau_t[i]/M_2PI)*opts->ref_t[i]);
769 else
771 MassQ->Qinv[i]=0.0;
775 else if (EI_VV(ir->eI))
777 /* Set pressure variables */
779 if (state->vol0 == 0)
781 state->vol0 = det(state->box); /* because we start by defining a fixed compressibility,
782 we need the volume at this compressibility to solve the problem */
785 /* units are nm^3 * ns^2 / (nm^3 * bar / kJ/mol) = kJ/mol */
786 /* Investigate this more -- is this the right mass to make it? */
787 MassQ->Winv = (PRESFAC*trace(ir->compress)*BOLTZ*opts->ref_t[0])/(DIM*state->vol0*sqr(ir->tau_p/M_2PI));
788 /* An alternate mass definition, from Tuckerman et al. */
789 /* MassQ->Winv = 1.0/(sqr(ir->tau_p/M_2PI)*(opts->nrdf[0]+DIM)*BOLTZ*opts->ref_t[0]); */
790 for (d=0;d<DIM;d++)
792 for (n=0;n<DIM;n++)
794 MassQ->Winvm[d][n]= PRESFAC*ir->compress[d][n]/(state->vol0*sqr(ir->tau_p/M_2PI));
795 /* not clear this is correct yet for the anisotropic case*/
798 /* Allocate space for thermostat variables */
799 snew(MassQ->Qinv,ngtc*nh);
801 /* now, set temperature variables */
802 for(i=0; i<ngtc; i++)
804 if ((opts->tau_t[i] > 0) && (opts->ref_t[i] > 0))
806 reft = max(0.0,opts->ref_t[i]);
807 nd = opts->nrdf[i];
808 kT = BOLTZ*reft;
809 for (j=0;j<nh;j++)
811 if (j==0)
813 ndj = nd;
815 else
817 ndj = 1;
819 MassQ->Qinv[i*nh+j] = 1.0/(sqr(opts->tau_t[i]/M_2PI)*ndj*kT);
822 else
824 reft=0.0;
825 for (j=0;j<nh;j++)
827 MassQ->Qinv[i*nh+j] = 0.0;
833 /* first, initialize clear all the trotter calls */
834 snew(trotter_seq,NTROTTERCALLS);
835 for (i=0;i<NTROTTERCALLS;i++)
837 snew(trotter_seq[i],NTROTTERPARTS);
838 for (j=0;j<NTROTTERPARTS;j++) {
839 trotter_seq[i][j] = etrtNONE;
841 trotter_seq[i][0] = etrtSKIPALL;
844 if (!bTrotter)
846 /* no trotter calls, so we never use the values in the array.
847 * We access them (so we need to define them, but ignore
848 * then.*/
850 return trotter_seq;
853 /* compute the kinetic energy by using the half step velocities or
854 * the kinetic energies, depending on the order of the trotter calls */
856 if (ir->eI==eiVV)
858 if (IR_NPT_TROTTER(ir))
860 /* This is the complicated version - there are 4 possible calls, depending on ordering.
861 We start with the initial one. */
862 /* first, a round that estimates veta. */
863 trotter_seq[0][0] = etrtBAROV;
865 /* trotter_seq[1] is etrtNHC for 1/2 step velocities - leave zero */
867 /* The first half trotter update */
868 trotter_seq[2][0] = etrtBAROV;
869 trotter_seq[2][1] = etrtNHC;
870 trotter_seq[2][2] = etrtBARONHC;
872 /* The second half trotter update */
873 trotter_seq[3][0] = etrtBARONHC;
874 trotter_seq[3][1] = etrtNHC;
875 trotter_seq[3][2] = etrtBAROV;
877 /* trotter_seq[4] is etrtNHC for second 1/2 step velocities - leave zero */
880 else
882 if (IR_NVT_TROTTER(ir))
884 /* This is the easy version - there are only two calls, both the same.
885 Otherwise, even easier -- no calls */
886 trotter_seq[2][0] = etrtNHC;
887 trotter_seq[3][0] = etrtNHC;
890 } else if (ir->eI==eiVVAK) {
891 if (IR_NPT_TROTTER(ir))
893 /* This is the complicated version - there are 4 possible calls, depending on ordering.
894 We start with the initial one. */
895 /* first, a round that estimates veta. */
896 trotter_seq[0][0] = etrtBAROV;
898 /* The first half trotter update, part 1 -- double update, because it commutes */
899 trotter_seq[1][0] = etrtNHC;
901 /* The first half trotter update, part 2 */
902 trotter_seq[2][0] = etrtBAROV;
903 trotter_seq[2][1] = etrtBARONHC;
905 /* The second half trotter update, part 1 */
906 trotter_seq[3][0] = etrtBARONHC;
907 trotter_seq[3][1] = etrtBAROV;
909 /* The second half trotter update -- blank for now */
910 trotter_seq[4][0] = etrtNHC;
912 else
914 if (IR_NVT_TROTTER(ir))
916 /* This is the easy version - there is only one call, both the same.
917 Otherwise, even easier -- no calls */
918 trotter_seq[1][0] = etrtNHC;
919 trotter_seq[4][0] = etrtNHC;
924 switch (ir->epct)
926 case epctISOTROPIC:
927 default:
928 bmass = DIM*DIM; /* recommended mass parameters for isotropic barostat */
931 snew(MassQ->QPinv,nnhpres*opts->nhchainlength);
933 /* barostat temperature */
934 if ((ir->tau_p > 0) && (opts->ref_t[0] > 0))
936 reft = max(0.0,opts->ref_t[0]);
937 kT = BOLTZ*reft;
938 for (i=0;i<nnhpres;i++) {
939 for (j=0;j<nh;j++)
941 if (j==0) {
942 qmass = bmass;
944 else
946 qmass = 1;
948 MassQ->QPinv[i*opts->nhchainlength+j] = 1.0/(sqr(opts->tau_t[0]/M_2PI)*qmass*kT);
952 else
954 for (i=0;i<nnhpres;i++) {
955 for (j=0;j<nh;j++)
957 MassQ->QPinv[i*nh+j]=0.0;
961 return trotter_seq;
964 real NPT_energy(t_inputrec *ir, t_state *state, t_extmass *MassQ)
966 int i,j,nd,ndj,bmass,qmass,ngtcall;
967 real ener_npt,reft,eta,kT,tau;
968 double *ivxi, *ixi;
969 double *iQinv;
970 real vol,dbaro,W,Q;
971 int nh = state->nhchainlength;
973 ener_npt = 0;
975 /* now we compute the contribution of the pressure to the conserved quantity*/
977 if (ir->epc==epcMTTK)
979 /* find the volume, and the kinetic energy of the volume */
981 switch (ir->epct) {
983 case epctISOTROPIC:
984 /* contribution from the pressure momenenta */
985 ener_npt += 0.5*sqr(state->veta)/MassQ->Winv;
987 /* contribution from the PV term */
988 vol = det(state->box);
989 ener_npt += vol*trace(ir->ref_p)/(DIM*PRESFAC);
991 break;
992 case epctANISOTROPIC:
994 break;
996 case epctSURFACETENSION:
998 break;
999 case epctSEMIISOTROPIC:
1001 break;
1002 default:
1003 break;
1007 if (IR_NPT_TROTTER(ir))
1009 /* add the energy from the barostat thermostat chain */
1010 for (i=0;i<state->nnhpres;i++) {
1012 /* note -- assumes only one degree of freedom that is thermostatted in barostat */
1013 ivxi = &state->nhpres_vxi[i*nh];
1014 ixi = &state->nhpres_xi[i*nh];
1015 iQinv = &(MassQ->QPinv[i*nh]);
1016 reft = max(ir->opts.ref_t[0],0); /* using 'System' temperature */
1017 kT = BOLTZ * reft;
1019 for (j=0;j<nh;j++)
1021 ener_npt += 0.5*sqr(ivxi[j])/iQinv[j];
1022 /* contribution from the thermal variable of the NH chain */
1023 ener_npt += ixi[j]*kT;
1024 if (debug)
1026 fprintf(debug,"P-T-group: %10d Chain %4d ThermV: %15.8f ThermX: %15.8f",i,j,ivxi[j],ixi[j]);
1032 if (ir->etc)
1034 for(i=0; i<ir->opts.ngtc; i++)
1036 ixi = &state->nosehoover_xi[i*nh];
1037 ivxi = &state->nosehoover_vxi[i*nh];
1038 iQinv = &(MassQ->Qinv[i*nh]);
1040 nd = ir->opts.nrdf[i];
1041 reft = max(ir->opts.ref_t[i],0);
1042 kT = BOLTZ * reft;
1044 if (nd > 0)
1046 if (IR_NVT_TROTTER(ir))
1048 /* contribution from the thermal momenta of the NH chain */
1049 for (j=0;j<nh;j++)
1051 ener_npt += 0.5*sqr(ivxi[j])/iQinv[j];
1052 /* contribution from the thermal variable of the NH chain */
1053 if (j==0) {
1054 ndj = nd;
1056 else
1058 ndj = 1;
1060 ener_npt += ndj*ixi[j]*kT;
1063 else /* Other non Trotter temperature NH control -- no chains yet. */
1065 ener_npt += 0.5*BOLTZ*nd*sqr(ivxi[0])/iQinv[0];
1066 ener_npt += nd*ixi[0]*kT;
1071 return ener_npt;
1074 static real vrescale_gamdev(int ia, gmx_rng_t rng)
1075 /* Gamma distribution, adapted from numerical recipes */
1077 int j;
1078 real am,e,s,v1,v2,x,y;
1080 if (ia < 6) {
1081 x = 1.0;
1082 for(j=1; j<=ia; j++) {
1083 x *= gmx_rng_uniform_real(rng);
1085 x = -log(x);
1086 } else {
1087 do {
1088 do {
1089 do {
1090 v1 = gmx_rng_uniform_real(rng);
1091 v2 = 2.0*gmx_rng_uniform_real(rng)-1.0;
1092 } while (v1*v1 + v2*v2 > 1.0);
1093 y = v2/v1;
1094 am = ia - 1;
1095 s = sqrt(2.0*am + 1.0);
1096 x = s*y + am;
1097 } while (x <= 0.0);
1098 e = (1.0 + y*y)*exp(am*log(x/am) - s*y);
1099 } while (gmx_rng_uniform_real(rng) > e);
1102 return x;
1105 static real vrescale_sumnoises(int nn,gmx_rng_t rng)
1108 * Returns the sum of n independent gaussian noises squared
1109 * (i.e. equivalent to summing the square of the return values
1110 * of nn calls to gmx_rng_gaussian_real).xs
1112 real rr;
1114 if (nn == 0) {
1115 return 0.0;
1116 } else if (nn == 1) {
1117 rr = gmx_rng_gaussian_real(rng);
1118 return rr*rr;
1119 } else if (nn % 2 == 0) {
1120 return 2.0*vrescale_gamdev(nn/2,rng);
1121 } else {
1122 rr = gmx_rng_gaussian_real(rng);
1123 return 2.0*vrescale_gamdev((nn-1)/2,rng) + rr*rr;
1127 static real vrescale_resamplekin(real kk,real sigma, int ndeg, real taut,
1128 gmx_rng_t rng)
1131 * Generates a new value for the kinetic energy,
1132 * according to Bussi et al JCP (2007), Eq. (A7)
1133 * kk: present value of the kinetic energy of the atoms to be thermalized (in arbitrary units)
1134 * sigma: target average value of the kinetic energy (ndeg k_b T/2) (in the same units as kk)
1135 * ndeg: number of degrees of freedom of the atoms to be thermalized
1136 * taut: relaxation time of the thermostat, in units of 'how often this routine is called'
1138 real factor,rr;
1140 if (taut > 0.1) {
1141 factor = exp(-1.0/taut);
1142 } else {
1143 factor = 0.0;
1145 rr = gmx_rng_gaussian_real(rng);
1146 return
1147 kk +
1148 (1.0 - factor)*(sigma*(vrescale_sumnoises(ndeg-1,rng) + rr*rr)/ndeg - kk) +
1149 2.0*rr*sqrt(kk*sigma/ndeg*(1.0 - factor)*factor);
1152 void vrescale_tcoupl(t_grpopts *opts,gmx_ekindata_t *ekind,real dt,
1153 double therm_integral[],gmx_rng_t rng)
1155 int i;
1156 real Ek,Ek_ref1,Ek_ref,Ek_new;
1158 for(i=0; (i<opts->ngtc); i++) {
1159 Ek = trace(ekind->tcstat[i].ekinh);
1161 if (opts->tau_t[i] >= 0 && opts->nrdf[i] > 0 && Ek > 0) {
1162 Ek_ref1 = 0.5*opts->ref_t[i]*BOLTZ;
1163 Ek_ref = Ek_ref1*opts->nrdf[i];
1165 Ek_new =
1166 vrescale_resamplekin(Ek,Ek_ref,opts->nrdf[i],opts->tau_t[i]/dt,rng);
1168 /* Analytically Ek_new>=0, but we check for rounding errors */
1169 if (Ek_new <= 0) {
1170 ekind->tcstat[i].lambda = 0.0;
1171 } else {
1172 ekind->tcstat[i].lambda = sqrt(Ek_new/Ek);
1174 therm_integral[i] -= Ek_new - Ek;
1176 if (debug) {
1177 fprintf(debug,"TC: group %d: Ekr %g, Ek %g, Ek_new %g, Lambda: %g\n",
1178 i,Ek_ref,Ek,Ek_new,ekind->tcstat[i].lambda);
1180 } else {
1181 ekind->tcstat[i].lambda = 1.0;
1186 real vrescale_energy(t_grpopts *opts,double therm_integral[])
1188 int i;
1189 real ener;
1191 ener = 0;
1192 for(i=0; i<opts->ngtc; i++) {
1193 ener += therm_integral[i];
1196 return ener;
1199 /* set target temperatures if we are annealing */
1200 void update_annealing_target_temp(t_grpopts *opts,real t)
1202 int i,j,n,npoints;
1203 real pert,thist=0,x;
1205 for(i=0;i<opts->ngtc;i++) {
1206 npoints = opts->anneal_npoints[i];
1207 switch (opts->annealing[i]) {
1208 case eannNO:
1209 continue;
1210 case eannPERIODIC:
1211 /* calculate time modulo the period */
1212 pert = opts->anneal_time[i][npoints-1];
1213 n = t / pert;
1214 thist = t - n*pert; /* modulo time */
1215 /* Make sure rounding didn't get us outside the interval */
1216 if (fabs(thist-pert) < GMX_REAL_EPS*100)
1217 thist=0;
1218 break;
1219 case eannSINGLE:
1220 thist = t;
1221 break;
1222 default:
1223 gmx_fatal(FARGS,"Death horror in update_annealing_target_temp (i=%d/%d npoints=%d)",i,opts->ngtc,npoints);
1225 /* We are doing annealing for this group if we got here,
1226 * and we have the (relative) time as thist.
1227 * calculate target temp */
1228 j=0;
1229 while ((j < npoints-1) && (thist>(opts->anneal_time[i][j+1])))
1230 j++;
1231 if (j < npoints-1) {
1232 /* Found our position between points j and j+1.
1233 * Interpolate: x is the amount from j+1, (1-x) from point j
1234 * First treat possible jumps in temperature as a special case.
1236 if ((opts->anneal_time[i][j+1]-opts->anneal_time[i][j]) < GMX_REAL_EPS*100)
1237 opts->ref_t[i]=opts->anneal_temp[i][j+1];
1238 else {
1239 x = ((thist-opts->anneal_time[i][j])/
1240 (opts->anneal_time[i][j+1]-opts->anneal_time[i][j]));
1241 opts->ref_t[i] = x*opts->anneal_temp[i][j+1]+(1-x)*opts->anneal_temp[i][j];
1244 else {
1245 opts->ref_t[i] = opts->anneal_temp[i][npoints-1];