Debian Codegraph @

ariba/assembly_compare.py

raw
1 import os
2 import copy
3 import pyfastaq
4 import pymummer
5
6 class Error (Exception): pass
7
8 class AssemblyCompare:
9 def __init__(self,
10 assembly_fa,
11 assembly_sequences,
12 ref_fa,
13 ref_sequence,
14 outprefix,
15 refdata,
16 nucmer_min_id=90,
17 nucmer_min_len=20,
18 nucmer_breaklen=200,
19 assembled_threshold=0.95,
20 unique_threshold=0.03,
21 max_gene_nt_extend=30,
22 ):
23 self.assembly_fa = os.path.abspath(assembly_fa)
24 self.assembly_sequences = assembly_sequences
25 self.ref_fa = os.path.abspath(ref_fa)
26 self.ref_sequence = ref_sequence
27 self.outprefix = os.path.abspath(outprefix)
28 self.refdata = refdata
29
30 self.nucmer_min_id = nucmer_min_id
31 self.nucmer_min_len = nucmer_min_len
32 self.nucmer_breaklen = nucmer_breaklen
33 self.assembled_threshold = assembled_threshold
34 self.unique_threshold = unique_threshold
35 self.max_gene_nt_extend = max_gene_nt_extend
36 self.scaff_name_matching_ref = None
37 self.gene_matching_ref = None
38 self.gene_matching_ref_type = None
39 self.gene_start_bases_added = None
40 self.gene_end_bases_added = None
41
42 self.nucmer_coords_file = self.outprefix + '.nucmer.coords'
43 self.nucmer_snps_file = self.nucmer_coords_file + '.snps'
44
45
46 def _run_nucmer(self):
47 pymummer.nucmer.Runner(
48 self.ref_fa,
49 self.assembly_fa,
50 self.nucmer_coords_file,
51 min_id=self.nucmer_min_id,
52 min_length=self.nucmer_min_len,
53 breaklen=self.nucmer_breaklen,
54 maxmatch=True,
55 show_snps=True,
56 show_snps_C=False,
57 ).run()
58
59
60 @staticmethod
61 def _parse_nucmer_coords_file(coords_file, ref_name):
62 '''Input is coords file made by self._run_nucmer. Reference should have one sequence only.
63 ref_name is name fo the reference sequence, to sanity check the coords file.
64 Returns dictionary. Key = assembly contig name. Value = list of nucmer hits to that contig'''
65 file_reader = pymummer.coords_file.reader(coords_file)
66 nucmer_hits = {}
67 for hit in file_reader:
68 assert hit.ref_name == ref_name
69 contig = hit.qry_name
70 if contig not in nucmer_hits:
71 nucmer_hits[contig] = []
72 nucmer_hits[contig].append(copy.copy(hit))
73
74 return nucmer_hits
75
76
77 @staticmethod
78 def _nucmer_hits_to_percent_identity(nucmer_hits):
79 '''Input is hits made by self._parse_nucmer_coords_file.
80 Returns dictionary. key = contig name. Value = percent identity of hits to that contig'''
81 percent_identities = {}
82 max_lengths = {}
83
84 for contig in nucmer_hits:
85 max_length = -1
86 percent_identity = 0
87 for hit in nucmer_hits[contig]:
88 if hit.hit_length_qry > max_length:
89 max_length = hit.hit_length_qry
90 percent_identity = hit.percent_identity
91 percent_identities[contig] = percent_identity
92
93 return percent_identities
94
95
96 @staticmethod
97 def _nucmer_hits_to_assembly_coords(nucmer_hits):
98 '''Input is hits made by self._parse_nucmer_coords_file.
99 Returns dictionary. key = contig name. Value = list of coords that match
100 to the reference gene'''
101 coords = {}
102 for l in nucmer_hits.values():
103 for hit in l:
104 if hit.qry_name not in coords:
105 coords[hit.qry_name] = []
106 coords[hit.qry_name].append(hit.qry_coords())
107
108 for scaff in coords:
109 pyfastaq.intervals.merge_overlapping_in_list(coords[scaff])
110
111 return coords
112
113
114 def assembly_match_coords(self):
115 return self._nucmer_hits_to_assembly_coords(self.nucmer_hits)
116
117
118 @classmethod
119 def nucmer_hits_to_ref_coords(cls, nucmer_hits, contig=None):
120 '''Input is hits made by self._parse_nucmer_coords_file.
121 Returns dictionary. Key = contig name. Value = list of coords in the
122 reference sequence for that contig.
123 if contig=contig_name, then just gets the ref coords from that contig,
124 instead of using all the contigs'''
125 coords = []
126 if contig is None:
127 coords = {key: [] for key in nucmer_hits.keys()}
128 else:
129 coords = {contig: []}
130
131 for key in coords:
132 coords[key] = [hit.ref_coords() for hit in nucmer_hits[key]]
133 pyfastaq.intervals.merge_overlapping_in_list(coords[key])
134
135 return coords
136
137
138 @classmethod
139 def nucmer_hits_to_ref_and_qry_coords(cls, nucmer_hits, contig=None):
140 '''Same as nucmer_hits_to_ref_coords, except removes containing hits first,
141 and returns ref and qry coords lists'''
142 if contig is None:
143 ctg_coords = {key: [] for key in nucmer_hits.keys()}
144 else:
145 ctg_coords = {contig: []}
146
147 ref_coords = {}
148
149 for key in ctg_coords:
150 hits = copy.copy(nucmer_hits[key])
151 hits.sort(key=lambda x: len(x.ref_coords()))
152
153 if len(hits) > 1:
154 i = 0
155 while i < len(hits) - 1:
156 c1 = hits[i].ref_coords()
157 c2 = hits[i+1].ref_coords()
158 if c2.contains(c1):
159 hits.pop(i)
160 else:
161 i += 1
162
163 ref_coords[key] = [hit.ref_coords() for hit in hits]
164 ctg_coords[key] = [hit.qry_coords() for hit in hits]
165 pyfastaq.intervals.merge_overlapping_in_list(ref_coords[key])
166 pyfastaq.intervals.merge_overlapping_in_list(ctg_coords[key])
167
168 return ctg_coords, ref_coords
169
170
171 @staticmethod
172 def ref_cov_per_contig(nucmer_hits):
173 '''Input is hits made by self._parse_nucmer_coords_file.
174 Returns dictionary. key = contig name. Value = number of bases that
175 match to the reference sequence.'''
176 coords = AssemblyCompare.nucmer_hits_to_ref_coords(nucmer_hits)
177 return {x: pyfastaq.intervals.length_sum_from_list(coords[x]) for x in coords}
178
179
180 @staticmethod
181 def _get_assembled_reference_sequences(nucmer_hits, ref_sequence, assembly):
182 '''nucmer_hits = hits made by self._parse_nucmer_coords_file.
183 ref_gene = reference sequence (pyfastaq.sequences.Fasta object)
184 assembly = dictionary of contig name -> contig.
185 Makes a set of Fasta objects of each piece of assembly that
186 corresponds to the reference sequeunce.'''
187 sequences = {}
188
189 for contig in sorted(nucmer_hits):
190 for hit in nucmer_hits[contig]:
191 qry_coords = hit.qry_coords()
192 fa = assembly[hit.qry_name].subseq(qry_coords.start, qry_coords.end + 1)
193 if hit.on_same_strand():
194 strand = '+'
195 else:
196 fa.revcomp()
197 strand = '-'
198 ref_coords = hit.ref_coords()
199 fa.id = '.'.join([
200 ref_sequence.id,
201 str(ref_coords.start + 1),
202 str(ref_coords.end + 1),
203 contig,
204 str(qry_coords.start + 1),
205 str(qry_coords.end + 1),
206 strand
207 ])
208
209 if hit.hit_length_ref == hit.ref_length:
210 fa.id += '.complete'
211
212 sequences[fa.id] = fa
213
214 return sequences
215
216
217 @staticmethod
218 def _whole_gene_covered_by_nucmer_hits(nucmer_hits, ref_seq, percent_threshold, max_nt_extend):
219 '''Returns true iff the reference sequence is covered by nucmer hits.
220 nucmer_hits = hits made by self._parse_nucmer_coords_file.
221 Counts as covered if (total ref bases covered) / len(ref_seq) >= threshold'''
222 coords = AssemblyCompare.nucmer_hits_to_ref_coords(nucmer_hits)
223 covered = []
224 for coords_list in coords.values():
225 covered.extend(coords_list)
226 pyfastaq.intervals.merge_overlapping_in_list(covered)
227 return (2 * max_nt_extend + pyfastaq.intervals.length_sum_from_list(covered)) / len(ref_seq) >= percent_threshold
228
229
230 @staticmethod
231 def _ref_has_region_assembled_twice(nucmer_hits, ref_seq, threshold):
232 '''Returns true iff there is a part of the reference that is assembled
233 more than once (ie covered by >1 nucmer hit).
234 Needs a minimum proportin of the ref to be assembled more than once,
235 determined by threshold.
236 nucmer_hits = hits made by self._parse_nucmer_coords_file.'''
237 coords = AssemblyCompare.nucmer_hits_to_ref_coords(nucmer_hits)
238 covered = []
239 for coords_list in coords.values():
240 covered.extend(coords_list)
241 covered.sort()
242
243 if len(covered) <= 1:
244 return False
245
246 coverage = {}
247 for i in covered:
248 for j in range(i.start, i.end + 1):
249 coverage[j] = coverage.get(j, 0) + 1
250
251 bases_depth_at_least_two = len([1 for x in coverage.values() if x > 1])
252 return bases_depth_at_least_two / len(ref_seq) >= threshold
253
254
255 @classmethod
256 def _longest_nucmer_hit_in_ref(cls, nucmer_hits):
257 max_length = None
258 max_hit = None
259
260 for l in nucmer_hits.values():
261 for hit in l:
262 if max_length is None or hit.hit_length_ref > max_length:
263 max_length = hit.hit_length_ref
264 max_hit = hit
265
266 return max_hit
267
268
269 @classmethod
270 def _find_previous_start_codon(cls, sequence, start_coord, min_start_coord):
271 for i in range(start_coord, min_start_coord - 1, -3):
272 codon = pyfastaq.sequences.Fasta('x', sequence[i:i+3])
273 aa = codon.translate()
274 if aa.seq == '*':
275 return None
276 elif codon.seq in pyfastaq.genetic_codes.starts[pyfastaq.sequences.genetic_code]:
277 return i
278
279 return None
280
281
282 @classmethod
283 def _find_next_stop_codon(cls, sequence, end_coord, max_end_coord):
284 final_i = min(len(sequence) - 3, max_end_coord - 2)
285 for i in range(end_coord, final_i + 1, 3):
286 codon = pyfastaq.sequences.Fasta('x', sequence[i:i+3])
287 aa = codon.translate()
288 if aa.seq == '*':
289 return i
290
291 return None
292
293
294 @classmethod
295 def _gene_from_nucmer_match(cls, nucmer_match, contig, max_end_nt_extend):
296 if nucmer_match.on_same_strand():
297 revcomp = False
298 else:
299 revcomp = True
300 nucmer_match = copy.copy(nucmer_match)
301 nucmer_match.reverse_query()
302 contig = copy.copy(contig)
303 contig.revcomp()
304
305 ref_hit_start = min(nucmer_match.ref_start, nucmer_match.ref_end)
306 contig_hit_start = min(nucmer_match.qry_start, nucmer_match.qry_end)
307 min_allowed_start = max(0, contig_hit_start - max_end_nt_extend)
308 if ref_hit_start % 3 != 0:
309 contig_hit_start += 3 - (ref_hit_start % 3)
310 contig_hit_end = max(nucmer_match.qry_start, nucmer_match.qry_end)
311 max_allowed_end = min(len(contig) - 1, contig_hit_end + max_end_nt_extend)
312 contig_hit_end -= (contig_hit_end - contig_hit_start + 1) % 3
313 assert contig_hit_start < contig_hit_end
314 gene_nt_name = nucmer_match.qry_name + '.' + str(contig_hit_start + 1) + '-' + str(contig_hit_end + 1)
315
316 gene_nt = pyfastaq.sequences.Fasta(gene_nt_name, contig[contig_hit_start:contig_hit_end+1])
317 assert len(gene_nt) % 3 == 0
318 gene_aa = gene_nt.translate()
319 if '*' in gene_aa[:-1]:
320 return gene_nt, 'HAS_STOP', None, None
321
322 extended_start_position = AssemblyCompare._find_previous_start_codon(contig, contig_hit_start, min_allowed_start)
323 extended_end_position = AssemblyCompare._find_next_stop_codon(contig, contig_hit_end - 2, max_allowed_end)
324 start = extended_start_position if extended_start_position is not None else contig_hit_start
325 end = extended_end_position + 2 if extended_end_position is not None else contig_hit_end
326
327 if revcomp:
328 gene_nt_name = nucmer_match.qry_name + '.' + str(end + 1) + '-' + str(start + 1)
329 else:
330 gene_nt_name = nucmer_match.qry_name + '.' + str(start + 1) + '-' + str(end + 1)
331
332 gene_nt = pyfastaq.sequences.Fasta(gene_nt_name, contig[start:end+1])
333 start_nt_added = None if extended_start_position is None else min(nucmer_match.qry_start, nucmer_match.qry_end) - start
334 end_nt_added = None if extended_end_position is None else end - max(nucmer_match.qry_start, nucmer_match.qry_end)
335
336 if None in [extended_start_position, extended_end_position]:
337 return gene_nt, 'START_OR_END_FAIL', start_nt_added, end_nt_added
338 else:
339 return gene_nt, 'GENE_FOUND', start_nt_added, end_nt_added
340
341
342 @staticmethod
343 def _get_gene_matching_ref(nucmer_hits, contigs, max_end_nt_extend):
344 longest_match = AssemblyCompare._longest_nucmer_hit_in_ref(nucmer_hits)
345 if longest_match is None:
346 return None, 'NO_MATCH', None, None
347 else:
348 return (longest_match.qry_name,) + AssemblyCompare._gene_from_nucmer_match(longest_match, contigs[longest_match.qry_name], max_end_nt_extend)
349
350
351 @staticmethod
352 def _ref_covered_by_at_least_one_full_length_contig(nucmer_hits, percent_threshold, max_nt_extend):
353 '''Returns true iff there exists a contig that completely
354 covers the reference sequence
355 nucmer_hits = hits made by self._parse_nucmer_coords_file.'''
356 for l in nucmer_hits.values():
357 for hit in l:
358 if ( (2 * max_nt_extend) + len(hit.ref_coords()) ) / hit.ref_length >= percent_threshold:
359 return True
360 return False
361
362
363 def update_flag(self, flag):
364 if self._whole_gene_covered_by_nucmer_hits(self.nucmer_hits, self.ref_sequence, self.assembled_threshold, self.max_gene_nt_extend):
365 flag.add('assembled')
366
367 if self.assembled_into_one_contig:
368 flag.add('assembled_into_one_contig')
369
370 if self._ref_has_region_assembled_twice(self.nucmer_hits, self.ref_sequence, self.unique_threshold):
371 flag.add('region_assembled_twice')
372
373 ref_seq_type, is_variant_only = self.refdata.sequence_type(self.ref_sequence.id)
374 if ref_seq_type == 'p' and self.gene_matching_ref_type == 'GENE_FOUND':
375 flag.add('complete_gene')
376
377 if len(self.nucmer_hits) == 1:
378 flag.add('unique_contig')
379
380 return flag
381
382
383 @staticmethod
384 def nucmer_hit_containing_reference_position(nucmer_hits, ref_name, ref_position, qry_name=None):
385 '''Returns the first nucmer match found that contains the given
386 reference location. nucmer_hits = hits made by self._parse_nucmer_coords_file.
387 Returns None if no matching hit found'''
388 for contig_name in nucmer_hits:
389 for hit in nucmer_hits[contig_name]:
390 if hit.ref_name == ref_name and (qry_name is None or qry_name == hit.qry_name) and hit.ref_coords().distance_to_point(ref_position) == 0:
391 return hit
392
393 return None
394
395
396 def run(self):
397 self._run_nucmer()
398 self.nucmer_hits = self._parse_nucmer_coords_file(self.nucmer_coords_file, self.ref_sequence.id)
399 self.percent_identities = self._nucmer_hits_to_percent_identity(self.nucmer_hits)
400 self.assembled_reference_sequences = self._get_assembled_reference_sequences(self.nucmer_hits, self.ref_sequence, self.assembly_sequences)
401 ref_seq_type, is_variant_only = self.refdata.sequence_type(self.ref_sequence.id)
402 if self._ref_covered_by_at_least_one_full_length_contig(self.nucmer_hits, self.assembled_threshold, self.max_gene_nt_extend):
403 self.assembled_into_one_contig = True
404 if ref_seq_type == 'p':
405 self.scaff_name_matching_ref, self.gene_matching_ref, self.gene_matching_ref_type, self.gene_start_bases_added, self.gene_end_bases_added = self._get_gene_matching_ref(self.nucmer_hits, self.assembly_sequences, self.max_gene_nt_extend)
406 else:
407 self.assembled_into_one_contig = False