repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
bcbio/bcbio-nextgen | bcbio/chipseq/peaks.py | _sync | def _sync(original, processed):
"""
Add output to data if run sucessfully.
For now only macs2 is available, so no need
to consider multiple callers.
"""
for original_sample in original:
original_sample[0]["peaks_files"] = {}
for process_sample in processed:
if dd.get_sample_name(original_sample[0]) == dd.get_sample_name(process_sample[0]):
for key in ["peaks_files"]:
if process_sample[0].get(key):
original_sample[0][key] = process_sample[0][key]
return original | python | def _sync(original, processed):
"""
Add output to data if run sucessfully.
For now only macs2 is available, so no need
to consider multiple callers.
"""
for original_sample in original:
original_sample[0]["peaks_files"] = {}
for process_sample in processed:
if dd.get_sample_name(original_sample[0]) == dd.get_sample_name(process_sample[0]):
for key in ["peaks_files"]:
if process_sample[0].get(key):
original_sample[0][key] = process_sample[0][key]
return original | [
"def",
"_sync",
"(",
"original",
",",
"processed",
")",
":",
"for",
"original_sample",
"in",
"original",
":",
"original_sample",
"[",
"0",
"]",
"[",
"\"peaks_files\"",
"]",
"=",
"{",
"}",
"for",
"process_sample",
"in",
"processed",
":",
"if",
"dd",
".",
... | Add output to data if run sucessfully.
For now only macs2 is available, so no need
to consider multiple callers. | [
"Add",
"output",
"to",
"data",
"if",
"run",
"sucessfully",
".",
"For",
"now",
"only",
"macs2",
"is",
"available",
"so",
"no",
"need",
"to",
"consider",
"multiple",
"callers",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/chipseq/peaks.py#L61-L74 | train | 218,700 |
bcbio/bcbio-nextgen | bcbio/chipseq/peaks.py | _check | def _check(sample, data):
"""Get input sample for each chip bam file."""
if dd.get_chip_method(sample).lower() == "atac":
return [sample]
if dd.get_phenotype(sample) == "input":
return None
for origin in data:
if dd.get_batch(sample) in (dd.get_batches(origin[0]) or []) and dd.get_phenotype(origin[0]) == "input":
sample["work_bam_input"] = origin[0].get("work_bam")
return [sample]
return [sample] | python | def _check(sample, data):
"""Get input sample for each chip bam file."""
if dd.get_chip_method(sample).lower() == "atac":
return [sample]
if dd.get_phenotype(sample) == "input":
return None
for origin in data:
if dd.get_batch(sample) in (dd.get_batches(origin[0]) or []) and dd.get_phenotype(origin[0]) == "input":
sample["work_bam_input"] = origin[0].get("work_bam")
return [sample]
return [sample] | [
"def",
"_check",
"(",
"sample",
",",
"data",
")",
":",
"if",
"dd",
".",
"get_chip_method",
"(",
"sample",
")",
".",
"lower",
"(",
")",
"==",
"\"atac\"",
":",
"return",
"[",
"sample",
"]",
"if",
"dd",
".",
"get_phenotype",
"(",
"sample",
")",
"==",
... | Get input sample for each chip bam file. | [
"Get",
"input",
"sample",
"for",
"each",
"chip",
"bam",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/chipseq/peaks.py#L76-L86 | train | 218,701 |
bcbio/bcbio-nextgen | bcbio/chipseq/peaks.py | _get_multiplier | def _get_multiplier(samples):
"""Get multiplier to get jobs
only for samples that have input
"""
to_process = 1.0
to_skip = 0
for sample in samples:
if dd.get_phenotype(sample[0]) == "chip":
to_process += 1.0
elif dd.get_chip_method(sample[0]).lower() == "atac":
to_process += 1.0
else:
to_skip += 1.0
mult = (to_process - to_skip) / len(samples)
if mult <= 0:
mult = 1 / len(samples)
return max(mult, 1) | python | def _get_multiplier(samples):
"""Get multiplier to get jobs
only for samples that have input
"""
to_process = 1.0
to_skip = 0
for sample in samples:
if dd.get_phenotype(sample[0]) == "chip":
to_process += 1.0
elif dd.get_chip_method(sample[0]).lower() == "atac":
to_process += 1.0
else:
to_skip += 1.0
mult = (to_process - to_skip) / len(samples)
if mult <= 0:
mult = 1 / len(samples)
return max(mult, 1) | [
"def",
"_get_multiplier",
"(",
"samples",
")",
":",
"to_process",
"=",
"1.0",
"to_skip",
"=",
"0",
"for",
"sample",
"in",
"samples",
":",
"if",
"dd",
".",
"get_phenotype",
"(",
"sample",
"[",
"0",
"]",
")",
"==",
"\"chip\"",
":",
"to_process",
"+=",
"1... | Get multiplier to get jobs
only for samples that have input | [
"Get",
"multiplier",
"to",
"get",
"jobs",
"only",
"for",
"samples",
"that",
"have",
"input"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/chipseq/peaks.py#L88-L104 | train | 218,702 |
bcbio/bcbio-nextgen | bcbio/chipseq/peaks.py | greylisting | def greylisting(data):
"""
Run ChIP-seq greylisting
"""
input_bam = data.get("work_bam_input", None)
if not input_bam:
logger.info("No input BAM file detected, skipping greylisting.")
return None
try:
greylister = config_utils.get_program("chipseq-greylist", data)
except config_utils.CmdNotFound:
logger.info("No greylister found, skipping greylisting.")
return None
greylistdir = os.path.join(os.path.dirname(input_bam), "greylist")
if os.path.exists(greylistdir):
return greylistdir
cmd = "{greylister} --outdir {txgreylistdir} {input_bam}"
message = "Running greylisting on %s." % input_bam
with file_transaction(greylistdir) as txgreylistdir:
utils.safe_makedir(txgreylistdir)
try:
do.run(cmd.format(**locals()), message)
except subprocess.CalledProcessError as msg:
if str(msg).find("Cannot take a larger sample than population when 'replace=False'") >= 0:
logger.info("Skipping chipseq greylisting because of small sample size: %s"
% dd.get_sample_name(data))
return None
return greylistdir | python | def greylisting(data):
"""
Run ChIP-seq greylisting
"""
input_bam = data.get("work_bam_input", None)
if not input_bam:
logger.info("No input BAM file detected, skipping greylisting.")
return None
try:
greylister = config_utils.get_program("chipseq-greylist", data)
except config_utils.CmdNotFound:
logger.info("No greylister found, skipping greylisting.")
return None
greylistdir = os.path.join(os.path.dirname(input_bam), "greylist")
if os.path.exists(greylistdir):
return greylistdir
cmd = "{greylister} --outdir {txgreylistdir} {input_bam}"
message = "Running greylisting on %s." % input_bam
with file_transaction(greylistdir) as txgreylistdir:
utils.safe_makedir(txgreylistdir)
try:
do.run(cmd.format(**locals()), message)
except subprocess.CalledProcessError as msg:
if str(msg).find("Cannot take a larger sample than population when 'replace=False'") >= 0:
logger.info("Skipping chipseq greylisting because of small sample size: %s"
% dd.get_sample_name(data))
return None
return greylistdir | [
"def",
"greylisting",
"(",
"data",
")",
":",
"input_bam",
"=",
"data",
".",
"get",
"(",
"\"work_bam_input\"",
",",
"None",
")",
"if",
"not",
"input_bam",
":",
"logger",
".",
"info",
"(",
"\"No input BAM file detected, skipping greylisting.\"",
")",
"return",
"No... | Run ChIP-seq greylisting | [
"Run",
"ChIP",
"-",
"seq",
"greylisting"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/chipseq/peaks.py#L106-L133 | train | 218,703 |
bcbio/bcbio-nextgen | bcbio/distributed/clargs.py | to_parallel | def to_parallel(args, module="bcbio.distributed"):
"""Convert input arguments into a parallel dictionary for passing to processing.
"""
ptype, cores = _get_cores_and_type(args.numcores,
getattr(args, "paralleltype", None),
args.scheduler)
local_controller = getattr(args, "local_controller", False)
parallel = {"type": ptype, "cores": cores,
"scheduler": args.scheduler, "queue": args.queue,
"tag": args.tag, "module": module,
"resources": args.resources, "timeout": args.timeout,
"retries": args.retries,
"run_local": args.queue == "localrun",
"local_controller": local_controller}
return parallel | python | def to_parallel(args, module="bcbio.distributed"):
"""Convert input arguments into a parallel dictionary for passing to processing.
"""
ptype, cores = _get_cores_and_type(args.numcores,
getattr(args, "paralleltype", None),
args.scheduler)
local_controller = getattr(args, "local_controller", False)
parallel = {"type": ptype, "cores": cores,
"scheduler": args.scheduler, "queue": args.queue,
"tag": args.tag, "module": module,
"resources": args.resources, "timeout": args.timeout,
"retries": args.retries,
"run_local": args.queue == "localrun",
"local_controller": local_controller}
return parallel | [
"def",
"to_parallel",
"(",
"args",
",",
"module",
"=",
"\"bcbio.distributed\"",
")",
":",
"ptype",
",",
"cores",
"=",
"_get_cores_and_type",
"(",
"args",
".",
"numcores",
",",
"getattr",
"(",
"args",
",",
"\"paralleltype\"",
",",
"None",
")",
",",
"args",
... | Convert input arguments into a parallel dictionary for passing to processing. | [
"Convert",
"input",
"arguments",
"into",
"a",
"parallel",
"dictionary",
"for",
"passing",
"to",
"processing",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/clargs.py#L4-L18 | train | 218,704 |
bcbio/bcbio-nextgen | bcbio/distributed/clargs.py | _get_cores_and_type | def _get_cores_and_type(numcores, paralleltype, scheduler):
"""Return core and parallelization approach from command line providing sane defaults.
"""
if scheduler is not None:
paralleltype = "ipython"
if paralleltype is None:
paralleltype = "local"
if not numcores or int(numcores) < 1:
numcores = 1
return paralleltype, int(numcores) | python | def _get_cores_and_type(numcores, paralleltype, scheduler):
"""Return core and parallelization approach from command line providing sane defaults.
"""
if scheduler is not None:
paralleltype = "ipython"
if paralleltype is None:
paralleltype = "local"
if not numcores or int(numcores) < 1:
numcores = 1
return paralleltype, int(numcores) | [
"def",
"_get_cores_and_type",
"(",
"numcores",
",",
"paralleltype",
",",
"scheduler",
")",
":",
"if",
"scheduler",
"is",
"not",
"None",
":",
"paralleltype",
"=",
"\"ipython\"",
"if",
"paralleltype",
"is",
"None",
":",
"paralleltype",
"=",
"\"local\"",
"if",
"n... | Return core and parallelization approach from command line providing sane defaults. | [
"Return",
"core",
"and",
"parallelization",
"approach",
"from",
"command",
"line",
"providing",
"sane",
"defaults",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/clargs.py#L20-L29 | train | 218,705 |
bcbio/bcbio-nextgen | bcbio/ngsalign/tophat.py | _fix_mates | def _fix_mates(orig_file, out_file, ref_file, config):
"""Fix problematic unmapped mate pairs in TopHat output.
TopHat 2.0.9 appears to have issues with secondary reads:
https://groups.google.com/forum/#!topic/tuxedo-tools-users/puLfDNbN9bo
This cleans the input file to only keep properly mapped pairs,
providing a general fix that will handle correctly mapped secondary
reads as well.
"""
if not file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
samtools = config_utils.get_program("samtools", config)
cmd = "{samtools} view -bS -h -t {ref_file}.fai -F 8 {orig_file} > {tx_out_file}"
do.run(cmd.format(**locals()), "Fix mate pairs in TopHat output", {})
return out_file | python | def _fix_mates(orig_file, out_file, ref_file, config):
"""Fix problematic unmapped mate pairs in TopHat output.
TopHat 2.0.9 appears to have issues with secondary reads:
https://groups.google.com/forum/#!topic/tuxedo-tools-users/puLfDNbN9bo
This cleans the input file to only keep properly mapped pairs,
providing a general fix that will handle correctly mapped secondary
reads as well.
"""
if not file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
samtools = config_utils.get_program("samtools", config)
cmd = "{samtools} view -bS -h -t {ref_file}.fai -F 8 {orig_file} > {tx_out_file}"
do.run(cmd.format(**locals()), "Fix mate pairs in TopHat output", {})
return out_file | [
"def",
"_fix_mates",
"(",
"orig_file",
",",
"out_file",
",",
"ref_file",
",",
"config",
")",
":",
"if",
"not",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
"config",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"samtools",
... | Fix problematic unmapped mate pairs in TopHat output.
TopHat 2.0.9 appears to have issues with secondary reads:
https://groups.google.com/forum/#!topic/tuxedo-tools-users/puLfDNbN9bo
This cleans the input file to only keep properly mapped pairs,
providing a general fix that will handle correctly mapped secondary
reads as well. | [
"Fix",
"problematic",
"unmapped",
"mate",
"pairs",
"in",
"TopHat",
"output",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/tophat.py#L173-L187 | train | 218,706 |
bcbio/bcbio-nextgen | bcbio/ngsalign/tophat.py | _add_rg | def _add_rg(unmapped_file, config, names):
"""Add the missing RG header."""
picard = broad.runner_from_path("picard", config)
rg_fixed = picard.run_fn("picard_fix_rgs", unmapped_file, names)
return rg_fixed | python | def _add_rg(unmapped_file, config, names):
"""Add the missing RG header."""
picard = broad.runner_from_path("picard", config)
rg_fixed = picard.run_fn("picard_fix_rgs", unmapped_file, names)
return rg_fixed | [
"def",
"_add_rg",
"(",
"unmapped_file",
",",
"config",
",",
"names",
")",
":",
"picard",
"=",
"broad",
".",
"runner_from_path",
"(",
"\"picard\"",
",",
"config",
")",
"rg_fixed",
"=",
"picard",
".",
"run_fn",
"(",
"\"picard_fix_rgs\"",
",",
"unmapped_file",
... | Add the missing RG header. | [
"Add",
"the",
"missing",
"RG",
"header",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/tophat.py#L189-L193 | train | 218,707 |
bcbio/bcbio-nextgen | bcbio/ngsalign/tophat.py | _estimate_paired_innerdist | def _estimate_paired_innerdist(fastq_file, pair_file, ref_file, out_base,
out_dir, data):
"""Use Bowtie to estimate the inner distance of paired reads.
"""
mean, stdev = _bowtie_for_innerdist("100000", fastq_file, pair_file, ref_file,
out_base, out_dir, data, True)
if not mean or not stdev:
mean, stdev = _bowtie_for_innerdist("1", fastq_file, pair_file, ref_file,
out_base, out_dir, data, True)
# No reads aligning so no data to process, set some default values
if not mean or not stdev:
mean, stdev = 200, 50
return mean, stdev | python | def _estimate_paired_innerdist(fastq_file, pair_file, ref_file, out_base,
out_dir, data):
"""Use Bowtie to estimate the inner distance of paired reads.
"""
mean, stdev = _bowtie_for_innerdist("100000", fastq_file, pair_file, ref_file,
out_base, out_dir, data, True)
if not mean or not stdev:
mean, stdev = _bowtie_for_innerdist("1", fastq_file, pair_file, ref_file,
out_base, out_dir, data, True)
# No reads aligning so no data to process, set some default values
if not mean or not stdev:
mean, stdev = 200, 50
return mean, stdev | [
"def",
"_estimate_paired_innerdist",
"(",
"fastq_file",
",",
"pair_file",
",",
"ref_file",
",",
"out_base",
",",
"out_dir",
",",
"data",
")",
":",
"mean",
",",
"stdev",
"=",
"_bowtie_for_innerdist",
"(",
"\"100000\"",
",",
"fastq_file",
",",
"pair_file",
",",
... | Use Bowtie to estimate the inner distance of paired reads. | [
"Use",
"Bowtie",
"to",
"estimate",
"the",
"inner",
"distance",
"of",
"paired",
"reads",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/tophat.py#L230-L243 | train | 218,708 |
bcbio/bcbio-nextgen | bcbio/ngsalign/tophat.py | fix_insert_size | def fix_insert_size(in_bam, config):
"""
Tophat sets PI in the RG to be the inner distance size, but the SAM spec
states should be the insert size. This fixes the RG in the alignment
file generated by Tophat header to match the spec
"""
fixed_file = os.path.splitext(in_bam)[0] + ".pi_fixed.bam"
if file_exists(fixed_file):
return fixed_file
header_file = os.path.splitext(in_bam)[0] + ".header.sam"
read_length = bam.estimate_read_length(in_bam)
bam_handle= bam.open_samfile(in_bam)
header = bam_handle.header.copy()
rg_dict = header['RG'][0]
if 'PI' not in rg_dict:
return in_bam
PI = int(rg_dict.get('PI'))
PI = PI + 2*read_length
rg_dict['PI'] = PI
header['RG'][0] = rg_dict
with pysam.Samfile(header_file, "wb", header=header) as out_handle:
with bam.open_samfile(in_bam) as in_handle:
for record in in_handle:
out_handle.write(record)
shutil.move(header_file, fixed_file)
return fixed_file | python | def fix_insert_size(in_bam, config):
"""
Tophat sets PI in the RG to be the inner distance size, but the SAM spec
states should be the insert size. This fixes the RG in the alignment
file generated by Tophat header to match the spec
"""
fixed_file = os.path.splitext(in_bam)[0] + ".pi_fixed.bam"
if file_exists(fixed_file):
return fixed_file
header_file = os.path.splitext(in_bam)[0] + ".header.sam"
read_length = bam.estimate_read_length(in_bam)
bam_handle= bam.open_samfile(in_bam)
header = bam_handle.header.copy()
rg_dict = header['RG'][0]
if 'PI' not in rg_dict:
return in_bam
PI = int(rg_dict.get('PI'))
PI = PI + 2*read_length
rg_dict['PI'] = PI
header['RG'][0] = rg_dict
with pysam.Samfile(header_file, "wb", header=header) as out_handle:
with bam.open_samfile(in_bam) as in_handle:
for record in in_handle:
out_handle.write(record)
shutil.move(header_file, fixed_file)
return fixed_file | [
"def",
"fix_insert_size",
"(",
"in_bam",
",",
"config",
")",
":",
"fixed_file",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"in_bam",
")",
"[",
"0",
"]",
"+",
"\".pi_fixed.bam\"",
"if",
"file_exists",
"(",
"fixed_file",
")",
":",
"return",
"fixed_file",
... | Tophat sets PI in the RG to be the inner distance size, but the SAM spec
states should be the insert size. This fixes the RG in the alignment
file generated by Tophat header to match the spec | [
"Tophat",
"sets",
"PI",
"in",
"the",
"RG",
"to",
"be",
"the",
"inner",
"distance",
"size",
"but",
"the",
"SAM",
"spec",
"states",
"should",
"be",
"the",
"insert",
"size",
".",
"This",
"fixes",
"the",
"RG",
"in",
"the",
"alignment",
"file",
"generated",
... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/tophat.py#L344-L369 | train | 218,709 |
bcbio/bcbio-nextgen | bcbio/variation/damage.py | _filter_to_info | def _filter_to_info(in_file, data):
"""Move DKFZ filter information into INFO field.
"""
header = ("""##INFO=<ID=DKFZBias,Number=.,Type=String,"""
"""Description="Bias estimation based on unequal read support from DKFZBiasFilterVariant Depth">\n""")
out_file = "%s-ann.vcf" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file) and not utils.file_uptodate(out_file + ".gz", in_file):
with file_transaction(data, out_file) as tx_out_file:
with utils.open_gzipsafe(in_file) as in_handle:
with open(tx_out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("#CHROM"):
out_handle.write(header + line)
elif line.startswith("#"):
out_handle.write(line)
else:
out_handle.write(_rec_filter_to_info(line))
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def _filter_to_info(in_file, data):
"""Move DKFZ filter information into INFO field.
"""
header = ("""##INFO=<ID=DKFZBias,Number=.,Type=String,"""
"""Description="Bias estimation based on unequal read support from DKFZBiasFilterVariant Depth">\n""")
out_file = "%s-ann.vcf" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file) and not utils.file_uptodate(out_file + ".gz", in_file):
with file_transaction(data, out_file) as tx_out_file:
with utils.open_gzipsafe(in_file) as in_handle:
with open(tx_out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("#CHROM"):
out_handle.write(header + line)
elif line.startswith("#"):
out_handle.write(line)
else:
out_handle.write(_rec_filter_to_info(line))
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"_filter_to_info",
"(",
"in_file",
",",
"data",
")",
":",
"header",
"=",
"(",
"\"\"\"##INFO=<ID=DKFZBias,Number=.,Type=String,\"\"\"",
"\"\"\"Description=\"Bias estimation based on unequal read support from DKFZBiasFilterVariant Depth\">\\n\"\"\"",
")",
"out_file",
"=",
"\"%s-... | Move DKFZ filter information into INFO field. | [
"Move",
"DKFZ",
"filter",
"information",
"into",
"INFO",
"field",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/damage.py#L46-L63 | train | 218,710 |
bcbio/bcbio-nextgen | bcbio/variation/damage.py | _rec_filter_to_info | def _rec_filter_to_info(line):
"""Move a DKFZBias filter to the INFO field, for a record.
"""
parts = line.rstrip().split("\t")
move_filters = {"bSeq": "strand", "bPcr": "damage"}
new_filters = []
bias_info = []
for f in parts[6].split(";"):
if f in move_filters:
bias_info.append(move_filters[f])
elif f not in ["."]:
new_filters.append(f)
if bias_info:
parts[7] += ";DKFZBias=%s" % ",".join(bias_info)
parts[6] = ";".join(new_filters or ["PASS"])
return "\t".join(parts) + "\n" | python | def _rec_filter_to_info(line):
"""Move a DKFZBias filter to the INFO field, for a record.
"""
parts = line.rstrip().split("\t")
move_filters = {"bSeq": "strand", "bPcr": "damage"}
new_filters = []
bias_info = []
for f in parts[6].split(";"):
if f in move_filters:
bias_info.append(move_filters[f])
elif f not in ["."]:
new_filters.append(f)
if bias_info:
parts[7] += ";DKFZBias=%s" % ",".join(bias_info)
parts[6] = ";".join(new_filters or ["PASS"])
return "\t".join(parts) + "\n" | [
"def",
"_rec_filter_to_info",
"(",
"line",
")",
":",
"parts",
"=",
"line",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"\"\\t\"",
")",
"move_filters",
"=",
"{",
"\"bSeq\"",
":",
"\"strand\"",
",",
"\"bPcr\"",
":",
"\"damage\"",
"}",
"new_filters",
"=",
"... | Move a DKFZBias filter to the INFO field, for a record. | [
"Move",
"a",
"DKFZBias",
"filter",
"to",
"the",
"INFO",
"field",
"for",
"a",
"record",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/damage.py#L65-L80 | train | 218,711 |
bcbio/bcbio-nextgen | bcbio/variation/damage.py | should_filter | def should_filter(items):
"""Check if we should do damage filtering on somatic calling with low frequency events.
"""
return (vcfutils.get_paired(items) is not None and
any("damage_filter" in dd.get_tools_on(d) for d in items)) | python | def should_filter(items):
"""Check if we should do damage filtering on somatic calling with low frequency events.
"""
return (vcfutils.get_paired(items) is not None and
any("damage_filter" in dd.get_tools_on(d) for d in items)) | [
"def",
"should_filter",
"(",
"items",
")",
":",
"return",
"(",
"vcfutils",
".",
"get_paired",
"(",
"items",
")",
"is",
"not",
"None",
"and",
"any",
"(",
"\"damage_filter\"",
"in",
"dd",
".",
"get_tools_on",
"(",
"d",
")",
"for",
"d",
"in",
"items",
")"... | Check if we should do damage filtering on somatic calling with low frequency events. | [
"Check",
"if",
"we",
"should",
"do",
"damage",
"filtering",
"on",
"somatic",
"calling",
"with",
"low",
"frequency",
"events",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/damage.py#L82-L86 | train | 218,712 |
bcbio/bcbio-nextgen | bcbio/provenance/diagnostics.py | start_cmd | def start_cmd(cmd, descr, data):
"""Retain details about starting a command, returning a command identifier.
"""
if data and "provenance" in data:
entity_id = tz.get_in(["provenance", "entity"], data) | python | def start_cmd(cmd, descr, data):
"""Retain details about starting a command, returning a command identifier.
"""
if data and "provenance" in data:
entity_id = tz.get_in(["provenance", "entity"], data) | [
"def",
"start_cmd",
"(",
"cmd",
",",
"descr",
",",
"data",
")",
":",
"if",
"data",
"and",
"\"provenance\"",
"in",
"data",
":",
"entity_id",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"provenance\"",
",",
"\"entity\"",
"]",
",",
"data",
")"
] | Retain details about starting a command, returning a command identifier. | [
"Retain",
"details",
"about",
"starting",
"a",
"command",
"returning",
"a",
"command",
"identifier",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/diagnostics.py#L23-L27 | train | 218,713 |
bcbio/bcbio-nextgen | bcbio/provenance/diagnostics.py | initialize | def initialize(dirs):
"""Initialize the biolite database to load provenance information.
"""
if biolite and dirs.get("work"):
base_dir = utils.safe_makedir(os.path.join(dirs["work"], "provenance"))
p_db = os.path.join(base_dir, "biolite.db")
biolite.config.resources["database"] = p_db
biolite.database.connect() | python | def initialize(dirs):
"""Initialize the biolite database to load provenance information.
"""
if biolite and dirs.get("work"):
base_dir = utils.safe_makedir(os.path.join(dirs["work"], "provenance"))
p_db = os.path.join(base_dir, "biolite.db")
biolite.config.resources["database"] = p_db
biolite.database.connect() | [
"def",
"initialize",
"(",
"dirs",
")",
":",
"if",
"biolite",
"and",
"dirs",
".",
"get",
"(",
"\"work\"",
")",
":",
"base_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirs",
"[",
"\"work\"",
"]",
",",
"\"provenan... | Initialize the biolite database to load provenance information. | [
"Initialize",
"the",
"biolite",
"database",
"to",
"load",
"provenance",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/diagnostics.py#L34-L41 | train | 218,714 |
bcbio/bcbio-nextgen | bcbio/provenance/diagnostics.py | track_parallel | def track_parallel(items, sub_type):
"""Create entity identifiers to trace the given items in sub-commands.
Helps handle nesting in parallel program execution:
run id => sub-section id => parallel ids
"""
out = []
for i, args in enumerate(items):
item_i, item = _get_provitem_from_args(args)
if item:
sub_entity = "%s.%s.%s" % (item["provenance"]["entity"], sub_type, i)
item["provenance"]["entity"] = sub_entity
args = list(args)
args[item_i] = item
out.append(args)
# TODO: store mapping of entity to sub identifiers
return out | python | def track_parallel(items, sub_type):
"""Create entity identifiers to trace the given items in sub-commands.
Helps handle nesting in parallel program execution:
run id => sub-section id => parallel ids
"""
out = []
for i, args in enumerate(items):
item_i, item = _get_provitem_from_args(args)
if item:
sub_entity = "%s.%s.%s" % (item["provenance"]["entity"], sub_type, i)
item["provenance"]["entity"] = sub_entity
args = list(args)
args[item_i] = item
out.append(args)
# TODO: store mapping of entity to sub identifiers
return out | [
"def",
"track_parallel",
"(",
"items",
",",
"sub_type",
")",
":",
"out",
"=",
"[",
"]",
"for",
"i",
",",
"args",
"in",
"enumerate",
"(",
"items",
")",
":",
"item_i",
",",
"item",
"=",
"_get_provitem_from_args",
"(",
"args",
")",
"if",
"item",
":",
"s... | Create entity identifiers to trace the given items in sub-commands.
Helps handle nesting in parallel program execution:
run id => sub-section id => parallel ids | [
"Create",
"entity",
"identifiers",
"to",
"trace",
"the",
"given",
"items",
"in",
"sub",
"-",
"commands",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/diagnostics.py#L49-L66 | train | 218,715 |
bcbio/bcbio-nextgen | bcbio/provenance/diagnostics.py | _get_provitem_from_args | def _get_provitem_from_args(xs):
"""Retrieve processed item from list of input arguments.
"""
for i, x in enumerate(xs):
if _has_provenance(x):
return i, x
return -1, None | python | def _get_provitem_from_args(xs):
"""Retrieve processed item from list of input arguments.
"""
for i, x in enumerate(xs):
if _has_provenance(x):
return i, x
return -1, None | [
"def",
"_get_provitem_from_args",
"(",
"xs",
")",
":",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"xs",
")",
":",
"if",
"_has_provenance",
"(",
"x",
")",
":",
"return",
"i",
",",
"x",
"return",
"-",
"1",
",",
"None"
] | Retrieve processed item from list of input arguments. | [
"Retrieve",
"processed",
"item",
"from",
"list",
"of",
"input",
"arguments",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/diagnostics.py#L71-L77 | train | 218,716 |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | handle_vcf_calls | def handle_vcf_calls(vcf_file, data, orig_items):
"""Prioritize VCF calls based on external annotations supplied through GEMINI.
"""
if not _do_prioritize(orig_items):
return vcf_file
else:
ann_vcf = population.run_vcfanno(vcf_file, data)
if ann_vcf:
priority_file = _prep_priority_filter_vcfanno(ann_vcf, data)
return _apply_priority_filter(ann_vcf, priority_file, data)
# No data available for filtering, return original file
else:
return vcf_file | python | def handle_vcf_calls(vcf_file, data, orig_items):
"""Prioritize VCF calls based on external annotations supplied through GEMINI.
"""
if not _do_prioritize(orig_items):
return vcf_file
else:
ann_vcf = population.run_vcfanno(vcf_file, data)
if ann_vcf:
priority_file = _prep_priority_filter_vcfanno(ann_vcf, data)
return _apply_priority_filter(ann_vcf, priority_file, data)
# No data available for filtering, return original file
else:
return vcf_file | [
"def",
"handle_vcf_calls",
"(",
"vcf_file",
",",
"data",
",",
"orig_items",
")",
":",
"if",
"not",
"_do_prioritize",
"(",
"orig_items",
")",
":",
"return",
"vcf_file",
"else",
":",
"ann_vcf",
"=",
"population",
".",
"run_vcfanno",
"(",
"vcf_file",
",",
"data... | Prioritize VCF calls based on external annotations supplied through GEMINI. | [
"Prioritize",
"VCF",
"calls",
"based",
"on",
"external",
"annotations",
"supplied",
"through",
"GEMINI",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L27-L39 | train | 218,717 |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | _apply_priority_filter | def _apply_priority_filter(in_file, priority_file, data):
"""Annotate variants with priority information and use to apply filters.
"""
out_file = "%s-priority%s" % utils.splitext_plus(in_file)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
header = ('##INFO=<ID=EPR,Number=.,Type=String,'
'Description="Somatic prioritization based on external annotations, '
'identify as likely germline">')
header_file = "%s-repeatheader.txt" % utils.splitext_plus(tx_out_file)[0]
with open(header_file, "w") as out_handle:
out_handle.write(header)
if "tumoronly_germline_filter" in dd.get_tools_on(data):
filter_cmd = ("bcftools filter -m '+' -s 'LowPriority' "
"""-e "EPR[0] != 'pass'" |""")
else:
filter_cmd = ""
cmd = ("bcftools annotate -a {priority_file} -h {header_file} "
"-c CHROM,FROM,TO,REF,ALT,INFO/EPR {in_file} | "
"{filter_cmd} bgzip -c > {tx_out_file}")
do.run(cmd.format(**locals()), "Run external annotation based prioritization filtering")
vcfutils.bgzip_and_index(out_file, data["config"])
return out_file | python | def _apply_priority_filter(in_file, priority_file, data):
"""Annotate variants with priority information and use to apply filters.
"""
out_file = "%s-priority%s" % utils.splitext_plus(in_file)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
header = ('##INFO=<ID=EPR,Number=.,Type=String,'
'Description="Somatic prioritization based on external annotations, '
'identify as likely germline">')
header_file = "%s-repeatheader.txt" % utils.splitext_plus(tx_out_file)[0]
with open(header_file, "w") as out_handle:
out_handle.write(header)
if "tumoronly_germline_filter" in dd.get_tools_on(data):
filter_cmd = ("bcftools filter -m '+' -s 'LowPriority' "
"""-e "EPR[0] != 'pass'" |""")
else:
filter_cmd = ""
cmd = ("bcftools annotate -a {priority_file} -h {header_file} "
"-c CHROM,FROM,TO,REF,ALT,INFO/EPR {in_file} | "
"{filter_cmd} bgzip -c > {tx_out_file}")
do.run(cmd.format(**locals()), "Run external annotation based prioritization filtering")
vcfutils.bgzip_and_index(out_file, data["config"])
return out_file | [
"def",
"_apply_priority_filter",
"(",
"in_file",
",",
"priority_file",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-priority%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
... | Annotate variants with priority information and use to apply filters. | [
"Annotate",
"variants",
"with",
"priority",
"information",
"and",
"use",
"to",
"apply",
"filters",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L41-L63 | train | 218,718 |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | _prep_priority_filter_vcfanno | def _prep_priority_filter_vcfanno(in_vcf, data):
"""Prepare tabix file with priority filters based on vcfanno annotations.
"""
pops = ['af_adj_exac_afr', 'af_adj_exac_amr', 'af_adj_exac_eas',
'af_adj_exac_fin', 'af_adj_exac_nfe', 'af_adj_exac_oth', 'af_adj_exac_sas',
'af_exac_all', 'max_aaf_all',
"af_esp_ea", "af_esp_aa", "af_esp_all", "af_1kg_amr", "af_1kg_eas",
"af_1kg_sas", "af_1kg_afr", "af_1kg_eur", "af_1kg_all"]
known = ["cosmic_ids", "cosmic_id", "clinvar_sig"]
out_file = "%s-priority.tsv" % utils.splitext_plus(in_vcf)[0]
if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
writer = csv.writer(out_handle, dialect="excel-tab")
header = ["#chrom", "start", "end", "ref", "alt", "filter"]
writer.writerow(header)
vcf_reader = cyvcf2.VCF(in_vcf)
impact_info = _get_impact_info(vcf_reader)
for rec in vcf_reader:
row = _prepare_vcf_rec(rec, pops, known, impact_info)
cur_filter = _calc_priority_filter(row, pops)
writer.writerow([rec.CHROM, rec.start, rec.end, rec.REF, ",".join(rec.ALT), cur_filter])
return vcfutils.bgzip_and_index(out_file, data["config"],
tabix_args="-0 -c '#' -s 1 -b 2 -e 3") | python | def _prep_priority_filter_vcfanno(in_vcf, data):
"""Prepare tabix file with priority filters based on vcfanno annotations.
"""
pops = ['af_adj_exac_afr', 'af_adj_exac_amr', 'af_adj_exac_eas',
'af_adj_exac_fin', 'af_adj_exac_nfe', 'af_adj_exac_oth', 'af_adj_exac_sas',
'af_exac_all', 'max_aaf_all',
"af_esp_ea", "af_esp_aa", "af_esp_all", "af_1kg_amr", "af_1kg_eas",
"af_1kg_sas", "af_1kg_afr", "af_1kg_eur", "af_1kg_all"]
known = ["cosmic_ids", "cosmic_id", "clinvar_sig"]
out_file = "%s-priority.tsv" % utils.splitext_plus(in_vcf)[0]
if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
writer = csv.writer(out_handle, dialect="excel-tab")
header = ["#chrom", "start", "end", "ref", "alt", "filter"]
writer.writerow(header)
vcf_reader = cyvcf2.VCF(in_vcf)
impact_info = _get_impact_info(vcf_reader)
for rec in vcf_reader:
row = _prepare_vcf_rec(rec, pops, known, impact_info)
cur_filter = _calc_priority_filter(row, pops)
writer.writerow([rec.CHROM, rec.start, rec.end, rec.REF, ",".join(rec.ALT), cur_filter])
return vcfutils.bgzip_and_index(out_file, data["config"],
tabix_args="-0 -c '#' -s 1 -b 2 -e 3") | [
"def",
"_prep_priority_filter_vcfanno",
"(",
"in_vcf",
",",
"data",
")",
":",
"pops",
"=",
"[",
"'af_adj_exac_afr'",
",",
"'af_adj_exac_amr'",
",",
"'af_adj_exac_eas'",
",",
"'af_adj_exac_fin'",
",",
"'af_adj_exac_nfe'",
",",
"'af_adj_exac_oth'",
",",
"'af_adj_exac_sas'... | Prepare tabix file with priority filters based on vcfanno annotations. | [
"Prepare",
"tabix",
"file",
"with",
"priority",
"filters",
"based",
"on",
"vcfanno",
"annotations",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L65-L88 | train | 218,719 |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | _get_impact_info | def _get_impact_info(vcf_reader):
"""Retrieve impact parsing information from INFO header.
"""
ImpactInfo = collections.namedtuple("ImpactInfo", "header, gclass, id")
KEY_2_CLASS = {
'CSQ': geneimpacts.VEP,
'ANN': geneimpacts.SnpEff,
'BCSQ': geneimpacts.BCFT}
for l in (x.strip() for x in _from_bytes(vcf_reader.raw_header).split("\n")):
if l.startswith("##INFO"):
patt = re.compile("(\w+)=(\"[^\"]+\"|[^,]+)")
stub = l.split("=<")[1].rstrip(">")
d = dict(patt.findall(_from_bytes(stub)))
if d["ID"] in KEY_2_CLASS:
return ImpactInfo(_parse_impact_header(d), KEY_2_CLASS[d["ID"]], d["ID"]) | python | def _get_impact_info(vcf_reader):
"""Retrieve impact parsing information from INFO header.
"""
ImpactInfo = collections.namedtuple("ImpactInfo", "header, gclass, id")
KEY_2_CLASS = {
'CSQ': geneimpacts.VEP,
'ANN': geneimpacts.SnpEff,
'BCSQ': geneimpacts.BCFT}
for l in (x.strip() for x in _from_bytes(vcf_reader.raw_header).split("\n")):
if l.startswith("##INFO"):
patt = re.compile("(\w+)=(\"[^\"]+\"|[^,]+)")
stub = l.split("=<")[1].rstrip(">")
d = dict(patt.findall(_from_bytes(stub)))
if d["ID"] in KEY_2_CLASS:
return ImpactInfo(_parse_impact_header(d), KEY_2_CLASS[d["ID"]], d["ID"]) | [
"def",
"_get_impact_info",
"(",
"vcf_reader",
")",
":",
"ImpactInfo",
"=",
"collections",
".",
"namedtuple",
"(",
"\"ImpactInfo\"",
",",
"\"header, gclass, id\"",
")",
"KEY_2_CLASS",
"=",
"{",
"'CSQ'",
":",
"geneimpacts",
".",
"VEP",
",",
"'ANN'",
":",
"geneimpa... | Retrieve impact parsing information from INFO header. | [
"Retrieve",
"impact",
"parsing",
"information",
"from",
"INFO",
"header",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L90-L104 | train | 218,720 |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | _parse_impact_header | def _parse_impact_header(hdr_dict):
"""Parse fields for impact, taken from vcf2db
"""
desc = hdr_dict["Description"]
if hdr_dict["ID"] == "ANN":
parts = [x.strip("\"'") for x in re.split("\s*\|\s*", desc.split(":", 1)[1].strip('" '))]
elif hdr_dict["ID"] == "EFF":
parts = [x.strip(" [])'(\"") for x in re.split("\||\(", desc.split(":", 1)[1].strip())]
elif hdr_dict["ID"] == "CSQ":
parts = [x.strip(" [])'(\"") for x in re.split("\||\(", desc.split(":", 1)[1].strip())]
elif hdr_dict["ID"] == "BCSQ":
parts = desc.split(']', 1)[1].split(']')[0].replace('[','').split("|")
else:
raise Exception("don't know how to use %s as annotation" % hdr_dict["ID"])
return parts | python | def _parse_impact_header(hdr_dict):
"""Parse fields for impact, taken from vcf2db
"""
desc = hdr_dict["Description"]
if hdr_dict["ID"] == "ANN":
parts = [x.strip("\"'") for x in re.split("\s*\|\s*", desc.split(":", 1)[1].strip('" '))]
elif hdr_dict["ID"] == "EFF":
parts = [x.strip(" [])'(\"") for x in re.split("\||\(", desc.split(":", 1)[1].strip())]
elif hdr_dict["ID"] == "CSQ":
parts = [x.strip(" [])'(\"") for x in re.split("\||\(", desc.split(":", 1)[1].strip())]
elif hdr_dict["ID"] == "BCSQ":
parts = desc.split(']', 1)[1].split(']')[0].replace('[','').split("|")
else:
raise Exception("don't know how to use %s as annotation" % hdr_dict["ID"])
return parts | [
"def",
"_parse_impact_header",
"(",
"hdr_dict",
")",
":",
"desc",
"=",
"hdr_dict",
"[",
"\"Description\"",
"]",
"if",
"hdr_dict",
"[",
"\"ID\"",
"]",
"==",
"\"ANN\"",
":",
"parts",
"=",
"[",
"x",
".",
"strip",
"(",
"\"\\\"'\"",
")",
"for",
"x",
"in",
"... | Parse fields for impact, taken from vcf2db | [
"Parse",
"fields",
"for",
"impact",
"taken",
"from",
"vcf2db"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L116-L130 | train | 218,721 |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | _prepare_vcf_rec | def _prepare_vcf_rec(rec, pops, known, impact_info):
"""Parse a vcfanno output into a dictionary of useful attributes.
"""
out = {}
for k in pops + known:
out[k] = rec.INFO.get(k)
if impact_info:
cur_info = rec.INFO.get(impact_info.id)
if cur_info:
cur_impacts = [impact_info.gclass(e, impact_info.header) for e in _from_bytes(cur_info).split(",")]
top = geneimpacts.Effect.top_severity(cur_impacts)
if isinstance(top, list):
top = top[0]
out["impact_severity"] = top.effect_severity
return out | python | def _prepare_vcf_rec(rec, pops, known, impact_info):
"""Parse a vcfanno output into a dictionary of useful attributes.
"""
out = {}
for k in pops + known:
out[k] = rec.INFO.get(k)
if impact_info:
cur_info = rec.INFO.get(impact_info.id)
if cur_info:
cur_impacts = [impact_info.gclass(e, impact_info.header) for e in _from_bytes(cur_info).split(",")]
top = geneimpacts.Effect.top_severity(cur_impacts)
if isinstance(top, list):
top = top[0]
out["impact_severity"] = top.effect_severity
return out | [
"def",
"_prepare_vcf_rec",
"(",
"rec",
",",
"pops",
",",
"known",
",",
"impact_info",
")",
":",
"out",
"=",
"{",
"}",
"for",
"k",
"in",
"pops",
"+",
"known",
":",
"out",
"[",
"k",
"]",
"=",
"rec",
".",
"INFO",
".",
"get",
"(",
"k",
")",
"if",
... | Parse a vcfanno output into a dictionary of useful attributes. | [
"Parse",
"a",
"vcfanno",
"output",
"into",
"a",
"dictionary",
"of",
"useful",
"attributes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L132-L146 | train | 218,722 |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | _calc_priority_filter | def _calc_priority_filter(row, pops):
"""Calculate the priority filter based on external associated data.
- Pass high/medium impact variants not found in population databases
- Pass variants found in COSMIC or Clinvar provided they don't have two
additional reasons to filter (found in multiple external populations)
"""
filters = []
passes = []
passes.extend(_find_known(row))
filters.extend(_known_populations(row, pops))
if len(filters) == 0 or (len(passes) > 0 and len(filters) < 2):
passes.insert(0, "pass")
return ",".join(passes + filters) | python | def _calc_priority_filter(row, pops):
"""Calculate the priority filter based on external associated data.
- Pass high/medium impact variants not found in population databases
- Pass variants found in COSMIC or Clinvar provided they don't have two
additional reasons to filter (found in multiple external populations)
"""
filters = []
passes = []
passes.extend(_find_known(row))
filters.extend(_known_populations(row, pops))
if len(filters) == 0 or (len(passes) > 0 and len(filters) < 2):
passes.insert(0, "pass")
return ",".join(passes + filters) | [
"def",
"_calc_priority_filter",
"(",
"row",
",",
"pops",
")",
":",
"filters",
"=",
"[",
"]",
"passes",
"=",
"[",
"]",
"passes",
".",
"extend",
"(",
"_find_known",
"(",
"row",
")",
")",
"filters",
".",
"extend",
"(",
"_known_populations",
"(",
"row",
",... | Calculate the priority filter based on external associated data.
- Pass high/medium impact variants not found in population databases
- Pass variants found in COSMIC or Clinvar provided they don't have two
additional reasons to filter (found in multiple external populations) | [
"Calculate",
"the",
"priority",
"filter",
"based",
"on",
"external",
"associated",
"data",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L148-L161 | train | 218,723 |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | _known_populations | def _known_populations(row, pops):
"""Find variants present in substantial frequency in population databases.
"""
cutoff = 0.01
out = set([])
for pop, base in [("esp", "af_esp_all"), ("1000g", "af_1kg_all"),
("exac", "af_exac_all"), ("anypop", "max_aaf_all")]:
for key in [x for x in pops if x.startswith(base)]:
val = row[key]
if val and val > cutoff:
out.add(pop)
return sorted(list(out)) | python | def _known_populations(row, pops):
"""Find variants present in substantial frequency in population databases.
"""
cutoff = 0.01
out = set([])
for pop, base in [("esp", "af_esp_all"), ("1000g", "af_1kg_all"),
("exac", "af_exac_all"), ("anypop", "max_aaf_all")]:
for key in [x for x in pops if x.startswith(base)]:
val = row[key]
if val and val > cutoff:
out.add(pop)
return sorted(list(out)) | [
"def",
"_known_populations",
"(",
"row",
",",
"pops",
")",
":",
"cutoff",
"=",
"0.01",
"out",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"pop",
",",
"base",
"in",
"[",
"(",
"\"esp\"",
",",
"\"af_esp_all\"",
")",
",",
"(",
"\"1000g\"",
",",
"\"af_1kg_all\... | Find variants present in substantial frequency in population databases. | [
"Find",
"variants",
"present",
"in",
"substantial",
"frequency",
"in",
"population",
"databases",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L163-L174 | train | 218,724 |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | _find_known | def _find_known(row):
"""Find variant present in known pathogenic databases.
"""
out = []
clinvar_no = set(["unknown", "untested", "non-pathogenic", "probable-non-pathogenic",
"uncertain_significance", "uncertain_significance", "not_provided",
"benign", "likely_benign"])
if row["cosmic_ids"] or row["cosmic_id"]:
out.append("cosmic")
if row["clinvar_sig"] and not row["clinvar_sig"].lower() in clinvar_no:
out.append("clinvar")
return out | python | def _find_known(row):
"""Find variant present in known pathogenic databases.
"""
out = []
clinvar_no = set(["unknown", "untested", "non-pathogenic", "probable-non-pathogenic",
"uncertain_significance", "uncertain_significance", "not_provided",
"benign", "likely_benign"])
if row["cosmic_ids"] or row["cosmic_id"]:
out.append("cosmic")
if row["clinvar_sig"] and not row["clinvar_sig"].lower() in clinvar_no:
out.append("clinvar")
return out | [
"def",
"_find_known",
"(",
"row",
")",
":",
"out",
"=",
"[",
"]",
"clinvar_no",
"=",
"set",
"(",
"[",
"\"unknown\"",
",",
"\"untested\"",
",",
"\"non-pathogenic\"",
",",
"\"probable-non-pathogenic\"",
",",
"\"uncertain_significance\"",
",",
"\"uncertain_significance... | Find variant present in known pathogenic databases. | [
"Find",
"variant",
"present",
"in",
"known",
"pathogenic",
"databases",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L176-L187 | train | 218,725 |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | _do_prioritize | def _do_prioritize(items):
"""Determine if we should perform prioritization.
Currently done on tumor-only input samples and feeding into PureCN
which needs the germline annotations.
"""
if not any("tumoronly-prioritization" in dd.get_tools_off(d) for d in items):
if vcfutils.get_paired_phenotype(items[0]):
has_tumor = False
has_normal = False
for sub_data in items:
if vcfutils.get_paired_phenotype(sub_data) == "tumor":
has_tumor = True
elif vcfutils.get_paired_phenotype(sub_data) == "normal":
has_normal = True
return has_tumor and not has_normal | python | def _do_prioritize(items):
"""Determine if we should perform prioritization.
Currently done on tumor-only input samples and feeding into PureCN
which needs the germline annotations.
"""
if not any("tumoronly-prioritization" in dd.get_tools_off(d) for d in items):
if vcfutils.get_paired_phenotype(items[0]):
has_tumor = False
has_normal = False
for sub_data in items:
if vcfutils.get_paired_phenotype(sub_data) == "tumor":
has_tumor = True
elif vcfutils.get_paired_phenotype(sub_data) == "normal":
has_normal = True
return has_tumor and not has_normal | [
"def",
"_do_prioritize",
"(",
"items",
")",
":",
"if",
"not",
"any",
"(",
"\"tumoronly-prioritization\"",
"in",
"dd",
".",
"get_tools_off",
"(",
"d",
")",
"for",
"d",
"in",
"items",
")",
":",
"if",
"vcfutils",
".",
"get_paired_phenotype",
"(",
"items",
"["... | Determine if we should perform prioritization.
Currently done on tumor-only input samples and feeding into PureCN
which needs the germline annotations. | [
"Determine",
"if",
"we",
"should",
"perform",
"prioritization",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L189-L204 | train | 218,726 |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | run_cortex | def run_cortex(align_bams, items, ref_file, assoc_files, region=None,
out_file=None):
"""Top level entry to regional de-novo based variant calling with cortex_var.
"""
raise NotImplementedError("Cortex currently out of date and needs reworking.")
if len(align_bams) == 1:
align_bam = align_bams[0]
config = items[0]["config"]
else:
raise NotImplementedError("Need to add multisample calling for cortex_var")
if out_file is None:
out_file = "%s-cortex.vcf" % os.path.splitext(align_bam)[0]
if region is not None:
work_dir = safe_makedir(os.path.join(os.path.dirname(out_file),
region.replace(".", "_")))
else:
work_dir = os.path.dirname(out_file)
if not file_exists(out_file):
bam.index(align_bam, config)
variant_regions = config["algorithm"].get("variant_regions", None)
if not variant_regions:
raise ValueError("Only support regional variant calling with cortex_var: set variant_regions")
target_regions = subset_variant_regions(variant_regions, region, out_file)
if os.path.isfile(target_regions):
with open(target_regions) as in_handle:
regional_vcfs = [_run_cortex_on_region(x.strip().split("\t")[:3], align_bam,
ref_file, work_dir, out_file, config)
for x in in_handle]
combine_file = "{0}-raw{1}".format(*os.path.splitext(out_file))
_combine_variants(regional_vcfs, combine_file, ref_file, config)
_select_final_variants(combine_file, out_file, config)
else:
vcfutils.write_empty_vcf(out_file)
return out_file | python | def run_cortex(align_bams, items, ref_file, assoc_files, region=None,
out_file=None):
"""Top level entry to regional de-novo based variant calling with cortex_var.
"""
raise NotImplementedError("Cortex currently out of date and needs reworking.")
if len(align_bams) == 1:
align_bam = align_bams[0]
config = items[0]["config"]
else:
raise NotImplementedError("Need to add multisample calling for cortex_var")
if out_file is None:
out_file = "%s-cortex.vcf" % os.path.splitext(align_bam)[0]
if region is not None:
work_dir = safe_makedir(os.path.join(os.path.dirname(out_file),
region.replace(".", "_")))
else:
work_dir = os.path.dirname(out_file)
if not file_exists(out_file):
bam.index(align_bam, config)
variant_regions = config["algorithm"].get("variant_regions", None)
if not variant_regions:
raise ValueError("Only support regional variant calling with cortex_var: set variant_regions")
target_regions = subset_variant_regions(variant_regions, region, out_file)
if os.path.isfile(target_regions):
with open(target_regions) as in_handle:
regional_vcfs = [_run_cortex_on_region(x.strip().split("\t")[:3], align_bam,
ref_file, work_dir, out_file, config)
for x in in_handle]
combine_file = "{0}-raw{1}".format(*os.path.splitext(out_file))
_combine_variants(regional_vcfs, combine_file, ref_file, config)
_select_final_variants(combine_file, out_file, config)
else:
vcfutils.write_empty_vcf(out_file)
return out_file | [
"def",
"run_cortex",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Cortex currently out of date and needs reworking.\"",
")",
"if",
... | Top level entry to regional de-novo based variant calling with cortex_var. | [
"Top",
"level",
"entry",
"to",
"regional",
"de",
"-",
"novo",
"based",
"variant",
"calling",
"with",
"cortex_var",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L28-L62 | train | 218,727 |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | _passes_cortex_depth | def _passes_cortex_depth(line, min_depth):
"""Do any genotypes in the cortex_var VCF line passes the minimum depth requirement?
"""
parts = line.split("\t")
cov_index = parts[8].split(":").index("COV")
passes_depth = False
for gt in parts[9:]:
cur_cov = gt.split(":")[cov_index]
cur_depth = sum(int(x) for x in cur_cov.split(","))
if cur_depth >= min_depth:
passes_depth = True
return passes_depth | python | def _passes_cortex_depth(line, min_depth):
"""Do any genotypes in the cortex_var VCF line passes the minimum depth requirement?
"""
parts = line.split("\t")
cov_index = parts[8].split(":").index("COV")
passes_depth = False
for gt in parts[9:]:
cur_cov = gt.split(":")[cov_index]
cur_depth = sum(int(x) for x in cur_cov.split(","))
if cur_depth >= min_depth:
passes_depth = True
return passes_depth | [
"def",
"_passes_cortex_depth",
"(",
"line",
",",
"min_depth",
")",
":",
"parts",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"cov_index",
"=",
"parts",
"[",
"8",
"]",
".",
"split",
"(",
"\":\"",
")",
".",
"index",
"(",
"\"COV\"",
")",
"passes_depth... | Do any genotypes in the cortex_var VCF line passes the minimum depth requirement? | [
"Do",
"any",
"genotypes",
"in",
"the",
"cortex_var",
"VCF",
"line",
"passes",
"the",
"minimum",
"depth",
"requirement?"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L64-L75 | train | 218,728 |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | _select_final_variants | def _select_final_variants(base_vcf, out_vcf, config):
"""Filter input file, removing items with low depth of support.
cortex_var calls are tricky to filter by depth. Count information is in
the COV FORMAT field grouped by alleles, so we need to sum up values and
compare.
"""
min_depth = int(config["algorithm"].get("min_depth", 4))
with file_transaction(out_vcf) as tx_out_file:
with open(base_vcf) as in_handle:
with open(tx_out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("#"):
passes = True
else:
passes = _passes_cortex_depth(line, min_depth)
if passes:
out_handle.write(line)
return out_vcf | python | def _select_final_variants(base_vcf, out_vcf, config):
"""Filter input file, removing items with low depth of support.
cortex_var calls are tricky to filter by depth. Count information is in
the COV FORMAT field grouped by alleles, so we need to sum up values and
compare.
"""
min_depth = int(config["algorithm"].get("min_depth", 4))
with file_transaction(out_vcf) as tx_out_file:
with open(base_vcf) as in_handle:
with open(tx_out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("#"):
passes = True
else:
passes = _passes_cortex_depth(line, min_depth)
if passes:
out_handle.write(line)
return out_vcf | [
"def",
"_select_final_variants",
"(",
"base_vcf",
",",
"out_vcf",
",",
"config",
")",
":",
"min_depth",
"=",
"int",
"(",
"config",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\"min_depth\"",
",",
"4",
")",
")",
"with",
"file_transaction",
"(",
"out_vcf",
... | Filter input file, removing items with low depth of support.
cortex_var calls are tricky to filter by depth. Count information is in
the COV FORMAT field grouped by alleles, so we need to sum up values and
compare. | [
"Filter",
"input",
"file",
"removing",
"items",
"with",
"low",
"depth",
"of",
"support",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L77-L95 | train | 218,729 |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | _combine_variants | def _combine_variants(in_vcfs, out_file, ref_file, config):
"""Combine variant files, writing the header from the first non-empty input.
in_vcfs is a list with each item starting with the chromosome regions,
and ending with the input file.
We sort by these regions to ensure the output file is in the expected order.
"""
in_vcfs.sort()
wrote_header = False
with open(out_file, "w") as out_handle:
for in_vcf in (x[-1] for x in in_vcfs):
with open(in_vcf) as in_handle:
header = list(itertools.takewhile(lambda x: x.startswith("#"),
in_handle))
if not header[0].startswith("##fileformat=VCFv4"):
raise ValueError("Unexpected VCF file: %s" % in_vcf)
for line in in_handle:
if not wrote_header:
wrote_header = True
out_handle.write("".join(header))
out_handle.write(line)
if not wrote_header:
out_handle.write("".join(header))
return out_file | python | def _combine_variants(in_vcfs, out_file, ref_file, config):
"""Combine variant files, writing the header from the first non-empty input.
in_vcfs is a list with each item starting with the chromosome regions,
and ending with the input file.
We sort by these regions to ensure the output file is in the expected order.
"""
in_vcfs.sort()
wrote_header = False
with open(out_file, "w") as out_handle:
for in_vcf in (x[-1] for x in in_vcfs):
with open(in_vcf) as in_handle:
header = list(itertools.takewhile(lambda x: x.startswith("#"),
in_handle))
if not header[0].startswith("##fileformat=VCFv4"):
raise ValueError("Unexpected VCF file: %s" % in_vcf)
for line in in_handle:
if not wrote_header:
wrote_header = True
out_handle.write("".join(header))
out_handle.write(line)
if not wrote_header:
out_handle.write("".join(header))
return out_file | [
"def",
"_combine_variants",
"(",
"in_vcfs",
",",
"out_file",
",",
"ref_file",
",",
"config",
")",
":",
"in_vcfs",
".",
"sort",
"(",
")",
"wrote_header",
"=",
"False",
"with",
"open",
"(",
"out_file",
",",
"\"w\"",
")",
"as",
"out_handle",
":",
"for",
"in... | Combine variant files, writing the header from the first non-empty input.
in_vcfs is a list with each item starting with the chromosome regions,
and ending with the input file.
We sort by these regions to ensure the output file is in the expected order. | [
"Combine",
"variant",
"files",
"writing",
"the",
"header",
"from",
"the",
"first",
"non",
"-",
"empty",
"input",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L97-L120 | train | 218,730 |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | _remap_cortex_out | def _remap_cortex_out(cortex_out, region, out_file):
"""Remap coordinates in local cortex variant calls to the original global region.
"""
def _remap_vcf_line(line, contig, start):
parts = line.split("\t")
if parts[0] == "" or parts[1] == "":
return None
parts[0] = contig
try:
parts[1] = str(int(parts[1]) + start)
except ValueError:
raise ValueError("Problem in {0} with \n{1}".format(
cortex_out, parts))
return "\t".join(parts)
def _not_filtered(line):
parts = line.split("\t")
return parts[6] == "PASS"
contig, start, _ = region
start = int(start)
with open(cortex_out) as in_handle:
with open(out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("##fileDate"):
pass
elif line.startswith("#"):
out_handle.write(line)
elif _not_filtered(line):
update_line = _remap_vcf_line(line, contig, start)
if update_line:
out_handle.write(update_line) | python | def _remap_cortex_out(cortex_out, region, out_file):
"""Remap coordinates in local cortex variant calls to the original global region.
"""
def _remap_vcf_line(line, contig, start):
parts = line.split("\t")
if parts[0] == "" or parts[1] == "":
return None
parts[0] = contig
try:
parts[1] = str(int(parts[1]) + start)
except ValueError:
raise ValueError("Problem in {0} with \n{1}".format(
cortex_out, parts))
return "\t".join(parts)
def _not_filtered(line):
parts = line.split("\t")
return parts[6] == "PASS"
contig, start, _ = region
start = int(start)
with open(cortex_out) as in_handle:
with open(out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("##fileDate"):
pass
elif line.startswith("#"):
out_handle.write(line)
elif _not_filtered(line):
update_line = _remap_vcf_line(line, contig, start)
if update_line:
out_handle.write(update_line) | [
"def",
"_remap_cortex_out",
"(",
"cortex_out",
",",
"region",
",",
"out_file",
")",
":",
"def",
"_remap_vcf_line",
"(",
"line",
",",
"contig",
",",
"start",
")",
":",
"parts",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"if",
"parts",
"[",
"0",
"]"... | Remap coordinates in local cortex variant calls to the original global region. | [
"Remap",
"coordinates",
"in",
"local",
"cortex",
"variant",
"calls",
"to",
"the",
"original",
"global",
"region",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L159-L188 | train | 218,731 |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | _run_cortex | def _run_cortex(fastq, indexes, params, out_base, dirs, config):
"""Run cortex_var run_calls.pl, producing a VCF variant file.
"""
print(out_base)
fastaq_index = "{0}.fastaq_index".format(out_base)
se_fastq_index = "{0}.se_fastq".format(out_base)
pe_fastq_index = "{0}.pe_fastq".format(out_base)
reffasta_index = "{0}.list_ref_fasta".format(out_base)
with open(se_fastq_index, "w") as out_handle:
out_handle.write(fastq + "\n")
with open(pe_fastq_index, "w") as out_handle:
out_handle.write("")
with open(fastaq_index, "w") as out_handle:
out_handle.write("{0}\t{1}\t{2}\t{2}\n".format(params["sample"], se_fastq_index,
pe_fastq_index))
with open(reffasta_index, "w") as out_handle:
for x in indexes["fasta"]:
out_handle.write(x + "\n")
os.environ["PERL5LIB"] = "{0}:{1}:{2}".format(
os.path.join(dirs["cortex"], "scripts/calling"),
os.path.join(dirs["cortex"], "scripts/analyse_variants/bioinf-perl/lib"),
os.environ.get("PERL5LIB", ""))
kmers = sorted(params["kmers"])
kmer_info = ["--first_kmer", str(kmers[0])]
if len(kmers) > 1:
kmer_info += ["--last_kmer", str(kmers[-1]),
"--kmer_step", str(kmers[1] - kmers[0])]
subprocess.check_call(["perl", os.path.join(dirs["cortex"], "scripts", "calling", "run_calls.pl"),
"--fastaq_index", fastaq_index,
"--auto_cleaning", "yes", "--bc", "yes", "--pd", "yes",
"--outdir", os.path.dirname(out_base), "--outvcf", os.path.basename(out_base),
"--ploidy", str(config["algorithm"].get("ploidy", 2)),
"--stampy_hash", indexes["stampy"],
"--stampy_bin", os.path.join(dirs["stampy"], "stampy.py"),
"--refbindir", os.path.dirname(indexes["cortex"][0]),
"--list_ref_fasta", reffasta_index,
"--genome_size", str(params["genome_size"]),
"--max_read_len", "30000",
#"--max_var_len", "4000",
"--format", "FASTQ", "--qthresh", "5", "--do_union", "yes",
"--mem_height", "17", "--mem_width", "100",
"--ref", "CoordinatesAndInCalling", "--workflow", "independent",
"--vcftools_dir", dirs["vcftools"],
"--logfile", "{0}.logfile,f".format(out_base)]
+ kmer_info)
final = glob.glob(os.path.join(os.path.dirname(out_base), "vcfs",
"{0}*FINALcombined_BC*decomp.vcf".format(os.path.basename(out_base))))
# No calls, need to setup an empty file
if len(final) != 1:
print("Did not find output VCF file for {0}".format(out_base))
return None
else:
return final[0] | python | def _run_cortex(fastq, indexes, params, out_base, dirs, config):
"""Run cortex_var run_calls.pl, producing a VCF variant file.
"""
print(out_base)
fastaq_index = "{0}.fastaq_index".format(out_base)
se_fastq_index = "{0}.se_fastq".format(out_base)
pe_fastq_index = "{0}.pe_fastq".format(out_base)
reffasta_index = "{0}.list_ref_fasta".format(out_base)
with open(se_fastq_index, "w") as out_handle:
out_handle.write(fastq + "\n")
with open(pe_fastq_index, "w") as out_handle:
out_handle.write("")
with open(fastaq_index, "w") as out_handle:
out_handle.write("{0}\t{1}\t{2}\t{2}\n".format(params["sample"], se_fastq_index,
pe_fastq_index))
with open(reffasta_index, "w") as out_handle:
for x in indexes["fasta"]:
out_handle.write(x + "\n")
os.environ["PERL5LIB"] = "{0}:{1}:{2}".format(
os.path.join(dirs["cortex"], "scripts/calling"),
os.path.join(dirs["cortex"], "scripts/analyse_variants/bioinf-perl/lib"),
os.environ.get("PERL5LIB", ""))
kmers = sorted(params["kmers"])
kmer_info = ["--first_kmer", str(kmers[0])]
if len(kmers) > 1:
kmer_info += ["--last_kmer", str(kmers[-1]),
"--kmer_step", str(kmers[1] - kmers[0])]
subprocess.check_call(["perl", os.path.join(dirs["cortex"], "scripts", "calling", "run_calls.pl"),
"--fastaq_index", fastaq_index,
"--auto_cleaning", "yes", "--bc", "yes", "--pd", "yes",
"--outdir", os.path.dirname(out_base), "--outvcf", os.path.basename(out_base),
"--ploidy", str(config["algorithm"].get("ploidy", 2)),
"--stampy_hash", indexes["stampy"],
"--stampy_bin", os.path.join(dirs["stampy"], "stampy.py"),
"--refbindir", os.path.dirname(indexes["cortex"][0]),
"--list_ref_fasta", reffasta_index,
"--genome_size", str(params["genome_size"]),
"--max_read_len", "30000",
#"--max_var_len", "4000",
"--format", "FASTQ", "--qthresh", "5", "--do_union", "yes",
"--mem_height", "17", "--mem_width", "100",
"--ref", "CoordinatesAndInCalling", "--workflow", "independent",
"--vcftools_dir", dirs["vcftools"],
"--logfile", "{0}.logfile,f".format(out_base)]
+ kmer_info)
final = glob.glob(os.path.join(os.path.dirname(out_base), "vcfs",
"{0}*FINALcombined_BC*decomp.vcf".format(os.path.basename(out_base))))
# No calls, need to setup an empty file
if len(final) != 1:
print("Did not find output VCF file for {0}".format(out_base))
return None
else:
return final[0] | [
"def",
"_run_cortex",
"(",
"fastq",
",",
"indexes",
",",
"params",
",",
"out_base",
",",
"dirs",
",",
"config",
")",
":",
"print",
"(",
"out_base",
")",
"fastaq_index",
"=",
"\"{0}.fastaq_index\"",
".",
"format",
"(",
"out_base",
")",
"se_fastq_index",
"=",
... | Run cortex_var run_calls.pl, producing a VCF variant file. | [
"Run",
"cortex_var",
"run_calls",
".",
"pl",
"producing",
"a",
"VCF",
"variant",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L190-L242 | train | 218,732 |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | _index_local_ref | def _index_local_ref(fasta_file, cortex_dir, stampy_dir, kmers):
"""Pre-index a generated local reference sequence with cortex_var and stampy.
"""
base_out = os.path.splitext(fasta_file)[0]
cindexes = []
for kmer in kmers:
out_file = "{0}.k{1}.ctx".format(base_out, kmer)
if not file_exists(out_file):
file_list = "{0}.se_list".format(base_out)
with open(file_list, "w") as out_handle:
out_handle.write(fasta_file + "\n")
subprocess.check_call([_get_cortex_binary(kmer, cortex_dir),
"--kmer_size", str(kmer), "--mem_height", "17",
"--se_list", file_list, "--format", "FASTA",
"--max_read_len", "30000",
"--sample_id", base_out,
"--dump_binary", out_file])
cindexes.append(out_file)
if not file_exists("{0}.stidx".format(base_out)):
subprocess.check_call([os.path.join(stampy_dir, "stampy.py"), "-G",
base_out, fasta_file])
subprocess.check_call([os.path.join(stampy_dir, "stampy.py"), "-g",
base_out, "-H", base_out])
return {"stampy": base_out,
"cortex": cindexes,
"fasta": [fasta_file]} | python | def _index_local_ref(fasta_file, cortex_dir, stampy_dir, kmers):
"""Pre-index a generated local reference sequence with cortex_var and stampy.
"""
base_out = os.path.splitext(fasta_file)[0]
cindexes = []
for kmer in kmers:
out_file = "{0}.k{1}.ctx".format(base_out, kmer)
if not file_exists(out_file):
file_list = "{0}.se_list".format(base_out)
with open(file_list, "w") as out_handle:
out_handle.write(fasta_file + "\n")
subprocess.check_call([_get_cortex_binary(kmer, cortex_dir),
"--kmer_size", str(kmer), "--mem_height", "17",
"--se_list", file_list, "--format", "FASTA",
"--max_read_len", "30000",
"--sample_id", base_out,
"--dump_binary", out_file])
cindexes.append(out_file)
if not file_exists("{0}.stidx".format(base_out)):
subprocess.check_call([os.path.join(stampy_dir, "stampy.py"), "-G",
base_out, fasta_file])
subprocess.check_call([os.path.join(stampy_dir, "stampy.py"), "-g",
base_out, "-H", base_out])
return {"stampy": base_out,
"cortex": cindexes,
"fasta": [fasta_file]} | [
"def",
"_index_local_ref",
"(",
"fasta_file",
",",
"cortex_dir",
",",
"stampy_dir",
",",
"kmers",
")",
":",
"base_out",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fasta_file",
")",
"[",
"0",
"]",
"cindexes",
"=",
"[",
"]",
"for",
"kmer",
"in",
"kme... | Pre-index a generated local reference sequence with cortex_var and stampy. | [
"Pre",
"-",
"index",
"a",
"generated",
"local",
"reference",
"sequence",
"with",
"cortex_var",
"and",
"stampy",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L255-L280 | train | 218,733 |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | _get_local_ref | def _get_local_ref(region, ref_file, out_vcf_base):
"""Retrieve a local FASTA file corresponding to the specified region.
"""
out_file = "{0}.fa".format(out_vcf_base)
if not file_exists(out_file):
with pysam.Fastafile(ref_file) as in_pysam:
contig, start, end = region
seq = in_pysam.fetch(contig, int(start), int(end))
with open(out_file, "w") as out_handle:
out_handle.write(">{0}-{1}-{2}\n{3}".format(contig, start, end,
str(seq)))
with open(out_file) as in_handle:
in_handle.readline()
size = len(in_handle.readline().strip())
return out_file, size | python | def _get_local_ref(region, ref_file, out_vcf_base):
"""Retrieve a local FASTA file corresponding to the specified region.
"""
out_file = "{0}.fa".format(out_vcf_base)
if not file_exists(out_file):
with pysam.Fastafile(ref_file) as in_pysam:
contig, start, end = region
seq = in_pysam.fetch(contig, int(start), int(end))
with open(out_file, "w") as out_handle:
out_handle.write(">{0}-{1}-{2}\n{3}".format(contig, start, end,
str(seq)))
with open(out_file) as in_handle:
in_handle.readline()
size = len(in_handle.readline().strip())
return out_file, size | [
"def",
"_get_local_ref",
"(",
"region",
",",
"ref_file",
",",
"out_vcf_base",
")",
":",
"out_file",
"=",
"\"{0}.fa\"",
".",
"format",
"(",
"out_vcf_base",
")",
"if",
"not",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"pysam",
".",
"Fastafile",
"(",
"... | Retrieve a local FASTA file corresponding to the specified region. | [
"Retrieve",
"a",
"local",
"FASTA",
"file",
"corresponding",
"to",
"the",
"specified",
"region",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L282-L296 | train | 218,734 |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | _get_fastq_in_region | def _get_fastq_in_region(region, align_bam, out_base):
"""Retrieve fastq files in region as single end.
Paired end is more complicated since pairs can map off the region, so focus
on local only assembly since we've previously used paired information for mapping.
"""
out_file = "{0}.fastq".format(out_base)
if not file_exists(out_file):
with pysam.Samfile(align_bam, "rb") as in_pysam:
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
contig, start, end = region
for read in in_pysam.fetch(contig, int(start), int(end)):
seq = Seq.Seq(read.seq)
qual = list(read.qual)
if read.is_reverse:
seq = seq.reverse_complement()
qual.reverse()
out_handle.write("@{name}\n{seq}\n+\n{qual}\n".format(
name=read.qname, seq=str(seq), qual="".join(qual)))
return out_file | python | def _get_fastq_in_region(region, align_bam, out_base):
"""Retrieve fastq files in region as single end.
Paired end is more complicated since pairs can map off the region, so focus
on local only assembly since we've previously used paired information for mapping.
"""
out_file = "{0}.fastq".format(out_base)
if not file_exists(out_file):
with pysam.Samfile(align_bam, "rb") as in_pysam:
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
contig, start, end = region
for read in in_pysam.fetch(contig, int(start), int(end)):
seq = Seq.Seq(read.seq)
qual = list(read.qual)
if read.is_reverse:
seq = seq.reverse_complement()
qual.reverse()
out_handle.write("@{name}\n{seq}\n+\n{qual}\n".format(
name=read.qname, seq=str(seq), qual="".join(qual)))
return out_file | [
"def",
"_get_fastq_in_region",
"(",
"region",
",",
"align_bam",
",",
"out_base",
")",
":",
"out_file",
"=",
"\"{0}.fastq\"",
".",
"format",
"(",
"out_base",
")",
"if",
"not",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"pysam",
".",
"Samfile",
"(",
"... | Retrieve fastq files in region as single end.
Paired end is more complicated since pairs can map off the region, so focus
on local only assembly since we've previously used paired information for mapping. | [
"Retrieve",
"fastq",
"files",
"in",
"region",
"as",
"single",
"end",
".",
"Paired",
"end",
"is",
"more",
"complicated",
"since",
"pairs",
"can",
"map",
"off",
"the",
"region",
"so",
"focus",
"on",
"local",
"only",
"assembly",
"since",
"we",
"ve",
"previous... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L298-L317 | train | 218,735 |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | _count_fastq_reads | def _count_fastq_reads(in_fastq, min_reads):
"""Count the number of fastq reads in a file, stopping after reaching min_reads.
"""
with open(in_fastq) as in_handle:
items = list(itertools.takewhile(lambda i : i <= min_reads,
(i for i, _ in enumerate(FastqGeneralIterator(in_handle)))))
return len(items) | python | def _count_fastq_reads(in_fastq, min_reads):
"""Count the number of fastq reads in a file, stopping after reaching min_reads.
"""
with open(in_fastq) as in_handle:
items = list(itertools.takewhile(lambda i : i <= min_reads,
(i for i, _ in enumerate(FastqGeneralIterator(in_handle)))))
return len(items) | [
"def",
"_count_fastq_reads",
"(",
"in_fastq",
",",
"min_reads",
")",
":",
"with",
"open",
"(",
"in_fastq",
")",
"as",
"in_handle",
":",
"items",
"=",
"list",
"(",
"itertools",
".",
"takewhile",
"(",
"lambda",
"i",
":",
"i",
"<=",
"min_reads",
",",
"(",
... | Count the number of fastq reads in a file, stopping after reaching min_reads. | [
"Count",
"the",
"number",
"of",
"fastq",
"reads",
"in",
"a",
"file",
"stopping",
"after",
"reaching",
"min_reads",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L321-L327 | train | 218,736 |
bcbio/bcbio-nextgen | bcbio/distributed/transaction.py | _move_file_with_sizecheck | def _move_file_with_sizecheck(tx_file, final_file):
"""Move transaction file to final location,
with size checks avoiding failed transfers.
Creates an empty file with '.bcbiotmp' extention in the destination
location, which serves as a flag. If a file like that is present,
it means that transaction didn't finish successfully.
"""
#logger.debug("Moving %s to %s" % (tx_file, final_file))
tmp_file = final_file + ".bcbiotmp"
open(tmp_file, 'wb').close()
want_size = utils.get_size(tx_file)
shutil.move(tx_file, final_file)
transfer_size = utils.get_size(final_file)
assert want_size == transfer_size, (
'distributed.transaction.file_transaction: File copy error: '
'file or directory on temporary storage ({}) size {} bytes '
'does not equal size of file or directory after transfer to '
'shared storage ({}) size {} bytes'.format(
tx_file, want_size, final_file, transfer_size)
)
utils.remove_safe(tmp_file) | python | def _move_file_with_sizecheck(tx_file, final_file):
"""Move transaction file to final location,
with size checks avoiding failed transfers.
Creates an empty file with '.bcbiotmp' extention in the destination
location, which serves as a flag. If a file like that is present,
it means that transaction didn't finish successfully.
"""
#logger.debug("Moving %s to %s" % (tx_file, final_file))
tmp_file = final_file + ".bcbiotmp"
open(tmp_file, 'wb').close()
want_size = utils.get_size(tx_file)
shutil.move(tx_file, final_file)
transfer_size = utils.get_size(final_file)
assert want_size == transfer_size, (
'distributed.transaction.file_transaction: File copy error: '
'file or directory on temporary storage ({}) size {} bytes '
'does not equal size of file or directory after transfer to '
'shared storage ({}) size {} bytes'.format(
tx_file, want_size, final_file, transfer_size)
)
utils.remove_safe(tmp_file) | [
"def",
"_move_file_with_sizecheck",
"(",
"tx_file",
",",
"final_file",
")",
":",
"#logger.debug(\"Moving %s to %s\" % (tx_file, final_file))",
"tmp_file",
"=",
"final_file",
"+",
"\".bcbiotmp\"",
"open",
"(",
"tmp_file",
",",
"'wb'",
")",
".",
"close",
"(",
")",
"want... | Move transaction file to final location,
with size checks avoiding failed transfers.
Creates an empty file with '.bcbiotmp' extention in the destination
location, which serves as a flag. If a file like that is present,
it means that transaction didn't finish successfully. | [
"Move",
"transaction",
"file",
"to",
"final",
"location",
"with",
"size",
"checks",
"avoiding",
"failed",
"transfers",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/transaction.py#L102-L127 | train | 218,737 |
bcbio/bcbio-nextgen | bcbio/variation/bamprep.py | _gatk_extract_reads_cl | def _gatk_extract_reads_cl(data, region, prep_params, tmp_dir):
"""Use GATK to extract reads from full BAM file.
"""
args = ["PrintReads",
"-L", region_to_gatk(region),
"-R", dd.get_ref_file(data),
"-I", data["work_bam"]]
# GATK3 back compatibility, need to specify analysis type
if "gatk4" in dd.get_tools_off(data):
args = ["--analysis_type"] + args
runner = broad.runner_from_config(data["config"])
return runner.cl_gatk(args, tmp_dir) | python | def _gatk_extract_reads_cl(data, region, prep_params, tmp_dir):
"""Use GATK to extract reads from full BAM file.
"""
args = ["PrintReads",
"-L", region_to_gatk(region),
"-R", dd.get_ref_file(data),
"-I", data["work_bam"]]
# GATK3 back compatibility, need to specify analysis type
if "gatk4" in dd.get_tools_off(data):
args = ["--analysis_type"] + args
runner = broad.runner_from_config(data["config"])
return runner.cl_gatk(args, tmp_dir) | [
"def",
"_gatk_extract_reads_cl",
"(",
"data",
",",
"region",
",",
"prep_params",
",",
"tmp_dir",
")",
":",
"args",
"=",
"[",
"\"PrintReads\"",
",",
"\"-L\"",
",",
"region_to_gatk",
"(",
"region",
")",
",",
"\"-R\"",
",",
"dd",
".",
"get_ref_file",
"(",
"da... | Use GATK to extract reads from full BAM file. | [
"Use",
"GATK",
"to",
"extract",
"reads",
"from",
"full",
"BAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bamprep.py#L23-L34 | train | 218,738 |
bcbio/bcbio-nextgen | bcbio/variation/bamprep.py | _piped_input_cl | def _piped_input_cl(data, region, tmp_dir, out_base_file, prep_params):
"""Retrieve the commandline for streaming input into preparation step.
"""
return data["work_bam"], _gatk_extract_reads_cl(data, region, prep_params, tmp_dir) | python | def _piped_input_cl(data, region, tmp_dir, out_base_file, prep_params):
"""Retrieve the commandline for streaming input into preparation step.
"""
return data["work_bam"], _gatk_extract_reads_cl(data, region, prep_params, tmp_dir) | [
"def",
"_piped_input_cl",
"(",
"data",
",",
"region",
",",
"tmp_dir",
",",
"out_base_file",
",",
"prep_params",
")",
":",
"return",
"data",
"[",
"\"work_bam\"",
"]",
",",
"_gatk_extract_reads_cl",
"(",
"data",
",",
"region",
",",
"prep_params",
",",
"tmp_dir",... | Retrieve the commandline for streaming input into preparation step. | [
"Retrieve",
"the",
"commandline",
"for",
"streaming",
"input",
"into",
"preparation",
"step",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bamprep.py#L36-L39 | train | 218,739 |
bcbio/bcbio-nextgen | bcbio/variation/bamprep.py | _piped_realign_gatk | def _piped_realign_gatk(data, region, cl, out_base_file, tmp_dir, prep_params):
"""Perform realignment with GATK, using input commandline.
GATK requires writing to disk and indexing before realignment.
"""
broad_runner = broad.runner_from_config(data["config"])
pa_bam = "%s-prealign%s" % os.path.splitext(out_base_file)
if not utils.file_exists(pa_bam):
with file_transaction(data, pa_bam) as tx_out_file:
cmd = "{cl} -o {tx_out_file}".format(**locals())
do.run(cmd, "GATK re-alignment {0}".format(region), data)
bam.index(pa_bam, data["config"])
realn_file = realign.gatk_realigner_targets(broad_runner, pa_bam, dd.get_ref_file(data), data["config"],
region=region_to_gatk(region),
known_vrns=dd.get_variation_resources(data))
realn_cl = realign.gatk_indel_realignment_cl(broad_runner, pa_bam, dd.get_ref_file(data),
realn_file, tmp_dir, region=region_to_gatk(region),
known_vrns=dd.get_variation_resources(data))
return pa_bam, realn_cl | python | def _piped_realign_gatk(data, region, cl, out_base_file, tmp_dir, prep_params):
"""Perform realignment with GATK, using input commandline.
GATK requires writing to disk and indexing before realignment.
"""
broad_runner = broad.runner_from_config(data["config"])
pa_bam = "%s-prealign%s" % os.path.splitext(out_base_file)
if not utils.file_exists(pa_bam):
with file_transaction(data, pa_bam) as tx_out_file:
cmd = "{cl} -o {tx_out_file}".format(**locals())
do.run(cmd, "GATK re-alignment {0}".format(region), data)
bam.index(pa_bam, data["config"])
realn_file = realign.gatk_realigner_targets(broad_runner, pa_bam, dd.get_ref_file(data), data["config"],
region=region_to_gatk(region),
known_vrns=dd.get_variation_resources(data))
realn_cl = realign.gatk_indel_realignment_cl(broad_runner, pa_bam, dd.get_ref_file(data),
realn_file, tmp_dir, region=region_to_gatk(region),
known_vrns=dd.get_variation_resources(data))
return pa_bam, realn_cl | [
"def",
"_piped_realign_gatk",
"(",
"data",
",",
"region",
",",
"cl",
",",
"out_base_file",
",",
"tmp_dir",
",",
"prep_params",
")",
":",
"broad_runner",
"=",
"broad",
".",
"runner_from_config",
"(",
"data",
"[",
"\"config\"",
"]",
")",
"pa_bam",
"=",
"\"%s-p... | Perform realignment with GATK, using input commandline.
GATK requires writing to disk and indexing before realignment. | [
"Perform",
"realignment",
"with",
"GATK",
"using",
"input",
"commandline",
".",
"GATK",
"requires",
"writing",
"to",
"disk",
"and",
"indexing",
"before",
"realignment",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bamprep.py#L41-L58 | train | 218,740 |
bcbio/bcbio-nextgen | bcbio/variation/bamprep.py | _get_prep_params | def _get_prep_params(data):
"""Retrieve configuration parameters with defaults for preparing BAM files.
"""
realign_param = dd.get_realign(data)
realign_param = "gatk" if realign_param is True else realign_param
return {"realign": realign_param} | python | def _get_prep_params(data):
"""Retrieve configuration parameters with defaults for preparing BAM files.
"""
realign_param = dd.get_realign(data)
realign_param = "gatk" if realign_param is True else realign_param
return {"realign": realign_param} | [
"def",
"_get_prep_params",
"(",
"data",
")",
":",
"realign_param",
"=",
"dd",
".",
"get_realign",
"(",
"data",
")",
"realign_param",
"=",
"\"gatk\"",
"if",
"realign_param",
"is",
"True",
"else",
"realign_param",
"return",
"{",
"\"realign\"",
":",
"realign_param"... | Retrieve configuration parameters with defaults for preparing BAM files. | [
"Retrieve",
"configuration",
"parameters",
"with",
"defaults",
"for",
"preparing",
"BAM",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bamprep.py#L90-L95 | train | 218,741 |
bcbio/bcbio-nextgen | bcbio/variation/bamprep.py | _piped_bamprep_region | def _piped_bamprep_region(data, region, out_file, tmp_dir):
"""Do work of preparing BAM input file on the selected region.
"""
if _need_prep(data):
prep_params = _get_prep_params(data)
_piped_bamprep_region_gatk(data, region, prep_params, out_file, tmp_dir)
else:
raise ValueError("No realignment specified") | python | def _piped_bamprep_region(data, region, out_file, tmp_dir):
"""Do work of preparing BAM input file on the selected region.
"""
if _need_prep(data):
prep_params = _get_prep_params(data)
_piped_bamprep_region_gatk(data, region, prep_params, out_file, tmp_dir)
else:
raise ValueError("No realignment specified") | [
"def",
"_piped_bamprep_region",
"(",
"data",
",",
"region",
",",
"out_file",
",",
"tmp_dir",
")",
":",
"if",
"_need_prep",
"(",
"data",
")",
":",
"prep_params",
"=",
"_get_prep_params",
"(",
"data",
")",
"_piped_bamprep_region_gatk",
"(",
"data",
",",
"region"... | Do work of preparing BAM input file on the selected region. | [
"Do",
"work",
"of",
"preparing",
"BAM",
"input",
"file",
"on",
"the",
"selected",
"region",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bamprep.py#L101-L108 | train | 218,742 |
bcbio/bcbio-nextgen | bcbio/variation/bamprep.py | piped_bamprep | def piped_bamprep(data, region=None, out_file=None):
"""Perform full BAM preparation using pipes to avoid intermediate disk IO.
Handles realignment of original BAMs.
"""
data["region"] = region
if not _need_prep(data):
return [data]
else:
utils.safe_makedir(os.path.dirname(out_file))
if region[0] == "nochrom":
prep_bam = shared.write_nochr_reads(data["work_bam"], out_file, data["config"])
elif region[0] == "noanalysis":
prep_bam = shared.write_noanalysis_reads(data["work_bam"], region[1], out_file,
data["config"])
else:
if not utils.file_exists(out_file):
with tx_tmpdir(data) as tmp_dir:
_piped_bamprep_region(data, region, out_file, tmp_dir)
prep_bam = out_file
bam.index(prep_bam, data["config"])
data["work_bam"] = prep_bam
return [data] | python | def piped_bamprep(data, region=None, out_file=None):
"""Perform full BAM preparation using pipes to avoid intermediate disk IO.
Handles realignment of original BAMs.
"""
data["region"] = region
if not _need_prep(data):
return [data]
else:
utils.safe_makedir(os.path.dirname(out_file))
if region[0] == "nochrom":
prep_bam = shared.write_nochr_reads(data["work_bam"], out_file, data["config"])
elif region[0] == "noanalysis":
prep_bam = shared.write_noanalysis_reads(data["work_bam"], region[1], out_file,
data["config"])
else:
if not utils.file_exists(out_file):
with tx_tmpdir(data) as tmp_dir:
_piped_bamprep_region(data, region, out_file, tmp_dir)
prep_bam = out_file
bam.index(prep_bam, data["config"])
data["work_bam"] = prep_bam
return [data] | [
"def",
"piped_bamprep",
"(",
"data",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"data",
"[",
"\"region\"",
"]",
"=",
"region",
"if",
"not",
"_need_prep",
"(",
"data",
")",
":",
"return",
"[",
"data",
"]",
"else",
":",
"utils"... | Perform full BAM preparation using pipes to avoid intermediate disk IO.
Handles realignment of original BAMs. | [
"Perform",
"full",
"BAM",
"preparation",
"using",
"pipes",
"to",
"avoid",
"intermediate",
"disk",
"IO",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bamprep.py#L110-L132 | train | 218,743 |
bcbio/bcbio-nextgen | bcbio/upload/galaxy.py | update_file | def update_file(finfo, sample_info, config):
"""Update file in Galaxy data libraries.
"""
if GalaxyInstance is None:
raise ImportError("Could not import bioblend.galaxy")
if "dir" not in config:
raise ValueError("Galaxy upload requires `dir` parameter in config specifying the "
"shared filesystem path to move files to.")
if "outputs" in config:
_galaxy_tool_copy(finfo, config["outputs"])
else:
_galaxy_library_upload(finfo, sample_info, config) | python | def update_file(finfo, sample_info, config):
"""Update file in Galaxy data libraries.
"""
if GalaxyInstance is None:
raise ImportError("Could not import bioblend.galaxy")
if "dir" not in config:
raise ValueError("Galaxy upload requires `dir` parameter in config specifying the "
"shared filesystem path to move files to.")
if "outputs" in config:
_galaxy_tool_copy(finfo, config["outputs"])
else:
_galaxy_library_upload(finfo, sample_info, config) | [
"def",
"update_file",
"(",
"finfo",
",",
"sample_info",
",",
"config",
")",
":",
"if",
"GalaxyInstance",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"\"Could not import bioblend.galaxy\"",
")",
"if",
"\"dir\"",
"not",
"in",
"config",
":",
"raise",
"ValueErro... | Update file in Galaxy data libraries. | [
"Update",
"file",
"in",
"Galaxy",
"data",
"libraries",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/galaxy.py#L28-L39 | train | 218,744 |
bcbio/bcbio-nextgen | bcbio/upload/galaxy.py | _galaxy_tool_copy | def _galaxy_tool_copy(finfo, outputs):
"""Copy information directly to pre-defined outputs from a Galaxy tool.
XXX Needs generalization
"""
tool_map = {"align": "bam", "variants": "vcf.gz"}
for galaxy_key, finfo_type in tool_map.items():
if galaxy_key in outputs and finfo.get("type") == finfo_type:
shutil.copy(finfo["path"], outputs[galaxy_key]) | python | def _galaxy_tool_copy(finfo, outputs):
"""Copy information directly to pre-defined outputs from a Galaxy tool.
XXX Needs generalization
"""
tool_map = {"align": "bam", "variants": "vcf.gz"}
for galaxy_key, finfo_type in tool_map.items():
if galaxy_key in outputs and finfo.get("type") == finfo_type:
shutil.copy(finfo["path"], outputs[galaxy_key]) | [
"def",
"_galaxy_tool_copy",
"(",
"finfo",
",",
"outputs",
")",
":",
"tool_map",
"=",
"{",
"\"align\"",
":",
"\"bam\"",
",",
"\"variants\"",
":",
"\"vcf.gz\"",
"}",
"for",
"galaxy_key",
",",
"finfo_type",
"in",
"tool_map",
".",
"items",
"(",
")",
":",
"if",... | Copy information directly to pre-defined outputs from a Galaxy tool.
XXX Needs generalization | [
"Copy",
"information",
"directly",
"to",
"pre",
"-",
"defined",
"outputs",
"from",
"a",
"Galaxy",
"tool",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/galaxy.py#L41-L49 | train | 218,745 |
bcbio/bcbio-nextgen | bcbio/upload/galaxy.py | _galaxy_library_upload | def _galaxy_library_upload(finfo, sample_info, config):
"""Upload results to galaxy library.
"""
folder_name = "%s_%s" % (config["fc_date"], config["fc_name"])
storage_dir = utils.safe_makedir(os.path.join(config["dir"], folder_name))
if finfo.get("type") == "directory":
storage_file = None
if finfo.get("ext") == "qc":
pdf_file = qcsummary.prep_pdf(finfo["path"], config)
if pdf_file:
finfo["path"] = pdf_file
finfo["type"] = "pdf"
storage_file = filesystem.copy_finfo(finfo, storage_dir, pass_uptodate=True)
else:
storage_file = filesystem.copy_finfo(finfo, storage_dir, pass_uptodate=True)
if "galaxy_url" in config and "galaxy_api_key" in config:
galaxy_url = config["galaxy_url"]
if not galaxy_url.endswith("/"):
galaxy_url += "/"
gi = GalaxyInstance(galaxy_url, config["galaxy_api_key"])
else:
raise ValueError("Galaxy upload requires `galaxy_url` and `galaxy_api_key` in config")
if storage_file and sample_info and not finfo.get("index", False) and not finfo.get("plus", False):
_to_datalibrary_safe(storage_file, gi, folder_name, sample_info, config) | python | def _galaxy_library_upload(finfo, sample_info, config):
"""Upload results to galaxy library.
"""
folder_name = "%s_%s" % (config["fc_date"], config["fc_name"])
storage_dir = utils.safe_makedir(os.path.join(config["dir"], folder_name))
if finfo.get("type") == "directory":
storage_file = None
if finfo.get("ext") == "qc":
pdf_file = qcsummary.prep_pdf(finfo["path"], config)
if pdf_file:
finfo["path"] = pdf_file
finfo["type"] = "pdf"
storage_file = filesystem.copy_finfo(finfo, storage_dir, pass_uptodate=True)
else:
storage_file = filesystem.copy_finfo(finfo, storage_dir, pass_uptodate=True)
if "galaxy_url" in config and "galaxy_api_key" in config:
galaxy_url = config["galaxy_url"]
if not galaxy_url.endswith("/"):
galaxy_url += "/"
gi = GalaxyInstance(galaxy_url, config["galaxy_api_key"])
else:
raise ValueError("Galaxy upload requires `galaxy_url` and `galaxy_api_key` in config")
if storage_file and sample_info and not finfo.get("index", False) and not finfo.get("plus", False):
_to_datalibrary_safe(storage_file, gi, folder_name, sample_info, config) | [
"def",
"_galaxy_library_upload",
"(",
"finfo",
",",
"sample_info",
",",
"config",
")",
":",
"folder_name",
"=",
"\"%s_%s\"",
"%",
"(",
"config",
"[",
"\"fc_date\"",
"]",
",",
"config",
"[",
"\"fc_name\"",
"]",
")",
"storage_dir",
"=",
"utils",
".",
"safe_mak... | Upload results to galaxy library. | [
"Upload",
"results",
"to",
"galaxy",
"library",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/galaxy.py#L51-L74 | train | 218,746 |
bcbio/bcbio-nextgen | bcbio/upload/galaxy.py | _to_datalibrary_safe | def _to_datalibrary_safe(fname, gi, folder_name, sample_info, config):
"""Upload with retries for intermittent JSON failures.
"""
num_tries = 0
max_tries = 5
while 1:
try:
_to_datalibrary(fname, gi, folder_name, sample_info, config)
break
except (simplejson.scanner.JSONDecodeError, bioblend.galaxy.client.ConnectionError) as e:
num_tries += 1
if num_tries > max_tries:
raise
print("Retrying upload, failed with:", str(e))
time.sleep(5) | python | def _to_datalibrary_safe(fname, gi, folder_name, sample_info, config):
"""Upload with retries for intermittent JSON failures.
"""
num_tries = 0
max_tries = 5
while 1:
try:
_to_datalibrary(fname, gi, folder_name, sample_info, config)
break
except (simplejson.scanner.JSONDecodeError, bioblend.galaxy.client.ConnectionError) as e:
num_tries += 1
if num_tries > max_tries:
raise
print("Retrying upload, failed with:", str(e))
time.sleep(5) | [
"def",
"_to_datalibrary_safe",
"(",
"fname",
",",
"gi",
",",
"folder_name",
",",
"sample_info",
",",
"config",
")",
":",
"num_tries",
"=",
"0",
"max_tries",
"=",
"5",
"while",
"1",
":",
"try",
":",
"_to_datalibrary",
"(",
"fname",
",",
"gi",
",",
"folder... | Upload with retries for intermittent JSON failures. | [
"Upload",
"with",
"retries",
"for",
"intermittent",
"JSON",
"failures",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/galaxy.py#L76-L90 | train | 218,747 |
bcbio/bcbio-nextgen | bcbio/upload/galaxy.py | _to_datalibrary | def _to_datalibrary(fname, gi, folder_name, sample_info, config):
"""Upload a file to a Galaxy data library in a project specific folder.
"""
library = _get_library(gi, sample_info, config)
libitems = gi.libraries.show_library(library.id, contents=True)
folder = _get_folder(gi, folder_name, library, libitems)
_file_to_folder(gi, fname, sample_info, libitems, library, folder) | python | def _to_datalibrary(fname, gi, folder_name, sample_info, config):
"""Upload a file to a Galaxy data library in a project specific folder.
"""
library = _get_library(gi, sample_info, config)
libitems = gi.libraries.show_library(library.id, contents=True)
folder = _get_folder(gi, folder_name, library, libitems)
_file_to_folder(gi, fname, sample_info, libitems, library, folder) | [
"def",
"_to_datalibrary",
"(",
"fname",
",",
"gi",
",",
"folder_name",
",",
"sample_info",
",",
"config",
")",
":",
"library",
"=",
"_get_library",
"(",
"gi",
",",
"sample_info",
",",
"config",
")",
"libitems",
"=",
"gi",
".",
"libraries",
".",
"show_libra... | Upload a file to a Galaxy data library in a project specific folder. | [
"Upload",
"a",
"file",
"to",
"a",
"Galaxy",
"data",
"library",
"in",
"a",
"project",
"specific",
"folder",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/galaxy.py#L92-L98 | train | 218,748 |
bcbio/bcbio-nextgen | bcbio/upload/galaxy.py | _file_to_folder | def _file_to_folder(gi, fname, sample_info, libitems, library, folder):
"""Check if file exists on Galaxy, if not upload to specified folder.
"""
full_name = os.path.join(folder["name"], os.path.basename(fname))
# Handle VCF: Galaxy reports VCF files without the gzip extension
file_type = "vcf_bgzip" if full_name.endswith(".vcf.gz") else "auto"
if full_name.endswith(".vcf.gz"):
full_name = full_name.replace(".vcf.gz", ".vcf")
for item in libitems:
if item["name"] == full_name:
return item
logger.info("Uploading to Galaxy library '%s': %s" % (library.name, full_name))
return gi.libraries.upload_from_galaxy_filesystem(str(library.id), fname, folder_id=str(folder["id"]),
link_data_only="link_to_files",
dbkey=sample_info["genome_build"],
file_type=file_type,
roles=str(library.roles) if library.roles else None) | python | def _file_to_folder(gi, fname, sample_info, libitems, library, folder):
"""Check if file exists on Galaxy, if not upload to specified folder.
"""
full_name = os.path.join(folder["name"], os.path.basename(fname))
# Handle VCF: Galaxy reports VCF files without the gzip extension
file_type = "vcf_bgzip" if full_name.endswith(".vcf.gz") else "auto"
if full_name.endswith(".vcf.gz"):
full_name = full_name.replace(".vcf.gz", ".vcf")
for item in libitems:
if item["name"] == full_name:
return item
logger.info("Uploading to Galaxy library '%s': %s" % (library.name, full_name))
return gi.libraries.upload_from_galaxy_filesystem(str(library.id), fname, folder_id=str(folder["id"]),
link_data_only="link_to_files",
dbkey=sample_info["genome_build"],
file_type=file_type,
roles=str(library.roles) if library.roles else None) | [
"def",
"_file_to_folder",
"(",
"gi",
",",
"fname",
",",
"sample_info",
",",
"libitems",
",",
"library",
",",
"folder",
")",
":",
"full_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
"[",
"\"name\"",
"]",
",",
"os",
".",
"path",
".",
"base... | Check if file exists on Galaxy, if not upload to specified folder. | [
"Check",
"if",
"file",
"exists",
"on",
"Galaxy",
"if",
"not",
"upload",
"to",
"specified",
"folder",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/galaxy.py#L100-L118 | train | 218,749 |
bcbio/bcbio-nextgen | bcbio/upload/galaxy.py | _get_folder | def _get_folder(gi, folder_name, library, libitems):
"""Retrieve or create a folder inside the library with the specified name.
"""
for item in libitems:
if item["type"] == "folder" and item["name"] == "/%s" % folder_name:
return item
return gi.libraries.create_folder(library.id, folder_name)[0] | python | def _get_folder(gi, folder_name, library, libitems):
"""Retrieve or create a folder inside the library with the specified name.
"""
for item in libitems:
if item["type"] == "folder" and item["name"] == "/%s" % folder_name:
return item
return gi.libraries.create_folder(library.id, folder_name)[0] | [
"def",
"_get_folder",
"(",
"gi",
",",
"folder_name",
",",
"library",
",",
"libitems",
")",
":",
"for",
"item",
"in",
"libitems",
":",
"if",
"item",
"[",
"\"type\"",
"]",
"==",
"\"folder\"",
"and",
"item",
"[",
"\"name\"",
"]",
"==",
"\"/%s\"",
"%",
"fo... | Retrieve or create a folder inside the library with the specified name. | [
"Retrieve",
"or",
"create",
"a",
"folder",
"inside",
"the",
"library",
"with",
"the",
"specified",
"name",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/galaxy.py#L120-L126 | train | 218,750 |
bcbio/bcbio-nextgen | bcbio/upload/galaxy.py | _get_library | def _get_library(gi, sample_info, config):
"""Retrieve the appropriate data library for the current user.
"""
galaxy_lib = sample_info.get("galaxy_library",
config.get("galaxy_library"))
role = sample_info.get("galaxy_role",
config.get("galaxy_role"))
if galaxy_lib:
return _get_library_from_name(gi, galaxy_lib, role, sample_info, create=True)
elif config.get("private_libs") or config.get("lab_association") or config.get("researcher"):
return _library_from_nglims(gi, sample_info, config)
else:
raise ValueError("No Galaxy library specified for sample: %s" %
sample_info["description"]) | python | def _get_library(gi, sample_info, config):
"""Retrieve the appropriate data library for the current user.
"""
galaxy_lib = sample_info.get("galaxy_library",
config.get("galaxy_library"))
role = sample_info.get("galaxy_role",
config.get("galaxy_role"))
if galaxy_lib:
return _get_library_from_name(gi, galaxy_lib, role, sample_info, create=True)
elif config.get("private_libs") or config.get("lab_association") or config.get("researcher"):
return _library_from_nglims(gi, sample_info, config)
else:
raise ValueError("No Galaxy library specified for sample: %s" %
sample_info["description"]) | [
"def",
"_get_library",
"(",
"gi",
",",
"sample_info",
",",
"config",
")",
":",
"galaxy_lib",
"=",
"sample_info",
".",
"get",
"(",
"\"galaxy_library\"",
",",
"config",
".",
"get",
"(",
"\"galaxy_library\"",
")",
")",
"role",
"=",
"sample_info",
".",
"get",
... | Retrieve the appropriate data library for the current user. | [
"Retrieve",
"the",
"appropriate",
"data",
"library",
"for",
"the",
"current",
"user",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/galaxy.py#L130-L143 | train | 218,751 |
bcbio/bcbio-nextgen | bcbio/upload/galaxy.py | _library_from_nglims | def _library_from_nglims(gi, sample_info, config):
"""Retrieve upload library from nglims specified user libraries.
"""
names = [config.get(x, "").strip() for x in ["lab_association", "researcher"]
if config.get(x)]
for name in names:
for ext in ["sequencing", "lab"]:
check_name = "%s %s" % (name.split()[0], ext)
try:
return _get_library_from_name(gi, check_name, None, sample_info)
except ValueError:
pass
check_names = set([x.lower() for x in names])
for libname, role in config["private_libs"]:
# Try to find library for lab or rsearcher
if libname.lower() in check_names:
return _get_library_from_name(gi, libname, role, sample_info)
# default to first private library if available
if len(config.get("private_libs", [])) > 0:
libname, role = config["private_libs"][0]
return _get_library_from_name(gi, libname, role, sample_info)
# otherwise use the lab association or researcher name
elif len(names) > 0:
return _get_library_from_name(gi, names[0], None, sample_info, create=True)
else:
raise ValueError("Could not find Galaxy library for sample %s" % sample_info["description"]) | python | def _library_from_nglims(gi, sample_info, config):
"""Retrieve upload library from nglims specified user libraries.
"""
names = [config.get(x, "").strip() for x in ["lab_association", "researcher"]
if config.get(x)]
for name in names:
for ext in ["sequencing", "lab"]:
check_name = "%s %s" % (name.split()[0], ext)
try:
return _get_library_from_name(gi, check_name, None, sample_info)
except ValueError:
pass
check_names = set([x.lower() for x in names])
for libname, role in config["private_libs"]:
# Try to find library for lab or rsearcher
if libname.lower() in check_names:
return _get_library_from_name(gi, libname, role, sample_info)
# default to first private library if available
if len(config.get("private_libs", [])) > 0:
libname, role = config["private_libs"][0]
return _get_library_from_name(gi, libname, role, sample_info)
# otherwise use the lab association or researcher name
elif len(names) > 0:
return _get_library_from_name(gi, names[0], None, sample_info, create=True)
else:
raise ValueError("Could not find Galaxy library for sample %s" % sample_info["description"]) | [
"def",
"_library_from_nglims",
"(",
"gi",
",",
"sample_info",
",",
"config",
")",
":",
"names",
"=",
"[",
"config",
".",
"get",
"(",
"x",
",",
"\"\"",
")",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"[",
"\"lab_association\"",
",",
"\"researcher\"",
"]"... | Retrieve upload library from nglims specified user libraries. | [
"Retrieve",
"upload",
"library",
"from",
"nglims",
"specified",
"user",
"libraries",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/galaxy.py#L163-L188 | train | 218,752 |
bcbio/bcbio-nextgen | bcbio/rnaseq/ericscript.py | prepare_input_data | def prepare_input_data(config):
""" In case of disambiguation, we want to run fusion calling on
the disambiguated reads, which are in the work_bam file.
As EricScript accepts 2 fastq files as input, we need to convert
the .bam to 2 .fq files.
"""
if not dd.get_disambiguate(config):
return dd.get_input_sequence_files(config)
work_bam = dd.get_work_bam(config)
logger.info("Converting disambiguated reads to fastq...")
fq_files = convert_bam_to_fastq(
work_bam, dd.get_work_dir(config), None, None, config
)
return fq_files | python | def prepare_input_data(config):
""" In case of disambiguation, we want to run fusion calling on
the disambiguated reads, which are in the work_bam file.
As EricScript accepts 2 fastq files as input, we need to convert
the .bam to 2 .fq files.
"""
if not dd.get_disambiguate(config):
return dd.get_input_sequence_files(config)
work_bam = dd.get_work_bam(config)
logger.info("Converting disambiguated reads to fastq...")
fq_files = convert_bam_to_fastq(
work_bam, dd.get_work_dir(config), None, None, config
)
return fq_files | [
"def",
"prepare_input_data",
"(",
"config",
")",
":",
"if",
"not",
"dd",
".",
"get_disambiguate",
"(",
"config",
")",
":",
"return",
"dd",
".",
"get_input_sequence_files",
"(",
"config",
")",
"work_bam",
"=",
"dd",
".",
"get_work_bam",
"(",
"config",
")",
... | In case of disambiguation, we want to run fusion calling on
the disambiguated reads, which are in the work_bam file.
As EricScript accepts 2 fastq files as input, we need to convert
the .bam to 2 .fq files. | [
"In",
"case",
"of",
"disambiguation",
"we",
"want",
"to",
"run",
"fusion",
"calling",
"on",
"the",
"disambiguated",
"reads",
"which",
"are",
"in",
"the",
"work_bam",
"file",
".",
"As",
"EricScript",
"accepts",
"2",
"fastq",
"files",
"as",
"input",
"we",
"n... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/ericscript.py#L32-L47 | train | 218,753 |
bcbio/bcbio-nextgen | bcbio/rnaseq/ericscript.py | EricScriptConfig.get_run_command | def get_run_command(self, tx_output_dir, input_files):
"""Constructs a command to run EricScript via do.run function.
:param tx_output_dir: A location where all EricScript output will be
written during execution.
:param input_files: an iterable with paths to 2 fastq files
with input data.
:return: list
"""
logger.debug("Input data: %s" % ', '.join(input_files))
cmd = [
self.EXECUTABLE,
'-db', self._db_location,
'-name', self._sample_name,
'-o', tx_output_dir,
] + list(input_files)
return "export PATH=%s:%s:\"$PATH\"; %s;" % (self._get_samtools0_path(), self._get_ericscript_path(), " ".join(cmd)) | python | def get_run_command(self, tx_output_dir, input_files):
"""Constructs a command to run EricScript via do.run function.
:param tx_output_dir: A location where all EricScript output will be
written during execution.
:param input_files: an iterable with paths to 2 fastq files
with input data.
:return: list
"""
logger.debug("Input data: %s" % ', '.join(input_files))
cmd = [
self.EXECUTABLE,
'-db', self._db_location,
'-name', self._sample_name,
'-o', tx_output_dir,
] + list(input_files)
return "export PATH=%s:%s:\"$PATH\"; %s;" % (self._get_samtools0_path(), self._get_ericscript_path(), " ".join(cmd)) | [
"def",
"get_run_command",
"(",
"self",
",",
"tx_output_dir",
",",
"input_files",
")",
":",
"logger",
".",
"debug",
"(",
"\"Input data: %s\"",
"%",
"', '",
".",
"join",
"(",
"input_files",
")",
")",
"cmd",
"=",
"[",
"self",
".",
"EXECUTABLE",
",",
"'-db'",
... | Constructs a command to run EricScript via do.run function.
:param tx_output_dir: A location where all EricScript output will be
written during execution.
:param input_files: an iterable with paths to 2 fastq files
with input data.
:return: list | [
"Constructs",
"a",
"command",
"to",
"run",
"EricScript",
"via",
"do",
".",
"run",
"function",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/ericscript.py#L107-L123 | train | 218,754 |
bcbio/bcbio-nextgen | bcbio/rnaseq/ericscript.py | EricScriptConfig._get_ericscript_path | def _get_ericscript_path(self):
"""Retrieve PATH to the isolated eriscript anaconda environment.
"""
es = utils.which(os.path.join(utils.get_bcbio_bin(), self.EXECUTABLE))
return os.path.dirname(os.path.realpath(es)) | python | def _get_ericscript_path(self):
"""Retrieve PATH to the isolated eriscript anaconda environment.
"""
es = utils.which(os.path.join(utils.get_bcbio_bin(), self.EXECUTABLE))
return os.path.dirname(os.path.realpath(es)) | [
"def",
"_get_ericscript_path",
"(",
"self",
")",
":",
"es",
"=",
"utils",
".",
"which",
"(",
"os",
".",
"path",
".",
"join",
"(",
"utils",
".",
"get_bcbio_bin",
"(",
")",
",",
"self",
".",
"EXECUTABLE",
")",
")",
"return",
"os",
".",
"path",
".",
"... | Retrieve PATH to the isolated eriscript anaconda environment. | [
"Retrieve",
"PATH",
"to",
"the",
"isolated",
"eriscript",
"anaconda",
"environment",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/ericscript.py#L125-L129 | train | 218,755 |
bcbio/bcbio-nextgen | bcbio/rnaseq/ericscript.py | EricScriptConfig._get_samtools0_path | def _get_samtools0_path(self):
"""Retrieve PATH to the samtools version specific for eriscript.
"""
samtools_path = os.path.realpath(os.path.join(self._get_ericscript_path(),"..", "..", "bin"))
return samtools_path | python | def _get_samtools0_path(self):
"""Retrieve PATH to the samtools version specific for eriscript.
"""
samtools_path = os.path.realpath(os.path.join(self._get_ericscript_path(),"..", "..", "bin"))
return samtools_path | [
"def",
"_get_samtools0_path",
"(",
"self",
")",
":",
"samtools_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_get_ericscript_path",
"(",
")",
",",
"\"..\"",
",",
"\"..\"",
",",
"\"bin\"",
")",
"... | Retrieve PATH to the samtools version specific for eriscript. | [
"Retrieve",
"PATH",
"to",
"the",
"samtools",
"version",
"specific",
"for",
"eriscript",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/ericscript.py#L130-L134 | train | 218,756 |
bcbio/bcbio-nextgen | bcbio/rnaseq/ericscript.py | EricScriptConfig.output_dir | def output_dir(self):
"""Absolute path to permanent location in working directory
where EricScript output will be stored.
"""
if self._output_dir is None:
self._output_dir = self._get_output_dir()
return self._output_dir | python | def output_dir(self):
"""Absolute path to permanent location in working directory
where EricScript output will be stored.
"""
if self._output_dir is None:
self._output_dir = self._get_output_dir()
return self._output_dir | [
"def",
"output_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"_output_dir",
"is",
"None",
":",
"self",
".",
"_output_dir",
"=",
"self",
".",
"_get_output_dir",
"(",
")",
"return",
"self",
".",
"_output_dir"
] | Absolute path to permanent location in working directory
where EricScript output will be stored. | [
"Absolute",
"path",
"to",
"permanent",
"location",
"in",
"working",
"directory",
"where",
"EricScript",
"output",
"will",
"be",
"stored",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/ericscript.py#L137-L143 | train | 218,757 |
bcbio/bcbio-nextgen | bcbio/rnaseq/ericscript.py | EricScriptConfig.reference_index | def reference_index(self):
"""Absolute path to the BWA index for EricScript reference data."""
if self._db_location:
ref_indices = glob.glob(os.path.join(self._db_location, "*", self._REF_INDEX))
if ref_indices:
return ref_indices[0] | python | def reference_index(self):
"""Absolute path to the BWA index for EricScript reference data."""
if self._db_location:
ref_indices = glob.glob(os.path.join(self._db_location, "*", self._REF_INDEX))
if ref_indices:
return ref_indices[0] | [
"def",
"reference_index",
"(",
"self",
")",
":",
"if",
"self",
".",
"_db_location",
":",
"ref_indices",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_db_location",
",",
"\"*\"",
",",
"self",
".",
"_REF_INDEX",
")",
... | Absolute path to the BWA index for EricScript reference data. | [
"Absolute",
"path",
"to",
"the",
"BWA",
"index",
"for",
"EricScript",
"reference",
"data",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/ericscript.py#L158-L163 | train | 218,758 |
bcbio/bcbio-nextgen | bcbio/rnaseq/ericscript.py | EricScriptConfig.reference_fasta | def reference_fasta(self):
"""Absolute path to the fasta file with EricScript reference data."""
if self._db_location:
ref_files = glob.glob(os.path.join(self._db_location, "*", self._REF_FASTA))
if ref_files:
return ref_files[0] | python | def reference_fasta(self):
"""Absolute path to the fasta file with EricScript reference data."""
if self._db_location:
ref_files = glob.glob(os.path.join(self._db_location, "*", self._REF_FASTA))
if ref_files:
return ref_files[0] | [
"def",
"reference_fasta",
"(",
"self",
")",
":",
"if",
"self",
".",
"_db_location",
":",
"ref_files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_db_location",
",",
"\"*\"",
",",
"self",
".",
"_REF_FASTA",
")",
... | Absolute path to the fasta file with EricScript reference data. | [
"Absolute",
"path",
"to",
"the",
"fasta",
"file",
"with",
"EricScript",
"reference",
"data",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/ericscript.py#L166-L171 | train | 218,759 |
bcbio/bcbio-nextgen | bcbio/qc/contamination.py | _get_input_args | def _get_input_args(bam_file, data, out_base, background):
"""Retrieve input args, depending on genome build.
VerifyBamID2 only handles GRCh37 (1, 2, 3) not hg19, so need to generate
a pileup for hg19 and fix chromosome naming.
"""
if dd.get_genome_build(data) in ["hg19"]:
return ["--PileupFile", _create_pileup(bam_file, data, out_base, background)]
else:
return ["--BamFile", bam_file] | python | def _get_input_args(bam_file, data, out_base, background):
"""Retrieve input args, depending on genome build.
VerifyBamID2 only handles GRCh37 (1, 2, 3) not hg19, so need to generate
a pileup for hg19 and fix chromosome naming.
"""
if dd.get_genome_build(data) in ["hg19"]:
return ["--PileupFile", _create_pileup(bam_file, data, out_base, background)]
else:
return ["--BamFile", bam_file] | [
"def",
"_get_input_args",
"(",
"bam_file",
",",
"data",
",",
"out_base",
",",
"background",
")",
":",
"if",
"dd",
".",
"get_genome_build",
"(",
"data",
")",
"in",
"[",
"\"hg19\"",
"]",
":",
"return",
"[",
"\"--PileupFile\"",
",",
"_create_pileup",
"(",
"ba... | Retrieve input args, depending on genome build.
VerifyBamID2 only handles GRCh37 (1, 2, 3) not hg19, so need to generate
a pileup for hg19 and fix chromosome naming. | [
"Retrieve",
"input",
"args",
"depending",
"on",
"genome",
"build",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/contamination.py#L78-L87 | train | 218,760 |
bcbio/bcbio-nextgen | bcbio/qc/contamination.py | _create_pileup | def _create_pileup(bam_file, data, out_base, background):
"""Create pileup calls in the regions of interest for hg19 -> GRCh37 chromosome mapping.
"""
out_file = "%s-mpileup.txt" % out_base
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
background_bed = os.path.normpath(os.path.join(
os.path.dirname(os.path.realpath(utils.which("verifybamid2"))),
"resource", "%s.%s.%s.vcf.gz.dat.bed" % (background["dataset"],
background["nvars"], background["build"])))
local_bed = os.path.join(os.path.dirname(out_base),
"%s.%s-hg19.bed" % (background["dataset"], background["nvars"]))
if not utils.file_exists(local_bed):
with file_transaction(data, local_bed) as tx_local_bed:
with open(background_bed) as in_handle:
with open(tx_local_bed, "w") as out_handle:
for line in in_handle:
out_handle.write("chr%s" % line)
mpileup_cl = samtools.prep_mpileup([bam_file], dd.get_ref_file(data), data["config"], want_bcf=False,
target_regions=local_bed)
cl = ("{mpileup_cl} | sed 's/^chr//' > {tx_out_file}")
do.run(cl.format(**locals()), "Create pileup from BAM input")
return out_file | python | def _create_pileup(bam_file, data, out_base, background):
"""Create pileup calls in the regions of interest for hg19 -> GRCh37 chromosome mapping.
"""
out_file = "%s-mpileup.txt" % out_base
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
background_bed = os.path.normpath(os.path.join(
os.path.dirname(os.path.realpath(utils.which("verifybamid2"))),
"resource", "%s.%s.%s.vcf.gz.dat.bed" % (background["dataset"],
background["nvars"], background["build"])))
local_bed = os.path.join(os.path.dirname(out_base),
"%s.%s-hg19.bed" % (background["dataset"], background["nvars"]))
if not utils.file_exists(local_bed):
with file_transaction(data, local_bed) as tx_local_bed:
with open(background_bed) as in_handle:
with open(tx_local_bed, "w") as out_handle:
for line in in_handle:
out_handle.write("chr%s" % line)
mpileup_cl = samtools.prep_mpileup([bam_file], dd.get_ref_file(data), data["config"], want_bcf=False,
target_regions=local_bed)
cl = ("{mpileup_cl} | sed 's/^chr//' > {tx_out_file}")
do.run(cl.format(**locals()), "Create pileup from BAM input")
return out_file | [
"def",
"_create_pileup",
"(",
"bam_file",
",",
"data",
",",
"out_base",
",",
"background",
")",
":",
"out_file",
"=",
"\"%s-mpileup.txt\"",
"%",
"out_base",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
... | Create pileup calls in the regions of interest for hg19 -> GRCh37 chromosome mapping. | [
"Create",
"pileup",
"calls",
"in",
"the",
"regions",
"of",
"interest",
"for",
"hg19",
"-",
">",
"GRCh37",
"chromosome",
"mapping",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/contamination.py#L89-L111 | train | 218,761 |
bcbio/bcbio-nextgen | bcbio/structural/convert.py | _cnvbed_to_bed | def _cnvbed_to_bed(in_file, caller, out_file):
"""Convert cn_mops CNV based bed files into flattened BED
"""
with open(out_file, "w") as out_handle:
for feat in pybedtools.BedTool(in_file):
out_handle.write("\t".join([feat.chrom, str(feat.start), str(feat.end),
"cnv%s_%s" % (feat.score, caller)])
+ "\n") | python | def _cnvbed_to_bed(in_file, caller, out_file):
"""Convert cn_mops CNV based bed files into flattened BED
"""
with open(out_file, "w") as out_handle:
for feat in pybedtools.BedTool(in_file):
out_handle.write("\t".join([feat.chrom, str(feat.start), str(feat.end),
"cnv%s_%s" % (feat.score, caller)])
+ "\n") | [
"def",
"_cnvbed_to_bed",
"(",
"in_file",
",",
"caller",
",",
"out_file",
")",
":",
"with",
"open",
"(",
"out_file",
",",
"\"w\"",
")",
"as",
"out_handle",
":",
"for",
"feat",
"in",
"pybedtools",
".",
"BedTool",
"(",
"in_file",
")",
":",
"out_handle",
"."... | Convert cn_mops CNV based bed files into flattened BED | [
"Convert",
"cn_mops",
"CNV",
"based",
"bed",
"files",
"into",
"flattened",
"BED"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/convert.py#L44-L51 | train | 218,762 |
bcbio/bcbio-nextgen | bcbio/structural/convert.py | to_bed | def to_bed(call, sample, work_dir, calls, data):
"""Create a simplified BED file from caller specific input.
"""
out_file = os.path.join(work_dir, "%s-%s-flat.bed" % (sample, call["variantcaller"]))
if call.get("vrn_file") and not utils.file_uptodate(out_file, call["vrn_file"]):
with file_transaction(data, out_file) as tx_out_file:
convert_fn = CALLER_TO_BED.get(call["variantcaller"])
if convert_fn:
vrn_file = call["vrn_file"]
if call["variantcaller"] in SUBSET_BY_SUPPORT:
ecalls = [x for x in calls if x["variantcaller"] in SUBSET_BY_SUPPORT[call["variantcaller"]]]
if len(ecalls) > 0:
vrn_file = _subset_by_support(call["vrn_file"], ecalls, data)
convert_fn(vrn_file, call["variantcaller"], tx_out_file)
if utils.file_exists(out_file):
return out_file | python | def to_bed(call, sample, work_dir, calls, data):
"""Create a simplified BED file from caller specific input.
"""
out_file = os.path.join(work_dir, "%s-%s-flat.bed" % (sample, call["variantcaller"]))
if call.get("vrn_file") and not utils.file_uptodate(out_file, call["vrn_file"]):
with file_transaction(data, out_file) as tx_out_file:
convert_fn = CALLER_TO_BED.get(call["variantcaller"])
if convert_fn:
vrn_file = call["vrn_file"]
if call["variantcaller"] in SUBSET_BY_SUPPORT:
ecalls = [x for x in calls if x["variantcaller"] in SUBSET_BY_SUPPORT[call["variantcaller"]]]
if len(ecalls) > 0:
vrn_file = _subset_by_support(call["vrn_file"], ecalls, data)
convert_fn(vrn_file, call["variantcaller"], tx_out_file)
if utils.file_exists(out_file):
return out_file | [
"def",
"to_bed",
"(",
"call",
",",
"sample",
",",
"work_dir",
",",
"calls",
",",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-%s-flat.bed\"",
"%",
"(",
"sample",
",",
"call",
"[",
"\"variantcaller\"",
"... | Create a simplified BED file from caller specific input. | [
"Create",
"a",
"simplified",
"BED",
"file",
"from",
"caller",
"specific",
"input",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/convert.py#L65-L80 | train | 218,763 |
bcbio/bcbio-nextgen | bcbio/structural/convert.py | _subset_by_support | def _subset_by_support(orig_vcf, cmp_calls, data):
"""Subset orig_vcf to calls also present in any of the comparison callers.
"""
cmp_vcfs = [x["vrn_file"] for x in cmp_calls]
out_file = "%s-inensemble.vcf.gz" % utils.splitext_plus(orig_vcf)[0]
if not utils.file_uptodate(out_file, orig_vcf):
with file_transaction(data, out_file) as tx_out_file:
cmd = "bedtools intersect -header -wa -f 0.5 -r -a {orig_vcf} -b "
for cmp_vcf in cmp_vcfs:
cmd += "<(bcftools view -f 'PASS,.' %s) " % cmp_vcf
cmd += "| bgzip -c > {tx_out_file}"
do.run(cmd.format(**locals()), "Subset calls by those present in Ensemble output")
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def _subset_by_support(orig_vcf, cmp_calls, data):
"""Subset orig_vcf to calls also present in any of the comparison callers.
"""
cmp_vcfs = [x["vrn_file"] for x in cmp_calls]
out_file = "%s-inensemble.vcf.gz" % utils.splitext_plus(orig_vcf)[0]
if not utils.file_uptodate(out_file, orig_vcf):
with file_transaction(data, out_file) as tx_out_file:
cmd = "bedtools intersect -header -wa -f 0.5 -r -a {orig_vcf} -b "
for cmp_vcf in cmp_vcfs:
cmd += "<(bcftools view -f 'PASS,.' %s) " % cmp_vcf
cmd += "| bgzip -c > {tx_out_file}"
do.run(cmd.format(**locals()), "Subset calls by those present in Ensemble output")
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"_subset_by_support",
"(",
"orig_vcf",
",",
"cmp_calls",
",",
"data",
")",
":",
"cmp_vcfs",
"=",
"[",
"x",
"[",
"\"vrn_file\"",
"]",
"for",
"x",
"in",
"cmp_calls",
"]",
"out_file",
"=",
"\"%s-inensemble.vcf.gz\"",
"%",
"utils",
".",
"splitext_plus",
"... | Subset orig_vcf to calls also present in any of the comparison callers. | [
"Subset",
"orig_vcf",
"to",
"calls",
"also",
"present",
"in",
"any",
"of",
"the",
"comparison",
"callers",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/convert.py#L82-L94 | train | 218,764 |
bcbio/bcbio-nextgen | bcbio/qc/coverage.py | run | def run(bam_file, data, out_dir):
"""Run coverage QC analysis
"""
out = dict()
out_dir = utils.safe_makedir(out_dir)
if dd.get_coverage(data) and dd.get_coverage(data) not in ["None"]:
merged_bed_file = bedutils.clean_file(dd.get_coverage_merged(data), data, prefix="cov-", simple=True)
target_name = "coverage"
elif dd.get_coverage_interval(data) != "genome":
merged_bed_file = dd.get_variant_regions_merged(data) or dd.get_sample_callable(data)
target_name = "variant_regions"
else:
merged_bed_file = None
target_name = "genome"
avg_depth = cov.get_average_coverage(target_name, merged_bed_file, data)
if target_name == "coverage":
out_files = cov.coverage_region_detailed_stats(target_name, merged_bed_file, data, out_dir)
else:
out_files = []
out['Avg_coverage'] = avg_depth
samtools_stats_dir = os.path.join(out_dir, os.path.pardir, 'samtools')
from bcbio.qc import samtools
samtools_stats = samtools.run(bam_file, data, samtools_stats_dir)["metrics"]
out["Total_reads"] = total_reads = int(samtools_stats["Total_reads"])
out["Mapped_reads"] = mapped = int(samtools_stats["Mapped_reads"])
out["Mapped_paired_reads"] = int(samtools_stats["Mapped_paired_reads"])
out['Duplicates'] = dups = int(samtools_stats["Duplicates"])
if total_reads:
out["Mapped_reads_pct"] = 100.0 * mapped / total_reads
if mapped:
out['Duplicates_pct'] = 100.0 * dups / mapped
if dd.get_coverage_interval(data) == "genome":
mapped_unique = mapped - dups
else:
mapped_unique = readstats.number_of_mapped_reads(data, bam_file, keep_dups=False)
out['Mapped_unique_reads'] = mapped_unique
if merged_bed_file:
ontarget = readstats.number_of_mapped_reads(
data, bam_file, keep_dups=False, bed_file=merged_bed_file, target_name=target_name)
out["Ontarget_unique_reads"] = ontarget
if mapped_unique:
out["Ontarget_pct"] = 100.0 * ontarget / mapped_unique
out['Offtarget_pct'] = 100.0 * (mapped_unique - ontarget) / mapped_unique
if dd.get_coverage_interval(data) != "genome":
# Skip padded calculation for WGS even if the "coverage" file is specified
# the padded statistic makes only sense for exomes and panels
padded_bed_file = bedutils.get_padded_bed_file(out_dir, merged_bed_file, 200, data)
ontarget_padded = readstats.number_of_mapped_reads(
data, bam_file, keep_dups=False, bed_file=padded_bed_file, target_name=target_name + "_padded")
out["Ontarget_padded_pct"] = 100.0 * ontarget_padded / mapped_unique
if total_reads:
out['Usable_pct'] = 100.0 * ontarget / total_reads
indexcov_files = _goleft_indexcov(bam_file, data, out_dir)
out_files += [x for x in indexcov_files if x and utils.file_exists(x)]
out = {"metrics": out}
if len(out_files) > 0:
out["base"] = out_files[0]
out["secondary"] = out_files[1:]
return out | python | def run(bam_file, data, out_dir):
"""Run coverage QC analysis
"""
out = dict()
out_dir = utils.safe_makedir(out_dir)
if dd.get_coverage(data) and dd.get_coverage(data) not in ["None"]:
merged_bed_file = bedutils.clean_file(dd.get_coverage_merged(data), data, prefix="cov-", simple=True)
target_name = "coverage"
elif dd.get_coverage_interval(data) != "genome":
merged_bed_file = dd.get_variant_regions_merged(data) or dd.get_sample_callable(data)
target_name = "variant_regions"
else:
merged_bed_file = None
target_name = "genome"
avg_depth = cov.get_average_coverage(target_name, merged_bed_file, data)
if target_name == "coverage":
out_files = cov.coverage_region_detailed_stats(target_name, merged_bed_file, data, out_dir)
else:
out_files = []
out['Avg_coverage'] = avg_depth
samtools_stats_dir = os.path.join(out_dir, os.path.pardir, 'samtools')
from bcbio.qc import samtools
samtools_stats = samtools.run(bam_file, data, samtools_stats_dir)["metrics"]
out["Total_reads"] = total_reads = int(samtools_stats["Total_reads"])
out["Mapped_reads"] = mapped = int(samtools_stats["Mapped_reads"])
out["Mapped_paired_reads"] = int(samtools_stats["Mapped_paired_reads"])
out['Duplicates'] = dups = int(samtools_stats["Duplicates"])
if total_reads:
out["Mapped_reads_pct"] = 100.0 * mapped / total_reads
if mapped:
out['Duplicates_pct'] = 100.0 * dups / mapped
if dd.get_coverage_interval(data) == "genome":
mapped_unique = mapped - dups
else:
mapped_unique = readstats.number_of_mapped_reads(data, bam_file, keep_dups=False)
out['Mapped_unique_reads'] = mapped_unique
if merged_bed_file:
ontarget = readstats.number_of_mapped_reads(
data, bam_file, keep_dups=False, bed_file=merged_bed_file, target_name=target_name)
out["Ontarget_unique_reads"] = ontarget
if mapped_unique:
out["Ontarget_pct"] = 100.0 * ontarget / mapped_unique
out['Offtarget_pct'] = 100.0 * (mapped_unique - ontarget) / mapped_unique
if dd.get_coverage_interval(data) != "genome":
# Skip padded calculation for WGS even if the "coverage" file is specified
# the padded statistic makes only sense for exomes and panels
padded_bed_file = bedutils.get_padded_bed_file(out_dir, merged_bed_file, 200, data)
ontarget_padded = readstats.number_of_mapped_reads(
data, bam_file, keep_dups=False, bed_file=padded_bed_file, target_name=target_name + "_padded")
out["Ontarget_padded_pct"] = 100.0 * ontarget_padded / mapped_unique
if total_reads:
out['Usable_pct'] = 100.0 * ontarget / total_reads
indexcov_files = _goleft_indexcov(bam_file, data, out_dir)
out_files += [x for x in indexcov_files if x and utils.file_exists(x)]
out = {"metrics": out}
if len(out_files) > 0:
out["base"] = out_files[0]
out["secondary"] = out_files[1:]
return out | [
"def",
"run",
"(",
"bam_file",
",",
"data",
",",
"out_dir",
")",
":",
"out",
"=",
"dict",
"(",
")",
"out_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"out_dir",
")",
"if",
"dd",
".",
"get_coverage",
"(",
"data",
")",
"and",
"dd",
".",
"get_coverage"... | Run coverage QC analysis | [
"Run",
"coverage",
"QC",
"analysis"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/coverage.py#L15-L82 | train | 218,765 |
bcbio/bcbio-nextgen | bcbio/qc/coverage.py | _goleft_indexcov | def _goleft_indexcov(bam_file, data, out_dir):
"""Use goleft indexcov to estimate coverage distributions using BAM index.
Only used for whole genome runs as captures typically don't have enough data
to be useful for index-only summaries.
"""
if not dd.get_coverage_interval(data) == "genome":
return []
out_dir = utils.safe_makedir(os.path.join(out_dir, "indexcov"))
out_files = [os.path.join(out_dir, "%s-indexcov.%s" % (dd.get_sample_name(data), ext))
for ext in ["roc", "ped", "bed.gz"]]
if not utils.file_uptodate(out_files[-1], bam_file):
with transaction.tx_tmpdir(data) as tmp_dir:
tmp_dir = utils.safe_makedir(os.path.join(tmp_dir, dd.get_sample_name(data)))
gender_chroms = [x.name for x in ref.file_contigs(dd.get_ref_file(data)) if chromhacks.is_sex(x.name)]
gender_args = "--sex %s" % (",".join(gender_chroms)) if gender_chroms else ""
cmd = "goleft indexcov --directory {tmp_dir} {gender_args} -- {bam_file}"
try:
do.run(cmd.format(**locals()), "QC: goleft indexcov")
except subprocess.CalledProcessError as msg:
if not ("indexcov: no usable" in str(msg) or
("indexcov: expected" in str(msg) and "sex chromosomes, found:" in str(msg))):
raise
for out_file in out_files:
orig_file = os.path.join(tmp_dir, os.path.basename(out_file))
if utils.file_exists(orig_file):
utils.copy_plus(orig_file, out_file)
# MultiQC needs non-gzipped/BED inputs so unpack the file
out_bed = out_files[-1].replace(".bed.gz", ".tsv")
if utils.file_exists(out_files[-1]) and not utils.file_exists(out_bed):
with transaction.file_transaction(data, out_bed) as tx_out_bed:
cmd = "gunzip -c %s > %s" % (out_files[-1], tx_out_bed)
do.run(cmd, "Unpack indexcov BED file")
out_files[-1] = out_bed
return [x for x in out_files if utils.file_exists(x)] | python | def _goleft_indexcov(bam_file, data, out_dir):
"""Use goleft indexcov to estimate coverage distributions using BAM index.
Only used for whole genome runs as captures typically don't have enough data
to be useful for index-only summaries.
"""
if not dd.get_coverage_interval(data) == "genome":
return []
out_dir = utils.safe_makedir(os.path.join(out_dir, "indexcov"))
out_files = [os.path.join(out_dir, "%s-indexcov.%s" % (dd.get_sample_name(data), ext))
for ext in ["roc", "ped", "bed.gz"]]
if not utils.file_uptodate(out_files[-1], bam_file):
with transaction.tx_tmpdir(data) as tmp_dir:
tmp_dir = utils.safe_makedir(os.path.join(tmp_dir, dd.get_sample_name(data)))
gender_chroms = [x.name for x in ref.file_contigs(dd.get_ref_file(data)) if chromhacks.is_sex(x.name)]
gender_args = "--sex %s" % (",".join(gender_chroms)) if gender_chroms else ""
cmd = "goleft indexcov --directory {tmp_dir} {gender_args} -- {bam_file}"
try:
do.run(cmd.format(**locals()), "QC: goleft indexcov")
except subprocess.CalledProcessError as msg:
if not ("indexcov: no usable" in str(msg) or
("indexcov: expected" in str(msg) and "sex chromosomes, found:" in str(msg))):
raise
for out_file in out_files:
orig_file = os.path.join(tmp_dir, os.path.basename(out_file))
if utils.file_exists(orig_file):
utils.copy_plus(orig_file, out_file)
# MultiQC needs non-gzipped/BED inputs so unpack the file
out_bed = out_files[-1].replace(".bed.gz", ".tsv")
if utils.file_exists(out_files[-1]) and not utils.file_exists(out_bed):
with transaction.file_transaction(data, out_bed) as tx_out_bed:
cmd = "gunzip -c %s > %s" % (out_files[-1], tx_out_bed)
do.run(cmd, "Unpack indexcov BED file")
out_files[-1] = out_bed
return [x for x in out_files if utils.file_exists(x)] | [
"def",
"_goleft_indexcov",
"(",
"bam_file",
",",
"data",
",",
"out_dir",
")",
":",
"if",
"not",
"dd",
".",
"get_coverage_interval",
"(",
"data",
")",
"==",
"\"genome\"",
":",
"return",
"[",
"]",
"out_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".... | Use goleft indexcov to estimate coverage distributions using BAM index.
Only used for whole genome runs as captures typically don't have enough data
to be useful for index-only summaries. | [
"Use",
"goleft",
"indexcov",
"to",
"estimate",
"coverage",
"distributions",
"using",
"BAM",
"index",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/coverage.py#L84-L118 | train | 218,766 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | picard_sort | def picard_sort(picard, align_bam, sort_order="coordinate",
out_file=None, compression_level=None, pipe=False):
"""Sort a BAM file by coordinates.
"""
base, ext = os.path.splitext(align_bam)
if out_file is None:
out_file = "%s-sort%s" % (base, ext)
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("INPUT", align_bam),
("OUTPUT", out_file if pipe else tx_out_file),
("TMP_DIR", tmp_dir),
("SORT_ORDER", sort_order)]
if compression_level:
opts.append(("COMPRESSION_LEVEL", compression_level))
picard.run("SortSam", opts, pipe=pipe)
return out_file | python | def picard_sort(picard, align_bam, sort_order="coordinate",
out_file=None, compression_level=None, pipe=False):
"""Sort a BAM file by coordinates.
"""
base, ext = os.path.splitext(align_bam)
if out_file is None:
out_file = "%s-sort%s" % (base, ext)
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("INPUT", align_bam),
("OUTPUT", out_file if pipe else tx_out_file),
("TMP_DIR", tmp_dir),
("SORT_ORDER", sort_order)]
if compression_level:
opts.append(("COMPRESSION_LEVEL", compression_level))
picard.run("SortSam", opts, pipe=pipe)
return out_file | [
"def",
"picard_sort",
"(",
"picard",
",",
"align_bam",
",",
"sort_order",
"=",
"\"coordinate\"",
",",
"out_file",
"=",
"None",
",",
"compression_level",
"=",
"None",
",",
"pipe",
"=",
"False",
")",
":",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
... | Sort a BAM file by coordinates. | [
"Sort",
"a",
"BAM",
"file",
"by",
"coordinates",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L46-L63 | train | 218,767 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | picard_merge | def picard_merge(picard, in_files, out_file=None,
merge_seq_dicts=False):
"""Merge multiple BAM files together with Picard.
"""
if out_file is None:
out_file = "%smerge.bam" % os.path.commonprefix(in_files)
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("OUTPUT", tx_out_file),
("SORT_ORDER", "coordinate"),
("MERGE_SEQUENCE_DICTIONARIES",
"true" if merge_seq_dicts else "false"),
("USE_THREADING", "true"),
("TMP_DIR", tmp_dir)]
for in_file in in_files:
opts.append(("INPUT", in_file))
picard.run("MergeSamFiles", opts)
return out_file | python | def picard_merge(picard, in_files, out_file=None,
merge_seq_dicts=False):
"""Merge multiple BAM files together with Picard.
"""
if out_file is None:
out_file = "%smerge.bam" % os.path.commonprefix(in_files)
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("OUTPUT", tx_out_file),
("SORT_ORDER", "coordinate"),
("MERGE_SEQUENCE_DICTIONARIES",
"true" if merge_seq_dicts else "false"),
("USE_THREADING", "true"),
("TMP_DIR", tmp_dir)]
for in_file in in_files:
opts.append(("INPUT", in_file))
picard.run("MergeSamFiles", opts)
return out_file | [
"def",
"picard_merge",
"(",
"picard",
",",
"in_files",
",",
"out_file",
"=",
"None",
",",
"merge_seq_dicts",
"=",
"False",
")",
":",
"if",
"out_file",
"is",
"None",
":",
"out_file",
"=",
"\"%smerge.bam\"",
"%",
"os",
".",
"path",
".",
"commonprefix",
"(",
... | Merge multiple BAM files together with Picard. | [
"Merge",
"multiple",
"BAM",
"files",
"together",
"with",
"Picard",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L65-L83 | train | 218,768 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | picard_reorder | def picard_reorder(picard, in_bam, ref_file, out_file):
"""Reorder BAM file to match reference file ordering.
"""
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("INPUT", in_bam),
("OUTPUT", tx_out_file),
("REFERENCE", ref_file),
("ALLOW_INCOMPLETE_DICT_CONCORDANCE", "true"),
("TMP_DIR", tmp_dir)]
picard.run("ReorderSam", opts)
return out_file | python | def picard_reorder(picard, in_bam, ref_file, out_file):
"""Reorder BAM file to match reference file ordering.
"""
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("INPUT", in_bam),
("OUTPUT", tx_out_file),
("REFERENCE", ref_file),
("ALLOW_INCOMPLETE_DICT_CONCORDANCE", "true"),
("TMP_DIR", tmp_dir)]
picard.run("ReorderSam", opts)
return out_file | [
"def",
"picard_reorder",
"(",
"picard",
",",
"in_bam",
",",
"ref_file",
",",
"out_file",
")",
":",
"if",
"not",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"tx_tmpdir",
"(",
"picard",
".",
"_config",
")",
"as",
"tmp_dir",
":",
"with",
"file_transacti... | Reorder BAM file to match reference file ordering. | [
"Reorder",
"BAM",
"file",
"to",
"match",
"reference",
"file",
"ordering",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L95-L107 | train | 218,769 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | picard_fix_rgs | def picard_fix_rgs(picard, in_bam, names):
"""Add read group information to BAM files and coordinate sort.
"""
out_file = "%s-fixrgs.bam" % os.path.splitext(in_bam)[0]
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("INPUT", in_bam),
("OUTPUT", tx_out_file),
("SORT_ORDER", "coordinate"),
("RGID", names["rg"]),
("RGLB", names.get("lb", "unknown")),
("RGPL", names["pl"]),
("RGPU", names["pu"]),
("RGSM", names["sample"]),
("TMP_DIR", tmp_dir)]
picard.run("AddOrReplaceReadGroups", opts)
return out_file | python | def picard_fix_rgs(picard, in_bam, names):
"""Add read group information to BAM files and coordinate sort.
"""
out_file = "%s-fixrgs.bam" % os.path.splitext(in_bam)[0]
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("INPUT", in_bam),
("OUTPUT", tx_out_file),
("SORT_ORDER", "coordinate"),
("RGID", names["rg"]),
("RGLB", names.get("lb", "unknown")),
("RGPL", names["pl"]),
("RGPU", names["pu"]),
("RGSM", names["sample"]),
("TMP_DIR", tmp_dir)]
picard.run("AddOrReplaceReadGroups", opts)
return out_file | [
"def",
"picard_fix_rgs",
"(",
"picard",
",",
"in_bam",
",",
"names",
")",
":",
"out_file",
"=",
"\"%s-fixrgs.bam\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"in_bam",
")",
"[",
"0",
"]",
"if",
"not",
"file_exists",
"(",
"out_file",
")",
":",
"wit... | Add read group information to BAM files and coordinate sort. | [
"Add",
"read",
"group",
"information",
"to",
"BAM",
"files",
"and",
"coordinate",
"sort",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L109-L126 | train | 218,770 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | picard_index_ref | def picard_index_ref(picard, ref_file):
"""Provide a Picard style dict index file for a reference genome.
"""
dict_file = "%s.dict" % os.path.splitext(ref_file)[0]
if not file_exists(dict_file):
with file_transaction(picard._config, dict_file) as tx_dict_file:
opts = [("REFERENCE", ref_file),
("OUTPUT", tx_dict_file)]
picard.run("CreateSequenceDictionary", opts)
return dict_file | python | def picard_index_ref(picard, ref_file):
"""Provide a Picard style dict index file for a reference genome.
"""
dict_file = "%s.dict" % os.path.splitext(ref_file)[0]
if not file_exists(dict_file):
with file_transaction(picard._config, dict_file) as tx_dict_file:
opts = [("REFERENCE", ref_file),
("OUTPUT", tx_dict_file)]
picard.run("CreateSequenceDictionary", opts)
return dict_file | [
"def",
"picard_index_ref",
"(",
"picard",
",",
"ref_file",
")",
":",
"dict_file",
"=",
"\"%s.dict\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"ref_file",
")",
"[",
"0",
"]",
"if",
"not",
"file_exists",
"(",
"dict_file",
")",
":",
"with",
"file_tran... | Provide a Picard style dict index file for a reference genome. | [
"Provide",
"a",
"Picard",
"style",
"dict",
"index",
"file",
"for",
"a",
"reference",
"genome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L142-L151 | train | 218,771 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | picard_bam_to_fastq | def picard_bam_to_fastq(picard, in_bam, fastq_one, fastq_two=None):
"""Convert BAM file to fastq.
"""
if not file_exists(fastq_one):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, fastq_one) as tx_out1:
opts = [("INPUT", in_bam),
("FASTQ", tx_out1),
("TMP_DIR", tmp_dir)]
if fastq_two is not None:
opts += [("SECOND_END_FASTQ", fastq_two)]
picard.run("SamToFastq", opts)
return (fastq_one, fastq_two) | python | def picard_bam_to_fastq(picard, in_bam, fastq_one, fastq_two=None):
"""Convert BAM file to fastq.
"""
if not file_exists(fastq_one):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, fastq_one) as tx_out1:
opts = [("INPUT", in_bam),
("FASTQ", tx_out1),
("TMP_DIR", tmp_dir)]
if fastq_two is not None:
opts += [("SECOND_END_FASTQ", fastq_two)]
picard.run("SamToFastq", opts)
return (fastq_one, fastq_two) | [
"def",
"picard_bam_to_fastq",
"(",
"picard",
",",
"in_bam",
",",
"fastq_one",
",",
"fastq_two",
"=",
"None",
")",
":",
"if",
"not",
"file_exists",
"(",
"fastq_one",
")",
":",
"with",
"tx_tmpdir",
"(",
"picard",
".",
"_config",
")",
"as",
"tmp_dir",
":",
... | Convert BAM file to fastq. | [
"Convert",
"BAM",
"file",
"to",
"fastq",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L174-L186 | train | 218,772 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | picard_sam_to_bam | def picard_sam_to_bam(picard, align_sam, fastq_bam, ref_file,
is_paired=False):
"""Convert SAM to BAM, including unmapped reads from fastq BAM file.
"""
to_retain = ["XS", "XG", "XM", "XN", "XO", "YT"]
if align_sam.endswith(".sam"):
out_bam = "%s.bam" % os.path.splitext(align_sam)[0]
elif align_sam.endswith("-align.bam"):
out_bam = "%s.bam" % align_sam.replace("-align.bam", "")
else:
raise NotImplementedError("Input format not recognized")
if not file_exists(out_bam):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_bam) as tx_out_bam:
opts = [("UNMAPPED", fastq_bam),
("ALIGNED", align_sam),
("OUTPUT", tx_out_bam),
("REFERENCE_SEQUENCE", ref_file),
("TMP_DIR", tmp_dir),
("PAIRED_RUN", ("true" if is_paired else "false")),
]
opts += [("ATTRIBUTES_TO_RETAIN", x) for x in to_retain]
picard.run("MergeBamAlignment", opts)
return out_bam | python | def picard_sam_to_bam(picard, align_sam, fastq_bam, ref_file,
is_paired=False):
"""Convert SAM to BAM, including unmapped reads from fastq BAM file.
"""
to_retain = ["XS", "XG", "XM", "XN", "XO", "YT"]
if align_sam.endswith(".sam"):
out_bam = "%s.bam" % os.path.splitext(align_sam)[0]
elif align_sam.endswith("-align.bam"):
out_bam = "%s.bam" % align_sam.replace("-align.bam", "")
else:
raise NotImplementedError("Input format not recognized")
if not file_exists(out_bam):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_bam) as tx_out_bam:
opts = [("UNMAPPED", fastq_bam),
("ALIGNED", align_sam),
("OUTPUT", tx_out_bam),
("REFERENCE_SEQUENCE", ref_file),
("TMP_DIR", tmp_dir),
("PAIRED_RUN", ("true" if is_paired else "false")),
]
opts += [("ATTRIBUTES_TO_RETAIN", x) for x in to_retain]
picard.run("MergeBamAlignment", opts)
return out_bam | [
"def",
"picard_sam_to_bam",
"(",
"picard",
",",
"align_sam",
",",
"fastq_bam",
",",
"ref_file",
",",
"is_paired",
"=",
"False",
")",
":",
"to_retain",
"=",
"[",
"\"XS\"",
",",
"\"XG\"",
",",
"\"XM\"",
",",
"\"XN\"",
",",
"\"XO\"",
",",
"\"YT\"",
"]",
"if... | Convert SAM to BAM, including unmapped reads from fastq BAM file. | [
"Convert",
"SAM",
"to",
"BAM",
"including",
"unmapped",
"reads",
"from",
"fastq",
"BAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L188-L211 | train | 218,773 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | picard_formatconverter | def picard_formatconverter(picard, align_sam):
"""Convert aligned SAM file to BAM format.
"""
out_bam = "%s.bam" % os.path.splitext(align_sam)[0]
if not file_exists(out_bam):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_bam) as tx_out_bam:
opts = [("INPUT", align_sam),
("OUTPUT", tx_out_bam),
("TMP_DIR", tmp_dir)]
picard.run("SamFormatConverter", opts)
return out_bam | python | def picard_formatconverter(picard, align_sam):
"""Convert aligned SAM file to BAM format.
"""
out_bam = "%s.bam" % os.path.splitext(align_sam)[0]
if not file_exists(out_bam):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_bam) as tx_out_bam:
opts = [("INPUT", align_sam),
("OUTPUT", tx_out_bam),
("TMP_DIR", tmp_dir)]
picard.run("SamFormatConverter", opts)
return out_bam | [
"def",
"picard_formatconverter",
"(",
"picard",
",",
"align_sam",
")",
":",
"out_bam",
"=",
"\"%s.bam\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"align_sam",
")",
"[",
"0",
"]",
"if",
"not",
"file_exists",
"(",
"out_bam",
")",
":",
"with",
"tx_tmp... | Convert aligned SAM file to BAM format. | [
"Convert",
"aligned",
"SAM",
"file",
"to",
"BAM",
"format",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L213-L224 | train | 218,774 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | picard_fixmate | def picard_fixmate(picard, align_bam):
"""Run Picard's FixMateInformation generating an aligned output file.
"""
base, ext = os.path.splitext(align_bam)
out_file = "%s-sort%s" % (base, ext)
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("INPUT", align_bam),
("OUTPUT", tx_out_file),
("TMP_DIR", tmp_dir),
("SORT_ORDER", "coordinate")]
picard.run("FixMateInformation", opts)
return out_file | python | def picard_fixmate(picard, align_bam):
"""Run Picard's FixMateInformation generating an aligned output file.
"""
base, ext = os.path.splitext(align_bam)
out_file = "%s-sort%s" % (base, ext)
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("INPUT", align_bam),
("OUTPUT", tx_out_file),
("TMP_DIR", tmp_dir),
("SORT_ORDER", "coordinate")]
picard.run("FixMateInformation", opts)
return out_file | [
"def",
"picard_fixmate",
"(",
"picard",
",",
"align_bam",
")",
":",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"align_bam",
")",
"out_file",
"=",
"\"%s-sort%s\"",
"%",
"(",
"base",
",",
"ext",
")",
"if",
"not",
"file_exists",
"("... | Run Picard's FixMateInformation generating an aligned output file. | [
"Run",
"Picard",
"s",
"FixMateInformation",
"generating",
"an",
"aligned",
"output",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L244-L257 | train | 218,775 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | picard_idxstats | def picard_idxstats(picard, align_bam):
"""Retrieve alignment stats from picard using BamIndexStats.
"""
opts = [("INPUT", align_bam)]
stdout = picard.run("BamIndexStats", opts, get_stdout=True)
out = []
AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "aligned", "unaligned"])
for line in stdout.split("\n"):
if line:
parts = line.split()
if len(parts) == 2:
_, unaligned = parts
out.append(AlignInfo("nocontig", 0, 0, int(unaligned)))
elif len(parts) == 7:
contig, _, length, _, aligned, _, unaligned = parts
out.append(AlignInfo(contig, int(length), int(aligned), int(unaligned)))
else:
raise ValueError("Unexpected output from BamIndexStats: %s" % line)
return out | python | def picard_idxstats(picard, align_bam):
"""Retrieve alignment stats from picard using BamIndexStats.
"""
opts = [("INPUT", align_bam)]
stdout = picard.run("BamIndexStats", opts, get_stdout=True)
out = []
AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "aligned", "unaligned"])
for line in stdout.split("\n"):
if line:
parts = line.split()
if len(parts) == 2:
_, unaligned = parts
out.append(AlignInfo("nocontig", 0, 0, int(unaligned)))
elif len(parts) == 7:
contig, _, length, _, aligned, _, unaligned = parts
out.append(AlignInfo(contig, int(length), int(aligned), int(unaligned)))
else:
raise ValueError("Unexpected output from BamIndexStats: %s" % line)
return out | [
"def",
"picard_idxstats",
"(",
"picard",
",",
"align_bam",
")",
":",
"opts",
"=",
"[",
"(",
"\"INPUT\"",
",",
"align_bam",
")",
"]",
"stdout",
"=",
"picard",
".",
"run",
"(",
"\"BamIndexStats\"",
",",
"opts",
",",
"get_stdout",
"=",
"True",
")",
"out",
... | Retrieve alignment stats from picard using BamIndexStats. | [
"Retrieve",
"alignment",
"stats",
"from",
"picard",
"using",
"BamIndexStats",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L259-L277 | train | 218,776 |
bcbio/bcbio-nextgen | bcbio/broad/picardrun.py | bed2interval | def bed2interval(align_file, bed, out_file=None):
"""Converts a bed file to an interval file for use with some of the
Picard tools by grabbing the header from the alignment file, reording
the bed file columns and gluing them together.
align_file can be in BAM or SAM format.
bed needs to be in bed12 format:
http://genome.ucsc.edu/FAQ/FAQformat.html#format1.5
"""
import pysam
base, ext = os.path.splitext(align_file)
if out_file is None:
out_file = base + ".interval"
with pysam.Samfile(align_file, "r" if ext.endswith(".sam") else "rb") as in_bam:
header = in_bam.text
def reorder_line(line):
splitline = line.strip().split("\t")
reordered = "\t".join([splitline[0], str(int(splitline[1]) + 1), splitline[2],
splitline[5], splitline[3]])
return reordered + "\n"
with file_transaction(out_file) as tx_out_file:
with open(bed) as bed_handle:
with open(tx_out_file, "w") as out_handle:
out_handle.write(header)
for line in bed_handle:
out_handle.write(reorder_line(line))
return out_file | python | def bed2interval(align_file, bed, out_file=None):
"""Converts a bed file to an interval file for use with some of the
Picard tools by grabbing the header from the alignment file, reording
the bed file columns and gluing them together.
align_file can be in BAM or SAM format.
bed needs to be in bed12 format:
http://genome.ucsc.edu/FAQ/FAQformat.html#format1.5
"""
import pysam
base, ext = os.path.splitext(align_file)
if out_file is None:
out_file = base + ".interval"
with pysam.Samfile(align_file, "r" if ext.endswith(".sam") else "rb") as in_bam:
header = in_bam.text
def reorder_line(line):
splitline = line.strip().split("\t")
reordered = "\t".join([splitline[0], str(int(splitline[1]) + 1), splitline[2],
splitline[5], splitline[3]])
return reordered + "\n"
with file_transaction(out_file) as tx_out_file:
with open(bed) as bed_handle:
with open(tx_out_file, "w") as out_handle:
out_handle.write(header)
for line in bed_handle:
out_handle.write(reorder_line(line))
return out_file | [
"def",
"bed2interval",
"(",
"align_file",
",",
"bed",
",",
"out_file",
"=",
"None",
")",
":",
"import",
"pysam",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"align_file",
")",
"if",
"out_file",
"is",
"None",
":",
"out_file",
"=",
... | Converts a bed file to an interval file for use with some of the
Picard tools by grabbing the header from the alignment file, reording
the bed file columns and gluing them together.
align_file can be in BAM or SAM format.
bed needs to be in bed12 format:
http://genome.ucsc.edu/FAQ/FAQformat.html#format1.5 | [
"Converts",
"a",
"bed",
"file",
"to",
"an",
"interval",
"file",
"for",
"use",
"with",
"some",
"of",
"the",
"Picard",
"tools",
"by",
"grabbing",
"the",
"header",
"from",
"the",
"alignment",
"file",
"reording",
"the",
"bed",
"file",
"columns",
"and",
"gluing... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/picardrun.py#L279-L309 | train | 218,777 |
bcbio/bcbio-nextgen | bcbio/variation/vardict.py | _enforce_max_region_size | def _enforce_max_region_size(in_file, data):
"""Ensure we don't have any chunks in the region greater than 20kb.
VarDict memory usage depends on size of individual windows in the input
file. This breaks regions into 20kb chunks with 250bp overlaps. 20kb gives
~1Gb/core memory usage and the overlaps avoid missing indels spanning a
gap. Downstream VarDict merging sorts out any variants across windows.
https://github.com/AstraZeneca-NGS/VarDictJava/issues/64
"""
max_size = 20000
overlap_size = 250
def _has_larger_regions(f):
return any(r.stop - r.start > max_size for r in pybedtools.BedTool(f))
out_file = "%s-regionlimit%s" % utils.splitext_plus(in_file)
if not utils.file_exists(out_file):
if _has_larger_regions(in_file):
with file_transaction(data, out_file) as tx_out_file:
pybedtools.BedTool().window_maker(w=max_size,
s=max_size - overlap_size,
b=pybedtools.BedTool(in_file)).saveas(tx_out_file)
else:
utils.symlink_plus(in_file, out_file)
return out_file | python | def _enforce_max_region_size(in_file, data):
"""Ensure we don't have any chunks in the region greater than 20kb.
VarDict memory usage depends on size of individual windows in the input
file. This breaks regions into 20kb chunks with 250bp overlaps. 20kb gives
~1Gb/core memory usage and the overlaps avoid missing indels spanning a
gap. Downstream VarDict merging sorts out any variants across windows.
https://github.com/AstraZeneca-NGS/VarDictJava/issues/64
"""
max_size = 20000
overlap_size = 250
def _has_larger_regions(f):
return any(r.stop - r.start > max_size for r in pybedtools.BedTool(f))
out_file = "%s-regionlimit%s" % utils.splitext_plus(in_file)
if not utils.file_exists(out_file):
if _has_larger_regions(in_file):
with file_transaction(data, out_file) as tx_out_file:
pybedtools.BedTool().window_maker(w=max_size,
s=max_size - overlap_size,
b=pybedtools.BedTool(in_file)).saveas(tx_out_file)
else:
utils.symlink_plus(in_file, out_file)
return out_file | [
"def",
"_enforce_max_region_size",
"(",
"in_file",
",",
"data",
")",
":",
"max_size",
"=",
"20000",
"overlap_size",
"=",
"250",
"def",
"_has_larger_regions",
"(",
"f",
")",
":",
"return",
"any",
"(",
"r",
".",
"stop",
"-",
"r",
".",
"start",
">",
"max_si... | Ensure we don't have any chunks in the region greater than 20kb.
VarDict memory usage depends on size of individual windows in the input
file. This breaks regions into 20kb chunks with 250bp overlaps. 20kb gives
~1Gb/core memory usage and the overlaps avoid missing indels spanning a
gap. Downstream VarDict merging sorts out any variants across windows.
https://github.com/AstraZeneca-NGS/VarDictJava/issues/64 | [
"Ensure",
"we",
"don",
"t",
"have",
"any",
"chunks",
"in",
"the",
"region",
"greater",
"than",
"20kb",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vardict.py#L90-L113 | train | 218,778 |
bcbio/bcbio-nextgen | bcbio/variation/vardict.py | run_vardict | def run_vardict(align_bams, items, ref_file, assoc_files, region=None,
out_file=None):
"""Run VarDict variant calling.
"""
items = shared.add_highdepth_genome_exclusion(items)
if vcfutils.is_paired_analysis(align_bams, items):
call_file = _run_vardict_paired(align_bams, items, ref_file,
assoc_files, region, out_file)
else:
vcfutils.check_paired_problems(items)
call_file = _run_vardict_caller(align_bams, items, ref_file,
assoc_files, region, out_file)
return call_file | python | def run_vardict(align_bams, items, ref_file, assoc_files, region=None,
out_file=None):
"""Run VarDict variant calling.
"""
items = shared.add_highdepth_genome_exclusion(items)
if vcfutils.is_paired_analysis(align_bams, items):
call_file = _run_vardict_paired(align_bams, items, ref_file,
assoc_files, region, out_file)
else:
vcfutils.check_paired_problems(items)
call_file = _run_vardict_caller(align_bams, items, ref_file,
assoc_files, region, out_file)
return call_file | [
"def",
"run_vardict",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"items",
"=",
"shared",
".",
"add_highdepth_genome_exclusion",
"(",
"items",
")",
"if",
"vcfutils"... | Run VarDict variant calling. | [
"Run",
"VarDict",
"variant",
"calling",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vardict.py#L115-L127 | train | 218,779 |
bcbio/bcbio-nextgen | bcbio/variation/vardict.py | _get_jvm_opts | def _get_jvm_opts(data, out_file):
"""Retrieve JVM options when running the Java version of VarDict.
"""
if get_vardict_command(data) == "vardict-java":
resources = config_utils.get_resources("vardict", data["config"])
jvm_opts = resources.get("jvm_opts", ["-Xms750m", "-Xmx4g"])
jvm_opts += broad.get_default_jvm_opts(os.path.dirname(out_file))
return "export VAR_DICT_OPTS='%s' && " % " ".join(jvm_opts)
else:
return "" | python | def _get_jvm_opts(data, out_file):
"""Retrieve JVM options when running the Java version of VarDict.
"""
if get_vardict_command(data) == "vardict-java":
resources = config_utils.get_resources("vardict", data["config"])
jvm_opts = resources.get("jvm_opts", ["-Xms750m", "-Xmx4g"])
jvm_opts += broad.get_default_jvm_opts(os.path.dirname(out_file))
return "export VAR_DICT_OPTS='%s' && " % " ".join(jvm_opts)
else:
return "" | [
"def",
"_get_jvm_opts",
"(",
"data",
",",
"out_file",
")",
":",
"if",
"get_vardict_command",
"(",
"data",
")",
"==",
"\"vardict-java\"",
":",
"resources",
"=",
"config_utils",
".",
"get_resources",
"(",
"\"vardict\"",
",",
"data",
"[",
"\"config\"",
"]",
")",
... | Retrieve JVM options when running the Java version of VarDict. | [
"Retrieve",
"JVM",
"options",
"when",
"running",
"the",
"Java",
"version",
"of",
"VarDict",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vardict.py#L129-L138 | train | 218,780 |
bcbio/bcbio-nextgen | bcbio/variation/vardict.py | _run_vardict_caller | def _run_vardict_caller(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Detect SNPs and indels with VarDict.
var2vcf_valid uses -A flag which reports all alleles and improves sensitivity:
https://github.com/AstraZeneca-NGS/VarDict/issues/35#issuecomment-276738191
"""
config = items[0]["config"]
if out_file is None:
out_file = "%s-variants.vcf.gz" % os.path.splitext(align_bams[0])[0]
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
vrs = bedutils.population_variant_regions(items)
target = shared.subset_variant_regions(
vrs, region, out_file, items=items, do_merge=False)
num_bams = len(align_bams)
sample_vcf_names = [] # for individual sample names, given batch calling may be required
for bamfile, item in zip(align_bams, items):
# prepare commands
sample = dd.get_sample_name(item)
vardict = get_vardict_command(items[0])
opts, var2vcf_opts = _vardict_options_from_config(items, config, out_file, target)
vcfstreamsort = config_utils.get_program("vcfstreamsort", config)
compress_cmd = "| bgzip -c" if tx_out_file.endswith("gz") else ""
fix_ambig_ref = vcfutils.fix_ambiguous_cl()
fix_ambig_alt = vcfutils.fix_ambiguous_cl(5)
remove_dup = vcfutils.remove_dup_cl()
py_cl = os.path.join(utils.get_bcbio_bin(), "py")
jvm_opts = _get_jvm_opts(items[0], tx_out_file)
setup = ("%s && unset JAVA_HOME &&" % utils.get_R_exports())
contig_cl = vcfutils.add_contig_to_header_cl(ref_file, tx_out_file)
lowfreq_filter = _lowfreq_linear_filter(0, False)
cmd = ("{setup}{jvm_opts}{vardict} -G {ref_file} "
"-N {sample} -b {bamfile} {opts} "
"| teststrandbias.R "
"| var2vcf_valid.pl -A -N {sample} -E {var2vcf_opts} "
"| {contig_cl} | bcftools filter -i 'QUAL >= 0' | {lowfreq_filter} "
"| {fix_ambig_ref} | {fix_ambig_alt} | {remove_dup} | {vcfstreamsort} {compress_cmd}")
if num_bams > 1:
temp_file_prefix = out_file.replace(".gz", "").replace(".vcf", "") + item["name"][1]
tmp_out = temp_file_prefix + ".temp.vcf"
tmp_out += ".gz" if out_file.endswith("gz") else ""
sample_vcf_names.append(tmp_out)
with file_transaction(item, tmp_out) as tx_tmp_file:
if not _is_bed_file(target):
vcfutils.write_empty_vcf(tx_tmp_file, config, samples=[sample])
else:
cmd += " > {tx_tmp_file}"
do.run(cmd.format(**locals()), "Genotyping with VarDict: Inference", {})
else:
if not _is_bed_file(target):
vcfutils.write_empty_vcf(tx_out_file, config, samples=[sample])
else:
cmd += " > {tx_out_file}"
do.run(cmd.format(**locals()), "Genotyping with VarDict: Inference", {})
if num_bams > 1:
# N.B. merge_variant_files wants region in 1-based end-inclusive
# coordinates. Thus use bamprep.region_to_gatk
vcfutils.merge_variant_files(orig_files=sample_vcf_names,
out_file=tx_out_file, ref_file=ref_file,
config=config, region=bamprep.region_to_gatk(region))
return out_file | python | def _run_vardict_caller(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Detect SNPs and indels with VarDict.
var2vcf_valid uses -A flag which reports all alleles and improves sensitivity:
https://github.com/AstraZeneca-NGS/VarDict/issues/35#issuecomment-276738191
"""
config = items[0]["config"]
if out_file is None:
out_file = "%s-variants.vcf.gz" % os.path.splitext(align_bams[0])[0]
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
vrs = bedutils.population_variant_regions(items)
target = shared.subset_variant_regions(
vrs, region, out_file, items=items, do_merge=False)
num_bams = len(align_bams)
sample_vcf_names = [] # for individual sample names, given batch calling may be required
for bamfile, item in zip(align_bams, items):
# prepare commands
sample = dd.get_sample_name(item)
vardict = get_vardict_command(items[0])
opts, var2vcf_opts = _vardict_options_from_config(items, config, out_file, target)
vcfstreamsort = config_utils.get_program("vcfstreamsort", config)
compress_cmd = "| bgzip -c" if tx_out_file.endswith("gz") else ""
fix_ambig_ref = vcfutils.fix_ambiguous_cl()
fix_ambig_alt = vcfutils.fix_ambiguous_cl(5)
remove_dup = vcfutils.remove_dup_cl()
py_cl = os.path.join(utils.get_bcbio_bin(), "py")
jvm_opts = _get_jvm_opts(items[0], tx_out_file)
setup = ("%s && unset JAVA_HOME &&" % utils.get_R_exports())
contig_cl = vcfutils.add_contig_to_header_cl(ref_file, tx_out_file)
lowfreq_filter = _lowfreq_linear_filter(0, False)
cmd = ("{setup}{jvm_opts}{vardict} -G {ref_file} "
"-N {sample} -b {bamfile} {opts} "
"| teststrandbias.R "
"| var2vcf_valid.pl -A -N {sample} -E {var2vcf_opts} "
"| {contig_cl} | bcftools filter -i 'QUAL >= 0' | {lowfreq_filter} "
"| {fix_ambig_ref} | {fix_ambig_alt} | {remove_dup} | {vcfstreamsort} {compress_cmd}")
if num_bams > 1:
temp_file_prefix = out_file.replace(".gz", "").replace(".vcf", "") + item["name"][1]
tmp_out = temp_file_prefix + ".temp.vcf"
tmp_out += ".gz" if out_file.endswith("gz") else ""
sample_vcf_names.append(tmp_out)
with file_transaction(item, tmp_out) as tx_tmp_file:
if not _is_bed_file(target):
vcfutils.write_empty_vcf(tx_tmp_file, config, samples=[sample])
else:
cmd += " > {tx_tmp_file}"
do.run(cmd.format(**locals()), "Genotyping with VarDict: Inference", {})
else:
if not _is_bed_file(target):
vcfutils.write_empty_vcf(tx_out_file, config, samples=[sample])
else:
cmd += " > {tx_out_file}"
do.run(cmd.format(**locals()), "Genotyping with VarDict: Inference", {})
if num_bams > 1:
# N.B. merge_variant_files wants region in 1-based end-inclusive
# coordinates. Thus use bamprep.region_to_gatk
vcfutils.merge_variant_files(orig_files=sample_vcf_names,
out_file=tx_out_file, ref_file=ref_file,
config=config, region=bamprep.region_to_gatk(region))
return out_file | [
"def",
"_run_vardict_caller",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
"if",
"out_file",
"is",... | Detect SNPs and indels with VarDict.
var2vcf_valid uses -A flag which reports all alleles and improves sensitivity:
https://github.com/AstraZeneca-NGS/VarDict/issues/35#issuecomment-276738191 | [
"Detect",
"SNPs",
"and",
"indels",
"with",
"VarDict",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vardict.py#L140-L201 | train | 218,781 |
bcbio/bcbio-nextgen | bcbio/variation/vardict.py | _lowfreq_linear_filter | def _lowfreq_linear_filter(tumor_index, is_paired):
"""Linear classifier for removing low frequency false positives.
Uses a logistic classifier based on 0.5% tumor only variants from the smcounter2 paper:
https://github.com/bcbio/bcbio_validations/tree/master/somatic-lowfreq
The classifier uses strand bias (SBF) and read mismatches (NM) and
applies only for low frequency (<2%) and low depth (<30) variants.
"""
if is_paired:
sbf = "FORMAT/SBF[%s]" % tumor_index
nm = "FORMAT/NM[%s]" % tumor_index
else:
sbf = "INFO/SBF"
nm = "INFO/NM"
cmd = ("""bcftools filter --soft-filter 'LowFreqBias' --mode '+' """
"""-e 'FORMAT/AF[{tumor_index}] < 0.02 && FORMAT/VD[{tumor_index}] < 30 """
"""&& {sbf} < 0.1 && {nm} >= 2.0'""")
return cmd.format(**locals()) | python | def _lowfreq_linear_filter(tumor_index, is_paired):
"""Linear classifier for removing low frequency false positives.
Uses a logistic classifier based on 0.5% tumor only variants from the smcounter2 paper:
https://github.com/bcbio/bcbio_validations/tree/master/somatic-lowfreq
The classifier uses strand bias (SBF) and read mismatches (NM) and
applies only for low frequency (<2%) and low depth (<30) variants.
"""
if is_paired:
sbf = "FORMAT/SBF[%s]" % tumor_index
nm = "FORMAT/NM[%s]" % tumor_index
else:
sbf = "INFO/SBF"
nm = "INFO/NM"
cmd = ("""bcftools filter --soft-filter 'LowFreqBias' --mode '+' """
"""-e 'FORMAT/AF[{tumor_index}] < 0.02 && FORMAT/VD[{tumor_index}] < 30 """
"""&& {sbf} < 0.1 && {nm} >= 2.0'""")
return cmd.format(**locals()) | [
"def",
"_lowfreq_linear_filter",
"(",
"tumor_index",
",",
"is_paired",
")",
":",
"if",
"is_paired",
":",
"sbf",
"=",
"\"FORMAT/SBF[%s]\"",
"%",
"tumor_index",
"nm",
"=",
"\"FORMAT/NM[%s]\"",
"%",
"tumor_index",
"else",
":",
"sbf",
"=",
"\"INFO/SBF\"",
"nm",
"=",... | Linear classifier for removing low frequency false positives.
Uses a logistic classifier based on 0.5% tumor only variants from the smcounter2 paper:
https://github.com/bcbio/bcbio_validations/tree/master/somatic-lowfreq
The classifier uses strand bias (SBF) and read mismatches (NM) and
applies only for low frequency (<2%) and low depth (<30) variants. | [
"Linear",
"classifier",
"for",
"removing",
"low",
"frequency",
"false",
"positives",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vardict.py#L203-L222 | train | 218,782 |
bcbio/bcbio-nextgen | bcbio/variation/vardict.py | add_db_germline_flag | def add_db_germline_flag(line):
"""Adds a DB flag for Germline filters, allowing downstream compatibility with PureCN.
"""
if line.startswith("#CHROM"):
headers = ['##INFO=<ID=DB,Number=0,Type=Flag,Description="Likely germline variant">']
return "\n".join(headers) + "\n" + line
elif line.startswith("#"):
return line
else:
parts = line.split("\t")
if parts[7].find("STATUS=Germline") >= 0:
parts[7] += ";DB"
return "\t".join(parts) | python | def add_db_germline_flag(line):
"""Adds a DB flag for Germline filters, allowing downstream compatibility with PureCN.
"""
if line.startswith("#CHROM"):
headers = ['##INFO=<ID=DB,Number=0,Type=Flag,Description="Likely germline variant">']
return "\n".join(headers) + "\n" + line
elif line.startswith("#"):
return line
else:
parts = line.split("\t")
if parts[7].find("STATUS=Germline") >= 0:
parts[7] += ";DB"
return "\t".join(parts) | [
"def",
"add_db_germline_flag",
"(",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"#CHROM\"",
")",
":",
"headers",
"=",
"[",
"'##INFO=<ID=DB,Number=0,Type=Flag,Description=\"Likely germline variant\">'",
"]",
"return",
"\"\\n\"",
".",
"join",
"(",
"headers... | Adds a DB flag for Germline filters, allowing downstream compatibility with PureCN. | [
"Adds",
"a",
"DB",
"flag",
"for",
"Germline",
"filters",
"allowing",
"downstream",
"compatibility",
"with",
"PureCN",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vardict.py#L224-L236 | train | 218,783 |
bcbio/bcbio-nextgen | bcbio/variation/vardict.py | depth_freq_filter | def depth_freq_filter(line, tumor_index, aligner):
"""Command line to filter VarDict calls based on depth, frequency and quality.
Looks at regions with low depth for allele frequency (AF * DP < 6, the equivalent
of < 13bp for heterogygote calls, but generalized. Within these calls filters if a
calls has:
- Low mapping quality and multiple mismatches in a read (NM)
For bwa only: MQ < 55.0 and NM > 1.0 or MQ < 60.0 and NM > 2.0
- Low depth (DP < 10)
- Low QUAL (QUAL < 45)
Also filters in low allele frequency regions with poor quality, if all of these are
true:
- Allele frequency < 0.2
- Quality < 55
- P-value (SSF) > 0.06
"""
if line.startswith("#CHROM"):
headers = [('##FILTER=<ID=LowAlleleDepth,Description="Low depth per allele frequency '
'along with poor depth, quality, mapping quality and read mismatches.">'),
('##FILTER=<ID=LowFreqQuality,Description="Low frequency read with '
'poor quality and p-value (SSF).">')]
return "\n".join(headers) + "\n" + line
elif line.startswith("#"):
return line
else:
parts = line.split("\t")
sample_ft = {a: v for (a, v) in zip(parts[8].split(":"), parts[9 + tumor_index].split(":"))}
qual = utils.safe_to_float(parts[5])
dp = utils.safe_to_float(sample_ft.get("DP"))
af = utils.safe_to_float(sample_ft.get("AF"))
nm = utils.safe_to_float(sample_ft.get("NM"))
mq = utils.safe_to_float(sample_ft.get("MQ"))
ssfs = [x for x in parts[7].split(";") if x.startswith("SSF=")]
pval = utils.safe_to_float(ssfs[0].split("=")[-1] if ssfs else None)
fname = None
if not chromhacks.is_sex(parts[0]) and dp is not None and af is not None:
if dp * af < 6:
if aligner == "bwa" and nm is not None and mq is not None:
if (mq < 55.0 and nm > 1.0) or (mq < 60.0 and nm > 2.0):
fname = "LowAlleleDepth"
if dp < 10:
fname = "LowAlleleDepth"
if qual is not None and qual < 45:
fname = "LowAlleleDepth"
if af is not None and qual is not None and pval is not None:
if af < 0.2 and qual < 45 and pval > 0.06:
fname = "LowFreqQuality"
if fname:
if parts[6] in set([".", "PASS"]):
parts[6] = fname
else:
parts[6] += ";%s" % fname
line = "\t".join(parts)
return line | python | def depth_freq_filter(line, tumor_index, aligner):
"""Command line to filter VarDict calls based on depth, frequency and quality.
Looks at regions with low depth for allele frequency (AF * DP < 6, the equivalent
of < 13bp for heterogygote calls, but generalized. Within these calls filters if a
calls has:
- Low mapping quality and multiple mismatches in a read (NM)
For bwa only: MQ < 55.0 and NM > 1.0 or MQ < 60.0 and NM > 2.0
- Low depth (DP < 10)
- Low QUAL (QUAL < 45)
Also filters in low allele frequency regions with poor quality, if all of these are
true:
- Allele frequency < 0.2
- Quality < 55
- P-value (SSF) > 0.06
"""
if line.startswith("#CHROM"):
headers = [('##FILTER=<ID=LowAlleleDepth,Description="Low depth per allele frequency '
'along with poor depth, quality, mapping quality and read mismatches.">'),
('##FILTER=<ID=LowFreqQuality,Description="Low frequency read with '
'poor quality and p-value (SSF).">')]
return "\n".join(headers) + "\n" + line
elif line.startswith("#"):
return line
else:
parts = line.split("\t")
sample_ft = {a: v for (a, v) in zip(parts[8].split(":"), parts[9 + tumor_index].split(":"))}
qual = utils.safe_to_float(parts[5])
dp = utils.safe_to_float(sample_ft.get("DP"))
af = utils.safe_to_float(sample_ft.get("AF"))
nm = utils.safe_to_float(sample_ft.get("NM"))
mq = utils.safe_to_float(sample_ft.get("MQ"))
ssfs = [x for x in parts[7].split(";") if x.startswith("SSF=")]
pval = utils.safe_to_float(ssfs[0].split("=")[-1] if ssfs else None)
fname = None
if not chromhacks.is_sex(parts[0]) and dp is not None and af is not None:
if dp * af < 6:
if aligner == "bwa" and nm is not None and mq is not None:
if (mq < 55.0 and nm > 1.0) or (mq < 60.0 and nm > 2.0):
fname = "LowAlleleDepth"
if dp < 10:
fname = "LowAlleleDepth"
if qual is not None and qual < 45:
fname = "LowAlleleDepth"
if af is not None and qual is not None and pval is not None:
if af < 0.2 and qual < 45 and pval > 0.06:
fname = "LowFreqQuality"
if fname:
if parts[6] in set([".", "PASS"]):
parts[6] = fname
else:
parts[6] += ";%s" % fname
line = "\t".join(parts)
return line | [
"def",
"depth_freq_filter",
"(",
"line",
",",
"tumor_index",
",",
"aligner",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"#CHROM\"",
")",
":",
"headers",
"=",
"[",
"(",
"'##FILTER=<ID=LowAlleleDepth,Description=\"Low depth per allele frequency '",
"'along with poo... | Command line to filter VarDict calls based on depth, frequency and quality.
Looks at regions with low depth for allele frequency (AF * DP < 6, the equivalent
of < 13bp for heterogygote calls, but generalized. Within these calls filters if a
calls has:
- Low mapping quality and multiple mismatches in a read (NM)
For bwa only: MQ < 55.0 and NM > 1.0 or MQ < 60.0 and NM > 2.0
- Low depth (DP < 10)
- Low QUAL (QUAL < 45)
Also filters in low allele frequency regions with poor quality, if all of these are
true:
- Allele frequency < 0.2
- Quality < 55
- P-value (SSF) > 0.06 | [
"Command",
"line",
"to",
"filter",
"VarDict",
"calls",
"based",
"on",
"depth",
"frequency",
"and",
"quality",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vardict.py#L238-L293 | train | 218,784 |
bcbio/bcbio-nextgen | bcbio/variation/vardict.py | get_vardict_command | def get_vardict_command(data):
"""
convert variantcaller specification to proper vardict command, handling
string or list specification
"""
vcaller = dd.get_variantcaller(data)
if isinstance(vcaller, list):
vardict = [x for x in vcaller if "vardict" in x]
if not vardict:
return None
vardict = vardict[0]
elif not vcaller:
return None
else:
vardict = vcaller
vardict = "vardict-java" if not vardict.endswith("-perl") else "vardict"
return vardict | python | def get_vardict_command(data):
"""
convert variantcaller specification to proper vardict command, handling
string or list specification
"""
vcaller = dd.get_variantcaller(data)
if isinstance(vcaller, list):
vardict = [x for x in vcaller if "vardict" in x]
if not vardict:
return None
vardict = vardict[0]
elif not vcaller:
return None
else:
vardict = vcaller
vardict = "vardict-java" if not vardict.endswith("-perl") else "vardict"
return vardict | [
"def",
"get_vardict_command",
"(",
"data",
")",
":",
"vcaller",
"=",
"dd",
".",
"get_variantcaller",
"(",
"data",
")",
"if",
"isinstance",
"(",
"vcaller",
",",
"list",
")",
":",
"vardict",
"=",
"[",
"x",
"for",
"x",
"in",
"vcaller",
"if",
"\"vardict\"",
... | convert variantcaller specification to proper vardict command, handling
string or list specification | [
"convert",
"variantcaller",
"specification",
"to",
"proper",
"vardict",
"command",
"handling",
"string",
"or",
"list",
"specification"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vardict.py#L362-L378 | train | 218,785 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | run | def run(vrn_info, calls_by_name, somatic_info, do_plots=True, handle_failures=True):
"""Run BubbleTree given variant calls, CNVs and somatic
"""
if "seq2c" in calls_by_name:
cnv_info = calls_by_name["seq2c"]
elif "cnvkit" in calls_by_name:
cnv_info = calls_by_name["cnvkit"]
else:
raise ValueError("BubbleTree only currently support CNVkit and Seq2c: %s" % ", ".join(calls_by_name.keys()))
work_dir = _cur_workdir(somatic_info.tumor_data)
class OutWriter:
def __init__(self, out_handle):
self.writer = csv.writer(out_handle)
def write_header(self):
self.writer.writerow(["chrom", "start", "end", "freq"])
def write_row(self, rec, stats):
self.writer.writerow([_to_ucsc_style(rec.chrom), rec.start, rec.stop, stats["tumor"]["freq"]])
vcf_csv = prep_vrn_file(vrn_info["vrn_file"], vrn_info["variantcaller"],
work_dir, somatic_info, OutWriter, cnv_info["cns"])
cnv_csv = _prep_cnv_file(cnv_info["cns"], cnv_info["variantcaller"], work_dir,
somatic_info.tumor_data)
wide_lrr = cnv_info["variantcaller"] == "cnvkit" and somatic_info.normal_bam is None
return _run_bubbletree(vcf_csv, cnv_csv, somatic_info.tumor_data, wide_lrr, do_plots,
handle_failures) | python | def run(vrn_info, calls_by_name, somatic_info, do_plots=True, handle_failures=True):
"""Run BubbleTree given variant calls, CNVs and somatic
"""
if "seq2c" in calls_by_name:
cnv_info = calls_by_name["seq2c"]
elif "cnvkit" in calls_by_name:
cnv_info = calls_by_name["cnvkit"]
else:
raise ValueError("BubbleTree only currently support CNVkit and Seq2c: %s" % ", ".join(calls_by_name.keys()))
work_dir = _cur_workdir(somatic_info.tumor_data)
class OutWriter:
def __init__(self, out_handle):
self.writer = csv.writer(out_handle)
def write_header(self):
self.writer.writerow(["chrom", "start", "end", "freq"])
def write_row(self, rec, stats):
self.writer.writerow([_to_ucsc_style(rec.chrom), rec.start, rec.stop, stats["tumor"]["freq"]])
vcf_csv = prep_vrn_file(vrn_info["vrn_file"], vrn_info["variantcaller"],
work_dir, somatic_info, OutWriter, cnv_info["cns"])
cnv_csv = _prep_cnv_file(cnv_info["cns"], cnv_info["variantcaller"], work_dir,
somatic_info.tumor_data)
wide_lrr = cnv_info["variantcaller"] == "cnvkit" and somatic_info.normal_bam is None
return _run_bubbletree(vcf_csv, cnv_csv, somatic_info.tumor_data, wide_lrr, do_plots,
handle_failures) | [
"def",
"run",
"(",
"vrn_info",
",",
"calls_by_name",
",",
"somatic_info",
",",
"do_plots",
"=",
"True",
",",
"handle_failures",
"=",
"True",
")",
":",
"if",
"\"seq2c\"",
"in",
"calls_by_name",
":",
"cnv_info",
"=",
"calls_by_name",
"[",
"\"seq2c\"",
"]",
"el... | Run BubbleTree given variant calls, CNVs and somatic | [
"Run",
"BubbleTree",
"given",
"variant",
"calls",
"CNVs",
"and",
"somatic"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L34-L57 | train | 218,786 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | _run_bubbletree | def _run_bubbletree(vcf_csv, cnv_csv, data, wide_lrr=False, do_plots=True,
handle_failures=True):
"""Create R script and run on input data
BubbleTree has some internal hardcoded paramters that assume a smaller
distribution of log2 scores. This is not true for tumor-only calls, so if
we specify wide_lrr we scale the calculations to actually get calls. Need a
better long term solution with flexible parameters.
"""
lrr_scale = 10.0 if wide_lrr else 1.0
local_sitelib = utils.R_sitelib()
base = utils.splitext_plus(vcf_csv)[0]
r_file = "%s-run.R" % base
bubbleplot_out = "%s-bubbleplot.pdf" % base
trackplot_out = "%s-trackplot.pdf" % base
calls_out = "%s-calls.rds" % base
freqs_out = "%s-bubbletree_prevalence.txt" % base
sample = dd.get_sample_name(data)
do_plots = "yes" if do_plots else "no"
with open(r_file, "w") as out_handle:
out_handle.write(_script.format(**locals()))
if not utils.file_exists(freqs_out):
cmd = "%s && %s --no-environ %s" % (utils.get_R_exports(), utils.Rscript_cmd(), r_file)
try:
do.run(cmd, "Assess heterogeneity with BubbleTree")
except subprocess.CalledProcessError as msg:
if handle_failures and _allowed_bubbletree_errorstates(str(msg)):
with open(freqs_out, "w") as out_handle:
out_handle.write('bubbletree failed:\n %s"\n' % (str(msg)))
else:
logger.exception()
raise
return {"caller": "bubbletree",
"report": freqs_out,
"plot": {"bubble": bubbleplot_out, "track": trackplot_out}} | python | def _run_bubbletree(vcf_csv, cnv_csv, data, wide_lrr=False, do_plots=True,
handle_failures=True):
"""Create R script and run on input data
BubbleTree has some internal hardcoded paramters that assume a smaller
distribution of log2 scores. This is not true for tumor-only calls, so if
we specify wide_lrr we scale the calculations to actually get calls. Need a
better long term solution with flexible parameters.
"""
lrr_scale = 10.0 if wide_lrr else 1.0
local_sitelib = utils.R_sitelib()
base = utils.splitext_plus(vcf_csv)[0]
r_file = "%s-run.R" % base
bubbleplot_out = "%s-bubbleplot.pdf" % base
trackplot_out = "%s-trackplot.pdf" % base
calls_out = "%s-calls.rds" % base
freqs_out = "%s-bubbletree_prevalence.txt" % base
sample = dd.get_sample_name(data)
do_plots = "yes" if do_plots else "no"
with open(r_file, "w") as out_handle:
out_handle.write(_script.format(**locals()))
if not utils.file_exists(freqs_out):
cmd = "%s && %s --no-environ %s" % (utils.get_R_exports(), utils.Rscript_cmd(), r_file)
try:
do.run(cmd, "Assess heterogeneity with BubbleTree")
except subprocess.CalledProcessError as msg:
if handle_failures and _allowed_bubbletree_errorstates(str(msg)):
with open(freqs_out, "w") as out_handle:
out_handle.write('bubbletree failed:\n %s"\n' % (str(msg)))
else:
logger.exception()
raise
return {"caller": "bubbletree",
"report": freqs_out,
"plot": {"bubble": bubbleplot_out, "track": trackplot_out}} | [
"def",
"_run_bubbletree",
"(",
"vcf_csv",
",",
"cnv_csv",
",",
"data",
",",
"wide_lrr",
"=",
"False",
",",
"do_plots",
"=",
"True",
",",
"handle_failures",
"=",
"True",
")",
":",
"lrr_scale",
"=",
"10.0",
"if",
"wide_lrr",
"else",
"1.0",
"local_sitelib",
"... | Create R script and run on input data
BubbleTree has some internal hardcoded paramters that assume a smaller
distribution of log2 scores. This is not true for tumor-only calls, so if
we specify wide_lrr we scale the calculations to actually get calls. Need a
better long term solution with flexible parameters. | [
"Create",
"R",
"script",
"and",
"run",
"on",
"input",
"data"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L59-L93 | train | 218,787 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | _prep_cnv_file | def _prep_cnv_file(cns_file, svcaller, work_dir, data):
"""Create a CSV file of CNV calls with log2 and number of marks.
"""
in_file = cns_file
out_file = os.path.join(work_dir, "%s-%s-prep.csv" % (utils.splitext_plus(os.path.basename(in_file))[0],
svcaller))
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:
reader = csv.reader(in_handle, dialect="excel-tab")
writer = csv.writer(out_handle)
writer.writerow(["chrom", "start", "end", "num.mark", "seg.mean"])
header = next(reader)
for line in reader:
cur = dict(zip(header, line))
if chromhacks.is_autosomal(cur["chromosome"]):
writer.writerow([_to_ucsc_style(cur["chromosome"]), cur["start"],
cur["end"], cur["probes"], cur["log2"]])
return out_file | python | def _prep_cnv_file(cns_file, svcaller, work_dir, data):
"""Create a CSV file of CNV calls with log2 and number of marks.
"""
in_file = cns_file
out_file = os.path.join(work_dir, "%s-%s-prep.csv" % (utils.splitext_plus(os.path.basename(in_file))[0],
svcaller))
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:
reader = csv.reader(in_handle, dialect="excel-tab")
writer = csv.writer(out_handle)
writer.writerow(["chrom", "start", "end", "num.mark", "seg.mean"])
header = next(reader)
for line in reader:
cur = dict(zip(header, line))
if chromhacks.is_autosomal(cur["chromosome"]):
writer.writerow([_to_ucsc_style(cur["chromosome"]), cur["start"],
cur["end"], cur["probes"], cur["log2"]])
return out_file | [
"def",
"_prep_cnv_file",
"(",
"cns_file",
",",
"svcaller",
",",
"work_dir",
",",
"data",
")",
":",
"in_file",
"=",
"cns_file",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-%s-prep.csv\"",
"%",
"(",
"utils",
".",
"splitext_pl... | Create a CSV file of CNV calls with log2 and number of marks. | [
"Create",
"a",
"CSV",
"file",
"of",
"CNV",
"calls",
"with",
"log2",
"and",
"number",
"of",
"marks",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L104-L123 | train | 218,788 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | prep_vrn_file | def prep_vrn_file(in_file, vcaller, work_dir, somatic_info, writer_class, seg_file=None, params=None):
"""Select heterozygous variants in the normal sample with sufficient depth.
writer_class implements write_header and write_row to write VCF outputs
from a record and extracted tumor/normal statistics.
"""
data = somatic_info.tumor_data
if not params:
params = PARAMS
out_file = os.path.join(work_dir, "%s-%s-prep.csv" % (utils.splitext_plus(os.path.basename(in_file))[0],
vcaller))
if not utils.file_uptodate(out_file, in_file):
# ready_bed = _identify_heterogeneity_blocks_seg(in_file, seg_file, params, work_dir, somatic_info)
ready_bed = None
if ready_bed and utils.file_exists(ready_bed):
sub_file = _create_subset_file(in_file, ready_bed, work_dir, data)
else:
sub_file = in_file
max_depth = max_normal_germline_depth(sub_file, params, somatic_info)
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
writer = writer_class(out_handle)
writer.write_header()
bcf_in = pysam.VariantFile(sub_file)
for rec in bcf_in:
stats = _is_possible_loh(rec, bcf_in, params, somatic_info, max_normal_depth=max_depth)
if chromhacks.is_autosomal(rec.chrom) and stats is not None:
writer.write_row(rec, stats)
return out_file | python | def prep_vrn_file(in_file, vcaller, work_dir, somatic_info, writer_class, seg_file=None, params=None):
"""Select heterozygous variants in the normal sample with sufficient depth.
writer_class implements write_header and write_row to write VCF outputs
from a record and extracted tumor/normal statistics.
"""
data = somatic_info.tumor_data
if not params:
params = PARAMS
out_file = os.path.join(work_dir, "%s-%s-prep.csv" % (utils.splitext_plus(os.path.basename(in_file))[0],
vcaller))
if not utils.file_uptodate(out_file, in_file):
# ready_bed = _identify_heterogeneity_blocks_seg(in_file, seg_file, params, work_dir, somatic_info)
ready_bed = None
if ready_bed and utils.file_exists(ready_bed):
sub_file = _create_subset_file(in_file, ready_bed, work_dir, data)
else:
sub_file = in_file
max_depth = max_normal_germline_depth(sub_file, params, somatic_info)
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
writer = writer_class(out_handle)
writer.write_header()
bcf_in = pysam.VariantFile(sub_file)
for rec in bcf_in:
stats = _is_possible_loh(rec, bcf_in, params, somatic_info, max_normal_depth=max_depth)
if chromhacks.is_autosomal(rec.chrom) and stats is not None:
writer.write_row(rec, stats)
return out_file | [
"def",
"prep_vrn_file",
"(",
"in_file",
",",
"vcaller",
",",
"work_dir",
",",
"somatic_info",
",",
"writer_class",
",",
"seg_file",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"data",
"=",
"somatic_info",
".",
"tumor_data",
"if",
"not",
"params",
":... | Select heterozygous variants in the normal sample with sufficient depth.
writer_class implements write_header and write_row to write VCF outputs
from a record and extracted tumor/normal statistics. | [
"Select",
"heterozygous",
"variants",
"in",
"the",
"normal",
"sample",
"with",
"sufficient",
"depth",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L125-L153 | train | 218,789 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | max_normal_germline_depth | def max_normal_germline_depth(in_file, params, somatic_info):
"""Calculate threshold for excluding potential heterozygotes based on normal depth.
"""
bcf_in = pysam.VariantFile(in_file)
depths = []
for rec in bcf_in:
stats = _is_possible_loh(rec, bcf_in, params, somatic_info)
if tz.get_in(["normal", "depth"], stats):
depths.append(tz.get_in(["normal", "depth"], stats))
if depths:
return np.median(depths) * NORMAL_FILTER_PARAMS["max_depth_percent"] | python | def max_normal_germline_depth(in_file, params, somatic_info):
"""Calculate threshold for excluding potential heterozygotes based on normal depth.
"""
bcf_in = pysam.VariantFile(in_file)
depths = []
for rec in bcf_in:
stats = _is_possible_loh(rec, bcf_in, params, somatic_info)
if tz.get_in(["normal", "depth"], stats):
depths.append(tz.get_in(["normal", "depth"], stats))
if depths:
return np.median(depths) * NORMAL_FILTER_PARAMS["max_depth_percent"] | [
"def",
"max_normal_germline_depth",
"(",
"in_file",
",",
"params",
",",
"somatic_info",
")",
":",
"bcf_in",
"=",
"pysam",
".",
"VariantFile",
"(",
"in_file",
")",
"depths",
"=",
"[",
"]",
"for",
"rec",
"in",
"bcf_in",
":",
"stats",
"=",
"_is_possible_loh",
... | Calculate threshold for excluding potential heterozygotes based on normal depth. | [
"Calculate",
"threshold",
"for",
"excluding",
"potential",
"heterozygotes",
"based",
"on",
"normal",
"depth",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L162-L172 | train | 218,790 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | _identify_heterogeneity_blocks_hmm | def _identify_heterogeneity_blocks_hmm(in_file, params, work_dir, somatic_info):
"""Use a HMM to identify blocks of heterogeneity to use for calculating allele frequencies.
The goal is to subset the genome to a more reasonable section that contains potential
loss of heterogeneity or other allele frequency adjustment based on selection.
"""
def _segment_by_hmm(chrom, freqs, coords):
cur_coords = []
for j, state in enumerate(_predict_states(freqs)):
if state == 0: # heterozygote region
if len(cur_coords) == 0:
num_misses = 0
cur_coords.append(coords[j])
else:
num_misses += 1
if num_misses > params["hetblock"]["allowed_misses"]:
if len(cur_coords) >= params["hetblock"]["min_alleles"]:
yield min(cur_coords), max(cur_coords)
cur_coords = []
if len(cur_coords) >= params["hetblock"]["min_alleles"]:
yield min(cur_coords), max(cur_coords)
return _identify_heterogeneity_blocks_shared(in_file, _segment_by_hmm, params, work_dir, somatic_info) | python | def _identify_heterogeneity_blocks_hmm(in_file, params, work_dir, somatic_info):
"""Use a HMM to identify blocks of heterogeneity to use for calculating allele frequencies.
The goal is to subset the genome to a more reasonable section that contains potential
loss of heterogeneity or other allele frequency adjustment based on selection.
"""
def _segment_by_hmm(chrom, freqs, coords):
cur_coords = []
for j, state in enumerate(_predict_states(freqs)):
if state == 0: # heterozygote region
if len(cur_coords) == 0:
num_misses = 0
cur_coords.append(coords[j])
else:
num_misses += 1
if num_misses > params["hetblock"]["allowed_misses"]:
if len(cur_coords) >= params["hetblock"]["min_alleles"]:
yield min(cur_coords), max(cur_coords)
cur_coords = []
if len(cur_coords) >= params["hetblock"]["min_alleles"]:
yield min(cur_coords), max(cur_coords)
return _identify_heterogeneity_blocks_shared(in_file, _segment_by_hmm, params, work_dir, somatic_info) | [
"def",
"_identify_heterogeneity_blocks_hmm",
"(",
"in_file",
",",
"params",
",",
"work_dir",
",",
"somatic_info",
")",
":",
"def",
"_segment_by_hmm",
"(",
"chrom",
",",
"freqs",
",",
"coords",
")",
":",
"cur_coords",
"=",
"[",
"]",
"for",
"j",
",",
"state",
... | Use a HMM to identify blocks of heterogeneity to use for calculating allele frequencies.
The goal is to subset the genome to a more reasonable section that contains potential
loss of heterogeneity or other allele frequency adjustment based on selection. | [
"Use",
"a",
"HMM",
"to",
"identify",
"blocks",
"of",
"heterogeneity",
"to",
"use",
"for",
"calculating",
"allele",
"frequencies",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L195-L216 | train | 218,791 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | _predict_states | def _predict_states(freqs):
"""Use frequencies to predict states across a chromosome.
Normalize so heterozygote blocks are assigned state 0 and homozygous
are assigned state 1.
"""
from hmmlearn import hmm
freqs = np.column_stack([np.array(freqs)])
model = hmm.GaussianHMM(2, covariance_type="full")
model.fit(freqs)
states = model.predict(freqs)
freqs_by_state = collections.defaultdict(list)
for i, state in enumerate(states):
freqs_by_state[state].append(freqs[i])
if np.median(freqs_by_state[0]) > np.median(freqs_by_state[1]):
states = [0 if s == 1 else 1 for s in states]
return states | python | def _predict_states(freqs):
"""Use frequencies to predict states across a chromosome.
Normalize so heterozygote blocks are assigned state 0 and homozygous
are assigned state 1.
"""
from hmmlearn import hmm
freqs = np.column_stack([np.array(freqs)])
model = hmm.GaussianHMM(2, covariance_type="full")
model.fit(freqs)
states = model.predict(freqs)
freqs_by_state = collections.defaultdict(list)
for i, state in enumerate(states):
freqs_by_state[state].append(freqs[i])
if np.median(freqs_by_state[0]) > np.median(freqs_by_state[1]):
states = [0 if s == 1 else 1 for s in states]
return states | [
"def",
"_predict_states",
"(",
"freqs",
")",
":",
"from",
"hmmlearn",
"import",
"hmm",
"freqs",
"=",
"np",
".",
"column_stack",
"(",
"[",
"np",
".",
"array",
"(",
"freqs",
")",
"]",
")",
"model",
"=",
"hmm",
".",
"GaussianHMM",
"(",
"2",
",",
"covari... | Use frequencies to predict states across a chromosome.
Normalize so heterozygote blocks are assigned state 0 and homozygous
are assigned state 1. | [
"Use",
"frequencies",
"to",
"predict",
"states",
"across",
"a",
"chromosome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L230-L246 | train | 218,792 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | _freqs_by_chromosome | def _freqs_by_chromosome(in_file, params, somatic_info):
"""Retrieve frequencies across each chromosome as inputs to HMM.
"""
freqs = []
coords = []
cur_chrom = None
with pysam.VariantFile(in_file) as bcf_in:
for rec in bcf_in:
if _is_biallelic_snp(rec) and _passes_plus_germline(rec) and chromhacks.is_autosomal(rec.chrom):
if cur_chrom is None or rec.chrom != cur_chrom:
if cur_chrom and len(freqs) > 0:
yield cur_chrom, freqs, coords
cur_chrom = rec.chrom
freqs = []
coords = []
stats = _tumor_normal_stats(rec, somatic_info)
if tz.get_in(["tumor", "depth"], stats, 0) > params["min_depth"]:
# not a ref only call
if len(rec.samples) == 0 or sum(rec.samples[somatic_info.tumor_name].allele_indices) > 0:
freqs.append(tz.get_in(["tumor", "freq"], stats))
coords.append(rec.start)
if cur_chrom and len(freqs) > 0:
yield cur_chrom, freqs, coords | python | def _freqs_by_chromosome(in_file, params, somatic_info):
"""Retrieve frequencies across each chromosome as inputs to HMM.
"""
freqs = []
coords = []
cur_chrom = None
with pysam.VariantFile(in_file) as bcf_in:
for rec in bcf_in:
if _is_biallelic_snp(rec) and _passes_plus_germline(rec) and chromhacks.is_autosomal(rec.chrom):
if cur_chrom is None or rec.chrom != cur_chrom:
if cur_chrom and len(freqs) > 0:
yield cur_chrom, freqs, coords
cur_chrom = rec.chrom
freqs = []
coords = []
stats = _tumor_normal_stats(rec, somatic_info)
if tz.get_in(["tumor", "depth"], stats, 0) > params["min_depth"]:
# not a ref only call
if len(rec.samples) == 0 or sum(rec.samples[somatic_info.tumor_name].allele_indices) > 0:
freqs.append(tz.get_in(["tumor", "freq"], stats))
coords.append(rec.start)
if cur_chrom and len(freqs) > 0:
yield cur_chrom, freqs, coords | [
"def",
"_freqs_by_chromosome",
"(",
"in_file",
",",
"params",
",",
"somatic_info",
")",
":",
"freqs",
"=",
"[",
"]",
"coords",
"=",
"[",
"]",
"cur_chrom",
"=",
"None",
"with",
"pysam",
".",
"VariantFile",
"(",
"in_file",
")",
"as",
"bcf_in",
":",
"for",
... | Retrieve frequencies across each chromosome as inputs to HMM. | [
"Retrieve",
"frequencies",
"across",
"each",
"chromosome",
"as",
"inputs",
"to",
"HMM",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L248-L270 | train | 218,793 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | _create_subset_file | def _create_subset_file(in_file, het_region_bed, work_dir, data):
"""Subset the VCF to a set of pre-calculated smaller regions.
"""
cnv_regions = shared.get_base_cnv_regions(data, work_dir)
region_bed = bedutils.intersect_two(het_region_bed, cnv_regions, work_dir, data)
out_file = os.path.join(work_dir, "%s-origsubset.bcf" % utils.splitext_plus(os.path.basename(in_file))[0])
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
regions = ("-R %s" % region_bed) if utils.file_exists(region_bed) else ""
cmd = "bcftools view {regions} -o {tx_out_file} -O b {in_file}"
do.run(cmd.format(**locals()), "Extract regions for BubbleTree frequency determination")
return out_file | python | def _create_subset_file(in_file, het_region_bed, work_dir, data):
"""Subset the VCF to a set of pre-calculated smaller regions.
"""
cnv_regions = shared.get_base_cnv_regions(data, work_dir)
region_bed = bedutils.intersect_two(het_region_bed, cnv_regions, work_dir, data)
out_file = os.path.join(work_dir, "%s-origsubset.bcf" % utils.splitext_plus(os.path.basename(in_file))[0])
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
regions = ("-R %s" % region_bed) if utils.file_exists(region_bed) else ""
cmd = "bcftools view {regions} -o {tx_out_file} -O b {in_file}"
do.run(cmd.format(**locals()), "Extract regions for BubbleTree frequency determination")
return out_file | [
"def",
"_create_subset_file",
"(",
"in_file",
",",
"het_region_bed",
",",
"work_dir",
",",
"data",
")",
":",
"cnv_regions",
"=",
"shared",
".",
"get_base_cnv_regions",
"(",
"data",
",",
"work_dir",
")",
"region_bed",
"=",
"bedutils",
".",
"intersect_two",
"(",
... | Subset the VCF to a set of pre-calculated smaller regions. | [
"Subset",
"the",
"VCF",
"to",
"a",
"set",
"of",
"pre",
"-",
"calculated",
"smaller",
"regions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L272-L283 | train | 218,794 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | is_info_germline | def is_info_germline(rec):
"""Check if a variant record is germline based on INFO attributes.
Works with VarDict's annotation of STATUS.
"""
if hasattr(rec, "INFO"):
status = rec.INFO.get("STATUS", "").lower()
else:
status = rec.info.get("STATUS", "").lower()
return status == "germline" or status.find("loh") >= 0 | python | def is_info_germline(rec):
"""Check if a variant record is germline based on INFO attributes.
Works with VarDict's annotation of STATUS.
"""
if hasattr(rec, "INFO"):
status = rec.INFO.get("STATUS", "").lower()
else:
status = rec.info.get("STATUS", "").lower()
return status == "germline" or status.find("loh") >= 0 | [
"def",
"is_info_germline",
"(",
"rec",
")",
":",
"if",
"hasattr",
"(",
"rec",
",",
"\"INFO\"",
")",
":",
"status",
"=",
"rec",
".",
"INFO",
".",
"get",
"(",
"\"STATUS\"",
",",
"\"\"",
")",
".",
"lower",
"(",
")",
"else",
":",
"status",
"=",
"rec",
... | Check if a variant record is germline based on INFO attributes.
Works with VarDict's annotation of STATUS. | [
"Check",
"if",
"a",
"variant",
"record",
"is",
"germline",
"based",
"on",
"INFO",
"attributes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L290-L299 | train | 218,795 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | _tumor_normal_stats | def _tumor_normal_stats(rec, somatic_info, vcf_rec):
"""Retrieve depth and frequency of tumor and normal samples.
"""
out = {"normal": {"alt": None, "depth": None, "freq": None},
"tumor": {"alt": 0, "depth": 0, "freq": None}}
if hasattr(vcf_rec, "samples"):
samples = [(s, {}) for s in vcf_rec.samples]
for fkey in ["AD", "AO", "RO", "AF", "DP"]:
try:
for i, v in enumerate(rec.format(fkey)):
samples[i][1][fkey] = v
except KeyError:
pass
# Handle INFO only inputs
elif len(rec.samples) == 0:
samples = [(somatic_info.tumor_name, None)]
else:
samples = rec.samples.items()
for name, sample in samples:
alt, depth, freq = sample_alt_and_depth(rec, sample)
if depth is not None and freq is not None:
if name == somatic_info.normal_name:
key = "normal"
elif name == somatic_info.tumor_name:
key = "tumor"
out[key]["freq"] = freq
out[key]["depth"] = depth
out[key]["alt"] = alt
return out | python | def _tumor_normal_stats(rec, somatic_info, vcf_rec):
"""Retrieve depth and frequency of tumor and normal samples.
"""
out = {"normal": {"alt": None, "depth": None, "freq": None},
"tumor": {"alt": 0, "depth": 0, "freq": None}}
if hasattr(vcf_rec, "samples"):
samples = [(s, {}) for s in vcf_rec.samples]
for fkey in ["AD", "AO", "RO", "AF", "DP"]:
try:
for i, v in enumerate(rec.format(fkey)):
samples[i][1][fkey] = v
except KeyError:
pass
# Handle INFO only inputs
elif len(rec.samples) == 0:
samples = [(somatic_info.tumor_name, None)]
else:
samples = rec.samples.items()
for name, sample in samples:
alt, depth, freq = sample_alt_and_depth(rec, sample)
if depth is not None and freq is not None:
if name == somatic_info.normal_name:
key = "normal"
elif name == somatic_info.tumor_name:
key = "tumor"
out[key]["freq"] = freq
out[key]["depth"] = depth
out[key]["alt"] = alt
return out | [
"def",
"_tumor_normal_stats",
"(",
"rec",
",",
"somatic_info",
",",
"vcf_rec",
")",
":",
"out",
"=",
"{",
"\"normal\"",
":",
"{",
"\"alt\"",
":",
"None",
",",
"\"depth\"",
":",
"None",
",",
"\"freq\"",
":",
"None",
"}",
",",
"\"tumor\"",
":",
"{",
"\"a... | Retrieve depth and frequency of tumor and normal samples. | [
"Retrieve",
"depth",
"and",
"frequency",
"of",
"tumor",
"and",
"normal",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L328-L356 | train | 218,796 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | _is_possible_loh | def _is_possible_loh(rec, vcf_rec, params, somatic_info, use_status=False, max_normal_depth=None):
"""Check if the VCF record is a het in the normal with sufficient support.
Only returns SNPs, since indels tend to have less precise frequency measurements.
"""
if _is_biallelic_snp(rec) and _passes_plus_germline(rec, use_status=use_status):
stats = _tumor_normal_stats(rec, somatic_info, vcf_rec)
depths = [tz.get_in([x, "depth"], stats) for x in ["normal", "tumor"]]
depths = [d for d in depths if d is not None]
normal_freq = tz.get_in(["normal", "freq"], stats)
tumor_freq = tz.get_in(["tumor", "freq"], stats)
if all([d > params["min_depth"] for d in depths]):
if max_normal_depth and tz.get_in(["normal", "depth"], stats, 0) > max_normal_depth:
return None
if normal_freq is not None:
if normal_freq >= params["min_freq"] and normal_freq <= params["max_freq"]:
return stats
elif (tumor_freq >= params["tumor_only"]["min_freq"] and
tumor_freq <= params["tumor_only"]["max_freq"]):
if (vcf_rec and not _has_population_germline(vcf_rec)) or is_population_germline(rec):
return stats | python | def _is_possible_loh(rec, vcf_rec, params, somatic_info, use_status=False, max_normal_depth=None):
"""Check if the VCF record is a het in the normal with sufficient support.
Only returns SNPs, since indels tend to have less precise frequency measurements.
"""
if _is_biallelic_snp(rec) and _passes_plus_germline(rec, use_status=use_status):
stats = _tumor_normal_stats(rec, somatic_info, vcf_rec)
depths = [tz.get_in([x, "depth"], stats) for x in ["normal", "tumor"]]
depths = [d for d in depths if d is not None]
normal_freq = tz.get_in(["normal", "freq"], stats)
tumor_freq = tz.get_in(["tumor", "freq"], stats)
if all([d > params["min_depth"] for d in depths]):
if max_normal_depth and tz.get_in(["normal", "depth"], stats, 0) > max_normal_depth:
return None
if normal_freq is not None:
if normal_freq >= params["min_freq"] and normal_freq <= params["max_freq"]:
return stats
elif (tumor_freq >= params["tumor_only"]["min_freq"] and
tumor_freq <= params["tumor_only"]["max_freq"]):
if (vcf_rec and not _has_population_germline(vcf_rec)) or is_population_germline(rec):
return stats | [
"def",
"_is_possible_loh",
"(",
"rec",
",",
"vcf_rec",
",",
"params",
",",
"somatic_info",
",",
"use_status",
"=",
"False",
",",
"max_normal_depth",
"=",
"None",
")",
":",
"if",
"_is_biallelic_snp",
"(",
"rec",
")",
"and",
"_passes_plus_germline",
"(",
"rec",
... | Check if the VCF record is a het in the normal with sufficient support.
Only returns SNPs, since indels tend to have less precise frequency measurements. | [
"Check",
"if",
"the",
"VCF",
"record",
"is",
"a",
"het",
"in",
"the",
"normal",
"with",
"sufficient",
"support",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L358-L378 | train | 218,797 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | _has_population_germline | def _has_population_germline(rec):
"""Check if header defines population annotated germline samples for tumor only.
"""
for k in population_keys:
if k in rec.header.info:
return True
return False | python | def _has_population_germline(rec):
"""Check if header defines population annotated germline samples for tumor only.
"""
for k in population_keys:
if k in rec.header.info:
return True
return False | [
"def",
"_has_population_germline",
"(",
"rec",
")",
":",
"for",
"k",
"in",
"population_keys",
":",
"if",
"k",
"in",
"rec",
".",
"header",
".",
"info",
":",
"return",
"True",
"return",
"False"
] | Check if header defines population annotated germline samples for tumor only. | [
"Check",
"if",
"header",
"defines",
"population",
"annotated",
"germline",
"samples",
"for",
"tumor",
"only",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L380-L386 | train | 218,798 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/bubbletree.py | is_population_germline | def is_population_germline(rec):
"""Identify a germline calls based on annoations with ExAC or other population databases.
"""
min_count = 50
for k in population_keys:
if k in rec.info:
val = rec.info.get(k)
if "," in val:
val = val.split(",")[0]
if isinstance(val, (list, tuple)):
val = max(val)
if int(val) > min_count:
return True
return False | python | def is_population_germline(rec):
"""Identify a germline calls based on annoations with ExAC or other population databases.
"""
min_count = 50
for k in population_keys:
if k in rec.info:
val = rec.info.get(k)
if "," in val:
val = val.split(",")[0]
if isinstance(val, (list, tuple)):
val = max(val)
if int(val) > min_count:
return True
return False | [
"def",
"is_population_germline",
"(",
"rec",
")",
":",
"min_count",
"=",
"50",
"for",
"k",
"in",
"population_keys",
":",
"if",
"k",
"in",
"rec",
".",
"info",
":",
"val",
"=",
"rec",
".",
"info",
".",
"get",
"(",
"k",
")",
"if",
"\",\"",
"in",
"val"... | Identify a germline calls based on annoations with ExAC or other population databases. | [
"Identify",
"a",
"germline",
"calls",
"based",
"on",
"annoations",
"with",
"ExAC",
"or",
"other",
"population",
"databases",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L388-L401 | train | 218,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.