id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
237,300 | bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | to_rec_single | def to_rec_single(samples, default_keys=None):
"""Convert output into a list of single CWL records.
"""
out = []
for data in samples:
recs = samples_to_records([normalize_missing(utils.to_single_data(data))], default_keys)
assert len(recs) == 1
out.append(recs[0])
return out | python | def to_rec_single(samples, default_keys=None):
out = []
for data in samples:
recs = samples_to_records([normalize_missing(utils.to_single_data(data))], default_keys)
assert len(recs) == 1
out.append(recs[0])
return out | [
"def",
"to_rec_single",
"(",
"samples",
",",
"default_keys",
"=",
"None",
")",
":",
"out",
"=",
"[",
"]",
"for",
"data",
"in",
"samples",
":",
"recs",
"=",
"samples_to_records",
"(",
"[",
"normalize_missing",
"(",
"utils",
".",
"to_single_data",
"(",
"data... | Convert output into a list of single CWL records. | [
"Convert",
"output",
"into",
"a",
"list",
"of",
"single",
"CWL",
"records",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L26-L34 |
237,301 | bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | handle_combined_input | def handle_combined_input(args):
"""Check for cases where we have a combined input nested list.
In these cases the CWL will be double nested:
[[[rec_a], [rec_b]]]
and we remove the outer nesting.
"""
cur_args = args[:]
while len(cur_args) == 1 and isinstance(cur_args[0], (list, tuple)):
cur_args = cur_args[0]
return cur_args | python | def handle_combined_input(args):
cur_args = args[:]
while len(cur_args) == 1 and isinstance(cur_args[0], (list, tuple)):
cur_args = cur_args[0]
return cur_args | [
"def",
"handle_combined_input",
"(",
"args",
")",
":",
"cur_args",
"=",
"args",
"[",
":",
"]",
"while",
"len",
"(",
"cur_args",
")",
"==",
"1",
"and",
"isinstance",
"(",
"cur_args",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"cur... | Check for cases where we have a combined input nested list.
In these cases the CWL will be double nested:
[[[rec_a], [rec_b]]]
and we remove the outer nesting. | [
"Check",
"for",
"cases",
"where",
"we",
"have",
"a",
"combined",
"input",
"nested",
"list",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L39-L51 |
237,302 | bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | normalize_missing | def normalize_missing(xs):
"""Normalize missing values to avoid string 'None' inputs.
"""
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = normalize_missing(v)
elif isinstance(xs, (list, tuple)):
xs = [normalize_missing(x) for x in xs]
elif isinstance(xs, six.string_types):
if xs.lower() in ["none", "null"]:
xs = None
elif xs.lower() == "true":
xs = True
elif xs.lower() == "false":
xs = False
return xs | python | def normalize_missing(xs):
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = normalize_missing(v)
elif isinstance(xs, (list, tuple)):
xs = [normalize_missing(x) for x in xs]
elif isinstance(xs, six.string_types):
if xs.lower() in ["none", "null"]:
xs = None
elif xs.lower() == "true":
xs = True
elif xs.lower() == "false":
xs = False
return xs | [
"def",
"normalize_missing",
"(",
"xs",
")",
":",
"if",
"isinstance",
"(",
"xs",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"xs",
".",
"items",
"(",
")",
":",
"xs",
"[",
"k",
"]",
"=",
"normalize_missing",
"(",
"v",
")",
"elif",
"isinstanc... | Normalize missing values to avoid string 'None' inputs. | [
"Normalize",
"missing",
"values",
"to",
"avoid",
"string",
"None",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L53-L68 |
237,303 | bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | unpack_tarballs | def unpack_tarballs(xs, data, use_subdir=True):
"""Unpack workflow tarballs into ready to use directories.
"""
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = unpack_tarballs(v, data, use_subdir)
elif isinstance(xs, (list, tuple)):
xs = [unpack_tarballs(x, data, use_subdir) for x in xs]
elif isinstance(xs, six.string_types):
if os.path.isfile(xs.encode("utf-8", "ignore")) and xs.endswith("-wf.tar.gz"):
if use_subdir:
tarball_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "wf-inputs"))
else:
tarball_dir = dd.get_work_dir(data)
out_dir = os.path.join(tarball_dir,
os.path.basename(xs).replace("-wf.tar.gz", "").replace("--", os.path.sep))
if not os.path.exists(out_dir):
with utils.chdir(tarball_dir):
with tarfile.open(xs, "r:gz") as tar:
tar.extractall()
assert os.path.exists(out_dir), out_dir
# Default to representing output directory
xs = out_dir
# Look for aligner indices
for fname in os.listdir(out_dir):
if fname.endswith(DIR_TARGETS):
xs = os.path.join(out_dir, fname)
break
elif fname.endswith(BASENAME_TARGETS):
base = os.path.join(out_dir, utils.splitext_plus(os.path.basename(fname))[0])
xs = glob.glob("%s*" % base)
break
return xs | python | def unpack_tarballs(xs, data, use_subdir=True):
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = unpack_tarballs(v, data, use_subdir)
elif isinstance(xs, (list, tuple)):
xs = [unpack_tarballs(x, data, use_subdir) for x in xs]
elif isinstance(xs, six.string_types):
if os.path.isfile(xs.encode("utf-8", "ignore")) and xs.endswith("-wf.tar.gz"):
if use_subdir:
tarball_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "wf-inputs"))
else:
tarball_dir = dd.get_work_dir(data)
out_dir = os.path.join(tarball_dir,
os.path.basename(xs).replace("-wf.tar.gz", "").replace("--", os.path.sep))
if not os.path.exists(out_dir):
with utils.chdir(tarball_dir):
with tarfile.open(xs, "r:gz") as tar:
tar.extractall()
assert os.path.exists(out_dir), out_dir
# Default to representing output directory
xs = out_dir
# Look for aligner indices
for fname in os.listdir(out_dir):
if fname.endswith(DIR_TARGETS):
xs = os.path.join(out_dir, fname)
break
elif fname.endswith(BASENAME_TARGETS):
base = os.path.join(out_dir, utils.splitext_plus(os.path.basename(fname))[0])
xs = glob.glob("%s*" % base)
break
return xs | [
"def",
"unpack_tarballs",
"(",
"xs",
",",
"data",
",",
"use_subdir",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"xs",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"xs",
".",
"items",
"(",
")",
":",
"xs",
"[",
"k",
"]",
"=",
"unpack_t... | Unpack workflow tarballs into ready to use directories. | [
"Unpack",
"workflow",
"tarballs",
"into",
"ready",
"to",
"use",
"directories",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L76-L108 |
237,304 | bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | _get_all_cwlkeys | def _get_all_cwlkeys(items, default_keys=None):
"""Retrieve cwlkeys from inputs, handling defaults which can be null.
When inputs are null in some and present in others, this creates unequal
keys in each sample, confusing decision making about which are primary and extras.
"""
if default_keys:
default_keys = set(default_keys)
else:
default_keys = set(["metadata__batch", "config__algorithm__validate",
"config__algorithm__validate_regions",
"config__algorithm__validate_regions_merged",
"config__algorithm__variant_regions",
"validate__summary",
"validate__tp", "validate__fp", "validate__fn",
"config__algorithm__coverage", "config__algorithm__coverage_merged",
"genome_resources__variation__cosmic", "genome_resources__variation__dbsnp",
"genome_resources__variation__clinvar"
])
all_keys = set([])
for data in items:
all_keys.update(set(data["cwl_keys"]))
all_keys.update(default_keys)
return all_keys | python | def _get_all_cwlkeys(items, default_keys=None):
if default_keys:
default_keys = set(default_keys)
else:
default_keys = set(["metadata__batch", "config__algorithm__validate",
"config__algorithm__validate_regions",
"config__algorithm__validate_regions_merged",
"config__algorithm__variant_regions",
"validate__summary",
"validate__tp", "validate__fp", "validate__fn",
"config__algorithm__coverage", "config__algorithm__coverage_merged",
"genome_resources__variation__cosmic", "genome_resources__variation__dbsnp",
"genome_resources__variation__clinvar"
])
all_keys = set([])
for data in items:
all_keys.update(set(data["cwl_keys"]))
all_keys.update(default_keys)
return all_keys | [
"def",
"_get_all_cwlkeys",
"(",
"items",
",",
"default_keys",
"=",
"None",
")",
":",
"if",
"default_keys",
":",
"default_keys",
"=",
"set",
"(",
"default_keys",
")",
"else",
":",
"default_keys",
"=",
"set",
"(",
"[",
"\"metadata__batch\"",
",",
"\"config__algo... | Retrieve cwlkeys from inputs, handling defaults which can be null.
When inputs are null in some and present in others, this creates unequal
keys in each sample, confusing decision making about which are primary and extras. | [
"Retrieve",
"cwlkeys",
"from",
"inputs",
"handling",
"defaults",
"which",
"can",
"be",
"null",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L110-L133 |
237,305 | bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | split_data_cwl_items | def split_data_cwl_items(items, default_keys=None):
"""Split a set of CWL output dictionaries into data samples and CWL items.
Handles cases where we're arrayed on multiple things, like a set of regional
VCF calls and data objects.
"""
key_lens = set([])
for data in items:
key_lens.add(len(_get_all_cwlkeys([data], default_keys)))
extra_key_len = min(list(key_lens)) if len(key_lens) > 1 else None
data_out = []
extra_out = []
for data in items:
if extra_key_len and len(_get_all_cwlkeys([data], default_keys)) == extra_key_len:
extra_out.append(data)
else:
data_out.append(data)
if len(extra_out) == 0:
return data_out, {}
else:
cwl_keys = extra_out[0]["cwl_keys"]
for extra in extra_out[1:]:
cur_cwl_keys = extra["cwl_keys"]
assert cur_cwl_keys == cwl_keys, pprint.pformat(extra_out)
cwl_extras = collections.defaultdict(list)
for data in items:
for key in cwl_keys:
cwl_extras[key].append(data[key])
data_final = []
for data in data_out:
for key in cwl_keys:
data.pop(key)
data_final.append(data)
return data_final, dict(cwl_extras) | python | def split_data_cwl_items(items, default_keys=None):
key_lens = set([])
for data in items:
key_lens.add(len(_get_all_cwlkeys([data], default_keys)))
extra_key_len = min(list(key_lens)) if len(key_lens) > 1 else None
data_out = []
extra_out = []
for data in items:
if extra_key_len and len(_get_all_cwlkeys([data], default_keys)) == extra_key_len:
extra_out.append(data)
else:
data_out.append(data)
if len(extra_out) == 0:
return data_out, {}
else:
cwl_keys = extra_out[0]["cwl_keys"]
for extra in extra_out[1:]:
cur_cwl_keys = extra["cwl_keys"]
assert cur_cwl_keys == cwl_keys, pprint.pformat(extra_out)
cwl_extras = collections.defaultdict(list)
for data in items:
for key in cwl_keys:
cwl_extras[key].append(data[key])
data_final = []
for data in data_out:
for key in cwl_keys:
data.pop(key)
data_final.append(data)
return data_final, dict(cwl_extras) | [
"def",
"split_data_cwl_items",
"(",
"items",
",",
"default_keys",
"=",
"None",
")",
":",
"key_lens",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"data",
"in",
"items",
":",
"key_lens",
".",
"add",
"(",
"len",
"(",
"_get_all_cwlkeys",
"(",
"[",
"data",
"]",
... | Split a set of CWL output dictionaries into data samples and CWL items.
Handles cases where we're arrayed on multiple things, like a set of regional
VCF calls and data objects. | [
"Split",
"a",
"set",
"of",
"CWL",
"output",
"dictionaries",
"into",
"data",
"samples",
"and",
"CWL",
"items",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L135-L168 |
237,306 | bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | samples_to_records | def samples_to_records(samples, default_keys=None):
"""Convert samples into output CWL records.
"""
from bcbio.pipeline import run_info
RECORD_CONVERT_TO_LIST = set(["config__algorithm__tools_on", "config__algorithm__tools_off",
"reference__genome_context"])
all_keys = _get_all_cwlkeys(samples, default_keys)
out = []
for data in samples:
for raw_key in sorted(list(all_keys)):
key = raw_key.split("__")
if tz.get_in(key, data) is None:
data = tz.update_in(data, key, lambda x: None)
if raw_key not in data["cwl_keys"]:
data["cwl_keys"].append(raw_key)
if raw_key in RECORD_CONVERT_TO_LIST:
val = tz.get_in(key, data)
if not val: val = []
elif not isinstance(val, (list, tuple)): val = [val]
data = tz.update_in(data, key, lambda x: val)
# Booleans are problematic for CWL serialization, convert into string representation
if isinstance(tz.get_in(key, data), bool):
data = tz.update_in(data, key, lambda x: str(tz.get_in(key, data)))
data["metadata"] = run_info.add_metadata_defaults(data.get("metadata", {}))
out.append(data)
return out | python | def samples_to_records(samples, default_keys=None):
from bcbio.pipeline import run_info
RECORD_CONVERT_TO_LIST = set(["config__algorithm__tools_on", "config__algorithm__tools_off",
"reference__genome_context"])
all_keys = _get_all_cwlkeys(samples, default_keys)
out = []
for data in samples:
for raw_key in sorted(list(all_keys)):
key = raw_key.split("__")
if tz.get_in(key, data) is None:
data = tz.update_in(data, key, lambda x: None)
if raw_key not in data["cwl_keys"]:
data["cwl_keys"].append(raw_key)
if raw_key in RECORD_CONVERT_TO_LIST:
val = tz.get_in(key, data)
if not val: val = []
elif not isinstance(val, (list, tuple)): val = [val]
data = tz.update_in(data, key, lambda x: val)
# Booleans are problematic for CWL serialization, convert into string representation
if isinstance(tz.get_in(key, data), bool):
data = tz.update_in(data, key, lambda x: str(tz.get_in(key, data)))
data["metadata"] = run_info.add_metadata_defaults(data.get("metadata", {}))
out.append(data)
return out | [
"def",
"samples_to_records",
"(",
"samples",
",",
"default_keys",
"=",
"None",
")",
":",
"from",
"bcbio",
".",
"pipeline",
"import",
"run_info",
"RECORD_CONVERT_TO_LIST",
"=",
"set",
"(",
"[",
"\"config__algorithm__tools_on\"",
",",
"\"config__algorithm__tools_off\"",
... | Convert samples into output CWL records. | [
"Convert",
"samples",
"into",
"output",
"CWL",
"records",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L170-L195 |
237,307 | bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | assign_complex_to_samples | def assign_complex_to_samples(items):
"""Assign complex inputs like variants and align outputs to samples.
Handles list inputs to record conversion where we have inputs from multiple
locations and need to ensure they are properly assigned to samples in many
environments.
The unpleasant approach here is to use standard file naming to match
with samples so this can work in environments where we don't download/stream
the input files (for space/time savings).
"""
extract_fns = {("variants", "samples"): _get_vcf_samples,
("align_bam",): _get_bam_samples}
complex = {k: {} for k in extract_fns.keys()}
for data in items:
for k in complex:
v = tz.get_in(k, data)
if v is not None:
for s in extract_fns[k](v, items):
if s:
complex[k][s] = v
out = []
for data in items:
for k in complex:
newv = tz.get_in([k, dd.get_sample_name(data)], complex)
if newv:
data = tz.update_in(data, k, lambda x: newv)
out.append(data)
return out | python | def assign_complex_to_samples(items):
extract_fns = {("variants", "samples"): _get_vcf_samples,
("align_bam",): _get_bam_samples}
complex = {k: {} for k in extract_fns.keys()}
for data in items:
for k in complex:
v = tz.get_in(k, data)
if v is not None:
for s in extract_fns[k](v, items):
if s:
complex[k][s] = v
out = []
for data in items:
for k in complex:
newv = tz.get_in([k, dd.get_sample_name(data)], complex)
if newv:
data = tz.update_in(data, k, lambda x: newv)
out.append(data)
return out | [
"def",
"assign_complex_to_samples",
"(",
"items",
")",
":",
"extract_fns",
"=",
"{",
"(",
"\"variants\"",
",",
"\"samples\"",
")",
":",
"_get_vcf_samples",
",",
"(",
"\"align_bam\"",
",",
")",
":",
"_get_bam_samples",
"}",
"complex",
"=",
"{",
"k",
":",
"{",... | Assign complex inputs like variants and align outputs to samples.
Handles list inputs to record conversion where we have inputs from multiple
locations and need to ensure they are properly assigned to samples in many
environments.
The unpleasant approach here is to use standard file naming to match
with samples so this can work in environments where we don't download/stream
the input files (for space/time savings). | [
"Assign",
"complex",
"inputs",
"like",
"variants",
"and",
"align",
"outputs",
"to",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L197-L225 |
237,308 | bcbio/bcbio-nextgen | bcbio/pipeline/variation.py | _normalize_vc_input | def _normalize_vc_input(data):
"""Normalize different types of variant calling inputs.
Handles standard and ensemble inputs.
"""
if data.get("ensemble"):
for k in ["batch_samples", "validate", "vrn_file"]:
data[k] = data["ensemble"][k]
data["config"]["algorithm"]["variantcaller"] = "ensemble"
data["metadata"] = {"batch": data["ensemble"]["batch_id"]}
return data | python | def _normalize_vc_input(data):
if data.get("ensemble"):
for k in ["batch_samples", "validate", "vrn_file"]:
data[k] = data["ensemble"][k]
data["config"]["algorithm"]["variantcaller"] = "ensemble"
data["metadata"] = {"batch": data["ensemble"]["batch_id"]}
return data | [
"def",
"_normalize_vc_input",
"(",
"data",
")",
":",
"if",
"data",
".",
"get",
"(",
"\"ensemble\"",
")",
":",
"for",
"k",
"in",
"[",
"\"batch_samples\"",
",",
"\"validate\"",
",",
"\"vrn_file\"",
"]",
":",
"data",
"[",
"k",
"]",
"=",
"data",
"[",
"\"en... | Normalize different types of variant calling inputs.
Handles standard and ensemble inputs. | [
"Normalize",
"different",
"types",
"of",
"variant",
"calling",
"inputs",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/variation.py#L65-L75 |
237,309 | bcbio/bcbio-nextgen | bcbio/pipeline/variation.py | _get_orig_items | def _get_orig_items(data):
"""Retrieve original items in a batch, handling CWL and standard cases.
"""
if isinstance(data, dict):
if dd.get_align_bam(data) and tz.get_in(["metadata", "batch"], data) and "group_orig" in data:
return vmulti.get_orig_items(data)
else:
return [data]
else:
return data | python | def _get_orig_items(data):
if isinstance(data, dict):
if dd.get_align_bam(data) and tz.get_in(["metadata", "batch"], data) and "group_orig" in data:
return vmulti.get_orig_items(data)
else:
return [data]
else:
return data | [
"def",
"_get_orig_items",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"if",
"dd",
".",
"get_align_bam",
"(",
"data",
")",
"and",
"tz",
".",
"get_in",
"(",
"[",
"\"metadata\"",
",",
"\"batch\"",
"]",
",",
"data",
")"... | Retrieve original items in a batch, handling CWL and standard cases. | [
"Retrieve",
"original",
"items",
"in",
"a",
"batch",
"handling",
"CWL",
"and",
"standard",
"cases",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/variation.py#L129-L138 |
237,310 | bcbio/bcbio-nextgen | bcbio/pipeline/variation.py | _symlink_to_workdir | def _symlink_to_workdir(data, key):
"""For CWL support, symlink files into a working directory if in read-only imports.
"""
orig_file = tz.get_in(key, data)
if orig_file and not orig_file.startswith(dd.get_work_dir(data)):
variantcaller = genotype.get_variantcaller(data, require_bam=False)
if not variantcaller:
variantcaller = "precalled"
out_file = os.path.join(dd.get_work_dir(data), variantcaller, os.path.basename(orig_file))
utils.safe_makedir(os.path.dirname(out_file))
utils.symlink_plus(orig_file, out_file)
data = tz.update_in(data, key, lambda x: out_file)
return data | python | def _symlink_to_workdir(data, key):
orig_file = tz.get_in(key, data)
if orig_file and not orig_file.startswith(dd.get_work_dir(data)):
variantcaller = genotype.get_variantcaller(data, require_bam=False)
if not variantcaller:
variantcaller = "precalled"
out_file = os.path.join(dd.get_work_dir(data), variantcaller, os.path.basename(orig_file))
utils.safe_makedir(os.path.dirname(out_file))
utils.symlink_plus(orig_file, out_file)
data = tz.update_in(data, key, lambda x: out_file)
return data | [
"def",
"_symlink_to_workdir",
"(",
"data",
",",
"key",
")",
":",
"orig_file",
"=",
"tz",
".",
"get_in",
"(",
"key",
",",
"data",
")",
"if",
"orig_file",
"and",
"not",
"orig_file",
".",
"startswith",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",
")"... | For CWL support, symlink files into a working directory if in read-only imports. | [
"For",
"CWL",
"support",
"symlink",
"files",
"into",
"a",
"working",
"directory",
"if",
"in",
"read",
"-",
"only",
"imports",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/variation.py#L140-L152 |
237,311 | bcbio/bcbio-nextgen | bcbio/pipeline/variation.py | _get_batch_representative | def _get_batch_representative(items, key):
"""Retrieve a representative data item from a batch.
Handles standard bcbio cases (a single data item) and CWL cases with
batches that have a consistent variant file.
"""
if isinstance(items, dict):
return items, items
else:
vals = set([])
out = []
for data in items:
if key in data:
vals.add(data[key])
out.append(data)
if len(vals) != 1:
raise ValueError("Incorrect values for %s: %s" % (key, list(vals)))
return out[0], items | python | def _get_batch_representative(items, key):
if isinstance(items, dict):
return items, items
else:
vals = set([])
out = []
for data in items:
if key in data:
vals.add(data[key])
out.append(data)
if len(vals) != 1:
raise ValueError("Incorrect values for %s: %s" % (key, list(vals)))
return out[0], items | [
"def",
"_get_batch_representative",
"(",
"items",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"items",
",",
"dict",
")",
":",
"return",
"items",
",",
"items",
"else",
":",
"vals",
"=",
"set",
"(",
"[",
"]",
")",
"out",
"=",
"[",
"]",
"for",
"dat... | Retrieve a representative data item from a batch.
Handles standard bcbio cases (a single data item) and CWL cases with
batches that have a consistent variant file. | [
"Retrieve",
"a",
"representative",
"data",
"item",
"from",
"a",
"batch",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/variation.py#L154-L171 |
237,312 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | _get_storage_manager | def _get_storage_manager(resource):
"""Return a storage manager which can process this resource."""
for manager in (AmazonS3, ArvadosKeep, SevenBridges, DNAnexus, AzureBlob, GoogleCloud, RegularServer):
if manager.check_resource(resource):
return manager()
raise ValueError("Unexpected object store %(resource)s" %
{"resource": resource}) | python | def _get_storage_manager(resource):
for manager in (AmazonS3, ArvadosKeep, SevenBridges, DNAnexus, AzureBlob, GoogleCloud, RegularServer):
if manager.check_resource(resource):
return manager()
raise ValueError("Unexpected object store %(resource)s" %
{"resource": resource}) | [
"def",
"_get_storage_manager",
"(",
"resource",
")",
":",
"for",
"manager",
"in",
"(",
"AmazonS3",
",",
"ArvadosKeep",
",",
"SevenBridges",
",",
"DNAnexus",
",",
"AzureBlob",
",",
"GoogleCloud",
",",
"RegularServer",
")",
":",
"if",
"manager",
".",
"check_reso... | Return a storage manager which can process this resource. | [
"Return",
"a",
"storage",
"manager",
"which",
"can",
"process",
"this",
"resource",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L624-L631 |
237,313 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | default_region | def default_region(fname):
"""Return the default region for the received resource.
Note:
This feature is available only for AmazonS3 storage manager.
"""
manager = _get_storage_manager(fname)
if hasattr(manager, "get_region"):
return manager.get_region()
raise NotImplementedError("Unexpected object store %s" % fname) | python | def default_region(fname):
manager = _get_storage_manager(fname)
if hasattr(manager, "get_region"):
return manager.get_region()
raise NotImplementedError("Unexpected object store %s" % fname) | [
"def",
"default_region",
"(",
"fname",
")",
":",
"manager",
"=",
"_get_storage_manager",
"(",
"fname",
")",
"if",
"hasattr",
"(",
"manager",
",",
"\"get_region\"",
")",
":",
"return",
"manager",
".",
"get_region",
"(",
")",
"raise",
"NotImplementedError",
"(",... | Return the default region for the received resource.
Note:
This feature is available only for AmazonS3 storage manager. | [
"Return",
"the",
"default",
"region",
"for",
"the",
"received",
"resource",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L651-L661 |
237,314 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | BlobHandle.blob_properties | def blob_properties(self):
"""Returns all user-defined metadata, standard HTTP properties,
and system properties for the blob.
"""
if not self._blob_properties:
self._blob_properties = self._blob_service.get_blob_properties(
container_name=self._container_name,
blob_name=self._blob_name)
return self._blob_properties | python | def blob_properties(self):
if not self._blob_properties:
self._blob_properties = self._blob_service.get_blob_properties(
container_name=self._container_name,
blob_name=self._blob_name)
return self._blob_properties | [
"def",
"blob_properties",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_blob_properties",
":",
"self",
".",
"_blob_properties",
"=",
"self",
".",
"_blob_service",
".",
"get_blob_properties",
"(",
"container_name",
"=",
"self",
".",
"_container_name",
",",
... | Returns all user-defined metadata, standard HTTP properties,
and system properties for the blob. | [
"Returns",
"all",
"user",
"-",
"defined",
"metadata",
"standard",
"HTTP",
"properties",
"and",
"system",
"properties",
"for",
"the",
"blob",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L154-L162 |
237,315 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | BlobHandle._chunk_offsets | def _chunk_offsets(self):
"""Iterator over chunk offests."""
index = 0
blob_size = self.blob_properties.get('content-length')
while index < blob_size:
yield index
index = index + self._chunk_size | python | def _chunk_offsets(self):
index = 0
blob_size = self.blob_properties.get('content-length')
while index < blob_size:
yield index
index = index + self._chunk_size | [
"def",
"_chunk_offsets",
"(",
"self",
")",
":",
"index",
"=",
"0",
"blob_size",
"=",
"self",
".",
"blob_properties",
".",
"get",
"(",
"'content-length'",
")",
"while",
"index",
"<",
"blob_size",
":",
"yield",
"index",
"index",
"=",
"index",
"+",
"self",
... | Iterator over chunk offests. | [
"Iterator",
"over",
"chunk",
"offests",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L164-L170 |
237,316 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | BlobHandle._chunk_iter | def _chunk_iter(self):
"""Iterator over the blob file."""
for chunk_offset in self._chunk_offsets():
yield self._download_chunk(chunk_offset=chunk_offset,
chunk_size=self._chunk_size) | python | def _chunk_iter(self):
for chunk_offset in self._chunk_offsets():
yield self._download_chunk(chunk_offset=chunk_offset,
chunk_size=self._chunk_size) | [
"def",
"_chunk_iter",
"(",
"self",
")",
":",
"for",
"chunk_offset",
"in",
"self",
".",
"_chunk_offsets",
"(",
")",
":",
"yield",
"self",
".",
"_download_chunk",
"(",
"chunk_offset",
"=",
"chunk_offset",
",",
"chunk_size",
"=",
"self",
".",
"_chunk_size",
")"... | Iterator over the blob file. | [
"Iterator",
"over",
"the",
"blob",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L172-L176 |
237,317 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3.parse_remote | def parse_remote(cls, filename):
"""Parses a remote filename into bucket and key information.
Handles S3 with optional region name specified in key:
BUCKETNAME@REGIONNAME/KEY
"""
parts = filename.split("//")[-1].split("/", 1)
bucket, key = parts if len(parts) == 2 else (parts[0], None)
if bucket.find("@") > 0:
bucket, region = bucket.split("@")
else:
region = None
return cls._REMOTE_FILE("s3", bucket, key, region) | python | def parse_remote(cls, filename):
parts = filename.split("//")[-1].split("/", 1)
bucket, key = parts if len(parts) == 2 else (parts[0], None)
if bucket.find("@") > 0:
bucket, region = bucket.split("@")
else:
region = None
return cls._REMOTE_FILE("s3", bucket, key, region) | [
"def",
"parse_remote",
"(",
"cls",
",",
"filename",
")",
":",
"parts",
"=",
"filename",
".",
"split",
"(",
"\"//\"",
")",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"bucket",
",",
"key",
"=",
"parts",
"if",
"len",
"(",
"parts"... | Parses a remote filename into bucket and key information.
Handles S3 with optional region name specified in key:
BUCKETNAME@REGIONNAME/KEY | [
"Parses",
"a",
"remote",
"filename",
"into",
"bucket",
"and",
"key",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L281-L294 |
237,318 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3._cl_aws_cli | def _cl_aws_cli(cls, file_info, region):
"""Command line required for download using the standard AWS
command line interface.
"""
s3file = cls._S3_FILE % {"bucket": file_info.bucket,
"key": file_info.key,
"region": ""}
command = [os.path.join(os.path.dirname(sys.executable), "aws"),
"s3", "cp", "--region", region, s3file]
return (command, "awscli") | python | def _cl_aws_cli(cls, file_info, region):
s3file = cls._S3_FILE % {"bucket": file_info.bucket,
"key": file_info.key,
"region": ""}
command = [os.path.join(os.path.dirname(sys.executable), "aws"),
"s3", "cp", "--region", region, s3file]
return (command, "awscli") | [
"def",
"_cl_aws_cli",
"(",
"cls",
",",
"file_info",
",",
"region",
")",
":",
"s3file",
"=",
"cls",
".",
"_S3_FILE",
"%",
"{",
"\"bucket\"",
":",
"file_info",
".",
"bucket",
",",
"\"key\"",
":",
"file_info",
".",
"key",
",",
"\"region\"",
":",
"\"\"",
"... | Command line required for download using the standard AWS
command line interface. | [
"Command",
"line",
"required",
"for",
"download",
"using",
"the",
"standard",
"AWS",
"command",
"line",
"interface",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L297-L306 |
237,319 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3._cl_gof3r | def _cl_gof3r(file_info, region):
"""Command line required for download using gof3r."""
command = ["gof3r", "get", "--no-md5",
"-k", file_info.key,
"-b", file_info.bucket]
if region != "us-east-1":
command += ["--endpoint=s3-%s.amazonaws.com" % region]
return (command, "gof3r") | python | def _cl_gof3r(file_info, region):
command = ["gof3r", "get", "--no-md5",
"-k", file_info.key,
"-b", file_info.bucket]
if region != "us-east-1":
command += ["--endpoint=s3-%s.amazonaws.com" % region]
return (command, "gof3r") | [
"def",
"_cl_gof3r",
"(",
"file_info",
",",
"region",
")",
":",
"command",
"=",
"[",
"\"gof3r\"",
",",
"\"get\"",
",",
"\"--no-md5\"",
",",
"\"-k\"",
",",
"file_info",
".",
"key",
",",
"\"-b\"",
",",
"file_info",
".",
"bucket",
"]",
"if",
"region",
"!=",
... | Command line required for download using gof3r. | [
"Command",
"line",
"required",
"for",
"download",
"using",
"gof3r",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L309-L316 |
237,320 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3.get_region | def get_region(cls, resource=None):
"""Retrieve region from standard environmental variables
or file name.
More information of the following link: http://goo.gl/Vb9Jky
"""
if resource:
resource_info = cls.parse_remote(resource)
if resource_info.region:
return resource_info.region
return os.environ.get("AWS_DEFAULT_REGION", cls._DEFAULT_REGION) | python | def get_region(cls, resource=None):
if resource:
resource_info = cls.parse_remote(resource)
if resource_info.region:
return resource_info.region
return os.environ.get("AWS_DEFAULT_REGION", cls._DEFAULT_REGION) | [
"def",
"get_region",
"(",
"cls",
",",
"resource",
"=",
"None",
")",
":",
"if",
"resource",
":",
"resource_info",
"=",
"cls",
".",
"parse_remote",
"(",
"resource",
")",
"if",
"resource_info",
".",
"region",
":",
"return",
"resource_info",
".",
"region",
"re... | Retrieve region from standard environmental variables
or file name.
More information of the following link: http://goo.gl/Vb9Jky | [
"Retrieve",
"region",
"from",
"standard",
"environmental",
"variables",
"or",
"file",
"name",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L338-L349 |
237,321 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3.connect | def connect(cls, resource):
"""Connect to this Region's endpoint.
Returns a connection object pointing to the endpoint associated
to the received resource.
"""
import boto
return boto.s3.connect_to_region(cls.get_region(resource)) | python | def connect(cls, resource):
import boto
return boto.s3.connect_to_region(cls.get_region(resource)) | [
"def",
"connect",
"(",
"cls",
",",
"resource",
")",
":",
"import",
"boto",
"return",
"boto",
".",
"s3",
".",
"connect_to_region",
"(",
"cls",
".",
"get_region",
"(",
"resource",
")",
")"
] | Connect to this Region's endpoint.
Returns a connection object pointing to the endpoint associated
to the received resource. | [
"Connect",
"to",
"this",
"Region",
"s",
"endpoint",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L362-L369 |
237,322 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AmazonS3.open | def open(cls, filename):
"""Return a handle like object for streaming from S3."""
import boto
file_info = cls.parse_remote(filename)
connection = cls.connect(filename)
try:
s3_bucket = connection.get_bucket(file_info.bucket)
except boto.exception.S3ResponseError as error:
# if we don't have bucket permissions but folder permissions,
# try without validation
if error.status == 403:
s3_bucket = connection.get_bucket(file_info.bucket,
validate=False)
else:
raise
s3_key = s3_bucket.get_key(file_info.key)
if s3_key is None:
raise ValueError("Did not find S3 key: %s" % filename)
return S3Handle(s3_key) | python | def open(cls, filename):
import boto
file_info = cls.parse_remote(filename)
connection = cls.connect(filename)
try:
s3_bucket = connection.get_bucket(file_info.bucket)
except boto.exception.S3ResponseError as error:
# if we don't have bucket permissions but folder permissions,
# try without validation
if error.status == 403:
s3_bucket = connection.get_bucket(file_info.bucket,
validate=False)
else:
raise
s3_key = s3_bucket.get_key(file_info.key)
if s3_key is None:
raise ValueError("Did not find S3 key: %s" % filename)
return S3Handle(s3_key) | [
"def",
"open",
"(",
"cls",
",",
"filename",
")",
":",
"import",
"boto",
"file_info",
"=",
"cls",
".",
"parse_remote",
"(",
"filename",
")",
"connection",
"=",
"cls",
".",
"connect",
"(",
"filename",
")",
"try",
":",
"s3_bucket",
"=",
"connection",
".",
... | Return a handle like object for streaming from S3. | [
"Return",
"a",
"handle",
"like",
"object",
"for",
"streaming",
"from",
"S3",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L434-L453 |
237,323 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AzureBlob.parse_remote | def parse_remote(cls, filename):
"""Parses a remote filename into blob information."""
blob_file = cls._URL_FORMAT.search(filename)
return cls._REMOTE_FILE("blob",
storage=blob_file.group("storage"),
container=blob_file.group("container"),
blob=blob_file.group("blob")) | python | def parse_remote(cls, filename):
blob_file = cls._URL_FORMAT.search(filename)
return cls._REMOTE_FILE("blob",
storage=blob_file.group("storage"),
container=blob_file.group("container"),
blob=blob_file.group("blob")) | [
"def",
"parse_remote",
"(",
"cls",
",",
"filename",
")",
":",
"blob_file",
"=",
"cls",
".",
"_URL_FORMAT",
".",
"search",
"(",
"filename",
")",
"return",
"cls",
".",
"_REMOTE_FILE",
"(",
"\"blob\"",
",",
"storage",
"=",
"blob_file",
".",
"group",
"(",
"\... | Parses a remote filename into blob information. | [
"Parses",
"a",
"remote",
"filename",
"into",
"blob",
"information",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L479-L485 |
237,324 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AzureBlob.connect | def connect(cls, resource):
"""Returns a connection object pointing to the endpoint
associated to the received resource.
"""
from azure import storage as azure_storage
file_info = cls.parse_remote(resource)
return azure_storage.BlobService(file_info.storage) | python | def connect(cls, resource):
from azure import storage as azure_storage
file_info = cls.parse_remote(resource)
return azure_storage.BlobService(file_info.storage) | [
"def",
"connect",
"(",
"cls",
",",
"resource",
")",
":",
"from",
"azure",
"import",
"storage",
"as",
"azure_storage",
"file_info",
"=",
"cls",
".",
"parse_remote",
"(",
"resource",
")",
"return",
"azure_storage",
".",
"BlobService",
"(",
"file_info",
".",
"s... | Returns a connection object pointing to the endpoint
associated to the received resource. | [
"Returns",
"a",
"connection",
"object",
"pointing",
"to",
"the",
"endpoint",
"associated",
"to",
"the",
"received",
"resource",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L488-L494 |
237,325 | bcbio/bcbio-nextgen | bcbio/distributed/objectstore.py | AzureBlob.open | def open(cls, filename):
"""Provide a handle-like object for streaming."""
file_info = cls.parse_remote(filename)
blob_service = cls.connect(filename)
return BlobHandle(blob_service=blob_service,
container=file_info.container,
blob=file_info.blob,
chunk_size=cls._BLOB_CHUNK_DATA_SIZE) | python | def open(cls, filename):
file_info = cls.parse_remote(filename)
blob_service = cls.connect(filename)
return BlobHandle(blob_service=blob_service,
container=file_info.container,
blob=file_info.blob,
chunk_size=cls._BLOB_CHUNK_DATA_SIZE) | [
"def",
"open",
"(",
"cls",
",",
"filename",
")",
":",
"file_info",
"=",
"cls",
".",
"parse_remote",
"(",
"filename",
")",
"blob_service",
"=",
"cls",
".",
"connect",
"(",
"filename",
")",
"return",
"BlobHandle",
"(",
"blob_service",
"=",
"blob_service",
",... | Provide a handle-like object for streaming. | [
"Provide",
"a",
"handle",
"-",
"like",
"object",
"for",
"streaming",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L538-L545 |
237,326 | bcbio/bcbio-nextgen | bcbio/bam/cram.py | compress | def compress(in_bam, data):
"""Compress a BAM file to CRAM, providing indexed CRAM file.
Does 8 bin compression of quality score and read name removal
using bamUtils squeeze if `cram` specified:
http://genome.sph.umich.edu/wiki/BamUtil:_squeeze
Otherwise does `cram-lossless` which only converts to CRAM.
"""
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "archive"))
out_file = os.path.join(out_dir, "%s.cram" % os.path.splitext(os.path.basename(in_bam))[0])
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
compress_type = dd.get_archive(data)
samtools = config_utils.get_program("samtools", data["config"])
try:
bam_cmd = config_utils.get_program("bam", data["config"])
except config_utils.CmdNotFound:
bam_cmd = None
to_cram = ("{samtools} view -T {ref_file} -@ {cores} "
"-C -x BD -x BI -o {tx_out_file}")
compressed = False
if "cram" in compress_type and bam_cmd:
try:
cmd = ("{bam_cmd} squeeze --in {in_bam} --out -.ubam --keepDups "
"--binQualS=2,10,20,25,30,35,70 --binMid | " + to_cram)
do.run(cmd.format(**locals()), "Compress BAM to CRAM: quality score binning")
compressed = True
# Retry failures avoiding using bam squeeze which can cause issues
except subprocess.CalledProcessError:
pass
if not compressed:
cmd = (to_cram + " {in_bam}")
do.run(cmd.format(**locals()), "Compress BAM to CRAM: lossless")
index(out_file, data["config"])
return out_file | python | def compress(in_bam, data):
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "archive"))
out_file = os.path.join(out_dir, "%s.cram" % os.path.splitext(os.path.basename(in_bam))[0])
cores = dd.get_num_cores(data)
ref_file = dd.get_ref_file(data)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
compress_type = dd.get_archive(data)
samtools = config_utils.get_program("samtools", data["config"])
try:
bam_cmd = config_utils.get_program("bam", data["config"])
except config_utils.CmdNotFound:
bam_cmd = None
to_cram = ("{samtools} view -T {ref_file} -@ {cores} "
"-C -x BD -x BI -o {tx_out_file}")
compressed = False
if "cram" in compress_type and bam_cmd:
try:
cmd = ("{bam_cmd} squeeze --in {in_bam} --out -.ubam --keepDups "
"--binQualS=2,10,20,25,30,35,70 --binMid | " + to_cram)
do.run(cmd.format(**locals()), "Compress BAM to CRAM: quality score binning")
compressed = True
# Retry failures avoiding using bam squeeze which can cause issues
except subprocess.CalledProcessError:
pass
if not compressed:
cmd = (to_cram + " {in_bam}")
do.run(cmd.format(**locals()), "Compress BAM to CRAM: lossless")
index(out_file, data["config"])
return out_file | [
"def",
"compress",
"(",
"in_bam",
",",
"data",
")",
":",
"out_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",
",",
"\"archive\"",
")",
")",
"out_file",
"=",
"os",
".",
... | Compress a BAM file to CRAM, providing indexed CRAM file.
Does 8 bin compression of quality score and read name removal
using bamUtils squeeze if `cram` specified:
http://genome.sph.umich.edu/wiki/BamUtil:_squeeze
Otherwise does `cram-lossless` which only converts to CRAM. | [
"Compress",
"a",
"BAM",
"file",
"to",
"CRAM",
"providing",
"indexed",
"CRAM",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/cram.py#L14-L52 |
237,327 | bcbio/bcbio-nextgen | bcbio/bam/cram.py | index | def index(in_cram, config):
"""Ensure CRAM file has a .crai index file.
"""
out_file = in_cram + ".crai"
if not utils.file_uptodate(out_file, in_cram):
with file_transaction(config, in_cram + ".crai") as tx_out_file:
tx_in_file = os.path.splitext(tx_out_file)[0]
utils.symlink_plus(in_cram, tx_in_file)
cmd = "samtools index {tx_in_file}"
do.run(cmd.format(**locals()), "Index CRAM file")
return out_file | python | def index(in_cram, config):
out_file = in_cram + ".crai"
if not utils.file_uptodate(out_file, in_cram):
with file_transaction(config, in_cram + ".crai") as tx_out_file:
tx_in_file = os.path.splitext(tx_out_file)[0]
utils.symlink_plus(in_cram, tx_in_file)
cmd = "samtools index {tx_in_file}"
do.run(cmd.format(**locals()), "Index CRAM file")
return out_file | [
"def",
"index",
"(",
"in_cram",
",",
"config",
")",
":",
"out_file",
"=",
"in_cram",
"+",
"\".crai\"",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"in_cram",
")",
":",
"with",
"file_transaction",
"(",
"config",
",",
"in_cram",
"+",
... | Ensure CRAM file has a .crai index file. | [
"Ensure",
"CRAM",
"file",
"has",
"a",
".",
"crai",
"index",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/cram.py#L54-L64 |
237,328 | bcbio/bcbio-nextgen | bcbio/bam/cram.py | to_bam | def to_bam(in_file, out_file, data):
"""Convert CRAM file into BAM.
"""
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ["samtools", "view", "-O", "BAM", "-o", tx_out_file, in_file]
do.run(cmd, "Convert CRAM to BAM")
bam.index(out_file, data["config"])
return out_file | python | def to_bam(in_file, out_file, data):
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ["samtools", "view", "-O", "BAM", "-o", tx_out_file, in_file]
do.run(cmd, "Convert CRAM to BAM")
bam.index(out_file, data["config"])
return out_file | [
"def",
"to_bam",
"(",
"in_file",
",",
"out_file",
",",
"data",
")",
":",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"in_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"cmd"... | Convert CRAM file into BAM. | [
"Convert",
"CRAM",
"file",
"into",
"BAM",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/cram.py#L66-L74 |
237,329 | bcbio/bcbio-nextgen | bcbio/distributed/prun.py | start | def start(parallel, items, config, dirs=None, name=None, multiplier=1,
max_multicore=None):
"""Start a parallel cluster or machines to be used for running remote
functions.
Returns a function used to process, in parallel items with a given function.
Allows sharing of a single cluster across multiple functions with
identical resource requirements. Uses local execution for non-distributed
clusters or completed jobs.
A checkpoint directory keeps track of finished tasks, avoiding spinning up
clusters for sections that have been previous processed.
multiplier - Number of expected jobs per initial input item. Used to avoid
underscheduling cores when an item is split during processing.
max_multicore -- The maximum number of cores to use for each process. Can be
used to process less multicore usage when jobs run faster on more single
cores.
"""
if name:
checkpoint_dir = utils.safe_makedir(os.path.join(dirs["work"],
"checkpoints_parallel"))
checkpoint_file = os.path.join(checkpoint_dir, "%s.done" % name)
else:
checkpoint_file = None
sysinfo = system.get_info(dirs, parallel, config.get("resources", {}))
items = [x for x in items if x is not None] if items else []
max_multicore = int(max_multicore or sysinfo.get("cores", 1))
parallel = resources.calculate(parallel, items, sysinfo, config,
multiplier=multiplier,
max_multicore=max_multicore)
try:
view = None
if parallel["type"] == "ipython":
if checkpoint_file and os.path.exists(checkpoint_file):
logger.info("Running locally instead of distributed -- checkpoint passed: %s" % name)
parallel["cores_per_job"] = 1
parallel["num_jobs"] = 1
parallel["checkpointed"] = True
yield multi.runner(parallel, config)
else:
from bcbio.distributed import ipython
with ipython.create(parallel, dirs, config) as view:
yield ipython.runner(view, parallel, dirs, config)
else:
yield multi.runner(parallel, config)
except:
if view is not None:
from bcbio.distributed import ipython
ipython.stop(view)
raise
else:
for x in ["cores_per_job", "num_jobs", "mem"]:
parallel.pop(x, None)
if checkpoint_file:
with open(checkpoint_file, "w") as out_handle:
out_handle.write("done\n") | python | def start(parallel, items, config, dirs=None, name=None, multiplier=1,
max_multicore=None):
if name:
checkpoint_dir = utils.safe_makedir(os.path.join(dirs["work"],
"checkpoints_parallel"))
checkpoint_file = os.path.join(checkpoint_dir, "%s.done" % name)
else:
checkpoint_file = None
sysinfo = system.get_info(dirs, parallel, config.get("resources", {}))
items = [x for x in items if x is not None] if items else []
max_multicore = int(max_multicore or sysinfo.get("cores", 1))
parallel = resources.calculate(parallel, items, sysinfo, config,
multiplier=multiplier,
max_multicore=max_multicore)
try:
view = None
if parallel["type"] == "ipython":
if checkpoint_file and os.path.exists(checkpoint_file):
logger.info("Running locally instead of distributed -- checkpoint passed: %s" % name)
parallel["cores_per_job"] = 1
parallel["num_jobs"] = 1
parallel["checkpointed"] = True
yield multi.runner(parallel, config)
else:
from bcbio.distributed import ipython
with ipython.create(parallel, dirs, config) as view:
yield ipython.runner(view, parallel, dirs, config)
else:
yield multi.runner(parallel, config)
except:
if view is not None:
from bcbio.distributed import ipython
ipython.stop(view)
raise
else:
for x in ["cores_per_job", "num_jobs", "mem"]:
parallel.pop(x, None)
if checkpoint_file:
with open(checkpoint_file, "w") as out_handle:
out_handle.write("done\n") | [
"def",
"start",
"(",
"parallel",
",",
"items",
",",
"config",
",",
"dirs",
"=",
"None",
",",
"name",
"=",
"None",
",",
"multiplier",
"=",
"1",
",",
"max_multicore",
"=",
"None",
")",
":",
"if",
"name",
":",
"checkpoint_dir",
"=",
"utils",
".",
"safe_... | Start a parallel cluster or machines to be used for running remote
functions.
Returns a function used to process, in parallel items with a given function.
Allows sharing of a single cluster across multiple functions with
identical resource requirements. Uses local execution for non-distributed
clusters or completed jobs.
A checkpoint directory keeps track of finished tasks, avoiding spinning up
clusters for sections that have been previous processed.
multiplier - Number of expected jobs per initial input item. Used to avoid
underscheduling cores when an item is split during processing.
max_multicore -- The maximum number of cores to use for each process. Can be
used to process less multicore usage when jobs run faster on more single
cores. | [
"Start",
"a",
"parallel",
"cluster",
"or",
"machines",
"to",
"be",
"used",
"for",
"running",
"remote",
"functions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/prun.py#L12-L69 |
237,330 | bcbio/bcbio-nextgen | scripts/utils/broad_redo_analysis.py | recalibrate_quality | def recalibrate_quality(bam_file, sam_ref, dbsnp_file, picard_dir):
"""Recalibrate alignments with GATK and provide pdf summary.
"""
cl = ["picard_gatk_recalibrate.py", picard_dir, sam_ref, bam_file]
if dbsnp_file:
cl.append(dbsnp_file)
subprocess.check_call(cl)
out_file = glob.glob("%s*gatkrecal.bam" % os.path.splitext(bam_file)[0])[0]
return out_file | python | def recalibrate_quality(bam_file, sam_ref, dbsnp_file, picard_dir):
cl = ["picard_gatk_recalibrate.py", picard_dir, sam_ref, bam_file]
if dbsnp_file:
cl.append(dbsnp_file)
subprocess.check_call(cl)
out_file = glob.glob("%s*gatkrecal.bam" % os.path.splitext(bam_file)[0])[0]
return out_file | [
"def",
"recalibrate_quality",
"(",
"bam_file",
",",
"sam_ref",
",",
"dbsnp_file",
",",
"picard_dir",
")",
":",
"cl",
"=",
"[",
"\"picard_gatk_recalibrate.py\"",
",",
"picard_dir",
",",
"sam_ref",
",",
"bam_file",
"]",
"if",
"dbsnp_file",
":",
"cl",
".",
"appen... | Recalibrate alignments with GATK and provide pdf summary. | [
"Recalibrate",
"alignments",
"with",
"GATK",
"and",
"provide",
"pdf",
"summary",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/broad_redo_analysis.py#L98-L106 |
237,331 | bcbio/bcbio-nextgen | scripts/utils/broad_redo_analysis.py | run_genotyper | def run_genotyper(bam_file, ref_file, dbsnp_file, config_file):
"""Perform SNP genotyping and analysis using GATK.
"""
cl = ["gatk_genotyper.py", config_file, ref_file, bam_file]
if dbsnp_file:
cl.append(dbsnp_file)
subprocess.check_call(cl) | python | def run_genotyper(bam_file, ref_file, dbsnp_file, config_file):
cl = ["gatk_genotyper.py", config_file, ref_file, bam_file]
if dbsnp_file:
cl.append(dbsnp_file)
subprocess.check_call(cl) | [
"def",
"run_genotyper",
"(",
"bam_file",
",",
"ref_file",
",",
"dbsnp_file",
",",
"config_file",
")",
":",
"cl",
"=",
"[",
"\"gatk_genotyper.py\"",
",",
"config_file",
",",
"ref_file",
",",
"bam_file",
"]",
"if",
"dbsnp_file",
":",
"cl",
".",
"append",
"(",
... | Perform SNP genotyping and analysis using GATK. | [
"Perform",
"SNP",
"genotyping",
"and",
"analysis",
"using",
"GATK",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/broad_redo_analysis.py#L108-L114 |
237,332 | bcbio/bcbio-nextgen | bcbio/structural/battenberg.py | _do_run | def _do_run(paired):
"""Perform Battenberg caling with the paired dataset.
This purposely does not use a temporary directory for the output
since Battenberg does smart restarts.
"""
work_dir = _sv_workdir(paired.tumor_data)
out = _get_battenberg_out(paired, work_dir)
ignore_file = os.path.join(work_dir, "ignore_chromosomes.txt")
if len(_missing_files(out)) > 0:
ref_file = dd.get_ref_file(paired.tumor_data)
bat_datadir = os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir, "battenberg"))
ignore_file, gl_file = _make_ignore_file(work_dir, ref_file, ignore_file,
os.path.join(bat_datadir, "impute", "impute_info.txt"))
tumor_bam = paired.tumor_bam
normal_bam = paired.normal_bam
platform = dd.get_platform(paired.tumor_data)
genome_build = paired.tumor_data["genome_build"]
# scale cores to avoid over-using memory during imputation
cores = max(1, int(dd.get_num_cores(paired.tumor_data) * 0.5))
gender = {"male": "XY", "female": "XX", "unknown": "L"}.get(population.get_gender(paired.tumor_data))
if gender == "L":
gender_str = "-ge %s -gl %s" % (gender, gl_file)
else:
gender_str = "-ge %s" % (gender)
r_export_cmd = utils.get_R_exports()
local_sitelib = utils.R_sitelib()
cmd = ("export R_LIBS_USER={local_sitelib} && {r_export_cmd} && "
"battenberg.pl -t {cores} -o {work_dir} -r {ref_file}.fai "
"-tb {tumor_bam} -nb {normal_bam} -e {bat_datadir}/impute/impute_info.txt "
"-u {bat_datadir}/1000genomesloci -c {bat_datadir}/probloci.txt "
"-ig {ignore_file} {gender_str} "
"-assembly {genome_build} -species Human -platform {platform}")
do.run(cmd.format(**locals()), "Battenberg CNV calling")
assert len(_missing_files(out)) == 0, "Missing Battenberg output: %s" % _missing_files(out)
out["plot"] = _get_battenberg_out_plots(paired, work_dir)
out["ignore"] = ignore_file
return out | python | def _do_run(paired):
work_dir = _sv_workdir(paired.tumor_data)
out = _get_battenberg_out(paired, work_dir)
ignore_file = os.path.join(work_dir, "ignore_chromosomes.txt")
if len(_missing_files(out)) > 0:
ref_file = dd.get_ref_file(paired.tumor_data)
bat_datadir = os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir, "battenberg"))
ignore_file, gl_file = _make_ignore_file(work_dir, ref_file, ignore_file,
os.path.join(bat_datadir, "impute", "impute_info.txt"))
tumor_bam = paired.tumor_bam
normal_bam = paired.normal_bam
platform = dd.get_platform(paired.tumor_data)
genome_build = paired.tumor_data["genome_build"]
# scale cores to avoid over-using memory during imputation
cores = max(1, int(dd.get_num_cores(paired.tumor_data) * 0.5))
gender = {"male": "XY", "female": "XX", "unknown": "L"}.get(population.get_gender(paired.tumor_data))
if gender == "L":
gender_str = "-ge %s -gl %s" % (gender, gl_file)
else:
gender_str = "-ge %s" % (gender)
r_export_cmd = utils.get_R_exports()
local_sitelib = utils.R_sitelib()
cmd = ("export R_LIBS_USER={local_sitelib} && {r_export_cmd} && "
"battenberg.pl -t {cores} -o {work_dir} -r {ref_file}.fai "
"-tb {tumor_bam} -nb {normal_bam} -e {bat_datadir}/impute/impute_info.txt "
"-u {bat_datadir}/1000genomesloci -c {bat_datadir}/probloci.txt "
"-ig {ignore_file} {gender_str} "
"-assembly {genome_build} -species Human -platform {platform}")
do.run(cmd.format(**locals()), "Battenberg CNV calling")
assert len(_missing_files(out)) == 0, "Missing Battenberg output: %s" % _missing_files(out)
out["plot"] = _get_battenberg_out_plots(paired, work_dir)
out["ignore"] = ignore_file
return out | [
"def",
"_do_run",
"(",
"paired",
")",
":",
"work_dir",
"=",
"_sv_workdir",
"(",
"paired",
".",
"tumor_data",
")",
"out",
"=",
"_get_battenberg_out",
"(",
"paired",
",",
"work_dir",
")",
"ignore_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
... | Perform Battenberg caling with the paired dataset.
This purposely does not use a temporary directory for the output
since Battenberg does smart restarts. | [
"Perform",
"Battenberg",
"caling",
"with",
"the",
"paired",
"dataset",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/battenberg.py#L40-L77 |
237,333 | bcbio/bcbio-nextgen | bcbio/structural/battenberg.py | _make_ignore_file | def _make_ignore_file(work_dir, ref_file, ignore_file, impute_file):
"""Create input files with chromosomes to ignore and gender loci.
"""
gl_file = os.path.join(work_dir, "gender_loci.txt")
chroms = set([])
with open(impute_file) as in_handle:
for line in in_handle:
chrom = line.split()[0]
chroms.add(chrom)
if not chrom.startswith("chr"):
chroms.add("chr%s" % chrom)
with open(ignore_file, "w") as out_handle:
for contig in ref.file_contigs(ref_file):
if contig.name not in chroms:
out_handle.write("%s\n" % contig.name)
with open(gl_file, "w") as out_handle:
for contig in ref.file_contigs(ref_file):
if contig.name in ["Y", "chrY"]:
# From https://github.com/cancerit/cgpBattenberg/blob/dev/perl/share/gender/GRCh37d5_Y.loci
positions = [2934912, 4546684, 4549638, 4550107]
for pos in positions:
out_handle.write("%s\t%s\n" % (contig.name, pos))
return ignore_file, gl_file | python | def _make_ignore_file(work_dir, ref_file, ignore_file, impute_file):
gl_file = os.path.join(work_dir, "gender_loci.txt")
chroms = set([])
with open(impute_file) as in_handle:
for line in in_handle:
chrom = line.split()[0]
chroms.add(chrom)
if not chrom.startswith("chr"):
chroms.add("chr%s" % chrom)
with open(ignore_file, "w") as out_handle:
for contig in ref.file_contigs(ref_file):
if contig.name not in chroms:
out_handle.write("%s\n" % contig.name)
with open(gl_file, "w") as out_handle:
for contig in ref.file_contigs(ref_file):
if contig.name in ["Y", "chrY"]:
# From https://github.com/cancerit/cgpBattenberg/blob/dev/perl/share/gender/GRCh37d5_Y.loci
positions = [2934912, 4546684, 4549638, 4550107]
for pos in positions:
out_handle.write("%s\t%s\n" % (contig.name, pos))
return ignore_file, gl_file | [
"def",
"_make_ignore_file",
"(",
"work_dir",
",",
"ref_file",
",",
"ignore_file",
",",
"impute_file",
")",
":",
"gl_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"gender_loci.txt\"",
")",
"chroms",
"=",
"set",
"(",
"[",
"]",
")",
"w... | Create input files with chromosomes to ignore and gender loci. | [
"Create",
"input",
"files",
"with",
"chromosomes",
"to",
"ignore",
"and",
"gender",
"loci",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/battenberg.py#L79-L101 |
237,334 | bcbio/bcbio-nextgen | bcbio/illumina/transfer.py | copy_flowcell | def copy_flowcell(dname, fastq_dir, sample_cfile, config):
"""Copy required files for processing using rsync, potentially to a remote server.
"""
with utils.chdir(dname):
reports = reduce(operator.add,
[glob.glob("*.xml"),
glob.glob("Data/Intensities/BaseCalls/*.xml"),
glob.glob("Data/Intensities/BaseCalls/*.xsl"),
glob.glob("Data/Intensities/BaseCalls/*.htm"),
["Data/Intensities/BaseCalls/Plots", "Data/reports",
"Data/Status.htm", "Data/Status_Files", "InterOp"]])
run_info = reduce(operator.add,
[glob.glob("run_info.yaml"),
glob.glob("*.csv")])
fastq = glob.glob(os.path.join(fastq_dir.replace(dname + "/", "", 1),
"*.gz"))
configs = [sample_cfile.replace(dname + "/", "", 1)]
include_file = os.path.join(dname, "transfer_files.txt")
with open(include_file, "w") as out_handle:
out_handle.write("+ */\n")
for fname in configs + fastq + run_info + reports:
out_handle.write("+ %s\n" % fname)
out_handle.write("- *\n")
# remote transfer
if utils.get_in(config, ("process", "host")):
dest = "%s@%s:%s" % (utils.get_in(config, ("process", "username")),
utils.get_in(config, ("process", "host")),
utils.get_in(config, ("process", "dir")))
# local transfer
else:
dest = utils.get_in(config, ("process", "dir"))
cmd = ["rsync", "-akmrtv", "--include-from=%s" % include_file, dname, dest]
logger.info("Copying files to analysis machine")
logger.info(" ".join(cmd))
subprocess.check_call(cmd) | python | def copy_flowcell(dname, fastq_dir, sample_cfile, config):
with utils.chdir(dname):
reports = reduce(operator.add,
[glob.glob("*.xml"),
glob.glob("Data/Intensities/BaseCalls/*.xml"),
glob.glob("Data/Intensities/BaseCalls/*.xsl"),
glob.glob("Data/Intensities/BaseCalls/*.htm"),
["Data/Intensities/BaseCalls/Plots", "Data/reports",
"Data/Status.htm", "Data/Status_Files", "InterOp"]])
run_info = reduce(operator.add,
[glob.glob("run_info.yaml"),
glob.glob("*.csv")])
fastq = glob.glob(os.path.join(fastq_dir.replace(dname + "/", "", 1),
"*.gz"))
configs = [sample_cfile.replace(dname + "/", "", 1)]
include_file = os.path.join(dname, "transfer_files.txt")
with open(include_file, "w") as out_handle:
out_handle.write("+ */\n")
for fname in configs + fastq + run_info + reports:
out_handle.write("+ %s\n" % fname)
out_handle.write("- *\n")
# remote transfer
if utils.get_in(config, ("process", "host")):
dest = "%s@%s:%s" % (utils.get_in(config, ("process", "username")),
utils.get_in(config, ("process", "host")),
utils.get_in(config, ("process", "dir")))
# local transfer
else:
dest = utils.get_in(config, ("process", "dir"))
cmd = ["rsync", "-akmrtv", "--include-from=%s" % include_file, dname, dest]
logger.info("Copying files to analysis machine")
logger.info(" ".join(cmd))
subprocess.check_call(cmd) | [
"def",
"copy_flowcell",
"(",
"dname",
",",
"fastq_dir",
",",
"sample_cfile",
",",
"config",
")",
":",
"with",
"utils",
".",
"chdir",
"(",
"dname",
")",
":",
"reports",
"=",
"reduce",
"(",
"operator",
".",
"add",
",",
"[",
"glob",
".",
"glob",
"(",
"\... | Copy required files for processing using rsync, potentially to a remote server. | [
"Copy",
"required",
"files",
"for",
"processing",
"using",
"rsync",
"potentially",
"to",
"a",
"remote",
"server",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/transfer.py#L12-L46 |
237,335 | bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | _umis_cmd | def _umis_cmd(data):
"""Return umis command line argument, with correct python and locale.
"""
return "%s %s %s" % (utils.locale_export(),
utils.get_program_python("umis"),
config_utils.get_program("umis", data["config"], default="umis")) | python | def _umis_cmd(data):
return "%s %s %s" % (utils.locale_export(),
utils.get_program_python("umis"),
config_utils.get_program("umis", data["config"], default="umis")) | [
"def",
"_umis_cmd",
"(",
"data",
")",
":",
"return",
"\"%s %s %s\"",
"%",
"(",
"utils",
".",
"locale_export",
"(",
")",
",",
"utils",
".",
"get_program_python",
"(",
"\"umis\"",
")",
",",
"config_utils",
".",
"get_program",
"(",
"\"umis\"",
",",
"data",
"[... | Return umis command line argument, with correct python and locale. | [
"Return",
"umis",
"command",
"line",
"argument",
"with",
"correct",
"python",
"and",
"locale",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L119-L124 |
237,336 | bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | demultiplex_samples | def demultiplex_samples(data):
"""
demultiplex a fastqtransformed FASTQ file into separate sample barcode files
"""
work_dir = os.path.join(dd.get_work_dir(data), "umis")
sample_dir = os.path.join(work_dir, dd.get_sample_name(data))
demulti_dir = os.path.join(sample_dir, "demultiplexed")
files = data["files"]
if len(files) == 2:
logger.error("Sample demultiplexing doesn't handle paired-end reads, but "
"we can add it. Open an issue here https://github.com/bcbio/bcbio-nextgen/issues if you need this and we'll add it.")
sys.exit(1)
else:
fq1 = files[0]
# check if samples need to be demultiplexed
with open_fastq(fq1) as in_handle:
read = next(in_handle)
if "SAMPLE_" not in read:
return [[data]]
bcfile = get_sample_barcodes(dd.get_sample_barcodes(data), sample_dir)
demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*"))
if demultiplexed:
return [split_demultiplexed_sampledata(data, demultiplexed)]
umis = _umis_cmd(data)
cmd = ("{umis} demultiplex_samples --nedit 1 --barcodes {bcfile} "
"--out_dir {tx_dir} {fq1}")
msg = "Demultiplexing {fq1}."
with file_transaction(data, demulti_dir) as tx_dir:
do.run(cmd.format(**locals()), msg.format(**locals()))
demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*"))
return [split_demultiplexed_sampledata(data, demultiplexed)] | python | def demultiplex_samples(data):
work_dir = os.path.join(dd.get_work_dir(data), "umis")
sample_dir = os.path.join(work_dir, dd.get_sample_name(data))
demulti_dir = os.path.join(sample_dir, "demultiplexed")
files = data["files"]
if len(files) == 2:
logger.error("Sample demultiplexing doesn't handle paired-end reads, but "
"we can add it. Open an issue here https://github.com/bcbio/bcbio-nextgen/issues if you need this and we'll add it.")
sys.exit(1)
else:
fq1 = files[0]
# check if samples need to be demultiplexed
with open_fastq(fq1) as in_handle:
read = next(in_handle)
if "SAMPLE_" not in read:
return [[data]]
bcfile = get_sample_barcodes(dd.get_sample_barcodes(data), sample_dir)
demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*"))
if demultiplexed:
return [split_demultiplexed_sampledata(data, demultiplexed)]
umis = _umis_cmd(data)
cmd = ("{umis} demultiplex_samples --nedit 1 --barcodes {bcfile} "
"--out_dir {tx_dir} {fq1}")
msg = "Demultiplexing {fq1}."
with file_transaction(data, demulti_dir) as tx_dir:
do.run(cmd.format(**locals()), msg.format(**locals()))
demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*"))
return [split_demultiplexed_sampledata(data, demultiplexed)] | [
"def",
"demultiplex_samples",
"(",
"data",
")",
":",
"work_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",
",",
"\"umis\"",
")",
"sample_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"dd... | demultiplex a fastqtransformed FASTQ file into separate sample barcode files | [
"demultiplex",
"a",
"fastqtransformed",
"FASTQ",
"file",
"into",
"separate",
"sample",
"barcode",
"files"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L359-L391 |
237,337 | bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | split_demultiplexed_sampledata | def split_demultiplexed_sampledata(data, demultiplexed):
"""
splits demultiplexed samples into separate entries in the global sample
datadict
"""
datadicts = []
samplename = dd.get_sample_name(data)
for fastq in demultiplexed:
barcode = os.path.basename(fastq).split(".")[0]
datadict = copy.deepcopy(data)
datadict = dd.set_sample_name(datadict, samplename + "-" + barcode)
datadict = dd.set_description(datadict, samplename + "-" + barcode)
datadict["rgnames"]["rg"] = samplename + "-" + barcode
datadict["name"]= ["", samplename + "-" + barcode]
datadict["files"] = [fastq]
datadicts.append(datadict)
return datadicts | python | def split_demultiplexed_sampledata(data, demultiplexed):
datadicts = []
samplename = dd.get_sample_name(data)
for fastq in demultiplexed:
barcode = os.path.basename(fastq).split(".")[0]
datadict = copy.deepcopy(data)
datadict = dd.set_sample_name(datadict, samplename + "-" + barcode)
datadict = dd.set_description(datadict, samplename + "-" + barcode)
datadict["rgnames"]["rg"] = samplename + "-" + barcode
datadict["name"]= ["", samplename + "-" + barcode]
datadict["files"] = [fastq]
datadicts.append(datadict)
return datadicts | [
"def",
"split_demultiplexed_sampledata",
"(",
"data",
",",
"demultiplexed",
")",
":",
"datadicts",
"=",
"[",
"]",
"samplename",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"for",
"fastq",
"in",
"demultiplexed",
":",
"barcode",
"=",
"os",
".",
"path"... | splits demultiplexed samples into separate entries in the global sample
datadict | [
"splits",
"demultiplexed",
"samples",
"into",
"separate",
"entries",
"in",
"the",
"global",
"sample",
"datadict"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L393-L409 |
237,338 | bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | is_transformed | def is_transformed(fastq):
"""
check the first 100 reads to see if a FASTQ file has already been transformed
by umis
"""
with open_fastq(fastq) as in_handle:
for line in islice(in_handle, 400):
if "UMI_" in line:
return True
return False | python | def is_transformed(fastq):
with open_fastq(fastq) as in_handle:
for line in islice(in_handle, 400):
if "UMI_" in line:
return True
return False | [
"def",
"is_transformed",
"(",
"fastq",
")",
":",
"with",
"open_fastq",
"(",
"fastq",
")",
"as",
"in_handle",
":",
"for",
"line",
"in",
"islice",
"(",
"in_handle",
",",
"400",
")",
":",
"if",
"\"UMI_\"",
"in",
"line",
":",
"return",
"True",
"return",
"F... | check the first 100 reads to see if a FASTQ file has already been transformed
by umis | [
"check",
"the",
"first",
"100",
"reads",
"to",
"see",
"if",
"a",
"FASTQ",
"file",
"has",
"already",
"been",
"transformed",
"by",
"umis"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L504-L514 |
237,339 | bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | SparseMatrix.read | def read(self, filename, rowprefix=None, colprefix=None, delim=":"):
"""read a sparse matrix, loading row and column name files. if
specified, will add a prefix to the row or column names"""
self.matrix = scipy.io.mmread(filename)
with open(filename + ".rownames") as in_handle:
self.rownames = [x.strip() for x in in_handle]
if rowprefix:
self.rownames = [rowprefix + delim + x for x in self.rownames]
with open(filename + ".colnames") as in_handle:
self.colnames = [x.strip() for x in in_handle]
if colprefix:
self.colnames = [colprefix + delim + x for x in self.colnames] | python | def read(self, filename, rowprefix=None, colprefix=None, delim=":"):
self.matrix = scipy.io.mmread(filename)
with open(filename + ".rownames") as in_handle:
self.rownames = [x.strip() for x in in_handle]
if rowprefix:
self.rownames = [rowprefix + delim + x for x in self.rownames]
with open(filename + ".colnames") as in_handle:
self.colnames = [x.strip() for x in in_handle]
if colprefix:
self.colnames = [colprefix + delim + x for x in self.colnames] | [
"def",
"read",
"(",
"self",
",",
"filename",
",",
"rowprefix",
"=",
"None",
",",
"colprefix",
"=",
"None",
",",
"delim",
"=",
"\":\"",
")",
":",
"self",
".",
"matrix",
"=",
"scipy",
".",
"io",
".",
"mmread",
"(",
"filename",
")",
"with",
"open",
"(... | read a sparse matrix, loading row and column name files. if
specified, will add a prefix to the row or column names | [
"read",
"a",
"sparse",
"matrix",
"loading",
"row",
"and",
"column",
"name",
"files",
".",
"if",
"specified",
"will",
"add",
"a",
"prefix",
"to",
"the",
"row",
"or",
"column",
"names"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L42-L54 |
237,340 | bcbio/bcbio-nextgen | bcbio/rnaseq/umi.py | SparseMatrix.write | def write(self, filename):
"""read a sparse matrix, loading row and column name files"""
if file_exists(filename):
return filename
out_files = [filename, filename + ".rownames", filename + ".colnames"]
with file_transaction(out_files) as tx_out_files:
with open(tx_out_files[0], "wb") as out_handle:
scipy.io.mmwrite(out_handle, scipy.sparse.csr_matrix(self.matrix))
pd.Series(self.rownames).to_csv(tx_out_files[1], index=False)
pd.Series(self.colnames).to_csv(tx_out_files[2], index=False)
return filename | python | def write(self, filename):
if file_exists(filename):
return filename
out_files = [filename, filename + ".rownames", filename + ".colnames"]
with file_transaction(out_files) as tx_out_files:
with open(tx_out_files[0], "wb") as out_handle:
scipy.io.mmwrite(out_handle, scipy.sparse.csr_matrix(self.matrix))
pd.Series(self.rownames).to_csv(tx_out_files[1], index=False)
pd.Series(self.colnames).to_csv(tx_out_files[2], index=False)
return filename | [
"def",
"write",
"(",
"self",
",",
"filename",
")",
":",
"if",
"file_exists",
"(",
"filename",
")",
":",
"return",
"filename",
"out_files",
"=",
"[",
"filename",
",",
"filename",
"+",
"\".rownames\"",
",",
"filename",
"+",
"\".colnames\"",
"]",
"with",
"fil... | read a sparse matrix, loading row and column name files | [
"read",
"a",
"sparse",
"matrix",
"loading",
"row",
"and",
"column",
"name",
"files"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L56-L66 |
237,341 | bcbio/bcbio-nextgen | bcbio/srna/sample.py | sample_annotation | def sample_annotation(data):
"""
Annotate miRNAs using miRBase database with seqbuster tool
"""
names = data["rgnames"]['sample']
tools = dd.get_expression_caller(data)
work_dir = os.path.join(dd.get_work_dir(data), "mirbase")
out_dir = os.path.join(work_dir, names)
utils.safe_makedir(out_dir)
out_file = op.join(out_dir, names)
if dd.get_mirbase_hairpin(data):
mirbase = op.abspath(op.dirname(dd.get_mirbase_hairpin(data)))
if utils.file_exists(data["collapse"]):
data['transcriptome_bam'] = _align(data["collapse"],
dd.get_mirbase_hairpin(data),
out_file,
data)
data['seqbuster'] = _miraligner(data["collapse"], out_file,
dd.get_species(data),
mirbase,
data['config'])
data["mirtop"] = _mirtop(data['seqbuster'],
dd.get_species(data),
mirbase,
out_dir,
data['config'])
else:
logger.debug("Trimmed collapsed file is empty for %s." % names)
else:
logger.debug("No annotation file from miRBase.")
sps = dd.get_species(data) if dd.get_species(data) else "None"
logger.debug("Looking for mirdeep2 database for %s" % names)
if file_exists(op.join(dd.get_work_dir(data), "mirdeep2", "novel", "hairpin.fa")):
data['seqbuster_novel'] = _miraligner(data["collapse"], "%s_novel" % out_file, sps,
op.join(dd.get_work_dir(data),
"mirdeep2", "novel"),
data['config'])
if "trna" in tools:
data['trna'] = _mint_trna_annotation(data)
data = spikein.counts_spikein(data)
return [[data]] | python | def sample_annotation(data):
names = data["rgnames"]['sample']
tools = dd.get_expression_caller(data)
work_dir = os.path.join(dd.get_work_dir(data), "mirbase")
out_dir = os.path.join(work_dir, names)
utils.safe_makedir(out_dir)
out_file = op.join(out_dir, names)
if dd.get_mirbase_hairpin(data):
mirbase = op.abspath(op.dirname(dd.get_mirbase_hairpin(data)))
if utils.file_exists(data["collapse"]):
data['transcriptome_bam'] = _align(data["collapse"],
dd.get_mirbase_hairpin(data),
out_file,
data)
data['seqbuster'] = _miraligner(data["collapse"], out_file,
dd.get_species(data),
mirbase,
data['config'])
data["mirtop"] = _mirtop(data['seqbuster'],
dd.get_species(data),
mirbase,
out_dir,
data['config'])
else:
logger.debug("Trimmed collapsed file is empty for %s." % names)
else:
logger.debug("No annotation file from miRBase.")
sps = dd.get_species(data) if dd.get_species(data) else "None"
logger.debug("Looking for mirdeep2 database for %s" % names)
if file_exists(op.join(dd.get_work_dir(data), "mirdeep2", "novel", "hairpin.fa")):
data['seqbuster_novel'] = _miraligner(data["collapse"], "%s_novel" % out_file, sps,
op.join(dd.get_work_dir(data),
"mirdeep2", "novel"),
data['config'])
if "trna" in tools:
data['trna'] = _mint_trna_annotation(data)
data = spikein.counts_spikein(data)
return [[data]] | [
"def",
"sample_annotation",
"(",
"data",
")",
":",
"names",
"=",
"data",
"[",
"\"rgnames\"",
"]",
"[",
"'sample'",
"]",
"tools",
"=",
"dd",
".",
"get_expression_caller",
"(",
"data",
")",
"work_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",... | Annotate miRNAs using miRBase database with seqbuster tool | [
"Annotate",
"miRNAs",
"using",
"miRBase",
"database",
"with",
"seqbuster",
"tool"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L106-L149 |
237,342 | bcbio/bcbio-nextgen | bcbio/srna/sample.py | _prepare_file | def _prepare_file(fn, out_dir):
"""Cut the beginning of the reads to avoid detection of miRNAs"""
atropos = _get_atropos()
cmd = "{atropos} trim --max-reads 500000 -u 22 -se {fn} -o {tx_file}"
out_file = os.path.join(out_dir, append_stem(os.path.basename(fn), "end"))
if file_exists(out_file):
return out_file
with file_transaction(out_file) as tx_file:
do.run(cmd.format(**locals()))
return out_file | python | def _prepare_file(fn, out_dir):
atropos = _get_atropos()
cmd = "{atropos} trim --max-reads 500000 -u 22 -se {fn} -o {tx_file}"
out_file = os.path.join(out_dir, append_stem(os.path.basename(fn), "end"))
if file_exists(out_file):
return out_file
with file_transaction(out_file) as tx_file:
do.run(cmd.format(**locals()))
return out_file | [
"def",
"_prepare_file",
"(",
"fn",
",",
"out_dir",
")",
":",
"atropos",
"=",
"_get_atropos",
"(",
")",
"cmd",
"=",
"\"{atropos} trim --max-reads 500000 -u 22 -se {fn} -o {tx_file}\"",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"append_st... | Cut the beginning of the reads to avoid detection of miRNAs | [
"Cut",
"the",
"beginning",
"of",
"the",
"reads",
"to",
"avoid",
"detection",
"of",
"miRNAs"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L151-L160 |
237,343 | bcbio/bcbio-nextgen | bcbio/srna/sample.py | _collapse | def _collapse(in_file):
"""
Collpase reads into unique sequences with seqcluster
"""
seqcluster = op.join(utils.get_bcbio_bin(), "seqcluster")
out_file = "%s.fastq" % utils.splitext_plus(append_stem(in_file, "_trimmed"))[0]
out_dir = os.path.dirname(in_file)
if file_exists(out_file):
return out_file
cmd = ("{seqcluster} collapse -o {out_dir} -f {in_file} -m 1 --min_size 16")
do.run(cmd.format(**locals()), "Running seqcluster collapse in %s." % in_file)
return out_file | python | def _collapse(in_file):
seqcluster = op.join(utils.get_bcbio_bin(), "seqcluster")
out_file = "%s.fastq" % utils.splitext_plus(append_stem(in_file, "_trimmed"))[0]
out_dir = os.path.dirname(in_file)
if file_exists(out_file):
return out_file
cmd = ("{seqcluster} collapse -o {out_dir} -f {in_file} -m 1 --min_size 16")
do.run(cmd.format(**locals()), "Running seqcluster collapse in %s." % in_file)
return out_file | [
"def",
"_collapse",
"(",
"in_file",
")",
":",
"seqcluster",
"=",
"op",
".",
"join",
"(",
"utils",
".",
"get_bcbio_bin",
"(",
")",
",",
"\"seqcluster\"",
")",
"out_file",
"=",
"\"%s.fastq\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"append_stem",
"(",
"in_... | Collpase reads into unique sequences with seqcluster | [
"Collpase",
"reads",
"into",
"unique",
"sequences",
"with",
"seqcluster"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L180-L191 |
237,344 | bcbio/bcbio-nextgen | bcbio/srna/sample.py | _summary | def _summary(in_file):
"""
Calculate size distribution after adapter removal
"""
data = Counter()
out_file = in_file + "_size_stats"
if file_exists(out_file):
return out_file
with open(in_file) as in_handle:
for line in in_handle:
counts = int(line.strip().split("_x")[1])
line = next(in_handle)
l = len(line.strip())
next(in_handle)
next(in_handle)
data[l] += counts
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, 'w') as out_handle:
for l, c in data.items():
out_handle.write("%s %s\n" % (l, c))
return out_file | python | def _summary(in_file):
data = Counter()
out_file = in_file + "_size_stats"
if file_exists(out_file):
return out_file
with open(in_file) as in_handle:
for line in in_handle:
counts = int(line.strip().split("_x")[1])
line = next(in_handle)
l = len(line.strip())
next(in_handle)
next(in_handle)
data[l] += counts
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, 'w') as out_handle:
for l, c in data.items():
out_handle.write("%s %s\n" % (l, c))
return out_file | [
"def",
"_summary",
"(",
"in_file",
")",
":",
"data",
"=",
"Counter",
"(",
")",
"out_file",
"=",
"in_file",
"+",
"\"_size_stats\"",
"if",
"file_exists",
"(",
"out_file",
")",
":",
"return",
"out_file",
"with",
"open",
"(",
"in_file",
")",
"as",
"in_handle",... | Calculate size distribution after adapter removal | [
"Calculate",
"size",
"distribution",
"after",
"adapter",
"removal"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L193-L213 |
237,345 | bcbio/bcbio-nextgen | bcbio/srna/sample.py | _mirtop | def _mirtop(input_fn, sps, db, out_dir, config):
"""
Convert to GFF3 standard format
"""
hairpin = os.path.join(db, "hairpin.fa")
gtf = os.path.join(db, "mirbase.gff3")
if not file_exists(hairpin) or not file_exists(gtf):
logger.warning("%s or %s are not installed. Skipping." % (hairpin, gtf))
return None
out_gtf_fn = "%s.gtf" % utils.splitext_plus(os.path.basename(input_fn))[0]
out_gff_fn = "%s.gff" % utils.splitext_plus(os.path.basename(input_fn))[0]
export = _get_env()
cmd = ("{export} mirtop gff --sps {sps} --hairpin {hairpin} "
"--gtf {gtf} --format seqbuster -o {out_tx} {input_fn}")
if not file_exists(os.path.join(out_dir, out_gtf_fn)) and \
not file_exists(os.path.join(out_dir, out_gff_fn)):
with tx_tmpdir() as out_tx:
do.run(cmd.format(**locals()), "Do miRNA annotation for %s" % input_fn)
with utils.chdir(out_tx):
out_fn = out_gtf_fn if utils.file_exists(out_gtf_fn) \
else out_gff_fn
if utils.file_exists(out_fn):
shutil.move(os.path.join(out_tx, out_fn),
os.path.join(out_dir, out_fn))
out_fn = out_gtf_fn if utils.file_exists(os.path.join(out_dir, out_gtf_fn)) \
else os.path.join(out_dir, out_gff_fn)
if utils.file_exists(os.path.join(out_dir, out_fn)):
return os.path.join(out_dir, out_fn) | python | def _mirtop(input_fn, sps, db, out_dir, config):
hairpin = os.path.join(db, "hairpin.fa")
gtf = os.path.join(db, "mirbase.gff3")
if not file_exists(hairpin) or not file_exists(gtf):
logger.warning("%s or %s are not installed. Skipping." % (hairpin, gtf))
return None
out_gtf_fn = "%s.gtf" % utils.splitext_plus(os.path.basename(input_fn))[0]
out_gff_fn = "%s.gff" % utils.splitext_plus(os.path.basename(input_fn))[0]
export = _get_env()
cmd = ("{export} mirtop gff --sps {sps} --hairpin {hairpin} "
"--gtf {gtf} --format seqbuster -o {out_tx} {input_fn}")
if not file_exists(os.path.join(out_dir, out_gtf_fn)) and \
not file_exists(os.path.join(out_dir, out_gff_fn)):
with tx_tmpdir() as out_tx:
do.run(cmd.format(**locals()), "Do miRNA annotation for %s" % input_fn)
with utils.chdir(out_tx):
out_fn = out_gtf_fn if utils.file_exists(out_gtf_fn) \
else out_gff_fn
if utils.file_exists(out_fn):
shutil.move(os.path.join(out_tx, out_fn),
os.path.join(out_dir, out_fn))
out_fn = out_gtf_fn if utils.file_exists(os.path.join(out_dir, out_gtf_fn)) \
else os.path.join(out_dir, out_gff_fn)
if utils.file_exists(os.path.join(out_dir, out_fn)):
return os.path.join(out_dir, out_fn) | [
"def",
"_mirtop",
"(",
"input_fn",
",",
"sps",
",",
"db",
",",
"out_dir",
",",
"config",
")",
":",
"hairpin",
"=",
"os",
".",
"path",
".",
"join",
"(",
"db",
",",
"\"hairpin.fa\"",
")",
"gtf",
"=",
"os",
".",
"path",
".",
"join",
"(",
"db",
",",
... | Convert to GFF3 standard format | [
"Convert",
"to",
"GFF3",
"standard",
"format"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L254-L281 |
237,346 | bcbio/bcbio-nextgen | bcbio/srna/sample.py | _trna_annotation | def _trna_annotation(data):
"""
use tDRmapper to quantify tRNAs
"""
trna_ref = op.join(dd.get_srna_trna_file(data))
name = dd.get_sample_name(data)
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna", name))
in_file = op.basename(data["clean_fastq"])
tdrmapper = os.path.join(os.path.dirname(sys.executable), "TdrMappingScripts.pl")
perl_export = utils.get_perl_exports()
if not file_exists(trna_ref) or not file_exists(tdrmapper):
logger.info("There is no tRNA annotation to run TdrMapper.")
return work_dir
out_file = op.join(work_dir, in_file + ".hq_cs.mapped")
if not file_exists(out_file):
with tx_tmpdir(data) as txdir:
with utils.chdir(txdir):
utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file))
cmd = ("{perl_export} && perl {tdrmapper} {trna_ref} {in_file}").format(**locals())
do.run(cmd, "tRNA for %s" % name)
for filename in glob.glob("*mapped*"):
shutil.move(filename, work_dir)
return work_dir | python | def _trna_annotation(data):
trna_ref = op.join(dd.get_srna_trna_file(data))
name = dd.get_sample_name(data)
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna", name))
in_file = op.basename(data["clean_fastq"])
tdrmapper = os.path.join(os.path.dirname(sys.executable), "TdrMappingScripts.pl")
perl_export = utils.get_perl_exports()
if not file_exists(trna_ref) or not file_exists(tdrmapper):
logger.info("There is no tRNA annotation to run TdrMapper.")
return work_dir
out_file = op.join(work_dir, in_file + ".hq_cs.mapped")
if not file_exists(out_file):
with tx_tmpdir(data) as txdir:
with utils.chdir(txdir):
utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file))
cmd = ("{perl_export} && perl {tdrmapper} {trna_ref} {in_file}").format(**locals())
do.run(cmd, "tRNA for %s" % name)
for filename in glob.glob("*mapped*"):
shutil.move(filename, work_dir)
return work_dir | [
"def",
"_trna_annotation",
"(",
"data",
")",
":",
"trna_ref",
"=",
"op",
".",
"join",
"(",
"dd",
".",
"get_srna_trna_file",
"(",
"data",
")",
")",
"name",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"work_dir",
"=",
"utils",
".",
"safe_makedir",... | use tDRmapper to quantify tRNAs | [
"use",
"tDRmapper",
"to",
"quantify",
"tRNAs"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L283-L305 |
237,347 | bcbio/bcbio-nextgen | bcbio/srna/sample.py | _mint_trna_annotation | def _mint_trna_annotation(data):
"""
use MINTmap to quantify tRNAs
"""
trna_lookup = op.join(dd.get_srna_mint_lookup(data))
trna_space = op.join(dd.get_srna_mint_space(data))
trna_other = op.join(dd.get_srna_mint_other(data))
name = dd.get_sample_name(data)
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna_mint", name))
in_file = op.basename(data["clean_fastq"])
mintmap = os.path.realpath(os.path.join(os.path.dirname(sys.executable), "MINTmap.pl"))
perl_export = utils.get_perl_exports()
if not file_exists(trna_lookup) or not file_exists(mintmap):
logger.info("There is no tRNA annotation to run MINTmap.")
return work_dir
jar_folder = os.path.join(os.path.dirname(mintmap), "MINTplates")
out_file = op.join(work_dir, name + "-MINTmap_v1-exclusive-tRFs.expression.txt")
if not file_exists(out_file):
with tx_tmpdir(data) as txdir:
with utils.chdir(txdir):
utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file))
cmd = ("{perl_export} && {mintmap} -f {in_file} -p {name} "
"-l {trna_lookup} -s {trna_space} -j {jar_folder} "
"-o {trna_other}").format(**locals())
do.run(cmd, "tRNA for %s" % name)
for filename in glob.glob("*MINTmap*"):
shutil.move(filename, work_dir)
return work_dir | python | def _mint_trna_annotation(data):
trna_lookup = op.join(dd.get_srna_mint_lookup(data))
trna_space = op.join(dd.get_srna_mint_space(data))
trna_other = op.join(dd.get_srna_mint_other(data))
name = dd.get_sample_name(data)
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna_mint", name))
in_file = op.basename(data["clean_fastq"])
mintmap = os.path.realpath(os.path.join(os.path.dirname(sys.executable), "MINTmap.pl"))
perl_export = utils.get_perl_exports()
if not file_exists(trna_lookup) or not file_exists(mintmap):
logger.info("There is no tRNA annotation to run MINTmap.")
return work_dir
jar_folder = os.path.join(os.path.dirname(mintmap), "MINTplates")
out_file = op.join(work_dir, name + "-MINTmap_v1-exclusive-tRFs.expression.txt")
if not file_exists(out_file):
with tx_tmpdir(data) as txdir:
with utils.chdir(txdir):
utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file))
cmd = ("{perl_export} && {mintmap} -f {in_file} -p {name} "
"-l {trna_lookup} -s {trna_space} -j {jar_folder} "
"-o {trna_other}").format(**locals())
do.run(cmd, "tRNA for %s" % name)
for filename in glob.glob("*MINTmap*"):
shutil.move(filename, work_dir)
return work_dir | [
"def",
"_mint_trna_annotation",
"(",
"data",
")",
":",
"trna_lookup",
"=",
"op",
".",
"join",
"(",
"dd",
".",
"get_srna_mint_lookup",
"(",
"data",
")",
")",
"trna_space",
"=",
"op",
".",
"join",
"(",
"dd",
".",
"get_srna_mint_space",
"(",
"data",
")",
")... | use MINTmap to quantify tRNAs | [
"use",
"MINTmap",
"to",
"quantify",
"tRNAs"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L307-L334 |
237,348 | bcbio/bcbio-nextgen | bcbio/bam/fasta.py | sequence_length | def sequence_length(fasta):
"""
return a dict of the lengths of sequences in a fasta file
"""
sequences = SeqIO.parse(fasta, "fasta")
records = {record.id: len(record) for record in sequences}
return records | python | def sequence_length(fasta):
sequences = SeqIO.parse(fasta, "fasta")
records = {record.id: len(record) for record in sequences}
return records | [
"def",
"sequence_length",
"(",
"fasta",
")",
":",
"sequences",
"=",
"SeqIO",
".",
"parse",
"(",
"fasta",
",",
"\"fasta\"",
")",
"records",
"=",
"{",
"record",
".",
"id",
":",
"len",
"(",
"record",
")",
"for",
"record",
"in",
"sequences",
"}",
"return",... | return a dict of the lengths of sequences in a fasta file | [
"return",
"a",
"dict",
"of",
"the",
"lengths",
"of",
"sequences",
"in",
"a",
"fasta",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fasta.py#L5-L11 |
237,349 | bcbio/bcbio-nextgen | bcbio/bam/fasta.py | sequence_names | def sequence_names(fasta):
"""
return a list of the sequence IDs in a FASTA file
"""
sequences = SeqIO.parse(fasta, "fasta")
records = [record.id for record in sequences]
return records | python | def sequence_names(fasta):
sequences = SeqIO.parse(fasta, "fasta")
records = [record.id for record in sequences]
return records | [
"def",
"sequence_names",
"(",
"fasta",
")",
":",
"sequences",
"=",
"SeqIO",
".",
"parse",
"(",
"fasta",
",",
"\"fasta\"",
")",
"records",
"=",
"[",
"record",
".",
"id",
"for",
"record",
"in",
"sequences",
"]",
"return",
"records"
] | return a list of the sequence IDs in a FASTA file | [
"return",
"a",
"list",
"of",
"the",
"sequence",
"IDs",
"in",
"a",
"FASTA",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fasta.py#L13-L19 |
237,350 | bcbio/bcbio-nextgen | bcbio/srna/mirdeep.py | _prepare_inputs | def _prepare_inputs(ma_fn, bam_file, out_dir):
"""
Convert to fastq with counts
"""
fixed_fa = os.path.join(out_dir, "file_reads.fa")
count_name =dict()
with file_transaction(fixed_fa) as out_tx:
with open(out_tx, 'w') as out_handle:
with open(ma_fn) as in_handle:
h = next(in_handle)
for line in in_handle:
cols = line.split("\t")
name_with_counts = "%s_x%s" % (cols[0], sum(map(int, cols[2:])))
count_name[cols[0]] = name_with_counts
out_handle.write(">%s\n%s\n" % (name_with_counts, cols[1]))
fixed_bam = os.path.join(out_dir, "align.bam")
bam_handle = pysam.AlignmentFile(bam_file, "rb")
with pysam.AlignmentFile(fixed_bam, "wb", template=bam_handle) as out_handle:
for read in bam_handle.fetch():
read.query_name = count_name[read.query_name]
out_handle.write(read)
return fixed_fa, fixed_bam | python | def _prepare_inputs(ma_fn, bam_file, out_dir):
fixed_fa = os.path.join(out_dir, "file_reads.fa")
count_name =dict()
with file_transaction(fixed_fa) as out_tx:
with open(out_tx, 'w') as out_handle:
with open(ma_fn) as in_handle:
h = next(in_handle)
for line in in_handle:
cols = line.split("\t")
name_with_counts = "%s_x%s" % (cols[0], sum(map(int, cols[2:])))
count_name[cols[0]] = name_with_counts
out_handle.write(">%s\n%s\n" % (name_with_counts, cols[1]))
fixed_bam = os.path.join(out_dir, "align.bam")
bam_handle = pysam.AlignmentFile(bam_file, "rb")
with pysam.AlignmentFile(fixed_bam, "wb", template=bam_handle) as out_handle:
for read in bam_handle.fetch():
read.query_name = count_name[read.query_name]
out_handle.write(read)
return fixed_fa, fixed_bam | [
"def",
"_prepare_inputs",
"(",
"ma_fn",
",",
"bam_file",
",",
"out_dir",
")",
":",
"fixed_fa",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"\"file_reads.fa\"",
")",
"count_name",
"=",
"dict",
"(",
")",
"with",
"file_transaction",
"(",
"fixed_... | Convert to fastq with counts | [
"Convert",
"to",
"fastq",
"with",
"counts"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/mirdeep.py#L52-L74 |
237,351 | bcbio/bcbio-nextgen | bcbio/srna/mirdeep.py | _parse_novel | def _parse_novel(csv_file, sps="new"):
"""Create input of novel miRNAs from miRDeep2"""
read = 0
seen = set()
safe_makedir("novel")
with open("novel/hairpin.fa", "w") as fa_handle, open("novel/miRNA.str", "w") as str_handle:
with open(csv_file) as in_handle:
for line in in_handle:
if line.startswith("mature miRBase miRNAs detected by miRDeep2"):
break
if line.startswith("novel miRNAs predicted"):
read = 1
line = next(in_handle)
continue
if read and line.strip():
cols = line.strip().split("\t")
name, start, score = cols[0], cols[16], cols[1]
if float(score) < 1:
continue
m5p, m3p, pre = cols[13], cols[14], cols[15].replace('u', 't').upper()
m5p_start = cols[15].find(m5p) + 1
m3p_start = cols[15].find(m3p) + 1
m5p_end = m5p_start + len(m5p) - 1
m3p_end = m3p_start + len(m3p) - 1
if m5p in seen:
continue
fa_handle.write(">{sps}-{name} {start}\n{pre}\n".format(**locals()))
str_handle.write(">{sps}-{name} ({score}) [{sps}-{name}-5p:{m5p_start}-{m5p_end}] [{sps}-{name}-3p:{m3p_start}-{m3p_end}]\n".format(**locals()))
seen.add(m5p)
return op.abspath("novel") | python | def _parse_novel(csv_file, sps="new"):
read = 0
seen = set()
safe_makedir("novel")
with open("novel/hairpin.fa", "w") as fa_handle, open("novel/miRNA.str", "w") as str_handle:
with open(csv_file) as in_handle:
for line in in_handle:
if line.startswith("mature miRBase miRNAs detected by miRDeep2"):
break
if line.startswith("novel miRNAs predicted"):
read = 1
line = next(in_handle)
continue
if read and line.strip():
cols = line.strip().split("\t")
name, start, score = cols[0], cols[16], cols[1]
if float(score) < 1:
continue
m5p, m3p, pre = cols[13], cols[14], cols[15].replace('u', 't').upper()
m5p_start = cols[15].find(m5p) + 1
m3p_start = cols[15].find(m3p) + 1
m5p_end = m5p_start + len(m5p) - 1
m3p_end = m3p_start + len(m3p) - 1
if m5p in seen:
continue
fa_handle.write(">{sps}-{name} {start}\n{pre}\n".format(**locals()))
str_handle.write(">{sps}-{name} ({score}) [{sps}-{name}-5p:{m5p_start}-{m5p_end}] [{sps}-{name}-3p:{m3p_start}-{m3p_end}]\n".format(**locals()))
seen.add(m5p)
return op.abspath("novel") | [
"def",
"_parse_novel",
"(",
"csv_file",
",",
"sps",
"=",
"\"new\"",
")",
":",
"read",
"=",
"0",
"seen",
"=",
"set",
"(",
")",
"safe_makedir",
"(",
"\"novel\"",
")",
"with",
"open",
"(",
"\"novel/hairpin.fa\"",
",",
"\"w\"",
")",
"as",
"fa_handle",
",",
... | Create input of novel miRNAs from miRDeep2 | [
"Create",
"input",
"of",
"novel",
"miRNAs",
"from",
"miRDeep2"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/mirdeep.py#L76-L105 |
237,352 | bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | _run_smoove | def _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items):
"""Run lumpy-sv using smoove.
"""
batch = sshared.get_cur_batch(items)
ext = "-%s-svs" % batch if batch else "-svs"
name = "%s%s" % (dd.get_sample_name(items[0]), ext)
out_file = os.path.join(work_dir, "%s-smoove.genotyped.vcf.gz" % name)
sv_exclude_bed = sshared.prepare_exclude_file(items, out_file)
old_out_file = os.path.join(work_dir, "%s%s-prep.vcf.gz"
% (os.path.splitext(os.path.basename(items[0]["align_bam"]))[0], ext))
if utils.file_exists(old_out_file):
return old_out_file, sv_exclude_bed
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
cores = dd.get_num_cores(items[0])
out_dir = os.path.dirname(tx_out_file)
ref_file = dd.get_ref_file(items[0])
full_bams = " ".join(_prepare_smoove_bams(full_bams, sr_bams, disc_bams, items,
os.path.dirname(tx_out_file)))
std_excludes = ["~^GL", "~^HLA", "~_random", "~^chrUn", "~alt", "~decoy"]
def _is_std_exclude(n):
clean_excludes = [x.replace("~", "").replace("^", "") for x in std_excludes]
return any([n.startswith(x) or n.endswith(x) for x in clean_excludes])
exclude_chrs = [c.name for c in ref.file_contigs(ref_file)
if not chromhacks.is_nonalt(c.name) and not _is_std_exclude(c.name)]
exclude_chrs = "--excludechroms '%s'" % ",".join(std_excludes + exclude_chrs)
exclude_bed = ("--exclude %s" % sv_exclude_bed) if utils.file_exists(sv_exclude_bed) else ""
tempdir = os.path.dirname(tx_out_file)
cmd = ("export TMPDIR={tempdir} && "
"smoove call --processes {cores} --genotype --removepr --fasta {ref_file} "
"--name {name} --outdir {out_dir} "
"{exclude_bed} {exclude_chrs} {full_bams}")
with utils.chdir(tempdir):
try:
do.run(cmd.format(**locals()), "smoove lumpy calling", items[0])
except subprocess.CalledProcessError as msg:
if _allowed_errors(msg):
vcfutils.write_empty_vcf(tx_out_file, config=items[0]["config"],
samples=[dd.get_sample_name(d) for d in items])
else:
logger.exception()
raise
vcfutils.bgzip_and_index(out_file, items[0]["config"])
return out_file, sv_exclude_bed | python | def _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items):
batch = sshared.get_cur_batch(items)
ext = "-%s-svs" % batch if batch else "-svs"
name = "%s%s" % (dd.get_sample_name(items[0]), ext)
out_file = os.path.join(work_dir, "%s-smoove.genotyped.vcf.gz" % name)
sv_exclude_bed = sshared.prepare_exclude_file(items, out_file)
old_out_file = os.path.join(work_dir, "%s%s-prep.vcf.gz"
% (os.path.splitext(os.path.basename(items[0]["align_bam"]))[0], ext))
if utils.file_exists(old_out_file):
return old_out_file, sv_exclude_bed
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
cores = dd.get_num_cores(items[0])
out_dir = os.path.dirname(tx_out_file)
ref_file = dd.get_ref_file(items[0])
full_bams = " ".join(_prepare_smoove_bams(full_bams, sr_bams, disc_bams, items,
os.path.dirname(tx_out_file)))
std_excludes = ["~^GL", "~^HLA", "~_random", "~^chrUn", "~alt", "~decoy"]
def _is_std_exclude(n):
clean_excludes = [x.replace("~", "").replace("^", "") for x in std_excludes]
return any([n.startswith(x) or n.endswith(x) for x in clean_excludes])
exclude_chrs = [c.name for c in ref.file_contigs(ref_file)
if not chromhacks.is_nonalt(c.name) and not _is_std_exclude(c.name)]
exclude_chrs = "--excludechroms '%s'" % ",".join(std_excludes + exclude_chrs)
exclude_bed = ("--exclude %s" % sv_exclude_bed) if utils.file_exists(sv_exclude_bed) else ""
tempdir = os.path.dirname(tx_out_file)
cmd = ("export TMPDIR={tempdir} && "
"smoove call --processes {cores} --genotype --removepr --fasta {ref_file} "
"--name {name} --outdir {out_dir} "
"{exclude_bed} {exclude_chrs} {full_bams}")
with utils.chdir(tempdir):
try:
do.run(cmd.format(**locals()), "smoove lumpy calling", items[0])
except subprocess.CalledProcessError as msg:
if _allowed_errors(msg):
vcfutils.write_empty_vcf(tx_out_file, config=items[0]["config"],
samples=[dd.get_sample_name(d) for d in items])
else:
logger.exception()
raise
vcfutils.bgzip_and_index(out_file, items[0]["config"])
return out_file, sv_exclude_bed | [
"def",
"_run_smoove",
"(",
"full_bams",
",",
"sr_bams",
",",
"disc_bams",
",",
"work_dir",
",",
"items",
")",
":",
"batch",
"=",
"sshared",
".",
"get_cur_batch",
"(",
"items",
")",
"ext",
"=",
"\"-%s-svs\"",
"%",
"batch",
"if",
"batch",
"else",
"\"-svs\"",... | Run lumpy-sv using smoove. | [
"Run",
"lumpy",
"-",
"sv",
"using",
"smoove",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L28-L71 |
237,353 | bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | _filter_by_support | def _filter_by_support(in_file, data):
"""Filter call file based on supporting evidence, adding FILTER annotations to VCF.
Filters based on the following criteria:
- Minimum read support for the call (SU = total support)
- Large calls need split read evidence.
"""
rc_filter = ("FORMAT/SU < 4 || "
"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)>50000) || "
"(FORMAT/SR == 0 && FORMAT/SU < 5 && ABS(SVLEN)<2000) || "
"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)<300)")
return vfilter.cutoff_w_expression(in_file, rc_filter, data, name="ReadCountSupport",
limit_regions=None) | python | def _filter_by_support(in_file, data):
rc_filter = ("FORMAT/SU < 4 || "
"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)>50000) || "
"(FORMAT/SR == 0 && FORMAT/SU < 5 && ABS(SVLEN)<2000) || "
"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)<300)")
return vfilter.cutoff_w_expression(in_file, rc_filter, data, name="ReadCountSupport",
limit_regions=None) | [
"def",
"_filter_by_support",
"(",
"in_file",
",",
"data",
")",
":",
"rc_filter",
"=",
"(",
"\"FORMAT/SU < 4 || \"",
"\"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)>50000) || \"",
"\"(FORMAT/SR == 0 && FORMAT/SU < 5 && ABS(SVLEN)<2000) || \"",
"\"(FORMAT/SR == 0 && FORMAT/SU < 15 && AB... | Filter call file based on supporting evidence, adding FILTER annotations to VCF.
Filters based on the following criteria:
- Minimum read support for the call (SU = total support)
- Large calls need split read evidence. | [
"Filter",
"call",
"file",
"based",
"on",
"supporting",
"evidence",
"adding",
"FILTER",
"annotations",
"to",
"VCF",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L104-L116 |
237,354 | bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | _filter_by_background | def _filter_by_background(base_name, back_samples, gt_vcfs, data):
"""Filter base samples, marking any also present in the background.
"""
filtname = "InBackground"
filtdoc = "Variant also present in background samples with same genotype"
orig_vcf = gt_vcfs[base_name]
out_file = "%s-backfilter.vcf" % (utils.splitext_plus(orig_vcf)[0])
if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
with file_transaction(data, out_file) as tx_out_file:
with utils.open_gzipsafe(orig_vcf) as in_handle:
inp = vcf.Reader(in_handle, orig_vcf)
inp.filters[filtname] = vcf.parser._Filter(filtname, filtdoc)
with open(tx_out_file, "w") as out_handle:
outp = vcf.Writer(out_handle, inp)
for rec in inp:
if _genotype_in_background(rec, base_name, back_samples):
rec.add_filter(filtname)
outp.write_record(rec)
if utils.file_exists(out_file + ".gz"):
out_file = out_file + ".gz"
gt_vcfs[base_name] = vcfutils.bgzip_and_index(out_file, data["config"])
return gt_vcfs | python | def _filter_by_background(base_name, back_samples, gt_vcfs, data):
filtname = "InBackground"
filtdoc = "Variant also present in background samples with same genotype"
orig_vcf = gt_vcfs[base_name]
out_file = "%s-backfilter.vcf" % (utils.splitext_plus(orig_vcf)[0])
if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
with file_transaction(data, out_file) as tx_out_file:
with utils.open_gzipsafe(orig_vcf) as in_handle:
inp = vcf.Reader(in_handle, orig_vcf)
inp.filters[filtname] = vcf.parser._Filter(filtname, filtdoc)
with open(tx_out_file, "w") as out_handle:
outp = vcf.Writer(out_handle, inp)
for rec in inp:
if _genotype_in_background(rec, base_name, back_samples):
rec.add_filter(filtname)
outp.write_record(rec)
if utils.file_exists(out_file + ".gz"):
out_file = out_file + ".gz"
gt_vcfs[base_name] = vcfutils.bgzip_and_index(out_file, data["config"])
return gt_vcfs | [
"def",
"_filter_by_background",
"(",
"base_name",
",",
"back_samples",
",",
"gt_vcfs",
",",
"data",
")",
":",
"filtname",
"=",
"\"InBackground\"",
"filtdoc",
"=",
"\"Variant also present in background samples with same genotype\"",
"orig_vcf",
"=",
"gt_vcfs",
"[",
"base_n... | Filter base samples, marking any also present in the background. | [
"Filter",
"base",
"samples",
"marking",
"any",
"also",
"present",
"in",
"the",
"background",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L118-L139 |
237,355 | bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | _genotype_in_background | def _genotype_in_background(rec, base_name, back_samples):
"""Check if the genotype in the record of interest is present in the background records.
"""
def passes(rec):
return not rec.FILTER or len(rec.FILTER) == 0
return (passes(rec) and
any(rec.genotype(base_name).gt_alleles == rec.genotype(back_name).gt_alleles
for back_name in back_samples)) | python | def _genotype_in_background(rec, base_name, back_samples):
def passes(rec):
return not rec.FILTER or len(rec.FILTER) == 0
return (passes(rec) and
any(rec.genotype(base_name).gt_alleles == rec.genotype(back_name).gt_alleles
for back_name in back_samples)) | [
"def",
"_genotype_in_background",
"(",
"rec",
",",
"base_name",
",",
"back_samples",
")",
":",
"def",
"passes",
"(",
"rec",
")",
":",
"return",
"not",
"rec",
".",
"FILTER",
"or",
"len",
"(",
"rec",
".",
"FILTER",
")",
"==",
"0",
"return",
"(",
"passes"... | Check if the genotype in the record of interest is present in the background records. | [
"Check",
"if",
"the",
"genotype",
"in",
"the",
"record",
"of",
"interest",
"is",
"present",
"in",
"the",
"background",
"records",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L141-L148 |
237,356 | bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | run | def run(items):
"""Perform detection of structural variations with lumpy.
"""
paired = vcfutils.get_paired(items)
work_dir = _sv_workdir(paired.tumor_data if paired and paired.tumor_data else items[0])
previous_evidence = {}
full_bams, sr_bams, disc_bams = [], [], []
for data in items:
full_bams.append(dd.get_align_bam(data))
sr_bam, disc_bam = sshared.find_existing_split_discordants(data)
sr_bams.append(sr_bam)
disc_bams.append(disc_bam)
cur_dels, cur_dups = _bedpes_from_cnv_caller(data, work_dir)
previous_evidence[dd.get_sample_name(data)] = {}
if cur_dels and utils.file_exists(cur_dels):
previous_evidence[dd.get_sample_name(data)]["dels"] = cur_dels
if cur_dups and utils.file_exists(cur_dups):
previous_evidence[dd.get_sample_name(data)]["dups"] = cur_dups
lumpy_vcf, exclude_file = _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items)
lumpy_vcf = sshared.annotate_with_depth(lumpy_vcf, items)
gt_vcfs = {}
# Retain paired samples with tumor/normal genotyped in one file
if paired and paired.normal_name:
batches = [[paired.tumor_data, paired.normal_data]]
else:
batches = [[x] for x in items]
for batch_items in batches:
for data in batch_items:
gt_vcfs[dd.get_sample_name(data)] = _filter_by_support(lumpy_vcf, data)
if paired and paired.normal_name:
gt_vcfs = _filter_by_background(paired.tumor_name, [paired.normal_name], gt_vcfs, paired.tumor_data)
out = []
upload_counts = collections.defaultdict(int)
for data in items:
if "sv" not in data:
data["sv"] = []
vcf_file = gt_vcfs.get(dd.get_sample_name(data))
if vcf_file:
effects_vcf, _ = effects.add_to_vcf(vcf_file, data, "snpeff")
data["sv"].append({"variantcaller": "lumpy",
"vrn_file": effects_vcf or vcf_file,
"do_upload": upload_counts[vcf_file] == 0, # only upload a single file per batch
"exclude_file": exclude_file})
upload_counts[vcf_file] += 1
out.append(data)
return out | python | def run(items):
paired = vcfutils.get_paired(items)
work_dir = _sv_workdir(paired.tumor_data if paired and paired.tumor_data else items[0])
previous_evidence = {}
full_bams, sr_bams, disc_bams = [], [], []
for data in items:
full_bams.append(dd.get_align_bam(data))
sr_bam, disc_bam = sshared.find_existing_split_discordants(data)
sr_bams.append(sr_bam)
disc_bams.append(disc_bam)
cur_dels, cur_dups = _bedpes_from_cnv_caller(data, work_dir)
previous_evidence[dd.get_sample_name(data)] = {}
if cur_dels and utils.file_exists(cur_dels):
previous_evidence[dd.get_sample_name(data)]["dels"] = cur_dels
if cur_dups and utils.file_exists(cur_dups):
previous_evidence[dd.get_sample_name(data)]["dups"] = cur_dups
lumpy_vcf, exclude_file = _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items)
lumpy_vcf = sshared.annotate_with_depth(lumpy_vcf, items)
gt_vcfs = {}
# Retain paired samples with tumor/normal genotyped in one file
if paired and paired.normal_name:
batches = [[paired.tumor_data, paired.normal_data]]
else:
batches = [[x] for x in items]
for batch_items in batches:
for data in batch_items:
gt_vcfs[dd.get_sample_name(data)] = _filter_by_support(lumpy_vcf, data)
if paired and paired.normal_name:
gt_vcfs = _filter_by_background(paired.tumor_name, [paired.normal_name], gt_vcfs, paired.tumor_data)
out = []
upload_counts = collections.defaultdict(int)
for data in items:
if "sv" not in data:
data["sv"] = []
vcf_file = gt_vcfs.get(dd.get_sample_name(data))
if vcf_file:
effects_vcf, _ = effects.add_to_vcf(vcf_file, data, "snpeff")
data["sv"].append({"variantcaller": "lumpy",
"vrn_file": effects_vcf or vcf_file,
"do_upload": upload_counts[vcf_file] == 0, # only upload a single file per batch
"exclude_file": exclude_file})
upload_counts[vcf_file] += 1
out.append(data)
return out | [
"def",
"run",
"(",
"items",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired",
"(",
"items",
")",
"work_dir",
"=",
"_sv_workdir",
"(",
"paired",
".",
"tumor_data",
"if",
"paired",
"and",
"paired",
".",
"tumor_data",
"else",
"items",
"[",
"0",
"]",
... | Perform detection of structural variations with lumpy. | [
"Perform",
"detection",
"of",
"structural",
"variations",
"with",
"lumpy",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L154-L200 |
237,357 | bcbio/bcbio-nextgen | bcbio/structural/lumpy.py | _bedpes_from_cnv_caller | def _bedpes_from_cnv_caller(data, work_dir):
"""Retrieve BEDPEs deletion and duplications from CNV callers.
Currently integrates with CNVkit.
"""
supported = set(["cnvkit"])
cns_file = None
for sv in data.get("sv", []):
if sv["variantcaller"] in supported and "cns" in sv and "lumpy_usecnv" in dd.get_tools_on(data):
cns_file = sv["cns"]
break
if not cns_file:
return None, None
else:
out_base = os.path.join(work_dir, utils.splitext_plus(os.path.basename(cns_file))[0])
out_dels = out_base + "-dels.bedpe"
out_dups = out_base + "-dups.bedpe"
if not os.path.exists(out_dels) or not os.path.exists(out_dups):
with file_transaction(data, out_dels, out_dups) as (tx_out_dels, tx_out_dups):
try:
cnvanator_path = config_utils.get_program("cnvanator_to_bedpes.py", data)
except config_utils.CmdNotFound:
return None, None
cmd = [cnvanator_path, "-c", cns_file, "--cnvkit",
"--del_o=%s" % tx_out_dels, "--dup_o=%s" % tx_out_dups,
"-b", "250"] # XXX Uses default piece size for CNVkit. Right approach?
do.run(cmd, "Prepare CNVkit as input for lumpy", data)
return out_dels, out_dups | python | def _bedpes_from_cnv_caller(data, work_dir):
supported = set(["cnvkit"])
cns_file = None
for sv in data.get("sv", []):
if sv["variantcaller"] in supported and "cns" in sv and "lumpy_usecnv" in dd.get_tools_on(data):
cns_file = sv["cns"]
break
if not cns_file:
return None, None
else:
out_base = os.path.join(work_dir, utils.splitext_plus(os.path.basename(cns_file))[0])
out_dels = out_base + "-dels.bedpe"
out_dups = out_base + "-dups.bedpe"
if not os.path.exists(out_dels) or not os.path.exists(out_dups):
with file_transaction(data, out_dels, out_dups) as (tx_out_dels, tx_out_dups):
try:
cnvanator_path = config_utils.get_program("cnvanator_to_bedpes.py", data)
except config_utils.CmdNotFound:
return None, None
cmd = [cnvanator_path, "-c", cns_file, "--cnvkit",
"--del_o=%s" % tx_out_dels, "--dup_o=%s" % tx_out_dups,
"-b", "250"] # XXX Uses default piece size for CNVkit. Right approach?
do.run(cmd, "Prepare CNVkit as input for lumpy", data)
return out_dels, out_dups | [
"def",
"_bedpes_from_cnv_caller",
"(",
"data",
",",
"work_dir",
")",
":",
"supported",
"=",
"set",
"(",
"[",
"\"cnvkit\"",
"]",
")",
"cns_file",
"=",
"None",
"for",
"sv",
"in",
"data",
".",
"get",
"(",
"\"sv\"",
",",
"[",
"]",
")",
":",
"if",
"sv",
... | Retrieve BEDPEs deletion and duplications from CNV callers.
Currently integrates with CNVkit. | [
"Retrieve",
"BEDPEs",
"deletion",
"and",
"duplications",
"from",
"CNV",
"callers",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L202-L229 |
237,358 | bcbio/bcbio-nextgen | bcbio/setpath.py | _prepend | def _prepend(original, to_prepend):
"""Prepend paths in a string representing a list of paths to another.
original and to_prepend are expected to be strings representing
os.pathsep-separated lists of filepaths.
If to_prepend is None, original is returned.
The list of paths represented in the returned value consists of the first of
occurrences of each non-empty path in the list obtained by prepending the
paths in to_prepend to the paths in original.
examples:
# Unix
_prepend('/b:/d:/a:/d', '/a:/b:/c:/a') -> '/a:/b:/c:/d'
_prepend('/a:/b:/a', '/a:/c:/c') -> '/a:/c:/b'
_prepend('/c', '/a::/b:/a') -> '/a:/b:/c'
_prepend('/a:/b:/a', None) -> '/a:/b:/a'
_prepend('/a:/b:/a', '') -> '/a:/b'
"""
if to_prepend is None:
return original
sep = os.pathsep
def split_path_value(path_value):
return [] if path_value == '' else path_value.split(sep)
seen = set()
components = []
for path in split_path_value(to_prepend) + split_path_value(original):
if path not in seen and path != '':
components.append(path)
seen.add(path)
return sep.join(components) | python | def _prepend(original, to_prepend):
if to_prepend is None:
return original
sep = os.pathsep
def split_path_value(path_value):
return [] if path_value == '' else path_value.split(sep)
seen = set()
components = []
for path in split_path_value(to_prepend) + split_path_value(original):
if path not in seen and path != '':
components.append(path)
seen.add(path)
return sep.join(components) | [
"def",
"_prepend",
"(",
"original",
",",
"to_prepend",
")",
":",
"if",
"to_prepend",
"is",
"None",
":",
"return",
"original",
"sep",
"=",
"os",
".",
"pathsep",
"def",
"split_path_value",
"(",
"path_value",
")",
":",
"return",
"[",
"]",
"if",
"path_value",
... | Prepend paths in a string representing a list of paths to another.
original and to_prepend are expected to be strings representing
os.pathsep-separated lists of filepaths.
If to_prepend is None, original is returned.
The list of paths represented in the returned value consists of the first of
occurrences of each non-empty path in the list obtained by prepending the
paths in to_prepend to the paths in original.
examples:
# Unix
_prepend('/b:/d:/a:/d', '/a:/b:/c:/a') -> '/a:/b:/c:/d'
_prepend('/a:/b:/a', '/a:/c:/c') -> '/a:/c:/b'
_prepend('/c', '/a::/b:/a') -> '/a:/b:/c'
_prepend('/a:/b:/a', None) -> '/a:/b:/a'
_prepend('/a:/b:/a', '') -> '/a:/b' | [
"Prepend",
"paths",
"in",
"a",
"string",
"representing",
"a",
"list",
"of",
"paths",
"to",
"another",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/setpath.py#L10-L48 |
237,359 | bcbio/bcbio-nextgen | bcbio/setpath.py | remove_bcbiopath | def remove_bcbiopath():
"""Remove bcbio internal path from first element in PATH.
Useful when we need to access remote programs, like Java 7 for older
installations.
"""
to_remove = os.environ.get("BCBIOPATH", utils.get_bcbio_bin()) + ":"
if os.environ["PATH"].startswith(to_remove):
os.environ["PATH"] = os.environ["PATH"][len(to_remove):] | python | def remove_bcbiopath():
to_remove = os.environ.get("BCBIOPATH", utils.get_bcbio_bin()) + ":"
if os.environ["PATH"].startswith(to_remove):
os.environ["PATH"] = os.environ["PATH"][len(to_remove):] | [
"def",
"remove_bcbiopath",
"(",
")",
":",
"to_remove",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"BCBIOPATH\"",
",",
"utils",
".",
"get_bcbio_bin",
"(",
")",
")",
"+",
"\":\"",
"if",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
".",
"startswith",
"(... | Remove bcbio internal path from first element in PATH.
Useful when we need to access remote programs, like Java 7 for older
installations. | [
"Remove",
"bcbio",
"internal",
"path",
"from",
"first",
"element",
"in",
"PATH",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/setpath.py#L64-L72 |
237,360 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | calculate_sv_bins | def calculate_sv_bins(*items):
"""Determine bin sizes and regions to use for samples.
Unified approach to prepare regional bins for coverage calculations across
multiple CNV callers. Splits into target and antitarget regions allowing
callers to take advantage of both. Provides consistent target/anti-target
bin sizes across batches.
Uses callable_regions as the access BED file and mosdepth regions in
variant_regions to estimate depth for bin sizes.
"""
calcfns = {"cnvkit": _calculate_sv_bins_cnvkit, "gatk-cnv": _calculate_sv_bins_gatk}
from bcbio.structural import cnvkit
items = [utils.to_single_data(x) for x in cwlutils.handle_combined_input(items)]
if all(not cnvkit.use_general_sv_bins(x) for x in items):
return [[d] for d in items]
out = []
for i, cnv_group in enumerate(_group_by_cnv_method(multi.group_by_batch(items, False))):
size_calc_fn = MemoizedSizes(cnv_group.region_file, cnv_group.items).get_target_antitarget_bin_sizes
for data in cnv_group.items:
if cnvkit.use_general_sv_bins(data):
target_bed, anti_bed, gcannotated_tsv = calcfns[cnvkit.bin_approach(data)](data, cnv_group,
size_calc_fn)
if not data.get("regions"):
data["regions"] = {}
data["regions"]["bins"] = {"target": target_bed, "antitarget": anti_bed, "group": str(i),
"gcannotated": gcannotated_tsv}
out.append([data])
if not len(out) == len(items):
raise AssertionError("Inconsistent samples in and out of SV bin calculation:\nout: %s\nin : %s" %
(sorted([dd.get_sample_name(utils.to_single_data(x)) for x in out]),
sorted([dd.get_sample_name(x) for x in items])))
return out | python | def calculate_sv_bins(*items):
calcfns = {"cnvkit": _calculate_sv_bins_cnvkit, "gatk-cnv": _calculate_sv_bins_gatk}
from bcbio.structural import cnvkit
items = [utils.to_single_data(x) for x in cwlutils.handle_combined_input(items)]
if all(not cnvkit.use_general_sv_bins(x) for x in items):
return [[d] for d in items]
out = []
for i, cnv_group in enumerate(_group_by_cnv_method(multi.group_by_batch(items, False))):
size_calc_fn = MemoizedSizes(cnv_group.region_file, cnv_group.items).get_target_antitarget_bin_sizes
for data in cnv_group.items:
if cnvkit.use_general_sv_bins(data):
target_bed, anti_bed, gcannotated_tsv = calcfns[cnvkit.bin_approach(data)](data, cnv_group,
size_calc_fn)
if not data.get("regions"):
data["regions"] = {}
data["regions"]["bins"] = {"target": target_bed, "antitarget": anti_bed, "group": str(i),
"gcannotated": gcannotated_tsv}
out.append([data])
if not len(out) == len(items):
raise AssertionError("Inconsistent samples in and out of SV bin calculation:\nout: %s\nin : %s" %
(sorted([dd.get_sample_name(utils.to_single_data(x)) for x in out]),
sorted([dd.get_sample_name(x) for x in items])))
return out | [
"def",
"calculate_sv_bins",
"(",
"*",
"items",
")",
":",
"calcfns",
"=",
"{",
"\"cnvkit\"",
":",
"_calculate_sv_bins_cnvkit",
",",
"\"gatk-cnv\"",
":",
"_calculate_sv_bins_gatk",
"}",
"from",
"bcbio",
".",
"structural",
"import",
"cnvkit",
"items",
"=",
"[",
"ut... | Determine bin sizes and regions to use for samples.
Unified approach to prepare regional bins for coverage calculations across
multiple CNV callers. Splits into target and antitarget regions allowing
callers to take advantage of both. Provides consistent target/anti-target
bin sizes across batches.
Uses callable_regions as the access BED file and mosdepth regions in
variant_regions to estimate depth for bin sizes. | [
"Determine",
"bin",
"sizes",
"and",
"regions",
"to",
"use",
"for",
"samples",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L27-L59 |
237,361 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | _calculate_sv_bins_gatk | def _calculate_sv_bins_gatk(data, cnv_group, size_calc_fn):
"""Calculate structural variant bins using GATK4 CNV callers region or even intervals approach.
"""
if dd.get_background_cnv_reference(data, "gatk-cnv"):
target_bed = gatkcnv.pon_to_bed(dd.get_background_cnv_reference(data, "gatk-cnv"), cnv_group.work_dir, data)
else:
target_bed = gatkcnv.prepare_intervals(data, cnv_group.region_file, cnv_group.work_dir)
gc_annotated_tsv = gatkcnv.annotate_intervals(target_bed, data)
return target_bed, None, gc_annotated_tsv | python | def _calculate_sv_bins_gatk(data, cnv_group, size_calc_fn):
if dd.get_background_cnv_reference(data, "gatk-cnv"):
target_bed = gatkcnv.pon_to_bed(dd.get_background_cnv_reference(data, "gatk-cnv"), cnv_group.work_dir, data)
else:
target_bed = gatkcnv.prepare_intervals(data, cnv_group.region_file, cnv_group.work_dir)
gc_annotated_tsv = gatkcnv.annotate_intervals(target_bed, data)
return target_bed, None, gc_annotated_tsv | [
"def",
"_calculate_sv_bins_gatk",
"(",
"data",
",",
"cnv_group",
",",
"size_calc_fn",
")",
":",
"if",
"dd",
".",
"get_background_cnv_reference",
"(",
"data",
",",
"\"gatk-cnv\"",
")",
":",
"target_bed",
"=",
"gatkcnv",
".",
"pon_to_bed",
"(",
"dd",
".",
"get_b... | Calculate structural variant bins using GATK4 CNV callers region or even intervals approach. | [
"Calculate",
"structural",
"variant",
"bins",
"using",
"GATK4",
"CNV",
"callers",
"region",
"or",
"even",
"intervals",
"approach",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L61-L69 |
237,362 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | calculate_sv_coverage | def calculate_sv_coverage(data):
"""Calculate coverage within bins for downstream CNV calling.
Creates corrected cnr files with log2 ratios and depths.
"""
calcfns = {"cnvkit": _calculate_sv_coverage_cnvkit, "gatk-cnv": _calculate_sv_coverage_gatk}
from bcbio.structural import cnvkit
data = utils.to_single_data(data)
if not cnvkit.use_general_sv_bins(data):
out_target_file, out_anti_file = (None, None)
else:
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural",
dd.get_sample_name(data), "bins"))
out_target_file, out_anti_file = calcfns[cnvkit.bin_approach(data)](data, work_dir)
if not os.path.exists(out_target_file):
out_target_file, out_anti_file = (None, None)
if "seq2c" in dd.get_svcaller(data):
from bcbio.structural import seq2c
seq2c_target = seq2c.precall(data)
else:
seq2c_target = None
if not tz.get_in(["depth", "bins"], data):
data = tz.update_in(data, ["depth", "bins"], lambda x: {})
data["depth"]["bins"] = {"target": out_target_file, "antitarget": out_anti_file, "seq2c": seq2c_target}
return [[data]] | python | def calculate_sv_coverage(data):
calcfns = {"cnvkit": _calculate_sv_coverage_cnvkit, "gatk-cnv": _calculate_sv_coverage_gatk}
from bcbio.structural import cnvkit
data = utils.to_single_data(data)
if not cnvkit.use_general_sv_bins(data):
out_target_file, out_anti_file = (None, None)
else:
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural",
dd.get_sample_name(data), "bins"))
out_target_file, out_anti_file = calcfns[cnvkit.bin_approach(data)](data, work_dir)
if not os.path.exists(out_target_file):
out_target_file, out_anti_file = (None, None)
if "seq2c" in dd.get_svcaller(data):
from bcbio.structural import seq2c
seq2c_target = seq2c.precall(data)
else:
seq2c_target = None
if not tz.get_in(["depth", "bins"], data):
data = tz.update_in(data, ["depth", "bins"], lambda x: {})
data["depth"]["bins"] = {"target": out_target_file, "antitarget": out_anti_file, "seq2c": seq2c_target}
return [[data]] | [
"def",
"calculate_sv_coverage",
"(",
"data",
")",
":",
"calcfns",
"=",
"{",
"\"cnvkit\"",
":",
"_calculate_sv_coverage_cnvkit",
",",
"\"gatk-cnv\"",
":",
"_calculate_sv_coverage_gatk",
"}",
"from",
"bcbio",
".",
"structural",
"import",
"cnvkit",
"data",
"=",
"utils"... | Calculate coverage within bins for downstream CNV calling.
Creates corrected cnr files with log2 ratios and depths. | [
"Calculate",
"coverage",
"within",
"bins",
"for",
"downstream",
"CNV",
"calling",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L168-L193 |
237,363 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | _calculate_sv_coverage_gatk | def _calculate_sv_coverage_gatk(data, work_dir):
"""Calculate coverage in defined regions using GATK tools
TODO: This does double calculations to get GATK4 compatible HDF read counts
and then depth and gene annotations. Both are needed for creating heterogeneity inputs.
Ideally replace with a single mosdepth coverage calculation, and creat GATK4 TSV format:
CONTIG START END COUNT
chrM 1 1000 13268
"""
from bcbio.variation import coverage
from bcbio.structural import annotate
# GATK compatible
target_file = gatkcnv.collect_read_counts(data, work_dir)
# heterogeneity compatible
target_in = bedutils.clean_file(tz.get_in(["regions", "bins", "target"], data), data, bedprep_dir=work_dir)
target_cov = coverage.run_mosdepth(data, "target-gatk", target_in)
target_cov_genes = annotate.add_genes(target_cov.regions, data, max_distance=0)
return target_file, target_cov_genes | python | def _calculate_sv_coverage_gatk(data, work_dir):
from bcbio.variation import coverage
from bcbio.structural import annotate
# GATK compatible
target_file = gatkcnv.collect_read_counts(data, work_dir)
# heterogeneity compatible
target_in = bedutils.clean_file(tz.get_in(["regions", "bins", "target"], data), data, bedprep_dir=work_dir)
target_cov = coverage.run_mosdepth(data, "target-gatk", target_in)
target_cov_genes = annotate.add_genes(target_cov.regions, data, max_distance=0)
return target_file, target_cov_genes | [
"def",
"_calculate_sv_coverage_gatk",
"(",
"data",
",",
"work_dir",
")",
":",
"from",
"bcbio",
".",
"variation",
"import",
"coverage",
"from",
"bcbio",
".",
"structural",
"import",
"annotate",
"# GATK compatible",
"target_file",
"=",
"gatkcnv",
".",
"collect_read_co... | Calculate coverage in defined regions using GATK tools
TODO: This does double calculations to get GATK4 compatible HDF read counts
and then depth and gene annotations. Both are needed for creating heterogeneity inputs.
Ideally replace with a single mosdepth coverage calculation, and creat GATK4 TSV format:
CONTIG START END COUNT
chrM 1 1000 13268 | [
"Calculate",
"coverage",
"in",
"defined",
"regions",
"using",
"GATK",
"tools"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L195-L213 |
237,364 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | _calculate_sv_coverage_cnvkit | def _calculate_sv_coverage_cnvkit(data, work_dir):
"""Calculate coverage in an CNVkit ready format using mosdepth.
"""
from bcbio.variation import coverage
from bcbio.structural import annotate
out_target_file = os.path.join(work_dir, "%s-target-coverage.cnn" % dd.get_sample_name(data))
out_anti_file = os.path.join(work_dir, "%s-antitarget-coverage.cnn" % dd.get_sample_name(data))
if ((not utils.file_exists(out_target_file) or not utils.file_exists(out_anti_file)) and
(dd.get_align_bam(data) or dd.get_work_bam(data))):
target_cov = coverage.run_mosdepth(data, "target", tz.get_in(["regions", "bins", "target"], data))
anti_cov = coverage.run_mosdepth(data, "antitarget", tz.get_in(["regions", "bins", "antitarget"], data))
target_cov_genes = annotate.add_genes(target_cov.regions, data, max_distance=0)
out_target_file = _add_log2_depth(target_cov_genes, out_target_file, data)
out_anti_file = _add_log2_depth(anti_cov.regions, out_anti_file, data)
return out_target_file, out_anti_file | python | def _calculate_sv_coverage_cnvkit(data, work_dir):
from bcbio.variation import coverage
from bcbio.structural import annotate
out_target_file = os.path.join(work_dir, "%s-target-coverage.cnn" % dd.get_sample_name(data))
out_anti_file = os.path.join(work_dir, "%s-antitarget-coverage.cnn" % dd.get_sample_name(data))
if ((not utils.file_exists(out_target_file) or not utils.file_exists(out_anti_file)) and
(dd.get_align_bam(data) or dd.get_work_bam(data))):
target_cov = coverage.run_mosdepth(data, "target", tz.get_in(["regions", "bins", "target"], data))
anti_cov = coverage.run_mosdepth(data, "antitarget", tz.get_in(["regions", "bins", "antitarget"], data))
target_cov_genes = annotate.add_genes(target_cov.regions, data, max_distance=0)
out_target_file = _add_log2_depth(target_cov_genes, out_target_file, data)
out_anti_file = _add_log2_depth(anti_cov.regions, out_anti_file, data)
return out_target_file, out_anti_file | [
"def",
"_calculate_sv_coverage_cnvkit",
"(",
"data",
",",
"work_dir",
")",
":",
"from",
"bcbio",
".",
"variation",
"import",
"coverage",
"from",
"bcbio",
".",
"structural",
"import",
"annotate",
"out_target_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"wor... | Calculate coverage in an CNVkit ready format using mosdepth. | [
"Calculate",
"coverage",
"in",
"an",
"CNVkit",
"ready",
"format",
"using",
"mosdepth",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L215-L229 |
237,365 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | normalize_sv_coverage | def normalize_sv_coverage(*items):
"""Normalize CNV coverage, providing flexible point for multiple methods.
"""
calcfns = {"cnvkit": _normalize_sv_coverage_cnvkit, "gatk-cnv": _normalize_sv_coverage_gatk}
from bcbio.structural import cnvkit
from bcbio.structural import shared as sshared
items = [utils.to_single_data(x) for x in cwlutils.handle_combined_input(items)]
if all(not cnvkit.use_general_sv_bins(x) for x in items):
return [[d] for d in items]
out_files = {}
back_files = {}
for group_id, gitems in itertools.groupby(items, lambda x: tz.get_in(["regions", "bins", "group"], x)):
# No CNVkit calling for this particular set of samples
if group_id is None:
continue
inputs, backgrounds = sshared.find_case_control(list(gitems))
assert inputs, "Did not find inputs for sample batch: %s" % (" ".join(dd.get_sample_name(x) for x in items))
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(inputs[0]), "structural",
dd.get_sample_name(inputs[0]), "bins"))
back_files, out_files = calcfns[cnvkit.bin_approach(inputs[0])](group_id, inputs, backgrounds, work_dir,
back_files, out_files)
out = []
for data in items:
if dd.get_sample_name(data) in out_files:
data["depth"]["bins"]["background"] = back_files[dd.get_sample_name(data)]
data["depth"]["bins"]["normalized"] = out_files[dd.get_sample_name(data)]
out.append([data])
return out | python | def normalize_sv_coverage(*items):
calcfns = {"cnvkit": _normalize_sv_coverage_cnvkit, "gatk-cnv": _normalize_sv_coverage_gatk}
from bcbio.structural import cnvkit
from bcbio.structural import shared as sshared
items = [utils.to_single_data(x) for x in cwlutils.handle_combined_input(items)]
if all(not cnvkit.use_general_sv_bins(x) for x in items):
return [[d] for d in items]
out_files = {}
back_files = {}
for group_id, gitems in itertools.groupby(items, lambda x: tz.get_in(["regions", "bins", "group"], x)):
# No CNVkit calling for this particular set of samples
if group_id is None:
continue
inputs, backgrounds = sshared.find_case_control(list(gitems))
assert inputs, "Did not find inputs for sample batch: %s" % (" ".join(dd.get_sample_name(x) for x in items))
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(inputs[0]), "structural",
dd.get_sample_name(inputs[0]), "bins"))
back_files, out_files = calcfns[cnvkit.bin_approach(inputs[0])](group_id, inputs, backgrounds, work_dir,
back_files, out_files)
out = []
for data in items:
if dd.get_sample_name(data) in out_files:
data["depth"]["bins"]["background"] = back_files[dd.get_sample_name(data)]
data["depth"]["bins"]["normalized"] = out_files[dd.get_sample_name(data)]
out.append([data])
return out | [
"def",
"normalize_sv_coverage",
"(",
"*",
"items",
")",
":",
"calcfns",
"=",
"{",
"\"cnvkit\"",
":",
"_normalize_sv_coverage_cnvkit",
",",
"\"gatk-cnv\"",
":",
"_normalize_sv_coverage_gatk",
"}",
"from",
"bcbio",
".",
"structural",
"import",
"cnvkit",
"from",
"bcbio... | Normalize CNV coverage, providing flexible point for multiple methods. | [
"Normalize",
"CNV",
"coverage",
"providing",
"flexible",
"point",
"for",
"multiple",
"methods",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L256-L283 |
237,366 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | _normalize_sv_coverage_gatk | def _normalize_sv_coverage_gatk(group_id, inputs, backgrounds, work_dir, back_files, out_files):
"""Normalize CNV coverage using panel of normals with GATK's de-noise approaches.
"""
input_backs = set(filter(lambda x: x is not None,
[dd.get_background_cnv_reference(d, "gatk-cnv") for d in inputs]))
if input_backs:
assert len(input_backs) == 1, "Multiple backgrounds in group: %s" % list(input_backs)
pon = list(input_backs)[0]
elif backgrounds:
pon = gatkcnv.create_panel_of_normals(backgrounds, group_id, work_dir)
else:
pon = None
for data in inputs:
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural",
dd.get_sample_name(data), "bins"))
denoise_file = gatkcnv.denoise(data, pon, work_dir)
out_files[dd.get_sample_name(data)] = denoise_file
back_files[dd.get_sample_name(data)] = pon
return back_files, out_files | python | def _normalize_sv_coverage_gatk(group_id, inputs, backgrounds, work_dir, back_files, out_files):
input_backs = set(filter(lambda x: x is not None,
[dd.get_background_cnv_reference(d, "gatk-cnv") for d in inputs]))
if input_backs:
assert len(input_backs) == 1, "Multiple backgrounds in group: %s" % list(input_backs)
pon = list(input_backs)[0]
elif backgrounds:
pon = gatkcnv.create_panel_of_normals(backgrounds, group_id, work_dir)
else:
pon = None
for data in inputs:
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural",
dd.get_sample_name(data), "bins"))
denoise_file = gatkcnv.denoise(data, pon, work_dir)
out_files[dd.get_sample_name(data)] = denoise_file
back_files[dd.get_sample_name(data)] = pon
return back_files, out_files | [
"def",
"_normalize_sv_coverage_gatk",
"(",
"group_id",
",",
"inputs",
",",
"backgrounds",
",",
"work_dir",
",",
"back_files",
",",
"out_files",
")",
":",
"input_backs",
"=",
"set",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"[",... | Normalize CNV coverage using panel of normals with GATK's de-noise approaches. | [
"Normalize",
"CNV",
"coverage",
"using",
"panel",
"of",
"normals",
"with",
"GATK",
"s",
"de",
"-",
"noise",
"approaches",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L285-L303 |
237,367 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | _normalize_sv_coverage_cnvkit | def _normalize_sv_coverage_cnvkit(group_id, inputs, backgrounds, work_dir, back_files, out_files):
"""Normalize CNV coverage depths by GC, repeats and background using CNVkit
- reference: calculates reference backgrounds from normals and pools
including GC and repeat information
- fix: Uses background to normalize coverage estimations
http://cnvkit.readthedocs.io/en/stable/pipeline.html#fix
"""
from bcbio.structural import cnvkit
cnns = reduce(operator.add, [[tz.get_in(["depth", "bins", "target"], x),
tz.get_in(["depth", "bins", "antitarget"], x)] for x in backgrounds], [])
for d in inputs:
if tz.get_in(["depth", "bins", "target"], d):
target_bed = tz.get_in(["depth", "bins", "target"], d)
antitarget_bed = tz.get_in(["depth", "bins", "antitarget"], d)
input_backs = set(filter(lambda x: x is not None,
[dd.get_background_cnv_reference(d, "cnvkit") for d in inputs]))
if input_backs:
assert len(input_backs) == 1, "Multiple backgrounds in group: %s" % list(input_backs)
back_file = list(input_backs)[0]
else:
back_file = cnvkit.cnvkit_background(cnns,
os.path.join(work_dir, "background-%s-cnvkit.cnn" % (group_id)),
backgrounds or inputs, target_bed, antitarget_bed)
fix_cmd_inputs = []
for data in inputs:
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural",
dd.get_sample_name(data), "bins"))
if tz.get_in(["depth", "bins", "target"], data):
fix_file = os.path.join(work_dir, "%s-normalized.cnr" % (dd.get_sample_name(data)))
fix_cmd_inputs.append((tz.get_in(["depth", "bins", "target"], data),
tz.get_in(["depth", "bins", "antitarget"], data),
back_file, fix_file, data))
out_files[dd.get_sample_name(data)] = fix_file
back_files[dd.get_sample_name(data)] = back_file
parallel = {"type": "local", "cores": dd.get_cores(inputs[0]), "progs": ["cnvkit"]}
run_multicore(cnvkit.run_fix_parallel, fix_cmd_inputs, inputs[0]["config"], parallel)
return back_files, out_files | python | def _normalize_sv_coverage_cnvkit(group_id, inputs, backgrounds, work_dir, back_files, out_files):
from bcbio.structural import cnvkit
cnns = reduce(operator.add, [[tz.get_in(["depth", "bins", "target"], x),
tz.get_in(["depth", "bins", "antitarget"], x)] for x in backgrounds], [])
for d in inputs:
if tz.get_in(["depth", "bins", "target"], d):
target_bed = tz.get_in(["depth", "bins", "target"], d)
antitarget_bed = tz.get_in(["depth", "bins", "antitarget"], d)
input_backs = set(filter(lambda x: x is not None,
[dd.get_background_cnv_reference(d, "cnvkit") for d in inputs]))
if input_backs:
assert len(input_backs) == 1, "Multiple backgrounds in group: %s" % list(input_backs)
back_file = list(input_backs)[0]
else:
back_file = cnvkit.cnvkit_background(cnns,
os.path.join(work_dir, "background-%s-cnvkit.cnn" % (group_id)),
backgrounds or inputs, target_bed, antitarget_bed)
fix_cmd_inputs = []
for data in inputs:
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural",
dd.get_sample_name(data), "bins"))
if tz.get_in(["depth", "bins", "target"], data):
fix_file = os.path.join(work_dir, "%s-normalized.cnr" % (dd.get_sample_name(data)))
fix_cmd_inputs.append((tz.get_in(["depth", "bins", "target"], data),
tz.get_in(["depth", "bins", "antitarget"], data),
back_file, fix_file, data))
out_files[dd.get_sample_name(data)] = fix_file
back_files[dd.get_sample_name(data)] = back_file
parallel = {"type": "local", "cores": dd.get_cores(inputs[0]), "progs": ["cnvkit"]}
run_multicore(cnvkit.run_fix_parallel, fix_cmd_inputs, inputs[0]["config"], parallel)
return back_files, out_files | [
"def",
"_normalize_sv_coverage_cnvkit",
"(",
"group_id",
",",
"inputs",
",",
"backgrounds",
",",
"work_dir",
",",
"back_files",
",",
"out_files",
")",
":",
"from",
"bcbio",
".",
"structural",
"import",
"cnvkit",
"cnns",
"=",
"reduce",
"(",
"operator",
".",
"ad... | Normalize CNV coverage depths by GC, repeats and background using CNVkit
- reference: calculates reference backgrounds from normals and pools
including GC and repeat information
- fix: Uses background to normalize coverage estimations
http://cnvkit.readthedocs.io/en/stable/pipeline.html#fix | [
"Normalize",
"CNV",
"coverage",
"depths",
"by",
"GC",
"repeats",
"and",
"background",
"using",
"CNVkit"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L305-L342 |
237,368 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | get_base_cnv_regions | def get_base_cnv_regions(data, work_dir, genome_default="transcripts1e4", include_gene_names=True):
"""Retrieve set of target regions for CNV analysis.
Subsets to extended transcript regions for WGS experiments to avoid
long runtimes.
"""
cov_interval = dd.get_coverage_interval(data)
base_regions = get_sv_bed(data, include_gene_names=include_gene_names)
# if we don't have a configured BED or regions to use for SV caling
if not base_regions:
# For genome calls, subset to regions near genes as targets
if cov_interval == "genome":
base_regions = get_sv_bed(data, genome_default, work_dir, include_gene_names=include_gene_names)
if base_regions:
base_regions = remove_exclude_regions(base_regions, base_regions, [data])
# Finally, default to the defined variant regions
if not base_regions:
base_regions = dd.get_variant_regions(data) or dd.get_sample_callable(data)
return bedutils.clean_file(base_regions, data) | python | def get_base_cnv_regions(data, work_dir, genome_default="transcripts1e4", include_gene_names=True):
cov_interval = dd.get_coverage_interval(data)
base_regions = get_sv_bed(data, include_gene_names=include_gene_names)
# if we don't have a configured BED or regions to use for SV caling
if not base_regions:
# For genome calls, subset to regions near genes as targets
if cov_interval == "genome":
base_regions = get_sv_bed(data, genome_default, work_dir, include_gene_names=include_gene_names)
if base_regions:
base_regions = remove_exclude_regions(base_regions, base_regions, [data])
# Finally, default to the defined variant regions
if not base_regions:
base_regions = dd.get_variant_regions(data) or dd.get_sample_callable(data)
return bedutils.clean_file(base_regions, data) | [
"def",
"get_base_cnv_regions",
"(",
"data",
",",
"work_dir",
",",
"genome_default",
"=",
"\"transcripts1e4\"",
",",
"include_gene_names",
"=",
"True",
")",
":",
"cov_interval",
"=",
"dd",
".",
"get_coverage_interval",
"(",
"data",
")",
"base_regions",
"=",
"get_sv... | Retrieve set of target regions for CNV analysis.
Subsets to extended transcript regions for WGS experiments to avoid
long runtimes. | [
"Retrieve",
"set",
"of",
"target",
"regions",
"for",
"CNV",
"analysis",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L346-L364 |
237,369 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | remove_exclude_regions | def remove_exclude_regions(orig_bed, base_file, items, remove_entire_feature=False):
"""Remove centromere and short end regions from an existing BED file of regions to target.
"""
from bcbio.structural import shared as sshared
out_bed = os.path.join("%s-noexclude.bed" % (utils.splitext_plus(base_file)[0]))
if not utils.file_uptodate(out_bed, orig_bed):
exclude_bed = sshared.prepare_exclude_file(items, base_file)
with file_transaction(items[0], out_bed) as tx_out_bed:
pybedtools.BedTool(orig_bed).subtract(pybedtools.BedTool(exclude_bed),
A=remove_entire_feature, nonamecheck=True).saveas(tx_out_bed)
if utils.file_exists(out_bed):
return out_bed
else:
return orig_bed | python | def remove_exclude_regions(orig_bed, base_file, items, remove_entire_feature=False):
from bcbio.structural import shared as sshared
out_bed = os.path.join("%s-noexclude.bed" % (utils.splitext_plus(base_file)[0]))
if not utils.file_uptodate(out_bed, orig_bed):
exclude_bed = sshared.prepare_exclude_file(items, base_file)
with file_transaction(items[0], out_bed) as tx_out_bed:
pybedtools.BedTool(orig_bed).subtract(pybedtools.BedTool(exclude_bed),
A=remove_entire_feature, nonamecheck=True).saveas(tx_out_bed)
if utils.file_exists(out_bed):
return out_bed
else:
return orig_bed | [
"def",
"remove_exclude_regions",
"(",
"orig_bed",
",",
"base_file",
",",
"items",
",",
"remove_entire_feature",
"=",
"False",
")",
":",
"from",
"bcbio",
".",
"structural",
"import",
"shared",
"as",
"sshared",
"out_bed",
"=",
"os",
".",
"path",
".",
"join",
"... | Remove centromere and short end regions from an existing BED file of regions to target. | [
"Remove",
"centromere",
"and",
"short",
"end",
"regions",
"from",
"an",
"existing",
"BED",
"file",
"of",
"regions",
"to",
"target",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L366-L379 |
237,370 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | get_sv_bed | def get_sv_bed(data, method=None, out_dir=None, include_gene_names=True):
"""Retrieve a BED file of regions for SV and heterogeneity calling using the provided method.
method choices:
- exons: Raw BED file of exon regions
- transcripts: Full collapsed regions with the min and max of each transcript.
- transcriptsXXXX: Collapsed regions around transcripts with a window size of
XXXX.
- A custom BED file of regions
"""
if method is None:
method = (tz.get_in(["config", "algorithm", "sv_regions"], data) or dd.get_variant_regions(data)
or dd.get_sample_callable(data))
gene_file = dd.get_gene_bed(data)
if method and os.path.isfile(method):
return method
elif not gene_file or not method:
return None
elif method == "exons":
return gene_file
elif method.startswith("transcripts"):
window = method.split("transcripts")[-1]
window = int(float(window)) if window else 0
return _collapse_transcripts(gene_file, window, data, out_dir, include_gene_names=include_gene_names)
else:
raise ValueError("Unexpected transcript retrieval method: %s" % method) | python | def get_sv_bed(data, method=None, out_dir=None, include_gene_names=True):
if method is None:
method = (tz.get_in(["config", "algorithm", "sv_regions"], data) or dd.get_variant_regions(data)
or dd.get_sample_callable(data))
gene_file = dd.get_gene_bed(data)
if method and os.path.isfile(method):
return method
elif not gene_file or not method:
return None
elif method == "exons":
return gene_file
elif method.startswith("transcripts"):
window = method.split("transcripts")[-1]
window = int(float(window)) if window else 0
return _collapse_transcripts(gene_file, window, data, out_dir, include_gene_names=include_gene_names)
else:
raise ValueError("Unexpected transcript retrieval method: %s" % method) | [
"def",
"get_sv_bed",
"(",
"data",
",",
"method",
"=",
"None",
",",
"out_dir",
"=",
"None",
",",
"include_gene_names",
"=",
"True",
")",
":",
"if",
"method",
"is",
"None",
":",
"method",
"=",
"(",
"tz",
".",
"get_in",
"(",
"[",
"\"config\"",
",",
"\"a... | Retrieve a BED file of regions for SV and heterogeneity calling using the provided method.
method choices:
- exons: Raw BED file of exon regions
- transcripts: Full collapsed regions with the min and max of each transcript.
- transcriptsXXXX: Collapsed regions around transcripts with a window size of
XXXX.
- A custom BED file of regions | [
"Retrieve",
"a",
"BED",
"file",
"of",
"regions",
"for",
"SV",
"and",
"heterogeneity",
"calling",
"using",
"the",
"provided",
"method",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L381-L406 |
237,371 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | _group_coords | def _group_coords(rs):
"""Organize coordinate regions into groups for each transcript.
Avoids collapsing very large introns or repetitive genes spread across
the chromosome by limiting the intron size to 100kb for creating a single transcript
"""
max_intron_size = 1e5
coords = []
for r in rs:
coords.append(r.start)
coords.append(r.end)
coord_groups = []
cur_group = []
for coord in sorted(coords):
if not cur_group or coord - cur_group[-1] < max_intron_size:
cur_group.append(coord)
else:
coord_groups.append(cur_group)
cur_group = [coord]
if cur_group:
coord_groups.append(cur_group)
return coord_groups | python | def _group_coords(rs):
max_intron_size = 1e5
coords = []
for r in rs:
coords.append(r.start)
coords.append(r.end)
coord_groups = []
cur_group = []
for coord in sorted(coords):
if not cur_group or coord - cur_group[-1] < max_intron_size:
cur_group.append(coord)
else:
coord_groups.append(cur_group)
cur_group = [coord]
if cur_group:
coord_groups.append(cur_group)
return coord_groups | [
"def",
"_group_coords",
"(",
"rs",
")",
":",
"max_intron_size",
"=",
"1e5",
"coords",
"=",
"[",
"]",
"for",
"r",
"in",
"rs",
":",
"coords",
".",
"append",
"(",
"r",
".",
"start",
")",
"coords",
".",
"append",
"(",
"r",
".",
"end",
")",
"coord_group... | Organize coordinate regions into groups for each transcript.
Avoids collapsing very large introns or repetitive genes spread across
the chromosome by limiting the intron size to 100kb for creating a single transcript | [
"Organize",
"coordinate",
"regions",
"into",
"groups",
"for",
"each",
"transcript",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L445-L466 |
237,372 | bcbio/bcbio-nextgen | bcbio/structural/regions.py | MemoizedSizes._calc_sizes | def _calc_sizes(self, cnv_file, items):
"""Retrieve target and antitarget bin sizes based on depth.
Similar to CNVkit's do_autobin but tries to have a standard set of
ranges (50bp intervals for target and 10kb intervals for antitarget).
"""
bp_per_bin = 100000 # same target as CNVkit
range_map = {"target": (100, 250), "antitarget": (10000, 1000000)}
target_bps = []
anti_bps = []
checked_beds = set([])
for data in items:
region_bed = tz.get_in(["depth", "variant_regions", "regions"], data)
if region_bed and region_bed not in checked_beds:
with utils.open_gzipsafe(region_bed) as in_handle:
for r in pybedtools.BedTool(in_handle).intersect(cnv_file):
if r.stop - r.start > range_map["target"][0]:
target_bps.append(float(r.name))
with utils.open_gzipsafe(region_bed) as in_handle:
for r in pybedtools.BedTool(in_handle).intersect(cnv_file, v=True):
if r.stop - r.start > range_map["target"][1]:
anti_bps.append(float(r.name))
checked_beds.add(region_bed)
def scale_in_boundary(raw, round_interval, range_targets):
min_val, max_val = range_targets
out = int(math.ceil(raw / float(round_interval)) * round_interval)
if out > max_val:
return max_val
elif out < min_val:
return min_val
else:
return out
if target_bps and np.median(target_bps) > 0:
raw_target_bin = bp_per_bin / float(np.median(target_bps))
target_bin = scale_in_boundary(raw_target_bin, 50, range_map["target"])
else:
target_bin = range_map["target"][1]
if anti_bps and np.median(anti_bps) > 0:
raw_anti_bin = bp_per_bin / float(np.median(anti_bps))
anti_bin = scale_in_boundary(raw_anti_bin, 10000, range_map["antitarget"])
else:
anti_bin = range_map["antitarget"][1]
return target_bin, anti_bin | python | def _calc_sizes(self, cnv_file, items):
bp_per_bin = 100000 # same target as CNVkit
range_map = {"target": (100, 250), "antitarget": (10000, 1000000)}
target_bps = []
anti_bps = []
checked_beds = set([])
for data in items:
region_bed = tz.get_in(["depth", "variant_regions", "regions"], data)
if region_bed and region_bed not in checked_beds:
with utils.open_gzipsafe(region_bed) as in_handle:
for r in pybedtools.BedTool(in_handle).intersect(cnv_file):
if r.stop - r.start > range_map["target"][0]:
target_bps.append(float(r.name))
with utils.open_gzipsafe(region_bed) as in_handle:
for r in pybedtools.BedTool(in_handle).intersect(cnv_file, v=True):
if r.stop - r.start > range_map["target"][1]:
anti_bps.append(float(r.name))
checked_beds.add(region_bed)
def scale_in_boundary(raw, round_interval, range_targets):
min_val, max_val = range_targets
out = int(math.ceil(raw / float(round_interval)) * round_interval)
if out > max_val:
return max_val
elif out < min_val:
return min_val
else:
return out
if target_bps and np.median(target_bps) > 0:
raw_target_bin = bp_per_bin / float(np.median(target_bps))
target_bin = scale_in_boundary(raw_target_bin, 50, range_map["target"])
else:
target_bin = range_map["target"][1]
if anti_bps and np.median(anti_bps) > 0:
raw_anti_bin = bp_per_bin / float(np.median(anti_bps))
anti_bin = scale_in_boundary(raw_anti_bin, 10000, range_map["antitarget"])
else:
anti_bin = range_map["antitarget"][1]
return target_bin, anti_bin | [
"def",
"_calc_sizes",
"(",
"self",
",",
"cnv_file",
",",
"items",
")",
":",
"bp_per_bin",
"=",
"100000",
"# same target as CNVkit",
"range_map",
"=",
"{",
"\"target\"",
":",
"(",
"100",
",",
"250",
")",
",",
"\"antitarget\"",
":",
"(",
"10000",
",",
"10000... | Retrieve target and antitarget bin sizes based on depth.
Similar to CNVkit's do_autobin but tries to have a standard set of
ranges (50bp intervals for target and 10kb intervals for antitarget). | [
"Retrieve",
"target",
"and",
"antitarget",
"bin",
"sizes",
"based",
"on",
"depth",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L98-L141 |
237,373 | bcbio/bcbio-nextgen | bcbio/hmmer/search.py | phmmer | def phmmer(**kwargs):
"""Search a protein sequence against a HMMER sequence database.
Arguments:
seq - The sequence to search -- a Fasta string.
seqdb -- Sequence database to search against.
range -- A string range of results to return (ie. 1,10 for the first ten)
output -- The output format (defaults to JSON).
"""
logging.debug(kwargs)
args = {'seq' : kwargs.get('seq'),
'seqdb' : kwargs.get('seqdb')}
args2 = {'output' : kwargs.get('output', 'json'),
'range' : kwargs.get('range')}
return _hmmer("http://hmmer.janelia.org/search/phmmer", args, args2) | python | def phmmer(**kwargs):
logging.debug(kwargs)
args = {'seq' : kwargs.get('seq'),
'seqdb' : kwargs.get('seqdb')}
args2 = {'output' : kwargs.get('output', 'json'),
'range' : kwargs.get('range')}
return _hmmer("http://hmmer.janelia.org/search/phmmer", args, args2) | [
"def",
"phmmer",
"(",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"debug",
"(",
"kwargs",
")",
"args",
"=",
"{",
"'seq'",
":",
"kwargs",
".",
"get",
"(",
"'seq'",
")",
",",
"'seqdb'",
":",
"kwargs",
".",
"get",
"(",
"'seqdb'",
")",
"}",
"args2"... | Search a protein sequence against a HMMER sequence database.
Arguments:
seq - The sequence to search -- a Fasta string.
seqdb -- Sequence database to search against.
range -- A string range of results to return (ie. 1,10 for the first ten)
output -- The output format (defaults to JSON). | [
"Search",
"a",
"protein",
"sequence",
"against",
"a",
"HMMER",
"sequence",
"database",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/hmmer/search.py#L40-L54 |
237,374 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | scrnaseq_concatenate_metadata | def scrnaseq_concatenate_metadata(samples):
"""
Create file same dimension than mtx.colnames
with metadata and sample name to help in the
creation of the SC object.
"""
barcodes = {}
counts = ""
metadata = {}
has_sample_barcodes = False
for sample in dd.sample_data_iterator(samples):
if dd.get_sample_barcodes(sample):
has_sample_barcodes = True
with open(dd.get_sample_barcodes(sample)) as inh:
for line in inh:
cols = line.strip().split(",")
if len(cols) == 1:
# Assign sample name in case of missing in barcodes
cols.append("NaN")
barcodes[(dd.get_sample_name(sample), cols[0])] = cols[1:]
else:
barcodes[(dd.get_sample_name(sample), "NaN")] = [dd.get_sample_name(sample), "NaN"]
counts = dd.get_combined_counts(sample)
meta = map(str, list(sample["metadata"].values()))
meta_cols = list(sample["metadata"].keys())
meta = ["NaN" if not v else v for v in meta]
metadata[dd.get_sample_name(sample)] = meta
metadata_fn = counts + ".metadata"
if file_exists(metadata_fn):
return samples
with file_transaction(metadata_fn) as tx_metadata_fn:
with open(tx_metadata_fn, 'w') as outh:
outh.write(",".join(["sample"] + meta_cols) + '\n')
with open(counts + ".colnames") as inh:
for line in inh:
sample = line.split(":")[0]
if has_sample_barcodes:
barcode = sample.split("-")[1]
else:
barcode = "NaN"
outh.write(",".join(barcodes[(sample, barcode)] + metadata[sample]) + '\n')
return samples | python | def scrnaseq_concatenate_metadata(samples):
barcodes = {}
counts = ""
metadata = {}
has_sample_barcodes = False
for sample in dd.sample_data_iterator(samples):
if dd.get_sample_barcodes(sample):
has_sample_barcodes = True
with open(dd.get_sample_barcodes(sample)) as inh:
for line in inh:
cols = line.strip().split(",")
if len(cols) == 1:
# Assign sample name in case of missing in barcodes
cols.append("NaN")
barcodes[(dd.get_sample_name(sample), cols[0])] = cols[1:]
else:
barcodes[(dd.get_sample_name(sample), "NaN")] = [dd.get_sample_name(sample), "NaN"]
counts = dd.get_combined_counts(sample)
meta = map(str, list(sample["metadata"].values()))
meta_cols = list(sample["metadata"].keys())
meta = ["NaN" if not v else v for v in meta]
metadata[dd.get_sample_name(sample)] = meta
metadata_fn = counts + ".metadata"
if file_exists(metadata_fn):
return samples
with file_transaction(metadata_fn) as tx_metadata_fn:
with open(tx_metadata_fn, 'w') as outh:
outh.write(",".join(["sample"] + meta_cols) + '\n')
with open(counts + ".colnames") as inh:
for line in inh:
sample = line.split(":")[0]
if has_sample_barcodes:
barcode = sample.split("-")[1]
else:
barcode = "NaN"
outh.write(",".join(barcodes[(sample, barcode)] + metadata[sample]) + '\n')
return samples | [
"def",
"scrnaseq_concatenate_metadata",
"(",
"samples",
")",
":",
"barcodes",
"=",
"{",
"}",
"counts",
"=",
"\"\"",
"metadata",
"=",
"{",
"}",
"has_sample_barcodes",
"=",
"False",
"for",
"sample",
"in",
"dd",
".",
"sample_data_iterator",
"(",
"samples",
")",
... | Create file same dimension than mtx.colnames
with metadata and sample name to help in the
creation of the SC object. | [
"Create",
"file",
"same",
"dimension",
"than",
"mtx",
".",
"colnames",
"with",
"metadata",
"and",
"sample",
"name",
"to",
"help",
"in",
"the",
"creation",
"of",
"the",
"SC",
"object",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L47-L90 |
237,375 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | rnaseq_variant_calling | def rnaseq_variant_calling(samples, run_parallel):
"""
run RNA-seq variant calling using GATK
"""
samples = run_parallel("run_rnaseq_variant_calling", samples)
variantcaller = dd.get_variantcaller(to_single_data(samples[0]))
if variantcaller and ("gatk-haplotype" in variantcaller):
out = []
for d in joint.square_off(samples, run_parallel):
out.extend([[to_single_data(xs)] for xs in multi.split_variants_by_sample(to_single_data(d))])
samples = out
if variantcaller:
samples = run_parallel("run_rnaseq_ann_filter", samples)
if variantcaller and ("gatk-haplotype" in variantcaller):
out = []
for data in (to_single_data(xs) for xs in samples):
if "variants" not in data:
data["variants"] = []
data["variants"].append({"variantcaller": "gatk-haplotype", "vcf": data["vrn_file_orig"],
"population": {"vcf": data["vrn_file"]}})
data["vrn_file"] = data.pop("vrn_file_orig")
out.append([data])
samples = out
return samples | python | def rnaseq_variant_calling(samples, run_parallel):
samples = run_parallel("run_rnaseq_variant_calling", samples)
variantcaller = dd.get_variantcaller(to_single_data(samples[0]))
if variantcaller and ("gatk-haplotype" in variantcaller):
out = []
for d in joint.square_off(samples, run_parallel):
out.extend([[to_single_data(xs)] for xs in multi.split_variants_by_sample(to_single_data(d))])
samples = out
if variantcaller:
samples = run_parallel("run_rnaseq_ann_filter", samples)
if variantcaller and ("gatk-haplotype" in variantcaller):
out = []
for data in (to_single_data(xs) for xs in samples):
if "variants" not in data:
data["variants"] = []
data["variants"].append({"variantcaller": "gatk-haplotype", "vcf": data["vrn_file_orig"],
"population": {"vcf": data["vrn_file"]}})
data["vrn_file"] = data.pop("vrn_file_orig")
out.append([data])
samples = out
return samples | [
"def",
"rnaseq_variant_calling",
"(",
"samples",
",",
"run_parallel",
")",
":",
"samples",
"=",
"run_parallel",
"(",
"\"run_rnaseq_variant_calling\"",
",",
"samples",
")",
"variantcaller",
"=",
"dd",
".",
"get_variantcaller",
"(",
"to_single_data",
"(",
"samples",
"... | run RNA-seq variant calling using GATK | [
"run",
"RNA",
"-",
"seq",
"variant",
"calling",
"using",
"GATK"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L92-L115 |
237,376 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | run_rnaseq_variant_calling | def run_rnaseq_variant_calling(data):
"""
run RNA-seq variant calling, variation file is stored in `vrn_file`
in the datadict
"""
variantcaller = dd.get_variantcaller(data)
if isinstance(variantcaller, list) and len(variantcaller) > 1:
logger.error("Only one variantcaller can be run for RNA-seq at "
"this time. Post an issue here "
"(https://github.com/bcbio/bcbio-nextgen/issues) "
"if this is something you need to do.")
sys.exit(1)
if variantcaller:
if "gatk-haplotype" in variantcaller:
data = variation.rnaseq_gatk_variant_calling(data)
if vardict.get_vardict_command(data):
data = variation.rnaseq_vardict_variant_calling(data)
vrn_file = dd.get_vrn_file(data)
return [[data]] | python | def run_rnaseq_variant_calling(data):
variantcaller = dd.get_variantcaller(data)
if isinstance(variantcaller, list) and len(variantcaller) > 1:
logger.error("Only one variantcaller can be run for RNA-seq at "
"this time. Post an issue here "
"(https://github.com/bcbio/bcbio-nextgen/issues) "
"if this is something you need to do.")
sys.exit(1)
if variantcaller:
if "gatk-haplotype" in variantcaller:
data = variation.rnaseq_gatk_variant_calling(data)
if vardict.get_vardict_command(data):
data = variation.rnaseq_vardict_variant_calling(data)
vrn_file = dd.get_vrn_file(data)
return [[data]] | [
"def",
"run_rnaseq_variant_calling",
"(",
"data",
")",
":",
"variantcaller",
"=",
"dd",
".",
"get_variantcaller",
"(",
"data",
")",
"if",
"isinstance",
"(",
"variantcaller",
",",
"list",
")",
"and",
"len",
"(",
"variantcaller",
")",
">",
"1",
":",
"logger",
... | run RNA-seq variant calling, variation file is stored in `vrn_file`
in the datadict | [
"run",
"RNA",
"-",
"seq",
"variant",
"calling",
"variation",
"file",
"is",
"stored",
"in",
"vrn_file",
"in",
"the",
"datadict"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L117-L136 |
237,377 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | run_rnaseq_ann_filter | def run_rnaseq_ann_filter(data):
"""Run RNA-seq annotation and filtering.
"""
data = to_single_data(data)
if dd.get_vrn_file(data):
eff_file = effects.add_to_vcf(dd.get_vrn_file(data), data)[0]
if eff_file:
data = dd.set_vrn_file(data, eff_file)
ann_file = population.run_vcfanno(dd.get_vrn_file(data), data)
if ann_file:
data = dd.set_vrn_file(data, ann_file)
variantcaller = dd.get_variantcaller(data)
if variantcaller and ("gatk-haplotype" in variantcaller):
filter_file = variation.gatk_filter_rnaseq(dd.get_vrn_file(data), data)
data = dd.set_vrn_file(data, filter_file)
# remove variants close to splice junctions
vrn_file = dd.get_vrn_file(data)
vrn_file = variation.filter_junction_variants(vrn_file, data)
data = dd.set_vrn_file(data, vrn_file)
return [[data]] | python | def run_rnaseq_ann_filter(data):
data = to_single_data(data)
if dd.get_vrn_file(data):
eff_file = effects.add_to_vcf(dd.get_vrn_file(data), data)[0]
if eff_file:
data = dd.set_vrn_file(data, eff_file)
ann_file = population.run_vcfanno(dd.get_vrn_file(data), data)
if ann_file:
data = dd.set_vrn_file(data, ann_file)
variantcaller = dd.get_variantcaller(data)
if variantcaller and ("gatk-haplotype" in variantcaller):
filter_file = variation.gatk_filter_rnaseq(dd.get_vrn_file(data), data)
data = dd.set_vrn_file(data, filter_file)
# remove variants close to splice junctions
vrn_file = dd.get_vrn_file(data)
vrn_file = variation.filter_junction_variants(vrn_file, data)
data = dd.set_vrn_file(data, vrn_file)
return [[data]] | [
"def",
"run_rnaseq_ann_filter",
"(",
"data",
")",
":",
"data",
"=",
"to_single_data",
"(",
"data",
")",
"if",
"dd",
".",
"get_vrn_file",
"(",
"data",
")",
":",
"eff_file",
"=",
"effects",
".",
"add_to_vcf",
"(",
"dd",
".",
"get_vrn_file",
"(",
"data",
")... | Run RNA-seq annotation and filtering. | [
"Run",
"RNA",
"-",
"seq",
"annotation",
"and",
"filtering",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L138-L157 |
237,378 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | quantitate | def quantitate(data):
"""CWL target for quantitation.
XXX Needs to be split and parallelized by expression caller, with merging
of multiple calls.
"""
data = to_single_data(to_single_data(data))
data = generate_transcript_counts(data)[0][0]
data["quant"] = {}
if "sailfish" in dd.get_expression_caller(data):
data = to_single_data(sailfish.run_sailfish(data)[0])
data["quant"]["tsv"] = data["sailfish"]
data["quant"]["hdf5"] = os.path.join(os.path.dirname(data["sailfish"]), "abundance.h5")
if ("kallisto" in dd.get_expression_caller(data) or "pizzly" in dd.get_fusion_caller(data, [])):
data = to_single_data(kallisto.run_kallisto_rnaseq(data)[0])
data["quant"]["tsv"] = os.path.join(data["kallisto_quant"], "abundance.tsv")
data["quant"]["hdf5"] = os.path.join(data["kallisto_quant"], "abundance.h5")
if (os.path.exists(os.path.join(data["kallisto_quant"], "fusion.txt"))):
data["quant"]["fusion"] = os.path.join(data["kallisto_quant"], "fusion.txt")
else:
data["quant"]["fusion"] = None
if "salmon" in dd.get_expression_caller(data):
data = to_single_data(salmon.run_salmon_reads(data)[0])
data["quant"]["tsv"] = data["salmon"]
data["quant"]["hdf5"] = os.path.join(os.path.dirname(data["salmon"]), "abundance.h5")
return [[data]] | python | def quantitate(data):
data = to_single_data(to_single_data(data))
data = generate_transcript_counts(data)[0][0]
data["quant"] = {}
if "sailfish" in dd.get_expression_caller(data):
data = to_single_data(sailfish.run_sailfish(data)[0])
data["quant"]["tsv"] = data["sailfish"]
data["quant"]["hdf5"] = os.path.join(os.path.dirname(data["sailfish"]), "abundance.h5")
if ("kallisto" in dd.get_expression_caller(data) or "pizzly" in dd.get_fusion_caller(data, [])):
data = to_single_data(kallisto.run_kallisto_rnaseq(data)[0])
data["quant"]["tsv"] = os.path.join(data["kallisto_quant"], "abundance.tsv")
data["quant"]["hdf5"] = os.path.join(data["kallisto_quant"], "abundance.h5")
if (os.path.exists(os.path.join(data["kallisto_quant"], "fusion.txt"))):
data["quant"]["fusion"] = os.path.join(data["kallisto_quant"], "fusion.txt")
else:
data["quant"]["fusion"] = None
if "salmon" in dd.get_expression_caller(data):
data = to_single_data(salmon.run_salmon_reads(data)[0])
data["quant"]["tsv"] = data["salmon"]
data["quant"]["hdf5"] = os.path.join(os.path.dirname(data["salmon"]), "abundance.h5")
return [[data]] | [
"def",
"quantitate",
"(",
"data",
")",
":",
"data",
"=",
"to_single_data",
"(",
"to_single_data",
"(",
"data",
")",
")",
"data",
"=",
"generate_transcript_counts",
"(",
"data",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"data",
"[",
"\"quant\"",
"]",
"=",
"{",... | CWL target for quantitation.
XXX Needs to be split and parallelized by expression caller, with merging
of multiple calls. | [
"CWL",
"target",
"for",
"quantitation",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L159-L184 |
237,379 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | quantitate_expression_parallel | def quantitate_expression_parallel(samples, run_parallel):
"""
quantitate expression, all programs run here should be multithreaded to
take advantage of the threaded run_parallel environment
"""
data = samples[0][0]
samples = run_parallel("generate_transcript_counts", samples)
if "cufflinks" in dd.get_expression_caller(data):
samples = run_parallel("run_cufflinks", samples)
if "stringtie" in dd.get_expression_caller(data):
samples = run_parallel("run_stringtie_expression", samples)
if ("kallisto" in dd.get_expression_caller(data) or
dd.get_fusion_mode(data) or
"pizzly" in dd.get_fusion_caller(data, [])):
samples = run_parallel("run_kallisto_index", [samples])
samples = run_parallel("run_kallisto_rnaseq", samples)
if "sailfish" in dd.get_expression_caller(data):
samples = run_parallel("run_sailfish_index", [samples])
samples = run_parallel("run_sailfish", samples)
# always run salmon
samples = run_parallel("run_salmon_index", [samples])
samples = run_parallel("run_salmon_reads", samples)
samples = run_parallel("detect_fusions", samples)
return samples | python | def quantitate_expression_parallel(samples, run_parallel):
data = samples[0][0]
samples = run_parallel("generate_transcript_counts", samples)
if "cufflinks" in dd.get_expression_caller(data):
samples = run_parallel("run_cufflinks", samples)
if "stringtie" in dd.get_expression_caller(data):
samples = run_parallel("run_stringtie_expression", samples)
if ("kallisto" in dd.get_expression_caller(data) or
dd.get_fusion_mode(data) or
"pizzly" in dd.get_fusion_caller(data, [])):
samples = run_parallel("run_kallisto_index", [samples])
samples = run_parallel("run_kallisto_rnaseq", samples)
if "sailfish" in dd.get_expression_caller(data):
samples = run_parallel("run_sailfish_index", [samples])
samples = run_parallel("run_sailfish", samples)
# always run salmon
samples = run_parallel("run_salmon_index", [samples])
samples = run_parallel("run_salmon_reads", samples)
samples = run_parallel("detect_fusions", samples)
return samples | [
"def",
"quantitate_expression_parallel",
"(",
"samples",
",",
"run_parallel",
")",
":",
"data",
"=",
"samples",
"[",
"0",
"]",
"[",
"0",
"]",
"samples",
"=",
"run_parallel",
"(",
"\"generate_transcript_counts\"",
",",
"samples",
")",
"if",
"\"cufflinks\"",
"in",... | quantitate expression, all programs run here should be multithreaded to
take advantage of the threaded run_parallel environment | [
"quantitate",
"expression",
"all",
"programs",
"run",
"here",
"should",
"be",
"multithreaded",
"to",
"take",
"advantage",
"of",
"the",
"threaded",
"run_parallel",
"environment"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L186-L210 |
237,380 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | quantitate_expression_noparallel | def quantitate_expression_noparallel(samples, run_parallel):
"""
run transcript quantitation for algorithms that don't run in parallel
"""
data = samples[0][0]
if "express" in dd.get_expression_caller(data):
samples = run_parallel("run_express", samples)
if "dexseq" in dd.get_expression_caller(data):
samples = run_parallel("run_dexseq", samples)
return samples | python | def quantitate_expression_noparallel(samples, run_parallel):
data = samples[0][0]
if "express" in dd.get_expression_caller(data):
samples = run_parallel("run_express", samples)
if "dexseq" in dd.get_expression_caller(data):
samples = run_parallel("run_dexseq", samples)
return samples | [
"def",
"quantitate_expression_noparallel",
"(",
"samples",
",",
"run_parallel",
")",
":",
"data",
"=",
"samples",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"\"express\"",
"in",
"dd",
".",
"get_expression_caller",
"(",
"data",
")",
":",
"samples",
"=",
"run_paralle... | run transcript quantitation for algorithms that don't run in parallel | [
"run",
"transcript",
"quantitation",
"for",
"algorithms",
"that",
"don",
"t",
"run",
"in",
"parallel"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L236-L245 |
237,381 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | generate_transcript_counts | def generate_transcript_counts(data):
"""Generate counts per transcript and per exon from an alignment"""
data["count_file"] = featureCounts.count(data)
if dd.get_fusion_mode(data, False) and not dd.get_fusion_caller(data):
oncofuse_file = oncofuse.run(data)
if oncofuse_file:
data = dd.set_oncofuse_file(data, oncofuse_file)
if dd.get_transcriptome_align(data):
# to create a disambiguated transcriptome file realign with bowtie2
if dd.get_disambiguate(data):
logger.info("Aligning to the transcriptome with bowtie2 using the "
"disambiguated reads.")
bam_path = data["work_bam"]
fastq_paths = alignprep._bgzip_from_bam(bam_path, data["dirs"], data, is_retry=False, output_infix='-transcriptome')
if len(fastq_paths) == 2:
file1, file2 = fastq_paths
else:
file1, file2 = fastq_paths[0], None
ref_file = dd.get_ref_file(data)
data = bowtie2.align_transcriptome(file1, file2, ref_file, data)
else:
file1, file2 = dd.get_input_sequence_files(data)
if not dd.get_transcriptome_bam(data):
ref_file = dd.get_ref_file(data)
logger.info("Transcriptome alignment was flagged to run, but the "
"transcriptome BAM file was not found. Aligning to the "
"transcriptome with bowtie2.")
data = bowtie2.align_transcriptome(file1, file2, ref_file, data)
data = spikein.counts_spikein(data)
return [[data]] | python | def generate_transcript_counts(data):
data["count_file"] = featureCounts.count(data)
if dd.get_fusion_mode(data, False) and not dd.get_fusion_caller(data):
oncofuse_file = oncofuse.run(data)
if oncofuse_file:
data = dd.set_oncofuse_file(data, oncofuse_file)
if dd.get_transcriptome_align(data):
# to create a disambiguated transcriptome file realign with bowtie2
if dd.get_disambiguate(data):
logger.info("Aligning to the transcriptome with bowtie2 using the "
"disambiguated reads.")
bam_path = data["work_bam"]
fastq_paths = alignprep._bgzip_from_bam(bam_path, data["dirs"], data, is_retry=False, output_infix='-transcriptome')
if len(fastq_paths) == 2:
file1, file2 = fastq_paths
else:
file1, file2 = fastq_paths[0], None
ref_file = dd.get_ref_file(data)
data = bowtie2.align_transcriptome(file1, file2, ref_file, data)
else:
file1, file2 = dd.get_input_sequence_files(data)
if not dd.get_transcriptome_bam(data):
ref_file = dd.get_ref_file(data)
logger.info("Transcriptome alignment was flagged to run, but the "
"transcriptome BAM file was not found. Aligning to the "
"transcriptome with bowtie2.")
data = bowtie2.align_transcriptome(file1, file2, ref_file, data)
data = spikein.counts_spikein(data)
return [[data]] | [
"def",
"generate_transcript_counts",
"(",
"data",
")",
":",
"data",
"[",
"\"count_file\"",
"]",
"=",
"featureCounts",
".",
"count",
"(",
"data",
")",
"if",
"dd",
".",
"get_fusion_mode",
"(",
"data",
",",
"False",
")",
"and",
"not",
"dd",
".",
"get_fusion_c... | Generate counts per transcript and per exon from an alignment | [
"Generate",
"counts",
"per",
"transcript",
"and",
"per",
"exon",
"from",
"an",
"alignment"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L247-L278 |
237,382 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | run_dexseq | def run_dexseq(data):
"""Quantitate exon-level counts with DEXSeq"""
if dd.get_dexseq_gff(data, None):
data = dexseq.bcbio_run(data)
return [[data]] | python | def run_dexseq(data):
if dd.get_dexseq_gff(data, None):
data = dexseq.bcbio_run(data)
return [[data]] | [
"def",
"run_dexseq",
"(",
"data",
")",
":",
"if",
"dd",
".",
"get_dexseq_gff",
"(",
"data",
",",
"None",
")",
":",
"data",
"=",
"dexseq",
".",
"bcbio_run",
"(",
"data",
")",
"return",
"[",
"[",
"data",
"]",
"]"
] | Quantitate exon-level counts with DEXSeq | [
"Quantitate",
"exon",
"-",
"level",
"counts",
"with",
"DEXSeq"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L285-L289 |
237,383 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | combine_express | def combine_express(samples, combined):
"""Combine tpm, effective counts and fpkm from express results"""
if not combined:
return None
to_combine = [dd.get_express_counts(x) for x in
dd.sample_data_iterator(samples) if dd.get_express_counts(x)]
gtf_file = dd.get_gtf_file(samples[0][0])
isoform_to_gene_file = os.path.join(os.path.dirname(combined), "isoform_to_gene.txt")
isoform_to_gene_file = express.isoform_to_gene_name(
gtf_file, isoform_to_gene_file, next(dd.sample_data_iterator(samples)))
if len(to_combine) > 0:
eff_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_counts"
eff_counts_combined = count.combine_count_files(to_combine, eff_counts_combined_file, ext=".counts")
to_combine = [dd.get_express_tpm(x) for x in
dd.sample_data_iterator(samples) if dd.get_express_tpm(x)]
tpm_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_tpm"
tpm_counts_combined = count.combine_count_files(to_combine, tpm_counts_combined_file)
to_combine = [dd.get_express_fpkm(x) for x in dd.sample_data_iterator(samples)
if dd.get_express_fpkm(x)]
fpkm_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_fpkm"
fpkm_counts_combined = count.combine_count_files(to_combine, fpkm_counts_combined_file, ext=".fpkm")
return {'counts': eff_counts_combined, 'tpm': tpm_counts_combined,
'fpkm': fpkm_counts_combined, 'isoform_to_gene': isoform_to_gene_file}
return {} | python | def combine_express(samples, combined):
if not combined:
return None
to_combine = [dd.get_express_counts(x) for x in
dd.sample_data_iterator(samples) if dd.get_express_counts(x)]
gtf_file = dd.get_gtf_file(samples[0][0])
isoform_to_gene_file = os.path.join(os.path.dirname(combined), "isoform_to_gene.txt")
isoform_to_gene_file = express.isoform_to_gene_name(
gtf_file, isoform_to_gene_file, next(dd.sample_data_iterator(samples)))
if len(to_combine) > 0:
eff_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_counts"
eff_counts_combined = count.combine_count_files(to_combine, eff_counts_combined_file, ext=".counts")
to_combine = [dd.get_express_tpm(x) for x in
dd.sample_data_iterator(samples) if dd.get_express_tpm(x)]
tpm_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_tpm"
tpm_counts_combined = count.combine_count_files(to_combine, tpm_counts_combined_file)
to_combine = [dd.get_express_fpkm(x) for x in dd.sample_data_iterator(samples)
if dd.get_express_fpkm(x)]
fpkm_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_fpkm"
fpkm_counts_combined = count.combine_count_files(to_combine, fpkm_counts_combined_file, ext=".fpkm")
return {'counts': eff_counts_combined, 'tpm': tpm_counts_combined,
'fpkm': fpkm_counts_combined, 'isoform_to_gene': isoform_to_gene_file}
return {} | [
"def",
"combine_express",
"(",
"samples",
",",
"combined",
")",
":",
"if",
"not",
"combined",
":",
"return",
"None",
"to_combine",
"=",
"[",
"dd",
".",
"get_express_counts",
"(",
"x",
")",
"for",
"x",
"in",
"dd",
".",
"sample_data_iterator",
"(",
"samples"... | Combine tpm, effective counts and fpkm from express results | [
"Combine",
"tpm",
"effective",
"counts",
"and",
"fpkm",
"from",
"express",
"results"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L296-L319 |
237,384 | bcbio/bcbio-nextgen | bcbio/pipeline/rnaseq.py | run_cufflinks | def run_cufflinks(data):
"""Quantitate transcript expression with Cufflinks"""
if "cufflinks" in dd.get_tools_off(data):
return [[data]]
work_bam = dd.get_work_bam(data)
ref_file = dd.get_sam_ref(data)
out_dir, fpkm_file, fpkm_isoform_file = cufflinks.run(work_bam, ref_file, data)
data = dd.set_cufflinks_dir(data, out_dir)
data = dd.set_fpkm(data, fpkm_file)
data = dd.set_fpkm_isoform(data, fpkm_isoform_file)
return [[data]] | python | def run_cufflinks(data):
if "cufflinks" in dd.get_tools_off(data):
return [[data]]
work_bam = dd.get_work_bam(data)
ref_file = dd.get_sam_ref(data)
out_dir, fpkm_file, fpkm_isoform_file = cufflinks.run(work_bam, ref_file, data)
data = dd.set_cufflinks_dir(data, out_dir)
data = dd.set_fpkm(data, fpkm_file)
data = dd.set_fpkm_isoform(data, fpkm_isoform_file)
return [[data]] | [
"def",
"run_cufflinks",
"(",
"data",
")",
":",
"if",
"\"cufflinks\"",
"in",
"dd",
".",
"get_tools_off",
"(",
"data",
")",
":",
"return",
"[",
"[",
"data",
"]",
"]",
"work_bam",
"=",
"dd",
".",
"get_work_bam",
"(",
"data",
")",
"ref_file",
"=",
"dd",
... | Quantitate transcript expression with Cufflinks | [
"Quantitate",
"transcript",
"expression",
"with",
"Cufflinks"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L321-L331 |
237,385 | bcbio/bcbio-nextgen | bcbio/rnaseq/express.py | run | def run(data):
"""Quantitaive isoforms expression by eXpress"""
name = dd.get_sample_name(data)
in_bam = dd.get_transcriptome_bam(data)
config = data['config']
if not in_bam:
logger.info("Transcriptome-mapped BAM file not found, skipping eXpress.")
return data
out_dir = os.path.join(dd.get_work_dir(data), "express", name)
out_file = os.path.join(out_dir, name + ".xprs")
express = config_utils.get_program("express", data['config'])
strand = _set_stranded_flag(in_bam, data)
if not file_exists(out_file):
gtf_fasta = gtf.gtf_to_fasta(dd.get_gtf_file(data), dd.get_ref_file(data))
with tx_tmpdir(data) as tmp_dir:
with file_transaction(data, out_dir) as tx_out_dir:
bam_file = _prepare_bam_file(in_bam, tmp_dir, config)
cmd = ("{express} --no-update-check -o {tx_out_dir} {strand} {gtf_fasta} {bam_file}")
do.run(cmd.format(**locals()), "Run express on %s." % in_bam, {})
shutil.move(os.path.join(out_dir, "results.xprs"), out_file)
eff_count_file = _get_column(out_file, out_file.replace(".xprs", "_eff.counts"), 7, data=data)
tpm_file = _get_column(out_file, out_file.replace("xprs", "tpm"), 14, data=data)
fpkm_file = _get_column(out_file, out_file.replace("xprs", "fpkm"), 10, data=data)
data = dd.set_express_counts(data, eff_count_file)
data = dd.set_express_tpm(data, tpm_file)
data = dd.set_express_fpkm(data, fpkm_file)
return data | python | def run(data):
name = dd.get_sample_name(data)
in_bam = dd.get_transcriptome_bam(data)
config = data['config']
if not in_bam:
logger.info("Transcriptome-mapped BAM file not found, skipping eXpress.")
return data
out_dir = os.path.join(dd.get_work_dir(data), "express", name)
out_file = os.path.join(out_dir, name + ".xprs")
express = config_utils.get_program("express", data['config'])
strand = _set_stranded_flag(in_bam, data)
if not file_exists(out_file):
gtf_fasta = gtf.gtf_to_fasta(dd.get_gtf_file(data), dd.get_ref_file(data))
with tx_tmpdir(data) as tmp_dir:
with file_transaction(data, out_dir) as tx_out_dir:
bam_file = _prepare_bam_file(in_bam, tmp_dir, config)
cmd = ("{express} --no-update-check -o {tx_out_dir} {strand} {gtf_fasta} {bam_file}")
do.run(cmd.format(**locals()), "Run express on %s." % in_bam, {})
shutil.move(os.path.join(out_dir, "results.xprs"), out_file)
eff_count_file = _get_column(out_file, out_file.replace(".xprs", "_eff.counts"), 7, data=data)
tpm_file = _get_column(out_file, out_file.replace("xprs", "tpm"), 14, data=data)
fpkm_file = _get_column(out_file, out_file.replace("xprs", "fpkm"), 10, data=data)
data = dd.set_express_counts(data, eff_count_file)
data = dd.set_express_tpm(data, tpm_file)
data = dd.set_express_fpkm(data, fpkm_file)
return data | [
"def",
"run",
"(",
"data",
")",
":",
"name",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"in_bam",
"=",
"dd",
".",
"get_transcriptome_bam",
"(",
"data",
")",
"config",
"=",
"data",
"[",
"'config'",
"]",
"if",
"not",
"in_bam",
":",
"logger",
... | Quantitaive isoforms expression by eXpress | [
"Quantitaive",
"isoforms",
"expression",
"by",
"eXpress"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/express.py#L13-L39 |
237,386 | bcbio/bcbio-nextgen | bcbio/rnaseq/express.py | _get_column | def _get_column(in_file, out_file, column, data=None):
"""Subset one column from a file
"""
with file_transaction(data, out_file) as tx_out_file:
with open(in_file) as in_handle:
with open(tx_out_file, 'w') as out_handle:
for line in in_handle:
cols = line.strip().split("\t")
if line.find("eff_count") > 0:
continue
number = cols[column]
if column == 7:
number = int(round(float(number), 0))
out_handle.write("%s\t%s\n" % (cols[1], number))
return out_file | python | def _get_column(in_file, out_file, column, data=None):
with file_transaction(data, out_file) as tx_out_file:
with open(in_file) as in_handle:
with open(tx_out_file, 'w') as out_handle:
for line in in_handle:
cols = line.strip().split("\t")
if line.find("eff_count") > 0:
continue
number = cols[column]
if column == 7:
number = int(round(float(number), 0))
out_handle.write("%s\t%s\n" % (cols[1], number))
return out_file | [
"def",
"_get_column",
"(",
"in_file",
",",
"out_file",
",",
"column",
",",
"data",
"=",
"None",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"with",
"open",
"(",
"in_file",
")",
"as",
"in_handle",
":"... | Subset one column from a file | [
"Subset",
"one",
"column",
"from",
"a",
"file"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/express.py#L41-L55 |
237,387 | bcbio/bcbio-nextgen | bcbio/rnaseq/express.py | _prepare_bam_file | def _prepare_bam_file(bam_file, tmp_dir, config):
"""
Pipe sort by name cmd in case sort by coordinates
"""
sort_mode = _get_sort_order(bam_file, config)
if sort_mode != "queryname":
bam_file = sort(bam_file, config, "queryname")
return bam_file | python | def _prepare_bam_file(bam_file, tmp_dir, config):
sort_mode = _get_sort_order(bam_file, config)
if sort_mode != "queryname":
bam_file = sort(bam_file, config, "queryname")
return bam_file | [
"def",
"_prepare_bam_file",
"(",
"bam_file",
",",
"tmp_dir",
",",
"config",
")",
":",
"sort_mode",
"=",
"_get_sort_order",
"(",
"bam_file",
",",
"config",
")",
"if",
"sort_mode",
"!=",
"\"queryname\"",
":",
"bam_file",
"=",
"sort",
"(",
"bam_file",
",",
"con... | Pipe sort by name cmd in case sort by coordinates | [
"Pipe",
"sort",
"by",
"name",
"cmd",
"in",
"case",
"sort",
"by",
"coordinates"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/express.py#L72-L79 |
237,388 | bcbio/bcbio-nextgen | bcbio/rnaseq/express.py | isoform_to_gene_name | def isoform_to_gene_name(gtf_file, out_file, data):
"""
produce a table of isoform -> gene mappings for loading into EBSeq
"""
if not out_file:
out_file = tempfile.NamedTemporaryFile(delete=False).name
if file_exists(out_file):
return out_file
db = gtf.get_gtf_db(gtf_file)
line_format = "{transcript}\t{gene}\n"
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for feature in db.features_of_type('transcript'):
transcript = feature['transcript_id'][0]
gene = feature['gene_id'][0]
out_handle.write(line_format.format(**locals()))
return out_file | python | def isoform_to_gene_name(gtf_file, out_file, data):
if not out_file:
out_file = tempfile.NamedTemporaryFile(delete=False).name
if file_exists(out_file):
return out_file
db = gtf.get_gtf_db(gtf_file)
line_format = "{transcript}\t{gene}\n"
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for feature in db.features_of_type('transcript'):
transcript = feature['transcript_id'][0]
gene = feature['gene_id'][0]
out_handle.write(line_format.format(**locals()))
return out_file | [
"def",
"isoform_to_gene_name",
"(",
"gtf_file",
",",
"out_file",
",",
"data",
")",
":",
"if",
"not",
"out_file",
":",
"out_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
".",
"name",
"if",
"file_exists",
"(",
"out_file",... | produce a table of isoform -> gene mappings for loading into EBSeq | [
"produce",
"a",
"table",
"of",
"isoform",
"-",
">",
"gene",
"mappings",
"for",
"loading",
"into",
"EBSeq"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/express.py#L81-L97 |
237,389 | bcbio/bcbio-nextgen | bcbio/variation/samtools.py | shared_variantcall | def shared_variantcall(call_fn, name, align_bams, ref_file, items,
assoc_files, region=None, out_file=None):
"""Provide base functionality for prepping and indexing for variant calling.
"""
config = items[0]["config"]
if out_file is None:
if vcfutils.is_paired_analysis(align_bams, items):
out_file = "%s-paired-variants.vcf.gz" % config["metdata"]["batch"]
else:
out_file = "%s-variants.vcf.gz" % os.path.splitext(align_bams[0])[0]
if not file_exists(out_file):
logger.debug("Genotyping with {name}: {region} {fname}".format(
name=name, region=region, fname=os.path.basename(align_bams[0])))
variant_regions = bedutils.population_variant_regions(items, merged=True)
target_regions = subset_variant_regions(variant_regions, region, out_file, items=items)
if (variant_regions is not None and isinstance(target_regions, six.string_types)
and not os.path.isfile(target_regions)):
vcfutils.write_empty_vcf(out_file, config)
else:
with file_transaction(config, out_file) as tx_out_file:
call_fn(align_bams, ref_file, items, target_regions,
tx_out_file)
if out_file.endswith(".gz"):
out_file = vcfutils.bgzip_and_index(out_file, config)
return out_file | python | def shared_variantcall(call_fn, name, align_bams, ref_file, items,
assoc_files, region=None, out_file=None):
config = items[0]["config"]
if out_file is None:
if vcfutils.is_paired_analysis(align_bams, items):
out_file = "%s-paired-variants.vcf.gz" % config["metdata"]["batch"]
else:
out_file = "%s-variants.vcf.gz" % os.path.splitext(align_bams[0])[0]
if not file_exists(out_file):
logger.debug("Genotyping with {name}: {region} {fname}".format(
name=name, region=region, fname=os.path.basename(align_bams[0])))
variant_regions = bedutils.population_variant_regions(items, merged=True)
target_regions = subset_variant_regions(variant_regions, region, out_file, items=items)
if (variant_regions is not None and isinstance(target_regions, six.string_types)
and not os.path.isfile(target_regions)):
vcfutils.write_empty_vcf(out_file, config)
else:
with file_transaction(config, out_file) as tx_out_file:
call_fn(align_bams, ref_file, items, target_regions,
tx_out_file)
if out_file.endswith(".gz"):
out_file = vcfutils.bgzip_and_index(out_file, config)
return out_file | [
"def",
"shared_variantcall",
"(",
"call_fn",
",",
"name",
",",
"align_bams",
",",
"ref_file",
",",
"items",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
... | Provide base functionality for prepping and indexing for variant calling. | [
"Provide",
"base",
"functionality",
"for",
"prepping",
"and",
"indexing",
"for",
"variant",
"calling",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/samtools.py#L19-L43 |
237,390 | bcbio/bcbio-nextgen | bcbio/variation/samtools.py | run_samtools | def run_samtools(align_bams, items, ref_file, assoc_files, region=None,
out_file=None):
"""Detect SNPs and indels with samtools mpileup and bcftools.
"""
return shared_variantcall(_call_variants_samtools, "samtools", align_bams, ref_file,
items, assoc_files, region, out_file) | python | def run_samtools(align_bams, items, ref_file, assoc_files, region=None,
out_file=None):
return shared_variantcall(_call_variants_samtools, "samtools", align_bams, ref_file,
items, assoc_files, region, out_file) | [
"def",
"run_samtools",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"return",
"shared_variantcall",
"(",
"_call_variants_samtools",
",",
"\"samtools\"",
",",
"align_bams... | Detect SNPs and indels with samtools mpileup and bcftools. | [
"Detect",
"SNPs",
"and",
"indels",
"with",
"samtools",
"mpileup",
"and",
"bcftools",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/samtools.py#L45-L50 |
237,391 | bcbio/bcbio-nextgen | bcbio/variation/samtools.py | _call_variants_samtools | def _call_variants_samtools(align_bams, ref_file, items, target_regions, tx_out_file):
"""Call variants with samtools in target_regions.
Works around a GATK VCF 4.2 compatibility issue in samtools 1.0
by removing addition 4.2-only isms from VCF header lines.
"""
config = items[0]["config"]
mpileup = prep_mpileup(align_bams, ref_file, config,
target_regions=target_regions, want_bcf=True)
bcftools = config_utils.get_program("bcftools", config)
samtools_version = programs.get_version("samtools", config=config)
if samtools_version and LooseVersion(samtools_version) <= LooseVersion("0.1.19"):
raise ValueError("samtools calling not supported with pre-1.0 samtools")
bcftools_opts = "call -v -m"
compress_cmd = "| bgzip -c" if tx_out_file.endswith(".gz") else ""
fix_ambig_ref = vcfutils.fix_ambiguous_cl()
fix_ambig_alt = vcfutils.fix_ambiguous_cl(5)
cmd = ("{mpileup} "
"| {bcftools} {bcftools_opts} - "
"| {fix_ambig_ref} | {fix_ambig_alt} "
"| vt normalize -n -q -r {ref_file} - "
"| sed 's/VCFv4.2/VCFv4.1/' "
"| sed 's/,Version=3>/>/' "
"| sed 's/,Version=\"3\">/>/' "
"| sed 's/Number=R/Number=./' "
"{compress_cmd} > {tx_out_file}")
do.run(cmd.format(**locals()), "Variant calling with samtools", items[0]) | python | def _call_variants_samtools(align_bams, ref_file, items, target_regions, tx_out_file):
config = items[0]["config"]
mpileup = prep_mpileup(align_bams, ref_file, config,
target_regions=target_regions, want_bcf=True)
bcftools = config_utils.get_program("bcftools", config)
samtools_version = programs.get_version("samtools", config=config)
if samtools_version and LooseVersion(samtools_version) <= LooseVersion("0.1.19"):
raise ValueError("samtools calling not supported with pre-1.0 samtools")
bcftools_opts = "call -v -m"
compress_cmd = "| bgzip -c" if tx_out_file.endswith(".gz") else ""
fix_ambig_ref = vcfutils.fix_ambiguous_cl()
fix_ambig_alt = vcfutils.fix_ambiguous_cl(5)
cmd = ("{mpileup} "
"| {bcftools} {bcftools_opts} - "
"| {fix_ambig_ref} | {fix_ambig_alt} "
"| vt normalize -n -q -r {ref_file} - "
"| sed 's/VCFv4.2/VCFv4.1/' "
"| sed 's/,Version=3>/>/' "
"| sed 's/,Version=\"3\">/>/' "
"| sed 's/Number=R/Number=./' "
"{compress_cmd} > {tx_out_file}")
do.run(cmd.format(**locals()), "Variant calling with samtools", items[0]) | [
"def",
"_call_variants_samtools",
"(",
"align_bams",
",",
"ref_file",
",",
"items",
",",
"target_regions",
",",
"tx_out_file",
")",
":",
"config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
"mpileup",
"=",
"prep_mpileup",
"(",
"align_bams",
",",
"r... | Call variants with samtools in target_regions.
Works around a GATK VCF 4.2 compatibility issue in samtools 1.0
by removing addition 4.2-only isms from VCF header lines. | [
"Call",
"variants",
"with",
"samtools",
"in",
"target_regions",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/samtools.py#L68-L94 |
237,392 | bcbio/bcbio-nextgen | bcbio/pipeline/sra.py | _convert_fastq | def _convert_fastq(srafn, outdir, single=False):
"convert sra to fastq"
cmd = "fastq-dump --split-files --gzip {srafn}"
cmd = "%s %s" % (utils.local_path_export(), cmd)
sraid = os.path.basename(utils.splitext_plus(srafn)[0])
if not srafn:
return None
if not single:
out_file = [os.path.join(outdir, "%s_1.fastq.gz" % sraid),
os.path.join(outdir, "%s_2.fastq.gz" % sraid)]
if not utils.file_exists(out_file[0]):
with utils.chdir(outdir):
do.run(cmd.format(**locals()), "Covert to fastq %s" % sraid)
if not utils.file_exists(out_file[0]):
raise IOError("SRA %s didn't convert, something happened." % srafn)
return [out for out in out_file if utils.file_exists(out)]
else:
raise ValueError("Not supported single-end sra samples for now.") | python | def _convert_fastq(srafn, outdir, single=False):
"convert sra to fastq"
cmd = "fastq-dump --split-files --gzip {srafn}"
cmd = "%s %s" % (utils.local_path_export(), cmd)
sraid = os.path.basename(utils.splitext_plus(srafn)[0])
if not srafn:
return None
if not single:
out_file = [os.path.join(outdir, "%s_1.fastq.gz" % sraid),
os.path.join(outdir, "%s_2.fastq.gz" % sraid)]
if not utils.file_exists(out_file[0]):
with utils.chdir(outdir):
do.run(cmd.format(**locals()), "Covert to fastq %s" % sraid)
if not utils.file_exists(out_file[0]):
raise IOError("SRA %s didn't convert, something happened." % srafn)
return [out for out in out_file if utils.file_exists(out)]
else:
raise ValueError("Not supported single-end sra samples for now.") | [
"def",
"_convert_fastq",
"(",
"srafn",
",",
"outdir",
",",
"single",
"=",
"False",
")",
":",
"cmd",
"=",
"\"fastq-dump --split-files --gzip {srafn}\"",
"cmd",
"=",
"\"%s %s\"",
"%",
"(",
"utils",
".",
"local_path_export",
"(",
")",
",",
"cmd",
")",
"sraid",
... | convert sra to fastq | [
"convert",
"sra",
"to",
"fastq"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sra.py#L119-L136 |
237,393 | bcbio/bcbio-nextgen | bcbio/illumina/machine.py | check_and_postprocess | def check_and_postprocess(args):
"""Check for newly dumped sequencer output, post-processing and transferring.
"""
with open(args.process_config) as in_handle:
config = yaml.safe_load(in_handle)
setup_local_logging(config)
for dname in _find_unprocessed(config):
lane_details = nglims.get_runinfo(config["galaxy_url"], config["galaxy_apikey"], dname,
utils.get_in(config, ("process", "storedir")))
if isinstance(lane_details, dict) and "error" in lane_details:
print("Flowcell not found in Galaxy: %s" % lane_details)
else:
lane_details = _tweak_lane(lane_details, dname)
fcid_ss = samplesheet.from_flowcell(dname, lane_details)
_update_reported(config["msg_db"], dname)
fastq_dir = demultiplex.run_bcl2fastq(dname, fcid_ss, config)
bcbio_config, ready_fastq_dir = nglims.prep_samples_and_config(dname, lane_details, fastq_dir, config)
transfer.copy_flowcell(dname, ready_fastq_dir, bcbio_config, config)
_start_processing(dname, bcbio_config, config) | python | def check_and_postprocess(args):
with open(args.process_config) as in_handle:
config = yaml.safe_load(in_handle)
setup_local_logging(config)
for dname in _find_unprocessed(config):
lane_details = nglims.get_runinfo(config["galaxy_url"], config["galaxy_apikey"], dname,
utils.get_in(config, ("process", "storedir")))
if isinstance(lane_details, dict) and "error" in lane_details:
print("Flowcell not found in Galaxy: %s" % lane_details)
else:
lane_details = _tweak_lane(lane_details, dname)
fcid_ss = samplesheet.from_flowcell(dname, lane_details)
_update_reported(config["msg_db"], dname)
fastq_dir = demultiplex.run_bcl2fastq(dname, fcid_ss, config)
bcbio_config, ready_fastq_dir = nglims.prep_samples_and_config(dname, lane_details, fastq_dir, config)
transfer.copy_flowcell(dname, ready_fastq_dir, bcbio_config, config)
_start_processing(dname, bcbio_config, config) | [
"def",
"check_and_postprocess",
"(",
"args",
")",
":",
"with",
"open",
"(",
"args",
".",
"process_config",
")",
"as",
"in_handle",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"in_handle",
")",
"setup_local_logging",
"(",
"config",
")",
"for",
"dname",... | Check for newly dumped sequencer output, post-processing and transferring. | [
"Check",
"for",
"newly",
"dumped",
"sequencer",
"output",
"post",
"-",
"processing",
"and",
"transferring",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L22-L40 |
237,394 | bcbio/bcbio-nextgen | bcbio/illumina/machine.py | _tweak_lane | def _tweak_lane(lane_details, dname):
"""Potentially tweak lane information to handle custom processing, reading a lane_config.yaml file.
"""
tweak_config_file = os.path.join(dname, "lane_config.yaml")
if os.path.exists(tweak_config_file):
with open(tweak_config_file) as in_handle:
tweak_config = yaml.safe_load(in_handle)
if tweak_config.get("uniquify_lanes"):
out = []
for ld in lane_details:
ld["name"] = "%s-%s" % (ld["name"], ld["lane"])
out.append(ld)
return out
return lane_details | python | def _tweak_lane(lane_details, dname):
tweak_config_file = os.path.join(dname, "lane_config.yaml")
if os.path.exists(tweak_config_file):
with open(tweak_config_file) as in_handle:
tweak_config = yaml.safe_load(in_handle)
if tweak_config.get("uniquify_lanes"):
out = []
for ld in lane_details:
ld["name"] = "%s-%s" % (ld["name"], ld["lane"])
out.append(ld)
return out
return lane_details | [
"def",
"_tweak_lane",
"(",
"lane_details",
",",
"dname",
")",
":",
"tweak_config_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dname",
",",
"\"lane_config.yaml\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"tweak_config_file",
")",
":",
"with",... | Potentially tweak lane information to handle custom processing, reading a lane_config.yaml file. | [
"Potentially",
"tweak",
"lane",
"information",
"to",
"handle",
"custom",
"processing",
"reading",
"a",
"lane_config",
".",
"yaml",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L42-L55 |
237,395 | bcbio/bcbio-nextgen | bcbio/illumina/machine.py | _remap_dirname | def _remap_dirname(local, remote):
"""Remap directory names from local to remote.
"""
def do(x):
return x.replace(local, remote, 1)
return do | python | def _remap_dirname(local, remote):
def do(x):
return x.replace(local, remote, 1)
return do | [
"def",
"_remap_dirname",
"(",
"local",
",",
"remote",
")",
":",
"def",
"do",
"(",
"x",
")",
":",
"return",
"x",
".",
"replace",
"(",
"local",
",",
"remote",
",",
"1",
")",
"return",
"do"
] | Remap directory names from local to remote. | [
"Remap",
"directory",
"names",
"from",
"local",
"to",
"remote",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L57-L62 |
237,396 | bcbio/bcbio-nextgen | bcbio/illumina/machine.py | _find_unprocessed | def _find_unprocessed(config):
"""Find any finished directories that have not been processed.
"""
reported = _read_reported(config["msg_db"])
for dname in _get_directories(config):
if os.path.isdir(dname) and dname not in reported:
if _is_finished_dumping(dname):
yield dname | python | def _find_unprocessed(config):
reported = _read_reported(config["msg_db"])
for dname in _get_directories(config):
if os.path.isdir(dname) and dname not in reported:
if _is_finished_dumping(dname):
yield dname | [
"def",
"_find_unprocessed",
"(",
"config",
")",
":",
"reported",
"=",
"_read_reported",
"(",
"config",
"[",
"\"msg_db\"",
"]",
")",
"for",
"dname",
"in",
"_get_directories",
"(",
"config",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dname",
")... | Find any finished directories that have not been processed. | [
"Find",
"any",
"finished",
"directories",
"that",
"have",
"not",
"been",
"processed",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L98-L105 |
237,397 | bcbio/bcbio-nextgen | bcbio/illumina/machine.py | _is_finished_dumping | def _is_finished_dumping(directory):
"""Determine if the sequencing directory has all files.
The final checkpoint file will differ depending if we are a
single or paired end run.
"""
#if _is_finished_dumping_checkpoint(directory):
# return True
# Check final output files; handles both HiSeq and GAII
run_info = os.path.join(directory, "RunInfo.xml")
hi_seq_checkpoint = "Basecalling_Netcopy_complete_Read%s.txt" % \
_expected_reads(run_info)
to_check = ["Basecalling_Netcopy_complete_SINGLEREAD.txt",
"Basecalling_Netcopy_complete_READ2.txt",
hi_seq_checkpoint]
return reduce(operator.or_,
[os.path.exists(os.path.join(directory, f)) for f in to_check]) | python | def _is_finished_dumping(directory):
#if _is_finished_dumping_checkpoint(directory):
# return True
# Check final output files; handles both HiSeq and GAII
run_info = os.path.join(directory, "RunInfo.xml")
hi_seq_checkpoint = "Basecalling_Netcopy_complete_Read%s.txt" % \
_expected_reads(run_info)
to_check = ["Basecalling_Netcopy_complete_SINGLEREAD.txt",
"Basecalling_Netcopy_complete_READ2.txt",
hi_seq_checkpoint]
return reduce(operator.or_,
[os.path.exists(os.path.join(directory, f)) for f in to_check]) | [
"def",
"_is_finished_dumping",
"(",
"directory",
")",
":",
"#if _is_finished_dumping_checkpoint(directory):",
"# return True",
"# Check final output files; handles both HiSeq and GAII",
"run_info",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"\"RunInfo.xml\""... | Determine if the sequencing directory has all files.
The final checkpoint file will differ depending if we are a
single or paired end run. | [
"Determine",
"if",
"the",
"sequencing",
"directory",
"has",
"all",
"files",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L113-L129 |
237,398 | bcbio/bcbio-nextgen | bcbio/illumina/machine.py | _expected_reads | def _expected_reads(run_info_file):
"""Parse the number of expected reads from the RunInfo.xml file.
"""
reads = []
if os.path.exists(run_info_file):
tree = ElementTree()
tree.parse(run_info_file)
read_elem = tree.find("Run/Reads")
reads = read_elem.findall("Read")
return len(reads) | python | def _expected_reads(run_info_file):
reads = []
if os.path.exists(run_info_file):
tree = ElementTree()
tree.parse(run_info_file)
read_elem = tree.find("Run/Reads")
reads = read_elem.findall("Read")
return len(reads) | [
"def",
"_expected_reads",
"(",
"run_info_file",
")",
":",
"reads",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"run_info_file",
")",
":",
"tree",
"=",
"ElementTree",
"(",
")",
"tree",
".",
"parse",
"(",
"run_info_file",
")",
"read_elem",
... | Parse the number of expected reads from the RunInfo.xml file. | [
"Parse",
"the",
"number",
"of",
"expected",
"reads",
"from",
"the",
"RunInfo",
".",
"xml",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L149-L158 |
237,399 | bcbio/bcbio-nextgen | bcbio/illumina/machine.py | _read_reported | def _read_reported(msg_db):
"""Retrieve a list of directories previous reported.
"""
reported = []
if os.path.exists(msg_db):
with open(msg_db) as in_handle:
for line in in_handle:
reported.append(line.strip())
return reported | python | def _read_reported(msg_db):
reported = []
if os.path.exists(msg_db):
with open(msg_db) as in_handle:
for line in in_handle:
reported.append(line.strip())
return reported | [
"def",
"_read_reported",
"(",
"msg_db",
")",
":",
"reported",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"msg_db",
")",
":",
"with",
"open",
"(",
"msg_db",
")",
"as",
"in_handle",
":",
"for",
"line",
"in",
"in_handle",
":",
"reported... | Retrieve a list of directories previous reported. | [
"Retrieve",
"a",
"list",
"of",
"directories",
"previous",
"reported",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L162-L170 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.