id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
223,700
bcbio/bcbio-nextgen
bcbio/utils.py
reservoir_sample
def reservoir_sample(stream, num_items, item_parser=lambda x: x): """ samples num_items from the stream keeping each with equal probability """ kept = [] for index, item in enumerate(stream): if index < num_items: kept.append(item_parser(item)) else: r = random.randint(0, index) if r < num_items: kept[r] = item_parser(item) return kept
python
def reservoir_sample(stream, num_items, item_parser=lambda x: x): """ samples num_items from the stream keeping each with equal probability """ kept = [] for index, item in enumerate(stream): if index < num_items: kept.append(item_parser(item)) else: r = random.randint(0, index) if r < num_items: kept[r] = item_parser(item) return kept
[ "def", "reservoir_sample", "(", "stream", ",", "num_items", ",", "item_parser", "=", "lambda", "x", ":", "x", ")", ":", "kept", "=", "[", "]", "for", "index", ",", "item", "in", "enumerate", "(", "stream", ")", ":", "if", "index", "<", "num_items", "...
samples num_items from the stream keeping each with equal probability
[ "samples", "num_items", "from", "the", "stream", "keeping", "each", "with", "equal", "probability" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L663-L675
223,701
bcbio/bcbio-nextgen
bcbio/utils.py
dictapply
def dictapply(d, fn): """ apply a function to all non-dict values in a dictionary """ for k, v in d.items(): if isinstance(v, dict): v = dictapply(v, fn) else: d[k] = fn(v) return d
python
def dictapply(d, fn): """ apply a function to all non-dict values in a dictionary """ for k, v in d.items(): if isinstance(v, dict): v = dictapply(v, fn) else: d[k] = fn(v) return d
[ "def", "dictapply", "(", "d", ",", "fn", ")", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "v", "=", "dictapply", "(", "v", ",", "fn", ")", "else", ":", "d", "[", ...
apply a function to all non-dict values in a dictionary
[ "apply", "a", "function", "to", "all", "non", "-", "dict", "values", "in", "a", "dictionary" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L681-L690
223,702
bcbio/bcbio-nextgen
bcbio/utils.py
Rscript_cmd
def Rscript_cmd(): """Retrieve path to locally installed Rscript or first in PATH. Prefers Rscript version installed via conda to a system version. """ rscript = which(os.path.join(get_bcbio_bin(), "Rscript")) if rscript: return rscript else: return which("Rscript")
python
def Rscript_cmd(): """Retrieve path to locally installed Rscript or first in PATH. Prefers Rscript version installed via conda to a system version. """ rscript = which(os.path.join(get_bcbio_bin(), "Rscript")) if rscript: return rscript else: return which("Rscript")
[ "def", "Rscript_cmd", "(", ")", ":", "rscript", "=", "which", "(", "os", ".", "path", ".", "join", "(", "get_bcbio_bin", "(", ")", ",", "\"Rscript\"", ")", ")", "if", "rscript", ":", "return", "rscript", "else", ":", "return", "which", "(", "\"Rscript\...
Retrieve path to locally installed Rscript or first in PATH. Prefers Rscript version installed via conda to a system version.
[ "Retrieve", "path", "to", "locally", "installed", "Rscript", "or", "first", "in", "PATH", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L692-L701
223,703
bcbio/bcbio-nextgen
bcbio/utils.py
R_package_resource
def R_package_resource(package, resource): """ return a path to an R package resource, if it is available """ package_path = R_package_path(package) if not package_path: return None package_resource = os.path.join(package_path, resource) if not file_exists(package_resource): return None else: return package_resource
python
def R_package_resource(package, resource): """ return a path to an R package resource, if it is available """ package_path = R_package_path(package) if not package_path: return None package_resource = os.path.join(package_path, resource) if not file_exists(package_resource): return None else: return package_resource
[ "def", "R_package_resource", "(", "package", ",", "resource", ")", ":", "package_path", "=", "R_package_path", "(", "package", ")", "if", "not", "package_path", ":", "return", "None", "package_resource", "=", "os", ".", "path", ".", "join", "(", "package_path"...
return a path to an R package resource, if it is available
[ "return", "a", "path", "to", "an", "R", "package", "resource", "if", "it", "is", "available" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L727-L738
223,704
bcbio/bcbio-nextgen
bcbio/utils.py
get_java_binpath
def get_java_binpath(cmd=None): """Retrieve path for java to use, handling custom BCBIO_JAVA_HOME Defaults to the dirname of cmd, or local anaconda directory """ if os.environ.get("BCBIO_JAVA_HOME"): test_cmd = os.path.join(os.environ["BCBIO_JAVA_HOME"], "bin", "java") if os.path.exists(test_cmd): cmd = test_cmd if not cmd: cmd = Rscript_cmd() return os.path.dirname(cmd)
python
def get_java_binpath(cmd=None): """Retrieve path for java to use, handling custom BCBIO_JAVA_HOME Defaults to the dirname of cmd, or local anaconda directory """ if os.environ.get("BCBIO_JAVA_HOME"): test_cmd = os.path.join(os.environ["BCBIO_JAVA_HOME"], "bin", "java") if os.path.exists(test_cmd): cmd = test_cmd if not cmd: cmd = Rscript_cmd() return os.path.dirname(cmd)
[ "def", "get_java_binpath", "(", "cmd", "=", "None", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "\"BCBIO_JAVA_HOME\"", ")", ":", "test_cmd", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "\"BCBIO_JAVA_HOME\"", "]", ","...
Retrieve path for java to use, handling custom BCBIO_JAVA_HOME Defaults to the dirname of cmd, or local anaconda directory
[ "Retrieve", "path", "for", "java", "to", "use", "handling", "custom", "BCBIO_JAVA_HOME" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L740-L751
223,705
bcbio/bcbio-nextgen
bcbio/utils.py
clear_java_home
def clear_java_home(): """Clear JAVA_HOME environment or reset to BCBIO_JAVA_HOME. Avoids accidental java injection but respects custom BCBIO_JAVA_HOME command. """ if os.environ.get("BCBIO_JAVA_HOME"): test_cmd = os.path.join(os.environ["BCBIO_JAVA_HOME"], "bin", "java") if os.path.exists(test_cmd): return "export JAVA_HOME=%s" % os.environ["BCBIO_JAVA_HOME"] return "unset JAVA_HOME"
python
def clear_java_home(): """Clear JAVA_HOME environment or reset to BCBIO_JAVA_HOME. Avoids accidental java injection but respects custom BCBIO_JAVA_HOME command. """ if os.environ.get("BCBIO_JAVA_HOME"): test_cmd = os.path.join(os.environ["BCBIO_JAVA_HOME"], "bin", "java") if os.path.exists(test_cmd): return "export JAVA_HOME=%s" % os.environ["BCBIO_JAVA_HOME"] return "unset JAVA_HOME"
[ "def", "clear_java_home", "(", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "\"BCBIO_JAVA_HOME\"", ")", ":", "test_cmd", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "\"BCBIO_JAVA_HOME\"", "]", ",", "\"bin\"", ",", "\"...
Clear JAVA_HOME environment or reset to BCBIO_JAVA_HOME. Avoids accidental java injection but respects custom BCBIO_JAVA_HOME command.
[ "Clear", "JAVA_HOME", "environment", "or", "reset", "to", "BCBIO_JAVA_HOME", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L753-L763
223,706
bcbio/bcbio-nextgen
bcbio/utils.py
perl_cmd
def perl_cmd(): """Retrieve path to locally installed conda Perl or first in PATH. """ perl = which(os.path.join(get_bcbio_bin(), "perl")) if perl: return perl else: return which("perl")
python
def perl_cmd(): """Retrieve path to locally installed conda Perl or first in PATH. """ perl = which(os.path.join(get_bcbio_bin(), "perl")) if perl: return perl else: return which("perl")
[ "def", "perl_cmd", "(", ")", ":", "perl", "=", "which", "(", "os", ".", "path", ".", "join", "(", "get_bcbio_bin", "(", ")", ",", "\"perl\"", ")", ")", "if", "perl", ":", "return", "perl", "else", ":", "return", "which", "(", "\"perl\"", ")" ]
Retrieve path to locally installed conda Perl or first in PATH.
[ "Retrieve", "path", "to", "locally", "installed", "conda", "Perl", "or", "first", "in", "PATH", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L773-L780
223,707
bcbio/bcbio-nextgen
bcbio/utils.py
get_perl_exports
def get_perl_exports(tmpdir=None): """Environmental exports to use conda installed perl. """ perl_path = os.path.dirname(perl_cmd()) out = "unset PERL5LIB && export PATH=%s:\"$PATH\"" % (perl_path) if tmpdir: out += " && export TMPDIR=%s" % (tmpdir) return out
python
def get_perl_exports(tmpdir=None): """Environmental exports to use conda installed perl. """ perl_path = os.path.dirname(perl_cmd()) out = "unset PERL5LIB && export PATH=%s:\"$PATH\"" % (perl_path) if tmpdir: out += " && export TMPDIR=%s" % (tmpdir) return out
[ "def", "get_perl_exports", "(", "tmpdir", "=", "None", ")", ":", "perl_path", "=", "os", ".", "path", ".", "dirname", "(", "perl_cmd", "(", ")", ")", "out", "=", "\"unset PERL5LIB && export PATH=%s:\\\"$PATH\\\"\"", "%", "(", "perl_path", ")", "if", "tmpdir", ...
Environmental exports to use conda installed perl.
[ "Environmental", "exports", "to", "use", "conda", "installed", "perl", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L782-L789
223,708
bcbio/bcbio-nextgen
bcbio/utils.py
get_all_conda_bins
def get_all_conda_bins(): """Retrieve all possible conda bin directories, including environments. """ bcbio_bin = get_bcbio_bin() conda_dir = os.path.dirname(bcbio_bin) if os.path.join("anaconda", "envs") in conda_dir: conda_dir = os.path.join(conda_dir[:conda_dir.rfind(os.path.join("anaconda", "envs"))], "anaconda") return [bcbio_bin] + list(glob.glob(os.path.join(conda_dir, "envs", "*", "bin")))
python
def get_all_conda_bins(): """Retrieve all possible conda bin directories, including environments. """ bcbio_bin = get_bcbio_bin() conda_dir = os.path.dirname(bcbio_bin) if os.path.join("anaconda", "envs") in conda_dir: conda_dir = os.path.join(conda_dir[:conda_dir.rfind(os.path.join("anaconda", "envs"))], "anaconda") return [bcbio_bin] + list(glob.glob(os.path.join(conda_dir, "envs", "*", "bin")))
[ "def", "get_all_conda_bins", "(", ")", ":", "bcbio_bin", "=", "get_bcbio_bin", "(", ")", "conda_dir", "=", "os", ".", "path", ".", "dirname", "(", "bcbio_bin", ")", "if", "os", ".", "path", ".", "join", "(", "\"anaconda\"", ",", "\"envs\"", ")", "in", ...
Retrieve all possible conda bin directories, including environments.
[ "Retrieve", "all", "possible", "conda", "bin", "directories", "including", "environments", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L809-L816
223,709
bcbio/bcbio-nextgen
bcbio/utils.py
get_program_python
def get_program_python(cmd): """Get the full path to a python version linked to the command. Allows finding python based programs in python 2 versus python 3 environments. """ full_cmd = os.path.realpath(which(cmd)) cmd_python = os.path.join(os.path.dirname(full_cmd), "python") env_python = None if "envs" in cmd_python: parts = cmd_python.split(os.sep) env_python = os.path.join(os.sep.join(parts[:parts.index("envs") + 2]), "bin", "python") if os.path.exists(cmd_python): return cmd_python elif env_python and os.path.exists(env_python): return env_python else: return os.path.realpath(sys.executable)
python
def get_program_python(cmd): """Get the full path to a python version linked to the command. Allows finding python based programs in python 2 versus python 3 environments. """ full_cmd = os.path.realpath(which(cmd)) cmd_python = os.path.join(os.path.dirname(full_cmd), "python") env_python = None if "envs" in cmd_python: parts = cmd_python.split(os.sep) env_python = os.path.join(os.sep.join(parts[:parts.index("envs") + 2]), "bin", "python") if os.path.exists(cmd_python): return cmd_python elif env_python and os.path.exists(env_python): return env_python else: return os.path.realpath(sys.executable)
[ "def", "get_program_python", "(", "cmd", ")", ":", "full_cmd", "=", "os", ".", "path", ".", "realpath", "(", "which", "(", "cmd", ")", ")", "cmd_python", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "full_cmd", ...
Get the full path to a python version linked to the command. Allows finding python based programs in python 2 versus python 3 environments.
[ "Get", "the", "full", "path", "to", "a", "python", "version", "linked", "to", "the", "command", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L818-L835
223,710
bcbio/bcbio-nextgen
bcbio/utils.py
local_path_export
def local_path_export(at_start=True, env_cmd=None): """Retrieve paths to local install, also including environment paths if env_cmd included. """ paths = [get_bcbio_bin()] if env_cmd: env_path = os.path.dirname(get_program_python(env_cmd)) if env_path not in paths: paths.insert(0, env_path) if at_start: return "export PATH=%s:\"$PATH\" && " % (":".join(paths)) else: return "export PATH=\"$PATH\":%s && " % (":".join(paths))
python
def local_path_export(at_start=True, env_cmd=None): """Retrieve paths to local install, also including environment paths if env_cmd included. """ paths = [get_bcbio_bin()] if env_cmd: env_path = os.path.dirname(get_program_python(env_cmd)) if env_path not in paths: paths.insert(0, env_path) if at_start: return "export PATH=%s:\"$PATH\" && " % (":".join(paths)) else: return "export PATH=\"$PATH\":%s && " % (":".join(paths))
[ "def", "local_path_export", "(", "at_start", "=", "True", ",", "env_cmd", "=", "None", ")", ":", "paths", "=", "[", "get_bcbio_bin", "(", ")", "]", "if", "env_cmd", ":", "env_path", "=", "os", ".", "path", ".", "dirname", "(", "get_program_python", "(", ...
Retrieve paths to local install, also including environment paths if env_cmd included.
[ "Retrieve", "paths", "to", "local", "install", "also", "including", "environment", "paths", "if", "env_cmd", "included", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L837-L848
223,711
bcbio/bcbio-nextgen
bcbio/utils.py
rbind
def rbind(dfs): """ acts like rbind for pandas dataframes """ if len(dfs) == 1: return dfs[0] df = dfs[0] for d in dfs[1:]: df = df.append(d) return df
python
def rbind(dfs): """ acts like rbind for pandas dataframes """ if len(dfs) == 1: return dfs[0] df = dfs[0] for d in dfs[1:]: df = df.append(d) return df
[ "def", "rbind", "(", "dfs", ")", ":", "if", "len", "(", "dfs", ")", "==", "1", ":", "return", "dfs", "[", "0", "]", "df", "=", "dfs", "[", "0", "]", "for", "d", "in", "dfs", "[", "1", ":", "]", ":", "df", "=", "df", ".", "append", "(", ...
acts like rbind for pandas dataframes
[ "acts", "like", "rbind", "for", "pandas", "dataframes" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L902-L911
223,712
bcbio/bcbio-nextgen
bcbio/utils.py
sort_filenames
def sort_filenames(filenames): """ sort a list of files by filename only, ignoring the directory names """ basenames = [os.path.basename(x) for x in filenames] indexes = [i[0] for i in sorted(enumerate(basenames), key=lambda x:x[1])] return [filenames[x] for x in indexes]
python
def sort_filenames(filenames): """ sort a list of files by filename only, ignoring the directory names """ basenames = [os.path.basename(x) for x in filenames] indexes = [i[0] for i in sorted(enumerate(basenames), key=lambda x:x[1])] return [filenames[x] for x in indexes]
[ "def", "sort_filenames", "(", "filenames", ")", ":", "basenames", "=", "[", "os", ".", "path", ".", "basename", "(", "x", ")", "for", "x", "in", "filenames", "]", "indexes", "=", "[", "i", "[", "0", "]", "for", "i", "in", "sorted", "(", "enumerate"...
sort a list of files by filename only, ignoring the directory names
[ "sort", "a", "list", "of", "files", "by", "filename", "only", "ignoring", "the", "directory", "names" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L936-L942
223,713
bcbio/bcbio-nextgen
bcbio/utils.py
walk_json
def walk_json(d, func): """ Walk over a parsed JSON nested structure `d`, apply `func` to each leaf element and replace it with result """ if isinstance(d, Mapping): return OrderedDict((k, walk_json(v, func)) for k, v in d.items()) elif isinstance(d, list): return [walk_json(v, func) for v in d] else: return func(d)
python
def walk_json(d, func): """ Walk over a parsed JSON nested structure `d`, apply `func` to each leaf element and replace it with result """ if isinstance(d, Mapping): return OrderedDict((k, walk_json(v, func)) for k, v in d.items()) elif isinstance(d, list): return [walk_json(v, func) for v in d] else: return func(d)
[ "def", "walk_json", "(", "d", ",", "func", ")", ":", "if", "isinstance", "(", "d", ",", "Mapping", ")", ":", "return", "OrderedDict", "(", "(", "k", ",", "walk_json", "(", "v", ",", "func", ")", ")", "for", "k", ",", "v", "in", "d", ".", "items...
Walk over a parsed JSON nested structure `d`, apply `func` to each leaf element and replace it with result
[ "Walk", "over", "a", "parsed", "JSON", "nested", "structure", "d", "apply", "func", "to", "each", "leaf", "element", "and", "replace", "it", "with", "result" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L989-L997
223,714
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
_link_bam_file
def _link_bam_file(in_file, new_dir, data): """Provide symlinks of BAM file and existing indexes if needed. """ new_dir = utils.safe_makedir(new_dir) out_file = os.path.join(new_dir, os.path.basename(in_file)) if not utils.file_exists(out_file): out_file = os.path.join(new_dir, "%s-prealign.bam" % dd.get_sample_name(data)) if data.get("cwl_keys"): # Has indexes, we're okay to go with the original file if utils.file_exists(in_file + ".bai"): out_file = in_file else: utils.copy_plus(in_file, out_file) else: utils.symlink_plus(in_file, out_file) return out_file
python
def _link_bam_file(in_file, new_dir, data): """Provide symlinks of BAM file and existing indexes if needed. """ new_dir = utils.safe_makedir(new_dir) out_file = os.path.join(new_dir, os.path.basename(in_file)) if not utils.file_exists(out_file): out_file = os.path.join(new_dir, "%s-prealign.bam" % dd.get_sample_name(data)) if data.get("cwl_keys"): # Has indexes, we're okay to go with the original file if utils.file_exists(in_file + ".bai"): out_file = in_file else: utils.copy_plus(in_file, out_file) else: utils.symlink_plus(in_file, out_file) return out_file
[ "def", "_link_bam_file", "(", "in_file", ",", "new_dir", ",", "data", ")", ":", "new_dir", "=", "utils", ".", "safe_makedir", "(", "new_dir", ")", "out_file", "=", "os", ".", "path", ".", "join", "(", "new_dir", ",", "os", ".", "path", ".", "basename",...
Provide symlinks of BAM file and existing indexes if needed.
[ "Provide", "symlinks", "of", "BAM", "file", "and", "existing", "indexes", "if", "needed", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L69-L84
223,715
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
_add_supplemental_bams
def _add_supplemental_bams(data): """Add supplemental files produced by alignment, useful for structural variant calling. """ file_key = "work_bam" if data.get(file_key): for supext in ["disc", "sr"]: base, ext = os.path.splitext(data[file_key]) test_file = "%s-%s%s" % (base, supext, ext) if os.path.exists(test_file): sup_key = file_key + "_plus" if sup_key not in data: data[sup_key] = {} data[sup_key][supext] = test_file return data
python
def _add_supplemental_bams(data): """Add supplemental files produced by alignment, useful for structural variant calling. """ file_key = "work_bam" if data.get(file_key): for supext in ["disc", "sr"]: base, ext = os.path.splitext(data[file_key]) test_file = "%s-%s%s" % (base, supext, ext) if os.path.exists(test_file): sup_key = file_key + "_plus" if sup_key not in data: data[sup_key] = {} data[sup_key][supext] = test_file return data
[ "def", "_add_supplemental_bams", "(", "data", ")", ":", "file_key", "=", "\"work_bam\"", "if", "data", ".", "get", "(", "file_key", ")", ":", "for", "supext", "in", "[", "\"disc\"", ",", "\"sr\"", "]", ":", "base", ",", "ext", "=", "os", ".", "path", ...
Add supplemental files produced by alignment, useful for structural variant calling.
[ "Add", "supplemental", "files", "produced", "by", "alignment", "useful", "for", "structural", "variant", "calling", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L86-L100
223,716
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
_add_hla_files
def _add_hla_files(data): """Add extracted fastq files of HLA alleles for typing. """ if "hla" not in data: data["hla"] = {} align_file = dd.get_align_bam(data) hla_dir = os.path.join(os.path.dirname(align_file), "hla") if not os.path.exists(hla_dir): hla_files = None else: hla_files = sorted(list(glob.glob(os.path.join(hla_dir, "%s.*.fq" % os.path.basename(align_file))))) data["hla"]["fastq"] = hla_files return data
python
def _add_hla_files(data): """Add extracted fastq files of HLA alleles for typing. """ if "hla" not in data: data["hla"] = {} align_file = dd.get_align_bam(data) hla_dir = os.path.join(os.path.dirname(align_file), "hla") if not os.path.exists(hla_dir): hla_files = None else: hla_files = sorted(list(glob.glob(os.path.join(hla_dir, "%s.*.fq" % os.path.basename(align_file))))) data["hla"]["fastq"] = hla_files return data
[ "def", "_add_hla_files", "(", "data", ")", ":", "if", "\"hla\"", "not", "in", "data", ":", "data", "[", "\"hla\"", "]", "=", "{", "}", "align_file", "=", "dd", ".", "get_align_bam", "(", "data", ")", "hla_dir", "=", "os", ".", "path", ".", "join", ...
Add extracted fastq files of HLA alleles for typing.
[ "Add", "extracted", "fastq", "files", "of", "HLA", "alleles", "for", "typing", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L102-L114
223,717
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
prep_samples
def prep_samples(*items): """Handle any global preparatory steps for samples with potentially shared data. Avoids race conditions in postprocess alignment when performing prep tasks on shared files between multiple similar samples. Cleans input BED files to avoid issues with overlapping input segments. """ out = [] for data in (utils.to_single_data(x) for x in items): data = cwlutils.normalize_missing(data) data = cwlutils.unpack_tarballs(data, data) data = clean_inputs(data) out.append([data]) return out
python
def prep_samples(*items): """Handle any global preparatory steps for samples with potentially shared data. Avoids race conditions in postprocess alignment when performing prep tasks on shared files between multiple similar samples. Cleans input BED files to avoid issues with overlapping input segments. """ out = [] for data in (utils.to_single_data(x) for x in items): data = cwlutils.normalize_missing(data) data = cwlutils.unpack_tarballs(data, data) data = clean_inputs(data) out.append([data]) return out
[ "def", "prep_samples", "(", "*", "items", ")", ":", "out", "=", "[", "]", "for", "data", "in", "(", "utils", ".", "to_single_data", "(", "x", ")", "for", "x", "in", "items", ")", ":", "data", "=", "cwlutils", ".", "normalize_missing", "(", "data", ...
Handle any global preparatory steps for samples with potentially shared data. Avoids race conditions in postprocess alignment when performing prep tasks on shared files between multiple similar samples. Cleans input BED files to avoid issues with overlapping input segments.
[ "Handle", "any", "global", "preparatory", "steps", "for", "samples", "with", "potentially", "shared", "data", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L192-L206
223,718
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
clean_inputs
def clean_inputs(data): """Clean BED input files to avoid overlapping segments that cause downstream issues. Per-merges inputs to avoid needing to call multiple times during later parallel steps. """ if not utils.get_in(data, ("config", "algorithm", "variant_regions_orig")): data["config"]["algorithm"]["variant_regions_orig"] = dd.get_variant_regions(data) clean_vr = clean_file(dd.get_variant_regions(data), data, prefix="cleaned-") merged_vr = merge_overlaps(clean_vr, data) data["config"]["algorithm"]["variant_regions"] = clean_vr data["config"]["algorithm"]["variant_regions_merged"] = merged_vr if dd.get_coverage(data): if not utils.get_in(data, ("config", "algorithm", "coverage_orig")): data["config"]["algorithm"]["coverage_orig"] = dd.get_coverage(data) clean_cov_bed = clean_file(dd.get_coverage(data), data, prefix="cov-", simple=True) merged_cov_bed = merge_overlaps(clean_cov_bed, data) data["config"]["algorithm"]["coverage"] = clean_cov_bed data["config"]["algorithm"]["coverage_merged"] = merged_cov_bed if 'seq2c' in get_svcallers(data): seq2c_ready_bed = prep_seq2c_bed(data) if not seq2c_ready_bed: logger.warning("Can't run Seq2C without a svregions or variant_regions BED file") else: data["config"]["algorithm"]["seq2c_bed_ready"] = seq2c_ready_bed elif regions.get_sv_bed(data): dd.set_sv_regions(data, clean_file(regions.get_sv_bed(data), data, prefix="svregions-")) return data
python
def clean_inputs(data): """Clean BED input files to avoid overlapping segments that cause downstream issues. Per-merges inputs to avoid needing to call multiple times during later parallel steps. """ if not utils.get_in(data, ("config", "algorithm", "variant_regions_orig")): data["config"]["algorithm"]["variant_regions_orig"] = dd.get_variant_regions(data) clean_vr = clean_file(dd.get_variant_regions(data), data, prefix="cleaned-") merged_vr = merge_overlaps(clean_vr, data) data["config"]["algorithm"]["variant_regions"] = clean_vr data["config"]["algorithm"]["variant_regions_merged"] = merged_vr if dd.get_coverage(data): if not utils.get_in(data, ("config", "algorithm", "coverage_orig")): data["config"]["algorithm"]["coverage_orig"] = dd.get_coverage(data) clean_cov_bed = clean_file(dd.get_coverage(data), data, prefix="cov-", simple=True) merged_cov_bed = merge_overlaps(clean_cov_bed, data) data["config"]["algorithm"]["coverage"] = clean_cov_bed data["config"]["algorithm"]["coverage_merged"] = merged_cov_bed if 'seq2c' in get_svcallers(data): seq2c_ready_bed = prep_seq2c_bed(data) if not seq2c_ready_bed: logger.warning("Can't run Seq2C without a svregions or variant_regions BED file") else: data["config"]["algorithm"]["seq2c_bed_ready"] = seq2c_ready_bed elif regions.get_sv_bed(data): dd.set_sv_regions(data, clean_file(regions.get_sv_bed(data), data, prefix="svregions-")) return data
[ "def", "clean_inputs", "(", "data", ")", ":", "if", "not", "utils", ".", "get_in", "(", "data", ",", "(", "\"config\"", ",", "\"algorithm\"", ",", "\"variant_regions_orig\"", ")", ")", ":", "data", "[", "\"config\"", "]", "[", "\"algorithm\"", "]", "[", ...
Clean BED input files to avoid overlapping segments that cause downstream issues. Per-merges inputs to avoid needing to call multiple times during later parallel steps.
[ "Clean", "BED", "input", "files", "to", "avoid", "overlapping", "segments", "that", "cause", "downstream", "issues", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L208-L236
223,719
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
postprocess_alignment
def postprocess_alignment(data): """Perform post-processing steps required on full BAM files. Prepares list of callable genome regions allowing subsequent parallelization. """ data = cwlutils.normalize_missing(utils.to_single_data(data)) data = cwlutils.unpack_tarballs(data, data) bam_file = data.get("align_bam") or data.get("work_bam") ref_file = dd.get_ref_file(data) if vmulti.bam_needs_processing(data) and bam_file and bam_file.endswith(".bam"): out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "align", dd.get_sample_name(data))) bam_file_ready = os.path.join(out_dir, os.path.basename(bam_file)) if not utils.file_exists(bam_file_ready): utils.symlink_plus(bam_file, bam_file_ready) bam.index(bam_file_ready, data["config"]) covinfo = callable.sample_callable_bed(bam_file_ready, ref_file, data) callable_region_bed, nblock_bed = \ callable.block_regions(covinfo.raw_callable, bam_file_ready, ref_file, data) data["regions"] = {"nblock": nblock_bed, "callable": covinfo.raw_callable, "sample_callable": covinfo.callable, "mapped_stats": readstats.get_cache_file(data)} data["depth"] = covinfo.depth_files data = coverage.assign_interval(data) data = samtools.run_and_save(data) data = recalibrate.prep_recal(data) data = recalibrate.apply_recal(data) elif dd.get_variant_regions(data): callable_region_bed, nblock_bed = \ callable.block_regions(dd.get_variant_regions(data), bam_file, ref_file, data) data["regions"] = {"nblock": nblock_bed, "callable": dd.get_variant_regions(data), "sample_callable": dd.get_variant_regions(data)} return [[data]]
python
def postprocess_alignment(data): """Perform post-processing steps required on full BAM files. Prepares list of callable genome regions allowing subsequent parallelization. """ data = cwlutils.normalize_missing(utils.to_single_data(data)) data = cwlutils.unpack_tarballs(data, data) bam_file = data.get("align_bam") or data.get("work_bam") ref_file = dd.get_ref_file(data) if vmulti.bam_needs_processing(data) and bam_file and bam_file.endswith(".bam"): out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "align", dd.get_sample_name(data))) bam_file_ready = os.path.join(out_dir, os.path.basename(bam_file)) if not utils.file_exists(bam_file_ready): utils.symlink_plus(bam_file, bam_file_ready) bam.index(bam_file_ready, data["config"]) covinfo = callable.sample_callable_bed(bam_file_ready, ref_file, data) callable_region_bed, nblock_bed = \ callable.block_regions(covinfo.raw_callable, bam_file_ready, ref_file, data) data["regions"] = {"nblock": nblock_bed, "callable": covinfo.raw_callable, "sample_callable": covinfo.callable, "mapped_stats": readstats.get_cache_file(data)} data["depth"] = covinfo.depth_files data = coverage.assign_interval(data) data = samtools.run_and_save(data) data = recalibrate.prep_recal(data) data = recalibrate.apply_recal(data) elif dd.get_variant_regions(data): callable_region_bed, nblock_bed = \ callable.block_regions(dd.get_variant_regions(data), bam_file, ref_file, data) data["regions"] = {"nblock": nblock_bed, "callable": dd.get_variant_regions(data), "sample_callable": dd.get_variant_regions(data)} return [[data]]
[ "def", "postprocess_alignment", "(", "data", ")", ":", "data", "=", "cwlutils", ".", "normalize_missing", "(", "utils", ".", "to_single_data", "(", "data", ")", ")", "data", "=", "cwlutils", ".", "unpack_tarballs", "(", "data", ",", "data", ")", "bam_file", ...
Perform post-processing steps required on full BAM files. Prepares list of callable genome regions allowing subsequent parallelization.
[ "Perform", "post", "-", "processing", "steps", "required", "on", "full", "BAM", "files", ".", "Prepares", "list", "of", "callable", "genome", "regions", "allowing", "subsequent", "parallelization", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L238-L270
223,720
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
_merge_out_from_infiles
def _merge_out_from_infiles(in_files): """Generate output merged file name from set of input files. Handles non-shared filesystems where we don't know output path when setting up split parts. """ fname = os.path.commonprefix([os.path.basename(f) for f in in_files]) while fname.endswith(("-", "_", ".")): fname = fname[:-1] ext = os.path.splitext(in_files[0])[-1] dirname = os.path.dirname(in_files[0]) while dirname.endswith(("split", "merge")): dirname = os.path.dirname(dirname) return os.path.join(dirname, "%s%s" % (fname, ext))
python
def _merge_out_from_infiles(in_files): """Generate output merged file name from set of input files. Handles non-shared filesystems where we don't know output path when setting up split parts. """ fname = os.path.commonprefix([os.path.basename(f) for f in in_files]) while fname.endswith(("-", "_", ".")): fname = fname[:-1] ext = os.path.splitext(in_files[0])[-1] dirname = os.path.dirname(in_files[0]) while dirname.endswith(("split", "merge")): dirname = os.path.dirname(dirname) return os.path.join(dirname, "%s%s" % (fname, ext))
[ "def", "_merge_out_from_infiles", "(", "in_files", ")", ":", "fname", "=", "os", ".", "path", ".", "commonprefix", "(", "[", "os", ".", "path", ".", "basename", "(", "f", ")", "for", "f", "in", "in_files", "]", ")", "while", "fname", ".", "endswith", ...
Generate output merged file name from set of input files. Handles non-shared filesystems where we don't know output path when setting up split parts.
[ "Generate", "output", "merged", "file", "name", "from", "set", "of", "input", "files", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L272-L285
223,721
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
delayed_bam_merge
def delayed_bam_merge(data): """Perform a merge on previously prepped files, delayed in processing. Handles merging of associated split read and discordant files if present. """ if data.get("combine"): assert len(data["combine"].keys()) == 1 file_key = list(data["combine"].keys())[0] extras = [] for x in data["combine"][file_key].get("extras", []): if isinstance(x, (list, tuple)): extras.extend(x) else: extras.append(x) if file_key in data: extras.append(data[file_key]) in_files = sorted(list(set(extras))) out_file = tz.get_in(["combine", file_key, "out"], data, _merge_out_from_infiles(in_files)) sup_exts = data.get(file_key + "_plus", {}).keys() for ext in list(sup_exts) + [""]: merged_file = None if os.path.exists(utils.append_stem(out_file, "-" + ext)): cur_out_file, cur_in_files = out_file, [] if ext: cur_in_files = list(filter(os.path.exists, (utils.append_stem(f, "-" + ext) for f in in_files))) cur_out_file = utils.append_stem(out_file, "-" + ext) if len(cur_in_files) > 0 else None else: cur_in_files, cur_out_file = in_files, out_file if cur_out_file: config = copy.deepcopy(data["config"]) if len(cur_in_files) > 0: merged_file = merge_bam_files(cur_in_files, os.path.dirname(cur_out_file), data, out_file=cur_out_file) else: assert os.path.exists(cur_out_file) merged_file = cur_out_file if merged_file: if ext: data[file_key + "_plus"][ext] = merged_file else: data[file_key] = merged_file data.pop("region", None) data.pop("combine", None) return [[data]]
python
def delayed_bam_merge(data): """Perform a merge on previously prepped files, delayed in processing. Handles merging of associated split read and discordant files if present. """ if data.get("combine"): assert len(data["combine"].keys()) == 1 file_key = list(data["combine"].keys())[0] extras = [] for x in data["combine"][file_key].get("extras", []): if isinstance(x, (list, tuple)): extras.extend(x) else: extras.append(x) if file_key in data: extras.append(data[file_key]) in_files = sorted(list(set(extras))) out_file = tz.get_in(["combine", file_key, "out"], data, _merge_out_from_infiles(in_files)) sup_exts = data.get(file_key + "_plus", {}).keys() for ext in list(sup_exts) + [""]: merged_file = None if os.path.exists(utils.append_stem(out_file, "-" + ext)): cur_out_file, cur_in_files = out_file, [] if ext: cur_in_files = list(filter(os.path.exists, (utils.append_stem(f, "-" + ext) for f in in_files))) cur_out_file = utils.append_stem(out_file, "-" + ext) if len(cur_in_files) > 0 else None else: cur_in_files, cur_out_file = in_files, out_file if cur_out_file: config = copy.deepcopy(data["config"]) if len(cur_in_files) > 0: merged_file = merge_bam_files(cur_in_files, os.path.dirname(cur_out_file), data, out_file=cur_out_file) else: assert os.path.exists(cur_out_file) merged_file = cur_out_file if merged_file: if ext: data[file_key + "_plus"][ext] = merged_file else: data[file_key] = merged_file data.pop("region", None) data.pop("combine", None) return [[data]]
[ "def", "delayed_bam_merge", "(", "data", ")", ":", "if", "data", ".", "get", "(", "\"combine\"", ")", ":", "assert", "len", "(", "data", "[", "\"combine\"", "]", ".", "keys", "(", ")", ")", "==", "1", "file_key", "=", "list", "(", "data", "[", "\"c...
Perform a merge on previously prepped files, delayed in processing. Handles merging of associated split read and discordant files if present.
[ "Perform", "a", "merge", "on", "previously", "prepped", "files", "delayed", "in", "processing", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L287-L330
223,722
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
merge_split_alignments
def merge_split_alignments(data): """Merge split BAM inputs generated by common workflow language runs. """ data = utils.to_single_data(data) data = _merge_align_bams(data) data = _merge_hla_fastq_inputs(data) return [[data]]
python
def merge_split_alignments(data): """Merge split BAM inputs generated by common workflow language runs. """ data = utils.to_single_data(data) data = _merge_align_bams(data) data = _merge_hla_fastq_inputs(data) return [[data]]
[ "def", "merge_split_alignments", "(", "data", ")", ":", "data", "=", "utils", ".", "to_single_data", "(", "data", ")", "data", "=", "_merge_align_bams", "(", "data", ")", "data", "=", "_merge_hla_fastq_inputs", "(", "data", ")", "return", "[", "[", "data", ...
Merge split BAM inputs generated by common workflow language runs.
[ "Merge", "split", "BAM", "inputs", "generated", "by", "common", "workflow", "language", "runs", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L332-L338
223,723
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
_merge_align_bams
def _merge_align_bams(data): """Merge multiple alignment BAMs, including split and discordant reads. """ for key in (["work_bam"], ["work_bam_plus", "disc"], ["work_bam_plus", "sr"], ["umi_bam"]): in_files = tz.get_in(key, data, []) if not isinstance(in_files, (list, tuple)): in_files = [in_files] in_files = [x for x in in_files if x and x != "None"] if in_files: ext = "-%s" % key[-1] if len(key) > 1 else "" out_file = os.path.join(dd.get_work_dir(data), "align", dd.get_sample_name(data), "%s-sort%s.bam" % (dd.get_sample_name(data), ext)) merged_file = merge_bam_files(in_files, utils.safe_makedir(os.path.dirname(out_file)), data, out_file=out_file) data = tz.update_in(data, key, lambda x: merged_file) else: data = tz.update_in(data, key, lambda x: None) if "align_bam" in data and "work_bam" in data: data["align_bam"] = data["work_bam"] return data
python
def _merge_align_bams(data): """Merge multiple alignment BAMs, including split and discordant reads. """ for key in (["work_bam"], ["work_bam_plus", "disc"], ["work_bam_plus", "sr"], ["umi_bam"]): in_files = tz.get_in(key, data, []) if not isinstance(in_files, (list, tuple)): in_files = [in_files] in_files = [x for x in in_files if x and x != "None"] if in_files: ext = "-%s" % key[-1] if len(key) > 1 else "" out_file = os.path.join(dd.get_work_dir(data), "align", dd.get_sample_name(data), "%s-sort%s.bam" % (dd.get_sample_name(data), ext)) merged_file = merge_bam_files(in_files, utils.safe_makedir(os.path.dirname(out_file)), data, out_file=out_file) data = tz.update_in(data, key, lambda x: merged_file) else: data = tz.update_in(data, key, lambda x: None) if "align_bam" in data and "work_bam" in data: data["align_bam"] = data["work_bam"] return data
[ "def", "_merge_align_bams", "(", "data", ")", ":", "for", "key", "in", "(", "[", "\"work_bam\"", "]", ",", "[", "\"work_bam_plus\"", ",", "\"disc\"", "]", ",", "[", "\"work_bam_plus\"", ",", "\"sr\"", "]", ",", "[", "\"umi_bam\"", "]", ")", ":", "in_file...
Merge multiple alignment BAMs, including split and discordant reads.
[ "Merge", "multiple", "alignment", "BAMs", "including", "split", "and", "discordant", "reads", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L340-L359
223,724
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
_merge_hla_fastq_inputs
def _merge_hla_fastq_inputs(data): """Merge HLA inputs from a split initial alignment. """ hla_key = ["hla", "fastq"] hla_sample_files = [x for x in (tz.get_in(hla_key, data) or []) if x and x != "None"] merged_hlas = None if hla_sample_files: out_files = collections.defaultdict(list) for hla_file in utils.flatten(hla_sample_files): rehla = re.search(r".hla.(?P<hlatype>[\w-]+).fq", hla_file) if rehla: hlatype = rehla.group("hlatype") out_files[hlatype].append(hla_file) if len(out_files) > 0: hla_outdir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "align", dd.get_sample_name(data), "hla")) merged_hlas = [] for hlatype, files in out_files.items(): out_file = os.path.join(hla_outdir, "%s-%s.fq" % (dd.get_sample_name(data), hlatype)) optitype.combine_hla_fqs([(hlatype, f) for f in files], out_file, data) merged_hlas.append(out_file) data = tz.update_in(data, hla_key, lambda x: merged_hlas) return data
python
def _merge_hla_fastq_inputs(data): """Merge HLA inputs from a split initial alignment. """ hla_key = ["hla", "fastq"] hla_sample_files = [x for x in (tz.get_in(hla_key, data) or []) if x and x != "None"] merged_hlas = None if hla_sample_files: out_files = collections.defaultdict(list) for hla_file in utils.flatten(hla_sample_files): rehla = re.search(r".hla.(?P<hlatype>[\w-]+).fq", hla_file) if rehla: hlatype = rehla.group("hlatype") out_files[hlatype].append(hla_file) if len(out_files) > 0: hla_outdir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "align", dd.get_sample_name(data), "hla")) merged_hlas = [] for hlatype, files in out_files.items(): out_file = os.path.join(hla_outdir, "%s-%s.fq" % (dd.get_sample_name(data), hlatype)) optitype.combine_hla_fqs([(hlatype, f) for f in files], out_file, data) merged_hlas.append(out_file) data = tz.update_in(data, hla_key, lambda x: merged_hlas) return data
[ "def", "_merge_hla_fastq_inputs", "(", "data", ")", ":", "hla_key", "=", "[", "\"hla\"", ",", "\"fastq\"", "]", "hla_sample_files", "=", "[", "x", "for", "x", "in", "(", "tz", ".", "get_in", "(", "hla_key", ",", "data", ")", "or", "[", "]", ")", "if"...
Merge HLA inputs from a split initial alignment.
[ "Merge", "HLA", "inputs", "from", "a", "split", "initial", "alignment", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L361-L383
223,725
bcbio/bcbio-nextgen
bcbio/pipeline/sample.py
prepare_bcbio_samples
def prepare_bcbio_samples(sample): """ Function that will use specific function to merge input files """ logger.info("Preparing %s files %s to merge into %s." % (sample['name'], sample['files'], sample['out_file'])) if sample['fn'] == "fq_merge": out_file = fq_merge(sample['files'], sample['out_file'], sample['config']) elif sample['fn'] == "bam_merge": out_file = bam_merge(sample['files'], sample['out_file'], sample['config']) elif sample['fn'] == "query_gsm": out_file = query_gsm(sample['files'], sample['out_file'], sample['config']) elif sample['fn'] == "query_srr": out_file = query_srr(sample['files'], sample['out_file'], sample['config']) sample['out_file'] = out_file return [sample]
python
def prepare_bcbio_samples(sample): """ Function that will use specific function to merge input files """ logger.info("Preparing %s files %s to merge into %s." % (sample['name'], sample['files'], sample['out_file'])) if sample['fn'] == "fq_merge": out_file = fq_merge(sample['files'], sample['out_file'], sample['config']) elif sample['fn'] == "bam_merge": out_file = bam_merge(sample['files'], sample['out_file'], sample['config']) elif sample['fn'] == "query_gsm": out_file = query_gsm(sample['files'], sample['out_file'], sample['config']) elif sample['fn'] == "query_srr": out_file = query_srr(sample['files'], sample['out_file'], sample['config']) sample['out_file'] = out_file return [sample]
[ "def", "prepare_bcbio_samples", "(", "sample", ")", ":", "logger", ".", "info", "(", "\"Preparing %s files %s to merge into %s.\"", "%", "(", "sample", "[", "'name'", "]", ",", "sample", "[", "'files'", "]", ",", "sample", "[", "'out_file'", "]", ")", ")", "...
Function that will use specific function to merge input files
[ "Function", "that", "will", "use", "specific", "function", "to", "merge", "input", "files" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sample.py#L385-L399
223,726
bcbio/bcbio-nextgen
bcbio/heterogeneity/__init__.py
_get_calls
def _get_calls(data, cnv_only=False): """Retrieve calls, organized by name, to use for heterogeneity analysis. """ cnvs_supported = set(["cnvkit", "battenberg"]) out = {} for sv in data.get("sv", []): if not cnv_only or sv["variantcaller"] in cnvs_supported: out[sv["variantcaller"]] = sv return out
python
def _get_calls(data, cnv_only=False): """Retrieve calls, organized by name, to use for heterogeneity analysis. """ cnvs_supported = set(["cnvkit", "battenberg"]) out = {} for sv in data.get("sv", []): if not cnv_only or sv["variantcaller"] in cnvs_supported: out[sv["variantcaller"]] = sv return out
[ "def", "_get_calls", "(", "data", ",", "cnv_only", "=", "False", ")", ":", "cnvs_supported", "=", "set", "(", "[", "\"cnvkit\"", ",", "\"battenberg\"", "]", ")", "out", "=", "{", "}", "for", "sv", "in", "data", ".", "get", "(", "\"sv\"", ",", "[", ...
Retrieve calls, organized by name, to use for heterogeneity analysis.
[ "Retrieve", "calls", "organized", "by", "name", "to", "use", "for", "heterogeneity", "analysis", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/__init__.py#L17-L25
223,727
bcbio/bcbio-nextgen
bcbio/heterogeneity/__init__.py
get_variants
def get_variants(data, include_germline=False): """Retrieve set of variant calls to use for heterogeneity analysis. """ data = utils.deepish_copy(data) supported = ["precalled", "vardict", "vardict-java", "vardict-perl", "freebayes", "octopus", "strelka2"] # Right now mutect2 and mutect do not provide heterozygous germline calls # to be useful https://github.com/bcbio/bcbio-nextgen/issues/2464 # supported += ["mutect2", "mutect"] if include_germline: supported.insert(1, "gatk-haplotype") out = [] # CWL based input if isinstance(data.get("variants"), dict) and "samples" in data["variants"]: cur_vs = [] # Unpack single sample list of files if (isinstance(data["variants"]["samples"], (list, tuple)) and len(data["variants"]["samples"]) == 1 and isinstance(data["variants"]["samples"][0], (list, tuple))): data["variants"]["samples"] = data["variants"]["samples"][0] for fname in data["variants"]["samples"]: variantcaller = utils.splitext_plus(os.path.basename(fname))[0] variantcaller = variantcaller.replace(dd.get_sample_name(data) + "-", "") for batch in dd.get_batches(data): variantcaller = variantcaller.replace(batch + "-", "") cur_vs.append({"vrn_file": fname, "variantcaller": variantcaller}) data["variants"] = cur_vs for v in data.get("variants", []): if v["variantcaller"] in supported and v.get("vrn_file"): out.append((supported.index(v["variantcaller"]), v)) out.sort() return [xs[1] for xs in out]
python
def get_variants(data, include_germline=False): """Retrieve set of variant calls to use for heterogeneity analysis. """ data = utils.deepish_copy(data) supported = ["precalled", "vardict", "vardict-java", "vardict-perl", "freebayes", "octopus", "strelka2"] # Right now mutect2 and mutect do not provide heterozygous germline calls # to be useful https://github.com/bcbio/bcbio-nextgen/issues/2464 # supported += ["mutect2", "mutect"] if include_germline: supported.insert(1, "gatk-haplotype") out = [] # CWL based input if isinstance(data.get("variants"), dict) and "samples" in data["variants"]: cur_vs = [] # Unpack single sample list of files if (isinstance(data["variants"]["samples"], (list, tuple)) and len(data["variants"]["samples"]) == 1 and isinstance(data["variants"]["samples"][0], (list, tuple))): data["variants"]["samples"] = data["variants"]["samples"][0] for fname in data["variants"]["samples"]: variantcaller = utils.splitext_plus(os.path.basename(fname))[0] variantcaller = variantcaller.replace(dd.get_sample_name(data) + "-", "") for batch in dd.get_batches(data): variantcaller = variantcaller.replace(batch + "-", "") cur_vs.append({"vrn_file": fname, "variantcaller": variantcaller}) data["variants"] = cur_vs for v in data.get("variants", []): if v["variantcaller"] in supported and v.get("vrn_file"): out.append((supported.index(v["variantcaller"]), v)) out.sort() return [xs[1] for xs in out]
[ "def", "get_variants", "(", "data", ",", "include_germline", "=", "False", ")", ":", "data", "=", "utils", ".", "deepish_copy", "(", "data", ")", "supported", "=", "[", "\"precalled\"", ",", "\"vardict\"", ",", "\"vardict-java\"", ",", "\"vardict-perl\"", ",",...
Retrieve set of variant calls to use for heterogeneity analysis.
[ "Retrieve", "set", "of", "variant", "calls", "to", "use", "for", "heterogeneity", "analysis", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/__init__.py#L27-L57
223,728
bcbio/bcbio-nextgen
bcbio/heterogeneity/__init__.py
_ready_for_het_analysis
def _ready_for_het_analysis(items): """Check if a sample has input information for heterogeneity analysis. We currently require a tumor/normal sample containing both CNV and variant calls. """ paired = vcfutils.get_paired_bams([dd.get_align_bam(d) for d in items], items) has_het = any(dd.get_hetcaller(d) for d in items) if has_het and paired: return get_variants(paired.tumor_data) and _get_calls(paired.tumor_data, cnv_only=True)
python
def _ready_for_het_analysis(items): """Check if a sample has input information for heterogeneity analysis. We currently require a tumor/normal sample containing both CNV and variant calls. """ paired = vcfutils.get_paired_bams([dd.get_align_bam(d) for d in items], items) has_het = any(dd.get_hetcaller(d) for d in items) if has_het and paired: return get_variants(paired.tumor_data) and _get_calls(paired.tumor_data, cnv_only=True)
[ "def", "_ready_for_het_analysis", "(", "items", ")", ":", "paired", "=", "vcfutils", ".", "get_paired_bams", "(", "[", "dd", ".", "get_align_bam", "(", "d", ")", "for", "d", "in", "items", "]", ",", "items", ")", "has_het", "=", "any", "(", "dd", ".", ...
Check if a sample has input information for heterogeneity analysis. We currently require a tumor/normal sample containing both CNV and variant calls.
[ "Check", "if", "a", "sample", "has", "input", "information", "for", "heterogeneity", "analysis", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/__init__.py#L59-L67
223,729
bcbio/bcbio-nextgen
bcbio/heterogeneity/__init__.py
run
def run(items, run_parallel): """Top level entry point for calculating heterogeneity, handles organization and job distribution. """ to_process = [] extras = [] for batch, cur_items in _group_by_batches(items).items(): if _ready_for_het_analysis(cur_items): to_process.append((batch, cur_items)) else: for data in cur_items: extras.append([data]) processed = run_parallel("heterogeneity_estimate", ([xs, b, xs[0]["config"]] for b, xs in to_process)) return _group_by_sample_and_batch(extras + processed)
python
def run(items, run_parallel): """Top level entry point for calculating heterogeneity, handles organization and job distribution. """ to_process = [] extras = [] for batch, cur_items in _group_by_batches(items).items(): if _ready_for_het_analysis(cur_items): to_process.append((batch, cur_items)) else: for data in cur_items: extras.append([data]) processed = run_parallel("heterogeneity_estimate", ([xs, b, xs[0]["config"]] for b, xs in to_process)) return _group_by_sample_and_batch(extras + processed)
[ "def", "run", "(", "items", ",", "run_parallel", ")", ":", "to_process", "=", "[", "]", "extras", "=", "[", "]", "for", "batch", ",", "cur_items", "in", "_group_by_batches", "(", "items", ")", ".", "items", "(", ")", ":", "if", "_ready_for_het_analysis",...
Top level entry point for calculating heterogeneity, handles organization and job distribution.
[ "Top", "level", "entry", "point", "for", "calculating", "heterogeneity", "handles", "organization", "and", "job", "distribution", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/__init__.py#L122-L134
223,730
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
create_inputs
def create_inputs(data): """Index input reads and prepare groups of reads to process concurrently. Allows parallelization of alignment beyond processors available on a single machine. Prepares a bgzip and grabix indexed file for retrieving sections of files. """ from bcbio.pipeline import sample data = cwlutils.normalize_missing(data) aligner = tz.get_in(("config", "algorithm", "aligner"), data) # CRAM files must be converted to bgzipped fastq, unless not aligning. # Also need to prep and download remote files. if not ("files" in data and data["files"] and aligner and (_is_cram_input(data["files"]) or objectstore.is_remote(data["files"][0]))): # skip indexing on samples without input files or not doing alignment if ("files" not in data or not data["files"] or data["files"][0] is None or not aligner): return [[data]] data["files_orig"] = data["files"] data["files"] = prep_fastq_inputs(data["files"], data) # preparation converts illumina into sanger format data["config"]["algorithm"]["quality_format"] = "standard" # Handle any necessary trimming data = utils.to_single_data(sample.trim_sample(data)[0]) _prep_grabix_indexes(data["files"], data) data = _set_align_split_size(data) out = [] if tz.get_in(["config", "algorithm", "align_split_size"], data): splits = _find_read_splits(data["files"][0], int(data["config"]["algorithm"]["align_split_size"])) for split in splits: cur_data = copy.deepcopy(data) cur_data["align_split"] = split out.append([cur_data]) else: out.append([data]) if "output_cwl_keys" in data: out = cwlutils.samples_to_records([utils.to_single_data(x) for x in out], ["files", "align_split", "config__algorithm__quality_format"]) return out
python
def create_inputs(data): """Index input reads and prepare groups of reads to process concurrently. Allows parallelization of alignment beyond processors available on a single machine. Prepares a bgzip and grabix indexed file for retrieving sections of files. """ from bcbio.pipeline import sample data = cwlutils.normalize_missing(data) aligner = tz.get_in(("config", "algorithm", "aligner"), data) # CRAM files must be converted to bgzipped fastq, unless not aligning. # Also need to prep and download remote files. if not ("files" in data and data["files"] and aligner and (_is_cram_input(data["files"]) or objectstore.is_remote(data["files"][0]))): # skip indexing on samples without input files or not doing alignment if ("files" not in data or not data["files"] or data["files"][0] is None or not aligner): return [[data]] data["files_orig"] = data["files"] data["files"] = prep_fastq_inputs(data["files"], data) # preparation converts illumina into sanger format data["config"]["algorithm"]["quality_format"] = "standard" # Handle any necessary trimming data = utils.to_single_data(sample.trim_sample(data)[0]) _prep_grabix_indexes(data["files"], data) data = _set_align_split_size(data) out = [] if tz.get_in(["config", "algorithm", "align_split_size"], data): splits = _find_read_splits(data["files"][0], int(data["config"]["algorithm"]["align_split_size"])) for split in splits: cur_data = copy.deepcopy(data) cur_data["align_split"] = split out.append([cur_data]) else: out.append([data]) if "output_cwl_keys" in data: out = cwlutils.samples_to_records([utils.to_single_data(x) for x in out], ["files", "align_split", "config__algorithm__quality_format"]) return out
[ "def", "create_inputs", "(", "data", ")", ":", "from", "bcbio", ".", "pipeline", "import", "sample", "data", "=", "cwlutils", ".", "normalize_missing", "(", "data", ")", "aligner", "=", "tz", ".", "get_in", "(", "(", "\"config\"", ",", "\"algorithm\"", ","...
Index input reads and prepare groups of reads to process concurrently. Allows parallelization of alignment beyond processors available on a single machine. Prepares a bgzip and grabix indexed file for retrieving sections of files.
[ "Index", "input", "reads", "and", "prepare", "groups", "of", "reads", "to", "process", "concurrently", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L25-L62
223,731
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_set_align_split_size
def _set_align_split_size(data): """Set useful align_split_size, generating an estimate if it doesn't exist. We try to split on larger inputs and avoid too many pieces, aiming for size chunks of 5Gb or at most 50 maximum splits. The size estimate used in calculations is 20 million reads for ~5Gb. For UMI calculations we skip splitting since we're going to align and re-align after consensus. For CWL runs, we pick larger split sizes to avoid overhead of staging each chunk. """ if cwlutils.is_cwl_run(data): target_size = 20 # Gb target_size_reads = 80 # million reads else: target_size = 5 # Gb target_size_reads = 20 # million reads max_splits = 100 # Avoid too many pieces, causing merge memory problems val = dd.get_align_split_size(data) umi_consensus = dd.get_umi_consensus(data) if val is None: if not umi_consensus: total_size = 0 # Gb # Use original files if we might have reduced the size of our prepped files input_files = data.get("files_orig", []) if dd.get_save_diskspace(data) else data.get("files", []) for fname in input_files: if os.path.exists(fname): total_size += os.path.getsize(fname) / (1024.0 * 1024.0 * 1024.0) # Only set if we have files and are bigger than the target size if total_size > target_size: data["config"]["algorithm"]["align_split_size"] = \ int(1e6 * _pick_align_split_size(total_size, target_size, target_size_reads, max_splits)) elif val: assert not umi_consensus, "Cannot set align_split_size to %s with UMI conensus specified" % val return data
python
def _set_align_split_size(data): """Set useful align_split_size, generating an estimate if it doesn't exist. We try to split on larger inputs and avoid too many pieces, aiming for size chunks of 5Gb or at most 50 maximum splits. The size estimate used in calculations is 20 million reads for ~5Gb. For UMI calculations we skip splitting since we're going to align and re-align after consensus. For CWL runs, we pick larger split sizes to avoid overhead of staging each chunk. """ if cwlutils.is_cwl_run(data): target_size = 20 # Gb target_size_reads = 80 # million reads else: target_size = 5 # Gb target_size_reads = 20 # million reads max_splits = 100 # Avoid too many pieces, causing merge memory problems val = dd.get_align_split_size(data) umi_consensus = dd.get_umi_consensus(data) if val is None: if not umi_consensus: total_size = 0 # Gb # Use original files if we might have reduced the size of our prepped files input_files = data.get("files_orig", []) if dd.get_save_diskspace(data) else data.get("files", []) for fname in input_files: if os.path.exists(fname): total_size += os.path.getsize(fname) / (1024.0 * 1024.0 * 1024.0) # Only set if we have files and are bigger than the target size if total_size > target_size: data["config"]["algorithm"]["align_split_size"] = \ int(1e6 * _pick_align_split_size(total_size, target_size, target_size_reads, max_splits)) elif val: assert not umi_consensus, "Cannot set align_split_size to %s with UMI conensus specified" % val return data
[ "def", "_set_align_split_size", "(", "data", ")", ":", "if", "cwlutils", ".", "is_cwl_run", "(", "data", ")", ":", "target_size", "=", "20", "# Gb", "target_size_reads", "=", "80", "# million reads", "else", ":", "target_size", "=", "5", "# Gb", "target_size_r...
Set useful align_split_size, generating an estimate if it doesn't exist. We try to split on larger inputs and avoid too many pieces, aiming for size chunks of 5Gb or at most 50 maximum splits. The size estimate used in calculations is 20 million reads for ~5Gb. For UMI calculations we skip splitting since we're going to align and re-align after consensus. For CWL runs, we pick larger split sizes to avoid overhead of staging each chunk.
[ "Set", "useful", "align_split_size", "generating", "an", "estimate", "if", "it", "doesn", "t", "exist", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L64-L101
223,732
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_pick_align_split_size
def _pick_align_split_size(total_size, target_size, target_size_reads, max_splits): """Do the work of picking an alignment split size for the given criteria. """ # Too many pieces, increase our target size to get max_splits pieces if total_size // target_size > max_splits: piece_size = total_size // max_splits return int(piece_size * target_size_reads / target_size) else: return int(target_size_reads)
python
def _pick_align_split_size(total_size, target_size, target_size_reads, max_splits): """Do the work of picking an alignment split size for the given criteria. """ # Too many pieces, increase our target size to get max_splits pieces if total_size // target_size > max_splits: piece_size = total_size // max_splits return int(piece_size * target_size_reads / target_size) else: return int(target_size_reads)
[ "def", "_pick_align_split_size", "(", "total_size", ",", "target_size", ",", "target_size_reads", ",", "max_splits", ")", ":", "# Too many pieces, increase our target size to get max_splits pieces", "if", "total_size", "//", "target_size", ">", "max_splits", ":", "piece_size"...
Do the work of picking an alignment split size for the given criteria.
[ "Do", "the", "work", "of", "picking", "an", "alignment", "split", "size", "for", "the", "given", "criteria", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L103-L111
223,733
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
split_namedpipe_cls
def split_namedpipe_cls(pair1_file, pair2_file, data): """Create a commandline suitable for use as a named pipe with reads in a given region. """ if "align_split" in data: start, end = [int(x) for x in data["align_split"].split("-")] else: start, end = None, None if pair1_file.endswith(".sdf"): assert not pair2_file, pair2_file return rtg.to_fastq_apipe_cl(pair1_file, start, end) else: out = [] for in_file in pair1_file, pair2_file: if in_file: assert _get_grabix_index(in_file), "Need grabix index for %s" % in_file out.append("<(grabix grab {in_file} {start} {end})".format(**locals())) else: out.append(None) return out
python
def split_namedpipe_cls(pair1_file, pair2_file, data): """Create a commandline suitable for use as a named pipe with reads in a given region. """ if "align_split" in data: start, end = [int(x) for x in data["align_split"].split("-")] else: start, end = None, None if pair1_file.endswith(".sdf"): assert not pair2_file, pair2_file return rtg.to_fastq_apipe_cl(pair1_file, start, end) else: out = [] for in_file in pair1_file, pair2_file: if in_file: assert _get_grabix_index(in_file), "Need grabix index for %s" % in_file out.append("<(grabix grab {in_file} {start} {end})".format(**locals())) else: out.append(None) return out
[ "def", "split_namedpipe_cls", "(", "pair1_file", ",", "pair2_file", ",", "data", ")", ":", "if", "\"align_split\"", "in", "data", ":", "start", ",", "end", "=", "[", "int", "(", "x", ")", "for", "x", "in", "data", "[", "\"align_split\"", "]", ".", "spl...
Create a commandline suitable for use as a named pipe with reads in a given region.
[ "Create", "a", "commandline", "suitable", "for", "use", "as", "a", "named", "pipe", "with", "reads", "in", "a", "given", "region", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L113-L131
223,734
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_seqtk_fastq_prep_cl
def _seqtk_fastq_prep_cl(data, in_file=None, read_num=0): """Provide a commandline for prep of fastq inputs with seqtk. Handles fast conversion of fastq quality scores and trimming. """ needs_convert = dd.get_quality_format(data).lower() == "illumina" trim_ends = dd.get_trim_ends(data) seqtk = config_utils.get_program("seqtk", data["config"]) if in_file: in_file = objectstore.cl_input(in_file) else: in_file = "/dev/stdin" cmd = "" if needs_convert: cmd += "{seqtk} seq -Q64 -V {in_file}".format(**locals()) if trim_ends: left_trim, right_trim = trim_ends[0:2] if data.get("read_num", read_num) == 0 else trim_ends[2:4] if left_trim or right_trim: trim_infile = "/dev/stdin" if needs_convert else in_file pipe = " | " if needs_convert else "" cmd += "{pipe}{seqtk} trimfq -b {left_trim} -e {right_trim} {trim_infile}".format(**locals()) return cmd
python
def _seqtk_fastq_prep_cl(data, in_file=None, read_num=0): """Provide a commandline for prep of fastq inputs with seqtk. Handles fast conversion of fastq quality scores and trimming. """ needs_convert = dd.get_quality_format(data).lower() == "illumina" trim_ends = dd.get_trim_ends(data) seqtk = config_utils.get_program("seqtk", data["config"]) if in_file: in_file = objectstore.cl_input(in_file) else: in_file = "/dev/stdin" cmd = "" if needs_convert: cmd += "{seqtk} seq -Q64 -V {in_file}".format(**locals()) if trim_ends: left_trim, right_trim = trim_ends[0:2] if data.get("read_num", read_num) == 0 else trim_ends[2:4] if left_trim or right_trim: trim_infile = "/dev/stdin" if needs_convert else in_file pipe = " | " if needs_convert else "" cmd += "{pipe}{seqtk} trimfq -b {left_trim} -e {right_trim} {trim_infile}".format(**locals()) return cmd
[ "def", "_seqtk_fastq_prep_cl", "(", "data", ",", "in_file", "=", "None", ",", "read_num", "=", "0", ")", ":", "needs_convert", "=", "dd", ".", "get_quality_format", "(", "data", ")", ".", "lower", "(", ")", "==", "\"illumina\"", "trim_ends", "=", "dd", "...
Provide a commandline for prep of fastq inputs with seqtk. Handles fast conversion of fastq quality scores and trimming.
[ "Provide", "a", "commandline", "for", "prep", "of", "fastq", "inputs", "with", "seqtk", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L133-L154
223,735
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
fastq_convert_pipe_cl
def fastq_convert_pipe_cl(in_file, data): """Create an anonymous pipe converting Illumina 1.3-1.7 to Sanger. Uses seqtk: https://github.com/lh3/seqt """ cmd = _seqtk_fastq_prep_cl(data, in_file) if not cmd: cat_cmd = "zcat" if in_file.endswith(".gz") else "cat" cmd = cat_cmd + " " + in_file return "<(%s)" % cmd
python
def fastq_convert_pipe_cl(in_file, data): """Create an anonymous pipe converting Illumina 1.3-1.7 to Sanger. Uses seqtk: https://github.com/lh3/seqt """ cmd = _seqtk_fastq_prep_cl(data, in_file) if not cmd: cat_cmd = "zcat" if in_file.endswith(".gz") else "cat" cmd = cat_cmd + " " + in_file return "<(%s)" % cmd
[ "def", "fastq_convert_pipe_cl", "(", "in_file", ",", "data", ")", ":", "cmd", "=", "_seqtk_fastq_prep_cl", "(", "data", ",", "in_file", ")", "if", "not", "cmd", ":", "cat_cmd", "=", "\"zcat\"", "if", "in_file", ".", "endswith", "(", "\".gz\"", ")", "else",...
Create an anonymous pipe converting Illumina 1.3-1.7 to Sanger. Uses seqtk: https://github.com/lh3/seqt
[ "Create", "an", "anonymous", "pipe", "converting", "Illumina", "1", ".", "3", "-", "1", ".", "7", "to", "Sanger", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L156-L165
223,736
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
parallel_multiplier
def parallel_multiplier(items): """Determine if we will be parallelizing items during processing. """ multiplier = 1 for data in (x[0] for x in items): if (tz.get_in(["config", "algorithm", "align_split_size"], data) is not False and tz.get_in(["algorithm", "align_split_size"], data) is not False): multiplier += 50 return multiplier
python
def parallel_multiplier(items): """Determine if we will be parallelizing items during processing. """ multiplier = 1 for data in (x[0] for x in items): if (tz.get_in(["config", "algorithm", "align_split_size"], data) is not False and tz.get_in(["algorithm", "align_split_size"], data) is not False): multiplier += 50 return multiplier
[ "def", "parallel_multiplier", "(", "items", ")", ":", "multiplier", "=", "1", "for", "data", "in", "(", "x", "[", "0", "]", "for", "x", "in", "items", ")", ":", "if", "(", "tz", ".", "get_in", "(", "[", "\"config\"", ",", "\"algorithm\"", ",", "\"a...
Determine if we will be parallelizing items during processing.
[ "Determine", "if", "we", "will", "be", "parallelizing", "items", "during", "processing", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L169-L177
223,737
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
setup_combine
def setup_combine(final_file, data): """Setup the data and outputs to allow merging data back together. """ if "align_split" not in data: return final_file, data align_dir = os.path.dirname(final_file) base, ext = os.path.splitext(os.path.basename(final_file)) start, end = [int(x) for x in data["align_split"].split("-")] out_file = os.path.join(utils.safe_makedir(os.path.join(align_dir, "split")), "%s-%s_%s%s" % (base, start, end, ext)) data["combine"] = {"work_bam": {"out": final_file, "extras": []}} return out_file, data
python
def setup_combine(final_file, data): """Setup the data and outputs to allow merging data back together. """ if "align_split" not in data: return final_file, data align_dir = os.path.dirname(final_file) base, ext = os.path.splitext(os.path.basename(final_file)) start, end = [int(x) for x in data["align_split"].split("-")] out_file = os.path.join(utils.safe_makedir(os.path.join(align_dir, "split")), "%s-%s_%s%s" % (base, start, end, ext)) data["combine"] = {"work_bam": {"out": final_file, "extras": []}} return out_file, data
[ "def", "setup_combine", "(", "final_file", ",", "data", ")", ":", "if", "\"align_split\"", "not", "in", "data", ":", "return", "final_file", ",", "data", "align_dir", "=", "os", ".", "path", ".", "dirname", "(", "final_file", ")", "base", ",", "ext", "="...
Setup the data and outputs to allow merging data back together.
[ "Setup", "the", "data", "and", "outputs", "to", "allow", "merging", "data", "back", "together", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L181-L192
223,738
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
merge_split_alignments
def merge_split_alignments(samples, run_parallel): """Manage merging split alignments back into a final working BAM file. Perform de-duplication on the final merged file. """ ready = [] file_key = "work_bam" to_merge = collections.defaultdict(list) for data in (xs[0] for xs in samples): if data.get("combine"): out_key = tz.get_in(["combine", file_key, "out"], data) if not out_key: out_key = data["rgnames"]["lane"] to_merge[out_key].append(data) else: ready.append([data]) ready_merge = [] hla_merges = [] for mgroup in to_merge.values(): cur_data = mgroup[0] del cur_data["align_split"] for x in mgroup[1:]: cur_data["combine"][file_key]["extras"].append(x[file_key]) ready_merge.append([cur_data]) cur_hla = None for d in mgroup: hla_files = tz.get_in(["hla", "fastq"], d) if hla_files: if not cur_hla: cur_hla = {"rgnames": {"sample": dd.get_sample_name(cur_data)}, "config": cur_data["config"], "dirs": cur_data["dirs"], "hla": {"fastq": []}} cur_hla["hla"]["fastq"].append(hla_files) if cur_hla: hla_merges.append([cur_hla]) if not tz.get_in(["config", "algorithm", "kraken"], data): # kraken requires fasta filenames from data['files'] as input. # We don't want to remove those files if kraken qc is required. _save_fastq_space(samples) merged = run_parallel("delayed_bam_merge", ready_merge) hla_merge_raw = run_parallel("merge_split_alignments", hla_merges) hla_merges = {} for hla_merge in [x[0] for x in hla_merge_raw]: hla_merges[dd.get_sample_name(hla_merge)] = tz.get_in(["hla", "fastq"], hla_merge) # Add stable 'align_bam' target to use for retrieving raw alignment out = [] for data in [x[0] for x in merged + ready]: if data.get("work_bam"): data["align_bam"] = data["work_bam"] if dd.get_sample_name(data) in hla_merges: data["hla"]["fastq"] = hla_merges[dd.get_sample_name(data)] else: hla_files = glob.glob(os.path.join(dd.get_work_dir(data), "align", dd.get_sample_name(data), "hla", "*.fq")) if hla_files: data["hla"]["fastq"] = hla_files out.append([data]) return out
python
def merge_split_alignments(samples, run_parallel): """Manage merging split alignments back into a final working BAM file. Perform de-duplication on the final merged file. """ ready = [] file_key = "work_bam" to_merge = collections.defaultdict(list) for data in (xs[0] for xs in samples): if data.get("combine"): out_key = tz.get_in(["combine", file_key, "out"], data) if not out_key: out_key = data["rgnames"]["lane"] to_merge[out_key].append(data) else: ready.append([data]) ready_merge = [] hla_merges = [] for mgroup in to_merge.values(): cur_data = mgroup[0] del cur_data["align_split"] for x in mgroup[1:]: cur_data["combine"][file_key]["extras"].append(x[file_key]) ready_merge.append([cur_data]) cur_hla = None for d in mgroup: hla_files = tz.get_in(["hla", "fastq"], d) if hla_files: if not cur_hla: cur_hla = {"rgnames": {"sample": dd.get_sample_name(cur_data)}, "config": cur_data["config"], "dirs": cur_data["dirs"], "hla": {"fastq": []}} cur_hla["hla"]["fastq"].append(hla_files) if cur_hla: hla_merges.append([cur_hla]) if not tz.get_in(["config", "algorithm", "kraken"], data): # kraken requires fasta filenames from data['files'] as input. # We don't want to remove those files if kraken qc is required. _save_fastq_space(samples) merged = run_parallel("delayed_bam_merge", ready_merge) hla_merge_raw = run_parallel("merge_split_alignments", hla_merges) hla_merges = {} for hla_merge in [x[0] for x in hla_merge_raw]: hla_merges[dd.get_sample_name(hla_merge)] = tz.get_in(["hla", "fastq"], hla_merge) # Add stable 'align_bam' target to use for retrieving raw alignment out = [] for data in [x[0] for x in merged + ready]: if data.get("work_bam"): data["align_bam"] = data["work_bam"] if dd.get_sample_name(data) in hla_merges: data["hla"]["fastq"] = hla_merges[dd.get_sample_name(data)] else: hla_files = glob.glob(os.path.join(dd.get_work_dir(data), "align", dd.get_sample_name(data), "hla", "*.fq")) if hla_files: data["hla"]["fastq"] = hla_files out.append([data]) return out
[ "def", "merge_split_alignments", "(", "samples", ",", "run_parallel", ")", ":", "ready", "=", "[", "]", "file_key", "=", "\"work_bam\"", "to_merge", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "data", "in", "(", "xs", "[", "0", "]", ...
Manage merging split alignments back into a final working BAM file. Perform de-duplication on the final merged file.
[ "Manage", "merging", "split", "alignments", "back", "into", "a", "final", "working", "BAM", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L194-L252
223,739
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_save_fastq_space
def _save_fastq_space(items): """Potentially save fastq space prior to merging, since alignments done. """ to_cleanup = {} for data in (utils.to_single_data(x) for x in items): for fname in data.get("files", []): if os.path.realpath(fname).startswith(dd.get_work_dir(data)): to_cleanup[fname] = data["config"] for fname, config in to_cleanup.items(): utils.save_diskspace(fname, "Cleanup prep files after alignment finished", config)
python
def _save_fastq_space(items): """Potentially save fastq space prior to merging, since alignments done. """ to_cleanup = {} for data in (utils.to_single_data(x) for x in items): for fname in data.get("files", []): if os.path.realpath(fname).startswith(dd.get_work_dir(data)): to_cleanup[fname] = data["config"] for fname, config in to_cleanup.items(): utils.save_diskspace(fname, "Cleanup prep files after alignment finished", config)
[ "def", "_save_fastq_space", "(", "items", ")", ":", "to_cleanup", "=", "{", "}", "for", "data", "in", "(", "utils", ".", "to_single_data", "(", "x", ")", "for", "x", "in", "items", ")", ":", "for", "fname", "in", "data", ".", "get", "(", "\"files\"",...
Potentially save fastq space prior to merging, since alignments done.
[ "Potentially", "save", "fastq", "space", "prior", "to", "merging", "since", "alignments", "done", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L254-L263
223,740
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
total_reads_from_grabix
def total_reads_from_grabix(in_file): """Retrieve total reads in a fastq file from grabix index. """ gbi_file = _get_grabix_index(in_file) if gbi_file: with open(gbi_file) as in_handle: next(in_handle) # throw away num_lines = int(next(in_handle).strip()) assert num_lines % 4 == 0, "Expected lines to be multiple of 4" return num_lines // 4 else: return 0
python
def total_reads_from_grabix(in_file): """Retrieve total reads in a fastq file from grabix index. """ gbi_file = _get_grabix_index(in_file) if gbi_file: with open(gbi_file) as in_handle: next(in_handle) # throw away num_lines = int(next(in_handle).strip()) assert num_lines % 4 == 0, "Expected lines to be multiple of 4" return num_lines // 4 else: return 0
[ "def", "total_reads_from_grabix", "(", "in_file", ")", ":", "gbi_file", "=", "_get_grabix_index", "(", "in_file", ")", "if", "gbi_file", ":", "with", "open", "(", "gbi_file", ")", "as", "in_handle", ":", "next", "(", "in_handle", ")", "# throw away", "num_line...
Retrieve total reads in a fastq file from grabix index.
[ "Retrieve", "total", "reads", "in", "a", "fastq", "file", "from", "grabix", "index", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L281-L292
223,741
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_find_read_splits
def _find_read_splits(in_file, split_size): """Determine sections of fastq files to process in splits. Assumes a 4 line order to input files (name, read, name, quality). grabix is 1-based inclusive, so return coordinates in that format. """ num_lines = total_reads_from_grabix(in_file) * 4 assert num_lines and num_lines > 0, "Did not find grabix index reads: %s %s" % (in_file, num_lines) split_lines = split_size * 4 chunks = [] last = 1 for chunki in range(num_lines // split_lines + min(1, num_lines % split_lines)): new = last + split_lines - 1 chunks.append((last, min(new, num_lines))) last = new + 1 return ["%s-%s" % (s, e) for s, e in chunks]
python
def _find_read_splits(in_file, split_size): """Determine sections of fastq files to process in splits. Assumes a 4 line order to input files (name, read, name, quality). grabix is 1-based inclusive, so return coordinates in that format. """ num_lines = total_reads_from_grabix(in_file) * 4 assert num_lines and num_lines > 0, "Did not find grabix index reads: %s %s" % (in_file, num_lines) split_lines = split_size * 4 chunks = [] last = 1 for chunki in range(num_lines // split_lines + min(1, num_lines % split_lines)): new = last + split_lines - 1 chunks.append((last, min(new, num_lines))) last = new + 1 return ["%s-%s" % (s, e) for s, e in chunks]
[ "def", "_find_read_splits", "(", "in_file", ",", "split_size", ")", ":", "num_lines", "=", "total_reads_from_grabix", "(", "in_file", ")", "*", "4", "assert", "num_lines", "and", "num_lines", ">", "0", ",", "\"Did not find grabix index reads: %s %s\"", "%", "(", "...
Determine sections of fastq files to process in splits. Assumes a 4 line order to input files (name, read, name, quality). grabix is 1-based inclusive, so return coordinates in that format.
[ "Determine", "sections", "of", "fastq", "files", "to", "process", "in", "splits", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L294-L309
223,742
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_ready_gzip_fastq
def _ready_gzip_fastq(in_files, data, require_bgzip=False): """Check if we have gzipped fastq and don't need format conversion or splitting. Avoid forcing bgzip if we don't need indexed files. """ all_gzipped = all([not x or x.endswith(".gz") for x in in_files]) if require_bgzip and all_gzipped: all_gzipped = all([not x or not _check_gzipped_input(x, data)[0] for x in in_files]) needs_convert = dd.get_quality_format(data).lower() == "illumina" needs_trim = dd.get_trim_ends(data) do_splitting = dd.get_align_split_size(data) is not False return (all_gzipped and not needs_convert and not do_splitting and not objectstore.is_remote(in_files[0]) and not needs_trim and not get_downsample_params(data))
python
def _ready_gzip_fastq(in_files, data, require_bgzip=False): """Check if we have gzipped fastq and don't need format conversion or splitting. Avoid forcing bgzip if we don't need indexed files. """ all_gzipped = all([not x or x.endswith(".gz") for x in in_files]) if require_bgzip and all_gzipped: all_gzipped = all([not x or not _check_gzipped_input(x, data)[0] for x in in_files]) needs_convert = dd.get_quality_format(data).lower() == "illumina" needs_trim = dd.get_trim_ends(data) do_splitting = dd.get_align_split_size(data) is not False return (all_gzipped and not needs_convert and not do_splitting and not objectstore.is_remote(in_files[0]) and not needs_trim and not get_downsample_params(data))
[ "def", "_ready_gzip_fastq", "(", "in_files", ",", "data", ",", "require_bgzip", "=", "False", ")", ":", "all_gzipped", "=", "all", "(", "[", "not", "x", "or", "x", ".", "endswith", "(", "\".gz\"", ")", "for", "x", "in", "in_files", "]", ")", "if", "r...
Check if we have gzipped fastq and don't need format conversion or splitting. Avoid forcing bgzip if we don't need indexed files.
[ "Check", "if", "we", "have", "gzipped", "fastq", "and", "don", "t", "need", "format", "conversion", "or", "splitting", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L319-L331
223,743
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
prep_fastq_inputs
def prep_fastq_inputs(in_files, data): """Prepare bgzipped fastq inputs """ if len(in_files) == 1 and _is_bam_input(in_files): out = _bgzip_from_bam(in_files[0], data["dirs"], data) elif len(in_files) == 1 and _is_cram_input(in_files): out = _bgzip_from_cram(in_files[0], data["dirs"], data) elif len(in_files) in [1, 2] and _ready_gzip_fastq(in_files, data): out = _symlink_in_files(in_files, data) else: if len(in_files) > 2: fpairs = fastq.combine_pairs(in_files) pair_types = set([len(xs) for xs in fpairs]) assert len(pair_types) == 1 fpairs.sort(key=lambda x: os.path.basename(x[0])) organized = [[xs[0] for xs in fpairs]] if len(fpairs[0]) > 1: organized.append([xs[1] for xs in fpairs]) in_files = organized parallel = {"type": "local", "num_jobs": len(in_files), "cores_per_job": max(1, data["config"]["algorithm"]["num_cores"] // len(in_files))} inputs = [{"in_file": x, "read_num": i, "dirs": data["dirs"], "config": data["config"], "is_cwl": "cwl_keys" in data, "rgnames": data["rgnames"]} for i, x in enumerate(in_files) if x] out = run_multicore(_bgzip_from_fastq_parallel, [[d] for d in inputs], data["config"], parallel) return out
python
def prep_fastq_inputs(in_files, data): """Prepare bgzipped fastq inputs """ if len(in_files) == 1 and _is_bam_input(in_files): out = _bgzip_from_bam(in_files[0], data["dirs"], data) elif len(in_files) == 1 and _is_cram_input(in_files): out = _bgzip_from_cram(in_files[0], data["dirs"], data) elif len(in_files) in [1, 2] and _ready_gzip_fastq(in_files, data): out = _symlink_in_files(in_files, data) else: if len(in_files) > 2: fpairs = fastq.combine_pairs(in_files) pair_types = set([len(xs) for xs in fpairs]) assert len(pair_types) == 1 fpairs.sort(key=lambda x: os.path.basename(x[0])) organized = [[xs[0] for xs in fpairs]] if len(fpairs[0]) > 1: organized.append([xs[1] for xs in fpairs]) in_files = organized parallel = {"type": "local", "num_jobs": len(in_files), "cores_per_job": max(1, data["config"]["algorithm"]["num_cores"] // len(in_files))} inputs = [{"in_file": x, "read_num": i, "dirs": data["dirs"], "config": data["config"], "is_cwl": "cwl_keys" in data, "rgnames": data["rgnames"]} for i, x in enumerate(in_files) if x] out = run_multicore(_bgzip_from_fastq_parallel, [[d] for d in inputs], data["config"], parallel) return out
[ "def", "prep_fastq_inputs", "(", "in_files", ",", "data", ")", ":", "if", "len", "(", "in_files", ")", "==", "1", "and", "_is_bam_input", "(", "in_files", ")", ":", "out", "=", "_bgzip_from_bam", "(", "in_files", "[", "0", "]", ",", "data", "[", "\"dir...
Prepare bgzipped fastq inputs
[ "Prepare", "bgzipped", "fastq", "inputs" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L333-L359
223,744
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_symlink_or_copy_grabix
def _symlink_or_copy_grabix(in_file, out_file, data): """We cannot symlink in CWL, but may be able to use inputs or copy """ if cwlutils.is_cwl_run(data): # Has grabix indexes, we're okay to go if utils.file_exists(in_file + ".gbi"): out_file = in_file else: utils.copy_plus(in_file, out_file) else: utils.symlink_plus(in_file, out_file) return out_file
python
def _symlink_or_copy_grabix(in_file, out_file, data): """We cannot symlink in CWL, but may be able to use inputs or copy """ if cwlutils.is_cwl_run(data): # Has grabix indexes, we're okay to go if utils.file_exists(in_file + ".gbi"): out_file = in_file else: utils.copy_plus(in_file, out_file) else: utils.symlink_plus(in_file, out_file) return out_file
[ "def", "_symlink_or_copy_grabix", "(", "in_file", ",", "out_file", ",", "data", ")", ":", "if", "cwlutils", ".", "is_cwl_run", "(", "data", ")", ":", "# Has grabix indexes, we're okay to go", "if", "utils", ".", "file_exists", "(", "in_file", "+", "\".gbi\"", ")...
We cannot symlink in CWL, but may be able to use inputs or copy
[ "We", "cannot", "symlink", "in", "CWL", "but", "may", "be", "able", "to", "use", "inputs", "or", "copy" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L372-L383
223,745
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_prep_grabix_indexes
def _prep_grabix_indexes(in_files, data): """Parallel preparation of grabix indexes for files. """ # if we have gzipped but not bgzipped, add a fake index for CWL support # Also skips bgzip indexing if we don't need alignment splitting if _ready_gzip_fastq(in_files, data) and (not _ready_gzip_fastq(in_files, data, require_bgzip=True) or dd.get_align_split_size(data) is False): for in_file in in_files: if not utils.file_exists(in_file + ".gbi"): with file_transaction(data, in_file + ".gbi") as tx_gbi_file: with open(tx_gbi_file, "w") as out_handle: out_handle.write("Not grabix indexed; index added for compatibility.\n") else: items = [[{"bgzip_file": x, "config": copy.deepcopy(data["config"])}] for x in in_files if x] run_multicore(_grabix_index, items, data["config"]) return data
python
def _prep_grabix_indexes(in_files, data): """Parallel preparation of grabix indexes for files. """ # if we have gzipped but not bgzipped, add a fake index for CWL support # Also skips bgzip indexing if we don't need alignment splitting if _ready_gzip_fastq(in_files, data) and (not _ready_gzip_fastq(in_files, data, require_bgzip=True) or dd.get_align_split_size(data) is False): for in_file in in_files: if not utils.file_exists(in_file + ".gbi"): with file_transaction(data, in_file + ".gbi") as tx_gbi_file: with open(tx_gbi_file, "w") as out_handle: out_handle.write("Not grabix indexed; index added for compatibility.\n") else: items = [[{"bgzip_file": x, "config": copy.deepcopy(data["config"])}] for x in in_files if x] run_multicore(_grabix_index, items, data["config"]) return data
[ "def", "_prep_grabix_indexes", "(", "in_files", ",", "data", ")", ":", "# if we have gzipped but not bgzipped, add a fake index for CWL support", "# Also skips bgzip indexing if we don't need alignment splitting", "if", "_ready_gzip_fastq", "(", "in_files", ",", "data", ")", "and",...
Parallel preparation of grabix indexes for files.
[ "Parallel", "preparation", "of", "grabix", "indexes", "for", "files", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L385-L400
223,746
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_bgzip_from_cram
def _bgzip_from_cram(cram_file, dirs, data): """Create bgzipped fastq files from an input CRAM file in regions of interest. Returns a list with a single file, for single end CRAM files, or two files for paired end input. """ import pybedtools region_file = (tz.get_in(["config", "algorithm", "variant_regions"], data) if tz.get_in(["config", "algorithm", "coverage_interval"], data) in ["regional", "exome", "amplicon"] else None) if region_file: regions = ["%s:%s-%s" % tuple(r[:3]) for r in pybedtools.BedTool(region_file)] else: regions = [None] work_dir = utils.safe_makedir(os.path.join(dirs["work"], "align_prep")) out_s, out_p1, out_p2 = [os.path.join(work_dir, "%s-%s.fq.gz" % (utils.splitext_plus(os.path.basename(cram_file))[0], fext)) for fext in ["s1", "p1", "p2"]] if (not utils.file_exists(out_s) and (not utils.file_exists(out_p1) or not utils.file_exists(out_p2))): cram.index(cram_file, data["config"]) fastqs, part_dir = _cram_to_fastq_regions(regions, cram_file, dirs, data) if len(fastqs[0]) == 1: with file_transaction(data, out_s) as tx_out_file: _merge_and_bgzip([xs[0] for xs in fastqs], tx_out_file, out_s) else: for i, out_file in enumerate([out_p1, out_p2]): if not utils.file_exists(out_file): ext = "/%s" % (i + 1) with file_transaction(data, out_file) as tx_out_file: _merge_and_bgzip([xs[i] for xs in fastqs], tx_out_file, out_file, ext) shutil.rmtree(part_dir) if utils.file_exists(out_p1): return [out_p1, out_p2] else: assert utils.file_exists(out_s) return [out_s]
python
def _bgzip_from_cram(cram_file, dirs, data): """Create bgzipped fastq files from an input CRAM file in regions of interest. Returns a list with a single file, for single end CRAM files, or two files for paired end input. """ import pybedtools region_file = (tz.get_in(["config", "algorithm", "variant_regions"], data) if tz.get_in(["config", "algorithm", "coverage_interval"], data) in ["regional", "exome", "amplicon"] else None) if region_file: regions = ["%s:%s-%s" % tuple(r[:3]) for r in pybedtools.BedTool(region_file)] else: regions = [None] work_dir = utils.safe_makedir(os.path.join(dirs["work"], "align_prep")) out_s, out_p1, out_p2 = [os.path.join(work_dir, "%s-%s.fq.gz" % (utils.splitext_plus(os.path.basename(cram_file))[0], fext)) for fext in ["s1", "p1", "p2"]] if (not utils.file_exists(out_s) and (not utils.file_exists(out_p1) or not utils.file_exists(out_p2))): cram.index(cram_file, data["config"]) fastqs, part_dir = _cram_to_fastq_regions(regions, cram_file, dirs, data) if len(fastqs[0]) == 1: with file_transaction(data, out_s) as tx_out_file: _merge_and_bgzip([xs[0] for xs in fastqs], tx_out_file, out_s) else: for i, out_file in enumerate([out_p1, out_p2]): if not utils.file_exists(out_file): ext = "/%s" % (i + 1) with file_transaction(data, out_file) as tx_out_file: _merge_and_bgzip([xs[i] for xs in fastqs], tx_out_file, out_file, ext) shutil.rmtree(part_dir) if utils.file_exists(out_p1): return [out_p1, out_p2] else: assert utils.file_exists(out_s) return [out_s]
[ "def", "_bgzip_from_cram", "(", "cram_file", ",", "dirs", ",", "data", ")", ":", "import", "pybedtools", "region_file", "=", "(", "tz", ".", "get_in", "(", "[", "\"config\"", ",", "\"algorithm\"", ",", "\"variant_regions\"", "]", ",", "data", ")", "if", "t...
Create bgzipped fastq files from an input CRAM file in regions of interest. Returns a list with a single file, for single end CRAM files, or two files for paired end input.
[ "Create", "bgzipped", "fastq", "files", "from", "an", "input", "CRAM", "file", "in", "regions", "of", "interest", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L402-L439
223,747
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_bgzip_from_cram_sambamba
def _bgzip_from_cram_sambamba(cram_file, dirs, data): """Use sambamba to extract from CRAM via regions. """ raise NotImplementedError("sambamba doesn't yet support retrieval from CRAM by BED file") region_file = (tz.get_in(["config", "algorithm", "variant_regions"], data) if tz.get_in(["config", "algorithm", "coverage_interval"], data) in ["regional", "exome"] else None) base_name = utils.splitext_plus(os.path.basename(cram_file))[0] work_dir = utils.safe_makedir(os.path.join(dirs["work"], "align_prep", "%s-parts" % base_name)) f1, f2, o1, o2, si = [os.path.join(work_dir, "%s.fq" % x) for x in ["match1", "match2", "unmatch1", "unmatch2", "single"]] ref_file = dd.get_ref_file(data) region = "-L %s" % region_file if region_file else "" cmd = ("sambamba view -f bam -l 0 -C {cram_file} -T {ref_file} {region} | " "bamtofastq F={f1} F2={f2} S={si} O={o1} O2={o2}") do.run(cmd.format(**locals()), "Convert CRAM to fastq in regions")
python
def _bgzip_from_cram_sambamba(cram_file, dirs, data): """Use sambamba to extract from CRAM via regions. """ raise NotImplementedError("sambamba doesn't yet support retrieval from CRAM by BED file") region_file = (tz.get_in(["config", "algorithm", "variant_regions"], data) if tz.get_in(["config", "algorithm", "coverage_interval"], data) in ["regional", "exome"] else None) base_name = utils.splitext_plus(os.path.basename(cram_file))[0] work_dir = utils.safe_makedir(os.path.join(dirs["work"], "align_prep", "%s-parts" % base_name)) f1, f2, o1, o2, si = [os.path.join(work_dir, "%s.fq" % x) for x in ["match1", "match2", "unmatch1", "unmatch2", "single"]] ref_file = dd.get_ref_file(data) region = "-L %s" % region_file if region_file else "" cmd = ("sambamba view -f bam -l 0 -C {cram_file} -T {ref_file} {region} | " "bamtofastq F={f1} F2={f2} S={si} O={o1} O2={o2}") do.run(cmd.format(**locals()), "Convert CRAM to fastq in regions")
[ "def", "_bgzip_from_cram_sambamba", "(", "cram_file", ",", "dirs", ",", "data", ")", ":", "raise", "NotImplementedError", "(", "\"sambamba doesn't yet support retrieval from CRAM by BED file\"", ")", "region_file", "=", "(", "tz", ".", "get_in", "(", "[", "\"config\"", ...
Use sambamba to extract from CRAM via regions.
[ "Use", "sambamba", "to", "extract", "from", "CRAM", "via", "regions", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L441-L457
223,748
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_cram_to_fastq_regions
def _cram_to_fastq_regions(regions, cram_file, dirs, data): """Convert CRAM files to fastq, potentially within sub regions. Returns multiple fastq files that can be merged back together. """ base_name = utils.splitext_plus(os.path.basename(cram_file))[0] work_dir = utils.safe_makedir(os.path.join(dirs["work"], "align_prep", "%s-parts" % base_name)) fnames = run_multicore(_cram_to_fastq_region, [(cram_file, work_dir, base_name, region, data) for region in regions], data["config"]) # check if we have paired or single end data if any(not _is_gzip_empty(p1) for p1, p2, s in fnames): out = [[p1, p2] for p1, p2, s in fnames] else: out = [[s] for p1, p2, s in fnames] return out, work_dir
python
def _cram_to_fastq_regions(regions, cram_file, dirs, data): """Convert CRAM files to fastq, potentially within sub regions. Returns multiple fastq files that can be merged back together. """ base_name = utils.splitext_plus(os.path.basename(cram_file))[0] work_dir = utils.safe_makedir(os.path.join(dirs["work"], "align_prep", "%s-parts" % base_name)) fnames = run_multicore(_cram_to_fastq_region, [(cram_file, work_dir, base_name, region, data) for region in regions], data["config"]) # check if we have paired or single end data if any(not _is_gzip_empty(p1) for p1, p2, s in fnames): out = [[p1, p2] for p1, p2, s in fnames] else: out = [[s] for p1, p2, s in fnames] return out, work_dir
[ "def", "_cram_to_fastq_regions", "(", "regions", ",", "cram_file", ",", "dirs", ",", "data", ")", ":", "base_name", "=", "utils", ".", "splitext_plus", "(", "os", ".", "path", ".", "basename", "(", "cram_file", ")", ")", "[", "0", "]", "work_dir", "=", ...
Convert CRAM files to fastq, potentially within sub regions. Returns multiple fastq files that can be merged back together.
[ "Convert", "CRAM", "files", "to", "fastq", "potentially", "within", "sub", "regions", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L482-L498
223,749
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_cram_to_fastq_region
def _cram_to_fastq_region(cram_file, work_dir, base_name, region, data): """Convert CRAM to fastq in a specified region. """ ref_file = tz.get_in(["reference", "fasta", "base"], data) resources = config_utils.get_resources("bamtofastq", data["config"]) cores = tz.get_in(["config", "algorithm", "num_cores"], data, 1) max_mem = config_utils.convert_to_bytes(resources.get("memory", "1G")) * cores rext = "-%s" % region.replace(":", "_").replace("-", "_") if region else "full" out_s, out_p1, out_p2, out_o1, out_o2 = [os.path.join(work_dir, "%s%s-%s.fq.gz" % (base_name, rext, fext)) for fext in ["s1", "p1", "p2", "o1", "o2"]] if not utils.file_exists(out_p1): with file_transaction(data, out_s, out_p1, out_p2, out_o1, out_o2) as \ (tx_out_s, tx_out_p1, tx_out_p2, tx_out_o1, tx_out_o2): cram_file = objectstore.cl_input(cram_file) sortprefix = "%s-sort" % utils.splitext_plus(tx_out_s)[0] cmd = ("bamtofastq filename={cram_file} inputformat=cram T={sortprefix} " "gz=1 collate=1 colsbs={max_mem} exclude=SECONDARY,SUPPLEMENTARY " "F={tx_out_p1} F2={tx_out_p2} S={tx_out_s} O={tx_out_o1} O2={tx_out_o2} " "reference={ref_file}") if region: cmd += " ranges='{region}'" do.run(cmd.format(**locals()), "CRAM to fastq %s" % region if region else "") return [[out_p1, out_p2, out_s]]
python
def _cram_to_fastq_region(cram_file, work_dir, base_name, region, data): """Convert CRAM to fastq in a specified region. """ ref_file = tz.get_in(["reference", "fasta", "base"], data) resources = config_utils.get_resources("bamtofastq", data["config"]) cores = tz.get_in(["config", "algorithm", "num_cores"], data, 1) max_mem = config_utils.convert_to_bytes(resources.get("memory", "1G")) * cores rext = "-%s" % region.replace(":", "_").replace("-", "_") if region else "full" out_s, out_p1, out_p2, out_o1, out_o2 = [os.path.join(work_dir, "%s%s-%s.fq.gz" % (base_name, rext, fext)) for fext in ["s1", "p1", "p2", "o1", "o2"]] if not utils.file_exists(out_p1): with file_transaction(data, out_s, out_p1, out_p2, out_o1, out_o2) as \ (tx_out_s, tx_out_p1, tx_out_p2, tx_out_o1, tx_out_o2): cram_file = objectstore.cl_input(cram_file) sortprefix = "%s-sort" % utils.splitext_plus(tx_out_s)[0] cmd = ("bamtofastq filename={cram_file} inputformat=cram T={sortprefix} " "gz=1 collate=1 colsbs={max_mem} exclude=SECONDARY,SUPPLEMENTARY " "F={tx_out_p1} F2={tx_out_p2} S={tx_out_s} O={tx_out_o1} O2={tx_out_o2} " "reference={ref_file}") if region: cmd += " ranges='{region}'" do.run(cmd.format(**locals()), "CRAM to fastq %s" % region if region else "") return [[out_p1, out_p2, out_s]]
[ "def", "_cram_to_fastq_region", "(", "cram_file", ",", "work_dir", ",", "base_name", ",", "region", ",", "data", ")", ":", "ref_file", "=", "tz", ".", "get_in", "(", "[", "\"reference\"", ",", "\"fasta\"", ",", "\"base\"", "]", ",", "data", ")", "resources...
Convert CRAM to fastq in a specified region.
[ "Convert", "CRAM", "to", "fastq", "in", "a", "specified", "region", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L502-L525
223,750
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_bgzip_from_bam
def _bgzip_from_bam(bam_file, dirs, data, is_retry=False, output_infix=''): """Create bgzipped fastq files from an input BAM file. """ # tools config = data["config"] bamtofastq = config_utils.get_program("bamtofastq", config) resources = config_utils.get_resources("bamtofastq", config) cores = config["algorithm"].get("num_cores", 1) max_mem = config_utils.convert_to_bytes(resources.get("memory", "1G")) * cores bgzip = tools.get_bgzip_cmd(config, is_retry) # files work_dir = utils.safe_makedir(os.path.join(dirs["work"], "align_prep")) out_file_1 = os.path.join(work_dir, "%s%s-1.fq.gz" % (os.path.splitext(os.path.basename(bam_file))[0], output_infix)) out_file_2 = out_file_1.replace("-1.fq.gz", "-2.fq.gz") needs_retry = False if is_retry or not utils.file_exists(out_file_1): if not bam.is_paired(bam_file): out_file_2 = None with file_transaction(config, out_file_1) as tx_out_file: for f in [tx_out_file, out_file_1, out_file_2]: if f and os.path.exists(f): os.remove(f) fq1_bgzip_cmd = "%s -c /dev/stdin > %s" % (bgzip, tx_out_file) prep_cmd = _seqtk_fastq_prep_cl(data, read_num=0) if prep_cmd: fq1_bgzip_cmd = prep_cmd + " | " + fq1_bgzip_cmd sortprefix = "%s-sort" % os.path.splitext(tx_out_file)[0] if bam.is_paired(bam_file): prep_cmd = _seqtk_fastq_prep_cl(data, read_num=1) fq2_bgzip_cmd = "%s -c /dev/stdin > %s" % (bgzip, out_file_2) if prep_cmd: fq2_bgzip_cmd = prep_cmd + " | " + fq2_bgzip_cmd out_str = ("F=>({fq1_bgzip_cmd}) F2=>({fq2_bgzip_cmd}) S=/dev/null O=/dev/null " "O2=/dev/null collate=1 colsbs={max_mem}") else: out_str = "S=>({fq1_bgzip_cmd})" bam_file = objectstore.cl_input(bam_file) extra_opts = " ".join([str(x) for x in resources.get("options", [])]) cmd = "{bamtofastq} filename={bam_file} T={sortprefix} {extra_opts} " + out_str try: do.run(cmd.format(**locals()), "BAM to bgzipped fastq", checks=[do.file_reasonable_size(tx_out_file, bam_file)], log_error=False) except subprocess.CalledProcessError as msg: if not is_retry and "deflate failed" in str(msg): logger.info("bamtofastq deflate IO failure preparing %s. Retrying with single core." % (bam_file)) needs_retry = True else: logger.exception() raise if needs_retry: return _bgzip_from_bam(bam_file, dirs, data, is_retry=True) else: return [x for x in [out_file_1, out_file_2] if x is not None and utils.file_exists(x)]
python
def _bgzip_from_bam(bam_file, dirs, data, is_retry=False, output_infix=''): """Create bgzipped fastq files from an input BAM file. """ # tools config = data["config"] bamtofastq = config_utils.get_program("bamtofastq", config) resources = config_utils.get_resources("bamtofastq", config) cores = config["algorithm"].get("num_cores", 1) max_mem = config_utils.convert_to_bytes(resources.get("memory", "1G")) * cores bgzip = tools.get_bgzip_cmd(config, is_retry) # files work_dir = utils.safe_makedir(os.path.join(dirs["work"], "align_prep")) out_file_1 = os.path.join(work_dir, "%s%s-1.fq.gz" % (os.path.splitext(os.path.basename(bam_file))[0], output_infix)) out_file_2 = out_file_1.replace("-1.fq.gz", "-2.fq.gz") needs_retry = False if is_retry or not utils.file_exists(out_file_1): if not bam.is_paired(bam_file): out_file_2 = None with file_transaction(config, out_file_1) as tx_out_file: for f in [tx_out_file, out_file_1, out_file_2]: if f and os.path.exists(f): os.remove(f) fq1_bgzip_cmd = "%s -c /dev/stdin > %s" % (bgzip, tx_out_file) prep_cmd = _seqtk_fastq_prep_cl(data, read_num=0) if prep_cmd: fq1_bgzip_cmd = prep_cmd + " | " + fq1_bgzip_cmd sortprefix = "%s-sort" % os.path.splitext(tx_out_file)[0] if bam.is_paired(bam_file): prep_cmd = _seqtk_fastq_prep_cl(data, read_num=1) fq2_bgzip_cmd = "%s -c /dev/stdin > %s" % (bgzip, out_file_2) if prep_cmd: fq2_bgzip_cmd = prep_cmd + " | " + fq2_bgzip_cmd out_str = ("F=>({fq1_bgzip_cmd}) F2=>({fq2_bgzip_cmd}) S=/dev/null O=/dev/null " "O2=/dev/null collate=1 colsbs={max_mem}") else: out_str = "S=>({fq1_bgzip_cmd})" bam_file = objectstore.cl_input(bam_file) extra_opts = " ".join([str(x) for x in resources.get("options", [])]) cmd = "{bamtofastq} filename={bam_file} T={sortprefix} {extra_opts} " + out_str try: do.run(cmd.format(**locals()), "BAM to bgzipped fastq", checks=[do.file_reasonable_size(tx_out_file, bam_file)], log_error=False) except subprocess.CalledProcessError as msg: if not is_retry and "deflate failed" in str(msg): logger.info("bamtofastq deflate IO failure preparing %s. Retrying with single core." % (bam_file)) needs_retry = True else: logger.exception() raise if needs_retry: return _bgzip_from_bam(bam_file, dirs, data, is_retry=True) else: return [x for x in [out_file_1, out_file_2] if x is not None and utils.file_exists(x)]
[ "def", "_bgzip_from_bam", "(", "bam_file", ",", "dirs", ",", "data", ",", "is_retry", "=", "False", ",", "output_infix", "=", "''", ")", ":", "# tools", "config", "=", "data", "[", "\"config\"", "]", "bamtofastq", "=", "config_utils", ".", "get_program", "...
Create bgzipped fastq files from an input BAM file.
[ "Create", "bgzipped", "fastq", "files", "from", "an", "input", "BAM", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L532-L586
223,751
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_grabix_index
def _grabix_index(data): """Create grabix index of bgzip input file. grabix does not allow specification of output file, so symlink the original file into a transactional directory. """ in_file = data["bgzip_file"] config = data["config"] grabix = config_utils.get_program("grabix", config) gbi_file = _get_grabix_index(in_file) # We always build grabix input so we can use it for counting reads and doing downsampling if not gbi_file or _is_partial_index(gbi_file): if gbi_file: utils.remove_safe(gbi_file) else: gbi_file = in_file + ".gbi" with file_transaction(data, gbi_file) as tx_gbi_file: tx_in_file = os.path.splitext(tx_gbi_file)[0] utils.symlink_plus(in_file, tx_in_file) do.run([grabix, "index", tx_in_file], "Index input with grabix: %s" % os.path.basename(in_file)) assert utils.file_exists(gbi_file) return [gbi_file]
python
def _grabix_index(data): """Create grabix index of bgzip input file. grabix does not allow specification of output file, so symlink the original file into a transactional directory. """ in_file = data["bgzip_file"] config = data["config"] grabix = config_utils.get_program("grabix", config) gbi_file = _get_grabix_index(in_file) # We always build grabix input so we can use it for counting reads and doing downsampling if not gbi_file or _is_partial_index(gbi_file): if gbi_file: utils.remove_safe(gbi_file) else: gbi_file = in_file + ".gbi" with file_transaction(data, gbi_file) as tx_gbi_file: tx_in_file = os.path.splitext(tx_gbi_file)[0] utils.symlink_plus(in_file, tx_in_file) do.run([grabix, "index", tx_in_file], "Index input with grabix: %s" % os.path.basename(in_file)) assert utils.file_exists(gbi_file) return [gbi_file]
[ "def", "_grabix_index", "(", "data", ")", ":", "in_file", "=", "data", "[", "\"bgzip_file\"", "]", "config", "=", "data", "[", "\"config\"", "]", "grabix", "=", "config_utils", ".", "get_program", "(", "\"grabix\"", ",", "config", ")", "gbi_file", "=", "_g...
Create grabix index of bgzip input file. grabix does not allow specification of output file, so symlink the original file into a transactional directory.
[ "Create", "grabix", "index", "of", "bgzip", "input", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L590-L611
223,752
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_is_partial_index
def _is_partial_index(gbi_file): """Check for truncated output since grabix doesn't write to a transactional directory. """ with open(gbi_file) as in_handle: for i, _ in enumerate(in_handle): if i > 2: return False return True
python
def _is_partial_index(gbi_file): """Check for truncated output since grabix doesn't write to a transactional directory. """ with open(gbi_file) as in_handle: for i, _ in enumerate(in_handle): if i > 2: return False return True
[ "def", "_is_partial_index", "(", "gbi_file", ")", ":", "with", "open", "(", "gbi_file", ")", "as", "in_handle", ":", "for", "i", ",", "_", "in", "enumerate", "(", "in_handle", ")", ":", "if", "i", ">", "2", ":", "return", "False", "return", "True" ]
Check for truncated output since grabix doesn't write to a transactional directory.
[ "Check", "for", "truncated", "output", "since", "grabix", "doesn", "t", "write", "to", "a", "transactional", "directory", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L613-L620
223,753
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_bgzip_file
def _bgzip_file(finput, config, work_dir, needs_bgzip, needs_gunzip, needs_convert, data): """Handle bgzip of input file, potentially gunzipping an existing file. Handles cases where finput might be multiple files and need to be concatenated. """ if isinstance(finput, six.string_types): in_file = finput else: assert not needs_convert, "Do not yet handle quality conversion with multiple inputs" return _bgzip_multiple_files(finput, work_dir, data) out_file = os.path.join(work_dir, os.path.basename(in_file).replace(".bz2", "") + (".gz" if not in_file.endswith(".gz") else "")) if not utils.file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: bgzip = tools.get_bgzip_cmd(config) is_remote = objectstore.is_remote(in_file) in_file = objectstore.cl_input(in_file, unpack=needs_gunzip or needs_convert or needs_bgzip or dd.get_trim_ends(data)) if needs_convert or dd.get_trim_ends(data): in_file = fastq_convert_pipe_cl(in_file, data) if needs_gunzip and not (needs_convert or dd.get_trim_ends(data)): if in_file.endswith(".bz2"): gunzip_cmd = "bunzip2 -c {in_file} |".format(**locals()) else: gunzip_cmd = "gunzip -c {in_file} |".format(**locals()) bgzip_in = "/dev/stdin" else: gunzip_cmd = "" bgzip_in = in_file if needs_bgzip: do.run("{gunzip_cmd} {bgzip} -c {bgzip_in} > {tx_out_file}".format(**locals()), "bgzip input file") elif is_remote: bgzip = "| bgzip -c" if (needs_convert or dd.get_trim_ends(data)) else "" do.run("cat {in_file} {bgzip} > {tx_out_file}".format(**locals()), "Get remote input") else: raise ValueError("Unexpected inputs: %s %s %s %s" % (in_file, needs_bgzip, needs_gunzip, needs_convert)) return out_file
python
def _bgzip_file(finput, config, work_dir, needs_bgzip, needs_gunzip, needs_convert, data): """Handle bgzip of input file, potentially gunzipping an existing file. Handles cases where finput might be multiple files and need to be concatenated. """ if isinstance(finput, six.string_types): in_file = finput else: assert not needs_convert, "Do not yet handle quality conversion with multiple inputs" return _bgzip_multiple_files(finput, work_dir, data) out_file = os.path.join(work_dir, os.path.basename(in_file).replace(".bz2", "") + (".gz" if not in_file.endswith(".gz") else "")) if not utils.file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: bgzip = tools.get_bgzip_cmd(config) is_remote = objectstore.is_remote(in_file) in_file = objectstore.cl_input(in_file, unpack=needs_gunzip or needs_convert or needs_bgzip or dd.get_trim_ends(data)) if needs_convert or dd.get_trim_ends(data): in_file = fastq_convert_pipe_cl(in_file, data) if needs_gunzip and not (needs_convert or dd.get_trim_ends(data)): if in_file.endswith(".bz2"): gunzip_cmd = "bunzip2 -c {in_file} |".format(**locals()) else: gunzip_cmd = "gunzip -c {in_file} |".format(**locals()) bgzip_in = "/dev/stdin" else: gunzip_cmd = "" bgzip_in = in_file if needs_bgzip: do.run("{gunzip_cmd} {bgzip} -c {bgzip_in} > {tx_out_file}".format(**locals()), "bgzip input file") elif is_remote: bgzip = "| bgzip -c" if (needs_convert or dd.get_trim_ends(data)) else "" do.run("cat {in_file} {bgzip} > {tx_out_file}".format(**locals()), "Get remote input") else: raise ValueError("Unexpected inputs: %s %s %s %s" % (in_file, needs_bgzip, needs_gunzip, needs_convert)) return out_file
[ "def", "_bgzip_file", "(", "finput", ",", "config", ",", "work_dir", ",", "needs_bgzip", ",", "needs_gunzip", ",", "needs_convert", ",", "data", ")", ":", "if", "isinstance", "(", "finput", ",", "six", ".", "string_types", ")", ":", "in_file", "=", "finput...
Handle bgzip of input file, potentially gunzipping an existing file. Handles cases where finput might be multiple files and need to be concatenated.
[ "Handle", "bgzip", "of", "input", "file", "potentially", "gunzipping", "an", "existing", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L659-L697
223,754
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
_check_gzipped_input
def _check_gzipped_input(in_file, data): """Determine if a gzipped input file is blocked gzip or standard. """ grabix = config_utils.get_program("grabix", data["config"]) is_bgzip = subprocess.check_output([grabix, "check", in_file]) if is_bgzip.strip() == "yes": return False, False else: return True, True
python
def _check_gzipped_input(in_file, data): """Determine if a gzipped input file is blocked gzip or standard. """ grabix = config_utils.get_program("grabix", data["config"]) is_bgzip = subprocess.check_output([grabix, "check", in_file]) if is_bgzip.strip() == "yes": return False, False else: return True, True
[ "def", "_check_gzipped_input", "(", "in_file", ",", "data", ")", ":", "grabix", "=", "config_utils", ".", "get_program", "(", "\"grabix\"", ",", "data", "[", "\"config\"", "]", ")", "is_bgzip", "=", "subprocess", ".", "check_output", "(", "[", "grabix", ",",...
Determine if a gzipped input file is blocked gzip or standard.
[ "Determine", "if", "a", "gzipped", "input", "file", "is", "blocked", "gzip", "or", "standard", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L715-L723
223,755
bcbio/bcbio-nextgen
bcbio/qc/fastqc.py
run
def run(bam_file, data, fastqc_out): """Run fastqc, generating report in specified directory and parsing metrics. Downsamples to 10 million reads to avoid excessive processing times with large files, unless we're running a Standard/smallRNA-seq/QC pipeline. Handles fastqc 0.11+, which use a single HTML file and older versions that use a directory of files + images. The goal is to eventually move to only 0.11+ """ sentry_file = os.path.join(fastqc_out, "fastqc_report.html") if not os.path.exists(sentry_file): work_dir = os.path.dirname(fastqc_out) utils.safe_makedir(work_dir) ds_file = (bam.downsample(bam_file, data, 1e7, work_dir=work_dir) if data.get("analysis", "").lower() not in ["standard", "smallrna-seq"] else None) if ds_file is not None: bam_file = ds_file frmt = "bam" if bam_file.endswith("bam") else "fastq" fastqc_name = utils.splitext_plus(os.path.basename(bam_file))[0] fastqc_clean_name = dd.get_sample_name(data) num_cores = data["config"]["algorithm"].get("num_cores", 1) with tx_tmpdir(data, work_dir) as tx_tmp_dir: with utils.chdir(tx_tmp_dir): cl = [config_utils.get_program("fastqc", data["config"]), "-d", tx_tmp_dir, "-t", str(num_cores), "--extract", "-o", tx_tmp_dir, "-f", frmt, bam_file] cl = "%s %s %s" % (utils.java_freetype_fix(), utils.local_path_export(), " ".join([str(x) for x in cl])) do.run(cl, "FastQC: %s" % dd.get_sample_name(data)) tx_fastqc_out = os.path.join(tx_tmp_dir, "%s_fastqc" % fastqc_name) tx_combo_file = os.path.join(tx_tmp_dir, "%s_fastqc.html" % fastqc_name) if not os.path.exists(sentry_file) and os.path.exists(tx_combo_file): utils.safe_makedir(fastqc_out) # Use sample name for reports instead of bam file name with open(os.path.join(tx_fastqc_out, "fastqc_data.txt"), 'r') as fastqc_bam_name, \ open(os.path.join(tx_fastqc_out, "_fastqc_data.txt"), 'w') as fastqc_sample_name: for line in fastqc_bam_name: fastqc_sample_name.write(line.replace(os.path.basename(bam_file), fastqc_clean_name)) shutil.move(os.path.join(tx_fastqc_out, "_fastqc_data.txt"), os.path.join(fastqc_out, 'fastqc_data.txt')) shutil.move(tx_combo_file, sentry_file) if os.path.exists("%s.zip" % tx_fastqc_out): shutil.move("%s.zip" % tx_fastqc_out, os.path.join(fastqc_out, "%s.zip" % fastqc_clean_name)) elif not os.path.exists(sentry_file): raise ValueError("FastQC failed to produce output HTML file: %s" % os.listdir(tx_tmp_dir)) logger.info("Produced HTML report %s" % sentry_file) parser = FastQCParser(fastqc_out, dd.get_sample_name(data)) stats = parser.get_fastqc_summary() parser.save_sections_into_file() return stats
python
def run(bam_file, data, fastqc_out): """Run fastqc, generating report in specified directory and parsing metrics. Downsamples to 10 million reads to avoid excessive processing times with large files, unless we're running a Standard/smallRNA-seq/QC pipeline. Handles fastqc 0.11+, which use a single HTML file and older versions that use a directory of files + images. The goal is to eventually move to only 0.11+ """ sentry_file = os.path.join(fastqc_out, "fastqc_report.html") if not os.path.exists(sentry_file): work_dir = os.path.dirname(fastqc_out) utils.safe_makedir(work_dir) ds_file = (bam.downsample(bam_file, data, 1e7, work_dir=work_dir) if data.get("analysis", "").lower() not in ["standard", "smallrna-seq"] else None) if ds_file is not None: bam_file = ds_file frmt = "bam" if bam_file.endswith("bam") else "fastq" fastqc_name = utils.splitext_plus(os.path.basename(bam_file))[0] fastqc_clean_name = dd.get_sample_name(data) num_cores = data["config"]["algorithm"].get("num_cores", 1) with tx_tmpdir(data, work_dir) as tx_tmp_dir: with utils.chdir(tx_tmp_dir): cl = [config_utils.get_program("fastqc", data["config"]), "-d", tx_tmp_dir, "-t", str(num_cores), "--extract", "-o", tx_tmp_dir, "-f", frmt, bam_file] cl = "%s %s %s" % (utils.java_freetype_fix(), utils.local_path_export(), " ".join([str(x) for x in cl])) do.run(cl, "FastQC: %s" % dd.get_sample_name(data)) tx_fastqc_out = os.path.join(tx_tmp_dir, "%s_fastqc" % fastqc_name) tx_combo_file = os.path.join(tx_tmp_dir, "%s_fastqc.html" % fastqc_name) if not os.path.exists(sentry_file) and os.path.exists(tx_combo_file): utils.safe_makedir(fastqc_out) # Use sample name for reports instead of bam file name with open(os.path.join(tx_fastqc_out, "fastqc_data.txt"), 'r') as fastqc_bam_name, \ open(os.path.join(tx_fastqc_out, "_fastqc_data.txt"), 'w') as fastqc_sample_name: for line in fastqc_bam_name: fastqc_sample_name.write(line.replace(os.path.basename(bam_file), fastqc_clean_name)) shutil.move(os.path.join(tx_fastqc_out, "_fastqc_data.txt"), os.path.join(fastqc_out, 'fastqc_data.txt')) shutil.move(tx_combo_file, sentry_file) if os.path.exists("%s.zip" % tx_fastqc_out): shutil.move("%s.zip" % tx_fastqc_out, os.path.join(fastqc_out, "%s.zip" % fastqc_clean_name)) elif not os.path.exists(sentry_file): raise ValueError("FastQC failed to produce output HTML file: %s" % os.listdir(tx_tmp_dir)) logger.info("Produced HTML report %s" % sentry_file) parser = FastQCParser(fastqc_out, dd.get_sample_name(data)) stats = parser.get_fastqc_summary() parser.save_sections_into_file() return stats
[ "def", "run", "(", "bam_file", ",", "data", ",", "fastqc_out", ")", ":", "sentry_file", "=", "os", ".", "path", ".", "join", "(", "fastqc_out", ",", "\"fastqc_report.html\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "sentry_file", ")", ...
Run fastqc, generating report in specified directory and parsing metrics. Downsamples to 10 million reads to avoid excessive processing times with large files, unless we're running a Standard/smallRNA-seq/QC pipeline. Handles fastqc 0.11+, which use a single HTML file and older versions that use a directory of files + images. The goal is to eventually move to only 0.11+
[ "Run", "fastqc", "generating", "report", "in", "specified", "directory", "and", "parsing", "metrics", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/fastqc.py#L21-L70
223,756
bcbio/bcbio-nextgen
bcbio/qc/fastqc.py
FastQCParser._get_module
def _get_module(self, parser, module): """ Get module using fadapa package """ dt = [] lines = parser.clean_data(module) header = lines[0] for data in lines[1:]: if data[0].startswith("#"): # some modules have two headers header = data continue if data[0].find("-") > -1: # expand positions 1-3 to 1, 2, 3 f, s = map(int, data[0].split("-")) for pos in range(f, s): dt.append([str(pos)] + data[1:]) else: dt.append(data) dt = pd.DataFrame(dt) dt.columns = [h.replace(" ", "_") for h in header] dt['sample'] = self.sample return dt
python
def _get_module(self, parser, module): """ Get module using fadapa package """ dt = [] lines = parser.clean_data(module) header = lines[0] for data in lines[1:]: if data[0].startswith("#"): # some modules have two headers header = data continue if data[0].find("-") > -1: # expand positions 1-3 to 1, 2, 3 f, s = map(int, data[0].split("-")) for pos in range(f, s): dt.append([str(pos)] + data[1:]) else: dt.append(data) dt = pd.DataFrame(dt) dt.columns = [h.replace(" ", "_") for h in header] dt['sample'] = self.sample return dt
[ "def", "_get_module", "(", "self", ",", "parser", ",", "module", ")", ":", "dt", "=", "[", "]", "lines", "=", "parser", ".", "clean_data", "(", "module", ")", "header", "=", "lines", "[", "0", "]", "for", "data", "in", "lines", "[", "1", ":", "]"...
Get module using fadapa package
[ "Get", "module", "using", "fadapa", "package" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/fastqc.py#L113-L133
223,757
bcbio/bcbio-nextgen
bcbio/server/background.py
GenericSubprocess.start
def start(self): """Spawn the task. Throws RuntimeError if the task was already started.""" if not self.pipe is None: raise RuntimeError("Cannot start task twice") self.ioloop = tornado.ioloop.IOLoop.instance() if self.timeout > 0: self.expiration = self.ioloop.add_timeout( time.time() + self.timeout, self.on_timeout ) self.pipe = subprocess.Popen(**self.args) self.streams = [ (self.pipe.stdout.fileno(), []), (self.pipe.stderr.fileno(), []) ] for fd, d in self.streams: flags = fcntl.fcntl(fd, fcntl.F_GETFL)| os.O_NDELAY fcntl.fcntl( fd, fcntl.F_SETFL, flags) self.ioloop.add_handler( fd, self.stat, self.ioloop.READ|self.ioloop.ERROR)
python
def start(self): """Spawn the task. Throws RuntimeError if the task was already started.""" if not self.pipe is None: raise RuntimeError("Cannot start task twice") self.ioloop = tornado.ioloop.IOLoop.instance() if self.timeout > 0: self.expiration = self.ioloop.add_timeout( time.time() + self.timeout, self.on_timeout ) self.pipe = subprocess.Popen(**self.args) self.streams = [ (self.pipe.stdout.fileno(), []), (self.pipe.stderr.fileno(), []) ] for fd, d in self.streams: flags = fcntl.fcntl(fd, fcntl.F_GETFL)| os.O_NDELAY fcntl.fcntl( fd, fcntl.F_SETFL, flags) self.ioloop.add_handler( fd, self.stat, self.ioloop.READ|self.ioloop.ERROR)
[ "def", "start", "(", "self", ")", ":", "if", "not", "self", ".", "pipe", "is", "None", ":", "raise", "RuntimeError", "(", "\"Cannot start task twice\"", ")", "self", ".", "ioloop", "=", "tornado", ".", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", ...
Spawn the task. Throws RuntimeError if the task was already started.
[ "Spawn", "the", "task", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/server/background.py#L32-L51
223,758
bcbio/bcbio-nextgen
bcbio/workflow/xprize.py
get_fc_date
def get_fc_date(out_config_file): """Retrieve flowcell date, reusing older dates if refreshing a present workflow. """ if os.path.exists(out_config_file): with open(out_config_file) as in_handle: old_config = yaml.safe_load(in_handle) fc_date = old_config["fc_date"] else: fc_date = datetime.datetime.now().strftime("%y%m%d") return fc_date
python
def get_fc_date(out_config_file): """Retrieve flowcell date, reusing older dates if refreshing a present workflow. """ if os.path.exists(out_config_file): with open(out_config_file) as in_handle: old_config = yaml.safe_load(in_handle) fc_date = old_config["fc_date"] else: fc_date = datetime.datetime.now().strftime("%y%m%d") return fc_date
[ "def", "get_fc_date", "(", "out_config_file", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "out_config_file", ")", ":", "with", "open", "(", "out_config_file", ")", "as", "in_handle", ":", "old_config", "=", "yaml", ".", "safe_load", "(", "in_han...
Retrieve flowcell date, reusing older dates if refreshing a present workflow.
[ "Retrieve", "flowcell", "date", "reusing", "older", "dates", "if", "refreshing", "a", "present", "workflow", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/xprize.py#L32-L41
223,759
bcbio/bcbio-nextgen
scripts/utils/analyze_quality_recal.py
draw_quality_plot
def draw_quality_plot(db_file, plot_file, position_select, title): """Draw a plot of remapped qualities using ggplot2. Remapping information is pulled from the sqlite3 database using sqldf according to the position select attribute, which is a selection phrase like '> 50' or '=28'. plyr is used to summarize data by the original and remapped score for all selected positions. ggplot2 plots a heatmap of remapped counts at each (original, remap) coordinate, with a x=y line added for reference. """ robjects.r.assign('db.file', db_file) robjects.r.assign('plot.file', plot_file) robjects.r.assign('position.select', position_select) robjects.r.assign('title', title) robjects.r(''' library(sqldf) library(plyr) library(ggplot2) sql <- paste("select * from data WHERE position", position.select, sep=" ") exp.data <- sqldf(sql, dbname=db.file) remap.data <- ddply(exp.data, c("orig", "remap"), transform, count=sum(count)) p <- ggplot(remap.data, aes(orig, remap)) + geom_tile(aes(fill = count)) + scale_fill_gradient(low = "white", high = "steelblue", trans="log") + opts(panel.background = theme_rect(fill = "white"), title=title) + geom_abline(intercept=0, slope=1) ggsave(plot.file, p, width=6, height=6) ''')
python
def draw_quality_plot(db_file, plot_file, position_select, title): """Draw a plot of remapped qualities using ggplot2. Remapping information is pulled from the sqlite3 database using sqldf according to the position select attribute, which is a selection phrase like '> 50' or '=28'. plyr is used to summarize data by the original and remapped score for all selected positions. ggplot2 plots a heatmap of remapped counts at each (original, remap) coordinate, with a x=y line added for reference. """ robjects.r.assign('db.file', db_file) robjects.r.assign('plot.file', plot_file) robjects.r.assign('position.select', position_select) robjects.r.assign('title', title) robjects.r(''' library(sqldf) library(plyr) library(ggplot2) sql <- paste("select * from data WHERE position", position.select, sep=" ") exp.data <- sqldf(sql, dbname=db.file) remap.data <- ddply(exp.data, c("orig", "remap"), transform, count=sum(count)) p <- ggplot(remap.data, aes(orig, remap)) + geom_tile(aes(fill = count)) + scale_fill_gradient(low = "white", high = "steelblue", trans="log") + opts(panel.background = theme_rect(fill = "white"), title=title) + geom_abline(intercept=0, slope=1) ggsave(plot.file, p, width=6, height=6) ''')
[ "def", "draw_quality_plot", "(", "db_file", ",", "plot_file", ",", "position_select", ",", "title", ")", ":", "robjects", ".", "r", ".", "assign", "(", "'db.file'", ",", "db_file", ")", "robjects", ".", "r", ".", "assign", "(", "'plot.file'", ",", "plot_fi...
Draw a plot of remapped qualities using ggplot2. Remapping information is pulled from the sqlite3 database using sqldf according to the position select attribute, which is a selection phrase like '> 50' or '=28'. plyr is used to summarize data by the original and remapped score for all selected positions. ggplot2 plots a heatmap of remapped counts at each (original, remap) coordinate, with a x=y line added for reference.
[ "Draw", "a", "plot", "of", "remapped", "qualities", "using", "ggplot2", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/analyze_quality_recal.py#L112-L143
223,760
bcbio/bcbio-nextgen
scripts/utils/analyze_quality_recal.py
_positions_to_examine
def _positions_to_examine(db_file): """Determine how to sub-divide recalibration analysis based on read length. """ conn = sqlite3.connect(db_file) cursor = conn.cursor() cursor.execute("""SELECT MAX(position) FROM data""") position = cursor.fetchone()[0] if position is not None: position = int(position) cursor.close() split_at = 50 if position is None: return [] elif position < split_at: return [("<= %s" % position, "lt%s" % position)] else: return [("< %s" % split_at, "lt%s" % split_at), (">= %s" % split_at, "gt%s" % split_at)]
python
def _positions_to_examine(db_file): """Determine how to sub-divide recalibration analysis based on read length. """ conn = sqlite3.connect(db_file) cursor = conn.cursor() cursor.execute("""SELECT MAX(position) FROM data""") position = cursor.fetchone()[0] if position is not None: position = int(position) cursor.close() split_at = 50 if position is None: return [] elif position < split_at: return [("<= %s" % position, "lt%s" % position)] else: return [("< %s" % split_at, "lt%s" % split_at), (">= %s" % split_at, "gt%s" % split_at)]
[ "def", "_positions_to_examine", "(", "db_file", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "db_file", ")", "cursor", "=", "conn", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "\"\"\"SELECT MAX(position) FROM data\"\"\"", ")", "position", ...
Determine how to sub-divide recalibration analysis based on read length.
[ "Determine", "how", "to", "sub", "-", "divide", "recalibration", "analysis", "based", "on", "read", "length", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/analyze_quality_recal.py#L145-L162
223,761
bcbio/bcbio-nextgen
scripts/utils/analyze_quality_recal.py
_organize_by_position
def _organize_by_position(orig_file, cmp_file, chunk_size): """Read two CSV files of qualities, organizing values by position. """ with open(orig_file) as in_handle: reader1 = csv.reader(in_handle) positions = len(next(reader1)) - 1 for positions in _chunks(range(positions), chunk_size): with open(orig_file) as orig_handle: with open(cmp_file) as cmp_handle: orig_reader = csv.reader(orig_handle) cmp_reader = csv.reader(cmp_handle) for item in _counts_at_position(positions, orig_reader, cmp_reader): yield item
python
def _organize_by_position(orig_file, cmp_file, chunk_size): """Read two CSV files of qualities, organizing values by position. """ with open(orig_file) as in_handle: reader1 = csv.reader(in_handle) positions = len(next(reader1)) - 1 for positions in _chunks(range(positions), chunk_size): with open(orig_file) as orig_handle: with open(cmp_file) as cmp_handle: orig_reader = csv.reader(orig_handle) cmp_reader = csv.reader(cmp_handle) for item in _counts_at_position(positions, orig_reader, cmp_reader): yield item
[ "def", "_organize_by_position", "(", "orig_file", ",", "cmp_file", ",", "chunk_size", ")", ":", "with", "open", "(", "orig_file", ")", "as", "in_handle", ":", "reader1", "=", "csv", ".", "reader", "(", "in_handle", ")", "positions", "=", "len", "(", "next"...
Read two CSV files of qualities, organizing values by position.
[ "Read", "two", "CSV", "files", "of", "qualities", "organizing", "values", "by", "position", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/analyze_quality_recal.py#L183-L196
223,762
bcbio/bcbio-nextgen
scripts/utils/analyze_quality_recal.py
_counts_at_position
def _counts_at_position(positions, orig_reader, cmp_reader): """Combine orignal and new qualities at each position, generating counts. """ pos_counts = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(int))) for orig_parts in orig_reader: cmp_parts = next(cmp_reader) for pos in positions: try: pos_counts[pos][int(orig_parts[pos+1])][int(cmp_parts[pos+1])] += 1 except IndexError: pass for pos, count_dict in pos_counts.iteritems(): for orig_val, cmp_dict in count_dict.iteritems(): for cmp_val, count in cmp_dict.iteritems(): yield pos+1, orig_val, cmp_val, count
python
def _counts_at_position(positions, orig_reader, cmp_reader): """Combine orignal and new qualities at each position, generating counts. """ pos_counts = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(int))) for orig_parts in orig_reader: cmp_parts = next(cmp_reader) for pos in positions: try: pos_counts[pos][int(orig_parts[pos+1])][int(cmp_parts[pos+1])] += 1 except IndexError: pass for pos, count_dict in pos_counts.iteritems(): for orig_val, cmp_dict in count_dict.iteritems(): for cmp_val, count in cmp_dict.iteritems(): yield pos+1, orig_val, cmp_val, count
[ "def", "_counts_at_position", "(", "positions", ",", "orig_reader", ",", "cmp_reader", ")", ":", "pos_counts", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "collections", ".", "defaultdict", "(", "lambda", ":", "collections", ".", "defaultdict", "...
Combine orignal and new qualities at each position, generating counts.
[ "Combine", "orignal", "and", "new", "qualities", "at", "each", "position", "generating", "counts", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/analyze_quality_recal.py#L206-L222
223,763
bcbio/bcbio-nextgen
scripts/utils/analyze_quality_recal.py
sort_csv
def sort_csv(in_file): """Sort a CSV file by read name, allowing direct comparison. """ out_file = "%s.sort" % in_file if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0): cl = ["sort", "-k", "1,1", in_file] with open(out_file, "w") as out_handle: child = subprocess.Popen(cl, stdout=out_handle) child.wait() return out_file
python
def sort_csv(in_file): """Sort a CSV file by read name, allowing direct comparison. """ out_file = "%s.sort" % in_file if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0): cl = ["sort", "-k", "1,1", in_file] with open(out_file, "w") as out_handle: child = subprocess.Popen(cl, stdout=out_handle) child.wait() return out_file
[ "def", "sort_csv", "(", "in_file", ")", ":", "out_file", "=", "\"%s.sort\"", "%", "in_file", "if", "not", "(", "os", ".", "path", ".", "exists", "(", "out_file", ")", "and", "os", ".", "path", ".", "getsize", "(", "out_file", ")", ">", "0", ")", ":...
Sort a CSV file by read name, allowing direct comparison.
[ "Sort", "a", "CSV", "file", "by", "read", "name", "allowing", "direct", "comparison", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/analyze_quality_recal.py#L224-L233
223,764
bcbio/bcbio-nextgen
scripts/utils/analyze_quality_recal.py
fastq_to_csv
def fastq_to_csv(in_file, fastq_format, work_dir): """Convert a fastq file into a CSV of phred quality scores. """ out_file = "%s.csv" % (os.path.splitext(os.path.basename(in_file))[0]) out_file = os.path.join(work_dir, out_file) if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0): with open(in_file) as in_handle: with open(out_file, "w") as out_handle: writer = csv.writer(out_handle) for rec in SeqIO.parse(in_handle, fastq_format): writer.writerow([rec.id] + rec.letter_annotations["phred_quality"]) return out_file
python
def fastq_to_csv(in_file, fastq_format, work_dir): """Convert a fastq file into a CSV of phred quality scores. """ out_file = "%s.csv" % (os.path.splitext(os.path.basename(in_file))[0]) out_file = os.path.join(work_dir, out_file) if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0): with open(in_file) as in_handle: with open(out_file, "w") as out_handle: writer = csv.writer(out_handle) for rec in SeqIO.parse(in_handle, fastq_format): writer.writerow([rec.id] + rec.letter_annotations["phred_quality"]) return out_file
[ "def", "fastq_to_csv", "(", "in_file", ",", "fastq_format", ",", "work_dir", ")", ":", "out_file", "=", "\"%s.csv\"", "%", "(", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "in_file", ")", ")", "[", "0", "]", ")",...
Convert a fastq file into a CSV of phred quality scores.
[ "Convert", "a", "fastq", "file", "into", "a", "CSV", "of", "phred", "quality", "scores", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/analyze_quality_recal.py#L235-L246
223,765
bcbio/bcbio-nextgen
scripts/utils/analyze_quality_recal.py
bam_to_fastq
def bam_to_fastq(bam_file, is_paired): """Convert a BAM file to fastq files. """ out_files, out_handles = _get_fastq_handles(bam_file, is_paired) if len(out_handles) > 0: in_bam = pysam.Samfile(bam_file, mode='rb') for read in in_bam: num = 1 if (not read.is_paired or read.is_read1) else 2 # reverse the sequence and quality if mapped to opposite strand if read.is_reverse: seq = str(Seq.reverse_complement(Seq.Seq(read.seq))) qual = "".join(reversed(read.qual)) else: seq = read.seq qual = read.qual out_handles[num].write("@%s\n%s\n+\n%s\n" % (read.qname, seq, qual)) [h.close() for h in out_handles.values()] return out_files
python
def bam_to_fastq(bam_file, is_paired): """Convert a BAM file to fastq files. """ out_files, out_handles = _get_fastq_handles(bam_file, is_paired) if len(out_handles) > 0: in_bam = pysam.Samfile(bam_file, mode='rb') for read in in_bam: num = 1 if (not read.is_paired or read.is_read1) else 2 # reverse the sequence and quality if mapped to opposite strand if read.is_reverse: seq = str(Seq.reverse_complement(Seq.Seq(read.seq))) qual = "".join(reversed(read.qual)) else: seq = read.seq qual = read.qual out_handles[num].write("@%s\n%s\n+\n%s\n" % (read.qname, seq, qual)) [h.close() for h in out_handles.values()] return out_files
[ "def", "bam_to_fastq", "(", "bam_file", ",", "is_paired", ")", ":", "out_files", ",", "out_handles", "=", "_get_fastq_handles", "(", "bam_file", ",", "is_paired", ")", "if", "len", "(", "out_handles", ")", ">", "0", ":", "in_bam", "=", "pysam", ".", "Samfi...
Convert a BAM file to fastq files.
[ "Convert", "a", "BAM", "file", "to", "fastq", "files", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/analyze_quality_recal.py#L248-L267
223,766
bcbio/bcbio-nextgen
scripts/utils/analyze_quality_recal.py
run_latex_report
def run_latex_report(base, report_dir, section_info): """Generate a pdf report with plots using latex. """ out_name = "%s_recal_plots.tex" % base out = os.path.join(report_dir, out_name) with open(out, "w") as out_handle: out_tmpl = Template(out_template) out_handle.write(out_tmpl.render(sections=section_info)) start_dir = os.getcwd() try: os.chdir(report_dir) cl = ["pdflatex", out_name] child = subprocess.Popen(cl) child.wait() finally: os.chdir(start_dir)
python
def run_latex_report(base, report_dir, section_info): """Generate a pdf report with plots using latex. """ out_name = "%s_recal_plots.tex" % base out = os.path.join(report_dir, out_name) with open(out, "w") as out_handle: out_tmpl = Template(out_template) out_handle.write(out_tmpl.render(sections=section_info)) start_dir = os.getcwd() try: os.chdir(report_dir) cl = ["pdflatex", out_name] child = subprocess.Popen(cl) child.wait() finally: os.chdir(start_dir)
[ "def", "run_latex_report", "(", "base", ",", "report_dir", ",", "section_info", ")", ":", "out_name", "=", "\"%s_recal_plots.tex\"", "%", "base", "out", "=", "os", ".", "path", ".", "join", "(", "report_dir", ",", "out_name", ")", "with", "open", "(", "out...
Generate a pdf report with plots using latex.
[ "Generate", "a", "pdf", "report", "with", "plots", "using", "latex", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/analyze_quality_recal.py#L301-L316
223,767
bcbio/bcbio-nextgen
bcbio/variation/multi.py
bam_needs_processing
def bam_needs_processing(data): """Check if a work input needs processing for parallelization. """ return ((data.get("work_bam") or data.get("align_bam")) and (any(tz.get_in(["config", "algorithm", x], data) for x in ["variantcaller", "mark_duplicates", "recalibrate", "realign", "svcaller", "jointcaller", "variant_regions"]) or any(k in data for k in ["cwl_keys", "output_cwl_keys"])))
python
def bam_needs_processing(data): """Check if a work input needs processing for parallelization. """ return ((data.get("work_bam") or data.get("align_bam")) and (any(tz.get_in(["config", "algorithm", x], data) for x in ["variantcaller", "mark_duplicates", "recalibrate", "realign", "svcaller", "jointcaller", "variant_regions"]) or any(k in data for k in ["cwl_keys", "output_cwl_keys"])))
[ "def", "bam_needs_processing", "(", "data", ")", ":", "return", "(", "(", "data", ".", "get", "(", "\"work_bam\"", ")", "or", "data", ".", "get", "(", "\"align_bam\"", ")", ")", "and", "(", "any", "(", "tz", ".", "get_in", "(", "[", "\"config\"", ","...
Check if a work input needs processing for parallelization.
[ "Check", "if", "a", "work", "input", "needs", "processing", "for", "parallelization", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L30-L37
223,768
bcbio/bcbio-nextgen
bcbio/variation/multi.py
get_batch_for_key
def get_batch_for_key(data): """Retrieve batch information useful as a unique key for the sample. """ batches = _get_batches(data, require_bam=False) if len(batches) == 1: return batches[0] else: return tuple(batches)
python
def get_batch_for_key(data): """Retrieve batch information useful as a unique key for the sample. """ batches = _get_batches(data, require_bam=False) if len(batches) == 1: return batches[0] else: return tuple(batches)
[ "def", "get_batch_for_key", "(", "data", ")", ":", "batches", "=", "_get_batches", "(", "data", ",", "require_bam", "=", "False", ")", "if", "len", "(", "batches", ")", "==", "1", ":", "return", "batches", "[", "0", "]", "else", ":", "return", "tuple",...
Retrieve batch information useful as a unique key for the sample.
[ "Retrieve", "batch", "information", "useful", "as", "a", "unique", "key", "for", "the", "sample", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L39-L46
223,769
bcbio/bcbio-nextgen
bcbio/variation/multi.py
_find_all_groups
def _find_all_groups(items, require_bam=True): """Find all groups """ all_groups = [] for data in items: batches = _get_batches(data, require_bam) all_groups.append(batches) return all_groups
python
def _find_all_groups(items, require_bam=True): """Find all groups """ all_groups = [] for data in items: batches = _get_batches(data, require_bam) all_groups.append(batches) return all_groups
[ "def", "_find_all_groups", "(", "items", ",", "require_bam", "=", "True", ")", ":", "all_groups", "=", "[", "]", "for", "data", "in", "items", ":", "batches", "=", "_get_batches", "(", "data", ",", "require_bam", ")", "all_groups", ".", "append", "(", "b...
Find all groups
[ "Find", "all", "groups" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L57-L64
223,770
bcbio/bcbio-nextgen
bcbio/variation/multi.py
_get_representative_batch
def _get_representative_batch(merged): """Prepare dictionary matching batch items to a representative within a group. """ out = {} for mgroup in merged: mgroup = sorted(list(mgroup)) for x in mgroup: out[x] = mgroup[0] return out
python
def _get_representative_batch(merged): """Prepare dictionary matching batch items to a representative within a group. """ out = {} for mgroup in merged: mgroup = sorted(list(mgroup)) for x in mgroup: out[x] = mgroup[0] return out
[ "def", "_get_representative_batch", "(", "merged", ")", ":", "out", "=", "{", "}", "for", "mgroup", "in", "merged", ":", "mgroup", "=", "sorted", "(", "list", "(", "mgroup", ")", ")", "for", "x", "in", "mgroup", ":", "out", "[", "x", "]", "=", "mgr...
Prepare dictionary matching batch items to a representative within a group.
[ "Prepare", "dictionary", "matching", "batch", "items", "to", "a", "representative", "within", "a", "group", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L90-L98
223,771
bcbio/bcbio-nextgen
bcbio/variation/multi.py
_group_batches_shared
def _group_batches_shared(xs, caller_batch_fn, prep_data_fn): """Shared functionality for grouping by batches for variant calling and joint calling. """ singles = [] batch_groups = collections.defaultdict(list) for args in xs: data = utils.to_single_data(args) caller, batch = caller_batch_fn(data) region = _list_to_tuple(data["region"]) if "region" in data else () if batch is not None: batches = batch if isinstance(batch, (list, tuple)) else [batch] for b in batches: batch_groups[(b, region, caller)].append(utils.deepish_copy(data)) else: data = prep_data_fn(data, [data]) singles.append(data) batches = [] for batch, items in batch_groups.items(): batch_data = utils.deepish_copy(_pick_lead_item(items)) # For nested primary batches, split permanently by batch if tz.get_in(["metadata", "batch"], batch_data): batch_name = batch[0] batch_data["metadata"]["batch"] = batch_name batch_data = prep_data_fn(batch_data, items) batch_data["group_orig"] = _collapse_subitems(batch_data, items) batch_data["group"] = batch batches.append(batch_data) return singles + batches
python
def _group_batches_shared(xs, caller_batch_fn, prep_data_fn): """Shared functionality for grouping by batches for variant calling and joint calling. """ singles = [] batch_groups = collections.defaultdict(list) for args in xs: data = utils.to_single_data(args) caller, batch = caller_batch_fn(data) region = _list_to_tuple(data["region"]) if "region" in data else () if batch is not None: batches = batch if isinstance(batch, (list, tuple)) else [batch] for b in batches: batch_groups[(b, region, caller)].append(utils.deepish_copy(data)) else: data = prep_data_fn(data, [data]) singles.append(data) batches = [] for batch, items in batch_groups.items(): batch_data = utils.deepish_copy(_pick_lead_item(items)) # For nested primary batches, split permanently by batch if tz.get_in(["metadata", "batch"], batch_data): batch_name = batch[0] batch_data["metadata"]["batch"] = batch_name batch_data = prep_data_fn(batch_data, items) batch_data["group_orig"] = _collapse_subitems(batch_data, items) batch_data["group"] = batch batches.append(batch_data) return singles + batches
[ "def", "_group_batches_shared", "(", "xs", ",", "caller_batch_fn", ",", "prep_data_fn", ")", ":", "singles", "=", "[", "]", "batch_groups", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "args", "in", "xs", ":", "data", "=", "utils", ".",...
Shared functionality for grouping by batches for variant calling and joint calling.
[ "Shared", "functionality", "for", "grouping", "by", "batches", "for", "variant", "calling", "and", "joint", "calling", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L106-L133
223,772
bcbio/bcbio-nextgen
bcbio/variation/multi.py
group_batches
def group_batches(xs): """Group samples into batches for simultaneous variant calling. Identify all samples to call together: those in the same batch and variant caller. Pull together all BAM files from this batch and process together, Provide details to pull these finalized files back into individual expected files. Only batches files if joint calling not specified. """ def _caller_batches(data): caller = tz.get_in(("config", "algorithm", "variantcaller"), data) jointcaller = tz.get_in(("config", "algorithm", "jointcaller"), data) batch = tz.get_in(("metadata", "batch"), data) if not jointcaller else None return caller, batch def _prep_data(data, items): data["region_bams"] = [x["region_bams"] for x in items] return data return _group_batches_shared(xs, _caller_batches, _prep_data)
python
def group_batches(xs): """Group samples into batches for simultaneous variant calling. Identify all samples to call together: those in the same batch and variant caller. Pull together all BAM files from this batch and process together, Provide details to pull these finalized files back into individual expected files. Only batches files if joint calling not specified. """ def _caller_batches(data): caller = tz.get_in(("config", "algorithm", "variantcaller"), data) jointcaller = tz.get_in(("config", "algorithm", "jointcaller"), data) batch = tz.get_in(("metadata", "batch"), data) if not jointcaller else None return caller, batch def _prep_data(data, items): data["region_bams"] = [x["region_bams"] for x in items] return data return _group_batches_shared(xs, _caller_batches, _prep_data)
[ "def", "group_batches", "(", "xs", ")", ":", "def", "_caller_batches", "(", "data", ")", ":", "caller", "=", "tz", ".", "get_in", "(", "(", "\"config\"", ",", "\"algorithm\"", ",", "\"variantcaller\"", ")", ",", "data", ")", "jointcaller", "=", "tz", "."...
Group samples into batches for simultaneous variant calling. Identify all samples to call together: those in the same batch and variant caller. Pull together all BAM files from this batch and process together, Provide details to pull these finalized files back into individual expected files. Only batches files if joint calling not specified.
[ "Group", "samples", "into", "batches", "for", "simultaneous", "variant", "calling", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L135-L153
223,773
bcbio/bcbio-nextgen
bcbio/variation/multi.py
_collapse_subitems
def _collapse_subitems(base, items): """Collapse full data representations relative to a standard base. """ out = [] for d in items: newd = _diff_dict(base, d) out.append(newd) return out
python
def _collapse_subitems(base, items): """Collapse full data representations relative to a standard base. """ out = [] for d in items: newd = _diff_dict(base, d) out.append(newd) return out
[ "def", "_collapse_subitems", "(", "base", ",", "items", ")", ":", "out", "=", "[", "]", "for", "d", "in", "items", ":", "newd", "=", "_diff_dict", "(", "base", ",", "d", ")", "out", ".", "append", "(", "newd", ")", "return", "out" ]
Collapse full data representations relative to a standard base.
[ "Collapse", "full", "data", "representations", "relative", "to", "a", "standard", "base", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L173-L180
223,774
bcbio/bcbio-nextgen
bcbio/variation/multi.py
_pick_lead_item
def _pick_lead_item(items): """Pick single representative sample for batch calling to attach calls to. For cancer samples, attach to tumor. """ if vcfutils.is_paired_analysis([dd.get_align_bam(x) for x in items], items): for data in items: if vcfutils.get_paired_phenotype(data) == "tumor": return data raise ValueError("Did not find tumor sample in paired tumor/normal calling") else: return items[0]
python
def _pick_lead_item(items): """Pick single representative sample for batch calling to attach calls to. For cancer samples, attach to tumor. """ if vcfutils.is_paired_analysis([dd.get_align_bam(x) for x in items], items): for data in items: if vcfutils.get_paired_phenotype(data) == "tumor": return data raise ValueError("Did not find tumor sample in paired tumor/normal calling") else: return items[0]
[ "def", "_pick_lead_item", "(", "items", ")", ":", "if", "vcfutils", ".", "is_paired_analysis", "(", "[", "dd", ".", "get_align_bam", "(", "x", ")", "for", "x", "in", "items", "]", ",", "items", ")", ":", "for", "data", "in", "items", ":", "if", "vcfu...
Pick single representative sample for batch calling to attach calls to. For cancer samples, attach to tumor.
[ "Pick", "single", "representative", "sample", "for", "batch", "calling", "to", "attach", "calls", "to", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L198-L209
223,775
bcbio/bcbio-nextgen
bcbio/variation/multi.py
get_orig_items
def get_orig_items(base): """Retrieve original items from a diffed set of nested samples. """ assert "group_orig" in base out = [] for data_diff in base["group_orig"]: new = utils.deepish_copy(base) new.pop("group_orig") out.append(_patch_dict(data_diff, new)) return out
python
def get_orig_items(base): """Retrieve original items from a diffed set of nested samples. """ assert "group_orig" in base out = [] for data_diff in base["group_orig"]: new = utils.deepish_copy(base) new.pop("group_orig") out.append(_patch_dict(data_diff, new)) return out
[ "def", "get_orig_items", "(", "base", ")", ":", "assert", "\"group_orig\"", "in", "base", "out", "=", "[", "]", "for", "data_diff", "in", "base", "[", "\"group_orig\"", "]", ":", "new", "=", "utils", ".", "deepish_copy", "(", "base", ")", "new", ".", "...
Retrieve original items from a diffed set of nested samples.
[ "Retrieve", "original", "items", "from", "a", "diffed", "set", "of", "nested", "samples", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L211-L220
223,776
bcbio/bcbio-nextgen
bcbio/variation/multi.py
_patch_dict
def _patch_dict(diff, base): """Patch a dictionary, substituting in changed items from the nested diff. """ for k, v in diff.items(): if isinstance(v, dict): base[k] = _patch_dict(v, base.get(k, {})) elif not v: base.pop(k, None) else: base[k] = v return base
python
def _patch_dict(diff, base): """Patch a dictionary, substituting in changed items from the nested diff. """ for k, v in diff.items(): if isinstance(v, dict): base[k] = _patch_dict(v, base.get(k, {})) elif not v: base.pop(k, None) else: base[k] = v return base
[ "def", "_patch_dict", "(", "diff", ",", "base", ")", ":", "for", "k", ",", "v", "in", "diff", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "base", "[", "k", "]", "=", "_patch_dict", "(", "v", ",", "base", ...
Patch a dictionary, substituting in changed items from the nested diff.
[ "Patch", "a", "dictionary", "substituting", "in", "changed", "items", "from", "the", "nested", "diff", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L222-L232
223,777
bcbio/bcbio-nextgen
bcbio/variation/multi.py
split_variants_by_sample
def split_variants_by_sample(data): """Split a multi-sample call file into inputs for individual samples. For tumor/normal paired analyses, do not split the final file and attach it to the tumor input. """ # not split, do nothing if "group_orig" not in data: return [[data]] # cancer tumor/normal elif (vcfutils.get_paired_phenotype(data) and "tumor" in [vcfutils.get_paired_phenotype(d) for d in get_orig_items(data)]): out = [] for i, sub_data in enumerate(get_orig_items(data)): if vcfutils.get_paired_phenotype(sub_data) == "tumor": cur_batch = tz.get_in(["metadata", "batch"], data) if cur_batch: sub_data["metadata"]["batch"] = cur_batch sub_data["vrn_file"] = data["vrn_file"] else: sub_data.pop("vrn_file", None) out.append([sub_data]) return out # joint calling or population runs, do not split back up and keep in batches else: out = [] for sub_data in get_orig_items(data): cur_batch = tz.get_in(["metadata", "batch"], data) if cur_batch: sub_data["metadata"]["batch"] = cur_batch sub_data["vrn_file_batch"] = data["vrn_file"] sub_data["vrn_file"] = data["vrn_file"] out.append([sub_data]) return out
python
def split_variants_by_sample(data): """Split a multi-sample call file into inputs for individual samples. For tumor/normal paired analyses, do not split the final file and attach it to the tumor input. """ # not split, do nothing if "group_orig" not in data: return [[data]] # cancer tumor/normal elif (vcfutils.get_paired_phenotype(data) and "tumor" in [vcfutils.get_paired_phenotype(d) for d in get_orig_items(data)]): out = [] for i, sub_data in enumerate(get_orig_items(data)): if vcfutils.get_paired_phenotype(sub_data) == "tumor": cur_batch = tz.get_in(["metadata", "batch"], data) if cur_batch: sub_data["metadata"]["batch"] = cur_batch sub_data["vrn_file"] = data["vrn_file"] else: sub_data.pop("vrn_file", None) out.append([sub_data]) return out # joint calling or population runs, do not split back up and keep in batches else: out = [] for sub_data in get_orig_items(data): cur_batch = tz.get_in(["metadata", "batch"], data) if cur_batch: sub_data["metadata"]["batch"] = cur_batch sub_data["vrn_file_batch"] = data["vrn_file"] sub_data["vrn_file"] = data["vrn_file"] out.append([sub_data]) return out
[ "def", "split_variants_by_sample", "(", "data", ")", ":", "# not split, do nothing", "if", "\"group_orig\"", "not", "in", "data", ":", "return", "[", "[", "data", "]", "]", "# cancer tumor/normal", "elif", "(", "vcfutils", ".", "get_paired_phenotype", "(", "data",...
Split a multi-sample call file into inputs for individual samples. For tumor/normal paired analyses, do not split the final file and attach it to the tumor input.
[ "Split", "a", "multi", "-", "sample", "call", "file", "into", "inputs", "for", "individual", "samples", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L236-L269
223,778
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
run
def run(call_file, ref_file, vrn_files, data): """Run filtering on the input call file, handling SNPs and indels separately. """ algs = [data["config"]["algorithm"]] * len(data.get("vrn_files", [1])) if includes_missingalt(data): logger.info("Removing variants with missing alts from %s." % call_file) call_file = gatk_remove_missingalt(call_file, data) if "gatkcnn" in dd.get_tools_on(data): return _cnn_filter(call_file, vrn_files, data) elif config_utils.use_vqsr(algs, call_file): if vcfutils.is_gvcf_file(call_file): raise ValueError("Cannot force gVCF output with joint calling using tools_on: [gvcf] and use VQSR. " "Try using cutoff-based soft filtering with tools_off: [vqsr]") snp_file, indel_file = vcfutils.split_snps_indels(call_file, ref_file, data["config"]) snp_filter_file = _variant_filtration(snp_file, ref_file, vrn_files, data, "SNP", vfilter.gatk_snp_cutoff) indel_filter_file = _variant_filtration(indel_file, ref_file, vrn_files, data, "INDEL", vfilter.gatk_indel_cutoff) orig_files = [snp_filter_file, indel_filter_file] out_file = "%scombined.vcf.gz" % os.path.commonprefix(orig_files) combined_file = vcfutils.combine_variant_files(orig_files, out_file, ref_file, data["config"]) return combined_file else: snp_filter = vfilter.gatk_snp_cutoff(call_file, data) indel_filter = vfilter.gatk_indel_cutoff(snp_filter, data) return indel_filter
python
def run(call_file, ref_file, vrn_files, data): """Run filtering on the input call file, handling SNPs and indels separately. """ algs = [data["config"]["algorithm"]] * len(data.get("vrn_files", [1])) if includes_missingalt(data): logger.info("Removing variants with missing alts from %s." % call_file) call_file = gatk_remove_missingalt(call_file, data) if "gatkcnn" in dd.get_tools_on(data): return _cnn_filter(call_file, vrn_files, data) elif config_utils.use_vqsr(algs, call_file): if vcfutils.is_gvcf_file(call_file): raise ValueError("Cannot force gVCF output with joint calling using tools_on: [gvcf] and use VQSR. " "Try using cutoff-based soft filtering with tools_off: [vqsr]") snp_file, indel_file = vcfutils.split_snps_indels(call_file, ref_file, data["config"]) snp_filter_file = _variant_filtration(snp_file, ref_file, vrn_files, data, "SNP", vfilter.gatk_snp_cutoff) indel_filter_file = _variant_filtration(indel_file, ref_file, vrn_files, data, "INDEL", vfilter.gatk_indel_cutoff) orig_files = [snp_filter_file, indel_filter_file] out_file = "%scombined.vcf.gz" % os.path.commonprefix(orig_files) combined_file = vcfutils.combine_variant_files(orig_files, out_file, ref_file, data["config"]) return combined_file else: snp_filter = vfilter.gatk_snp_cutoff(call_file, data) indel_filter = vfilter.gatk_indel_cutoff(snp_filter, data) return indel_filter
[ "def", "run", "(", "call_file", ",", "ref_file", ",", "vrn_files", ",", "data", ")", ":", "algs", "=", "[", "data", "[", "\"config\"", "]", "[", "\"algorithm\"", "]", "]", "*", "len", "(", "data", ".", "get", "(", "\"vrn_files\"", ",", "[", "1", "]...
Run filtering on the input call file, handling SNPs and indels separately.
[ "Run", "filtering", "on", "the", "input", "call", "file", "handling", "SNPs", "and", "indels", "separately", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L15-L41
223,779
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
_cnn_filter
def _cnn_filter(in_file, vrn_files, data): """Perform CNN filtering on input VCF using pre-trained models. """ #tensor_type = "reference" # 1D, reference sequence tensor_type = "read_tensor" # 2D, reads, flags, mapping quality score_file = _cnn_score_variants(in_file, tensor_type, data) return _cnn_tranch_filtering(score_file, vrn_files, tensor_type, data)
python
def _cnn_filter(in_file, vrn_files, data): """Perform CNN filtering on input VCF using pre-trained models. """ #tensor_type = "reference" # 1D, reference sequence tensor_type = "read_tensor" # 2D, reads, flags, mapping quality score_file = _cnn_score_variants(in_file, tensor_type, data) return _cnn_tranch_filtering(score_file, vrn_files, tensor_type, data)
[ "def", "_cnn_filter", "(", "in_file", ",", "vrn_files", ",", "data", ")", ":", "#tensor_type = \"reference\" # 1D, reference sequence", "tensor_type", "=", "\"read_tensor\"", "# 2D, reads, flags, mapping quality", "score_file", "=", "_cnn_score_variants", "(", "in_file", ","...
Perform CNN filtering on input VCF using pre-trained models.
[ "Perform", "CNN", "filtering", "on", "input", "VCF", "using", "pre", "-", "trained", "models", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L45-L51
223,780
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
_cnn_tranch_filtering
def _cnn_tranch_filtering(in_file, vrn_files, tensor_type, data): """Filter CNN scored VCFs in tranches using standard SNP and Indel truth sets. """ out_file = "%s-filter.vcf.gz" % utils.splitext_plus(in_file)[0] if not utils.file_uptodate(out_file, in_file): runner = broad.runner_from_config(data["config"]) gatk_type = runner.gatk_type() assert gatk_type == "gatk4", "CNN filtering requires GATK4" if "train_hapmap" not in vrn_files: raise ValueError("CNN filtering requires HapMap training inputs: %s" % vrn_files) with file_transaction(data, out_file) as tx_out_file: params = ["-T", "FilterVariantTranches", "--variant", in_file, "--output", tx_out_file, "--snp-truth-vcf", vrn_files["train_hapmap"], "--indel-truth-vcf", vrn_files["train_indels"]] if tensor_type == "reference": params += ["--info-key", "CNN_1D", "--tranche", "99"] else: assert tensor_type == "read_tensor" params += ["--info-key", "CNN_2D", "--tranche", "99"] runner.run_gatk(params) return vcfutils.bgzip_and_index(out_file, data["config"])
python
def _cnn_tranch_filtering(in_file, vrn_files, tensor_type, data): """Filter CNN scored VCFs in tranches using standard SNP and Indel truth sets. """ out_file = "%s-filter.vcf.gz" % utils.splitext_plus(in_file)[0] if not utils.file_uptodate(out_file, in_file): runner = broad.runner_from_config(data["config"]) gatk_type = runner.gatk_type() assert gatk_type == "gatk4", "CNN filtering requires GATK4" if "train_hapmap" not in vrn_files: raise ValueError("CNN filtering requires HapMap training inputs: %s" % vrn_files) with file_transaction(data, out_file) as tx_out_file: params = ["-T", "FilterVariantTranches", "--variant", in_file, "--output", tx_out_file, "--snp-truth-vcf", vrn_files["train_hapmap"], "--indel-truth-vcf", vrn_files["train_indels"]] if tensor_type == "reference": params += ["--info-key", "CNN_1D", "--tranche", "99"] else: assert tensor_type == "read_tensor" params += ["--info-key", "CNN_2D", "--tranche", "99"] runner.run_gatk(params) return vcfutils.bgzip_and_index(out_file, data["config"])
[ "def", "_cnn_tranch_filtering", "(", "in_file", ",", "vrn_files", ",", "tensor_type", ",", "data", ")", ":", "out_file", "=", "\"%s-filter.vcf.gz\"", "%", "utils", ".", "splitext_plus", "(", "in_file", ")", "[", "0", "]", "if", "not", "utils", ".", "file_upt...
Filter CNN scored VCFs in tranches using standard SNP and Indel truth sets.
[ "Filter", "CNN", "scored", "VCFs", "in", "tranches", "using", "standard", "SNP", "and", "Indel", "truth", "sets", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L53-L74
223,781
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
_cnn_score_variants
def _cnn_score_variants(in_file, tensor_type, data): """Score variants with pre-trained CNN models. """ out_file = "%s-cnnscore.vcf.gz" % utils.splitext_plus(in_file)[0] if not utils.file_uptodate(out_file, in_file): runner = broad.runner_from_config(data["config"]) gatk_type = runner.gatk_type() assert gatk_type == "gatk4", "CNN filtering requires GATK4" with file_transaction(data, out_file) as tx_out_file: params = ["-T", "CNNScoreVariants", "--variant", in_file, "--reference", dd.get_ref_file(data), "--output", tx_out_file, "--input", dd.get_align_bam(data)] params += ["--tensor-type", tensor_type] runner.run_gatk(params) return vcfutils.bgzip_and_index(out_file, data["config"])
python
def _cnn_score_variants(in_file, tensor_type, data): """Score variants with pre-trained CNN models. """ out_file = "%s-cnnscore.vcf.gz" % utils.splitext_plus(in_file)[0] if not utils.file_uptodate(out_file, in_file): runner = broad.runner_from_config(data["config"]) gatk_type = runner.gatk_type() assert gatk_type == "gatk4", "CNN filtering requires GATK4" with file_transaction(data, out_file) as tx_out_file: params = ["-T", "CNNScoreVariants", "--variant", in_file, "--reference", dd.get_ref_file(data), "--output", tx_out_file, "--input", dd.get_align_bam(data)] params += ["--tensor-type", tensor_type] runner.run_gatk(params) return vcfutils.bgzip_and_index(out_file, data["config"])
[ "def", "_cnn_score_variants", "(", "in_file", ",", "tensor_type", ",", "data", ")", ":", "out_file", "=", "\"%s-cnnscore.vcf.gz\"", "%", "utils", ".", "splitext_plus", "(", "in_file", ")", "[", "0", "]", "if", "not", "utils", ".", "file_uptodate", "(", "out_...
Score variants with pre-trained CNN models.
[ "Score", "variants", "with", "pre", "-", "trained", "CNN", "models", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L76-L89
223,782
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
_apply_vqsr
def _apply_vqsr(in_file, ref_file, recal_file, tranch_file, sensitivity_cutoff, filter_type, data): """Apply VQSR based on the specified tranche, returning a filtered VCF file. """ base, ext = utils.splitext_plus(in_file) out_file = "{base}-{filter}filter{ext}".format(base=base, ext=ext, filter=filter_type) if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: broad_runner = broad.runner_from_config(data["config"]) gatk_type = broad_runner.gatk_type() if gatk_type == "gatk4": params = ["-T", "ApplyVQSR", "--variant", in_file, "--output", tx_out_file, "--recal-file", recal_file, "--tranches-file", tranch_file] else: params = ["-T", "ApplyRecalibration", "--input", in_file, "--out", tx_out_file, "--recal_file", recal_file, "--tranches_file", tranch_file] params += ["-R", ref_file, "--mode", filter_type] resources = config_utils.get_resources("gatk_apply_recalibration", data["config"]) opts = resources.get("options", []) if not opts: if gatk_type == "gatk4": opts += ["--truth-sensitivity-filter-level", sensitivity_cutoff] else: opts += ["--ts_filter_level", sensitivity_cutoff] params += opts broad_runner.run_gatk(params) return out_file
python
def _apply_vqsr(in_file, ref_file, recal_file, tranch_file, sensitivity_cutoff, filter_type, data): """Apply VQSR based on the specified tranche, returning a filtered VCF file. """ base, ext = utils.splitext_plus(in_file) out_file = "{base}-{filter}filter{ext}".format(base=base, ext=ext, filter=filter_type) if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: broad_runner = broad.runner_from_config(data["config"]) gatk_type = broad_runner.gatk_type() if gatk_type == "gatk4": params = ["-T", "ApplyVQSR", "--variant", in_file, "--output", tx_out_file, "--recal-file", recal_file, "--tranches-file", tranch_file] else: params = ["-T", "ApplyRecalibration", "--input", in_file, "--out", tx_out_file, "--recal_file", recal_file, "--tranches_file", tranch_file] params += ["-R", ref_file, "--mode", filter_type] resources = config_utils.get_resources("gatk_apply_recalibration", data["config"]) opts = resources.get("options", []) if not opts: if gatk_type == "gatk4": opts += ["--truth-sensitivity-filter-level", sensitivity_cutoff] else: opts += ["--ts_filter_level", sensitivity_cutoff] params += opts broad_runner.run_gatk(params) return out_file
[ "def", "_apply_vqsr", "(", "in_file", ",", "ref_file", ",", "recal_file", ",", "tranch_file", ",", "sensitivity_cutoff", ",", "filter_type", ",", "data", ")", ":", "base", ",", "ext", "=", "utils", ".", "splitext_plus", "(", "in_file", ")", "out_file", "=", ...
Apply VQSR based on the specified tranche, returning a filtered VCF file.
[ "Apply", "VQSR", "based", "on", "the", "specified", "tranche", "returning", "a", "filtered", "VCF", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L93-L127
223,783
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
_get_training_data
def _get_training_data(vrn_files): """Retrieve training data, returning an empty set of information if not available. """ out = {"SNP": [], "INDEL": []} # SNPs for name, train_info in [("train_hapmap", "known=false,training=true,truth=true,prior=15.0"), ("train_omni", "known=false,training=true,truth=true,prior=12.0"), ("train_1000g", "known=false,training=true,truth=false,prior=10.0"), ("dbsnp", "known=true,training=false,truth=false,prior=2.0")]: if name not in vrn_files: return {} else: out["SNP"].append((name.replace("train_", ""), train_info, vrn_files[name])) # Indels if "train_indels" in vrn_files: out["INDEL"].append(("mills", "known=true,training=true,truth=true,prior=12.0", vrn_files["train_indels"])) else: return {} return out
python
def _get_training_data(vrn_files): """Retrieve training data, returning an empty set of information if not available. """ out = {"SNP": [], "INDEL": []} # SNPs for name, train_info in [("train_hapmap", "known=false,training=true,truth=true,prior=15.0"), ("train_omni", "known=false,training=true,truth=true,prior=12.0"), ("train_1000g", "known=false,training=true,truth=false,prior=10.0"), ("dbsnp", "known=true,training=false,truth=false,prior=2.0")]: if name not in vrn_files: return {} else: out["SNP"].append((name.replace("train_", ""), train_info, vrn_files[name])) # Indels if "train_indels" in vrn_files: out["INDEL"].append(("mills", "known=true,training=true,truth=true,prior=12.0", vrn_files["train_indels"])) else: return {} return out
[ "def", "_get_training_data", "(", "vrn_files", ")", ":", "out", "=", "{", "\"SNP\"", ":", "[", "]", ",", "\"INDEL\"", ":", "[", "]", "}", "# SNPs", "for", "name", ",", "train_info", "in", "[", "(", "\"train_hapmap\"", ",", "\"known=false,training=true,truth=...
Retrieve training data, returning an empty set of information if not available.
[ "Retrieve", "training", "data", "returning", "an", "empty", "set", "of", "information", "if", "not", "available", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L129-L148
223,784
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
_get_vqsr_training
def _get_vqsr_training(filter_type, vrn_files, gatk_type): """Return parameters for VQSR training, handling SNPs and Indels. """ params = [] for name, train_info, fname in _get_training_data(vrn_files)[filter_type]: if gatk_type == "gatk4": params.extend(["--resource:%s,%s" % (name, train_info), fname]) if filter_type == "INDEL": params.extend(["--max-gaussians", "4"]) else: params.extend(["-resource:%s,VCF,%s" % (name, train_info), fname]) if filter_type == "INDEL": params.extend(["--maxGaussians", "4"]) return params
python
def _get_vqsr_training(filter_type, vrn_files, gatk_type): """Return parameters for VQSR training, handling SNPs and Indels. """ params = [] for name, train_info, fname in _get_training_data(vrn_files)[filter_type]: if gatk_type == "gatk4": params.extend(["--resource:%s,%s" % (name, train_info), fname]) if filter_type == "INDEL": params.extend(["--max-gaussians", "4"]) else: params.extend(["-resource:%s,VCF,%s" % (name, train_info), fname]) if filter_type == "INDEL": params.extend(["--maxGaussians", "4"]) return params
[ "def", "_get_vqsr_training", "(", "filter_type", ",", "vrn_files", ",", "gatk_type", ")", ":", "params", "=", "[", "]", "for", "name", ",", "train_info", ",", "fname", "in", "_get_training_data", "(", "vrn_files", ")", "[", "filter_type", "]", ":", "if", "...
Return parameters for VQSR training, handling SNPs and Indels.
[ "Return", "parameters", "for", "VQSR", "training", "handling", "SNPs", "and", "Indels", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L153-L166
223,785
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
_get_vqsr_annotations
def _get_vqsr_annotations(filter_type, data): """Retrieve appropriate annotations to use for VQSR based on filter type. Issues reported with MQ and bwa-mem quality distribution, results in intermittent failures to use VQSR: http://gatkforums.broadinstitute.org/discussion/4425/variant-recalibration-failing http://gatkforums.broadinstitute.org/discussion/4248/variantrecalibrator-removing-all-snps-from-the-training-set """ if filter_type == "SNP": # MQ, MQRankSum anns = ["QD", "FS", "ReadPosRankSum", "SOR"] else: assert filter_type == "INDEL" # MQRankSum anns = ["QD", "FS", "ReadPosRankSum", "SOR"] if dd.get_coverage_interval(data) == "genome": anns += ["DP"] return anns
python
def _get_vqsr_annotations(filter_type, data): """Retrieve appropriate annotations to use for VQSR based on filter type. Issues reported with MQ and bwa-mem quality distribution, results in intermittent failures to use VQSR: http://gatkforums.broadinstitute.org/discussion/4425/variant-recalibration-failing http://gatkforums.broadinstitute.org/discussion/4248/variantrecalibrator-removing-all-snps-from-the-training-set """ if filter_type == "SNP": # MQ, MQRankSum anns = ["QD", "FS", "ReadPosRankSum", "SOR"] else: assert filter_type == "INDEL" # MQRankSum anns = ["QD", "FS", "ReadPosRankSum", "SOR"] if dd.get_coverage_interval(data) == "genome": anns += ["DP"] return anns
[ "def", "_get_vqsr_annotations", "(", "filter_type", ",", "data", ")", ":", "if", "filter_type", "==", "\"SNP\"", ":", "# MQ, MQRankSum", "anns", "=", "[", "\"QD\"", ",", "\"FS\"", ",", "\"ReadPosRankSum\"", ",", "\"SOR\"", "]", "else", ":", "assert", "filter_t...
Retrieve appropriate annotations to use for VQSR based on filter type. Issues reported with MQ and bwa-mem quality distribution, results in intermittent failures to use VQSR: http://gatkforums.broadinstitute.org/discussion/4425/variant-recalibration-failing http://gatkforums.broadinstitute.org/discussion/4248/variantrecalibrator-removing-all-snps-from-the-training-set
[ "Retrieve", "appropriate", "annotations", "to", "use", "for", "VQSR", "based", "on", "filter", "type", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L168-L185
223,786
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
_run_vqsr
def _run_vqsr(in_file, ref_file, vrn_files, sensitivity_cutoff, filter_type, data): """Run variant quality score recalibration. """ cutoffs = ["100.0", "99.99", "99.98", "99.97", "99.96", "99.95", "99.94", "99.93", "99.92", "99.91", "99.9", "99.8", "99.7", "99.6", "99.5", "99.0", "98.0", "90.0"] if sensitivity_cutoff not in cutoffs: cutoffs.append(sensitivity_cutoff) cutoffs.sort() broad_runner = broad.runner_from_config(data["config"]) gatk_type = broad_runner.gatk_type() base = utils.splitext_plus(in_file)[0] recal_file = ("%s-vqsrrecal.vcf.gz" % base) if gatk_type == "gatk4" else ("%s.recal" % base) tranches_file = "%s.tranches" % base plot_file = "%s-plots.R" % base if not utils.file_exists(recal_file): with file_transaction(data, recal_file, tranches_file, plot_file) as (tx_recal, tx_tranches, tx_plot_file): params = ["-T", "VariantRecalibrator", "-R", ref_file, "--mode", filter_type] if gatk_type == "gatk4": params += ["--variant", in_file, "--output", tx_recal, "--tranches-file", tx_tranches, "--rscript-file", tx_plot_file] else: params += ["--input", in_file, "--recal_file", tx_recal, "--tranches_file", tx_tranches, "--rscript_file", tx_plot_file] params += _get_vqsr_training(filter_type, vrn_files, gatk_type) resources = config_utils.get_resources("gatk_variant_recalibrator", data["config"]) opts = resources.get("options", []) if not opts: for cutoff in cutoffs: opts += ["-tranche", str(cutoff)] for a in _get_vqsr_annotations(filter_type, data): opts += ["-an", a] params += opts cores = dd.get_cores(data) memscale = {"magnitude": 0.9 * cores, "direction": "increase"} if cores > 1 else None try: broad_runner.new_resources("gatk-vqsr") broad_runner.run_gatk(params, log_error=False, memscale=memscale, parallel_gc=True) except: # Can fail to run if not enough values are present to train. return None, None if gatk_type == "gatk4": vcfutils.bgzip_and_index(recal_file, data["config"]) return recal_file, tranches_file
python
def _run_vqsr(in_file, ref_file, vrn_files, sensitivity_cutoff, filter_type, data): """Run variant quality score recalibration. """ cutoffs = ["100.0", "99.99", "99.98", "99.97", "99.96", "99.95", "99.94", "99.93", "99.92", "99.91", "99.9", "99.8", "99.7", "99.6", "99.5", "99.0", "98.0", "90.0"] if sensitivity_cutoff not in cutoffs: cutoffs.append(sensitivity_cutoff) cutoffs.sort() broad_runner = broad.runner_from_config(data["config"]) gatk_type = broad_runner.gatk_type() base = utils.splitext_plus(in_file)[0] recal_file = ("%s-vqsrrecal.vcf.gz" % base) if gatk_type == "gatk4" else ("%s.recal" % base) tranches_file = "%s.tranches" % base plot_file = "%s-plots.R" % base if not utils.file_exists(recal_file): with file_transaction(data, recal_file, tranches_file, plot_file) as (tx_recal, tx_tranches, tx_plot_file): params = ["-T", "VariantRecalibrator", "-R", ref_file, "--mode", filter_type] if gatk_type == "gatk4": params += ["--variant", in_file, "--output", tx_recal, "--tranches-file", tx_tranches, "--rscript-file", tx_plot_file] else: params += ["--input", in_file, "--recal_file", tx_recal, "--tranches_file", tx_tranches, "--rscript_file", tx_plot_file] params += _get_vqsr_training(filter_type, vrn_files, gatk_type) resources = config_utils.get_resources("gatk_variant_recalibrator", data["config"]) opts = resources.get("options", []) if not opts: for cutoff in cutoffs: opts += ["-tranche", str(cutoff)] for a in _get_vqsr_annotations(filter_type, data): opts += ["-an", a] params += opts cores = dd.get_cores(data) memscale = {"magnitude": 0.9 * cores, "direction": "increase"} if cores > 1 else None try: broad_runner.new_resources("gatk-vqsr") broad_runner.run_gatk(params, log_error=False, memscale=memscale, parallel_gc=True) except: # Can fail to run if not enough values are present to train. return None, None if gatk_type == "gatk4": vcfutils.bgzip_and_index(recal_file, data["config"]) return recal_file, tranches_file
[ "def", "_run_vqsr", "(", "in_file", ",", "ref_file", ",", "vrn_files", ",", "sensitivity_cutoff", ",", "filter_type", ",", "data", ")", ":", "cutoffs", "=", "[", "\"100.0\"", ",", "\"99.99\"", ",", "\"99.98\"", ",", "\"99.97\"", ",", "\"99.96\"", ",", "\"99....
Run variant quality score recalibration.
[ "Run", "variant", "quality", "score", "recalibration", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L187-L230
223,787
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
_already_cutoff_filtered
def _already_cutoff_filtered(in_file, filter_type): """Check if we have a pre-existing cutoff-based filter file from previous VQSR failure. """ filter_file = "%s-filter%s.vcf.gz" % (utils.splitext_plus(in_file)[0], filter_type) return utils.file_exists(filter_file)
python
def _already_cutoff_filtered(in_file, filter_type): """Check if we have a pre-existing cutoff-based filter file from previous VQSR failure. """ filter_file = "%s-filter%s.vcf.gz" % (utils.splitext_plus(in_file)[0], filter_type) return utils.file_exists(filter_file)
[ "def", "_already_cutoff_filtered", "(", "in_file", ",", "filter_type", ")", ":", "filter_file", "=", "\"%s-filter%s.vcf.gz\"", "%", "(", "utils", ".", "splitext_plus", "(", "in_file", ")", "[", "0", "]", ",", "filter_type", ")", "return", "utils", ".", "file_e...
Check if we have a pre-existing cutoff-based filter file from previous VQSR failure.
[ "Check", "if", "we", "have", "a", "pre", "-", "existing", "cutoff", "-", "based", "filter", "file", "from", "previous", "VQSR", "failure", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L234-L238
223,788
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
_variant_filtration
def _variant_filtration(in_file, ref_file, vrn_files, data, filter_type, hard_filter_fn): """Filter SNP and indel variant calls using GATK best practice recommendations. Use cutoff-based soft filters if configuration indicates too little data or already finished a cutoff-based filtering step, otherwise try VQSR. """ # Algorithms multiplied by number of input files to check for large enough sample sizes algs = [data["config"]["algorithm"]] * len(data.get("vrn_files", [1])) if (not config_utils.use_vqsr(algs, in_file) or _already_cutoff_filtered(in_file, filter_type)): logger.info("Skipping VQSR, using cutoff-based filers: we don't have whole genome input data") return hard_filter_fn(in_file, data) elif not _have_training_data(vrn_files): logger.info("Skipping VQSR, using cutoff-based filers: genome build does not have sufficient training data") return hard_filter_fn(in_file, data) else: sensitivities = {"INDEL": "98.0", "SNP": "99.97"} recal_file, tranches_file = _run_vqsr(in_file, ref_file, vrn_files, sensitivities[filter_type], filter_type, data) if recal_file is None: # VQSR failed logger.info("VQSR failed due to lack of training data. Using cutoff-based soft filtering.") return hard_filter_fn(in_file, data) else: return _apply_vqsr(in_file, ref_file, recal_file, tranches_file, sensitivities[filter_type], filter_type, data)
python
def _variant_filtration(in_file, ref_file, vrn_files, data, filter_type, hard_filter_fn): """Filter SNP and indel variant calls using GATK best practice recommendations. Use cutoff-based soft filters if configuration indicates too little data or already finished a cutoff-based filtering step, otherwise try VQSR. """ # Algorithms multiplied by number of input files to check for large enough sample sizes algs = [data["config"]["algorithm"]] * len(data.get("vrn_files", [1])) if (not config_utils.use_vqsr(algs, in_file) or _already_cutoff_filtered(in_file, filter_type)): logger.info("Skipping VQSR, using cutoff-based filers: we don't have whole genome input data") return hard_filter_fn(in_file, data) elif not _have_training_data(vrn_files): logger.info("Skipping VQSR, using cutoff-based filers: genome build does not have sufficient training data") return hard_filter_fn(in_file, data) else: sensitivities = {"INDEL": "98.0", "SNP": "99.97"} recal_file, tranches_file = _run_vqsr(in_file, ref_file, vrn_files, sensitivities[filter_type], filter_type, data) if recal_file is None: # VQSR failed logger.info("VQSR failed due to lack of training data. Using cutoff-based soft filtering.") return hard_filter_fn(in_file, data) else: return _apply_vqsr(in_file, ref_file, recal_file, tranches_file, sensitivities[filter_type], filter_type, data)
[ "def", "_variant_filtration", "(", "in_file", ",", "ref_file", ",", "vrn_files", ",", "data", ",", "filter_type", ",", "hard_filter_fn", ")", ":", "# Algorithms multiplied by number of input files to check for large enough sample sizes", "algs", "=", "[", "data", "[", "\"...
Filter SNP and indel variant calls using GATK best practice recommendations. Use cutoff-based soft filters if configuration indicates too little data or already finished a cutoff-based filtering step, otherwise try VQSR.
[ "Filter", "SNP", "and", "indel", "variant", "calls", "using", "GATK", "best", "practice", "recommendations", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L240-L265
223,789
bcbio/bcbio-nextgen
bcbio/variation/gatkfilter.py
gatk_remove_missingalt
def gatk_remove_missingalt(in_file, data): """ GATK 4.1.0.0 outputs variants that have missing ALTs, which breaks downstream tools, this filters those out. """ base = in_file.split('.vcf.gz')[0] out_file = "%s-nomissingalt%s" % (base, '.vcf.gz') if utils.file_exists(out_file): return out_file no_gzip_out = out_file.replace(".vcf.gz", ".vcf") with file_transaction(no_gzip_out) as tx_out_file: with utils.open_gzipsafe(in_file) as in_handle, open(tx_out_file, "w") as out_handle: for line in in_handle: line = remove_missingalt(line) if line: out_handle.write(line) return vcfutils.bgzip_and_index(no_gzip_out, data["config"])
python
def gatk_remove_missingalt(in_file, data): """ GATK 4.1.0.0 outputs variants that have missing ALTs, which breaks downstream tools, this filters those out. """ base = in_file.split('.vcf.gz')[0] out_file = "%s-nomissingalt%s" % (base, '.vcf.gz') if utils.file_exists(out_file): return out_file no_gzip_out = out_file.replace(".vcf.gz", ".vcf") with file_transaction(no_gzip_out) as tx_out_file: with utils.open_gzipsafe(in_file) as in_handle, open(tx_out_file, "w") as out_handle: for line in in_handle: line = remove_missingalt(line) if line: out_handle.write(line) return vcfutils.bgzip_and_index(no_gzip_out, data["config"])
[ "def", "gatk_remove_missingalt", "(", "in_file", ",", "data", ")", ":", "base", "=", "in_file", ".", "split", "(", "'.vcf.gz'", ")", "[", "0", "]", "out_file", "=", "\"%s-nomissingalt%s\"", "%", "(", "base", ",", "'.vcf.gz'", ")", "if", "utils", ".", "fi...
GATK 4.1.0.0 outputs variants that have missing ALTs, which breaks downstream tools, this filters those out.
[ "GATK", "4", ".", "1", ".", "0", ".", "0", "outputs", "variants", "that", "have", "missing", "ALTs", "which", "breaks", "downstream", "tools", "this", "filters", "those", "out", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/gatkfilter.py#L276-L292
223,790
bcbio/bcbio-nextgen
bcbio/rnaseq/cufflinks.py
strand_unknown
def strand_unknown(db, transcript): """ for unstranded data with novel transcripts single exon genes will have no strand information. single exon novel genes are also a source of noise in the Cufflinks assembly so this removes them """ features = list(db.children(transcript)) strand = features[0].strand if strand == ".": return True else: return False
python
def strand_unknown(db, transcript): """ for unstranded data with novel transcripts single exon genes will have no strand information. single exon novel genes are also a source of noise in the Cufflinks assembly so this removes them """ features = list(db.children(transcript)) strand = features[0].strand if strand == ".": return True else: return False
[ "def", "strand_unknown", "(", "db", ",", "transcript", ")", ":", "features", "=", "list", "(", "db", ".", "children", "(", "transcript", ")", ")", "strand", "=", "features", "[", "0", "]", ".", "strand", "if", "strand", "==", "\".\"", ":", "return", ...
for unstranded data with novel transcripts single exon genes will have no strand information. single exon novel genes are also a source of noise in the Cufflinks assembly so this removes them
[ "for", "unstranded", "data", "with", "novel", "transcripts", "single", "exon", "genes", "will", "have", "no", "strand", "information", ".", "single", "exon", "novel", "genes", "are", "also", "a", "source", "of", "noise", "in", "the", "Cufflinks", "assembly", ...
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/cufflinks.py#L156-L167
223,791
bcbio/bcbio-nextgen
bcbio/rnaseq/cufflinks.py
fix_cufflinks_attributes
def fix_cufflinks_attributes(ref_gtf, merged_gtf, data, out_file=None): """ replace the cufflinks gene_id and transcript_id with the gene_id and transcript_id from ref_gtf, where available """ base, ext = os.path.splitext(merged_gtf) fixed = out_file if out_file else base + ".clean.fixed" + ext if file_exists(fixed): return fixed ref_db = gtf.get_gtf_db(ref_gtf) merged_db = gtf.get_gtf_db(merged_gtf, in_memory=True) ref_tid_to_gid = {} for gene in ref_db.features_of_type('gene'): for transcript in ref_db.children(gene, level=1): ref_tid_to_gid[transcript.id] = gene.id ctid_to_cgid = {} ctid_to_oid = {} for gene in merged_db.features_of_type('gene'): for transcript in merged_db.children(gene, level=1): ctid_to_cgid[transcript.id] = gene.id feature = list(merged_db.children(transcript))[0] oid = feature.attributes.get("oId", [None])[0] if oid: ctid_to_oid[transcript.id] = oid cgid_to_gid = {} for ctid, oid in ctid_to_oid.items(): cgid = ctid_to_cgid.get(ctid, None) oid = ctid_to_oid.get(ctid, None) gid = ref_tid_to_gid.get(oid, None) if oid else None if cgid and gid: cgid_to_gid[cgid] = gid with file_transaction(data, fixed) as tmp_fixed_file: with open(tmp_fixed_file, "w") as out_handle: for gene in merged_db.features_of_type('gene'): for transcript in merged_db.children(gene, level=1): for feature in merged_db.children(transcript): cgid = feature.attributes.get("gene_id", [None])[0] gid = cgid_to_gid.get(cgid, None) ctid = None if gid: feature.attributes["gene_id"][0] = gid ctid = feature.attributes.get("transcript_id", [None])[0] tid = ctid_to_oid.get(ctid, None) if tid: feature.attributes["transcript_id"][0] = tid if "nearest_ref" in feature.attributes: del feature.attributes["nearest_ref"] if "oId" in feature.attributes: del feature.attributes["oId"] out_handle.write(str(feature) + "\n") return fixed
python
def fix_cufflinks_attributes(ref_gtf, merged_gtf, data, out_file=None): """ replace the cufflinks gene_id and transcript_id with the gene_id and transcript_id from ref_gtf, where available """ base, ext = os.path.splitext(merged_gtf) fixed = out_file if out_file else base + ".clean.fixed" + ext if file_exists(fixed): return fixed ref_db = gtf.get_gtf_db(ref_gtf) merged_db = gtf.get_gtf_db(merged_gtf, in_memory=True) ref_tid_to_gid = {} for gene in ref_db.features_of_type('gene'): for transcript in ref_db.children(gene, level=1): ref_tid_to_gid[transcript.id] = gene.id ctid_to_cgid = {} ctid_to_oid = {} for gene in merged_db.features_of_type('gene'): for transcript in merged_db.children(gene, level=1): ctid_to_cgid[transcript.id] = gene.id feature = list(merged_db.children(transcript))[0] oid = feature.attributes.get("oId", [None])[0] if oid: ctid_to_oid[transcript.id] = oid cgid_to_gid = {} for ctid, oid in ctid_to_oid.items(): cgid = ctid_to_cgid.get(ctid, None) oid = ctid_to_oid.get(ctid, None) gid = ref_tid_to_gid.get(oid, None) if oid else None if cgid and gid: cgid_to_gid[cgid] = gid with file_transaction(data, fixed) as tmp_fixed_file: with open(tmp_fixed_file, "w") as out_handle: for gene in merged_db.features_of_type('gene'): for transcript in merged_db.children(gene, level=1): for feature in merged_db.children(transcript): cgid = feature.attributes.get("gene_id", [None])[0] gid = cgid_to_gid.get(cgid, None) ctid = None if gid: feature.attributes["gene_id"][0] = gid ctid = feature.attributes.get("transcript_id", [None])[0] tid = ctid_to_oid.get(ctid, None) if tid: feature.attributes["transcript_id"][0] = tid if "nearest_ref" in feature.attributes: del feature.attributes["nearest_ref"] if "oId" in feature.attributes: del feature.attributes["oId"] out_handle.write(str(feature) + "\n") return fixed
[ "def", "fix_cufflinks_attributes", "(", "ref_gtf", ",", "merged_gtf", ",", "data", ",", "out_file", "=", "None", ")", ":", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "merged_gtf", ")", "fixed", "=", "out_file", "if", "out_file", "e...
replace the cufflinks gene_id and transcript_id with the gene_id and transcript_id from ref_gtf, where available
[ "replace", "the", "cufflinks", "gene_id", "and", "transcript_id", "with", "the", "gene_id", "and", "transcript_id", "from", "ref_gtf", "where", "available" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/cufflinks.py#L179-L234
223,792
bcbio/bcbio-nextgen
bcbio/rnaseq/cufflinks.py
merge
def merge(assembled_gtfs, ref_file, gtf_file, num_cores, data): """ run cuffmerge on a set of assembled GTF files """ assembled_file = tempfile.NamedTemporaryFile(delete=False).name with open(assembled_file, "w") as temp_handle: for assembled in assembled_gtfs: temp_handle.write(assembled + "\n") out_dir = os.path.join("assembly", "cuffmerge") merged_file = os.path.join(out_dir, "merged.gtf") out_file = os.path.join(out_dir, "assembled.gtf") if file_exists(out_file): return out_file if not file_exists(merged_file): with file_transaction(data, out_dir) as tmp_out_dir: cmd = ("cuffmerge -o {tmp_out_dir} --ref-gtf {gtf_file} " "--num-threads {num_cores} --ref-sequence {ref_file} " "{assembled_file}") cmd = cmd.format(**locals()) message = ("Merging the following transcript assemblies with " "Cuffmerge: %s" % ", ".join(assembled_gtfs)) do.run(cmd, message) clean, _ = clean_assembly(merged_file) fixed = fix_cufflinks_attributes(gtf_file, clean, data) classified = annotate_gtf.annotate_novel_coding(fixed, gtf_file, ref_file, data) filtered = annotate_gtf.cleanup_transcripts(classified, gtf_file, ref_file) shutil.move(filtered, out_file) return out_file
python
def merge(assembled_gtfs, ref_file, gtf_file, num_cores, data): """ run cuffmerge on a set of assembled GTF files """ assembled_file = tempfile.NamedTemporaryFile(delete=False).name with open(assembled_file, "w") as temp_handle: for assembled in assembled_gtfs: temp_handle.write(assembled + "\n") out_dir = os.path.join("assembly", "cuffmerge") merged_file = os.path.join(out_dir, "merged.gtf") out_file = os.path.join(out_dir, "assembled.gtf") if file_exists(out_file): return out_file if not file_exists(merged_file): with file_transaction(data, out_dir) as tmp_out_dir: cmd = ("cuffmerge -o {tmp_out_dir} --ref-gtf {gtf_file} " "--num-threads {num_cores} --ref-sequence {ref_file} " "{assembled_file}") cmd = cmd.format(**locals()) message = ("Merging the following transcript assemblies with " "Cuffmerge: %s" % ", ".join(assembled_gtfs)) do.run(cmd, message) clean, _ = clean_assembly(merged_file) fixed = fix_cufflinks_attributes(gtf_file, clean, data) classified = annotate_gtf.annotate_novel_coding(fixed, gtf_file, ref_file, data) filtered = annotate_gtf.cleanup_transcripts(classified, gtf_file, ref_file) shutil.move(filtered, out_file) return out_file
[ "def", "merge", "(", "assembled_gtfs", ",", "ref_file", ",", "gtf_file", ",", "num_cores", ",", "data", ")", ":", "assembled_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", ".", "name", "with", "open", "(", "assembled_fil...
run cuffmerge on a set of assembled GTF files
[ "run", "cuffmerge", "on", "a", "set", "of", "assembled", "GTF", "files" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/cufflinks.py#L237-L265
223,793
bcbio/bcbio-nextgen
scripts/utils/hydra_to_vcf.py
_vcf_info
def _vcf_info(start, end, mate_id, info=None): """Return breakend information line with mate and imprecise location. """ out = "SVTYPE=BND;MATEID={mate};IMPRECISE;CIPOS=0,{size}".format( mate=mate_id, size=end-start) if info is not None: extra_info = ";".join("{0}={1}".format(k, v) for k, v in info.iteritems()) out = "{0};{1}".format(out, extra_info) return out
python
def _vcf_info(start, end, mate_id, info=None): """Return breakend information line with mate and imprecise location. """ out = "SVTYPE=BND;MATEID={mate};IMPRECISE;CIPOS=0,{size}".format( mate=mate_id, size=end-start) if info is not None: extra_info = ";".join("{0}={1}".format(k, v) for k, v in info.iteritems()) out = "{0};{1}".format(out, extra_info) return out
[ "def", "_vcf_info", "(", "start", ",", "end", ",", "mate_id", ",", "info", "=", "None", ")", ":", "out", "=", "\"SVTYPE=BND;MATEID={mate};IMPRECISE;CIPOS=0,{size}\"", ".", "format", "(", "mate", "=", "mate_id", ",", "size", "=", "end", "-", "start", ")", "...
Return breakend information line with mate and imprecise location.
[ "Return", "breakend", "information", "line", "with", "mate", "and", "imprecise", "location", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/hydra_to_vcf.py#L47-L55
223,794
bcbio/bcbio-nextgen
scripts/utils/hydra_to_vcf.py
_vcf_alt
def _vcf_alt(base, other_chr, other_pos, isrc, is_first): """Create ALT allele line in VCF 4.1 format associating with other paired end. """ if is_first: pipe = "[" if isrc else "]" out_str = "{base}{pipe}{chr}:{pos}{pipe}" else: pipe = "]" if isrc else "[" out_str = "{pipe}{chr}:{pos}{pipe}{base}" return out_str.format(pipe=pipe, chr=other_chr, pos=other_pos + 1, base=base)
python
def _vcf_alt(base, other_chr, other_pos, isrc, is_first): """Create ALT allele line in VCF 4.1 format associating with other paired end. """ if is_first: pipe = "[" if isrc else "]" out_str = "{base}{pipe}{chr}:{pos}{pipe}" else: pipe = "]" if isrc else "[" out_str = "{pipe}{chr}:{pos}{pipe}{base}" return out_str.format(pipe=pipe, chr=other_chr, pos=other_pos + 1, base=base)
[ "def", "_vcf_alt", "(", "base", ",", "other_chr", ",", "other_pos", ",", "isrc", ",", "is_first", ")", ":", "if", "is_first", ":", "pipe", "=", "\"[\"", "if", "isrc", "else", "\"]\"", "out_str", "=", "\"{base}{pipe}{chr}:{pos}{pipe}\"", "else", ":", "pipe", ...
Create ALT allele line in VCF 4.1 format associating with other paired end.
[ "Create", "ALT", "allele", "line", "in", "VCF", "4", ".", "1", "format", "associating", "with", "other", "paired", "end", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/hydra_to_vcf.py#L57-L67
223,795
bcbio/bcbio-nextgen
scripts/utils/hydra_to_vcf.py
_breakend_orientation
def _breakend_orientation(strand1, strand2): """Convert BEDPE strand representation of breakpoints into VCF. | strand1 | strand2 | VCF | +----------+----------+--------------+ | + | - | t[p[ ]p]t | | + | + | t]p] t]p] | | - | - | [p[t [p[t | | - | + | ]p]t t[p[ | """ EndOrientation = namedtuple("EndOrientation", ["is_first1", "is_rc1", "is_first2", "is_rc2"]) if strand1 == "+" and strand2 == "-": return EndOrientation(True, True, False, True) elif strand1 == "+" and strand2 == "+": return EndOrientation(True, False, True, False) elif strand1 == "-" and strand2 == "-": return EndOrientation(False, False, False, False) elif strand1 == "-" and strand2 == "+": return EndOrientation(False, True, True, True) else: raise ValueError("Unexpected strand pairing: {0} {1}".format( strand1, strand2))
python
def _breakend_orientation(strand1, strand2): """Convert BEDPE strand representation of breakpoints into VCF. | strand1 | strand2 | VCF | +----------+----------+--------------+ | + | - | t[p[ ]p]t | | + | + | t]p] t]p] | | - | - | [p[t [p[t | | - | + | ]p]t t[p[ | """ EndOrientation = namedtuple("EndOrientation", ["is_first1", "is_rc1", "is_first2", "is_rc2"]) if strand1 == "+" and strand2 == "-": return EndOrientation(True, True, False, True) elif strand1 == "+" and strand2 == "+": return EndOrientation(True, False, True, False) elif strand1 == "-" and strand2 == "-": return EndOrientation(False, False, False, False) elif strand1 == "-" and strand2 == "+": return EndOrientation(False, True, True, True) else: raise ValueError("Unexpected strand pairing: {0} {1}".format( strand1, strand2))
[ "def", "_breakend_orientation", "(", "strand1", ",", "strand2", ")", ":", "EndOrientation", "=", "namedtuple", "(", "\"EndOrientation\"", ",", "[", "\"is_first1\"", ",", "\"is_rc1\"", ",", "\"is_first2\"", ",", "\"is_rc2\"", "]", ")", "if", "strand1", "==", "\"+...
Convert BEDPE strand representation of breakpoints into VCF. | strand1 | strand2 | VCF | +----------+----------+--------------+ | + | - | t[p[ ]p]t | | + | + | t]p] t]p] | | - | - | [p[t [p[t | | - | + | ]p]t t[p[ |
[ "Convert", "BEDPE", "strand", "representation", "of", "breakpoints", "into", "VCF", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/hydra_to_vcf.py#L69-L91
223,796
bcbio/bcbio-nextgen
scripts/utils/hydra_to_vcf.py
build_vcf_parts
def build_vcf_parts(feature, genome_2bit, info=None): """Convert BedPe feature information into VCF part representation. Each feature will have two VCF lines for each side of the breakpoint. """ base1 = genome_2bit[feature.chrom1].get( feature.start1, feature.start1 + 1).upper() id1 = "hydra{0}a".format(feature.name) base2 = genome_2bit[feature.chrom2].get( feature.start2, feature.start2 + 1).upper() id2 = "hydra{0}b".format(feature.name) orientation = _breakend_orientation(feature.strand1, feature.strand2) return (VcfLine(feature.chrom1, feature.start1, id1, base1, _vcf_alt(base1, feature.chrom2, feature.start2, orientation.is_rc1, orientation.is_first1), _vcf_info(feature.start1, feature.end1, id2, info)), VcfLine(feature.chrom2, feature.start2, id2, base2, _vcf_alt(base2, feature.chrom1, feature.start1, orientation.is_rc2, orientation.is_first2), _vcf_info(feature.start2, feature.end2, id1, info)))
python
def build_vcf_parts(feature, genome_2bit, info=None): """Convert BedPe feature information into VCF part representation. Each feature will have two VCF lines for each side of the breakpoint. """ base1 = genome_2bit[feature.chrom1].get( feature.start1, feature.start1 + 1).upper() id1 = "hydra{0}a".format(feature.name) base2 = genome_2bit[feature.chrom2].get( feature.start2, feature.start2 + 1).upper() id2 = "hydra{0}b".format(feature.name) orientation = _breakend_orientation(feature.strand1, feature.strand2) return (VcfLine(feature.chrom1, feature.start1, id1, base1, _vcf_alt(base1, feature.chrom2, feature.start2, orientation.is_rc1, orientation.is_first1), _vcf_info(feature.start1, feature.end1, id2, info)), VcfLine(feature.chrom2, feature.start2, id2, base2, _vcf_alt(base2, feature.chrom1, feature.start1, orientation.is_rc2, orientation.is_first2), _vcf_info(feature.start2, feature.end2, id1, info)))
[ "def", "build_vcf_parts", "(", "feature", ",", "genome_2bit", ",", "info", "=", "None", ")", ":", "base1", "=", "genome_2bit", "[", "feature", ".", "chrom1", "]", ".", "get", "(", "feature", ".", "start1", ",", "feature", ".", "start1", "+", "1", ")", ...
Convert BedPe feature information into VCF part representation. Each feature will have two VCF lines for each side of the breakpoint.
[ "Convert", "BedPe", "feature", "information", "into", "VCF", "part", "representation", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/hydra_to_vcf.py#L95-L114
223,797
bcbio/bcbio-nextgen
scripts/utils/hydra_to_vcf.py
build_vcf_deletion
def build_vcf_deletion(x, genome_2bit): """Provide representation of deletion from BedPE breakpoints. """ base1 = genome_2bit[x.chrom1].get(x.start1, x.start1 + 1).upper() id1 = "hydra{0}".format(x.name) return VcfLine(x.chrom1, x.start1, id1, base1, "<DEL>", _vcf_single_end_info(x, "DEL", True))
python
def build_vcf_deletion(x, genome_2bit): """Provide representation of deletion from BedPE breakpoints. """ base1 = genome_2bit[x.chrom1].get(x.start1, x.start1 + 1).upper() id1 = "hydra{0}".format(x.name) return VcfLine(x.chrom1, x.start1, id1, base1, "<DEL>", _vcf_single_end_info(x, "DEL", True))
[ "def", "build_vcf_deletion", "(", "x", ",", "genome_2bit", ")", ":", "base1", "=", "genome_2bit", "[", "x", ".", "chrom1", "]", ".", "get", "(", "x", ".", "start1", ",", "x", ".", "start1", "+", "1", ")", ".", "upper", "(", ")", "id1", "=", "\"hy...
Provide representation of deletion from BedPE breakpoints.
[ "Provide", "representation", "of", "deletion", "from", "BedPE", "breakpoints", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/hydra_to_vcf.py#L136-L142
223,798
bcbio/bcbio-nextgen
scripts/utils/hydra_to_vcf.py
build_vcf_inversion
def build_vcf_inversion(x1, x2, genome_2bit): """Provide representation of inversion from BedPE breakpoints. """ id1 = "hydra{0}".format(x1.name) start_coords = sorted([x1.start1, x1.end1, x2.start1, x2.end1]) end_coords = sorted([x1.start2, x1.end2, x2.start2, x2.start2]) start_pos = (start_coords[1] + start_coords[2]) // 2 end_pos = (end_coords[1] + end_coords[2]) // 2 base1 = genome_2bit[x1.chrom1].get(start_pos, start_pos + 1).upper() info = "SVTYPE=INV;IMPRECISE;CIPOS={cip1},{cip2};CIEND={cie1},{cie2};" \ "END={end};SVLEN={length}".format(cip1=start_pos - start_coords[0], cip2=start_coords[-1] - start_pos, cie1=end_pos - end_coords[0], cie2=end_coords[-1] - end_pos, end=end_pos, length=end_pos-start_pos) return VcfLine(x1.chrom1, start_pos, id1, base1, "<INV>", info)
python
def build_vcf_inversion(x1, x2, genome_2bit): """Provide representation of inversion from BedPE breakpoints. """ id1 = "hydra{0}".format(x1.name) start_coords = sorted([x1.start1, x1.end1, x2.start1, x2.end1]) end_coords = sorted([x1.start2, x1.end2, x2.start2, x2.start2]) start_pos = (start_coords[1] + start_coords[2]) // 2 end_pos = (end_coords[1] + end_coords[2]) // 2 base1 = genome_2bit[x1.chrom1].get(start_pos, start_pos + 1).upper() info = "SVTYPE=INV;IMPRECISE;CIPOS={cip1},{cip2};CIEND={cie1},{cie2};" \ "END={end};SVLEN={length}".format(cip1=start_pos - start_coords[0], cip2=start_coords[-1] - start_pos, cie1=end_pos - end_coords[0], cie2=end_coords[-1] - end_pos, end=end_pos, length=end_pos-start_pos) return VcfLine(x1.chrom1, start_pos, id1, base1, "<INV>", info)
[ "def", "build_vcf_inversion", "(", "x1", ",", "x2", ",", "genome_2bit", ")", ":", "id1", "=", "\"hydra{0}\"", ".", "format", "(", "x1", ".", "name", ")", "start_coords", "=", "sorted", "(", "[", "x1", ".", "start1", ",", "x1", ".", "end1", ",", "x2",...
Provide representation of inversion from BedPE breakpoints.
[ "Provide", "representation", "of", "inversion", "from", "BedPE", "breakpoints", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/hydra_to_vcf.py#L166-L182
223,799
bcbio/bcbio-nextgen
scripts/utils/hydra_to_vcf.py
hydra_parser
def hydra_parser(in_file, options=None): """Parse hydra input file into namedtuple of values. """ if options is None: options = {} BedPe = namedtuple('BedPe', ["chrom1", "start1", "end1", "chrom2", "start2", "end2", "name", "strand1", "strand2", "support"]) with open(in_file) as in_handle: reader = csv.reader(in_handle, dialect="excel-tab") for line in reader: cur = BedPe(line[0], int(line[1]), int(line[2]), line[3], int(line[4]), int(line[5]), line[6], line[8], line[9], float(line[18])) if cur.support >= options.get("min_support", 0): yield cur
python
def hydra_parser(in_file, options=None): """Parse hydra input file into namedtuple of values. """ if options is None: options = {} BedPe = namedtuple('BedPe', ["chrom1", "start1", "end1", "chrom2", "start2", "end2", "name", "strand1", "strand2", "support"]) with open(in_file) as in_handle: reader = csv.reader(in_handle, dialect="excel-tab") for line in reader: cur = BedPe(line[0], int(line[1]), int(line[2]), line[3], int(line[4]), int(line[5]), line[6], line[8], line[9], float(line[18])) if cur.support >= options.get("min_support", 0): yield cur
[ "def", "hydra_parser", "(", "in_file", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "BedPe", "=", "namedtuple", "(", "'BedPe'", ",", "[", "\"chrom1\"", ",", "\"start1\"", ",", "\"end1\"", ",", "\"...
Parse hydra input file into namedtuple of values.
[ "Parse", "hydra", "input", "file", "into", "namedtuple", "of", "values", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/hydra_to_vcf.py#L198-L214