id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
237,500
bcbio/bcbio-nextgen
bcbio/broad/__init__.py
BroadRunner._get_picard_cmd
def _get_picard_cmd(self, command, memscale=None): """Retrieve the base Picard command, handling both shell scripts and directory of jars. """ resources = config_utils.get_resources("picard", self._config) if memscale: jvm_opts = get_picard_opts(self._config, memscale=memscale) elif resources.get("jvm_opts"): jvm_opts = resources.get("jvm_opts") else: jvm_opts = self._jvm_opts if os.path.isdir(self._picard_ref): dist_file = self._get_jar(command) return ["java"] + jvm_opts + get_default_jvm_opts() + ["-jar", dist_file] else: # XXX Cannot currently set JVM opts with picard-tools script return [self._picard_ref, command]
python
def _get_picard_cmd(self, command, memscale=None): resources = config_utils.get_resources("picard", self._config) if memscale: jvm_opts = get_picard_opts(self._config, memscale=memscale) elif resources.get("jvm_opts"): jvm_opts = resources.get("jvm_opts") else: jvm_opts = self._jvm_opts if os.path.isdir(self._picard_ref): dist_file = self._get_jar(command) return ["java"] + jvm_opts + get_default_jvm_opts() + ["-jar", dist_file] else: # XXX Cannot currently set JVM opts with picard-tools script return [self._picard_ref, command]
[ "def", "_get_picard_cmd", "(", "self", ",", "command", ",", "memscale", "=", "None", ")", ":", "resources", "=", "config_utils", ".", "get_resources", "(", "\"picard\"", ",", "self", ".", "_config", ")", "if", "memscale", ":", "jvm_opts", "=", "get_picard_op...
Retrieve the base Picard command, handling both shell scripts and directory of jars.
[ "Retrieve", "the", "base", "Picard", "command", "handling", "both", "shell", "scripts", "and", "directory", "of", "jars", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/__init__.py#L446-L461
237,501
bcbio/bcbio-nextgen
bcbio/broad/__init__.py
BroadRunner._get_jar
def _get_jar(self, command, alts=None, allow_missing=False): """Retrieve the jar for running the specified command. """ dirs = [] for bdir in [self._gatk_dir, self._picard_ref]: dirs.extend([bdir, os.path.join(bdir, os.pardir, "gatk")]) if alts is None: alts = [] for check_cmd in [command] + alts: for dir_check in dirs: try: check_file = config_utils.get_jar(check_cmd, dir_check) return check_file except ValueError as msg: if str(msg).find("multiple") > 0: raise else: pass if allow_missing: return None else: raise ValueError("Could not find jar %s in %s:%s" % (command, self._picard_ref, self._gatk_dir))
python
def _get_jar(self, command, alts=None, allow_missing=False): dirs = [] for bdir in [self._gatk_dir, self._picard_ref]: dirs.extend([bdir, os.path.join(bdir, os.pardir, "gatk")]) if alts is None: alts = [] for check_cmd in [command] + alts: for dir_check in dirs: try: check_file = config_utils.get_jar(check_cmd, dir_check) return check_file except ValueError as msg: if str(msg).find("multiple") > 0: raise else: pass if allow_missing: return None else: raise ValueError("Could not find jar %s in %s:%s" % (command, self._picard_ref, self._gatk_dir))
[ "def", "_get_jar", "(", "self", ",", "command", ",", "alts", "=", "None", ",", "allow_missing", "=", "False", ")", ":", "dirs", "=", "[", "]", "for", "bdir", "in", "[", "self", ".", "_gatk_dir", ",", "self", ".", "_picard_ref", "]", ":", "dirs", "....
Retrieve the jar for running the specified command.
[ "Retrieve", "the", "jar", "for", "running", "the", "specified", "command", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/__init__.py#L463-L484
237,502
bcbio/bcbio-nextgen
bcbio/utils.py
cpmap
def cpmap(cores=1): """Configurable parallel map context manager. Returns appropriate map compatible function based on configuration: - Local single core (the default) - Multiple local cores """ if int(cores) == 1: yield itertools.imap else: if futures is None: raise ImportError("concurrent.futures not available") pool = futures.ProcessPoolExecutor(cores) yield pool.map pool.shutdown()
python
def cpmap(cores=1): if int(cores) == 1: yield itertools.imap else: if futures is None: raise ImportError("concurrent.futures not available") pool = futures.ProcessPoolExecutor(cores) yield pool.map pool.shutdown()
[ "def", "cpmap", "(", "cores", "=", "1", ")", ":", "if", "int", "(", "cores", ")", "==", "1", ":", "yield", "itertools", ".", "imap", "else", ":", "if", "futures", "is", "None", ":", "raise", "ImportError", "(", "\"concurrent.futures not available\"", ")"...
Configurable parallel map context manager. Returns appropriate map compatible function based on configuration: - Local single core (the default) - Multiple local cores
[ "Configurable", "parallel", "map", "context", "manager", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L34-L48
237,503
bcbio/bcbio-nextgen
bcbio/utils.py
map_wrap
def map_wrap(f): """Wrap standard function to easily pass into 'map' processing. """ @functools.wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper
python
def map_wrap(f): @functools.wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper
[ "def", "map_wrap", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Wrap standard function to easily pass into 'map' processing.
[ "Wrap", "standard", "function", "to", "easily", "pass", "into", "map", "processing", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L50-L56
237,504
bcbio/bcbio-nextgen
bcbio/utils.py
unpack_worlds
def unpack_worlds(items): """Handle all the ways we can pass multiple samples for back-compatibility. """ # Unpack nested lists of samples grouped together (old IPython style) if isinstance(items[0], (list, tuple)) and len(items[0]) == 1: out = [] for d in items: assert len(d) == 1 and isinstance(d[0], dict), len(d) out.append(d[0]) # Unpack a single argument with multiple samples (CWL style) elif isinstance(items, (list, tuple)) and len(items) == 1 and isinstance(items[0], (list, tuple)): out = items[0] else: out = items return out
python
def unpack_worlds(items): # Unpack nested lists of samples grouped together (old IPython style) if isinstance(items[0], (list, tuple)) and len(items[0]) == 1: out = [] for d in items: assert len(d) == 1 and isinstance(d[0], dict), len(d) out.append(d[0]) # Unpack a single argument with multiple samples (CWL style) elif isinstance(items, (list, tuple)) and len(items) == 1 and isinstance(items[0], (list, tuple)): out = items[0] else: out = items return out
[ "def", "unpack_worlds", "(", "items", ")", ":", "# Unpack nested lists of samples grouped together (old IPython style)", "if", "isinstance", "(", "items", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", "and", "len", "(", "items", "[", "0", "]", ")", ...
Handle all the ways we can pass multiple samples for back-compatibility.
[ "Handle", "all", "the", "ways", "we", "can", "pass", "multiple", "samples", "for", "back", "-", "compatibility", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L160-L174
237,505
bcbio/bcbio-nextgen
bcbio/utils.py
safe_makedir
def safe_makedir(dname): """Make a directory if it doesn't exist, handling concurrent race conditions. """ if not dname: return dname num_tries = 0 max_tries = 5 while not os.path.exists(dname): # we could get an error here if multiple processes are creating # the directory at the same time. Grr, concurrency. try: os.makedirs(dname) except OSError: if num_tries > max_tries: raise num_tries += 1 time.sleep(2) return dname
python
def safe_makedir(dname): if not dname: return dname num_tries = 0 max_tries = 5 while not os.path.exists(dname): # we could get an error here if multiple processes are creating # the directory at the same time. Grr, concurrency. try: os.makedirs(dname) except OSError: if num_tries > max_tries: raise num_tries += 1 time.sleep(2) return dname
[ "def", "safe_makedir", "(", "dname", ")", ":", "if", "not", "dname", ":", "return", "dname", "num_tries", "=", "0", "max_tries", "=", "5", "while", "not", "os", ".", "path", ".", "exists", "(", "dname", ")", ":", "# we could get an error here if multiple pro...
Make a directory if it doesn't exist, handling concurrent race conditions.
[ "Make", "a", "directory", "if", "it", "doesn", "t", "exist", "handling", "concurrent", "race", "conditions", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L176-L193
237,506
bcbio/bcbio-nextgen
bcbio/utils.py
tmpfile
def tmpfile(*args, **kwargs): """Make a tempfile, safely cleaning up file descriptors on completion. """ (fd, fname) = tempfile.mkstemp(*args, **kwargs) try: yield fname finally: os.close(fd) if os.path.exists(fname): os.remove(fname)
python
def tmpfile(*args, **kwargs): (fd, fname) = tempfile.mkstemp(*args, **kwargs) try: yield fname finally: os.close(fd) if os.path.exists(fname): os.remove(fname)
[ "def", "tmpfile", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "(", "fd", ",", "fname", ")", "=", "tempfile", ".", "mkstemp", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "yield", "fname", "finally", ":", "os", ".", "clos...
Make a tempfile, safely cleaning up file descriptors on completion.
[ "Make", "a", "tempfile", "safely", "cleaning", "up", "file", "descriptors", "on", "completion", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L221-L230
237,507
bcbio/bcbio-nextgen
bcbio/utils.py
file_exists
def file_exists(fname): """Check if a file exists and is non-empty. """ try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: return False
python
def file_exists(fname): try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: return False
[ "def", "file_exists", "(", "fname", ")", ":", "try", ":", "return", "fname", "and", "os", ".", "path", ".", "exists", "(", "fname", ")", "and", "os", ".", "path", ".", "getsize", "(", "fname", ")", ">", "0", "except", "OSError", ":", "return", "Fal...
Check if a file exists and is non-empty.
[ "Check", "if", "a", "file", "exists", "and", "is", "non", "-", "empty", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L232-L238
237,508
bcbio/bcbio-nextgen
bcbio/utils.py
get_size
def get_size(path): """ Returns the size in bytes if `path` is a file, or the size of all files in `path` if it's a directory. Analogous to `du -s`. """ if os.path.isfile(path): return os.path.getsize(path) return sum(get_size(os.path.join(path, f)) for f in os.listdir(path))
python
def get_size(path): if os.path.isfile(path): return os.path.getsize(path) return sum(get_size(os.path.join(path, f)) for f in os.listdir(path))
[ "def", "get_size", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "return", "os", ".", "path", ".", "getsize", "(", "path", ")", "return", "sum", "(", "get_size", "(", "os", ".", "path", ".", "join", "(", ...
Returns the size in bytes if `path` is a file, or the size of all files in `path` if it's a directory. Analogous to `du -s`.
[ "Returns", "the", "size", "in", "bytes", "if", "path", "is", "a", "file", "or", "the", "size", "of", "all", "files", "in", "path", "if", "it", "s", "a", "directory", ".", "Analogous", "to", "du", "-", "s", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L241-L248
237,509
bcbio/bcbio-nextgen
bcbio/utils.py
read_galaxy_amqp_config
def read_galaxy_amqp_config(galaxy_config, base_dir): """Read connection information on the RabbitMQ server from Galaxy config. """ galaxy_config = add_full_path(galaxy_config, base_dir) config = six.moves.configparser.ConfigParser() config.read(galaxy_config) amqp_config = {} for option in config.options("galaxy_amqp"): amqp_config[option] = config.get("galaxy_amqp", option) return amqp_config
python
def read_galaxy_amqp_config(galaxy_config, base_dir): galaxy_config = add_full_path(galaxy_config, base_dir) config = six.moves.configparser.ConfigParser() config.read(galaxy_config) amqp_config = {} for option in config.options("galaxy_amqp"): amqp_config[option] = config.get("galaxy_amqp", option) return amqp_config
[ "def", "read_galaxy_amqp_config", "(", "galaxy_config", ",", "base_dir", ")", ":", "galaxy_config", "=", "add_full_path", "(", "galaxy_config", ",", "base_dir", ")", "config", "=", "six", ".", "moves", ".", "configparser", ".", "ConfigParser", "(", ")", "config"...
Read connection information on the RabbitMQ server from Galaxy config.
[ "Read", "connection", "information", "on", "the", "RabbitMQ", "server", "from", "Galaxy", "config", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L279-L288
237,510
bcbio/bcbio-nextgen
bcbio/utils.py
move_safe
def move_safe(origin, target): """ Move file, skip if exists """ if origin == target: return origin if file_exists(target): return target shutil.move(origin, target) return target
python
def move_safe(origin, target): if origin == target: return origin if file_exists(target): return target shutil.move(origin, target) return target
[ "def", "move_safe", "(", "origin", ",", "target", ")", ":", "if", "origin", "==", "target", ":", "return", "origin", "if", "file_exists", "(", "target", ")", ":", "return", "target", "shutil", ".", "move", "(", "origin", ",", "target", ")", "return", "...
Move file, skip if exists
[ "Move", "file", "skip", "if", "exists" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L315-L324
237,511
bcbio/bcbio-nextgen
bcbio/utils.py
file_plus_index
def file_plus_index(fname): """Convert a file name into the file plus required indexes. """ exts = {".vcf": ".idx", ".bam": ".bai", ".vcf.gz": ".tbi", ".bed.gz": ".tbi", ".fq.gz": ".gbi"} ext = splitext_plus(fname)[-1] if ext in exts: return [fname, fname + exts[ext]] else: return [fname]
python
def file_plus_index(fname): exts = {".vcf": ".idx", ".bam": ".bai", ".vcf.gz": ".tbi", ".bed.gz": ".tbi", ".fq.gz": ".gbi"} ext = splitext_plus(fname)[-1] if ext in exts: return [fname, fname + exts[ext]] else: return [fname]
[ "def", "file_plus_index", "(", "fname", ")", ":", "exts", "=", "{", "\".vcf\"", ":", "\".idx\"", ",", "\".bam\"", ":", "\".bai\"", ",", "\".vcf.gz\"", ":", "\".tbi\"", ",", "\".bed.gz\"", ":", "\".tbi\"", ",", "\".fq.gz\"", ":", "\".gbi\"", "}", "ext", "="...
Convert a file name into the file plus required indexes.
[ "Convert", "a", "file", "name", "into", "the", "file", "plus", "required", "indexes", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L326-L335
237,512
bcbio/bcbio-nextgen
bcbio/utils.py
remove_plus
def remove_plus(orig): """Remove a fils, including biological index files. """ for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]: if os.path.exists(orig + ext): remove_safe(orig + ext)
python
def remove_plus(orig): for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]: if os.path.exists(orig + ext): remove_safe(orig + ext)
[ "def", "remove_plus", "(", "orig", ")", ":", "for", "ext", "in", "[", "\"\"", ",", "\".idx\"", ",", "\".gbi\"", ",", "\".tbi\"", ",", "\".bai\"", "]", ":", "if", "os", ".", "path", ".", "exists", "(", "orig", "+", "ext", ")", ":", "remove_safe", "(...
Remove a fils, including biological index files.
[ "Remove", "a", "fils", "including", "biological", "index", "files", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L337-L342
237,513
bcbio/bcbio-nextgen
bcbio/utils.py
copy_plus
def copy_plus(orig, new): """Copy a fils, including biological index files. """ for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]: if os.path.exists(orig + ext) and (not os.path.lexists(new + ext) or not os.path.exists(new + ext)): shutil.copyfile(orig + ext, new + ext)
python
def copy_plus(orig, new): for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]: if os.path.exists(orig + ext) and (not os.path.lexists(new + ext) or not os.path.exists(new + ext)): shutil.copyfile(orig + ext, new + ext)
[ "def", "copy_plus", "(", "orig", ",", "new", ")", ":", "for", "ext", "in", "[", "\"\"", ",", "\".idx\"", ",", "\".gbi\"", ",", "\".tbi\"", ",", "\".bai\"", "]", ":", "if", "os", ".", "path", ".", "exists", "(", "orig", "+", "ext", ")", "and", "("...
Copy a fils, including biological index files.
[ "Copy", "a", "fils", "including", "biological", "index", "files", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L344-L349
237,514
bcbio/bcbio-nextgen
bcbio/utils.py
merge_config_files
def merge_config_files(fnames): """Merge configuration files, preferring definitions in latter files. """ def _load_yaml(fname): with open(fname) as in_handle: config = yaml.safe_load(in_handle) return config out = _load_yaml(fnames[0]) for fname in fnames[1:]: cur = _load_yaml(fname) for k, v in cur.items(): if k in out and isinstance(out[k], dict): out[k].update(v) else: out[k] = v return out
python
def merge_config_files(fnames): def _load_yaml(fname): with open(fname) as in_handle: config = yaml.safe_load(in_handle) return config out = _load_yaml(fnames[0]) for fname in fnames[1:]: cur = _load_yaml(fname) for k, v in cur.items(): if k in out and isinstance(out[k], dict): out[k].update(v) else: out[k] = v return out
[ "def", "merge_config_files", "(", "fnames", ")", ":", "def", "_load_yaml", "(", "fname", ")", ":", "with", "open", "(", "fname", ")", "as", "in_handle", ":", "config", "=", "yaml", ".", "safe_load", "(", "in_handle", ")", "return", "config", "out", "=", ...
Merge configuration files, preferring definitions in latter files.
[ "Merge", "configuration", "files", "preferring", "definitions", "in", "latter", "files", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L475-L490
237,515
bcbio/bcbio-nextgen
bcbio/utils.py
deepish_copy
def deepish_copy(org): """Improved speed deep copy for dictionaries of simple python types. Thanks to Gregg Lind: http://writeonly.wordpress.com/2009/05/07/deepcopy-is-a-pig-for-simple-data/ """ out = dict().fromkeys(org) for k, v in org.items(): if isinstance(v, dict): out[k] = deepish_copy(v) else: try: out[k] = v.copy() # dicts, sets except AttributeError: try: out[k] = v[:] # lists, tuples, strings, unicode except TypeError: out[k] = v # ints return out
python
def deepish_copy(org): out = dict().fromkeys(org) for k, v in org.items(): if isinstance(v, dict): out[k] = deepish_copy(v) else: try: out[k] = v.copy() # dicts, sets except AttributeError: try: out[k] = v[:] # lists, tuples, strings, unicode except TypeError: out[k] = v # ints return out
[ "def", "deepish_copy", "(", "org", ")", ":", "out", "=", "dict", "(", ")", ".", "fromkeys", "(", "org", ")", "for", "k", ",", "v", "in", "org", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "out", "[", "k",...
Improved speed deep copy for dictionaries of simple python types. Thanks to Gregg Lind: http://writeonly.wordpress.com/2009/05/07/deepcopy-is-a-pig-for-simple-data/
[ "Improved", "speed", "deep", "copy", "for", "dictionaries", "of", "simple", "python", "types", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L492-L510
237,516
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): 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
237,517
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): 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
237,518
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(): 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
237,519
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): 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
237,520
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): 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
237,521
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(): 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
237,522
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(): 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
237,523
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): 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
237,524
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(): 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
237,525
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): 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
237,526
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): 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
237,527
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): 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
237,528
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): 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
237,529
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): 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
237,530
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): 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
237,531
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): 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
237,532
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): 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
237,533
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): 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
237,534
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): 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
237,535
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): 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
237,536
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): 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
237,537
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): 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
237,538
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): 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
237,539
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): 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
237,540
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): 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
237,541
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): 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
237,542
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): 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
237,543
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): 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
237,544
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): 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
237,545
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): 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
237,546
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): 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
237,547
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): 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
237,548
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): # 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
237,549
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): 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
237,550
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): 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
237,551
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): 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
237,552
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): 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
237,553
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): 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
237,554
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): 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
237,555
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): 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
237,556
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): 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
237,557
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): 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
237,558
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): 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
237,559
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): 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
237,560
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): 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
237,561
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): # 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
237,562
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): 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
237,563
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): 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
237,564
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): 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
237,565
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): 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
237,566
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=''): # 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
237,567
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): 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
237,568
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): 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
237,569
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): 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
237,570
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): 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
237,571
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): 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
237,572
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): 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
237,573
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): 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
237,574
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): 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
237,575
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): 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
237,576
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): 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
237,577
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): 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
237,578
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): 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
237,579
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): 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
237,580
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): 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
237,581
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): 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
237,582
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): 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
237,583
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): 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
237,584
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): 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
237,585
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): 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
237,586
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): 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
237,587
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): 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
237,588
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): 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
237,589
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): 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
237,590
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): 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
237,591
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): 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
237,592
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): 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
237,593
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): # 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
237,594
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): 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
237,595
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): #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
237,596
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): 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
237,597
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): 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
237,598
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): 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
237,599
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): 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