Always set b-state posres, even if identical to a-state
[alexxy/gromacs.git] / src / gromacs / mdlib / tables.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 #ifdef HAVE_CONFIG_H
38 #include <config.h>
39 #endif
40
41 #include <math.h>
42 #include "gromacs/math/utilities.h"
43 #include "typedefs.h"
44 #include "names.h"
45 #include "gromacs/utility/smalloc.h"
46 #include "gmx_fatal.h"
47 #include "gromacs/fileio/futil.h"
48 #include "xvgr.h"
49 #include "vec.h"
50 #include "main.h"
51 #include "network.h"
52 #include "physics.h"
53 #include "force.h"
54 #include "gromacs/fileio/gmxfio.h"
55 #include "macros.h"
56 #include "tables.h"
57
58 /* All the possible (implemented) table functions */
59 enum {
60     etabLJ6,
61     etabLJ12,
62     etabLJ6Shift,
63     etabLJ12Shift,
64     etabShift,
65     etabRF,
66     etabRF_ZERO,
67     etabCOUL,
68     etabEwald,
69     etabEwaldSwitch,
70     etabEwaldUser,
71     etabEwaldUserSwitch,
72     etabLJ6Ewald,
73     etabLJ6Switch,
74     etabLJ12Switch,
75     etabCOULSwitch,
76     etabLJ6Encad,
77     etabLJ12Encad,
78     etabCOULEncad,
79     etabEXPMIN,
80     etabUSER,
81     etabNR
82 };
83
84 /** Evaluates to true if the table type contains user data. */
85 #define ETAB_USER(e)  ((e) == etabUSER || \
86                        (e) == etabEwaldUser || (e) == etabEwaldUserSwitch)
87
88 typedef struct {
89     const char *name;
90     gmx_bool    bCoulomb;
91 } t_tab_props;
92
93 /* This structure holds name and a flag that tells whether
94    this is a Coulomb type funtion */
95 static const t_tab_props tprops[etabNR] = {
96     { "LJ6",  FALSE },
97     { "LJ12", FALSE },
98     { "LJ6Shift", FALSE },
99     { "LJ12Shift", FALSE },
100     { "Shift", TRUE },
101     { "RF", TRUE },
102     { "RF-zero", TRUE },
103     { "COUL", TRUE },
104     { "Ewald", TRUE },
105     { "Ewald-Switch", TRUE },
106     { "Ewald-User", TRUE },
107     { "Ewald-User-Switch", TRUE },
108     { "LJ6Ewald", FALSE },
109     { "LJ6Switch", FALSE },
110     { "LJ12Switch", FALSE },
111     { "COULSwitch", TRUE },
112     { "LJ6-Encad shift", FALSE },
113     { "LJ12-Encad shift", FALSE },
114     { "COUL-Encad shift",  TRUE },
115     { "EXPMIN", FALSE },
116     { "USER", FALSE },
117 };
118
119 /* Index in the table that says which function to use */
120 enum {
121     etiCOUL, etiLJ6, etiLJ12, etiNR
122 };
123
124 typedef struct {
125     int     nx, nx0;
126     double  tabscale;
127     double *x, *v, *f;
128 } t_tabledata;
129
130 #define pow2(x) ((x)*(x))
131 #define pow3(x) ((x)*(x)*(x))
132 #define pow4(x) ((x)*(x)*(x)*(x))
133 #define pow5(x) ((x)*(x)*(x)*(x)*(x))
134
135 double v_q_ewald_lr(double beta, double r)
136 {
137     if (r == 0)
138     {
139         return beta*2/sqrt(M_PI);
140     }
141     else
142     {
143         return gmx_erfd(beta*r)/r;
144     }
145 }
146
147 double v_lj_ewald_lr(double beta, double r)
148 {
149     double br, br2, br4, r6, factor;
150     if (r == 0)
151     {
152         return pow(beta, 6)/6;
153     }
154     else
155     {
156         br     = beta*r;
157         br2    = br*br;
158         br4    = br2*br2;
159         r6     = pow(r, 6.0);
160         factor = (1.0 - exp(-br2)*(1 + br2 + 0.5*br4))/r6;
161         return factor;
162     }
163 }
164
165 void table_spline3_fill_ewald_lr(real                                 *table_f,
166                                  real                                 *table_v,
167                                  real                                 *table_fdv0,
168                                  int                                   ntab,
169                                  real                                  dx,
170                                  real                                  beta,
171                                  real_space_grid_contribution_computer v_lr)
172 {
173     real     tab_max;
174     int      i, i_inrange;
175     double   dc, dc_new;
176     gmx_bool bOutOfRange;
177     double   v_r0, v_r1, v_inrange, vi, a0, a1, a2dx;
178     double   x_r0;
179
180     /* This function is called using either v_ewald_lr or v_lj_ewald_lr as a function argument
181      * depending on wether we should create electrostatic or Lennard-Jones Ewald tables.
182      */
183
184     if (ntab < 2)
185     {
186         gmx_fatal(FARGS, "Can not make a spline table with less than 2 points");
187     }
188
189     /* We need some margin to be able to divide table values by r
190      * in the kernel and also to do the integration arithmetics
191      * without going out of range. Furthemore, we divide by dx below.
192      */
193     tab_max = GMX_REAL_MAX*0.0001;
194
195     /* This function produces a table with:
196      * maximum energy error: V'''/(6*12*sqrt(3))*dx^3
197      * maximum force error:  V'''/(6*4)*dx^2
198      * The rms force error is the max error times 1/sqrt(5)=0.45.
199      */
200
201     bOutOfRange = FALSE;
202     i_inrange   = ntab;
203     v_inrange   = 0;
204     dc          = 0;
205     for (i = ntab-1; i >= 0; i--)
206     {
207         x_r0 = i*dx;
208
209         v_r0 = (*v_lr)(beta, x_r0);
210
211         if (!bOutOfRange)
212         {
213             i_inrange = i;
214             v_inrange = v_r0;
215
216             vi = v_r0;
217         }
218         else
219         {
220             /* Linear continuation for the last point in range */
221             vi = v_inrange - dc*(i - i_inrange)*dx;
222         }
223
224         if (table_v != NULL)
225         {
226             table_v[i] = vi;
227         }
228
229         if (i == 0)
230         {
231             continue;
232         }
233
234         /* Get the potential at table point i-1 */
235         v_r1 = (*v_lr)(beta, (i-1)*dx);
236
237         if (v_r1 != v_r1 || v_r1 < -tab_max || v_r1 > tab_max)
238         {
239             bOutOfRange = TRUE;
240         }
241
242         if (!bOutOfRange)
243         {
244             /* Calculate the average second derivative times dx over interval i-1 to i.
245              * Using the function values at the end points and in the middle.
246              */
247             a2dx = (v_r0 + v_r1 - 2*(*v_lr)(beta, x_r0-0.5*dx))/(0.25*dx);
248             /* Set the derivative of the spline to match the difference in potential
249              * over the interval plus the average effect of the quadratic term.
250              * This is the essential step for minimizing the error in the force.
251              */
252             dc = (v_r0 - v_r1)/dx + 0.5*a2dx;
253         }
254
255         if (i == ntab - 1)
256         {
257             /* Fill the table with the force, minus the derivative of the spline */
258             table_f[i] = -dc;
259         }
260         else
261         {
262             /* tab[i] will contain the average of the splines over the two intervals */
263             table_f[i] += -0.5*dc;
264         }
265
266         if (!bOutOfRange)
267         {
268             /* Make spline s(x) = a0 + a1*(x - xr) + 0.5*a2*(x - xr)^2
269              * matching the potential at the two end points
270              * and the derivative dc at the end point xr.
271              */
272             a0   = v_r0;
273             a1   = dc;
274             a2dx = (a1*dx + v_r1 - a0)*2/dx;
275
276             /* Set dc to the derivative at the next point */
277             dc_new = a1 - a2dx;
278
279             if (dc_new != dc_new || dc_new < -tab_max || dc_new > tab_max)
280             {
281                 bOutOfRange = TRUE;
282             }
283             else
284             {
285                 dc = dc_new;
286             }
287         }
288
289         table_f[(i-1)] = -0.5*dc;
290     }
291     /* Currently the last value only contains half the force: double it */
292     table_f[0] *= 2;
293
294     if (table_v != NULL && table_fdv0 != NULL)
295     {
296         /* Copy to FDV0 table too. Allocation occurs in forcerec.c,
297          * init_ewald_f_table().
298          */
299         for (i = 0; i < ntab-1; i++)
300         {
301             table_fdv0[4*i]     = table_f[i];
302             table_fdv0[4*i+1]   = table_f[i+1]-table_f[i];
303             table_fdv0[4*i+2]   = table_v[i];
304             table_fdv0[4*i+3]   = 0.0;
305         }
306         table_fdv0[4*(ntab-1)]    = table_f[(ntab-1)];
307         table_fdv0[4*(ntab-1)+1]  = -table_f[(ntab-1)];
308         table_fdv0[4*(ntab-1)+2]  = table_v[(ntab-1)];
309         table_fdv0[4*(ntab-1)+3]  = 0.0;
310     }
311 }
312
313 /* The scale (1/spacing) for third order spline interpolation
314  * of the Ewald mesh contribution which needs to be subtracted
315  * from the non-bonded interactions.
316  */
317 real ewald_spline3_table_scale(real ewaldcoeff, real rc)
318 {
319     double erf_x_d3 = 1.0522; /* max of (erf(x)/x)''' */
320     double ftol, etol;
321     double sc_f, sc_e;
322
323     /* Force tolerance: single precision accuracy */
324     ftol = GMX_FLOAT_EPS;
325     sc_f = sqrt(erf_x_d3/(6*4*ftol*ewaldcoeff))*ewaldcoeff;
326
327     /* Energy tolerance: 10x more accurate than the cut-off jump */
328     etol = 0.1*gmx_erfc(ewaldcoeff*rc);
329     etol = max(etol, GMX_REAL_EPS);
330     sc_e = pow(erf_x_d3/(6*12*sqrt(3)*etol), 1.0/3.0)*ewaldcoeff;
331
332     return max(sc_f, sc_e);
333 }
334
335 /* Calculate the potential and force for an r value
336  * in exactly the same way it is done in the inner loop.
337  * VFtab is a pointer to the table data, offset is
338  * the point where we should begin and stride is
339  * 4 if we have a buckingham table, 3 otherwise.
340  * If you want to evaluate table no N, set offset to 4*N.
341  *
342  * We use normal precision here, since that is what we
343  * will use in the inner loops.
344  */
345 static void evaluate_table(real VFtab[], int offset, int stride,
346                            real tabscale, real r, real *y, real *yp)
347 {
348     int  n;
349     real rt, eps, eps2;
350     real Y, F, Geps, Heps2, Fp;
351
352     rt       =  r*tabscale;
353     n        =  (int)rt;
354     eps      =  rt - n;
355     eps2     =  eps*eps;
356     n        =  offset+stride*n;
357     Y        =  VFtab[n];
358     F        =  VFtab[n+1];
359     Geps     =  eps*VFtab[n+2];
360     Heps2    =  eps2*VFtab[n+3];
361     Fp       =  F+Geps+Heps2;
362     *y       =  Y+eps*Fp;
363     *yp      =  (Fp+Geps+2.0*Heps2)*tabscale;
364 }
365
366 static void copy2table(int n, int offset, int stride,
367                        double x[], double Vtab[], double Ftab[], real scalefactor,
368                        real dest[])
369 {
370 /* Use double prec. for the intermediary variables
371  * and temporary x/vtab/vtab2 data to avoid unnecessary
372  * loss of precision.
373  */
374     int    i, nn0;
375     double F, G, H, h;
376
377     h = 0;
378     for (i = 0; (i < n); i++)
379     {
380         if (i < n-1)
381         {
382             h   = x[i+1] - x[i];
383             F   = -Ftab[i]*h;
384             G   =  3*(Vtab[i+1] - Vtab[i]) + (Ftab[i+1] + 2*Ftab[i])*h;
385             H   = -2*(Vtab[i+1] - Vtab[i]) - (Ftab[i+1] +   Ftab[i])*h;
386         }
387         else
388         {
389             /* Fill the last entry with a linear potential,
390              * this is mainly for rounding issues with angle and dihedral potentials.
391              */
392             F   = -Ftab[i]*h;
393             G   = 0;
394             H   = 0;
395         }
396         nn0         = offset + i*stride;
397         dest[nn0]   = scalefactor*Vtab[i];
398         dest[nn0+1] = scalefactor*F;
399         dest[nn0+2] = scalefactor*G;
400         dest[nn0+3] = scalefactor*H;
401     }
402 }
403
404 static void init_table(int n, int nx0,
405                        double tabscale, t_tabledata *td, gmx_bool bAlloc)
406 {
407     int i;
408
409     td->nx       = n;
410     td->nx0      = nx0;
411     td->tabscale = tabscale;
412     if (bAlloc)
413     {
414         snew(td->x, td->nx);
415         snew(td->v, td->nx);
416         snew(td->f, td->nx);
417     }
418     for (i = 0; (i < td->nx); i++)
419     {
420         td->x[i] = i/tabscale;
421     }
422 }
423
424 static void spline_forces(int nx, double h, double v[], gmx_bool bS3, gmx_bool bE3,
425                           double f[])
426 {
427     int    start, end, i;
428     double v3, b_s, b_e, b;
429     double beta, *gamma;
430
431     /* Formulas can be found in:
432      * H.J.C. Berendsen, Simulating the Physical World, Cambridge 2007
433      */
434
435     if (nx < 4 && (bS3 || bE3))
436     {
437         gmx_fatal(FARGS, "Can not generate splines with third derivative boundary conditions with less than 4 (%d) points", nx);
438     }
439
440     /* To make life easy we initially set the spacing to 1
441      * and correct for this at the end.
442      */
443     beta = 2;
444     if (bS3)
445     {
446         /* Fit V''' at the start */
447         v3  = v[3] - 3*v[2] + 3*v[1] - v[0];
448         if (debug)
449         {
450             fprintf(debug, "The left third derivative is %g\n", v3/(h*h*h));
451         }
452         b_s   = 2*(v[1] - v[0]) + v3/6;
453         start = 0;
454
455         if (FALSE)
456         {
457             /* Fit V'' at the start */
458             real v2;
459
460             v2  = -v[3] + 4*v[2] - 5*v[1] + 2*v[0];
461             /* v2  = v[2] - 2*v[1] + v[0]; */
462             if (debug)
463             {
464                 fprintf(debug, "The left second derivative is %g\n", v2/(h*h));
465             }
466             b_s   = 3*(v[1] - v[0]) - v2/2;
467             start = 0;
468         }
469     }
470     else
471     {
472         b_s   = 3*(v[2] - v[0]) + f[0]*h;
473         start = 1;
474     }
475     if (bE3)
476     {
477         /* Fit V''' at the end */
478         v3  = v[nx-1] - 3*v[nx-2] + 3*v[nx-3] - v[nx-4];
479         if (debug)
480         {
481             fprintf(debug, "The right third derivative is %g\n", v3/(h*h*h));
482         }
483         b_e = 2*(v[nx-1] - v[nx-2]) + v3/6;
484         end = nx;
485     }
486     else
487     {
488         /* V'=0 at the end */
489         b_e = 3*(v[nx-1] - v[nx-3]) + f[nx-1]*h;
490         end = nx - 1;
491     }
492
493     snew(gamma, nx);
494     beta = (bS3 ? 1 : 4);
495
496     /* For V'' fitting */
497     /* beta = (bS3 ? 2 : 4); */
498
499     f[start] = b_s/beta;
500     for (i = start+1; i < end; i++)
501     {
502         gamma[i] = 1/beta;
503         beta     = 4 - gamma[i];
504         b        =  3*(v[i+1] - v[i-1]);
505         f[i]     = (b - f[i-1])/beta;
506     }
507     gamma[end-1] = 1/beta;
508     beta         = (bE3 ? 1 : 4) - gamma[end-1];
509     f[end-1]     = (b_e - f[end-2])/beta;
510
511     for (i = end-2; i >= start; i--)
512     {
513         f[i] -= gamma[i+1]*f[i+1];
514     }
515     sfree(gamma);
516
517     /* Correct for the minus sign and the spacing */
518     for (i = start; i < end; i++)
519     {
520         f[i] = -f[i]/h;
521     }
522 }
523
524 static void set_forces(FILE *fp, int angle,
525                        int nx, double h, double v[], double f[],
526                        int table)
527 {
528     int start, end;
529
530     if (angle == 2)
531     {
532         gmx_fatal(FARGS,
533                   "Force generation for dihedral tables is not (yet) implemented");
534     }
535
536     start = 0;
537     while (v[start] == 0)
538     {
539         start++;
540     }
541
542     end = nx;
543     while (v[end-1] == 0)
544     {
545         end--;
546     }
547     if (end > nx - 2)
548     {
549         end = nx;
550     }
551     else
552     {
553         end++;
554     }
555
556     if (fp)
557     {
558         fprintf(fp, "Generating forces for table %d, boundary conditions: V''' at %g, %s at %g\n",
559                 table+1, start*h, end == nx ? "V'''" : "V'=0", (end-1)*h);
560     }
561     spline_forces(end-start, h, v+start, TRUE, end == nx, f+start);
562 }
563
564 static void read_tables(FILE *fp, const char *fn,
565                         int ntab, int angle, t_tabledata td[])
566 {
567     char    *libfn;
568     char     buf[STRLEN];
569     double **yy = NULL, start, end, dx0, dx1, ssd, vm, vp, f, numf;
570     int      k, i, nx, nx0 = 0, ny, nny, ns;
571     gmx_bool bAllZero, bZeroV, bZeroF;
572     double   tabscale;
573
574     nny   = 2*ntab+1;
575     libfn = gmxlibfn(fn);
576     nx    = read_xvg(libfn, &yy, &ny);
577     if (ny != nny)
578     {
579         gmx_fatal(FARGS, "Trying to read file %s, but nr columns = %d, should be %d",
580                   libfn, ny, nny);
581     }
582     if (angle == 0)
583     {
584         if (yy[0][0] != 0.0)
585         {
586             gmx_fatal(FARGS,
587                       "The first distance in file %s is %f nm instead of %f nm",
588                       libfn, yy[0][0], 0.0);
589         }
590     }
591     else
592     {
593         if (angle == 1)
594         {
595             start = 0.0;
596         }
597         else
598         {
599             start = -180.0;
600         }
601         end = 180.0;
602         if (yy[0][0] != start || yy[0][nx-1] != end)
603         {
604             gmx_fatal(FARGS, "The angles in file %s should go from %f to %f instead of %f to %f\n",
605                       libfn, start, end, yy[0][0], yy[0][nx-1]);
606         }
607     }
608
609     tabscale = (nx-1)/(yy[0][nx-1] - yy[0][0]);
610
611     if (fp)
612     {
613         fprintf(fp, "Read user tables from %s with %d data points.\n", libfn, nx);
614         if (angle == 0)
615         {
616             fprintf(fp, "Tabscale = %g points/nm\n", tabscale);
617         }
618     }
619
620     bAllZero = TRUE;
621     for (k = 0; k < ntab; k++)
622     {
623         bZeroV = TRUE;
624         bZeroF = TRUE;
625         for (i = 0; (i < nx); i++)
626         {
627             if (i >= 2)
628             {
629                 dx0 = yy[0][i-1] - yy[0][i-2];
630                 dx1 = yy[0][i]   - yy[0][i-1];
631                 /* Check for 1% deviation in spacing */
632                 if (fabs(dx1 - dx0) >= 0.005*(fabs(dx0) + fabs(dx1)))
633                 {
634                     gmx_fatal(FARGS, "In table file '%s' the x values are not equally spaced: %f %f %f", fn, yy[0][i-2], yy[0][i-1], yy[0][i]);
635                 }
636             }
637             if (yy[1+k*2][i] != 0)
638             {
639                 bZeroV = FALSE;
640                 if (bAllZero)
641                 {
642                     bAllZero = FALSE;
643                     nx0      = i;
644                 }
645                 if (yy[1+k*2][i] >  0.01*GMX_REAL_MAX ||
646                     yy[1+k*2][i] < -0.01*GMX_REAL_MAX)
647                 {
648                     gmx_fatal(FARGS, "Out of range potential value %g in file '%s'",
649                               yy[1+k*2][i], fn);
650                 }
651             }
652             if (yy[1+k*2+1][i] != 0)
653             {
654                 bZeroF = FALSE;
655                 if (bAllZero)
656                 {
657                     bAllZero = FALSE;
658                     nx0      = i;
659                 }
660                 if (yy[1+k*2+1][i] >  0.01*GMX_REAL_MAX ||
661                     yy[1+k*2+1][i] < -0.01*GMX_REAL_MAX)
662                 {
663                     gmx_fatal(FARGS, "Out of range force value %g in file '%s'",
664                               yy[1+k*2+1][i], fn);
665                 }
666             }
667         }
668
669         if (!bZeroV && bZeroF)
670         {
671             set_forces(fp, angle, nx, 1/tabscale, yy[1+k*2], yy[1+k*2+1], k);
672         }
673         else
674         {
675             /* Check if the second column is close to minus the numerical
676              * derivative of the first column.
677              */
678             ssd = 0;
679             ns  = 0;
680             for (i = 1; (i < nx-1); i++)
681             {
682                 vm = yy[1+2*k][i-1];
683                 vp = yy[1+2*k][i+1];
684                 f  = yy[1+2*k+1][i];
685                 if (vm != 0 && vp != 0 && f != 0)
686                 {
687                     /* Take the centered difference */
688                     numf = -(vp - vm)*0.5*tabscale;
689                     ssd += fabs(2*(f - numf)/(f + numf));
690                     ns++;
691                 }
692             }
693             if (ns > 0)
694             {
695                 ssd /= ns;
696                 sprintf(buf, "For the %d non-zero entries for table %d in %s the forces deviate on average %d%% from minus the numerical derivative of the potential\n", ns, k, libfn, (int)(100*ssd+0.5));
697                 if (debug)
698                 {
699                     fprintf(debug, "%s", buf);
700                 }
701                 if (ssd > 0.2)
702                 {
703                     if (fp)
704                     {
705                         fprintf(fp, "\nWARNING: %s\n", buf);
706                     }
707                     fprintf(stderr, "\nWARNING: %s\n", buf);
708                 }
709             }
710         }
711     }
712     if (bAllZero && fp)
713     {
714         fprintf(fp, "\nNOTE: All elements in table %s are zero\n\n", libfn);
715     }
716
717     for (k = 0; (k < ntab); k++)
718     {
719         init_table(nx, nx0, tabscale, &(td[k]), TRUE);
720         for (i = 0; (i < nx); i++)
721         {
722             td[k].x[i] = yy[0][i];
723             td[k].v[i] = yy[2*k+1][i];
724             td[k].f[i] = yy[2*k+2][i];
725         }
726     }
727     for (i = 0; (i < ny); i++)
728     {
729         sfree(yy[i]);
730     }
731     sfree(yy);
732     sfree(libfn);
733 }
734
735 static void done_tabledata(t_tabledata *td)
736 {
737     int i;
738
739     if (!td)
740     {
741         return;
742     }
743
744     sfree(td->x);
745     sfree(td->v);
746     sfree(td->f);
747 }
748
749 static void fill_table(t_tabledata *td, int tp, const t_forcerec *fr,
750                        gmx_bool b14only)
751 {
752     /* Fill the table according to the formulas in the manual.
753      * In principle, we only need the potential and the second
754      * derivative, but then we would have to do lots of calculations
755      * in the inner loop. By precalculating some terms (see manual)
756      * we get better eventual performance, despite a larger table.
757      *
758      * Since some of these higher-order terms are very small,
759      * we always use double precision to calculate them here, in order
760      * to avoid unnecessary loss of precision.
761      */
762 #ifdef DEBUG_SWITCH
763     FILE    *fp;
764 #endif
765     int      i;
766     double   reppow, p;
767     double   r1, rc, r12, r13;
768     double   r, r2, r6, rc2, rc6, rc12;
769     double   expr, Vtab, Ftab;
770     /* Parameters for David's function */
771     double   A = 0, B = 0, C = 0, A_3 = 0, B_4 = 0;
772     /* Parameters for the switching function */
773     double   ksw, swi, swi1;
774     /* Temporary parameters */
775     gmx_bool bPotentialSwitch, bForceSwitch, bPotentialShift;
776     double   ewc   = fr->ewaldcoeff_q;
777     double   ewclj = fr->ewaldcoeff_lj;
778     double   Vcut  = 0;
779
780     if (b14only)
781     {
782         bPotentialSwitch = FALSE;
783         bForceSwitch     = FALSE;
784         bPotentialShift  = FALSE;
785     }
786     else
787     {
788         bPotentialSwitch = ((tp == etabLJ6Switch) || (tp == etabLJ12Switch) ||
789                             (tp == etabCOULSwitch) ||
790                             (tp == etabEwaldSwitch) || (tp == etabEwaldUserSwitch) ||
791                             (tprops[tp].bCoulomb && (fr->coulomb_modifier == eintmodPOTSWITCH)) ||
792                             (!tprops[tp].bCoulomb && (fr->vdw_modifier == eintmodPOTSWITCH)));
793         bForceSwitch  = ((tp == etabLJ6Shift) || (tp == etabLJ12Shift) ||
794                          (tp == etabShift) ||
795                          (tprops[tp].bCoulomb && (fr->coulomb_modifier == eintmodFORCESWITCH)) ||
796                          (!tprops[tp].bCoulomb && (fr->vdw_modifier == eintmodFORCESWITCH)));
797         bPotentialShift = ((tprops[tp].bCoulomb && (fr->coulomb_modifier == eintmodPOTSHIFT)) ||
798                            (!tprops[tp].bCoulomb && (fr->vdw_modifier == eintmodPOTSHIFT)));
799     }
800
801     reppow = fr->reppow;
802
803     if (tprops[tp].bCoulomb)
804     {
805         r1 = fr->rcoulomb_switch;
806         rc = fr->rcoulomb;
807     }
808     else
809     {
810         r1 = fr->rvdw_switch;
811         rc = fr->rvdw;
812     }
813     if (bPotentialSwitch)
814     {
815         ksw  = 1.0/(pow5(rc-r1));
816     }
817     else
818     {
819         ksw  = 0.0;
820     }
821     if (bForceSwitch)
822     {
823         if (tp == etabShift)
824         {
825             p = 1;
826         }
827         else if (tp == etabLJ6Shift)
828         {
829             p = 6;
830         }
831         else
832         {
833             p = reppow;
834         }
835
836         A = p * ((p+1)*r1-(p+4)*rc)/(pow(rc, p+2)*pow2(rc-r1));
837         B = -p * ((p+1)*r1-(p+3)*rc)/(pow(rc, p+2)*pow3(rc-r1));
838         C = 1.0/pow(rc, p)-A/3.0*pow3(rc-r1)-B/4.0*pow4(rc-r1);
839         if (tp == etabLJ6Shift)
840         {
841             A = -A;
842             B = -B;
843             C = -C;
844         }
845         A_3 = A/3.0;
846         B_4 = B/4.0;
847     }
848     if (debug)
849     {
850         fprintf(debug, "Setting up tables\n"); fflush(debug);
851     }
852
853 #ifdef DEBUG_SWITCH
854     fp = xvgropen("switch.xvg", "switch", "r", "s");
855 #endif
856
857     if (bPotentialShift)
858     {
859         rc2   = rc*rc;
860         rc6   = 1.0/(rc2*rc2*rc2);
861         if (gmx_within_tol(reppow, 12.0, 10*GMX_DOUBLE_EPS))
862         {
863             rc12 = rc6*rc6;
864         }
865         else
866         {
867             rc12 = pow(rc, -reppow);
868         }
869
870         switch (tp)
871         {
872             case etabLJ6:
873                 /* Dispersion */
874                 Vcut = -rc6;
875                 break;
876             case etabLJ6Ewald:
877                 Vcut  = -rc6*exp(-ewclj*ewclj*rc2)*(1 + ewclj*ewclj*rc2 + pow4(ewclj)*rc2*rc2/2);
878                 break;
879             case etabLJ12:
880                 /* Repulsion */
881                 Vcut  = rc12;
882                 break;
883             case etabCOUL:
884                 Vcut  = 1.0/rc;
885                 break;
886             case etabEwald:
887             case etabEwaldSwitch:
888                 Vtab  = gmx_erfc(ewc*rc)/rc;
889                 break;
890             case etabEwaldUser:
891                 /* Only calculate minus the reciprocal space contribution */
892                 Vtab  = -gmx_erf(ewc*rc)/rc;
893                 break;
894             case etabRF:
895             case etabRF_ZERO:
896                 /* No need for preventing the usage of modifiers with RF */
897                 Vcut  = 0.0;
898                 break;
899             case etabEXPMIN:
900                 Vcut  = exp(-rc);
901                 break;
902             default:
903                 gmx_fatal(FARGS, "Cannot apply new potential-shift modifier to interaction type '%s' yet. (%s,%d)",
904                           tprops[tp].name, __FILE__, __LINE__);
905         }
906     }
907
908     for (i = td->nx0; (i < td->nx); i++)
909     {
910         r     = td->x[i];
911         r2    = r*r;
912         r6    = 1.0/(r2*r2*r2);
913         if (gmx_within_tol(reppow, 12.0, 10*GMX_DOUBLE_EPS))
914         {
915             r12 = r6*r6;
916         }
917         else
918         {
919             r12 = pow(r, -reppow);
920         }
921         Vtab  = 0.0;
922         Ftab  = 0.0;
923         if (bPotentialSwitch)
924         {
925             /* swi is function, swi1 1st derivative and swi2 2nd derivative */
926             /* The switch function is 1 for r<r1, 0 for r>rc, and smooth for
927              * r1<=r<=rc. The 1st and 2nd derivatives are both zero at
928              * r1 and rc.
929              * ksw is just the constant 1/(rc-r1)^5, to save some calculations...
930              */
931             if (r <= r1)
932             {
933                 swi  = 1.0;
934                 swi1 = 0.0;
935             }
936             else if (r >= rc)
937             {
938                 swi  = 0.0;
939                 swi1 = 0.0;
940             }
941             else
942             {
943                 swi      = 1 - 10*pow3(r-r1)*ksw*pow2(rc-r1)
944                     + 15*pow4(r-r1)*ksw*(rc-r1) - 6*pow5(r-r1)*ksw;
945                 swi1     = -30*pow2(r-r1)*ksw*pow2(rc-r1)
946                     + 60*pow3(r-r1)*ksw*(rc-r1) - 30*pow4(r-r1)*ksw;
947             }
948         }
949         else /* not really needed, but avoids compiler warnings... */
950         {
951             swi  = 1.0;
952             swi1 = 0.0;
953         }
954 #ifdef DEBUG_SWITCH
955         fprintf(fp, "%10g  %10g  %10g  %10g\n", r, swi, swi1, swi2);
956 #endif
957
958         rc6 = rc*rc*rc;
959         rc6 = 1.0/(rc6*rc6);
960
961         switch (tp)
962         {
963             case etabLJ6:
964                 /* Dispersion */
965                 Vtab = -r6;
966                 Ftab = 6.0*Vtab/r;
967                 break;
968             case etabLJ6Switch:
969             case etabLJ6Shift:
970                 /* Dispersion */
971                 if (r < rc)
972                 {
973                     Vtab = -r6;
974                     Ftab = 6.0*Vtab/r;
975                     break;
976                 }
977                 break;
978             case etabLJ12:
979                 /* Repulsion */
980                 Vtab  = r12;
981                 Ftab  = reppow*Vtab/r;
982                 break;
983             case etabLJ12Switch:
984             case etabLJ12Shift:
985                 /* Repulsion */
986                 if (r < rc)
987                 {
988                     Vtab  = r12;
989                     Ftab  = reppow*Vtab/r;
990                 }
991                 break;
992             case etabLJ6Encad:
993                 if (r < rc)
994                 {
995                     Vtab  = -(r6-6.0*(rc-r)*rc6/rc-rc6);
996                     Ftab  = -(6.0*r6/r-6.0*rc6/rc);
997                 }
998                 else /* r>rc */
999                 {
1000                     Vtab  = 0;
1001                     Ftab  = 0;
1002                 }
1003                 break;
1004             case etabLJ12Encad:
1005                 if (r < rc)
1006                 {
1007                     Vtab  = -(r6-6.0*(rc-r)*rc6/rc-rc6);
1008                     Ftab  = -(6.0*r6/r-6.0*rc6/rc);
1009                 }
1010                 else /* r>rc */
1011                 {
1012                     Vtab  = 0;
1013                     Ftab  = 0;
1014                 }
1015                 break;
1016             case etabCOUL:
1017                 Vtab  = 1.0/r;
1018                 Ftab  = 1.0/r2;
1019                 break;
1020             case etabCOULSwitch:
1021             case etabShift:
1022                 if (r < rc)
1023                 {
1024                     Vtab  = 1.0/r;
1025                     Ftab  = 1.0/r2;
1026                 }
1027                 break;
1028             case etabEwald:
1029             case etabEwaldSwitch:
1030                 Vtab  = gmx_erfc(ewc*r)/r;
1031                 Ftab  = gmx_erfc(ewc*r)/r2+exp(-(ewc*ewc*r2))*ewc*M_2_SQRTPI/r;
1032                 break;
1033             case etabEwaldUser:
1034             case etabEwaldUserSwitch:
1035                 /* Only calculate the negative of the reciprocal space contribution */
1036                 Vtab  = -gmx_erf(ewc*r)/r;
1037                 Ftab  = -gmx_erf(ewc*r)/r2+exp(-(ewc*ewc*r2))*ewc*M_2_SQRTPI/r;
1038                 break;
1039             case etabLJ6Ewald:
1040                 Vtab  = -r6*exp(-ewclj*ewclj*r2)*(1 + ewclj*ewclj*r2 + pow4(ewclj)*r2*r2/2);
1041                 Ftab  = 6.0*Vtab/r - r6*exp(-ewclj*ewclj*r2)*pow5(ewclj)*ewclj*r2*r2*r;
1042                 break;
1043             case etabRF:
1044             case etabRF_ZERO:
1045                 Vtab  = 1.0/r      +   fr->k_rf*r2 - fr->c_rf;
1046                 Ftab  = 1.0/r2     - 2*fr->k_rf*r;
1047                 if (tp == etabRF_ZERO && r >= rc)
1048                 {
1049                     Vtab = 0;
1050                     Ftab = 0;
1051                 }
1052                 break;
1053             case etabEXPMIN:
1054                 expr  = exp(-r);
1055                 Vtab  = expr;
1056                 Ftab  = expr;
1057                 break;
1058             case etabCOULEncad:
1059                 if (r < rc)
1060                 {
1061                     Vtab  = 1.0/r-(rc-r)/(rc*rc)-1.0/rc;
1062                     Ftab  = 1.0/r2-1.0/(rc*rc);
1063                 }
1064                 else /* r>rc */
1065                 {
1066                     Vtab  = 0;
1067                     Ftab  = 0;
1068                 }
1069                 break;
1070             default:
1071                 gmx_fatal(FARGS, "Table type %d not implemented yet. (%s,%d)",
1072                           tp, __FILE__, __LINE__);
1073         }
1074         if (bForceSwitch)
1075         {
1076             /* Normal coulomb with cut-off correction for potential */
1077             if (r < rc)
1078             {
1079                 Vtab -= C;
1080                 /* If in Shifting range add something to it */
1081                 if (r > r1)
1082                 {
1083                     r12    = (r-r1)*(r-r1);
1084                     r13    = (r-r1)*r12;
1085                     Vtab  += -A_3*r13 - B_4*r12*r12;
1086                     Ftab  +=   A*r12 + B*r13;
1087                 }
1088             }
1089             else
1090             {
1091                 /* Make sure interactions are zero outside cutoff with modifiers */
1092                 Vtab = 0;
1093                 Ftab = 0;
1094             }
1095         }
1096         if (bPotentialShift)
1097         {
1098             if (r < rc)
1099             {
1100                 Vtab -= Vcut;
1101             }
1102             else
1103             {
1104                 /* Make sure interactions are zero outside cutoff with modifiers */
1105                 Vtab = 0;
1106                 Ftab = 0;
1107             }
1108         }
1109
1110         if (ETAB_USER(tp))
1111         {
1112             Vtab += td->v[i];
1113             Ftab += td->f[i];
1114         }
1115
1116         if (bPotentialSwitch)
1117         {
1118             if (r >= rc)
1119             {
1120                 /* Make sure interactions are zero outside cutoff with modifiers */
1121                 Vtab = 0;
1122                 Ftab = 0;
1123             }
1124             else if (r > r1)
1125             {
1126                 Ftab = Ftab*swi - Vtab*swi1;
1127                 Vtab = Vtab*swi;
1128             }
1129         }
1130         /* Convert to single precision when we store to mem */
1131         td->v[i]  = Vtab;
1132         td->f[i]  = Ftab;
1133     }
1134
1135     /* Continue the table linearly from nx0 to 0.
1136      * These values are only required for energy minimization with overlap or TPI.
1137      */
1138     for (i = td->nx0-1; i >= 0; i--)
1139     {
1140         td->v[i] = td->v[i+1] + td->f[i+1]*(td->x[i+1] - td->x[i]);
1141         td->f[i] = td->f[i+1];
1142     }
1143
1144 #ifdef DEBUG_SWITCH
1145     gmx_fio_fclose(fp);
1146 #endif
1147 }
1148
1149 static void set_table_type(int tabsel[], const t_forcerec *fr, gmx_bool b14only)
1150 {
1151     int eltype, vdwtype;
1152
1153     /* Set the different table indices.
1154      * Coulomb first.
1155      */
1156
1157
1158     if (b14only)
1159     {
1160         switch (fr->eeltype)
1161         {
1162             case eelRF_NEC:
1163                 eltype = eelRF;
1164                 break;
1165             case eelUSER:
1166             case eelPMEUSER:
1167             case eelPMEUSERSWITCH:
1168                 eltype = eelUSER;
1169                 break;
1170             default:
1171                 eltype = eelCUT;
1172         }
1173     }
1174     else
1175     {
1176         eltype = fr->eeltype;
1177     }
1178
1179     switch (eltype)
1180     {
1181         case eelCUT:
1182             tabsel[etiCOUL] = etabCOUL;
1183             break;
1184         case eelPOISSON:
1185             tabsel[etiCOUL] = etabShift;
1186             break;
1187         case eelSHIFT:
1188             if (fr->rcoulomb > fr->rcoulomb_switch)
1189             {
1190                 tabsel[etiCOUL] = etabShift;
1191             }
1192             else
1193             {
1194                 tabsel[etiCOUL] = etabCOUL;
1195             }
1196             break;
1197         case eelEWALD:
1198         case eelPME:
1199         case eelP3M_AD:
1200             tabsel[etiCOUL] = etabEwald;
1201             break;
1202         case eelPMESWITCH:
1203             tabsel[etiCOUL] = etabEwaldSwitch;
1204             break;
1205         case eelPMEUSER:
1206             tabsel[etiCOUL] = etabEwaldUser;
1207             break;
1208         case eelPMEUSERSWITCH:
1209             tabsel[etiCOUL] = etabEwaldUserSwitch;
1210             break;
1211         case eelRF:
1212         case eelGRF:
1213         case eelRF_NEC:
1214             tabsel[etiCOUL] = etabRF;
1215             break;
1216         case eelRF_ZERO:
1217             tabsel[etiCOUL] = etabRF_ZERO;
1218             break;
1219         case eelSWITCH:
1220             tabsel[etiCOUL] = etabCOULSwitch;
1221             break;
1222         case eelUSER:
1223             tabsel[etiCOUL] = etabUSER;
1224             break;
1225         case eelENCADSHIFT:
1226             tabsel[etiCOUL] = etabCOULEncad;
1227             break;
1228         default:
1229             gmx_fatal(FARGS, "Invalid eeltype %d", eltype);
1230     }
1231
1232     /* Van der Waals time */
1233     if (fr->bBHAM && !b14only)
1234     {
1235         tabsel[etiLJ6]  = etabLJ6;
1236         tabsel[etiLJ12] = etabEXPMIN;
1237     }
1238     else
1239     {
1240         if (b14only && fr->vdwtype != evdwUSER)
1241         {
1242             vdwtype = evdwCUT;
1243         }
1244         else
1245         {
1246             vdwtype = fr->vdwtype;
1247         }
1248
1249         switch (vdwtype)
1250         {
1251             case evdwSWITCH:
1252                 tabsel[etiLJ6]  = etabLJ6Switch;
1253                 tabsel[etiLJ12] = etabLJ12Switch;
1254                 break;
1255             case evdwSHIFT:
1256                 tabsel[etiLJ6]  = etabLJ6Shift;
1257                 tabsel[etiLJ12] = etabLJ12Shift;
1258                 break;
1259             case evdwUSER:
1260                 tabsel[etiLJ6]  = etabUSER;
1261                 tabsel[etiLJ12] = etabUSER;
1262                 break;
1263             case evdwCUT:
1264                 tabsel[etiLJ6]  = etabLJ6;
1265                 tabsel[etiLJ12] = etabLJ12;
1266                 break;
1267             case evdwENCADSHIFT:
1268                 tabsel[etiLJ6]  = etabLJ6Encad;
1269                 tabsel[etiLJ12] = etabLJ12Encad;
1270                 break;
1271             case evdwPME:
1272                 tabsel[etiLJ6]  = etabLJ6Ewald;
1273                 tabsel[etiLJ12] = etabLJ12;
1274                 break;
1275             default:
1276                 gmx_fatal(FARGS, "Invalid vdwtype %d in %s line %d", vdwtype,
1277                           __FILE__, __LINE__);
1278         }
1279
1280         if (!b14only && fr->vdw_modifier != eintmodNONE)
1281         {
1282             if (fr->vdw_modifier != eintmodPOTSHIFT &&
1283                 fr->vdwtype != evdwCUT)
1284             {
1285                 gmx_incons("Potential modifiers other than potential-shift are only implemented for LJ cut-off");
1286             }
1287
1288             /* LJ-PME and other (shift-only) modifiers are handled by applying the modifiers
1289              * to the original interaction forms when we fill the table, so we only check cutoffs here.
1290              */
1291             if (fr->vdwtype == evdwCUT)
1292             {
1293                 switch (fr->vdw_modifier)
1294                 {
1295                     case eintmodNONE:
1296                     case eintmodPOTSHIFT:
1297                     case eintmodEXACTCUTOFF:
1298                         /* No modification */
1299                         break;
1300                     case eintmodPOTSWITCH:
1301                         tabsel[etiLJ6]  = etabLJ6Switch;
1302                         tabsel[etiLJ12] = etabLJ12Switch;
1303                         break;
1304                     case eintmodFORCESWITCH:
1305                         tabsel[etiLJ6]  = etabLJ6Shift;
1306                         tabsel[etiLJ12] = etabLJ12Shift;
1307                         break;
1308                     default:
1309                         gmx_incons("Unsupported vdw_modifier");
1310                 }
1311             }
1312         }
1313     }
1314 }
1315
1316 t_forcetable make_tables(FILE *out, const output_env_t oenv,
1317                          const t_forcerec *fr,
1318                          gmx_bool bVerbose, const char *fn,
1319                          real rtab, int flags)
1320 {
1321     const char     *fns[3]   = { "ctab.xvg", "dtab.xvg", "rtab.xvg" };
1322     const char     *fns14[3] = { "ctab14.xvg", "dtab14.xvg", "rtab14.xvg" };
1323     FILE           *fp;
1324     t_tabledata    *td;
1325     gmx_bool        b14only, bReadTab, bGenTab;
1326     real            x0, y0, yp;
1327     int             i, j, k, nx, nx0, tabsel[etiNR];
1328     real            scalefactor;
1329
1330     t_forcetable    table;
1331
1332     b14only = (flags & GMX_MAKETABLES_14ONLY);
1333
1334     if (flags & GMX_MAKETABLES_FORCEUSER)
1335     {
1336         tabsel[etiCOUL] = etabUSER;
1337         tabsel[etiLJ6]  = etabUSER;
1338         tabsel[etiLJ12] = etabUSER;
1339     }
1340     else
1341     {
1342         set_table_type(tabsel, fr, b14only);
1343     }
1344     snew(td, etiNR);
1345     table.r         = rtab;
1346     table.scale     = 0;
1347     table.n         = 0;
1348     table.scale_exp = 0;
1349     nx0             = 10;
1350     nx              = 0;
1351
1352     table.interaction   = GMX_TABLE_INTERACTION_ELEC_VDWREP_VDWDISP;
1353     table.format        = GMX_TABLE_FORMAT_CUBICSPLINE_YFGH;
1354     table.formatsize    = 4;
1355     table.ninteractions = 3;
1356     table.stride        = table.formatsize*table.ninteractions;
1357
1358     /* Check whether we have to read or generate */
1359     bReadTab = FALSE;
1360     bGenTab  = FALSE;
1361     for (i = 0; (i < etiNR); i++)
1362     {
1363         if (ETAB_USER(tabsel[i]))
1364         {
1365             bReadTab = TRUE;
1366         }
1367         if (tabsel[i] != etabUSER)
1368         {
1369             bGenTab  = TRUE;
1370         }
1371     }
1372     if (bReadTab)
1373     {
1374         read_tables(out, fn, etiNR, 0, td);
1375         if (rtab == 0 || (flags & GMX_MAKETABLES_14ONLY))
1376         {
1377             rtab      = td[0].x[td[0].nx-1];
1378             table.n   = td[0].nx;
1379             nx        = table.n;
1380         }
1381         else
1382         {
1383             if (td[0].x[td[0].nx-1] < rtab)
1384             {
1385                 gmx_fatal(FARGS, "Tables in file %s not long enough for cut-off:\n"
1386                           "\tshould be at least %f nm\n", fn, rtab);
1387             }
1388             nx        = table.n = (int)(rtab*td[0].tabscale + 0.5);
1389         }
1390         table.scale = td[0].tabscale;
1391         nx0         = td[0].nx0;
1392     }
1393     if (bGenTab)
1394     {
1395         if (!bReadTab)
1396         {
1397 #ifdef GMX_DOUBLE
1398             table.scale = 2000.0;
1399 #else
1400             table.scale = 500.0;
1401 #endif
1402             nx = table.n = rtab*table.scale;
1403         }
1404     }
1405     if (fr->bBHAM)
1406     {
1407         if (fr->bham_b_max != 0)
1408         {
1409             table.scale_exp = table.scale/fr->bham_b_max;
1410         }
1411         else
1412         {
1413             table.scale_exp = table.scale;
1414         }
1415     }
1416
1417     /* Each table type (e.g. coul,lj6,lj12) requires four
1418      * numbers per nx+1 data points. For performance reasons we want
1419      * the table data to be aligned to 16-byte.
1420      */
1421     snew_aligned(table.data, 12*(nx+1)*sizeof(real), 32);
1422
1423     for (k = 0; (k < etiNR); k++)
1424     {
1425         if (tabsel[k] != etabUSER)
1426         {
1427             init_table(nx, nx0,
1428                        (tabsel[k] == etabEXPMIN) ? table.scale_exp : table.scale,
1429                        &(td[k]), !bReadTab);
1430             fill_table(&(td[k]), tabsel[k], fr, b14only);
1431             if (out)
1432             {
1433                 fprintf(out, "%s table with %d data points for %s%s.\n"
1434                         "Tabscale = %g points/nm\n",
1435                         ETAB_USER(tabsel[k]) ? "Modified" : "Generated",
1436                         td[k].nx, b14only ? "1-4 " : "", tprops[tabsel[k]].name,
1437                         td[k].tabscale);
1438             }
1439         }
1440
1441         /* Set scalefactor for c6/c12 tables. This is because we save flops in the non-table kernels
1442          * by including the derivative constants (6.0 or 12.0) in the parameters, since
1443          * we no longer calculate force in most steps. This means the c6/c12 parameters
1444          * have been scaled up, so we need to scale down the table interactions too.
1445          * It comes here since we need to scale user tables too.
1446          */
1447         if (k == etiLJ6)
1448         {
1449             scalefactor = 1.0/6.0;
1450         }
1451         else if (k == etiLJ12 && tabsel[k] != etabEXPMIN)
1452         {
1453             scalefactor = 1.0/12.0;
1454         }
1455         else
1456         {
1457             scalefactor = 1.0;
1458         }
1459
1460         copy2table(table.n, k*4, 12, td[k].x, td[k].v, td[k].f, scalefactor, table.data);
1461
1462         if (bDebugMode() && bVerbose)
1463         {
1464             if (b14only)
1465             {
1466                 fp = xvgropen(fns14[k], fns14[k], "r", "V", oenv);
1467             }
1468             else
1469             {
1470                 fp = xvgropen(fns[k], fns[k], "r", "V", oenv);
1471             }
1472             /* plot the output 5 times denser than the table data */
1473             for (i = 5*((nx0+1)/2); i < 5*table.n; i++)
1474             {
1475                 x0 = i*table.r/(5*(table.n-1));
1476                 evaluate_table(table.data, 4*k, 12, table.scale, x0, &y0, &yp);
1477                 fprintf(fp, "%15.10e  %15.10e  %15.10e\n", x0, y0, yp);
1478             }
1479             gmx_fio_fclose(fp);
1480         }
1481         done_tabledata(&(td[k]));
1482     }
1483     sfree(td);
1484
1485     return table;
1486 }
1487
1488 t_forcetable make_gb_table(const output_env_t oenv,
1489                            const t_forcerec  *fr)
1490 {
1491     const char     *fns[3]   = { "gbctab.xvg", "gbdtab.xvg", "gbrtab.xvg" };
1492     const char     *fns14[3] = { "gbctab14.xvg", "gbdtab14.xvg", "gbrtab14.xvg" };
1493     FILE           *fp;
1494     t_tabledata    *td;
1495     gmx_bool        bReadTab, bGenTab;
1496     real            x0, y0, yp;
1497     int             i, j, k, nx, nx0, tabsel[etiNR];
1498     double          r, r2, Vtab, Ftab, expterm;
1499
1500     t_forcetable    table;
1501
1502     double          abs_error_r, abs_error_r2;
1503     double          rel_error_r, rel_error_r2;
1504     double          rel_error_r_old = 0, rel_error_r2_old = 0;
1505     double          x0_r_error, x0_r2_error;
1506
1507
1508     /* Only set a Coulomb table for GB */
1509     /*
1510        tabsel[0]=etabGB;
1511        tabsel[1]=-1;
1512        tabsel[2]=-1;
1513      */
1514
1515     /* Set the table dimensions for GB, not really necessary to
1516      * use etiNR (since we only have one table, but ...)
1517      */
1518     snew(td, 1);
1519     table.interaction   = GMX_TABLE_INTERACTION_ELEC;
1520     table.format        = GMX_TABLE_FORMAT_CUBICSPLINE_YFGH;
1521     table.r             = fr->gbtabr;
1522     table.scale         = fr->gbtabscale;
1523     table.scale_exp     = 0;
1524     table.n             = table.scale*table.r;
1525     table.formatsize    = 4;
1526     table.ninteractions = 1;
1527     table.stride        = table.formatsize*table.ninteractions;
1528     nx0                 = 0;
1529     nx                  = table.scale*table.r;
1530
1531     /* Check whether we have to read or generate
1532      * We will always generate a table, so remove the read code
1533      * (Compare with original make_table function
1534      */
1535     bReadTab = FALSE;
1536     bGenTab  = TRUE;
1537
1538     /* Each table type (e.g. coul,lj6,lj12) requires four
1539      * numbers per datapoint. For performance reasons we want
1540      * the table data to be aligned to 16-byte. This is accomplished
1541      * by allocating 16 bytes extra to a temporary pointer, and then
1542      * calculating an aligned pointer. This new pointer must not be
1543      * used in a free() call, but thankfully we're sloppy enough not
1544      * to do this :-)
1545      */
1546
1547     snew_aligned(table.data, 4*nx, 32);
1548
1549     init_table(nx, nx0, table.scale, &(td[0]), !bReadTab);
1550
1551     /* Local implementation so we don't have to use the etabGB
1552      * enum above, which will cause problems later when
1553      * making the other tables (right now even though we are using
1554      * GB, the normal Coulomb tables will be created, but this
1555      * will cause a problem since fr->eeltype==etabGB which will not
1556      * be defined in fill_table and set_table_type
1557      */
1558
1559     for (i = nx0; i < nx; i++)
1560     {
1561         r       = td->x[i];
1562         r2      = r*r;
1563         expterm = exp(-0.25*r2);
1564
1565         Vtab = 1/sqrt(r2+expterm);
1566         Ftab = (r-0.25*r*expterm)/((r2+expterm)*sqrt(r2+expterm));
1567
1568         /* Convert to single precision when we store to mem */
1569         td->v[i]  = Vtab;
1570         td->f[i]  = Ftab;
1571
1572     }
1573
1574     copy2table(table.n, 0, 4, td[0].x, td[0].v, td[0].f, 1.0, table.data);
1575
1576     if (bDebugMode())
1577     {
1578         fp = xvgropen(fns[0], fns[0], "r", "V", oenv);
1579         /* plot the output 5 times denser than the table data */
1580         /* for(i=5*nx0;i<5*table.n;i++) */
1581         for (i = nx0; i < table.n; i++)
1582         {
1583             /* x0=i*table.r/(5*table.n); */
1584             x0 = i*table.r/table.n;
1585             evaluate_table(table.data, 0, 4, table.scale, x0, &y0, &yp);
1586             fprintf(fp, "%15.10e  %15.10e  %15.10e\n", x0, y0, yp);
1587
1588         }
1589         gmx_fio_fclose(fp);
1590     }
1591
1592     /*
1593        for(i=100*nx0;i<99.81*table.n;i++)
1594        {
1595        r = i*table.r/(100*table.n);
1596        r2      = r*r;
1597        expterm = exp(-0.25*r2);
1598
1599        Vtab = 1/sqrt(r2+expterm);
1600        Ftab = (r-0.25*r*expterm)/((r2+expterm)*sqrt(r2+expterm));
1601
1602
1603        evaluate_table(table.data,0,4,table.scale,r,&y0,&yp);
1604        printf("gb: i=%d, x0=%g, y0=%15.15f, Vtab=%15.15f, yp=%15.15f, Ftab=%15.15f\n",i,r, y0, Vtab, yp, Ftab);
1605
1606        abs_error_r=fabs(y0-Vtab);
1607        abs_error_r2=fabs(yp-(-1)*Ftab);
1608
1609        rel_error_r=abs_error_r/y0;
1610        rel_error_r2=fabs(abs_error_r2/yp);
1611
1612
1613        if(rel_error_r>rel_error_r_old)
1614        {
1615        rel_error_r_old=rel_error_r;
1616        x0_r_error=x0;
1617        }
1618
1619        if(rel_error_r2>rel_error_r2_old)
1620        {
1621        rel_error_r2_old=rel_error_r2;
1622        x0_r2_error=x0;
1623        }
1624        }
1625
1626        printf("gb: MAX REL ERROR IN R=%15.15f, MAX REL ERROR IN R2=%15.15f\n",rel_error_r_old, rel_error_r2_old);
1627        printf("gb: XO_R=%g, X0_R2=%g\n",x0_r_error, x0_r2_error);
1628
1629        exit(1); */
1630     done_tabledata(&(td[0]));
1631     sfree(td);
1632
1633     return table;
1634
1635
1636 }
1637
1638 t_forcetable make_atf_table(FILE *out, const output_env_t oenv,
1639                             const t_forcerec *fr,
1640                             const char *fn,
1641                             matrix box)
1642 {
1643     const char  *fns[3] = { "tf_tab.xvg", "atfdtab.xvg", "atfrtab.xvg" };
1644     FILE        *fp;
1645     t_tabledata *td;
1646     real         x0, y0, yp, rtab;
1647     int          i, nx, nx0;
1648     real         rx, ry, rz, box_r;
1649
1650     t_forcetable table;
1651
1652
1653     /* Set the table dimensions for ATF, not really necessary to
1654      * use etiNR (since we only have one table, but ...)
1655      */
1656     snew(td, 1);
1657
1658     if (fr->adress_type == eAdressSphere)
1659     {
1660         /* take half box diagonal direction as tab range */
1661         rx    = 0.5*box[0][0]+0.5*box[1][0]+0.5*box[2][0];
1662         ry    = 0.5*box[0][1]+0.5*box[1][1]+0.5*box[2][1];
1663         rz    = 0.5*box[0][2]+0.5*box[1][2]+0.5*box[2][2];
1664         box_r = sqrt(rx*rx+ry*ry+rz*rz);
1665
1666     }
1667     else
1668     {
1669         /* xsplit: take half box x direction as tab range */
1670         box_r        = box[0][0]/2;
1671     }
1672     table.r         = box_r;
1673     table.scale     = 0;
1674     table.n         = 0;
1675     table.scale_exp = 0;
1676     nx0             = 10;
1677     nx              = 0;
1678
1679     read_tables(out, fn, 1, 0, td);
1680     rtab      = td[0].x[td[0].nx-1];
1681
1682     if (fr->adress_type == eAdressXSplit && (rtab < box[0][0]/2))
1683     {
1684         gmx_fatal(FARGS, "AdResS full box therm force table in file %s extends to %f:\n"
1685                   "\tshould extend to at least half the length of the box in x-direction"
1686                   "%f\n", fn, rtab, box[0][0]/2);
1687     }
1688     if (rtab < box_r)
1689     {
1690         gmx_fatal(FARGS, "AdResS full box therm force table in file %s extends to %f:\n"
1691                   "\tshould extend to at least for spherical adress"
1692                   "%f (=distance from center to furthermost point in box \n", fn, rtab, box_r);
1693     }
1694
1695
1696     table.n     = td[0].nx;
1697     nx          = table.n;
1698     table.scale = td[0].tabscale;
1699     nx0         = td[0].nx0;
1700
1701     /* Each table type (e.g. coul,lj6,lj12) requires four
1702      * numbers per datapoint. For performance reasons we want
1703      * the table data to be aligned to 16-byte. This is accomplished
1704      * by allocating 16 bytes extra to a temporary pointer, and then
1705      * calculating an aligned pointer. This new pointer must not be
1706      * used in a free() call, but thankfully we're sloppy enough not
1707      * to do this :-)
1708      */
1709
1710     snew_aligned(table.data, 4*nx, 32);
1711
1712     copy2table(table.n, 0, 4, td[0].x, td[0].v, td[0].f, 1.0, table.data);
1713
1714     if (bDebugMode())
1715     {
1716         fp = xvgropen(fns[0], fns[0], "r", "V", oenv);
1717         /* plot the output 5 times denser than the table data */
1718         /* for(i=5*nx0;i<5*table.n;i++) */
1719
1720         for (i = 5*((nx0+1)/2); i < 5*table.n; i++)
1721         {
1722             /* x0=i*table.r/(5*table.n); */
1723             x0 = i*table.r/(5*(table.n-1));
1724             evaluate_table(table.data, 0, 4, table.scale, x0, &y0, &yp);
1725             fprintf(fp, "%15.10e  %15.10e  %15.10e\n", x0, y0, yp);
1726
1727         }
1728         gmx_ffclose(fp);
1729     }
1730
1731     done_tabledata(&(td[0]));
1732     sfree(td);
1733
1734     table.interaction   = GMX_TABLE_INTERACTION_ELEC_VDWREP_VDWDISP;
1735     table.format        = GMX_TABLE_FORMAT_CUBICSPLINE_YFGH;
1736     table.formatsize    = 4;
1737     table.ninteractions = 3;
1738     table.stride        = table.formatsize*table.ninteractions;
1739
1740
1741     return table;
1742 }
1743
1744 bondedtable_t make_bonded_table(FILE *fplog, char *fn, int angle)
1745 {
1746     t_tabledata   td;
1747     double        start;
1748     int           i;
1749     bondedtable_t tab;
1750
1751     if (angle < 2)
1752     {
1753         start = 0;
1754     }
1755     else
1756     {
1757         start = -180.0;
1758     }
1759     read_tables(fplog, fn, 1, angle, &td);
1760     if (angle > 0)
1761     {
1762         /* Convert the table from degrees to radians */
1763         for (i = 0; i < td.nx; i++)
1764         {
1765             td.x[i] *= DEG2RAD;
1766             td.f[i] *= RAD2DEG;
1767         }
1768         td.tabscale *= RAD2DEG;
1769     }
1770     tab.n     = td.nx;
1771     tab.scale = td.tabscale;
1772     snew(tab.data, tab.n*4);
1773     copy2table(tab.n, 0, 4, td.x, td.v, td.f, 1.0, tab.data);
1774     done_tabledata(&td);
1775
1776     return tab;
1777 }