Merge branch 'release-4-6'
[alexxy/gromacs.git] / src / gromacs / gmxana / gmx_make_edi.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012, by the GROMACS development team, led by
5  * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6  * others, as listed in the AUTHORS file in the top-level source
7  * directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /* The make_edi program was generously contributed by Oliver Lange, based
36  * on the code from g_anaeig. You can reach him as olange@gwdg.de. He
37  * probably also holds copyright to the following code.
38  */
39 #ifdef HAVE_CONFIG_H
40 #include <config.h>
41 #endif
42
43 #include <math.h>
44 #include <stdlib.h>
45 #include <ctype.h>
46 #include <string.h>
47 #include "readinp.h"
48 #include "statutil.h"
49 #include "sysstuff.h"
50 #include "typedefs.h"
51 #include "smalloc.h"
52 #include "macros.h"
53 #include "gmx_fatal.h"
54 #include "vec.h"
55 #include "pbc.h"
56 #include "copyrite.h"
57 #include "futil.h"
58 #include "statutil.h"
59 #include "pdbio.h"
60 #include "confio.h"
61 #include "tpxio.h"
62 #include "matio.h"
63 #include "mshift.h"
64 #include "xvgr.h"
65 #include "do_fit.h"
66 #include "rmpbc.h"
67 #include "txtdump.h"
68 #include "eigio.h"
69 #include "index.h"
70 #include "string2.h"
71
72 typedef struct
73 {
74     real        deltaF0;
75     gmx_bool    bHarmonic;
76     gmx_bool    bConstForce;   /* Do constant force flooding instead of
77                                   evaluating a flooding potential             */
78     real        tau;
79     real        deltaF;
80     real        kT;
81     real        constEfl;
82     real        alpha2;
83 } t_edflood;
84
85
86 /* This type is for the average, reference, target, and origin structure   */
87 typedef struct edix
88 {
89     int          nr;            /* number of atoms this structure contains */
90     int         *anrs;          /* atom index numbers                      */
91     rvec        *x;             /* positions                               */
92     real        *sqrtm;         /* sqrt of the masses used for mass-
93                                  * weighting of analysis                   */
94 } t_edix;
95
96
97 typedef struct edipar
98 {
99     int         nini;           /* total Nr of atoms                    */
100     gmx_bool    fitmas;         /* true if trans fit with cm            */
101     gmx_bool    pcamas;         /* true if mass-weighted PCA            */
102     int         presteps;       /* number of steps to run without any
103                                  *    perturbations ... just monitoring */
104     int         outfrq;         /* freq (in steps) of writing to edo    */
105     int         maxedsteps;     /* max nr of steps per cycle            */
106     struct edix sref;           /* reference positions, to these fitting
107                                  * will be done                         */
108     struct edix sav;            /* average positions                    */
109     struct edix star;           /* target positions                     */
110     struct edix sori;           /* origin positions                     */
111     real        slope;          /* minimal slope in acceptance radexp   */
112     int         ned;            /* Nr of atoms in essdyn buffer         */
113     t_edflood   flood;          /* parameters especially for flooding   */
114 } t_edipar;
115
116
117
118 void make_t_edx(struct edix *edx, int natoms, rvec *pos, atom_id index[])
119 {
120     edx->nr   = natoms;
121     edx->anrs = index;
122     edx->x    = pos;
123 }
124
125 void write_t_edx(FILE *fp, struct edix edx, const char *comment)
126 {
127     /*here we copy only the pointers into the t_edx struct
128        no data is copied and edx.box is ignored  */
129     int i;
130     fprintf(fp, "#%s \n %d \n", comment, edx.nr);
131     for (i = 0; i < edx.nr; i++)
132     {
133         fprintf(fp, "%d  %f  %f  %f\n", (edx.anrs)[i]+1, (edx.x)[i][XX], (edx.x)[i][YY], (edx.x)[i][ZZ]);
134     }
135 }
136
137 int sscan_list(int *list[], const char *str, const char *listname)
138 {
139     /*this routine scans a string of the form 1,3-6,9 and returns the
140        selected numbers (in this case 1 3 4 5 6 9) in NULL-terminated array of integers.
141        memory for this list will be allocated  in this routine -- sscan_list expects *list to
142        be a NULL-Pointer
143
144        listname is a string used in the errormessage*/
145
146
147     int   i, istep;
148     char  c;
149     char *pos, *startpos, *step;
150     int   n = strlen(str);
151
152     /*enums to define the different lexical stati */
153     enum {
154         sBefore, sNumber, sMinus, sRange, sZero, sSmaller, sError, sSteppedRange
155     };
156
157     int   status     = sBefore; /*status of the deterministic automat to scan str   */
158     int   number     = 0;
159     int   end_number = 0;
160
161     char *start = NULL; /*holds the string of the number behind a ','*/
162     char *end   = NULL; /*holds the string of the number behind a '-' */
163
164     int   nvecs = 0;    /* counts the number of vectors in the list*/
165
166     step = NULL;
167     snew(pos, n+4);
168     startpos = pos;
169     strcpy(pos, str);
170     pos[n]   = ',';
171     pos[n+1] = '1';
172     pos[n+2] = '\0';
173
174     *list = NULL;
175
176     while ((c = *pos) != 0)
177     {
178         switch (status)
179         {
180             /* expect a number */
181             case sBefore: if (isdigit(c))
182                 {
183                     start  = pos;
184                     status = sNumber;
185                     break;
186                 }
187                 else
188                 {
189                     status = sError;
190                 } break;
191
192             /* have read a number, expect ',' or '-' */
193             case sNumber: if (c == ',')
194                 {
195                     /*store number*/
196                     srenew(*list, nvecs+1);
197                     (*list)[nvecs++] = number = strtol(start, NULL, 10);
198                     status           = sBefore;
199                     if (number == 0)
200                     {
201                         status = sZero;
202                     }
203                     break;
204                 }
205                 else if (c == '-')
206                 {
207                     status = sMinus; break;
208                 }
209                 else if (isdigit(c))
210                 {
211                     break;
212                 }
213                 else
214                 {
215                     status = sError;
216                 } break;
217
218             /* have read a '-' -> expect a number */
219             case sMinus:
220                 if (isdigit(c))
221                 {
222                     end    = pos;
223                     status = sRange; break;
224                 }
225                 else
226                 {
227                     status = sError;
228                 } break;
229
230             case sSteppedRange:
231                 if (isdigit(c))
232                 {
233                     if (step)
234                     {
235                         status = sError; break;
236                     }
237                     else
238                     {
239                         step = pos;
240                     }
241                     status = sRange;
242                     break;
243                 }
244                 else
245                 {
246                     status = sError;
247                 } break;
248
249             /* have read the number after a minus, expect ',' or ':' */
250             case sRange:
251                 if (c == ',')
252                 {
253                     /*store numbers*/
254                     end_number = strtol(end, NULL, 10);
255                     number     = strtol(start, NULL, 10);
256                     status     = sBefore;
257                     if (number == 0)
258                     {
259                         status = sZero; break;
260                     }
261                     if (end_number <= number)
262                     {
263                         status = sSmaller; break;
264                     }
265                     srenew(*list, nvecs+end_number-number+1);
266                     if (step)
267                     {
268                         istep = strtol(step, NULL, 10);
269                         step  = NULL;
270                     }
271                     else
272                     {
273                         istep = 1;
274                     }
275                     for (i = number; i <= end_number; i += istep)
276                     {
277                         (*list)[nvecs++] = i;
278                     }
279                     break;
280                 }
281                 else if (c == ':')
282                 {
283                     status = sSteppedRange;
284                     break;
285                 }
286                 else if (isdigit(c))
287                 {
288                     break;
289                 }
290                 else
291                 {
292                     status = sError;
293                 } break;
294
295             /* format error occured */
296             case sError:
297                 gmx_fatal(FARGS, "Error in the list of eigenvectors for %s at pos %d with char %c", listname, pos-startpos, *(pos-1));
298                 break;
299             /* logical error occured */
300             case sZero:
301                 gmx_fatal(FARGS, "Error in the list of eigenvectors for %s at pos %d: eigenvector 0 is not valid", listname, pos-startpos);
302                 break;
303             case sSmaller:
304                 gmx_fatal(FARGS, "Error in the list of eigenvectors for %s at pos %d: second index %d is not bigger than %d", listname, pos-startpos, end_number, number);
305                 break;
306         }
307         ++pos; /* read next character */
308     }          /*scanner has finished */
309
310     /* append zero to list of eigenvectors */
311     srenew(*list, nvecs+1);
312     (*list)[nvecs] = 0;
313     sfree(startpos);
314     return nvecs;
315 } /*sscan_list*/
316
317 void write_eigvec(FILE* fp, int natoms, int eig_list[], rvec** eigvecs, int nvec, const char *grouptitle, real steps[])
318 {
319 /* eig_list is a zero-terminated list of indices into the eigvecs array.
320    eigvecs are coordinates of eigenvectors
321    grouptitle to write in the comment line
322    steps  -- array with stepsizes for evLINFIX, evLINACC and evRADACC
323  */
324
325     int  n = 0, i; rvec x;
326     real sum;
327     while (eig_list[n++])
328     {
329         ;                 /*count selected eigenvecs*/
330
331     }
332     fprintf(fp, "# NUMBER OF EIGENVECTORS + %s\n %d\n", grouptitle, n-1);
333
334     /* write list of eigenvector indicess */
335     for (n = 0; eig_list[n]; n++)
336     {
337         if (steps)
338         {
339             fprintf(fp, "%8d   %g\n", eig_list[n], steps[n]);
340         }
341         else
342         {
343             fprintf(fp, "%8d   %g\n", eig_list[n], 1.0);
344         }
345     }
346     n = 0;
347
348     /* dump coordinates of the selected eigenvectors */
349     while (eig_list[n])
350     {
351         sum = 0;
352         for (i = 0; i < natoms; i++)
353         {
354             if (eig_list[n] > nvec)
355             {
356                 gmx_fatal(FARGS, "Selected eigenvector %d is higher than maximum number %d of available eigenvectors", eig_list[n], nvec);
357             }
358             copy_rvec(eigvecs[eig_list[n]-1][i], x);
359             sum += norm2(x);
360             fprintf(fp, "%8.5f %8.5f %8.5f\n", x[XX], x[YY], x[ZZ]);
361         }
362         n++;
363     }
364 }
365
366
367 /*enum referring to the different lists of eigenvectors*/
368 enum {
369     evLINFIX, evLINACC, evFLOOD, evRADFIX, evRADACC, evRADCON, evMON,  evNr
370 };
371 #define oldMAGIC 666
372 #define MAGIC 670
373
374
375 void write_the_whole_thing(FILE* fp, t_edipar *edpars, rvec** eigvecs,
376                            int nvec, int *eig_listen[], real* evStepList[])
377 {
378 /* write edi-file */
379
380     /*Header*/
381     fprintf(fp, "#MAGIC\n %d \n#NINI\n %d\n#FITMAS\n %d\n#ANALYSIS_MAS\n %d\n",
382             MAGIC, edpars->nini, edpars->fitmas, edpars->pcamas);
383     fprintf(fp, "#OUTFRQ\n %d\n#MAXLEN\n %d\n#SLOPECRIT\n %f\n",
384             edpars->outfrq, edpars->maxedsteps, edpars->slope);
385     fprintf(fp, "#PRESTEPS\n %d\n#DELTA_F0\n %f\n#INIT_DELTA_F\n %f\n#TAU\n %f\n#EFL_NULL\n %f\n#ALPHA2\n %f\n#KT\n %f\n#HARMONIC\n %d\n#CONST_FORCE_FLOODING\n %d\n",
386             edpars->presteps, edpars->flood.deltaF0, edpars->flood.deltaF, edpars->flood.tau, edpars->flood.constEfl,
387             edpars->flood.alpha2, edpars->flood.kT, edpars->flood.bHarmonic, edpars->flood.bConstForce);
388
389     /* Average and reference positions */
390     write_t_edx(fp, edpars->sref, "NREF, XREF");
391     write_t_edx(fp, edpars->sav, "NAV, XAV");
392
393     /*Eigenvectors */
394
395     write_eigvec(fp, edpars->ned, eig_listen[evMON], eigvecs, nvec, "COMPONENTS GROUP 1", NULL);
396     write_eigvec(fp, edpars->ned, eig_listen[evLINFIX], eigvecs, nvec, "COMPONENTS GROUP 2", evStepList[evLINFIX]);
397     write_eigvec(fp, edpars->ned, eig_listen[evLINACC], eigvecs, nvec, "COMPONENTS GROUP 3", evStepList[evLINACC]);
398     write_eigvec(fp, edpars->ned, eig_listen[evRADFIX], eigvecs, nvec, "COMPONENTS GROUP 4", evStepList[evRADFIX]);
399     write_eigvec(fp, edpars->ned, eig_listen[evRADACC], eigvecs, nvec, "COMPONENTS GROUP 5", NULL);
400     write_eigvec(fp, edpars->ned, eig_listen[evRADCON], eigvecs, nvec, "COMPONENTS GROUP 6", NULL);
401     write_eigvec(fp, edpars->ned, eig_listen[evFLOOD], eigvecs, nvec, "COMPONENTS GROUP 7", evStepList[evFLOOD]);
402
403
404     /*Target and Origin positions */
405     write_t_edx(fp, edpars->star, "NTARGET, XTARGET");
406     write_t_edx(fp, edpars->sori, "NORIGIN, XORIGIN");
407 }
408
409 int read_conffile(const char *confin, char *title, rvec *x[])
410 {
411 /* read coordinates out of STX file  */
412     int      natoms;
413     t_atoms  confat;
414     matrix   box;
415     printf("read coordnumber from file %s\n", confin);
416     get_stx_coordnum(confin, &natoms);
417     printf("number of coordinates in file %d\n", natoms);
418 /*  if (natoms != ncoords)
419      gmx_fatal(FARGS,"number of coordinates in coordinate file (%s, %d)\n"
420            "             does not match topology (= %d)",
421            confin,natoms,ncoords);
422    else {*/
423     /* make space for coordinates and velocities */
424     init_t_atoms(&confat, natoms, FALSE);
425     snew(*x, natoms);
426     read_stx_conf(confin, title, &confat, *x, NULL, NULL, box);
427     return natoms;
428 }
429
430
431 void read_eigenvalues(int vecs[], const char *eigfile, real values[],
432                       gmx_bool bHesse, real kT)
433 {
434     int      neig, nrow, i;
435     double **eigval;
436
437     neig = read_xvg(eigfile, &eigval, &nrow);
438
439     fprintf(stderr, "Read %d eigenvalues\n", neig);
440     for (i = bHesse ? 6 : 0; i < neig; i++)
441     {
442         if (eigval[1][i] < -0.001 && bHesse)
443         {
444             fprintf(stderr,
445                     "WARNING: The Hessian Matrix has negative eigenvalue %f, we set it to zero (no flooding in this direction)\n\n", eigval[1][i]);
446         }
447
448         if (eigval[1][i] < 0)
449         {
450             eigval[1][i] = 0;
451         }
452     }
453     if (bHesse)
454     {
455         for (i = 0; vecs[i]; i++)
456         {
457             if (vecs[i] < 7)
458             {
459                 gmx_fatal(FARGS, "ERROR: You have chosen one of the first 6 eigenvectors of the HESSE Matrix. That does not make sense, since they correspond to the 6 rotational and translational degrees of freedom.\n\n");
460             }
461             values[i] = eigval[1][vecs[i]-1]/kT;
462         }
463     }
464     else
465     {
466         for (i = 0; vecs[i]; i++)
467         {
468             if (vecs[i] > (neig-6))
469             {
470                 gmx_fatal(FARGS, "ERROR: You have chosen one of the last 6 eigenvectors of the COVARIANCE Matrix. That does not make sense, since they correspond to the 6 rotational and translational degrees of freedom.\n\n");
471             }
472             values[i] = 1/eigval[1][vecs[i]-1];
473         }
474     }
475     /* free memory */
476     for (i = 0; i < nrow; i++)
477     {
478         sfree(eigval[i]);
479     }
480     sfree(eigval);
481 }
482
483
484 static real *scan_vecparams(const char *str, const char * par, int nvecs)
485 {
486     char    f0[256], f1[256];         /*format strings adapted every pass of the loop*/
487     double  d, tcap = 0;
488     int     i;
489     real   *vec_params;
490
491     snew(vec_params, nvecs);
492     if (str)
493     {
494         f0[0] = '\0';
495         for (i = 0; (i < nvecs); i++)
496         {
497             strcpy(f1, f0);    /*f0 is the format string for the "to-be-ignored" numbers*/
498             strcat(f1, "%lf"); /*and f1 to read the actual number in this pass of the loop*/
499             if (sscanf(str, f1, &d) != 1)
500             {
501                 gmx_fatal(FARGS, "Not enough elements for %s parameter (I need %d)", par, nvecs);
502             }
503             vec_params[i] = d;
504             tcap         += d;
505             strcat(f0, "%*s");
506         }
507     }
508     return vec_params;
509 }
510
511
512 void init_edx(struct edix *edx)
513 {
514     edx->nr = 0;
515     snew(edx->x, 1);
516     snew(edx->anrs, 1);
517 }
518
519 void filter2edx(struct edix *edx, int nindex, atom_id index[], int ngro,
520                 atom_id igro[], rvec *x, const char* structure)
521 {
522 /* filter2edx copies coordinates from x to edx which are given in index
523  */
524
525     int pos, i;
526     int ix = edx->nr;
527     edx->nr += nindex;
528     srenew(edx->x, edx->nr);
529     srenew(edx->anrs, edx->nr);
530     for (i = 0; i < nindex; i++, ix++)
531     {
532         for (pos = 0; pos < ngro-1 && igro[pos] != index[i]; ++pos)
533         {
534         }
535         ;                                                            /*search element in igro*/
536         if (igro[pos] != index[i])
537         {
538             gmx_fatal(FARGS, "Couldn't find atom with index %d in structure %s", index[i], structure);
539         }
540         edx->anrs[ix] = index[i];
541         copy_rvec(x[pos], edx->x[ix]);
542     }
543 }
544
545 void get_structure(t_atoms *atoms, const char *IndexFile,
546                    const char *StructureFile, struct edix *edx, int nfit,
547                    atom_id ifit[], int nav, atom_id index[])
548 {
549     atom_id *igro; /*index corresponding to target or origin structure*/
550     int      ngro;
551     int      ntar;
552     rvec    *xtar;
553     char     title[STRLEN];
554     char   * grpname;
555
556
557     ntar = read_conffile(StructureFile, title, &xtar);
558     printf("Select an index group of %d elements that corresponds to the atoms in the structure file %s\n",
559            ntar, StructureFile);
560     get_index(atoms, IndexFile, 1, &ngro, &igro, &grpname);
561     if (ngro != ntar)
562     {
563         gmx_fatal(FARGS, "You selected an index group with %d elements instead of %d", ngro, ntar);
564     }
565     init_edx(edx);
566     filter2edx(edx, nfit, ifit, ngro, igro, xtar, StructureFile);
567
568     /* If average and reference/fitting structure differ, append the average structure as well */
569     if (ifit != index) /*if fit structure is different append these coordinates, too -- don't mind duplicates*/
570     {
571         filter2edx(edx, nav, index, ngro, igro, xtar, StructureFile);
572     }
573 }
574
575 int gmx_make_edi(int argc, char *argv[])
576 {
577
578     static const char *desc[] = {
579         "[TT]make_edi[tt] generates an essential dynamics (ED) sampling input file to be used with [TT]mdrun[tt]",
580         "based on eigenvectors of a covariance matrix ([TT]g_covar[tt]) or from a",
581         "normal modes analysis ([TT]g_nmeig[tt]).",
582         "ED sampling can be used to manipulate the position along collective coordinates",
583         "(eigenvectors) of (biological) macromolecules during a simulation. Particularly,",
584         "it may be used to enhance the sampling efficiency of MD simulations by stimulating",
585         "the system to explore new regions along these collective coordinates. A number",
586         "of different algorithms are implemented to drive the system along the eigenvectors",
587         "([TT]-linfix[tt], [TT]-linacc[tt], [TT]-radfix[tt], [TT]-radacc[tt], [TT]-radcon[tt]),",
588         "to keep the position along a certain (set of) coordinate(s) fixed ([TT]-linfix[tt]),",
589         "or to only monitor the projections of the positions onto",
590         "these coordinates ([TT]-mon[tt]).[PAR]",
591         "References:[BR]",
592         "A. Amadei, A.B.M. Linssen, B.L. de Groot, D.M.F. van Aalten and ",
593         "H.J.C. Berendsen; An efficient method for sampling the essential subspace ",
594         "of proteins., J. Biomol. Struct. Dyn. 13:615-626 (1996)[BR]",
595         "B.L. de Groot, A. Amadei, D.M.F. van Aalten and H.J.C. Berendsen; ",
596         "Towards an exhaustive sampling of the configurational spaces of the ",
597         "two forms of the peptide hormone guanylin,",
598         "J. Biomol. Struct. Dyn. 13 : 741-751 (1996)[BR]",
599         "B.L. de Groot, A.Amadei, R.M. Scheek, N.A.J. van Nuland and H.J.C. Berendsen; ",
600         "An extended sampling of the configurational space of HPr from E. coli",
601         "Proteins: Struct. Funct. Gen. 26: 314-322 (1996)",
602         "[PAR]You will be prompted for one or more index groups that correspond to the eigenvectors,",
603         "reference structure, target positions, etc.[PAR]",
604
605         "[TT]-mon[tt]: monitor projections of the coordinates onto selected eigenvectors.[PAR]",
606         "[TT]-linfix[tt]: perform fixed-step linear expansion along selected eigenvectors.[PAR]",
607         "[TT]-linacc[tt]: perform acceptance linear expansion along selected eigenvectors.",
608         "(steps in the desired directions will be accepted, others will be rejected).[PAR]",
609         "[TT]-radfix[tt]: perform fixed-step radius expansion along selected eigenvectors.[PAR]",
610         "[TT]-radacc[tt]: perform acceptance radius expansion along selected eigenvectors.",
611         "(steps in the desired direction will be accepted, others will be rejected).",
612         "[BB]Note:[bb] by default the starting MD structure will be taken as origin of the first",
613         "expansion cycle for radius expansion. If [TT]-ori[tt] is specified, you will be able",
614         "to read in a structure file that defines an external origin.[PAR]",
615         "[TT]-radcon[tt]: perform acceptance radius contraction along selected eigenvectors",
616         "towards a target structure specified with [TT]-tar[tt].[PAR]",
617         "NOTE: each eigenvector can be selected only once. [PAR]",
618         "[TT]-outfrq[tt]: frequency (in steps) of writing out projections etc. to [TT].xvg[tt] file[PAR]",
619         "[TT]-slope[tt]: minimal slope in acceptance radius expansion. A new expansion",
620         "cycle will be started if the spontaneous increase of the radius (in nm/step)",
621         "is less than the value specified.[PAR]",
622         "[TT]-maxedsteps[tt]: maximum number of steps per cycle in radius expansion",
623         "before a new cycle is started.[PAR]",
624         "Note on the parallel implementation: since ED sampling is a 'global' thing",
625         "(collective coordinates etc.), at least on the 'protein' side, ED sampling",
626         "is not very parallel-friendly from an implementation point of view. Because",
627         "parallel ED requires some extra communication, expect the performance to be",
628         "lower as in a free MD simulation, especially on a large number of nodes and/or",
629         "when the ED group contains a lot of atoms. [PAR]",
630         "Please also note that if your ED group contains more than a single protein,",
631         "then the [TT].tpr[tt] file must contain the correct PBC representation of the ED group.",
632         "Take a look on the initial RMSD from the reference structure, which is printed",
633         "out at the start of the simulation; if this is much higher than expected, one",
634         "of the ED molecules might be shifted by a box vector. [PAR]",
635         "All ED-related output of [TT]mdrun[tt] (specify with [TT]-eo[tt]) is written to a [TT].xvg[tt] file",
636         "as a function of time in intervals of OUTFRQ steps.[PAR]",
637         "[BB]Note[bb] that you can impose multiple ED constraints and flooding potentials in",
638         "a single simulation (on different molecules) if several [TT].edi[tt] files were concatenated",
639         "first. The constraints are applied in the order they appear in the [TT].edi[tt] file. ",
640         "Depending on what was specified in the [TT].edi[tt] input file, the output file contains for each ED dataset[PAR]",
641         "[TT]*[tt] the RMSD of the fitted molecule to the reference structure (for atoms involved in fitting prior to calculating the ED constraints)[BR]",
642         "[TT]*[tt] projections of the positions onto selected eigenvectors[BR]",
643         "[PAR][PAR]",
644         "FLOODING:[PAR]",
645         "with [TT]-flood[tt], you can specify which eigenvectors are used to compute a flooding potential,",
646         "which will lead to extra forces expelling the structure out of the region described",
647         "by the covariance matrix. If you switch -restrain the potential is inverted and the structure",
648         "is kept in that region.",
649         "[PAR]",
650         "The origin is normally the average structure stored in the [TT]eigvec.trr[tt] file.",
651         "It can be changed with [TT]-ori[tt] to an arbitrary position in configuration space.",
652         "With [TT]-tau[tt], [TT]-deltaF0[tt], and [TT]-Eflnull[tt] you control the flooding behaviour.",
653         "Efl is the flooding strength, it is updated according to the rule of adaptive flooding.",
654         "Tau is the time constant of adaptive flooding, high [GRK]tau[grk] means slow adaption (i.e. growth). ",
655         "DeltaF0 is the flooding strength you want to reach after tau ps of simulation.",
656         "To use constant Efl set [TT]-tau[tt] to zero.",
657         "[PAR]",
658         "[TT]-alpha[tt] is a fudge parameter to control the width of the flooding potential. A value of 2 has been found",
659         "to give good results for most standard cases in flooding of proteins.",
660         "[GRK]alpha[grk] basically accounts for incomplete sampling, if you sampled further the width of the ensemble would",
661         "increase, this is mimicked by [GRK]alpha[grk] > 1.",
662         "For restraining, [GRK]alpha[grk] < 1 can give you smaller width in the restraining potential.",
663         "[PAR]",
664         "RESTART and FLOODING:",
665         "If you want to restart a crashed flooding simulation please find the values deltaF and Efl in",
666         "the output file and manually put them into the [TT].edi[tt] file under DELTA_F0 and EFL_NULL."
667     };
668
669     /* Save all the params in this struct and then save it in an edi file.
670      * ignoring fields nmass,massnrs,mass,tmass,nfit,fitnrs,edo
671      */
672     static t_edipar edi_params;
673
674     enum  {
675         evStepNr = evRADFIX + 1
676     };
677     static const char* evSelections[evNr]      = {NULL, NULL, NULL, NULL, NULL, NULL};
678     static const char* evOptions[evNr]         = {"-linfix", "-linacc", "-flood", "-radfix", "-radacc", "-radcon", "-mon"};
679     static const char* evParams[evStepNr]      = {NULL, NULL};
680     static const char* evStepOptions[evStepNr] = {"-linstep", "-accdir", "-not_used", "-radstep"};
681     static const char* ConstForceStr;
682     static real      * evStepList[evStepNr];
683     static real        radfix   = 0.0;
684     static real        deltaF0  = 150;
685     static real        deltaF   = 0;
686     static real        tau      = .1;
687     static real        constEfl = 0.0;
688     static real        alpha    = 1;
689     static int         eqSteps  = 0;
690     static int       * listen[evNr];
691     static real        T         = 300.0;
692     const real         kB        = 2.5 / 300.0; /* k_boltzmann in MD units */
693     static gmx_bool    bRestrain = FALSE;
694     static gmx_bool    bHesse    = FALSE;
695     static gmx_bool    bHarmonic = FALSE;
696     t_pargs            pa[]      = {
697         { "-mon", FALSE, etSTR, {&evSelections[evMON]},
698           "Indices of eigenvectors for projections of x (e.g. 1,2-5,9) or 1-100:10 means 1 11 21 31 ... 91" },
699         { "-linfix", FALSE, etSTR, {&evSelections[0]},
700           "Indices of eigenvectors for fixed increment linear sampling" },
701         { "-linacc", FALSE, etSTR, {&evSelections[1]},
702           "Indices of eigenvectors for acceptance linear sampling" },
703         { "-radfix", FALSE, etSTR, {&evSelections[3]},
704           "Indices of eigenvectors for fixed increment radius expansion" },
705         { "-radacc", FALSE, etSTR, {&evSelections[4]},
706           "Indices of eigenvectors for acceptance radius expansion" },
707         { "-radcon", FALSE, etSTR, {&evSelections[5]},
708           "Indices of eigenvectors for acceptance radius contraction" },
709         { "-flood",  FALSE, etSTR, {&evSelections[2]},
710           "Indices of eigenvectors for flooding"},
711         { "-outfrq", FALSE, etINT, {&edi_params.outfrq},
712           "Freqency (in steps) of writing output in [TT].xvg[tt] file" },
713         { "-slope", FALSE, etREAL, { &edi_params.slope},
714           "Minimal slope in acceptance radius expansion"},
715         { "-linstep", FALSE, etSTR, {&evParams[0]},
716           "Stepsizes (nm/step) for fixed increment linear sampling (put in quotes! \"1.0 2.3 5.1 -3.1\")"},
717         { "-accdir", FALSE, etSTR, {&evParams[1]},
718           "Directions for acceptance linear sampling - only sign counts! (put in quotes! \"-1 +1 -1.1\")"},
719         { "-radstep", FALSE, etREAL, {&radfix},
720           "Stepsize (nm/step) for fixed increment radius expansion"},
721         { "-maxedsteps", FALSE, etINT, {&edi_params.maxedsteps},
722           "Maximum number of steps per cycle" },
723         { "-eqsteps", FALSE, etINT, {&eqSteps},
724           "Number of steps to run without any perturbations "},
725         { "-deltaF0", FALSE, etREAL, {&deltaF0},
726           "Target destabilization energy for flooding"},
727         { "-deltaF", FALSE, etREAL, {&deltaF},
728           "Start deltaF with this parameter - default 0, nonzero values only needed for restart"},
729         { "-tau", FALSE, etREAL, {&tau},
730           "Coupling constant for adaption of flooding strength according to deltaF0, 0 = infinity i.e. constant flooding strength"},
731         { "-Eflnull", FALSE, etREAL, {&constEfl},
732           "The starting value of the flooding strength. The flooding strength is updated "
733           "according to the adaptive flooding scheme. For a constant flooding strength use [TT]-tau[tt] 0. "},
734         { "-T", FALSE, etREAL, {&T},
735           "T is temperature, the value is needed if you want to do flooding "},
736         { "-alpha", FALSE, etREAL, {&alpha},
737           "Scale width of gaussian flooding potential with alpha^2 "},
738         { "-restrain", FALSE, etBOOL, {&bRestrain},
739           "Use the flooding potential with inverted sign -> effects as quasiharmonic restraining potential"},
740         { "-hessian", FALSE, etBOOL, {&bHesse},
741           "The eigenvectors and eigenvalues are from a Hessian matrix"},
742         { "-harmonic", FALSE, etBOOL, {&bHarmonic},
743           "The eigenvalues are interpreted as spring constant"},
744         { "-constF", FALSE, etSTR, {&ConstForceStr},
745           "Constant force flooding: manually set the forces for the eigenvectors selected with -flood "
746           "(put in quotes! \"1.0 2.3 5.1 -3.1\"). No other flooding parameters are needed when specifying the forces directly."}
747     };
748 #define NPA asize(pa)
749
750     rvec        *xref1;
751     int          nvec1, *eignr1 = NULL;
752     rvec        *xav1, **eigvec1 = NULL;
753     t_atoms     *atoms = NULL;
754     int          nav; /* Number of atoms in the average structure */
755     char        *grpname;
756     const char  *indexfile;
757     int          i;
758     atom_id     *index, *ifit;
759     int          nfit;           /* Number of atoms in the reference/fit structure */
760     int          ev_class;       /* parameter _class i.e. evMON, evRADFIX etc. */
761     int          nvecs;
762     real        *eigval1 = NULL; /* in V3.3 this is parameter of read_eigenvectors */
763
764     const char  *EdiFile;
765     const char  *TargetFile;
766     const char  *OriginFile;
767     const char  *EigvecFile;
768
769     output_env_t oenv;
770
771     /*to read topology file*/
772     t_topology  top;
773     int         ePBC;
774     char        title[STRLEN];
775     matrix      topbox;
776     rvec       *xtop;
777     gmx_bool    bTop, bFit1;
778
779     t_filenm    fnm[] = {
780         { efTRN, "-f",    "eigenvec",    ffREAD  },
781         { efXVG, "-eig",  "eigenval",    ffOPTRD },
782         { efTPS, NULL,    NULL,          ffREAD },
783         { efNDX, NULL,    NULL,  ffOPTRD },
784         { efSTX, "-tar", "target", ffOPTRD},
785         { efSTX, "-ori", "origin", ffOPTRD},
786         { efEDI, "-o", "sam", ffWRITE }
787     };
788 #define NFILE asize(fnm)
789     edi_params.outfrq = 100; edi_params.slope = 0.0; edi_params.maxedsteps = 0;
790     parse_common_args(&argc, argv, 0,
791                       NFILE, fnm, NPA, pa, asize(desc), desc, 0, NULL, &oenv);
792
793     indexfile       = ftp2fn_null(efNDX, NFILE, fnm);
794     EdiFile         = ftp2fn(efEDI, NFILE, fnm);
795     TargetFile      = opt2fn_null("-tar", NFILE, fnm);
796     OriginFile      = opt2fn_null("-ori", NFILE, fnm);
797
798
799     for (ev_class = 0; ev_class < evNr; ++ev_class)
800     {
801         if (opt2parg_bSet(evOptions[ev_class], NPA, pa))
802         {
803             /*get list of eigenvectors*/
804             nvecs = sscan_list(&(listen[ev_class]), opt2parg_str(evOptions[ev_class], NPA, pa), evOptions[ev_class]);
805             if (ev_class < evStepNr-2)
806             {
807                 /*if apropriate get list of stepsizes for these eigenvectors*/
808                 if (opt2parg_bSet(evStepOptions[ev_class], NPA, pa))
809                 {
810                     evStepList[ev_class] =
811                         scan_vecparams(opt2parg_str(evStepOptions[ev_class], NPA, pa), evStepOptions[ev_class], nvecs);
812                 }
813                 else   /*if list is not given fill with zeros */
814                 {
815                     snew(evStepList[ev_class], nvecs);
816                     for (i = 0; i < nvecs; i++)
817                     {
818                         evStepList[ev_class][i] = 0.0;
819                     }
820                 }
821             }
822             else if (ev_class == evRADFIX && opt2parg_bSet(evStepOptions[ev_class], NPA, pa))
823             {
824                 snew(evStepList[ev_class], nvecs);
825                 for (i = 0; i < nvecs; i++)
826                 {
827                     evStepList[ev_class][i] = radfix;
828                 }
829             }
830             else if (ev_class == evFLOOD)
831             {
832                 snew(evStepList[ev_class], nvecs);
833
834                 /* Are we doing constant force flooding? In that case, we read in
835                  * the fproj values from the command line */
836                 if (opt2parg_bSet("-constF", NPA, pa))
837                 {
838                     evStepList[ev_class] = scan_vecparams(opt2parg_str("-constF", NPA, pa), "-constF", nvecs);
839                 }
840             }
841             else
842             {
843             };   /*to avoid ambiguity   */
844         }
845         else     /* if there are no eigenvectors for this option set list to zero */
846         {
847             listen[ev_class] = NULL;
848             snew(listen[ev_class], 1);
849             listen[ev_class][0] = 0;
850         }
851     }
852
853     /* print the interpreted list of eigenvectors - to give some feedback*/
854     for (ev_class = 0; ev_class < evNr; ++ev_class)
855     {
856         printf("Eigenvector list %7s consists of the indices: ", evOptions[ev_class]);
857         i = 0;
858         while (listen[ev_class][i])
859         {
860             printf("%d ", listen[ev_class][i++]);
861         }
862         printf("\n");
863     }
864
865     EigvecFile = NULL;
866     EigvecFile = opt2fn("-f", NFILE, fnm);
867
868     /*read eigenvectors from eigvec.trr*/
869     read_eigenvectors(EigvecFile, &nav, &bFit1,
870                       &xref1, &edi_params.fitmas, &xav1, &edi_params.pcamas, &nvec1, &eignr1, &eigvec1, &eigval1);
871
872     bTop = read_tps_conf(ftp2fn(efTPS, NFILE, fnm),
873                          title, &top, &ePBC, &xtop, NULL, topbox, 0);
874     atoms = &top.atoms;
875
876
877     printf("\nSelect an index group of %d elements that corresponds to the eigenvectors\n", nav);
878     get_index(atoms, indexfile, 1, &i, &index, &grpname); /*if indexfile != NULL parameter 'atoms' is ignored */
879     if (i != nav)
880     {
881         gmx_fatal(FARGS, "you selected a group with %d elements instead of %d",
882                   i, nav);
883     }
884     printf("\n");
885
886
887     if (xref1 == NULL)
888     {
889         if (bFit1)
890         {
891             /* if g_covar used different coordinate groups to fit and to do the PCA */
892             printf("\nNote: the structure in %s should be the same\n"
893                    "      as the one used for the fit in g_covar\n", ftp2fn(efTPS, NFILE, fnm));
894             printf("\nSelect the index group that was used for the least squares fit in g_covar\n");
895         }
896         else
897         {
898             printf("\nNote: Apparently no fitting was done in g_covar.\n"
899                    "      However, you need to select a reference group for fitting in mdrun\n");
900         }
901         get_index(atoms, indexfile, 1, &nfit, &ifit, &grpname);
902         snew(xref1, nfit);
903         for (i = 0; i < nfit; i++)
904         {
905             copy_rvec(xtop[ifit[i]], xref1[i]);
906         }
907     }
908     else
909     {
910         nfit = nav;
911         ifit = index;
912     }
913
914     if (opt2parg_bSet("-constF", NPA, pa))
915     {
916         /* Constant force flooding is special: Most of the normal flooding
917          * options are not needed. */
918         edi_params.flood.bConstForce = TRUE;
919     }
920     else
921     {
922         /* For normal flooding read eigenvalues and store them in evSteplist[evFLOOD] */
923
924         if (listen[evFLOOD][0] != 0)
925         {
926             read_eigenvalues(listen[evFLOOD], opt2fn("-eig", NFILE, fnm), evStepList[evFLOOD], bHesse, kB*T);
927         }
928
929         edi_params.flood.tau       = tau;
930         edi_params.flood.deltaF0   = deltaF0;
931         edi_params.flood.deltaF    = deltaF;
932         edi_params.presteps        = eqSteps;
933         edi_params.flood.kT        = kB*T;
934         edi_params.flood.bHarmonic = bHarmonic;
935         if (bRestrain)
936         {
937             /* Trick: invert sign of Efl and alpha2 then this will give the same sign in the exponential and inverted sign outside */
938             edi_params.flood.constEfl = -constEfl;
939             edi_params.flood.alpha2   = -sqr(alpha);
940         }
941         else
942         {
943             edi_params.flood.constEfl = constEfl;
944             edi_params.flood.alpha2   = sqr(alpha);
945         }
946     }
947
948     edi_params.ned = nav;
949
950     /*number of system atoms  */
951     edi_params.nini = atoms->nr;
952
953
954     /*store reference and average structure in edi_params*/
955     make_t_edx(&edi_params.sref, nfit, xref1, ifit );
956     make_t_edx(&edi_params.sav, nav, xav1, index);
957
958
959     /* Store target positions in edi_params */
960     if (opt2bSet("-tar", NFILE, fnm))
961     {
962         if (0 != listen[evFLOOD][0])
963         {
964             fprintf(stderr, "\nNote: Providing a TARGET structure has no effect when using flooding.\n"
965                     "      You may want to use -ori to define the flooding potential center.\n\n");
966         }
967         get_structure(atoms, indexfile, TargetFile, &edi_params.star, nfit, ifit, nav, index);
968     }
969     else
970     {
971         make_t_edx(&edi_params.star, 0, NULL, index);
972     }
973
974     /* Store origin positions */
975     if (opt2bSet("-ori", NFILE, fnm))
976     {
977         get_structure(atoms, indexfile, OriginFile, &edi_params.sori, nfit, ifit, nav, index);
978     }
979     else
980     {
981         make_t_edx(&edi_params.sori, 0, NULL, index);
982     }
983
984     /* Write edi-file */
985     write_the_whole_thing(ffopen(EdiFile, "w"), &edi_params, eigvec1, nvec1, listen, evStepList);
986     thanx(stderr);
987
988     return 0;
989 }