1 /* -*- mode: c; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
3 /*********************************************************************
4 * Clustal Omega - Multiple sequence alignment
6 * Copyright (C) 2010 University College Dublin
8 * Clustal-Omega is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License as
10 * published by the Free Software Foundation; either version 2 of the
11 * License, or (at your option) any later version.
13 * This file is part of Clustal-Omega.
15 ********************************************************************/
18 * RCS $Id: hhalignment-C.h 316 2016-12-16 16:14:39Z fabian $
23 * Changelog: Michael Remmert made changes to hhalign stand-alone code
24 * FS implemented some of the changes on 2010-10-28 -> MR1
26 * Note: MR seems to have changed all [aijk]++ to ++[aijk],
27 * FS did not do that on 2010-10-28
32 //////////////////////////////////////////////////////////////////////////////
34 //////////////////////////////////////////////////////////////////////////////
40 #include <iostream> // cin, cout, cerr
41 #include <fstream> // ofstream, ifstream
42 #include <stdio.h> // printf
49 #include <stdlib.h> // exit
50 #include <string> // strcmp, strstr
51 #include <math.h> // sqrt, pow
52 #include <limits.h> // INT_MIN
53 #include <float.h> // FLT_MIN
54 #include <time.h> // clock
55 #include <ctype.h> // islower, isdigit etc
56 #include "util-C.h" // imax, fmax, iround, iceil, ifloor, strint, strscn, strcut, substr, uprstr, uprchr, Basename etc.
57 #include "list.h" // list data structure
58 #include "hash.h" // hash data structure
60 #include "hhutil-C.h" // imax, fmax, iround, iceil, ifloor, strint, strscn, strcut, substr, uprstr, uprchr, Basename etc.
67 //#include "new_new.h" /* memory tracking */
70 enum {KEEP_NOT = 0, KEEP_CONDITIONALLY, KEEP_ALWAYS};
72 //////////////////////////////////////////////////////////////////////////////
74 //////////////////////////////////////////////////////////////////////////////
77 //////////////////////////////////////////////////////////////////////////////
79 //////////////////////////////////////////////////////////////////////////////
80 Alignment::Alignment(int maxseq, int maxres)
83 //printf(">>>>>>>>%s:%s:%d: maxseq=%d, maxres=%d\n", __FUNCTION__, __FILE__, __LINE__, maxseq, maxres); /* (FS) */
84 longname = new(char[DESCLEN]);
85 sname = new char*[maxseq+2]; /* MR1 */
86 seq = new char*[maxseq+2]; /* MR1 */
88 X = new char*[maxseq+2]; /* MR1 */
89 I = new short unsigned int*[maxseq+2]; /* MR1 */
90 keep = new char[maxseq+2]; /* MR1 */
91 display = new char[maxseq+2]; /* MR1 */
92 wg = new float[maxseq+2]; /* MR1 */
93 nseqs = new int[maxres+2]; /* MR1 */
95 nres=NULL; // number of residues per sequence k
96 first=NULL; // first residue in sequence k
97 last=NULL; // last residue in sequence k
98 ksort=NULL; // sequence indices sorted by descending nres[k]
99 name[0]='\0'; // no name defined yet
100 longname[0]='\0'; // no name defined yet
101 fam[0]='\0'; // no name defined yet
102 file[0]='\0'; // no name defined yet
103 readCommentLine = '0'; /* MR1 */
106 //////////////////////////////////////////////////////////////////////////////
108 //////////////////////////////////////////////////////////////////////////////
109 Alignment::~Alignment()
111 delete[] longname; longname = NULL;
112 for(int k=0; k<N_in; k++)
114 delete[] sname[k]; sname[k] = NULL;
115 delete[] seq[k]; seq[k] = NULL;
116 delete[] X[k]; X[k] = NULL;
117 delete[] I[k]; I[k] = NULL;
119 delete[] sname; sname = NULL;
120 delete[] seq; seq = NULL;
121 delete[] X; X = NULL;
122 delete[] I; I = NULL;
123 delete[] l; l = NULL;
124 delete[] keep; keep = NULL;
125 delete[] display; display = NULL;
126 delete[] wg; wg = NULL;
127 delete[] nseqs; nseqs = NULL;
128 delete[] nres; nres = NULL;
129 delete[] first; first = NULL;
130 delete[] last; last = NULL;
131 delete[] ksort; ksort = NULL;
136 * @brief Reads in an alignment from file into matrix seq[k][l] as ASCII
139 Alignment::Read(FILE* inf, char infile[], char* firstline)
141 int l; // Postion in alignment incl. gaps (first=1)
142 int h; // Position in input line (first=0)
143 int k; // Index of sequence being read currently (first=0)
144 char line[LINELEN]=""; // input line
145 //char cur_seq[MAXCOL]; // Sequence currently read in
146 char *cur_seq=new char[par.maxColCnt];
147 char* cur_name; // Sequence currently read in
148 int linenr=0; // current line number in input file
149 char skip_sequence=0;
150 RemoveExtension(file,infile); //copy rootname (w/o path) of infile into file variable of class object
152 kss_dssp=ksa_dssp=kss_pred=kss_conf=kfirst=-1;
157 cur_seq[0]=' '; // overwrite '\0' character at beginning to be able to do strcpy(*,cur_seq)
160 // Does firstline already contain first line of file?
161 if (firstline!= NULL) strcpy(line,firstline);
163 /////////////////////////////////////////////////////////////////////////
164 // Read infile line by line
165 /* FIXME: not safe to use MAXSEQ, however, don't think we ever get here (FS) */
166 while(firstline || (fgetline(line,LINELEN,inf) && (k<MAXSEQ))) /* FIXME: FS introduced () around &&, precedence! MR1 */
170 if (line[0]=='>') //line contains sequence name
174 if (v>=1 && k>=MAXSEQ)
175 cerr<<endl<<"WARNING: maximum number "<<MAXSEQ<<" of sequences exceded in file "<<infile<<"\n";
178 cur_name=line+1; //beginning of current sequence name
179 if (k>=0) //if this is at least the second name line
181 if (strlen(cur_seq)==0)
183 cerr<<endl<<"Error: sequence "<<sname[k]<<" contains no residues."<<endl;
187 // Create space for residues and paste new sequence in
188 seq[k]=new char[strlen(cur_seq)+2];
189 if (!seq[k]) MemoryError("array for input sequences");
190 X[k]=new char[strlen(cur_seq)+2];
191 if (!X[k]) MemoryError("array for input sequences");
192 I[k]=new short unsigned int[strlen(cur_seq)+2];
193 if (!I[k]) MemoryError("array for input sequences");
194 strcpy(seq[k],cur_seq);
199 l=1; //position in current sequence (first=1)
201 // display[k]= 0: do not show in Q-T alignments 1: show if not filtered out later 2: show in any case (do not filter out)
202 // keep[k] = 0: do not include in profile 1: include if not filtered out later 2: include in any case (do not filter out)
203 /* {KEEP_NOT=0, KEEP_CONDITIONALLY=1, KEEP_ALWAYS=2} */
204 if (line[1]=='@') cur_name++; //skip @-character in name
205 if (!strncmp(line,">ss_dssp",8)) {
206 if (kss_dssp<0) {display[k]=2; n_display++; keep[k]=KEEP_NOT; kss_dssp=k; N_ss++;} else {skip_sequence=1; k--; continue;}
208 else if (!strncmp(line,">sa_dssp",8)) {
209 if (ksa_dssp<0) {display[k]=KEEP_ALWAYS; n_display++; keep[k]=KEEP_NOT; ksa_dssp=k; N_ss++;} else {skip_sequence=1; k--; continue;}
211 else if (!strncmp(line,">ss_pred",8)) {
212 if (kss_pred<0) {display[k]=KEEP_ALWAYS; n_display++; keep[k]=KEEP_NOT; kss_pred=k; N_ss++;} else {skip_sequence=1; k--; continue;}
214 else if (!strncmp(line,">ss_conf",8)) {
215 if (kss_conf<0) {display[k]=KEEP_ALWAYS; n_display++; keep[k]=KEEP_NOT; kss_conf=k; N_ss++;} else {skip_sequence=1; k--; continue;}
217 else if (!strncmp(line,">ss_",4) || !strncmp(line,">sa_",4)) {
218 display[k]=KEEP_ALWAYS; n_display++; keep[k]=KEEP_NOT; N_ss++;
220 else if (!strncmp(line,">aa_",4)) { // ignore sequences beginning with ">aa_"
221 skip_sequence=1; k--; continue;
223 //store first real seq
227 strwrd(word,line); // Copies first word in ptr to str
228 if (strstr(word,"_consensus"))
229 {display[k]=2; keep[k]=0; n_display++; kfirst=k;} /* MR1 */
231 {display[k]=keep[k]=KEEP_ALWAYS; n_display++; kfirst=k;}
233 //store all sequences
234 else if (par.mark==0) {display[k]=keep[k]=KEEP_CONDITIONALLY; n_display++;}
235 //store sequences up to nseqdis
236 else if (line[1]=='@'&& n_display-N_ss<par.nseqdis) {display[k]=keep[k]=KEEP_ALWAYS; n_display++;}
237 else {display[k]=KEEP_NOT; keep[k]=KEEP_CONDITIONALLY;}
239 // store sequence name
240 if (v>=4) printf("Reading seq %-16.16s k=%3i n_displ=%3i display[k]=%i keep[k]=%i\n",cur_name,k,n_display,display[k],keep[k]);
241 sname[k] = new char[strlen(cur_name)+1];
242 if (!sname[k]) {MemoryError("array for sequence names");}
243 strcpy(sname[k],cur_name);
244 } // end if(line contains sequence name)
246 else if (line[0]=='#') // Commentary line?
248 // #PF01367.9 5_3_exonuc: 5'-3' exonuclease, C-terminal SAM fold; PDB 1taq, 1bgx (T:271-174), 1taq (271-174)
249 if (name[0]) continue; // if already name defined: skip commentary line
251 ptr1=strscn_(line+1); // set ptr1 to first non-whitespace character after '#' -> AC number
252 strncpy(longname,ptr1,DESCLEN-1); // copy whole commentary line after '# ' into longname
253 longname[DESCLEN-1]='\0';
254 strtr(longname,""," ");
255 ptr2=strcut_(ptr1); // cut after AC number and set ptr2 to first non-whitespace character after AC number
256 // strcpy(fam,ptr1); // copy AC number to fam
257 // if (!strncmp(fam,"PF",2)) strcut_(fam,'.'); // if PFAM identifier contains '.' cut it off
258 // strcut_(ptr2); // cut after first word ...
259 strcpy(name,ptr1); // ... and copy first word into name
260 readCommentLine = '1'; /* MR1 */
263 //line contains sequence residues or SS information and does not belong to a >aa_ sequence
264 else if (!skip_sequence)
266 if (v>=4) cout<<line<<"\n"; //DEBUG
269 cerr<<endl<<"WARNING: No sequence name preceding following line in "<<infile<<":\n\'"<<line<<"\'\n";
273 h=0; //counts characters in current line
275 // Check whether all characters are correct; store into cur_seq
276 if (keep[k] || (k == kfirst) ) // normal line containing residues /* MR1 */
278 while (h<LINELEN && line[h]>'\0' && l</*MAXCOL*/par.maxColCnt-1)
280 if (aa2i(line[h])>=0) // ignore white-space characters ' ', \t and \n (aa2i()==-1)
281 {cur_seq[l]=line[h]; l++;}
282 else if (aa2i(line[h])==-2 && v)
283 cerr<<endl<<"WARNING: invalid symbol \'"<<line[h]<<"\' at pos. "<<h<<" in line "<<linenr<<" of "<<infile<<"\n";
287 else if (k==kss_dssp) // lines with dssp secondary structure states (. - H E C S T G B)
289 while (h<LINELEN && line[h]>'\0' && l</*MAXCOL*/par.maxColCnt-1)
291 if (ss2i(line[h])>=0 && ss2i(line[h])<=7)
292 {cur_seq[l]=ss2ss(line[h]); l++;}
294 cerr<<endl<<"WARNING: invalid symbol \'"<<line[h]<<"\' at pos. "<<h<<" in line "<<linenr<<" of "<<infile<<"\n";
298 else if (k==ksa_dssp) // lines with dssp solvent accessibility states (. - ???)
300 while (h<LINELEN && line[h]>'\0' && l</*MAXCOL*/par.maxColCnt-1)
302 if (sa2i(line[h])>=0)
303 cur_seq[l++]=line[h];
305 cerr<<endl<<"WARNING: invalid symbol \'"<<line[h]<<"\' at pos. "<<h<<" in line "<<linenr<<" of "<<infile<<"\n";
309 else if (k==kss_pred) // lines with predicted secondary structure (. - H E C)
311 while (h<LINELEN && line[h]>'\0' && l</*MAXCOL*/par.maxColCnt-1)
313 if (ss2i(line[h])>=0 && ss2i(line[h])<=3)
314 {cur_seq[l]=ss2ss(line[h]); l++;}
316 cerr<<endl<<"WARNING: invalid symbol \'"<<line[h]<<"\' at pos. "<<h<<" in line "<<linenr<<" of "<<infile<<"\n";
320 else if (k==kss_conf) // lines with confidence values should contain only 0-9, '-', or '.'
322 while (h<LINELEN && line[h]>'\0' && l</*MAXCOL*/par.maxColCnt-1)
324 if (line[h]=='-' || line[h]=='.' || (line[h]>='0' && line[h]<='9'))
325 {cur_seq[l]=line[h]; l++;}
327 cerr<<endl<<"WARNING: invalid symbol \'"<<line[h]<<"\' at pos. "<<l<<" in line "<<linenr<<" of "<<infile<<"\n";
331 else if (display[k]) // other lines such as >sa_pred etc
333 while (h<LINELEN && line[h]>'\0' && l</*MAXCOL*/par.maxColCnt-1)
335 if (line[h]=='-' || line[h]=='.' || (line[h]>='0' && line[h]<='9') || (line[h]>='A' && line[h]<='B'))
336 {cur_seq[l]=line[h]; l++;}
338 cerr<<endl<<"WARNING: invalid symbol \'"<<line[h]<<"\' at pos. "<<l<<" in line "<<linenr<<" of "<<infile<<"\n";
342 if (v && l>=/*MAXCOL*/par.maxColCnt-1)
344 cerr<<endl<<"WARNING: maximum number of residues "<</*MAXCOL*/par.maxColCnt-2<<" exceded in sequence "<<sname[k]<<"\n";
347 cur_seq[l]='\0'; //Ensure that cur_seq ends with a '\0' character
351 /////////////////////////////////////////////////////////////////////////
354 if (k>=0) //if at least one sequence was read in
356 seq[k]=new char[strlen(cur_seq)+2];
357 if (!seq[k]) MemoryError("array for input sequences");
358 X[k]=new char[strlen(cur_seq)+2];
359 if (!X[k]) MemoryError("array for input sequences");
360 I[k]=new short unsigned int[strlen(cur_seq)+2];
361 if (!I[k]) MemoryError("array for input sequences");
362 strcpy(seq[k],cur_seq);
365 {cerr<<endl<<"Error: no sequences found in file "<<infile<<"\n"; exit(1);}
369 // Set name, longname, fam
370 if (!*name) // longname, name and family were not set by '#...' line yet -> extract from first sequence
373 // strtr(sname[kfirst],"~"," "); // 'transpose': replaces the tilde with a blanc everywhere in sname[kfirst]
374 strncpy(longname,sname[kfirst],DESCLEN-1); // longname is name of first sequence
375 longname[DESCLEN-1]='\0';
376 strncpy(name,sname[kfirst],NAMELEN-1); // Shortname is first word of longname...
377 name[NAMELEN-1]='\0';
378 ptr = strcut(name); // ...until first white-space character
379 if (ptr && islower(ptr[0]) && ptr[1]=='.' && isdigit(ptr[2])) //Scop family code present as second word?
381 lwrstr(name); // Transform upper case to lower case
382 strcut(ptr); // Non-white-space characters until next white-space character..
383 strcpy(fam,ptr); // ...are the SCOP familiy code
385 else if (name[0]=='P' && name[1]=='F' && isdigit(name[2]) && isdigit(name[3]) ) //Pfam code
387 strcpy(fam,name); // set family name = Pfam code
393 delete[] cur_seq; cur_seq = NULL;
395 // Checking for warning messages
397 if (v>=2) cout<<"Read "<<infile<<" with "<<N_in<<" sequences\n";
398 if (v>=3) cout<<"Query sequence for alignment has number "<<kfirst<<" (0 is first)\n";
403 * At this point GetSeqsFromHMM() slots in, however,
404 * only needed in hhbliys.C, so will skip it for moment, MR1
408 /////////////////////////////////////////////////////////////////////////////
410 * @brief Convert ASCII in seq[k][l] to int (0-20) in X[k][i],
411 * throw out all insert states, record their number in I[k][i]
412 * and store sequences to be displayed in seq[k] */
413 /////////////////////////////////////////////////////////////////////////////
415 Alignment::Compress(const char infile[])
417 int i; // Index for match state (first=1)
418 int l; // Postion in alignment incl. gaps (first=1)
419 int k; // Index for sequences (first=0)
420 int a; // amino acid index
422 int unequal_lengths=0; /* k: seq k doesn't have same number
423 of match states as seq 0 => WARNING */
424 /* points to next character in seq[k] to be written */
425 /*static short unsigned int h[MAXSEQ];*/
426 /*short*/ unsigned int *h = NULL; /* short may lead to overflow for long alignments, FS, r235 -> r236 */
428 h = new /*short*/ unsigned int[N_in+2]; /* short -> overflow, FS, r235 -> r236 */
429 float *percent_gaps = NULL; /* FS, 2010-Nov */
430 char *match_state = NULL; /* FS, 2010-Nov */
434 for (k=0;k<N_in; k++)
440 cout<<"Using match state assignment by capital letters (a2m format)\n";
441 else if (par.M==2) cout<<"Using percentage-rule match state assignment\n";
442 else if (par.M==3) cout<<"Using residues of first sequence as match states\n";
445 // Create matrices X and I with amino acids represented by integer numbers
449 /////////////////////////////////////////////////////////////////////////
450 /* a2m/a3m format: match states capital case,
451 inserts lower case, delete states '-', inserted gaps '.'
452 The confidence values for ss prediction are interpreted as follows:
453 0-9:match states(!) '-' :match state '.':insert */
457 // Warn if alignment is ment to be -M first or -M NN instead of A2M/A3M
458 if (v>=2 && strchr(seq[kfirst],'-') ) // Seed/query sequence contains a gap ...
460 for (k=1; k<N_in; k++)
461 if (strpbrk(seq[k],"abcdefghiklmnpqrstuvwxyz.")) break;
462 if (k==N_in) // ... but alignment contains no lower case residue
463 printf("WARNING: input alignment %s looks like aligned FASTA instead of A2M/A3M format. Consider using '-M first' or '-M 50'\n",infile);
466 // Remove '.' characters from seq[k]
467 for(k=0; k<N_in; k++)
469 char* ptrS=seq[k]; // pointer to source: character in seq[k]
470 char* ptrD=seq[k]; // pointer to destination: seq[k]
471 while(1) // omit '.' symbols
473 if (*ptrS!='.') {*ptrD=*ptrS; ptrD++;} //leave out '.' symbols
478 L=/*MAXRES*/par.maxResLen-2; // needed because L=imin(L,i)
479 for (k=0; k<N_in; k++)
481 i=1; l=1; // start at i=1, not i=0!
482 if (keep[k]) //skip >ss_dssp, >ss_pred, >ss_conf, >aa_... sequences
484 while((c=seq[k][l++])) // assign residue to c at same time
486 if (c>='a' && c<='z') I[k][i-1]++;//insert state = lower case character
487 else if (c!='.') //match state = upper case character
495 else if (k==kss_dssp || k==kss_pred) // does alignment contain sequence of secondary structure states?
497 while((c=seq[k][l++])) // assign residue to c at same time
498 if (c!='.' && !(c>='a' && c<='z')) X[k][i++]=ss2i(c); //match state = upper case character
500 else if (k==ksa_dssp) // does alignment contain sequence of prediction confidence values?
502 while((c=seq[k][l++])) // assign residue to c at same time
503 if (c!='.' && !(c>='a' && c<='z')) X[k][i++]=sa2i(c); //match state = upper case character
505 else if (k==kss_conf) // does alignment contain sequence of prediction confidence values?
507 while((c=seq[k][l++])) // assign residue to c at same time
508 if (c!='.') X[k][i++]=cf2i(c); //match state = 0-9 or '-'
510 else if (k==kfirst) // does alignment contain sequence of prediction confidence values?
512 while((c=seq[k][l++])) // assign residue to c at same time
522 if (L!=i && L!=/*MAXRES*/par.maxResLen-2 && !unequal_lengths) unequal_lengths=k; //sequences have different lengths
525 if (unequal_lengths) break;
527 //Replace GAP with ENDGAP for all end gaps /* MR1 */
528 for (k=0; k<N_in; ++k)
530 if (!keep[k]) continue;
531 for (i=1; i<=L && X[k][i]==GAP; i++) X[k][i]=ENDGAP; /* MR1: NOTE i++ <- ++i */
532 for (i=L; i>=1 && X[k][i]==GAP; i--) X[k][i]=ENDGAP; /* MR1 */
535 for (i=1; i<=L; i++) this->l[i]=i; //assign column indices to match states
538 cout<<"\nError: Alignment in "<<infile<<" contains no match states. Consider using -M first or -M <int> option"<<endl;
542 if (L==/*MAXRES*/par.maxResLen-2 && v>=2)
544 printf("WARNING: Number of match columns too large. Only first %i match columns will be kept!\n",L);
547 if (v>=2) cout<<"Alignment in "<<infile<<" contains "<<L<<" match states\n";
550 /////////////////////////////////////////////////////////////////////////
551 // gap-rule assignment of match states
553 int nl[NAA+2]; //nl[a] = number of seq's with amino acid a at position l
554 /* Note: allocating statically is fine most of the time
555 but when the sequences/profiles get really long
556 we might run out of memory, so must really do it dynamically.
557 had to move declaration of float *percent_gaps out of switch()
559 //float percent_gaps[MAXCOL]; //percentage of gaps in column k (with weighted sequences)
560 percent_gaps = new float[par.maxColCnt];
562 //determine number of columns L in alignment
563 L=strlen(seq[kfirst])-1;
565 // Conversion to integer representation, checking for unequal lengths and initialization
566 if (nres==NULL) nres=new int[N_in];
569 #pragma omp parallel for schedule(static), private(l)
571 for (k=0; k<N_in; k++)
573 if (!keep[k]) continue;
578 X[k][l]=aa2i(seq[k][l]);
579 if (X[k][l]<NAA) nr++;
582 if (seq[k][L+1]!='\0' && !unequal_lengths) unequal_lengths=k;
584 if (unequal_lengths) break;
586 // Quick and dirty calculation of the weight per sequence wg[k]
587 for (l=1; l<=L; l++) // for all positions l in alignment
589 int naa=0; //number of different amino acids
590 for (a=0; a<20; a++) nl[a]=0;
591 for (k=0; k<N_in; k++) if (keep[k]) nl[ (int)X[k][l]]++;
592 for (a=0; a<20; a++) if(nl[a]) naa++;
593 if (!naa) naa=1; //naa=0 when column consists of only gaps and Xs (=ANY)
596 #pragma omp parallel for schedule(static)
598 for (k=0; k<N_in; k++)
599 if (keep[k] && (X[k][l]<20) )
601 //wg[k]+=1.0/float(nl[ (int)X[k][l]]*naa*nres[k]+30.0); /* original version */
602 wg[k] += 1.0/float(nl[ (int)X[k][l]]*naa*(nres[k]+30.0)); /* MR1 */
603 // wg[k] += 1.0/float(nl[ (int)X[k][l]]*(nres[k]+30.0)); /* MR1 commented out */
604 // wg[k] += (naa-1.0)/float(nl[ (int)X[k][l]]*(nres[k]+30.0)); /* MR1 commented out */
608 //Replace GAP with ENDGAP for all end gaps
609 for (k=0; k<N_in; ++k)
611 if (!keep[k]) continue;
612 for (i=1; i<=L && X[k][i]==GAP; i++) X[k][i]=ENDGAP; /* MR1: NOTE i++ <- ++i */
613 for (i=L; i>=1 && X[k][i]==GAP; i--) X[k][i]=ENDGAP; /* MR1 */
616 // Add up percentage of gaps
619 #pragma omp parallel for schedule(static) private(k)
625 for (k=0; k< N_in; k++){
627 if ( X[k][l]<GAP) res+=wg[k]; /* MR1, AA or ANY, changed from <ANY */
628 else if ( X[k][l] != ENDGAP) gap+=wg[k]; /* MR1, else: GAP. ENDGAPs are ignored for counting percentage */
631 percent_gaps[l]=100.*gap/(res+gap);
632 if (v>=4) cout<<"percent gaps["<<l<<"]="<<percent_gaps[l]<<" first seq:"<<seq[0][l]<<"\n";
635 /* Insert states 'bloat' the HMM,
636 throwing them out 'slims' down the HMM.
637 A slimmer HMM takes less time to construct.
638 However, the marriage of Clustal and Hhalign
639 is particularly sensitive to residues
640 at the very end of the profile; these I call
641 'telomeres'. Telomeres must not be shed when
642 throwing out insert states, for the telomeres
643 we set the match threshold to 100%.
646 #define TELOMERE_LOGIC 1
647 #define TELOMERE_DYNAMIC 0
649 #define ALWAYS_ACCEPT 101.0 /* do NOT change this parameter, must be >=100,
650 make slightly bigger than 100% -- to be sure to be sure */
651 #define DEFAULT_MGAPS 100.0 /* Soeding's default is 50, omega default prior to telomere logic was 100
652 FIXME: this used to be par.Mgaps,
653 in a later version re-introduce par.Mgaps to keep this value flexible */
654 #define TELOMER_LENGTH 10 /* this parameter must be > 0 (unless DEFAULT_MGAPS=100),
655 if it is too big (L/2) then telomere logic has no effect,
656 don't think it should be changed (much) */
657 #define TELOMER_FRACTION 0.10
658 //#define HMM_MIN_LENGTH 0.923
659 #define HMM_MIN_LENGTH 0.950
660 #define FORTRAN_OFFSET 1
661 double dDefaultMgaps;
662 dDefaultMgaps = DEFAULT_MGAPS;
664 #if TELOMERE_LOGIC /* turn telomere logic on (1) or off (0) */
667 #if TELOMERE_DYNAMIC /* keep telomere length 'dynamic' */
668 iTelomereLength = TELOMER_LENGTH > (int)(L*TELOMER_FRACTION) ? TELOMER_LENGTH : (int)(L*TELOMER_FRACTION);
670 iTelomereLength = TELOMER_LENGTH;
671 #endif /* this was dynamic telomere */
672 #endif /* this was telomere logic */
674 /* if HMMs get too small (much smaller than profile length L)
675 then one is liable to get a back-tracking error.
676 So we should ensure that the DEFAULT_MGAPS parameter does NOT
677 shrink the HMM too much.
678 take percentage-gap vector, sort it, and fix dDefaultMgaps,
679 such that at least (HMM_MIN_LENGTH)*(L) are left
681 #if MGAP_LOGIC /* try to adapt Mgaps to size of final HMM */
683 float *pfPercentGaps = NULL;
684 if (NULL == (pfPercentGaps = (float *)malloc((L+1)*sizeof(float)))){
685 printf("%s:%s:%d: could not malloc %d float for sorted percent-gaps\n",
686 __FUNCTION__, __FILE__, __LINE__, L+1);
687 dDefaultMgaps = DEFAULT_MGAPS;
690 for (l = 0; l < L; l++) {
691 pfPercentGaps[l] = percent_gaps[l+FORTRAN_OFFSET];
693 qsort(pfPercentGaps, L, sizeof(float), CompFltAsc);
695 dDefaultMgaps = pfPercentGaps[(int)(HMM_MIN_LENGTH*L)];
696 if (dDefaultMgaps < DEFAULT_MGAPS){
697 //printf("Mgaps = %f <- %f\n", DEFAULT_MGAPS, dDefaultMgaps);
698 dDefaultMgaps = DEFAULT_MGAPS;
701 //printf("Mgaps = %f\n", dDefaultMgaps);
704 free(pfPercentGaps); pfPercentGaps = NULL;
707 #endif /* tried to adapt Mgaps to size of final HMM */
709 // Throw out insert states and keep only match states
711 for (k=0; k<N_in; k++) {h[k]=1; seq[k][0]='-';}
715 float fMgaps = ALWAYS_ACCEPT;
716 if ( (l < iTelomereLength) || (L-l < iTelomereLength) ){
717 /* residue is in telomere, always retain this position */
718 fMgaps = ALWAYS_ACCEPT;
721 /* FIXME: would like to put a transition phase in here,
722 where the Mgap value gradually goes down from 100 to DEFAULT_MGAPS,
723 however, may not be necessary and will make code more clunky */
726 /* position is in centre of sequence,
727 retain position if less than DEFAULT_MGAPS% gaps at this position,
728 for example, if DEFAULT_MGAPS=30 throw out if more than 30% gap.
729 conversely, if DEFAULT_MGAPS=100 throw out if more than 100% gaps,
730 which can never happen, so always retain */
731 fMgaps = dDefaultMgaps;
733 if (percent_gaps[l] <= fMgaps)
734 #else /* this was telomere logic */
735 if (percent_gaps[l]<=float(par.Mgaps))
736 #endif /* this was Soeding default */
738 if (i>=/*MAXRES*/par.maxResLen-2) {
740 printf("WARNING: Number of match columns too large. Only first %i match columns will be kept!\n",i);
747 #pragma omp parallel for schedule(static)
749 for (k=0; k<N_in; k++)
753 seq[k][h[k]++]=MatchChr(seq[k][l]);
757 else if (k==kss_dssp || k==kss_pred)
759 seq[k][h[k]++]=MatchChr(seq[k][l]);
760 X[k][i]=ss2i(seq[k][l]);
762 else if (k==ksa_dssp)
764 seq[k][h[k]++]=MatchChr(seq[k][l]);
765 X[k][i]=sa2i(seq[k][l]);
767 else if (k==kss_conf)
769 seq[k][h[k]++]=seq[k][l];
770 X[k][i]=cf2i(seq[k][l]);
776 for (k=0; k<N_in; k++)
777 if (keep[k] && X[k][l]<GAP)
780 seq[k][h[k]++]=InsertChr(seq[k][l]);
784 for (k=0; k<N_in; k++) seq[k][h[k]]='\0';
786 //printf("%d\t%d\t%d\tN/L/M\n", N_in, L, i); /* -------- FIXME */
788 if (v>=2) cout<<"Alignment in "<<infile<<" contains "<<L<<" columns and "<<i<<" match states\n";
789 L = i; //Number of match states
791 delete[] percent_gaps; percent_gaps = NULL;
795 ////////////////////////////////////////////////////////////////////////
796 // Using residues of first sequence as match states
798 /* Note: allocating statically is fine most of the time
799 but when the sequences/profiles get really long
800 we might run out of memory, so must really do it dynamically.
801 had to move declaration of float *percent_gaps out of switch()
803 //char match_state[MAXCOL]; //1: column assigned to match state 0: insert state
804 match_state = new char[par.maxColCnt];
806 // Determine number of columns L in alignment
808 if (v>=3) printf("Length of first seq = %i\n",L);
809 // Check for sequences with unequal lengths
810 for (k=1; k<N_in; k++)
811 if (int(strlen(seq[k]+1))!=L) {unequal_lengths=k; break;}
812 if (unequal_lengths) break;
814 // Determine match states: seq kfirst has residue at pos l -> match state
816 if (isalpha(seq[kfirst][l])) match_state[l]=1; else match_state[l]=0;
817 // Throw out insert states and keep only match states
818 for (k=0; k<N_in; k++) {h[k]=1; seq[k][0]='-';}
822 if (match_state[l]) // does sequence 0 have residue at position l?
824 if (i>=/*MAXRES*/par.maxResLen-2) {
826 printf("WARNING: Number of match columns too large. Only first %i match columns will be kept!\n",i);
831 for (k=0; k<N_in; k++)
835 seq[k][h[k]++]=MatchChr(seq[k][l]);
836 X[k][i]=aa2i(seq[k][l]);
839 else if (k==kss_dssp || k==kss_pred)
841 seq[k][h[k]++]=MatchChr(seq[k][l]);
842 X[k][i]=ss2i(seq[k][l]);
844 else if (k==ksa_dssp)
846 seq[k][h[k]++]=MatchChr(seq[k][l]);
847 X[k][i]=sa2i(seq[k][l]);
849 else if (k==kss_conf)
851 seq[k][h[k]++]=seq[k][l];
852 X[k][i]=cf2i(seq[k][l]);
858 for (k=0; k<N_in; k++)
859 if (keep[k] && aa2i(seq[k][l])<GAP)
862 seq[k][h[k]++]=InsertChr(seq[k][l]);
866 for (k=0; k<N_in; k++) seq[k][h[k]]='\0';
868 //Replace GAP with ENDGAP for all end gaps /* MR1 */
869 for (k=0; k<N_in; ++k)
871 if (!keep[k]) continue;
872 for (i=1; i<=L && X[k][i]==GAP; i++) X[k][i]=ENDGAP; /* MR1, note i++ <- ++i */
873 for (i=L; i>=1 && X[k][i]==GAP; i--) X[k][i]=ENDGAP; /* MR1 */
876 if (v>=2) cout<<"Alignment in "<<infile<<" contains "<<L<<" columns and "<<i<<" match states\n";
877 L = i; //Number of match states
879 delete[] match_state; match_state = NULL;
883 ///////////////////////////////////////////////////////////////////////////
889 strcut(sname[unequal_lengths]);
890 cerr<<endl<<"Error: sequences in "<<infile<<" do not all have the same number of columns, \ne.g. first sequence and sequence "<<sname[unequal_lengths]<<".\n";
891 if(par.M==1) cerr<<".\nCheck input format for '-M a2m' option and consider using '-M first' or '-M 50'\n";
895 // Avert user about -cons option?
896 if (v>=2 && !par.cons)
899 if (X[kfirst][i]==GAP)
901 printf("NOTE: Use the '-cons' option to calculate a consensus sequence as first sequence of the alignment.\n");
906 //Replace GAP with ENDGAP for all end gaps
907 for (k=0; k<N_in; k++)
909 if (!keep[k]) continue;
910 for (i=1; i<=L && X[k][i]==GAP; i++) X[k][i]=ENDGAP;
911 for (i=L; i>=1 && X[k][i]==GAP; i--) X[k][i]=ENDGAP;
916 for (k=0; k<N_in; k++)
918 if (!display[k]) continue;
919 cout<<">"<<sname[k]<<"\n";
920 if (k==kss_dssp || k==kss_pred) {for (i=1; i<=L; i++) cout<<char(i2ss(X[k][i]));}
921 else if (k==kss_conf) {for (i=1; i<=L; i++) cout<<char(i2cf(X[k][i]));}
922 else if (k==ksa_dssp) {for (i=1; i<=L; i++) cout<<char(i2sa(X[k][i]));}
925 for (i=1; i<=L; i++) cout<<char(i2aa(X[k][i]));
928 if (I[k][i]==0) cout<<"-"; else if (I[k][i]>9) cout<<"X"; else cout<<I[k][i];
933 delete[](h); h = NULL;
938 * @brief Remove sequences with seq. identity larger than seqid percent
939 *(remove the shorter of two) or coverage<cov_thr
941 * FIXME: originally max_seqid is a variable that is the cutoff
942 * above which sequences are thrown out. We want to throw out sequences
943 * when building the HMM but not for display, there we want to keep all.
944 * This should be really easy, but there is some hidden stuff going on
945 * in this function, so I did a minimal-invasive change and just stuck
946 * (effectively) a hard-wired 100 instead of the variable.
947 * At a later stage we should get rid of this function alltogether
948 * as it does gobble up some time (and is quadratic in noof sequences, I think)
951 ////////////////////////////////////////////////////////////////////////////
955 Alignment::FilterForDisplay(int max_seqid, int coverage, int qid, float qsc, int N)
959 * by just returning n_display and not doing anything
960 * I think we display everything and not do any work for it
962 return n_display; /* FS, 2010-10-04*/
965 if (par.mark) return n_display;
966 char *dummy = new char[N_in+1];
970 if (kss_dssp>=0) display[kss_dssp]=KEEP_NOT;
971 if (ksa_dssp>=0) display[ksa_dssp]=KEEP_NOT;
972 if (kss_pred>=0) display[kss_pred]=KEEP_NOT;
973 if (kss_conf>=0) display[kss_conf]=KEEP_NOT;
974 for (seqid=imin(10,max_seqid); n_display<N && seqid<=max_seqid; seqid++)
976 for (int k=0; k<N_in; k++) dummy[k]=display[k];
977 n_display = Filter2(dummy,coverage,qid,qsc,20,seqid,0);
978 // printf("Seqid=%3i n_display=%4i\n",seqid,n_display);
982 for (int k=0; k<N_in; k++) dummy[k]=display[k];
983 n_display = Filter2(dummy,coverage,qid,qsc,20,--(--seqid),0);
986 for (int k=0; k<N_in; k++) display[k]=dummy[k];
987 if (kss_dssp>=0) {display[kss_dssp]=KEEP_CONDITIONALLY; n_display++;}
988 if (ksa_dssp>=0) {display[ksa_dssp]=KEEP_CONDITIONALLY; n_display++;}
989 if (kss_pred>=0) {display[kss_pred]=KEEP_CONDITIONALLY; n_display++;}
990 if (kss_conf>=0) {display[kss_conf]=KEEP_CONDITIONALLY; n_display++;}
991 delete[] dummy; dummy = NULL;
995 /////////////////////////////////////////////////////////////////////////////////////
996 // Remove sequences with seq. identity larger than seqid percent (remove the shorter of two) or coverage<cov_thr
997 /////////////////////////////////////////////////////////////////////////////////////
998 inline int Alignment::Filter(int max_seqid, int coverage, int qid, float qsc, int N)
1000 return Filter2(keep,coverage,qid,qsc,20,max_seqid,N);
1003 /////////////////////////////////////////////////////////////////////////////
1005 * @brief Select set of representative sequences in the multiple sequence alignment
1008 * Remove sequences with coverage of query less than "coverage" percent
1009 * Remove sequences with sequence identity to query of less than "qid" percent
1010 * If Ndiff==0, remove sequences with seq. identity larger than seqid2(=max_seqid) percent
1011 * If Ndiff>0, remove sequences with minimum-sequence-identity filter of between seqid1
1012 * and seqid2 (%), where the minimum seqid threshold is determined such that,
1013 * in all column blocks of at least WMIN=25 residues, at least Ndiff sequences are left.
1014 * This ensures that in multi-domain proteins sequences covering one domain are not
1015 * removed completely because sequences covering other domains are more diverse.
1017 * Allways the shorter of two compared sequences is removed (=> sort sequences by length first).
1018 * Please note: sequence identity of sequence x with y when filtering x is calculated as
1019 * number of residues in sequence x that are identical to an aligned residue in y / number of residues in x
1020 * Example: two sequences x and y are 100% identical in their overlapping region but one overlaps by 10% of its
1021 * length on the left and the other by 20% on the right. Then x has 10% seq.id with y and y has 20% seq.id. with x.
1023 //////////////////////////////////////////////////////////////////////////////
1025 Alignment::Filter2(char keep[], int coverage, int qid, float qsc, int seqid1, int seqid2, int Ndiff)
1027 // In the beginnning, keep[k] is 1 for all regular amino acid sequences and 0 for all others (ss_conf, ss_pred,...)
1028 // In the end, keep[k] will be 1 for all regular representative sequences kept in the alignment, 0 for all others
1029 char* in=new char[N_in+1]; // in[k]=1: seq k has been accepted; in[k]=0: seq k has not yet been accepted at current seqid
1030 char* inkk=new char[N_in+1]; // inkk[k]=1 iff in[ksort[k]]=1 else 0;
1031 int* Nmax=new int[L+2]; // position-dependent maximum-sequence-identity threshold for filtering /* MR1, used to be called idmax*/
1032 int* idmaxwin=new int[L+2]; // minimum value of idmax[i-WFIL,i+WFIL]
1033 int* seqid_prev=new int[N_in+1]; // maximum-sequence-identity threshold used in previous round of filtering (with lower seqid)
1034 int* N=new int[L+2]; // N[i] number of already accepted sequences at position i
1035 const int WFIL=25; // see previous line
1037 int diffNmax=Ndiff; // current maximum difference of Nmax[i] and Ndiff /* MR1 */
1038 int diffNmax_prev=0; // previous maximum difference of Nmax[i] and Ndiff /* MR1 */
1040 int seqid; // current maximum value for the position-dependent maximum-sequence-identity thresholds in idmax[]
1041 int seqid_step=0; // previous increment of seqid /* MR1 */
1043 float diff_min_frac; // minimum fraction of differing positions between sequence j and k needed to accept sequence k
1044 float qdiff_max_frac=0.9999-0.01*qid; // maximum allowable number of residues different from query sequence
1045 int diff; // number of differing positions between sequences j and k (counted so far)
1046 int diff_suff; // number of differing positions between sequences j and k that would be sufficient
1047 int qdiff_max; // maximum number of residues required to be different from query
1048 int cov_kj; // upper limit of number of positions where both sequence k and j have a residue
1049 int first_kj; // first non-gap position in sequence j AND k
1050 int last_kj; // last non-gap position in sequence j AND k
1051 int kk, jj; // indices for sequence from 1 to N_in
1052 int k, j; // kk=ksort[k], jj=ksort[j]
1053 int i; // counts residues
1054 int n; // number of sequences accepted so far
1057 for (n=k=0; k<N_in; k++) if (keep[k]==KEEP_ALWAYS) {in[k]=2/*KEEP_ALWAYS??*/; n++;} else in[k]=0;
1059 // Determine first[k], last[k]?
1062 first=new int[N_in];// first non-gap position in sequence k
1063 last =new int[N_in];// last non-gap position in sequence k
1064 for (k=0; k<N_in; k++) // do this for ALL sequences, not only those with in[k]==1 (since in[k] may be display[k])
1066 for (i=1; i<=L; i++) if (X[k][i]<NAA) break;
1068 for (i=L; i>=1; i--) if (X[k][i]<NAA) break;
1073 // Determine number of residues nres[k]?
1074 // KB: memory leak as sizeof(nres) just gives the size of an int pointer
1075 //if ( (nres==NULL) || (sizeof(nres)<N_in*sizeof(int)) )
1079 for (k=0; k<N_in; k++) // do this for ALL sequences, not only those with in[k]==1 (since in[k] may be display[k])
1082 for (i=first[k]; i<=last[k]; i++)
1083 if (X[k][i]<NAA) nr++;
1085 // printf("%20.20s nres=%3i first=%3i last=%3i\n",sname[k],nr,first[k],last[k]);
1089 // Sort sequences according to length; afterwards, nres[ksort[kk]] is sorted by size
1092 ksort=new int[N_in]; // never reuse alignment object for new alignment with more sequences
1093 for (k=0; k<N_in; k++) ksort[k]=k;
1094 QSortInt(nres,ksort,kfirst+1,N_in-1,-1); //Sort sequences after kfirst (query) in descending order
1096 for (kk=0; kk<N_in; kk++) inkk[kk]=in[ksort[kk]];
1098 // Initialize N[i], idmax[i], idprev[i]
1099 for (i=1; i<first[kfirst]; i++) N[i]=0;
1100 for (i=first[kfirst]; i<=last[kfirst]; i++) N[i]=1;
1101 for (i=last[kfirst]+1; i<=L; i++) N[i]=0;
1102 //for (i=1; i<=L; i++) {idmax[i]=seqid1; idmaxwin[i]=-1;}
1103 for (i=1; i<=L; ++i) {Nmax[i]=0; idmaxwin[i]=-1;} /* MR1 */
1104 for (k=0; k<N_in; k++) seqid_prev[k]=-1;
1105 if (Ndiff<=0 || Ndiff>=N_in) {seqid1=seqid2; Ndiff=N_in; diffNmax=Ndiff;}
1107 // Check coverage and sim-to-query criteria for each sequence k
1108 for (k=0; k<N_in; k++)
1110 if (keep[k]==KEEP_NOT || keep[k]==KEEP_ALWAYS) continue; // seq k not regular sequence OR is marked sequence
1111 if (100*nres[k]<coverage*L) {keep[k]=KEEP_NOT; continue;} // coverage too low? => reject once and for all
1115 // Check if score-per-column with query is at least qsc
1118 float qsc_min = qsc*nres[k]; // minimum total score of seq k with query
1120 int gapq=0, gapk=0; // number of consecutive gaps in query or k'th sequence at position i
1121 for (int i=first[k]; i<=last[k]; i++)
1126 if (X[kfirst][i]<20)
1129 qsc_sum += S[(int)X[kfirst][i]][(int)X[k][i]];
1131 else if (gapq++) qsc_sum-=PLTY_GAPEXTD; else qsc_sum-=PLTY_GAPOPEN;
1133 else if (X[kfirst][i]<20)
1136 if (gapk++) qsc_sum-=PLTY_GAPEXTD; else qsc_sum-=PLTY_GAPOPEN;
1139 // printf("k=%3i qsc=%6.2f\n",k,qsc_sum);
1140 if (qsc_sum<qsc_min) {keep[k]=KEEP_NOT; continue;} // too different from query? => reject once and for all
1143 //Check if sequence similarity with query at least qid?
1144 if (qdiff_max_frac<0.999)
1146 qdiff_max=int(qdiff_max_frac*nres[k]+0.9999);
1147 // printf("k=%-4i nres=%-4i qdiff_max=%-4i first=%-4i last=%-4i",k,nres[k],qdiff_max,first[k],last[k]);
1149 for (int i=first[k]; i<=last[k]; i++)
1150 // enough different residues to reject based on minimum qid with query? => break
1151 if (X[k][i]<20 && X[k][i]!=X[kfirst][i] && ++diff>=qdiff_max) break;
1152 // printf(" diff=%4i\n",diff);
1153 if (diff>=qdiff_max) {keep[k]=KEEP_NOT; continue;} // too different from query? => reject once and for all
1155 // printf(" qsc=%6.2f qid=%6.2f \n",qsc_sum/nres[k],100.0*(1.0-(float)(diff)/nres[k]));
1160 for (n=k=0; k<N_in; k++) if (keep[k]>KEEP_NOT) n++;
1164 // Successively increment idmax[i] at positons where N[i]<Ndiff
1165 //for (seqid=seqid1; seqid<=seqid2; seqid+=1+(seqid>=50)) /* MR1 */
1167 while (seqid<=seqid2)
1171 for (i=1; i<=L; i++) if (N[i]<Ndiff) idmax[i]=seqid;
1173 // Update idmaxwin[i] as minimum of idmax[i-WFIL,i+WFIL]. If idmaxwin[] has not changed then stop
1175 for (i=1; i<=L; i++)
1177 int idmax_min=seqid2;
1178 for (j=imax(1,imin(L-2*WFIL+1,i-WFIL)); j<=imin(L,imax(2*WFIL,i+WFIL)); j++)
1179 if (idmax[j]<idmax_min) idmax_min=idmax[j];
1180 if (idmax_min>idmaxwin[i]) stop=0; // idmaxwin[i] has changed => do not stop
1181 idmaxwin[i]=idmax_min;
1186 diffNmax_prev = diffNmax;
1188 for (i=1; i<=L; ++i)
1191 for (j=imax(1,imin(L-2*WFIL+1,i-WFIL)); j<=imin(L,imax(2*WFIL,i+WFIL)); ++j)
1192 if (N[j]>max) max=N[j];
1193 if (Nmax[i]<max) Nmax[i]=max;
1198 if (diffNmax<Ndiff-Nmax[i]) diffNmax=Ndiff-Nmax[i];
1203 //printf("seqid=%3i diffNmax_prev= %-4i diffNmax= %-4i n=%-5i N_in-N_ss=%-5i\n",seqid,diffNmax_prev,diffNmax,n,N_in-N_ss);
1208 // printf("idmax ");
1209 // for (i=1; i<=L; i++) printf("%2i ",idmax[i]);
1211 // printf("idmaxwin ");
1212 // for (i=1; i<=L; i++) printf("%2i ",idmaxwin[i]);
1215 // for (i=1; i<=L; i++) printf("%2i ",N[i]);
1218 // Loop over all candidate sequences kk (-> k)
1220 //#ifdef HAVE_OPENMP
1221 #pragma omp parallel for schedule(static) private(k, i, diff_min_frac, jj, j, first_kj, last_kj, cov_kj, diff_suff, diff)
1223 for (kk=0; kk<N_in; kk++)
1225 if (inkk[kk]) continue; // seq k already accepted
1227 if (!keep[k]) continue; // seq k is not regular aa sequence or already suppressed by coverage or qid criterion
1228 if (keep[k]==KEEP_ALWAYS) {inkk[kk]=2; continue;} // accept all marked sequences (no n++, since this has been done already)
1230 // Calculate max-seq-id threshold seqidk for sequence k (as maximum over idmaxwin[i])
1231 // if (seqid>=100) {in[k]=inkk[kk]=1; n++; continue;}
1235 //#ifdef HAVE_OPENMP
1241 float seqidk=seqid1;
1242 for (i=first[k]; i<=last[k]; i++)
1243 if (idmaxwin[i]>seqidk) seqidk=idmaxwin[i];
1244 if (seqid==seqid_prev[k]) continue; // sequence has already been rejected at this seqid threshold => reject this time
1245 seqid_prev[k]=seqid;
1246 diff_min_frac =0.9999-0.01*seqidk; // min fraction of differing positions between sequence j and k needed to accept sequence k
1248 // Loop over already accepted sequences
1249 for (jj=0; jj<kk; jj++)
1251 if (!inkk[jj]) continue;
1253 first_kj=imax(first[k],first[j]);
1254 last_kj =imin(last[k],last[j]);
1255 cov_kj = last_kj-first_kj+1;
1256 diff_suff=int(diff_min_frac*imin(nres[k],cov_kj)+0.999); // nres[j]>nres[k] anyway because of sorting /* MR1 0.999 */
1258 for (int i=first_kj; i<=last_kj; i++)
1260 // enough different residues to accept? => break
1261 if (X[k][i]>=NAA || X[j][i]>=NAA)
1264 if (X[k][i]!=X[j][i] && ++diff>=diff_suff) break; // accept (k,j)
1267 // printf("%20.20s with %20.20s: diff=%i diff_min_frac*cov_kj=%f diff_suff=%i nres=%i cov_kj=%i\n",sname[k],sname[j],diff,diff_min_frac*cov_kj,diff_suff,nres[k],cov_kj);
1268 // printf("%s\n%s\n\n",seq[k],seq[j]);
1270 //if (float(diff)<fmin(diff_min_frac*cov_kj,diff_suff)) break; //similarity > acceptace threshold? Reject! /* MR1 */
1271 if (diff<diff_suff && float(diff)<=diff_min_frac*cov_kj) break; //dissimilarity < acceptace threshold? Reject! /* MR1 */
1275 if (jj>=kk) // did loop reach end? => accept k. Otherwise reject k (the shorter of the two)
1279 //#ifdef HAVE_OPENMP
1283 for (i=first[k]; i<=last[k]; i++) {
1285 //#ifdef HAVE_OPENMP
1288 N[i]++; // update number of sequences at position i
1290 // printf("%i %20.20s accepted\n",k,sname[k]);
1294 // printf("%20.20s rejected: too similar with seq %20.20s diff=%i diff_min_frac*cov_kj=%f diff_suff=%i nres=%i cov_kj=%i\n",sname[k],sname[j],diff,diff_min_frac*cov_kj,diff_suff,nres[k],cov_kj);
1295 // printf("%s\n%s\n\n",seq[k],seq[j]);
1298 } // End Loop over all candidate sequences kk
1302 // printf("seqid_prev[k]= \n");
1303 // for (k=0; k<N_in; k++) printf("%2i ",seqid_prev[k]);
1306 // Increment seqid /* MR1 */
1307 seqid_step = imax(1,imin(5,diffNmax/(diffNmax_prev-diffNmax+1)*seqid_step/2));
1308 seqid += seqid_step;
1310 } // End Loop over seqid
1314 printf("%i out of %i sequences passed filter (",n,N_in-N_ss);
1316 printf("%i%% min coverage, ",coverage);
1318 printf("%i%% min sequence identity to query, ",qid);
1320 printf("%.2f bits min score per column to query, ",qsc);
1321 if (Ndiff<N_in && Ndiff>0)
1322 printf("up to %i%% position-dependent max pairwise sequence identity)\n",seqid);
1324 printf("%i%% max pairwise sequence identity)\n",seqid1);
1327 for (k=0; k<N_in; k++) keep[k]=in[k];
1328 delete[] in; in = NULL;
1329 delete[] inkk; inkk = NULL;
1330 //delete[] idmax; idmax = NULL;
1331 delete[] Nmax; /* MR1 */
1332 delete[] idmaxwin; idmaxwin = NULL;
1333 delete[] seqid_prev; seqid_prev = NULL;
1334 delete[] N; N = NULL;
1336 printf("%s:%s:%d: sequences accepted = %d/%d\n", __FUNCTION__, __FILE__, __LINE__, n, N_in-N_ss);
1343 /* MR1: the Alignment::HomologyFilter is no longer needed in hhalign-stand-alone */
1344 /////////////////////////////////////////////////////////////////////////////
1346 * @brief Filter for min score per column coresc with core query profile,
1347 * defined by coverage_core and qsc_core
1349 /////////////////////////////////////////////////////////////////////////////
1351 Alignment::HomologyFilter(int coverage_core, float qsc_core, float coresc)
1353 const int seqid_core=90; //maximum sequence identity in core alignment
1354 const int qid_core=0;
1355 const int Ndiff_core=0;
1358 char* coreseq=new char[N_in]; // coreseq[k]=1 if sequence belongs to core of alignment (i.e. it is very similar to query)
1359 for (int k=0; k<N_in; k++) coreseq[k]=keep[k]; // Copy keep[] into coreseq[]
1361 // Remove sequences with seq. identity larger than seqid percent (remove the shorter of two)
1363 n = Filter2(coreseq,coverage_core,qid_core,qsc_core,seqid_core,seqid_core,Ndiff_core);
1367 printf("%i out of %i core alignment sequences passed filter (",n,N_in-N_ss);
1368 if (par.coverage_core)
1369 printf("%i%% min coverage, ",coverage_core);
1371 printf("%i%% min sequence identity to query, ",qid_core);
1373 printf("%.2f bits min score per column to query, ",qsc_core);
1374 printf("%i%% max pairwise sequence identity)\n",seqid_core);
1377 // Calculate bare AA frequencies and transition probabilities -> qcore.f[i][a], qcore.tr[i][a]
1378 FrequenciesAndTransitions(qcore,coreseq);
1380 // Add transition pseudocounts to query -> q.p[i][a] (gapd=1.0, gape=0.333, gapf=gapg=1.0, gaph=gapi=1.0, gapb=1.0
1381 qcore.AddTransitionPseudocounts(1.0,0.333,1.0,1.0,1.0,1.0,1.0);
1383 // Generate an amino acid frequency matrix from f[i][a] with full pseudocount admixture (tau=1) -> g[i][a]
1384 qcore.PreparePseudocounts();
1386 // Add amino acid pseudocounts to query: qcore.p[i][a] = (1-tau)*f[i][a] + tau*g[i][a]
1387 qcore.AddAminoAcidPseudocounts(2,1.5,2.0,1.0); // pcm=2, pca=1.0, pcb=2.5, pcc=1.0
1389 // Filter out all sequences below min score per column with qcore
1390 n=FilterWithCoreHMM(keep, coresc, qcore);
1392 if (v>=2) cout<<n<<" out of "<<N_in-N_ss<<" sequences filtered by minimum score-per-column threshold of "<<qsc_core<<"\n";
1393 delete[] coreseq; coreseq = NULL;
1398 /////////////////////////////////////////////////////////////////////////////////////
1400 * @brief Filter out all sequences below a minimum score per column with profile qcore
1403 Alignment::FilterWithCoreHMM(char in[], float coresc, HMM& qcore)
1405 int k; // count sequences in alignment
1406 int i; // column in query alignment
1407 int a; // amino acid (0..19)
1408 int n=1; // number of sequences that passed filter
1409 float** logodds=new float*[L+1]; // log-odds ratios for HMM qcore
1410 char gap; // 1: previous state in seq k was a gap 0: previous state in seq k was an amino acid
1411 float score; // score of sequence k aligned with qcore
1413 for (i=1; i<=L; i++) logodds[i]=new(float[21]);
1415 // Determine first[k], last[k]?
1418 first=new int[N_in];// first non-gap position in sequence k
1419 last =new int[N_in];// last non-gap position in sequence k
1420 for (k=0; k<N_in; k++) // do this for ALL sequences, not only those with in[k]==1 (since in[k] may be display[k])
1422 for (i=1; i<=L; i++) if (X[k][i]<NAA) break;
1424 for (i=L; i>=1; i--) if (X[k][i]<NAA) break;
1429 // Determine number of residues nres[k]?
1433 for (k=0; k<N_in; k++) // do this for ALL sequences, not only those with in[k]==1 (since in[k] may be display[k])
1436 for (i=first[k]; i<=last[k]; i++)
1437 if (X[k][i]<NAA) nr++;
1439 // printf("%20.20s nres=%3i first=%3i last=%3i\n",sname[k],nr,f,l);
1443 // Precalculate the log-odds for qcore
1444 for (i=1; i<=L; i++)
1446 for (a=0; a<NAA; a++)
1447 logodds[i][a]=fast_log2(qcore.p[i][a]/pb[a]);
1448 logodds[i][ANY]=-0.5; // half a bit penalty for X
1450 // printf(" A R N D C Q E G H I L K M F P S T W Y V\n");
1451 // printf("%6i ",i);
1452 // for (a=0; a<20; ++a) fprintf(stdout,"%5.1f ",100*qcore.f[i][a]);
1455 // for (a=0; a<20; ++a) fprintf(stdout,"%5.1f ",100*qcore.g[i][a]);
1458 // for (a=0; a<20; ++a) fprintf(stdout,"%5.1f ",100*qcore.p[i][a]);
1461 // for (a=0; a<20; ++a) fprintf(stdout,"%5.1f ",100*pb[a]);
1464 // for (a=0; a<20; ++a) fprintf(stdout,"%5.2f ",fast_log2(qcore.p[i][a]/pb[a]));
1468 // Main loop: test all sequences k
1469 for (k=kfirst+1; k<N_in; k++)
1471 if (!in[k]) continue; // if in[k]==0 sequence k will be suppressed directly
1474 float score_prev=0.0;
1476 // Calculate score of sequence k with core HMM
1478 for (i=first[k]; i<=last[k]; i++)
1481 if (X[k][i]<=ANY) // current state is Match
1483 score_M=logodds[i][ (int)X[k][i]];
1484 score+=logodds[i][ (int)X[k][i]];
1485 if (gap) score+=qcore.tr[i][D2M]; else score+=qcore.tr[i][M2M];
1488 else if (X[k][i]==GAP) // current state is Delete (ignore ENDGAPs)
1490 if (gap) score+=qcore.tr[i][D2D]; else score+=qcore.tr[i][M2D];
1493 if (I[k][i]) score+=qcore.tr[i][M2I]+(I[k][i]-1)*qcore.tr[i][I2I]+qcore.tr[i][I2M];
1494 // if (k==2) printf("i=%3i %c:%c score_M=%6.2f score=%6.2f score_sum=%6.2f \n",i,i2aa(X[kfirst][i]),i2aa(X[k][i]),score_M,score-score_prev,score);
1498 printf("k=%3i score=%6.2f\n",k,score);
1499 if (score<nres[k]*coresc) in[k]=0; else n++;// reject sequence k?
1501 for (i=1; i<=L; i++){
1502 delete[] logodds[i]; logodds[i] = NULL;
1504 delete[] logodds; logodds = NULL;
1511 /////////////////////////////////////////////////////////////////////////////////////
1513 * @brief Filter alignment to given diversity/Neff
1516 Alignment::FilterNeff()
1520 const float TOLX=0.001;
1521 const float TOLY=0.02;
1523 for (int k=0; k<N_in; ++k) dummy[k]=keep[k];
1527 float y0=filter_by_qsc(x0,dummy);
1528 float y1=filter_by_qsc(x1,dummy);
1530 while (y0-par.Neff>0 && par.Neff-y1>0)
1532 x = x0 + (par.Neff-y0)*(x1-x0)/(y1-y0); // linear interpolation between (x0,y0) and (x1,y1)
1533 y = filter_by_qsc(x,dummy);
1534 if (v>=2) printf(" %3i x0=%6.3f -> %6.3f x=%6.3f -> %6.3f x1=%6.3f -> %6.3f \n",++i,x0,y0,x,y,x1,y1);
1535 if (y>par.Neff) {x0=x; y0=y;} else {x1=x; y1=y;}
1536 if (fabs(par.Neff-y)<TOLY || x1-x0<TOLX) break;
1540 if (y0>=par.Neff && y1<=par.Neff)
1542 // Write filtered alignment WITH insert states (lower case) to alignment file
1543 if (v>=2) printf("Found Neff=%6.3f at filter threshold qsc=%6.3f\n",y,x);
1547 printf("Diversity of unfiltered alignment %.2f is below target diversity %.2f. No alignment written\n",y0,par.Neff);
1552 float Alignment::filter_by_qsc(float qsc, char* dummy)
1555 for (int k=0; k<N_in; ++k) keep[k]=dummy[k];
1556 Filter2(keep,par.coverage,0,qsc,par.max_seqid+1,par.max_seqid,0);
1557 FrequenciesAndTransitions(q);
1558 // printf("qsc=%4.1f N_filtered=%-3i Neff=%6.3f\n",qsc,n,q.Neff_HMM);
1563 /////////////////////////////////////////////////////////////////////////////////////
1565 * @brief Calculate AA frequencies q.p[i][a] and transition probabilities q.tr[i][a] from alignment
1568 Alignment::FrequenciesAndTransitions(HMM& q, char* in)
1570 int k; // index of sequence
1571 int i; // position in alignment
1572 int a; // amino acid (0..19)
1573 int ni[NAA+3]; // number of times amino acid a occurs at position i
1574 int naa; // number of different amino acids
1577 cout<<"Calculating position-dependent weights on subalignments\n";
1579 if (in==NULL) in=keep; // what's this good for?
1583 for (k=0; k<N_in; k++) wg[k]=0.0; // initialized wg[k]
1584 // Calculate global weights
1585 for (i=1; i<=L; i++) // for all positions i in alignment
1587 for (a=0; a<20; a++) ni[a]=0;
1588 for (k=0; k<N_in; k++) if (in[k]) ni[ (int)X[k][i]]++;
1589 naa=0; for (a=0; a<20; a++) if(ni[a]) naa++;
1590 if (!naa) naa=1; //naa=0 when column consists of only gaps and Xs (=ANY)
1591 for (k=0; k<N_in; k++)
1592 if (in[k] && X[k][i]<20)
1593 wg[k] += 1.0/float(ni[ (int)X[k][i]]*naa*(nres[k]+30));
1594 // ensure that each residue of a short sequence contributes as much as a residue of a long sequence:
1595 // contribution is proportional to one over sequence length nres[k] plus 30.
1597 NormalizeTo1(wg,N_in);
1600 // Do pos-specific sequence weighting and calculate amino acid frequencies and transitions
1601 for (k=0; k<N_in; k++) X[k][0]=ENDGAP; // make sure that sequences ENTER subalignment j for j=1
1602 for (k=0; k<N_in; k++) X[k][L+1]=ENDGAP; // does it have an influence?
1605 //#ifdef HAVE_OPENMP
1608 #pragma omp parallel sections
1611 Amino_acid_frequencies_and_transitions_from_M_state(q,in); // use subalignments of seqs with residue in i
1613 Transitions_from_I_state(q,in); // use subalignments of seqs with insert in i
1615 Transitions_from_D_state(q,in); // use subalignments of seqs with delete in i. Must be last of these three calls if par.wg==1!
1620 #pragma omp parallel sections
1623 Amino_acid_frequencies_and_transitions_from_M_state(q,in); // use subalignments of seqs with residue in i
1625 Transitions_from_I_state(q,in); // use subalignments of seqs with insert in i
1627 Transitions_from_D_state(q,in); // use subalignments of seqs with delete in i. Must be last of these three calls if par.wg==1!
1630 Amino_acid_frequencies_and_transitions_from_M_state(q,in);
1631 Transitions_from_I_state(q,in);
1632 Transitions_from_D_state(q,in);
1635 else // N_filtered==1
1637 X[kfirst][0]=X[kfirst][L+1]=ANY; // (to avoid anallowed access within loop)
1639 for (i=0; i<=L+1; i++) // for all positions i in alignment
1642 q.Neff_I[i]=q.Neff_D[i]=0.0f;
1643 for (a=0; a<20; a++) q.f[i][a]=0.0;
1644 /* this is the crucial change that makes terminal-X work */
1645 //q.f[i][ (int)(X[kfirst][i]) ] = 1.0; /* MR1 */
1646 if (X[kfirst][i] < ANY) /* MR1 */
1647 q.f[i][(unsigned int) X[kfirst][i] ] = 1.0;
1649 for (a=0; a<20; ++a) q.f[i][a]=pb[a];
1651 q.tr[i][M2I]=-100000.0;
1652 q.tr[i][M2D]=-100000.0;
1653 q.tr[i][I2M]=-100000.0;
1654 q.tr[i][I2I]=-100000.0;
1655 q.tr[i][D2M]=-100000.0;
1656 q.tr[i][D2D]=-100000.0;
1661 q.Neff_M[0]=q.Neff_I[0]=q.Neff_D[0]=99.999; // Neff_av[0] is used for calculation of transition pseudocounts for the start state
1666 printf("\nMatches:\n");
1667 printf("col Neff nseqs\n");
1668 for (i=1; i<=imin(L,100); i++)
1669 printf("%3i %5.2f %3i\n",i,q.Neff_M[i],nseqs[i]);
1671 printf("\nInserts:\n");
1672 printf("col Neff nseqs\n");
1673 for (i=1; i<=imin(L,100); i++)
1674 printf("%3i %5.2f %3i\n",i,q.Neff_I[i],nseqs[i]);
1676 printf("\nDeletes:\n");
1677 printf("col Neff nseqs\n");
1678 for (i=1; i<=imin(L,100); i++)
1679 printf("%3i %5.2f %3i\n",i,q.Neff_D[i],nseqs[i]);
1682 // Copy column information into HMM q
1685 q.N_filtered=N_filtered;
1686 for (i=1; i<=L; i++) q.l[i]=l[i];
1688 // Set names in HMM q
1689 if (strlen(q.name)==0) strcpy(q.name,name);
1690 if (strlen(q.longname)==0) strcpy(q.longname,longname);
1691 if (strlen(q.fam)==0) strcpy(q.fam,fam);
1692 ScopID(q.cl,q.fold,q.sfam,q.fam); // derive superfamily, fold and class code from family name
1693 strcpy(q.file,file); // Store basename of alignment file name in q.file
1695 // Copy sequences to be displayed into HMM
1696 q.nss_dssp=q.nsa_dssp=q.nss_pred=q.nss_conf=q.nfirst=-1;
1698 if (kss_dssp>=0) q.nss_dssp=n++; // copy dssp sequence?
1699 if (ksa_dssp>=0) q.nsa_dssp=n++; // copy dssp sequence?
1700 if (kss_pred>=0) q.nss_pred=n++; // copy psipred sequence?
1701 if (kss_conf>=0) q.nss_conf=n++; // copy confidence value sequence?
1703 // Calculate consensus sequence?
1704 if (par.showcons || par.cons)
1710 // Reserve space for consensus/conservation sequence as Q-T alignment mark-up
1712 q.sname[q.ncons]=new(char[10]);
1713 if (!q.sname[q.ncons]) {MemoryError("array of names for displayed sequences");}
1714 strcpy(q.sname[q.ncons],"Consensus");
1715 q.seq[q.ncons]=new char[L+2];
1716 if (!q.seq[q.ncons]) {MemoryError("array of names for displayed sequences");}
1720 // Reserve space for consensus sequence as first sequence in alignment
1721 q.nfirst=n++; kfirst=-1;
1722 q.sname[q.nfirst]=new char[strlen(name)+11];
1723 if (!q.sname[q.nfirst]) {MemoryError("array of names for displayed sequences");}
1724 strcpy(q.sname[q.nfirst],name);
1725 strcat(q.sname[q.nfirst],"_consensus");
1726 q.seq[q.nfirst]=new char[L+2];
1727 if (!q.seq[q.nfirst]) {MemoryError("array of names for displayed sequences");}
1729 // Calculate consensus amino acids using similarity matrix
1730 for (i=1; i<=L; i++)
1733 for (a=0; a<20; a++)
1734 if (q.f[i][a]-pb[a]>maxw) {maxw = q.f[i][a]-pb[a]; maxa = a;}
1739 for (int b=0; b<20; b++) maxw += q.f[i][b]*Sim[maxa][b]*Sim[maxa][b];
1740 maxw *= q.Neff_M[i]/(q.Neff_HMM+1); // columns with many gaps don't get consensus symbol
1741 if (maxw>0.6) q.seq[q.ncons][i] = uprchr(i2aa(maxa));
1742 else if (maxw>0.4) q.seq[q.ncons][i] = lwrchr(i2aa(maxa));
1743 else q.seq[q.ncons][i] = 'x';
1745 if (par.cons) q.seq[q.nfirst][i] = uprchr(i2aa(maxa));
1749 q.seq[q.ncons][0]='-';
1750 q.seq[q.ncons][L+1]='\0';
1754 q.seq[q.nfirst][0]='-';
1755 q.seq[q.nfirst][L+1]='\0';
1759 // Copy sequences to be displayed from alignment to HMM
1760 for (k=0; k<N_in; k++)
1765 if (0 && (n>=MAXSEQDIS)) {
1766 /* FIXME: the test was if(n>=MAXSEQDIS),
1767 this test was necessary because alignment memory was static,
1768 now it should be dynamic, and should always have the right size,
1769 there are at least number-of-sequences plus a 'bit' more
1770 however, I do not know what that 'bit' is likely to be (in the future).
1771 at the moment it is 1 for the consnseus and 1 for structure,
1772 but this might change (FS)
1774 if (par.mark) cerr<<"WARNING: maximum number "<<MAXSEQDIS<<" of sequences for display of alignment exceeded\n";
1777 if (k==kss_dssp) nn=q.nss_dssp; // copy dssp sequence to nss_dssp
1778 else if (k==ksa_dssp) nn=q.nsa_dssp;
1779 else if (k==kss_pred) nn=q.nss_pred;
1780 else if (k==kss_conf) nn=q.nss_conf;
1781 else if (k==kfirst) nn=q.nfirst=n++;
1783 // strcut(sname[k]," "); // delete rest of name line beginning with two spaces " " // Why this?? Problem for pdb seqs without chain
1784 q.sname[nn]=new char[strlen(sname[k])+1];
1785 if (!q.sname[nn]) {MemoryError("array of names for displayed sequences");}
1786 strcpy(q.sname[nn],sname[k]);
1787 q.seq[nn]=new char[strlen(seq[k])+1];
1788 if (!q.seq[nn]) {MemoryError("array of names for displayed sequences");}
1789 strcpy(q.seq[nn],seq[k]);
1792 q.n_display=n; // how many sequences to be displayed in alignments?
1794 // Copy secondary structure information into HMM
1796 for (i=1; i<=L; i++) q.ss_dssp[i]=X[kss_dssp][i];
1798 for (i=1; i<=L; i++) q.sa_dssp[i]=X[ksa_dssp][i];
1801 for (i=1; i<=L; i++) q.ss_pred[i]=X[kss_pred][i];
1803 for (i=1; i<=L; i++) q.ss_conf[i]=X[kss_conf][i];
1805 for (i=1; i<=L; i++) q.ss_conf[i]=5;
1811 // Debug: print occurence of amino acids for each position i
1812 if (v>=2) printf("Effective number of sequences exp(entropy) = %-4.1f\n",q.Neff_HMM); //PRINT
1816 for (a=0; a<20; a++) printf("%4.1f ",100*pb[a]);
1817 cout<<"\nAmino acid frequencies without pseudocounts:\n";
1818 cout<<" A R N D C Q E G H I L K M F P S T W Y V\n";
1819 for (i=1; i<=L; i++)
1822 for (a=0; a<20; a++) printf("%4.0f ",100*q.f[i][a]);
1827 printf("\nListing transition probabilities without pseudocounts:\n");
1828 printf(" i M->M M->I M->D I->M I->I D->M D->D Neff_M Neff_I Neff_D\n");
1829 for (i=0; i<=L; i++)
1831 printf("%4i %6.3f %6.3f %6.3f ",i,pow(2.0,q.tr[i][M2M]),pow(2.0,q.tr[i][M2I]),pow(2.0,q.tr[i][M2D]));
1832 printf("%6.3f %6.3f ",pow(2.0,q.tr[i][I2M]),pow(2.0,q.tr[i][I2I]));
1833 printf("%6.3f %6.3f ",pow(2.0,q.tr[i][D2M]),pow(2.0,q.tr[i][D2D]));
1834 printf("%6.3f %6.3f %6.3f\n",q.Neff_M[i],q.Neff_I[i],q.Neff_D[i]);
1838 q.has_pseudocounts=false; /* MR1 */
1844 /////////////////////////////////////////////////////////////////////////////////////
1846 * FIXME: one of the most time consuming routines (according to gprof on r112)
1849 * @brief Calculate freqs q.f[i][a] and transitions q.tr[i][a] (a=MM,MI,MD) with pos-specific subalignments
1850 * Pos-specific weights are calculated like in "GetPositionSpecificWeights()"
1853 Alignment::Amino_acid_frequencies_and_transitions_from_M_state(HMM& q, char* in)
1855 // Calculate position-dependent weights wi[k] for each i.
1856 // For calculation of weights in column i use sub-alignment
1857 // over sequences which have a *residue* in column i (no gap, no end gap)
1858 // and over columns where none of these sequences has an end gap.
1859 // This is done by updating the arrays n[j][a] at each step i-1->i while letting i run from 1 to L.
1860 // n[j][a] = number of occurences of amino acid a at column j of the subalignment,
1861 // => only columns with n[j][ENDGAP]=0 are contained in the subalignment!
1862 // If no sequences enter or leave the subalignment at the step i-1 -> i (i.e. change=0)
1863 // then the old values wi[k], Neff[i-1], and ncol are used for the new position i.
1864 // Index a can be an amino acid (0-19), ANY=20, GAP=21, or ENDGAP=22
1866 int k; // index of sequence
1867 int i,j; // position in alignment
1868 int a; // amino acid (0..19)
1869 int naa; // number of different amino acids
1870 int** n; // n[j][a] = number of seq's with some residue at column i AND a at position j
1871 //float wi[MAXSEQ]; // weight of sequence k in column i, calculated from subalignment i
1872 float *wi=NULL; // weight of sequence k in column i, calculated from subalignment i
1873 //float Neff[MAXRES]; // diversity of subalignment i
1874 float *Neff = new float[par.maxResLen]; // diversity of subalignment i
1875 int nseqi=0; // number of sequences in subalignment i
1876 int ncol=0; // number of columns j that contribute to Neff[i]
1877 char change; // has the set of sequences in subalignment changed? 0:no 1:yes
1878 float fj[NAA+3]; // to calculate entropy
1881 wi = new float[N_in+2];
1885 for (k=0; k<N_in; k++)
1890 Neff[0]=0.0; // if the first column has no residues (i.e. change==0), Neff[i]=Neff[i-1]=Neff[0]
1894 #pragma omp parallel for schedule(static) private(a)
1896 for (j=1; j<=L; j++) {
1897 n[j]=new(int[NAA+3]);
1898 for (a=0; a<NAA+3; a++)
1903 //////////////////////////////////////////////////////////////////////////////////////////////
1904 // Main loop through alignment columns
1905 for (i=1; i<=L; i++) // Calculate wi[k] at position i as well as Neff[i]
1910 // Check all sequences k and update n[j][a] and ri[j] if necessary
1911 for (k=0; k<N_in; k++)
1913 if (!in[k]) continue;
1914 if (X[k][i-1]>=ANY && X[k][i]<ANY)
1915 { // ... if sequence k was NOT included in i-1 and has to be included for column i
1920 #pragma omp parallel for schedule(static)
1922 for (int j=1; j<=L; j++)
1923 n[j][ (int)X[k][j]]++;
1925 else if (X[k][i-1]<ANY && X[k][i]>=ANY)
1926 { // ... if sequence k WAS included in i-1 and has to be thrown out for column i
1931 #pragma omp parallel for schedule(static)
1933 for (int j=1; j<=L; j++)
1934 n[j][ (int)X[k][j]]--;
1939 // If subalignment changed: update weights wi[k] and Neff[i]
1942 // Initialize weights and numbers of residues for subalignment i
1944 for (k=0; k<N_in; k++)
1945 wi[k]=1E-8; // for pathological alignments all wi[k] can get 0; /* MR1 */
1947 // sum wi[k] over all columns j and sequences k of subalignment
1950 #pragma omp parallel for schedule(static) private(naa, a, k)
1952 for (j=1; j<=L; j++)
1954 // do at least a fraction MAXENDGAPFRAC of sequences in subalignment contain an end gap in j?
1955 if (n[j][ENDGAP]>MAXENDGAPFRAC*nseqi) continue;
1957 for (a=0; a<20; a++)
1960 if (naa==0) continue;
1966 for (k=0; k<N_in; k++)
1968 if (in[k] && X[k][i]<ANY && X[k][j]<ANY)
1970 // if (!n[j][ (int)X[k][j]]) {fprintf(stderr,"Error: Mi=%i: n[%i][X[%i]]=0! (X[%i]=%i)\n",i,j,k,k,X[k][j]);}
1975 wi[k]+=1.0/float(n[j][ (int)X[k][j] ]*naa);
1980 // Check whether number of columns in subalignment is sufficient
1982 // Take global weights
1983 for (k=0; k<N_in; k++)
1984 if(in[k] && X[k][i]<ANY)
1988 // Calculate Neff[i]
1992 #pragma omp parallel for schedule(static) private(a, k, fj)
1994 for (j=1; j<=L; j++)
1996 // do at least a fraction MAXENDGAPFRA of sequences in subalignment contain an end gap in j?
1997 if (n[j][ENDGAP]>MAXENDGAPFRAC*nseqi) continue;
1998 for (a=0; a<20; a++) fj[a]=0;
1999 for (k=0; k<N_in; k++)
2000 if (in[k] && X[k][i]<ANY && X[k][j]<ANY)
2001 fj[ (int)X[k][j] ]+=wi[k];
2002 NormalizeTo1(fj,NAA);
2003 for (a=0; a<20; a++)
2009 Neff[i]-=fj[a]*fast_log2(fj[a]);
2012 Neff[i]=pow(2.0,Neff[i]/ncol);
2017 else //no update was necessary; copy values for i-1
2024 // Calculate amino acid frequencies q.f[i][a] from weights wi[k]
2025 for (a=0; a<20; a++)
2027 for (k=0; k<N_in; k++)
2029 q.f[i][ (int)X[k][i] ]+=wi[k];
2030 NormalizeTo1(q.f[i],NAA,pb);
2032 // Calculate transition probabilities from M state
2033 q.tr[i][M2M]=q.tr[i][M2D]=q.tr[i][M2I]=0.0;
2034 for (k=0; k<N_in; k++) //for all sequences
2036 if (!in[k]) continue;
2037 //if input alignment is local ignore transitions from and to end gaps
2038 if (X[k][i]<ANY) //current state is M
2040 if (I[k][i]) //next state is I
2041 q.tr[i][M2I]+=wi[k];
2042 else if (X[k][i+1]<=ANY) //next state is M
2043 q.tr[i][M2M]+=wi[k];
2044 else if (X[k][i+1]==GAP) //next state is D
2045 q.tr[i][M2D]+=wi[k];
2048 // Normalize and take log
2049 sum = q.tr[i][M2M]+q.tr[i][M2I]+q.tr[i][M2D]+FLT_MIN;
2050 q.tr[i][M2M]=Log2(q.tr[i][M2M]/sum);
2051 q.tr[i][M2I]=Log2(q.tr[i][M2I]/sum);
2052 q.tr[i][M2D]=Log2(q.tr[i][M2D]/sum);
2054 // for (k=0; k<N_in; k++) if (in[k]) w[k][i]=wi[k];
2055 } // end loop through alignment columns i
2057 // DD TODO:fill in all the missing Neff values
2059 //////////////////////////////////////////////////////////////////////////////////////////////
2061 delete[](wi); wi=NULL;
2063 for (j=1; j<=L; j++){
2067 delete[](n); (n) = NULL;
2070 q.tr[0][M2I]=-100000;
2071 q.tr[0][M2D]=-100000;
2073 q.tr[L][M2I]=-100000;
2074 q.tr[L][M2D]=-100000;
2075 q.Neff_M[0]=99.999; // Neff_av[0] is used for calculation of transition pseudocounts for the start state
2077 // Set emission probabilities of zero'th (begin) state and L+1st (end) state to background probabilities
2078 for (a=0; a<20; a++)
2079 q.f[0][a]=q.f[L+1][a]=pb[a];
2081 // Assign Neff_M[i] and calculate average over alignment, Neff_M[0]
2086 #pragma omp parallel for schedule(static) private(a)
2088 for (i=1; i<=L; i++)
2091 for (a=0; a<20; a++)
2092 if (q.f[i][a]>1E-10)
2093 sum -= q.f[i][a]*fast_log2(q.f[i][a]);
2098 q.Neff_HMM+=pow(2.0,sum);
2101 float Nlim=fmax(10.0,q.Neff_HMM+1.0); // limiting Neff
2102 float scale=Log2((Nlim-q.Neff_HMM)/(Nlim-1.0)); // for calculating Neff for those seqs with inserts at specific pos
2105 #pragma omp parallel for schedule(static) private(k)
2107 for (i=1; i<=L; i++)
2109 float w_M=-1.0/N_filtered;
2110 for (k=0; k<N_in; k++)
2111 if (in[k] && X[k][i]<=ANY)
2116 q.Neff_M[i] = Nlim - (Nlim-1.0)*fpow2(scale*w_M);
2117 // fprintf(stderr,"M i=%3i ncol=--- Neff_M=%5.2f Nlim=%5.2f w_M=%5.3f Neff_M=%5.2f\n",i,q.Neff_HMM,Nlim,w_M,q.Neff_M[i]);
2122 for (i=1; i<=L; i++)
2124 q.Neff_HMM+=Neff[i];
2125 q.Neff_M[i]=Neff[i];
2126 if (q.Neff_M[i] == 0) {
2133 delete[] Neff; Neff = NULL;
2137 } /* this is the end of Alignment::Amino_acid_frequencies_and_transitions_from_M_state() */
2140 /////////////////////////////////////////////////////////////////////////////////////
2142 * @brief Calculate transitions q.tr[i][a] (a=DM,DD) with pos-specific subalignments
2145 Alignment::Transitions_from_I_state(HMM& q, char* in)
2147 // Calculate position-dependent weights wi[k] for each i.
2148 // For calculation of weights in column i use sub-alignment
2149 // over sequences which have a INSERT in column i
2150 // and over columns where none of these sequences has an end gap.
2151 // This is done by calculating the arrays n[j][a] and rj[j] at each step i-1->i while letting i run from 1 to L.
2152 // n[j][a] = number of occurences of amino acid a at column j of the subalignment,
2153 // => only columns with n[j][ENDGAP]=0 are contained in the subalignment!
2154 // If no sequences enter or leave the subalignment at the step i-1 -> i (i.e. change=0)
2155 // then the old values wi[k], Neff[i-1], and ncol are used for the new position i.
2156 // Index a can be an amino acid (0-19), ANY=20, GAP=21, or ENDGAP=22
2158 int k; // index of sequence
2159 int i,j; // position in alignment
2160 int a; // amino acid (0..19)
2161 int naa; // number of different amino acids
2162 int** n; // n[j][a] = number of seq's with some residue at column i AND a at position j
2163 //float wi[MAXSEQ]; // weight of sequence k in column i, calculated from subalignment i
2164 float *wi = NULL; // weight of sequence k in column i, calculated from subalignment i
2165 //float Neff[MAXRES]; // diversity of subalignment i
2166 float *Neff = new float[par.maxResLen]; // diversity of subalignment i
2167 int nseqi; // number of sequences in subalignment i
2168 int ncol; // number of columns j that contribute to Neff[i]
2169 float fj[NAA+3]; // to calculate entropy
2171 float Nlim=0.0; // only for global weights
2172 float scale=0.0; // only for global weights
2174 wi = new float[N_in+2];
2179 for (k=0; k<N_in; k++) wi[k]=wg[k];
2180 Nlim=fmax(10.0,q.Neff_HMM+1.0); // limiting Neff
2181 scale=Log2((Nlim-q.Neff_HMM)/(Nlim-1.0)); // for calculating Neff for those seqs with inserts at specific pos
2186 for (j=1; j<=L; j++) n[j]=new(int[NAA+3]);
2188 //////////////////////////////////////////////////////////////////////////////////////////////
2189 // Main loop through alignment columns
2190 for (i=1; i<=L; i++) // Calculate wi[k] at position i as well as Neff[i]
2192 if (par.wg==0) // local weights?
2195 // Calculate n[j][a] and ri[j]
2197 for (k=0; k<N_in; k++)
2199 if (in[k] && I[k][i]>0)
2201 if (nseqi==0) // Initialize only if inserts present! Otherwise O(L*L) even for single sequences!
2203 // Initialization of n[j][a]
2204 for (j=1; j<=L; j++)
2205 for (a=0; a<NAA+3; a++) n[j][a]=0;
2208 for (int j=1; j<=L; j++) n[j][ (int)X[k][j]]++;
2213 // If there is no sequence in subalignment j ...
2217 Neff[i]=0.0; // effective number of sequence = 0!
2218 q.tr[i][I2M]=-100000;
2219 q.tr[i][I2I]=-100000;
2223 // update weights wi[k] and Neff[i]
2226 // Initialize weights and numbers of residues for subalignment i
2228 for (k=0; k<N_in; k++) wi[k]=0.0;
2230 // sum wi[k] over all columns j and sequences k of subalignment
2231 for (j=1; j<=L; j++)
2233 if (n[j][ENDGAP]>MAXENDGAPFRAC*nseqi) continue;
2234 naa=0; for (a=0; a<20; a++) if(n[j][a]) naa++;
2235 if (naa==0) continue;
2237 for (k=0; k<N_in; k++)
2239 if (in[k] && I[k][i]>0 && X[k][j]<ANY)
2241 if (!n[j][ (int)X[k][j]]) {fprintf(stderr,"Error: Ii=%i: n[%i][X[%i]]=0! (X[%i]=%i)\n",i,j,k,k,X[k][j]);}
2242 wi[k]+=1.0/float(n[j][ (int)X[k][j] ]*naa);
2247 // Check whether number of columns in subalignment is sufficient
2249 // Take global weights
2250 for (k=0; k<N_in; k++)
2251 if(in[k] && I[k][i]>0) wi[k]=wg[k]; else wi[k]=0.0;
2253 // Calculate Neff[i]
2255 for (j=1; j<=L; j++)
2257 if (n[j][ENDGAP]>MAXENDGAPFRAC*nseqi) continue;
2258 for (a=0; a<20; a++) fj[a]=0;
2259 for (k=0; k<N_in; k++)
2260 if (in[k] && I[k][i]>0 && X[k][j]<ANY)
2261 fj[ (int)X[k][j] ]+=wi[k];
2262 NormalizeTo1(fj,NAA);
2263 for (a=0; a<20; a++)
2264 if (fj[a]>1E-10) Neff[i]-=fj[a]*fast_log2(fj[a]);
2266 if (ncol>0) Neff[i]=pow(2.0,Neff[i]/ncol); else Neff[i]=1.0;
2269 // Calculate transition probabilities from I state
2270 q.tr[i][I2M]=q.tr[i][I2I]=0.0;
2271 for (k=0; k<N_in; k++) //for all sequences
2273 if (in[k] && I[k][i]>0) //current state is I
2275 q.tr[i][I2M]+=wi[k];
2276 q.tr[i][I2I]+=wi[k]*(I[k][i]-1);
2281 else // fast global weights?
2283 float w_I=-1.0/N_filtered;
2285 q.tr[i][I2M]=q.tr[i][I2I]=0.0;
2286 // Calculate amino acid frequencies fj[a] from weights wg[k]
2287 for (k=0; k<N_in; k++)
2288 if (in[k] && I[k][i]>0)
2292 q.tr[i][I2M]+=wi[k];
2293 q.tr[i][I2I]+=wi[k]*(I[k][i]-1);
2297 if (w_I<0) Neff[i]=1.0;
2298 else Neff[i] = Nlim - (Nlim-1.0)*fpow2(scale*w_I);
2299 // fprintf(stderr,"I i=%3i ncol=%3i Neff_M=%5.2f Nlim=%5.2f w_I=%5.3f Neff_I=%5.2f\n",i,ncol,q.Neff_HMM,Nlim,w_I,Neff[i]);
2304 q.tr[i][I2M]=-100000;
2305 q.tr[i][I2I]=-100000;
2310 // Normalize and take log
2311 sum = q.tr[i][I2M]+q.tr[i][I2I];
2312 q.tr[i][I2M]=Log2(q.tr[i][I2M]/sum);
2313 q.tr[i][I2I]=Log2(q.tr[i][I2I]/sum);
2316 // end loop through alignment columns i
2317 //////////////////////////////////////////////////////////////////////////////////////////////
2319 delete[](wi); wi = NULL;
2321 for (j=1; j<=L; j++){
2322 delete[](n[j]); (n[j]) = NULL;
2324 delete[](n); (n) = NULL;
2327 q.tr[0][I2I]=-100000;
2329 q.tr[L][I2I]=-100000;
2333 for (i=1; i<=L; i++) // Calculate wi[k] at position i as well as Neff[i] and Neff[i]
2334 q.Neff_I[i]=Neff[i];
2336 delete[] Neff; Neff = NULL;
2339 } /* this is the end of Alignment::Transitions_from_I_state() */
2342 /////////////////////////////////////////////////////////////////////////////////////
2344 * @brief Calculate transitions q.tr[i][a] (a=DM,DD) with pos-specific subalignments
2347 Alignment::Transitions_from_D_state(HMM& q, char* in)
2349 // Calculate position-dependent weights wi[k] for each i.
2350 // For calculation of weights in column i use sub-alignment
2351 // over sequences which have a DELETE in column i
2352 // and over columns where none of these sequences has an end gap.
2353 // This is done by updating the arrays n[j][a] and rj[j] at each step i-1->i while letting i run from 1 to L.
2354 // n[j][a] = number of occurences of index a at column j of the subalignment,
2355 // => only columns with n[j][ENDGAP]=0 are contained in the subalignment!
2356 // If no sequences enter or leave the subalignment at the step i-1 -> i (i.e. change=0)
2357 // then the old values wi[k], Neff[i-1], and ncol are used for the new position i.
2358 // Index a can be an amino acid (0-19), ANY=20, GAP=21, or ENDGAP=22
2360 int k; // index of sequence
2361 int i,j; // position in alignment
2362 int a; // amino acid (0..19)
2363 int naa; // number of different amino acids
2364 int** n; // n[j][a] = number of seq's with some residue at column i AND a at position j
2365 //float wi[MAXSEQ]; // weight of sequence k in column i, calculated from subalignment i
2366 float *wi=NULL; // weight of sequence k in column i, calculated from subalignment i
2367 //float Neff[MAXRES]; // diversity of subalignment i
2368 float *Neff = new float[par.maxResLen]; // diversity of subalignment i
2369 int nseqi=0; // number of sequences in subalignment i (for DEBUGGING)
2370 int ncol=0; // number of columns j that contribute to Neff[i]
2371 char change; // has the set of sequences in subalignment changed? 0:no 1:yes
2372 float fj[NAA+3]; // to calculate entropy
2374 float Nlim=0.0; // only for global weights
2375 float scale=0.0; // only for global weights
2377 wi = new float[N_in+2]; /* FIXME: FS */
2381 for (k=0; k<N_in; k++)
2383 Nlim=fmax(10.0,q.Neff_HMM+1.0); // limiting Neff
2384 scale=Log2((Nlim-q.Neff_HMM)/(Nlim-1.0)); // for calculating Neff for those seqs with dels at specific pos
2391 #pragma omp parallel for schedule(static) private(a)
2393 for (j=1; j<=L; j++) {
2394 n[j]=new(int[NAA+3]);
2395 for (a=0; a<NAA+3; a++)
2399 //////////////////////////////////////////////////////////////////////////////////////////////
2400 // Main loop through alignment columns
2401 for (i=1; i<=L; i++) // Calculate wi[k] at position i as well as Neff[i]
2403 if (par.wg==0) // if local weights
2406 // Check all sequences k and update n[j][a] and ri[j] if necessary
2407 for (k=0; k<N_in; k++)
2409 if (!in[k]) continue;
2410 if (X[k][i-1]!=GAP && X[k][i]==GAP)
2411 { // ... if sequence k was NOT included in i-1 and has to be included for column i
2416 #pragma omp parallel for schedule(static)
2418 for (int j=1; j<=L; j++)
2419 n[j][ (int)X[k][j]]++;
2421 else if (X[k][i-1]==GAP && X[k][i]!=GAP)
2422 { // ... if sequence k WAS included in i-1 and has to be thrown out for column i
2427 #pragma omp parallel for schedule(static)
2429 for (int j=1; j<=L; j++)
2430 n[j][ (int)X[k][j]]--;
2435 // If there is no sequence in subalignment j ...
2439 Neff[i]=0.0; // effective number of sequences = 0!
2440 q.tr[i][D2M]=-100000;
2441 q.tr[i][D2D]=-100000;
2445 // If subalignment changed: update weights wi[k] and Neff[i]
2448 // Initialize weights and numbers of residues for subalignment i
2450 for (k=0; k<N_in; k++)
2453 // sum wg[k][i] over all columns j and sequences k of subalignment
2456 #pragma omp parallel for schedule(static) private(naa, a, k)
2458 for (j=1; j<=L; j++)
2460 if (n[j][ENDGAP]>MAXENDGAPFRAC*nseqi) continue;
2462 for (a=0; a<20; a++)
2465 if (naa==0) continue;
2471 for (k=0; k<N_in; k++)
2473 if (in[k] && X[k][i]==GAP && X[k][j]<ANY)
2475 if (!n[j][ (int)X[k][j]]) {fprintf(stderr,"Error: Di=%i: n[%i][X[%i]]=0! (X[%i]=%i)\n",i,j,k,k,X[k][j]);}
2480 wi[k]+=1.0/float(n[j][ (int)X[k][j] ]*naa);
2484 // Check whether number of columns in subalignment is sufficient
2486 // Take global weights
2487 for (k=0; k<N_in; k++)
2488 if(in[k] && X[k][i]==GAP)
2493 // Calculate Neff[i]
2497 #pragma omp parallel for schedule(static) private(a, k, fj)
2499 for (j=1; j<=L; j++)
2501 if (n[j][ENDGAP]>MAXENDGAPFRAC*nseqi) continue;
2502 for (a=0; a<20; a++) fj[a]=0;
2503 for (k=0; k<N_in; k++)
2504 if (in[k] && X[k][i]==GAP && X[k][j]<ANY)
2505 fj[ (int)X[k][j] ]+=wi[k];
2506 NormalizeTo1(fj,NAA);
2507 for (a=0; a<20; a++)
2513 Neff[i]-=fj[a]*fast_log2(fj[a]);
2515 if (ncol>0) Neff[i]=pow(2.0,Neff[i]/ncol); else Neff[i]=1.0;
2519 else //no update was necessary; copy values for i-1
2524 // Calculate transition probabilities from D state
2525 q.tr[i][D2M]=q.tr[i][D2D]=0.0;
2526 for (k=0; k<N_in; k++) //for all sequences
2528 if (in[k] && X[k][i]==GAP) //current state is D
2530 if (X[k][i+1]==GAP) //next state is D
2531 q.tr[i][D2D]+=wi[k];
2532 else if (X[k][i+1]<=ANY) //next state is M
2533 q.tr[i][D2M]+=wi[k];
2538 else // fast global weights?
2540 float w_D=-1.0/N_filtered;
2542 q.tr[i][D2M]=q.tr[i][D2D]=0.0;
2543 // Calculate amino acid frequencies fj[a] from weights wg[k]
2544 for (k=0; k<N_in; k++) //for all sequences
2545 if (in[k] && X[k][i]==GAP) //current state is D
2549 if (X[k][i+1]==GAP) //next state is D
2550 q.tr[i][D2D]+=wi[k];
2551 else if (X[k][i+1]<=ANY) //next state is M
2552 q.tr[i][D2M]+=wi[k];
2556 if (w_D<0) Neff[i]=1.0;
2557 else Neff[i] = Nlim - (Nlim-1.0)*fpow2(scale*w_D);
2558 // fprintf(stderr,"D i=%3i ncol=%3i Neff_M=%5.2f Nlim=%5.2f w_D=%5.3f Neff_D=%5.2f\n",i,ncol,q.Neff_HMM,Nlim,w_D,Neff[i]);
2562 Neff[i]=0.0; // effective number of sequences = 0!
2563 q.tr[i][D2M]=-100000;
2564 q.tr[i][D2D]=-100000;
2569 // Normalize and take log
2570 sum = q.tr[i][D2M]+q.tr[i][D2D];
2571 q.tr[i][D2M]=Log2(q.tr[i][D2M]/sum);
2572 q.tr[i][D2D]=Log2(q.tr[i][D2D]/sum);
2575 // end loop through alignment columns i
2576 //////////////////////////////////////////////////////////////////////////////////////////////
2579 q.tr[0][D2D]=-100000;
2583 for (i=1; i<=L; i++) {
2584 q.Neff_D[i]=Neff[i];
2589 delete[](n); (n) = NULL;
2590 delete[](wi); wi = NULL;/* FIXME: FS */
2592 delete[] Neff; Neff = NULL;
2595 } /* this is the end of Alignment::Transitions_from_D_state() */
2599 /////////////////////////////////////////////////////////////////////////////////////
2601 * @brief Write alignment without insert states (lower case) to alignment file?
2604 Alignment::WriteWithoutInsertsToFile(char* alnfile)
2606 if (v>=2) cout<<"Writing alignment to "<<alnfile<<"\n";
2608 if (!par.append) alnf = fopen(alnfile,"w"); else alnf = fopen(alnfile,"a");
2609 if (!alnf) OpenFileError(alnfile);
2610 // If alignment name is different from that of query: write name into commentary line
2611 if (strncmp(longname,sname[kfirst],DESCLEN-1)) fprintf(alnf,"#%s\n",longname);
2612 if (v>=2) cout<<"Writing alignment to "<<alnfile<<"\n";
2613 for (int k=0; k<N_in; k++)
2614 if (keep[k] || display[k]==KEEP_ALWAYS) // print if either in profile (keep[k]>0) or display is obligatory (display[k]==2)
2616 fprintf(alnf,">%s\n",sname[k]);
2617 for (int i=1; i<=L; i++) fprintf(alnf,"%c",i2aa(X[k][i]));
2623 /////////////////////////////////////////////////////////////////////////////////////
2624 // Write stored,filtered sequences WITH insert states (lower case) to alignment file?
2625 /////////////////////////////////////////////////////////////////////////////////////
2626 void Alignment::WriteToFile(char* alnfile, const char format[])
2629 if (!par.append) alnf = fopen(alnfile,"w"); else alnf = fopen(alnfile,"a");
2630 if (!alnf) OpenFileError(alnfile);
2631 // If alignment name is different from that of query: write name into commentary line
2632 if (strncmp(longname,sname[kfirst],DESCLEN-1)) fprintf(alnf,"#%s\n",longname);
2633 if (!format || !strcmp(format,"a3m"))
2635 if (v>=2) cout<<"Writing A3M alignment to "<<alnfile<<"\n";
2636 for (int k=0; k<N_in; k++)
2637 if (keep[k] || display[k]==KEEP_ALWAYS) // print if either in profile (keep[k]>0) or display obligatory (display[k]==2)
2638 fprintf(alnf,">%s\n%s\n",sname[k],seq[k]+1);
2640 else // PSI-BLAST format
2642 if (v>=2) cout<<"Writing PSI-BLAST-formatted alignment to "<<alnfile<<"\n";
2643 for (int k=kfirst; k<N_in; k++) // skip sequences before kfirst!!
2644 if (keep[k] || display[k]==KEEP_ALWAYS) // print if either in profile (keep[k]>0) or display obligatory (display[k]==2)
2647 fprintf(alnf,"%-20.20s ",sname[k]);
2648 // for (int i=1; i<=L; i++) fprintf(alnf,"%c",i2aa(X[k][i]));
2649 // fprintf(alnf,"\n");
2651 for (; *ptr!='\0'; ptr++)
2652 if (*ptr==45 || (*ptr>=65 && *ptr<=90)) fprintf(alnf,"%c",*ptr);
2663 * FIXME: this function contains a reference to MAXSEQ & MAXCOL
2664 * however, this may not be accessed (FS)
2666 /////////////////////////////////////////////////////////////////////////////////////
2668 * @brief Read a3m slave alignment of hit from file and merge into (query) master alignment
2671 Alignment::MergeMasterSlave(Hit& hit, char ta3mfile[])
2674 char* cur_seq = new(char[MAXCOL]); // Sequence currently read in
2676 int l,ll; // position in unaligned template (T) sequence Tali.seq[l]
2677 int i; // counts match states in query (Q) HMM
2678 int j; // counts match states in T sequence Tali.seq[l]
2679 int h; // position in aligned T sequence cur_seq[h]
2680 int k; // sequence index
2682 printf("****************%s:%s:%d: did get into MergeMasterSlave\n", __FUNCTION__, __FILE__, __LINE__);
2683 if (v>=3) printf("Merging %s to query alignment\n",ta3mfile);
2685 // If par.append==1 do not print query alignment
2686 if (par.append) for (k=0; k<N_in; k++) keep[k]=display[k]=KEEP_NOT;
2688 // Read template alignment into Tali
2689 FILE* ta3mf=fopen(ta3mfile,"r");
2690 if (!ta3mf) OpenFileError(ta3mfile);
2691 Tali.Read(ta3mf,ta3mfile);
2694 // Filter Tali alignment
2695 Tali.Compress(ta3mfile);
2696 N_filtered = Tali.Filter(par.max_seqid,par.coverage,par.qid,par.qsc,par.Ndiff);
2699 int* imatch=new int[hit.j2+1];
2700 int step = hit.nsteps;
2701 for (j=hit.j1; j<=hit.j2; j++)
2703 // Advance to position of next T match state j
2704 while (hit.j[step]<j) step--;
2705 imatch[j] = hit.i[step];
2706 // printf("step=%-3i i=%-3i j=%-3i\n",step,imatch[j],j);
2709 // Determine number of match states of Qali
2710 for (L=0,l=1; seq[kfirst][l]>'\0'; l++)
2711 if ((seq[kfirst][l]>='A' && seq[kfirst][l]<='Z') || seq[kfirst][l]=='-') L++;
2713 // For each sequence in T alignment: align to Qali
2714 for (k=0; k<Tali.N_in; k++)
2716 if (!Tali.keep[k]) continue;
2719 fprintf(stderr,"WARNING in %s: maximum number of %i sequences exceeded while reading %s. Skipping all following sequences\n",program_name,MAXSEQ,ta3mfile);
2722 cur_seq[0]=' '; // 0'th position not used
2724 // Add the hit.i1-1 left end gaps to aligned sequence
2725 for (h=1; h<hit.i1; h++) cur_seq[h]='-';
2727 // Advance to match state hit.j1 of Tali.seq[k]
2728 for (j=0, l=1; (c=Tali.seq[k][l])>'\0'; l++)
2729 if ((c>='A' && c<='Z') || c=='-') // match state at position l?
2730 if ((++j)==hit.j1) break; // yes: increment j. Reached hit,j1? yes: break
2733 {printf("Error: did not find %i match states in sequence %i of %s. Sequence:\n%s\n",hit.j1,k,Tali.name,Tali.seq[k]); exit(1);}
2735 // Write first match state to cur_seq
2736 int iprev=hit.i1; // index of previous query match state
2737 int lprev=l; // previous T match state in Tali.seq[k][l]
2738 cur_seq[h++] = Tali.seq[k][l]; // first column of alignment is Match-Match state
2740 // For each further match state j in alignment
2742 for (j=hit.j1+1; j<=hit.j2; j++)
2744 // Advance to position of next T match state j
2747 // Advance to position of next T match state j
2748 while ((c=Tali.seq[k][++l])>'\0' && ((c>='a' && c<='z') || c=='.')) ;
2750 int di=i-iprev; // number of Match states in Q between T match state j-1 and j
2751 int dl=l-lprev; // 1 + number of inserted residues in T sequence between T match state j-1 and j
2754 // One Q match state for one T match state (treated as special case for speed reasons)
2756 // Q: XXXXXX.....XXXXXX
2757 // T: YYYYYYyyyyyYYYYYY
2761 // Inserts in lower case
2762 for (ll=lprev+1; ll<l; ll++)
2763 if (Tali.seq[k][ll]!='-' && Tali.seq[k][ll]!='.') cur_seq[h++] = lwrchr(Tali.seq[k][ll]);
2765 // Template Match state -> upper case
2766 cur_seq[h++] = Tali.seq[k][ll];
2770 // Gap in query: no Q match state for on T match state (special case for speed reasons)
2772 // Q: XXXXXX.....~~~XXX
2773 // T: YYYYYYyyyyyYYYYYY
2777 // All T residues (including T match state) in lower case
2778 for (ll=lprev+1; ll<=l; ll++)
2779 if (Tali.seq[k][ll]!='-' && Tali.seq[k][ll]!='.') cur_seq[h++] = lwrchr(Tali.seq[k][ll]);
2783 // More Match states in Q than Inserts in the T sequence
2784 // => half T inserts y left, half right-aligned in uc, gaps to fill up
2785 // Number of T insert residues to be left-aligned: (int)(dl/2)
2787 // Q: XXXXXXXXXXXXXXXXXX
2788 // T: YYYYYYYyyy-yyYYYYY
2792 // Add left-bounded template residues
2793 for (ll=lprev+1; ll<=lprev+(int)(dl/2); ll++)
2794 cur_seq[h++]=uprchr(Tali.seq[k][ll]);
2797 for (int gap=1; gap<=di-dl; gap++) cur_seq[h++]='-';
2799 // Add right-bounded residues
2801 cur_seq[h++]=uprchr(Tali.seq[k][ll]);
2805 // Fewer Match states in Q than inserts in T sequence
2806 // => half of available space di for left- half for right-aligned T inserts, rest in lc
2807 // number of T inserts to be left-aligned in uc: (int)(di/2),
2809 // Q: XXXXXXXXX.XXXXXXX
2810 // T: YYYYYYYyyyyyYYYYY
2814 // Add left-bounded template residues
2815 for (ll=lprev+1; ll<=lprev+(int)(di/2); ll++)
2816 cur_seq[h++]=uprchr(Tali.seq[k][ll]);
2818 // Add central inserts
2819 for (int ins=1; ins<=dl-di; ins++,ll++)
2820 if (Tali.seq[k][ll]!='-' && Tali.seq[k][ll]!='.') cur_seq[h++] = lwrchr(Tali.seq[k][ll]);
2822 // Add right-bounded residues
2824 cur_seq[h++]=uprchr(Tali.seq[k][ll]);
2826 // printf("i=%-3i j=%-3i l=%-3i cur_seq=%s\n",i,j,l,cur_seq);
2829 if (h>=maxcol-1000) // too few columns? Reserve double space
2831 char* new_seq=new char[2*maxcol];
2832 strncpy(new_seq,cur_seq,maxcol); //////// check: maxcol-1 ????
2833 delete[](cur_seq); (cur_seq) = NULL;
2839 // Add the remaining gaps '-' to the end of the template sequence
2840 for (i=hit.i2+1; i<=L; i++) cur_seq[h++]='-';
2843 keep[N_in] = display[N_in] = KEEP_CONDITIONALLY;
2844 seq[N_in]=new char[h];
2845 if (!seq[N_in]) MemoryError("array for input sequences");
2846 strcpy(seq[N_in],cur_seq);
2847 X[N_in]=new char[h];
2848 if (!X[N_in]) MemoryError("array for input sequences");
2849 I[N_in]=new short unsigned int[h];
2850 if (!I[N_in]) MemoryError("array for input sequences");
2851 sname[N_in]=new char[strlen(Tali.sname[k])+1];
2852 if (!sname[N_in]) MemoryError("array for input sequences");
2853 strcpy(sname[N_in],Tali.sname[k]);
2856 // printf("k=%-3i %s\n",k,Tali.seq[k]);
2857 // printf("Query %s\n",seq[kfirst]);
2858 // printf("k=%-3i %s\n\n",k,cur_seq);
2862 // printf("N_in=%-5i HMM=%s with %i sequences\n",N_in,ta3mfile,N_filtered);
2864 delete[] cur_seq; cur_seq = NULL;
2865 delete[] imatch; imatch = NULL;
2866 delete[] ksort; ksort=NULL; // if ksort already existed it will be to short for merged alignment
2867 delete[] first; first=NULL; // if first already existed it will be to short for merged alignment
2868 delete[] last; last=NULL; // if last already existed it will be to short for merged alignment
2870 } /* this is the end of Alignment::MergeMasterSlave() */
2873 /////////////////////////////////////////////////////////////////////////////////////
2875 * @brief Add a sequence to Qali
2878 Alignment::AddSequence(char Xk[], int Ik[])
2880 int i; // position in query and target
2881 if (L<=0) InternalError("L is not set in AddSequence()");
2882 X[N_in]=new char[L+2];
2883 for (i=0; i<=L+1; i++) X[N_in][i]=Xk[i];
2885 for (i=0; i<=L+1; i++) I[N_in][i]=0;
2887 for (i=0; i<=L+1; i++) I[N_in][i]=Ik[i];
2892 /////////////////////////////////////////////////////////////////////////////////////
2894 * @brief Determine matrix of position-specific weights w[k][i] for multiple alignment
2895 * Pos-specific weights are calculated like in "Amino_acid_frequencies_and_transitions_from_M_state()"
2898 Alignment::GetPositionSpecificWeights(float* w[])
2900 // Calculate position-dependent weights wi[k] for each i.
2901 // For calculation of weights in column i use sub-alignment
2902 // over sequences which have a *residue* in column i (no gap, no end gap)
2903 // and over columns where none of these sequences has an end gap.
2904 // This is done by updating the arrays n[j][a] at each step i-1->i while letting i run from 1 to L.
2905 // n[j][a] = number of occurences of amino acid a at column j of the subalignment,
2906 // => only columns with n[j][ENDGAP]=0 are contained in the subalignment!
2907 // If no sequences enter or leave the subalignment at the step i-1 -> i (i.e. change=0)
2908 // then the old values w[k][i] and ncol are used for the new position i.
2909 // Index a can be an amino acid (0-19), ANY=20, GAP=21, or ENDGAP=22
2911 char* in=keep; // to keep the code similar to Amino_acid_frequencies_and_transitions_from_M_state()
2912 int k; // index of sequence
2913 int i,j; // position in alignment
2914 int a; // amino acid (0..19)
2915 int naa; // number of different amino acids
2916 int** n; // n[j][a] = number of seq's with some residue at column i AND a at position j
2917 int nseqi=0; // number of sequences in subalignment i
2918 int ncol=0; // number of columns j that contribute to Neff[i]
2919 char change; // has the set of sequences in subalignment changed? 0:no 1:yes
2925 for (k=0; k<N_in; k++)
2926 for (i=1; i<=L; i++) w[k][i]=wg[k];
2933 for (j=1; j<=L; j++) n[j]=new(int[NAA+3]);
2934 for (j=1; j<=L; j++)
2935 for (a=0; a<NAA+3; a++) n[j][a]=0;
2937 //////////////////////////////////////////////////////////////////////////////////////////////
2938 // Main loop through alignment columns
2939 for (i=1; i<=L; i++) // Calculate w[k][i]
2942 // Check all sequences k and update n[j][a] and ri[j] if necessary
2943 for (k=0; k<N_in; k++)
2945 if (!in[k]) continue;
2946 if (X[k][i-1]>=ANY && X[k][i]<ANY)
2947 { // ... if sequence k was NOT included in i-1 and has to be included for column i
2950 for (int j=1; j<=L; j++) n[j][ (int)X[k][j]]++;
2952 else if (X[k][i-1]<ANY && X[k][i]>=ANY)
2953 { // ... if sequence k WAS included in i-1 and has to be thrown out for column i
2956 for (int j=1; j<=L; j++) n[j][ (int)X[k][j]]--;
2961 // If subalignment changed: update weights w[k][i] and Neff[i]
2964 // Initialize weights and numbers of residues for subalignment i
2966 for (k=0; k<N_in; k++) w[k][i]=0.0;
2968 // sum wi[k] over all columns j and sequences k of subalignment
2969 for (j=1; j<=L; j++)
2971 // do at least a fraction MAXENDGAPFRAC of sequences in subalignment contain an end gap in j?
2972 if (n[j][ENDGAP]>MAXENDGAPFRAC*nseqi) continue;
2973 naa=0; for (a=0; a<20; a++) if(n[j][a]) naa++;
2974 if (naa==0) continue;
2976 for (k=0; k<N_in; k++)
2978 if (in[k] && X[k][i]<ANY && X[k][j]<ANY)
2980 // if (!n[j][ (int)X[k][j]]) {fprintf(stderr,"Error: Mi=%i: n[%i][X[%i]]=0! (X[%i]=%i)\n",i,j,k,k,X[k][j]);}
2981 w[k][i]+=1.0/float(n[j][ (int)X[k][j] ]*naa);
2986 // Check whether number of columns in subalignment is sufficient
2988 // Take global weights
2989 for (k=0; k<N_in; k++)
2990 if(in[k]) {if(X[k][i]<ANY) w[k][i]=wg[k]; else w[k][i]=0.0;}
2993 // end loop through alignment columns i
2994 ///////////////////////////////////////////////////////////////////////
2997 for (j=1; j<=L; j++){
2998 delete[](n[j]); (n[j]) = NULL;
3000 delete[](n); (n) = NULL;
3009 * take sequence data from Clustal and transfer it into
3010 * hhalign accessible information (structure/class)
3012 * Note that hhalign does not see all sequences/profiles
3013 * but only sequences that are elements of the 2 profiles
3016 * References to the required sequences are passed into hhalign
3017 * through auxilliary pointers that are shallow copies of the
3018 * sequence/profile data available to Clustal.
3020 * Re-allocating memory for these auxilliary pointers
3021 * would be desaterous, as it might detach the memory
3025 Alignment::Transfer(char **ppcProf, int iCnt){
3027 /* @<variables local to Transfer@> */
3028 int iLen; /* length of profile */
3029 int k; /* generic iterator */
3031 /* @<initialisation@> */
3033 N_filtered = N_ss = 0;
3034 kss_dssp = ksa_dssp = kss_pred = kss_conf = -1;
3036 strcpy(longname, "unknown_long_seq_name");
3037 strcpy(name, "unknown_seq_name");
3038 strcpy(file, "unknown_file_name");
3041 /* @<determine length of profile@>
3042 all sequences in profile should have same length,
3043 so only do it for 1st */
3044 for (iLen = 0; '\0' != ppcProf[0][iLen]; iLen++);
3046 /* @<allocate memory for sequences etc@> */
3047 for (k = 0; k < iCnt; k++){
3048 #define GOOD_MEASURE 1000 /* Temporary -- can be removed once rest in place */
3049 I[k] = new short unsigned int[iLen+2+GOOD_MEASURE];
3050 X[k] = new char[iLen+2+GOOD_MEASURE];
3051 seq[k] = new char[iLen+2+GOOD_MEASURE];
3054 if (NULL == ppcProf[k]){
3055 printf("%s:%d: Arena[%d]=NULL, cnt=%d\n", __FILE__, __LINE__, k, iCnt);
3058 strcat(seq[k], ppcProf[k]);
3059 keep[k] = KEEP_CONDITIONALLY;
3060 display[k] = KEEP_CONDITIONALLY;
3061 sname[k] = new(char[GOOD_MEASURE]);
3062 strcpy(sname[k], "unknown_sname");
3063 } /* (0 <= k < iCnt) */
3064 /* FIXME: Soeding always makes 1st sequence permanent */
3065 /*keep[0] = KEEP_ALWAYS;
3066 display[k] = KEEP_ALWAYS;*/
3068 /* Believe that the first and last positions are
3069 most important in stability of this algorithm.
3070 Must make sure that at least 2 sequences with
3071 residues in these positions are kept.
3072 Think any sequence will do, but better to keep
3073 the one with the longest 'contig'
3075 int iSeq; /* sequence iterator */
3076 int iHeadLen = 0, iHeadID = -1; /* length & ID of longest head contig */
3077 int iTailLen = 0, iTailID = -1; /* length & ID of longest head contig */
3079 char *pcFind = NULL;
3082 printf("%s:%s:%d: NEW PROFILE (%d seq) ================\n",
3083 __FUNCTION__, __FILE__, __LINE__, iCnt);
3085 for (iSeq = 0; iSeq < iCnt; iSeq++){
3087 printf("%s:%s:%d: consider seq %d ------------------\n",
3088 __FUNCTION__, __FILE__, __LINE__, iSeq);
3090 pcFind = strchr(&seq[iSeq][1], '-');
3091 if (NULL == pcFind){
3092 /* no gap at all in this sequences, spans entire profile */
3093 iHeadID = iTailID = iSeq;
3094 iHeadLen = iTailLen = iLen;
3097 iCont = (int)(pcFind - &seq[iSeq][1]);
3098 if (iCont > iHeadLen){
3102 pcFind = strrchr(seq[iSeq], '-');
3103 iCont = iLen - (int)(pcFind - seq[iSeq]);
3104 if (iCont > iTailLen){
3110 printf("%s:%s:%d: seq %3d: len = %d(%d) %s\n",
3111 __FUNCTION__, __FILE__, __LINE__, iSeq, iCont, iLen, seq[iSeq]);
3113 } /* 0 <= iSeq < iCnt */
3115 printf("%s:%s:%d: seq %d is winner with head contig of %d, seq %d tail contig of %d\n"
3116 , __FUNCTION__, __FILE__, __LINE__, iHeadID, iHeadLen, iTailID, iTailLen);
3118 if ( (-1 == iHeadID) || (-1 == iTailID) ){
3119 printf("%s:%s:%d: profile has no leading and/or trailing residues (h=%d:t=%d:#=%d)\n",
3120 __FUNCTION__, __FILE__, __LINE__, iHeadID, iTailID, iCnt);
3123 keep[iHeadID] = KEEP_ALWAYS;
3124 keep[iTailID] = KEEP_ALWAYS;
3130 } /* this is the end of Transfer() */
3134 /* @* Alignment::ClobberGlobal (eg: qali)
3136 * Note: originally hhalign() was stand-alone code,
3137 * there are a couple of GLOBAL (!) variables,
3138 * which would have been destroyed on exit.
3139 * However, now there is no 'exit' from hhalign(),
3140 * and on re-entry the global variable must be clean again.
3143 Alignment::ClobberGlobal(void){
3146 these are essential to re-set (as some of them are used as flags) */
3147 for(int k=0; k<N_in; k++)
3149 delete[] sname[k]; sname[k] = NULL;
3150 delete[] seq[k]; seq[k] = NULL;
3151 delete[] X[k]; X[k] = NULL;
3152 delete[] I[k]; I[k] = NULL;
3154 delete[] nres; nres = NULL;
3155 delete[] first; first = NULL;
3156 delete[] last; last = NULL;
3157 delete[] ksort; ksort = NULL;
3158 N_in = N_filtered = n_display = 0;
3160 kss_dssp = ksa_dssp = kss_pred = kss_conf = kfirst = -1;
3162 /* @<re-set but keep memory@>
3163 do not free the memory but re-set content */
3164 longname[0] = '\0'; //delete[] longname; longname = NULL;
3165 keep[0] = '\0'; //delete[] keep; keep = NULL;
3166 display[0] = '\0'; //delete[] display; display = NULL;
3167 wg[0] = 0; //delete[] wg; wg = NULL;
3168 nseqs[0] = 0; //delete[] nseqs; nseqs = NULL;
3172 //delete[] sname; sname = NULL;
3173 //delete[] seq; seq = NULL;
3174 //delete[] X; X = NULL;
3175 //delete[] I; I = NULL;
3176 //delete[] l; l = NULL;