6e76ed186cb5edaf200fb12997a87f227dc0fc64
[alexxy/gromacs.git] / src / gromacs / gmxana / gmx_dielectric.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,2015, 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 <stdlib.h>
42 #include <string.h>
43
44 #include "gromacs/correlationfunctions/expfit.h"
45 #include "gromacs/correlationfunctions/integrate.h"
46 #include "gromacs/fft/fft.h"
47 #include "gromacs/fileio/xvgr.h"
48 #include "gromacs/gmxana/gmx_ana.h"
49 #include "gromacs/gmxana/gstat.h"
50 #include "gromacs/legacyheaders/copyrite.h"
51 #include "gromacs/legacyheaders/macros.h"
52 #include "gromacs/legacyheaders/typedefs.h"
53 #include "gromacs/legacyheaders/viewit.h"
54 #include "gromacs/math/gmxcomplex.h"
55 #include "gromacs/math/utilities.h"
56 #include "gromacs/utility/fatalerror.h"
57 #include "gromacs/utility/futil.h"
58 #include "gromacs/utility/smalloc.h"
59 #include "gromacs/utility/fatalerror.h"
60 #include "gromacs/math/gmxcomplex.h"
61 #include "gromacs/math/utilities.h"
62 #include "gmx_ana.h"
63
64 /* Determines at which point in the array the fit should start */
65 int calc_nbegin(int nx, real x[], real tbegin)
66 {
67     int  nbegin;
68     real dt, dtt;
69
70     /* Assume input x is sorted */
71     for (nbegin = 0; (nbegin < nx) && (x[nbegin] <= tbegin); nbegin++)
72     {
73         ;
74     }
75     if ((nbegin == nx) || (nbegin == 0))
76     {
77         gmx_fatal(FARGS, "Begin time %f not in x-domain [%f through %f]\n",
78                   tbegin, x[0], x[nx-1]);
79     }
80
81     /* Take the one closest to tbegin */
82     if (fabs(x[nbegin]-tbegin) > fabs(x[nbegin-1]-tbegin))
83     {
84         nbegin--;
85     }
86
87     printf("nbegin = %d, x[nbegin] = %g, tbegin = %g\n",
88            nbegin, x[nbegin], tbegin);
89
90     return nbegin;
91 }
92
93 real numerical_deriv(int nx, real x[], real y[], real fity[], real combined[], real dy[],
94                      real tendInt, int nsmooth)
95 {
96     FILE *tmpfp;
97     int   i, nbegin, i0, i1;
98     real  fac, fx, fy, integralSmth;
99
100     nbegin = calc_nbegin(nx, x, tendInt);
101     if (nsmooth == 0)
102     {
103         for (i = 0; (i < nbegin); i++)
104         {
105             combined[i] = y[i];
106         }
107         fac = y[nbegin]/fity[nbegin];
108         printf("scaling fitted curve by %g\n", fac);
109         for (i = nbegin; (i < nx); i++)
110         {
111             combined[i] = fity[i]*fac;
112         }
113     }
114     else
115     {
116         i0 = max(0, nbegin);
117         i1 = min(nx-1, nbegin+nsmooth);
118         printf("Making smooth transition from %d through %d\n", i0, i1);
119         for (i = 0; (i < i0); i++)
120         {
121             combined[i] = y[i];
122         }
123         for (i = i0; (i <= i1); i++)
124         {
125             fx = (i1-i)/(real)(i1-i0);
126             fy = (i-i0)/(real)(i1-i0);
127             if (debug)
128             {
129                 fprintf(debug, "x: %g factors for smoothing: %10g %10g\n", x[i], fx, fy);
130             }
131             combined[i] = fx*y[i] + fy*fity[i];
132         }
133         for (i = i1+1; (i < nx); i++)
134         {
135             combined[i] = fity[i];
136         }
137     }
138
139     tmpfp        = gmx_ffopen("integral_smth.xvg", "w");
140     integralSmth = print_and_integrate(tmpfp, nx, x[1]-x[0], combined, NULL, 1);
141     printf("SMOOTH integral = %10.5e\n", integralSmth);
142
143     dy[0] = (combined[1]-combined[0])/(x[1]-x[0]);
144     for (i = 1; (i < nx-1); i++)
145     {
146         dy[i] = (combined[i+1]-combined[i-1])/(x[i+1]-x[i-1]);
147     }
148     dy[nx-1] = (combined[nx-1]-combined[nx-2])/(x[nx-1]-x[nx-2]);
149
150     for (i = 0; (i < nx); i++)
151     {
152         dy[i] *= -1;
153     }
154
155     return integralSmth;
156 }
157
158 void do_four(const char *fn, const char *cn, int nx, real x[], real dy[],
159              real eps0, real epsRF, const output_env_t oenv)
160 {
161     FILE      *fp, *cp;
162     t_complex *tmp, gw, hw, kw;
163     int        i, nnx, nxsav;
164     real       fac, nu, dt, *ptr, maxeps, numax;
165     gmx_fft_t  fft;
166     int        fftcode;
167
168     nxsav = nx;
169     /*while ((dy[nx-1] == 0.0) && (nx > 0))
170        nx--;*/
171     if (nx == 0)
172     {
173         gmx_fatal(FARGS, "Empty dataset in %s, line %d!", __FILE__, __LINE__);
174     }
175
176     nnx = 1;
177     while (nnx < 2*nx)
178     {
179         nnx *= 2;
180     }
181
182     snew(tmp, 2*nnx);
183     printf("Doing FFT of %d points\n", nnx);
184     for (i = 0; (i < nx); i++)
185     {
186         tmp[i].re = dy[i];
187     }
188     if ((fftcode = gmx_fft_init_1d_real(&fft, nnx,
189                                         GMX_FFT_FLAG_NONE)) != 0)
190     {
191         gmx_fatal(FARGS, "gmx_fft_init_1d_real returned %d", fftcode);
192     }
193     if ((fftcode = gmx_fft_1d_real(fft, GMX_FFT_COMPLEX_TO_REAL,
194                                    (void *)tmp, (void *)tmp)) != 0)
195     {
196         gmx_fatal(FARGS, "gmx_fft_1d_real returned %d", fftcode);
197     }
198     gmx_fft_destroy(fft);
199     dt = x[1]-x[0];
200     if (epsRF == 0)
201     {
202         fac = (eps0-1)/tmp[0].re;
203     }
204     else
205     {
206         fac = ((eps0-1)/(2*epsRF+eps0))/tmp[0].re;
207     }
208     fp     = xvgropen(fn, "Epsilon(\\8w\\4)", "Freq. (GHz)", "eps", oenv);
209     cp     = xvgropen(cn, "Cole-Cole plot", "Eps'", "Eps''", oenv);
210     maxeps = 0;
211     numax  = 0;
212     for (i = 0; (i < nxsav); i++)
213     {
214         if (epsRF == 0)
215         {
216             kw.re = 1+fac*tmp[i].re;
217             kw.im = 1+fac*tmp[i].im;
218         }
219         else
220         {
221             gw     = rcmul(fac, tmp[i]);
222             hw     = rcmul(2*epsRF, gw);
223             hw.re += 1.0;
224             gw.re  = 1.0 - gw.re;
225             gw.im  = -gw.im;
226             kw     = cdiv(hw, gw);
227         }
228         kw.im *= -1;
229
230         nu     = (i+1)*1000.0/(nnx*dt);
231         if (kw.im > maxeps)
232         {
233             maxeps = kw.im;
234             numax  = nu;
235         }
236
237         fprintf(fp, "%10.5e  %10.5e  %10.5e\n", nu, kw.re, kw.im);
238         fprintf(cp, "%10.5e  %10.5e\n", kw.re, kw.im);
239     }
240     printf("MAXEPS = %10.5e at frequency %10.5e GHz (tauD = %8.1f ps)\n",
241            maxeps, numax, 1000/(2*M_PI*numax));
242     xvgrclose(fp);
243     xvgrclose(cp);
244     sfree(tmp);
245 }
246
247 int gmx_dielectric(int argc, char *argv[])
248 {
249     const char  *desc[] = {
250         "[THISMODULE] calculates frequency dependent dielectric constants",
251         "from the autocorrelation function of the total dipole moment in",
252         "your simulation. This ACF can be generated by [gmx-dipoles].",
253         "The functional forms of the available functions are:",
254         "",
255         " * One parameter:    y = [EXP]-a[SUB]1[sub] x[exp],",
256         " * Two parameters:   y = a[SUB]2[sub] [EXP]-a[SUB]1[sub] x[exp],",
257         " * Three parameters: y = a[SUB]2[sub] [EXP]-a[SUB]1[sub] x[exp] + (1 - a[SUB]2[sub]) [EXP]-a[SUB]3[sub] x[exp].",
258         "",
259         "Start values for the fit procedure can be given on the command line.",
260         "It is also possible to fix parameters at their start value, use [TT]-fix[tt]",
261         "with the number of the parameter you want to fix.",
262         "[PAR]",
263         "Three output files are generated, the first contains the ACF,",
264         "an exponential fit to it with 1, 2 or 3 parameters, and the",
265         "numerical derivative of the combination data/fit.",
266         "The second file contains the real and imaginary parts of the",
267         "frequency-dependent dielectric constant, the last gives a plot",
268         "known as the Cole-Cole plot, in which the imaginary",
269         "component is plotted as a function of the real component.",
270         "For a pure exponential relaxation (Debye relaxation) the latter",
271         "plot should be one half of a circle."
272     };
273     t_filenm     fnm[] = {
274         { efXVG, "-f", "dipcorr", ffREAD  },
275         { efXVG, "-d", "deriv",  ffWRITE },
276         { efXVG, "-o", "epsw",   ffWRITE },
277         { efXVG, "-c", "cole",   ffWRITE }
278     };
279 #define NFILE asize(fnm)
280     output_env_t oenv;
281     int          i, j, nx, ny, nxtail, eFitFn, nfitparm;
282     real         dt, integral, fitintegral, fac, rffac;
283     double      *fitparms;
284     double     **yd;
285     real       **y;
286     const char  *legend[] = { "Correlation", "Std. Dev.", "Fit", "Combined", "Derivative" };
287     static int   fix      = 0, bX = 1, nsmooth = 3;
288     static real  tendInt  = 5.0, tbegin = 5.0, tend = 500.0;
289     static real  A        = 0.5, tau1 = 10.0, tau2 = 1.0, eps0 = 80, epsRF = 78.5, tail = 500.0;
290     real         lambda;
291     t_pargs      pa[] = {
292         { "-x1",  FALSE, etBOOL, {&bX},
293           "use first column as [IT]x[it]-axis rather than first data set" },
294         { "-eint", FALSE, etREAL, {&tendInt},
295           "Time to end the integration of the data and start to use the fit"},
296         { "-bfit", FALSE, etREAL, {&tbegin},
297           "Begin time of fit" },
298         { "-efit", FALSE, etREAL, {&tend},
299           "End time of fit" },
300         { "-tail", FALSE, etREAL, {&tail},
301           "Length of function including data and tail from fit" },
302         { "-A", FALSE, etREAL, {&A},
303           "Start value for fit parameter A" },
304         { "-tau1", FALSE, etREAL, {&tau1},
305           "Start value for fit parameter [GRK]tau[grk]1" },
306         { "-tau2", FALSE, etREAL, {&tau2},
307           "Start value for fit parameter [GRK]tau[grk]2" },
308         { "-eps0", FALSE, etREAL, {&eps0},
309           "[GRK]epsilon[grk]0 of your liquid" },
310         { "-epsRF", FALSE, etREAL, {&epsRF},
311           "[GRK]epsilon[grk] of the reaction field used in your simulation. A value of 0 means infinity." },
312         { "-fix", FALSE, etINT,  {&fix},
313           "Fix parameters at their start values, A (2), tau1 (1), or tau2 (4)" },
314         { "-ffn",    FALSE, etENUM, {s_ffn},
315           "Fit function" },
316         { "-nsmooth", FALSE, etINT, {&nsmooth},
317           "Number of points for smoothing" }
318     };
319
320     if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW,
321                            NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, NULL, &oenv))
322     {
323         return 0;
324     }
325     please_cite(stdout, "Spoel98a");
326     printf("WARNING: non-polarizable models can never yield an infinite\n"
327            "dielectric constant that is different from 1. This is incorrect\n"
328            "in the reference given above (Spoel98a).\n\n");
329
330
331     nx     = read_xvg(opt2fn("-f", NFILE, fnm), &yd, &ny);
332     dt     = yd[0][1] - yd[0][0];
333     nxtail = min(tail/dt, nx);
334
335     printf("Read data set containing %d colums and %d rows\n", ny, nx);
336     printf("Assuming (from data) that timestep is %g, nxtail = %d\n",
337            dt, nxtail);
338     snew(y, 6);
339     for (i = 0; (i < ny); i++)
340     {
341         snew(y[i], max(nx, nxtail));
342     }
343     for (i = 0; (i < nx); i++)
344     {
345         y[0][i] = yd[0][i];
346         for (j = 1; (j < ny); j++)
347         {
348             y[j][i] = yd[j][i];
349         }
350     }
351     if (nxtail > nx)
352     {
353         for (i = nx; (i < nxtail); i++)
354         {
355             y[0][i] = dt*i+y[0][0];
356             for (j = 1; (j < ny); j++)
357             {
358                 y[j][i] = 0.0;
359             }
360         }
361         nx = nxtail;
362     }
363
364
365     /* We have read a file WITHOUT standard deviations, so we make our own... */
366     if (ny == 2)
367     {
368         printf("Creating standard deviation numbers ...\n");
369         srenew(y, 3);
370         snew(y[2], nx);
371
372         fac = 1.0/((real)nx);
373         for (i = 0; (i < nx); i++)
374         {
375             y[2][i] = fac;
376         }
377     }
378
379     eFitFn   = sffn2effn(s_ffn);
380     nfitparm = effnNparams(eFitFn);
381     snew(fitparms, 4);
382     fitparms[0] = tau1;
383     if (nfitparm > 1)
384     {
385         fitparms[1] = A;
386     }
387     if (nfitparm > 2)
388     {
389         fitparms[2] = tau2;
390     }
391
392
393     snew(y[3], nx);
394     snew(y[4], nx);
395     snew(y[5], nx);
396
397     integral = print_and_integrate(NULL, calc_nbegin(nx, y[0], tbegin),
398                                    dt, y[1], NULL, 1);
399     integral += do_lmfit(nx, y[1], y[2], dt, y[0], tbegin, tend,
400                          oenv, TRUE, eFitFn, fitparms, fix, NULL);
401     for (i = 0; i < nx; i++)
402     {
403         y[3][i] = fit_function(eFitFn, fitparms, y[0][i]);
404     }
405
406     if (epsRF == 0)
407     {
408         /* This means infinity! */
409         lambda = 0;
410         rffac  = 1;
411     }
412     else
413     {
414         lambda = (eps0 - 1.0)/(2*epsRF - 1.0);
415         rffac  = (2*epsRF+eps0)/(2*epsRF+1);
416     }
417     printf("DATA INTEGRAL: %5.1f, tauD(old) = %5.1f ps, "
418            "tau_slope = %5.1f, tau_slope,D = %5.1f ps\n",
419            integral, integral*rffac, fitparms[0], fitparms[0]*rffac);
420
421     printf("tau_D from tau1 = %8.3g , eps(Infty) = %8.3f\n",
422            fitparms[0]*(1 + fitparms[1]*lambda),
423            1 + ((1 - fitparms[1])*(eps0 - 1))/(1 + fitparms[1]*lambda));
424
425     fitintegral = numerical_deriv(nx, y[0], y[1], y[3], y[4], y[5], tendInt, nsmooth);
426     printf("FIT INTEGRAL (tau_M): %5.1f, tau_D = %5.1f\n",
427            fitintegral, fitintegral*rffac);
428
429     /* Now we have the negative gradient of <Phi(0) Phi(t)> */
430     write_xvg(opt2fn("-d", NFILE, fnm), "Data", nx-1, 6, y, legend, oenv);
431
432     /* Do FFT and analysis */
433     do_four(opt2fn("-o", NFILE, fnm), opt2fn("-c", NFILE, fnm),
434             nx-1, y[0], y[5], eps0, epsRF, oenv);
435
436     do_view(oenv, opt2fn("-o", NFILE, fnm), "-nxy");
437     do_view(oenv, opt2fn("-c", NFILE, fnm), NULL);
438     do_view(oenv, opt2fn("-d", NFILE, fnm), "-nxy");
439
440     return 0;
441 }