id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
238,100
bcbio/bcbio-nextgen
bcbio/pipeline/qcsummary.py
_merge_metadata
def _merge_metadata(samples): """Merge all metadata into CSV file""" samples = list(utils.flatten(samples)) out_dir = dd.get_work_dir(samples[0]) logger.info("summarize metadata") out_file = os.path.join(out_dir, "metadata.csv") sample_metrics = collections.defaultdict(dict) for s in samples: m = tz.get_in(['metadata'], s) if isinstance(m, six.string_types): m = json.loads(m) if m: for me in list(m.keys()): if isinstance(m[me], list) or isinstance(m[me], dict) or isinstance(m[me], tuple): m.pop(me, None) sample_metrics[dd.get_sample_name(s)].update(m) pd.DataFrame(sample_metrics).transpose().to_csv(out_file) return out_file
python
def _merge_metadata(samples): samples = list(utils.flatten(samples)) out_dir = dd.get_work_dir(samples[0]) logger.info("summarize metadata") out_file = os.path.join(out_dir, "metadata.csv") sample_metrics = collections.defaultdict(dict) for s in samples: m = tz.get_in(['metadata'], s) if isinstance(m, six.string_types): m = json.loads(m) if m: for me in list(m.keys()): if isinstance(m[me], list) or isinstance(m[me], dict) or isinstance(m[me], tuple): m.pop(me, None) sample_metrics[dd.get_sample_name(s)].update(m) pd.DataFrame(sample_metrics).transpose().to_csv(out_file) return out_file
[ "def", "_merge_metadata", "(", "samples", ")", ":", "samples", "=", "list", "(", "utils", ".", "flatten", "(", "samples", ")", ")", "out_dir", "=", "dd", ".", "get_work_dir", "(", "samples", "[", "0", "]", ")", "logger", ".", "info", "(", "\"summarize ...
Merge all metadata into CSV file
[ "Merge", "all", "metadata", "into", "CSV", "file" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/qcsummary.py#L297-L314
238,101
bcbio/bcbio-nextgen
bcbio/pipeline/qcsummary.py
_other_pipeline_samples
def _other_pipeline_samples(summary_file, cur_samples): """Retrieve samples produced previously by another pipeline in the summary output. """ cur_descriptions = set([s[0]["description"] for s in cur_samples]) out = [] if utils.file_exists(summary_file): with open(summary_file) as in_handle: for s in yaml.safe_load(in_handle).get("samples", []): if s["description"] not in cur_descriptions: out.append(s) return out
python
def _other_pipeline_samples(summary_file, cur_samples): cur_descriptions = set([s[0]["description"] for s in cur_samples]) out = [] if utils.file_exists(summary_file): with open(summary_file) as in_handle: for s in yaml.safe_load(in_handle).get("samples", []): if s["description"] not in cur_descriptions: out.append(s) return out
[ "def", "_other_pipeline_samples", "(", "summary_file", ",", "cur_samples", ")", ":", "cur_descriptions", "=", "set", "(", "[", "s", "[", "0", "]", "[", "\"description\"", "]", "for", "s", "in", "cur_samples", "]", ")", "out", "=", "[", "]", "if", "utils"...
Retrieve samples produced previously by another pipeline in the summary output.
[ "Retrieve", "samples", "produced", "previously", "by", "another", "pipeline", "in", "the", "summary", "output", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/qcsummary.py#L316-L326
238,102
bcbio/bcbio-nextgen
bcbio/pipeline/qcsummary.py
_add_researcher_summary
def _add_researcher_summary(samples, summary_yaml): """Generate summary files per researcher if organized via a LIMS. """ by_researcher = collections.defaultdict(list) for data in (x[0] for x in samples): researcher = utils.get_in(data, ("upload", "researcher")) if researcher: by_researcher[researcher].append(data["description"]) out_by_researcher = {} for researcher, descrs in by_researcher.items(): out_by_researcher[researcher] = _summary_csv_by_researcher(summary_yaml, researcher, set(descrs), samples[0][0]) out = [] for data in (x[0] for x in samples): researcher = utils.get_in(data, ("upload", "researcher")) if researcher: data["summary"]["researcher"] = out_by_researcher[researcher] out.append([data]) return out
python
def _add_researcher_summary(samples, summary_yaml): by_researcher = collections.defaultdict(list) for data in (x[0] for x in samples): researcher = utils.get_in(data, ("upload", "researcher")) if researcher: by_researcher[researcher].append(data["description"]) out_by_researcher = {} for researcher, descrs in by_researcher.items(): out_by_researcher[researcher] = _summary_csv_by_researcher(summary_yaml, researcher, set(descrs), samples[0][0]) out = [] for data in (x[0] for x in samples): researcher = utils.get_in(data, ("upload", "researcher")) if researcher: data["summary"]["researcher"] = out_by_researcher[researcher] out.append([data]) return out
[ "def", "_add_researcher_summary", "(", "samples", ",", "summary_yaml", ")", ":", "by_researcher", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "data", "in", "(", "x", "[", "0", "]", "for", "x", "in", "samples", ")", ":", "researcher", ...
Generate summary files per researcher if organized via a LIMS.
[ "Generate", "summary", "files", "per", "researcher", "if", "organized", "via", "a", "LIMS", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/qcsummary.py#L338-L356
238,103
bcbio/bcbio-nextgen
bcbio/pipeline/qcsummary.py
_summary_csv_by_researcher
def _summary_csv_by_researcher(summary_yaml, researcher, descrs, data): """Generate a CSV file with summary information for a researcher on this project. """ out_file = os.path.join(utils.safe_makedir(os.path.join(data["dirs"]["work"], "researcher")), "%s-summary.tsv" % run_info.clean_name(researcher)) metrics = ["Total_reads", "Mapped_reads", "Mapped_reads_pct", "Duplicates", "Duplicates_pct"] with open(summary_yaml) as in_handle: with open(out_file, "w") as out_handle: writer = csv.writer(out_handle, dialect="excel-tab") writer.writerow(["Name"] + metrics) for sample in yaml.safe_load(in_handle)["samples"]: if sample["description"] in descrs: row = [sample["description"]] + [utils.get_in(sample, ("summary", "metrics", x), "") for x in metrics] writer.writerow(row) return out_file
python
def _summary_csv_by_researcher(summary_yaml, researcher, descrs, data): out_file = os.path.join(utils.safe_makedir(os.path.join(data["dirs"]["work"], "researcher")), "%s-summary.tsv" % run_info.clean_name(researcher)) metrics = ["Total_reads", "Mapped_reads", "Mapped_reads_pct", "Duplicates", "Duplicates_pct"] with open(summary_yaml) as in_handle: with open(out_file, "w") as out_handle: writer = csv.writer(out_handle, dialect="excel-tab") writer.writerow(["Name"] + metrics) for sample in yaml.safe_load(in_handle)["samples"]: if sample["description"] in descrs: row = [sample["description"]] + [utils.get_in(sample, ("summary", "metrics", x), "") for x in metrics] writer.writerow(row) return out_file
[ "def", "_summary_csv_by_researcher", "(", "summary_yaml", ",", "researcher", ",", "descrs", ",", "data", ")", ":", "out_file", "=", "os", ".", "path", ".", "join", "(", "utils", ".", "safe_makedir", "(", "os", ".", "path", ".", "join", "(", "data", "[", ...
Generate a CSV file with summary information for a researcher on this project.
[ "Generate", "a", "CSV", "file", "with", "summary", "information", "for", "a", "researcher", "on", "this", "project", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/qcsummary.py#L358-L373
238,104
bcbio/bcbio-nextgen
bcbio/pipeline/qcsummary.py
prep_pdf
def prep_pdf(qc_dir, config): """Create PDF from HTML summary outputs in QC directory. Requires wkhtmltopdf installed: http://www.msweet.org/projects.php?Z1 Thanks to: https://www.biostars.org/p/16991/ Works around issues with CSS conversion on CentOS by adjusting CSS. """ html_file = os.path.join(qc_dir, "fastqc", "fastqc_report.html") html_fixed = "%s-fixed%s" % os.path.splitext(html_file) try: topdf = config_utils.get_program("wkhtmltopdf", config) except config_utils.CmdNotFound: topdf = None if topdf and utils.file_exists(html_file): out_file = "%s.pdf" % os.path.splitext(html_file)[0] if not utils.file_exists(out_file): cmd = ("sed 's/div.summary/div.summary-no/' %s | sed 's/div.main/div.main-no/' > %s" % (html_file, html_fixed)) do.run(cmd, "Fix fastqc CSS to be compatible with wkhtmltopdf") cmd = [topdf, html_fixed, out_file] do.run(cmd, "Convert QC HTML to PDF") return out_file
python
def prep_pdf(qc_dir, config): html_file = os.path.join(qc_dir, "fastqc", "fastqc_report.html") html_fixed = "%s-fixed%s" % os.path.splitext(html_file) try: topdf = config_utils.get_program("wkhtmltopdf", config) except config_utils.CmdNotFound: topdf = None if topdf and utils.file_exists(html_file): out_file = "%s.pdf" % os.path.splitext(html_file)[0] if not utils.file_exists(out_file): cmd = ("sed 's/div.summary/div.summary-no/' %s | sed 's/div.main/div.main-no/' > %s" % (html_file, html_fixed)) do.run(cmd, "Fix fastqc CSS to be compatible with wkhtmltopdf") cmd = [topdf, html_fixed, out_file] do.run(cmd, "Convert QC HTML to PDF") return out_file
[ "def", "prep_pdf", "(", "qc_dir", ",", "config", ")", ":", "html_file", "=", "os", ".", "path", ".", "join", "(", "qc_dir", ",", "\"fastqc\"", ",", "\"fastqc_report.html\"", ")", "html_fixed", "=", "\"%s-fixed%s\"", "%", "os", ".", "path", ".", "splitext",...
Create PDF from HTML summary outputs in QC directory. Requires wkhtmltopdf installed: http://www.msweet.org/projects.php?Z1 Thanks to: https://www.biostars.org/p/16991/ Works around issues with CSS conversion on CentOS by adjusting CSS.
[ "Create", "PDF", "from", "HTML", "summary", "outputs", "in", "QC", "directory", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/qcsummary.py#L377-L399
238,105
bcbio/bcbio-nextgen
bcbio/structural/purecn.py
_run_purecn_dx
def _run_purecn_dx(out, paired): """Extract signatures and mutational burdens from PureCN rds file. """ out_base, out, all_files = _get_purecn_dx_files(paired, out) if not utils.file_uptodate(out["mutation_burden"], out["rds"]): with file_transaction(paired.tumor_data, out_base) as tx_out_base: cmd = ["PureCN_Dx.R", "--rds", out["rds"], "--callable", dd.get_sample_callable(paired.tumor_data), "--signatures", "--out", tx_out_base] do.run(cmd, "PureCN Dx mutational burden and signatures") for f in all_files: if os.path.exists(os.path.join(os.path.dirname(tx_out_base), f)): shutil.move(os.path.join(os.path.dirname(tx_out_base), f), os.path.join(os.path.dirname(out_base), f)) return out
python
def _run_purecn_dx(out, paired): out_base, out, all_files = _get_purecn_dx_files(paired, out) if not utils.file_uptodate(out["mutation_burden"], out["rds"]): with file_transaction(paired.tumor_data, out_base) as tx_out_base: cmd = ["PureCN_Dx.R", "--rds", out["rds"], "--callable", dd.get_sample_callable(paired.tumor_data), "--signatures", "--out", tx_out_base] do.run(cmd, "PureCN Dx mutational burden and signatures") for f in all_files: if os.path.exists(os.path.join(os.path.dirname(tx_out_base), f)): shutil.move(os.path.join(os.path.dirname(tx_out_base), f), os.path.join(os.path.dirname(out_base), f)) return out
[ "def", "_run_purecn_dx", "(", "out", ",", "paired", ")", ":", "out_base", ",", "out", ",", "all_files", "=", "_get_purecn_dx_files", "(", "paired", ",", "out", ")", "if", "not", "utils", ".", "file_uptodate", "(", "out", "[", "\"mutation_burden\"", "]", ",...
Extract signatures and mutational burdens from PureCN rds file.
[ "Extract", "signatures", "and", "mutational", "burdens", "from", "PureCN", "rds", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purecn.py#L49-L62
238,106
bcbio/bcbio-nextgen
bcbio/structural/purecn.py
_get_purecn_dx_files
def _get_purecn_dx_files(paired, out): """Retrieve files generated by PureCN_Dx """ out_base = "%s-dx" % utils.splitext_plus(out["rds"])[0] all_files = [] for key, ext in [[("mutation_burden",), "_mutation_burden.csv"], [("plot", "signatures"), "_signatures.pdf"], [("signatures",), "_signatures.csv"]]: cur_file = "%s%s" % (out_base, ext) out = tz.update_in(out, key, lambda x: cur_file) all_files.append(os.path.basename(cur_file)) return out_base, out, all_files
python
def _get_purecn_dx_files(paired, out): out_base = "%s-dx" % utils.splitext_plus(out["rds"])[0] all_files = [] for key, ext in [[("mutation_burden",), "_mutation_burden.csv"], [("plot", "signatures"), "_signatures.pdf"], [("signatures",), "_signatures.csv"]]: cur_file = "%s%s" % (out_base, ext) out = tz.update_in(out, key, lambda x: cur_file) all_files.append(os.path.basename(cur_file)) return out_base, out, all_files
[ "def", "_get_purecn_dx_files", "(", "paired", ",", "out", ")", ":", "out_base", "=", "\"%s-dx\"", "%", "utils", ".", "splitext_plus", "(", "out", "[", "\"rds\"", "]", ")", "[", "0", "]", "all_files", "=", "[", "]", "for", "key", ",", "ext", "in", "["...
Retrieve files generated by PureCN_Dx
[ "Retrieve", "files", "generated", "by", "PureCN_Dx" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purecn.py#L64-L75
238,107
bcbio/bcbio-nextgen
bcbio/structural/purecn.py
_run_purecn
def _run_purecn(paired, work_dir): """Run PureCN.R wrapper with pre-segmented CNVkit or GATK4 inputs. """ segfns = {"cnvkit": _segment_normalized_cnvkit, "gatk-cnv": _segment_normalized_gatk} out_base, out, all_files = _get_purecn_files(paired, work_dir) failed_file = out_base + "-failed.log" cnr_file = tz.get_in(["depth", "bins", "normalized"], paired.tumor_data) if not utils.file_uptodate(out["rds"], cnr_file) and not utils.file_exists(failed_file): cnr_file, seg_file = segfns[cnvkit.bin_approach(paired.tumor_data)](cnr_file, work_dir, paired) from bcbio import heterogeneity vcf_file = heterogeneity.get_variants(paired.tumor_data, include_germline=False)[0]["vrn_file"] vcf_file = germline.filter_to_pass_and_reject(vcf_file, paired, out_dir=work_dir) with file_transaction(paired.tumor_data, out_base) as tx_out_base: # Use UCSC style naming for human builds to support BSgenome genome = ("hg19" if dd.get_genome_build(paired.tumor_data) in ["GRCh37", "hg19"] else dd.get_genome_build(paired.tumor_data)) cmd = ["PureCN.R", "--seed", "42", "--out", tx_out_base, "--rds", "%s.rds" % tx_out_base, "--sampleid", dd.get_sample_name(paired.tumor_data), "--genome", genome, "--vcf", vcf_file, "--tumor", cnr_file, "--segfile", seg_file, "--funsegmentation", "Hclust", "--maxnonclonal", "0.3"] if dd.get_num_cores(paired.tumor_data) > 1: cmd += ["--cores", str(dd.get_num_cores(paired.tumor_data))] try: cmd = "export R_LIBS_USER=%s && %s && %s" % (utils.R_sitelib(), utils.get_R_exports(), " ".join([str(x) for x in cmd])) do.run(cmd, "PureCN copy number calling") except subprocess.CalledProcessError as msg: if _allowed_errors(str(msg)): logger.info("PureCN failed to find solution for %s: skipping" % dd.get_sample_name(paired.tumor_data)) with open(failed_file, "w") as out_handle: out_handle.write(str(msg)) else: logger.exception() raise for f in all_files: if os.path.exists(os.path.join(os.path.dirname(tx_out_base), f)): shutil.move(os.path.join(os.path.dirname(tx_out_base), f), os.path.join(os.path.dirname(out_base), f)) out = _get_purecn_files(paired, work_dir, require_exist=True)[1] return out if (out.get("rds") and os.path.exists(out["rds"])) else None
python
def _run_purecn(paired, work_dir): segfns = {"cnvkit": _segment_normalized_cnvkit, "gatk-cnv": _segment_normalized_gatk} out_base, out, all_files = _get_purecn_files(paired, work_dir) failed_file = out_base + "-failed.log" cnr_file = tz.get_in(["depth", "bins", "normalized"], paired.tumor_data) if not utils.file_uptodate(out["rds"], cnr_file) and not utils.file_exists(failed_file): cnr_file, seg_file = segfns[cnvkit.bin_approach(paired.tumor_data)](cnr_file, work_dir, paired) from bcbio import heterogeneity vcf_file = heterogeneity.get_variants(paired.tumor_data, include_germline=False)[0]["vrn_file"] vcf_file = germline.filter_to_pass_and_reject(vcf_file, paired, out_dir=work_dir) with file_transaction(paired.tumor_data, out_base) as tx_out_base: # Use UCSC style naming for human builds to support BSgenome genome = ("hg19" if dd.get_genome_build(paired.tumor_data) in ["GRCh37", "hg19"] else dd.get_genome_build(paired.tumor_data)) cmd = ["PureCN.R", "--seed", "42", "--out", tx_out_base, "--rds", "%s.rds" % tx_out_base, "--sampleid", dd.get_sample_name(paired.tumor_data), "--genome", genome, "--vcf", vcf_file, "--tumor", cnr_file, "--segfile", seg_file, "--funsegmentation", "Hclust", "--maxnonclonal", "0.3"] if dd.get_num_cores(paired.tumor_data) > 1: cmd += ["--cores", str(dd.get_num_cores(paired.tumor_data))] try: cmd = "export R_LIBS_USER=%s && %s && %s" % (utils.R_sitelib(), utils.get_R_exports(), " ".join([str(x) for x in cmd])) do.run(cmd, "PureCN copy number calling") except subprocess.CalledProcessError as msg: if _allowed_errors(str(msg)): logger.info("PureCN failed to find solution for %s: skipping" % dd.get_sample_name(paired.tumor_data)) with open(failed_file, "w") as out_handle: out_handle.write(str(msg)) else: logger.exception() raise for f in all_files: if os.path.exists(os.path.join(os.path.dirname(tx_out_base), f)): shutil.move(os.path.join(os.path.dirname(tx_out_base), f), os.path.join(os.path.dirname(out_base), f)) out = _get_purecn_files(paired, work_dir, require_exist=True)[1] return out if (out.get("rds") and os.path.exists(out["rds"])) else None
[ "def", "_run_purecn", "(", "paired", ",", "work_dir", ")", ":", "segfns", "=", "{", "\"cnvkit\"", ":", "_segment_normalized_cnvkit", ",", "\"gatk-cnv\"", ":", "_segment_normalized_gatk", "}", "out_base", ",", "out", ",", "all_files", "=", "_get_purecn_files", "(",...
Run PureCN.R wrapper with pre-segmented CNVkit or GATK4 inputs.
[ "Run", "PureCN", ".", "R", "wrapper", "with", "pre", "-", "segmented", "CNVkit", "or", "GATK4", "inputs", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purecn.py#L77-L118
238,108
bcbio/bcbio-nextgen
bcbio/structural/purecn.py
_segment_normalized_gatk
def _segment_normalized_gatk(cnr_file, work_dir, paired): """Segmentation of normalized inputs using GATK4, converting into standard input formats. """ work_dir = utils.safe_makedir(os.path.join(work_dir, "gatk-cnv")) seg_file = gatkcnv.model_segments(cnr_file, work_dir, paired)["seg"] std_seg_file = seg_file.replace(".cr.seg", ".seg") if not utils.file_uptodate(std_seg_file, seg_file): with file_transaction(std_seg_file) as tx_out_file: df = pd.read_csv(seg_file, sep="\t", comment="@", header=0, names=["chrom", "loc.start", "loc.end", "num.mark", "seg.mean"]) df.insert(0, "ID", [dd.get_sample_name(paired.tumor_data)] * len(df)) df.to_csv(tx_out_file, sep="\t", header=True, index=False) std_cnr_file = os.path.join(work_dir, "%s.cnr" % dd.get_sample_name(paired.tumor_data)) if not utils.file_uptodate(std_cnr_file, cnr_file): with file_transaction(std_cnr_file) as tx_out_file: logdf = pd.read_csv(cnr_file, sep="\t", comment="@", header=0, names=["chrom", "start", "end", "log2"]) covdf = pd.read_csv(tz.get_in(["depth", "bins", "antitarget"], paired.tumor_data), sep="\t", header=None, names=["chrom", "start", "end", "orig.name", "depth", "gene"]) df = pd.merge(logdf, covdf, on=["chrom", "start", "end"]) del df["orig.name"] df = df[["chrom", "start", "end", "gene", "log2", "depth"]] df.insert(6, "weight", [1.0] * len(df)) df.to_csv(tx_out_file, sep="\t", header=True, index=False) return std_cnr_file, std_seg_file
python
def _segment_normalized_gatk(cnr_file, work_dir, paired): work_dir = utils.safe_makedir(os.path.join(work_dir, "gatk-cnv")) seg_file = gatkcnv.model_segments(cnr_file, work_dir, paired)["seg"] std_seg_file = seg_file.replace(".cr.seg", ".seg") if not utils.file_uptodate(std_seg_file, seg_file): with file_transaction(std_seg_file) as tx_out_file: df = pd.read_csv(seg_file, sep="\t", comment="@", header=0, names=["chrom", "loc.start", "loc.end", "num.mark", "seg.mean"]) df.insert(0, "ID", [dd.get_sample_name(paired.tumor_data)] * len(df)) df.to_csv(tx_out_file, sep="\t", header=True, index=False) std_cnr_file = os.path.join(work_dir, "%s.cnr" % dd.get_sample_name(paired.tumor_data)) if not utils.file_uptodate(std_cnr_file, cnr_file): with file_transaction(std_cnr_file) as tx_out_file: logdf = pd.read_csv(cnr_file, sep="\t", comment="@", header=0, names=["chrom", "start", "end", "log2"]) covdf = pd.read_csv(tz.get_in(["depth", "bins", "antitarget"], paired.tumor_data), sep="\t", header=None, names=["chrom", "start", "end", "orig.name", "depth", "gene"]) df = pd.merge(logdf, covdf, on=["chrom", "start", "end"]) del df["orig.name"] df = df[["chrom", "start", "end", "gene", "log2", "depth"]] df.insert(6, "weight", [1.0] * len(df)) df.to_csv(tx_out_file, sep="\t", header=True, index=False) return std_cnr_file, std_seg_file
[ "def", "_segment_normalized_gatk", "(", "cnr_file", ",", "work_dir", ",", "paired", ")", ":", "work_dir", "=", "utils", ".", "safe_makedir", "(", "os", ".", "path", ".", "join", "(", "work_dir", ",", "\"gatk-cnv\"", ")", ")", "seg_file", "=", "gatkcnv", "....
Segmentation of normalized inputs using GATK4, converting into standard input formats.
[ "Segmentation", "of", "normalized", "inputs", "using", "GATK4", "converting", "into", "standard", "input", "formats", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purecn.py#L126-L151
238,109
bcbio/bcbio-nextgen
bcbio/structural/purecn.py
_segment_normalized_cnvkit
def _segment_normalized_cnvkit(cnr_file, work_dir, paired): """Segmentation of normalized inputs using CNVkit. """ cnvkit_base = os.path.join(utils.safe_makedir(os.path.join(work_dir, "cnvkit")), dd.get_sample_name(paired.tumor_data)) cnr_file = chromhacks.bed_to_standardonly(cnr_file, paired.tumor_data, headers="chromosome", include_sex_chroms=True, out_dir=os.path.dirname(cnvkit_base)) cnr_file = _remove_overlaps(cnr_file, os.path.dirname(cnvkit_base), paired.tumor_data) seg_file = cnvkit.segment_from_cnr(cnr_file, paired.tumor_data, cnvkit_base) return cnr_file, seg_file
python
def _segment_normalized_cnvkit(cnr_file, work_dir, paired): cnvkit_base = os.path.join(utils.safe_makedir(os.path.join(work_dir, "cnvkit")), dd.get_sample_name(paired.tumor_data)) cnr_file = chromhacks.bed_to_standardonly(cnr_file, paired.tumor_data, headers="chromosome", include_sex_chroms=True, out_dir=os.path.dirname(cnvkit_base)) cnr_file = _remove_overlaps(cnr_file, os.path.dirname(cnvkit_base), paired.tumor_data) seg_file = cnvkit.segment_from_cnr(cnr_file, paired.tumor_data, cnvkit_base) return cnr_file, seg_file
[ "def", "_segment_normalized_cnvkit", "(", "cnr_file", ",", "work_dir", ",", "paired", ")", ":", "cnvkit_base", "=", "os", ".", "path", ".", "join", "(", "utils", ".", "safe_makedir", "(", "os", ".", "path", ".", "join", "(", "work_dir", ",", "\"cnvkit\"", ...
Segmentation of normalized inputs using CNVkit.
[ "Segmentation", "of", "normalized", "inputs", "using", "CNVkit", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purecn.py#L153-L163
238,110
bcbio/bcbio-nextgen
bcbio/structural/purecn.py
_remove_overlaps
def _remove_overlaps(in_file, out_dir, data): """Remove regions that overlap with next region, these result in issues with PureCN. """ out_file = os.path.join(out_dir, "%s-nooverlaps%s" % utils.splitext_plus(os.path.basename(in_file))) if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: with open(in_file) as in_handle: with open(tx_out_file, "w") as out_handle: prev_line = None for line in in_handle: if prev_line: pchrom, pstart, pend = prev_line.split("\t", 4)[:3] cchrom, cstart, cend = line.split("\t", 4)[:3] # Skip if chromosomes match and end overlaps start if pchrom == cchrom and int(pend) > int(cstart): pass else: out_handle.write(prev_line) prev_line = line out_handle.write(prev_line) return out_file
python
def _remove_overlaps(in_file, out_dir, data): out_file = os.path.join(out_dir, "%s-nooverlaps%s" % utils.splitext_plus(os.path.basename(in_file))) if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: with open(in_file) as in_handle: with open(tx_out_file, "w") as out_handle: prev_line = None for line in in_handle: if prev_line: pchrom, pstart, pend = prev_line.split("\t", 4)[:3] cchrom, cstart, cend = line.split("\t", 4)[:3] # Skip if chromosomes match and end overlaps start if pchrom == cchrom and int(pend) > int(cstart): pass else: out_handle.write(prev_line) prev_line = line out_handle.write(prev_line) return out_file
[ "def", "_remove_overlaps", "(", "in_file", ",", "out_dir", ",", "data", ")", ":", "out_file", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "\"%s-nooverlaps%s\"", "%", "utils", ".", "splitext_plus", "(", "os", ".", "path", ".", "basename", "(...
Remove regions that overlap with next region, these result in issues with PureCN.
[ "Remove", "regions", "that", "overlap", "with", "next", "region", "these", "result", "in", "issues", "with", "PureCN", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purecn.py#L165-L185
238,111
bcbio/bcbio-nextgen
bcbio/structural/purecn.py
_get_purecn_files
def _get_purecn_files(paired, work_dir, require_exist=False): """Retrieve organized structure of PureCN output files. """ out_base = os.path.join(work_dir, "%s-purecn" % (dd.get_sample_name(paired.tumor_data))) out = {"plot": {}} all_files = [] for plot in ["chromosomes", "local_optima", "segmentation", "summary"]: if plot == "summary": cur_file = "%s.pdf" % out_base else: cur_file = "%s_%s.pdf" % (out_base, plot) if not require_exist or os.path.exists(cur_file): out["plot"][plot] = cur_file all_files.append(os.path.basename(cur_file)) for key, ext in [["hetsummary", ".csv"], ["dnacopy", "_dnacopy.seg"], ["genes", "_genes.csv"], ["log", ".log"], ["loh", "_loh.csv"], ["rds", ".rds"], ["variants", "_variants.csv"]]: cur_file = "%s%s" % (out_base, ext) if not require_exist or os.path.exists(cur_file): out[key] = cur_file all_files.append(os.path.basename(cur_file)) return out_base, out, all_files
python
def _get_purecn_files(paired, work_dir, require_exist=False): out_base = os.path.join(work_dir, "%s-purecn" % (dd.get_sample_name(paired.tumor_data))) out = {"plot": {}} all_files = [] for plot in ["chromosomes", "local_optima", "segmentation", "summary"]: if plot == "summary": cur_file = "%s.pdf" % out_base else: cur_file = "%s_%s.pdf" % (out_base, plot) if not require_exist or os.path.exists(cur_file): out["plot"][plot] = cur_file all_files.append(os.path.basename(cur_file)) for key, ext in [["hetsummary", ".csv"], ["dnacopy", "_dnacopy.seg"], ["genes", "_genes.csv"], ["log", ".log"], ["loh", "_loh.csv"], ["rds", ".rds"], ["variants", "_variants.csv"]]: cur_file = "%s%s" % (out_base, ext) if not require_exist or os.path.exists(cur_file): out[key] = cur_file all_files.append(os.path.basename(cur_file)) return out_base, out, all_files
[ "def", "_get_purecn_files", "(", "paired", ",", "work_dir", ",", "require_exist", "=", "False", ")", ":", "out_base", "=", "os", ".", "path", ".", "join", "(", "work_dir", ",", "\"%s-purecn\"", "%", "(", "dd", ".", "get_sample_name", "(", "paired", ".", ...
Retrieve organized structure of PureCN output files.
[ "Retrieve", "organized", "structure", "of", "PureCN", "output", "files", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purecn.py#L187-L208
238,112
bcbio/bcbio-nextgen
bcbio/structural/purecn.py
_loh_to_vcf
def _loh_to_vcf(cur): """Convert LOH output into standardized VCF. """ cn = int(float(cur["C"])) minor_cn = int(float(cur["M"])) if cur["type"].find("LOH"): svtype = "LOH" elif cn > 2: svtype = "DUP" elif cn < 1: svtype = "DEL" else: svtype = None if svtype: info = ["SVTYPE=%s" % svtype, "END=%s" % cur["end"], "SVLEN=%s" % (int(cur["end"]) - int(cur["start"])), "CN=%s" % cn, "MajorCN=%s" % (cn - minor_cn), "MinorCN=%s" % minor_cn] return [cur["chr"], cur["start"], ".", "N", "<%s>" % svtype, ".", ".", ";".join(info), "GT", "0/1"]
python
def _loh_to_vcf(cur): cn = int(float(cur["C"])) minor_cn = int(float(cur["M"])) if cur["type"].find("LOH"): svtype = "LOH" elif cn > 2: svtype = "DUP" elif cn < 1: svtype = "DEL" else: svtype = None if svtype: info = ["SVTYPE=%s" % svtype, "END=%s" % cur["end"], "SVLEN=%s" % (int(cur["end"]) - int(cur["start"])), "CN=%s" % cn, "MajorCN=%s" % (cn - minor_cn), "MinorCN=%s" % minor_cn] return [cur["chr"], cur["start"], ".", "N", "<%s>" % svtype, ".", ".", ";".join(info), "GT", "0/1"]
[ "def", "_loh_to_vcf", "(", "cur", ")", ":", "cn", "=", "int", "(", "float", "(", "cur", "[", "\"C\"", "]", ")", ")", "minor_cn", "=", "int", "(", "float", "(", "cur", "[", "\"M\"", "]", ")", ")", "if", "cur", "[", "\"type\"", "]", ".", "find", ...
Convert LOH output into standardized VCF.
[ "Convert", "LOH", "output", "into", "standardized", "VCF", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purecn.py#L219-L237
238,113
bcbio/bcbio-nextgen
scripts/utils/collect_metrics_to_csv.py
_generate_metrics
def _generate_metrics(bam_fname, config_file, ref_file, bait_file, target_file): """Run Picard commands to generate metrics files when missing. """ with open(config_file) as in_handle: config = yaml.safe_load(in_handle) broad_runner = broad.runner_from_config(config) bam_fname = os.path.abspath(bam_fname) path = os.path.dirname(bam_fname) out_dir = os.path.join(path, "metrics") utils.safe_makedir(out_dir) with utils.chdir(out_dir): with tx_tmpdir() as tmp_dir: cur_bam = os.path.basename(bam_fname) if not os.path.exists(cur_bam): os.symlink(bam_fname, cur_bam) gen_metrics = PicardMetrics(broad_runner, tmp_dir) gen_metrics.report(cur_bam, ref_file, _bam_is_paired(bam_fname), bait_file, target_file) return out_dir
python
def _generate_metrics(bam_fname, config_file, ref_file, bait_file, target_file): with open(config_file) as in_handle: config = yaml.safe_load(in_handle) broad_runner = broad.runner_from_config(config) bam_fname = os.path.abspath(bam_fname) path = os.path.dirname(bam_fname) out_dir = os.path.join(path, "metrics") utils.safe_makedir(out_dir) with utils.chdir(out_dir): with tx_tmpdir() as tmp_dir: cur_bam = os.path.basename(bam_fname) if not os.path.exists(cur_bam): os.symlink(bam_fname, cur_bam) gen_metrics = PicardMetrics(broad_runner, tmp_dir) gen_metrics.report(cur_bam, ref_file, _bam_is_paired(bam_fname), bait_file, target_file) return out_dir
[ "def", "_generate_metrics", "(", "bam_fname", ",", "config_file", ",", "ref_file", ",", "bait_file", ",", "target_file", ")", ":", "with", "open", "(", "config_file", ")", "as", "in_handle", ":", "config", "=", "yaml", ".", "safe_load", "(", "in_handle", ")"...
Run Picard commands to generate metrics files when missing.
[ "Run", "Picard", "commands", "to", "generate", "metrics", "files", "when", "missing", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/collect_metrics_to_csv.py#L135-L155
238,114
bcbio/bcbio-nextgen
bcbio/structural/gatkcnv.py
run
def run(items, background=None): """Detect copy number variations from batched set of samples using GATK4 CNV calling. TODO: implement germline calling with DetermineGermlineContigPloidy and GermlineCNVCaller """ if not background: background = [] paired = vcfutils.get_paired(items + background) if paired: out = _run_paired(paired) else: out = items logger.warn("GATK4 CNV calling currently only available for somatic samples: %s" % ", ".join([dd.get_sample_name(d) for d in items + background])) return out
python
def run(items, background=None): if not background: background = [] paired = vcfutils.get_paired(items + background) if paired: out = _run_paired(paired) else: out = items logger.warn("GATK4 CNV calling currently only available for somatic samples: %s" % ", ".join([dd.get_sample_name(d) for d in items + background])) return out
[ "def", "run", "(", "items", ",", "background", "=", "None", ")", ":", "if", "not", "background", ":", "background", "=", "[", "]", "paired", "=", "vcfutils", ".", "get_paired", "(", "items", "+", "background", ")", "if", "paired", ":", "out", "=", "_...
Detect copy number variations from batched set of samples using GATK4 CNV calling. TODO: implement germline calling with DetermineGermlineContigPloidy and GermlineCNVCaller
[ "Detect", "copy", "number", "variations", "from", "batched", "set", "of", "samples", "using", "GATK4", "CNV", "calling", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L19-L32
238,115
bcbio/bcbio-nextgen
bcbio/structural/gatkcnv.py
_run_paired
def _run_paired(paired): """Run somatic variant calling pipeline. """ from bcbio.structural import titancna work_dir = _sv_workdir(paired.tumor_data) seg_files = model_segments(tz.get_in(["depth", "bins", "normalized"], paired.tumor_data), work_dir, paired) call_file = call_copy_numbers(seg_files["seg"], work_dir, paired.tumor_data) out = [] if paired.normal_data: out.append(paired.normal_data) if "sv" not in paired.tumor_data: paired.tumor_data["sv"] = [] paired.tumor_data["sv"].append({"variantcaller": "gatk-cnv", "call_file": call_file, "vrn_file": titancna.to_vcf(call_file, "GATK4-CNV", _get_seg_header, _seg_to_vcf, paired.tumor_data), "seg": seg_files["seg"], "plot": plot_model_segments(seg_files, work_dir, paired.tumor_data)}) out.append(paired.tumor_data) return out
python
def _run_paired(paired): from bcbio.structural import titancna work_dir = _sv_workdir(paired.tumor_data) seg_files = model_segments(tz.get_in(["depth", "bins", "normalized"], paired.tumor_data), work_dir, paired) call_file = call_copy_numbers(seg_files["seg"], work_dir, paired.tumor_data) out = [] if paired.normal_data: out.append(paired.normal_data) if "sv" not in paired.tumor_data: paired.tumor_data["sv"] = [] paired.tumor_data["sv"].append({"variantcaller": "gatk-cnv", "call_file": call_file, "vrn_file": titancna.to_vcf(call_file, "GATK4-CNV", _get_seg_header, _seg_to_vcf, paired.tumor_data), "seg": seg_files["seg"], "plot": plot_model_segments(seg_files, work_dir, paired.tumor_data)}) out.append(paired.tumor_data) return out
[ "def", "_run_paired", "(", "paired", ")", ":", "from", "bcbio", ".", "structural", "import", "titancna", "work_dir", "=", "_sv_workdir", "(", "paired", ".", "tumor_data", ")", "seg_files", "=", "model_segments", "(", "tz", ".", "get_in", "(", "[", "\"depth\"...
Run somatic variant calling pipeline.
[ "Run", "somatic", "variant", "calling", "pipeline", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L34-L54
238,116
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): 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
238,117
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): 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
238,118
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): 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
238,119
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): 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
238,120
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): 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
238,121
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): 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
238,122
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): 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
238,123
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): 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
238,124
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): 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
238,125
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): 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
238,126
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): 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
238,127
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): 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
238,128
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): 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
238,129
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): 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
238,130
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_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
238,131
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): 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
238,132
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): 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
238,133
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): 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
238,134
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): 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
238,135
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): 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
238,136
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): 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
238,137
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): 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
238,138
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): 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
238,139
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): 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
238,140
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): 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
238,141
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): 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
238,142
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): _, 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
238,143
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): 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
238,144
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): 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
238,145
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): 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
238,146
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): 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
238,147
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): 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
238,148
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): 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
238,149
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): 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
238,150
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): 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
238,151
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): 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
238,152
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): 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
238,153
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): 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
238,154
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): 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
238,155
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): 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
238,156
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): 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
238,157
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): 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
238,158
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): 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
238,159
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): 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
238,160
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): 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
238,161
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): 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
238,162
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): 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
238,163
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): # 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
238,164
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): # 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
238,165
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): 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
238,166
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): 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
238,167
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): 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
238,168
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): 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
238,169
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): 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
238,170
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): 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
238,171
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): 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
238,172
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): 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
238,173
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): 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
238,174
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): 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
238,175
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): 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
238,176
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): 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
238,177
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): 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
238,178
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): 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
238,179
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): 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
238,180
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): 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
238,181
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): 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
238,182
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): 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
238,183
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): 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
238,184
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): 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
238,185
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): 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
238,186
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): 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
238,187
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): 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
238,188
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): 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
238,189
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): 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
238,190
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): 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
238,191
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): 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
238,192
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): 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
238,193
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): 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
238,194
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): 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
238,195
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): 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
238,196
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): 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
238,197
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): 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
238,198
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): 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
238,199
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): 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