def main(): args = docopt(__doc__) #print(args) bam_f = args['--bam'] include_f = args['--include'] exclude_f = args['--exclude'] out_prefix = args['--out'] read_format = args['--read_format'] if not read_format in set(['fq', 'fa']): sys.exit("[X] Read format must be fq or fa!") noninterleaved = args['--noninterleaved'] include_unmapped = True if args['--exclude_unmapped']: include_unmapped = False out_f = BtIO.getOutFile(bam_f, out_prefix, None) if include_f and exclude_f: print(BtLog.error('43')) elif include_f: sequence_list = BtIO.parseList(include_f) BtIO.parseBamForFilter(bam_f, include_unmapped, noninterleaved, out_f, sequence_list, None, read_format) elif exclude_f: sequence_list = BtIO.parseList(exclude_f) BtIO.parseBamForFilter(bam_f, include_unmapped, noninterleaved, out_f, None, sequence_list, read_format) else: BtIO.parseBamForFilter(bam_f, include_unmapped, noninterleaved, out_f, None, None, read_format)
def mapping(): out_f, hit_f, map_f, taxid_d = None, None, None, {} hit_f = megablast_output #hit file: BLAST similarity search result (TSV format) map_f = "/home/nancy/assembly_app/blobtools/blobtools-master/taxon_n" #mapping file (TSV format), in which one column lists a sequence ID (of a subject) and another the NCBI TaxID map_col_sseqid = "0" #column of mapping file containing sequence IDs (of the subject) map_col_taxid = "2" #column of mapping file containing the TaxID of the subject hit_col_qseqid = "0" #column of the hit file containing query ID hit_col_sseqid = "1" #column of the hit file containing subject ID hit_col_score = "11" #column of the hit file containing (bit)score try: hit_col_qseqid = int(hit_col_qseqid) hit_col_sseqid = int(hit_col_sseqid) hit_col_score = int(hit_col_score) except ValueError: BtLog.error('41' % ( "--hit_column_qseqid, --hit_column_sseqid and --hit_column_score" )) if map_f: if map_col_sseqid and map_col_taxid: try: map_col_sseqid = int(map_col_sseqid) map_col_taxid = int(map_col_taxid) except ValueError: BtLog.error('44') print BtLog.status_d['1'] % ("Mapping file", map_f) taxid_d = BtIO.parseDict(map_f, map_col_sseqid, map_col_taxid) out_f = BtIO.getOutFile("taxified", hit_f, "out") else: BtLog.error('44') else: BtLog.error('41') output = [] print BtLog.status_d['1'] % ("similarity search result", hit_f) with open(hit_f) as fh: for idx, line in enumerate(fh): col = line.rstrip("\n").split() qseqid = col[hit_col_qseqid] sseqid = col[hit_col_sseqid] score = col[hit_col_score] tax_id = None if sseqid not in taxid_d: BtLog.warn_d['12'] % (sseqid, map_f) tax_id = taxid_d.get(sseqid, "N/A") output.append("%s\t%s\t%s\t%s" % (qseqid, tax_id, score, sseqid)) if output: with open(out_f, "w") as fh: print BtLog.status_d['24'] % out_f fh.write("\n".join(output) + "\n")
def main(): args = docopt(__doc__) bam_f = args['--bam'] include_f = args['--include'] exclude_f = args['--exclude'] out_prefix = args['--out'] include_unmapped = args['--include_unmapped'] gzip = None do_sort = args['--sort'] keep_sorted = args['--keep'] sort_threads = int(args['--threads']) out_f = BtIO.getOutFile(bam_f, out_prefix, None) if include_f and exclude_f: print BtLog.error('43') elif include_f: sequence_list = BtIO.parseList(include_f) BtIO.parseBamForFilter(bam_f, include_unmapped, out_f, sequence_list, None, gzip, do_sort, keep_sorted, sort_threads) elif exclude_f: sequence_list = BtIO.parseList(exclude_f) BtIO.parseBamForFilter(bam_f, include_unmapped, out_f, None, sequence_list, gzip, do_sort, keep_sorted, sort_threads) else: BtIO.parseBamForFilter(bam_f, include_unmapped, out_f, None, None, gzip, do_sort, keep_sorted, sort_threads)
def main(): args = docopt(__doc__) fasta_f = args['--infile'] list_f = args['--list'] invert = args['--invert'] prefix = args['--out'] output = [] out_f = BtIO.getOutFile(fasta_f, prefix, "filtered.fna") print BtLog.status_d['1'] % ("list", list_f) items = BtIO.parseSet(list_f) items_count = len(items) print BtLog.status_d['22'] % fasta_f items_parsed = [] sequences = 0 for header, sequence in BtIO.readFasta(fasta_f): sequences += 1 if header in items: if not (invert): items_parsed.append(header) output.append(">%s\n%s\n" % (header, sequence)) else: if (invert): items_parsed.append(header) output.append(">%s\n%s\n" % (header, sequence)) BtLog.progress(len(output), 10, items_count, no_limit=True) BtLog.progress(items_count, 10, items_count) items_parsed_count = len(items_parsed) print BtLog.status_d['23'] % ('{:.2%}'.format(items_parsed_count/sequences), "{:,}".format(items_count), "{:,}".format(items_parsed_count), "{:,}".format(sequences)) items_parsed_count_unique = len(set(items_parsed)) if not items_parsed_count == items_parsed_count_unique: print BtLog.warn_d['8'] % "\n\t\t\t".join(list(set([x for x in items_parsed if items_parsed.count(x) > 1]))) with open(out_f, "w") as fh: print BtLog.status_d['24'] % out_f fh.write("".join(output))
def main(): args = docopt(__doc__) fasta_f = args['--infile'] list_f = args['--list'] invert = args['--invert'] prefix = args['--out'] output = [] out_f = BtIO.getOutFile(fasta_f, prefix, "filtered.fna") print(BtLog.status_d['1'] % ("list", list_f)) items = BtIO.parseSet(list_f) items_count = len(items) print(BtLog.status_d['22'] % fasta_f) items_parsed = [] with tqdm(total=items_count, desc="[%] ", ncols=200, unit_scale=True) as pbar: for header, sequence in BtIO.readFasta(fasta_f): if header in items: if not (invert): items_parsed.append(header) output.append(">%s\n%s\n" % (header, sequence)) else: if (invert): items_parsed.append(header) output.append(">%s\n%s\n" % (header, sequence)) pbar.update() items_parsed_count = len(items_parsed) items_parsed_count_unique = len(set(items_parsed)) if not items_parsed_count == items_parsed_count_unique: print(BtLog.warn_d['8'] % "\n\t\t\t".join(list(set([x for x in items_parsed if items_parsed.count(x) > 1])))) with open(out_f, "w") as fh: print(BtLog.status_d['24'] % out_f) fh.write("".join(output))
def main(): #print(data_dir) args = docopt(__doc__) blobdb_f = args['--input'] prefix = args['--out'] ranks = args['--rank'] taxrule = args['--taxrule'] hits_flag = args['--hits'] seq_list_f = args['--list'] concoct = args['--concoct'] cov = args['--cov'] notable = args['--notable'] experimental = args['--experimental'] # Does blobdb_f exist ? if not isfile(blobdb_f): BtLog.error('0', blobdb_f) out_f = BtIO.getOutFile(blobdb_f, prefix, None) # Are ranks sane ? if 'all' in ranks: temp_ranks = RANKS[0:-1] ranks = temp_ranks[::-1] else: for rank in ranks: if rank not in RANKS: BtLog.error('9', rank) # Does seq_list file exist? seqs = [] if (seq_list_f): if isfile(seq_list_f): seqs = BtIO.parseList(seq_list_f) else: BtLog.error('0', seq_list_f) # Load BlobDb blobDb = BtCore.BlobDb('new') print(BtLog.status_d['9'] % (blobdb_f)) blobDb.load(blobdb_f) blobDb.version = interface.__version__ # Is taxrule sane and was it computed? if (blobDb.hitLibs) and taxrule not in blobDb.taxrules: BtLog.error('11', taxrule, blobDb.taxrules) # view(s) viewObjs = [] print(BtLog.status_d['14']) if not (notable): tableView = None if len(blobDb.hitLibs) > 1: tableView = BtCore.ViewObj(name="table", out_f=out_f, suffix="%s.table.txt" % (taxrule), body=[]) else: tableView = BtCore.ViewObj(name="table", out_f=out_f, suffix="table.txt", body=[]) viewObjs.append(tableView) if not experimental == 'False': meta = {} if isfile(experimental): meta = BtIO.readYaml(experimental) experimentalView = BtCore.ExperimentalViewObj(name="experimental", view_dir=out_f, blobDb=blobDb, meta=meta) viewObjs.append(experimentalView) if (concoct): concoctTaxView = None concoctCovView = None if len(blobDb.hitLibs) > 1: concoctTaxView = BtCore.ViewObj( name="concoct_tax", out_f=out_f, suffix="%s.concoct_taxonomy_info.csv" % (taxrule), body=dict()) concoctCovView = BtCore.ViewObj( name="concoct_cov", out_f=out_f, suffix="%s.concoct_coverage_info.tsv" % (taxrule), body=[]) else: concoctTaxView = BtCore.ViewObj(name="concoct_tax", out_f=out_f, suffix="concoct_taxonomy_info.csv", body=dict()) concoctCovView = BtCore.ViewObj(name="concoct_cov", out_f=out_f, suffix="concoct_coverage_info.tsv", body=[]) viewObjs.append(concoctTaxView) viewObjs.append(concoctCovView) if (cov): for cov_lib_name, covLibDict in blobDb.covLibs.items(): out_f = BtIO.getOutFile(covLibDict['f'], prefix, None) covView = BtCore.ViewObj(name="covlib", out_f=out_f, suffix="cov", body=[]) blobDb.view(viewObjs=[covView], ranks=None, taxrule=None, hits_flag=None, seqs=None, cov_libs=[cov_lib_name], progressbar=True) if (viewObjs): #for viewObj in viewObjs: # print(viewObj.name) blobDb.view(viewObjs=viewObjs, ranks=ranks, taxrule=taxrule, hits_flag=hits_flag, seqs=seqs, cov_libs=[], progressbar=True) print(BtLog.status_d['19'])
def main(): args = docopt(__doc__) args = BtPlot.check_input(args) blobdb_f = args['--infile'] rank = args['--rank'] min_length = int(args['--length']) max_group_plot = int(args['--plotgroups']) hide_nohits = args['--nohit'] taxrule = args['--taxrule'] c_index = args['--cindex'] exclude_groups = args['--exclude'] labels = args['--label'] colour_f = args['--colours'] refcov_f = args['--refcov'] catcolour_f = args['--catcolour'] multiplot = args['--multiplot'] out_prefix = args['--out'] sort_order = args['--sort'] sort_first = args['--sort_first'] hist_type = args['--hist'] no_title = args['--notitle'] ignore_contig_length = args['--noscale'] format_plot = args['--format'] no_plot_blobs = args['--noblobs'] no_plot_reads = args['--noreads'] legend_flag = args['--legend'] cumulative_flag = args['--cumulative'] cov_lib_selection = args['--lib'] filelabel = args['--filelabel'] exclude_groups = BtIO.parseCmdlist(exclude_groups) refcov_dict = BtIO.parseReferenceCov(refcov_f) user_labels = BtIO.parseCmdLabels(labels) catcolour_dict = BtIO.parseCatColour(catcolour_f) colour_dict = BtIO.parseColours(colour_f) # Load BlobDb print BtLog.status_d['9'] % blobdb_f blobDb = BtCore.BlobDb('blobplot') blobDb.version = blobtools.__version__ blobDb.load(blobdb_f) # Generate plot data print BtLog.status_d['18'] data_dict, min_cov, max_cov, cov_lib_dict = blobDb.getPlotData( rank, min_length, hide_nohits, taxrule, c_index, catcolour_dict) plotObj = BtPlot.PlotObj(data_dict, cov_lib_dict, cov_lib_selection, 'blobplot', sort_first) plotObj.exclude_groups = exclude_groups plotObj.version = blobDb.version plotObj.format = format_plot plotObj.max_cov = max_cov plotObj.min_cov = min_cov plotObj.no_title = no_title plotObj.multiplot = multiplot plotObj.hist_type = hist_type plotObj.ignore_contig_length = ignore_contig_length plotObj.max_group_plot = max_group_plot plotObj.legend_flag = legend_flag plotObj.cumulative_flag = cumulative_flag # order by which to plot (should know about user label) plotObj.group_order = BtPlot.getSortedGroups(data_dict, sort_order, sort_first) # labels for each level of stats plotObj.labels.update(plotObj.group_order) # plotObj.group_labels is dict that contains labels for each group : all/other/user_label if (user_labels): for group, label in user_labels.items(): plotObj.labels.add(label) plotObj.group_labels = {group: set() for group in plotObj.group_order} plotObj.relabel_and_colour(colour_dict, user_labels) plotObj.compute_stats() plotObj.refcov_dict = refcov_dict # Plotting info_flag = 1 out_f = '' for cov_lib in plotObj.cov_libs: plotObj.ylabel = "Coverage" plotObj.xlabel = "GC proportion" if (filelabel): plotObj.ylabel = basename(cov_lib_dict[cov_lib]['f']) out_f = "%s.%s.%s.p%s.%s.%s" % (blobDb.title, taxrule, rank, max_group_plot, hist_type, min_length) if catcolour_dict: out_f = "%s.%s" % (out_f, "catcolour") if ignore_contig_length: out_f = "%s.%s" % (out_f, "noscale") if c_index: out_f = "%s.%s" % (out_f, "c_index") if exclude_groups: out_f = "%s.%s" % (out_f, "exclude_" + "_".join(exclude_groups)) if labels: out_f = "%s.%s" % (out_f, "userlabel_" + "_".join( set([name for name in user_labels.values()]))) out_f = "%s.%s" % (out_f, "blobplot") if (plotObj.cumulative_flag): out_f = "%s.%s" % (out_f, "cumulative") if (plotObj.multiplot): out_f = "%s.%s" % (out_f, "multiplot") out_f = BtIO.getOutFile(out_f, out_prefix, None) if not (no_plot_blobs): plotObj.plotScatter(cov_lib, info_flag, out_f) info_flag = 0 if not (no_plot_reads) and ( plotObj.cov_libs_total_reads_dict[cov_lib]): # prevent plotting if --noreads or total_reads == 0 plotObj.plotBar(cov_lib, out_f) plotObj.write_stats(out_f)
def parseCoverage(self, **kwargs): # arguments covLibObjs = kwargs['covLibObjs'] no_base_cov = kwargs['no_base_cov'] for covLib in covLibObjs: self.addCovLib(covLib) print BtLog.status_d['1'] % (covLib.name, covLib.f) if covLib.fmt == 'bam' or covLib.fmt == 'sam': base_cov_dict = {} if covLib.fmt == 'bam': base_cov_dict, covLib.reads_total, covLib.reads_mapped, read_cov_dict = BtIO.parseBam( covLib.f, set(self.dict_of_blobs), no_base_cov) else: base_cov_dict, covLib.reads_total, covLib.reads_mapped, read_cov_dict = BtIO.parseSam( covLib.f, set(self.dict_of_blobs), no_base_cov) if covLib.reads_total == 0: print BtLog.warn_d['4'] % covLib.f for name, base_cov in base_cov_dict.items(): cov = base_cov / self.dict_of_blobs[name].agct_count covLib.cov_sum += cov self.dict_of_blobs[name].addCov(covLib.name, cov) self.dict_of_blobs[name].addReadCov( covLib.name, read_cov_dict[name]) # Create COV file for future use out_f = BtIO.getOutFile(covLib.f, kwargs.get('prefix', None), None) covView = ViewObj(name="covlib", out_f=out_f, suffix="cov", header="", body=[]) self.view(viewObjs=[covView], ranks=None, taxrule=None, hits_flag=None, seqs=None, cov_libs=[covLib.name], progressbar=False) elif covLib.fmt == 'cas': cov_dict, covLib.reads_total, covLib.reads_mapped, read_cov_dict = BtIO.parseCas( covLib.f, self.order_of_blobs) if covLib.reads_total == 0: print BtLog.warn_d['4'] % covLib.f for name, cov in cov_dict.items(): covLib.cov_sum += cov self.dict_of_blobs[name].addCov(covLib.name, cov) self.dict_of_blobs[name].addReadCov( covLib.name, read_cov_dict[name]) out_f = BtIO.getOutFile(covLib.f, kwargs.get('prefix', None), None) covView = ViewObj(name="covlib", out_f=out_f, suffix="cov", header="", body=[]) self.view(viewObjs=[covView], ranks=None, taxrule=None, hits_flag=None, seqs=None, cov_libs=[covLib.name], progressbar=False) elif covLib.fmt == 'cov': base_cov_dict, covLib.reads_total, covLib.reads_mapped, covLib.reads_unmapped, read_cov_dict = BtIO.parseCov( covLib.f, set(self.dict_of_blobs)) #cov_dict = BtIO.readCov(covLib.f, set(self.dict_of_blobs)) if not len(base_cov_dict) == self.seqs: print BtLog.warn_d['4'] % covLib.f for name, cov in base_cov_dict.items(): covLib.cov_sum += cov self.dict_of_blobs[name].addCov(covLib.name, cov) if name in read_cov_dict: self.dict_of_blobs[name].addReadCov( covLib.name, read_cov_dict[name]) else: pass covLib.mean_cov = covLib.cov_sum / self.seqs if covLib.cov_sum == 0.0: print BtLog.warn_d['6'] % (covLib.name) self.covLibs[covLib.name] = covLib
def main(): args = docopt(__doc__) out_f, hit_f, map_f, taxid_d = None, None, None, {} hit_f = args['--hit_file'] hit_col_qseqid = args['--hit_column_qseqid'] hit_col_sseqid = args['--hit_column_sseqid'] hit_col_score = args['--hit_column_score'] map_f = args['--taxid_mapping_file'] map_col_sseqid = args['--map_col_sseqid'] map_col_taxid = args['--map_col_taxid'] custom_f = args['--custom'] custom_taxid = args['--custom_taxid'] custom_score = args['--custom_score'] prefix = args['--out'] try: hit_col_qseqid = int(hit_col_qseqid) hit_col_sseqid = int(hit_col_sseqid) hit_col_score = int(hit_col_score) except ValueError: BtLog.error('41' % ( "--hit_column_qseqid, --hit_column_sseqid and --hit_column_score")) if custom_taxid: try: custom_taxid = int(custom_taxid) except TypeError: BtLog.error('26') out_f = BtIO.getOutFile(hit_f, prefix, "taxID_%s.out" % custom_taxid) taxid_d = defaultdict(lambda: custom_taxid) elif map_f: if map_col_sseqid and map_col_taxid: try: map_col_sseqid = int(map_col_sseqid) map_col_taxid = int(map_col_taxid) except ValueError: BtLog.error('44') print BtLog.status_d['1'] % ("Mapping file", map_f) taxid_d = BtIO.parseDict(map_f, map_col_sseqid, map_col_taxid) out_f = BtIO.getOutFile(hit_f, prefix, "taxified.out") else: BtLog.error('44') else: BtLog.error('41') output = [] print BtLog.status_d['1'] % ("similarity search result", hit_f) with open(hit_f) as fh: for idx, line in enumerate(fh): col = line.rstrip("\n").split() qseqid = col[hit_col_qseqid] sseqid = col[hit_col_sseqid] score = col[hit_col_score] tax_id = None if custom_taxid: tax_id = taxid_d[sseqid] else: if sseqid not in taxid_d: BtLog.warn_d['12'] % (sseqid, map_f) tax_id = taxid_d.get(sseqid, "N/A") output.append("%s\t%s\t%s\t%s" % (qseqid, tax_id, score, sseqid)) if output: with open(out_f, "w") as fh: print BtLog.status_d['24'] % out_f fh.write("\n".join(output) + "\n")
def main(): #main_dir = dirname(__file__) args = docopt(__doc__) fasta_f = args['--infile'] fasta_type = args['--type'] bam_fs = args['--bam'] cov_fs = args['--cov'] cas_fs = args['--cas'] hit_fs = args['--hitsfile'] prefix = args['--out'] nodesDB_f = args['--db'] names_f = args['--names'] estimate_cov_flag = True if not args['--calculate_cov'] else False nodes_f = args['--nodes'] taxrules = args['--taxrule'] try: min_bitscore_diff = float(args['--min_diff']) min_score = float(args['--min_score']) except ValueError(): BtLog.error('45') tax_collision_random = args['--tax_collision_random'] title = args['--title'] # outfile out_f = BtIO.getOutFile("blobDB", prefix, "json") if not (title): title = out_f # coverage if not (fasta_type) and not bam_fs and not cov_fs and not cas_fs: BtLog.error('1') cov_libs = [BtCore.CovLibObj('bam' + str(idx), 'bam', lib_f) for idx, lib_f in enumerate(bam_fs)] + \ [BtCore.CovLibObj('cas' + str(idx), 'cas', lib_f) for idx, lib_f in enumerate(cas_fs)] + \ [BtCore.CovLibObj('cov' + str(idx), 'cov', lib_f) for idx, lib_f in enumerate(cov_fs)] # taxonomy hit_libs = [ BtCore.HitLibObj('tax' + str(idx), 'tax', lib_f) for idx, lib_f in enumerate(hit_fs) ] # Create BlobDB object blobDb = BtCore.BlobDb(title) blobDb.version = interface.__version__ # Parse FASTA blobDb.parseFasta(fasta_f, fasta_type) # Parse nodesDB OR names.dmp, nodes.dmp nodesDB_default = join(dirname(abspath(__file__)), "../data/nodesDB.txt") nodesDB, nodesDB_f = BtIO.parseNodesDB(nodes=nodes_f, names=names_f, nodesDB=nodesDB_f, nodesDBdefault=nodesDB_default) blobDb.nodesDB_f = nodesDB_f # Parse similarity hits if (hit_libs): blobDb.parseHits(hit_libs) if not taxrules: if len(hit_libs) > 1: taxrules = ['bestsum', 'bestsumorder'] else: taxrules = ['bestsum'] blobDb.computeTaxonomy(taxrules, nodesDB, min_score, min_bitscore_diff, tax_collision_random) else: print(BtLog.warn_d['0']) # Parse coverage blobDb.parseCoverage(covLibObjs=cov_libs, estimate_cov=estimate_cov_flag, prefix=prefix) # Generating BlobDB and writing to file print(BtLog.status_d['7'] % out_f) BtIO.writeJson(blobDb.dump(), out_f)