| 1 |
import os |
| 2 |
import copy |
| 3 |
import sys |
| 4 |
import pyfastaq |
| 5 |
import dendropy |
| 6 |
from ariba import summary_sample |
| 7 |
|
| 8 |
class Error (Exception): pass |
| 9 |
|
| 10 |
required_keys_for_difference = {'no', 'yes', 'yes_nonunique', 'fragmented'} |
| 11 |
|
| 12 |
class Summary: |
| 13 |
def __init__( |
| 14 |
self, |
| 15 |
outprefix, |
| 16 |
filenames=None, |
| 17 |
fofn=None, |
| 18 |
filter_rows=True, |
| 19 |
filter_columns=True, |
| 20 |
min_id=90.0, |
| 21 |
cluster_cols='assembled,match,ref_seq,pct_id,ctg_cov,known_var,novel_var', |
| 22 |
make_phandango_tree=True, |
| 23 |
only_clusters=None, |
| 24 |
show_var_groups=False, |
| 25 |
show_known_vars=False, |
| 26 |
show_novel_vars=False, |
| 27 |
verbose=False, |
| 28 |
): |
| 29 |
if filenames is None and fofn is None: |
| 30 |
raise Error('Error! Must supply filenames or fofn to Summary(). Cannot continue') |
| 31 |
|
| 32 |
if filenames is None: |
| 33 |
self.filenames = {} |
| 34 |
else: |
| 35 |
self.filenames = {x: None for x in filenames} |
| 36 |
|
| 37 |
if fofn is not None: |
| 38 |
self.filenames.update(self._load_fofn(fofn)) |
| 39 |
|
| 40 |
self.cluster_columns = self._determine_cluster_cols(cluster_cols) |
| 41 |
self.filter_rows = filter_rows |
| 42 |
self.filter_columns = filter_columns |
| 43 |
self.min_id = min_id |
| 44 |
self.outprefix = outprefix |
| 45 |
self.make_phandango_tree = make_phandango_tree |
| 46 |
self.only_clusters = only_clusters |
| 47 |
self.show_var_groups = show_var_groups |
| 48 |
self.show_known_vars = show_known_vars |
| 49 |
self.show_novel_vars = show_novel_vars |
| 50 |
self.verbose = verbose |
| 51 |
|
| 52 |
|
| 53 |
@classmethod |
| 54 |
def _determine_cols(cls, cols_string, allowed_cols, error_string): |
| 55 |
if cols_string == '' or cols_string is None: |
| 56 |
return {x: False for x in allowed_cols} |
| 57 |
wanted_cols = set(cols_string.split(',')) |
| 58 |
if not wanted_cols.issubset(allowed_cols): |
| 59 |
raise Error('Error in ' + error_string + '. Allowed values are: ' + str(','.join(list(allowed_cols))) + '. Got: ' + cols_string) |
| 60 |
return {x: x in wanted_cols for x in allowed_cols} |
| 61 |
|
| 62 |
|
| 63 |
@staticmethod |
| 64 |
def _determine_cluster_cols(cols_string): |
| 65 |
allowed_cols = {'assembled', 'match', 'ref_seq', 'pct_id', 'ctg_cov', 'known_var', 'novel_var'} |
| 66 |
return Summary._determine_cols(cols_string, allowed_cols, 'cluster columns') |
| 67 |
|
| 68 |
|
| 69 |
@classmethod |
| 70 |
def _load_fofn(cls, fofn): |
| 71 |
'''Returns dictionary of filename -> short name. Value is None |
| 72 |
whenever short name is not provided''' |
| 73 |
filenames = {} |
| 74 |
f = pyfastaq.utils.open_file_read(fofn) |
| 75 |
for line in f: |
| 76 |
fields = line.rstrip().split() |
| 77 |
if len(fields) == 1: |
| 78 |
filenames[fields[0]] = None |
| 79 |
elif len(fields) == 2: |
| 80 |
filenames[fields[0]] = fields[1] |
| 81 |
else: |
| 82 |
raise Error('Error at the following line of file ' + fofn + '. Expected at most 2 fields.\n' + line) |
| 83 |
|
| 84 |
pyfastaq.utils.close(f) |
| 85 |
return filenames |
| 86 |
|
| 87 |
|
| 88 |
def _check_files_exist(self): |
| 89 |
for fname in self.filenames: |
| 90 |
if not os.path.exists(fname): |
| 91 |
raise Error('File not found: "' + fname + '". Cannot continue') |
| 92 |
|
| 93 |
|
| 94 |
@classmethod |
| 95 |
def _load_input_files(cls, filenames, min_id, verbose=False, only_clusters=None): |
| 96 |
samples = {} |
| 97 |
for filename in filenames: |
| 98 |
samples[filename] = summary_sample.SummarySample(filename, min_pc_id=min_id, only_clusters=only_clusters) |
| 99 |
samples[filename].run() |
| 100 |
if verbose: |
| 101 |
print('Loaded file', filename, flush=True) |
| 102 |
return samples |
| 103 |
|
| 104 |
|
| 105 |
def _gather_unfiltered_output_data(self): |
| 106 |
self.all_potential_columns = {} |
| 107 |
self.all_data = {} |
| 108 |
|
| 109 |
for filename in sorted(self.samples): |
| 110 |
self.all_data[filename] = {} |
| 111 |
for cluster in self.samples[filename].clusters.values(): |
| 112 |
self.all_data[filename][cluster.name] = {} |
| 113 |
if cluster.name not in self.all_potential_columns: |
| 114 |
self.all_potential_columns[cluster.name] = {'summary' : set(), 'groups': set(), 'vars': set()} |
| 115 |
|
| 116 |
this_cluster_dict = {'groups': {}, 'vars': {}} |
| 117 |
|
| 118 |
if cluster.summary['assembled'] == 'no': |
| 119 |
this_cluster_dict['summary'] = { |
| 120 |
'assembled': 'no', |
| 121 |
'known_var': 'NA', |
| 122 |
'match': 'no', |
| 123 |
'novel_var': 'NA', |
| 124 |
'pct_id': 'NA', |
| 125 |
'ctg_cov': 'NA', |
| 126 |
'ref_seq': 'NA' |
| 127 |
} |
| 128 |
else: |
| 129 |
this_cluster_dict['summary'] = copy.copy(cluster.summary) |
| 130 |
seen_groups = {} |
| 131 |
|
| 132 |
for variant in cluster.variants: |
| 133 |
if (self.show_known_vars and variant.known) or (self.show_novel_vars and not variant.known): |
| 134 |
this_cluster_dict['vars'][variant.var_string] = 'yes' if (variant.het_percent is None or not variant.is_het) else 'het' |
| 135 |
if variant.het_percent is not None: |
| 136 |
this_cluster_dict['vars'][variant.var_string + '.%'] = variant.het_percent |
| 137 |
|
| 138 |
if self.show_var_groups and variant.var_group != '.': |
| 139 |
if variant.var_group not in seen_groups: |
| 140 |
seen_groups[variant.var_group] = {'yes': 0, 'het': 0} |
| 141 |
|
| 142 |
if variant.het_percent is not None: |
| 143 |
this_cluster_dict['groups'][variant.var_group + '.%'] = variant.het_percent |
| 144 |
|
| 145 |
if variant.is_het: |
| 146 |
seen_groups[variant.var_group]['het'] += 1 |
| 147 |
this_cluster_dict['groups'][variant.var_group] = 'het' |
| 148 |
else: |
| 149 |
seen_groups[variant.var_group]['yes'] += 1 |
| 150 |
this_cluster_dict['groups'][variant.var_group] = 'yes' |
| 151 |
|
| 152 |
for group, d in seen_groups.items(): |
| 153 |
if d['het'] > 0 and d['het'] + d['yes'] > 1: |
| 154 |
this_cluster_dict['groups'][group] = 'yes_multi_het' |
| 155 |
this_cluster_dict['groups'][group + '.%'] = 'NA' |
| 156 |
|
| 157 |
for x in this_cluster_dict: |
| 158 |
self.all_potential_columns[cluster.name][x].update(set(this_cluster_dict[x].keys())) |
| 159 |
|
| 160 |
self.all_data[filename][cluster.name] = this_cluster_dict |
| 161 |
|
| 162 |
|
| 163 |
@classmethod |
| 164 |
def _to_matrix(cls, filenames, all_data, all_potential_columns, cluster_cols): |
| 165 |
matrix = [] |
| 166 |
making_header_lines = True |
| 167 |
phandango_header = ['name'] |
| 168 |
phandango_suffixes = {'assembled': ':o1', 'match': ':o1', 'ref_seq': ':o2', 'pct_id': ':c1', 'ctg_cov': ':c3', 'known_var': ':o1', 'novel_var': ':o1'} |
| 169 |
ref_seq_counter = 2 |
| 170 |
csv_header = ['name'] |
| 171 |
summary_cols_in_order = ['assembled', 'match', 'ref_seq', 'pct_id', 'ctg_cov', 'known_var', 'novel_var'] |
| 172 |
summary_cols_set = set(['assembled', 'match', 'ref_seq', 'pct_id', 'ctg_cov', 'known_var', 'novel_var']) |
| 173 |
summary_cols_in_order = [x for x in summary_cols_in_order if cluster_cols[x]] |
| 174 |
|
| 175 |
for filename in sorted(filenames): |
| 176 |
line = [filename if filenames[filename] is None else filenames[filename]] |
| 177 |
|
| 178 |
for cluster_name in sorted(all_potential_columns): |
| 179 |
group_cols = sorted(list(all_potential_columns[cluster_name]['groups'])) |
| 180 |
var_cols = sorted(list(all_potential_columns[cluster_name]['vars'])) |
| 181 |
|
| 182 |
for col in summary_cols_in_order + group_cols + var_cols: |
| 183 |
if making_header_lines: |
| 184 |
csv_header.append(cluster_name + '.' + col) |
| 185 |
if col == 'ref_seq': |
| 186 |
phandango_suffixes[col] = ':o' + str(ref_seq_counter) |
| 187 |
ref_seq_counter += 1 |
| 188 |
phandango_header.append(cluster_name + '.' + col + phandango_suffixes[col]) |
| 189 |
elif col in phandango_suffixes: |
| 190 |
phandango_header.append(cluster_name + '.' + col + phandango_suffixes[col]) |
| 191 |
elif col.endswith('.%'): |
| 192 |
phandango_header.append(cluster_name + '.' + col + ':c2') |
| 193 |
else: |
| 194 |
phandango_header.append(cluster_name + '.' + col + ':o1') |
| 195 |
|
| 196 |
for col_type in ['summary', 'groups', 'vars']: |
| 197 |
if cluster_name in all_data[filename] and col in all_data[filename][cluster_name][col_type]: |
| 198 |
line.append(all_data[filename][cluster_name][col_type][col]) |
| 199 |
break |
| 200 |
else: |
| 201 |
if col in {'assembled', 'match'}: |
| 202 |
line.append('no') |
| 203 |
elif col in summary_cols_set: |
| 204 |
line.append('NA') |
| 205 |
elif cluster_name in all_data[filename] and all_data[filename][cluster_name]['summary'].get('assembled', 'no') != 'no': |
| 206 |
if col.endswith('.%'): |
| 207 |
line.append('NA') |
| 208 |
else: |
| 209 |
line.append('no') |
| 210 |
else: |
| 211 |
line.append('NA') |
| 212 |
|
| 213 |
making_header_lines = False |
| 214 |
matrix.append(line) |
| 215 |
|
| 216 |
assert len(phandango_header) == len(csv_header) |
| 217 |
for line in matrix: |
| 218 |
assert len(line) == len(csv_header) |
| 219 |
return phandango_header, csv_header, matrix |
| 220 |
|
| 221 |
|
| 222 |
@classmethod |
| 223 |
def _filter_matrix_rows(cls, matrix): |
| 224 |
'''matrix = output from _to_matrix''' |
| 225 |
indexes_to_keep = [] |
| 226 |
|
| 227 |
for i in range(len(matrix)): |
| 228 |
keep_row = False |
| 229 |
for element in matrix[i]: |
| 230 |
if element not in {'NA', 'no'}: |
| 231 |
keep_row = True |
| 232 |
break |
| 233 |
if keep_row: |
| 234 |
indexes_to_keep.append(i) |
| 235 |
|
| 236 |
return [matrix[i] for i in indexes_to_keep] |
| 237 |
|
| 238 |
|
| 239 |
@classmethod |
| 240 |
def _filter_matrix_columns(cls, matrix, phandango_header, csv_header): |
| 241 |
'''phandango_header, csv_header, matrix = output from _to_matrix''' |
| 242 |
indexes_to_keep = set() |
| 243 |
|
| 244 |
for row in matrix: |
| 245 |
for i in range(len(row)): |
| 246 |
if row[i] not in {'NA', 'no'}: |
| 247 |
indexes_to_keep.add(i) |
| 248 |
|
| 249 |
indexes_to_keep = sorted(list(indexes_to_keep)) |
| 250 |
|
| 251 |
for i in range(len(matrix)): |
| 252 |
matrix[i] = [matrix[i][j] for j in indexes_to_keep] |
| 253 |
|
| 254 |
phandango_header = [phandango_header[i] for i in indexes_to_keep] |
| 255 |
csv_header = [csv_header[i] for i in indexes_to_keep] |
| 256 |
return phandango_header, csv_header, matrix |
| 257 |
|
| 258 |
|
| 259 |
@classmethod |
| 260 |
def _add_phandango_colour_columns(cls, header, matrix, nonunique_same_colour=True): |
| 261 |
header = copy.deepcopy(header) |
| 262 |
matrix = copy.deepcopy(matrix) |
| 263 |
cols_to_add_colour_col = [i for i in range(len(header)) if header[i].endswith(':o1')] |
| 264 |
field_to_col = { |
| 265 |
'yes': '#33a02c', |
| 266 |
'yes_nonunique': '#33a02c' if nonunique_same_colour else '#b2df8a', |
| 267 |
'no': '#fb9a99', |
| 268 |
'NA': '#ffffff', |
| 269 |
'het': '#fdbf6f', |
| 270 |
'yes_multi_het': '#fdbf6f', |
| 271 |
'fragmented': '#1f78b4', |
| 272 |
'interrupted': '#a6cee3', |
| 273 |
'partial': '#fdbf6f', |
| 274 |
} |
| 275 |
|
| 276 |
cols_to_add_colour_col.reverse() |
| 277 |
|
| 278 |
for col_index in cols_to_add_colour_col: |
| 279 |
header[col_index] = header[col_index][:-3] |
| 280 |
header.insert(col_index + 1, header[col_index] + ':colour') |
| 281 |
|
| 282 |
for row_index in range(len(matrix)): |
| 283 |
colour = field_to_col[matrix[row_index][col_index]] |
| 284 |
matrix[row_index].insert(col_index + 1, colour) |
| 285 |
|
| 286 |
return header, matrix |
| 287 |
|
| 288 |
|
| 289 |
@classmethod |
| 290 |
def _matrix_to_csv(cls, matrix, header, outfile, remove_nas=False): |
| 291 |
f = pyfastaq.utils.open_file_write(outfile) |
| 292 |
fixed_header = [x.replace(',', '/') for x in header] |
| 293 |
print(*fixed_header, sep=',', file=f) |
| 294 |
for line in matrix: |
| 295 |
if remove_nas: |
| 296 |
new_line = ['' if x=='NA' else x for x in line] |
| 297 |
print(*new_line, sep=',', file=f) |
| 298 |
else: |
| 299 |
print(*line, sep=',', file=f) |
| 300 |
pyfastaq.utils.close(f) |
| 301 |
|
| 302 |
|
| 303 |
@staticmethod |
| 304 |
def _distance_score_between_values(value1, value2): |
| 305 |
if value1 == 'partial': |
| 306 |
value1 = 'no' |
| 307 |
if value2 == 'partial': |
| 308 |
value2 = 'no' |
| 309 |
value_set = {value1, value2} |
| 310 |
if value_set.isdisjoint(required_keys_for_difference) or value1 == value2 or value_set == {'NA', 'no'}: |
| 311 |
return 0 |
| 312 |
else: |
| 313 |
return 1 |
| 314 |
|
| 315 |
|
| 316 |
@classmethod |
| 317 |
def _distance_score_between_lists(cls, scores1, scores2): |
| 318 |
assert len(scores1) == len(scores2) |
| 319 |
return sum([cls._distance_score_between_values(scores1[i], scores2[i]) for i in range(1, len(scores1))]) |
| 320 |
|
| 321 |
|
| 322 |
@classmethod |
| 323 |
def _write_distance_matrix(cls, lines, outfile): |
| 324 |
if len(lines) < 2: |
| 325 |
raise Error('Cannot calculate distance matrix to make tree for phandango.\n' + |
| 326 |
'Only one sample present.') |
| 327 |
|
| 328 |
if len(lines[0]) < 2: |
| 329 |
raise Error('Cannot calculate distance matrix to make tree for phandango. Not enough columns') |
| 330 |
|
| 331 |
scores = [[0 for i in range(len(lines))] for j in range(len(lines))] |
| 332 |
|
| 333 |
for i in range(len(lines)): |
| 334 |
for j in range(i + 1, len(lines), 1): |
| 335 |
scores[i][j] = Summary._distance_score_between_lists(lines[i], lines[j]) |
| 336 |
scores[j][i] = scores[i][j] |
| 337 |
|
| 338 |
with open(outfile, 'w') as f: |
| 339 |
sample_names = [''] + [x[0] for x in lines] |
| 340 |
print(*sample_names, sep='\t', file=f) |
| 341 |
for i in range(len(scores)): |
| 342 |
print(lines[i][0], *scores[i], sep='\t', file=f) |
| 343 |
|
| 344 |
|
| 345 |
@classmethod |
| 346 |
def _newick_from_dist_matrix(cls, distance_file, outfile): |
| 347 |
with open(distance_file) as f: |
| 348 |
pdm = dendropy.PhylogeneticDistanceMatrix.from_csv(src=f, delimiter='\t') |
| 349 |
upgma_tree = pdm.upgma_tree() |
| 350 |
with open(outfile, 'w') as f: |
| 351 |
print(upgma_tree.as_string("newick", suppress_rooting=True).replace("'", ''), end='', file=f) |
| 352 |
|
| 353 |
|
| 354 |
def run(self): |
| 355 |
if self.verbose: |
| 356 |
print('Loading input files...', flush=True) |
| 357 |
self._check_files_exist() |
| 358 |
self.samples = self._load_input_files(self.filenames, self.min_id, verbose=self.verbose, only_clusters=self.only_clusters) |
| 359 |
if self.verbose: |
| 360 |
print('Generating output rows', flush=True) |
| 361 |
self._gather_unfiltered_output_data() |
| 362 |
phandango_header, csv_header, matrix = Summary._to_matrix(self.filenames, self.all_data, self.all_potential_columns, self.cluster_columns) |
| 363 |
|
| 364 |
# sanity check same number of columns in headers and matrix |
| 365 |
lengths = {len(x) for x in matrix} |
| 366 |
assert len(lengths) == 1 |
| 367 |
assert len(matrix[0]) == len(phandango_header) == len(csv_header) |
| 368 |
|
| 369 |
if self.filter_rows: |
| 370 |
if self.verbose: |
| 371 |
print('Filtering rows', flush=True) |
| 372 |
matrix = Summary._filter_matrix_rows(matrix) |
| 373 |
|
| 374 |
if len(matrix) == 0: |
| 375 |
print('No rows left after filtering rows. Cannot continue', file=sys.stderr) |
| 376 |
sys.exit(1) |
| 377 |
|
| 378 |
if self.filter_columns: |
| 379 |
if self.verbose: |
| 380 |
print('Filtering columns', flush=True) |
| 381 |
phandango_header, csv_header, matrix = Summary._filter_matrix_columns(matrix, phandango_header, csv_header) |
| 382 |
|
| 383 |
if len(matrix) == 0 or len(matrix[0]) == 0: |
| 384 |
print('No columns left after filtering columns. Cannot continue', file=sys.stderr) |
| 385 |
|
| 386 |
# sanity check same number of columns in headers and matrix |
| 387 |
lengths = {len(x) for x in matrix} |
| 388 |
assert len(lengths) == 1 |
| 389 |
assert len(matrix[0]) == len(phandango_header) == len(csv_header) |
| 390 |
|
| 391 |
csv_file = self.outprefix + '.csv' |
| 392 |
if self.verbose: |
| 393 |
print('Writing csv file', csv_file, flush=True) |
| 394 |
Summary._matrix_to_csv(matrix, csv_header, csv_file) |
| 395 |
|
| 396 |
if len(matrix) > 1: |
| 397 |
if self.verbose: |
| 398 |
print('Making Phandango csv file', csv_file, flush=True) |
| 399 |
csv_file = self.outprefix + '.phandango.csv' |
| 400 |
phandango_header, phandango_matrix = Summary._add_phandango_colour_columns(phandango_header, matrix, nonunique_same_colour=True) |
| 401 |
Summary._matrix_to_csv(phandango_matrix, phandango_header, csv_file, remove_nas=True) |
| 402 |
|
| 403 |
if self.make_phandango_tree: |
| 404 |
dist_matrix_file = self.outprefix + '.phandango.distance_matrix' |
| 405 |
tree_file = self.outprefix + '.phandango.tre' |
| 406 |
|
| 407 |
if self.verbose: |
| 408 |
print('Making Phandango distance matrix', dist_matrix_file, flush=True) |
| 409 |
Summary._write_distance_matrix(matrix, dist_matrix_file) |
| 410 |
|
| 411 |
if self.verbose: |
| 412 |
print('Making Phandango tree file', tree_file, flush=True) |
| 413 |
Summary._newick_from_dist_matrix(dist_matrix_file, tree_file) |
| 414 |
os.unlink(dist_matrix_file) |
| 415 |
elif self.verbose: |
| 416 |
print('Skipping making tree because you asked me not to make it', flush=True) |
| 417 |
else: |
| 418 |
print('Made csv file. Not making Phandango files because only one sample remains after filtering', file=sys.stderr) |
| 419 |
|
| 420 |
if self.verbose: |
| 421 |
print('Finished', flush=True) |
| 422 |
|