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
224,400
google/tangent
tangent/transformers.py
TreeTransformer.prepend
def prepend(self, node): """Prepend a statement to the current statement. Note that multiple calls to prepend will result in the last statement to be prepended to end up at the top. Args: node: The statement to prepend. Raises: ValueError: If the given node is not a statement. """ if not isinstance(node, grammar.STATEMENTS): raise ValueError self.to_prepend[-1].appendleft(node)
python
def prepend(self, node): if not isinstance(node, grammar.STATEMENTS): raise ValueError self.to_prepend[-1].appendleft(node)
[ "def", "prepend", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "grammar", ".", "STATEMENTS", ")", ":", "raise", "ValueError", "self", ".", "to_prepend", "[", "-", "1", "]", ".", "appendleft", "(", "node", ")" ]
Prepend a statement to the current statement. Note that multiple calls to prepend will result in the last statement to be prepended to end up at the top. Args: node: The statement to prepend. Raises: ValueError: If the given node is not a statement.
[ "Prepend", "a", "statement", "to", "the", "current", "statement", "." ]
6533e83af09de7345d1b438512679992f080dcc9
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/transformers.py#L64-L79
224,401
google/tangent
tangent/transformers.py
TreeTransformer.append
def append(self, node): """Append a statement to the current statement. Note that multiple calls to append will result in the last statement to be appended to end up at the bottom. Args: node: The statement to append. Raises: ValueError: If the given node is not a statement. """ if not isinstance(node, grammar.STATEMENTS): raise ValueError self.to_append[-1].append(node)
python
def append(self, node): if not isinstance(node, grammar.STATEMENTS): raise ValueError self.to_append[-1].append(node)
[ "def", "append", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "grammar", ".", "STATEMENTS", ")", ":", "raise", "ValueError", "self", ".", "to_append", "[", "-", "1", "]", ".", "append", "(", "node", ")" ]
Append a statement to the current statement. Note that multiple calls to append will result in the last statement to be appended to end up at the bottom. Args: node: The statement to append. Raises: ValueError: If the given node is not a statement.
[ "Append", "a", "statement", "to", "the", "current", "statement", "." ]
6533e83af09de7345d1b438512679992f080dcc9
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/transformers.py#L81-L96
224,402
google/tangent
tangent/transformers.py
TreeTransformer.insert_top
def insert_top(self, node): """Insert statements at the top of the function body. Note that multiple calls to `insert_top` will result in the statements being prepended in that order; this is different behavior from `prepend`. Args: node: The statement to prepend. Raises: ValueError: If the given node is not a statement. """ if not isinstance(node, grammar.STATEMENTS): raise ValueError self.to_insert_top.append(node)
python
def insert_top(self, node): if not isinstance(node, grammar.STATEMENTS): raise ValueError self.to_insert_top.append(node)
[ "def", "insert_top", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "grammar", ".", "STATEMENTS", ")", ":", "raise", "ValueError", "self", ".", "to_insert_top", ".", "append", "(", "node", ")" ]
Insert statements at the top of the function body. Note that multiple calls to `insert_top` will result in the statements being prepended in that order; this is different behavior from `prepend`. Args: node: The statement to prepend. Raises: ValueError: If the given node is not a statement.
[ "Insert", "statements", "at", "the", "top", "of", "the", "function", "body", "." ]
6533e83af09de7345d1b438512679992f080dcc9
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/transformers.py#L102-L117
224,403
google/tangent
tangent/transformers.py
TreeTransformer.prepend_block
def prepend_block(self, node, reverse=False): """Prepend a statement to the current block. Args: node: The statement to prepend. reverse: When called multiple times, this flag determines whether the statement should be prepended or appended to the already inserted statements. Raises: ValueError: If the given node is not a statement. """ if not isinstance(node, grammar.STATEMENTS): raise ValueError if reverse: self.to_prepend_block[-1].appendleft(node) else: self.to_prepend_block[-1].append(node)
python
def prepend_block(self, node, reverse=False): if not isinstance(node, grammar.STATEMENTS): raise ValueError if reverse: self.to_prepend_block[-1].appendleft(node) else: self.to_prepend_block[-1].append(node)
[ "def", "prepend_block", "(", "self", ",", "node", ",", "reverse", "=", "False", ")", ":", "if", "not", "isinstance", "(", "node", ",", "grammar", ".", "STATEMENTS", ")", ":", "raise", "ValueError", "if", "reverse", ":", "self", ".", "to_prepend_block", "...
Prepend a statement to the current block. Args: node: The statement to prepend. reverse: When called multiple times, this flag determines whether the statement should be prepended or appended to the already inserted statements. Raises: ValueError: If the given node is not a statement.
[ "Prepend", "a", "statement", "to", "the", "current", "block", "." ]
6533e83af09de7345d1b438512679992f080dcc9
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/transformers.py#L119-L137
224,404
google/tangent
tangent/transformers.py
TreeTransformer.append_block
def append_block(self, node, reverse=False): """Append a statement to the current block. Args: node: The statement to prepend. reverse: When called multiple times, this flag determines whether the statement should be prepended or appended to the already inserted statements. Raises: ValueError: If the given node is not a statement. """ if not isinstance(node, grammar.STATEMENTS): raise ValueError if reverse: self.to_append_block[-1].appendleft(node) else: self.to_append_block[-1].append(node)
python
def append_block(self, node, reverse=False): if not isinstance(node, grammar.STATEMENTS): raise ValueError if reverse: self.to_append_block[-1].appendleft(node) else: self.to_append_block[-1].append(node)
[ "def", "append_block", "(", "self", ",", "node", ",", "reverse", "=", "False", ")", ":", "if", "not", "isinstance", "(", "node", ",", "grammar", ".", "STATEMENTS", ")", ":", "raise", "ValueError", "if", "reverse", ":", "self", ".", "to_append_block", "["...
Append a statement to the current block. Args: node: The statement to prepend. reverse: When called multiple times, this flag determines whether the statement should be prepended or appended to the already inserted statements. Raises: ValueError: If the given node is not a statement.
[ "Append", "a", "statement", "to", "the", "current", "block", "." ]
6533e83af09de7345d1b438512679992f080dcc9
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/transformers.py#L139-L157
224,405
google/tangent
tangent/transformers.py
TreeTransformer.visit_statements
def visit_statements(self, nodes): """Visit a series of nodes in a node body. This function is factored out so that it can be called recursively on statements that are appended or prepended. This allows e.g. a nested expression to prepend a statement, and that statement can prepend a statement again, etc. Args: nodes: A list of statements. Returns: A list of transformed statements. """ for node in nodes: if isinstance(node, gast.AST): self.to_prepend.append(deque()) self.to_append.append(deque()) node = self.visit(node) self.visit_statements(self.to_prepend.pop()) if isinstance(node, gast.AST): self.to_insert[-1].append(node) elif node: self.to_insert[-1].extend(node) self.visit_statements(self.to_append.pop()) else: self.to_insert[-1].append(node) return self.to_insert[-1]
python
def visit_statements(self, nodes): for node in nodes: if isinstance(node, gast.AST): self.to_prepend.append(deque()) self.to_append.append(deque()) node = self.visit(node) self.visit_statements(self.to_prepend.pop()) if isinstance(node, gast.AST): self.to_insert[-1].append(node) elif node: self.to_insert[-1].extend(node) self.visit_statements(self.to_append.pop()) else: self.to_insert[-1].append(node) return self.to_insert[-1]
[ "def", "visit_statements", "(", "self", ",", "nodes", ")", ":", "for", "node", "in", "nodes", ":", "if", "isinstance", "(", "node", ",", "gast", ".", "AST", ")", ":", "self", ".", "to_prepend", ".", "append", "(", "deque", "(", ")", ")", "self", "....
Visit a series of nodes in a node body. This function is factored out so that it can be called recursively on statements that are appended or prepended. This allows e.g. a nested expression to prepend a statement, and that statement can prepend a statement again, etc. Args: nodes: A list of statements. Returns: A list of transformed statements.
[ "Visit", "a", "series", "of", "nodes", "in", "a", "node", "body", "." ]
6533e83af09de7345d1b438512679992f080dcc9
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/transformers.py#L159-L186
224,406
google/tangent
tangent/annotate.py
resolve_calls
def resolve_calls(func): """Parse a function into an AST with function calls resolved. Since the calls are resolved using the global and local namespace of the function it means that procedural parameters (i.e. functions passed as arguments) won't be resolved. Similarly, functions defined inside of the function that we are trying to resolve won't be resolved, since they are not in the local namespace of the outer function. The function definition itself is also annotated, so that it can be matched to calls to it in other functions. Args: func: The function whose calls are being resolved. Returns: node: An AST where each `Call` node has a `func` annotation with the function handle that the call resolves to. Raises: AttributeError: When a function is used on the RHS of an assignment cannot be resolved (because it was passed as an argument or was defined in the body of the function). """ node = quoting.parse_function(func) ResolveCalls(func).visit(node) return node
python
def resolve_calls(func): node = quoting.parse_function(func) ResolveCalls(func).visit(node) return node
[ "def", "resolve_calls", "(", "func", ")", ":", "node", "=", "quoting", ".", "parse_function", "(", "func", ")", "ResolveCalls", "(", "func", ")", ".", "visit", "(", "node", ")", "return", "node" ]
Parse a function into an AST with function calls resolved. Since the calls are resolved using the global and local namespace of the function it means that procedural parameters (i.e. functions passed as arguments) won't be resolved. Similarly, functions defined inside of the function that we are trying to resolve won't be resolved, since they are not in the local namespace of the outer function. The function definition itself is also annotated, so that it can be matched to calls to it in other functions. Args: func: The function whose calls are being resolved. Returns: node: An AST where each `Call` node has a `func` annotation with the function handle that the call resolves to. Raises: AttributeError: When a function is used on the RHS of an assignment cannot be resolved (because it was passed as an argument or was defined in the body of the function).
[ "Parse", "a", "function", "into", "an", "AST", "with", "function", "calls", "resolved", "." ]
6533e83af09de7345d1b438512679992f080dcc9
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/annotate.py#L83-L111
224,407
google/tangent
tangent/annotate.py
find_stacks
def find_stacks(node, strict=False): """Find pushes and pops to the stack and annotate them as such. Args: node: An AST node that might contain stack pushes and pops. strict: A boolean indicating whether to stringently test whether each push and pop are matched. This is not always possible when taking higher-order derivatives of code generated in split-motion. Returns: node: The node passed in, but with pushes and pops annotated in AST nodes. """ # First, find all stack operation IDs. fso = FindStackOps() fso.visit(node) # Using those IDs, make annotations onto the push and pop nodes. AnnotateStacks(fso.push_pop_pairs, strict).visit(node) return node
python
def find_stacks(node, strict=False): # First, find all stack operation IDs. fso = FindStackOps() fso.visit(node) # Using those IDs, make annotations onto the push and pop nodes. AnnotateStacks(fso.push_pop_pairs, strict).visit(node) return node
[ "def", "find_stacks", "(", "node", ",", "strict", "=", "False", ")", ":", "# First, find all stack operation IDs.", "fso", "=", "FindStackOps", "(", ")", "fso", ".", "visit", "(", "node", ")", "# Using those IDs, make annotations onto the push and pop nodes.", "Annotate...
Find pushes and pops to the stack and annotate them as such. Args: node: An AST node that might contain stack pushes and pops. strict: A boolean indicating whether to stringently test whether each push and pop are matched. This is not always possible when taking higher-order derivatives of code generated in split-motion. Returns: node: The node passed in, but with pushes and pops annotated in AST nodes.
[ "Find", "pushes", "and", "pops", "to", "the", "stack", "and", "annotate", "them", "as", "such", "." ]
6533e83af09de7345d1b438512679992f080dcc9
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/annotate.py#L245-L262
224,408
google/tangent
tangent/annotate.py
unused
def unused(node): """Find unused definitions that can be remove. This runs reaching definitions analysis followed by a walk over the AST to find all variable definitions that are not used later on. Args: node: The AST of e.g. a function body to find unused variable definitions. Returns: unused: After visiting all the nodes, this attribute contanis a set of definitions in the form of `(variable_name, node)` pairs which are unused in this AST. """ cfg.forward(node, cfg.ReachingDefinitions()) unused_obj = Unused() unused_obj.visit(node) return unused_obj.unused
python
def unused(node): cfg.forward(node, cfg.ReachingDefinitions()) unused_obj = Unused() unused_obj.visit(node) return unused_obj.unused
[ "def", "unused", "(", "node", ")", ":", "cfg", ".", "forward", "(", "node", ",", "cfg", ".", "ReachingDefinitions", "(", ")", ")", "unused_obj", "=", "Unused", "(", ")", "unused_obj", ".", "visit", "(", "node", ")", "return", "unused_obj", ".", "unused...
Find unused definitions that can be remove. This runs reaching definitions analysis followed by a walk over the AST to find all variable definitions that are not used later on. Args: node: The AST of e.g. a function body to find unused variable definitions. Returns: unused: After visiting all the nodes, this attribute contanis a set of definitions in the form of `(variable_name, node)` pairs which are unused in this AST.
[ "Find", "unused", "definitions", "that", "can", "be", "remove", "." ]
6533e83af09de7345d1b438512679992f080dcc9
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/annotate.py#L304-L321
224,409
google/tangent
tangent/annotate.py
Unused.unused
def unused(self): """Calculate which AST nodes are unused. Note that we have to take special care in the case of x,y = f(z) where x is used later, but y is not.""" unused = self.definitions - self.used # Filter (variable_name,node) pairs that should be removed, because # node is used elsewhere used_nodes = set([u[1] for u in self.used]) unused = set([u for u in unused if u[1] not in used_nodes]) return unused
python
def unused(self): unused = self.definitions - self.used # Filter (variable_name,node) pairs that should be removed, because # node is used elsewhere used_nodes = set([u[1] for u in self.used]) unused = set([u for u in unused if u[1] not in used_nodes]) return unused
[ "def", "unused", "(", "self", ")", ":", "unused", "=", "self", ".", "definitions", "-", "self", ".", "used", "# Filter (variable_name,node) pairs that should be removed, because", "# node is used elsewhere", "used_nodes", "=", "set", "(", "[", "u", "[", "1", "]", ...
Calculate which AST nodes are unused. Note that we have to take special care in the case of x,y = f(z) where x is used later, but y is not.
[ "Calculate", "which", "AST", "nodes", "are", "unused", "." ]
6533e83af09de7345d1b438512679992f080dcc9
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/annotate.py#L280-L290
224,410
sirfz/tesserocr
setup.py
package_config
def package_config(): """Use pkg-config to get library build parameters and tesseract version.""" p = subprocess.Popen(['pkg-config', '--exists', '--atleast-version={}'.format(_TESSERACT_MIN_VERSION), '--print-errors', 'tesseract'], stderr=subprocess.PIPE) _, error = p.communicate() if p.returncode != 0: raise Exception(error) p = subprocess.Popen(['pkg-config', '--libs', '--cflags', 'tesseract'], stdout=subprocess.PIPE) output, _ = p.communicate() flags = _read_string(output).strip().split() p = subprocess.Popen(['pkg-config', '--libs', '--cflags', 'lept'], stdout=subprocess.PIPE) output, _ = p.communicate() flags2 = _read_string(output).strip().split() options = {'-L': 'library_dirs', '-I': 'include_dirs', '-l': 'libraries'} config = {} import itertools for f in itertools.chain(flags, flags2): try: opt = options[f[:2]] except KeyError: continue val = f[2:] if opt == 'include_dirs' and psplit(val)[1].strip(os.sep) in ('leptonica', 'tesseract'): val = dirname(val) config.setdefault(opt, set()).add(val) config = {k: list(v) for k, v in config.items()} p = subprocess.Popen(['pkg-config', '--modversion', 'tesseract'], stdout=subprocess.PIPE) version, _ = p.communicate() version = _read_string(version).strip() _LOGGER.info("Supporting tesseract v{}".format(version)) config['cython_compile_time_env'] = {'TESSERACT_VERSION': version_to_int(version)} _LOGGER.info("Configs from pkg-config: {}".format(config)) return config
python
def package_config(): p = subprocess.Popen(['pkg-config', '--exists', '--atleast-version={}'.format(_TESSERACT_MIN_VERSION), '--print-errors', 'tesseract'], stderr=subprocess.PIPE) _, error = p.communicate() if p.returncode != 0: raise Exception(error) p = subprocess.Popen(['pkg-config', '--libs', '--cflags', 'tesseract'], stdout=subprocess.PIPE) output, _ = p.communicate() flags = _read_string(output).strip().split() p = subprocess.Popen(['pkg-config', '--libs', '--cflags', 'lept'], stdout=subprocess.PIPE) output, _ = p.communicate() flags2 = _read_string(output).strip().split() options = {'-L': 'library_dirs', '-I': 'include_dirs', '-l': 'libraries'} config = {} import itertools for f in itertools.chain(flags, flags2): try: opt = options[f[:2]] except KeyError: continue val = f[2:] if opt == 'include_dirs' and psplit(val)[1].strip(os.sep) in ('leptonica', 'tesseract'): val = dirname(val) config.setdefault(opt, set()).add(val) config = {k: list(v) for k, v in config.items()} p = subprocess.Popen(['pkg-config', '--modversion', 'tesseract'], stdout=subprocess.PIPE) version, _ = p.communicate() version = _read_string(version).strip() _LOGGER.info("Supporting tesseract v{}".format(version)) config['cython_compile_time_env'] = {'TESSERACT_VERSION': version_to_int(version)} _LOGGER.info("Configs from pkg-config: {}".format(config)) return config
[ "def", "package_config", "(", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "'pkg-config'", ",", "'--exists'", ",", "'--atleast-version={}'", ".", "format", "(", "_TESSERACT_MIN_VERSION", ")", ",", "'--print-errors'", ",", "'tesseract'", "]", ",", ...
Use pkg-config to get library build parameters and tesseract version.
[ "Use", "pkg", "-", "config", "to", "get", "library", "build", "parameters", "and", "tesseract", "version", "." ]
052fb5d7d4e1398c8a07958b389b37e1090fb897
https://github.com/sirfz/tesserocr/blob/052fb5d7d4e1398c8a07958b389b37e1090fb897/setup.py#L80-L115
224,411
sirfz/tesserocr
setup.py
get_tesseract_version
def get_tesseract_version(): """Try to extract version from tesseract otherwise default min version.""" config = {'libraries': ['tesseract', 'lept']} try: p = subprocess.Popen(['tesseract', '-v'], stderr=subprocess.PIPE, stdout=subprocess.PIPE) stdout_version, version = p.communicate() version = _read_string(version).strip() if version == '': version = _read_string(stdout_version).strip() version_match = re.search(r'^tesseract ((?:\d+\.)+\d+).*', version, re.M) if version_match: version = version_match.group(1) else: _LOGGER.warn('Failed to extract tesseract version number from: {}'.format(version)) version = _TESSERACT_MIN_VERSION except OSError as e: _LOGGER.warn('Failed to extract tesseract version from executable: {}'.format(e)) version = _TESSERACT_MIN_VERSION _LOGGER.info("Supporting tesseract v{}".format(version)) version = version_to_int(version) config['cython_compile_time_env'] = {'TESSERACT_VERSION': version} _LOGGER.info("Building with configs: {}".format(config)) return config
python
def get_tesseract_version(): config = {'libraries': ['tesseract', 'lept']} try: p = subprocess.Popen(['tesseract', '-v'], stderr=subprocess.PIPE, stdout=subprocess.PIPE) stdout_version, version = p.communicate() version = _read_string(version).strip() if version == '': version = _read_string(stdout_version).strip() version_match = re.search(r'^tesseract ((?:\d+\.)+\d+).*', version, re.M) if version_match: version = version_match.group(1) else: _LOGGER.warn('Failed to extract tesseract version number from: {}'.format(version)) version = _TESSERACT_MIN_VERSION except OSError as e: _LOGGER.warn('Failed to extract tesseract version from executable: {}'.format(e)) version = _TESSERACT_MIN_VERSION _LOGGER.info("Supporting tesseract v{}".format(version)) version = version_to_int(version) config['cython_compile_time_env'] = {'TESSERACT_VERSION': version} _LOGGER.info("Building with configs: {}".format(config)) return config
[ "def", "get_tesseract_version", "(", ")", ":", "config", "=", "{", "'libraries'", ":", "[", "'tesseract'", ",", "'lept'", "]", "}", "try", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "'tesseract'", ",", "'-v'", "]", ",", "stderr", "=", "subpro...
Try to extract version from tesseract otherwise default min version.
[ "Try", "to", "extract", "version", "from", "tesseract", "otherwise", "default", "min", "version", "." ]
052fb5d7d4e1398c8a07958b389b37e1090fb897
https://github.com/sirfz/tesserocr/blob/052fb5d7d4e1398c8a07958b389b37e1090fb897/setup.py#L118-L140
224,412
sirfz/tesserocr
setup.py
get_build_args
def get_build_args(): """Return proper build parameters.""" try: build_args = package_config() except Exception as e: if isinstance(e, OSError): if e.errno != errno.ENOENT: _LOGGER.warn('Failed to run pkg-config: {}'.format(e)) else: _LOGGER.warn('pkg-config failed to find tesseract/lept libraries: {}'.format(e)) build_args = get_tesseract_version() if build_args['cython_compile_time_env']['TESSERACT_VERSION'] >= 0x3050200: _LOGGER.debug('tesseract >= 03.05.02 requires c++11 compiler support') build_args['extra_compile_args'] = ['-std=c++11', '-DUSE_STD_NAMESPACE'] _LOGGER.debug('build parameters: {}'.format(build_args)) return build_args
python
def get_build_args(): try: build_args = package_config() except Exception as e: if isinstance(e, OSError): if e.errno != errno.ENOENT: _LOGGER.warn('Failed to run pkg-config: {}'.format(e)) else: _LOGGER.warn('pkg-config failed to find tesseract/lept libraries: {}'.format(e)) build_args = get_tesseract_version() if build_args['cython_compile_time_env']['TESSERACT_VERSION'] >= 0x3050200: _LOGGER.debug('tesseract >= 03.05.02 requires c++11 compiler support') build_args['extra_compile_args'] = ['-std=c++11', '-DUSE_STD_NAMESPACE'] _LOGGER.debug('build parameters: {}'.format(build_args)) return build_args
[ "def", "get_build_args", "(", ")", ":", "try", ":", "build_args", "=", "package_config", "(", ")", "except", "Exception", "as", "e", ":", "if", "isinstance", "(", "e", ",", "OSError", ")", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", "...
Return proper build parameters.
[ "Return", "proper", "build", "parameters", "." ]
052fb5d7d4e1398c8a07958b389b37e1090fb897
https://github.com/sirfz/tesserocr/blob/052fb5d7d4e1398c8a07958b389b37e1090fb897/setup.py#L143-L160
224,413
ewels/MultiQC
multiqc/modules/star/star.py
MultiqcModule.parse_star_report
def parse_star_report (self, raw_data): """ Parse the final STAR log file. """ regexes = { 'total_reads': r"Number of input reads \|\s+(\d+)", 'avg_input_read_length': r"Average input read length \|\s+([\d\.]+)", 'uniquely_mapped': r"Uniquely mapped reads number \|\s+(\d+)", 'uniquely_mapped_percent': r"Uniquely mapped reads % \|\s+([\d\.]+)", 'avg_mapped_read_length': r"Average mapped length \|\s+([\d\.]+)", 'num_splices': r"Number of splices: Total \|\s+(\d+)", 'num_annotated_splices': r"Number of splices: Annotated \(sjdb\) \|\s+(\d+)", 'num_GTAG_splices': r"Number of splices: GT/AG \|\s+(\d+)", 'num_GCAG_splices': r"Number of splices: GC/AG \|\s+(\d+)", 'num_ATAC_splices': r"Number of splices: AT/AC \|\s+(\d+)", 'num_noncanonical_splices': r"Number of splices: Non-canonical \|\s+(\d+)", 'mismatch_rate': r"Mismatch rate per base, % \|\s+([\d\.]+)", 'deletion_rate': r"Deletion rate per base \|\s+([\d\.]+)", 'deletion_length': r"Deletion average length \|\s+([\d\.]+)", 'insertion_rate': r"Insertion rate per base \|\s+([\d\.]+)", 'insertion_length': r"Insertion average length \|\s+([\d\.]+)", 'multimapped': r"Number of reads mapped to multiple loci \|\s+(\d+)", 'multimapped_percent': r"% of reads mapped to multiple loci \|\s+([\d\.]+)", 'multimapped_toomany': r"Number of reads mapped to too many loci \|\s+(\d+)", 'multimapped_toomany_percent': r"% of reads mapped to too many loci \|\s+([\d\.]+)", 'unmapped_mismatches_percent': r"% of reads unmapped: too many mismatches \|\s+([\d\.]+)", 'unmapped_tooshort_percent': r"% of reads unmapped: too short \|\s+([\d\.]+)", 'unmapped_other_percent': r"% of reads unmapped: other \|\s+([\d\.]+)", } parsed_data = {} for k, r in regexes.items(): r_search = re.search(r, raw_data, re.MULTILINE) if r_search: parsed_data[k] = float(r_search.group(1)) # Figure out the numbers for unmapped as for some reason only the percentages are given try: total_mapped = parsed_data['uniquely_mapped'] + parsed_data['multimapped'] + parsed_data['multimapped_toomany'] unmapped_count = parsed_data['total_reads'] - total_mapped total_unmapped_percent = parsed_data['unmapped_mismatches_percent'] + parsed_data['unmapped_tooshort_percent'] + parsed_data['unmapped_other_percent'] try: parsed_data['unmapped_mismatches'] = int(round(unmapped_count * (parsed_data['unmapped_mismatches_percent'] / total_unmapped_percent), 0)) parsed_data['unmapped_tooshort'] = int(round(unmapped_count * (parsed_data['unmapped_tooshort_percent'] / total_unmapped_percent), 0)) parsed_data['unmapped_other'] = int(round(unmapped_count * (parsed_data['unmapped_other_percent'] / total_unmapped_percent), 0)) except ZeroDivisionError: parsed_data['unmapped_mismatches'] = 0 parsed_data['unmapped_tooshort'] = 0 parsed_data['unmapped_other'] = 0 except KeyError: pass if len(parsed_data) == 0: return None return parsed_data
python
def parse_star_report (self, raw_data): regexes = { 'total_reads': r"Number of input reads \|\s+(\d+)", 'avg_input_read_length': r"Average input read length \|\s+([\d\.]+)", 'uniquely_mapped': r"Uniquely mapped reads number \|\s+(\d+)", 'uniquely_mapped_percent': r"Uniquely mapped reads % \|\s+([\d\.]+)", 'avg_mapped_read_length': r"Average mapped length \|\s+([\d\.]+)", 'num_splices': r"Number of splices: Total \|\s+(\d+)", 'num_annotated_splices': r"Number of splices: Annotated \(sjdb\) \|\s+(\d+)", 'num_GTAG_splices': r"Number of splices: GT/AG \|\s+(\d+)", 'num_GCAG_splices': r"Number of splices: GC/AG \|\s+(\d+)", 'num_ATAC_splices': r"Number of splices: AT/AC \|\s+(\d+)", 'num_noncanonical_splices': r"Number of splices: Non-canonical \|\s+(\d+)", 'mismatch_rate': r"Mismatch rate per base, % \|\s+([\d\.]+)", 'deletion_rate': r"Deletion rate per base \|\s+([\d\.]+)", 'deletion_length': r"Deletion average length \|\s+([\d\.]+)", 'insertion_rate': r"Insertion rate per base \|\s+([\d\.]+)", 'insertion_length': r"Insertion average length \|\s+([\d\.]+)", 'multimapped': r"Number of reads mapped to multiple loci \|\s+(\d+)", 'multimapped_percent': r"% of reads mapped to multiple loci \|\s+([\d\.]+)", 'multimapped_toomany': r"Number of reads mapped to too many loci \|\s+(\d+)", 'multimapped_toomany_percent': r"% of reads mapped to too many loci \|\s+([\d\.]+)", 'unmapped_mismatches_percent': r"% of reads unmapped: too many mismatches \|\s+([\d\.]+)", 'unmapped_tooshort_percent': r"% of reads unmapped: too short \|\s+([\d\.]+)", 'unmapped_other_percent': r"% of reads unmapped: other \|\s+([\d\.]+)", } parsed_data = {} for k, r in regexes.items(): r_search = re.search(r, raw_data, re.MULTILINE) if r_search: parsed_data[k] = float(r_search.group(1)) # Figure out the numbers for unmapped as for some reason only the percentages are given try: total_mapped = parsed_data['uniquely_mapped'] + parsed_data['multimapped'] + parsed_data['multimapped_toomany'] unmapped_count = parsed_data['total_reads'] - total_mapped total_unmapped_percent = parsed_data['unmapped_mismatches_percent'] + parsed_data['unmapped_tooshort_percent'] + parsed_data['unmapped_other_percent'] try: parsed_data['unmapped_mismatches'] = int(round(unmapped_count * (parsed_data['unmapped_mismatches_percent'] / total_unmapped_percent), 0)) parsed_data['unmapped_tooshort'] = int(round(unmapped_count * (parsed_data['unmapped_tooshort_percent'] / total_unmapped_percent), 0)) parsed_data['unmapped_other'] = int(round(unmapped_count * (parsed_data['unmapped_other_percent'] / total_unmapped_percent), 0)) except ZeroDivisionError: parsed_data['unmapped_mismatches'] = 0 parsed_data['unmapped_tooshort'] = 0 parsed_data['unmapped_other'] = 0 except KeyError: pass if len(parsed_data) == 0: return None return parsed_data
[ "def", "parse_star_report", "(", "self", ",", "raw_data", ")", ":", "regexes", "=", "{", "'total_reads'", ":", "r\"Number of input reads \\|\\s+(\\d+)\"", ",", "'avg_input_read_length'", ":", "r\"Average input read length \\|\\s+([\\d\\.]+)\"", ",", "'uniquely_mapped'", ":", ...
Parse the final STAR log file.
[ "Parse", "the", "final", "STAR", "log", "file", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/star/star.py#L100-L150
224,414
ewels/MultiQC
multiqc/modules/star/star.py
MultiqcModule.parse_star_genecount_report
def parse_star_genecount_report(self, f): """ Parse a STAR gene counts output file """ # Three numeric columns: unstranded, stranded/first-strand, stranded/second-strand keys = [ 'N_unmapped', 'N_multimapping', 'N_noFeature', 'N_ambiguous' ] unstranded = { 'N_genes': 0 } first_strand = { 'N_genes': 0 } second_strand = { 'N_genes': 0 } num_errors = 0 num_genes = 0 for l in f['f']: s = l.split("\t") try: for i in [1,2,3]: s[i] = float(s[i]) if s[0] in keys: unstranded[s[0]] = s[1] first_strand[s[0]] = s[2] second_strand[s[0]] = s[3] else: unstranded['N_genes'] += s[1] first_strand['N_genes'] += s[2] second_strand['N_genes'] += s[3] num_genes += 1 except IndexError: # Tolerate a few errors in case there is something random added at the top of the file num_errors += 1 if num_errors > 10 and num_genes == 0: log.warning("Error parsing {}".format(f['fn'])) return None if num_genes > 0: return { 'unstranded': unstranded, 'first_strand': first_strand, 'second_strand': second_strand } else: return None
python
def parse_star_genecount_report(self, f): # Three numeric columns: unstranded, stranded/first-strand, stranded/second-strand keys = [ 'N_unmapped', 'N_multimapping', 'N_noFeature', 'N_ambiguous' ] unstranded = { 'N_genes': 0 } first_strand = { 'N_genes': 0 } second_strand = { 'N_genes': 0 } num_errors = 0 num_genes = 0 for l in f['f']: s = l.split("\t") try: for i in [1,2,3]: s[i] = float(s[i]) if s[0] in keys: unstranded[s[0]] = s[1] first_strand[s[0]] = s[2] second_strand[s[0]] = s[3] else: unstranded['N_genes'] += s[1] first_strand['N_genes'] += s[2] second_strand['N_genes'] += s[3] num_genes += 1 except IndexError: # Tolerate a few errors in case there is something random added at the top of the file num_errors += 1 if num_errors > 10 and num_genes == 0: log.warning("Error parsing {}".format(f['fn'])) return None if num_genes > 0: return { 'unstranded': unstranded, 'first_strand': first_strand, 'second_strand': second_strand } else: return None
[ "def", "parse_star_genecount_report", "(", "self", ",", "f", ")", ":", "# Three numeric columns: unstranded, stranded/first-strand, stranded/second-strand", "keys", "=", "[", "'N_unmapped'", ",", "'N_multimapping'", ",", "'N_noFeature'", ",", "'N_ambiguous'", "]", "unstranded...
Parse a STAR gene counts output file
[ "Parse", "a", "STAR", "gene", "counts", "output", "file" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/star/star.py#L152-L184
224,415
ewels/MultiQC
multiqc/modules/star/star.py
MultiqcModule.star_stats_table
def star_stats_table(self): """ Take the parsed stats from the STAR report and add them to the basic stats table at the top of the report """ headers = OrderedDict() headers['uniquely_mapped_percent'] = { 'title': '% Aligned', 'description': '% Uniquely mapped reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['uniquely_mapped'] = { 'title': '{} Aligned'.format(config.read_count_prefix), 'description': 'Uniquely mapped reads ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } self.general_stats_addcols(self.star_data, headers)
python
def star_stats_table(self): headers = OrderedDict() headers['uniquely_mapped_percent'] = { 'title': '% Aligned', 'description': '% Uniquely mapped reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['uniquely_mapped'] = { 'title': '{} Aligned'.format(config.read_count_prefix), 'description': 'Uniquely mapped reads ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } self.general_stats_addcols(self.star_data, headers)
[ "def", "star_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'uniquely_mapped_percent'", "]", "=", "{", "'title'", ":", "'% Aligned'", ",", "'description'", ":", "'% Uniquely mapped reads'", ",", "'max'", ":", "100"...
Take the parsed stats from the STAR report and add them to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "STAR", "report", "and", "add", "them", "to", "the", "basic", "stats", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/star/star.py#L186-L207
224,416
ewels/MultiQC
multiqc/modules/star/star.py
MultiqcModule.star_genecount_chart
def star_genecount_chart (self): """ Make a plot for the ReadsPerGene output """ # Specify the order of the different possible categories keys = OrderedDict() keys['N_genes'] = { 'color': '#2f7ed8', 'name': 'Overlapping Genes' } keys['N_noFeature'] = { 'color': '#0d233a', 'name': 'No Feature' } keys['N_ambiguous'] = { 'color': '#492970', 'name': 'Ambiguous Features' } keys['N_multimapping'] = { 'color': '#f28f43', 'name': 'Multimapping' } keys['N_unmapped'] = { 'color': '#7f0000', 'name': 'Unmapped' } # Config for the plot pconfig = { 'id': 'star_gene_counts', 'title': 'STAR: Gene Counts', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads', 'data_labels': ['Unstranded','Same Stranded','Reverse Stranded'] } datasets = [ self.star_genecounts_unstranded, self.star_genecounts_first_strand, self.star_genecounts_second_strand ] return bargraph.plot(datasets, [keys,keys,keys,keys], pconfig)
python
def star_genecount_chart (self): # Specify the order of the different possible categories keys = OrderedDict() keys['N_genes'] = { 'color': '#2f7ed8', 'name': 'Overlapping Genes' } keys['N_noFeature'] = { 'color': '#0d233a', 'name': 'No Feature' } keys['N_ambiguous'] = { 'color': '#492970', 'name': 'Ambiguous Features' } keys['N_multimapping'] = { 'color': '#f28f43', 'name': 'Multimapping' } keys['N_unmapped'] = { 'color': '#7f0000', 'name': 'Unmapped' } # Config for the plot pconfig = { 'id': 'star_gene_counts', 'title': 'STAR: Gene Counts', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads', 'data_labels': ['Unstranded','Same Stranded','Reverse Stranded'] } datasets = [ self.star_genecounts_unstranded, self.star_genecounts_first_strand, self.star_genecounts_second_strand ] return bargraph.plot(datasets, [keys,keys,keys,keys], pconfig)
[ "def", "star_genecount_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'N_genes'", "]", "=", "{", "'color'", ":", "'#2f7ed8'", ",", "'name'", ":", "'Overlapping Genes'", "...
Make a plot for the ReadsPerGene output
[ "Make", "a", "plot", "for", "the", "ReadsPerGene", "output" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/star/star.py#L231-L255
224,417
ewels/MultiQC
multiqc/modules/mirtrace/mirtrace.py
MultiqcModule.mirtrace_length_plot
def mirtrace_length_plot(self): """ Generate the miRTrace Read Length Distribution""" data = dict() for s_name in self.length_data: try: data[s_name] = {int(d): int(self.length_data[s_name][d]) for d in self.length_data[s_name]} except KeyError: pass if len(data) == 0: log.debug('No valid data for read length distribution') return None config = { 'id': 'mirtrace_length_plot', 'title': 'miRTrace: Read Length Distribution', 'ylab': 'Read Count', 'xlab': 'Read Lenth (bp)', 'ymin': 0, 'xmin': 0, 'xDecimals': False, 'tt_label': '<b>Read Length (bp) {point.x}</b>: {point.y} Read Count', 'xPlotBands': [ {'from': 40, 'to': 50, 'color': '#ffebd1'}, {'from': 26, 'to': 40, 'color': '#e2f5ff'}, {'from': 18, 'to': 26, 'color': '#e5fce0'}, {'from': 0, 'to': 18, 'color': '#ffffe2'}, ] } return linegraph.plot(data, config)
python
def mirtrace_length_plot(self): data = dict() for s_name in self.length_data: try: data[s_name] = {int(d): int(self.length_data[s_name][d]) for d in self.length_data[s_name]} except KeyError: pass if len(data) == 0: log.debug('No valid data for read length distribution') return None config = { 'id': 'mirtrace_length_plot', 'title': 'miRTrace: Read Length Distribution', 'ylab': 'Read Count', 'xlab': 'Read Lenth (bp)', 'ymin': 0, 'xmin': 0, 'xDecimals': False, 'tt_label': '<b>Read Length (bp) {point.x}</b>: {point.y} Read Count', 'xPlotBands': [ {'from': 40, 'to': 50, 'color': '#ffebd1'}, {'from': 26, 'to': 40, 'color': '#e2f5ff'}, {'from': 18, 'to': 26, 'color': '#e5fce0'}, {'from': 0, 'to': 18, 'color': '#ffffe2'}, ] } return linegraph.plot(data, config)
[ "def", "mirtrace_length_plot", "(", "self", ")", ":", "data", "=", "dict", "(", ")", "for", "s_name", "in", "self", ".", "length_data", ":", "try", ":", "data", "[", "s_name", "]", "=", "{", "int", "(", "d", ")", ":", "int", "(", "self", ".", "le...
Generate the miRTrace Read Length Distribution
[ "Generate", "the", "miRTrace", "Read", "Length", "Distribution" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/mirtrace/mirtrace.py#L241-L271
224,418
ewels/MultiQC
multiqc/modules/mirtrace/mirtrace.py
MultiqcModule.mirtrace_rna_categories
def mirtrace_rna_categories(self): """ Generate the miRTrace RNA Categories""" # Specify the order of the different possible categories keys = OrderedDict() keys['reads_mirna'] = { 'color': '#33a02c', 'name': 'miRNA' } keys['reads_rrna'] = { 'color': '#ff7f00', 'name': 'rRNA' } keys['reads_trna'] = { 'color': '#1f78b4', 'name': 'tRNA' } keys['reads_artifact'] = { 'color': '#fb9a99', 'name': 'Artifact' } keys['reads_unknown'] = { 'color': '#d9d9d9', 'name': 'Unknown' } # Config for the plot config = { 'id': 'mirtrace_rna_categories_plot', 'title': 'miRTrace: RNA Categories', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(self.summary_data, keys, config)
python
def mirtrace_rna_categories(self): # Specify the order of the different possible categories keys = OrderedDict() keys['reads_mirna'] = { 'color': '#33a02c', 'name': 'miRNA' } keys['reads_rrna'] = { 'color': '#ff7f00', 'name': 'rRNA' } keys['reads_trna'] = { 'color': '#1f78b4', 'name': 'tRNA' } keys['reads_artifact'] = { 'color': '#fb9a99', 'name': 'Artifact' } keys['reads_unknown'] = { 'color': '#d9d9d9', 'name': 'Unknown' } # Config for the plot config = { 'id': 'mirtrace_rna_categories_plot', 'title': 'miRTrace: RNA Categories', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(self.summary_data, keys, config)
[ "def", "mirtrace_rna_categories", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'reads_mirna'", "]", "=", "{", "'color'", ":", "'#33a02c'", ",", "'name'", ":", "'miRNA'", "}", ...
Generate the miRTrace RNA Categories
[ "Generate", "the", "miRTrace", "RNA", "Categories" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/mirtrace/mirtrace.py#L275-L294
224,419
ewels/MultiQC
multiqc/modules/mirtrace/mirtrace.py
MultiqcModule.mirtrace_contamination_check
def mirtrace_contamination_check(self): """ Generate the miRTrace Contamination Check""" # A library of 24 colors. Should be enough for this plot color_lib = ['rgb(166,206,227)', 'rgb(31,120,180)', 'rgb(178,223,138)', 'rgb(51,160,44)', 'rgb(251,154,153)', 'rgb(227,26,28)', 'rgb(253,191,111)', 'rgb(255,127,0)', 'rgb(202,178,214)', 'rgb(106,61,154)', 'rgb(255,255,153)', 'rgb(177,89,40)', 'rgb(141,211,199)', 'rgb(255,255,179)', 'rgb(190,186,218)', 'rgb(251,128,114)', 'rgb(128,177,211)', 'rgb(253,180,98)', 'rgb(179,222,105)', 'rgb(252,205,229)', 'rgb(217,217,217)', 'rgb(188,128,189)', 'rgb(204,235,197)', 'rgb(255,237,111)'] idx = 0 # Specify the order of the different possible categories keys = OrderedDict() for clade in self.contamination_data[list(self.contamination_data.keys())[0]]: keys[clade] = { 'color': color_lib[idx], 'name': clade } if idx < 23: idx += 1 else: idx = 0 # Config for the plot config = { 'cpswitch_c_active': False, 'id': 'mirtrace_contamination_check_plot', 'title': 'miRTrace: Contamination Check', 'ylab': '# miRNA detected', 'cpswitch_counts_label': 'Number of detected miRNA' } return bargraph.plot(self.contamination_data, keys, config)
python
def mirtrace_contamination_check(self): # A library of 24 colors. Should be enough for this plot color_lib = ['rgb(166,206,227)', 'rgb(31,120,180)', 'rgb(178,223,138)', 'rgb(51,160,44)', 'rgb(251,154,153)', 'rgb(227,26,28)', 'rgb(253,191,111)', 'rgb(255,127,0)', 'rgb(202,178,214)', 'rgb(106,61,154)', 'rgb(255,255,153)', 'rgb(177,89,40)', 'rgb(141,211,199)', 'rgb(255,255,179)', 'rgb(190,186,218)', 'rgb(251,128,114)', 'rgb(128,177,211)', 'rgb(253,180,98)', 'rgb(179,222,105)', 'rgb(252,205,229)', 'rgb(217,217,217)', 'rgb(188,128,189)', 'rgb(204,235,197)', 'rgb(255,237,111)'] idx = 0 # Specify the order of the different possible categories keys = OrderedDict() for clade in self.contamination_data[list(self.contamination_data.keys())[0]]: keys[clade] = { 'color': color_lib[idx], 'name': clade } if idx < 23: idx += 1 else: idx = 0 # Config for the plot config = { 'cpswitch_c_active': False, 'id': 'mirtrace_contamination_check_plot', 'title': 'miRTrace: Contamination Check', 'ylab': '# miRNA detected', 'cpswitch_counts_label': 'Number of detected miRNA' } return bargraph.plot(self.contamination_data, keys, config)
[ "def", "mirtrace_contamination_check", "(", "self", ")", ":", "# A library of 24 colors. Should be enough for this plot", "color_lib", "=", "[", "'rgb(166,206,227)'", ",", "'rgb(31,120,180)'", ",", "'rgb(178,223,138)'", ",", "'rgb(51,160,44)'", ",", "'rgb(251,154,153)'", ",", ...
Generate the miRTrace Contamination Check
[ "Generate", "the", "miRTrace", "Contamination", "Check" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/mirtrace/mirtrace.py#L298-L324
224,420
ewels/MultiQC
multiqc/modules/mirtrace/mirtrace.py
MultiqcModule.mirtrace_complexity_plot
def mirtrace_complexity_plot(self): """ Generate the miRTrace miRNA Complexity Plot""" data = dict() for s_name in self.complexity_data: try: data[s_name] = {int(self.complexity_data[s_name][d]) : int(d) for d in self.complexity_data[s_name]} except KeyError: pass if len(data) == 0: log.debug('No valid data for miRNA complexity') return None config = { 'id': 'mirtrace_complexity_plot', 'title': 'miRTrace: miRNA Complexity Plot', 'ylab': 'Distinct miRNA Count', 'xlab': 'Number of Sequencing Reads', 'ymin': 0, 'xmin': 1, 'xDecimals': False, 'tt_label': '<b>Number of Sequencing Reads {point.x}</b>: {point.y} Distinct miRNA Count', } return linegraph.plot(data, config)
python
def mirtrace_complexity_plot(self): data = dict() for s_name in self.complexity_data: try: data[s_name] = {int(self.complexity_data[s_name][d]) : int(d) for d in self.complexity_data[s_name]} except KeyError: pass if len(data) == 0: log.debug('No valid data for miRNA complexity') return None config = { 'id': 'mirtrace_complexity_plot', 'title': 'miRTrace: miRNA Complexity Plot', 'ylab': 'Distinct miRNA Count', 'xlab': 'Number of Sequencing Reads', 'ymin': 0, 'xmin': 1, 'xDecimals': False, 'tt_label': '<b>Number of Sequencing Reads {point.x}</b>: {point.y} Distinct miRNA Count', } return linegraph.plot(data, config)
[ "def", "mirtrace_complexity_plot", "(", "self", ")", ":", "data", "=", "dict", "(", ")", "for", "s_name", "in", "self", ".", "complexity_data", ":", "try", ":", "data", "[", "s_name", "]", "=", "{", "int", "(", "self", ".", "complexity_data", "[", "s_n...
Generate the miRTrace miRNA Complexity Plot
[ "Generate", "the", "miRTrace", "miRNA", "Complexity", "Plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/mirtrace/mirtrace.py#L328-L352
224,421
ewels/MultiQC
multiqc/modules/bcftools/stats.py
StatsReportMixin.bcftools_stats_genstats_headers
def bcftools_stats_genstats_headers(self): """ Add key statistics to the General Stats table """ stats_headers = OrderedDict() stats_headers['number_of_records'] = { 'title': 'Vars', 'description': 'Variations total', 'min': 0, 'format': '{:,.0f}', } stats_headers['variations_hom'] = { 'title': 'Hom', 'description': 'Variations homozygous', 'min': 0, 'format': '{:,.0f}', } stats_headers['variations_het'] = { 'title': 'Het', 'description': 'Variations heterozygous', 'min': 0, 'format': '{:,.0f}', } stats_headers['number_of_SNPs'] = { 'title': 'SNP', 'description': 'Variation SNPs', 'min': 0, 'format': '{:,.0f}', } stats_headers['number_of_indels'] = { 'title': 'Indel', 'description': 'Variation Insertions/Deletions', 'min': 0, 'format': '{:,.0f}', } stats_headers['tstv'] = { 'title': 'Ts/Tv', 'description': 'Variant SNP transition / transversion ratio', 'min': 0, 'format': '{:,.2f}', } stats_headers['number_of_MNPs'] = { 'title': 'MNP', 'description': 'Variation multinucleotide polymorphisms', 'min': 0, 'format': '{:,.0f}', "hidden": True, } return stats_headers
python
def bcftools_stats_genstats_headers(self): stats_headers = OrderedDict() stats_headers['number_of_records'] = { 'title': 'Vars', 'description': 'Variations total', 'min': 0, 'format': '{:,.0f}', } stats_headers['variations_hom'] = { 'title': 'Hom', 'description': 'Variations homozygous', 'min': 0, 'format': '{:,.0f}', } stats_headers['variations_het'] = { 'title': 'Het', 'description': 'Variations heterozygous', 'min': 0, 'format': '{:,.0f}', } stats_headers['number_of_SNPs'] = { 'title': 'SNP', 'description': 'Variation SNPs', 'min': 0, 'format': '{:,.0f}', } stats_headers['number_of_indels'] = { 'title': 'Indel', 'description': 'Variation Insertions/Deletions', 'min': 0, 'format': '{:,.0f}', } stats_headers['tstv'] = { 'title': 'Ts/Tv', 'description': 'Variant SNP transition / transversion ratio', 'min': 0, 'format': '{:,.2f}', } stats_headers['number_of_MNPs'] = { 'title': 'MNP', 'description': 'Variation multinucleotide polymorphisms', 'min': 0, 'format': '{:,.0f}', "hidden": True, } return stats_headers
[ "def", "bcftools_stats_genstats_headers", "(", "self", ")", ":", "stats_headers", "=", "OrderedDict", "(", ")", "stats_headers", "[", "'number_of_records'", "]", "=", "{", "'title'", ":", "'Vars'", ",", "'description'", ":", "'Variations total'", ",", "'min'", ":"...
Add key statistics to the General Stats table
[ "Add", "key", "statistics", "to", "the", "General", "Stats", "table" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bcftools/stats.py#L219-L257
224,422
ewels/MultiQC
multiqc/modules/hicup/hicup.py
MultiqcModule.parse_hicup_logs
def parse_hicup_logs(self, f): """ Parse a HiCUP summary report """ if not f['fn'].endswith('.txt'): return None header = [] lines = f['f'].splitlines() for l in lines: s = l.split("\t") if len(header) == 0: if s[0] != 'File': return None header = s[1:] else: s_name = self.clean_s_name(s[0], f['root']).lstrip('HiCUP_output/') parsed_data = {} for idx, num in enumerate(s[1:]): try: parsed_data[header[idx]] = float(num) except: parsed_data[header[idx]] = num parsed_data['Duplicate_Read_Pairs'] = parsed_data['Valid_Pairs'] - parsed_data['Deduplication_Read_Pairs_Uniques'] if s_name in self.hicup_data: log.debug("Duplicate sample name found! Overwriting: {}".format(s_name)) self.add_data_source(f, s_name) self.hicup_data[s_name] = parsed_data
python
def parse_hicup_logs(self, f): if not f['fn'].endswith('.txt'): return None header = [] lines = f['f'].splitlines() for l in lines: s = l.split("\t") if len(header) == 0: if s[0] != 'File': return None header = s[1:] else: s_name = self.clean_s_name(s[0], f['root']).lstrip('HiCUP_output/') parsed_data = {} for idx, num in enumerate(s[1:]): try: parsed_data[header[idx]] = float(num) except: parsed_data[header[idx]] = num parsed_data['Duplicate_Read_Pairs'] = parsed_data['Valid_Pairs'] - parsed_data['Deduplication_Read_Pairs_Uniques'] if s_name in self.hicup_data: log.debug("Duplicate sample name found! Overwriting: {}".format(s_name)) self.add_data_source(f, s_name) self.hicup_data[s_name] = parsed_data
[ "def", "parse_hicup_logs", "(", "self", ",", "f", ")", ":", "if", "not", "f", "[", "'fn'", "]", ".", "endswith", "(", "'.txt'", ")", ":", "return", "None", "header", "=", "[", "]", "lines", "=", "f", "[", "'f'", "]", ".", "splitlines", "(", ")", ...
Parse a HiCUP summary report
[ "Parse", "a", "HiCUP", "summary", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicup/hicup.py#L78-L102
224,423
ewels/MultiQC
multiqc/modules/hicup/hicup.py
MultiqcModule.hicup_stats_table
def hicup_stats_table(self): """ Add core HiCUP stats to the general stats table """ headers = OrderedDict() headers['Percentage_Ditags_Passed_Through_HiCUP'] = { 'title': '% Passed', 'description': 'Percentage Di-Tags Passed Through HiCUP', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['Deduplication_Read_Pairs_Uniques'] = { 'title': '{} Unique'.format(config.read_count_prefix), 'description': 'Unique Di-Tags ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } headers['Percentage_Uniques'] = { 'title': '% Duplicates', 'description': 'Percent Duplicate Di-Tags', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn-rev', 'modify': lambda x: 100 - x } headers['Valid_Pairs'] = { 'title': '{} Valid'.format(config.read_count_prefix), 'description': 'Valid Pairs ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } headers['Percentage_Valid'] = { 'title': '% Valid', 'description': 'Percent Valid Pairs', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['Paired_Read_1'] = { 'title': '{} Pairs Aligned'.format(config.read_count_prefix), 'description': 'Paired Alignments ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } headers['Percentage_Mapped'] = { 'title': '% Aligned', 'description': 'Percentage of Paired Alignments', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } self.general_stats_addcols(self.hicup_data, headers, 'HiCUP')
python
def hicup_stats_table(self): headers = OrderedDict() headers['Percentage_Ditags_Passed_Through_HiCUP'] = { 'title': '% Passed', 'description': 'Percentage Di-Tags Passed Through HiCUP', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['Deduplication_Read_Pairs_Uniques'] = { 'title': '{} Unique'.format(config.read_count_prefix), 'description': 'Unique Di-Tags ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } headers['Percentage_Uniques'] = { 'title': '% Duplicates', 'description': 'Percent Duplicate Di-Tags', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn-rev', 'modify': lambda x: 100 - x } headers['Valid_Pairs'] = { 'title': '{} Valid'.format(config.read_count_prefix), 'description': 'Valid Pairs ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } headers['Percentage_Valid'] = { 'title': '% Valid', 'description': 'Percent Valid Pairs', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['Paired_Read_1'] = { 'title': '{} Pairs Aligned'.format(config.read_count_prefix), 'description': 'Paired Alignments ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } headers['Percentage_Mapped'] = { 'title': '% Aligned', 'description': 'Percentage of Paired Alignments', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } self.general_stats_addcols(self.hicup_data, headers, 'HiCUP')
[ "def", "hicup_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'Percentage_Ditags_Passed_Through_HiCUP'", "]", "=", "{", "'title'", ":", "'% Passed'", ",", "'description'", ":", "'Percentage Di-Tags Passed Through HiCUP'", ...
Add core HiCUP stats to the general stats table
[ "Add", "core", "HiCUP", "stats", "to", "the", "general", "stats", "table" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicup/hicup.py#L105-L165
224,424
ewels/MultiQC
multiqc/modules/hicup/hicup.py
MultiqcModule.hicup_truncating_chart
def hicup_truncating_chart (self): """ Generate the HiCUP Truncated reads plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['Not_Truncated_Reads'] = { 'color': '#2f7ed8', 'name': 'Not Truncated' } keys['Truncated_Read'] = { 'color': '#0d233a', 'name': 'Truncated' } # Construct a data structure for the plot - duplicate the samples for read 1 and read 2 data = {} for s_name in self.hicup_data: data['{} Read 1'.format(s_name)] = {} data['{} Read 2'.format(s_name)] = {} data['{} Read 1'.format(s_name)]['Not_Truncated_Reads'] = self.hicup_data[s_name]['Not_Truncated_Reads_1'] data['{} Read 2'.format(s_name)]['Not_Truncated_Reads'] = self.hicup_data[s_name]['Not_Truncated_Reads_2'] data['{} Read 1'.format(s_name)]['Truncated_Read'] = self.hicup_data[s_name]['Truncated_Read_1'] data['{} Read 2'.format(s_name)]['Truncated_Read'] = self.hicup_data[s_name]['Truncated_Read_2'] # Config for the plot config = { 'id': 'hicup_truncated_reads_plot', 'title': 'HiCUP: Truncated Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(data, keys, config)
python
def hicup_truncating_chart (self): # Specify the order of the different possible categories keys = OrderedDict() keys['Not_Truncated_Reads'] = { 'color': '#2f7ed8', 'name': 'Not Truncated' } keys['Truncated_Read'] = { 'color': '#0d233a', 'name': 'Truncated' } # Construct a data structure for the plot - duplicate the samples for read 1 and read 2 data = {} for s_name in self.hicup_data: data['{} Read 1'.format(s_name)] = {} data['{} Read 2'.format(s_name)] = {} data['{} Read 1'.format(s_name)]['Not_Truncated_Reads'] = self.hicup_data[s_name]['Not_Truncated_Reads_1'] data['{} Read 2'.format(s_name)]['Not_Truncated_Reads'] = self.hicup_data[s_name]['Not_Truncated_Reads_2'] data['{} Read 1'.format(s_name)]['Truncated_Read'] = self.hicup_data[s_name]['Truncated_Read_1'] data['{} Read 2'.format(s_name)]['Truncated_Read'] = self.hicup_data[s_name]['Truncated_Read_2'] # Config for the plot config = { 'id': 'hicup_truncated_reads_plot', 'title': 'HiCUP: Truncated Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(data, keys, config)
[ "def", "hicup_truncating_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'Not_Truncated_Reads'", "]", "=", "{", "'color'", ":", "'#2f7ed8'", ",", "'name'", ":", "'Not Trunca...
Generate the HiCUP Truncated reads plot
[ "Generate", "the", "HiCUP", "Truncated", "reads", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicup/hicup.py#L167-L193
224,425
ewels/MultiQC
multiqc/modules/hicup/hicup.py
MultiqcModule.hicup_alignment_chart
def hicup_alignment_chart (self): """ Generate the HiCUP Aligned reads plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['Unique_Alignments_Read'] = { 'color': '#2f7ed8', 'name': 'Unique Alignments' } keys['Multiple_Alignments_Read'] = { 'color': '#492970', 'name': 'Multiple Alignments' } keys['Failed_To_Align_Read'] = { 'color': '#0d233a', 'name': 'Failed To Align' } keys['Too_Short_To_Map_Read'] = { 'color': '#f28f43', 'name': 'Too short to map' } # Construct a data structure for the plot - duplicate the samples for read 1 and read 2 data = {} for s_name in self.hicup_data: data['{} Read 1'.format(s_name)] = {} data['{} Read 2'.format(s_name)] = {} data['{} Read 1'.format(s_name)]['Unique_Alignments_Read'] = self.hicup_data[s_name]['Unique_Alignments_Read_1'] data['{} Read 2'.format(s_name)]['Unique_Alignments_Read'] = self.hicup_data[s_name]['Unique_Alignments_Read_2'] data['{} Read 1'.format(s_name)]['Multiple_Alignments_Read'] = self.hicup_data[s_name]['Multiple_Alignments_Read_1'] data['{} Read 2'.format(s_name)]['Multiple_Alignments_Read'] = self.hicup_data[s_name]['Multiple_Alignments_Read_2'] data['{} Read 1'.format(s_name)]['Failed_To_Align_Read'] = self.hicup_data[s_name]['Failed_To_Align_Read_1'] data['{} Read 2'.format(s_name)]['Failed_To_Align_Read'] = self.hicup_data[s_name]['Failed_To_Align_Read_2'] data['{} Read 1'.format(s_name)]['Too_Short_To_Map_Read'] = self.hicup_data[s_name]['Too_Short_To_Map_Read_1'] data['{} Read 2'.format(s_name)]['Too_Short_To_Map_Read'] = self.hicup_data[s_name]['Too_Short_To_Map_Read_2'] # Config for the plot config = { 'id': 'hicup_mapping_stats_plot', 'title': 'HiCUP: Mapping Statistics', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(data, keys, config)
python
def hicup_alignment_chart (self): # Specify the order of the different possible categories keys = OrderedDict() keys['Unique_Alignments_Read'] = { 'color': '#2f7ed8', 'name': 'Unique Alignments' } keys['Multiple_Alignments_Read'] = { 'color': '#492970', 'name': 'Multiple Alignments' } keys['Failed_To_Align_Read'] = { 'color': '#0d233a', 'name': 'Failed To Align' } keys['Too_Short_To_Map_Read'] = { 'color': '#f28f43', 'name': 'Too short to map' } # Construct a data structure for the plot - duplicate the samples for read 1 and read 2 data = {} for s_name in self.hicup_data: data['{} Read 1'.format(s_name)] = {} data['{} Read 2'.format(s_name)] = {} data['{} Read 1'.format(s_name)]['Unique_Alignments_Read'] = self.hicup_data[s_name]['Unique_Alignments_Read_1'] data['{} Read 2'.format(s_name)]['Unique_Alignments_Read'] = self.hicup_data[s_name]['Unique_Alignments_Read_2'] data['{} Read 1'.format(s_name)]['Multiple_Alignments_Read'] = self.hicup_data[s_name]['Multiple_Alignments_Read_1'] data['{} Read 2'.format(s_name)]['Multiple_Alignments_Read'] = self.hicup_data[s_name]['Multiple_Alignments_Read_2'] data['{} Read 1'.format(s_name)]['Failed_To_Align_Read'] = self.hicup_data[s_name]['Failed_To_Align_Read_1'] data['{} Read 2'.format(s_name)]['Failed_To_Align_Read'] = self.hicup_data[s_name]['Failed_To_Align_Read_2'] data['{} Read 1'.format(s_name)]['Too_Short_To_Map_Read'] = self.hicup_data[s_name]['Too_Short_To_Map_Read_1'] data['{} Read 2'.format(s_name)]['Too_Short_To_Map_Read'] = self.hicup_data[s_name]['Too_Short_To_Map_Read_2'] # Config for the plot config = { 'id': 'hicup_mapping_stats_plot', 'title': 'HiCUP: Mapping Statistics', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(data, keys, config)
[ "def", "hicup_alignment_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'Unique_Alignments_Read'", "]", "=", "{", "'color'", ":", "'#2f7ed8'", ",", "'name'", ":", "'Unique A...
Generate the HiCUP Aligned reads plot
[ "Generate", "the", "HiCUP", "Aligned", "reads", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicup/hicup.py#L195-L227
224,426
ewels/MultiQC
multiqc/modules/hicup/hicup.py
MultiqcModule.hicup_filtering_chart
def hicup_filtering_chart(self): """ Generate the HiCUP filtering plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['Valid_Pairs'] = { 'color': '#2f7ed8', 'name': 'Valid Pairs' } keys['Same_Fragment_Internal'] = { 'color': '#0d233a', 'name': 'Same Fragment - Internal' } keys['Same_Circularised'] = { 'color': '#910000', 'name': 'Same Fragment - Circularised' } keys['Same_Dangling_Ends'] = { 'color': '#8bbc21', 'name': 'Same Fragment - Dangling Ends' } keys['Re_Ligation'] = { 'color': '#1aadce', 'name': 'Re-ligation' } keys['Contiguous_Sequence'] = { 'color': '#f28f43', 'name': 'Contiguous Sequence' } keys['Wrong_Size'] = { 'color': '#492970', 'name': 'Wrong Size' } # Config for the plot config = { 'id': 'hicup_filtering_plot', 'title': 'HiCUP: Filtering Statistics', 'ylab': '# Read Pairs', 'cpswitch_counts_label': 'Number of Read Pairs', 'cpswitch_c_active': False } return bargraph.plot(self.hicup_data, keys, config)
python
def hicup_filtering_chart(self): # Specify the order of the different possible categories keys = OrderedDict() keys['Valid_Pairs'] = { 'color': '#2f7ed8', 'name': 'Valid Pairs' } keys['Same_Fragment_Internal'] = { 'color': '#0d233a', 'name': 'Same Fragment - Internal' } keys['Same_Circularised'] = { 'color': '#910000', 'name': 'Same Fragment - Circularised' } keys['Same_Dangling_Ends'] = { 'color': '#8bbc21', 'name': 'Same Fragment - Dangling Ends' } keys['Re_Ligation'] = { 'color': '#1aadce', 'name': 'Re-ligation' } keys['Contiguous_Sequence'] = { 'color': '#f28f43', 'name': 'Contiguous Sequence' } keys['Wrong_Size'] = { 'color': '#492970', 'name': 'Wrong Size' } # Config for the plot config = { 'id': 'hicup_filtering_plot', 'title': 'HiCUP: Filtering Statistics', 'ylab': '# Read Pairs', 'cpswitch_counts_label': 'Number of Read Pairs', 'cpswitch_c_active': False } return bargraph.plot(self.hicup_data, keys, config)
[ "def", "hicup_filtering_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'Valid_Pairs'", "]", "=", "{", "'color'", ":", "'#2f7ed8'", ",", "'name'", ":", "'Valid Pairs'", "}...
Generate the HiCUP filtering plot
[ "Generate", "the", "HiCUP", "filtering", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicup/hicup.py#L229-L251
224,427
ewels/MultiQC
multiqc/modules/qualimap/QM_BamQC.py
parse_reports
def parse_reports(self): """ Find Qualimap BamQC reports and parse their data """ # General stats - genome_results.txt self.qualimap_bamqc_genome_results = dict() for f in self.find_log_files('qualimap/bamqc/genome_results'): parse_genome_results(self, f) self.qualimap_bamqc_genome_results = self.ignore_samples(self.qualimap_bamqc_genome_results) # Coverage - coverage_histogram.txt self.qualimap_bamqc_coverage_hist = dict() for f in self.find_log_files('qualimap/bamqc/coverage', filehandles=True): parse_coverage(self, f) self.qualimap_bamqc_coverage_hist = self.ignore_samples(self.qualimap_bamqc_coverage_hist) # Insert size - insert_size_histogram.txt self.qualimap_bamqc_insert_size_hist = dict() for f in self.find_log_files('qualimap/bamqc/insert_size', filehandles=True): parse_insert_size(self, f) self.qualimap_bamqc_insert_size_hist = self.ignore_samples(self.qualimap_bamqc_insert_size_hist) # GC distribution - mapped_reads_gc-content_distribution.txt self.qualimap_bamqc_gc_content_dist = dict() self.qualimap_bamqc_gc_by_species = dict() # {'HUMAN': data_dict, 'MOUSE': data_dict} for f in self.find_log_files('qualimap/bamqc/gc_dist', filehandles=True): parse_gc_dist(self, f) self.qualimap_bamqc_gc_by_species = self.ignore_samples(self.qualimap_bamqc_gc_by_species) num_parsed = max( len(self.qualimap_bamqc_genome_results), len(self.qualimap_bamqc_coverage_hist), len(self.qualimap_bamqc_insert_size_hist), len(self.qualimap_bamqc_gc_content_dist) ) # Go no further if nothing found if num_parsed == 0: return 0 try: covs = config.qualimap_config['general_stats_coverage'] assert type(covs) == list assert len(covs) > 0 covs = [str(i) for i in covs] log.debug("Custom Qualimap thresholds: {}".format(", ".join([i for i in covs]))) except (AttributeError, TypeError, AssertionError): covs = [1, 5, 10, 30, 50] covs = [str(i) for i in covs] log.debug("Using default Qualimap thresholds: {}".format(", ".join([i for i in covs]))) self.covs = covs # Make the plots for the report report_sections(self) # Set up the general stats table general_stats_headers(self) # Return the number of reports we found return num_parsed
python
def parse_reports(self): # General stats - genome_results.txt self.qualimap_bamqc_genome_results = dict() for f in self.find_log_files('qualimap/bamqc/genome_results'): parse_genome_results(self, f) self.qualimap_bamqc_genome_results = self.ignore_samples(self.qualimap_bamqc_genome_results) # Coverage - coverage_histogram.txt self.qualimap_bamqc_coverage_hist = dict() for f in self.find_log_files('qualimap/bamqc/coverage', filehandles=True): parse_coverage(self, f) self.qualimap_bamqc_coverage_hist = self.ignore_samples(self.qualimap_bamqc_coverage_hist) # Insert size - insert_size_histogram.txt self.qualimap_bamqc_insert_size_hist = dict() for f in self.find_log_files('qualimap/bamqc/insert_size', filehandles=True): parse_insert_size(self, f) self.qualimap_bamqc_insert_size_hist = self.ignore_samples(self.qualimap_bamqc_insert_size_hist) # GC distribution - mapped_reads_gc-content_distribution.txt self.qualimap_bamqc_gc_content_dist = dict() self.qualimap_bamqc_gc_by_species = dict() # {'HUMAN': data_dict, 'MOUSE': data_dict} for f in self.find_log_files('qualimap/bamqc/gc_dist', filehandles=True): parse_gc_dist(self, f) self.qualimap_bamqc_gc_by_species = self.ignore_samples(self.qualimap_bamqc_gc_by_species) num_parsed = max( len(self.qualimap_bamqc_genome_results), len(self.qualimap_bamqc_coverage_hist), len(self.qualimap_bamqc_insert_size_hist), len(self.qualimap_bamqc_gc_content_dist) ) # Go no further if nothing found if num_parsed == 0: return 0 try: covs = config.qualimap_config['general_stats_coverage'] assert type(covs) == list assert len(covs) > 0 covs = [str(i) for i in covs] log.debug("Custom Qualimap thresholds: {}".format(", ".join([i for i in covs]))) except (AttributeError, TypeError, AssertionError): covs = [1, 5, 10, 30, 50] covs = [str(i) for i in covs] log.debug("Using default Qualimap thresholds: {}".format(", ".join([i for i in covs]))) self.covs = covs # Make the plots for the report report_sections(self) # Set up the general stats table general_stats_headers(self) # Return the number of reports we found return num_parsed
[ "def", "parse_reports", "(", "self", ")", ":", "# General stats - genome_results.txt", "self", ".", "qualimap_bamqc_genome_results", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'qualimap/bamqc/genome_results'", ")", ":", "parse_genome...
Find Qualimap BamQC reports and parse their data
[ "Find", "Qualimap", "BamQC", "reports", "and", "parse", "their", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/qualimap/QM_BamQC.py#L17-L74
224,428
ewels/MultiQC
multiqc/modules/qualimap/QM_BamQC.py
parse_genome_results
def parse_genome_results(self, f): """ Parse the contents of the Qualimap BamQC genome_results.txt file """ regexes = { 'bam_file': r"bam file = (.+)", 'total_reads': r"number of reads = ([\d,]+)", 'mapped_reads': r"number of mapped reads = ([\d,]+)", 'mapped_bases': r"number of mapped bases = ([\d,]+)", 'sequenced_bases': r"number of sequenced bases = ([\d,]+)", 'mean_insert_size': r"mean insert size = ([\d,\.]+)", 'median_insert_size': r"median insert size = ([\d,\.]+)", 'mean_mapping_quality': r"mean mapping quality = ([\d,\.]+)", 'general_error_rate': r"general error rate = ([\d,\.]+)", } d = dict() for k, r in regexes.items(): r_search = re.search(r, f['f'], re.MULTILINE) if r_search: try: d[k] = float(r_search.group(1).replace(',','')) except ValueError: d[k] = r_search.group(1) # Check we have an input filename if 'bam_file' not in d: log.debug("Couldn't find an input filename in genome_results file {}".format(f['fn'])) return None # Get a nice sample name s_name = self.clean_s_name(d['bam_file'], f['root']) # Add to general stats table & calculate a nice % aligned try: self.general_stats_data[s_name]['total_reads'] = d['total_reads'] self.general_stats_data[s_name]['mapped_reads'] = d['mapped_reads'] d['percentage_aligned'] = (d['mapped_reads'] / d['total_reads'])*100 self.general_stats_data[s_name]['percentage_aligned'] = d['percentage_aligned'] self.general_stats_data[s_name]['general_error_rate'] = d['general_error_rate']*100 except KeyError: pass # Save results if s_name in self.qualimap_bamqc_genome_results: log.debug("Duplicate genome results sample name found! Overwriting: {}".format(s_name)) self.qualimap_bamqc_genome_results[s_name] = d self.add_data_source(f, s_name=s_name, section='genome_results')
python
def parse_genome_results(self, f): regexes = { 'bam_file': r"bam file = (.+)", 'total_reads': r"number of reads = ([\d,]+)", 'mapped_reads': r"number of mapped reads = ([\d,]+)", 'mapped_bases': r"number of mapped bases = ([\d,]+)", 'sequenced_bases': r"number of sequenced bases = ([\d,]+)", 'mean_insert_size': r"mean insert size = ([\d,\.]+)", 'median_insert_size': r"median insert size = ([\d,\.]+)", 'mean_mapping_quality': r"mean mapping quality = ([\d,\.]+)", 'general_error_rate': r"general error rate = ([\d,\.]+)", } d = dict() for k, r in regexes.items(): r_search = re.search(r, f['f'], re.MULTILINE) if r_search: try: d[k] = float(r_search.group(1).replace(',','')) except ValueError: d[k] = r_search.group(1) # Check we have an input filename if 'bam_file' not in d: log.debug("Couldn't find an input filename in genome_results file {}".format(f['fn'])) return None # Get a nice sample name s_name = self.clean_s_name(d['bam_file'], f['root']) # Add to general stats table & calculate a nice % aligned try: self.general_stats_data[s_name]['total_reads'] = d['total_reads'] self.general_stats_data[s_name]['mapped_reads'] = d['mapped_reads'] d['percentage_aligned'] = (d['mapped_reads'] / d['total_reads'])*100 self.general_stats_data[s_name]['percentage_aligned'] = d['percentage_aligned'] self.general_stats_data[s_name]['general_error_rate'] = d['general_error_rate']*100 except KeyError: pass # Save results if s_name in self.qualimap_bamqc_genome_results: log.debug("Duplicate genome results sample name found! Overwriting: {}".format(s_name)) self.qualimap_bamqc_genome_results[s_name] = d self.add_data_source(f, s_name=s_name, section='genome_results')
[ "def", "parse_genome_results", "(", "self", ",", "f", ")", ":", "regexes", "=", "{", "'bam_file'", ":", "r\"bam file = (.+)\"", ",", "'total_reads'", ":", "r\"number of reads = ([\\d,]+)\"", ",", "'mapped_reads'", ":", "r\"number of mapped reads = ([\\d,]+)\"", ",", "'m...
Parse the contents of the Qualimap BamQC genome_results.txt file
[ "Parse", "the", "contents", "of", "the", "Qualimap", "BamQC", "genome_results", ".", "txt", "file" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/qualimap/QM_BamQC.py#L76-L119
224,429
ewels/MultiQC
multiqc/modules/qualimap/QM_BamQC.py
parse_coverage
def parse_coverage(self, f): """ Parse the contents of the Qualimap BamQC Coverage Histogram file """ # Get the sample name from the parent parent directory # Typical path: <sample name>/raw_data_qualimapReport/coverage_histogram.txt s_name = self.get_s_name(f) d = dict() for l in f['f']: if l.startswith('#'): continue coverage, count = l.split(None, 1) coverage = int(round(float(coverage))) count = float(count) d[coverage] = count if len(d) == 0: log.debug("Couldn't parse contents of coverage histogram file {}".format(f['fn'])) return None # Find median without importing anything to do it for us num_counts = sum(d.values()) cum_counts = 0 median_coverage = None for thiscov, thiscount in d.items(): cum_counts += thiscount if cum_counts >= num_counts/2: median_coverage = thiscov break self.general_stats_data[s_name]['median_coverage'] = median_coverage # Save results if s_name in self.qualimap_bamqc_coverage_hist: log.debug("Duplicate coverage histogram sample name found! Overwriting: {}".format(s_name)) self.qualimap_bamqc_coverage_hist[s_name] = d self.add_data_source(f, s_name=s_name, section='coverage_histogram')
python
def parse_coverage(self, f): # Get the sample name from the parent parent directory # Typical path: <sample name>/raw_data_qualimapReport/coverage_histogram.txt s_name = self.get_s_name(f) d = dict() for l in f['f']: if l.startswith('#'): continue coverage, count = l.split(None, 1) coverage = int(round(float(coverage))) count = float(count) d[coverage] = count if len(d) == 0: log.debug("Couldn't parse contents of coverage histogram file {}".format(f['fn'])) return None # Find median without importing anything to do it for us num_counts = sum(d.values()) cum_counts = 0 median_coverage = None for thiscov, thiscount in d.items(): cum_counts += thiscount if cum_counts >= num_counts/2: median_coverage = thiscov break self.general_stats_data[s_name]['median_coverage'] = median_coverage # Save results if s_name in self.qualimap_bamqc_coverage_hist: log.debug("Duplicate coverage histogram sample name found! Overwriting: {}".format(s_name)) self.qualimap_bamqc_coverage_hist[s_name] = d self.add_data_source(f, s_name=s_name, section='coverage_histogram')
[ "def", "parse_coverage", "(", "self", ",", "f", ")", ":", "# Get the sample name from the parent parent directory", "# Typical path: <sample name>/raw_data_qualimapReport/coverage_histogram.txt", "s_name", "=", "self", ".", "get_s_name", "(", "f", ")", "d", "=", "dict", "("...
Parse the contents of the Qualimap BamQC Coverage Histogram file
[ "Parse", "the", "contents", "of", "the", "Qualimap", "BamQC", "Coverage", "Histogram", "file" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/qualimap/QM_BamQC.py#L122-L156
224,430
ewels/MultiQC
multiqc/modules/qualimap/QM_BamQC.py
parse_insert_size
def parse_insert_size(self, f): """ Parse the contents of the Qualimap BamQC Insert Size Histogram file """ # Get the sample name from the parent parent directory # Typical path: <sample name>/raw_data_qualimapReport/insert_size_histogram.txt s_name = self.get_s_name(f) d = dict() zero_insertsize = 0 for l in f['f']: if l.startswith('#'): continue insertsize, count = l.split(None, 1) insertsize = int(round(float(insertsize))) count = float(count) / 1000000 if(insertsize == 0): zero_insertsize = count else: d[insertsize] = count # Find median without importing anything to do it for us num_counts = sum(d.values()) cum_counts = 0 median_insert_size = None for thisins, thiscount in d.items(): cum_counts += thiscount if cum_counts >= num_counts/2: median_insert_size = thisins break # Add the median insert size to the general stats table self.general_stats_data[s_name]['median_insert_size'] = median_insert_size # Save results if s_name in self.qualimap_bamqc_insert_size_hist: log.debug("Duplicate insert size histogram sample name found! Overwriting: {}".format(s_name)) self.qualimap_bamqc_insert_size_hist[s_name] = d self.add_data_source(f, s_name=s_name, section='insert_size_histogram')
python
def parse_insert_size(self, f): # Get the sample name from the parent parent directory # Typical path: <sample name>/raw_data_qualimapReport/insert_size_histogram.txt s_name = self.get_s_name(f) d = dict() zero_insertsize = 0 for l in f['f']: if l.startswith('#'): continue insertsize, count = l.split(None, 1) insertsize = int(round(float(insertsize))) count = float(count) / 1000000 if(insertsize == 0): zero_insertsize = count else: d[insertsize] = count # Find median without importing anything to do it for us num_counts = sum(d.values()) cum_counts = 0 median_insert_size = None for thisins, thiscount in d.items(): cum_counts += thiscount if cum_counts >= num_counts/2: median_insert_size = thisins break # Add the median insert size to the general stats table self.general_stats_data[s_name]['median_insert_size'] = median_insert_size # Save results if s_name in self.qualimap_bamqc_insert_size_hist: log.debug("Duplicate insert size histogram sample name found! Overwriting: {}".format(s_name)) self.qualimap_bamqc_insert_size_hist[s_name] = d self.add_data_source(f, s_name=s_name, section='insert_size_histogram')
[ "def", "parse_insert_size", "(", "self", ",", "f", ")", ":", "# Get the sample name from the parent parent directory", "# Typical path: <sample name>/raw_data_qualimapReport/insert_size_histogram.txt", "s_name", "=", "self", ".", "get_s_name", "(", "f", ")", "d", "=", "dict",...
Parse the contents of the Qualimap BamQC Insert Size Histogram file
[ "Parse", "the", "contents", "of", "the", "Qualimap", "BamQC", "Insert", "Size", "Histogram", "file" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/qualimap/QM_BamQC.py#L158-L193
224,431
ewels/MultiQC
multiqc/modules/qualimap/QM_BamQC.py
parse_gc_dist
def parse_gc_dist(self, f): """ Parse the contents of the Qualimap BamQC Mapped Reads GC content distribution file """ # Get the sample name from the parent parent directory # Typical path: <sample name>/raw_data_qualimapReport/mapped_reads_gc-content_distribution.txt s_name = self.get_s_name(f) d = dict() reference_species = None reference_d = dict() avg_gc = 0 for l in f['f']: if l.startswith('#'): sections = l.strip("\n").split("\t", 3) if len(sections) > 2: reference_species = sections[2] continue sections = l.strip("\n").split("\t", 3) gc = int(round(float(sections[0]))) content = float(sections[1]) avg_gc += gc * content d[gc] = content if len(sections) > 2: reference_content = float(sections[2]) reference_d[gc] = reference_content # Add average GC to the general stats table self.general_stats_data[s_name]['avg_gc'] = avg_gc # Save results if s_name in self.qualimap_bamqc_gc_content_dist: log.debug("Duplicate Mapped Reads GC content distribution sample name found! Overwriting: {}".format(s_name)) self.qualimap_bamqc_gc_content_dist[s_name] = d if reference_species and reference_species not in self.qualimap_bamqc_gc_by_species: self.qualimap_bamqc_gc_by_species[reference_species] = reference_d self.add_data_source(f, s_name=s_name, section='mapped_gc_distribution')
python
def parse_gc_dist(self, f): # Get the sample name from the parent parent directory # Typical path: <sample name>/raw_data_qualimapReport/mapped_reads_gc-content_distribution.txt s_name = self.get_s_name(f) d = dict() reference_species = None reference_d = dict() avg_gc = 0 for l in f['f']: if l.startswith('#'): sections = l.strip("\n").split("\t", 3) if len(sections) > 2: reference_species = sections[2] continue sections = l.strip("\n").split("\t", 3) gc = int(round(float(sections[0]))) content = float(sections[1]) avg_gc += gc * content d[gc] = content if len(sections) > 2: reference_content = float(sections[2]) reference_d[gc] = reference_content # Add average GC to the general stats table self.general_stats_data[s_name]['avg_gc'] = avg_gc # Save results if s_name in self.qualimap_bamqc_gc_content_dist: log.debug("Duplicate Mapped Reads GC content distribution sample name found! Overwriting: {}".format(s_name)) self.qualimap_bamqc_gc_content_dist[s_name] = d if reference_species and reference_species not in self.qualimap_bamqc_gc_by_species: self.qualimap_bamqc_gc_by_species[reference_species] = reference_d self.add_data_source(f, s_name=s_name, section='mapped_gc_distribution')
[ "def", "parse_gc_dist", "(", "self", ",", "f", ")", ":", "# Get the sample name from the parent parent directory", "# Typical path: <sample name>/raw_data_qualimapReport/mapped_reads_gc-content_distribution.txt", "s_name", "=", "self", ".", "get_s_name", "(", "f", ")", "d", "="...
Parse the contents of the Qualimap BamQC Mapped Reads GC content distribution file
[ "Parse", "the", "contents", "of", "the", "Qualimap", "BamQC", "Mapped", "Reads", "GC", "content", "distribution", "file" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/qualimap/QM_BamQC.py#L195-L229
224,432
ewels/MultiQC
multiqc/modules/flexbar/flexbar.py
MultiqcModule.flexbar_barplot
def flexbar_barplot (self): """ Make the HighCharts HTML to plot the flexbar rates """ # Specify the order of the different possible categories keys = OrderedDict() keys['remaining_reads'] = { 'color': '#437bb1', 'name': 'Remaining reads' } keys['skipped_due_to_uncalled_bases'] = { 'color': '#e63491', 'name': 'Skipped due to uncalled bases' } keys['short_prior_to_adapter_removal'] = { 'color': '#b1084c', 'name': 'Short prior to adapter removal' } keys['finally_skipped_short_reads'] = { 'color': '#7f0000', 'name': 'Finally skipped short reads' } # Config for the plot pconfig = { 'id': 'flexbar_plot', 'title': 'Flexbar: Processed Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads', 'hide_zero_cats': False } self.add_section( plot = bargraph.plot(self.flexbar_data, keys, pconfig) )
python
def flexbar_barplot (self): # Specify the order of the different possible categories keys = OrderedDict() keys['remaining_reads'] = { 'color': '#437bb1', 'name': 'Remaining reads' } keys['skipped_due_to_uncalled_bases'] = { 'color': '#e63491', 'name': 'Skipped due to uncalled bases' } keys['short_prior_to_adapter_removal'] = { 'color': '#b1084c', 'name': 'Short prior to adapter removal' } keys['finally_skipped_short_reads'] = { 'color': '#7f0000', 'name': 'Finally skipped short reads' } # Config for the plot pconfig = { 'id': 'flexbar_plot', 'title': 'Flexbar: Processed Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads', 'hide_zero_cats': False } self.add_section( plot = bargraph.plot(self.flexbar_data, keys, pconfig) )
[ "def", "flexbar_barplot", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'remaining_reads'", "]", "=", "{", "'color'", ":", "'#437bb1'", ",", "'name'", ":", "'Remaining reads'", ...
Make the HighCharts HTML to plot the flexbar rates
[ "Make", "the", "HighCharts", "HTML", "to", "plot", "the", "flexbar", "rates" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/flexbar/flexbar.py#L98-L117
224,433
ewels/MultiQC
multiqc/modules/rseqc/read_gc.py
parse_reports
def parse_reports(self): """ Find RSeQC read_GC reports and parse their data """ # Set up vars self.read_gc = dict() self.read_gc_pct = dict() # Go through files and parse data for f in self.find_log_files('rseqc/read_gc'): if f['f'].startswith('GC% read_count'): gc = list() counts = list() for l in f['f'].splitlines(): s = l.split() try: gc.append(float(s[0])) counts.append(float(s[1])) except: pass if len(gc) > 0: sorted_gc_keys = sorted(range(len(gc)), key=lambda k: gc[k]) total = sum(counts) if f['s_name'] in self.read_gc: log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) self.add_data_source(f, section='read_GC') self.read_gc[f['s_name']] = OrderedDict() self.read_gc_pct[f['s_name']] = OrderedDict() for i in sorted_gc_keys: self.read_gc[f['s_name']][gc[i]] = counts[i] self.read_gc_pct[f['s_name']][gc[i]] = (counts[i]/total)*100 # Filter to strip out ignored sample names self.read_gc = self.ignore_samples(self.read_gc) if len(self.read_gc) > 0: # Add line graph to section pconfig = { 'id': 'rseqc_read_gc_plot', 'title': 'RSeQC: Read GC Content', 'ylab': 'Number of Reads', 'xlab': "GC content (%)", 'xmin': 0, 'xmax': 100, 'tt_label': "<strong>{point.x}% GC</strong>: {point.y:.2f}", 'data_labels': [ {'name': 'Counts', 'ylab': 'Number of Reads'}, {'name': 'Percentages', 'ylab': 'Percentage of Reads'} ] } self.add_section ( name = 'Read GC Content', anchor = 'rseqc-read_gc', description = '<a href="http://rseqc.sourceforge.net/#read-gc-py" target="_blank">read_GC</a>' \ " calculates a histogram of read GC content.</p>", plot = linegraph.plot([self.read_gc, self.read_gc_pct], pconfig) ) # Return number of samples found return len(self.read_gc)
python
def parse_reports(self): # Set up vars self.read_gc = dict() self.read_gc_pct = dict() # Go through files and parse data for f in self.find_log_files('rseqc/read_gc'): if f['f'].startswith('GC% read_count'): gc = list() counts = list() for l in f['f'].splitlines(): s = l.split() try: gc.append(float(s[0])) counts.append(float(s[1])) except: pass if len(gc) > 0: sorted_gc_keys = sorted(range(len(gc)), key=lambda k: gc[k]) total = sum(counts) if f['s_name'] in self.read_gc: log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) self.add_data_source(f, section='read_GC') self.read_gc[f['s_name']] = OrderedDict() self.read_gc_pct[f['s_name']] = OrderedDict() for i in sorted_gc_keys: self.read_gc[f['s_name']][gc[i]] = counts[i] self.read_gc_pct[f['s_name']][gc[i]] = (counts[i]/total)*100 # Filter to strip out ignored sample names self.read_gc = self.ignore_samples(self.read_gc) if len(self.read_gc) > 0: # Add line graph to section pconfig = { 'id': 'rseqc_read_gc_plot', 'title': 'RSeQC: Read GC Content', 'ylab': 'Number of Reads', 'xlab': "GC content (%)", 'xmin': 0, 'xmax': 100, 'tt_label': "<strong>{point.x}% GC</strong>: {point.y:.2f}", 'data_labels': [ {'name': 'Counts', 'ylab': 'Number of Reads'}, {'name': 'Percentages', 'ylab': 'Percentage of Reads'} ] } self.add_section ( name = 'Read GC Content', anchor = 'rseqc-read_gc', description = '<a href="http://rseqc.sourceforge.net/#read-gc-py" target="_blank">read_GC</a>' \ " calculates a histogram of read GC content.</p>", plot = linegraph.plot([self.read_gc, self.read_gc_pct], pconfig) ) # Return number of samples found return len(self.read_gc)
[ "def", "parse_reports", "(", "self", ")", ":", "# Set up vars", "self", ".", "read_gc", "=", "dict", "(", ")", "self", ".", "read_gc_pct", "=", "dict", "(", ")", "# Go through files and parse data", "for", "f", "in", "self", ".", "find_log_files", "(", "'rse...
Find RSeQC read_GC reports and parse their data
[ "Find", "RSeQC", "read_GC", "reports", "and", "parse", "their", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rseqc/read_gc.py#L15-L75
224,434
ewels/MultiQC
multiqc/modules/picard/VariantCallingMetrics.py
collect_data
def collect_data(parent_module): """ Find Picard VariantCallingMetrics reports and parse their data """ data = dict() for file_meta in parent_module.find_log_files('picard/variant_calling_metrics', filehandles=True): s_name = None for header, value in table_in(file_meta['f'], pre_header_string='## METRICS CLASS'): if header == 'SAMPLE_ALIAS': s_name = value if s_name in data: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(file_meta['fn'], s_name)) data[s_name] = OrderedDict() else: data[s_name][header] = value return data
python
def collect_data(parent_module): data = dict() for file_meta in parent_module.find_log_files('picard/variant_calling_metrics', filehandles=True): s_name = None for header, value in table_in(file_meta['f'], pre_header_string='## METRICS CLASS'): if header == 'SAMPLE_ALIAS': s_name = value if s_name in data: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(file_meta['fn'], s_name)) data[s_name] = OrderedDict() else: data[s_name][header] = value return data
[ "def", "collect_data", "(", "parent_module", ")", ":", "data", "=", "dict", "(", ")", "for", "file_meta", "in", "parent_module", ".", "find_log_files", "(", "'picard/variant_calling_metrics'", ",", "filehandles", "=", "True", ")", ":", "s_name", "=", "None", "...
Find Picard VariantCallingMetrics reports and parse their data
[ "Find", "Picard", "VariantCallingMetrics", "reports", "and", "parse", "their", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/VariantCallingMetrics.py#L118-L132
224,435
ewels/MultiQC
multiqc/modules/picard/VariantCallingMetrics.py
table_in
def table_in(filehandle, pre_header_string): """ Generator that assumes a table starts the line after a given string """ in_histogram = False next_is_header = False headers = list() for line in stripped(filehandle): if not in_histogram and line.startswith(pre_header_string): in_histogram = True next_is_header = True elif in_histogram and next_is_header: next_is_header = False headers = line.split("\t") elif in_histogram: values = line.split("\t") if values != ['']: for couple in zip(headers, values): yield couple
python
def table_in(filehandle, pre_header_string): in_histogram = False next_is_header = False headers = list() for line in stripped(filehandle): if not in_histogram and line.startswith(pre_header_string): in_histogram = True next_is_header = True elif in_histogram and next_is_header: next_is_header = False headers = line.split("\t") elif in_histogram: values = line.split("\t") if values != ['']: for couple in zip(headers, values): yield couple
[ "def", "table_in", "(", "filehandle", ",", "pre_header_string", ")", ":", "in_histogram", "=", "False", "next_is_header", "=", "False", "headers", "=", "list", "(", ")", "for", "line", "in", "stripped", "(", "filehandle", ")", ":", "if", "not", "in_histogram...
Generator that assumes a table starts the line after a given string
[ "Generator", "that", "assumes", "a", "table", "starts", "the", "line", "after", "a", "given", "string" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/VariantCallingMetrics.py#L135-L152
224,436
ewels/MultiQC
multiqc/modules/picard/VariantCallingMetrics.py
derive_data
def derive_data(data): """ Based on the data derive additional data """ for s_name, values in data.items(): # setup holding variable # Sum all variants that have been called total_called_variants = 0 for value_name in ['TOTAL_SNPS', 'TOTAL_COMPLEX_INDELS', 'TOTAL_MULTIALLELIC_SNPS', 'TOTAL_INDELS']: total_called_variants = total_called_variants + int(values[value_name]) values['total_called_variants'] = total_called_variants # Sum all variants that have been called and are known total_called_variants_known = 0 for value_name in ['NUM_IN_DB_SNP', 'NUM_IN_DB_SNP_COMPLEX_INDELS', 'NUM_IN_DB_SNP_MULTIALLELIC']: total_called_variants_known = total_called_variants_known + int(values[value_name]) total_called_variants_known = total_called_variants_known + int(values['TOTAL_INDELS']) - int(values['NOVEL_INDELS']) values['total_called_variants_known'] = total_called_variants_known # Extrapolate the total novel variants values['total_called_variants_novel'] = total_called_variants - total_called_variants_known
python
def derive_data(data): for s_name, values in data.items(): # setup holding variable # Sum all variants that have been called total_called_variants = 0 for value_name in ['TOTAL_SNPS', 'TOTAL_COMPLEX_INDELS', 'TOTAL_MULTIALLELIC_SNPS', 'TOTAL_INDELS']: total_called_variants = total_called_variants + int(values[value_name]) values['total_called_variants'] = total_called_variants # Sum all variants that have been called and are known total_called_variants_known = 0 for value_name in ['NUM_IN_DB_SNP', 'NUM_IN_DB_SNP_COMPLEX_INDELS', 'NUM_IN_DB_SNP_MULTIALLELIC']: total_called_variants_known = total_called_variants_known + int(values[value_name]) total_called_variants_known = total_called_variants_known + int(values['TOTAL_INDELS']) - int(values['NOVEL_INDELS']) values['total_called_variants_known'] = total_called_variants_known # Extrapolate the total novel variants values['total_called_variants_novel'] = total_called_variants - total_called_variants_known
[ "def", "derive_data", "(", "data", ")", ":", "for", "s_name", ",", "values", "in", "data", ".", "items", "(", ")", ":", "# setup holding variable", "# Sum all variants that have been called", "total_called_variants", "=", "0", "for", "value_name", "in", "[", "'TOT...
Based on the data derive additional data
[ "Based", "on", "the", "data", "derive", "additional", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/VariantCallingMetrics.py#L155-L175
224,437
ewels/MultiQC
multiqc/modules/picard/VariantCallingMetrics.py
compare_variants_label_plot
def compare_variants_label_plot(data): """ Return HTML for the Compare variants plot""" keys = OrderedDict() keys['total_called_variants_known'] = {'name': 'Known Variants'} keys['total_called_variants_novel'] = {'name': 'Novel Variants'} pconfig = { 'id': 'picard_variantCallingMetrics_variant_label', 'title': 'Picard: Variants Called', 'ylab': 'Counts of Variants', } return bargraph.plot(data, cats=keys, pconfig=pconfig)
python
def compare_variants_label_plot(data): keys = OrderedDict() keys['total_called_variants_known'] = {'name': 'Known Variants'} keys['total_called_variants_novel'] = {'name': 'Novel Variants'} pconfig = { 'id': 'picard_variantCallingMetrics_variant_label', 'title': 'Picard: Variants Called', 'ylab': 'Counts of Variants', } return bargraph.plot(data, cats=keys, pconfig=pconfig)
[ "def", "compare_variants_label_plot", "(", "data", ")", ":", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'total_called_variants_known'", "]", "=", "{", "'name'", ":", "'Known Variants'", "}", "keys", "[", "'total_called_variants_novel'", "]", "=", "{", "...
Return HTML for the Compare variants plot
[ "Return", "HTML", "for", "the", "Compare", "variants", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/VariantCallingMetrics.py#L233-L246
224,438
ewels/MultiQC
multiqc/modules/quast/quast.py
MultiqcModule.quast_general_stats_table
def quast_general_stats_table(self): """ Take the parsed stats from the QUAST report and add some to the General Statistics table at the top of the report """ headers = OrderedDict() headers['N50'] = { 'title': 'N50 ({})'.format(self.contig_length_suffix), 'description': 'N50 is the contig length such that using longer or equal length contigs produces half (50%) of the bases of the assembly (kilo base pairs)', 'min': 0, 'suffix': self.contig_length_suffix, 'scale': 'RdYlGn', 'modify': lambda x: x * self.contig_length_multiplier } headers['Total length'] = { 'title': 'Length ({})'.format(self.total_length_suffix), 'description': 'The total number of bases in the assembly (mega base pairs).', 'min': 0, 'suffix': self.total_length_suffix, 'scale': 'YlGn', 'modify': lambda x: x * self.total_length_multiplier } self.general_stats_addcols(self.quast_data, headers)
python
def quast_general_stats_table(self): headers = OrderedDict() headers['N50'] = { 'title': 'N50 ({})'.format(self.contig_length_suffix), 'description': 'N50 is the contig length such that using longer or equal length contigs produces half (50%) of the bases of the assembly (kilo base pairs)', 'min': 0, 'suffix': self.contig_length_suffix, 'scale': 'RdYlGn', 'modify': lambda x: x * self.contig_length_multiplier } headers['Total length'] = { 'title': 'Length ({})'.format(self.total_length_suffix), 'description': 'The total number of bases in the assembly (mega base pairs).', 'min': 0, 'suffix': self.total_length_suffix, 'scale': 'YlGn', 'modify': lambda x: x * self.total_length_multiplier } self.general_stats_addcols(self.quast_data, headers)
[ "def", "quast_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'N50'", "]", "=", "{", "'title'", ":", "'N50 ({})'", ".", "format", "(", "self", ".", "contig_length_suffix", ")", ",", "'description'", ":",...
Take the parsed stats from the QUAST report and add some to the General Statistics table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "QUAST", "report", "and", "add", "some", "to", "the", "General", "Statistics", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/quast/quast.py#L122-L143
224,439
ewels/MultiQC
multiqc/modules/quast/quast.py
MultiqcModule.quast_contigs_barplot
def quast_contigs_barplot(self): """ Make a bar plot showing the number and length of contigs for each assembly """ # Prep the data data = dict() categories = [] for s_name, d in self.quast_data.items(): nums_by_t = dict() for k, v in d.items(): m = re.match('# contigs \(>= (\d+) bp\)', k) if m and v != '-': nums_by_t[int(m.groups()[0])] = int(v) tresholds = sorted(nums_by_t.keys(), reverse=True) p = dict() cats = [] for i, t in enumerate(tresholds): if i == 0: c = '>= ' + str(t) + ' bp' cats.append(c) p[c] = nums_by_t[t] else: c = str(t) + '-' + str(tresholds[i - 1]) + ' bp' cats.append(c) p[c] = nums_by_t[t] - nums_by_t[tresholds[i - 1]] if not categories: categories = cats data[s_name] = p pconfig = { 'id': 'quast_num_contigs', 'title': 'QUAST: Number of Contigs', 'ylab': '# Contigs', 'yDecimals': False } return bargraph.plot(data, categories, pconfig)
python
def quast_contigs_barplot(self): # Prep the data data = dict() categories = [] for s_name, d in self.quast_data.items(): nums_by_t = dict() for k, v in d.items(): m = re.match('# contigs \(>= (\d+) bp\)', k) if m and v != '-': nums_by_t[int(m.groups()[0])] = int(v) tresholds = sorted(nums_by_t.keys(), reverse=True) p = dict() cats = [] for i, t in enumerate(tresholds): if i == 0: c = '>= ' + str(t) + ' bp' cats.append(c) p[c] = nums_by_t[t] else: c = str(t) + '-' + str(tresholds[i - 1]) + ' bp' cats.append(c) p[c] = nums_by_t[t] - nums_by_t[tresholds[i - 1]] if not categories: categories = cats data[s_name] = p pconfig = { 'id': 'quast_num_contigs', 'title': 'QUAST: Number of Contigs', 'ylab': '# Contigs', 'yDecimals': False } return bargraph.plot(data, categories, pconfig)
[ "def", "quast_contigs_barplot", "(", "self", ")", ":", "# Prep the data", "data", "=", "dict", "(", ")", "categories", "=", "[", "]", "for", "s_name", ",", "d", "in", "self", ".", "quast_data", ".", "items", "(", ")", ":", "nums_by_t", "=", "dict", "("...
Make a bar plot showing the number and length of contigs for each assembly
[ "Make", "a", "bar", "plot", "showing", "the", "number", "and", "length", "of", "contigs", "for", "each", "assembly" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/quast/quast.py#L255-L291
224,440
ewels/MultiQC
multiqc/modules/quast/quast.py
MultiqcModule.quast_predicted_genes_barplot
def quast_predicted_genes_barplot(self): """ Make a bar plot showing the number and length of predicted genes for each assembly """ # Prep the data # extract the ranges given to quast with "--gene-thresholds" prefix = '# predicted genes (>= ' suffix = ' bp)' all_thresholds = sorted(list(set([ int(key[len(prefix):-len(suffix)]) for _, d in self.quast_data.items() for key in d.keys() if key.startswith(prefix) ]))) data = {} ourpat = '>= {}{} bp' theirpat = prefix+"{}"+suffix for s_name, d in self.quast_data.items(): thresholds = sorted(list(set([ int(key[len(prefix):-len(suffix)]) for _, x in self.quast_data.items() for key in x.keys() if key.startswith(prefix) ]))) if len(thresholds)<2: continue p = dict() try: p = { ourpat.format(thresholds[-1],""): d[theirpat.format(thresholds[-1])] } for low,high in zip(thresholds[:-1], thresholds[1:]): p[ourpat.format(low,-high)] = d[theirpat.format(low)] - d[theirpat.format(high)] assert sum(p.values()) == d[theirpat.format(0)] except AssertionError: log.warning("Predicted gene counts didn't add up properly for \"{}\"".format(s_name)) except KeyError: log.warning("Not all predicted gene thresholds available for \"{}\"".format(s_name)) data[s_name] = p cats = [ ourpat.format(low,-high if high else "") for low,high in zip(all_thresholds, all_thresholds[1:]+[None]) ] if len(cats) > 0: return bargraph.plot(data, cats, {'id': 'quast_predicted_genes', 'title': 'QUAST: Number of predicted genes', 'ylab': 'Number of predicted genes'}) else: return None
python
def quast_predicted_genes_barplot(self): # Prep the data # extract the ranges given to quast with "--gene-thresholds" prefix = '# predicted genes (>= ' suffix = ' bp)' all_thresholds = sorted(list(set([ int(key[len(prefix):-len(suffix)]) for _, d in self.quast_data.items() for key in d.keys() if key.startswith(prefix) ]))) data = {} ourpat = '>= {}{} bp' theirpat = prefix+"{}"+suffix for s_name, d in self.quast_data.items(): thresholds = sorted(list(set([ int(key[len(prefix):-len(suffix)]) for _, x in self.quast_data.items() for key in x.keys() if key.startswith(prefix) ]))) if len(thresholds)<2: continue p = dict() try: p = { ourpat.format(thresholds[-1],""): d[theirpat.format(thresholds[-1])] } for low,high in zip(thresholds[:-1], thresholds[1:]): p[ourpat.format(low,-high)] = d[theirpat.format(low)] - d[theirpat.format(high)] assert sum(p.values()) == d[theirpat.format(0)] except AssertionError: log.warning("Predicted gene counts didn't add up properly for \"{}\"".format(s_name)) except KeyError: log.warning("Not all predicted gene thresholds available for \"{}\"".format(s_name)) data[s_name] = p cats = [ ourpat.format(low,-high if high else "") for low,high in zip(all_thresholds, all_thresholds[1:]+[None]) ] if len(cats) > 0: return bargraph.plot(data, cats, {'id': 'quast_predicted_genes', 'title': 'QUAST: Number of predicted genes', 'ylab': 'Number of predicted genes'}) else: return None
[ "def", "quast_predicted_genes_barplot", "(", "self", ")", ":", "# Prep the data", "# extract the ranges given to quast with \"--gene-thresholds\"", "prefix", "=", "'# predicted genes (>= '", "suffix", "=", "' bp)'", "all_thresholds", "=", "sorted", "(", "list", "(", "set", ...
Make a bar plot showing the number and length of predicted genes for each assembly
[ "Make", "a", "bar", "plot", "showing", "the", "number", "and", "length", "of", "predicted", "genes", "for", "each", "assembly" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/quast/quast.py#L293-L341
224,441
ewels/MultiQC
multiqc/modules/clipandmerge/clipandmerge.py
MultiqcModule.clipandmerge_general_stats_table
def clipandmerge_general_stats_table(self): """ Take the parsed stats from the ClipAndMerge report and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['percentage'] = { 'title': '% Merged', 'description': 'Percentage of reads merged', 'min': 0, 'max': 100, 'suffix': '%', 'scale': 'Greens', 'format': '{:,.2f}', } self.general_stats_addcols(self.clipandmerge_data, headers)
python
def clipandmerge_general_stats_table(self): headers = OrderedDict() headers['percentage'] = { 'title': '% Merged', 'description': 'Percentage of reads merged', 'min': 0, 'max': 100, 'suffix': '%', 'scale': 'Greens', 'format': '{:,.2f}', } self.general_stats_addcols(self.clipandmerge_data, headers)
[ "def", "clipandmerge_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'percentage'", "]", "=", "{", "'title'", ":", "'% Merged'", ",", "'description'", ":", "'Percentage of reads merged'", ",", "'min'", ":", ...
Take the parsed stats from the ClipAndMerge report and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "ClipAndMerge", "report", "and", "add", "it", "to", "the", "basic", "stats", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/clipandmerge/clipandmerge.py#L78-L92
224,442
ewels/MultiQC
multiqc/modules/bbmap/plot_basic_hist.py
plot_basic_hist
def plot_basic_hist(samples, file_type, **plot_args): """ Create line graph plot for basic histogram data for 'file_type'. The 'samples' parameter could be from the bbmap mod_data dictionary: samples = bbmap.MultiqcModule.mod_data[file_type] """ sumy = sum([int(samples[sample]['data'][x][0]) for sample in samples for x in samples[sample]['data']]) cutoff = sumy * 0.999 all_x = set() for item in sorted(chain(*[samples[sample]['data'].items() for sample in samples])): all_x.add(item[0]) cutoff -= item[1][0] if cutoff < 0: xmax = item[0] break else: xmax = max(all_x) data = { sample: { x: samples[sample]['data'][x][0] if x in samples[sample]['data'] else 0 for x in all_x } for sample in samples } plot_params = { 'id': 'bbmap-' + file_type + '_plot', 'title': 'BBTools: ' + plot_args['plot_title'], 'xmax': xmax } plot_params.update(plot_args['plot_params']) plot = linegraph.plot( data, plot_params ) return plot
python
def plot_basic_hist(samples, file_type, **plot_args): sumy = sum([int(samples[sample]['data'][x][0]) for sample in samples for x in samples[sample]['data']]) cutoff = sumy * 0.999 all_x = set() for item in sorted(chain(*[samples[sample]['data'].items() for sample in samples])): all_x.add(item[0]) cutoff -= item[1][0] if cutoff < 0: xmax = item[0] break else: xmax = max(all_x) data = { sample: { x: samples[sample]['data'][x][0] if x in samples[sample]['data'] else 0 for x in all_x } for sample in samples } plot_params = { 'id': 'bbmap-' + file_type + '_plot', 'title': 'BBTools: ' + plot_args['plot_title'], 'xmax': xmax } plot_params.update(plot_args['plot_params']) plot = linegraph.plot( data, plot_params ) return plot
[ "def", "plot_basic_hist", "(", "samples", ",", "file_type", ",", "*", "*", "plot_args", ")", ":", "sumy", "=", "sum", "(", "[", "int", "(", "samples", "[", "sample", "]", "[", "'data'", "]", "[", "x", "]", "[", "0", "]", ")", "for", "sample", "in...
Create line graph plot for basic histogram data for 'file_type'. The 'samples' parameter could be from the bbmap mod_data dictionary: samples = bbmap.MultiqcModule.mod_data[file_type]
[ "Create", "line", "graph", "plot", "for", "basic", "histogram", "data", "for", "file_type", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bbmap/plot_basic_hist.py#L5-L47
224,443
ewels/MultiQC
multiqc/modules/gatk/base_recalibrator.py
BaseRecalibratorMixin.parse_gatk_base_recalibrator
def parse_gatk_base_recalibrator(self): """ Find GATK BaseRecalibrator logs and parse their data """ report_table_headers = { '#:GATKTable:Arguments:Recalibration argument collection values used in this run': 'arguments', '#:GATKTable:Quantized:Quality quantization map': 'quality_quantization_map', '#:GATKTable:RecalTable0:': 'recal_table_0', '#:GATKTable:RecalTable1:': 'recal_table_1', '#:GATKTable:RecalTable2:': 'recal_table_2', } samples_kept = {rt_type: set() for rt_type in recal_table_type} self.gatk_base_recalibrator = {recal_type: {table_name: {} for table_name in report_table_headers.values()} for recal_type in recal_table_type} for f in self.find_log_files('gatk/base_recalibrator', filehandles=True): parsed_data = self.parse_report(f['f'].readlines(), report_table_headers) rt_type = determine_recal_table_type(parsed_data) if len(parsed_data) > 0: if f['s_name'] in samples_kept[rt_type]: log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) else: samples_kept[rt_type].add(f['s_name']) self.add_data_source(f, section='base_recalibrator') for table_name, sample_tables in parsed_data.items(): self.gatk_base_recalibrator[rt_type][table_name][ f['s_name']] = sample_tables # Filter to strip out ignored sample names for rt_type in recal_table_type: for table_name, sample_tables in self.gatk_base_recalibrator[rt_type].items(): self.gatk_base_recalibrator[rt_type][table_name] = self.ignore_samples( sample_tables) n_reports_found = sum([len(samples_kept[rt_type]) for rt_type in recal_table_type]) if n_reports_found > 0: log.info("Found {} BaseRecalibrator reports".format(n_reports_found)) self.add_quality_score_vs_no_of_observations_section() return n_reports_found
python
def parse_gatk_base_recalibrator(self): report_table_headers = { '#:GATKTable:Arguments:Recalibration argument collection values used in this run': 'arguments', '#:GATKTable:Quantized:Quality quantization map': 'quality_quantization_map', '#:GATKTable:RecalTable0:': 'recal_table_0', '#:GATKTable:RecalTable1:': 'recal_table_1', '#:GATKTable:RecalTable2:': 'recal_table_2', } samples_kept = {rt_type: set() for rt_type in recal_table_type} self.gatk_base_recalibrator = {recal_type: {table_name: {} for table_name in report_table_headers.values()} for recal_type in recal_table_type} for f in self.find_log_files('gatk/base_recalibrator', filehandles=True): parsed_data = self.parse_report(f['f'].readlines(), report_table_headers) rt_type = determine_recal_table_type(parsed_data) if len(parsed_data) > 0: if f['s_name'] in samples_kept[rt_type]: log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) else: samples_kept[rt_type].add(f['s_name']) self.add_data_source(f, section='base_recalibrator') for table_name, sample_tables in parsed_data.items(): self.gatk_base_recalibrator[rt_type][table_name][ f['s_name']] = sample_tables # Filter to strip out ignored sample names for rt_type in recal_table_type: for table_name, sample_tables in self.gatk_base_recalibrator[rt_type].items(): self.gatk_base_recalibrator[rt_type][table_name] = self.ignore_samples( sample_tables) n_reports_found = sum([len(samples_kept[rt_type]) for rt_type in recal_table_type]) if n_reports_found > 0: log.info("Found {} BaseRecalibrator reports".format(n_reports_found)) self.add_quality_score_vs_no_of_observations_section() return n_reports_found
[ "def", "parse_gatk_base_recalibrator", "(", "self", ")", ":", "report_table_headers", "=", "{", "'#:GATKTable:Arguments:Recalibration argument collection values used in this run'", ":", "'arguments'", ",", "'#:GATKTable:Quantized:Quality quantization map'", ":", "'quality_quantization_...
Find GATK BaseRecalibrator logs and parse their data
[ "Find", "GATK", "BaseRecalibrator", "logs", "and", "parse", "their", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/gatk/base_recalibrator.py#L17-L61
224,444
ewels/MultiQC
multiqc/modules/gatk/base_recalibrator.py
BaseRecalibratorMixin.add_quality_score_vs_no_of_observations_section
def add_quality_score_vs_no_of_observations_section(self): """ Add a section for the quality score vs number of observations line plot """ sample_data = [] data_labels = [] for rt_type_name, rt_type in recal_table_type._asdict().items(): sample_tables = self.gatk_base_recalibrator[rt_type]['quality_quantization_map'] if len(sample_tables) == 0: continue sample_data.append({ sample: {int(x): int(y) for x, y in zip(table['QualityScore'], table['Count'])} for sample, table in sample_tables.items() }) sample_y_sums = { sample: sum(int(y) for y in table['Count']) for sample, table in sample_tables.items() } sample_data.append({ sample: { int(x): float(y) / sample_y_sums[sample] for x, y in zip(table['QualityScore'], table['Count']) } for sample, table in sample_tables.items() }) flat_proportions = [float(y) / sample_y_sums[sample] for sample, table in sample_tables.items() for y in table['Count']] prop_ymax = max(flat_proportions) data_labels.append({'name': "{} Count".format(rt_type_name.capitalize().replace('_', '-')), 'ylab': 'Count'}) data_labels.append({'ymax': prop_ymax, 'name': "{} Percent".format(rt_type_name.capitalize().replace('_', '-')), 'ylab': 'Percent'}) plot = linegraph.plot( sample_data, pconfig={ 'title': "Observed Quality Score Counts", 'id': 'gatk-base-recalibrator-quality-score-vs-number-of-observations', 'xlab': 'Observed Quality Score', 'ylab': 'Count', 'xDecimals': False, 'data_labels': data_labels, }) # Reported vs empirical quality scores self.add_section( name='Observed Quality Scores', description=( 'This plot shows the distribution of base quality scores in each sample before and ' 'after base quality score recalibration (BQSR). Applying BQSR should broaden the ' 'distribution of base quality scores.' ), helptext=( 'For more information see ' '[the Broad\'s description of BQSR]' '(https://gatkforums.broadinstitute.org/gatk/discussion/44/base-quality-score-recalibration-bqsr)' '.' ), plot=plot, )
python
def add_quality_score_vs_no_of_observations_section(self): sample_data = [] data_labels = [] for rt_type_name, rt_type in recal_table_type._asdict().items(): sample_tables = self.gatk_base_recalibrator[rt_type]['quality_quantization_map'] if len(sample_tables) == 0: continue sample_data.append({ sample: {int(x): int(y) for x, y in zip(table['QualityScore'], table['Count'])} for sample, table in sample_tables.items() }) sample_y_sums = { sample: sum(int(y) for y in table['Count']) for sample, table in sample_tables.items() } sample_data.append({ sample: { int(x): float(y) / sample_y_sums[sample] for x, y in zip(table['QualityScore'], table['Count']) } for sample, table in sample_tables.items() }) flat_proportions = [float(y) / sample_y_sums[sample] for sample, table in sample_tables.items() for y in table['Count']] prop_ymax = max(flat_proportions) data_labels.append({'name': "{} Count".format(rt_type_name.capitalize().replace('_', '-')), 'ylab': 'Count'}) data_labels.append({'ymax': prop_ymax, 'name': "{} Percent".format(rt_type_name.capitalize().replace('_', '-')), 'ylab': 'Percent'}) plot = linegraph.plot( sample_data, pconfig={ 'title': "Observed Quality Score Counts", 'id': 'gatk-base-recalibrator-quality-score-vs-number-of-observations', 'xlab': 'Observed Quality Score', 'ylab': 'Count', 'xDecimals': False, 'data_labels': data_labels, }) # Reported vs empirical quality scores self.add_section( name='Observed Quality Scores', description=( 'This plot shows the distribution of base quality scores in each sample before and ' 'after base quality score recalibration (BQSR). Applying BQSR should broaden the ' 'distribution of base quality scores.' ), helptext=( 'For more information see ' '[the Broad\'s description of BQSR]' '(https://gatkforums.broadinstitute.org/gatk/discussion/44/base-quality-score-recalibration-bqsr)' '.' ), plot=plot, )
[ "def", "add_quality_score_vs_no_of_observations_section", "(", "self", ")", ":", "sample_data", "=", "[", "]", "data_labels", "=", "[", "]", "for", "rt_type_name", ",", "rt_type", "in", "recal_table_type", ".", "_asdict", "(", ")", ".", "items", "(", ")", ":",...
Add a section for the quality score vs number of observations line plot
[ "Add", "a", "section", "for", "the", "quality", "score", "vs", "number", "of", "observations", "line", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/gatk/base_recalibrator.py#L63-L128
224,445
ewels/MultiQC
multiqc/modules/biobloomtools/biobloomtools.py
MultiqcModule.parse_bbt
def parse_bbt(self, fh): """ Parse the BioBloom Tools output into a 3D dict """ parsed_data = OrderedDict() headers = None for l in fh: s = l.split("\t") if headers is None: headers = s else: parsed_data[s[0]] = dict() for i, h in enumerate(headers[1:]): parsed_data[s[0]][h] = float(s[i+1]) return parsed_data
python
def parse_bbt(self, fh): parsed_data = OrderedDict() headers = None for l in fh: s = l.split("\t") if headers is None: headers = s else: parsed_data[s[0]] = dict() for i, h in enumerate(headers[1:]): parsed_data[s[0]][h] = float(s[i+1]) return parsed_data
[ "def", "parse_bbt", "(", "self", ",", "fh", ")", ":", "parsed_data", "=", "OrderedDict", "(", ")", "headers", "=", "None", "for", "l", "in", "fh", ":", "s", "=", "l", ".", "split", "(", "\"\\t\"", ")", "if", "headers", "is", "None", ":", "headers",...
Parse the BioBloom Tools output into a 3D dict
[ "Parse", "the", "BioBloom", "Tools", "output", "into", "a", "3D", "dict" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/biobloomtools/biobloomtools.py#L58-L71
224,446
ewels/MultiQC
multiqc/modules/fastq_screen/fastq_screen.py
MultiqcModule.parse_fqscreen
def parse_fqscreen(self, f): """ Parse the FastQ Screen output into a 3D dict """ parsed_data = OrderedDict() reads_processed = None nohits_pct = None for l in f['f']: if l.startswith('%Hit_no_genomes:') or l.startswith('%Hit_no_libraries:'): nohits_pct = float(l.split(':', 1)[1]) parsed_data['No hits'] = {'percentages': {'one_hit_one_library': nohits_pct }} else: fqs = re.search(r"^(\S+)\s+(\d+)\s+(\d+)\s+([\d\.]+)\s+(\d+)\s+([\d\.]+)\s+(\d+)\s+([\d\.]+)\s+(\d+)\s+([\d\.]+)\s+(\d+)\s+([\d\.]+)$", l) if fqs: org = fqs.group(1) parsed_data[org] = {'percentages':{}, 'counts':{}} reads_processed = int(fqs.group(2)) parsed_data[org]['counts']['reads_processed'] = int(fqs.group(2)) parsed_data[org]['counts']['unmapped'] = int(fqs.group(3)) parsed_data[org]['percentages']['unmapped'] = float(fqs.group(4)) parsed_data[org]['counts']['one_hit_one_library'] = int(fqs.group(5)) parsed_data[org]['percentages']['one_hit_one_library'] = float(fqs.group(6)) parsed_data[org]['counts']['multiple_hits_one_library'] = int(fqs.group(7)) parsed_data[org]['percentages']['multiple_hits_one_library'] = float(fqs.group(8)) parsed_data[org]['counts']['one_hit_multiple_libraries'] = int(fqs.group(9)) parsed_data[org]['percentages']['one_hit_multiple_libraries'] = float(fqs.group(10)) parsed_data[org]['counts']['multiple_hits_multiple_libraries'] = int(fqs.group(11)) parsed_data[org]['percentages']['multiple_hits_multiple_libraries'] = float(fqs.group(12)) # Can't use #Reads in subset as varies. #Reads_processed should be same for all orgs in a sample parsed_data['total_reads'] = int(fqs.group(2)) if len(parsed_data) == 0: return None # Calculate no hits counts if reads_processed and nohits_pct: parsed_data['No hits']['counts'] = {'one_hit_one_library': int((nohits_pct/100.0) * float(reads_processed)) } else: log.warn("Couldn't find number of reads with no hits for '{}'".format(f['s_name'])) self.num_orgs = max(len(parsed_data), self.num_orgs) return parsed_data
python
def parse_fqscreen(self, f): parsed_data = OrderedDict() reads_processed = None nohits_pct = None for l in f['f']: if l.startswith('%Hit_no_genomes:') or l.startswith('%Hit_no_libraries:'): nohits_pct = float(l.split(':', 1)[1]) parsed_data['No hits'] = {'percentages': {'one_hit_one_library': nohits_pct }} else: fqs = re.search(r"^(\S+)\s+(\d+)\s+(\d+)\s+([\d\.]+)\s+(\d+)\s+([\d\.]+)\s+(\d+)\s+([\d\.]+)\s+(\d+)\s+([\d\.]+)\s+(\d+)\s+([\d\.]+)$", l) if fqs: org = fqs.group(1) parsed_data[org] = {'percentages':{}, 'counts':{}} reads_processed = int(fqs.group(2)) parsed_data[org]['counts']['reads_processed'] = int(fqs.group(2)) parsed_data[org]['counts']['unmapped'] = int(fqs.group(3)) parsed_data[org]['percentages']['unmapped'] = float(fqs.group(4)) parsed_data[org]['counts']['one_hit_one_library'] = int(fqs.group(5)) parsed_data[org]['percentages']['one_hit_one_library'] = float(fqs.group(6)) parsed_data[org]['counts']['multiple_hits_one_library'] = int(fqs.group(7)) parsed_data[org]['percentages']['multiple_hits_one_library'] = float(fqs.group(8)) parsed_data[org]['counts']['one_hit_multiple_libraries'] = int(fqs.group(9)) parsed_data[org]['percentages']['one_hit_multiple_libraries'] = float(fqs.group(10)) parsed_data[org]['counts']['multiple_hits_multiple_libraries'] = int(fqs.group(11)) parsed_data[org]['percentages']['multiple_hits_multiple_libraries'] = float(fqs.group(12)) # Can't use #Reads in subset as varies. #Reads_processed should be same for all orgs in a sample parsed_data['total_reads'] = int(fqs.group(2)) if len(parsed_data) == 0: return None # Calculate no hits counts if reads_processed and nohits_pct: parsed_data['No hits']['counts'] = {'one_hit_one_library': int((nohits_pct/100.0) * float(reads_processed)) } else: log.warn("Couldn't find number of reads with no hits for '{}'".format(f['s_name'])) self.num_orgs = max(len(parsed_data), self.num_orgs) return parsed_data
[ "def", "parse_fqscreen", "(", "self", ",", "f", ")", ":", "parsed_data", "=", "OrderedDict", "(", ")", "reads_processed", "=", "None", "nohits_pct", "=", "None", "for", "l", "in", "f", "[", "'f'", "]", ":", "if", "l", ".", "startswith", "(", "'%Hit_no_...
Parse the FastQ Screen output into a 3D dict
[ "Parse", "the", "FastQ", "Screen", "output", "into", "a", "3D", "dict" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastq_screen/fastq_screen.py#L60-L99
224,447
ewels/MultiQC
multiqc/modules/fastq_screen/fastq_screen.py
MultiqcModule.fqscreen_plot
def fqscreen_plot (self): """ Makes a fancy custom plot which replicates the plot seen in the main FastQ Screen program. Not useful if lots of samples as gets too wide. """ categories = list() getCats = True data = list() p_types = OrderedDict() p_types['multiple_hits_multiple_libraries'] = {'col': '#7f0000', 'name': 'Multiple Hits, Multiple Genomes' } p_types['one_hit_multiple_libraries'] = {'col': '#ff0000', 'name': 'One Hit, Multiple Genomes' } p_types['multiple_hits_one_library'] = {'col': '#00007f', 'name': 'Multiple Hits, One Genome' } p_types['one_hit_one_library'] = {'col': '#0000ff', 'name': 'One Hit, One Genome' } for k, t in p_types.items(): first = True for s in sorted(self.fq_screen_data.keys()): thisdata = list() if len(categories) > 0: getCats = False for org in sorted(self.fq_screen_data[s]): if org == 'total_reads': continue try: thisdata.append(self.fq_screen_data[s][org]['percentages'][k]) except KeyError: thisdata.append(None) if getCats: categories.append(org) td = { 'name': t['name'], 'stack': s, 'data': thisdata, 'color': t['col'] } if first: first = False else: td['linkedTo'] = ':previous' data.append(td) html = '<div id="fq_screen_plot" class="hc-plot"></div> \n\ <script type="text/javascript"> \n\ fq_screen_data = {};\n\ fq_screen_categories = {};\n\ $(function () {{ \n\ $("#fq_screen_plot").highcharts({{ \n\ chart: {{ type: "column", backgroundColor: null }}, \n\ title: {{ text: "FastQ Screen Results" }}, \n\ xAxis: {{ categories: fq_screen_categories }}, \n\ yAxis: {{ \n\ max: 100, \n\ min: 0, \n\ title: {{ text: "Percentage Aligned" }} \n\ }}, \n\ tooltip: {{ \n\ formatter: function () {{ \n\ return "<b>" + this.series.stackKey.replace("column","") + " - " + this.x + "</b><br/>" + \n\ this.series.name + ": " + this.y + "%<br/>" + \n\ "Total Alignment: " + this.point.stackTotal + "%"; \n\ }}, \n\ }}, \n\ plotOptions: {{ \n\ column: {{ \n\ pointPadding: 0, \n\ groupPadding: 0.02, \n\ stacking: "normal" }} \n\ }}, \n\ series: fq_screen_data \n\ }}); \n\ }}); \n\ </script>'.format(json.dumps(data), json.dumps(categories)) return html
python
def fqscreen_plot (self): categories = list() getCats = True data = list() p_types = OrderedDict() p_types['multiple_hits_multiple_libraries'] = {'col': '#7f0000', 'name': 'Multiple Hits, Multiple Genomes' } p_types['one_hit_multiple_libraries'] = {'col': '#ff0000', 'name': 'One Hit, Multiple Genomes' } p_types['multiple_hits_one_library'] = {'col': '#00007f', 'name': 'Multiple Hits, One Genome' } p_types['one_hit_one_library'] = {'col': '#0000ff', 'name': 'One Hit, One Genome' } for k, t in p_types.items(): first = True for s in sorted(self.fq_screen_data.keys()): thisdata = list() if len(categories) > 0: getCats = False for org in sorted(self.fq_screen_data[s]): if org == 'total_reads': continue try: thisdata.append(self.fq_screen_data[s][org]['percentages'][k]) except KeyError: thisdata.append(None) if getCats: categories.append(org) td = { 'name': t['name'], 'stack': s, 'data': thisdata, 'color': t['col'] } if first: first = False else: td['linkedTo'] = ':previous' data.append(td) html = '<div id="fq_screen_plot" class="hc-plot"></div> \n\ <script type="text/javascript"> \n\ fq_screen_data = {};\n\ fq_screen_categories = {};\n\ $(function () {{ \n\ $("#fq_screen_plot").highcharts({{ \n\ chart: {{ type: "column", backgroundColor: null }}, \n\ title: {{ text: "FastQ Screen Results" }}, \n\ xAxis: {{ categories: fq_screen_categories }}, \n\ yAxis: {{ \n\ max: 100, \n\ min: 0, \n\ title: {{ text: "Percentage Aligned" }} \n\ }}, \n\ tooltip: {{ \n\ formatter: function () {{ \n\ return "<b>" + this.series.stackKey.replace("column","") + " - " + this.x + "</b><br/>" + \n\ this.series.name + ": " + this.y + "%<br/>" + \n\ "Total Alignment: " + this.point.stackTotal + "%"; \n\ }}, \n\ }}, \n\ plotOptions: {{ \n\ column: {{ \n\ pointPadding: 0, \n\ groupPadding: 0.02, \n\ stacking: "normal" }} \n\ }}, \n\ series: fq_screen_data \n\ }}); \n\ }}); \n\ </script>'.format(json.dumps(data), json.dumps(categories)) return html
[ "def", "fqscreen_plot", "(", "self", ")", ":", "categories", "=", "list", "(", ")", "getCats", "=", "True", "data", "=", "list", "(", ")", "p_types", "=", "OrderedDict", "(", ")", "p_types", "[", "'multiple_hits_multiple_libraries'", "]", "=", "{", "'col'"...
Makes a fancy custom plot which replicates the plot seen in the main FastQ Screen program. Not useful if lots of samples as gets too wide.
[ "Makes", "a", "fancy", "custom", "plot", "which", "replicates", "the", "plot", "seen", "in", "the", "main", "FastQ", "Screen", "program", ".", "Not", "useful", "if", "lots", "of", "samples", "as", "gets", "too", "wide", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastq_screen/fastq_screen.py#L125-L196
224,448
ewels/MultiQC
multiqc/modules/minionqc/minionqc.py
MultiqcModule.parse_minionqc_report
def parse_minionqc_report(self, s_name, f): ''' Parses minionqc's 'summary.yaml' report file for results. Uses only the "All reads" stats. Ignores "Q>=x" part. ''' try: # Parsing as OrderedDict is slightly messier with YAML # http://stackoverflow.com/a/21048064/713980 def dict_constructor(loader, node): return OrderedDict(loader.construct_pairs(node)) yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, dict_constructor) summary_dict = yaml.safe_load(f) except Exception as e: log.error("Error parsing MinIONQC input file: {}".format(f)) return # Do a deep copy as dicts are immutable self.minionqc_raw_data[s_name] = copy.deepcopy(summary_dict) # get q value threshold used for reads q_threshold = None for k in summary_dict.keys(): if k.startswith('Q>='): q_threshold = k data_dict = {} data_dict['all'] = summary_dict['All reads'] # all reads data_dict['q_filt'] = summary_dict[q_threshold] # quality filtered reads for q_key in ['all', 'q_filt']: for key_1 in ['reads', 'gigabases']: for key_2 in data_dict[q_key][key_1]: new_key = '{} {}'.format(key_1, key_2) data_dict[q_key][new_key] = data_dict[q_key][key_1][key_2] data_dict[q_key].pop(key_1) # removes key after flattening self.minionqc_data[s_name] = data_dict['all'] # stats for all reads self.qfilt_data[s_name] = data_dict['q_filt'] # stats for q-filtered reads self.q_threshold_list.add(q_threshold)
python
def parse_minionqc_report(self, s_name, f): ''' Parses minionqc's 'summary.yaml' report file for results. Uses only the "All reads" stats. Ignores "Q>=x" part. ''' try: # Parsing as OrderedDict is slightly messier with YAML # http://stackoverflow.com/a/21048064/713980 def dict_constructor(loader, node): return OrderedDict(loader.construct_pairs(node)) yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, dict_constructor) summary_dict = yaml.safe_load(f) except Exception as e: log.error("Error parsing MinIONQC input file: {}".format(f)) return # Do a deep copy as dicts are immutable self.minionqc_raw_data[s_name] = copy.deepcopy(summary_dict) # get q value threshold used for reads q_threshold = None for k in summary_dict.keys(): if k.startswith('Q>='): q_threshold = k data_dict = {} data_dict['all'] = summary_dict['All reads'] # all reads data_dict['q_filt'] = summary_dict[q_threshold] # quality filtered reads for q_key in ['all', 'q_filt']: for key_1 in ['reads', 'gigabases']: for key_2 in data_dict[q_key][key_1]: new_key = '{} {}'.format(key_1, key_2) data_dict[q_key][new_key] = data_dict[q_key][key_1][key_2] data_dict[q_key].pop(key_1) # removes key after flattening self.minionqc_data[s_name] = data_dict['all'] # stats for all reads self.qfilt_data[s_name] = data_dict['q_filt'] # stats for q-filtered reads self.q_threshold_list.add(q_threshold)
[ "def", "parse_minionqc_report", "(", "self", ",", "s_name", ",", "f", ")", ":", "try", ":", "# Parsing as OrderedDict is slightly messier with YAML", "# http://stackoverflow.com/a/21048064/713980", "def", "dict_constructor", "(", "loader", ",", "node", ")", ":", "return",...
Parses minionqc's 'summary.yaml' report file for results. Uses only the "All reads" stats. Ignores "Q>=x" part.
[ "Parses", "minionqc", "s", "summary", ".", "yaml", "report", "file", "for", "results", ".", "Uses", "only", "the", "All", "reads", "stats", ".", "Ignores", "Q", ">", "=", "x", "part", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/minionqc/minionqc.py#L72-L110
224,449
ewels/MultiQC
multiqc/modules/minionqc/minionqc.py
MultiqcModule.headers_to_use
def headers_to_use(self): ''' Defines features of columns to be used in multiqc table ''' headers = OrderedDict() headers['total.reads'] = { 'title': 'Total reads', 'description': 'Total number of reads', 'format': '{:,.0f}', 'scale': 'Greys' } headers['total.gigabases'] = { 'title': 'Total bases (GB)', 'description': 'Total bases', 'format': '{:,.2f}', 'scale': 'Blues' } headers['N50.length'] = { 'title': 'Reads N50', 'description': 'Minimum read length needed to cover 50% of all reads', 'format': '{:,.0f}', 'scale': 'Purples', } headers['mean.q'] = { 'title': 'Mean Q score', 'description': 'Mean quality of reads', 'min': 0, 'max': 15, 'format': '{:,.1f}', 'hidden': True, 'scale': 'Greens', } headers['median.q'] = { 'title': 'Median Q score', 'description': 'Median quality of reads', 'min': 0, 'max': 15, 'format': '{:,.1f}', 'scale': 'Greens', } headers['mean.length'] = { 'title': 'Mean length (bp)', 'description': 'Mean read length', 'format': '{:,.0f}', 'hidden': True, 'scale': 'Blues', } headers['median.length'] = { 'title': 'Median length (bp)', 'description': 'Median read length', 'format': '{:,.0f}', 'scale': 'Blues', } # Add row ID to avoid duplicates for k in headers: h_id = re.sub('[^0-9a-zA-Z]+', '_', headers[k]['title']) headers[k]['rid'] = "rid_{}".format(h_id) return headers
python
def headers_to_use(self): ''' Defines features of columns to be used in multiqc table ''' headers = OrderedDict() headers['total.reads'] = { 'title': 'Total reads', 'description': 'Total number of reads', 'format': '{:,.0f}', 'scale': 'Greys' } headers['total.gigabases'] = { 'title': 'Total bases (GB)', 'description': 'Total bases', 'format': '{:,.2f}', 'scale': 'Blues' } headers['N50.length'] = { 'title': 'Reads N50', 'description': 'Minimum read length needed to cover 50% of all reads', 'format': '{:,.0f}', 'scale': 'Purples', } headers['mean.q'] = { 'title': 'Mean Q score', 'description': 'Mean quality of reads', 'min': 0, 'max': 15, 'format': '{:,.1f}', 'hidden': True, 'scale': 'Greens', } headers['median.q'] = { 'title': 'Median Q score', 'description': 'Median quality of reads', 'min': 0, 'max': 15, 'format': '{:,.1f}', 'scale': 'Greens', } headers['mean.length'] = { 'title': 'Mean length (bp)', 'description': 'Mean read length', 'format': '{:,.0f}', 'hidden': True, 'scale': 'Blues', } headers['median.length'] = { 'title': 'Median length (bp)', 'description': 'Median read length', 'format': '{:,.0f}', 'scale': 'Blues', } # Add row ID to avoid duplicates for k in headers: h_id = re.sub('[^0-9a-zA-Z]+', '_', headers[k]['title']) headers[k]['rid'] = "rid_{}".format(h_id) return headers
[ "def", "headers_to_use", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'total.reads'", "]", "=", "{", "'title'", ":", "'Total reads'", ",", "'description'", ":", "'Total number of reads'", ",", "'format'", ":", "'{:,.0f}'", "...
Defines features of columns to be used in multiqc table
[ "Defines", "features", "of", "columns", "to", "be", "used", "in", "multiqc", "table" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/minionqc/minionqc.py#L113-L173
224,450
ewels/MultiQC
multiqc/modules/minionqc/minionqc.py
MultiqcModule.table_qALL
def table_qALL(self): """ Table showing stats for all reads """ self.add_section ( name = 'Stats: All reads', anchor = 'minionqc-stats-qAll', description = 'MinIONQC statistics for all reads', plot = table.plot( self.minionqc_data, self.headers_to_use(), { 'namespace': 'MinIONQC', 'id': 'minionqc-stats-qAll-table', 'table_title': 'MinIONQC Stats: All reads' } ) )
python
def table_qALL(self): self.add_section ( name = 'Stats: All reads', anchor = 'minionqc-stats-qAll', description = 'MinIONQC statistics for all reads', plot = table.plot( self.minionqc_data, self.headers_to_use(), { 'namespace': 'MinIONQC', 'id': 'minionqc-stats-qAll-table', 'table_title': 'MinIONQC Stats: All reads' } ) )
[ "def", "table_qALL", "(", "self", ")", ":", "self", ".", "add_section", "(", "name", "=", "'Stats: All reads'", ",", "anchor", "=", "'minionqc-stats-qAll'", ",", "description", "=", "'MinIONQC statistics for all reads'", ",", "plot", "=", "table", ".", "plot", "...
Table showing stats for all reads
[ "Table", "showing", "stats", "for", "all", "reads" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/minionqc/minionqc.py#L176-L192
224,451
ewels/MultiQC
multiqc/modules/minionqc/minionqc.py
MultiqcModule.table_qfiltered
def table_qfiltered(self): """ Table showing stats for q-filtered reads """ description = 'MinIONQC statistics for quality filtered reads. ' + \ 'Quailty threshold used: {}.'.format(', '.join(list(self.q_threshold_list))) if len(self.q_threshold_list) > 1: description += ''' <div class="alert alert-warning"> <span class="glyphicon glyphicon-warning-sign"></span> <strong>Warning!</strong> More than one quality thresholds were present. </div> ''' log.warning('More than one quality thresholds were present. Thresholds: {}.'.format(', '.join(list(self.q_threshold_list)))) self.add_section ( name = 'Stats: Quality filtered reads', anchor = 'minionqc-stats-qFilt', description = description, plot = table.plot( self.qfilt_data, self.headers_to_use(), { 'namespace': 'MinIONQC', 'id': 'minionqc-stats-qFilt-table', 'table_title': 'MinIONQC Stats: Quality filtered reads' } ) )
python
def table_qfiltered(self): description = 'MinIONQC statistics for quality filtered reads. ' + \ 'Quailty threshold used: {}.'.format(', '.join(list(self.q_threshold_list))) if len(self.q_threshold_list) > 1: description += ''' <div class="alert alert-warning"> <span class="glyphicon glyphicon-warning-sign"></span> <strong>Warning!</strong> More than one quality thresholds were present. </div> ''' log.warning('More than one quality thresholds were present. Thresholds: {}.'.format(', '.join(list(self.q_threshold_list)))) self.add_section ( name = 'Stats: Quality filtered reads', anchor = 'minionqc-stats-qFilt', description = description, plot = table.plot( self.qfilt_data, self.headers_to_use(), { 'namespace': 'MinIONQC', 'id': 'minionqc-stats-qFilt-table', 'table_title': 'MinIONQC Stats: Quality filtered reads' } ) )
[ "def", "table_qfiltered", "(", "self", ")", ":", "description", "=", "'MinIONQC statistics for quality filtered reads. '", "+", "'Quailty threshold used: {}.'", ".", "format", "(", "', '", ".", "join", "(", "list", "(", "self", ".", "q_threshold_list", ")", ")", ")"...
Table showing stats for q-filtered reads
[ "Table", "showing", "stats", "for", "q", "-", "filtered", "reads" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/minionqc/minionqc.py#L195-L222
224,452
ewels/MultiQC
multiqc/modules/samtools/rmdup.py
RmdupReportMixin.parse_samtools_rmdup
def parse_samtools_rmdup(self): """ Find Samtools rmdup logs and parse their data """ self.samtools_rmdup = dict() for f in self.find_log_files('samtools/rmdup', filehandles=True): # Example below: # [bam_rmdupse_core] 26602816 / 103563641 = 0.2569 in library ' ' dups_regex = "\[bam_rmdups?e?_core\] (\d+) / (\d+) = (\d+\.\d+) in library '(.*)'" s_name = f['s_name'] for l in f['f']: match = re.search(dups_regex, l) if match: library_name = match.group(4).strip() if library_name != '': s_name = library_name if s_name in self.samtools_rmdup: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name)) self.add_data_source(f, s_name) self.samtools_rmdup[s_name] = dict() self.samtools_rmdup[s_name]['n_dups'] = int(match.group(1)) self.samtools_rmdup[s_name]['n_tot'] = int(match.group(2)) self.samtools_rmdup[s_name]['n_unique'] = int(match.group(2)) - int(match.group(1)) self.samtools_rmdup[s_name]['pct_dups'] = float(match.group(3))*100 # Filter to strip out ignored sample names self.samtools_rmdup = self.ignore_samples(self.samtools_rmdup) if len(self.samtools_rmdup) > 0: # Write parsed report data to a file self.write_data_file(self.samtools_rmdup, 'multiqc_samtools_rmdup') # Make a bar plot showing duplicates keys = OrderedDict() keys['n_unique'] = {'name': 'Non-duplicated reads'} keys['n_dups'] = {'name': 'Duplicated reads'} pconfig = { 'id': 'samtools_rmdup_plot', 'title': 'Samtools rmdup: Duplicate alignments', 'ylab': 'Number of reads', 'yDecimals': False } self.add_section ( name = 'Duplicates removed', anchor = 'samtools-rmdup', plot = bargraph.plot(self.samtools_rmdup, keys, pconfig) ) # Add a column to the General Stats table # General Stats Table stats_headers = OrderedDict() stats_headers['pct_dups'] = { 'title': '% Dups', 'description': 'Percent of duplicate alignments', 'min': 0, 'max': 100, 'suffix': '%', 'scale': 'OrRd' } self.general_stats_addcols(self.samtools_rmdup, stats_headers, 'Samtools rmdup') return len(self.samtools_rmdup)
python
def parse_samtools_rmdup(self): self.samtools_rmdup = dict() for f in self.find_log_files('samtools/rmdup', filehandles=True): # Example below: # [bam_rmdupse_core] 26602816 / 103563641 = 0.2569 in library ' ' dups_regex = "\[bam_rmdups?e?_core\] (\d+) / (\d+) = (\d+\.\d+) in library '(.*)'" s_name = f['s_name'] for l in f['f']: match = re.search(dups_regex, l) if match: library_name = match.group(4).strip() if library_name != '': s_name = library_name if s_name in self.samtools_rmdup: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name)) self.add_data_source(f, s_name) self.samtools_rmdup[s_name] = dict() self.samtools_rmdup[s_name]['n_dups'] = int(match.group(1)) self.samtools_rmdup[s_name]['n_tot'] = int(match.group(2)) self.samtools_rmdup[s_name]['n_unique'] = int(match.group(2)) - int(match.group(1)) self.samtools_rmdup[s_name]['pct_dups'] = float(match.group(3))*100 # Filter to strip out ignored sample names self.samtools_rmdup = self.ignore_samples(self.samtools_rmdup) if len(self.samtools_rmdup) > 0: # Write parsed report data to a file self.write_data_file(self.samtools_rmdup, 'multiqc_samtools_rmdup') # Make a bar plot showing duplicates keys = OrderedDict() keys['n_unique'] = {'name': 'Non-duplicated reads'} keys['n_dups'] = {'name': 'Duplicated reads'} pconfig = { 'id': 'samtools_rmdup_plot', 'title': 'Samtools rmdup: Duplicate alignments', 'ylab': 'Number of reads', 'yDecimals': False } self.add_section ( name = 'Duplicates removed', anchor = 'samtools-rmdup', plot = bargraph.plot(self.samtools_rmdup, keys, pconfig) ) # Add a column to the General Stats table # General Stats Table stats_headers = OrderedDict() stats_headers['pct_dups'] = { 'title': '% Dups', 'description': 'Percent of duplicate alignments', 'min': 0, 'max': 100, 'suffix': '%', 'scale': 'OrRd' } self.general_stats_addcols(self.samtools_rmdup, stats_headers, 'Samtools rmdup') return len(self.samtools_rmdup)
[ "def", "parse_samtools_rmdup", "(", "self", ")", ":", "self", ".", "samtools_rmdup", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'samtools/rmdup'", ",", "filehandles", "=", "True", ")", ":", "# Example below:", "# [bam_rmdupse...
Find Samtools rmdup logs and parse their data
[ "Find", "Samtools", "rmdup", "logs", "and", "parse", "their", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/samtools/rmdup.py#L16-L76
224,453
ewels/MultiQC
multiqc/modules/disambiguate/disambiguate.py
MultiqcModule.parse_summary
def parse_summary(self, contents): """Parses summary file into a dictionary of counts.""" lines = contents.strip().split('\n') data = {} for row in lines[1:]: split = row.strip().split('\t') sample = split[0] data[sample] = { 'species_a': int(split[1]), 'species_b': int(split[2]), 'ambiguous': int(split[3]) } return data
python
def parse_summary(self, contents): lines = contents.strip().split('\n') data = {} for row in lines[1:]: split = row.strip().split('\t') sample = split[0] data[sample] = { 'species_a': int(split[1]), 'species_b': int(split[2]), 'ambiguous': int(split[3]) } return data
[ "def", "parse_summary", "(", "self", ",", "contents", ")", ":", "lines", "=", "contents", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "data", "=", "{", "}", "for", "row", "in", "lines", "[", "1", ":", "]", ":", "split", "=", "row", ...
Parses summary file into a dictionary of counts.
[ "Parses", "summary", "file", "into", "a", "dictionary", "of", "counts", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/disambiguate/disambiguate.py#L55-L72
224,454
ewels/MultiQC
multiqc/modules/disambiguate/disambiguate.py
MultiqcModule.add_stats_table
def add_stats_table(self): """Adds stats to general table.""" totals = {sample: sum(counts.values()) for sample, counts in self.data.items()} percentages = {sample: {k: (v / totals[sample]) * 100 for k, v in counts.items()} for sample, counts in self.data.items()} headers = { 'species_a': { 'title': '% Species a', 'description': 'Percentage of reads mapping to species a', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } } self.general_stats_addcols(percentages, headers)
python
def add_stats_table(self): totals = {sample: sum(counts.values()) for sample, counts in self.data.items()} percentages = {sample: {k: (v / totals[sample]) * 100 for k, v in counts.items()} for sample, counts in self.data.items()} headers = { 'species_a': { 'title': '% Species a', 'description': 'Percentage of reads mapping to species a', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } } self.general_stats_addcols(percentages, headers)
[ "def", "add_stats_table", "(", "self", ")", ":", "totals", "=", "{", "sample", ":", "sum", "(", "counts", ".", "values", "(", ")", ")", "for", "sample", ",", "counts", "in", "self", ".", "data", ".", "items", "(", ")", "}", "percentages", "=", "{",...
Adds stats to general table.
[ "Adds", "stats", "to", "general", "table", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/disambiguate/disambiguate.py#L75-L96
224,455
ewels/MultiQC
multiqc/modules/disambiguate/disambiguate.py
MultiqcModule.add_stats_plot
def add_stats_plot(self): """Plots alignment stats as bargraph.""" keys = OrderedDict() keys['species_a'] = {'color': '#437bb1', 'name': 'Species a'} keys['species_b'] = {'color': '#b1084c', 'name': 'Species b'} keys['ambiguous'] = {'color': '#333333', 'name': 'Ambiguous'} plot_config = { 'id': "disambiguated_alignments", 'title': "Disambiguate: Alignment Counts", 'cpswitch_counts_label': "# Reads", 'ylab': "# Reads" } self.add_section( plot=bargraph.plot(self.data, keys, plot_config) )
python
def add_stats_plot(self): keys = OrderedDict() keys['species_a'] = {'color': '#437bb1', 'name': 'Species a'} keys['species_b'] = {'color': '#b1084c', 'name': 'Species b'} keys['ambiguous'] = {'color': '#333333', 'name': 'Ambiguous'} plot_config = { 'id': "disambiguated_alignments", 'title': "Disambiguate: Alignment Counts", 'cpswitch_counts_label': "# Reads", 'ylab': "# Reads" } self.add_section( plot=bargraph.plot(self.data, keys, plot_config) )
[ "def", "add_stats_plot", "(", "self", ")", ":", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'species_a'", "]", "=", "{", "'color'", ":", "'#437bb1'", ",", "'name'", ":", "'Species a'", "}", "keys", "[", "'species_b'", "]", "=", "{", "'color'", ...
Plots alignment stats as bargraph.
[ "Plots", "alignment", "stats", "as", "bargraph", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/disambiguate/disambiguate.py#L104-L121
224,456
ewels/MultiQC
multiqc/modules/htseq/htseq.py
MultiqcModule.parse_htseq_report
def parse_htseq_report (self, f): """ Parse the HTSeq Count log file. """ keys = [ '__no_feature', '__ambiguous', '__too_low_aQual', '__not_aligned', '__alignment_not_unique' ] parsed_data = dict() assigned_counts = 0 for l in f['f']: s = l.split("\t") if s[0] in keys: parsed_data[s[0][2:]] = int(s[-1]) else: try: assigned_counts += int(s[-1]) except (ValueError, IndexError): pass if len(parsed_data) > 0: parsed_data['assigned'] = assigned_counts parsed_data['total_count'] = sum([v for v in parsed_data.values()]) parsed_data['percent_assigned'] = (float(parsed_data['assigned']) / float(parsed_data['total_count'])) * 100.0 return parsed_data return None
python
def parse_htseq_report (self, f): keys = [ '__no_feature', '__ambiguous', '__too_low_aQual', '__not_aligned', '__alignment_not_unique' ] parsed_data = dict() assigned_counts = 0 for l in f['f']: s = l.split("\t") if s[0] in keys: parsed_data[s[0][2:]] = int(s[-1]) else: try: assigned_counts += int(s[-1]) except (ValueError, IndexError): pass if len(parsed_data) > 0: parsed_data['assigned'] = assigned_counts parsed_data['total_count'] = sum([v for v in parsed_data.values()]) parsed_data['percent_assigned'] = (float(parsed_data['assigned']) / float(parsed_data['total_count'])) * 100.0 return parsed_data return None
[ "def", "parse_htseq_report", "(", "self", ",", "f", ")", ":", "keys", "=", "[", "'__no_feature'", ",", "'__ambiguous'", ",", "'__too_low_aQual'", ",", "'__not_aligned'", ",", "'__alignment_not_unique'", "]", "parsed_data", "=", "dict", "(", ")", "assigned_counts",...
Parse the HTSeq Count log file.
[ "Parse", "the", "HTSeq", "Count", "log", "file", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/htseq/htseq.py#L53-L72
224,457
ewels/MultiQC
multiqc/modules/htseq/htseq.py
MultiqcModule.htseq_stats_table
def htseq_stats_table(self): """ Take the parsed stats from the HTSeq Count report and add them to the basic stats table at the top of the report """ headers = OrderedDict() headers['percent_assigned'] = { 'title': '% Assigned', 'description': '% Assigned reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn' } headers['assigned'] = { 'title': '{} Assigned'.format(config.read_count_prefix), 'description': 'Assigned Reads ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuBu', 'modify': lambda x: float(x) * config.read_count_multiplier, 'shared_key': 'read_count' } self.general_stats_addcols(self.htseq_data, headers)
python
def htseq_stats_table(self): headers = OrderedDict() headers['percent_assigned'] = { 'title': '% Assigned', 'description': '% Assigned reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn' } headers['assigned'] = { 'title': '{} Assigned'.format(config.read_count_prefix), 'description': 'Assigned Reads ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuBu', 'modify': lambda x: float(x) * config.read_count_multiplier, 'shared_key': 'read_count' } self.general_stats_addcols(self.htseq_data, headers)
[ "def", "htseq_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'percent_assigned'", "]", "=", "{", "'title'", ":", "'% Assigned'", ",", "'description'", ":", "'% Assigned reads'", ",", "'max'", ":", "100", ",", "...
Take the parsed stats from the HTSeq Count report and add them to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "HTSeq", "Count", "report", "and", "add", "them", "to", "the", "basic", "stats", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/htseq/htseq.py#L75-L96
224,458
ewels/MultiQC
multiqc/modules/htseq/htseq.py
MultiqcModule.htseq_counts_chart
def htseq_counts_chart (self): """ Make the HTSeq Count assignment rates plot """ cats = OrderedDict() cats['assigned'] = { 'name': 'Assigned' } cats['ambiguous'] = { 'name': 'Ambiguous' } cats['alignment_not_unique'] = { 'name': 'Alignment Not Unique' } cats['no_feature'] = { 'name': 'No Feature' } cats['too_low_aQual'] = { 'name': 'Too Low aQual' } cats['not_aligned'] = { 'name': 'Not Aligned' } config = { 'id': 'htseq_assignment_plot', 'title': 'HTSeq: Count Assignments', 'ylab': '# Reads', 'hide_zero_cats': False, 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(self.htseq_data, cats, config)
python
def htseq_counts_chart (self): cats = OrderedDict() cats['assigned'] = { 'name': 'Assigned' } cats['ambiguous'] = { 'name': 'Ambiguous' } cats['alignment_not_unique'] = { 'name': 'Alignment Not Unique' } cats['no_feature'] = { 'name': 'No Feature' } cats['too_low_aQual'] = { 'name': 'Too Low aQual' } cats['not_aligned'] = { 'name': 'Not Aligned' } config = { 'id': 'htseq_assignment_plot', 'title': 'HTSeq: Count Assignments', 'ylab': '# Reads', 'hide_zero_cats': False, 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(self.htseq_data, cats, config)
[ "def", "htseq_counts_chart", "(", "self", ")", ":", "cats", "=", "OrderedDict", "(", ")", "cats", "[", "'assigned'", "]", "=", "{", "'name'", ":", "'Assigned'", "}", "cats", "[", "'ambiguous'", "]", "=", "{", "'name'", ":", "'Ambiguous'", "}", "cats", ...
Make the HTSeq Count assignment rates plot
[ "Make", "the", "HTSeq", "Count", "assignment", "rates", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/htseq/htseq.py#L99-L115
224,459
ewels/MultiQC
multiqc/modules/verifybamid/verifybamid.py
MultiqcModule.parse_selfsm
def parse_selfsm(self, f): """ Go through selfSM file and create a dictionary with the sample name as a key, """ #create a dictionary to populate from this sample's file parsed_data = dict() # set a empty variable which denotes if the headers have been read headers = None # for each line in the file for l in f['f'].splitlines(): # split the line on tab s = l.split("\t") # if we haven't already read the header line if headers is None: # assign this list to headers variable headers = s # for all rows after the first else: # clean the sample name (first column) and assign to s_name s_name = self.clean_s_name(s[0], f['root']) # create a dictionary entry with the first column as a key (sample name) and empty dictionary as a value parsed_data[s_name] = {} # for each item in list of items in the row for i, v in enumerate(s): # if it's not the first element (if it's not the name) if i != 0: # see if CHIP is in the column header and the value is not NA if "CHIP" in [headers[i]] and v != "NA": # set hide_chip_columns = False so they are not hidden self.hide_chip_columns=False # try and convert the value into a float try: # and add to the dictionary the key as the corrsponding item from the header and the value from the list parsed_data[s_name][headers[i]] = float(v) #if can't convert to float... except ValueError: # add to the dictionary the key as the corrsponding item from the header and the value from the list parsed_data[s_name][headers[i]] = v # else return the dictionary return parsed_data
python
def parse_selfsm(self, f): #create a dictionary to populate from this sample's file parsed_data = dict() # set a empty variable which denotes if the headers have been read headers = None # for each line in the file for l in f['f'].splitlines(): # split the line on tab s = l.split("\t") # if we haven't already read the header line if headers is None: # assign this list to headers variable headers = s # for all rows after the first else: # clean the sample name (first column) and assign to s_name s_name = self.clean_s_name(s[0], f['root']) # create a dictionary entry with the first column as a key (sample name) and empty dictionary as a value parsed_data[s_name] = {} # for each item in list of items in the row for i, v in enumerate(s): # if it's not the first element (if it's not the name) if i != 0: # see if CHIP is in the column header and the value is not NA if "CHIP" in [headers[i]] and v != "NA": # set hide_chip_columns = False so they are not hidden self.hide_chip_columns=False # try and convert the value into a float try: # and add to the dictionary the key as the corrsponding item from the header and the value from the list parsed_data[s_name][headers[i]] = float(v) #if can't convert to float... except ValueError: # add to the dictionary the key as the corrsponding item from the header and the value from the list parsed_data[s_name][headers[i]] = v # else return the dictionary return parsed_data
[ "def", "parse_selfsm", "(", "self", ",", "f", ")", ":", "#create a dictionary to populate from this sample's file", "parsed_data", "=", "dict", "(", ")", "# set a empty variable which denotes if the headers have been read", "headers", "=", "None", "# for each line in the file", ...
Go through selfSM file and create a dictionary with the sample name as a key,
[ "Go", "through", "selfSM", "file", "and", "create", "a", "dictionary", "with", "the", "sample", "name", "as", "a", "key" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/verifybamid/verifybamid.py#L78-L116
224,460
ewels/MultiQC
multiqc/modules/hisat2/hisat2.py
MultiqcModule.hisat2_general_stats_table
def hisat2_general_stats_table(self): """ Take the parsed stats from the HISAT2 report and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['overall_alignment_rate'] = { 'title': '% Aligned', 'description': 'overall alignment rate', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } self.general_stats_addcols(self.hisat2_data, headers)
python
def hisat2_general_stats_table(self): headers = OrderedDict() headers['overall_alignment_rate'] = { 'title': '% Aligned', 'description': 'overall alignment rate', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } self.general_stats_addcols(self.hisat2_data, headers)
[ "def", "hisat2_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'overall_alignment_rate'", "]", "=", "{", "'title'", ":", "'% Aligned'", ",", "'description'", ":", "'overall alignment rate'", ",", "'max'", ":",...
Take the parsed stats from the HISAT2 report and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "HISAT2", "report", "and", "add", "it", "to", "the", "basic", "stats", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hisat2/hisat2.py#L108-L121
224,461
ewels/MultiQC
multiqc/modules/base_module.py
BaseMultiqcModule.add_section
def add_section(self, name=None, anchor=None, description='', comment='', helptext='', plot='', content='', autoformat=True, autoformat_type='markdown'): """ Add a section to the module report output """ # Default anchor if anchor is None: if name is not None: nid = name.lower().strip().replace(' ','-') anchor = '{}-{}'.format(self.anchor, nid) else: sl = len(self.sections) + 1 anchor = '{}-section-{}'.format(self.anchor, sl) # Skip if user has a config to remove this module section if anchor in config.remove_sections: logger.debug("Skipping section '{}' because specified in user config".format(anchor)) return # Sanitise anchor ID and check for duplicates anchor = report.save_htmlid(anchor) # See if we have a user comment in the config if anchor in config.section_comments: comment = config.section_comments[anchor] # Format the content if autoformat: if len(description) > 0: description = textwrap.dedent(description) if autoformat_type == 'markdown': description = markdown.markdown(description) if len(comment) > 0: comment = textwrap.dedent(comment) if autoformat_type == 'markdown': comment = markdown.markdown(comment) if len(helptext) > 0: helptext = textwrap.dedent(helptext) if autoformat_type == 'markdown': helptext = markdown.markdown(helptext) # Strip excess whitespace description = description.strip() comment = comment.strip() helptext = helptext.strip() self.sections.append({ 'name': name, 'anchor': anchor, 'description': description, 'comment': comment, 'helptext': helptext, 'plot': plot, 'content': content, 'print_section': any([ n is not None and len(n) > 0 for n in [description, comment, helptext, plot, content] ]) })
python
def add_section(self, name=None, anchor=None, description='', comment='', helptext='', plot='', content='', autoformat=True, autoformat_type='markdown'): # Default anchor if anchor is None: if name is not None: nid = name.lower().strip().replace(' ','-') anchor = '{}-{}'.format(self.anchor, nid) else: sl = len(self.sections) + 1 anchor = '{}-section-{}'.format(self.anchor, sl) # Skip if user has a config to remove this module section if anchor in config.remove_sections: logger.debug("Skipping section '{}' because specified in user config".format(anchor)) return # Sanitise anchor ID and check for duplicates anchor = report.save_htmlid(anchor) # See if we have a user comment in the config if anchor in config.section_comments: comment = config.section_comments[anchor] # Format the content if autoformat: if len(description) > 0: description = textwrap.dedent(description) if autoformat_type == 'markdown': description = markdown.markdown(description) if len(comment) > 0: comment = textwrap.dedent(comment) if autoformat_type == 'markdown': comment = markdown.markdown(comment) if len(helptext) > 0: helptext = textwrap.dedent(helptext) if autoformat_type == 'markdown': helptext = markdown.markdown(helptext) # Strip excess whitespace description = description.strip() comment = comment.strip() helptext = helptext.strip() self.sections.append({ 'name': name, 'anchor': anchor, 'description': description, 'comment': comment, 'helptext': helptext, 'plot': plot, 'content': content, 'print_section': any([ n is not None and len(n) > 0 for n in [description, comment, helptext, plot, content] ]) })
[ "def", "add_section", "(", "self", ",", "name", "=", "None", ",", "anchor", "=", "None", ",", "description", "=", "''", ",", "comment", "=", "''", ",", "helptext", "=", "''", ",", "plot", "=", "''", ",", "content", "=", "''", ",", "autoformat", "="...
Add a section to the module report output
[ "Add", "a", "section", "to", "the", "module", "report", "output" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/base_module.py#L140-L193
224,462
ewels/MultiQC
multiqc/modules/base_module.py
BaseMultiqcModule.ignore_samples
def ignore_samples(self, data): """ Strip out samples which match `sample_names_ignore` """ try: if isinstance(data, OrderedDict): newdata = OrderedDict() elif isinstance(data, dict): newdata = dict() else: return data for k,v in data.items(): # Match ignore glob patterns glob_match = any( fnmatch.fnmatch(k, sn) for sn in config.sample_names_ignore ) re_match = any( re.match(sn, k) for sn in config.sample_names_ignore_re ) if not glob_match and not re_match: newdata[k] = v return newdata except (TypeError, AttributeError): return data
python
def ignore_samples(self, data): try: if isinstance(data, OrderedDict): newdata = OrderedDict() elif isinstance(data, dict): newdata = dict() else: return data for k,v in data.items(): # Match ignore glob patterns glob_match = any( fnmatch.fnmatch(k, sn) for sn in config.sample_names_ignore ) re_match = any( re.match(sn, k) for sn in config.sample_names_ignore_re ) if not glob_match and not re_match: newdata[k] = v return newdata except (TypeError, AttributeError): return data
[ "def", "ignore_samples", "(", "self", ",", "data", ")", ":", "try", ":", "if", "isinstance", "(", "data", ",", "OrderedDict", ")", ":", "newdata", "=", "OrderedDict", "(", ")", "elif", "isinstance", "(", "data", ",", "dict", ")", ":", "newdata", "=", ...
Strip out samples which match `sample_names_ignore`
[ "Strip", "out", "samples", "which", "match", "sample_names_ignore" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/base_module.py#L254-L271
224,463
ewels/MultiQC
multiqc/modules/samtools/idxstats.py
parse_single_report
def parse_single_report(f): """ Parse a samtools idxstats idxstats """ parsed_data = OrderedDict() for l in f.splitlines(): s = l.split("\t") try: parsed_data[s[0]] = int(s[2]) except (IndexError, ValueError): pass return parsed_data
python
def parse_single_report(f): parsed_data = OrderedDict() for l in f.splitlines(): s = l.split("\t") try: parsed_data[s[0]] = int(s[2]) except (IndexError, ValueError): pass return parsed_data
[ "def", "parse_single_report", "(", "f", ")", ":", "parsed_data", "=", "OrderedDict", "(", ")", "for", "l", "in", "f", ".", "splitlines", "(", ")", ":", "s", "=", "l", ".", "split", "(", "\"\\t\"", ")", "try", ":", "parsed_data", "[", "s", "[", "0",...
Parse a samtools idxstats idxstats
[ "Parse", "a", "samtools", "idxstats", "idxstats" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/samtools/idxstats.py#L154-L164
224,464
ewels/MultiQC
multiqc/modules/hicexplorer/hicexplorer.py
MultiqcModule.parse_logs
def parse_logs(self, f): """Parse a given HiCExplorer log file from hicBuildMatrix.""" data = {} for l in f.splitlines(): # catch empty lines if len(l) == 0: continue s = l.split("\t") data_ = [] # catch lines with descriptive content: "Of pairs used:" for i in s[1:]: if len(i) == 0: continue try: i.replace('(', '') i.replace(')', '') i.replace(',', '') data_.append(float(i)) except ValueError: data_.append(i) if len(data_) == 0: continue if s[0].startswith('short range'): s[0] = 'short range' elif s[0].startswith('same fragment'): s[0] = 'same fragment' s[0] = s[0].capitalize() data[s[0]] = data_ return data
python
def parse_logs(self, f): data = {} for l in f.splitlines(): # catch empty lines if len(l) == 0: continue s = l.split("\t") data_ = [] # catch lines with descriptive content: "Of pairs used:" for i in s[1:]: if len(i) == 0: continue try: i.replace('(', '') i.replace(')', '') i.replace(',', '') data_.append(float(i)) except ValueError: data_.append(i) if len(data_) == 0: continue if s[0].startswith('short range'): s[0] = 'short range' elif s[0].startswith('same fragment'): s[0] = 'same fragment' s[0] = s[0].capitalize() data[s[0]] = data_ return data
[ "def", "parse_logs", "(", "self", ",", "f", ")", ":", "data", "=", "{", "}", "for", "l", "in", "f", ".", "splitlines", "(", ")", ":", "# catch empty lines", "if", "len", "(", "l", ")", "==", "0", ":", "continue", "s", "=", "l", ".", "split", "(...
Parse a given HiCExplorer log file from hicBuildMatrix.
[ "Parse", "a", "given", "HiCExplorer", "log", "file", "from", "hicBuildMatrix", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicexplorer/hicexplorer.py#L132-L161
224,465
ewels/MultiQC
multiqc/modules/hicexplorer/hicexplorer.py
MultiqcModule.hicexplorer_basic_statistics
def hicexplorer_basic_statistics(self): """Create the general statistics for HiCExplorer.""" data = {} for file in self.mod_data: max_distance_key = 'Max rest. site distance' total_pairs = self.mod_data[file]['Pairs considered'][0] try: self.mod_data[file][max_distance_key][0] except KeyError: max_distance_key = 'Max library insert size' data_ = { 'Pairs considered': self.mod_data[file]['Pairs considered'][0], 'Pairs used': self.mod_data[file]['Pairs used'][0] / total_pairs, 'Mapped': self.mod_data[file]['One mate unmapped'][0] / total_pairs, 'Min rest. site distance': self.mod_data[file]['Min rest. site distance'][0], max_distance_key: self.mod_data[file][max_distance_key][0], } data[self.mod_data[file]['File'][0]] = data_ headers = OrderedDict() headers['Pairs considered'] = { 'title': '{} Pairs'.format(config.read_count_prefix), 'description': 'Total number of read pairs ({})'.format(config.read_count_desc), 'shared_key': 'read_count' } headers['Pairs used'] = { 'title': '% Used pairs', 'max': 100, 'min': 0, 'modify': lambda x: x * 100, 'suffix': '%' } headers['Mapped'] = { 'title': '% Mapped', 'max': 100, 'min': 0, 'modify': lambda x: (1 - x) * 100, 'scale': 'RdYlGn', 'suffix': '%' } headers['Min rest. site distance'] = { 'title': 'Min RE dist', 'description': 'Minimum restriction site distance (bp)', 'format': '{:.0f}', 'suffix': ' bp' } headers[max_distance_key] = { 'title': 'Max RE dist', 'description': max_distance_key + ' (bp)', 'format': '{:.0f}', 'suffix': ' bp' } self.general_stats_addcols(data, headers)
python
def hicexplorer_basic_statistics(self): data = {} for file in self.mod_data: max_distance_key = 'Max rest. site distance' total_pairs = self.mod_data[file]['Pairs considered'][0] try: self.mod_data[file][max_distance_key][0] except KeyError: max_distance_key = 'Max library insert size' data_ = { 'Pairs considered': self.mod_data[file]['Pairs considered'][0], 'Pairs used': self.mod_data[file]['Pairs used'][0] / total_pairs, 'Mapped': self.mod_data[file]['One mate unmapped'][0] / total_pairs, 'Min rest. site distance': self.mod_data[file]['Min rest. site distance'][0], max_distance_key: self.mod_data[file][max_distance_key][0], } data[self.mod_data[file]['File'][0]] = data_ headers = OrderedDict() headers['Pairs considered'] = { 'title': '{} Pairs'.format(config.read_count_prefix), 'description': 'Total number of read pairs ({})'.format(config.read_count_desc), 'shared_key': 'read_count' } headers['Pairs used'] = { 'title': '% Used pairs', 'max': 100, 'min': 0, 'modify': lambda x: x * 100, 'suffix': '%' } headers['Mapped'] = { 'title': '% Mapped', 'max': 100, 'min': 0, 'modify': lambda x: (1 - x) * 100, 'scale': 'RdYlGn', 'suffix': '%' } headers['Min rest. site distance'] = { 'title': 'Min RE dist', 'description': 'Minimum restriction site distance (bp)', 'format': '{:.0f}', 'suffix': ' bp' } headers[max_distance_key] = { 'title': 'Max RE dist', 'description': max_distance_key + ' (bp)', 'format': '{:.0f}', 'suffix': ' bp' } self.general_stats_addcols(data, headers)
[ "def", "hicexplorer_basic_statistics", "(", "self", ")", ":", "data", "=", "{", "}", "for", "file", "in", "self", ".", "mod_data", ":", "max_distance_key", "=", "'Max rest. site distance'", "total_pairs", "=", "self", ".", "mod_data", "[", "file", "]", "[", ...
Create the general statistics for HiCExplorer.
[ "Create", "the", "general", "statistics", "for", "HiCExplorer", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicexplorer/hicexplorer.py#L163-L215
224,466
ewels/MultiQC
multiqc/modules/hicexplorer/hicexplorer.py
MultiqcModule.hicexplorer_create_plot
def hicexplorer_create_plot(self, pKeyList, pTitle, pId): """Create the graphics containing information about the read quality.""" keys = OrderedDict() for i, key_ in enumerate(pKeyList): keys[key_] = {'color': self.colors[i]} data = {} for data_ in self.mod_data: data['{}'.format(self.mod_data[data_]['File'][0])] = {} for key_ in pKeyList: data['{}'.format(self.mod_data[data_]['File'][0])][key_] = self.mod_data[data_][key_][0] config = { 'id': 'hicexplorer_' + pId + '_plot', 'title': pTitle, 'ylab': 'Number of Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(data, keys, config)
python
def hicexplorer_create_plot(self, pKeyList, pTitle, pId): keys = OrderedDict() for i, key_ in enumerate(pKeyList): keys[key_] = {'color': self.colors[i]} data = {} for data_ in self.mod_data: data['{}'.format(self.mod_data[data_]['File'][0])] = {} for key_ in pKeyList: data['{}'.format(self.mod_data[data_]['File'][0])][key_] = self.mod_data[data_][key_][0] config = { 'id': 'hicexplorer_' + pId + '_plot', 'title': pTitle, 'ylab': 'Number of Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(data, keys, config)
[ "def", "hicexplorer_create_plot", "(", "self", ",", "pKeyList", ",", "pTitle", ",", "pId", ")", ":", "keys", "=", "OrderedDict", "(", ")", "for", "i", ",", "key_", "in", "enumerate", "(", "pKeyList", ")", ":", "keys", "[", "key_", "]", "=", "{", "'co...
Create the graphics containing information about the read quality.
[ "Create", "the", "graphics", "containing", "information", "about", "the", "read", "quality", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicexplorer/hicexplorer.py#L217-L239
224,467
ewels/MultiQC
multiqc/modules/clusterflow/clusterflow.py
MultiqcModule.parse_clusterflow_logs
def parse_clusterflow_logs(self, f): """ Parse Clusterflow logs """ module = None job_id = None pipeline_id = None for l in f['f']: # Get pipeline ID module_r = re.match(r'Module:\s+(.+)$', l) if module_r: module = module_r.group(1) job_id_r = re.match(r'Job ID:\s+(.+)$', l) if job_id_r: job_id = job_id_r.group(1) if module is not None: pipeline_r = re.match(r"(cf_.+)_"+re.escape(module)+r"_\d+$", job_id) if pipeline_r: pipeline_id = pipeline_r.group(1) # Get commands that have been run if l.startswith('###CFCMD'): if pipeline_id is None: pipeline_id = 'unknown' if pipeline_id not in self.clusterflow_commands.keys(): self.clusterflow_commands[pipeline_id] = list() self.clusterflow_commands[pipeline_id].append(l[8:])
python
def parse_clusterflow_logs(self, f): module = None job_id = None pipeline_id = None for l in f['f']: # Get pipeline ID module_r = re.match(r'Module:\s+(.+)$', l) if module_r: module = module_r.group(1) job_id_r = re.match(r'Job ID:\s+(.+)$', l) if job_id_r: job_id = job_id_r.group(1) if module is not None: pipeline_r = re.match(r"(cf_.+)_"+re.escape(module)+r"_\d+$", job_id) if pipeline_r: pipeline_id = pipeline_r.group(1) # Get commands that have been run if l.startswith('###CFCMD'): if pipeline_id is None: pipeline_id = 'unknown' if pipeline_id not in self.clusterflow_commands.keys(): self.clusterflow_commands[pipeline_id] = list() self.clusterflow_commands[pipeline_id].append(l[8:])
[ "def", "parse_clusterflow_logs", "(", "self", ",", "f", ")", ":", "module", "=", "None", "job_id", "=", "None", "pipeline_id", "=", "None", "for", "l", "in", "f", "[", "'f'", "]", ":", "# Get pipeline ID", "module_r", "=", "re", ".", "match", "(", "r'M...
Parse Clusterflow logs
[ "Parse", "Clusterflow", "logs" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/clusterflow/clusterflow.py#L68-L93
224,468
ewels/MultiQC
multiqc/modules/clusterflow/clusterflow.py
MultiqcModule.clusterflow_commands_table
def clusterflow_commands_table (self): """ Make a table of the Cluster Flow commands """ # I wrote this when I was tired. Sorry if it's incomprehensible. desc = '''Every Cluster Flow run will have many different commands. MultiQC splits these by whitespace, collects by the tool name and shows the first command found. Any terms not found in <em>all</em> subsequent calls are replaced with <code>[variable]</code> <em>(typically input and ouput filenames)</em>. Each column is for one Cluster Flow run.''' # Loop through pipelines tool_cmds = OrderedDict() headers = dict() for pipeline_id, commands in self.clusterflow_commands.items(): headers[pipeline_id] = {'scale': False} self.var_html = '<span style="background-color:#dedede; color:#999;">[variable]</span>' tool_cmd_parts = OrderedDict() for cmd in commands: s = cmd.split() tool = self._guess_cmd_name(s) if tool not in tool_cmd_parts.keys(): tool_cmd_parts[tool] = list() tool_cmd_parts[tool].append(s) for tool, cmds in tool_cmd_parts.items(): cons_cmd = self._replace_variable_chunks(cmds) # Try again with first two blocks if all variable variable_count = cons_cmd.count(self.var_html) if variable_count == len(cmds[0]) - 1 and len(cmds[0]) > 2: for subcmd in set([x[1] for x in cmds]): sub_cons_cmd = self._replace_variable_chunks([cmd for cmd in cmds if cmd[1] == subcmd]) tool = "{} {}".format(tool, subcmd) if tool not in tool_cmds: tool_cmds[tool] = dict() tool_cmds[tool][pipeline_id] = '<code style="white-space:nowrap;">{}</code>'.format(" ".join(sub_cons_cmd) ) else: if tool not in tool_cmds: tool_cmds[tool] = dict() tool_cmds[tool][pipeline_id] = '<code style="white-space:nowrap;">{}</code>'.format(" ".join(cons_cmd) ) table_config = { 'namespace': 'Cluster Flow', 'id': 'clusterflow-commands-table', 'table_title': 'Cluster Flow Commands', 'col1_header': 'Tool', 'sortRows': False, 'no_beeswarm': True } self.add_section ( name = 'Commands', anchor = 'clusterflow-commands', description = desc, plot = table.plot(tool_cmds, headers, table_config) )
python
def clusterflow_commands_table (self): # I wrote this when I was tired. Sorry if it's incomprehensible. desc = '''Every Cluster Flow run will have many different commands. MultiQC splits these by whitespace, collects by the tool name and shows the first command found. Any terms not found in <em>all</em> subsequent calls are replaced with <code>[variable]</code> <em>(typically input and ouput filenames)</em>. Each column is for one Cluster Flow run.''' # Loop through pipelines tool_cmds = OrderedDict() headers = dict() for pipeline_id, commands in self.clusterflow_commands.items(): headers[pipeline_id] = {'scale': False} self.var_html = '<span style="background-color:#dedede; color:#999;">[variable]</span>' tool_cmd_parts = OrderedDict() for cmd in commands: s = cmd.split() tool = self._guess_cmd_name(s) if tool not in tool_cmd_parts.keys(): tool_cmd_parts[tool] = list() tool_cmd_parts[tool].append(s) for tool, cmds in tool_cmd_parts.items(): cons_cmd = self._replace_variable_chunks(cmds) # Try again with first two blocks if all variable variable_count = cons_cmd.count(self.var_html) if variable_count == len(cmds[0]) - 1 and len(cmds[0]) > 2: for subcmd in set([x[1] for x in cmds]): sub_cons_cmd = self._replace_variable_chunks([cmd for cmd in cmds if cmd[1] == subcmd]) tool = "{} {}".format(tool, subcmd) if tool not in tool_cmds: tool_cmds[tool] = dict() tool_cmds[tool][pipeline_id] = '<code style="white-space:nowrap;">{}</code>'.format(" ".join(sub_cons_cmd) ) else: if tool not in tool_cmds: tool_cmds[tool] = dict() tool_cmds[tool][pipeline_id] = '<code style="white-space:nowrap;">{}</code>'.format(" ".join(cons_cmd) ) table_config = { 'namespace': 'Cluster Flow', 'id': 'clusterflow-commands-table', 'table_title': 'Cluster Flow Commands', 'col1_header': 'Tool', 'sortRows': False, 'no_beeswarm': True } self.add_section ( name = 'Commands', anchor = 'clusterflow-commands', description = desc, plot = table.plot(tool_cmds, headers, table_config) )
[ "def", "clusterflow_commands_table", "(", "self", ")", ":", "# I wrote this when I was tired. Sorry if it's incomprehensible.", "desc", "=", "'''Every Cluster Flow run will have many different commands.\n MultiQC splits these by whitespace, collects by the tool name\n and sho...
Make a table of the Cluster Flow commands
[ "Make", "a", "table", "of", "the", "Cluster", "Flow", "commands" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/clusterflow/clusterflow.py#L96-L151
224,469
ewels/MultiQC
multiqc/modules/clusterflow/clusterflow.py
MultiqcModule._replace_variable_chunks
def _replace_variable_chunks(self, cmds): """ List through a list of command chunks. Return a single list with any variable bits blanked out. """ cons_cmd = None while cons_cmd is None: for cmd in cmds: if cons_cmd is None: cons_cmd = cmd[:] else: for idx, s in enumerate(cons_cmd): if s not in cmd: cons_cmd[idx] = self.var_html return cons_cmd
python
def _replace_variable_chunks(self, cmds): cons_cmd = None while cons_cmd is None: for cmd in cmds: if cons_cmd is None: cons_cmd = cmd[:] else: for idx, s in enumerate(cons_cmd): if s not in cmd: cons_cmd[idx] = self.var_html return cons_cmd
[ "def", "_replace_variable_chunks", "(", "self", ",", "cmds", ")", ":", "cons_cmd", "=", "None", "while", "cons_cmd", "is", "None", ":", "for", "cmd", "in", "cmds", ":", "if", "cons_cmd", "is", "None", ":", "cons_cmd", "=", "cmd", "[", ":", "]", "else",...
List through a list of command chunks. Return a single list with any variable bits blanked out.
[ "List", "through", "a", "list", "of", "command", "chunks", ".", "Return", "a", "single", "list", "with", "any", "variable", "bits", "blanked", "out", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/clusterflow/clusterflow.py#L154-L167
224,470
ewels/MultiQC
multiqc/modules/clusterflow/clusterflow.py
MultiqcModule._guess_cmd_name
def _guess_cmd_name(self, cmd): """ Manually guess some known command names, where we can do a better job than the automatic parsing. """ # zcat to bowtie if cmd[0] == 'zcat' and 'bowtie' in cmd: return 'bowtie' # samtools if cmd[0] == 'samtools': return ' '.join(cmd[0:2]) # java (eg. picard) if cmd[0] == 'java': jars = [s for s in cmd if '.jar' in s] return os.path.basename(jars[0].replace('.jar', '')) return cmd[0]
python
def _guess_cmd_name(self, cmd): # zcat to bowtie if cmd[0] == 'zcat' and 'bowtie' in cmd: return 'bowtie' # samtools if cmd[0] == 'samtools': return ' '.join(cmd[0:2]) # java (eg. picard) if cmd[0] == 'java': jars = [s for s in cmd if '.jar' in s] return os.path.basename(jars[0].replace('.jar', '')) return cmd[0]
[ "def", "_guess_cmd_name", "(", "self", ",", "cmd", ")", ":", "# zcat to bowtie", "if", "cmd", "[", "0", "]", "==", "'zcat'", "and", "'bowtie'", "in", "cmd", ":", "return", "'bowtie'", "# samtools", "if", "cmd", "[", "0", "]", "==", "'samtools'", ":", "...
Manually guess some known command names, where we can do a better job than the automatic parsing.
[ "Manually", "guess", "some", "known", "command", "names", "where", "we", "can", "do", "a", "better", "job", "than", "the", "automatic", "parsing", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/clusterflow/clusterflow.py#L169-L183
224,471
ewels/MultiQC
multiqc/modules/clusterflow/clusterflow.py
MultiqcModule.clusterflow_pipelines_section
def clusterflow_pipelines_section(self): """ Generate HTML for section about pipelines, generated from information parsed from run files. """ data = dict() pids_guessed = '' for f,d in self.clusterflow_runfiles.items(): pid = d.get('pipeline_id', 'unknown') if d.get('pipeline_id_guess', False) is True: pid += '*' pids_guessed = ' Project IDs with an asterisk may be inaccurate.' # Count the number of files going into the first module num_starting_files = 0 for step_name, files in d.get('files',{}).items(): if step_name.startswith('start'): num_starting_files += len(files) # Reformat the date so that column sorting works nicely if 'pipeline_start_dateparts' in d: dt = d['pipeline_start_dateparts'] d['pipeline_start'] = '{}-{:02d}-{:02d} {:02d}:{:02d}'.format(dt['year'], dt['month'], dt['day'], dt['hour'], dt['minute']) if pid not in data: data[pid] = d data[pid]['num_starting_files'] = int(num_starting_files) else: data[pid]['num_starting_files'] += int(num_starting_files) headers = OrderedDict() headers['pipeline_name'] = {'title': 'Pipeline Name'} headers['pipeline_start'] = {'title': 'Date Started', 'description': 'Date and time that pipeline was started (YYYY-MM-DD HH:SS)'} headers['genome'] = {'title': 'Genome ID', 'description': 'ID of reference genome used'} headers['num_starting_files'] = {'title': '# Starting Files', 'format': '{:,.0f}', 'description': 'Number of input files at start of pipeline run.'} table_config = { 'namespace': 'Cluster Flow', 'id': 'clusterflow-pipelines-table', 'table_title': 'Cluster Flow Pipelines', 'col1_header': 'Pipeline ID', 'no_beeswarm': True, 'save_file': True } self.add_section ( name = 'Pipelines', anchor = 'clusterflow-pipelines', description = 'Information about pipelines is parsed from <code>*.run</code> files. {}'.format(pids_guessed), plot = table.plot(data, headers, table_config), content = self.clusterflow_pipelines_printout() )
python
def clusterflow_pipelines_section(self): data = dict() pids_guessed = '' for f,d in self.clusterflow_runfiles.items(): pid = d.get('pipeline_id', 'unknown') if d.get('pipeline_id_guess', False) is True: pid += '*' pids_guessed = ' Project IDs with an asterisk may be inaccurate.' # Count the number of files going into the first module num_starting_files = 0 for step_name, files in d.get('files',{}).items(): if step_name.startswith('start'): num_starting_files += len(files) # Reformat the date so that column sorting works nicely if 'pipeline_start_dateparts' in d: dt = d['pipeline_start_dateparts'] d['pipeline_start'] = '{}-{:02d}-{:02d} {:02d}:{:02d}'.format(dt['year'], dt['month'], dt['day'], dt['hour'], dt['minute']) if pid not in data: data[pid] = d data[pid]['num_starting_files'] = int(num_starting_files) else: data[pid]['num_starting_files'] += int(num_starting_files) headers = OrderedDict() headers['pipeline_name'] = {'title': 'Pipeline Name'} headers['pipeline_start'] = {'title': 'Date Started', 'description': 'Date and time that pipeline was started (YYYY-MM-DD HH:SS)'} headers['genome'] = {'title': 'Genome ID', 'description': 'ID of reference genome used'} headers['num_starting_files'] = {'title': '# Starting Files', 'format': '{:,.0f}', 'description': 'Number of input files at start of pipeline run.'} table_config = { 'namespace': 'Cluster Flow', 'id': 'clusterflow-pipelines-table', 'table_title': 'Cluster Flow Pipelines', 'col1_header': 'Pipeline ID', 'no_beeswarm': True, 'save_file': True } self.add_section ( name = 'Pipelines', anchor = 'clusterflow-pipelines', description = 'Information about pipelines is parsed from <code>*.run</code> files. {}'.format(pids_guessed), plot = table.plot(data, headers, table_config), content = self.clusterflow_pipelines_printout() )
[ "def", "clusterflow_pipelines_section", "(", "self", ")", ":", "data", "=", "dict", "(", ")", "pids_guessed", "=", "''", "for", "f", ",", "d", "in", "self", ".", "clusterflow_runfiles", ".", "items", "(", ")", ":", "pid", "=", "d", ".", "get", "(", "...
Generate HTML for section about pipelines, generated from information parsed from run files.
[ "Generate", "HTML", "for", "section", "about", "pipelines", "generated", "from", "information", "parsed", "from", "run", "files", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/clusterflow/clusterflow.py#L278-L322
224,472
ewels/MultiQC
multiqc/modules/sortmerna/sortmerna.py
MultiqcModule.sortmerna_detailed_barplot
def sortmerna_detailed_barplot (self): """ Make the HighCharts HTML to plot the sortmerna rates """ # Specify the order of the different possible categories keys = OrderedDict() metrics = set() for sample in self.sortmerna: for key in self.sortmerna[sample]: if not key in ["total", "rRNA", "non_rRNA"] and not "_pct" in key: metrics.add(key) for key in metrics: keys[key] = { 'name': key.replace("_count","") } # Config for the plot pconfig = { 'id': 'sortmerna-detailed-plot', 'title': 'SortMeRNA: Hit Counts', 'ylab': 'Reads' } self.add_section( plot = bargraph.plot(self.sortmerna, keys, pconfig) )
python
def sortmerna_detailed_barplot (self): # Specify the order of the different possible categories keys = OrderedDict() metrics = set() for sample in self.sortmerna: for key in self.sortmerna[sample]: if not key in ["total", "rRNA", "non_rRNA"] and not "_pct" in key: metrics.add(key) for key in metrics: keys[key] = { 'name': key.replace("_count","") } # Config for the plot pconfig = { 'id': 'sortmerna-detailed-plot', 'title': 'SortMeRNA: Hit Counts', 'ylab': 'Reads' } self.add_section( plot = bargraph.plot(self.sortmerna, keys, pconfig) )
[ "def", "sortmerna_detailed_barplot", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "metrics", "=", "set", "(", ")", "for", "sample", "in", "self", ".", "sortmerna", ":", "for", "key", "in",...
Make the HighCharts HTML to plot the sortmerna rates
[ "Make", "the", "HighCharts", "HTML", "to", "plot", "the", "sortmerna", "rates" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/sortmerna/sortmerna.py#L116-L137
224,473
ewels/MultiQC
multiqc/modules/rseqc/inner_distance.py
parse_reports
def parse_reports(self): """ Find RSeQC inner_distance frequency reports and parse their data """ # Set up vars self.inner_distance = dict() self.inner_distance_pct = dict() # Go through files and parse data for f in self.find_log_files('rseqc/inner_distance'): if f['s_name'] in self.inner_distance: log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) self.add_data_source(f, section='inner_distance') #saving to temporary variable fro SE checking later parsed_data = OrderedDict() for l in f['f'].splitlines(): s = l.split() try: avg_pos = (float(s[0]) + float(s[1])) / 2.0 parsed_data[avg_pos] = float(s[2]) except: # Don't bother running through whole file if wrong break # Only add if we actually found something i,e it was PE data if len(parsed_data) > 0: self.inner_distance[f['s_name']] = parsed_data # Filter to strip out ignored sample names self.inner_distance = self.ignore_samples(self.inner_distance) if len(self.inner_distance) > 0: # Make a normalised percentage version of the data for s_name in self.inner_distance: self.inner_distance_pct[s_name] = OrderedDict() total = sum( self.inner_distance[s_name].values() ) for k, v in self.inner_distance[s_name].items(): self.inner_distance_pct[s_name][k] = (v/total)*100 # Add line graph to section pconfig = { 'id': 'rseqc_inner_distance_plot', 'title': 'RSeQC: Inner Distance', 'ylab': 'Counts', 'xlab': "Inner Distance (bp)", 'tt_label': "<strong>{point.x} bp</strong>: {point.y:.2f}", 'data_labels': [ {'name': 'Counts', 'ylab': 'Counts'}, {'name': 'Percentages', 'ylab': 'Percentage'} ] } self.add_section ( name = 'Inner Distance', anchor = 'rseqc-inner_distance', description = '<a href="http://rseqc.sourceforge.net/#inner-distance-py" target="_blank">Inner Distance</a>' \ " calculates the inner distance" \ " (or insert size) between two paired RNA reads." \ " Note that this can be negative if fragments overlap.", plot = linegraph.plot([self.inner_distance, self.inner_distance_pct], pconfig) ) # Return number of samples found return len(self.inner_distance)
python
def parse_reports(self): # Set up vars self.inner_distance = dict() self.inner_distance_pct = dict() # Go through files and parse data for f in self.find_log_files('rseqc/inner_distance'): if f['s_name'] in self.inner_distance: log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) self.add_data_source(f, section='inner_distance') #saving to temporary variable fro SE checking later parsed_data = OrderedDict() for l in f['f'].splitlines(): s = l.split() try: avg_pos = (float(s[0]) + float(s[1])) / 2.0 parsed_data[avg_pos] = float(s[2]) except: # Don't bother running through whole file if wrong break # Only add if we actually found something i,e it was PE data if len(parsed_data) > 0: self.inner_distance[f['s_name']] = parsed_data # Filter to strip out ignored sample names self.inner_distance = self.ignore_samples(self.inner_distance) if len(self.inner_distance) > 0: # Make a normalised percentage version of the data for s_name in self.inner_distance: self.inner_distance_pct[s_name] = OrderedDict() total = sum( self.inner_distance[s_name].values() ) for k, v in self.inner_distance[s_name].items(): self.inner_distance_pct[s_name][k] = (v/total)*100 # Add line graph to section pconfig = { 'id': 'rseqc_inner_distance_plot', 'title': 'RSeQC: Inner Distance', 'ylab': 'Counts', 'xlab': "Inner Distance (bp)", 'tt_label': "<strong>{point.x} bp</strong>: {point.y:.2f}", 'data_labels': [ {'name': 'Counts', 'ylab': 'Counts'}, {'name': 'Percentages', 'ylab': 'Percentage'} ] } self.add_section ( name = 'Inner Distance', anchor = 'rseqc-inner_distance', description = '<a href="http://rseqc.sourceforge.net/#inner-distance-py" target="_blank">Inner Distance</a>' \ " calculates the inner distance" \ " (or insert size) between two paired RNA reads." \ " Note that this can be negative if fragments overlap.", plot = linegraph.plot([self.inner_distance, self.inner_distance_pct], pconfig) ) # Return number of samples found return len(self.inner_distance)
[ "def", "parse_reports", "(", "self", ")", ":", "# Set up vars", "self", ".", "inner_distance", "=", "dict", "(", ")", "self", ".", "inner_distance_pct", "=", "dict", "(", ")", "# Go through files and parse data", "for", "f", "in", "self", ".", "find_log_files", ...
Find RSeQC inner_distance frequency reports and parse their data
[ "Find", "RSeQC", "inner_distance", "frequency", "reports", "and", "parse", "their", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rseqc/inner_distance.py#L15-L77
224,474
ewels/MultiQC
multiqc/modules/bcl2fastq/bcl2fastq.py
MultiqcModule.lane_stats_table
def lane_stats_table(self): """ Return a table with overview stats for each bcl2fastq lane for a single flow cell """ headers = OrderedDict() headers['total_yield'] = { 'title': '{} Total Yield'.format(config.base_count_prefix), 'description': 'Number of bases ({})'.format(config.base_count_desc), 'scale': 'Greens', 'shared_key': 'base_count' } headers['total'] = { 'title': '{} Total Clusters'.format(config.read_count_prefix), 'description': 'Total number of clusters for this lane ({})'.format(config.read_count_desc), 'scale': 'Blues', 'shared_key': 'read_count' } headers['percent_Q30'] = { 'title': '% bases &ge; Q30', 'description': 'Percentage of bases with greater than or equal to Q30 quality score', 'suffix': '%', 'max': 100, 'min': 0, 'scale': 'RdYlGn' } headers['mean_qscore'] = { 'title': 'Mean Quality', 'description': 'Average phred qualty score', 'min': 0, 'scale': 'Spectral' } headers['percent_perfectIndex'] = { 'title': '% Perfect Index', 'description': 'Percent of reads with perfect index (0 mismatches)', 'max': 100, 'min': 0, 'scale': 'RdYlGn', 'suffix': '%' } table_config = { 'namespace': 'bcl2fastq', 'id': 'bcl2fastq-lane-stats-table', 'table_title': 'bcl2fastq Lane Statistics', 'col1_header': 'Run ID - Lane', 'no_beeswarm': True } return table.plot(self.bcl2fastq_bylane, headers, table_config)
python
def lane_stats_table(self): headers = OrderedDict() headers['total_yield'] = { 'title': '{} Total Yield'.format(config.base_count_prefix), 'description': 'Number of bases ({})'.format(config.base_count_desc), 'scale': 'Greens', 'shared_key': 'base_count' } headers['total'] = { 'title': '{} Total Clusters'.format(config.read_count_prefix), 'description': 'Total number of clusters for this lane ({})'.format(config.read_count_desc), 'scale': 'Blues', 'shared_key': 'read_count' } headers['percent_Q30'] = { 'title': '% bases &ge; Q30', 'description': 'Percentage of bases with greater than or equal to Q30 quality score', 'suffix': '%', 'max': 100, 'min': 0, 'scale': 'RdYlGn' } headers['mean_qscore'] = { 'title': 'Mean Quality', 'description': 'Average phred qualty score', 'min': 0, 'scale': 'Spectral' } headers['percent_perfectIndex'] = { 'title': '% Perfect Index', 'description': 'Percent of reads with perfect index (0 mismatches)', 'max': 100, 'min': 0, 'scale': 'RdYlGn', 'suffix': '%' } table_config = { 'namespace': 'bcl2fastq', 'id': 'bcl2fastq-lane-stats-table', 'table_title': 'bcl2fastq Lane Statistics', 'col1_header': 'Run ID - Lane', 'no_beeswarm': True } return table.plot(self.bcl2fastq_bylane, headers, table_config)
[ "def", "lane_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'total_yield'", "]", "=", "{", "'title'", ":", "'{} Total Yield'", ".", "format", "(", "config", ".", "base_count_prefix", ")", ",", "'description'", ...
Return a table with overview stats for each bcl2fastq lane for a single flow cell
[ "Return", "a", "table", "with", "overview", "stats", "for", "each", "bcl2fastq", "lane", "for", "a", "single", "flow", "cell" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bcl2fastq/bcl2fastq.py#L437-L481
224,475
ewels/MultiQC
multiqc/modules/bcl2fastq/bcl2fastq.py
MultiqcModule.get_bar_data_from_undetermined
def get_bar_data_from_undetermined(self, flowcells): """ Get data to plot for undetermined barcodes. """ bar_data = defaultdict(dict) # get undetermined barcodes for each lanes for lane_id, lane in flowcells.items(): try: for barcode, count in islice(lane['unknown_barcodes'].items(), 20): bar_data[barcode][lane_id] = count except AttributeError: pass # sort results bar_data = OrderedDict(sorted( bar_data.items(), key=lambda x: sum(x[1].values()), reverse=True )) return OrderedDict( (key, value) for key, value in islice(bar_data.items(), 20) )
python
def get_bar_data_from_undetermined(self, flowcells): bar_data = defaultdict(dict) # get undetermined barcodes for each lanes for lane_id, lane in flowcells.items(): try: for barcode, count in islice(lane['unknown_barcodes'].items(), 20): bar_data[barcode][lane_id] = count except AttributeError: pass # sort results bar_data = OrderedDict(sorted( bar_data.items(), key=lambda x: sum(x[1].values()), reverse=True )) return OrderedDict( (key, value) for key, value in islice(bar_data.items(), 20) )
[ "def", "get_bar_data_from_undetermined", "(", "self", ",", "flowcells", ")", ":", "bar_data", "=", "defaultdict", "(", "dict", ")", "# get undetermined barcodes for each lanes", "for", "lane_id", ",", "lane", "in", "flowcells", ".", "items", "(", ")", ":", "try", ...
Get data to plot for undetermined barcodes.
[ "Get", "data", "to", "plot", "for", "undetermined", "barcodes", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bcl2fastq/bcl2fastq.py#L497-L517
224,476
ewels/MultiQC
multiqc/modules/kallisto/kallisto.py
MultiqcModule.kallisto_general_stats_table
def kallisto_general_stats_table(self): """ Take the parsed stats from the Kallisto report and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['fragment_length'] = { 'title': 'Frag Length', 'description': 'Estimated average fragment length', 'min': 0, 'suffix': 'bp', 'scale': 'RdYlGn' } headers['percent_aligned'] = { 'title': '% Aligned', 'description': '% processed reads that were pseudoaligned', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['pseudoaligned_reads'] = { 'title': '{} Aligned'.format(config.read_count_prefix), 'description': 'Pseudoaligned reads ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } self.general_stats_addcols(self.kallisto_data, headers)
python
def kallisto_general_stats_table(self): headers = OrderedDict() headers['fragment_length'] = { 'title': 'Frag Length', 'description': 'Estimated average fragment length', 'min': 0, 'suffix': 'bp', 'scale': 'RdYlGn' } headers['percent_aligned'] = { 'title': '% Aligned', 'description': '% processed reads that were pseudoaligned', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['pseudoaligned_reads'] = { 'title': '{} Aligned'.format(config.read_count_prefix), 'description': 'Pseudoaligned reads ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } self.general_stats_addcols(self.kallisto_data, headers)
[ "def", "kallisto_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'fragment_length'", "]", "=", "{", "'title'", ":", "'Frag Length'", ",", "'description'", ":", "'Estimated average fragment length'", ",", "'min'"...
Take the parsed stats from the Kallisto report and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "Kallisto", "report", "and", "add", "it", "to", "the", "basic", "stats", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/kallisto/kallisto.py#L86-L114
224,477
ewels/MultiQC
multiqc/modules/hicpro/hicpro.py
MultiqcModule.parse_hicpro_stats
def parse_hicpro_stats(self, f, rsection): """ Parse a HiC-Pro stat file """ s_name = self.clean_s_name(os.path.basename(f['root']), os.path.dirname(f['root'])) if s_name not in self.hicpro_data.keys(): self.hicpro_data[s_name] = {} self.add_data_source(f, s_name, section=rsection) for l in f['f'].splitlines(): if not l.startswith('#'): s = l.split("\t") if s[0] in self.hicpro_data[s_name]: log.debug("Duplicated keys found! Overwriting: {}".format(s[0])) self.hicpro_data[s_name][s[0]] = int(s[1])
python
def parse_hicpro_stats(self, f, rsection): s_name = self.clean_s_name(os.path.basename(f['root']), os.path.dirname(f['root'])) if s_name not in self.hicpro_data.keys(): self.hicpro_data[s_name] = {} self.add_data_source(f, s_name, section=rsection) for l in f['f'].splitlines(): if not l.startswith('#'): s = l.split("\t") if s[0] in self.hicpro_data[s_name]: log.debug("Duplicated keys found! Overwriting: {}".format(s[0])) self.hicpro_data[s_name][s[0]] = int(s[1])
[ "def", "parse_hicpro_stats", "(", "self", ",", "f", ",", "rsection", ")", ":", "s_name", "=", "self", ".", "clean_s_name", "(", "os", ".", "path", ".", "basename", "(", "f", "[", "'root'", "]", ")", ",", "os", ".", "path", ".", "dirname", "(", "f",...
Parse a HiC-Pro stat file
[ "Parse", "a", "HiC", "-", "Pro", "stat", "file" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicpro/hicpro.py#L140-L153
224,478
ewels/MultiQC
multiqc/modules/hicpro/hicpro.py
MultiqcModule.hicpro_mapping_chart
def hicpro_mapping_chart (self): """ Generate the HiC-Pro Aligned reads plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['Full_Alignments_Read'] = { 'color': '#005ce6', 'name': 'Full reads Alignments' } keys['Trimmed_Alignments_Read'] = { 'color': '#3385ff', 'name': 'Trimmed reads Alignments' } keys['Failed_To_Align_Read'] = { 'color': '#a9a2a2', 'name': 'Failed To Align' } data = [{},{}] for s_name in self.hicpro_data: for r in [1,2]: data[r-1]['{} [R{}]'.format(s_name, r)] = { 'Full_Alignments_Read': self.hicpro_data[s_name]['global_R{}'.format(r)], 'Trimmed_Alignments_Read': self.hicpro_data[s_name]['local_R{}'.format(r)], 'Failed_To_Align_Read': int(self.hicpro_data[s_name]['total_R{}'.format(r)]) - int(self.hicpro_data[s_name]['mapped_R{}'.format(r)]) } # Config for the plot config = { 'id': 'hicpro_mapping_stats_plot', 'title': 'HiC-Pro: Mapping Statistics', 'ylab': '# Reads', 'ylab': '# Reads: Read 1', 'data_labels': [ {'name': 'Read 1', 'ylab': '# Reads: Read 1'}, {'name': 'Read 2', 'ylab': '# Reads: Read 2'} ] } return bargraph.plot(data, [keys, keys], config)
python
def hicpro_mapping_chart (self): # Specify the order of the different possible categories keys = OrderedDict() keys['Full_Alignments_Read'] = { 'color': '#005ce6', 'name': 'Full reads Alignments' } keys['Trimmed_Alignments_Read'] = { 'color': '#3385ff', 'name': 'Trimmed reads Alignments' } keys['Failed_To_Align_Read'] = { 'color': '#a9a2a2', 'name': 'Failed To Align' } data = [{},{}] for s_name in self.hicpro_data: for r in [1,2]: data[r-1]['{} [R{}]'.format(s_name, r)] = { 'Full_Alignments_Read': self.hicpro_data[s_name]['global_R{}'.format(r)], 'Trimmed_Alignments_Read': self.hicpro_data[s_name]['local_R{}'.format(r)], 'Failed_To_Align_Read': int(self.hicpro_data[s_name]['total_R{}'.format(r)]) - int(self.hicpro_data[s_name]['mapped_R{}'.format(r)]) } # Config for the plot config = { 'id': 'hicpro_mapping_stats_plot', 'title': 'HiC-Pro: Mapping Statistics', 'ylab': '# Reads', 'ylab': '# Reads: Read 1', 'data_labels': [ {'name': 'Read 1', 'ylab': '# Reads: Read 1'}, {'name': 'Read 2', 'ylab': '# Reads: Read 2'} ] } return bargraph.plot(data, [keys, keys], config)
[ "def", "hicpro_mapping_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'Full_Alignments_Read'", "]", "=", "{", "'color'", ":", "'#005ce6'", ",", "'name'", ":", "'Full reads ...
Generate the HiC-Pro Aligned reads plot
[ "Generate", "the", "HiC", "-", "Pro", "Aligned", "reads", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicpro/hicpro.py#L269-L299
224,479
ewels/MultiQC
multiqc/modules/hicpro/hicpro.py
MultiqcModule.hicpro_pairing_chart
def hicpro_pairing_chart (self): """ Generate Pairing chart """ # Specify the order of the different possible categories keys = OrderedDict() keys['Unique_paired_alignments'] = { 'color': '#005ce6', 'name': 'Uniquely Aligned' } keys['Low_qual_pairs'] = { 'color': '#b97b35', 'name': 'Low Quality' } keys['Pairs_with_singleton'] = { 'color': '#ff9933', 'name': 'Singleton' } keys['Multiple_pairs_alignments'] = { 'color': '#e67300', 'name': 'Multi Aligned' } keys['Unmapped_airs'] = { 'color': '#a9a2a2', 'name': 'Failed To Align' } # Config for the plot config = { 'id': 'hicpro_pairing_stats_plot', 'title': 'HiC-Pro: Pairing Statistics', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(self.hicpro_data, keys, config)
python
def hicpro_pairing_chart (self): # Specify the order of the different possible categories keys = OrderedDict() keys['Unique_paired_alignments'] = { 'color': '#005ce6', 'name': 'Uniquely Aligned' } keys['Low_qual_pairs'] = { 'color': '#b97b35', 'name': 'Low Quality' } keys['Pairs_with_singleton'] = { 'color': '#ff9933', 'name': 'Singleton' } keys['Multiple_pairs_alignments'] = { 'color': '#e67300', 'name': 'Multi Aligned' } keys['Unmapped_airs'] = { 'color': '#a9a2a2', 'name': 'Failed To Align' } # Config for the plot config = { 'id': 'hicpro_pairing_stats_plot', 'title': 'HiC-Pro: Pairing Statistics', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(self.hicpro_data, keys, config)
[ "def", "hicpro_pairing_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'Unique_paired_alignments'", "]", "=", "{", "'color'", ":", "'#005ce6'", ",", "'name'", ":", "'Uniquel...
Generate Pairing chart
[ "Generate", "Pairing", "chart" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicpro/hicpro.py#L301-L320
224,480
ewels/MultiQC
multiqc/modules/hicpro/hicpro.py
MultiqcModule.hicpro_filtering_chart
def hicpro_filtering_chart (self): """ Generate the HiC-Pro filtering plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['Valid_interaction_pairs_FF'] = { 'color': '#ccddff', 'name': 'Valid Pairs FF' } keys['Valid_interaction_pairs_RR'] = { 'color': '#6699ff', 'name': 'Valid Pairs RR' } keys['Valid_interaction_pairs_RF'] = { 'color': '#0055ff', 'name': 'Valid Pairs RF' } keys['Valid_interaction_pairs_FR'] = { 'color': '#003399', 'name': 'Valid Pairs FR' } keys['Self_Cycle_pairs'] = { 'color': '#ffad99', 'name': 'Same Fragment - Self-Circle' } keys['Dangling_end_pairs'] = { 'color': '#ff5c33', 'name': 'Same Fragment - Dangling Ends' } keys['Religation_pairs'] = { 'color': '#cc2900', 'name': 'Re-ligation' } keys['Filtered_pairs'] = { 'color': '#661400', 'name': 'Filtered pairs' } keys['Dumped_pairs'] = { 'color': '#330a00', 'name': 'Dumped pairs' } # Config for the plot config = { 'id': 'hicpro_filtering_plot', 'title': 'HiC-Pro: Filtering Statistics', 'ylab': '# Read Pairs', 'cpswitch_counts_label': 'Number of Read Pairs' } return bargraph.plot(self.hicpro_data, keys, config)
python
def hicpro_filtering_chart (self): # Specify the order of the different possible categories keys = OrderedDict() keys['Valid_interaction_pairs_FF'] = { 'color': '#ccddff', 'name': 'Valid Pairs FF' } keys['Valid_interaction_pairs_RR'] = { 'color': '#6699ff', 'name': 'Valid Pairs RR' } keys['Valid_interaction_pairs_RF'] = { 'color': '#0055ff', 'name': 'Valid Pairs RF' } keys['Valid_interaction_pairs_FR'] = { 'color': '#003399', 'name': 'Valid Pairs FR' } keys['Self_Cycle_pairs'] = { 'color': '#ffad99', 'name': 'Same Fragment - Self-Circle' } keys['Dangling_end_pairs'] = { 'color': '#ff5c33', 'name': 'Same Fragment - Dangling Ends' } keys['Religation_pairs'] = { 'color': '#cc2900', 'name': 'Re-ligation' } keys['Filtered_pairs'] = { 'color': '#661400', 'name': 'Filtered pairs' } keys['Dumped_pairs'] = { 'color': '#330a00', 'name': 'Dumped pairs' } # Config for the plot config = { 'id': 'hicpro_filtering_plot', 'title': 'HiC-Pro: Filtering Statistics', 'ylab': '# Read Pairs', 'cpswitch_counts_label': 'Number of Read Pairs' } return bargraph.plot(self.hicpro_data, keys, config)
[ "def", "hicpro_filtering_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'Valid_interaction_pairs_FF'", "]", "=", "{", "'color'", ":", "'#ccddff'", ",", "'name'", ":", "'Val...
Generate the HiC-Pro filtering plot
[ "Generate", "the", "HiC", "-", "Pro", "filtering", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicpro/hicpro.py#L323-L346
224,481
ewels/MultiQC
multiqc/modules/hicpro/hicpro.py
MultiqcModule.hicpro_contact_chart
def hicpro_contact_chart (self): """ Generate the HiC-Pro interaction plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['cis_shortRange'] = { 'color': '#0039e6', 'name': 'Unique: cis <= 20Kbp' } keys['cis_longRange'] = { 'color': '#809fff', 'name': 'Unique: cis > 20Kbp' } keys['trans_interaction'] = { 'color': '#009933', 'name': 'Unique: trans' } keys['duplicates'] = { 'color': '#a9a2a2', 'name': 'Duplicate read pairs' } # Config for the plot config = { 'id': 'hicpro_contact_plot', 'title': 'HiC-Pro: Contact Statistics', 'ylab': '# Pairs', 'cpswitch_counts_label': 'Number of Pairs' } return bargraph.plot(self.hicpro_data, keys, config)
python
def hicpro_contact_chart (self): # Specify the order of the different possible categories keys = OrderedDict() keys['cis_shortRange'] = { 'color': '#0039e6', 'name': 'Unique: cis <= 20Kbp' } keys['cis_longRange'] = { 'color': '#809fff', 'name': 'Unique: cis > 20Kbp' } keys['trans_interaction'] = { 'color': '#009933', 'name': 'Unique: trans' } keys['duplicates'] = { 'color': '#a9a2a2', 'name': 'Duplicate read pairs' } # Config for the plot config = { 'id': 'hicpro_contact_plot', 'title': 'HiC-Pro: Contact Statistics', 'ylab': '# Pairs', 'cpswitch_counts_label': 'Number of Pairs' } return bargraph.plot(self.hicpro_data, keys, config)
[ "def", "hicpro_contact_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'cis_shortRange'", "]", "=", "{", "'color'", ":", "'#0039e6'", ",", "'name'", ":", "'Unique: cis <= 20...
Generate the HiC-Pro interaction plot
[ "Generate", "the", "HiC", "-", "Pro", "interaction", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicpro/hicpro.py#L348-L366
224,482
ewels/MultiQC
multiqc/modules/hicpro/hicpro.py
MultiqcModule.hicpro_capture_chart
def hicpro_capture_chart (self): """ Generate Capture Hi-C plot""" keys = OrderedDict() keys['valid_pairs_on_target_cap_cap'] = { 'color': '#0039e6', 'name': 'Capture-Capture interactions' } keys['valid_pairs_on_target_cap_rep'] = { 'color': '#809fff', 'name': 'Capture-Reporter interactions' } keys['valid_pairs_off_target'] = { 'color': '#cccccc', 'name': 'Off-target valid pairs' } # Check capture info are available num_samples = 0 for s_name in self.hicpro_data: for k in keys: num_samples += sum([1 if k in self.hicpro_data[s_name] else 0]) if num_samples == 0: return False # Config for the plot config = { 'id': 'hicpro_cap_plot', 'title': 'HiC-Pro: Capture Statistics', 'ylab': '# Pairs', 'cpswitch_counts_label': 'Number of Pairs' } return bargraph.plot(self.hicpro_data, keys, config)
python
def hicpro_capture_chart (self): keys = OrderedDict() keys['valid_pairs_on_target_cap_cap'] = { 'color': '#0039e6', 'name': 'Capture-Capture interactions' } keys['valid_pairs_on_target_cap_rep'] = { 'color': '#809fff', 'name': 'Capture-Reporter interactions' } keys['valid_pairs_off_target'] = { 'color': '#cccccc', 'name': 'Off-target valid pairs' } # Check capture info are available num_samples = 0 for s_name in self.hicpro_data: for k in keys: num_samples += sum([1 if k in self.hicpro_data[s_name] else 0]) if num_samples == 0: return False # Config for the plot config = { 'id': 'hicpro_cap_plot', 'title': 'HiC-Pro: Capture Statistics', 'ylab': '# Pairs', 'cpswitch_counts_label': 'Number of Pairs' } return bargraph.plot(self.hicpro_data, keys, config)
[ "def", "hicpro_capture_chart", "(", "self", ")", ":", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'valid_pairs_on_target_cap_cap'", "]", "=", "{", "'color'", ":", "'#0039e6'", ",", "'name'", ":", "'Capture-Capture interactions'", "}", "keys", "[", "'vali...
Generate Capture Hi-C plot
[ "Generate", "Capture", "Hi", "-", "C", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicpro/hicpro.py#L399-L423
224,483
ewels/MultiQC
multiqc/modules/deeptools/plotCorrelation.py
plotCorrelationMixin.parse_plotCorrelation
def parse_plotCorrelation(self): """Find plotCorrelation output""" self.deeptools_plotCorrelationData = dict() for f in self.find_log_files('deeptools/plotCorrelationData', filehandles=False): parsed_data, samples = self.parsePlotCorrelationData(f) for k, v in parsed_data.items(): if k in self.deeptools_plotCorrelationData: log.warning("Replacing duplicate sample {}.".format(k)) self.deeptools_plotCorrelationData[k] = v if len(parsed_data) > 0: self.add_data_source(f, section='plotCorrelation') if len(self.deeptools_plotCorrelationData) > 0: config = { 'id': 'deeptools_correlation_plot', 'title': 'deeptools: Correlation Plot', } data = [] for s_name in samples: try: data.append(self.deeptools_plotCorrelationData[s_name]) except KeyError: pass if len(data) == 0: log.debug('No valid data for correlation plot') return None self.add_section( name="Correlation heatmap", anchor="deeptools_correlation", description="Pairwise correlations of samples based on distribution of sequence reads", plot=heatmap.plot(data, samples, samples, config) ) return len(self.deeptools_plotCorrelationData)
python
def parse_plotCorrelation(self): self.deeptools_plotCorrelationData = dict() for f in self.find_log_files('deeptools/plotCorrelationData', filehandles=False): parsed_data, samples = self.parsePlotCorrelationData(f) for k, v in parsed_data.items(): if k in self.deeptools_plotCorrelationData: log.warning("Replacing duplicate sample {}.".format(k)) self.deeptools_plotCorrelationData[k] = v if len(parsed_data) > 0: self.add_data_source(f, section='plotCorrelation') if len(self.deeptools_plotCorrelationData) > 0: config = { 'id': 'deeptools_correlation_plot', 'title': 'deeptools: Correlation Plot', } data = [] for s_name in samples: try: data.append(self.deeptools_plotCorrelationData[s_name]) except KeyError: pass if len(data) == 0: log.debug('No valid data for correlation plot') return None self.add_section( name="Correlation heatmap", anchor="deeptools_correlation", description="Pairwise correlations of samples based on distribution of sequence reads", plot=heatmap.plot(data, samples, samples, config) ) return len(self.deeptools_plotCorrelationData)
[ "def", "parse_plotCorrelation", "(", "self", ")", ":", "self", ".", "deeptools_plotCorrelationData", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'deeptools/plotCorrelationData'", ",", "filehandles", "=", "False", ")", ":", "pars...
Find plotCorrelation output
[ "Find", "plotCorrelation", "output" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/deeptools/plotCorrelation.py#L17-L51
224,484
ewels/MultiQC
multiqc/modules/featureCounts/feature_counts.py
MultiqcModule.parse_featurecounts_report
def parse_featurecounts_report (self, f): """ Parse the featureCounts log file. """ file_names = list() parsed_data = dict() for l in f['f'].splitlines(): thisrow = list() s = l.split("\t") if len(s) < 2: continue if s[0] == 'Status': for f_name in s[1:]: file_names.append(f_name) else: k = s[0] if k not in self.featurecounts_keys: self.featurecounts_keys.append(k) for val in s[1:]: try: thisrow.append(int(val)) except ValueError: pass if len(thisrow) > 0: parsed_data[k] = thisrow # Check that this actually is a featureCounts file, as format and parsing is quite general if 'Assigned' not in parsed_data.keys(): return None for idx, f_name in enumerate(file_names): # Clean up sample name s_name = self.clean_s_name(f_name, f['root']) # Reorganised parsed data for this sample # Collect total count number data = dict() data['Total'] = 0 for k in parsed_data: data[k] = parsed_data[k][idx] data['Total'] += parsed_data[k][idx] # Calculate the percent aligned if we can try: data['percent_assigned'] = (float(data['Assigned'])/float(data['Total'])) * 100.0 except (KeyError, ZeroDivisionError): pass # Add to the main dictionary if len(data) > 1: if s_name in self.featurecounts_data: log.debug("Duplicate sample name found! Overwriting: {}".format(s_name)) self.add_data_source(f, s_name) self.featurecounts_data[s_name] = data
python
def parse_featurecounts_report (self, f): file_names = list() parsed_data = dict() for l in f['f'].splitlines(): thisrow = list() s = l.split("\t") if len(s) < 2: continue if s[0] == 'Status': for f_name in s[1:]: file_names.append(f_name) else: k = s[0] if k not in self.featurecounts_keys: self.featurecounts_keys.append(k) for val in s[1:]: try: thisrow.append(int(val)) except ValueError: pass if len(thisrow) > 0: parsed_data[k] = thisrow # Check that this actually is a featureCounts file, as format and parsing is quite general if 'Assigned' not in parsed_data.keys(): return None for idx, f_name in enumerate(file_names): # Clean up sample name s_name = self.clean_s_name(f_name, f['root']) # Reorganised parsed data for this sample # Collect total count number data = dict() data['Total'] = 0 for k in parsed_data: data[k] = parsed_data[k][idx] data['Total'] += parsed_data[k][idx] # Calculate the percent aligned if we can try: data['percent_assigned'] = (float(data['Assigned'])/float(data['Total'])) * 100.0 except (KeyError, ZeroDivisionError): pass # Add to the main dictionary if len(data) > 1: if s_name in self.featurecounts_data: log.debug("Duplicate sample name found! Overwriting: {}".format(s_name)) self.add_data_source(f, s_name) self.featurecounts_data[s_name] = data
[ "def", "parse_featurecounts_report", "(", "self", ",", "f", ")", ":", "file_names", "=", "list", "(", ")", "parsed_data", "=", "dict", "(", ")", "for", "l", "in", "f", "[", "'f'", "]", ".", "splitlines", "(", ")", ":", "thisrow", "=", "list", "(", ...
Parse the featureCounts log file.
[ "Parse", "the", "featureCounts", "log", "file", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/featureCounts/feature_counts.py#L52-L103
224,485
ewels/MultiQC
multiqc/modules/featureCounts/feature_counts.py
MultiqcModule.featurecounts_stats_table
def featurecounts_stats_table(self): """ Take the parsed stats from the featureCounts report and add them to the basic stats table at the top of the report """ headers = OrderedDict() headers['percent_assigned'] = { 'title': '% Assigned', 'description': '% Assigned reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn' } headers['Assigned'] = { 'title': '{} Assigned'.format(config.read_count_prefix), 'description': 'Assigned reads ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuBu', 'modify': lambda x: float(x) * config.read_count_multiplier, 'shared_key': 'read_count' } self.general_stats_addcols(self.featurecounts_data, headers)
python
def featurecounts_stats_table(self): headers = OrderedDict() headers['percent_assigned'] = { 'title': '% Assigned', 'description': '% Assigned reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn' } headers['Assigned'] = { 'title': '{} Assigned'.format(config.read_count_prefix), 'description': 'Assigned reads ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuBu', 'modify': lambda x: float(x) * config.read_count_multiplier, 'shared_key': 'read_count' } self.general_stats_addcols(self.featurecounts_data, headers)
[ "def", "featurecounts_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'percent_assigned'", "]", "=", "{", "'title'", ":", "'% Assigned'", ",", "'description'", ":", "'% Assigned reads'", ",", "'max'", ":", "100", ...
Take the parsed stats from the featureCounts report and add them to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "featureCounts", "report", "and", "add", "them", "to", "the", "basic", "stats", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/featureCounts/feature_counts.py#L106-L127
224,486
ewels/MultiQC
multiqc/modules/featureCounts/feature_counts.py
MultiqcModule.featureCounts_chart
def featureCounts_chart (self): """ Make the featureCounts assignment rates plot """ # Config for the plot config = { 'id': 'featureCounts_assignment_plot', 'title': 'featureCounts: Assignments', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(self.featurecounts_data, self.featurecounts_keys, config)
python
def featureCounts_chart (self): # Config for the plot config = { 'id': 'featureCounts_assignment_plot', 'title': 'featureCounts: Assignments', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } return bargraph.plot(self.featurecounts_data, self.featurecounts_keys, config)
[ "def", "featureCounts_chart", "(", "self", ")", ":", "# Config for the plot", "config", "=", "{", "'id'", ":", "'featureCounts_assignment_plot'", ",", "'title'", ":", "'featureCounts: Assignments'", ",", "'ylab'", ":", "'# Reads'", ",", "'cpswitch_counts_label'", ":", ...
Make the featureCounts assignment rates plot
[ "Make", "the", "featureCounts", "assignment", "rates", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/featureCounts/feature_counts.py#L130-L141
224,487
ewels/MultiQC
multiqc/plots/linegraph.py
smooth_line_data
def smooth_line_data(data, numpoints, sumcounts=True): """ Function to take an x-y dataset and use binning to smooth to a maximum number of datapoints. """ smoothed = {} for s_name, d in data.items(): # Check that we need to smooth this data if len(d) <= numpoints: smoothed[s_name] = d continue smoothed[s_name] = OrderedDict(); p = 0 binsize = len(d) / numpoints if binsize < 1: binsize = 1 binvals = [] for x in sorted(d): y = d[x] if p < binsize: binvals.append(y) p += 1 else: if sumcounts is True: v = sum(binvals) else: v = sum(binvals) / binsize smoothed[s_name][x] = v p = 0 binvals = [] return smoothed
python
def smooth_line_data(data, numpoints, sumcounts=True): smoothed = {} for s_name, d in data.items(): # Check that we need to smooth this data if len(d) <= numpoints: smoothed[s_name] = d continue smoothed[s_name] = OrderedDict(); p = 0 binsize = len(d) / numpoints if binsize < 1: binsize = 1 binvals = [] for x in sorted(d): y = d[x] if p < binsize: binvals.append(y) p += 1 else: if sumcounts is True: v = sum(binvals) else: v = sum(binvals) / binsize smoothed[s_name][x] = v p = 0 binvals = [] return smoothed
[ "def", "smooth_line_data", "(", "data", ",", "numpoints", ",", "sumcounts", "=", "True", ")", ":", "smoothed", "=", "{", "}", "for", "s_name", ",", "d", "in", "data", ".", "items", "(", ")", ":", "# Check that we need to smooth this data", "if", "len", "("...
Function to take an x-y dataset and use binning to smooth to a maximum number of datapoints.
[ "Function", "to", "take", "an", "x", "-", "y", "dataset", "and", "use", "binning", "to", "smooth", "to", "a", "maximum", "number", "of", "datapoints", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/plots/linegraph.py#L457-L489
224,488
ewels/MultiQC
multiqc/modules/picard/ValidateSamFile.py
parse_reports
def parse_reports(self): """ Find Picard ValidateSamFile reports and parse their data based on wether we think it's a VERBOSE or SUMMARY report """ # Get data data = _parse_reports_by_type(self) if data: # Filter to strip out ignored sample names (REQUIRED) data = self.ignore_samples(data) # Populate the general stats table _add_data_to_general_stats(self, data) # Add any found data to the report _add_section_to_report(self, data) # Write parsed data to a file self.write_data_file(data, 'multiqc_picard_validatesamfile') self.picard_ValidateSamFile_data = data # Seems like the right thing to do return len(data)
python
def parse_reports(self): # Get data data = _parse_reports_by_type(self) if data: # Filter to strip out ignored sample names (REQUIRED) data = self.ignore_samples(data) # Populate the general stats table _add_data_to_general_stats(self, data) # Add any found data to the report _add_section_to_report(self, data) # Write parsed data to a file self.write_data_file(data, 'multiqc_picard_validatesamfile') self.picard_ValidateSamFile_data = data # Seems like the right thing to do return len(data)
[ "def", "parse_reports", "(", "self", ")", ":", "# Get data", "data", "=", "_parse_reports_by_type", "(", "self", ")", "if", "data", ":", "# Filter to strip out ignored sample names (REQUIRED)", "data", "=", "self", ".", "ignore_samples", "(", "data", ")", "# Popula...
Find Picard ValidateSamFile reports and parse their data based on wether we think it's a VERBOSE or SUMMARY report
[ "Find", "Picard", "ValidateSamFile", "reports", "and", "parse", "their", "data", "based", "on", "wether", "we", "think", "it", "s", "a", "VERBOSE", "or", "SUMMARY", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/ValidateSamFile.py#L84-L107
224,489
ewels/MultiQC
multiqc/modules/picard/ValidateSamFile.py
_parse_reports_by_type
def _parse_reports_by_type(self): """ Returns a data dictionary Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type. """ data = dict() for file_meta in self.find_log_files('picard/sam_file_validation', filehandles=True): sample = file_meta['s_name'] if sample in data: log.debug("Duplicate sample name found! Overwriting: {}".format(sample)) filehandle = file_meta['f'] first_line = filehandle.readline().rstrip() filehandle.seek(0) # Rewind reading of the file if 'No errors found' in first_line: sample_data = _parse_no_error_report() elif first_line.startswith('ERROR') or first_line.startswith('WARNING'): sample_data = _parse_verbose_report(filehandle) else: sample_data = _parse_summary_report(filehandle) data[sample] = sample_data return data
python
def _parse_reports_by_type(self): data = dict() for file_meta in self.find_log_files('picard/sam_file_validation', filehandles=True): sample = file_meta['s_name'] if sample in data: log.debug("Duplicate sample name found! Overwriting: {}".format(sample)) filehandle = file_meta['f'] first_line = filehandle.readline().rstrip() filehandle.seek(0) # Rewind reading of the file if 'No errors found' in first_line: sample_data = _parse_no_error_report() elif first_line.startswith('ERROR') or first_line.startswith('WARNING'): sample_data = _parse_verbose_report(filehandle) else: sample_data = _parse_summary_report(filehandle) data[sample] = sample_data return data
[ "def", "_parse_reports_by_type", "(", "self", ")", ":", "data", "=", "dict", "(", ")", "for", "file_meta", "in", "self", ".", "find_log_files", "(", "'picard/sam_file_validation'", ",", "filehandles", "=", "True", ")", ":", "sample", "=", "file_meta", "[", "...
Returns a data dictionary Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type.
[ "Returns", "a", "data", "dictionary" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/ValidateSamFile.py#L110-L137
224,490
ewels/MultiQC
multiqc/modules/picard/ValidateSamFile.py
_histogram_data
def _histogram_data(iterator): """ Yields only the row contents that contain the histogram entries """ histogram_started = False header_passed = False for l in iterator: if '## HISTOGRAM' in l: histogram_started = True elif histogram_started: if header_passed: values = l.rstrip().split("\t") problem_type, name = values[0].split(':') yield problem_type, name, int(values[1]) elif l.startswith('Error Type'): header_passed = True
python
def _histogram_data(iterator): histogram_started = False header_passed = False for l in iterator: if '## HISTOGRAM' in l: histogram_started = True elif histogram_started: if header_passed: values = l.rstrip().split("\t") problem_type, name = values[0].split(':') yield problem_type, name, int(values[1]) elif l.startswith('Error Type'): header_passed = True
[ "def", "_histogram_data", "(", "iterator", ")", ":", "histogram_started", "=", "False", "header_passed", "=", "False", "for", "l", "in", "iterator", ":", "if", "'## HISTOGRAM'", "in", "l", ":", "histogram_started", "=", "True", "elif", "histogram_started", ":", ...
Yields only the row contents that contain the histogram entries
[ "Yields", "only", "the", "row", "contents", "that", "contain", "the", "histogram", "entries" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/ValidateSamFile.py#L178-L191
224,491
ewels/MultiQC
multiqc/modules/picard/ValidateSamFile.py
_add_data_to_general_stats
def _add_data_to_general_stats(self, data): """ Add data for the general stats in a Picard-module specific manner """ headers = _get_general_stats_headers() self.general_stats_headers.update(headers) header_names = ('ERROR_count', 'WARNING_count', 'file_validation_status') general_data = dict() for sample in data: general_data[sample] = {column: data[sample][column] for column in header_names} if sample not in self.general_stats_data: self.general_stats_data[sample] = dict() if data[sample]['file_validation_status'] != 'pass': headers['file_validation_status']['hidden'] = False self.general_stats_data[sample].update(general_data[sample])
python
def _add_data_to_general_stats(self, data): headers = _get_general_stats_headers() self.general_stats_headers.update(headers) header_names = ('ERROR_count', 'WARNING_count', 'file_validation_status') general_data = dict() for sample in data: general_data[sample] = {column: data[sample][column] for column in header_names} if sample not in self.general_stats_data: self.general_stats_data[sample] = dict() if data[sample]['file_validation_status'] != 'pass': headers['file_validation_status']['hidden'] = False self.general_stats_data[sample].update(general_data[sample])
[ "def", "_add_data_to_general_stats", "(", "self", ",", "data", ")", ":", "headers", "=", "_get_general_stats_headers", "(", ")", "self", ".", "general_stats_headers", ".", "update", "(", "headers", ")", "header_names", "=", "(", "'ERROR_count'", ",", "'WARNING_cou...
Add data for the general stats in a Picard-module specific manner
[ "Add", "data", "for", "the", "general", "stats", "in", "a", "Picard", "-", "module", "specific", "manner" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/ValidateSamFile.py#L238-L255
224,492
ewels/MultiQC
multiqc/modules/picard/ValidateSamFile.py
_generate_overview_note
def _generate_overview_note(pass_count, only_warning_count, error_count, total_count): """ Generates and returns the HTML note that provides a summary of validation status. """ note_html = ['<div class="progress">'] pbars = [ [ float(error_count), 'danger', 'had errors' ], [ float(only_warning_count), 'warning', 'had warnings' ], [ float(pass_count), 'success', 'passed' ] ] for b in pbars: if b[0]: note_html.append( '<div class="progress-bar progress-bar-{pbcol}" style="width: {pct}%" data-toggle="tooltip" title="{count} {sample} {txt}">{count}</div>'. \ format( pbcol = b[1], count = int(b[0]), pct = (b[0]/float(total_count))*100.0, txt = b[2], sample = 'samples' if b[0] > 1 else 'sample' ) ) note_html.append('</div>') return "\n".join(note_html)
python
def _generate_overview_note(pass_count, only_warning_count, error_count, total_count): note_html = ['<div class="progress">'] pbars = [ [ float(error_count), 'danger', 'had errors' ], [ float(only_warning_count), 'warning', 'had warnings' ], [ float(pass_count), 'success', 'passed' ] ] for b in pbars: if b[0]: note_html.append( '<div class="progress-bar progress-bar-{pbcol}" style="width: {pct}%" data-toggle="tooltip" title="{count} {sample} {txt}">{count}</div>'. \ format( pbcol = b[1], count = int(b[0]), pct = (b[0]/float(total_count))*100.0, txt = b[2], sample = 'samples' if b[0] > 1 else 'sample' ) ) note_html.append('</div>') return "\n".join(note_html)
[ "def", "_generate_overview_note", "(", "pass_count", ",", "only_warning_count", ",", "error_count", ",", "total_count", ")", ":", "note_html", "=", "[", "'<div class=\"progress\">'", "]", "pbars", "=", "[", "[", "float", "(", "error_count", ")", ",", "'danger'", ...
Generates and returns the HTML note that provides a summary of validation status.
[ "Generates", "and", "returns", "the", "HTML", "note", "that", "provides", "a", "summary", "of", "validation", "status", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/ValidateSamFile.py#L292-L315
224,493
ewels/MultiQC
multiqc/modules/picard/ValidateSamFile.py
_generate_detailed_table
def _generate_detailed_table(data): """ Generates and retuns the HTML table that overviews the details found. """ headers = _get_general_stats_headers() # Only add headers for errors/warnings we have found for problems in data.values(): for problem in problems: if problem not in headers and problem in WARNING_DESCRIPTIONS: headers['WARNING_count']['hidden'] = False headers[problem] = { 'description': WARNING_DESCRIPTIONS[problem], 'namespace': 'WARNING', 'scale': headers['WARNING_count']['scale'], 'format': '{:.0f}', 'shared_key': 'warnings', 'hidden': True, # Hide by default; to unclutter things. } if problem not in headers and problem in ERROR_DESCRIPTIONS: headers['ERROR_count']['hidden'] = False headers[problem] = { 'description': ERROR_DESCRIPTIONS[problem], 'namespace': 'ERROR', 'scale': headers['ERROR_count']['scale'], 'format': '{:.0f}', 'shared_key': 'errors', 'hidden': True, # Hide by default; to unclutter things. } table_config = { 'table_title': 'Picard: SAM/BAM File Validation', } return table.plot(data=data, headers=headers, pconfig=table_config)
python
def _generate_detailed_table(data): headers = _get_general_stats_headers() # Only add headers for errors/warnings we have found for problems in data.values(): for problem in problems: if problem not in headers and problem in WARNING_DESCRIPTIONS: headers['WARNING_count']['hidden'] = False headers[problem] = { 'description': WARNING_DESCRIPTIONS[problem], 'namespace': 'WARNING', 'scale': headers['WARNING_count']['scale'], 'format': '{:.0f}', 'shared_key': 'warnings', 'hidden': True, # Hide by default; to unclutter things. } if problem not in headers and problem in ERROR_DESCRIPTIONS: headers['ERROR_count']['hidden'] = False headers[problem] = { 'description': ERROR_DESCRIPTIONS[problem], 'namespace': 'ERROR', 'scale': headers['ERROR_count']['scale'], 'format': '{:.0f}', 'shared_key': 'errors', 'hidden': True, # Hide by default; to unclutter things. } table_config = { 'table_title': 'Picard: SAM/BAM File Validation', } return table.plot(data=data, headers=headers, pconfig=table_config)
[ "def", "_generate_detailed_table", "(", "data", ")", ":", "headers", "=", "_get_general_stats_headers", "(", ")", "# Only add headers for errors/warnings we have found", "for", "problems", "in", "data", ".", "values", "(", ")", ":", "for", "problem", "in", "problems",...
Generates and retuns the HTML table that overviews the details found.
[ "Generates", "and", "retuns", "the", "HTML", "table", "that", "overviews", "the", "details", "found", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/ValidateSamFile.py#L318-L352
224,494
ewels/MultiQC
multiqc/modules/busco/busco.py
MultiqcModule.busco_plot
def busco_plot (self, lin): """ Make the HighCharts HTML for the BUSCO plot for a particular lineage """ data = {} for s_name in self.busco_data: if self.busco_data[s_name].get('lineage_dataset') == lin: data[s_name] = self.busco_data[s_name] plot_keys = ['complete_single_copy','complete_duplicated','fragmented','missing'] plot_cols = ['#7CB5EC', '#434348', '#F7A35C', '#FF3C50'] keys = OrderedDict() for k, col in zip(plot_keys, plot_cols): keys[k] = {'name': self.busco_keys[k], 'color': col} # Config for the plot config = { 'id': 'busco_plot_{}'.format(re.sub('\W+', '_', str(lin))), 'title': 'BUSCO: Assessment Results' if lin is None else 'BUSCO Assessment Results: {}'.format(lin), 'ylab': '# BUSCOs', 'cpswitch_counts_label': 'Number of BUSCOs' } return bargraph.plot(data, keys, config)
python
def busco_plot (self, lin): data = {} for s_name in self.busco_data: if self.busco_data[s_name].get('lineage_dataset') == lin: data[s_name] = self.busco_data[s_name] plot_keys = ['complete_single_copy','complete_duplicated','fragmented','missing'] plot_cols = ['#7CB5EC', '#434348', '#F7A35C', '#FF3C50'] keys = OrderedDict() for k, col in zip(plot_keys, plot_cols): keys[k] = {'name': self.busco_keys[k], 'color': col} # Config for the plot config = { 'id': 'busco_plot_{}'.format(re.sub('\W+', '_', str(lin))), 'title': 'BUSCO: Assessment Results' if lin is None else 'BUSCO Assessment Results: {}'.format(lin), 'ylab': '# BUSCOs', 'cpswitch_counts_label': 'Number of BUSCOs' } return bargraph.plot(data, keys, config)
[ "def", "busco_plot", "(", "self", ",", "lin", ")", ":", "data", "=", "{", "}", "for", "s_name", "in", "self", ".", "busco_data", ":", "if", "self", ".", "busco_data", "[", "s_name", "]", ".", "get", "(", "'lineage_dataset'", ")", "==", "lin", ":", ...
Make the HighCharts HTML for the BUSCO plot for a particular lineage
[ "Make", "the", "HighCharts", "HTML", "for", "the", "BUSCO", "plot", "for", "a", "particular", "lineage" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/busco/busco.py#L75-L97
224,495
ewels/MultiQC
multiqc/modules/trimmomatic/trimmomatic.py
MultiqcModule.trimmomatic_barplot
def trimmomatic_barplot (self): """ Make the HighCharts HTML to plot the trimmomatic rates """ # Specify the order of the different possible categories keys = OrderedDict() keys['surviving'] = { 'color': '#437bb1', 'name': 'Surviving Reads' } keys['both_surviving'] = { 'color': '#f7a35c', 'name': 'Both Surviving' } keys['forward_only_surviving'] = { 'color': '#e63491', 'name': 'Forward Only Surviving' } keys['reverse_only_surviving'] = { 'color': '#b1084c', 'name': 'Reverse Only Surviving' } keys['dropped'] = { 'color': '#7f0000', 'name': 'Dropped' } # Config for the plot pconfig = { 'id': 'trimmomatic_plot', 'title': 'Trimmomatic: Surviving Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } self.add_section( plot = bargraph.plot(self.trimmomatic, keys, pconfig) )
python
def trimmomatic_barplot (self): # Specify the order of the different possible categories keys = OrderedDict() keys['surviving'] = { 'color': '#437bb1', 'name': 'Surviving Reads' } keys['both_surviving'] = { 'color': '#f7a35c', 'name': 'Both Surviving' } keys['forward_only_surviving'] = { 'color': '#e63491', 'name': 'Forward Only Surviving' } keys['reverse_only_surviving'] = { 'color': '#b1084c', 'name': 'Reverse Only Surviving' } keys['dropped'] = { 'color': '#7f0000', 'name': 'Dropped' } # Config for the plot pconfig = { 'id': 'trimmomatic_plot', 'title': 'Trimmomatic: Surviving Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } self.add_section( plot = bargraph.plot(self.trimmomatic, keys, pconfig) )
[ "def", "trimmomatic_barplot", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'surviving'", "]", "=", "{", "'color'", ":", "'#437bb1'", ",", "'name'", ":", "'Surviving Reads'", "}...
Make the HighCharts HTML to plot the trimmomatic rates
[ "Make", "the", "HighCharts", "HTML", "to", "plot", "the", "trimmomatic", "rates" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/trimmomatic/trimmomatic.py#L113-L132
224,496
ewels/MultiQC
multiqc/modules/peddy/peddy.py
MultiqcModule.parse_peddy_summary
def parse_peddy_summary(self, f): """ Go through log file looking for peddy output """ parsed_data = dict() headers = None for l in f['f'].splitlines(): s = l.split("\t") if headers is None: s[0] = s[0].lstrip('#') headers = s else: parsed_data[s[1]] = dict() for i, v in enumerate(s): if i != 1: try: parsed_data[s[1]][headers[i]] = float(v) except ValueError: parsed_data[s[1]][headers[i]] = v if len(parsed_data) == 0: return None return parsed_data
python
def parse_peddy_summary(self, f): parsed_data = dict() headers = None for l in f['f'].splitlines(): s = l.split("\t") if headers is None: s[0] = s[0].lstrip('#') headers = s else: parsed_data[s[1]] = dict() for i, v in enumerate(s): if i != 1: try: parsed_data[s[1]][headers[i]] = float(v) except ValueError: parsed_data[s[1]][headers[i]] = v if len(parsed_data) == 0: return None return parsed_data
[ "def", "parse_peddy_summary", "(", "self", ",", "f", ")", ":", "parsed_data", "=", "dict", "(", ")", "headers", "=", "None", "for", "l", "in", "f", "[", "'f'", "]", ".", "splitlines", "(", ")", ":", "s", "=", "l", ".", "split", "(", "\"\\t\"", ")...
Go through log file looking for peddy output
[ "Go", "through", "log", "file", "looking", "for", "peddy", "output" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/peddy/peddy.py#L97-L116
224,497
ewels/MultiQC
multiqc/modules/peddy/peddy.py
MultiqcModule.parse_peddy_csv
def parse_peddy_csv(self, f, pattern): """ Parse csv output from peddy """ parsed_data = dict() headers = None s_name_idx = None for l in f['f'].splitlines(): s = l.split(",") if headers is None: headers = s try: s_name_idx = [headers.index("sample_id")] except ValueError: try: s_name_idx = [headers.index("sample_a"), headers.index("sample_b")] except ValueError: log.warn("Could not find sample name in Peddy output: {}".format(f['fn'])) return None else: s_name = '-'.join([s[idx] for idx in s_name_idx]) parsed_data[s_name] = dict() for i, v in enumerate(s): if i not in s_name_idx: if headers[i] == "error" and pattern == "sex_check": v = "True" if v == "False" else "False" try: # add the pattern as a suffix to key parsed_data[s_name][headers[i] + "_" + pattern] = float(v) except ValueError: # add the pattern as a suffix to key parsed_data[s_name][headers[i] + "_" + pattern] = v if len(parsed_data) == 0: return None return parsed_data
python
def parse_peddy_csv(self, f, pattern): parsed_data = dict() headers = None s_name_idx = None for l in f['f'].splitlines(): s = l.split(",") if headers is None: headers = s try: s_name_idx = [headers.index("sample_id")] except ValueError: try: s_name_idx = [headers.index("sample_a"), headers.index("sample_b")] except ValueError: log.warn("Could not find sample name in Peddy output: {}".format(f['fn'])) return None else: s_name = '-'.join([s[idx] for idx in s_name_idx]) parsed_data[s_name] = dict() for i, v in enumerate(s): if i not in s_name_idx: if headers[i] == "error" and pattern == "sex_check": v = "True" if v == "False" else "False" try: # add the pattern as a suffix to key parsed_data[s_name][headers[i] + "_" + pattern] = float(v) except ValueError: # add the pattern as a suffix to key parsed_data[s_name][headers[i] + "_" + pattern] = v if len(parsed_data) == 0: return None return parsed_data
[ "def", "parse_peddy_csv", "(", "self", ",", "f", ",", "pattern", ")", ":", "parsed_data", "=", "dict", "(", ")", "headers", "=", "None", "s_name_idx", "=", "None", "for", "l", "in", "f", "[", "'f'", "]", ".", "splitlines", "(", ")", ":", "s", "=", ...
Parse csv output from peddy
[ "Parse", "csv", "output", "from", "peddy" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/peddy/peddy.py#L118-L150
224,498
ewels/MultiQC
multiqc/modules/peddy/peddy.py
MultiqcModule.peddy_general_stats_table
def peddy_general_stats_table(self): """ Take the parsed stats from the Peddy report and add it to the basic stats table at the top of the report """ family_ids = [ x.get('family_id') for x in self.peddy_data.values() ] headers = OrderedDict() headers['family_id'] = { 'title': 'Family ID', 'hidden': True if all([v == family_ids[0] for v in family_ids]) else False } headers['ancestry-prediction'] = { 'title': 'Ancestry', 'description': 'Ancestry Prediction', } headers['ancestry-prob_het_check'] = { 'title': 'P(Ancestry)', 'description': 'Probability predicted ancestry is correct.' } headers['sex_het_ratio'] = { 'title': 'Sex / Het Ratio', } headers['error_sex_check'] = { 'title': 'Correct Sex', 'description': 'Displays False if error in sample sex prediction', } headers['predicted_sex_sex_check'] = { 'title': 'Sex', 'description': 'Predicted sex' } self.general_stats_addcols(self.peddy_data, headers)
python
def peddy_general_stats_table(self): family_ids = [ x.get('family_id') for x in self.peddy_data.values() ] headers = OrderedDict() headers['family_id'] = { 'title': 'Family ID', 'hidden': True if all([v == family_ids[0] for v in family_ids]) else False } headers['ancestry-prediction'] = { 'title': 'Ancestry', 'description': 'Ancestry Prediction', } headers['ancestry-prob_het_check'] = { 'title': 'P(Ancestry)', 'description': 'Probability predicted ancestry is correct.' } headers['sex_het_ratio'] = { 'title': 'Sex / Het Ratio', } headers['error_sex_check'] = { 'title': 'Correct Sex', 'description': 'Displays False if error in sample sex prediction', } headers['predicted_sex_sex_check'] = { 'title': 'Sex', 'description': 'Predicted sex' } self.general_stats_addcols(self.peddy_data, headers)
[ "def", "peddy_general_stats_table", "(", "self", ")", ":", "family_ids", "=", "[", "x", ".", "get", "(", "'family_id'", ")", "for", "x", "in", "self", ".", "peddy_data", ".", "values", "(", ")", "]", "headers", "=", "OrderedDict", "(", ")", "headers", ...
Take the parsed stats from the Peddy report and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "Peddy", "report", "and", "add", "it", "to", "the", "basic", "stats", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/peddy/peddy.py#L152-L182
224,499
ewels/MultiQC
multiqc/modules/samblaster/samblaster.py
MultiqcModule.add_barplot
def add_barplot(self): """ Generate the Samblaster bar plot. """ cats = OrderedDict() cats['n_nondups'] = {'name': 'Non-duplicates'} cats['n_dups'] = {'name': 'Duplicates'} pconfig = { 'id': 'samblaster_duplicates', 'title': 'Samblaster: Number of duplicate reads', 'ylab': 'Number of reads' } self.add_section( plot = bargraph.plot(self.samblaster_data, cats, pconfig) )
python
def add_barplot(self): cats = OrderedDict() cats['n_nondups'] = {'name': 'Non-duplicates'} cats['n_dups'] = {'name': 'Duplicates'} pconfig = { 'id': 'samblaster_duplicates', 'title': 'Samblaster: Number of duplicate reads', 'ylab': 'Number of reads' } self.add_section( plot = bargraph.plot(self.samblaster_data, cats, pconfig) )
[ "def", "add_barplot", "(", "self", ")", ":", "cats", "=", "OrderedDict", "(", ")", "cats", "[", "'n_nondups'", "]", "=", "{", "'name'", ":", "'Non-duplicates'", "}", "cats", "[", "'n_dups'", "]", "=", "{", "'name'", ":", "'Duplicates'", "}", "pconfig", ...
Generate the Samblaster bar plot.
[ "Generate", "the", "Samblaster", "bar", "plot", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/samblaster/samblaster.py#L56-L67