id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
224,300 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | call_copy_numbers | def call_copy_numbers(seg_file, work_dir, data):
"""Call copy numbers from a normalized and segmented input file.
"""
out_file = os.path.join(work_dir, "%s-call.seg" % dd.get_sample_name(data))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
params = ["-T", "CallCopyRatioSegments",
"-I", seg_file, "-O", tx_out_file]
_run_with_memory_scaling(params, tx_out_file, data)
return out_file | python | def call_copy_numbers(seg_file, work_dir, data):
"""Call copy numbers from a normalized and segmented input file.
"""
out_file = os.path.join(work_dir, "%s-call.seg" % dd.get_sample_name(data))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
params = ["-T", "CallCopyRatioSegments",
"-I", seg_file, "-O", tx_out_file]
_run_with_memory_scaling(params, tx_out_file, data)
return out_file | [
"def",
"call_copy_numbers",
"(",
"seg_file",
",",
"work_dir",
",",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-call.seg\"",
"%",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
")",
"if",
"not",
"utils",... | Call copy numbers from a normalized and segmented input file. | [
"Call",
"copy",
"numbers",
"from",
"a",
"normalized",
"and",
"segmented",
"input",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L56-L65 |
224,301 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | plot_model_segments | def plot_model_segments(seg_files, work_dir, data):
"""Diagnostic plots of segmentation and inputs.
"""
from bcbio.heterogeneity import chromhacks
out_file = os.path.join(work_dir, "%s.modeled.png" % dd.get_sample_name(data))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
dict_file = utils.splitext_plus(dd.get_ref_file(data))[0] + ".dict"
plot_dict = os.path.join(os.path.dirname(tx_out_file), os.path.basename(dict_file))
with open(dict_file) as in_handle:
with open(plot_dict, "w") as out_handle:
for line in in_handle:
if line.startswith("@SQ"):
cur_chrom = [x.split(":", 1)[1].strip()
for x in line.split("\t") if x.startswith("SN:")][0]
if chromhacks.is_autosomal_or_sex(cur_chrom):
out_handle.write(line)
else:
out_handle.write(line)
params = ["-T", "PlotModeledSegments",
"--denoised-copy-ratios", tz.get_in(["depth", "bins", "normalized"], data),
"--segments", seg_files["final_seg"],
"--allelic-counts", seg_files["tumor_hets"],
"--sequence-dictionary", plot_dict,
"--minimum-contig-length", "10",
"--output-prefix", dd.get_sample_name(data),
"-O", os.path.dirname(tx_out_file)]
_run_with_memory_scaling(params, tx_out_file, data)
return {"seg": out_file} | python | def plot_model_segments(seg_files, work_dir, data):
"""Diagnostic plots of segmentation and inputs.
"""
from bcbio.heterogeneity import chromhacks
out_file = os.path.join(work_dir, "%s.modeled.png" % dd.get_sample_name(data))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
dict_file = utils.splitext_plus(dd.get_ref_file(data))[0] + ".dict"
plot_dict = os.path.join(os.path.dirname(tx_out_file), os.path.basename(dict_file))
with open(dict_file) as in_handle:
with open(plot_dict, "w") as out_handle:
for line in in_handle:
if line.startswith("@SQ"):
cur_chrom = [x.split(":", 1)[1].strip()
for x in line.split("\t") if x.startswith("SN:")][0]
if chromhacks.is_autosomal_or_sex(cur_chrom):
out_handle.write(line)
else:
out_handle.write(line)
params = ["-T", "PlotModeledSegments",
"--denoised-copy-ratios", tz.get_in(["depth", "bins", "normalized"], data),
"--segments", seg_files["final_seg"],
"--allelic-counts", seg_files["tumor_hets"],
"--sequence-dictionary", plot_dict,
"--minimum-contig-length", "10",
"--output-prefix", dd.get_sample_name(data),
"-O", os.path.dirname(tx_out_file)]
_run_with_memory_scaling(params, tx_out_file, data)
return {"seg": out_file} | [
"def",
"plot_model_segments",
"(",
"seg_files",
",",
"work_dir",
",",
"data",
")",
":",
"from",
"bcbio",
".",
"heterogeneity",
"import",
"chromhacks",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s.modeled.png\"",
"%",
"dd",
"."... | Diagnostic plots of segmentation and inputs. | [
"Diagnostic",
"plots",
"of",
"segmentation",
"and",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L67-L95 |
224,302 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | model_segments | def model_segments(copy_file, work_dir, paired):
"""Perform segmentation on input copy number log2 ratio file.
"""
out_file = os.path.join(work_dir, "%s.cr.seg" % dd.get_sample_name(paired.tumor_data))
tumor_counts, normal_counts = heterogzygote_counts(paired)
if not utils.file_exists(out_file):
with file_transaction(paired.tumor_data, out_file) as tx_out_file:
params = ["-T", "ModelSegments",
"--denoised-copy-ratios", copy_file,
"--allelic-counts", tumor_counts,
"--output-prefix", dd.get_sample_name(paired.tumor_data),
"-O", os.path.dirname(tx_out_file)]
if normal_counts:
params += ["--normal-allelic-counts", normal_counts]
_run_with_memory_scaling(params, tx_out_file, paired.tumor_data)
for tx_fname in glob.glob(os.path.join(os.path.dirname(tx_out_file),
"%s*" % dd.get_sample_name(paired.tumor_data))):
shutil.copy(tx_fname, os.path.join(work_dir, os.path.basename(tx_fname)))
return {"seg": out_file, "tumor_hets": out_file.replace(".cr.seg", ".hets.tsv"),
"final_seg": out_file.replace(".cr.seg", ".modelFinal.seg")} | python | def model_segments(copy_file, work_dir, paired):
"""Perform segmentation on input copy number log2 ratio file.
"""
out_file = os.path.join(work_dir, "%s.cr.seg" % dd.get_sample_name(paired.tumor_data))
tumor_counts, normal_counts = heterogzygote_counts(paired)
if not utils.file_exists(out_file):
with file_transaction(paired.tumor_data, out_file) as tx_out_file:
params = ["-T", "ModelSegments",
"--denoised-copy-ratios", copy_file,
"--allelic-counts", tumor_counts,
"--output-prefix", dd.get_sample_name(paired.tumor_data),
"-O", os.path.dirname(tx_out_file)]
if normal_counts:
params += ["--normal-allelic-counts", normal_counts]
_run_with_memory_scaling(params, tx_out_file, paired.tumor_data)
for tx_fname in glob.glob(os.path.join(os.path.dirname(tx_out_file),
"%s*" % dd.get_sample_name(paired.tumor_data))):
shutil.copy(tx_fname, os.path.join(work_dir, os.path.basename(tx_fname)))
return {"seg": out_file, "tumor_hets": out_file.replace(".cr.seg", ".hets.tsv"),
"final_seg": out_file.replace(".cr.seg", ".modelFinal.seg")} | [
"def",
"model_segments",
"(",
"copy_file",
",",
"work_dir",
",",
"paired",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s.cr.seg\"",
"%",
"dd",
".",
"get_sample_name",
"(",
"paired",
".",
"tumor_data",
")",
")",
"t... | Perform segmentation on input copy number log2 ratio file. | [
"Perform",
"segmentation",
"on",
"input",
"copy",
"number",
"log2",
"ratio",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L97-L116 |
224,303 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | create_panel_of_normals | def create_panel_of_normals(items, group_id, work_dir):
"""Create a panel of normals from one or more background read counts.
"""
out_file = os.path.join(work_dir, "%s-%s-pon.hdf5" % (dd.get_sample_name(items[0]), group_id))
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
params = ["-T", "CreateReadCountPanelOfNormals",
"-O", tx_out_file,
"--annotated-intervals", tz.get_in(["regions", "bins", "gcannotated"], items[0])]
for data in items:
params += ["-I", tz.get_in(["depth", "bins", "target"], data)]
_run_with_memory_scaling(params, tx_out_file, items[0], ld_preload=True)
return out_file | python | def create_panel_of_normals(items, group_id, work_dir):
"""Create a panel of normals from one or more background read counts.
"""
out_file = os.path.join(work_dir, "%s-%s-pon.hdf5" % (dd.get_sample_name(items[0]), group_id))
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
params = ["-T", "CreateReadCountPanelOfNormals",
"-O", tx_out_file,
"--annotated-intervals", tz.get_in(["regions", "bins", "gcannotated"], items[0])]
for data in items:
params += ["-I", tz.get_in(["depth", "bins", "target"], data)]
_run_with_memory_scaling(params, tx_out_file, items[0], ld_preload=True)
return out_file | [
"def",
"create_panel_of_normals",
"(",
"items",
",",
"group_id",
",",
"work_dir",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-%s-pon.hdf5\"",
"%",
"(",
"dd",
".",
"get_sample_name",
"(",
"items",
"[",
"0",
"]",
... | Create a panel of normals from one or more background read counts. | [
"Create",
"a",
"panel",
"of",
"normals",
"from",
"one",
"or",
"more",
"background",
"read",
"counts",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L136-L148 |
224,304 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | pon_to_bed | def pon_to_bed(pon_file, out_dir, data):
"""Extract BED intervals from a GATK4 hdf5 panel of normal file.
"""
out_file = os.path.join(out_dir, "%s-intervals.bed" % (utils.splitext_plus(os.path.basename(pon_file))[0]))
if not utils.file_uptodate(out_file, pon_file):
import h5py
with file_transaction(data, out_file) as tx_out_file:
with h5py.File(pon_file, "r") as f:
with open(tx_out_file, "w") as out_handle:
intervals = f["original_data"]["intervals"]
for i in range(len(intervals["transposed_index_start_end"][0])):
chrom = intervals["indexed_contig_names"][intervals["transposed_index_start_end"][0][i]]
start = int(intervals["transposed_index_start_end"][1][i]) - 1
end = int(intervals["transposed_index_start_end"][2][i])
out_handle.write("%s\t%s\t%s\n" % (chrom, start, end))
return out_file | python | def pon_to_bed(pon_file, out_dir, data):
"""Extract BED intervals from a GATK4 hdf5 panel of normal file.
"""
out_file = os.path.join(out_dir, "%s-intervals.bed" % (utils.splitext_plus(os.path.basename(pon_file))[0]))
if not utils.file_uptodate(out_file, pon_file):
import h5py
with file_transaction(data, out_file) as tx_out_file:
with h5py.File(pon_file, "r") as f:
with open(tx_out_file, "w") as out_handle:
intervals = f["original_data"]["intervals"]
for i in range(len(intervals["transposed_index_start_end"][0])):
chrom = intervals["indexed_contig_names"][intervals["transposed_index_start_end"][0][i]]
start = int(intervals["transposed_index_start_end"][1][i]) - 1
end = int(intervals["transposed_index_start_end"][2][i])
out_handle.write("%s\t%s\t%s\n" % (chrom, start, end))
return out_file | [
"def",
"pon_to_bed",
"(",
"pon_file",
",",
"out_dir",
",",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"\"%s-intervals.bed\"",
"%",
"(",
"utils",
".",
"splitext_plus",
"(",
"os",
".",
"path",
".",
"basename",
... | Extract BED intervals from a GATK4 hdf5 panel of normal file. | [
"Extract",
"BED",
"intervals",
"from",
"a",
"GATK4",
"hdf5",
"panel",
"of",
"normal",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L150-L165 |
224,305 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | prepare_intervals | def prepare_intervals(data, region_file, work_dir):
"""Prepare interval regions for targeted and gene based regions.
"""
target_file = os.path.join(work_dir, "%s-target.interval_list" % dd.get_sample_name(data))
if not utils.file_uptodate(target_file, region_file):
with file_transaction(data, target_file) as tx_out_file:
params = ["-T", "PreprocessIntervals", "-R", dd.get_ref_file(data),
"--interval-merging-rule", "OVERLAPPING_ONLY",
"-O", tx_out_file]
if dd.get_coverage_interval(data) == "genome":
params += ["--bin-length", "1000", "--padding", "0"]
else:
params += ["-L", region_file, "--bin-length", "0", "--padding", "250"]
_run_with_memory_scaling(params, tx_out_file, data)
return target_file | python | def prepare_intervals(data, region_file, work_dir):
"""Prepare interval regions for targeted and gene based regions.
"""
target_file = os.path.join(work_dir, "%s-target.interval_list" % dd.get_sample_name(data))
if not utils.file_uptodate(target_file, region_file):
with file_transaction(data, target_file) as tx_out_file:
params = ["-T", "PreprocessIntervals", "-R", dd.get_ref_file(data),
"--interval-merging-rule", "OVERLAPPING_ONLY",
"-O", tx_out_file]
if dd.get_coverage_interval(data) == "genome":
params += ["--bin-length", "1000", "--padding", "0"]
else:
params += ["-L", region_file, "--bin-length", "0", "--padding", "250"]
_run_with_memory_scaling(params, tx_out_file, data)
return target_file | [
"def",
"prepare_intervals",
"(",
"data",
",",
"region_file",
",",
"work_dir",
")",
":",
"target_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-target.interval_list\"",
"%",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
")",
"if",
... | Prepare interval regions for targeted and gene based regions. | [
"Prepare",
"interval",
"regions",
"for",
"targeted",
"and",
"gene",
"based",
"regions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L167-L181 |
224,306 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | annotate_intervals | def annotate_intervals(target_file, data):
"""Provide GC annotated intervals for error correction during panels and denoising.
TODO: include mappability and segmentation duplication inputs
"""
out_file = "%s-gcannotated.tsv" % utils.splitext_plus(target_file)[0]
if not utils.file_uptodate(out_file, target_file):
with file_transaction(data, out_file) as tx_out_file:
params = ["-T", "AnnotateIntervals", "-R", dd.get_ref_file(data),
"-L", target_file,
"--interval-merging-rule", "OVERLAPPING_ONLY",
"-O", tx_out_file]
_run_with_memory_scaling(params, tx_out_file, data)
return out_file | python | def annotate_intervals(target_file, data):
"""Provide GC annotated intervals for error correction during panels and denoising.
TODO: include mappability and segmentation duplication inputs
"""
out_file = "%s-gcannotated.tsv" % utils.splitext_plus(target_file)[0]
if not utils.file_uptodate(out_file, target_file):
with file_transaction(data, out_file) as tx_out_file:
params = ["-T", "AnnotateIntervals", "-R", dd.get_ref_file(data),
"-L", target_file,
"--interval-merging-rule", "OVERLAPPING_ONLY",
"-O", tx_out_file]
_run_with_memory_scaling(params, tx_out_file, data)
return out_file | [
"def",
"annotate_intervals",
"(",
"target_file",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-gcannotated.tsv\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"target_file",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"... | Provide GC annotated intervals for error correction during panels and denoising.
TODO: include mappability and segmentation duplication inputs | [
"Provide",
"GC",
"annotated",
"intervals",
"for",
"error",
"correction",
"during",
"panels",
"and",
"denoising",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L183-L196 |
224,307 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | collect_read_counts | def collect_read_counts(data, work_dir):
"""Count reads in defined bins using CollectReadCounts.
"""
out_file = os.path.join(work_dir, "%s-target-coverage.hdf5" % dd.get_sample_name(data))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
params = ["-T", "CollectReadCounts", "-I", dd.get_align_bam(data),
"-L", tz.get_in(["regions", "bins", "target"], data),
"--interval-merging-rule", "OVERLAPPING_ONLY",
"-O", tx_out_file, "--format", "HDF5"]
_run_with_memory_scaling(params, tx_out_file, data)
return out_file | python | def collect_read_counts(data, work_dir):
"""Count reads in defined bins using CollectReadCounts.
"""
out_file = os.path.join(work_dir, "%s-target-coverage.hdf5" % dd.get_sample_name(data))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
params = ["-T", "CollectReadCounts", "-I", dd.get_align_bam(data),
"-L", tz.get_in(["regions", "bins", "target"], data),
"--interval-merging-rule", "OVERLAPPING_ONLY",
"-O", tx_out_file, "--format", "HDF5"]
_run_with_memory_scaling(params, tx_out_file, data)
return out_file | [
"def",
"collect_read_counts",
"(",
"data",
",",
"work_dir",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-target-coverage.hdf5\"",
"%",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
")",
"if",
"not",
"utils",
".",... | Count reads in defined bins using CollectReadCounts. | [
"Count",
"reads",
"in",
"defined",
"bins",
"using",
"CollectReadCounts",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L198-L209 |
224,308 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | _filter_by_normal | def _filter_by_normal(tumor_counts, normal_counts, data):
"""Filter count files based on normal frequency and median depth, avoiding high depth regions.
For frequency, restricts normal positions to those between 0.4 and 0.65
For depth, matches approach used in AMBER to try and avoid problematic genomic regions
with high count in the normal:
https://github.com/hartwigmedical/hmftools/tree/master/amber#usage
"""
from bcbio.heterogeneity import bubbletree
fparams = bubbletree.NORMAL_FILTER_PARAMS
tumor_out = "%s-normfilter%s" % utils.splitext_plus(tumor_counts)
normal_out = "%s-normfilter%s" % utils.splitext_plus(normal_counts)
if not utils.file_uptodate(tumor_out, tumor_counts):
with file_transaction(data, tumor_out, normal_out) as (tx_tumor_out, tx_normal_out):
median_depth = _get_normal_median_depth(normal_counts)
min_normal_depth = median_depth * fparams["min_depth_percent"]
max_normal_depth = median_depth * fparams["max_depth_percent"]
with open(tumor_counts) as tumor_handle:
with open(normal_counts) as normal_handle:
with open(tx_tumor_out, "w") as tumor_out_handle:
with open(tx_normal_out, "w") as normal_out_handle:
header = None
for t, n in zip(tumor_handle, normal_handle):
if header is None:
if not n.startswith("@"):
header = n.strip().split()
tumor_out_handle.write(t)
normal_out_handle.write(n)
elif (_normal_passes_depth(header, n, min_normal_depth, max_normal_depth) and
_normal_passes_freq(header, n, fparams)):
tumor_out_handle.write(t)
normal_out_handle.write(n)
return tumor_out, normal_out | python | def _filter_by_normal(tumor_counts, normal_counts, data):
"""Filter count files based on normal frequency and median depth, avoiding high depth regions.
For frequency, restricts normal positions to those between 0.4 and 0.65
For depth, matches approach used in AMBER to try and avoid problematic genomic regions
with high count in the normal:
https://github.com/hartwigmedical/hmftools/tree/master/amber#usage
"""
from bcbio.heterogeneity import bubbletree
fparams = bubbletree.NORMAL_FILTER_PARAMS
tumor_out = "%s-normfilter%s" % utils.splitext_plus(tumor_counts)
normal_out = "%s-normfilter%s" % utils.splitext_plus(normal_counts)
if not utils.file_uptodate(tumor_out, tumor_counts):
with file_transaction(data, tumor_out, normal_out) as (tx_tumor_out, tx_normal_out):
median_depth = _get_normal_median_depth(normal_counts)
min_normal_depth = median_depth * fparams["min_depth_percent"]
max_normal_depth = median_depth * fparams["max_depth_percent"]
with open(tumor_counts) as tumor_handle:
with open(normal_counts) as normal_handle:
with open(tx_tumor_out, "w") as tumor_out_handle:
with open(tx_normal_out, "w") as normal_out_handle:
header = None
for t, n in zip(tumor_handle, normal_handle):
if header is None:
if not n.startswith("@"):
header = n.strip().split()
tumor_out_handle.write(t)
normal_out_handle.write(n)
elif (_normal_passes_depth(header, n, min_normal_depth, max_normal_depth) and
_normal_passes_freq(header, n, fparams)):
tumor_out_handle.write(t)
normal_out_handle.write(n)
return tumor_out, normal_out | [
"def",
"_filter_by_normal",
"(",
"tumor_counts",
",",
"normal_counts",
",",
"data",
")",
":",
"from",
"bcbio",
".",
"heterogeneity",
"import",
"bubbletree",
"fparams",
"=",
"bubbletree",
".",
"NORMAL_FILTER_PARAMS",
"tumor_out",
"=",
"\"%s-normfilter%s\"",
"%",
"uti... | Filter count files based on normal frequency and median depth, avoiding high depth regions.
For frequency, restricts normal positions to those between 0.4 and 0.65
For depth, matches approach used in AMBER to try and avoid problematic genomic regions
with high count in the normal:
https://github.com/hartwigmedical/hmftools/tree/master/amber#usage | [
"Filter",
"count",
"files",
"based",
"on",
"normal",
"frequency",
"and",
"median",
"depth",
"avoiding",
"high",
"depth",
"regions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L226-L259 |
224,309 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | _run_collect_allelic_counts | def _run_collect_allelic_counts(pos_file, pos_name, work_dir, data):
"""Counts by alleles for a specific sample and set of positions.
"""
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural", "counts"))
out_file = os.path.join(out_dir, "%s-%s-counts.tsv" % (dd.get_sample_name(data), pos_name))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
params = ["-T", "CollectAllelicCounts", "-L", pos_file, "-I", dd.get_align_bam(data),
"-R", dd.get_ref_file(data), "-O", tx_out_file]
_run_with_memory_scaling(params, tx_out_file, data)
return out_file | python | def _run_collect_allelic_counts(pos_file, pos_name, work_dir, data):
"""Counts by alleles for a specific sample and set of positions.
"""
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural", "counts"))
out_file = os.path.join(out_dir, "%s-%s-counts.tsv" % (dd.get_sample_name(data), pos_name))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
params = ["-T", "CollectAllelicCounts", "-L", pos_file, "-I", dd.get_align_bam(data),
"-R", dd.get_ref_file(data), "-O", tx_out_file]
_run_with_memory_scaling(params, tx_out_file, data)
return out_file | [
"def",
"_run_collect_allelic_counts",
"(",
"pos_file",
",",
"pos_name",
",",
"work_dir",
",",
"data",
")",
":",
"out_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",
",",
"\"s... | Counts by alleles for a specific sample and set of positions. | [
"Counts",
"by",
"alleles",
"for",
"a",
"specific",
"sample",
"and",
"set",
"of",
"positions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L287-L297 |
224,310 | bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | _seg_to_vcf | def _seg_to_vcf(vals):
"""Convert GATK CNV calls seg output to a VCF line.
"""
call_to_cn = {"+": 3, "-": 1}
call_to_type = {"+": "DUP", "-": "DEL"}
if vals["CALL"] not in ["0"]:
info = ["FOLD_CHANGE_LOG=%s" % vals["MEAN_LOG2_COPY_RATIO"],
"PROBES=%s" % vals["NUM_POINTS_COPY_RATIO"],
"SVTYPE=%s" % call_to_type[vals["CALL"]],
"SVLEN=%s" % (int(vals["END"]) - int(vals["START"])),
"END=%s" % vals["END"],
"CN=%s" % call_to_cn[vals["CALL"]]]
return [vals["CONTIG"], vals["START"], ".", "N", "<%s>" % call_to_type[vals["CALL"]], ".",
".", ";".join(info), "GT", "0/1"] | python | def _seg_to_vcf(vals):
"""Convert GATK CNV calls seg output to a VCF line.
"""
call_to_cn = {"+": 3, "-": 1}
call_to_type = {"+": "DUP", "-": "DEL"}
if vals["CALL"] not in ["0"]:
info = ["FOLD_CHANGE_LOG=%s" % vals["MEAN_LOG2_COPY_RATIO"],
"PROBES=%s" % vals["NUM_POINTS_COPY_RATIO"],
"SVTYPE=%s" % call_to_type[vals["CALL"]],
"SVLEN=%s" % (int(vals["END"]) - int(vals["START"])),
"END=%s" % vals["END"],
"CN=%s" % call_to_cn[vals["CALL"]]]
return [vals["CONTIG"], vals["START"], ".", "N", "<%s>" % call_to_type[vals["CALL"]], ".",
".", ";".join(info), "GT", "0/1"] | [
"def",
"_seg_to_vcf",
"(",
"vals",
")",
":",
"call_to_cn",
"=",
"{",
"\"+\"",
":",
"3",
",",
"\"-\"",
":",
"1",
"}",
"call_to_type",
"=",
"{",
"\"+\"",
":",
"\"DUP\"",
",",
"\"-\"",
":",
"\"DEL\"",
"}",
"if",
"vals",
"[",
"\"CALL\"",
"]",
"not",
"i... | Convert GATK CNV calls seg output to a VCF line. | [
"Convert",
"GATK",
"CNV",
"calls",
"seg",
"output",
"to",
"a",
"VCF",
"line",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L313-L326 |
224,311 | bcbio/bcbio-nextgen | bcbio/rnaseq/bcbiornaseq.py | make_bcbiornaseq_object | def make_bcbiornaseq_object(data):
"""
load the initial bcb.rda object using bcbioRNASeq
"""
if "bcbiornaseq" not in dd.get_tools_on(data):
return data
upload_dir = tz.get_in(("upload", "dir"), data)
report_dir = os.path.join(upload_dir, "bcbioRNASeq")
safe_makedir(report_dir)
organism = dd.get_bcbiornaseq(data).get("organism", None)
groups = dd.get_bcbiornaseq(data).get("interesting_groups", None)
loadstring = create_load_string(upload_dir, groups, organism)
r_file = os.path.join(report_dir, "load_bcbioRNAseq.R")
with file_transaction(r_file) as tmp_file:
memoize_write_file(loadstring, tmp_file)
rcmd = Rscript_cmd()
with chdir(report_dir):
do.run([rcmd, "--no-environ", r_file], "Loading bcbioRNASeq object.")
make_quality_report(data)
return data | python | def make_bcbiornaseq_object(data):
"""
load the initial bcb.rda object using bcbioRNASeq
"""
if "bcbiornaseq" not in dd.get_tools_on(data):
return data
upload_dir = tz.get_in(("upload", "dir"), data)
report_dir = os.path.join(upload_dir, "bcbioRNASeq")
safe_makedir(report_dir)
organism = dd.get_bcbiornaseq(data).get("organism", None)
groups = dd.get_bcbiornaseq(data).get("interesting_groups", None)
loadstring = create_load_string(upload_dir, groups, organism)
r_file = os.path.join(report_dir, "load_bcbioRNAseq.R")
with file_transaction(r_file) as tmp_file:
memoize_write_file(loadstring, tmp_file)
rcmd = Rscript_cmd()
with chdir(report_dir):
do.run([rcmd, "--no-environ", r_file], "Loading bcbioRNASeq object.")
make_quality_report(data)
return data | [
"def",
"make_bcbiornaseq_object",
"(",
"data",
")",
":",
"if",
"\"bcbiornaseq\"",
"not",
"in",
"dd",
".",
"get_tools_on",
"(",
"data",
")",
":",
"return",
"data",
"upload_dir",
"=",
"tz",
".",
"get_in",
"(",
"(",
"\"upload\"",
",",
"\"dir\"",
")",
",",
"... | load the initial bcb.rda object using bcbioRNASeq | [
"load",
"the",
"initial",
"bcb",
".",
"rda",
"object",
"using",
"bcbioRNASeq"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/bcbiornaseq.py#L12-L31 |
224,312 | bcbio/bcbio-nextgen | bcbio/rnaseq/bcbiornaseq.py | make_quality_report | def make_quality_report(data):
"""
create and render the bcbioRNASeq quality report
"""
if "bcbiornaseq" not in dd.get_tools_on(data):
return data
upload_dir = tz.get_in(("upload", "dir"), data)
report_dir = os.path.join(upload_dir, "bcbioRNASeq")
safe_makedir(report_dir)
quality_rmd = os.path.join(report_dir, "quality_control.Rmd")
quality_html = os.path.join(report_dir, "quality_control.html")
quality_rmd = rmarkdown_draft(quality_rmd, "quality_control", "bcbioRNASeq")
if not file_exists(quality_html):
render_rmarkdown_file(quality_rmd)
return data | python | def make_quality_report(data):
"""
create and render the bcbioRNASeq quality report
"""
if "bcbiornaseq" not in dd.get_tools_on(data):
return data
upload_dir = tz.get_in(("upload", "dir"), data)
report_dir = os.path.join(upload_dir, "bcbioRNASeq")
safe_makedir(report_dir)
quality_rmd = os.path.join(report_dir, "quality_control.Rmd")
quality_html = os.path.join(report_dir, "quality_control.html")
quality_rmd = rmarkdown_draft(quality_rmd, "quality_control", "bcbioRNASeq")
if not file_exists(quality_html):
render_rmarkdown_file(quality_rmd)
return data | [
"def",
"make_quality_report",
"(",
"data",
")",
":",
"if",
"\"bcbiornaseq\"",
"not",
"in",
"dd",
".",
"get_tools_on",
"(",
"data",
")",
":",
"return",
"data",
"upload_dir",
"=",
"tz",
".",
"get_in",
"(",
"(",
"\"upload\"",
",",
"\"dir\"",
")",
",",
"data... | create and render the bcbioRNASeq quality report | [
"create",
"and",
"render",
"the",
"bcbioRNASeq",
"quality",
"report"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/bcbiornaseq.py#L33-L47 |
224,313 | bcbio/bcbio-nextgen | bcbio/rnaseq/bcbiornaseq.py | rmarkdown_draft | def rmarkdown_draft(filename, template, package):
"""
create a draft rmarkdown file from an installed template
"""
if file_exists(filename):
return filename
draft_template = Template(
'rmarkdown::draft("$filename", template="$template", package="$package", edit=FALSE)'
)
draft_string = draft_template.substitute(
filename=filename, template=template, package=package)
report_dir = os.path.dirname(filename)
rcmd = Rscript_cmd()
with chdir(report_dir):
do.run([rcmd, "--no-environ", "-e", draft_string], "Creating bcbioRNASeq quality control template.")
do.run(["sed", "-i", "s/YYYY-MM-DD\///g", filename], "Editing bcbioRNAseq quality control template.")
return filename | python | def rmarkdown_draft(filename, template, package):
"""
create a draft rmarkdown file from an installed template
"""
if file_exists(filename):
return filename
draft_template = Template(
'rmarkdown::draft("$filename", template="$template", package="$package", edit=FALSE)'
)
draft_string = draft_template.substitute(
filename=filename, template=template, package=package)
report_dir = os.path.dirname(filename)
rcmd = Rscript_cmd()
with chdir(report_dir):
do.run([rcmd, "--no-environ", "-e", draft_string], "Creating bcbioRNASeq quality control template.")
do.run(["sed", "-i", "s/YYYY-MM-DD\///g", filename], "Editing bcbioRNAseq quality control template.")
return filename | [
"def",
"rmarkdown_draft",
"(",
"filename",
",",
"template",
",",
"package",
")",
":",
"if",
"file_exists",
"(",
"filename",
")",
":",
"return",
"filename",
"draft_template",
"=",
"Template",
"(",
"'rmarkdown::draft(\"$filename\", template=\"$template\", package=\"$package... | create a draft rmarkdown file from an installed template | [
"create",
"a",
"draft",
"rmarkdown",
"file",
"from",
"an",
"installed",
"template"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/bcbiornaseq.py#L49-L65 |
224,314 | bcbio/bcbio-nextgen | bcbio/rnaseq/bcbiornaseq.py | render_rmarkdown_file | def render_rmarkdown_file(filename):
"""
render a rmarkdown file using the rmarkdown library
"""
render_template = Template(
'rmarkdown::render("$filename")'
)
render_string = render_template.substitute(
filename=filename)
report_dir = os.path.dirname(filename)
rcmd = Rscript_cmd()
with chdir(report_dir):
do.run([rcmd, "--no-environ", "-e", render_string], "Rendering bcbioRNASeq quality control report.")
return filename | python | def render_rmarkdown_file(filename):
"""
render a rmarkdown file using the rmarkdown library
"""
render_template = Template(
'rmarkdown::render("$filename")'
)
render_string = render_template.substitute(
filename=filename)
report_dir = os.path.dirname(filename)
rcmd = Rscript_cmd()
with chdir(report_dir):
do.run([rcmd, "--no-environ", "-e", render_string], "Rendering bcbioRNASeq quality control report.")
return filename | [
"def",
"render_rmarkdown_file",
"(",
"filename",
")",
":",
"render_template",
"=",
"Template",
"(",
"'rmarkdown::render(\"$filename\")'",
")",
"render_string",
"=",
"render_template",
".",
"substitute",
"(",
"filename",
"=",
"filename",
")",
"report_dir",
"=",
"os",
... | render a rmarkdown file using the rmarkdown library | [
"render",
"a",
"rmarkdown",
"file",
"using",
"the",
"rmarkdown",
"library"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/bcbiornaseq.py#L67-L80 |
224,315 | bcbio/bcbio-nextgen | bcbio/rnaseq/bcbiornaseq.py | create_load_string | def create_load_string(upload_dir, groups=None, organism=None):
"""
create the code necessary to load the bcbioRNAseq object
"""
libraryline = 'library(bcbioRNASeq)'
load_template = Template(
('bcb <- bcbioRNASeq(uploadDir="$upload_dir",'
'interestingGroups=$groups,'
'organism="$organism")'))
load_noorganism_template = Template(
('bcb <- bcbioRNASeq(uploadDir="$upload_dir",'
'interestingGroups=$groups,'
'organism=NULL)'))
flatline = 'flat <- flatFiles(bcb)'
saveline = 'saveData(bcb, flat, dir="data")'
if groups:
groups = _list2Rlist(groups)
else:
groups = _quotestring("sampleName")
if organism:
load_bcbio = load_template.substitute(
upload_dir=upload_dir, groups=groups, organism=organism)
else:
load_bcbio = load_noorganism_template.substitute(upload_dir=upload_dir,
groups=groups)
return ";\n".join([libraryline, load_bcbio, flatline, saveline]) | python | def create_load_string(upload_dir, groups=None, organism=None):
"""
create the code necessary to load the bcbioRNAseq object
"""
libraryline = 'library(bcbioRNASeq)'
load_template = Template(
('bcb <- bcbioRNASeq(uploadDir="$upload_dir",'
'interestingGroups=$groups,'
'organism="$organism")'))
load_noorganism_template = Template(
('bcb <- bcbioRNASeq(uploadDir="$upload_dir",'
'interestingGroups=$groups,'
'organism=NULL)'))
flatline = 'flat <- flatFiles(bcb)'
saveline = 'saveData(bcb, flat, dir="data")'
if groups:
groups = _list2Rlist(groups)
else:
groups = _quotestring("sampleName")
if organism:
load_bcbio = load_template.substitute(
upload_dir=upload_dir, groups=groups, organism=organism)
else:
load_bcbio = load_noorganism_template.substitute(upload_dir=upload_dir,
groups=groups)
return ";\n".join([libraryline, load_bcbio, flatline, saveline]) | [
"def",
"create_load_string",
"(",
"upload_dir",
",",
"groups",
"=",
"None",
",",
"organism",
"=",
"None",
")",
":",
"libraryline",
"=",
"'library(bcbioRNASeq)'",
"load_template",
"=",
"Template",
"(",
"(",
"'bcb <- bcbioRNASeq(uploadDir=\"$upload_dir\",'",
"'interesting... | create the code necessary to load the bcbioRNAseq object | [
"create",
"the",
"code",
"necessary",
"to",
"load",
"the",
"bcbioRNAseq",
"object"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/bcbiornaseq.py#L82-L107 |
224,316 | bcbio/bcbio-nextgen | bcbio/rnaseq/bcbiornaseq.py | _list2Rlist | def _list2Rlist(xs):
""" convert a python list to an R list """
if isinstance(xs, six.string_types):
xs = [xs]
rlist = ",".join([_quotestring(x) for x in xs])
return "c(" + rlist + ")" | python | def _list2Rlist(xs):
""" convert a python list to an R list """
if isinstance(xs, six.string_types):
xs = [xs]
rlist = ",".join([_quotestring(x) for x in xs])
return "c(" + rlist + ")" | [
"def",
"_list2Rlist",
"(",
"xs",
")",
":",
"if",
"isinstance",
"(",
"xs",
",",
"six",
".",
"string_types",
")",
":",
"xs",
"=",
"[",
"xs",
"]",
"rlist",
"=",
"\",\"",
".",
"join",
"(",
"[",
"_quotestring",
"(",
"x",
")",
"for",
"x",
"in",
"xs",
... | convert a python list to an R list | [
"convert",
"a",
"python",
"list",
"to",
"an",
"R",
"list"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/bcbiornaseq.py#L124-L129 |
224,317 | bcbio/bcbio-nextgen | bcbio/variation/qsnp.py | _run_qsnp_paired | def _run_qsnp_paired(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Detect somatic mutations with qSNP.
This is used for paired tumor / normal samples.
"""
config = items[0]["config"]
if out_file is None:
out_file = "%s-paired-variants.vcf" % os.path.splitext(align_bams[0])[0]
if not utils.file_exists(out_file):
out_file = out_file.replace(".gz", "")
with file_transaction(config, out_file) as tx_out_file:
with tx_tmpdir(config) as tmpdir:
with utils.chdir(tmpdir):
paired = get_paired_bams(align_bams, items)
qsnp = config_utils.get_program("qsnp", config)
resources = config_utils.get_resources("qsnp", config)
mem = " ".join(resources.get("jvm_opts", ["-Xms750m -Xmx4g"]))
qsnp_log = os.path.join(tmpdir, "qsnp.log")
qsnp_init = os.path.join(tmpdir, "qsnp.ini")
if region:
paired = _create_bam_region(paired, region, tmpdir)
_create_input(paired, tx_out_file, ref_file, assoc_files['dbsnp'], qsnp_init)
cl = ("{qsnp} {mem} -i {qsnp_init} -log {qsnp_log}")
do.run(cl.format(**locals()), "Genotyping paired variants with Qsnp", {})
out_file = _filter_vcf(out_file)
out_file = bgzip_and_index(out_file, config)
return out_file | python | def _run_qsnp_paired(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Detect somatic mutations with qSNP.
This is used for paired tumor / normal samples.
"""
config = items[0]["config"]
if out_file is None:
out_file = "%s-paired-variants.vcf" % os.path.splitext(align_bams[0])[0]
if not utils.file_exists(out_file):
out_file = out_file.replace(".gz", "")
with file_transaction(config, out_file) as tx_out_file:
with tx_tmpdir(config) as tmpdir:
with utils.chdir(tmpdir):
paired = get_paired_bams(align_bams, items)
qsnp = config_utils.get_program("qsnp", config)
resources = config_utils.get_resources("qsnp", config)
mem = " ".join(resources.get("jvm_opts", ["-Xms750m -Xmx4g"]))
qsnp_log = os.path.join(tmpdir, "qsnp.log")
qsnp_init = os.path.join(tmpdir, "qsnp.ini")
if region:
paired = _create_bam_region(paired, region, tmpdir)
_create_input(paired, tx_out_file, ref_file, assoc_files['dbsnp'], qsnp_init)
cl = ("{qsnp} {mem} -i {qsnp_init} -log {qsnp_log}")
do.run(cl.format(**locals()), "Genotyping paired variants with Qsnp", {})
out_file = _filter_vcf(out_file)
out_file = bgzip_and_index(out_file, config)
return out_file | [
"def",
"_run_qsnp_paired",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
"if",
"out_file",
"is",
... | Detect somatic mutations with qSNP.
This is used for paired tumor / normal samples. | [
"Detect",
"somatic",
"mutations",
"with",
"qSNP",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/qsnp.py#L55-L82 |
224,318 | bcbio/bcbio-nextgen | bcbio/variation/qsnp.py | _clean_regions | def _clean_regions(items, region):
"""Intersect region with target file if it exists"""
variant_regions = bedutils.population_variant_regions(items, merged=True)
with utils.tmpfile() as tx_out_file:
target = subset_variant_regions(variant_regions, region, tx_out_file, items)
if target:
if isinstance(target, six.string_types) and os.path.isfile(target):
target = _load_regions(target)
else:
target = [target]
return target | python | def _clean_regions(items, region):
"""Intersect region with target file if it exists"""
variant_regions = bedutils.population_variant_regions(items, merged=True)
with utils.tmpfile() as tx_out_file:
target = subset_variant_regions(variant_regions, region, tx_out_file, items)
if target:
if isinstance(target, six.string_types) and os.path.isfile(target):
target = _load_regions(target)
else:
target = [target]
return target | [
"def",
"_clean_regions",
"(",
"items",
",",
"region",
")",
":",
"variant_regions",
"=",
"bedutils",
".",
"population_variant_regions",
"(",
"items",
",",
"merged",
"=",
"True",
")",
"with",
"utils",
".",
"tmpfile",
"(",
")",
"as",
"tx_out_file",
":",
"target... | Intersect region with target file if it exists | [
"Intersect",
"region",
"with",
"target",
"file",
"if",
"it",
"exists"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/qsnp.py#L84-L94 |
224,319 | bcbio/bcbio-nextgen | bcbio/variation/qsnp.py | _load_regions | def _load_regions(target):
"""Get list of tupples from bed file"""
regions = []
with open(target) as in_handle:
for line in in_handle:
if not line.startswith("#"):
c, s, e = line.strip().split("\t")
regions.append((c, s, e))
return regions | python | def _load_regions(target):
"""Get list of tupples from bed file"""
regions = []
with open(target) as in_handle:
for line in in_handle:
if not line.startswith("#"):
c, s, e = line.strip().split("\t")
regions.append((c, s, e))
return regions | [
"def",
"_load_regions",
"(",
"target",
")",
":",
"regions",
"=",
"[",
"]",
"with",
"open",
"(",
"target",
")",
"as",
"in_handle",
":",
"for",
"line",
"in",
"in_handle",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"c",
",",
... | Get list of tupples from bed file | [
"Get",
"list",
"of",
"tupples",
"from",
"bed",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/qsnp.py#L96-L104 |
224,320 | bcbio/bcbio-nextgen | bcbio/variation/qsnp.py | _slice_bam | def _slice_bam(in_bam, region, tmp_dir, config):
"""Use sambamba to slice a bam region"""
name_file = os.path.splitext(os.path.basename(in_bam))[0]
out_file = os.path.join(tmp_dir, os.path.join(tmp_dir, name_file + _to_str(region) + ".bam"))
sambamba = config_utils.get_program("sambamba", config)
region = _to_sambamba(region)
with file_transaction(out_file) as tx_out_file:
cmd = ("{sambamba} slice {in_bam} {region} -o {tx_out_file}")
do.run(cmd.format(**locals()), "Slice region", {})
return out_file | python | def _slice_bam(in_bam, region, tmp_dir, config):
"""Use sambamba to slice a bam region"""
name_file = os.path.splitext(os.path.basename(in_bam))[0]
out_file = os.path.join(tmp_dir, os.path.join(tmp_dir, name_file + _to_str(region) + ".bam"))
sambamba = config_utils.get_program("sambamba", config)
region = _to_sambamba(region)
with file_transaction(out_file) as tx_out_file:
cmd = ("{sambamba} slice {in_bam} {region} -o {tx_out_file}")
do.run(cmd.format(**locals()), "Slice region", {})
return out_file | [
"def",
"_slice_bam",
"(",
"in_bam",
",",
"region",
",",
"tmp_dir",
",",
"config",
")",
":",
"name_file",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"in_bam",
")",
")",
"[",
"0",
"]",
"out_file",
"=",
"os"... | Use sambamba to slice a bam region | [
"Use",
"sambamba",
"to",
"slice",
"a",
"bam",
"region"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/qsnp.py#L114-L123 |
224,321 | bcbio/bcbio-nextgen | bcbio/variation/qsnp.py | _create_input | def _create_input(paired, out_file, ref_file, snp_file, qsnp_file):
"""Create INI input for qSNP"""
ini_file["[inputFiles]"]["dbSNP"] = snp_file
ini_file["[inputFiles]"]["ref"] = ref_file
ini_file["[inputFiles]"]["normalBam"] = paired.normal_bam
ini_file["[inputFiles]"]["tumourBam"] = paired.tumor_bam
ini_file["[ids]"]["normalSample"] = paired.normal_name
ini_file["[ids]"]["tumourSample"] = paired.tumor_name
ini_file["[ids]"]["donor"] = paired.tumor_name
ini_file["[outputFiles]"]["vcf"] = out_file
with open(qsnp_file, "w") as out_handle:
for k, v in ini_file.items():
out_handle.write("%s\n" % k)
for opt, value in v.items():
if value != "":
out_handle.write("%s = %s\n" % (opt, value)) | python | def _create_input(paired, out_file, ref_file, snp_file, qsnp_file):
"""Create INI input for qSNP"""
ini_file["[inputFiles]"]["dbSNP"] = snp_file
ini_file["[inputFiles]"]["ref"] = ref_file
ini_file["[inputFiles]"]["normalBam"] = paired.normal_bam
ini_file["[inputFiles]"]["tumourBam"] = paired.tumor_bam
ini_file["[ids]"]["normalSample"] = paired.normal_name
ini_file["[ids]"]["tumourSample"] = paired.tumor_name
ini_file["[ids]"]["donor"] = paired.tumor_name
ini_file["[outputFiles]"]["vcf"] = out_file
with open(qsnp_file, "w") as out_handle:
for k, v in ini_file.items():
out_handle.write("%s\n" % k)
for opt, value in v.items():
if value != "":
out_handle.write("%s = %s\n" % (opt, value)) | [
"def",
"_create_input",
"(",
"paired",
",",
"out_file",
",",
"ref_file",
",",
"snp_file",
",",
"qsnp_file",
")",
":",
"ini_file",
"[",
"\"[inputFiles]\"",
"]",
"[",
"\"dbSNP\"",
"]",
"=",
"snp_file",
"ini_file",
"[",
"\"[inputFiles]\"",
"]",
"[",
"\"ref\"",
... | Create INI input for qSNP | [
"Create",
"INI",
"input",
"for",
"qSNP"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/qsnp.py#L125-L140 |
224,322 | bcbio/bcbio-nextgen | bcbio/variation/qsnp.py | _filter_vcf | def _filter_vcf(out_file):
"""Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference.
"""
in_file = out_file.replace(".vcf", "-ori.vcf")
FILTER_line = ('##FILTER=<ID=SBIAS,Description="Due to bias">\n'
'##FILTER=<ID=5BP,Description="Due to 5BP">\n'
'##FILTER=<ID=REJECT,Description="Not somatic due to qSNP filters">\n')
SOMATIC_line = '##INFO=<ID=SOMATIC,Number=0,Type=Flag,Description="somatic event">\n'
if not utils.file_exists(in_file):
shutil.move(out_file, in_file)
with file_transaction(out_file) as tx_out_file:
with open(in_file) as in_handle, open(tx_out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("##normalSample="):
normal_name = line.strip().split("=")[1]
if line.startswith("##patient_id="):
tumor_name = line.strip().split("=")[1]
if line.startswith("#CHROM"):
line = line.replace("Normal", normal_name)
line = line.replace("Tumour", tumor_name)
if line.startswith("##INFO=<ID=FS"):
line = line.replace("ID=FS", "ID=RNT")
if line.find("FS=") > -1:
line = line.replace("FS=", "RNT=")
if "5BP" in line:
line = sub("5BP[0-9]+", "5BP", line)
if line.find("PASS") == -1:
line = _set_reject(line)
if line.find("PASS") > - 1 and line.find("SOMATIC") == -1:
line = _set_reject(line)
if not _has_ambiguous_ref_allele(line):
out_handle.write(line)
if line.startswith("##FILTER") and FILTER_line:
out_handle.write("%s" % FILTER_line)
FILTER_line = ""
if line.startswith("##INFO") and SOMATIC_line:
out_handle.write("%s" % SOMATIC_line)
SOMATIC_line = ""
return out_file | python | def _filter_vcf(out_file):
"""Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference.
"""
in_file = out_file.replace(".vcf", "-ori.vcf")
FILTER_line = ('##FILTER=<ID=SBIAS,Description="Due to bias">\n'
'##FILTER=<ID=5BP,Description="Due to 5BP">\n'
'##FILTER=<ID=REJECT,Description="Not somatic due to qSNP filters">\n')
SOMATIC_line = '##INFO=<ID=SOMATIC,Number=0,Type=Flag,Description="somatic event">\n'
if not utils.file_exists(in_file):
shutil.move(out_file, in_file)
with file_transaction(out_file) as tx_out_file:
with open(in_file) as in_handle, open(tx_out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("##normalSample="):
normal_name = line.strip().split("=")[1]
if line.startswith("##patient_id="):
tumor_name = line.strip().split("=")[1]
if line.startswith("#CHROM"):
line = line.replace("Normal", normal_name)
line = line.replace("Tumour", tumor_name)
if line.startswith("##INFO=<ID=FS"):
line = line.replace("ID=FS", "ID=RNT")
if line.find("FS=") > -1:
line = line.replace("FS=", "RNT=")
if "5BP" in line:
line = sub("5BP[0-9]+", "5BP", line)
if line.find("PASS") == -1:
line = _set_reject(line)
if line.find("PASS") > - 1 and line.find("SOMATIC") == -1:
line = _set_reject(line)
if not _has_ambiguous_ref_allele(line):
out_handle.write(line)
if line.startswith("##FILTER") and FILTER_line:
out_handle.write("%s" % FILTER_line)
FILTER_line = ""
if line.startswith("##INFO") and SOMATIC_line:
out_handle.write("%s" % SOMATIC_line)
SOMATIC_line = ""
return out_file | [
"def",
"_filter_vcf",
"(",
"out_file",
")",
":",
"in_file",
"=",
"out_file",
".",
"replace",
"(",
"\".vcf\"",
",",
"\"-ori.vcf\"",
")",
"FILTER_line",
"=",
"(",
"'##FILTER=<ID=SBIAS,Description=\"Due to bias\">\\n'",
"'##FILTER=<ID=5BP,Description=\"Due to 5BP\">\\n'",
"'##... | Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference. | [
"Fix",
"sample",
"names",
"FILTER",
"and",
"FORMAT",
"fields",
".",
"Remove",
"lines",
"with",
"ambiguous",
"reference",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/qsnp.py#L147-L185 |
224,323 | bcbio/bcbio-nextgen | bcbio/variation/qsnp.py | _set_reject | def _set_reject(line):
"""Set REJECT in VCF line, or add it if there is something else."""
if line.startswith("#"):
return line
parts = line.split("\t")
if parts[6] == "PASS":
parts[6] = "REJECT"
else:
parts[6] += ";REJECT"
return "\t".join(parts) | python | def _set_reject(line):
"""Set REJECT in VCF line, or add it if there is something else."""
if line.startswith("#"):
return line
parts = line.split("\t")
if parts[6] == "PASS":
parts[6] = "REJECT"
else:
parts[6] += ";REJECT"
return "\t".join(parts) | [
"def",
"_set_reject",
"(",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"return",
"line",
"parts",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"if",
"parts",
"[",
"6",
"]",
"==",
"\"PASS\"",
":",
"parts",
"[",
"6",... | Set REJECT in VCF line, or add it if there is something else. | [
"Set",
"REJECT",
"in",
"VCF",
"line",
"or",
"add",
"it",
"if",
"there",
"is",
"something",
"else",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/qsnp.py#L193-L202 |
224,324 | bcbio/bcbio-nextgen | scripts/utils/cg_svevents_to_vcf.py | svevent_reader | def svevent_reader(in_file):
"""Lazy generator of SV events, returned as dictionary of parts.
"""
with open(in_file) as in_handle:
while 1:
line = next(in_handle)
if line.startswith(">"):
break
header = line[1:].rstrip().split("\t")
reader = csv.reader(in_handle, dialect="excel-tab")
for parts in reader:
out = {}
for h, p in zip(header, parts):
out[h] = p
yield out | python | def svevent_reader(in_file):
"""Lazy generator of SV events, returned as dictionary of parts.
"""
with open(in_file) as in_handle:
while 1:
line = next(in_handle)
if line.startswith(">"):
break
header = line[1:].rstrip().split("\t")
reader = csv.reader(in_handle, dialect="excel-tab")
for parts in reader:
out = {}
for h, p in zip(header, parts):
out[h] = p
yield out | [
"def",
"svevent_reader",
"(",
"in_file",
")",
":",
"with",
"open",
"(",
"in_file",
")",
"as",
"in_handle",
":",
"while",
"1",
":",
"line",
"=",
"next",
"(",
"in_handle",
")",
"if",
"line",
".",
"startswith",
"(",
"\">\"",
")",
":",
"break",
"header",
... | Lazy generator of SV events, returned as dictionary of parts. | [
"Lazy",
"generator",
"of",
"SV",
"events",
"returned",
"as",
"dictionary",
"of",
"parts",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/cg_svevents_to_vcf.py#L64-L78 |
224,325 | bcbio/bcbio-nextgen | bcbio/cwl/inspect.py | initialize_watcher | def initialize_watcher(samples):
"""
check to see if cwl_reporting is set for any samples,
and if so, initialize a WorldWatcher object from a set of samples,
"""
work_dir = dd.get_in_samples(samples, dd.get_work_dir)
ww = WorldWatcher(work_dir,
is_on=any([dd.get_cwl_reporting(d[0]) for d in samples]))
ww.initialize(samples)
return ww | python | def initialize_watcher(samples):
"""
check to see if cwl_reporting is set for any samples,
and if so, initialize a WorldWatcher object from a set of samples,
"""
work_dir = dd.get_in_samples(samples, dd.get_work_dir)
ww = WorldWatcher(work_dir,
is_on=any([dd.get_cwl_reporting(d[0]) for d in samples]))
ww.initialize(samples)
return ww | [
"def",
"initialize_watcher",
"(",
"samples",
")",
":",
"work_dir",
"=",
"dd",
".",
"get_in_samples",
"(",
"samples",
",",
"dd",
".",
"get_work_dir",
")",
"ww",
"=",
"WorldWatcher",
"(",
"work_dir",
",",
"is_on",
"=",
"any",
"(",
"[",
"dd",
".",
"get_cwl_... | check to see if cwl_reporting is set for any samples,
and if so, initialize a WorldWatcher object from a set of samples, | [
"check",
"to",
"see",
"if",
"cwl_reporting",
"is",
"set",
"for",
"any",
"samples",
"and",
"if",
"so",
"initialize",
"a",
"WorldWatcher",
"object",
"from",
"a",
"set",
"of",
"samples"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/inspect.py#L92-L101 |
224,326 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | guess_infer_extent | def guess_infer_extent(gtf_file):
"""
guess if we need to use the gene extent option when making a gffutils
database by making a tiny database of 1000 lines from the original
GTF and looking for all of the features
"""
_, ext = os.path.splitext(gtf_file)
tmp_out = tempfile.NamedTemporaryFile(suffix=".gtf", delete=False).name
with open(tmp_out, "w") as out_handle:
count = 0
in_handle = utils.open_gzipsafe(gtf_file)
for line in in_handle:
if count > 1000:
break
out_handle.write(line)
count += 1
in_handle.close()
db = gffutils.create_db(tmp_out, dbfn=":memory:", infer_gene_extent=False)
os.remove(tmp_out)
features = [x for x in db.featuretypes()]
if "gene" in features and "transcript" in features:
return False
else:
return True | python | def guess_infer_extent(gtf_file):
"""
guess if we need to use the gene extent option when making a gffutils
database by making a tiny database of 1000 lines from the original
GTF and looking for all of the features
"""
_, ext = os.path.splitext(gtf_file)
tmp_out = tempfile.NamedTemporaryFile(suffix=".gtf", delete=False).name
with open(tmp_out, "w") as out_handle:
count = 0
in_handle = utils.open_gzipsafe(gtf_file)
for line in in_handle:
if count > 1000:
break
out_handle.write(line)
count += 1
in_handle.close()
db = gffutils.create_db(tmp_out, dbfn=":memory:", infer_gene_extent=False)
os.remove(tmp_out)
features = [x for x in db.featuretypes()]
if "gene" in features and "transcript" in features:
return False
else:
return True | [
"def",
"guess_infer_extent",
"(",
"gtf_file",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"gtf_file",
")",
"tmp_out",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"\".gtf\"",
",",
"delete",
"=",
"False",
")... | guess if we need to use the gene extent option when making a gffutils
database by making a tiny database of 1000 lines from the original
GTF and looking for all of the features | [
"guess",
"if",
"we",
"need",
"to",
"use",
"the",
"gene",
"extent",
"option",
"when",
"making",
"a",
"gffutils",
"database",
"by",
"making",
"a",
"tiny",
"database",
"of",
"1000",
"lines",
"from",
"the",
"original",
"GTF",
"and",
"looking",
"for",
"all",
... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L13-L36 |
224,327 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | get_gtf_db | def get_gtf_db(gtf, in_memory=False):
"""
create a gffutils DB, in memory if we don't have write permissions
"""
db_file = gtf + ".db"
if file_exists(db_file):
return gffutils.FeatureDB(db_file)
if not os.access(os.path.dirname(db_file), os.W_OK | os.X_OK):
in_memory = True
db_file = ":memory:" if in_memory else db_file
if in_memory or not file_exists(db_file):
infer_extent = guess_infer_extent(gtf)
disable_extent = not infer_extent
db = gffutils.create_db(gtf, dbfn=db_file,
disable_infer_genes=disable_extent,
disable_infer_transcripts=disable_extent)
if in_memory:
return db
else:
return gffutils.FeatureDB(db_file) | python | def get_gtf_db(gtf, in_memory=False):
"""
create a gffutils DB, in memory if we don't have write permissions
"""
db_file = gtf + ".db"
if file_exists(db_file):
return gffutils.FeatureDB(db_file)
if not os.access(os.path.dirname(db_file), os.W_OK | os.X_OK):
in_memory = True
db_file = ":memory:" if in_memory else db_file
if in_memory or not file_exists(db_file):
infer_extent = guess_infer_extent(gtf)
disable_extent = not infer_extent
db = gffutils.create_db(gtf, dbfn=db_file,
disable_infer_genes=disable_extent,
disable_infer_transcripts=disable_extent)
if in_memory:
return db
else:
return gffutils.FeatureDB(db_file) | [
"def",
"get_gtf_db",
"(",
"gtf",
",",
"in_memory",
"=",
"False",
")",
":",
"db_file",
"=",
"gtf",
"+",
"\".db\"",
"if",
"file_exists",
"(",
"db_file",
")",
":",
"return",
"gffutils",
".",
"FeatureDB",
"(",
"db_file",
")",
"if",
"not",
"os",
".",
"acces... | create a gffutils DB, in memory if we don't have write permissions | [
"create",
"a",
"gffutils",
"DB",
"in",
"memory",
"if",
"we",
"don",
"t",
"have",
"write",
"permissions"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L38-L57 |
224,328 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | partition_gtf | def partition_gtf(gtf, coding=False, out_file=False):
"""
return a GTF file of all non-coding or coding transcripts. the GTF must be annotated
with gene_biotype = "protein_coding" or to have the source column set to the
biotype for all coding transcripts. set coding to
True to get only the coding, false to get only the non-coding
"""
if out_file and file_exists(out_file):
return out_file
if not out_file:
out_file = tempfile.NamedTemporaryFile(delete=False,
suffix=".gtf").name
if coding:
pred = lambda biotype: biotype and biotype == "protein_coding"
else:
pred = lambda biotype: biotype and biotype != "protein_coding"
biotype_lookup = _biotype_lookup_fn(gtf)
db = get_gtf_db(gtf)
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for feature in db.all_features():
biotype = biotype_lookup(feature)
if pred(biotype):
out_handle.write(str(feature) + "\n")
return out_file | python | def partition_gtf(gtf, coding=False, out_file=False):
"""
return a GTF file of all non-coding or coding transcripts. the GTF must be annotated
with gene_biotype = "protein_coding" or to have the source column set to the
biotype for all coding transcripts. set coding to
True to get only the coding, false to get only the non-coding
"""
if out_file and file_exists(out_file):
return out_file
if not out_file:
out_file = tempfile.NamedTemporaryFile(delete=False,
suffix=".gtf").name
if coding:
pred = lambda biotype: biotype and biotype == "protein_coding"
else:
pred = lambda biotype: biotype and biotype != "protein_coding"
biotype_lookup = _biotype_lookup_fn(gtf)
db = get_gtf_db(gtf)
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for feature in db.all_features():
biotype = biotype_lookup(feature)
if pred(biotype):
out_handle.write(str(feature) + "\n")
return out_file | [
"def",
"partition_gtf",
"(",
"gtf",
",",
"coding",
"=",
"False",
",",
"out_file",
"=",
"False",
")",
":",
"if",
"out_file",
"and",
"file_exists",
"(",
"out_file",
")",
":",
"return",
"out_file",
"if",
"not",
"out_file",
":",
"out_file",
"=",
"tempfile",
... | return a GTF file of all non-coding or coding transcripts. the GTF must be annotated
with gene_biotype = "protein_coding" or to have the source column set to the
biotype for all coding transcripts. set coding to
True to get only the coding, false to get only the non-coding | [
"return",
"a",
"GTF",
"file",
"of",
"all",
"non",
"-",
"coding",
"or",
"coding",
"transcripts",
".",
"the",
"GTF",
"must",
"be",
"annotated",
"with",
"gene_biotype",
"=",
"protein_coding",
"or",
"to",
"have",
"the",
"source",
"column",
"set",
"to",
"the",
... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L142-L169 |
224,329 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | split_gtf | def split_gtf(gtf, sample_size=None, out_dir=None):
"""
split a GTF file into two equal parts, randomly selecting genes.
sample_size will select up to sample_size genes in total
"""
if out_dir:
part1_fn = os.path.basename(os.path.splitext(gtf)[0]) + ".part1.gtf"
part2_fn = os.path.basename(os.path.splitext(gtf)[0]) + ".part2.gtf"
part1 = os.path.join(out_dir, part1_fn)
part2 = os.path.join(out_dir, part2_fn)
if file_exists(part1) and file_exists(part2):
return part1, part2
else:
part1 = tempfile.NamedTemporaryFile(delete=False, suffix=".part1.gtf").name
part2 = tempfile.NamedTemporaryFile(delete=False, suffix=".part2.gtf").name
db = get_gtf_db(gtf)
gene_ids = set([x['gene_id'][0] for x in db.all_features()])
if not sample_size or (sample_size and sample_size > len(gene_ids)):
sample_size = len(gene_ids)
gene_ids = set(random.sample(gene_ids, sample_size))
part1_ids = set(random.sample(gene_ids, sample_size / 2))
part2_ids = gene_ids.difference(part1_ids)
with open(part1, "w") as part1_handle:
for gene in part1_ids:
for feature in db.children(gene):
part1_handle.write(str(feature) + "\n")
with open(part2, "w") as part2_handle:
for gene in part2_ids:
for feature in db.children(gene):
part2_handle.write(str(feature) + "\n")
return part1, part2 | python | def split_gtf(gtf, sample_size=None, out_dir=None):
"""
split a GTF file into two equal parts, randomly selecting genes.
sample_size will select up to sample_size genes in total
"""
if out_dir:
part1_fn = os.path.basename(os.path.splitext(gtf)[0]) + ".part1.gtf"
part2_fn = os.path.basename(os.path.splitext(gtf)[0]) + ".part2.gtf"
part1 = os.path.join(out_dir, part1_fn)
part2 = os.path.join(out_dir, part2_fn)
if file_exists(part1) and file_exists(part2):
return part1, part2
else:
part1 = tempfile.NamedTemporaryFile(delete=False, suffix=".part1.gtf").name
part2 = tempfile.NamedTemporaryFile(delete=False, suffix=".part2.gtf").name
db = get_gtf_db(gtf)
gene_ids = set([x['gene_id'][0] for x in db.all_features()])
if not sample_size or (sample_size and sample_size > len(gene_ids)):
sample_size = len(gene_ids)
gene_ids = set(random.sample(gene_ids, sample_size))
part1_ids = set(random.sample(gene_ids, sample_size / 2))
part2_ids = gene_ids.difference(part1_ids)
with open(part1, "w") as part1_handle:
for gene in part1_ids:
for feature in db.children(gene):
part1_handle.write(str(feature) + "\n")
with open(part2, "w") as part2_handle:
for gene in part2_ids:
for feature in db.children(gene):
part2_handle.write(str(feature) + "\n")
return part1, part2 | [
"def",
"split_gtf",
"(",
"gtf",
",",
"sample_size",
"=",
"None",
",",
"out_dir",
"=",
"None",
")",
":",
"if",
"out_dir",
":",
"part1_fn",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"gtf",
")",
"[",
"0",
... | split a GTF file into two equal parts, randomly selecting genes.
sample_size will select up to sample_size genes in total | [
"split",
"a",
"GTF",
"file",
"into",
"two",
"equal",
"parts",
"randomly",
"selecting",
"genes",
".",
"sample_size",
"will",
"select",
"up",
"to",
"sample_size",
"genes",
"in",
"total"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L171-L202 |
224,330 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | get_coding_noncoding_transcript_ids | def get_coding_noncoding_transcript_ids(gtf):
"""
return a set of coding and non-coding transcript_ids from a GTF
"""
coding_gtf = partition_gtf(gtf, coding=True)
coding_db = get_gtf_db(coding_gtf)
coding_ids = set([x['transcript_id'][0] for x in coding_db.all_features()
if 'transcript_id' in x.attributes])
noncoding_gtf = partition_gtf(gtf)
noncoding_db = get_gtf_db(noncoding_gtf)
noncoding_ids = set([x['transcript_id'][0] for x in noncoding_db.all_features()
if 'transcript_id' in x.attributes])
return coding_ids, noncoding_ids | python | def get_coding_noncoding_transcript_ids(gtf):
"""
return a set of coding and non-coding transcript_ids from a GTF
"""
coding_gtf = partition_gtf(gtf, coding=True)
coding_db = get_gtf_db(coding_gtf)
coding_ids = set([x['transcript_id'][0] for x in coding_db.all_features()
if 'transcript_id' in x.attributes])
noncoding_gtf = partition_gtf(gtf)
noncoding_db = get_gtf_db(noncoding_gtf)
noncoding_ids = set([x['transcript_id'][0] for x in noncoding_db.all_features()
if 'transcript_id' in x.attributes])
return coding_ids, noncoding_ids | [
"def",
"get_coding_noncoding_transcript_ids",
"(",
"gtf",
")",
":",
"coding_gtf",
"=",
"partition_gtf",
"(",
"gtf",
",",
"coding",
"=",
"True",
")",
"coding_db",
"=",
"get_gtf_db",
"(",
"coding_gtf",
")",
"coding_ids",
"=",
"set",
"(",
"[",
"x",
"[",
"'trans... | return a set of coding and non-coding transcript_ids from a GTF | [
"return",
"a",
"set",
"of",
"coding",
"and",
"non",
"-",
"coding",
"transcript_ids",
"from",
"a",
"GTF"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L204-L216 |
224,331 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | get_gene_source_set | def get_gene_source_set(gtf):
"""
get a dictionary of the set of all sources for a gene
"""
gene_to_source = {}
db = get_gtf_db(gtf)
for feature in complete_features(db):
gene_id = feature['gene_id'][0]
sources = gene_to_source.get(gene_id, set([])).union(set([feature.source]))
gene_to_source[gene_id] = sources
return gene_to_source | python | def get_gene_source_set(gtf):
"""
get a dictionary of the set of all sources for a gene
"""
gene_to_source = {}
db = get_gtf_db(gtf)
for feature in complete_features(db):
gene_id = feature['gene_id'][0]
sources = gene_to_source.get(gene_id, set([])).union(set([feature.source]))
gene_to_source[gene_id] = sources
return gene_to_source | [
"def",
"get_gene_source_set",
"(",
"gtf",
")",
":",
"gene_to_source",
"=",
"{",
"}",
"db",
"=",
"get_gtf_db",
"(",
"gtf",
")",
"for",
"feature",
"in",
"complete_features",
"(",
"db",
")",
":",
"gene_id",
"=",
"feature",
"[",
"'gene_id'",
"]",
"[",
"0",
... | get a dictionary of the set of all sources for a gene | [
"get",
"a",
"dictionary",
"of",
"the",
"set",
"of",
"all",
"sources",
"for",
"a",
"gene"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L218-L228 |
224,332 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | get_transcript_source_set | def get_transcript_source_set(gtf):
"""
get a dictionary of the set of all sources of the gene for a given
transcript
"""
gene_to_source = get_gene_source_set(gtf)
transcript_to_source = {}
db = get_gtf_db(gtf)
for feature in complete_features(db):
gene_id = feature['gene_id'][0]
transcript_to_source[feature['transcript_id'][0]] = gene_to_source[gene_id]
return transcript_to_source | python | def get_transcript_source_set(gtf):
"""
get a dictionary of the set of all sources of the gene for a given
transcript
"""
gene_to_source = get_gene_source_set(gtf)
transcript_to_source = {}
db = get_gtf_db(gtf)
for feature in complete_features(db):
gene_id = feature['gene_id'][0]
transcript_to_source[feature['transcript_id'][0]] = gene_to_source[gene_id]
return transcript_to_source | [
"def",
"get_transcript_source_set",
"(",
"gtf",
")",
":",
"gene_to_source",
"=",
"get_gene_source_set",
"(",
"gtf",
")",
"transcript_to_source",
"=",
"{",
"}",
"db",
"=",
"get_gtf_db",
"(",
"gtf",
")",
"for",
"feature",
"in",
"complete_features",
"(",
"db",
")... | get a dictionary of the set of all sources of the gene for a given
transcript | [
"get",
"a",
"dictionary",
"of",
"the",
"set",
"of",
"all",
"sources",
"of",
"the",
"gene",
"for",
"a",
"given",
"transcript"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L230-L241 |
224,333 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | get_rRNA | def get_rRNA(gtf):
"""
extract rRNA genes and transcripts from a gtf file
"""
rRNA_biotypes = ["rRNA", "Mt_rRNA", "tRNA", "MT_tRNA"]
features = set()
with open_gzipsafe(gtf) as in_handle:
for line in in_handle:
if not "gene_id" in line or not "transcript_id" in line:
continue
if any(x in line for x in rRNA_biotypes):
geneid = line.split("gene_id")[1].split(" ")[1]
geneid = _strip_non_alphanumeric(geneid)
geneid = _strip_feature_version(geneid)
txid = line.split("transcript_id")[1].split(" ")[1]
txid = _strip_non_alphanumeric(txid)
txid = _strip_feature_version(txid)
features.add((geneid, txid))
return features | python | def get_rRNA(gtf):
"""
extract rRNA genes and transcripts from a gtf file
"""
rRNA_biotypes = ["rRNA", "Mt_rRNA", "tRNA", "MT_tRNA"]
features = set()
with open_gzipsafe(gtf) as in_handle:
for line in in_handle:
if not "gene_id" in line or not "transcript_id" in line:
continue
if any(x in line for x in rRNA_biotypes):
geneid = line.split("gene_id")[1].split(" ")[1]
geneid = _strip_non_alphanumeric(geneid)
geneid = _strip_feature_version(geneid)
txid = line.split("transcript_id")[1].split(" ")[1]
txid = _strip_non_alphanumeric(txid)
txid = _strip_feature_version(txid)
features.add((geneid, txid))
return features | [
"def",
"get_rRNA",
"(",
"gtf",
")",
":",
"rRNA_biotypes",
"=",
"[",
"\"rRNA\"",
",",
"\"Mt_rRNA\"",
",",
"\"tRNA\"",
",",
"\"MT_tRNA\"",
"]",
"features",
"=",
"set",
"(",
")",
"with",
"open_gzipsafe",
"(",
"gtf",
")",
"as",
"in_handle",
":",
"for",
"line... | extract rRNA genes and transcripts from a gtf file | [
"extract",
"rRNA",
"genes",
"and",
"transcripts",
"from",
"a",
"gtf",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L243-L261 |
224,334 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | _biotype_lookup_fn | def _biotype_lookup_fn(gtf):
"""
return a function that will look up the biotype of a feature
this checks for either gene_biotype or biotype being set or for the source
column to have biotype information
"""
db = get_gtf_db(gtf)
sources = set([feature.source for feature in db.all_features()])
gene_biotypes = set([feature.attributes.get("gene_biotype", [None])[0]
for feature in db.all_features()])
biotypes = set([feature.attributes.get("biotype", [None])[0]
for feature in db.all_features()])
if "protein_coding" in sources:
return lambda feature: feature.source
elif "protein_coding" in biotypes:
return lambda feature: feature.attributes.get("biotype", [None])[0]
elif "protein_coding" in gene_biotypes:
return lambda feature: feature.attributes.get("gene_biotype", [None])[0]
else:
return None | python | def _biotype_lookup_fn(gtf):
"""
return a function that will look up the biotype of a feature
this checks for either gene_biotype or biotype being set or for the source
column to have biotype information
"""
db = get_gtf_db(gtf)
sources = set([feature.source for feature in db.all_features()])
gene_biotypes = set([feature.attributes.get("gene_biotype", [None])[0]
for feature in db.all_features()])
biotypes = set([feature.attributes.get("biotype", [None])[0]
for feature in db.all_features()])
if "protein_coding" in sources:
return lambda feature: feature.source
elif "protein_coding" in biotypes:
return lambda feature: feature.attributes.get("biotype", [None])[0]
elif "protein_coding" in gene_biotypes:
return lambda feature: feature.attributes.get("gene_biotype", [None])[0]
else:
return None | [
"def",
"_biotype_lookup_fn",
"(",
"gtf",
")",
":",
"db",
"=",
"get_gtf_db",
"(",
"gtf",
")",
"sources",
"=",
"set",
"(",
"[",
"feature",
".",
"source",
"for",
"feature",
"in",
"db",
".",
"all_features",
"(",
")",
"]",
")",
"gene_biotypes",
"=",
"set",
... | return a function that will look up the biotype of a feature
this checks for either gene_biotype or biotype being set or for the source
column to have biotype information | [
"return",
"a",
"function",
"that",
"will",
"look",
"up",
"the",
"biotype",
"of",
"a",
"feature",
"this",
"checks",
"for",
"either",
"gene_biotype",
"or",
"biotype",
"being",
"set",
"or",
"for",
"the",
"source",
"column",
"to",
"have",
"biotype",
"information... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L263-L282 |
224,335 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | tx2genedict | def tx2genedict(gtf, keep_version=False):
"""
produce a tx2gene dictionary from a GTF file
"""
d = {}
with open_gzipsafe(gtf) as in_handle:
for line in in_handle:
if "gene_id" not in line or "transcript_id" not in line:
continue
geneid = line.split("gene_id")[1].split(" ")[1]
geneid = _strip_non_alphanumeric(geneid)
txid = line.split("transcript_id")[1].split(" ")[1]
txid = _strip_non_alphanumeric(txid)
if keep_version and "transcript_version" in line:
txversion = line.split("transcript_version")[1].split(" ")[1]
txversion = _strip_non_alphanumeric(txversion)
txid += "." + txversion
if has_transcript_version(line) and not keep_version:
txid = _strip_feature_version(txid)
geneid = _strip_feature_version(geneid)
d[txid] = geneid
return d | python | def tx2genedict(gtf, keep_version=False):
"""
produce a tx2gene dictionary from a GTF file
"""
d = {}
with open_gzipsafe(gtf) as in_handle:
for line in in_handle:
if "gene_id" not in line or "transcript_id" not in line:
continue
geneid = line.split("gene_id")[1].split(" ")[1]
geneid = _strip_non_alphanumeric(geneid)
txid = line.split("transcript_id")[1].split(" ")[1]
txid = _strip_non_alphanumeric(txid)
if keep_version and "transcript_version" in line:
txversion = line.split("transcript_version")[1].split(" ")[1]
txversion = _strip_non_alphanumeric(txversion)
txid += "." + txversion
if has_transcript_version(line) and not keep_version:
txid = _strip_feature_version(txid)
geneid = _strip_feature_version(geneid)
d[txid] = geneid
return d | [
"def",
"tx2genedict",
"(",
"gtf",
",",
"keep_version",
"=",
"False",
")",
":",
"d",
"=",
"{",
"}",
"with",
"open_gzipsafe",
"(",
"gtf",
")",
"as",
"in_handle",
":",
"for",
"line",
"in",
"in_handle",
":",
"if",
"\"gene_id\"",
"not",
"in",
"line",
"or",
... | produce a tx2gene dictionary from a GTF file | [
"produce",
"a",
"tx2gene",
"dictionary",
"from",
"a",
"GTF",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L284-L305 |
224,336 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | _strip_feature_version | def _strip_feature_version(featureid):
"""
some feature versions are encoded as featureid.version, this strips those off, if they exist
"""
version_detector = re.compile(r"(?P<featureid>.*)(?P<version>\.\d+)")
match = version_detector.match(featureid)
if match:
return match.groupdict()["featureid"]
else:
return featureid | python | def _strip_feature_version(featureid):
"""
some feature versions are encoded as featureid.version, this strips those off, if they exist
"""
version_detector = re.compile(r"(?P<featureid>.*)(?P<version>\.\d+)")
match = version_detector.match(featureid)
if match:
return match.groupdict()["featureid"]
else:
return featureid | [
"def",
"_strip_feature_version",
"(",
"featureid",
")",
":",
"version_detector",
"=",
"re",
".",
"compile",
"(",
"r\"(?P<featureid>.*)(?P<version>\\.\\d+)\"",
")",
"match",
"=",
"version_detector",
".",
"match",
"(",
"featureid",
")",
"if",
"match",
":",
"return",
... | some feature versions are encoded as featureid.version, this strips those off, if they exist | [
"some",
"feature",
"versions",
"are",
"encoded",
"as",
"featureid",
".",
"version",
"this",
"strips",
"those",
"off",
"if",
"they",
"exist"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L307-L316 |
224,337 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | tx2genefile | def tx2genefile(gtf, out_file=None, data=None, tsv=True, keep_version=False):
"""
write out a file of transcript->gene mappings.
"""
if tsv:
extension = ".tsv"
sep = "\t"
else:
extension = ".csv"
sep = ","
if file_exists(out_file):
return out_file
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for k, v in tx2genedict(gtf, keep_version).items():
out_handle.write(sep.join([k, v]) + "\n")
logger.info("tx2gene file %s created from %s." % (out_file, gtf))
return out_file | python | def tx2genefile(gtf, out_file=None, data=None, tsv=True, keep_version=False):
"""
write out a file of transcript->gene mappings.
"""
if tsv:
extension = ".tsv"
sep = "\t"
else:
extension = ".csv"
sep = ","
if file_exists(out_file):
return out_file
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for k, v in tx2genedict(gtf, keep_version).items():
out_handle.write(sep.join([k, v]) + "\n")
logger.info("tx2gene file %s created from %s." % (out_file, gtf))
return out_file | [
"def",
"tx2genefile",
"(",
"gtf",
",",
"out_file",
"=",
"None",
",",
"data",
"=",
"None",
",",
"tsv",
"=",
"True",
",",
"keep_version",
"=",
"False",
")",
":",
"if",
"tsv",
":",
"extension",
"=",
"\".tsv\"",
"sep",
"=",
"\"\\t\"",
"else",
":",
"exten... | write out a file of transcript->gene mappings. | [
"write",
"out",
"a",
"file",
"of",
"transcript",
"-",
">",
"gene",
"mappings",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L330-L347 |
224,338 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | is_qualimap_compatible | def is_qualimap_compatible(gtf):
"""
Qualimap needs a very specific GTF format or it fails, so skip it if
the GTF is not in that format
"""
if not gtf:
return False
db = get_gtf_db(gtf)
def qualimap_compatible(feature):
gene_id = feature.attributes.get('gene_id', [None])[0]
transcript_id = feature.attributes.get('transcript_id', [None])[0]
gene_biotype = feature.attributes.get('gene_biotype', [None])[0]
return gene_id and transcript_id and gene_biotype
for feature in db.all_features():
if qualimap_compatible(feature):
return True
return False | python | def is_qualimap_compatible(gtf):
"""
Qualimap needs a very specific GTF format or it fails, so skip it if
the GTF is not in that format
"""
if not gtf:
return False
db = get_gtf_db(gtf)
def qualimap_compatible(feature):
gene_id = feature.attributes.get('gene_id', [None])[0]
transcript_id = feature.attributes.get('transcript_id', [None])[0]
gene_biotype = feature.attributes.get('gene_biotype', [None])[0]
return gene_id and transcript_id and gene_biotype
for feature in db.all_features():
if qualimap_compatible(feature):
return True
return False | [
"def",
"is_qualimap_compatible",
"(",
"gtf",
")",
":",
"if",
"not",
"gtf",
":",
"return",
"False",
"db",
"=",
"get_gtf_db",
"(",
"gtf",
")",
"def",
"qualimap_compatible",
"(",
"feature",
")",
":",
"gene_id",
"=",
"feature",
".",
"attributes",
".",
"get",
... | Qualimap needs a very specific GTF format or it fails, so skip it if
the GTF is not in that format | [
"Qualimap",
"needs",
"a",
"very",
"specific",
"GTF",
"format",
"or",
"it",
"fails",
"so",
"skip",
"it",
"if",
"the",
"GTF",
"is",
"not",
"in",
"that",
"format"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L349-L365 |
224,339 | bcbio/bcbio-nextgen | bcbio/rnaseq/gtf.py | is_cpat_compatible | def is_cpat_compatible(gtf):
"""
CPAT needs some transcripts annotated with protein coding status to work
properly
"""
if not gtf:
return False
db = get_gtf_db(gtf)
pred = lambda biotype: biotype and biotype == "protein_coding"
biotype_lookup = _biotype_lookup_fn(gtf)
if not biotype_lookup:
return False
db = get_gtf_db(gtf)
for feature in db.all_features():
biotype = biotype_lookup(feature)
if pred(biotype):
return True
return False | python | def is_cpat_compatible(gtf):
"""
CPAT needs some transcripts annotated with protein coding status to work
properly
"""
if not gtf:
return False
db = get_gtf_db(gtf)
pred = lambda biotype: biotype and biotype == "protein_coding"
biotype_lookup = _biotype_lookup_fn(gtf)
if not biotype_lookup:
return False
db = get_gtf_db(gtf)
for feature in db.all_features():
biotype = biotype_lookup(feature)
if pred(biotype):
return True
return False | [
"def",
"is_cpat_compatible",
"(",
"gtf",
")",
":",
"if",
"not",
"gtf",
":",
"return",
"False",
"db",
"=",
"get_gtf_db",
"(",
"gtf",
")",
"pred",
"=",
"lambda",
"biotype",
":",
"biotype",
"and",
"biotype",
"==",
"\"protein_coding\"",
"biotype_lookup",
"=",
... | CPAT needs some transcripts annotated with protein coding status to work
properly | [
"CPAT",
"needs",
"some",
"transcripts",
"annotated",
"with",
"protein",
"coding",
"status",
"to",
"work",
"properly"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/gtf.py#L403-L420 |
224,340 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | organize | def organize(dirs, config, run_info_yaml, sample_names=None, is_cwl=False,
integrations=None):
"""Organize run information from a passed YAML file or the Galaxy API.
Creates the high level structure used for subsequent processing.
sample_names is a list of samples to include from the overall file, for cases
where we are running multiple pipelines from the same configuration file.
"""
from bcbio.pipeline import qcsummary
if integrations is None: integrations = {}
logger.info("Using input YAML configuration: %s" % run_info_yaml)
assert run_info_yaml and os.path.exists(run_info_yaml), \
"Did not find input sample YAML file: %s" % run_info_yaml
run_details = _run_info_from_yaml(dirs, run_info_yaml, config, sample_names,
is_cwl=is_cwl, integrations=integrations)
remote_retriever = None
for iname, retriever in integrations.items():
if iname in config:
run_details = retriever.add_remotes(run_details, config[iname])
remote_retriever = retriever
out = []
for item in run_details:
item["dirs"] = dirs
if "name" not in item:
item["name"] = ["", item["description"]]
elif isinstance(item["name"], six.string_types):
description = "%s-%s" % (item["name"], clean_name(item["description"]))
item["name"] = [item["name"], description]
item["description"] = description
# add algorithm details to configuration, avoid double specification
item["resources"] = _add_remote_resources(item["resources"])
item["config"] = config_utils.update_w_custom(config, item)
item.pop("algorithm", None)
item = add_reference_resources(item, remote_retriever)
item["config"]["algorithm"]["qc"] = qcsummary.get_qc_tools(item)
item["config"]["algorithm"]["vcfanno"] = vcfanno.find_annotations(item, remote_retriever)
# Create temporary directories and make absolute, expanding environmental variables
tmp_dir = tz.get_in(["config", "resources", "tmp", "dir"], item)
if tmp_dir:
# if no environmental variables, make and normalize the directory
# otherwise we normalize later in distributed.transaction:
if os.path.expandvars(tmp_dir) == tmp_dir:
tmp_dir = utils.safe_makedir(os.path.expandvars(tmp_dir))
tmp_dir = genome.abs_file_paths(tmp_dir, do_download=not integrations)
item["config"]["resources"]["tmp"]["dir"] = tmp_dir
out.append(item)
out = _add_provenance(out, dirs, config, not is_cwl)
return out | python | def organize(dirs, config, run_info_yaml, sample_names=None, is_cwl=False,
integrations=None):
"""Organize run information from a passed YAML file or the Galaxy API.
Creates the high level structure used for subsequent processing.
sample_names is a list of samples to include from the overall file, for cases
where we are running multiple pipelines from the same configuration file.
"""
from bcbio.pipeline import qcsummary
if integrations is None: integrations = {}
logger.info("Using input YAML configuration: %s" % run_info_yaml)
assert run_info_yaml and os.path.exists(run_info_yaml), \
"Did not find input sample YAML file: %s" % run_info_yaml
run_details = _run_info_from_yaml(dirs, run_info_yaml, config, sample_names,
is_cwl=is_cwl, integrations=integrations)
remote_retriever = None
for iname, retriever in integrations.items():
if iname in config:
run_details = retriever.add_remotes(run_details, config[iname])
remote_retriever = retriever
out = []
for item in run_details:
item["dirs"] = dirs
if "name" not in item:
item["name"] = ["", item["description"]]
elif isinstance(item["name"], six.string_types):
description = "%s-%s" % (item["name"], clean_name(item["description"]))
item["name"] = [item["name"], description]
item["description"] = description
# add algorithm details to configuration, avoid double specification
item["resources"] = _add_remote_resources(item["resources"])
item["config"] = config_utils.update_w_custom(config, item)
item.pop("algorithm", None)
item = add_reference_resources(item, remote_retriever)
item["config"]["algorithm"]["qc"] = qcsummary.get_qc_tools(item)
item["config"]["algorithm"]["vcfanno"] = vcfanno.find_annotations(item, remote_retriever)
# Create temporary directories and make absolute, expanding environmental variables
tmp_dir = tz.get_in(["config", "resources", "tmp", "dir"], item)
if tmp_dir:
# if no environmental variables, make and normalize the directory
# otherwise we normalize later in distributed.transaction:
if os.path.expandvars(tmp_dir) == tmp_dir:
tmp_dir = utils.safe_makedir(os.path.expandvars(tmp_dir))
tmp_dir = genome.abs_file_paths(tmp_dir, do_download=not integrations)
item["config"]["resources"]["tmp"]["dir"] = tmp_dir
out.append(item)
out = _add_provenance(out, dirs, config, not is_cwl)
return out | [
"def",
"organize",
"(",
"dirs",
",",
"config",
",",
"run_info_yaml",
",",
"sample_names",
"=",
"None",
",",
"is_cwl",
"=",
"False",
",",
"integrations",
"=",
"None",
")",
":",
"from",
"bcbio",
".",
"pipeline",
"import",
"qcsummary",
"if",
"integrations",
"... | Organize run information from a passed YAML file or the Galaxy API.
Creates the high level structure used for subsequent processing.
sample_names is a list of samples to include from the overall file, for cases
where we are running multiple pipelines from the same configuration file. | [
"Organize",
"run",
"information",
"from",
"a",
"passed",
"YAML",
"file",
"or",
"the",
"Galaxy",
"API",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L46-L94 |
224,341 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _get_full_paths | def _get_full_paths(fastq_dir, config, config_file):
"""Retrieve full paths for directories in the case of relative locations.
"""
if fastq_dir:
fastq_dir = utils.add_full_path(fastq_dir)
config_dir = utils.add_full_path(os.path.dirname(config_file))
galaxy_config_file = utils.add_full_path(config.get("galaxy_config", "universe_wsgi.ini"),
config_dir)
return fastq_dir, os.path.dirname(galaxy_config_file), config_dir | python | def _get_full_paths(fastq_dir, config, config_file):
"""Retrieve full paths for directories in the case of relative locations.
"""
if fastq_dir:
fastq_dir = utils.add_full_path(fastq_dir)
config_dir = utils.add_full_path(os.path.dirname(config_file))
galaxy_config_file = utils.add_full_path(config.get("galaxy_config", "universe_wsgi.ini"),
config_dir)
return fastq_dir, os.path.dirname(galaxy_config_file), config_dir | [
"def",
"_get_full_paths",
"(",
"fastq_dir",
",",
"config",
",",
"config_file",
")",
":",
"if",
"fastq_dir",
":",
"fastq_dir",
"=",
"utils",
".",
"add_full_path",
"(",
"fastq_dir",
")",
"config_dir",
"=",
"utils",
".",
"add_full_path",
"(",
"os",
".",
"path",... | Retrieve full paths for directories in the case of relative locations. | [
"Retrieve",
"full",
"paths",
"for",
"directories",
"in",
"the",
"case",
"of",
"relative",
"locations",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L130-L138 |
224,342 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | add_reference_resources | def add_reference_resources(data, remote_retriever=None):
"""Add genome reference information to the item to process.
"""
aligner = data["config"]["algorithm"].get("aligner", None)
if remote_retriever:
data["reference"] = remote_retriever.get_refs(data["genome_build"],
alignment.get_aligner_with_aliases(aligner, data),
data["config"])
else:
data["reference"] = genome.get_refs(data["genome_build"], alignment.get_aligner_with_aliases(aligner, data),
data["dirs"]["galaxy"], data)
_check_ref_files(data["reference"], data)
# back compatible `sam_ref` target
data["sam_ref"] = utils.get_in(data, ("reference", "fasta", "base"))
ref_loc = utils.get_in(data, ("config", "resources", "species", "dir"),
utils.get_in(data, ("reference", "fasta", "base")))
if remote_retriever:
data = remote_retriever.get_resources(data["genome_build"], ref_loc, data)
else:
data["genome_resources"] = genome.get_resources(data["genome_build"], ref_loc, data)
data["genome_resources"] = genome.add_required_resources(data["genome_resources"])
if effects.get_type(data) == "snpeff" and "snpeff" not in data["reference"]:
data["reference"]["snpeff"] = effects.get_snpeff_files(data)
if "genome_context" not in data["reference"]:
data["reference"]["genome_context"] = annotation.get_context_files(data)
if "viral" not in data["reference"]:
data["reference"]["viral"] = viral.get_files(data)
if not data["reference"]["viral"]:
data["reference"]["viral"] = None
if "versions" not in data["reference"]:
data["reference"]["versions"] = _get_data_versions(data)
data = _fill_validation_targets(data)
data = _fill_prioritization_targets(data)
data = _fill_capture_regions(data)
# Re-enable when we have ability to re-define gemini configuration directory
if False:
data["reference"]["gemini"] = population.get_gemini_files(data)
return data | python | def add_reference_resources(data, remote_retriever=None):
"""Add genome reference information to the item to process.
"""
aligner = data["config"]["algorithm"].get("aligner", None)
if remote_retriever:
data["reference"] = remote_retriever.get_refs(data["genome_build"],
alignment.get_aligner_with_aliases(aligner, data),
data["config"])
else:
data["reference"] = genome.get_refs(data["genome_build"], alignment.get_aligner_with_aliases(aligner, data),
data["dirs"]["galaxy"], data)
_check_ref_files(data["reference"], data)
# back compatible `sam_ref` target
data["sam_ref"] = utils.get_in(data, ("reference", "fasta", "base"))
ref_loc = utils.get_in(data, ("config", "resources", "species", "dir"),
utils.get_in(data, ("reference", "fasta", "base")))
if remote_retriever:
data = remote_retriever.get_resources(data["genome_build"], ref_loc, data)
else:
data["genome_resources"] = genome.get_resources(data["genome_build"], ref_loc, data)
data["genome_resources"] = genome.add_required_resources(data["genome_resources"])
if effects.get_type(data) == "snpeff" and "snpeff" not in data["reference"]:
data["reference"]["snpeff"] = effects.get_snpeff_files(data)
if "genome_context" not in data["reference"]:
data["reference"]["genome_context"] = annotation.get_context_files(data)
if "viral" not in data["reference"]:
data["reference"]["viral"] = viral.get_files(data)
if not data["reference"]["viral"]:
data["reference"]["viral"] = None
if "versions" not in data["reference"]:
data["reference"]["versions"] = _get_data_versions(data)
data = _fill_validation_targets(data)
data = _fill_prioritization_targets(data)
data = _fill_capture_regions(data)
# Re-enable when we have ability to re-define gemini configuration directory
if False:
data["reference"]["gemini"] = population.get_gemini_files(data)
return data | [
"def",
"add_reference_resources",
"(",
"data",
",",
"remote_retriever",
"=",
"None",
")",
":",
"aligner",
"=",
"data",
"[",
"\"config\"",
"]",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\"aligner\"",
",",
"None",
")",
"if",
"remote_retriever",
":",
"data",... | Add genome reference information to the item to process. | [
"Add",
"genome",
"reference",
"information",
"to",
"the",
"item",
"to",
"process",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L166-L204 |
224,343 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _get_data_versions | def _get_data_versions(data):
"""Retrieve CSV file with version information for reference data.
"""
genome_dir = install.get_genome_dir(data["genome_build"], data["dirs"].get("galaxy"), data)
if genome_dir:
version_file = os.path.join(genome_dir, "versions.csv")
if version_file and os.path.exists(version_file):
return version_file
return None | python | def _get_data_versions(data):
"""Retrieve CSV file with version information for reference data.
"""
genome_dir = install.get_genome_dir(data["genome_build"], data["dirs"].get("galaxy"), data)
if genome_dir:
version_file = os.path.join(genome_dir, "versions.csv")
if version_file and os.path.exists(version_file):
return version_file
return None | [
"def",
"_get_data_versions",
"(",
"data",
")",
":",
"genome_dir",
"=",
"install",
".",
"get_genome_dir",
"(",
"data",
"[",
"\"genome_build\"",
"]",
",",
"data",
"[",
"\"dirs\"",
"]",
".",
"get",
"(",
"\"galaxy\"",
")",
",",
"data",
")",
"if",
"genome_dir",... | Retrieve CSV file with version information for reference data. | [
"Retrieve",
"CSV",
"file",
"with",
"version",
"information",
"for",
"reference",
"data",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L206-L214 |
224,344 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _fill_validation_targets | def _fill_validation_targets(data):
"""Fill validation targets pointing to globally installed truth sets.
"""
ref_file = dd.get_ref_file(data)
sv_truth = tz.get_in(["config", "algorithm", "svvalidate"], data, {})
sv_targets = (zip(itertools.repeat("svvalidate"), sv_truth.keys()) if isinstance(sv_truth, dict)
else [["svvalidate"]])
for vtarget in [list(xs) for xs in [["validate"], ["validate_regions"], ["variant_regions"]] + list(sv_targets)]:
val = tz.get_in(["config", "algorithm"] + vtarget, data)
if val and not os.path.exists(val) and not objectstore.is_remote(val):
installed_val = os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir, "validation", val))
if os.path.exists(installed_val):
data = tz.update_in(data, ["config", "algorithm"] + vtarget, lambda x: installed_val)
else:
raise ValueError("Configuration problem. Validation file not found for %s: %s" %
(vtarget, val))
return data | python | def _fill_validation_targets(data):
"""Fill validation targets pointing to globally installed truth sets.
"""
ref_file = dd.get_ref_file(data)
sv_truth = tz.get_in(["config", "algorithm", "svvalidate"], data, {})
sv_targets = (zip(itertools.repeat("svvalidate"), sv_truth.keys()) if isinstance(sv_truth, dict)
else [["svvalidate"]])
for vtarget in [list(xs) for xs in [["validate"], ["validate_regions"], ["variant_regions"]] + list(sv_targets)]:
val = tz.get_in(["config", "algorithm"] + vtarget, data)
if val and not os.path.exists(val) and not objectstore.is_remote(val):
installed_val = os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir, "validation", val))
if os.path.exists(installed_val):
data = tz.update_in(data, ["config", "algorithm"] + vtarget, lambda x: installed_val)
else:
raise ValueError("Configuration problem. Validation file not found for %s: %s" %
(vtarget, val))
return data | [
"def",
"_fill_validation_targets",
"(",
"data",
")",
":",
"ref_file",
"=",
"dd",
".",
"get_ref_file",
"(",
"data",
")",
"sv_truth",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"config\"",
",",
"\"algorithm\"",
",",
"\"svvalidate\"",
"]",
",",
"data",
",",
"{",
... | Fill validation targets pointing to globally installed truth sets. | [
"Fill",
"validation",
"targets",
"pointing",
"to",
"globally",
"installed",
"truth",
"sets",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L236-L252 |
224,345 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _fill_capture_regions | def _fill_capture_regions(data):
"""Fill short-hand specification of BED capture regions.
"""
special_targets = {"sv_regions": ("exons", "transcripts")}
ref_file = dd.get_ref_file(data)
for target in ["variant_regions", "sv_regions", "coverage"]:
val = tz.get_in(["config", "algorithm", target], data)
if val and not os.path.exists(val) and not objectstore.is_remote(val):
installed_vals = []
# Check prioritize directory
for ext in [".bed", ".bed.gz"]:
installed_vals += glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
"coverage", val + ext)))
if len(installed_vals) == 0:
if target not in special_targets or not val.startswith(special_targets[target]):
raise ValueError("Configuration problem. BED file not found for %s: %s" %
(target, val))
else:
assert len(installed_vals) == 1, installed_vals
data = tz.update_in(data, ["config", "algorithm", target], lambda x: installed_vals[0])
return data | python | def _fill_capture_regions(data):
"""Fill short-hand specification of BED capture regions.
"""
special_targets = {"sv_regions": ("exons", "transcripts")}
ref_file = dd.get_ref_file(data)
for target in ["variant_regions", "sv_regions", "coverage"]:
val = tz.get_in(["config", "algorithm", target], data)
if val and not os.path.exists(val) and not objectstore.is_remote(val):
installed_vals = []
# Check prioritize directory
for ext in [".bed", ".bed.gz"]:
installed_vals += glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
"coverage", val + ext)))
if len(installed_vals) == 0:
if target not in special_targets or not val.startswith(special_targets[target]):
raise ValueError("Configuration problem. BED file not found for %s: %s" %
(target, val))
else:
assert len(installed_vals) == 1, installed_vals
data = tz.update_in(data, ["config", "algorithm", target], lambda x: installed_vals[0])
return data | [
"def",
"_fill_capture_regions",
"(",
"data",
")",
":",
"special_targets",
"=",
"{",
"\"sv_regions\"",
":",
"(",
"\"exons\"",
",",
"\"transcripts\"",
")",
"}",
"ref_file",
"=",
"dd",
".",
"get_ref_file",
"(",
"data",
")",
"for",
"target",
"in",
"[",
"\"varian... | Fill short-hand specification of BED capture regions. | [
"Fill",
"short",
"-",
"hand",
"specification",
"of",
"BED",
"capture",
"regions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L254-L274 |
224,346 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _fill_prioritization_targets | def _fill_prioritization_targets(data):
"""Fill in globally installed files for prioritization.
"""
ref_file = dd.get_ref_file(data)
for target in ["svprioritize", "coverage"]:
val = tz.get_in(["config", "algorithm", target], data)
if val and not os.path.exists(val) and not objectstore.is_remote(val):
installed_vals = []
# Check prioritize directory
for ext in [".bed", ".bed.gz"]:
installed_vals += glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
"coverage", "prioritize",
val + "*%s" % ext)))
# Check sv-annotation directory for prioritize gene name lists
if target == "svprioritize":
simple_sv_bin = utils.which("simple_sv_annotation.py")
if simple_sv_bin:
installed_vals += glob.glob(os.path.join(os.path.dirname(os.path.realpath(simple_sv_bin)),
"%s*" % os.path.basename(val)))
if len(installed_vals) == 0:
# some targets can be filled in later
if target not in set(["coverage"]):
raise ValueError("Configuration problem. BED file not found for %s: %s" %
(target, val))
else:
installed_val = val
elif len(installed_vals) == 1:
installed_val = installed_vals[0]
else:
# check for partial matches
installed_val = None
for v in installed_vals:
if v.endswith(val + ".bed.gz") or v.endswith(val + ".bed"):
installed_val = v
break
# handle date-stamped inputs
if not installed_val:
installed_val = sorted(installed_vals, reverse=True)[0]
data = tz.update_in(data, ["config", "algorithm", target], lambda x: installed_val)
return data | python | def _fill_prioritization_targets(data):
"""Fill in globally installed files for prioritization.
"""
ref_file = dd.get_ref_file(data)
for target in ["svprioritize", "coverage"]:
val = tz.get_in(["config", "algorithm", target], data)
if val and not os.path.exists(val) and not objectstore.is_remote(val):
installed_vals = []
# Check prioritize directory
for ext in [".bed", ".bed.gz"]:
installed_vals += glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
"coverage", "prioritize",
val + "*%s" % ext)))
# Check sv-annotation directory for prioritize gene name lists
if target == "svprioritize":
simple_sv_bin = utils.which("simple_sv_annotation.py")
if simple_sv_bin:
installed_vals += glob.glob(os.path.join(os.path.dirname(os.path.realpath(simple_sv_bin)),
"%s*" % os.path.basename(val)))
if len(installed_vals) == 0:
# some targets can be filled in later
if target not in set(["coverage"]):
raise ValueError("Configuration problem. BED file not found for %s: %s" %
(target, val))
else:
installed_val = val
elif len(installed_vals) == 1:
installed_val = installed_vals[0]
else:
# check for partial matches
installed_val = None
for v in installed_vals:
if v.endswith(val + ".bed.gz") or v.endswith(val + ".bed"):
installed_val = v
break
# handle date-stamped inputs
if not installed_val:
installed_val = sorted(installed_vals, reverse=True)[0]
data = tz.update_in(data, ["config", "algorithm", target], lambda x: installed_val)
return data | [
"def",
"_fill_prioritization_targets",
"(",
"data",
")",
":",
"ref_file",
"=",
"dd",
".",
"get_ref_file",
"(",
"data",
")",
"for",
"target",
"in",
"[",
"\"svprioritize\"",
",",
"\"coverage\"",
"]",
":",
"val",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"config\... | Fill in globally installed files for prioritization. | [
"Fill",
"in",
"globally",
"installed",
"files",
"for",
"prioritization",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L276-L315 |
224,347 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _clean_algorithm | def _clean_algorithm(data):
"""Clean algorithm keys, handling items that can be specified as lists or single items.
"""
# convert single items to lists
for key in ["variantcaller", "jointcaller", "svcaller"]:
val = tz.get_in(["algorithm", key], data)
if val:
if not isinstance(val, (list, tuple)) and isinstance(val, six.string_types):
val = [val]
# check for cases like [false] or [None]
if isinstance(val, (list, tuple)):
if len(val) == 1 and not val[0] or (isinstance(val[0], six.string_types)
and val[0].lower() in ["none", "false"]):
val = False
data["algorithm"][key] = val
return data | python | def _clean_algorithm(data):
"""Clean algorithm keys, handling items that can be specified as lists or single items.
"""
# convert single items to lists
for key in ["variantcaller", "jointcaller", "svcaller"]:
val = tz.get_in(["algorithm", key], data)
if val:
if not isinstance(val, (list, tuple)) and isinstance(val, six.string_types):
val = [val]
# check for cases like [false] or [None]
if isinstance(val, (list, tuple)):
if len(val) == 1 and not val[0] or (isinstance(val[0], six.string_types)
and val[0].lower() in ["none", "false"]):
val = False
data["algorithm"][key] = val
return data | [
"def",
"_clean_algorithm",
"(",
"data",
")",
":",
"# convert single items to lists",
"for",
"key",
"in",
"[",
"\"variantcaller\"",
",",
"\"jointcaller\"",
",",
"\"svcaller\"",
"]",
":",
"val",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"algorithm\"",
",",
"key",
"]... | Clean algorithm keys, handling items that can be specified as lists or single items. | [
"Clean",
"algorithm",
"keys",
"handling",
"items",
"that",
"can",
"be",
"specified",
"as",
"lists",
"or",
"single",
"items",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L336-L351 |
224,348 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _organize_tools_on | def _organize_tools_on(data, is_cwl):
"""Ensure tools_on inputs match items specified elsewhere.
"""
# want tools_on: [gvcf] if joint calling specified in CWL
if is_cwl:
if tz.get_in(["algorithm", "jointcaller"], data):
val = tz.get_in(["algorithm", "tools_on"], data)
if not val:
val = []
if not isinstance(val, (list, tuple)):
val = [val]
if "gvcf" not in val:
val.append("gvcf")
data["algorithm"]["tools_on"] = val
return data | python | def _organize_tools_on(data, is_cwl):
"""Ensure tools_on inputs match items specified elsewhere.
"""
# want tools_on: [gvcf] if joint calling specified in CWL
if is_cwl:
if tz.get_in(["algorithm", "jointcaller"], data):
val = tz.get_in(["algorithm", "tools_on"], data)
if not val:
val = []
if not isinstance(val, (list, tuple)):
val = [val]
if "gvcf" not in val:
val.append("gvcf")
data["algorithm"]["tools_on"] = val
return data | [
"def",
"_organize_tools_on",
"(",
"data",
",",
"is_cwl",
")",
":",
"# want tools_on: [gvcf] if joint calling specified in CWL",
"if",
"is_cwl",
":",
"if",
"tz",
".",
"get_in",
"(",
"[",
"\"algorithm\"",
",",
"\"jointcaller\"",
"]",
",",
"data",
")",
":",
"val",
... | Ensure tools_on inputs match items specified elsewhere. | [
"Ensure",
"tools_on",
"inputs",
"match",
"items",
"specified",
"elsewhere",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L353-L367 |
224,349 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _clean_background | def _clean_background(data):
"""Clean up background specification, remaining back compatible.
"""
allowed_keys = set(["variant", "cnv_reference"])
val = tz.get_in(["algorithm", "background"], data)
errors = []
if val:
out = {}
# old style specification, single string for variant
if isinstance(val, six.string_types):
out["variant"] = _file_to_abs(val, [os.getcwd()])
elif isinstance(val, dict):
for k, v in val.items():
if k in allowed_keys:
if isinstance(v, six.string_types):
out[k] = _file_to_abs(v, [os.getcwd()])
else:
assert isinstance(v, dict)
for ik, iv in v.items():
v[ik] = _file_to_abs(iv, [os.getcwd()])
out[k] = v
else:
errors.append("Unexpected key: %s" % k)
else:
errors.append("Unexpected input: %s" % val)
if errors:
raise ValueError("Problematic algorithm background specification for %s:\n %s" %
(data["description"], "\n".join(errors)))
out["cnv_reference"] = structural.standardize_cnv_reference({"config": data,
"description": data["description"]})
data["algorithm"]["background"] = out
return data | python | def _clean_background(data):
"""Clean up background specification, remaining back compatible.
"""
allowed_keys = set(["variant", "cnv_reference"])
val = tz.get_in(["algorithm", "background"], data)
errors = []
if val:
out = {}
# old style specification, single string for variant
if isinstance(val, six.string_types):
out["variant"] = _file_to_abs(val, [os.getcwd()])
elif isinstance(val, dict):
for k, v in val.items():
if k in allowed_keys:
if isinstance(v, six.string_types):
out[k] = _file_to_abs(v, [os.getcwd()])
else:
assert isinstance(v, dict)
for ik, iv in v.items():
v[ik] = _file_to_abs(iv, [os.getcwd()])
out[k] = v
else:
errors.append("Unexpected key: %s" % k)
else:
errors.append("Unexpected input: %s" % val)
if errors:
raise ValueError("Problematic algorithm background specification for %s:\n %s" %
(data["description"], "\n".join(errors)))
out["cnv_reference"] = structural.standardize_cnv_reference({"config": data,
"description": data["description"]})
data["algorithm"]["background"] = out
return data | [
"def",
"_clean_background",
"(",
"data",
")",
":",
"allowed_keys",
"=",
"set",
"(",
"[",
"\"variant\"",
",",
"\"cnv_reference\"",
"]",
")",
"val",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"algorithm\"",
",",
"\"background\"",
"]",
",",
"data",
")",
"errors",
... | Clean up background specification, remaining back compatible. | [
"Clean",
"up",
"background",
"specification",
"remaining",
"back",
"compatible",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L369-L400 |
224,350 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _clean_characters | def _clean_characters(x):
"""Clean problem characters in sample lane or descriptions.
"""
if not isinstance(x, six.string_types):
x = str(x)
else:
if not all(ord(char) < 128 for char in x):
msg = "Found unicode character in input YAML (%s)" % (x)
raise ValueError(repr(msg))
for problem in [" ", ".", "/", "\\", "[", "]", "&", ";", "#", "+", ":", ")", "("]:
x = x.replace(problem, "_")
return x | python | def _clean_characters(x):
"""Clean problem characters in sample lane or descriptions.
"""
if not isinstance(x, six.string_types):
x = str(x)
else:
if not all(ord(char) < 128 for char in x):
msg = "Found unicode character in input YAML (%s)" % (x)
raise ValueError(repr(msg))
for problem in [" ", ".", "/", "\\", "[", "]", "&", ";", "#", "+", ":", ")", "("]:
x = x.replace(problem, "_")
return x | [
"def",
"_clean_characters",
"(",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_types",
")",
":",
"x",
"=",
"str",
"(",
"x",
")",
"else",
":",
"if",
"not",
"all",
"(",
"ord",
"(",
"char",
")",
"<",
"128",
"for",
"c... | Clean problem characters in sample lane or descriptions. | [
"Clean",
"problem",
"characters",
"in",
"sample",
"lane",
"or",
"descriptions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L402-L413 |
224,351 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | prep_rg_names | def prep_rg_names(item, config, fc_name, fc_date):
"""Generate read group names from item inputs.
"""
if fc_name and fc_date:
lane_name = "%s_%s_%s" % (item["lane"], fc_date, fc_name)
else:
lane_name = item["description"]
return {"rg": item["description"],
"sample": item["description"],
"lane": lane_name,
"pl": (tz.get_in(["algorithm", "platform"], item)
or tz.get_in(["algorithm", "platform"], item, "illumina")).lower(),
"lb": tz.get_in(["metadata", "library"], item),
"pu": tz.get_in(["metadata", "platform_unit"], item) or lane_name} | python | def prep_rg_names(item, config, fc_name, fc_date):
"""Generate read group names from item inputs.
"""
if fc_name and fc_date:
lane_name = "%s_%s_%s" % (item["lane"], fc_date, fc_name)
else:
lane_name = item["description"]
return {"rg": item["description"],
"sample": item["description"],
"lane": lane_name,
"pl": (tz.get_in(["algorithm", "platform"], item)
or tz.get_in(["algorithm", "platform"], item, "illumina")).lower(),
"lb": tz.get_in(["metadata", "library"], item),
"pu": tz.get_in(["metadata", "platform_unit"], item) or lane_name} | [
"def",
"prep_rg_names",
"(",
"item",
",",
"config",
",",
"fc_name",
",",
"fc_date",
")",
":",
"if",
"fc_name",
"and",
"fc_date",
":",
"lane_name",
"=",
"\"%s_%s_%s\"",
"%",
"(",
"item",
"[",
"\"lane\"",
"]",
",",
"fc_date",
",",
"fc_name",
")",
"else",
... | Generate read group names from item inputs. | [
"Generate",
"read",
"group",
"names",
"from",
"item",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L415-L428 |
224,352 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_for_duplicates | def _check_for_duplicates(xs, attr, check_fn=None):
"""Identify and raise errors on duplicate items.
"""
dups = []
for key, vals in itertools.groupby(x[attr] for x in xs):
if len(list(vals)) > 1:
dups.append(key)
if len(dups) > 0:
psamples = []
for x in xs:
if x[attr] in dups:
psamples.append(x)
# option to skip problem based on custom input function.
if check_fn and check_fn(psamples):
return
descrs = [x["description"] for x in psamples]
raise ValueError("Duplicate '%s' found in input sample configuration.\n"
"Required to be unique for a project: %s\n"
"Problem found in these samples: %s" % (attr, dups, descrs)) | python | def _check_for_duplicates(xs, attr, check_fn=None):
"""Identify and raise errors on duplicate items.
"""
dups = []
for key, vals in itertools.groupby(x[attr] for x in xs):
if len(list(vals)) > 1:
dups.append(key)
if len(dups) > 0:
psamples = []
for x in xs:
if x[attr] in dups:
psamples.append(x)
# option to skip problem based on custom input function.
if check_fn and check_fn(psamples):
return
descrs = [x["description"] for x in psamples]
raise ValueError("Duplicate '%s' found in input sample configuration.\n"
"Required to be unique for a project: %s\n"
"Problem found in these samples: %s" % (attr, dups, descrs)) | [
"def",
"_check_for_duplicates",
"(",
"xs",
",",
"attr",
",",
"check_fn",
"=",
"None",
")",
":",
"dups",
"=",
"[",
"]",
"for",
"key",
",",
"vals",
"in",
"itertools",
".",
"groupby",
"(",
"x",
"[",
"attr",
"]",
"for",
"x",
"in",
"xs",
")",
":",
"if... | Identify and raise errors on duplicate items. | [
"Identify",
"and",
"raise",
"errors",
"on",
"duplicate",
"items",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L432-L450 |
224,353 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_for_batch_clashes | def _check_for_batch_clashes(xs):
"""Check that batch names do not overlap with sample names.
"""
names = set([x["description"] for x in xs])
dups = set([])
for x in xs:
batches = tz.get_in(("metadata", "batch"), x)
if batches:
if not isinstance(batches, (list, tuple)):
batches = [batches]
for batch in batches:
if batch in names:
dups.add(batch)
if len(dups) > 0:
raise ValueError("Batch names must be unique from sample descriptions.\n"
"Clashing batch names: %s" % sorted(list(dups))) | python | def _check_for_batch_clashes(xs):
"""Check that batch names do not overlap with sample names.
"""
names = set([x["description"] for x in xs])
dups = set([])
for x in xs:
batches = tz.get_in(("metadata", "batch"), x)
if batches:
if not isinstance(batches, (list, tuple)):
batches = [batches]
for batch in batches:
if batch in names:
dups.add(batch)
if len(dups) > 0:
raise ValueError("Batch names must be unique from sample descriptions.\n"
"Clashing batch names: %s" % sorted(list(dups))) | [
"def",
"_check_for_batch_clashes",
"(",
"xs",
")",
":",
"names",
"=",
"set",
"(",
"[",
"x",
"[",
"\"description\"",
"]",
"for",
"x",
"in",
"xs",
"]",
")",
"dups",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"x",
"in",
"xs",
":",
"batches",
"=",
"tz",
... | Check that batch names do not overlap with sample names. | [
"Check",
"that",
"batch",
"names",
"do",
"not",
"overlap",
"with",
"sample",
"names",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L452-L467 |
224,354 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_for_problem_somatic_batches | def _check_for_problem_somatic_batches(items, config):
"""Identify problem batch setups for somatic calling.
We do not support multiple tumors in a single batch and VarDict(Java) does not
handle pooled calling, only tumor/normal.
"""
to_check = []
for data in items:
data = copy.deepcopy(data)
data["config"] = config_utils.update_w_custom(config, data)
to_check.append(data)
data_by_batches = collections.defaultdict(list)
for data in to_check:
batches = dd.get_batches(data)
if batches:
for batch in batches:
data_by_batches[batch].append(data)
for batch, items in data_by_batches.items():
if vcfutils.get_paired(items):
vcfutils.check_paired_problems(items)
elif len(items) > 1:
vcs = vcfutils.get_somatic_variantcallers(items)
if "vardict" in vcs:
raise ValueError("VarDict does not support pooled non-tumor/normal calling, in batch %s: %s"
% (batch, [dd.get_sample_name(data) for data in items]))
elif "mutect" in vcs or "mutect2" in vcs:
raise ValueError("MuTect and MuTect2 require a 'phenotype: tumor' sample for calling, "
"in batch %s: %s"
% (batch, [dd.get_sample_name(data) for data in items])) | python | def _check_for_problem_somatic_batches(items, config):
"""Identify problem batch setups for somatic calling.
We do not support multiple tumors in a single batch and VarDict(Java) does not
handle pooled calling, only tumor/normal.
"""
to_check = []
for data in items:
data = copy.deepcopy(data)
data["config"] = config_utils.update_w_custom(config, data)
to_check.append(data)
data_by_batches = collections.defaultdict(list)
for data in to_check:
batches = dd.get_batches(data)
if batches:
for batch in batches:
data_by_batches[batch].append(data)
for batch, items in data_by_batches.items():
if vcfutils.get_paired(items):
vcfutils.check_paired_problems(items)
elif len(items) > 1:
vcs = vcfutils.get_somatic_variantcallers(items)
if "vardict" in vcs:
raise ValueError("VarDict does not support pooled non-tumor/normal calling, in batch %s: %s"
% (batch, [dd.get_sample_name(data) for data in items]))
elif "mutect" in vcs or "mutect2" in vcs:
raise ValueError("MuTect and MuTect2 require a 'phenotype: tumor' sample for calling, "
"in batch %s: %s"
% (batch, [dd.get_sample_name(data) for data in items])) | [
"def",
"_check_for_problem_somatic_batches",
"(",
"items",
",",
"config",
")",
":",
"to_check",
"=",
"[",
"]",
"for",
"data",
"in",
"items",
":",
"data",
"=",
"copy",
".",
"deepcopy",
"(",
"data",
")",
"data",
"[",
"\"config\"",
"]",
"=",
"config_utils",
... | Identify problem batch setups for somatic calling.
We do not support multiple tumors in a single batch and VarDict(Java) does not
handle pooled calling, only tumor/normal. | [
"Identify",
"problem",
"batch",
"setups",
"for",
"somatic",
"calling",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L469-L497 |
224,355 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_for_misplaced | def _check_for_misplaced(xs, subkey, other_keys):
"""Ensure configuration keys are not incorrectly nested under other keys.
"""
problems = []
for x in xs:
check_dict = x.get(subkey, {})
for to_check in other_keys:
if to_check in check_dict:
problems.append((x["description"], to_check, subkey))
if len(problems) > 0:
raise ValueError("\n".join(["Incorrectly nested keys found in sample YAML. These should be top level:",
" sample | key name | nested under ",
"----------------+-----------------+----------------"] +
["% 15s | % 15s | % 15s" % (a, b, c) for (a, b, c) in problems])) | python | def _check_for_misplaced(xs, subkey, other_keys):
"""Ensure configuration keys are not incorrectly nested under other keys.
"""
problems = []
for x in xs:
check_dict = x.get(subkey, {})
for to_check in other_keys:
if to_check in check_dict:
problems.append((x["description"], to_check, subkey))
if len(problems) > 0:
raise ValueError("\n".join(["Incorrectly nested keys found in sample YAML. These should be top level:",
" sample | key name | nested under ",
"----------------+-----------------+----------------"] +
["% 15s | % 15s | % 15s" % (a, b, c) for (a, b, c) in problems])) | [
"def",
"_check_for_misplaced",
"(",
"xs",
",",
"subkey",
",",
"other_keys",
")",
":",
"problems",
"=",
"[",
"]",
"for",
"x",
"in",
"xs",
":",
"check_dict",
"=",
"x",
".",
"get",
"(",
"subkey",
",",
"{",
"}",
")",
"for",
"to_check",
"in",
"other_keys"... | Ensure configuration keys are not incorrectly nested under other keys. | [
"Ensure",
"configuration",
"keys",
"are",
"not",
"incorrectly",
"nested",
"under",
"other",
"keys",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L499-L512 |
224,356 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_for_degenerate_interesting_groups | def _check_for_degenerate_interesting_groups(items):
""" Make sure interesting_groups specify existing metadata and that
the interesting_group is not all of the same for all of the samples
"""
igkey = ("algorithm", "bcbiornaseq", "interesting_groups")
interesting_groups = tz.get_in(igkey, items[0], [])
if isinstance(interesting_groups, str):
interesting_groups = [interesting_groups]
for group in interesting_groups:
values = [tz.get_in(("metadata", group), x, None) for x in items]
if all(x is None for x in values):
raise ValueError("group %s is labelled as an interesting group, "
"but does not appear in the metadata." % group)
if len(list(tz.unique(values))) == 1:
raise ValueError("group %s is marked as an interesting group, "
"but all samples have the same value." % group) | python | def _check_for_degenerate_interesting_groups(items):
""" Make sure interesting_groups specify existing metadata and that
the interesting_group is not all of the same for all of the samples
"""
igkey = ("algorithm", "bcbiornaseq", "interesting_groups")
interesting_groups = tz.get_in(igkey, items[0], [])
if isinstance(interesting_groups, str):
interesting_groups = [interesting_groups]
for group in interesting_groups:
values = [tz.get_in(("metadata", group), x, None) for x in items]
if all(x is None for x in values):
raise ValueError("group %s is labelled as an interesting group, "
"but does not appear in the metadata." % group)
if len(list(tz.unique(values))) == 1:
raise ValueError("group %s is marked as an interesting group, "
"but all samples have the same value." % group) | [
"def",
"_check_for_degenerate_interesting_groups",
"(",
"items",
")",
":",
"igkey",
"=",
"(",
"\"algorithm\"",
",",
"\"bcbiornaseq\"",
",",
"\"interesting_groups\"",
")",
"interesting_groups",
"=",
"tz",
".",
"get_in",
"(",
"igkey",
",",
"items",
"[",
"0",
"]",
... | Make sure interesting_groups specify existing metadata and that
the interesting_group is not all of the same for all of the samples | [
"Make",
"sure",
"interesting_groups",
"specify",
"existing",
"metadata",
"and",
"that",
"the",
"interesting_group",
"is",
"not",
"all",
"of",
"the",
"same",
"for",
"all",
"of",
"the",
"samples"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L514-L529 |
224,357 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_algorithm_keys | def _check_algorithm_keys(item):
"""Check for unexpected keys in the algorithm section.
Needs to be manually updated when introducing new keys, but avoids silent bugs
with typos in key names.
"""
problem_keys = [k for k in item["algorithm"].keys() if k not in ALGORITHM_KEYS]
if len(problem_keys) > 0:
raise ValueError("Unexpected configuration keyword in 'algorithm' section: %s\n"
"See configuration documentation for supported options:\n%s\n"
% (problem_keys, ALG_DOC_URL)) | python | def _check_algorithm_keys(item):
"""Check for unexpected keys in the algorithm section.
Needs to be manually updated when introducing new keys, but avoids silent bugs
with typos in key names.
"""
problem_keys = [k for k in item["algorithm"].keys() if k not in ALGORITHM_KEYS]
if len(problem_keys) > 0:
raise ValueError("Unexpected configuration keyword in 'algorithm' section: %s\n"
"See configuration documentation for supported options:\n%s\n"
% (problem_keys, ALG_DOC_URL)) | [
"def",
"_check_algorithm_keys",
"(",
"item",
")",
":",
"problem_keys",
"=",
"[",
"k",
"for",
"k",
"in",
"item",
"[",
"\"algorithm\"",
"]",
".",
"keys",
"(",
")",
"if",
"k",
"not",
"in",
"ALGORITHM_KEYS",
"]",
"if",
"len",
"(",
"problem_keys",
")",
">",... | Check for unexpected keys in the algorithm section.
Needs to be manually updated when introducing new keys, but avoids silent bugs
with typos in key names. | [
"Check",
"for",
"unexpected",
"keys",
"in",
"the",
"algorithm",
"section",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L575-L585 |
224,358 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_algorithm_values | def _check_algorithm_values(item):
"""Check for misplaced inputs in the algorithms.
- Identify incorrect boolean values where a choice is required.
"""
problems = []
for k, v in item.get("algorithm", {}).items():
if v is True and k not in ALG_ALLOW_BOOLEANS:
problems.append("%s set as true" % k)
elif v is False and (k not in ALG_ALLOW_BOOLEANS and k not in ALG_ALLOW_FALSE):
problems.append("%s set as false" % k)
if len(problems) > 0:
raise ValueError("Incorrect settings in 'algorithm' section for %s:\n%s"
"\nSee configuration documentation for supported options:\n%s\n"
% (item["description"], "\n".join(problems), ALG_DOC_URL)) | python | def _check_algorithm_values(item):
"""Check for misplaced inputs in the algorithms.
- Identify incorrect boolean values where a choice is required.
"""
problems = []
for k, v in item.get("algorithm", {}).items():
if v is True and k not in ALG_ALLOW_BOOLEANS:
problems.append("%s set as true" % k)
elif v is False and (k not in ALG_ALLOW_BOOLEANS and k not in ALG_ALLOW_FALSE):
problems.append("%s set as false" % k)
if len(problems) > 0:
raise ValueError("Incorrect settings in 'algorithm' section for %s:\n%s"
"\nSee configuration documentation for supported options:\n%s\n"
% (item["description"], "\n".join(problems), ALG_DOC_URL)) | [
"def",
"_check_algorithm_values",
"(",
"item",
")",
":",
"problems",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"item",
".",
"get",
"(",
"\"algorithm\"",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"True",
"and",
"k",
"not",... | Check for misplaced inputs in the algorithms.
- Identify incorrect boolean values where a choice is required. | [
"Check",
"for",
"misplaced",
"inputs",
"in",
"the",
"algorithms",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L587-L601 |
224,359 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_toplevel_misplaced | def _check_toplevel_misplaced(item):
"""Check for algorithm keys accidentally placed at the top level.
"""
problem_keys = [k for k in item.keys() if k in ALGORITHM_KEYS]
if len(problem_keys) > 0:
raise ValueError("Unexpected configuration keywords found in top level of %s: %s\n"
"This should be placed in the 'algorithm' section."
% (item["description"], problem_keys))
problem_keys = [k for k in item.keys() if k not in TOPLEVEL_KEYS]
if len(problem_keys) > 0:
raise ValueError("Unexpected configuration keywords found in top level of %s: %s\n"
% (item["description"], problem_keys)) | python | def _check_toplevel_misplaced(item):
"""Check for algorithm keys accidentally placed at the top level.
"""
problem_keys = [k for k in item.keys() if k in ALGORITHM_KEYS]
if len(problem_keys) > 0:
raise ValueError("Unexpected configuration keywords found in top level of %s: %s\n"
"This should be placed in the 'algorithm' section."
% (item["description"], problem_keys))
problem_keys = [k for k in item.keys() if k not in TOPLEVEL_KEYS]
if len(problem_keys) > 0:
raise ValueError("Unexpected configuration keywords found in top level of %s: %s\n"
% (item["description"], problem_keys)) | [
"def",
"_check_toplevel_misplaced",
"(",
"item",
")",
":",
"problem_keys",
"=",
"[",
"k",
"for",
"k",
"in",
"item",
".",
"keys",
"(",
")",
"if",
"k",
"in",
"ALGORITHM_KEYS",
"]",
"if",
"len",
"(",
"problem_keys",
")",
">",
"0",
":",
"raise",
"ValueErro... | Check for algorithm keys accidentally placed at the top level. | [
"Check",
"for",
"algorithm",
"keys",
"accidentally",
"placed",
"at",
"the",
"top",
"level",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L604-L615 |
224,360 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_quality_format | def _check_quality_format(items):
"""
Check if quality_format="standard" and fastq_format is not sanger
"""
SAMPLE_FORMAT = {"illumina_1.3+": "illumina",
"illumina_1.5+": "illumina",
"illumina_1.8+": "standard",
"solexa": "solexa",
"sanger": "standard"}
fastq_extensions = ["fq.gz", "fastq.gz", ".fastq", ".fq"]
for item in items:
specified_format = item["algorithm"].get("quality_format", "standard").lower()
if specified_format not in SAMPLE_FORMAT.values():
raise ValueError("Quality format specified in the YAML file"
"is not supported. Supported values are %s."
% (SAMPLE_FORMAT.values()))
fastq_file = next((f for f in item.get("files") or [] if f.endswith(tuple(fastq_extensions))), None)
if fastq_file and specified_format and not objectstore.is_remote(fastq_file):
fastq_format = _detect_fastq_format(fastq_file)
detected_encodings = set([SAMPLE_FORMAT[x] for x in fastq_format])
if detected_encodings:
if specified_format not in detected_encodings:
raise ValueError("Quality format specified in the YAML "
"file might be a different encoding. "
"'%s' was specified but possible formats "
"detected were %s." % (specified_format,
", ".join(detected_encodings))) | python | def _check_quality_format(items):
"""
Check if quality_format="standard" and fastq_format is not sanger
"""
SAMPLE_FORMAT = {"illumina_1.3+": "illumina",
"illumina_1.5+": "illumina",
"illumina_1.8+": "standard",
"solexa": "solexa",
"sanger": "standard"}
fastq_extensions = ["fq.gz", "fastq.gz", ".fastq", ".fq"]
for item in items:
specified_format = item["algorithm"].get("quality_format", "standard").lower()
if specified_format not in SAMPLE_FORMAT.values():
raise ValueError("Quality format specified in the YAML file"
"is not supported. Supported values are %s."
% (SAMPLE_FORMAT.values()))
fastq_file = next((f for f in item.get("files") or [] if f.endswith(tuple(fastq_extensions))), None)
if fastq_file and specified_format and not objectstore.is_remote(fastq_file):
fastq_format = _detect_fastq_format(fastq_file)
detected_encodings = set([SAMPLE_FORMAT[x] for x in fastq_format])
if detected_encodings:
if specified_format not in detected_encodings:
raise ValueError("Quality format specified in the YAML "
"file might be a different encoding. "
"'%s' was specified but possible formats "
"detected were %s." % (specified_format,
", ".join(detected_encodings))) | [
"def",
"_check_quality_format",
"(",
"items",
")",
":",
"SAMPLE_FORMAT",
"=",
"{",
"\"illumina_1.3+\"",
":",
"\"illumina\"",
",",
"\"illumina_1.5+\"",
":",
"\"illumina\"",
",",
"\"illumina_1.8+\"",
":",
"\"standard\"",
",",
"\"solexa\"",
":",
"\"solexa\"",
",",
"\"s... | Check if quality_format="standard" and fastq_format is not sanger | [
"Check",
"if",
"quality_format",
"=",
"standard",
"and",
"fastq_format",
"is",
"not",
"sanger"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L648-L677 |
224,361 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_aligner | def _check_aligner(item):
"""Ensure specified aligner is valid choice.
"""
allowed = set(list(alignment.TOOLS.keys()) + [None, False])
if item["algorithm"].get("aligner") not in allowed:
raise ValueError("Unexpected algorithm 'aligner' parameter: %s\n"
"Supported options: %s\n" %
(item["algorithm"].get("aligner"), sorted(list(allowed)))) | python | def _check_aligner(item):
"""Ensure specified aligner is valid choice.
"""
allowed = set(list(alignment.TOOLS.keys()) + [None, False])
if item["algorithm"].get("aligner") not in allowed:
raise ValueError("Unexpected algorithm 'aligner' parameter: %s\n"
"Supported options: %s\n" %
(item["algorithm"].get("aligner"), sorted(list(allowed)))) | [
"def",
"_check_aligner",
"(",
"item",
")",
":",
"allowed",
"=",
"set",
"(",
"list",
"(",
"alignment",
".",
"TOOLS",
".",
"keys",
"(",
")",
")",
"+",
"[",
"None",
",",
"False",
"]",
")",
"if",
"item",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\... | Ensure specified aligner is valid choice. | [
"Ensure",
"specified",
"aligner",
"is",
"valid",
"choice",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L680-L687 |
224,362 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_variantcaller | def _check_variantcaller(item):
"""Ensure specified variantcaller is a valid choice.
"""
allowed = set(list(genotype.get_variantcallers().keys()) + [None, False])
vcs = item["algorithm"].get("variantcaller")
if not isinstance(vcs, dict):
vcs = {"variantcaller": vcs}
for vc_set in vcs.values():
if not isinstance(vc_set, (tuple, list)):
vc_set = [vc_set]
problem = [x for x in vc_set if x not in allowed]
if len(problem) > 0:
raise ValueError("Unexpected algorithm 'variantcaller' parameter: %s\n"
"Supported options: %s\n" % (problem, sorted(list(allowed))))
# Ensure germline somatic calling only specified with tumor/normal samples
if "germline" in vcs or "somatic" in vcs:
paired = vcfutils.get_paired_phenotype(item)
if not paired:
raise ValueError("%s: somatic/germline calling in 'variantcaller' "
"but tumor/normal metadata phenotype not specified" % dd.get_sample_name(item)) | python | def _check_variantcaller(item):
"""Ensure specified variantcaller is a valid choice.
"""
allowed = set(list(genotype.get_variantcallers().keys()) + [None, False])
vcs = item["algorithm"].get("variantcaller")
if not isinstance(vcs, dict):
vcs = {"variantcaller": vcs}
for vc_set in vcs.values():
if not isinstance(vc_set, (tuple, list)):
vc_set = [vc_set]
problem = [x for x in vc_set if x not in allowed]
if len(problem) > 0:
raise ValueError("Unexpected algorithm 'variantcaller' parameter: %s\n"
"Supported options: %s\n" % (problem, sorted(list(allowed))))
# Ensure germline somatic calling only specified with tumor/normal samples
if "germline" in vcs or "somatic" in vcs:
paired = vcfutils.get_paired_phenotype(item)
if not paired:
raise ValueError("%s: somatic/germline calling in 'variantcaller' "
"but tumor/normal metadata phenotype not specified" % dd.get_sample_name(item)) | [
"def",
"_check_variantcaller",
"(",
"item",
")",
":",
"allowed",
"=",
"set",
"(",
"list",
"(",
"genotype",
".",
"get_variantcallers",
"(",
")",
".",
"keys",
"(",
")",
")",
"+",
"[",
"None",
",",
"False",
"]",
")",
"vcs",
"=",
"item",
"[",
"\"algorith... | Ensure specified variantcaller is a valid choice. | [
"Ensure",
"specified",
"variantcaller",
"is",
"a",
"valid",
"choice",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L689-L708 |
224,363 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_svcaller | def _check_svcaller(item):
"""Ensure the provide structural variant caller is valid.
"""
allowed = set(reduce(operator.add, [list(d.keys()) for d in structural._CALLERS.values()]) + [None, False])
svs = item["algorithm"].get("svcaller")
if not isinstance(svs, (list, tuple)):
svs = [svs]
problem = [x for x in svs if x not in allowed]
if len(problem) > 0:
raise ValueError("Unexpected algorithm 'svcaller' parameters: %s\n"
"Supported options: %s\n" % (" ".join(["'%s'" % x for x in problem]),
sorted(list(allowed)))) | python | def _check_svcaller(item):
"""Ensure the provide structural variant caller is valid.
"""
allowed = set(reduce(operator.add, [list(d.keys()) for d in structural._CALLERS.values()]) + [None, False])
svs = item["algorithm"].get("svcaller")
if not isinstance(svs, (list, tuple)):
svs = [svs]
problem = [x for x in svs if x not in allowed]
if len(problem) > 0:
raise ValueError("Unexpected algorithm 'svcaller' parameters: %s\n"
"Supported options: %s\n" % (" ".join(["'%s'" % x for x in problem]),
sorted(list(allowed)))) | [
"def",
"_check_svcaller",
"(",
"item",
")",
":",
"allowed",
"=",
"set",
"(",
"reduce",
"(",
"operator",
".",
"add",
",",
"[",
"list",
"(",
"d",
".",
"keys",
"(",
")",
")",
"for",
"d",
"in",
"structural",
".",
"_CALLERS",
".",
"values",
"(",
")",
... | Ensure the provide structural variant caller is valid. | [
"Ensure",
"the",
"provide",
"structural",
"variant",
"caller",
"is",
"valid",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L710-L721 |
224,364 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_hetcaller | def _check_hetcaller(item):
"""Ensure upstream SV callers requires to heterogeneity analysis are available.
"""
svs = _get_as_list(item, "svcaller")
hets = _get_as_list(item, "hetcaller")
if hets or any([x in svs for x in ["titancna", "purecn"]]):
if not any([x in svs for x in ["cnvkit", "gatk-cnv"]]):
raise ValueError("Heterogeneity caller used but need CNV calls. Add `gatk4-cnv` "
"or `cnvkit` to `svcaller` in sample: %s" % item["description"]) | python | def _check_hetcaller(item):
"""Ensure upstream SV callers requires to heterogeneity analysis are available.
"""
svs = _get_as_list(item, "svcaller")
hets = _get_as_list(item, "hetcaller")
if hets or any([x in svs for x in ["titancna", "purecn"]]):
if not any([x in svs for x in ["cnvkit", "gatk-cnv"]]):
raise ValueError("Heterogeneity caller used but need CNV calls. Add `gatk4-cnv` "
"or `cnvkit` to `svcaller` in sample: %s" % item["description"]) | [
"def",
"_check_hetcaller",
"(",
"item",
")",
":",
"svs",
"=",
"_get_as_list",
"(",
"item",
",",
"\"svcaller\"",
")",
"hets",
"=",
"_get_as_list",
"(",
"item",
",",
"\"hetcaller\"",
")",
"if",
"hets",
"or",
"any",
"(",
"[",
"x",
"in",
"svs",
"for",
"x",... | Ensure upstream SV callers requires to heterogeneity analysis are available. | [
"Ensure",
"upstream",
"SV",
"callers",
"requires",
"to",
"heterogeneity",
"analysis",
"are",
"available",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L731-L739 |
224,365 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_jointcaller | def _check_jointcaller(data):
"""Ensure specified jointcaller is valid.
"""
allowed = set(joint.get_callers() + [None, False])
cs = data["algorithm"].get("jointcaller", [])
if not isinstance(cs, (tuple, list)):
cs = [cs]
problem = [x for x in cs if x not in allowed]
if len(problem) > 0:
raise ValueError("Unexpected algorithm 'jointcaller' parameter: %s\n"
"Supported options: %s\n" % (problem, sorted(list(allowed), key=lambda x: x or ""))) | python | def _check_jointcaller(data):
"""Ensure specified jointcaller is valid.
"""
allowed = set(joint.get_callers() + [None, False])
cs = data["algorithm"].get("jointcaller", [])
if not isinstance(cs, (tuple, list)):
cs = [cs]
problem = [x for x in cs if x not in allowed]
if len(problem) > 0:
raise ValueError("Unexpected algorithm 'jointcaller' parameter: %s\n"
"Supported options: %s\n" % (problem, sorted(list(allowed), key=lambda x: x or ""))) | [
"def",
"_check_jointcaller",
"(",
"data",
")",
":",
"allowed",
"=",
"set",
"(",
"joint",
".",
"get_callers",
"(",
")",
"+",
"[",
"None",
",",
"False",
"]",
")",
"cs",
"=",
"data",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\"jointcaller\"",
",",
"[... | Ensure specified jointcaller is valid. | [
"Ensure",
"specified",
"jointcaller",
"is",
"valid",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L741-L751 |
224,366 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_realign | def _check_realign(data):
"""Check for realignment, which is not supported in GATK4
"""
if "gatk4" not in data["algorithm"].get("tools_off", []) and not "gatk4" == data["algorithm"].get("tools_off"):
if data["algorithm"].get("realign"):
raise ValueError("In sample %s, realign specified but it is not supported for GATK4. "
"Realignment is generally not necessary for most variant callers." %
(dd.get_sample_name(data))) | python | def _check_realign(data):
"""Check for realignment, which is not supported in GATK4
"""
if "gatk4" not in data["algorithm"].get("tools_off", []) and not "gatk4" == data["algorithm"].get("tools_off"):
if data["algorithm"].get("realign"):
raise ValueError("In sample %s, realign specified but it is not supported for GATK4. "
"Realignment is generally not necessary for most variant callers." %
(dd.get_sample_name(data))) | [
"def",
"_check_realign",
"(",
"data",
")",
":",
"if",
"\"gatk4\"",
"not",
"in",
"data",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\"tools_off\"",
",",
"[",
"]",
")",
"and",
"not",
"\"gatk4\"",
"==",
"data",
"[",
"\"algorithm\"",
"]",
".",
"get",
"("... | Check for realignment, which is not supported in GATK4 | [
"Check",
"for",
"realignment",
"which",
"is",
"not",
"supported",
"in",
"GATK4"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L767-L774 |
224,367 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_trim | def _check_trim(data):
"""Check for valid values for trim_reads.
"""
trim = data["algorithm"].get("trim_reads")
if trim:
if trim == "fastp" and data["algorithm"].get("align_split_size") is not False:
raise ValueError("In sample %s, `trim_reads: fastp` currently requires `align_split_size: false`" %
(dd.get_sample_name(data))) | python | def _check_trim(data):
"""Check for valid values for trim_reads.
"""
trim = data["algorithm"].get("trim_reads")
if trim:
if trim == "fastp" and data["algorithm"].get("align_split_size") is not False:
raise ValueError("In sample %s, `trim_reads: fastp` currently requires `align_split_size: false`" %
(dd.get_sample_name(data))) | [
"def",
"_check_trim",
"(",
"data",
")",
":",
"trim",
"=",
"data",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\"trim_reads\"",
")",
"if",
"trim",
":",
"if",
"trim",
"==",
"\"fastp\"",
"and",
"data",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\"align... | Check for valid values for trim_reads. | [
"Check",
"for",
"valid",
"values",
"for",
"trim_reads",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L776-L783 |
224,368 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _check_sample_config | def _check_sample_config(items, in_file, config):
"""Identify common problems in input sample configuration files.
"""
logger.info("Checking sample YAML configuration: %s" % in_file)
_check_quality_format(items)
_check_for_duplicates(items, "lane")
_check_for_duplicates(items, "description")
_check_for_degenerate_interesting_groups(items)
_check_for_batch_clashes(items)
_check_for_problem_somatic_batches(items, config)
_check_for_misplaced(items, "algorithm",
["resources", "metadata", "analysis",
"description", "genome_build", "lane", "files"])
[_check_toplevel_misplaced(x) for x in items]
[_check_algorithm_keys(x) for x in items]
[_check_algorithm_values(x) for x in items]
[_check_aligner(x) for x in items]
[_check_variantcaller(x) for x in items]
[_check_svcaller(x) for x in items]
[_check_hetcaller(x) for x in items]
[_check_indelcaller(x) for x in items]
[_check_jointcaller(x) for x in items]
[_check_hlacaller(x) for x in items]
[_check_realign(x) for x in items]
[_check_trim(x) for x in items] | python | def _check_sample_config(items, in_file, config):
"""Identify common problems in input sample configuration files.
"""
logger.info("Checking sample YAML configuration: %s" % in_file)
_check_quality_format(items)
_check_for_duplicates(items, "lane")
_check_for_duplicates(items, "description")
_check_for_degenerate_interesting_groups(items)
_check_for_batch_clashes(items)
_check_for_problem_somatic_batches(items, config)
_check_for_misplaced(items, "algorithm",
["resources", "metadata", "analysis",
"description", "genome_build", "lane", "files"])
[_check_toplevel_misplaced(x) for x in items]
[_check_algorithm_keys(x) for x in items]
[_check_algorithm_values(x) for x in items]
[_check_aligner(x) for x in items]
[_check_variantcaller(x) for x in items]
[_check_svcaller(x) for x in items]
[_check_hetcaller(x) for x in items]
[_check_indelcaller(x) for x in items]
[_check_jointcaller(x) for x in items]
[_check_hlacaller(x) for x in items]
[_check_realign(x) for x in items]
[_check_trim(x) for x in items] | [
"def",
"_check_sample_config",
"(",
"items",
",",
"in_file",
",",
"config",
")",
":",
"logger",
".",
"info",
"(",
"\"Checking sample YAML configuration: %s\"",
"%",
"in_file",
")",
"_check_quality_format",
"(",
"items",
")",
"_check_for_duplicates",
"(",
"items",
",... | Identify common problems in input sample configuration files. | [
"Identify",
"common",
"problems",
"in",
"input",
"sample",
"configuration",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L786-L811 |
224,369 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _file_to_abs | def _file_to_abs(x, dnames, makedir=False):
"""Make a file absolute using the supplied base directory choices.
"""
if x is None or os.path.isabs(x):
return x
elif isinstance(x, six.string_types) and objectstore.is_remote(x):
return x
elif isinstance(x, six.string_types) and x.lower() == "none":
return None
else:
for dname in dnames:
if dname:
normx = os.path.normpath(os.path.join(dname, x))
if os.path.exists(normx):
return normx
elif makedir:
utils.safe_makedir(normx)
return normx
raise ValueError("Did not find input file %s in %s" % (x, dnames)) | python | def _file_to_abs(x, dnames, makedir=False):
"""Make a file absolute using the supplied base directory choices.
"""
if x is None or os.path.isabs(x):
return x
elif isinstance(x, six.string_types) and objectstore.is_remote(x):
return x
elif isinstance(x, six.string_types) and x.lower() == "none":
return None
else:
for dname in dnames:
if dname:
normx = os.path.normpath(os.path.join(dname, x))
if os.path.exists(normx):
return normx
elif makedir:
utils.safe_makedir(normx)
return normx
raise ValueError("Did not find input file %s in %s" % (x, dnames)) | [
"def",
"_file_to_abs",
"(",
"x",
",",
"dnames",
",",
"makedir",
"=",
"False",
")",
":",
"if",
"x",
"is",
"None",
"or",
"os",
".",
"path",
".",
"isabs",
"(",
"x",
")",
":",
"return",
"x",
"elif",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_ty... | Make a file absolute using the supplied base directory choices. | [
"Make",
"a",
"file",
"absolute",
"using",
"the",
"supplied",
"base",
"directory",
"choices",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L815-L833 |
224,370 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _normalize_files | def _normalize_files(item, fc_dir=None):
"""Ensure the files argument is a list of absolute file names.
Handles BAM, single and paired end fastq, as well as split inputs.
"""
files = item.get("files")
if files:
if isinstance(files, six.string_types):
files = [files]
fastq_dir = flowcell.get_fastq_dir(fc_dir) if fc_dir else os.getcwd()
files = [_file_to_abs(x, [os.getcwd(), fc_dir, fastq_dir]) for x in files]
files = [x for x in files if x]
_sanity_check_files(item, files)
item["files"] = files
return item | python | def _normalize_files(item, fc_dir=None):
"""Ensure the files argument is a list of absolute file names.
Handles BAM, single and paired end fastq, as well as split inputs.
"""
files = item.get("files")
if files:
if isinstance(files, six.string_types):
files = [files]
fastq_dir = flowcell.get_fastq_dir(fc_dir) if fc_dir else os.getcwd()
files = [_file_to_abs(x, [os.getcwd(), fc_dir, fastq_dir]) for x in files]
files = [x for x in files if x]
_sanity_check_files(item, files)
item["files"] = files
return item | [
"def",
"_normalize_files",
"(",
"item",
",",
"fc_dir",
"=",
"None",
")",
":",
"files",
"=",
"item",
".",
"get",
"(",
"\"files\"",
")",
"if",
"files",
":",
"if",
"isinstance",
"(",
"files",
",",
"six",
".",
"string_types",
")",
":",
"files",
"=",
"[",... | Ensure the files argument is a list of absolute file names.
Handles BAM, single and paired end fastq, as well as split inputs. | [
"Ensure",
"the",
"files",
"argument",
"is",
"a",
"list",
"of",
"absolute",
"file",
"names",
".",
"Handles",
"BAM",
"single",
"and",
"paired",
"end",
"fastq",
"as",
"well",
"as",
"split",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L835-L848 |
224,371 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _sanity_check_files | def _sanity_check_files(item, files):
"""Ensure input files correspond with supported approaches.
Handles BAM, fastqs, plus split fastqs.
"""
msg = None
file_types = set([("bam" if x.endswith(".bam") else "fastq") for x in files if x])
if len(file_types) > 1:
msg = "Found multiple file types (BAM and fastq)"
file_type = file_types.pop()
if file_type == "bam":
if len(files) != 1:
msg = "Expect a single BAM file input as input"
elif file_type == "fastq":
if len(files) not in [1, 2] and item["analysis"].lower() != "scrna-seq":
pair_types = set([len(xs) for xs in fastq.combine_pairs(files)])
if len(pair_types) != 1 or pair_types.pop() not in [1, 2]:
msg = "Expect either 1 (single end) or 2 (paired end) fastq inputs"
if len(files) == 2 and files[0] == files[1]:
msg = "Expect both fastq files to not be the same"
if msg:
raise ValueError("%s for %s: %s" % (msg, item.get("description", ""), files)) | python | def _sanity_check_files(item, files):
"""Ensure input files correspond with supported approaches.
Handles BAM, fastqs, plus split fastqs.
"""
msg = None
file_types = set([("bam" if x.endswith(".bam") else "fastq") for x in files if x])
if len(file_types) > 1:
msg = "Found multiple file types (BAM and fastq)"
file_type = file_types.pop()
if file_type == "bam":
if len(files) != 1:
msg = "Expect a single BAM file input as input"
elif file_type == "fastq":
if len(files) not in [1, 2] and item["analysis"].lower() != "scrna-seq":
pair_types = set([len(xs) for xs in fastq.combine_pairs(files)])
if len(pair_types) != 1 or pair_types.pop() not in [1, 2]:
msg = "Expect either 1 (single end) or 2 (paired end) fastq inputs"
if len(files) == 2 and files[0] == files[1]:
msg = "Expect both fastq files to not be the same"
if msg:
raise ValueError("%s for %s: %s" % (msg, item.get("description", ""), files)) | [
"def",
"_sanity_check_files",
"(",
"item",
",",
"files",
")",
":",
"msg",
"=",
"None",
"file_types",
"=",
"set",
"(",
"[",
"(",
"\"bam\"",
"if",
"x",
".",
"endswith",
"(",
"\".bam\"",
")",
"else",
"\"fastq\"",
")",
"for",
"x",
"in",
"files",
"if",
"x... | Ensure input files correspond with supported approaches.
Handles BAM, fastqs, plus split fastqs. | [
"Ensure",
"input",
"files",
"correspond",
"with",
"supported",
"approaches",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L850-L871 |
224,372 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | add_metadata_defaults | def add_metadata_defaults(md):
"""Central location for defaults for algorithm inputs.
"""
defaults = {"batch": None,
"phenotype": ""}
for k, v in defaults.items():
if k not in md:
md[k] = v
return md | python | def add_metadata_defaults(md):
"""Central location for defaults for algorithm inputs.
"""
defaults = {"batch": None,
"phenotype": ""}
for k, v in defaults.items():
if k not in md:
md[k] = v
return md | [
"def",
"add_metadata_defaults",
"(",
"md",
")",
":",
"defaults",
"=",
"{",
"\"batch\"",
":",
"None",
",",
"\"phenotype\"",
":",
"\"\"",
"}",
"for",
"k",
",",
"v",
"in",
"defaults",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"md",
":",
"md... | Central location for defaults for algorithm inputs. | [
"Central",
"location",
"for",
"defaults",
"for",
"algorithm",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L1031-L1039 |
224,373 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _add_algorithm_defaults | def _add_algorithm_defaults(algorithm, analysis, is_cwl):
"""Central location specifying defaults for algorithm inputs.
Converts allowed multiple inputs into lists if specified as a single item.
Converts required single items into string if specified as a list
"""
if not algorithm:
algorithm = {}
defaults = {"archive": None,
"tools_off": [],
"tools_on": [],
"qc": [],
"trim_reads": False,
"adapters": [],
"effects": "snpeff",
"quality_format": "standard",
"expression_caller": ["salmon"] if analysis.lower().find("rna-seq") >= 0 else None,
"align_split_size": None,
"bam_clean": False,
"nomap_split_size": 250,
"nomap_split_targets": _get_nomap_split_targets(analysis, is_cwl),
"mark_duplicates": False if not algorithm.get("aligner") else True,
"coverage_interval": None,
"min_allele_fraction": 10.0,
"recalibrate": False,
"realign": False,
"ensemble": None,
"exclude_regions": [],
"variant_regions": None,
"svcaller": [],
"svvalidate": None,
"svprioritize": None,
"validate": None,
"validate_regions": None,
"vcfanno": []}
convert_to_list = set(["tools_off", "tools_on", "hetcaller", "variantcaller", "svcaller", "qc", "disambiguate",
"vcfanno", "adapters", "custom_trim", "exclude_regions"])
convert_to_single = set(["hlacaller", "indelcaller", "validate_method"])
for k, v in defaults.items():
if k not in algorithm:
algorithm[k] = v
for k, v in algorithm.items():
if k in convert_to_list:
if v and not isinstance(v, (list, tuple)) and not isinstance(v, dict):
algorithm[k] = [v]
# ensure dictionary specified inputs get converted into individual lists
elif v and not isinstance(v, (list, tuple)) and isinstance(v, dict):
new = {}
for innerk, innerv in v.items():
if innerv and not isinstance(innerv, (list, tuple)) and not isinstance(innerv, dict):
innerv = [innerv]
new[innerk] = innerv
algorithm[k] = new
elif v is None:
algorithm[k] = []
elif k in convert_to_single:
if v and not isinstance(v, six.string_types):
if isinstance(v, (list, tuple)) and len(v) == 1:
algorithm[k] = v[0]
else:
raise ValueError("Unexpected input in sample YAML; need a single item for %s: %s" % (k, v))
return algorithm | python | def _add_algorithm_defaults(algorithm, analysis, is_cwl):
"""Central location specifying defaults for algorithm inputs.
Converts allowed multiple inputs into lists if specified as a single item.
Converts required single items into string if specified as a list
"""
if not algorithm:
algorithm = {}
defaults = {"archive": None,
"tools_off": [],
"tools_on": [],
"qc": [],
"trim_reads": False,
"adapters": [],
"effects": "snpeff",
"quality_format": "standard",
"expression_caller": ["salmon"] if analysis.lower().find("rna-seq") >= 0 else None,
"align_split_size": None,
"bam_clean": False,
"nomap_split_size": 250,
"nomap_split_targets": _get_nomap_split_targets(analysis, is_cwl),
"mark_duplicates": False if not algorithm.get("aligner") else True,
"coverage_interval": None,
"min_allele_fraction": 10.0,
"recalibrate": False,
"realign": False,
"ensemble": None,
"exclude_regions": [],
"variant_regions": None,
"svcaller": [],
"svvalidate": None,
"svprioritize": None,
"validate": None,
"validate_regions": None,
"vcfanno": []}
convert_to_list = set(["tools_off", "tools_on", "hetcaller", "variantcaller", "svcaller", "qc", "disambiguate",
"vcfanno", "adapters", "custom_trim", "exclude_regions"])
convert_to_single = set(["hlacaller", "indelcaller", "validate_method"])
for k, v in defaults.items():
if k not in algorithm:
algorithm[k] = v
for k, v in algorithm.items():
if k in convert_to_list:
if v and not isinstance(v, (list, tuple)) and not isinstance(v, dict):
algorithm[k] = [v]
# ensure dictionary specified inputs get converted into individual lists
elif v and not isinstance(v, (list, tuple)) and isinstance(v, dict):
new = {}
for innerk, innerv in v.items():
if innerv and not isinstance(innerv, (list, tuple)) and not isinstance(innerv, dict):
innerv = [innerv]
new[innerk] = innerv
algorithm[k] = new
elif v is None:
algorithm[k] = []
elif k in convert_to_single:
if v and not isinstance(v, six.string_types):
if isinstance(v, (list, tuple)) and len(v) == 1:
algorithm[k] = v[0]
else:
raise ValueError("Unexpected input in sample YAML; need a single item for %s: %s" % (k, v))
return algorithm | [
"def",
"_add_algorithm_defaults",
"(",
"algorithm",
",",
"analysis",
",",
"is_cwl",
")",
":",
"if",
"not",
"algorithm",
":",
"algorithm",
"=",
"{",
"}",
"defaults",
"=",
"{",
"\"archive\"",
":",
"None",
",",
"\"tools_off\"",
":",
"[",
"]",
",",
"\"tools_on... | Central location specifying defaults for algorithm inputs.
Converts allowed multiple inputs into lists if specified as a single item.
Converts required single items into string if specified as a list | [
"Central",
"location",
"specifying",
"defaults",
"for",
"algorithm",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L1055-L1116 |
224,374 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | _replace_global_vars | def _replace_global_vars(xs, global_vars):
"""Replace globally shared names from input header with value.
The value of the `algorithm` item may be a pointer to a real
file specified in the `global` section. If found, replace with
the full value.
"""
if isinstance(xs, (list, tuple)):
return [_replace_global_vars(x) for x in xs]
elif isinstance(xs, dict):
final = {}
for k, v in xs.items():
if isinstance(v, six.string_types) and v in global_vars:
v = global_vars[v]
final[k] = v
return final
else:
return xs | python | def _replace_global_vars(xs, global_vars):
"""Replace globally shared names from input header with value.
The value of the `algorithm` item may be a pointer to a real
file specified in the `global` section. If found, replace with
the full value.
"""
if isinstance(xs, (list, tuple)):
return [_replace_global_vars(x) for x in xs]
elif isinstance(xs, dict):
final = {}
for k, v in xs.items():
if isinstance(v, six.string_types) and v in global_vars:
v = global_vars[v]
final[k] = v
return final
else:
return xs | [
"def",
"_replace_global_vars",
"(",
"xs",
",",
"global_vars",
")",
":",
"if",
"isinstance",
"(",
"xs",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"_replace_global_vars",
"(",
"x",
")",
"for",
"x",
"in",
"xs",
"]",
"elif",
"isinstance... | Replace globally shared names from input header with value.
The value of the `algorithm` item may be a pointer to a real
file specified in the `global` section. If found, replace with
the full value. | [
"Replace",
"globally",
"shared",
"names",
"from",
"input",
"header",
"with",
"value",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L1118-L1135 |
224,375 | bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | prep_system | def prep_system(run_info_yaml, bcbio_system=None):
"""Prepare system configuration information from an input configuration file.
This does the work of parsing the system input file and setting up directories
for use in 'organize'.
"""
work_dir = os.getcwd()
config, config_file = config_utils.load_system_config(bcbio_system, work_dir)
dirs = setup_directories(work_dir, os.path.normpath(os.path.dirname(os.path.dirname(run_info_yaml))),
config, config_file)
return [dirs, config, run_info_yaml] | python | def prep_system(run_info_yaml, bcbio_system=None):
"""Prepare system configuration information from an input configuration file.
This does the work of parsing the system input file and setting up directories
for use in 'organize'.
"""
work_dir = os.getcwd()
config, config_file = config_utils.load_system_config(bcbio_system, work_dir)
dirs = setup_directories(work_dir, os.path.normpath(os.path.dirname(os.path.dirname(run_info_yaml))),
config, config_file)
return [dirs, config, run_info_yaml] | [
"def",
"prep_system",
"(",
"run_info_yaml",
",",
"bcbio_system",
"=",
"None",
")",
":",
"work_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"config",
",",
"config_file",
"=",
"config_utils",
".",
"load_system_config",
"(",
"bcbio_system",
",",
"work_dir",
")",
"... | Prepare system configuration information from an input configuration file.
This does the work of parsing the system input file and setting up directories
for use in 'organize'. | [
"Prepare",
"system",
"configuration",
"information",
"from",
"an",
"input",
"configuration",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L1150-L1160 |
224,376 | bcbio/bcbio-nextgen | bcbio/variation/platypus.py | run | def run(align_bams, items, ref_file, assoc_files, region, out_file):
"""Run platypus variant calling, germline whole genome or exome.
"""
assert out_file.endswith(".vcf.gz")
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
for align_bam in align_bams:
bam.index(align_bam, items[0]["config"])
cmd = ["platypus", "callVariants", "--regions=%s" % _subset_regions(region, out_file, items),
"--bamFiles=%s" % ",".join(align_bams),
"--refFile=%s" % dd.get_ref_file(items[0]), "--output=-",
"--logFileName", "/dev/null", "--verbosity=1"]
resources = config_utils.get_resources("platypus", items[0]["config"])
if resources.get("options"):
# normalize options so we can set defaults without overwriting user specified
for opt in resources["options"]:
if "=" in opt:
key, val = opt.split("=")
cmd.extend([key, val])
else:
cmd.append(opt)
if any("gvcf" in dd.get_tools_on(d) for d in items):
cmd += ["--outputRefCalls", "1", "--refCallBlockSize", "50000"]
# Adjust default filter thresholds to achieve similar sensitivity/specificity to other callers
# Currently not used after doing more cross validation as they increase false positives
# which seems to be a major advantage for Platypus users.
# tuned_opts = ["--hapScoreThreshold", "10", "--scThreshold", "0.99", "--filteredReadsFrac", "0.9",
# "--rmsmqThreshold", "20", "--qdThreshold", "0", "--abThreshold", "0.0001",
# "--minVarFreq", "0.0", "--assemble", "1"]
# for okey, oval in utils.partition_all(2, tuned_opts):
# if okey not in cmd:
# cmd.extend([okey, oval])
# Avoid filtering duplicates on high depth targeted regions where we don't mark duplicates
if any(not dd.get_mark_duplicates(data) for data in items):
cmd += ["--filterDuplicates=0"]
post_process_cmd = (" | %s | %s | %s | vcfallelicprimitives -t DECOMPOSED --keep-geno | vcffixup - | "
"vcfstreamsort | bgzip -c > %s" %
(vcfutils.fix_ambiguous_cl(), vcfutils.fix_ambiguous_cl(5),
vcfutils.add_contig_to_header_cl(dd.get_ref_file(items[0]), tx_out_file),
tx_out_file))
do.run(" ".join(cmd) + post_process_cmd, "platypus variant calling")
out_file = vcfutils.bgzip_and_index(out_file, items[0]["config"])
return out_file | python | def run(align_bams, items, ref_file, assoc_files, region, out_file):
"""Run platypus variant calling, germline whole genome or exome.
"""
assert out_file.endswith(".vcf.gz")
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
for align_bam in align_bams:
bam.index(align_bam, items[0]["config"])
cmd = ["platypus", "callVariants", "--regions=%s" % _subset_regions(region, out_file, items),
"--bamFiles=%s" % ",".join(align_bams),
"--refFile=%s" % dd.get_ref_file(items[0]), "--output=-",
"--logFileName", "/dev/null", "--verbosity=1"]
resources = config_utils.get_resources("platypus", items[0]["config"])
if resources.get("options"):
# normalize options so we can set defaults without overwriting user specified
for opt in resources["options"]:
if "=" in opt:
key, val = opt.split("=")
cmd.extend([key, val])
else:
cmd.append(opt)
if any("gvcf" in dd.get_tools_on(d) for d in items):
cmd += ["--outputRefCalls", "1", "--refCallBlockSize", "50000"]
# Adjust default filter thresholds to achieve similar sensitivity/specificity to other callers
# Currently not used after doing more cross validation as they increase false positives
# which seems to be a major advantage for Platypus users.
# tuned_opts = ["--hapScoreThreshold", "10", "--scThreshold", "0.99", "--filteredReadsFrac", "0.9",
# "--rmsmqThreshold", "20", "--qdThreshold", "0", "--abThreshold", "0.0001",
# "--minVarFreq", "0.0", "--assemble", "1"]
# for okey, oval in utils.partition_all(2, tuned_opts):
# if okey not in cmd:
# cmd.extend([okey, oval])
# Avoid filtering duplicates on high depth targeted regions where we don't mark duplicates
if any(not dd.get_mark_duplicates(data) for data in items):
cmd += ["--filterDuplicates=0"]
post_process_cmd = (" | %s | %s | %s | vcfallelicprimitives -t DECOMPOSED --keep-geno | vcffixup - | "
"vcfstreamsort | bgzip -c > %s" %
(vcfutils.fix_ambiguous_cl(), vcfutils.fix_ambiguous_cl(5),
vcfutils.add_contig_to_header_cl(dd.get_ref_file(items[0]), tx_out_file),
tx_out_file))
do.run(" ".join(cmd) + post_process_cmd, "platypus variant calling")
out_file = vcfutils.bgzip_and_index(out_file, items[0]["config"])
return out_file | [
"def",
"run",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
",",
"out_file",
")",
":",
"assert",
"out_file",
".",
"endswith",
"(",
"\".vcf.gz\"",
")",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
... | Run platypus variant calling, germline whole genome or exome. | [
"Run",
"platypus",
"variant",
"calling",
"germline",
"whole",
"genome",
"or",
"exome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/platypus.py#L19-L62 |
224,377 | bcbio/bcbio-nextgen | bcbio/qc/srna.py | run | def run(bam_file, data, out_dir):
"""Create several log files"""
m = {"base": None, "secondary": []}
m.update(_mirbase_stats(data, out_dir))
m["secondary"].append(_seqcluster_stats(data, out_dir)) | python | def run(bam_file, data, out_dir):
"""Create several log files"""
m = {"base": None, "secondary": []}
m.update(_mirbase_stats(data, out_dir))
m["secondary"].append(_seqcluster_stats(data, out_dir)) | [
"def",
"run",
"(",
"bam_file",
",",
"data",
",",
"out_dir",
")",
":",
"m",
"=",
"{",
"\"base\"",
":",
"None",
",",
"\"secondary\"",
":",
"[",
"]",
"}",
"m",
".",
"update",
"(",
"_mirbase_stats",
"(",
"data",
",",
"out_dir",
")",
")",
"m",
"[",
"\... | Create several log files | [
"Create",
"several",
"log",
"files"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/srna.py#L14-L18 |
224,378 | bcbio/bcbio-nextgen | bcbio/qc/srna.py | _mirbase_stats | def _mirbase_stats(data, out_dir):
"""Create stats from miraligner"""
utils.safe_makedir(out_dir)
out_file = os.path.join(out_dir, "%s_bcbio_mirbase.txt" % dd.get_sample_name(data))
out_file_novel = os.path.join(out_dir, "%s_bcbio_mirdeeep2.txt" % dd.get_sample_name(data))
mirbase_fn = data.get("seqbuster", None)
if mirbase_fn:
_get_stats_from_miraligner(mirbase_fn, out_file, "seqbuster")
mirdeep_fn = data.get("seqbuster_novel", None)
if mirdeep_fn:
_get_stats_from_miraligner(mirdeep_fn, out_file_novel, "mirdeep2")
return {"base": out_file, "secondary": [out_file_novel]} | python | def _mirbase_stats(data, out_dir):
"""Create stats from miraligner"""
utils.safe_makedir(out_dir)
out_file = os.path.join(out_dir, "%s_bcbio_mirbase.txt" % dd.get_sample_name(data))
out_file_novel = os.path.join(out_dir, "%s_bcbio_mirdeeep2.txt" % dd.get_sample_name(data))
mirbase_fn = data.get("seqbuster", None)
if mirbase_fn:
_get_stats_from_miraligner(mirbase_fn, out_file, "seqbuster")
mirdeep_fn = data.get("seqbuster_novel", None)
if mirdeep_fn:
_get_stats_from_miraligner(mirdeep_fn, out_file_novel, "mirdeep2")
return {"base": out_file, "secondary": [out_file_novel]} | [
"def",
"_mirbase_stats",
"(",
"data",
",",
"out_dir",
")",
":",
"utils",
".",
"safe_makedir",
"(",
"out_dir",
")",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"\"%s_bcbio_mirbase.txt\"",
"%",
"dd",
".",
"get_sample_name",
"(",
"da... | Create stats from miraligner | [
"Create",
"stats",
"from",
"miraligner"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/srna.py#L20-L31 |
224,379 | bcbio/bcbio-nextgen | bcbio/qc/srna.py | _seqcluster_stats | def _seqcluster_stats(data, out_dir):
"""Parse seqcluster output"""
name = dd.get_sample_name(data)
fn = data.get("seqcluster", {}).get("stat_file", None)
if not fn:
return None
out_file = os.path.join(out_dir, "%s.txt" % name)
df = pd.read_csv(fn, sep="\t", names = ["reads", "sample", "type"])
df_sample = df[df["sample"] == name]
df_sample.to_csv(out_file, sep="\t")
return out_file | python | def _seqcluster_stats(data, out_dir):
"""Parse seqcluster output"""
name = dd.get_sample_name(data)
fn = data.get("seqcluster", {}).get("stat_file", None)
if not fn:
return None
out_file = os.path.join(out_dir, "%s.txt" % name)
df = pd.read_csv(fn, sep="\t", names = ["reads", "sample", "type"])
df_sample = df[df["sample"] == name]
df_sample.to_csv(out_file, sep="\t")
return out_file | [
"def",
"_seqcluster_stats",
"(",
"data",
",",
"out_dir",
")",
":",
"name",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"fn",
"=",
"data",
".",
"get",
"(",
"\"seqcluster\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"stat_file\"",
",",
"None",
"... | Parse seqcluster output | [
"Parse",
"seqcluster",
"output"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/srna.py#L61-L71 |
224,380 | bcbio/bcbio-nextgen | bcbio/illumina/samplesheet.py | from_flowcell | def from_flowcell(run_folder, lane_details, out_dir=None):
"""Convert a flowcell into a samplesheet for demultiplexing.
"""
fcid = os.path.basename(run_folder)
if out_dir is None:
out_dir = run_folder
out_file = os.path.join(out_dir, "%s.csv" % fcid)
with open(out_file, "w") as out_handle:
writer = csv.writer(out_handle)
writer.writerow(["FCID", "Lane", "Sample_ID", "SampleRef", "Index",
"Description", "Control", "Recipe", "Operator", "SampleProject"])
for ldetail in lane_details:
writer.writerow(_lane_detail_to_ss(fcid, ldetail))
return out_file | python | def from_flowcell(run_folder, lane_details, out_dir=None):
"""Convert a flowcell into a samplesheet for demultiplexing.
"""
fcid = os.path.basename(run_folder)
if out_dir is None:
out_dir = run_folder
out_file = os.path.join(out_dir, "%s.csv" % fcid)
with open(out_file, "w") as out_handle:
writer = csv.writer(out_handle)
writer.writerow(["FCID", "Lane", "Sample_ID", "SampleRef", "Index",
"Description", "Control", "Recipe", "Operator", "SampleProject"])
for ldetail in lane_details:
writer.writerow(_lane_detail_to_ss(fcid, ldetail))
return out_file | [
"def",
"from_flowcell",
"(",
"run_folder",
",",
"lane_details",
",",
"out_dir",
"=",
"None",
")",
":",
"fcid",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"run_folder",
")",
"if",
"out_dir",
"is",
"None",
":",
"out_dir",
"=",
"run_folder",
"out_file",
... | Convert a flowcell into a samplesheet for demultiplexing. | [
"Convert",
"a",
"flowcell",
"into",
"a",
"samplesheet",
"for",
"demultiplexing",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L20-L33 |
224,381 | bcbio/bcbio-nextgen | bcbio/illumina/samplesheet.py | _lane_detail_to_ss | def _lane_detail_to_ss(fcid, ldetail):
"""Convert information about a lane into Illumina samplesheet output.
"""
return [fcid, ldetail["lane"], ldetail["name"], ldetail["genome_build"],
ldetail["bc_index"], ldetail["description"].encode("ascii", "ignore"), "N", "", "",
ldetail["project_name"]] | python | def _lane_detail_to_ss(fcid, ldetail):
"""Convert information about a lane into Illumina samplesheet output.
"""
return [fcid, ldetail["lane"], ldetail["name"], ldetail["genome_build"],
ldetail["bc_index"], ldetail["description"].encode("ascii", "ignore"), "N", "", "",
ldetail["project_name"]] | [
"def",
"_lane_detail_to_ss",
"(",
"fcid",
",",
"ldetail",
")",
":",
"return",
"[",
"fcid",
",",
"ldetail",
"[",
"\"lane\"",
"]",
",",
"ldetail",
"[",
"\"name\"",
"]",
",",
"ldetail",
"[",
"\"genome_build\"",
"]",
",",
"ldetail",
"[",
"\"bc_index\"",
"]",
... | Convert information about a lane into Illumina samplesheet output. | [
"Convert",
"information",
"about",
"a",
"lane",
"into",
"Illumina",
"samplesheet",
"output",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L35-L40 |
224,382 | bcbio/bcbio-nextgen | bcbio/illumina/samplesheet.py | _organize_lanes | def _organize_lanes(info_iter, barcode_ids):
"""Organize flat lane information into nested YAML structure.
"""
all_lanes = []
for (fcid, lane, sampleref), info in itertools.groupby(info_iter, lambda x: (x[0], x[1], x[1])):
info = list(info)
cur_lane = dict(flowcell_id=fcid, lane=lane, genome_build=info[0][3], analysis="Standard")
if not _has_barcode(info):
cur_lane["description"] = info[0][1]
else: # barcoded sample
cur_lane["description"] = "Barcoded lane %s" % lane
multiplex = []
for (_, _, sample_id, _, bc_seq) in info:
bc_type, bc_id = barcode_ids[bc_seq]
multiplex.append(dict(barcode_type=bc_type,
barcode_id=bc_id,
sequence=bc_seq,
name=sample_id))
cur_lane["multiplex"] = multiplex
all_lanes.append(cur_lane)
return all_lanes | python | def _organize_lanes(info_iter, barcode_ids):
"""Organize flat lane information into nested YAML structure.
"""
all_lanes = []
for (fcid, lane, sampleref), info in itertools.groupby(info_iter, lambda x: (x[0], x[1], x[1])):
info = list(info)
cur_lane = dict(flowcell_id=fcid, lane=lane, genome_build=info[0][3], analysis="Standard")
if not _has_barcode(info):
cur_lane["description"] = info[0][1]
else: # barcoded sample
cur_lane["description"] = "Barcoded lane %s" % lane
multiplex = []
for (_, _, sample_id, _, bc_seq) in info:
bc_type, bc_id = barcode_ids[bc_seq]
multiplex.append(dict(barcode_type=bc_type,
barcode_id=bc_id,
sequence=bc_seq,
name=sample_id))
cur_lane["multiplex"] = multiplex
all_lanes.append(cur_lane)
return all_lanes | [
"def",
"_organize_lanes",
"(",
"info_iter",
",",
"barcode_ids",
")",
":",
"all_lanes",
"=",
"[",
"]",
"for",
"(",
"fcid",
",",
"lane",
",",
"sampleref",
")",
",",
"info",
"in",
"itertools",
".",
"groupby",
"(",
"info_iter",
",",
"lambda",
"x",
":",
"("... | Organize flat lane information into nested YAML structure. | [
"Organize",
"flat",
"lane",
"information",
"into",
"nested",
"YAML",
"structure",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L44-L64 |
224,383 | bcbio/bcbio-nextgen | bcbio/illumina/samplesheet.py | _generate_barcode_ids | def _generate_barcode_ids(info_iter):
"""Create unique barcode IDs assigned to sequences
"""
bc_type = "SampleSheet"
barcodes = list(set([x[-1] for x in info_iter]))
barcodes.sort()
barcode_ids = {}
for i, bc in enumerate(barcodes):
barcode_ids[bc] = (bc_type, i+1)
return barcode_ids | python | def _generate_barcode_ids(info_iter):
"""Create unique barcode IDs assigned to sequences
"""
bc_type = "SampleSheet"
barcodes = list(set([x[-1] for x in info_iter]))
barcodes.sort()
barcode_ids = {}
for i, bc in enumerate(barcodes):
barcode_ids[bc] = (bc_type, i+1)
return barcode_ids | [
"def",
"_generate_barcode_ids",
"(",
"info_iter",
")",
":",
"bc_type",
"=",
"\"SampleSheet\"",
"barcodes",
"=",
"list",
"(",
"set",
"(",
"[",
"x",
"[",
"-",
"1",
"]",
"for",
"x",
"in",
"info_iter",
"]",
")",
")",
"barcodes",
".",
"sort",
"(",
")",
"b... | Create unique barcode IDs assigned to sequences | [
"Create",
"unique",
"barcode",
"IDs",
"assigned",
"to",
"sequences"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L70-L79 |
224,384 | bcbio/bcbio-nextgen | bcbio/illumina/samplesheet.py | _read_input_csv | def _read_input_csv(in_file):
"""Parse useful details from SampleSheet CSV file.
"""
with io.open(in_file, newline=None) as in_handle:
reader = csv.reader(in_handle)
next(reader) # header
for line in reader:
if line: # empty lines
(fc_id, lane, sample_id, genome, barcode) = line[:5]
yield fc_id, lane, sample_id, genome, barcode | python | def _read_input_csv(in_file):
"""Parse useful details from SampleSheet CSV file.
"""
with io.open(in_file, newline=None) as in_handle:
reader = csv.reader(in_handle)
next(reader) # header
for line in reader:
if line: # empty lines
(fc_id, lane, sample_id, genome, barcode) = line[:5]
yield fc_id, lane, sample_id, genome, barcode | [
"def",
"_read_input_csv",
"(",
"in_file",
")",
":",
"with",
"io",
".",
"open",
"(",
"in_file",
",",
"newline",
"=",
"None",
")",
"as",
"in_handle",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"in_handle",
")",
"next",
"(",
"reader",
")",
"# header",... | Parse useful details from SampleSheet CSV file. | [
"Parse",
"useful",
"details",
"from",
"SampleSheet",
"CSV",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L81-L90 |
224,385 | bcbio/bcbio-nextgen | bcbio/illumina/samplesheet.py | _get_flowcell_id | def _get_flowcell_id(in_file, require_single=True):
"""Retrieve the unique flowcell id represented in the SampleSheet.
"""
fc_ids = set([x[0] for x in _read_input_csv(in_file)])
if require_single and len(fc_ids) > 1:
raise ValueError("There are several FCIDs in the same samplesheet file: %s" % in_file)
else:
return fc_ids | python | def _get_flowcell_id(in_file, require_single=True):
"""Retrieve the unique flowcell id represented in the SampleSheet.
"""
fc_ids = set([x[0] for x in _read_input_csv(in_file)])
if require_single and len(fc_ids) > 1:
raise ValueError("There are several FCIDs in the same samplesheet file: %s" % in_file)
else:
return fc_ids | [
"def",
"_get_flowcell_id",
"(",
"in_file",
",",
"require_single",
"=",
"True",
")",
":",
"fc_ids",
"=",
"set",
"(",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"_read_input_csv",
"(",
"in_file",
")",
"]",
")",
"if",
"require_single",
"and",
"len",
"(",
... | Retrieve the unique flowcell id represented in the SampleSheet. | [
"Retrieve",
"the",
"unique",
"flowcell",
"id",
"represented",
"in",
"the",
"SampleSheet",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L92-L99 |
224,386 | bcbio/bcbio-nextgen | bcbio/illumina/samplesheet.py | csv2yaml | def csv2yaml(in_file, out_file=None):
"""Convert a CSV SampleSheet to YAML run_info format.
"""
if out_file is None:
out_file = "%s.yaml" % os.path.splitext(in_file)[0]
barcode_ids = _generate_barcode_ids(_read_input_csv(in_file))
lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids)
with open(out_file, "w") as out_handle:
out_handle.write(yaml.safe_dump(lanes, default_flow_style=False))
return out_file | python | def csv2yaml(in_file, out_file=None):
"""Convert a CSV SampleSheet to YAML run_info format.
"""
if out_file is None:
out_file = "%s.yaml" % os.path.splitext(in_file)[0]
barcode_ids = _generate_barcode_ids(_read_input_csv(in_file))
lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids)
with open(out_file, "w") as out_handle:
out_handle.write(yaml.safe_dump(lanes, default_flow_style=False))
return out_file | [
"def",
"csv2yaml",
"(",
"in_file",
",",
"out_file",
"=",
"None",
")",
":",
"if",
"out_file",
"is",
"None",
":",
"out_file",
"=",
"\"%s.yaml\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"in_file",
")",
"[",
"0",
"]",
"barcode_ids",
"=",
"_generate_... | Convert a CSV SampleSheet to YAML run_info format. | [
"Convert",
"a",
"CSV",
"SampleSheet",
"to",
"YAML",
"run_info",
"format",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L101-L110 |
224,387 | bcbio/bcbio-nextgen | bcbio/illumina/samplesheet.py | run_has_samplesheet | def run_has_samplesheet(fc_dir, config, require_single=True):
"""Checks if there's a suitable SampleSheet.csv present for the run
"""
fc_name, _ = flowcell.parse_dirname(fc_dir)
sheet_dirs = config.get("samplesheet_directories", [])
fcid_sheet = {}
for ss_dir in (s for s in sheet_dirs if os.path.exists(s)):
with utils.chdir(ss_dir):
for ss in glob.glob("*.csv"):
fc_ids = _get_flowcell_id(ss, require_single)
for fcid in fc_ids:
if fcid:
fcid_sheet[fcid] = os.path.join(ss_dir, ss)
# difflib handles human errors while entering data on the SampleSheet.
# Only one best candidate is returned (if any). 0.85 cutoff allows for
# maximum of 2 mismatches in fcid
potential_fcids = difflib.get_close_matches(fc_name, fcid_sheet.keys(), 1, 0.85)
if len(potential_fcids) > 0 and potential_fcids[0] in fcid_sheet:
return fcid_sheet[potential_fcids[0]]
else:
return None | python | def run_has_samplesheet(fc_dir, config, require_single=True):
"""Checks if there's a suitable SampleSheet.csv present for the run
"""
fc_name, _ = flowcell.parse_dirname(fc_dir)
sheet_dirs = config.get("samplesheet_directories", [])
fcid_sheet = {}
for ss_dir in (s for s in sheet_dirs if os.path.exists(s)):
with utils.chdir(ss_dir):
for ss in glob.glob("*.csv"):
fc_ids = _get_flowcell_id(ss, require_single)
for fcid in fc_ids:
if fcid:
fcid_sheet[fcid] = os.path.join(ss_dir, ss)
# difflib handles human errors while entering data on the SampleSheet.
# Only one best candidate is returned (if any). 0.85 cutoff allows for
# maximum of 2 mismatches in fcid
potential_fcids = difflib.get_close_matches(fc_name, fcid_sheet.keys(), 1, 0.85)
if len(potential_fcids) > 0 and potential_fcids[0] in fcid_sheet:
return fcid_sheet[potential_fcids[0]]
else:
return None | [
"def",
"run_has_samplesheet",
"(",
"fc_dir",
",",
"config",
",",
"require_single",
"=",
"True",
")",
":",
"fc_name",
",",
"_",
"=",
"flowcell",
".",
"parse_dirname",
"(",
"fc_dir",
")",
"sheet_dirs",
"=",
"config",
".",
"get",
"(",
"\"samplesheet_directories\"... | Checks if there's a suitable SampleSheet.csv present for the run | [
"Checks",
"if",
"there",
"s",
"a",
"suitable",
"SampleSheet",
".",
"csv",
"present",
"for",
"the",
"run"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L112-L133 |
224,388 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | combine_bam | def combine_bam(in_files, out_file, config):
"""Parallel target to combine multiple BAM files.
"""
runner = broad.runner_from_path("picard", config)
runner.run_fn("picard_merge", in_files, out_file)
for in_file in in_files:
save_diskspace(in_file, "Merged into {0}".format(out_file), config)
bam.index(out_file, config)
return out_file | python | def combine_bam(in_files, out_file, config):
"""Parallel target to combine multiple BAM files.
"""
runner = broad.runner_from_path("picard", config)
runner.run_fn("picard_merge", in_files, out_file)
for in_file in in_files:
save_diskspace(in_file, "Merged into {0}".format(out_file), config)
bam.index(out_file, config)
return out_file | [
"def",
"combine_bam",
"(",
"in_files",
",",
"out_file",
",",
"config",
")",
":",
"runner",
"=",
"broad",
".",
"runner_from_path",
"(",
"\"picard\"",
",",
"config",
")",
"runner",
".",
"run_fn",
"(",
"\"picard_merge\"",
",",
"in_files",
",",
"out_file",
")",
... | Parallel target to combine multiple BAM files. | [
"Parallel",
"target",
"to",
"combine",
"multiple",
"BAM",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L25-L33 |
224,389 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | write_nochr_reads | def write_nochr_reads(in_file, out_file, config):
"""Write a BAM file of reads that are not mapped on a reference chromosome.
This is useful for maintaining non-mapped reads in parallel processes
that split processing by chromosome.
"""
if not file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
samtools = config_utils.get_program("samtools", config)
cmd = "{samtools} view -b -f 4 {in_file} > {tx_out_file}"
do.run(cmd.format(**locals()), "Select unmapped reads")
return out_file | python | def write_nochr_reads(in_file, out_file, config):
"""Write a BAM file of reads that are not mapped on a reference chromosome.
This is useful for maintaining non-mapped reads in parallel processes
that split processing by chromosome.
"""
if not file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
samtools = config_utils.get_program("samtools", config)
cmd = "{samtools} view -b -f 4 {in_file} > {tx_out_file}"
do.run(cmd.format(**locals()), "Select unmapped reads")
return out_file | [
"def",
"write_nochr_reads",
"(",
"in_file",
",",
"out_file",
",",
"config",
")",
":",
"if",
"not",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
"config",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"samtools",
"=",
"config_u... | Write a BAM file of reads that are not mapped on a reference chromosome.
This is useful for maintaining non-mapped reads in parallel processes
that split processing by chromosome. | [
"Write",
"a",
"BAM",
"file",
"of",
"reads",
"that",
"are",
"not",
"mapped",
"on",
"a",
"reference",
"chromosome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L57-L68 |
224,390 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | write_noanalysis_reads | def write_noanalysis_reads(in_file, region_file, out_file, config):
"""Write a BAM file of reads in the specified region file that are not analyzed.
We want to get only reads not in analysis regions but also make use of
the BAM index to perform well on large files. The tricky part is avoiding
command line limits. There is a nice discussion on SeqAnswers:
http://seqanswers.com/forums/showthread.php?t=29538
sambamba supports intersection via an input BED file so avoids command line
length issues.
"""
if not file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
bedtools = config_utils.get_program("bedtools", config)
sambamba = config_utils.get_program("sambamba", config)
cl = ("{sambamba} view -f bam -l 0 -L {region_file} {in_file} | "
"{bedtools} intersect -abam - -b {region_file} -f 1.0 -nonamecheck"
"> {tx_out_file}")
do.run(cl.format(**locals()), "Select unanalyzed reads")
return out_file | python | def write_noanalysis_reads(in_file, region_file, out_file, config):
"""Write a BAM file of reads in the specified region file that are not analyzed.
We want to get only reads not in analysis regions but also make use of
the BAM index to perform well on large files. The tricky part is avoiding
command line limits. There is a nice discussion on SeqAnswers:
http://seqanswers.com/forums/showthread.php?t=29538
sambamba supports intersection via an input BED file so avoids command line
length issues.
"""
if not file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
bedtools = config_utils.get_program("bedtools", config)
sambamba = config_utils.get_program("sambamba", config)
cl = ("{sambamba} view -f bam -l 0 -L {region_file} {in_file} | "
"{bedtools} intersect -abam - -b {region_file} -f 1.0 -nonamecheck"
"> {tx_out_file}")
do.run(cl.format(**locals()), "Select unanalyzed reads")
return out_file | [
"def",
"write_noanalysis_reads",
"(",
"in_file",
",",
"region_file",
",",
"out_file",
",",
"config",
")",
":",
"if",
"not",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
"config",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"... | Write a BAM file of reads in the specified region file that are not analyzed.
We want to get only reads not in analysis regions but also make use of
the BAM index to perform well on large files. The tricky part is avoiding
command line limits. There is a nice discussion on SeqAnswers:
http://seqanswers.com/forums/showthread.php?t=29538
sambamba supports intersection via an input BED file so avoids command line
length issues. | [
"Write",
"a",
"BAM",
"file",
"of",
"reads",
"in",
"the",
"specified",
"region",
"file",
"that",
"are",
"not",
"analyzed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L70-L88 |
224,391 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | subset_bam_by_region | def subset_bam_by_region(in_file, region, config, out_file_base=None):
"""Subset BAM files based on specified chromosome region.
"""
if out_file_base is not None:
base, ext = os.path.splitext(out_file_base)
else:
base, ext = os.path.splitext(in_file)
out_file = "%s-subset%s%s" % (base, region, ext)
if not file_exists(out_file):
with pysam.Samfile(in_file, "rb") as in_bam:
target_tid = in_bam.gettid(region)
assert region is not None, \
"Did not find reference region %s in %s" % \
(region, in_file)
with file_transaction(config, out_file) as tx_out_file:
with pysam.Samfile(tx_out_file, "wb", template=in_bam) as out_bam:
for read in in_bam:
if read.tid == target_tid:
out_bam.write(read)
return out_file | python | def subset_bam_by_region(in_file, region, config, out_file_base=None):
"""Subset BAM files based on specified chromosome region.
"""
if out_file_base is not None:
base, ext = os.path.splitext(out_file_base)
else:
base, ext = os.path.splitext(in_file)
out_file = "%s-subset%s%s" % (base, region, ext)
if not file_exists(out_file):
with pysam.Samfile(in_file, "rb") as in_bam:
target_tid = in_bam.gettid(region)
assert region is not None, \
"Did not find reference region %s in %s" % \
(region, in_file)
with file_transaction(config, out_file) as tx_out_file:
with pysam.Samfile(tx_out_file, "wb", template=in_bam) as out_bam:
for read in in_bam:
if read.tid == target_tid:
out_bam.write(read)
return out_file | [
"def",
"subset_bam_by_region",
"(",
"in_file",
",",
"region",
",",
"config",
",",
"out_file_base",
"=",
"None",
")",
":",
"if",
"out_file_base",
"is",
"not",
"None",
":",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"out_file_base",
... | Subset BAM files based on specified chromosome region. | [
"Subset",
"BAM",
"files",
"based",
"on",
"specified",
"chromosome",
"region",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L90-L109 |
224,392 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | subset_bed_by_chrom | def subset_bed_by_chrom(in_file, chrom, data, out_dir=None):
"""Subset a BED file to only have items from the specified chromosome.
"""
if out_dir is None:
out_dir = os.path.dirname(in_file)
base, ext = os.path.splitext(os.path.basename(in_file))
out_file = os.path.join(out_dir, "%s-%s%s" % (base, chrom, ext))
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
_rewrite_bed_with_chrom(in_file, tx_out_file, chrom)
return out_file | python | def subset_bed_by_chrom(in_file, chrom, data, out_dir=None):
"""Subset a BED file to only have items from the specified chromosome.
"""
if out_dir is None:
out_dir = os.path.dirname(in_file)
base, ext = os.path.splitext(os.path.basename(in_file))
out_file = os.path.join(out_dir, "%s-%s%s" % (base, chrom, ext))
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
_rewrite_bed_with_chrom(in_file, tx_out_file, chrom)
return out_file | [
"def",
"subset_bed_by_chrom",
"(",
"in_file",
",",
"chrom",
",",
"data",
",",
"out_dir",
"=",
"None",
")",
":",
"if",
"out_dir",
"is",
"None",
":",
"out_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"in_file",
")",
"base",
",",
"ext",
"=",
"os",... | Subset a BED file to only have items from the specified chromosome. | [
"Subset",
"a",
"BED",
"file",
"to",
"only",
"have",
"items",
"from",
"the",
"specified",
"chromosome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L111-L121 |
224,393 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | remove_lcr_regions | def remove_lcr_regions(orig_bed, items):
"""If configured and available, update a BED file to remove low complexity regions.
"""
lcr_bed = tz.get_in(["genome_resources", "variation", "lcr"], items[0])
if lcr_bed and os.path.exists(lcr_bed) and "lcr" in get_exclude_regions(items):
return _remove_regions(orig_bed, [lcr_bed], "nolcr", items[0])
else:
return orig_bed | python | def remove_lcr_regions(orig_bed, items):
"""If configured and available, update a BED file to remove low complexity regions.
"""
lcr_bed = tz.get_in(["genome_resources", "variation", "lcr"], items[0])
if lcr_bed and os.path.exists(lcr_bed) and "lcr" in get_exclude_regions(items):
return _remove_regions(orig_bed, [lcr_bed], "nolcr", items[0])
else:
return orig_bed | [
"def",
"remove_lcr_regions",
"(",
"orig_bed",
",",
"items",
")",
":",
"lcr_bed",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"genome_resources\"",
",",
"\"variation\"",
",",
"\"lcr\"",
"]",
",",
"items",
"[",
"0",
"]",
")",
"if",
"lcr_bed",
"and",
"os",
".",
... | If configured and available, update a BED file to remove low complexity regions. | [
"If",
"configured",
"and",
"available",
"update",
"a",
"BED",
"file",
"to",
"remove",
"low",
"complexity",
"regions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L143-L150 |
224,394 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | remove_polyx_regions | def remove_polyx_regions(in_file, items):
"""Remove polyX stretches, contributing to long variant runtimes.
"""
ex_bed = tz.get_in(["genome_resources", "variation", "polyx"], items[0])
if ex_bed and os.path.exists(ex_bed):
return _remove_regions(in_file, [ex_bed], "nopolyx", items[0])
else:
return in_file | python | def remove_polyx_regions(in_file, items):
"""Remove polyX stretches, contributing to long variant runtimes.
"""
ex_bed = tz.get_in(["genome_resources", "variation", "polyx"], items[0])
if ex_bed and os.path.exists(ex_bed):
return _remove_regions(in_file, [ex_bed], "nopolyx", items[0])
else:
return in_file | [
"def",
"remove_polyx_regions",
"(",
"in_file",
",",
"items",
")",
":",
"ex_bed",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"genome_resources\"",
",",
"\"variation\"",
",",
"\"polyx\"",
"]",
",",
"items",
"[",
"0",
"]",
")",
"if",
"ex_bed",
"and",
"os",
".",
... | Remove polyX stretches, contributing to long variant runtimes. | [
"Remove",
"polyX",
"stretches",
"contributing",
"to",
"long",
"variant",
"runtimes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L152-L159 |
224,395 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | add_highdepth_genome_exclusion | def add_highdepth_genome_exclusion(items):
"""Add exclusions to input items to avoid slow runtimes on whole genomes.
"""
out = []
for d in items:
d = utils.deepish_copy(d)
if dd.get_coverage_interval(d) == "genome":
e = dd.get_exclude_regions(d)
if "highdepth" not in e:
e.append("highdepth")
d = dd.set_exclude_regions(d, e)
out.append(d)
return out | python | def add_highdepth_genome_exclusion(items):
"""Add exclusions to input items to avoid slow runtimes on whole genomes.
"""
out = []
for d in items:
d = utils.deepish_copy(d)
if dd.get_coverage_interval(d) == "genome":
e = dd.get_exclude_regions(d)
if "highdepth" not in e:
e.append("highdepth")
d = dd.set_exclude_regions(d, e)
out.append(d)
return out | [
"def",
"add_highdepth_genome_exclusion",
"(",
"items",
")",
":",
"out",
"=",
"[",
"]",
"for",
"d",
"in",
"items",
":",
"d",
"=",
"utils",
".",
"deepish_copy",
"(",
"d",
")",
"if",
"dd",
".",
"get_coverage_interval",
"(",
"d",
")",
"==",
"\"genome\"",
"... | Add exclusions to input items to avoid slow runtimes on whole genomes. | [
"Add",
"exclusions",
"to",
"input",
"items",
"to",
"avoid",
"slow",
"runtimes",
"on",
"whole",
"genomes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L161-L173 |
224,396 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | remove_highdepth_regions | def remove_highdepth_regions(in_file, items):
"""Remove high depth regions from a BED file for analyzing a set of calls.
Tries to avoid spurious errors and slow run times in collapsed repeat regions.
Also adds ENCODE blacklist regions which capture additional collapsed repeats
around centromeres.
"""
encode_bed = tz.get_in(["genome_resources", "variation", "encode_blacklist"], items[0])
if encode_bed and os.path.exists(encode_bed):
return _remove_regions(in_file, [encode_bed], "glimit", items[0])
else:
return in_file | python | def remove_highdepth_regions(in_file, items):
"""Remove high depth regions from a BED file for analyzing a set of calls.
Tries to avoid spurious errors and slow run times in collapsed repeat regions.
Also adds ENCODE blacklist regions which capture additional collapsed repeats
around centromeres.
"""
encode_bed = tz.get_in(["genome_resources", "variation", "encode_blacklist"], items[0])
if encode_bed and os.path.exists(encode_bed):
return _remove_regions(in_file, [encode_bed], "glimit", items[0])
else:
return in_file | [
"def",
"remove_highdepth_regions",
"(",
"in_file",
",",
"items",
")",
":",
"encode_bed",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"genome_resources\"",
",",
"\"variation\"",
",",
"\"encode_blacklist\"",
"]",
",",
"items",
"[",
"0",
"]",
")",
"if",
"encode_bed",
... | Remove high depth regions from a BED file for analyzing a set of calls.
Tries to avoid spurious errors and slow run times in collapsed repeat regions.
Also adds ENCODE blacklist regions which capture additional collapsed repeats
around centromeres. | [
"Remove",
"high",
"depth",
"regions",
"from",
"a",
"BED",
"file",
"for",
"analyzing",
"a",
"set",
"of",
"calls",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L175-L187 |
224,397 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | _remove_regions | def _remove_regions(in_file, remove_beds, ext, data):
"""Subtract a list of BED files from an input BED.
General approach handling none, one and more remove_beds.
"""
from bcbio.variation import bedutils
out_file = "%s-%s.bed" % (utils.splitext_plus(in_file)[0], ext)
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
with bedtools_tmpdir(data):
if len(remove_beds) == 0:
to_remove = None
elif len(remove_beds) == 1:
to_remove = remove_beds[0]
else:
to_remove = "%s-all.bed" % utils.splitext_plus(tx_out_file)[0]
with open(to_remove, "w") as out_handle:
for b in remove_beds:
with utils.open_gzipsafe(b) as in_handle:
for line in in_handle:
parts = line.split("\t")
out_handle.write("\t".join(parts[:4]).rstrip() + "\n")
if utils.file_exists(to_remove):
to_remove = bedutils.sort_merge(to_remove, data)
if to_remove and utils.file_exists(to_remove):
cmd = "bedtools subtract -nonamecheck -a {in_file} -b {to_remove} > {tx_out_file}"
do.run(cmd.format(**locals()), "Remove problematic regions: %s" % ext)
else:
utils.symlink_plus(in_file, out_file)
return out_file | python | def _remove_regions(in_file, remove_beds, ext, data):
"""Subtract a list of BED files from an input BED.
General approach handling none, one and more remove_beds.
"""
from bcbio.variation import bedutils
out_file = "%s-%s.bed" % (utils.splitext_plus(in_file)[0], ext)
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
with bedtools_tmpdir(data):
if len(remove_beds) == 0:
to_remove = None
elif len(remove_beds) == 1:
to_remove = remove_beds[0]
else:
to_remove = "%s-all.bed" % utils.splitext_plus(tx_out_file)[0]
with open(to_remove, "w") as out_handle:
for b in remove_beds:
with utils.open_gzipsafe(b) as in_handle:
for line in in_handle:
parts = line.split("\t")
out_handle.write("\t".join(parts[:4]).rstrip() + "\n")
if utils.file_exists(to_remove):
to_remove = bedutils.sort_merge(to_remove, data)
if to_remove and utils.file_exists(to_remove):
cmd = "bedtools subtract -nonamecheck -a {in_file} -b {to_remove} > {tx_out_file}"
do.run(cmd.format(**locals()), "Remove problematic regions: %s" % ext)
else:
utils.symlink_plus(in_file, out_file)
return out_file | [
"def",
"_remove_regions",
"(",
"in_file",
",",
"remove_beds",
",",
"ext",
",",
"data",
")",
":",
"from",
"bcbio",
".",
"variation",
"import",
"bedutils",
"out_file",
"=",
"\"%s-%s.bed\"",
"%",
"(",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"[",
"... | Subtract a list of BED files from an input BED.
General approach handling none, one and more remove_beds. | [
"Subtract",
"a",
"list",
"of",
"BED",
"files",
"from",
"an",
"input",
"BED",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L189-L218 |
224,398 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | get_exclude_regions | def get_exclude_regions(items):
"""Retrieve regions to exclude from a set of items.
Includes back compatibility for older custom ways of specifying different
exclusions.
"""
def _get_sample_excludes(d):
excludes = dd.get_exclude_regions(d)
# back compatible
if tz.get_in(("config", "algorithm", "remove_lcr"), d, False):
excludes.append("lcr")
return excludes
out = reduce(operator.add, [_get_sample_excludes(d) for d in items])
return sorted(list(set(out))) | python | def get_exclude_regions(items):
"""Retrieve regions to exclude from a set of items.
Includes back compatibility for older custom ways of specifying different
exclusions.
"""
def _get_sample_excludes(d):
excludes = dd.get_exclude_regions(d)
# back compatible
if tz.get_in(("config", "algorithm", "remove_lcr"), d, False):
excludes.append("lcr")
return excludes
out = reduce(operator.add, [_get_sample_excludes(d) for d in items])
return sorted(list(set(out))) | [
"def",
"get_exclude_regions",
"(",
"items",
")",
":",
"def",
"_get_sample_excludes",
"(",
"d",
")",
":",
"excludes",
"=",
"dd",
".",
"get_exclude_regions",
"(",
"d",
")",
"# back compatible",
"if",
"tz",
".",
"get_in",
"(",
"(",
"\"config\"",
",",
"\"algorit... | Retrieve regions to exclude from a set of items.
Includes back compatibility for older custom ways of specifying different
exclusions. | [
"Retrieve",
"regions",
"to",
"exclude",
"from",
"a",
"set",
"of",
"items",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L231-L244 |
224,399 | bcbio/bcbio-nextgen | bcbio/pipeline/shared.py | to_multiregion | def to_multiregion(region):
"""Convert a single region or multiple region specification into multiregion list.
If a single region (chrom, start, end), returns [(chrom, start, end)]
otherwise returns multiregion.
"""
assert isinstance(region, (list, tuple)), region
if isinstance(region[0], (list, tuple)):
return region
else:
assert len(region) == 3
return [tuple(region)] | python | def to_multiregion(region):
"""Convert a single region or multiple region specification into multiregion list.
If a single region (chrom, start, end), returns [(chrom, start, end)]
otherwise returns multiregion.
"""
assert isinstance(region, (list, tuple)), region
if isinstance(region[0], (list, tuple)):
return region
else:
assert len(region) == 3
return [tuple(region)] | [
"def",
"to_multiregion",
"(",
"region",
")",
":",
"assert",
"isinstance",
"(",
"region",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"region",
"if",
"isinstance",
"(",
"region",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"retu... | Convert a single region or multiple region specification into multiregion list.
If a single region (chrom, start, end), returns [(chrom, start, end)]
otherwise returns multiregion. | [
"Convert",
"a",
"single",
"region",
"or",
"multiple",
"region",
"specification",
"into",
"multiregion",
"list",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L261-L272 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.