id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
237,100 | bcbio/bcbio-nextgen | bcbio/structural/cnvkit.py | _add_coverage_bedgraph_to_output | def _add_coverage_bedgraph_to_output(out, data):
"""Add BedGraph representation of coverage to the output
"""
out_file = "%s.coverage.bedgraph" % os.path.splitext(out["cns"])[0]
if utils.file_exists(out_file):
out["bedgraph"] = out_file
return out
bam_file = dd.get_align_bam(data)
bedtools = config_utils.get_program("bedtools", data["config"])
samtools = config_utils.get_program("samtools", data["config"])
cns_file = out["cns"]
bed_file = tempfile.NamedTemporaryFile(suffix=".bed", delete=False).name
with file_transaction(data, out_file) as tx_out_file:
cmd = ("sed 1d {cns_file} | cut -f1,2,3 > {bed_file}; "
"{samtools} view -b -L {bed_file} {bam_file} | "
"{bedtools} genomecov -bg -ibam - -g {bed_file} >"
"{tx_out_file}").format(**locals())
do.run(cmd, "CNVkit bedGraph conversion")
os.remove(bed_file)
out["bedgraph"] = out_file
return out | python | def _add_coverage_bedgraph_to_output(out, data):
out_file = "%s.coverage.bedgraph" % os.path.splitext(out["cns"])[0]
if utils.file_exists(out_file):
out["bedgraph"] = out_file
return out
bam_file = dd.get_align_bam(data)
bedtools = config_utils.get_program("bedtools", data["config"])
samtools = config_utils.get_program("samtools", data["config"])
cns_file = out["cns"]
bed_file = tempfile.NamedTemporaryFile(suffix=".bed", delete=False).name
with file_transaction(data, out_file) as tx_out_file:
cmd = ("sed 1d {cns_file} | cut -f1,2,3 > {bed_file}; "
"{samtools} view -b -L {bed_file} {bam_file} | "
"{bedtools} genomecov -bg -ibam - -g {bed_file} >"
"{tx_out_file}").format(**locals())
do.run(cmd, "CNVkit bedGraph conversion")
os.remove(bed_file)
out["bedgraph"] = out_file
return out | [
"def",
"_add_coverage_bedgraph_to_output",
"(",
"out",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s.coverage.bedgraph\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"out",
"[",
"\"cns\"",
"]",
")",
"[",
"0",
"]",
"if",
"utils",
".",
"file_exists",
"(",... | Add BedGraph representation of coverage to the output | [
"Add",
"BedGraph",
"representation",
"of",
"coverage",
"to",
"the",
"output"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/cnvkit.py#L611-L631 |
237,101 | bcbio/bcbio-nextgen | bcbio/structural/cnvkit.py | _add_plots_to_output | def _add_plots_to_output(out, data):
"""Add CNVkit plots summarizing called copy number values.
"""
out["plot"] = {}
diagram_plot = _add_diagram_plot(out, data)
if diagram_plot:
out["plot"]["diagram"] = diagram_plot
scatter = _add_scatter_plot(out, data)
if scatter:
out["plot"]["scatter"] = scatter
scatter_global = _add_global_scatter_plot(out, data)
if scatter_global:
out["plot"]["scatter_global"] = scatter_global
return out | python | def _add_plots_to_output(out, data):
out["plot"] = {}
diagram_plot = _add_diagram_plot(out, data)
if diagram_plot:
out["plot"]["diagram"] = diagram_plot
scatter = _add_scatter_plot(out, data)
if scatter:
out["plot"]["scatter"] = scatter
scatter_global = _add_global_scatter_plot(out, data)
if scatter_global:
out["plot"]["scatter_global"] = scatter_global
return out | [
"def",
"_add_plots_to_output",
"(",
"out",
",",
"data",
")",
":",
"out",
"[",
"\"plot\"",
"]",
"=",
"{",
"}",
"diagram_plot",
"=",
"_add_diagram_plot",
"(",
"out",
",",
"data",
")",
"if",
"diagram_plot",
":",
"out",
"[",
"\"plot\"",
"]",
"[",
"\"diagram\... | Add CNVkit plots summarizing called copy number values. | [
"Add",
"CNVkit",
"plots",
"summarizing",
"called",
"copy",
"number",
"values",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/cnvkit.py#L633-L646 |
237,102 | bcbio/bcbio-nextgen | bcbio/structural/cnvkit.py | _get_larger_chroms | def _get_larger_chroms(ref_file):
"""Retrieve larger chromosomes, avoiding the smaller ones for plotting.
"""
from scipy.cluster.vq import kmeans, vq
all_sizes = []
for c in ref.file_contigs(ref_file):
all_sizes.append(float(c.size))
all_sizes.sort()
if len(all_sizes) > 5:
# separate out smaller chromosomes and haplotypes with kmeans
centroids, _ = kmeans(np.array(all_sizes), 2)
idx, _ = vq(np.array(all_sizes), centroids)
little_sizes = tz.first(tz.partitionby(lambda xs: xs[0], zip(idx, all_sizes)))
little_sizes = [x[1] for x in little_sizes]
# create one more cluster with the smaller, removing the haplotypes
centroids2, _ = kmeans(np.array(little_sizes), 2)
idx2, _ = vq(np.array(little_sizes), centroids2)
little_sizes2 = tz.first(tz.partitionby(lambda xs: xs[0], zip(idx2, little_sizes)))
little_sizes2 = [x[1] for x in little_sizes2]
# get any chromosomes not in haplotype/random bin
thresh = max(little_sizes2)
else:
thresh = 0
larger_chroms = []
for c in ref.file_contigs(ref_file):
if c.size > thresh:
larger_chroms.append(c.name)
return larger_chroms | python | def _get_larger_chroms(ref_file):
from scipy.cluster.vq import kmeans, vq
all_sizes = []
for c in ref.file_contigs(ref_file):
all_sizes.append(float(c.size))
all_sizes.sort()
if len(all_sizes) > 5:
# separate out smaller chromosomes and haplotypes with kmeans
centroids, _ = kmeans(np.array(all_sizes), 2)
idx, _ = vq(np.array(all_sizes), centroids)
little_sizes = tz.first(tz.partitionby(lambda xs: xs[0], zip(idx, all_sizes)))
little_sizes = [x[1] for x in little_sizes]
# create one more cluster with the smaller, removing the haplotypes
centroids2, _ = kmeans(np.array(little_sizes), 2)
idx2, _ = vq(np.array(little_sizes), centroids2)
little_sizes2 = tz.first(tz.partitionby(lambda xs: xs[0], zip(idx2, little_sizes)))
little_sizes2 = [x[1] for x in little_sizes2]
# get any chromosomes not in haplotype/random bin
thresh = max(little_sizes2)
else:
thresh = 0
larger_chroms = []
for c in ref.file_contigs(ref_file):
if c.size > thresh:
larger_chroms.append(c.name)
return larger_chroms | [
"def",
"_get_larger_chroms",
"(",
"ref_file",
")",
":",
"from",
"scipy",
".",
"cluster",
".",
"vq",
"import",
"kmeans",
",",
"vq",
"all_sizes",
"=",
"[",
"]",
"for",
"c",
"in",
"ref",
".",
"file_contigs",
"(",
"ref_file",
")",
":",
"all_sizes",
".",
"a... | Retrieve larger chromosomes, avoiding the smaller ones for plotting. | [
"Retrieve",
"larger",
"chromosomes",
"avoiding",
"the",
"smaller",
"ones",
"for",
"plotting",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/cnvkit.py#L648-L675 |
237,103 | bcbio/bcbio-nextgen | bcbio/structural/cnvkit.py | segment_from_cnr | def segment_from_cnr(cnr_file, data, out_base):
"""Provide segmentation on a cnr file, used in external PureCN integration.
"""
cns_file = _cnvkit_segment(cnr_file, dd.get_coverage_interval(data),
data, [data], out_file="%s.cns" % out_base, detailed=True)
out = _add_seg_to_output({"cns": cns_file}, data, enumerate_chroms=False)
return out["seg"] | python | def segment_from_cnr(cnr_file, data, out_base):
cns_file = _cnvkit_segment(cnr_file, dd.get_coverage_interval(data),
data, [data], out_file="%s.cns" % out_base, detailed=True)
out = _add_seg_to_output({"cns": cns_file}, data, enumerate_chroms=False)
return out["seg"] | [
"def",
"segment_from_cnr",
"(",
"cnr_file",
",",
"data",
",",
"out_base",
")",
":",
"cns_file",
"=",
"_cnvkit_segment",
"(",
"cnr_file",
",",
"dd",
".",
"get_coverage_interval",
"(",
"data",
")",
",",
"data",
",",
"[",
"data",
"]",
",",
"out_file",
"=",
... | Provide segmentation on a cnr file, used in external PureCN integration. | [
"Provide",
"segmentation",
"on",
"a",
"cnr",
"file",
"used",
"in",
"external",
"PureCN",
"integration",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/cnvkit.py#L747-L753 |
237,104 | bcbio/bcbio-nextgen | bcbio/structural/cnvkit.py | export_theta | def export_theta(ckout, data):
"""Provide updated set of data with export information for TheTA2 input.
"""
cns_file = chromhacks.bed_to_standardonly(ckout["cns"], data, headers="chromosome")
cnr_file = chromhacks.bed_to_standardonly(ckout["cnr"], data, headers="chromosome")
out_file = "%s-theta.input" % utils.splitext_plus(cns_file)[0]
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = [_get_cmd(), "export", "theta", cns_file, cnr_file, "-o", tx_out_file]
do.run(_prep_cmd(cmd, tx_out_file), "Export CNVkit calls as inputs for TheTA2")
ckout["theta_input"] = out_file
return ckout | python | def export_theta(ckout, data):
cns_file = chromhacks.bed_to_standardonly(ckout["cns"], data, headers="chromosome")
cnr_file = chromhacks.bed_to_standardonly(ckout["cnr"], data, headers="chromosome")
out_file = "%s-theta.input" % utils.splitext_plus(cns_file)[0]
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = [_get_cmd(), "export", "theta", cns_file, cnr_file, "-o", tx_out_file]
do.run(_prep_cmd(cmd, tx_out_file), "Export CNVkit calls as inputs for TheTA2")
ckout["theta_input"] = out_file
return ckout | [
"def",
"export_theta",
"(",
"ckout",
",",
"data",
")",
":",
"cns_file",
"=",
"chromhacks",
".",
"bed_to_standardonly",
"(",
"ckout",
"[",
"\"cns\"",
"]",
",",
"data",
",",
"headers",
"=",
"\"chromosome\"",
")",
"cnr_file",
"=",
"chromhacks",
".",
"bed_to_sta... | Provide updated set of data with export information for TheTA2 input. | [
"Provide",
"updated",
"set",
"of",
"data",
"with",
"export",
"information",
"for",
"TheTA2",
"input",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/cnvkit.py#L757-L768 |
237,105 | bcbio/bcbio-nextgen | bcbio/rnaseq/stringtie.py | _stringtie_expression | def _stringtie_expression(bam, data, out_dir="."):
"""
only estimate expression the Stringtie, do not assemble new transcripts
"""
gtf_file = dd.get_gtf_file(data)
num_cores = dd.get_num_cores(data)
error_message = "The %s file for %s is missing. StringTie has an error."
stringtie = config_utils.get_program("stringtie", data, default="stringtie")
# don't assemble transcripts unless asked
exp_flag = ("-e" if "stringtie" not in dd.get_transcript_assembler(data)
else "")
base_cmd = ("{stringtie} {exp_flag} -b {out_dir} -p {num_cores} -G {gtf_file} "
"-o {out_gtf} {bam}")
transcript_file = os.path.join(out_dir, "t_data.ctab")
exon_file = os.path.join(out_dir, "e_data.ctab")
out_gtf = os.path.join(out_dir, "stringtie-assembly.gtf")
if file_exists(transcript_file):
return exon_file, transcript_file, out_gtf
cmd = base_cmd.format(**locals())
do.run(cmd, "Running Stringtie on %s." % bam)
assert file_exists(exon_file), error_message % ("exon", exon_file)
assert file_exists(transcript_file), error_message % ("transcript", transcript_file)
return transcript_file | python | def _stringtie_expression(bam, data, out_dir="."):
gtf_file = dd.get_gtf_file(data)
num_cores = dd.get_num_cores(data)
error_message = "The %s file for %s is missing. StringTie has an error."
stringtie = config_utils.get_program("stringtie", data, default="stringtie")
# don't assemble transcripts unless asked
exp_flag = ("-e" if "stringtie" not in dd.get_transcript_assembler(data)
else "")
base_cmd = ("{stringtie} {exp_flag} -b {out_dir} -p {num_cores} -G {gtf_file} "
"-o {out_gtf} {bam}")
transcript_file = os.path.join(out_dir, "t_data.ctab")
exon_file = os.path.join(out_dir, "e_data.ctab")
out_gtf = os.path.join(out_dir, "stringtie-assembly.gtf")
if file_exists(transcript_file):
return exon_file, transcript_file, out_gtf
cmd = base_cmd.format(**locals())
do.run(cmd, "Running Stringtie on %s." % bam)
assert file_exists(exon_file), error_message % ("exon", exon_file)
assert file_exists(transcript_file), error_message % ("transcript", transcript_file)
return transcript_file | [
"def",
"_stringtie_expression",
"(",
"bam",
",",
"data",
",",
"out_dir",
"=",
"\".\"",
")",
":",
"gtf_file",
"=",
"dd",
".",
"get_gtf_file",
"(",
"data",
")",
"num_cores",
"=",
"dd",
".",
"get_num_cores",
"(",
"data",
")",
"error_message",
"=",
"\"The %s f... | only estimate expression the Stringtie, do not assemble new transcripts | [
"only",
"estimate",
"expression",
"the",
"Stringtie",
"do",
"not",
"assemble",
"new",
"transcripts"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/stringtie.py#L21-L43 |
237,106 | bcbio/bcbio-nextgen | bcbio/rnaseq/stringtie.py | run_stringtie_expression | def run_stringtie_expression(data):
"""
estimate expression from Stringtie, using the bcbio datadict
does not do transcriptome assembly
"""
bam = dd.get_work_bam(data)
sample_name = dd.get_sample_name(data)
out_dir = os.path.join("stringtie", sample_name)
isoform_fpkm = os.path.join(out_dir, sample_name + ".isoform.fpkm")
gene_fpkm = os.path.join(out_dir, sample_name + ".fpkm")
assembly = os.path.abspath(os.path.join(out_dir, "stringtie-assembly.gtf"))
if file_exists(isoform_fpkm) and file_exists(gene_fpkm):
data = dd.set_stringtie_dir(data, out_dir)
data = dd.set_fpkm(data, gene_fpkm)
data = dd.set_fpkm_isoform(data, isoform_fpkm)
if "stringtie" in dd.get_transcript_assembler(data):
assembled_gtfs = dd.get_assembled_gtf(data)
assembled_gtfs.append(assembly)
data = dd.set_assembled_gtf(data, assembled_gtfs)
return data
with file_transaction(data, out_dir) as tx_out_dir:
transcript_file = _stringtie_expression(bam, data, tx_out_dir)
df = _parse_ballgown(transcript_file)
_write_fpkms(df, tx_out_dir, sample_name)
data = dd.set_stringtie_dir(data, out_dir)
data = dd.set_fpkm(data, gene_fpkm)
data = dd.set_fpkm_isoform(data, isoform_fpkm)
if "stringtie" in dd.get_transcript_assembler(data):
assembled_gtfs = dd.get_assembled_gtf(data)
assembled_gtfs.append(assembly)
data = dd.set_assembled_gtf(data, assembled_gtfs)
return data | python | def run_stringtie_expression(data):
bam = dd.get_work_bam(data)
sample_name = dd.get_sample_name(data)
out_dir = os.path.join("stringtie", sample_name)
isoform_fpkm = os.path.join(out_dir, sample_name + ".isoform.fpkm")
gene_fpkm = os.path.join(out_dir, sample_name + ".fpkm")
assembly = os.path.abspath(os.path.join(out_dir, "stringtie-assembly.gtf"))
if file_exists(isoform_fpkm) and file_exists(gene_fpkm):
data = dd.set_stringtie_dir(data, out_dir)
data = dd.set_fpkm(data, gene_fpkm)
data = dd.set_fpkm_isoform(data, isoform_fpkm)
if "stringtie" in dd.get_transcript_assembler(data):
assembled_gtfs = dd.get_assembled_gtf(data)
assembled_gtfs.append(assembly)
data = dd.set_assembled_gtf(data, assembled_gtfs)
return data
with file_transaction(data, out_dir) as tx_out_dir:
transcript_file = _stringtie_expression(bam, data, tx_out_dir)
df = _parse_ballgown(transcript_file)
_write_fpkms(df, tx_out_dir, sample_name)
data = dd.set_stringtie_dir(data, out_dir)
data = dd.set_fpkm(data, gene_fpkm)
data = dd.set_fpkm_isoform(data, isoform_fpkm)
if "stringtie" in dd.get_transcript_assembler(data):
assembled_gtfs = dd.get_assembled_gtf(data)
assembled_gtfs.append(assembly)
data = dd.set_assembled_gtf(data, assembled_gtfs)
return data | [
"def",
"run_stringtie_expression",
"(",
"data",
")",
":",
"bam",
"=",
"dd",
".",
"get_work_bam",
"(",
"data",
")",
"sample_name",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"out_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"stringtie\"",
"... | estimate expression from Stringtie, using the bcbio datadict
does not do transcriptome assembly | [
"estimate",
"expression",
"from",
"Stringtie",
"using",
"the",
"bcbio",
"datadict",
"does",
"not",
"do",
"transcriptome",
"assembly"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/stringtie.py#L45-L76 |
237,107 | bcbio/bcbio-nextgen | bcbio/upload/filesystem.py | update_file | def update_file(finfo, sample_info, config, pass_uptodate=False):
"""Update the file in local filesystem storage.
"""
storage_dir = utils.safe_makedir(_get_storage_dir(finfo, config))
if finfo.get("type") == "directory":
return _copy_finfo_directory(finfo, storage_dir)
else:
return _copy_finfo(finfo, storage_dir, pass_uptodate=pass_uptodate) | python | def update_file(finfo, sample_info, config, pass_uptodate=False):
storage_dir = utils.safe_makedir(_get_storage_dir(finfo, config))
if finfo.get("type") == "directory":
return _copy_finfo_directory(finfo, storage_dir)
else:
return _copy_finfo(finfo, storage_dir, pass_uptodate=pass_uptodate) | [
"def",
"update_file",
"(",
"finfo",
",",
"sample_info",
",",
"config",
",",
"pass_uptodate",
"=",
"False",
")",
":",
"storage_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"_get_storage_dir",
"(",
"finfo",
",",
"config",
")",
")",
"if",
"finfo",
".",
"get"... | Update the file in local filesystem storage. | [
"Update",
"the",
"file",
"in",
"local",
"filesystem",
"storage",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/filesystem.py#L10-L17 |
237,108 | bcbio/bcbio-nextgen | bcbio/upload/filesystem.py | _copy_finfo | def _copy_finfo(finfo, storage_dir, pass_uptodate=False):
"""Copy a file into the output storage directory.
"""
out_file = _get_file_upload_path(finfo, storage_dir)
if not shared.up_to_date(out_file, finfo):
logger.info("Storing in local filesystem: %s" % out_file)
shutil.copy(finfo["path"], out_file)
return out_file
if pass_uptodate:
return out_file | python | def _copy_finfo(finfo, storage_dir, pass_uptodate=False):
out_file = _get_file_upload_path(finfo, storage_dir)
if not shared.up_to_date(out_file, finfo):
logger.info("Storing in local filesystem: %s" % out_file)
shutil.copy(finfo["path"], out_file)
return out_file
if pass_uptodate:
return out_file | [
"def",
"_copy_finfo",
"(",
"finfo",
",",
"storage_dir",
",",
"pass_uptodate",
"=",
"False",
")",
":",
"out_file",
"=",
"_get_file_upload_path",
"(",
"finfo",
",",
"storage_dir",
")",
"if",
"not",
"shared",
".",
"up_to_date",
"(",
"out_file",
",",
"finfo",
")... | Copy a file into the output storage directory. | [
"Copy",
"a",
"file",
"into",
"the",
"output",
"storage",
"directory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/filesystem.py#L63-L72 |
237,109 | bcbio/bcbio-nextgen | bcbio/upload/filesystem.py | _copy_finfo_directory | def _copy_finfo_directory(finfo, out_dir):
"""Copy a directory into the final output directory.
"""
out_dir = _get_dir_upload_path(finfo, out_dir)
if not shared.up_to_date(out_dir, finfo):
logger.info("Storing directory in local filesystem: %s" % out_dir)
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
shutil.copytree(finfo["path"], out_dir)
for tmpdir in ["tx", "tmp"]:
if os.path.exists(os.path.join(out_dir, tmpdir)):
shutil.rmtree(os.path.join(out_dir, tmpdir))
os.utime(out_dir, None)
return out_dir | python | def _copy_finfo_directory(finfo, out_dir):
out_dir = _get_dir_upload_path(finfo, out_dir)
if not shared.up_to_date(out_dir, finfo):
logger.info("Storing directory in local filesystem: %s" % out_dir)
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
shutil.copytree(finfo["path"], out_dir)
for tmpdir in ["tx", "tmp"]:
if os.path.exists(os.path.join(out_dir, tmpdir)):
shutil.rmtree(os.path.join(out_dir, tmpdir))
os.utime(out_dir, None)
return out_dir | [
"def",
"_copy_finfo_directory",
"(",
"finfo",
",",
"out_dir",
")",
":",
"out_dir",
"=",
"_get_dir_upload_path",
"(",
"finfo",
",",
"out_dir",
")",
"if",
"not",
"shared",
".",
"up_to_date",
"(",
"out_dir",
",",
"finfo",
")",
":",
"logger",
".",
"info",
"(",... | Copy a directory into the final output directory. | [
"Copy",
"a",
"directory",
"into",
"the",
"final",
"output",
"directory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/filesystem.py#L74-L87 |
237,110 | bcbio/bcbio-nextgen | bcbio/variation/naming.py | handle_synonyms | def handle_synonyms(in_file, ref_file, genome_build, work_dir, data):
"""Potentially handle remapping synonymous chromosome names between builds.
Handles tab delimited file formats like BED and VCF where the contig
is in the first column.
"""
if genome_build in GMAP and ref_file:
mappings = GMAP[genome_build]
contigs = set([c.name for c in ref.file_contigs(ref_file)])
out_file = os.path.join(work_dir, "%s-fixed_contigs%s" % utils.splitext_plus(os.path.basename(in_file)))
if not utils.file_exists(out_file):
if out_file.endswith(".gz"):
out_file = out_file.replace(".gz", "")
needs_bgzip = True
else:
needs_bgzip = False
checked_file = "%s.checked" % utils.splitext_plus(out_file)[0]
if not _matches_contigs(in_file, contigs, checked_file):
with file_transaction(data, out_file) as tx_out_file:
_write_newname_file(in_file, tx_out_file, mappings)
if needs_bgzip:
out_file = vcfutils.bgzip_and_index(out_file, data["config"])
return out_file
return in_file | python | def handle_synonyms(in_file, ref_file, genome_build, work_dir, data):
if genome_build in GMAP and ref_file:
mappings = GMAP[genome_build]
contigs = set([c.name for c in ref.file_contigs(ref_file)])
out_file = os.path.join(work_dir, "%s-fixed_contigs%s" % utils.splitext_plus(os.path.basename(in_file)))
if not utils.file_exists(out_file):
if out_file.endswith(".gz"):
out_file = out_file.replace(".gz", "")
needs_bgzip = True
else:
needs_bgzip = False
checked_file = "%s.checked" % utils.splitext_plus(out_file)[0]
if not _matches_contigs(in_file, contigs, checked_file):
with file_transaction(data, out_file) as tx_out_file:
_write_newname_file(in_file, tx_out_file, mappings)
if needs_bgzip:
out_file = vcfutils.bgzip_and_index(out_file, data["config"])
return out_file
return in_file | [
"def",
"handle_synonyms",
"(",
"in_file",
",",
"ref_file",
",",
"genome_build",
",",
"work_dir",
",",
"data",
")",
":",
"if",
"genome_build",
"in",
"GMAP",
"and",
"ref_file",
":",
"mappings",
"=",
"GMAP",
"[",
"genome_build",
"]",
"contigs",
"=",
"set",
"(... | Potentially handle remapping synonymous chromosome names between builds.
Handles tab delimited file formats like BED and VCF where the contig
is in the first column. | [
"Potentially",
"handle",
"remapping",
"synonymous",
"chromosome",
"names",
"between",
"builds",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/naming.py#L101-L124 |
237,111 | bcbio/bcbio-nextgen | bcbio/variation/naming.py | _write_newname_file | def _write_newname_file(in_file, out_file, mappings):
"""Re-write an input file with contigs matching the correct reference.
"""
with utils.open_gzipsafe(in_file) as in_handle:
with open(out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("#"):
out_handle.write(line)
else:
parts = line.split("\t")
new_contig = mappings.get(parts[0])
if new_contig:
parts[0] = new_contig
out_handle.write("\t".join(parts)) | python | def _write_newname_file(in_file, out_file, mappings):
with utils.open_gzipsafe(in_file) as in_handle:
with open(out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("#"):
out_handle.write(line)
else:
parts = line.split("\t")
new_contig = mappings.get(parts[0])
if new_contig:
parts[0] = new_contig
out_handle.write("\t".join(parts)) | [
"def",
"_write_newname_file",
"(",
"in_file",
",",
"out_file",
",",
"mappings",
")",
":",
"with",
"utils",
".",
"open_gzipsafe",
"(",
"in_file",
")",
"as",
"in_handle",
":",
"with",
"open",
"(",
"out_file",
",",
"\"w\"",
")",
"as",
"out_handle",
":",
"for"... | Re-write an input file with contigs matching the correct reference. | [
"Re",
"-",
"write",
"an",
"input",
"file",
"with",
"contigs",
"matching",
"the",
"correct",
"reference",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/naming.py#L126-L139 |
237,112 | bcbio/bcbio-nextgen | bcbio/variation/naming.py | _matches_contigs | def _matches_contigs(in_file, contigs, checked_file):
"""Check if the contigs in the input file match the defined contigs in the reference genome.
"""
tocheck_contigs = 2
if utils.file_exists(checked_file):
with open(checked_file) as in_handle:
return in_handle.read().strip() == "match"
else:
with utils.open_gzipsafe(in_file) as in_handle:
to_check = set([])
for line in in_handle:
if not line.startswith("#"):
to_check.add(line.split()[0])
if len(to_check) >= tocheck_contigs:
break
with open(checked_file, "w") as out_handle:
if any([c not in contigs for c in to_check]):
out_handle.write("different")
return False
else:
out_handle.write("match")
return True | python | def _matches_contigs(in_file, contigs, checked_file):
tocheck_contigs = 2
if utils.file_exists(checked_file):
with open(checked_file) as in_handle:
return in_handle.read().strip() == "match"
else:
with utils.open_gzipsafe(in_file) as in_handle:
to_check = set([])
for line in in_handle:
if not line.startswith("#"):
to_check.add(line.split()[0])
if len(to_check) >= tocheck_contigs:
break
with open(checked_file, "w") as out_handle:
if any([c not in contigs for c in to_check]):
out_handle.write("different")
return False
else:
out_handle.write("match")
return True | [
"def",
"_matches_contigs",
"(",
"in_file",
",",
"contigs",
",",
"checked_file",
")",
":",
"tocheck_contigs",
"=",
"2",
"if",
"utils",
".",
"file_exists",
"(",
"checked_file",
")",
":",
"with",
"open",
"(",
"checked_file",
")",
"as",
"in_handle",
":",
"return... | Check if the contigs in the input file match the defined contigs in the reference genome. | [
"Check",
"if",
"the",
"contigs",
"in",
"the",
"input",
"file",
"match",
"the",
"defined",
"contigs",
"in",
"the",
"reference",
"genome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/naming.py#L141-L162 |
237,113 | bcbio/bcbio-nextgen | bcbio/ngsalign/novoalign.py | align_bam | def align_bam(in_bam, ref_file, names, align_dir, data):
"""Perform realignment of input BAM file; uses unix pipes for avoid IO.
"""
config = data["config"]
out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"]))
novoalign = config_utils.get_program("novoalign", config)
samtools = config_utils.get_program("samtools", config)
resources = config_utils.get_resources("novoalign", config)
num_cores = config["algorithm"].get("num_cores", 1)
max_mem = resources.get("memory", "4G").upper()
extra_novo_args = " ".join(_novoalign_args_from_config(config, False))
if not file_exists(out_file):
with tx_tmpdir(data, base_dir=align_dir) as work_dir:
with postalign.tobam_cl(data, out_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file):
rg_info = get_rg_info(names)
tx_out_prefix = os.path.splitext(tx_out_file)[0]
prefix1 = "%s-in1" % tx_out_prefix
cmd = ("unset JAVA_HOME && "
"{samtools} sort -n -o -l 1 -@ {num_cores} -m {max_mem} {in_bam} {prefix1} "
"| {novoalign} -o SAM '{rg_info}' -d {ref_file} -f /dev/stdin "
" -F BAMPE -c {num_cores} {extra_novo_args} | ")
cmd = (cmd + tobam_cl).format(**locals())
do.run(cmd, "Novoalign: %s" % names["sample"], None,
[do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)])
return out_file | python | def align_bam(in_bam, ref_file, names, align_dir, data):
config = data["config"]
out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"]))
novoalign = config_utils.get_program("novoalign", config)
samtools = config_utils.get_program("samtools", config)
resources = config_utils.get_resources("novoalign", config)
num_cores = config["algorithm"].get("num_cores", 1)
max_mem = resources.get("memory", "4G").upper()
extra_novo_args = " ".join(_novoalign_args_from_config(config, False))
if not file_exists(out_file):
with tx_tmpdir(data, base_dir=align_dir) as work_dir:
with postalign.tobam_cl(data, out_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file):
rg_info = get_rg_info(names)
tx_out_prefix = os.path.splitext(tx_out_file)[0]
prefix1 = "%s-in1" % tx_out_prefix
cmd = ("unset JAVA_HOME && "
"{samtools} sort -n -o -l 1 -@ {num_cores} -m {max_mem} {in_bam} {prefix1} "
"| {novoalign} -o SAM '{rg_info}' -d {ref_file} -f /dev/stdin "
" -F BAMPE -c {num_cores} {extra_novo_args} | ")
cmd = (cmd + tobam_cl).format(**locals())
do.run(cmd, "Novoalign: %s" % names["sample"], None,
[do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)])
return out_file | [
"def",
"align_bam",
"(",
"in_bam",
",",
"ref_file",
",",
"names",
",",
"align_dir",
",",
"data",
")",
":",
"config",
"=",
"data",
"[",
"\"config\"",
"]",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"align_dir",
",",
"\"{0}-sort.bam\"",
".",
"... | Perform realignment of input BAM file; uses unix pipes for avoid IO. | [
"Perform",
"realignment",
"of",
"input",
"BAM",
"file",
";",
"uses",
"unix",
"pipes",
"for",
"avoid",
"IO",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/novoalign.py#L29-L54 |
237,114 | bcbio/bcbio-nextgen | bcbio/ngsalign/novoalign.py | _novoalign_args_from_config | def _novoalign_args_from_config(config, need_quality=True):
"""Select novoalign options based on configuration parameters.
"""
if need_quality:
qual_format = config["algorithm"].get("quality_format", "").lower()
qual_flags = ["-F", "ILMFQ" if qual_format == "illumina" else "STDFQ"]
else:
qual_flags = []
multi_mappers = config["algorithm"].get("multiple_mappers")
if multi_mappers is True:
multi_flag = "Random"
elif isinstance(multi_mappers, six.string_types):
multi_flag = multi_mappers
else:
multi_flag = "None"
multi_flags = ["-r"] + multi_flag.split()
resources = config_utils.get_resources("novoalign", config)
# default arguments for improved variant calling based on
# comparisons to reference materials: turn off soft clipping and recalibrate
if resources.get("options") is None:
extra_args = ["-o", "FullNW", "-k"]
else:
extra_args = [str(x) for x in resources.get("options", [])]
return qual_flags + multi_flags + extra_args | python | def _novoalign_args_from_config(config, need_quality=True):
if need_quality:
qual_format = config["algorithm"].get("quality_format", "").lower()
qual_flags = ["-F", "ILMFQ" if qual_format == "illumina" else "STDFQ"]
else:
qual_flags = []
multi_mappers = config["algorithm"].get("multiple_mappers")
if multi_mappers is True:
multi_flag = "Random"
elif isinstance(multi_mappers, six.string_types):
multi_flag = multi_mappers
else:
multi_flag = "None"
multi_flags = ["-r"] + multi_flag.split()
resources = config_utils.get_resources("novoalign", config)
# default arguments for improved variant calling based on
# comparisons to reference materials: turn off soft clipping and recalibrate
if resources.get("options") is None:
extra_args = ["-o", "FullNW", "-k"]
else:
extra_args = [str(x) for x in resources.get("options", [])]
return qual_flags + multi_flags + extra_args | [
"def",
"_novoalign_args_from_config",
"(",
"config",
",",
"need_quality",
"=",
"True",
")",
":",
"if",
"need_quality",
":",
"qual_format",
"=",
"config",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\"quality_format\"",
",",
"\"\"",
")",
".",
"lower",
"(",
"... | Select novoalign options based on configuration parameters. | [
"Select",
"novoalign",
"options",
"based",
"on",
"configuration",
"parameters",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/novoalign.py#L92-L115 |
237,115 | bcbio/bcbio-nextgen | bcbio/ngsalign/novoalign.py | remap_index_fn | def remap_index_fn(ref_file):
"""Map sequence references to equivalent novoalign indexes.
"""
checks = [os.path.splitext(ref_file)[0].replace("/seq/", "/novoalign/"),
os.path.splitext(ref_file)[0] + ".ndx",
ref_file + ".bs.ndx",
ref_file + ".ndx"]
for check in checks:
if os.path.exists(check):
return check
return checks[0] | python | def remap_index_fn(ref_file):
checks = [os.path.splitext(ref_file)[0].replace("/seq/", "/novoalign/"),
os.path.splitext(ref_file)[0] + ".ndx",
ref_file + ".bs.ndx",
ref_file + ".ndx"]
for check in checks:
if os.path.exists(check):
return check
return checks[0] | [
"def",
"remap_index_fn",
"(",
"ref_file",
")",
":",
"checks",
"=",
"[",
"os",
".",
"path",
".",
"splitext",
"(",
"ref_file",
")",
"[",
"0",
"]",
".",
"replace",
"(",
"\"/seq/\"",
",",
"\"/novoalign/\"",
")",
",",
"os",
".",
"path",
".",
"splitext",
"... | Map sequence references to equivalent novoalign indexes. | [
"Map",
"sequence",
"references",
"to",
"equivalent",
"novoalign",
"indexes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/novoalign.py#L138-L148 |
237,116 | bcbio/bcbio-nextgen | bcbio/variation/sentieon.py | license_export | def license_export(data):
"""Retrieve export statement for sentieon license server.
"""
resources = config_utils.get_resources("sentieon", data["config"])
server = resources.get("keyfile")
if not server:
server = tz.get_in(["resources", "sentieon", "keyfile"], data)
if not server:
raise ValueError("Need to set resources keyfile with URL:port of license server, local license file or "
"environmental variables to export \n"
"http://bcbio-nextgen.readthedocs.io/en/latest/contents/configuration.html#resources\n"
"Configuration: %s" % pprint.pformat(data))
if isinstance(server, six.string_types):
return "export SENTIEON_LICENSE=%s && " % server
else:
assert isinstance(server, dict), server
exports = ""
for key, val in server.items():
exports += "export %s=%s && " % (key.upper(), val)
return exports | python | def license_export(data):
resources = config_utils.get_resources("sentieon", data["config"])
server = resources.get("keyfile")
if not server:
server = tz.get_in(["resources", "sentieon", "keyfile"], data)
if not server:
raise ValueError("Need to set resources keyfile with URL:port of license server, local license file or "
"environmental variables to export \n"
"http://bcbio-nextgen.readthedocs.io/en/latest/contents/configuration.html#resources\n"
"Configuration: %s" % pprint.pformat(data))
if isinstance(server, six.string_types):
return "export SENTIEON_LICENSE=%s && " % server
else:
assert isinstance(server, dict), server
exports = ""
for key, val in server.items():
exports += "export %s=%s && " % (key.upper(), val)
return exports | [
"def",
"license_export",
"(",
"data",
")",
":",
"resources",
"=",
"config_utils",
".",
"get_resources",
"(",
"\"sentieon\"",
",",
"data",
"[",
"\"config\"",
"]",
")",
"server",
"=",
"resources",
".",
"get",
"(",
"\"keyfile\"",
")",
"if",
"not",
"server",
"... | Retrieve export statement for sentieon license server. | [
"Retrieve",
"export",
"statement",
"for",
"sentieon",
"license",
"server",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/sentieon.py#L25-L44 |
237,117 | bcbio/bcbio-nextgen | bcbio/variation/sentieon.py | _get_interval | def _get_interval(variant_regions, region, out_file, items):
"""Retrieve interval to run analysis in. Handles no targets, BED and regions
region can be a single region or list of multiple regions for multicore calling.
"""
target = shared.subset_variant_regions(variant_regions, region, out_file, items)
if target:
if isinstance(target, six.string_types) and os.path.isfile(target):
return "--interval %s" % target
else:
return "--interval %s" % bamprep.region_to_gatk(target)
else:
return "" | python | def _get_interval(variant_regions, region, out_file, items):
target = shared.subset_variant_regions(variant_regions, region, out_file, items)
if target:
if isinstance(target, six.string_types) and os.path.isfile(target):
return "--interval %s" % target
else:
return "--interval %s" % bamprep.region_to_gatk(target)
else:
return "" | [
"def",
"_get_interval",
"(",
"variant_regions",
",",
"region",
",",
"out_file",
",",
"items",
")",
":",
"target",
"=",
"shared",
".",
"subset_variant_regions",
"(",
"variant_regions",
",",
"region",
",",
"out_file",
",",
"items",
")",
"if",
"target",
":",
"i... | Retrieve interval to run analysis in. Handles no targets, BED and regions
region can be a single region or list of multiple regions for multicore calling. | [
"Retrieve",
"interval",
"to",
"run",
"analysis",
"in",
".",
"Handles",
"no",
"targets",
"BED",
"and",
"regions"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/sentieon.py#L46-L58 |
237,118 | bcbio/bcbio-nextgen | bcbio/variation/sentieon.py | run_tnscope | def run_tnscope(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Call variants with Sentieon's TNscope somatic caller.
"""
if out_file is None:
out_file = "%s-variants.vcf.gz" % utils.splitext_plus(align_bams[0])[0]
if not utils.file_exists(out_file):
variant_regions = bedutils.population_variant_regions(items, merged=True)
interval = _get_interval(variant_regions, region, out_file, items)
with file_transaction(items[0], out_file) as tx_out_file:
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and paired.normal_bam, "Require normal BAM for Sentieon TNscope"
dbsnp = "--dbsnp %s" % (assoc_files.get("dbsnp")) if "dbsnp" in assoc_files else ""
license = license_export(items[0])
cores = dd.get_num_cores(items[0])
cmd = ("{license}sentieon driver -t {cores} -r {ref_file} "
"-i {paired.tumor_bam} -i {paired.normal_bam} {interval} "
"--algo TNscope "
"--tumor_sample {paired.tumor_name} --normal_sample {paired.normal_name} "
"{dbsnp} {tx_out_file}")
do.run(cmd.format(**locals()), "Sentieon TNscope")
return out_file | python | def run_tnscope(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
if out_file is None:
out_file = "%s-variants.vcf.gz" % utils.splitext_plus(align_bams[0])[0]
if not utils.file_exists(out_file):
variant_regions = bedutils.population_variant_regions(items, merged=True)
interval = _get_interval(variant_regions, region, out_file, items)
with file_transaction(items[0], out_file) as tx_out_file:
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and paired.normal_bam, "Require normal BAM for Sentieon TNscope"
dbsnp = "--dbsnp %s" % (assoc_files.get("dbsnp")) if "dbsnp" in assoc_files else ""
license = license_export(items[0])
cores = dd.get_num_cores(items[0])
cmd = ("{license}sentieon driver -t {cores} -r {ref_file} "
"-i {paired.tumor_bam} -i {paired.normal_bam} {interval} "
"--algo TNscope "
"--tumor_sample {paired.tumor_name} --normal_sample {paired.normal_name} "
"{dbsnp} {tx_out_file}")
do.run(cmd.format(**locals()), "Sentieon TNscope")
return out_file | [
"def",
"run_tnscope",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"if",
"out_file",
"is",
"None",
":",
"out_file",
"=",
"\"%s-variants.vcf.gz\"",
"%",
"utils",
".... | Call variants with Sentieon's TNscope somatic caller. | [
"Call",
"variants",
"with",
"Sentieon",
"s",
"TNscope",
"somatic",
"caller",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/sentieon.py#L60-L81 |
237,119 | bcbio/bcbio-nextgen | bcbio/variation/sentieon.py | run_gvcftyper | def run_gvcftyper(vrn_files, out_file, region, data):
"""Produce joint called variants from input gVCF files.
"""
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
license = license_export(data)
ref_file = dd.get_ref_file(data)
input_files = " ".join(vrn_files)
region = bamprep.region_to_gatk(region)
cmd = ("{license}sentieon driver -r {ref_file} --interval {region} "
"--algo GVCFtyper {tx_out_file} {input_files}")
do.run(cmd.format(**locals()), "Sentieon GVCFtyper")
return out_file | python | def run_gvcftyper(vrn_files, out_file, region, data):
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
license = license_export(data)
ref_file = dd.get_ref_file(data)
input_files = " ".join(vrn_files)
region = bamprep.region_to_gatk(region)
cmd = ("{license}sentieon driver -r {ref_file} --interval {region} "
"--algo GVCFtyper {tx_out_file} {input_files}")
do.run(cmd.format(**locals()), "Sentieon GVCFtyper")
return out_file | [
"def",
"run_gvcftyper",
"(",
"vrn_files",
",",
"out_file",
",",
"region",
",",
"data",
")",
":",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
... | Produce joint called variants from input gVCF files. | [
"Produce",
"joint",
"called",
"variants",
"from",
"input",
"gVCF",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/sentieon.py#L137-L149 |
237,120 | bcbio/bcbio-nextgen | bcbio/variation/sentieon.py | bqsr_table | def bqsr_table(data):
"""Generate recalibration tables as inputs to BQSR.
"""
in_file = dd.get_align_bam(data)
out_file = "%s-recal-table.txt" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
assoc_files = dd.get_variation_resources(data)
known = "-k %s" % (assoc_files.get("dbsnp")) if "dbsnp" in assoc_files else ""
license = license_export(data)
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
cmd = ("{license}sentieon driver -t {cores} -r {ref_file} "
"-i {in_file} --algo QualCal {known} {tx_out_file}")
do.run(cmd.format(**locals()), "Sentieon QualCal generate table")
return out_file | python | def bqsr_table(data):
in_file = dd.get_align_bam(data)
out_file = "%s-recal-table.txt" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
assoc_files = dd.get_variation_resources(data)
known = "-k %s" % (assoc_files.get("dbsnp")) if "dbsnp" in assoc_files else ""
license = license_export(data)
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
cmd = ("{license}sentieon driver -t {cores} -r {ref_file} "
"-i {in_file} --algo QualCal {known} {tx_out_file}")
do.run(cmd.format(**locals()), "Sentieon QualCal generate table")
return out_file | [
"def",
"bqsr_table",
"(",
"data",
")",
":",
"in_file",
"=",
"dd",
".",
"get_align_bam",
"(",
"data",
")",
"out_file",
"=",
"\"%s-recal-table.txt\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
".",
"file_... | Generate recalibration tables as inputs to BQSR. | [
"Generate",
"recalibration",
"tables",
"as",
"inputs",
"to",
"BQSR",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/sentieon.py#L151-L166 |
237,121 | bcbio/bcbio-nextgen | bcbio/ngsalign/rtg.py | to_sdf | def to_sdf(files, data):
"""Convert a fastq or BAM input into a SDF indexed file.
"""
# BAM
if len(files) == 1 and files[0].endswith(".bam"):
qual = []
format = ["-f", "sam-pe" if bam.is_paired(files[0]) else "sam-se"]
inputs = [files[0]]
# fastq
else:
qual = ["-q", "illumina" if dd.get_quality_format(data).lower() == "illumina" else "sanger"]
format = ["-f", "fastq"]
if len(files) == 2:
inputs = ["-l", files[0], "-r", files[1]]
else:
assert len(files) == 1
inputs = [files[0]]
work_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "align_prep"))
out_file = os.path.join(work_dir,
"%s.sdf" % utils.splitext_plus(os.path.basename(os.path.commonprefix(files)))[0])
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = _rtg_cmd(["rtg", "format", "-o", tx_out_file] + format + qual + inputs)
do.run(cmd, "Format inputs to indexed SDF")
return out_file | python | def to_sdf(files, data):
# BAM
if len(files) == 1 and files[0].endswith(".bam"):
qual = []
format = ["-f", "sam-pe" if bam.is_paired(files[0]) else "sam-se"]
inputs = [files[0]]
# fastq
else:
qual = ["-q", "illumina" if dd.get_quality_format(data).lower() == "illumina" else "sanger"]
format = ["-f", "fastq"]
if len(files) == 2:
inputs = ["-l", files[0], "-r", files[1]]
else:
assert len(files) == 1
inputs = [files[0]]
work_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "align_prep"))
out_file = os.path.join(work_dir,
"%s.sdf" % utils.splitext_plus(os.path.basename(os.path.commonprefix(files)))[0])
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = _rtg_cmd(["rtg", "format", "-o", tx_out_file] + format + qual + inputs)
do.run(cmd, "Format inputs to indexed SDF")
return out_file | [
"def",
"to_sdf",
"(",
"files",
",",
"data",
")",
":",
"# BAM",
"if",
"len",
"(",
"files",
")",
"==",
"1",
"and",
"files",
"[",
"0",
"]",
".",
"endswith",
"(",
"\".bam\"",
")",
":",
"qual",
"=",
"[",
"]",
"format",
"=",
"[",
"\"-f\"",
",",
"\"sa... | Convert a fastq or BAM input into a SDF indexed file. | [
"Convert",
"a",
"fastq",
"or",
"BAM",
"input",
"into",
"a",
"SDF",
"indexed",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/rtg.py#L16-L40 |
237,122 | bcbio/bcbio-nextgen | bcbio/ngsalign/rtg.py | to_fastq_apipe_cl | def to_fastq_apipe_cl(sdf_file, start=None, end=None):
"""Return a command lines to provide streaming fastq input.
For paired end, returns a forward and reverse command line. For
single end returns a single command line and None for the pair.
"""
cmd = ["rtg", "sdf2fastq", "--no-gzip", "-o", "-"]
if start is not None:
cmd += ["--start-id=%s" % start]
if end is not None:
cmd += ["--end-id=%s" % end]
if is_paired(sdf_file):
out = []
for ext in ["left", "right"]:
out.append("<(%s)" % _rtg_cmd(cmd + ["-i", os.path.join(sdf_file, ext)]))
return out
else:
cmd += ["-i", sdf_file]
return ["<(%s)" % _rtg_cmd(cmd), None] | python | def to_fastq_apipe_cl(sdf_file, start=None, end=None):
cmd = ["rtg", "sdf2fastq", "--no-gzip", "-o", "-"]
if start is not None:
cmd += ["--start-id=%s" % start]
if end is not None:
cmd += ["--end-id=%s" % end]
if is_paired(sdf_file):
out = []
for ext in ["left", "right"]:
out.append("<(%s)" % _rtg_cmd(cmd + ["-i", os.path.join(sdf_file, ext)]))
return out
else:
cmd += ["-i", sdf_file]
return ["<(%s)" % _rtg_cmd(cmd), None] | [
"def",
"to_fastq_apipe_cl",
"(",
"sdf_file",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"\"rtg\"",
",",
"\"sdf2fastq\"",
",",
"\"--no-gzip\"",
",",
"\"-o\"",
",",
"\"-\"",
"]",
"if",
"start",
"is",
"not",
"None",
":"... | Return a command lines to provide streaming fastq input.
For paired end, returns a forward and reverse command line. For
single end returns a single command line and None for the pair. | [
"Return",
"a",
"command",
"lines",
"to",
"provide",
"streaming",
"fastq",
"input",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/rtg.py#L82-L100 |
237,123 | bcbio/bcbio-nextgen | bcbio/pipeline/tools.py | get_tabix_cmd | def get_tabix_cmd(config):
"""Retrieve tabix command, handling new bcftools tabix and older tabix.
"""
try:
bcftools = config_utils.get_program("bcftools", config)
# bcftools has terrible error codes and stderr output, swallow those.
bcftools_tabix = subprocess.check_output("{bcftools} 2>&1; echo $?".format(**locals()),
shell=True).decode().find("tabix") >= 0
except config_utils.CmdNotFound:
bcftools_tabix = False
if bcftools_tabix:
return "{0} tabix".format(bcftools)
else:
tabix = config_utils.get_program("tabix", config)
return tabix | python | def get_tabix_cmd(config):
try:
bcftools = config_utils.get_program("bcftools", config)
# bcftools has terrible error codes and stderr output, swallow those.
bcftools_tabix = subprocess.check_output("{bcftools} 2>&1; echo $?".format(**locals()),
shell=True).decode().find("tabix") >= 0
except config_utils.CmdNotFound:
bcftools_tabix = False
if bcftools_tabix:
return "{0} tabix".format(bcftools)
else:
tabix = config_utils.get_program("tabix", config)
return tabix | [
"def",
"get_tabix_cmd",
"(",
"config",
")",
":",
"try",
":",
"bcftools",
"=",
"config_utils",
".",
"get_program",
"(",
"\"bcftools\"",
",",
"config",
")",
"# bcftools has terrible error codes and stderr output, swallow those.",
"bcftools_tabix",
"=",
"subprocess",
".",
... | Retrieve tabix command, handling new bcftools tabix and older tabix. | [
"Retrieve",
"tabix",
"command",
"handling",
"new",
"bcftools",
"tabix",
"and",
"older",
"tabix",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/tools.py#L10-L24 |
237,124 | bcbio/bcbio-nextgen | bcbio/pipeline/tools.py | get_bgzip_cmd | def get_bgzip_cmd(config, is_retry=False):
"""Retrieve command to use for bgzip, trying to use bgzip parallel threads.
By default, parallel bgzip is enabled in bcbio. If it causes problems
please report them. You can turn parallel bgzip off with `tools_off: [pbgzip]`
"""
num_cores = tz.get_in(["algorithm", "num_cores"], config, 1)
cmd = config_utils.get_program("bgzip", config)
if (not is_retry and num_cores > 1 and
"pbgzip" not in dd.get_tools_off({"config": config})):
cmd += " --threads %s" % num_cores
return cmd | python | def get_bgzip_cmd(config, is_retry=False):
num_cores = tz.get_in(["algorithm", "num_cores"], config, 1)
cmd = config_utils.get_program("bgzip", config)
if (not is_retry and num_cores > 1 and
"pbgzip" not in dd.get_tools_off({"config": config})):
cmd += " --threads %s" % num_cores
return cmd | [
"def",
"get_bgzip_cmd",
"(",
"config",
",",
"is_retry",
"=",
"False",
")",
":",
"num_cores",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"algorithm\"",
",",
"\"num_cores\"",
"]",
",",
"config",
",",
"1",
")",
"cmd",
"=",
"config_utils",
".",
"get_program",
"("... | Retrieve command to use for bgzip, trying to use bgzip parallel threads.
By default, parallel bgzip is enabled in bcbio. If it causes problems
please report them. You can turn parallel bgzip off with `tools_off: [pbgzip]` | [
"Retrieve",
"command",
"to",
"use",
"for",
"bgzip",
"trying",
"to",
"use",
"bgzip",
"parallel",
"threads",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/tools.py#L26-L37 |
237,125 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | is_empty | def is_empty(bam_file):
"""Determine if a BAM file is empty
"""
bam_file = objectstore.cl_input(bam_file)
cmd = ("set -o pipefail; "
"samtools view {bam_file} | head -1 | wc -l")
p = subprocess.Popen(cmd.format(**locals()), shell=True,
executable=do.find_bash(),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL))
stdout, stderr = p.communicate()
stdout = stdout.decode()
stderr = stderr.decode()
if ((p.returncode == 0 or p.returncode == 141) and
(stderr == "" or (stderr.startswith("gof3r") and stderr.endswith("broken pipe")))):
return int(stdout) == 0
else:
raise ValueError("Failed to check empty status of BAM file: %s" % str(stderr)) | python | def is_empty(bam_file):
bam_file = objectstore.cl_input(bam_file)
cmd = ("set -o pipefail; "
"samtools view {bam_file} | head -1 | wc -l")
p = subprocess.Popen(cmd.format(**locals()), shell=True,
executable=do.find_bash(),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL))
stdout, stderr = p.communicate()
stdout = stdout.decode()
stderr = stderr.decode()
if ((p.returncode == 0 or p.returncode == 141) and
(stderr == "" or (stderr.startswith("gof3r") and stderr.endswith("broken pipe")))):
return int(stdout) == 0
else:
raise ValueError("Failed to check empty status of BAM file: %s" % str(stderr)) | [
"def",
"is_empty",
"(",
"bam_file",
")",
":",
"bam_file",
"=",
"objectstore",
".",
"cl_input",
"(",
"bam_file",
")",
"cmd",
"=",
"(",
"\"set -o pipefail; \"",
"\"samtools view {bam_file} | head -1 | wc -l\"",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
... | Determine if a BAM file is empty | [
"Determine",
"if",
"a",
"BAM",
"file",
"is",
"empty"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L24-L41 |
237,126 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | fake_index | def fake_index(in_bam, data):
"""Create a fake index file for namesorted BAMs. bais require by CWL for consistency.
"""
index_file = "%s.bai" % in_bam
if not utils.file_exists(index_file):
with file_transaction(data, index_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
out_handle.write("name sorted -- no index")
return index_file | python | def fake_index(in_bam, data):
index_file = "%s.bai" % in_bam
if not utils.file_exists(index_file):
with file_transaction(data, index_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
out_handle.write("name sorted -- no index")
return index_file | [
"def",
"fake_index",
"(",
"in_bam",
",",
"data",
")",
":",
"index_file",
"=",
"\"%s.bai\"",
"%",
"in_bam",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"index_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"index_file",
")",
"as",
"tx_out... | Create a fake index file for namesorted BAMs. bais require by CWL for consistency. | [
"Create",
"a",
"fake",
"index",
"file",
"for",
"namesorted",
"BAMs",
".",
"bais",
"require",
"by",
"CWL",
"for",
"consistency",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L67-L75 |
237,127 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | index | def index(in_bam, config, check_timestamp=True):
"""Index a BAM file, skipping if index present.
Centralizes BAM indexing providing ability to switch indexing approaches.
"""
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
index_file = "%s.bai" % in_bam
alt_index_file = "%s.bai" % os.path.splitext(in_bam)[0]
if check_timestamp:
bai_exists = utils.file_uptodate(index_file, in_bam) or utils.file_uptodate(alt_index_file, in_bam)
else:
bai_exists = utils.file_exists(index_file) or utils.file_exists(alt_index_file)
if not bai_exists:
# Remove old index files and re-run to prevent linking into tx directory
for fname in [index_file, alt_index_file]:
utils.remove_safe(fname)
samtools = config_utils.get_program("samtools", config)
num_cores = config["algorithm"].get("num_cores", 1)
with file_transaction(config, index_file) as tx_index_file:
cmd = "{samtools} index -@ {num_cores} {in_bam} {tx_index_file}"
do.run(cmd.format(**locals()), "Index BAM file: %s" % os.path.basename(in_bam))
return index_file if utils.file_exists(index_file) else alt_index_file | python | def index(in_bam, config, check_timestamp=True):
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
index_file = "%s.bai" % in_bam
alt_index_file = "%s.bai" % os.path.splitext(in_bam)[0]
if check_timestamp:
bai_exists = utils.file_uptodate(index_file, in_bam) or utils.file_uptodate(alt_index_file, in_bam)
else:
bai_exists = utils.file_exists(index_file) or utils.file_exists(alt_index_file)
if not bai_exists:
# Remove old index files and re-run to prevent linking into tx directory
for fname in [index_file, alt_index_file]:
utils.remove_safe(fname)
samtools = config_utils.get_program("samtools", config)
num_cores = config["algorithm"].get("num_cores", 1)
with file_transaction(config, index_file) as tx_index_file:
cmd = "{samtools} index -@ {num_cores} {in_bam} {tx_index_file}"
do.run(cmd.format(**locals()), "Index BAM file: %s" % os.path.basename(in_bam))
return index_file if utils.file_exists(index_file) else alt_index_file | [
"def",
"index",
"(",
"in_bam",
",",
"config",
",",
"check_timestamp",
"=",
"True",
")",
":",
"assert",
"is_bam",
"(",
"in_bam",
")",
",",
"\"%s in not a BAM file\"",
"%",
"in_bam",
"index_file",
"=",
"\"%s.bai\"",
"%",
"in_bam",
"alt_index_file",
"=",
"\"%s.ba... | Index a BAM file, skipping if index present.
Centralizes BAM indexing providing ability to switch indexing approaches. | [
"Index",
"a",
"BAM",
"file",
"skipping",
"if",
"index",
"present",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L77-L98 |
237,128 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | remove | def remove(in_bam):
"""
remove bam file and the index if exists
"""
if utils.file_exists(in_bam):
utils.remove_safe(in_bam)
if utils.file_exists(in_bam + ".bai"):
utils.remove_safe(in_bam + ".bai") | python | def remove(in_bam):
if utils.file_exists(in_bam):
utils.remove_safe(in_bam)
if utils.file_exists(in_bam + ".bai"):
utils.remove_safe(in_bam + ".bai") | [
"def",
"remove",
"(",
"in_bam",
")",
":",
"if",
"utils",
".",
"file_exists",
"(",
"in_bam",
")",
":",
"utils",
".",
"remove_safe",
"(",
"in_bam",
")",
"if",
"utils",
".",
"file_exists",
"(",
"in_bam",
"+",
"\".bai\"",
")",
":",
"utils",
".",
"remove_sa... | remove bam file and the index if exists | [
"remove",
"bam",
"file",
"and",
"the",
"index",
"if",
"exists"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L100-L107 |
237,129 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | idxstats | def idxstats(in_bam, data):
"""Return BAM index stats for the given file, using samtools idxstats.
"""
index(in_bam, data["config"], check_timestamp=False)
AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "aligned", "unaligned"])
samtools = config_utils.get_program("samtools", data["config"])
idxstats_out = subprocess.check_output([samtools, "idxstats", in_bam]).decode()
out = []
for line in idxstats_out.split("\n"):
if line.strip():
contig, length, aligned, unaligned = line.split("\t")
out.append(AlignInfo(contig, int(length), int(aligned), int(unaligned)))
return out | python | def idxstats(in_bam, data):
index(in_bam, data["config"], check_timestamp=False)
AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "aligned", "unaligned"])
samtools = config_utils.get_program("samtools", data["config"])
idxstats_out = subprocess.check_output([samtools, "idxstats", in_bam]).decode()
out = []
for line in idxstats_out.split("\n"):
if line.strip():
contig, length, aligned, unaligned = line.split("\t")
out.append(AlignInfo(contig, int(length), int(aligned), int(unaligned)))
return out | [
"def",
"idxstats",
"(",
"in_bam",
",",
"data",
")",
":",
"index",
"(",
"in_bam",
",",
"data",
"[",
"\"config\"",
"]",
",",
"check_timestamp",
"=",
"False",
")",
"AlignInfo",
"=",
"collections",
".",
"namedtuple",
"(",
"\"AlignInfo\"",
",",
"[",
"\"contig\"... | Return BAM index stats for the given file, using samtools idxstats. | [
"Return",
"BAM",
"index",
"stats",
"for",
"the",
"given",
"file",
"using",
"samtools",
"idxstats",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L109-L121 |
237,130 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | fai_from_bam | def fai_from_bam(ref_file, bam_file, out_file, data):
"""Create a fai index with only contigs in the input BAM file.
"""
contigs = set([x.contig for x in idxstats(bam_file, data)])
if not utils.file_uptodate(out_file, bam_file):
with open(ref.fasta_idx(ref_file, data["config"])) as in_handle:
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for line in (l for l in in_handle if l.strip()):
if line.split()[0] in contigs:
out_handle.write(line)
return out_file | python | def fai_from_bam(ref_file, bam_file, out_file, data):
contigs = set([x.contig for x in idxstats(bam_file, data)])
if not utils.file_uptodate(out_file, bam_file):
with open(ref.fasta_idx(ref_file, data["config"])) as in_handle:
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for line in (l for l in in_handle if l.strip()):
if line.split()[0] in contigs:
out_handle.write(line)
return out_file | [
"def",
"fai_from_bam",
"(",
"ref_file",
",",
"bam_file",
",",
"out_file",
",",
"data",
")",
":",
"contigs",
"=",
"set",
"(",
"[",
"x",
".",
"contig",
"for",
"x",
"in",
"idxstats",
"(",
"bam_file",
",",
"data",
")",
"]",
")",
"if",
"not",
"utils",
"... | Create a fai index with only contigs in the input BAM file. | [
"Create",
"a",
"fai",
"index",
"with",
"only",
"contigs",
"in",
"the",
"input",
"BAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L123-L134 |
237,131 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | ref_file_from_bam | def ref_file_from_bam(bam_file, data):
"""Subset a fasta input file to only a fraction of input contigs.
"""
new_ref = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(data), "inputs", "ref")),
"%s-subset.fa" % dd.get_genome_build(data))
if not utils.file_exists(new_ref):
with file_transaction(data, new_ref) as tx_out_file:
contig_file = "%s-contigs.txt" % utils.splitext_plus(new_ref)[0]
with open(contig_file, "w") as out_handle:
for contig in [x.contig for x in idxstats(bam_file, data) if x.contig != "*"]:
out_handle.write("%s\n" % contig)
cmd = "seqtk subseq -l 100 %s %s > %s" % (dd.get_ref_file(data), contig_file, tx_out_file)
do.run(cmd, "Subset %s to BAM file contigs" % dd.get_genome_build(data))
ref.fasta_idx(new_ref, data["config"])
runner = broad.runner_from_path("picard", data["config"])
runner.run_fn("picard_index_ref", new_ref)
return {"base": new_ref} | python | def ref_file_from_bam(bam_file, data):
new_ref = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(data), "inputs", "ref")),
"%s-subset.fa" % dd.get_genome_build(data))
if not utils.file_exists(new_ref):
with file_transaction(data, new_ref) as tx_out_file:
contig_file = "%s-contigs.txt" % utils.splitext_plus(new_ref)[0]
with open(contig_file, "w") as out_handle:
for contig in [x.contig for x in idxstats(bam_file, data) if x.contig != "*"]:
out_handle.write("%s\n" % contig)
cmd = "seqtk subseq -l 100 %s %s > %s" % (dd.get_ref_file(data), contig_file, tx_out_file)
do.run(cmd, "Subset %s to BAM file contigs" % dd.get_genome_build(data))
ref.fasta_idx(new_ref, data["config"])
runner = broad.runner_from_path("picard", data["config"])
runner.run_fn("picard_index_ref", new_ref)
return {"base": new_ref} | [
"def",
"ref_file_from_bam",
"(",
"bam_file",
",",
"data",
")",
":",
"new_ref",
"=",
"os",
".",
"path",
".",
"join",
"(",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",
",",
"\"inpu... | Subset a fasta input file to only a fraction of input contigs. | [
"Subset",
"a",
"fasta",
"input",
"file",
"to",
"only",
"a",
"fraction",
"of",
"input",
"contigs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L136-L152 |
237,132 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | get_downsample_pct | def get_downsample_pct(in_bam, target_counts, data):
"""Retrieve percentage of file to downsample to get to target counts.
Avoids minimal downsample which is not especially useful for
improving QC times; 90& or more of reads.
"""
total = sum(x.aligned for x in idxstats(in_bam, data))
with pysam.Samfile(in_bam, "rb") as work_bam:
n_rgs = max(1, len(work_bam.header.get("RG", [])))
rg_target = n_rgs * target_counts
if total > rg_target:
pct = float(rg_target) / float(total)
if pct < 0.9:
return pct | python | def get_downsample_pct(in_bam, target_counts, data):
total = sum(x.aligned for x in idxstats(in_bam, data))
with pysam.Samfile(in_bam, "rb") as work_bam:
n_rgs = max(1, len(work_bam.header.get("RG", [])))
rg_target = n_rgs * target_counts
if total > rg_target:
pct = float(rg_target) / float(total)
if pct < 0.9:
return pct | [
"def",
"get_downsample_pct",
"(",
"in_bam",
",",
"target_counts",
",",
"data",
")",
":",
"total",
"=",
"sum",
"(",
"x",
".",
"aligned",
"for",
"x",
"in",
"idxstats",
"(",
"in_bam",
",",
"data",
")",
")",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
... | Retrieve percentage of file to downsample to get to target counts.
Avoids minimal downsample which is not especially useful for
improving QC times; 90& or more of reads. | [
"Retrieve",
"percentage",
"of",
"file",
"to",
"downsample",
"to",
"get",
"to",
"target",
"counts",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L154-L167 |
237,133 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | downsample | def downsample(in_bam, data, target_counts, work_dir=None):
"""Downsample a BAM file to the specified number of target counts.
"""
index(in_bam, data["config"], check_timestamp=False)
ds_pct = get_downsample_pct(in_bam, target_counts, data)
if ds_pct:
out_file = "%s-downsample%s" % os.path.splitext(in_bam)
if work_dir:
out_file = os.path.join(work_dir, os.path.basename(out_file))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
samtools = config_utils.get_program("samtools", data["config"])
num_cores = dd.get_num_cores(data)
ds_pct = "42." + "{ds_pct:.3}".format(ds_pct=ds_pct).replace("0.", "")
cmd = ("{samtools} view -O BAM -@ {num_cores} -o {tx_out_file} "
"-s {ds_pct} {in_bam}")
do.run(cmd.format(**locals()), "Downsample BAM file: %s" % os.path.basename(in_bam))
return out_file | python | def downsample(in_bam, data, target_counts, work_dir=None):
index(in_bam, data["config"], check_timestamp=False)
ds_pct = get_downsample_pct(in_bam, target_counts, data)
if ds_pct:
out_file = "%s-downsample%s" % os.path.splitext(in_bam)
if work_dir:
out_file = os.path.join(work_dir, os.path.basename(out_file))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
samtools = config_utils.get_program("samtools", data["config"])
num_cores = dd.get_num_cores(data)
ds_pct = "42." + "{ds_pct:.3}".format(ds_pct=ds_pct).replace("0.", "")
cmd = ("{samtools} view -O BAM -@ {num_cores} -o {tx_out_file} "
"-s {ds_pct} {in_bam}")
do.run(cmd.format(**locals()), "Downsample BAM file: %s" % os.path.basename(in_bam))
return out_file | [
"def",
"downsample",
"(",
"in_bam",
",",
"data",
",",
"target_counts",
",",
"work_dir",
"=",
"None",
")",
":",
"index",
"(",
"in_bam",
",",
"data",
"[",
"\"config\"",
"]",
",",
"check_timestamp",
"=",
"False",
")",
"ds_pct",
"=",
"get_downsample_pct",
"(",... | Downsample a BAM file to the specified number of target counts. | [
"Downsample",
"a",
"BAM",
"file",
"to",
"the",
"specified",
"number",
"of",
"target",
"counts",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L177-L194 |
237,134 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | get_maxcov_downsample_cl | def get_maxcov_downsample_cl(data, in_pipe=None):
"""Retrieve command line for max coverage downsampling, fitting into bamsormadup output.
"""
max_cov = _get_maxcov_downsample(data) if dd.get_aligner(data) not in ["snap"] else None
if max_cov:
if in_pipe == "bamsormadup":
prefix = "level=0"
elif in_pipe == "samtools":
prefix = "-l 0"
else:
prefix = ""
# Swap over to multiple cores until after testing
#core_arg = "-t %s" % dd.get_num_cores(data)
core_arg = ""
return ("%s | variant - -b %s --mark-as-qc-fail --max-coverage %s"
% (prefix, core_arg, max_cov))
else:
if in_pipe == "bamsormadup":
prefix = "indexfilename={tx_out_file}.bai"
else:
prefix = ""
return prefix | python | def get_maxcov_downsample_cl(data, in_pipe=None):
max_cov = _get_maxcov_downsample(data) if dd.get_aligner(data) not in ["snap"] else None
if max_cov:
if in_pipe == "bamsormadup":
prefix = "level=0"
elif in_pipe == "samtools":
prefix = "-l 0"
else:
prefix = ""
# Swap over to multiple cores until after testing
#core_arg = "-t %s" % dd.get_num_cores(data)
core_arg = ""
return ("%s | variant - -b %s --mark-as-qc-fail --max-coverage %s"
% (prefix, core_arg, max_cov))
else:
if in_pipe == "bamsormadup":
prefix = "indexfilename={tx_out_file}.bai"
else:
prefix = ""
return prefix | [
"def",
"get_maxcov_downsample_cl",
"(",
"data",
",",
"in_pipe",
"=",
"None",
")",
":",
"max_cov",
"=",
"_get_maxcov_downsample",
"(",
"data",
")",
"if",
"dd",
".",
"get_aligner",
"(",
"data",
")",
"not",
"in",
"[",
"\"snap\"",
"]",
"else",
"None",
"if",
... | Retrieve command line for max coverage downsampling, fitting into bamsormadup output. | [
"Retrieve",
"command",
"line",
"for",
"max",
"coverage",
"downsampling",
"fitting",
"into",
"bamsormadup",
"output",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L196-L217 |
237,135 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | _get_maxcov_downsample | def _get_maxcov_downsample(data):
"""Calculate maximum coverage downsampling for whole genome samples.
Returns None if we're not doing downsampling.
"""
from bcbio.bam import ref
from bcbio.ngsalign import alignprep, bwa
from bcbio.variation import coverage
fastq_file = data["files"][0]
params = alignprep.get_downsample_params(data)
if params:
num_reads = alignprep.total_reads_from_grabix(fastq_file)
if num_reads:
vrs = dd.get_variant_regions_merged(data)
total_size = sum([c.size for c in ref.file_contigs(dd.get_ref_file(data), data["config"])])
if vrs:
callable_size = pybedtools.BedTool(vrs).total_coverage()
genome_cov_pct = callable_size / float(total_size)
else:
callable_size = total_size
genome_cov_pct = 1.0
if (genome_cov_pct > coverage.GENOME_COV_THRESH
and dd.get_coverage_interval(data) in ["genome", None, False]):
total_counts, total_sizes = 0, 0
for count, size in bwa.fastq_size_output(fastq_file, 5000):
total_counts += int(count)
total_sizes += (int(size) * int(count))
read_size = float(total_sizes) / float(total_counts)
avg_cov = float(num_reads * read_size) / callable_size
if avg_cov >= params["min_coverage_for_downsampling"]:
return int(avg_cov * params["maxcov_downsample_multiplier"])
return None | python | def _get_maxcov_downsample(data):
from bcbio.bam import ref
from bcbio.ngsalign import alignprep, bwa
from bcbio.variation import coverage
fastq_file = data["files"][0]
params = alignprep.get_downsample_params(data)
if params:
num_reads = alignprep.total_reads_from_grabix(fastq_file)
if num_reads:
vrs = dd.get_variant_regions_merged(data)
total_size = sum([c.size for c in ref.file_contigs(dd.get_ref_file(data), data["config"])])
if vrs:
callable_size = pybedtools.BedTool(vrs).total_coverage()
genome_cov_pct = callable_size / float(total_size)
else:
callable_size = total_size
genome_cov_pct = 1.0
if (genome_cov_pct > coverage.GENOME_COV_THRESH
and dd.get_coverage_interval(data) in ["genome", None, False]):
total_counts, total_sizes = 0, 0
for count, size in bwa.fastq_size_output(fastq_file, 5000):
total_counts += int(count)
total_sizes += (int(size) * int(count))
read_size = float(total_sizes) / float(total_counts)
avg_cov = float(num_reads * read_size) / callable_size
if avg_cov >= params["min_coverage_for_downsampling"]:
return int(avg_cov * params["maxcov_downsample_multiplier"])
return None | [
"def",
"_get_maxcov_downsample",
"(",
"data",
")",
":",
"from",
"bcbio",
".",
"bam",
"import",
"ref",
"from",
"bcbio",
".",
"ngsalign",
"import",
"alignprep",
",",
"bwa",
"from",
"bcbio",
".",
"variation",
"import",
"coverage",
"fastq_file",
"=",
"data",
"["... | Calculate maximum coverage downsampling for whole genome samples.
Returns None if we're not doing downsampling. | [
"Calculate",
"maximum",
"coverage",
"downsampling",
"for",
"whole",
"genome",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L219-L250 |
237,136 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | check_header | def check_header(in_bam, rgnames, ref_file, config):
"""Ensure passed in BAM header matches reference file and read groups names.
"""
_check_bam_contigs(in_bam, ref_file, config)
_check_sample(in_bam, rgnames) | python | def check_header(in_bam, rgnames, ref_file, config):
_check_bam_contigs(in_bam, ref_file, config)
_check_sample(in_bam, rgnames) | [
"def",
"check_header",
"(",
"in_bam",
",",
"rgnames",
",",
"ref_file",
",",
"config",
")",
":",
"_check_bam_contigs",
"(",
"in_bam",
",",
"ref_file",
",",
"config",
")",
"_check_sample",
"(",
"in_bam",
",",
"rgnames",
")"
] | Ensure passed in BAM header matches reference file and read groups names. | [
"Ensure",
"passed",
"in",
"BAM",
"header",
"matches",
"reference",
"file",
"and",
"read",
"groups",
"names",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L253-L257 |
237,137 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | _check_sample | def _check_sample(in_bam, rgnames):
"""Ensure input sample name matches expected run group names.
"""
with pysam.Samfile(in_bam, "rb") as bamfile:
rg = bamfile.header.get("RG", [{}])
msgs = []
warnings = []
if len(rg) > 1:
warnings.append("Multiple read groups found in input BAM. Expect single RG per BAM.")
if len(rg) == 0:
msgs.append("No read groups found in input BAM. Expect single RG per BAM.")
if len(rg) > 0 and any(x.get("SM") != rgnames["sample"] for x in rg):
msgs.append("Read group sample name (SM) does not match configuration `description`: %s vs %s"
% (rg[0].get("SM"), rgnames["sample"]))
if len(msgs) > 0:
raise ValueError("Problems with pre-aligned input BAM file: %s\n" % (in_bam)
+ "\n".join(msgs) +
"\nSetting `bam_clean: fixrg`\n"
"in the configuration can often fix this issue.")
if warnings:
print("*** Potential problems in input BAM compared to reference:\n%s\n" %
"\n".join(warnings)) | python | def _check_sample(in_bam, rgnames):
with pysam.Samfile(in_bam, "rb") as bamfile:
rg = bamfile.header.get("RG", [{}])
msgs = []
warnings = []
if len(rg) > 1:
warnings.append("Multiple read groups found in input BAM. Expect single RG per BAM.")
if len(rg) == 0:
msgs.append("No read groups found in input BAM. Expect single RG per BAM.")
if len(rg) > 0 and any(x.get("SM") != rgnames["sample"] for x in rg):
msgs.append("Read group sample name (SM) does not match configuration `description`: %s vs %s"
% (rg[0].get("SM"), rgnames["sample"]))
if len(msgs) > 0:
raise ValueError("Problems with pre-aligned input BAM file: %s\n" % (in_bam)
+ "\n".join(msgs) +
"\nSetting `bam_clean: fixrg`\n"
"in the configuration can often fix this issue.")
if warnings:
print("*** Potential problems in input BAM compared to reference:\n%s\n" %
"\n".join(warnings)) | [
"def",
"_check_sample",
"(",
"in_bam",
",",
"rgnames",
")",
":",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
",",
"\"rb\"",
")",
"as",
"bamfile",
":",
"rg",
"=",
"bamfile",
".",
"header",
".",
"get",
"(",
"\"RG\"",
",",
"[",
"{",
"}",
"]",
")",... | Ensure input sample name matches expected run group names. | [
"Ensure",
"input",
"sample",
"name",
"matches",
"expected",
"run",
"group",
"names",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L259-L280 |
237,138 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | _check_bam_contigs | def _check_bam_contigs(in_bam, ref_file, config):
"""Ensure a pre-aligned BAM file matches the expected reference genome.
"""
# GATK allows chromosome M to be in multiple locations, skip checking it
allowed_outoforder = ["chrM", "MT"]
ref_contigs = [c.name for c in ref.file_contigs(ref_file, config)]
with pysam.Samfile(in_bam, "rb") as bamfile:
bam_contigs = [c["SN"] for c in bamfile.header["SQ"]]
extra_bcs = [x for x in bam_contigs if x not in ref_contigs]
extra_rcs = [x for x in ref_contigs if x not in bam_contigs]
problems = []
warnings = []
for bc, rc in zip_longest([x for x in bam_contigs if (x not in extra_bcs and
x not in allowed_outoforder)],
[x for x in ref_contigs if (x not in extra_rcs and
x not in allowed_outoforder)]):
if bc != rc:
if bc and rc:
problems.append("Reference mismatch. BAM: %s Reference: %s" % (bc, rc))
elif bc:
warnings.append("Extra BAM chromosomes: %s" % bc)
elif rc:
warnings.append("Extra reference chromosomes: %s" % rc)
for bc in extra_bcs:
warnings.append("Extra BAM chromosomes: %s" % bc)
for rc in extra_rcs:
warnings.append("Extra reference chromosomes: %s" % rc)
if problems:
raise ValueError("Unexpected order, name or contig mismatches between input BAM and reference file:\n%s\n"
"Setting `bam_clean: remove_extracontigs` in the configuration can often fix this issue."
% "\n".join(problems))
if warnings:
print("*** Potential problems in input BAM compared to reference:\n%s\n" %
"\n".join(warnings)) | python | def _check_bam_contigs(in_bam, ref_file, config):
# GATK allows chromosome M to be in multiple locations, skip checking it
allowed_outoforder = ["chrM", "MT"]
ref_contigs = [c.name for c in ref.file_contigs(ref_file, config)]
with pysam.Samfile(in_bam, "rb") as bamfile:
bam_contigs = [c["SN"] for c in bamfile.header["SQ"]]
extra_bcs = [x for x in bam_contigs if x not in ref_contigs]
extra_rcs = [x for x in ref_contigs if x not in bam_contigs]
problems = []
warnings = []
for bc, rc in zip_longest([x for x in bam_contigs if (x not in extra_bcs and
x not in allowed_outoforder)],
[x for x in ref_contigs if (x not in extra_rcs and
x not in allowed_outoforder)]):
if bc != rc:
if bc and rc:
problems.append("Reference mismatch. BAM: %s Reference: %s" % (bc, rc))
elif bc:
warnings.append("Extra BAM chromosomes: %s" % bc)
elif rc:
warnings.append("Extra reference chromosomes: %s" % rc)
for bc in extra_bcs:
warnings.append("Extra BAM chromosomes: %s" % bc)
for rc in extra_rcs:
warnings.append("Extra reference chromosomes: %s" % rc)
if problems:
raise ValueError("Unexpected order, name or contig mismatches between input BAM and reference file:\n%s\n"
"Setting `bam_clean: remove_extracontigs` in the configuration can often fix this issue."
% "\n".join(problems))
if warnings:
print("*** Potential problems in input BAM compared to reference:\n%s\n" %
"\n".join(warnings)) | [
"def",
"_check_bam_contigs",
"(",
"in_bam",
",",
"ref_file",
",",
"config",
")",
":",
"# GATK allows chromosome M to be in multiple locations, skip checking it",
"allowed_outoforder",
"=",
"[",
"\"chrM\"",
",",
"\"MT\"",
"]",
"ref_contigs",
"=",
"[",
"c",
".",
"name",
... | Ensure a pre-aligned BAM file matches the expected reference genome. | [
"Ensure",
"a",
"pre",
"-",
"aligned",
"BAM",
"file",
"matches",
"the",
"expected",
"reference",
"genome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L282-L315 |
237,139 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | sort | def sort(in_bam, config, order="coordinate", out_dir=None):
"""Sort a BAM file, skipping if already present.
"""
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
if bam_already_sorted(in_bam, config, order):
return in_bam
sort_stem = _get_sort_stem(in_bam, order, out_dir)
sort_file = sort_stem + ".bam"
if not utils.file_exists(sort_file):
samtools = config_utils.get_program("samtools", config)
cores = config["algorithm"].get("num_cores", 1)
with file_transaction(config, sort_file) as tx_sort_file:
tx_sort_stem = os.path.splitext(tx_sort_file)[0]
tx_dir = utils.safe_makedir(os.path.dirname(tx_sort_file))
order_flag = "-n" if order == "queryname" else ""
resources = config_utils.get_resources("samtools", config)
# Slightly decrease memory and allow more accurate representation
# in Mb to ensure fits within systems like SLURM
mem = config_utils.adjust_memory(resources.get("memory", "2G"),
1.25, "decrease", out_modifier="M").upper()
cmd = ("{samtools} sort -@ {cores} -m {mem} -O BAM {order_flag} "
"-T {tx_sort_stem}-sort -o {tx_sort_file} {in_bam}")
do.run(cmd.format(**locals()), "Sort BAM file %s: %s to %s" %
(order, os.path.basename(in_bam), os.path.basename(sort_file)))
return sort_file | python | def sort(in_bam, config, order="coordinate", out_dir=None):
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
if bam_already_sorted(in_bam, config, order):
return in_bam
sort_stem = _get_sort_stem(in_bam, order, out_dir)
sort_file = sort_stem + ".bam"
if not utils.file_exists(sort_file):
samtools = config_utils.get_program("samtools", config)
cores = config["algorithm"].get("num_cores", 1)
with file_transaction(config, sort_file) as tx_sort_file:
tx_sort_stem = os.path.splitext(tx_sort_file)[0]
tx_dir = utils.safe_makedir(os.path.dirname(tx_sort_file))
order_flag = "-n" if order == "queryname" else ""
resources = config_utils.get_resources("samtools", config)
# Slightly decrease memory and allow more accurate representation
# in Mb to ensure fits within systems like SLURM
mem = config_utils.adjust_memory(resources.get("memory", "2G"),
1.25, "decrease", out_modifier="M").upper()
cmd = ("{samtools} sort -@ {cores} -m {mem} -O BAM {order_flag} "
"-T {tx_sort_stem}-sort -o {tx_sort_file} {in_bam}")
do.run(cmd.format(**locals()), "Sort BAM file %s: %s to %s" %
(order, os.path.basename(in_bam), os.path.basename(sort_file)))
return sort_file | [
"def",
"sort",
"(",
"in_bam",
",",
"config",
",",
"order",
"=",
"\"coordinate\"",
",",
"out_dir",
"=",
"None",
")",
":",
"assert",
"is_bam",
"(",
"in_bam",
")",
",",
"\"%s in not a BAM file\"",
"%",
"in_bam",
"if",
"bam_already_sorted",
"(",
"in_bam",
",",
... | Sort a BAM file, skipping if already present. | [
"Sort",
"a",
"BAM",
"file",
"skipping",
"if",
"already",
"present",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L406-L431 |
237,140 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | aligner_from_header | def aligner_from_header(in_bam):
"""Identify aligner from the BAM header; handling pre-aligned inputs.
"""
from bcbio.pipeline.alignment import TOOLS
with pysam.Samfile(in_bam, "rb") as bamfile:
for pg in bamfile.header.get("PG", []):
for ka in TOOLS.keys():
if pg.get("PN", "").lower().find(ka) >= 0:
return ka | python | def aligner_from_header(in_bam):
from bcbio.pipeline.alignment import TOOLS
with pysam.Samfile(in_bam, "rb") as bamfile:
for pg in bamfile.header.get("PG", []):
for ka in TOOLS.keys():
if pg.get("PN", "").lower().find(ka) >= 0:
return ka | [
"def",
"aligner_from_header",
"(",
"in_bam",
")",
":",
"from",
"bcbio",
".",
"pipeline",
".",
"alignment",
"import",
"TOOLS",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
",",
"\"rb\"",
")",
"as",
"bamfile",
":",
"for",
"pg",
"in",
"bamfile",
".",
"he... | Identify aligner from the BAM header; handling pre-aligned inputs. | [
"Identify",
"aligner",
"from",
"the",
"BAM",
"header",
";",
"handling",
"pre",
"-",
"aligned",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L455-L463 |
237,141 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | sample_name | def sample_name(in_bam):
"""Get sample name from BAM file.
"""
with pysam.AlignmentFile(in_bam, "rb", check_sq=False) as in_pysam:
try:
if "RG" in in_pysam.header:
return in_pysam.header["RG"][0]["SM"]
except ValueError:
return None | python | def sample_name(in_bam):
with pysam.AlignmentFile(in_bam, "rb", check_sq=False) as in_pysam:
try:
if "RG" in in_pysam.header:
return in_pysam.header["RG"][0]["SM"]
except ValueError:
return None | [
"def",
"sample_name",
"(",
"in_bam",
")",
":",
"with",
"pysam",
".",
"AlignmentFile",
"(",
"in_bam",
",",
"\"rb\"",
",",
"check_sq",
"=",
"False",
")",
"as",
"in_pysam",
":",
"try",
":",
"if",
"\"RG\"",
"in",
"in_pysam",
".",
"header",
":",
"return",
"... | Get sample name from BAM file. | [
"Get",
"sample",
"name",
"from",
"BAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L465-L473 |
237,142 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | filter_primary | def filter_primary(bam_file, data):
"""Filter reads to primary only BAM.
Removes:
- not primary alignment (0x100) 256
- supplementary alignment (0x800) 2048
"""
stem, ext = os.path.splitext(bam_file)
out_file = stem + ".primary" + ext
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cores = dd.get_num_cores(data)
cmd = ("samtools view -@ {cores} -F 2304 -b {bam_file} > {tx_out_file}")
do.run(cmd.format(**locals()), ("Filtering primary alignments in %s." %
os.path.basename(bam_file)))
return out_file | python | def filter_primary(bam_file, data):
stem, ext = os.path.splitext(bam_file)
out_file = stem + ".primary" + ext
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cores = dd.get_num_cores(data)
cmd = ("samtools view -@ {cores} -F 2304 -b {bam_file} > {tx_out_file}")
do.run(cmd.format(**locals()), ("Filtering primary alignments in %s." %
os.path.basename(bam_file)))
return out_file | [
"def",
"filter_primary",
"(",
"bam_file",
",",
"data",
")",
":",
"stem",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"bam_file",
")",
"out_file",
"=",
"stem",
"+",
"\".primary\"",
"+",
"ext",
"if",
"not",
"utils",
".",
"file_exists",
"(",... | Filter reads to primary only BAM.
Removes:
- not primary alignment (0x100) 256
- supplementary alignment (0x800) 2048 | [
"Filter",
"reads",
"to",
"primary",
"only",
"BAM",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L496-L511 |
237,143 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | estimate_max_mapq | def estimate_max_mapq(in_bam, nreads=1e6):
"""Guess maximum MAPQ in a BAM file of reads with alignments
"""
with pysam.Samfile(in_bam, "rb") as work_bam:
reads = tz.take(int(nreads), work_bam)
return max([x.mapq for x in reads if not x.is_unmapped]) | python | def estimate_max_mapq(in_bam, nreads=1e6):
with pysam.Samfile(in_bam, "rb") as work_bam:
reads = tz.take(int(nreads), work_bam)
return max([x.mapq for x in reads if not x.is_unmapped]) | [
"def",
"estimate_max_mapq",
"(",
"in_bam",
",",
"nreads",
"=",
"1e6",
")",
":",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
",",
"\"rb\"",
")",
"as",
"work_bam",
":",
"reads",
"=",
"tz",
".",
"take",
"(",
"int",
"(",
"nreads",
")",
",",
"work_bam... | Guess maximum MAPQ in a BAM file of reads with alignments | [
"Guess",
"maximum",
"MAPQ",
"in",
"a",
"BAM",
"file",
"of",
"reads",
"with",
"alignments"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L513-L518 |
237,144 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | convert_cufflinks_mapq | def convert_cufflinks_mapq(in_bam, out_bam=None):
"""Cufflinks expects the not-valid 255 MAPQ for uniquely mapped reads.
This detects the maximum mapping quality in a BAM file and sets
reads with that quality to be 255
"""
CUFFLINKSMAPQ = 255
if not out_bam:
out_bam = os.path.splitext(in_bam)[0] + "-cufflinks.bam"
if utils.file_exists(out_bam):
return out_bam
maxmapq = estimate_max_mapq(in_bam)
if maxmapq == CUFFLINKSMAPQ:
return in_bam
logger.info("Converting MAPQ scores in %s to be Cufflinks compatible." % in_bam)
with pysam.Samfile(in_bam, "rb") as in_bam_fh:
with pysam.Samfile(out_bam, "wb", template=in_bam_fh) as out_bam_fh:
for read in in_bam_fh:
if read.mapq == maxmapq and not read.is_unmapped:
read.mapq = CUFFLINKSMAPQ
out_bam_fh.write(read)
return out_bam | python | def convert_cufflinks_mapq(in_bam, out_bam=None):
CUFFLINKSMAPQ = 255
if not out_bam:
out_bam = os.path.splitext(in_bam)[0] + "-cufflinks.bam"
if utils.file_exists(out_bam):
return out_bam
maxmapq = estimate_max_mapq(in_bam)
if maxmapq == CUFFLINKSMAPQ:
return in_bam
logger.info("Converting MAPQ scores in %s to be Cufflinks compatible." % in_bam)
with pysam.Samfile(in_bam, "rb") as in_bam_fh:
with pysam.Samfile(out_bam, "wb", template=in_bam_fh) as out_bam_fh:
for read in in_bam_fh:
if read.mapq == maxmapq and not read.is_unmapped:
read.mapq = CUFFLINKSMAPQ
out_bam_fh.write(read)
return out_bam | [
"def",
"convert_cufflinks_mapq",
"(",
"in_bam",
",",
"out_bam",
"=",
"None",
")",
":",
"CUFFLINKSMAPQ",
"=",
"255",
"if",
"not",
"out_bam",
":",
"out_bam",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"in_bam",
")",
"[",
"0",
"]",
"+",
"\"-cufflinks.bam... | Cufflinks expects the not-valid 255 MAPQ for uniquely mapped reads.
This detects the maximum mapping quality in a BAM file and sets
reads with that quality to be 255 | [
"Cufflinks",
"expects",
"the",
"not",
"-",
"valid",
"255",
"MAPQ",
"for",
"uniquely",
"mapped",
"reads",
".",
"This",
"detects",
"the",
"maximum",
"mapping",
"quality",
"in",
"a",
"BAM",
"file",
"and",
"sets",
"reads",
"with",
"that",
"quality",
"to",
"be"... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L520-L540 |
237,145 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | get_gatk_annotations | def get_gatk_annotations(config, include_depth=True, include_baseqranksum=True,
gatk_input=True):
"""Retrieve annotations to use for GATK VariantAnnotator.
If include_depth is false, we'll skip annotating DP. Since GATK downsamples
this will undercount on high depth sequencing and the standard outputs
from the original callers may be preferable.
BaseQRankSum can cause issues with some MuTect2 and other runs, so we
provide option to skip it.
"""
broad_runner = broad.runner_from_config(config)
anns = ["MappingQualityRankSumTest", "MappingQualityZero",
"QualByDepth", "ReadPosRankSumTest", "RMSMappingQuality"]
if include_baseqranksum:
anns += ["BaseQualityRankSumTest"]
# Some annotations not working correctly with external datasets and GATK 3
if gatk_input or broad_runner.gatk_type() == "gatk4":
anns += ["FisherStrand"]
if broad_runner.gatk_type() == "gatk4":
anns += ["MappingQuality"]
else:
anns += ["GCContent", "HaplotypeScore", "HomopolymerRun"]
if include_depth:
anns += ["DepthPerAlleleBySample"]
if broad_runner.gatk_type() in ["restricted", "gatk4"]:
anns += ["Coverage"]
else:
anns += ["DepthOfCoverage"]
return anns | python | def get_gatk_annotations(config, include_depth=True, include_baseqranksum=True,
gatk_input=True):
broad_runner = broad.runner_from_config(config)
anns = ["MappingQualityRankSumTest", "MappingQualityZero",
"QualByDepth", "ReadPosRankSumTest", "RMSMappingQuality"]
if include_baseqranksum:
anns += ["BaseQualityRankSumTest"]
# Some annotations not working correctly with external datasets and GATK 3
if gatk_input or broad_runner.gatk_type() == "gatk4":
anns += ["FisherStrand"]
if broad_runner.gatk_type() == "gatk4":
anns += ["MappingQuality"]
else:
anns += ["GCContent", "HaplotypeScore", "HomopolymerRun"]
if include_depth:
anns += ["DepthPerAlleleBySample"]
if broad_runner.gatk_type() in ["restricted", "gatk4"]:
anns += ["Coverage"]
else:
anns += ["DepthOfCoverage"]
return anns | [
"def",
"get_gatk_annotations",
"(",
"config",
",",
"include_depth",
"=",
"True",
",",
"include_baseqranksum",
"=",
"True",
",",
"gatk_input",
"=",
"True",
")",
":",
"broad_runner",
"=",
"broad",
".",
"runner_from_config",
"(",
"config",
")",
"anns",
"=",
"[",
... | Retrieve annotations to use for GATK VariantAnnotator.
If include_depth is false, we'll skip annotating DP. Since GATK downsamples
this will undercount on high depth sequencing and the standard outputs
from the original callers may be preferable.
BaseQRankSum can cause issues with some MuTect2 and other runs, so we
provide option to skip it. | [
"Retrieve",
"annotations",
"to",
"use",
"for",
"GATK",
"VariantAnnotator",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L17-L46 |
237,146 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | finalize_vcf | def finalize_vcf(in_file, variantcaller, items):
"""Perform cleanup and dbSNP annotation of the final VCF.
- Adds contigs to header for bcftools compatibility
- adds sample information for tumor/normal
"""
out_file = "%s-annotated%s" % utils.splitext_plus(in_file)
if not utils.file_uptodate(out_file, in_file):
header_cl = _add_vcf_header_sample_cl(in_file, items, out_file)
contig_cl = _add_contig_cl(in_file, items, out_file)
cls = [x for x in (contig_cl, header_cl) if x]
if cls:
post_cl = " | ".join(cls) + " | "
else:
post_cl = None
dbsnp_file = tz.get_in(("genome_resources", "variation", "dbsnp"), items[0])
if dbsnp_file:
out_file = _add_dbsnp(in_file, dbsnp_file, items[0], out_file, post_cl)
if utils.file_exists(out_file):
return vcfutils.bgzip_and_index(out_file, items[0]["config"])
else:
return in_file | python | def finalize_vcf(in_file, variantcaller, items):
out_file = "%s-annotated%s" % utils.splitext_plus(in_file)
if not utils.file_uptodate(out_file, in_file):
header_cl = _add_vcf_header_sample_cl(in_file, items, out_file)
contig_cl = _add_contig_cl(in_file, items, out_file)
cls = [x for x in (contig_cl, header_cl) if x]
if cls:
post_cl = " | ".join(cls) + " | "
else:
post_cl = None
dbsnp_file = tz.get_in(("genome_resources", "variation", "dbsnp"), items[0])
if dbsnp_file:
out_file = _add_dbsnp(in_file, dbsnp_file, items[0], out_file, post_cl)
if utils.file_exists(out_file):
return vcfutils.bgzip_and_index(out_file, items[0]["config"])
else:
return in_file | [
"def",
"finalize_vcf",
"(",
"in_file",
",",
"variantcaller",
",",
"items",
")",
":",
"out_file",
"=",
"\"%s-annotated%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"in_file",
... | Perform cleanup and dbSNP annotation of the final VCF.
- Adds contigs to header for bcftools compatibility
- adds sample information for tumor/normal | [
"Perform",
"cleanup",
"and",
"dbSNP",
"annotation",
"of",
"the",
"final",
"VCF",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L48-L69 |
237,147 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | _add_vcf_header_sample_cl | def _add_vcf_header_sample_cl(in_file, items, base_file):
"""Add phenotype information to a VCF header.
Encode tumor/normal relationships in VCF header.
Could also eventually handle more complicated pedigree information if useful.
"""
paired = vcfutils.get_paired(items)
if paired:
toadd = ["##SAMPLE=<ID=%s,Genomes=Tumor>" % paired.tumor_name]
if paired.normal_name:
toadd.append("##SAMPLE=<ID=%s,Genomes=Germline>" % paired.normal_name)
toadd.append("##PEDIGREE=<Derived=%s,Original=%s>" % (paired.tumor_name, paired.normal_name))
new_header = _update_header(in_file, base_file, toadd, _fix_generic_tn_names(paired))
if vcfutils.vcf_has_variants(in_file):
cmd = "bcftools reheader -h {new_header} | bcftools view "
return cmd.format(**locals()) | python | def _add_vcf_header_sample_cl(in_file, items, base_file):
paired = vcfutils.get_paired(items)
if paired:
toadd = ["##SAMPLE=<ID=%s,Genomes=Tumor>" % paired.tumor_name]
if paired.normal_name:
toadd.append("##SAMPLE=<ID=%s,Genomes=Germline>" % paired.normal_name)
toadd.append("##PEDIGREE=<Derived=%s,Original=%s>" % (paired.tumor_name, paired.normal_name))
new_header = _update_header(in_file, base_file, toadd, _fix_generic_tn_names(paired))
if vcfutils.vcf_has_variants(in_file):
cmd = "bcftools reheader -h {new_header} | bcftools view "
return cmd.format(**locals()) | [
"def",
"_add_vcf_header_sample_cl",
"(",
"in_file",
",",
"items",
",",
"base_file",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired",
"(",
"items",
")",
"if",
"paired",
":",
"toadd",
"=",
"[",
"\"##SAMPLE=<ID=%s,Genomes=Tumor>\"",
"%",
"paired",
".",
"tu... | Add phenotype information to a VCF header.
Encode tumor/normal relationships in VCF header.
Could also eventually handle more complicated pedigree information if useful. | [
"Add",
"phenotype",
"information",
"to",
"a",
"VCF",
"header",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L98-L113 |
237,148 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | _update_header | def _update_header(orig_vcf, base_file, new_lines, chrom_process_fn=None):
"""Fix header with additional lines and remapping of generic sample names.
"""
new_header = "%s-sample_header.txt" % utils.splitext_plus(base_file)[0]
with open(new_header, "w") as out_handle:
chrom_line = None
with utils.open_gzipsafe(orig_vcf) as in_handle:
for line in in_handle:
if line.startswith("##"):
out_handle.write(line)
else:
chrom_line = line
break
assert chrom_line is not None
for line in new_lines:
out_handle.write(line + "\n")
if chrom_process_fn:
chrom_line = chrom_process_fn(chrom_line)
out_handle.write(chrom_line)
return new_header | python | def _update_header(orig_vcf, base_file, new_lines, chrom_process_fn=None):
new_header = "%s-sample_header.txt" % utils.splitext_plus(base_file)[0]
with open(new_header, "w") as out_handle:
chrom_line = None
with utils.open_gzipsafe(orig_vcf) as in_handle:
for line in in_handle:
if line.startswith("##"):
out_handle.write(line)
else:
chrom_line = line
break
assert chrom_line is not None
for line in new_lines:
out_handle.write(line + "\n")
if chrom_process_fn:
chrom_line = chrom_process_fn(chrom_line)
out_handle.write(chrom_line)
return new_header | [
"def",
"_update_header",
"(",
"orig_vcf",
",",
"base_file",
",",
"new_lines",
",",
"chrom_process_fn",
"=",
"None",
")",
":",
"new_header",
"=",
"\"%s-sample_header.txt\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"base_file",
")",
"[",
"0",
"]",
"with",
"open... | Fix header with additional lines and remapping of generic sample names. | [
"Fix",
"header",
"with",
"additional",
"lines",
"and",
"remapping",
"of",
"generic",
"sample",
"names",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L115-L134 |
237,149 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | _add_dbsnp | def _add_dbsnp(orig_file, dbsnp_file, data, out_file=None, post_cl=None):
"""Annotate a VCF file with dbSNP.
vcfanno has flexible matching for NON_REF gVCF positions, matching
at position and REF allele, matching ALT NON_REF as a wildcard.
"""
orig_file = vcfutils.bgzip_and_index(orig_file, data["config"])
if out_file is None:
out_file = "%s-wdbsnp.vcf.gz" % utils.splitext_plus(orig_file)[0]
if not utils.file_uptodate(out_file, orig_file):
with file_transaction(data, out_file) as tx_out_file:
conf_file = os.path.join(os.path.dirname(out_file), "dbsnp.conf")
with open(conf_file, "w") as out_handle:
out_handle.write(_DBSNP_TEMPLATE % os.path.normpath(os.path.join(dd.get_work_dir(data), dbsnp_file)))
if not post_cl: post_cl = ""
cores = dd.get_num_cores(data)
cmd = ("vcfanno -p {cores} {conf_file} {orig_file} | {post_cl} "
"bgzip -c > {tx_out_file}")
do.run(cmd.format(**locals()), "Annotate with dbSNP")
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def _add_dbsnp(orig_file, dbsnp_file, data, out_file=None, post_cl=None):
orig_file = vcfutils.bgzip_and_index(orig_file, data["config"])
if out_file is None:
out_file = "%s-wdbsnp.vcf.gz" % utils.splitext_plus(orig_file)[0]
if not utils.file_uptodate(out_file, orig_file):
with file_transaction(data, out_file) as tx_out_file:
conf_file = os.path.join(os.path.dirname(out_file), "dbsnp.conf")
with open(conf_file, "w") as out_handle:
out_handle.write(_DBSNP_TEMPLATE % os.path.normpath(os.path.join(dd.get_work_dir(data), dbsnp_file)))
if not post_cl: post_cl = ""
cores = dd.get_num_cores(data)
cmd = ("vcfanno -p {cores} {conf_file} {orig_file} | {post_cl} "
"bgzip -c > {tx_out_file}")
do.run(cmd.format(**locals()), "Annotate with dbSNP")
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"_add_dbsnp",
"(",
"orig_file",
",",
"dbsnp_file",
",",
"data",
",",
"out_file",
"=",
"None",
",",
"post_cl",
"=",
"None",
")",
":",
"orig_file",
"=",
"vcfutils",
".",
"bgzip_and_index",
"(",
"orig_file",
",",
"data",
"[",
"\"config\"",
"]",
")",
... | Annotate a VCF file with dbSNP.
vcfanno has flexible matching for NON_REF gVCF positions, matching
at position and REF allele, matching ALT NON_REF as a wildcard. | [
"Annotate",
"a",
"VCF",
"file",
"with",
"dbSNP",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L154-L173 |
237,150 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | get_context_files | def get_context_files(data):
"""Retrieve pre-installed annotation files for annotating genome context.
"""
ref_file = dd.get_ref_file(data)
all_files = []
for ext in [".bed.gz"]:
all_files += sorted(glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
"coverage", "problem_regions", "*",
"*%s" % ext))))
return sorted(all_files) | python | def get_context_files(data):
ref_file = dd.get_ref_file(data)
all_files = []
for ext in [".bed.gz"]:
all_files += sorted(glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
"coverage", "problem_regions", "*",
"*%s" % ext))))
return sorted(all_files) | [
"def",
"get_context_files",
"(",
"data",
")",
":",
"ref_file",
"=",
"dd",
".",
"get_ref_file",
"(",
"data",
")",
"all_files",
"=",
"[",
"]",
"for",
"ext",
"in",
"[",
"\".bed.gz\"",
"]",
":",
"all_files",
"+=",
"sorted",
"(",
"glob",
".",
"glob",
"(",
... | Retrieve pre-installed annotation files for annotating genome context. | [
"Retrieve",
"pre",
"-",
"installed",
"annotation",
"files",
"for",
"annotating",
"genome",
"context",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L175-L184 |
237,151 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | add_genome_context | def add_genome_context(orig_file, data):
"""Annotate a file with annotations of genome context using vcfanno.
"""
out_file = "%s-context.vcf.gz" % utils.splitext_plus(orig_file)[0]
if not utils.file_uptodate(out_file, orig_file):
with file_transaction(data, out_file) as tx_out_file:
config_file = "%s.toml" % (utils.splitext_plus(tx_out_file)[0])
with open(config_file, "w") as out_handle:
all_names = []
for fname in dd.get_genome_context_files(data):
bt = pybedtools.BedTool(fname)
if bt.field_count() >= 4:
d, base = os.path.split(fname)
_, prefix = os.path.split(d)
name = "%s_%s" % (prefix, utils.splitext_plus(base)[0])
out_handle.write("[[annotation]]\n")
out_handle.write('file = "%s"\n' % fname)
out_handle.write("columns = [4]\n")
out_handle.write('names = ["%s"]\n' % name)
out_handle.write('ops = ["uniq"]\n')
all_names.append(name)
out_handle.write("[[postannotation]]\n")
out_handle.write("fields = [%s]\n" % (", ".join(['"%s"' % n for n in all_names])))
out_handle.write('name = "genome_context"\n')
out_handle.write('op = "concat"\n')
out_handle.write('type = "String"\n')
cmd = "vcfanno {config_file} {orig_file} | bgzip -c > {tx_out_file}"
do.run(cmd.format(**locals()), "Annotate with problem annotations", data)
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def add_genome_context(orig_file, data):
out_file = "%s-context.vcf.gz" % utils.splitext_plus(orig_file)[0]
if not utils.file_uptodate(out_file, orig_file):
with file_transaction(data, out_file) as tx_out_file:
config_file = "%s.toml" % (utils.splitext_plus(tx_out_file)[0])
with open(config_file, "w") as out_handle:
all_names = []
for fname in dd.get_genome_context_files(data):
bt = pybedtools.BedTool(fname)
if bt.field_count() >= 4:
d, base = os.path.split(fname)
_, prefix = os.path.split(d)
name = "%s_%s" % (prefix, utils.splitext_plus(base)[0])
out_handle.write("[[annotation]]\n")
out_handle.write('file = "%s"\n' % fname)
out_handle.write("columns = [4]\n")
out_handle.write('names = ["%s"]\n' % name)
out_handle.write('ops = ["uniq"]\n')
all_names.append(name)
out_handle.write("[[postannotation]]\n")
out_handle.write("fields = [%s]\n" % (", ".join(['"%s"' % n for n in all_names])))
out_handle.write('name = "genome_context"\n')
out_handle.write('op = "concat"\n')
out_handle.write('type = "String"\n')
cmd = "vcfanno {config_file} {orig_file} | bgzip -c > {tx_out_file}"
do.run(cmd.format(**locals()), "Annotate with problem annotations", data)
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"add_genome_context",
"(",
"orig_file",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-context.vcf.gz\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"orig_file",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"orig_... | Annotate a file with annotations of genome context using vcfanno. | [
"Annotate",
"a",
"file",
"with",
"annotations",
"of",
"genome",
"context",
"using",
"vcfanno",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L186-L214 |
237,152 | bcbio/bcbio-nextgen | bcbio/illumina/demultiplex.py | _submit_and_wait | def _submit_and_wait(cmd, cores, config, output_dir):
"""Submit command with batch script specified in configuration, wait until finished
"""
batch_script = "submit_bcl2fastq.sh"
if not os.path.exists(batch_script + ".finished"):
if os.path.exists(batch_script + ".failed"):
os.remove(batch_script + ".failed")
with open(batch_script, "w") as out_handle:
out_handle.write(config["process"]["bcl2fastq_batch"].format(
cores=cores, bcl2fastq_cmd=" ".join(cmd), batch_script=batch_script))
submit_cmd = utils.get_in(config, ("process", "submit_cmd"))
subprocess.check_call(submit_cmd.format(batch_script=batch_script), shell=True)
# wait until finished or failure checkpoint file
while 1:
if os.path.exists(batch_script + ".finished"):
break
if os.path.exists(batch_script + ".failed"):
raise ValueError("bcl2fastq batch script failed: %s" %
os.path.join(output_dir, batch_script))
time.sleep(5) | python | def _submit_and_wait(cmd, cores, config, output_dir):
batch_script = "submit_bcl2fastq.sh"
if not os.path.exists(batch_script + ".finished"):
if os.path.exists(batch_script + ".failed"):
os.remove(batch_script + ".failed")
with open(batch_script, "w") as out_handle:
out_handle.write(config["process"]["bcl2fastq_batch"].format(
cores=cores, bcl2fastq_cmd=" ".join(cmd), batch_script=batch_script))
submit_cmd = utils.get_in(config, ("process", "submit_cmd"))
subprocess.check_call(submit_cmd.format(batch_script=batch_script), shell=True)
# wait until finished or failure checkpoint file
while 1:
if os.path.exists(batch_script + ".finished"):
break
if os.path.exists(batch_script + ".failed"):
raise ValueError("bcl2fastq batch script failed: %s" %
os.path.join(output_dir, batch_script))
time.sleep(5) | [
"def",
"_submit_and_wait",
"(",
"cmd",
",",
"cores",
",",
"config",
",",
"output_dir",
")",
":",
"batch_script",
"=",
"\"submit_bcl2fastq.sh\"",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"batch_script",
"+",
"\".finished\"",
")",
":",
"if",
"os",
... | Submit command with batch script specified in configuration, wait until finished | [
"Submit",
"command",
"with",
"batch",
"script",
"specified",
"in",
"configuration",
"wait",
"until",
"finished"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/demultiplex.py#L32-L51 |
237,153 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _prep_items_from_base | def _prep_items_from_base(base, in_files, metadata, separators, force_single=False):
"""Prepare a set of configuration items for input files.
"""
details = []
in_files = _expand_dirs(in_files, KNOWN_EXTS)
in_files = _expand_wildcards(in_files)
ext_groups = collections.defaultdict(list)
for ext, files in itertools.groupby(
in_files, lambda x: KNOWN_EXTS.get(utils.splitext_plus(x)[-1].lower())):
ext_groups[ext].extend(list(files))
for ext, files in ext_groups.items():
if ext == "bam":
for f in files:
details.append(_prep_bam_input(f, base))
elif ext in ["fastq", "fq", "fasta"]:
files, glob_files = _find_glob_matches(files, metadata)
for fs in glob_files:
details.append(_prep_fastq_input(fs, base))
for fs in fastq.combine_pairs(files, force_single, separators=separators):
details.append(_prep_fastq_input(fs, base))
elif ext in ["vcf"]:
for f in files:
details.append(_prep_vcf_input(f, base))
else:
print("Ignoring unexpected input file types %s: %s" % (ext, list(files)))
return details | python | def _prep_items_from_base(base, in_files, metadata, separators, force_single=False):
details = []
in_files = _expand_dirs(in_files, KNOWN_EXTS)
in_files = _expand_wildcards(in_files)
ext_groups = collections.defaultdict(list)
for ext, files in itertools.groupby(
in_files, lambda x: KNOWN_EXTS.get(utils.splitext_plus(x)[-1].lower())):
ext_groups[ext].extend(list(files))
for ext, files in ext_groups.items():
if ext == "bam":
for f in files:
details.append(_prep_bam_input(f, base))
elif ext in ["fastq", "fq", "fasta"]:
files, glob_files = _find_glob_matches(files, metadata)
for fs in glob_files:
details.append(_prep_fastq_input(fs, base))
for fs in fastq.combine_pairs(files, force_single, separators=separators):
details.append(_prep_fastq_input(fs, base))
elif ext in ["vcf"]:
for f in files:
details.append(_prep_vcf_input(f, base))
else:
print("Ignoring unexpected input file types %s: %s" % (ext, list(files)))
return details | [
"def",
"_prep_items_from_base",
"(",
"base",
",",
"in_files",
",",
"metadata",
",",
"separators",
",",
"force_single",
"=",
"False",
")",
":",
"details",
"=",
"[",
"]",
"in_files",
"=",
"_expand_dirs",
"(",
"in_files",
",",
"KNOWN_EXTS",
")",
"in_files",
"="... | Prepare a set of configuration items for input files. | [
"Prepare",
"a",
"set",
"of",
"configuration",
"items",
"for",
"input",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L100-L126 |
237,154 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _find_glob_matches | def _find_glob_matches(in_files, metadata):
"""Group files that match by globs for merging, rather than by explicit pairs.
"""
reg_files = copy.deepcopy(in_files)
glob_files = []
for glob_search in [x for x in metadata.keys() if "*" in x]:
cur = []
for fname in in_files:
if fnmatch.fnmatch(fname, "*/%s" % glob_search):
cur.append(fname)
reg_files.remove(fname)
assert cur, "Did not find file matches for %s" % glob_search
glob_files.append(cur)
return reg_files, glob_files | python | def _find_glob_matches(in_files, metadata):
reg_files = copy.deepcopy(in_files)
glob_files = []
for glob_search in [x for x in metadata.keys() if "*" in x]:
cur = []
for fname in in_files:
if fnmatch.fnmatch(fname, "*/%s" % glob_search):
cur.append(fname)
reg_files.remove(fname)
assert cur, "Did not find file matches for %s" % glob_search
glob_files.append(cur)
return reg_files, glob_files | [
"def",
"_find_glob_matches",
"(",
"in_files",
",",
"metadata",
")",
":",
"reg_files",
"=",
"copy",
".",
"deepcopy",
"(",
"in_files",
")",
"glob_files",
"=",
"[",
"]",
"for",
"glob_search",
"in",
"[",
"x",
"for",
"x",
"in",
"metadata",
".",
"keys",
"(",
... | Group files that match by globs for merging, rather than by explicit pairs. | [
"Group",
"files",
"that",
"match",
"by",
"globs",
"for",
"merging",
"rather",
"than",
"by",
"explicit",
"pairs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L128-L141 |
237,155 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | name_to_config | def name_to_config(template):
"""Read template file into a dictionary to use as base for all samples.
Handles well-known template names, pulled from GitHub repository and local
files.
"""
if objectstore.is_remote(template):
with objectstore.open_file(template) as in_handle:
config = yaml.safe_load(in_handle)
with objectstore.open_file(template) as in_handle:
txt_config = in_handle.read()
elif os.path.isfile(template):
if template.endswith(".csv"):
raise ValueError("Expected YAML file for template and found CSV, are arguments switched? %s" % template)
with open(template) as in_handle:
txt_config = in_handle.read()
with open(template) as in_handle:
config = yaml.safe_load(in_handle)
else:
base_url = "https://raw.github.com/bcbio/bcbio-nextgen/master/config/templates/%s.yaml"
try:
with contextlib.closing(urllib.request.urlopen(base_url % template)) as in_handle:
txt_config = in_handle.read().decode()
with contextlib.closing(urllib.request.urlopen(base_url % template)) as in_handle:
config = yaml.safe_load(in_handle)
except (urllib.error.HTTPError, urllib.error.URLError):
raise ValueError("Could not find template '%s' locally or in standard templates on GitHub"
% template)
return config, txt_config | python | def name_to_config(template):
if objectstore.is_remote(template):
with objectstore.open_file(template) as in_handle:
config = yaml.safe_load(in_handle)
with objectstore.open_file(template) as in_handle:
txt_config = in_handle.read()
elif os.path.isfile(template):
if template.endswith(".csv"):
raise ValueError("Expected YAML file for template and found CSV, are arguments switched? %s" % template)
with open(template) as in_handle:
txt_config = in_handle.read()
with open(template) as in_handle:
config = yaml.safe_load(in_handle)
else:
base_url = "https://raw.github.com/bcbio/bcbio-nextgen/master/config/templates/%s.yaml"
try:
with contextlib.closing(urllib.request.urlopen(base_url % template)) as in_handle:
txt_config = in_handle.read().decode()
with contextlib.closing(urllib.request.urlopen(base_url % template)) as in_handle:
config = yaml.safe_load(in_handle)
except (urllib.error.HTTPError, urllib.error.URLError):
raise ValueError("Could not find template '%s' locally or in standard templates on GitHub"
% template)
return config, txt_config | [
"def",
"name_to_config",
"(",
"template",
")",
":",
"if",
"objectstore",
".",
"is_remote",
"(",
"template",
")",
":",
"with",
"objectstore",
".",
"open_file",
"(",
"template",
")",
"as",
"in_handle",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"in_h... | Read template file into a dictionary to use as base for all samples.
Handles well-known template names, pulled from GitHub repository and local
files. | [
"Read",
"template",
"file",
"into",
"a",
"dictionary",
"to",
"use",
"as",
"base",
"for",
"all",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L168-L196 |
237,156 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _write_config_file | def _write_config_file(items, global_vars, template, project_name, out_dir,
remotes):
"""Write configuration file, adding required top level attributes.
"""
config_dir = utils.safe_makedir(os.path.join(out_dir, "config"))
out_config_file = os.path.join(config_dir, "%s.yaml" % project_name)
out = {"fc_name": project_name,
"upload": {"dir": "../final"},
"details": items}
if remotes.get("base"):
r_base = objectstore.parse_remote(remotes.get("base"))
out["upload"]["method"] = r_base.store
out["upload"]["bucket"] = r_base.bucket
out["upload"]["folder"] = os.path.join(r_base.key, "final") if r_base.key else "final"
if r_base.region:
out["upload"]["region"] = r_base.region
if global_vars:
out["globals"] = global_vars
for k, v in template.items():
if k not in ["details"]:
out[k] = v
if os.path.exists(out_config_file):
shutil.move(out_config_file,
out_config_file + ".bak%s" % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
with open(out_config_file, "w") as out_handle:
yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
return out_config_file | python | def _write_config_file(items, global_vars, template, project_name, out_dir,
remotes):
config_dir = utils.safe_makedir(os.path.join(out_dir, "config"))
out_config_file = os.path.join(config_dir, "%s.yaml" % project_name)
out = {"fc_name": project_name,
"upload": {"dir": "../final"},
"details": items}
if remotes.get("base"):
r_base = objectstore.parse_remote(remotes.get("base"))
out["upload"]["method"] = r_base.store
out["upload"]["bucket"] = r_base.bucket
out["upload"]["folder"] = os.path.join(r_base.key, "final") if r_base.key else "final"
if r_base.region:
out["upload"]["region"] = r_base.region
if global_vars:
out["globals"] = global_vars
for k, v in template.items():
if k not in ["details"]:
out[k] = v
if os.path.exists(out_config_file):
shutil.move(out_config_file,
out_config_file + ".bak%s" % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
with open(out_config_file, "w") as out_handle:
yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
return out_config_file | [
"def",
"_write_config_file",
"(",
"items",
",",
"global_vars",
",",
"template",
",",
"project_name",
",",
"out_dir",
",",
"remotes",
")",
":",
"config_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"\"con... | Write configuration file, adding required top level attributes. | [
"Write",
"configuration",
"file",
"adding",
"required",
"top",
"level",
"attributes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L205-L231 |
237,157 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _set_global_vars | def _set_global_vars(metadata):
"""Identify files used multiple times in metadata and replace with global variables
"""
fnames = collections.defaultdict(list)
for sample in metadata.keys():
for k, v in metadata[sample].items():
if isinstance(v, six.string_types) and os.path.isfile(v):
v = _expand_file(v)
metadata[sample][k] = v
fnames[v].append(k)
global_vars = {}
# Skip global vars -- more confusing than useful
# loc_counts = collections.defaultdict(int)
# global_var_sub = {}
# for fname, locs in fnames.items():
# if len(locs) > 1:
# loc_counts[locs[0]] += 1
# name = "%s%s" % (locs[0], loc_counts[locs[0]])
# global_var_sub[fname] = name
# global_vars[name] = fname
# for sample in metadata.keys():
# for k, v in metadata[sample].items():
# if isinstance(v, six.string_types) and v in global_var_sub:
# metadata[sample][k] = global_var_sub[v]
return metadata, global_vars | python | def _set_global_vars(metadata):
fnames = collections.defaultdict(list)
for sample in metadata.keys():
for k, v in metadata[sample].items():
if isinstance(v, six.string_types) and os.path.isfile(v):
v = _expand_file(v)
metadata[sample][k] = v
fnames[v].append(k)
global_vars = {}
# Skip global vars -- more confusing than useful
# loc_counts = collections.defaultdict(int)
# global_var_sub = {}
# for fname, locs in fnames.items():
# if len(locs) > 1:
# loc_counts[locs[0]] += 1
# name = "%s%s" % (locs[0], loc_counts[locs[0]])
# global_var_sub[fname] = name
# global_vars[name] = fname
# for sample in metadata.keys():
# for k, v in metadata[sample].items():
# if isinstance(v, six.string_types) and v in global_var_sub:
# metadata[sample][k] = global_var_sub[v]
return metadata, global_vars | [
"def",
"_set_global_vars",
"(",
"metadata",
")",
":",
"fnames",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"sample",
"in",
"metadata",
".",
"keys",
"(",
")",
":",
"for",
"k",
",",
"v",
"in",
"metadata",
"[",
"sample",
"]",
".",
... | Identify files used multiple times in metadata and replace with global variables | [
"Identify",
"files",
"used",
"multiple",
"times",
"in",
"metadata",
"and",
"replace",
"with",
"global",
"variables"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L238-L262 |
237,158 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _clean_string | def _clean_string(v, sinfo):
"""Test for and clean unicode present in template CSVs.
"""
if isinstance(v, (list, tuple)):
return [_clean_string(x, sinfo) for x in v]
else:
assert isinstance(v, six.string_types), v
try:
if hasattr(v, "decode"):
return str(v.decode("ascii"))
else:
return str(v.encode("ascii").decode("ascii"))
except UnicodeDecodeError as msg:
raise ValueError("Found unicode character in template CSV line %s:\n%s" % (sinfo, str(msg))) | python | def _clean_string(v, sinfo):
if isinstance(v, (list, tuple)):
return [_clean_string(x, sinfo) for x in v]
else:
assert isinstance(v, six.string_types), v
try:
if hasattr(v, "decode"):
return str(v.decode("ascii"))
else:
return str(v.encode("ascii").decode("ascii"))
except UnicodeDecodeError as msg:
raise ValueError("Found unicode character in template CSV line %s:\n%s" % (sinfo, str(msg))) | [
"def",
"_clean_string",
"(",
"v",
",",
"sinfo",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"_clean_string",
"(",
"x",
",",
"sinfo",
")",
"for",
"x",
"in",
"v",
"]",
"else",
":",
"assert",... | Test for and clean unicode present in template CSVs. | [
"Test",
"for",
"and",
"clean",
"unicode",
"present",
"in",
"template",
"CSVs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L264-L277 |
237,159 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _parse_metadata | def _parse_metadata(in_handle):
"""Reads metadata from a simple CSV structured input file.
samplename,batch,phenotype
ERR256785,batch1,normal
"""
metadata = {}
reader = csv.reader(in_handle)
while 1:
header = next(reader)
if not header[0].startswith("#"):
break
keys = [x.strip() for x in header[1:]]
for sinfo in (x for x in reader if x and not x[0].startswith("#")):
sinfo = [_strip_and_convert_lists(x) for x in sinfo]
sample = sinfo[0]
if isinstance(sample, list):
sample = tuple(sample)
# sanity check to avoid duplicate rows
if sample in metadata:
raise ValueError("Sample %s present multiple times in metadata file.\n"
"If you need to specify multiple attributes as a list "
"use a semi-colon to separate them on a single line.\n"
"https://bcbio-nextgen.readthedocs.org/en/latest/"
"contents/configuration.html#automated-sample-configuration\n"
"Duplicate line is %s" % (sample, sinfo))
vals = [_clean_string(v, sinfo) for v in sinfo[1:]]
metadata[sample] = dict(zip(keys, vals))
metadata, global_vars = _set_global_vars(metadata)
return metadata, global_vars | python | def _parse_metadata(in_handle):
metadata = {}
reader = csv.reader(in_handle)
while 1:
header = next(reader)
if not header[0].startswith("#"):
break
keys = [x.strip() for x in header[1:]]
for sinfo in (x for x in reader if x and not x[0].startswith("#")):
sinfo = [_strip_and_convert_lists(x) for x in sinfo]
sample = sinfo[0]
if isinstance(sample, list):
sample = tuple(sample)
# sanity check to avoid duplicate rows
if sample in metadata:
raise ValueError("Sample %s present multiple times in metadata file.\n"
"If you need to specify multiple attributes as a list "
"use a semi-colon to separate them on a single line.\n"
"https://bcbio-nextgen.readthedocs.org/en/latest/"
"contents/configuration.html#automated-sample-configuration\n"
"Duplicate line is %s" % (sample, sinfo))
vals = [_clean_string(v, sinfo) for v in sinfo[1:]]
metadata[sample] = dict(zip(keys, vals))
metadata, global_vars = _set_global_vars(metadata)
return metadata, global_vars | [
"def",
"_parse_metadata",
"(",
"in_handle",
")",
":",
"metadata",
"=",
"{",
"}",
"reader",
"=",
"csv",
".",
"reader",
"(",
"in_handle",
")",
"while",
"1",
":",
"header",
"=",
"next",
"(",
"reader",
")",
"if",
"not",
"header",
"[",
"0",
"]",
".",
"s... | Reads metadata from a simple CSV structured input file.
samplename,batch,phenotype
ERR256785,batch1,normal | [
"Reads",
"metadata",
"from",
"a",
"simple",
"CSV",
"structured",
"input",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L279-L308 |
237,160 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _pname_and_metadata | def _pname_and_metadata(in_file):
"""Retrieve metadata and project name from the input metadata CSV file.
Uses the input file name for the project name and for back compatibility,
accepts the project name as an input, providing no metadata.
"""
if os.path.isfile(in_file):
with open(in_file) as in_handle:
md, global_vars = _parse_metadata(in_handle)
base = os.path.splitext(os.path.basename(in_file))[0]
md_file = in_file
elif objectstore.is_remote(in_file):
with objectstore.open_file(in_file) as in_handle:
md, global_vars = _parse_metadata(in_handle)
base = os.path.splitext(os.path.basename(in_file))[0]
md_file = None
else:
if in_file.endswith(".csv"):
raise ValueError("Did not find input metadata file: %s" % in_file)
base, md, global_vars = _safe_name(os.path.splitext(os.path.basename(in_file))[0]), {}, {}
md_file = None
return _safe_name(base), md, global_vars, md_file | python | def _pname_and_metadata(in_file):
if os.path.isfile(in_file):
with open(in_file) as in_handle:
md, global_vars = _parse_metadata(in_handle)
base = os.path.splitext(os.path.basename(in_file))[0]
md_file = in_file
elif objectstore.is_remote(in_file):
with objectstore.open_file(in_file) as in_handle:
md, global_vars = _parse_metadata(in_handle)
base = os.path.splitext(os.path.basename(in_file))[0]
md_file = None
else:
if in_file.endswith(".csv"):
raise ValueError("Did not find input metadata file: %s" % in_file)
base, md, global_vars = _safe_name(os.path.splitext(os.path.basename(in_file))[0]), {}, {}
md_file = None
return _safe_name(base), md, global_vars, md_file | [
"def",
"_pname_and_metadata",
"(",
"in_file",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"in_file",
")",
":",
"with",
"open",
"(",
"in_file",
")",
"as",
"in_handle",
":",
"md",
",",
"global_vars",
"=",
"_parse_metadata",
"(",
"in_handle",
")"... | Retrieve metadata and project name from the input metadata CSV file.
Uses the input file name for the project name and for back compatibility,
accepts the project name as an input, providing no metadata. | [
"Retrieve",
"metadata",
"and",
"project",
"name",
"from",
"the",
"input",
"metadata",
"CSV",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L318-L339 |
237,161 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _handle_special_yaml_cases | def _handle_special_yaml_cases(v):
"""Handle values that pass integer, boolean, list or dictionary values.
"""
if "::" in v:
out = {}
for part in v.split("::"):
k_part, v_part = part.split(":")
out[k_part] = v_part.split(";")
v = out
elif ";" in v:
# split lists and remove accidental empty values
v = [x for x in v.split(";") if x != ""]
elif isinstance(v, list):
v = v
else:
try:
v = int(v)
except ValueError:
if v.lower() == "true":
v = True
elif v.lower() == "false":
v = False
return v | python | def _handle_special_yaml_cases(v):
if "::" in v:
out = {}
for part in v.split("::"):
k_part, v_part = part.split(":")
out[k_part] = v_part.split(";")
v = out
elif ";" in v:
# split lists and remove accidental empty values
v = [x for x in v.split(";") if x != ""]
elif isinstance(v, list):
v = v
else:
try:
v = int(v)
except ValueError:
if v.lower() == "true":
v = True
elif v.lower() == "false":
v = False
return v | [
"def",
"_handle_special_yaml_cases",
"(",
"v",
")",
":",
"if",
"\"::\"",
"in",
"v",
":",
"out",
"=",
"{",
"}",
"for",
"part",
"in",
"v",
".",
"split",
"(",
"\"::\"",
")",
":",
"k_part",
",",
"v_part",
"=",
"part",
".",
"split",
"(",
"\":\"",
")",
... | Handle values that pass integer, boolean, list or dictionary values. | [
"Handle",
"values",
"that",
"pass",
"integer",
"boolean",
"list",
"or",
"dictionary",
"values",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L341-L363 |
237,162 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _add_ped_metadata | def _add_ped_metadata(name, metadata):
"""Add standard PED file attributes into metadata if not present.
http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped
"""
ignore = set(["-9", "undefined", "unknown", "."])
def _ped_mapping(x, valmap):
try:
x = int(x)
except ValueError:
x = -1
for k, v in valmap.items():
if k == x:
return v
return None
def _ped_to_gender(x):
return _ped_mapping(x, {1: "male", 2: "female"})
def _ped_to_phenotype(x):
known_phenotypes = set(["unaffected", "affected", "tumor", "normal"])
if x in known_phenotypes:
return x
else:
return _ped_mapping(x, {1: "unaffected", 2: "affected"})
def _ped_to_batch(x):
if x not in ignore and x != "0":
return x
with open(metadata["ped"]) as in_handle:
for line in in_handle:
parts = line.split("\t")[:6]
if parts[1] == str(name):
for index, key, convert_fn in [(4, "sex", _ped_to_gender), (0, "batch", _ped_to_batch),
(5, "phenotype", _ped_to_phenotype)]:
val = convert_fn(parts[index])
if val is not None and key not in metadata:
metadata[key] = val
break
return metadata | python | def _add_ped_metadata(name, metadata):
ignore = set(["-9", "undefined", "unknown", "."])
def _ped_mapping(x, valmap):
try:
x = int(x)
except ValueError:
x = -1
for k, v in valmap.items():
if k == x:
return v
return None
def _ped_to_gender(x):
return _ped_mapping(x, {1: "male", 2: "female"})
def _ped_to_phenotype(x):
known_phenotypes = set(["unaffected", "affected", "tumor", "normal"])
if x in known_phenotypes:
return x
else:
return _ped_mapping(x, {1: "unaffected", 2: "affected"})
def _ped_to_batch(x):
if x not in ignore and x != "0":
return x
with open(metadata["ped"]) as in_handle:
for line in in_handle:
parts = line.split("\t")[:6]
if parts[1] == str(name):
for index, key, convert_fn in [(4, "sex", _ped_to_gender), (0, "batch", _ped_to_batch),
(5, "phenotype", _ped_to_phenotype)]:
val = convert_fn(parts[index])
if val is not None and key not in metadata:
metadata[key] = val
break
return metadata | [
"def",
"_add_ped_metadata",
"(",
"name",
",",
"metadata",
")",
":",
"ignore",
"=",
"set",
"(",
"[",
"\"-9\"",
",",
"\"undefined\"",
",",
"\"unknown\"",
",",
"\".\"",
"]",
")",
"def",
"_ped_mapping",
"(",
"x",
",",
"valmap",
")",
":",
"try",
":",
"x",
... | Add standard PED file attributes into metadata if not present.
http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped | [
"Add",
"standard",
"PED",
"file",
"attributes",
"into",
"metadata",
"if",
"not",
"present",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L365-L401 |
237,163 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _add_metadata | def _add_metadata(item, metadata, remotes, only_metadata=False):
"""Add metadata information from CSV file to current item.
Retrieves metadata based on 'description' parsed from input CSV file.
Adds to object and handles special keys:
- `description`: A new description for the item. Used to relabel items
based on the pre-determined description from fastq name or BAM read groups.
- Keys matching supported names in the algorithm section map
to key/value pairs there instead of metadata.
"""
for check_key in [item["description"]] + _get_file_keys(item) + _get_vrn_keys(item):
item_md = metadata.get(check_key)
if item_md:
break
if not item_md:
item_md = _find_glob_metadata(item["files"], metadata)
if remotes.get("region"):
item["algorithm"]["variant_regions"] = remotes["region"]
TOP_LEVEL = set(["description", "genome_build", "lane", "vrn_file", "files", "analysis"])
keep_sample = True
if item_md and len(item_md) > 0:
if "metadata" not in item:
item["metadata"] = {}
for k, v in item_md.items():
if v:
if k in TOP_LEVEL:
item[k] = v
elif k in run_info.ALGORITHM_KEYS:
v = _handle_special_yaml_cases(v)
item["algorithm"][k] = v
else:
v = _handle_special_yaml_cases(v)
item["metadata"][k] = v
elif len(metadata) > 0:
warn = "Dropped sample" if only_metadata else "Added minimal sample information"
print("WARNING: %s: metadata not found for %s, %s" % (warn, item["description"],
[os.path.basename(f) for f in item["files"]]))
keep_sample = not only_metadata
if tz.get_in(["metadata", "ped"], item):
item["metadata"] = _add_ped_metadata(item["description"], item["metadata"])
return item if keep_sample else None | python | def _add_metadata(item, metadata, remotes, only_metadata=False):
for check_key in [item["description"]] + _get_file_keys(item) + _get_vrn_keys(item):
item_md = metadata.get(check_key)
if item_md:
break
if not item_md:
item_md = _find_glob_metadata(item["files"], metadata)
if remotes.get("region"):
item["algorithm"]["variant_regions"] = remotes["region"]
TOP_LEVEL = set(["description", "genome_build", "lane", "vrn_file", "files", "analysis"])
keep_sample = True
if item_md and len(item_md) > 0:
if "metadata" not in item:
item["metadata"] = {}
for k, v in item_md.items():
if v:
if k in TOP_LEVEL:
item[k] = v
elif k in run_info.ALGORITHM_KEYS:
v = _handle_special_yaml_cases(v)
item["algorithm"][k] = v
else:
v = _handle_special_yaml_cases(v)
item["metadata"][k] = v
elif len(metadata) > 0:
warn = "Dropped sample" if only_metadata else "Added minimal sample information"
print("WARNING: %s: metadata not found for %s, %s" % (warn, item["description"],
[os.path.basename(f) for f in item["files"]]))
keep_sample = not only_metadata
if tz.get_in(["metadata", "ped"], item):
item["metadata"] = _add_ped_metadata(item["description"], item["metadata"])
return item if keep_sample else None | [
"def",
"_add_metadata",
"(",
"item",
",",
"metadata",
",",
"remotes",
",",
"only_metadata",
"=",
"False",
")",
":",
"for",
"check_key",
"in",
"[",
"item",
"[",
"\"description\"",
"]",
"]",
"+",
"_get_file_keys",
"(",
"item",
")",
"+",
"_get_vrn_keys",
"(",... | Add metadata information from CSV file to current item.
Retrieves metadata based on 'description' parsed from input CSV file.
Adds to object and handles special keys:
- `description`: A new description for the item. Used to relabel items
based on the pre-determined description from fastq name or BAM read groups.
- Keys matching supported names in the algorithm section map
to key/value pairs there instead of metadata. | [
"Add",
"metadata",
"information",
"from",
"CSV",
"file",
"to",
"current",
"item",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L421-L461 |
237,164 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _retrieve_remote | def _retrieve_remote(fnames):
"""Retrieve remote inputs found in the same bucket as the template or metadata files.
"""
for fname in fnames:
if objectstore.is_remote(fname):
inputs = []
regions = []
remote_base = os.path.dirname(fname)
for rfname in objectstore.list(remote_base):
if rfname.endswith(tuple(KNOWN_EXTS.keys())):
inputs.append(rfname)
elif rfname.endswith((".bed", ".bed.gz")):
regions.append(rfname)
return {"base": remote_base,
"inputs": inputs,
"region": regions[0] if len(regions) == 1 else None}
return {} | python | def _retrieve_remote(fnames):
for fname in fnames:
if objectstore.is_remote(fname):
inputs = []
regions = []
remote_base = os.path.dirname(fname)
for rfname in objectstore.list(remote_base):
if rfname.endswith(tuple(KNOWN_EXTS.keys())):
inputs.append(rfname)
elif rfname.endswith((".bed", ".bed.gz")):
regions.append(rfname)
return {"base": remote_base,
"inputs": inputs,
"region": regions[0] if len(regions) == 1 else None}
return {} | [
"def",
"_retrieve_remote",
"(",
"fnames",
")",
":",
"for",
"fname",
"in",
"fnames",
":",
"if",
"objectstore",
".",
"is_remote",
"(",
"fname",
")",
":",
"inputs",
"=",
"[",
"]",
"regions",
"=",
"[",
"]",
"remote_base",
"=",
"os",
".",
"path",
".",
"di... | Retrieve remote inputs found in the same bucket as the template or metadata files. | [
"Retrieve",
"remote",
"inputs",
"found",
"in",
"the",
"same",
"bucket",
"as",
"the",
"template",
"or",
"metadata",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L477-L493 |
237,165 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _convert_to_relpaths | def _convert_to_relpaths(data, work_dir):
"""Convert absolute paths in the input data to relative paths to the work directory.
"""
work_dir = os.path.abspath(work_dir)
data["files"] = [os.path.relpath(f, work_dir) for f in data["files"]]
for topk in ["metadata", "algorithm"]:
for k, v in data[topk].items():
if isinstance(v, six.string_types) and os.path.isfile(v) and os.path.isabs(v):
data[topk][k] = os.path.relpath(v, work_dir)
return data | python | def _convert_to_relpaths(data, work_dir):
work_dir = os.path.abspath(work_dir)
data["files"] = [os.path.relpath(f, work_dir) for f in data["files"]]
for topk in ["metadata", "algorithm"]:
for k, v in data[topk].items():
if isinstance(v, six.string_types) and os.path.isfile(v) and os.path.isabs(v):
data[topk][k] = os.path.relpath(v, work_dir)
return data | [
"def",
"_convert_to_relpaths",
"(",
"data",
",",
"work_dir",
")",
":",
"work_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"work_dir",
")",
"data",
"[",
"\"files\"",
"]",
"=",
"[",
"os",
".",
"path",
".",
"relpath",
"(",
"f",
",",
"work_dir",
")... | Convert absolute paths in the input data to relative paths to the work directory. | [
"Convert",
"absolute",
"paths",
"in",
"the",
"input",
"data",
"to",
"relative",
"paths",
"to",
"the",
"work",
"directory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L495-L504 |
237,166 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _check_all_metadata_found | def _check_all_metadata_found(metadata, items):
"""Print warning if samples in CSV file are missing in folder"""
for name in metadata:
seen = False
for sample in items:
check_file = sample["files"][0] if sample.get("files") else sample["vrn_file"]
if isinstance(name, (tuple, list)):
if check_file.find(name[0]) > -1:
seen = True
elif check_file.find(name) > -1:
seen = True
elif "*" in name and fnmatch.fnmatch(check_file, "*/%s" % name):
seen = True
if not seen:
print("WARNING: sample not found %s" % str(name)) | python | def _check_all_metadata_found(metadata, items):
for name in metadata:
seen = False
for sample in items:
check_file = sample["files"][0] if sample.get("files") else sample["vrn_file"]
if isinstance(name, (tuple, list)):
if check_file.find(name[0]) > -1:
seen = True
elif check_file.find(name) > -1:
seen = True
elif "*" in name and fnmatch.fnmatch(check_file, "*/%s" % name):
seen = True
if not seen:
print("WARNING: sample not found %s" % str(name)) | [
"def",
"_check_all_metadata_found",
"(",
"metadata",
",",
"items",
")",
":",
"for",
"name",
"in",
"metadata",
":",
"seen",
"=",
"False",
"for",
"sample",
"in",
"items",
":",
"check_file",
"=",
"sample",
"[",
"\"files\"",
"]",
"[",
"0",
"]",
"if",
"sample... | Print warning if samples in CSV file are missing in folder | [
"Print",
"warning",
"if",
"samples",
"in",
"CSV",
"file",
"are",
"missing",
"in",
"folder"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L506-L520 |
237,167 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _copy_to_configdir | def _copy_to_configdir(items, out_dir, args):
"""Copy configuration files like PED inputs to working config directory.
"""
out = []
for item in items:
ped_file = tz.get_in(["metadata", "ped"], item)
if ped_file and os.path.exists(ped_file):
ped_config_file = os.path.join(out_dir, "config", os.path.basename(ped_file))
if not os.path.exists(ped_config_file):
shutil.copy(ped_file, ped_config_file)
item["metadata"]["ped"] = ped_config_file
out.append(item)
if hasattr(args, "systemconfig") and args.systemconfig:
shutil.copy(args.systemconfig, os.path.join(out_dir, "config", os.path.basename(args.systemconfig)))
return out | python | def _copy_to_configdir(items, out_dir, args):
out = []
for item in items:
ped_file = tz.get_in(["metadata", "ped"], item)
if ped_file and os.path.exists(ped_file):
ped_config_file = os.path.join(out_dir, "config", os.path.basename(ped_file))
if not os.path.exists(ped_config_file):
shutil.copy(ped_file, ped_config_file)
item["metadata"]["ped"] = ped_config_file
out.append(item)
if hasattr(args, "systemconfig") and args.systemconfig:
shutil.copy(args.systemconfig, os.path.join(out_dir, "config", os.path.basename(args.systemconfig)))
return out | [
"def",
"_copy_to_configdir",
"(",
"items",
",",
"out_dir",
",",
"args",
")",
":",
"out",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"ped_file",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"metadata\"",
",",
"\"ped\"",
"]",
",",
"item",
")",
"if",
... | Copy configuration files like PED inputs to working config directory. | [
"Copy",
"configuration",
"files",
"like",
"PED",
"inputs",
"to",
"working",
"config",
"directory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L522-L536 |
237,168 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | load_system_config | def load_system_config(config_file=None, work_dir=None, allow_missing=False):
"""Load bcbio_system.yaml configuration file, handling standard defaults.
Looks for configuration file in default location within
final base directory from a standard installation. Handles both standard
installs (galaxy/bcbio_system.yaml) and docker installs (config/bcbio_system.yaml).
"""
docker_config = _get_docker_config()
if config_file is None:
config_file = "bcbio_system.yaml"
if not os.path.exists(config_file):
base_dir = get_base_installdir()
test_config = os.path.join(base_dir, "galaxy", config_file)
if os.path.exists(test_config):
config_file = test_config
elif allow_missing:
config_file = None
else:
raise ValueError("Could not find input system configuration file %s, "
"including inside standard directory %s" %
(config_file, os.path.join(base_dir, "galaxy")))
config = load_config(config_file) if config_file else {}
if docker_config:
assert work_dir is not None, "Need working directory to merge docker config"
config_file = os.path.join(work_dir, "%s-merged%s" % os.path.splitext(os.path.basename(config_file)))
config = _merge_system_configs(config, docker_config, config_file)
if "algorithm" not in config:
config["algorithm"] = {}
config["bcbio_system"] = config_file
return config, config_file | python | def load_system_config(config_file=None, work_dir=None, allow_missing=False):
docker_config = _get_docker_config()
if config_file is None:
config_file = "bcbio_system.yaml"
if not os.path.exists(config_file):
base_dir = get_base_installdir()
test_config = os.path.join(base_dir, "galaxy", config_file)
if os.path.exists(test_config):
config_file = test_config
elif allow_missing:
config_file = None
else:
raise ValueError("Could not find input system configuration file %s, "
"including inside standard directory %s" %
(config_file, os.path.join(base_dir, "galaxy")))
config = load_config(config_file) if config_file else {}
if docker_config:
assert work_dir is not None, "Need working directory to merge docker config"
config_file = os.path.join(work_dir, "%s-merged%s" % os.path.splitext(os.path.basename(config_file)))
config = _merge_system_configs(config, docker_config, config_file)
if "algorithm" not in config:
config["algorithm"] = {}
config["bcbio_system"] = config_file
return config, config_file | [
"def",
"load_system_config",
"(",
"config_file",
"=",
"None",
",",
"work_dir",
"=",
"None",
",",
"allow_missing",
"=",
"False",
")",
":",
"docker_config",
"=",
"_get_docker_config",
"(",
")",
"if",
"config_file",
"is",
"None",
":",
"config_file",
"=",
"\"bcbio... | Load bcbio_system.yaml configuration file, handling standard defaults.
Looks for configuration file in default location within
final base directory from a standard installation. Handles both standard
installs (galaxy/bcbio_system.yaml) and docker installs (config/bcbio_system.yaml). | [
"Load",
"bcbio_system",
".",
"yaml",
"configuration",
"file",
"handling",
"standard",
"defaults",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L50-L79 |
237,169 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | _merge_system_configs | def _merge_system_configs(host_config, container_config, out_file=None):
"""Create a merged system configuration from external and internal specification.
"""
out = copy.deepcopy(container_config)
for k, v in host_config.items():
if k in set(["galaxy_config"]):
out[k] = v
elif k == "resources":
for pname, resources in v.items():
if not isinstance(resources, dict) and pname not in out[k]:
out[k][pname] = resources
else:
for rname, rval in resources.items():
if (rname in set(["cores", "jvm_opts", "memory"])
or pname in set(["gatk", "mutect"])):
if pname not in out[k]:
out[k][pname] = {}
out[k][pname][rname] = rval
# Ensure final file is relocatable by mapping back to reference directory
if "bcbio_system" in out and ("galaxy_config" not in out or not os.path.isabs(out["galaxy_config"])):
out["galaxy_config"] = os.path.normpath(os.path.join(os.path.dirname(out["bcbio_system"]),
os.pardir, "galaxy",
"universe_wsgi.ini"))
if out_file:
with open(out_file, "w") as out_handle:
yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
return out | python | def _merge_system_configs(host_config, container_config, out_file=None):
out = copy.deepcopy(container_config)
for k, v in host_config.items():
if k in set(["galaxy_config"]):
out[k] = v
elif k == "resources":
for pname, resources in v.items():
if not isinstance(resources, dict) and pname not in out[k]:
out[k][pname] = resources
else:
for rname, rval in resources.items():
if (rname in set(["cores", "jvm_opts", "memory"])
or pname in set(["gatk", "mutect"])):
if pname not in out[k]:
out[k][pname] = {}
out[k][pname][rname] = rval
# Ensure final file is relocatable by mapping back to reference directory
if "bcbio_system" in out and ("galaxy_config" not in out or not os.path.isabs(out["galaxy_config"])):
out["galaxy_config"] = os.path.normpath(os.path.join(os.path.dirname(out["bcbio_system"]),
os.pardir, "galaxy",
"universe_wsgi.ini"))
if out_file:
with open(out_file, "w") as out_handle:
yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
return out | [
"def",
"_merge_system_configs",
"(",
"host_config",
",",
"container_config",
",",
"out_file",
"=",
"None",
")",
":",
"out",
"=",
"copy",
".",
"deepcopy",
"(",
"container_config",
")",
"for",
"k",
",",
"v",
"in",
"host_config",
".",
"items",
"(",
")",
":",
... | Create a merged system configuration from external and internal specification. | [
"Create",
"a",
"merged",
"system",
"configuration",
"from",
"external",
"and",
"internal",
"specification",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L84-L110 |
237,170 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | merge_resources | def merge_resources(args):
"""Merge docker local resources and global resource specification in a set of arguments.
Finds the `data` object within passed arguments and updates the resources
from a local docker configuration if present.
"""
docker_config = _get_docker_config()
if not docker_config:
return args
else:
def _update_resources(config):
config["resources"] = _merge_system_configs(config, docker_config)["resources"]
return config
return _update_config(args, _update_resources, allow_missing=True) | python | def merge_resources(args):
docker_config = _get_docker_config()
if not docker_config:
return args
else:
def _update_resources(config):
config["resources"] = _merge_system_configs(config, docker_config)["resources"]
return config
return _update_config(args, _update_resources, allow_missing=True) | [
"def",
"merge_resources",
"(",
"args",
")",
":",
"docker_config",
"=",
"_get_docker_config",
"(",
")",
"if",
"not",
"docker_config",
":",
"return",
"args",
"else",
":",
"def",
"_update_resources",
"(",
"config",
")",
":",
"config",
"[",
"\"resources\"",
"]",
... | Merge docker local resources and global resource specification in a set of arguments.
Finds the `data` object within passed arguments and updates the resources
from a local docker configuration if present. | [
"Merge",
"docker",
"local",
"resources",
"and",
"global",
"resource",
"specification",
"in",
"a",
"set",
"of",
"arguments",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L118-L131 |
237,171 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | load_config | def load_config(config_file):
"""Load YAML config file, replacing environmental variables.
"""
with open(config_file) as in_handle:
config = yaml.safe_load(in_handle)
config = _expand_paths(config)
if 'resources' not in config:
config['resources'] = {}
# lowercase resource names, the preferred way to specify, for back-compatibility
newr = {}
for k, v in config["resources"].items():
if k.lower() != k:
newr[k.lower()] = v
config["resources"].update(newr)
return config | python | def load_config(config_file):
with open(config_file) as in_handle:
config = yaml.safe_load(in_handle)
config = _expand_paths(config)
if 'resources' not in config:
config['resources'] = {}
# lowercase resource names, the preferred way to specify, for back-compatibility
newr = {}
for k, v in config["resources"].items():
if k.lower() != k:
newr[k.lower()] = v
config["resources"].update(newr)
return config | [
"def",
"load_config",
"(",
"config_file",
")",
":",
"with",
"open",
"(",
"config_file",
")",
"as",
"in_handle",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"in_handle",
")",
"config",
"=",
"_expand_paths",
"(",
"config",
")",
"if",
"'resources'",
"n... | Load YAML config file, replacing environmental variables. | [
"Load",
"YAML",
"config",
"file",
"replacing",
"environmental",
"variables",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L133-L147 |
237,172 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | get_resources | def get_resources(name, config):
"""Retrieve resources for a program, pulling from multiple config sources.
"""
return tz.get_in(["resources", name], config,
tz.get_in(["resources", "default"], config, {})) | python | def get_resources(name, config):
return tz.get_in(["resources", name], config,
tz.get_in(["resources", "default"], config, {})) | [
"def",
"get_resources",
"(",
"name",
",",
"config",
")",
":",
"return",
"tz",
".",
"get_in",
"(",
"[",
"\"resources\"",
",",
"name",
"]",
",",
"config",
",",
"tz",
".",
"get_in",
"(",
"[",
"\"resources\"",
",",
"\"default\"",
"]",
",",
"config",
",",
... | Retrieve resources for a program, pulling from multiple config sources. | [
"Retrieve",
"resources",
"for",
"a",
"program",
"pulling",
"from",
"multiple",
"config",
"sources",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L165-L169 |
237,173 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | get_program | def get_program(name, config, ptype="cmd", default=None):
"""Retrieve program information from the configuration.
This handles back compatible location specification in input
YAML. The preferred location for program information is in
`resources` but the older `program` tag is also supported.
"""
# support taking in the data dictionary
config = config.get("config", config)
try:
pconfig = config.get("resources", {})[name]
# If have leftover old
except KeyError:
pconfig = {}
old_config = config.get("program", {}).get(name, None)
if old_config:
for key in ["dir", "cmd"]:
if not key in pconfig:
pconfig[key] = old_config
if ptype == "cmd":
return _get_program_cmd(name, pconfig, config, default)
elif ptype == "dir":
return _get_program_dir(name, pconfig)
else:
raise ValueError("Don't understand program type: %s" % ptype) | python | def get_program(name, config, ptype="cmd", default=None):
# support taking in the data dictionary
config = config.get("config", config)
try:
pconfig = config.get("resources", {})[name]
# If have leftover old
except KeyError:
pconfig = {}
old_config = config.get("program", {}).get(name, None)
if old_config:
for key in ["dir", "cmd"]:
if not key in pconfig:
pconfig[key] = old_config
if ptype == "cmd":
return _get_program_cmd(name, pconfig, config, default)
elif ptype == "dir":
return _get_program_dir(name, pconfig)
else:
raise ValueError("Don't understand program type: %s" % ptype) | [
"def",
"get_program",
"(",
"name",
",",
"config",
",",
"ptype",
"=",
"\"cmd\"",
",",
"default",
"=",
"None",
")",
":",
"# support taking in the data dictionary",
"config",
"=",
"config",
".",
"get",
"(",
"\"config\"",
",",
"config",
")",
"try",
":",
"pconfig... | Retrieve program information from the configuration.
This handles back compatible location specification in input
YAML. The preferred location for program information is in
`resources` but the older `program` tag is also supported. | [
"Retrieve",
"program",
"information",
"from",
"the",
"configuration",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L171-L195 |
237,174 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | _get_program_cmd | def _get_program_cmd(name, pconfig, config, default):
"""Retrieve commandline of a program.
"""
if pconfig is None:
return name
elif isinstance(pconfig, six.string_types):
return pconfig
elif "cmd" in pconfig:
return pconfig["cmd"]
elif default is not None:
return default
else:
return name | python | def _get_program_cmd(name, pconfig, config, default):
if pconfig is None:
return name
elif isinstance(pconfig, six.string_types):
return pconfig
elif "cmd" in pconfig:
return pconfig["cmd"]
elif default is not None:
return default
else:
return name | [
"def",
"_get_program_cmd",
"(",
"name",
",",
"pconfig",
",",
"config",
",",
"default",
")",
":",
"if",
"pconfig",
"is",
"None",
":",
"return",
"name",
"elif",
"isinstance",
"(",
"pconfig",
",",
"six",
".",
"string_types",
")",
":",
"return",
"pconfig",
"... | Retrieve commandline of a program. | [
"Retrieve",
"commandline",
"of",
"a",
"program",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L221-L233 |
237,175 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | get_jar | def get_jar(base_name, dname):
"""Retrieve a jar in the provided directory
"""
jars = glob.glob(os.path.join(expand_path(dname), "%s*.jar" % base_name))
if len(jars) == 1:
return jars[0]
elif len(jars) > 1:
raise ValueError("Found multiple jars for %s in %s. Need single jar: %s" %
(base_name, dname, jars))
else:
raise ValueError("Could not find java jar %s in %s" %
(base_name, dname)) | python | def get_jar(base_name, dname):
jars = glob.glob(os.path.join(expand_path(dname), "%s*.jar" % base_name))
if len(jars) == 1:
return jars[0]
elif len(jars) > 1:
raise ValueError("Found multiple jars for %s in %s. Need single jar: %s" %
(base_name, dname, jars))
else:
raise ValueError("Could not find java jar %s in %s" %
(base_name, dname)) | [
"def",
"get_jar",
"(",
"base_name",
",",
"dname",
")",
":",
"jars",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"expand_path",
"(",
"dname",
")",
",",
"\"%s*.jar\"",
"%",
"base_name",
")",
")",
"if",
"len",
"(",
"jars",
")",... | Retrieve a jar in the provided directory | [
"Retrieve",
"a",
"jar",
"in",
"the",
"provided",
"directory"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L247-L259 |
237,176 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | get_algorithm_config | def get_algorithm_config(xs):
"""Flexibly extract algorithm configuration for a sample from any function arguments.
"""
if isinstance(xs, dict):
xs = [xs]
for x in xs:
if is_std_config_arg(x):
return x["algorithm"]
elif is_nested_config_arg(x):
return x["config"]["algorithm"]
elif isinstance(x, (list, tuple)) and is_nested_config_arg(x[0]):
return x[0]["config"]["algorithm"]
raise ValueError("Did not find algorithm configuration in items: {0}"
.format(pprint.pformat(xs))) | python | def get_algorithm_config(xs):
if isinstance(xs, dict):
xs = [xs]
for x in xs:
if is_std_config_arg(x):
return x["algorithm"]
elif is_nested_config_arg(x):
return x["config"]["algorithm"]
elif isinstance(x, (list, tuple)) and is_nested_config_arg(x[0]):
return x[0]["config"]["algorithm"]
raise ValueError("Did not find algorithm configuration in items: {0}"
.format(pprint.pformat(xs))) | [
"def",
"get_algorithm_config",
"(",
"xs",
")",
":",
"if",
"isinstance",
"(",
"xs",
",",
"dict",
")",
":",
"xs",
"=",
"[",
"xs",
"]",
"for",
"x",
"in",
"xs",
":",
"if",
"is_std_config_arg",
"(",
"x",
")",
":",
"return",
"x",
"[",
"\"algorithm\"",
"]... | Flexibly extract algorithm configuration for a sample from any function arguments. | [
"Flexibly",
"extract",
"algorithm",
"configuration",
"for",
"a",
"sample",
"from",
"any",
"function",
"arguments",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L269-L282 |
237,177 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | get_dataarg | def get_dataarg(args):
"""Retrieve the world 'data' argument from a set of input parameters.
"""
for i, arg in enumerate(args):
if is_nested_config_arg(arg):
return i, arg
elif is_std_config_arg(arg):
return i, {"config": arg}
elif isinstance(arg, (list, tuple)) and is_nested_config_arg(arg[0]):
return i, arg[0]
raise ValueError("Did not find configuration or data object in arguments: %s" % args) | python | def get_dataarg(args):
for i, arg in enumerate(args):
if is_nested_config_arg(arg):
return i, arg
elif is_std_config_arg(arg):
return i, {"config": arg}
elif isinstance(arg, (list, tuple)) and is_nested_config_arg(arg[0]):
return i, arg[0]
raise ValueError("Did not find configuration or data object in arguments: %s" % args) | [
"def",
"get_dataarg",
"(",
"args",
")",
":",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"is_nested_config_arg",
"(",
"arg",
")",
":",
"return",
"i",
",",
"arg",
"elif",
"is_std_config_arg",
"(",
"arg",
")",
":",
"return",
... | Retrieve the world 'data' argument from a set of input parameters. | [
"Retrieve",
"the",
"world",
"data",
"argument",
"from",
"a",
"set",
"of",
"input",
"parameters",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L284-L294 |
237,178 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | add_cores_to_config | def add_cores_to_config(args, cores_per_job, parallel=None):
"""Add information about available cores for a job to configuration.
Ugly hack to update core information in a configuration dictionary.
"""
def _update_cores(config):
config["algorithm"]["num_cores"] = int(cores_per_job)
if parallel:
parallel.pop("view", None)
config["parallel"] = parallel
return config
return _update_config(args, _update_cores) | python | def add_cores_to_config(args, cores_per_job, parallel=None):
def _update_cores(config):
config["algorithm"]["num_cores"] = int(cores_per_job)
if parallel:
parallel.pop("view", None)
config["parallel"] = parallel
return config
return _update_config(args, _update_cores) | [
"def",
"add_cores_to_config",
"(",
"args",
",",
"cores_per_job",
",",
"parallel",
"=",
"None",
")",
":",
"def",
"_update_cores",
"(",
"config",
")",
":",
"config",
"[",
"\"algorithm\"",
"]",
"[",
"\"num_cores\"",
"]",
"=",
"int",
"(",
"cores_per_job",
")",
... | Add information about available cores for a job to configuration.
Ugly hack to update core information in a configuration dictionary. | [
"Add",
"information",
"about",
"available",
"cores",
"for",
"a",
"job",
"to",
"configuration",
".",
"Ugly",
"hack",
"to",
"update",
"core",
"information",
"in",
"a",
"configuration",
"dictionary",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L296-L306 |
237,179 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | _update_config | def _update_config(args, update_fn, allow_missing=False):
"""Update configuration, nested in argument list, with the provided update function.
"""
new_i = None
for i, arg in enumerate(args):
if (is_std_config_arg(arg) or is_nested_config_arg(arg) or
(isinstance(arg, (list, tuple)) and is_nested_config_arg(arg[0]))):
new_i = i
break
if new_i is None:
if allow_missing:
return args
else:
raise ValueError("Could not find configuration in args: %s" % str(args))
new_arg = args[new_i]
if is_nested_config_arg(new_arg):
new_arg["config"] = update_fn(copy.deepcopy(new_arg["config"]))
elif is_std_config_arg(new_arg):
new_arg = update_fn(copy.deepcopy(new_arg))
elif isinstance(arg, (list, tuple)) and is_nested_config_arg(new_arg[0]):
new_arg_first = new_arg[0]
new_arg_first["config"] = update_fn(copy.deepcopy(new_arg_first["config"]))
new_arg = [new_arg_first] + new_arg[1:]
else:
raise ValueError("Unexpected configuration dictionary: %s" % new_arg)
args = list(args)[:]
args[new_i] = new_arg
return args | python | def _update_config(args, update_fn, allow_missing=False):
new_i = None
for i, arg in enumerate(args):
if (is_std_config_arg(arg) or is_nested_config_arg(arg) or
(isinstance(arg, (list, tuple)) and is_nested_config_arg(arg[0]))):
new_i = i
break
if new_i is None:
if allow_missing:
return args
else:
raise ValueError("Could not find configuration in args: %s" % str(args))
new_arg = args[new_i]
if is_nested_config_arg(new_arg):
new_arg["config"] = update_fn(copy.deepcopy(new_arg["config"]))
elif is_std_config_arg(new_arg):
new_arg = update_fn(copy.deepcopy(new_arg))
elif isinstance(arg, (list, tuple)) and is_nested_config_arg(new_arg[0]):
new_arg_first = new_arg[0]
new_arg_first["config"] = update_fn(copy.deepcopy(new_arg_first["config"]))
new_arg = [new_arg_first] + new_arg[1:]
else:
raise ValueError("Unexpected configuration dictionary: %s" % new_arg)
args = list(args)[:]
args[new_i] = new_arg
return args | [
"def",
"_update_config",
"(",
"args",
",",
"update_fn",
",",
"allow_missing",
"=",
"False",
")",
":",
"new_i",
"=",
"None",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"(",
"is_std_config_arg",
"(",
"arg",
")",
"or",
"is_nes... | Update configuration, nested in argument list, with the provided update function. | [
"Update",
"configuration",
"nested",
"in",
"argument",
"list",
"with",
"the",
"provided",
"update",
"function",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L308-L336 |
237,180 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | convert_to_bytes | def convert_to_bytes(mem_str):
"""Convert a memory specification, potentially with M or G, into bytes.
"""
if str(mem_str)[-1].upper().endswith("G"):
return int(round(float(mem_str[:-1]) * 1024 * 1024))
elif str(mem_str)[-1].upper().endswith("M"):
return int(round(float(mem_str[:-1]) * 1024))
else:
return int(round(float(mem_str))) | python | def convert_to_bytes(mem_str):
if str(mem_str)[-1].upper().endswith("G"):
return int(round(float(mem_str[:-1]) * 1024 * 1024))
elif str(mem_str)[-1].upper().endswith("M"):
return int(round(float(mem_str[:-1]) * 1024))
else:
return int(round(float(mem_str))) | [
"def",
"convert_to_bytes",
"(",
"mem_str",
")",
":",
"if",
"str",
"(",
"mem_str",
")",
"[",
"-",
"1",
"]",
".",
"upper",
"(",
")",
".",
"endswith",
"(",
"\"G\"",
")",
":",
"return",
"int",
"(",
"round",
"(",
"float",
"(",
"mem_str",
"[",
":",
"-"... | Convert a memory specification, potentially with M or G, into bytes. | [
"Convert",
"a",
"memory",
"specification",
"potentially",
"with",
"M",
"or",
"G",
"into",
"bytes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L338-L346 |
237,181 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | adjust_memory | def adjust_memory(val, magnitude, direction="increase", out_modifier="", maximum=None):
"""Adjust memory based on number of cores utilized.
"""
modifier = val[-1:]
amount = float(val[:-1])
if direction == "decrease":
new_amount = amount / float(magnitude)
# dealing with a specifier like 1G, need to scale to Mb
if new_amount < 1 or (out_modifier.upper().startswith("M") and modifier.upper().startswith("G")):
if modifier.upper().startswith("G"):
new_amount = (amount * 1024) / magnitude
modifier = "M" + modifier[1:]
else:
raise ValueError("Unexpected decrease in memory: %s by %s" % (val, magnitude))
amount = int(new_amount)
elif direction == "increase" and magnitude > 1:
# for increases with multiple cores, leave small percentage of
# memory for system to maintain process running resource and
# avoid OOM killers
adjuster = 0.91
amount = int(math.ceil(amount * (adjuster * magnitude)))
if out_modifier.upper().startswith("G") and modifier.upper().startswith("M"):
modifier = out_modifier
amount = int(math.floor(amount / 1024.0))
if out_modifier.upper().startswith("M") and modifier.upper().startswith("G"):
modifier = out_modifier
modifier = int(amount * 1024)
if maximum:
max_modifier = maximum[-1]
max_amount = float(maximum[:-1])
if modifier.upper() == "G" and max_modifier.upper() == "M":
max_amount = max_amount / 1024.0
elif modifier.upper() == "M" and max_modifier.upper() == "G":
max_amount = max_amount * 1024.0
amount = min([amount, max_amount])
return "{amount}{modifier}".format(amount=int(math.floor(amount)), modifier=modifier) | python | def adjust_memory(val, magnitude, direction="increase", out_modifier="", maximum=None):
modifier = val[-1:]
amount = float(val[:-1])
if direction == "decrease":
new_amount = amount / float(magnitude)
# dealing with a specifier like 1G, need to scale to Mb
if new_amount < 1 or (out_modifier.upper().startswith("M") and modifier.upper().startswith("G")):
if modifier.upper().startswith("G"):
new_amount = (amount * 1024) / magnitude
modifier = "M" + modifier[1:]
else:
raise ValueError("Unexpected decrease in memory: %s by %s" % (val, magnitude))
amount = int(new_amount)
elif direction == "increase" and magnitude > 1:
# for increases with multiple cores, leave small percentage of
# memory for system to maintain process running resource and
# avoid OOM killers
adjuster = 0.91
amount = int(math.ceil(amount * (adjuster * magnitude)))
if out_modifier.upper().startswith("G") and modifier.upper().startswith("M"):
modifier = out_modifier
amount = int(math.floor(amount / 1024.0))
if out_modifier.upper().startswith("M") and modifier.upper().startswith("G"):
modifier = out_modifier
modifier = int(amount * 1024)
if maximum:
max_modifier = maximum[-1]
max_amount = float(maximum[:-1])
if modifier.upper() == "G" and max_modifier.upper() == "M":
max_amount = max_amount / 1024.0
elif modifier.upper() == "M" and max_modifier.upper() == "G":
max_amount = max_amount * 1024.0
amount = min([amount, max_amount])
return "{amount}{modifier}".format(amount=int(math.floor(amount)), modifier=modifier) | [
"def",
"adjust_memory",
"(",
"val",
",",
"magnitude",
",",
"direction",
"=",
"\"increase\"",
",",
"out_modifier",
"=",
"\"\"",
",",
"maximum",
"=",
"None",
")",
":",
"modifier",
"=",
"val",
"[",
"-",
"1",
":",
"]",
"amount",
"=",
"float",
"(",
"val",
... | Adjust memory based on number of cores utilized. | [
"Adjust",
"memory",
"based",
"on",
"number",
"of",
"cores",
"utilized",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L361-L396 |
237,182 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | adjust_opts | def adjust_opts(in_opts, config):
"""Establish JVM opts, adjusting memory for the context if needed.
This allows using less or more memory for highly parallel or multicore
supporting processes, respectively.
"""
memory_adjust = config["algorithm"].get("memory_adjust", {})
out_opts = []
for opt in in_opts:
if opt.startswith("-Xmx") or (opt.startswith("-Xms") and memory_adjust.get("direction") == "decrease"):
arg = opt[:4]
opt = "{arg}{val}".format(arg=arg,
val=adjust_memory(opt[4:],
memory_adjust.get("magnitude", 1),
memory_adjust.get("direction"),
maximum=memory_adjust.get("maximum")))
out_opts.append(opt)
return out_opts | python | def adjust_opts(in_opts, config):
memory_adjust = config["algorithm"].get("memory_adjust", {})
out_opts = []
for opt in in_opts:
if opt.startswith("-Xmx") or (opt.startswith("-Xms") and memory_adjust.get("direction") == "decrease"):
arg = opt[:4]
opt = "{arg}{val}".format(arg=arg,
val=adjust_memory(opt[4:],
memory_adjust.get("magnitude", 1),
memory_adjust.get("direction"),
maximum=memory_adjust.get("maximum")))
out_opts.append(opt)
return out_opts | [
"def",
"adjust_opts",
"(",
"in_opts",
",",
"config",
")",
":",
"memory_adjust",
"=",
"config",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\"memory_adjust\"",
",",
"{",
"}",
")",
"out_opts",
"=",
"[",
"]",
"for",
"opt",
"in",
"in_opts",
":",
"if",
"op... | Establish JVM opts, adjusting memory for the context if needed.
This allows using less or more memory for highly parallel or multicore
supporting processes, respectively. | [
"Establish",
"JVM",
"opts",
"adjusting",
"memory",
"for",
"the",
"context",
"if",
"needed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L398-L415 |
237,183 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | use_vqsr | def use_vqsr(algs, call_file=None):
"""Processing uses GATK's Variant Quality Score Recalibration.
"""
from bcbio.variation import vcfutils
vqsr_callers = set(["gatk", "gatk-haplotype"])
vqsr_sample_thresh = 50
vqsr_supported = collections.defaultdict(int)
coverage_intervals = set([])
for alg in algs:
callers = alg.get("variantcaller")
if isinstance(callers, six.string_types):
callers = [callers]
if not callers: # no variant calling, no VQSR
continue
if "vqsr" in (alg.get("tools_off") or []): # VQSR turned off
continue
for c in callers:
if c in vqsr_callers:
if "vqsr" in (alg.get("tools_on") or []): # VQSR turned on:
vqsr_supported[c] += 1
coverage_intervals.add("genome")
# Do not try VQSR for gVCF inputs
elif call_file and vcfutils.is_gvcf_file(call_file):
pass
else:
coverage_intervals.add(alg.get("coverage_interval", "exome").lower())
vqsr_supported[c] += 1
if len(vqsr_supported) > 0:
num_samples = max(vqsr_supported.values())
if "genome" in coverage_intervals or num_samples >= vqsr_sample_thresh:
return True
return False | python | def use_vqsr(algs, call_file=None):
from bcbio.variation import vcfutils
vqsr_callers = set(["gatk", "gatk-haplotype"])
vqsr_sample_thresh = 50
vqsr_supported = collections.defaultdict(int)
coverage_intervals = set([])
for alg in algs:
callers = alg.get("variantcaller")
if isinstance(callers, six.string_types):
callers = [callers]
if not callers: # no variant calling, no VQSR
continue
if "vqsr" in (alg.get("tools_off") or []): # VQSR turned off
continue
for c in callers:
if c in vqsr_callers:
if "vqsr" in (alg.get("tools_on") or []): # VQSR turned on:
vqsr_supported[c] += 1
coverage_intervals.add("genome")
# Do not try VQSR for gVCF inputs
elif call_file and vcfutils.is_gvcf_file(call_file):
pass
else:
coverage_intervals.add(alg.get("coverage_interval", "exome").lower())
vqsr_supported[c] += 1
if len(vqsr_supported) > 0:
num_samples = max(vqsr_supported.values())
if "genome" in coverage_intervals or num_samples >= vqsr_sample_thresh:
return True
return False | [
"def",
"use_vqsr",
"(",
"algs",
",",
"call_file",
"=",
"None",
")",
":",
"from",
"bcbio",
".",
"variation",
"import",
"vcfutils",
"vqsr_callers",
"=",
"set",
"(",
"[",
"\"gatk\"",
",",
"\"gatk-haplotype\"",
"]",
")",
"vqsr_sample_thresh",
"=",
"50",
"vqsr_su... | Processing uses GATK's Variant Quality Score Recalibration. | [
"Processing",
"uses",
"GATK",
"s",
"Variant",
"Quality",
"Score",
"Recalibration",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L419-L450 |
237,184 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | use_bcbio_variation_recall | def use_bcbio_variation_recall(algs):
"""Processing uses bcbio-variation-recall. Avoids core requirement if not used.
"""
for alg in algs:
jointcaller = alg.get("jointcaller", [])
if not isinstance(jointcaller, (tuple, list)):
jointcaller = [jointcaller]
for caller in jointcaller:
if caller not in set(["gatk-haplotype-joint", None, False]):
return True
return False | python | def use_bcbio_variation_recall(algs):
for alg in algs:
jointcaller = alg.get("jointcaller", [])
if not isinstance(jointcaller, (tuple, list)):
jointcaller = [jointcaller]
for caller in jointcaller:
if caller not in set(["gatk-haplotype-joint", None, False]):
return True
return False | [
"def",
"use_bcbio_variation_recall",
"(",
"algs",
")",
":",
"for",
"alg",
"in",
"algs",
":",
"jointcaller",
"=",
"alg",
".",
"get",
"(",
"\"jointcaller\"",
",",
"[",
"]",
")",
"if",
"not",
"isinstance",
"(",
"jointcaller",
",",
"(",
"tuple",
",",
"list",... | Processing uses bcbio-variation-recall. Avoids core requirement if not used. | [
"Processing",
"uses",
"bcbio",
"-",
"variation",
"-",
"recall",
".",
"Avoids",
"core",
"requirement",
"if",
"not",
"used",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L457-L467 |
237,185 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | program_installed | def program_installed(program, data):
"""
returns True if the path to a program can be found
"""
try:
path = get_program(program, data)
except CmdNotFound:
return False
return True | python | def program_installed(program, data):
try:
path = get_program(program, data)
except CmdNotFound:
return False
return True | [
"def",
"program_installed",
"(",
"program",
",",
"data",
")",
":",
"try",
":",
"path",
"=",
"get_program",
"(",
"program",
",",
"data",
")",
"except",
"CmdNotFound",
":",
"return",
"False",
"return",
"True"
] | returns True if the path to a program can be found | [
"returns",
"True",
"if",
"the",
"path",
"to",
"a",
"program",
"can",
"be",
"found"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L480-L488 |
237,186 | bcbio/bcbio-nextgen | bcbio/provenance/versioncheck.py | samtools | def samtools(items):
"""Ensure samtools has parallel processing required for piped analysis.
"""
samtools = config_utils.get_program("samtools", items[0]["config"])
p = subprocess.Popen([samtools, "sort", "-h"], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, stderr = p.communicate()
p.stdout.close()
p.stderr.close()
if str(output).find("-@") == -1 and str(stderr).find("-@") == -1:
return ("Installed version of samtools sort does not have support for "
"multithreading (-@ option) "
"required to support bwa piped alignment and BAM merging. "
"Please upgrade to the latest version "
"from http://samtools.sourceforge.net/") | python | def samtools(items):
samtools = config_utils.get_program("samtools", items[0]["config"])
p = subprocess.Popen([samtools, "sort", "-h"], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, stderr = p.communicate()
p.stdout.close()
p.stderr.close()
if str(output).find("-@") == -1 and str(stderr).find("-@") == -1:
return ("Installed version of samtools sort does not have support for "
"multithreading (-@ option) "
"required to support bwa piped alignment and BAM merging. "
"Please upgrade to the latest version "
"from http://samtools.sourceforge.net/") | [
"def",
"samtools",
"(",
"items",
")",
":",
"samtools",
"=",
"config_utils",
".",
"get_program",
"(",
"\"samtools\"",
",",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"samtools",
",",
"\"sort\"",
... | Ensure samtools has parallel processing required for piped analysis. | [
"Ensure",
"samtools",
"has",
"parallel",
"processing",
"required",
"for",
"piped",
"analysis",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/versioncheck.py#L11-L25 |
237,187 | bcbio/bcbio-nextgen | bcbio/provenance/versioncheck.py | _needs_java | def _needs_java(data):
"""Check if a caller needs external java for MuTect.
No longer check for older GATK (<3.6) versions because of time cost; this
won't be relevant to most runs so we skip the sanity check.
"""
vc = dd.get_variantcaller(data)
if isinstance(vc, dict):
out = {}
for k, v in vc.items():
if not isinstance(v, (list, tuple)):
v = [v]
out[k] = v
vc = out
elif not isinstance(vc, (list, tuple)):
vc = [vc]
if "mutect" in vc or ("somatic" in vc and "mutect" in vc["somatic"]):
return True
if "gatk" in vc or "gatk-haplotype" in vc or ("germline" in vc and "gatk-haplotype" in vc["germline"]):
pass
# runner = broad.runner_from_config(data["config"])
# version = runner.get_gatk_version()
# if LooseVersion(version) < LooseVersion("3.6"):
# return True
return False | python | def _needs_java(data):
vc = dd.get_variantcaller(data)
if isinstance(vc, dict):
out = {}
for k, v in vc.items():
if not isinstance(v, (list, tuple)):
v = [v]
out[k] = v
vc = out
elif not isinstance(vc, (list, tuple)):
vc = [vc]
if "mutect" in vc or ("somatic" in vc and "mutect" in vc["somatic"]):
return True
if "gatk" in vc or "gatk-haplotype" in vc or ("germline" in vc and "gatk-haplotype" in vc["germline"]):
pass
# runner = broad.runner_from_config(data["config"])
# version = runner.get_gatk_version()
# if LooseVersion(version) < LooseVersion("3.6"):
# return True
return False | [
"def",
"_needs_java",
"(",
"data",
")",
":",
"vc",
"=",
"dd",
".",
"get_variantcaller",
"(",
"data",
")",
"if",
"isinstance",
"(",
"vc",
",",
"dict",
")",
":",
"out",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"vc",
".",
"items",
"(",
")",
":",... | Check if a caller needs external java for MuTect.
No longer check for older GATK (<3.6) versions because of time cost; this
won't be relevant to most runs so we skip the sanity check. | [
"Check",
"if",
"a",
"caller",
"needs",
"external",
"java",
"for",
"MuTect",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/versioncheck.py#L32-L56 |
237,188 | bcbio/bcbio-nextgen | bcbio/provenance/versioncheck.py | java | def java(items):
"""Check for presence of external Java 1.7 for tools that require it.
"""
if any([_needs_java(d) for d in items]):
min_version = "1.7"
max_version = "1.8"
with setpath.orig_paths():
java = utils.which("java")
if not java:
return ("java not found on PATH. Java %s required for MuTect and GATK < 3.6." % min_version)
p = subprocess.Popen([java, "-Xms250m", "-Xmx250m", "-version"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, _ = p.communicate()
p.stdout.close()
version = ""
for line in output.split("\n"):
if line.startswith(("java version", "openjdk version")):
version = line.strip().split()[-1]
if version.startswith('"'):
version = version[1:]
if version.endswith('"'):
version = version[:-1]
if (not version or LooseVersion(version) >= LooseVersion(max_version) or
LooseVersion(version) < LooseVersion(min_version)):
return ("java version %s required for running MuTect and GATK < 3.6.\n"
"It needs to be first on your PATH so running 'java -version' give the correct version.\n"
"Found version %s at %s" % (min_version, version, java)) | python | def java(items):
if any([_needs_java(d) for d in items]):
min_version = "1.7"
max_version = "1.8"
with setpath.orig_paths():
java = utils.which("java")
if not java:
return ("java not found on PATH. Java %s required for MuTect and GATK < 3.6." % min_version)
p = subprocess.Popen([java, "-Xms250m", "-Xmx250m", "-version"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, _ = p.communicate()
p.stdout.close()
version = ""
for line in output.split("\n"):
if line.startswith(("java version", "openjdk version")):
version = line.strip().split()[-1]
if version.startswith('"'):
version = version[1:]
if version.endswith('"'):
version = version[:-1]
if (not version or LooseVersion(version) >= LooseVersion(max_version) or
LooseVersion(version) < LooseVersion(min_version)):
return ("java version %s required for running MuTect and GATK < 3.6.\n"
"It needs to be first on your PATH so running 'java -version' give the correct version.\n"
"Found version %s at %s" % (min_version, version, java)) | [
"def",
"java",
"(",
"items",
")",
":",
"if",
"any",
"(",
"[",
"_needs_java",
"(",
"d",
")",
"for",
"d",
"in",
"items",
"]",
")",
":",
"min_version",
"=",
"\"1.7\"",
"max_version",
"=",
"\"1.8\"",
"with",
"setpath",
".",
"orig_paths",
"(",
")",
":",
... | Check for presence of external Java 1.7 for tools that require it. | [
"Check",
"for",
"presence",
"of",
"external",
"Java",
"1",
".",
"7",
"for",
"tools",
"that",
"require",
"it",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/versioncheck.py#L58-L84 |
237,189 | bcbio/bcbio-nextgen | bcbio/install.py | upgrade_bcbio | def upgrade_bcbio(args):
"""Perform upgrade of bcbio to latest release, or from GitHub development version.
Handles bcbio, third party tools and data.
"""
print("Upgrading bcbio")
args = add_install_defaults(args)
if args.upgrade in ["stable", "system", "deps", "development"]:
if args.upgrade == "development":
anaconda_dir = _update_conda_devel()
_check_for_conda_problems()
print("Upgrading bcbio-nextgen to latest development version")
pip_bin = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), "pip")
git_tag = "@%s" % args.revision if args.revision != "master" else ""
_pip_safe_ssl([[pip_bin, "install", "--upgrade", "--no-deps",
"git+%s%s#egg=bcbio-nextgen" % (REMOTES["gitrepo"], git_tag)]], anaconda_dir)
print("Upgrade of bcbio-nextgen development code complete.")
else:
_update_conda_packages()
_check_for_conda_problems()
print("Upgrade of bcbio-nextgen code complete.")
if args.cwl and args.upgrade:
_update_bcbiovm()
try:
_set_matplotlib_default_backend()
except OSError:
pass
if args.tooldir:
with bcbio_tmpdir():
print("Upgrading third party tools to latest versions")
_symlink_bcbio(args, script="bcbio_nextgen.py")
_symlink_bcbio(args, script="bcbio_setup_genome.py")
_symlink_bcbio(args, script="bcbio_prepare_samples.py")
_symlink_bcbio(args, script="bcbio_fastq_umi_prep.py")
if args.cwl:
_symlink_bcbio(args, "bcbio_vm.py", "bcbiovm")
_symlink_bcbio(args, "python", "bcbiovm", "bcbiovm")
upgrade_thirdparty_tools(args, REMOTES)
print("Third party tools upgrade complete.")
if args.toolplus:
print("Installing additional tools")
_install_toolplus(args)
if args.install_data:
for default in DEFAULT_INDEXES:
if default not in args.aligners:
args.aligners.append(default)
if len(args.aligners) == 0:
print("Warning: no aligners provided with `--aligners` flag")
if len(args.genomes) == 0:
print("Data not installed, no genomes provided with `--genomes` flag")
else:
with bcbio_tmpdir():
print("Upgrading bcbio-nextgen data files")
upgrade_bcbio_data(args, REMOTES)
print("bcbio-nextgen data upgrade complete.")
if args.isolate and args.tooldir:
print("Isolated tool installation not automatically added to environmental variables")
print(" Add:\n {t}/bin to PATH".format(t=args.tooldir))
save_install_defaults(args)
args.datadir = _get_data_dir()
_install_container_bcbio_system(args.datadir)
print("Upgrade completed successfully.")
return args | python | def upgrade_bcbio(args):
print("Upgrading bcbio")
args = add_install_defaults(args)
if args.upgrade in ["stable", "system", "deps", "development"]:
if args.upgrade == "development":
anaconda_dir = _update_conda_devel()
_check_for_conda_problems()
print("Upgrading bcbio-nextgen to latest development version")
pip_bin = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), "pip")
git_tag = "@%s" % args.revision if args.revision != "master" else ""
_pip_safe_ssl([[pip_bin, "install", "--upgrade", "--no-deps",
"git+%s%s#egg=bcbio-nextgen" % (REMOTES["gitrepo"], git_tag)]], anaconda_dir)
print("Upgrade of bcbio-nextgen development code complete.")
else:
_update_conda_packages()
_check_for_conda_problems()
print("Upgrade of bcbio-nextgen code complete.")
if args.cwl and args.upgrade:
_update_bcbiovm()
try:
_set_matplotlib_default_backend()
except OSError:
pass
if args.tooldir:
with bcbio_tmpdir():
print("Upgrading third party tools to latest versions")
_symlink_bcbio(args, script="bcbio_nextgen.py")
_symlink_bcbio(args, script="bcbio_setup_genome.py")
_symlink_bcbio(args, script="bcbio_prepare_samples.py")
_symlink_bcbio(args, script="bcbio_fastq_umi_prep.py")
if args.cwl:
_symlink_bcbio(args, "bcbio_vm.py", "bcbiovm")
_symlink_bcbio(args, "python", "bcbiovm", "bcbiovm")
upgrade_thirdparty_tools(args, REMOTES)
print("Third party tools upgrade complete.")
if args.toolplus:
print("Installing additional tools")
_install_toolplus(args)
if args.install_data:
for default in DEFAULT_INDEXES:
if default not in args.aligners:
args.aligners.append(default)
if len(args.aligners) == 0:
print("Warning: no aligners provided with `--aligners` flag")
if len(args.genomes) == 0:
print("Data not installed, no genomes provided with `--genomes` flag")
else:
with bcbio_tmpdir():
print("Upgrading bcbio-nextgen data files")
upgrade_bcbio_data(args, REMOTES)
print("bcbio-nextgen data upgrade complete.")
if args.isolate and args.tooldir:
print("Isolated tool installation not automatically added to environmental variables")
print(" Add:\n {t}/bin to PATH".format(t=args.tooldir))
save_install_defaults(args)
args.datadir = _get_data_dir()
_install_container_bcbio_system(args.datadir)
print("Upgrade completed successfully.")
return args | [
"def",
"upgrade_bcbio",
"(",
"args",
")",
":",
"print",
"(",
"\"Upgrading bcbio\"",
")",
"args",
"=",
"add_install_defaults",
"(",
"args",
")",
"if",
"args",
".",
"upgrade",
"in",
"[",
"\"stable\"",
",",
"\"system\"",
",",
"\"deps\"",
",",
"\"development\"",
... | Perform upgrade of bcbio to latest release, or from GitHub development version.
Handles bcbio, third party tools and data. | [
"Perform",
"upgrade",
"of",
"bcbio",
"to",
"latest",
"release",
"or",
"from",
"GitHub",
"development",
"version",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L51-L115 |
237,190 | bcbio/bcbio-nextgen | bcbio/install.py | _pip_safe_ssl | def _pip_safe_ssl(cmds, anaconda_dir):
"""Run pip, retrying with conda SSL certificate if global certificate fails.
"""
try:
for cmd in cmds:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
_set_pip_ssl(anaconda_dir)
for cmd in cmds:
subprocess.check_call(cmd) | python | def _pip_safe_ssl(cmds, anaconda_dir):
try:
for cmd in cmds:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
_set_pip_ssl(anaconda_dir)
for cmd in cmds:
subprocess.check_call(cmd) | [
"def",
"_pip_safe_ssl",
"(",
"cmds",
",",
"anaconda_dir",
")",
":",
"try",
":",
"for",
"cmd",
"in",
"cmds",
":",
"subprocess",
".",
"check_call",
"(",
"cmd",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"_set_pip_ssl",
"(",
"anaconda_dir",
")... | Run pip, retrying with conda SSL certificate if global certificate fails. | [
"Run",
"pip",
"retrying",
"with",
"conda",
"SSL",
"certificate",
"if",
"global",
"certificate",
"fails",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L117-L126 |
237,191 | bcbio/bcbio-nextgen | bcbio/install.py | _set_pip_ssl | def _set_pip_ssl(anaconda_dir):
"""Set PIP SSL certificate to installed conda certificate to avoid SSL errors
"""
if anaconda_dir:
cert_file = os.path.join(anaconda_dir, "ssl", "cert.pem")
if os.path.exists(cert_file):
os.environ["PIP_CERT"] = cert_file | python | def _set_pip_ssl(anaconda_dir):
if anaconda_dir:
cert_file = os.path.join(anaconda_dir, "ssl", "cert.pem")
if os.path.exists(cert_file):
os.environ["PIP_CERT"] = cert_file | [
"def",
"_set_pip_ssl",
"(",
"anaconda_dir",
")",
":",
"if",
"anaconda_dir",
":",
"cert_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"anaconda_dir",
",",
"\"ssl\"",
",",
"\"cert.pem\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"cert_file",
")... | Set PIP SSL certificate to installed conda certificate to avoid SSL errors | [
"Set",
"PIP",
"SSL",
"certificate",
"to",
"installed",
"conda",
"certificate",
"to",
"avoid",
"SSL",
"errors"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L128-L134 |
237,192 | bcbio/bcbio-nextgen | bcbio/install.py | _set_matplotlib_default_backend | def _set_matplotlib_default_backend():
"""
matplotlib will try to print to a display if it is available, but don't want
to run it in interactive mode. we tried setting the backend to 'Agg'' before
importing, but it was still resulting in issues. we replace the existing
backend with 'agg' in the default matplotlibrc. This is a hack until we can
find a better solution
"""
if _matplotlib_installed():
import matplotlib
matplotlib.use('Agg', force=True)
config = matplotlib.matplotlib_fname()
if os.access(config, os.W_OK):
with file_transaction(config) as tx_out_file:
with open(config) as in_file, open(tx_out_file, "w") as out_file:
for line in in_file:
if line.split(":")[0].strip() == "backend":
out_file.write("backend: agg\n")
else:
out_file.write(line) | python | def _set_matplotlib_default_backend():
if _matplotlib_installed():
import matplotlib
matplotlib.use('Agg', force=True)
config = matplotlib.matplotlib_fname()
if os.access(config, os.W_OK):
with file_transaction(config) as tx_out_file:
with open(config) as in_file, open(tx_out_file, "w") as out_file:
for line in in_file:
if line.split(":")[0].strip() == "backend":
out_file.write("backend: agg\n")
else:
out_file.write(line) | [
"def",
"_set_matplotlib_default_backend",
"(",
")",
":",
"if",
"_matplotlib_installed",
"(",
")",
":",
"import",
"matplotlib",
"matplotlib",
".",
"use",
"(",
"'Agg'",
",",
"force",
"=",
"True",
")",
"config",
"=",
"matplotlib",
".",
"matplotlib_fname",
"(",
")... | matplotlib will try to print to a display if it is available, but don't want
to run it in interactive mode. we tried setting the backend to 'Agg'' before
importing, but it was still resulting in issues. we replace the existing
backend with 'agg' in the default matplotlibrc. This is a hack until we can
find a better solution | [
"matplotlib",
"will",
"try",
"to",
"print",
"to",
"a",
"display",
"if",
"it",
"is",
"available",
"but",
"don",
"t",
"want",
"to",
"run",
"it",
"in",
"interactive",
"mode",
".",
"we",
"tried",
"setting",
"the",
"backend",
"to",
"Agg",
"before",
"importing... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L136-L155 |
237,193 | bcbio/bcbio-nextgen | bcbio/install.py | _symlink_bcbio | def _symlink_bcbio(args, script="bcbio_nextgen.py", env_name=None, prefix=None):
"""Ensure a bcbio-nextgen script symlink in final tool directory.
"""
if env_name:
bcbio_anaconda = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(sys.executable))),
"envs", env_name, "bin", script)
else:
bcbio_anaconda = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), script)
bindir = os.path.join(args.tooldir, "bin")
if not os.path.exists(bindir):
os.makedirs(bindir)
if prefix:
script = "%s_%s" % (prefix, script)
bcbio_final = os.path.join(bindir, script)
if not os.path.exists(bcbio_final):
if os.path.lexists(bcbio_final):
subprocess.check_call(["rm", "-f", bcbio_final])
subprocess.check_call(["ln", "-s", bcbio_anaconda, bcbio_final]) | python | def _symlink_bcbio(args, script="bcbio_nextgen.py", env_name=None, prefix=None):
if env_name:
bcbio_anaconda = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(sys.executable))),
"envs", env_name, "bin", script)
else:
bcbio_anaconda = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), script)
bindir = os.path.join(args.tooldir, "bin")
if not os.path.exists(bindir):
os.makedirs(bindir)
if prefix:
script = "%s_%s" % (prefix, script)
bcbio_final = os.path.join(bindir, script)
if not os.path.exists(bcbio_final):
if os.path.lexists(bcbio_final):
subprocess.check_call(["rm", "-f", bcbio_final])
subprocess.check_call(["ln", "-s", bcbio_anaconda, bcbio_final]) | [
"def",
"_symlink_bcbio",
"(",
"args",
",",
"script",
"=",
"\"bcbio_nextgen.py\"",
",",
"env_name",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"env_name",
":",
"bcbio_anaconda",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
... | Ensure a bcbio-nextgen script symlink in final tool directory. | [
"Ensure",
"a",
"bcbio",
"-",
"nextgen",
"script",
"symlink",
"in",
"final",
"tool",
"directory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L164-L181 |
237,194 | bcbio/bcbio-nextgen | bcbio/install.py | _install_container_bcbio_system | def _install_container_bcbio_system(datadir):
"""Install limited bcbio_system.yaml file for setting core and memory usage.
Adds any non-specific programs to the exposed bcbio_system.yaml file, only
when upgrade happening inside a docker container.
"""
base_file = os.path.join(datadir, "config", "bcbio_system.yaml")
if not os.path.exists(base_file):
return
expose_file = os.path.join(datadir, "galaxy", "bcbio_system.yaml")
expose = set(["memory", "cores", "jvm_opts"])
with open(base_file) as in_handle:
config = yaml.safe_load(in_handle)
if os.path.exists(expose_file):
with open(expose_file) as in_handle:
expose_config = yaml.safe_load(in_handle)
else:
expose_config = {"resources": {}}
for pname, vals in config["resources"].items():
expose_vals = {}
for k, v in vals.items():
if k in expose:
expose_vals[k] = v
if len(expose_vals) > 0 and pname not in expose_config["resources"]:
expose_config["resources"][pname] = expose_vals
if expose_file and os.path.exists(os.path.dirname(expose_file)):
with open(expose_file, "w") as out_handle:
yaml.safe_dump(expose_config, out_handle, default_flow_style=False, allow_unicode=False)
return expose_file | python | def _install_container_bcbio_system(datadir):
base_file = os.path.join(datadir, "config", "bcbio_system.yaml")
if not os.path.exists(base_file):
return
expose_file = os.path.join(datadir, "galaxy", "bcbio_system.yaml")
expose = set(["memory", "cores", "jvm_opts"])
with open(base_file) as in_handle:
config = yaml.safe_load(in_handle)
if os.path.exists(expose_file):
with open(expose_file) as in_handle:
expose_config = yaml.safe_load(in_handle)
else:
expose_config = {"resources": {}}
for pname, vals in config["resources"].items():
expose_vals = {}
for k, v in vals.items():
if k in expose:
expose_vals[k] = v
if len(expose_vals) > 0 and pname not in expose_config["resources"]:
expose_config["resources"][pname] = expose_vals
if expose_file and os.path.exists(os.path.dirname(expose_file)):
with open(expose_file, "w") as out_handle:
yaml.safe_dump(expose_config, out_handle, default_flow_style=False, allow_unicode=False)
return expose_file | [
"def",
"_install_container_bcbio_system",
"(",
"datadir",
")",
":",
"base_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"datadir",
",",
"\"config\"",
",",
"\"bcbio_system.yaml\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"base_file",
")",
... | Install limited bcbio_system.yaml file for setting core and memory usage.
Adds any non-specific programs to the exposed bcbio_system.yaml file, only
when upgrade happening inside a docker container. | [
"Install",
"limited",
"bcbio_system",
".",
"yaml",
"file",
"for",
"setting",
"core",
"and",
"memory",
"usage",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L183-L211 |
237,195 | bcbio/bcbio-nextgen | bcbio/install.py | _check_for_conda_problems | def _check_for_conda_problems():
"""Identify post-install conda problems and fix.
- libgcc upgrades can remove libquadmath, which moved to libgcc-ng
"""
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
lib_dir = os.path.join(os.path.dirname(conda_bin), os.pardir, "lib")
for l in ["libgomp.so.1", "libquadmath.so"]:
if not os.path.exists(os.path.join(lib_dir, l)):
subprocess.check_call([conda_bin, "install", "-f", "--yes"] + channels + ["libgcc-ng"]) | python | def _check_for_conda_problems():
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
lib_dir = os.path.join(os.path.dirname(conda_bin), os.pardir, "lib")
for l in ["libgomp.so.1", "libquadmath.so"]:
if not os.path.exists(os.path.join(lib_dir, l)):
subprocess.check_call([conda_bin, "install", "-f", "--yes"] + channels + ["libgcc-ng"]) | [
"def",
"_check_for_conda_problems",
"(",
")",
":",
"conda_bin",
"=",
"_get_conda_bin",
"(",
")",
"channels",
"=",
"_get_conda_channels",
"(",
"conda_bin",
")",
"lib_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"co... | Identify post-install conda problems and fix.
- libgcc upgrades can remove libquadmath, which moved to libgcc-ng | [
"Identify",
"post",
"-",
"install",
"conda",
"problems",
"and",
"fix",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L218-L228 |
237,196 | bcbio/bcbio-nextgen | bcbio/install.py | _update_bcbiovm | def _update_bcbiovm():
"""Update or install a local bcbiovm install with tools and dependencies.
"""
print("## CWL support with bcbio-vm")
python_env = "python=3"
conda_bin, env_name = _add_environment("bcbiovm", python_env)
channels = _get_conda_channels(conda_bin)
base_cmd = [conda_bin, "install", "--yes", "--name", env_name] + channels
subprocess.check_call(base_cmd + [python_env, "nomkl", "bcbio-nextgen"])
extra_uptodate = ["cromwell"]
subprocess.check_call(base_cmd + [python_env, "bcbio-nextgen-vm"] + extra_uptodate) | python | def _update_bcbiovm():
print("## CWL support with bcbio-vm")
python_env = "python=3"
conda_bin, env_name = _add_environment("bcbiovm", python_env)
channels = _get_conda_channels(conda_bin)
base_cmd = [conda_bin, "install", "--yes", "--name", env_name] + channels
subprocess.check_call(base_cmd + [python_env, "nomkl", "bcbio-nextgen"])
extra_uptodate = ["cromwell"]
subprocess.check_call(base_cmd + [python_env, "bcbio-nextgen-vm"] + extra_uptodate) | [
"def",
"_update_bcbiovm",
"(",
")",
":",
"print",
"(",
"\"## CWL support with bcbio-vm\"",
")",
"python_env",
"=",
"\"python=3\"",
"conda_bin",
",",
"env_name",
"=",
"_add_environment",
"(",
"\"bcbiovm\"",
",",
"python_env",
")",
"channels",
"=",
"_get_conda_channels"... | Update or install a local bcbiovm install with tools and dependencies. | [
"Update",
"or",
"install",
"a",
"local",
"bcbiovm",
"install",
"with",
"tools",
"and",
"dependencies",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L230-L240 |
237,197 | bcbio/bcbio-nextgen | bcbio/install.py | _get_conda_channels | def _get_conda_channels(conda_bin):
"""Retrieve default conda channels, checking if they are pre-specified in config.
This allows users to override defaults with specific mirrors in their .condarc
"""
channels = ["bioconda", "conda-forge"]
out = []
config = yaml.safe_load(subprocess.check_output([conda_bin, "config", "--show"]))
for c in channels:
present = False
for orig_c in config.get("channels") or []:
if orig_c.endswith((c, "%s/" % c)):
present = True
break
if not present:
out += ["-c", c]
return out | python | def _get_conda_channels(conda_bin):
channels = ["bioconda", "conda-forge"]
out = []
config = yaml.safe_load(subprocess.check_output([conda_bin, "config", "--show"]))
for c in channels:
present = False
for orig_c in config.get("channels") or []:
if orig_c.endswith((c, "%s/" % c)):
present = True
break
if not present:
out += ["-c", c]
return out | [
"def",
"_get_conda_channels",
"(",
"conda_bin",
")",
":",
"channels",
"=",
"[",
"\"bioconda\"",
",",
"\"conda-forge\"",
"]",
"out",
"=",
"[",
"]",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"subprocess",
".",
"check_output",
"(",
"[",
"conda_bin",
",",
... | Retrieve default conda channels, checking if they are pre-specified in config.
This allows users to override defaults with specific mirrors in their .condarc | [
"Retrieve",
"default",
"conda",
"channels",
"checking",
"if",
"they",
"are",
"pre",
"-",
"specified",
"in",
"config",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L255-L271 |
237,198 | bcbio/bcbio-nextgen | bcbio/install.py | _update_conda_packages | def _update_conda_packages():
"""If installed in an anaconda directory, upgrade conda packages.
"""
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
assert conda_bin, ("Could not find anaconda distribution for upgrading bcbio.\n"
"Using python at %s but could not find conda." % (os.path.realpath(sys.executable)))
req_file = "bcbio-update-requirements.txt"
if os.path.exists(req_file):
os.remove(req_file)
subprocess.check_call(["wget", "-O", req_file, "--no-check-certificate", REMOTES["requirements"]])
subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] + channels +
["--file", req_file])
if os.path.exists(req_file):
os.remove(req_file)
return os.path.dirname(os.path.dirname(conda_bin)) | python | def _update_conda_packages():
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
assert conda_bin, ("Could not find anaconda distribution for upgrading bcbio.\n"
"Using python at %s but could not find conda." % (os.path.realpath(sys.executable)))
req_file = "bcbio-update-requirements.txt"
if os.path.exists(req_file):
os.remove(req_file)
subprocess.check_call(["wget", "-O", req_file, "--no-check-certificate", REMOTES["requirements"]])
subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] + channels +
["--file", req_file])
if os.path.exists(req_file):
os.remove(req_file)
return os.path.dirname(os.path.dirname(conda_bin)) | [
"def",
"_update_conda_packages",
"(",
")",
":",
"conda_bin",
"=",
"_get_conda_bin",
"(",
")",
"channels",
"=",
"_get_conda_channels",
"(",
"conda_bin",
")",
"assert",
"conda_bin",
",",
"(",
"\"Could not find anaconda distribution for upgrading bcbio.\\n\"",
"\"Using python ... | If installed in an anaconda directory, upgrade conda packages. | [
"If",
"installed",
"in",
"an",
"anaconda",
"directory",
"upgrade",
"conda",
"packages",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L273-L288 |
237,199 | bcbio/bcbio-nextgen | bcbio/install.py | _update_conda_devel | def _update_conda_devel():
"""Update to the latest development conda package.
"""
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
assert conda_bin, "Could not find anaconda distribution for upgrading bcbio"
subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] + channels +
["bcbio-nextgen>=%s" % version.__version__.replace("a0", "a")])
return os.path.dirname(os.path.dirname(conda_bin)) | python | def _update_conda_devel():
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
assert conda_bin, "Could not find anaconda distribution for upgrading bcbio"
subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] + channels +
["bcbio-nextgen>=%s" % version.__version__.replace("a0", "a")])
return os.path.dirname(os.path.dirname(conda_bin)) | [
"def",
"_update_conda_devel",
"(",
")",
":",
"conda_bin",
"=",
"_get_conda_bin",
"(",
")",
"channels",
"=",
"_get_conda_channels",
"(",
"conda_bin",
")",
"assert",
"conda_bin",
",",
"\"Could not find anaconda distribution for upgrading bcbio\"",
"subprocess",
".",
"check_... | Update to the latest development conda package. | [
"Update",
"to",
"the",
"latest",
"development",
"conda",
"package",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L290-L298 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.