| 1 |
import tempfile |
| 2 |
import copy |
| 3 |
import os |
| 4 |
import pymummer |
| 5 |
import pyfastaq |
| 6 |
from ariba import common |
| 7 |
|
| 8 |
class Error (Exception): pass |
| 9 |
|
| 10 |
class RefSeqChooser: |
| 11 |
def __init__(self, |
| 12 |
cluster_fasta, |
| 13 |
all_refs_fasta, |
| 14 |
assembly_fasta_in, |
| 15 |
assembly_fasta_out, |
| 16 |
log_fh, |
| 17 |
contig_name_prefix='', |
| 18 |
nucmer_min_id=90, |
| 19 |
nucmer_min_len=20, |
| 20 |
nucmer_breaklen=200, |
| 21 |
): |
| 22 |
self.cluster_fasta = os.path.abspath(cluster_fasta) |
| 23 |
self.all_refs_fasta = os.path.abspath(all_refs_fasta) |
| 24 |
self.assembly_fasta_in = os.path.abspath(assembly_fasta_in) |
| 25 |
self.assembly_fasta_out = os.path.abspath(assembly_fasta_out) |
| 26 |
self.log_fh = log_fh |
| 27 |
self.nucmer_min_id = nucmer_min_id |
| 28 |
self.nucmer_min_len = nucmer_min_len |
| 29 |
self.nucmer_breaklen = nucmer_breaklen |
| 30 |
self.closest_ref_within_cluster = None |
| 31 |
self.closest_ref_from_all_refs = None |
| 32 |
self.closest_ref_is_in_cluster = False |
| 33 |
|
| 34 |
|
| 35 |
@classmethod |
| 36 |
def _make_matching_contig_pieces_fasta(cls, contig_fasta, coords_list, outfile): |
| 37 |
matches = {} |
| 38 |
for hit in coords_list: |
| 39 |
if hit.qry_name not in matches: |
| 40 |
matches[hit.qry_name] = [] |
| 41 |
matches[hit.qry_name].append(hit.qry_coords()) |
| 42 |
|
| 43 |
if len(matches) == 0: |
| 44 |
return False |
| 45 |
|
| 46 |
contig_seqs = {} |
| 47 |
pyfastaq.tasks.file_to_dict(contig_fasta, contig_seqs) |
| 48 |
|
| 49 |
f_out = pyfastaq.utils.open_file_write(outfile) |
| 50 |
|
| 51 |
for contig_name in sorted(matches): |
| 52 |
pyfastaq.intervals.merge_overlapping_in_list(matches[contig_name]) |
| 53 |
for interval in matches[contig_name]: |
| 54 |
subseq = contig_seqs[contig_name].subseq(interval.start, interval.end+1) |
| 55 |
subseq.id = contig_name + ':' + str(interval.start+1) + '-' + str(interval.end+1) |
| 56 |
print(subseq, file=f_out) |
| 57 |
|
| 58 |
pyfastaq.utils.close(f_out) |
| 59 |
return True |
| 60 |
|
| 61 |
|
| 62 |
@classmethod |
| 63 |
def _sequence_is_in_fasta_file(cls, seq_name, fasta_file): |
| 64 |
for seq in pyfastaq.sequences.file_reader(fasta_file): |
| 65 |
if seq.id == seq_name: |
| 66 |
return True |
| 67 |
return False |
| 68 |
|
| 69 |
|
| 70 |
@classmethod |
| 71 |
def _load_nucmer_coords_file(cls, coords_file, log_fh=None): |
| 72 |
matches = {} |
| 73 |
file_reader = pymummer.coords_file.reader(coords_file) |
| 74 |
for hit in file_reader: |
| 75 |
if log_fh is not None: |
| 76 |
print('[choose ref nucmer]', hit, sep='\t', file=log_fh) |
| 77 |
if hit.ref_name not in matches: |
| 78 |
matches[hit.ref_name] = [] |
| 79 |
matches[hit.ref_name].append(copy.copy(hit)) |
| 80 |
return matches |
| 81 |
|
| 82 |
|
| 83 |
@classmethod |
| 84 |
def _l_and_c_from_contig_name(cls, name): |
| 85 |
try: |
| 86 |
prefix, l_string, c_string, ctg, counter = name.split('.') |
| 87 |
l = int(l_string[1:]) |
| 88 |
c = int(c_string[1:]) |
| 89 |
except: |
| 90 |
raise Error('Error parsing contig name "' + name + '"') |
| 91 |
|
| 92 |
return l, c |
| 93 |
|
| 94 |
|
| 95 |
@classmethod |
| 96 |
def _best_of_two_hits(cls, hit1, hit2, use_qry_length=False, check_flanking=False): |
| 97 |
if use_qry_length: |
| 98 |
qry_length_percent1 = hit1.hit_length_qry / hit1.qry_length |
| 99 |
qry_length_percent2 = hit2.hit_length_qry / hit2.qry_length |
| 100 |
if qry_length_percent1 != qry_length_percent2: |
| 101 |
return hit1 if qry_length_percent1 > qry_length_percent2 else hit2 |
| 102 |
|
| 103 |
ref_length_percent1 = hit1.hit_length_ref / hit1.ref_length |
| 104 |
ref_length_percent2 = hit2.hit_length_ref / hit2.ref_length |
| 105 |
if ref_length_percent1 != ref_length_percent2: |
| 106 |
return hit1 if ref_length_percent1 > ref_length_percent2 else hit2 |
| 107 |
elif hit1.percent_identity != hit2.percent_identity: |
| 108 |
return hit1 if hit1.percent_identity > hit2.percent_identity else hit2 |
| 109 |
else: |
| 110 |
if check_flanking: |
| 111 |
flank1 = min(min(hit1.qry_start, hit1.qry_end), hit1.qry_length - 1 - max(hit1.qry_start, hit1.qry_end)) |
| 112 |
flank2 = min(min(hit2.qry_start, hit2.qry_end), hit2.qry_length - 1 - max(hit2.qry_start, hit2.qry_end)) |
| 113 |
if flank1 != flank2: |
| 114 |
return hit1 if flank1 > flank2 else hit2 |
| 115 |
l1, c1 = RefSeqChooser._l_and_c_from_contig_name(hit1.qry_name) |
| 116 |
l2, c2 = RefSeqChooser._l_and_c_from_contig_name(hit2.qry_name) |
| 117 |
if l1 != l2: |
| 118 |
return hit1 if l1 > l2 else hit2 |
| 119 |
else: |
| 120 |
return hit1 if c1 > c2 else hit2 |
| 121 |
|
| 122 |
|
| 123 |
@classmethod |
| 124 |
def _choose_best_nucmer_match(cls, matches, use_qry_length=False, check_flanking=False): |
| 125 |
best_match = None |
| 126 |
for ref_name in matches: |
| 127 |
for hit in matches[ref_name]: |
| 128 |
if best_match is None: |
| 129 |
best_match = hit |
| 130 |
else: |
| 131 |
best_match = RefSeqChooser._best_of_two_hits(best_match, hit, use_qry_length=use_qry_length, check_flanking=check_flanking) |
| 132 |
|
| 133 |
return best_match |
| 134 |
|
| 135 |
|
| 136 |
@classmethod |
| 137 |
def _closest_nucmer_match_between_fastas(cls, ref_fasta, qry_fasta, log_fh, min_id, min_length, breaklen, use_qry_length, check_flanking): |
| 138 |
tmpdir = tempfile.mkdtemp(prefix='tmp.closest_nucmer_match.', dir=os.getcwd()) |
| 139 |
coords_file = os.path.join(tmpdir, 'nucmer_vs_cluster_refs.coords') |
| 140 |
pymummer.nucmer.Runner( |
| 141 |
ref_fasta, |
| 142 |
qry_fasta, |
| 143 |
coords_file, |
| 144 |
min_id=min_id, |
| 145 |
min_length=min_length, |
| 146 |
breaklen=breaklen, |
| 147 |
maxmatch=True, |
| 148 |
).run() |
| 149 |
nucmer_matches = RefSeqChooser._load_nucmer_coords_file(coords_file, log_fh=log_fh) |
| 150 |
common.rmtree(tmpdir) |
| 151 |
|
| 152 |
if len(nucmer_matches) == 0: |
| 153 |
return None, {} |
| 154 |
else: |
| 155 |
best_hit = RefSeqChooser._choose_best_nucmer_match(nucmer_matches, use_qry_length=use_qry_length, check_flanking=check_flanking) |
| 156 |
return best_hit, nucmer_matches |
| 157 |
|
| 158 |
|
| 159 |
def run(self): |
| 160 |
print('Looking for closest match from sequences within cluster', file=self.log_fh) |
| 161 |
best_hit_from_cluster, nucmer_matches = RefSeqChooser._closest_nucmer_match_between_fastas(self.cluster_fasta, self.assembly_fasta_in, self.log_fh, self.nucmer_min_id, self.nucmer_min_len, self.nucmer_breaklen, False, True) |
| 162 |
if best_hit_from_cluster is None: |
| 163 |
return |
| 164 |
|
| 165 |
self.closest_ref_within_cluster = best_hit_from_cluster.ref_name |
| 166 |
contigs_prefix = best_hit_from_cluster.qry_name.rsplit('.', maxsplit=2)[0] |
| 167 |
print('Closest cluster ref sequence is', self.closest_ref_within_cluster, 'to assembly', contigs_prefix, file=self.log_fh) |
| 168 |
tmpdir = tempfile.mkdtemp(prefix='tmp.choose_ref.', dir=os.getcwd()) |
| 169 |
pieces_fasta_file = os.path.join(tmpdir, 'nucmer_vs_cluster_refs.pieces.fa') |
| 170 |
pieces_coords = [hit for hit in nucmer_matches[best_hit_from_cluster.ref_name] if hit.qry_name.startswith(contigs_prefix + '.')] |
| 171 |
RefSeqChooser._make_matching_contig_pieces_fasta(self.assembly_fasta_in, pieces_coords, pieces_fasta_file) |
| 172 |
|
| 173 |
print('Checking for a better match to a ref sequence outside the cluster', file=self.log_fh) |
| 174 |
best_hit_from_all_seqs, not_needed = RefSeqChooser._closest_nucmer_match_between_fastas(self.all_refs_fasta, pieces_fasta_file, self.log_fh, self.nucmer_min_id, self.nucmer_min_len, self.nucmer_breaklen, True, False) |
| 175 |
common.rmtree(tmpdir) |
| 176 |
self.closest_ref_from_all_refs = best_hit_from_all_seqs.ref_name |
| 177 |
if self.closest_ref_from_all_refs is None: |
| 178 |
return |
| 179 |
|
| 180 |
self.closest_ref_is_in_cluster = RefSeqChooser._sequence_is_in_fasta_file(self.closest_ref_from_all_refs, self.cluster_fasta) |
| 181 |
|
| 182 |
if self.closest_ref_is_in_cluster: |
| 183 |
print('Closest reference is', self.closest_ref_from_all_refs, 'and belongs to cluster', file=self.log_fh) |
| 184 |
l_and_c_bits = contigs_prefix.rsplit('.', maxsplit=2)[1:] |
| 185 |
name_regex = r'''\.''' + l_and_c_bits[0] + r'''\.''' + l_and_c_bits[1] + r'''\.ctg\.[0-9]+$''' |
| 186 |
print('Writing best assembly (contigs matching ', name_regex + ') to fasta file', self.assembly_fasta_out, file=self.log_fh) |
| 187 |
pyfastaq.tasks.filter(self.assembly_fasta_in, self.assembly_fasta_out, regex=name_regex) |
| 188 |
else: |
| 189 |
print('Closest reference is', self.closest_ref_from_all_refs, 'and does not belong to cluster', file=self.log_fh) |
| 190 |
|