Debian Codegraph @

sim4dbutils/pickUniquePolish-nhgri.C

raw
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <string.h>
5 #include <assert.h>
6
7 #include "bio.h"
8 #include "sim4.H"
9
10 // Kaz Kylheku <[email protected]> library.
11 #include "kazlib/dict.h"
12 #include "kazlib/except.h"
13 #include "kazlib/hash.h"
14 #include "kazlib/list.h"
15 #include "kazlib/sfx.h"
16
17 this is now dead code. It was unused and needed too much effort to update to sim4polishReader
18
19 // Derived from pickBestPolish.c. We report only the single best
20 // match, when it is obvious that there is EXACTLY one best match.
21 //
22 // Example: we have ten matches, but one is 3%id better than everyone
23 // else -- that is an obviously unique match. The rest are noise.
24 //
25 // Example: ten matches, but they're all about the same quality -- within
26 // a few percent id, and about the same length. We pick no match, and
27 // silently discard all.
28 //
29
30 // Modified to:
31 // a) not print out unique matches
32 // b) print hangs
33 // c) print q20 bases inside mapped regions, outside, etc.
34 //
35 // It needs two args -f seq.fasta -q qlt.fasta, both must have an
36 // index -- build it for the seq.fasta, and COPY the index to
37 // qlt.fastaidx. Be sure to 'touch -r seq.fasta qlt.fasta' to get
38 // the same timestamp on the files.
39 //
40 //
41 // Further modified to behave like pickUniquePolish (print unique matches
42 // to a specific file).
43 //
44 // so: pickUniquePolish-nhgri needs to read polishes on stdin
45 // -f qry.fasta -- query sequences for quality comparison
46 // -q qlt.fasta --
47 // -scores X.scores -- write stats to file X
48 // -unique X.bz2 -- write uniquely mapped stuff to bzip2 file X.bz2
49 // -filter X -- filter out polishes less than X% of the longest
50 // -output X.bz2 -- write filtered polishes to bzip2 file X.bz2
51 //
52 // It has two modes:
53 // -f -q -- just compute stats on the input.
54 // all options -- filter, and compute stats.
55 //
56 // bzip2 -dc pass?/map-gen*-qlt$id.sim4db.bz2 |
57 // $bin/fixPolishesIID -c $qry -g $gen |
58 // $bin/filterPolishes -node -D |
59 // $bin/sortPolishes -c -m 768 -t /scratch -v |
60 // $bin/pickUniquePolish-nhgri > all-$id.scores
61 // -o all-$id.sim4db.bz2
62 // -F X
63 // -f $qry
64 // -q $qlt
65 // -stats all-$id.scores |
66 // -uniq all-$id.sim4db.bz2
67
68
69
70 uint32 statOneMatch = 0;
71 uint32 statConsistent = 0;
72 uint32 statInconsistent = 0;
73 uint32 statUnique = 0;
74 uint32 statLost = 0;
75
76 uint32 consistentTie = 0;
77 uint32 consistentMatches = 0;
78 uint32 consistentIdentity = 0;
79 uint32 consistentTooShort = 0;
80 uint32 consistentNot = 0;
81
82 uint32 totLQ = 0;
83 uint32 totMQ = 0;
84 uint32 totRQ = 0;
85
86 seqCache *SEQ = 0L;
87 seqCache *QLT = 0L;
88
89 double filter = 0.0;
90 FILE *oFile = 0L;
91 int oFileIsPipe = 0;
92 FILE *sFile = 0L;
93 FILE *uFile = 0L;
94 bool doFiltering = false;
95
96
97 void
98 analyze(uint32 iid,
99 uint32 clrl,
100 uint32 clrr,
101 uint32 len,
102 bool isForward,
103 char type) {
104
105 seqInCore *Q = QLT->getSequenceInCore(iid);;
106
107 char *q = Q->sequence();
108
109 uint32 i = 0;
110
111 uint32 lq = 0;
112 uint32 mq = 0;
113 uint32 rq = 0;
114
115 for ( ;i<clrl; i++)
116 if (q[i] >= '0' + 20)
117 lq++;
118
119 for ( ;i<clrr; i++)
120 if (q[i] >= '0' + 20)
121 mq++;
122
123 for ( ; i<len; i++)
124 if (q[i] >= '0' + 20)
125 rq++;
126
127 delete Q;
128
129 if (isForward) {
130 totLQ += lq;
131 totMQ += mq;
132 totRQ += rq;
133 } else {
134 totLQ += rq;
135 totMQ += mq;
136 totRQ += lq;
137 }
138
139 fprintf(sFile, uint32FMT"\t"uint32FMT"\t"uint32FMT"\t"uint32FMT"\t"uint32FMT"\t"uint32FMT"\t"uint32FMT"\t%c\n",
140 iid, clrl, clrr, len, lq, mq, rq, type);
141 }
142
143
144 void
145 analyze(sim4polish *p,
146 char type) {
147
148 uint32 clrl = p->_exons[0]._estFrom - 1;
149 uint32 clrr = p->_exons[0]._estTo - 1;
150
151 if (p->_matchOrientation == SIM4_MATCH_COMPLEMENT) {
152 clrl = p->_estLen - (p->_exons[0]._estTo - 1);
153 clrr = p->_estLen - (p->_exons[0]._estFrom - 1);
154 }
155
156 analyze(p->_estID, clrl, clrr, p->_estLen, p->_matchOrientation != SIM4_MATCH_COMPLEMENT, type);
157 }
158
159
160
161 void
162 pickBestSlave(sim4polish **p, uint32 pNum) {
163 uint32 identitym = 0, nmatchesm = 0; // Best score for the mList
164 uint32 identityi = 0, nmatchesi = 0; // Best score the the iList
165 uint32 matchi = 0, matchm = 0;
166
167 // Difficult choice here....
168 //
169 if (pNum == 1) {
170 statOneMatch++;
171 statUnique++;
172
173 if (uFile)
174 p[0]->s4p_printPolish(uFile);
175
176 if (oFile)
177 p[0]->s4p_printPolish(oFile);
178
179 analyze(p[0], 'U');
180
181 return;
182 }
183
184 // Find the best percentIdentity and best numberOfMatches.
185 //
186 // identityi is the best percent identity of all the matches for this EST, and
187 // nmatchesi is the number of matches for the longest best identity match(es).
188 // matchi is the match index
189 //
190 // nmatchesm is the best numMatches of all the matches for this EST, and
191 // identitym is the highest percent identity for the best numMatches match(es).
192 // matchm is the match index
193
194 for (uint32 i=0; i<pNum; i++) {
195 if ((p[i]->_percentIdentity > identityi) ||
196 (p[i]->_percentIdentity == identityi && p[i]->_numMatches > nmatchesi)) {
197 identityi = p[i]->_percentIdentity;
198 nmatchesi = p[i]->_numMatches;
199 matchi = i;
200 }
201
202 if ((p[i]->_numMatches > nmatchesm) ||
203 (p[i]->_numMatches == nmatchesm && p[i]->_percentIdentity > identitym)) {
204 nmatchesm = p[i]->_numMatches;
205 identitym = p[i]->_percentIdentity;
206 matchm = i;
207 }
208 }
209
210
211 bool matchIsOK = false;
212
213 // If we are in agreement on what the best quality match is,
214 // see if the best match is obviously unique.
215 //
216 if ((identityi == identitym) ||
217 (nmatchesi == nmatchesm)) {
218 statConsistent++;
219
220 // It's clear what the quality values of the best match is, but we
221 // don't know if those values are shared by more than one match.
222 // Count the number of matches with exactly those scores. If
223 // there is more than one, then we cannot pick out a single best.
224 //
225 uint32 numBest = 0;
226 for (uint32 i=0; i<pNum; i++)
227 if ((p[i]->_percentIdentity == identityi) && (p[i]->_numMatches == nmatchesi))
228 numBest++;
229
230 if (numBest > 1) {
231
232 // Dang, we mapped this guy more than once, exactly the same!
233 //
234 consistentTie++;
235
236 } else {
237
238 // We claim to have a single best match. See if any other
239 // matches are close to the quality of that one.
240
241 uint32 closeQuality = 0;
242
243 for (uint32 i=0; i<pNum; i++)
244 if (((p[i]->_percentIdentity * 102) >= (identityi * 100)) ||
245 ((p[i]->_numMatches * 102) >= (nmatchesi * 100)))
246 closeQuality++;
247
248 // If only one match has close quality (the one we want to save!),
249 // save it. Otherwise, label this query as multiple.
250
251 uint32 length = p[matchi]->_exons[0]._estFrom - p[matchi]->_exons[0]._estTo;
252
253 if (closeQuality == 1) {
254 matchIsOK = true;
255 consistentMatches++;
256 } else if ((length > 100) &&
257 (length / p[matchi]->_estLen < 0.5)) {
258 consistentTooShort++;
259 } else {
260 consistentNot++;
261 }
262 }
263
264 } else {
265
266 // Otherwise, we disagree on what the best match is.
267 //
268 // That is, the match with the highest identity is not the match
269 // with the highest number of matches -- a longer match exists, but
270 // at lower overall percent identity.
271
272 statInconsistent++;
273
274 // Estimate the identity of the extended part, assuming the piece
275 // matched in common is matched at about the same identity. Or
276 // just give up and say it's mapped to multiple places!
277
278 }
279
280
281 uint32 best = 0;
282 uint32 besti = 0;
283
284 if (matchIsOK) {
285 statUnique++;
286 if (uFile)
287 p[matchi]->s4p_printPolish(uFile);
288
289 assert(matchi == matchm);
290
291 besti = matchi;
292 analyze(p[besti], 'G');
293 } else {
294 statLost++;
295
296 // Just pick the longest match, analyze that.
297
298 for (uint32 i=0; i<pNum; i++) {
299 uint32 len = p[i]->_exons[0]._estFrom - p[i]->_exons[0]._estTo;
300
301 if ((len > best) ||
302 ((len == best) && (p[i]->_numMatches > p[besti]->_numMatches))) {
303 best = len;
304 besti = i;
305 }
306 }
307
308 analyze(p[besti], 'N');
309 }
310
311
312 #if 0
313 uint32 nm = (uint32)(p[besti]->_numMatches * 0.75);
314 uint32 sv = 0;
315
316 for (uint32 i=0; i<pNum; i++)
317 if (p[i]->_numMatches >= nm)
318 sv++;
319
320 fprintf(stderr, "Saved "uint32FMT" matches more than nmatches "uint32FMT" (from best of "uint32FMT")\n", sv, nm, p[besti]->_numMatches);
321 #endif
322
323
324 // besti is the best/longest match we have. Decide on a threshold
325 // to throw out the obvious junk.
326 //
327 if ((oFile) && (doFiltering)) {
328 uint32 nm = (uint32)(p[besti]->_numMatches * filter);
329
330 for (uint32 i=0; i<pNum; i++)
331 if (p[i]->_numMatches >= nm)
332 p[i]->s4p_printPolish(oFile);
333 }
334
335 #if 0
336 fprintf(stderr, "Uni:"uint32FMTW(8)" Con:"uint32FMTW(8)" (T:"uint32FMTW(8)" M:"uint32FMTW(8)" I:"uint32FMTW(8)" N:"uint32FMTW(8)") Inc:"uint32FMTW(8)" -- Save:"uint32FMTW(8)" Lost:"uint32FMTW(8)"\r",
337 statOneMatch,
338 statConsistent, consistentTie, consistentMatches, consistentIdentity, consistentNot,
339 statInconsistent,
340 statUnique, statLost);
341 #endif
342 }
343
344
345
346
347
348
349
350 // Just a wrapper around the real best picker, so that we can easily
351 // destroy polishes when we're done.
352 //
353 void
354 pickBest(sim4polish **p, uint32 pNum) {
355
356 pickBestSlave(p, pNum);
357
358 for (uint32 i=0; i<pNum; i++)
359 delete p[i];
360 }
361
362
363
364
365
366
367
368 dict_t *IIDdict = 0L;
369 dict_t *SEQdict = 0L;
370 dict_t *GENdict = 0L;
371
372 void
373 fixIID(sim4polish *q, dict_t *estdict) {
374
375 // Fix the IID's
376 dnode_t *cid = dict_lookup(estdict, q->_estDefLine);
377 dnode_t *gid = dict_lookup(GENdict, q->_genDefLine);
378
379 if ((cid == 0L) || (gid == 0L)) {
380 const char *msg = "both deflines";
381 if (cid) msg = "genomic defline";
382 if (gid) msg = "est defline";
383
384 q->s4p_printPolish(stdout);
385 fprintf(stderr, "ERROR: Couldn't find %s (%p %p) in the dictionary!\n", msg, cid, gid);
386 exit(1);
387 }
388
389 q->_estID = (uint32)(unsigned long)dnode_get(cid);
390 q->_genID = (uint32)(unsigned long)dnode_get(gid);
391 }
392
393
394
395
396
397
398
399
400
401
402
403 //
404 // Stolen from sortPolishes
405 //
406 int mergeFilesLen;
407 int mergeFilesMax;
408 FILE **mergeFiles;
409 char **mergeNames;
410 sim4polish **mergePolishes;
411
412 sim4polish *
413 nextPolish(void) {
414 int smallestPolish = 0;
415 int nextPolish = 1;
416
417 // If no merge files, read from stdin
418 //
419 if (mergeFilesLen == 0) {
420 return(new sim4polish(stdin));
421 }
422
423 // Find the smallest polish.
424 //
425 for (nextPolish = smallestPolish+1; nextPolish < mergeFilesLen; nextPolish++) {
426 if (s4p_estIDcompare(mergePolishes+smallestPolish, mergePolishes+nextPolish) > 0)
427 smallestPolish = nextPolish;
428 }
429
430 // If the smallestPolish is 0L, we're all done. Otherwise, dump
431 // the current smallest and fill it with a new polish.
432 //
433 if (mergePolishes[smallestPolish] == 0L) {
434 return(0L);
435 } else {
436 sim4polish *ret = mergePolishes[smallestPolish];
437 mergePolishes[smallestPolish] = new sim4polish(mergeFiles[smallestPolish]);
438
439 // fix the iid's to be consistent in our partition, so we can have the input files
440 // sorted by est iid.
441 if (mergePolishes[smallestPolish])
442 fixIID(mergePolishes[smallestPolish], IIDdict);
443
444 // fix the iid's to be consistent globally
445 fixIID(ret, SEQdict);
446
447 return(ret);
448 }
449 }
450
451
452
453
454
455
456
457 //
458 // Stolen from fixPolishesIID
459 //
460 void
461 addToDict(dict_t *d, char *n) {
462 dnode_t *node = 0L;
463 char *dcpy = 0L;
464
465 if (n == 0L)
466 return;
467
468 seqCache *F = new seqCache(n);
469 seqInCore *S = F->getSequenceInCore();
470
471 while (S) {
472 node = (dnode_t *)palloc(sizeof(dnode_t));
473 dcpy = (char *)palloc(sizeof(char) * S->headerLength() + 1);
474
475 strcpy(dcpy, S->header());
476
477 dnode_init(node, (void *)(unsigned long)S->getIID());
478 dict_insert(d, node, dcpy);
479
480 delete S;
481 S = F->getSequenceInCore();
482 }
483 delete F;
484 }
485
486 int
487 headerCompare(const void *a, const void *b) {
488 char *A = *((char **)a);
489 char *B = *((char **)b);
490
491 //fprintf(stderr, "%s -- %s\n", A, B);
492 return(strcmp(A, B));
493 }
494
495
496
497
498
499
500
501
502 int
503 main(int argc, char **argv) {
504 uint32 pNum = 0;
505 uint32 pAlloc = 8388608;
506 uint32 estID = ~uint32ZERO;
507
508 bool *found = 0L;
509
510 // From fixPolishesIID.c
511 IIDdict = 0L;
512 SEQdict = 0L;
513 GENdict = 0L;
514
515 // Incorporated from sortPolishes
516 mergeFilesLen = 0;
517 mergeFilesMax = sysconf(_SC_OPEN_MAX);
518 mergeFiles = new FILE * [mergeFilesMax];
519 mergeNames = new char * [mergeFilesMax];
520 mergePolishes = new sim4polish * [mergeFilesMax];
521
522 // Default to printing stats on stdout.
523 sFile = stdout;
524
525 int arg = 1;
526 while (arg < argc) {
527 if (strcmp(argv[arg], "-n") == 0) {
528 pAlloc = strtouint32(argv[++arg], 0L);
529
530 } else if (strcmp(argv[arg], "-fpart") == 0) {
531 arg++;
532 fprintf(stderr, "reading query deflines from '%s'\n", argv[arg]);
533 IIDdict = dict_create(DICTCOUNT_T_MAX, headerCompare);
534 addToDict(IIDdict, argv[arg]);
535 } else if (strcmp(argv[arg], "-g") == 0) {
536 ++arg;
537 fprintf(stderr, "reading genomic deflines from '%s'\n", argv[arg]);
538 GENdict = dict_create(DICTCOUNT_T_MAX, headerCompare);
539 addToDict(GENdict, argv[arg]);
540 } else if (strcmp(argv[arg], "-F") == 0) {
541 ++arg;
542 fprintf(stderr, "reading query deflines from '%s'\n", argv[arg]);
543 SEQdict = dict_create(DICTCOUNT_T_MAX, headerCompare);
544 addToDict(SEQdict, argv[arg]);
545 } else if (strcmp(argv[arg], "-f") == 0) {
546 ++arg;
547 SEQ = new seqCache(argv[arg]);
548 } else if (strcmp(argv[arg], "-q") == 0) {
549 ++arg;
550 QLT = new seqCache(argv[arg]);
551
552 } else if (strcmp(argv[arg], "-filter") == 0) {
553 filter = atof(argv[++arg]);
554 doFiltering = true;
555 } else if (strcmp(argv[arg], "-output") == 0) {
556 char cmd[1024] = {0};
557 errno = 0;
558 ++arg;
559 if (strcmp(argv[arg] + strlen(argv[arg]) - 4, ".bz2") == 0) {
560 sprintf(cmd, "bzip2 -1c > %s", argv[arg]);
561 oFile = popen(cmd, "w");
562 oFileIsPipe = 1;
563 } else if (strcmp(argv[arg] + strlen(argv[arg]) - 3, ".gz") == 0) {
564 sprintf(cmd, "gzip -1c > %s", argv[arg]);
565 oFile = popen(cmd, "w");
566 oFileIsPipe = 1;
567 } else {
568 fprintf(stderr, "Got %s, not .bz2 not .gz!\n", argv[arg]);
569 exit(1);
570 }
571 if (errno)
572 fprintf(stderr, "Failed to open '%s': %s\n", cmd, strerror(errno));
573 doFiltering = true;
574 } else if (strcmp(argv[arg], "-scores") == 0) {
575 errno = 0;
576 sFile = fopen(argv[++arg], "w");
577 if (errno)
578 fprintf(stderr, "Failed to open '%s': %s\n", argv[arg-1], strerror(errno));
579 doFiltering = true;
580 } else if (strcmp(argv[arg], "-unique") == 0) {
581 char cmd[1024] = {0};
582 errno = 0;
583 arg++;
584 if (strcmp(argv[arg] + strlen(argv[arg]) - 4, ".bz2") == 0)
585 sprintf(cmd, "bzip2 -1c > %s", argv[arg]);
586 else if (strcmp(argv[arg] + strlen(argv[arg]) - 3, ".gz") == 0)
587 sprintf(cmd, "gzip -1c > %s", argv[arg]);
588 else
589 sprintf(cmd, "cat > %s", argv[arg]);
590 uFile = popen(cmd, "w");
591 if (errno)
592 fprintf(stderr, "Failed to open '%s': %s\n", cmd, strerror(errno));
593 doFiltering = true;
594
595 } else if (strncmp(argv[arg], "-M", 2) == 0) {
596 arg++;
597 while ((arg < argc) && (fileExists(argv[arg]))) {
598 if (mergeFilesLen >= mergeFilesMax) {
599 fprintf(stderr, "%s: ERROR! Too many input files! Should be less than %d\n", argv[0], mergeFilesMax);
600 exit(1);
601 }
602 mergeNames[mergeFilesLen] = argv[arg];
603 mergeFiles[mergeFilesLen++] = openFile(argv[arg], "r");
604 arg++;
605 }
606 arg--;
607
608 } else {
609 fprintf(stderr, "unknown option: %s\n", argv[arg]);
610 }
611 arg++;
612 }
613
614
615 if (doFiltering) {
616 if (uFile == 0L)
617 fprintf(stderr, "ERROR: -unique is required\n"), exit(1);
618 if (sFile == 0L)
619 fprintf(stderr, "ERROR: -scores is required\n"), exit(1);
620 if ((filter < 0.0) || (filter > 1.0))
621 fprintf(stderr, "ERROR: -filter value of %f invalid. 0 <= F <= 100.\n", filter), exit(1);
622 }
623
624
625 if ((IIDdict == 0L) || (SEQdict == 0L) || (GENdict == 0L)) {
626 fprintf(stderr, "WARNING! No sequence dictionaries, NOT FIXING IIDs! (supply -fpart, -f and -g)\n");
627 }
628
629
630 if ((SEQ == 0L) || (QLT == 0L)) {
631 fprintf(stderr, "I need -f and -q\n");
632 exit(1);
633 }
634
635 // We no longer require that input polishes be sorted increasingly;
636 // now they only must be grouped. This remembers if we've seen a
637 // match or not. At the end, we'll analyze() those we haven't done
638 // already.
639 //
640 found = new bool [ SEQ->getNumberOfSequences() ];
641 for (uint32 i=0; i<SEQ->getNumberOfSequences(); i++)
642 found[i] = false;
643
644
645 // Initialize the merge -- if no merge files, nothing done!
646 //
647 for (int i=0; i<mergeFilesLen; i++) {
648 mergePolishes[i] = new sim4polish(mergeFiles[i]);
649 fixIID(mergePolishes[i], IIDdict);
650 }
651
652
653 // Read polishes, picking the best when we see a change in the
654 // estID.
655
656 sim4polish **p = new sim4polish * [pAlloc];
657 sim4polish *q;
658
659 while ((q = nextPolish()) != 0L) {
660
661 if ((q->_estID != estID) && (pNum > 0)) {
662 //fprintf(stderr, "PickBest for estID "uint32FMT"\n", estID);
663
664 found[estID] = true;
665 pickBest(p, pNum);
666 pNum = 0;
667 }
668
669 if (pNum >= pAlloc) {
670 sim4polish **P = new sim4polish * [pAlloc * 2];
671 memcpy(p, P, sizeof(sim4polish *) * pAlloc);
672 delete [] p;
673 p = P;
674 pAlloc *= 2;
675 }
676
677 p[pNum++] = q;
678 estID = q->_estID;
679 }
680
681 if (pNum > 0) {
682 found[estID] = true;
683 pickBest(p, pNum);
684 }
685
686 // Attempt cleanup
687 //
688 for (int i=0; i<mergeFilesLen; i++)
689 closeFile(mergeFiles[i], mergeNames[i]);
690
691 for (estID=0; estID < SEQ->getNumberOfSequences(); estID++)
692 if (found[estID] == false)
693 analyze(estID, 0, SEQ->getSequenceLength(estID), SEQ->getSequenceLength(estID), true, 'M');
694
695 delete [] mergeFiles;
696 delete [] mergeNames;
697 delete [] mergePolishes;
698
699 if (oFile) pclose(oFile);
700 if (uFile) pclose(uFile);
701 if (sFile) fclose(sFile);
702
703 fprintf(stderr, "Uni:"uint32FMTW(8)" Con:"uint32FMTW(8)" (T:"uint32FMTW(8)" M:"uint32FMTW(8)" I:"uint32FMTW(8)" S:"uint32FMTW(8)" N:"uint32FMTW(8)") Inc:"uint32FMTW(8)" -- Save:"uint32FMTW(8)" Lost:"uint32FMTW(8)"\n",
704 statOneMatch,
705 statConsistent, consistentTie, consistentMatches, consistentIdentity, consistentTooShort, consistentNot,
706 statInconsistent,
707 statUnique, statLost);
708 fprintf(stderr, "total: LQ:"uint32FMT" MQ:"uint32FMT" RQ:"uint32FMT"\n",
709 totLQ, totMQ, totRQ);
710
711 return(0);
712 }
713