id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
224,100 | bcbio/bcbio-nextgen | bcbio/distributed/resources.py | _scale_cores_to_memory | def _scale_cores_to_memory(cores, mem_per_core, sysinfo, system_memory):
"""Scale multicore usage to avoid excessive memory usage based on system information.
"""
total_mem = "%.2f" % (cores * mem_per_core + system_memory)
if "cores" not in sysinfo:
return cores, total_mem, 1.0
total_mem = min(float(total_mem), float(sysinfo["memory"]) - system_memory)
cores = min(cores, int(sysinfo["cores"]))
mem_cores = int(math.floor(float(total_mem) / mem_per_core)) # cores based on available memory
if mem_cores < 1:
out_cores = 1
elif mem_cores < cores:
out_cores = mem_cores
else:
out_cores = cores
mem_pct = float(out_cores) / float(cores)
return out_cores, total_mem, mem_pct | python | def _scale_cores_to_memory(cores, mem_per_core, sysinfo, system_memory):
"""Scale multicore usage to avoid excessive memory usage based on system information.
"""
total_mem = "%.2f" % (cores * mem_per_core + system_memory)
if "cores" not in sysinfo:
return cores, total_mem, 1.0
total_mem = min(float(total_mem), float(sysinfo["memory"]) - system_memory)
cores = min(cores, int(sysinfo["cores"]))
mem_cores = int(math.floor(float(total_mem) / mem_per_core)) # cores based on available memory
if mem_cores < 1:
out_cores = 1
elif mem_cores < cores:
out_cores = mem_cores
else:
out_cores = cores
mem_pct = float(out_cores) / float(cores)
return out_cores, total_mem, mem_pct | [
"def",
"_scale_cores_to_memory",
"(",
"cores",
",",
"mem_per_core",
",",
"sysinfo",
",",
"system_memory",
")",
":",
"total_mem",
"=",
"\"%.2f\"",
"%",
"(",
"cores",
"*",
"mem_per_core",
"+",
"system_memory",
")",
"if",
"\"cores\"",
"not",
"in",
"sysinfo",
":",... | Scale multicore usage to avoid excessive memory usage based on system information. | [
"Scale",
"multicore",
"usage",
"to",
"avoid",
"excessive",
"memory",
"usage",
"based",
"on",
"system",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L100-L117 |
224,101 | bcbio/bcbio-nextgen | bcbio/distributed/resources.py | _scale_jobs_to_memory | def _scale_jobs_to_memory(jobs, mem_per_core, sysinfo):
"""When scheduling jobs with single cores, avoid overscheduling due to memory.
"""
if "cores" not in sysinfo:
return jobs, 1.0
sys_mem_per_core = float(sysinfo["memory"]) / float(sysinfo["cores"])
if sys_mem_per_core < mem_per_core:
pct = sys_mem_per_core / float(mem_per_core)
target_jobs = int(math.floor(jobs * pct))
return max(target_jobs, 1), pct
else:
return jobs, 1.0 | python | def _scale_jobs_to_memory(jobs, mem_per_core, sysinfo):
"""When scheduling jobs with single cores, avoid overscheduling due to memory.
"""
if "cores" not in sysinfo:
return jobs, 1.0
sys_mem_per_core = float(sysinfo["memory"]) / float(sysinfo["cores"])
if sys_mem_per_core < mem_per_core:
pct = sys_mem_per_core / float(mem_per_core)
target_jobs = int(math.floor(jobs * pct))
return max(target_jobs, 1), pct
else:
return jobs, 1.0 | [
"def",
"_scale_jobs_to_memory",
"(",
"jobs",
",",
"mem_per_core",
",",
"sysinfo",
")",
":",
"if",
"\"cores\"",
"not",
"in",
"sysinfo",
":",
"return",
"jobs",
",",
"1.0",
"sys_mem_per_core",
"=",
"float",
"(",
"sysinfo",
"[",
"\"memory\"",
"]",
")",
"/",
"f... | When scheduling jobs with single cores, avoid overscheduling due to memory. | [
"When",
"scheduling",
"jobs",
"with",
"single",
"cores",
"avoid",
"overscheduling",
"due",
"to",
"memory",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L119-L130 |
224,102 | bcbio/bcbio-nextgen | bcbio/distributed/resources.py | calculate | def calculate(parallel, items, sysinfo, config, multiplier=1,
max_multicore=None):
"""Determine cores and workers to use for this stage based on used programs.
multiplier specifies the number of regions items will be split into during
processing.
max_multicore specifies an optional limit on the maximum cores. Can use to
force single core processing during specific tasks.
sysinfo specifies cores and memory on processing nodes, allowing us to tailor
jobs for available resources.
"""
assert len(items) > 0, "Finding job resources but no items to process"
all_cores = []
all_memory = []
# Provide 100Mb of additional memory for the system
system_memory = 0.10
algs = [config_utils.get_algorithm_config(x) for x in items]
progs = _get_resource_programs(parallel.get("progs", []), algs)
# Calculate cores
for prog in progs:
resources = config_utils.get_resources(prog, config)
all_cores.append(resources.get("cores", 1))
if len(all_cores) == 0:
all_cores.append(1)
cores_per_job = max(all_cores)
if max_multicore:
cores_per_job = min(cores_per_job, max_multicore)
if "cores" in sysinfo:
cores_per_job = min(cores_per_job, int(sysinfo["cores"]))
total = parallel["cores"]
if total > cores_per_job:
num_jobs = total // cores_per_job
else:
num_jobs, cores_per_job = 1, total
# Calculate memory. Use 1Gb memory usage per core as min baseline if not specified
for prog in progs:
resources = config_utils.get_resources(prog, config)
memory = _get_prog_memory(resources, cores_per_job)
if memory:
all_memory.append(memory)
if len(all_memory) == 0:
all_memory.append(1)
memory_per_core = max(all_memory)
logger.debug("Resource requests: {progs}; memory: {memory}; cores: {cores}".format(
progs=", ".join(progs), memory=", ".join("%.2f" % x for x in all_memory),
cores=", ".join(str(x) for x in all_cores)))
cores_per_job, memory_per_core = _ensure_min_resources(progs, cores_per_job, memory_per_core,
min_memory=parallel.get("ensure_mem", {}))
if cores_per_job == 1:
memory_per_job = "%.2f" % memory_per_core
num_jobs, mem_pct = _scale_jobs_to_memory(num_jobs, memory_per_core, sysinfo)
# For single core jobs, avoid overscheduling maximum cores_per_job
num_jobs = min(num_jobs, total)
else:
cores_per_job, memory_per_job, mem_pct = _scale_cores_to_memory(cores_per_job,
memory_per_core, sysinfo,
system_memory)
# For local runs with multiple jobs and multiple cores, potentially scale jobs down
if num_jobs > 1 and parallel.get("type") == "local":
memory_per_core = float(memory_per_job) / cores_per_job
num_jobs, _ = _scale_jobs_to_memory(num_jobs, memory_per_core, sysinfo)
# do not overschedule if we don't have extra items to process
num_jobs = int(min(num_jobs, len(items) * multiplier))
logger.debug("Configuring %d jobs to run, using %d cores each with %sg of "
"memory reserved for each job" % (num_jobs, cores_per_job,
str(memory_per_job)))
parallel = copy.deepcopy(parallel)
parallel["cores_per_job"] = cores_per_job
parallel["num_jobs"] = num_jobs
parallel["mem"] = str(memory_per_job)
parallel["mem_pct"] = "%.2f" % mem_pct
parallel["system_cores"] = sysinfo.get("cores", 1)
return parallel | python | def calculate(parallel, items, sysinfo, config, multiplier=1,
max_multicore=None):
"""Determine cores and workers to use for this stage based on used programs.
multiplier specifies the number of regions items will be split into during
processing.
max_multicore specifies an optional limit on the maximum cores. Can use to
force single core processing during specific tasks.
sysinfo specifies cores and memory on processing nodes, allowing us to tailor
jobs for available resources.
"""
assert len(items) > 0, "Finding job resources but no items to process"
all_cores = []
all_memory = []
# Provide 100Mb of additional memory for the system
system_memory = 0.10
algs = [config_utils.get_algorithm_config(x) for x in items]
progs = _get_resource_programs(parallel.get("progs", []), algs)
# Calculate cores
for prog in progs:
resources = config_utils.get_resources(prog, config)
all_cores.append(resources.get("cores", 1))
if len(all_cores) == 0:
all_cores.append(1)
cores_per_job = max(all_cores)
if max_multicore:
cores_per_job = min(cores_per_job, max_multicore)
if "cores" in sysinfo:
cores_per_job = min(cores_per_job, int(sysinfo["cores"]))
total = parallel["cores"]
if total > cores_per_job:
num_jobs = total // cores_per_job
else:
num_jobs, cores_per_job = 1, total
# Calculate memory. Use 1Gb memory usage per core as min baseline if not specified
for prog in progs:
resources = config_utils.get_resources(prog, config)
memory = _get_prog_memory(resources, cores_per_job)
if memory:
all_memory.append(memory)
if len(all_memory) == 0:
all_memory.append(1)
memory_per_core = max(all_memory)
logger.debug("Resource requests: {progs}; memory: {memory}; cores: {cores}".format(
progs=", ".join(progs), memory=", ".join("%.2f" % x for x in all_memory),
cores=", ".join(str(x) for x in all_cores)))
cores_per_job, memory_per_core = _ensure_min_resources(progs, cores_per_job, memory_per_core,
min_memory=parallel.get("ensure_mem", {}))
if cores_per_job == 1:
memory_per_job = "%.2f" % memory_per_core
num_jobs, mem_pct = _scale_jobs_to_memory(num_jobs, memory_per_core, sysinfo)
# For single core jobs, avoid overscheduling maximum cores_per_job
num_jobs = min(num_jobs, total)
else:
cores_per_job, memory_per_job, mem_pct = _scale_cores_to_memory(cores_per_job,
memory_per_core, sysinfo,
system_memory)
# For local runs with multiple jobs and multiple cores, potentially scale jobs down
if num_jobs > 1 and parallel.get("type") == "local":
memory_per_core = float(memory_per_job) / cores_per_job
num_jobs, _ = _scale_jobs_to_memory(num_jobs, memory_per_core, sysinfo)
# do not overschedule if we don't have extra items to process
num_jobs = int(min(num_jobs, len(items) * multiplier))
logger.debug("Configuring %d jobs to run, using %d cores each with %sg of "
"memory reserved for each job" % (num_jobs, cores_per_job,
str(memory_per_job)))
parallel = copy.deepcopy(parallel)
parallel["cores_per_job"] = cores_per_job
parallel["num_jobs"] = num_jobs
parallel["mem"] = str(memory_per_job)
parallel["mem_pct"] = "%.2f" % mem_pct
parallel["system_cores"] = sysinfo.get("cores", 1)
return parallel | [
"def",
"calculate",
"(",
"parallel",
",",
"items",
",",
"sysinfo",
",",
"config",
",",
"multiplier",
"=",
"1",
",",
"max_multicore",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"items",
")",
">",
"0",
",",
"\"Finding job resources but no items to process\"",
... | Determine cores and workers to use for this stage based on used programs.
multiplier specifies the number of regions items will be split into during
processing.
max_multicore specifies an optional limit on the maximum cores. Can use to
force single core processing during specific tasks.
sysinfo specifies cores and memory on processing nodes, allowing us to tailor
jobs for available resources. | [
"Determine",
"cores",
"and",
"workers",
"to",
"use",
"for",
"this",
"stage",
"based",
"on",
"used",
"programs",
".",
"multiplier",
"specifies",
"the",
"number",
"of",
"regions",
"items",
"will",
"be",
"split",
"into",
"during",
"processing",
".",
"max_multicor... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L159-L234 |
224,103 | bcbio/bcbio-nextgen | bcbio/ngsalign/hisat2.py | create_splicesites_file | def create_splicesites_file(gtf_file, align_dir, data):
"""
if not pre-created, make a splicesites file to use with hisat2
"""
out_file = os.path.join(align_dir, "ref-transcripts-splicesites.txt")
if file_exists(out_file):
return out_file
safe_makedir(align_dir)
hisat2_ss = config_utils.get_program("hisat2_extract_splice_sites.py", data)
cmd = "{hisat2_ss} {gtf_file} > {tx_out_file}"
message = "Creating hisat2 splicesites file from %s." % gtf_file
with file_transaction(out_file) as tx_out_file:
do.run(cmd.format(**locals()), message)
return out_file | python | def create_splicesites_file(gtf_file, align_dir, data):
"""
if not pre-created, make a splicesites file to use with hisat2
"""
out_file = os.path.join(align_dir, "ref-transcripts-splicesites.txt")
if file_exists(out_file):
return out_file
safe_makedir(align_dir)
hisat2_ss = config_utils.get_program("hisat2_extract_splice_sites.py", data)
cmd = "{hisat2_ss} {gtf_file} > {tx_out_file}"
message = "Creating hisat2 splicesites file from %s." % gtf_file
with file_transaction(out_file) as tx_out_file:
do.run(cmd.format(**locals()), message)
return out_file | [
"def",
"create_splicesites_file",
"(",
"gtf_file",
",",
"align_dir",
",",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"align_dir",
",",
"\"ref-transcripts-splicesites.txt\"",
")",
"if",
"file_exists",
"(",
"out_file",
")",
":",
"ret... | if not pre-created, make a splicesites file to use with hisat2 | [
"if",
"not",
"pre",
"-",
"created",
"make",
"a",
"splicesites",
"file",
"to",
"use",
"with",
"hisat2"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/hisat2.py#L63-L76 |
224,104 | bcbio/bcbio-nextgen | bcbio/ngsalign/hisat2.py | get_splicejunction_file | def get_splicejunction_file(align_dir, data):
"""
locate the splice junction file from hisat2. hisat2 outputs a novel
splicesites file to go along with the provided file, if available.
this combines the two together and outputs a combined file of all
of the known and novel splice junctions
"""
samplename = dd.get_sample_name(data)
align_dir = os.path.dirname(dd.get_work_bam(data))
knownfile = get_known_splicesites_file(align_dir, data)
novelfile = os.path.join(align_dir, "%s-novelsplicesites.bed" % samplename)
bed_files = [x for x in [knownfile, novelfile] if file_exists(x)]
splicejunction = bed.concat(bed_files)
splicejunctionfile = os.path.join(align_dir,
"%s-splicejunctions.bed" % samplename)
if splicejunction:
splicejunction.saveas(splicejunctionfile)
return splicejunctionfile
else:
return None | python | def get_splicejunction_file(align_dir, data):
"""
locate the splice junction file from hisat2. hisat2 outputs a novel
splicesites file to go along with the provided file, if available.
this combines the two together and outputs a combined file of all
of the known and novel splice junctions
"""
samplename = dd.get_sample_name(data)
align_dir = os.path.dirname(dd.get_work_bam(data))
knownfile = get_known_splicesites_file(align_dir, data)
novelfile = os.path.join(align_dir, "%s-novelsplicesites.bed" % samplename)
bed_files = [x for x in [knownfile, novelfile] if file_exists(x)]
splicejunction = bed.concat(bed_files)
splicejunctionfile = os.path.join(align_dir,
"%s-splicejunctions.bed" % samplename)
if splicejunction:
splicejunction.saveas(splicejunctionfile)
return splicejunctionfile
else:
return None | [
"def",
"get_splicejunction_file",
"(",
"align_dir",
",",
"data",
")",
":",
"samplename",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"align_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dd",
".",
"get_work_bam",
"(",
"data",
")",
")",
"kno... | locate the splice junction file from hisat2. hisat2 outputs a novel
splicesites file to go along with the provided file, if available.
this combines the two together and outputs a combined file of all
of the known and novel splice junctions | [
"locate",
"the",
"splice",
"junction",
"file",
"from",
"hisat2",
".",
"hisat2",
"outputs",
"a",
"novel",
"splicesites",
"file",
"to",
"go",
"along",
"with",
"the",
"provided",
"file",
"if",
"available",
".",
"this",
"combines",
"the",
"two",
"together",
"and... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/hisat2.py#L127-L146 |
224,105 | bcbio/bcbio-nextgen | bcbio/provenance/system.py | write_info | def write_info(dirs, parallel, config):
"""Write cluster or local filesystem resources, spinning up cluster if not present.
"""
if parallel["type"] in ["ipython"] and not parallel.get("run_local"):
out_file = _get_cache_file(dirs, parallel)
if not utils.file_exists(out_file):
sys_config = copy.deepcopy(config)
minfos = _get_machine_info(parallel, sys_config, dirs, config)
with open(out_file, "w") as out_handle:
yaml.safe_dump(minfos, out_handle, default_flow_style=False, allow_unicode=False) | python | def write_info(dirs, parallel, config):
"""Write cluster or local filesystem resources, spinning up cluster if not present.
"""
if parallel["type"] in ["ipython"] and not parallel.get("run_local"):
out_file = _get_cache_file(dirs, parallel)
if not utils.file_exists(out_file):
sys_config = copy.deepcopy(config)
minfos = _get_machine_info(parallel, sys_config, dirs, config)
with open(out_file, "w") as out_handle:
yaml.safe_dump(minfos, out_handle, default_flow_style=False, allow_unicode=False) | [
"def",
"write_info",
"(",
"dirs",
",",
"parallel",
",",
"config",
")",
":",
"if",
"parallel",
"[",
"\"type\"",
"]",
"in",
"[",
"\"ipython\"",
"]",
"and",
"not",
"parallel",
".",
"get",
"(",
"\"run_local\"",
")",
":",
"out_file",
"=",
"_get_cache_file",
"... | Write cluster or local filesystem resources, spinning up cluster if not present. | [
"Write",
"cluster",
"or",
"local",
"filesystem",
"resources",
"spinning",
"up",
"cluster",
"if",
"not",
"present",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L25-L34 |
224,106 | bcbio/bcbio-nextgen | bcbio/provenance/system.py | _get_machine_info | def _get_machine_info(parallel, sys_config, dirs, config):
"""Get machine resource information from the job scheduler via either the command line or the queue.
"""
if parallel.get("queue") and parallel.get("scheduler"):
# dictionary as switch statement; can add new scheduler implementation functions as (lowercase) keys
sched_info_dict = {
"slurm": _slurm_info,
"torque": _torque_info,
"sge": _sge_info
}
if parallel["scheduler"].lower() in sched_info_dict:
try:
return sched_info_dict[parallel["scheduler"].lower()](parallel.get("queue", ""))
except:
# If something goes wrong, just hit the queue
logger.exception("Couldn't get machine information from resource query function for queue "
"'{0}' on scheduler \"{1}\"; "
"submitting job to queue".format(parallel.get("queue", ""), parallel["scheduler"]))
else:
logger.info("Resource query function not implemented for scheduler \"{0}\"; "
"submitting job to queue".format(parallel["scheduler"]))
from bcbio.distributed import prun
with prun.start(parallel, [[sys_config]], config, dirs) as run_parallel:
return run_parallel("machine_info", [[sys_config]]) | python | def _get_machine_info(parallel, sys_config, dirs, config):
"""Get machine resource information from the job scheduler via either the command line or the queue.
"""
if parallel.get("queue") and parallel.get("scheduler"):
# dictionary as switch statement; can add new scheduler implementation functions as (lowercase) keys
sched_info_dict = {
"slurm": _slurm_info,
"torque": _torque_info,
"sge": _sge_info
}
if parallel["scheduler"].lower() in sched_info_dict:
try:
return sched_info_dict[parallel["scheduler"].lower()](parallel.get("queue", ""))
except:
# If something goes wrong, just hit the queue
logger.exception("Couldn't get machine information from resource query function for queue "
"'{0}' on scheduler \"{1}\"; "
"submitting job to queue".format(parallel.get("queue", ""), parallel["scheduler"]))
else:
logger.info("Resource query function not implemented for scheduler \"{0}\"; "
"submitting job to queue".format(parallel["scheduler"]))
from bcbio.distributed import prun
with prun.start(parallel, [[sys_config]], config, dirs) as run_parallel:
return run_parallel("machine_info", [[sys_config]]) | [
"def",
"_get_machine_info",
"(",
"parallel",
",",
"sys_config",
",",
"dirs",
",",
"config",
")",
":",
"if",
"parallel",
".",
"get",
"(",
"\"queue\"",
")",
"and",
"parallel",
".",
"get",
"(",
"\"scheduler\"",
")",
":",
"# dictionary as switch statement; can add n... | Get machine resource information from the job scheduler via either the command line or the queue. | [
"Get",
"machine",
"resource",
"information",
"from",
"the",
"job",
"scheduler",
"via",
"either",
"the",
"command",
"line",
"or",
"the",
"queue",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L36-L59 |
224,107 | bcbio/bcbio-nextgen | bcbio/provenance/system.py | _slurm_info | def _slurm_info(queue):
"""Returns machine information for a slurm job scheduler.
"""
cl = "sinfo -h -p {} --format '%c %m %D'".format(queue)
num_cpus, mem, num_nodes = subprocess.check_output(shlex.split(cl)).decode().split()
# if the queue contains multiple memory configurations, the minimum value is printed with a trailing '+'
mem = float(mem.replace('+', ''))
num_cpus = int(num_cpus.replace('+', ''))
# handle small clusters where we need to allocate memory for bcbio and the controller
# This will typically be on cloud AWS machines
bcbio_mem = 2000
controller_mem = 4000
if int(num_nodes) < 3 and mem > (bcbio_mem + controller_mem) * 2:
mem = mem - bcbio_mem - controller_mem
return [{"cores": int(num_cpus), "memory": mem / 1024.0, "name": "slurm_machine"}] | python | def _slurm_info(queue):
"""Returns machine information for a slurm job scheduler.
"""
cl = "sinfo -h -p {} --format '%c %m %D'".format(queue)
num_cpus, mem, num_nodes = subprocess.check_output(shlex.split(cl)).decode().split()
# if the queue contains multiple memory configurations, the minimum value is printed with a trailing '+'
mem = float(mem.replace('+', ''))
num_cpus = int(num_cpus.replace('+', ''))
# handle small clusters where we need to allocate memory for bcbio and the controller
# This will typically be on cloud AWS machines
bcbio_mem = 2000
controller_mem = 4000
if int(num_nodes) < 3 and mem > (bcbio_mem + controller_mem) * 2:
mem = mem - bcbio_mem - controller_mem
return [{"cores": int(num_cpus), "memory": mem / 1024.0, "name": "slurm_machine"}] | [
"def",
"_slurm_info",
"(",
"queue",
")",
":",
"cl",
"=",
"\"sinfo -h -p {} --format '%c %m %D'\"",
".",
"format",
"(",
"queue",
")",
"num_cpus",
",",
"mem",
",",
"num_nodes",
"=",
"subprocess",
".",
"check_output",
"(",
"shlex",
".",
"split",
"(",
"cl",
")",... | Returns machine information for a slurm job scheduler. | [
"Returns",
"machine",
"information",
"for",
"a",
"slurm",
"job",
"scheduler",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L61-L75 |
224,108 | bcbio/bcbio-nextgen | bcbio/provenance/system.py | _torque_info | def _torque_info(queue):
"""Return machine information for a torque job scheduler using pbsnodes.
To identify which host to use it tries to parse available hosts
from qstat -Qf `acl_hosts`. If found, it uses these and gets the
first node from pbsnodes matching to the list. If no attached
hosts are available, it uses the first host found from pbsnodes.
"""
nodes = _torque_queue_nodes(queue)
pbs_out = subprocess.check_output(["pbsnodes"]).decode()
info = {}
for i, line in enumerate(pbs_out.split("\n")):
if i == 0 and len(nodes) == 0:
info["name"] = line.strip()
elif line.startswith(nodes):
info["name"] = line.strip()
elif info.get("name"):
if line.strip().startswith("np = "):
info["cores"] = int(line.replace("np = ", "").strip())
elif line.strip().startswith("status = "):
mem = [x for x in pbs_out.split(",") if x.startswith("physmem=")][0]
info["memory"] = float(mem.split("=")[1].rstrip("kb")) / 1048576.0
return [info] | python | def _torque_info(queue):
"""Return machine information for a torque job scheduler using pbsnodes.
To identify which host to use it tries to parse available hosts
from qstat -Qf `acl_hosts`. If found, it uses these and gets the
first node from pbsnodes matching to the list. If no attached
hosts are available, it uses the first host found from pbsnodes.
"""
nodes = _torque_queue_nodes(queue)
pbs_out = subprocess.check_output(["pbsnodes"]).decode()
info = {}
for i, line in enumerate(pbs_out.split("\n")):
if i == 0 and len(nodes) == 0:
info["name"] = line.strip()
elif line.startswith(nodes):
info["name"] = line.strip()
elif info.get("name"):
if line.strip().startswith("np = "):
info["cores"] = int(line.replace("np = ", "").strip())
elif line.strip().startswith("status = "):
mem = [x for x in pbs_out.split(",") if x.startswith("physmem=")][0]
info["memory"] = float(mem.split("=")[1].rstrip("kb")) / 1048576.0
return [info] | [
"def",
"_torque_info",
"(",
"queue",
")",
":",
"nodes",
"=",
"_torque_queue_nodes",
"(",
"queue",
")",
"pbs_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"pbsnodes\"",
"]",
")",
".",
"decode",
"(",
")",
"info",
"=",
"{",
"}",
"for",
"i",
",... | Return machine information for a torque job scheduler using pbsnodes.
To identify which host to use it tries to parse available hosts
from qstat -Qf `acl_hosts`. If found, it uses these and gets the
first node from pbsnodes matching to the list. If no attached
hosts are available, it uses the first host found from pbsnodes. | [
"Return",
"machine",
"information",
"for",
"a",
"torque",
"job",
"scheduler",
"using",
"pbsnodes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L77-L99 |
224,109 | bcbio/bcbio-nextgen | bcbio/provenance/system.py | _torque_queue_nodes | def _torque_queue_nodes(queue):
"""Retrieve the nodes available for a queue.
Parses out nodes from `acl_hosts` in qstat -Qf and extracts the
initial names of nodes used in pbsnodes.
"""
qstat_out = subprocess.check_output(["qstat", "-Qf", queue]).decode()
hosts = []
in_hosts = False
for line in qstat_out.split("\n"):
if line.strip().startswith("acl_hosts = "):
hosts.extend(line.replace("acl_hosts = ", "").strip().split(","))
in_hosts = True
elif in_hosts:
if line.find(" = ") > 0:
break
else:
hosts.extend(line.strip().split(","))
return tuple([h.split(".")[0].strip() for h in hosts if h.strip()]) | python | def _torque_queue_nodes(queue):
"""Retrieve the nodes available for a queue.
Parses out nodes from `acl_hosts` in qstat -Qf and extracts the
initial names of nodes used in pbsnodes.
"""
qstat_out = subprocess.check_output(["qstat", "-Qf", queue]).decode()
hosts = []
in_hosts = False
for line in qstat_out.split("\n"):
if line.strip().startswith("acl_hosts = "):
hosts.extend(line.replace("acl_hosts = ", "").strip().split(","))
in_hosts = True
elif in_hosts:
if line.find(" = ") > 0:
break
else:
hosts.extend(line.strip().split(","))
return tuple([h.split(".")[0].strip() for h in hosts if h.strip()]) | [
"def",
"_torque_queue_nodes",
"(",
"queue",
")",
":",
"qstat_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"qstat\"",
",",
"\"-Qf\"",
",",
"queue",
"]",
")",
".",
"decode",
"(",
")",
"hosts",
"=",
"[",
"]",
"in_hosts",
"=",
"False",
"for",
... | Retrieve the nodes available for a queue.
Parses out nodes from `acl_hosts` in qstat -Qf and extracts the
initial names of nodes used in pbsnodes. | [
"Retrieve",
"the",
"nodes",
"available",
"for",
"a",
"queue",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L101-L119 |
224,110 | bcbio/bcbio-nextgen | bcbio/provenance/system.py | _sge_info | def _sge_info(queue):
"""Returns machine information for an sge job scheduler.
"""
qhost_out = subprocess.check_output(["qhost", "-q", "-xml"]).decode()
qstat_queue = ["-q", queue] if queue and "," not in queue else []
qstat_out = subprocess.check_output(["qstat", "-f", "-xml"] + qstat_queue).decode()
slot_info = _sge_get_slots(qstat_out)
mem_info = _sge_get_mem(qhost_out, queue)
machine_keys = slot_info.keys()
#num_cpus_vec = [slot_info[x]["slots_total"] for x in machine_keys]
#mem_vec = [mem_info[x]["mem_total"] for x in machine_keys]
mem_per_slot = [mem_info[x]["mem_total"] / float(slot_info[x]["slots_total"]) for x in machine_keys]
min_ratio_index = mem_per_slot.index(median_left(mem_per_slot))
mem_info[machine_keys[min_ratio_index]]["mem_total"]
return [{"cores": slot_info[machine_keys[min_ratio_index]]["slots_total"],
"memory": mem_info[machine_keys[min_ratio_index]]["mem_total"],
"name": "sge_machine"}] | python | def _sge_info(queue):
"""Returns machine information for an sge job scheduler.
"""
qhost_out = subprocess.check_output(["qhost", "-q", "-xml"]).decode()
qstat_queue = ["-q", queue] if queue and "," not in queue else []
qstat_out = subprocess.check_output(["qstat", "-f", "-xml"] + qstat_queue).decode()
slot_info = _sge_get_slots(qstat_out)
mem_info = _sge_get_mem(qhost_out, queue)
machine_keys = slot_info.keys()
#num_cpus_vec = [slot_info[x]["slots_total"] for x in machine_keys]
#mem_vec = [mem_info[x]["mem_total"] for x in machine_keys]
mem_per_slot = [mem_info[x]["mem_total"] / float(slot_info[x]["slots_total"]) for x in machine_keys]
min_ratio_index = mem_per_slot.index(median_left(mem_per_slot))
mem_info[machine_keys[min_ratio_index]]["mem_total"]
return [{"cores": slot_info[machine_keys[min_ratio_index]]["slots_total"],
"memory": mem_info[machine_keys[min_ratio_index]]["mem_total"],
"name": "sge_machine"}] | [
"def",
"_sge_info",
"(",
"queue",
")",
":",
"qhost_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"qhost\"",
",",
"\"-q\"",
",",
"\"-xml\"",
"]",
")",
".",
"decode",
"(",
")",
"qstat_queue",
"=",
"[",
"\"-q\"",
",",
"queue",
"]",
"if",
"queu... | Returns machine information for an sge job scheduler. | [
"Returns",
"machine",
"information",
"for",
"an",
"sge",
"job",
"scheduler",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L128-L144 |
224,111 | bcbio/bcbio-nextgen | bcbio/provenance/system.py | _sge_get_slots | def _sge_get_slots(xmlstring):
""" Get slot information from qstat
"""
rootxml = ET.fromstring(xmlstring)
my_machine_dict = {}
for queue_list in rootxml.iter("Queue-List"):
# find all hosts supporting queues
my_hostname = queue_list.find("name").text.rsplit("@")[-1]
my_slots = queue_list.find("slots_total").text
my_machine_dict[my_hostname] = {}
my_machine_dict[my_hostname]["slots_total"] = int(my_slots)
return my_machine_dict | python | def _sge_get_slots(xmlstring):
""" Get slot information from qstat
"""
rootxml = ET.fromstring(xmlstring)
my_machine_dict = {}
for queue_list in rootxml.iter("Queue-List"):
# find all hosts supporting queues
my_hostname = queue_list.find("name").text.rsplit("@")[-1]
my_slots = queue_list.find("slots_total").text
my_machine_dict[my_hostname] = {}
my_machine_dict[my_hostname]["slots_total"] = int(my_slots)
return my_machine_dict | [
"def",
"_sge_get_slots",
"(",
"xmlstring",
")",
":",
"rootxml",
"=",
"ET",
".",
"fromstring",
"(",
"xmlstring",
")",
"my_machine_dict",
"=",
"{",
"}",
"for",
"queue_list",
"in",
"rootxml",
".",
"iter",
"(",
"\"Queue-List\"",
")",
":",
"# find all hosts support... | Get slot information from qstat | [
"Get",
"slot",
"information",
"from",
"qstat"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L146-L157 |
224,112 | bcbio/bcbio-nextgen | bcbio/provenance/system.py | _sge_get_mem | def _sge_get_mem(xmlstring, queue_name):
""" Get memory information from qhost
"""
rootxml = ET.fromstring(xmlstring)
my_machine_dict = {}
# on some machines rootxml.tag looks like "{...}qhost" where the "{...}" gets prepended to all attributes
rootTag = rootxml.tag.rstrip("qhost")
for host in rootxml.findall(rootTag + 'host'):
# find all hosts supporting queues
for queues in host.findall(rootTag + 'queue'):
# if the user specified queue matches that in the xml:
if not queue_name or any(q in queues.attrib['name'] for q in queue_name.split(",")):
my_machine_dict[host.attrib['name']] = {}
# values from xml for number of processors and mem_total on each machine
for hostvalues in host.findall(rootTag + 'hostvalue'):
if('mem_total' == hostvalues.attrib['name']):
if hostvalues.text.lower().endswith('g'):
multip = 1
elif hostvalues.text.lower().endswith('m'):
multip = 1 / float(1024)
elif hostvalues.text.lower().endswith('t'):
multip = 1024
else:
raise Exception("Unrecognized suffix in mem_tot from SGE")
my_machine_dict[host.attrib['name']]['mem_total'] = \
float(hostvalues.text[:-1]) * float(multip)
break
return my_machine_dict | python | def _sge_get_mem(xmlstring, queue_name):
""" Get memory information from qhost
"""
rootxml = ET.fromstring(xmlstring)
my_machine_dict = {}
# on some machines rootxml.tag looks like "{...}qhost" where the "{...}" gets prepended to all attributes
rootTag = rootxml.tag.rstrip("qhost")
for host in rootxml.findall(rootTag + 'host'):
# find all hosts supporting queues
for queues in host.findall(rootTag + 'queue'):
# if the user specified queue matches that in the xml:
if not queue_name or any(q in queues.attrib['name'] for q in queue_name.split(",")):
my_machine_dict[host.attrib['name']] = {}
# values from xml for number of processors and mem_total on each machine
for hostvalues in host.findall(rootTag + 'hostvalue'):
if('mem_total' == hostvalues.attrib['name']):
if hostvalues.text.lower().endswith('g'):
multip = 1
elif hostvalues.text.lower().endswith('m'):
multip = 1 / float(1024)
elif hostvalues.text.lower().endswith('t'):
multip = 1024
else:
raise Exception("Unrecognized suffix in mem_tot from SGE")
my_machine_dict[host.attrib['name']]['mem_total'] = \
float(hostvalues.text[:-1]) * float(multip)
break
return my_machine_dict | [
"def",
"_sge_get_mem",
"(",
"xmlstring",
",",
"queue_name",
")",
":",
"rootxml",
"=",
"ET",
".",
"fromstring",
"(",
"xmlstring",
")",
"my_machine_dict",
"=",
"{",
"}",
"# on some machines rootxml.tag looks like \"{...}qhost\" where the \"{...}\" gets prepended to all attribut... | Get memory information from qhost | [
"Get",
"memory",
"information",
"from",
"qhost"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L159-L186 |
224,113 | bcbio/bcbio-nextgen | bcbio/provenance/system.py | get_info | def get_info(dirs, parallel, resources=None):
"""Retrieve cluster or local filesystem resources from pre-retrieved information.
"""
# Allow custom specification of cores/memory in resources
if resources and isinstance(resources, dict) and "machine" in resources:
minfo = resources["machine"]
assert "memory" in minfo, "Require memory specification (Gb) in machine resources: %s" % minfo
assert "cores" in minfo, "Require core specification in machine resources: %s" % minfo
return minfo
if parallel["type"] in ["ipython"] and not parallel["queue"] == "localrun":
cache_file = _get_cache_file(dirs, parallel)
if utils.file_exists(cache_file):
with open(cache_file) as in_handle:
minfo = yaml.safe_load(in_handle)
return _combine_machine_info(minfo)
else:
return {}
else:
return _combine_machine_info(machine_info()) | python | def get_info(dirs, parallel, resources=None):
"""Retrieve cluster or local filesystem resources from pre-retrieved information.
"""
# Allow custom specification of cores/memory in resources
if resources and isinstance(resources, dict) and "machine" in resources:
minfo = resources["machine"]
assert "memory" in minfo, "Require memory specification (Gb) in machine resources: %s" % minfo
assert "cores" in minfo, "Require core specification in machine resources: %s" % minfo
return minfo
if parallel["type"] in ["ipython"] and not parallel["queue"] == "localrun":
cache_file = _get_cache_file(dirs, parallel)
if utils.file_exists(cache_file):
with open(cache_file) as in_handle:
minfo = yaml.safe_load(in_handle)
return _combine_machine_info(minfo)
else:
return {}
else:
return _combine_machine_info(machine_info()) | [
"def",
"get_info",
"(",
"dirs",
",",
"parallel",
",",
"resources",
"=",
"None",
")",
":",
"# Allow custom specification of cores/memory in resources",
"if",
"resources",
"and",
"isinstance",
"(",
"resources",
",",
"dict",
")",
"and",
"\"machine\"",
"in",
"resources"... | Retrieve cluster or local filesystem resources from pre-retrieved information. | [
"Retrieve",
"cluster",
"or",
"local",
"filesystem",
"resources",
"from",
"pre",
"-",
"retrieved",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L194-L212 |
224,114 | bcbio/bcbio-nextgen | bcbio/provenance/system.py | machine_info | def machine_info():
"""Retrieve core and memory information for the current machine.
"""
import psutil
BYTES_IN_GIG = 1073741824.0
free_bytes = psutil.virtual_memory().total
return [{"memory": float("%.1f" % (free_bytes / BYTES_IN_GIG)), "cores": multiprocessing.cpu_count(),
"name": socket.gethostname()}] | python | def machine_info():
"""Retrieve core and memory information for the current machine.
"""
import psutil
BYTES_IN_GIG = 1073741824.0
free_bytes = psutil.virtual_memory().total
return [{"memory": float("%.1f" % (free_bytes / BYTES_IN_GIG)), "cores": multiprocessing.cpu_count(),
"name": socket.gethostname()}] | [
"def",
"machine_info",
"(",
")",
":",
"import",
"psutil",
"BYTES_IN_GIG",
"=",
"1073741824.0",
"free_bytes",
"=",
"psutil",
".",
"virtual_memory",
"(",
")",
".",
"total",
"return",
"[",
"{",
"\"memory\"",
":",
"float",
"(",
"\"%.1f\"",
"%",
"(",
"free_bytes"... | Retrieve core and memory information for the current machine. | [
"Retrieve",
"core",
"and",
"memory",
"information",
"for",
"the",
"current",
"machine",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L214-L221 |
224,115 | bcbio/bcbio-nextgen | bcbio/rnaseq/dexseq.py | run_count | def run_count(bam_file, dexseq_gff, stranded, out_file, data):
"""
run dexseq_count on a BAM file
"""
assert file_exists(bam_file), "%s does not exist." % bam_file
sort_order = bam._get_sort_order(bam_file, {})
assert sort_order, "Cannot determine sort order of %s." % bam_file
strand_flag = _strand_flag(stranded)
assert strand_flag, "%s is not a valid strandedness value." % stranded
if not dexseq_gff:
logger.info("No DEXSeq GFF file was found, skipping exon-level counting.")
return None
elif not file_exists(dexseq_gff):
logger.info("%s was not found, so exon-level counting is being "
"skipped." % dexseq_gff)
return None
dexseq_count = _dexseq_count_path()
if not dexseq_count:
logger.info("DEXseq is not installed, skipping exon-level counting.")
return None
if dd.get_aligner(data) == "bwa":
logger.info("Can't use DEXSeq with bwa alignments, skipping exon-level counting.")
return None
sort_flag = "name" if sort_order == "queryname" else "pos"
is_paired = bam.is_paired(bam_file)
paired_flag = "yes" if is_paired else "no"
bcbio_python = sys.executable
if file_exists(out_file):
return out_file
cmd = ("{bcbio_python} {dexseq_count} -f bam -r {sort_flag} -p {paired_flag} "
"-s {strand_flag} {dexseq_gff} {bam_file} {tx_out_file}")
message = "Counting exon-level counts with %s and %s." % (bam_file, dexseq_gff)
with file_transaction(data, out_file) as tx_out_file:
do.run(cmd.format(**locals()), message)
return out_file | python | def run_count(bam_file, dexseq_gff, stranded, out_file, data):
"""
run dexseq_count on a BAM file
"""
assert file_exists(bam_file), "%s does not exist." % bam_file
sort_order = bam._get_sort_order(bam_file, {})
assert sort_order, "Cannot determine sort order of %s." % bam_file
strand_flag = _strand_flag(stranded)
assert strand_flag, "%s is not a valid strandedness value." % stranded
if not dexseq_gff:
logger.info("No DEXSeq GFF file was found, skipping exon-level counting.")
return None
elif not file_exists(dexseq_gff):
logger.info("%s was not found, so exon-level counting is being "
"skipped." % dexseq_gff)
return None
dexseq_count = _dexseq_count_path()
if not dexseq_count:
logger.info("DEXseq is not installed, skipping exon-level counting.")
return None
if dd.get_aligner(data) == "bwa":
logger.info("Can't use DEXSeq with bwa alignments, skipping exon-level counting.")
return None
sort_flag = "name" if sort_order == "queryname" else "pos"
is_paired = bam.is_paired(bam_file)
paired_flag = "yes" if is_paired else "no"
bcbio_python = sys.executable
if file_exists(out_file):
return out_file
cmd = ("{bcbio_python} {dexseq_count} -f bam -r {sort_flag} -p {paired_flag} "
"-s {strand_flag} {dexseq_gff} {bam_file} {tx_out_file}")
message = "Counting exon-level counts with %s and %s." % (bam_file, dexseq_gff)
with file_transaction(data, out_file) as tx_out_file:
do.run(cmd.format(**locals()), message)
return out_file | [
"def",
"run_count",
"(",
"bam_file",
",",
"dexseq_gff",
",",
"stranded",
",",
"out_file",
",",
"data",
")",
":",
"assert",
"file_exists",
"(",
"bam_file",
")",
",",
"\"%s does not exist.\"",
"%",
"bam_file",
"sort_order",
"=",
"bam",
".",
"_get_sort_order",
"(... | run dexseq_count on a BAM file | [
"run",
"dexseq_count",
"on",
"a",
"BAM",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/dexseq.py#L27-L65 |
224,116 | bcbio/bcbio-nextgen | bcbio/bam/trim.py | _trim_adapters | def _trim_adapters(fastq_files, out_dir, data):
"""
for small insert sizes, the read length can be longer than the insert
resulting in the reverse complement of the 3' adapter being sequenced.
this takes adapter sequences and trims the only the reverse complement
of the adapter
MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim)
"""
to_trim = _get_sequences_to_trim(data["config"], SUPPORTED_ADAPTERS)
if dd.get_trim_reads(data) == "fastp":
out_files, report_file = _fastp_trim(fastq_files, to_trim, out_dir, data)
else:
out_files, report_file = _atropos_trim(fastq_files, to_trim, out_dir, data)
# quality_format = _get_quality_format(data["config"])
# out_files = replace_directory(append_stem(fastq_files, "_%s.trimmed" % name), out_dir)
# log_file = "%s_log_cutadapt.txt" % splitext_plus(out_files[0])[0]
# out_files = _cutadapt_trim(fastq_files, quality_format, to_trim, out_files, log_file, data)
# if file_exists(log_file):
# content = open(log_file).read().replace(fastq_files[0], name)
# if len(fastq_files) > 1:
# content = content.replace(fastq_files[1], name)
# open(log_file, 'w').write(content)
return out_files | python | def _trim_adapters(fastq_files, out_dir, data):
"""
for small insert sizes, the read length can be longer than the insert
resulting in the reverse complement of the 3' adapter being sequenced.
this takes adapter sequences and trims the only the reverse complement
of the adapter
MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim)
"""
to_trim = _get_sequences_to_trim(data["config"], SUPPORTED_ADAPTERS)
if dd.get_trim_reads(data) == "fastp":
out_files, report_file = _fastp_trim(fastq_files, to_trim, out_dir, data)
else:
out_files, report_file = _atropos_trim(fastq_files, to_trim, out_dir, data)
# quality_format = _get_quality_format(data["config"])
# out_files = replace_directory(append_stem(fastq_files, "_%s.trimmed" % name), out_dir)
# log_file = "%s_log_cutadapt.txt" % splitext_plus(out_files[0])[0]
# out_files = _cutadapt_trim(fastq_files, quality_format, to_trim, out_files, log_file, data)
# if file_exists(log_file):
# content = open(log_file).read().replace(fastq_files[0], name)
# if len(fastq_files) > 1:
# content = content.replace(fastq_files[1], name)
# open(log_file, 'w').write(content)
return out_files | [
"def",
"_trim_adapters",
"(",
"fastq_files",
",",
"out_dir",
",",
"data",
")",
":",
"to_trim",
"=",
"_get_sequences_to_trim",
"(",
"data",
"[",
"\"config\"",
"]",
",",
"SUPPORTED_ADAPTERS",
")",
"if",
"dd",
".",
"get_trim_reads",
"(",
"data",
")",
"==",
"\"f... | for small insert sizes, the read length can be longer than the insert
resulting in the reverse complement of the 3' adapter being sequenced.
this takes adapter sequences and trims the only the reverse complement
of the adapter
MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim) | [
"for",
"small",
"insert",
"sizes",
"the",
"read",
"length",
"can",
"be",
"longer",
"than",
"the",
"insert",
"resulting",
"in",
"the",
"reverse",
"complement",
"of",
"the",
"3",
"adapter",
"being",
"sequenced",
".",
"this",
"takes",
"adapter",
"sequences",
"a... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L36-L59 |
224,117 | bcbio/bcbio-nextgen | bcbio/bam/trim.py | _cutadapt_trim | def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, log_file, data):
"""Trimming with cutadapt.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
cmd = _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data)
if len(fastq_files) == 1:
of = [out_files[0], log_file]
message = "Trimming %s in single end mode with cutadapt." % (fastq_files[0])
with file_transaction(data, of) as of_tx:
of1_tx, log_tx = of_tx
do.run(cmd.format(**locals()), message)
else:
of = out_files + [log_file]
with file_transaction(data, of) as tx_out_files:
of1_tx, of2_tx, log_tx = tx_out_files
tmp_fq1 = utils.append_stem(of1_tx, ".tmp")
tmp_fq2 = utils.append_stem(of2_tx, ".tmp")
singles_file = of1_tx + ".single"
message = "Trimming %s and %s in paired end mode with cutadapt." % (fastq_files[0],
fastq_files[1])
do.run(cmd.format(**locals()), message)
return out_files | python | def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, log_file, data):
"""Trimming with cutadapt.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
cmd = _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data)
if len(fastq_files) == 1:
of = [out_files[0], log_file]
message = "Trimming %s in single end mode with cutadapt." % (fastq_files[0])
with file_transaction(data, of) as of_tx:
of1_tx, log_tx = of_tx
do.run(cmd.format(**locals()), message)
else:
of = out_files + [log_file]
with file_transaction(data, of) as tx_out_files:
of1_tx, of2_tx, log_tx = tx_out_files
tmp_fq1 = utils.append_stem(of1_tx, ".tmp")
tmp_fq2 = utils.append_stem(of2_tx, ".tmp")
singles_file = of1_tx + ".single"
message = "Trimming %s and %s in paired end mode with cutadapt." % (fastq_files[0],
fastq_files[1])
do.run(cmd.format(**locals()), message)
return out_files | [
"def",
"_cutadapt_trim",
"(",
"fastq_files",
",",
"quality_format",
",",
"adapters",
",",
"out_files",
",",
"log_file",
",",
"data",
")",
":",
"if",
"all",
"(",
"[",
"utils",
".",
"file_exists",
"(",
"x",
")",
"for",
"x",
"in",
"out_files",
"]",
")",
"... | Trimming with cutadapt. | [
"Trimming",
"with",
"cutadapt",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L192-L214 |
224,118 | bcbio/bcbio-nextgen | bcbio/bam/trim.py | _cutadapt_trim_cmd | def _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data):
"""Trimming with cutadapt, using version installed with bcbio-nextgen.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
if quality_format == "illumina":
quality_base = "64"
else:
quality_base = "33"
# --times=2 tries twice remove adapters which will allow things like:
# realsequenceAAAAAAadapter to remove both the poly-A and the adapter
# this behavior might not be what we want; we could also do two or
# more passes of cutadapt
cutadapt = os.path.join(os.path.dirname(sys.executable), "cutadapt")
adapter_cmd = " ".join(map(lambda x: "-a " + x, adapters))
ropts = " ".join(str(x) for x in
config_utils.get_resources("cutadapt", data["config"]).get("options", []))
base_cmd = ("{cutadapt} {ropts} --times=2 --quality-base={quality_base} "
"--quality-cutoff=5 --format=fastq "
"{adapter_cmd} ").format(**locals())
if len(fastq_files) == 2:
# support for the single-command paired trimming introduced in
# cutadapt 1.8
adapter_cmd = adapter_cmd.replace("-a ", "-A ")
base_cmd += "{adapter_cmd} ".format(adapter_cmd=adapter_cmd)
return _cutadapt_pe_cmd(fastq_files, out_files, quality_format, base_cmd, data)
else:
return _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data) | python | def _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data):
"""Trimming with cutadapt, using version installed with bcbio-nextgen.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
if quality_format == "illumina":
quality_base = "64"
else:
quality_base = "33"
# --times=2 tries twice remove adapters which will allow things like:
# realsequenceAAAAAAadapter to remove both the poly-A and the adapter
# this behavior might not be what we want; we could also do two or
# more passes of cutadapt
cutadapt = os.path.join(os.path.dirname(sys.executable), "cutadapt")
adapter_cmd = " ".join(map(lambda x: "-a " + x, adapters))
ropts = " ".join(str(x) for x in
config_utils.get_resources("cutadapt", data["config"]).get("options", []))
base_cmd = ("{cutadapt} {ropts} --times=2 --quality-base={quality_base} "
"--quality-cutoff=5 --format=fastq "
"{adapter_cmd} ").format(**locals())
if len(fastq_files) == 2:
# support for the single-command paired trimming introduced in
# cutadapt 1.8
adapter_cmd = adapter_cmd.replace("-a ", "-A ")
base_cmd += "{adapter_cmd} ".format(adapter_cmd=adapter_cmd)
return _cutadapt_pe_cmd(fastq_files, out_files, quality_format, base_cmd, data)
else:
return _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data) | [
"def",
"_cutadapt_trim_cmd",
"(",
"fastq_files",
",",
"quality_format",
",",
"adapters",
",",
"out_files",
",",
"data",
")",
":",
"if",
"all",
"(",
"[",
"utils",
".",
"file_exists",
"(",
"x",
")",
"for",
"x",
"in",
"out_files",
"]",
")",
":",
"return",
... | Trimming with cutadapt, using version installed with bcbio-nextgen. | [
"Trimming",
"with",
"cutadapt",
"using",
"version",
"installed",
"with",
"bcbio",
"-",
"nextgen",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L216-L244 |
224,119 | bcbio/bcbio-nextgen | bcbio/bam/trim.py | _cutadapt_se_cmd | def _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data):
"""
this has to use the -o option, not redirect to stdout in order for
gzipping to be supported
"""
min_length = dd.get_min_read_length(data)
cmd = base_cmd + " --minimum-length={min_length} ".format(**locals())
fq1 = objectstore.cl_input(fastq_files[0])
of1 = out_files[0]
cmd += " -o {of1_tx} " + str(fq1)
cmd = "%s | tee > {log_tx}" % cmd
return cmd | python | def _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data):
"""
this has to use the -o option, not redirect to stdout in order for
gzipping to be supported
"""
min_length = dd.get_min_read_length(data)
cmd = base_cmd + " --minimum-length={min_length} ".format(**locals())
fq1 = objectstore.cl_input(fastq_files[0])
of1 = out_files[0]
cmd += " -o {of1_tx} " + str(fq1)
cmd = "%s | tee > {log_tx}" % cmd
return cmd | [
"def",
"_cutadapt_se_cmd",
"(",
"fastq_files",
",",
"out_files",
",",
"base_cmd",
",",
"data",
")",
":",
"min_length",
"=",
"dd",
".",
"get_min_read_length",
"(",
"data",
")",
"cmd",
"=",
"base_cmd",
"+",
"\" --minimum-length={min_length} \"",
".",
"format",
"("... | this has to use the -o option, not redirect to stdout in order for
gzipping to be supported | [
"this",
"has",
"to",
"use",
"the",
"-",
"o",
"option",
"not",
"redirect",
"to",
"stdout",
"in",
"order",
"for",
"gzipping",
"to",
"be",
"supported"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L246-L257 |
224,120 | bcbio/bcbio-nextgen | bcbio/bam/trim.py | _cutadapt_pe_cmd | def _cutadapt_pe_cmd(fastq_files, out_files, quality_format, base_cmd, data):
"""
run cutadapt in paired end mode
"""
fq1, fq2 = [objectstore.cl_input(x) for x in fastq_files]
of1, of2 = out_files
base_cmd += " --minimum-length={min_length} ".format(min_length=dd.get_min_read_length(data))
first_cmd = base_cmd + " -o {of1_tx} -p {of2_tx} " + fq1 + " " + fq2
return first_cmd + "| tee > {log_tx};" | python | def _cutadapt_pe_cmd(fastq_files, out_files, quality_format, base_cmd, data):
"""
run cutadapt in paired end mode
"""
fq1, fq2 = [objectstore.cl_input(x) for x in fastq_files]
of1, of2 = out_files
base_cmd += " --minimum-length={min_length} ".format(min_length=dd.get_min_read_length(data))
first_cmd = base_cmd + " -o {of1_tx} -p {of2_tx} " + fq1 + " " + fq2
return first_cmd + "| tee > {log_tx};" | [
"def",
"_cutadapt_pe_cmd",
"(",
"fastq_files",
",",
"out_files",
",",
"quality_format",
",",
"base_cmd",
",",
"data",
")",
":",
"fq1",
",",
"fq2",
"=",
"[",
"objectstore",
".",
"cl_input",
"(",
"x",
")",
"for",
"x",
"in",
"fastq_files",
"]",
"of1",
",",
... | run cutadapt in paired end mode | [
"run",
"cutadapt",
"in",
"paired",
"end",
"mode"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L259-L267 |
224,121 | bcbio/bcbio-nextgen | bcbio/variation/realign.py | gatk_realigner_targets | def gatk_realigner_targets(runner, align_bam, ref_file, config, dbsnp=None,
region=None, out_file=None, deep_coverage=False,
variant_regions=None, known_vrns=None):
"""Generate a list of interval regions for realignment around indels.
"""
if not known_vrns:
known_vrns = {}
if out_file:
out_file = "%s.intervals" % os.path.splitext(out_file)[0]
else:
out_file = "%s-realign.intervals" % os.path.splitext(align_bam)[0]
# check only for file existence; interval files can be empty after running
# on small chromosomes, so don't rerun in those cases
if not os.path.exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
logger.debug("GATK RealignerTargetCreator: %s %s" %
(os.path.basename(align_bam), region))
params = ["-T", "RealignerTargetCreator",
"-I", align_bam,
"-R", ref_file,
"-o", tx_out_file,
"-l", "INFO",
]
region = subset_variant_regions(variant_regions, region, tx_out_file)
if region:
params += ["-L", region, "--interval_set_rule", "INTERSECTION"]
if known_vrns.get("train_indels"):
params += ["--known", known_vrns["train_indels"]]
if deep_coverage:
params += ["--mismatchFraction", "0.30",
"--maxIntervalSize", "650"]
runner.run_gatk(params, memscale={"direction": "decrease", "magnitude": 2})
return out_file | python | def gatk_realigner_targets(runner, align_bam, ref_file, config, dbsnp=None,
region=None, out_file=None, deep_coverage=False,
variant_regions=None, known_vrns=None):
"""Generate a list of interval regions for realignment around indels.
"""
if not known_vrns:
known_vrns = {}
if out_file:
out_file = "%s.intervals" % os.path.splitext(out_file)[0]
else:
out_file = "%s-realign.intervals" % os.path.splitext(align_bam)[0]
# check only for file existence; interval files can be empty after running
# on small chromosomes, so don't rerun in those cases
if not os.path.exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
logger.debug("GATK RealignerTargetCreator: %s %s" %
(os.path.basename(align_bam), region))
params = ["-T", "RealignerTargetCreator",
"-I", align_bam,
"-R", ref_file,
"-o", tx_out_file,
"-l", "INFO",
]
region = subset_variant_regions(variant_regions, region, tx_out_file)
if region:
params += ["-L", region, "--interval_set_rule", "INTERSECTION"]
if known_vrns.get("train_indels"):
params += ["--known", known_vrns["train_indels"]]
if deep_coverage:
params += ["--mismatchFraction", "0.30",
"--maxIntervalSize", "650"]
runner.run_gatk(params, memscale={"direction": "decrease", "magnitude": 2})
return out_file | [
"def",
"gatk_realigner_targets",
"(",
"runner",
",",
"align_bam",
",",
"ref_file",
",",
"config",
",",
"dbsnp",
"=",
"None",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
",",
"deep_coverage",
"=",
"False",
",",
"variant_regions",
"=",
"None",
... | Generate a list of interval regions for realignment around indels. | [
"Generate",
"a",
"list",
"of",
"interval",
"regions",
"for",
"realignment",
"around",
"indels",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/realign.py#L15-L47 |
224,122 | bcbio/bcbio-nextgen | bcbio/variation/realign.py | gatk_indel_realignment_cl | def gatk_indel_realignment_cl(runner, align_bam, ref_file, intervals,
tmp_dir, region=None, deep_coverage=False,
known_vrns=None):
"""Prepare input arguments for GATK indel realignment.
"""
if not known_vrns:
known_vrns = {}
params = ["-T", "IndelRealigner",
"-I", align_bam,
"-R", ref_file,
"-targetIntervals", intervals,
]
if region:
params += ["-L", region]
if known_vrns.get("train_indels"):
params += ["--knownAlleles", known_vrns["train_indels"]]
if deep_coverage:
params += ["--maxReadsInMemory", "300000",
"--maxReadsForRealignment", str(int(5e5)),
"--maxReadsForConsensuses", "500",
"--maxConsensuses", "100"]
return runner.cl_gatk(params, tmp_dir) | python | def gatk_indel_realignment_cl(runner, align_bam, ref_file, intervals,
tmp_dir, region=None, deep_coverage=False,
known_vrns=None):
"""Prepare input arguments for GATK indel realignment.
"""
if not known_vrns:
known_vrns = {}
params = ["-T", "IndelRealigner",
"-I", align_bam,
"-R", ref_file,
"-targetIntervals", intervals,
]
if region:
params += ["-L", region]
if known_vrns.get("train_indels"):
params += ["--knownAlleles", known_vrns["train_indels"]]
if deep_coverage:
params += ["--maxReadsInMemory", "300000",
"--maxReadsForRealignment", str(int(5e5)),
"--maxReadsForConsensuses", "500",
"--maxConsensuses", "100"]
return runner.cl_gatk(params, tmp_dir) | [
"def",
"gatk_indel_realignment_cl",
"(",
"runner",
",",
"align_bam",
",",
"ref_file",
",",
"intervals",
",",
"tmp_dir",
",",
"region",
"=",
"None",
",",
"deep_coverage",
"=",
"False",
",",
"known_vrns",
"=",
"None",
")",
":",
"if",
"not",
"known_vrns",
":",
... | Prepare input arguments for GATK indel realignment. | [
"Prepare",
"input",
"arguments",
"for",
"GATK",
"indel",
"realignment",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/realign.py#L49-L70 |
224,123 | bcbio/bcbio-nextgen | bcbio/variation/realign.py | has_aligned_reads | def has_aligned_reads(align_bam, region=None):
"""Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions.
"""
import pybedtools
if region is not None:
if isinstance(region, six.string_types) and os.path.isfile(region):
regions = [tuple(r) for r in pybedtools.BedTool(region)]
else:
regions = [region]
with pysam.Samfile(align_bam, "rb") as cur_bam:
if region is not None:
for region in regions:
if isinstance(region, six.string_types):
for item in cur_bam.fetch(str(region)):
return True
else:
for item in cur_bam.fetch(str(region[0]), int(region[1]), int(region[2])):
return True
else:
for item in cur_bam:
if not item.is_unmapped:
return True
return False | python | def has_aligned_reads(align_bam, region=None):
"""Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions.
"""
import pybedtools
if region is not None:
if isinstance(region, six.string_types) and os.path.isfile(region):
regions = [tuple(r) for r in pybedtools.BedTool(region)]
else:
regions = [region]
with pysam.Samfile(align_bam, "rb") as cur_bam:
if region is not None:
for region in regions:
if isinstance(region, six.string_types):
for item in cur_bam.fetch(str(region)):
return True
else:
for item in cur_bam.fetch(str(region[0]), int(region[1]), int(region[2])):
return True
else:
for item in cur_bam:
if not item.is_unmapped:
return True
return False | [
"def",
"has_aligned_reads",
"(",
"align_bam",
",",
"region",
"=",
"None",
")",
":",
"import",
"pybedtools",
"if",
"region",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"region",
",",
"six",
".",
"string_types",
")",
"and",
"os",
".",
"path",
".",
... | Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions. | [
"Check",
"if",
"the",
"aligned",
"BAM",
"file",
"has",
"any",
"reads",
"in",
"the",
"region",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/realign.py#L74-L99 |
224,124 | bcbio/bcbio-nextgen | bcbio/cwl/defs.py | s | def s(name, parallel, inputs, outputs, image, programs=None, disk=None, cores=None, unlist=None,
no_files=False):
"""Represent a step in a workflow.
name -- The run function name, which must match a definition in distributed/multitasks
inputs -- List of input keys required for the function. Each key is of the type:
["toplevel", "sublevel"] -- an argument you could pass to toolz.get_in.
outputs -- List of outputs with information about file type. Use cwlout functions
programs -- Required programs for this step, used to define resource usage.
disk -- Information about disk usage requirements, specified as multipliers of
input files. Ensures enough disk present when that is a limiting factor
when selecting cloud node resources.
cores -- Maximum cores necessary for this step, for non-multicore processes.
unlist -- Variables being unlisted by this process. Useful for parallelization splitting and
batching from multiple variables, like variant calling.
no_files -- This step does not require file access.
parallel -- Parallelization approach. There are three different levels of parallelization,
each with subcomponents:
1. multi -- Multiple samples, parallelizing at the sample level. Used in top-level workflow.
- multi-parallel -- Run individual samples in parallel.
- multi-combined -- Run all samples together.
- multi-batch -- Run all samples together, converting into batches of grouped samples.
2. single -- A single sample, used in sub-workflows.
- single-split -- Split a sample into sub-components (by read sections).
- single-parallel -- Run sub-components of a sample in parallel.
- single-merge -- Merge multiple sub-components into a single sample.
- single-single -- Single sample, single item, nothing fancy.
3. batch -- Several related samples (tumor/normal, or populations). Used in sub-workflows.
- batch-split -- Split a batch of samples into sub-components (by genomic region).
- batch-parallel -- Run sub-components of a batch in parallel.
- batch-merge -- Merge sub-components back into a single batch.
- batch-single -- Run on a single batch.
"""
Step = collections.namedtuple("Step", "name parallel inputs outputs image programs disk cores unlist no_files")
if programs is None: programs = []
if unlist is None: unlist = []
return Step(name, parallel, inputs, outputs, image, programs, disk, cores, unlist, no_files) | python | def s(name, parallel, inputs, outputs, image, programs=None, disk=None, cores=None, unlist=None,
no_files=False):
"""Represent a step in a workflow.
name -- The run function name, which must match a definition in distributed/multitasks
inputs -- List of input keys required for the function. Each key is of the type:
["toplevel", "sublevel"] -- an argument you could pass to toolz.get_in.
outputs -- List of outputs with information about file type. Use cwlout functions
programs -- Required programs for this step, used to define resource usage.
disk -- Information about disk usage requirements, specified as multipliers of
input files. Ensures enough disk present when that is a limiting factor
when selecting cloud node resources.
cores -- Maximum cores necessary for this step, for non-multicore processes.
unlist -- Variables being unlisted by this process. Useful for parallelization splitting and
batching from multiple variables, like variant calling.
no_files -- This step does not require file access.
parallel -- Parallelization approach. There are three different levels of parallelization,
each with subcomponents:
1. multi -- Multiple samples, parallelizing at the sample level. Used in top-level workflow.
- multi-parallel -- Run individual samples in parallel.
- multi-combined -- Run all samples together.
- multi-batch -- Run all samples together, converting into batches of grouped samples.
2. single -- A single sample, used in sub-workflows.
- single-split -- Split a sample into sub-components (by read sections).
- single-parallel -- Run sub-components of a sample in parallel.
- single-merge -- Merge multiple sub-components into a single sample.
- single-single -- Single sample, single item, nothing fancy.
3. batch -- Several related samples (tumor/normal, or populations). Used in sub-workflows.
- batch-split -- Split a batch of samples into sub-components (by genomic region).
- batch-parallel -- Run sub-components of a batch in parallel.
- batch-merge -- Merge sub-components back into a single batch.
- batch-single -- Run on a single batch.
"""
Step = collections.namedtuple("Step", "name parallel inputs outputs image programs disk cores unlist no_files")
if programs is None: programs = []
if unlist is None: unlist = []
return Step(name, parallel, inputs, outputs, image, programs, disk, cores, unlist, no_files) | [
"def",
"s",
"(",
"name",
",",
"parallel",
",",
"inputs",
",",
"outputs",
",",
"image",
",",
"programs",
"=",
"None",
",",
"disk",
"=",
"None",
",",
"cores",
"=",
"None",
",",
"unlist",
"=",
"None",
",",
"no_files",
"=",
"False",
")",
":",
"Step",
... | Represent a step in a workflow.
name -- The run function name, which must match a definition in distributed/multitasks
inputs -- List of input keys required for the function. Each key is of the type:
["toplevel", "sublevel"] -- an argument you could pass to toolz.get_in.
outputs -- List of outputs with information about file type. Use cwlout functions
programs -- Required programs for this step, used to define resource usage.
disk -- Information about disk usage requirements, specified as multipliers of
input files. Ensures enough disk present when that is a limiting factor
when selecting cloud node resources.
cores -- Maximum cores necessary for this step, for non-multicore processes.
unlist -- Variables being unlisted by this process. Useful for parallelization splitting and
batching from multiple variables, like variant calling.
no_files -- This step does not require file access.
parallel -- Parallelization approach. There are three different levels of parallelization,
each with subcomponents:
1. multi -- Multiple samples, parallelizing at the sample level. Used in top-level workflow.
- multi-parallel -- Run individual samples in parallel.
- multi-combined -- Run all samples together.
- multi-batch -- Run all samples together, converting into batches of grouped samples.
2. single -- A single sample, used in sub-workflows.
- single-split -- Split a sample into sub-components (by read sections).
- single-parallel -- Run sub-components of a sample in parallel.
- single-merge -- Merge multiple sub-components into a single sample.
- single-single -- Single sample, single item, nothing fancy.
3. batch -- Several related samples (tumor/normal, or populations). Used in sub-workflows.
- batch-split -- Split a batch of samples into sub-components (by genomic region).
- batch-parallel -- Run sub-components of a batch in parallel.
- batch-merge -- Merge sub-components back into a single batch.
- batch-single -- Run on a single batch. | [
"Represent",
"a",
"step",
"in",
"a",
"workflow",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L17-L54 |
224,125 | bcbio/bcbio-nextgen | bcbio/cwl/defs.py | w | def w(name, parallel, workflow, internal):
"""A workflow, allowing specification of sub-workflows for nested parallelization.
name and parallel are documented under the Step (s) function.
workflow -- a list of Step tuples defining the sub-workflow
internal -- variables used in the sub-workflow but not exposed to subsequent steps
"""
Workflow = collections.namedtuple("Workflow", "name parallel workflow internal")
return Workflow(name, parallel, workflow, internal) | python | def w(name, parallel, workflow, internal):
"""A workflow, allowing specification of sub-workflows for nested parallelization.
name and parallel are documented under the Step (s) function.
workflow -- a list of Step tuples defining the sub-workflow
internal -- variables used in the sub-workflow but not exposed to subsequent steps
"""
Workflow = collections.namedtuple("Workflow", "name parallel workflow internal")
return Workflow(name, parallel, workflow, internal) | [
"def",
"w",
"(",
"name",
",",
"parallel",
",",
"workflow",
",",
"internal",
")",
":",
"Workflow",
"=",
"collections",
".",
"namedtuple",
"(",
"\"Workflow\"",
",",
"\"name parallel workflow internal\"",
")",
"return",
"Workflow",
"(",
"name",
",",
"parallel",
"... | A workflow, allowing specification of sub-workflows for nested parallelization.
name and parallel are documented under the Step (s) function.
workflow -- a list of Step tuples defining the sub-workflow
internal -- variables used in the sub-workflow but not exposed to subsequent steps | [
"A",
"workflow",
"allowing",
"specification",
"of",
"sub",
"-",
"workflows",
"for",
"nested",
"parallelization",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L56-L64 |
224,126 | bcbio/bcbio-nextgen | bcbio/cwl/defs.py | et | def et(name, parallel, inputs, outputs, expression):
"""Represent an ExpressionTool that reorders inputs using javascript.
"""
ExpressionTool = collections.namedtuple("ExpressionTool", "name inputs outputs expression parallel")
return ExpressionTool(name, inputs, outputs, expression, parallel) | python | def et(name, parallel, inputs, outputs, expression):
"""Represent an ExpressionTool that reorders inputs using javascript.
"""
ExpressionTool = collections.namedtuple("ExpressionTool", "name inputs outputs expression parallel")
return ExpressionTool(name, inputs, outputs, expression, parallel) | [
"def",
"et",
"(",
"name",
",",
"parallel",
",",
"inputs",
",",
"outputs",
",",
"expression",
")",
":",
"ExpressionTool",
"=",
"collections",
".",
"namedtuple",
"(",
"\"ExpressionTool\"",
",",
"\"name inputs outputs expression parallel\"",
")",
"return",
"ExpressionT... | Represent an ExpressionTool that reorders inputs using javascript. | [
"Represent",
"an",
"ExpressionTool",
"that",
"reorders",
"inputs",
"using",
"javascript",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L66-L70 |
224,127 | bcbio/bcbio-nextgen | bcbio/cwl/defs.py | cwlout | def cwlout(key, valtype=None, extensions=None, fields=None, exclude=None):
"""Definition of an output variable, defining the type and associated secondary files.
"""
out = {"id": key}
if valtype:
out["type"] = valtype
if fields:
out["fields"] = fields
if extensions:
out["secondaryFiles"] = extensions
if exclude:
out["exclude"] = exclude
return out | python | def cwlout(key, valtype=None, extensions=None, fields=None, exclude=None):
"""Definition of an output variable, defining the type and associated secondary files.
"""
out = {"id": key}
if valtype:
out["type"] = valtype
if fields:
out["fields"] = fields
if extensions:
out["secondaryFiles"] = extensions
if exclude:
out["exclude"] = exclude
return out | [
"def",
"cwlout",
"(",
"key",
",",
"valtype",
"=",
"None",
",",
"extensions",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"out",
"=",
"{",
"\"id\"",
":",
"key",
"}",
"if",
"valtype",
":",
"out",
"[",
"\"type\"",
... | Definition of an output variable, defining the type and associated secondary files. | [
"Definition",
"of",
"an",
"output",
"variable",
"defining",
"the",
"type",
"and",
"associated",
"secondary",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L72-L84 |
224,128 | bcbio/bcbio-nextgen | bcbio/cwl/defs.py | _variant_hla | def _variant_hla(checkpoints):
"""Add hla analysis to workflow, if configured.
"""
if not checkpoints.get("hla"):
return [], []
hla = [s("hla_to_rec", "multi-batch",
[["hla", "fastq"],
["config", "algorithm", "hlacaller"]],
[cwlout("hla_rec", "record")],
"bcbio-vc", cores=1, no_files=True),
s("call_hla", "multi-parallel",
[["hla_rec"]],
[cwlout(["hla", "hlacaller"], ["string", "null"]),
cwlout(["hla", "call_file"], ["File", "null"])],
"bcbio-vc", ["optitype;env=python2", "razers3=3.5.0", "coincbc"])]
return hla, [["hla", "call_file"]] | python | def _variant_hla(checkpoints):
"""Add hla analysis to workflow, if configured.
"""
if not checkpoints.get("hla"):
return [], []
hla = [s("hla_to_rec", "multi-batch",
[["hla", "fastq"],
["config", "algorithm", "hlacaller"]],
[cwlout("hla_rec", "record")],
"bcbio-vc", cores=1, no_files=True),
s("call_hla", "multi-parallel",
[["hla_rec"]],
[cwlout(["hla", "hlacaller"], ["string", "null"]),
cwlout(["hla", "call_file"], ["File", "null"])],
"bcbio-vc", ["optitype;env=python2", "razers3=3.5.0", "coincbc"])]
return hla, [["hla", "call_file"]] | [
"def",
"_variant_hla",
"(",
"checkpoints",
")",
":",
"if",
"not",
"checkpoints",
".",
"get",
"(",
"\"hla\"",
")",
":",
"return",
"[",
"]",
",",
"[",
"]",
"hla",
"=",
"[",
"s",
"(",
"\"hla_to_rec\"",
",",
"\"multi-batch\"",
",",
"[",
"[",
"\"hla\"",
"... | Add hla analysis to workflow, if configured. | [
"Add",
"hla",
"analysis",
"to",
"workflow",
"if",
"configured",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L128-L143 |
224,129 | bcbio/bcbio-nextgen | bcbio/cwl/defs.py | variant | def variant(samples):
"""Variant calling workflow definition for CWL generation.
"""
checkpoints = _variant_checkpoints(samples)
if checkpoints["align"]:
align_wf = _alignment(checkpoints)
alignin = [["files"], ["analysis"],
["config", "algorithm", "align_split_size"],
["reference", "fasta", "base"],
["rgnames", "pl"], ["rgnames", "sample"], ["rgnames", "pu"],
["rgnames", "lane"], ["rgnames", "rg"], ["rgnames", "lb"],
["reference", "aligner", "indexes"],
["config", "algorithm", "aligner"],
["config", "algorithm", "trim_reads"],
["config", "algorithm", "adapters"],
["config", "algorithm", "bam_clean"],
["config", "algorithm", "variant_regions"],
["config", "algorithm", "mark_duplicates"]]
if checkpoints["hla"]:
alignin.append(["config", "algorithm", "hlacaller"])
if checkpoints["umi"]:
alignin.append(["config", "algorithm", "umi_type"])
align = [s("alignment_to_rec", "multi-combined", alignin,
[cwlout("alignment_rec", "record")],
"bcbio-vc",
disk={"files": 1.5}, cores=1, no_files=True),
w("alignment", "multi-parallel", align_wf,
[["align_split"], ["process_alignment_rec"],
["work_bam"], ["config", "algorithm", "quality_format"]])]
else:
align = [s("organize_noalign", "multi-parallel",
["files"],
[cwlout(["align_bam"], ["File", "null"], [".bai"]),
cwlout(["work_bam_plus", "disc"], ["File", "null"]),
cwlout(["work_bam_plus", "sr"], ["File", "null"]),
cwlout(["hla", "fastq"], ["File", "null"])],
"bcbio-vc", cores=1)]
align_out = [["rgnames", "sample"], ["align_bam"]]
pp_align, pp_align_out = _postprocess_alignment(checkpoints)
if checkpoints["umi"]:
align_out += [["umi_bam"]]
vc, vc_out = _variant_vc(checkpoints)
sv, sv_out = _variant_sv(checkpoints)
hla, hla_out = _variant_hla(checkpoints)
qc, qc_out = _qc_workflow(checkpoints)
steps = align + pp_align + hla + vc + sv + qc
final_outputs = align_out + pp_align_out + vc_out + hla_out + sv_out + qc_out
return steps, final_outputs | python | def variant(samples):
"""Variant calling workflow definition for CWL generation.
"""
checkpoints = _variant_checkpoints(samples)
if checkpoints["align"]:
align_wf = _alignment(checkpoints)
alignin = [["files"], ["analysis"],
["config", "algorithm", "align_split_size"],
["reference", "fasta", "base"],
["rgnames", "pl"], ["rgnames", "sample"], ["rgnames", "pu"],
["rgnames", "lane"], ["rgnames", "rg"], ["rgnames", "lb"],
["reference", "aligner", "indexes"],
["config", "algorithm", "aligner"],
["config", "algorithm", "trim_reads"],
["config", "algorithm", "adapters"],
["config", "algorithm", "bam_clean"],
["config", "algorithm", "variant_regions"],
["config", "algorithm", "mark_duplicates"]]
if checkpoints["hla"]:
alignin.append(["config", "algorithm", "hlacaller"])
if checkpoints["umi"]:
alignin.append(["config", "algorithm", "umi_type"])
align = [s("alignment_to_rec", "multi-combined", alignin,
[cwlout("alignment_rec", "record")],
"bcbio-vc",
disk={"files": 1.5}, cores=1, no_files=True),
w("alignment", "multi-parallel", align_wf,
[["align_split"], ["process_alignment_rec"],
["work_bam"], ["config", "algorithm", "quality_format"]])]
else:
align = [s("organize_noalign", "multi-parallel",
["files"],
[cwlout(["align_bam"], ["File", "null"], [".bai"]),
cwlout(["work_bam_plus", "disc"], ["File", "null"]),
cwlout(["work_bam_plus", "sr"], ["File", "null"]),
cwlout(["hla", "fastq"], ["File", "null"])],
"bcbio-vc", cores=1)]
align_out = [["rgnames", "sample"], ["align_bam"]]
pp_align, pp_align_out = _postprocess_alignment(checkpoints)
if checkpoints["umi"]:
align_out += [["umi_bam"]]
vc, vc_out = _variant_vc(checkpoints)
sv, sv_out = _variant_sv(checkpoints)
hla, hla_out = _variant_hla(checkpoints)
qc, qc_out = _qc_workflow(checkpoints)
steps = align + pp_align + hla + vc + sv + qc
final_outputs = align_out + pp_align_out + vc_out + hla_out + sv_out + qc_out
return steps, final_outputs | [
"def",
"variant",
"(",
"samples",
")",
":",
"checkpoints",
"=",
"_variant_checkpoints",
"(",
"samples",
")",
"if",
"checkpoints",
"[",
"\"align\"",
"]",
":",
"align_wf",
"=",
"_alignment",
"(",
"checkpoints",
")",
"alignin",
"=",
"[",
"[",
"\"files\"",
"]",
... | Variant calling workflow definition for CWL generation. | [
"Variant",
"calling",
"workflow",
"definition",
"for",
"CWL",
"generation",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/defs.py#L414-L461 |
224,130 | bcbio/bcbio-nextgen | bcbio/structural/plot.py | breakpoints_by_caller | def breakpoints_by_caller(bed_files):
"""
given a list of BED files of the form
chrom start end caller
return a BedTool of breakpoints as each line with
the fourth column the caller with evidence for the breakpoint
chr1 1 10 caller1 -> chr1 1 1 caller1
chr1 1 20 caller2 chr1 1 1 caller2
chr1 10 10 caller1
chr1 20 20 caller2
"""
merged = concat(bed_files)
if not merged:
return []
grouped_start = merged.groupby(g=[1, 2, 2], c=4, o=["distinct"]).filter(lambda r: r.end > r.start).saveas()
grouped_end = merged.groupby(g=[1, 3, 3], c=4, o=["distinct"]).filter(lambda r: r.end > r.start).saveas()
together = concat([grouped_start, grouped_end])
if together:
final = together.expand(c=4)
final = final.sort()
return final | python | def breakpoints_by_caller(bed_files):
"""
given a list of BED files of the form
chrom start end caller
return a BedTool of breakpoints as each line with
the fourth column the caller with evidence for the breakpoint
chr1 1 10 caller1 -> chr1 1 1 caller1
chr1 1 20 caller2 chr1 1 1 caller2
chr1 10 10 caller1
chr1 20 20 caller2
"""
merged = concat(bed_files)
if not merged:
return []
grouped_start = merged.groupby(g=[1, 2, 2], c=4, o=["distinct"]).filter(lambda r: r.end > r.start).saveas()
grouped_end = merged.groupby(g=[1, 3, 3], c=4, o=["distinct"]).filter(lambda r: r.end > r.start).saveas()
together = concat([grouped_start, grouped_end])
if together:
final = together.expand(c=4)
final = final.sort()
return final | [
"def",
"breakpoints_by_caller",
"(",
"bed_files",
")",
":",
"merged",
"=",
"concat",
"(",
"bed_files",
")",
"if",
"not",
"merged",
":",
"return",
"[",
"]",
"grouped_start",
"=",
"merged",
".",
"groupby",
"(",
"g",
"=",
"[",
"1",
",",
"2",
",",
"2",
"... | given a list of BED files of the form
chrom start end caller
return a BedTool of breakpoints as each line with
the fourth column the caller with evidence for the breakpoint
chr1 1 10 caller1 -> chr1 1 1 caller1
chr1 1 20 caller2 chr1 1 1 caller2
chr1 10 10 caller1
chr1 20 20 caller2 | [
"given",
"a",
"list",
"of",
"BED",
"files",
"of",
"the",
"form",
"chrom",
"start",
"end",
"caller",
"return",
"a",
"BedTool",
"of",
"breakpoints",
"as",
"each",
"line",
"with",
"the",
"fourth",
"column",
"the",
"caller",
"with",
"evidence",
"for",
"the",
... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/plot.py#L17-L37 |
224,131 | bcbio/bcbio-nextgen | bcbio/structural/plot.py | _get_sv_callers | def _get_sv_callers(items):
"""
return a sorted list of all of the structural variant callers run
"""
callers = []
for data in items:
for sv in data.get("sv", []):
callers.append(sv["variantcaller"])
return list(set([x for x in callers if x != "sv-ensemble"])).sort() | python | def _get_sv_callers(items):
"""
return a sorted list of all of the structural variant callers run
"""
callers = []
for data in items:
for sv in data.get("sv", []):
callers.append(sv["variantcaller"])
return list(set([x for x in callers if x != "sv-ensemble"])).sort() | [
"def",
"_get_sv_callers",
"(",
"items",
")",
":",
"callers",
"=",
"[",
"]",
"for",
"data",
"in",
"items",
":",
"for",
"sv",
"in",
"data",
".",
"get",
"(",
"\"sv\"",
",",
"[",
"]",
")",
":",
"callers",
".",
"append",
"(",
"sv",
"[",
"\"variantcaller... | return a sorted list of all of the structural variant callers run | [
"return",
"a",
"sorted",
"list",
"of",
"all",
"of",
"the",
"structural",
"variant",
"callers",
"run"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/plot.py#L39-L47 |
224,132 | bcbio/bcbio-nextgen | bcbio/structural/plot.py | _prioritize_plot_regions | def _prioritize_plot_regions(region_bt, data, out_dir=None):
"""Avoid plotting large numbers of regions due to speed issues. Prioritize most interesting.
XXX For now, just removes larger regions and avoid plotting thousands of regions.
Longer term we'll insert biology-based prioritization.
"""
max_plots = 1000
max_size = 100 * 1000 # 100kb
out_file = "%s-priority%s" % utils.splitext_plus(region_bt.fn)
if out_dir:
out_file = os.path.join(out_dir, os.path.basename(out_file))
num_plots = 0
if not utils.file_uptodate(out_file, region_bt.fn):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for r in region_bt:
if r.stop - r.start < max_size:
if num_plots < max_plots:
num_plots += 1
out_handle.write("%s\t%s\t%s\n" % (r.chrom, r.start, r.stop))
return out_file | python | def _prioritize_plot_regions(region_bt, data, out_dir=None):
"""Avoid plotting large numbers of regions due to speed issues. Prioritize most interesting.
XXX For now, just removes larger regions and avoid plotting thousands of regions.
Longer term we'll insert biology-based prioritization.
"""
max_plots = 1000
max_size = 100 * 1000 # 100kb
out_file = "%s-priority%s" % utils.splitext_plus(region_bt.fn)
if out_dir:
out_file = os.path.join(out_dir, os.path.basename(out_file))
num_plots = 0
if not utils.file_uptodate(out_file, region_bt.fn):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for r in region_bt:
if r.stop - r.start < max_size:
if num_plots < max_plots:
num_plots += 1
out_handle.write("%s\t%s\t%s\n" % (r.chrom, r.start, r.stop))
return out_file | [
"def",
"_prioritize_plot_regions",
"(",
"region_bt",
",",
"data",
",",
"out_dir",
"=",
"None",
")",
":",
"max_plots",
"=",
"1000",
"max_size",
"=",
"100",
"*",
"1000",
"# 100kb",
"out_file",
"=",
"\"%s-priority%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
... | Avoid plotting large numbers of regions due to speed issues. Prioritize most interesting.
XXX For now, just removes larger regions and avoid plotting thousands of regions.
Longer term we'll insert biology-based prioritization. | [
"Avoid",
"plotting",
"large",
"numbers",
"of",
"regions",
"due",
"to",
"speed",
"issues",
".",
"Prioritize",
"most",
"interesting",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/plot.py#L76-L96 |
224,133 | bcbio/bcbio-nextgen | bcbio/structural/plot.py | by_regions | def by_regions(items):
"""Plot for a union set of combined ensemble regions across all of the data
items.
"""
work_dir = os.path.join(dd.get_work_dir(items[0]), "structural", "coverage")
safe_makedir(work_dir)
out_file = os.path.join(work_dir, "%s-coverage.pdf" % (dd.get_sample_name(items[0])))
if file_exists(out_file):
items = _add_regional_coverage_plot(items, out_file)
else:
bed_files = _get_ensemble_bed_files(items)
merged = bed.merge(bed_files)
breakpoints = breakpoints_by_caller(bed_files)
if merged:
priority_merged = _prioritize_plot_regions(merged, items[0])
out_file = plot_multiple_regions_coverage(items, out_file, items[0],
priority_merged, breakpoints)
items = _add_regional_coverage_plot(items, out_file)
return items | python | def by_regions(items):
"""Plot for a union set of combined ensemble regions across all of the data
items.
"""
work_dir = os.path.join(dd.get_work_dir(items[0]), "structural", "coverage")
safe_makedir(work_dir)
out_file = os.path.join(work_dir, "%s-coverage.pdf" % (dd.get_sample_name(items[0])))
if file_exists(out_file):
items = _add_regional_coverage_plot(items, out_file)
else:
bed_files = _get_ensemble_bed_files(items)
merged = bed.merge(bed_files)
breakpoints = breakpoints_by_caller(bed_files)
if merged:
priority_merged = _prioritize_plot_regions(merged, items[0])
out_file = plot_multiple_regions_coverage(items, out_file, items[0],
priority_merged, breakpoints)
items = _add_regional_coverage_plot(items, out_file)
return items | [
"def",
"by_regions",
"(",
"items",
")",
":",
"work_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"items",
"[",
"0",
"]",
")",
",",
"\"structural\"",
",",
"\"coverage\"",
")",
"safe_makedir",
"(",
"work_dir",
")",
"out_... | Plot for a union set of combined ensemble regions across all of the data
items. | [
"Plot",
"for",
"a",
"union",
"set",
"of",
"combined",
"ensemble",
"regions",
"across",
"all",
"of",
"the",
"data",
"items",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/plot.py#L98-L116 |
224,134 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | finalize_sv | def finalize_sv(orig_vcf, data, items):
"""Finalize structural variants, adding effects and splitting if needed.
"""
paired = vcfutils.get_paired(items)
# For paired/somatic, attach combined calls to tumor sample
if paired:
sample_vcf = orig_vcf if paired.tumor_name == dd.get_sample_name(data) else None
else:
sample_vcf = "%s-%s.vcf.gz" % (utils.splitext_plus(orig_vcf)[0], dd.get_sample_name(data))
sample_vcf = vcfutils.select_sample(orig_vcf, dd.get_sample_name(data), sample_vcf, data["config"])
if sample_vcf:
effects_vcf, _ = effects.add_to_vcf(sample_vcf, data, "snpeff")
else:
effects_vcf = None
return effects_vcf or sample_vcf | python | def finalize_sv(orig_vcf, data, items):
"""Finalize structural variants, adding effects and splitting if needed.
"""
paired = vcfutils.get_paired(items)
# For paired/somatic, attach combined calls to tumor sample
if paired:
sample_vcf = orig_vcf if paired.tumor_name == dd.get_sample_name(data) else None
else:
sample_vcf = "%s-%s.vcf.gz" % (utils.splitext_plus(orig_vcf)[0], dd.get_sample_name(data))
sample_vcf = vcfutils.select_sample(orig_vcf, dd.get_sample_name(data), sample_vcf, data["config"])
if sample_vcf:
effects_vcf, _ = effects.add_to_vcf(sample_vcf, data, "snpeff")
else:
effects_vcf = None
return effects_vcf or sample_vcf | [
"def",
"finalize_sv",
"(",
"orig_vcf",
",",
"data",
",",
"items",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired",
"(",
"items",
")",
"# For paired/somatic, attach combined calls to tumor sample",
"if",
"paired",
":",
"sample_vcf",
"=",
"orig_vcf",
"if",
"p... | Finalize structural variants, adding effects and splitting if needed. | [
"Finalize",
"structural",
"variants",
"adding",
"effects",
"and",
"splitting",
"if",
"needed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L25-L39 |
224,135 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | _get_sv_exclude_file | def _get_sv_exclude_file(items):
"""Retrieve SV file of regions to exclude.
"""
sv_bed = utils.get_in(items[0], ("genome_resources", "variation", "sv_repeat"))
if sv_bed and os.path.exists(sv_bed):
return sv_bed | python | def _get_sv_exclude_file(items):
"""Retrieve SV file of regions to exclude.
"""
sv_bed = utils.get_in(items[0], ("genome_resources", "variation", "sv_repeat"))
if sv_bed and os.path.exists(sv_bed):
return sv_bed | [
"def",
"_get_sv_exclude_file",
"(",
"items",
")",
":",
"sv_bed",
"=",
"utils",
".",
"get_in",
"(",
"items",
"[",
"0",
"]",
",",
"(",
"\"genome_resources\"",
",",
"\"variation\"",
",",
"\"sv_repeat\"",
")",
")",
"if",
"sv_bed",
"and",
"os",
".",
"path",
"... | Retrieve SV file of regions to exclude. | [
"Retrieve",
"SV",
"file",
"of",
"regions",
"to",
"exclude",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L86-L91 |
224,136 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | _get_variant_regions | def _get_variant_regions(items):
"""Retrieve variant regions defined in any of the input items.
"""
return list(filter(lambda x: x is not None,
[tz.get_in(("config", "algorithm", "variant_regions"), data)
for data in items
if tz.get_in(["config", "algorithm", "coverage_interval"], data) != "genome"])) | python | def _get_variant_regions(items):
"""Retrieve variant regions defined in any of the input items.
"""
return list(filter(lambda x: x is not None,
[tz.get_in(("config", "algorithm", "variant_regions"), data)
for data in items
if tz.get_in(["config", "algorithm", "coverage_interval"], data) != "genome"])) | [
"def",
"_get_variant_regions",
"(",
"items",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"[",
"tz",
".",
"get_in",
"(",
"(",
"\"config\"",
",",
"\"algorithm\"",
",",
"\"variant_regions\"",
")",
",",
... | Retrieve variant regions defined in any of the input items. | [
"Retrieve",
"variant",
"regions",
"defined",
"in",
"any",
"of",
"the",
"input",
"items",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L93-L99 |
224,137 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | prepare_exclude_file | def prepare_exclude_file(items, base_file, chrom=None):
"""Prepare a BED file for exclusion.
Excludes high depth and centromere regions which contribute to long run times and
false positive structural variant calls.
"""
items = shared.add_highdepth_genome_exclusion(items)
out_file = "%s-exclude%s.bed" % (utils.splitext_plus(base_file)[0], "-%s" % chrom if chrom else "")
if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
with shared.bedtools_tmpdir(items[0]):
with file_transaction(items[0], out_file) as tx_out_file:
# Get a bedtool for the full region if no variant regions
want_bedtool = callable.get_ref_bedtool(tz.get_in(["reference", "fasta", "base"], items[0]),
items[0]["config"], chrom)
want_bedtool = pybedtools.BedTool(shared.subset_variant_regions(want_bedtool.saveas().fn,
chrom, tx_out_file, items))
sv_exclude_bed = _get_sv_exclude_file(items)
if sv_exclude_bed and len(want_bedtool) > 0:
want_bedtool = want_bedtool.subtract(sv_exclude_bed, nonamecheck=True).saveas()
full_bedtool = callable.get_ref_bedtool(tz.get_in(["reference", "fasta", "base"], items[0]),
items[0]["config"])
if len(want_bedtool) > 0:
full_bedtool.subtract(want_bedtool, nonamecheck=True).saveas(tx_out_file)
else:
full_bedtool.saveas(tx_out_file)
return out_file | python | def prepare_exclude_file(items, base_file, chrom=None):
"""Prepare a BED file for exclusion.
Excludes high depth and centromere regions which contribute to long run times and
false positive structural variant calls.
"""
items = shared.add_highdepth_genome_exclusion(items)
out_file = "%s-exclude%s.bed" % (utils.splitext_plus(base_file)[0], "-%s" % chrom if chrom else "")
if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
with shared.bedtools_tmpdir(items[0]):
with file_transaction(items[0], out_file) as tx_out_file:
# Get a bedtool for the full region if no variant regions
want_bedtool = callable.get_ref_bedtool(tz.get_in(["reference", "fasta", "base"], items[0]),
items[0]["config"], chrom)
want_bedtool = pybedtools.BedTool(shared.subset_variant_regions(want_bedtool.saveas().fn,
chrom, tx_out_file, items))
sv_exclude_bed = _get_sv_exclude_file(items)
if sv_exclude_bed and len(want_bedtool) > 0:
want_bedtool = want_bedtool.subtract(sv_exclude_bed, nonamecheck=True).saveas()
full_bedtool = callable.get_ref_bedtool(tz.get_in(["reference", "fasta", "base"], items[0]),
items[0]["config"])
if len(want_bedtool) > 0:
full_bedtool.subtract(want_bedtool, nonamecheck=True).saveas(tx_out_file)
else:
full_bedtool.saveas(tx_out_file)
return out_file | [
"def",
"prepare_exclude_file",
"(",
"items",
",",
"base_file",
",",
"chrom",
"=",
"None",
")",
":",
"items",
"=",
"shared",
".",
"add_highdepth_genome_exclusion",
"(",
"items",
")",
"out_file",
"=",
"\"%s-exclude%s.bed\"",
"%",
"(",
"utils",
".",
"splitext_plus"... | Prepare a BED file for exclusion.
Excludes high depth and centromere regions which contribute to long run times and
false positive structural variant calls. | [
"Prepare",
"a",
"BED",
"file",
"for",
"exclusion",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L112-L137 |
224,138 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | exclude_by_ends | def exclude_by_ends(in_file, exclude_file, data, in_params=None):
"""Exclude calls based on overlap of the ends with exclusion regions.
Removes structural variants with either end being in a repeat: a large
source of false positives.
Parameters tuned based on removal of LCR overlapping false positives in DREAM
synthetic 3 data.
"""
params = {"end_buffer": 50,
"rpt_pct": 0.9,
"total_rpt_pct": 0.2,
"sv_pct": 0.5}
if in_params:
params.update(in_params)
assert in_file.endswith(".bed")
out_file = "%s-norepeats%s" % utils.splitext_plus(in_file)
to_filter = collections.defaultdict(list)
removed = 0
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
with shared.bedtools_tmpdir(data):
for coord, end_name in [(1, "end1"), (2, "end2")]:
base, ext = utils.splitext_plus(tx_out_file)
end_file = _create_end_file(in_file, coord, params, "%s-%s%s" % (base, end_name, ext))
to_filter = _find_to_filter(end_file, exclude_file, params, to_filter)
with open(tx_out_file, "w") as out_handle:
with open(in_file) as in_handle:
for line in in_handle:
key = "%s:%s-%s" % tuple(line.strip().split("\t")[:3])
total_rpt_size = sum(to_filter.get(key, [0]))
if total_rpt_size <= (params["total_rpt_pct"] * params["end_buffer"]):
out_handle.write(line)
else:
removed += 1
return out_file, removed | python | def exclude_by_ends(in_file, exclude_file, data, in_params=None):
"""Exclude calls based on overlap of the ends with exclusion regions.
Removes structural variants with either end being in a repeat: a large
source of false positives.
Parameters tuned based on removal of LCR overlapping false positives in DREAM
synthetic 3 data.
"""
params = {"end_buffer": 50,
"rpt_pct": 0.9,
"total_rpt_pct": 0.2,
"sv_pct": 0.5}
if in_params:
params.update(in_params)
assert in_file.endswith(".bed")
out_file = "%s-norepeats%s" % utils.splitext_plus(in_file)
to_filter = collections.defaultdict(list)
removed = 0
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
with shared.bedtools_tmpdir(data):
for coord, end_name in [(1, "end1"), (2, "end2")]:
base, ext = utils.splitext_plus(tx_out_file)
end_file = _create_end_file(in_file, coord, params, "%s-%s%s" % (base, end_name, ext))
to_filter = _find_to_filter(end_file, exclude_file, params, to_filter)
with open(tx_out_file, "w") as out_handle:
with open(in_file) as in_handle:
for line in in_handle:
key = "%s:%s-%s" % tuple(line.strip().split("\t")[:3])
total_rpt_size = sum(to_filter.get(key, [0]))
if total_rpt_size <= (params["total_rpt_pct"] * params["end_buffer"]):
out_handle.write(line)
else:
removed += 1
return out_file, removed | [
"def",
"exclude_by_ends",
"(",
"in_file",
",",
"exclude_file",
",",
"data",
",",
"in_params",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"end_buffer\"",
":",
"50",
",",
"\"rpt_pct\"",
":",
"0.9",
",",
"\"total_rpt_pct\"",
":",
"0.2",
",",
"\"sv_pct\"",
"... | Exclude calls based on overlap of the ends with exclusion regions.
Removes structural variants with either end being in a repeat: a large
source of false positives.
Parameters tuned based on removal of LCR overlapping false positives in DREAM
synthetic 3 data. | [
"Exclude",
"calls",
"based",
"on",
"overlap",
"of",
"the",
"ends",
"with",
"exclusion",
"regions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L139-L174 |
224,139 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | _find_to_filter | def _find_to_filter(in_file, exclude_file, params, to_exclude):
"""Identify regions in the end file that overlap the exclusion file.
We look for ends with a large percentage in a repeat or where the end contains
an entire repeat.
"""
for feat in pybedtools.BedTool(in_file).intersect(pybedtools.BedTool(exclude_file), wao=True, nonamecheck=True):
us_chrom, us_start, us_end, name, other_chrom, other_start, other_end, overlap = feat.fields
if float(overlap) > 0:
other_size = float(other_end) - float(other_start)
other_pct = float(overlap) / other_size
us_pct = float(overlap) / (float(us_end) - float(us_start))
if us_pct > params["sv_pct"] or (other_pct > params["rpt_pct"]):
to_exclude[name].append(float(overlap))
return to_exclude | python | def _find_to_filter(in_file, exclude_file, params, to_exclude):
"""Identify regions in the end file that overlap the exclusion file.
We look for ends with a large percentage in a repeat or where the end contains
an entire repeat.
"""
for feat in pybedtools.BedTool(in_file).intersect(pybedtools.BedTool(exclude_file), wao=True, nonamecheck=True):
us_chrom, us_start, us_end, name, other_chrom, other_start, other_end, overlap = feat.fields
if float(overlap) > 0:
other_size = float(other_end) - float(other_start)
other_pct = float(overlap) / other_size
us_pct = float(overlap) / (float(us_end) - float(us_start))
if us_pct > params["sv_pct"] or (other_pct > params["rpt_pct"]):
to_exclude[name].append(float(overlap))
return to_exclude | [
"def",
"_find_to_filter",
"(",
"in_file",
",",
"exclude_file",
",",
"params",
",",
"to_exclude",
")",
":",
"for",
"feat",
"in",
"pybedtools",
".",
"BedTool",
"(",
"in_file",
")",
".",
"intersect",
"(",
"pybedtools",
".",
"BedTool",
"(",
"exclude_file",
")",
... | Identify regions in the end file that overlap the exclusion file.
We look for ends with a large percentage in a repeat or where the end contains
an entire repeat. | [
"Identify",
"regions",
"in",
"the",
"end",
"file",
"that",
"overlap",
"the",
"exclusion",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L176-L190 |
224,140 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | get_sv_chroms | def get_sv_chroms(items, exclude_file):
"""Retrieve chromosomes to process on, avoiding extra skipped chromosomes.
"""
exclude_regions = {}
for region in pybedtools.BedTool(exclude_file):
if int(region.start) == 0:
exclude_regions[region.chrom] = int(region.end)
out = []
with pysam.Samfile(dd.get_align_bam(items[0]) or dd.get_work_bam(items[0]))as pysam_work_bam:
for chrom, length in zip(pysam_work_bam.references, pysam_work_bam.lengths):
exclude_length = exclude_regions.get(chrom, 0)
if exclude_length < length:
out.append(chrom)
return out | python | def get_sv_chroms(items, exclude_file):
"""Retrieve chromosomes to process on, avoiding extra skipped chromosomes.
"""
exclude_regions = {}
for region in pybedtools.BedTool(exclude_file):
if int(region.start) == 0:
exclude_regions[region.chrom] = int(region.end)
out = []
with pysam.Samfile(dd.get_align_bam(items[0]) or dd.get_work_bam(items[0]))as pysam_work_bam:
for chrom, length in zip(pysam_work_bam.references, pysam_work_bam.lengths):
exclude_length = exclude_regions.get(chrom, 0)
if exclude_length < length:
out.append(chrom)
return out | [
"def",
"get_sv_chroms",
"(",
"items",
",",
"exclude_file",
")",
":",
"exclude_regions",
"=",
"{",
"}",
"for",
"region",
"in",
"pybedtools",
".",
"BedTool",
"(",
"exclude_file",
")",
":",
"if",
"int",
"(",
"region",
".",
"start",
")",
"==",
"0",
":",
"e... | Retrieve chromosomes to process on, avoiding extra skipped chromosomes. | [
"Retrieve",
"chromosomes",
"to",
"process",
"on",
"avoiding",
"extra",
"skipped",
"chromosomes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L209-L222 |
224,141 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | _extract_split_and_discordants | def _extract_split_and_discordants(in_bam, work_dir, data):
"""Retrieve split-read alignments from input BAM file.
"""
sr_file = os.path.join(work_dir, "%s-sr.bam" % os.path.splitext(os.path.basename(in_bam))[0])
disc_file = os.path.join(work_dir, "%s-disc.bam" % os.path.splitext(os.path.basename(in_bam))[0])
if not utils.file_exists(sr_file) or not utils.file_exists(disc_file):
with file_transaction(data, sr_file) as tx_sr_file:
with file_transaction(data, disc_file) as tx_disc_file:
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
cmd = ("extract-sv-reads -e --threads {cores} -T {ref_file} "
"-i {in_bam} -s {tx_sr_file} -d {tx_disc_file}")
do.run(cmd.format(**locals()), "extract split and discordant reads", data)
for fname in [sr_file, disc_file]:
bam.index(fname, data["config"])
return sr_file, disc_file | python | def _extract_split_and_discordants(in_bam, work_dir, data):
"""Retrieve split-read alignments from input BAM file.
"""
sr_file = os.path.join(work_dir, "%s-sr.bam" % os.path.splitext(os.path.basename(in_bam))[0])
disc_file = os.path.join(work_dir, "%s-disc.bam" % os.path.splitext(os.path.basename(in_bam))[0])
if not utils.file_exists(sr_file) or not utils.file_exists(disc_file):
with file_transaction(data, sr_file) as tx_sr_file:
with file_transaction(data, disc_file) as tx_disc_file:
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
cmd = ("extract-sv-reads -e --threads {cores} -T {ref_file} "
"-i {in_bam} -s {tx_sr_file} -d {tx_disc_file}")
do.run(cmd.format(**locals()), "extract split and discordant reads", data)
for fname in [sr_file, disc_file]:
bam.index(fname, data["config"])
return sr_file, disc_file | [
"def",
"_extract_split_and_discordants",
"(",
"in_bam",
",",
"work_dir",
",",
"data",
")",
":",
"sr_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-sr.bam\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
... | Retrieve split-read alignments from input BAM file. | [
"Retrieve",
"split",
"-",
"read",
"alignments",
"from",
"input",
"BAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L226-L241 |
224,142 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | find_existing_split_discordants | def find_existing_split_discordants(data):
"""Check for pre-calculated split reads and discordants done as part of alignment streaming.
"""
in_bam = dd.get_align_bam(data)
sr_file = "%s-sr.bam" % os.path.splitext(in_bam)[0]
disc_file = "%s-disc.bam" % os.path.splitext(in_bam)[0]
if utils.file_exists(sr_file) and utils.file_exists(disc_file):
return sr_file, disc_file
else:
sr_file = dd.get_sr_bam(data)
disc_file = dd.get_disc_bam(data)
if sr_file and utils.file_exists(sr_file) and disc_file and utils.file_exists(disc_file):
return sr_file, disc_file
else:
return None, None | python | def find_existing_split_discordants(data):
"""Check for pre-calculated split reads and discordants done as part of alignment streaming.
"""
in_bam = dd.get_align_bam(data)
sr_file = "%s-sr.bam" % os.path.splitext(in_bam)[0]
disc_file = "%s-disc.bam" % os.path.splitext(in_bam)[0]
if utils.file_exists(sr_file) and utils.file_exists(disc_file):
return sr_file, disc_file
else:
sr_file = dd.get_sr_bam(data)
disc_file = dd.get_disc_bam(data)
if sr_file and utils.file_exists(sr_file) and disc_file and utils.file_exists(disc_file):
return sr_file, disc_file
else:
return None, None | [
"def",
"find_existing_split_discordants",
"(",
"data",
")",
":",
"in_bam",
"=",
"dd",
".",
"get_align_bam",
"(",
"data",
")",
"sr_file",
"=",
"\"%s-sr.bam\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"in_bam",
")",
"[",
"0",
"]",
"disc_file",
"=",
"... | Check for pre-calculated split reads and discordants done as part of alignment streaming. | [
"Check",
"for",
"pre",
"-",
"calculated",
"split",
"reads",
"and",
"discordants",
"done",
"as",
"part",
"of",
"alignment",
"streaming",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L243-L257 |
224,143 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | get_split_discordants | def get_split_discordants(data, work_dir):
"""Retrieve split and discordant reads, potentially calculating with extract_sv_reads as needed.
"""
align_bam = dd.get_align_bam(data)
sr_bam, disc_bam = find_existing_split_discordants(data)
if not sr_bam:
work_dir = (work_dir if not os.access(os.path.dirname(align_bam), os.W_OK | os.X_OK)
else os.path.dirname(align_bam))
sr_bam, disc_bam = _extract_split_and_discordants(align_bam, work_dir, data)
return sr_bam, disc_bam | python | def get_split_discordants(data, work_dir):
"""Retrieve split and discordant reads, potentially calculating with extract_sv_reads as needed.
"""
align_bam = dd.get_align_bam(data)
sr_bam, disc_bam = find_existing_split_discordants(data)
if not sr_bam:
work_dir = (work_dir if not os.access(os.path.dirname(align_bam), os.W_OK | os.X_OK)
else os.path.dirname(align_bam))
sr_bam, disc_bam = _extract_split_and_discordants(align_bam, work_dir, data)
return sr_bam, disc_bam | [
"def",
"get_split_discordants",
"(",
"data",
",",
"work_dir",
")",
":",
"align_bam",
"=",
"dd",
".",
"get_align_bam",
"(",
"data",
")",
"sr_bam",
",",
"disc_bam",
"=",
"find_existing_split_discordants",
"(",
"data",
")",
"if",
"not",
"sr_bam",
":",
"work_dir",... | Retrieve split and discordant reads, potentially calculating with extract_sv_reads as needed. | [
"Retrieve",
"split",
"and",
"discordant",
"reads",
"potentially",
"calculating",
"with",
"extract_sv_reads",
"as",
"needed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L259-L268 |
224,144 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | get_cur_batch | def get_cur_batch(items):
"""Retrieve name of the batch shared between all items in a group.
"""
batches = []
for data in items:
batch = tz.get_in(["metadata", "batch"], data, [])
batches.append(set(batch) if isinstance(batch, (list, tuple)) else set([batch]))
combo_batches = reduce(lambda b1, b2: b1.intersection(b2), batches)
if len(combo_batches) == 1:
return combo_batches.pop()
elif len(combo_batches) == 0:
return None
else:
raise ValueError("Found multiple overlapping batches: %s -- %s" % (combo_batches, batches)) | python | def get_cur_batch(items):
"""Retrieve name of the batch shared between all items in a group.
"""
batches = []
for data in items:
batch = tz.get_in(["metadata", "batch"], data, [])
batches.append(set(batch) if isinstance(batch, (list, tuple)) else set([batch]))
combo_batches = reduce(lambda b1, b2: b1.intersection(b2), batches)
if len(combo_batches) == 1:
return combo_batches.pop()
elif len(combo_batches) == 0:
return None
else:
raise ValueError("Found multiple overlapping batches: %s -- %s" % (combo_batches, batches)) | [
"def",
"get_cur_batch",
"(",
"items",
")",
":",
"batches",
"=",
"[",
"]",
"for",
"data",
"in",
"items",
":",
"batch",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"metadata\"",
",",
"\"batch\"",
"]",
",",
"data",
",",
"[",
"]",
")",
"batches",
".",
"appen... | Retrieve name of the batch shared between all items in a group. | [
"Retrieve",
"name",
"of",
"the",
"batch",
"shared",
"between",
"all",
"items",
"in",
"a",
"group",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L270-L283 |
224,145 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | calc_paired_insert_stats | def calc_paired_insert_stats(in_bam, nsample=1000000):
"""Retrieve statistics for paired end read insert distances.
"""
dists = []
n = 0
with pysam.Samfile(in_bam, "rb") as in_pysam:
for read in in_pysam:
if read.is_proper_pair and read.is_read1:
n += 1
dists.append(abs(read.isize))
if n >= nsample:
break
return insert_size_stats(dists) | python | def calc_paired_insert_stats(in_bam, nsample=1000000):
"""Retrieve statistics for paired end read insert distances.
"""
dists = []
n = 0
with pysam.Samfile(in_bam, "rb") as in_pysam:
for read in in_pysam:
if read.is_proper_pair and read.is_read1:
n += 1
dists.append(abs(read.isize))
if n >= nsample:
break
return insert_size_stats(dists) | [
"def",
"calc_paired_insert_stats",
"(",
"in_bam",
",",
"nsample",
"=",
"1000000",
")",
":",
"dists",
"=",
"[",
"]",
"n",
"=",
"0",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
",",
"\"rb\"",
")",
"as",
"in_pysam",
":",
"for",
"read",
"in",
"in_pysam... | Retrieve statistics for paired end read insert distances. | [
"Retrieve",
"statistics",
"for",
"paired",
"end",
"read",
"insert",
"distances",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L307-L319 |
224,146 | bcbio/bcbio-nextgen | bcbio/structural/shared.py | calc_paired_insert_stats_save | def calc_paired_insert_stats_save(in_bam, stat_file, nsample=1000000):
"""Calculate paired stats, saving to a file for re-runs.
"""
if utils.file_exists(stat_file):
with open(stat_file) as in_handle:
return yaml.safe_load(in_handle)
else:
stats = calc_paired_insert_stats(in_bam, nsample)
with open(stat_file, "w") as out_handle:
yaml.safe_dump(stats, out_handle, default_flow_style=False, allow_unicode=False)
return stats | python | def calc_paired_insert_stats_save(in_bam, stat_file, nsample=1000000):
"""Calculate paired stats, saving to a file for re-runs.
"""
if utils.file_exists(stat_file):
with open(stat_file) as in_handle:
return yaml.safe_load(in_handle)
else:
stats = calc_paired_insert_stats(in_bam, nsample)
with open(stat_file, "w") as out_handle:
yaml.safe_dump(stats, out_handle, default_flow_style=False, allow_unicode=False)
return stats | [
"def",
"calc_paired_insert_stats_save",
"(",
"in_bam",
",",
"stat_file",
",",
"nsample",
"=",
"1000000",
")",
":",
"if",
"utils",
".",
"file_exists",
"(",
"stat_file",
")",
":",
"with",
"open",
"(",
"stat_file",
")",
"as",
"in_handle",
":",
"return",
"yaml",... | Calculate paired stats, saving to a file for re-runs. | [
"Calculate",
"paired",
"stats",
"saving",
"to",
"a",
"file",
"for",
"re",
"-",
"runs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L321-L331 |
224,147 | bcbio/bcbio-nextgen | scripts/utils/upload_to_synapse.py | _accumulate_remotes | def _accumulate_remotes(synapse_parent_id, syn):
"""Retrieve references to all remote directories and files.
"""
remotes = {}
s_base_folder = syn.get(synapse_parent_id)
for (s_dirpath, s_dirpath_id), _, s_filenames in synapseutils.walk(syn, synapse_parent_id):
remotes[s_dirpath] = s_dirpath_id
if s_filenames:
for s_filename, s_filename_id in s_filenames:
remotes[os.path.join(s_dirpath, s_filename)] = s_filename_id
return s_base_folder, remotes | python | def _accumulate_remotes(synapse_parent_id, syn):
"""Retrieve references to all remote directories and files.
"""
remotes = {}
s_base_folder = syn.get(synapse_parent_id)
for (s_dirpath, s_dirpath_id), _, s_filenames in synapseutils.walk(syn, synapse_parent_id):
remotes[s_dirpath] = s_dirpath_id
if s_filenames:
for s_filename, s_filename_id in s_filenames:
remotes[os.path.join(s_dirpath, s_filename)] = s_filename_id
return s_base_folder, remotes | [
"def",
"_accumulate_remotes",
"(",
"synapse_parent_id",
",",
"syn",
")",
":",
"remotes",
"=",
"{",
"}",
"s_base_folder",
"=",
"syn",
".",
"get",
"(",
"synapse_parent_id",
")",
"for",
"(",
"s_dirpath",
",",
"s_dirpath_id",
")",
",",
"_",
",",
"s_filenames",
... | Retrieve references to all remote directories and files. | [
"Retrieve",
"references",
"to",
"all",
"remote",
"directories",
"and",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/upload_to_synapse.py#L38-L48 |
224,148 | bcbio/bcbio-nextgen | scripts/utils/upload_to_synapse.py | _remote_folder | def _remote_folder(dirpath, remotes, syn):
"""Retrieve the remote folder for files, creating if necessary.
"""
if dirpath in remotes:
return remotes[dirpath], remotes
else:
parent_dir, cur_dir = os.path.split(dirpath)
parent_folder, remotes = _remote_folder(parent_dir, remotes, syn)
s_cur_dir = syn.store(synapseclient.Folder(cur_dir, parent=parent_folder))
remotes[dirpath] = s_cur_dir.id
return s_cur_dir.id, remotes | python | def _remote_folder(dirpath, remotes, syn):
"""Retrieve the remote folder for files, creating if necessary.
"""
if dirpath in remotes:
return remotes[dirpath], remotes
else:
parent_dir, cur_dir = os.path.split(dirpath)
parent_folder, remotes = _remote_folder(parent_dir, remotes, syn)
s_cur_dir = syn.store(synapseclient.Folder(cur_dir, parent=parent_folder))
remotes[dirpath] = s_cur_dir.id
return s_cur_dir.id, remotes | [
"def",
"_remote_folder",
"(",
"dirpath",
",",
"remotes",
",",
"syn",
")",
":",
"if",
"dirpath",
"in",
"remotes",
":",
"return",
"remotes",
"[",
"dirpath",
"]",
",",
"remotes",
"else",
":",
"parent_dir",
",",
"cur_dir",
"=",
"os",
".",
"path",
".",
"spl... | Retrieve the remote folder for files, creating if necessary. | [
"Retrieve",
"the",
"remote",
"folder",
"for",
"files",
"creating",
"if",
"necessary",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/upload_to_synapse.py#L50-L60 |
224,149 | bcbio/bcbio-nextgen | bcbio/structural/wham.py | run | def run(items, background=None):
"""Detect copy number variations from batched set of samples using WHAM.
"""
if not background: background = []
background_bams = []
paired = vcfutils.get_paired_bams([x["align_bam"] for x in items], items)
if paired:
inputs = [paired.tumor_data]
if paired.normal_bam:
background = [paired.normal_data]
background_bams = [paired.normal_bam]
else:
assert not background
inputs, background = shared.find_case_control(items)
background_bams = [x["align_bam"] for x in background]
orig_vcf = _run_wham(inputs, background_bams)
out = []
for data in inputs:
if "sv" not in data:
data["sv"] = []
final_vcf = shared.finalize_sv(orig_vcf, data, items)
data["sv"].append({"variantcaller": "wham", "vrn_file": final_vcf})
out.append(data)
return out | python | def run(items, background=None):
"""Detect copy number variations from batched set of samples using WHAM.
"""
if not background: background = []
background_bams = []
paired = vcfutils.get_paired_bams([x["align_bam"] for x in items], items)
if paired:
inputs = [paired.tumor_data]
if paired.normal_bam:
background = [paired.normal_data]
background_bams = [paired.normal_bam]
else:
assert not background
inputs, background = shared.find_case_control(items)
background_bams = [x["align_bam"] for x in background]
orig_vcf = _run_wham(inputs, background_bams)
out = []
for data in inputs:
if "sv" not in data:
data["sv"] = []
final_vcf = shared.finalize_sv(orig_vcf, data, items)
data["sv"].append({"variantcaller": "wham", "vrn_file": final_vcf})
out.append(data)
return out | [
"def",
"run",
"(",
"items",
",",
"background",
"=",
"None",
")",
":",
"if",
"not",
"background",
":",
"background",
"=",
"[",
"]",
"background_bams",
"=",
"[",
"]",
"paired",
"=",
"vcfutils",
".",
"get_paired_bams",
"(",
"[",
"x",
"[",
"\"align_bam\"",
... | Detect copy number variations from batched set of samples using WHAM. | [
"Detect",
"copy",
"number",
"variations",
"from",
"batched",
"set",
"of",
"samples",
"using",
"WHAM",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/wham.py#L19-L42 |
224,150 | bcbio/bcbio-nextgen | bcbio/structural/wham.py | _run_wham | def _run_wham(inputs, background_bams):
"""Run WHAM on a defined set of inputs and targets.
"""
out_file = os.path.join(_sv_workdir(inputs[0]), "%s-wham.vcf.gz" % dd.get_sample_name(inputs[0]))
if not utils.file_exists(out_file):
with file_transaction(inputs[0], out_file) as tx_out_file:
cores = dd.get_cores(inputs[0])
ref_file = dd.get_ref_file(inputs[0])
include_chroms = ",".join([c.name for c in ref.file_contigs(ref_file)
if chromhacks.is_autosomal_or_x(c.name)])
all_bams = ",".join([x["align_bam"] for x in inputs] + background_bams)
cmd = ("whamg -x {cores} -a {ref_file} -f {all_bams} -c {include_chroms} "
"| bgzip -c > {tx_out_file}")
do.run(cmd.format(**locals()), "WHAM SV caller: %s" % ", ".join(dd.get_sample_name(d) for d in inputs))
return vcfutils.bgzip_and_index(out_file, inputs[0]["config"]) | python | def _run_wham(inputs, background_bams):
"""Run WHAM on a defined set of inputs and targets.
"""
out_file = os.path.join(_sv_workdir(inputs[0]), "%s-wham.vcf.gz" % dd.get_sample_name(inputs[0]))
if not utils.file_exists(out_file):
with file_transaction(inputs[0], out_file) as tx_out_file:
cores = dd.get_cores(inputs[0])
ref_file = dd.get_ref_file(inputs[0])
include_chroms = ",".join([c.name for c in ref.file_contigs(ref_file)
if chromhacks.is_autosomal_or_x(c.name)])
all_bams = ",".join([x["align_bam"] for x in inputs] + background_bams)
cmd = ("whamg -x {cores} -a {ref_file} -f {all_bams} -c {include_chroms} "
"| bgzip -c > {tx_out_file}")
do.run(cmd.format(**locals()), "WHAM SV caller: %s" % ", ".join(dd.get_sample_name(d) for d in inputs))
return vcfutils.bgzip_and_index(out_file, inputs[0]["config"]) | [
"def",
"_run_wham",
"(",
"inputs",
",",
"background_bams",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_sv_workdir",
"(",
"inputs",
"[",
"0",
"]",
")",
",",
"\"%s-wham.vcf.gz\"",
"%",
"dd",
".",
"get_sample_name",
"(",
"inputs",
"[",... | Run WHAM on a defined set of inputs and targets. | [
"Run",
"WHAM",
"on",
"a",
"defined",
"set",
"of",
"inputs",
"and",
"targets",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/wham.py#L48-L62 |
224,151 | bcbio/bcbio-nextgen | bcbio/structural/wham.py | filter_by_background | def filter_by_background(in_vcf, full_vcf, background, data):
"""Filter SV calls also present in background samples.
Skips filtering of inversions, which are not characterized differently
between cases and controls in test datasets.
"""
Filter = collections.namedtuple('Filter', ['id', 'desc'])
back_filter = Filter(id='InBackground',
desc='Rejected due to presence in background sample')
out_file = "%s-filter.vcf" % utils.splitext_plus(in_vcf)[0]
if not utils.file_uptodate(out_file, in_vcf) and not utils.file_uptodate(out_file + ".vcf.gz", in_vcf):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
reader = vcf.VCFReader(filename=in_vcf)
reader.filters["InBackground"] = back_filter
full_reader = vcf.VCFReader(filename=full_vcf)
writer = vcf.VCFWriter(out_handle, template=reader)
for out_rec, rec in zip(reader, full_reader):
rec_type = rec.genotype(dd.get_sample_name(data)).gt_type
if rec_type == 0 or any(rec_type == rec.genotype(dd.get_sample_name(x)).gt_type
for x in background):
out_rec.add_filter("InBackground")
writer.write_record(out_rec)
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def filter_by_background(in_vcf, full_vcf, background, data):
"""Filter SV calls also present in background samples.
Skips filtering of inversions, which are not characterized differently
between cases and controls in test datasets.
"""
Filter = collections.namedtuple('Filter', ['id', 'desc'])
back_filter = Filter(id='InBackground',
desc='Rejected due to presence in background sample')
out_file = "%s-filter.vcf" % utils.splitext_plus(in_vcf)[0]
if not utils.file_uptodate(out_file, in_vcf) and not utils.file_uptodate(out_file + ".vcf.gz", in_vcf):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
reader = vcf.VCFReader(filename=in_vcf)
reader.filters["InBackground"] = back_filter
full_reader = vcf.VCFReader(filename=full_vcf)
writer = vcf.VCFWriter(out_handle, template=reader)
for out_rec, rec in zip(reader, full_reader):
rec_type = rec.genotype(dd.get_sample_name(data)).gt_type
if rec_type == 0 or any(rec_type == rec.genotype(dd.get_sample_name(x)).gt_type
for x in background):
out_rec.add_filter("InBackground")
writer.write_record(out_rec)
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"filter_by_background",
"(",
"in_vcf",
",",
"full_vcf",
",",
"background",
",",
"data",
")",
":",
"Filter",
"=",
"collections",
".",
"namedtuple",
"(",
"'Filter'",
",",
"[",
"'id'",
",",
"'desc'",
"]",
")",
"back_filter",
"=",
"Filter",
"(",
"id",
... | Filter SV calls also present in background samples.
Skips filtering of inversions, which are not characterized differently
between cases and controls in test datasets. | [
"Filter",
"SV",
"calls",
"also",
"present",
"in",
"background",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/wham.py#L64-L87 |
224,152 | bcbio/bcbio-nextgen | bcbio/variation/gatkjoint.py | run_region | def run_region(data, region, vrn_files, out_file):
"""Perform variant calling on gVCF inputs in a specific genomic region.
"""
broad_runner = broad.runner_from_config(data["config"])
if broad_runner.gatk_type() == "gatk4":
genomics_db = _run_genomicsdb_import(vrn_files, region, out_file, data)
return _run_genotype_gvcfs_genomicsdb(genomics_db, region, out_file, data)
else:
vrn_files = _batch_gvcfs(data, region, vrn_files, dd.get_ref_file(data), out_file)
return _run_genotype_gvcfs_gatk3(data, region, vrn_files, dd.get_ref_file(data), out_file) | python | def run_region(data, region, vrn_files, out_file):
"""Perform variant calling on gVCF inputs in a specific genomic region.
"""
broad_runner = broad.runner_from_config(data["config"])
if broad_runner.gatk_type() == "gatk4":
genomics_db = _run_genomicsdb_import(vrn_files, region, out_file, data)
return _run_genotype_gvcfs_genomicsdb(genomics_db, region, out_file, data)
else:
vrn_files = _batch_gvcfs(data, region, vrn_files, dd.get_ref_file(data), out_file)
return _run_genotype_gvcfs_gatk3(data, region, vrn_files, dd.get_ref_file(data), out_file) | [
"def",
"run_region",
"(",
"data",
",",
"region",
",",
"vrn_files",
",",
"out_file",
")",
":",
"broad_runner",
"=",
"broad",
".",
"runner_from_config",
"(",
"data",
"[",
"\"config\"",
"]",
")",
"if",
"broad_runner",
".",
"gatk_type",
"(",
")",
"==",
"\"gatk... | Perform variant calling on gVCF inputs in a specific genomic region. | [
"Perform",
"variant",
"calling",
"on",
"gVCF",
"inputs",
"in",
"a",
"specific",
"genomic",
"region",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkjoint.py#L18-L27 |
224,153 | bcbio/bcbio-nextgen | bcbio/variation/gatkjoint.py | _incomplete_genomicsdb | def _incomplete_genomicsdb(dbdir):
"""Check if a GenomicsDB output is incomplete and we should regenerate.
Works around current inability to move GenomicsDB outputs and support
transactional directories.
"""
for test_file in ["callset.json", "vidmap.json", "genomicsdb_array/genomicsdb_meta.json"]:
if not os.path.exists(os.path.join(dbdir, test_file)):
return True
return False | python | def _incomplete_genomicsdb(dbdir):
"""Check if a GenomicsDB output is incomplete and we should regenerate.
Works around current inability to move GenomicsDB outputs and support
transactional directories.
"""
for test_file in ["callset.json", "vidmap.json", "genomicsdb_array/genomicsdb_meta.json"]:
if not os.path.exists(os.path.join(dbdir, test_file)):
return True
return False | [
"def",
"_incomplete_genomicsdb",
"(",
"dbdir",
")",
":",
"for",
"test_file",
"in",
"[",
"\"callset.json\"",
",",
"\"vidmap.json\"",
",",
"\"genomicsdb_array/genomicsdb_meta.json\"",
"]",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",... | Check if a GenomicsDB output is incomplete and we should regenerate.
Works around current inability to move GenomicsDB outputs and support
transactional directories. | [
"Check",
"if",
"a",
"GenomicsDB",
"output",
"is",
"incomplete",
"and",
"we",
"should",
"regenerate",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkjoint.py#L64-L73 |
224,154 | bcbio/bcbio-nextgen | bcbio/variation/gatkjoint.py | _run_genotype_gvcfs_gatk3 | def _run_genotype_gvcfs_gatk3(data, region, vrn_files, ref_file, out_file):
"""Performs genotyping of gVCFs into final VCF files.
"""
if not utils.file_exists(out_file):
broad_runner = broad.runner_from_config(data["config"])
with file_transaction(data, out_file) as tx_out_file:
assoc_files = tz.get_in(("genome_resources", "variation"), data, {})
if not assoc_files: assoc_files = {}
params = ["-T", "GenotypeGVCFs",
"-R", ref_file, "-o", tx_out_file,
"-L", bamprep.region_to_gatk(region),
"--max_alternate_alleles", "4"]
for vrn_file in vrn_files:
params += ["--variant", vrn_file]
if assoc_files.get("dbsnp"):
params += ["--dbsnp", assoc_files["dbsnp"]]
broad_runner.new_resources("gatk-haplotype")
cores = dd.get_cores(data)
if cores > 1:
# GATK performs poorly with memory usage when parallelizing
# with a large number of cores but makes use of extra memory,
# so we cap at 6 cores.
# See issue #1565 for discussion
# Recent GATK 3.x versions also have race conditions with multiple
# threads, so limit to 1 and keep memory available
# https://gatkforums.broadinstitute.org/wdl/discussion/8718/concurrentmodificationexception-in-gatk-3-7-genotypegvcfs
# params += ["-nt", str(min(6, cores))]
memscale = {"magnitude": 0.9 * cores, "direction": "increase"}
else:
memscale = None
broad_runner.run_gatk(params, memscale=memscale, parallel_gc=True)
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def _run_genotype_gvcfs_gatk3(data, region, vrn_files, ref_file, out_file):
"""Performs genotyping of gVCFs into final VCF files.
"""
if not utils.file_exists(out_file):
broad_runner = broad.runner_from_config(data["config"])
with file_transaction(data, out_file) as tx_out_file:
assoc_files = tz.get_in(("genome_resources", "variation"), data, {})
if not assoc_files: assoc_files = {}
params = ["-T", "GenotypeGVCFs",
"-R", ref_file, "-o", tx_out_file,
"-L", bamprep.region_to_gatk(region),
"--max_alternate_alleles", "4"]
for vrn_file in vrn_files:
params += ["--variant", vrn_file]
if assoc_files.get("dbsnp"):
params += ["--dbsnp", assoc_files["dbsnp"]]
broad_runner.new_resources("gatk-haplotype")
cores = dd.get_cores(data)
if cores > 1:
# GATK performs poorly with memory usage when parallelizing
# with a large number of cores but makes use of extra memory,
# so we cap at 6 cores.
# See issue #1565 for discussion
# Recent GATK 3.x versions also have race conditions with multiple
# threads, so limit to 1 and keep memory available
# https://gatkforums.broadinstitute.org/wdl/discussion/8718/concurrentmodificationexception-in-gatk-3-7-genotypegvcfs
# params += ["-nt", str(min(6, cores))]
memscale = {"magnitude": 0.9 * cores, "direction": "increase"}
else:
memscale = None
broad_runner.run_gatk(params, memscale=memscale, parallel_gc=True)
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"_run_genotype_gvcfs_gatk3",
"(",
"data",
",",
"region",
",",
"vrn_files",
",",
"ref_file",
",",
"out_file",
")",
":",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"broad_runner",
"=",
"broad",
".",
"runner_from_config",
"(",
"... | Performs genotyping of gVCFs into final VCF files. | [
"Performs",
"genotyping",
"of",
"gVCFs",
"into",
"final",
"VCF",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkjoint.py#L102-L133 |
224,155 | bcbio/bcbio-nextgen | bcbio/variation/gatkjoint.py | _batch_gvcfs | def _batch_gvcfs(data, region, vrn_files, ref_file, out_file=None):
"""Perform batching of gVCF files if above recommended input count.
"""
if out_file is None:
out_file = vrn_files[0]
# group to get below the maximum batch size, using 200 as the baseline
max_batch = int(dd.get_joint_group_size(data))
if len(vrn_files) > max_batch:
out = []
num_batches = int(math.ceil(float(len(vrn_files)) / max_batch))
for i, batch_vrn_files in enumerate(tz.partition_all(num_batches, vrn_files)):
base, ext = utils.splitext_plus(out_file)
batch_out_file = "%s-b%s%s" % (base, i, ext)
out.append(run_combine_gvcfs(batch_vrn_files, region, ref_file, batch_out_file, data))
return _batch_gvcfs(data, region, out, ref_file)
else:
return vrn_files | python | def _batch_gvcfs(data, region, vrn_files, ref_file, out_file=None):
"""Perform batching of gVCF files if above recommended input count.
"""
if out_file is None:
out_file = vrn_files[0]
# group to get below the maximum batch size, using 200 as the baseline
max_batch = int(dd.get_joint_group_size(data))
if len(vrn_files) > max_batch:
out = []
num_batches = int(math.ceil(float(len(vrn_files)) / max_batch))
for i, batch_vrn_files in enumerate(tz.partition_all(num_batches, vrn_files)):
base, ext = utils.splitext_plus(out_file)
batch_out_file = "%s-b%s%s" % (base, i, ext)
out.append(run_combine_gvcfs(batch_vrn_files, region, ref_file, batch_out_file, data))
return _batch_gvcfs(data, region, out, ref_file)
else:
return vrn_files | [
"def",
"_batch_gvcfs",
"(",
"data",
",",
"region",
",",
"vrn_files",
",",
"ref_file",
",",
"out_file",
"=",
"None",
")",
":",
"if",
"out_file",
"is",
"None",
":",
"out_file",
"=",
"vrn_files",
"[",
"0",
"]",
"# group to get below the maximum batch size, using 20... | Perform batching of gVCF files if above recommended input count. | [
"Perform",
"batching",
"of",
"gVCF",
"files",
"if",
"above",
"recommended",
"input",
"count",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkjoint.py#L137-L153 |
224,156 | bcbio/bcbio-nextgen | bcbio/qc/preseq.py | _get_preseq_params | def _get_preseq_params(data, preseq_cmd, read_count):
""" Get parameters through resources.
If "step" or "extrap" limit are not provided, then calculate optimal values based on read count.
"""
defaults = {
'seg_len': 100000, # maximum segment length when merging paired end bam reads
'steps': 300, # number of points on the plot
'extrap_fraction': 3, # extrapolate up to X times read_count
'extrap': None, # extrapolate up to X reads
'step': None, # step size (number of reads between points on the plot)
'options': '',
}
params = {}
main_opts = [("-e", "-extrap"), ("-l", "-seg_len"), ("-s", "-step")]
other_opts = config_utils.get_resources("preseq", data["config"]).get("options", [])
if isinstance(other_opts, str):
other_opts = [other_opts]
for sht, lng in main_opts:
if sht in other_opts:
i = other_opts.index(sht)
elif lng in other_opts:
i = other_opts.index(lng)
else:
i = None
if i is not None:
params[lng[1:]] = other_opts[i + 1]
other_opts = other_opts[:i] + other_opts[i + 2:]
params['options'] = ' '.join(other_opts)
for k, v in config_utils.get_resources("preseq", data["config"]).items():
if k != 'options':
params[k] = v
params['steps'] = params.get('steps', defaults['steps'])
if preseq_cmd == 'c_curve':
params['extrap_fraction'] = 1
else:
if params.get('step') is None:
if params.get('extrap') is None:
unrounded__extrap = read_count * params.get('extrap_fraction', defaults['extrap_fraction'])
unrounded__step = unrounded__extrap // params['steps']
if params.get('extrap_fraction') is not None: # extrap_fraction explicitly provided
params['extrap'] = unrounded__extrap
params['step'] = unrounded__step
else:
power_of_10 = 10 ** math.floor(math.log(unrounded__step, 10))
rounded__step = int(math.floor(unrounded__step // power_of_10) * power_of_10)
rounded__extrap = int(rounded__step) * params['steps']
params['step'] = rounded__step
params['extrap'] = rounded__extrap
else:
params['step'] = params['extrap'] // params['steps']
elif params.get('extrap') is None:
params['extrap'] = params['step'] * params['steps']
params['step'] = params.get('step', defaults['step'])
params['extrap'] = params.get('extrap', defaults['extrap'])
params['seg_len'] = params.get('seg_len', defaults['seg_len'])
logger.info("Preseq: running {steps} steps of size {step}, extap limit {extrap}".format(**params))
return params | python | def _get_preseq_params(data, preseq_cmd, read_count):
""" Get parameters through resources.
If "step" or "extrap" limit are not provided, then calculate optimal values based on read count.
"""
defaults = {
'seg_len': 100000, # maximum segment length when merging paired end bam reads
'steps': 300, # number of points on the plot
'extrap_fraction': 3, # extrapolate up to X times read_count
'extrap': None, # extrapolate up to X reads
'step': None, # step size (number of reads between points on the plot)
'options': '',
}
params = {}
main_opts = [("-e", "-extrap"), ("-l", "-seg_len"), ("-s", "-step")]
other_opts = config_utils.get_resources("preseq", data["config"]).get("options", [])
if isinstance(other_opts, str):
other_opts = [other_opts]
for sht, lng in main_opts:
if sht in other_opts:
i = other_opts.index(sht)
elif lng in other_opts:
i = other_opts.index(lng)
else:
i = None
if i is not None:
params[lng[1:]] = other_opts[i + 1]
other_opts = other_opts[:i] + other_opts[i + 2:]
params['options'] = ' '.join(other_opts)
for k, v in config_utils.get_resources("preseq", data["config"]).items():
if k != 'options':
params[k] = v
params['steps'] = params.get('steps', defaults['steps'])
if preseq_cmd == 'c_curve':
params['extrap_fraction'] = 1
else:
if params.get('step') is None:
if params.get('extrap') is None:
unrounded__extrap = read_count * params.get('extrap_fraction', defaults['extrap_fraction'])
unrounded__step = unrounded__extrap // params['steps']
if params.get('extrap_fraction') is not None: # extrap_fraction explicitly provided
params['extrap'] = unrounded__extrap
params['step'] = unrounded__step
else:
power_of_10 = 10 ** math.floor(math.log(unrounded__step, 10))
rounded__step = int(math.floor(unrounded__step // power_of_10) * power_of_10)
rounded__extrap = int(rounded__step) * params['steps']
params['step'] = rounded__step
params['extrap'] = rounded__extrap
else:
params['step'] = params['extrap'] // params['steps']
elif params.get('extrap') is None:
params['extrap'] = params['step'] * params['steps']
params['step'] = params.get('step', defaults['step'])
params['extrap'] = params.get('extrap', defaults['extrap'])
params['seg_len'] = params.get('seg_len', defaults['seg_len'])
logger.info("Preseq: running {steps} steps of size {step}, extap limit {extrap}".format(**params))
return params | [
"def",
"_get_preseq_params",
"(",
"data",
",",
"preseq_cmd",
",",
"read_count",
")",
":",
"defaults",
"=",
"{",
"'seg_len'",
":",
"100000",
",",
"# maximum segment length when merging paired end bam reads",
"'steps'",
":",
"300",
",",
"# number of points on the plot",
"... | Get parameters through resources.
If "step" or "extrap" limit are not provided, then calculate optimal values based on read count. | [
"Get",
"parameters",
"through",
"resources",
".",
"If",
"step",
"or",
"extrap",
"limit",
"are",
"not",
"provided",
"then",
"calculate",
"optimal",
"values",
"based",
"on",
"read",
"count",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/preseq.py#L51-L114 |
224,157 | bcbio/bcbio-nextgen | bcbio/variation/germline.py | split_somatic | def split_somatic(items):
"""Split somatic batches, adding a germline target.
Enables separate germline calling of samples using shared alignments.
"""
items = [_clean_flat_variantcaller(x) for x in items]
somatic_groups, somatic, non_somatic = vcfutils.somatic_batches(items)
# extract germline samples to run from normals in tumor/normal pairs
germline_added = set([])
germline = []
for somatic_group in somatic_groups:
paired = vcfutils.get_paired(somatic_group)
if paired and paired.normal_data:
cur = utils.deepish_copy(paired.normal_data)
vc = dd.get_variantcaller(cur)
if isinstance(vc, dict) and "germline" in vc:
if cur["description"] not in germline_added:
germline_added.add(cur["description"])
cur["rgnames"]["sample"] = cur["description"]
cur["metadata"]["batch"] = "%s-germline" % cur["description"]
cur["metadata"]["phenotype"] = "germline"
cur = remove_align_qc_tools(cur)
cur["config"]["algorithm"]["variantcaller"] = vc["germline"]
germline.append(cur)
# Fix variantcalling specification for only somatic targets
somatic_out = []
for data in somatic:
vc = dd.get_variantcaller(data)
if isinstance(vc, dict) and "somatic" in vc:
data["config"]["algorithm"]["variantcaller"] = vc["somatic"]
somatic_out.append(data)
return non_somatic + somatic_out + germline | python | def split_somatic(items):
"""Split somatic batches, adding a germline target.
Enables separate germline calling of samples using shared alignments.
"""
items = [_clean_flat_variantcaller(x) for x in items]
somatic_groups, somatic, non_somatic = vcfutils.somatic_batches(items)
# extract germline samples to run from normals in tumor/normal pairs
germline_added = set([])
germline = []
for somatic_group in somatic_groups:
paired = vcfutils.get_paired(somatic_group)
if paired and paired.normal_data:
cur = utils.deepish_copy(paired.normal_data)
vc = dd.get_variantcaller(cur)
if isinstance(vc, dict) and "germline" in vc:
if cur["description"] not in germline_added:
germline_added.add(cur["description"])
cur["rgnames"]["sample"] = cur["description"]
cur["metadata"]["batch"] = "%s-germline" % cur["description"]
cur["metadata"]["phenotype"] = "germline"
cur = remove_align_qc_tools(cur)
cur["config"]["algorithm"]["variantcaller"] = vc["germline"]
germline.append(cur)
# Fix variantcalling specification for only somatic targets
somatic_out = []
for data in somatic:
vc = dd.get_variantcaller(data)
if isinstance(vc, dict) and "somatic" in vc:
data["config"]["algorithm"]["variantcaller"] = vc["somatic"]
somatic_out.append(data)
return non_somatic + somatic_out + germline | [
"def",
"split_somatic",
"(",
"items",
")",
":",
"items",
"=",
"[",
"_clean_flat_variantcaller",
"(",
"x",
")",
"for",
"x",
"in",
"items",
"]",
"somatic_groups",
",",
"somatic",
",",
"non_somatic",
"=",
"vcfutils",
".",
"somatic_batches",
"(",
"items",
")",
... | Split somatic batches, adding a germline target.
Enables separate germline calling of samples using shared alignments. | [
"Split",
"somatic",
"batches",
"adding",
"a",
"germline",
"target",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/germline.py#L19-L50 |
224,158 | bcbio/bcbio-nextgen | bcbio/variation/germline.py | _clean_flat_variantcaller | def _clean_flat_variantcaller(data):
"""Convert flattened dictionary from CWL representation into dictionary.
CWL flattens somatic/germline tags into a set of strings, which we
reconstitute as a dictionary.
"""
vc = dd.get_variantcaller(data)
if isinstance(vc, (list, tuple)) and all([x.count(":") == 1 for x in vc]):
out = {}
for v in vc:
k, v = v.split(":")
if k in out:
out[k].append(v)
else:
out[k] = [v]
data = dd.set_variantcaller(data, out)
return data | python | def _clean_flat_variantcaller(data):
"""Convert flattened dictionary from CWL representation into dictionary.
CWL flattens somatic/germline tags into a set of strings, which we
reconstitute as a dictionary.
"""
vc = dd.get_variantcaller(data)
if isinstance(vc, (list, tuple)) and all([x.count(":") == 1 for x in vc]):
out = {}
for v in vc:
k, v = v.split(":")
if k in out:
out[k].append(v)
else:
out[k] = [v]
data = dd.set_variantcaller(data, out)
return data | [
"def",
"_clean_flat_variantcaller",
"(",
"data",
")",
":",
"vc",
"=",
"dd",
".",
"get_variantcaller",
"(",
"data",
")",
"if",
"isinstance",
"(",
"vc",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"all",
"(",
"[",
"x",
".",
"count",
"(",
"\":\"",
... | Convert flattened dictionary from CWL representation into dictionary.
CWL flattens somatic/germline tags into a set of strings, which we
reconstitute as a dictionary. | [
"Convert",
"flattened",
"dictionary",
"from",
"CWL",
"representation",
"into",
"dictionary",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/germline.py#L52-L68 |
224,159 | bcbio/bcbio-nextgen | bcbio/variation/germline.py | remove_align_qc_tools | def remove_align_qc_tools(data):
"""Remove alignment based QC tools we don't need for data replicates.
When we do multiple variant calling on a sample file (somatic/germline),
avoid re-running QC.
"""
align_qc = set(["qsignature", "coverage", "picard", "samtools", "fastqc"])
data["config"]["algorithm"]["qc"] = [t for t in dd.get_algorithm_qc(data)
if t not in align_qc]
return data | python | def remove_align_qc_tools(data):
"""Remove alignment based QC tools we don't need for data replicates.
When we do multiple variant calling on a sample file (somatic/germline),
avoid re-running QC.
"""
align_qc = set(["qsignature", "coverage", "picard", "samtools", "fastqc"])
data["config"]["algorithm"]["qc"] = [t for t in dd.get_algorithm_qc(data)
if t not in align_qc]
return data | [
"def",
"remove_align_qc_tools",
"(",
"data",
")",
":",
"align_qc",
"=",
"set",
"(",
"[",
"\"qsignature\"",
",",
"\"coverage\"",
",",
"\"picard\"",
",",
"\"samtools\"",
",",
"\"fastqc\"",
"]",
")",
"data",
"[",
"\"config\"",
"]",
"[",
"\"algorithm\"",
"]",
"[... | Remove alignment based QC tools we don't need for data replicates.
When we do multiple variant calling on a sample file (somatic/germline),
avoid re-running QC. | [
"Remove",
"alignment",
"based",
"QC",
"tools",
"we",
"don",
"t",
"need",
"for",
"data",
"replicates",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/germline.py#L70-L79 |
224,160 | bcbio/bcbio-nextgen | bcbio/variation/germline.py | extract | def extract(data, items, out_dir=None):
"""Extract germline calls for the given sample, if tumor only.
"""
if vcfutils.get_paired_phenotype(data):
if len(items) == 1:
germline_vcf = _remove_prioritization(data["vrn_file"], data, out_dir)
germline_vcf = vcfutils.bgzip_and_index(germline_vcf, data["config"])
data["vrn_file_plus"] = {"germline": germline_vcf}
return data | python | def extract(data, items, out_dir=None):
"""Extract germline calls for the given sample, if tumor only.
"""
if vcfutils.get_paired_phenotype(data):
if len(items) == 1:
germline_vcf = _remove_prioritization(data["vrn_file"], data, out_dir)
germline_vcf = vcfutils.bgzip_and_index(germline_vcf, data["config"])
data["vrn_file_plus"] = {"germline": germline_vcf}
return data | [
"def",
"extract",
"(",
"data",
",",
"items",
",",
"out_dir",
"=",
"None",
")",
":",
"if",
"vcfutils",
".",
"get_paired_phenotype",
"(",
"data",
")",
":",
"if",
"len",
"(",
"items",
")",
"==",
"1",
":",
"germline_vcf",
"=",
"_remove_prioritization",
"(",
... | Extract germline calls for the given sample, if tumor only. | [
"Extract",
"germline",
"calls",
"for",
"the",
"given",
"sample",
"if",
"tumor",
"only",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/germline.py#L81-L89 |
224,161 | bcbio/bcbio-nextgen | bcbio/variation/germline.py | fix_germline_samplename | def fix_germline_samplename(in_file, sample_name, data):
"""Replace germline sample names, originally from normal BAM file.
"""
out_file = "%s-fixnames%s" % utils.splitext_plus(in_file)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
sample_file = "%s-samples.txt" % utils.splitext_plus(tx_out_file)[0]
with open(sample_file, "w") as out_handle:
out_handle.write("%s\n" % sample_name)
cmd = ("bcftools reheader -s {sample_file} {in_file} -o {tx_out_file}")
do.run(cmd.format(**locals()), "Fix germline samplename: %s" % sample_name)
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def fix_germline_samplename(in_file, sample_name, data):
"""Replace germline sample names, originally from normal BAM file.
"""
out_file = "%s-fixnames%s" % utils.splitext_plus(in_file)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
sample_file = "%s-samples.txt" % utils.splitext_plus(tx_out_file)[0]
with open(sample_file, "w") as out_handle:
out_handle.write("%s\n" % sample_name)
cmd = ("bcftools reheader -s {sample_file} {in_file} -o {tx_out_file}")
do.run(cmd.format(**locals()), "Fix germline samplename: %s" % sample_name)
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"fix_germline_samplename",
"(",
"in_file",
",",
"sample_name",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-fixnames%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"... | Replace germline sample names, originally from normal BAM file. | [
"Replace",
"germline",
"sample",
"names",
"originally",
"from",
"normal",
"BAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/germline.py#L133-L144 |
224,162 | bcbio/bcbio-nextgen | bcbio/variation/germline.py | _remove_prioritization | def _remove_prioritization(in_file, data, out_dir=None):
"""Remove tumor-only prioritization and return non-filtered calls.
"""
out_file = "%s-germline.vcf" % utils.splitext_plus(in_file)[0]
if out_dir:
out_file = os.path.join(out_dir, os.path.basename(out_file))
if not utils.file_uptodate(out_file, in_file) and not utils.file_uptodate(out_file + ".gz", in_file):
with file_transaction(data, out_file) as tx_out_file:
reader = cyvcf2.VCF(str(in_file))
reader.add_filter_to_header({'ID': 'Somatic', 'Description': 'Variant called as Somatic'})
# with open(tx_out_file, "w") as out_handle:
# out_handle.write(reader.raw_header)
with contextlib.closing(cyvcf2.Writer(tx_out_file, reader)) as writer:
for rec in reader:
rec = _update_prioritization_filters(rec)
# out_handle.write(str(rec))
writer.write_record(rec)
return out_file | python | def _remove_prioritization(in_file, data, out_dir=None):
"""Remove tumor-only prioritization and return non-filtered calls.
"""
out_file = "%s-germline.vcf" % utils.splitext_plus(in_file)[0]
if out_dir:
out_file = os.path.join(out_dir, os.path.basename(out_file))
if not utils.file_uptodate(out_file, in_file) and not utils.file_uptodate(out_file + ".gz", in_file):
with file_transaction(data, out_file) as tx_out_file:
reader = cyvcf2.VCF(str(in_file))
reader.add_filter_to_header({'ID': 'Somatic', 'Description': 'Variant called as Somatic'})
# with open(tx_out_file, "w") as out_handle:
# out_handle.write(reader.raw_header)
with contextlib.closing(cyvcf2.Writer(tx_out_file, reader)) as writer:
for rec in reader:
rec = _update_prioritization_filters(rec)
# out_handle.write(str(rec))
writer.write_record(rec)
return out_file | [
"def",
"_remove_prioritization",
"(",
"in_file",
",",
"data",
",",
"out_dir",
"=",
"None",
")",
":",
"out_file",
"=",
"\"%s-germline.vcf\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"[",
"0",
"]",
"if",
"out_dir",
":",
"out_file",
"=",
"os"... | Remove tumor-only prioritization and return non-filtered calls. | [
"Remove",
"tumor",
"-",
"only",
"prioritization",
"and",
"return",
"non",
"-",
"filtered",
"calls",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/germline.py#L146-L163 |
224,163 | bcbio/bcbio-nextgen | bcbio/variation/germline.py | _extract_germline | def _extract_germline(in_file, data):
"""Extract germline calls non-somatic, non-filtered calls.
"""
out_file = "%s-germline.vcf" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file) and not utils.file_uptodate(out_file + ".gz", in_file):
with file_transaction(data, out_file) as tx_out_file:
reader = cyvcf2.VCF(str(in_file))
reader.add_filter_to_header({'ID': 'Somatic', 'Description': 'Variant called as Somatic'})
#with contextlib.closing(cyvcf2.Writer(tx_out_file, reader)) as writer:
with open(tx_out_file, "w") as out_handle:
out_handle.write(reader.raw_header)
for rec in reader:
rec = _update_germline_filters(rec)
out_handle.write(str(rec))
#writer.write_record(rec)
return out_file | python | def _extract_germline(in_file, data):
"""Extract germline calls non-somatic, non-filtered calls.
"""
out_file = "%s-germline.vcf" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file) and not utils.file_uptodate(out_file + ".gz", in_file):
with file_transaction(data, out_file) as tx_out_file:
reader = cyvcf2.VCF(str(in_file))
reader.add_filter_to_header({'ID': 'Somatic', 'Description': 'Variant called as Somatic'})
#with contextlib.closing(cyvcf2.Writer(tx_out_file, reader)) as writer:
with open(tx_out_file, "w") as out_handle:
out_handle.write(reader.raw_header)
for rec in reader:
rec = _update_germline_filters(rec)
out_handle.write(str(rec))
#writer.write_record(rec)
return out_file | [
"def",
"_extract_germline",
"(",
"in_file",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-germline.vcf\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"in_file",
... | Extract germline calls non-somatic, non-filtered calls. | [
"Extract",
"germline",
"calls",
"non",
"-",
"somatic",
"non",
"-",
"filtered",
"calls",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/germline.py#L169-L184 |
224,164 | bcbio/bcbio-nextgen | bcbio/variation/germline.py | _is_somatic | def _is_somatic(rec):
"""Handle somatic classifications from MuTect, MuTect2, VarDict and VarScan
"""
if _has_somatic_flag(rec):
return True
if _is_mutect2_somatic(rec):
return True
ss_flag = rec.INFO.get("SS")
if ss_flag is not None:
if str(ss_flag) == "2":
return True
status_flag = rec.INFO.get("STATUS")
if status_flag is not None:
if str(status_flag).lower() in ["somatic", "likelysomatic", "strongsomatic", "samplespecific"]:
return True
epr = rec.INFO.get("EPR", "").split(",")
if epr and all([p == "pass" for p in epr]):
return True
return False | python | def _is_somatic(rec):
"""Handle somatic classifications from MuTect, MuTect2, VarDict and VarScan
"""
if _has_somatic_flag(rec):
return True
if _is_mutect2_somatic(rec):
return True
ss_flag = rec.INFO.get("SS")
if ss_flag is not None:
if str(ss_flag) == "2":
return True
status_flag = rec.INFO.get("STATUS")
if status_flag is not None:
if str(status_flag).lower() in ["somatic", "likelysomatic", "strongsomatic", "samplespecific"]:
return True
epr = rec.INFO.get("EPR", "").split(",")
if epr and all([p == "pass" for p in epr]):
return True
return False | [
"def",
"_is_somatic",
"(",
"rec",
")",
":",
"if",
"_has_somatic_flag",
"(",
"rec",
")",
":",
"return",
"True",
"if",
"_is_mutect2_somatic",
"(",
"rec",
")",
":",
"return",
"True",
"ss_flag",
"=",
"rec",
".",
"INFO",
".",
"get",
"(",
"\"SS\"",
")",
"if"... | Handle somatic classifications from MuTect, MuTect2, VarDict and VarScan | [
"Handle",
"somatic",
"classifications",
"from",
"MuTect",
"MuTect2",
"VarDict",
"and",
"VarScan"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/germline.py#L210-L228 |
224,165 | bcbio/bcbio-nextgen | bcbio/variation/germline.py | _is_germline | def _is_germline(rec):
"""Handle somatic INFO classifications from MuTect, MuTect2, VarDict, VarScan and Octopus.
"""
if _has_somatic_flag(rec):
return False
if _is_mutect2_somatic(rec):
return False
ss_flag = rec.INFO.get("SS")
if ss_flag is not None:
if str(ss_flag) == "1":
return True
# Octopus, assessed for potentially being Germline and not flagged SOMATIC
# https://github.com/luntergroup/octopus/wiki/Calling-models:-Cancer#qual-vs-pp
pp = rec.INFO.get("PP")
if pp and float(pp) / float(rec.QUAL) >= 0.5:
return True
status_flag = rec.INFO.get("STATUS")
if status_flag is not None:
if str(status_flag).lower() in ["germline", "likelyloh", "strongloh", "afdiff", "deletion"]:
return True
return False | python | def _is_germline(rec):
"""Handle somatic INFO classifications from MuTect, MuTect2, VarDict, VarScan and Octopus.
"""
if _has_somatic_flag(rec):
return False
if _is_mutect2_somatic(rec):
return False
ss_flag = rec.INFO.get("SS")
if ss_flag is not None:
if str(ss_flag) == "1":
return True
# Octopus, assessed for potentially being Germline and not flagged SOMATIC
# https://github.com/luntergroup/octopus/wiki/Calling-models:-Cancer#qual-vs-pp
pp = rec.INFO.get("PP")
if pp and float(pp) / float(rec.QUAL) >= 0.5:
return True
status_flag = rec.INFO.get("STATUS")
if status_flag is not None:
if str(status_flag).lower() in ["germline", "likelyloh", "strongloh", "afdiff", "deletion"]:
return True
return False | [
"def",
"_is_germline",
"(",
"rec",
")",
":",
"if",
"_has_somatic_flag",
"(",
"rec",
")",
":",
"return",
"False",
"if",
"_is_mutect2_somatic",
"(",
"rec",
")",
":",
"return",
"False",
"ss_flag",
"=",
"rec",
".",
"INFO",
".",
"get",
"(",
"\"SS\"",
")",
"... | Handle somatic INFO classifications from MuTect, MuTect2, VarDict, VarScan and Octopus. | [
"Handle",
"somatic",
"INFO",
"classifications",
"from",
"MuTect",
"MuTect2",
"VarDict",
"VarScan",
"and",
"Octopus",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/germline.py#L242-L262 |
224,166 | bcbio/bcbio-nextgen | bcbio/variation/bedutils.py | get_sort_cmd | def get_sort_cmd(tmp_dir=None):
"""Retrieve GNU coreutils sort command, using version-sort if available.
Recent versions of sort have alpha-numeric sorting, which provides
more natural sorting of chromosomes (chr1, chr2) instead of (chr1, chr10).
This also fixes versions of sort, like 8.22 in CentOS 7.1, that have broken
sorting without version sorting specified.
https://github.com/bcbio/bcbio-nextgen/issues/624
https://github.com/bcbio/bcbio-nextgen/issues/1017
"""
has_versionsort = subprocess.check_output("sort --help | grep version-sort; exit 0", shell=True).strip()
if has_versionsort:
cmd = "sort -V"
else:
cmd = "sort"
if tmp_dir and os.path.exists(tmp_dir) and os.path.isdir(tmp_dir):
cmd += " -T %s" % tmp_dir
return cmd | python | def get_sort_cmd(tmp_dir=None):
"""Retrieve GNU coreutils sort command, using version-sort if available.
Recent versions of sort have alpha-numeric sorting, which provides
more natural sorting of chromosomes (chr1, chr2) instead of (chr1, chr10).
This also fixes versions of sort, like 8.22 in CentOS 7.1, that have broken
sorting without version sorting specified.
https://github.com/bcbio/bcbio-nextgen/issues/624
https://github.com/bcbio/bcbio-nextgen/issues/1017
"""
has_versionsort = subprocess.check_output("sort --help | grep version-sort; exit 0", shell=True).strip()
if has_versionsort:
cmd = "sort -V"
else:
cmd = "sort"
if tmp_dir and os.path.exists(tmp_dir) and os.path.isdir(tmp_dir):
cmd += " -T %s" % tmp_dir
return cmd | [
"def",
"get_sort_cmd",
"(",
"tmp_dir",
"=",
"None",
")",
":",
"has_versionsort",
"=",
"subprocess",
".",
"check_output",
"(",
"\"sort --help | grep version-sort; exit 0\"",
",",
"shell",
"=",
"True",
")",
".",
"strip",
"(",
")",
"if",
"has_versionsort",
":",
"cm... | Retrieve GNU coreutils sort command, using version-sort if available.
Recent versions of sort have alpha-numeric sorting, which provides
more natural sorting of chromosomes (chr1, chr2) instead of (chr1, chr10).
This also fixes versions of sort, like 8.22 in CentOS 7.1, that have broken
sorting without version sorting specified.
https://github.com/bcbio/bcbio-nextgen/issues/624
https://github.com/bcbio/bcbio-nextgen/issues/1017 | [
"Retrieve",
"GNU",
"coreutils",
"sort",
"command",
"using",
"version",
"-",
"sort",
"if",
"available",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bedutils.py#L18-L36 |
224,167 | bcbio/bcbio-nextgen | bcbio/variation/bedutils.py | check_bed_contigs | def check_bed_contigs(in_file, data):
"""Ensure BED file contigs match the reference genome.
"""
if not dd.get_ref_file(data):
return
contigs = set([])
with utils.open_gzipsafe(in_file) as in_handle:
for line in in_handle:
if not line.startswith(("#", "track", "browser", "@")) and line.strip():
contigs.add(line.split()[0])
ref_contigs = set([x.name for x in ref.file_contigs(dd.get_ref_file(data))])
if contigs and len(contigs - ref_contigs) / float(len(contigs)) > 0.25:
raise ValueError("Contigs in BED file %s not in reference genome:\n %s\n"
% (in_file, list(contigs - ref_contigs)) +
"This is typically due to chr1 versus 1 differences in BED file and reference.") | python | def check_bed_contigs(in_file, data):
"""Ensure BED file contigs match the reference genome.
"""
if not dd.get_ref_file(data):
return
contigs = set([])
with utils.open_gzipsafe(in_file) as in_handle:
for line in in_handle:
if not line.startswith(("#", "track", "browser", "@")) and line.strip():
contigs.add(line.split()[0])
ref_contigs = set([x.name for x in ref.file_contigs(dd.get_ref_file(data))])
if contigs and len(contigs - ref_contigs) / float(len(contigs)) > 0.25:
raise ValueError("Contigs in BED file %s not in reference genome:\n %s\n"
% (in_file, list(contigs - ref_contigs)) +
"This is typically due to chr1 versus 1 differences in BED file and reference.") | [
"def",
"check_bed_contigs",
"(",
"in_file",
",",
"data",
")",
":",
"if",
"not",
"dd",
".",
"get_ref_file",
"(",
"data",
")",
":",
"return",
"contigs",
"=",
"set",
"(",
"[",
"]",
")",
"with",
"utils",
".",
"open_gzipsafe",
"(",
"in_file",
")",
"as",
"... | Ensure BED file contigs match the reference genome. | [
"Ensure",
"BED",
"file",
"contigs",
"match",
"the",
"reference",
"genome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bedutils.py#L38-L52 |
224,168 | bcbio/bcbio-nextgen | bcbio/variation/bedutils.py | check_bed_coords | def check_bed_coords(in_file, data):
"""Ensure BED file coordinates match reference genome.
Catches errors like using a hg38 BED file for an hg19 genome run.
"""
if dd.get_ref_file(data):
contig_sizes = {}
for contig in ref.file_contigs(dd.get_ref_file(data)):
contig_sizes[contig.name] = contig.size
with utils.open_gzipsafe(in_file) as in_handle:
for line in in_handle:
if not line.startswith(("#", "track", "browser", "@")) and line.strip():
parts = line.split()
if len(parts) > 3:
try:
end = int(parts[2])
except ValueError:
continue
contig = parts[0]
check_size = contig_sizes.get(contig)
if check_size and end > check_size:
raise ValueError("Found BED coordinate off the end of the chromosome:\n%s%s\n"
"Is the input BED from the right genome build?" %
(line, in_file)) | python | def check_bed_coords(in_file, data):
"""Ensure BED file coordinates match reference genome.
Catches errors like using a hg38 BED file for an hg19 genome run.
"""
if dd.get_ref_file(data):
contig_sizes = {}
for contig in ref.file_contigs(dd.get_ref_file(data)):
contig_sizes[contig.name] = contig.size
with utils.open_gzipsafe(in_file) as in_handle:
for line in in_handle:
if not line.startswith(("#", "track", "browser", "@")) and line.strip():
parts = line.split()
if len(parts) > 3:
try:
end = int(parts[2])
except ValueError:
continue
contig = parts[0]
check_size = contig_sizes.get(contig)
if check_size and end > check_size:
raise ValueError("Found BED coordinate off the end of the chromosome:\n%s%s\n"
"Is the input BED from the right genome build?" %
(line, in_file)) | [
"def",
"check_bed_coords",
"(",
"in_file",
",",
"data",
")",
":",
"if",
"dd",
".",
"get_ref_file",
"(",
"data",
")",
":",
"contig_sizes",
"=",
"{",
"}",
"for",
"contig",
"in",
"ref",
".",
"file_contigs",
"(",
"dd",
".",
"get_ref_file",
"(",
"data",
")"... | Ensure BED file coordinates match reference genome.
Catches errors like using a hg38 BED file for an hg19 genome run. | [
"Ensure",
"BED",
"file",
"coordinates",
"match",
"reference",
"genome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bedutils.py#L54-L77 |
224,169 | bcbio/bcbio-nextgen | bcbio/variation/bedutils.py | clean_file | def clean_file(in_file, data, prefix="", bedprep_dir=None, simple=None):
"""Prepare a clean sorted input BED file without headers
"""
# Remove non-ascii characters. Used in coverage analysis, to support JSON code in one column
# and be happy with sambamba:
simple = "iconv -c -f utf-8 -t ascii | sed 's/ //g' |" if simple else ""
if in_file:
if not bedprep_dir:
bedprep_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "bedprep"))
# Avoid running multiple times with same prefix
if prefix and os.path.basename(in_file).startswith(prefix):
return in_file
out_file = os.path.join(bedprep_dir, "%s%s" % (prefix, os.path.basename(in_file)))
out_file = out_file.replace(".interval_list", ".bed")
if out_file.endswith(".gz"):
out_file = out_file[:-3]
if not utils.file_uptodate(out_file, in_file):
check_bed_contigs(in_file, data)
check_bed_coords(in_file, data)
with file_transaction(data, out_file) as tx_out_file:
bcbio_py = sys.executable
cat_cmd = "zcat" if in_file.endswith(".gz") else "cat"
sort_cmd = get_sort_cmd(os.path.dirname(tx_out_file))
cmd = ("{cat_cmd} {in_file} | grep -v ^track | grep -v ^browser | grep -v ^@ | "
"grep -v ^# | {simple} "
"{bcbio_py} -c 'from bcbio.variation import bedutils; bedutils.remove_bad()' | "
"{sort_cmd} -k1,1 -k2,2n > {tx_out_file}")
do.run(cmd.format(**locals()), "Prepare cleaned BED file", data)
vcfutils.bgzip_and_index(out_file, data.get("config", {}), remove_orig=False)
return out_file | python | def clean_file(in_file, data, prefix="", bedprep_dir=None, simple=None):
"""Prepare a clean sorted input BED file without headers
"""
# Remove non-ascii characters. Used in coverage analysis, to support JSON code in one column
# and be happy with sambamba:
simple = "iconv -c -f utf-8 -t ascii | sed 's/ //g' |" if simple else ""
if in_file:
if not bedprep_dir:
bedprep_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "bedprep"))
# Avoid running multiple times with same prefix
if prefix and os.path.basename(in_file).startswith(prefix):
return in_file
out_file = os.path.join(bedprep_dir, "%s%s" % (prefix, os.path.basename(in_file)))
out_file = out_file.replace(".interval_list", ".bed")
if out_file.endswith(".gz"):
out_file = out_file[:-3]
if not utils.file_uptodate(out_file, in_file):
check_bed_contigs(in_file, data)
check_bed_coords(in_file, data)
with file_transaction(data, out_file) as tx_out_file:
bcbio_py = sys.executable
cat_cmd = "zcat" if in_file.endswith(".gz") else "cat"
sort_cmd = get_sort_cmd(os.path.dirname(tx_out_file))
cmd = ("{cat_cmd} {in_file} | grep -v ^track | grep -v ^browser | grep -v ^@ | "
"grep -v ^# | {simple} "
"{bcbio_py} -c 'from bcbio.variation import bedutils; bedutils.remove_bad()' | "
"{sort_cmd} -k1,1 -k2,2n > {tx_out_file}")
do.run(cmd.format(**locals()), "Prepare cleaned BED file", data)
vcfutils.bgzip_and_index(out_file, data.get("config", {}), remove_orig=False)
return out_file | [
"def",
"clean_file",
"(",
"in_file",
",",
"data",
",",
"prefix",
"=",
"\"\"",
",",
"bedprep_dir",
"=",
"None",
",",
"simple",
"=",
"None",
")",
":",
"# Remove non-ascii characters. Used in coverage analysis, to support JSON code in one column",
"# and be happy with sambam... | Prepare a clean sorted input BED file without headers | [
"Prepare",
"a",
"clean",
"sorted",
"input",
"BED",
"file",
"without",
"headers"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bedutils.py#L79-L108 |
224,170 | bcbio/bcbio-nextgen | bcbio/variation/bedutils.py | remove_bad | def remove_bad():
"""Remove non-increasing BED lines which will cause variant callers to choke.
Also fixes space separated BED inputs.
"""
for line in sys.stdin:
parts = line.strip().split("\t")
if len(parts) == 1 and len(line.strip().split()) > 1:
parts = line.strip().split()
if line.strip() and len(parts) > 2 and int(parts[2]) > int(parts[1]):
sys.stdout.write("\t".join(parts) + "\n") | python | def remove_bad():
"""Remove non-increasing BED lines which will cause variant callers to choke.
Also fixes space separated BED inputs.
"""
for line in sys.stdin:
parts = line.strip().split("\t")
if len(parts) == 1 and len(line.strip().split()) > 1:
parts = line.strip().split()
if line.strip() and len(parts) > 2 and int(parts[2]) > int(parts[1]):
sys.stdout.write("\t".join(parts) + "\n") | [
"def",
"remove_bad",
"(",
")",
":",
"for",
"line",
"in",
"sys",
".",
"stdin",
":",
"parts",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\t\"",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
"and",
"len",
"(",
"line",
".",
"stri... | Remove non-increasing BED lines which will cause variant callers to choke.
Also fixes space separated BED inputs. | [
"Remove",
"non",
"-",
"increasing",
"BED",
"lines",
"which",
"will",
"cause",
"variant",
"callers",
"to",
"choke",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bedutils.py#L134-L144 |
224,171 | bcbio/bcbio-nextgen | bcbio/variation/bedutils.py | merge_overlaps | def merge_overlaps(in_file, data, distance=None, out_dir=None):
"""Merge bed file intervals to avoid overlapping regions. Output is always a 3 column file.
Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes
that don't collapse BEDs prior to using them.
"""
config = data["config"]
if in_file:
bedtools = config_utils.get_program("bedtools", config,
default="bedtools")
work_dir = tz.get_in(["dirs", "work"], data)
if out_dir:
bedprep_dir = out_dir
elif work_dir:
bedprep_dir = utils.safe_makedir(os.path.join(work_dir, "bedprep"))
else:
bedprep_dir = os.path.dirname(in_file)
out_file = os.path.join(bedprep_dir, "%s-merged.bed" % (utils.splitext_plus(os.path.basename(in_file))[0]))
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
distance = "-d %s" % distance if distance else ""
cmd = "{bedtools} merge {distance} -i {in_file} > {tx_out_file}"
do.run(cmd.format(**locals()), "Prepare merged BED file", data)
vcfutils.bgzip_and_index(out_file, data["config"], remove_orig=False)
return out_file | python | def merge_overlaps(in_file, data, distance=None, out_dir=None):
"""Merge bed file intervals to avoid overlapping regions. Output is always a 3 column file.
Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes
that don't collapse BEDs prior to using them.
"""
config = data["config"]
if in_file:
bedtools = config_utils.get_program("bedtools", config,
default="bedtools")
work_dir = tz.get_in(["dirs", "work"], data)
if out_dir:
bedprep_dir = out_dir
elif work_dir:
bedprep_dir = utils.safe_makedir(os.path.join(work_dir, "bedprep"))
else:
bedprep_dir = os.path.dirname(in_file)
out_file = os.path.join(bedprep_dir, "%s-merged.bed" % (utils.splitext_plus(os.path.basename(in_file))[0]))
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
distance = "-d %s" % distance if distance else ""
cmd = "{bedtools} merge {distance} -i {in_file} > {tx_out_file}"
do.run(cmd.format(**locals()), "Prepare merged BED file", data)
vcfutils.bgzip_and_index(out_file, data["config"], remove_orig=False)
return out_file | [
"def",
"merge_overlaps",
"(",
"in_file",
",",
"data",
",",
"distance",
"=",
"None",
",",
"out_dir",
"=",
"None",
")",
":",
"config",
"=",
"data",
"[",
"\"config\"",
"]",
"if",
"in_file",
":",
"bedtools",
"=",
"config_utils",
".",
"get_program",
"(",
"\"b... | Merge bed file intervals to avoid overlapping regions. Output is always a 3 column file.
Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes
that don't collapse BEDs prior to using them. | [
"Merge",
"bed",
"file",
"intervals",
"to",
"avoid",
"overlapping",
"regions",
".",
"Output",
"is",
"always",
"a",
"3",
"column",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bedutils.py#L146-L170 |
224,172 | bcbio/bcbio-nextgen | bcbio/variation/bedutils.py | population_variant_regions | def population_variant_regions(items, merged=False):
"""Retrieve the variant region BED file from a population of items.
If tumor/normal, return the tumor BED file. If a population, return
the BED file covering the most bases.
"""
def _get_variant_regions(data):
out = dd.get_variant_regions(data) or dd.get_sample_callable(data)
# Only need to merge for variant region inputs, not callable BED regions which don't overlap
if merged and dd.get_variant_regions(data):
merged_out = dd.get_variant_regions_merged(data)
if merged_out:
out = merged_out
else:
out = merge_overlaps(out, data)
return out
import pybedtools
if len(items) == 1:
return _get_variant_regions(items[0])
else:
paired = vcfutils.get_paired(items)
if paired:
return _get_variant_regions(paired.tumor_data)
else:
vrs = []
for data in items:
vr_bed = _get_variant_regions(data)
if vr_bed:
vrs.append((pybedtools.BedTool(vr_bed).total_coverage(), vr_bed))
vrs.sort(reverse=True)
if vrs:
return vrs[0][1] | python | def population_variant_regions(items, merged=False):
"""Retrieve the variant region BED file from a population of items.
If tumor/normal, return the tumor BED file. If a population, return
the BED file covering the most bases.
"""
def _get_variant_regions(data):
out = dd.get_variant_regions(data) or dd.get_sample_callable(data)
# Only need to merge for variant region inputs, not callable BED regions which don't overlap
if merged and dd.get_variant_regions(data):
merged_out = dd.get_variant_regions_merged(data)
if merged_out:
out = merged_out
else:
out = merge_overlaps(out, data)
return out
import pybedtools
if len(items) == 1:
return _get_variant_regions(items[0])
else:
paired = vcfutils.get_paired(items)
if paired:
return _get_variant_regions(paired.tumor_data)
else:
vrs = []
for data in items:
vr_bed = _get_variant_regions(data)
if vr_bed:
vrs.append((pybedtools.BedTool(vr_bed).total_coverage(), vr_bed))
vrs.sort(reverse=True)
if vrs:
return vrs[0][1] | [
"def",
"population_variant_regions",
"(",
"items",
",",
"merged",
"=",
"False",
")",
":",
"def",
"_get_variant_regions",
"(",
"data",
")",
":",
"out",
"=",
"dd",
".",
"get_variant_regions",
"(",
"data",
")",
"or",
"dd",
".",
"get_sample_callable",
"(",
"data... | Retrieve the variant region BED file from a population of items.
If tumor/normal, return the tumor BED file. If a population, return
the BED file covering the most bases. | [
"Retrieve",
"the",
"variant",
"region",
"BED",
"file",
"from",
"a",
"population",
"of",
"items",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bedutils.py#L172-L203 |
224,173 | bcbio/bcbio-nextgen | bcbio/variation/bedutils.py | combine | def combine(in_files, out_file, config):
"""Combine multiple BED files into a single output.
"""
if not utils.file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for in_file in in_files:
with open(in_file) as in_handle:
shutil.copyfileobj(in_handle, out_handle)
return out_file | python | def combine(in_files, out_file, config):
"""Combine multiple BED files into a single output.
"""
if not utils.file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for in_file in in_files:
with open(in_file) as in_handle:
shutil.copyfileobj(in_handle, out_handle)
return out_file | [
"def",
"combine",
"(",
"in_files",
",",
"out_file",
",",
"config",
")",
":",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
"config",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"with",
"open",
"... | Combine multiple BED files into a single output. | [
"Combine",
"multiple",
"BED",
"files",
"into",
"a",
"single",
"output",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bedutils.py#L205-L214 |
224,174 | bcbio/bcbio-nextgen | bcbio/variation/bedutils.py | intersect_two | def intersect_two(f1, f2, work_dir, data):
"""Intersect two regions, handling cases where either file is not present.
"""
bedtools = config_utils.get_program("bedtools", data, default="bedtools")
f1_exists = f1 and utils.file_exists(f1)
f2_exists = f2 and utils.file_exists(f2)
if not f1_exists and not f2_exists:
return None
elif f1_exists and not f2_exists:
return f1
elif f2_exists and not f1_exists:
return f2
else:
out_file = os.path.join(work_dir, "%s-merged.bed" % (utils.splitext_plus(os.path.basename(f1))[0]))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = "{bedtools} intersect -a {f1} -b {f2} > {tx_out_file}"
do.run(cmd.format(**locals()), "Intersect BED files", data)
return out_file | python | def intersect_two(f1, f2, work_dir, data):
"""Intersect two regions, handling cases where either file is not present.
"""
bedtools = config_utils.get_program("bedtools", data, default="bedtools")
f1_exists = f1 and utils.file_exists(f1)
f2_exists = f2 and utils.file_exists(f2)
if not f1_exists and not f2_exists:
return None
elif f1_exists and not f2_exists:
return f1
elif f2_exists and not f1_exists:
return f2
else:
out_file = os.path.join(work_dir, "%s-merged.bed" % (utils.splitext_plus(os.path.basename(f1))[0]))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = "{bedtools} intersect -a {f1} -b {f2} > {tx_out_file}"
do.run(cmd.format(**locals()), "Intersect BED files", data)
return out_file | [
"def",
"intersect_two",
"(",
"f1",
",",
"f2",
",",
"work_dir",
",",
"data",
")",
":",
"bedtools",
"=",
"config_utils",
".",
"get_program",
"(",
"\"bedtools\"",
",",
"data",
",",
"default",
"=",
"\"bedtools\"",
")",
"f1_exists",
"=",
"f1",
"and",
"utils",
... | Intersect two regions, handling cases where either file is not present. | [
"Intersect",
"two",
"regions",
"handling",
"cases",
"where",
"either",
"file",
"is",
"not",
"present",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bedutils.py#L216-L234 |
224,175 | bcbio/bcbio-nextgen | bcbio/variation/bedutils.py | subset_to_genome | def subset_to_genome(in_file, out_file, data):
"""Subset a BED file to only contain contigs present in the reference genome.
"""
if not utils.file_uptodate(out_file, in_file):
contigs = set([x.name for x in ref.file_contigs(dd.get_ref_file(data))])
with utils.open_gzipsafe(in_file) 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 in_handle:
parts = line.split()
if parts and parts[0] in contigs:
out_handle.write(line)
return out_file | python | def subset_to_genome(in_file, out_file, data):
"""Subset a BED file to only contain contigs present in the reference genome.
"""
if not utils.file_uptodate(out_file, in_file):
contigs = set([x.name for x in ref.file_contigs(dd.get_ref_file(data))])
with utils.open_gzipsafe(in_file) 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 in_handle:
parts = line.split()
if parts and parts[0] in contigs:
out_handle.write(line)
return out_file | [
"def",
"subset_to_genome",
"(",
"in_file",
",",
"out_file",
",",
"data",
")",
":",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"in_file",
")",
":",
"contigs",
"=",
"set",
"(",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"ref",
".",... | Subset a BED file to only contain contigs present in the reference genome. | [
"Subset",
"a",
"BED",
"file",
"to",
"only",
"contain",
"contigs",
"present",
"in",
"the",
"reference",
"genome",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/bedutils.py#L247-L259 |
224,176 | bcbio/bcbio-nextgen | bcbio/variation/octopus.py | run | def run(align_bams, items, ref_file, assoc_files, region, out_file):
"""Run octopus variant calling, handling both somatic and germline calling.
"""
if not utils.file_exists(out_file):
paired = vcfutils.get_paired_bams(align_bams, items)
vrs = bedutils.population_variant_regions(items)
target = shared.subset_variant_regions(vrs, region,
out_file, items=items, do_merge=True)
if paired:
return _run_somatic(paired, ref_file, target, out_file)
else:
return _run_germline(align_bams, items, ref_file, target, out_file)
return out_file | python | def run(align_bams, items, ref_file, assoc_files, region, out_file):
"""Run octopus variant calling, handling both somatic and germline calling.
"""
if not utils.file_exists(out_file):
paired = vcfutils.get_paired_bams(align_bams, items)
vrs = bedutils.population_variant_regions(items)
target = shared.subset_variant_regions(vrs, region,
out_file, items=items, do_merge=True)
if paired:
return _run_somatic(paired, ref_file, target, out_file)
else:
return _run_germline(align_bams, items, ref_file, target, out_file)
return out_file | [
"def",
"run",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
",",
"out_file",
")",
":",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired_bams",
"(",
"al... | Run octopus variant calling, handling both somatic and germline calling. | [
"Run",
"octopus",
"variant",
"calling",
"handling",
"both",
"somatic",
"and",
"germline",
"calling",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/octopus.py#L17-L29 |
224,177 | bcbio/bcbio-nextgen | bcbio/variation/octopus.py | _produce_compatible_vcf | def _produce_compatible_vcf(out_file, data, is_somatic):
"""Create a compatible VCF that downstream tools can deal with.
- htsjdk and thus GATK and Picard do not support VCF4.3:
https://github.com/broadinstitute/gatk/issues/2092
- Use octopus legacy format to avoid incompatibilities.
https://github.com/luntergroup/octopus#output-format
- Fixes `##contig` lines since octopus only writes contigs
used in the BED file region, causing incompatibilies with
GatherVcfs when merging
- Fixes alleles prefixed with '*' like 'C,*T' which cause
downstream failures when reading with GATK.
"""
base, ext = utils.splitext_plus(out_file)
legacy_file = "%s.legacy%s" % (base, ext)
if is_somatic:
legacy_file = _covert_to_diploid(legacy_file, data)
final_file = "%s.vcf.gz" % base
cat_cmd = "zcat" if legacy_file.endswith(".gz") else "cat"
contig_cl = vcfutils.add_contig_to_header_cl(dd.get_ref_file(data), out_file)
remove_problem_alleles = r"sed 's/,\*\([A-Z]\)/,\1/'"
cmd = ("{cat_cmd} {legacy_file} | sed 's/fileformat=VCFv4.3/fileformat=VCFv4.2/' | "
"{remove_problem_alleles} | {contig_cl} | bgzip -c > {final_file}")
do.run(cmd.format(**locals()), "Produce compatible VCF output file from octopus")
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def _produce_compatible_vcf(out_file, data, is_somatic):
"""Create a compatible VCF that downstream tools can deal with.
- htsjdk and thus GATK and Picard do not support VCF4.3:
https://github.com/broadinstitute/gatk/issues/2092
- Use octopus legacy format to avoid incompatibilities.
https://github.com/luntergroup/octopus#output-format
- Fixes `##contig` lines since octopus only writes contigs
used in the BED file region, causing incompatibilies with
GatherVcfs when merging
- Fixes alleles prefixed with '*' like 'C,*T' which cause
downstream failures when reading with GATK.
"""
base, ext = utils.splitext_plus(out_file)
legacy_file = "%s.legacy%s" % (base, ext)
if is_somatic:
legacy_file = _covert_to_diploid(legacy_file, data)
final_file = "%s.vcf.gz" % base
cat_cmd = "zcat" if legacy_file.endswith(".gz") else "cat"
contig_cl = vcfutils.add_contig_to_header_cl(dd.get_ref_file(data), out_file)
remove_problem_alleles = r"sed 's/,\*\([A-Z]\)/,\1/'"
cmd = ("{cat_cmd} {legacy_file} | sed 's/fileformat=VCFv4.3/fileformat=VCFv4.2/' | "
"{remove_problem_alleles} | {contig_cl} | bgzip -c > {final_file}")
do.run(cmd.format(**locals()), "Produce compatible VCF output file from octopus")
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"_produce_compatible_vcf",
"(",
"out_file",
",",
"data",
",",
"is_somatic",
")",
":",
"base",
",",
"ext",
"=",
"utils",
".",
"splitext_plus",
"(",
"out_file",
")",
"legacy_file",
"=",
"\"%s.legacy%s\"",
"%",
"(",
"base",
",",
"ext",
")",
"if",
"is_s... | Create a compatible VCF that downstream tools can deal with.
- htsjdk and thus GATK and Picard do not support VCF4.3:
https://github.com/broadinstitute/gatk/issues/2092
- Use octopus legacy format to avoid incompatibilities.
https://github.com/luntergroup/octopus#output-format
- Fixes `##contig` lines since octopus only writes contigs
used in the BED file region, causing incompatibilies with
GatherVcfs when merging
- Fixes alleles prefixed with '*' like 'C,*T' which cause
downstream failures when reading with GATK. | [
"Create",
"a",
"compatible",
"VCF",
"that",
"downstream",
"tools",
"can",
"deal",
"with",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/octopus.py#L31-L55 |
224,178 | bcbio/bcbio-nextgen | bcbio/variation/octopus.py | _covert_to_diploid | def _covert_to_diploid(in_file, data):
"""Converts non-diploid somatic outputs into diploid.
https://github.com/luntergroup/octopus/wiki/Case-study:-Tumour-only-UMI#evaluate-variant-calls
"""
sample = dd.get_sample_name(data)
out_file = "%s-diploid.vcf" % utils.splitext_plus(in_file)[0]
in_vcf = pysam.VariantFile(in_file)
out_vcf = pysam.VariantFile(out_file, 'w', header=in_vcf.header)
for record in in_vcf:
gt = list(record.samples[sample]['GT'])
if 'SOMATIC' in record.info:
for allele in set(gt):
if allele != gt[0]:
record.samples[sample]['GT'] = gt[0], allele
out_vcf.write(record)
else:
if len(gt) == 1:
record.samples[sample]['GT'] = gt
else:
record.samples[sample]['GT'] = gt[0], gt[1]
out_vcf.write(record)
in_vcf.close()
out_vcf.close()
return vcfutils.bgzip_and_index(out_file, data["config"]) | python | def _covert_to_diploid(in_file, data):
"""Converts non-diploid somatic outputs into diploid.
https://github.com/luntergroup/octopus/wiki/Case-study:-Tumour-only-UMI#evaluate-variant-calls
"""
sample = dd.get_sample_name(data)
out_file = "%s-diploid.vcf" % utils.splitext_plus(in_file)[0]
in_vcf = pysam.VariantFile(in_file)
out_vcf = pysam.VariantFile(out_file, 'w', header=in_vcf.header)
for record in in_vcf:
gt = list(record.samples[sample]['GT'])
if 'SOMATIC' in record.info:
for allele in set(gt):
if allele != gt[0]:
record.samples[sample]['GT'] = gt[0], allele
out_vcf.write(record)
else:
if len(gt) == 1:
record.samples[sample]['GT'] = gt
else:
record.samples[sample]['GT'] = gt[0], gt[1]
out_vcf.write(record)
in_vcf.close()
out_vcf.close()
return vcfutils.bgzip_and_index(out_file, data["config"]) | [
"def",
"_covert_to_diploid",
"(",
"in_file",
",",
"data",
")",
":",
"sample",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"out_file",
"=",
"\"%s-diploid.vcf\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"[",
"0",
"]",
"in_vcf",
"=",... | Converts non-diploid somatic outputs into diploid.
https://github.com/luntergroup/octopus/wiki/Case-study:-Tumour-only-UMI#evaluate-variant-calls | [
"Converts",
"non",
"-",
"diploid",
"somatic",
"outputs",
"into",
"diploid",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/octopus.py#L57-L81 |
224,179 | bcbio/bcbio-nextgen | bcbio/variation/octopus.py | _run_germline | def _run_germline(align_bams, items, ref_file, target, out_file):
"""Run germline calling, handling populations.
TODO:
- We could better handle trio calling with ped inputs as octopus
has special support.
"""
align_bams = " ".join(align_bams)
cores = dd.get_num_cores(items[0])
cmd = ("octopus --threads {cores} --reference {ref_file} --reads {align_bams} "
"--regions-file {target} "
"--working-directory {tmp_dir} "
"-o {tx_out_file} --legacy")
with file_transaction(items[0], out_file) as tx_out_file:
tmp_dir = os.path.dirname(tx_out_file)
do.run(cmd.format(**locals()), "Octopus germline calling")
_produce_compatible_vcf(tx_out_file, items[0])
return out_file | python | def _run_germline(align_bams, items, ref_file, target, out_file):
"""Run germline calling, handling populations.
TODO:
- We could better handle trio calling with ped inputs as octopus
has special support.
"""
align_bams = " ".join(align_bams)
cores = dd.get_num_cores(items[0])
cmd = ("octopus --threads {cores} --reference {ref_file} --reads {align_bams} "
"--regions-file {target} "
"--working-directory {tmp_dir} "
"-o {tx_out_file} --legacy")
with file_transaction(items[0], out_file) as tx_out_file:
tmp_dir = os.path.dirname(tx_out_file)
do.run(cmd.format(**locals()), "Octopus germline calling")
_produce_compatible_vcf(tx_out_file, items[0])
return out_file | [
"def",
"_run_germline",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"target",
",",
"out_file",
")",
":",
"align_bams",
"=",
"\" \"",
".",
"join",
"(",
"align_bams",
")",
"cores",
"=",
"dd",
".",
"get_num_cores",
"(",
"items",
"[",
"0",
"]",
... | Run germline calling, handling populations.
TODO:
- We could better handle trio calling with ped inputs as octopus
has special support. | [
"Run",
"germline",
"calling",
"handling",
"populations",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/octopus.py#L83-L100 |
224,180 | bcbio/bcbio-nextgen | bcbio/variation/octopus.py | _run_somatic | def _run_somatic(paired, ref_file, target, out_file):
"""Run somatic calling with octopus, handling both paired and tumor-only cases.
Tweaks for low frequency, tumor only and UMI calling documented in:
https://github.com/luntergroup/octopus/blob/develop/configs/UMI.config
"""
align_bams = paired.tumor_bam
if paired.normal_bam:
align_bams += " %s --normal-sample %s" % (paired.normal_bam, paired.normal_name)
cores = dd.get_num_cores(paired.tumor_data)
# Do not try to search below 0.4% currently as leads to long runtimes
# https://github.com/luntergroup/octopus/issues/29#issuecomment-428167979
min_af = max([float(dd.get_min_allele_fraction(paired.tumor_data)) / 100.0, 0.004])
min_af_floor = min_af / 4.0
cmd = ("octopus --threads {cores} --reference {ref_file} --reads {align_bams} "
"--regions-file {target} "
"--min-credible-somatic-frequency {min_af_floor} --min-expected-somatic-frequency {min_af} "
"--downsample-above 4000 --downsample-target 4000 --min-kmer-prune 5 --min-bubble-score 20 "
"--max-haplotypes 200 --somatic-snv-mutation-rate '5e-4' --somatic-indel-mutation-rate '1e-05' "
"--target-working-memory 5G --target-read-buffer-footprint 5G --max-somatic-haplotypes 3 "
"--caller cancer "
"--working-directory {tmp_dir} "
"-o {tx_out_file} --legacy")
if not paired.normal_bam:
cmd += (" --tumour-germline-concentration 5")
if dd.get_umi_type(paired.tumor_data) or _is_umi_consensus_bam(paired.tumor_bam):
cmd += (" --allow-octopus-duplicates --overlap-masking 0 "
"--somatic-filter-expression 'GQ < 200 | MQ < 30 | SB > 0.2 | SD[.25] > 0.1 "
"| BQ < 40 | DP < 100 | MF > 0.1 | AD < 5 | CC > 1.1 | GQD > 2'")
with file_transaction(paired.tumor_data, out_file) as tx_out_file:
tmp_dir = os.path.dirname(tx_out_file)
do.run(cmd.format(**locals()), "Octopus somatic calling")
_produce_compatible_vcf(tx_out_file, paired.tumor_data, is_somatic=True)
return out_file | python | def _run_somatic(paired, ref_file, target, out_file):
"""Run somatic calling with octopus, handling both paired and tumor-only cases.
Tweaks for low frequency, tumor only and UMI calling documented in:
https://github.com/luntergroup/octopus/blob/develop/configs/UMI.config
"""
align_bams = paired.tumor_bam
if paired.normal_bam:
align_bams += " %s --normal-sample %s" % (paired.normal_bam, paired.normal_name)
cores = dd.get_num_cores(paired.tumor_data)
# Do not try to search below 0.4% currently as leads to long runtimes
# https://github.com/luntergroup/octopus/issues/29#issuecomment-428167979
min_af = max([float(dd.get_min_allele_fraction(paired.tumor_data)) / 100.0, 0.004])
min_af_floor = min_af / 4.0
cmd = ("octopus --threads {cores} --reference {ref_file} --reads {align_bams} "
"--regions-file {target} "
"--min-credible-somatic-frequency {min_af_floor} --min-expected-somatic-frequency {min_af} "
"--downsample-above 4000 --downsample-target 4000 --min-kmer-prune 5 --min-bubble-score 20 "
"--max-haplotypes 200 --somatic-snv-mutation-rate '5e-4' --somatic-indel-mutation-rate '1e-05' "
"--target-working-memory 5G --target-read-buffer-footprint 5G --max-somatic-haplotypes 3 "
"--caller cancer "
"--working-directory {tmp_dir} "
"-o {tx_out_file} --legacy")
if not paired.normal_bam:
cmd += (" --tumour-germline-concentration 5")
if dd.get_umi_type(paired.tumor_data) or _is_umi_consensus_bam(paired.tumor_bam):
cmd += (" --allow-octopus-duplicates --overlap-masking 0 "
"--somatic-filter-expression 'GQ < 200 | MQ < 30 | SB > 0.2 | SD[.25] > 0.1 "
"| BQ < 40 | DP < 100 | MF > 0.1 | AD < 5 | CC > 1.1 | GQD > 2'")
with file_transaction(paired.tumor_data, out_file) as tx_out_file:
tmp_dir = os.path.dirname(tx_out_file)
do.run(cmd.format(**locals()), "Octopus somatic calling")
_produce_compatible_vcf(tx_out_file, paired.tumor_data, is_somatic=True)
return out_file | [
"def",
"_run_somatic",
"(",
"paired",
",",
"ref_file",
",",
"target",
",",
"out_file",
")",
":",
"align_bams",
"=",
"paired",
".",
"tumor_bam",
"if",
"paired",
".",
"normal_bam",
":",
"align_bams",
"+=",
"\" %s --normal-sample %s\"",
"%",
"(",
"paired",
".",
... | Run somatic calling with octopus, handling both paired and tumor-only cases.
Tweaks for low frequency, tumor only and UMI calling documented in:
https://github.com/luntergroup/octopus/blob/develop/configs/UMI.config | [
"Run",
"somatic",
"calling",
"with",
"octopus",
"handling",
"both",
"paired",
"and",
"tumor",
"-",
"only",
"cases",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/octopus.py#L102-L135 |
224,181 | bcbio/bcbio-nextgen | bcbio/variation/octopus.py | _is_umi_consensus_bam | def _is_umi_consensus_bam(in_file):
"""Check if input BAM file generated by fgbio consensus calls on UMIs.
Identify these by lack of duplicated reads.
This is useful for pre-aligned consensus BAMs feeding into octopus.
"""
cmd = "samtools view -h %s | head -500000 | samtools view -c -f 1024"
count = subprocess.check_output(cmd % in_file, shell=True)
return int(count) == 0 | python | def _is_umi_consensus_bam(in_file):
"""Check if input BAM file generated by fgbio consensus calls on UMIs.
Identify these by lack of duplicated reads.
This is useful for pre-aligned consensus BAMs feeding into octopus.
"""
cmd = "samtools view -h %s | head -500000 | samtools view -c -f 1024"
count = subprocess.check_output(cmd % in_file, shell=True)
return int(count) == 0 | [
"def",
"_is_umi_consensus_bam",
"(",
"in_file",
")",
":",
"cmd",
"=",
"\"samtools view -h %s | head -500000 | samtools view -c -f 1024\"",
"count",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
"%",
"in_file",
",",
"shell",
"=",
"True",
")",
"return",
"int",
"... | Check if input BAM file generated by fgbio consensus calls on UMIs.
Identify these by lack of duplicated reads.
This is useful for pre-aligned consensus BAMs feeding into octopus. | [
"Check",
"if",
"input",
"BAM",
"file",
"generated",
"by",
"fgbio",
"consensus",
"calls",
"on",
"UMIs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/octopus.py#L137-L145 |
224,182 | bcbio/bcbio-nextgen | bcbio/upload/s3.py | update_file | def update_file(finfo, sample_info, config):
"""Update the file to an Amazon S3 bucket, using server side encryption.
"""
ffinal = filesystem.update_file(finfo, sample_info, config, pass_uptodate=True)
if os.path.isdir(ffinal):
to_transfer = []
for path, dirs, files in os.walk(ffinal):
for f in files:
full_f = os.path.join(path, f)
k = full_f.replace(os.path.abspath(config["dir"]) + "/", "")
to_transfer.append((full_f, k))
else:
k = ffinal.replace(os.path.abspath(config["dir"]) + "/", "")
to_transfer = [(ffinal, k)]
region = "@%s" % config["region"] if config.get("region") else ""
fname = "s3://%s%s/%s" % (config["bucket"], region, to_transfer[0][1])
conn = objectstore.connect(fname)
bucket = conn.lookup(config["bucket"])
if not bucket:
bucket = conn.create_bucket(config["bucket"], location=config.get("region", "us-east-1"))
for fname, orig_keyname in to_transfer:
keyname = os.path.join(config.get("folder", ""), orig_keyname)
key = bucket.get_key(keyname) if bucket else None
modified = datetime.datetime.fromtimestamp(email.utils.mktime_tz(
email.utils.parsedate_tz(key.last_modified))) if key else None
no_upload = key and modified >= finfo["mtime"]
if not no_upload:
_upload_file_aws_cli(fname, config["bucket"], keyname, config, finfo) | python | def update_file(finfo, sample_info, config):
"""Update the file to an Amazon S3 bucket, using server side encryption.
"""
ffinal = filesystem.update_file(finfo, sample_info, config, pass_uptodate=True)
if os.path.isdir(ffinal):
to_transfer = []
for path, dirs, files in os.walk(ffinal):
for f in files:
full_f = os.path.join(path, f)
k = full_f.replace(os.path.abspath(config["dir"]) + "/", "")
to_transfer.append((full_f, k))
else:
k = ffinal.replace(os.path.abspath(config["dir"]) + "/", "")
to_transfer = [(ffinal, k)]
region = "@%s" % config["region"] if config.get("region") else ""
fname = "s3://%s%s/%s" % (config["bucket"], region, to_transfer[0][1])
conn = objectstore.connect(fname)
bucket = conn.lookup(config["bucket"])
if not bucket:
bucket = conn.create_bucket(config["bucket"], location=config.get("region", "us-east-1"))
for fname, orig_keyname in to_transfer:
keyname = os.path.join(config.get("folder", ""), orig_keyname)
key = bucket.get_key(keyname) if bucket else None
modified = datetime.datetime.fromtimestamp(email.utils.mktime_tz(
email.utils.parsedate_tz(key.last_modified))) if key else None
no_upload = key and modified >= finfo["mtime"]
if not no_upload:
_upload_file_aws_cli(fname, config["bucket"], keyname, config, finfo) | [
"def",
"update_file",
"(",
"finfo",
",",
"sample_info",
",",
"config",
")",
":",
"ffinal",
"=",
"filesystem",
".",
"update_file",
"(",
"finfo",
",",
"sample_info",
",",
"config",
",",
"pass_uptodate",
"=",
"True",
")",
"if",
"os",
".",
"path",
".",
"isdi... | Update the file to an Amazon S3 bucket, using server side encryption. | [
"Update",
"the",
"file",
"to",
"an",
"Amazon",
"S3",
"bucket",
"using",
"server",
"side",
"encryption",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/s3.py#L20-L49 |
224,183 | bcbio/bcbio-nextgen | bcbio/upload/s3.py | _upload_file_aws_cli | def _upload_file_aws_cli(local_fname, bucket, keyname, config=None, mditems=None):
"""Streaming upload via the standard AWS command line interface.
"""
s3_fname = "s3://%s/%s" % (bucket, keyname)
args = ["--sse", "--expected-size", str(os.path.getsize(local_fname))]
if config:
if config.get("region"):
args += ["--region", config.get("region")]
if config.get("reduced_redundancy"):
args += ["--storage-class", "REDUCED_REDUNDANCY"]
cmd = [os.path.join(os.path.dirname(sys.executable), "aws"), "s3", "cp"] + args + \
[local_fname, s3_fname]
do.run(cmd, "Upload to s3: %s %s" % (bucket, keyname)) | python | def _upload_file_aws_cli(local_fname, bucket, keyname, config=None, mditems=None):
"""Streaming upload via the standard AWS command line interface.
"""
s3_fname = "s3://%s/%s" % (bucket, keyname)
args = ["--sse", "--expected-size", str(os.path.getsize(local_fname))]
if config:
if config.get("region"):
args += ["--region", config.get("region")]
if config.get("reduced_redundancy"):
args += ["--storage-class", "REDUCED_REDUNDANCY"]
cmd = [os.path.join(os.path.dirname(sys.executable), "aws"), "s3", "cp"] + args + \
[local_fname, s3_fname]
do.run(cmd, "Upload to s3: %s %s" % (bucket, keyname)) | [
"def",
"_upload_file_aws_cli",
"(",
"local_fname",
",",
"bucket",
",",
"keyname",
",",
"config",
"=",
"None",
",",
"mditems",
"=",
"None",
")",
":",
"s3_fname",
"=",
"\"s3://%s/%s\"",
"%",
"(",
"bucket",
",",
"keyname",
")",
"args",
"=",
"[",
"\"--sse\"",
... | Streaming upload via the standard AWS command line interface. | [
"Streaming",
"upload",
"via",
"the",
"standard",
"AWS",
"command",
"line",
"interface",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/s3.py#L69-L81 |
224,184 | bcbio/bcbio-nextgen | bcbio/upload/s3.py | upload_file_boto | def upload_file_boto(fname, remote_fname, mditems=None):
"""Upload a file using boto instead of external tools.
"""
r_fname = objectstore.parse_remote(remote_fname)
conn = objectstore.connect(remote_fname)
bucket = conn.lookup(r_fname.bucket)
if not bucket:
bucket = conn.create_bucket(r_fname.bucket, location=objectstore.get_region(remote_fname))
key = bucket.get_key(r_fname.key, validate=False)
if mditems is None:
mditems = {}
if "x-amz-server-side-encryption" not in mditems:
mditems["x-amz-server-side-encryption"] = "AES256"
for name, val in mditems.items():
key.set_metadata(name, val)
key.set_contents_from_filename(fname, encrypt_key=True) | python | def upload_file_boto(fname, remote_fname, mditems=None):
"""Upload a file using boto instead of external tools.
"""
r_fname = objectstore.parse_remote(remote_fname)
conn = objectstore.connect(remote_fname)
bucket = conn.lookup(r_fname.bucket)
if not bucket:
bucket = conn.create_bucket(r_fname.bucket, location=objectstore.get_region(remote_fname))
key = bucket.get_key(r_fname.key, validate=False)
if mditems is None:
mditems = {}
if "x-amz-server-side-encryption" not in mditems:
mditems["x-amz-server-side-encryption"] = "AES256"
for name, val in mditems.items():
key.set_metadata(name, val)
key.set_contents_from_filename(fname, encrypt_key=True) | [
"def",
"upload_file_boto",
"(",
"fname",
",",
"remote_fname",
",",
"mditems",
"=",
"None",
")",
":",
"r_fname",
"=",
"objectstore",
".",
"parse_remote",
"(",
"remote_fname",
")",
"conn",
"=",
"objectstore",
".",
"connect",
"(",
"remote_fname",
")",
"bucket",
... | Upload a file using boto instead of external tools. | [
"Upload",
"a",
"file",
"using",
"boto",
"instead",
"of",
"external",
"tools",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/s3.py#L83-L98 |
224,185 | bcbio/bcbio-nextgen | bcbio/qc/chipseq.py | run | def run(bam_file, sample, out_dir):
"""Standard QC metrics for chipseq"""
out = {}
# if "rchipqc" in dd.get_tools_on(sample):
# out = chipqc(bam_file, sample, out_dir)
peaks = sample.get("peaks_files", {}).get("main")
if peaks:
out.update(_reads_in_peaks(bam_file, peaks, sample))
return out | python | def run(bam_file, sample, out_dir):
"""Standard QC metrics for chipseq"""
out = {}
# if "rchipqc" in dd.get_tools_on(sample):
# out = chipqc(bam_file, sample, out_dir)
peaks = sample.get("peaks_files", {}).get("main")
if peaks:
out.update(_reads_in_peaks(bam_file, peaks, sample))
return out | [
"def",
"run",
"(",
"bam_file",
",",
"sample",
",",
"out_dir",
")",
":",
"out",
"=",
"{",
"}",
"# if \"rchipqc\" in dd.get_tools_on(sample):",
"# out = chipqc(bam_file, sample, out_dir)",
"peaks",
"=",
"sample",
".",
"get",
"(",
"\"peaks_files\"",
",",
"{",
"}",
... | Standard QC metrics for chipseq | [
"Standard",
"QC",
"metrics",
"for",
"chipseq"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/chipseq.py#L16-L25 |
224,186 | bcbio/bcbio-nextgen | bcbio/qc/chipseq.py | _reads_in_peaks | def _reads_in_peaks(bam_file, peaks_file, sample):
"""Calculate number of reads in peaks"""
if not peaks_file:
return {}
rip = number_of_mapped_reads(sample, bam_file, bed_file = peaks_file)
return {"metrics": {"RiP": rip}} | python | def _reads_in_peaks(bam_file, peaks_file, sample):
"""Calculate number of reads in peaks"""
if not peaks_file:
return {}
rip = number_of_mapped_reads(sample, bam_file, bed_file = peaks_file)
return {"metrics": {"RiP": rip}} | [
"def",
"_reads_in_peaks",
"(",
"bam_file",
",",
"peaks_file",
",",
"sample",
")",
":",
"if",
"not",
"peaks_file",
":",
"return",
"{",
"}",
"rip",
"=",
"number_of_mapped_reads",
"(",
"sample",
",",
"bam_file",
",",
"bed_file",
"=",
"peaks_file",
")",
"return"... | Calculate number of reads in peaks | [
"Calculate",
"number",
"of",
"reads",
"in",
"peaks"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/chipseq.py#L27-L32 |
224,187 | bcbio/bcbio-nextgen | bcbio/qc/chipseq.py | chipqc | def chipqc(bam_file, sample, out_dir):
"""Attempt code to run ChIPQC bioconductor packate in one sample"""
sample_name = dd.get_sample_name(sample)
logger.warning("ChIPQC is unstable right now, if it breaks, turn off the tool.")
if utils.file_exists(out_dir):
return _get_output(out_dir)
with tx_tmpdir() as tmp_dir:
rcode = _sample_template(sample, tmp_dir)
if rcode:
# local_sitelib = utils.R_sitelib()
rscript = utils.Rscript_cmd()
do.run([rscript, "--no-environ", rcode], "ChIPQC in %s" % sample_name, log_error=False)
shutil.move(tmp_dir, out_dir)
return _get_output(out_dir) | python | def chipqc(bam_file, sample, out_dir):
"""Attempt code to run ChIPQC bioconductor packate in one sample"""
sample_name = dd.get_sample_name(sample)
logger.warning("ChIPQC is unstable right now, if it breaks, turn off the tool.")
if utils.file_exists(out_dir):
return _get_output(out_dir)
with tx_tmpdir() as tmp_dir:
rcode = _sample_template(sample, tmp_dir)
if rcode:
# local_sitelib = utils.R_sitelib()
rscript = utils.Rscript_cmd()
do.run([rscript, "--no-environ", rcode], "ChIPQC in %s" % sample_name, log_error=False)
shutil.move(tmp_dir, out_dir)
return _get_output(out_dir) | [
"def",
"chipqc",
"(",
"bam_file",
",",
"sample",
",",
"out_dir",
")",
":",
"sample_name",
"=",
"dd",
".",
"get_sample_name",
"(",
"sample",
")",
"logger",
".",
"warning",
"(",
"\"ChIPQC is unstable right now, if it breaks, turn off the tool.\"",
")",
"if",
"utils",
... | Attempt code to run ChIPQC bioconductor packate in one sample | [
"Attempt",
"code",
"to",
"run",
"ChIPQC",
"bioconductor",
"packate",
"in",
"one",
"sample"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/chipseq.py#L34-L47 |
224,188 | bcbio/bcbio-nextgen | bcbio/qc/chipseq.py | _sample_template | def _sample_template(sample, out_dir):
"""R code to get QC for one sample"""
bam_fn = dd.get_work_bam(sample)
genome = dd.get_genome_build(sample)
if genome in supported:
peaks = sample.get("peaks_files", []).get("main")
if peaks:
r_code = ("library(ChIPQC);\n"
"sample = ChIPQCsample(\"{bam_fn}\","
"\"{peaks}\", "
"annotation = \"{genome}\","
");\n"
"ChIPQCreport(sample);\n")
r_code_fn = os.path.join(out_dir, "chipqc.r")
with open(r_code_fn, 'w') as inh:
inh.write(r_code.format(**locals()))
return r_code_fn | python | def _sample_template(sample, out_dir):
"""R code to get QC for one sample"""
bam_fn = dd.get_work_bam(sample)
genome = dd.get_genome_build(sample)
if genome in supported:
peaks = sample.get("peaks_files", []).get("main")
if peaks:
r_code = ("library(ChIPQC);\n"
"sample = ChIPQCsample(\"{bam_fn}\","
"\"{peaks}\", "
"annotation = \"{genome}\","
");\n"
"ChIPQCreport(sample);\n")
r_code_fn = os.path.join(out_dir, "chipqc.r")
with open(r_code_fn, 'w') as inh:
inh.write(r_code.format(**locals()))
return r_code_fn | [
"def",
"_sample_template",
"(",
"sample",
",",
"out_dir",
")",
":",
"bam_fn",
"=",
"dd",
".",
"get_work_bam",
"(",
"sample",
")",
"genome",
"=",
"dd",
".",
"get_genome_build",
"(",
"sample",
")",
"if",
"genome",
"in",
"supported",
":",
"peaks",
"=",
"sam... | R code to get QC for one sample | [
"R",
"code",
"to",
"get",
"QC",
"for",
"one",
"sample"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/chipseq.py#L56-L72 |
224,189 | bcbio/bcbio-nextgen | bcbio/rnaseq/featureCounts.py | _change_sample_name | def _change_sample_name(in_file, sample_name, data=None):
"""Fix name in feature counts log file to get the same
name in multiqc report.
"""
out_file = append_stem(in_file, "_fixed")
with file_transaction(data, out_file) as tx_out:
with open(tx_out, "w") as out_handle:
with open(in_file) as in_handle:
for line in in_handle:
if line.startswith("Status"):
line = "Status\t%s.bam" % sample_name
out_handle.write("%s\n" % line.strip())
return out_file | python | def _change_sample_name(in_file, sample_name, data=None):
"""Fix name in feature counts log file to get the same
name in multiqc report.
"""
out_file = append_stem(in_file, "_fixed")
with file_transaction(data, out_file) as tx_out:
with open(tx_out, "w") as out_handle:
with open(in_file) as in_handle:
for line in in_handle:
if line.startswith("Status"):
line = "Status\t%s.bam" % sample_name
out_handle.write("%s\n" % line.strip())
return out_file | [
"def",
"_change_sample_name",
"(",
"in_file",
",",
"sample_name",
",",
"data",
"=",
"None",
")",
":",
"out_file",
"=",
"append_stem",
"(",
"in_file",
",",
"\"_fixed\"",
")",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
")",
"as",
"tx_out",
":",
... | Fix name in feature counts log file to get the same
name in multiqc report. | [
"Fix",
"name",
"in",
"feature",
"counts",
"log",
"file",
"to",
"get",
"the",
"same",
"name",
"in",
"multiqc",
"report",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/featureCounts.py#L57-L69 |
224,190 | bcbio/bcbio-nextgen | bcbio/rnaseq/featureCounts.py | _format_count_file | def _format_count_file(count_file, data):
"""
this cuts the count file produced from featureCounts down to
a two column file of gene ids and number of reads mapping to
each gene
"""
COUNT_COLUMN = 5
out_file = os.path.splitext(count_file)[0] + ".fixed.counts"
if file_exists(out_file):
return out_file
df = pd.io.parsers.read_table(count_file, sep="\t", index_col=0, header=1)
df_sub = df.ix[:, COUNT_COLUMN]
with file_transaction(data, out_file) as tx_out_file:
df_sub.to_csv(tx_out_file, sep="\t", index_label="id", header=False)
return out_file | python | def _format_count_file(count_file, data):
"""
this cuts the count file produced from featureCounts down to
a two column file of gene ids and number of reads mapping to
each gene
"""
COUNT_COLUMN = 5
out_file = os.path.splitext(count_file)[0] + ".fixed.counts"
if file_exists(out_file):
return out_file
df = pd.io.parsers.read_table(count_file, sep="\t", index_col=0, header=1)
df_sub = df.ix[:, COUNT_COLUMN]
with file_transaction(data, out_file) as tx_out_file:
df_sub.to_csv(tx_out_file, sep="\t", index_label="id", header=False)
return out_file | [
"def",
"_format_count_file",
"(",
"count_file",
",",
"data",
")",
":",
"COUNT_COLUMN",
"=",
"5",
"out_file",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"count_file",
")",
"[",
"0",
"]",
"+",
"\".fixed.counts\"",
"if",
"file_exists",
"(",
"out_file",
")"... | this cuts the count file produced from featureCounts down to
a two column file of gene ids and number of reads mapping to
each gene | [
"this",
"cuts",
"the",
"count",
"file",
"produced",
"from",
"featureCounts",
"down",
"to",
"a",
"two",
"column",
"file",
"of",
"gene",
"ids",
"and",
"number",
"of",
"reads",
"mapping",
"to",
"each",
"gene"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/featureCounts.py#L71-L86 |
224,191 | bcbio/bcbio-nextgen | bcbio/variation/peddy.py | run_qc | def run_qc(_, data, out_dir):
"""Run quality control in QC environment on a single sample.
Enables peddy integration with CWL runs.
"""
if cwlutils.is_cwl_run(data):
qc_data = run_peddy([data], out_dir)
if tz.get_in(["summary", "qc", "peddy"], qc_data):
return tz.get_in(["summary", "qc", "peddy"], qc_data) | python | def run_qc(_, data, out_dir):
"""Run quality control in QC environment on a single sample.
Enables peddy integration with CWL runs.
"""
if cwlutils.is_cwl_run(data):
qc_data = run_peddy([data], out_dir)
if tz.get_in(["summary", "qc", "peddy"], qc_data):
return tz.get_in(["summary", "qc", "peddy"], qc_data) | [
"def",
"run_qc",
"(",
"_",
",",
"data",
",",
"out_dir",
")",
":",
"if",
"cwlutils",
".",
"is_cwl_run",
"(",
"data",
")",
":",
"qc_data",
"=",
"run_peddy",
"(",
"[",
"data",
"]",
",",
"out_dir",
")",
"if",
"tz",
".",
"get_in",
"(",
"[",
"\"summary\"... | Run quality control in QC environment on a single sample.
Enables peddy integration with CWL runs. | [
"Run",
"quality",
"control",
"in",
"QC",
"environment",
"on",
"a",
"single",
"sample",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/peddy.py#L35-L43 |
224,192 | bcbio/bcbio-nextgen | bcbio/chipseq/macs2.py | run | def run(name, chip_bam, input_bam, genome_build, out_dir, method, resources, data):
"""
Run macs2 for chip and input samples avoiding
errors due to samples.
"""
# output file name need to have the caller name
config = dd.get_config(data)
out_file = os.path.join(out_dir, name + "_peaks_macs2.xls")
macs2_file = os.path.join(out_dir, name + "_peaks.xls")
if utils.file_exists(out_file):
_compres_bdg_files(out_dir)
return _get_output_files(out_dir)
macs2 = config_utils.get_program("macs2", config)
options = " ".join(resources.get("macs2", {}).get("options", ""))
genome_size = bam.fasta.total_sequence_length(dd.get_ref_file(data))
genome_size = "" if options.find("-g") > -1 else "-g %s" % genome_size
paired = "-f BAMPE" if bam.is_paired(chip_bam) else ""
with utils.chdir(out_dir):
cmd = _macs2_cmd(method)
try:
do.run(cmd.format(**locals()), "macs2 for %s" % name)
utils.move_safe(macs2_file, out_file)
except subprocess.CalledProcessError:
raise RuntimeWarning("macs2 terminated with an error.\n"
"Please, check the message and report "
"error if it is related to bcbio.\n"
"You can add specific options for the sample "
"setting resources as explained in docs: "
"https://bcbio-nextgen.readthedocs.org/en/latest/contents/configuration.html#sample-specific-resources")
_compres_bdg_files(out_dir)
return _get_output_files(out_dir) | python | def run(name, chip_bam, input_bam, genome_build, out_dir, method, resources, data):
"""
Run macs2 for chip and input samples avoiding
errors due to samples.
"""
# output file name need to have the caller name
config = dd.get_config(data)
out_file = os.path.join(out_dir, name + "_peaks_macs2.xls")
macs2_file = os.path.join(out_dir, name + "_peaks.xls")
if utils.file_exists(out_file):
_compres_bdg_files(out_dir)
return _get_output_files(out_dir)
macs2 = config_utils.get_program("macs2", config)
options = " ".join(resources.get("macs2", {}).get("options", ""))
genome_size = bam.fasta.total_sequence_length(dd.get_ref_file(data))
genome_size = "" if options.find("-g") > -1 else "-g %s" % genome_size
paired = "-f BAMPE" if bam.is_paired(chip_bam) else ""
with utils.chdir(out_dir):
cmd = _macs2_cmd(method)
try:
do.run(cmd.format(**locals()), "macs2 for %s" % name)
utils.move_safe(macs2_file, out_file)
except subprocess.CalledProcessError:
raise RuntimeWarning("macs2 terminated with an error.\n"
"Please, check the message and report "
"error if it is related to bcbio.\n"
"You can add specific options for the sample "
"setting resources as explained in docs: "
"https://bcbio-nextgen.readthedocs.org/en/latest/contents/configuration.html#sample-specific-resources")
_compres_bdg_files(out_dir)
return _get_output_files(out_dir) | [
"def",
"run",
"(",
"name",
",",
"chip_bam",
",",
"input_bam",
",",
"genome_build",
",",
"out_dir",
",",
"method",
",",
"resources",
",",
"data",
")",
":",
"# output file name need to have the caller name",
"config",
"=",
"dd",
".",
"get_config",
"(",
"data",
"... | Run macs2 for chip and input samples avoiding
errors due to samples. | [
"Run",
"macs2",
"for",
"chip",
"and",
"input",
"samples",
"avoiding",
"errors",
"due",
"to",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/chipseq/macs2.py#L11-L41 |
224,193 | bcbio/bcbio-nextgen | bcbio/chipseq/macs2.py | _macs2_cmd | def _macs2_cmd(method="chip"):
"""Main command for macs2 tool."""
if method.lower() == "chip":
cmd = ("{macs2} callpeak -t {chip_bam} -c {input_bam} {paired} "
" {genome_size} -n {name} -B {options}")
elif method.lower() == "atac":
cmd = ("{macs2} callpeak -t {chip_bam} --nomodel "
" {paired} {genome_size} -n {name} -B {options}"
" --nolambda --keep-dup all")
else:
raise ValueError("chip_method should be chip or atac.")
return cmd | python | def _macs2_cmd(method="chip"):
"""Main command for macs2 tool."""
if method.lower() == "chip":
cmd = ("{macs2} callpeak -t {chip_bam} -c {input_bam} {paired} "
" {genome_size} -n {name} -B {options}")
elif method.lower() == "atac":
cmd = ("{macs2} callpeak -t {chip_bam} --nomodel "
" {paired} {genome_size} -n {name} -B {options}"
" --nolambda --keep-dup all")
else:
raise ValueError("chip_method should be chip or atac.")
return cmd | [
"def",
"_macs2_cmd",
"(",
"method",
"=",
"\"chip\"",
")",
":",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"\"chip\"",
":",
"cmd",
"=",
"(",
"\"{macs2} callpeak -t {chip_bam} -c {input_bam} {paired} \"",
"\" {genome_size} -n {name} -B {options}\"",
")",
"elif",
"met... | Main command for macs2 tool. | [
"Main",
"command",
"for",
"macs2",
"tool",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/chipseq/macs2.py#L60-L71 |
224,194 | bcbio/bcbio-nextgen | bcbio/pipeline/archive.py | to_cram | def to_cram(data):
"""Convert BAM archive files into indexed CRAM.
"""
data = utils.to_single_data(data)
cram_file = cram.compress(dd.get_work_bam(data) or dd.get_align_bam(data), data)
out_key = "archive_bam" if cwlutils.is_cwl_run(data) else "work_bam"
data[out_key] = cram_file
return [[data]] | python | def to_cram(data):
"""Convert BAM archive files into indexed CRAM.
"""
data = utils.to_single_data(data)
cram_file = cram.compress(dd.get_work_bam(data) or dd.get_align_bam(data), data)
out_key = "archive_bam" if cwlutils.is_cwl_run(data) else "work_bam"
data[out_key] = cram_file
return [[data]] | [
"def",
"to_cram",
"(",
"data",
")",
":",
"data",
"=",
"utils",
".",
"to_single_data",
"(",
"data",
")",
"cram_file",
"=",
"cram",
".",
"compress",
"(",
"dd",
".",
"get_work_bam",
"(",
"data",
")",
"or",
"dd",
".",
"get_align_bam",
"(",
"data",
")",
"... | Convert BAM archive files into indexed CRAM. | [
"Convert",
"BAM",
"archive",
"files",
"into",
"indexed",
"CRAM",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/archive.py#L11-L18 |
224,195 | bcbio/bcbio-nextgen | bcbio/pipeline/archive.py | compress | def compress(samples, run_parallel):
"""Perform compression of output files for long term storage.
"""
to_cram = []
finished = []
for data in [x[0] for x in samples]:
if "cram" in dd.get_archive(data) or "cram-lossless" in dd.get_archive(data):
to_cram.append([data])
else:
finished.append([data])
crammed = run_parallel("archive_to_cram", to_cram)
return finished + crammed | python | def compress(samples, run_parallel):
"""Perform compression of output files for long term storage.
"""
to_cram = []
finished = []
for data in [x[0] for x in samples]:
if "cram" in dd.get_archive(data) or "cram-lossless" in dd.get_archive(data):
to_cram.append([data])
else:
finished.append([data])
crammed = run_parallel("archive_to_cram", to_cram)
return finished + crammed | [
"def",
"compress",
"(",
"samples",
",",
"run_parallel",
")",
":",
"to_cram",
"=",
"[",
"]",
"finished",
"=",
"[",
"]",
"for",
"data",
"in",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"samples",
"]",
":",
"if",
"\"cram\"",
"in",
"dd",
".",
"get_ar... | Perform compression of output files for long term storage. | [
"Perform",
"compression",
"of",
"output",
"files",
"for",
"long",
"term",
"storage",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/archive.py#L20-L31 |
224,196 | bcbio/bcbio-nextgen | bcbio/qc/samtools.py | run | def run(_, data, out_dir=None):
"""Run samtools stats with reports on mapped reads, duplicates and insert sizes.
"""
stats_file, idxstats_file = _get_stats_files(data, out_dir)
samtools = config_utils.get_program("samtools", data["config"])
bam_file = dd.get_align_bam(data) or dd.get_work_bam(data)
if not utils.file_exists(stats_file):
utils.safe_makedir(out_dir)
with file_transaction(data, stats_file) as tx_out_file:
cores = dd.get_num_cores(data)
cmd = "{samtools} stats -@ {cores} {bam_file}"
cmd += " > {tx_out_file}"
do.run(cmd.format(**locals()), "samtools stats", data)
if not utils.file_exists(idxstats_file):
utils.safe_makedir(out_dir)
with file_transaction(data, idxstats_file) as tx_out_file:
cmd = "{samtools} idxstats {bam_file}"
cmd += " > {tx_out_file}"
do.run(cmd.format(**locals()), "samtools index stats", data)
out = {"base": idxstats_file, "secondary": [stats_file]}
out["metrics"] = _parse_samtools_stats(stats_file)
return out | python | def run(_, data, out_dir=None):
"""Run samtools stats with reports on mapped reads, duplicates and insert sizes.
"""
stats_file, idxstats_file = _get_stats_files(data, out_dir)
samtools = config_utils.get_program("samtools", data["config"])
bam_file = dd.get_align_bam(data) or dd.get_work_bam(data)
if not utils.file_exists(stats_file):
utils.safe_makedir(out_dir)
with file_transaction(data, stats_file) as tx_out_file:
cores = dd.get_num_cores(data)
cmd = "{samtools} stats -@ {cores} {bam_file}"
cmd += " > {tx_out_file}"
do.run(cmd.format(**locals()), "samtools stats", data)
if not utils.file_exists(idxstats_file):
utils.safe_makedir(out_dir)
with file_transaction(data, idxstats_file) as tx_out_file:
cmd = "{samtools} idxstats {bam_file}"
cmd += " > {tx_out_file}"
do.run(cmd.format(**locals()), "samtools index stats", data)
out = {"base": idxstats_file, "secondary": [stats_file]}
out["metrics"] = _parse_samtools_stats(stats_file)
return out | [
"def",
"run",
"(",
"_",
",",
"data",
",",
"out_dir",
"=",
"None",
")",
":",
"stats_file",
",",
"idxstats_file",
"=",
"_get_stats_files",
"(",
"data",
",",
"out_dir",
")",
"samtools",
"=",
"config_utils",
".",
"get_program",
"(",
"\"samtools\"",
",",
"data"... | Run samtools stats with reports on mapped reads, duplicates and insert sizes. | [
"Run",
"samtools",
"stats",
"with",
"reports",
"on",
"mapped",
"reads",
"duplicates",
"and",
"insert",
"sizes",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/samtools.py#L13-L34 |
224,197 | bcbio/bcbio-nextgen | bcbio/qc/samtools.py | run_and_save | def run_and_save(data):
"""Run QC, saving file outputs in data dictionary.
"""
run(None, data)
stats_file, idxstats_file = _get_stats_files(data)
data = tz.update_in(data, ["depth", "samtools", "stats"], lambda x: stats_file)
data = tz.update_in(data, ["depth", "samtools", "idxstats"], lambda x: idxstats_file)
return data | python | def run_and_save(data):
"""Run QC, saving file outputs in data dictionary.
"""
run(None, data)
stats_file, idxstats_file = _get_stats_files(data)
data = tz.update_in(data, ["depth", "samtools", "stats"], lambda x: stats_file)
data = tz.update_in(data, ["depth", "samtools", "idxstats"], lambda x: idxstats_file)
return data | [
"def",
"run_and_save",
"(",
"data",
")",
":",
"run",
"(",
"None",
",",
"data",
")",
"stats_file",
",",
"idxstats_file",
"=",
"_get_stats_files",
"(",
"data",
")",
"data",
"=",
"tz",
".",
"update_in",
"(",
"data",
",",
"[",
"\"depth\"",
",",
"\"samtools\"... | Run QC, saving file outputs in data dictionary. | [
"Run",
"QC",
"saving",
"file",
"outputs",
"in",
"data",
"dictionary",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/samtools.py#L36-L43 |
224,198 | bcbio/bcbio-nextgen | bcbio/qc/samtools.py | _get_stats_files | def _get_stats_files(data, out_dir=None):
"""Retrieve stats files from pre-existing dictionary or filesystem.
"""
if not out_dir:
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data),
"qc", dd.get_sample_name(data), "samtools"))
stats_file = tz.get_in(["depth", "samtools", "stats"], data)
idxstats_file = tz.get_in(["depth", "samtools", "idxstats"], data)
if not stats_file:
stats_file = os.path.join(out_dir, "%s.txt" % dd.get_sample_name(data))
if not idxstats_file:
idxstats_file = os.path.join(out_dir, "%s-idxstats.txt" % dd.get_sample_name(data))
return stats_file, idxstats_file | python | def _get_stats_files(data, out_dir=None):
"""Retrieve stats files from pre-existing dictionary or filesystem.
"""
if not out_dir:
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data),
"qc", dd.get_sample_name(data), "samtools"))
stats_file = tz.get_in(["depth", "samtools", "stats"], data)
idxstats_file = tz.get_in(["depth", "samtools", "idxstats"], data)
if not stats_file:
stats_file = os.path.join(out_dir, "%s.txt" % dd.get_sample_name(data))
if not idxstats_file:
idxstats_file = os.path.join(out_dir, "%s-idxstats.txt" % dd.get_sample_name(data))
return stats_file, idxstats_file | [
"def",
"_get_stats_files",
"(",
"data",
",",
"out_dir",
"=",
"None",
")",
":",
"if",
"not",
"out_dir",
":",
"out_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",
",",
"\"q... | Retrieve stats files from pre-existing dictionary or filesystem. | [
"Retrieve",
"stats",
"files",
"from",
"pre",
"-",
"existing",
"dictionary",
"or",
"filesystem",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/samtools.py#L45-L57 |
224,199 | bcbio/bcbio-nextgen | bcbio/provenance/do.py | _descr_str | def _descr_str(descr, data, region):
"""Add additional useful information from data to description string.
"""
if data:
name = dd.get_sample_name(data)
if name:
descr = "{0} : {1}".format(descr, name)
elif "work_bam" in data:
descr = "{0} : {1}".format(descr, os.path.basename(data["work_bam"]))
if region:
descr = "{0} : {1}".format(descr, region)
return descr | python | def _descr_str(descr, data, region):
"""Add additional useful information from data to description string.
"""
if data:
name = dd.get_sample_name(data)
if name:
descr = "{0} : {1}".format(descr, name)
elif "work_bam" in data:
descr = "{0} : {1}".format(descr, os.path.basename(data["work_bam"]))
if region:
descr = "{0} : {1}".format(descr, region)
return descr | [
"def",
"_descr_str",
"(",
"descr",
",",
"data",
",",
"region",
")",
":",
"if",
"data",
":",
"name",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"if",
"name",
":",
"descr",
"=",
"\"{0} : {1}\"",
".",
"format",
"(",
"descr",
",",
"name",
")",
... | Add additional useful information from data to description string. | [
"Add",
"additional",
"useful",
"information",
"from",
"data",
"to",
"description",
"string",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/do.py#L35-L46 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.