ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/gclib/GAlnExtend.h
Revision: 184
Committed: Thu Feb 16 21:59:44 2012 UTC (7 years, 3 months ago) by gpertea
File size: 24511 byte(s)
Log Message:
works

Line User Rev File contents
1 gpertea 93 #ifndef _GALIGNEXTEND_H
2    
3     //greedy gapped alignment extension
4     //(mostly lifted from NCBI's megablast gapped extension code)
5    
6     #include "GBase.h"
7     #include "GList.hh"
8 gpertea 171 #include "gdna.h"
9 gpertea 93
10 gpertea 106 //#define GDEBUG 1
11 gpertea 93
12     enum {
13     gxEDIT_OP_MASK = 0x3,
14     gxEDIT_OP_ERR = 0x0,
15     gxEDIT_OP_INS = 0x1,
16     gxEDIT_OP_DEL = 0x2,
17     gxEDIT_OP_REP = 0x3
18     };
19    
20     #define GX_EDITOP_VAL(op) ((op) >> 2)
21     #define GX_EDITOP_GET(op) ((op) & gxEDIT_OP_MASK)
22     #define GX_EDITOP_CONS(op, val) (((val) << 2) | ((op) & gxEDIT_OP_MASK))
23    
24     #ifdef GDEBUG
25     enum {c_black=0,
26     c_red, c_green,c_brown,c_blue,c_magenta,c_cyan,c_white
27     };
28    
29     void color_fg(int c, FILE* f=stderr);
30     void color_bg(int c, FILE* f=stderr);
31     void color_resetfg(FILE* f=stderr);
32     void color_resetbg(FILE* f=stderr);
33     void color_reset(FILE* f=stderr);
34     void color_normal(FILE* f=stderr);
35     #endif
36    
37     struct GXEditScript{
38     uint32 *ops; // array of edit operations
39     uint32 opsize, opnum; // size of allocation, number in use
40     uint32 oplast; // most recent operation added
41     //methods
42    
43     GXEditScript() {
44     init();
45     }
46     ~GXEditScript() {
47     GFREE(ops);
48     }
49     void init() {
50     ops = NULL;
51     opsize = 0;
52     opnum = 0;
53     oplast = 0;
54     getReady(8);
55     }
56    
57     int getReady(uint32 n) {
58     uint32 m = n + n/2;
59     if (opsize <= n) {
60     GREALLOC(ops, m*sizeof(uint32));
61     opsize = m;
62     }
63     return 1;
64     }
65    
66     int getReady2(uint32 n) {
67     if (opsize - opnum <= n)
68     return getReady(n + opnum);
69     return 1;
70     }
71    
72     int Put(uint32 op, uint32 n) {
73     if (!getReady2(2))
74     return 0;
75     oplast = op;
76     ops[opnum] = GX_EDITOP_CONS(op, n);
77     opnum += 1;
78     ops[opnum] = 0; // sentinel
79     return 1;
80     }
81     uint32* First() {
82     return opnum > 0 ? & ops[0] : NULL;
83     }
84    
85     uint32* Next(uint32 *op) {
86     // assumes flat address space !
87     if (&ops[0] <= op && op < &ops[opnum-1])
88     return op+1;
89     else
90     return 0;
91     }
92    
93     int More(uint32 op, uint32 k) {
94     if (op == gxEDIT_OP_ERR) {
95     GError("GXEditScript::opMore: bad opcode %d:%d", op, k);
96     return -1;
97     }
98    
99     if (GX_EDITOP_GET(oplast) == op) {
100     uint32 l=ops[opnum-1];
101 gpertea 171 ops[opnum-1]=GX_EDITOP_CONS((GX_EDITOP_GET(l)),
102 gpertea 93 (GX_EDITOP_VAL(l) + k));
103     }
104     else {
105     Put(op, k);
106     }
107    
108     return 0;
109     }
110    
111     GXEditScript* Append(GXEditScript *et) {
112     uint32 *op;
113     for (op = et->First(); op; op = et->Next(op))
114     More(GX_EDITOP_GET(*op), GX_EDITOP_VAL(*op));
115     return this;
116     }
117    
118     int opDel(uint32 k) {
119     return More(gxEDIT_OP_DEL, k);
120     }
121     int opIns(uint32 k) {
122     return More(gxEDIT_OP_INS, k);
123     }
124     int opRep(uint32 k) {
125     return More(gxEDIT_OP_REP, k);
126     }
127    
128     GXEditScript *reverse() {
129     const uint32 mid = opnum/2;
130     const uint32 end = opnum-1;
131     for (uint32 i = 0; i < mid; ++i) {
132     const uint32 t = ops[i];
133     ops[i] = ops[end-i];
134     ops[end-i] = t;
135     }
136     return this;
137     }
138     };
139    
140    
141     /** Bookkeeping structure for greedy alignment. When aligning
142     two sequences, the members of this structure store the
143     largest offset into the second sequence that leads to a
144     high-scoring alignment for a given start point */
145     struct SGreedyOffset {
146     int insert_off; // Best offset for a path ending in an insertion
147     int match_off; // Best offset for a path ending in a match
148     int delete_off; // Best offset for a path ending in a deletion
149     };
150    
151     // ----- pool allocator -----
152     // works as a linked list of allocated memory blocks
153     struct GXMemPool {
154     SGreedyOffset* memblock;
155     int used, size;
156     GXMemPool *next;
157     static int kMinSpace;
158     //methods
159     GXMemPool(int num_offsp=0) { //by default allocate a large block here (10M)
160     num_offsp=GMAX(kMinSpace, num_offsp);
161     GMALLOC(memblock, num_offsp*sizeof(SGreedyOffset));
162     if (memblock == NULL) {
163     GError("Failed to allocated GXMemPool(%d) for greedy extension!\n",num_offsp);
164     return;
165     }
166     used = 0;
167     size = num_offsp;
168     next = NULL;
169     }
170    
171     void refresh() {
172     GXMemPool* sp=this;
173     while (sp) {
174     sp->used = 0;
175     sp = sp->next;
176     }
177     }
178     ~GXMemPool() {
179     GXMemPool* next_sp;
180     GXMemPool* sp=this->next;
181     while (sp) {
182     next_sp = sp->next;
183     GFREE(sp->memblock);
184     delete sp;
185     sp = next_sp;
186     }
187     GFREE(memblock);
188     }
189    
190     SGreedyOffset* getSpace(int num_alloc) { // SGreedyOffset[num_alloc] array
191     //can use the first found memory block with enough room,
192     // or allocate a new large block
193     SGreedyOffset* v;
194     if (num_alloc < 0) return NULL;
195     GXMemPool* S=this;
196     while (used+num_alloc > S->size) {
197     //no room in current block, get a new mem block
198     if (next == NULL) {
199     next=new GXMemPool(num_alloc); //allocates a large contiguous memory block
200     }
201     S = S->next;
202     }
203     v = S->memblock+S->used;
204     S->used += num_alloc;
205     //align to first 8-byte boundary
206     int m8 = S->used & 7; //modulo 8
207     if (m8)
208     S->used += 8 - m8;
209     return v;
210     }
211    
212     void* getByteSpace(int byte_size) { //amount to use or allocate memory, in bytes
213     return (void*)getSpace(byte_size/sizeof(SGreedyOffset));
214     }
215    
216     };
217    
218 gpertea 109 #define GREEDY_MAX_COST_FRACTION 8
219 gpertea 93 /* (was 2) sequence_length / (this number) is a measure of how hard the
220     alignment code will work to find the optimal alignment; in fact
221     this gives a worst case bound on the number of loop iterations */
222    
223     #define GREEDY_MAX_COST 1000
224     // The largest diff distance (max indels+mismatches) to be examined for an optimal alignment
225     // (should be increased for large sequences)
226    
227     #define GX_GALLOC_ERROR "Error: failed to allocate memory for greedy alignment!\n"
228    
229     // all auxiliary memory needed for the greedy extension algorithm
230 gpertea 101 class CGreedyAlignData {
231     int d_diff;
232     int max_d;
233     public:
234 gpertea 93 int** last_seq2_off; // 2-D array of distances
235     int* max_score; // array of maximum scores
236     GXMemPool* space; // local memory pool for SGreedyOffset structs
237 gpertea 101 //
238     int match_reward;
239     int mismatch_penalty;
240     int x_drop;
241 gpertea 93 // Allocate memory for the greedy gapped alignment algorithm
242 gpertea 101 CGreedyAlignData(int reward, int penalty, int xdrop) {
243 gpertea 93 //int max_d, diff_d;
244     if (penalty<0) penalty=-penalty;
245     if (reward % 2) {
246     //scale params
247 gpertea 101 match_reward = reward << 1;
248     mismatch_penalty = (penalty << 1);
249     x_drop = xdrop<<1;
250 gpertea 93 }
251 gpertea 101 else {
252     match_reward=reward;
253     mismatch_penalty = penalty;
254     x_drop=xdrop;
255     }
256 gpertea 93 //if (gap_open == 0 && gap_extend == 0)
257     // gap_extend = (reward >> 1) + penalty;
258     const int max_dbseq_length=255; //adjust this accordingly
259     max_d = GMIN(GREEDY_MAX_COST,
260     (max_dbseq_length/GREEDY_MAX_COST_FRACTION + 1));
261    
262     last_seq2_off=NULL; // 2-D array of distances
263     max_score=NULL; // array of maximum scores
264     space=NULL; // local memory pool for SGreedyOffset structs
265     //if (score_params.gap_open==0 && score_params.gap_extend==0) {
266     //non-affine, simpler Greedy algorithm
267 gpertea 101 d_diff = (x_drop+match_reward/2)/(mismatch_penalty+match_reward)+1;
268 gpertea 93 GMALLOC(last_seq2_off, ((max_d + 2) * sizeof(int*)));
269     if (!last_seq2_off)
270     GError(GX_GALLOC_ERROR);
271     GCALLOC(last_seq2_off[0], ((max_d + max_d + 6) * sizeof(int) * 2));
272     //allocates contiguous memory for 2 rows here
273     if (!last_seq2_off[0])
274     GError(GX_GALLOC_ERROR);
275     last_seq2_off[1] = last_seq2_off[0] + max_d + max_d + 6; //memory allocated already for this row
276    
277     GCALLOC(max_score, (sizeof(int) * (max_d + 1 + d_diff)));
278     space = new GXMemPool();
279     if (!max_score || !space)
280     GError(GX_GALLOC_ERROR);
281     } //consructor
282    
283     void reset() {
284     space->refresh();
285     if (last_seq2_off) {
286     GFREE((last_seq2_off[0]));
287     }
288     GFREE(max_score);
289     GCALLOC(last_seq2_off[0], ((max_d + max_d + 6) * sizeof(int) * 2));
290     if (!last_seq2_off[0]) GError(GX_GALLOC_ERROR);
291     //allocates contiguous memory for 2 rows here
292     last_seq2_off[1] = last_seq2_off[0] + max_d + max_d + 6;
293     GCALLOC(max_score, (sizeof(int) * (max_d + 1 + d_diff)));
294     if (!max_score) GError(GX_GALLOC_ERROR);
295     }
296 gpertea 101 ~CGreedyAlignData() {
297 gpertea 93 if (last_seq2_off) {
298     GFREE(last_seq2_off[0]);
299     GFREE(last_seq2_off);
300     }
301     GFREE(max_score);
302     delete space;
303     }
304    
305     };
306    
307    
308     #define GAPALIGN_SUB ((unsigned char)0) /*op types within the edit script*/
309     #define GAPALIGN_INS ((unsigned char)1)
310     #define GAPALIGN_DEL ((unsigned char)2)
311     #define GAPALIGN_DECLINE ((unsigned char)3)
312    
313     struct GapXEditScript {
314     unsigned char op_type; // GAPALIGN_SUB, GAPALIGN_INS, or GAPALIGN_DEL
315     int num; // Number of operations
316     GapXEditScript* next;
317     GapXEditScript() {
318     op_type=0;
319     num=0;
320     next=NULL;
321     }
322     void print();
323     };
324    
325     class CSeqGap { //
326     public:
327     int offset;
328     int len;
329     CSeqGap(int gofs=0,int glen=1) {
330     offset=gofs;
331     len=glen;
332     }
333     };
334    
335     class CAlnGapInfo {
336     int a_ofs; //alignment start on seq a (0 based)
337     int b_ofs; //alignment start on seq b (0 based)
338     int a_len; //length of alignment on seq a
339     int b_len; //length of alignment on seq b
340     public:
341     GVec<CSeqGap> a_gaps;
342     GVec<CSeqGap> b_gaps;
343     CAlnGapInfo(GXEditScript* ed_script, int astart=0, int bstart=0):a_gaps(),b_gaps() {
344     a_ofs=astart;
345     b_ofs=bstart;
346     a_len=0;
347     b_len=0;
348     if (ed_script==NULL) return;
349 gpertea 173 for (uint32 i=0; i<ed_script->opnum; i++) {
350 gpertea 93 int num=((ed_script->ops[i]) >> 2);
351     char op_type = 3 - ( ed_script->ops[i] & gxEDIT_OP_MASK );
352     if (op_type == 3 || op_type < 0 )
353     GError("Error: encountered op_type %d in ed_script?!\n", (int)op_type);
354     CSeqGap gap;
355     switch (op_type) {
356     case GAPALIGN_SUB: a_len+=num;
357     b_len+=num;
358     break;
359     case GAPALIGN_INS: a_len+=num;
360     gap.offset=b_ofs+b_len;
361     gap.len=num;
362     b_gaps.Add(gap);
363     break;
364     case GAPALIGN_DEL: b_len+=num;
365     gap.offset=a_ofs+a_len;
366     gap.len=num;
367     a_gaps.Add(gap);
368     break;
369     }
370     }
371     }
372    
373     #ifdef GDEBUG
374 gpertea 171 void printAlignment(FILE* f, const char* sa, int sa_len,
375 gpertea 93 const char* sb, int sb_len) {
376     //print seq A
377     char al[1024]; //display buffer for seq A
378     int ap=0; //index in al[] for current character printed
379     int g=0;
380     int aend=a_ofs+a_len;
381     if (a_ofs<b_ofs) {
382     for (int i=0;i<b_ofs-a_ofs;i++) {
383     fprintf(f, " ");
384     al[++ap]=' ';
385     }
386     }
387     for (int i=0;i<aend;i++) {
388     if (g<a_gaps.Count() && a_gaps[g].offset==i) {
389     for (int j=0;j<a_gaps[g].len;j++) {
390     fprintf(f, "-");
391     al[++ap]='-';
392     }
393     g++;
394     }
395     if (i==a_ofs) color_bg(c_blue,f);
396     fprintf(f, "%c", sa[i]);
397     al[++ap]=sa[i];
398     }
399     color_reset(f);
400     if (aend<sa_len)
401     fprintf(f, &sa[aend]);
402     fprintf(f, "\n");
403     //print seq B
404     ap=0;
405     g=0;
406     int bend=b_ofs+b_len;
407     if (a_ofs>b_ofs) {
408     for (int i=0;i<a_ofs-b_ofs;i++) {
409     fprintf(f, " ");
410     ap++;
411     }
412     }
413     for (int i=0;i<b_ofs;i++) {
414     fprintf(f, "%c", sb[i]);
415     ap++;
416     }
417     for (int i=b_ofs;i<bend;i++) {
418     if (g<b_gaps.Count() && b_gaps[g].offset==i) {
419     for (int j=0;j<b_gaps[g].len;j++) {
420     fprintf(f, "-");
421     ap++;
422     }
423     g++;
424     }
425     if (i==b_ofs) color_bg(c_blue,f);
426     ap++;
427     bool mismatch=(sb[i]!=al[ap] && al[ap]!='-');
428     if (mismatch) color_bg(c_red,f);
429     fprintf(f, "%c", sb[i]);
430     if (mismatch) color_bg(c_blue,f);
431     }
432     color_reset(f);
433     if (bend<sb_len)
434     fprintf(f, &sb[bend]);
435     fprintf(f, "\n");
436     }
437     #endif
438     };
439 gpertea 171
440 gpertea 93 struct GXAlnInfo {
441     const char *qseq;
442     int ql,qr;
443     const char *sseq;
444     int sl,sr;
445     int score;
446     double pid;
447 gpertea 184 bool strong;
448 gpertea 93 GXEditScript* editscript;
449     CAlnGapInfo* gapinfo;
450     GXAlnInfo(const char* q, int q_l, int q_r, const char* s, int s_l, int s_r,
451     int sc=0, double percid=0) {
452     qseq=q;
453     sseq=s;
454     ql=q_l;
455     qr=q_r;
456     sl=s_l;
457     sr=s_r;
458     score=sc;
459     pid=percid;
460 gpertea 184 strong=false;
461 gpertea 93 editscript=NULL;
462     gapinfo=NULL;
463     }
464     ~GXAlnInfo() {
465     delete editscript;
466     delete gapinfo;
467     }
468     bool operator<(GXAlnInfo& d) {
469     return ((score==d.score)? pid>d.pid : score>d.score);
470     }
471     bool operator==(GXAlnInfo& d) {
472     return (score==d.score && pid==d.pid);
473     }
474    
475     };
476    
477    
478    
479     struct GXSeed {
480     int b_ofs; //0-based coordinate on seq b (x coordinate)
481     int a_ofs; //0-based coordinate on seq a (y coordinate)
482     int len; //length of exact match after extension
483     bool operator<(GXSeed& d){
484     return ((b_ofs==d.b_ofs) ? a_ofs<d.a_ofs : b_ofs<d.b_ofs);
485     }
486     bool operator==(GXSeed& d){
487     return (b_ofs==d.b_ofs && a_ofs==d.a_ofs); //should never be the case, seeds are uniquely constructed
488     }
489     GXSeed(int aofs=0, int bofs=0, int l=4) {
490     a_ofs=aofs;
491     b_ofs=bofs;
492     len=l;
493     }
494     };
495    
496     int cmpSeedDiag(const pointer p1, const pointer p2);
497     //seeds are "equal" if they're on the same diagonal (for selection purposes only)
498    
499     int cmpSeedScore(const pointer p1, const pointer p2); //also takes position into account
500     //among seeds with same length, prefer those closer to the left end of the read (seq_b)
501    
502     struct GXBand {
503     //bundle of seed matches on 3 adjacent diagonals
504     int diag; //first anti-diagonal (b_ofs-a_ofs) in this group of 3
505     //seeds for this, and diag+1 and diag+2 are stored here
506     int min_a, max_a; //maximal coordinates of the bundle
507     int min_b, max_b;
508 gpertea 101 int w_min_b; //weighted average of left start coordinate
509     int avg_len;
510 gpertea 93 GList<GXSeed> seeds; //sorted by x coordinate (b_ofs)
511     int score; //sum of seed scores (- overlapping_bases/2 - gaps)
512 gpertea 101 bool tested;
513 gpertea 93 GXBand(int start_diag=-1, GXSeed* seed=NULL):seeds(true, false, false) {
514     diag=start_diag;
515     min_a=MAX_INT;
516     min_b=MAX_INT;
517     max_a=0;
518     max_b=0;
519     score=0;
520 gpertea 101 avg_len=0;
521     w_min_b=0;
522     tested=false;
523 gpertea 93 if (seed!=NULL) addSeed(seed);
524     }
525     void addSeed(GXSeed* seed) {
526     seeds.Add(seed);
527     score+=seed->len;
528 gpertea 101 avg_len+=seed->len;
529     w_min_b+=seed->b_ofs * seed->len;
530 gpertea 93 //if (diag<0) diag=seed->diag; //should NOT be done like this
531     if (seed->a_ofs < min_a) min_a=seed->a_ofs;
532     if (seed->a_ofs+ seed->len > max_a) max_a=seed->a_ofs+seed->len;
533     if (seed->b_ofs < min_b) min_b=seed->b_ofs;
534     if (seed->b_ofs+seed->len > max_b) max_b=seed->b_ofs+seed->len;
535     }
536 gpertea 101
537 gpertea 93 void finalize() {
538     //!! to be called only AFTER all seeds have been added
539     // seeds are sorted by b_ofs
540     //penalize seed gaps and overlaps on b sequence
541 gpertea 101 if (avg_len==0) return;
542     w_min_b/=avg_len;
543     avg_len>>=1;
544 gpertea 93 for (int i=1;i<seeds.Count();i++) {
545     GXSeed& sprev=*seeds[i-1];
546     GXSeed& scur=*seeds[i];
547     if (scur==sprev) GError("Error: duplicate seeds found (%d-%d:%d-%d)!\n",
548     scur.a_ofs+1, scur.a_ofs+scur.len, scur.b_ofs+1, scur.b_ofs+scur.len);
549     int b_gap=scur.b_ofs-sprev.b_ofs-sprev.len;
550     int a_gap=scur.a_ofs-sprev.a_ofs-sprev.len;
551     int max_gap=b_gap;
552     int min_gap=a_gap;
553 gpertea 144 if (min_gap>max_gap) Gswap(max_gap, min_gap);
554 gpertea 101 int _penalty=0;
555 gpertea 93 if (min_gap<0) { //overlap
556 gpertea 101 if (max_gap>0) { _penalty=GMAX((-min_gap), max_gap); }
557     else _penalty=-min_gap;
558 gpertea 93 }
559     else { //gap
560 gpertea 101 _penalty=max_gap;
561 gpertea 93 }
562 gpertea 101 score-=(_penalty>>1);
563     //score-=_penalty;
564     }//for each seed
565 gpertea 93 }
566    
567     //bands will be sorted by decreasing score eventually, after all seeds are added
568     //more seeds better than one longer seed?
569     bool operator<(GXBand& d){
570 gpertea 101 //return ((score==d.score) ? seeds.Count()>d.seeds.Count() : score>d.score);
571     return ((score==d.score) ? w_min_b<d.w_min_b : score>d.score);
572 gpertea 93 }
573     bool operator==(GXBand& d){
574 gpertea 101 //return (score==d.score && seeds.Count()==d.seeds.Count());
575     return (score==d.score && w_min_b==d.w_min_b);
576 gpertea 93 }
577    
578     };
579    
580     class GXBandSet:public GList<GXBand> {
581     public:
582 gpertea 99 GXSeed* qmatch; //long match (mismatches allowed) if a very good match was extended well
583 gpertea 178 GXSeed* tmatch_r; //terminal match to be used if there is no better alignment
584     GXSeed* tmatch_l; //terminal match to be used if there is no better alignment
585 gpertea 93 int idxoffset; //global anti-diagonal->index offset (a_len-1)
586     //used to convert a diagonal to an index
587     //diagonal is always b_ofs-a_ofs, so the minimum value is -a_len+1
588     //hence offset is a_len-1
589     GXBand* band(int diag) { //retrieve the band for given anti-diagonal (b_ofs-a_ofs)
590     return Get(diag+idxoffset);
591     }
592     GXBand* band(int a_ofs, int b_ofs) { //retrieve the band for given anti-diagonal (b_ofs-a_ofs)
593     return Get(b_ofs-a_ofs+idxoffset);
594     }
595     GXBandSet(int a_len, int b_len):GList<GXBand>(a_len+b_len-1, false, true, false) {
596     idxoffset=a_len-1;
597 gpertea 99 qmatch=NULL;
598 gpertea 178 tmatch_l=NULL; //terminal match to be used if everything else fails
599     tmatch_r=NULL;
600 gpertea 93 //diag will range from -a_len+1 to b_len-1, so after adjustment
601     //by idxoffset we get a max of a_len+b_len-2
602     int bcount=a_len+b_len-1;
603     for (int i=0;i<bcount;i++)
604 gpertea 174 this->Add(new GXBand(i-idxoffset));
605 gpertea 93 //unsorted, this should set fList[i]
606     }
607 gpertea 99 ~GXBandSet() {
608     delete qmatch;
609     }
610 gpertea 93 void addSeed(GXSeed* seed) {
611     //MUST be unsorted !!!
612     int idx=(seed->b_ofs-seed->a_ofs)+idxoffset;
613     fList[idx]->addSeed(seed);
614     if (idx>0) fList[idx-1]->addSeed(seed);
615     if (idx<fCount-1) fList[idx+1]->addSeed(seed);
616     }
617     };
618    
619 gpertea 176 struct GXSeqData {
620     const char* aseq;
621     int alen;
622     const char* bseq;
623     int blen;
624     GVec<uint16>** amers;
625     int amlen; //minimum alignment length that's sufficient to
626     //trigger the quick extension heuristics
627     GXSeqData(const char* sa=NULL, int la=0, const char* sb=NULL, int lb=0,
628     GVec<uint16>* mers[]=NULL):aseq(sa), alen(la),
629     bseq(sb), blen(lb), amers(mers), amlen(0) {
630     calc_amlen();
631     calc_bmlen();
632     }
633     void calc_amlen() {
634     if (alen) {
635     int ah=iround(double(alen)*0.8);
636     if (ah<12) ah=12;
637     if (amlen>ah) amlen=ah;
638     }
639     }
640     void calc_bmlen() {
641     if (blen) {
642     int bh = iround(double(alen)*0.6);
643     if (bh<12) bh=12;
644     if (amlen>bh) amlen=bh;
645     }
646     }
647     void update(const char* sa, int la, GVec<uint16>** mers,
648     const char* sb, int lb, int mlen=0) {
649     aseq=sa;
650     alen=la;
651     amers=mers;
652     if (mlen) {
653     amlen=mlen;
654     }
655     else calc_amlen();
656     if (sb==bseq && blen==lb) return;
657     bseq=sb;
658     blen=lb;
659     calc_bmlen();
660     }
661     /*
662     void update_b(const char* sb, int lb) {
663     if (sb==bseq && blen==lb) return;
664     bseq=sb;
665     blen=lb;
666     calc_bmlen();
667     }*/
668     };
669 gpertea 93
670 gpertea 171 uint16 get6mer(char* p);
671 gpertea 173 void table6mers(const char* s, int slen, GVec<uint16>* amers[]);
672 gpertea 93
673 gpertea 178 //GXBandSet* collectSeeds_R(GList<GXSeed>& seeds, GXSeqData& sd); //for overlap at 3' end of seqb
674 gpertea 93
675 gpertea 178 GXBandSet* collectSeeds(GList<GXSeed>& seeds, GXSeqData& sd); //for overlap at 5' end of seqb
676 gpertea 171
677 gpertea 93 void printEditScript(GXEditScript* ed_script);
678    
679    
680     int GXGreedyExtend(const char* seq1, int len1,
681     const char* seq2, int len2,
682     bool reverse, int xdrop_threshold,
683     int match_cost, int mismatch_cost,
684     int& seq1_align_len, int& seq2_align_len,
685 gpertea 101 CGreedyAlignData& aux_data,
686 gpertea 93 GXEditScript *edit_block);
687    
688    
689     enum GAlnTrimType {
690 gpertea 181 //Describes trimming intent
691     galn_None=0, //no trimming, just alignment
692 gpertea 93 galn_TrimLeft,
693 gpertea 181 galn_TrimRight,
694     galn_TrimEither //adaptor should be trimmed from either end
695 gpertea 93 };
696    
697 gpertea 101 struct CAlnTrim {
698     GAlnTrimType type;
699 gpertea 181 int l_boundary; //base index (either left or right) excluding terminal poly-A stretches
700     int r_boundary; //base index (either left or right) excluding terminal poly-A stretches
701     int alen; //query/adaptor seq length (for validate())
702 gpertea 176 int safelen; //alignment length > amlen should be automatically validated
703     int seedlen;
704     void prepare(const char* s, int s_len) {
705     //type=trim_type;
706     //amlen=smlen;
707 gpertea 181 l_boundary=0;
708     r_boundary=0;
709     //if (type==galn_TrimLeft) {
710 gpertea 101 int s_lbound=0;
711     if (s[0]=='A' && s[1]=='A' && s[2]=='A') {
712     s_lbound=3;
713     while (s_lbound<s_len-1 && s[s_lbound]=='A') s_lbound++;
714     }
715     else if (s[1]=='A' && s[2]=='A' && s[3]=='A') {
716     s_lbound=4;
717     while (s_lbound<s_len-1 && s[s_lbound]=='A') s_lbound++;
718     }
719 gpertea 181 l_boundary=s_lbound+3;
720     // return;
721     // }
722     //if (type==galn_TrimRight) {
723 gpertea 101 int r=s_len-1;
724     if (s[r]=='A' && s[r-1]=='A' && s[r-2]=='A') {
725     r-=3;
726     while (r>0 && s[r]=='A') r--;
727     }
728     else if (s[r-1]=='A' && s[r-2]=='A' && s[r-3]=='A') {
729     r-=4;
730     while (r>0 && s[r]=='A') r--;
731     }
732 gpertea 181 r_boundary=r-3;
733     // }
734 gpertea 101 }
735    
736 gpertea 181 CAlnTrim(GAlnTrimType trim_type, const char* s, int s_len, int a_len, int smlen):
737     type(trim_type), l_boundary(0), r_boundary(0), alen(a_len), safelen(smlen) {
738 gpertea 176 prepare(s, s_len);
739 gpertea 101 }
740    
741 gpertea 181 bool validate_R(int sr, int admax, int badj, int adist) {
742     if (adist>admax) return false;
743     return (sr>=r_boundary+badj);
744     }
745 gpertea 184
746 gpertea 181 bool validate_L(int sl, int alnlen, int admax, int badj, int alnpid, int adist) {
747     if (adist>admax) return false;
748     //left match should be more stringent (5')
749     if (alnpid<93) {
750     if (alnlen<13) return false;
751     admax=0;
752     badj++;
753     }
754     return (sl<=l_boundary-badj);
755     }
756    
757     bool validate(GXAlnInfo* alninfo) {
758     int alnlen=alninfo->sr - alninfo->sl + 1;
759 gpertea 184 if (alninfo->pid>90.0 && alnlen>safelen) {
760 gpertea 181 //special case: heavy match, could be in the middle
761 gpertea 184 if (alninfo->pid>95) alninfo->strong=true;
762 gpertea 181 return true;
763 gpertea 184 }
764 gpertea 181 int sl=alninfo->sl;
765     int sr=alninfo->sr;
766 gpertea 101 sl--;sr--; //boundary is 0-based
767 gpertea 109 int badj=0; //default boundary is 3 bases distance to end
768     int admax=1;
769     if (alnlen<13) {
770 gpertea 101 //stricter boundary check
771 gpertea 181 if (alninfo->pid<90) return false;
772 gpertea 101 badj=2;
773 gpertea 109 if (alnlen<=7) { badj++; admax=0; }
774 gpertea 101 }
775 gpertea 181 if (type==galn_TrimLeft) {
776     return validate_L(sl, alnlen, admax, badj, alninfo->pid, alen-alninfo->qr);
777     }
778     else if (type==galn_TrimRight) {
779     return validate_R(sr, admax, badj, alninfo->ql-1);
780     }
781     else if (type==galn_TrimEither) {
782     return (validate_R(sr, admax, badj, alninfo->ql-1) ||
783     validate_L(sl, alnlen, admax, badj, alninfo->pid, alen-alninfo->qr));
784     }
785     return true;
786     /*
787 gpertea 101 if (type==galn_TrimRight) {
788     return (sr>=boundary+badj);
789     }
790     else {
791 gpertea 109 //left match should be more stringent (5')
792     if (alnpid<93) {
793     if (alnlen<13) return false;
794     admax=0;
795 gpertea 101 badj++;
796     }
797     return (sl<=boundary-badj);
798     }
799 gpertea 181 */
800 gpertea 101 }
801     };
802    
803    
804 gpertea 93 // reward MUST be >1, always
805     GXAlnInfo* GreedyAlignRegion(const char* q_seq, int q_alnstart, int q_max,
806 gpertea 101 const char* s_seq, int s_alnstart, int s_max,
807     int reward, int penalty, int xdrop, CGreedyAlignData* gxmem=NULL,
808     CAlnTrim* trim=NULL, bool editscript=false);
809     GXAlnInfo* GreedyAlignRegion(const char* q_seq, int q_alnstart, int q_max,
810     const char* s_seq, int s_alnstart, int s_max, CGreedyAlignData* gxmem,
811     CAlnTrim* trim=NULL, bool editscript=false);
812    
813 gpertea 93 GXAlnInfo* GreedyAlign(const char* q_seq, int q_alnstart, const char* s_seq, int s_alnstart,
814     bool editscript=false, int reward=2, int penalty=3, int xdrop=8);
815    
816 gpertea 181 GXAlnInfo* match_adaptor(GXSeqData& sd, GAlnTrimType trim_type,
817     CGreedyAlignData* gxmem=NULL, int min_pid=90);
818     //GXAlnInfo* match_RightEnd(GXSeqData& sd, CGreedyAlignData* gxmem=NULL, int min_pid=90);
819 gpertea 93 #endif