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
57 #include "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++)
150 void mc_optimize(FILE *log,t_mat *m,int maxiter,int *seed,real kT)
152 real e[2],ei,ej,efac;
156 int i,isw,jsw,iisw,jjsw,nn;
158 fprintf(stderr,"\nDoing Monte Carlo clustering\n");
161 cp_index(nn,m->m_ind,low_index);
162 if (getenv("TESTMC")) {
163 e[cur] = mat_energy(m);
164 pr_energy(log,e[cur]);
165 fprintf(log,"Doing 1000 random swaps\n");
166 for(i=0; (i<1000); i++) {
168 isw = nn*rando(seed);
169 jsw = nn*rando(seed);
170 } while ((isw == jsw) || (isw >= nn) || (jsw >= nn));
171 iisw = m->m_ind[isw];
172 jjsw = m->m_ind[jsw];
173 m->m_ind[isw] = jjsw;
174 m->m_ind[jsw] = iisw;
177 e[cur] = mat_energy(m);
178 pr_energy(log,e[cur]);
179 for(i=0; (i<maxiter); i++) {
181 isw = nn*rando(seed);
182 jsw = nn*rando(seed);
183 } while ((isw == jsw) || (isw >= nn) || (jsw >= nn));
185 iisw = m->m_ind[isw];
186 jjsw = m->m_ind[jsw];
187 ei = row_energy(nn,iisw,m->mat[jsw]);
188 ej = row_energy(nn,jjsw,m->mat[isw]);
190 e[next] = e[cur] + (ei+ej-EROW(m,isw)-EROW(m,jsw))/nn;
192 efac = kT ? exp((e[next]-e[cur])/kT) : -1;
193 if ((e[next] > e[cur]) || (efac > rando(seed))) {
195 if (e[next] > e[cur])
196 cp_index(nn,m->m_ind,low_index);
198 fprintf(log,"Taking uphill step\n");
200 /* Now swapping rows */
201 m->m_ind[isw] = jjsw;
202 m->m_ind[jsw] = iisw;
206 fprintf(log,"Iter: %d Swapped %4d and %4d (now %g)",
207 i,isw,jsw,mat_energy(m));
208 pr_energy(log,e[cur]);
211 /* Now restore the highest energy index */
212 cp_index(nn,low_index,m->m_ind);
215 static void calc_dist(int nind,rvec x[],real **d)
221 for(i=0; (i<nind-1); i++) {
223 for(j=i+1; (j<nind); j++) {
224 /* Should use pbc_dx when analysing multiple molecueles,
225 * but the box is not stored for every frame.
227 rvec_sub(xi,x[j],dx);
233 static real rms_dist(int isize,real **d,real **d_r)
239 for(i=0; (i<isize-1); i++)
240 for(j=i+1; (j<isize); j++) {
244 r2/=(isize*(isize-1))/2;
249 static int rms_dist_comp(const void *a,const void *b)
256 if (da->dist - db->dist < 0)
258 else if (da->dist - db->dist > 0)
263 static int clust_id_comp(const void *a,const void *b)
270 return da->clust - db->clust;
273 static int nrnb_comp(const void *a, const void *b)
280 /* return the b-a, we want highest first */
281 return db->nr - da->nr;
284 void gather(t_mat *m,real cutoff,t_clusters *clust)
288 int i,j,k,nn,cid,n1,diff;
291 /* First we sort the entries in the RMSD matrix */
295 for(i=k=0; (i<n1); i++)
296 for(j=i+1; (j<n1); j++,k++) {
299 d[k].dist = m->mat[i][j];
302 gmx_incons("gather algortihm");
303 qsort(d,nn,sizeof(d[0]),rms_dist_comp);
305 /* Now we make a cluster index for all of the conformations */
308 /* Now we check the closest structures, and equalize their cluster numbers */
309 fprintf(stderr,"Linking structures ");
313 for(k=0; (k<nn) && (d[k].dist < cutoff); k++) {
314 diff = c[d[k].j].clust - c[d[k].i].clust;
318 c[d[k].j].clust = c[d[k].i].clust;
320 c[d[k].i].clust = c[d[k].j].clust;
324 fprintf(stderr,"\nSorting and renumbering clusters\n");
325 /* Sort on cluster number */
326 qsort(c,n1,sizeof(c[0]),clust_id_comp);
328 /* Renumber clusters */
330 for(k=1; k<n1; k++) {
331 if (c[k].clust != c[k-1].clust) {
339 for(k=0; (k<n1); k++)
340 fprintf(debug,"Cluster index for conformation %d: %d\n",
341 c[k].conf,c[k].clust);
344 clust->cl[c[k].conf] = c[k].clust;
350 gmx_bool jp_same(int **nnb,int i,int j,int P)
356 for(k=0; nnb[i][k]>=0; k++)
357 bIn = bIn || (nnb[i][k] == j);
362 for(k=0; nnb[j][k]>=0; k++)
363 bIn = bIn || (nnb[j][k] == i);
368 for(ii=0; nnb[i][ii]>=0; ii++)
369 for(jj=0; nnb[j][jj]>=0; jj++)
370 if ((nnb[i][ii] == nnb[j][jj]) && (nnb[i][ii] != -1))
376 static void jarvis_patrick(int n1,real **mat,int M,int P,
377 real rmsdcut,t_clusters *clust)
382 int i,j,k,cid,diff,max;
389 /* First we sort the entries in the RMSD matrix row by row.
390 * This gives us the nearest neighbor list.
394 for(i=0; (i<n1); i++) {
395 for(j=0; (j<n1); j++) {
397 row[j].dist = mat[i][j];
399 qsort(row,n1,sizeof(row[0]),rms_dist_comp);
401 /* Put the M nearest neighbors in the list */
403 for(j=k=0; (k<M) && (j<n1) && (mat[i][row[j].j] < rmsdcut); j++)
405 nnb[i][k] = row[j].j;
410 /* Put all neighbors nearer than rmsdcut in the list */
413 for(j=0; (j<n1) && (mat[i][row[j].j] < rmsdcut); j++)
419 nnb[i][k] = row[j].j;
423 srenew(nnb[i],max+1);
429 fprintf(debug,"Nearest neighborlist. M = %d, P = %d\n",M,P);
430 for(i=0; (i<n1); i++) {
431 fprintf(debug,"i:%5d nbs:",i);
432 for(j=0; nnb[i][j]>=0; j++)
433 fprintf(debug,"%5d[%5.3f]",nnb[i][j],mat[i][nnb[i][j]]);
439 fprintf(stderr,"Linking structures ");
440 /* Use mcpy for temporary storage of booleans */
441 mcpy = mk_matrix(n1,n1,FALSE);
443 for(j=i+1; j<n1; j++)
444 mcpy[i][j] = jp_same(nnb,i,j,P);
448 for(i=0; i<n1; i++) {
449 for(j=i+1; j<n1; j++)
451 diff = c[j].clust - c[i].clust;
455 c[j].clust = c[i].clust;
457 c[i].clust = c[j].clust;
463 fprintf(stderr,"\nSorting and renumbering clusters\n");
464 /* Sort on cluster number */
465 qsort(c,n1,sizeof(c[0]),clust_id_comp);
467 /* Renumber clusters */
469 for(k=1; k<n1; k++) {
470 if (c[k].clust != c[k-1].clust) {
479 clust->cl[c[k].conf] = c[k].clust;
481 for(k=0; (k<n1); k++)
482 fprintf(debug,"Cluster index for conformation %d: %d\n",
483 c[k].conf,c[k].clust);
485 /* Again, I don't see the point in this... (AF) */
486 /* for(i=0; (i<n1); i++) { */
487 /* for(j=0; (j<n1); j++) */
488 /* mcpy[c[i].conf][c[j].conf] = mat[i][j]; */
490 /* for(i=0; (i<n1); i++) { */
491 /* for(j=0; (j<n1); j++) */
492 /* mat[i][j] = mcpy[i][j]; */
494 done_matrix(n1,&mcpy);
497 for(i=0; (i<n1); i++)
502 static void dump_nnb (FILE *fp, const char *title, int n1, t_nnb *nnb)
506 /* dump neighbor list */
507 fprintf(fp,"%s",title);
508 for(i=0; (i<n1); i++) {
509 fprintf(fp,"i:%5d #:%5d nbs:",i,nnb[i].nr);
510 for(j=0; j<nnb[i].nr; j++)
511 fprintf(fp,"%5d",nnb[i].nb[j]);
516 static void gromos(int n1, real **mat, real rmsdcut, t_clusters *clust)
522 /* Put all neighbors nearer than rmsdcut in the list */
523 fprintf(stderr,"Making list of neighbors within cutoff ");
526 for(i=0; (i<n1); i++) {
529 /* put all neighbors within cut-off in list */
531 if (mat[i][j] < rmsdcut) {
534 srenew(nnb[i].nb,max);
539 /* store nr of neighbors, we'll need that */
541 if (i%(1+n1/100)==0) fprintf(stderr,"%3d%%\b\b\b\b",(i*100+1)/n1);
543 fprintf(stderr,"%3d%%\n",100);
546 /* sort neighbor list on number of neighbors, largest first */
547 qsort(nnb,n1,sizeof(nnb[0]),nrnb_comp);
549 if (debug) dump_nnb(debug, "Nearest neighborlist after sort.\n", n1, nnb);
551 /* turn first structure with all its neighbors (largest) into cluster
552 remove them from pool of structures and repeat for all remaining */
553 fprintf(stderr,"Finding clusters %4d", 0);
554 /* cluster id's start at 1: */
557 /* set cluster id (k) for first item in neighborlist */
558 for (j=0; j<nnb[0].nr; j++)
559 clust->cl[nnb[0].nb[j]] = k;
564 /* adjust number of neighbors for others, taking removals into account: */
565 for(i=1; i<n1 && nnb[i].nr; i++) {
567 for(j=0; j<nnb[i].nr; j++)
568 /* if this neighbor wasn't removed */
569 if ( clust->cl[nnb[i].nb[j]] == 0 ) {
570 /* shift the rest (j1<=j) */
571 nnb[i].nb[j1]=nnb[i].nb[j];
575 /* now j1 is the new number of neighbors */
578 /* sort again on nnb[].nr, because we have new # neighbors: */
579 /* but we only need to sort upto i, i.e. when nnb[].nr>0 */
580 qsort(nnb,i,sizeof(nnb[0]),nrnb_comp);
582 fprintf(stderr,"\b\b\b\b%4d",k);
586 fprintf(stderr,"\n");
589 fprintf(debug,"Clusters (%d):\n", k);
591 fprintf(debug," %3d", clust->cl[i]);
598 rvec **read_whole_trj(const char *fn,int isize,atom_id index[],int skip,
599 int *nframe, real **time,const output_env_t oenv,gmx_bool bPBC, gmx_rmpbc_t gpbc)
612 natom = read_first_x(oenv,&status,fn,&t,&x,box);
617 gmx_rmpbc(gpbc,natom,box,x);
622 srenew(*time,max_nf);
624 if ((i % skip) == 0) {
626 /* Store only the interesting atoms */
627 for(j=0; (j<isize); j++)
628 copy_rvec(x[index[j]],xx[i0][j]);
633 } while (read_next_x(oenv,status,&t,natom,x,box));
634 fprintf(stderr,"Allocated %lu bytes for frames\n",
635 (unsigned long) (max_nf*isize*sizeof(**xx)));
636 fprintf(stderr,"Read %d frames from trajectory %s\n",i0,fn);
643 static int plot_clusters(int nf, real **mat, t_clusters *clust,
644 int nlevels, int minstruct)
647 int *cl_id,*nstruct,*strind;
652 for(i=0; i<nf; i++) {
654 cl_id[i] = clust->cl[i];
658 for(i=0; i<nf; i++) {
659 if (nstruct[i] >= minstruct) {
661 for(j=0; (j<nf); j++)
663 strind[j] = ncluster;
667 fprintf(stderr,"There are %d clusters with at least %d conformations\n",
670 for(i=0; (i<nf); i++) {
673 if ((ci == cl_id[j]) && (nstruct[ci] >= minstruct)) {
674 /* color different clusters with different colors, as long as
675 we don't run out of colors */
676 mat[i][j] = strind[i];
688 static void mark_clusters(int nf, real **mat, real val, t_clusters *clust)
694 if (clust->cl[i] == clust->cl[j])
700 static char *parse_filename(const char *fn, int maxnr)
708 gmx_fatal(FARGS,"will not number filename %s containing '%c'",fn,'%');
709 /* number of digits needed in numbering */
710 i = (int)(log(maxnr)/log(10)) + 1;
711 /* split fn and ext */
712 ext = strrchr(fn, '.');
714 gmx_fatal(FARGS,"cannot separate extension in filename %s",fn);
716 /* insert e.g. '%03d' between fn and ext */
717 sprintf(buf,"%s%%0%dd.%s",fn,i,ext);
718 snew(fnout,strlen(buf)+1);
724 static void ana_trans(t_clusters *clust, int nf,
725 const char *transfn, const char *ntransfn, FILE *log,
726 t_rgb rlo,t_rgb rhi,const output_env_t oenv)
731 int i,ntranst,maxtrans;
734 snew(ntrans,clust->ncl);
735 snew(trans,clust->ncl);
736 snew(axis,clust->ncl);
737 for(i=0; i<clust->ncl; i++) {
739 snew(trans[i],clust->ncl);
744 if(clust->cl[i] != clust->cl[i-1]) {
746 ntrans[clust->cl[i-1]-1]++;
747 ntrans[clust->cl[i]-1]++;
748 trans[clust->cl[i-1]-1][clust->cl[i]-1]++;
749 maxtrans = max(maxtrans, trans[clust->cl[i]-1][clust->cl[i-1]-1]);
751 ffprintf_dd(stderr,log,buf,"Counted %d transitions in total, "
752 "max %d between two specific clusters\n",ntranst,maxtrans);
754 fp=ffopen(transfn,"w");
755 i = min(maxtrans+1, 80);
756 write_xpm(fp,0,"Cluster Transitions","# transitions",
757 "from cluster","to cluster",
758 clust->ncl, clust->ncl, axis, axis, trans,
759 0, maxtrans, rlo, rhi, &i);
763 fp=xvgropen(ntransfn,"Cluster Transitions","Cluster #","# transitions",
765 for(i=0; i<clust->ncl; i++)
766 fprintf(fp,"%5d %5d\n",i+1,ntrans[i]);
770 for(i=0; i<clust->ncl; i++)
776 static void analyze_clusters(int nf, t_clusters *clust, real **rmsd,
777 int natom, t_atoms *atoms, rvec *xtps,
778 real *mass, rvec **xx, real *time,
779 int ifsize, atom_id *fitidx,
780 int iosize, atom_id *outidx,
781 const char *trxfn, const char *sizefn,
782 const char *transfn, const char *ntransfn,
783 const char *clustidfn, gmx_bool bAverage,
784 int write_ncl, int write_nst, real rmsmin,
785 gmx_bool bFit, FILE *log,t_rgb rlo,t_rgb rhi,
786 const output_env_t oenv)
789 char buf[STRLEN],buf1[40],buf2[40],buf3[40],*trxsfn;
790 t_trxstatus *trxout=NULL;
791 t_trxstatus *trxsout=NULL;
792 int i,i1,cl,nstr,*structure,first=0,midstr;
793 gmx_bool *bWrite=NULL;
794 real r,clrmsd,midrmsd;
800 ffprintf_d(stderr,log,buf,"\nFound %d clusters\n\n",clust->ncl);
803 /* do we write all structures? */
805 trxsfn = parse_filename(trxfn, max(write_ncl,clust->ncl));
808 ffprintf_ss(stderr,log,buf,"Writing %s structure for each cluster to %s\n",
809 bAverage ? "average" : "middle", trxfn);
811 /* find out what we want to tell the user:
812 Writing [all structures|structures with rmsd > %g] for
813 {all|first %d} clusters {with more than %d structures} to %s */
815 sprintf(buf1,"structures with rmsd > %g",rmsmin);
817 sprintf(buf1,"all structures");
818 buf2[0]=buf3[0]='\0';
819 if (write_ncl>=clust->ncl) {
821 sprintf(buf2,"all ");
823 sprintf(buf2,"the first %d ",write_ncl);
825 sprintf(buf3," with more than %d structures",write_nst);
826 sprintf(buf,"Writing %s for %sclusters%s to %s\n",buf1,buf2,buf3,trxsfn);
827 ffprintf(stderr,log,buf);
830 /* Prepare a reference structure for the orientation of the clusters */
832 reset_x(ifsize,fitidx,natom,NULL,xtps,mass);
833 trxout = open_trx(trxfn,"w");
834 /* Calculate the average structure in each cluster, *
835 * all structures are fitted to the first struture of the cluster */
839 if (transfn || ntransfn)
840 ana_trans(clust, nf, transfn, ntransfn, log,rlo,rhi,oenv);
843 fp=xvgropen(clustidfn,"Clusters",output_env_get_xvgr_tlabel(oenv),"Cluster #",oenv);
844 fprintf(fp,"@ s0 symbol 2\n");
845 fprintf(fp,"@ s0 symbol size 0.2\n");
846 fprintf(fp,"@ s0 linestyle 0\n");
848 fprintf(fp,"%8g %8d\n",time[i],clust->cl[i]);
852 fp=xvgropen(sizefn,"Cluster Sizes","Cluster #","# Structures",oenv);
853 fprintf(fp,"@g%d type %s\n",0,"bar");
856 fprintf(log,"\n%3s | %3s %4s | %6s %4s | cluster members\n",
857 "cl.","#st","rmsd","middle","rmsd");
858 for(cl=1; cl<=clust->ncl; cl++) {
859 /* prepare structures (fit, middle, average) */
861 for(i=0; i<natom;i++)
864 for(i1=0; i1<nf; i1++)
865 if (clust->cl[i1] == cl) {
866 structure[nstr] = i1;
868 if (trxfn && (bAverage || write_ncl) ) {
870 reset_x(ifsize,fitidx,natom,NULL,xx[i1],mass);
874 do_fit(natom,mass,xx[first],xx[i1]);
876 for(i=0; i<natom; i++)
877 rvec_inc(xav[i],xx[i1][i]);
881 fprintf(fp,"%8d %8d\n",cl,nstr);
885 for(i1=0; i1<nstr; i1++) {
888 for(i=0; i<nstr; i++)
890 r += rmsd[structure[i]][structure[i1]];
892 r += rmsd[structure[i1]][structure[i]];
896 midstr = structure[i1];
903 /* dump cluster info to logfile */
905 sprintf(buf1,"%6.3f",clrmsd);
908 sprintf(buf2,"%5.3f",midrmsd);
912 sprintf(buf1,"%5s","");
913 sprintf(buf2,"%5s","");
915 fprintf(log,"%3d | %3d %s | %6g%s |",cl,nstr,buf1,time[midstr],buf2);
916 for(i=0; i<nstr; i++) {
917 if ((i % 7 == 0) && i)
918 sprintf(buf,"\n%3s | %3s %4s | %6s %4s |","","","","","");
922 fprintf(log,"%s %6g",buf,time[i1]);
926 /* write structures to trajectory file(s) */
929 for(i=0; i<nstr; i++)
931 if ( cl < write_ncl+1 && nstr > write_nst ) {
932 /* Dump all structures for this cluster */
933 /* generate numbered filename (there is a %d in trxfn!) */
934 sprintf(buf,trxsfn,cl);
935 trxsout = open_trx(buf,"w");
936 for(i=0; i<nstr; i++) {
939 for(i1=0; i1<i && bWrite[i]; i1++)
941 bWrite[i] = rmsd[structure[i1]][structure[i]] > rmsmin;
943 write_trx(trxsout,iosize,outidx,atoms,i,time[structure[i]],zerobox,
944 xx[structure[i]],NULL,NULL);
948 /* Dump the average structure for this cluster */
950 for(i=0; i<natom; i++)
951 svmul(1.0/nstr,xav[i],xav[i]);
953 for(i=0; i<natom; i++)
954 copy_rvec(xx[midstr][i],xav[i]);
956 reset_x(ifsize,fitidx,natom,NULL,xav,mass);
959 do_fit(natom,mass,xtps,xav);
961 write_trx(trxout,iosize,outidx,atoms,cl,time[midstr],zerobox,xav,NULL,NULL);
976 static void convert_mat(t_matrix *mat,t_mat *rms)
981 matrix2real(mat,rms->mat);
982 /* free input xpm matrix data */
983 for(i=0; i<mat->nx; i++)
984 sfree(mat->matrix[i]);
987 for(i=0; i<mat->nx; i++)
988 for(j=i; j<mat->nx; j++) {
989 rms->sumrms += rms->mat[i][j];
990 rms->maxrms = max(rms->maxrms, rms->mat[i][j]);
992 rms->minrms = min(rms->minrms, rms->mat[i][j]);
997 int gmx_cluster(int argc,char *argv[])
999 const char *desc[] = {
1000 "[TT]g_cluster[tt] can cluster structures using several different methods.",
1001 "Distances between structures can be determined from a trajectory",
1002 "or read from an [TT].xpm[tt] matrix file with the [TT]-dm[tt] option.",
1003 "RMS deviation after fitting or RMS deviation of atom-pair distances",
1004 "can be used to define the distance between structures.[PAR]",
1006 "single linkage: add a structure to a cluster when its distance to any",
1007 "element of the cluster is less than [TT]cutoff[tt].[PAR]",
1009 "Jarvis Patrick: add a structure to a cluster when this structure",
1010 "and a structure in the cluster have each other as neighbors and",
1011 "they have a least [TT]P[tt] neighbors in common. The neighbors",
1012 "of a structure are the M closest structures or all structures within",
1013 "[TT]cutoff[tt].[PAR]",
1015 "Monte Carlo: reorder the RMSD matrix using Monte Carlo.[PAR]",
1017 "diagonalization: diagonalize the RMSD matrix.[PAR]",
1019 "gromos: use algorithm as described in Daura [IT]et al.[it]",
1020 "([IT]Angew. Chem. Int. Ed.[it] [BB]1999[bb], [IT]38[it], pp 236-240).",
1021 "Count number of neighbors using cut-off, take structure with",
1022 "largest number of neighbors with all its neighbors as cluster",
1023 "and eliminate it from the pool of clusters. Repeat for remaining",
1024 "structures in pool.[PAR]",
1026 "When the clustering algorithm assigns each structure to exactly one",
1027 "cluster (single linkage, Jarvis Patrick and gromos) and a trajectory",
1028 "file is supplied, the structure with",
1029 "the smallest average distance to the others or the average structure",
1030 "or all structures for each cluster will be written to a trajectory",
1031 "file. When writing all structures, separate numbered files are made",
1032 "for each cluster.[PAR]",
1034 "Two output files are always written:[BR]",
1035 "[TT]-o[tt] writes the RMSD values in the upper left half of the matrix",
1036 "and a graphical depiction of the clusters in the lower right half",
1037 "When [TT]-minstruct[tt] = 1 the graphical depiction is black",
1038 "when two structures are in the same cluster.",
1039 "When [TT]-minstruct[tt] > 1 different colors will be used for each",
1041 "[TT]-g[tt] writes information on the options used and a detailed list",
1042 "of all clusters and their members.[PAR]",
1044 "Additionally, a number of optional output files can be written:[BR]",
1045 "[TT]-dist[tt] writes the RMSD distribution.[BR]",
1046 "[TT]-ev[tt] writes the eigenvectors of the RMSD matrix",
1047 "diagonalization.[BR]",
1048 "[TT]-sz[tt] writes the cluster sizes.[BR]",
1049 "[TT]-tr[tt] writes a matrix of the number transitions between",
1050 "cluster pairs.[BR]",
1051 "[TT]-ntr[tt] writes the total number of transitions to or from",
1052 "each cluster.[BR]",
1053 "[TT]-clid[tt] writes the cluster number as a function of time.[BR]",
1054 "[TT]-cl[tt] writes average (with option [TT]-av[tt]) or central",
1055 "structure of each cluster or writes numbered files with cluster members",
1056 "for a selected set of clusters (with option [TT]-wcl[tt], depends on",
1057 "[TT]-nst[tt] and [TT]-rmsmin[tt]). The center of a cluster is the",
1058 "structure with the smallest average RMSD from all other structures",
1059 "of the cluster.[BR]",
1063 int i,i1,i2,j,nf,nrms;
1066 rvec *xtps,*usextps,*x1,**xx=NULL;
1067 const char *fn,*trx_out_fn;
1074 t_matrix *readmat=NULL;
1077 int isize=0,ifsize=0,iosize=0;
1078 atom_id *index=NULL, *fitidx, *outidx;
1080 real rmsd,**d1,**d2,*time=NULL,time_invfac,*mass=NULL;
1081 char buf[STRLEN],buf1[80],title[STRLEN];
1082 gmx_bool bAnalyze,bUseRmsdCut,bJP_RMSD=FALSE,bReadMat,bReadTraj,bPBC=TRUE;
1084 int method,ncluster=0;
1085 static const char *methodname[] = {
1086 NULL, "linkage", "jarvis-patrick","monte-carlo",
1087 "diagonalization", "gromos", NULL
1089 enum { m_null, m_linkage, m_jarvis_patrick,
1090 m_monte_carlo, m_diagonalize, m_gromos, m_nr };
1091 /* Set colors for plotting: white = zero RMS, black = maximum */
1092 static t_rgb rlo_top = { 1.0, 1.0, 1.0 };
1093 static t_rgb rhi_top = { 0.0, 0.0, 0.0 };
1094 static t_rgb rlo_bot = { 1.0, 1.0, 1.0 };
1095 static t_rgb rhi_bot = { 0.0, 0.0, 1.0 };
1096 static int nlevels=40,skip=1;
1097 static real scalemax=-1.0,rmsdcut=0.1,rmsmin=0.0;
1098 gmx_bool bRMSdist=FALSE,bBinary=FALSE,bAverage=FALSE,bFit=TRUE;
1099 static int niter=10000,seed=1993,write_ncl=0,write_nst=1,minstruct=1;
1100 static real kT=1e-3;
1101 static int M=10,P=3;
1103 gmx_rmpbc_t gpbc=NULL;
1106 { "-dista", FALSE, etBOOL, {&bRMSdist},
1107 "Use RMSD of distances instead of RMS deviation" },
1108 { "-nlevels",FALSE,etINT, {&nlevels},
1109 "Discretize RMSD matrix in # levels" },
1110 { "-cutoff",FALSE, etREAL, {&rmsdcut},
1111 "RMSD cut-off (nm) for two structures to be neighbor" },
1112 { "-fit", FALSE, etBOOL, {&bFit},
1113 "Use least squares fitting before RMSD calculation" },
1114 { "-max", FALSE, etREAL, {&scalemax},
1115 "Maximum level in RMSD matrix" },
1116 { "-skip", FALSE, etINT, {&skip},
1117 "Only analyze every nr-th frame" },
1118 { "-av", FALSE, etBOOL, {&bAverage},
1119 "Write average iso middle structure for each cluster" },
1120 { "-wcl", FALSE, etINT, {&write_ncl},
1121 "Write all structures for first # clusters to numbered files" },
1122 { "-nst", FALSE, etINT, {&write_nst},
1123 "Only write all structures if more than # per cluster" },
1124 { "-rmsmin",FALSE, etREAL, {&rmsmin},
1125 "minimum rms difference with rest of cluster for writing structures" },
1126 { "-method",FALSE, etENUM, {methodname},
1127 "Method for cluster determination" },
1128 { "-minstruct", FALSE, etINT, {&minstruct},
1129 "Minimum number of structures in cluster for coloring in the [TT].xpm[tt] file" },
1130 { "-binary",FALSE, etBOOL, {&bBinary},
1131 "Treat the RMSD matrix as consisting of 0 and 1, where the cut-off "
1132 "is given by [TT]-cutoff[tt]" },
1133 { "-M", FALSE, etINT, {&M},
1134 "Number of nearest neighbors considered for Jarvis-Patrick algorithm, "
1135 "0 is use cutoff" },
1136 { "-P", FALSE, etINT, {&P},
1137 "Number of identical nearest neighbors required to form a cluster" },
1138 { "-seed", FALSE, etINT, {&seed},
1139 "Random number seed for Monte Carlo clustering algorithm" },
1140 { "-niter", FALSE, etINT, {&niter},
1141 "Number of iterations for MC" },
1142 { "-kT", FALSE, etREAL, {&kT},
1143 "Boltzmann weighting factor for Monte Carlo optimization "
1144 "(zero turns off uphill steps)" },
1145 { "-pbc", FALSE, etBOOL,
1146 { &bPBC }, "PBC check" }
1149 { efTRX, "-f", NULL, ffOPTRD },
1150 { efTPS, "-s", NULL, ffOPTRD },
1151 { efNDX, NULL, NULL, ffOPTRD },
1152 { efXPM, "-dm", "rmsd", ffOPTRD },
1153 { efXPM, "-o", "rmsd-clust", ffWRITE },
1154 { efLOG, "-g", "cluster", ffWRITE },
1155 { efXVG, "-dist", "rmsd-dist", ffOPTWR },
1156 { efXVG, "-ev", "rmsd-eig", ffOPTWR },
1157 { efXVG, "-sz", "clust-size", ffOPTWR},
1158 { efXPM, "-tr", "clust-trans",ffOPTWR},
1159 { efXVG, "-ntr", "clust-trans",ffOPTWR},
1160 { efXVG, "-clid", "clust-id.xvg",ffOPTWR},
1161 { efTRX, "-cl", "clusters.pdb", ffOPTWR }
1163 #define NFILE asize(fnm)
1165 CopyRight(stderr,argv[0]);
1166 parse_common_args(&argc,argv,
1167 PCA_CAN_VIEW | PCA_CAN_TIME | PCA_TIME_UNIT | PCA_BE_NICE,
1168 NFILE,fnm,asize(pa),pa,asize(desc),desc,0,NULL,
1172 bReadMat = opt2bSet("-dm",NFILE,fnm);
1173 bReadTraj = opt2bSet("-f",NFILE,fnm) || !bReadMat;
1174 if ( opt2parg_bSet("-av",asize(pa),pa) ||
1175 opt2parg_bSet("-wcl",asize(pa),pa) ||
1176 opt2parg_bSet("-nst",asize(pa),pa) ||
1177 opt2parg_bSet("-rmsmin",asize(pa),pa) ||
1178 opt2bSet("-cl",NFILE,fnm) )
1179 trx_out_fn = opt2fn("-cl",NFILE,fnm);
1182 if (bReadMat && output_env_get_time_factor(oenv)!=1) {
1184 "\nWarning: assuming the time unit in %s is %s\n",
1185 opt2fn("-dm",NFILE,fnm),output_env_get_time_unit(oenv));
1187 if (trx_out_fn && !bReadTraj)
1188 fprintf(stderr,"\nWarning: "
1189 "cannot write cluster structures without reading trajectory\n"
1190 " ignoring option -cl %s\n", trx_out_fn);
1193 while ( method < m_nr && gmx_strcasecmp(methodname[0], methodname[method])!=0 )
1196 gmx_fatal(FARGS,"Invalid method");
1198 bAnalyze = (method == m_linkage || method == m_jarvis_patrick ||
1199 method == m_gromos );
1202 log = ftp2FILE(efLOG,NFILE,fnm,"w");
1204 fprintf(stderr,"Using %s method for clustering\n",methodname[0]);
1205 fprintf(log,"Using %s method for clustering\n",methodname[0]);
1207 /* check input and write parameters to log file */
1208 bUseRmsdCut = FALSE;
1209 if (method == m_jarvis_patrick) {
1210 bJP_RMSD = (M == 0) || opt2parg_bSet("-cutoff",asize(pa),pa);
1211 if ((M<0) || (M == 1))
1212 gmx_fatal(FARGS,"M (%d) must be 0 or larger than 1",M);
1214 sprintf(buf1,"Will use P=%d and RMSD cutoff (%g)",P,rmsdcut);
1218 gmx_fatal(FARGS,"Number of neighbors required (P) must be less than M");
1220 sprintf(buf1,"Will use P=%d, M=%d and RMSD cutoff (%g)",P,M,rmsdcut);
1223 sprintf(buf1,"Will use P=%d, M=%d",P,M);
1225 ffprintf_s(stderr,log,buf,"%s for determining the neighbors\n\n",buf1);
1226 } else /* method != m_jarvis */
1227 bUseRmsdCut = ( bBinary || method == m_linkage || method == m_gromos );
1228 if (bUseRmsdCut && method != m_jarvis_patrick)
1229 fprintf(log,"Using RMSD cutoff %g nm\n",rmsdcut);
1230 if ( method==m_monte_carlo )
1231 fprintf(log,"Using %d iterations\n",niter);
1234 gmx_fatal(FARGS,"skip (%d) should be >= 1",skip);
1238 /* don't read mass-database as masses (and top) are not used */
1239 read_tps_conf(ftp2fn(efTPS,NFILE,fnm),buf,&top,&ePBC,&xtps,NULL,box,
1242 gpbc = gmx_rmpbc_init(&top.idef,ePBC,top.atoms.nr,box);
1245 fprintf(stderr,"\nSelect group for least squares fit%s:\n",
1246 bReadMat?"":" and RMSD calculation");
1247 get_index(&(top.atoms),ftp2fn_null(efNDX,NFILE,fnm),
1248 1,&ifsize,&fitidx,&grpname);
1250 fprintf(stderr,"\nSelect group for output:\n");
1251 get_index(&(top.atoms),ftp2fn_null(efNDX,NFILE,fnm),
1252 1,&iosize,&outidx,&grpname);
1253 /* merge and convert both index groups: */
1254 /* first copy outidx to index. let outidx refer to elements in index */
1257 for(i=0; i<iosize; i++) {
1261 /* now lookup elements from fitidx in index, add them if necessary
1262 and also let fitidx refer to elements in index */
1263 for(i=0; i<ifsize; i++) {
1265 while (j<isize && index[j]!=fitidx[i])
1268 /* slow this way, but doesn't matter much */
1270 srenew(index,isize);
1275 } else { /* !trx_out_fn */
1278 for(i=0; i<ifsize; i++) {
1284 /* Initiate arrays */
1287 for(i=0; (i<isize); i++) {
1293 /* Loop over first coordinate file */
1294 fn = opt2fn("-f",NFILE,fnm);
1296 xx = read_whole_trj(fn,isize,index,skip,&nf,&time,oenv,bPBC,gpbc);
1297 output_env_conv_times(oenv, nf, time);
1298 if (!bRMSdist || bAnalyze) {
1299 /* Center all frames on zero */
1301 for(i=0; i<ifsize; i++)
1302 mass[fitidx[i]] = top.atoms.atom[index[fitidx[i]]].m;
1305 reset_x(ifsize,fitidx,isize,NULL,xx[i],mass);
1309 gmx_rmpbc_done(gpbc);
1314 fprintf(stderr,"Reading rms distance matrix ");
1315 read_xpm_matrix(opt2fn("-dm",NFILE,fnm),&readmat);
1316 fprintf(stderr,"\n");
1317 if (readmat[0].nx != readmat[0].ny)
1318 gmx_fatal(FARGS,"Matrix (%dx%d) is not square",
1319 readmat[0].nx,readmat[0].ny);
1320 if (bReadTraj && bAnalyze && (readmat[0].nx != nf))
1321 gmx_fatal(FARGS,"Matrix size (%dx%d) does not match the number of "
1322 "frames (%d)",readmat[0].nx,readmat[0].ny,nf);
1326 time = readmat[0].axis_x;
1327 time_invfac = output_env_get_time_invfactor(oenv);
1329 time[i] *= time_invfac;
1331 rms = init_mat(readmat[0].nx,method == m_diagonalize);
1332 convert_mat(&(readmat[0]),rms);
1334 nlevels = readmat[0].nmap;
1335 } else { /* !bReadMat */
1336 rms = init_mat(nf,method == m_diagonalize);
1337 nrms = (nf*(nf-1))/2;
1339 fprintf(stderr,"Computing %dx%d RMS deviation matrix\n",nf,nf);
1341 for(i1=0; (i1<nf); i1++) {
1342 for(i2=i1+1; (i2<nf); i2++) {
1343 for(i=0; i<isize; i++)
1344 copy_rvec(xx[i1][i],x1[i]);
1346 do_fit(isize,mass,xx[i2],x1);
1347 rmsd = rmsdev(isize,mass,xx[i2],x1);
1348 set_mat_entry(rms,i1,i2,rmsd);
1351 fprintf(stderr,"\r# RMSD calculations left: %d ",nrms);
1353 } else { /* bRMSdist */
1354 fprintf(stderr,"Computing %dx%d RMS distance deviation matrix\n",nf,nf);
1355 for(i1=0; (i1<nf); i1++) {
1356 calc_dist(isize,xx[i1],d1);
1357 for(i2=i1+1; (i2<nf); i2++) {
1358 calc_dist(isize,xx[i2],d2);
1359 set_mat_entry(rms,i1,i2,rms_dist(isize,d1,d2));
1362 fprintf(stderr,"\r# RMSD calculations left: %d ",nrms);
1365 fprintf(stderr,"\n\n");
1367 ffprintf_gg(stderr,log,buf,"The RMSD ranges from %g to %g nm\n",
1368 rms->minrms,rms->maxrms);
1369 ffprintf_g(stderr,log,buf,"Average RMSD is %g\n",2*rms->sumrms/(nf*(nf-1)));
1370 ffprintf_d(stderr,log,buf,"Number of structures for matrix %d\n",nf);
1371 ffprintf_g(stderr,log,buf,"Energy of the matrix is %g nm\n",mat_energy(rms));
1372 if (bUseRmsdCut && (rmsdcut < rms->minrms || rmsdcut > rms->maxrms) )
1373 fprintf(stderr,"WARNING: rmsd cutoff %g is outside range of rmsd values "
1374 "%g to %g\n",rmsdcut,rms->minrms,rms->maxrms);
1375 if (bAnalyze && (rmsmin < rms->minrms) )
1376 fprintf(stderr,"WARNING: rmsd minimum %g is below lowest rmsd value %g\n",
1377 rmsmin,rms->minrms);
1378 if (bAnalyze && (rmsmin > rmsdcut) )
1379 fprintf(stderr,"WARNING: rmsd minimum %g is above rmsd cutoff %g\n",
1382 /* Plot the rmsd distribution */
1383 rmsd_distribution(opt2fn("-dist",NFILE,fnm),rms,oenv);
1386 for(i1=0; (i1 < nf); i1++)
1387 for(i2=0; (i2 < nf); i2++)
1388 if (rms->mat[i1][i2] < rmsdcut)
1389 rms->mat[i1][i2] = 0;
1391 rms->mat[i1][i2] = 1;
1397 /* Now sort the matrix and write it out again */
1398 gather(rms,rmsdcut,&clust);
1401 /* Do a diagonalization */
1404 memcpy(tmp,rms->mat[0],nf*nf*sizeof(real));
1405 eigensolver(tmp,nf,0,nf,eigval,rms->mat[0]);
1408 fp = xvgropen(opt2fn("-ev",NFILE,fnm),"RMSD matrix Eigenvalues",
1409 "Eigenvector index","Eigenvalues (nm\\S2\\N)",oenv);
1410 for(i=0; (i<nf); i++)
1411 fprintf(fp,"%10d %10g\n",i,eigval[i]);
1415 mc_optimize(log,rms,niter,&seed,kT);
1419 case m_jarvis_patrick:
1420 jarvis_patrick(rms->nn,rms->mat,M,P,bJP_RMSD ? rmsdcut : -1,&clust);
1423 gromos(rms->nn,rms->mat,rmsdcut,&clust);
1426 gmx_fatal(FARGS,"DEATH HORROR unknown method \"%s\"",methodname[0]);
1429 if (method == m_monte_carlo || method == m_diagonalize)
1430 fprintf(stderr,"Energy of the matrix after clustering is %g nm\n",
1434 if (minstruct > 1) {
1435 ncluster = plot_clusters(nf,rms->mat,&clust,nlevels,minstruct);
1437 mark_clusters(nf,rms->mat,rms->maxrms,&clust);
1439 init_t_atoms(&useatoms,isize,FALSE);
1440 snew(usextps, isize);
1441 useatoms.resinfo = top.atoms.resinfo;
1442 for(i=0; i<isize; i++) {
1443 useatoms.atomname[i]=top.atoms.atomname[index[i]];
1444 useatoms.atom[i].resind = top.atoms.atom[index[i]].resind;
1445 useatoms.nres = max(useatoms.nres,useatoms.atom[i].resind+1);
1446 copy_rvec(xtps[index[i]],usextps[i]);
1449 analyze_clusters(nf,&clust,rms->mat,isize,&useatoms,usextps,mass,xx,time,
1450 ifsize,fitidx,iosize,outidx,
1451 bReadTraj?trx_out_fn:NULL,
1452 opt2fn_null("-sz",NFILE,fnm),
1453 opt2fn_null("-tr",NFILE,fnm),
1454 opt2fn_null("-ntr",NFILE,fnm),
1455 opt2fn_null("-clid",NFILE,fnm),
1456 bAverage, write_ncl, write_nst, rmsmin, bFit, log,
1457 rlo_bot,rhi_bot,oenv);
1461 if (bBinary && !bAnalyze)
1462 /* Make the clustering visible */
1463 for(i2=0; (i2 < nf); i2++)
1464 for(i1=i2+1; (i1 < nf); i1++)
1465 if (rms->mat[i1][i2])
1466 rms->mat[i1][i2] = rms->maxrms;
1468 fp = opt2FILE("-o",NFILE,fnm,"w");
1469 fprintf(stderr,"Writing rms distance/clustering matrix ");
1471 write_xpm(fp,0,readmat[0].title,readmat[0].legend,readmat[0].label_x,
1472 readmat[0].label_y,nf,nf,readmat[0].axis_x,readmat[0].axis_y,
1473 rms->mat,0.0,rms->maxrms,rlo_top,rhi_top,&nlevels);
1476 sprintf(buf,"Time (%s)",output_env_get_time_unit(oenv));
1477 sprintf(title,"RMS%sDeviation / Cluster Index",
1478 bRMSdist ? " Distance " : " ");
1479 if (minstruct > 1) {
1480 write_xpm_split(fp,0,title,"RMSD (nm)",buf,buf,
1481 nf,nf,time,time,rms->mat,0.0,rms->maxrms,&nlevels,
1482 rlo_top,rhi_top,0.0,(real) ncluster,
1483 &ncluster,TRUE,rlo_bot,rhi_bot);
1485 write_xpm(fp,0,title,"RMSD (nm)",buf,buf,
1486 nf,nf,time,time,rms->mat,0.0,rms->maxrms,
1487 rlo_top,rhi_top,&nlevels);
1490 fprintf(stderr,"\n");
1493 /* now show what we've done */
1494 do_view(oenv,opt2fn("-o",NFILE,fnm),"-nxy");
1495 do_view(oenv,opt2fn_null("-sz",NFILE,fnm),"-nxy");
1496 if (method == m_diagonalize)
1497 do_view(oenv,opt2fn_null("-ev",NFILE,fnm),"-nxy");
1498 do_view(oenv,opt2fn("-dist",NFILE,fnm),"-nxy");
1500 do_view(oenv,opt2fn_null("-tr",NFILE,fnm),"-nxy");
1501 do_view(oenv,opt2fn_null("-ntr",NFILE,fnm),"-nxy");
1502 do_view(oenv,opt2fn_null("-clid",NFILE,fnm),"-nxy");
1505 /* Thank the user for her patience */