ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/seqalign/GXAlign.h
Revision: 82
Committed: Thu Sep 29 20:46:39 2011 UTC (9 years, 7 months ago) by gpertea
File size: 15566 byte(s)
Log Message:
wip

Line User Rev File contents
1 gpertea 74 #ifndef _GXALIGN_H
2    
3     #include "GBase.h"
4     #include "GList.hh"
5    
6     #define GDEBUG 1
7    
8 gpertea 82 #define MAX_SPACE 2000000
9 gpertea 74
10     enum {
11     EDIT_OP_MASK = 0x3,
12     EDIT_OP_ERR = 0x0,
13     EDIT_OP_INS = 0x1,
14     EDIT_OP_DEL = 0x2,
15     EDIT_OP_REP = 0x3
16     };
17    
18     #define GX_EDITOP_VAL(op) ((op) >> 2)
19     #define GX_EDITOP_GET(op) ((op) & EDIT_OP_MASK)
20     #define GX_EDITOP_CONS(op, val) (((val) << 2) | ((op) & EDIT_OP_MASK))
21    
22     #ifdef GDEBUG
23     enum {c_black=0,
24     c_red, c_green,c_brown,c_blue,c_magenta,c_cyan,c_white
25     };
26    
27     void color_fg(int c, FILE* f=stderr);
28     void color_bg(int c, FILE* f=stderr);
29     void color_resetfg(FILE* f=stderr);
30     void color_resetbg(FILE* f=stderr);
31     void color_reset(FILE* f=stderr);
32     void color_normal(FILE* f=stderr);
33     #endif
34    
35     struct GXEditScript{
36     uint32 *ops; // array of edit operations
37     uint32 opsize, opnum; // size of allocation, number in use
38     uint32 oplast; // most recent operation added
39     //methods
40    
41     GXEditScript() {
42     init();
43     }
44     ~GXEditScript() {
45     GFREE(ops);
46     }
47     void init() {
48     ops = NULL;
49     opsize = 0;
50     opnum = 0;
51     oplast = 0;
52     getReady(8);
53     }
54    
55     int getReady(uint32 n) {
56     uint32 m = n + n/2;
57     if (opsize <= n) {
58     GREALLOC(ops, m*sizeof(uint32));
59     opsize = m;
60     }
61     return 1;
62     }
63    
64     int getReady2(uint32 n) {
65     if (opsize - opnum <= n)
66     return getReady(n + opnum);
67     return 1;
68     }
69    
70     int Put(uint32 op, uint32 n) {
71     if (!getReady2(2))
72     return 0;
73     oplast = op;
74     ops[opnum] = GX_EDITOP_CONS(op, n);
75     opnum += 1;
76     ops[opnum] = 0; // sentinel
77     return 1;
78     }
79     uint32* First() {
80     return opnum > 0 ? & ops[0] : NULL;
81     }
82    
83     uint32* Next(uint32 *op) {
84     // assumes flat address space !
85     if (&ops[0] <= op && op < &ops[opnum-1])
86     return op+1;
87     else
88     return 0;
89     }
90    
91     int More(uint32 op, uint32 k) {
92     if (op == EDIT_OP_ERR) {
93     GError("GXEditScript::opMore: bad opcode %d:%d", op, k);
94     return -1;
95     }
96    
97     if (GX_EDITOP_GET(oplast) == op) {
98     uint32 l=ops[opnum-1];
99     ops[opnum-1]=GX_EDITOP_CONS((GX_EDITOP_GET(l)),
100     (GX_EDITOP_VAL(l) + k));
101     }
102     else {
103     Put(op, k);
104     }
105    
106     return 0;
107     }
108    
109     GXEditScript* Append(GXEditScript *et) {
110     uint32 *op;
111     for (op = et->First(); op; op = et->Next(op))
112     More(GX_EDITOP_GET(*op), GX_EDITOP_VAL(*op));
113     return this;
114     }
115    
116     int opDel(uint32 k) {
117     return More(EDIT_OP_DEL, k);
118     }
119     int opIns(uint32 k) {
120     return More(EDIT_OP_INS, k);
121     }
122     int opRep(uint32 k) {
123     return More(EDIT_OP_REP, k);
124     }
125    
126     GXEditScript *reverse() {
127     const uint32 mid = opnum/2;
128     const uint32 end = opnum-1;
129     for (uint32 i = 0; i < mid; ++i) {
130     const uint32 t = ops[i];
131     ops[i] = ops[end-i];
132     ops[end-i] = t;
133     }
134     return this;
135     }
136     };
137    
138    
139 gpertea 81 // ----- pool allocator -----
140 gpertea 82 // works as a linked list of allocated memory blocks
141     struct GXMemPool {
142     char* memblock;
143 gpertea 74 int used, size;
144 gpertea 82 GXMemPool *next;
145 gpertea 74 //methods
146 gpertea 82 GXMemPool() { //by default allocate a large block here (10M)
147     uint32 amount= MAX_SPACE<<3;
148     GCALLOC(memblock, amount);
149     if (memblock == NULL) {
150 gpertea 74 GError("Failed to allocated GXAlnSpace for greedy extension!\n");
151     return;
152     }
153     used = 0;
154     size = amount;
155     next = NULL;
156     }
157     void refresh() {
158 gpertea 82 GXMemPool* sp=this;
159 gpertea 74 while (sp) {
160     sp->used = 0;
161     sp = sp->next;
162     }
163     }
164 gpertea 82 ~GXMemPool() {
165     GXMemPool* next_sp;
166     GXMemPool* sp=this->next;
167 gpertea 74 while (sp) {
168     next_sp = sp->next;
169 gpertea 82 GFREE(sp->memblock);
170 gpertea 74 delete sp;
171     sp = next_sp;
172     }
173 gpertea 82 GFREE(memblock);
174 gpertea 74 }
175 gpertea 79
176 gpertea 82 void* getSpace(int amount) { //amount to use or allocate memory, in bytes
177     //can use the first found memory block with enough room,
178     // or allocate a new large block
179     char* v;
180 gpertea 74 if (amount < 0) return NULL;
181 gpertea 82 GXMemPool* S=this;
182 gpertea 74 while (used+amount > S->size) {
183 gpertea 82 //no room in current block, get a new mem block
184 gpertea 74 if (next == NULL) {
185 gpertea 82 next=new GXMemPool(); //allocates a large contiguous memory block
186 gpertea 74 }
187     S = S->next;
188     }
189 gpertea 82 v = S->memblock+S->used;
190 gpertea 74 S->used += amount;
191 gpertea 82 //align to next 8-byte boundary
192     int m8 = S->used & 7; //modulo 8
193     if (m8)
194     S->used += 8 - m8;
195     return (void*)v;
196 gpertea 74 }
197     };
198    
199 gpertea 79 #define ERROR_FRACTION 6 // 1/this : the higher it is, the smaller the diagonal band
200    
201 gpertea 74 struct GXAlnMem { //GreedyAlignMem
202 gpertea 81 int** flast_d; //flast_d[][]
203 gpertea 74 int* max_row_free;
204     int* uplow_free;
205 gpertea 82 GXMemPool* space;
206 gpertea 74 int max_d;
207     GXAlnMem(int max_len, int reward, int penalty, int Xdrop) {
208     flast_d=NULL;
209     max_row_free=NULL;
210     max_d=0;
211     uplow_free=NULL;
212     space=NULL;
213     max_d = (int)(max_len / ERROR_FRACTION + 1);
214     int d_diff = (Xdrop+reward/2)/(penalty+reward) + 1;
215 gpertea 79 GCALLOC(flast_d, (max_d+2)* sizeof(int*));
216 gpertea 74 if (flast_d == NULL) {
217     GError("Error: cannot allocate GXAlnMem structure!\n");
218     }
219     flast_d[0] = (int*)malloc((max_d + max_d + 6) * sizeof(int) * 2);
220 gpertea 82 //allocates two int rows - flast_d[1] too
221 gpertea 74 if (flast_d[0] == NULL) {
222     GError("Error: failed to allocate flast_d[0] in GXAlnMem!\n");
223     }
224 gpertea 82 flast_d[1] = flast_d[0] + max_d + max_d + 6; //int array for next row
225 gpertea 74 uplow_free = NULL;
226     max_row_free = (int*) malloc(sizeof(int) * (max_d + 1 + d_diff));
227 gpertea 82 space = new GXMemPool();
228 gpertea 74 }
229     ~GXAlnMem() {
230     delete space;
231     GFREE(max_row_free);
232 gpertea 79 GFREE(flast_d[0]);
233     GFREE(flast_d);
234 gpertea 74 }
235     };
236    
237     int GXGreedyAlign(const char* s1, int len1,
238     const char* s2, int len2,
239     bool reverse, int xdrop_threshold,
240     int match_cost, int mismatch_cost,
241     int* e1, int* e2,
242     GXAlnMem* abmp, GXEditScript *S=NULL);
243    
244     #define GAPALIGN_SUB ((unsigned char)0) /*op types within the edit script*/
245     #define GAPALIGN_INS ((unsigned char)1)
246     #define GAPALIGN_DEL ((unsigned char)2)
247     #define GAPALIGN_DECLINE ((unsigned char)3)
248    
249     struct GapXEditScript {
250     unsigned char op_type; // GAPALIGN_SUB, GAPALIGN_INS, or GAPALIGN_DEL
251     int num; // Number of operations
252     GapXEditScript* next;
253     GapXEditScript() {
254     op_type=0;
255     num=0;
256     next=NULL;
257     }
258     void print();
259     };
260    
261     class CSeqGap { //
262     public:
263     int offset;
264     int len;
265     CSeqGap(int gofs=0,int glen=1) {
266     offset=gofs;
267     len=glen;
268     }
269     };
270    
271     class CAlnGapInfo {
272     int a_ofs; //alignment start on seq a (0 based)
273     int b_ofs; //alignment start on seq b (0 based)
274     int a_len; //length of alignment on seq a
275     int b_len; //length of alignment on seq b
276     public:
277     GVec<CSeqGap> a_gaps;
278     GVec<CSeqGap> b_gaps;
279     CAlnGapInfo(GXEditScript* ed_script, int astart=0, int bstart=0):a_gaps(),b_gaps() {
280     a_ofs=astart;
281     b_ofs=bstart;
282     a_len=0;
283 gpertea 82 b_len=0;
284     if (ed_script==NULL) return;
285     for (uint32 i=0; i<ed_script->opnum; i++) {
286     int num=((ed_script->ops[i]) >> 2);
287     char op_type = 3 - ( ed_script->ops[i] & EDIT_OP_MASK );
288     if (op_type == 3 || op_type < 0 )
289     GError("Error: encountered op_type %d in ed_script?!\n", (int)op_type);
290     CSeqGap gap;
291     switch (op_type) {
292     case GAPALIGN_SUB: a_len+=num;
293     b_len+=num;
294     break;
295     case GAPALIGN_INS: a_len+=num;
296     gap.offset=b_ofs+b_len;
297     gap.len=num;
298     b_gaps.Add(gap);
299     break;
300     case GAPALIGN_DEL: b_len+=num;
301     gap.offset=a_ofs+a_len;
302     gap.len=num;
303     a_gaps.Add(gap);
304     break;
305     }
306     }
307     }
308    
309 gpertea 74 #ifdef GDEBUG
310 gpertea 82 void printAlignment(FILE* f, const char* sa, const char* sb) {
311     //print seq A
312     char al[1024]; //display buffer for seq A
313     int ap=0; //index in al[] for current character printed
314     int g=0;
315     int aend=a_ofs+a_len;
316     if (a_ofs<b_ofs) {
317     for (int i=0;i<b_ofs-a_ofs;i++) {
318 gpertea 74 fprintf(f, " ");
319     al[++ap]=' ';
320     }
321     }
322     for (int i=0;i<aend;i++) {
323     if (g<a_gaps.Count() && a_gaps[g].offset==i) {
324     for (int j=0;j<a_gaps[g].len;j++) {
325     fprintf(f, "-");
326     al[++ap]='-';
327     }
328     g++;
329     }
330     if (i==a_ofs) color_bg(c_blue,f);
331     fprintf(f, "%c", sa[i]);
332     al[++ap]=sa[i];
333     }
334     color_reset(f);
335     fprintf(f, &sa[aend]);
336     fprintf(f, "\n");
337     //print seq B
338     ap=0;
339     g=0;
340     int bend=b_ofs+b_len;
341     if (a_ofs>b_ofs) {
342     for (int i=0;i<a_ofs-b_ofs;i++) {
343     fprintf(f, " ");
344     ap++;
345     }
346     }
347     for (int i=0;i<b_ofs;i++) {
348     fprintf(f, "%c", sb[i]);
349     ap++;
350     }
351     for (int i=b_ofs;i<bend;i++) {
352     if (g<b_gaps.Count() && b_gaps[g].offset==i) {
353     for (int j=0;j<b_gaps[g].len;j++) {
354     fprintf(f, "-");
355     ap++;
356     }
357     g++;
358     }
359     if (i==b_ofs) color_bg(c_blue,f);
360     ap++;
361     bool mismatch=(sb[i]!=al[ap] && al[ap]!='-');
362     if (mismatch) color_bg(c_red,f);
363     fprintf(f, "%c", sb[i]);
364     if (mismatch) color_bg(c_blue,f);
365     }
366     color_reset(f);
367     fprintf(f, &sb[bend]);
368     fprintf(f, "\n");
369     }
370     #endif
371     };
372    
373    
374     struct GXAlnInfo {
375     const char *qseq;
376     int ql,qr;
377     const char *sseq;
378     int sl,sr;
379     int score;
380     double pid;
381     GXEditScript* editscript;
382     GXAlnMem* abmp;
383     CAlnGapInfo* gapinfo;
384     GXAlnInfo(const char* q, int q_l, int q_r, const char* s, int s_l, int s_r,
385     int sc=0, double percid=0) {
386     qseq=q;
387     sseq=s;
388     ql=q_l;
389     qr=q_r;
390     sl=s_l;
391     sr=s_r;
392     score=sc;
393     pid=percid;
394     //editscript=NULL;
395     gapinfo=NULL;
396     }
397     ~GXAlnInfo() {
398     delete editscript;
399     delete abmp;
400     delete gapinfo;
401     }
402 gpertea 78 bool operator<(GXAlnInfo& d) {
403     return ((score==d.score)? pid>d.pid : score>d.score);
404     }
405     bool operator>(GXAlnInfo& d) {
406     return ((score==d.score)? pid<d.pid : score<d.score);
407     }
408     bool operator==(GXAlnInfo& d) {
409     return (score==d.score && pid==d.pid);
410     }
411    
412 gpertea 74 };
413    
414    
415    
416     struct GXSeed {
417 gpertea 77 int b_ofs; //0-based coordinate on seq b (x coordinate)
418     int a_ofs; //0-based coordinate on seq a (y coordinate)
419 gpertea 74 int len; //length of exact match after extension
420     bool operator<(GXSeed& d){
421 gpertea 77 return ((b_ofs==d.b_ofs) ? a_ofs<d.a_ofs : b_ofs<d.b_ofs);
422 gpertea 74 }
423     bool operator>(GXSeed& d){
424 gpertea 77 return ((b_ofs==d.b_ofs) ? a_ofs>d.a_ofs : b_ofs>d.b_ofs);
425 gpertea 74 }
426     bool operator==(GXSeed& d){
427 gpertea 77 return (b_ofs==d.b_ofs && a_ofs==d.a_ofs); //should never be the case, seeds are uniquely constructed
428 gpertea 74 }
429     GXSeed(int aofs=0, int bofs=0, int l=4) {
430     a_ofs=aofs;
431     b_ofs=bofs;
432     len=l;
433     }
434     };
435    
436 gpertea 81 int cmpSeedDiag(const pointer p1, const pointer p2);
437     //seeds are "equal" if they're on the same diagonal (for selection purposes only)
438 gpertea 78
439 gpertea 81 int cmpSeedScore(const pointer p1, const pointer p2); //also takes position into account
440     //among seeds with same length, prefer those closer to the left end of the read (seq_b)
441    
442 gpertea 77 struct GXBand {
443     //bundle of seed matches on 3 adjacent diagonals
444     int diag; //first anti-diagonal (b_ofs-a_ofs) in this group of 3
445     //seeds for this, and diag+1 and diag+2 are stored here
446     int min_a, max_a; //maximal coordinates of the bundle
447     int min_b, max_b;
448     GList<GXSeed> seeds; //sorted by x coordinate (b_ofs)
449     int score; //sum of seed scores (- overlapping_bases/2 - gaps)
450 gpertea 78 GXBand(int start_diag=-1, GXSeed* seed=NULL):seeds(true, false, false) {
451 gpertea 77 diag=start_diag;
452     min_a=MAX_INT;
453     min_b=MAX_INT;
454     max_a=0;
455     max_b=0;
456     score=0;
457 gpertea 78 if (seed!=NULL) addSeed(seed);
458     }
459 gpertea 77 void addSeed(GXSeed* seed) {
460     seeds.Add(seed);
461     score+=seed->len;
462     //if (diag<0) diag=seed->diag; //should NOT be done like this
463     if (seed->a_ofs < min_a) min_a=seed->a_ofs;
464     if (seed->a_ofs+ seed->len > max_a) max_a=seed->a_ofs+seed->len;
465     if (seed->b_ofs < min_b) min_b=seed->b_ofs;
466     if (seed->b_ofs+seed->len > max_b) max_b=seed->b_ofs+seed->len;
467     }
468     void finalize() {
469 gpertea 78 //!! to be called only AFTER all seeds have been added
470     // seeds are sorted by b_ofs
471     //penalize seed gaps and overlaps on b sequence
472 gpertea 77 for (int i=1;i<seeds.Count();i++) {
473     GXSeed& sprev=*seeds[i-1];
474     GXSeed& scur=*seeds[i];
475     if (scur==sprev) GError("Error: duplicate seeds found (%d-%d:%d-%d)!\n",
476     scur.a_ofs+1, scur.a_ofs+scur.len, scur.b_ofs+1, scur.b_ofs+scur.len);
477     int b_gap=scur.b_ofs-sprev.b_ofs-sprev.len;
478     int a_gap=scur.a_ofs-sprev.a_ofs-sprev.len;
479     int max_gap=b_gap;
480     int min_gap=a_gap;
481     if (min_gap>max_gap) swap(max_gap, min_gap);
482 gpertea 78 if (min_gap<0) { //overlap
483     if (max_gap>0) { score-=GMAX((-min_gap), max_gap); }
484     else score+=min_gap;
485 gpertea 77 }
486 gpertea 78 else { //gap
487     score-=max_gap;
488 gpertea 77 }
489 gpertea 78 }//for each seed
490 gpertea 77 }
491 gpertea 78
492 gpertea 77 //bands will be sorted by decreasing score eventually, after all seeds are added
493     bool operator<(GXBand& d){
494     return ((score==d.score) ? seeds.Count()>d.seeds.Count() : score>d.score);
495     }
496     bool operator>(GXBand& d){
497     return ((score==d.score) ? seeds.Count()<d.seeds.Count() : score<d.score);
498     }
499     bool operator==(GXBand& d){
500     return (score==d.score && seeds.Count()==d.seeds.Count());
501     }
502    
503     };
504    
505     class GXBandSet:public GList<GXBand> {
506     public:
507     int idxoffset; //global anti-diagonal->index offset (a_len-1)
508     //used to convert a diagonal to an index
509     //diagonal is always b_ofs-a_ofs, so the minimum value is -a_len+1
510     //hence offset is a_len-1
511     GXBand* band(int diag) { //retrieve the band for given anti-diagonal (b_ofs-a_ofs)
512     return Get(diag+idxoffset);
513     }
514     GXBand* band(int a_ofs, int b_ofs) { //retrieve the band for given anti-diagonal (b_ofs-a_ofs)
515     return Get(b_ofs-a_ofs+idxoffset);
516     }
517     GXBandSet(int a_len, int b_len):GList<GXBand>(a_len+b_len-1, false, true, false) {
518     idxoffset=a_len-1;
519     //diag will range from -a_len+1 to b_len-1, so after adjustment
520     //by idxoffset we get a max of a_len+b_len-2
521     int bcount=a_len+b_len-1;
522     for (int i=0;i<bcount;i++)
523 gpertea 78 this->Add(new GXBand(i-idxoffset));
524     //unsorted, this should set fList[i]
525 gpertea 77 }
526     void addSeed(GXSeed* seed) {
527     //MUST be unsorted !!!
528     int idx=(seed->b_ofs-seed->a_ofs)+idxoffset;
529     fList[idx]->addSeed(seed);
530     if (idx>0) fList[idx-1]->addSeed(seed);
531     if (idx<fCount-1) fList[idx+1]->addSeed(seed);
532     }
533     };
534    
535     GXBandSet* collectSeeds_R(GList<GXSeed>& seeds, const char* seqa, int a_len, const char* seqb, int b_len); //overlap of 3' end of seqb
536 gpertea 74 //void collectSeeds_L(GList<GXSeed>& seeds, const char* seqa, const char* seqb); //overlap of 5' end of seqb
537    
538     void printEditScript(GXEditScript* ed_script);
539    
540 gpertea 81
541     // reward MUST be >1, always
542 gpertea 74 GXAlnInfo* GreedyAlignRegion(const char* q_seq, int q_alnstart, int q_max,
543     const char* s_seq, int s_alnstart, int s_max,
544 gpertea 81 bool editscript=false, int reward=2, int penalty=-2, int xdrop=14);
545 gpertea 74 GXAlnInfo* GreedyAlign(const char* q_seq, int q_alnstart, const char* s_seq, int s_alnstart,
546 gpertea 81 bool editscript=false, int reward=2, int penalty=-2, int xdrop=14);
547 gpertea 74
548     #endif