3 * This source code is part of
7 * GROningen MAchine for Chemical Simulations
10 * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
11 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
12 * Copyright (c) 2001-2004, The GROMACS development team,
13 * check out http://www.gromacs.org for more information.
15 * This program is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU General Public License
17 * as published by the Free Software Foundation; either version 2
18 * of the License, or (at your option) any later version.
20 * If you want to redistribute modifications, please consider that
21 * scientific software is very special. Version control is crucial -
22 * bugs must be traceable. We will be happy to consider code for
23 * inclusion in the official distribution, but derived work must not
24 * be called official GROMACS. Details are found in the README & COPYING
25 * files - if they are missing, get the official version at www.gromacs.org.
27 * To help us fund GROMACS development, we humbly ask that you cite
28 * the papers on the package - you can find them in the top README file.
30 * For more info, check our website at http://www.gromacs.org
33 * Green Red Orange Magenta Azure Cyan Skyblue
62 #include "gromacs/linearalgebra/eigensolver.h"
64 /* print to two file pointers at once (i.e. stderr and log) */
66 void lo_ffprintf(FILE *fp1, FILE *fp2, const char *buf)
68 fprintf(fp1, "%s", buf);
69 fprintf(fp2, "%s", buf);
72 /* just print a prepared buffer to fp1 and fp2 */
74 void ffprintf(FILE *fp1, FILE *fp2, const char *buf)
76 lo_ffprintf(fp1, fp2, buf);
79 /* prepare buffer with one argument, then print to fp1 and fp2 */
81 void ffprintf_d(FILE *fp1, FILE *fp2, char *buf, const char *fmt, int arg)
83 sprintf(buf, fmt, arg);
84 lo_ffprintf(fp1, fp2, buf);
87 /* prepare buffer with one argument, then print to fp1 and fp2 */
89 void ffprintf_g(FILE *fp1, FILE *fp2, char *buf, const char *fmt, real arg)
91 sprintf(buf, fmt, arg);
92 lo_ffprintf(fp1, fp2, buf);
95 /* prepare buffer with one argument, then print to fp1 and fp2 */
97 void ffprintf_s(FILE *fp1, FILE *fp2, char *buf, const char *fmt, const char *arg)
99 sprintf(buf, fmt, arg);
100 lo_ffprintf(fp1, fp2, buf);
103 /* prepare buffer with two arguments, then print to fp1 and fp2 */
105 void ffprintf_dd(FILE *fp1, FILE *fp2, char *buf, const char *fmt, int arg1, int arg2)
107 sprintf(buf, fmt, arg1, arg2);
108 lo_ffprintf(fp1, fp2, buf);
111 /* prepare buffer with two arguments, then print to fp1 and fp2 */
113 void ffprintf_gg(FILE *fp1, FILE *fp2, char *buf, const char *fmt, real arg1, real arg2)
115 sprintf(buf, fmt, arg1, arg2);
116 lo_ffprintf(fp1, fp2, buf);
119 /* prepare buffer with two arguments, then print to fp1 and fp2 */
121 void ffprintf_ss(FILE *fp1, FILE *fp2, char *buf, const char *fmt, const char *arg1, const char *arg2)
123 sprintf(buf, fmt, arg1, arg2);
124 lo_ffprintf(fp1, fp2, buf);
137 void pr_energy(FILE *fp, real e)
139 fprintf(fp, "Energy: %8.4f\n", e);
142 void cp_index(int nn, int from[], int to[])
146 for (i = 0; (i < nn); i++)
152 void mc_optimize(FILE *log, t_mat *m, int maxiter, int *seed, real kT)
154 real e[2], ei, ej, efac;
158 int i, isw, jsw, iisw, jjsw, nn;
160 fprintf(stderr, "\nDoing Monte Carlo clustering\n");
163 cp_index(nn, m->m_ind, low_index);
164 if (getenv("TESTMC"))
166 e[cur] = mat_energy(m);
167 pr_energy(log, e[cur]);
168 fprintf(log, "Doing 1000 random swaps\n");
169 for (i = 0; (i < 1000); i++)
173 isw = nn*rando(seed);
174 jsw = nn*rando(seed);
176 while ((isw == jsw) || (isw >= nn) || (jsw >= nn));
177 iisw = m->m_ind[isw];
178 jjsw = m->m_ind[jsw];
179 m->m_ind[isw] = jjsw;
180 m->m_ind[jsw] = iisw;
183 e[cur] = mat_energy(m);
184 pr_energy(log, e[cur]);
185 for (i = 0; (i < maxiter); i++)
189 isw = nn*rando(seed);
190 jsw = nn*rando(seed);
192 while ((isw == jsw) || (isw >= nn) || (jsw >= nn));
194 iisw = m->m_ind[isw];
195 jjsw = m->m_ind[jsw];
196 ei = row_energy(nn, iisw, m->mat[jsw]);
197 ej = row_energy(nn, jjsw, m->mat[isw]);
199 e[next] = e[cur] + (ei+ej-EROW(m, isw)-EROW(m, jsw))/nn;
201 efac = kT ? exp((e[next]-e[cur])/kT) : -1;
202 if ((e[next] > e[cur]) || (efac > rando(seed)))
205 if (e[next] > e[cur])
207 cp_index(nn, m->m_ind, low_index);
211 fprintf(log, "Taking uphill step\n");
214 /* Now swapping rows */
215 m->m_ind[isw] = jjsw;
216 m->m_ind[jsw] = iisw;
220 fprintf(log, "Iter: %d Swapped %4d and %4d (now %g)",
221 i, isw, jsw, mat_energy(m));
222 pr_energy(log, e[cur]);
225 /* Now restore the highest energy index */
226 cp_index(nn, low_index, m->m_ind);
229 static void calc_dist(int nind, rvec x[], real **d)
235 for (i = 0; (i < nind-1); i++)
238 for (j = i+1; (j < nind); j++)
240 /* Should use pbc_dx when analysing multiple molecueles,
241 * but the box is not stored for every frame.
243 rvec_sub(xi, x[j], dx);
249 static real rms_dist(int isize, real **d, real **d_r)
255 for (i = 0; (i < isize-1); i++)
257 for (j = i+1; (j < isize); j++)
259 r = d[i][j]-d_r[i][j];
263 r2 /= (isize*(isize-1))/2;
268 static int rms_dist_comp(const void *a, const void *b)
275 if (da->dist - db->dist < 0)
279 else if (da->dist - db->dist > 0)
286 static int clust_id_comp(const void *a, const void *b)
293 return da->clust - db->clust;
296 static int nrnb_comp(const void *a, const void *b)
303 /* return the b-a, we want highest first */
304 return db->nr - da->nr;
307 void gather(t_mat *m, real cutoff, t_clusters *clust)
311 int i, j, k, nn, cid, n1, diff;
314 /* First we sort the entries in the RMSD matrix */
318 for (i = k = 0; (i < n1); i++)
320 for (j = i+1; (j < n1); j++, k++)
324 d[k].dist = m->mat[i][j];
329 gmx_incons("gather algortihm");
331 qsort(d, nn, sizeof(d[0]), rms_dist_comp);
333 /* Now we make a cluster index for all of the conformations */
336 /* Now we check the closest structures, and equalize their cluster numbers */
337 fprintf(stderr, "Linking structures ");
340 fprintf(stderr, "*");
342 for (k = 0; (k < nn) && (d[k].dist < cutoff); k++)
344 diff = c[d[k].j].clust - c[d[k].i].clust;
350 c[d[k].j].clust = c[d[k].i].clust;
354 c[d[k].i].clust = c[d[k].j].clust;
360 fprintf(stderr, "\nSorting and renumbering clusters\n");
361 /* Sort on cluster number */
362 qsort(c, n1, sizeof(c[0]), clust_id_comp);
364 /* Renumber clusters */
366 for (k = 1; k < n1; k++)
368 if (c[k].clust != c[k-1].clust)
381 for (k = 0; (k < n1); k++)
383 fprintf(debug, "Cluster index for conformation %d: %d\n",
384 c[k].conf, c[k].clust);
388 for (k = 0; k < n1; k++)
390 clust->cl[c[k].conf] = c[k].clust;
397 gmx_bool jp_same(int **nnb, int i, int j, int P)
403 for (k = 0; nnb[i][k] >= 0; k++)
405 bIn = bIn || (nnb[i][k] == j);
413 for (k = 0; nnb[j][k] >= 0; k++)
415 bIn = bIn || (nnb[j][k] == i);
423 for (ii = 0; nnb[i][ii] >= 0; ii++)
425 for (jj = 0; nnb[j][jj] >= 0; jj++)
427 if ((nnb[i][ii] == nnb[j][jj]) && (nnb[i][ii] != -1))
437 static void jarvis_patrick(int n1, real **mat, int M, int P,
438 real rmsdcut, t_clusters *clust)
443 int i, j, k, cid, diff, max;
452 /* First we sort the entries in the RMSD matrix row by row.
453 * This gives us the nearest neighbor list.
457 for (i = 0; (i < n1); i++)
459 for (j = 0; (j < n1); j++)
462 row[j].dist = mat[i][j];
464 qsort(row, n1, sizeof(row[0]), rms_dist_comp);
467 /* Put the M nearest neighbors in the list */
469 for (j = k = 0; (k < M) && (j < n1) && (mat[i][row[j].j] < rmsdcut); j++)
473 nnb[i][k] = row[j].j;
481 /* Put all neighbors nearer than rmsdcut in the list */
484 for (j = 0; (j < n1) && (mat[i][row[j].j] < rmsdcut); j++)
493 nnb[i][k] = row[j].j;
499 srenew(nnb[i], max+1);
507 fprintf(debug, "Nearest neighborlist. M = %d, P = %d\n", M, P);
508 for (i = 0; (i < n1); i++)
510 fprintf(debug, "i:%5d nbs:", i);
511 for (j = 0; nnb[i][j] >= 0; j++)
513 fprintf(debug, "%5d[%5.3f]", nnb[i][j], mat[i][nnb[i][j]]);
515 fprintf(debug, "\n");
520 fprintf(stderr, "Linking structures ");
521 /* Use mcpy for temporary storage of booleans */
522 mcpy = mk_matrix(n1, n1, FALSE);
523 for (i = 0; i < n1; i++)
525 for (j = i+1; j < n1; j++)
527 mcpy[i][j] = jp_same(nnb, i, j, P);
532 fprintf(stderr, "*");
534 for (i = 0; i < n1; i++)
536 for (j = i+1; j < n1; j++)
540 diff = c[j].clust - c[i].clust;
546 c[j].clust = c[i].clust;
550 c[i].clust = c[j].clust;
559 fprintf(stderr, "\nSorting and renumbering clusters\n");
560 /* Sort on cluster number */
561 qsort(c, n1, sizeof(c[0]), clust_id_comp);
563 /* Renumber clusters */
565 for (k = 1; k < n1; k++)
567 if (c[k].clust != c[k-1].clust)
579 for (k = 0; k < n1; k++)
581 clust->cl[c[k].conf] = c[k].clust;
585 for (k = 0; (k < n1); k++)
587 fprintf(debug, "Cluster index for conformation %d: %d\n",
588 c[k].conf, c[k].clust);
592 /* Again, I don't see the point in this... (AF) */
593 /* for(i=0; (i<n1); i++) { */
594 /* for(j=0; (j<n1); j++) */
595 /* mcpy[c[i].conf][c[j].conf] = mat[i][j]; */
597 /* for(i=0; (i<n1); i++) { */
598 /* for(j=0; (j<n1); j++) */
599 /* mat[i][j] = mcpy[i][j]; */
601 done_matrix(n1, &mcpy);
604 for (i = 0; (i < n1); i++)
611 static void dump_nnb (FILE *fp, const char *title, int n1, t_nnb *nnb)
615 /* dump neighbor list */
616 fprintf(fp, "%s", title);
617 for (i = 0; (i < n1); i++)
619 fprintf(fp, "i:%5d #:%5d nbs:", i, nnb[i].nr);
620 for (j = 0; j < nnb[i].nr; j++)
622 fprintf(fp, "%5d", nnb[i].nb[j]);
628 static void gromos(int n1, real **mat, real rmsdcut, t_clusters *clust)
632 int i, j, k, j1, max;
634 /* Put all neighbors nearer than rmsdcut in the list */
635 fprintf(stderr, "Making list of neighbors within cutoff ");
638 for (i = 0; (i < n1); i++)
642 /* put all neighbors within cut-off in list */
643 for (j = 0; j < n1; j++)
645 if (mat[i][j] < rmsdcut)
650 srenew(nnb[i].nb, max);
656 /* store nr of neighbors, we'll need that */
658 if (i%(1+n1/100) == 0)
660 fprintf(stderr, "%3d%%\b\b\b\b", (i*100+1)/n1);
663 fprintf(stderr, "%3d%%\n", 100);
666 /* sort neighbor list on number of neighbors, largest first */
667 qsort(nnb, n1, sizeof(nnb[0]), nrnb_comp);
671 dump_nnb(debug, "Nearest neighborlist after sort.\n", n1, nnb);
674 /* turn first structure with all its neighbors (largest) into cluster
675 remove them from pool of structures and repeat for all remaining */
676 fprintf(stderr, "Finding clusters %4d", 0);
677 /* cluster id's start at 1: */
681 /* set cluster id (k) for first item in neighborlist */
682 for (j = 0; j < nnb[0].nr; j++)
684 clust->cl[nnb[0].nb[j]] = k;
690 /* adjust number of neighbors for others, taking removals into account: */
691 for (i = 1; i < n1 && nnb[i].nr; i++)
694 for (j = 0; j < nnb[i].nr; j++)
696 /* if this neighbor wasn't removed */
697 if (clust->cl[nnb[i].nb[j]] == 0)
699 /* shift the rest (j1<=j) */
700 nnb[i].nb[j1] = nnb[i].nb[j];
705 /* now j1 is the new number of neighbors */
708 /* sort again on nnb[].nr, because we have new # neighbors: */
709 /* but we only need to sort upto i, i.e. when nnb[].nr>0 */
710 qsort(nnb, i, sizeof(nnb[0]), nrnb_comp);
712 fprintf(stderr, "\b\b\b\b%4d", k);
716 fprintf(stderr, "\n");
720 fprintf(debug, "Clusters (%d):\n", k);
721 for (i = 0; i < n1; i++)
723 fprintf(debug, " %3d", clust->cl[i]);
725 fprintf(debug, "\n");
731 rvec **read_whole_trj(const char *fn, int isize, atom_id index[], int skip,
732 int *nframe, real **time, const output_env_t oenv, gmx_bool bPBC, gmx_rmpbc_t gpbc)
737 int i, i0, j, max_nf;
745 natom = read_first_x(oenv, &status, fn, &t, &x, box);
752 gmx_rmpbc(gpbc, natom, box, x);
758 srenew(*time, max_nf);
763 /* Store only the interesting atoms */
764 for (j = 0; (j < isize); j++)
766 copy_rvec(x[index[j]], xx[i0][j]);
773 while (read_next_x(oenv, status, &t, natom, x, box));
774 fprintf(stderr, "Allocated %lu bytes for frames\n",
775 (unsigned long) (max_nf*isize*sizeof(**xx)));
776 fprintf(stderr, "Read %d frames from trajectory %s\n", i0, fn);
783 static int plot_clusters(int nf, real **mat, t_clusters *clust,
786 int i, j, ncluster, ci;
787 int *cl_id, *nstruct, *strind;
792 for (i = 0; i < nf; i++)
795 cl_id[i] = clust->cl[i];
799 for (i = 0; i < nf; i++)
801 if (nstruct[i] >= minstruct)
804 for (j = 0; (j < nf); j++)
808 strind[j] = ncluster;
814 fprintf(stderr, "There are %d clusters with at least %d conformations\n",
815 ncluster, minstruct);
817 for (i = 0; (i < nf); i++)
820 for (j = 0; j < i; j++)
822 if ((ci == cl_id[j]) && (nstruct[ci] >= minstruct))
824 /* color different clusters with different colors, as long as
825 we don't run out of colors */
826 mat[i][j] = strind[i];
841 static void mark_clusters(int nf, real **mat, real val, t_clusters *clust)
845 for (i = 0; i < nf; i++)
847 for (j = 0; j < i; j++)
849 if (clust->cl[i] == clust->cl[j])
861 static char *parse_filename(const char *fn, int maxnr)
870 gmx_fatal(FARGS, "will not number filename %s containing '%c'", fn, '%');
872 /* number of digits needed in numbering */
873 i = (int)(log(maxnr)/log(10)) + 1;
874 /* split fn and ext */
875 ext = strrchr(fn, '.');
878 gmx_fatal(FARGS, "cannot separate extension in filename %s", fn);
881 /* insert e.g. '%03d' between fn and ext */
882 sprintf(buf, "%s%%0%dd.%s", fn, i, ext);
883 snew(fnout, strlen(buf)+1);
889 static void ana_trans(t_clusters *clust, int nf,
890 const char *transfn, const char *ntransfn, FILE *log,
891 t_rgb rlo, t_rgb rhi, const output_env_t oenv)
896 int i, ntranst, maxtrans;
899 snew(ntrans, clust->ncl);
900 snew(trans, clust->ncl);
901 snew(axis, clust->ncl);
902 for (i = 0; i < clust->ncl; i++)
905 snew(trans[i], clust->ncl);
909 for (i = 1; i < nf; i++)
911 if (clust->cl[i] != clust->cl[i-1])
914 ntrans[clust->cl[i-1]-1]++;
915 ntrans[clust->cl[i]-1]++;
916 trans[clust->cl[i-1]-1][clust->cl[i]-1]++;
917 maxtrans = max(maxtrans, trans[clust->cl[i]-1][clust->cl[i-1]-1]);
920 ffprintf_dd(stderr, log, buf, "Counted %d transitions in total, "
921 "max %d between two specific clusters\n", ntranst, maxtrans);
924 fp = ffopen(transfn, "w");
925 i = min(maxtrans+1, 80);
926 write_xpm(fp, 0, "Cluster Transitions", "# transitions",
927 "from cluster", "to cluster",
928 clust->ncl, clust->ncl, axis, axis, trans,
929 0, maxtrans, rlo, rhi, &i);
934 fp = xvgropen(ntransfn, "Cluster Transitions", "Cluster #", "# transitions",
936 for (i = 0; i < clust->ncl; i++)
938 fprintf(fp, "%5d %5d\n", i+1, ntrans[i]);
943 for (i = 0; i < clust->ncl; i++)
951 static void analyze_clusters(int nf, t_clusters *clust, real **rmsd,
952 int natom, t_atoms *atoms, rvec *xtps,
953 real *mass, rvec **xx, real *time,
954 int ifsize, atom_id *fitidx,
955 int iosize, atom_id *outidx,
956 const char *trxfn, const char *sizefn,
957 const char *transfn, const char *ntransfn,
958 const char *clustidfn, gmx_bool bAverage,
959 int write_ncl, int write_nst, real rmsmin,
960 gmx_bool bFit, FILE *log, t_rgb rlo, t_rgb rhi,
961 const output_env_t oenv)
964 char buf[STRLEN], buf1[40], buf2[40], buf3[40], *trxsfn;
965 t_trxstatus *trxout = NULL;
966 t_trxstatus *trxsout = NULL;
967 int i, i1, cl, nstr, *structure, first = 0, midstr;
968 gmx_bool *bWrite = NULL;
969 real r, clrmsd, midrmsd;
975 ffprintf_d(stderr, log, buf, "\nFound %d clusters\n\n", clust->ncl);
979 /* do we write all structures? */
982 trxsfn = parse_filename(trxfn, max(write_ncl, clust->ncl));
985 ffprintf_ss(stderr, log, buf, "Writing %s structure for each cluster to %s\n",
986 bAverage ? "average" : "middle", trxfn);
989 /* find out what we want to tell the user:
990 Writing [all structures|structures with rmsd > %g] for
991 {all|first %d} clusters {with more than %d structures} to %s */
994 sprintf(buf1, "structures with rmsd > %g", rmsmin);
998 sprintf(buf1, "all structures");
1000 buf2[0] = buf3[0] = '\0';
1001 if (write_ncl >= clust->ncl)
1005 sprintf(buf2, "all ");
1010 sprintf(buf2, "the first %d ", write_ncl);
1014 sprintf(buf3, " with more than %d structures", write_nst);
1016 sprintf(buf, "Writing %s for %sclusters%s to %s\n", buf1, buf2, buf3, trxsfn);
1017 ffprintf(stderr, log, buf);
1020 /* Prepare a reference structure for the orientation of the clusters */
1023 reset_x(ifsize, fitidx, natom, NULL, xtps, mass);
1025 trxout = open_trx(trxfn, "w");
1026 /* Calculate the average structure in each cluster, *
1027 * all structures are fitted to the first struture of the cluster */
1031 if (transfn || ntransfn)
1033 ana_trans(clust, nf, transfn, ntransfn, log, rlo, rhi, oenv);
1038 fp = xvgropen(clustidfn, "Clusters", output_env_get_xvgr_tlabel(oenv), "Cluster #", oenv);
1039 fprintf(fp, "@ s0 symbol 2\n");
1040 fprintf(fp, "@ s0 symbol size 0.2\n");
1041 fprintf(fp, "@ s0 linestyle 0\n");
1042 for (i = 0; i < nf; i++)
1044 fprintf(fp, "%8g %8d\n", time[i], clust->cl[i]);
1050 fp = xvgropen(sizefn, "Cluster Sizes", "Cluster #", "# Structures", oenv);
1051 fprintf(fp, "@g%d type %s\n", 0, "bar");
1053 snew(structure, nf);
1054 fprintf(log, "\n%3s | %3s %4s | %6s %4s | cluster members\n",
1055 "cl.", "#st", "rmsd", "middle", "rmsd");
1056 for (cl = 1; cl <= clust->ncl; cl++)
1058 /* prepare structures (fit, middle, average) */
1061 for (i = 0; i < natom; i++)
1067 for (i1 = 0; i1 < nf; i1++)
1069 if (clust->cl[i1] == cl)
1071 structure[nstr] = i1;
1073 if (trxfn && (bAverage || write_ncl) )
1077 reset_x(ifsize, fitidx, natom, NULL, xx[i1], mass);
1085 do_fit(natom, mass, xx[first], xx[i1]);
1089 for (i = 0; i < natom; i++)
1091 rvec_inc(xav[i], xx[i1][i]);
1099 fprintf(fp, "%8d %8d\n", cl, nstr);
1104 for (i1 = 0; i1 < nstr; i1++)
1109 for (i = 0; i < nstr; i++)
1113 r += rmsd[structure[i]][structure[i1]];
1117 r += rmsd[structure[i1]][structure[i]];
1124 midstr = structure[i1];
1131 /* dump cluster info to logfile */
1134 sprintf(buf1, "%6.3f", clrmsd);
1139 sprintf(buf2, "%5.3f", midrmsd);
1147 sprintf(buf1, "%5s", "");
1148 sprintf(buf2, "%5s", "");
1150 fprintf(log, "%3d | %3d %s | %6g%s |", cl, nstr, buf1, time[midstr], buf2);
1151 for (i = 0; i < nstr; i++)
1153 if ((i % 7 == 0) && i)
1155 sprintf(buf, "\n%3s | %3s %4s | %6s %4s |", "", "", "", "", "");
1162 fprintf(log, "%s %6g", buf, time[i1]);
1166 /* write structures to trajectory file(s) */
1171 for (i = 0; i < nstr; i++)
1176 if (cl < write_ncl+1 && nstr > write_nst)
1178 /* Dump all structures for this cluster */
1179 /* generate numbered filename (there is a %d in trxfn!) */
1180 sprintf(buf, trxsfn, cl);
1181 trxsout = open_trx(buf, "w");
1182 for (i = 0; i < nstr; i++)
1187 for (i1 = 0; i1 < i && bWrite[i]; i1++)
1191 bWrite[i] = rmsd[structure[i1]][structure[i]] > rmsmin;
1197 write_trx(trxsout, iosize, outidx, atoms, i, time[structure[i]], zerobox,
1198 xx[structure[i]], NULL, NULL);
1203 /* Dump the average structure for this cluster */
1206 for (i = 0; i < natom; i++)
1208 svmul(1.0/nstr, xav[i], xav[i]);
1213 for (i = 0; i < natom; i++)
1215 copy_rvec(xx[midstr][i], xav[i]);
1219 reset_x(ifsize, fitidx, natom, NULL, xav, mass);
1224 do_fit(natom, mass, xtps, xav);
1227 write_trx(trxout, iosize, outidx, atoms, cl, time[midstr], zerobox, xav, NULL, NULL);
1247 static void convert_mat(t_matrix *mat, t_mat *rms)
1252 matrix2real(mat, rms->mat);
1253 /* free input xpm matrix data */
1254 for (i = 0; i < mat->nx; i++)
1256 sfree(mat->matrix[i]);
1260 for (i = 0; i < mat->nx; i++)
1262 for (j = i; j < mat->nx; j++)
1264 rms->sumrms += rms->mat[i][j];
1265 rms->maxrms = max(rms->maxrms, rms->mat[i][j]);
1268 rms->minrms = min(rms->minrms, rms->mat[i][j]);
1275 int gmx_cluster(int argc, char *argv[])
1277 const char *desc[] = {
1278 "[TT]g_cluster[tt] can cluster structures using several different methods.",
1279 "Distances between structures can be determined from a trajectory",
1280 "or read from an [TT].xpm[tt] matrix file with the [TT]-dm[tt] option.",
1281 "RMS deviation after fitting or RMS deviation of atom-pair distances",
1282 "can be used to define the distance between structures.[PAR]",
1284 "single linkage: add a structure to a cluster when its distance to any",
1285 "element of the cluster is less than [TT]cutoff[tt].[PAR]",
1287 "Jarvis Patrick: add a structure to a cluster when this structure",
1288 "and a structure in the cluster have each other as neighbors and",
1289 "they have a least [TT]P[tt] neighbors in common. The neighbors",
1290 "of a structure are the M closest structures or all structures within",
1291 "[TT]cutoff[tt].[PAR]",
1293 "Monte Carlo: reorder the RMSD matrix using Monte Carlo.[PAR]",
1295 "diagonalization: diagonalize the RMSD matrix.[PAR]",
1297 "gromos: use algorithm as described in Daura [IT]et al.[it]",
1298 "([IT]Angew. Chem. Int. Ed.[it] [BB]1999[bb], [IT]38[it], pp 236-240).",
1299 "Count number of neighbors using cut-off, take structure with",
1300 "largest number of neighbors with all its neighbors as cluster",
1301 "and eliminate it from the pool of clusters. Repeat for remaining",
1302 "structures in pool.[PAR]",
1304 "When the clustering algorithm assigns each structure to exactly one",
1305 "cluster (single linkage, Jarvis Patrick and gromos) and a trajectory",
1306 "file is supplied, the structure with",
1307 "the smallest average distance to the others or the average structure",
1308 "or all structures for each cluster will be written to a trajectory",
1309 "file. When writing all structures, separate numbered files are made",
1310 "for each cluster.[PAR]",
1312 "Two output files are always written:[BR]",
1313 "[TT]-o[tt] writes the RMSD values in the upper left half of the matrix",
1314 "and a graphical depiction of the clusters in the lower right half",
1315 "When [TT]-minstruct[tt] = 1 the graphical depiction is black",
1316 "when two structures are in the same cluster.",
1317 "When [TT]-minstruct[tt] > 1 different colors will be used for each",
1319 "[TT]-g[tt] writes information on the options used and a detailed list",
1320 "of all clusters and their members.[PAR]",
1322 "Additionally, a number of optional output files can be written:[BR]",
1323 "[TT]-dist[tt] writes the RMSD distribution.[BR]",
1324 "[TT]-ev[tt] writes the eigenvectors of the RMSD matrix",
1325 "diagonalization.[BR]",
1326 "[TT]-sz[tt] writes the cluster sizes.[BR]",
1327 "[TT]-tr[tt] writes a matrix of the number transitions between",
1328 "cluster pairs.[BR]",
1329 "[TT]-ntr[tt] writes the total number of transitions to or from",
1330 "each cluster.[BR]",
1331 "[TT]-clid[tt] writes the cluster number as a function of time.[BR]",
1332 "[TT]-cl[tt] writes average (with option [TT]-av[tt]) or central",
1333 "structure of each cluster or writes numbered files with cluster members",
1334 "for a selected set of clusters (with option [TT]-wcl[tt], depends on",
1335 "[TT]-nst[tt] and [TT]-rmsmin[tt]). The center of a cluster is the",
1336 "structure with the smallest average RMSD from all other structures",
1337 "of the cluster.[BR]",
1341 int i, i1, i2, j, nf, nrms;
1344 rvec *xtps, *usextps, *x1, **xx = NULL;
1345 const char *fn, *trx_out_fn;
1352 t_matrix *readmat = NULL;
1355 int isize = 0, ifsize = 0, iosize = 0;
1356 atom_id *index = NULL, *fitidx, *outidx;
1358 real rmsd, **d1, **d2, *time = NULL, time_invfac, *mass = NULL;
1359 char buf[STRLEN], buf1[80], title[STRLEN];
1360 gmx_bool bAnalyze, bUseRmsdCut, bJP_RMSD = FALSE, bReadMat, bReadTraj, bPBC = TRUE;
1362 int method, ncluster = 0;
1363 static const char *methodname[] = {
1364 NULL, "linkage", "jarvis-patrick", "monte-carlo",
1365 "diagonalization", "gromos", NULL
1368 m_null, m_linkage, m_jarvis_patrick,
1369 m_monte_carlo, m_diagonalize, m_gromos, m_nr
1371 /* Set colors for plotting: white = zero RMS, black = maximum */
1372 static t_rgb rlo_top = { 1.0, 1.0, 1.0 };
1373 static t_rgb rhi_top = { 0.0, 0.0, 0.0 };
1374 static t_rgb rlo_bot = { 1.0, 1.0, 1.0 };
1375 static t_rgb rhi_bot = { 0.0, 0.0, 1.0 };
1376 static int nlevels = 40, skip = 1;
1377 static real scalemax = -1.0, rmsdcut = 0.1, rmsmin = 0.0;
1378 gmx_bool bRMSdist = FALSE, bBinary = FALSE, bAverage = FALSE, bFit = TRUE;
1379 static int niter = 10000, seed = 1993, write_ncl = 0, write_nst = 1, minstruct = 1;
1380 static real kT = 1e-3;
1381 static int M = 10, P = 3;
1383 gmx_rmpbc_t gpbc = NULL;
1386 { "-dista", FALSE, etBOOL, {&bRMSdist},
1387 "Use RMSD of distances instead of RMS deviation" },
1388 { "-nlevels", FALSE, etINT, {&nlevels},
1389 "Discretize RMSD matrix in this number of levels" },
1390 { "-cutoff", FALSE, etREAL, {&rmsdcut},
1391 "RMSD cut-off (nm) for two structures to be neighbor" },
1392 { "-fit", FALSE, etBOOL, {&bFit},
1393 "Use least squares fitting before RMSD calculation" },
1394 { "-max", FALSE, etREAL, {&scalemax},
1395 "Maximum level in RMSD matrix" },
1396 { "-skip", FALSE, etINT, {&skip},
1397 "Only analyze every nr-th frame" },
1398 { "-av", FALSE, etBOOL, {&bAverage},
1399 "Write average iso middle structure for each cluster" },
1400 { "-wcl", FALSE, etINT, {&write_ncl},
1401 "Write the structures for this number of clusters to numbered files" },
1402 { "-nst", FALSE, etINT, {&write_nst},
1403 "Only write all structures if more than this number of structures per cluster" },
1404 { "-rmsmin", FALSE, etREAL, {&rmsmin},
1405 "minimum rms difference with rest of cluster for writing structures" },
1406 { "-method", FALSE, etENUM, {methodname},
1407 "Method for cluster determination" },
1408 { "-minstruct", FALSE, etINT, {&minstruct},
1409 "Minimum number of structures in cluster for coloring in the [TT].xpm[tt] file" },
1410 { "-binary", FALSE, etBOOL, {&bBinary},
1411 "Treat the RMSD matrix as consisting of 0 and 1, where the cut-off "
1412 "is given by [TT]-cutoff[tt]" },
1413 { "-M", FALSE, etINT, {&M},
1414 "Number of nearest neighbors considered for Jarvis-Patrick algorithm, "
1415 "0 is use cutoff" },
1416 { "-P", FALSE, etINT, {&P},
1417 "Number of identical nearest neighbors required to form a cluster" },
1418 { "-seed", FALSE, etINT, {&seed},
1419 "Random number seed for Monte Carlo clustering algorithm" },
1420 { "-niter", FALSE, etINT, {&niter},
1421 "Number of iterations for MC" },
1422 { "-kT", FALSE, etREAL, {&kT},
1423 "Boltzmann weighting factor for Monte Carlo optimization "
1424 "(zero turns off uphill steps)" },
1425 { "-pbc", FALSE, etBOOL,
1426 { &bPBC }, "PBC check" }
1429 { efTRX, "-f", NULL, ffOPTRD },
1430 { efTPS, "-s", NULL, ffOPTRD },
1431 { efNDX, NULL, NULL, ffOPTRD },
1432 { efXPM, "-dm", "rmsd", ffOPTRD },
1433 { efXPM, "-o", "rmsd-clust", ffWRITE },
1434 { efLOG, "-g", "cluster", ffWRITE },
1435 { efXVG, "-dist", "rmsd-dist", ffOPTWR },
1436 { efXVG, "-ev", "rmsd-eig", ffOPTWR },
1437 { efXVG, "-sz", "clust-size", ffOPTWR},
1438 { efXPM, "-tr", "clust-trans", ffOPTWR},
1439 { efXVG, "-ntr", "clust-trans", ffOPTWR},
1440 { efXVG, "-clid", "clust-id.xvg", ffOPTWR},
1441 { efTRX, "-cl", "clusters.pdb", ffOPTWR }
1443 #define NFILE asize(fnm)
1445 parse_common_args(&argc, argv,
1446 PCA_CAN_VIEW | PCA_CAN_TIME | PCA_TIME_UNIT | PCA_BE_NICE,
1447 NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, NULL,
1451 bReadMat = opt2bSet("-dm", NFILE, fnm);
1452 bReadTraj = opt2bSet("-f", NFILE, fnm) || !bReadMat;
1453 if (opt2parg_bSet("-av", asize(pa), pa) ||
1454 opt2parg_bSet("-wcl", asize(pa), pa) ||
1455 opt2parg_bSet("-nst", asize(pa), pa) ||
1456 opt2parg_bSet("-rmsmin", asize(pa), pa) ||
1457 opt2bSet("-cl", NFILE, fnm) )
1459 trx_out_fn = opt2fn("-cl", NFILE, fnm);
1465 if (bReadMat && output_env_get_time_factor(oenv) != 1)
1468 "\nWarning: assuming the time unit in %s is %s\n",
1469 opt2fn("-dm", NFILE, fnm), output_env_get_time_unit(oenv));
1471 if (trx_out_fn && !bReadTraj)
1473 fprintf(stderr, "\nWarning: "
1474 "cannot write cluster structures without reading trajectory\n"
1475 " ignoring option -cl %s\n", trx_out_fn);
1479 while (method < m_nr && gmx_strcasecmp(methodname[0], methodname[method]) != 0)
1485 gmx_fatal(FARGS, "Invalid method");
1488 bAnalyze = (method == m_linkage || method == m_jarvis_patrick ||
1489 method == m_gromos );
1492 log = ftp2FILE(efLOG, NFILE, fnm, "w");
1494 fprintf(stderr, "Using %s method for clustering\n", methodname[0]);
1495 fprintf(log, "Using %s method for clustering\n", methodname[0]);
1497 /* check input and write parameters to log file */
1498 bUseRmsdCut = FALSE;
1499 if (method == m_jarvis_patrick)
1501 bJP_RMSD = (M == 0) || opt2parg_bSet("-cutoff", asize(pa), pa);
1502 if ((M < 0) || (M == 1))
1504 gmx_fatal(FARGS, "M (%d) must be 0 or larger than 1", M);
1508 sprintf(buf1, "Will use P=%d and RMSD cutoff (%g)", P, rmsdcut);
1515 gmx_fatal(FARGS, "Number of neighbors required (P) must be less than M");
1519 sprintf(buf1, "Will use P=%d, M=%d and RMSD cutoff (%g)", P, M, rmsdcut);
1524 sprintf(buf1, "Will use P=%d, M=%d", P, M);
1527 ffprintf_s(stderr, log, buf, "%s for determining the neighbors\n\n", buf1);
1529 else /* method != m_jarvis */
1531 bUseRmsdCut = ( bBinary || method == m_linkage || method == m_gromos );
1533 if (bUseRmsdCut && method != m_jarvis_patrick)
1535 fprintf(log, "Using RMSD cutoff %g nm\n", rmsdcut);
1537 if (method == m_monte_carlo)
1539 fprintf(log, "Using %d iterations\n", niter);
1544 gmx_fatal(FARGS, "skip (%d) should be >= 1", skip);
1550 /* don't read mass-database as masses (and top) are not used */
1551 read_tps_conf(ftp2fn(efTPS, NFILE, fnm), buf, &top, &ePBC, &xtps, NULL, box,
1555 gpbc = gmx_rmpbc_init(&top.idef, ePBC, top.atoms.nr, box);
1558 fprintf(stderr, "\nSelect group for least squares fit%s:\n",
1559 bReadMat ? "" : " and RMSD calculation");
1560 get_index(&(top.atoms), ftp2fn_null(efNDX, NFILE, fnm),
1561 1, &ifsize, &fitidx, &grpname);
1564 fprintf(stderr, "\nSelect group for output:\n");
1565 get_index(&(top.atoms), ftp2fn_null(efNDX, NFILE, fnm),
1566 1, &iosize, &outidx, &grpname);
1567 /* merge and convert both index groups: */
1568 /* first copy outidx to index. let outidx refer to elements in index */
1569 snew(index, iosize);
1571 for (i = 0; i < iosize; i++)
1573 index[i] = outidx[i];
1576 /* now lookup elements from fitidx in index, add them if necessary
1577 and also let fitidx refer to elements in index */
1578 for (i = 0; i < ifsize; i++)
1581 while (j < isize && index[j] != fitidx[i])
1587 /* slow this way, but doesn't matter much */
1589 srenew(index, isize);
1591 index[j] = fitidx[i];
1595 else /* !trx_out_fn */
1599 for (i = 0; i < ifsize; i++)
1601 index[i] = fitidx[i];
1606 /* Initiate arrays */
1609 for (i = 0; (i < isize); i++)
1617 /* Loop over first coordinate file */
1618 fn = opt2fn("-f", NFILE, fnm);
1620 xx = read_whole_trj(fn, isize, index, skip, &nf, &time, oenv, bPBC, gpbc);
1621 output_env_conv_times(oenv, nf, time);
1622 if (!bRMSdist || bAnalyze)
1624 /* Center all frames on zero */
1626 for (i = 0; i < ifsize; i++)
1628 mass[fitidx[i]] = top.atoms.atom[index[fitidx[i]]].m;
1632 for (i = 0; i < nf; i++)
1634 reset_x(ifsize, fitidx, isize, NULL, xx[i], mass);
1640 gmx_rmpbc_done(gpbc);
1646 fprintf(stderr, "Reading rms distance matrix ");
1647 read_xpm_matrix(opt2fn("-dm", NFILE, fnm), &readmat);
1648 fprintf(stderr, "\n");
1649 if (readmat[0].nx != readmat[0].ny)
1651 gmx_fatal(FARGS, "Matrix (%dx%d) is not square",
1652 readmat[0].nx, readmat[0].ny);
1654 if (bReadTraj && bAnalyze && (readmat[0].nx != nf))
1656 gmx_fatal(FARGS, "Matrix size (%dx%d) does not match the number of "
1657 "frames (%d)", readmat[0].nx, readmat[0].ny, nf);
1662 time = readmat[0].axis_x;
1663 time_invfac = output_env_get_time_invfactor(oenv);
1664 for (i = 0; i < nf; i++)
1666 time[i] *= time_invfac;
1669 rms = init_mat(readmat[0].nx, method == m_diagonalize);
1670 convert_mat(&(readmat[0]), rms);
1672 nlevels = readmat[0].nmap;
1674 else /* !bReadMat */
1676 rms = init_mat(nf, method == m_diagonalize);
1677 nrms = (nf*(nf-1))/2;
1680 fprintf(stderr, "Computing %dx%d RMS deviation matrix\n", nf, nf);
1682 for (i1 = 0; (i1 < nf); i1++)
1684 for (i2 = i1+1; (i2 < nf); i2++)
1686 for (i = 0; i < isize; i++)
1688 copy_rvec(xx[i1][i], x1[i]);
1692 do_fit(isize, mass, xx[i2], x1);
1694 rmsd = rmsdev(isize, mass, xx[i2], x1);
1695 set_mat_entry(rms, i1, i2, rmsd);
1698 fprintf(stderr, "\r# RMSD calculations left: %d ", nrms);
1703 fprintf(stderr, "Computing %dx%d RMS distance deviation matrix\n", nf, nf);
1704 for (i1 = 0; (i1 < nf); i1++)
1706 calc_dist(isize, xx[i1], d1);
1707 for (i2 = i1+1; (i2 < nf); i2++)
1709 calc_dist(isize, xx[i2], d2);
1710 set_mat_entry(rms, i1, i2, rms_dist(isize, d1, d2));
1713 fprintf(stderr, "\r# RMSD calculations left: %d ", nrms);
1716 fprintf(stderr, "\n\n");
1718 ffprintf_gg(stderr, log, buf, "The RMSD ranges from %g to %g nm\n",
1719 rms->minrms, rms->maxrms);
1720 ffprintf_g(stderr, log, buf, "Average RMSD is %g\n", 2*rms->sumrms/(nf*(nf-1)));
1721 ffprintf_d(stderr, log, buf, "Number of structures for matrix %d\n", nf);
1722 ffprintf_g(stderr, log, buf, "Energy of the matrix is %g nm\n", mat_energy(rms));
1723 if (bUseRmsdCut && (rmsdcut < rms->minrms || rmsdcut > rms->maxrms) )
1725 fprintf(stderr, "WARNING: rmsd cutoff %g is outside range of rmsd values "
1726 "%g to %g\n", rmsdcut, rms->minrms, rms->maxrms);
1728 if (bAnalyze && (rmsmin < rms->minrms) )
1730 fprintf(stderr, "WARNING: rmsd minimum %g is below lowest rmsd value %g\n",
1731 rmsmin, rms->minrms);
1733 if (bAnalyze && (rmsmin > rmsdcut) )
1735 fprintf(stderr, "WARNING: rmsd minimum %g is above rmsd cutoff %g\n",
1739 /* Plot the rmsd distribution */
1740 rmsd_distribution(opt2fn("-dist", NFILE, fnm), rms, oenv);
1744 for (i1 = 0; (i1 < nf); i1++)
1746 for (i2 = 0; (i2 < nf); i2++)
1748 if (rms->mat[i1][i2] < rmsdcut)
1750 rms->mat[i1][i2] = 0;
1754 rms->mat[i1][i2] = 1;
1764 /* Now sort the matrix and write it out again */
1765 gather(rms, rmsdcut, &clust);
1768 /* Do a diagonalization */
1769 snew(eigenvalues, nf);
1770 snew(eigenvectors, nf*nf);
1771 memcpy(eigenvectors, rms->mat[0], nf*nf*sizeof(real));
1772 eigensolver(eigenvectors, nf, 0, nf, eigenvalues, rms->mat[0]);
1773 sfree(eigenvectors);
1775 fp = xvgropen(opt2fn("-ev", NFILE, fnm), "RMSD matrix Eigenvalues",
1776 "Eigenvector index", "Eigenvalues (nm\\S2\\N)", oenv);
1777 for (i = 0; (i < nf); i++)
1779 fprintf(fp, "%10d %10g\n", i, eigenvalues[i]);
1784 mc_optimize(log, rms, niter, &seed, kT);
1788 case m_jarvis_patrick:
1789 jarvis_patrick(rms->nn, rms->mat, M, P, bJP_RMSD ? rmsdcut : -1, &clust);
1792 gromos(rms->nn, rms->mat, rmsdcut, &clust);
1795 gmx_fatal(FARGS, "DEATH HORROR unknown method \"%s\"", methodname[0]);
1798 if (method == m_monte_carlo || method == m_diagonalize)
1800 fprintf(stderr, "Energy of the matrix after clustering is %g nm\n",
1808 ncluster = plot_clusters(nf, rms->mat, &clust, minstruct);
1812 mark_clusters(nf, rms->mat, rms->maxrms, &clust);
1814 init_t_atoms(&useatoms, isize, FALSE);
1815 snew(usextps, isize);
1816 useatoms.resinfo = top.atoms.resinfo;
1817 for (i = 0; i < isize; i++)
1819 useatoms.atomname[i] = top.atoms.atomname[index[i]];
1820 useatoms.atom[i].resind = top.atoms.atom[index[i]].resind;
1821 useatoms.nres = max(useatoms.nres, useatoms.atom[i].resind+1);
1822 copy_rvec(xtps[index[i]], usextps[i]);
1824 useatoms.nr = isize;
1825 analyze_clusters(nf, &clust, rms->mat, isize, &useatoms, usextps, mass, xx, time,
1826 ifsize, fitidx, iosize, outidx,
1827 bReadTraj ? trx_out_fn : NULL,
1828 opt2fn_null("-sz", NFILE, fnm),
1829 opt2fn_null("-tr", NFILE, fnm),
1830 opt2fn_null("-ntr", NFILE, fnm),
1831 opt2fn_null("-clid", NFILE, fnm),
1832 bAverage, write_ncl, write_nst, rmsmin, bFit, log,
1833 rlo_bot, rhi_bot, oenv);
1837 if (bBinary && !bAnalyze)
1839 /* Make the clustering visible */
1840 for (i2 = 0; (i2 < nf); i2++)
1842 for (i1 = i2+1; (i1 < nf); i1++)
1844 if (rms->mat[i1][i2])
1846 rms->mat[i1][i2] = rms->maxrms;
1852 fp = opt2FILE("-o", NFILE, fnm, "w");
1853 fprintf(stderr, "Writing rms distance/clustering matrix ");
1856 write_xpm(fp, 0, readmat[0].title, readmat[0].legend, readmat[0].label_x,
1857 readmat[0].label_y, nf, nf, readmat[0].axis_x, readmat[0].axis_y,
1858 rms->mat, 0.0, rms->maxrms, rlo_top, rhi_top, &nlevels);
1862 sprintf(buf, "Time (%s)", output_env_get_time_unit(oenv));
1863 sprintf(title, "RMS%sDeviation / Cluster Index",
1864 bRMSdist ? " Distance " : " ");
1867 write_xpm_split(fp, 0, title, "RMSD (nm)", buf, buf,
1868 nf, nf, time, time, rms->mat, 0.0, rms->maxrms, &nlevels,
1869 rlo_top, rhi_top, 0.0, (real) ncluster,
1870 &ncluster, TRUE, rlo_bot, rhi_bot);
1874 write_xpm(fp, 0, title, "RMSD (nm)", buf, buf,
1875 nf, nf, time, time, rms->mat, 0.0, rms->maxrms,
1876 rlo_top, rhi_top, &nlevels);
1879 fprintf(stderr, "\n");
1882 /* now show what we've done */
1883 do_view(oenv, opt2fn("-o", NFILE, fnm), "-nxy");
1884 do_view(oenv, opt2fn_null("-sz", NFILE, fnm), "-nxy");
1885 if (method == m_diagonalize)
1887 do_view(oenv, opt2fn_null("-ev", NFILE, fnm), "-nxy");
1889 do_view(oenv, opt2fn("-dist", NFILE, fnm), "-nxy");
1892 do_view(oenv, opt2fn_null("-tr", NFILE, fnm), "-nxy");
1893 do_view(oenv, opt2fn_null("-ntr", NFILE, fnm), "-nxy");
1894 do_view(oenv, opt2fn_null("-clid", NFILE, fnm), "-nxy");