id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
223,300 | bcbio/bcbio-nextgen | bcbio/variation/sentieon.py | license_export | def license_export(data):
"""Retrieve export statement for sentieon license server.
"""
resources = config_utils.get_resources("sentieon", data["config"])
server = resources.get("keyfile")
if not server:
server = tz.get_in(["resources", "sentieon", "keyfile"], data)
if not server:
raise ValueError("Need to set resources keyfile with URL:port of license server, local license file or "
"environmental variables to export \n"
"http://bcbio-nextgen.readthedocs.io/en/latest/contents/configuration.html#resources\n"
"Configuration: %s" % pprint.pformat(data))
if isinstance(server, six.string_types):
return "export SENTIEON_LICENSE=%s && " % server
else:
assert isinstance(server, dict), server
exports = ""
for key, val in server.items():
exports += "export %s=%s && " % (key.upper(), val)
return exports | python | def license_export(data):
"""Retrieve export statement for sentieon license server.
"""
resources = config_utils.get_resources("sentieon", data["config"])
server = resources.get("keyfile")
if not server:
server = tz.get_in(["resources", "sentieon", "keyfile"], data)
if not server:
raise ValueError("Need to set resources keyfile with URL:port of license server, local license file or "
"environmental variables to export \n"
"http://bcbio-nextgen.readthedocs.io/en/latest/contents/configuration.html#resources\n"
"Configuration: %s" % pprint.pformat(data))
if isinstance(server, six.string_types):
return "export SENTIEON_LICENSE=%s && " % server
else:
assert isinstance(server, dict), server
exports = ""
for key, val in server.items():
exports += "export %s=%s && " % (key.upper(), val)
return exports | [
"def",
"license_export",
"(",
"data",
")",
":",
"resources",
"=",
"config_utils",
".",
"get_resources",
"(",
"\"sentieon\"",
",",
"data",
"[",
"\"config\"",
"]",
")",
"server",
"=",
"resources",
".",
"get",
"(",
"\"keyfile\"",
")",
"if",
"not",
"server",
"... | Retrieve export statement for sentieon license server. | [
"Retrieve",
"export",
"statement",
"for",
"sentieon",
"license",
"server",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/sentieon.py#L25-L44 |
223,301 | bcbio/bcbio-nextgen | bcbio/variation/sentieon.py | _get_interval | def _get_interval(variant_regions, region, out_file, items):
"""Retrieve interval to run analysis in. Handles no targets, BED and regions
region can be a single region or list of multiple regions for multicore calling.
"""
target = shared.subset_variant_regions(variant_regions, region, out_file, items)
if target:
if isinstance(target, six.string_types) and os.path.isfile(target):
return "--interval %s" % target
else:
return "--interval %s" % bamprep.region_to_gatk(target)
else:
return "" | python | def _get_interval(variant_regions, region, out_file, items):
"""Retrieve interval to run analysis in. Handles no targets, BED and regions
region can be a single region or list of multiple regions for multicore calling.
"""
target = shared.subset_variant_regions(variant_regions, region, out_file, items)
if target:
if isinstance(target, six.string_types) and os.path.isfile(target):
return "--interval %s" % target
else:
return "--interval %s" % bamprep.region_to_gatk(target)
else:
return "" | [
"def",
"_get_interval",
"(",
"variant_regions",
",",
"region",
",",
"out_file",
",",
"items",
")",
":",
"target",
"=",
"shared",
".",
"subset_variant_regions",
"(",
"variant_regions",
",",
"region",
",",
"out_file",
",",
"items",
")",
"if",
"target",
":",
"i... | Retrieve interval to run analysis in. Handles no targets, BED and regions
region can be a single region or list of multiple regions for multicore calling. | [
"Retrieve",
"interval",
"to",
"run",
"analysis",
"in",
".",
"Handles",
"no",
"targets",
"BED",
"and",
"regions"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/sentieon.py#L46-L58 |
223,302 | bcbio/bcbio-nextgen | bcbio/variation/sentieon.py | run_tnscope | def run_tnscope(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Call variants with Sentieon's TNscope somatic caller.
"""
if out_file is None:
out_file = "%s-variants.vcf.gz" % utils.splitext_plus(align_bams[0])[0]
if not utils.file_exists(out_file):
variant_regions = bedutils.population_variant_regions(items, merged=True)
interval = _get_interval(variant_regions, region, out_file, items)
with file_transaction(items[0], out_file) as tx_out_file:
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and paired.normal_bam, "Require normal BAM for Sentieon TNscope"
dbsnp = "--dbsnp %s" % (assoc_files.get("dbsnp")) if "dbsnp" in assoc_files else ""
license = license_export(items[0])
cores = dd.get_num_cores(items[0])
cmd = ("{license}sentieon driver -t {cores} -r {ref_file} "
"-i {paired.tumor_bam} -i {paired.normal_bam} {interval} "
"--algo TNscope "
"--tumor_sample {paired.tumor_name} --normal_sample {paired.normal_name} "
"{dbsnp} {tx_out_file}")
do.run(cmd.format(**locals()), "Sentieon TNscope")
return out_file | python | def run_tnscope(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Call variants with Sentieon's TNscope somatic caller.
"""
if out_file is None:
out_file = "%s-variants.vcf.gz" % utils.splitext_plus(align_bams[0])[0]
if not utils.file_exists(out_file):
variant_regions = bedutils.population_variant_regions(items, merged=True)
interval = _get_interval(variant_regions, region, out_file, items)
with file_transaction(items[0], out_file) as tx_out_file:
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and paired.normal_bam, "Require normal BAM for Sentieon TNscope"
dbsnp = "--dbsnp %s" % (assoc_files.get("dbsnp")) if "dbsnp" in assoc_files else ""
license = license_export(items[0])
cores = dd.get_num_cores(items[0])
cmd = ("{license}sentieon driver -t {cores} -r {ref_file} "
"-i {paired.tumor_bam} -i {paired.normal_bam} {interval} "
"--algo TNscope "
"--tumor_sample {paired.tumor_name} --normal_sample {paired.normal_name} "
"{dbsnp} {tx_out_file}")
do.run(cmd.format(**locals()), "Sentieon TNscope")
return out_file | [
"def",
"run_tnscope",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"if",
"out_file",
"is",
"None",
":",
"out_file",
"=",
"\"%s-variants.vcf.gz\"",
"%",
"utils",
".... | Call variants with Sentieon's TNscope somatic caller. | [
"Call",
"variants",
"with",
"Sentieon",
"s",
"TNscope",
"somatic",
"caller",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/sentieon.py#L60-L81 |
223,303 | bcbio/bcbio-nextgen | bcbio/variation/sentieon.py | run_gvcftyper | def run_gvcftyper(vrn_files, out_file, region, data):
"""Produce joint called variants from input gVCF files.
"""
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
license = license_export(data)
ref_file = dd.get_ref_file(data)
input_files = " ".join(vrn_files)
region = bamprep.region_to_gatk(region)
cmd = ("{license}sentieon driver -r {ref_file} --interval {region} "
"--algo GVCFtyper {tx_out_file} {input_files}")
do.run(cmd.format(**locals()), "Sentieon GVCFtyper")
return out_file | python | def run_gvcftyper(vrn_files, out_file, region, data):
"""Produce joint called variants from input gVCF files.
"""
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
license = license_export(data)
ref_file = dd.get_ref_file(data)
input_files = " ".join(vrn_files)
region = bamprep.region_to_gatk(region)
cmd = ("{license}sentieon driver -r {ref_file} --interval {region} "
"--algo GVCFtyper {tx_out_file} {input_files}")
do.run(cmd.format(**locals()), "Sentieon GVCFtyper")
return out_file | [
"def",
"run_gvcftyper",
"(",
"vrn_files",
",",
"out_file",
",",
"region",
",",
"data",
")",
":",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
... | Produce joint called variants from input gVCF files. | [
"Produce",
"joint",
"called",
"variants",
"from",
"input",
"gVCF",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/sentieon.py#L137-L149 |
223,304 | bcbio/bcbio-nextgen | bcbio/variation/sentieon.py | bqsr_table | def bqsr_table(data):
"""Generate recalibration tables as inputs to BQSR.
"""
in_file = dd.get_align_bam(data)
out_file = "%s-recal-table.txt" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
assoc_files = dd.get_variation_resources(data)
known = "-k %s" % (assoc_files.get("dbsnp")) if "dbsnp" in assoc_files else ""
license = license_export(data)
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
cmd = ("{license}sentieon driver -t {cores} -r {ref_file} "
"-i {in_file} --algo QualCal {known} {tx_out_file}")
do.run(cmd.format(**locals()), "Sentieon QualCal generate table")
return out_file | python | def bqsr_table(data):
"""Generate recalibration tables as inputs to BQSR.
"""
in_file = dd.get_align_bam(data)
out_file = "%s-recal-table.txt" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
assoc_files = dd.get_variation_resources(data)
known = "-k %s" % (assoc_files.get("dbsnp")) if "dbsnp" in assoc_files else ""
license = license_export(data)
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
cmd = ("{license}sentieon driver -t {cores} -r {ref_file} "
"-i {in_file} --algo QualCal {known} {tx_out_file}")
do.run(cmd.format(**locals()), "Sentieon QualCal generate table")
return out_file | [
"def",
"bqsr_table",
"(",
"data",
")",
":",
"in_file",
"=",
"dd",
".",
"get_align_bam",
"(",
"data",
")",
"out_file",
"=",
"\"%s-recal-table.txt\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
".",
"file_... | Generate recalibration tables as inputs to BQSR. | [
"Generate",
"recalibration",
"tables",
"as",
"inputs",
"to",
"BQSR",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/sentieon.py#L151-L166 |
223,305 | bcbio/bcbio-nextgen | bcbio/ngsalign/rtg.py | to_sdf | def to_sdf(files, data):
"""Convert a fastq or BAM input into a SDF indexed file.
"""
# BAM
if len(files) == 1 and files[0].endswith(".bam"):
qual = []
format = ["-f", "sam-pe" if bam.is_paired(files[0]) else "sam-se"]
inputs = [files[0]]
# fastq
else:
qual = ["-q", "illumina" if dd.get_quality_format(data).lower() == "illumina" else "sanger"]
format = ["-f", "fastq"]
if len(files) == 2:
inputs = ["-l", files[0], "-r", files[1]]
else:
assert len(files) == 1
inputs = [files[0]]
work_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "align_prep"))
out_file = os.path.join(work_dir,
"%s.sdf" % utils.splitext_plus(os.path.basename(os.path.commonprefix(files)))[0])
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = _rtg_cmd(["rtg", "format", "-o", tx_out_file] + format + qual + inputs)
do.run(cmd, "Format inputs to indexed SDF")
return out_file | python | def to_sdf(files, data):
"""Convert a fastq or BAM input into a SDF indexed file.
"""
# BAM
if len(files) == 1 and files[0].endswith(".bam"):
qual = []
format = ["-f", "sam-pe" if bam.is_paired(files[0]) else "sam-se"]
inputs = [files[0]]
# fastq
else:
qual = ["-q", "illumina" if dd.get_quality_format(data).lower() == "illumina" else "sanger"]
format = ["-f", "fastq"]
if len(files) == 2:
inputs = ["-l", files[0], "-r", files[1]]
else:
assert len(files) == 1
inputs = [files[0]]
work_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "align_prep"))
out_file = os.path.join(work_dir,
"%s.sdf" % utils.splitext_plus(os.path.basename(os.path.commonprefix(files)))[0])
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = _rtg_cmd(["rtg", "format", "-o", tx_out_file] + format + qual + inputs)
do.run(cmd, "Format inputs to indexed SDF")
return out_file | [
"def",
"to_sdf",
"(",
"files",
",",
"data",
")",
":",
"# BAM",
"if",
"len",
"(",
"files",
")",
"==",
"1",
"and",
"files",
"[",
"0",
"]",
".",
"endswith",
"(",
"\".bam\"",
")",
":",
"qual",
"=",
"[",
"]",
"format",
"=",
"[",
"\"-f\"",
",",
"\"sa... | Convert a fastq or BAM input into a SDF indexed file. | [
"Convert",
"a",
"fastq",
"or",
"BAM",
"input",
"into",
"a",
"SDF",
"indexed",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/rtg.py#L16-L40 |
223,306 | bcbio/bcbio-nextgen | bcbio/ngsalign/rtg.py | to_fastq_apipe_cl | def to_fastq_apipe_cl(sdf_file, start=None, end=None):
"""Return a command lines to provide streaming fastq input.
For paired end, returns a forward and reverse command line. For
single end returns a single command line and None for the pair.
"""
cmd = ["rtg", "sdf2fastq", "--no-gzip", "-o", "-"]
if start is not None:
cmd += ["--start-id=%s" % start]
if end is not None:
cmd += ["--end-id=%s" % end]
if is_paired(sdf_file):
out = []
for ext in ["left", "right"]:
out.append("<(%s)" % _rtg_cmd(cmd + ["-i", os.path.join(sdf_file, ext)]))
return out
else:
cmd += ["-i", sdf_file]
return ["<(%s)" % _rtg_cmd(cmd), None] | python | def to_fastq_apipe_cl(sdf_file, start=None, end=None):
"""Return a command lines to provide streaming fastq input.
For paired end, returns a forward and reverse command line. For
single end returns a single command line and None for the pair.
"""
cmd = ["rtg", "sdf2fastq", "--no-gzip", "-o", "-"]
if start is not None:
cmd += ["--start-id=%s" % start]
if end is not None:
cmd += ["--end-id=%s" % end]
if is_paired(sdf_file):
out = []
for ext in ["left", "right"]:
out.append("<(%s)" % _rtg_cmd(cmd + ["-i", os.path.join(sdf_file, ext)]))
return out
else:
cmd += ["-i", sdf_file]
return ["<(%s)" % _rtg_cmd(cmd), None] | [
"def",
"to_fastq_apipe_cl",
"(",
"sdf_file",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"\"rtg\"",
",",
"\"sdf2fastq\"",
",",
"\"--no-gzip\"",
",",
"\"-o\"",
",",
"\"-\"",
"]",
"if",
"start",
"is",
"not",
"None",
":"... | Return a command lines to provide streaming fastq input.
For paired end, returns a forward and reverse command line. For
single end returns a single command line and None for the pair. | [
"Return",
"a",
"command",
"lines",
"to",
"provide",
"streaming",
"fastq",
"input",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/rtg.py#L82-L100 |
223,307 | bcbio/bcbio-nextgen | bcbio/pipeline/tools.py | get_tabix_cmd | def get_tabix_cmd(config):
"""Retrieve tabix command, handling new bcftools tabix and older tabix.
"""
try:
bcftools = config_utils.get_program("bcftools", config)
# bcftools has terrible error codes and stderr output, swallow those.
bcftools_tabix = subprocess.check_output("{bcftools} 2>&1; echo $?".format(**locals()),
shell=True).decode().find("tabix") >= 0
except config_utils.CmdNotFound:
bcftools_tabix = False
if bcftools_tabix:
return "{0} tabix".format(bcftools)
else:
tabix = config_utils.get_program("tabix", config)
return tabix | python | def get_tabix_cmd(config):
"""Retrieve tabix command, handling new bcftools tabix and older tabix.
"""
try:
bcftools = config_utils.get_program("bcftools", config)
# bcftools has terrible error codes and stderr output, swallow those.
bcftools_tabix = subprocess.check_output("{bcftools} 2>&1; echo $?".format(**locals()),
shell=True).decode().find("tabix") >= 0
except config_utils.CmdNotFound:
bcftools_tabix = False
if bcftools_tabix:
return "{0} tabix".format(bcftools)
else:
tabix = config_utils.get_program("tabix", config)
return tabix | [
"def",
"get_tabix_cmd",
"(",
"config",
")",
":",
"try",
":",
"bcftools",
"=",
"config_utils",
".",
"get_program",
"(",
"\"bcftools\"",
",",
"config",
")",
"# bcftools has terrible error codes and stderr output, swallow those.",
"bcftools_tabix",
"=",
"subprocess",
".",
... | Retrieve tabix command, handling new bcftools tabix and older tabix. | [
"Retrieve",
"tabix",
"command",
"handling",
"new",
"bcftools",
"tabix",
"and",
"older",
"tabix",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/tools.py#L10-L24 |
223,308 | bcbio/bcbio-nextgen | bcbio/pipeline/tools.py | get_bgzip_cmd | def get_bgzip_cmd(config, is_retry=False):
"""Retrieve command to use for bgzip, trying to use bgzip parallel threads.
By default, parallel bgzip is enabled in bcbio. If it causes problems
please report them. You can turn parallel bgzip off with `tools_off: [pbgzip]`
"""
num_cores = tz.get_in(["algorithm", "num_cores"], config, 1)
cmd = config_utils.get_program("bgzip", config)
if (not is_retry and num_cores > 1 and
"pbgzip" not in dd.get_tools_off({"config": config})):
cmd += " --threads %s" % num_cores
return cmd | python | def get_bgzip_cmd(config, is_retry=False):
"""Retrieve command to use for bgzip, trying to use bgzip parallel threads.
By default, parallel bgzip is enabled in bcbio. If it causes problems
please report them. You can turn parallel bgzip off with `tools_off: [pbgzip]`
"""
num_cores = tz.get_in(["algorithm", "num_cores"], config, 1)
cmd = config_utils.get_program("bgzip", config)
if (not is_retry and num_cores > 1 and
"pbgzip" not in dd.get_tools_off({"config": config})):
cmd += " --threads %s" % num_cores
return cmd | [
"def",
"get_bgzip_cmd",
"(",
"config",
",",
"is_retry",
"=",
"False",
")",
":",
"num_cores",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"algorithm\"",
",",
"\"num_cores\"",
"]",
",",
"config",
",",
"1",
")",
"cmd",
"=",
"config_utils",
".",
"get_program",
"("... | Retrieve command to use for bgzip, trying to use bgzip parallel threads.
By default, parallel bgzip is enabled in bcbio. If it causes problems
please report them. You can turn parallel bgzip off with `tools_off: [pbgzip]` | [
"Retrieve",
"command",
"to",
"use",
"for",
"bgzip",
"trying",
"to",
"use",
"bgzip",
"parallel",
"threads",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/tools.py#L26-L37 |
223,309 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | is_empty | def is_empty(bam_file):
"""Determine if a BAM file is empty
"""
bam_file = objectstore.cl_input(bam_file)
cmd = ("set -o pipefail; "
"samtools view {bam_file} | head -1 | wc -l")
p = subprocess.Popen(cmd.format(**locals()), shell=True,
executable=do.find_bash(),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL))
stdout, stderr = p.communicate()
stdout = stdout.decode()
stderr = stderr.decode()
if ((p.returncode == 0 or p.returncode == 141) and
(stderr == "" or (stderr.startswith("gof3r") and stderr.endswith("broken pipe")))):
return int(stdout) == 0
else:
raise ValueError("Failed to check empty status of BAM file: %s" % str(stderr)) | python | def is_empty(bam_file):
"""Determine if a BAM file is empty
"""
bam_file = objectstore.cl_input(bam_file)
cmd = ("set -o pipefail; "
"samtools view {bam_file} | head -1 | wc -l")
p = subprocess.Popen(cmd.format(**locals()), shell=True,
executable=do.find_bash(),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL))
stdout, stderr = p.communicate()
stdout = stdout.decode()
stderr = stderr.decode()
if ((p.returncode == 0 or p.returncode == 141) and
(stderr == "" or (stderr.startswith("gof3r") and stderr.endswith("broken pipe")))):
return int(stdout) == 0
else:
raise ValueError("Failed to check empty status of BAM file: %s" % str(stderr)) | [
"def",
"is_empty",
"(",
"bam_file",
")",
":",
"bam_file",
"=",
"objectstore",
".",
"cl_input",
"(",
"bam_file",
")",
"cmd",
"=",
"(",
"\"set -o pipefail; \"",
"\"samtools view {bam_file} | head -1 | wc -l\"",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
... | Determine if a BAM file is empty | [
"Determine",
"if",
"a",
"BAM",
"file",
"is",
"empty"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L24-L41 |
223,310 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | fake_index | def fake_index(in_bam, data):
"""Create a fake index file for namesorted BAMs. bais require by CWL for consistency.
"""
index_file = "%s.bai" % in_bam
if not utils.file_exists(index_file):
with file_transaction(data, index_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
out_handle.write("name sorted -- no index")
return index_file | python | def fake_index(in_bam, data):
"""Create a fake index file for namesorted BAMs. bais require by CWL for consistency.
"""
index_file = "%s.bai" % in_bam
if not utils.file_exists(index_file):
with file_transaction(data, index_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
out_handle.write("name sorted -- no index")
return index_file | [
"def",
"fake_index",
"(",
"in_bam",
",",
"data",
")",
":",
"index_file",
"=",
"\"%s.bai\"",
"%",
"in_bam",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"index_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"index_file",
")",
"as",
"tx_out... | Create a fake index file for namesorted BAMs. bais require by CWL for consistency. | [
"Create",
"a",
"fake",
"index",
"file",
"for",
"namesorted",
"BAMs",
".",
"bais",
"require",
"by",
"CWL",
"for",
"consistency",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L67-L75 |
223,311 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | index | def index(in_bam, config, check_timestamp=True):
"""Index a BAM file, skipping if index present.
Centralizes BAM indexing providing ability to switch indexing approaches.
"""
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
index_file = "%s.bai" % in_bam
alt_index_file = "%s.bai" % os.path.splitext(in_bam)[0]
if check_timestamp:
bai_exists = utils.file_uptodate(index_file, in_bam) or utils.file_uptodate(alt_index_file, in_bam)
else:
bai_exists = utils.file_exists(index_file) or utils.file_exists(alt_index_file)
if not bai_exists:
# Remove old index files and re-run to prevent linking into tx directory
for fname in [index_file, alt_index_file]:
utils.remove_safe(fname)
samtools = config_utils.get_program("samtools", config)
num_cores = config["algorithm"].get("num_cores", 1)
with file_transaction(config, index_file) as tx_index_file:
cmd = "{samtools} index -@ {num_cores} {in_bam} {tx_index_file}"
do.run(cmd.format(**locals()), "Index BAM file: %s" % os.path.basename(in_bam))
return index_file if utils.file_exists(index_file) else alt_index_file | python | def index(in_bam, config, check_timestamp=True):
"""Index a BAM file, skipping if index present.
Centralizes BAM indexing providing ability to switch indexing approaches.
"""
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
index_file = "%s.bai" % in_bam
alt_index_file = "%s.bai" % os.path.splitext(in_bam)[0]
if check_timestamp:
bai_exists = utils.file_uptodate(index_file, in_bam) or utils.file_uptodate(alt_index_file, in_bam)
else:
bai_exists = utils.file_exists(index_file) or utils.file_exists(alt_index_file)
if not bai_exists:
# Remove old index files and re-run to prevent linking into tx directory
for fname in [index_file, alt_index_file]:
utils.remove_safe(fname)
samtools = config_utils.get_program("samtools", config)
num_cores = config["algorithm"].get("num_cores", 1)
with file_transaction(config, index_file) as tx_index_file:
cmd = "{samtools} index -@ {num_cores} {in_bam} {tx_index_file}"
do.run(cmd.format(**locals()), "Index BAM file: %s" % os.path.basename(in_bam))
return index_file if utils.file_exists(index_file) else alt_index_file | [
"def",
"index",
"(",
"in_bam",
",",
"config",
",",
"check_timestamp",
"=",
"True",
")",
":",
"assert",
"is_bam",
"(",
"in_bam",
")",
",",
"\"%s in not a BAM file\"",
"%",
"in_bam",
"index_file",
"=",
"\"%s.bai\"",
"%",
"in_bam",
"alt_index_file",
"=",
"\"%s.ba... | Index a BAM file, skipping if index present.
Centralizes BAM indexing providing ability to switch indexing approaches. | [
"Index",
"a",
"BAM",
"file",
"skipping",
"if",
"index",
"present",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L77-L98 |
223,312 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | remove | def remove(in_bam):
"""
remove bam file and the index if exists
"""
if utils.file_exists(in_bam):
utils.remove_safe(in_bam)
if utils.file_exists(in_bam + ".bai"):
utils.remove_safe(in_bam + ".bai") | python | def remove(in_bam):
"""
remove bam file and the index if exists
"""
if utils.file_exists(in_bam):
utils.remove_safe(in_bam)
if utils.file_exists(in_bam + ".bai"):
utils.remove_safe(in_bam + ".bai") | [
"def",
"remove",
"(",
"in_bam",
")",
":",
"if",
"utils",
".",
"file_exists",
"(",
"in_bam",
")",
":",
"utils",
".",
"remove_safe",
"(",
"in_bam",
")",
"if",
"utils",
".",
"file_exists",
"(",
"in_bam",
"+",
"\".bai\"",
")",
":",
"utils",
".",
"remove_sa... | remove bam file and the index if exists | [
"remove",
"bam",
"file",
"and",
"the",
"index",
"if",
"exists"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L100-L107 |
223,313 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | idxstats | def idxstats(in_bam, data):
"""Return BAM index stats for the given file, using samtools idxstats.
"""
index(in_bam, data["config"], check_timestamp=False)
AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "aligned", "unaligned"])
samtools = config_utils.get_program("samtools", data["config"])
idxstats_out = subprocess.check_output([samtools, "idxstats", in_bam]).decode()
out = []
for line in idxstats_out.split("\n"):
if line.strip():
contig, length, aligned, unaligned = line.split("\t")
out.append(AlignInfo(contig, int(length), int(aligned), int(unaligned)))
return out | python | def idxstats(in_bam, data):
"""Return BAM index stats for the given file, using samtools idxstats.
"""
index(in_bam, data["config"], check_timestamp=False)
AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "aligned", "unaligned"])
samtools = config_utils.get_program("samtools", data["config"])
idxstats_out = subprocess.check_output([samtools, "idxstats", in_bam]).decode()
out = []
for line in idxstats_out.split("\n"):
if line.strip():
contig, length, aligned, unaligned = line.split("\t")
out.append(AlignInfo(contig, int(length), int(aligned), int(unaligned)))
return out | [
"def",
"idxstats",
"(",
"in_bam",
",",
"data",
")",
":",
"index",
"(",
"in_bam",
",",
"data",
"[",
"\"config\"",
"]",
",",
"check_timestamp",
"=",
"False",
")",
"AlignInfo",
"=",
"collections",
".",
"namedtuple",
"(",
"\"AlignInfo\"",
",",
"[",
"\"contig\"... | Return BAM index stats for the given file, using samtools idxstats. | [
"Return",
"BAM",
"index",
"stats",
"for",
"the",
"given",
"file",
"using",
"samtools",
"idxstats",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L109-L121 |
223,314 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | fai_from_bam | def fai_from_bam(ref_file, bam_file, out_file, data):
"""Create a fai index with only contigs in the input BAM file.
"""
contigs = set([x.contig for x in idxstats(bam_file, data)])
if not utils.file_uptodate(out_file, bam_file):
with open(ref.fasta_idx(ref_file, data["config"])) as in_handle:
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for line in (l for l in in_handle if l.strip()):
if line.split()[0] in contigs:
out_handle.write(line)
return out_file | python | def fai_from_bam(ref_file, bam_file, out_file, data):
"""Create a fai index with only contigs in the input BAM file.
"""
contigs = set([x.contig for x in idxstats(bam_file, data)])
if not utils.file_uptodate(out_file, bam_file):
with open(ref.fasta_idx(ref_file, data["config"])) as in_handle:
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for line in (l for l in in_handle if l.strip()):
if line.split()[0] in contigs:
out_handle.write(line)
return out_file | [
"def",
"fai_from_bam",
"(",
"ref_file",
",",
"bam_file",
",",
"out_file",
",",
"data",
")",
":",
"contigs",
"=",
"set",
"(",
"[",
"x",
".",
"contig",
"for",
"x",
"in",
"idxstats",
"(",
"bam_file",
",",
"data",
")",
"]",
")",
"if",
"not",
"utils",
"... | Create a fai index with only contigs in the input BAM file. | [
"Create",
"a",
"fai",
"index",
"with",
"only",
"contigs",
"in",
"the",
"input",
"BAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L123-L134 |
223,315 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | ref_file_from_bam | def ref_file_from_bam(bam_file, data):
"""Subset a fasta input file to only a fraction of input contigs.
"""
new_ref = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(data), "inputs", "ref")),
"%s-subset.fa" % dd.get_genome_build(data))
if not utils.file_exists(new_ref):
with file_transaction(data, new_ref) as tx_out_file:
contig_file = "%s-contigs.txt" % utils.splitext_plus(new_ref)[0]
with open(contig_file, "w") as out_handle:
for contig in [x.contig for x in idxstats(bam_file, data) if x.contig != "*"]:
out_handle.write("%s\n" % contig)
cmd = "seqtk subseq -l 100 %s %s > %s" % (dd.get_ref_file(data), contig_file, tx_out_file)
do.run(cmd, "Subset %s to BAM file contigs" % dd.get_genome_build(data))
ref.fasta_idx(new_ref, data["config"])
runner = broad.runner_from_path("picard", data["config"])
runner.run_fn("picard_index_ref", new_ref)
return {"base": new_ref} | python | def ref_file_from_bam(bam_file, data):
"""Subset a fasta input file to only a fraction of input contigs.
"""
new_ref = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(data), "inputs", "ref")),
"%s-subset.fa" % dd.get_genome_build(data))
if not utils.file_exists(new_ref):
with file_transaction(data, new_ref) as tx_out_file:
contig_file = "%s-contigs.txt" % utils.splitext_plus(new_ref)[0]
with open(contig_file, "w") as out_handle:
for contig in [x.contig for x in idxstats(bam_file, data) if x.contig != "*"]:
out_handle.write("%s\n" % contig)
cmd = "seqtk subseq -l 100 %s %s > %s" % (dd.get_ref_file(data), contig_file, tx_out_file)
do.run(cmd, "Subset %s to BAM file contigs" % dd.get_genome_build(data))
ref.fasta_idx(new_ref, data["config"])
runner = broad.runner_from_path("picard", data["config"])
runner.run_fn("picard_index_ref", new_ref)
return {"base": new_ref} | [
"def",
"ref_file_from_bam",
"(",
"bam_file",
",",
"data",
")",
":",
"new_ref",
"=",
"os",
".",
"path",
".",
"join",
"(",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",
",",
"\"inpu... | Subset a fasta input file to only a fraction of input contigs. | [
"Subset",
"a",
"fasta",
"input",
"file",
"to",
"only",
"a",
"fraction",
"of",
"input",
"contigs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L136-L152 |
223,316 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | get_downsample_pct | def get_downsample_pct(in_bam, target_counts, data):
"""Retrieve percentage of file to downsample to get to target counts.
Avoids minimal downsample which is not especially useful for
improving QC times; 90& or more of reads.
"""
total = sum(x.aligned for x in idxstats(in_bam, data))
with pysam.Samfile(in_bam, "rb") as work_bam:
n_rgs = max(1, len(work_bam.header.get("RG", [])))
rg_target = n_rgs * target_counts
if total > rg_target:
pct = float(rg_target) / float(total)
if pct < 0.9:
return pct | python | def get_downsample_pct(in_bam, target_counts, data):
"""Retrieve percentage of file to downsample to get to target counts.
Avoids minimal downsample which is not especially useful for
improving QC times; 90& or more of reads.
"""
total = sum(x.aligned for x in idxstats(in_bam, data))
with pysam.Samfile(in_bam, "rb") as work_bam:
n_rgs = max(1, len(work_bam.header.get("RG", [])))
rg_target = n_rgs * target_counts
if total > rg_target:
pct = float(rg_target) / float(total)
if pct < 0.9:
return pct | [
"def",
"get_downsample_pct",
"(",
"in_bam",
",",
"target_counts",
",",
"data",
")",
":",
"total",
"=",
"sum",
"(",
"x",
".",
"aligned",
"for",
"x",
"in",
"idxstats",
"(",
"in_bam",
",",
"data",
")",
")",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
... | Retrieve percentage of file to downsample to get to target counts.
Avoids minimal downsample which is not especially useful for
improving QC times; 90& or more of reads. | [
"Retrieve",
"percentage",
"of",
"file",
"to",
"downsample",
"to",
"get",
"to",
"target",
"counts",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L154-L167 |
223,317 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | downsample | def downsample(in_bam, data, target_counts, work_dir=None):
"""Downsample a BAM file to the specified number of target counts.
"""
index(in_bam, data["config"], check_timestamp=False)
ds_pct = get_downsample_pct(in_bam, target_counts, data)
if ds_pct:
out_file = "%s-downsample%s" % os.path.splitext(in_bam)
if work_dir:
out_file = os.path.join(work_dir, os.path.basename(out_file))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
samtools = config_utils.get_program("samtools", data["config"])
num_cores = dd.get_num_cores(data)
ds_pct = "42." + "{ds_pct:.3}".format(ds_pct=ds_pct).replace("0.", "")
cmd = ("{samtools} view -O BAM -@ {num_cores} -o {tx_out_file} "
"-s {ds_pct} {in_bam}")
do.run(cmd.format(**locals()), "Downsample BAM file: %s" % os.path.basename(in_bam))
return out_file | python | def downsample(in_bam, data, target_counts, work_dir=None):
"""Downsample a BAM file to the specified number of target counts.
"""
index(in_bam, data["config"], check_timestamp=False)
ds_pct = get_downsample_pct(in_bam, target_counts, data)
if ds_pct:
out_file = "%s-downsample%s" % os.path.splitext(in_bam)
if work_dir:
out_file = os.path.join(work_dir, os.path.basename(out_file))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
samtools = config_utils.get_program("samtools", data["config"])
num_cores = dd.get_num_cores(data)
ds_pct = "42." + "{ds_pct:.3}".format(ds_pct=ds_pct).replace("0.", "")
cmd = ("{samtools} view -O BAM -@ {num_cores} -o {tx_out_file} "
"-s {ds_pct} {in_bam}")
do.run(cmd.format(**locals()), "Downsample BAM file: %s" % os.path.basename(in_bam))
return out_file | [
"def",
"downsample",
"(",
"in_bam",
",",
"data",
",",
"target_counts",
",",
"work_dir",
"=",
"None",
")",
":",
"index",
"(",
"in_bam",
",",
"data",
"[",
"\"config\"",
"]",
",",
"check_timestamp",
"=",
"False",
")",
"ds_pct",
"=",
"get_downsample_pct",
"(",... | Downsample a BAM file to the specified number of target counts. | [
"Downsample",
"a",
"BAM",
"file",
"to",
"the",
"specified",
"number",
"of",
"target",
"counts",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L177-L194 |
223,318 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | get_maxcov_downsample_cl | def get_maxcov_downsample_cl(data, in_pipe=None):
"""Retrieve command line for max coverage downsampling, fitting into bamsormadup output.
"""
max_cov = _get_maxcov_downsample(data) if dd.get_aligner(data) not in ["snap"] else None
if max_cov:
if in_pipe == "bamsormadup":
prefix = "level=0"
elif in_pipe == "samtools":
prefix = "-l 0"
else:
prefix = ""
# Swap over to multiple cores until after testing
#core_arg = "-t %s" % dd.get_num_cores(data)
core_arg = ""
return ("%s | variant - -b %s --mark-as-qc-fail --max-coverage %s"
% (prefix, core_arg, max_cov))
else:
if in_pipe == "bamsormadup":
prefix = "indexfilename={tx_out_file}.bai"
else:
prefix = ""
return prefix | python | def get_maxcov_downsample_cl(data, in_pipe=None):
"""Retrieve command line for max coverage downsampling, fitting into bamsormadup output.
"""
max_cov = _get_maxcov_downsample(data) if dd.get_aligner(data) not in ["snap"] else None
if max_cov:
if in_pipe == "bamsormadup":
prefix = "level=0"
elif in_pipe == "samtools":
prefix = "-l 0"
else:
prefix = ""
# Swap over to multiple cores until after testing
#core_arg = "-t %s" % dd.get_num_cores(data)
core_arg = ""
return ("%s | variant - -b %s --mark-as-qc-fail --max-coverage %s"
% (prefix, core_arg, max_cov))
else:
if in_pipe == "bamsormadup":
prefix = "indexfilename={tx_out_file}.bai"
else:
prefix = ""
return prefix | [
"def",
"get_maxcov_downsample_cl",
"(",
"data",
",",
"in_pipe",
"=",
"None",
")",
":",
"max_cov",
"=",
"_get_maxcov_downsample",
"(",
"data",
")",
"if",
"dd",
".",
"get_aligner",
"(",
"data",
")",
"not",
"in",
"[",
"\"snap\"",
"]",
"else",
"None",
"if",
... | Retrieve command line for max coverage downsampling, fitting into bamsormadup output. | [
"Retrieve",
"command",
"line",
"for",
"max",
"coverage",
"downsampling",
"fitting",
"into",
"bamsormadup",
"output",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L196-L217 |
223,319 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | _get_maxcov_downsample | def _get_maxcov_downsample(data):
"""Calculate maximum coverage downsampling for whole genome samples.
Returns None if we're not doing downsampling.
"""
from bcbio.bam import ref
from bcbio.ngsalign import alignprep, bwa
from bcbio.variation import coverage
fastq_file = data["files"][0]
params = alignprep.get_downsample_params(data)
if params:
num_reads = alignprep.total_reads_from_grabix(fastq_file)
if num_reads:
vrs = dd.get_variant_regions_merged(data)
total_size = sum([c.size for c in ref.file_contigs(dd.get_ref_file(data), data["config"])])
if vrs:
callable_size = pybedtools.BedTool(vrs).total_coverage()
genome_cov_pct = callable_size / float(total_size)
else:
callable_size = total_size
genome_cov_pct = 1.0
if (genome_cov_pct > coverage.GENOME_COV_THRESH
and dd.get_coverage_interval(data) in ["genome", None, False]):
total_counts, total_sizes = 0, 0
for count, size in bwa.fastq_size_output(fastq_file, 5000):
total_counts += int(count)
total_sizes += (int(size) * int(count))
read_size = float(total_sizes) / float(total_counts)
avg_cov = float(num_reads * read_size) / callable_size
if avg_cov >= params["min_coverage_for_downsampling"]:
return int(avg_cov * params["maxcov_downsample_multiplier"])
return None | python | def _get_maxcov_downsample(data):
"""Calculate maximum coverage downsampling for whole genome samples.
Returns None if we're not doing downsampling.
"""
from bcbio.bam import ref
from bcbio.ngsalign import alignprep, bwa
from bcbio.variation import coverage
fastq_file = data["files"][0]
params = alignprep.get_downsample_params(data)
if params:
num_reads = alignprep.total_reads_from_grabix(fastq_file)
if num_reads:
vrs = dd.get_variant_regions_merged(data)
total_size = sum([c.size for c in ref.file_contigs(dd.get_ref_file(data), data["config"])])
if vrs:
callable_size = pybedtools.BedTool(vrs).total_coverage()
genome_cov_pct = callable_size / float(total_size)
else:
callable_size = total_size
genome_cov_pct = 1.0
if (genome_cov_pct > coverage.GENOME_COV_THRESH
and dd.get_coverage_interval(data) in ["genome", None, False]):
total_counts, total_sizes = 0, 0
for count, size in bwa.fastq_size_output(fastq_file, 5000):
total_counts += int(count)
total_sizes += (int(size) * int(count))
read_size = float(total_sizes) / float(total_counts)
avg_cov = float(num_reads * read_size) / callable_size
if avg_cov >= params["min_coverage_for_downsampling"]:
return int(avg_cov * params["maxcov_downsample_multiplier"])
return None | [
"def",
"_get_maxcov_downsample",
"(",
"data",
")",
":",
"from",
"bcbio",
".",
"bam",
"import",
"ref",
"from",
"bcbio",
".",
"ngsalign",
"import",
"alignprep",
",",
"bwa",
"from",
"bcbio",
".",
"variation",
"import",
"coverage",
"fastq_file",
"=",
"data",
"["... | Calculate maximum coverage downsampling for whole genome samples.
Returns None if we're not doing downsampling. | [
"Calculate",
"maximum",
"coverage",
"downsampling",
"for",
"whole",
"genome",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L219-L250 |
223,320 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | check_header | def check_header(in_bam, rgnames, ref_file, config):
"""Ensure passed in BAM header matches reference file and read groups names.
"""
_check_bam_contigs(in_bam, ref_file, config)
_check_sample(in_bam, rgnames) | python | def check_header(in_bam, rgnames, ref_file, config):
"""Ensure passed in BAM header matches reference file and read groups names.
"""
_check_bam_contigs(in_bam, ref_file, config)
_check_sample(in_bam, rgnames) | [
"def",
"check_header",
"(",
"in_bam",
",",
"rgnames",
",",
"ref_file",
",",
"config",
")",
":",
"_check_bam_contigs",
"(",
"in_bam",
",",
"ref_file",
",",
"config",
")",
"_check_sample",
"(",
"in_bam",
",",
"rgnames",
")"
] | Ensure passed in BAM header matches reference file and read groups names. | [
"Ensure",
"passed",
"in",
"BAM",
"header",
"matches",
"reference",
"file",
"and",
"read",
"groups",
"names",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L253-L257 |
223,321 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | _check_sample | def _check_sample(in_bam, rgnames):
"""Ensure input sample name matches expected run group names.
"""
with pysam.Samfile(in_bam, "rb") as bamfile:
rg = bamfile.header.get("RG", [{}])
msgs = []
warnings = []
if len(rg) > 1:
warnings.append("Multiple read groups found in input BAM. Expect single RG per BAM.")
if len(rg) == 0:
msgs.append("No read groups found in input BAM. Expect single RG per BAM.")
if len(rg) > 0 and any(x.get("SM") != rgnames["sample"] for x in rg):
msgs.append("Read group sample name (SM) does not match configuration `description`: %s vs %s"
% (rg[0].get("SM"), rgnames["sample"]))
if len(msgs) > 0:
raise ValueError("Problems with pre-aligned input BAM file: %s\n" % (in_bam)
+ "\n".join(msgs) +
"\nSetting `bam_clean: fixrg`\n"
"in the configuration can often fix this issue.")
if warnings:
print("*** Potential problems in input BAM compared to reference:\n%s\n" %
"\n".join(warnings)) | python | def _check_sample(in_bam, rgnames):
"""Ensure input sample name matches expected run group names.
"""
with pysam.Samfile(in_bam, "rb") as bamfile:
rg = bamfile.header.get("RG", [{}])
msgs = []
warnings = []
if len(rg) > 1:
warnings.append("Multiple read groups found in input BAM. Expect single RG per BAM.")
if len(rg) == 0:
msgs.append("No read groups found in input BAM. Expect single RG per BAM.")
if len(rg) > 0 and any(x.get("SM") != rgnames["sample"] for x in rg):
msgs.append("Read group sample name (SM) does not match configuration `description`: %s vs %s"
% (rg[0].get("SM"), rgnames["sample"]))
if len(msgs) > 0:
raise ValueError("Problems with pre-aligned input BAM file: %s\n" % (in_bam)
+ "\n".join(msgs) +
"\nSetting `bam_clean: fixrg`\n"
"in the configuration can often fix this issue.")
if warnings:
print("*** Potential problems in input BAM compared to reference:\n%s\n" %
"\n".join(warnings)) | [
"def",
"_check_sample",
"(",
"in_bam",
",",
"rgnames",
")",
":",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
",",
"\"rb\"",
")",
"as",
"bamfile",
":",
"rg",
"=",
"bamfile",
".",
"header",
".",
"get",
"(",
"\"RG\"",
",",
"[",
"{",
"}",
"]",
")",... | Ensure input sample name matches expected run group names. | [
"Ensure",
"input",
"sample",
"name",
"matches",
"expected",
"run",
"group",
"names",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L259-L280 |
223,322 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | _check_bam_contigs | def _check_bam_contigs(in_bam, ref_file, config):
"""Ensure a pre-aligned BAM file matches the expected reference genome.
"""
# GATK allows chromosome M to be in multiple locations, skip checking it
allowed_outoforder = ["chrM", "MT"]
ref_contigs = [c.name for c in ref.file_contigs(ref_file, config)]
with pysam.Samfile(in_bam, "rb") as bamfile:
bam_contigs = [c["SN"] for c in bamfile.header["SQ"]]
extra_bcs = [x for x in bam_contigs if x not in ref_contigs]
extra_rcs = [x for x in ref_contigs if x not in bam_contigs]
problems = []
warnings = []
for bc, rc in zip_longest([x for x in bam_contigs if (x not in extra_bcs and
x not in allowed_outoforder)],
[x for x in ref_contigs if (x not in extra_rcs and
x not in allowed_outoforder)]):
if bc != rc:
if bc and rc:
problems.append("Reference mismatch. BAM: %s Reference: %s" % (bc, rc))
elif bc:
warnings.append("Extra BAM chromosomes: %s" % bc)
elif rc:
warnings.append("Extra reference chromosomes: %s" % rc)
for bc in extra_bcs:
warnings.append("Extra BAM chromosomes: %s" % bc)
for rc in extra_rcs:
warnings.append("Extra reference chromosomes: %s" % rc)
if problems:
raise ValueError("Unexpected order, name or contig mismatches between input BAM and reference file:\n%s\n"
"Setting `bam_clean: remove_extracontigs` in the configuration can often fix this issue."
% "\n".join(problems))
if warnings:
print("*** Potential problems in input BAM compared to reference:\n%s\n" %
"\n".join(warnings)) | python | def _check_bam_contigs(in_bam, ref_file, config):
"""Ensure a pre-aligned BAM file matches the expected reference genome.
"""
# GATK allows chromosome M to be in multiple locations, skip checking it
allowed_outoforder = ["chrM", "MT"]
ref_contigs = [c.name for c in ref.file_contigs(ref_file, config)]
with pysam.Samfile(in_bam, "rb") as bamfile:
bam_contigs = [c["SN"] for c in bamfile.header["SQ"]]
extra_bcs = [x for x in bam_contigs if x not in ref_contigs]
extra_rcs = [x for x in ref_contigs if x not in bam_contigs]
problems = []
warnings = []
for bc, rc in zip_longest([x for x in bam_contigs if (x not in extra_bcs and
x not in allowed_outoforder)],
[x for x in ref_contigs if (x not in extra_rcs and
x not in allowed_outoforder)]):
if bc != rc:
if bc and rc:
problems.append("Reference mismatch. BAM: %s Reference: %s" % (bc, rc))
elif bc:
warnings.append("Extra BAM chromosomes: %s" % bc)
elif rc:
warnings.append("Extra reference chromosomes: %s" % rc)
for bc in extra_bcs:
warnings.append("Extra BAM chromosomes: %s" % bc)
for rc in extra_rcs:
warnings.append("Extra reference chromosomes: %s" % rc)
if problems:
raise ValueError("Unexpected order, name or contig mismatches between input BAM and reference file:\n%s\n"
"Setting `bam_clean: remove_extracontigs` in the configuration can often fix this issue."
% "\n".join(problems))
if warnings:
print("*** Potential problems in input BAM compared to reference:\n%s\n" %
"\n".join(warnings)) | [
"def",
"_check_bam_contigs",
"(",
"in_bam",
",",
"ref_file",
",",
"config",
")",
":",
"# GATK allows chromosome M to be in multiple locations, skip checking it",
"allowed_outoforder",
"=",
"[",
"\"chrM\"",
",",
"\"MT\"",
"]",
"ref_contigs",
"=",
"[",
"c",
".",
"name",
... | Ensure a pre-aligned BAM file matches the expected reference genome. | [
"Ensure",
"a",
"pre",
"-",
"aligned",
"BAM",
"file",
"matches",
"the",
"expected",
"reference",
"genome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L282-L315 |
223,323 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | sort | def sort(in_bam, config, order="coordinate", out_dir=None):
"""Sort a BAM file, skipping if already present.
"""
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
if bam_already_sorted(in_bam, config, order):
return in_bam
sort_stem = _get_sort_stem(in_bam, order, out_dir)
sort_file = sort_stem + ".bam"
if not utils.file_exists(sort_file):
samtools = config_utils.get_program("samtools", config)
cores = config["algorithm"].get("num_cores", 1)
with file_transaction(config, sort_file) as tx_sort_file:
tx_sort_stem = os.path.splitext(tx_sort_file)[0]
tx_dir = utils.safe_makedir(os.path.dirname(tx_sort_file))
order_flag = "-n" if order == "queryname" else ""
resources = config_utils.get_resources("samtools", config)
# Slightly decrease memory and allow more accurate representation
# in Mb to ensure fits within systems like SLURM
mem = config_utils.adjust_memory(resources.get("memory", "2G"),
1.25, "decrease", out_modifier="M").upper()
cmd = ("{samtools} sort -@ {cores} -m {mem} -O BAM {order_flag} "
"-T {tx_sort_stem}-sort -o {tx_sort_file} {in_bam}")
do.run(cmd.format(**locals()), "Sort BAM file %s: %s to %s" %
(order, os.path.basename(in_bam), os.path.basename(sort_file)))
return sort_file | python | def sort(in_bam, config, order="coordinate", out_dir=None):
"""Sort a BAM file, skipping if already present.
"""
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
if bam_already_sorted(in_bam, config, order):
return in_bam
sort_stem = _get_sort_stem(in_bam, order, out_dir)
sort_file = sort_stem + ".bam"
if not utils.file_exists(sort_file):
samtools = config_utils.get_program("samtools", config)
cores = config["algorithm"].get("num_cores", 1)
with file_transaction(config, sort_file) as tx_sort_file:
tx_sort_stem = os.path.splitext(tx_sort_file)[0]
tx_dir = utils.safe_makedir(os.path.dirname(tx_sort_file))
order_flag = "-n" if order == "queryname" else ""
resources = config_utils.get_resources("samtools", config)
# Slightly decrease memory and allow more accurate representation
# in Mb to ensure fits within systems like SLURM
mem = config_utils.adjust_memory(resources.get("memory", "2G"),
1.25, "decrease", out_modifier="M").upper()
cmd = ("{samtools} sort -@ {cores} -m {mem} -O BAM {order_flag} "
"-T {tx_sort_stem}-sort -o {tx_sort_file} {in_bam}")
do.run(cmd.format(**locals()), "Sort BAM file %s: %s to %s" %
(order, os.path.basename(in_bam), os.path.basename(sort_file)))
return sort_file | [
"def",
"sort",
"(",
"in_bam",
",",
"config",
",",
"order",
"=",
"\"coordinate\"",
",",
"out_dir",
"=",
"None",
")",
":",
"assert",
"is_bam",
"(",
"in_bam",
")",
",",
"\"%s in not a BAM file\"",
"%",
"in_bam",
"if",
"bam_already_sorted",
"(",
"in_bam",
",",
... | Sort a BAM file, skipping if already present. | [
"Sort",
"a",
"BAM",
"file",
"skipping",
"if",
"already",
"present",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L406-L431 |
223,324 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | aligner_from_header | def aligner_from_header(in_bam):
"""Identify aligner from the BAM header; handling pre-aligned inputs.
"""
from bcbio.pipeline.alignment import TOOLS
with pysam.Samfile(in_bam, "rb") as bamfile:
for pg in bamfile.header.get("PG", []):
for ka in TOOLS.keys():
if pg.get("PN", "").lower().find(ka) >= 0:
return ka | python | def aligner_from_header(in_bam):
"""Identify aligner from the BAM header; handling pre-aligned inputs.
"""
from bcbio.pipeline.alignment import TOOLS
with pysam.Samfile(in_bam, "rb") as bamfile:
for pg in bamfile.header.get("PG", []):
for ka in TOOLS.keys():
if pg.get("PN", "").lower().find(ka) >= 0:
return ka | [
"def",
"aligner_from_header",
"(",
"in_bam",
")",
":",
"from",
"bcbio",
".",
"pipeline",
".",
"alignment",
"import",
"TOOLS",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
",",
"\"rb\"",
")",
"as",
"bamfile",
":",
"for",
"pg",
"in",
"bamfile",
".",
"he... | Identify aligner from the BAM header; handling pre-aligned inputs. | [
"Identify",
"aligner",
"from",
"the",
"BAM",
"header",
";",
"handling",
"pre",
"-",
"aligned",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L455-L463 |
223,325 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | sample_name | def sample_name(in_bam):
"""Get sample name from BAM file.
"""
with pysam.AlignmentFile(in_bam, "rb", check_sq=False) as in_pysam:
try:
if "RG" in in_pysam.header:
return in_pysam.header["RG"][0]["SM"]
except ValueError:
return None | python | def sample_name(in_bam):
"""Get sample name from BAM file.
"""
with pysam.AlignmentFile(in_bam, "rb", check_sq=False) as in_pysam:
try:
if "RG" in in_pysam.header:
return in_pysam.header["RG"][0]["SM"]
except ValueError:
return None | [
"def",
"sample_name",
"(",
"in_bam",
")",
":",
"with",
"pysam",
".",
"AlignmentFile",
"(",
"in_bam",
",",
"\"rb\"",
",",
"check_sq",
"=",
"False",
")",
"as",
"in_pysam",
":",
"try",
":",
"if",
"\"RG\"",
"in",
"in_pysam",
".",
"header",
":",
"return",
"... | Get sample name from BAM file. | [
"Get",
"sample",
"name",
"from",
"BAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L465-L473 |
223,326 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | filter_primary | def filter_primary(bam_file, data):
"""Filter reads to primary only BAM.
Removes:
- not primary alignment (0x100) 256
- supplementary alignment (0x800) 2048
"""
stem, ext = os.path.splitext(bam_file)
out_file = stem + ".primary" + ext
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cores = dd.get_num_cores(data)
cmd = ("samtools view -@ {cores} -F 2304 -b {bam_file} > {tx_out_file}")
do.run(cmd.format(**locals()), ("Filtering primary alignments in %s." %
os.path.basename(bam_file)))
return out_file | python | def filter_primary(bam_file, data):
"""Filter reads to primary only BAM.
Removes:
- not primary alignment (0x100) 256
- supplementary alignment (0x800) 2048
"""
stem, ext = os.path.splitext(bam_file)
out_file = stem + ".primary" + ext
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cores = dd.get_num_cores(data)
cmd = ("samtools view -@ {cores} -F 2304 -b {bam_file} > {tx_out_file}")
do.run(cmd.format(**locals()), ("Filtering primary alignments in %s." %
os.path.basename(bam_file)))
return out_file | [
"def",
"filter_primary",
"(",
"bam_file",
",",
"data",
")",
":",
"stem",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"bam_file",
")",
"out_file",
"=",
"stem",
"+",
"\".primary\"",
"+",
"ext",
"if",
"not",
"utils",
".",
"file_exists",
"(",... | Filter reads to primary only BAM.
Removes:
- not primary alignment (0x100) 256
- supplementary alignment (0x800) 2048 | [
"Filter",
"reads",
"to",
"primary",
"only",
"BAM",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L496-L511 |
223,327 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | estimate_max_mapq | def estimate_max_mapq(in_bam, nreads=1e6):
"""Guess maximum MAPQ in a BAM file of reads with alignments
"""
with pysam.Samfile(in_bam, "rb") as work_bam:
reads = tz.take(int(nreads), work_bam)
return max([x.mapq for x in reads if not x.is_unmapped]) | python | def estimate_max_mapq(in_bam, nreads=1e6):
"""Guess maximum MAPQ in a BAM file of reads with alignments
"""
with pysam.Samfile(in_bam, "rb") as work_bam:
reads = tz.take(int(nreads), work_bam)
return max([x.mapq for x in reads if not x.is_unmapped]) | [
"def",
"estimate_max_mapq",
"(",
"in_bam",
",",
"nreads",
"=",
"1e6",
")",
":",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
",",
"\"rb\"",
")",
"as",
"work_bam",
":",
"reads",
"=",
"tz",
".",
"take",
"(",
"int",
"(",
"nreads",
")",
",",
"work_bam... | Guess maximum MAPQ in a BAM file of reads with alignments | [
"Guess",
"maximum",
"MAPQ",
"in",
"a",
"BAM",
"file",
"of",
"reads",
"with",
"alignments"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L513-L518 |
223,328 | bcbio/bcbio-nextgen | bcbio/bam/__init__.py | convert_cufflinks_mapq | def convert_cufflinks_mapq(in_bam, out_bam=None):
"""Cufflinks expects the not-valid 255 MAPQ for uniquely mapped reads.
This detects the maximum mapping quality in a BAM file and sets
reads with that quality to be 255
"""
CUFFLINKSMAPQ = 255
if not out_bam:
out_bam = os.path.splitext(in_bam)[0] + "-cufflinks.bam"
if utils.file_exists(out_bam):
return out_bam
maxmapq = estimate_max_mapq(in_bam)
if maxmapq == CUFFLINKSMAPQ:
return in_bam
logger.info("Converting MAPQ scores in %s to be Cufflinks compatible." % in_bam)
with pysam.Samfile(in_bam, "rb") as in_bam_fh:
with pysam.Samfile(out_bam, "wb", template=in_bam_fh) as out_bam_fh:
for read in in_bam_fh:
if read.mapq == maxmapq and not read.is_unmapped:
read.mapq = CUFFLINKSMAPQ
out_bam_fh.write(read)
return out_bam | python | def convert_cufflinks_mapq(in_bam, out_bam=None):
"""Cufflinks expects the not-valid 255 MAPQ for uniquely mapped reads.
This detects the maximum mapping quality in a BAM file and sets
reads with that quality to be 255
"""
CUFFLINKSMAPQ = 255
if not out_bam:
out_bam = os.path.splitext(in_bam)[0] + "-cufflinks.bam"
if utils.file_exists(out_bam):
return out_bam
maxmapq = estimate_max_mapq(in_bam)
if maxmapq == CUFFLINKSMAPQ:
return in_bam
logger.info("Converting MAPQ scores in %s to be Cufflinks compatible." % in_bam)
with pysam.Samfile(in_bam, "rb") as in_bam_fh:
with pysam.Samfile(out_bam, "wb", template=in_bam_fh) as out_bam_fh:
for read in in_bam_fh:
if read.mapq == maxmapq and not read.is_unmapped:
read.mapq = CUFFLINKSMAPQ
out_bam_fh.write(read)
return out_bam | [
"def",
"convert_cufflinks_mapq",
"(",
"in_bam",
",",
"out_bam",
"=",
"None",
")",
":",
"CUFFLINKSMAPQ",
"=",
"255",
"if",
"not",
"out_bam",
":",
"out_bam",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"in_bam",
")",
"[",
"0",
"]",
"+",
"\"-cufflinks.bam... | Cufflinks expects the not-valid 255 MAPQ for uniquely mapped reads.
This detects the maximum mapping quality in a BAM file and sets
reads with that quality to be 255 | [
"Cufflinks",
"expects",
"the",
"not",
"-",
"valid",
"255",
"MAPQ",
"for",
"uniquely",
"mapped",
"reads",
".",
"This",
"detects",
"the",
"maximum",
"mapping",
"quality",
"in",
"a",
"BAM",
"file",
"and",
"sets",
"reads",
"with",
"that",
"quality",
"to",
"be"... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L520-L540 |
223,329 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | get_gatk_annotations | def get_gatk_annotations(config, include_depth=True, include_baseqranksum=True,
gatk_input=True):
"""Retrieve annotations to use for GATK VariantAnnotator.
If include_depth is false, we'll skip annotating DP. Since GATK downsamples
this will undercount on high depth sequencing and the standard outputs
from the original callers may be preferable.
BaseQRankSum can cause issues with some MuTect2 and other runs, so we
provide option to skip it.
"""
broad_runner = broad.runner_from_config(config)
anns = ["MappingQualityRankSumTest", "MappingQualityZero",
"QualByDepth", "ReadPosRankSumTest", "RMSMappingQuality"]
if include_baseqranksum:
anns += ["BaseQualityRankSumTest"]
# Some annotations not working correctly with external datasets and GATK 3
if gatk_input or broad_runner.gatk_type() == "gatk4":
anns += ["FisherStrand"]
if broad_runner.gatk_type() == "gatk4":
anns += ["MappingQuality"]
else:
anns += ["GCContent", "HaplotypeScore", "HomopolymerRun"]
if include_depth:
anns += ["DepthPerAlleleBySample"]
if broad_runner.gatk_type() in ["restricted", "gatk4"]:
anns += ["Coverage"]
else:
anns += ["DepthOfCoverage"]
return anns | python | def get_gatk_annotations(config, include_depth=True, include_baseqranksum=True,
gatk_input=True):
"""Retrieve annotations to use for GATK VariantAnnotator.
If include_depth is false, we'll skip annotating DP. Since GATK downsamples
this will undercount on high depth sequencing and the standard outputs
from the original callers may be preferable.
BaseQRankSum can cause issues with some MuTect2 and other runs, so we
provide option to skip it.
"""
broad_runner = broad.runner_from_config(config)
anns = ["MappingQualityRankSumTest", "MappingQualityZero",
"QualByDepth", "ReadPosRankSumTest", "RMSMappingQuality"]
if include_baseqranksum:
anns += ["BaseQualityRankSumTest"]
# Some annotations not working correctly with external datasets and GATK 3
if gatk_input or broad_runner.gatk_type() == "gatk4":
anns += ["FisherStrand"]
if broad_runner.gatk_type() == "gatk4":
anns += ["MappingQuality"]
else:
anns += ["GCContent", "HaplotypeScore", "HomopolymerRun"]
if include_depth:
anns += ["DepthPerAlleleBySample"]
if broad_runner.gatk_type() in ["restricted", "gatk4"]:
anns += ["Coverage"]
else:
anns += ["DepthOfCoverage"]
return anns | [
"def",
"get_gatk_annotations",
"(",
"config",
",",
"include_depth",
"=",
"True",
",",
"include_baseqranksum",
"=",
"True",
",",
"gatk_input",
"=",
"True",
")",
":",
"broad_runner",
"=",
"broad",
".",
"runner_from_config",
"(",
"config",
")",
"anns",
"=",
"[",
... | Retrieve annotations to use for GATK VariantAnnotator.
If include_depth is false, we'll skip annotating DP. Since GATK downsamples
this will undercount on high depth sequencing and the standard outputs
from the original callers may be preferable.
BaseQRankSum can cause issues with some MuTect2 and other runs, so we
provide option to skip it. | [
"Retrieve",
"annotations",
"to",
"use",
"for",
"GATK",
"VariantAnnotator",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L17-L46 |
223,330 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | finalize_vcf | def finalize_vcf(in_file, variantcaller, items):
"""Perform cleanup and dbSNP annotation of the final VCF.
- Adds contigs to header for bcftools compatibility
- adds sample information for tumor/normal
"""
out_file = "%s-annotated%s" % utils.splitext_plus(in_file)
if not utils.file_uptodate(out_file, in_file):
header_cl = _add_vcf_header_sample_cl(in_file, items, out_file)
contig_cl = _add_contig_cl(in_file, items, out_file)
cls = [x for x in (contig_cl, header_cl) if x]
if cls:
post_cl = " | ".join(cls) + " | "
else:
post_cl = None
dbsnp_file = tz.get_in(("genome_resources", "variation", "dbsnp"), items[0])
if dbsnp_file:
out_file = _add_dbsnp(in_file, dbsnp_file, items[0], out_file, post_cl)
if utils.file_exists(out_file):
return vcfutils.bgzip_and_index(out_file, items[0]["config"])
else:
return in_file | python | def finalize_vcf(in_file, variantcaller, items):
"""Perform cleanup and dbSNP annotation of the final VCF.
- Adds contigs to header for bcftools compatibility
- adds sample information for tumor/normal
"""
out_file = "%s-annotated%s" % utils.splitext_plus(in_file)
if not utils.file_uptodate(out_file, in_file):
header_cl = _add_vcf_header_sample_cl(in_file, items, out_file)
contig_cl = _add_contig_cl(in_file, items, out_file)
cls = [x for x in (contig_cl, header_cl) if x]
if cls:
post_cl = " | ".join(cls) + " | "
else:
post_cl = None
dbsnp_file = tz.get_in(("genome_resources", "variation", "dbsnp"), items[0])
if dbsnp_file:
out_file = _add_dbsnp(in_file, dbsnp_file, items[0], out_file, post_cl)
if utils.file_exists(out_file):
return vcfutils.bgzip_and_index(out_file, items[0]["config"])
else:
return in_file | [
"def",
"finalize_vcf",
"(",
"in_file",
",",
"variantcaller",
",",
"items",
")",
":",
"out_file",
"=",
"\"%s-annotated%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"in_file",
... | Perform cleanup and dbSNP annotation of the final VCF.
- Adds contigs to header for bcftools compatibility
- adds sample information for tumor/normal | [
"Perform",
"cleanup",
"and",
"dbSNP",
"annotation",
"of",
"the",
"final",
"VCF",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L48-L69 |
223,331 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | _add_vcf_header_sample_cl | def _add_vcf_header_sample_cl(in_file, items, base_file):
"""Add phenotype information to a VCF header.
Encode tumor/normal relationships in VCF header.
Could also eventually handle more complicated pedigree information if useful.
"""
paired = vcfutils.get_paired(items)
if paired:
toadd = ["##SAMPLE=<ID=%s,Genomes=Tumor>" % paired.tumor_name]
if paired.normal_name:
toadd.append("##SAMPLE=<ID=%s,Genomes=Germline>" % paired.normal_name)
toadd.append("##PEDIGREE=<Derived=%s,Original=%s>" % (paired.tumor_name, paired.normal_name))
new_header = _update_header(in_file, base_file, toadd, _fix_generic_tn_names(paired))
if vcfutils.vcf_has_variants(in_file):
cmd = "bcftools reheader -h {new_header} | bcftools view "
return cmd.format(**locals()) | python | def _add_vcf_header_sample_cl(in_file, items, base_file):
"""Add phenotype information to a VCF header.
Encode tumor/normal relationships in VCF header.
Could also eventually handle more complicated pedigree information if useful.
"""
paired = vcfutils.get_paired(items)
if paired:
toadd = ["##SAMPLE=<ID=%s,Genomes=Tumor>" % paired.tumor_name]
if paired.normal_name:
toadd.append("##SAMPLE=<ID=%s,Genomes=Germline>" % paired.normal_name)
toadd.append("##PEDIGREE=<Derived=%s,Original=%s>" % (paired.tumor_name, paired.normal_name))
new_header = _update_header(in_file, base_file, toadd, _fix_generic_tn_names(paired))
if vcfutils.vcf_has_variants(in_file):
cmd = "bcftools reheader -h {new_header} | bcftools view "
return cmd.format(**locals()) | [
"def",
"_add_vcf_header_sample_cl",
"(",
"in_file",
",",
"items",
",",
"base_file",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired",
"(",
"items",
")",
"if",
"paired",
":",
"toadd",
"=",
"[",
"\"##SAMPLE=<ID=%s,Genomes=Tumor>\"",
"%",
"paired",
".",
"tu... | Add phenotype information to a VCF header.
Encode tumor/normal relationships in VCF header.
Could also eventually handle more complicated pedigree information if useful. | [
"Add",
"phenotype",
"information",
"to",
"a",
"VCF",
"header",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L98-L113 |
223,332 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | _update_header | def _update_header(orig_vcf, base_file, new_lines, chrom_process_fn=None):
"""Fix header with additional lines and remapping of generic sample names.
"""
new_header = "%s-sample_header.txt" % utils.splitext_plus(base_file)[0]
with open(new_header, "w") as out_handle:
chrom_line = None
with utils.open_gzipsafe(orig_vcf) as in_handle:
for line in in_handle:
if line.startswith("##"):
out_handle.write(line)
else:
chrom_line = line
break
assert chrom_line is not None
for line in new_lines:
out_handle.write(line + "\n")
if chrom_process_fn:
chrom_line = chrom_process_fn(chrom_line)
out_handle.write(chrom_line)
return new_header | python | def _update_header(orig_vcf, base_file, new_lines, chrom_process_fn=None):
"""Fix header with additional lines and remapping of generic sample names.
"""
new_header = "%s-sample_header.txt" % utils.splitext_plus(base_file)[0]
with open(new_header, "w") as out_handle:
chrom_line = None
with utils.open_gzipsafe(orig_vcf) as in_handle:
for line in in_handle:
if line.startswith("##"):
out_handle.write(line)
else:
chrom_line = line
break
assert chrom_line is not None
for line in new_lines:
out_handle.write(line + "\n")
if chrom_process_fn:
chrom_line = chrom_process_fn(chrom_line)
out_handle.write(chrom_line)
return new_header | [
"def",
"_update_header",
"(",
"orig_vcf",
",",
"base_file",
",",
"new_lines",
",",
"chrom_process_fn",
"=",
"None",
")",
":",
"new_header",
"=",
"\"%s-sample_header.txt\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"base_file",
")",
"[",
"0",
"]",
"with",
"open... | Fix header with additional lines and remapping of generic sample names. | [
"Fix",
"header",
"with",
"additional",
"lines",
"and",
"remapping",
"of",
"generic",
"sample",
"names",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L115-L134 |
223,333 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | _add_dbsnp | def _add_dbsnp(orig_file, dbsnp_file, data, out_file=None, post_cl=None):
"""Annotate a VCF file with dbSNP.
vcfanno has flexible matching for NON_REF gVCF positions, matching
at position and REF allele, matching ALT NON_REF as a wildcard.
"""
orig_file = vcfutils.bgzip_and_index(orig_file, data["config"])
if out_file is None:
out_file = "%s-wdbsnp.vcf.gz" % utils.splitext_plus(orig_file)[0]
if not utils.file_uptodate(out_file, orig_file):
with file_transaction(data, out_file) as tx_out_file:
conf_file = os.path.join(os.path.dirname(out_file), "dbsnp.conf")
with open(conf_file, "w") as out_handle:
out_handle.write(_DBSNP_TEMPLATE % os.path.normpath(os.path.join(dd.get_work_dir(data), dbsnp_file)))
if not post_cl: post_cl = ""
cores = dd.get_num_cores(data)
cmd = ("vcfanno -p {cores} {conf_file} {orig_file} | {post_cl} "
"bgzip -c > {tx_out_file}")
do.run(cmd.format(**locals()), "Annotate with dbSNP")
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def _add_dbsnp(orig_file, dbsnp_file, data, out_file=None, post_cl=None):
"""Annotate a VCF file with dbSNP.
vcfanno has flexible matching for NON_REF gVCF positions, matching
at position and REF allele, matching ALT NON_REF as a wildcard.
"""
orig_file = vcfutils.bgzip_and_index(orig_file, data["config"])
if out_file is None:
out_file = "%s-wdbsnp.vcf.gz" % utils.splitext_plus(orig_file)[0]
if not utils.file_uptodate(out_file, orig_file):
with file_transaction(data, out_file) as tx_out_file:
conf_file = os.path.join(os.path.dirname(out_file), "dbsnp.conf")
with open(conf_file, "w") as out_handle:
out_handle.write(_DBSNP_TEMPLATE % os.path.normpath(os.path.join(dd.get_work_dir(data), dbsnp_file)))
if not post_cl: post_cl = ""
cores = dd.get_num_cores(data)
cmd = ("vcfanno -p {cores} {conf_file} {orig_file} | {post_cl} "
"bgzip -c > {tx_out_file}")
do.run(cmd.format(**locals()), "Annotate with dbSNP")
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"_add_dbsnp",
"(",
"orig_file",
",",
"dbsnp_file",
",",
"data",
",",
"out_file",
"=",
"None",
",",
"post_cl",
"=",
"None",
")",
":",
"orig_file",
"=",
"vcfutils",
".",
"bgzip_and_index",
"(",
"orig_file",
",",
"data",
"[",
"\"config\"",
"]",
")",
... | Annotate a VCF file with dbSNP.
vcfanno has flexible matching for NON_REF gVCF positions, matching
at position and REF allele, matching ALT NON_REF as a wildcard. | [
"Annotate",
"a",
"VCF",
"file",
"with",
"dbSNP",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L154-L173 |
223,334 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | get_context_files | def get_context_files(data):
"""Retrieve pre-installed annotation files for annotating genome context.
"""
ref_file = dd.get_ref_file(data)
all_files = []
for ext in [".bed.gz"]:
all_files += sorted(glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
"coverage", "problem_regions", "*",
"*%s" % ext))))
return sorted(all_files) | python | def get_context_files(data):
"""Retrieve pre-installed annotation files for annotating genome context.
"""
ref_file = dd.get_ref_file(data)
all_files = []
for ext in [".bed.gz"]:
all_files += sorted(glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
"coverage", "problem_regions", "*",
"*%s" % ext))))
return sorted(all_files) | [
"def",
"get_context_files",
"(",
"data",
")",
":",
"ref_file",
"=",
"dd",
".",
"get_ref_file",
"(",
"data",
")",
"all_files",
"=",
"[",
"]",
"for",
"ext",
"in",
"[",
"\".bed.gz\"",
"]",
":",
"all_files",
"+=",
"sorted",
"(",
"glob",
".",
"glob",
"(",
... | Retrieve pre-installed annotation files for annotating genome context. | [
"Retrieve",
"pre",
"-",
"installed",
"annotation",
"files",
"for",
"annotating",
"genome",
"context",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L175-L184 |
223,335 | bcbio/bcbio-nextgen | bcbio/variation/annotation.py | add_genome_context | def add_genome_context(orig_file, data):
"""Annotate a file with annotations of genome context using vcfanno.
"""
out_file = "%s-context.vcf.gz" % utils.splitext_plus(orig_file)[0]
if not utils.file_uptodate(out_file, orig_file):
with file_transaction(data, out_file) as tx_out_file:
config_file = "%s.toml" % (utils.splitext_plus(tx_out_file)[0])
with open(config_file, "w") as out_handle:
all_names = []
for fname in dd.get_genome_context_files(data):
bt = pybedtools.BedTool(fname)
if bt.field_count() >= 4:
d, base = os.path.split(fname)
_, prefix = os.path.split(d)
name = "%s_%s" % (prefix, utils.splitext_plus(base)[0])
out_handle.write("[[annotation]]\n")
out_handle.write('file = "%s"\n' % fname)
out_handle.write("columns = [4]\n")
out_handle.write('names = ["%s"]\n' % name)
out_handle.write('ops = ["uniq"]\n')
all_names.append(name)
out_handle.write("[[postannotation]]\n")
out_handle.write("fields = [%s]\n" % (", ".join(['"%s"' % n for n in all_names])))
out_handle.write('name = "genome_context"\n')
out_handle.write('op = "concat"\n')
out_handle.write('type = "String"\n')
cmd = "vcfanno {config_file} {orig_file} | bgzip -c > {tx_out_file}"
do.run(cmd.format(**locals()), "Annotate with problem annotations", data)
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def add_genome_context(orig_file, data):
"""Annotate a file with annotations of genome context using vcfanno.
"""
out_file = "%s-context.vcf.gz" % utils.splitext_plus(orig_file)[0]
if not utils.file_uptodate(out_file, orig_file):
with file_transaction(data, out_file) as tx_out_file:
config_file = "%s.toml" % (utils.splitext_plus(tx_out_file)[0])
with open(config_file, "w") as out_handle:
all_names = []
for fname in dd.get_genome_context_files(data):
bt = pybedtools.BedTool(fname)
if bt.field_count() >= 4:
d, base = os.path.split(fname)
_, prefix = os.path.split(d)
name = "%s_%s" % (prefix, utils.splitext_plus(base)[0])
out_handle.write("[[annotation]]\n")
out_handle.write('file = "%s"\n' % fname)
out_handle.write("columns = [4]\n")
out_handle.write('names = ["%s"]\n' % name)
out_handle.write('ops = ["uniq"]\n')
all_names.append(name)
out_handle.write("[[postannotation]]\n")
out_handle.write("fields = [%s]\n" % (", ".join(['"%s"' % n for n in all_names])))
out_handle.write('name = "genome_context"\n')
out_handle.write('op = "concat"\n')
out_handle.write('type = "String"\n')
cmd = "vcfanno {config_file} {orig_file} | bgzip -c > {tx_out_file}"
do.run(cmd.format(**locals()), "Annotate with problem annotations", data)
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"add_genome_context",
"(",
"orig_file",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-context.vcf.gz\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"orig_file",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"orig_... | Annotate a file with annotations of genome context using vcfanno. | [
"Annotate",
"a",
"file",
"with",
"annotations",
"of",
"genome",
"context",
"using",
"vcfanno",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/annotation.py#L186-L214 |
223,336 | bcbio/bcbio-nextgen | bcbio/illumina/demultiplex.py | _submit_and_wait | def _submit_and_wait(cmd, cores, config, output_dir):
"""Submit command with batch script specified in configuration, wait until finished
"""
batch_script = "submit_bcl2fastq.sh"
if not os.path.exists(batch_script + ".finished"):
if os.path.exists(batch_script + ".failed"):
os.remove(batch_script + ".failed")
with open(batch_script, "w") as out_handle:
out_handle.write(config["process"]["bcl2fastq_batch"].format(
cores=cores, bcl2fastq_cmd=" ".join(cmd), batch_script=batch_script))
submit_cmd = utils.get_in(config, ("process", "submit_cmd"))
subprocess.check_call(submit_cmd.format(batch_script=batch_script), shell=True)
# wait until finished or failure checkpoint file
while 1:
if os.path.exists(batch_script + ".finished"):
break
if os.path.exists(batch_script + ".failed"):
raise ValueError("bcl2fastq batch script failed: %s" %
os.path.join(output_dir, batch_script))
time.sleep(5) | python | def _submit_and_wait(cmd, cores, config, output_dir):
"""Submit command with batch script specified in configuration, wait until finished
"""
batch_script = "submit_bcl2fastq.sh"
if not os.path.exists(batch_script + ".finished"):
if os.path.exists(batch_script + ".failed"):
os.remove(batch_script + ".failed")
with open(batch_script, "w") as out_handle:
out_handle.write(config["process"]["bcl2fastq_batch"].format(
cores=cores, bcl2fastq_cmd=" ".join(cmd), batch_script=batch_script))
submit_cmd = utils.get_in(config, ("process", "submit_cmd"))
subprocess.check_call(submit_cmd.format(batch_script=batch_script), shell=True)
# wait until finished or failure checkpoint file
while 1:
if os.path.exists(batch_script + ".finished"):
break
if os.path.exists(batch_script + ".failed"):
raise ValueError("bcl2fastq batch script failed: %s" %
os.path.join(output_dir, batch_script))
time.sleep(5) | [
"def",
"_submit_and_wait",
"(",
"cmd",
",",
"cores",
",",
"config",
",",
"output_dir",
")",
":",
"batch_script",
"=",
"\"submit_bcl2fastq.sh\"",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"batch_script",
"+",
"\".finished\"",
")",
":",
"if",
"os",
... | Submit command with batch script specified in configuration, wait until finished | [
"Submit",
"command",
"with",
"batch",
"script",
"specified",
"in",
"configuration",
"wait",
"until",
"finished"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/demultiplex.py#L32-L51 |
223,337 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _prep_items_from_base | def _prep_items_from_base(base, in_files, metadata, separators, force_single=False):
"""Prepare a set of configuration items for input files.
"""
details = []
in_files = _expand_dirs(in_files, KNOWN_EXTS)
in_files = _expand_wildcards(in_files)
ext_groups = collections.defaultdict(list)
for ext, files in itertools.groupby(
in_files, lambda x: KNOWN_EXTS.get(utils.splitext_plus(x)[-1].lower())):
ext_groups[ext].extend(list(files))
for ext, files in ext_groups.items():
if ext == "bam":
for f in files:
details.append(_prep_bam_input(f, base))
elif ext in ["fastq", "fq", "fasta"]:
files, glob_files = _find_glob_matches(files, metadata)
for fs in glob_files:
details.append(_prep_fastq_input(fs, base))
for fs in fastq.combine_pairs(files, force_single, separators=separators):
details.append(_prep_fastq_input(fs, base))
elif ext in ["vcf"]:
for f in files:
details.append(_prep_vcf_input(f, base))
else:
print("Ignoring unexpected input file types %s: %s" % (ext, list(files)))
return details | python | def _prep_items_from_base(base, in_files, metadata, separators, force_single=False):
"""Prepare a set of configuration items for input files.
"""
details = []
in_files = _expand_dirs(in_files, KNOWN_EXTS)
in_files = _expand_wildcards(in_files)
ext_groups = collections.defaultdict(list)
for ext, files in itertools.groupby(
in_files, lambda x: KNOWN_EXTS.get(utils.splitext_plus(x)[-1].lower())):
ext_groups[ext].extend(list(files))
for ext, files in ext_groups.items():
if ext == "bam":
for f in files:
details.append(_prep_bam_input(f, base))
elif ext in ["fastq", "fq", "fasta"]:
files, glob_files = _find_glob_matches(files, metadata)
for fs in glob_files:
details.append(_prep_fastq_input(fs, base))
for fs in fastq.combine_pairs(files, force_single, separators=separators):
details.append(_prep_fastq_input(fs, base))
elif ext in ["vcf"]:
for f in files:
details.append(_prep_vcf_input(f, base))
else:
print("Ignoring unexpected input file types %s: %s" % (ext, list(files)))
return details | [
"def",
"_prep_items_from_base",
"(",
"base",
",",
"in_files",
",",
"metadata",
",",
"separators",
",",
"force_single",
"=",
"False",
")",
":",
"details",
"=",
"[",
"]",
"in_files",
"=",
"_expand_dirs",
"(",
"in_files",
",",
"KNOWN_EXTS",
")",
"in_files",
"="... | Prepare a set of configuration items for input files. | [
"Prepare",
"a",
"set",
"of",
"configuration",
"items",
"for",
"input",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L100-L126 |
223,338 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _find_glob_matches | def _find_glob_matches(in_files, metadata):
"""Group files that match by globs for merging, rather than by explicit pairs.
"""
reg_files = copy.deepcopy(in_files)
glob_files = []
for glob_search in [x for x in metadata.keys() if "*" in x]:
cur = []
for fname in in_files:
if fnmatch.fnmatch(fname, "*/%s" % glob_search):
cur.append(fname)
reg_files.remove(fname)
assert cur, "Did not find file matches for %s" % glob_search
glob_files.append(cur)
return reg_files, glob_files | python | def _find_glob_matches(in_files, metadata):
"""Group files that match by globs for merging, rather than by explicit pairs.
"""
reg_files = copy.deepcopy(in_files)
glob_files = []
for glob_search in [x for x in metadata.keys() if "*" in x]:
cur = []
for fname in in_files:
if fnmatch.fnmatch(fname, "*/%s" % glob_search):
cur.append(fname)
reg_files.remove(fname)
assert cur, "Did not find file matches for %s" % glob_search
glob_files.append(cur)
return reg_files, glob_files | [
"def",
"_find_glob_matches",
"(",
"in_files",
",",
"metadata",
")",
":",
"reg_files",
"=",
"copy",
".",
"deepcopy",
"(",
"in_files",
")",
"glob_files",
"=",
"[",
"]",
"for",
"glob_search",
"in",
"[",
"x",
"for",
"x",
"in",
"metadata",
".",
"keys",
"(",
... | Group files that match by globs for merging, rather than by explicit pairs. | [
"Group",
"files",
"that",
"match",
"by",
"globs",
"for",
"merging",
"rather",
"than",
"by",
"explicit",
"pairs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L128-L141 |
223,339 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | name_to_config | def name_to_config(template):
"""Read template file into a dictionary to use as base for all samples.
Handles well-known template names, pulled from GitHub repository and local
files.
"""
if objectstore.is_remote(template):
with objectstore.open_file(template) as in_handle:
config = yaml.safe_load(in_handle)
with objectstore.open_file(template) as in_handle:
txt_config = in_handle.read()
elif os.path.isfile(template):
if template.endswith(".csv"):
raise ValueError("Expected YAML file for template and found CSV, are arguments switched? %s" % template)
with open(template) as in_handle:
txt_config = in_handle.read()
with open(template) as in_handle:
config = yaml.safe_load(in_handle)
else:
base_url = "https://raw.github.com/bcbio/bcbio-nextgen/master/config/templates/%s.yaml"
try:
with contextlib.closing(urllib.request.urlopen(base_url % template)) as in_handle:
txt_config = in_handle.read().decode()
with contextlib.closing(urllib.request.urlopen(base_url % template)) as in_handle:
config = yaml.safe_load(in_handle)
except (urllib.error.HTTPError, urllib.error.URLError):
raise ValueError("Could not find template '%s' locally or in standard templates on GitHub"
% template)
return config, txt_config | python | def name_to_config(template):
"""Read template file into a dictionary to use as base for all samples.
Handles well-known template names, pulled from GitHub repository and local
files.
"""
if objectstore.is_remote(template):
with objectstore.open_file(template) as in_handle:
config = yaml.safe_load(in_handle)
with objectstore.open_file(template) as in_handle:
txt_config = in_handle.read()
elif os.path.isfile(template):
if template.endswith(".csv"):
raise ValueError("Expected YAML file for template and found CSV, are arguments switched? %s" % template)
with open(template) as in_handle:
txt_config = in_handle.read()
with open(template) as in_handle:
config = yaml.safe_load(in_handle)
else:
base_url = "https://raw.github.com/bcbio/bcbio-nextgen/master/config/templates/%s.yaml"
try:
with contextlib.closing(urllib.request.urlopen(base_url % template)) as in_handle:
txt_config = in_handle.read().decode()
with contextlib.closing(urllib.request.urlopen(base_url % template)) as in_handle:
config = yaml.safe_load(in_handle)
except (urllib.error.HTTPError, urllib.error.URLError):
raise ValueError("Could not find template '%s' locally or in standard templates on GitHub"
% template)
return config, txt_config | [
"def",
"name_to_config",
"(",
"template",
")",
":",
"if",
"objectstore",
".",
"is_remote",
"(",
"template",
")",
":",
"with",
"objectstore",
".",
"open_file",
"(",
"template",
")",
"as",
"in_handle",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"in_h... | Read template file into a dictionary to use as base for all samples.
Handles well-known template names, pulled from GitHub repository and local
files. | [
"Read",
"template",
"file",
"into",
"a",
"dictionary",
"to",
"use",
"as",
"base",
"for",
"all",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L168-L196 |
223,340 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _write_config_file | def _write_config_file(items, global_vars, template, project_name, out_dir,
remotes):
"""Write configuration file, adding required top level attributes.
"""
config_dir = utils.safe_makedir(os.path.join(out_dir, "config"))
out_config_file = os.path.join(config_dir, "%s.yaml" % project_name)
out = {"fc_name": project_name,
"upload": {"dir": "../final"},
"details": items}
if remotes.get("base"):
r_base = objectstore.parse_remote(remotes.get("base"))
out["upload"]["method"] = r_base.store
out["upload"]["bucket"] = r_base.bucket
out["upload"]["folder"] = os.path.join(r_base.key, "final") if r_base.key else "final"
if r_base.region:
out["upload"]["region"] = r_base.region
if global_vars:
out["globals"] = global_vars
for k, v in template.items():
if k not in ["details"]:
out[k] = v
if os.path.exists(out_config_file):
shutil.move(out_config_file,
out_config_file + ".bak%s" % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
with open(out_config_file, "w") as out_handle:
yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
return out_config_file | python | def _write_config_file(items, global_vars, template, project_name, out_dir,
remotes):
"""Write configuration file, adding required top level attributes.
"""
config_dir = utils.safe_makedir(os.path.join(out_dir, "config"))
out_config_file = os.path.join(config_dir, "%s.yaml" % project_name)
out = {"fc_name": project_name,
"upload": {"dir": "../final"},
"details": items}
if remotes.get("base"):
r_base = objectstore.parse_remote(remotes.get("base"))
out["upload"]["method"] = r_base.store
out["upload"]["bucket"] = r_base.bucket
out["upload"]["folder"] = os.path.join(r_base.key, "final") if r_base.key else "final"
if r_base.region:
out["upload"]["region"] = r_base.region
if global_vars:
out["globals"] = global_vars
for k, v in template.items():
if k not in ["details"]:
out[k] = v
if os.path.exists(out_config_file):
shutil.move(out_config_file,
out_config_file + ".bak%s" % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
with open(out_config_file, "w") as out_handle:
yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
return out_config_file | [
"def",
"_write_config_file",
"(",
"items",
",",
"global_vars",
",",
"template",
",",
"project_name",
",",
"out_dir",
",",
"remotes",
")",
":",
"config_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"\"con... | Write configuration file, adding required top level attributes. | [
"Write",
"configuration",
"file",
"adding",
"required",
"top",
"level",
"attributes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L205-L231 |
223,341 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _set_global_vars | def _set_global_vars(metadata):
"""Identify files used multiple times in metadata and replace with global variables
"""
fnames = collections.defaultdict(list)
for sample in metadata.keys():
for k, v in metadata[sample].items():
if isinstance(v, six.string_types) and os.path.isfile(v):
v = _expand_file(v)
metadata[sample][k] = v
fnames[v].append(k)
global_vars = {}
# Skip global vars -- more confusing than useful
# loc_counts = collections.defaultdict(int)
# global_var_sub = {}
# for fname, locs in fnames.items():
# if len(locs) > 1:
# loc_counts[locs[0]] += 1
# name = "%s%s" % (locs[0], loc_counts[locs[0]])
# global_var_sub[fname] = name
# global_vars[name] = fname
# for sample in metadata.keys():
# for k, v in metadata[sample].items():
# if isinstance(v, six.string_types) and v in global_var_sub:
# metadata[sample][k] = global_var_sub[v]
return metadata, global_vars | python | def _set_global_vars(metadata):
"""Identify files used multiple times in metadata and replace with global variables
"""
fnames = collections.defaultdict(list)
for sample in metadata.keys():
for k, v in metadata[sample].items():
if isinstance(v, six.string_types) and os.path.isfile(v):
v = _expand_file(v)
metadata[sample][k] = v
fnames[v].append(k)
global_vars = {}
# Skip global vars -- more confusing than useful
# loc_counts = collections.defaultdict(int)
# global_var_sub = {}
# for fname, locs in fnames.items():
# if len(locs) > 1:
# loc_counts[locs[0]] += 1
# name = "%s%s" % (locs[0], loc_counts[locs[0]])
# global_var_sub[fname] = name
# global_vars[name] = fname
# for sample in metadata.keys():
# for k, v in metadata[sample].items():
# if isinstance(v, six.string_types) and v in global_var_sub:
# metadata[sample][k] = global_var_sub[v]
return metadata, global_vars | [
"def",
"_set_global_vars",
"(",
"metadata",
")",
":",
"fnames",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"sample",
"in",
"metadata",
".",
"keys",
"(",
")",
":",
"for",
"k",
",",
"v",
"in",
"metadata",
"[",
"sample",
"]",
".",
... | Identify files used multiple times in metadata and replace with global variables | [
"Identify",
"files",
"used",
"multiple",
"times",
"in",
"metadata",
"and",
"replace",
"with",
"global",
"variables"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L238-L262 |
223,342 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _clean_string | def _clean_string(v, sinfo):
"""Test for and clean unicode present in template CSVs.
"""
if isinstance(v, (list, tuple)):
return [_clean_string(x, sinfo) for x in v]
else:
assert isinstance(v, six.string_types), v
try:
if hasattr(v, "decode"):
return str(v.decode("ascii"))
else:
return str(v.encode("ascii").decode("ascii"))
except UnicodeDecodeError as msg:
raise ValueError("Found unicode character in template CSV line %s:\n%s" % (sinfo, str(msg))) | python | def _clean_string(v, sinfo):
"""Test for and clean unicode present in template CSVs.
"""
if isinstance(v, (list, tuple)):
return [_clean_string(x, sinfo) for x in v]
else:
assert isinstance(v, six.string_types), v
try:
if hasattr(v, "decode"):
return str(v.decode("ascii"))
else:
return str(v.encode("ascii").decode("ascii"))
except UnicodeDecodeError as msg:
raise ValueError("Found unicode character in template CSV line %s:\n%s" % (sinfo, str(msg))) | [
"def",
"_clean_string",
"(",
"v",
",",
"sinfo",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"_clean_string",
"(",
"x",
",",
"sinfo",
")",
"for",
"x",
"in",
"v",
"]",
"else",
":",
"assert",... | Test for and clean unicode present in template CSVs. | [
"Test",
"for",
"and",
"clean",
"unicode",
"present",
"in",
"template",
"CSVs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L264-L277 |
223,343 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _parse_metadata | def _parse_metadata(in_handle):
"""Reads metadata from a simple CSV structured input file.
samplename,batch,phenotype
ERR256785,batch1,normal
"""
metadata = {}
reader = csv.reader(in_handle)
while 1:
header = next(reader)
if not header[0].startswith("#"):
break
keys = [x.strip() for x in header[1:]]
for sinfo in (x for x in reader if x and not x[0].startswith("#")):
sinfo = [_strip_and_convert_lists(x) for x in sinfo]
sample = sinfo[0]
if isinstance(sample, list):
sample = tuple(sample)
# sanity check to avoid duplicate rows
if sample in metadata:
raise ValueError("Sample %s present multiple times in metadata file.\n"
"If you need to specify multiple attributes as a list "
"use a semi-colon to separate them on a single line.\n"
"https://bcbio-nextgen.readthedocs.org/en/latest/"
"contents/configuration.html#automated-sample-configuration\n"
"Duplicate line is %s" % (sample, sinfo))
vals = [_clean_string(v, sinfo) for v in sinfo[1:]]
metadata[sample] = dict(zip(keys, vals))
metadata, global_vars = _set_global_vars(metadata)
return metadata, global_vars | python | def _parse_metadata(in_handle):
"""Reads metadata from a simple CSV structured input file.
samplename,batch,phenotype
ERR256785,batch1,normal
"""
metadata = {}
reader = csv.reader(in_handle)
while 1:
header = next(reader)
if not header[0].startswith("#"):
break
keys = [x.strip() for x in header[1:]]
for sinfo in (x for x in reader if x and not x[0].startswith("#")):
sinfo = [_strip_and_convert_lists(x) for x in sinfo]
sample = sinfo[0]
if isinstance(sample, list):
sample = tuple(sample)
# sanity check to avoid duplicate rows
if sample in metadata:
raise ValueError("Sample %s present multiple times in metadata file.\n"
"If you need to specify multiple attributes as a list "
"use a semi-colon to separate them on a single line.\n"
"https://bcbio-nextgen.readthedocs.org/en/latest/"
"contents/configuration.html#automated-sample-configuration\n"
"Duplicate line is %s" % (sample, sinfo))
vals = [_clean_string(v, sinfo) for v in sinfo[1:]]
metadata[sample] = dict(zip(keys, vals))
metadata, global_vars = _set_global_vars(metadata)
return metadata, global_vars | [
"def",
"_parse_metadata",
"(",
"in_handle",
")",
":",
"metadata",
"=",
"{",
"}",
"reader",
"=",
"csv",
".",
"reader",
"(",
"in_handle",
")",
"while",
"1",
":",
"header",
"=",
"next",
"(",
"reader",
")",
"if",
"not",
"header",
"[",
"0",
"]",
".",
"s... | Reads metadata from a simple CSV structured input file.
samplename,batch,phenotype
ERR256785,batch1,normal | [
"Reads",
"metadata",
"from",
"a",
"simple",
"CSV",
"structured",
"input",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L279-L308 |
223,344 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _pname_and_metadata | def _pname_and_metadata(in_file):
"""Retrieve metadata and project name from the input metadata CSV file.
Uses the input file name for the project name and for back compatibility,
accepts the project name as an input, providing no metadata.
"""
if os.path.isfile(in_file):
with open(in_file) as in_handle:
md, global_vars = _parse_metadata(in_handle)
base = os.path.splitext(os.path.basename(in_file))[0]
md_file = in_file
elif objectstore.is_remote(in_file):
with objectstore.open_file(in_file) as in_handle:
md, global_vars = _parse_metadata(in_handle)
base = os.path.splitext(os.path.basename(in_file))[0]
md_file = None
else:
if in_file.endswith(".csv"):
raise ValueError("Did not find input metadata file: %s" % in_file)
base, md, global_vars = _safe_name(os.path.splitext(os.path.basename(in_file))[0]), {}, {}
md_file = None
return _safe_name(base), md, global_vars, md_file | python | def _pname_and_metadata(in_file):
"""Retrieve metadata and project name from the input metadata CSV file.
Uses the input file name for the project name and for back compatibility,
accepts the project name as an input, providing no metadata.
"""
if os.path.isfile(in_file):
with open(in_file) as in_handle:
md, global_vars = _parse_metadata(in_handle)
base = os.path.splitext(os.path.basename(in_file))[0]
md_file = in_file
elif objectstore.is_remote(in_file):
with objectstore.open_file(in_file) as in_handle:
md, global_vars = _parse_metadata(in_handle)
base = os.path.splitext(os.path.basename(in_file))[0]
md_file = None
else:
if in_file.endswith(".csv"):
raise ValueError("Did not find input metadata file: %s" % in_file)
base, md, global_vars = _safe_name(os.path.splitext(os.path.basename(in_file))[0]), {}, {}
md_file = None
return _safe_name(base), md, global_vars, md_file | [
"def",
"_pname_and_metadata",
"(",
"in_file",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"in_file",
")",
":",
"with",
"open",
"(",
"in_file",
")",
"as",
"in_handle",
":",
"md",
",",
"global_vars",
"=",
"_parse_metadata",
"(",
"in_handle",
")"... | Retrieve metadata and project name from the input metadata CSV file.
Uses the input file name for the project name and for back compatibility,
accepts the project name as an input, providing no metadata. | [
"Retrieve",
"metadata",
"and",
"project",
"name",
"from",
"the",
"input",
"metadata",
"CSV",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L318-L339 |
223,345 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _handle_special_yaml_cases | def _handle_special_yaml_cases(v):
"""Handle values that pass integer, boolean, list or dictionary values.
"""
if "::" in v:
out = {}
for part in v.split("::"):
k_part, v_part = part.split(":")
out[k_part] = v_part.split(";")
v = out
elif ";" in v:
# split lists and remove accidental empty values
v = [x for x in v.split(";") if x != ""]
elif isinstance(v, list):
v = v
else:
try:
v = int(v)
except ValueError:
if v.lower() == "true":
v = True
elif v.lower() == "false":
v = False
return v | python | def _handle_special_yaml_cases(v):
"""Handle values that pass integer, boolean, list or dictionary values.
"""
if "::" in v:
out = {}
for part in v.split("::"):
k_part, v_part = part.split(":")
out[k_part] = v_part.split(";")
v = out
elif ";" in v:
# split lists and remove accidental empty values
v = [x for x in v.split(";") if x != ""]
elif isinstance(v, list):
v = v
else:
try:
v = int(v)
except ValueError:
if v.lower() == "true":
v = True
elif v.lower() == "false":
v = False
return v | [
"def",
"_handle_special_yaml_cases",
"(",
"v",
")",
":",
"if",
"\"::\"",
"in",
"v",
":",
"out",
"=",
"{",
"}",
"for",
"part",
"in",
"v",
".",
"split",
"(",
"\"::\"",
")",
":",
"k_part",
",",
"v_part",
"=",
"part",
".",
"split",
"(",
"\":\"",
")",
... | Handle values that pass integer, boolean, list or dictionary values. | [
"Handle",
"values",
"that",
"pass",
"integer",
"boolean",
"list",
"or",
"dictionary",
"values",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L341-L363 |
223,346 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _add_ped_metadata | def _add_ped_metadata(name, metadata):
"""Add standard PED file attributes into metadata if not present.
http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped
"""
ignore = set(["-9", "undefined", "unknown", "."])
def _ped_mapping(x, valmap):
try:
x = int(x)
except ValueError:
x = -1
for k, v in valmap.items():
if k == x:
return v
return None
def _ped_to_gender(x):
return _ped_mapping(x, {1: "male", 2: "female"})
def _ped_to_phenotype(x):
known_phenotypes = set(["unaffected", "affected", "tumor", "normal"])
if x in known_phenotypes:
return x
else:
return _ped_mapping(x, {1: "unaffected", 2: "affected"})
def _ped_to_batch(x):
if x not in ignore and x != "0":
return x
with open(metadata["ped"]) as in_handle:
for line in in_handle:
parts = line.split("\t")[:6]
if parts[1] == str(name):
for index, key, convert_fn in [(4, "sex", _ped_to_gender), (0, "batch", _ped_to_batch),
(5, "phenotype", _ped_to_phenotype)]:
val = convert_fn(parts[index])
if val is not None and key not in metadata:
metadata[key] = val
break
return metadata | python | def _add_ped_metadata(name, metadata):
"""Add standard PED file attributes into metadata if not present.
http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped
"""
ignore = set(["-9", "undefined", "unknown", "."])
def _ped_mapping(x, valmap):
try:
x = int(x)
except ValueError:
x = -1
for k, v in valmap.items():
if k == x:
return v
return None
def _ped_to_gender(x):
return _ped_mapping(x, {1: "male", 2: "female"})
def _ped_to_phenotype(x):
known_phenotypes = set(["unaffected", "affected", "tumor", "normal"])
if x in known_phenotypes:
return x
else:
return _ped_mapping(x, {1: "unaffected", 2: "affected"})
def _ped_to_batch(x):
if x not in ignore and x != "0":
return x
with open(metadata["ped"]) as in_handle:
for line in in_handle:
parts = line.split("\t")[:6]
if parts[1] == str(name):
for index, key, convert_fn in [(4, "sex", _ped_to_gender), (0, "batch", _ped_to_batch),
(5, "phenotype", _ped_to_phenotype)]:
val = convert_fn(parts[index])
if val is not None and key not in metadata:
metadata[key] = val
break
return metadata | [
"def",
"_add_ped_metadata",
"(",
"name",
",",
"metadata",
")",
":",
"ignore",
"=",
"set",
"(",
"[",
"\"-9\"",
",",
"\"undefined\"",
",",
"\"unknown\"",
",",
"\".\"",
"]",
")",
"def",
"_ped_mapping",
"(",
"x",
",",
"valmap",
")",
":",
"try",
":",
"x",
... | Add standard PED file attributes into metadata if not present.
http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped | [
"Add",
"standard",
"PED",
"file",
"attributes",
"into",
"metadata",
"if",
"not",
"present",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L365-L401 |
223,347 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _add_metadata | def _add_metadata(item, metadata, remotes, only_metadata=False):
"""Add metadata information from CSV file to current item.
Retrieves metadata based on 'description' parsed from input CSV file.
Adds to object and handles special keys:
- `description`: A new description for the item. Used to relabel items
based on the pre-determined description from fastq name or BAM read groups.
- Keys matching supported names in the algorithm section map
to key/value pairs there instead of metadata.
"""
for check_key in [item["description"]] + _get_file_keys(item) + _get_vrn_keys(item):
item_md = metadata.get(check_key)
if item_md:
break
if not item_md:
item_md = _find_glob_metadata(item["files"], metadata)
if remotes.get("region"):
item["algorithm"]["variant_regions"] = remotes["region"]
TOP_LEVEL = set(["description", "genome_build", "lane", "vrn_file", "files", "analysis"])
keep_sample = True
if item_md and len(item_md) > 0:
if "metadata" not in item:
item["metadata"] = {}
for k, v in item_md.items():
if v:
if k in TOP_LEVEL:
item[k] = v
elif k in run_info.ALGORITHM_KEYS:
v = _handle_special_yaml_cases(v)
item["algorithm"][k] = v
else:
v = _handle_special_yaml_cases(v)
item["metadata"][k] = v
elif len(metadata) > 0:
warn = "Dropped sample" if only_metadata else "Added minimal sample information"
print("WARNING: %s: metadata not found for %s, %s" % (warn, item["description"],
[os.path.basename(f) for f in item["files"]]))
keep_sample = not only_metadata
if tz.get_in(["metadata", "ped"], item):
item["metadata"] = _add_ped_metadata(item["description"], item["metadata"])
return item if keep_sample else None | python | def _add_metadata(item, metadata, remotes, only_metadata=False):
"""Add metadata information from CSV file to current item.
Retrieves metadata based on 'description' parsed from input CSV file.
Adds to object and handles special keys:
- `description`: A new description for the item. Used to relabel items
based on the pre-determined description from fastq name or BAM read groups.
- Keys matching supported names in the algorithm section map
to key/value pairs there instead of metadata.
"""
for check_key in [item["description"]] + _get_file_keys(item) + _get_vrn_keys(item):
item_md = metadata.get(check_key)
if item_md:
break
if not item_md:
item_md = _find_glob_metadata(item["files"], metadata)
if remotes.get("region"):
item["algorithm"]["variant_regions"] = remotes["region"]
TOP_LEVEL = set(["description", "genome_build", "lane", "vrn_file", "files", "analysis"])
keep_sample = True
if item_md and len(item_md) > 0:
if "metadata" not in item:
item["metadata"] = {}
for k, v in item_md.items():
if v:
if k in TOP_LEVEL:
item[k] = v
elif k in run_info.ALGORITHM_KEYS:
v = _handle_special_yaml_cases(v)
item["algorithm"][k] = v
else:
v = _handle_special_yaml_cases(v)
item["metadata"][k] = v
elif len(metadata) > 0:
warn = "Dropped sample" if only_metadata else "Added minimal sample information"
print("WARNING: %s: metadata not found for %s, %s" % (warn, item["description"],
[os.path.basename(f) for f in item["files"]]))
keep_sample = not only_metadata
if tz.get_in(["metadata", "ped"], item):
item["metadata"] = _add_ped_metadata(item["description"], item["metadata"])
return item if keep_sample else None | [
"def",
"_add_metadata",
"(",
"item",
",",
"metadata",
",",
"remotes",
",",
"only_metadata",
"=",
"False",
")",
":",
"for",
"check_key",
"in",
"[",
"item",
"[",
"\"description\"",
"]",
"]",
"+",
"_get_file_keys",
"(",
"item",
")",
"+",
"_get_vrn_keys",
"(",... | Add metadata information from CSV file to current item.
Retrieves metadata based on 'description' parsed from input CSV file.
Adds to object and handles special keys:
- `description`: A new description for the item. Used to relabel items
based on the pre-determined description from fastq name or BAM read groups.
- Keys matching supported names in the algorithm section map
to key/value pairs there instead of metadata. | [
"Add",
"metadata",
"information",
"from",
"CSV",
"file",
"to",
"current",
"item",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L421-L461 |
223,348 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _retrieve_remote | def _retrieve_remote(fnames):
"""Retrieve remote inputs found in the same bucket as the template or metadata files.
"""
for fname in fnames:
if objectstore.is_remote(fname):
inputs = []
regions = []
remote_base = os.path.dirname(fname)
for rfname in objectstore.list(remote_base):
if rfname.endswith(tuple(KNOWN_EXTS.keys())):
inputs.append(rfname)
elif rfname.endswith((".bed", ".bed.gz")):
regions.append(rfname)
return {"base": remote_base,
"inputs": inputs,
"region": regions[0] if len(regions) == 1 else None}
return {} | python | def _retrieve_remote(fnames):
"""Retrieve remote inputs found in the same bucket as the template or metadata files.
"""
for fname in fnames:
if objectstore.is_remote(fname):
inputs = []
regions = []
remote_base = os.path.dirname(fname)
for rfname in objectstore.list(remote_base):
if rfname.endswith(tuple(KNOWN_EXTS.keys())):
inputs.append(rfname)
elif rfname.endswith((".bed", ".bed.gz")):
regions.append(rfname)
return {"base": remote_base,
"inputs": inputs,
"region": regions[0] if len(regions) == 1 else None}
return {} | [
"def",
"_retrieve_remote",
"(",
"fnames",
")",
":",
"for",
"fname",
"in",
"fnames",
":",
"if",
"objectstore",
".",
"is_remote",
"(",
"fname",
")",
":",
"inputs",
"=",
"[",
"]",
"regions",
"=",
"[",
"]",
"remote_base",
"=",
"os",
".",
"path",
".",
"di... | Retrieve remote inputs found in the same bucket as the template or metadata files. | [
"Retrieve",
"remote",
"inputs",
"found",
"in",
"the",
"same",
"bucket",
"as",
"the",
"template",
"or",
"metadata",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L477-L493 |
223,349 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _convert_to_relpaths | def _convert_to_relpaths(data, work_dir):
"""Convert absolute paths in the input data to relative paths to the work directory.
"""
work_dir = os.path.abspath(work_dir)
data["files"] = [os.path.relpath(f, work_dir) for f in data["files"]]
for topk in ["metadata", "algorithm"]:
for k, v in data[topk].items():
if isinstance(v, six.string_types) and os.path.isfile(v) and os.path.isabs(v):
data[topk][k] = os.path.relpath(v, work_dir)
return data | python | def _convert_to_relpaths(data, work_dir):
"""Convert absolute paths in the input data to relative paths to the work directory.
"""
work_dir = os.path.abspath(work_dir)
data["files"] = [os.path.relpath(f, work_dir) for f in data["files"]]
for topk in ["metadata", "algorithm"]:
for k, v in data[topk].items():
if isinstance(v, six.string_types) and os.path.isfile(v) and os.path.isabs(v):
data[topk][k] = os.path.relpath(v, work_dir)
return data | [
"def",
"_convert_to_relpaths",
"(",
"data",
",",
"work_dir",
")",
":",
"work_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"work_dir",
")",
"data",
"[",
"\"files\"",
"]",
"=",
"[",
"os",
".",
"path",
".",
"relpath",
"(",
"f",
",",
"work_dir",
")... | Convert absolute paths in the input data to relative paths to the work directory. | [
"Convert",
"absolute",
"paths",
"in",
"the",
"input",
"data",
"to",
"relative",
"paths",
"to",
"the",
"work",
"directory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L495-L504 |
223,350 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _check_all_metadata_found | def _check_all_metadata_found(metadata, items):
"""Print warning if samples in CSV file are missing in folder"""
for name in metadata:
seen = False
for sample in items:
check_file = sample["files"][0] if sample.get("files") else sample["vrn_file"]
if isinstance(name, (tuple, list)):
if check_file.find(name[0]) > -1:
seen = True
elif check_file.find(name) > -1:
seen = True
elif "*" in name and fnmatch.fnmatch(check_file, "*/%s" % name):
seen = True
if not seen:
print("WARNING: sample not found %s" % str(name)) | python | def _check_all_metadata_found(metadata, items):
"""Print warning if samples in CSV file are missing in folder"""
for name in metadata:
seen = False
for sample in items:
check_file = sample["files"][0] if sample.get("files") else sample["vrn_file"]
if isinstance(name, (tuple, list)):
if check_file.find(name[0]) > -1:
seen = True
elif check_file.find(name) > -1:
seen = True
elif "*" in name and fnmatch.fnmatch(check_file, "*/%s" % name):
seen = True
if not seen:
print("WARNING: sample not found %s" % str(name)) | [
"def",
"_check_all_metadata_found",
"(",
"metadata",
",",
"items",
")",
":",
"for",
"name",
"in",
"metadata",
":",
"seen",
"=",
"False",
"for",
"sample",
"in",
"items",
":",
"check_file",
"=",
"sample",
"[",
"\"files\"",
"]",
"[",
"0",
"]",
"if",
"sample... | Print warning if samples in CSV file are missing in folder | [
"Print",
"warning",
"if",
"samples",
"in",
"CSV",
"file",
"are",
"missing",
"in",
"folder"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L506-L520 |
223,351 | bcbio/bcbio-nextgen | bcbio/workflow/template.py | _copy_to_configdir | def _copy_to_configdir(items, out_dir, args):
"""Copy configuration files like PED inputs to working config directory.
"""
out = []
for item in items:
ped_file = tz.get_in(["metadata", "ped"], item)
if ped_file and os.path.exists(ped_file):
ped_config_file = os.path.join(out_dir, "config", os.path.basename(ped_file))
if not os.path.exists(ped_config_file):
shutil.copy(ped_file, ped_config_file)
item["metadata"]["ped"] = ped_config_file
out.append(item)
if hasattr(args, "systemconfig") and args.systemconfig:
shutil.copy(args.systemconfig, os.path.join(out_dir, "config", os.path.basename(args.systemconfig)))
return out | python | def _copy_to_configdir(items, out_dir, args):
"""Copy configuration files like PED inputs to working config directory.
"""
out = []
for item in items:
ped_file = tz.get_in(["metadata", "ped"], item)
if ped_file and os.path.exists(ped_file):
ped_config_file = os.path.join(out_dir, "config", os.path.basename(ped_file))
if not os.path.exists(ped_config_file):
shutil.copy(ped_file, ped_config_file)
item["metadata"]["ped"] = ped_config_file
out.append(item)
if hasattr(args, "systemconfig") and args.systemconfig:
shutil.copy(args.systemconfig, os.path.join(out_dir, "config", os.path.basename(args.systemconfig)))
return out | [
"def",
"_copy_to_configdir",
"(",
"items",
",",
"out_dir",
",",
"args",
")",
":",
"out",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"ped_file",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"metadata\"",
",",
"\"ped\"",
"]",
",",
"item",
")",
"if",
... | Copy configuration files like PED inputs to working config directory. | [
"Copy",
"configuration",
"files",
"like",
"PED",
"inputs",
"to",
"working",
"config",
"directory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L522-L536 |
223,352 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | load_system_config | def load_system_config(config_file=None, work_dir=None, allow_missing=False):
"""Load bcbio_system.yaml configuration file, handling standard defaults.
Looks for configuration file in default location within
final base directory from a standard installation. Handles both standard
installs (galaxy/bcbio_system.yaml) and docker installs (config/bcbio_system.yaml).
"""
docker_config = _get_docker_config()
if config_file is None:
config_file = "bcbio_system.yaml"
if not os.path.exists(config_file):
base_dir = get_base_installdir()
test_config = os.path.join(base_dir, "galaxy", config_file)
if os.path.exists(test_config):
config_file = test_config
elif allow_missing:
config_file = None
else:
raise ValueError("Could not find input system configuration file %s, "
"including inside standard directory %s" %
(config_file, os.path.join(base_dir, "galaxy")))
config = load_config(config_file) if config_file else {}
if docker_config:
assert work_dir is not None, "Need working directory to merge docker config"
config_file = os.path.join(work_dir, "%s-merged%s" % os.path.splitext(os.path.basename(config_file)))
config = _merge_system_configs(config, docker_config, config_file)
if "algorithm" not in config:
config["algorithm"] = {}
config["bcbio_system"] = config_file
return config, config_file | python | def load_system_config(config_file=None, work_dir=None, allow_missing=False):
"""Load bcbio_system.yaml configuration file, handling standard defaults.
Looks for configuration file in default location within
final base directory from a standard installation. Handles both standard
installs (galaxy/bcbio_system.yaml) and docker installs (config/bcbio_system.yaml).
"""
docker_config = _get_docker_config()
if config_file is None:
config_file = "bcbio_system.yaml"
if not os.path.exists(config_file):
base_dir = get_base_installdir()
test_config = os.path.join(base_dir, "galaxy", config_file)
if os.path.exists(test_config):
config_file = test_config
elif allow_missing:
config_file = None
else:
raise ValueError("Could not find input system configuration file %s, "
"including inside standard directory %s" %
(config_file, os.path.join(base_dir, "galaxy")))
config = load_config(config_file) if config_file else {}
if docker_config:
assert work_dir is not None, "Need working directory to merge docker config"
config_file = os.path.join(work_dir, "%s-merged%s" % os.path.splitext(os.path.basename(config_file)))
config = _merge_system_configs(config, docker_config, config_file)
if "algorithm" not in config:
config["algorithm"] = {}
config["bcbio_system"] = config_file
return config, config_file | [
"def",
"load_system_config",
"(",
"config_file",
"=",
"None",
",",
"work_dir",
"=",
"None",
",",
"allow_missing",
"=",
"False",
")",
":",
"docker_config",
"=",
"_get_docker_config",
"(",
")",
"if",
"config_file",
"is",
"None",
":",
"config_file",
"=",
"\"bcbio... | Load bcbio_system.yaml configuration file, handling standard defaults.
Looks for configuration file in default location within
final base directory from a standard installation. Handles both standard
installs (galaxy/bcbio_system.yaml) and docker installs (config/bcbio_system.yaml). | [
"Load",
"bcbio_system",
".",
"yaml",
"configuration",
"file",
"handling",
"standard",
"defaults",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L50-L79 |
223,353 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | _merge_system_configs | def _merge_system_configs(host_config, container_config, out_file=None):
"""Create a merged system configuration from external and internal specification.
"""
out = copy.deepcopy(container_config)
for k, v in host_config.items():
if k in set(["galaxy_config"]):
out[k] = v
elif k == "resources":
for pname, resources in v.items():
if not isinstance(resources, dict) and pname not in out[k]:
out[k][pname] = resources
else:
for rname, rval in resources.items():
if (rname in set(["cores", "jvm_opts", "memory"])
or pname in set(["gatk", "mutect"])):
if pname not in out[k]:
out[k][pname] = {}
out[k][pname][rname] = rval
# Ensure final file is relocatable by mapping back to reference directory
if "bcbio_system" in out and ("galaxy_config" not in out or not os.path.isabs(out["galaxy_config"])):
out["galaxy_config"] = os.path.normpath(os.path.join(os.path.dirname(out["bcbio_system"]),
os.pardir, "galaxy",
"universe_wsgi.ini"))
if out_file:
with open(out_file, "w") as out_handle:
yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
return out | python | def _merge_system_configs(host_config, container_config, out_file=None):
"""Create a merged system configuration from external and internal specification.
"""
out = copy.deepcopy(container_config)
for k, v in host_config.items():
if k in set(["galaxy_config"]):
out[k] = v
elif k == "resources":
for pname, resources in v.items():
if not isinstance(resources, dict) and pname not in out[k]:
out[k][pname] = resources
else:
for rname, rval in resources.items():
if (rname in set(["cores", "jvm_opts", "memory"])
or pname in set(["gatk", "mutect"])):
if pname not in out[k]:
out[k][pname] = {}
out[k][pname][rname] = rval
# Ensure final file is relocatable by mapping back to reference directory
if "bcbio_system" in out and ("galaxy_config" not in out or not os.path.isabs(out["galaxy_config"])):
out["galaxy_config"] = os.path.normpath(os.path.join(os.path.dirname(out["bcbio_system"]),
os.pardir, "galaxy",
"universe_wsgi.ini"))
if out_file:
with open(out_file, "w") as out_handle:
yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
return out | [
"def",
"_merge_system_configs",
"(",
"host_config",
",",
"container_config",
",",
"out_file",
"=",
"None",
")",
":",
"out",
"=",
"copy",
".",
"deepcopy",
"(",
"container_config",
")",
"for",
"k",
",",
"v",
"in",
"host_config",
".",
"items",
"(",
")",
":",
... | Create a merged system configuration from external and internal specification. | [
"Create",
"a",
"merged",
"system",
"configuration",
"from",
"external",
"and",
"internal",
"specification",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L84-L110 |
223,354 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | merge_resources | def merge_resources(args):
"""Merge docker local resources and global resource specification in a set of arguments.
Finds the `data` object within passed arguments and updates the resources
from a local docker configuration if present.
"""
docker_config = _get_docker_config()
if not docker_config:
return args
else:
def _update_resources(config):
config["resources"] = _merge_system_configs(config, docker_config)["resources"]
return config
return _update_config(args, _update_resources, allow_missing=True) | python | def merge_resources(args):
"""Merge docker local resources and global resource specification in a set of arguments.
Finds the `data` object within passed arguments and updates the resources
from a local docker configuration if present.
"""
docker_config = _get_docker_config()
if not docker_config:
return args
else:
def _update_resources(config):
config["resources"] = _merge_system_configs(config, docker_config)["resources"]
return config
return _update_config(args, _update_resources, allow_missing=True) | [
"def",
"merge_resources",
"(",
"args",
")",
":",
"docker_config",
"=",
"_get_docker_config",
"(",
")",
"if",
"not",
"docker_config",
":",
"return",
"args",
"else",
":",
"def",
"_update_resources",
"(",
"config",
")",
":",
"config",
"[",
"\"resources\"",
"]",
... | Merge docker local resources and global resource specification in a set of arguments.
Finds the `data` object within passed arguments and updates the resources
from a local docker configuration if present. | [
"Merge",
"docker",
"local",
"resources",
"and",
"global",
"resource",
"specification",
"in",
"a",
"set",
"of",
"arguments",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L118-L131 |
223,355 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | load_config | def load_config(config_file):
"""Load YAML config file, replacing environmental variables.
"""
with open(config_file) as in_handle:
config = yaml.safe_load(in_handle)
config = _expand_paths(config)
if 'resources' not in config:
config['resources'] = {}
# lowercase resource names, the preferred way to specify, for back-compatibility
newr = {}
for k, v in config["resources"].items():
if k.lower() != k:
newr[k.lower()] = v
config["resources"].update(newr)
return config | python | def load_config(config_file):
"""Load YAML config file, replacing environmental variables.
"""
with open(config_file) as in_handle:
config = yaml.safe_load(in_handle)
config = _expand_paths(config)
if 'resources' not in config:
config['resources'] = {}
# lowercase resource names, the preferred way to specify, for back-compatibility
newr = {}
for k, v in config["resources"].items():
if k.lower() != k:
newr[k.lower()] = v
config["resources"].update(newr)
return config | [
"def",
"load_config",
"(",
"config_file",
")",
":",
"with",
"open",
"(",
"config_file",
")",
"as",
"in_handle",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"in_handle",
")",
"config",
"=",
"_expand_paths",
"(",
"config",
")",
"if",
"'resources'",
"n... | Load YAML config file, replacing environmental variables. | [
"Load",
"YAML",
"config",
"file",
"replacing",
"environmental",
"variables",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L133-L147 |
223,356 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | get_resources | def get_resources(name, config):
"""Retrieve resources for a program, pulling from multiple config sources.
"""
return tz.get_in(["resources", name], config,
tz.get_in(["resources", "default"], config, {})) | python | def get_resources(name, config):
"""Retrieve resources for a program, pulling from multiple config sources.
"""
return tz.get_in(["resources", name], config,
tz.get_in(["resources", "default"], config, {})) | [
"def",
"get_resources",
"(",
"name",
",",
"config",
")",
":",
"return",
"tz",
".",
"get_in",
"(",
"[",
"\"resources\"",
",",
"name",
"]",
",",
"config",
",",
"tz",
".",
"get_in",
"(",
"[",
"\"resources\"",
",",
"\"default\"",
"]",
",",
"config",
",",
... | Retrieve resources for a program, pulling from multiple config sources. | [
"Retrieve",
"resources",
"for",
"a",
"program",
"pulling",
"from",
"multiple",
"config",
"sources",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L165-L169 |
223,357 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | get_program | def get_program(name, config, ptype="cmd", default=None):
"""Retrieve program information from the configuration.
This handles back compatible location specification in input
YAML. The preferred location for program information is in
`resources` but the older `program` tag is also supported.
"""
# support taking in the data dictionary
config = config.get("config", config)
try:
pconfig = config.get("resources", {})[name]
# If have leftover old
except KeyError:
pconfig = {}
old_config = config.get("program", {}).get(name, None)
if old_config:
for key in ["dir", "cmd"]:
if not key in pconfig:
pconfig[key] = old_config
if ptype == "cmd":
return _get_program_cmd(name, pconfig, config, default)
elif ptype == "dir":
return _get_program_dir(name, pconfig)
else:
raise ValueError("Don't understand program type: %s" % ptype) | python | def get_program(name, config, ptype="cmd", default=None):
"""Retrieve program information from the configuration.
This handles back compatible location specification in input
YAML. The preferred location for program information is in
`resources` but the older `program` tag is also supported.
"""
# support taking in the data dictionary
config = config.get("config", config)
try:
pconfig = config.get("resources", {})[name]
# If have leftover old
except KeyError:
pconfig = {}
old_config = config.get("program", {}).get(name, None)
if old_config:
for key in ["dir", "cmd"]:
if not key in pconfig:
pconfig[key] = old_config
if ptype == "cmd":
return _get_program_cmd(name, pconfig, config, default)
elif ptype == "dir":
return _get_program_dir(name, pconfig)
else:
raise ValueError("Don't understand program type: %s" % ptype) | [
"def",
"get_program",
"(",
"name",
",",
"config",
",",
"ptype",
"=",
"\"cmd\"",
",",
"default",
"=",
"None",
")",
":",
"# support taking in the data dictionary",
"config",
"=",
"config",
".",
"get",
"(",
"\"config\"",
",",
"config",
")",
"try",
":",
"pconfig... | Retrieve program information from the configuration.
This handles back compatible location specification in input
YAML. The preferred location for program information is in
`resources` but the older `program` tag is also supported. | [
"Retrieve",
"program",
"information",
"from",
"the",
"configuration",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L171-L195 |
223,358 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | _get_program_cmd | def _get_program_cmd(name, pconfig, config, default):
"""Retrieve commandline of a program.
"""
if pconfig is None:
return name
elif isinstance(pconfig, six.string_types):
return pconfig
elif "cmd" in pconfig:
return pconfig["cmd"]
elif default is not None:
return default
else:
return name | python | def _get_program_cmd(name, pconfig, config, default):
"""Retrieve commandline of a program.
"""
if pconfig is None:
return name
elif isinstance(pconfig, six.string_types):
return pconfig
elif "cmd" in pconfig:
return pconfig["cmd"]
elif default is not None:
return default
else:
return name | [
"def",
"_get_program_cmd",
"(",
"name",
",",
"pconfig",
",",
"config",
",",
"default",
")",
":",
"if",
"pconfig",
"is",
"None",
":",
"return",
"name",
"elif",
"isinstance",
"(",
"pconfig",
",",
"six",
".",
"string_types",
")",
":",
"return",
"pconfig",
"... | Retrieve commandline of a program. | [
"Retrieve",
"commandline",
"of",
"a",
"program",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L221-L233 |
223,359 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | get_jar | def get_jar(base_name, dname):
"""Retrieve a jar in the provided directory
"""
jars = glob.glob(os.path.join(expand_path(dname), "%s*.jar" % base_name))
if len(jars) == 1:
return jars[0]
elif len(jars) > 1:
raise ValueError("Found multiple jars for %s in %s. Need single jar: %s" %
(base_name, dname, jars))
else:
raise ValueError("Could not find java jar %s in %s" %
(base_name, dname)) | python | def get_jar(base_name, dname):
"""Retrieve a jar in the provided directory
"""
jars = glob.glob(os.path.join(expand_path(dname), "%s*.jar" % base_name))
if len(jars) == 1:
return jars[0]
elif len(jars) > 1:
raise ValueError("Found multiple jars for %s in %s. Need single jar: %s" %
(base_name, dname, jars))
else:
raise ValueError("Could not find java jar %s in %s" %
(base_name, dname)) | [
"def",
"get_jar",
"(",
"base_name",
",",
"dname",
")",
":",
"jars",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"expand_path",
"(",
"dname",
")",
",",
"\"%s*.jar\"",
"%",
"base_name",
")",
")",
"if",
"len",
"(",
"jars",
")",... | Retrieve a jar in the provided directory | [
"Retrieve",
"a",
"jar",
"in",
"the",
"provided",
"directory"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L247-L259 |
223,360 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | get_algorithm_config | def get_algorithm_config(xs):
"""Flexibly extract algorithm configuration for a sample from any function arguments.
"""
if isinstance(xs, dict):
xs = [xs]
for x in xs:
if is_std_config_arg(x):
return x["algorithm"]
elif is_nested_config_arg(x):
return x["config"]["algorithm"]
elif isinstance(x, (list, tuple)) and is_nested_config_arg(x[0]):
return x[0]["config"]["algorithm"]
raise ValueError("Did not find algorithm configuration in items: {0}"
.format(pprint.pformat(xs))) | python | def get_algorithm_config(xs):
"""Flexibly extract algorithm configuration for a sample from any function arguments.
"""
if isinstance(xs, dict):
xs = [xs]
for x in xs:
if is_std_config_arg(x):
return x["algorithm"]
elif is_nested_config_arg(x):
return x["config"]["algorithm"]
elif isinstance(x, (list, tuple)) and is_nested_config_arg(x[0]):
return x[0]["config"]["algorithm"]
raise ValueError("Did not find algorithm configuration in items: {0}"
.format(pprint.pformat(xs))) | [
"def",
"get_algorithm_config",
"(",
"xs",
")",
":",
"if",
"isinstance",
"(",
"xs",
",",
"dict",
")",
":",
"xs",
"=",
"[",
"xs",
"]",
"for",
"x",
"in",
"xs",
":",
"if",
"is_std_config_arg",
"(",
"x",
")",
":",
"return",
"x",
"[",
"\"algorithm\"",
"]... | Flexibly extract algorithm configuration for a sample from any function arguments. | [
"Flexibly",
"extract",
"algorithm",
"configuration",
"for",
"a",
"sample",
"from",
"any",
"function",
"arguments",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L269-L282 |
223,361 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | get_dataarg | def get_dataarg(args):
"""Retrieve the world 'data' argument from a set of input parameters.
"""
for i, arg in enumerate(args):
if is_nested_config_arg(arg):
return i, arg
elif is_std_config_arg(arg):
return i, {"config": arg}
elif isinstance(arg, (list, tuple)) and is_nested_config_arg(arg[0]):
return i, arg[0]
raise ValueError("Did not find configuration or data object in arguments: %s" % args) | python | def get_dataarg(args):
"""Retrieve the world 'data' argument from a set of input parameters.
"""
for i, arg in enumerate(args):
if is_nested_config_arg(arg):
return i, arg
elif is_std_config_arg(arg):
return i, {"config": arg}
elif isinstance(arg, (list, tuple)) and is_nested_config_arg(arg[0]):
return i, arg[0]
raise ValueError("Did not find configuration or data object in arguments: %s" % args) | [
"def",
"get_dataarg",
"(",
"args",
")",
":",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"is_nested_config_arg",
"(",
"arg",
")",
":",
"return",
"i",
",",
"arg",
"elif",
"is_std_config_arg",
"(",
"arg",
")",
":",
"return",
... | Retrieve the world 'data' argument from a set of input parameters. | [
"Retrieve",
"the",
"world",
"data",
"argument",
"from",
"a",
"set",
"of",
"input",
"parameters",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L284-L294 |
223,362 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | add_cores_to_config | def add_cores_to_config(args, cores_per_job, parallel=None):
"""Add information about available cores for a job to configuration.
Ugly hack to update core information in a configuration dictionary.
"""
def _update_cores(config):
config["algorithm"]["num_cores"] = int(cores_per_job)
if parallel:
parallel.pop("view", None)
config["parallel"] = parallel
return config
return _update_config(args, _update_cores) | python | def add_cores_to_config(args, cores_per_job, parallel=None):
"""Add information about available cores for a job to configuration.
Ugly hack to update core information in a configuration dictionary.
"""
def _update_cores(config):
config["algorithm"]["num_cores"] = int(cores_per_job)
if parallel:
parallel.pop("view", None)
config["parallel"] = parallel
return config
return _update_config(args, _update_cores) | [
"def",
"add_cores_to_config",
"(",
"args",
",",
"cores_per_job",
",",
"parallel",
"=",
"None",
")",
":",
"def",
"_update_cores",
"(",
"config",
")",
":",
"config",
"[",
"\"algorithm\"",
"]",
"[",
"\"num_cores\"",
"]",
"=",
"int",
"(",
"cores_per_job",
")",
... | Add information about available cores for a job to configuration.
Ugly hack to update core information in a configuration dictionary. | [
"Add",
"information",
"about",
"available",
"cores",
"for",
"a",
"job",
"to",
"configuration",
".",
"Ugly",
"hack",
"to",
"update",
"core",
"information",
"in",
"a",
"configuration",
"dictionary",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L296-L306 |
223,363 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | _update_config | def _update_config(args, update_fn, allow_missing=False):
"""Update configuration, nested in argument list, with the provided update function.
"""
new_i = None
for i, arg in enumerate(args):
if (is_std_config_arg(arg) or is_nested_config_arg(arg) or
(isinstance(arg, (list, tuple)) and is_nested_config_arg(arg[0]))):
new_i = i
break
if new_i is None:
if allow_missing:
return args
else:
raise ValueError("Could not find configuration in args: %s" % str(args))
new_arg = args[new_i]
if is_nested_config_arg(new_arg):
new_arg["config"] = update_fn(copy.deepcopy(new_arg["config"]))
elif is_std_config_arg(new_arg):
new_arg = update_fn(copy.deepcopy(new_arg))
elif isinstance(arg, (list, tuple)) and is_nested_config_arg(new_arg[0]):
new_arg_first = new_arg[0]
new_arg_first["config"] = update_fn(copy.deepcopy(new_arg_first["config"]))
new_arg = [new_arg_first] + new_arg[1:]
else:
raise ValueError("Unexpected configuration dictionary: %s" % new_arg)
args = list(args)[:]
args[new_i] = new_arg
return args | python | def _update_config(args, update_fn, allow_missing=False):
"""Update configuration, nested in argument list, with the provided update function.
"""
new_i = None
for i, arg in enumerate(args):
if (is_std_config_arg(arg) or is_nested_config_arg(arg) or
(isinstance(arg, (list, tuple)) and is_nested_config_arg(arg[0]))):
new_i = i
break
if new_i is None:
if allow_missing:
return args
else:
raise ValueError("Could not find configuration in args: %s" % str(args))
new_arg = args[new_i]
if is_nested_config_arg(new_arg):
new_arg["config"] = update_fn(copy.deepcopy(new_arg["config"]))
elif is_std_config_arg(new_arg):
new_arg = update_fn(copy.deepcopy(new_arg))
elif isinstance(arg, (list, tuple)) and is_nested_config_arg(new_arg[0]):
new_arg_first = new_arg[0]
new_arg_first["config"] = update_fn(copy.deepcopy(new_arg_first["config"]))
new_arg = [new_arg_first] + new_arg[1:]
else:
raise ValueError("Unexpected configuration dictionary: %s" % new_arg)
args = list(args)[:]
args[new_i] = new_arg
return args | [
"def",
"_update_config",
"(",
"args",
",",
"update_fn",
",",
"allow_missing",
"=",
"False",
")",
":",
"new_i",
"=",
"None",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"(",
"is_std_config_arg",
"(",
"arg",
")",
"or",
"is_nes... | Update configuration, nested in argument list, with the provided update function. | [
"Update",
"configuration",
"nested",
"in",
"argument",
"list",
"with",
"the",
"provided",
"update",
"function",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L308-L336 |
223,364 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | convert_to_bytes | def convert_to_bytes(mem_str):
"""Convert a memory specification, potentially with M or G, into bytes.
"""
if str(mem_str)[-1].upper().endswith("G"):
return int(round(float(mem_str[:-1]) * 1024 * 1024))
elif str(mem_str)[-1].upper().endswith("M"):
return int(round(float(mem_str[:-1]) * 1024))
else:
return int(round(float(mem_str))) | python | def convert_to_bytes(mem_str):
"""Convert a memory specification, potentially with M or G, into bytes.
"""
if str(mem_str)[-1].upper().endswith("G"):
return int(round(float(mem_str[:-1]) * 1024 * 1024))
elif str(mem_str)[-1].upper().endswith("M"):
return int(round(float(mem_str[:-1]) * 1024))
else:
return int(round(float(mem_str))) | [
"def",
"convert_to_bytes",
"(",
"mem_str",
")",
":",
"if",
"str",
"(",
"mem_str",
")",
"[",
"-",
"1",
"]",
".",
"upper",
"(",
")",
".",
"endswith",
"(",
"\"G\"",
")",
":",
"return",
"int",
"(",
"round",
"(",
"float",
"(",
"mem_str",
"[",
":",
"-"... | Convert a memory specification, potentially with M or G, into bytes. | [
"Convert",
"a",
"memory",
"specification",
"potentially",
"with",
"M",
"or",
"G",
"into",
"bytes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L338-L346 |
223,365 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | adjust_memory | def adjust_memory(val, magnitude, direction="increase", out_modifier="", maximum=None):
"""Adjust memory based on number of cores utilized.
"""
modifier = val[-1:]
amount = float(val[:-1])
if direction == "decrease":
new_amount = amount / float(magnitude)
# dealing with a specifier like 1G, need to scale to Mb
if new_amount < 1 or (out_modifier.upper().startswith("M") and modifier.upper().startswith("G")):
if modifier.upper().startswith("G"):
new_amount = (amount * 1024) / magnitude
modifier = "M" + modifier[1:]
else:
raise ValueError("Unexpected decrease in memory: %s by %s" % (val, magnitude))
amount = int(new_amount)
elif direction == "increase" and magnitude > 1:
# for increases with multiple cores, leave small percentage of
# memory for system to maintain process running resource and
# avoid OOM killers
adjuster = 0.91
amount = int(math.ceil(amount * (adjuster * magnitude)))
if out_modifier.upper().startswith("G") and modifier.upper().startswith("M"):
modifier = out_modifier
amount = int(math.floor(amount / 1024.0))
if out_modifier.upper().startswith("M") and modifier.upper().startswith("G"):
modifier = out_modifier
modifier = int(amount * 1024)
if maximum:
max_modifier = maximum[-1]
max_amount = float(maximum[:-1])
if modifier.upper() == "G" and max_modifier.upper() == "M":
max_amount = max_amount / 1024.0
elif modifier.upper() == "M" and max_modifier.upper() == "G":
max_amount = max_amount * 1024.0
amount = min([amount, max_amount])
return "{amount}{modifier}".format(amount=int(math.floor(amount)), modifier=modifier) | python | def adjust_memory(val, magnitude, direction="increase", out_modifier="", maximum=None):
"""Adjust memory based on number of cores utilized.
"""
modifier = val[-1:]
amount = float(val[:-1])
if direction == "decrease":
new_amount = amount / float(magnitude)
# dealing with a specifier like 1G, need to scale to Mb
if new_amount < 1 or (out_modifier.upper().startswith("M") and modifier.upper().startswith("G")):
if modifier.upper().startswith("G"):
new_amount = (amount * 1024) / magnitude
modifier = "M" + modifier[1:]
else:
raise ValueError("Unexpected decrease in memory: %s by %s" % (val, magnitude))
amount = int(new_amount)
elif direction == "increase" and magnitude > 1:
# for increases with multiple cores, leave small percentage of
# memory for system to maintain process running resource and
# avoid OOM killers
adjuster = 0.91
amount = int(math.ceil(amount * (adjuster * magnitude)))
if out_modifier.upper().startswith("G") and modifier.upper().startswith("M"):
modifier = out_modifier
amount = int(math.floor(amount / 1024.0))
if out_modifier.upper().startswith("M") and modifier.upper().startswith("G"):
modifier = out_modifier
modifier = int(amount * 1024)
if maximum:
max_modifier = maximum[-1]
max_amount = float(maximum[:-1])
if modifier.upper() == "G" and max_modifier.upper() == "M":
max_amount = max_amount / 1024.0
elif modifier.upper() == "M" and max_modifier.upper() == "G":
max_amount = max_amount * 1024.0
amount = min([amount, max_amount])
return "{amount}{modifier}".format(amount=int(math.floor(amount)), modifier=modifier) | [
"def",
"adjust_memory",
"(",
"val",
",",
"magnitude",
",",
"direction",
"=",
"\"increase\"",
",",
"out_modifier",
"=",
"\"\"",
",",
"maximum",
"=",
"None",
")",
":",
"modifier",
"=",
"val",
"[",
"-",
"1",
":",
"]",
"amount",
"=",
"float",
"(",
"val",
... | Adjust memory based on number of cores utilized. | [
"Adjust",
"memory",
"based",
"on",
"number",
"of",
"cores",
"utilized",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L361-L396 |
223,366 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | adjust_opts | def adjust_opts(in_opts, config):
"""Establish JVM opts, adjusting memory for the context if needed.
This allows using less or more memory for highly parallel or multicore
supporting processes, respectively.
"""
memory_adjust = config["algorithm"].get("memory_adjust", {})
out_opts = []
for opt in in_opts:
if opt.startswith("-Xmx") or (opt.startswith("-Xms") and memory_adjust.get("direction") == "decrease"):
arg = opt[:4]
opt = "{arg}{val}".format(arg=arg,
val=adjust_memory(opt[4:],
memory_adjust.get("magnitude", 1),
memory_adjust.get("direction"),
maximum=memory_adjust.get("maximum")))
out_opts.append(opt)
return out_opts | python | def adjust_opts(in_opts, config):
"""Establish JVM opts, adjusting memory for the context if needed.
This allows using less or more memory for highly parallel or multicore
supporting processes, respectively.
"""
memory_adjust = config["algorithm"].get("memory_adjust", {})
out_opts = []
for opt in in_opts:
if opt.startswith("-Xmx") or (opt.startswith("-Xms") and memory_adjust.get("direction") == "decrease"):
arg = opt[:4]
opt = "{arg}{val}".format(arg=arg,
val=adjust_memory(opt[4:],
memory_adjust.get("magnitude", 1),
memory_adjust.get("direction"),
maximum=memory_adjust.get("maximum")))
out_opts.append(opt)
return out_opts | [
"def",
"adjust_opts",
"(",
"in_opts",
",",
"config",
")",
":",
"memory_adjust",
"=",
"config",
"[",
"\"algorithm\"",
"]",
".",
"get",
"(",
"\"memory_adjust\"",
",",
"{",
"}",
")",
"out_opts",
"=",
"[",
"]",
"for",
"opt",
"in",
"in_opts",
":",
"if",
"op... | Establish JVM opts, adjusting memory for the context if needed.
This allows using less or more memory for highly parallel or multicore
supporting processes, respectively. | [
"Establish",
"JVM",
"opts",
"adjusting",
"memory",
"for",
"the",
"context",
"if",
"needed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L398-L415 |
223,367 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | use_vqsr | def use_vqsr(algs, call_file=None):
"""Processing uses GATK's Variant Quality Score Recalibration.
"""
from bcbio.variation import vcfutils
vqsr_callers = set(["gatk", "gatk-haplotype"])
vqsr_sample_thresh = 50
vqsr_supported = collections.defaultdict(int)
coverage_intervals = set([])
for alg in algs:
callers = alg.get("variantcaller")
if isinstance(callers, six.string_types):
callers = [callers]
if not callers: # no variant calling, no VQSR
continue
if "vqsr" in (alg.get("tools_off") or []): # VQSR turned off
continue
for c in callers:
if c in vqsr_callers:
if "vqsr" in (alg.get("tools_on") or []): # VQSR turned on:
vqsr_supported[c] += 1
coverage_intervals.add("genome")
# Do not try VQSR for gVCF inputs
elif call_file and vcfutils.is_gvcf_file(call_file):
pass
else:
coverage_intervals.add(alg.get("coverage_interval", "exome").lower())
vqsr_supported[c] += 1
if len(vqsr_supported) > 0:
num_samples = max(vqsr_supported.values())
if "genome" in coverage_intervals or num_samples >= vqsr_sample_thresh:
return True
return False | python | def use_vqsr(algs, call_file=None):
"""Processing uses GATK's Variant Quality Score Recalibration.
"""
from bcbio.variation import vcfutils
vqsr_callers = set(["gatk", "gatk-haplotype"])
vqsr_sample_thresh = 50
vqsr_supported = collections.defaultdict(int)
coverage_intervals = set([])
for alg in algs:
callers = alg.get("variantcaller")
if isinstance(callers, six.string_types):
callers = [callers]
if not callers: # no variant calling, no VQSR
continue
if "vqsr" in (alg.get("tools_off") or []): # VQSR turned off
continue
for c in callers:
if c in vqsr_callers:
if "vqsr" in (alg.get("tools_on") or []): # VQSR turned on:
vqsr_supported[c] += 1
coverage_intervals.add("genome")
# Do not try VQSR for gVCF inputs
elif call_file and vcfutils.is_gvcf_file(call_file):
pass
else:
coverage_intervals.add(alg.get("coverage_interval", "exome").lower())
vqsr_supported[c] += 1
if len(vqsr_supported) > 0:
num_samples = max(vqsr_supported.values())
if "genome" in coverage_intervals or num_samples >= vqsr_sample_thresh:
return True
return False | [
"def",
"use_vqsr",
"(",
"algs",
",",
"call_file",
"=",
"None",
")",
":",
"from",
"bcbio",
".",
"variation",
"import",
"vcfutils",
"vqsr_callers",
"=",
"set",
"(",
"[",
"\"gatk\"",
",",
"\"gatk-haplotype\"",
"]",
")",
"vqsr_sample_thresh",
"=",
"50",
"vqsr_su... | Processing uses GATK's Variant Quality Score Recalibration. | [
"Processing",
"uses",
"GATK",
"s",
"Variant",
"Quality",
"Score",
"Recalibration",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L419-L450 |
223,368 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | use_bcbio_variation_recall | def use_bcbio_variation_recall(algs):
"""Processing uses bcbio-variation-recall. Avoids core requirement if not used.
"""
for alg in algs:
jointcaller = alg.get("jointcaller", [])
if not isinstance(jointcaller, (tuple, list)):
jointcaller = [jointcaller]
for caller in jointcaller:
if caller not in set(["gatk-haplotype-joint", None, False]):
return True
return False | python | def use_bcbio_variation_recall(algs):
"""Processing uses bcbio-variation-recall. Avoids core requirement if not used.
"""
for alg in algs:
jointcaller = alg.get("jointcaller", [])
if not isinstance(jointcaller, (tuple, list)):
jointcaller = [jointcaller]
for caller in jointcaller:
if caller not in set(["gatk-haplotype-joint", None, False]):
return True
return False | [
"def",
"use_bcbio_variation_recall",
"(",
"algs",
")",
":",
"for",
"alg",
"in",
"algs",
":",
"jointcaller",
"=",
"alg",
".",
"get",
"(",
"\"jointcaller\"",
",",
"[",
"]",
")",
"if",
"not",
"isinstance",
"(",
"jointcaller",
",",
"(",
"tuple",
",",
"list",... | Processing uses bcbio-variation-recall. Avoids core requirement if not used. | [
"Processing",
"uses",
"bcbio",
"-",
"variation",
"-",
"recall",
".",
"Avoids",
"core",
"requirement",
"if",
"not",
"used",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L457-L467 |
223,369 | bcbio/bcbio-nextgen | bcbio/pipeline/config_utils.py | program_installed | def program_installed(program, data):
"""
returns True if the path to a program can be found
"""
try:
path = get_program(program, data)
except CmdNotFound:
return False
return True | python | def program_installed(program, data):
"""
returns True if the path to a program can be found
"""
try:
path = get_program(program, data)
except CmdNotFound:
return False
return True | [
"def",
"program_installed",
"(",
"program",
",",
"data",
")",
":",
"try",
":",
"path",
"=",
"get_program",
"(",
"program",
",",
"data",
")",
"except",
"CmdNotFound",
":",
"return",
"False",
"return",
"True"
] | returns True if the path to a program can be found | [
"returns",
"True",
"if",
"the",
"path",
"to",
"a",
"program",
"can",
"be",
"found"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/config_utils.py#L480-L488 |
223,370 | bcbio/bcbio-nextgen | bcbio/provenance/versioncheck.py | samtools | def samtools(items):
"""Ensure samtools has parallel processing required for piped analysis.
"""
samtools = config_utils.get_program("samtools", items[0]["config"])
p = subprocess.Popen([samtools, "sort", "-h"], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, stderr = p.communicate()
p.stdout.close()
p.stderr.close()
if str(output).find("-@") == -1 and str(stderr).find("-@") == -1:
return ("Installed version of samtools sort does not have support for "
"multithreading (-@ option) "
"required to support bwa piped alignment and BAM merging. "
"Please upgrade to the latest version "
"from http://samtools.sourceforge.net/") | python | def samtools(items):
"""Ensure samtools has parallel processing required for piped analysis.
"""
samtools = config_utils.get_program("samtools", items[0]["config"])
p = subprocess.Popen([samtools, "sort", "-h"], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, stderr = p.communicate()
p.stdout.close()
p.stderr.close()
if str(output).find("-@") == -1 and str(stderr).find("-@") == -1:
return ("Installed version of samtools sort does not have support for "
"multithreading (-@ option) "
"required to support bwa piped alignment and BAM merging. "
"Please upgrade to the latest version "
"from http://samtools.sourceforge.net/") | [
"def",
"samtools",
"(",
"items",
")",
":",
"samtools",
"=",
"config_utils",
".",
"get_program",
"(",
"\"samtools\"",
",",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"samtools",
",",
"\"sort\"",
... | Ensure samtools has parallel processing required for piped analysis. | [
"Ensure",
"samtools",
"has",
"parallel",
"processing",
"required",
"for",
"piped",
"analysis",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/versioncheck.py#L11-L25 |
223,371 | bcbio/bcbio-nextgen | bcbio/provenance/versioncheck.py | _needs_java | def _needs_java(data):
"""Check if a caller needs external java for MuTect.
No longer check for older GATK (<3.6) versions because of time cost; this
won't be relevant to most runs so we skip the sanity check.
"""
vc = dd.get_variantcaller(data)
if isinstance(vc, dict):
out = {}
for k, v in vc.items():
if not isinstance(v, (list, tuple)):
v = [v]
out[k] = v
vc = out
elif not isinstance(vc, (list, tuple)):
vc = [vc]
if "mutect" in vc or ("somatic" in vc and "mutect" in vc["somatic"]):
return True
if "gatk" in vc or "gatk-haplotype" in vc or ("germline" in vc and "gatk-haplotype" in vc["germline"]):
pass
# runner = broad.runner_from_config(data["config"])
# version = runner.get_gatk_version()
# if LooseVersion(version) < LooseVersion("3.6"):
# return True
return False | python | def _needs_java(data):
"""Check if a caller needs external java for MuTect.
No longer check for older GATK (<3.6) versions because of time cost; this
won't be relevant to most runs so we skip the sanity check.
"""
vc = dd.get_variantcaller(data)
if isinstance(vc, dict):
out = {}
for k, v in vc.items():
if not isinstance(v, (list, tuple)):
v = [v]
out[k] = v
vc = out
elif not isinstance(vc, (list, tuple)):
vc = [vc]
if "mutect" in vc or ("somatic" in vc and "mutect" in vc["somatic"]):
return True
if "gatk" in vc or "gatk-haplotype" in vc or ("germline" in vc and "gatk-haplotype" in vc["germline"]):
pass
# runner = broad.runner_from_config(data["config"])
# version = runner.get_gatk_version()
# if LooseVersion(version) < LooseVersion("3.6"):
# return True
return False | [
"def",
"_needs_java",
"(",
"data",
")",
":",
"vc",
"=",
"dd",
".",
"get_variantcaller",
"(",
"data",
")",
"if",
"isinstance",
"(",
"vc",
",",
"dict",
")",
":",
"out",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"vc",
".",
"items",
"(",
")",
":",... | Check if a caller needs external java for MuTect.
No longer check for older GATK (<3.6) versions because of time cost; this
won't be relevant to most runs so we skip the sanity check. | [
"Check",
"if",
"a",
"caller",
"needs",
"external",
"java",
"for",
"MuTect",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/versioncheck.py#L32-L56 |
223,372 | bcbio/bcbio-nextgen | bcbio/provenance/versioncheck.py | java | def java(items):
"""Check for presence of external Java 1.7 for tools that require it.
"""
if any([_needs_java(d) for d in items]):
min_version = "1.7"
max_version = "1.8"
with setpath.orig_paths():
java = utils.which("java")
if not java:
return ("java not found on PATH. Java %s required for MuTect and GATK < 3.6." % min_version)
p = subprocess.Popen([java, "-Xms250m", "-Xmx250m", "-version"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, _ = p.communicate()
p.stdout.close()
version = ""
for line in output.split("\n"):
if line.startswith(("java version", "openjdk version")):
version = line.strip().split()[-1]
if version.startswith('"'):
version = version[1:]
if version.endswith('"'):
version = version[:-1]
if (not version or LooseVersion(version) >= LooseVersion(max_version) or
LooseVersion(version) < LooseVersion(min_version)):
return ("java version %s required for running MuTect and GATK < 3.6.\n"
"It needs to be first on your PATH so running 'java -version' give the correct version.\n"
"Found version %s at %s" % (min_version, version, java)) | python | def java(items):
"""Check for presence of external Java 1.7 for tools that require it.
"""
if any([_needs_java(d) for d in items]):
min_version = "1.7"
max_version = "1.8"
with setpath.orig_paths():
java = utils.which("java")
if not java:
return ("java not found on PATH. Java %s required for MuTect and GATK < 3.6." % min_version)
p = subprocess.Popen([java, "-Xms250m", "-Xmx250m", "-version"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, _ = p.communicate()
p.stdout.close()
version = ""
for line in output.split("\n"):
if line.startswith(("java version", "openjdk version")):
version = line.strip().split()[-1]
if version.startswith('"'):
version = version[1:]
if version.endswith('"'):
version = version[:-1]
if (not version or LooseVersion(version) >= LooseVersion(max_version) or
LooseVersion(version) < LooseVersion(min_version)):
return ("java version %s required for running MuTect and GATK < 3.6.\n"
"It needs to be first on your PATH so running 'java -version' give the correct version.\n"
"Found version %s at %s" % (min_version, version, java)) | [
"def",
"java",
"(",
"items",
")",
":",
"if",
"any",
"(",
"[",
"_needs_java",
"(",
"d",
")",
"for",
"d",
"in",
"items",
"]",
")",
":",
"min_version",
"=",
"\"1.7\"",
"max_version",
"=",
"\"1.8\"",
"with",
"setpath",
".",
"orig_paths",
"(",
")",
":",
... | Check for presence of external Java 1.7 for tools that require it. | [
"Check",
"for",
"presence",
"of",
"external",
"Java",
"1",
".",
"7",
"for",
"tools",
"that",
"require",
"it",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/versioncheck.py#L58-L84 |
223,373 | bcbio/bcbio-nextgen | bcbio/install.py | upgrade_bcbio | def upgrade_bcbio(args):
"""Perform upgrade of bcbio to latest release, or from GitHub development version.
Handles bcbio, third party tools and data.
"""
print("Upgrading bcbio")
args = add_install_defaults(args)
if args.upgrade in ["stable", "system", "deps", "development"]:
if args.upgrade == "development":
anaconda_dir = _update_conda_devel()
_check_for_conda_problems()
print("Upgrading bcbio-nextgen to latest development version")
pip_bin = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), "pip")
git_tag = "@%s" % args.revision if args.revision != "master" else ""
_pip_safe_ssl([[pip_bin, "install", "--upgrade", "--no-deps",
"git+%s%s#egg=bcbio-nextgen" % (REMOTES["gitrepo"], git_tag)]], anaconda_dir)
print("Upgrade of bcbio-nextgen development code complete.")
else:
_update_conda_packages()
_check_for_conda_problems()
print("Upgrade of bcbio-nextgen code complete.")
if args.cwl and args.upgrade:
_update_bcbiovm()
try:
_set_matplotlib_default_backend()
except OSError:
pass
if args.tooldir:
with bcbio_tmpdir():
print("Upgrading third party tools to latest versions")
_symlink_bcbio(args, script="bcbio_nextgen.py")
_symlink_bcbio(args, script="bcbio_setup_genome.py")
_symlink_bcbio(args, script="bcbio_prepare_samples.py")
_symlink_bcbio(args, script="bcbio_fastq_umi_prep.py")
if args.cwl:
_symlink_bcbio(args, "bcbio_vm.py", "bcbiovm")
_symlink_bcbio(args, "python", "bcbiovm", "bcbiovm")
upgrade_thirdparty_tools(args, REMOTES)
print("Third party tools upgrade complete.")
if args.toolplus:
print("Installing additional tools")
_install_toolplus(args)
if args.install_data:
for default in DEFAULT_INDEXES:
if default not in args.aligners:
args.aligners.append(default)
if len(args.aligners) == 0:
print("Warning: no aligners provided with `--aligners` flag")
if len(args.genomes) == 0:
print("Data not installed, no genomes provided with `--genomes` flag")
else:
with bcbio_tmpdir():
print("Upgrading bcbio-nextgen data files")
upgrade_bcbio_data(args, REMOTES)
print("bcbio-nextgen data upgrade complete.")
if args.isolate and args.tooldir:
print("Isolated tool installation not automatically added to environmental variables")
print(" Add:\n {t}/bin to PATH".format(t=args.tooldir))
save_install_defaults(args)
args.datadir = _get_data_dir()
_install_container_bcbio_system(args.datadir)
print("Upgrade completed successfully.")
return args | python | def upgrade_bcbio(args):
"""Perform upgrade of bcbio to latest release, or from GitHub development version.
Handles bcbio, third party tools and data.
"""
print("Upgrading bcbio")
args = add_install_defaults(args)
if args.upgrade in ["stable", "system", "deps", "development"]:
if args.upgrade == "development":
anaconda_dir = _update_conda_devel()
_check_for_conda_problems()
print("Upgrading bcbio-nextgen to latest development version")
pip_bin = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), "pip")
git_tag = "@%s" % args.revision if args.revision != "master" else ""
_pip_safe_ssl([[pip_bin, "install", "--upgrade", "--no-deps",
"git+%s%s#egg=bcbio-nextgen" % (REMOTES["gitrepo"], git_tag)]], anaconda_dir)
print("Upgrade of bcbio-nextgen development code complete.")
else:
_update_conda_packages()
_check_for_conda_problems()
print("Upgrade of bcbio-nextgen code complete.")
if args.cwl and args.upgrade:
_update_bcbiovm()
try:
_set_matplotlib_default_backend()
except OSError:
pass
if args.tooldir:
with bcbio_tmpdir():
print("Upgrading third party tools to latest versions")
_symlink_bcbio(args, script="bcbio_nextgen.py")
_symlink_bcbio(args, script="bcbio_setup_genome.py")
_symlink_bcbio(args, script="bcbio_prepare_samples.py")
_symlink_bcbio(args, script="bcbio_fastq_umi_prep.py")
if args.cwl:
_symlink_bcbio(args, "bcbio_vm.py", "bcbiovm")
_symlink_bcbio(args, "python", "bcbiovm", "bcbiovm")
upgrade_thirdparty_tools(args, REMOTES)
print("Third party tools upgrade complete.")
if args.toolplus:
print("Installing additional tools")
_install_toolplus(args)
if args.install_data:
for default in DEFAULT_INDEXES:
if default not in args.aligners:
args.aligners.append(default)
if len(args.aligners) == 0:
print("Warning: no aligners provided with `--aligners` flag")
if len(args.genomes) == 0:
print("Data not installed, no genomes provided with `--genomes` flag")
else:
with bcbio_tmpdir():
print("Upgrading bcbio-nextgen data files")
upgrade_bcbio_data(args, REMOTES)
print("bcbio-nextgen data upgrade complete.")
if args.isolate and args.tooldir:
print("Isolated tool installation not automatically added to environmental variables")
print(" Add:\n {t}/bin to PATH".format(t=args.tooldir))
save_install_defaults(args)
args.datadir = _get_data_dir()
_install_container_bcbio_system(args.datadir)
print("Upgrade completed successfully.")
return args | [
"def",
"upgrade_bcbio",
"(",
"args",
")",
":",
"print",
"(",
"\"Upgrading bcbio\"",
")",
"args",
"=",
"add_install_defaults",
"(",
"args",
")",
"if",
"args",
".",
"upgrade",
"in",
"[",
"\"stable\"",
",",
"\"system\"",
",",
"\"deps\"",
",",
"\"development\"",
... | Perform upgrade of bcbio to latest release, or from GitHub development version.
Handles bcbio, third party tools and data. | [
"Perform",
"upgrade",
"of",
"bcbio",
"to",
"latest",
"release",
"or",
"from",
"GitHub",
"development",
"version",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L51-L115 |
223,374 | bcbio/bcbio-nextgen | bcbio/install.py | _pip_safe_ssl | def _pip_safe_ssl(cmds, anaconda_dir):
"""Run pip, retrying with conda SSL certificate if global certificate fails.
"""
try:
for cmd in cmds:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
_set_pip_ssl(anaconda_dir)
for cmd in cmds:
subprocess.check_call(cmd) | python | def _pip_safe_ssl(cmds, anaconda_dir):
"""Run pip, retrying with conda SSL certificate if global certificate fails.
"""
try:
for cmd in cmds:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
_set_pip_ssl(anaconda_dir)
for cmd in cmds:
subprocess.check_call(cmd) | [
"def",
"_pip_safe_ssl",
"(",
"cmds",
",",
"anaconda_dir",
")",
":",
"try",
":",
"for",
"cmd",
"in",
"cmds",
":",
"subprocess",
".",
"check_call",
"(",
"cmd",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"_set_pip_ssl",
"(",
"anaconda_dir",
")... | Run pip, retrying with conda SSL certificate if global certificate fails. | [
"Run",
"pip",
"retrying",
"with",
"conda",
"SSL",
"certificate",
"if",
"global",
"certificate",
"fails",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L117-L126 |
223,375 | bcbio/bcbio-nextgen | bcbio/install.py | _set_pip_ssl | def _set_pip_ssl(anaconda_dir):
"""Set PIP SSL certificate to installed conda certificate to avoid SSL errors
"""
if anaconda_dir:
cert_file = os.path.join(anaconda_dir, "ssl", "cert.pem")
if os.path.exists(cert_file):
os.environ["PIP_CERT"] = cert_file | python | def _set_pip_ssl(anaconda_dir):
"""Set PIP SSL certificate to installed conda certificate to avoid SSL errors
"""
if anaconda_dir:
cert_file = os.path.join(anaconda_dir, "ssl", "cert.pem")
if os.path.exists(cert_file):
os.environ["PIP_CERT"] = cert_file | [
"def",
"_set_pip_ssl",
"(",
"anaconda_dir",
")",
":",
"if",
"anaconda_dir",
":",
"cert_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"anaconda_dir",
",",
"\"ssl\"",
",",
"\"cert.pem\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"cert_file",
")... | Set PIP SSL certificate to installed conda certificate to avoid SSL errors | [
"Set",
"PIP",
"SSL",
"certificate",
"to",
"installed",
"conda",
"certificate",
"to",
"avoid",
"SSL",
"errors"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L128-L134 |
223,376 | bcbio/bcbio-nextgen | bcbio/install.py | _set_matplotlib_default_backend | def _set_matplotlib_default_backend():
"""
matplotlib will try to print to a display if it is available, but don't want
to run it in interactive mode. we tried setting the backend to 'Agg'' before
importing, but it was still resulting in issues. we replace the existing
backend with 'agg' in the default matplotlibrc. This is a hack until we can
find a better solution
"""
if _matplotlib_installed():
import matplotlib
matplotlib.use('Agg', force=True)
config = matplotlib.matplotlib_fname()
if os.access(config, os.W_OK):
with file_transaction(config) as tx_out_file:
with open(config) as in_file, open(tx_out_file, "w") as out_file:
for line in in_file:
if line.split(":")[0].strip() == "backend":
out_file.write("backend: agg\n")
else:
out_file.write(line) | python | def _set_matplotlib_default_backend():
"""
matplotlib will try to print to a display if it is available, but don't want
to run it in interactive mode. we tried setting the backend to 'Agg'' before
importing, but it was still resulting in issues. we replace the existing
backend with 'agg' in the default matplotlibrc. This is a hack until we can
find a better solution
"""
if _matplotlib_installed():
import matplotlib
matplotlib.use('Agg', force=True)
config = matplotlib.matplotlib_fname()
if os.access(config, os.W_OK):
with file_transaction(config) as tx_out_file:
with open(config) as in_file, open(tx_out_file, "w") as out_file:
for line in in_file:
if line.split(":")[0].strip() == "backend":
out_file.write("backend: agg\n")
else:
out_file.write(line) | [
"def",
"_set_matplotlib_default_backend",
"(",
")",
":",
"if",
"_matplotlib_installed",
"(",
")",
":",
"import",
"matplotlib",
"matplotlib",
".",
"use",
"(",
"'Agg'",
",",
"force",
"=",
"True",
")",
"config",
"=",
"matplotlib",
".",
"matplotlib_fname",
"(",
")... | matplotlib will try to print to a display if it is available, but don't want
to run it in interactive mode. we tried setting the backend to 'Agg'' before
importing, but it was still resulting in issues. we replace the existing
backend with 'agg' in the default matplotlibrc. This is a hack until we can
find a better solution | [
"matplotlib",
"will",
"try",
"to",
"print",
"to",
"a",
"display",
"if",
"it",
"is",
"available",
"but",
"don",
"t",
"want",
"to",
"run",
"it",
"in",
"interactive",
"mode",
".",
"we",
"tried",
"setting",
"the",
"backend",
"to",
"Agg",
"before",
"importing... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L136-L155 |
223,377 | bcbio/bcbio-nextgen | bcbio/install.py | _symlink_bcbio | def _symlink_bcbio(args, script="bcbio_nextgen.py", env_name=None, prefix=None):
"""Ensure a bcbio-nextgen script symlink in final tool directory.
"""
if env_name:
bcbio_anaconda = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(sys.executable))),
"envs", env_name, "bin", script)
else:
bcbio_anaconda = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), script)
bindir = os.path.join(args.tooldir, "bin")
if not os.path.exists(bindir):
os.makedirs(bindir)
if prefix:
script = "%s_%s" % (prefix, script)
bcbio_final = os.path.join(bindir, script)
if not os.path.exists(bcbio_final):
if os.path.lexists(bcbio_final):
subprocess.check_call(["rm", "-f", bcbio_final])
subprocess.check_call(["ln", "-s", bcbio_anaconda, bcbio_final]) | python | def _symlink_bcbio(args, script="bcbio_nextgen.py", env_name=None, prefix=None):
"""Ensure a bcbio-nextgen script symlink in final tool directory.
"""
if env_name:
bcbio_anaconda = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(sys.executable))),
"envs", env_name, "bin", script)
else:
bcbio_anaconda = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), script)
bindir = os.path.join(args.tooldir, "bin")
if not os.path.exists(bindir):
os.makedirs(bindir)
if prefix:
script = "%s_%s" % (prefix, script)
bcbio_final = os.path.join(bindir, script)
if not os.path.exists(bcbio_final):
if os.path.lexists(bcbio_final):
subprocess.check_call(["rm", "-f", bcbio_final])
subprocess.check_call(["ln", "-s", bcbio_anaconda, bcbio_final]) | [
"def",
"_symlink_bcbio",
"(",
"args",
",",
"script",
"=",
"\"bcbio_nextgen.py\"",
",",
"env_name",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"env_name",
":",
"bcbio_anaconda",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
... | Ensure a bcbio-nextgen script symlink in final tool directory. | [
"Ensure",
"a",
"bcbio",
"-",
"nextgen",
"script",
"symlink",
"in",
"final",
"tool",
"directory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L164-L181 |
223,378 | bcbio/bcbio-nextgen | bcbio/install.py | _install_container_bcbio_system | def _install_container_bcbio_system(datadir):
"""Install limited bcbio_system.yaml file for setting core and memory usage.
Adds any non-specific programs to the exposed bcbio_system.yaml file, only
when upgrade happening inside a docker container.
"""
base_file = os.path.join(datadir, "config", "bcbio_system.yaml")
if not os.path.exists(base_file):
return
expose_file = os.path.join(datadir, "galaxy", "bcbio_system.yaml")
expose = set(["memory", "cores", "jvm_opts"])
with open(base_file) as in_handle:
config = yaml.safe_load(in_handle)
if os.path.exists(expose_file):
with open(expose_file) as in_handle:
expose_config = yaml.safe_load(in_handle)
else:
expose_config = {"resources": {}}
for pname, vals in config["resources"].items():
expose_vals = {}
for k, v in vals.items():
if k in expose:
expose_vals[k] = v
if len(expose_vals) > 0 and pname not in expose_config["resources"]:
expose_config["resources"][pname] = expose_vals
if expose_file and os.path.exists(os.path.dirname(expose_file)):
with open(expose_file, "w") as out_handle:
yaml.safe_dump(expose_config, out_handle, default_flow_style=False, allow_unicode=False)
return expose_file | python | def _install_container_bcbio_system(datadir):
"""Install limited bcbio_system.yaml file for setting core and memory usage.
Adds any non-specific programs to the exposed bcbio_system.yaml file, only
when upgrade happening inside a docker container.
"""
base_file = os.path.join(datadir, "config", "bcbio_system.yaml")
if not os.path.exists(base_file):
return
expose_file = os.path.join(datadir, "galaxy", "bcbio_system.yaml")
expose = set(["memory", "cores", "jvm_opts"])
with open(base_file) as in_handle:
config = yaml.safe_load(in_handle)
if os.path.exists(expose_file):
with open(expose_file) as in_handle:
expose_config = yaml.safe_load(in_handle)
else:
expose_config = {"resources": {}}
for pname, vals in config["resources"].items():
expose_vals = {}
for k, v in vals.items():
if k in expose:
expose_vals[k] = v
if len(expose_vals) > 0 and pname not in expose_config["resources"]:
expose_config["resources"][pname] = expose_vals
if expose_file and os.path.exists(os.path.dirname(expose_file)):
with open(expose_file, "w") as out_handle:
yaml.safe_dump(expose_config, out_handle, default_flow_style=False, allow_unicode=False)
return expose_file | [
"def",
"_install_container_bcbio_system",
"(",
"datadir",
")",
":",
"base_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"datadir",
",",
"\"config\"",
",",
"\"bcbio_system.yaml\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"base_file",
")",
... | Install limited bcbio_system.yaml file for setting core and memory usage.
Adds any non-specific programs to the exposed bcbio_system.yaml file, only
when upgrade happening inside a docker container. | [
"Install",
"limited",
"bcbio_system",
".",
"yaml",
"file",
"for",
"setting",
"core",
"and",
"memory",
"usage",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L183-L211 |
223,379 | bcbio/bcbio-nextgen | bcbio/install.py | _check_for_conda_problems | def _check_for_conda_problems():
"""Identify post-install conda problems and fix.
- libgcc upgrades can remove libquadmath, which moved to libgcc-ng
"""
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
lib_dir = os.path.join(os.path.dirname(conda_bin), os.pardir, "lib")
for l in ["libgomp.so.1", "libquadmath.so"]:
if not os.path.exists(os.path.join(lib_dir, l)):
subprocess.check_call([conda_bin, "install", "-f", "--yes"] + channels + ["libgcc-ng"]) | python | def _check_for_conda_problems():
"""Identify post-install conda problems and fix.
- libgcc upgrades can remove libquadmath, which moved to libgcc-ng
"""
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
lib_dir = os.path.join(os.path.dirname(conda_bin), os.pardir, "lib")
for l in ["libgomp.so.1", "libquadmath.so"]:
if not os.path.exists(os.path.join(lib_dir, l)):
subprocess.check_call([conda_bin, "install", "-f", "--yes"] + channels + ["libgcc-ng"]) | [
"def",
"_check_for_conda_problems",
"(",
")",
":",
"conda_bin",
"=",
"_get_conda_bin",
"(",
")",
"channels",
"=",
"_get_conda_channels",
"(",
"conda_bin",
")",
"lib_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"co... | Identify post-install conda problems and fix.
- libgcc upgrades can remove libquadmath, which moved to libgcc-ng | [
"Identify",
"post",
"-",
"install",
"conda",
"problems",
"and",
"fix",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L218-L228 |
223,380 | bcbio/bcbio-nextgen | bcbio/install.py | _update_bcbiovm | def _update_bcbiovm():
"""Update or install a local bcbiovm install with tools and dependencies.
"""
print("## CWL support with bcbio-vm")
python_env = "python=3"
conda_bin, env_name = _add_environment("bcbiovm", python_env)
channels = _get_conda_channels(conda_bin)
base_cmd = [conda_bin, "install", "--yes", "--name", env_name] + channels
subprocess.check_call(base_cmd + [python_env, "nomkl", "bcbio-nextgen"])
extra_uptodate = ["cromwell"]
subprocess.check_call(base_cmd + [python_env, "bcbio-nextgen-vm"] + extra_uptodate) | python | def _update_bcbiovm():
"""Update or install a local bcbiovm install with tools and dependencies.
"""
print("## CWL support with bcbio-vm")
python_env = "python=3"
conda_bin, env_name = _add_environment("bcbiovm", python_env)
channels = _get_conda_channels(conda_bin)
base_cmd = [conda_bin, "install", "--yes", "--name", env_name] + channels
subprocess.check_call(base_cmd + [python_env, "nomkl", "bcbio-nextgen"])
extra_uptodate = ["cromwell"]
subprocess.check_call(base_cmd + [python_env, "bcbio-nextgen-vm"] + extra_uptodate) | [
"def",
"_update_bcbiovm",
"(",
")",
":",
"print",
"(",
"\"## CWL support with bcbio-vm\"",
")",
"python_env",
"=",
"\"python=3\"",
"conda_bin",
",",
"env_name",
"=",
"_add_environment",
"(",
"\"bcbiovm\"",
",",
"python_env",
")",
"channels",
"=",
"_get_conda_channels"... | Update or install a local bcbiovm install with tools and dependencies. | [
"Update",
"or",
"install",
"a",
"local",
"bcbiovm",
"install",
"with",
"tools",
"and",
"dependencies",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L230-L240 |
223,381 | bcbio/bcbio-nextgen | bcbio/install.py | _get_conda_channels | def _get_conda_channels(conda_bin):
"""Retrieve default conda channels, checking if they are pre-specified in config.
This allows users to override defaults with specific mirrors in their .condarc
"""
channels = ["bioconda", "conda-forge"]
out = []
config = yaml.safe_load(subprocess.check_output([conda_bin, "config", "--show"]))
for c in channels:
present = False
for orig_c in config.get("channels") or []:
if orig_c.endswith((c, "%s/" % c)):
present = True
break
if not present:
out += ["-c", c]
return out | python | def _get_conda_channels(conda_bin):
"""Retrieve default conda channels, checking if they are pre-specified in config.
This allows users to override defaults with specific mirrors in their .condarc
"""
channels = ["bioconda", "conda-forge"]
out = []
config = yaml.safe_load(subprocess.check_output([conda_bin, "config", "--show"]))
for c in channels:
present = False
for orig_c in config.get("channels") or []:
if orig_c.endswith((c, "%s/" % c)):
present = True
break
if not present:
out += ["-c", c]
return out | [
"def",
"_get_conda_channels",
"(",
"conda_bin",
")",
":",
"channels",
"=",
"[",
"\"bioconda\"",
",",
"\"conda-forge\"",
"]",
"out",
"=",
"[",
"]",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"subprocess",
".",
"check_output",
"(",
"[",
"conda_bin",
",",
... | Retrieve default conda channels, checking if they are pre-specified in config.
This allows users to override defaults with specific mirrors in their .condarc | [
"Retrieve",
"default",
"conda",
"channels",
"checking",
"if",
"they",
"are",
"pre",
"-",
"specified",
"in",
"config",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L255-L271 |
223,382 | bcbio/bcbio-nextgen | bcbio/install.py | _update_conda_packages | def _update_conda_packages():
"""If installed in an anaconda directory, upgrade conda packages.
"""
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
assert conda_bin, ("Could not find anaconda distribution for upgrading bcbio.\n"
"Using python at %s but could not find conda." % (os.path.realpath(sys.executable)))
req_file = "bcbio-update-requirements.txt"
if os.path.exists(req_file):
os.remove(req_file)
subprocess.check_call(["wget", "-O", req_file, "--no-check-certificate", REMOTES["requirements"]])
subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] + channels +
["--file", req_file])
if os.path.exists(req_file):
os.remove(req_file)
return os.path.dirname(os.path.dirname(conda_bin)) | python | def _update_conda_packages():
"""If installed in an anaconda directory, upgrade conda packages.
"""
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
assert conda_bin, ("Could not find anaconda distribution for upgrading bcbio.\n"
"Using python at %s but could not find conda." % (os.path.realpath(sys.executable)))
req_file = "bcbio-update-requirements.txt"
if os.path.exists(req_file):
os.remove(req_file)
subprocess.check_call(["wget", "-O", req_file, "--no-check-certificate", REMOTES["requirements"]])
subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] + channels +
["--file", req_file])
if os.path.exists(req_file):
os.remove(req_file)
return os.path.dirname(os.path.dirname(conda_bin)) | [
"def",
"_update_conda_packages",
"(",
")",
":",
"conda_bin",
"=",
"_get_conda_bin",
"(",
")",
"channels",
"=",
"_get_conda_channels",
"(",
"conda_bin",
")",
"assert",
"conda_bin",
",",
"(",
"\"Could not find anaconda distribution for upgrading bcbio.\\n\"",
"\"Using python ... | If installed in an anaconda directory, upgrade conda packages. | [
"If",
"installed",
"in",
"an",
"anaconda",
"directory",
"upgrade",
"conda",
"packages",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L273-L288 |
223,383 | bcbio/bcbio-nextgen | bcbio/install.py | _update_conda_devel | def _update_conda_devel():
"""Update to the latest development conda package.
"""
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
assert conda_bin, "Could not find anaconda distribution for upgrading bcbio"
subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] + channels +
["bcbio-nextgen>=%s" % version.__version__.replace("a0", "a")])
return os.path.dirname(os.path.dirname(conda_bin)) | python | def _update_conda_devel():
"""Update to the latest development conda package.
"""
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
assert conda_bin, "Could not find anaconda distribution for upgrading bcbio"
subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] + channels +
["bcbio-nextgen>=%s" % version.__version__.replace("a0", "a")])
return os.path.dirname(os.path.dirname(conda_bin)) | [
"def",
"_update_conda_devel",
"(",
")",
":",
"conda_bin",
"=",
"_get_conda_bin",
"(",
")",
"channels",
"=",
"_get_conda_channels",
"(",
"conda_bin",
")",
"assert",
"conda_bin",
",",
"\"Could not find anaconda distribution for upgrading bcbio\"",
"subprocess",
".",
"check_... | Update to the latest development conda package. | [
"Update",
"to",
"the",
"latest",
"development",
"conda",
"package",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L290-L298 |
223,384 | bcbio/bcbio-nextgen | bcbio/install.py | get_genome_dir | def get_genome_dir(gid, galaxy_dir, data):
"""Return standard location of genome directories.
"""
if galaxy_dir:
refs = genome.get_refs(gid, None, galaxy_dir, data)
seq_file = tz.get_in(["fasta", "base"], refs)
if seq_file and os.path.exists(seq_file):
return os.path.dirname(os.path.dirname(seq_file))
else:
gdirs = glob.glob(os.path.join(_get_data_dir(), "genomes", "*", gid))
if len(gdirs) == 1 and os.path.exists(gdirs[0]):
return gdirs[0] | python | def get_genome_dir(gid, galaxy_dir, data):
"""Return standard location of genome directories.
"""
if galaxy_dir:
refs = genome.get_refs(gid, None, galaxy_dir, data)
seq_file = tz.get_in(["fasta", "base"], refs)
if seq_file and os.path.exists(seq_file):
return os.path.dirname(os.path.dirname(seq_file))
else:
gdirs = glob.glob(os.path.join(_get_data_dir(), "genomes", "*", gid))
if len(gdirs) == 1 and os.path.exists(gdirs[0]):
return gdirs[0] | [
"def",
"get_genome_dir",
"(",
"gid",
",",
"galaxy_dir",
",",
"data",
")",
":",
"if",
"galaxy_dir",
":",
"refs",
"=",
"genome",
".",
"get_refs",
"(",
"gid",
",",
"None",
",",
"galaxy_dir",
",",
"data",
")",
"seq_file",
"=",
"tz",
".",
"get_in",
"(",
"... | Return standard location of genome directories. | [
"Return",
"standard",
"location",
"of",
"genome",
"directories",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L300-L311 |
223,385 | bcbio/bcbio-nextgen | bcbio/install.py | _prepare_cwl_tarballs | def _prepare_cwl_tarballs(data_dir):
"""Create CWL ready tarballs for complex directories.
Avoids need for CWL runners to pass and serialize complex directories
of files, which is inconsistent between runners.
"""
for dbref_dir in filter(os.path.isdir, glob.glob(os.path.join(data_dir, "genomes", "*", "*"))):
base_dir, dbref = os.path.split(dbref_dir)
for indexdir in TARBALL_DIRECTORIES:
cur_target = os.path.join(dbref_dir, indexdir)
if os.path.isdir(cur_target):
# Some indices, like rtg, have a single nested directory
subdirs = [x for x in os.listdir(cur_target) if os.path.isdir(os.path.join(cur_target, x))]
if len(subdirs) == 1:
cur_target = os.path.join(cur_target, subdirs[0])
create.directory_tarball(cur_target) | python | def _prepare_cwl_tarballs(data_dir):
"""Create CWL ready tarballs for complex directories.
Avoids need for CWL runners to pass and serialize complex directories
of files, which is inconsistent between runners.
"""
for dbref_dir in filter(os.path.isdir, glob.glob(os.path.join(data_dir, "genomes", "*", "*"))):
base_dir, dbref = os.path.split(dbref_dir)
for indexdir in TARBALL_DIRECTORIES:
cur_target = os.path.join(dbref_dir, indexdir)
if os.path.isdir(cur_target):
# Some indices, like rtg, have a single nested directory
subdirs = [x for x in os.listdir(cur_target) if os.path.isdir(os.path.join(cur_target, x))]
if len(subdirs) == 1:
cur_target = os.path.join(cur_target, subdirs[0])
create.directory_tarball(cur_target) | [
"def",
"_prepare_cwl_tarballs",
"(",
"data_dir",
")",
":",
"for",
"dbref_dir",
"in",
"filter",
"(",
"os",
".",
"path",
".",
"isdir",
",",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"genomes\"",
",",
"\"*\"",
",",
... | Create CWL ready tarballs for complex directories.
Avoids need for CWL runners to pass and serialize complex directories
of files, which is inconsistent between runners. | [
"Create",
"CWL",
"ready",
"tarballs",
"for",
"complex",
"directories",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L358-L373 |
223,386 | bcbio/bcbio-nextgen | bcbio/install.py | _upgrade_genome_resources | def _upgrade_genome_resources(galaxy_dir, base_url):
"""Retrieve latest version of genome resource YAML configuration files.
"""
import requests
for dbkey, ref_file in genome.get_builds(galaxy_dir):
# Check for a remote genome resources file
remote_url = base_url % dbkey
requests.packages.urllib3.disable_warnings()
r = requests.get(remote_url, verify=False)
if r.status_code == requests.codes.ok:
local_file = os.path.join(os.path.dirname(ref_file), os.path.basename(remote_url))
if os.path.exists(local_file):
with open(local_file) as in_handle:
local_config = yaml.safe_load(in_handle)
remote_config = yaml.safe_load(r.text)
needs_update = remote_config["version"] > local_config.get("version", 0)
if needs_update:
shutil.move(local_file, local_file + ".old%s" % local_config.get("version", 0))
else:
needs_update = True
if needs_update:
print("Updating %s genome resources configuration" % dbkey)
with open(local_file, "w") as out_handle:
out_handle.write(r.text) | python | def _upgrade_genome_resources(galaxy_dir, base_url):
"""Retrieve latest version of genome resource YAML configuration files.
"""
import requests
for dbkey, ref_file in genome.get_builds(galaxy_dir):
# Check for a remote genome resources file
remote_url = base_url % dbkey
requests.packages.urllib3.disable_warnings()
r = requests.get(remote_url, verify=False)
if r.status_code == requests.codes.ok:
local_file = os.path.join(os.path.dirname(ref_file), os.path.basename(remote_url))
if os.path.exists(local_file):
with open(local_file) as in_handle:
local_config = yaml.safe_load(in_handle)
remote_config = yaml.safe_load(r.text)
needs_update = remote_config["version"] > local_config.get("version", 0)
if needs_update:
shutil.move(local_file, local_file + ".old%s" % local_config.get("version", 0))
else:
needs_update = True
if needs_update:
print("Updating %s genome resources configuration" % dbkey)
with open(local_file, "w") as out_handle:
out_handle.write(r.text) | [
"def",
"_upgrade_genome_resources",
"(",
"galaxy_dir",
",",
"base_url",
")",
":",
"import",
"requests",
"for",
"dbkey",
",",
"ref_file",
"in",
"genome",
".",
"get_builds",
"(",
"galaxy_dir",
")",
":",
"# Check for a remote genome resources file",
"remote_url",
"=",
... | Retrieve latest version of genome resource YAML configuration files. | [
"Retrieve",
"latest",
"version",
"of",
"genome",
"resource",
"YAML",
"configuration",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L375-L398 |
223,387 | bcbio/bcbio-nextgen | bcbio/install.py | _upgrade_snpeff_data | def _upgrade_snpeff_data(galaxy_dir, args, remotes):
"""Install or upgrade snpEff databases, localized to reference directory.
"""
snpeff_version = effects.snpeff_version(args)
if not snpeff_version:
return
for dbkey, ref_file in genome.get_builds(galaxy_dir):
resource_file = os.path.join(os.path.dirname(ref_file), "%s-resources.yaml" % dbkey)
if os.path.exists(resource_file):
with open(resource_file) as in_handle:
resources = yaml.safe_load(in_handle)
snpeff_db, snpeff_base_dir = effects.get_db({"genome_resources": resources,
"reference": {"fasta": {"base": ref_file}}})
if snpeff_db:
snpeff_db_dir = os.path.join(snpeff_base_dir, snpeff_db)
if os.path.exists(snpeff_db_dir) and _is_old_database(snpeff_db_dir, args):
shutil.rmtree(snpeff_db_dir)
if not os.path.exists(snpeff_db_dir):
print("Installing snpEff database %s in %s" % (snpeff_db, snpeff_base_dir))
dl_url = remotes["snpeff_dl_url"].format(
snpeff_ver=snpeff_version.replace(".", "_"),
genome=snpeff_db)
dl_file = os.path.basename(dl_url)
with utils.chdir(snpeff_base_dir):
subprocess.check_call(["wget", "--no-check-certificate", "-c", "-O", dl_file, dl_url])
subprocess.check_call(["unzip", dl_file])
os.remove(dl_file)
dl_dir = os.path.join(snpeff_base_dir, "data", snpeff_db)
shutil.move(dl_dir, snpeff_db_dir)
os.rmdir(os.path.join(snpeff_base_dir, "data"))
if args.cwl:
create.directory_tarball(snpeff_db_dir) | python | def _upgrade_snpeff_data(galaxy_dir, args, remotes):
"""Install or upgrade snpEff databases, localized to reference directory.
"""
snpeff_version = effects.snpeff_version(args)
if not snpeff_version:
return
for dbkey, ref_file in genome.get_builds(galaxy_dir):
resource_file = os.path.join(os.path.dirname(ref_file), "%s-resources.yaml" % dbkey)
if os.path.exists(resource_file):
with open(resource_file) as in_handle:
resources = yaml.safe_load(in_handle)
snpeff_db, snpeff_base_dir = effects.get_db({"genome_resources": resources,
"reference": {"fasta": {"base": ref_file}}})
if snpeff_db:
snpeff_db_dir = os.path.join(snpeff_base_dir, snpeff_db)
if os.path.exists(snpeff_db_dir) and _is_old_database(snpeff_db_dir, args):
shutil.rmtree(snpeff_db_dir)
if not os.path.exists(snpeff_db_dir):
print("Installing snpEff database %s in %s" % (snpeff_db, snpeff_base_dir))
dl_url = remotes["snpeff_dl_url"].format(
snpeff_ver=snpeff_version.replace(".", "_"),
genome=snpeff_db)
dl_file = os.path.basename(dl_url)
with utils.chdir(snpeff_base_dir):
subprocess.check_call(["wget", "--no-check-certificate", "-c", "-O", dl_file, dl_url])
subprocess.check_call(["unzip", dl_file])
os.remove(dl_file)
dl_dir = os.path.join(snpeff_base_dir, "data", snpeff_db)
shutil.move(dl_dir, snpeff_db_dir)
os.rmdir(os.path.join(snpeff_base_dir, "data"))
if args.cwl:
create.directory_tarball(snpeff_db_dir) | [
"def",
"_upgrade_snpeff_data",
"(",
"galaxy_dir",
",",
"args",
",",
"remotes",
")",
":",
"snpeff_version",
"=",
"effects",
".",
"snpeff_version",
"(",
"args",
")",
"if",
"not",
"snpeff_version",
":",
"return",
"for",
"dbkey",
",",
"ref_file",
"in",
"genome",
... | Install or upgrade snpEff databases, localized to reference directory. | [
"Install",
"or",
"upgrade",
"snpEff",
"databases",
"localized",
"to",
"reference",
"directory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L404-L435 |
223,388 | bcbio/bcbio-nextgen | bcbio/install.py | _is_old_database | def _is_old_database(db_dir, args):
"""Check for old database versions, supported in snpEff 4.1.
"""
snpeff_version = effects.snpeff_version(args)
if LooseVersion(snpeff_version) >= LooseVersion("4.1"):
pred_file = os.path.join(db_dir, "snpEffectPredictor.bin")
if not utils.file_exists(pred_file):
return True
with utils.open_gzipsafe(pred_file, is_gz=True) as in_handle:
version_info = in_handle.readline().strip().split("\t")
program, version = version_info[:2]
if not program.lower() == "snpeff" or LooseVersion(snpeff_version) > LooseVersion(version):
return True
return False | python | def _is_old_database(db_dir, args):
"""Check for old database versions, supported in snpEff 4.1.
"""
snpeff_version = effects.snpeff_version(args)
if LooseVersion(snpeff_version) >= LooseVersion("4.1"):
pred_file = os.path.join(db_dir, "snpEffectPredictor.bin")
if not utils.file_exists(pred_file):
return True
with utils.open_gzipsafe(pred_file, is_gz=True) as in_handle:
version_info = in_handle.readline().strip().split("\t")
program, version = version_info[:2]
if not program.lower() == "snpeff" or LooseVersion(snpeff_version) > LooseVersion(version):
return True
return False | [
"def",
"_is_old_database",
"(",
"db_dir",
",",
"args",
")",
":",
"snpeff_version",
"=",
"effects",
".",
"snpeff_version",
"(",
"args",
")",
"if",
"LooseVersion",
"(",
"snpeff_version",
")",
">=",
"LooseVersion",
"(",
"\"4.1\"",
")",
":",
"pred_file",
"=",
"o... | Check for old database versions, supported in snpEff 4.1. | [
"Check",
"for",
"old",
"database",
"versions",
"supported",
"in",
"snpEff",
"4",
".",
"1",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L437-L450 |
223,389 | bcbio/bcbio-nextgen | bcbio/install.py | _get_biodata | def _get_biodata(base_file, args):
"""Retrieve biodata genome targets customized by install parameters.
"""
with open(base_file) as in_handle:
config = yaml.safe_load(in_handle)
config["install_liftover"] = False
config["genome_indexes"] = args.aligners
ann_groups = config.pop("annotation_groups", {})
config["genomes"] = [_setup_genome_annotations(g, args, ann_groups)
for g in config["genomes"] if g["dbkey"] in args.genomes]
return config | python | def _get_biodata(base_file, args):
"""Retrieve biodata genome targets customized by install parameters.
"""
with open(base_file) as in_handle:
config = yaml.safe_load(in_handle)
config["install_liftover"] = False
config["genome_indexes"] = args.aligners
ann_groups = config.pop("annotation_groups", {})
config["genomes"] = [_setup_genome_annotations(g, args, ann_groups)
for g in config["genomes"] if g["dbkey"] in args.genomes]
return config | [
"def",
"_get_biodata",
"(",
"base_file",
",",
"args",
")",
":",
"with",
"open",
"(",
"base_file",
")",
"as",
"in_handle",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"in_handle",
")",
"config",
"[",
"\"install_liftover\"",
"]",
"=",
"False",
"config... | Retrieve biodata genome targets customized by install parameters. | [
"Retrieve",
"biodata",
"genome",
"targets",
"customized",
"by",
"install",
"parameters",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L452-L462 |
223,390 | bcbio/bcbio-nextgen | bcbio/install.py | _setup_genome_annotations | def _setup_genome_annotations(g, args, ann_groups):
"""Configure genome annotations to install based on datatarget.
"""
available_anns = g.get("annotations", []) + g.pop("annotations_available", [])
anns = []
for orig_target in args.datatarget:
if orig_target in ann_groups:
targets = ann_groups[orig_target]
else:
targets = [orig_target]
for target in targets:
if target in available_anns:
anns.append(target)
g["annotations"] = anns
if "variation" not in args.datatarget and "validation" in g:
del g["validation"]
return g | python | def _setup_genome_annotations(g, args, ann_groups):
"""Configure genome annotations to install based on datatarget.
"""
available_anns = g.get("annotations", []) + g.pop("annotations_available", [])
anns = []
for orig_target in args.datatarget:
if orig_target in ann_groups:
targets = ann_groups[orig_target]
else:
targets = [orig_target]
for target in targets:
if target in available_anns:
anns.append(target)
g["annotations"] = anns
if "variation" not in args.datatarget and "validation" in g:
del g["validation"]
return g | [
"def",
"_setup_genome_annotations",
"(",
"g",
",",
"args",
",",
"ann_groups",
")",
":",
"available_anns",
"=",
"g",
".",
"get",
"(",
"\"annotations\"",
",",
"[",
"]",
")",
"+",
"g",
".",
"pop",
"(",
"\"annotations_available\"",
",",
"[",
"]",
")",
"anns"... | Configure genome annotations to install based on datatarget. | [
"Configure",
"genome",
"annotations",
"to",
"install",
"based",
"on",
"datatarget",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L464-L480 |
223,391 | bcbio/bcbio-nextgen | bcbio/install.py | upgrade_thirdparty_tools | def upgrade_thirdparty_tools(args, remotes):
"""Install and update third party tools used in the pipeline.
Creates a manifest directory with installed programs on the system.
"""
cbl = get_cloudbiolinux(remotes)
if args.toolconf and os.path.exists(args.toolconf):
package_yaml = args.toolconf
else:
package_yaml = os.path.join(cbl["dir"], "contrib", "flavor",
"ngs_pipeline_minimal", "packages-conda.yaml")
sys.path.insert(0, cbl["dir"])
cbl_conda = __import__("cloudbio.package.conda", fromlist=["conda"])
cbl_conda.install_in(_get_conda_bin(), args.tooldir, package_yaml)
manifest_dir = os.path.join(_get_data_dir(), "manifest")
print("Creating manifest of installed packages in %s" % manifest_dir)
cbl_manifest = __import__("cloudbio.manifest", fromlist=["manifest"])
if os.path.exists(manifest_dir):
for fname in os.listdir(manifest_dir):
if not fname.startswith("toolplus"):
os.remove(os.path.join(manifest_dir, fname))
cbl_manifest.create(manifest_dir, args.tooldir) | python | def upgrade_thirdparty_tools(args, remotes):
"""Install and update third party tools used in the pipeline.
Creates a manifest directory with installed programs on the system.
"""
cbl = get_cloudbiolinux(remotes)
if args.toolconf and os.path.exists(args.toolconf):
package_yaml = args.toolconf
else:
package_yaml = os.path.join(cbl["dir"], "contrib", "flavor",
"ngs_pipeline_minimal", "packages-conda.yaml")
sys.path.insert(0, cbl["dir"])
cbl_conda = __import__("cloudbio.package.conda", fromlist=["conda"])
cbl_conda.install_in(_get_conda_bin(), args.tooldir, package_yaml)
manifest_dir = os.path.join(_get_data_dir(), "manifest")
print("Creating manifest of installed packages in %s" % manifest_dir)
cbl_manifest = __import__("cloudbio.manifest", fromlist=["manifest"])
if os.path.exists(manifest_dir):
for fname in os.listdir(manifest_dir):
if not fname.startswith("toolplus"):
os.remove(os.path.join(manifest_dir, fname))
cbl_manifest.create(manifest_dir, args.tooldir) | [
"def",
"upgrade_thirdparty_tools",
"(",
"args",
",",
"remotes",
")",
":",
"cbl",
"=",
"get_cloudbiolinux",
"(",
"remotes",
")",
"if",
"args",
".",
"toolconf",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"args",
".",
"toolconf",
")",
":",
"package_yaml",
... | Install and update third party tools used in the pipeline.
Creates a manifest directory with installed programs on the system. | [
"Install",
"and",
"update",
"third",
"party",
"tools",
"used",
"in",
"the",
"pipeline",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L482-L503 |
223,392 | bcbio/bcbio-nextgen | bcbio/install.py | _install_toolplus | def _install_toolplus(args):
"""Install additional tools we cannot distribute, updating local manifest.
"""
manifest_dir = os.path.join(_get_data_dir(), "manifest")
toolplus_manifest = os.path.join(manifest_dir, "toolplus-packages.yaml")
system_config = os.path.join(_get_data_dir(), "galaxy", "bcbio_system.yaml")
# Handle toolplus installs inside Docker container
if not os.path.exists(system_config):
docker_system_config = os.path.join(_get_data_dir(), "config", "bcbio_system.yaml")
if os.path.exists(docker_system_config):
system_config = docker_system_config
toolplus_dir = os.path.join(_get_data_dir(), "toolplus")
for tool in args.toolplus:
if tool.name in set(["gatk", "mutect"]):
print("Installing %s" % tool.name)
_install_gatk_jar(tool.name, tool.fname, toolplus_manifest, system_config, toolplus_dir)
else:
raise ValueError("Unexpected toolplus argument: %s %s" % (tool.name, tool.fname)) | python | def _install_toolplus(args):
"""Install additional tools we cannot distribute, updating local manifest.
"""
manifest_dir = os.path.join(_get_data_dir(), "manifest")
toolplus_manifest = os.path.join(manifest_dir, "toolplus-packages.yaml")
system_config = os.path.join(_get_data_dir(), "galaxy", "bcbio_system.yaml")
# Handle toolplus installs inside Docker container
if not os.path.exists(system_config):
docker_system_config = os.path.join(_get_data_dir(), "config", "bcbio_system.yaml")
if os.path.exists(docker_system_config):
system_config = docker_system_config
toolplus_dir = os.path.join(_get_data_dir(), "toolplus")
for tool in args.toolplus:
if tool.name in set(["gatk", "mutect"]):
print("Installing %s" % tool.name)
_install_gatk_jar(tool.name, tool.fname, toolplus_manifest, system_config, toolplus_dir)
else:
raise ValueError("Unexpected toolplus argument: %s %s" % (tool.name, tool.fname)) | [
"def",
"_install_toolplus",
"(",
"args",
")",
":",
"manifest_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_get_data_dir",
"(",
")",
",",
"\"manifest\"",
")",
"toolplus_manifest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"manifest_dir",
",",
"\"toolplu... | Install additional tools we cannot distribute, updating local manifest. | [
"Install",
"additional",
"tools",
"we",
"cannot",
"distribute",
"updating",
"local",
"manifest",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L505-L522 |
223,393 | bcbio/bcbio-nextgen | bcbio/install.py | _install_gatk_jar | def _install_gatk_jar(name, fname, manifest, system_config, toolplus_dir):
"""Install a jar for GATK or associated tools like MuTect.
"""
if not fname.endswith(".jar"):
raise ValueError("--toolplus argument for %s expects a jar file: %s" % (name, fname))
version = get_gatk_jar_version(name, fname)
store_dir = utils.safe_makedir(os.path.join(toolplus_dir, name, version))
shutil.copyfile(fname, os.path.join(store_dir, os.path.basename(fname)))
_update_system_file(system_config, name, {"dir": store_dir})
_update_manifest(manifest, name, version) | python | def _install_gatk_jar(name, fname, manifest, system_config, toolplus_dir):
"""Install a jar for GATK or associated tools like MuTect.
"""
if not fname.endswith(".jar"):
raise ValueError("--toolplus argument for %s expects a jar file: %s" % (name, fname))
version = get_gatk_jar_version(name, fname)
store_dir = utils.safe_makedir(os.path.join(toolplus_dir, name, version))
shutil.copyfile(fname, os.path.join(store_dir, os.path.basename(fname)))
_update_system_file(system_config, name, {"dir": store_dir})
_update_manifest(manifest, name, version) | [
"def",
"_install_gatk_jar",
"(",
"name",
",",
"fname",
",",
"manifest",
",",
"system_config",
",",
"toolplus_dir",
")",
":",
"if",
"not",
"fname",
".",
"endswith",
"(",
"\".jar\"",
")",
":",
"raise",
"ValueError",
"(",
"\"--toolplus argument for %s expects a jar f... | Install a jar for GATK or associated tools like MuTect. | [
"Install",
"a",
"jar",
"for",
"GATK",
"or",
"associated",
"tools",
"like",
"MuTect",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L532-L541 |
223,394 | bcbio/bcbio-nextgen | bcbio/install.py | _update_manifest | def _update_manifest(manifest_file, name, version):
"""Update the toolplus manifest file with updated name and version
"""
if os.path.exists(manifest_file):
with open(manifest_file) as in_handle:
manifest = yaml.safe_load(in_handle)
else:
manifest = {}
manifest[name] = {"name": name, "version": version}
with open(manifest_file, "w") as out_handle:
yaml.safe_dump(manifest, out_handle, default_flow_style=False, allow_unicode=False) | python | def _update_manifest(manifest_file, name, version):
"""Update the toolplus manifest file with updated name and version
"""
if os.path.exists(manifest_file):
with open(manifest_file) as in_handle:
manifest = yaml.safe_load(in_handle)
else:
manifest = {}
manifest[name] = {"name": name, "version": version}
with open(manifest_file, "w") as out_handle:
yaml.safe_dump(manifest, out_handle, default_flow_style=False, allow_unicode=False) | [
"def",
"_update_manifest",
"(",
"manifest_file",
",",
"name",
",",
"version",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"manifest_file",
")",
":",
"with",
"open",
"(",
"manifest_file",
")",
"as",
"in_handle",
":",
"manifest",
"=",
"yaml",
".... | Update the toolplus manifest file with updated name and version | [
"Update",
"the",
"toolplus",
"manifest",
"file",
"with",
"updated",
"name",
"and",
"version"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L543-L553 |
223,395 | bcbio/bcbio-nextgen | bcbio/install.py | _update_system_file | def _update_system_file(system_file, name, new_kvs):
"""Update the bcbio_system.yaml file with new resource information.
"""
if os.path.exists(system_file):
bak_file = system_file + ".bak%s" % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
shutil.copyfile(system_file, bak_file)
with open(system_file) as in_handle:
config = yaml.safe_load(in_handle)
else:
utils.safe_makedir(os.path.dirname(system_file))
config = {}
new_rs = {}
added = False
for rname, r_kvs in config.get("resources", {}).items():
if rname == name:
for k, v in new_kvs.items():
r_kvs[k] = v
added = True
new_rs[rname] = r_kvs
if not added:
new_rs[name] = new_kvs
config["resources"] = new_rs
with open(system_file, "w") as out_handle:
yaml.safe_dump(config, out_handle, default_flow_style=False, allow_unicode=False) | python | def _update_system_file(system_file, name, new_kvs):
"""Update the bcbio_system.yaml file with new resource information.
"""
if os.path.exists(system_file):
bak_file = system_file + ".bak%s" % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
shutil.copyfile(system_file, bak_file)
with open(system_file) as in_handle:
config = yaml.safe_load(in_handle)
else:
utils.safe_makedir(os.path.dirname(system_file))
config = {}
new_rs = {}
added = False
for rname, r_kvs in config.get("resources", {}).items():
if rname == name:
for k, v in new_kvs.items():
r_kvs[k] = v
added = True
new_rs[rname] = r_kvs
if not added:
new_rs[name] = new_kvs
config["resources"] = new_rs
with open(system_file, "w") as out_handle:
yaml.safe_dump(config, out_handle, default_flow_style=False, allow_unicode=False) | [
"def",
"_update_system_file",
"(",
"system_file",
",",
"name",
",",
"new_kvs",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"system_file",
")",
":",
"bak_file",
"=",
"system_file",
"+",
"\".bak%s\"",
"%",
"datetime",
".",
"datetime",
".",
"now",
... | Update the bcbio_system.yaml file with new resource information. | [
"Update",
"the",
"bcbio_system",
".",
"yaml",
"file",
"with",
"new",
"resource",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L555-L578 |
223,396 | bcbio/bcbio-nextgen | bcbio/install.py | _install_kraken_db | def _install_kraken_db(datadir, args):
"""Install kraken minimal DB in genome folder.
"""
import requests
kraken = os.path.join(datadir, "genomes/kraken")
url = "https://ccb.jhu.edu/software/kraken/dl/minikraken.tgz"
compress = os.path.join(kraken, os.path.basename(url))
base, ext = utils.splitext_plus(os.path.basename(url))
db = os.path.join(kraken, base)
tooldir = args.tooldir or get_defaults()["tooldir"]
requests.packages.urllib3.disable_warnings()
last_mod = urllib.request.urlopen(url).info().get('Last-Modified')
last_mod = dateutil.parser.parse(last_mod).astimezone(dateutil.tz.tzutc())
if os.path.exists(os.path.join(tooldir, "bin", "kraken")):
if not os.path.exists(db):
is_new_version = True
else:
cur_file = glob.glob(os.path.join(kraken, "minikraken_*"))[0]
cur_version = datetime.datetime.utcfromtimestamp(os.path.getmtime(cur_file))
is_new_version = last_mod.date() > cur_version.date()
if is_new_version:
shutil.move(cur_file, cur_file.replace('minikraken', 'old'))
if not os.path.exists(kraken):
utils.safe_makedir(kraken)
if is_new_version:
if not os.path.exists(compress):
subprocess.check_call(["wget", "-O", compress, url, "--no-check-certificate"])
cmd = ["tar", "-xzvf", compress, "-C", kraken]
subprocess.check_call(cmd)
last_version = glob.glob(os.path.join(kraken, "minikraken_*"))
utils.symlink_plus(os.path.join(kraken, last_version[0]), os.path.join(kraken, "minikraken"))
utils.remove_safe(compress)
else:
print("You have the latest version %s." % last_mod)
else:
raise argparse.ArgumentTypeError("kraken not installed in tooldir %s." %
os.path.join(tooldir, "bin", "kraken")) | python | def _install_kraken_db(datadir, args):
"""Install kraken minimal DB in genome folder.
"""
import requests
kraken = os.path.join(datadir, "genomes/kraken")
url = "https://ccb.jhu.edu/software/kraken/dl/minikraken.tgz"
compress = os.path.join(kraken, os.path.basename(url))
base, ext = utils.splitext_plus(os.path.basename(url))
db = os.path.join(kraken, base)
tooldir = args.tooldir or get_defaults()["tooldir"]
requests.packages.urllib3.disable_warnings()
last_mod = urllib.request.urlopen(url).info().get('Last-Modified')
last_mod = dateutil.parser.parse(last_mod).astimezone(dateutil.tz.tzutc())
if os.path.exists(os.path.join(tooldir, "bin", "kraken")):
if not os.path.exists(db):
is_new_version = True
else:
cur_file = glob.glob(os.path.join(kraken, "minikraken_*"))[0]
cur_version = datetime.datetime.utcfromtimestamp(os.path.getmtime(cur_file))
is_new_version = last_mod.date() > cur_version.date()
if is_new_version:
shutil.move(cur_file, cur_file.replace('minikraken', 'old'))
if not os.path.exists(kraken):
utils.safe_makedir(kraken)
if is_new_version:
if not os.path.exists(compress):
subprocess.check_call(["wget", "-O", compress, url, "--no-check-certificate"])
cmd = ["tar", "-xzvf", compress, "-C", kraken]
subprocess.check_call(cmd)
last_version = glob.glob(os.path.join(kraken, "minikraken_*"))
utils.symlink_plus(os.path.join(kraken, last_version[0]), os.path.join(kraken, "minikraken"))
utils.remove_safe(compress)
else:
print("You have the latest version %s." % last_mod)
else:
raise argparse.ArgumentTypeError("kraken not installed in tooldir %s." %
os.path.join(tooldir, "bin", "kraken")) | [
"def",
"_install_kraken_db",
"(",
"datadir",
",",
"args",
")",
":",
"import",
"requests",
"kraken",
"=",
"os",
".",
"path",
".",
"join",
"(",
"datadir",
",",
"\"genomes/kraken\"",
")",
"url",
"=",
"\"https://ccb.jhu.edu/software/kraken/dl/minikraken.tgz\"",
"compres... | Install kraken minimal DB in genome folder. | [
"Install",
"kraken",
"minimal",
"DB",
"in",
"genome",
"folder",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L580-L616 |
223,397 | bcbio/bcbio-nextgen | bcbio/install.py | _get_install_config | def _get_install_config():
"""Return the YAML configuration file used to store upgrade information.
"""
try:
data_dir = _get_data_dir()
except ValueError:
return None
config_dir = utils.safe_makedir(os.path.join(data_dir, "config"))
return os.path.join(config_dir, "install-params.yaml") | python | def _get_install_config():
"""Return the YAML configuration file used to store upgrade information.
"""
try:
data_dir = _get_data_dir()
except ValueError:
return None
config_dir = utils.safe_makedir(os.path.join(data_dir, "config"))
return os.path.join(config_dir, "install-params.yaml") | [
"def",
"_get_install_config",
"(",
")",
":",
"try",
":",
"data_dir",
"=",
"_get_data_dir",
"(",
")",
"except",
"ValueError",
":",
"return",
"None",
"config_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
... | Return the YAML configuration file used to store upgrade information. | [
"Return",
"the",
"YAML",
"configuration",
"file",
"used",
"to",
"store",
"upgrade",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L620-L628 |
223,398 | bcbio/bcbio-nextgen | bcbio/install.py | save_install_defaults | def save_install_defaults(args):
"""Save installation information to make future upgrades easier.
"""
install_config = _get_install_config()
if install_config is None:
return
if utils.file_exists(install_config):
with open(install_config) as in_handle:
cur_config = yaml.safe_load(in_handle)
else:
cur_config = {}
if args.tooldir:
cur_config["tooldir"] = args.tooldir
cur_config["isolate"] = args.isolate
for attr in ["genomes", "aligners", "datatarget"]:
if not cur_config.get(attr):
cur_config[attr] = []
for x in getattr(args, attr):
if x not in cur_config[attr]:
cur_config[attr].append(x)
# toolplus -- save non-filename inputs
attr = "toolplus"
if not cur_config.get(attr):
cur_config[attr] = []
for x in getattr(args, attr):
if not x.fname:
if x.name not in cur_config[attr]:
cur_config[attr].append(x.name)
with open(install_config, "w") as out_handle:
yaml.safe_dump(cur_config, out_handle, default_flow_style=False, allow_unicode=False) | python | def save_install_defaults(args):
"""Save installation information to make future upgrades easier.
"""
install_config = _get_install_config()
if install_config is None:
return
if utils.file_exists(install_config):
with open(install_config) as in_handle:
cur_config = yaml.safe_load(in_handle)
else:
cur_config = {}
if args.tooldir:
cur_config["tooldir"] = args.tooldir
cur_config["isolate"] = args.isolate
for attr in ["genomes", "aligners", "datatarget"]:
if not cur_config.get(attr):
cur_config[attr] = []
for x in getattr(args, attr):
if x not in cur_config[attr]:
cur_config[attr].append(x)
# toolplus -- save non-filename inputs
attr = "toolplus"
if not cur_config.get(attr):
cur_config[attr] = []
for x in getattr(args, attr):
if not x.fname:
if x.name not in cur_config[attr]:
cur_config[attr].append(x.name)
with open(install_config, "w") as out_handle:
yaml.safe_dump(cur_config, out_handle, default_flow_style=False, allow_unicode=False) | [
"def",
"save_install_defaults",
"(",
"args",
")",
":",
"install_config",
"=",
"_get_install_config",
"(",
")",
"if",
"install_config",
"is",
"None",
":",
"return",
"if",
"utils",
".",
"file_exists",
"(",
"install_config",
")",
":",
"with",
"open",
"(",
"instal... | Save installation information to make future upgrades easier. | [
"Save",
"installation",
"information",
"to",
"make",
"future",
"upgrades",
"easier",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L630-L659 |
223,399 | bcbio/bcbio-nextgen | bcbio/install.py | add_install_defaults | def add_install_defaults(args):
"""Add any saved installation defaults to the upgrade.
"""
# Ensure we install data if we've specified any secondary installation targets
if len(args.genomes) > 0 or len(args.aligners) > 0 or len(args.datatarget) > 0:
args.install_data = True
install_config = _get_install_config()
if install_config is None or not utils.file_exists(install_config):
default_args = {}
else:
with open(install_config) as in_handle:
default_args = yaml.safe_load(in_handle)
# if we are upgrading to development, also upgrade the tools
if args.upgrade in ["development"] and (args.tooldir or "tooldir" in default_args):
args.tools = True
if args.tools and args.tooldir is None:
if "tooldir" in default_args:
args.tooldir = str(default_args["tooldir"])
else:
raise ValueError("Default tool directory not yet saved in config defaults. "
"Specify the '--tooldir=/path/to/tools' to upgrade tools. "
"After a successful upgrade, the '--tools' parameter will "
"work for future upgrades.")
for attr in ["genomes", "aligners"]:
# don't upgrade default genomes if a genome was specified
if attr == "genomes" and len(args.genomes) > 0:
continue
for x in default_args.get(attr, []):
x = str(x)
new_val = getattr(args, attr)
if x not in getattr(args, attr):
new_val.append(x)
setattr(args, attr, new_val)
args = _datatarget_defaults(args, default_args)
if "isolate" in default_args and args.isolate is not True:
args.isolate = default_args["isolate"]
return args | python | def add_install_defaults(args):
"""Add any saved installation defaults to the upgrade.
"""
# Ensure we install data if we've specified any secondary installation targets
if len(args.genomes) > 0 or len(args.aligners) > 0 or len(args.datatarget) > 0:
args.install_data = True
install_config = _get_install_config()
if install_config is None or not utils.file_exists(install_config):
default_args = {}
else:
with open(install_config) as in_handle:
default_args = yaml.safe_load(in_handle)
# if we are upgrading to development, also upgrade the tools
if args.upgrade in ["development"] and (args.tooldir or "tooldir" in default_args):
args.tools = True
if args.tools and args.tooldir is None:
if "tooldir" in default_args:
args.tooldir = str(default_args["tooldir"])
else:
raise ValueError("Default tool directory not yet saved in config defaults. "
"Specify the '--tooldir=/path/to/tools' to upgrade tools. "
"After a successful upgrade, the '--tools' parameter will "
"work for future upgrades.")
for attr in ["genomes", "aligners"]:
# don't upgrade default genomes if a genome was specified
if attr == "genomes" and len(args.genomes) > 0:
continue
for x in default_args.get(attr, []):
x = str(x)
new_val = getattr(args, attr)
if x not in getattr(args, attr):
new_val.append(x)
setattr(args, attr, new_val)
args = _datatarget_defaults(args, default_args)
if "isolate" in default_args and args.isolate is not True:
args.isolate = default_args["isolate"]
return args | [
"def",
"add_install_defaults",
"(",
"args",
")",
":",
"# Ensure we install data if we've specified any secondary installation targets",
"if",
"len",
"(",
"args",
".",
"genomes",
")",
">",
"0",
"or",
"len",
"(",
"args",
".",
"aligners",
")",
">",
"0",
"or",
"len",
... | Add any saved installation defaults to the upgrade. | [
"Add",
"any",
"saved",
"installation",
"defaults",
"to",
"the",
"upgrade",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L661-L697 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.