Debian Codegraph @

atac-driver/chainer/python/AtacDriver.py

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