Sort all includes in src/gromacs
[alexxy/gromacs.git] / src / gromacs / gmxana / gmx_tcaf.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #include "gmxpre.h"
38
39 #include <math.h>
40 #include <stdio.h>
41 #include <string.h>
42
43 #include "gromacs/commandline/pargs.h"
44 #include "gromacs/fileio/confio.h"
45 #include "gromacs/fileio/trxio.h"
46 #include "gromacs/fileio/xvgr.h"
47 #include "gromacs/gmxana/gmx_ana.h"
48 #include "gromacs/gmxana/gstat.h"
49 #include "gromacs/legacyheaders/macros.h"
50 #include "gromacs/legacyheaders/txtdump.h"
51 #include "gromacs/legacyheaders/typedefs.h"
52 #include "gromacs/legacyheaders/viewit.h"
53 #include "gromacs/math/units.h"
54 #include "gromacs/math/utilities.h"
55 #include "gromacs/math/vec.h"
56 #include "gromacs/pbcutil/pbc.h"
57 #include "gromacs/topology/index.h"
58 #include "gromacs/utility/fatalerror.h"
59 #include "gromacs/utility/futil.h"
60 #include "gromacs/utility/smalloc.h"
61
62
63 #define NK  24
64 #define NPK 4
65
66 #define NKC  6
67 #define NKC0 4
68 int  kset_c[NKC+1] = { 0, 3, 9, 13, 16, 19, NK };
69
70 rvec v0[NK] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 1, 0}, {1, -1, 0}, {1, 0, 1}, {1, 0, -1}, {0, 1, 1}, {0, 1, -1}, {1, 1, 1}, {1, 1, -1}, {1, -1, 1}, {-1, 1, 1}, {2, 0, 0}, {0, 2, 0}, {0, 0, 2}, {3, 0, 0}, {0, 3, 0}, {0, 0, 3}, {4, 0, 0}, {0, 4, 0}, {0, 0, 4}};
71 rvec v1[NK] = {{0, 1, 0}, {0, 0, 1}, {1, 0, 0}, {0, 0, 1}, {0, 0, 1}, {0, 1, 0}, {0, 1, 0}, {1, 0, 0}, {1, 0, 0}, {1, -1, 0}, {1, -1, 0}, {1, 0, -1}, { 0, 1, -1}, {0, 1, 0}, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 0, 0}};
72 rvec v2[NK] = {{0, 0, 1}, {1, 0, 0}, {0, 1, 0}, {1, -1, 0}, {1, 1, 0}, {1, 0, -1}, {1, 0, 1}, {0, 1, -1}, {0, 1, 1}, {1, 1, -2}, {1, 1, 2}, {1, 2, 1}, { 2, 1, 1}, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}};
73
74 static void process_tcaf(int nframes, real dt, int nkc, real **tc, rvec *kfac,
75                          real rho, real wt, const char *fn_trans,
76                          const char *fn_tca, const char *fn_tc,
77                          const char *fn_tcf, const char *fn_cub,
78                          const char *fn_vk, const output_env_t oenv)
79 {
80     FILE  *fp, *fp_vk, *fp_cub = NULL;
81     int    nk, ntc;
82     real **tcaf, **tcafc = NULL, eta;
83     int    i, j, k, kc;
84     int    ncorr;
85     real   fitparms[3], *sig;
86
87     nk  = kset_c[nkc];
88     ntc = nk*NPK;
89
90     if (fn_trans)
91     {
92         fp = xvgropen(fn_trans, "Transverse Current", "Time (ps)", "TC (nm/ps)",
93                       oenv);
94         for (i = 0; i < nframes; i++)
95         {
96             fprintf(fp, "%g", i*dt);
97             for (j = 0; j < ntc; j++)
98             {
99                 fprintf(fp, " %g", tc[j][i]);
100             }
101             fprintf(fp, "\n");
102         }
103         gmx_ffclose(fp);
104         do_view(oenv, fn_trans, "-nxy");
105     }
106
107     ncorr = (nframes+1)/2;
108     if (ncorr > (int)(5*wt/dt+0.5))
109     {
110         ncorr = (int)(5*wt/dt+0.5)+1;
111     }
112     snew(tcaf, nk);
113     for (k = 0; k < nk; k++)
114     {
115         snew(tcaf[k], ncorr);
116     }
117     if (fn_cub)
118     {
119         snew(tcafc, nkc);
120         for (k = 0; k < nkc; k++)
121         {
122             snew(tcafc[k], ncorr);
123         }
124     }
125     snew(sig, ncorr);
126     for (i = 0; i < ncorr; i++)
127     {
128         sig[i] = exp(0.5*i*dt/wt);
129     }
130
131     low_do_autocorr(fn_tca, oenv, "Transverse Current Autocorrelation Functions",
132                     nframes, ntc, ncorr, tc, dt, eacNormal,
133                     1, FALSE, FALSE, FALSE, 0, 0, 0);
134     do_view(oenv, fn_tca, "-nxy");
135
136     fp = xvgropen(fn_tc, "Transverse Current Autocorrelation Functions",
137                   "Time (ps)", "TCAF", oenv);
138     for (i = 0; i < ncorr; i++)
139     {
140         kc = 0;
141         fprintf(fp, "%g", i*dt);
142         for (k = 0; k < nk; k++)
143         {
144             for (j = 0; j < NPK; j++)
145             {
146                 tcaf[k][i] += tc[NPK*k+j][i];
147             }
148             if (fn_cub)
149             {
150                 for (j = 0; j < NPK; j++)
151                 {
152                     tcafc[kc][i] += tc[NPK*k+j][i];
153                 }
154             }
155             if (i == 0)
156             {
157                 fprintf(fp, " %g", 1.0);
158             }
159             else
160             {
161                 tcaf[k][i] /= tcaf[k][0];
162                 fprintf(fp, " %g", tcaf[k][i]);
163             }
164             if (k+1 == kset_c[kc+1])
165             {
166                 kc++;
167             }
168         }
169         fprintf(fp, "\n");
170     }
171     gmx_ffclose(fp);
172     do_view(oenv, fn_tc, "-nxy");
173
174     if (fn_cub)
175     {
176         fp_cub = xvgropen(fn_cub, "TCAFs and fits", "Time (ps)", "TCAF", oenv);
177         for (kc = 0; kc < nkc; kc++)
178         {
179             fprintf(fp_cub, "%g %g\n", 0.0, 1.0);
180             for (i = 1; i < ncorr; i++)
181             {
182                 tcafc[kc][i] /= tcafc[kc][0];
183                 fprintf(fp_cub, "%g %g\n", i*dt, tcafc[kc][i]);
184             }
185             fprintf(fp_cub, "%s\n", output_env_get_print_xvgr_codes(oenv) ? "&" : "");
186             tcafc[kc][0] = 1.0;
187         }
188     }
189
190     fp_vk = xvgropen(fn_vk, "Fits", "k (nm\\S-1\\N)",
191                      "\\8h\\4 (10\\S-3\\N kg m\\S-1\\N s\\S-1\\N)", oenv);
192     if (output_env_get_print_xvgr_codes(oenv))
193     {
194         fprintf(fp_vk, "@    s0 symbol 2\n");
195         fprintf(fp_vk, "@    s0 symbol color 1\n");
196         fprintf(fp_vk, "@    s0 linestyle 0\n");
197         if (fn_cub)
198         {
199             fprintf(fp_vk, "@    s1 symbol 3\n");
200             fprintf(fp_vk, "@    s1 symbol color 2\n");
201         }
202     }
203     fp = xvgropen(fn_tcf, "TCAF Fits", "Time (ps)", "", oenv);
204     for (k = 0; k < nk; k++)
205     {
206         tcaf[k][0]   = 1.0;
207         fitparms[0]  = 1;
208         fitparms[1]  = 1;
209         do_lmfit(ncorr, tcaf[k], sig, dt, 0, 0, ncorr*dt,
210                  oenv, bDebugMode(), effnVAC, fitparms, 0);
211         eta = 1000*fitparms[1]*rho/
212             (4*fitparms[0]*PICO*norm2(kfac[k])/(NANO*NANO));
213         fprintf(stdout, "k %6.3f  tau %6.3f  eta %8.5f 10^-3 kg/(m s)\n",
214                 norm(kfac[k]), fitparms[0], eta);
215         fprintf(fp_vk, "%6.3f %g\n", norm(kfac[k]), eta);
216         for (i = 0; i < ncorr; i++)
217         {
218             fprintf(fp, "%g %g\n", i*dt, fit_function(effnVAC, fitparms, i*dt));
219         }
220         fprintf(fp, "%s\n", output_env_get_print_xvgr_codes(oenv) ? "&" : "");
221     }
222     gmx_ffclose(fp);
223     do_view(oenv, fn_tcf, "-nxy");
224
225     if (fn_cub)
226     {
227         fprintf(stdout, "Averaged over k-vectors:\n");
228         fprintf(fp_vk, "%s\n", output_env_get_print_xvgr_codes(oenv) ? "&" : "");
229         for (k = 0; k < nkc; k++)
230         {
231             tcafc[k][0]  = 1.0;
232             fitparms[0]  = 1;
233             fitparms[1]  = 1;
234             do_lmfit(ncorr, tcafc[k], sig, dt, 0, 0, ncorr*dt,
235                      oenv, bDebugMode(), effnVAC, fitparms, 0);
236             eta = 1000*fitparms[1]*rho/
237                 (4*fitparms[0]*PICO*norm2(kfac[kset_c[k]])/(NANO*NANO));
238             fprintf(stdout,
239                     "k %6.3f  tau %6.3f  Omega %6.3f  eta %8.5f 10^-3 kg/(m s)\n",
240                     norm(kfac[kset_c[k]]), fitparms[0], fitparms[1], eta);
241             fprintf(fp_vk, "%6.3f %g\n", norm(kfac[kset_c[k]]), eta);
242             for (i = 0; i < ncorr; i++)
243             {
244                 fprintf(fp_cub, "%g %g\n", i*dt, fit_function(effnVAC, fitparms, i*dt));
245             }
246             fprintf(fp_cub, "%s\n", output_env_get_print_xvgr_codes(oenv) ? "&" : "");
247         }
248         fprintf(fp_vk, "%s\n", output_env_get_print_xvgr_codes(oenv) ? "&" : "");
249         gmx_ffclose(fp_cub);
250         do_view(oenv, fn_cub, "-nxy");
251     }
252     gmx_ffclose(fp_vk);
253     do_view(oenv, fn_vk, "-nxy");
254 }
255
256
257 int gmx_tcaf(int argc, char *argv[])
258 {
259     const char     *desc[] = {
260         "[THISMODULE] computes tranverse current autocorrelations.",
261         "These are used to estimate the shear viscosity, [GRK]eta[grk].",
262         "For details see: Palmer, Phys. Rev. E 49 (1994) pp 359-366.[PAR]",
263         "Transverse currents are calculated using the",
264         "k-vectors (1,0,0) and (2,0,0) each also in the [IT]y[it]- and [IT]z[it]-direction,",
265         "(1,1,0) and (1,-1,0) each also in the 2 other planes (these vectors",
266         "are not independent) and (1,1,1) and the 3 other box diagonals (also",
267         "not independent). For each k-vector the sine and cosine are used, in",
268         "combination with the velocity in 2 perpendicular directions. This gives",
269         "a total of 16*2*2=64 transverse currents. One autocorrelation is",
270         "calculated fitted for each k-vector, which gives 16 TCAFs. Each of",
271         "these TCAFs is fitted to [MATH]f(t) = [EXP]-v[exp]([COSH]Wv[cosh] + 1/W [SINH]Wv[sinh])[math],",
272         "[MATH]v = -t/(2 [GRK]tau[grk])[math], [MATH]W = [SQRT]1 - 4 [GRK]tau[grk] [GRK]eta[grk]/[GRK]rho[grk] k^2[sqrt][math], which gives 16 values of [GRK]tau[grk]",
273         "and [GRK]eta[grk]. The fit weights decay exponentially with time constant [MATH]w[math] (given with [TT]-wt[tt]) as [MATH][EXP]-t/w[exp][math], and the TCAF and",
274         "fit are calculated up to time [MATH]5*w[math].",
275         "The [GRK]eta[grk] values should be fitted to [MATH]1 - a [GRK]eta[grk](k) k^2[math], from which",
276         "one can estimate the shear viscosity at k=0.[PAR]",
277         "When the box is cubic, one can use the option [TT]-oc[tt], which",
278         "averages the TCAFs over all k-vectors with the same length.",
279         "This results in more accurate TCAFs.",
280         "Both the cubic TCAFs and fits are written to [TT]-oc[tt]",
281         "The cubic [GRK]eta[grk] estimates are also written to [TT]-ov[tt].[PAR]",
282         "With option [TT]-mol[tt], the transverse current is determined of",
283         "molecules instead of atoms. In this case, the index group should",
284         "consist of molecule numbers instead of atom numbers.[PAR]",
285         "The k-dependent viscosities in the [TT]-ov[tt] file should be",
286         "fitted to [MATH][GRK]eta[grk](k) = [GRK]eta[grk][SUB]0[sub] (1 - a k^2)[math] to obtain the viscosity at",
287         "infinite wavelength.[PAR]",
288         "[BB]Note:[bb] make sure you write coordinates and velocities often enough.",
289         "The initial, non-exponential, part of the autocorrelation function",
290         "is very important for obtaining a good fit."
291     };
292
293     static gmx_bool bMol = FALSE, bK34 = FALSE;
294     static real     wt   = 5;
295     t_pargs         pa[] = {
296         { "-mol", FALSE, etBOOL, {&bMol},
297           "Calculate TCAF of molecules" },
298         { "-k34", FALSE, etBOOL, {&bK34},
299           "Also use k=(3,0,0) and k=(4,0,0)" },
300         { "-wt", FALSE, etREAL, {&wt},
301           "Exponential decay time for the TCAF fit weights" }
302     };
303
304     t_topology      top;
305     int             ePBC;
306     t_trxframe      fr;
307     matrix          box;
308     gmx_bool        bTPS, bTop; /* ,bCubic; */
309     int             gnx;
310     atom_id        *index, *atndx = NULL, at;
311     char           *grpname;
312     char            title[256];
313     real            t0, t1, dt, m, mtot, sysmass, rho, sx, cx;
314     t_trxstatus    *status;
315     int             nframes, n_alloc, i, j, k, d;
316     rvec            mv_mol, cm_mol, kfac[NK];
317     int             nkc, nk, ntc;
318     real          **c1, **tc;
319     output_env_t    oenv;
320
321 #define NHISTO 360
322
323     t_filenm  fnm[] = {
324         { efTRN, "-f",    NULL,      ffREAD  },
325         { efTPS, NULL,    NULL,      ffOPTRD },
326         { efNDX, NULL,    NULL,      ffOPTRD },
327         { efXVG, "-ot",  "transcur", ffOPTWR },
328         { efXVG, "-oa",  "tcaf_all", ffWRITE },
329         { efXVG, "-o",   "tcaf",     ffWRITE },
330         { efXVG, "-of",  "tcaf_fit", ffWRITE },
331         { efXVG, "-oc",  "tcaf_cub", ffOPTWR },
332         { efXVG, "-ov",  "visc_k",   ffWRITE }
333     };
334 #define NFILE asize(fnm)
335     int       npargs;
336     t_pargs  *ppa;
337
338     npargs = asize(pa);
339     ppa    = add_acf_pargs(&npargs, pa);
340
341     if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME,
342                            NFILE, fnm, npargs, ppa, asize(desc), desc, 0, NULL, &oenv))
343     {
344         return 0;
345     }
346
347     bTop = read_tps_conf(ftp2fn(efTPS, NFILE, fnm), title, &top, &ePBC, NULL, NULL, box,
348                          TRUE);
349     get_index(&top.atoms, ftp2fn_null(efNDX, NFILE, fnm), 1, &gnx, &index, &grpname);
350
351     if (bMol)
352     {
353         if (!bTop)
354         {
355             gmx_fatal(FARGS, "Need a topology to determine the molecules");
356         }
357         atndx = top.mols.index;
358     }
359
360     if (bK34)
361     {
362         nkc = NKC;
363     }
364     else
365     {
366         nkc = NKC0;
367     }
368     nk  = kset_c[nkc];
369     ntc = nk*NPK;
370
371     sprintf(title, "Velocity Autocorrelation Function for %s", grpname);
372
373     sysmass = 0;
374     for (i = 0; i < nk; i++)
375     {
376         if (iprod(v0[i], v1[i]) != 0)
377         {
378             gmx_fatal(FARGS, "DEATH HORROR: vectors not orthogonal");
379         }
380         if (iprod(v0[i], v2[i]) != 0)
381         {
382             gmx_fatal(FARGS, "DEATH HORROR: vectors not orthogonal");
383         }
384         if (iprod(v1[i], v2[i]) != 0)
385         {
386             gmx_fatal(FARGS, "DEATH HORROR: vectors not orthogonal");
387         }
388         unitv(v1[i], v1[i]);
389         unitv(v2[i], v2[i]);
390     }
391     snew(tc, ntc);
392     for (i = 0; i < top.atoms.nr; i++)
393     {
394         sysmass += top.atoms.atom[i].m;
395     }
396
397     read_first_frame(oenv, &status, ftp2fn(efTRN, NFILE, fnm), &fr,
398                      TRX_NEED_X | TRX_NEED_V);
399     t0 = fr.time;
400
401     n_alloc = 0;
402     nframes = 0;
403     rho     = 0;
404     /* bCubic = TRUE; */
405     do
406     {
407         /*
408            bCubic = bCubic && !TRICLINIC(fr.box) &&
409            fabs(fr.box[XX][XX]-fr.box[YY][YY]) < 0.001*fr.box[XX][XX] &&
410            fabs(fr.box[XX][XX]-fr.box[ZZ][ZZ]) < 0.001*fr.box[XX][XX];
411          */
412
413         if (nframes >= n_alloc)
414         {
415             n_alloc += 100;
416             for (i = 0; i < ntc; i++)
417             {
418                 srenew(tc[i], n_alloc);
419             }
420         }
421
422         rho += 1/det(fr.box);
423         for (k = 0; k < nk; k++)
424         {
425             for (d = 0; d < DIM; d++)
426             {
427                 kfac[k][d] = 2*M_PI*v0[k][d]/fr.box[d][d];
428             }
429         }
430         for (i = 0; i < ntc; i++)
431         {
432             tc[i][nframes] = 0;
433         }
434
435         for (i = 0; i < gnx; i++)
436         {
437             if (bMol)
438             {
439                 clear_rvec(mv_mol);
440                 clear_rvec(cm_mol);
441                 mtot = 0;
442                 for (j = 0; j < atndx[index[i]+1] - atndx[index[i]]; j++)
443                 {
444                     at          = atndx[index[i]] + j;
445                     m           = top.atoms.atom[at].m;
446                     mv_mol[XX] += m*fr.v[at][XX];
447                     mv_mol[YY] += m*fr.v[at][YY];
448                     mv_mol[ZZ] += m*fr.v[at][ZZ];
449                     cm_mol[XX] += m*fr.x[at][XX];
450                     cm_mol[YY] += m*fr.x[at][YY];
451                     cm_mol[ZZ] += m*fr.x[at][ZZ];
452                     mtot       += m;
453                 }
454                 svmul(1.0/mtot, cm_mol, cm_mol);
455             }
456             else
457             {
458                 svmul(top.atoms.atom[index[i]].m, fr.v[index[i]], mv_mol);
459             }
460
461             if (!bMol)
462             {
463                 copy_rvec(fr.x[index[i]], cm_mol);
464             }
465             j = 0;
466             for (k = 0; k < nk; k++)
467             {
468                 sx              = sin(iprod(kfac[k], cm_mol));
469                 cx              = cos(iprod(kfac[k], cm_mol));
470                 tc[j][nframes] += sx*iprod(v1[k], mv_mol);
471                 j++;
472                 tc[j][nframes] += cx*iprod(v1[k], mv_mol);
473                 j++;
474                 tc[j][nframes] += sx*iprod(v2[k], mv_mol);
475                 j++;
476                 tc[j][nframes] += cx*iprod(v2[k], mv_mol);
477                 j++;
478             }
479         }
480
481         t1 = fr.time;
482         nframes++;
483     }
484     while (read_next_frame(oenv, status, &fr));
485     close_trj(status);
486
487     dt = (t1-t0)/(nframes-1);
488
489     rho *= sysmass/nframes*AMU/(NANO*NANO*NANO);
490     fprintf(stdout, "Density = %g (kg/m^3)\n", rho);
491     process_tcaf(nframes, dt, nkc, tc, kfac, rho, wt,
492                  opt2fn_null("-ot", NFILE, fnm),
493                  opt2fn("-oa", NFILE, fnm), opt2fn("-o", NFILE, fnm),
494                  opt2fn("-of", NFILE, fnm), opt2fn_null("-oc", NFILE, fnm),
495                  opt2fn("-ov", NFILE, fnm), oenv);
496
497     return 0;
498 }