9bb0b9eaa6de08075de0a8cb302785237f81efa8
[alexxy/gromacs.git] / src / gromacs / gmxana / sfactor.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 "gromacs/utility/smalloc.h"
42 #include "gromacs/utility/futil.h"
43 #include "gromacs/math/utilities.h"
44 #include "gromacs/utility/fatalerror.h"
45 #include "gromacs/math/vec.h"
46 #include "macros.h"
47 #include "index.h"
48 #include "gromacs/fileio/strdb.h"
49 #include "gromacs/fileio/tpxio.h"
50 #include "gromacs/fileio/trxio.h"
51 #include "typedefs.h"
52 #include "oenv.h"
53 #include "gromacs/fileio/gmxfio.h"
54 #include "gromacs/fileio/xvgr.h"
55 #include "gromacs/fileio/matio.h"
56 #include "names.h"
57 #include "sfactor.h"
58
59
60 typedef struct gmx_structurefactors {
61     int    nratoms;
62     int   *p;      /* proton number */
63     int   *n;      /* neutron number */
64     /* Parameters for the Cromer Mann fit */
65     real **a;      /* parameter a */
66     real **b;      /* parameter b */
67     real  *c;      /* parameter c */
68     char **atomnm; /* atomname */
69
70 } gmx_structurefactors;
71
72 typedef struct reduced_atom{
73     rvec x;
74     int  t;
75 } reduced_atom;
76
77
78 typedef struct structure_factor
79 {
80     int       n_angles;
81     int       n_groups;
82     double    lambda;
83     double    energy;
84     double    momentum;
85     double    ref_k;
86     double  **F;
87     int       nSteps;
88     int       total_n_atoms;
89 } structure_factor;
90
91
92 extern int * create_indexed_atom_type (reduced_atom_t * atm, int size)
93 {
94 /*
95  * create an index of the atom types found in a  group
96  * i.e.: for water index_atp[0]=type_number_of_O and
97  *                 index_atp[1]=type_number_of_H
98  *
99  * the last element is set to 0
100  */
101     int          *index_atp, i, i_tmp, j;
102
103     reduced_atom *att = (reduced_atom *)atm;
104
105     snew (index_atp, 1);
106     i_tmp        = 1;
107     index_atp[0] = att[0].t;
108     for (i = 1; i < size; i++)
109     {
110         for (j = 0; j < i_tmp; j++)
111         {
112             if (att[i].t == index_atp[j])
113             {
114                 break;
115             }
116         }
117         if (j == i_tmp) /* i.e. no indexed atom type is  == to atm[i].t */
118         {
119             i_tmp++;
120             srenew (index_atp, i_tmp * sizeof (int));
121             index_atp[i_tmp - 1] = att[i].t;
122         }
123     }
124     i_tmp++;
125     srenew (index_atp, i_tmp * sizeof (int));
126     index_atp[i_tmp - 1] = 0;
127     return index_atp;
128 }
129
130
131
132 extern t_complex *** rc_tensor_allocation(int x, int y, int z)
133 {
134     t_complex ***t;
135     int          i, j;
136
137     snew(t, x);
138     snew(t[0], x*y);
139     snew(t[0][0], x*y*z);
140
141     for (j = 1; j < y; j++)
142     {
143         t[0][j] = t[0][j-1] + z;
144     }
145     for (i = 1; i < x; i++)
146     {
147         t[i]    = t[i-1] + y;
148         t[i][0] = t[i-1][0] + y*z;
149         for (j = 1; j < y; j++)
150         {
151             t[i][j] = t[i][j-1] + z;
152         }
153     }
154     return t;
155 }
156
157
158 extern void compute_structure_factor (structure_factor_t * sft, matrix box,
159                                       reduced_atom_t * red, int isize, real start_q,
160                                       real end_q, int group, real **sf_table)
161 {
162     structure_factor *sf   = (structure_factor *)sft;
163     reduced_atom     *redt = (reduced_atom *)red;
164
165     t_complex      ***tmpSF;
166     rvec              k_factor;
167     real              kdotx, asf, kx, ky, kz, krr;
168     int               kr, maxkx, maxky, maxkz, i, j, k, p, *counter;
169
170
171     k_factor[XX] = 2 * M_PI / box[XX][XX];
172     k_factor[YY] = 2 * M_PI / box[YY][YY];
173     k_factor[ZZ] = 2 * M_PI / box[ZZ][ZZ];
174
175     maxkx = (int) (end_q / k_factor[XX] + 0.5);
176     maxky = (int) (end_q / k_factor[YY] + 0.5);
177     maxkz = (int) (end_q / k_factor[ZZ] + 0.5);
178
179     snew (counter, sf->n_angles);
180
181     tmpSF = rc_tensor_allocation(maxkx, maxky, maxkz);
182 /*
183  * The big loop...
184  * compute real and imaginary part of the structure factor for every
185  * (kx,ky,kz))
186  */
187     fprintf(stderr, "\n");
188     for (i = 0; i < maxkx; i++)
189     {
190         fprintf (stderr, "\rdone %3.1f%%     ", (double)(100.0*(i+1))/maxkx);
191         kx = i * k_factor[XX];
192         for (j = 0; j < maxky; j++)
193         {
194             ky = j * k_factor[YY];
195             for (k = 0; k < maxkz; k++)
196             {
197                 if (i != 0 || j != 0 || k != 0)
198                 {
199                     kz  = k * k_factor[ZZ];
200                     krr = sqrt (sqr (kx) + sqr (ky) + sqr (kz));
201                     if (krr >= start_q && krr <= end_q)
202                     {
203                         kr = (int) (krr/sf->ref_k + 0.5);
204                         if (kr < sf->n_angles)
205                         {
206                             counter[kr]++; /* will be used for the copmutation
207                                               of the average*/
208                             for (p = 0; p < isize; p++)
209                             {
210                                 asf = sf_table[redt[p].t][kr];
211
212                                 kdotx = kx * redt[p].x[XX] +
213                                     ky * redt[p].x[YY] + kz * redt[p].x[ZZ];
214
215                                 tmpSF[i][j][k].re += cos (kdotx) * asf;
216                                 tmpSF[i][j][k].im += sin (kdotx) * asf;
217                             }
218                         }
219                     }
220                 }
221             }
222         }
223     }               /* end loop on i */
224 /*
225  *  compute the square modulus of the structure factor, averaging on the surface
226  *  kx*kx + ky*ky + kz*kz = krr*krr
227  *  note that this is correct only for a (on the macroscopic scale)
228  *  isotropic system.
229  */
230     for (i = 0; i < maxkx; i++)
231     {
232         kx = i * k_factor[XX]; for (j = 0; j < maxky; j++)
233         {
234             ky = j * k_factor[YY]; for (k = 0; k < maxkz; k++)
235             {
236                 kz = k * k_factor[ZZ]; krr = sqrt (sqr (kx) + sqr (ky)
237                                                    + sqr (kz)); if (krr >= start_q && krr <= end_q)
238                 {
239                     kr = (int) (krr / sf->ref_k + 0.5);
240                     if (kr < sf->n_angles && counter[kr] != 0)
241                     {
242                         sf->F[group][kr] +=
243                             (sqr (tmpSF[i][j][k].re) +
244                              sqr (tmpSF[i][j][k].im))/ counter[kr];
245                     }
246                 }
247             }
248         }
249     }
250     sfree(counter);
251     sfree(tmpSF[0][0]);
252     sfree(tmpSF[0]);
253     sfree(tmpSF);
254 }
255
256
257 extern gmx_structurefactors_t *gmx_structurefactors_init(const char *datfn)
258 {
259
260     /* Read the database for the structure factor of the different atoms */
261
262     FILE                 *fp;
263     char                  line[STRLEN];
264     gmx_structurefactors *gsf;
265     double                a1, a2, a3, a4, b1, b2, b3, b4, c;
266     int                   p;
267     int                   i;
268     int                   nralloc = 10;
269     int                   line_no;
270     char                  atomn[32];
271     fp      = libopen(datfn);
272     line_no = 0;
273     snew(gsf, 1);
274
275     snew(gsf->atomnm, nralloc);
276     snew(gsf->a, nralloc);
277     snew(gsf->b, nralloc);
278     snew(gsf->c, nralloc);
279     snew(gsf->p, nralloc);
280     gsf->n       = NULL;
281     gsf->nratoms = line_no;
282     while (get_a_line(fp, line, STRLEN))
283     {
284         i = line_no;
285         if (sscanf(line, "%s %d %lf %lf %lf %lf %lf %lf %lf %lf %lf",
286                    atomn, &p, &a1, &a2, &a3, &a4, &b1, &b2, &b3, &b4, &c) == 11)
287         {
288             gsf->atomnm[i] = strdup(atomn);
289             gsf->p[i]      = p;
290             snew(gsf->a[i], 4);
291             snew(gsf->b[i], 4);
292             gsf->a[i][0] = a1;
293             gsf->a[i][1] = a2;
294             gsf->a[i][2] = a3;
295             gsf->a[i][3] = a4;
296             gsf->b[i][0] = b1;
297             gsf->b[i][1] = b2;
298             gsf->b[i][2] = b3;
299             gsf->b[i][3] = b4;
300             gsf->c[i]    = c;
301             line_no++;
302             gsf->nratoms = line_no;
303             if (line_no == nralloc)
304             {
305                 nralloc += 10;
306                 srenew(gsf->atomnm, nralloc);
307                 srenew(gsf->a, nralloc);
308                 srenew(gsf->b, nralloc);
309                 srenew(gsf->c, nralloc);
310                 srenew(gsf->p, nralloc);
311             }
312         }
313         else
314         {
315             fprintf(stderr, "WARNING: Error in file %s at line %d ignored\n",
316                     datfn, line_no);
317         }
318     }
319
320     srenew(gsf->atomnm, gsf->nratoms);
321     srenew(gsf->a, gsf->nratoms);
322     srenew(gsf->b, gsf->nratoms);
323     srenew(gsf->c, gsf->nratoms);
324     srenew(gsf->p, gsf->nratoms);
325
326     fclose(fp);
327
328     return (gmx_structurefactors_t *) gsf;
329
330 }
331
332
333 extern void rearrange_atoms (reduced_atom_t * positions, t_trxframe *fr, atom_id * index,
334                              int isize, t_topology * top, gmx_bool flag, gmx_structurefactors_t *gsf)
335 /* given the group's index, return the (continuous) array of atoms */
336 {
337     int           i;
338
339     reduced_atom *pos = (reduced_atom *)positions;
340
341     if (flag)
342     {
343         for (i = 0; i < isize; i++)
344         {
345             pos[i].t =
346                 return_atom_type (*(top->atoms.atomname[index[i]]), gsf);
347         }
348     }
349     for (i = 0; i < isize; i++)
350     {
351         copy_rvec (fr->x[index[i]], pos[i].x);
352     }
353
354     positions = (reduced_atom_t *)pos;
355 }
356
357
358 extern int return_atom_type (const char *name, gmx_structurefactors_t *gsf)
359 {
360     typedef struct {
361         const char *name;
362         int         nh;
363     } t_united_h;
364     t_united_h            uh[] = {
365         { "CH1", 1 }, { "CH2", 2 }, { "CH3", 3 },
366         { "CS1", 1 }, { "CS2", 2 }, { "CS3", 3 },
367         { "CP1", 1 }, { "CP2", 2 }, { "CP3", 3 }
368     };
369     int                   i, cnt = 0;
370     int                  *tndx;
371     int                   nrc;
372     int                   fndx = 0;
373     int                   NCMT;
374
375     gmx_structurefactors *gsft = (gmx_structurefactors *)gsf;
376
377     NCMT = gsft->nratoms;
378
379     snew(tndx, NCMT);
380
381     for (i = 0; (i < asize(uh)); i++)
382     {
383         if (strcmp(name, uh[i].name) == 0)
384         {
385             return NCMT-1+uh[i].nh;
386         }
387     }
388
389     for (i = 0; (i < NCMT); i++)
390     {
391         if (strncmp (name, gsft->atomnm[i], strlen(gsft->atomnm[i])) == 0)
392         {
393             tndx[cnt] = i;
394             cnt++;
395         }
396     }
397
398     if (cnt == 0)
399     {
400         gmx_fatal(FARGS, "\nError: atom (%s) not in list (%d types checked)!\n",
401                   name, i);
402     }
403     else
404     {
405         nrc = 0;
406         for (i = 0; i < cnt; i++)
407         {
408             if (strlen(gsft->atomnm[tndx[i]]) > (size_t)nrc)
409             {
410                 nrc  = strlen(gsft->atomnm[tndx[i]]);
411                 fndx = tndx[i];
412             }
413         }
414
415         return fndx;
416     }
417
418     return 0;
419 }
420
421 extern int gmx_structurefactors_get_sf(gmx_structurefactors_t *gsf, int elem, real a[4], real b[4], real *c)
422 {
423
424     int                   success;
425     int                   i;
426     gmx_structurefactors *gsft = (gmx_structurefactors *)gsf;
427     success = 0;
428
429     for (i = 0; i < 4; i++)
430     {
431         a[i] = gsft->a[elem][i];
432         b[i] = gsft->b[elem][i];
433         *c   = gsft->c[elem];
434     }
435
436     success += 1;
437     return success;
438 }
439
440 extern int do_scattering_intensity (const char* fnTPS, const char* fnNDX,
441                                     const char* fnXVG, const char *fnTRX,
442                                     const char* fnDAT,
443                                     real start_q, real end_q,
444                                     real energy, int ng, const output_env_t oenv)
445 {
446     int                     i, *isize, flags = TRX_READ_X, **index_atp;
447     t_trxstatus            *status;
448     char                  **grpname, title[STRLEN];
449     atom_id               **index;
450     t_topology              top;
451     int                     ePBC;
452     t_trxframe              fr;
453     reduced_atom_t        **red;
454     structure_factor       *sf;
455     rvec                   *xtop;
456     real                  **sf_table;
457     int                     nsftable;
458     matrix                  box;
459     double                  r_tmp;
460
461     gmx_structurefactors_t *gmx_sf;
462     real                   *a, *b, c;
463     int                     success;
464
465     snew(a, 4);
466     snew(b, 4);
467
468
469     gmx_sf = gmx_structurefactors_init(fnDAT);
470
471     success = gmx_structurefactors_get_sf(gmx_sf, 0, a, b, &c);
472
473     snew (sf, 1);
474     sf->energy = energy;
475
476     /* Read the topology informations */
477     read_tps_conf (fnTPS, title, &top, &ePBC, &xtop, NULL, box, TRUE);
478     sfree (xtop);
479
480     /* groups stuff... */
481     snew (isize, ng);
482     snew (index, ng);
483     snew (grpname, ng);
484
485     fprintf (stderr, "\nSelect %d group%s\n", ng,
486              ng == 1 ? "" : "s");
487     if (fnTPS)
488     {
489         get_index (&top.atoms, fnNDX, ng, isize, index, grpname);
490     }
491     else
492     {
493         rd_index (fnNDX, ng, isize, index, grpname);
494     }
495
496     /* The first time we read data is a little special */
497     read_first_frame (oenv, &status, fnTRX, &fr, flags);
498
499     sf->total_n_atoms = fr.natoms;
500
501     snew (red, ng);
502     snew (index_atp, ng);
503
504     r_tmp = max (box[XX][XX], box[YY][YY]);
505     r_tmp = (double) max (box[ZZ][ZZ], r_tmp);
506
507     sf->ref_k = (2.0 * M_PI) / (r_tmp);
508     /* ref_k will be the reference momentum unit */
509     sf->n_angles = (int) (end_q / sf->ref_k + 0.5);
510
511     snew (sf->F, ng);
512     for (i = 0; i < ng; i++)
513     {
514         snew (sf->F[i], sf->n_angles);
515     }
516     for (i = 0; i < ng; i++)
517     {
518         snew (red[i], isize[i]);
519         rearrange_atoms (red[i], &fr, index[i], isize[i], &top, TRUE, gmx_sf);
520         index_atp[i] = create_indexed_atom_type (red[i], isize[i]);
521     }
522
523     sf_table = compute_scattering_factor_table (gmx_sf, (structure_factor_t *)sf);
524
525
526     /* This is the main loop over frames */
527
528     do
529     {
530         sf->nSteps++;
531         for (i = 0; i < ng; i++)
532         {
533             rearrange_atoms (red[i], &fr, index[i], isize[i], &top, FALSE, gmx_sf);
534
535             compute_structure_factor ((structure_factor_t *)sf, box, red[i], isize[i],
536                                       start_q, end_q, i, sf_table);
537         }
538     }
539
540     while (read_next_frame (oenv, status, &fr));
541
542     save_data ((structure_factor_t *)sf, fnXVG, ng, start_q, end_q, oenv);
543
544
545     sfree(a);
546     sfree(b);
547
548     gmx_structurefactors_done(gmx_sf);
549
550     return 0;
551 }
552
553
554 extern void save_data (structure_factor_t *sft, const char *file, int ngrps,
555                        real start_q, real end_q, const output_env_t oenv)
556 {
557
558     FILE             *fp;
559     int               i, g = 0;
560     double           *tmp, polarization_factor, A;
561
562     structure_factor *sf = (structure_factor *)sft;
563
564     fp = xvgropen (file, "Scattering Intensity", "q (1/nm)",
565                    "Intensity (a.u.)", oenv);
566
567     snew (tmp, ngrps);
568
569     for (g = 0; g < ngrps; g++)
570     {
571         for (i = 0; i < sf->n_angles; i++)
572         {
573
574 /*
575  *          theta is half the angle between incoming and scattered vectors.
576  *
577  *          polar. fact. = 0.5*(1+cos^2(2*theta)) = 1 - 0.5 * sin^2(2*theta)
578  *
579  *          sin(theta) = q/(2k) := A  ->  sin^2(theta) = 4*A^2 (1-A^2) ->
580  *          -> 0.5*(1+cos^2(2*theta)) = 1 - 2 A^2 (1-A^2)
581  */
582             A                   = (double) (i * sf->ref_k) / (2.0 * sf->momentum);
583             polarization_factor = 1 - 2.0 * sqr (A) * (1 - sqr (A));
584             sf->F[g][i]        *= polarization_factor;
585         }
586     }
587     for (i = 0; i < sf->n_angles; i++)
588     {
589         if (i * sf->ref_k >= start_q && i * sf->ref_k <= end_q)
590         {
591             fprintf (fp, "%10.5f  ", i * sf->ref_k);
592             for (g = 0; g < ngrps; g++)
593             {
594                 fprintf (fp, "  %10.5f ", (sf->F[g][i]) /( sf->total_n_atoms*
595                                                            sf->nSteps));
596             }
597             fprintf (fp, "\n");
598         }
599     }
600
601     gmx_ffclose (fp);
602 }
603
604
605 extern double CMSF (gmx_structurefactors_t *gsf, int type, int nh, double lambda, double sin_theta)
606 /*
607  * return Cromer-Mann fit for the atomic scattering factor:
608  * sin_theta is the sine of half the angle between incoming and scattered
609  * vectors. See g_sq.h for a short description of CM fit.
610  */
611 {
612     int    i, success;
613     double tmp = 0.0, k2;
614     real  *a, *b;
615     real   c;
616
617     snew(a, 4);
618     snew(b, 4);
619
620     /*
621      *
622      * f0[k] = c + [SUM a_i*EXP(-b_i*(k^2)) ]
623      *             i=1,4
624      */
625
626     /*
627      *  united atoms case
628      *  CH2 / CH3 groups
629      */
630     if (nh > 0)
631     {
632         tmp = (CMSF (gsf, return_atom_type ("C", gsf), 0, lambda, sin_theta) +
633                nh*CMSF (gsf, return_atom_type ("H", gsf), 0, lambda, sin_theta));
634     }
635     /* all atom case */
636     else
637     {
638         k2      = (sqr (sin_theta) / sqr (10.0 * lambda));
639         success = gmx_structurefactors_get_sf(gsf, type, a, b, &c);
640         tmp     = c;
641         for (i = 0; (i < 4); i++)
642         {
643             tmp += a[i] * exp (-b[i] * k2);
644         }
645     }
646     return tmp;
647 }
648
649
650
651 extern real **gmx_structurefactors_table(gmx_structurefactors_t *gsf, real momentum, real ref_k, real lambda, int n_angles)
652 {
653
654     int                   NCMT;
655     int                   nsftable;
656     int                   i, j;
657     double                q, sin_theta;
658     real                **sf_table;
659     gmx_structurefactors *gsft = (gmx_structurefactors *)gsf;
660
661     NCMT     = gsft->nratoms;
662     nsftable = NCMT+3;
663
664     snew (sf_table, nsftable);
665     for (i = 0; (i < nsftable); i++)
666     {
667         snew (sf_table[i], n_angles);
668         for (j = 0; j < n_angles; j++)
669         {
670             q = ((double) j * ref_k);
671             /* theta is half the angle between incoming
672                and scattered wavevectors. */
673             sin_theta = q / (2.0 * momentum);
674             if (i < NCMT)
675             {
676                 sf_table[i][j] = CMSF (gsf, i, 0, lambda, sin_theta);
677             }
678             else
679             {
680                 sf_table[i][j] = CMSF (gsf, i, i-NCMT+1, lambda, sin_theta);
681             }
682         }
683     }
684     return sf_table;
685 }
686
687 extern void gmx_structurefactors_done(gmx_structurefactors_t *gsf)
688 {
689
690     int                   i;
691     gmx_structurefactors *sf;
692     sf = (gmx_structurefactors *) gsf;
693
694     for (i = 0; i < sf->nratoms; i++)
695     {
696         sfree(sf->a[i]);
697         sfree(sf->b[i]);
698         sfree(sf->atomnm[i]);
699     }
700
701     sfree(sf->a);
702     sfree(sf->b);
703     sfree(sf->atomnm);
704     sfree(sf->p);
705     sfree(sf->c);
706
707     sfree(sf);
708
709 }
710
711 extern real **compute_scattering_factor_table (gmx_structurefactors_t *gsf, structure_factor_t *sft)
712 {
713 /*
714  *  this function build up a table of scattering factors for every atom
715  *  type and for every scattering angle.
716  */
717
718     double            hc = 1239.842;
719     real           ** sf_table;
720
721     structure_factor *sf = (structure_factor *)sft;
722
723
724     /* \hbar \omega \lambda = hc = 1239.842 eV * nm */
725     sf->momentum = ((double) (2. * 1000.0 * M_PI * sf->energy) / hc);
726     sf->lambda   = hc / (1000.0 * sf->energy);
727     fprintf (stderr, "\nwavelenght = %f nm\n", sf->lambda);
728
729     sf_table = gmx_structurefactors_table(gsf, sf->momentum, sf->ref_k, sf->lambda, sf->n_angles);
730
731     return sf_table;
732 }