| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
import sys, os, subprocess, inspect |
| 4 |
import platform, multiprocessing |
| 5 |
import string, re |
| 6 |
from datetime import datetime, date, time |
| 7 |
import copy |
| 8 |
from argparse import ArgumentParser, FileType |
| 9 |
|
| 10 |
|
| 11 |
""" |
| 12 |
""" |
| 13 |
def read_taxonomy_tree(tax_file): |
| 14 |
taxonomy_tree = {} |
| 15 |
for line in tax_file: |
| 16 |
fields = line.strip().split('\t') |
| 17 |
assert len(fields) == 5 |
| 18 |
tax_id, parent_tax_id, rank = fields[0], fields[2], fields[4] |
| 19 |
assert tax_id not in taxonomy_tree |
| 20 |
taxonomy_tree[tax_id] = [parent_tax_id, rank] |
| 21 |
return taxonomy_tree |
| 22 |
|
| 23 |
|
| 24 |
""" |
| 25 |
""" |
| 26 |
def compare_scm(centrifuge_out, true_out, taxonomy_tree, rank): |
| 27 |
higher_ranked = {} |
| 28 |
|
| 29 |
ancestors = set() |
| 30 |
for tax_id in taxonomy_tree.keys(): |
| 31 |
if tax_id in ancestors: |
| 32 |
continue |
| 33 |
while True: |
| 34 |
parent_tax_id, cur_rank = taxonomy_tree[tax_id] |
| 35 |
if parent_tax_id in ancestors: |
| 36 |
break |
| 37 |
if tax_id == parent_tax_id: |
| 38 |
break |
| 39 |
tax_id = parent_tax_id |
| 40 |
ancestors.add(tax_id) |
| 41 |
|
| 42 |
db_dic = {} |
| 43 |
first = True |
| 44 |
for line in open(centrifuge_out): |
| 45 |
if first: |
| 46 |
first = False |
| 47 |
continue |
| 48 |
read_name, seq_id, tax_id, score, _, _, _, _ = line.strip().split('\t') |
| 49 |
|
| 50 |
# Traverse up taxonomy tree to match the given rank parameter |
| 51 |
rank_tax_id = tax_id |
| 52 |
if rank != "strain": |
| 53 |
while True: |
| 54 |
if tax_id not in taxonomy_tree: |
| 55 |
rank_tax_id = "" |
| 56 |
break |
| 57 |
parent_tax_id, cur_rank = taxonomy_tree[tax_id] |
| 58 |
if cur_rank == rank: |
| 59 |
rank_tax_id = tax_id |
| 60 |
break |
| 61 |
if tax_id == parent_tax_id: |
| 62 |
rank_tax_id = "" |
| 63 |
break |
| 64 |
tax_id = parent_tax_id |
| 65 |
else: |
| 66 |
assert rank == "strain" |
| 67 |
if tax_id in ancestors: |
| 68 |
continue |
| 69 |
|
| 70 |
if rank_tax_id == "": |
| 71 |
# higher_ranked[read_name] = True |
| 72 |
continue |
| 73 |
|
| 74 |
if read_name not in db_dic: |
| 75 |
db_dic[read_name] = set() |
| 76 |
db_dic[read_name].add(rank_tax_id) |
| 77 |
|
| 78 |
classified, unclassified, unique_classified = 0, 0, 0 |
| 79 |
for line in open(true_out): |
| 80 |
if line.startswith('@'): |
| 81 |
continue |
| 82 |
|
| 83 |
fields = line.strip().split('\t') |
| 84 |
if len(fields) != 3: |
| 85 |
print >> sys.stderr, "Warning: %s missing" % (line.strip()) |
| 86 |
continue |
| 87 |
read_name, tax_id = fields[1:3] |
| 88 |
# Traverse up taxonomy tree to match the given rank parameter |
| 89 |
rank_tax_id = tax_id |
| 90 |
if rank != "strain": |
| 91 |
while True: |
| 92 |
if tax_id not in taxonomy_tree: |
| 93 |
rank_tax_id = "" |
| 94 |
break |
| 95 |
parent_tax_id, cur_rank = taxonomy_tree[tax_id] |
| 96 |
if cur_rank == rank: |
| 97 |
rank_tax_id = tax_id |
| 98 |
break |
| 99 |
if tax_id == parent_tax_id: |
| 100 |
rank_tax_id = "" |
| 101 |
break |
| 102 |
tax_id = parent_tax_id |
| 103 |
if rank_tax_id == "": |
| 104 |
continue |
| 105 |
if read_name not in db_dic: |
| 106 |
unclassified += 1 |
| 107 |
continue |
| 108 |
|
| 109 |
maps = db_dic[read_name] |
| 110 |
if rank_tax_id in maps: |
| 111 |
classified += 1 |
| 112 |
if len(maps) == 1 and read_name not in higher_ranked: |
| 113 |
unique_classified += 1 |
| 114 |
else: |
| 115 |
unclassified += 1 |
| 116 |
# daehwan - for debugging purposes |
| 117 |
# print read_name |
| 118 |
|
| 119 |
raw_unique_classified = 0 |
| 120 |
for read_name, maps in db_dic.items(): |
| 121 |
if len(maps) == 1 and read_name not in higher_ranked: |
| 122 |
raw_unique_classified += 1 |
| 123 |
return classified, unique_classified, unclassified, len(db_dic), raw_unique_classified |
| 124 |
|
| 125 |
|
| 126 |
""" |
| 127 |
""" |
| 128 |
def evaluate(index_base, |
| 129 |
ranks, |
| 130 |
verbose, |
| 131 |
debug): |
| 132 |
# Current script directory |
| 133 |
curr_script = os.path.realpath(inspect.getsourcefile(evaluate)) |
| 134 |
path_base = os.path.dirname(curr_script) + "/.." |
| 135 |
|
| 136 |
def check_files(fnames): |
| 137 |
for fname in fnames: |
| 138 |
if not os.path.exists(fname): |
| 139 |
return False |
| 140 |
return True |
| 141 |
|
| 142 |
# Check if indexes exists, otherwise create indexes |
| 143 |
index_path = "%s/indexes/Centrifuge" % path_base |
| 144 |
# index_path = "." |
| 145 |
if not os.path.exists(path_base + "/indexes"): |
| 146 |
os.mkdir(path_base + "/indexes") |
| 147 |
if not os.path.exists(index_path): |
| 148 |
os.mkdir(index_path) |
| 149 |
index_fnames = ["%s/%s.%d.cf" % (index_path, index_base, i+1) for i in range(3)] |
| 150 |
assert check_files(index_fnames) |
| 151 |
|
| 152 |
# Read taxonomic IDs |
| 153 |
centrifuge_inspect = os.path.join(path_base, "../centrifuge-inspect") |
| 154 |
tax_ids = set() |
| 155 |
tax_cmd = [centrifuge_inspect, |
| 156 |
"--conversion-table", |
| 157 |
"%s/%s" % (index_path, "b+h+v")] |
| 158 |
tax_proc = subprocess.Popen(tax_cmd, stdout=subprocess.PIPE) |
| 159 |
for line in tax_proc.stdout: |
| 160 |
_, tax_id = line.strip().split() |
| 161 |
tax_ids.add(tax_id) |
| 162 |
tax_ids = list(tax_ids) |
| 163 |
|
| 164 |
# Read taxonomic tree |
| 165 |
tax_tree_cmd = [centrifuge_inspect, |
| 166 |
"--taxonomy-tree", |
| 167 |
"%s/%s" % (index_path, "b+h+v")] |
| 168 |
tax_tree_proc = subprocess.Popen(tax_tree_cmd, stdout=subprocess.PIPE, stderr=open("/dev/null", 'w')) |
| 169 |
taxonomy_tree = read_taxonomy_tree(tax_tree_proc.stdout) |
| 170 |
|
| 171 |
compressed = (index_base.find("compressed") != -1) or (index_base == "centrifuge_Dec_Bonly") |
| 172 |
|
| 173 |
read_fname = "centrifuge_data/bacteria_sim10K/bacteria_sim10K.fa" |
| 174 |
scm_fname = "centrifuge_data/bacteria_sim10K/bacteria_sim10K.truth_species" |
| 175 |
read_fnames = [read_fname, scm_fname] |
| 176 |
|
| 177 |
program_bin_base = "%s/.." % path_base |
| 178 |
centrifuge_cmd = ["%s/centrifuge" % program_bin_base, |
| 179 |
# "-k", "20", |
| 180 |
# "--min-hitlen", "15", |
| 181 |
"-f", |
| 182 |
"-p", "1", |
| 183 |
"%s/%s" % (index_path, index_base), |
| 184 |
read_fname] |
| 185 |
|
| 186 |
if verbose: |
| 187 |
print >> sys.stderr, ' '.join(centrifuge_cmd) |
| 188 |
|
| 189 |
out_fname = "centrifuge.output" |
| 190 |
proc = subprocess.Popen(centrifuge_cmd, stdout=open(out_fname, "w"), stderr=subprocess.PIPE) |
| 191 |
proc.communicate() |
| 192 |
|
| 193 |
results = {"strain" : [0, 0, 0], |
| 194 |
"species" : [0, 0, 0], |
| 195 |
"genus" : [0, 0, 0], |
| 196 |
"family" : [0, 0, 0], |
| 197 |
"order" : [0, 0, 0], |
| 198 |
"class" : [0, 0, 0], |
| 199 |
"phylum" : [0, 0, 0]} |
| 200 |
for rank in ranks: |
| 201 |
if compressed and rank == "strain": |
| 202 |
continue |
| 203 |
|
| 204 |
classified, unique_classified, unclassified, raw_classified, raw_unique_classified = \ |
| 205 |
compare_scm(out_fname, scm_fname, taxonomy_tree, rank) |
| 206 |
results[rank] = [classified, unique_classified, unclassified] |
| 207 |
num_cases = classified + unclassified |
| 208 |
# if rank == "strain": |
| 209 |
# assert num_cases == num_fragment |
| 210 |
|
| 211 |
print >> sys.stderr, "\t\t%s" % rank |
| 212 |
print >> sys.stderr, "\t\t\tsensitivity: {:,} / {:,} ({:.2%})".format(classified, num_cases, float(classified) / num_cases) |
| 213 |
print >> sys.stderr, "\t\t\tprecision : {:,} / {:,} ({:.2%})".format(classified, raw_classified, float(classified) / raw_classified) |
| 214 |
print >> sys.stderr, "\n\t\t\tfor uniquely classified " |
| 215 |
print >> sys.stderr, "\t\t\t\t\tsensitivity: {:,} / {:,} ({:.2%})".format(unique_classified, num_cases, float(unique_classified) / num_cases) |
| 216 |
print >> sys.stderr, "\t\t\t\t\tprecision : {:,} / {:,} ({:.2%})".format(unique_classified, raw_unique_classified, float(unique_classified) / raw_unique_classified) |
| 217 |
|
| 218 |
# Calculate sum of squared residuals in abundance |
| 219 |
""" |
| 220 |
if rank == "strain": |
| 221 |
abundance_SSR = compare_abundance("centrifuge_report.tsv", truth_fname, taxonomy_tree, debug) |
| 222 |
print >> sys.stderr, "\t\t\tsum of squared residuals in abundance: {}".format(abundance_SSR) |
| 223 |
""" |
| 224 |
|
| 225 |
# calculate true abundance |
| 226 |
true_abundance = {} |
| 227 |
total_sum = 0.0 |
| 228 |
num_genomes, num_species = 0, 0 |
| 229 |
for line in open("abundance.txt"): |
| 230 |
seqID, taxID, genomeSize, reads, reads10K, genomeName = line.strip().split(',')[:6] |
| 231 |
genomeSize, reads, reads10K = int(genomeSize), int(reads), int(reads10K) |
| 232 |
if reads <= 0: |
| 233 |
continue |
| 234 |
num_genomes += 1 |
| 235 |
while True: |
| 236 |
if taxID not in taxonomy_tree: |
| 237 |
rank_taxID = "" |
| 238 |
break |
| 239 |
parent_taxID, rank = taxonomy_tree[taxID] |
| 240 |
if rank == "species": |
| 241 |
rank_taxID = taxID |
| 242 |
break |
| 243 |
if taxID == parent_taxID: |
| 244 |
rank_taxID = "" |
| 245 |
break |
| 246 |
taxID = parent_taxID |
| 247 |
if rank_taxID == "": |
| 248 |
continue |
| 249 |
assert rank == "species" |
| 250 |
num_species += 1 |
| 251 |
total_sum += (reads / float(genomeSize)) |
| 252 |
if rank_taxID not in true_abundance: |
| 253 |
true_abundance[rank_taxID] = 0.0 |
| 254 |
true_abundance[rank_taxID] += (reads / float(genomeSize)) |
| 255 |
for taxID, reads in true_abundance.items(): |
| 256 |
true_abundance[taxID] /= total_sum |
| 257 |
|
| 258 |
print >> sys.stderr, "number of genomes:", num_genomes |
| 259 |
print >> sys.stderr, "number of species:", num_species |
| 260 |
print >> sys.stderr, "number of uniq species:", len(true_abundance) |
| 261 |
|
| 262 |
read_fname = "centrifuge_data/bacteria_sim10M/bacteria_sim10M.fa" |
| 263 |
summary_fname = "centrifuge.summary" |
| 264 |
centrifuge_cmd = ["%s/centrifuge" % program_bin_base, |
| 265 |
# "-k", "20", |
| 266 |
# "--min-hitlen", "15", |
| 267 |
"--report-file", summary_fname, |
| 268 |
"-f", |
| 269 |
"-p", "3", |
| 270 |
"%s/%s" % (index_path, index_base), |
| 271 |
read_fname] |
| 272 |
|
| 273 |
if verbose: |
| 274 |
print >> sys.stderr, ' '.join(centrifuge_cmd) |
| 275 |
|
| 276 |
out_fname = "centrifuge.output" |
| 277 |
proc = subprocess.Popen(centrifuge_cmd, stdout=open(out_fname, "w"), stderr=subprocess.PIPE) |
| 278 |
proc.communicate() |
| 279 |
|
| 280 |
calc_abundance = {} |
| 281 |
for taxID in true_abundance.keys(): |
| 282 |
calc_abundance[taxID] = 0.0 |
| 283 |
first = True |
| 284 |
for line in open(summary_fname): |
| 285 |
if first: |
| 286 |
first = False |
| 287 |
continue |
| 288 |
name, taxID, taxRank, genomeSize, numReads, numUniqueReads, abundance = line.strip().split("\t") |
| 289 |
genomeSize, numReads, numUniqueReads, abundance = int(genomeSize), int(numReads), int(numUniqueReads), float(abundance) |
| 290 |
calc_abundance[taxID] = abundance |
| 291 |
|
| 292 |
# DK - for debugging purposes |
| 293 |
""" |
| 294 |
if taxID in true_abundance: |
| 295 |
print >> sys.stderr, "%s: %.6f vs. %.6f" % (taxID, abundance, true_abundance[taxID]) |
| 296 |
""" |
| 297 |
|
| 298 |
abundance_file = open("abundance.cmp", 'w') |
| 299 |
print >> abundance_file, "taxID\ttrue\tcalc\trank" |
| 300 |
for rank in ranks: |
| 301 |
if rank == "strain": |
| 302 |
continue |
| 303 |
true_abundance_rank, calc_abundance_rank = {}, {} |
| 304 |
for taxID in true_abundance.keys(): |
| 305 |
assert taxID in calc_abundance |
| 306 |
rank_taxID = taxID |
| 307 |
while True: |
| 308 |
if rank_taxID not in taxonomy_tree: |
| 309 |
rank_taxID = "" |
| 310 |
break |
| 311 |
parent_taxID, cur_rank = taxonomy_tree[rank_taxID] |
| 312 |
if cur_rank == rank: |
| 313 |
break |
| 314 |
if rank_taxID == parent_taxID: |
| 315 |
rank_taxID = "" |
| 316 |
break |
| 317 |
rank_taxID = parent_taxID |
| 318 |
if rank_taxID not in true_abundance_rank: |
| 319 |
true_abundance_rank[rank_taxID] = 0.0 |
| 320 |
calc_abundance_rank[rank_taxID] = 0.0 |
| 321 |
true_abundance_rank[rank_taxID] += true_abundance[taxID] |
| 322 |
calc_abundance_rank[rank_taxID] += calc_abundance[taxID] |
| 323 |
|
| 324 |
ssr = 0.0 # Sum of Squared Residuals |
| 325 |
for taxID in true_abundance_rank.keys(): |
| 326 |
assert taxID in calc_abundance_rank |
| 327 |
ssr += (true_abundance_rank[taxID] - calc_abundance_rank[taxID]) ** 2 |
| 328 |
print >> abundance_file, "%s\t%.6f\t%.6f\t%s" % (taxID, true_abundance_rank[taxID], calc_abundance_rank[taxID], rank) |
| 329 |
print >> sys.stderr, "%s) Sum of squared residuals: %.6f" % (rank, ssr) |
| 330 |
abundance_file.close() |
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
if __name__ == "__main__": |
| 335 |
parser = ArgumentParser( |
| 336 |
description='Centrifuge evaluation on Mason simulated reads') |
| 337 |
parser.add_argument("--index-base", |
| 338 |
type=str, |
| 339 |
default="b_compressed", |
| 340 |
help='Centrifuge index such as b_compressed, b+h+v, and centrifuge_Dec_Bonly (default: b_compressed)') |
| 341 |
rank_list_default = "strain,species,genus,family,order,class,phylum" |
| 342 |
parser.add_argument("--rank-list", |
| 343 |
dest="ranks", |
| 344 |
type=str, |
| 345 |
default=rank_list_default, |
| 346 |
help="A comma-separated list of ranks (default: %s)" % rank_list_default) |
| 347 |
parser.add_argument('-v', '--verbose', |
| 348 |
dest='verbose', |
| 349 |
action='store_true', |
| 350 |
help='also print some statistics to stderr') |
| 351 |
parser.add_argument('--debug', |
| 352 |
dest='debug', |
| 353 |
action='store_true', |
| 354 |
help='Debug') |
| 355 |
|
| 356 |
args = parser.parse_args() |
| 357 |
if not args.index_base: |
| 358 |
parser.print_help() |
| 359 |
exit(1) |
| 360 |
ranks = args.ranks.split(',') |
| 361 |
evaluate(args.index_base, |
| 362 |
ranks, |
| 363 |
args.verbose, |
| 364 |
args.debug) |