Debian Codegraph @

bin/maf-join

raw
1 #! /usr/bin/env python3
2
3 # Copyright 2009, 2010, 2011 Martin C. Frith
4
5 # Join two or more sets of MAF-format multiple alignments into bigger
6 # multiple alignments. The 'join field' is the top genome, which
7 # should be the same for each input. Each input should be sorted by
8 # position in the top genome.
9
10 # WARNING: Alignment columns with a gap in the top genome are joined
11 # arbitrarily!!!
12
13 from __future__ import print_function
14
15 import functools
16 import sys, os, fileinput, optparse, signal
17
18 try:
19 from future_builtins import map, zip
20 except ImportError:
21 pass
22
23 signal.signal(signal.SIGPIPE, signal.SIG_DFL) # stop spurious error message
24
25 class peekable: # Adapted from Python Cookbook 2nd edition
26 """An iterator that supports a peek operation."""
27 def __init__(self, iterable):
28 self.it = iter(iterable)
29 self.cache = []
30 def __iter__(self):
31 return self
32 def __next__(self):
33 if self.cache: return self.cache.pop()
34 else: return next(self.it)
35 next = __next__
36 def peek(self):
37 if not self.cache: self.cache.append(next(self.it))
38 return self.cache[0]
39
40 def maxLen(things): return max(map(len, things))
41
42 class MafBlock:
43 def __init__(self, chrom, beg, end, strand, chrSize, seq, prob):
44 self.chr = chrom # chromosome names
45 self.beg = beg # alignment begin coordinates
46 self.end = end # alignment end coordinates
47 self.strand = strand
48 self.chrSize = chrSize # chromosome sizes
49 self.seq = seq # aligned sequences, including gaps
50 self.prob = prob # probabilities (may be empty)
51
52 def __bool__(self):
53 return len(self.seq) > 0
54 __nonzero__ = __bool__
55
56 def __lt__(self, other):
57 return (self.chr[:1] + self.beg[:1]) < (other.chr[:1] + other.beg[:1])
58
59 def before(self, other):
60 return (self.chr[0], self.end[0]) <= (other.chr[0], other.beg[0])
61
62 def after(self, other):
63 return (self.chr[0], self.beg[0]) >= (other.chr[0], other.end[0])
64
65 def addLine(self, line):
66 words = line.split()
67 if line[0] == "s":
68 self.chr.append(words[1])
69 self.beg.append(int(words[2]))
70 self.end.append(int(words[2]) + int(words[3]))
71 self.strand.append(words[4])
72 self.chrSize.append(words[5])
73 self.seq.append(list(words[6]))
74 elif line[0] == "p":
75 self.prob.append(words[1])
76
77 def write(self):
78 beg = [str(i) for i in self.beg]
79 size = [str(e-b) for b, e in zip(self.beg, self.end)]
80 seq = [''.join(i) for i in self.seq]
81 columns = self.chr, beg, size, self.strand, self.chrSize, seq
82 widths = [maxLen(i) for i in columns]
83 print('a')
84 for row in zip(*columns):
85 widthsAndFields = list(zip(widths, row))
86 field0 = "%-*s" % widthsAndFields[0] # left-justify
87 fields = ["%*s" % i for i in widthsAndFields[1:]] # right-justify
88 print('s', field0, ' '.join(fields))
89 pad = ' '.join(' ' * i for i in widths[:-1])
90 for i in self.prob:
91 print('p', pad, i)
92 print() # blank line afterwards
93
94 def topSeqBeg(maf): return maf.beg[0]
95 def topSeqEnd(maf): return maf.end[0]
96 def emptyMaf(): return MafBlock([], [], [], [], [], [], [])
97
98 def joinOnFirstItem(x, y):
99 if x[0] != y[0]:
100 raise ValueError('join fields not equal:\n'+str(x[0])+'\n'+str(y[0]))
101 return x + y[1:]
102
103 def mafEasyJoin(x, y):
104 '''Join two MAF blocks on the top sequence.'''
105 xJoin = list(zip(x.chr, x.beg, x.end, x.strand, x.chrSize, x.seq))
106 yJoin = list(zip(y.chr, y.beg, y.end, y.strand, y.chrSize, y.seq))
107 joined = joinOnFirstItem(xJoin, yJoin)
108 chrom, beg, end, strand, chrSize, seq = zip(*joined)
109 prob = x.prob + y.prob
110 return MafBlock(chrom, beg, end, strand, chrSize, seq, prob)
111
112 def countNonGaps(s): return len(s) - s.count('-')
113
114 def nthNonGap(s, n):
115 '''Get the start position of the n-th non-gap.'''
116 for i, x in enumerate(s):
117 if x != '-':
118 if n == 0: return i
119 n -= 1
120 raise ValueError('non-gap not found')
121
122 def nthLastNonGap(s, n):
123 '''Get the end position of the n-th last non-gap.'''
124 return len(s) - nthNonGap(s[::-1], n)
125
126 def mafSlice(maf, alnBeg, alnEnd):
127 '''Return a slice of a MAF block, using coordinates in the alignment.'''
128 beg = [b + countNonGaps(s[:alnBeg]) for b, s in zip(maf.beg, maf.seq)]
129 end = [e - countNonGaps(s[alnEnd:]) for e, s in zip(maf.end, maf.seq)]
130 seq = [i[alnBeg:alnEnd] for i in maf.seq]
131 prob = [i[alnBeg:alnEnd] for i in maf.prob]
132 return MafBlock(maf.chr, beg, end, maf.strand, maf.chrSize, seq, prob)
133
134 def mafSliceTopSeq(maf, newTopSeqBeg, newTopSeqEnd):
135 '''Return a slice of a MAF block, using coordinates in the top sequence.'''
136 lettersFromBeg = newTopSeqBeg - topSeqBeg(maf)
137 lettersFromEnd = topSeqEnd(maf) - newTopSeqEnd
138 alnBeg = nthNonGap(maf.seq[0], lettersFromBeg)
139 alnEnd = nthLastNonGap(maf.seq[0], lettersFromEnd)
140 return mafSlice(maf, alnBeg, alnEnd)
141
142 def jumpGaps(sequence, index):
143 '''Return the next index of the sequence where there is a non-gap.'''
144 nextIndex = index
145 while sequence[nextIndex] == '-': nextIndex += 1
146 return nextIndex
147
148 def gapsToAdd(sequences):
149 '''Return new gaps and their positions, needed to align the non-gaps.'''
150 gapInfo = [[] for i in sequences]
151 gapBeg = [0 for i in sequences]
152 try:
153 while True:
154 gapEnd = [jumpGaps(s, p) for s, p in zip(sequences, gapBeg)]
155 gapSize = [e-b for b, e in zip(gapBeg, gapEnd)]
156 maxGapSize = max(gapSize)
157 for s, e, i in zip(gapSize, gapEnd, gapInfo):
158 if s < maxGapSize:
159 newGap = maxGapSize - s
160 i.append((newGap, e))
161 gapBeg = [e+1 for e in gapEnd]
162 except IndexError: return gapInfo
163
164 def chunksAndGaps(s, gapsAndPositions, oneGap):
165 '''Yield chunks of "s" interspersed with gaps at given positions.'''
166 oldPosition = 0
167 for gapLen, position in gapsAndPositions:
168 yield s[oldPosition:position]
169 yield oneGap * gapLen
170 oldPosition = position
171 yield s[oldPosition:]
172
173 def mafAddGaps(maf, gapsAndPositions):
174 '''Add the given gaps at the given positions to a MAF block.'''
175 maf.seq = [sum(chunksAndGaps(i, gapsAndPositions, ['-']), [])
176 for i in maf.seq]
177 maf.prob = [''.join(chunksAndGaps(i, gapsAndPositions, '~'))
178 for i in maf.prob]
179
180 def mafJoin(mafs):
181 '''Intersect and join overlapping MAF blocks.'''
182 newTopSeqBeg = max(map(topSeqBeg, mafs))
183 newTopSeqEnd = min(map(topSeqEnd, mafs))
184 mafs = [mafSliceTopSeq(i, newTopSeqBeg, newTopSeqEnd) for i in mafs]
185 topSeqs = [i.seq[0] for i in mafs]
186 gapInfo = gapsToAdd(topSeqs)
187 for maf, gapsAndPositions in zip(mafs, gapInfo):
188 mafAddGaps(maf, gapsAndPositions)
189 return functools.reduce(mafEasyJoin, mafs)
190
191 def mafInput(lines):
192 '''Read lines and yield MAF blocks.'''
193 maf = emptyMaf()
194 for line in lines:
195 if line.isspace():
196 if maf: yield maf
197 maf = emptyMaf()
198 else:
199 maf.addLine(line)
200 if maf: yield maf
201
202 def sortedMafInput(lines):
203 '''Read lines and yield MAF blocks, checking that they are in order.'''
204 old = emptyMaf()
205 for maf in mafInput(lines):
206 if maf < old: sys.exit(progName + ": MAF blocks not sorted properly")
207 yield maf
208 old = maf
209
210 def allOverlaps(sequences, beg, end):
211 '''Yield all combinations of MAF blocks that overlap in the top genome.'''
212 assert beg < end
213 if not sequences:
214 yield ()
215 return
216 for i in sequences[0]:
217 if topSeqEnd(i) <= beg: continue
218 if topSeqBeg(i) >= end: break # assumes they're sorted by position
219 newBeg = max(beg, topSeqBeg(i))
220 newEnd = min(end, topSeqEnd(i))
221 for j in allOverlaps(sequences[1:], newBeg, newEnd):
222 yield (i,) + j
223
224 def nextWindow(window, theInput, referenceMaf):
225 '''Yield "relevant" MAF blocks, based on overlap with referenceMaf.'''
226 for maf in window:
227 if not maf.before(referenceMaf): yield maf
228 try:
229 while True:
230 maf = theInput.peek()
231 if maf.after(referenceMaf): break
232 maf = theInput.next()
233 if not maf.before(referenceMaf): yield maf
234 except StopIteration: pass
235
236 def overlappingMafs(sortedMafInputs):
237 '''Yield all combinations of MAF blocks that overlap in the top genome.'''
238 if not sortedMafInputs: return
239 head, tail = sortedMafInputs[0], sortedMafInputs[1:]
240 windows = [[] for t in tail]
241 for h in head: # iterate over MAF blocks in the first input
242 windows = [list(nextWindow(w, t, h)) for w, t in zip(windows, tail)]
243 for i in allOverlaps(windows, topSeqBeg(h), topSeqEnd(h)):
244 yield (h,) + i
245
246 op = optparse.OptionParser(usage="%prog sorted-file1.maf sorted-file2.maf ...")
247 opts, args = op.parse_args()
248
249 progName = os.path.basename(sys.argv[0])
250
251 inputs = [peekable(sortedMafInput(fileinput.input(i))) for i in args]
252
253 for mafs in overlappingMafs(inputs):
254 mafJoin(mafs).write()