Debian Codegraph @

atac-driver/chainer/python/AtacDriver.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python
2
3 """
4 The environmental variable "PYTHONPATH" is a colon separated list
5 of directories of imported Python modules (*.py) and C/C++ shared
6 libraries (*.so for Unix or *.dll for Windows).
7
8 Written by Clark Mobarry, Applied Biosystems, 2002-2004.
9 """
10
11 """
12 Known issues:
13 (1) I need to remove from parameters from the output: /inpname=, /outname=,.
14 (4) The checkpointing scheme assumes that a previous existing checkpoint file is GOOD.
15 """
16
17 import os, sys, time, getopt, tempfile
18 import MyFile
19 import MatchRecord
20 import AtacFile
21 import IdxStore
22 import UniqueFilter
23 import PerfectRuns
24 import TrimMatchOverlaps
25 import squeezeIntraRunGaps
26 import localAlignerInterface
27 import fillIntraRunGaps
28
29 #import dedashMatches
30
31 STDERR=sys.stderr
32 STDOUT=sys.stdout
33
34 def die(message):
35 print >>STDERR, message
36 os.exit(1)
37
38 def cvm(f,x,y):
39 # A cvm variant (flag ? y : x) = (x,y)[f]
40 if f :
41 return x
42 else:
43 return y
44 # end if
45 # end def
46
47
48
49 class GlobalParam:
50 def __init__(self,line):
51 pass
52 def __str__ (self):
53 return "/%s=%s" % (self._key,self._value)
54 def get(self):
55 return (self._key,self._value)
56 def put(self,key,value):
57 (self._key,self._value) = (key,value)
58
59
60 def usage (*_):
61 print >>STDERR, "Usage: atacdriver.py matchFilePrefix"
62 # end def
63
64 def filterByMatchLength( inpfile, outfile, minimum_length):
65 "Only keep matches that are long enough."
66 inpfile.seek(0)
67 for line in inpfile:
68 if(line[0] == 'M'):
69 FM = MatchRecord.MatchRecord(line)
70 if (FM.x_length >= minimum_length and
71 FM.y_length >= minimum_length ):
72 print >>outfile, FM
73 # end if
74 # end if
75 # end for
76 # end def
77
78
79 def onlyKeepLongRuns ( inpfile, outname, lengthThreshold ):
80 outfile = MyFile.myfile()
81 rejectsfile = MyFile.myfile()
82
83 FL = None
84 store = []
85 lenInMatches = 0
86 inpfile.seek(0)
87 for line in inpfile:
88 if(line[0] == 'M'):
89 FM = MatchRecord.MatchRecord(line)
90 SL = FM.x_length
91 if FL != None and FL.runid != FM.runid :
92 for x in store:
93 print >>rejectsfile, x
94 # end for
95 store = []
96 lenInMatches = SL
97 else:
98 lenInMatches += SL
99 # end if
100
101 if lenInMatches < lengthThreshold:
102 store.append(FM)
103 else:
104 for x in store:
105 print >>outfile, x
106 # end for
107 store = []
108 print >>outfile, FM
109 # end if
110 FL = FM
111 # end if
112 # end for
113 rejectsfile.close()
114 return outfile
115 # end def
116
117 def coalesceMatches ( inpfile, outfile, needs_to_share_diagonal ):
118 "Coalesce overlapping and abutting matches within the same run."
119
120 firstF = None
121 lastF = None
122
123 lastLX = -3
124 lastLY = -4
125 lastForward = 0
126
127 lowHitPX = None
128 lowHitPY = None
129 hghHitPX = None
130 hghHitPY = None
131 inpfile.seek(0)
132 outfile.seek(0)
133 for line in inpfile:
134 if(line[0] == 'M'):
135 curF = MatchRecord.MatchRecord(line)
136 px = curF.x_start
137 nx = curF.x_length
138 py = curF.y_start
139 ny = curF.y_length
140 assert(px >= 0)
141 assert(nx >= 0)
142 assert(py >= 0)
143 assert(ny >= 0)
144 if (not (not needs_to_share_diagonal or nx == ny)):
145 print >>STDERR, 'Bombed on:'
146 print >>STDERR, str(curF)
147 print >>STDERR, 'needs_to_share_diagonal=' + str(needs_to_share_diagonal)
148 print >>STDERR, 'nx=' + str(nx) + ' ny=' + str(ny)
149 # end if
150 assert((hghHitPX == None or (not needs_to_share_diagonal) or nx == ny))
151 forward = (curF.x_orientation == curF.y_orientation)
152 lx = px
153 ly = cvm( forward, py, py + ny)
154 rx = px + nx
155 ry = cvm( forward, py + ny, py)
156
157 overlapping = ((lastF != None) and
158 (curF.x_scaf_uid == lastF.x_scaf_uid) and
159 (curF.y_scaf_uid == lastF.y_scaf_uid) and
160 (((lx >= lowHitPX and lx <= hghHitPX) and
161 (ly >= lowHitPY and ly <= hghHitPY)) or
162 ((rx >= lowHitPX and rx <= hghHitPX) and
163 (ry >= lowHitPY and ry <= hghHitPY))))
164 on_diagonal = ((forward == lastForward) and
165 ((lx - lastLX) == ((ly - lastLY) * cvm(forward, 1, -1))))
166 # print >>STDOUT, lastF, curF
167 # print >>STDOUT, lx,rx,ly,ry
168 # print >>STDOUT, lowHitPX,hghHitPX,lowHitPY,hghHitPY
169 # print >>STDOUT, "overlapping=",overlapping
170 # print >>STDOUT, "on_diagonal=",on_diagonal
171
172 lowMerPX = px
173 lowMerPY = py
174 hghMerPX = px + nx
175 hghMerPY = py + ny
176 if (not (overlapping and (not needs_to_share_diagonal or on_diagonal))):
177 if (firstF != None):
178 # if (lastF == None or firstF.runid != lastF.runid):
179 # end if
180 firstF.subtype = ('g','u')[needs_to_share_diagonal]
181 firstF.x_start = lowHitPX
182 firstF.y_start = lowHitPY
183 firstF.x_length = hghHitPX - lowHitPX
184 firstF.y_length = hghHitPY - lowHitPY
185 print >>outfile, firstF
186 # end if
187 firstF = curF
188 lowHitPX = lowMerPX
189 lowHitPY = lowMerPY
190 hghHitPX = hghMerPX
191 hghHitPY = hghMerPY
192 # end if
193 lowHitPX = cvm(lowHitPX < lowMerPX, lowHitPX, lowMerPX)
194 lowHitPY = cvm(lowHitPY < lowMerPY, lowHitPY, lowMerPY)
195 hghHitPX = cvm(hghHitPX > hghMerPX, hghHitPX, hghMerPX)
196 hghHitPY = cvm(hghHitPY > hghMerPY, hghHitPY, hghMerPY)
197
198 lastLX = lx
199 lastLY = ly
200 lastForward = forward
201 lastF = curF
202 # end if
203 # end for
204
205
206 if (firstF != None):
207 firstF.subtype = ('g','u')[needs_to_share_diagonal]
208 firstF.x_start = lowHitPX
209 firstF.y_start = lowHitPY
210 firstF.x_length = hghHitPX - lowHitPX
211 firstF.y_length = hghHitPY - lowHitPY
212 print >>outfile, firstF
213
214 return
215 # end def
216
217
218
219 # Note that if record has an initial rank for the X and Y sorting,
220 # then re-sorting and box recovery are simplified.
221
222 # Resorting becomes making the inital sparse ranking dense then a
223 # scattering to the destination.
224
225 # NOTE THAT outname is unused here.
226
227 def boxRecovery( inpfile, rawfile, outname):
228 inpfile.seek(0)
229 rawfile.seek(0)
230 outfile = MyFile.myfile()
231
232 rawfileIter = iter(rawfile)
233
234 # This is a modified merge operation?
235 # The two input files must be sorted the same manner.
236 leftMatch = None
237 for line in inpfile:
238 if(line[0] == 'M'):
239 rightMatch = MatchRecord.MatchRecord(line)
240 if( leftMatch != None and leftMatch.inSameRunAs(rightMatch) ):
241 # print >>STDERR, "In same run leftMatch=", leftMatch, " rightMatch=", rightMatch
242 for rawline in rawfileIter:
243 if( rawline[0] == 'M'):
244 rawMatch = MatchRecord.MatchRecord(rawline)
245 if(rawMatch.sameAs(rightMatch)):
246 print >>outfile, rightMatch
247 break
248 else:
249 # print "Inside run rawMatch=", rawMatch
250 if(rawMatch.isInsideBox(leftMatch,rightMatch)):
251 print >>outfile, rawMatch
252 # end if
253 # end if
254 # end if
255 # end for
256 # We should die here if there is no rawMatch that matched the rightMatch ...
257 else:
258 # print >>STDERR, "Between runs leftMatch=", leftMatch, " rightMatch=", rightMatch
259 for rawline in rawfileIter:
260 if( rawline[0] == 'M'):
261 rawMatch = MatchRecord.MatchRecord(rawline)
262 if(rawMatch.sameAs(rightMatch)):
263 print >>outfile, rightMatch
264 break
265 else:
266 # print >>STDERR, "Discard rawMatch=", rawMatch
267 pass
268 # end if
269 # end if
270 # end for
271 # We should die here if there is no rawMatch that matched the rightMatch ...
272 # Discard raw Matches until it is ge to the right match.
273 # end if
274 leftMatch = rightMatch
275 # end if
276 # end for
277 return outfile
278 # end def
279
280
281 class AtacDriver(AtacFile.AtacFile):
282 def runOld(self):
283 self.globals['atacAlgorithmVersion'] = str(17)
284 print >>STDERR, "runName = %s\n" % self.runName
285
286 # The ATAC globals used by this script:
287 opt_t = int(self.globals['globalMatchMinSize'])
288 opt_l = int(self.globals['globalPerfectRunMinLen'])
289 maxdiff = int(self.globals['globalPerfectRunMaxGapLen'])
290
291 assemblyId1 = self.globals['assemblyId1']
292 assemblyId2 = self.globals['assemblyId2']
293
294 assemblyFile1 = self.globals['assemblyFile1']
295 assemblyFile2 = self.globals['assemblyFile2']
296
297 boxRecoveryOn = 0 # Deprecated for same species comparisons 2003/09/09.
298 if(self.globals.has_key("boxRecoveryOn")):
299 boxRecoveryOn = int(self.globals['boxRecoveryOn'])
300
301 t0 = time.time()
302
303 assemblyIdx1 = IdxStore.IdxStore(assemblyFile1,assemblyId1)
304 assemblyIdx2 = IdxStore.IdxStore(assemblyFile2,assemblyId2)
305 rawfile = None
306
307 ###################################################################
308 # Setup for checkpointing scheme.
309 redo = 0
310 keep = 0
311 step = 0
312 if(self.globals.has_key("ckpKeep")):
313 keep = int(self.globals['ckpKeep'])
314 ckpName = "AllDone"
315 ###################################################################
316
317 print >>STDERR, 'Keep step=' + str(keep)
318 print >>STDERR, 'At step=' + str(step)
319 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
320
321 outprefix = self.runName
322
323 step += 1
324 print >>STDERR, 'At uniqueFilter, step=' + str(step)
325 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
326 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
327 redo = 1
328 if(not(self.globals.has_key('uniqueFilterOn') and self.globals['uniqueFilterOn']=="0")):
329 print >>STDERR, 'Running UniqueFilter'
330 outfile = MyFile.myfile()
331 UniqueFilter.main( self.matches, outfile)
332 self.matches = outfile
333 outprefix += '.uniq'
334 self.checkpoint(outprefix)
335
336 step += 1
337 print >>STDERR, 'At filterByMatchLength, step=' + str(step)
338 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
339 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
340 redo = 1
341 print >>STDERR, 'Running filterByMatchLength'
342 outfile = MyFile.myfile()
343 filterByMatchLength( self.matches, outfile, opt_t)
344 self.matches = outfile
345 outprefix += '.t' + str(opt_t)
346 self.checkpoint(outprefix)
347
348 step += 1
349 print >>STDERR, 'At trimMatchOverlaps, step=' + str(step)
350 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
351 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
352 redo = 1
353 print >>STDERR, "Start trimming for bp one-to-one-ness"
354 tempdata = MyFile.myfile()
355 TrimMatchOverlaps.trimMatchOverlapsInBoth(self.matches,tempdata,'u')
356 self.matches = tempdata
357 print >>STDERR, "Finished trimming for bp one-to-one-ness"
358 outprefix += '.trim'
359 self.checkpoint(outprefix)
360
361 if( boxRecoveryOn == 1 ):
362 # For box recovery later ... but what if we start from a checkpoint?
363 rawfile = self.matches
364
365 step += 1
366 print >>STDERR, 'At formPerfectRuns, step=' + str(step)
367 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
368 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
369 redo = 1
370 print >>STDERR, 'from ' + outprefix + ' making ' + outprefix + '.p6'
371 tempdata = PerfectRuns.formPerfectRuns(self.matches,
372 MatchRecord.sortInXorderAP,
373 MatchRecord.sortInYorderAP,
374 maxdiff,
375 'r')
376 self.matches = tempdata
377 outprefix += ".p6"
378 # end if
379
380 step += 1
381 print >>STDERR, 'At onlyKeepLongRuns, step=' + str(step)
382 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
383 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
384 redo = 1
385 print >>STDERR, 'from ' + outprefix + ' making ' + outprefix + '.l' + str(opt_l)
386 tempdata = onlyKeepLongRuns( self.matches, outprefix, opt_l)
387 self.matches = tempdata
388 outprefix += '.l' + str(opt_l)
389 self.checkpoint(outprefix)
390
391 step += 1
392 print >>STDERR, 'At formPerfectRuns, step=' + str(step)
393 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
394 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
395 redo = 1
396 print >>STDERR, 'Heal the perfect runs'
397 tempdata = PerfectRuns.formPerfectRuns(self.matches,
398 MatchRecord.sortInYorderAP,
399 MatchRecord.sortInXorderAP, maxdiff, 'r')
400 self.matches = tempdata
401 outprefix += '.pr'
402 self.checkpoint(outprefix)
403
404 if(boxRecoveryOn == 1):
405
406 # This is a box recovery step.
407 step += 1
408 print >>STDERR, 'At boxRecovery, step=' + str(step)
409 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
410 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
411 redo = 1
412 print >>STDERR, 'from ' + outprefix + ' making ' + outprefix + '.br'
413 print >>STDERR, "Make sorted raw matches"
414 outfile = MyFile.myfile()
415 MatchRecord.sortInXorderAP( rawfile, outfile)
416 rawfile = outfile
417 print >>STDERR, "perform box recovery"
418 tempdata = boxRecovery( self.matches, rawfile, outprefix)
419 self.matches = tempdata
420 outprefix += '.br'
421 self.checkpoint(outprefix)
422 # end if
423
424 step += 1
425 print >>STDERR, 'At formPerfectRuns, step=' + str(step)
426 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
427 if (redo or ( (keep < step) and not self.globals.has_key(ckpName))):
428 print >>STDERR, "form perfect runs"
429 redo = 1
430 print >>STDERR, 'from ' + outprefix + ' to ' + outprefix + '.p6'
431 tempdata = PerfectRuns.formPerfectRuns(self.matches,
432 MatchRecord.sortInXorderAP,
433 MatchRecord.sortInYorderAP, maxdiff, 'r')
434 self.matches = tempdata
435 outprefix += '.pr'
436 self.checkpoint(outprefix)
437
438 step += 1
439 print >>STDERR, 'At squeezeIntraRunGaps, step=' + str(step)
440 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
441 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
442 redo = 1
443 print >>STDERR, 'from ' + outprefix + ' to ' + outprefix + '.sq'
444 tempdata = MyFile.myfile()
445 squeezeIntraRunGaps.mainLoop(
446 self.matches,
447 tempdata,
448 assemblyIdx1, assemblyIdx2)
449 tempy = MyFile.myfile()
450 # Beware the current match subtypes are 'x', 'L', and 'R'!
451 coalesceMatches( tempdata, tempy, 1)
452 self.matches = tempy
453 outprefix += '.sq'
454 self.checkpoint(outprefix)
455
456 step += 1
457 print >>STDERR, 'At TrimMatchOverlaps, step=' + str(step)
458 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
459 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
460 redo = 1
461 print >>STDERR, "Start trimming for bp one-to-one-ness"
462 tempdata = MyFile.myfile()
463 TrimMatchOverlaps.trimMatchOverlapsInBoth(self.matches,tempdata,'u')
464 self.matches = tempdata
465 outprefix += '.trim'
466 print >>STDERR, "Finished trimming for bp one-to-one-ness"
467
468 step += 1
469 print >>STDERR, 'At RunsAsMatches, step=' + str(step)
470 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
471 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
472 redo = 1
473 self.runs = PerfectRuns.runsAsMatches( self.matches)
474 outprefix += '.runs'
475 self.checkpoint(outprefix)
476 # end if
477
478 if(self.globals.has_key('fillIntraRunGapsOn') and self.globals['fillIntraRunGapsOn']=="1" ):
479
480 # Next comes the DNA sequence dependent stuff.
481 step += 1
482 print >>STDERR, 'At fillIntraRunGaps, step=' + str(step)
483 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
484 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
485 redo = 1
486 print >>STDERR, "fill the intrarun gaps"
487 if(not self.globals.has_key('fillIntraRunGapsErate')):
488 self.globals['fillIntraRunGapsErate'] = 0.10
489 if(not self.globals.has_key('fillIntraRunGapsMaxGap')):
490 self.globals['fillIntraRunGapsMaxGap'] = 100000
491 fillIntraRunGapsErate = float(self.globals['fillIntraRunGapsErate'])
492 fillIntraRunGapsMaxGap = int(self.globals['fillIntraRunGapsMaxGap'])
493 tempdata = MyFile.myfile()
494 fillIntraRunGaps.mainLoop(self.matches, tempdata,
495 assemblyIdx1, assemblyIdx2,
496 fillIntraRunGapsMaxGap, fillIntraRunGapsErate)
497 self.matches = tempdata
498 outprefix += '.fill'
499 self.checkpoint(outprefix)
500
501 step += 1
502 print >>STDERR, 'At TrimMatchOverlaps, step=' + str(step)
503 print >>STDERR, 'Time elapsed=' + str(time.time()-t0)
504 if (redo or ((keep < step) and not self.globals.has_key(ckpName))):
505 redo = 1
506 print >>STDERR, "trim the overlaps"
507 tempdata = MyFile.myfile()
508 TrimMatchOverlaps.trimMatchOverlapsInBoth(self.matches,tempdata,'u')
509 self.matches = tempdata
510 outprefix += '.trim'
511 self.checkpoint(outprefix)
512
513 # end if "fillIntraRunGapsOn"
514
515 # end def
516
517 # end class
518
519
520 class localExecutable :
521 def __init__(self, name):
522 self.name = name
523 def run(self,argline,inpfile,outfile):
524 cmd = "%s %s %s %s" % (self.name,argline,inpfile,outfile)
525 print >>STDERR,"cmd =", cmd
526 iret = os.system(cmd)
527 assert(iret == 0)
528
529
530 def main(runName):
531
532 t0 = time.time()
533 obj = AtacDriver(runName)
534
535 t1 = time.time()
536 print >>STDERR, "Read checkpoint in %d seconds." % (t1-t0)
537 t0=t1
538
539 # The following are required:
540 assert(obj.globals.has_key('assemblyId1'))
541 assert(obj.globals.has_key('assemblyId2'))
542 assert(obj.globals.has_key('assemblyFile1'))
543 assert(obj.globals.has_key('assemblyFile2'))
544
545 assemblyId1 = obj.globals['assemblyId1']
546 assemblyId2 = obj.globals['assemblyId2']
547
548 assemblyFile1 = obj.globals["assemblyFile1"]
549 assemblyFile2 = obj.globals["assemblyFile2"]
550
551 assert(os.path.exists(assemblyFile1))
552 assert(os.path.exists(assemblyFile2))
553
554 if(not os.path.exists(assemblyFile1+".idxStore")):
555 IdxStore.createIndexedFasta( assemblyFile1, assemblyId2)
556
557 if(not os.path.exists(assemblyFile2+".idxStore")):
558 IdxStore.createIndexedFasta( assemblyFile2, assemblyId2)
559
560 assert(os.path.exists(assemblyFile1+".idxStore"))
561 assert(os.path.exists(assemblyFile2+".idxStore"))
562
563 if not obj.globals.has_key('matchesFile'):
564 print >>STDERR, "We need to make the raw matches."
565
566 if(not obj.globals.has_key('rawMatchMerSize')):
567 obj.globals['rawMatchMerSize'] = 20
568 if(not obj.globals.has_key('rawMatchMerMaxDegeneracy')):
569 obj.globals['rawMatchMerMaxDegeneracy'] = 1
570 if(not obj.globals.has_key('rawMatchMinFillSize')):
571 obj.globals['rawMatchMinSize'] = obj.globals['rawMatchMerSize']
572
573 # Many 2*rawMatchMerSize-1 matches are due to isolated single
574 # nucleotide mutations in otherwise perfect repeats.
575
576 if(not obj.globals.has_key('globalMatchMinSize')):
577 obj.globals['globalMatchMinSize'] = 2*int(obj.globals['rawMatchMerSize'])
578 if(not obj.globals.has_key('globalPerfectRunMinLen')):
579 obj.globals['globalPerfectRunMinLen'] = 100
580 if(not obj.globals.has_key('globalPerfectRunMaxGapLen')):
581 obj.globals['globalPerfectRunMaxGapLen'] = 100000
582
583 if(not obj.globals.has_key('intraRunGapIsolatedMismatchLen')):
584 obj.globals['intraRunGapIsolatedMismatchLen'] = 20
585
586 obj.runOld()
587
588 t1 = time.time()
589 print >>STDERR, "Ran in %d seconds." % (t1-t0)
590
591 obj.checkpoint(runName + ".chained.atac")
592
593
594
595 if __name__ == '__main__':
596 if (len(sys.argv) == 1):
597 print >>sys.stderr, "usage: $sys.argv[0] file.atac"
598 sys.exit(1)
599 if (sys.argv[1] == "justtestingifitworks"):
600 sys.exit(0)
601 main(sys.argv[1])
602