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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
bcbio/bcbio-nextgen | bcbio/ngsalign/postalign.py | _sam_to_grouped_umi_cl | def _sam_to_grouped_umi_cl(data, umi_consensus, tx_out_file):
"""Mark duplicates on aligner output and convert to grouped UMIs by position.
Works with either a separate umi_file or UMI embedded in the read names.
"""
tmp_file = "%s-sorttmp" % utils.splitext_plus(tx_out_file)[0]
jvm_opts = _get_fgbio_jvm_opts(data, os.path.dirname(tmp_file), 1)
cores, mem = _get_cores_memory(data)
bamsormadup = config_utils.get_program("bamsormadup", data)
cmd = ("{bamsormadup} tmpfile={tmp_file}-markdup inputformat=sam threads={cores} outputformat=bam "
"level=0 SO=coordinate | ")
# UMIs in a separate file
if os.path.exists(umi_consensus) and os.path.isfile(umi_consensus):
cmd += "fgbio {jvm_opts} AnnotateBamWithUmis -i /dev/stdin -f {umi_consensus} -o {tx_out_file}"
# UMIs embedded in read name
else:
cmd += ("%s %s bamtag - | samtools view -b > {tx_out_file}" %
(utils.get_program_python("umis"),
config_utils.get_program("umis", data["config"])))
return cmd.format(**locals()) | python | def _sam_to_grouped_umi_cl(data, umi_consensus, tx_out_file):
"""Mark duplicates on aligner output and convert to grouped UMIs by position.
Works with either a separate umi_file or UMI embedded in the read names.
"""
tmp_file = "%s-sorttmp" % utils.splitext_plus(tx_out_file)[0]
jvm_opts = _get_fgbio_jvm_opts(data, os.path.dirname(tmp_file), 1)
cores, mem = _get_cores_memory(data)
bamsormadup = config_utils.get_program("bamsormadup", data)
cmd = ("{bamsormadup} tmpfile={tmp_file}-markdup inputformat=sam threads={cores} outputformat=bam "
"level=0 SO=coordinate | ")
# UMIs in a separate file
if os.path.exists(umi_consensus) and os.path.isfile(umi_consensus):
cmd += "fgbio {jvm_opts} AnnotateBamWithUmis -i /dev/stdin -f {umi_consensus} -o {tx_out_file}"
# UMIs embedded in read name
else:
cmd += ("%s %s bamtag - | samtools view -b > {tx_out_file}" %
(utils.get_program_python("umis"),
config_utils.get_program("umis", data["config"])))
return cmd.format(**locals()) | [
"def",
"_sam_to_grouped_umi_cl",
"(",
"data",
",",
"umi_consensus",
",",
"tx_out_file",
")",
":",
"tmp_file",
"=",
"\"%s-sorttmp\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"tx_out_file",
")",
"[",
"0",
"]",
"jvm_opts",
"=",
"_get_fgbio_jvm_opts",
"(",
"data",
... | Mark duplicates on aligner output and convert to grouped UMIs by position.
Works with either a separate umi_file or UMI embedded in the read names. | [
"Mark",
"duplicates",
"on",
"aligner",
"output",
"and",
"convert",
"to",
"grouped",
"UMIs",
"by",
"position",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/postalign.py#L136-L155 | train | 218,300 |
bcbio/bcbio-nextgen | bcbio/ngsalign/postalign.py | umi_consensus | def umi_consensus(data):
"""Convert UMI grouped reads into fastq pair for re-alignment.
"""
align_bam = dd.get_work_bam(data)
umi_method, umi_tag = _check_umi_type(align_bam)
f1_out = "%s-cumi-1.fq.gz" % utils.splitext_plus(align_bam)[0]
f2_out = "%s-cumi-2.fq.gz" % utils.splitext_plus(align_bam)[0]
avg_coverage = coverage.get_average_coverage("rawumi", dd.get_variant_regions(data), data)
if not utils.file_uptodate(f1_out, align_bam):
with file_transaction(data, f1_out, f2_out) as (tx_f1_out, tx_f2_out):
jvm_opts = _get_fgbio_jvm_opts(data, os.path.dirname(tx_f1_out), 2)
# Improve speeds by avoiding compression read/write bottlenecks
io_opts = "--async-io=true --compression=0"
est_options = _estimate_fgbio_defaults(avg_coverage)
group_opts, cons_opts, filter_opts = _get_fgbio_options(data, est_options, umi_method)
cons_method = "CallDuplexConsensusReads" if umi_method == "paired" else "CallMolecularConsensusReads"
tempfile = "%s-bamtofastq-tmp" % utils.splitext_plus(f1_out)[0]
ref_file = dd.get_ref_file(data)
cmd = ("unset JAVA_HOME && "
"fgbio {jvm_opts} {io_opts} GroupReadsByUmi {group_opts} -t {umi_tag} -s {umi_method} "
"-i {align_bam} | "
"fgbio {jvm_opts} {io_opts} {cons_method} {cons_opts} --sort-order=:none: "
"-i /dev/stdin -o /dev/stdout | "
"fgbio {jvm_opts} {io_opts} FilterConsensusReads {filter_opts} -r {ref_file} "
"-i /dev/stdin -o /dev/stdout | "
"bamtofastq collate=1 T={tempfile} F={tx_f1_out} F2={tx_f2_out} tags=cD,cM,cE gz=1")
do.run(cmd.format(**locals()), "UMI consensus fastq generation")
return f1_out, f2_out, avg_coverage | python | def umi_consensus(data):
"""Convert UMI grouped reads into fastq pair for re-alignment.
"""
align_bam = dd.get_work_bam(data)
umi_method, umi_tag = _check_umi_type(align_bam)
f1_out = "%s-cumi-1.fq.gz" % utils.splitext_plus(align_bam)[0]
f2_out = "%s-cumi-2.fq.gz" % utils.splitext_plus(align_bam)[0]
avg_coverage = coverage.get_average_coverage("rawumi", dd.get_variant_regions(data), data)
if not utils.file_uptodate(f1_out, align_bam):
with file_transaction(data, f1_out, f2_out) as (tx_f1_out, tx_f2_out):
jvm_opts = _get_fgbio_jvm_opts(data, os.path.dirname(tx_f1_out), 2)
# Improve speeds by avoiding compression read/write bottlenecks
io_opts = "--async-io=true --compression=0"
est_options = _estimate_fgbio_defaults(avg_coverage)
group_opts, cons_opts, filter_opts = _get_fgbio_options(data, est_options, umi_method)
cons_method = "CallDuplexConsensusReads" if umi_method == "paired" else "CallMolecularConsensusReads"
tempfile = "%s-bamtofastq-tmp" % utils.splitext_plus(f1_out)[0]
ref_file = dd.get_ref_file(data)
cmd = ("unset JAVA_HOME && "
"fgbio {jvm_opts} {io_opts} GroupReadsByUmi {group_opts} -t {umi_tag} -s {umi_method} "
"-i {align_bam} | "
"fgbio {jvm_opts} {io_opts} {cons_method} {cons_opts} --sort-order=:none: "
"-i /dev/stdin -o /dev/stdout | "
"fgbio {jvm_opts} {io_opts} FilterConsensusReads {filter_opts} -r {ref_file} "
"-i /dev/stdin -o /dev/stdout | "
"bamtofastq collate=1 T={tempfile} F={tx_f1_out} F2={tx_f2_out} tags=cD,cM,cE gz=1")
do.run(cmd.format(**locals()), "UMI consensus fastq generation")
return f1_out, f2_out, avg_coverage | [
"def",
"umi_consensus",
"(",
"data",
")",
":",
"align_bam",
"=",
"dd",
".",
"get_work_bam",
"(",
"data",
")",
"umi_method",
",",
"umi_tag",
"=",
"_check_umi_type",
"(",
"align_bam",
")",
"f1_out",
"=",
"\"%s-cumi-1.fq.gz\"",
"%",
"utils",
".",
"splitext_plus",... | Convert UMI grouped reads into fastq pair for re-alignment. | [
"Convert",
"UMI",
"grouped",
"reads",
"into",
"fastq",
"pair",
"for",
"re",
"-",
"alignment",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/postalign.py#L188-L215 | train | 218,301 |
bcbio/bcbio-nextgen | bcbio/ngsalign/postalign.py | _get_fgbio_options | def _get_fgbio_options(data, estimated_defaults, umi_method):
"""Get adjustable, through resources, or default options for fgbio.
"""
group_opts = ["--edits", "--min-map-q"]
cons_opts = ["--min-input-base-quality"]
if umi_method != "paired":
cons_opts += ["--min-reads", "--max-reads"]
filter_opts = ["--min-reads", "--min-base-quality", "--max-base-error-rate"]
defaults = {"--min-reads": "1",
"--max-reads": "100000",
"--min-map-q": "1",
"--min-base-quality": "13",
"--max-base-error-rate": "0.1",
"--min-input-base-quality": "2",
"--edits": "1"}
defaults.update(estimated_defaults)
ropts = config_utils.get_resources("fgbio", data["config"]).get("options", [])
assert len(ropts) % 2 == 0, "Expect even number of options for fgbio" % ropts
ropts = dict(tz.partition(2, ropts))
# Back compatibility for older base quality settings
if "--min-consensus-base-quality" in ropts:
ropts["--min-base-quality"] = ropts.pop("--min-consensus-base-quality")
defaults.update(ropts)
group_out = " ".join(["%s=%s" % (x, defaults[x]) for x in group_opts])
cons_out = " ".join(["%s=%s" % (x, defaults[x]) for x in cons_opts])
filter_out = " ".join(["%s=%s" % (x, defaults[x]) for x in filter_opts])
if umi_method != "paired":
cons_out += " --output-per-base-tags=false"
return group_out, cons_out, filter_out | python | def _get_fgbio_options(data, estimated_defaults, umi_method):
"""Get adjustable, through resources, or default options for fgbio.
"""
group_opts = ["--edits", "--min-map-q"]
cons_opts = ["--min-input-base-quality"]
if umi_method != "paired":
cons_opts += ["--min-reads", "--max-reads"]
filter_opts = ["--min-reads", "--min-base-quality", "--max-base-error-rate"]
defaults = {"--min-reads": "1",
"--max-reads": "100000",
"--min-map-q": "1",
"--min-base-quality": "13",
"--max-base-error-rate": "0.1",
"--min-input-base-quality": "2",
"--edits": "1"}
defaults.update(estimated_defaults)
ropts = config_utils.get_resources("fgbio", data["config"]).get("options", [])
assert len(ropts) % 2 == 0, "Expect even number of options for fgbio" % ropts
ropts = dict(tz.partition(2, ropts))
# Back compatibility for older base quality settings
if "--min-consensus-base-quality" in ropts:
ropts["--min-base-quality"] = ropts.pop("--min-consensus-base-quality")
defaults.update(ropts)
group_out = " ".join(["%s=%s" % (x, defaults[x]) for x in group_opts])
cons_out = " ".join(["%s=%s" % (x, defaults[x]) for x in cons_opts])
filter_out = " ".join(["%s=%s" % (x, defaults[x]) for x in filter_opts])
if umi_method != "paired":
cons_out += " --output-per-base-tags=false"
return group_out, cons_out, filter_out | [
"def",
"_get_fgbio_options",
"(",
"data",
",",
"estimated_defaults",
",",
"umi_method",
")",
":",
"group_opts",
"=",
"[",
"\"--edits\"",
",",
"\"--min-map-q\"",
"]",
"cons_opts",
"=",
"[",
"\"--min-input-base-quality\"",
"]",
"if",
"umi_method",
"!=",
"\"paired\"",
... | Get adjustable, through resources, or default options for fgbio. | [
"Get",
"adjustable",
"through",
"resources",
"or",
"default",
"options",
"for",
"fgbio",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/postalign.py#L235-L263 | train | 218,302 |
bcbio/bcbio-nextgen | bcbio/ngsalign/postalign.py | _check_dedup | def _check_dedup(data):
"""Check configuration for de-duplication.
Defaults to no de-duplication for RNA-seq and small RNA, the
back compatible default. Allow overwriting with explicit
`mark_duplicates: true` setting.
Also defaults to false for no alignment inputs.
"""
if dd.get_analysis(data).lower() in ["rna-seq", "smallrna-seq"] or not dd.get_aligner(data):
dup_param = utils.get_in(data, ("config", "algorithm", "mark_duplicates"), False)
else:
dup_param = utils.get_in(data, ("config", "algorithm", "mark_duplicates"), True)
if dup_param and isinstance(dup_param, six.string_types):
logger.info("Warning: bcbio no longer support explicit setting of mark_duplicate algorithm. "
"Using best-practice choice based on input data.")
dup_param = True
return dup_param | python | def _check_dedup(data):
"""Check configuration for de-duplication.
Defaults to no de-duplication for RNA-seq and small RNA, the
back compatible default. Allow overwriting with explicit
`mark_duplicates: true` setting.
Also defaults to false for no alignment inputs.
"""
if dd.get_analysis(data).lower() in ["rna-seq", "smallrna-seq"] or not dd.get_aligner(data):
dup_param = utils.get_in(data, ("config", "algorithm", "mark_duplicates"), False)
else:
dup_param = utils.get_in(data, ("config", "algorithm", "mark_duplicates"), True)
if dup_param and isinstance(dup_param, six.string_types):
logger.info("Warning: bcbio no longer support explicit setting of mark_duplicate algorithm. "
"Using best-practice choice based on input data.")
dup_param = True
return dup_param | [
"def",
"_check_dedup",
"(",
"data",
")",
":",
"if",
"dd",
".",
"get_analysis",
"(",
"data",
")",
".",
"lower",
"(",
")",
"in",
"[",
"\"rna-seq\"",
",",
"\"smallrna-seq\"",
"]",
"or",
"not",
"dd",
".",
"get_aligner",
"(",
"data",
")",
":",
"dup_param",
... | Check configuration for de-duplication.
Defaults to no de-duplication for RNA-seq and small RNA, the
back compatible default. Allow overwriting with explicit
`mark_duplicates: true` setting.
Also defaults to false for no alignment inputs. | [
"Check",
"configuration",
"for",
"de",
"-",
"duplication",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/postalign.py#L265-L281 | train | 218,303 |
bcbio/bcbio-nextgen | bcbio/ngsalign/postalign.py | dedup_bam | def dedup_bam(in_bam, data):
"""Perform non-stream based deduplication of BAM input files using biobambam.
"""
if _check_dedup(data):
out_file = os.path.join(utils.safe_makedir(os.path.join(os.getcwd(), "align", dd.get_sample_name(data))),
"%s-dedup%s" % utils.splitext_plus(os.path.basename(in_bam)))
if not utils.file_exists(out_file):
with tx_tmpdir(data) as tmpdir:
with file_transaction(data, out_file) as tx_out_file:
bammarkduplicates = config_utils.get_program("bammarkduplicates", data["config"])
base_tmp = os.path.join(tmpdir, os.path.splitext(os.path.basename(tx_out_file))[0])
cores, mem = _get_cores_memory(data, downscale=2)
cmd = ("{bammarkduplicates} tmpfile={base_tmp}-markdup "
"markthreads={cores} I={in_bam} O={tx_out_file}")
do.run(cmd.format(**locals()), "De-duplication with biobambam")
bam.index(out_file, data["config"])
return out_file
else:
return in_bam | python | def dedup_bam(in_bam, data):
"""Perform non-stream based deduplication of BAM input files using biobambam.
"""
if _check_dedup(data):
out_file = os.path.join(utils.safe_makedir(os.path.join(os.getcwd(), "align", dd.get_sample_name(data))),
"%s-dedup%s" % utils.splitext_plus(os.path.basename(in_bam)))
if not utils.file_exists(out_file):
with tx_tmpdir(data) as tmpdir:
with file_transaction(data, out_file) as tx_out_file:
bammarkduplicates = config_utils.get_program("bammarkduplicates", data["config"])
base_tmp = os.path.join(tmpdir, os.path.splitext(os.path.basename(tx_out_file))[0])
cores, mem = _get_cores_memory(data, downscale=2)
cmd = ("{bammarkduplicates} tmpfile={base_tmp}-markdup "
"markthreads={cores} I={in_bam} O={tx_out_file}")
do.run(cmd.format(**locals()), "De-duplication with biobambam")
bam.index(out_file, data["config"])
return out_file
else:
return in_bam | [
"def",
"dedup_bam",
"(",
"in_bam",
",",
"data",
")",
":",
"if",
"_check_dedup",
"(",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd"... | Perform non-stream based deduplication of BAM input files using biobambam. | [
"Perform",
"non",
"-",
"stream",
"based",
"deduplication",
"of",
"BAM",
"input",
"files",
"using",
"biobambam",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/postalign.py#L283-L301 | train | 218,304 |
bcbio/bcbio-nextgen | bcbio/structural/titancna.py | _finalize_sv | def _finalize_sv(solution_file, data):
"""Add output files from TitanCNA calling optional solution.
"""
out = {"variantcaller": "titancna"}
with open(solution_file) as in_handle:
solution = dict(zip(in_handle.readline().strip("\r\n").split("\t"),
in_handle.readline().strip("\r\n").split("\t")))
if solution.get("path"):
out["purity"] = solution["purity"]
out["ploidy"] = solution["ploidy"]
out["cellular_prevalence"] = [x.strip() for x in solution["cellPrev"].split(",")]
base = os.path.basename(solution["path"])
out["plot"] = dict([(n, solution["path"] + ext) for (n, ext) in [("rplots", ".Rplots.pdf"),
("cf", "/%s_CF.pdf" % base),
("cna", "/%s_CNA.pdf" % base),
("loh", "/%s_LOH.pdf" % base)]
if os.path.exists(solution["path"] + ext)])
out["subclones"] = "%s.segs.txt" % solution["path"]
out["hetsummary"] = solution_file
out["vrn_file"] = to_vcf(out["subclones"], "TitanCNA", _get_header, _seg_to_vcf, data)
out["lohsummary"] = loh.summary_status(out, data)
return out | python | def _finalize_sv(solution_file, data):
"""Add output files from TitanCNA calling optional solution.
"""
out = {"variantcaller": "titancna"}
with open(solution_file) as in_handle:
solution = dict(zip(in_handle.readline().strip("\r\n").split("\t"),
in_handle.readline().strip("\r\n").split("\t")))
if solution.get("path"):
out["purity"] = solution["purity"]
out["ploidy"] = solution["ploidy"]
out["cellular_prevalence"] = [x.strip() for x in solution["cellPrev"].split(",")]
base = os.path.basename(solution["path"])
out["plot"] = dict([(n, solution["path"] + ext) for (n, ext) in [("rplots", ".Rplots.pdf"),
("cf", "/%s_CF.pdf" % base),
("cna", "/%s_CNA.pdf" % base),
("loh", "/%s_LOH.pdf" % base)]
if os.path.exists(solution["path"] + ext)])
out["subclones"] = "%s.segs.txt" % solution["path"]
out["hetsummary"] = solution_file
out["vrn_file"] = to_vcf(out["subclones"], "TitanCNA", _get_header, _seg_to_vcf, data)
out["lohsummary"] = loh.summary_status(out, data)
return out | [
"def",
"_finalize_sv",
"(",
"solution_file",
",",
"data",
")",
":",
"out",
"=",
"{",
"\"variantcaller\"",
":",
"\"titancna\"",
"}",
"with",
"open",
"(",
"solution_file",
")",
"as",
"in_handle",
":",
"solution",
"=",
"dict",
"(",
"zip",
"(",
"in_handle",
".... | Add output files from TitanCNA calling optional solution. | [
"Add",
"output",
"files",
"from",
"TitanCNA",
"calling",
"optional",
"solution",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/titancna.py#L52-L73 | train | 218,305 |
bcbio/bcbio-nextgen | bcbio/structural/titancna.py | _should_run | def _should_run(het_file):
"""Check for enough input data to proceed with analysis.
"""
has_hets = False
with open(het_file) as in_handle:
for i, line in enumerate(in_handle):
if i > 1:
has_hets = True
break
return has_hets | python | def _should_run(het_file):
"""Check for enough input data to proceed with analysis.
"""
has_hets = False
with open(het_file) as in_handle:
for i, line in enumerate(in_handle):
if i > 1:
has_hets = True
break
return has_hets | [
"def",
"_should_run",
"(",
"het_file",
")",
":",
"has_hets",
"=",
"False",
"with",
"open",
"(",
"het_file",
")",
"as",
"in_handle",
":",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"in_handle",
")",
":",
"if",
"i",
">",
"1",
":",
"has_hets",
"="... | Check for enough input data to proceed with analysis. | [
"Check",
"for",
"enough",
"input",
"data",
"to",
"proceed",
"with",
"analysis",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/titancna.py#L75-L84 | train | 218,306 |
bcbio/bcbio-nextgen | bcbio/structural/titancna.py | _titan_cn_file | def _titan_cn_file(cnr_file, work_dir, data):
"""Convert CNVkit or GATK4 normalized input into TitanCNA ready format.
"""
out_file = os.path.join(work_dir, "%s.cn" % (utils.splitext_plus(os.path.basename(cnr_file))[0]))
support_cols = {"cnvkit": ["chromosome", "start", "end", "log2"],
"gatk-cnv": ["CONTIG", "START", "END", "LOG2_COPY_RATIO"]}
cols = support_cols[cnvkit.bin_approach(data)]
if not utils.file_uptodate(out_file, cnr_file):
with file_transaction(data, out_file) as tx_out_file:
iterator = pd.read_table(cnr_file, sep="\t", iterator=True, header=0, comment="@")
with open(tx_out_file, "w") as handle:
for chunk in iterator:
chunk = chunk[cols]
chunk.columns = ["chrom", "start", "end", "logR"]
if cnvkit.bin_approach(data) == "cnvkit":
chunk['start'] += 1
chunk.to_csv(handle, mode="a", sep="\t", index=False)
return out_file | python | def _titan_cn_file(cnr_file, work_dir, data):
"""Convert CNVkit or GATK4 normalized input into TitanCNA ready format.
"""
out_file = os.path.join(work_dir, "%s.cn" % (utils.splitext_plus(os.path.basename(cnr_file))[0]))
support_cols = {"cnvkit": ["chromosome", "start", "end", "log2"],
"gatk-cnv": ["CONTIG", "START", "END", "LOG2_COPY_RATIO"]}
cols = support_cols[cnvkit.bin_approach(data)]
if not utils.file_uptodate(out_file, cnr_file):
with file_transaction(data, out_file) as tx_out_file:
iterator = pd.read_table(cnr_file, sep="\t", iterator=True, header=0, comment="@")
with open(tx_out_file, "w") as handle:
for chunk in iterator:
chunk = chunk[cols]
chunk.columns = ["chrom", "start", "end", "logR"]
if cnvkit.bin_approach(data) == "cnvkit":
chunk['start'] += 1
chunk.to_csv(handle, mode="a", sep="\t", index=False)
return out_file | [
"def",
"_titan_cn_file",
"(",
"cnr_file",
",",
"work_dir",
",",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s.cn\"",
"%",
"(",
"utils",
".",
"splitext_plus",
"(",
"os",
".",
"path",
".",
"basename",
"(",... | Convert CNVkit or GATK4 normalized input into TitanCNA ready format. | [
"Convert",
"CNVkit",
"or",
"GATK4",
"normalized",
"input",
"into",
"TitanCNA",
"ready",
"format",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/titancna.py#L164-L181 | train | 218,307 |
bcbio/bcbio-nextgen | bcbio/structural/titancna.py | to_vcf | def to_vcf(in_file, caller, header_fn, vcf_fn, data, sep="\t"):
"""Convert output TitanCNA segs file into bgzipped VCF.
"""
out_file = "%s.vcf" % utils.splitext_plus(in_file)[0]
if not utils.file_exists(out_file + ".gz") and not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
with open(in_file) as in_handle:
with open(tx_out_file, "w") as out_handle:
out_handle.write(_vcf_header.format(caller=caller))
out_handle.write("\t".join(["#CHROM", "POS", "ID", "REF", "ALT", "QUAL",
"FILTER", "INFO", "FORMAT", dd.get_sample_name(data)]) + "\n")
header, in_handle = header_fn(in_handle)
for line in in_handle:
out = vcf_fn(dict(zip(header, line.strip().split(sep))))
if out:
out_handle.write("\t".join(out) + "\n")
out_file = vcfutils.bgzip_and_index(out_file, data["config"])
effects_vcf, _ = effects.add_to_vcf(out_file, data, "snpeff")
return effects_vcf or out_file | python | def to_vcf(in_file, caller, header_fn, vcf_fn, data, sep="\t"):
"""Convert output TitanCNA segs file into bgzipped VCF.
"""
out_file = "%s.vcf" % utils.splitext_plus(in_file)[0]
if not utils.file_exists(out_file + ".gz") and not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
with open(in_file) as in_handle:
with open(tx_out_file, "w") as out_handle:
out_handle.write(_vcf_header.format(caller=caller))
out_handle.write("\t".join(["#CHROM", "POS", "ID", "REF", "ALT", "QUAL",
"FILTER", "INFO", "FORMAT", dd.get_sample_name(data)]) + "\n")
header, in_handle = header_fn(in_handle)
for line in in_handle:
out = vcf_fn(dict(zip(header, line.strip().split(sep))))
if out:
out_handle.write("\t".join(out) + "\n")
out_file = vcfutils.bgzip_and_index(out_file, data["config"])
effects_vcf, _ = effects.add_to_vcf(out_file, data, "snpeff")
return effects_vcf or out_file | [
"def",
"to_vcf",
"(",
"in_file",
",",
"caller",
",",
"header_fn",
",",
"vcf_fn",
",",
"data",
",",
"sep",
"=",
"\"\\t\"",
")",
":",
"out_file",
"=",
"\"%s.vcf\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"[",
"0",
"]",
"if",
"not",
"u... | Convert output TitanCNA segs file into bgzipped VCF. | [
"Convert",
"output",
"TitanCNA",
"segs",
"file",
"into",
"bgzipped",
"VCF",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/titancna.py#L214-L232 | train | 218,308 |
bcbio/bcbio-nextgen | bcbio/structural/metasv.py | run | def run(items):
"""Run MetaSV if we have enough supported callers, adding output to the set of calls.
"""
assert len(items) == 1, "Expect one input to MetaSV ensemble calling"
data = items[0]
work_dir = _sv_workdir(data)
out_file = os.path.join(work_dir, "variants.vcf.gz")
cmd = _get_cmd() + ["--sample", dd.get_sample_name(data), "--reference", dd.get_ref_file(data),
"--bam", dd.get_align_bam(data), "--outdir", work_dir]
methods = []
for call in data.get("sv", []):
vcf_file = call.get("vcf_file", call.get("vrn_file", None))
if call["variantcaller"] in SUPPORTED and call["variantcaller"] not in methods and vcf_file is not None:
methods.append(call["variantcaller"])
cmd += ["--%s_vcf" % call["variantcaller"], vcf_file]
if len(methods) >= MIN_CALLERS:
if not utils.file_exists(out_file):
tx_work_dir = utils.safe_makedir(os.path.join(work_dir, "raw"))
ins_stats = shared.calc_paired_insert_stats_save(dd.get_align_bam(data),
os.path.join(tx_work_dir, "insert-stats.yaml"))
cmd += ["--workdir", tx_work_dir, "--num_threads", str(dd.get_num_cores(data))]
cmd += ["--spades", utils.which("spades.py"), "--age", utils.which("age_align")]
cmd += ["--assembly_max_tools=1", "--assembly_pad=500"]
cmd += ["--boost_sc", "--isize_mean", ins_stats["mean"], "--isize_sd", ins_stats["std"]]
do.run(cmd, "Combine variant calls with MetaSV")
filters = ("(NUM_SVTOOLS = 1 && ABS(SVLEN)>50000) || "
"(NUM_SVTOOLS = 1 && ABS(SVLEN)<4000 && BA_FLANK_PERCENT>80) || "
"(NUM_SVTOOLS = 1 && ABS(SVLEN)<4000 && BA_NUM_GOOD_REC=0) || "
"(ABS(SVLEN)<4000 && BA_NUM_GOOD_REC>2)")
filter_file = vfilter.cutoff_w_expression(out_file, filters,
data, name="ReassemblyStats", limit_regions=None)
effects_vcf, _ = effects.add_to_vcf(filter_file, data, "snpeff")
data["sv"].append({"variantcaller": "metasv",
"vrn_file": effects_vcf or filter_file})
return [data] | python | def run(items):
"""Run MetaSV if we have enough supported callers, adding output to the set of calls.
"""
assert len(items) == 1, "Expect one input to MetaSV ensemble calling"
data = items[0]
work_dir = _sv_workdir(data)
out_file = os.path.join(work_dir, "variants.vcf.gz")
cmd = _get_cmd() + ["--sample", dd.get_sample_name(data), "--reference", dd.get_ref_file(data),
"--bam", dd.get_align_bam(data), "--outdir", work_dir]
methods = []
for call in data.get("sv", []):
vcf_file = call.get("vcf_file", call.get("vrn_file", None))
if call["variantcaller"] in SUPPORTED and call["variantcaller"] not in methods and vcf_file is not None:
methods.append(call["variantcaller"])
cmd += ["--%s_vcf" % call["variantcaller"], vcf_file]
if len(methods) >= MIN_CALLERS:
if not utils.file_exists(out_file):
tx_work_dir = utils.safe_makedir(os.path.join(work_dir, "raw"))
ins_stats = shared.calc_paired_insert_stats_save(dd.get_align_bam(data),
os.path.join(tx_work_dir, "insert-stats.yaml"))
cmd += ["--workdir", tx_work_dir, "--num_threads", str(dd.get_num_cores(data))]
cmd += ["--spades", utils.which("spades.py"), "--age", utils.which("age_align")]
cmd += ["--assembly_max_tools=1", "--assembly_pad=500"]
cmd += ["--boost_sc", "--isize_mean", ins_stats["mean"], "--isize_sd", ins_stats["std"]]
do.run(cmd, "Combine variant calls with MetaSV")
filters = ("(NUM_SVTOOLS = 1 && ABS(SVLEN)>50000) || "
"(NUM_SVTOOLS = 1 && ABS(SVLEN)<4000 && BA_FLANK_PERCENT>80) || "
"(NUM_SVTOOLS = 1 && ABS(SVLEN)<4000 && BA_NUM_GOOD_REC=0) || "
"(ABS(SVLEN)<4000 && BA_NUM_GOOD_REC>2)")
filter_file = vfilter.cutoff_w_expression(out_file, filters,
data, name="ReassemblyStats", limit_regions=None)
effects_vcf, _ = effects.add_to_vcf(filter_file, data, "snpeff")
data["sv"].append({"variantcaller": "metasv",
"vrn_file": effects_vcf or filter_file})
return [data] | [
"def",
"run",
"(",
"items",
")",
":",
"assert",
"len",
"(",
"items",
")",
"==",
"1",
",",
"\"Expect one input to MetaSV ensemble calling\"",
"data",
"=",
"items",
"[",
"0",
"]",
"work_dir",
"=",
"_sv_workdir",
"(",
"data",
")",
"out_file",
"=",
"os",
".",
... | Run MetaSV if we have enough supported callers, adding output to the set of calls. | [
"Run",
"MetaSV",
"if",
"we",
"have",
"enough",
"supported",
"callers",
"adding",
"output",
"to",
"the",
"set",
"of",
"calls",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/metasv.py#L18-L52 | train | 218,309 |
bcbio/bcbio-nextgen | bcbio/rnaseq/count.py | combine_count_files | def combine_count_files(files, out_file=None, ext=".fpkm"):
"""
combine a set of count files into a single combined file
"""
files = list(files)
if not files:
return None
assert all([file_exists(x) for x in files]), \
"Some count files in %s do not exist." % files
for f in files:
assert file_exists(f), "%s does not exist or is empty." % f
col_names = [os.path.basename(x.replace(ext, "")) for x in files]
if not out_file:
out_dir = os.path.join(os.path.dirname(files[0]))
out_file = os.path.join(out_dir, "combined.counts")
if file_exists(out_file):
return out_file
logger.info("Combining count files into %s." % out_file)
row_names = []
col_vals = defaultdict(list)
for i, f in enumerate(files):
vals = []
if i == 0:
with open(f) as in_handle:
for line in in_handle:
rname, val = line.strip().split("\t")
row_names.append(rname)
vals.append(val)
else:
with open(f) as in_handle:
for line in in_handle:
_, val = line.strip().split("\t")
vals.append(val)
col_vals[col_names[i]] = vals
df = pd.DataFrame(col_vals, index=row_names)
df.to_csv(out_file, sep="\t", index_label="id")
return out_file | python | def combine_count_files(files, out_file=None, ext=".fpkm"):
"""
combine a set of count files into a single combined file
"""
files = list(files)
if not files:
return None
assert all([file_exists(x) for x in files]), \
"Some count files in %s do not exist." % files
for f in files:
assert file_exists(f), "%s does not exist or is empty." % f
col_names = [os.path.basename(x.replace(ext, "")) for x in files]
if not out_file:
out_dir = os.path.join(os.path.dirname(files[0]))
out_file = os.path.join(out_dir, "combined.counts")
if file_exists(out_file):
return out_file
logger.info("Combining count files into %s." % out_file)
row_names = []
col_vals = defaultdict(list)
for i, f in enumerate(files):
vals = []
if i == 0:
with open(f) as in_handle:
for line in in_handle:
rname, val = line.strip().split("\t")
row_names.append(rname)
vals.append(val)
else:
with open(f) as in_handle:
for line in in_handle:
_, val = line.strip().split("\t")
vals.append(val)
col_vals[col_names[i]] = vals
df = pd.DataFrame(col_vals, index=row_names)
df.to_csv(out_file, sep="\t", index_label="id")
return out_file | [
"def",
"combine_count_files",
"(",
"files",
",",
"out_file",
"=",
"None",
",",
"ext",
"=",
"\".fpkm\"",
")",
":",
"files",
"=",
"list",
"(",
"files",
")",
"if",
"not",
"files",
":",
"return",
"None",
"assert",
"all",
"(",
"[",
"file_exists",
"(",
"x",
... | combine a set of count files into a single combined file | [
"combine",
"a",
"set",
"of",
"count",
"files",
"into",
"a",
"single",
"combined",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/count.py#L13-L51 | train | 218,310 |
bcbio/bcbio-nextgen | scripts/utils/cwltool2nextflow.py | nf_step_to_process | def nf_step_to_process(step, out_handle):
"""Convert CWL step into a nextflow process.
"""
pprint.pprint(step)
directives = []
for req in step["task_definition"]["requirements"]:
if req["requirement_type"] == "docker":
directives.append("container '%s'" % req["value"])
elif req["requirement_type"] == "cpu":
directives.append("cpus %s" % req["value"])
elif req["requirement_type"] == "memory":
directives.append("memory '%s'" % req["value"])
task_id = step["task_id"]
directives = "\n ".join(directives)
inputs = "\n ".join(nf_io_to_process(step["inputs"], step["task_definition"]["inputs"],
step["scatter"]))
outputs = "\n ".join(nf_io_to_process(step["outputs"], step["task_definition"]["outputs"]))
commandline = (step["task_definition"]["baseCommand"] + " " +
" ".join([nf_input_to_cl(i) for i in step["task_definition"]["inputs"]]))
out_handle.write(_nf_process_tmpl.format(**locals())) | python | def nf_step_to_process(step, out_handle):
"""Convert CWL step into a nextflow process.
"""
pprint.pprint(step)
directives = []
for req in step["task_definition"]["requirements"]:
if req["requirement_type"] == "docker":
directives.append("container '%s'" % req["value"])
elif req["requirement_type"] == "cpu":
directives.append("cpus %s" % req["value"])
elif req["requirement_type"] == "memory":
directives.append("memory '%s'" % req["value"])
task_id = step["task_id"]
directives = "\n ".join(directives)
inputs = "\n ".join(nf_io_to_process(step["inputs"], step["task_definition"]["inputs"],
step["scatter"]))
outputs = "\n ".join(nf_io_to_process(step["outputs"], step["task_definition"]["outputs"]))
commandline = (step["task_definition"]["baseCommand"] + " " +
" ".join([nf_input_to_cl(i) for i in step["task_definition"]["inputs"]]))
out_handle.write(_nf_process_tmpl.format(**locals())) | [
"def",
"nf_step_to_process",
"(",
"step",
",",
"out_handle",
")",
":",
"pprint",
".",
"pprint",
"(",
"step",
")",
"directives",
"=",
"[",
"]",
"for",
"req",
"in",
"step",
"[",
"\"task_definition\"",
"]",
"[",
"\"requirements\"",
"]",
":",
"if",
"req",
"[... | Convert CWL step into a nextflow process. | [
"Convert",
"CWL",
"step",
"into",
"a",
"nextflow",
"process",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/cwltool2nextflow.py#L53-L74 | train | 218,311 |
bcbio/bcbio-nextgen | scripts/utils/cwltool2nextflow.py | nf_input_to_cl | def nf_input_to_cl(inp):
"""Convert an input description into command line argument.
"""
sep = " " if inp.get("separate") else ""
val = "'%s'" % inp.get("default") if inp.get("default") else "$%s" % inp["name"]
return "%s%s%s" % (inp["prefix"], sep, val) | python | def nf_input_to_cl(inp):
"""Convert an input description into command line argument.
"""
sep = " " if inp.get("separate") else ""
val = "'%s'" % inp.get("default") if inp.get("default") else "$%s" % inp["name"]
return "%s%s%s" % (inp["prefix"], sep, val) | [
"def",
"nf_input_to_cl",
"(",
"inp",
")",
":",
"sep",
"=",
"\" \"",
"if",
"inp",
".",
"get",
"(",
"\"separate\"",
")",
"else",
"\"\"",
"val",
"=",
"\"'%s'\"",
"%",
"inp",
".",
"get",
"(",
"\"default\"",
")",
"if",
"inp",
".",
"get",
"(",
"\"default\"... | Convert an input description into command line argument. | [
"Convert",
"an",
"input",
"description",
"into",
"command",
"line",
"argument",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/cwltool2nextflow.py#L107-L112 | train | 218,312 |
bcbio/bcbio-nextgen | scripts/utils/cwltool2nextflow.py | _wf_to_dict | def _wf_to_dict(wf):
"""Parse a workflow into cwl2wdl style dictionary.
"""
inputs, outputs = _get_wf_inout(wf)
out = {"name": _id_to_name(wf.tool["id"]).replace("-", "_"), "inputs": inputs,
"outputs": outputs, "steps": [], "subworkflows": [],
"requirements": []}
for step in wf.steps:
inputs, outputs = _get_step_inout(step)
inputs, scatter = _organize_step_scatter(step, inputs)
if isinstance(step.embedded_tool, cwltool.workflow.Workflow):
wf_def = _wf_to_dict(step.embedded_tool)
out["subworkflows"].append({"id": wf_def["name"], "definition": wf_def,
"inputs": inputs, "outputs": outputs, "scatter": scatter})
else:
task_def = _tool_to_dict(step.embedded_tool)
out["steps"].append({"task_id": task_def["name"], "task_definition": task_def,
"inputs": inputs, "outputs": outputs, "scatter": scatter})
return out | python | def _wf_to_dict(wf):
"""Parse a workflow into cwl2wdl style dictionary.
"""
inputs, outputs = _get_wf_inout(wf)
out = {"name": _id_to_name(wf.tool["id"]).replace("-", "_"), "inputs": inputs,
"outputs": outputs, "steps": [], "subworkflows": [],
"requirements": []}
for step in wf.steps:
inputs, outputs = _get_step_inout(step)
inputs, scatter = _organize_step_scatter(step, inputs)
if isinstance(step.embedded_tool, cwltool.workflow.Workflow):
wf_def = _wf_to_dict(step.embedded_tool)
out["subworkflows"].append({"id": wf_def["name"], "definition": wf_def,
"inputs": inputs, "outputs": outputs, "scatter": scatter})
else:
task_def = _tool_to_dict(step.embedded_tool)
out["steps"].append({"task_id": task_def["name"], "task_definition": task_def,
"inputs": inputs, "outputs": outputs, "scatter": scatter})
return out | [
"def",
"_wf_to_dict",
"(",
"wf",
")",
":",
"inputs",
",",
"outputs",
"=",
"_get_wf_inout",
"(",
"wf",
")",
"out",
"=",
"{",
"\"name\"",
":",
"_id_to_name",
"(",
"wf",
".",
"tool",
"[",
"\"id\"",
"]",
")",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
... | Parse a workflow into cwl2wdl style dictionary. | [
"Parse",
"a",
"workflow",
"into",
"cwl2wdl",
"style",
"dictionary",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/cwltool2nextflow.py#L116-L134 | train | 218,313 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _get_validate | def _get_validate(data):
"""Retrieve items to validate, from single samples or from combined joint calls.
"""
if data.get("vrn_file") and tz.get_in(["config", "algorithm", "validate"], data):
return utils.deepish_copy(data)
elif "group_orig" in data:
for sub in multi.get_orig_items(data):
if "validate" in sub["config"]["algorithm"]:
sub_val = utils.deepish_copy(sub)
sub_val["vrn_file"] = data["vrn_file"]
return sub_val
return None | python | def _get_validate(data):
"""Retrieve items to validate, from single samples or from combined joint calls.
"""
if data.get("vrn_file") and tz.get_in(["config", "algorithm", "validate"], data):
return utils.deepish_copy(data)
elif "group_orig" in data:
for sub in multi.get_orig_items(data):
if "validate" in sub["config"]["algorithm"]:
sub_val = utils.deepish_copy(sub)
sub_val["vrn_file"] = data["vrn_file"]
return sub_val
return None | [
"def",
"_get_validate",
"(",
"data",
")",
":",
"if",
"data",
".",
"get",
"(",
"\"vrn_file\"",
")",
"and",
"tz",
".",
"get_in",
"(",
"[",
"\"config\"",
",",
"\"algorithm\"",
",",
"\"validate\"",
"]",
",",
"data",
")",
":",
"return",
"utils",
".",
"deepi... | Retrieve items to validate, from single samples or from combined joint calls. | [
"Retrieve",
"items",
"to",
"validate",
"from",
"single",
"samples",
"or",
"from",
"combined",
"joint",
"calls",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L31-L42 | train | 218,314 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | normalize_input_path | def normalize_input_path(x, data):
"""Normalize path for input files, handling relative paths.
Looks for non-absolute paths in local and fastq directories
"""
if x is None:
return None
elif os.path.isabs(x):
return os.path.normpath(x)
else:
for d in [data["dirs"].get("fastq"), data["dirs"].get("work")]:
if d:
cur_x = os.path.normpath(os.path.join(d, x))
if os.path.exists(cur_x):
return cur_x
raise IOError("Could not find validation file %s" % x) | python | def normalize_input_path(x, data):
"""Normalize path for input files, handling relative paths.
Looks for non-absolute paths in local and fastq directories
"""
if x is None:
return None
elif os.path.isabs(x):
return os.path.normpath(x)
else:
for d in [data["dirs"].get("fastq"), data["dirs"].get("work")]:
if d:
cur_x = os.path.normpath(os.path.join(d, x))
if os.path.exists(cur_x):
return cur_x
raise IOError("Could not find validation file %s" % x) | [
"def",
"normalize_input_path",
"(",
"x",
",",
"data",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"None",
"elif",
"os",
".",
"path",
".",
"isabs",
"(",
"x",
")",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"x",
")",
"else",
":",... | Normalize path for input files, handling relative paths.
Looks for non-absolute paths in local and fastq directories | [
"Normalize",
"path",
"for",
"input",
"files",
"handling",
"relative",
"paths",
".",
"Looks",
"for",
"non",
"-",
"absolute",
"paths",
"in",
"local",
"and",
"fastq",
"directories"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L44-L58 | train | 218,315 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _get_caller_supplement | def _get_caller_supplement(caller, data):
"""Some callers like MuTect incorporate a second caller for indels.
"""
if caller == "mutect":
icaller = tz.get_in(["config", "algorithm", "indelcaller"], data)
if icaller:
caller = "%s/%s" % (caller, icaller)
return caller | python | def _get_caller_supplement(caller, data):
"""Some callers like MuTect incorporate a second caller for indels.
"""
if caller == "mutect":
icaller = tz.get_in(["config", "algorithm", "indelcaller"], data)
if icaller:
caller = "%s/%s" % (caller, icaller)
return caller | [
"def",
"_get_caller_supplement",
"(",
"caller",
",",
"data",
")",
":",
"if",
"caller",
"==",
"\"mutect\"",
":",
"icaller",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"config\"",
",",
"\"algorithm\"",
",",
"\"indelcaller\"",
"]",
",",
"data",
")",
"if",
"icaller... | Some callers like MuTect incorporate a second caller for indels. | [
"Some",
"callers",
"like",
"MuTect",
"incorporate",
"a",
"second",
"caller",
"for",
"indels",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L84-L91 | train | 218,316 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _pick_lead_item | def _pick_lead_item(items):
"""Choose lead item for a set of samples.
Picks tumors for tumor/normal pairs and first sample for batch groups.
"""
paired = vcfutils.get_paired(items)
if paired:
return paired.tumor_data
else:
return list(items)[0] | python | def _pick_lead_item(items):
"""Choose lead item for a set of samples.
Picks tumors for tumor/normal pairs and first sample for batch groups.
"""
paired = vcfutils.get_paired(items)
if paired:
return paired.tumor_data
else:
return list(items)[0] | [
"def",
"_pick_lead_item",
"(",
"items",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired",
"(",
"items",
")",
"if",
"paired",
":",
"return",
"paired",
".",
"tumor_data",
"else",
":",
"return",
"list",
"(",
"items",
")",
"[",
"0",
"]"
] | Choose lead item for a set of samples.
Picks tumors for tumor/normal pairs and first sample for batch groups. | [
"Choose",
"lead",
"item",
"for",
"a",
"set",
"of",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L93-L102 | train | 218,317 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _normalize_cwl_inputs | def _normalize_cwl_inputs(items):
"""Extract variation and validation data from CWL input list of batched samples.
"""
with_validate = {}
vrn_files = []
ready_items = []
batch_samples = []
for data in (cwlutils.normalize_missing(utils.to_single_data(d)) for d in items):
batch_samples.append(dd.get_sample_name(data))
if tz.get_in(["config", "algorithm", "validate"], data):
with_validate[_checksum(tz.get_in(["config", "algorithm", "validate"], data))] = data
if data.get("vrn_file"):
vrn_files.append(data["vrn_file"])
ready_items.append(data)
if len(with_validate) == 0:
data = _pick_lead_item(ready_items)
data["batch_samples"] = batch_samples
return data
else:
assert len(with_validate) == 1, len(with_validate)
assert len(set(vrn_files)) == 1, set(vrn_files)
data = _pick_lead_item(with_validate.values())
data["batch_samples"] = batch_samples
data["vrn_file"] = vrn_files[0]
return data | python | def _normalize_cwl_inputs(items):
"""Extract variation and validation data from CWL input list of batched samples.
"""
with_validate = {}
vrn_files = []
ready_items = []
batch_samples = []
for data in (cwlutils.normalize_missing(utils.to_single_data(d)) for d in items):
batch_samples.append(dd.get_sample_name(data))
if tz.get_in(["config", "algorithm", "validate"], data):
with_validate[_checksum(tz.get_in(["config", "algorithm", "validate"], data))] = data
if data.get("vrn_file"):
vrn_files.append(data["vrn_file"])
ready_items.append(data)
if len(with_validate) == 0:
data = _pick_lead_item(ready_items)
data["batch_samples"] = batch_samples
return data
else:
assert len(with_validate) == 1, len(with_validate)
assert len(set(vrn_files)) == 1, set(vrn_files)
data = _pick_lead_item(with_validate.values())
data["batch_samples"] = batch_samples
data["vrn_file"] = vrn_files[0]
return data | [
"def",
"_normalize_cwl_inputs",
"(",
"items",
")",
":",
"with_validate",
"=",
"{",
"}",
"vrn_files",
"=",
"[",
"]",
"ready_items",
"=",
"[",
"]",
"batch_samples",
"=",
"[",
"]",
"for",
"data",
"in",
"(",
"cwlutils",
".",
"normalize_missing",
"(",
"utils",
... | Extract variation and validation data from CWL input list of batched samples. | [
"Extract",
"variation",
"and",
"validation",
"data",
"from",
"CWL",
"input",
"list",
"of",
"batched",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L104-L128 | train | 218,318 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | compare_to_rm | def compare_to_rm(data):
"""Compare final variant calls against reference materials of known calls.
"""
if isinstance(data, (list, tuple)) and cwlutils.is_cwl_run(utils.to_single_data(data[0])):
data = _normalize_cwl_inputs(data)
toval_data = _get_validate(data)
toval_data = cwlutils.unpack_tarballs(toval_data, toval_data)
if toval_data:
caller = _get_caller(toval_data)
sample = dd.get_sample_name(toval_data)
base_dir = utils.safe_makedir(os.path.join(toval_data["dirs"]["work"], "validate", sample, caller))
if isinstance(toval_data["vrn_file"], (list, tuple)):
raise NotImplementedError("Multiple input files for validation: %s" % toval_data["vrn_file"])
else:
vrn_file = os.path.abspath(toval_data["vrn_file"])
rm_file = normalize_input_path(toval_data["config"]["algorithm"]["validate"], toval_data)
rm_interval_file = _gunzip(normalize_input_path(toval_data["config"]["algorithm"].get("validate_regions"),
toval_data),
toval_data)
rm_interval_file = bedutils.clean_file(rm_interval_file, toval_data, prefix="validateregions-",
bedprep_dir=utils.safe_makedir(os.path.join(base_dir, "bedprep")))
rm_file = naming.handle_synonyms(rm_file, dd.get_ref_file(toval_data), data.get("genome_build"),
base_dir, data)
rm_interval_file = (naming.handle_synonyms(rm_interval_file, dd.get_ref_file(toval_data),
data.get("genome_build"), base_dir, data)
if rm_interval_file else None)
vmethod = tz.get_in(["config", "algorithm", "validate_method"], data, "rtg")
# RTG can fail on totally empty files. Call everything in truth set as false negatives
if not vcfutils.vcf_has_variants(vrn_file):
eval_files = _setup_call_false(rm_file, rm_interval_file, base_dir, toval_data, "fn")
data["validate"] = _rtg_add_summary_file(eval_files, base_dir, toval_data)
# empty validation file, every call is a false positive
elif not vcfutils.vcf_has_variants(rm_file):
eval_files = _setup_call_fps(vrn_file, rm_interval_file, base_dir, toval_data, "fp")
data["validate"] = _rtg_add_summary_file(eval_files, base_dir, toval_data)
elif vmethod in ["rtg", "rtg-squash-ploidy"]:
eval_files = _run_rtg_eval(vrn_file, rm_file, rm_interval_file, base_dir, toval_data, vmethod)
eval_files = _annotate_validations(eval_files, toval_data)
data["validate"] = _rtg_add_summary_file(eval_files, base_dir, toval_data)
elif vmethod == "hap.py":
data["validate"] = _run_happy_eval(vrn_file, rm_file, rm_interval_file, base_dir, toval_data)
elif vmethod == "bcbio.variation":
data["validate"] = _run_bcbio_variation(vrn_file, rm_file, rm_interval_file, base_dir,
sample, caller, toval_data)
return [[data]] | python | def compare_to_rm(data):
"""Compare final variant calls against reference materials of known calls.
"""
if isinstance(data, (list, tuple)) and cwlutils.is_cwl_run(utils.to_single_data(data[0])):
data = _normalize_cwl_inputs(data)
toval_data = _get_validate(data)
toval_data = cwlutils.unpack_tarballs(toval_data, toval_data)
if toval_data:
caller = _get_caller(toval_data)
sample = dd.get_sample_name(toval_data)
base_dir = utils.safe_makedir(os.path.join(toval_data["dirs"]["work"], "validate", sample, caller))
if isinstance(toval_data["vrn_file"], (list, tuple)):
raise NotImplementedError("Multiple input files for validation: %s" % toval_data["vrn_file"])
else:
vrn_file = os.path.abspath(toval_data["vrn_file"])
rm_file = normalize_input_path(toval_data["config"]["algorithm"]["validate"], toval_data)
rm_interval_file = _gunzip(normalize_input_path(toval_data["config"]["algorithm"].get("validate_regions"),
toval_data),
toval_data)
rm_interval_file = bedutils.clean_file(rm_interval_file, toval_data, prefix="validateregions-",
bedprep_dir=utils.safe_makedir(os.path.join(base_dir, "bedprep")))
rm_file = naming.handle_synonyms(rm_file, dd.get_ref_file(toval_data), data.get("genome_build"),
base_dir, data)
rm_interval_file = (naming.handle_synonyms(rm_interval_file, dd.get_ref_file(toval_data),
data.get("genome_build"), base_dir, data)
if rm_interval_file else None)
vmethod = tz.get_in(["config", "algorithm", "validate_method"], data, "rtg")
# RTG can fail on totally empty files. Call everything in truth set as false negatives
if not vcfutils.vcf_has_variants(vrn_file):
eval_files = _setup_call_false(rm_file, rm_interval_file, base_dir, toval_data, "fn")
data["validate"] = _rtg_add_summary_file(eval_files, base_dir, toval_data)
# empty validation file, every call is a false positive
elif not vcfutils.vcf_has_variants(rm_file):
eval_files = _setup_call_fps(vrn_file, rm_interval_file, base_dir, toval_data, "fp")
data["validate"] = _rtg_add_summary_file(eval_files, base_dir, toval_data)
elif vmethod in ["rtg", "rtg-squash-ploidy"]:
eval_files = _run_rtg_eval(vrn_file, rm_file, rm_interval_file, base_dir, toval_data, vmethod)
eval_files = _annotate_validations(eval_files, toval_data)
data["validate"] = _rtg_add_summary_file(eval_files, base_dir, toval_data)
elif vmethod == "hap.py":
data["validate"] = _run_happy_eval(vrn_file, rm_file, rm_interval_file, base_dir, toval_data)
elif vmethod == "bcbio.variation":
data["validate"] = _run_bcbio_variation(vrn_file, rm_file, rm_interval_file, base_dir,
sample, caller, toval_data)
return [[data]] | [
"def",
"compare_to_rm",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"cwlutils",
".",
"is_cwl_run",
"(",
"utils",
".",
"to_single_data",
"(",
"data",
"[",
"0",
"]",
")",
")",
":",
"data",
... | Compare final variant calls against reference materials of known calls. | [
"Compare",
"final",
"variant",
"calls",
"against",
"reference",
"materials",
"of",
"known",
"calls",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L139-L184 | train | 218,319 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _annotate_validations | def _annotate_validations(eval_files, data):
"""Add annotations about potential problem regions to validation VCFs.
"""
for key in ["tp", "tp-calls", "fp", "fn"]:
if eval_files.get(key):
eval_files[key] = annotation.add_genome_context(eval_files[key], data)
return eval_files | python | def _annotate_validations(eval_files, data):
"""Add annotations about potential problem regions to validation VCFs.
"""
for key in ["tp", "tp-calls", "fp", "fn"]:
if eval_files.get(key):
eval_files[key] = annotation.add_genome_context(eval_files[key], data)
return eval_files | [
"def",
"_annotate_validations",
"(",
"eval_files",
",",
"data",
")",
":",
"for",
"key",
"in",
"[",
"\"tp\"",
",",
"\"tp-calls\"",
",",
"\"fp\"",
",",
"\"fn\"",
"]",
":",
"if",
"eval_files",
".",
"get",
"(",
"key",
")",
":",
"eval_files",
"[",
"key",
"]... | Add annotations about potential problem regions to validation VCFs. | [
"Add",
"annotations",
"about",
"potential",
"problem",
"regions",
"to",
"validation",
"VCFs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L186-L192 | train | 218,320 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _setup_call_false | def _setup_call_false(vrn_file, rm_bed, base_dir, data, call_type):
"""Create set of false positives or ngatives for inputs with empty truth sets.
"""
out_file = os.path.join(base_dir, "%s.vcf.gz" % call_type)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
if not vrn_file.endswith(".gz"):
vrn_file = vcfutils.bgzip_and_index(vrn_file, out_dir=os.path.dirname(tx_out_file))
cmd = ("bcftools view -R {rm_bed} -f 'PASS,.' {vrn_file} -O z -o {tx_out_file}")
do.run(cmd.format(**locals()), "Prepare %s with empty reference" % call_type, data)
return {call_type: out_file} | python | def _setup_call_false(vrn_file, rm_bed, base_dir, data, call_type):
"""Create set of false positives or ngatives for inputs with empty truth sets.
"""
out_file = os.path.join(base_dir, "%s.vcf.gz" % call_type)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
if not vrn_file.endswith(".gz"):
vrn_file = vcfutils.bgzip_and_index(vrn_file, out_dir=os.path.dirname(tx_out_file))
cmd = ("bcftools view -R {rm_bed} -f 'PASS,.' {vrn_file} -O z -o {tx_out_file}")
do.run(cmd.format(**locals()), "Prepare %s with empty reference" % call_type, data)
return {call_type: out_file} | [
"def",
"_setup_call_false",
"(",
"vrn_file",
",",
"rm_bed",
",",
"base_dir",
",",
"data",
",",
"call_type",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"\"%s.vcf.gz\"",
"%",
"call_type",
")",
"if",
"not",
"utils",
"."... | Create set of false positives or ngatives for inputs with empty truth sets. | [
"Create",
"set",
"of",
"false",
"positives",
"or",
"ngatives",
"for",
"inputs",
"with",
"empty",
"truth",
"sets",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L196-L206 | train | 218,321 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _rtg_add_summary_file | def _rtg_add_summary_file(eval_files, base_dir, data):
"""Parse output TP FP and FN files to generate metrics for plotting.
"""
out_file = os.path.join(base_dir, "validate-summary.csv")
if not utils.file_uptodate(out_file, eval_files.get("tp", eval_files.get("fp", eval_files["fn"]))):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
writer = csv.writer(out_handle)
writer.writerow(["sample", "caller", "vtype", "metric", "value"])
base = _get_sample_and_caller(data)
for metric in ["tp", "fp", "fn"]:
for vtype, bcftools_types in [("SNPs", "--types snps"),
("Indels", "--exclude-types snps")]:
in_file = eval_files.get(metric)
if in_file and os.path.exists(in_file):
cmd = ("bcftools view {bcftools_types} {in_file} | grep -v ^# | wc -l")
count = int(subprocess.check_output(cmd.format(**locals()), shell=True))
else:
count = 0
writer.writerow(base + [vtype, metric, count])
eval_files["summary"] = out_file
return eval_files | python | def _rtg_add_summary_file(eval_files, base_dir, data):
"""Parse output TP FP and FN files to generate metrics for plotting.
"""
out_file = os.path.join(base_dir, "validate-summary.csv")
if not utils.file_uptodate(out_file, eval_files.get("tp", eval_files.get("fp", eval_files["fn"]))):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
writer = csv.writer(out_handle)
writer.writerow(["sample", "caller", "vtype", "metric", "value"])
base = _get_sample_and_caller(data)
for metric in ["tp", "fp", "fn"]:
for vtype, bcftools_types in [("SNPs", "--types snps"),
("Indels", "--exclude-types snps")]:
in_file = eval_files.get(metric)
if in_file and os.path.exists(in_file):
cmd = ("bcftools view {bcftools_types} {in_file} | grep -v ^# | wc -l")
count = int(subprocess.check_output(cmd.format(**locals()), shell=True))
else:
count = 0
writer.writerow(base + [vtype, metric, count])
eval_files["summary"] = out_file
return eval_files | [
"def",
"_rtg_add_summary_file",
"(",
"eval_files",
",",
"base_dir",
",",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"\"validate-summary.csv\"",
")",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",... | Parse output TP FP and FN files to generate metrics for plotting. | [
"Parse",
"output",
"TP",
"FP",
"and",
"FN",
"files",
"to",
"generate",
"metrics",
"for",
"plotting",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L214-L235 | train | 218,322 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _prepare_inputs | def _prepare_inputs(vrn_file, rm_file, rm_interval_file, base_dir, data):
"""Prepare input VCF and BED files for validation.
"""
if not rm_file.endswith(".vcf.gz") or not os.path.exists(rm_file + ".tbi"):
rm_file = vcfutils.bgzip_and_index(rm_file, data["config"], out_dir=base_dir)
if len(vcfutils.get_samples(vrn_file)) > 1:
base = utils.splitext_plus(os.path.basename(vrn_file))[0]
sample_file = os.path.join(base_dir, "%s-%s.vcf.gz" % (base, dd.get_sample_name(data)))
vrn_file = vcfutils.select_sample(vrn_file, dd.get_sample_name(data), sample_file, data["config"])
# rtg fails on bgzipped VCFs produced by GatherVcfs so we re-prep them
else:
vrn_file = vcfutils.bgzip_and_index(vrn_file, data["config"], out_dir=base_dir)
interval_bed = _get_merged_intervals(rm_interval_file, vrn_file, base_dir, data)
return vrn_file, rm_file, interval_bed | python | def _prepare_inputs(vrn_file, rm_file, rm_interval_file, base_dir, data):
"""Prepare input VCF and BED files for validation.
"""
if not rm_file.endswith(".vcf.gz") or not os.path.exists(rm_file + ".tbi"):
rm_file = vcfutils.bgzip_and_index(rm_file, data["config"], out_dir=base_dir)
if len(vcfutils.get_samples(vrn_file)) > 1:
base = utils.splitext_plus(os.path.basename(vrn_file))[0]
sample_file = os.path.join(base_dir, "%s-%s.vcf.gz" % (base, dd.get_sample_name(data)))
vrn_file = vcfutils.select_sample(vrn_file, dd.get_sample_name(data), sample_file, data["config"])
# rtg fails on bgzipped VCFs produced by GatherVcfs so we re-prep them
else:
vrn_file = vcfutils.bgzip_and_index(vrn_file, data["config"], out_dir=base_dir)
interval_bed = _get_merged_intervals(rm_interval_file, vrn_file, base_dir, data)
return vrn_file, rm_file, interval_bed | [
"def",
"_prepare_inputs",
"(",
"vrn_file",
",",
"rm_file",
",",
"rm_interval_file",
",",
"base_dir",
",",
"data",
")",
":",
"if",
"not",
"rm_file",
".",
"endswith",
"(",
"\".vcf.gz\"",
")",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"rm_file",
"... | Prepare input VCF and BED files for validation. | [
"Prepare",
"input",
"VCF",
"and",
"BED",
"files",
"for",
"validation",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L237-L251 | train | 218,323 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _pick_best_quality_score | def _pick_best_quality_score(vrn_file):
"""Flexible quality score selection, picking the best available.
Implementation based on discussion:
https://github.com/bcbio/bcbio-nextgen/commit/a538cecd86c0000d17d3f9d4f8ac9d2da04f9884#commitcomment-14539249
(RTG=AVR/GATK=VQSLOD/MuTect=t_lod_fstar, otherwise GQ, otherwise QUAL, otherwise DP.)
For MuTect, it's not clear how to get t_lod_fstar, the right quality score, into VCF cleanly.
MuTect2 has TLOD in the INFO field.
"""
# pysam fails on checking reference contigs if input is empty
if not vcfutils.vcf_has_variants(vrn_file):
return "DP"
to_check = 25
scores = collections.defaultdict(int)
try:
in_handle = VariantFile(vrn_file)
except ValueError:
raise ValueError("Failed to parse input file in preparation for validation: %s" % vrn_file)
with contextlib.closing(in_handle) as val_in:
for i, rec in enumerate(val_in):
if i > to_check:
break
if "VQSLOD" in rec.info and rec.info.get("VQSLOD") is not None:
scores["INFO=VQSLOD"] += 1
if "TLOD" in rec.info and rec.info.get("TLOD") is not None:
scores["INFO=TLOD"] += 1
for skey in ["AVR", "GQ", "DP"]:
if len(rec.samples) > 0 and rec.samples[0].get(skey) is not None:
scores[skey] += 1
if rec.qual:
scores["QUAL"] += 1
for key in ["AVR", "INFO=VQSLOD", "INFO=TLOD", "GQ", "QUAL", "DP"]:
if scores[key] > 0:
return key
raise ValueError("Did not find quality score for validation from %s" % vrn_file) | python | def _pick_best_quality_score(vrn_file):
"""Flexible quality score selection, picking the best available.
Implementation based on discussion:
https://github.com/bcbio/bcbio-nextgen/commit/a538cecd86c0000d17d3f9d4f8ac9d2da04f9884#commitcomment-14539249
(RTG=AVR/GATK=VQSLOD/MuTect=t_lod_fstar, otherwise GQ, otherwise QUAL, otherwise DP.)
For MuTect, it's not clear how to get t_lod_fstar, the right quality score, into VCF cleanly.
MuTect2 has TLOD in the INFO field.
"""
# pysam fails on checking reference contigs if input is empty
if not vcfutils.vcf_has_variants(vrn_file):
return "DP"
to_check = 25
scores = collections.defaultdict(int)
try:
in_handle = VariantFile(vrn_file)
except ValueError:
raise ValueError("Failed to parse input file in preparation for validation: %s" % vrn_file)
with contextlib.closing(in_handle) as val_in:
for i, rec in enumerate(val_in):
if i > to_check:
break
if "VQSLOD" in rec.info and rec.info.get("VQSLOD") is not None:
scores["INFO=VQSLOD"] += 1
if "TLOD" in rec.info and rec.info.get("TLOD") is not None:
scores["INFO=TLOD"] += 1
for skey in ["AVR", "GQ", "DP"]:
if len(rec.samples) > 0 and rec.samples[0].get(skey) is not None:
scores[skey] += 1
if rec.qual:
scores["QUAL"] += 1
for key in ["AVR", "INFO=VQSLOD", "INFO=TLOD", "GQ", "QUAL", "DP"]:
if scores[key] > 0:
return key
raise ValueError("Did not find quality score for validation from %s" % vrn_file) | [
"def",
"_pick_best_quality_score",
"(",
"vrn_file",
")",
":",
"# pysam fails on checking reference contigs if input is empty",
"if",
"not",
"vcfutils",
".",
"vcf_has_variants",
"(",
"vrn_file",
")",
":",
"return",
"\"DP\"",
"to_check",
"=",
"25",
"scores",
"=",
"collect... | Flexible quality score selection, picking the best available.
Implementation based on discussion:
https://github.com/bcbio/bcbio-nextgen/commit/a538cecd86c0000d17d3f9d4f8ac9d2da04f9884#commitcomment-14539249
(RTG=AVR/GATK=VQSLOD/MuTect=t_lod_fstar, otherwise GQ, otherwise QUAL, otherwise DP.)
For MuTect, it's not clear how to get t_lod_fstar, the right quality score, into VCF cleanly.
MuTect2 has TLOD in the INFO field. | [
"Flexible",
"quality",
"score",
"selection",
"picking",
"the",
"best",
"available",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L305-L342 | train | 218,324 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _get_merged_intervals | def _get_merged_intervals(rm_interval_file, vrn_file, base_dir, data):
"""Retrieve intervals to run validation on, merging reference and callable BED files.
"""
a_intervals = get_analysis_intervals(data, vrn_file, base_dir)
if a_intervals:
final_intervals = shared.remove_lcr_regions(a_intervals, [data])
if rm_interval_file:
caller = _get_caller(data)
sample = dd.get_sample_name(data)
combo_intervals = os.path.join(base_dir, "%s-%s-%s-wrm.bed" %
(utils.splitext_plus(os.path.basename(final_intervals))[0],
sample, caller))
if not utils.file_uptodate(combo_intervals, final_intervals):
with file_transaction(data, combo_intervals) as tx_out_file:
with utils.chdir(os.path.dirname(tx_out_file)):
# Copy files locally to avoid issues on shared filesystems
# where BEDtools has trouble accessing the same base
# files from multiple locations
a = os.path.basename(final_intervals)
b = os.path.basename(rm_interval_file)
try:
shutil.copyfile(final_intervals, a)
except IOError:
time.sleep(60)
shutil.copyfile(final_intervals, a)
try:
shutil.copyfile(rm_interval_file, b)
except IOError:
time.sleep(60)
shutil.copyfile(rm_interval_file, b)
cmd = ("bedtools intersect -nonamecheck -a {a} -b {b} > {tx_out_file}")
do.run(cmd.format(**locals()), "Intersect callable intervals for rtg vcfeval")
final_intervals = combo_intervals
else:
assert rm_interval_file, "No intervals to subset analysis with for %s" % vrn_file
final_intervals = shared.remove_lcr_regions(rm_interval_file, [data])
return final_intervals | python | def _get_merged_intervals(rm_interval_file, vrn_file, base_dir, data):
"""Retrieve intervals to run validation on, merging reference and callable BED files.
"""
a_intervals = get_analysis_intervals(data, vrn_file, base_dir)
if a_intervals:
final_intervals = shared.remove_lcr_regions(a_intervals, [data])
if rm_interval_file:
caller = _get_caller(data)
sample = dd.get_sample_name(data)
combo_intervals = os.path.join(base_dir, "%s-%s-%s-wrm.bed" %
(utils.splitext_plus(os.path.basename(final_intervals))[0],
sample, caller))
if not utils.file_uptodate(combo_intervals, final_intervals):
with file_transaction(data, combo_intervals) as tx_out_file:
with utils.chdir(os.path.dirname(tx_out_file)):
# Copy files locally to avoid issues on shared filesystems
# where BEDtools has trouble accessing the same base
# files from multiple locations
a = os.path.basename(final_intervals)
b = os.path.basename(rm_interval_file)
try:
shutil.copyfile(final_intervals, a)
except IOError:
time.sleep(60)
shutil.copyfile(final_intervals, a)
try:
shutil.copyfile(rm_interval_file, b)
except IOError:
time.sleep(60)
shutil.copyfile(rm_interval_file, b)
cmd = ("bedtools intersect -nonamecheck -a {a} -b {b} > {tx_out_file}")
do.run(cmd.format(**locals()), "Intersect callable intervals for rtg vcfeval")
final_intervals = combo_intervals
else:
assert rm_interval_file, "No intervals to subset analysis with for %s" % vrn_file
final_intervals = shared.remove_lcr_regions(rm_interval_file, [data])
return final_intervals | [
"def",
"_get_merged_intervals",
"(",
"rm_interval_file",
",",
"vrn_file",
",",
"base_dir",
",",
"data",
")",
":",
"a_intervals",
"=",
"get_analysis_intervals",
"(",
"data",
",",
"vrn_file",
",",
"base_dir",
")",
"if",
"a_intervals",
":",
"final_intervals",
"=",
... | Retrieve intervals to run validation on, merging reference and callable BED files. | [
"Retrieve",
"intervals",
"to",
"run",
"validation",
"on",
"merging",
"reference",
"and",
"callable",
"BED",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L344-L380 | train | 218,325 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _callable_from_gvcf | def _callable_from_gvcf(data, vrn_file, out_dir):
"""Retrieve callable regions based on ref call regions in gVCF.
Uses https://github.com/lijiayong/gvcf_regions
"""
methods = {"freebayes": "freebayes", "platypus": "platypus",
"gatk-haplotype": "gatk"}
gvcf_type = methods.get(dd.get_variantcaller(data))
if gvcf_type:
out_file = os.path.join(out_dir, "%s-gcvf-coverage.bed" %
utils.splitext_plus(os.path.basename(vrn_file))[0])
if not utils.file_uptodate(out_file, vrn_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ("gvcf_regions.py --gvcf_type {gvcf_type} {vrn_file} "
"| bedtools merge > {tx_out_file}")
do.run(cmd.format(**locals()), "Convert gVCF to BED file of callable regions")
return out_file | python | def _callable_from_gvcf(data, vrn_file, out_dir):
"""Retrieve callable regions based on ref call regions in gVCF.
Uses https://github.com/lijiayong/gvcf_regions
"""
methods = {"freebayes": "freebayes", "platypus": "platypus",
"gatk-haplotype": "gatk"}
gvcf_type = methods.get(dd.get_variantcaller(data))
if gvcf_type:
out_file = os.path.join(out_dir, "%s-gcvf-coverage.bed" %
utils.splitext_plus(os.path.basename(vrn_file))[0])
if not utils.file_uptodate(out_file, vrn_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ("gvcf_regions.py --gvcf_type {gvcf_type} {vrn_file} "
"| bedtools merge > {tx_out_file}")
do.run(cmd.format(**locals()), "Convert gVCF to BED file of callable regions")
return out_file | [
"def",
"_callable_from_gvcf",
"(",
"data",
",",
"vrn_file",
",",
"out_dir",
")",
":",
"methods",
"=",
"{",
"\"freebayes\"",
":",
"\"freebayes\"",
",",
"\"platypus\"",
":",
"\"platypus\"",
",",
"\"gatk-haplotype\"",
":",
"\"gatk\"",
"}",
"gvcf_type",
"=",
"method... | Retrieve callable regions based on ref call regions in gVCF.
Uses https://github.com/lijiayong/gvcf_regions | [
"Retrieve",
"callable",
"regions",
"based",
"on",
"ref",
"call",
"regions",
"in",
"gVCF",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L382-L398 | train | 218,326 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | get_analysis_intervals | def get_analysis_intervals(data, vrn_file, base_dir):
"""Retrieve analysis regions for the current variant calling pipeline.
"""
from bcbio.bam import callable
if vrn_file and vcfutils.is_gvcf_file(vrn_file):
callable_bed = _callable_from_gvcf(data, vrn_file, base_dir)
if callable_bed:
return callable_bed
if data.get("ensemble_bed"):
return data["ensemble_bed"]
elif dd.get_sample_callable(data):
return dd.get_sample_callable(data)
elif data.get("align_bam"):
return callable.sample_callable_bed(data["align_bam"], dd.get_ref_file(data), data)[0]
elif data.get("work_bam"):
return callable.sample_callable_bed(data["work_bam"], dd.get_ref_file(data), data)[0]
elif data.get("work_bam_callable"):
data = utils.deepish_copy(data)
data["work_bam"] = data.pop("work_bam_callable")
return callable.sample_callable_bed(data["work_bam"], dd.get_ref_file(data), data)[0]
elif tz.get_in(["config", "algorithm", "callable_regions"], data):
return tz.get_in(["config", "algorithm", "callable_regions"], data)
elif tz.get_in(["config", "algorithm", "variant_regions"], data):
return tz.get_in(["config", "algorithm", "variant_regions"], data) | python | def get_analysis_intervals(data, vrn_file, base_dir):
"""Retrieve analysis regions for the current variant calling pipeline.
"""
from bcbio.bam import callable
if vrn_file and vcfutils.is_gvcf_file(vrn_file):
callable_bed = _callable_from_gvcf(data, vrn_file, base_dir)
if callable_bed:
return callable_bed
if data.get("ensemble_bed"):
return data["ensemble_bed"]
elif dd.get_sample_callable(data):
return dd.get_sample_callable(data)
elif data.get("align_bam"):
return callable.sample_callable_bed(data["align_bam"], dd.get_ref_file(data), data)[0]
elif data.get("work_bam"):
return callable.sample_callable_bed(data["work_bam"], dd.get_ref_file(data), data)[0]
elif data.get("work_bam_callable"):
data = utils.deepish_copy(data)
data["work_bam"] = data.pop("work_bam_callable")
return callable.sample_callable_bed(data["work_bam"], dd.get_ref_file(data), data)[0]
elif tz.get_in(["config", "algorithm", "callable_regions"], data):
return tz.get_in(["config", "algorithm", "callable_regions"], data)
elif tz.get_in(["config", "algorithm", "variant_regions"], data):
return tz.get_in(["config", "algorithm", "variant_regions"], data) | [
"def",
"get_analysis_intervals",
"(",
"data",
",",
"vrn_file",
",",
"base_dir",
")",
":",
"from",
"bcbio",
".",
"bam",
"import",
"callable",
"if",
"vrn_file",
"and",
"vcfutils",
".",
"is_gvcf_file",
"(",
"vrn_file",
")",
":",
"callable_bed",
"=",
"_callable_fr... | Retrieve analysis regions for the current variant calling pipeline. | [
"Retrieve",
"analysis",
"regions",
"for",
"the",
"current",
"variant",
"calling",
"pipeline",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L400-L424 | train | 218,327 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _get_location_list | def _get_location_list(interval_bed):
"""Retrieve list of locations to analyze from input BED file.
"""
import pybedtools
regions = collections.OrderedDict()
for region in pybedtools.BedTool(interval_bed):
regions[str(region.chrom)] = None
return regions.keys() | python | def _get_location_list(interval_bed):
"""Retrieve list of locations to analyze from input BED file.
"""
import pybedtools
regions = collections.OrderedDict()
for region in pybedtools.BedTool(interval_bed):
regions[str(region.chrom)] = None
return regions.keys() | [
"def",
"_get_location_list",
"(",
"interval_bed",
")",
":",
"import",
"pybedtools",
"regions",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"region",
"in",
"pybedtools",
".",
"BedTool",
"(",
"interval_bed",
")",
":",
"regions",
"[",
"str",
"(",
"... | Retrieve list of locations to analyze from input BED file. | [
"Retrieve",
"list",
"of",
"locations",
"to",
"analyze",
"from",
"input",
"BED",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L443-L450 | train | 218,328 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _run_bcbio_variation | def _run_bcbio_variation(vrn_file, rm_file, rm_interval_file, base_dir, sample, caller, data):
"""Run validation of a caller against the truth set using bcbio.variation.
"""
val_config_file = _create_validate_config_file(vrn_file, rm_file, rm_interval_file,
base_dir, data)
work_dir = os.path.join(base_dir, "work")
out = {"summary": os.path.join(work_dir, "validate-summary.csv"),
"grading": os.path.join(work_dir, "validate-grading.yaml"),
"discordant": os.path.join(work_dir, "%s-eval-ref-discordance-annotate.vcf" % sample)}
if not utils.file_exists(out["discordant"]) or not utils.file_exists(out["grading"]):
bcbio_variation_comparison(val_config_file, base_dir, data)
out["concordant"] = filter(os.path.exists,
[os.path.join(work_dir, "%s-%s-concordance.vcf" % (sample, x))
for x in ["eval-ref", "ref-eval"]])[0]
return out | python | def _run_bcbio_variation(vrn_file, rm_file, rm_interval_file, base_dir, sample, caller, data):
"""Run validation of a caller against the truth set using bcbio.variation.
"""
val_config_file = _create_validate_config_file(vrn_file, rm_file, rm_interval_file,
base_dir, data)
work_dir = os.path.join(base_dir, "work")
out = {"summary": os.path.join(work_dir, "validate-summary.csv"),
"grading": os.path.join(work_dir, "validate-grading.yaml"),
"discordant": os.path.join(work_dir, "%s-eval-ref-discordance-annotate.vcf" % sample)}
if not utils.file_exists(out["discordant"]) or not utils.file_exists(out["grading"]):
bcbio_variation_comparison(val_config_file, base_dir, data)
out["concordant"] = filter(os.path.exists,
[os.path.join(work_dir, "%s-%s-concordance.vcf" % (sample, x))
for x in ["eval-ref", "ref-eval"]])[0]
return out | [
"def",
"_run_bcbio_variation",
"(",
"vrn_file",
",",
"rm_file",
",",
"rm_interval_file",
",",
"base_dir",
",",
"sample",
",",
"caller",
",",
"data",
")",
":",
"val_config_file",
"=",
"_create_validate_config_file",
"(",
"vrn_file",
",",
"rm_file",
",",
"rm_interva... | Run validation of a caller against the truth set using bcbio.variation. | [
"Run",
"validation",
"of",
"a",
"caller",
"against",
"the",
"truth",
"set",
"using",
"bcbio",
".",
"variation",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L454-L468 | train | 218,329 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _create_validate_config | def _create_validate_config(vrn_file, rm_file, rm_interval_file, base_dir, data):
"""Create a bcbio.variation configuration input for validation.
"""
ref_call = {"file": str(rm_file), "name": "ref", "type": "grading-ref",
"fix-sample-header": True, "remove-refcalls": True}
a_intervals = get_analysis_intervals(data, vrn_file, base_dir)
if a_intervals:
a_intervals = shared.remove_lcr_regions(a_intervals, [data])
if rm_interval_file:
ref_call["intervals"] = rm_interval_file
eval_call = {"file": vrn_file, "name": "eval", "remove-refcalls": True}
exp = {"sample": data["name"][-1],
"ref": dd.get_ref_file(data),
"approach": "grade",
"calls": [ref_call, eval_call]}
if a_intervals:
exp["intervals"] = os.path.abspath(a_intervals)
if data.get("align_bam"):
exp["align"] = data["align_bam"]
elif data.get("work_bam"):
exp["align"] = data["work_bam"]
return {"dir": {"base": base_dir, "out": "work", "prep": "work/prep"},
"experiments": [exp]} | python | def _create_validate_config(vrn_file, rm_file, rm_interval_file, base_dir, data):
"""Create a bcbio.variation configuration input for validation.
"""
ref_call = {"file": str(rm_file), "name": "ref", "type": "grading-ref",
"fix-sample-header": True, "remove-refcalls": True}
a_intervals = get_analysis_intervals(data, vrn_file, base_dir)
if a_intervals:
a_intervals = shared.remove_lcr_regions(a_intervals, [data])
if rm_interval_file:
ref_call["intervals"] = rm_interval_file
eval_call = {"file": vrn_file, "name": "eval", "remove-refcalls": True}
exp = {"sample": data["name"][-1],
"ref": dd.get_ref_file(data),
"approach": "grade",
"calls": [ref_call, eval_call]}
if a_intervals:
exp["intervals"] = os.path.abspath(a_intervals)
if data.get("align_bam"):
exp["align"] = data["align_bam"]
elif data.get("work_bam"):
exp["align"] = data["work_bam"]
return {"dir": {"base": base_dir, "out": "work", "prep": "work/prep"},
"experiments": [exp]} | [
"def",
"_create_validate_config",
"(",
"vrn_file",
",",
"rm_file",
",",
"rm_interval_file",
",",
"base_dir",
",",
"data",
")",
":",
"ref_call",
"=",
"{",
"\"file\"",
":",
"str",
"(",
"rm_file",
")",
",",
"\"name\"",
":",
"\"ref\"",
",",
"\"type\"",
":",
"\... | Create a bcbio.variation configuration input for validation. | [
"Create",
"a",
"bcbio",
".",
"variation",
"configuration",
"input",
"for",
"validation",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L492-L514 | train | 218,330 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | summarize_grading | def summarize_grading(samples, vkey="validate"):
"""Provide summaries of grading results across all samples.
Handles both traditional pipelines (validation part of variants) and CWL
pipelines (validation at top level)
"""
samples = list(utils.flatten(samples))
if not _has_grading_info(samples, vkey):
return [[d] for d in samples]
validate_dir = utils.safe_makedir(os.path.join(samples[0]["dirs"]["work"], vkey))
header = ["sample", "caller", "variant.type", "category", "value"]
_summarize_combined(samples, vkey)
validated, out = _group_validate_samples(samples, vkey,
(["metadata", "validate_batch"], ["metadata", "batch"], ["description"]))
for vname, vitems in validated.items():
out_csv = os.path.join(validate_dir, "grading-summary-%s.csv" % vname)
with open(out_csv, "w") as out_handle:
writer = csv.writer(out_handle)
writer.writerow(header)
plot_data = []
plot_files = []
for data in sorted(vitems, key=lambda x: x.get("lane", dd.get_sample_name(x)) or ""):
validations = [variant.get(vkey) for variant in data.get("variants", [])
if isinstance(variant, dict)]
validations = [v for v in validations if v]
if len(validations) == 0 and vkey in data:
validations = [data.get(vkey)]
for validate in validations:
if validate:
validate["grading_summary"] = out_csv
if validate.get("grading"):
for row in _get_validate_plotdata_yaml(validate["grading"], data):
writer.writerow(row)
plot_data.append(row)
elif validate.get("summary") and not validate.get("summary") == "None":
if isinstance(validate["summary"], (list, tuple)):
plot_files.extend(list(set(validate["summary"])))
else:
plot_files.append(validate["summary"])
if plot_files:
plots = validateplot.classifyplot_from_plotfiles(plot_files, out_csv)
elif plot_data:
plots = validateplot.create(plot_data, header, 0, data["config"],
os.path.splitext(out_csv)[0])
else:
plots = []
for data in vitems:
if data.get(vkey):
data[vkey]["grading_plots"] = plots
for variant in data.get("variants", []):
if isinstance(variant, dict) and variant.get(vkey):
variant[vkey]["grading_plots"] = plots
out.append([data])
return out | python | def summarize_grading(samples, vkey="validate"):
"""Provide summaries of grading results across all samples.
Handles both traditional pipelines (validation part of variants) and CWL
pipelines (validation at top level)
"""
samples = list(utils.flatten(samples))
if not _has_grading_info(samples, vkey):
return [[d] for d in samples]
validate_dir = utils.safe_makedir(os.path.join(samples[0]["dirs"]["work"], vkey))
header = ["sample", "caller", "variant.type", "category", "value"]
_summarize_combined(samples, vkey)
validated, out = _group_validate_samples(samples, vkey,
(["metadata", "validate_batch"], ["metadata", "batch"], ["description"]))
for vname, vitems in validated.items():
out_csv = os.path.join(validate_dir, "grading-summary-%s.csv" % vname)
with open(out_csv, "w") as out_handle:
writer = csv.writer(out_handle)
writer.writerow(header)
plot_data = []
plot_files = []
for data in sorted(vitems, key=lambda x: x.get("lane", dd.get_sample_name(x)) or ""):
validations = [variant.get(vkey) for variant in data.get("variants", [])
if isinstance(variant, dict)]
validations = [v for v in validations if v]
if len(validations) == 0 and vkey in data:
validations = [data.get(vkey)]
for validate in validations:
if validate:
validate["grading_summary"] = out_csv
if validate.get("grading"):
for row in _get_validate_plotdata_yaml(validate["grading"], data):
writer.writerow(row)
plot_data.append(row)
elif validate.get("summary") and not validate.get("summary") == "None":
if isinstance(validate["summary"], (list, tuple)):
plot_files.extend(list(set(validate["summary"])))
else:
plot_files.append(validate["summary"])
if plot_files:
plots = validateplot.classifyplot_from_plotfiles(plot_files, out_csv)
elif plot_data:
plots = validateplot.create(plot_data, header, 0, data["config"],
os.path.splitext(out_csv)[0])
else:
plots = []
for data in vitems:
if data.get(vkey):
data[vkey]["grading_plots"] = plots
for variant in data.get("variants", []):
if isinstance(variant, dict) and variant.get(vkey):
variant[vkey]["grading_plots"] = plots
out.append([data])
return out | [
"def",
"summarize_grading",
"(",
"samples",
",",
"vkey",
"=",
"\"validate\"",
")",
":",
"samples",
"=",
"list",
"(",
"utils",
".",
"flatten",
"(",
"samples",
")",
")",
"if",
"not",
"_has_grading_info",
"(",
"samples",
",",
"vkey",
")",
":",
"return",
"["... | Provide summaries of grading results across all samples.
Handles both traditional pipelines (validation part of variants) and CWL
pipelines (validation at top level) | [
"Provide",
"summaries",
"of",
"grading",
"results",
"across",
"all",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L560-L613 | train | 218,331 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _summarize_combined | def _summarize_combined(samples, vkey):
"""Prepare summarized CSV and plot files for samples to combine together.
Helps handle cases where we want to summarize over multiple samples.
"""
validate_dir = utils.safe_makedir(os.path.join(samples[0]["dirs"]["work"], vkey))
combined, _ = _group_validate_samples(samples, vkey, [["metadata", "validate_combine"]])
for vname, vitems in combined.items():
if vname:
cur_combined = collections.defaultdict(int)
for data in sorted(vitems, key=lambda x: x.get("lane", dd.get_sample_name(x))):
validations = [variant.get(vkey) for variant in data.get("variants", [])]
validations = [v for v in validations if v]
if len(validations) == 0 and vkey in data:
validations = [data.get(vkey)]
for validate in validations:
with open(validate["summary"]) as in_handle:
reader = csv.reader(in_handle)
next(reader) # header
for _, caller, vtype, metric, value in reader:
cur_combined[(caller, vtype, metric)] += int(value)
out_csv = os.path.join(validate_dir, "grading-summary-%s.csv" % vname)
with open(out_csv, "w") as out_handle:
writer = csv.writer(out_handle)
header = ["sample", "caller", "vtype", "metric", "value"]
writer.writerow(header)
for (caller, variant_type, category), val in cur_combined.items():
writer.writerow(["combined-%s" % vname, caller, variant_type, category, val])
plots = validateplot.classifyplot_from_valfile(out_csv) | python | def _summarize_combined(samples, vkey):
"""Prepare summarized CSV and plot files for samples to combine together.
Helps handle cases where we want to summarize over multiple samples.
"""
validate_dir = utils.safe_makedir(os.path.join(samples[0]["dirs"]["work"], vkey))
combined, _ = _group_validate_samples(samples, vkey, [["metadata", "validate_combine"]])
for vname, vitems in combined.items():
if vname:
cur_combined = collections.defaultdict(int)
for data in sorted(vitems, key=lambda x: x.get("lane", dd.get_sample_name(x))):
validations = [variant.get(vkey) for variant in data.get("variants", [])]
validations = [v for v in validations if v]
if len(validations) == 0 and vkey in data:
validations = [data.get(vkey)]
for validate in validations:
with open(validate["summary"]) as in_handle:
reader = csv.reader(in_handle)
next(reader) # header
for _, caller, vtype, metric, value in reader:
cur_combined[(caller, vtype, metric)] += int(value)
out_csv = os.path.join(validate_dir, "grading-summary-%s.csv" % vname)
with open(out_csv, "w") as out_handle:
writer = csv.writer(out_handle)
header = ["sample", "caller", "vtype", "metric", "value"]
writer.writerow(header)
for (caller, variant_type, category), val in cur_combined.items():
writer.writerow(["combined-%s" % vname, caller, variant_type, category, val])
plots = validateplot.classifyplot_from_valfile(out_csv) | [
"def",
"_summarize_combined",
"(",
"samples",
",",
"vkey",
")",
":",
"validate_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"samples",
"[",
"0",
"]",
"[",
"\"dirs\"",
"]",
"[",
"\"work\"",
"]",
",",
"vkey",
")",
... | Prepare summarized CSV and plot files for samples to combine together.
Helps handle cases where we want to summarize over multiple samples. | [
"Prepare",
"summarized",
"CSV",
"and",
"plot",
"files",
"for",
"samples",
"to",
"combine",
"together",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L615-L643 | train | 218,332 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | combine_validations | def combine_validations(items, vkey="validate"):
"""Combine multiple batch validations into validation outputs.
"""
csvs = set([])
pngs = set([])
for v in [x.get(vkey) for x in items]:
if v and v.get("grading_summary"):
csvs.add(v.get("grading_summary"))
if v and v.get("grading_plots"):
pngs |= set(v.get("grading_plots"))
if len(csvs) == 1:
grading_summary = csvs.pop()
else:
grading_summary = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(items[0]), vkey)),
"grading-summary-combined.csv")
with open(grading_summary, "w") as out_handle:
for i, csv in enumerate(sorted(list(csvs))):
with open(csv) as in_handle:
h = in_handle.readline()
if i == 0:
out_handle.write(h)
for l in in_handle:
out_handle.write(l)
return {"grading_plots": sorted(list(pngs)), "grading_summary": grading_summary} | python | def combine_validations(items, vkey="validate"):
"""Combine multiple batch validations into validation outputs.
"""
csvs = set([])
pngs = set([])
for v in [x.get(vkey) for x in items]:
if v and v.get("grading_summary"):
csvs.add(v.get("grading_summary"))
if v and v.get("grading_plots"):
pngs |= set(v.get("grading_plots"))
if len(csvs) == 1:
grading_summary = csvs.pop()
else:
grading_summary = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(items[0]), vkey)),
"grading-summary-combined.csv")
with open(grading_summary, "w") as out_handle:
for i, csv in enumerate(sorted(list(csvs))):
with open(csv) as in_handle:
h = in_handle.readline()
if i == 0:
out_handle.write(h)
for l in in_handle:
out_handle.write(l)
return {"grading_plots": sorted(list(pngs)), "grading_summary": grading_summary} | [
"def",
"combine_validations",
"(",
"items",
",",
"vkey",
"=",
"\"validate\"",
")",
":",
"csvs",
"=",
"set",
"(",
"[",
"]",
")",
"pngs",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"v",
"in",
"[",
"x",
".",
"get",
"(",
"vkey",
")",
"for",
"x",
"in",
... | Combine multiple batch validations into validation outputs. | [
"Combine",
"multiple",
"batch",
"validations",
"into",
"validation",
"outputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L645-L668 | train | 218,333 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | freq_summary | def freq_summary(val_file, call_file, truth_file, target_name):
"""Summarize true and false positive calls by variant type and frequency.
Resolve differences in true/false calls based on output from hap.py:
https://github.com/sequencing/hap.py
"""
out_file = "%s-freqs.csv" % utils.splitext_plus(val_file)[0]
truth_freqs = _read_truth_freqs(truth_file)
call_freqs = _read_call_freqs(call_file, target_name)
with VariantFile(val_file) as val_in:
with open(out_file, "w") as out_handle:
writer = csv.writer(out_handle)
writer.writerow(["vtype", "valclass", "freq"])
for rec in val_in:
call_type = _classify_rec(rec)
val_type = _get_validation_status(rec)
key = _get_key(rec)
freq = truth_freqs.get(key, call_freqs.get(key, 0.0))
writer.writerow([call_type, val_type, freq])
return out_file | python | def freq_summary(val_file, call_file, truth_file, target_name):
"""Summarize true and false positive calls by variant type and frequency.
Resolve differences in true/false calls based on output from hap.py:
https://github.com/sequencing/hap.py
"""
out_file = "%s-freqs.csv" % utils.splitext_plus(val_file)[0]
truth_freqs = _read_truth_freqs(truth_file)
call_freqs = _read_call_freqs(call_file, target_name)
with VariantFile(val_file) as val_in:
with open(out_file, "w") as out_handle:
writer = csv.writer(out_handle)
writer.writerow(["vtype", "valclass", "freq"])
for rec in val_in:
call_type = _classify_rec(rec)
val_type = _get_validation_status(rec)
key = _get_key(rec)
freq = truth_freqs.get(key, call_freqs.get(key, 0.0))
writer.writerow([call_type, val_type, freq])
return out_file | [
"def",
"freq_summary",
"(",
"val_file",
",",
"call_file",
",",
"truth_file",
",",
"target_name",
")",
":",
"out_file",
"=",
"\"%s-freqs.csv\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"val_file",
")",
"[",
"0",
"]",
"truth_freqs",
"=",
"_read_truth_freqs",
"(... | Summarize true and false positive calls by variant type and frequency.
Resolve differences in true/false calls based on output from hap.py:
https://github.com/sequencing/hap.py | [
"Summarize",
"true",
"and",
"false",
"positive",
"calls",
"by",
"variant",
"type",
"and",
"frequency",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L684-L703 | train | 218,334 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _read_call_freqs | def _read_call_freqs(in_file, sample_name):
"""Identify frequencies for calls in the input file.
"""
from bcbio.heterogeneity import bubbletree
out = {}
with VariantFile(in_file) as call_in:
for rec in call_in:
if rec.filter.keys() == ["PASS"]:
for name, sample in rec.samples.items():
if name == sample_name:
alt, depth, freq = bubbletree.sample_alt_and_depth(rec, sample)
if freq is not None:
out[_get_key(rec)] = freq
return out | python | def _read_call_freqs(in_file, sample_name):
"""Identify frequencies for calls in the input file.
"""
from bcbio.heterogeneity import bubbletree
out = {}
with VariantFile(in_file) as call_in:
for rec in call_in:
if rec.filter.keys() == ["PASS"]:
for name, sample in rec.samples.items():
if name == sample_name:
alt, depth, freq = bubbletree.sample_alt_and_depth(rec, sample)
if freq is not None:
out[_get_key(rec)] = freq
return out | [
"def",
"_read_call_freqs",
"(",
"in_file",
",",
"sample_name",
")",
":",
"from",
"bcbio",
".",
"heterogeneity",
"import",
"bubbletree",
"out",
"=",
"{",
"}",
"with",
"VariantFile",
"(",
"in_file",
")",
"as",
"call_in",
":",
"for",
"rec",
"in",
"call_in",
"... | Identify frequencies for calls in the input file. | [
"Identify",
"frequencies",
"for",
"calls",
"in",
"the",
"input",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L721-L734 | train | 218,335 |
bcbio/bcbio-nextgen | bcbio/variation/validate.py | _read_truth_freqs | def _read_truth_freqs(in_file):
"""Read frequency of calls from truth VCF.
Currently handles DREAM data, needs generalization for other datasets.
"""
out = {}
with VariantFile(in_file) as bcf_in:
for rec in bcf_in:
freq = float(rec.info.get("VAF", 1.0))
out[_get_key(rec)] = freq
return out | python | def _read_truth_freqs(in_file):
"""Read frequency of calls from truth VCF.
Currently handles DREAM data, needs generalization for other datasets.
"""
out = {}
with VariantFile(in_file) as bcf_in:
for rec in bcf_in:
freq = float(rec.info.get("VAF", 1.0))
out[_get_key(rec)] = freq
return out | [
"def",
"_read_truth_freqs",
"(",
"in_file",
")",
":",
"out",
"=",
"{",
"}",
"with",
"VariantFile",
"(",
"in_file",
")",
"as",
"bcf_in",
":",
"for",
"rec",
"in",
"bcf_in",
":",
"freq",
"=",
"float",
"(",
"rec",
".",
"info",
".",
"get",
"(",
"\"VAF\"",... | Read frequency of calls from truth VCF.
Currently handles DREAM data, needs generalization for other datasets. | [
"Read",
"frequency",
"of",
"calls",
"from",
"truth",
"VCF",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L736-L746 | train | 218,336 |
bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | to_rec | def to_rec(samples, default_keys=None):
"""Convert inputs into CWL records, useful for single item parallelization.
"""
recs = samples_to_records([normalize_missing(utils.to_single_data(x)) for x in samples], default_keys)
return [[x] for x in recs] | python | def to_rec(samples, default_keys=None):
"""Convert inputs into CWL records, useful for single item parallelization.
"""
recs = samples_to_records([normalize_missing(utils.to_single_data(x)) for x in samples], default_keys)
return [[x] for x in recs] | [
"def",
"to_rec",
"(",
"samples",
",",
"default_keys",
"=",
"None",
")",
":",
"recs",
"=",
"samples_to_records",
"(",
"[",
"normalize_missing",
"(",
"utils",
".",
"to_single_data",
"(",
"x",
")",
")",
"for",
"x",
"in",
"samples",
"]",
",",
"default_keys",
... | Convert inputs into CWL records, useful for single item parallelization. | [
"Convert",
"inputs",
"into",
"CWL",
"records",
"useful",
"for",
"single",
"item",
"parallelization",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L20-L24 | train | 218,337 |
bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | to_rec_single | def to_rec_single(samples, default_keys=None):
"""Convert output into a list of single CWL records.
"""
out = []
for data in samples:
recs = samples_to_records([normalize_missing(utils.to_single_data(data))], default_keys)
assert len(recs) == 1
out.append(recs[0])
return out | python | def to_rec_single(samples, default_keys=None):
"""Convert output into a list of single CWL records.
"""
out = []
for data in samples:
recs = samples_to_records([normalize_missing(utils.to_single_data(data))], default_keys)
assert len(recs) == 1
out.append(recs[0])
return out | [
"def",
"to_rec_single",
"(",
"samples",
",",
"default_keys",
"=",
"None",
")",
":",
"out",
"=",
"[",
"]",
"for",
"data",
"in",
"samples",
":",
"recs",
"=",
"samples_to_records",
"(",
"[",
"normalize_missing",
"(",
"utils",
".",
"to_single_data",
"(",
"data... | Convert output into a list of single CWL records. | [
"Convert",
"output",
"into",
"a",
"list",
"of",
"single",
"CWL",
"records",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L26-L34 | train | 218,338 |
bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | handle_combined_input | def handle_combined_input(args):
"""Check for cases where we have a combined input nested list.
In these cases the CWL will be double nested:
[[[rec_a], [rec_b]]]
and we remove the outer nesting.
"""
cur_args = args[:]
while len(cur_args) == 1 and isinstance(cur_args[0], (list, tuple)):
cur_args = cur_args[0]
return cur_args | python | def handle_combined_input(args):
"""Check for cases where we have a combined input nested list.
In these cases the CWL will be double nested:
[[[rec_a], [rec_b]]]
and we remove the outer nesting.
"""
cur_args = args[:]
while len(cur_args) == 1 and isinstance(cur_args[0], (list, tuple)):
cur_args = cur_args[0]
return cur_args | [
"def",
"handle_combined_input",
"(",
"args",
")",
":",
"cur_args",
"=",
"args",
"[",
":",
"]",
"while",
"len",
"(",
"cur_args",
")",
"==",
"1",
"and",
"isinstance",
"(",
"cur_args",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"cur... | Check for cases where we have a combined input nested list.
In these cases the CWL will be double nested:
[[[rec_a], [rec_b]]]
and we remove the outer nesting. | [
"Check",
"for",
"cases",
"where",
"we",
"have",
"a",
"combined",
"input",
"nested",
"list",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L39-L51 | train | 218,339 |
bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | normalize_missing | def normalize_missing(xs):
"""Normalize missing values to avoid string 'None' inputs.
"""
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = normalize_missing(v)
elif isinstance(xs, (list, tuple)):
xs = [normalize_missing(x) for x in xs]
elif isinstance(xs, six.string_types):
if xs.lower() in ["none", "null"]:
xs = None
elif xs.lower() == "true":
xs = True
elif xs.lower() == "false":
xs = False
return xs | python | def normalize_missing(xs):
"""Normalize missing values to avoid string 'None' inputs.
"""
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = normalize_missing(v)
elif isinstance(xs, (list, tuple)):
xs = [normalize_missing(x) for x in xs]
elif isinstance(xs, six.string_types):
if xs.lower() in ["none", "null"]:
xs = None
elif xs.lower() == "true":
xs = True
elif xs.lower() == "false":
xs = False
return xs | [
"def",
"normalize_missing",
"(",
"xs",
")",
":",
"if",
"isinstance",
"(",
"xs",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"xs",
".",
"items",
"(",
")",
":",
"xs",
"[",
"k",
"]",
"=",
"normalize_missing",
"(",
"v",
")",
"elif",
"isinstanc... | Normalize missing values to avoid string 'None' inputs. | [
"Normalize",
"missing",
"values",
"to",
"avoid",
"string",
"None",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L53-L68 | train | 218,340 |
bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | unpack_tarballs | def unpack_tarballs(xs, data, use_subdir=True):
"""Unpack workflow tarballs into ready to use directories.
"""
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = unpack_tarballs(v, data, use_subdir)
elif isinstance(xs, (list, tuple)):
xs = [unpack_tarballs(x, data, use_subdir) for x in xs]
elif isinstance(xs, six.string_types):
if os.path.isfile(xs.encode("utf-8", "ignore")) and xs.endswith("-wf.tar.gz"):
if use_subdir:
tarball_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "wf-inputs"))
else:
tarball_dir = dd.get_work_dir(data)
out_dir = os.path.join(tarball_dir,
os.path.basename(xs).replace("-wf.tar.gz", "").replace("--", os.path.sep))
if not os.path.exists(out_dir):
with utils.chdir(tarball_dir):
with tarfile.open(xs, "r:gz") as tar:
tar.extractall()
assert os.path.exists(out_dir), out_dir
# Default to representing output directory
xs = out_dir
# Look for aligner indices
for fname in os.listdir(out_dir):
if fname.endswith(DIR_TARGETS):
xs = os.path.join(out_dir, fname)
break
elif fname.endswith(BASENAME_TARGETS):
base = os.path.join(out_dir, utils.splitext_plus(os.path.basename(fname))[0])
xs = glob.glob("%s*" % base)
break
return xs | python | def unpack_tarballs(xs, data, use_subdir=True):
"""Unpack workflow tarballs into ready to use directories.
"""
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = unpack_tarballs(v, data, use_subdir)
elif isinstance(xs, (list, tuple)):
xs = [unpack_tarballs(x, data, use_subdir) for x in xs]
elif isinstance(xs, six.string_types):
if os.path.isfile(xs.encode("utf-8", "ignore")) and xs.endswith("-wf.tar.gz"):
if use_subdir:
tarball_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "wf-inputs"))
else:
tarball_dir = dd.get_work_dir(data)
out_dir = os.path.join(tarball_dir,
os.path.basename(xs).replace("-wf.tar.gz", "").replace("--", os.path.sep))
if not os.path.exists(out_dir):
with utils.chdir(tarball_dir):
with tarfile.open(xs, "r:gz") as tar:
tar.extractall()
assert os.path.exists(out_dir), out_dir
# Default to representing output directory
xs = out_dir
# Look for aligner indices
for fname in os.listdir(out_dir):
if fname.endswith(DIR_TARGETS):
xs = os.path.join(out_dir, fname)
break
elif fname.endswith(BASENAME_TARGETS):
base = os.path.join(out_dir, utils.splitext_plus(os.path.basename(fname))[0])
xs = glob.glob("%s*" % base)
break
return xs | [
"def",
"unpack_tarballs",
"(",
"xs",
",",
"data",
",",
"use_subdir",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"xs",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"xs",
".",
"items",
"(",
")",
":",
"xs",
"[",
"k",
"]",
"=",
"unpack_t... | Unpack workflow tarballs into ready to use directories. | [
"Unpack",
"workflow",
"tarballs",
"into",
"ready",
"to",
"use",
"directories",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L76-L108 | train | 218,341 |
bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | _get_all_cwlkeys | def _get_all_cwlkeys(items, default_keys=None):
"""Retrieve cwlkeys from inputs, handling defaults which can be null.
When inputs are null in some and present in others, this creates unequal
keys in each sample, confusing decision making about which are primary and extras.
"""
if default_keys:
default_keys = set(default_keys)
else:
default_keys = set(["metadata__batch", "config__algorithm__validate",
"config__algorithm__validate_regions",
"config__algorithm__validate_regions_merged",
"config__algorithm__variant_regions",
"validate__summary",
"validate__tp", "validate__fp", "validate__fn",
"config__algorithm__coverage", "config__algorithm__coverage_merged",
"genome_resources__variation__cosmic", "genome_resources__variation__dbsnp",
"genome_resources__variation__clinvar"
])
all_keys = set([])
for data in items:
all_keys.update(set(data["cwl_keys"]))
all_keys.update(default_keys)
return all_keys | python | def _get_all_cwlkeys(items, default_keys=None):
"""Retrieve cwlkeys from inputs, handling defaults which can be null.
When inputs are null in some and present in others, this creates unequal
keys in each sample, confusing decision making about which are primary and extras.
"""
if default_keys:
default_keys = set(default_keys)
else:
default_keys = set(["metadata__batch", "config__algorithm__validate",
"config__algorithm__validate_regions",
"config__algorithm__validate_regions_merged",
"config__algorithm__variant_regions",
"validate__summary",
"validate__tp", "validate__fp", "validate__fn",
"config__algorithm__coverage", "config__algorithm__coverage_merged",
"genome_resources__variation__cosmic", "genome_resources__variation__dbsnp",
"genome_resources__variation__clinvar"
])
all_keys = set([])
for data in items:
all_keys.update(set(data["cwl_keys"]))
all_keys.update(default_keys)
return all_keys | [
"def",
"_get_all_cwlkeys",
"(",
"items",
",",
"default_keys",
"=",
"None",
")",
":",
"if",
"default_keys",
":",
"default_keys",
"=",
"set",
"(",
"default_keys",
")",
"else",
":",
"default_keys",
"=",
"set",
"(",
"[",
"\"metadata__batch\"",
",",
"\"config__algo... | Retrieve cwlkeys from inputs, handling defaults which can be null.
When inputs are null in some and present in others, this creates unequal
keys in each sample, confusing decision making about which are primary and extras. | [
"Retrieve",
"cwlkeys",
"from",
"inputs",
"handling",
"defaults",
"which",
"can",
"be",
"null",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L110-L133 | train | 218,342 |
bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | split_data_cwl_items | def split_data_cwl_items(items, default_keys=None):
"""Split a set of CWL output dictionaries into data samples and CWL items.
Handles cases where we're arrayed on multiple things, like a set of regional
VCF calls and data objects.
"""
key_lens = set([])
for data in items:
key_lens.add(len(_get_all_cwlkeys([data], default_keys)))
extra_key_len = min(list(key_lens)) if len(key_lens) > 1 else None
data_out = []
extra_out = []
for data in items:
if extra_key_len and len(_get_all_cwlkeys([data], default_keys)) == extra_key_len:
extra_out.append(data)
else:
data_out.append(data)
if len(extra_out) == 0:
return data_out, {}
else:
cwl_keys = extra_out[0]["cwl_keys"]
for extra in extra_out[1:]:
cur_cwl_keys = extra["cwl_keys"]
assert cur_cwl_keys == cwl_keys, pprint.pformat(extra_out)
cwl_extras = collections.defaultdict(list)
for data in items:
for key in cwl_keys:
cwl_extras[key].append(data[key])
data_final = []
for data in data_out:
for key in cwl_keys:
data.pop(key)
data_final.append(data)
return data_final, dict(cwl_extras) | python | def split_data_cwl_items(items, default_keys=None):
"""Split a set of CWL output dictionaries into data samples and CWL items.
Handles cases where we're arrayed on multiple things, like a set of regional
VCF calls and data objects.
"""
key_lens = set([])
for data in items:
key_lens.add(len(_get_all_cwlkeys([data], default_keys)))
extra_key_len = min(list(key_lens)) if len(key_lens) > 1 else None
data_out = []
extra_out = []
for data in items:
if extra_key_len and len(_get_all_cwlkeys([data], default_keys)) == extra_key_len:
extra_out.append(data)
else:
data_out.append(data)
if len(extra_out) == 0:
return data_out, {}
else:
cwl_keys = extra_out[0]["cwl_keys"]
for extra in extra_out[1:]:
cur_cwl_keys = extra["cwl_keys"]
assert cur_cwl_keys == cwl_keys, pprint.pformat(extra_out)
cwl_extras = collections.defaultdict(list)
for data in items:
for key in cwl_keys:
cwl_extras[key].append(data[key])
data_final = []
for data in data_out:
for key in cwl_keys:
data.pop(key)
data_final.append(data)
return data_final, dict(cwl_extras) | [
"def",
"split_data_cwl_items",
"(",
"items",
",",
"default_keys",
"=",
"None",
")",
":",
"key_lens",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"data",
"in",
"items",
":",
"key_lens",
".",
"add",
"(",
"len",
"(",
"_get_all_cwlkeys",
"(",
"[",
"data",
"]",
... | Split a set of CWL output dictionaries into data samples and CWL items.
Handles cases where we're arrayed on multiple things, like a set of regional
VCF calls and data objects. | [
"Split",
"a",
"set",
"of",
"CWL",
"output",
"dictionaries",
"into",
"data",
"samples",
"and",
"CWL",
"items",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L135-L168 | train | 218,343 |
bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | samples_to_records | def samples_to_records(samples, default_keys=None):
"""Convert samples into output CWL records.
"""
from bcbio.pipeline import run_info
RECORD_CONVERT_TO_LIST = set(["config__algorithm__tools_on", "config__algorithm__tools_off",
"reference__genome_context"])
all_keys = _get_all_cwlkeys(samples, default_keys)
out = []
for data in samples:
for raw_key in sorted(list(all_keys)):
key = raw_key.split("__")
if tz.get_in(key, data) is None:
data = tz.update_in(data, key, lambda x: None)
if raw_key not in data["cwl_keys"]:
data["cwl_keys"].append(raw_key)
if raw_key in RECORD_CONVERT_TO_LIST:
val = tz.get_in(key, data)
if not val: val = []
elif not isinstance(val, (list, tuple)): val = [val]
data = tz.update_in(data, key, lambda x: val)
# Booleans are problematic for CWL serialization, convert into string representation
if isinstance(tz.get_in(key, data), bool):
data = tz.update_in(data, key, lambda x: str(tz.get_in(key, data)))
data["metadata"] = run_info.add_metadata_defaults(data.get("metadata", {}))
out.append(data)
return out | python | def samples_to_records(samples, default_keys=None):
"""Convert samples into output CWL records.
"""
from bcbio.pipeline import run_info
RECORD_CONVERT_TO_LIST = set(["config__algorithm__tools_on", "config__algorithm__tools_off",
"reference__genome_context"])
all_keys = _get_all_cwlkeys(samples, default_keys)
out = []
for data in samples:
for raw_key in sorted(list(all_keys)):
key = raw_key.split("__")
if tz.get_in(key, data) is None:
data = tz.update_in(data, key, lambda x: None)
if raw_key not in data["cwl_keys"]:
data["cwl_keys"].append(raw_key)
if raw_key in RECORD_CONVERT_TO_LIST:
val = tz.get_in(key, data)
if not val: val = []
elif not isinstance(val, (list, tuple)): val = [val]
data = tz.update_in(data, key, lambda x: val)
# Booleans are problematic for CWL serialization, convert into string representation
if isinstance(tz.get_in(key, data), bool):
data = tz.update_in(data, key, lambda x: str(tz.get_in(key, data)))
data["metadata"] = run_info.add_metadata_defaults(data.get("metadata", {}))
out.append(data)
return out | [
"def",
"samples_to_records",
"(",
"samples",
",",
"default_keys",
"=",
"None",
")",
":",
"from",
"bcbio",
".",
"pipeline",
"import",
"run_info",
"RECORD_CONVERT_TO_LIST",
"=",
"set",
"(",
"[",
"\"config__algorithm__tools_on\"",
",",
"\"config__algorithm__tools_off\"",
... | Convert samples into output CWL records. | [
"Convert",
"samples",
"into",
"output",
"CWL",
"records",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L170-L195 | train | 218,344 |
bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | assign_complex_to_samples | def assign_complex_to_samples(items):
"""Assign complex inputs like variants and align outputs to samples.
Handles list inputs to record conversion where we have inputs from multiple
locations and need to ensure they are properly assigned to samples in many
environments.
The unpleasant approach here is to use standard file naming to match
with samples so this can work in environments where we don't download/stream
the input files (for space/time savings).
"""
extract_fns = {("variants", "samples"): _get_vcf_samples,
("align_bam",): _get_bam_samples}
complex = {k: {} for k in extract_fns.keys()}
for data in items:
for k in complex:
v = tz.get_in(k, data)
if v is not None:
for s in extract_fns[k](v, items):
if s:
complex[k][s] = v
out = []
for data in items:
for k in complex:
newv = tz.get_in([k, dd.get_sample_name(data)], complex)
if newv:
data = tz.update_in(data, k, lambda x: newv)
out.append(data)
return out | python | def assign_complex_to_samples(items):
"""Assign complex inputs like variants and align outputs to samples.
Handles list inputs to record conversion where we have inputs from multiple
locations and need to ensure they are properly assigned to samples in many
environments.
The unpleasant approach here is to use standard file naming to match
with samples so this can work in environments where we don't download/stream
the input files (for space/time savings).
"""
extract_fns = {("variants", "samples"): _get_vcf_samples,
("align_bam",): _get_bam_samples}
complex = {k: {} for k in extract_fns.keys()}
for data in items:
for k in complex:
v = tz.get_in(k, data)
if v is not None:
for s in extract_fns[k](v, items):
if s:
complex[k][s] = v
out = []
for data in items:
for k in complex:
newv = tz.get_in([k, dd.get_sample_name(data)], complex)
if newv:
data = tz.update_in(data, k, lambda x: newv)
out.append(data)
return out | [
"def",
"assign_complex_to_samples",
"(",
"items",
")",
":",
"extract_fns",
"=",
"{",
"(",
"\"variants\"",
",",
"\"samples\"",
")",
":",
"_get_vcf_samples",
",",
"(",
"\"align_bam\"",
",",
")",
":",
"_get_bam_samples",
"}",
"complex",
"=",
"{",
"k",
":",
"{",... | Assign complex inputs like variants and align outputs to samples.
Handles list inputs to record conversion where we have inputs from multiple
locations and need to ensure they are properly assigned to samples in many
environments.
The unpleasant approach here is to use standard file naming to match
with samples so this can work in environments where we don't download/stream
the input files (for space/time savings). | [
"Assign",
"complex",
"inputs",
"like",
"variants",
"and",
"align",
"outputs",
"to",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L197-L225 | train | 218,345 |
bcbio/bcbio-nextgen | bcbio/pipeline/variation.py | _normalize_vc_input | def _normalize_vc_input(data):
"""Normalize different types of variant calling inputs.
Handles standard and ensemble inputs.
"""
if data.get("ensemble"):
for k in ["batch_samples", "validate", "vrn_file"]:
data[k] = data["ensemble"][k]
data["config"]["algorithm"]["variantcaller"] = "ensemble"
data["metadata"] = {"batch": data["ensemble"]["batch_id"]}
return data | python | def _normalize_vc_input(data):
"""Normalize different types of variant calling inputs.
Handles standard and ensemble inputs.
"""
if data.get("ensemble"):
for k in ["batch_samples", "validate", "vrn_file"]:
data[k] = data["ensemble"][k]
data["config"]["algorithm"]["variantcaller"] = "ensemble"
data["metadata"] = {"batch": data["ensemble"]["batch_id"]}
return data | [
"def",
"_normalize_vc_input",
"(",
"data",
")",
":",
"if",
"data",
".",
"get",
"(",
"\"ensemble\"",
")",
":",
"for",
"k",
"in",
"[",
"\"batch_samples\"",
",",
"\"validate\"",
",",
"\"vrn_file\"",
"]",
":",
"data",
"[",
"k",
"]",
"=",
"data",
"[",
"\"en... | Normalize different types of variant calling inputs.
Handles standard and ensemble inputs. | [
"Normalize",
"different",
"types",
"of",
"variant",
"calling",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/variation.py#L65-L75 | train | 218,346 |
bcbio/bcbio-nextgen | bcbio/pipeline/variation.py | _get_orig_items | def _get_orig_items(data):
"""Retrieve original items in a batch, handling CWL and standard cases.
"""
if isinstance(data, dict):
if dd.get_align_bam(data) and tz.get_in(["metadata", "batch"], data) and "group_orig" in data:
return vmulti.get_orig_items(data)
else:
return [data]
else:
return data | python | def _get_orig_items(data):
"""Retrieve original items in a batch, handling CWL and standard cases.
"""
if isinstance(data, dict):
if dd.get_align_bam(data) and tz.get_in(["metadata", "batch"], data) and "group_orig" in data:
return vmulti.get_orig_items(data)
else:
return [data]
else:
return data | [
"def",
"_get_orig_items",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"if",
"dd",
".",
"get_align_bam",
"(",
"data",
")",
"and",
"tz",
".",
"get_in",
"(",
"[",
"\"metadata\"",
",",
"\"batch\"",
"]",
",",
"data",
")"... | Retrieve original items in a batch, handling CWL and standard cases. | [
"Retrieve",
"original",
"items",
"in",
"a",
"batch",
"handling",
"CWL",
"and",
"standard",
"cases",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/variation.py#L129-L138 | train | 218,347 |
bcbio/bcbio-nextgen | bcbio/pipeline/variation.py | _symlink_to_workdir | def _symlink_to_workdir(data, key):
"""For CWL support, symlink files into a working directory if in read-only imports.
"""
orig_file = tz.get_in(key, data)
if orig_file and not orig_file.startswith(dd.get_work_dir(data)):
variantcaller = genotype.get_variantcaller(data, require_bam=False)
if not variantcaller:
variantcaller = "precalled"
out_file = os.path.join(dd.get_work_dir(data), variantcaller, os.path.basename(orig_file))
utils.safe_makedir(os.path.dirname(out_file))
utils.symlink_plus(orig_file, out_file)
data = tz.update_in(data, key, lambda x: out_file)
return data | python | def _symlink_to_workdir(data, key):
"""For CWL support, symlink files into a working directory if in read-only imports.
"""
orig_file = tz.get_in(key, data)
if orig_file and not orig_file.startswith(dd.get_work_dir(data)):
variantcaller = genotype.get_variantcaller(data, require_bam=False)
if not variantcaller:
variantcaller = "precalled"
out_file = os.path.join(dd.get_work_dir(data), variantcaller, os.path.basename(orig_file))
utils.safe_makedir(os.path.dirname(out_file))
utils.symlink_plus(orig_file, out_file)
data = tz.update_in(data, key, lambda x: out_file)
return data | [
"def",
"_symlink_to_workdir",
"(",
"data",
",",
"key",
")",
":",
"orig_file",
"=",
"tz",
".",
"get_in",
"(",
"key",
",",
"data",
")",
"if",
"orig_file",
"and",
"not",
"orig_file",
".",
"startswith",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",
")"... | For CWL support, symlink files into a working directory if in read-only imports. | [
"For",
"CWL",
"support",
"symlink",
"files",
"into",
"a",
"working",
"directory",
"if",
"in",
"read",
"-",
"only",
"imports",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/variation.py#L140-L152 | train | 218,348 |
bcbio/bcbio-nextgen | bcbio/pipeline/variation.py | _get_batch_representative | def _get_batch_representative(items, key):
"""Retrieve a representative data item from a batch.
Handles standard bcbio cases (a single data item) and CWL cases with
batches that have a consistent variant file.
"""
if isinstance(items, dict):
return items, items
else:
vals = set([])
out = []
for data in items:
if key in data:
vals.add(data[key])
out.append(data)
if len(vals) != 1:
raise ValueError("Incorrect values for %s: %s" % (key, list(vals)))
return out[0], items | python | def _get_batch_representative(items, key):
"""Retrieve a representative data item from a batch.
Handles standard bcbio cases (a single data item) and CWL cases with
batches that have a consistent variant file.
"""
if isinstance(items, dict):
return items, items
else:
vals = set([])
out = []
for data in items:
if key in data:
vals.add(data[key])
out.append(data)
if len(vals) != 1:
raise ValueError("Incorrect values for %s: %s" % (key, list(vals)))
return out[0], items | [
"def",
"_get_batch_representative",
"(",
"items",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"items",
",",
"dict",
")",
":",
"return",
"items",
",",
"items",
"else",
":",
"vals",
"=",
"set",
"(",
"[",
"]",
")",
"out",
"=",
"[",
"]",
"for",
"dat... | Retrieve a representative data item from a batch.
Handles standard bcbio cases (a single data item) and CWL cases with
batches that have a consistent variant file. | [
"Retrieve",
"a",
"representative",
"data",
"item",
"from",
"a",
"batch",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/variation.py#L154-L171 | train | 218,349 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | _get_storage_manager | def _get_storage_manager(resource):
"""Return a storage manager which can process this resource."""
for manager in (AmazonS3, ArvadosKeep, SevenBridges, DNAnexus, AzureBlob, GoogleCloud, RegularServer):
if manager.check_resource(resource):
return manager()
raise ValueError("Unexpected object store %(resource)s" %
{"resource": resource}) | python | def _get_storage_manager(resource):
"""Return a storage manager which can process this resource."""
for manager in (AmazonS3, ArvadosKeep, SevenBridges, DNAnexus, AzureBlob, GoogleCloud, RegularServer):
if manager.check_resource(resource):
return manager()
raise ValueError("Unexpected object store %(resource)s" %
{"resource": resource}) | [
"def",
"_get_storage_manager",
"(",
"resource",
")",
":",
"for",
"manager",
"in",
"(",
"AmazonS3",
",",
"ArvadosKeep",
",",
"SevenBridges",
",",
"DNAnexus",
",",
"AzureBlob",
",",
"GoogleCloud",
",",
"RegularServer",
")",
":",
"if",
"manager",
".",
"check_reso... | Return a storage manager which can process this resource. | [
"Return",
"a",
"storage",
"manager",
"which",
"can",
"process",
"this",
"resource",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L624-L631 | train | 218,350 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | default_region | def default_region(fname):
"""Return the default region for the received resource.
Note:
This feature is available only for AmazonS3 storage manager.
"""
manager = _get_storage_manager(fname)
if hasattr(manager, "get_region"):
return manager.get_region()
raise NotImplementedError("Unexpected object store %s" % fname) | python | def default_region(fname):
"""Return the default region for the received resource.
Note:
This feature is available only for AmazonS3 storage manager.
"""
manager = _get_storage_manager(fname)
if hasattr(manager, "get_region"):
return manager.get_region()
raise NotImplementedError("Unexpected object store %s" % fname) | [
"def",
"default_region",
"(",
"fname",
")",
":",
"manager",
"=",
"_get_storage_manager",
"(",
"fname",
")",
"if",
"hasattr",
"(",
"manager",
",",
"\"get_region\"",
")",
":",
"return",
"manager",
".",
"get_region",
"(",
")",
"raise",
"NotImplementedError",
"(",... | Return the default region for the received resource.
Note:
This feature is available only for AmazonS3 storage manager. | [
"Return",
"the",
"default",
"region",
"for",
"the",
"received",
"resource",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L651-L661 | train | 218,351 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | BlobHandle.blob_properties | def blob_properties(self):
"""Returns all user-defined metadata, standard HTTP properties,
and system properties for the blob.
"""
if not self._blob_properties:
self._blob_properties = self._blob_service.get_blob_properties(
container_name=self._container_name,
blob_name=self._blob_name)
return self._blob_properties | python | def blob_properties(self):
"""Returns all user-defined metadata, standard HTTP properties,
and system properties for the blob.
"""
if not self._blob_properties:
self._blob_properties = self._blob_service.get_blob_properties(
container_name=self._container_name,
blob_name=self._blob_name)
return self._blob_properties | [
"def",
"blob_properties",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_blob_properties",
":",
"self",
".",
"_blob_properties",
"=",
"self",
".",
"_blob_service",
".",
"get_blob_properties",
"(",
"container_name",
"=",
"self",
".",
"_container_name",
",",
... | Returns all user-defined metadata, standard HTTP properties,
and system properties for the blob. | [
"Returns",
"all",
"user",
"-",
"defined",
"metadata",
"standard",
"HTTP",
"properties",
"and",
"system",
"properties",
"for",
"the",
"blob",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L154-L162 | train | 218,352 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | BlobHandle._chunk_offsets | def _chunk_offsets(self):
"""Iterator over chunk offests."""
index = 0
blob_size = self.blob_properties.get('content-length')
while index < blob_size:
yield index
index = index + self._chunk_size | python | def _chunk_offsets(self):
"""Iterator over chunk offests."""
index = 0
blob_size = self.blob_properties.get('content-length')
while index < blob_size:
yield index
index = index + self._chunk_size | [
"def",
"_chunk_offsets",
"(",
"self",
")",
":",
"index",
"=",
"0",
"blob_size",
"=",
"self",
".",
"blob_properties",
".",
"get",
"(",
"'content-length'",
")",
"while",
"index",
"<",
"blob_size",
":",
"yield",
"index",
"index",
"=",
"index",
"+",
"self",
... | Iterator over chunk offests. | [
"Iterator",
"over",
"chunk",
"offests",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L164-L170 | train | 218,353 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | BlobHandle._chunk_iter | def _chunk_iter(self):
"""Iterator over the blob file."""
for chunk_offset in self._chunk_offsets():
yield self._download_chunk(chunk_offset=chunk_offset,
chunk_size=self._chunk_size) | python | def _chunk_iter(self):
"""Iterator over the blob file."""
for chunk_offset in self._chunk_offsets():
yield self._download_chunk(chunk_offset=chunk_offset,
chunk_size=self._chunk_size) | [
"def",
"_chunk_iter",
"(",
"self",
")",
":",
"for",
"chunk_offset",
"in",
"self",
".",
"_chunk_offsets",
"(",
")",
":",
"yield",
"self",
".",
"_download_chunk",
"(",
"chunk_offset",
"=",
"chunk_offset",
",",
"chunk_size",
"=",
"self",
".",
"_chunk_size",
")"... | Iterator over the blob file. | [
"Iterator",
"over",
"the",
"blob",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L172-L176 | train | 218,354 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3.parse_remote | def parse_remote(cls, filename):
"""Parses a remote filename into bucket and key information.
Handles S3 with optional region name specified in key:
BUCKETNAME@REGIONNAME/KEY
"""
parts = filename.split("//")[-1].split("/", 1)
bucket, key = parts if len(parts) == 2 else (parts[0], None)
if bucket.find("@") > 0:
bucket, region = bucket.split("@")
else:
region = None
return cls._REMOTE_FILE("s3", bucket, key, region) | python | def parse_remote(cls, filename):
"""Parses a remote filename into bucket and key information.
Handles S3 with optional region name specified in key:
BUCKETNAME@REGIONNAME/KEY
"""
parts = filename.split("//")[-1].split("/", 1)
bucket, key = parts if len(parts) == 2 else (parts[0], None)
if bucket.find("@") > 0:
bucket, region = bucket.split("@")
else:
region = None
return cls._REMOTE_FILE("s3", bucket, key, region) | [
"def",
"parse_remote",
"(",
"cls",
",",
"filename",
")",
":",
"parts",
"=",
"filename",
".",
"split",
"(",
"\"//\"",
")",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"bucket",
",",
"key",
"=",
"parts",
"if",
"len",
"(",
"parts"... | Parses a remote filename into bucket and key information.
Handles S3 with optional region name specified in key:
BUCKETNAME@REGIONNAME/KEY | [
"Parses",
"a",
"remote",
"filename",
"into",
"bucket",
"and",
"key",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L281-L294 | train | 218,355 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3._cl_aws_cli | def _cl_aws_cli(cls, file_info, region):
"""Command line required for download using the standard AWS
command line interface.
"""
s3file = cls._S3_FILE % {"bucket": file_info.bucket,
"key": file_info.key,
"region": ""}
command = [os.path.join(os.path.dirname(sys.executable), "aws"),
"s3", "cp", "--region", region, s3file]
return (command, "awscli") | python | def _cl_aws_cli(cls, file_info, region):
"""Command line required for download using the standard AWS
command line interface.
"""
s3file = cls._S3_FILE % {"bucket": file_info.bucket,
"key": file_info.key,
"region": ""}
command = [os.path.join(os.path.dirname(sys.executable), "aws"),
"s3", "cp", "--region", region, s3file]
return (command, "awscli") | [
"def",
"_cl_aws_cli",
"(",
"cls",
",",
"file_info",
",",
"region",
")",
":",
"s3file",
"=",
"cls",
".",
"_S3_FILE",
"%",
"{",
"\"bucket\"",
":",
"file_info",
".",
"bucket",
",",
"\"key\"",
":",
"file_info",
".",
"key",
",",
"\"region\"",
":",
"\"\"",
"... | Command line required for download using the standard AWS
command line interface. | [
"Command",
"line",
"required",
"for",
"download",
"using",
"the",
"standard",
"AWS",
"command",
"line",
"interface",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L297-L306 | train | 218,356 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3._cl_gof3r | def _cl_gof3r(file_info, region):
"""Command line required for download using gof3r."""
command = ["gof3r", "get", "--no-md5",
"-k", file_info.key,
"-b", file_info.bucket]
if region != "us-east-1":
command += ["--endpoint=s3-%s.amazonaws.com" % region]
return (command, "gof3r") | python | def _cl_gof3r(file_info, region):
"""Command line required for download using gof3r."""
command = ["gof3r", "get", "--no-md5",
"-k", file_info.key,
"-b", file_info.bucket]
if region != "us-east-1":
command += ["--endpoint=s3-%s.amazonaws.com" % region]
return (command, "gof3r") | [
"def",
"_cl_gof3r",
"(",
"file_info",
",",
"region",
")",
":",
"command",
"=",
"[",
"\"gof3r\"",
",",
"\"get\"",
",",
"\"--no-md5\"",
",",
"\"-k\"",
",",
"file_info",
".",
"key",
",",
"\"-b\"",
",",
"file_info",
".",
"bucket",
"]",
"if",
"region",
"!=",
... | Command line required for download using gof3r. | [
"Command",
"line",
"required",
"for",
"download",
"using",
"gof3r",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L309-L316 | train | 218,357 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3.get_region | def get_region(cls, resource=None):
"""Retrieve region from standard environmental variables
or file name.
More information of the following link: http://goo.gl/Vb9Jky
"""
if resource:
resource_info = cls.parse_remote(resource)
if resource_info.region:
return resource_info.region
return os.environ.get("AWS_DEFAULT_REGION", cls._DEFAULT_REGION) | python | def get_region(cls, resource=None):
"""Retrieve region from standard environmental variables
or file name.
More information of the following link: http://goo.gl/Vb9Jky
"""
if resource:
resource_info = cls.parse_remote(resource)
if resource_info.region:
return resource_info.region
return os.environ.get("AWS_DEFAULT_REGION", cls._DEFAULT_REGION) | [
"def",
"get_region",
"(",
"cls",
",",
"resource",
"=",
"None",
")",
":",
"if",
"resource",
":",
"resource_info",
"=",
"cls",
".",
"parse_remote",
"(",
"resource",
")",
"if",
"resource_info",
".",
"region",
":",
"return",
"resource_info",
".",
"region",
"re... | Retrieve region from standard environmental variables
or file name.
More information of the following link: http://goo.gl/Vb9Jky | [
"Retrieve",
"region",
"from",
"standard",
"environmental",
"variables",
"or",
"file",
"name",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L338-L349 | train | 218,358 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3.connect | def connect(cls, resource):
"""Connect to this Region's endpoint.
Returns a connection object pointing to the endpoint associated
to the received resource.
"""
import boto
return boto.s3.connect_to_region(cls.get_region(resource)) | python | def connect(cls, resource):
"""Connect to this Region's endpoint.
Returns a connection object pointing to the endpoint associated
to the received resource.
"""
import boto
return boto.s3.connect_to_region(cls.get_region(resource)) | [
"def",
"connect",
"(",
"cls",
",",
"resource",
")",
":",
"import",
"boto",
"return",
"boto",
".",
"s3",
".",
"connect_to_region",
"(",
"cls",
".",
"get_region",
"(",
"resource",
")",
")"
] | Connect to this Region's endpoint.
Returns a connection object pointing to the endpoint associated
to the received resource. | [
"Connect",
"to",
"this",
"Region",
"s",
"endpoint",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L362-L369 | train | 218,359 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3.open | def open(cls, filename):
"""Return a handle like object for streaming from S3."""
import boto
file_info = cls.parse_remote(filename)
connection = cls.connect(filename)
try:
s3_bucket = connection.get_bucket(file_info.bucket)
except boto.exception.S3ResponseError as error:
# if we don't have bucket permissions but folder permissions,
# try without validation
if error.status == 403:
s3_bucket = connection.get_bucket(file_info.bucket,
validate=False)
else:
raise
s3_key = s3_bucket.get_key(file_info.key)
if s3_key is None:
raise ValueError("Did not find S3 key: %s" % filename)
return S3Handle(s3_key) | python | def open(cls, filename):
"""Return a handle like object for streaming from S3."""
import boto
file_info = cls.parse_remote(filename)
connection = cls.connect(filename)
try:
s3_bucket = connection.get_bucket(file_info.bucket)
except boto.exception.S3ResponseError as error:
# if we don't have bucket permissions but folder permissions,
# try without validation
if error.status == 403:
s3_bucket = connection.get_bucket(file_info.bucket,
validate=False)
else:
raise
s3_key = s3_bucket.get_key(file_info.key)
if s3_key is None:
raise ValueError("Did not find S3 key: %s" % filename)
return S3Handle(s3_key) | [
"def",
"open",
"(",
"cls",
",",
"filename",
")",
":",
"import",
"boto",
"file_info",
"=",
"cls",
".",
"parse_remote",
"(",
"filename",
")",
"connection",
"=",
"cls",
".",
"connect",
"(",
"filename",
")",
"try",
":",
"s3_bucket",
"=",
"connection",
".",
... | Return a handle like object for streaming from S3. | [
"Return",
"a",
"handle",
"like",
"object",
"for",
"streaming",
"from",
"S3",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L434-L453 | train | 218,360 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AzureBlob.parse_remote | def parse_remote(cls, filename):
"""Parses a remote filename into blob information."""
blob_file = cls._URL_FORMAT.search(filename)
return cls._REMOTE_FILE("blob",
storage=blob_file.group("storage"),
container=blob_file.group("container"),
blob=blob_file.group("blob")) | python | def parse_remote(cls, filename):
"""Parses a remote filename into blob information."""
blob_file = cls._URL_FORMAT.search(filename)
return cls._REMOTE_FILE("blob",
storage=blob_file.group("storage"),
container=blob_file.group("container"),
blob=blob_file.group("blob")) | [
"def",
"parse_remote",
"(",
"cls",
",",
"filename",
")",
":",
"blob_file",
"=",
"cls",
".",
"_URL_FORMAT",
".",
"search",
"(",
"filename",
")",
"return",
"cls",
".",
"_REMOTE_FILE",
"(",
"\"blob\"",
",",
"storage",
"=",
"blob_file",
".",
"group",
"(",
"\... | Parses a remote filename into blob information. | [
"Parses",
"a",
"remote",
"filename",
"into",
"blob",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L479-L485 | train | 218,361 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AzureBlob.connect | def connect(cls, resource):
"""Returns a connection object pointing to the endpoint
associated to the received resource.
"""
from azure import storage as azure_storage
file_info = cls.parse_remote(resource)
return azure_storage.BlobService(file_info.storage) | python | def connect(cls, resource):
"""Returns a connection object pointing to the endpoint
associated to the received resource.
"""
from azure import storage as azure_storage
file_info = cls.parse_remote(resource)
return azure_storage.BlobService(file_info.storage) | [
"def",
"connect",
"(",
"cls",
",",
"resource",
")",
":",
"from",
"azure",
"import",
"storage",
"as",
"azure_storage",
"file_info",
"=",
"cls",
".",
"parse_remote",
"(",
"resource",
")",
"return",
"azure_storage",
".",
"BlobService",
"(",
"file_info",
".",
"s... | Returns a connection object pointing to the endpoint
associated to the received resource. | [
"Returns",
"a",
"connection",
"object",
"pointing",
"to",
"the",
"endpoint",
"associated",
"to",
"the",
"received",
"resource",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L488-L494 | train | 218,362 |
bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AzureBlob.open | def open(cls, filename):
"""Provide a handle-like object for streaming."""
file_info = cls.parse_remote(filename)
blob_service = cls.connect(filename)
return BlobHandle(blob_service=blob_service,
container=file_info.container,
blob=file_info.blob,
chunk_size=cls._BLOB_CHUNK_DATA_SIZE) | python | def open(cls, filename):
"""Provide a handle-like object for streaming."""
file_info = cls.parse_remote(filename)
blob_service = cls.connect(filename)
return BlobHandle(blob_service=blob_service,
container=file_info.container,
blob=file_info.blob,
chunk_size=cls._BLOB_CHUNK_DATA_SIZE) | [
"def",
"open",
"(",
"cls",
",",
"filename",
")",
":",
"file_info",
"=",
"cls",
".",
"parse_remote",
"(",
"filename",
")",
"blob_service",
"=",
"cls",
".",
"connect",
"(",
"filename",
")",
"return",
"BlobHandle",
"(",
"blob_service",
"=",
"blob_service",
",... | Provide a handle-like object for streaming. | [
"Provide",
"a",
"handle",
"-",
"like",
"object",
"for",
"streaming",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L538-L545 | train | 218,363 |
bcbio/bcbio-nextgen | bcbio/bam/cram.py | compress | def compress(in_bam, data):
"""Compress a BAM file to CRAM, providing indexed CRAM file.
Does 8 bin compression of quality score and read name removal
using bamUtils squeeze if `cram` specified:
http://genome.sph.umich.edu/wiki/BamUtil:_squeeze
Otherwise does `cram-lossless` which only converts to CRAM.
"""
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "archive"))
out_file = os.path.join(out_dir, "%s.cram" % os.path.splitext(os.path.basename(in_bam))[0])
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
compress_type = dd.get_archive(data)
samtools = config_utils.get_program("samtools", data["config"])
try:
bam_cmd = config_utils.get_program("bam", data["config"])
except config_utils.CmdNotFound:
bam_cmd = None
to_cram = ("{samtools} view -T {ref_file} -@ {cores} "
"-C -x BD -x BI -o {tx_out_file}")
compressed = False
if "cram" in compress_type and bam_cmd:
try:
cmd = ("{bam_cmd} squeeze --in {in_bam} --out -.ubam --keepDups "
"--binQualS=2,10,20,25,30,35,70 --binMid | " + to_cram)
do.run(cmd.format(**locals()), "Compress BAM to CRAM: quality score binning")
compressed = True
# Retry failures avoiding using bam squeeze which can cause issues
except subprocess.CalledProcessError:
pass
if not compressed:
cmd = (to_cram + " {in_bam}")
do.run(cmd.format(**locals()), "Compress BAM to CRAM: lossless")
index(out_file, data["config"])
return out_file | python | def compress(in_bam, data):
"""Compress a BAM file to CRAM, providing indexed CRAM file.
Does 8 bin compression of quality score and read name removal
using bamUtils squeeze if `cram` specified:
http://genome.sph.umich.edu/wiki/BamUtil:_squeeze
Otherwise does `cram-lossless` which only converts to CRAM.
"""
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "archive"))
out_file = os.path.join(out_dir, "%s.cram" % os.path.splitext(os.path.basename(in_bam))[0])
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
compress_type = dd.get_archive(data)
samtools = config_utils.get_program("samtools", data["config"])
try:
bam_cmd = config_utils.get_program("bam", data["config"])
except config_utils.CmdNotFound:
bam_cmd = None
to_cram = ("{samtools} view -T {ref_file} -@ {cores} "
"-C -x BD -x BI -o {tx_out_file}")
compressed = False
if "cram" in compress_type and bam_cmd:
try:
cmd = ("{bam_cmd} squeeze --in {in_bam} --out -.ubam --keepDups "
"--binQualS=2,10,20,25,30,35,70 --binMid | " + to_cram)
do.run(cmd.format(**locals()), "Compress BAM to CRAM: quality score binning")
compressed = True
# Retry failures avoiding using bam squeeze which can cause issues
except subprocess.CalledProcessError:
pass
if not compressed:
cmd = (to_cram + " {in_bam}")
do.run(cmd.format(**locals()), "Compress BAM to CRAM: lossless")
index(out_file, data["config"])
return out_file | [
"def",
"compress",
"(",
"in_bam",
",",
"data",
")",
":",
"out_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",
",",
"\"archive\"",
")",
")",
"out_file",
"=",
"os",
".",
... | Compress a BAM file to CRAM, providing indexed CRAM file.
Does 8 bin compression of quality score and read name removal
using bamUtils squeeze if `cram` specified:
http://genome.sph.umich.edu/wiki/BamUtil:_squeeze
Otherwise does `cram-lossless` which only converts to CRAM. | [
"Compress",
"a",
"BAM",
"file",
"to",
"CRAM",
"providing",
"indexed",
"CRAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/cram.py#L14-L52 | train | 218,364 |
bcbio/bcbio-nextgen | bcbio/bam/cram.py | index | def index(in_cram, config):
"""Ensure CRAM file has a .crai index file.
"""
out_file = in_cram + ".crai"
if not utils.file_uptodate(out_file, in_cram):
with file_transaction(config, in_cram + ".crai") as tx_out_file:
tx_in_file = os.path.splitext(tx_out_file)[0]
utils.symlink_plus(in_cram, tx_in_file)
cmd = "samtools index {tx_in_file}"
do.run(cmd.format(**locals()), "Index CRAM file")
return out_file | python | def index(in_cram, config):
"""Ensure CRAM file has a .crai index file.
"""
out_file = in_cram + ".crai"
if not utils.file_uptodate(out_file, in_cram):
with file_transaction(config, in_cram + ".crai") as tx_out_file:
tx_in_file = os.path.splitext(tx_out_file)[0]
utils.symlink_plus(in_cram, tx_in_file)
cmd = "samtools index {tx_in_file}"
do.run(cmd.format(**locals()), "Index CRAM file")
return out_file | [
"def",
"index",
"(",
"in_cram",
",",
"config",
")",
":",
"out_file",
"=",
"in_cram",
"+",
"\".crai\"",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"in_cram",
")",
":",
"with",
"file_transaction",
"(",
"config",
",",
"in_cram",
"+",
... | Ensure CRAM file has a .crai index file. | [
"Ensure",
"CRAM",
"file",
"has",
"a",
".",
"crai",
"index",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/cram.py#L54-L64 | train | 218,365 |
bcbio/bcbio-nextgen | bcbio/bam/cram.py | to_bam | def to_bam(in_file, out_file, data):
"""Convert CRAM file into BAM.
"""
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ["samtools", "view", "-O", "BAM", "-o", tx_out_file, in_file]
do.run(cmd, "Convert CRAM to BAM")
bam.index(out_file, data["config"])
return out_file | python | def to_bam(in_file, out_file, data):
"""Convert CRAM file into BAM.
"""
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ["samtools", "view", "-O", "BAM", "-o", tx_out_file, in_file]
do.run(cmd, "Convert CRAM to BAM")
bam.index(out_file, data["config"])
return out_file | [
"def",
"to_bam",
"(",
"in_file",
",",
"out_file",
",",
"data",
")",
":",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"in_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"cmd"... | Convert CRAM file into BAM. | [
"Convert",
"CRAM",
"file",
"into",
"BAM",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/cram.py#L66-L74 | train | 218,366 |
bcbio/bcbio-nextgen | bcbio/distributed/prun.py | start | def start(parallel, items, config, dirs=None, name=None, multiplier=1,
max_multicore=None):
"""Start a parallel cluster or machines to be used for running remote
functions.
Returns a function used to process, in parallel items with a given function.
Allows sharing of a single cluster across multiple functions with
identical resource requirements. Uses local execution for non-distributed
clusters or completed jobs.
A checkpoint directory keeps track of finished tasks, avoiding spinning up
clusters for sections that have been previous processed.
multiplier - Number of expected jobs per initial input item. Used to avoid
underscheduling cores when an item is split during processing.
max_multicore -- The maximum number of cores to use for each process. Can be
used to process less multicore usage when jobs run faster on more single
cores.
"""
if name:
checkpoint_dir = utils.safe_makedir(os.path.join(dirs["work"],
"checkpoints_parallel"))
checkpoint_file = os.path.join(checkpoint_dir, "%s.done" % name)
else:
checkpoint_file = None
sysinfo = system.get_info(dirs, parallel, config.get("resources", {}))
items = [x for x in items if x is not None] if items else []
max_multicore = int(max_multicore or sysinfo.get("cores", 1))
parallel = resources.calculate(parallel, items, sysinfo, config,
multiplier=multiplier,
max_multicore=max_multicore)
try:
view = None
if parallel["type"] == "ipython":
if checkpoint_file and os.path.exists(checkpoint_file):
logger.info("Running locally instead of distributed -- checkpoint passed: %s" % name)
parallel["cores_per_job"] = 1
parallel["num_jobs"] = 1
parallel["checkpointed"] = True
yield multi.runner(parallel, config)
else:
from bcbio.distributed import ipython
with ipython.create(parallel, dirs, config) as view:
yield ipython.runner(view, parallel, dirs, config)
else:
yield multi.runner(parallel, config)
except:
if view is not None:
from bcbio.distributed import ipython
ipython.stop(view)
raise
else:
for x in ["cores_per_job", "num_jobs", "mem"]:
parallel.pop(x, None)
if checkpoint_file:
with open(checkpoint_file, "w") as out_handle:
out_handle.write("done\n") | python | def start(parallel, items, config, dirs=None, name=None, multiplier=1,
max_multicore=None):
"""Start a parallel cluster or machines to be used for running remote
functions.
Returns a function used to process, in parallel items with a given function.
Allows sharing of a single cluster across multiple functions with
identical resource requirements. Uses local execution for non-distributed
clusters or completed jobs.
A checkpoint directory keeps track of finished tasks, avoiding spinning up
clusters for sections that have been previous processed.
multiplier - Number of expected jobs per initial input item. Used to avoid
underscheduling cores when an item is split during processing.
max_multicore -- The maximum number of cores to use for each process. Can be
used to process less multicore usage when jobs run faster on more single
cores.
"""
if name:
checkpoint_dir = utils.safe_makedir(os.path.join(dirs["work"],
"checkpoints_parallel"))
checkpoint_file = os.path.join(checkpoint_dir, "%s.done" % name)
else:
checkpoint_file = None
sysinfo = system.get_info(dirs, parallel, config.get("resources", {}))
items = [x for x in items if x is not None] if items else []
max_multicore = int(max_multicore or sysinfo.get("cores", 1))
parallel = resources.calculate(parallel, items, sysinfo, config,
multiplier=multiplier,
max_multicore=max_multicore)
try:
view = None
if parallel["type"] == "ipython":
if checkpoint_file and os.path.exists(checkpoint_file):
logger.info("Running locally instead of distributed -- checkpoint passed: %s" % name)
parallel["cores_per_job"] = 1
parallel["num_jobs"] = 1
parallel["checkpointed"] = True
yield multi.runner(parallel, config)
else:
from bcbio.distributed import ipython
with ipython.create(parallel, dirs, config) as view:
yield ipython.runner(view, parallel, dirs, config)
else:
yield multi.runner(parallel, config)
except:
if view is not None:
from bcbio.distributed import ipython
ipython.stop(view)
raise
else:
for x in ["cores_per_job", "num_jobs", "mem"]:
parallel.pop(x, None)
if checkpoint_file:
with open(checkpoint_file, "w") as out_handle:
out_handle.write("done\n") | [
"def",
"start",
"(",
"parallel",
",",
"items",
",",
"config",
",",
"dirs",
"=",
"None",
",",
"name",
"=",
"None",
",",
"multiplier",
"=",
"1",
",",
"max_multicore",
"=",
"None",
")",
":",
"if",
"name",
":",
"checkpoint_dir",
"=",
"utils",
".",
"safe_... | Start a parallel cluster or machines to be used for running remote
functions.
Returns a function used to process, in parallel items with a given function.
Allows sharing of a single cluster across multiple functions with
identical resource requirements. Uses local execution for non-distributed
clusters or completed jobs.
A checkpoint directory keeps track of finished tasks, avoiding spinning up
clusters for sections that have been previous processed.
multiplier - Number of expected jobs per initial input item. Used to avoid
underscheduling cores when an item is split during processing.
max_multicore -- The maximum number of cores to use for each process. Can be
used to process less multicore usage when jobs run faster on more single
cores. | [
"Start",
"a",
"parallel",
"cluster",
"or",
"machines",
"to",
"be",
"used",
"for",
"running",
"remote",
"functions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/prun.py#L12-L69 | train | 218,367 |
bcbio/bcbio-nextgen | scripts/utils/broad_redo_analysis.py | recalibrate_quality | def recalibrate_quality(bam_file, sam_ref, dbsnp_file, picard_dir):
"""Recalibrate alignments with GATK and provide pdf summary.
"""
cl = ["picard_gatk_recalibrate.py", picard_dir, sam_ref, bam_file]
if dbsnp_file:
cl.append(dbsnp_file)
subprocess.check_call(cl)
out_file = glob.glob("%s*gatkrecal.bam" % os.path.splitext(bam_file)[0])[0]
return out_file | python | def recalibrate_quality(bam_file, sam_ref, dbsnp_file, picard_dir):
"""Recalibrate alignments with GATK and provide pdf summary.
"""
cl = ["picard_gatk_recalibrate.py", picard_dir, sam_ref, bam_file]
if dbsnp_file:
cl.append(dbsnp_file)
subprocess.check_call(cl)
out_file = glob.glob("%s*gatkrecal.bam" % os.path.splitext(bam_file)[0])[0]
return out_file | [
"def",
"recalibrate_quality",
"(",
"bam_file",
",",
"sam_ref",
",",
"dbsnp_file",
",",
"picard_dir",
")",
":",
"cl",
"=",
"[",
"\"picard_gatk_recalibrate.py\"",
",",
"picard_dir",
",",
"sam_ref",
",",
"bam_file",
"]",
"if",
"dbsnp_file",
":",
"cl",
".",
"appen... | Recalibrate alignments with GATK and provide pdf summary. | [
"Recalibrate",
"alignments",
"with",
"GATK",
"and",
"provide",
"pdf",
"summary",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/broad_redo_analysis.py#L98-L106 | train | 218,368 |
bcbio/bcbio-nextgen | scripts/utils/broad_redo_analysis.py | run_genotyper | def run_genotyper(bam_file, ref_file, dbsnp_file, config_file):
"""Perform SNP genotyping and analysis using GATK.
"""
cl = ["gatk_genotyper.py", config_file, ref_file, bam_file]
if dbsnp_file:
cl.append(dbsnp_file)
subprocess.check_call(cl) | python | def run_genotyper(bam_file, ref_file, dbsnp_file, config_file):
"""Perform SNP genotyping and analysis using GATK.
"""
cl = ["gatk_genotyper.py", config_file, ref_file, bam_file]
if dbsnp_file:
cl.append(dbsnp_file)
subprocess.check_call(cl) | [
"def",
"run_genotyper",
"(",
"bam_file",
",",
"ref_file",
",",
"dbsnp_file",
",",
"config_file",
")",
":",
"cl",
"=",
"[",
"\"gatk_genotyper.py\"",
",",
"config_file",
",",
"ref_file",
",",
"bam_file",
"]",
"if",
"dbsnp_file",
":",
"cl",
".",
"append",
"(",
... | Perform SNP genotyping and analysis using GATK. | [
"Perform",
"SNP",
"genotyping",
"and",
"analysis",
"using",
"GATK",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/broad_redo_analysis.py#L108-L114 | train | 218,369 |
bcbio/bcbio-nextgen | bcbio/structural/battenberg.py | _do_run | def _do_run(paired):
"""Perform Battenberg caling with the paired dataset.
This purposely does not use a temporary directory for the output
since Battenberg does smart restarts.
"""
work_dir = _sv_workdir(paired.tumor_data)
out = _get_battenberg_out(paired, work_dir)
ignore_file = os.path.join(work_dir, "ignore_chromosomes.txt")
if len(_missing_files(out)) > 0:
ref_file = dd.get_ref_file(paired.tumor_data)
bat_datadir = os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir, "battenberg"))
ignore_file, gl_file = _make_ignore_file(work_dir, ref_file, ignore_file,
os.path.join(bat_datadir, "impute", "impute_info.txt"))
tumor_bam = paired.tumor_bam
normal_bam = paired.normal_bam
platform = dd.get_platform(paired.tumor_data)
genome_build = paired.tumor_data["genome_build"]
# scale cores to avoid over-using memory during imputation
cores = max(1, int(dd.get_num_cores(paired.tumor_data) * 0.5))
gender = {"male": "XY", "female": "XX", "unknown": "L"}.get(population.get_gender(paired.tumor_data))
if gender == "L":
gender_str = "-ge %s -gl %s" % (gender, gl_file)
else:
gender_str = "-ge %s" % (gender)
r_export_cmd = utils.get_R_exports()
local_sitelib = utils.R_sitelib()
cmd = ("export R_LIBS_USER={local_sitelib} && {r_export_cmd} && "
"battenberg.pl -t {cores} -o {work_dir} -r {ref_file}.fai "
"-tb {tumor_bam} -nb {normal_bam} -e {bat_datadir}/impute/impute_info.txt "
"-u {bat_datadir}/1000genomesloci -c {bat_datadir}/probloci.txt "
"-ig {ignore_file} {gender_str} "
"-assembly {genome_build} -species Human -platform {platform}")
do.run(cmd.format(**locals()), "Battenberg CNV calling")
assert len(_missing_files(out)) == 0, "Missing Battenberg output: %s" % _missing_files(out)
out["plot"] = _get_battenberg_out_plots(paired, work_dir)
out["ignore"] = ignore_file
return out | python | def _do_run(paired):
"""Perform Battenberg caling with the paired dataset.
This purposely does not use a temporary directory for the output
since Battenberg does smart restarts.
"""
work_dir = _sv_workdir(paired.tumor_data)
out = _get_battenberg_out(paired, work_dir)
ignore_file = os.path.join(work_dir, "ignore_chromosomes.txt")
if len(_missing_files(out)) > 0:
ref_file = dd.get_ref_file(paired.tumor_data)
bat_datadir = os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir, "battenberg"))
ignore_file, gl_file = _make_ignore_file(work_dir, ref_file, ignore_file,
os.path.join(bat_datadir, "impute", "impute_info.txt"))
tumor_bam = paired.tumor_bam
normal_bam = paired.normal_bam
platform = dd.get_platform(paired.tumor_data)
genome_build = paired.tumor_data["genome_build"]
# scale cores to avoid over-using memory during imputation
cores = max(1, int(dd.get_num_cores(paired.tumor_data) * 0.5))
gender = {"male": "XY", "female": "XX", "unknown": "L"}.get(population.get_gender(paired.tumor_data))
if gender == "L":
gender_str = "-ge %s -gl %s" % (gender, gl_file)
else:
gender_str = "-ge %s" % (gender)
r_export_cmd = utils.get_R_exports()
local_sitelib = utils.R_sitelib()
cmd = ("export R_LIBS_USER={local_sitelib} && {r_export_cmd} && "
"battenberg.pl -t {cores} -o {work_dir} -r {ref_file}.fai "
"-tb {tumor_bam} -nb {normal_bam} -e {bat_datadir}/impute/impute_info.txt "
"-u {bat_datadir}/1000genomesloci -c {bat_datadir}/probloci.txt "
"-ig {ignore_file} {gender_str} "
"-assembly {genome_build} -species Human -platform {platform}")
do.run(cmd.format(**locals()), "Battenberg CNV calling")
assert len(_missing_files(out)) == 0, "Missing Battenberg output: %s" % _missing_files(out)
out["plot"] = _get_battenberg_out_plots(paired, work_dir)
out["ignore"] = ignore_file
return out | [
"def",
"_do_run",
"(",
"paired",
")",
":",
"work_dir",
"=",
"_sv_workdir",
"(",
"paired",
".",
"tumor_data",
")",
"out",
"=",
"_get_battenberg_out",
"(",
"paired",
",",
"work_dir",
")",
"ignore_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
... | Perform Battenberg caling with the paired dataset.
This purposely does not use a temporary directory for the output
since Battenberg does smart restarts. | [
"Perform",
"Battenberg",
"caling",
"with",
"the",
"paired",
"dataset",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/battenberg.py#L40-L77 | train | 218,370 |
bcbio/bcbio-nextgen | bcbio/structural/battenberg.py | _make_ignore_file | def _make_ignore_file(work_dir, ref_file, ignore_file, impute_file):
"""Create input files with chromosomes to ignore and gender loci.
"""
gl_file = os.path.join(work_dir, "gender_loci.txt")
chroms = set([])
with open(impute_file) as in_handle:
for line in in_handle:
chrom = line.split()[0]
chroms.add(chrom)
if not chrom.startswith("chr"):
chroms.add("chr%s" % chrom)
with open(ignore_file, "w") as out_handle:
for contig in ref.file_contigs(ref_file):
if contig.name not in chroms:
out_handle.write("%s\n" % contig.name)
with open(gl_file, "w") as out_handle:
for contig in ref.file_contigs(ref_file):
if contig.name in ["Y", "chrY"]:
# From https://github.com/cancerit/cgpBattenberg/blob/dev/perl/share/gender/GRCh37d5_Y.loci
positions = [2934912, 4546684, 4549638, 4550107]
for pos in positions:
out_handle.write("%s\t%s\n" % (contig.name, pos))
return ignore_file, gl_file | python | def _make_ignore_file(work_dir, ref_file, ignore_file, impute_file):
"""Create input files with chromosomes to ignore and gender loci.
"""
gl_file = os.path.join(work_dir, "gender_loci.txt")
chroms = set([])
with open(impute_file) as in_handle:
for line in in_handle:
chrom = line.split()[0]
chroms.add(chrom)
if not chrom.startswith("chr"):
chroms.add("chr%s" % chrom)
with open(ignore_file, "w") as out_handle:
for contig in ref.file_contigs(ref_file):
if contig.name not in chroms:
out_handle.write("%s\n" % contig.name)
with open(gl_file, "w") as out_handle:
for contig in ref.file_contigs(ref_file):
if contig.name in ["Y", "chrY"]:
# From https://github.com/cancerit/cgpBattenberg/blob/dev/perl/share/gender/GRCh37d5_Y.loci
positions = [2934912, 4546684, 4549638, 4550107]
for pos in positions:
out_handle.write("%s\t%s\n" % (contig.name, pos))
return ignore_file, gl_file | [
"def",
"_make_ignore_file",
"(",
"work_dir",
",",
"ref_file",
",",
"ignore_file",
",",
"impute_file",
")",
":",
"gl_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"gender_loci.txt\"",
")",
"chroms",
"=",
"set",
"(",
"[",
"]",
")",
"w... | Create input files with chromosomes to ignore and gender loci. | [
"Create",
"input",
"files",
"with",
"chromosomes",
"to",
"ignore",
"and",
"gender",
"loci",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/battenberg.py#L79-L101 | train | 218,371 |
bcbio/bcbio-nextgen | bcbio/illumina/transfer.py | copy_flowcell | def copy_flowcell(dname, fastq_dir, sample_cfile, config):
"""Copy required files for processing using rsync, potentially to a remote server.
"""
with utils.chdir(dname):
reports = reduce(operator.add,
[glob.glob("*.xml"),
glob.glob("Data/Intensities/BaseCalls/*.xml"),
glob.glob("Data/Intensities/BaseCalls/*.xsl"),
glob.glob("Data/Intensities/BaseCalls/*.htm"),
["Data/Intensities/BaseCalls/Plots", "Data/reports",
"Data/Status.htm", "Data/Status_Files", "InterOp"]])
run_info = reduce(operator.add,
[glob.glob("run_info.yaml"),
glob.glob("*.csv")])
fastq = glob.glob(os.path.join(fastq_dir.replace(dname + "/", "", 1),
"*.gz"))
configs = [sample_cfile.replace(dname + "/", "", 1)]
include_file = os.path.join(dname, "transfer_files.txt")
with open(include_file, "w") as out_handle:
out_handle.write("+ */\n")
for fname in configs + fastq + run_info + reports:
out_handle.write("+ %s\n" % fname)
out_handle.write("- *\n")
# remote transfer
if utils.get_in(config, ("process", "host")):
dest = "%s@%s:%s" % (utils.get_in(config, ("process", "username")),
utils.get_in(config, ("process", "host")),
utils.get_in(config, ("process", "dir")))
# local transfer
else:
dest = utils.get_in(config, ("process", "dir"))
cmd = ["rsync", "-akmrtv", "--include-from=%s" % include_file, dname, dest]
logger.info("Copying files to analysis machine")
logger.info(" ".join(cmd))
subprocess.check_call(cmd) | python | def copy_flowcell(dname, fastq_dir, sample_cfile, config):
"""Copy required files for processing using rsync, potentially to a remote server.
"""
with utils.chdir(dname):
reports = reduce(operator.add,
[glob.glob("*.xml"),
glob.glob("Data/Intensities/BaseCalls/*.xml"),
glob.glob("Data/Intensities/BaseCalls/*.xsl"),
glob.glob("Data/Intensities/BaseCalls/*.htm"),
["Data/Intensities/BaseCalls/Plots", "Data/reports",
"Data/Status.htm", "Data/Status_Files", "InterOp"]])
run_info = reduce(operator.add,
[glob.glob("run_info.yaml"),
glob.glob("*.csv")])
fastq = glob.glob(os.path.join(fastq_dir.replace(dname + "/", "", 1),
"*.gz"))
configs = [sample_cfile.replace(dname + "/", "", 1)]
include_file = os.path.join(dname, "transfer_files.txt")
with open(include_file, "w") as out_handle:
out_handle.write("+ */\n")
for fname in configs + fastq + run_info + reports:
out_handle.write("+ %s\n" % fname)
out_handle.write("- *\n")
# remote transfer
if utils.get_in(config, ("process", "host")):
dest = "%s@%s:%s" % (utils.get_in(config, ("process", "username")),
utils.get_in(config, ("process", "host")),
utils.get_in(config, ("process", "dir")))
# local transfer
else:
dest = utils.get_in(config, ("process", "dir"))
cmd = ["rsync", "-akmrtv", "--include-from=%s" % include_file, dname, dest]
logger.info("Copying files to analysis machine")
logger.info(" ".join(cmd))
subprocess.check_call(cmd) | [
"def",
"copy_flowcell",
"(",
"dname",
",",
"fastq_dir",
",",
"sample_cfile",
",",
"config",
")",
":",
"with",
"utils",
".",
"chdir",
"(",
"dname",
")",
":",
"reports",
"=",
"reduce",
"(",
"operator",
".",
"add",
",",
"[",
"glob",
".",
"glob",
"(",
"\... | Copy required files for processing using rsync, potentially to a remote server. | [
"Copy",
"required",
"files",
"for",
"processing",
"using",
"rsync",
"potentially",
"to",
"a",
"remote",
"server",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/transfer.py#L12-L46 | train | 218,372 |
bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | _umis_cmd | def _umis_cmd(data):
"""Return umis command line argument, with correct python and locale.
"""
return "%s %s %s" % (utils.locale_export(),
utils.get_program_python("umis"),
config_utils.get_program("umis", data["config"], default="umis")) | python | def _umis_cmd(data):
"""Return umis command line argument, with correct python and locale.
"""
return "%s %s %s" % (utils.locale_export(),
utils.get_program_python("umis"),
config_utils.get_program("umis", data["config"], default="umis")) | [
"def",
"_umis_cmd",
"(",
"data",
")",
":",
"return",
"\"%s %s %s\"",
"%",
"(",
"utils",
".",
"locale_export",
"(",
")",
",",
"utils",
".",
"get_program_python",
"(",
"\"umis\"",
")",
",",
"config_utils",
".",
"get_program",
"(",
"\"umis\"",
",",
"data",
"[... | Return umis command line argument, with correct python and locale. | [
"Return",
"umis",
"command",
"line",
"argument",
"with",
"correct",
"python",
"and",
"locale",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L119-L124 | train | 218,373 |
bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | demultiplex_samples | def demultiplex_samples(data):
"""
demultiplex a fastqtransformed FASTQ file into separate sample barcode files
"""
work_dir = os.path.join(dd.get_work_dir(data), "umis")
sample_dir = os.path.join(work_dir, dd.get_sample_name(data))
demulti_dir = os.path.join(sample_dir, "demultiplexed")
files = data["files"]
if len(files) == 2:
logger.error("Sample demultiplexing doesn't handle paired-end reads, but "
"we can add it. Open an issue here https://github.com/bcbio/bcbio-nextgen/issues if you need this and we'll add it.")
sys.exit(1)
else:
fq1 = files[0]
# check if samples need to be demultiplexed
with open_fastq(fq1) as in_handle:
read = next(in_handle)
if "SAMPLE_" not in read:
return [[data]]
bcfile = get_sample_barcodes(dd.get_sample_barcodes(data), sample_dir)
demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*"))
if demultiplexed:
return [split_demultiplexed_sampledata(data, demultiplexed)]
umis = _umis_cmd(data)
cmd = ("{umis} demultiplex_samples --nedit 1 --barcodes {bcfile} "
"--out_dir {tx_dir} {fq1}")
msg = "Demultiplexing {fq1}."
with file_transaction(data, demulti_dir) as tx_dir:
do.run(cmd.format(**locals()), msg.format(**locals()))
demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*"))
return [split_demultiplexed_sampledata(data, demultiplexed)] | python | def demultiplex_samples(data):
"""
demultiplex a fastqtransformed FASTQ file into separate sample barcode files
"""
work_dir = os.path.join(dd.get_work_dir(data), "umis")
sample_dir = os.path.join(work_dir, dd.get_sample_name(data))
demulti_dir = os.path.join(sample_dir, "demultiplexed")
files = data["files"]
if len(files) == 2:
logger.error("Sample demultiplexing doesn't handle paired-end reads, but "
"we can add it. Open an issue here https://github.com/bcbio/bcbio-nextgen/issues if you need this and we'll add it.")
sys.exit(1)
else:
fq1 = files[0]
# check if samples need to be demultiplexed
with open_fastq(fq1) as in_handle:
read = next(in_handle)
if "SAMPLE_" not in read:
return [[data]]
bcfile = get_sample_barcodes(dd.get_sample_barcodes(data), sample_dir)
demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*"))
if demultiplexed:
return [split_demultiplexed_sampledata(data, demultiplexed)]
umis = _umis_cmd(data)
cmd = ("{umis} demultiplex_samples --nedit 1 --barcodes {bcfile} "
"--out_dir {tx_dir} {fq1}")
msg = "Demultiplexing {fq1}."
with file_transaction(data, demulti_dir) as tx_dir:
do.run(cmd.format(**locals()), msg.format(**locals()))
demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*"))
return [split_demultiplexed_sampledata(data, demultiplexed)] | [
"def",
"demultiplex_samples",
"(",
"data",
")",
":",
"work_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",
",",
"\"umis\"",
")",
"sample_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"dd... | demultiplex a fastqtransformed FASTQ file into separate sample barcode files | [
"demultiplex",
"a",
"fastqtransformed",
"FASTQ",
"file",
"into",
"separate",
"sample",
"barcode",
"files"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L359-L391 | train | 218,374 |
bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | split_demultiplexed_sampledata | def split_demultiplexed_sampledata(data, demultiplexed):
"""
splits demultiplexed samples into separate entries in the global sample
datadict
"""
datadicts = []
samplename = dd.get_sample_name(data)
for fastq in demultiplexed:
barcode = os.path.basename(fastq).split(".")[0]
datadict = copy.deepcopy(data)
datadict = dd.set_sample_name(datadict, samplename + "-" + barcode)
datadict = dd.set_description(datadict, samplename + "-" + barcode)
datadict["rgnames"]["rg"] = samplename + "-" + barcode
datadict["name"]= ["", samplename + "-" + barcode]
datadict["files"] = [fastq]
datadicts.append(datadict)
return datadicts | python | def split_demultiplexed_sampledata(data, demultiplexed):
"""
splits demultiplexed samples into separate entries in the global sample
datadict
"""
datadicts = []
samplename = dd.get_sample_name(data)
for fastq in demultiplexed:
barcode = os.path.basename(fastq).split(".")[0]
datadict = copy.deepcopy(data)
datadict = dd.set_sample_name(datadict, samplename + "-" + barcode)
datadict = dd.set_description(datadict, samplename + "-" + barcode)
datadict["rgnames"]["rg"] = samplename + "-" + barcode
datadict["name"]= ["", samplename + "-" + barcode]
datadict["files"] = [fastq]
datadicts.append(datadict)
return datadicts | [
"def",
"split_demultiplexed_sampledata",
"(",
"data",
",",
"demultiplexed",
")",
":",
"datadicts",
"=",
"[",
"]",
"samplename",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"for",
"fastq",
"in",
"demultiplexed",
":",
"barcode",
"=",
"os",
".",
"path"... | splits demultiplexed samples into separate entries in the global sample
datadict | [
"splits",
"demultiplexed",
"samples",
"into",
"separate",
"entries",
"in",
"the",
"global",
"sample",
"datadict"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L393-L409 | train | 218,375 |
bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | is_transformed | def is_transformed(fastq):
"""
check the first 100 reads to see if a FASTQ file has already been transformed
by umis
"""
with open_fastq(fastq) as in_handle:
for line in islice(in_handle, 400):
if "UMI_" in line:
return True
return False | python | def is_transformed(fastq):
"""
check the first 100 reads to see if a FASTQ file has already been transformed
by umis
"""
with open_fastq(fastq) as in_handle:
for line in islice(in_handle, 400):
if "UMI_" in line:
return True
return False | [
"def",
"is_transformed",
"(",
"fastq",
")",
":",
"with",
"open_fastq",
"(",
"fastq",
")",
"as",
"in_handle",
":",
"for",
"line",
"in",
"islice",
"(",
"in_handle",
",",
"400",
")",
":",
"if",
"\"UMI_\"",
"in",
"line",
":",
"return",
"True",
"return",
"F... | check the first 100 reads to see if a FASTQ file has already been transformed
by umis | [
"check",
"the",
"first",
"100",
"reads",
"to",
"see",
"if",
"a",
"FASTQ",
"file",
"has",
"already",
"been",
"transformed",
"by",
"umis"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L504-L514 | train | 218,376 |
bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | SparseMatrix.read | def read(self, filename, rowprefix=None, colprefix=None, delim=":"):
"""read a sparse matrix, loading row and column name files. if
specified, will add a prefix to the row or column names"""
self.matrix = scipy.io.mmread(filename)
with open(filename + ".rownames") as in_handle:
self.rownames = [x.strip() for x in in_handle]
if rowprefix:
self.rownames = [rowprefix + delim + x for x in self.rownames]
with open(filename + ".colnames") as in_handle:
self.colnames = [x.strip() for x in in_handle]
if colprefix:
self.colnames = [colprefix + delim + x for x in self.colnames] | python | def read(self, filename, rowprefix=None, colprefix=None, delim=":"):
"""read a sparse matrix, loading row and column name files. if
specified, will add a prefix to the row or column names"""
self.matrix = scipy.io.mmread(filename)
with open(filename + ".rownames") as in_handle:
self.rownames = [x.strip() for x in in_handle]
if rowprefix:
self.rownames = [rowprefix + delim + x for x in self.rownames]
with open(filename + ".colnames") as in_handle:
self.colnames = [x.strip() for x in in_handle]
if colprefix:
self.colnames = [colprefix + delim + x for x in self.colnames] | [
"def",
"read",
"(",
"self",
",",
"filename",
",",
"rowprefix",
"=",
"None",
",",
"colprefix",
"=",
"None",
",",
"delim",
"=",
"\":\"",
")",
":",
"self",
".",
"matrix",
"=",
"scipy",
".",
"io",
".",
"mmread",
"(",
"filename",
")",
"with",
"open",
"(... | read a sparse matrix, loading row and column name files. if
specified, will add a prefix to the row or column names | [
"read",
"a",
"sparse",
"matrix",
"loading",
"row",
"and",
"column",
"name",
"files",
".",
"if",
"specified",
"will",
"add",
"a",
"prefix",
"to",
"the",
"row",
"or",
"column",
"names"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L42-L54 | train | 218,377 |
bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | SparseMatrix.write | def write(self, filename):
"""read a sparse matrix, loading row and column name files"""
if file_exists(filename):
return filename
out_files = [filename, filename + ".rownames", filename + ".colnames"]
with file_transaction(out_files) as tx_out_files:
with open(tx_out_files[0], "wb") as out_handle:
scipy.io.mmwrite(out_handle, scipy.sparse.csr_matrix(self.matrix))
pd.Series(self.rownames).to_csv(tx_out_files[1], index=False)
pd.Series(self.colnames).to_csv(tx_out_files[2], index=False)
return filename | python | def write(self, filename):
"""read a sparse matrix, loading row and column name files"""
if file_exists(filename):
return filename
out_files = [filename, filename + ".rownames", filename + ".colnames"]
with file_transaction(out_files) as tx_out_files:
with open(tx_out_files[0], "wb") as out_handle:
scipy.io.mmwrite(out_handle, scipy.sparse.csr_matrix(self.matrix))
pd.Series(self.rownames).to_csv(tx_out_files[1], index=False)
pd.Series(self.colnames).to_csv(tx_out_files[2], index=False)
return filename | [
"def",
"write",
"(",
"self",
",",
"filename",
")",
":",
"if",
"file_exists",
"(",
"filename",
")",
":",
"return",
"filename",
"out_files",
"=",
"[",
"filename",
",",
"filename",
"+",
"\".rownames\"",
",",
"filename",
"+",
"\".colnames\"",
"]",
"with",
"fil... | read a sparse matrix, loading row and column name files | [
"read",
"a",
"sparse",
"matrix",
"loading",
"row",
"and",
"column",
"name",
"files"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L56-L66 | train | 218,378 |
bcbio/bcbio-nextgen | bcbio/srna/sample.py | sample_annotation | def sample_annotation(data):
"""
Annotate miRNAs using miRBase database with seqbuster tool
"""
names = data["rgnames"]['sample']
tools = dd.get_expression_caller(data)
work_dir = os.path.join(dd.get_work_dir(data), "mirbase")
out_dir = os.path.join(work_dir, names)
utils.safe_makedir(out_dir)
out_file = op.join(out_dir, names)
if dd.get_mirbase_hairpin(data):
mirbase = op.abspath(op.dirname(dd.get_mirbase_hairpin(data)))
if utils.file_exists(data["collapse"]):
data['transcriptome_bam'] = _align(data["collapse"],
dd.get_mirbase_hairpin(data),
out_file,
data)
data['seqbuster'] = _miraligner(data["collapse"], out_file,
dd.get_species(data),
mirbase,
data['config'])
data["mirtop"] = _mirtop(data['seqbuster'],
dd.get_species(data),
mirbase,
out_dir,
data['config'])
else:
logger.debug("Trimmed collapsed file is empty for %s." % names)
else:
logger.debug("No annotation file from miRBase.")
sps = dd.get_species(data) if dd.get_species(data) else "None"
logger.debug("Looking for mirdeep2 database for %s" % names)
if file_exists(op.join(dd.get_work_dir(data), "mirdeep2", "novel", "hairpin.fa")):
data['seqbuster_novel'] = _miraligner(data["collapse"], "%s_novel" % out_file, sps,
op.join(dd.get_work_dir(data),
"mirdeep2", "novel"),
data['config'])
if "trna" in tools:
data['trna'] = _mint_trna_annotation(data)
data = spikein.counts_spikein(data)
return [[data]] | python | def sample_annotation(data):
"""
Annotate miRNAs using miRBase database with seqbuster tool
"""
names = data["rgnames"]['sample']
tools = dd.get_expression_caller(data)
work_dir = os.path.join(dd.get_work_dir(data), "mirbase")
out_dir = os.path.join(work_dir, names)
utils.safe_makedir(out_dir)
out_file = op.join(out_dir, names)
if dd.get_mirbase_hairpin(data):
mirbase = op.abspath(op.dirname(dd.get_mirbase_hairpin(data)))
if utils.file_exists(data["collapse"]):
data['transcriptome_bam'] = _align(data["collapse"],
dd.get_mirbase_hairpin(data),
out_file,
data)
data['seqbuster'] = _miraligner(data["collapse"], out_file,
dd.get_species(data),
mirbase,
data['config'])
data["mirtop"] = _mirtop(data['seqbuster'],
dd.get_species(data),
mirbase,
out_dir,
data['config'])
else:
logger.debug("Trimmed collapsed file is empty for %s." % names)
else:
logger.debug("No annotation file from miRBase.")
sps = dd.get_species(data) if dd.get_species(data) else "None"
logger.debug("Looking for mirdeep2 database for %s" % names)
if file_exists(op.join(dd.get_work_dir(data), "mirdeep2", "novel", "hairpin.fa")):
data['seqbuster_novel'] = _miraligner(data["collapse"], "%s_novel" % out_file, sps,
op.join(dd.get_work_dir(data),
"mirdeep2", "novel"),
data['config'])
if "trna" in tools:
data['trna'] = _mint_trna_annotation(data)
data = spikein.counts_spikein(data)
return [[data]] | [
"def",
"sample_annotation",
"(",
"data",
")",
":",
"names",
"=",
"data",
"[",
"\"rgnames\"",
"]",
"[",
"'sample'",
"]",
"tools",
"=",
"dd",
".",
"get_expression_caller",
"(",
"data",
")",
"work_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",... | Annotate miRNAs using miRBase database with seqbuster tool | [
"Annotate",
"miRNAs",
"using",
"miRBase",
"database",
"with",
"seqbuster",
"tool"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L106-L149 | train | 218,379 |
bcbio/bcbio-nextgen | bcbio/srna/sample.py | _prepare_file | def _prepare_file(fn, out_dir):
"""Cut the beginning of the reads to avoid detection of miRNAs"""
atropos = _get_atropos()
cmd = "{atropos} trim --max-reads 500000 -u 22 -se {fn} -o {tx_file}"
out_file = os.path.join(out_dir, append_stem(os.path.basename(fn), "end"))
if file_exists(out_file):
return out_file
with file_transaction(out_file) as tx_file:
do.run(cmd.format(**locals()))
return out_file | python | def _prepare_file(fn, out_dir):
"""Cut the beginning of the reads to avoid detection of miRNAs"""
atropos = _get_atropos()
cmd = "{atropos} trim --max-reads 500000 -u 22 -se {fn} -o {tx_file}"
out_file = os.path.join(out_dir, append_stem(os.path.basename(fn), "end"))
if file_exists(out_file):
return out_file
with file_transaction(out_file) as tx_file:
do.run(cmd.format(**locals()))
return out_file | [
"def",
"_prepare_file",
"(",
"fn",
",",
"out_dir",
")",
":",
"atropos",
"=",
"_get_atropos",
"(",
")",
"cmd",
"=",
"\"{atropos} trim --max-reads 500000 -u 22 -se {fn} -o {tx_file}\"",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"append_st... | Cut the beginning of the reads to avoid detection of miRNAs | [
"Cut",
"the",
"beginning",
"of",
"the",
"reads",
"to",
"avoid",
"detection",
"of",
"miRNAs"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L151-L160 | train | 218,380 |
bcbio/bcbio-nextgen | bcbio/srna/sample.py | _collapse | def _collapse(in_file):
"""
Collpase reads into unique sequences with seqcluster
"""
seqcluster = op.join(utils.get_bcbio_bin(), "seqcluster")
out_file = "%s.fastq" % utils.splitext_plus(append_stem(in_file, "_trimmed"))[0]
out_dir = os.path.dirname(in_file)
if file_exists(out_file):
return out_file
cmd = ("{seqcluster} collapse -o {out_dir} -f {in_file} -m 1 --min_size 16")
do.run(cmd.format(**locals()), "Running seqcluster collapse in %s." % in_file)
return out_file | python | def _collapse(in_file):
"""
Collpase reads into unique sequences with seqcluster
"""
seqcluster = op.join(utils.get_bcbio_bin(), "seqcluster")
out_file = "%s.fastq" % utils.splitext_plus(append_stem(in_file, "_trimmed"))[0]
out_dir = os.path.dirname(in_file)
if file_exists(out_file):
return out_file
cmd = ("{seqcluster} collapse -o {out_dir} -f {in_file} -m 1 --min_size 16")
do.run(cmd.format(**locals()), "Running seqcluster collapse in %s." % in_file)
return out_file | [
"def",
"_collapse",
"(",
"in_file",
")",
":",
"seqcluster",
"=",
"op",
".",
"join",
"(",
"utils",
".",
"get_bcbio_bin",
"(",
")",
",",
"\"seqcluster\"",
")",
"out_file",
"=",
"\"%s.fastq\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"append_stem",
"(",
"in_... | Collpase reads into unique sequences with seqcluster | [
"Collpase",
"reads",
"into",
"unique",
"sequences",
"with",
"seqcluster"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L180-L191 | train | 218,381 |
bcbio/bcbio-nextgen | bcbio/srna/sample.py | _summary | def _summary(in_file):
"""
Calculate size distribution after adapter removal
"""
data = Counter()
out_file = in_file + "_size_stats"
if file_exists(out_file):
return out_file
with open(in_file) as in_handle:
for line in in_handle:
counts = int(line.strip().split("_x")[1])
line = next(in_handle)
l = len(line.strip())
next(in_handle)
next(in_handle)
data[l] += counts
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, 'w') as out_handle:
for l, c in data.items():
out_handle.write("%s %s\n" % (l, c))
return out_file | python | def _summary(in_file):
"""
Calculate size distribution after adapter removal
"""
data = Counter()
out_file = in_file + "_size_stats"
if file_exists(out_file):
return out_file
with open(in_file) as in_handle:
for line in in_handle:
counts = int(line.strip().split("_x")[1])
line = next(in_handle)
l = len(line.strip())
next(in_handle)
next(in_handle)
data[l] += counts
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, 'w') as out_handle:
for l, c in data.items():
out_handle.write("%s %s\n" % (l, c))
return out_file | [
"def",
"_summary",
"(",
"in_file",
")",
":",
"data",
"=",
"Counter",
"(",
")",
"out_file",
"=",
"in_file",
"+",
"\"_size_stats\"",
"if",
"file_exists",
"(",
"out_file",
")",
":",
"return",
"out_file",
"with",
"open",
"(",
"in_file",
")",
"as",
"in_handle",... | Calculate size distribution after adapter removal | [
"Calculate",
"size",
"distribution",
"after",
"adapter",
"removal"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L193-L213 | train | 218,382 |
bcbio/bcbio-nextgen | bcbio/srna/sample.py | _mirtop | def _mirtop(input_fn, sps, db, out_dir, config):
"""
Convert to GFF3 standard format
"""
hairpin = os.path.join(db, "hairpin.fa")
gtf = os.path.join(db, "mirbase.gff3")
if not file_exists(hairpin) or not file_exists(gtf):
logger.warning("%s or %s are not installed. Skipping." % (hairpin, gtf))
return None
out_gtf_fn = "%s.gtf" % utils.splitext_plus(os.path.basename(input_fn))[0]
out_gff_fn = "%s.gff" % utils.splitext_plus(os.path.basename(input_fn))[0]
export = _get_env()
cmd = ("{export} mirtop gff --sps {sps} --hairpin {hairpin} "
"--gtf {gtf} --format seqbuster -o {out_tx} {input_fn}")
if not file_exists(os.path.join(out_dir, out_gtf_fn)) and \
not file_exists(os.path.join(out_dir, out_gff_fn)):
with tx_tmpdir() as out_tx:
do.run(cmd.format(**locals()), "Do miRNA annotation for %s" % input_fn)
with utils.chdir(out_tx):
out_fn = out_gtf_fn if utils.file_exists(out_gtf_fn) \
else out_gff_fn
if utils.file_exists(out_fn):
shutil.move(os.path.join(out_tx, out_fn),
os.path.join(out_dir, out_fn))
out_fn = out_gtf_fn if utils.file_exists(os.path.join(out_dir, out_gtf_fn)) \
else os.path.join(out_dir, out_gff_fn)
if utils.file_exists(os.path.join(out_dir, out_fn)):
return os.path.join(out_dir, out_fn) | python | def _mirtop(input_fn, sps, db, out_dir, config):
"""
Convert to GFF3 standard format
"""
hairpin = os.path.join(db, "hairpin.fa")
gtf = os.path.join(db, "mirbase.gff3")
if not file_exists(hairpin) or not file_exists(gtf):
logger.warning("%s or %s are not installed. Skipping." % (hairpin, gtf))
return None
out_gtf_fn = "%s.gtf" % utils.splitext_plus(os.path.basename(input_fn))[0]
out_gff_fn = "%s.gff" % utils.splitext_plus(os.path.basename(input_fn))[0]
export = _get_env()
cmd = ("{export} mirtop gff --sps {sps} --hairpin {hairpin} "
"--gtf {gtf} --format seqbuster -o {out_tx} {input_fn}")
if not file_exists(os.path.join(out_dir, out_gtf_fn)) and \
not file_exists(os.path.join(out_dir, out_gff_fn)):
with tx_tmpdir() as out_tx:
do.run(cmd.format(**locals()), "Do miRNA annotation for %s" % input_fn)
with utils.chdir(out_tx):
out_fn = out_gtf_fn if utils.file_exists(out_gtf_fn) \
else out_gff_fn
if utils.file_exists(out_fn):
shutil.move(os.path.join(out_tx, out_fn),
os.path.join(out_dir, out_fn))
out_fn = out_gtf_fn if utils.file_exists(os.path.join(out_dir, out_gtf_fn)) \
else os.path.join(out_dir, out_gff_fn)
if utils.file_exists(os.path.join(out_dir, out_fn)):
return os.path.join(out_dir, out_fn) | [
"def",
"_mirtop",
"(",
"input_fn",
",",
"sps",
",",
"db",
",",
"out_dir",
",",
"config",
")",
":",
"hairpin",
"=",
"os",
".",
"path",
".",
"join",
"(",
"db",
",",
"\"hairpin.fa\"",
")",
"gtf",
"=",
"os",
".",
"path",
".",
"join",
"(",
"db",
",",
... | Convert to GFF3 standard format | [
"Convert",
"to",
"GFF3",
"standard",
"format"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L254-L281 | train | 218,383 |
bcbio/bcbio-nextgen | bcbio/srna/sample.py | _trna_annotation | def _trna_annotation(data):
"""
use tDRmapper to quantify tRNAs
"""
trna_ref = op.join(dd.get_srna_trna_file(data))
name = dd.get_sample_name(data)
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna", name))
in_file = op.basename(data["clean_fastq"])
tdrmapper = os.path.join(os.path.dirname(sys.executable), "TdrMappingScripts.pl")
perl_export = utils.get_perl_exports()
if not file_exists(trna_ref) or not file_exists(tdrmapper):
logger.info("There is no tRNA annotation to run TdrMapper.")
return work_dir
out_file = op.join(work_dir, in_file + ".hq_cs.mapped")
if not file_exists(out_file):
with tx_tmpdir(data) as txdir:
with utils.chdir(txdir):
utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file))
cmd = ("{perl_export} && perl {tdrmapper} {trna_ref} {in_file}").format(**locals())
do.run(cmd, "tRNA for %s" % name)
for filename in glob.glob("*mapped*"):
shutil.move(filename, work_dir)
return work_dir | python | def _trna_annotation(data):
"""
use tDRmapper to quantify tRNAs
"""
trna_ref = op.join(dd.get_srna_trna_file(data))
name = dd.get_sample_name(data)
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna", name))
in_file = op.basename(data["clean_fastq"])
tdrmapper = os.path.join(os.path.dirname(sys.executable), "TdrMappingScripts.pl")
perl_export = utils.get_perl_exports()
if not file_exists(trna_ref) or not file_exists(tdrmapper):
logger.info("There is no tRNA annotation to run TdrMapper.")
return work_dir
out_file = op.join(work_dir, in_file + ".hq_cs.mapped")
if not file_exists(out_file):
with tx_tmpdir(data) as txdir:
with utils.chdir(txdir):
utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file))
cmd = ("{perl_export} && perl {tdrmapper} {trna_ref} {in_file}").format(**locals())
do.run(cmd, "tRNA for %s" % name)
for filename in glob.glob("*mapped*"):
shutil.move(filename, work_dir)
return work_dir | [
"def",
"_trna_annotation",
"(",
"data",
")",
":",
"trna_ref",
"=",
"op",
".",
"join",
"(",
"dd",
".",
"get_srna_trna_file",
"(",
"data",
")",
")",
"name",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"work_dir",
"=",
"utils",
".",
"safe_makedir",... | use tDRmapper to quantify tRNAs | [
"use",
"tDRmapper",
"to",
"quantify",
"tRNAs"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L283-L305 | train | 218,384 |
bcbio/bcbio-nextgen | bcbio/srna/sample.py | _mint_trna_annotation | def _mint_trna_annotation(data):
"""
use MINTmap to quantify tRNAs
"""
trna_lookup = op.join(dd.get_srna_mint_lookup(data))
trna_space = op.join(dd.get_srna_mint_space(data))
trna_other = op.join(dd.get_srna_mint_other(data))
name = dd.get_sample_name(data)
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna_mint", name))
in_file = op.basename(data["clean_fastq"])
mintmap = os.path.realpath(os.path.join(os.path.dirname(sys.executable), "MINTmap.pl"))
perl_export = utils.get_perl_exports()
if not file_exists(trna_lookup) or not file_exists(mintmap):
logger.info("There is no tRNA annotation to run MINTmap.")
return work_dir
jar_folder = os.path.join(os.path.dirname(mintmap), "MINTplates")
out_file = op.join(work_dir, name + "-MINTmap_v1-exclusive-tRFs.expression.txt")
if not file_exists(out_file):
with tx_tmpdir(data) as txdir:
with utils.chdir(txdir):
utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file))
cmd = ("{perl_export} && {mintmap} -f {in_file} -p {name} "
"-l {trna_lookup} -s {trna_space} -j {jar_folder} "
"-o {trna_other}").format(**locals())
do.run(cmd, "tRNA for %s" % name)
for filename in glob.glob("*MINTmap*"):
shutil.move(filename, work_dir)
return work_dir | python | def _mint_trna_annotation(data):
"""
use MINTmap to quantify tRNAs
"""
trna_lookup = op.join(dd.get_srna_mint_lookup(data))
trna_space = op.join(dd.get_srna_mint_space(data))
trna_other = op.join(dd.get_srna_mint_other(data))
name = dd.get_sample_name(data)
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna_mint", name))
in_file = op.basename(data["clean_fastq"])
mintmap = os.path.realpath(os.path.join(os.path.dirname(sys.executable), "MINTmap.pl"))
perl_export = utils.get_perl_exports()
if not file_exists(trna_lookup) or not file_exists(mintmap):
logger.info("There is no tRNA annotation to run MINTmap.")
return work_dir
jar_folder = os.path.join(os.path.dirname(mintmap), "MINTplates")
out_file = op.join(work_dir, name + "-MINTmap_v1-exclusive-tRFs.expression.txt")
if not file_exists(out_file):
with tx_tmpdir(data) as txdir:
with utils.chdir(txdir):
utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file))
cmd = ("{perl_export} && {mintmap} -f {in_file} -p {name} "
"-l {trna_lookup} -s {trna_space} -j {jar_folder} "
"-o {trna_other}").format(**locals())
do.run(cmd, "tRNA for %s" % name)
for filename in glob.glob("*MINTmap*"):
shutil.move(filename, work_dir)
return work_dir | [
"def",
"_mint_trna_annotation",
"(",
"data",
")",
":",
"trna_lookup",
"=",
"op",
".",
"join",
"(",
"dd",
".",
"get_srna_mint_lookup",
"(",
"data",
")",
")",
"trna_space",
"=",
"op",
".",
"join",
"(",
"dd",
".",
"get_srna_mint_space",
"(",
"data",
")",
")... | use MINTmap to quantify tRNAs | [
"use",
"MINTmap",
"to",
"quantify",
"tRNAs"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L307-L334 | train | 218,385 |
bcbio/bcbio-nextgen | bcbio/bam/fasta.py | sequence_length | def sequence_length(fasta):
"""
return a dict of the lengths of sequences in a fasta file
"""
sequences = SeqIO.parse(fasta, "fasta")
records = {record.id: len(record) for record in sequences}
return records | python | def sequence_length(fasta):
"""
return a dict of the lengths of sequences in a fasta file
"""
sequences = SeqIO.parse(fasta, "fasta")
records = {record.id: len(record) for record in sequences}
return records | [
"def",
"sequence_length",
"(",
"fasta",
")",
":",
"sequences",
"=",
"SeqIO",
".",
"parse",
"(",
"fasta",
",",
"\"fasta\"",
")",
"records",
"=",
"{",
"record",
".",
"id",
":",
"len",
"(",
"record",
")",
"for",
"record",
"in",
"sequences",
"}",
"return",... | return a dict of the lengths of sequences in a fasta file | [
"return",
"a",
"dict",
"of",
"the",
"lengths",
"of",
"sequences",
"in",
"a",
"fasta",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fasta.py#L5-L11 | train | 218,386 |
bcbio/bcbio-nextgen | bcbio/bam/fasta.py | sequence_names | def sequence_names(fasta):
"""
return a list of the sequence IDs in a FASTA file
"""
sequences = SeqIO.parse(fasta, "fasta")
records = [record.id for record in sequences]
return records | python | def sequence_names(fasta):
"""
return a list of the sequence IDs in a FASTA file
"""
sequences = SeqIO.parse(fasta, "fasta")
records = [record.id for record in sequences]
return records | [
"def",
"sequence_names",
"(",
"fasta",
")",
":",
"sequences",
"=",
"SeqIO",
".",
"parse",
"(",
"fasta",
",",
"\"fasta\"",
")",
"records",
"=",
"[",
"record",
".",
"id",
"for",
"record",
"in",
"sequences",
"]",
"return",
"records"
] | return a list of the sequence IDs in a FASTA file | [
"return",
"a",
"list",
"of",
"the",
"sequence",
"IDs",
"in",
"a",
"FASTA",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fasta.py#L13-L19 | train | 218,387 |
bcbio/bcbio-nextgen | bcbio/srna/mirdeep.py | _prepare_inputs | def _prepare_inputs(ma_fn, bam_file, out_dir):
"""
Convert to fastq with counts
"""
fixed_fa = os.path.join(out_dir, "file_reads.fa")
count_name =dict()
with file_transaction(fixed_fa) as out_tx:
with open(out_tx, 'w') as out_handle:
with open(ma_fn) as in_handle:
h = next(in_handle)
for line in in_handle:
cols = line.split("\t")
name_with_counts = "%s_x%s" % (cols[0], sum(map(int, cols[2:])))
count_name[cols[0]] = name_with_counts
out_handle.write(">%s\n%s\n" % (name_with_counts, cols[1]))
fixed_bam = os.path.join(out_dir, "align.bam")
bam_handle = pysam.AlignmentFile(bam_file, "rb")
with pysam.AlignmentFile(fixed_bam, "wb", template=bam_handle) as out_handle:
for read in bam_handle.fetch():
read.query_name = count_name[read.query_name]
out_handle.write(read)
return fixed_fa, fixed_bam | python | def _prepare_inputs(ma_fn, bam_file, out_dir):
"""
Convert to fastq with counts
"""
fixed_fa = os.path.join(out_dir, "file_reads.fa")
count_name =dict()
with file_transaction(fixed_fa) as out_tx:
with open(out_tx, 'w') as out_handle:
with open(ma_fn) as in_handle:
h = next(in_handle)
for line in in_handle:
cols = line.split("\t")
name_with_counts = "%s_x%s" % (cols[0], sum(map(int, cols[2:])))
count_name[cols[0]] = name_with_counts
out_handle.write(">%s\n%s\n" % (name_with_counts, cols[1]))
fixed_bam = os.path.join(out_dir, "align.bam")
bam_handle = pysam.AlignmentFile(bam_file, "rb")
with pysam.AlignmentFile(fixed_bam, "wb", template=bam_handle) as out_handle:
for read in bam_handle.fetch():
read.query_name = count_name[read.query_name]
out_handle.write(read)
return fixed_fa, fixed_bam | [
"def",
"_prepare_inputs",
"(",
"ma_fn",
",",
"bam_file",
",",
"out_dir",
")",
":",
"fixed_fa",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"\"file_reads.fa\"",
")",
"count_name",
"=",
"dict",
"(",
")",
"with",
"file_transaction",
"(",
"fixed_... | Convert to fastq with counts | [
"Convert",
"to",
"fastq",
"with",
"counts"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/mirdeep.py#L52-L74 | train | 218,388 |
bcbio/bcbio-nextgen | bcbio/srna/mirdeep.py | _parse_novel | def _parse_novel(csv_file, sps="new"):
"""Create input of novel miRNAs from miRDeep2"""
read = 0
seen = set()
safe_makedir("novel")
with open("novel/hairpin.fa", "w") as fa_handle, open("novel/miRNA.str", "w") as str_handle:
with open(csv_file) as in_handle:
for line in in_handle:
if line.startswith("mature miRBase miRNAs detected by miRDeep2"):
break
if line.startswith("novel miRNAs predicted"):
read = 1
line = next(in_handle)
continue
if read and line.strip():
cols = line.strip().split("\t")
name, start, score = cols[0], cols[16], cols[1]
if float(score) < 1:
continue
m5p, m3p, pre = cols[13], cols[14], cols[15].replace('u', 't').upper()
m5p_start = cols[15].find(m5p) + 1
m3p_start = cols[15].find(m3p) + 1
m5p_end = m5p_start + len(m5p) - 1
m3p_end = m3p_start + len(m3p) - 1
if m5p in seen:
continue
fa_handle.write(">{sps}-{name} {start}\n{pre}\n".format(**locals()))
str_handle.write(">{sps}-{name} ({score}) [{sps}-{name}-5p:{m5p_start}-{m5p_end}] [{sps}-{name}-3p:{m3p_start}-{m3p_end}]\n".format(**locals()))
seen.add(m5p)
return op.abspath("novel") | python | def _parse_novel(csv_file, sps="new"):
"""Create input of novel miRNAs from miRDeep2"""
read = 0
seen = set()
safe_makedir("novel")
with open("novel/hairpin.fa", "w") as fa_handle, open("novel/miRNA.str", "w") as str_handle:
with open(csv_file) as in_handle:
for line in in_handle:
if line.startswith("mature miRBase miRNAs detected by miRDeep2"):
break
if line.startswith("novel miRNAs predicted"):
read = 1
line = next(in_handle)
continue
if read and line.strip():
cols = line.strip().split("\t")
name, start, score = cols[0], cols[16], cols[1]
if float(score) < 1:
continue
m5p, m3p, pre = cols[13], cols[14], cols[15].replace('u', 't').upper()
m5p_start = cols[15].find(m5p) + 1
m3p_start = cols[15].find(m3p) + 1
m5p_end = m5p_start + len(m5p) - 1
m3p_end = m3p_start + len(m3p) - 1
if m5p in seen:
continue
fa_handle.write(">{sps}-{name} {start}\n{pre}\n".format(**locals()))
str_handle.write(">{sps}-{name} ({score}) [{sps}-{name}-5p:{m5p_start}-{m5p_end}] [{sps}-{name}-3p:{m3p_start}-{m3p_end}]\n".format(**locals()))
seen.add(m5p)
return op.abspath("novel") | [
"def",
"_parse_novel",
"(",
"csv_file",
",",
"sps",
"=",
"\"new\"",
")",
":",
"read",
"=",
"0",
"seen",
"=",
"set",
"(",
")",
"safe_makedir",
"(",
"\"novel\"",
")",
"with",
"open",
"(",
"\"novel/hairpin.fa\"",
",",
"\"w\"",
")",
"as",
"fa_handle",
",",
... | Create input of novel miRNAs from miRDeep2 | [
"Create",
"input",
"of",
"novel",
"miRNAs",
"from",
"miRDeep2"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/mirdeep.py#L76-L105 | train | 218,389 |
bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | _run_smoove | def _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items):
"""Run lumpy-sv using smoove.
"""
batch = sshared.get_cur_batch(items)
ext = "-%s-svs" % batch if batch else "-svs"
name = "%s%s" % (dd.get_sample_name(items[0]), ext)
out_file = os.path.join(work_dir, "%s-smoove.genotyped.vcf.gz" % name)
sv_exclude_bed = sshared.prepare_exclude_file(items, out_file)
old_out_file = os.path.join(work_dir, "%s%s-prep.vcf.gz"
% (os.path.splitext(os.path.basename(items[0]["align_bam"]))[0], ext))
if utils.file_exists(old_out_file):
return old_out_file, sv_exclude_bed
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
cores = dd.get_num_cores(items[0])
out_dir = os.path.dirname(tx_out_file)
ref_file = dd.get_ref_file(items[0])
full_bams = " ".join(_prepare_smoove_bams(full_bams, sr_bams, disc_bams, items,
os.path.dirname(tx_out_file)))
std_excludes = ["~^GL", "~^HLA", "~_random", "~^chrUn", "~alt", "~decoy"]
def _is_std_exclude(n):
clean_excludes = [x.replace("~", "").replace("^", "") for x in std_excludes]
return any([n.startswith(x) or n.endswith(x) for x in clean_excludes])
exclude_chrs = [c.name for c in ref.file_contigs(ref_file)
if not chromhacks.is_nonalt(c.name) and not _is_std_exclude(c.name)]
exclude_chrs = "--excludechroms '%s'" % ",".join(std_excludes + exclude_chrs)
exclude_bed = ("--exclude %s" % sv_exclude_bed) if utils.file_exists(sv_exclude_bed) else ""
tempdir = os.path.dirname(tx_out_file)
cmd = ("export TMPDIR={tempdir} && "
"smoove call --processes {cores} --genotype --removepr --fasta {ref_file} "
"--name {name} --outdir {out_dir} "
"{exclude_bed} {exclude_chrs} {full_bams}")
with utils.chdir(tempdir):
try:
do.run(cmd.format(**locals()), "smoove lumpy calling", items[0])
except subprocess.CalledProcessError as msg:
if _allowed_errors(msg):
vcfutils.write_empty_vcf(tx_out_file, config=items[0]["config"],
samples=[dd.get_sample_name(d) for d in items])
else:
logger.exception()
raise
vcfutils.bgzip_and_index(out_file, items[0]["config"])
return out_file, sv_exclude_bed | python | def _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items):
"""Run lumpy-sv using smoove.
"""
batch = sshared.get_cur_batch(items)
ext = "-%s-svs" % batch if batch else "-svs"
name = "%s%s" % (dd.get_sample_name(items[0]), ext)
out_file = os.path.join(work_dir, "%s-smoove.genotyped.vcf.gz" % name)
sv_exclude_bed = sshared.prepare_exclude_file(items, out_file)
old_out_file = os.path.join(work_dir, "%s%s-prep.vcf.gz"
% (os.path.splitext(os.path.basename(items[0]["align_bam"]))[0], ext))
if utils.file_exists(old_out_file):
return old_out_file, sv_exclude_bed
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
cores = dd.get_num_cores(items[0])
out_dir = os.path.dirname(tx_out_file)
ref_file = dd.get_ref_file(items[0])
full_bams = " ".join(_prepare_smoove_bams(full_bams, sr_bams, disc_bams, items,
os.path.dirname(tx_out_file)))
std_excludes = ["~^GL", "~^HLA", "~_random", "~^chrUn", "~alt", "~decoy"]
def _is_std_exclude(n):
clean_excludes = [x.replace("~", "").replace("^", "") for x in std_excludes]
return any([n.startswith(x) or n.endswith(x) for x in clean_excludes])
exclude_chrs = [c.name for c in ref.file_contigs(ref_file)
if not chromhacks.is_nonalt(c.name) and not _is_std_exclude(c.name)]
exclude_chrs = "--excludechroms '%s'" % ",".join(std_excludes + exclude_chrs)
exclude_bed = ("--exclude %s" % sv_exclude_bed) if utils.file_exists(sv_exclude_bed) else ""
tempdir = os.path.dirname(tx_out_file)
cmd = ("export TMPDIR={tempdir} && "
"smoove call --processes {cores} --genotype --removepr --fasta {ref_file} "
"--name {name} --outdir {out_dir} "
"{exclude_bed} {exclude_chrs} {full_bams}")
with utils.chdir(tempdir):
try:
do.run(cmd.format(**locals()), "smoove lumpy calling", items[0])
except subprocess.CalledProcessError as msg:
if _allowed_errors(msg):
vcfutils.write_empty_vcf(tx_out_file, config=items[0]["config"],
samples=[dd.get_sample_name(d) for d in items])
else:
logger.exception()
raise
vcfutils.bgzip_and_index(out_file, items[0]["config"])
return out_file, sv_exclude_bed | [
"def",
"_run_smoove",
"(",
"full_bams",
",",
"sr_bams",
",",
"disc_bams",
",",
"work_dir",
",",
"items",
")",
":",
"batch",
"=",
"sshared",
".",
"get_cur_batch",
"(",
"items",
")",
"ext",
"=",
"\"-%s-svs\"",
"%",
"batch",
"if",
"batch",
"else",
"\"-svs\"",... | Run lumpy-sv using smoove. | [
"Run",
"lumpy",
"-",
"sv",
"using",
"smoove",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L28-L71 | train | 218,390 |
bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | _filter_by_support | def _filter_by_support(in_file, data):
"""Filter call file based on supporting evidence, adding FILTER annotations to VCF.
Filters based on the following criteria:
- Minimum read support for the call (SU = total support)
- Large calls need split read evidence.
"""
rc_filter = ("FORMAT/SU < 4 || "
"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)>50000) || "
"(FORMAT/SR == 0 && FORMAT/SU < 5 && ABS(SVLEN)<2000) || "
"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)<300)")
return vfilter.cutoff_w_expression(in_file, rc_filter, data, name="ReadCountSupport",
limit_regions=None) | python | def _filter_by_support(in_file, data):
"""Filter call file based on supporting evidence, adding FILTER annotations to VCF.
Filters based on the following criteria:
- Minimum read support for the call (SU = total support)
- Large calls need split read evidence.
"""
rc_filter = ("FORMAT/SU < 4 || "
"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)>50000) || "
"(FORMAT/SR == 0 && FORMAT/SU < 5 && ABS(SVLEN)<2000) || "
"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)<300)")
return vfilter.cutoff_w_expression(in_file, rc_filter, data, name="ReadCountSupport",
limit_regions=None) | [
"def",
"_filter_by_support",
"(",
"in_file",
",",
"data",
")",
":",
"rc_filter",
"=",
"(",
"\"FORMAT/SU < 4 || \"",
"\"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)>50000) || \"",
"\"(FORMAT/SR == 0 && FORMAT/SU < 5 && ABS(SVLEN)<2000) || \"",
"\"(FORMAT/SR == 0 && FORMAT/SU < 15 && AB... | Filter call file based on supporting evidence, adding FILTER annotations to VCF.
Filters based on the following criteria:
- Minimum read support for the call (SU = total support)
- Large calls need split read evidence. | [
"Filter",
"call",
"file",
"based",
"on",
"supporting",
"evidence",
"adding",
"FILTER",
"annotations",
"to",
"VCF",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L104-L116 | train | 218,391 |
bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | _filter_by_background | def _filter_by_background(base_name, back_samples, gt_vcfs, data):
"""Filter base samples, marking any also present in the background.
"""
filtname = "InBackground"
filtdoc = "Variant also present in background samples with same genotype"
orig_vcf = gt_vcfs[base_name]
out_file = "%s-backfilter.vcf" % (utils.splitext_plus(orig_vcf)[0])
if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
with file_transaction(data, out_file) as tx_out_file:
with utils.open_gzipsafe(orig_vcf) as in_handle:
inp = vcf.Reader(in_handle, orig_vcf)
inp.filters[filtname] = vcf.parser._Filter(filtname, filtdoc)
with open(tx_out_file, "w") as out_handle:
outp = vcf.Writer(out_handle, inp)
for rec in inp:
if _genotype_in_background(rec, base_name, back_samples):
rec.add_filter(filtname)
outp.write_record(rec)
if utils.file_exists(out_file + ".gz"):
out_file = out_file + ".gz"
gt_vcfs[base_name] = vcfutils.bgzip_and_index(out_file, data["config"])
return gt_vcfs | python | def _filter_by_background(base_name, back_samples, gt_vcfs, data):
"""Filter base samples, marking any also present in the background.
"""
filtname = "InBackground"
filtdoc = "Variant also present in background samples with same genotype"
orig_vcf = gt_vcfs[base_name]
out_file = "%s-backfilter.vcf" % (utils.splitext_plus(orig_vcf)[0])
if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
with file_transaction(data, out_file) as tx_out_file:
with utils.open_gzipsafe(orig_vcf) as in_handle:
inp = vcf.Reader(in_handle, orig_vcf)
inp.filters[filtname] = vcf.parser._Filter(filtname, filtdoc)
with open(tx_out_file, "w") as out_handle:
outp = vcf.Writer(out_handle, inp)
for rec in inp:
if _genotype_in_background(rec, base_name, back_samples):
rec.add_filter(filtname)
outp.write_record(rec)
if utils.file_exists(out_file + ".gz"):
out_file = out_file + ".gz"
gt_vcfs[base_name] = vcfutils.bgzip_and_index(out_file, data["config"])
return gt_vcfs | [
"def",
"_filter_by_background",
"(",
"base_name",
",",
"back_samples",
",",
"gt_vcfs",
",",
"data",
")",
":",
"filtname",
"=",
"\"InBackground\"",
"filtdoc",
"=",
"\"Variant also present in background samples with same genotype\"",
"orig_vcf",
"=",
"gt_vcfs",
"[",
"base_n... | Filter base samples, marking any also present in the background. | [
"Filter",
"base",
"samples",
"marking",
"any",
"also",
"present",
"in",
"the",
"background",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L118-L139 | train | 218,392 |
bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | _genotype_in_background | def _genotype_in_background(rec, base_name, back_samples):
"""Check if the genotype in the record of interest is present in the background records.
"""
def passes(rec):
return not rec.FILTER or len(rec.FILTER) == 0
return (passes(rec) and
any(rec.genotype(base_name).gt_alleles == rec.genotype(back_name).gt_alleles
for back_name in back_samples)) | python | def _genotype_in_background(rec, base_name, back_samples):
"""Check if the genotype in the record of interest is present in the background records.
"""
def passes(rec):
return not rec.FILTER or len(rec.FILTER) == 0
return (passes(rec) and
any(rec.genotype(base_name).gt_alleles == rec.genotype(back_name).gt_alleles
for back_name in back_samples)) | [
"def",
"_genotype_in_background",
"(",
"rec",
",",
"base_name",
",",
"back_samples",
")",
":",
"def",
"passes",
"(",
"rec",
")",
":",
"return",
"not",
"rec",
".",
"FILTER",
"or",
"len",
"(",
"rec",
".",
"FILTER",
")",
"==",
"0",
"return",
"(",
"passes"... | Check if the genotype in the record of interest is present in the background records. | [
"Check",
"if",
"the",
"genotype",
"in",
"the",
"record",
"of",
"interest",
"is",
"present",
"in",
"the",
"background",
"records",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L141-L148 | train | 218,393 |
bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | run | def run(items):
"""Perform detection of structural variations with lumpy.
"""
paired = vcfutils.get_paired(items)
work_dir = _sv_workdir(paired.tumor_data if paired and paired.tumor_data else items[0])
previous_evidence = {}
full_bams, sr_bams, disc_bams = [], [], []
for data in items:
full_bams.append(dd.get_align_bam(data))
sr_bam, disc_bam = sshared.find_existing_split_discordants(data)
sr_bams.append(sr_bam)
disc_bams.append(disc_bam)
cur_dels, cur_dups = _bedpes_from_cnv_caller(data, work_dir)
previous_evidence[dd.get_sample_name(data)] = {}
if cur_dels and utils.file_exists(cur_dels):
previous_evidence[dd.get_sample_name(data)]["dels"] = cur_dels
if cur_dups and utils.file_exists(cur_dups):
previous_evidence[dd.get_sample_name(data)]["dups"] = cur_dups
lumpy_vcf, exclude_file = _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items)
lumpy_vcf = sshared.annotate_with_depth(lumpy_vcf, items)
gt_vcfs = {}
# Retain paired samples with tumor/normal genotyped in one file
if paired and paired.normal_name:
batches = [[paired.tumor_data, paired.normal_data]]
else:
batches = [[x] for x in items]
for batch_items in batches:
for data in batch_items:
gt_vcfs[dd.get_sample_name(data)] = _filter_by_support(lumpy_vcf, data)
if paired and paired.normal_name:
gt_vcfs = _filter_by_background(paired.tumor_name, [paired.normal_name], gt_vcfs, paired.tumor_data)
out = []
upload_counts = collections.defaultdict(int)
for data in items:
if "sv" not in data:
data["sv"] = []
vcf_file = gt_vcfs.get(dd.get_sample_name(data))
if vcf_file:
effects_vcf, _ = effects.add_to_vcf(vcf_file, data, "snpeff")
data["sv"].append({"variantcaller": "lumpy",
"vrn_file": effects_vcf or vcf_file,
"do_upload": upload_counts[vcf_file] == 0, # only upload a single file per batch
"exclude_file": exclude_file})
upload_counts[vcf_file] += 1
out.append(data)
return out | python | def run(items):
"""Perform detection of structural variations with lumpy.
"""
paired = vcfutils.get_paired(items)
work_dir = _sv_workdir(paired.tumor_data if paired and paired.tumor_data else items[0])
previous_evidence = {}
full_bams, sr_bams, disc_bams = [], [], []
for data in items:
full_bams.append(dd.get_align_bam(data))
sr_bam, disc_bam = sshared.find_existing_split_discordants(data)
sr_bams.append(sr_bam)
disc_bams.append(disc_bam)
cur_dels, cur_dups = _bedpes_from_cnv_caller(data, work_dir)
previous_evidence[dd.get_sample_name(data)] = {}
if cur_dels and utils.file_exists(cur_dels):
previous_evidence[dd.get_sample_name(data)]["dels"] = cur_dels
if cur_dups and utils.file_exists(cur_dups):
previous_evidence[dd.get_sample_name(data)]["dups"] = cur_dups
lumpy_vcf, exclude_file = _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items)
lumpy_vcf = sshared.annotate_with_depth(lumpy_vcf, items)
gt_vcfs = {}
# Retain paired samples with tumor/normal genotyped in one file
if paired and paired.normal_name:
batches = [[paired.tumor_data, paired.normal_data]]
else:
batches = [[x] for x in items]
for batch_items in batches:
for data in batch_items:
gt_vcfs[dd.get_sample_name(data)] = _filter_by_support(lumpy_vcf, data)
if paired and paired.normal_name:
gt_vcfs = _filter_by_background(paired.tumor_name, [paired.normal_name], gt_vcfs, paired.tumor_data)
out = []
upload_counts = collections.defaultdict(int)
for data in items:
if "sv" not in data:
data["sv"] = []
vcf_file = gt_vcfs.get(dd.get_sample_name(data))
if vcf_file:
effects_vcf, _ = effects.add_to_vcf(vcf_file, data, "snpeff")
data["sv"].append({"variantcaller": "lumpy",
"vrn_file": effects_vcf or vcf_file,
"do_upload": upload_counts[vcf_file] == 0, # only upload a single file per batch
"exclude_file": exclude_file})
upload_counts[vcf_file] += 1
out.append(data)
return out | [
"def",
"run",
"(",
"items",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired",
"(",
"items",
")",
"work_dir",
"=",
"_sv_workdir",
"(",
"paired",
".",
"tumor_data",
"if",
"paired",
"and",
"paired",
".",
"tumor_data",
"else",
"items",
"[",
"0",
"]",
... | Perform detection of structural variations with lumpy. | [
"Perform",
"detection",
"of",
"structural",
"variations",
"with",
"lumpy",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L154-L200 | train | 218,394 |
bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | _bedpes_from_cnv_caller | def _bedpes_from_cnv_caller(data, work_dir):
"""Retrieve BEDPEs deletion and duplications from CNV callers.
Currently integrates with CNVkit.
"""
supported = set(["cnvkit"])
cns_file = None
for sv in data.get("sv", []):
if sv["variantcaller"] in supported and "cns" in sv and "lumpy_usecnv" in dd.get_tools_on(data):
cns_file = sv["cns"]
break
if not cns_file:
return None, None
else:
out_base = os.path.join(work_dir, utils.splitext_plus(os.path.basename(cns_file))[0])
out_dels = out_base + "-dels.bedpe"
out_dups = out_base + "-dups.bedpe"
if not os.path.exists(out_dels) or not os.path.exists(out_dups):
with file_transaction(data, out_dels, out_dups) as (tx_out_dels, tx_out_dups):
try:
cnvanator_path = config_utils.get_program("cnvanator_to_bedpes.py", data)
except config_utils.CmdNotFound:
return None, None
cmd = [cnvanator_path, "-c", cns_file, "--cnvkit",
"--del_o=%s" % tx_out_dels, "--dup_o=%s" % tx_out_dups,
"-b", "250"] # XXX Uses default piece size for CNVkit. Right approach?
do.run(cmd, "Prepare CNVkit as input for lumpy", data)
return out_dels, out_dups | python | def _bedpes_from_cnv_caller(data, work_dir):
"""Retrieve BEDPEs deletion and duplications from CNV callers.
Currently integrates with CNVkit.
"""
supported = set(["cnvkit"])
cns_file = None
for sv in data.get("sv", []):
if sv["variantcaller"] in supported and "cns" in sv and "lumpy_usecnv" in dd.get_tools_on(data):
cns_file = sv["cns"]
break
if not cns_file:
return None, None
else:
out_base = os.path.join(work_dir, utils.splitext_plus(os.path.basename(cns_file))[0])
out_dels = out_base + "-dels.bedpe"
out_dups = out_base + "-dups.bedpe"
if not os.path.exists(out_dels) or not os.path.exists(out_dups):
with file_transaction(data, out_dels, out_dups) as (tx_out_dels, tx_out_dups):
try:
cnvanator_path = config_utils.get_program("cnvanator_to_bedpes.py", data)
except config_utils.CmdNotFound:
return None, None
cmd = [cnvanator_path, "-c", cns_file, "--cnvkit",
"--del_o=%s" % tx_out_dels, "--dup_o=%s" % tx_out_dups,
"-b", "250"] # XXX Uses default piece size for CNVkit. Right approach?
do.run(cmd, "Prepare CNVkit as input for lumpy", data)
return out_dels, out_dups | [
"def",
"_bedpes_from_cnv_caller",
"(",
"data",
",",
"work_dir",
")",
":",
"supported",
"=",
"set",
"(",
"[",
"\"cnvkit\"",
"]",
")",
"cns_file",
"=",
"None",
"for",
"sv",
"in",
"data",
".",
"get",
"(",
"\"sv\"",
",",
"[",
"]",
")",
":",
"if",
"sv",
... | Retrieve BEDPEs deletion and duplications from CNV callers.
Currently integrates with CNVkit. | [
"Retrieve",
"BEDPEs",
"deletion",
"and",
"duplications",
"from",
"CNV",
"callers",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L202-L229 | train | 218,395 |
bcbio/bcbio-nextgen | bcbio/setpath.py | _prepend | def _prepend(original, to_prepend):
"""Prepend paths in a string representing a list of paths to another.
original and to_prepend are expected to be strings representing
os.pathsep-separated lists of filepaths.
If to_prepend is None, original is returned.
The list of paths represented in the returned value consists of the first of
occurrences of each non-empty path in the list obtained by prepending the
paths in to_prepend to the paths in original.
examples:
# Unix
_prepend('/b:/d:/a:/d', '/a:/b:/c:/a') -> '/a:/b:/c:/d'
_prepend('/a:/b:/a', '/a:/c:/c') -> '/a:/c:/b'
_prepend('/c', '/a::/b:/a') -> '/a:/b:/c'
_prepend('/a:/b:/a', None) -> '/a:/b:/a'
_prepend('/a:/b:/a', '') -> '/a:/b'
"""
if to_prepend is None:
return original
sep = os.pathsep
def split_path_value(path_value):
return [] if path_value == '' else path_value.split(sep)
seen = set()
components = []
for path in split_path_value(to_prepend) + split_path_value(original):
if path not in seen and path != '':
components.append(path)
seen.add(path)
return sep.join(components) | python | def _prepend(original, to_prepend):
"""Prepend paths in a string representing a list of paths to another.
original and to_prepend are expected to be strings representing
os.pathsep-separated lists of filepaths.
If to_prepend is None, original is returned.
The list of paths represented in the returned value consists of the first of
occurrences of each non-empty path in the list obtained by prepending the
paths in to_prepend to the paths in original.
examples:
# Unix
_prepend('/b:/d:/a:/d', '/a:/b:/c:/a') -> '/a:/b:/c:/d'
_prepend('/a:/b:/a', '/a:/c:/c') -> '/a:/c:/b'
_prepend('/c', '/a::/b:/a') -> '/a:/b:/c'
_prepend('/a:/b:/a', None) -> '/a:/b:/a'
_prepend('/a:/b:/a', '') -> '/a:/b'
"""
if to_prepend is None:
return original
sep = os.pathsep
def split_path_value(path_value):
return [] if path_value == '' else path_value.split(sep)
seen = set()
components = []
for path in split_path_value(to_prepend) + split_path_value(original):
if path not in seen and path != '':
components.append(path)
seen.add(path)
return sep.join(components) | [
"def",
"_prepend",
"(",
"original",
",",
"to_prepend",
")",
":",
"if",
"to_prepend",
"is",
"None",
":",
"return",
"original",
"sep",
"=",
"os",
".",
"pathsep",
"def",
"split_path_value",
"(",
"path_value",
")",
":",
"return",
"[",
"]",
"if",
"path_value",
... | Prepend paths in a string representing a list of paths to another.
original and to_prepend are expected to be strings representing
os.pathsep-separated lists of filepaths.
If to_prepend is None, original is returned.
The list of paths represented in the returned value consists of the first of
occurrences of each non-empty path in the list obtained by prepending the
paths in to_prepend to the paths in original.
examples:
# Unix
_prepend('/b:/d:/a:/d', '/a:/b:/c:/a') -> '/a:/b:/c:/d'
_prepend('/a:/b:/a', '/a:/c:/c') -> '/a:/c:/b'
_prepend('/c', '/a::/b:/a') -> '/a:/b:/c'
_prepend('/a:/b:/a', None) -> '/a:/b:/a'
_prepend('/a:/b:/a', '') -> '/a:/b' | [
"Prepend",
"paths",
"in",
"a",
"string",
"representing",
"a",
"list",
"of",
"paths",
"to",
"another",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/setpath.py#L10-L48 | train | 218,396 |
bcbio/bcbio-nextgen | bcbio/setpath.py | remove_bcbiopath | def remove_bcbiopath():
"""Remove bcbio internal path from first element in PATH.
Useful when we need to access remote programs, like Java 7 for older
installations.
"""
to_remove = os.environ.get("BCBIOPATH", utils.get_bcbio_bin()) + ":"
if os.environ["PATH"].startswith(to_remove):
os.environ["PATH"] = os.environ["PATH"][len(to_remove):] | python | def remove_bcbiopath():
"""Remove bcbio internal path from first element in PATH.
Useful when we need to access remote programs, like Java 7 for older
installations.
"""
to_remove = os.environ.get("BCBIOPATH", utils.get_bcbio_bin()) + ":"
if os.environ["PATH"].startswith(to_remove):
os.environ["PATH"] = os.environ["PATH"][len(to_remove):] | [
"def",
"remove_bcbiopath",
"(",
")",
":",
"to_remove",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"BCBIOPATH\"",
",",
"utils",
".",
"get_bcbio_bin",
"(",
")",
")",
"+",
"\":\"",
"if",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
".",
"startswith",
"(... | Remove bcbio internal path from first element in PATH.
Useful when we need to access remote programs, like Java 7 for older
installations. | [
"Remove",
"bcbio",
"internal",
"path",
"from",
"first",
"element",
"in",
"PATH",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/setpath.py#L64-L72 | train | 218,397 |
bcbio/bcbio-nextgen | bcbio/structural/regions.py | calculate_sv_bins | def calculate_sv_bins(*items):
"""Determine bin sizes and regions to use for samples.
Unified approach to prepare regional bins for coverage calculations across
multiple CNV callers. Splits into target and antitarget regions allowing
callers to take advantage of both. Provides consistent target/anti-target
bin sizes across batches.
Uses callable_regions as the access BED file and mosdepth regions in
variant_regions to estimate depth for bin sizes.
"""
calcfns = {"cnvkit": _calculate_sv_bins_cnvkit, "gatk-cnv": _calculate_sv_bins_gatk}
from bcbio.structural import cnvkit
items = [utils.to_single_data(x) for x in cwlutils.handle_combined_input(items)]
if all(not cnvkit.use_general_sv_bins(x) for x in items):
return [[d] for d in items]
out = []
for i, cnv_group in enumerate(_group_by_cnv_method(multi.group_by_batch(items, False))):
size_calc_fn = MemoizedSizes(cnv_group.region_file, cnv_group.items).get_target_antitarget_bin_sizes
for data in cnv_group.items:
if cnvkit.use_general_sv_bins(data):
target_bed, anti_bed, gcannotated_tsv = calcfns[cnvkit.bin_approach(data)](data, cnv_group,
size_calc_fn)
if not data.get("regions"):
data["regions"] = {}
data["regions"]["bins"] = {"target": target_bed, "antitarget": anti_bed, "group": str(i),
"gcannotated": gcannotated_tsv}
out.append([data])
if not len(out) == len(items):
raise AssertionError("Inconsistent samples in and out of SV bin calculation:\nout: %s\nin : %s" %
(sorted([dd.get_sample_name(utils.to_single_data(x)) for x in out]),
sorted([dd.get_sample_name(x) for x in items])))
return out | python | def calculate_sv_bins(*items):
"""Determine bin sizes and regions to use for samples.
Unified approach to prepare regional bins for coverage calculations across
multiple CNV callers. Splits into target and antitarget regions allowing
callers to take advantage of both. Provides consistent target/anti-target
bin sizes across batches.
Uses callable_regions as the access BED file and mosdepth regions in
variant_regions to estimate depth for bin sizes.
"""
calcfns = {"cnvkit": _calculate_sv_bins_cnvkit, "gatk-cnv": _calculate_sv_bins_gatk}
from bcbio.structural import cnvkit
items = [utils.to_single_data(x) for x in cwlutils.handle_combined_input(items)]
if all(not cnvkit.use_general_sv_bins(x) for x in items):
return [[d] for d in items]
out = []
for i, cnv_group in enumerate(_group_by_cnv_method(multi.group_by_batch(items, False))):
size_calc_fn = MemoizedSizes(cnv_group.region_file, cnv_group.items).get_target_antitarget_bin_sizes
for data in cnv_group.items:
if cnvkit.use_general_sv_bins(data):
target_bed, anti_bed, gcannotated_tsv = calcfns[cnvkit.bin_approach(data)](data, cnv_group,
size_calc_fn)
if not data.get("regions"):
data["regions"] = {}
data["regions"]["bins"] = {"target": target_bed, "antitarget": anti_bed, "group": str(i),
"gcannotated": gcannotated_tsv}
out.append([data])
if not len(out) == len(items):
raise AssertionError("Inconsistent samples in and out of SV bin calculation:\nout: %s\nin : %s" %
(sorted([dd.get_sample_name(utils.to_single_data(x)) for x in out]),
sorted([dd.get_sample_name(x) for x in items])))
return out | [
"def",
"calculate_sv_bins",
"(",
"*",
"items",
")",
":",
"calcfns",
"=",
"{",
"\"cnvkit\"",
":",
"_calculate_sv_bins_cnvkit",
",",
"\"gatk-cnv\"",
":",
"_calculate_sv_bins_gatk",
"}",
"from",
"bcbio",
".",
"structural",
"import",
"cnvkit",
"items",
"=",
"[",
"ut... | Determine bin sizes and regions to use for samples.
Unified approach to prepare regional bins for coverage calculations across
multiple CNV callers. Splits into target and antitarget regions allowing
callers to take advantage of both. Provides consistent target/anti-target
bin sizes across batches.
Uses callable_regions as the access BED file and mosdepth regions in
variant_regions to estimate depth for bin sizes. | [
"Determine",
"bin",
"sizes",
"and",
"regions",
"to",
"use",
"for",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L27-L59 | train | 218,398 |
bcbio/bcbio-nextgen | bcbio/structural/regions.py | _calculate_sv_bins_gatk | def _calculate_sv_bins_gatk(data, cnv_group, size_calc_fn):
"""Calculate structural variant bins using GATK4 CNV callers region or even intervals approach.
"""
if dd.get_background_cnv_reference(data, "gatk-cnv"):
target_bed = gatkcnv.pon_to_bed(dd.get_background_cnv_reference(data, "gatk-cnv"), cnv_group.work_dir, data)
else:
target_bed = gatkcnv.prepare_intervals(data, cnv_group.region_file, cnv_group.work_dir)
gc_annotated_tsv = gatkcnv.annotate_intervals(target_bed, data)
return target_bed, None, gc_annotated_tsv | python | def _calculate_sv_bins_gatk(data, cnv_group, size_calc_fn):
"""Calculate structural variant bins using GATK4 CNV callers region or even intervals approach.
"""
if dd.get_background_cnv_reference(data, "gatk-cnv"):
target_bed = gatkcnv.pon_to_bed(dd.get_background_cnv_reference(data, "gatk-cnv"), cnv_group.work_dir, data)
else:
target_bed = gatkcnv.prepare_intervals(data, cnv_group.region_file, cnv_group.work_dir)
gc_annotated_tsv = gatkcnv.annotate_intervals(target_bed, data)
return target_bed, None, gc_annotated_tsv | [
"def",
"_calculate_sv_bins_gatk",
"(",
"data",
",",
"cnv_group",
",",
"size_calc_fn",
")",
":",
"if",
"dd",
".",
"get_background_cnv_reference",
"(",
"data",
",",
"\"gatk-cnv\"",
")",
":",
"target_bed",
"=",
"gatkcnv",
".",
"pon_to_bed",
"(",
"dd",
".",
"get_b... | Calculate structural variant bins using GATK4 CNV callers region or even intervals approach. | [
"Calculate",
"structural",
"variant",
"bins",
"using",
"GATK4",
"CNV",
"callers",
"region",
"or",
"even",
"intervals",
"approach",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L61-L69 | train | 218,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.