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,500
ewels/MultiQC
multiqc/modules/samblaster/samblaster.py
MultiqcModule.parse_samblaster
def parse_samblaster(self, f): """ Go through log file looking for samblaster output. If the Grab the name from the RG tag of the preceding bwa command """ dups_regex = "samblaster: (Removed|Marked) (\d+) of (\d+) \((\d+.\d+)%\) read ids as duplicates" input_file_regex = "samblaster: Opening (\S+) for read." rgtag_name_regex = "\\\\tID:(\S*?)\\\\t" data = {} s_name = None fh = f['f'] for l in fh: # try to find name from RG-tag. If bwa mem is used upstream samblaster with pipes, then the bwa mem command # including the read group will be written in the log match = re.search(rgtag_name_regex, l) if match: s_name = self.clean_s_name( match.group(1), f['root']) # try to find name from the input file name, if used match = re.search(input_file_regex, l) if match: basefn = os.path.basename(match.group(1)) fname, ext = os.path.splitext(basefn) # if it's stdin, then try bwa RG-tag instead if fname != 'stdin': s_name = self.clean_s_name( fname, f['root']) match = re.search(dups_regex, l) if match: data['n_dups'] = int(match.group(2)) data['n_tot'] = int(match.group(3)) data['n_nondups'] = data['n_tot'] - data['n_dups'] data['pct_dups'] = float(match.group(4)) if s_name is None: s_name = f['s_name'] if len(data) > 0: if s_name in self.samblaster_data: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name)) self.add_data_source(f, s_name) self.samblaster_data[s_name] = data
python
def parse_samblaster(self, f): dups_regex = "samblaster: (Removed|Marked) (\d+) of (\d+) \((\d+.\d+)%\) read ids as duplicates" input_file_regex = "samblaster: Opening (\S+) for read." rgtag_name_regex = "\\\\tID:(\S*?)\\\\t" data = {} s_name = None fh = f['f'] for l in fh: # try to find name from RG-tag. If bwa mem is used upstream samblaster with pipes, then the bwa mem command # including the read group will be written in the log match = re.search(rgtag_name_regex, l) if match: s_name = self.clean_s_name( match.group(1), f['root']) # try to find name from the input file name, if used match = re.search(input_file_regex, l) if match: basefn = os.path.basename(match.group(1)) fname, ext = os.path.splitext(basefn) # if it's stdin, then try bwa RG-tag instead if fname != 'stdin': s_name = self.clean_s_name( fname, f['root']) match = re.search(dups_regex, l) if match: data['n_dups'] = int(match.group(2)) data['n_tot'] = int(match.group(3)) data['n_nondups'] = data['n_tot'] - data['n_dups'] data['pct_dups'] = float(match.group(4)) if s_name is None: s_name = f['s_name'] if len(data) > 0: if s_name in self.samblaster_data: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name)) self.add_data_source(f, s_name) self.samblaster_data[s_name] = data
[ "def", "parse_samblaster", "(", "self", ",", "f", ")", ":", "dups_regex", "=", "\"samblaster: (Removed|Marked) (\\d+) of (\\d+) \\((\\d+.\\d+)%\\) read ids as duplicates\"", "input_file_regex", "=", "\"samblaster: Opening (\\S+) for read.\"", "rgtag_name_regex", "=", "\"\\\\\\\\tID:(...
Go through log file looking for samblaster output. If the Grab the name from the RG tag of the preceding bwa command
[ "Go", "through", "log", "file", "looking", "for", "samblaster", "output", ".", "If", "the", "Grab", "the", "name", "from", "the", "RG", "tag", "of", "the", "preceding", "bwa", "command" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/samblaster/samblaster.py#L69-L109
224,501
ewels/MultiQC
multiqc/modules/goleft_indexcov/goleft_indexcov.py
MultiqcModule._short_chrom
def _short_chrom(self, chrom): """Plot standard chromosomes + X, sorted numerically. Allows specification from a list of chromosomes via config for non-standard genomes. """ default_allowed = set(["X"]) allowed_chroms = set(getattr(config, "goleft_indexcov_config", {}).get("chromosomes", [])) chrom_clean = chrom.replace("chr", "") try: chrom_clean = int(chrom_clean) except ValueError: if chrom_clean not in default_allowed and chrom_clean not in allowed_chroms: chrom_clean = None if allowed_chroms: if chrom in allowed_chroms or chrom_clean in allowed_chroms: return chrom_clean elif isinstance(chrom_clean, int) or chrom_clean in default_allowed: return chrom_clean
python
def _short_chrom(self, chrom): default_allowed = set(["X"]) allowed_chroms = set(getattr(config, "goleft_indexcov_config", {}).get("chromosomes", [])) chrom_clean = chrom.replace("chr", "") try: chrom_clean = int(chrom_clean) except ValueError: if chrom_clean not in default_allowed and chrom_clean not in allowed_chroms: chrom_clean = None if allowed_chroms: if chrom in allowed_chroms or chrom_clean in allowed_chroms: return chrom_clean elif isinstance(chrom_clean, int) or chrom_clean in default_allowed: return chrom_clean
[ "def", "_short_chrom", "(", "self", ",", "chrom", ")", ":", "default_allowed", "=", "set", "(", "[", "\"X\"", "]", ")", "allowed_chroms", "=", "set", "(", "getattr", "(", "config", ",", "\"goleft_indexcov_config\"", ",", "{", "}", ")", ".", "get", "(", ...
Plot standard chromosomes + X, sorted numerically. Allows specification from a list of chromosomes via config for non-standard genomes.
[ "Plot", "standard", "chromosomes", "+", "X", "sorted", "numerically", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/goleft_indexcov/goleft_indexcov.py#L26-L46
224,502
ewels/MultiQC
multiqc/modules/conpair/conpair.py
MultiqcModule.parse_conpair_logs
def parse_conpair_logs(self, f): """ Go through log file looking for conpair concordance or contamination output One parser to rule them all. """ conpair_regexes = { 'concordance_concordance': r"Concordance: ([\d\.]+)%", 'concordance_used_markers': r"Based on (\d+)/\d+ markers", 'concordance_total_markers': r"Based on \d+/(\d+) markers", 'concordance_marker_threshold': r"\(coverage per marker threshold : (\d+) reads\)", 'concordance_min_mapping_quality': r"Minimum mappinq quality: (\d+)", 'concordance_min_base_quality': r"Minimum base quality: (\d+)", 'contamination_normal': r"Normal sample contamination level: ([\d\.]+)%", 'contamination_tumor': r"Tumor sample contamination level: ([\d\.]+)%" } parsed_data = {} for k, r in conpair_regexes.items(): match = re.search(r, f['f']) if match: parsed_data[k] = float(match.group(1)) def _cp_type(data): if 'concordance_concordance' in parsed_data: return 'concordance' elif 'contamination_normal' in parsed_data: return 'contamination' if len(parsed_data) > 0: if f['s_name'] in self.conpair_data: if(_cp_type(self.conpair_data[f['s_name']]) == _cp_type(parsed_data)): log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) else: self.conpair_data[f['s_name']] = dict() self.add_data_source(f, section=_cp_type(parsed_data)) self.conpair_data[f['s_name']].update(parsed_data)
python
def parse_conpair_logs(self, f): conpair_regexes = { 'concordance_concordance': r"Concordance: ([\d\.]+)%", 'concordance_used_markers': r"Based on (\d+)/\d+ markers", 'concordance_total_markers': r"Based on \d+/(\d+) markers", 'concordance_marker_threshold': r"\(coverage per marker threshold : (\d+) reads\)", 'concordance_min_mapping_quality': r"Minimum mappinq quality: (\d+)", 'concordance_min_base_quality': r"Minimum base quality: (\d+)", 'contamination_normal': r"Normal sample contamination level: ([\d\.]+)%", 'contamination_tumor': r"Tumor sample contamination level: ([\d\.]+)%" } parsed_data = {} for k, r in conpair_regexes.items(): match = re.search(r, f['f']) if match: parsed_data[k] = float(match.group(1)) def _cp_type(data): if 'concordance_concordance' in parsed_data: return 'concordance' elif 'contamination_normal' in parsed_data: return 'contamination' if len(parsed_data) > 0: if f['s_name'] in self.conpair_data: if(_cp_type(self.conpair_data[f['s_name']]) == _cp_type(parsed_data)): log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) else: self.conpair_data[f['s_name']] = dict() self.add_data_source(f, section=_cp_type(parsed_data)) self.conpair_data[f['s_name']].update(parsed_data)
[ "def", "parse_conpair_logs", "(", "self", ",", "f", ")", ":", "conpair_regexes", "=", "{", "'concordance_concordance'", ":", "r\"Concordance: ([\\d\\.]+)%\"", ",", "'concordance_used_markers'", ":", "r\"Based on (\\d+)/\\d+ markers\"", ",", "'concordance_total_markers'", ":",...
Go through log file looking for conpair concordance or contamination output One parser to rule them all.
[ "Go", "through", "log", "file", "looking", "for", "conpair", "concordance", "or", "contamination", "output", "One", "parser", "to", "rule", "them", "all", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/conpair/conpair.py#L53-L87
224,503
ewels/MultiQC
multiqc/modules/conpair/conpair.py
MultiqcModule.conpair_general_stats_table
def conpair_general_stats_table(self): """ Take the parsed stats from the Conpair report and add it to the basic stats table at the top of the report """ headers = {} headers['concordance_concordance'] = { 'title': 'Concordance', 'max': 100, 'min': 0, 'suffix': '%', 'format': '{:,.2f}', 'scale': 'RdYlGn' } headers['contamination_normal'] = { 'title': 'N Contamination', 'description': 'Normal sample contamination level', 'max': 100, 'min': 0, 'suffix': '%', 'format': '{:,.3f}', 'scale': 'RdYlBu-rev' } headers['contamination_tumor'] = { 'title': 'T Contamination', 'description': 'Tumor sample contamination level', 'max': 100, 'min': 0, 'suffix': '%', 'format': '{:,.3f}', 'scale': 'RdYlBu-rev' } self.general_stats_addcols(self.conpair_data, headers)
python
def conpair_general_stats_table(self): headers = {} headers['concordance_concordance'] = { 'title': 'Concordance', 'max': 100, 'min': 0, 'suffix': '%', 'format': '{:,.2f}', 'scale': 'RdYlGn' } headers['contamination_normal'] = { 'title': 'N Contamination', 'description': 'Normal sample contamination level', 'max': 100, 'min': 0, 'suffix': '%', 'format': '{:,.3f}', 'scale': 'RdYlBu-rev' } headers['contamination_tumor'] = { 'title': 'T Contamination', 'description': 'Tumor sample contamination level', 'max': 100, 'min': 0, 'suffix': '%', 'format': '{:,.3f}', 'scale': 'RdYlBu-rev' } self.general_stats_addcols(self.conpair_data, headers)
[ "def", "conpair_general_stats_table", "(", "self", ")", ":", "headers", "=", "{", "}", "headers", "[", "'concordance_concordance'", "]", "=", "{", "'title'", ":", "'Concordance'", ",", "'max'", ":", "100", ",", "'min'", ":", "0", ",", "'suffix'", ":", "'%'...
Take the parsed stats from the Conpair report and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "Conpair", "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/conpair/conpair.py#L90-L121
224,504
ewels/MultiQC
multiqc/modules/deeptools/plotPCA.py
plotPCAMixin.parse_plotPCA
def parse_plotPCA(self): """Find plotPCA output""" self.deeptools_plotPCAData = dict() for f in self.find_log_files('deeptools/plotPCAData', filehandles=False): parsed_data = self.parsePlotPCAData(f) for k, v in parsed_data.items(): if k in self.deeptools_plotPCAData: log.warning("Replacing duplicate sample {}.".format(k)) self.deeptools_plotPCAData[k] = v if len(parsed_data) > 0: self.add_data_source(f, section='plotPCA') if len(self.deeptools_plotPCAData) > 0: config = { 'id': 'deeptools_pca_plot', 'title': 'deeptools: PCA Plot', 'xlab': 'PC1', 'ylab': 'PC2', 'tt_label': 'PC1 {point.x:.2f}: PC2 {point.y:.2f}', } data = dict() for s_name in self.deeptools_plotPCAData: try: data[s_name] = {'x': self.deeptools_plotPCAData[s_name][1], 'y': self.deeptools_plotPCAData[s_name][2]} except KeyError: pass if len(data) == 0: log.debug('No valid data for PCA plot') return None self.add_section( name="PCA plot", anchor="deeptools_pca", description="PCA plot with the top two principal components calculated based on genome-wide distribution of sequence reads", plot=scatter.plot(data, config) ) return len(self.deeptools_plotPCAData)
python
def parse_plotPCA(self): self.deeptools_plotPCAData = dict() for f in self.find_log_files('deeptools/plotPCAData', filehandles=False): parsed_data = self.parsePlotPCAData(f) for k, v in parsed_data.items(): if k in self.deeptools_plotPCAData: log.warning("Replacing duplicate sample {}.".format(k)) self.deeptools_plotPCAData[k] = v if len(parsed_data) > 0: self.add_data_source(f, section='plotPCA') if len(self.deeptools_plotPCAData) > 0: config = { 'id': 'deeptools_pca_plot', 'title': 'deeptools: PCA Plot', 'xlab': 'PC1', 'ylab': 'PC2', 'tt_label': 'PC1 {point.x:.2f}: PC2 {point.y:.2f}', } data = dict() for s_name in self.deeptools_plotPCAData: try: data[s_name] = {'x': self.deeptools_plotPCAData[s_name][1], 'y': self.deeptools_plotPCAData[s_name][2]} except KeyError: pass if len(data) == 0: log.debug('No valid data for PCA plot') return None self.add_section( name="PCA plot", anchor="deeptools_pca", description="PCA plot with the top two principal components calculated based on genome-wide distribution of sequence reads", plot=scatter.plot(data, config) ) return len(self.deeptools_plotPCAData)
[ "def", "parse_plotPCA", "(", "self", ")", ":", "self", ".", "deeptools_plotPCAData", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'deeptools/plotPCAData'", ",", "filehandles", "=", "False", ")", ":", "parsed_data", "=", "self...
Find plotPCA output
[ "Find", "plotPCA", "output" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/deeptools/plotPCA.py#L17-L54
224,505
ewels/MultiQC
multiqc/utils/config.py
mqc_load_userconfig
def mqc_load_userconfig(paths=()): """ Overwrite config defaults with user config files """ # Load and parse installation config file if we find it mqc_load_config(os.path.join( os.path.dirname(MULTIQC_DIR), 'multiqc_config.yaml')) # Load and parse a user config file if we find it mqc_load_config(os.path.expanduser('~/.multiqc_config.yaml')) # Load and parse a config file path set in an ENV variable if we find it if os.environ.get('MULTIQC_CONFIG_PATH') is not None: mqc_load_config( os.environ.get('MULTIQC_CONFIG_PATH') ) # Load and parse a config file in this working directory if we find it mqc_load_config('multiqc_config.yaml') # Custom command line config for p in paths: mqc_load_config(p)
python
def mqc_load_userconfig(paths=()): # Load and parse installation config file if we find it mqc_load_config(os.path.join( os.path.dirname(MULTIQC_DIR), 'multiqc_config.yaml')) # Load and parse a user config file if we find it mqc_load_config(os.path.expanduser('~/.multiqc_config.yaml')) # Load and parse a config file path set in an ENV variable if we find it if os.environ.get('MULTIQC_CONFIG_PATH') is not None: mqc_load_config( os.environ.get('MULTIQC_CONFIG_PATH') ) # Load and parse a config file in this working directory if we find it mqc_load_config('multiqc_config.yaml') # Custom command line config for p in paths: mqc_load_config(p)
[ "def", "mqc_load_userconfig", "(", "paths", "=", "(", ")", ")", ":", "# Load and parse installation config file if we find it", "mqc_load_config", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "MULTIQC_DIR", ")", ",", "'multiq...
Overwrite config defaults with user config files
[ "Overwrite", "config", "defaults", "with", "user", "config", "files" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/config.py#L95-L113
224,506
ewels/MultiQC
multiqc/utils/config.py
mqc_load_config
def mqc_load_config(yaml_config): """ Load and parse a config file if we find it """ if os.path.isfile(yaml_config): try: with open(yaml_config) as f: new_config = yaml.safe_load(f) logger.debug("Loading config settings from: {}".format(yaml_config)) mqc_add_config(new_config, yaml_config) except (IOError, AttributeError) as e: logger.debug("Config error: {}".format(e)) except yaml.scanner.ScannerError as e: logger.error("Error parsing config YAML: {}".format(e)) sys.exit(1) else: logger.debug("No MultiQC config found: {}".format(yaml_config))
python
def mqc_load_config(yaml_config): if os.path.isfile(yaml_config): try: with open(yaml_config) as f: new_config = yaml.safe_load(f) logger.debug("Loading config settings from: {}".format(yaml_config)) mqc_add_config(new_config, yaml_config) except (IOError, AttributeError) as e: logger.debug("Config error: {}".format(e)) except yaml.scanner.ScannerError as e: logger.error("Error parsing config YAML: {}".format(e)) sys.exit(1) else: logger.debug("No MultiQC config found: {}".format(yaml_config))
[ "def", "mqc_load_config", "(", "yaml_config", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "yaml_config", ")", ":", "try", ":", "with", "open", "(", "yaml_config", ")", "as", "f", ":", "new_config", "=", "yaml", ".", "safe_load", "(", "f", ...
Load and parse a config file if we find it
[ "Load", "and", "parse", "a", "config", "file", "if", "we", "find", "it" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/config.py#L116-L130
224,507
ewels/MultiQC
multiqc/utils/config.py
mqc_add_config
def mqc_add_config(conf, conf_path=None): """ Add to the global config with given MultiQC config dict """ global fn_clean_exts, fn_clean_trim for c, v in conf.items(): if c == 'sp': # Merge filename patterns instead of replacing sp.update(v) logger.debug("Added to filename patterns: {}".format(v)) elif c == 'extra_fn_clean_exts': # Prepend to filename cleaning patterns instead of replacing fn_clean_exts[0:0] = v logger.debug("Added to filename clean extensions: {}".format(v)) elif c == 'extra_fn_clean_trim': # Prepend to filename cleaning patterns instead of replacing fn_clean_trim[0:0] = v logger.debug("Added to filename clean trimmings: {}".format(v)) elif c in ['custom_logo'] and v: # Resolve file paths - absolute or cwd, or relative to config file fpath = v if os.path.exists(v): fpath = os.path.abspath(v) elif conf_path is not None and os.path.exists(os.path.join(os.path.dirname(conf_path), v)): fpath = os.path.abspath(os.path.join(os.path.dirname(conf_path), v)) else: logger.error("Config '{}' path not found, skipping ({})".format(c, fpath)) continue logger.debug("New config '{}': {}".format(c, fpath)) update({c: fpath}) else: logger.debug("New config '{}': {}".format(c, v)) update({c: v})
python
def mqc_add_config(conf, conf_path=None): global fn_clean_exts, fn_clean_trim for c, v in conf.items(): if c == 'sp': # Merge filename patterns instead of replacing sp.update(v) logger.debug("Added to filename patterns: {}".format(v)) elif c == 'extra_fn_clean_exts': # Prepend to filename cleaning patterns instead of replacing fn_clean_exts[0:0] = v logger.debug("Added to filename clean extensions: {}".format(v)) elif c == 'extra_fn_clean_trim': # Prepend to filename cleaning patterns instead of replacing fn_clean_trim[0:0] = v logger.debug("Added to filename clean trimmings: {}".format(v)) elif c in ['custom_logo'] and v: # Resolve file paths - absolute or cwd, or relative to config file fpath = v if os.path.exists(v): fpath = os.path.abspath(v) elif conf_path is not None and os.path.exists(os.path.join(os.path.dirname(conf_path), v)): fpath = os.path.abspath(os.path.join(os.path.dirname(conf_path), v)) else: logger.error("Config '{}' path not found, skipping ({})".format(c, fpath)) continue logger.debug("New config '{}': {}".format(c, fpath)) update({c: fpath}) else: logger.debug("New config '{}': {}".format(c, v)) update({c: v})
[ "def", "mqc_add_config", "(", "conf", ",", "conf_path", "=", "None", ")", ":", "global", "fn_clean_exts", ",", "fn_clean_trim", "for", "c", ",", "v", "in", "conf", ".", "items", "(", ")", ":", "if", "c", "==", "'sp'", ":", "# Merge filename patterns instea...
Add to the global config with given MultiQC config dict
[ "Add", "to", "the", "global", "config", "with", "given", "MultiQC", "config", "dict" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/config.py#L149-L179
224,508
ewels/MultiQC
multiqc/utils/config.py
update_dict
def update_dict(d, u): """ Recursively updates nested dict d from nested dict u """ for key, val in u.items(): if isinstance(val, collections.Mapping): d[key] = update_dict(d.get(key, {}), val) else: d[key] = u[key] return d
python
def update_dict(d, u): for key, val in u.items(): if isinstance(val, collections.Mapping): d[key] = update_dict(d.get(key, {}), val) else: d[key] = u[key] return d
[ "def", "update_dict", "(", "d", ",", "u", ")", ":", "for", "key", ",", "val", "in", "u", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "collections", ".", "Mapping", ")", ":", "d", "[", "key", "]", "=", "update_dict", "(", "...
Recursively updates nested dict d from nested dict u
[ "Recursively", "updates", "nested", "dict", "d", "from", "nested", "dict", "u" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/config.py#L212-L220
224,509
ewels/MultiQC
multiqc/modules/preseq/preseq.py
_parse_preseq_logs
def _parse_preseq_logs(f): """ Go through log file looking for preseq output """ lines = f['f'].splitlines() header = lines.pop(0) data_is_bases = False if header.startswith('TOTAL_READS EXPECTED_DISTINCT'): pass elif header.startswith('TOTAL_BASES EXPECTED_DISTINCT'): data_is_bases = True elif header.startswith('total_reads distinct_reads'): pass else: log.debug("First line of preseq file {} did not look right".format(f['fn'])) return None, None data = dict() for l in lines: s = l.split() # Sometimes the Expected_distinct count drops to 0, not helpful if float(s[1]) == 0 and float(s[0]) > 0: continue data[float(s[0])] = float(s[1]) return data, data_is_bases
python
def _parse_preseq_logs(f): lines = f['f'].splitlines() header = lines.pop(0) data_is_bases = False if header.startswith('TOTAL_READS EXPECTED_DISTINCT'): pass elif header.startswith('TOTAL_BASES EXPECTED_DISTINCT'): data_is_bases = True elif header.startswith('total_reads distinct_reads'): pass else: log.debug("First line of preseq file {} did not look right".format(f['fn'])) return None, None data = dict() for l in lines: s = l.split() # Sometimes the Expected_distinct count drops to 0, not helpful if float(s[1]) == 0 and float(s[0]) > 0: continue data[float(s[0])] = float(s[1]) return data, data_is_bases
[ "def", "_parse_preseq_logs", "(", "f", ")", ":", "lines", "=", "f", "[", "'f'", "]", ".", "splitlines", "(", ")", "header", "=", "lines", ".", "pop", "(", "0", ")", "data_is_bases", "=", "False", "if", "header", ".", "startswith", "(", "'TOTAL_READS\tE...
Go through log file looking for preseq output
[ "Go", "through", "log", "file", "looking", "for", "preseq", "output" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/preseq/preseq.py#L188-L213
224,510
ewels/MultiQC
multiqc/utils/mqc_colour.py
mqc_colour_scale.get_colour
def get_colour(self, val, colformat='hex'): """ Given a value, return a colour within the colour scale """ try: # Sanity checks val = re.sub("[^0-9\.]", "", str(val)) if val == '': val = self.minval val = float(val) val = max(val, self.minval) val = min(val, self.maxval) domain_nums = list( np.linspace(self.minval, self.maxval, len(self.colours)) ) my_scale = spectra.scale(self.colours).domain(domain_nums) # Weird, I know. I ported this from the original JavaScript for continuity # Seems to work better than adjusting brightness / saturation / luminosity rgb_converter = lambda x: max(0, min(1, 1+((x-1)*0.3))) thecolour = spectra.rgb( *[rgb_converter(v) for v in my_scale(val).rgb] ) return thecolour.hexcode except: # Shouldn't crash all of MultiQC just for colours return ''
python
def get_colour(self, val, colformat='hex'): try: # Sanity checks val = re.sub("[^0-9\.]", "", str(val)) if val == '': val = self.minval val = float(val) val = max(val, self.minval) val = min(val, self.maxval) domain_nums = list( np.linspace(self.minval, self.maxval, len(self.colours)) ) my_scale = spectra.scale(self.colours).domain(domain_nums) # Weird, I know. I ported this from the original JavaScript for continuity # Seems to work better than adjusting brightness / saturation / luminosity rgb_converter = lambda x: max(0, min(1, 1+((x-1)*0.3))) thecolour = spectra.rgb( *[rgb_converter(v) for v in my_scale(val).rgb] ) return thecolour.hexcode except: # Shouldn't crash all of MultiQC just for colours return ''
[ "def", "get_colour", "(", "self", ",", "val", ",", "colformat", "=", "'hex'", ")", ":", "try", ":", "# Sanity checks", "val", "=", "re", ".", "sub", "(", "\"[^0-9\\.]\"", ",", "\"\"", ",", "str", "(", "val", ")", ")", "if", "val", "==", "''", ":", ...
Given a value, return a colour within the colour scale
[ "Given", "a", "value", "return", "a", "colour", "within", "the", "colour", "scale" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/mqc_colour.py#L41-L64
224,511
ewels/MultiQC
multiqc/modules/tophat/tophat.py
MultiqcModule.parse_tophat_log
def parse_tophat_log (self, raw_data): """ Parse the Tophat alignment log file. """ if 'Aligned pairs' in raw_data: # Paired end data regexes = { 'overall_aligned_percent': r"([\d\.]+)% overall read mapping rate.", 'concordant_aligned_percent': r"([\d\.]+)% concordant pair alignment rate.", 'aligned_total': r"Aligned pairs:\s+(\d+)", 'aligned_multimap': r"Aligned pairs:\s+\d+\n\s+of these:\s+(\d+)", 'aligned_discordant': r"(\d+) \([\s\d\.]+%\) are discordant alignments", 'total_reads': r"[Rr]eads:\n\s+Input\s*:\s+(\d+)", } else: # Single end data regexes = { 'total_reads': r"[Rr]eads:\n\s+Input\s*:\s+(\d+)", 'aligned_total': r"Mapped\s*:\s+(\d+)", 'aligned_multimap': r"of these\s*:\s+(\d+)", 'overall_aligned_percent': r"([\d\.]+)% overall read mapping rate.", } 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)) if len(parsed_data) == 0: return None parsed_data['concordant_aligned_percent'] = parsed_data.get('concordant_aligned_percent', 0) parsed_data['aligned_total'] = parsed_data.get('aligned_total', 0) parsed_data['aligned_multimap'] = parsed_data.get('aligned_multimap', 0) parsed_data['aligned_discordant'] = parsed_data.get('aligned_discordant', 0) parsed_data['unaligned_total'] = parsed_data['total_reads'] - parsed_data['aligned_total'] parsed_data['aligned_not_multimapped_discordant'] = parsed_data['aligned_total'] - parsed_data['aligned_multimap'] - parsed_data['aligned_discordant'] return parsed_data
python
def parse_tophat_log (self, raw_data): if 'Aligned pairs' in raw_data: # Paired end data regexes = { 'overall_aligned_percent': r"([\d\.]+)% overall read mapping rate.", 'concordant_aligned_percent': r"([\d\.]+)% concordant pair alignment rate.", 'aligned_total': r"Aligned pairs:\s+(\d+)", 'aligned_multimap': r"Aligned pairs:\s+\d+\n\s+of these:\s+(\d+)", 'aligned_discordant': r"(\d+) \([\s\d\.]+%\) are discordant alignments", 'total_reads': r"[Rr]eads:\n\s+Input\s*:\s+(\d+)", } else: # Single end data regexes = { 'total_reads': r"[Rr]eads:\n\s+Input\s*:\s+(\d+)", 'aligned_total': r"Mapped\s*:\s+(\d+)", 'aligned_multimap': r"of these\s*:\s+(\d+)", 'overall_aligned_percent': r"([\d\.]+)% overall read mapping rate.", } 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)) if len(parsed_data) == 0: return None parsed_data['concordant_aligned_percent'] = parsed_data.get('concordant_aligned_percent', 0) parsed_data['aligned_total'] = parsed_data.get('aligned_total', 0) parsed_data['aligned_multimap'] = parsed_data.get('aligned_multimap', 0) parsed_data['aligned_discordant'] = parsed_data.get('aligned_discordant', 0) parsed_data['unaligned_total'] = parsed_data['total_reads'] - parsed_data['aligned_total'] parsed_data['aligned_not_multimapped_discordant'] = parsed_data['aligned_total'] - parsed_data['aligned_multimap'] - parsed_data['aligned_discordant'] return parsed_data
[ "def", "parse_tophat_log", "(", "self", ",", "raw_data", ")", ":", "if", "'Aligned pairs'", "in", "raw_data", ":", "# Paired end data", "regexes", "=", "{", "'overall_aligned_percent'", ":", "r\"([\\d\\.]+)% overall read mapping rate.\"", ",", "'concordant_aligned_percent'"...
Parse the Tophat alignment log file.
[ "Parse", "the", "Tophat", "alignment", "log", "file", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/tophat/tophat.py#L62-L96
224,512
ewels/MultiQC
multiqc/modules/tophat/tophat.py
MultiqcModule.tophat_general_stats_table
def tophat_general_stats_table(self): """ Take the parsed stats from the Tophat report and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['overall_aligned_percent'] = { 'title': '% Aligned', 'description': 'overall read mapping rate', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['aligned_not_multimapped_discordant'] = { 'title': '{} Aligned'.format(config.read_count_prefix), 'description': 'Aligned reads, not multimapped or discordant ({})'.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.tophat_data, headers)
python
def tophat_general_stats_table(self): headers = OrderedDict() headers['overall_aligned_percent'] = { 'title': '% Aligned', 'description': 'overall read mapping rate', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['aligned_not_multimapped_discordant'] = { 'title': '{} Aligned'.format(config.read_count_prefix), 'description': 'Aligned reads, not multimapped or discordant ({})'.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.tophat_data, headers)
[ "def", "tophat_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'overall_aligned_percent'", "]", "=", "{", "'title'", ":", "'% Aligned'", ",", "'description'", ":", "'overall read mapping rate'", ",", "'max'", ...
Take the parsed stats from the Tophat report and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "Tophat", "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/tophat/tophat.py#L99-L120
224,513
ewels/MultiQC
multiqc/modules/cutadapt/cutadapt.py
MultiqcModule.cutadapt_length_trimmed_plot
def cutadapt_length_trimmed_plot (self): """ Generate the trimming length plot """ description = 'This plot shows the number of reads with certain lengths of adapter trimmed. \n\ Obs/Exp shows the raw counts divided by the number expected due to sequencing errors. A defined peak \n\ may be related to adapter length. See the \n\ <a href="http://cutadapt.readthedocs.org/en/latest/guide.html#how-to-read-the-report" target="_blank">cutadapt documentation</a> \n\ for more information on how these numbers are generated.' pconfig = { 'id': 'cutadapt_plot', 'title': 'Cutadapt: Lengths of Trimmed Sequences', 'ylab': 'Counts', 'xlab': 'Length Trimmed (bp)', 'xDecimals': False, 'ymin': 0, 'tt_label': '<b>{point.x} bp trimmed</b>: {point.y:.0f}', 'data_labels': [{'name': 'Counts', 'ylab': 'Count'}, {'name': 'Obs/Exp', 'ylab': 'Observed / Expected'}] } self.add_section( description = description, plot = linegraph.plot([self.cutadapt_length_counts, self.cutadapt_length_obsexp], pconfig) )
python
def cutadapt_length_trimmed_plot (self): description = 'This plot shows the number of reads with certain lengths of adapter trimmed. \n\ Obs/Exp shows the raw counts divided by the number expected due to sequencing errors. A defined peak \n\ may be related to adapter length. See the \n\ <a href="http://cutadapt.readthedocs.org/en/latest/guide.html#how-to-read-the-report" target="_blank">cutadapt documentation</a> \n\ for more information on how these numbers are generated.' pconfig = { 'id': 'cutadapt_plot', 'title': 'Cutadapt: Lengths of Trimmed Sequences', 'ylab': 'Counts', 'xlab': 'Length Trimmed (bp)', 'xDecimals': False, 'ymin': 0, 'tt_label': '<b>{point.x} bp trimmed</b>: {point.y:.0f}', 'data_labels': [{'name': 'Counts', 'ylab': 'Count'}, {'name': 'Obs/Exp', 'ylab': 'Observed / Expected'}] } self.add_section( description = description, plot = linegraph.plot([self.cutadapt_length_counts, self.cutadapt_length_obsexp], pconfig) )
[ "def", "cutadapt_length_trimmed_plot", "(", "self", ")", ":", "description", "=", "'This plot shows the number of reads with certain lengths of adapter trimmed. \\n\\\n Obs/Exp shows the raw counts divided by the number expected due to sequencing errors. A defined peak \\n\\\n may be r...
Generate the trimming length plot
[ "Generate", "the", "trimming", "length", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/cutadapt/cutadapt.py#L176-L200
224,514
ewels/MultiQC
multiqc/modules/bowtie2/bowtie2.py
MultiqcModule.bowtie2_general_stats_table
def bowtie2_general_stats_table(self): """ Take the parsed stats from the Bowtie 2 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.bowtie2_data, headers)
python
def bowtie2_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.bowtie2_data, headers)
[ "def", "bowtie2_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'overall_alignment_rate'", "]", "=", "{", "'title'", ":", "'% Aligned'", ",", "'description'", ":", "'overall alignment rate'", ",", "'max'", ":"...
Take the parsed stats from the Bowtie 2 report and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "Bowtie", "2", "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/bowtie2/bowtie2.py#L191-L204
224,515
ewels/MultiQC
multiqc/modules/damageprofiler/damageprofiler.py
MultiqcModule.parseJSON
def parseJSON(self, f): """ Parse the JSON output from DamageProfiler and save the summary statistics """ try: parsed_json = json.load(f['f']) except Exception as e: print(e) log.warn("Could not parse DamageProfiler JSON: '{}'".format(f['fn'])) return None #Get sample name from JSON first s_name = self.clean_s_name(parsed_json['metadata']['sample_name'],'') self.add_data_source(f, s_name) #Add 3' G to A data self.threepGtoAfreq_data[s_name] = parsed_json['dmg_3p'] #Add 5' C to T data self.fivepCtoTfreq_data[s_name] = parsed_json['dmg_5p'] #Add lendist forward self.lgdist_fw_data[s_name] = parsed_json['lendist_fw'] #Add lendist reverse self.lgdist_rv_data[s_name] = parsed_json['lendist_rv'] #Add summary metrics self.summary_metrics_data[s_name] = parsed_json['summary_stats']
python
def parseJSON(self, f): try: parsed_json = json.load(f['f']) except Exception as e: print(e) log.warn("Could not parse DamageProfiler JSON: '{}'".format(f['fn'])) return None #Get sample name from JSON first s_name = self.clean_s_name(parsed_json['metadata']['sample_name'],'') self.add_data_source(f, s_name) #Add 3' G to A data self.threepGtoAfreq_data[s_name] = parsed_json['dmg_3p'] #Add 5' C to T data self.fivepCtoTfreq_data[s_name] = parsed_json['dmg_5p'] #Add lendist forward self.lgdist_fw_data[s_name] = parsed_json['lendist_fw'] #Add lendist reverse self.lgdist_rv_data[s_name] = parsed_json['lendist_rv'] #Add summary metrics self.summary_metrics_data[s_name] = parsed_json['summary_stats']
[ "def", "parseJSON", "(", "self", ",", "f", ")", ":", "try", ":", "parsed_json", "=", "json", ".", "load", "(", "f", "[", "'f'", "]", ")", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "log", ".", "warn", "(", "\"Could not parse Dam...
Parse the JSON output from DamageProfiler and save the summary statistics
[ "Parse", "the", "JSON", "output", "from", "DamageProfiler", "and", "save", "the", "summary", "statistics" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/damageprofiler/damageprofiler.py#L96-L123
224,516
ewels/MultiQC
multiqc/modules/damageprofiler/damageprofiler.py
MultiqcModule.lgdistplot
def lgdistplot(self,dict_to_use,orientation): """Generate a read length distribution plot""" data = dict() for s_name in dict_to_use: try: data[s_name] = {int(d): int (dict_to_use[s_name][d]) for d in dict_to_use[s_name]} except KeyError: pass if len(data) == 0: log.debug('No valid data for forward read lgdist input!') return None config = { 'id': 'length-distribution-{}'.format(orientation), 'title': 'DamageProfiler: Read length distribution: {} '.format(orientation), 'ylab': 'Number of reads', 'xlab': 'Readlength (bp)', 'xDecimals': False, 'tt_label': '{point.y} reads of length {point.x}', 'ymin': 0, 'xmin': 0 } return linegraph.plot(data,config)
python
def lgdistplot(self,dict_to_use,orientation): data = dict() for s_name in dict_to_use: try: data[s_name] = {int(d): int (dict_to_use[s_name][d]) for d in dict_to_use[s_name]} except KeyError: pass if len(data) == 0: log.debug('No valid data for forward read lgdist input!') return None config = { 'id': 'length-distribution-{}'.format(orientation), 'title': 'DamageProfiler: Read length distribution: {} '.format(orientation), 'ylab': 'Number of reads', 'xlab': 'Readlength (bp)', 'xDecimals': False, 'tt_label': '{point.y} reads of length {point.x}', 'ymin': 0, 'xmin': 0 } return linegraph.plot(data,config)
[ "def", "lgdistplot", "(", "self", ",", "dict_to_use", ",", "orientation", ")", ":", "data", "=", "dict", "(", ")", "for", "s_name", "in", "dict_to_use", ":", "try", ":", "data", "[", "s_name", "]", "=", "{", "int", "(", "d", ")", ":", "int", "(", ...
Generate a read length distribution plot
[ "Generate", "a", "read", "length", "distribution", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/damageprofiler/damageprofiler.py#L215-L238
224,517
ewels/MultiQC
multiqc/modules/damageprofiler/damageprofiler.py
MultiqcModule.threeprime_plot
def threeprime_plot(self): """Generate a 3' G>A linegraph plot""" data = dict() dict_to_add = dict() # Create tuples out of entries for key in self.threepGtoAfreq_data: pos = list(range(1,len(self.threepGtoAfreq_data.get(key)))) #Multiply values by 100 to get % tmp = [i * 100.0 for i in self.threepGtoAfreq_data.get(key)] tuples = list(zip(pos,tmp)) # Get a dictionary out of it data = dict((x, y) for x, y in tuples) dict_to_add[key] = data config = { 'id': 'threeprime_misinc_plot', 'title': 'DamageProfiler: 3P G>A misincorporation plot', 'ylab': '% G to A substituted', 'xlab': 'Nucleotide position from 3\'', 'tt_label': '{point.y:.2f} % G>A misincorporations at nucleotide position {point.x}', 'ymin': 0, 'xmin': 1 } return linegraph.plot(dict_to_add,config)
python
def threeprime_plot(self): data = dict() dict_to_add = dict() # Create tuples out of entries for key in self.threepGtoAfreq_data: pos = list(range(1,len(self.threepGtoAfreq_data.get(key)))) #Multiply values by 100 to get % tmp = [i * 100.0 for i in self.threepGtoAfreq_data.get(key)] tuples = list(zip(pos,tmp)) # Get a dictionary out of it data = dict((x, y) for x, y in tuples) dict_to_add[key] = data config = { 'id': 'threeprime_misinc_plot', 'title': 'DamageProfiler: 3P G>A misincorporation plot', 'ylab': '% G to A substituted', 'xlab': 'Nucleotide position from 3\'', 'tt_label': '{point.y:.2f} % G>A misincorporations at nucleotide position {point.x}', 'ymin': 0, 'xmin': 1 } return linegraph.plot(dict_to_add,config)
[ "def", "threeprime_plot", "(", "self", ")", ":", "data", "=", "dict", "(", ")", "dict_to_add", "=", "dict", "(", ")", "# Create tuples out of entries", "for", "key", "in", "self", ".", "threepGtoAfreq_data", ":", "pos", "=", "list", "(", "range", "(", "1",...
Generate a 3' G>A linegraph plot
[ "Generate", "a", "3", "G", ">", "A", "linegraph", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/damageprofiler/damageprofiler.py#L242-L267
224,518
ewels/MultiQC
multiqc/modules/fastqc/fastqc.py
MultiqcModule.parse_fastqc_report
def parse_fastqc_report(self, file_contents, s_name=None, f=None): """ Takes contents from a fastq_data.txt file and parses out required statistics and data. Returns a dict with keys 'stats' and 'data'. Data is for plotting graphs, stats are for top table. """ # Make the sample name from the input filename if we find it fn_search = re.search(r"Filename\s+(.+)", file_contents) if fn_search: s_name = self.clean_s_name(fn_search.group(1) , f['root']) if s_name in self.fastqc_data.keys(): log.debug("Duplicate sample name found! Overwriting: {}".format(s_name)) self.add_data_source(f, s_name) self.fastqc_data[s_name] = { 'statuses': dict() } # Parse the report section = None s_headers = None self.dup_keys = [] for l in file_contents.splitlines(): if l == '>>END_MODULE': section = None s_headers = None elif l.startswith('>>'): (section, status) = l[2:].split("\t", 1) section = section.lower().replace(' ', '_') self.fastqc_data[s_name]['statuses'][section] = status elif section is not None: if l.startswith('#'): s_headers = l[1:].split("\t") # Special case: Total Deduplicated Percentage header line if s_headers[0] == 'Total Deduplicated Percentage': self.fastqc_data[s_name]['basic_statistics'].append({ 'measure': 'total_deduplicated_percentage', 'value': float(s_headers[1]) }) else: # Special case: Rename dedup header in old versions of FastQC (v10) if s_headers[1] == 'Relative count': s_headers[1] = 'Percentage of total' s_headers = [s.lower().replace(' ', '_') for s in s_headers] self.fastqc_data[s_name][section] = list() elif s_headers is not None: s = l.split("\t") row = dict() for (i, v) in enumerate(s): v.replace('NaN','0') try: v = float(v) except ValueError: pass row[s_headers[i]] = v self.fastqc_data[s_name][section].append(row) # Special case - need to remember order of duplication keys if section == 'sequence_duplication_levels': try: self.dup_keys.append(float(s[0])) except ValueError: self.dup_keys.append(s[0]) # Tidy up the Basic Stats self.fastqc_data[s_name]['basic_statistics'] = {d['measure']: d['value'] for d in self.fastqc_data[s_name]['basic_statistics']} # Calculate the average sequence length (Basic Statistics gives a range) length_bp = 0 total_count = 0 for d in self.fastqc_data[s_name].get('sequence_length_distribution', {}): length_bp += d['count'] * self.avg_bp_from_range(d['length']) total_count += d['count'] if total_count > 0: self.fastqc_data[s_name]['basic_statistics']['avg_sequence_length'] = length_bp / total_count
python
def parse_fastqc_report(self, file_contents, s_name=None, f=None): # Make the sample name from the input filename if we find it fn_search = re.search(r"Filename\s+(.+)", file_contents) if fn_search: s_name = self.clean_s_name(fn_search.group(1) , f['root']) if s_name in self.fastqc_data.keys(): log.debug("Duplicate sample name found! Overwriting: {}".format(s_name)) self.add_data_source(f, s_name) self.fastqc_data[s_name] = { 'statuses': dict() } # Parse the report section = None s_headers = None self.dup_keys = [] for l in file_contents.splitlines(): if l == '>>END_MODULE': section = None s_headers = None elif l.startswith('>>'): (section, status) = l[2:].split("\t", 1) section = section.lower().replace(' ', '_') self.fastqc_data[s_name]['statuses'][section] = status elif section is not None: if l.startswith('#'): s_headers = l[1:].split("\t") # Special case: Total Deduplicated Percentage header line if s_headers[0] == 'Total Deduplicated Percentage': self.fastqc_data[s_name]['basic_statistics'].append({ 'measure': 'total_deduplicated_percentage', 'value': float(s_headers[1]) }) else: # Special case: Rename dedup header in old versions of FastQC (v10) if s_headers[1] == 'Relative count': s_headers[1] = 'Percentage of total' s_headers = [s.lower().replace(' ', '_') for s in s_headers] self.fastqc_data[s_name][section] = list() elif s_headers is not None: s = l.split("\t") row = dict() for (i, v) in enumerate(s): v.replace('NaN','0') try: v = float(v) except ValueError: pass row[s_headers[i]] = v self.fastqc_data[s_name][section].append(row) # Special case - need to remember order of duplication keys if section == 'sequence_duplication_levels': try: self.dup_keys.append(float(s[0])) except ValueError: self.dup_keys.append(s[0]) # Tidy up the Basic Stats self.fastqc_data[s_name]['basic_statistics'] = {d['measure']: d['value'] for d in self.fastqc_data[s_name]['basic_statistics']} # Calculate the average sequence length (Basic Statistics gives a range) length_bp = 0 total_count = 0 for d in self.fastqc_data[s_name].get('sequence_length_distribution', {}): length_bp += d['count'] * self.avg_bp_from_range(d['length']) total_count += d['count'] if total_count > 0: self.fastqc_data[s_name]['basic_statistics']['avg_sequence_length'] = length_bp / total_count
[ "def", "parse_fastqc_report", "(", "self", ",", "file_contents", ",", "s_name", "=", "None", ",", "f", "=", "None", ")", ":", "# Make the sample name from the input filename if we find it", "fn_search", "=", "re", ".", "search", "(", "r\"Filename\\s+(.+)\"", ",", "f...
Takes contents from a fastq_data.txt file and parses out required statistics and data. Returns a dict with keys 'stats' and 'data'. Data is for plotting graphs, stats are for top table.
[ "Takes", "contents", "from", "a", "fastq_data", ".", "txt", "file", "and", "parses", "out", "required", "statistics", "and", "data", ".", "Returns", "a", "dict", "with", "keys", "stats", "and", "data", ".", "Data", "is", "for", "plotting", "graphs", "stats...
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastqc/fastqc.py#L117-L188
224,519
ewels/MultiQC
multiqc/modules/fastqc/fastqc.py
MultiqcModule.fastqc_general_stats
def fastqc_general_stats(self): """ Add some single-number stats to the basic statistics table at the top of the report """ # Prep the data data = dict() for s_name in self.fastqc_data: bs = self.fastqc_data[s_name]['basic_statistics'] data[s_name] = { 'percent_gc': bs['%GC'], 'avg_sequence_length': bs['avg_sequence_length'], 'total_sequences': bs['Total Sequences'], } try: data[s_name]['percent_duplicates'] = 100 - bs['total_deduplicated_percentage'] except KeyError: pass # Older versions of FastQC don't have this # Add count of fail statuses num_statuses = 0 num_fails = 0 for s in self.fastqc_data[s_name]['statuses'].values(): num_statuses += 1 if s == 'fail': num_fails += 1 data[s_name]['percent_fails'] = (float(num_fails)/float(num_statuses))*100.0 # Are sequence lengths interesting? seq_lengths = [x['avg_sequence_length'] for x in data.values()] hide_seq_length = False if max(seq_lengths) - min(seq_lengths) > 10 else True headers = OrderedDict() headers['percent_duplicates'] = { 'title': '% Dups', 'description': '% Duplicate Reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn-rev' } headers['percent_gc'] = { 'title': '% GC', 'description': 'Average % GC Content', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Set1', 'format': '{:,.0f}' } headers['avg_sequence_length'] = { 'title': 'Length', 'description': 'Average Sequence Length (bp)', 'min': 0, 'suffix': ' bp', 'scale': 'RdYlGn', 'format': '{:,.0f}', 'hidden': hide_seq_length } headers['percent_fails'] = { 'title': '% Failed', 'description': 'Percentage of modules failed in FastQC report (includes those not plotted here)', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Reds', 'format': '{:,.0f}', 'hidden': True } headers['total_sequences'] = { 'title': '{} Seqs'.format(config.read_count_prefix), 'description': 'Total Sequences ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'Blues', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } self.general_stats_addcols(data, headers)
python
def fastqc_general_stats(self): # Prep the data data = dict() for s_name in self.fastqc_data: bs = self.fastqc_data[s_name]['basic_statistics'] data[s_name] = { 'percent_gc': bs['%GC'], 'avg_sequence_length': bs['avg_sequence_length'], 'total_sequences': bs['Total Sequences'], } try: data[s_name]['percent_duplicates'] = 100 - bs['total_deduplicated_percentage'] except KeyError: pass # Older versions of FastQC don't have this # Add count of fail statuses num_statuses = 0 num_fails = 0 for s in self.fastqc_data[s_name]['statuses'].values(): num_statuses += 1 if s == 'fail': num_fails += 1 data[s_name]['percent_fails'] = (float(num_fails)/float(num_statuses))*100.0 # Are sequence lengths interesting? seq_lengths = [x['avg_sequence_length'] for x in data.values()] hide_seq_length = False if max(seq_lengths) - min(seq_lengths) > 10 else True headers = OrderedDict() headers['percent_duplicates'] = { 'title': '% Dups', 'description': '% Duplicate Reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn-rev' } headers['percent_gc'] = { 'title': '% GC', 'description': 'Average % GC Content', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Set1', 'format': '{:,.0f}' } headers['avg_sequence_length'] = { 'title': 'Length', 'description': 'Average Sequence Length (bp)', 'min': 0, 'suffix': ' bp', 'scale': 'RdYlGn', 'format': '{:,.0f}', 'hidden': hide_seq_length } headers['percent_fails'] = { 'title': '% Failed', 'description': 'Percentage of modules failed in FastQC report (includes those not plotted here)', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Reds', 'format': '{:,.0f}', 'hidden': True } headers['total_sequences'] = { 'title': '{} Seqs'.format(config.read_count_prefix), 'description': 'Total Sequences ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'Blues', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count' } self.general_stats_addcols(data, headers)
[ "def", "fastqc_general_stats", "(", "self", ")", ":", "# Prep the data", "data", "=", "dict", "(", ")", "for", "s_name", "in", "self", ".", "fastqc_data", ":", "bs", "=", "self", ".", "fastqc_data", "[", "s_name", "]", "[", "'basic_statistics'", "]", "data...
Add some single-number stats to the basic statistics table at the top of the report
[ "Add", "some", "single", "-", "number", "stats", "to", "the", "basic", "statistics", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastqc/fastqc.py#L190-L265
224,520
ewels/MultiQC
multiqc/modules/fastqc/fastqc.py
MultiqcModule.get_status_cols
def get_status_cols(self, section): """ Helper function - returns a list of colours according to the FastQC status of this module for each sample. """ colours = dict() for s_name in self.fastqc_data: status = self.fastqc_data[s_name]['statuses'].get(section, 'default') colours[s_name] = self.status_colours[status] return colours
python
def get_status_cols(self, section): colours = dict() for s_name in self.fastqc_data: status = self.fastqc_data[s_name]['statuses'].get(section, 'default') colours[s_name] = self.status_colours[status] return colours
[ "def", "get_status_cols", "(", "self", ",", "section", ")", ":", "colours", "=", "dict", "(", ")", "for", "s_name", "in", "self", ".", "fastqc_data", ":", "status", "=", "self", ".", "fastqc_data", "[", "s_name", "]", "[", "'statuses'", "]", ".", "get"...
Helper function - returns a list of colours according to the FastQC status of this module for each sample.
[ "Helper", "function", "-", "returns", "a", "list", "of", "colours", "according", "to", "the", "FastQC", "status", "of", "this", "module", "for", "each", "sample", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastqc/fastqc.py#L953-L960
224,521
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.homer_tagdirectory
def homer_tagdirectory(self): """ Find HOMER tagdirectory logs and parse their data """ self.parse_gc_content() self.parse_re_dist() self.parse_tagLength_dist() self.parse_tagInfo_data() self.parse_FreqDistribution_data() self.homer_stats_table_tagInfo() return sum([len(v) for v in self.tagdir_data.values()])
python
def homer_tagdirectory(self): self.parse_gc_content() self.parse_re_dist() self.parse_tagLength_dist() self.parse_tagInfo_data() self.parse_FreqDistribution_data() self.homer_stats_table_tagInfo() return sum([len(v) for v in self.tagdir_data.values()])
[ "def", "homer_tagdirectory", "(", "self", ")", ":", "self", ".", "parse_gc_content", "(", ")", "self", ".", "parse_re_dist", "(", ")", "self", ".", "parse_tagLength_dist", "(", ")", "self", ".", "parse_tagInfo_data", "(", ")", "self", ".", "parse_FreqDistribut...
Find HOMER tagdirectory logs and parse their data
[ "Find", "HOMER", "tagdirectory", "logs", "and", "parse", "their", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L19-L28
224,522
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.parse_gc_content
def parse_gc_content(self): """parses and plots GC content and genome GC content files""" # Find and parse GC content: for f in self.find_log_files('homer/GCcontent', filehandles=True): # Get the s_name from the parent directory s_name = os.path.basename(f['root']) s_name = self.clean_s_name(s_name, f['root']) parsed_data = self.parse_twoCol_file(f) if parsed_data is not None: if s_name in self.tagdir_data['GCcontent']: log.debug("Duplicate GCcontent sample log found! Overwriting: {}".format(s_name)) self.add_data_source(f, s_name, section='GCcontent') self.tagdir_data['GCcontent'][s_name] = parsed_data ## get esimated genome content distribution: for f in self.find_log_files('homer/genomeGCcontent', filehandles=True): parsed_data = self.parse_twoCol_file(f) if parsed_data is not None: if s_name + "_genome" in self.tagdir_data['GCcontent']: log.debug("Duplicate genome GCcontent sample log found! Overwriting: {}".format(s_name+ "_genome")) self.add_data_source(f, s_name + "_genome", section='GCcontent') self.tagdir_data['GCcontent'][s_name + "_genome"] = parsed_data self.tagdir_data['GCcontent'] = self.ignore_samples(self.tagdir_data['GCcontent']) if len(self.tagdir_data['GCcontent']) > 0: self.add_section ( name = 'Per Sequence GC Content', anchor = 'homer_per_sequence_gc_content', description = 'This plot shows the distribution of GC content.', plot = self.GCcontent_plot() )
python
def parse_gc_content(self): # Find and parse GC content: for f in self.find_log_files('homer/GCcontent', filehandles=True): # Get the s_name from the parent directory s_name = os.path.basename(f['root']) s_name = self.clean_s_name(s_name, f['root']) parsed_data = self.parse_twoCol_file(f) if parsed_data is not None: if s_name in self.tagdir_data['GCcontent']: log.debug("Duplicate GCcontent sample log found! Overwriting: {}".format(s_name)) self.add_data_source(f, s_name, section='GCcontent') self.tagdir_data['GCcontent'][s_name] = parsed_data ## get esimated genome content distribution: for f in self.find_log_files('homer/genomeGCcontent', filehandles=True): parsed_data = self.parse_twoCol_file(f) if parsed_data is not None: if s_name + "_genome" in self.tagdir_data['GCcontent']: log.debug("Duplicate genome GCcontent sample log found! Overwriting: {}".format(s_name+ "_genome")) self.add_data_source(f, s_name + "_genome", section='GCcontent') self.tagdir_data['GCcontent'][s_name + "_genome"] = parsed_data self.tagdir_data['GCcontent'] = self.ignore_samples(self.tagdir_data['GCcontent']) if len(self.tagdir_data['GCcontent']) > 0: self.add_section ( name = 'Per Sequence GC Content', anchor = 'homer_per_sequence_gc_content', description = 'This plot shows the distribution of GC content.', plot = self.GCcontent_plot() )
[ "def", "parse_gc_content", "(", "self", ")", ":", "# Find and parse GC content:", "for", "f", "in", "self", ".", "find_log_files", "(", "'homer/GCcontent'", ",", "filehandles", "=", "True", ")", ":", "# Get the s_name from the parent directory", "s_name", "=", "os", ...
parses and plots GC content and genome GC content files
[ "parses", "and", "plots", "GC", "content", "and", "genome", "GC", "content", "files" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L31-L64
224,523
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.parse_tagLength_dist
def parse_tagLength_dist(self): """parses and plots tag length distribution files""" # Find and parse homer tag length distribution reports for f in self.find_log_files('homer/LengthDistribution', filehandles=True): s_name = os.path.basename(f['root']) s_name = self.clean_s_name(s_name, f['root']) parsed_data = self.parse_length_dist(f) if parsed_data is not None: if s_name in self.tagdir_data['length']: log.debug("Duplicate Length Distribution sample log found! Overwriting: {}".format(s_name)) self.add_data_source(f, s_name, section='length') self.tagdir_data['length'][s_name] = parsed_data self.tagdir_data['length'] = self.ignore_samples(self.tagdir_data['length']) if len(self.tagdir_data['length']) > 0: self.add_section ( name = 'Tag Length Distribution', anchor = 'homer-tagLength', description = 'This plot shows the distribution of tag length.', helptext = 'This is a good quality control for tag length inputed into Homer.', plot = self.length_dist_chart() )
python
def parse_tagLength_dist(self): # Find and parse homer tag length distribution reports for f in self.find_log_files('homer/LengthDistribution', filehandles=True): s_name = os.path.basename(f['root']) s_name = self.clean_s_name(s_name, f['root']) parsed_data = self.parse_length_dist(f) if parsed_data is not None: if s_name in self.tagdir_data['length']: log.debug("Duplicate Length Distribution sample log found! Overwriting: {}".format(s_name)) self.add_data_source(f, s_name, section='length') self.tagdir_data['length'][s_name] = parsed_data self.tagdir_data['length'] = self.ignore_samples(self.tagdir_data['length']) if len(self.tagdir_data['length']) > 0: self.add_section ( name = 'Tag Length Distribution', anchor = 'homer-tagLength', description = 'This plot shows the distribution of tag length.', helptext = 'This is a good quality control for tag length inputed into Homer.', plot = self.length_dist_chart() )
[ "def", "parse_tagLength_dist", "(", "self", ")", ":", "# Find and parse homer tag length distribution reports", "for", "f", "in", "self", ".", "find_log_files", "(", "'homer/LengthDistribution'", ",", "filehandles", "=", "True", ")", ":", "s_name", "=", "os", ".", "...
parses and plots tag length distribution files
[ "parses", "and", "plots", "tag", "length", "distribution", "files" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L97-L118
224,524
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.homer_stats_table_tagInfo
def homer_stats_table_tagInfo(self): """ Add core HOMER stats to the general stats table from tagInfo file""" if len(self.tagdir_data['header']) == 0: return None headers = OrderedDict() headers['UniqPositions'] = { 'title': 'Uniq Pos', 'description': 'Numer of Unique Di-Tags Passed Through HOMER', 'format': '{:,.0f}', 'modify': lambda x: x * 0.000001, 'suffix': "M" } headers['TotalPositions'] = { 'title': 'Total Pos', 'description': 'Numer of Total Di-Tags Passed Through HOMER', 'format': '{:,.0f}', 'modify': lambda x: x * 0.000001, 'suffix': "M" } headers['fragmentLengthEstimate'] = { 'title': 'fragment Length', 'description': 'Estimate of Fragnment Length', 'format': '{:,.0f}' } headers['peakSizeEstimate'] = { 'title': 'Peak Size', 'description': 'Estimate of Peak Size', 'format': '{:,.0f}' } headers['tagsPerBP'] = { 'title': 'tagsPerBP', 'description': 'average tags Per basepair', 'format': '{:,.3f}', } headers['TagsPerPosition'] = { 'title': 'averageTagsPerPosition', 'description': 'Average Tags Per Position', 'format': '{:,.2f}' } headers['averageTagLength'] = { 'title': 'TagLength', 'description': 'Average Tag Length', 'format': '{:,.0f}' } headers['averageFragmentGCcontent'] = { 'title': 'GCcontent', 'description': 'Average Fragment GC content', 'max': 1, 'min': 0, 'format': '{:,.2f}' } self.general_stats_addcols(self.tagdir_data['header'], headers, 'HOMER')
python
def homer_stats_table_tagInfo(self): if len(self.tagdir_data['header']) == 0: return None headers = OrderedDict() headers['UniqPositions'] = { 'title': 'Uniq Pos', 'description': 'Numer of Unique Di-Tags Passed Through HOMER', 'format': '{:,.0f}', 'modify': lambda x: x * 0.000001, 'suffix': "M" } headers['TotalPositions'] = { 'title': 'Total Pos', 'description': 'Numer of Total Di-Tags Passed Through HOMER', 'format': '{:,.0f}', 'modify': lambda x: x * 0.000001, 'suffix': "M" } headers['fragmentLengthEstimate'] = { 'title': 'fragment Length', 'description': 'Estimate of Fragnment Length', 'format': '{:,.0f}' } headers['peakSizeEstimate'] = { 'title': 'Peak Size', 'description': 'Estimate of Peak Size', 'format': '{:,.0f}' } headers['tagsPerBP'] = { 'title': 'tagsPerBP', 'description': 'average tags Per basepair', 'format': '{:,.3f}', } headers['TagsPerPosition'] = { 'title': 'averageTagsPerPosition', 'description': 'Average Tags Per Position', 'format': '{:,.2f}' } headers['averageTagLength'] = { 'title': 'TagLength', 'description': 'Average Tag Length', 'format': '{:,.0f}' } headers['averageFragmentGCcontent'] = { 'title': 'GCcontent', 'description': 'Average Fragment GC content', 'max': 1, 'min': 0, 'format': '{:,.2f}' } self.general_stats_addcols(self.tagdir_data['header'], headers, 'HOMER')
[ "def", "homer_stats_table_tagInfo", "(", "self", ")", ":", "if", "len", "(", "self", ".", "tagdir_data", "[", "'header'", "]", ")", "==", "0", ":", "return", "None", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'UniqPositions'", "]", "=", "{...
Add core HOMER stats to the general stats table from tagInfo file
[ "Add", "core", "HOMER", "stats", "to", "the", "general", "stats", "table", "from", "tagInfo", "file" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L192-L246
224,525
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.homer_stats_table_interChr
def homer_stats_table_interChr(self): """ Add core HOMER stats to the general stats table from FrequencyDistribution file""" headers = OrderedDict() headers['InterChr'] = { 'title': 'InterChr', 'description': 'Fraction of Reads forming inter chromosomal interactions', 'format': '{:,.4f}' } self.general_stats_addcols(self.tagdir_data['FreqDistribution'], headers, 'Homer-InterChr')
python
def homer_stats_table_interChr(self): headers = OrderedDict() headers['InterChr'] = { 'title': 'InterChr', 'description': 'Fraction of Reads forming inter chromosomal interactions', 'format': '{:,.4f}' } self.general_stats_addcols(self.tagdir_data['FreqDistribution'], headers, 'Homer-InterChr')
[ "def", "homer_stats_table_interChr", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'InterChr'", "]", "=", "{", "'title'", ":", "'InterChr'", ",", "'description'", ":", "'Fraction of Reads forming inter chromosomal interactions'", ","...
Add core HOMER stats to the general stats table from FrequencyDistribution file
[ "Add", "core", "HOMER", "stats", "to", "the", "general", "stats", "table", "from", "FrequencyDistribution", "file" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L249-L258
224,526
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.parse_restriction_dist
def parse_restriction_dist(self, f): """ Parse HOMER tagdirectory petagRestrictionDistribution file. """ parsed_data = dict() firstline = True for l in f['f']: if firstline: #skip first line firstline = False continue s = l.split("\t") if len(s) > 1: nuc = float(s[0].strip()) v1 = float(s[1].strip()) v2 = float(s[2].strip()) v = v1 + v2 #parsed_data.update({nuc:v1}) #parsed_data.update({nuc:v2}) parsed_data.update({nuc:v}) return parsed_data
python
def parse_restriction_dist(self, f): parsed_data = dict() firstline = True for l in f['f']: if firstline: #skip first line firstline = False continue s = l.split("\t") if len(s) > 1: nuc = float(s[0].strip()) v1 = float(s[1].strip()) v2 = float(s[2].strip()) v = v1 + v2 #parsed_data.update({nuc:v1}) #parsed_data.update({nuc:v2}) parsed_data.update({nuc:v}) return parsed_data
[ "def", "parse_restriction_dist", "(", "self", ",", "f", ")", ":", "parsed_data", "=", "dict", "(", ")", "firstline", "=", "True", "for", "l", "in", "f", "[", "'f'", "]", ":", "if", "firstline", ":", "#skip first line", "firstline", "=", "False", "continu...
Parse HOMER tagdirectory petagRestrictionDistribution file.
[ "Parse", "HOMER", "tagdirectory", "petagRestrictionDistribution", "file", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L285-L302
224,527
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.parse_length_dist
def parse_length_dist(self, f): """ Parse HOMER tagdirectory tagLengthDistribution file. """ parsed_data = dict() firstline = True for l in f['f']: if firstline: #skip first line firstline = False continue s = l.split("\t") if len(s) > 1: k = float(s[0].strip()) v = float(s[1].strip()) parsed_data[k] = v return parsed_data
python
def parse_length_dist(self, f): parsed_data = dict() firstline = True for l in f['f']: if firstline: #skip first line firstline = False continue s = l.split("\t") if len(s) > 1: k = float(s[0].strip()) v = float(s[1].strip()) parsed_data[k] = v return parsed_data
[ "def", "parse_length_dist", "(", "self", ",", "f", ")", ":", "parsed_data", "=", "dict", "(", ")", "firstline", "=", "True", "for", "l", "in", "f", "[", "'f'", "]", ":", "if", "firstline", ":", "#skip first line", "firstline", "=", "False", "continue", ...
Parse HOMER tagdirectory tagLengthDistribution file.
[ "Parse", "HOMER", "tagdirectory", "tagLengthDistribution", "file", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L305-L319
224,528
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.parse_tag_info
def parse_tag_info(self, f): """ Parse HOMER tagdirectory taginfo.txt file to extract statistics in the first 11 lines. """ # General Stats Table tag_info = dict() for l in f['f']: s = l.split("=") if len(s) > 1: if s[0].strip() == 'genome': ss = s[1].split("\t") if len(ss) > 2: tag_info['genome'] = ss[0].strip() try: tag_info['UniqPositions'] = float(ss[1].strip()) tag_info['TotalPositions'] = float(ss[2].strip()) except: tag_info['UniqPositions'] = ss[1].strip() tag_info['TotalPositions'] = ss[2].strip() try: tag_info[s[0].strip()] = float(s[1].strip()) except ValueError: tag_info[s[0].strip()] = s[1].strip() return tag_info
python
def parse_tag_info(self, f): # General Stats Table tag_info = dict() for l in f['f']: s = l.split("=") if len(s) > 1: if s[0].strip() == 'genome': ss = s[1].split("\t") if len(ss) > 2: tag_info['genome'] = ss[0].strip() try: tag_info['UniqPositions'] = float(ss[1].strip()) tag_info['TotalPositions'] = float(ss[2].strip()) except: tag_info['UniqPositions'] = ss[1].strip() tag_info['TotalPositions'] = ss[2].strip() try: tag_info[s[0].strip()] = float(s[1].strip()) except ValueError: tag_info[s[0].strip()] = s[1].strip() return tag_info
[ "def", "parse_tag_info", "(", "self", ",", "f", ")", ":", "# General Stats Table", "tag_info", "=", "dict", "(", ")", "for", "l", "in", "f", "[", "'f'", "]", ":", "s", "=", "l", ".", "split", "(", "\"=\"", ")", "if", "len", "(", "s", ")", ">", ...
Parse HOMER tagdirectory taginfo.txt file to extract statistics in the first 11 lines.
[ "Parse", "HOMER", "tagdirectory", "taginfo", ".", "txt", "file", "to", "extract", "statistics", "in", "the", "first", "11", "lines", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L322-L343
224,529
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.parse_tag_info_chrs
def parse_tag_info_chrs(self, f, convChr=True): """ Parse HOMER tagdirectory taginfo.txt file to extract chromosome coverage. """ parsed_data_total = OrderedDict() parsed_data_uniq = OrderedDict() remove = ["hap", "random", "chrUn", "cmd", "EBV", "GL", "NT_"] for l in f['f']: s = l.split("\t") key = s[0].strip() # skip header if '=' in l or len(s) != 3: continue if convChr: if any(x in key for x in remove): continue try: vT = float(s[1].strip()) vU = float(s[2].strip()) except ValueError: continue parsed_data_total[key] = vT parsed_data_uniq[key] = vU return [parsed_data_total, parsed_data_uniq]
python
def parse_tag_info_chrs(self, f, convChr=True): parsed_data_total = OrderedDict() parsed_data_uniq = OrderedDict() remove = ["hap", "random", "chrUn", "cmd", "EBV", "GL", "NT_"] for l in f['f']: s = l.split("\t") key = s[0].strip() # skip header if '=' in l or len(s) != 3: continue if convChr: if any(x in key for x in remove): continue try: vT = float(s[1].strip()) vU = float(s[2].strip()) except ValueError: continue parsed_data_total[key] = vT parsed_data_uniq[key] = vU return [parsed_data_total, parsed_data_uniq]
[ "def", "parse_tag_info_chrs", "(", "self", ",", "f", ",", "convChr", "=", "True", ")", ":", "parsed_data_total", "=", "OrderedDict", "(", ")", "parsed_data_uniq", "=", "OrderedDict", "(", ")", "remove", "=", "[", "\"hap\"", ",", "\"random\"", ",", "\"chrUn\"...
Parse HOMER tagdirectory taginfo.txt file to extract chromosome coverage.
[ "Parse", "HOMER", "tagdirectory", "taginfo", ".", "txt", "file", "to", "extract", "chromosome", "coverage", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L348-L371
224,530
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.parse_FreqDist
def parse_FreqDist(self, f): """ Parse HOMER tagdirectory petag.FreqDistribution_1000 file. """ parsed_data = dict() firstline = True for l in f['f']: if firstline: firstline = False continue else: s = l.split("\t") if len(s) > 1: k = s[0].strip() if k.startswith("More than "): k = re.sub("More than ", "", k) k = float(k) v = float(s[1].strip()) parsed_data[k] = v return parsed_data
python
def parse_FreqDist(self, f): parsed_data = dict() firstline = True for l in f['f']: if firstline: firstline = False continue else: s = l.split("\t") if len(s) > 1: k = s[0].strip() if k.startswith("More than "): k = re.sub("More than ", "", k) k = float(k) v = float(s[1].strip()) parsed_data[k] = v return parsed_data
[ "def", "parse_FreqDist", "(", "self", ",", "f", ")", ":", "parsed_data", "=", "dict", "(", ")", "firstline", "=", "True", "for", "l", "in", "f", "[", "'f'", "]", ":", "if", "firstline", ":", "firstline", "=", "False", "continue", "else", ":", "s", ...
Parse HOMER tagdirectory petag.FreqDistribution_1000 file.
[ "Parse", "HOMER", "tagdirectory", "petag", ".", "FreqDistribution_1000", "file", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L374-L392
224,531
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.parse_FreqDist_interChr
def parse_FreqDist_interChr(self, f): """ Parse HOMER tagdirectory petag.FreqDistribution_1000 file to get inter-chromosomal interactions. """ parsed_data = dict() firstline = True for l in f['f']: if firstline: firstline = False interChr = float(re.sub("\)", "", l.split(":")[1])) else: break parsed_data['interChr'] = interChr return parsed_data
python
def parse_FreqDist_interChr(self, f): parsed_data = dict() firstline = True for l in f['f']: if firstline: firstline = False interChr = float(re.sub("\)", "", l.split(":")[1])) else: break parsed_data['interChr'] = interChr return parsed_data
[ "def", "parse_FreqDist_interChr", "(", "self", ",", "f", ")", ":", "parsed_data", "=", "dict", "(", ")", "firstline", "=", "True", "for", "l", "in", "f", "[", "'f'", "]", ":", "if", "firstline", ":", "firstline", "=", "False", "interChr", "=", "float",...
Parse HOMER tagdirectory petag.FreqDistribution_1000 file to get inter-chromosomal interactions.
[ "Parse", "HOMER", "tagdirectory", "petag", ".", "FreqDistribution_1000", "file", "to", "get", "inter", "-", "chromosomal", "interactions", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L394-L405
224,532
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.restriction_dist_chart
def restriction_dist_chart (self): """ Make the petagRestrictionDistribution plot """ pconfig = { 'id': 'petagRestrictionDistribution', 'title': 'Restriction Distribution', 'ylab': 'Reads', 'xlab': 'Distance from cut site (bp)', 'data_labels': [ {'name': 'Number of Tags'}, {'name': 'Percenatge'} ] } datasets = [ self.tagdir_data['restriction'], self.tagdir_data['restriction_norm'] ] return linegraph.plot(datasets, pconfig)
python
def restriction_dist_chart (self): pconfig = { 'id': 'petagRestrictionDistribution', 'title': 'Restriction Distribution', 'ylab': 'Reads', 'xlab': 'Distance from cut site (bp)', 'data_labels': [ {'name': 'Number of Tags'}, {'name': 'Percenatge'} ] } datasets = [ self.tagdir_data['restriction'], self.tagdir_data['restriction_norm'] ] return linegraph.plot(datasets, pconfig)
[ "def", "restriction_dist_chart", "(", "self", ")", ":", "pconfig", "=", "{", "'id'", ":", "'petagRestrictionDistribution'", ",", "'title'", ":", "'Restriction Distribution'", ",", "'ylab'", ":", "'Reads'", ",", "'xlab'", ":", "'Distance from cut site (bp)'", ",", "'...
Make the petagRestrictionDistribution plot
[ "Make", "the", "petagRestrictionDistribution", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L408-L427
224,533
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.GCcontent_plot
def GCcontent_plot (self): """ Create the HTML for the Homer GC content plot """ pconfig = { 'id': 'homer-tag-directory-gc-content', 'title': 'Homer: Tag Directory Per Sequence GC Content', 'smooth_points': 200, 'smooth_points_sumcounts': False, 'ylab': 'Normalized Count', 'xlab': '% GC', 'ymin': 0, 'xmax': 1, 'xmin': 0, 'yDecimals': True, 'tt_label': '<b>{point.x}% GC</b>: {point.y}' } return linegraph.plot(self.tagdir_data['GCcontent'], pconfig)
python
def GCcontent_plot (self): pconfig = { 'id': 'homer-tag-directory-gc-content', 'title': 'Homer: Tag Directory Per Sequence GC Content', 'smooth_points': 200, 'smooth_points_sumcounts': False, 'ylab': 'Normalized Count', 'xlab': '% GC', 'ymin': 0, 'xmax': 1, 'xmin': 0, 'yDecimals': True, 'tt_label': '<b>{point.x}% GC</b>: {point.y}' } return linegraph.plot(self.tagdir_data['GCcontent'], pconfig)
[ "def", "GCcontent_plot", "(", "self", ")", ":", "pconfig", "=", "{", "'id'", ":", "'homer-tag-directory-gc-content'", ",", "'title'", ":", "'Homer: Tag Directory Per Sequence GC Content'", ",", "'smooth_points'", ":", "200", ",", "'smooth_points_sumcounts'", ":", "False...
Create the HTML for the Homer GC content plot
[ "Create", "the", "HTML", "for", "the", "Homer", "GC", "content", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L447-L463
224,534
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.tag_info_chart
def tag_info_chart (self): """ Make the taginfo.txt plot """ ## TODO: human chrs on hg19. How will this work with GRCh genome or other, non human, genomes? # nice if they are ordered by size ucsc = ["chr" + str(i) for i in range(1,23)].append([ "chrX", "chrY", "chrM"]) ensembl = list(range(1,23)).append([ "X", "Y", "MT"]) pconfig = { 'id': 'tagInfo', 'title': 'Homer: Tag Info Distribution', 'ylab': 'Tags', 'cpswitch_counts_label': 'Number of Tags' } ## check if chromosomes starts with "chr" (UCSC) or "#" (ensembl) sample1 = next(iter(self.tagdir_data['taginfo_total'])) chrFormat = next(iter(self.tagdir_data['taginfo_total'][sample1])) if ("chr" in chrFormat): chrs = ucsc else: chrs = ensembl return bargraph.plot(self.tagdir_data['taginfo_total'], chrs, pconfig)
python
def tag_info_chart (self): ## TODO: human chrs on hg19. How will this work with GRCh genome or other, non human, genomes? # nice if they are ordered by size ucsc = ["chr" + str(i) for i in range(1,23)].append([ "chrX", "chrY", "chrM"]) ensembl = list(range(1,23)).append([ "X", "Y", "MT"]) pconfig = { 'id': 'tagInfo', 'title': 'Homer: Tag Info Distribution', 'ylab': 'Tags', 'cpswitch_counts_label': 'Number of Tags' } ## check if chromosomes starts with "chr" (UCSC) or "#" (ensembl) sample1 = next(iter(self.tagdir_data['taginfo_total'])) chrFormat = next(iter(self.tagdir_data['taginfo_total'][sample1])) if ("chr" in chrFormat): chrs = ucsc else: chrs = ensembl return bargraph.plot(self.tagdir_data['taginfo_total'], chrs, pconfig)
[ "def", "tag_info_chart", "(", "self", ")", ":", "## TODO: human chrs on hg19. How will this work with GRCh genome or other, non human, genomes?", "# nice if they are ordered by size", "ucsc", "=", "[", "\"chr\"", "+", "str", "(", "i", ")", "for", "i", "in", "range", "(", ...
Make the taginfo.txt plot
[ "Make", "the", "taginfo", ".", "txt", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L466-L490
224,535
ewels/MultiQC
multiqc/modules/homer/tagdirectory.py
TagDirReportMixin.FreqDist_chart
def FreqDist_chart (self): """ Make the petag.FreqDistribution_1000 plot """ # Take a log of the data before plotting so that we can # reduce the number of points to plot evenly pdata = {} for idx, s_name in enumerate(self.tagdir_data['FreqDistribution']): pdata[s_name] = {} for x, y in self.tagdir_data['FreqDistribution'][s_name].items(): try: pdata[s_name][math.log(float(x))] = y except ValueError: pass pconfig = { 'id': 'FreqDistribution', 'title': 'Frequency Distribution', 'ylab': 'Fraction of Reads', 'xlab': 'Log10(Distance between regions)', 'data_labels': ['Reads', 'Percent'], 'smooth_points': 500, 'smooth_points_sumcounts': False, 'yLog' : True } return linegraph.plot(pdata, pconfig)
python
def FreqDist_chart (self): # Take a log of the data before plotting so that we can # reduce the number of points to plot evenly pdata = {} for idx, s_name in enumerate(self.tagdir_data['FreqDistribution']): pdata[s_name] = {} for x, y in self.tagdir_data['FreqDistribution'][s_name].items(): try: pdata[s_name][math.log(float(x))] = y except ValueError: pass pconfig = { 'id': 'FreqDistribution', 'title': 'Frequency Distribution', 'ylab': 'Fraction of Reads', 'xlab': 'Log10(Distance between regions)', 'data_labels': ['Reads', 'Percent'], 'smooth_points': 500, 'smooth_points_sumcounts': False, 'yLog' : True } return linegraph.plot(pdata, pconfig)
[ "def", "FreqDist_chart", "(", "self", ")", ":", "# Take a log of the data before plotting so that we can", "# reduce the number of points to plot evenly", "pdata", "=", "{", "}", "for", "idx", ",", "s_name", "in", "enumerate", "(", "self", ".", "tagdir_data", "[", "'Fre...
Make the petag.FreqDistribution_1000 plot
[ "Make", "the", "petag", ".", "FreqDistribution_1000", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/tagdirectory.py#L493-L515
224,536
ewels/MultiQC
multiqc/modules/bismark/bismark.py
MultiqcModule.parse_bismark_report
def parse_bismark_report(self, report, regexes): """ Search a bismark report with a set of regexes """ parsed_data = {} for k, r in regexes.items(): r_search = re.search(r, report, re.MULTILINE) if r_search: try: parsed_data[k] = float(r_search.group(1)) except ValueError: parsed_data[k] = r_search.group(1) # NaN if len(parsed_data) == 0: return None return parsed_data
python
def parse_bismark_report(self, report, regexes): parsed_data = {} for k, r in regexes.items(): r_search = re.search(r, report, re.MULTILINE) if r_search: try: parsed_data[k] = float(r_search.group(1)) except ValueError: parsed_data[k] = r_search.group(1) # NaN if len(parsed_data) == 0: return None return parsed_data
[ "def", "parse_bismark_report", "(", "self", ",", "report", ",", "regexes", ")", ":", "parsed_data", "=", "{", "}", "for", "k", ",", "r", "in", "regexes", ".", "items", "(", ")", ":", "r_search", "=", "re", ".", "search", "(", "r", ",", "report", ",...
Search a bismark report with a set of regexes
[ "Search", "a", "bismark", "report", "with", "a", "set", "of", "regexes" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bismark/bismark.py#L173-L184
224,537
ewels/MultiQC
multiqc/modules/bismark/bismark.py
MultiqcModule.parse_bismark_mbias
def parse_bismark_mbias(self, f): """ Parse the Bismark M-Bias plot data """ s = f['s_name'] self.bismark_mbias_data['meth']['CpG_R1'][s] = {} self.bismark_mbias_data['meth']['CHG_R1'][s] = {} self.bismark_mbias_data['meth']['CHH_R1'][s] = {} self.bismark_mbias_data['cov']['CpG_R1'][s] = {} self.bismark_mbias_data['cov']['CHG_R1'][s] = {} self.bismark_mbias_data['cov']['CHH_R1'][s] = {} self.bismark_mbias_data['meth']['CpG_R2'][s] = {} self.bismark_mbias_data['meth']['CHG_R2'][s] = {} self.bismark_mbias_data['meth']['CHH_R2'][s] = {} self.bismark_mbias_data['cov']['CpG_R2'][s] = {} self.bismark_mbias_data['cov']['CHG_R2'][s] = {} self.bismark_mbias_data['cov']['CHH_R2'][s] = {} key = None for l in f['f']: if 'context' in l: if 'CpG' in l: key = 'CpG' elif 'CHG' in l: key = 'CHG' elif 'CHH' in l: key = 'CHH' if '(R1)' in l: key += '_R1' elif '(R2)' in l: key += '_R2' else: key += '_R1' if key is not None: sections = l.split() try: pos = int(sections[0]) self.bismark_mbias_data['meth'][key][s][pos] = float(sections[3]) self.bismark_mbias_data['cov'][key][s][pos] = int(sections[4]) except (IndexError, ValueError): continue # Remove empty dicts (eg. R2 for SE data) for t in self.bismark_mbias_data: for k in self.bismark_mbias_data[t]: self.bismark_mbias_data[t][k] = { s_name: self.bismark_mbias_data[t][k][s_name] for s_name in self.bismark_mbias_data[t][k] if len(self.bismark_mbias_data[t][k][s_name]) > 0 }
python
def parse_bismark_mbias(self, f): s = f['s_name'] self.bismark_mbias_data['meth']['CpG_R1'][s] = {} self.bismark_mbias_data['meth']['CHG_R1'][s] = {} self.bismark_mbias_data['meth']['CHH_R1'][s] = {} self.bismark_mbias_data['cov']['CpG_R1'][s] = {} self.bismark_mbias_data['cov']['CHG_R1'][s] = {} self.bismark_mbias_data['cov']['CHH_R1'][s] = {} self.bismark_mbias_data['meth']['CpG_R2'][s] = {} self.bismark_mbias_data['meth']['CHG_R2'][s] = {} self.bismark_mbias_data['meth']['CHH_R2'][s] = {} self.bismark_mbias_data['cov']['CpG_R2'][s] = {} self.bismark_mbias_data['cov']['CHG_R2'][s] = {} self.bismark_mbias_data['cov']['CHH_R2'][s] = {} key = None for l in f['f']: if 'context' in l: if 'CpG' in l: key = 'CpG' elif 'CHG' in l: key = 'CHG' elif 'CHH' in l: key = 'CHH' if '(R1)' in l: key += '_R1' elif '(R2)' in l: key += '_R2' else: key += '_R1' if key is not None: sections = l.split() try: pos = int(sections[0]) self.bismark_mbias_data['meth'][key][s][pos] = float(sections[3]) self.bismark_mbias_data['cov'][key][s][pos] = int(sections[4]) except (IndexError, ValueError): continue # Remove empty dicts (eg. R2 for SE data) for t in self.bismark_mbias_data: for k in self.bismark_mbias_data[t]: self.bismark_mbias_data[t][k] = { s_name: self.bismark_mbias_data[t][k][s_name] for s_name in self.bismark_mbias_data[t][k] if len(self.bismark_mbias_data[t][k][s_name]) > 0 }
[ "def", "parse_bismark_mbias", "(", "self", ",", "f", ")", ":", "s", "=", "f", "[", "'s_name'", "]", "self", ".", "bismark_mbias_data", "[", "'meth'", "]", "[", "'CpG_R1'", "]", "[", "s", "]", "=", "{", "}", "self", ".", "bismark_mbias_data", "[", "'m...
Parse the Bismark M-Bias plot data
[ "Parse", "the", "Bismark", "M", "-", "Bias", "plot", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bismark/bismark.py#L186-L232
224,538
ewels/MultiQC
multiqc/modules/bismark/bismark.py
MultiqcModule.parse_bismark_bam2nuc
def parse_bismark_bam2nuc(self, f): """ Parse reports generated by Bismark bam2nuc """ if f['s_name'] in self.bismark_data['bam2nuc']: log.debug("Duplicate deduplication sample log found! Overwriting: {}".format(f['s_name'])) self.add_data_source(f, section='bam2nuc') self.bismark_data['bam2nuc'][f['s_name']] = dict() headers = None for l in f['f']: sections = l.rstrip().split("\t") if headers is None: headers = sections else: for i, h in enumerate(headers): if i == 0: k = sections[0] else: key = "{}_{}".format(k, h.lower().replace(' ','_')) self.bismark_data['bam2nuc'][f['s_name']][key] = sections[i]
python
def parse_bismark_bam2nuc(self, f): if f['s_name'] in self.bismark_data['bam2nuc']: log.debug("Duplicate deduplication sample log found! Overwriting: {}".format(f['s_name'])) self.add_data_source(f, section='bam2nuc') self.bismark_data['bam2nuc'][f['s_name']] = dict() headers = None for l in f['f']: sections = l.rstrip().split("\t") if headers is None: headers = sections else: for i, h in enumerate(headers): if i == 0: k = sections[0] else: key = "{}_{}".format(k, h.lower().replace(' ','_')) self.bismark_data['bam2nuc'][f['s_name']][key] = sections[i]
[ "def", "parse_bismark_bam2nuc", "(", "self", ",", "f", ")", ":", "if", "f", "[", "'s_name'", "]", "in", "self", ".", "bismark_data", "[", "'bam2nuc'", "]", ":", "log", ".", "debug", "(", "\"Duplicate deduplication sample log found! Overwriting: {}\"", ".", "form...
Parse reports generated by Bismark bam2nuc
[ "Parse", "reports", "generated", "by", "Bismark", "bam2nuc" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bismark/bismark.py#L234-L252
224,539
ewels/MultiQC
multiqc/modules/bismark/bismark.py
MultiqcModule.bismark_stats_table
def bismark_stats_table(self): """ Take the parsed stats from the Bismark reports and add them to the basic stats table at the top of the report """ headers = { 'alignment': OrderedDict(), 'dedup': OrderedDict(), 'methextract': OrderedDict(), 'bam2nuc': OrderedDict() } headers['methextract']['percent_cpg_meth'] = { 'title': '% mCpG', 'description': '% Cytosines methylated in CpG context', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Greens' } headers['methextract']['percent_chg_meth'] = { 'title': '% mCHG', 'description': '% Cytosines methylated in CHG context', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Oranges' } headers['methextract']['percent_chh_meth'] = { 'title': '% mCHH', 'description': '% Cytosines methylated in CHH context', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Oranges' } headers['methextract']['total_c'] = { 'title': "M C's", 'description': 'Total number of C\'s analysed, in millions', 'min': 0, 'scale': 'Purples', 'modify': lambda x: x / 1000000 } headers['bam2nuc']['C_coverage'] = { 'title': 'C Coverage', 'description': 'Cyotosine Coverage', 'min': 0, 'suffix': 'X', 'scale': 'Greens', 'format': '{:,.2f}' } headers['dedup']['dup_reads_percent'] = { 'title': '% Dups', 'description': 'Percent Duplicated Alignments', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn-rev', } headers['dedup']['dedup_reads'] = { 'title': '{} Unique'.format(config.read_count_prefix), 'description': 'Deduplicated Alignments ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'Greens', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count', 'hidden': True } headers['alignment']['aligned_reads'] = { 'title': '{} Aligned'.format(config.read_count_prefix), 'description': 'Total Aligned Sequences ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count', 'hidden': True } headers['alignment']['percent_aligned'] = { 'title': '% Aligned', 'description': 'Percent Aligned Sequences', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } self.general_stats_addcols(self.bismark_data['methextract'], headers['methextract']) self.general_stats_addcols(self.bismark_data['bam2nuc'], headers['bam2nuc']) self.general_stats_addcols(self.bismark_data['dedup'], headers['dedup']) self.general_stats_addcols(self.bismark_data['alignment'], headers['alignment'])
python
def bismark_stats_table(self): headers = { 'alignment': OrderedDict(), 'dedup': OrderedDict(), 'methextract': OrderedDict(), 'bam2nuc': OrderedDict() } headers['methextract']['percent_cpg_meth'] = { 'title': '% mCpG', 'description': '% Cytosines methylated in CpG context', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Greens' } headers['methextract']['percent_chg_meth'] = { 'title': '% mCHG', 'description': '% Cytosines methylated in CHG context', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Oranges' } headers['methextract']['percent_chh_meth'] = { 'title': '% mCHH', 'description': '% Cytosines methylated in CHH context', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Oranges' } headers['methextract']['total_c'] = { 'title': "M C's", 'description': 'Total number of C\'s analysed, in millions', 'min': 0, 'scale': 'Purples', 'modify': lambda x: x / 1000000 } headers['bam2nuc']['C_coverage'] = { 'title': 'C Coverage', 'description': 'Cyotosine Coverage', 'min': 0, 'suffix': 'X', 'scale': 'Greens', 'format': '{:,.2f}' } headers['dedup']['dup_reads_percent'] = { 'title': '% Dups', 'description': 'Percent Duplicated Alignments', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn-rev', } headers['dedup']['dedup_reads'] = { 'title': '{} Unique'.format(config.read_count_prefix), 'description': 'Deduplicated Alignments ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'Greens', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count', 'hidden': True } headers['alignment']['aligned_reads'] = { 'title': '{} Aligned'.format(config.read_count_prefix), 'description': 'Total Aligned Sequences ({})'.format(config.read_count_desc), 'min': 0, 'scale': 'PuRd', 'modify': lambda x: x * config.read_count_multiplier, 'shared_key': 'read_count', 'hidden': True } headers['alignment']['percent_aligned'] = { 'title': '% Aligned', 'description': 'Percent Aligned Sequences', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } self.general_stats_addcols(self.bismark_data['methextract'], headers['methextract']) self.general_stats_addcols(self.bismark_data['bam2nuc'], headers['bam2nuc']) self.general_stats_addcols(self.bismark_data['dedup'], headers['dedup']) self.general_stats_addcols(self.bismark_data['alignment'], headers['alignment'])
[ "def", "bismark_stats_table", "(", "self", ")", ":", "headers", "=", "{", "'alignment'", ":", "OrderedDict", "(", ")", ",", "'dedup'", ":", "OrderedDict", "(", ")", ",", "'methextract'", ":", "OrderedDict", "(", ")", ",", "'bam2nuc'", ":", "OrderedDict", "...
Take the parsed stats from the Bismark reports and add them to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "Bismark", "reports", "and", "add", "them", "to", "the", "basic", "stats", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bismark/bismark.py#L254-L341
224,540
ewels/MultiQC
multiqc/modules/bismark/bismark.py
MultiqcModule.bismark_alignment_chart
def bismark_alignment_chart (self): """ Make the alignment plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['aligned_reads'] = { 'color': '#2f7ed8', 'name': 'Aligned Uniquely' } keys['ambig_reads'] = { 'color': '#492970', 'name': 'Aligned Ambiguously' } keys['no_alignments'] = { 'color': '#0d233a', 'name': 'Did Not Align' } keys['discarded_reads'] = { 'color': '#f28f43', 'name': 'No Genomic Sequence' } # Config for the plot config = { 'id': 'bismark_alignment', 'title': 'Bismark: Alignment Scores', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } self.add_section ( name = 'Alignment Rates', anchor = 'bismark-alignment', plot = bargraph.plot(self.bismark_data['alignment'], keys, config) )
python
def bismark_alignment_chart (self): # Specify the order of the different possible categories keys = OrderedDict() keys['aligned_reads'] = { 'color': '#2f7ed8', 'name': 'Aligned Uniquely' } keys['ambig_reads'] = { 'color': '#492970', 'name': 'Aligned Ambiguously' } keys['no_alignments'] = { 'color': '#0d233a', 'name': 'Did Not Align' } keys['discarded_reads'] = { 'color': '#f28f43', 'name': 'No Genomic Sequence' } # Config for the plot config = { 'id': 'bismark_alignment', 'title': 'Bismark: Alignment Scores', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } self.add_section ( name = 'Alignment Rates', anchor = 'bismark-alignment', plot = bargraph.plot(self.bismark_data['alignment'], keys, config) )
[ "def", "bismark_alignment_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'aligned_reads'", "]", "=", "{", "'color'", ":", "'#2f7ed8'", ",", "'name'", ":", "'Aligned Uniquel...
Make the alignment plot
[ "Make", "the", "alignment", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bismark/bismark.py#L344-L366
224,541
ewels/MultiQC
multiqc/modules/bismark/bismark.py
MultiqcModule.bismark_strand_chart
def bismark_strand_chart (self): """ Make the strand alignment plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['strand_ob'] = { 'name': 'Original bottom strand' } keys['strand_ctob'] = { 'name': 'Complementary to original bottom strand' } keys['strand_ctot'] = { 'name': 'Complementary to original top strand' } keys['strand_ot'] = { 'name': 'Original top strand' } # See if we have any directional samples directional = 0 d_mode = '' for sn in self.bismark_data['alignment'].values(): if 'strand_directional' in sn.keys(): directional += 1 if directional == len(self.bismark_data['alignment']): keys.pop('strand_ctob', None) keys.pop('strand_ctot', None) d_mode = 'All samples were run with <code>--directional</code> mode; alignments to complementary strands (CTOT, CTOB) were ignored.' elif directional > 0: d_mode = '{} samples were run with <code>--directional</code> mode; alignments to complementary strands (CTOT, CTOB) were ignored.'.format(directional) # Config for the plot config = { 'id': 'bismark_strand_alignment', 'title': 'Bismark: Alignment to Individual Bisulfite Strands', 'ylab': '% Reads', 'cpswitch_c_active': False, 'cpswitch_counts_label': 'Number of Reads' } self.add_section ( name = 'Strand Alignment', anchor = 'bismark-strands', description = d_mode, plot = bargraph.plot(self.bismark_data['alignment'], keys, config) )
python
def bismark_strand_chart (self): # Specify the order of the different possible categories keys = OrderedDict() keys['strand_ob'] = { 'name': 'Original bottom strand' } keys['strand_ctob'] = { 'name': 'Complementary to original bottom strand' } keys['strand_ctot'] = { 'name': 'Complementary to original top strand' } keys['strand_ot'] = { 'name': 'Original top strand' } # See if we have any directional samples directional = 0 d_mode = '' for sn in self.bismark_data['alignment'].values(): if 'strand_directional' in sn.keys(): directional += 1 if directional == len(self.bismark_data['alignment']): keys.pop('strand_ctob', None) keys.pop('strand_ctot', None) d_mode = 'All samples were run with <code>--directional</code> mode; alignments to complementary strands (CTOT, CTOB) were ignored.' elif directional > 0: d_mode = '{} samples were run with <code>--directional</code> mode; alignments to complementary strands (CTOT, CTOB) were ignored.'.format(directional) # Config for the plot config = { 'id': 'bismark_strand_alignment', 'title': 'Bismark: Alignment to Individual Bisulfite Strands', 'ylab': '% Reads', 'cpswitch_c_active': False, 'cpswitch_counts_label': 'Number of Reads' } self.add_section ( name = 'Strand Alignment', anchor = 'bismark-strands', description = d_mode, plot = bargraph.plot(self.bismark_data['alignment'], keys, config) )
[ "def", "bismark_strand_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'strand_ob'", "]", "=", "{", "'name'", ":", "'Original bottom strand'", "}", "keys", "[", "'strand_cto...
Make the strand alignment plot
[ "Make", "the", "strand", "alignment", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bismark/bismark.py#L369-L406
224,542
ewels/MultiQC
multiqc/modules/bismark/bismark.py
MultiqcModule.bismark_dedup_chart
def bismark_dedup_chart (self): """ Make the deduplication plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['dedup_reads'] = { 'name': 'Deduplicated reads (remaining)' } keys['dup_reads'] = { 'name': 'Duplicate reads (removed)' } # Config for the plot config = { 'id': 'bismark_deduplication', 'title': 'Bismark: Deduplication', 'ylab': '% Reads', 'cpswitch_c_active': False, 'cpswitch_counts_label': 'Number of Reads' } self.add_section ( name = 'Deduplication', anchor = 'bismark-deduplication', plot = bargraph.plot(self.bismark_data['dedup'], keys, config) )
python
def bismark_dedup_chart (self): # Specify the order of the different possible categories keys = OrderedDict() keys['dedup_reads'] = { 'name': 'Deduplicated reads (remaining)' } keys['dup_reads'] = { 'name': 'Duplicate reads (removed)' } # Config for the plot config = { 'id': 'bismark_deduplication', 'title': 'Bismark: Deduplication', 'ylab': '% Reads', 'cpswitch_c_active': False, 'cpswitch_counts_label': 'Number of Reads' } self.add_section ( name = 'Deduplication', anchor = 'bismark-deduplication', plot = bargraph.plot(self.bismark_data['dedup'], keys, config) )
[ "def", "bismark_dedup_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'dedup_reads'", "]", "=", "{", "'name'", ":", "'Deduplicated reads (remaining)'", "}", "keys", "[", "'d...
Make the deduplication plot
[ "Make", "the", "deduplication", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bismark/bismark.py#L409-L430
224,543
ewels/MultiQC
multiqc/modules/bismark/bismark.py
MultiqcModule.bismark_methlyation_chart
def bismark_methlyation_chart (self): """ Make the methylation plot """ # Config for the plot keys = OrderedDict() defaults = { 'max': 100, 'min': 0, 'suffix': '%', 'decimalPlaces': 1 } keys['percent_cpg_meth'] = dict(defaults, **{ 'title': 'Methylated CpG' }) keys['percent_chg_meth'] = dict(defaults, **{ 'title': 'Methylated CHG' }) keys['percent_chh_meth'] = dict(defaults, **{ 'title': 'Methylated CHH' }) self.add_section ( name = 'Cytosine Methylation', anchor = 'bismark-methylation', plot = beeswarm.plot(self.bismark_data['methextract'], keys, {'id': 'bismark-methylation-dp'}) )
python
def bismark_methlyation_chart (self): # Config for the plot keys = OrderedDict() defaults = { 'max': 100, 'min': 0, 'suffix': '%', 'decimalPlaces': 1 } keys['percent_cpg_meth'] = dict(defaults, **{ 'title': 'Methylated CpG' }) keys['percent_chg_meth'] = dict(defaults, **{ 'title': 'Methylated CHG' }) keys['percent_chh_meth'] = dict(defaults, **{ 'title': 'Methylated CHH' }) self.add_section ( name = 'Cytosine Methylation', anchor = 'bismark-methylation', plot = beeswarm.plot(self.bismark_data['methextract'], keys, {'id': 'bismark-methylation-dp'}) )
[ "def", "bismark_methlyation_chart", "(", "self", ")", ":", "# Config for the plot", "keys", "=", "OrderedDict", "(", ")", "defaults", "=", "{", "'max'", ":", "100", ",", "'min'", ":", "0", ",", "'suffix'", ":", "'%'", ",", "'decimalPlaces'", ":", "1", "}",...
Make the methylation plot
[ "Make", "the", "methylation", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bismark/bismark.py#L434-L453
224,544
ewels/MultiQC
multiqc/modules/bismark/bismark.py
MultiqcModule.bismark_mbias_plot
def bismark_mbias_plot (self): """ Make the M-Bias plot """ description = '<p>This plot shows the average percentage methylation and coverage across reads. See the \n\ <a href="https://rawgit.com/FelixKrueger/Bismark/master/Docs/Bismark_User_Guide.html#m-bias-plot" target="_blank">bismark user guide</a> \n\ for more information on how these numbers are generated.</p>' pconfig = { 'id': 'bismark_mbias', 'title': 'Bismark: M-Bias', 'ylab': '% Methylation', 'xlab': 'Position (bp)', 'xDecimals': False, 'ymax': 100, 'ymin': 0, 'tt_label': '<b>{point.x} bp</b>: {point.y:.1f}%', 'data_labels': [ {'name': 'CpG R1', 'ylab': '% Methylation', 'ymax': 100}, {'name': 'CHG R1', 'ylab': '% Methylation', 'ymax': 100}, {'name': 'CHH R1', 'ylab': '% Methylation', 'ymax': 100} ] } datasets = [ self.bismark_mbias_data['meth']['CpG_R1'], self.bismark_mbias_data['meth']['CHG_R1'], self.bismark_mbias_data['meth']['CHH_R1'] ] if len(self.bismark_mbias_data['meth']['CpG_R2']) > 0: pconfig['data_labels'].append({'name': 'CpG R2', 'ylab': '% Methylation', 'ymax': 100}) pconfig['data_labels'].append({'name': 'CHG R2', 'ylab': '% Methylation', 'ymax': 100}) pconfig['data_labels'].append({'name': 'CHH R2', 'ylab': '% Methylation', 'ymax': 100}) datasets.append(self.bismark_mbias_data['meth']['CpG_R2']) datasets.append(self.bismark_mbias_data['meth']['CHG_R2']) datasets.append(self.bismark_mbias_data['meth']['CHH_R2']) self.add_section ( name = 'M-Bias', anchor = 'bismark-mbias', description = description, plot = linegraph.plot(datasets, pconfig) )
python
def bismark_mbias_plot (self): description = '<p>This plot shows the average percentage methylation and coverage across reads. See the \n\ <a href="https://rawgit.com/FelixKrueger/Bismark/master/Docs/Bismark_User_Guide.html#m-bias-plot" target="_blank">bismark user guide</a> \n\ for more information on how these numbers are generated.</p>' pconfig = { 'id': 'bismark_mbias', 'title': 'Bismark: M-Bias', 'ylab': '% Methylation', 'xlab': 'Position (bp)', 'xDecimals': False, 'ymax': 100, 'ymin': 0, 'tt_label': '<b>{point.x} bp</b>: {point.y:.1f}%', 'data_labels': [ {'name': 'CpG R1', 'ylab': '% Methylation', 'ymax': 100}, {'name': 'CHG R1', 'ylab': '% Methylation', 'ymax': 100}, {'name': 'CHH R1', 'ylab': '% Methylation', 'ymax': 100} ] } datasets = [ self.bismark_mbias_data['meth']['CpG_R1'], self.bismark_mbias_data['meth']['CHG_R1'], self.bismark_mbias_data['meth']['CHH_R1'] ] if len(self.bismark_mbias_data['meth']['CpG_R2']) > 0: pconfig['data_labels'].append({'name': 'CpG R2', 'ylab': '% Methylation', 'ymax': 100}) pconfig['data_labels'].append({'name': 'CHG R2', 'ylab': '% Methylation', 'ymax': 100}) pconfig['data_labels'].append({'name': 'CHH R2', 'ylab': '% Methylation', 'ymax': 100}) datasets.append(self.bismark_mbias_data['meth']['CpG_R2']) datasets.append(self.bismark_mbias_data['meth']['CHG_R2']) datasets.append(self.bismark_mbias_data['meth']['CHH_R2']) self.add_section ( name = 'M-Bias', anchor = 'bismark-mbias', description = description, plot = linegraph.plot(datasets, pconfig) )
[ "def", "bismark_mbias_plot", "(", "self", ")", ":", "description", "=", "'<p>This plot shows the average percentage methylation and coverage across reads. See the \\n\\\n <a href=\"https://rawgit.com/FelixKrueger/Bismark/master/Docs/Bismark_User_Guide.html#m-bias-plot\" target=\"_blank\">bism...
Make the M-Bias plot
[ "Make", "the", "M", "-", "Bias", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bismark/bismark.py#L456-L497
224,545
ewels/MultiQC
multiqc/modules/afterqc/afterqc.py
MultiqcModule.parse_afterqc_log
def parse_afterqc_log(self, f): """ Parse the JSON output from AfterQC and save the summary statistics """ try: parsed_json = json.load(f['f']) except: log.warn("Could not parse AfterQC JSON: '{}'".format(f['fn'])) return None # AfterQC changed the name of their summary key at some point if 'summary' in parsed_json: summaryk = 'summary' elif 'afterqc_main_summary' in parsed_json: summaryk = 'afterqc_main_summary' else: log.warn("AfterQC JSON did not have a 'summary' or 'afterqc_main_summary' key, skipping: '{}'".format(f['fn'])) return None s_name = f['s_name'] self.add_data_source(f, s_name) self.afterqc_data[s_name] = {} for k in parsed_json[summaryk]: try: self.afterqc_data[s_name][k] = float(parsed_json[summaryk][k]) except ValueError: self.afterqc_data[s_name][k] = parsed_json[summaryk][k] try: self.afterqc_data[s_name]['pct_good_bases'] = (self.afterqc_data[s_name]['good_bases'] / self.afterqc_data[s_name]['total_bases']) * 100.0 except KeyError: pass
python
def parse_afterqc_log(self, f): try: parsed_json = json.load(f['f']) except: log.warn("Could not parse AfterQC JSON: '{}'".format(f['fn'])) return None # AfterQC changed the name of their summary key at some point if 'summary' in parsed_json: summaryk = 'summary' elif 'afterqc_main_summary' in parsed_json: summaryk = 'afterqc_main_summary' else: log.warn("AfterQC JSON did not have a 'summary' or 'afterqc_main_summary' key, skipping: '{}'".format(f['fn'])) return None s_name = f['s_name'] self.add_data_source(f, s_name) self.afterqc_data[s_name] = {} for k in parsed_json[summaryk]: try: self.afterqc_data[s_name][k] = float(parsed_json[summaryk][k]) except ValueError: self.afterqc_data[s_name][k] = parsed_json[summaryk][k] try: self.afterqc_data[s_name]['pct_good_bases'] = (self.afterqc_data[s_name]['good_bases'] / self.afterqc_data[s_name]['total_bases']) * 100.0 except KeyError: pass
[ "def", "parse_afterqc_log", "(", "self", ",", "f", ")", ":", "try", ":", "parsed_json", "=", "json", ".", "load", "(", "f", "[", "'f'", "]", ")", "except", ":", "log", ".", "warn", "(", "\"Could not parse AfterQC JSON: '{}'\"", ".", "format", "(", "f", ...
Parse the JSON output from AfterQC and save the summary statistics
[ "Parse", "the", "JSON", "output", "from", "AfterQC", "and", "save", "the", "summary", "statistics" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/afterqc/afterqc.py#L56-L84
224,546
ewels/MultiQC
multiqc/modules/afterqc/afterqc.py
MultiqcModule.afterqc_general_stats_table
def afterqc_general_stats_table(self): """ Take the parsed stats from the Afterqc report and add it to the General Statistics table at the top of the report """ headers = OrderedDict() headers['pct_good_bases'] = { 'title': '% Good Bases', 'description': 'Percent Good Bases', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'BuGn', } headers['good_reads'] = { 'title': '{} Good Reads'.format(config.read_count_prefix), 'description': 'Good Reads ({})'.format(config.read_count_desc), 'min': 0, 'modify': lambda x: x * config.read_count_multiplier, 'scale': 'GnBu', 'shared_key': 'read_count' } headers['total_reads'] = { 'title': '{} Total Reads'.format(config.read_count_prefix), 'description': 'Total Reads ({})'.format(config.read_count_desc), 'min': 0, 'modify': lambda x: x * config.read_count_multiplier, 'scale': 'Blues', 'shared_key': 'read_count' } headers['readlen'] = { 'title': 'Read Length', 'description': 'Read Length', 'min': 0, 'suffix': ' bp', 'format': '{:,.0f}', 'scale': 'YlGn' } self.general_stats_addcols(self.afterqc_data, headers)
python
def afterqc_general_stats_table(self): headers = OrderedDict() headers['pct_good_bases'] = { 'title': '% Good Bases', 'description': 'Percent Good Bases', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'BuGn', } headers['good_reads'] = { 'title': '{} Good Reads'.format(config.read_count_prefix), 'description': 'Good Reads ({})'.format(config.read_count_desc), 'min': 0, 'modify': lambda x: x * config.read_count_multiplier, 'scale': 'GnBu', 'shared_key': 'read_count' } headers['total_reads'] = { 'title': '{} Total Reads'.format(config.read_count_prefix), 'description': 'Total Reads ({})'.format(config.read_count_desc), 'min': 0, 'modify': lambda x: x * config.read_count_multiplier, 'scale': 'Blues', 'shared_key': 'read_count' } headers['readlen'] = { 'title': 'Read Length', 'description': 'Read Length', 'min': 0, 'suffix': ' bp', 'format': '{:,.0f}', 'scale': 'YlGn' } self.general_stats_addcols(self.afterqc_data, headers)
[ "def", "afterqc_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'pct_good_bases'", "]", "=", "{", "'title'", ":", "'% Good Bases'", ",", "'description'", ":", "'Percent Good Bases'", ",", "'max'", ":", "100"...
Take the parsed stats from the Afterqc report and add it to the General Statistics table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "Afterqc", "report", "and", "add", "it", "to", "the", "General", "Statistics", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/afterqc/afterqc.py#L86-L123
224,547
ewels/MultiQC
multiqc/modules/afterqc/afterqc.py
MultiqcModule.after_qc_bad_reads_chart
def after_qc_bad_reads_chart(self): """ Function to generate the AfterQC bad reads bar plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['good_reads'] = { 'name': 'Good Reads' } keys['bad_reads_with_bad_barcode'] = { 'name': 'Bad Barcode' } keys['bad_reads_with_bad_overlap'] = { 'name': 'Bad Overlap' } keys['bad_reads_with_bad_read_length'] = { 'name': 'Bad Read Length' } keys['bad_reads_with_low_quality'] = { 'name': 'Low Quality' } keys['bad_reads_with_polyX'] = { 'name': 'PolyX' } keys['bad_reads_with_reads_in_bubble'] = { 'name': 'Reads In Bubble' } keys['bad_reads_with_too_many_N'] = { 'name': 'Too many N' } # Config for the plot pconfig = { 'id': 'afterqc_bad_reads_plot', 'title': 'AfterQC: Filtered Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads', 'hide_zero_cats': False, } return bargraph.plot(self.afterqc_data, keys, pconfig)
python
def after_qc_bad_reads_chart(self): # Specify the order of the different possible categories keys = OrderedDict() keys['good_reads'] = { 'name': 'Good Reads' } keys['bad_reads_with_bad_barcode'] = { 'name': 'Bad Barcode' } keys['bad_reads_with_bad_overlap'] = { 'name': 'Bad Overlap' } keys['bad_reads_with_bad_read_length'] = { 'name': 'Bad Read Length' } keys['bad_reads_with_low_quality'] = { 'name': 'Low Quality' } keys['bad_reads_with_polyX'] = { 'name': 'PolyX' } keys['bad_reads_with_reads_in_bubble'] = { 'name': 'Reads In Bubble' } keys['bad_reads_with_too_many_N'] = { 'name': 'Too many N' } # Config for the plot pconfig = { 'id': 'afterqc_bad_reads_plot', 'title': 'AfterQC: Filtered Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads', 'hide_zero_cats': False, } return bargraph.plot(self.afterqc_data, keys, pconfig)
[ "def", "after_qc_bad_reads_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'good_reads'", "]", "=", "{", "'name'", ":", "'Good Reads'", "}", "keys", "[", "'bad_reads_with_ba...
Function to generate the AfterQC bad reads bar plot
[ "Function", "to", "generate", "the", "AfterQC", "bad", "reads", "bar", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/afterqc/afterqc.py#L125-L146
224,548
ewels/MultiQC
multiqc/modules/bbmap/bbmap.py
MultiqcModule.plot
def plot(self, file_type): """ Call file_type plotting function. """ samples = self.mod_data[file_type] plot_title = file_types[file_type]['title'] plot_func = file_types[file_type]['plot_func'] plot_params = file_types[file_type]['plot_params'] return plot_func(samples, file_type, plot_title=plot_title, plot_params=plot_params)
python
def plot(self, file_type): samples = self.mod_data[file_type] plot_title = file_types[file_type]['title'] plot_func = file_types[file_type]['plot_func'] plot_params = file_types[file_type]['plot_params'] return plot_func(samples, file_type, plot_title=plot_title, plot_params=plot_params)
[ "def", "plot", "(", "self", ",", "file_type", ")", ":", "samples", "=", "self", ".", "mod_data", "[", "file_type", "]", "plot_title", "=", "file_types", "[", "file_type", "]", "[", "'title'", "]", "plot_func", "=", "file_types", "[", "file_type", "]", "[...
Call file_type plotting function.
[ "Call", "file_type", "plotting", "function", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bbmap/bbmap.py#L151-L162
224,549
ewels/MultiQC
multiqc/modules/bbmap/bbmap.py
MultiqcModule.make_basic_table
def make_basic_table(self, file_type): """ Create table of key-value items in 'file_type'. """ table_data = {sample: items['kv'] for sample, items in self.mod_data[file_type].items() } table_headers = {} for column_header, (description, header_options) in file_types[file_type]['kv_descriptions'].items(): table_headers[column_header] = { 'rid': '{}_{}_bbmstheader'.format(file_type, column_header), 'title': column_header, 'description': description, } table_headers[column_header].update(header_options) tconfig = { 'id': file_type + '_bbm_table', 'namespace': 'BBTools' } for sample in table_data: for key, value in table_data[sample].items(): try: table_data[sample][key] = float(value) except ValueError: pass return table.plot(table_data, table_headers, tconfig)
python
def make_basic_table(self, file_type): table_data = {sample: items['kv'] for sample, items in self.mod_data[file_type].items() } table_headers = {} for column_header, (description, header_options) in file_types[file_type]['kv_descriptions'].items(): table_headers[column_header] = { 'rid': '{}_{}_bbmstheader'.format(file_type, column_header), 'title': column_header, 'description': description, } table_headers[column_header].update(header_options) tconfig = { 'id': file_type + '_bbm_table', 'namespace': 'BBTools' } for sample in table_data: for key, value in table_data[sample].items(): try: table_data[sample][key] = float(value) except ValueError: pass return table.plot(table_data, table_headers, tconfig)
[ "def", "make_basic_table", "(", "self", ",", "file_type", ")", ":", "table_data", "=", "{", "sample", ":", "items", "[", "'kv'", "]", "for", "sample", ",", "items", "in", "self", ".", "mod_data", "[", "file_type", "]", ".", "items", "(", ")", "}", "t...
Create table of key-value items in 'file_type'.
[ "Create", "table", "of", "key", "-", "value", "items", "in", "file_type", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bbmap/bbmap.py#L165-L192
224,550
ewels/MultiQC
multiqc/modules/vcftools/tstv_by_count.py
TsTvByCountMixin.parse_tstv_by_count
def parse_tstv_by_count(self): """ Create the HTML for the TsTv by alternative allele count linegraph plot. """ self.vcftools_tstv_by_count = dict() for f in self.find_log_files('vcftools/tstv_by_count', filehandles=True): d = {} for line in f['f'].readlines()[1:]: # don't add the header line (first row) key = float(line.split()[0]) # taking the first column (alternative allele count) as key val = float(line.split()[3]) # taking Ts/Tv as value d[key] = val self.vcftools_tstv_by_count[f['s_name']] = d # Filter out ignored sample names self.vcftools_tstv_by_count = self.ignore_samples(self.vcftools_tstv_by_count) if len(self.vcftools_tstv_by_count) == 0: return 0 pconfig = { 'id': 'vcftools_tstv_by_count', 'title': 'VCFTools: TsTv by Count', 'ylab': 'TsTv Ratio', 'xlab': 'Alternative Allele Count', 'xmin': 0, 'ymin': 0, 'smooth_points': 400, # this limits huge filesizes and prevents browser crashing 'smooth_points_sumcounts': False } helptext = ''' `Transition` is a purine-to-purine or pyrimidine-to-pyrimidine point mutations. `Transversion` is a purine-to-pyrimidine or pyrimidine-to-purine point mutation. `Alternative allele count` is the number of alternative alleles at the site. Note: only bi-allelic SNPs are used (multi-allelic sites and INDELs are skipped.) Refer to Vcftools's manual (https://vcftools.github.io/man_latest.html) on `--TsTv-by-count` ''' self.add_section( name = 'TsTv by Count', anchor = 'vcftools-tstv-by-count', description = "Plot of `TSTV-BY-COUNT` - the transition to transversion ratio as a function of alternative allele count from the output of vcftools TsTv-by-count.", helptext = helptext, plot = linegraph.plot(self.vcftools_tstv_by_count,pconfig) ) return len(self.vcftools_tstv_by_count)
python
def parse_tstv_by_count(self): self.vcftools_tstv_by_count = dict() for f in self.find_log_files('vcftools/tstv_by_count', filehandles=True): d = {} for line in f['f'].readlines()[1:]: # don't add the header line (first row) key = float(line.split()[0]) # taking the first column (alternative allele count) as key val = float(line.split()[3]) # taking Ts/Tv as value d[key] = val self.vcftools_tstv_by_count[f['s_name']] = d # Filter out ignored sample names self.vcftools_tstv_by_count = self.ignore_samples(self.vcftools_tstv_by_count) if len(self.vcftools_tstv_by_count) == 0: return 0 pconfig = { 'id': 'vcftools_tstv_by_count', 'title': 'VCFTools: TsTv by Count', 'ylab': 'TsTv Ratio', 'xlab': 'Alternative Allele Count', 'xmin': 0, 'ymin': 0, 'smooth_points': 400, # this limits huge filesizes and prevents browser crashing 'smooth_points_sumcounts': False } helptext = ''' `Transition` is a purine-to-purine or pyrimidine-to-pyrimidine point mutations. `Transversion` is a purine-to-pyrimidine or pyrimidine-to-purine point mutation. `Alternative allele count` is the number of alternative alleles at the site. Note: only bi-allelic SNPs are used (multi-allelic sites and INDELs are skipped.) Refer to Vcftools's manual (https://vcftools.github.io/man_latest.html) on `--TsTv-by-count` ''' self.add_section( name = 'TsTv by Count', anchor = 'vcftools-tstv-by-count', description = "Plot of `TSTV-BY-COUNT` - the transition to transversion ratio as a function of alternative allele count from the output of vcftools TsTv-by-count.", helptext = helptext, plot = linegraph.plot(self.vcftools_tstv_by_count,pconfig) ) return len(self.vcftools_tstv_by_count)
[ "def", "parse_tstv_by_count", "(", "self", ")", ":", "self", ".", "vcftools_tstv_by_count", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'vcftools/tstv_by_count'", ",", "filehandles", "=", "True", ")", ":", "d", "=", "{", "...
Create the HTML for the TsTv by alternative allele count linegraph plot.
[ "Create", "the", "HTML", "for", "the", "TsTv", "by", "alternative", "allele", "count", "linegraph", "plot", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/vcftools/tstv_by_count.py#L13-L58
224,551
ewels/MultiQC
multiqc/modules/deeptools/plotEnrichment.py
plotEnrichmentMixin.parse_plotEnrichment
def parse_plotEnrichment(self): """Find plotEnrichment output.""" self.deeptools_plotEnrichment = dict() for f in self.find_log_files('deeptools/plotEnrichment'): parsed_data = self.parsePlotEnrichment(f) for k, v in parsed_data.items(): if k in self.deeptools_plotEnrichment: log.warning("Replacing duplicate sample {}.".format(k)) self.deeptools_plotEnrichment[k] = v if len(parsed_data) > 0: self.add_data_source(f, section='plotEnrichment') if len(self.deeptools_plotEnrichment) > 0: dCounts = OrderedDict() dPercents = OrderedDict() for sample, v in self.deeptools_plotEnrichment.items(): dCounts[sample] = OrderedDict() dPercents[sample] = OrderedDict() for category, v2 in v.items(): dCounts[sample][category] = v2['count'] dPercents[sample][category] = v2['percent'] config = {'data_labels': [ {'name': 'Counts in features', 'ylab': 'Counts in feature'}, {'name': 'Percents in features', 'ylab': 'Percent of reads in feature'}], 'id': 'deeptools_enrichment_plot', 'title': 'deepTools: Signal enrichment per feature', 'ylab': 'Counts in feature', 'categories': True, 'ymin': 0.0} self.add_section(name="Feature enrichment", description="Signal enrichment per feature according to plotEnrichment", anchor="deeptools_enrichment", plot=linegraph.plot([dCounts, dPercents], pconfig=config)) return len(self.deeptools_plotEnrichment)
python
def parse_plotEnrichment(self): self.deeptools_plotEnrichment = dict() for f in self.find_log_files('deeptools/plotEnrichment'): parsed_data = self.parsePlotEnrichment(f) for k, v in parsed_data.items(): if k in self.deeptools_plotEnrichment: log.warning("Replacing duplicate sample {}.".format(k)) self.deeptools_plotEnrichment[k] = v if len(parsed_data) > 0: self.add_data_source(f, section='plotEnrichment') if len(self.deeptools_plotEnrichment) > 0: dCounts = OrderedDict() dPercents = OrderedDict() for sample, v in self.deeptools_plotEnrichment.items(): dCounts[sample] = OrderedDict() dPercents[sample] = OrderedDict() for category, v2 in v.items(): dCounts[sample][category] = v2['count'] dPercents[sample][category] = v2['percent'] config = {'data_labels': [ {'name': 'Counts in features', 'ylab': 'Counts in feature'}, {'name': 'Percents in features', 'ylab': 'Percent of reads in feature'}], 'id': 'deeptools_enrichment_plot', 'title': 'deepTools: Signal enrichment per feature', 'ylab': 'Counts in feature', 'categories': True, 'ymin': 0.0} self.add_section(name="Feature enrichment", description="Signal enrichment per feature according to plotEnrichment", anchor="deeptools_enrichment", plot=linegraph.plot([dCounts, dPercents], pconfig=config)) return len(self.deeptools_plotEnrichment)
[ "def", "parse_plotEnrichment", "(", "self", ")", ":", "self", ".", "deeptools_plotEnrichment", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'deeptools/plotEnrichment'", ")", ":", "parsed_data", "=", "self", ".", "parsePlotEnrichm...
Find plotEnrichment output.
[ "Find", "plotEnrichment", "output", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/deeptools/plotEnrichment.py#L16-L51
224,552
ewels/MultiQC
multiqc/modules/slamdunk/slamdunk.py
MultiqcModule.slamdunkGeneralStatsTable
def slamdunkGeneralStatsTable(self): """ Take the parsed summary stats from Slamdunk and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['counted'] = { 'title': '{} Counted'.format(config.read_count_prefix), 'description': '# reads counted within 3\'UTRs ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['retained'] = { 'title': '{} Retained'.format(config.read_count_prefix), 'description': '# retained reads after filtering ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['mapped'] = { 'title': '{} Mapped'.format(config.read_count_prefix), 'description': '# mapped reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['sequenced'] = { 'title': '{} Sequenced'.format(config.read_count_prefix), 'description': '# sequenced reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } self.general_stats_addcols(self.slamdunk_data, headers)
python
def slamdunkGeneralStatsTable(self): headers = OrderedDict() headers['counted'] = { 'title': '{} Counted'.format(config.read_count_prefix), 'description': '# reads counted within 3\'UTRs ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['retained'] = { 'title': '{} Retained'.format(config.read_count_prefix), 'description': '# retained reads after filtering ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['mapped'] = { 'title': '{} Mapped'.format(config.read_count_prefix), 'description': '# mapped reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['sequenced'] = { 'title': '{} Sequenced'.format(config.read_count_prefix), 'description': '# sequenced reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } self.general_stats_addcols(self.slamdunk_data, headers)
[ "def", "slamdunkGeneralStatsTable", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'counted'", "]", "=", "{", "'title'", ":", "'{} Counted'", ".", "format", "(", "config", ".", "read_count_prefix", ")", ",", "'description'", ...
Take the parsed summary stats from Slamdunk and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "summary", "stats", "from", "Slamdunk", "and", "add", "it", "to", "the", "basic", "stats", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/slamdunk/slamdunk.py#L319-L362
224,553
ewels/MultiQC
multiqc/modules/slamdunk/slamdunk.py
MultiqcModule.slamdunkFilterStatsTable
def slamdunkFilterStatsTable(self): """ Take the parsed filter stats from Slamdunk and add it to a separate table """ headers = OrderedDict() headers['mapped'] = { 'namespace': 'Slamdunk', 'title': '{} Mapped'.format(config.read_count_prefix), 'description': '# mapped reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['multimapper'] = { 'namespace': 'Slamdunk', 'title': '{} Multimap-Filtered'.format(config.read_count_prefix), 'description': '# multimap-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['nmfiltered'] = { 'namespace': 'Slamdunk', 'title': '{} NM-Filtered'.format(config.read_count_prefix), 'description': '# NM-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['idfiltered'] = { 'namespace': 'Slamdunk', 'title': '{} Identity-Filtered'.format(config.read_count_prefix), 'description': '# identity-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['mqfiltered'] = { 'namespace': 'Slamdunk', 'title': '{} MQ-Filtered'.format(config.read_count_prefix), 'description': '# MQ-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } pconfig = { 'id': 'slamdunk_filtering_table', 'min': 0, } self.add_section ( name = 'Filter statistics', anchor = 'slamdunk_filtering', description = 'This table shows the number of reads filtered with each filter criterion during filtering phase of slamdunk.', plot = table.plot(self.slamdunk_data, headers, pconfig) )
python
def slamdunkFilterStatsTable(self): headers = OrderedDict() headers['mapped'] = { 'namespace': 'Slamdunk', 'title': '{} Mapped'.format(config.read_count_prefix), 'description': '# mapped reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['multimapper'] = { 'namespace': 'Slamdunk', 'title': '{} Multimap-Filtered'.format(config.read_count_prefix), 'description': '# multimap-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['nmfiltered'] = { 'namespace': 'Slamdunk', 'title': '{} NM-Filtered'.format(config.read_count_prefix), 'description': '# NM-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['idfiltered'] = { 'namespace': 'Slamdunk', 'title': '{} Identity-Filtered'.format(config.read_count_prefix), 'description': '# identity-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['mqfiltered'] = { 'namespace': 'Slamdunk', 'title': '{} MQ-Filtered'.format(config.read_count_prefix), 'description': '# MQ-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } pconfig = { 'id': 'slamdunk_filtering_table', 'min': 0, } self.add_section ( name = 'Filter statistics', anchor = 'slamdunk_filtering', description = 'This table shows the number of reads filtered with each filter criterion during filtering phase of slamdunk.', plot = table.plot(self.slamdunk_data, headers, pconfig) )
[ "def", "slamdunkFilterStatsTable", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'mapped'", "]", "=", "{", "'namespace'", ":", "'Slamdunk'", ",", "'title'", ":", "'{} Mapped'", ".", "format", "(", "config", ".", "read_count...
Take the parsed filter stats from Slamdunk and add it to a separate table
[ "Take", "the", "parsed", "filter", "stats", "from", "Slamdunk", "and", "add", "it", "to", "a", "separate", "table" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/slamdunk/slamdunk.py#L364-L433
224,554
ewels/MultiQC
multiqc/modules/bowtie1/bowtie1.py
MultiqcModule.bowtie_general_stats_table
def bowtie_general_stats_table(self): """ Take the parsed stats from the Bowtie report and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['reads_aligned_percentage'] = { 'title': '% Aligned', 'description': '% reads with at least one reported alignment', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['reads_aligned'] = { 'title': '{} Aligned'.format(config.read_count_prefix), 'description': 'reads with at least one reported alignment ({})'.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.bowtie_data, headers)
python
def bowtie_general_stats_table(self): headers = OrderedDict() headers['reads_aligned_percentage'] = { 'title': '% Aligned', 'description': '% reads with at least one reported alignment', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['reads_aligned'] = { 'title': '{} Aligned'.format(config.read_count_prefix), 'description': 'reads with at least one reported alignment ({})'.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.bowtie_data, headers)
[ "def", "bowtie_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'reads_aligned_percentage'", "]", "=", "{", "'title'", ":", "'% Aligned'", ",", "'description'", ":", "'% reads with at least one reported alignment'", ...
Take the parsed stats from the Bowtie report and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "Bowtie", "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/bowtie1/bowtie1.py#L93-L114
224,555
ewels/MultiQC
multiqc/utils/report.py
search_file
def search_file (pattern, f): """ Function to searach a single file for a single search pattern. """ fn_matched = False contents_matched = False # Use mimetypes to exclude binary files where possible if not re.match(r'.+_mqc\.(png|jpg|jpeg)', f['fn']): (ftype, encoding) = mimetypes.guess_type(os.path.join(f['root'], f['fn'])) if encoding is not None: return False if ftype is not None and ftype.startswith('image'): return False # Search pattern specific filesize limit if pattern.get('max_filesize') is not None and 'filesize' in f: if f['filesize'] > pattern.get('max_filesize'): logger.debug("Ignoring because exceeded search pattern filesize limit: {}".format(f['fn'])) return False # Search by file name (glob) if pattern.get('fn') is not None: if fnmatch.fnmatch(f['fn'], pattern['fn']): fn_matched = True if pattern.get('contents') is None and pattern.get('contents_re') is None: return True # Search by file name (regex) if pattern.get('fn_re') is not None: if re.match( pattern['fn_re'], f['fn']): fn_matched = True if pattern.get('contents') is None and pattern.get('contents_re') is None: return True # Search by file contents if pattern.get('contents') is not None or pattern.get('contents_re') is not None: if pattern.get('contents_re') is not None: repattern = re.compile(pattern['contents_re']) try: with io.open (os.path.join(f['root'],f['fn']), "r", encoding='utf-8') as f: l = 1 for line in f: # Search by file contents (string) if pattern.get('contents') is not None: if pattern['contents'] in line: contents_matched = True if pattern.get('fn') is None and pattern.get('fn_re') is None: return True break # Search by file contents (regex) elif pattern.get('contents_re') is not None: if re.search(repattern, line): contents_matched = True if pattern.get('fn') is None and pattern.get('fn_re') is None: return True break # Break if we've searched enough lines for this pattern if pattern.get('num_lines') and l >= pattern.get('num_lines'): break l += 1 except (IOError, OSError, ValueError, UnicodeDecodeError): if config.report_readerrors: logger.debug("Couldn't read file when looking for output: {}".format(f['fn'])) return False return fn_matched and contents_matched
python
def search_file (pattern, f): fn_matched = False contents_matched = False # Use mimetypes to exclude binary files where possible if not re.match(r'.+_mqc\.(png|jpg|jpeg)', f['fn']): (ftype, encoding) = mimetypes.guess_type(os.path.join(f['root'], f['fn'])) if encoding is not None: return False if ftype is not None and ftype.startswith('image'): return False # Search pattern specific filesize limit if pattern.get('max_filesize') is not None and 'filesize' in f: if f['filesize'] > pattern.get('max_filesize'): logger.debug("Ignoring because exceeded search pattern filesize limit: {}".format(f['fn'])) return False # Search by file name (glob) if pattern.get('fn') is not None: if fnmatch.fnmatch(f['fn'], pattern['fn']): fn_matched = True if pattern.get('contents') is None and pattern.get('contents_re') is None: return True # Search by file name (regex) if pattern.get('fn_re') is not None: if re.match( pattern['fn_re'], f['fn']): fn_matched = True if pattern.get('contents') is None and pattern.get('contents_re') is None: return True # Search by file contents if pattern.get('contents') is not None or pattern.get('contents_re') is not None: if pattern.get('contents_re') is not None: repattern = re.compile(pattern['contents_re']) try: with io.open (os.path.join(f['root'],f['fn']), "r", encoding='utf-8') as f: l = 1 for line in f: # Search by file contents (string) if pattern.get('contents') is not None: if pattern['contents'] in line: contents_matched = True if pattern.get('fn') is None and pattern.get('fn_re') is None: return True break # Search by file contents (regex) elif pattern.get('contents_re') is not None: if re.search(repattern, line): contents_matched = True if pattern.get('fn') is None and pattern.get('fn_re') is None: return True break # Break if we've searched enough lines for this pattern if pattern.get('num_lines') and l >= pattern.get('num_lines'): break l += 1 except (IOError, OSError, ValueError, UnicodeDecodeError): if config.report_readerrors: logger.debug("Couldn't read file when looking for output: {}".format(f['fn'])) return False return fn_matched and contents_matched
[ "def", "search_file", "(", "pattern", ",", "f", ")", ":", "fn_matched", "=", "False", "contents_matched", "=", "False", "# Use mimetypes to exclude binary files where possible", "if", "not", "re", ".", "match", "(", "r'.+_mqc\\.(png|jpg|jpeg)'", ",", "f", "[", "'fn'...
Function to searach a single file for a single search pattern.
[ "Function", "to", "searach", "a", "single", "file", "for", "a", "single", "search", "pattern", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/report.py#L189-L256
224,556
ewels/MultiQC
multiqc/utils/report.py
exclude_file
def exclude_file(sp, f): """ Exclude discovered files if they match the special exclude_ search pattern keys """ # Make everything a list if it isn't already for k in sp: if k in ['exclude_fn', 'exclude_fn_re' 'exclude_contents', 'exclude_contents_re']: if not isinstance(sp[k], list): sp[k] = [sp[k]] # Search by file name (glob) if 'exclude_fn' in sp: for pat in sp['exclude_fn']: if fnmatch.fnmatch(f['fn'], pat): return True # Search by file name (regex) if 'exclude_fn_re' in sp: for pat in sp['exclude_fn_re']: if re.match( pat, f['fn']): return True # Search the contents of the file if 'exclude_contents' in sp or 'exclude_contents_re' in sp: # Compile regex patterns if we have any if 'exclude_contents_re' in sp: sp['exclude_contents_re'] = [re.compile(pat) for pat in sp['exclude_contents_re']] with io.open (os.path.join(f['root'],f['fn']), "r", encoding='utf-8') as fh: for line in fh: if 'exclude_contents' in sp: for pat in sp['exclude_contents']: if pat in line: return True if 'exclude_contents_re' in sp: for pat in sp['exclude_contents_re']: if re.search(pat, line): return True return False
python
def exclude_file(sp, f): # Make everything a list if it isn't already for k in sp: if k in ['exclude_fn', 'exclude_fn_re' 'exclude_contents', 'exclude_contents_re']: if not isinstance(sp[k], list): sp[k] = [sp[k]] # Search by file name (glob) if 'exclude_fn' in sp: for pat in sp['exclude_fn']: if fnmatch.fnmatch(f['fn'], pat): return True # Search by file name (regex) if 'exclude_fn_re' in sp: for pat in sp['exclude_fn_re']: if re.match( pat, f['fn']): return True # Search the contents of the file if 'exclude_contents' in sp or 'exclude_contents_re' in sp: # Compile regex patterns if we have any if 'exclude_contents_re' in sp: sp['exclude_contents_re'] = [re.compile(pat) for pat in sp['exclude_contents_re']] with io.open (os.path.join(f['root'],f['fn']), "r", encoding='utf-8') as fh: for line in fh: if 'exclude_contents' in sp: for pat in sp['exclude_contents']: if pat in line: return True if 'exclude_contents_re' in sp: for pat in sp['exclude_contents_re']: if re.search(pat, line): return True return False
[ "def", "exclude_file", "(", "sp", ",", "f", ")", ":", "# Make everything a list if it isn't already", "for", "k", "in", "sp", ":", "if", "k", "in", "[", "'exclude_fn'", ",", "'exclude_fn_re'", "'exclude_contents'", ",", "'exclude_contents_re'", "]", ":", "if", "...
Exclude discovered files if they match the special exclude_ search pattern keys
[ "Exclude", "discovered", "files", "if", "they", "match", "the", "special", "exclude_", "search", "pattern", "keys" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/report.py#L258-L296
224,557
ewels/MultiQC
multiqc/utils/report.py
save_htmlid
def save_htmlid(html_id, skiplint=False): """ Take a HTML ID, sanitise for HTML, check for duplicates and save. Returns sanitised, unique ID """ global html_ids global lint_errors # Trailing whitespace html_id_clean = html_id.strip() # Trailing underscores html_id_clean = html_id_clean.strip('_') # Must begin with a letter if re.match(r'^[a-zA-Z]', html_id_clean) is None: html_id_clean = 'mqc_{}'.format(html_id_clean) # Replace illegal characters html_id_clean = re.sub('[^a-zA-Z0-9_-]+', '_', html_id_clean) # Validate if linting if config.lint and not skiplint: modname = '' codeline = '' callstack = inspect.stack() for n in callstack: if 'multiqc/modules/' in n[1] and 'base_module.py' not in n[1]: callpath = n[1].split('multiqc/modules/',1)[-1] modname = '>{}< '.format(callpath) codeline = n[4][0].strip() break if config.lint and not skiplint and html_id != html_id_clean: errmsg = "LINT: {}HTML ID was not clean ('{}' -> '{}') ## {}".format(modname, html_id, html_id_clean, codeline) logger.error(errmsg) lint_errors.append(errmsg) # Check for duplicates i = 1 html_id_base = html_id_clean while html_id_clean in html_ids: html_id_clean = '{}-{}'.format(html_id_base, i) i += 1 if config.lint and not skiplint: errmsg = "LINT: {}HTML ID was a duplicate ({}) ## {}".format(modname, html_id_clean, codeline) logger.error(errmsg) lint_errors.append(errmsg) # Remember and return html_ids.append(html_id_clean) return html_id_clean
python
def save_htmlid(html_id, skiplint=False): global html_ids global lint_errors # Trailing whitespace html_id_clean = html_id.strip() # Trailing underscores html_id_clean = html_id_clean.strip('_') # Must begin with a letter if re.match(r'^[a-zA-Z]', html_id_clean) is None: html_id_clean = 'mqc_{}'.format(html_id_clean) # Replace illegal characters html_id_clean = re.sub('[^a-zA-Z0-9_-]+', '_', html_id_clean) # Validate if linting if config.lint and not skiplint: modname = '' codeline = '' callstack = inspect.stack() for n in callstack: if 'multiqc/modules/' in n[1] and 'base_module.py' not in n[1]: callpath = n[1].split('multiqc/modules/',1)[-1] modname = '>{}< '.format(callpath) codeline = n[4][0].strip() break if config.lint and not skiplint and html_id != html_id_clean: errmsg = "LINT: {}HTML ID was not clean ('{}' -> '{}') ## {}".format(modname, html_id, html_id_clean, codeline) logger.error(errmsg) lint_errors.append(errmsg) # Check for duplicates i = 1 html_id_base = html_id_clean while html_id_clean in html_ids: html_id_clean = '{}-{}'.format(html_id_base, i) i += 1 if config.lint and not skiplint: errmsg = "LINT: {}HTML ID was a duplicate ({}) ## {}".format(modname, html_id_clean, codeline) logger.error(errmsg) lint_errors.append(errmsg) # Remember and return html_ids.append(html_id_clean) return html_id_clean
[ "def", "save_htmlid", "(", "html_id", ",", "skiplint", "=", "False", ")", ":", "global", "html_ids", "global", "lint_errors", "# Trailing whitespace", "html_id_clean", "=", "html_id", ".", "strip", "(", ")", "# Trailing underscores", "html_id_clean", "=", "html_id_c...
Take a HTML ID, sanitise for HTML, check for duplicates and save. Returns sanitised, unique ID
[ "Take", "a", "HTML", "ID", "sanitise", "for", "HTML", "check", "for", "duplicates", "and", "save", ".", "Returns", "sanitised", "unique", "ID" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/report.py#L315-L363
224,558
ewels/MultiQC
multiqc/utils/report.py
compress_json
def compress_json(data): """ Take a Python data object. Convert to JSON and compress using lzstring """ json_string = json.dumps(data).encode('utf-8', 'ignore').decode('utf-8') # JSON.parse() doesn't handle `NaN`, but it does handle `null`. json_string = json_string.replace('NaN', 'null'); x = lzstring.LZString() return x.compressToBase64(json_string)
python
def compress_json(data): json_string = json.dumps(data).encode('utf-8', 'ignore').decode('utf-8') # JSON.parse() doesn't handle `NaN`, but it does handle `null`. json_string = json_string.replace('NaN', 'null'); x = lzstring.LZString() return x.compressToBase64(json_string)
[ "def", "compress_json", "(", "data", ")", ":", "json_string", "=", "json", ".", "dumps", "(", "data", ")", ".", "encode", "(", "'utf-8'", ",", "'ignore'", ")", ".", "decode", "(", "'utf-8'", ")", "# JSON.parse() doesn't handle `NaN`, but it does handle `null`.", ...
Take a Python data object. Convert to JSON and compress using lzstring
[ "Take", "a", "Python", "data", "object", ".", "Convert", "to", "JSON", "and", "compress", "using", "lzstring" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/report.py#L366-L372
224,559
ewels/MultiQC
multiqc/modules/methylQA/methylQA.py
MultiqcModule.methylqa_general_stats_table
def methylqa_general_stats_table(self): """ Take the parsed stats from the methylQA report and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['coverage'] = { 'title': 'Fold Coverage', 'min': 0, 'suffix': 'X', 'scale': 'YlGn' } self.general_stats_addcols(self.methylqa_data, headers)
python
def methylqa_general_stats_table(self): headers = OrderedDict() headers['coverage'] = { 'title': 'Fold Coverage', 'min': 0, 'suffix': 'X', 'scale': 'YlGn' } self.general_stats_addcols(self.methylqa_data, headers)
[ "def", "methylqa_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'coverage'", "]", "=", "{", "'title'", ":", "'Fold Coverage'", ",", "'min'", ":", "0", ",", "'suffix'", ":", "'X'", ",", "'scale'", ":",...
Take the parsed stats from the methylQA report and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "methylQA", "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/methylQA/methylQA.py#L107-L118
224,560
ewels/MultiQC
multiqc/modules/rsem/rsem.py
MultiqcModule.rsem_stats_table
def rsem_stats_table(self): """ Take the parsed stats from the rsem report and add them to the basic stats table at the top of the report """ headers = OrderedDict() headers['alignable_percent'] = { 'title': '% Alignable'.format(config.read_count_prefix), 'description': '% Alignable reads'.format(config.read_count_desc), 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } self.general_stats_addcols(self.rsem_mapped_data, headers)
python
def rsem_stats_table(self): headers = OrderedDict() headers['alignable_percent'] = { 'title': '% Alignable'.format(config.read_count_prefix), 'description': '% Alignable reads'.format(config.read_count_desc), 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } self.general_stats_addcols(self.rsem_mapped_data, headers)
[ "def", "rsem_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'alignable_percent'", "]", "=", "{", "'title'", ":", "'% Alignable'", ".", "format", "(", "config", ".", "read_count_prefix", ")", ",", "'description'",...
Take the parsed stats from the rsem report and add them to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "rsem", "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/rsem/rsem.py#L113-L125
224,561
ewels/MultiQC
multiqc/modules/rsem/rsem.py
MultiqcModule.rsem_mapped_reads_plot
def rsem_mapped_reads_plot(self): """ Make the rsem assignment rates plot """ # Plot categories keys = OrderedDict() keys['Unique'] = { 'color': '#437bb1', 'name': 'Aligned uniquely to a gene' } keys['Multi'] = { 'color': '#e63491', 'name': 'Aligned to multiple genes' } keys['Filtered'] = { 'color': '#b1084c', 'name': 'Filtered due to too many alignments' } keys['Unalignable'] = { 'color': '#7f0000', 'name': 'Unalignable reads' } # Config for the plot config = { 'id': 'rsem_assignment_plot', 'title': 'RSEM: Mapped reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads', 'hide_zero_cats': False } self.add_section( name = 'Mapped Reads', anchor = 'rsem_mapped_reads', description = 'A breakdown of how all reads were aligned for each sample.', plot = bargraph.plot(self.rsem_mapped_data, keys, config) )
python
def rsem_mapped_reads_plot(self): # Plot categories keys = OrderedDict() keys['Unique'] = { 'color': '#437bb1', 'name': 'Aligned uniquely to a gene' } keys['Multi'] = { 'color': '#e63491', 'name': 'Aligned to multiple genes' } keys['Filtered'] = { 'color': '#b1084c', 'name': 'Filtered due to too many alignments' } keys['Unalignable'] = { 'color': '#7f0000', 'name': 'Unalignable reads' } # Config for the plot config = { 'id': 'rsem_assignment_plot', 'title': 'RSEM: Mapped reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads', 'hide_zero_cats': False } self.add_section( name = 'Mapped Reads', anchor = 'rsem_mapped_reads', description = 'A breakdown of how all reads were aligned for each sample.', plot = bargraph.plot(self.rsem_mapped_data, keys, config) )
[ "def", "rsem_mapped_reads_plot", "(", "self", ")", ":", "# Plot categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'Unique'", "]", "=", "{", "'color'", ":", "'#437bb1'", ",", "'name'", ":", "'Aligned uniquely to a gene'", "}", "keys", "[", "'Mult...
Make the rsem assignment rates plot
[ "Make", "the", "rsem", "assignment", "rates", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rsem/rsem.py#L128-L152
224,562
ewels/MultiQC
multiqc/modules/vcftools/tstv_by_qual.py
TsTvByQualMixin.parse_tstv_by_qual
def parse_tstv_by_qual(self): """ Create the HTML for the TsTv by quality linegraph plot. """ self.vcftools_tstv_by_qual = dict() for f in self.find_log_files('vcftools/tstv_by_qual', filehandles=True): d = {} for line in f['f'].readlines()[1:]: # don't add the header line (first row) key = float(line.split()[0]) # taking the first column (QUAL_THRESHOLD) as key val = float(line.split()[6]) # taking Ts/Tv_GT_QUAL_THRESHOLD as value if (val == float('inf')) or (val == float('-inf')): val = float('nan') d[key] = val self.vcftools_tstv_by_qual[f['s_name']] = d # Filter out ignored sample names self.vcftools_tstv_by_qual = self.ignore_samples(self.vcftools_tstv_by_qual) if len(self.vcftools_tstv_by_qual) == 0: return 0 pconfig = { 'id': 'vcftools_tstv_by_qual', 'title': 'VCFTools: TsTv by Qual', 'ylab': 'TsTv Ratio', 'xlab': 'SNP Quality Threshold', 'xmin': 0, 'ymin': 0, 'smooth_points': 400, # this limits huge filesizes and prevents browser crashing 'smooth_points_sumcounts': False } helptext = ''' `Transition` is a purine-to-purine or pyrimidine-to-pyrimidine point mutations. `Transversion` is a purine-to-pyrimidine or pyrimidine-to-purine point mutation. `Quality` here is the Phred-scaled quality score as given in the QUAL column of VCF. Note: only bi-allelic SNPs are used (multi-allelic sites and INDELs are skipped.) Refer to Vcftools's manual (https://vcftools.github.io/man_latest.html) on `--TsTv-by-qual` ''' self.add_section( name = 'TsTv by Qual', anchor = 'vcftools-tstv-by-qual', description = "Plot of `TSTV-BY-QUAL` - the transition to transversion ratio as a function of SNP quality from the output of vcftools TsTv-by-qual.", helptext = helptext, plot = linegraph.plot(self.vcftools_tstv_by_qual,pconfig) ) return len(self.vcftools_tstv_by_qual)
python
def parse_tstv_by_qual(self): self.vcftools_tstv_by_qual = dict() for f in self.find_log_files('vcftools/tstv_by_qual', filehandles=True): d = {} for line in f['f'].readlines()[1:]: # don't add the header line (first row) key = float(line.split()[0]) # taking the first column (QUAL_THRESHOLD) as key val = float(line.split()[6]) # taking Ts/Tv_GT_QUAL_THRESHOLD as value if (val == float('inf')) or (val == float('-inf')): val = float('nan') d[key] = val self.vcftools_tstv_by_qual[f['s_name']] = d # Filter out ignored sample names self.vcftools_tstv_by_qual = self.ignore_samples(self.vcftools_tstv_by_qual) if len(self.vcftools_tstv_by_qual) == 0: return 0 pconfig = { 'id': 'vcftools_tstv_by_qual', 'title': 'VCFTools: TsTv by Qual', 'ylab': 'TsTv Ratio', 'xlab': 'SNP Quality Threshold', 'xmin': 0, 'ymin': 0, 'smooth_points': 400, # this limits huge filesizes and prevents browser crashing 'smooth_points_sumcounts': False } helptext = ''' `Transition` is a purine-to-purine or pyrimidine-to-pyrimidine point mutations. `Transversion` is a purine-to-pyrimidine or pyrimidine-to-purine point mutation. `Quality` here is the Phred-scaled quality score as given in the QUAL column of VCF. Note: only bi-allelic SNPs are used (multi-allelic sites and INDELs are skipped.) Refer to Vcftools's manual (https://vcftools.github.io/man_latest.html) on `--TsTv-by-qual` ''' self.add_section( name = 'TsTv by Qual', anchor = 'vcftools-tstv-by-qual', description = "Plot of `TSTV-BY-QUAL` - the transition to transversion ratio as a function of SNP quality from the output of vcftools TsTv-by-qual.", helptext = helptext, plot = linegraph.plot(self.vcftools_tstv_by_qual,pconfig) ) return len(self.vcftools_tstv_by_qual)
[ "def", "parse_tstv_by_qual", "(", "self", ")", ":", "self", ".", "vcftools_tstv_by_qual", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'vcftools/tstv_by_qual'", ",", "filehandles", "=", "True", ")", ":", "d", "=", "{", "}",...
Create the HTML for the TsTv by quality linegraph plot.
[ "Create", "the", "HTML", "for", "the", "TsTv", "by", "quality", "linegraph", "plot", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/vcftools/tstv_by_qual.py#L13-L60
224,563
ewels/MultiQC
multiqc/modules/snpeff/snpeff.py
MultiqcModule.general_stats
def general_stats(self): """ Add key SnpEff stats to the general stats table """ headers = OrderedDict() headers['Change_rate'] = { 'title': 'Change rate', 'scale': 'RdYlBu-rev', 'min': 0, 'format': '{:,.0f}' } headers['Ts_Tv_ratio'] = { 'title': 'Ts/Tv', 'description': 'Transitions / Transversions ratio', 'format': '{:,.3f}' } headers['Number_of_variants_before_filter'] = { 'title': 'M Variants', 'description': 'Number of variants before filter (millions)', 'scale': 'PuRd', 'modify': lambda x: x / 1000000, 'min': 0, 'format': '{:,.2f}' } self.general_stats_addcols(self.snpeff_data, headers)
python
def general_stats(self): headers = OrderedDict() headers['Change_rate'] = { 'title': 'Change rate', 'scale': 'RdYlBu-rev', 'min': 0, 'format': '{:,.0f}' } headers['Ts_Tv_ratio'] = { 'title': 'Ts/Tv', 'description': 'Transitions / Transversions ratio', 'format': '{:,.3f}' } headers['Number_of_variants_before_filter'] = { 'title': 'M Variants', 'description': 'Number of variants before filter (millions)', 'scale': 'PuRd', 'modify': lambda x: x / 1000000, 'min': 0, 'format': '{:,.2f}' } self.general_stats_addcols(self.snpeff_data, headers)
[ "def", "general_stats", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'Change_rate'", "]", "=", "{", "'title'", ":", "'Change rate'", ",", "'scale'", ":", "'RdYlBu-rev'", ",", "'min'", ":", "0", ",", "'format'", ":", "'...
Add key SnpEff stats to the general stats table
[ "Add", "key", "SnpEff", "stats", "to", "the", "general", "stats", "table" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/snpeff/snpeff.py#L183-L206
224,564
ewels/MultiQC
multiqc/modules/snpeff/snpeff.py
MultiqcModule.count_genomic_region_plot
def count_genomic_region_plot(self): """ Generate the SnpEff Counts by Genomic Region plot """ # Sort the keys based on the total counts keys = self.snpeff_section_totals['# Count by genomic region'] sorted_keys = sorted(keys, reverse=True, key=keys.get) # Make nicer label names pkeys = OrderedDict() for k in sorted_keys: pkeys[k] = {'name': k.replace('_', ' ').title().replace('Utr', 'UTR') } # Config for the plot pconfig = { 'id': 'snpeff_variant_effects_region', 'title': 'SnpEff: Counts by Genomic Region', 'ylab': '# Reads', 'logswitch': True } return bargraph.plot(self.snpeff_data, pkeys, pconfig)
python
def count_genomic_region_plot(self): # Sort the keys based on the total counts keys = self.snpeff_section_totals['# Count by genomic region'] sorted_keys = sorted(keys, reverse=True, key=keys.get) # Make nicer label names pkeys = OrderedDict() for k in sorted_keys: pkeys[k] = {'name': k.replace('_', ' ').title().replace('Utr', 'UTR') } # Config for the plot pconfig = { 'id': 'snpeff_variant_effects_region', 'title': 'SnpEff: Counts by Genomic Region', 'ylab': '# Reads', 'logswitch': True } return bargraph.plot(self.snpeff_data, pkeys, pconfig)
[ "def", "count_genomic_region_plot", "(", "self", ")", ":", "# Sort the keys based on the total counts", "keys", "=", "self", ".", "snpeff_section_totals", "[", "'# Count by genomic region'", "]", "sorted_keys", "=", "sorted", "(", "keys", ",", "reverse", "=", "True", ...
Generate the SnpEff Counts by Genomic Region plot
[ "Generate", "the", "SnpEff", "Counts", "by", "Genomic", "Region", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/snpeff/snpeff.py#L209-L229
224,565
ewels/MultiQC
multiqc/modules/snpeff/snpeff.py
MultiqcModule.effects_impact_plot
def effects_impact_plot(self): """ Generate the SnpEff Counts by Effects Impact plot """ # Put keys in a more logical order keys = [ 'MODIFIER', 'LOW', 'MODERATE', 'HIGH' ] # Make nicer label names pkeys = OrderedDict() for k in keys: pkeys[k] = {'name': k.title() } # Config for the plot pconfig = { 'id': 'snpeff_variant_effects_impact', 'title': 'SnpEff: Counts by Effects Impact', 'ylab': '# Reads', 'logswitch': True } return bargraph.plot(self.snpeff_data, pkeys, pconfig)
python
def effects_impact_plot(self): # Put keys in a more logical order keys = [ 'MODIFIER', 'LOW', 'MODERATE', 'HIGH' ] # Make nicer label names pkeys = OrderedDict() for k in keys: pkeys[k] = {'name': k.title() } # Config for the plot pconfig = { 'id': 'snpeff_variant_effects_impact', 'title': 'SnpEff: Counts by Effects Impact', 'ylab': '# Reads', 'logswitch': True } return bargraph.plot(self.snpeff_data, pkeys, pconfig)
[ "def", "effects_impact_plot", "(", "self", ")", ":", "# Put keys in a more logical order", "keys", "=", "[", "'MODIFIER'", ",", "'LOW'", ",", "'MODERATE'", ",", "'HIGH'", "]", "# Make nicer label names", "pkeys", "=", "OrderedDict", "(", ")", "for", "k", "in", "...
Generate the SnpEff Counts by Effects Impact plot
[ "Generate", "the", "SnpEff", "Counts", "by", "Effects", "Impact", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/snpeff/snpeff.py#L232-L251
224,566
ewels/MultiQC
multiqc/modules/prokka/prokka.py
MultiqcModule.parse_prokka
def parse_prokka(self, f): """ Parse prokka txt summary files. Prokka summary files are difficult to identify as there are practically no distinct prokka identifiers in the filenames or file contents. This parser makes an attempt using the first three lines, expected to contain organism, contigs, and bases statistics. """ s_name = None # Look at the first three lines, they are always the same first_line = f['f'].readline() contigs_line = f['f'].readline() bases_line = f['f'].readline() # If any of these fail, it's probably not a prokka summary file if not all((first_line.startswith("organism:"), contigs_line.startswith("contigs:"), bases_line.startswith("bases:"))): return # Get organism and sample name from the first line # Assumes organism name only consists of two words, # i.e. 'Genusname speciesname', and that the remaining # text on the organism line is the sample name. try: organism = " ".join(first_line.strip().split(":", 1)[1].split()[:2]) s_name = self.clean_s_name(" ".join(first_line.split()[3:]), f['root']) except KeyError: organism = first_line.strip().split(":", 1)[1] s_name = f['s_name'] # Don't try to guess sample name if requested in the config if getattr(config, 'prokka_fn_snames', False): s_name = f['s_name'] if s_name in self.prokka: log.debug("Duplicate sample name found! Overwriting: {}".format(s_name)) self.prokka[s_name] = dict() self.prokka[s_name]['organism'] = organism self.prokka[s_name]['contigs'] = int(contigs_line.split(":")[1]) self.prokka[s_name]['bases'] = int(bases_line.split(":")[1]) # Get additional info from remaining lines for line in f['f']: description, value = line.split(":") try: self.prokka[s_name][description] = int(value) except ValueError: log.warning("Unable to parse line: '%s'", line) self.add_data_source(f, s_name)
python
def parse_prokka(self, f): s_name = None # Look at the first three lines, they are always the same first_line = f['f'].readline() contigs_line = f['f'].readline() bases_line = f['f'].readline() # If any of these fail, it's probably not a prokka summary file if not all((first_line.startswith("organism:"), contigs_line.startswith("contigs:"), bases_line.startswith("bases:"))): return # Get organism and sample name from the first line # Assumes organism name only consists of two words, # i.e. 'Genusname speciesname', and that the remaining # text on the organism line is the sample name. try: organism = " ".join(first_line.strip().split(":", 1)[1].split()[:2]) s_name = self.clean_s_name(" ".join(first_line.split()[3:]), f['root']) except KeyError: organism = first_line.strip().split(":", 1)[1] s_name = f['s_name'] # Don't try to guess sample name if requested in the config if getattr(config, 'prokka_fn_snames', False): s_name = f['s_name'] if s_name in self.prokka: log.debug("Duplicate sample name found! Overwriting: {}".format(s_name)) self.prokka[s_name] = dict() self.prokka[s_name]['organism'] = organism self.prokka[s_name]['contigs'] = int(contigs_line.split(":")[1]) self.prokka[s_name]['bases'] = int(bases_line.split(":")[1]) # Get additional info from remaining lines for line in f['f']: description, value = line.split(":") try: self.prokka[s_name][description] = int(value) except ValueError: log.warning("Unable to parse line: '%s'", line) self.add_data_source(f, s_name)
[ "def", "parse_prokka", "(", "self", ",", "f", ")", ":", "s_name", "=", "None", "# Look at the first three lines, they are always the same", "first_line", "=", "f", "[", "'f'", "]", ".", "readline", "(", ")", "contigs_line", "=", "f", "[", "'f'", "]", ".", "r...
Parse prokka txt summary files. Prokka summary files are difficult to identify as there are practically no distinct prokka identifiers in the filenames or file contents. This parser makes an attempt using the first three lines, expected to contain organism, contigs, and bases statistics.
[ "Parse", "prokka", "txt", "summary", "files", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/prokka/prokka.py#L90-L140
224,567
ewels/MultiQC
multiqc/modules/prokka/prokka.py
MultiqcModule.prokka_table
def prokka_table(self): """ Make basic table of the annotation stats """ # Specify the order of the different possible categories headers = OrderedDict() headers['organism'] = { 'title': 'Organism', 'description': 'Organism name', } headers['contigs'] = { 'title': '# contigs', 'description': 'Number of contigs in assembly', 'format': '{:i}', } headers['bases'] = { 'title': '# bases', 'description': 'Number of nucleotide bases in assembly', 'format': '{:i}', } headers['CDS'] = { 'title': '# CDS', 'description': 'Number of annotated CDS', 'format': '{:i}', } headers['rRNA'] = { 'title': '# rRNA', 'description': 'Number of annotated rRNA', 'format': '{:i}', } headers['tRNA'] = { 'title': '# tRNA', 'description': 'Number of annotated tRNA', 'format': '{:i}', } headers['tmRNA'] = { 'title': '# tmRNA', 'description': 'Number of annotated tmRNA', 'format': '{:i}', } headers['misc_RNA'] = { 'title': '# misc RNA', 'description': 'Number of annotated misc. RNA', 'format': '{:i}', } headers['sig_peptide'] = { 'title': '# sig_peptide', 'description': 'Number of annotated sig_peptide', 'format': '{:i}', } headers['repeat_region'] = { 'title': '# CRISPR arrays', 'description': 'Number of annotated CRSIPR arrays', 'format': '{:i}', } table_config = { 'namespace': 'prokka', 'min': 0, } return table.plot(self.prokka, headers, table_config)
python
def prokka_table(self): # Specify the order of the different possible categories headers = OrderedDict() headers['organism'] = { 'title': 'Organism', 'description': 'Organism name', } headers['contigs'] = { 'title': '# contigs', 'description': 'Number of contigs in assembly', 'format': '{:i}', } headers['bases'] = { 'title': '# bases', 'description': 'Number of nucleotide bases in assembly', 'format': '{:i}', } headers['CDS'] = { 'title': '# CDS', 'description': 'Number of annotated CDS', 'format': '{:i}', } headers['rRNA'] = { 'title': '# rRNA', 'description': 'Number of annotated rRNA', 'format': '{:i}', } headers['tRNA'] = { 'title': '# tRNA', 'description': 'Number of annotated tRNA', 'format': '{:i}', } headers['tmRNA'] = { 'title': '# tmRNA', 'description': 'Number of annotated tmRNA', 'format': '{:i}', } headers['misc_RNA'] = { 'title': '# misc RNA', 'description': 'Number of annotated misc. RNA', 'format': '{:i}', } headers['sig_peptide'] = { 'title': '# sig_peptide', 'description': 'Number of annotated sig_peptide', 'format': '{:i}', } headers['repeat_region'] = { 'title': '# CRISPR arrays', 'description': 'Number of annotated CRSIPR arrays', 'format': '{:i}', } table_config = { 'namespace': 'prokka', 'min': 0, } return table.plot(self.prokka, headers, table_config)
[ "def", "prokka_table", "(", "self", ")", ":", "# Specify the order of the different possible categories", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'organism'", "]", "=", "{", "'title'", ":", "'Organism'", ",", "'description'", ":", "'Organism name'", ...
Make basic table of the annotation stats
[ "Make", "basic", "table", "of", "the", "annotation", "stats" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/prokka/prokka.py#L143-L202
224,568
ewels/MultiQC
multiqc/modules/prokka/prokka.py
MultiqcModule.prokka_barplot
def prokka_barplot(self): """ Make a basic plot of the annotation stats """ # Specify the order of the different categories keys = OrderedDict() keys['CDS'] = { 'name': 'CDS' } keys['rRNA'] = { 'name': 'rRNA' } keys['tRNA'] = { 'name': 'tRNA' } keys['tmRNA'] = { 'name': 'tmRNA' } keys['misc_RNA'] = { 'name': 'misc RNA' } keys['sig_peptide'] = { 'name': 'Signal peptides' } keys['repeat_region'] = { 'name': 'CRISPR array'} plot_config = { 'id': 'prokka_plot', 'title': 'Prokka: Feature Types', 'ylab': '# Counts', 'cpswitch_counts_label': 'Features' } return bargraph.plot(self.prokka, keys, plot_config)
python
def prokka_barplot(self): # Specify the order of the different categories keys = OrderedDict() keys['CDS'] = { 'name': 'CDS' } keys['rRNA'] = { 'name': 'rRNA' } keys['tRNA'] = { 'name': 'tRNA' } keys['tmRNA'] = { 'name': 'tmRNA' } keys['misc_RNA'] = { 'name': 'misc RNA' } keys['sig_peptide'] = { 'name': 'Signal peptides' } keys['repeat_region'] = { 'name': 'CRISPR array'} plot_config = { 'id': 'prokka_plot', 'title': 'Prokka: Feature Types', 'ylab': '# Counts', 'cpswitch_counts_label': 'Features' } return bargraph.plot(self.prokka, keys, plot_config)
[ "def", "prokka_barplot", "(", "self", ")", ":", "# Specify the order of the different categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'CDS'", "]", "=", "{", "'name'", ":", "'CDS'", "}", "keys", "[", "'rRNA'", "]", "=", "{", "'name'", ":", ...
Make a basic plot of the annotation stats
[ "Make", "a", "basic", "plot", "of", "the", "annotation", "stats" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/prokka/prokka.py#L204-L224
224,569
ewels/MultiQC
multiqc/modules/bbmap/plot_bhist.py
plot_bhist
def plot_bhist(samples, file_type, **plot_args): """ Create line graph plot of histogram data for BBMap 'bhist' output. The 'samples' parameter could be from the bbmap mod_data dictionary: samples = bbmap.MultiqcModule.mod_data[file_type] """ all_x = set() for item in sorted(chain(*[samples[sample]['data'].items() for sample in samples])): all_x.add(item[0]) columns_to_plot = { 'GC': { 1: 'C', 2: 'G', }, 'AT': { 0: 'A', 3: 'T', }, 'N': { 4: 'N' }, } nucleotide_data = [] for column_type in columns_to_plot: nucleotide_data.append( { sample+'.'+column_name: { x: samples[sample]['data'][x][column]*100 if x in samples[sample]['data'] else 0 for x in all_x } for sample in samples for column, column_name in columns_to_plot[column_type].items() } ) plot_params = { 'id': 'bbmap-' + file_type + '_plot', 'title': 'BBTools: ' + plot_args['plot_title'], 'xlab': 'Read position', 'ymin': 0, 'ymax': 100, 'data_labels': [ {'name': 'Percentage of G+C bases'}, {'name': 'Percentage of A+T bases'}, {'name': 'Percentage of N bases'}, ] } plot_params.update(plot_args['plot_params']) plot = linegraph.plot( nucleotide_data, plot_params ) return plot
python
def plot_bhist(samples, file_type, **plot_args): all_x = set() for item in sorted(chain(*[samples[sample]['data'].items() for sample in samples])): all_x.add(item[0]) columns_to_plot = { 'GC': { 1: 'C', 2: 'G', }, 'AT': { 0: 'A', 3: 'T', }, 'N': { 4: 'N' }, } nucleotide_data = [] for column_type in columns_to_plot: nucleotide_data.append( { sample+'.'+column_name: { x: samples[sample]['data'][x][column]*100 if x in samples[sample]['data'] else 0 for x in all_x } for sample in samples for column, column_name in columns_to_plot[column_type].items() } ) plot_params = { 'id': 'bbmap-' + file_type + '_plot', 'title': 'BBTools: ' + plot_args['plot_title'], 'xlab': 'Read position', 'ymin': 0, 'ymax': 100, 'data_labels': [ {'name': 'Percentage of G+C bases'}, {'name': 'Percentage of A+T bases'}, {'name': 'Percentage of N bases'}, ] } plot_params.update(plot_args['plot_params']) plot = linegraph.plot( nucleotide_data, plot_params ) return plot
[ "def", "plot_bhist", "(", "samples", ",", "file_type", ",", "*", "*", "plot_args", ")", ":", "all_x", "=", "set", "(", ")", "for", "item", "in", "sorted", "(", "chain", "(", "*", "[", "samples", "[", "sample", "]", "[", "'data'", "]", ".", "items",...
Create line graph plot of histogram data for BBMap 'bhist' output. The 'samples' parameter could be from the bbmap mod_data dictionary: samples = bbmap.MultiqcModule.mod_data[file_type]
[ "Create", "line", "graph", "plot", "of", "histogram", "data", "for", "BBMap", "bhist", "output", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bbmap/plot_bhist.py#L5-L61
224,570
ewels/MultiQC
multiqc/modules/skewer/skewer.py
MultiqcModule.add_readlen_dist_plot
def add_readlen_dist_plot(self): """ Generate plot HTML for read length distribution plot. """ pconfig = { 'id': 'skewer_read_length_histogram', 'title': 'Skewer: Read Length Distribution after trimming', 'xDecimals': False, 'ylab': '% of Reads', 'xlab': 'Read Length', 'xmin': 0, 'ymin': 0, 'tt_label': '<b>{point.x}</b>: {point.y:.1f}%', } self.add_section( plot = linegraph.plot(self.skewer_readlen_dist, pconfig) )
python
def add_readlen_dist_plot(self): pconfig = { 'id': 'skewer_read_length_histogram', 'title': 'Skewer: Read Length Distribution after trimming', 'xDecimals': False, 'ylab': '% of Reads', 'xlab': 'Read Length', 'xmin': 0, 'ymin': 0, 'tt_label': '<b>{point.x}</b>: {point.y:.1f}%', } self.add_section( plot = linegraph.plot(self.skewer_readlen_dist, pconfig) )
[ "def", "add_readlen_dist_plot", "(", "self", ")", ":", "pconfig", "=", "{", "'id'", ":", "'skewer_read_length_histogram'", ",", "'title'", ":", "'Skewer: Read Length Distribution after trimming'", ",", "'xDecimals'", ":", "False", ",", "'ylab'", ":", "'% of Reads'", "...
Generate plot HTML for read length distribution plot.
[ "Generate", "plot", "HTML", "for", "read", "length", "distribution", "plot", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/skewer/skewer.py#L75-L89
224,571
ewels/MultiQC
multiqc/modules/skewer/skewer.py
MultiqcModule.parse_skewer_log
def parse_skewer_log(self, f): """ Go through log file looking for skewer output """ fh = f['f'] regexes = { 'fq1': "Input file:\s+(.+)", 'fq2': "Paired file:\s+(.+)", 'r_processed': "(\d+) read|reads pairs? processed", 'r_short_filtered': "(\d+) \(\s*\d+.\d+%\) short read", 'r_empty_filtered': "(\d+) \(\s*\d+.\d+%\) empty read", 'r_avail': "(\d+) \(\s*\d+.\d+%\) read", 'r_trimmed': "(\d+) \(\s*\d+.\d+%\) trimmed read", 'r_untrimmed': "(\d+) \(\s*\d+.\d+%\) untrimmed read" } regex_hist = "\s?(\d+)\s+(\d+)\s+(\d+.\d+)%" data = dict() for k, v in regexes.items(): data[k] = 0 data['fq1'] = None data['fq2'] = None readlen_dist = OrderedDict() for l in fh: for k, r in regexes.items(): match = re.search(r, l) if match: data[k] = match.group(1).replace(',', '') match = re.search(regex_hist, l) if match: read_length = int(match.group(1)) pct_at_rl = float(match.group(3)) readlen_dist[read_length] = pct_at_rl if data['fq1'] is not None: s_name = self.clean_s_name(data['fq1'], f['root']) if s_name in self.skewer_readlen_dist: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name)) self.add_data_source(f, s_name) self.add_skewer_data(s_name, data, f) self.skewer_readlen_dist[s_name] = readlen_dist if data['fq2'] is not None: s_name = self.clean_s_name(data['fq1'], f['root']) if s_name in self.skewer_readlen_dist: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name)) self.add_data_source(f, s_name) self.add_skewer_data(s_name, data, f) self.skewer_readlen_dist[s_name] = readlen_dist
python
def parse_skewer_log(self, f): fh = f['f'] regexes = { 'fq1': "Input file:\s+(.+)", 'fq2': "Paired file:\s+(.+)", 'r_processed': "(\d+) read|reads pairs? processed", 'r_short_filtered': "(\d+) \(\s*\d+.\d+%\) short read", 'r_empty_filtered': "(\d+) \(\s*\d+.\d+%\) empty read", 'r_avail': "(\d+) \(\s*\d+.\d+%\) read", 'r_trimmed': "(\d+) \(\s*\d+.\d+%\) trimmed read", 'r_untrimmed': "(\d+) \(\s*\d+.\d+%\) untrimmed read" } regex_hist = "\s?(\d+)\s+(\d+)\s+(\d+.\d+)%" data = dict() for k, v in regexes.items(): data[k] = 0 data['fq1'] = None data['fq2'] = None readlen_dist = OrderedDict() for l in fh: for k, r in regexes.items(): match = re.search(r, l) if match: data[k] = match.group(1).replace(',', '') match = re.search(regex_hist, l) if match: read_length = int(match.group(1)) pct_at_rl = float(match.group(3)) readlen_dist[read_length] = pct_at_rl if data['fq1'] is not None: s_name = self.clean_s_name(data['fq1'], f['root']) if s_name in self.skewer_readlen_dist: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name)) self.add_data_source(f, s_name) self.add_skewer_data(s_name, data, f) self.skewer_readlen_dist[s_name] = readlen_dist if data['fq2'] is not None: s_name = self.clean_s_name(data['fq1'], f['root']) if s_name in self.skewer_readlen_dist: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name)) self.add_data_source(f, s_name) self.add_skewer_data(s_name, data, f) self.skewer_readlen_dist[s_name] = readlen_dist
[ "def", "parse_skewer_log", "(", "self", ",", "f", ")", ":", "fh", "=", "f", "[", "'f'", "]", "regexes", "=", "{", "'fq1'", ":", "\"Input file:\\s+(.+)\"", ",", "'fq2'", ":", "\"Paired file:\\s+(.+)\"", ",", "'r_processed'", ":", "\"(\\d+) read|reads pairs? proce...
Go through log file looking for skewer output
[ "Go", "through", "log", "file", "looking", "for", "skewer", "output" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/skewer/skewer.py#L91-L139
224,572
ewels/MultiQC
multiqc/modules/rseqc/read_duplication.py
parse_reports
def parse_reports(self): """ Find RSeQC read_duplication reports and parse their data """ # Set up vars self.read_dups = dict() # Go through files and parse data for f in self.find_log_files('rseqc/read_duplication_pos'): if f['f'].startswith('Occurrence UniqReadNumber'): if f['s_name'] in self.read_dups: log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) self.add_data_source(f, section='read_duplication') self.read_dups[f['s_name']] = OrderedDict() for l in f['f'].splitlines(): s = l.split() try: if int(s[0]) <= 500: self.read_dups[f['s_name']][int(s[0])] = int(s[1]) except: pass # Filter to strip out ignored sample names self.read_dups = self.ignore_samples(self.read_dups) if len(self.read_dups) > 0: # Add line graph to section pconfig = { 'smooth_points': 200, 'id': 'rseqc_read_dups_plot', 'title': 'RSeQC: Read Duplication', 'ylab': 'Number of Reads (log10)', 'xlab': "Occurrence of read", 'yLog': True, 'tt_label': "<strong>{point.x} occurrences</strong>: {point.y} reads", } self.add_section ( name = 'Read Duplication', anchor = 'rseqc-read_dups', description = '<a href="http://rseqc.sourceforge.net/#read-duplication-py" target="_blank">read_duplication.py</a>' \ " calculates how many alignment positions have a certain number of exact duplicates."\ " Note - plot truncated at 500 occurrences and binned.</p>", plot = linegraph.plot(self.read_dups, pconfig) ) # Return number of samples found return len(self.read_dups)
python
def parse_reports(self): # Set up vars self.read_dups = dict() # Go through files and parse data for f in self.find_log_files('rseqc/read_duplication_pos'): if f['f'].startswith('Occurrence UniqReadNumber'): if f['s_name'] in self.read_dups: log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) self.add_data_source(f, section='read_duplication') self.read_dups[f['s_name']] = OrderedDict() for l in f['f'].splitlines(): s = l.split() try: if int(s[0]) <= 500: self.read_dups[f['s_name']][int(s[0])] = int(s[1]) except: pass # Filter to strip out ignored sample names self.read_dups = self.ignore_samples(self.read_dups) if len(self.read_dups) > 0: # Add line graph to section pconfig = { 'smooth_points': 200, 'id': 'rseqc_read_dups_plot', 'title': 'RSeQC: Read Duplication', 'ylab': 'Number of Reads (log10)', 'xlab': "Occurrence of read", 'yLog': True, 'tt_label': "<strong>{point.x} occurrences</strong>: {point.y} reads", } self.add_section ( name = 'Read Duplication', anchor = 'rseqc-read_dups', description = '<a href="http://rseqc.sourceforge.net/#read-duplication-py" target="_blank">read_duplication.py</a>' \ " calculates how many alignment positions have a certain number of exact duplicates."\ " Note - plot truncated at 500 occurrences and binned.</p>", plot = linegraph.plot(self.read_dups, pconfig) ) # Return number of samples found return len(self.read_dups)
[ "def", "parse_reports", "(", "self", ")", ":", "# Set up vars", "self", ".", "read_dups", "=", "dict", "(", ")", "# Go through files and parse data", "for", "f", "in", "self", ".", "find_log_files", "(", "'rseqc/read_duplication_pos'", ")", ":", "if", "f", "[", ...
Find RSeQC read_duplication reports and parse their data
[ "Find", "RSeQC", "read_duplication", "reports", "and", "parse", "their", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rseqc/read_duplication.py#L15-L62
224,573
ewels/MultiQC
multiqc/modules/picard/BaseDistributionByCycleMetrics.py
read_sample_name
def read_sample_name(line_iter, clean_fn): """ Consumes lines from the provided line_iter and parses those lines as a header for the picard base distribution file. The header file is assumed to contain a line with both 'INPUT' and 'BaseDistributionByCycle'. If the header parses correctly, the sample name is returned. If the header does not parse correctly, None is returned. """ try: while True: new_line = next(line_iter) new_line = new_line.strip() if 'BaseDistributionByCycle' in new_line and 'INPUT' in new_line: # Pull sample name from input fn_search = re.search(r"INPUT=?\s*(\[?[^\s]+\]?)", new_line, flags=re.IGNORECASE) if fn_search: s_name = os.path.basename(fn_search.group(1).strip('[]')) s_name = clean_fn(s_name) return s_name except StopIteration: return None
python
def read_sample_name(line_iter, clean_fn): try: while True: new_line = next(line_iter) new_line = new_line.strip() if 'BaseDistributionByCycle' in new_line and 'INPUT' in new_line: # Pull sample name from input fn_search = re.search(r"INPUT=?\s*(\[?[^\s]+\]?)", new_line, flags=re.IGNORECASE) if fn_search: s_name = os.path.basename(fn_search.group(1).strip('[]')) s_name = clean_fn(s_name) return s_name except StopIteration: return None
[ "def", "read_sample_name", "(", "line_iter", ",", "clean_fn", ")", ":", "try", ":", "while", "True", ":", "new_line", "=", "next", "(", "line_iter", ")", "new_line", "=", "new_line", ".", "strip", "(", ")", "if", "'BaseDistributionByCycle'", "in", "new_line"...
Consumes lines from the provided line_iter and parses those lines as a header for the picard base distribution file. The header file is assumed to contain a line with both 'INPUT' and 'BaseDistributionByCycle'. If the header parses correctly, the sample name is returned. If the header does not parse correctly, None is returned.
[ "Consumes", "lines", "from", "the", "provided", "line_iter", "and", "parses", "those", "lines", "as", "a", "header", "for", "the", "picard", "base", "distribution", "file", ".", "The", "header", "file", "is", "assumed", "to", "contain", "a", "line", "with", ...
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/BaseDistributionByCycleMetrics.py#L14-L36
224,574
ewels/MultiQC
multiqc/modules/fastp/fastp.py
MultiqcModule.fastp_general_stats_table
def fastp_general_stats_table(self): """ Take the parsed stats from the fastp report and add it to the General Statistics table at the top of the report """ headers = OrderedDict() headers['pct_duplication'] = { 'title': '% Duplication', 'description': 'Duplication rate in filtered reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn-rev' } headers['after_filtering_q30_rate'] = { 'title': '% > Q30', 'description': 'Percentage of reads > Q30 after filtering', 'min': 0, 'max': 100, 'modify': lambda x: x * 100.0, 'scale': 'GnBu', 'suffix': '%', 'hidden': True } headers['after_filtering_q30_bases'] = { 'title': '{} Q30 bases'.format(config.base_count_prefix), 'description': 'Bases > Q30 after filtering ({})'.format(config.base_count_desc), 'min': 0, 'modify': lambda x: x * config.base_count_multiplier, 'scale': 'GnBu', 'shared_key': 'base_count', 'hidden': True } headers['after_filtering_gc_content'] = { 'title': 'GC content', 'description': 'GC content after filtering', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Blues', 'modify': lambda x: x * 100.0 } headers['pct_surviving'] = { 'title': '% PF', 'description': 'Percent reads passing filter', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'BuGn', } headers['pct_adapter'] = { 'title': '% Adapter', 'description': 'Percentage adapter-trimmed reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn-rev', } self.general_stats_addcols(self.fastp_data, headers)
python
def fastp_general_stats_table(self): headers = OrderedDict() headers['pct_duplication'] = { 'title': '% Duplication', 'description': 'Duplication rate in filtered reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn-rev' } headers['after_filtering_q30_rate'] = { 'title': '% > Q30', 'description': 'Percentage of reads > Q30 after filtering', 'min': 0, 'max': 100, 'modify': lambda x: x * 100.0, 'scale': 'GnBu', 'suffix': '%', 'hidden': True } headers['after_filtering_q30_bases'] = { 'title': '{} Q30 bases'.format(config.base_count_prefix), 'description': 'Bases > Q30 after filtering ({})'.format(config.base_count_desc), 'min': 0, 'modify': lambda x: x * config.base_count_multiplier, 'scale': 'GnBu', 'shared_key': 'base_count', 'hidden': True } headers['after_filtering_gc_content'] = { 'title': 'GC content', 'description': 'GC content after filtering', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Blues', 'modify': lambda x: x * 100.0 } headers['pct_surviving'] = { 'title': '% PF', 'description': 'Percent reads passing filter', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'BuGn', } headers['pct_adapter'] = { 'title': '% Adapter', 'description': 'Percentage adapter-trimmed reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn-rev', } self.general_stats_addcols(self.fastp_data, headers)
[ "def", "fastp_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'pct_duplication'", "]", "=", "{", "'title'", ":", "'% Duplication'", ",", "'description'", ":", "'Duplication rate in filtered reads'", ",", "'max'"...
Take the parsed stats from the fastp report and add it to the General Statistics table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "fastp", "report", "and", "add", "it", "to", "the", "General", "Statistics", "table", "at", "the", "top", "of", "the", "report" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastp/fastp.py#L275-L333
224,575
ewels/MultiQC
multiqc/modules/fastp/fastp.py
MultiqcModule.fastp_filtered_reads_chart
def fastp_filtered_reads_chart(self): """ Function to generate the fastp filtered reads bar plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['filtering_result_passed_filter_reads'] = { 'name': 'Passed Filter' } keys['filtering_result_low_quality_reads'] = { 'name': 'Low Quality' } keys['filtering_result_too_many_N_reads'] = { 'name': 'Too Many N' } keys['filtering_result_too_short_reads'] = { 'name': 'Too short' } # Config for the plot pconfig = { 'id': 'fastp_filtered_reads_plot', 'title': 'Fastp: Filtered Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads', 'hide_zero_cats': False, } return bargraph.plot(self.fastp_data, keys, pconfig)
python
def fastp_filtered_reads_chart(self): # Specify the order of the different possible categories keys = OrderedDict() keys['filtering_result_passed_filter_reads'] = { 'name': 'Passed Filter' } keys['filtering_result_low_quality_reads'] = { 'name': 'Low Quality' } keys['filtering_result_too_many_N_reads'] = { 'name': 'Too Many N' } keys['filtering_result_too_short_reads'] = { 'name': 'Too short' } # Config for the plot pconfig = { 'id': 'fastp_filtered_reads_plot', 'title': 'Fastp: Filtered Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads', 'hide_zero_cats': False, } return bargraph.plot(self.fastp_data, keys, pconfig)
[ "def", "fastp_filtered_reads_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'filtering_result_passed_filter_reads'", "]", "=", "{", "'name'", ":", "'Passed Filter'", "}", "keys...
Function to generate the fastp filtered reads bar plot
[ "Function", "to", "generate", "the", "fastp", "filtered", "reads", "bar", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastp/fastp.py#L335-L352
224,576
ewels/MultiQC
multiqc/modules/fastp/fastp.py
MultiqcModule.fastp_read_qual_plot
def fastp_read_qual_plot(self): """ Make the read quality plot for Fastp """ data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_qual_plotdata, 'Sequence Quality') pconfig = { 'id': 'fastp-seq-quality-plot', 'title': 'Fastp: Sequence Quality', 'xlab': 'Read Position', 'ylab': 'R1 Before filtering: Sequence Quality', 'ymin': 0, 'xDecimals': False, 'data_labels': data_labels } return linegraph.plot(pdata, pconfig)
python
def fastp_read_qual_plot(self): data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_qual_plotdata, 'Sequence Quality') pconfig = { 'id': 'fastp-seq-quality-plot', 'title': 'Fastp: Sequence Quality', 'xlab': 'Read Position', 'ylab': 'R1 Before filtering: Sequence Quality', 'ymin': 0, 'xDecimals': False, 'data_labels': data_labels } return linegraph.plot(pdata, pconfig)
[ "def", "fastp_read_qual_plot", "(", "self", ")", ":", "data_labels", ",", "pdata", "=", "self", ".", "filter_pconfig_pdata_subplots", "(", "self", ".", "fastp_qual_plotdata", ",", "'Sequence Quality'", ")", "pconfig", "=", "{", "'id'", ":", "'fastp-seq-quality-plot'...
Make the read quality plot for Fastp
[ "Make", "the", "read", "quality", "plot", "for", "Fastp" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastp/fastp.py#L354-L366
224,577
ewels/MultiQC
multiqc/modules/fastp/fastp.py
MultiqcModule.fastp_read_gc_plot
def fastp_read_gc_plot(self): """ Make the read GC plot for Fastp """ data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_gc_content_data, 'Base Content Percent') pconfig = { 'id': 'fastp-seq-content-gc-plot', 'title': 'Fastp: Read GC Content', 'xlab': 'Read Position', 'ylab': 'R1 Before filtering: Base Content Percent', 'ymax': 100, 'ymin': 0, 'xDecimals': False, 'yLabelFormat': '{value}%', 'tt_label': '{point.x}: {point.y:.2f}%', 'data_labels': data_labels } return linegraph.plot(pdata, pconfig)
python
def fastp_read_gc_plot(self): data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_gc_content_data, 'Base Content Percent') pconfig = { 'id': 'fastp-seq-content-gc-plot', 'title': 'Fastp: Read GC Content', 'xlab': 'Read Position', 'ylab': 'R1 Before filtering: Base Content Percent', 'ymax': 100, 'ymin': 0, 'xDecimals': False, 'yLabelFormat': '{value}%', 'tt_label': '{point.x}: {point.y:.2f}%', 'data_labels': data_labels } return linegraph.plot(pdata, pconfig)
[ "def", "fastp_read_gc_plot", "(", "self", ")", ":", "data_labels", ",", "pdata", "=", "self", ".", "filter_pconfig_pdata_subplots", "(", "self", ".", "fastp_gc_content_data", ",", "'Base Content Percent'", ")", "pconfig", "=", "{", "'id'", ":", "'fastp-seq-content-g...
Make the read GC plot for Fastp
[ "Make", "the", "read", "GC", "plot", "for", "Fastp" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastp/fastp.py#L368-L383
224,578
ewels/MultiQC
multiqc/modules/fastp/fastp.py
MultiqcModule.fastp_read_n_plot
def fastp_read_n_plot(self): """ Make the read N content plot for Fastp """ data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_n_content_data, 'Base Content Percent') pconfig = { 'id': 'fastp-seq-content-n-plot', 'title': 'Fastp: Read N Content', 'xlab': 'Read Position', 'ylab': 'R1 Before filtering: Base Content Percent', 'yCeiling': 100, 'yMinRange': 5, 'ymin': 0, 'xDecimals': False, 'yLabelFormat': '{value}%', 'tt_label': '{point.x}: {point.y:.2f}%', 'data_labels': data_labels } return linegraph.plot(pdata, pconfig)
python
def fastp_read_n_plot(self): data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_n_content_data, 'Base Content Percent') pconfig = { 'id': 'fastp-seq-content-n-plot', 'title': 'Fastp: Read N Content', 'xlab': 'Read Position', 'ylab': 'R1 Before filtering: Base Content Percent', 'yCeiling': 100, 'yMinRange': 5, 'ymin': 0, 'xDecimals': False, 'yLabelFormat': '{value}%', 'tt_label': '{point.x}: {point.y:.2f}%', 'data_labels': data_labels } return linegraph.plot(pdata, pconfig)
[ "def", "fastp_read_n_plot", "(", "self", ")", ":", "data_labels", ",", "pdata", "=", "self", ".", "filter_pconfig_pdata_subplots", "(", "self", ".", "fastp_n_content_data", ",", "'Base Content Percent'", ")", "pconfig", "=", "{", "'id'", ":", "'fastp-seq-content-n-p...
Make the read N content plot for Fastp
[ "Make", "the", "read", "N", "content", "plot", "for", "Fastp" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastp/fastp.py#L385-L401
224,579
ewels/MultiQC
multiqc/modules/deeptools/plotProfile.py
plotProfileMixin.parse_plotProfile
def parse_plotProfile(self): """Find plotProfile output""" self.deeptools_plotProfile = dict() for f in self.find_log_files('deeptools/plotProfile', filehandles=False): parsed_data, bin_labels, converted_bin_labels = self.parsePlotProfileData(f) for k, v in parsed_data.items(): if k in self.deeptools_plotProfile: log.warning("Replacing duplicate sample {}.".format(k)) self.deeptools_plotProfile[k] = v if len(parsed_data) > 0: self.add_data_source(f, section='plotProfile') if len(self.deeptools_plotProfile) > 0: config = { 'id': 'read_distribution_profile', 'title': 'deeptools: Read Distribution Profile after Annotation', 'ylab': 'Occurrence', 'xlab': None, 'smooth_points': 100, 'xPlotBands': [ {'from': converted_bin_labels[bin_labels.index('TES')], 'to': converted_bin_labels[-1], 'color': '#f7cfcf'}, {'from': converted_bin_labels[bin_labels.index('TSS')], 'to': converted_bin_labels[bin_labels.index('TES')], 'color': '#ffffe2'}, {'from': converted_bin_labels[0], 'to': converted_bin_labels[bin_labels.index('TSS')], 'color': '#e5fce0'}, ], 'xPlotLines': [ {'width': 1, 'value': converted_bin_labels[bin_labels.index('TES')], 'dashStyle': 'Dash', 'color': '#000000'}, {'width': 1, 'value': converted_bin_labels[bin_labels.index('TSS')], 'dashStyle': 'Dash', 'color': '#000000'}, ], } self.add_section ( name = 'Read Distribution Profile after Annotation', anchor = 'read_distribution_profile_plot', description="Accumulated view of the distribution of sequence reads related to the closest annotated gene. All annotated genes have been normalized to the same size. Green: {} upstream of gene to {}; Yellow: {} to {}; Pink: {} to {} downstream of gene".format(list(filter(None,bin_labels))[0], list(filter(None,bin_labels))[1], list(filter(None,bin_labels))[1], list(filter(None,bin_labels))[2], list(filter(None,bin_labels))[2], list(filter(None,bin_labels))[3]), plot=linegraph.plot(self.deeptools_plotProfile, config) ) return len(self.deeptools_bamPEFragmentSizeDistribution)
python
def parse_plotProfile(self): self.deeptools_plotProfile = dict() for f in self.find_log_files('deeptools/plotProfile', filehandles=False): parsed_data, bin_labels, converted_bin_labels = self.parsePlotProfileData(f) for k, v in parsed_data.items(): if k in self.deeptools_plotProfile: log.warning("Replacing duplicate sample {}.".format(k)) self.deeptools_plotProfile[k] = v if len(parsed_data) > 0: self.add_data_source(f, section='plotProfile') if len(self.deeptools_plotProfile) > 0: config = { 'id': 'read_distribution_profile', 'title': 'deeptools: Read Distribution Profile after Annotation', 'ylab': 'Occurrence', 'xlab': None, 'smooth_points': 100, 'xPlotBands': [ {'from': converted_bin_labels[bin_labels.index('TES')], 'to': converted_bin_labels[-1], 'color': '#f7cfcf'}, {'from': converted_bin_labels[bin_labels.index('TSS')], 'to': converted_bin_labels[bin_labels.index('TES')], 'color': '#ffffe2'}, {'from': converted_bin_labels[0], 'to': converted_bin_labels[bin_labels.index('TSS')], 'color': '#e5fce0'}, ], 'xPlotLines': [ {'width': 1, 'value': converted_bin_labels[bin_labels.index('TES')], 'dashStyle': 'Dash', 'color': '#000000'}, {'width': 1, 'value': converted_bin_labels[bin_labels.index('TSS')], 'dashStyle': 'Dash', 'color': '#000000'}, ], } self.add_section ( name = 'Read Distribution Profile after Annotation', anchor = 'read_distribution_profile_plot', description="Accumulated view of the distribution of sequence reads related to the closest annotated gene. All annotated genes have been normalized to the same size. Green: {} upstream of gene to {}; Yellow: {} to {}; Pink: {} to {} downstream of gene".format(list(filter(None,bin_labels))[0], list(filter(None,bin_labels))[1], list(filter(None,bin_labels))[1], list(filter(None,bin_labels))[2], list(filter(None,bin_labels))[2], list(filter(None,bin_labels))[3]), plot=linegraph.plot(self.deeptools_plotProfile, config) ) return len(self.deeptools_bamPEFragmentSizeDistribution)
[ "def", "parse_plotProfile", "(", "self", ")", ":", "self", ".", "deeptools_plotProfile", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'deeptools/plotProfile'", ",", "filehandles", "=", "False", ")", ":", "parsed_data", ",", "...
Find plotProfile output
[ "Find", "plotProfile", "output" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/deeptools/plotProfile.py#L16-L53
224,580
ewels/MultiQC
multiqc/modules/qorts/qorts.py
MultiqcModule.qorts_general_stats
def qorts_general_stats (self): """ Add columns to the General Statistics table """ headers = OrderedDict() headers['Genes_PercentWithNonzeroCounts'] = { 'title': '% Genes with Counts', 'description': 'Percent of Genes with Non-Zero Counts', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['NumberOfChromosomesCovered'] = { 'title': 'Chrs Covered', 'description': 'Number of Chromosomes Covered', 'format': '{:,.0f}' } self.general_stats_addcols(self.qorts_data, headers)
python
def qorts_general_stats (self): headers = OrderedDict() headers['Genes_PercentWithNonzeroCounts'] = { 'title': '% Genes with Counts', 'description': 'Percent of Genes with Non-Zero Counts', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn' } headers['NumberOfChromosomesCovered'] = { 'title': 'Chrs Covered', 'description': 'Number of Chromosomes Covered', 'format': '{:,.0f}' } self.general_stats_addcols(self.qorts_data, headers)
[ "def", "qorts_general_stats", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'Genes_PercentWithNonzeroCounts'", "]", "=", "{", "'title'", ":", "'% Genes with Counts'", ",", "'description'", ":", "'Percent of Genes with Non-Zero Counts'"...
Add columns to the General Statistics table
[ "Add", "columns", "to", "the", "General", "Statistics", "table" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/qorts/qorts.py#L76-L92
224,581
ewels/MultiQC
multiqc/modules/rna_seqc/rna_seqc.py
MultiqcModule.parse_metrics
def parse_metrics(self, f): """ Parse the metrics.tsv file from RNA-SeQC """ headers = None for l in f['f'].splitlines(): s = l.strip().split("\t") if headers is None: headers = s else: s_name = s[ headers.index('Sample') ] data = dict() for idx, h in enumerate(headers): try: data[h] = float(s[idx]) except ValueError: data[h] = s[idx] self.rna_seqc_metrics[s_name] = data
python
def parse_metrics(self, f): headers = None for l in f['f'].splitlines(): s = l.strip().split("\t") if headers is None: headers = s else: s_name = s[ headers.index('Sample') ] data = dict() for idx, h in enumerate(headers): try: data[h] = float(s[idx]) except ValueError: data[h] = s[idx] self.rna_seqc_metrics[s_name] = data
[ "def", "parse_metrics", "(", "self", ",", "f", ")", ":", "headers", "=", "None", "for", "l", "in", "f", "[", "'f'", "]", ".", "splitlines", "(", ")", ":", "s", "=", "l", ".", "strip", "(", ")", ".", "split", "(", "\"\\t\"", ")", "if", "headers"...
Parse the metrics.tsv file from RNA-SeQC
[ "Parse", "the", "metrics", ".", "tsv", "file", "from", "RNA", "-", "SeQC" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rna_seqc/rna_seqc.py#L68-L85
224,582
ewels/MultiQC
multiqc/modules/rna_seqc/rna_seqc.py
MultiqcModule.rnaseqc_general_stats
def rnaseqc_general_stats (self): """ Add alignment rate to the general stats table """ headers = OrderedDict() headers['Expression Profiling Efficiency'] = { 'title': '% Expression Efficiency', 'description': 'Expression Profiling Efficiency: Ratio of exon reads to total reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn', 'modify': lambda x: float(x) * 100.0 } headers['Genes Detected'] = { 'title': '# Genes', 'description': 'Number of genes detected with at least 5 reads.', 'min': 0, 'scale': 'Bu', 'format': '{:,.0f}' } headers['rRNA rate'] = { 'title': '% rRNA Alignment', 'description': ' rRNA reads (non-duplicate and duplicate reads) per total reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Reds', 'modify': lambda x: float(x) * 100.0 } self.general_stats_addcols(self.rna_seqc_metrics, headers)
python
def rnaseqc_general_stats (self): headers = OrderedDict() headers['Expression Profiling Efficiency'] = { 'title': '% Expression Efficiency', 'description': 'Expression Profiling Efficiency: Ratio of exon reads to total reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'YlGn', 'modify': lambda x: float(x) * 100.0 } headers['Genes Detected'] = { 'title': '# Genes', 'description': 'Number of genes detected with at least 5 reads.', 'min': 0, 'scale': 'Bu', 'format': '{:,.0f}' } headers['rRNA rate'] = { 'title': '% rRNA Alignment', 'description': ' rRNA reads (non-duplicate and duplicate reads) per total reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'Reds', 'modify': lambda x: float(x) * 100.0 } self.general_stats_addcols(self.rna_seqc_metrics, headers)
[ "def", "rnaseqc_general_stats", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'Expression Profiling Efficiency'", "]", "=", "{", "'title'", ":", "'% Expression Efficiency'", ",", "'description'", ":", "'Expression Profiling Efficiency:...
Add alignment rate to the general stats table
[ "Add", "alignment", "rate", "to", "the", "general", "stats", "table" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rna_seqc/rna_seqc.py#L87-L118
224,583
ewels/MultiQC
multiqc/modules/rna_seqc/rna_seqc.py
MultiqcModule.transcript_associated_plot
def transcript_associated_plot (self): """ Plot a bargraph showing the Transcript-associated reads """ # Plot bar graph of groups keys = OrderedDict() keys['Exonic Rate'] = { 'name': 'Exonic', 'color': '#2f7ed8' } keys['Intronic Rate'] = { 'name': 'Intronic', 'color': '#8bbc21' } keys['Intergenic Rate'] = { 'name': 'Intergenic', 'color': '#0d233a'} # Config for the plot pconfig = { 'id': 'rna_seqc_position_plot', 'title': 'RNA-SeQC: Transcript-associated reads', 'ylab': 'Ratio of Reads', 'cpswitch': False, 'ymax': 1, 'ymin': 0, 'tt_decimals': 3, 'cpswitch_c_active': False } self.add_section ( name = 'Transcript-associated reads', anchor = 'Transcript_associated', helptext = 'All of the above rates are per mapped read. Exonic Rate is the fraction mapping within exons. ' 'Intronic Rate is the fraction mapping within introns. ' 'Intergenic Rate is the fraction mapping in the genomic space between genes. ', plot = bargraph.plot(self.rna_seqc_metrics, keys, pconfig) )
python
def transcript_associated_plot (self): # Plot bar graph of groups keys = OrderedDict() keys['Exonic Rate'] = { 'name': 'Exonic', 'color': '#2f7ed8' } keys['Intronic Rate'] = { 'name': 'Intronic', 'color': '#8bbc21' } keys['Intergenic Rate'] = { 'name': 'Intergenic', 'color': '#0d233a'} # Config for the plot pconfig = { 'id': 'rna_seqc_position_plot', 'title': 'RNA-SeQC: Transcript-associated reads', 'ylab': 'Ratio of Reads', 'cpswitch': False, 'ymax': 1, 'ymin': 0, 'tt_decimals': 3, 'cpswitch_c_active': False } self.add_section ( name = 'Transcript-associated reads', anchor = 'Transcript_associated', helptext = 'All of the above rates are per mapped read. Exonic Rate is the fraction mapping within exons. ' 'Intronic Rate is the fraction mapping within introns. ' 'Intergenic Rate is the fraction mapping in the genomic space between genes. ', plot = bargraph.plot(self.rna_seqc_metrics, keys, pconfig) )
[ "def", "transcript_associated_plot", "(", "self", ")", ":", "# Plot bar graph of groups", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'Exonic Rate'", "]", "=", "{", "'name'", ":", "'Exonic'", ",", "'color'", ":", "'#2f7ed8'", "}", "keys", "[", "'Intron...
Plot a bargraph showing the Transcript-associated reads
[ "Plot", "a", "bargraph", "showing", "the", "Transcript", "-", "associated", "reads" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rna_seqc/rna_seqc.py#L120-L147
224,584
ewels/MultiQC
multiqc/modules/rna_seqc/rna_seqc.py
MultiqcModule.strand_barplot
def strand_barplot(self): """ Plot a bargraph showing the strandedness of alignments """ # Plot bar graph of groups keys = [ 'End 1 Sense', 'End 1 Antisense', 'End 2 Sense', 'End 2 Antisense' ] # Config for the plot pconfig = { 'id': 'rna_seqc_strandedness_plot', 'title': 'RNA-SeQC: Strand Specificity', 'ylab': '% Reads', 'cpswitch_counts_label': '# Reads', 'cpswitch_percent_label': '% Reads', 'ymin': 0, 'cpswitch_c_active': False } self.add_section ( name = 'Strand Specificity', anchor = 'rna_seqc_strand_specificity', helptext = 'End 1/2 Sense are the number of End 1 or 2 reads that were sequenced in the sense direction. ' 'Similarly, End 1/2 Antisense are the number of End 1 or 2 reads that were sequenced in the ' 'antisense direction', plot = bargraph.plot(self.rna_seqc_metrics, keys, pconfig) )
python
def strand_barplot(self): # Plot bar graph of groups keys = [ 'End 1 Sense', 'End 1 Antisense', 'End 2 Sense', 'End 2 Antisense' ] # Config for the plot pconfig = { 'id': 'rna_seqc_strandedness_plot', 'title': 'RNA-SeQC: Strand Specificity', 'ylab': '% Reads', 'cpswitch_counts_label': '# Reads', 'cpswitch_percent_label': '% Reads', 'ymin': 0, 'cpswitch_c_active': False } self.add_section ( name = 'Strand Specificity', anchor = 'rna_seqc_strand_specificity', helptext = 'End 1/2 Sense are the number of End 1 or 2 reads that were sequenced in the sense direction. ' 'Similarly, End 1/2 Antisense are the number of End 1 or 2 reads that were sequenced in the ' 'antisense direction', plot = bargraph.plot(self.rna_seqc_metrics, keys, pconfig) )
[ "def", "strand_barplot", "(", "self", ")", ":", "# Plot bar graph of groups", "keys", "=", "[", "'End 1 Sense'", ",", "'End 1 Antisense'", ",", "'End 2 Sense'", ",", "'End 2 Antisense'", "]", "# Config for the plot", "pconfig", "=", "{", "'id'", ":", "'rna_seqc_strand...
Plot a bargraph showing the strandedness of alignments
[ "Plot", "a", "bargraph", "showing", "the", "strandedness", "of", "alignments" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rna_seqc/rna_seqc.py#L151-L172
224,585
ewels/MultiQC
multiqc/modules/rna_seqc/rna_seqc.py
MultiqcModule.parse_coverage
def parse_coverage (self, f): """ Parse the RNA-SeQC Normalised Coverage Files """ data = dict() s_names = None j = 1 for l in f['f'].splitlines(): s = l.strip().split("\t") if s_names is None: s_names = s for s_name in s_names: data[s_name] = dict() else: for i, v in enumerate(s): data[s_names[i]][j] = float(v) j += 1 if f['fn'] == 'meanCoverageNorm_high.txt': self.rna_seqc_norm_high_cov.update(data) elif f['fn'] == 'meanCoverageNorm_medium.txt': self.rna_seqc_norm_medium_cov.update(data) elif f['fn'] == 'meanCoverageNorm_low.txt': self.rna_seqc_norm_low_cov.update(data)
python
def parse_coverage (self, f): data = dict() s_names = None j = 1 for l in f['f'].splitlines(): s = l.strip().split("\t") if s_names is None: s_names = s for s_name in s_names: data[s_name] = dict() else: for i, v in enumerate(s): data[s_names[i]][j] = float(v) j += 1 if f['fn'] == 'meanCoverageNorm_high.txt': self.rna_seqc_norm_high_cov.update(data) elif f['fn'] == 'meanCoverageNorm_medium.txt': self.rna_seqc_norm_medium_cov.update(data) elif f['fn'] == 'meanCoverageNorm_low.txt': self.rna_seqc_norm_low_cov.update(data)
[ "def", "parse_coverage", "(", "self", ",", "f", ")", ":", "data", "=", "dict", "(", ")", "s_names", "=", "None", "j", "=", "1", "for", "l", "in", "f", "[", "'f'", "]", ".", "splitlines", "(", ")", ":", "s", "=", "l", ".", "strip", "(", ")", ...
Parse the RNA-SeQC Normalised Coverage Files
[ "Parse", "the", "RNA", "-", "SeQC", "Normalised", "Coverage", "Files" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rna_seqc/rna_seqc.py#L175-L195
224,586
ewels/MultiQC
multiqc/modules/rna_seqc/rna_seqc.py
MultiqcModule.coverage_lineplot
def coverage_lineplot (self): """ Make HTML for coverage line plots """ # Add line graph to section data = list() data_labels = list() if len(self.rna_seqc_norm_high_cov) > 0: data.append(self.rna_seqc_norm_high_cov) data_labels.append({'name': 'High Expressed'}) if len(self.rna_seqc_norm_medium_cov) > 0: data.append(self.rna_seqc_norm_medium_cov) data_labels.append({'name': 'Medium Expressed'}) if len(self.rna_seqc_norm_low_cov) > 0: data.append(self.rna_seqc_norm_low_cov) data_labels.append({'name': 'Low Expressed'}) pconfig = { 'id': 'rna_seqc_mean_coverage_plot', 'title': 'RNA-SeQC: Gene Body Coverage', 'ylab': '% Coverage', 'xlab': "Gene Body Percentile (5' -> 3')", 'xmin': 0, 'xmax': 100, 'tt_label': "<strong>{point.x}% from 5'</strong>: {point.y:.2f}", 'data_labels': data_labels } if len(data) > 0: self.add_section ( name = 'Gene Body Coverage', anchor = 'rseqc-rna_seqc_mean_coverage', helptext = 'The metrics are calculated across the transcripts with tiered expression levels.', plot = linegraph.plot(data, pconfig) )
python
def coverage_lineplot (self): # Add line graph to section data = list() data_labels = list() if len(self.rna_seqc_norm_high_cov) > 0: data.append(self.rna_seqc_norm_high_cov) data_labels.append({'name': 'High Expressed'}) if len(self.rna_seqc_norm_medium_cov) > 0: data.append(self.rna_seqc_norm_medium_cov) data_labels.append({'name': 'Medium Expressed'}) if len(self.rna_seqc_norm_low_cov) > 0: data.append(self.rna_seqc_norm_low_cov) data_labels.append({'name': 'Low Expressed'}) pconfig = { 'id': 'rna_seqc_mean_coverage_plot', 'title': 'RNA-SeQC: Gene Body Coverage', 'ylab': '% Coverage', 'xlab': "Gene Body Percentile (5' -> 3')", 'xmin': 0, 'xmax': 100, 'tt_label': "<strong>{point.x}% from 5'</strong>: {point.y:.2f}", 'data_labels': data_labels } if len(data) > 0: self.add_section ( name = 'Gene Body Coverage', anchor = 'rseqc-rna_seqc_mean_coverage', helptext = 'The metrics are calculated across the transcripts with tiered expression levels.', plot = linegraph.plot(data, pconfig) )
[ "def", "coverage_lineplot", "(", "self", ")", ":", "# Add line graph to section", "data", "=", "list", "(", ")", "data_labels", "=", "list", "(", ")", "if", "len", "(", "self", ".", "rna_seqc_norm_high_cov", ")", ">", "0", ":", "data", ".", "append", "(", ...
Make HTML for coverage line plots
[ "Make", "HTML", "for", "coverage", "line", "plots" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rna_seqc/rna_seqc.py#L197-L227
224,587
ewels/MultiQC
multiqc/modules/rna_seqc/rna_seqc.py
MultiqcModule.parse_correlation
def parse_correlation(self, f): """ Parse RNA-SeQC correlation matrices """ s_names = None data = list() for l in f['f'].splitlines(): s = l.strip().split("\t") if s_names is None: s_names = [ x for x in s if x != '' ] else: data.append(s[1:]) if f['fn'] == 'corrMatrixPearson.txt': self.rna_seqc_pearson = (s_names, data) elif f['fn'] == 'corrMatrixSpearman.txt': self.rna_seqc_spearman = (s_names, data)
python
def parse_correlation(self, f): s_names = None data = list() for l in f['f'].splitlines(): s = l.strip().split("\t") if s_names is None: s_names = [ x for x in s if x != '' ] else: data.append(s[1:]) if f['fn'] == 'corrMatrixPearson.txt': self.rna_seqc_pearson = (s_names, data) elif f['fn'] == 'corrMatrixSpearman.txt': self.rna_seqc_spearman = (s_names, data)
[ "def", "parse_correlation", "(", "self", ",", "f", ")", ":", "s_names", "=", "None", "data", "=", "list", "(", ")", "for", "l", "in", "f", "[", "'f'", "]", ".", "splitlines", "(", ")", ":", "s", "=", "l", ".", "strip", "(", ")", ".", "split", ...
Parse RNA-SeQC correlation matrices
[ "Parse", "RNA", "-", "SeQC", "correlation", "matrices" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rna_seqc/rna_seqc.py#L229-L242
224,588
ewels/MultiQC
multiqc/modules/rna_seqc/rna_seqc.py
MultiqcModule.plot_correlation_heatmap
def plot_correlation_heatmap(self): """ Return HTML for correlation heatmap """ data = None corr_type = None correlation_type = getattr(config, 'rna_seqc' ,{}).get('default_correlation', 'spearman') if self.rna_seqc_spearman is not None and correlation_type != 'pearson': data = self.rna_seqc_spearman corr_type = 'Spearman' elif self.rna_seqc_pearson is not None: data = self.rna_seqc_pearson corr_type = 'Pearson' if data is not None: pconfig = { 'id': 'rna_seqc_correlation_heatmap', 'title': 'RNA-SeQC: {} Sample Correlation'.format(corr_type) } self.add_section ( name = '{} Correlation'.format(corr_type), anchor = 'rseqc-rna_seqc_correlation', plot = heatmap.plot(data[1], data[0], data[0], pconfig) )
python
def plot_correlation_heatmap(self): data = None corr_type = None correlation_type = getattr(config, 'rna_seqc' ,{}).get('default_correlation', 'spearman') if self.rna_seqc_spearman is not None and correlation_type != 'pearson': data = self.rna_seqc_spearman corr_type = 'Spearman' elif self.rna_seqc_pearson is not None: data = self.rna_seqc_pearson corr_type = 'Pearson' if data is not None: pconfig = { 'id': 'rna_seqc_correlation_heatmap', 'title': 'RNA-SeQC: {} Sample Correlation'.format(corr_type) } self.add_section ( name = '{} Correlation'.format(corr_type), anchor = 'rseqc-rna_seqc_correlation', plot = heatmap.plot(data[1], data[0], data[0], pconfig) )
[ "def", "plot_correlation_heatmap", "(", "self", ")", ":", "data", "=", "None", "corr_type", "=", "None", "correlation_type", "=", "getattr", "(", "config", ",", "'rna_seqc'", ",", "{", "}", ")", ".", "get", "(", "'default_correlation'", ",", "'spearman'", ")...
Return HTML for correlation heatmap
[ "Return", "HTML", "for", "correlation", "heatmap" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/rna_seqc/rna_seqc.py#L245-L265
224,589
ewels/MultiQC
multiqc/modules/theta2/theta2.py
MultiqcModule.parse_theta2_report
def parse_theta2_report (self, fh): """ Parse the final THetA2 log file. """ parsed_data = {} for l in fh: if l.startswith('#'): continue else: s = l.split("\t") purities = s[1].split(',') parsed_data['proportion_germline'] = float(purities[0]) * 100.0 for i, v in enumerate(purities[1:]): if i <= 5: parsed_data['proportion_tumour_{}'.format(i+1)] = float(v) * 100.0 else: parsed_data['proportion_tumour_gt5'] = (float(v) * 100.0) + parsed_data.get('proportion_tumour_gt5', 0) break return parsed_data
python
def parse_theta2_report (self, fh): parsed_data = {} for l in fh: if l.startswith('#'): continue else: s = l.split("\t") purities = s[1].split(',') parsed_data['proportion_germline'] = float(purities[0]) * 100.0 for i, v in enumerate(purities[1:]): if i <= 5: parsed_data['proportion_tumour_{}'.format(i+1)] = float(v) * 100.0 else: parsed_data['proportion_tumour_gt5'] = (float(v) * 100.0) + parsed_data.get('proportion_tumour_gt5', 0) break return parsed_data
[ "def", "parse_theta2_report", "(", "self", ",", "fh", ")", ":", "parsed_data", "=", "{", "}", "for", "l", "in", "fh", ":", "if", "l", ".", "startswith", "(", "'#'", ")", ":", "continue", "else", ":", "s", "=", "l", ".", "split", "(", "\"\\t\"", "...
Parse the final THetA2 log file.
[ "Parse", "the", "final", "THetA2", "log", "file", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/theta2/theta2.py#L56-L72
224,590
ewels/MultiQC
multiqc/modules/gatk/varianteval.py
parse_single_report
def parse_single_report(f): """ Parse a gatk varianteval varianteval """ # Fixme: Separate GATKReport parsing and data subsetting. A GATKReport parser now available from the GATK MultiqcModel. data = dict() in_CompOverlap = False in_CountVariants = False in_TiTv = False for l in f: # Detect section headers if '#:GATKTable:CompOverlap' in l: in_CompOverlap = True elif '#:GATKTable:CountVariants' in l: in_CountVariants = True elif '#:GATKTable:TiTvVariantEvaluator' in l: in_TiTv = True else: # Parse contents using nested loops if in_CompOverlap: headers = l.split() while in_CompOverlap: l = f.readline().strip("\n") d = dict() try: for i, s in enumerate(l.split()): d[headers[i]] = s if d['Novelty'] == 'all': data['reference'] = d['CompRod'] data['comp_rate'] = float(d['compRate']) data['concordant_rate'] = float(d['concordantRate']) data['eval_variants'] = int(d['nEvalVariants']) data['novel_sites'] = int(d['novelSites']) elif d['Novelty'] == 'known': data['known_sites'] = int(d['nEvalVariants']) except KeyError: in_CompOverlap = False elif in_CountVariants: headers = l.split() while in_CountVariants: l = f.readline().strip("\n") d = dict() try: for i, s in enumerate(l.split()): d[headers[i]] = s if d['Novelty'] == 'all': data['snps'] = int(d['nSNPs']) data['mnps'] = int(d['nMNPs']) data['insertions'] = int(d['nInsertions']) data['deletions'] = int(d['nDeletions']) data['complex'] = int(d['nComplex']) data['symbolic'] = int(d['nSymbolic']) data['mixed'] = int(d['nMixed']) data['nocalls'] = int(d['nNoCalls']) except KeyError: in_CountVariants = False elif in_TiTv: headers = l.split() data['titv_reference'] = 'unknown' while in_TiTv: l = f.readline().strip("\n") d = dict() try: for i, s in enumerate(l.split()): d[headers[i]] = s if d['Novelty'] == 'known': data['titv_reference'] = d['CompRod'] data['known_titv'] = float(d['tiTvRatio']) elif d['Novelty'] == 'novel': data['novel_titv'] = float(d['tiTvRatio']) except KeyError: in_TiTv = False return data
python
def parse_single_report(f): # Fixme: Separate GATKReport parsing and data subsetting. A GATKReport parser now available from the GATK MultiqcModel. data = dict() in_CompOverlap = False in_CountVariants = False in_TiTv = False for l in f: # Detect section headers if '#:GATKTable:CompOverlap' in l: in_CompOverlap = True elif '#:GATKTable:CountVariants' in l: in_CountVariants = True elif '#:GATKTable:TiTvVariantEvaluator' in l: in_TiTv = True else: # Parse contents using nested loops if in_CompOverlap: headers = l.split() while in_CompOverlap: l = f.readline().strip("\n") d = dict() try: for i, s in enumerate(l.split()): d[headers[i]] = s if d['Novelty'] == 'all': data['reference'] = d['CompRod'] data['comp_rate'] = float(d['compRate']) data['concordant_rate'] = float(d['concordantRate']) data['eval_variants'] = int(d['nEvalVariants']) data['novel_sites'] = int(d['novelSites']) elif d['Novelty'] == 'known': data['known_sites'] = int(d['nEvalVariants']) except KeyError: in_CompOverlap = False elif in_CountVariants: headers = l.split() while in_CountVariants: l = f.readline().strip("\n") d = dict() try: for i, s in enumerate(l.split()): d[headers[i]] = s if d['Novelty'] == 'all': data['snps'] = int(d['nSNPs']) data['mnps'] = int(d['nMNPs']) data['insertions'] = int(d['nInsertions']) data['deletions'] = int(d['nDeletions']) data['complex'] = int(d['nComplex']) data['symbolic'] = int(d['nSymbolic']) data['mixed'] = int(d['nMixed']) data['nocalls'] = int(d['nNoCalls']) except KeyError: in_CountVariants = False elif in_TiTv: headers = l.split() data['titv_reference'] = 'unknown' while in_TiTv: l = f.readline().strip("\n") d = dict() try: for i, s in enumerate(l.split()): d[headers[i]] = s if d['Novelty'] == 'known': data['titv_reference'] = d['CompRod'] data['known_titv'] = float(d['tiTvRatio']) elif d['Novelty'] == 'novel': data['novel_titv'] = float(d['tiTvRatio']) except KeyError: in_TiTv = False return data
[ "def", "parse_single_report", "(", "f", ")", ":", "# Fixme: Separate GATKReport parsing and data subsetting. A GATKReport parser now available from the GATK MultiqcModel.", "data", "=", "dict", "(", ")", "in_CompOverlap", "=", "False", "in_CountVariants", "=", "False", "in_TiTv",...
Parse a gatk varianteval varianteval
[ "Parse", "a", "gatk", "varianteval", "varianteval" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/gatk/varianteval.py#L81-L153
224,591
ewels/MultiQC
multiqc/modules/gatk/varianteval.py
comp_overlap_table
def comp_overlap_table(data): """Build a table from the comp overlaps output.""" headers = OrderedDict() headers['comp_rate'] = { 'title': 'Compare rate', 'description': 'Ratio of known variants found in the reference set.', 'namespace': 'GATK', 'min': 0, 'max': 100, 'suffix': '%', 'format': '{:,.2f}', 'scale': 'Blues', } headers['concordant_rate'] = { 'title': 'Concordant rate', 'description': 'Ratio of variants matching alleles in the reference set.', 'namespace': 'GATK', 'min': 0, 'max': 100, 'suffix': '%', 'format': '{:,.2f}', 'scale': 'Blues', } headers['eval_variants'] = { 'title': 'M Evaluated variants', 'description': 'Number of called variants (millions)', 'namespace': 'GATK', 'min': 0, 'modify': lambda x: float(x) / 1000000.0 } headers['known_sites'] = { 'title': 'M Known sites', 'description': 'Number of known variants (millions)', 'namespace': 'GATK', 'min': 0, 'modify': lambda x: float(x) / 1000000.0 } headers['novel_sites'] = { 'title': 'M Novel sites', 'description': 'Number of novel variants (millions)', 'namespace': 'GATK', 'min': 0, 'modify': lambda x: float(x) / 1000000.0 } table_html = table.plot(data, headers, {'id': 'gatk_compare_overlap', 'table_title': 'GATK - Compare Overlap'}) return table_html
python
def comp_overlap_table(data): headers = OrderedDict() headers['comp_rate'] = { 'title': 'Compare rate', 'description': 'Ratio of known variants found in the reference set.', 'namespace': 'GATK', 'min': 0, 'max': 100, 'suffix': '%', 'format': '{:,.2f}', 'scale': 'Blues', } headers['concordant_rate'] = { 'title': 'Concordant rate', 'description': 'Ratio of variants matching alleles in the reference set.', 'namespace': 'GATK', 'min': 0, 'max': 100, 'suffix': '%', 'format': '{:,.2f}', 'scale': 'Blues', } headers['eval_variants'] = { 'title': 'M Evaluated variants', 'description': 'Number of called variants (millions)', 'namespace': 'GATK', 'min': 0, 'modify': lambda x: float(x) / 1000000.0 } headers['known_sites'] = { 'title': 'M Known sites', 'description': 'Number of known variants (millions)', 'namespace': 'GATK', 'min': 0, 'modify': lambda x: float(x) / 1000000.0 } headers['novel_sites'] = { 'title': 'M Novel sites', 'description': 'Number of novel variants (millions)', 'namespace': 'GATK', 'min': 0, 'modify': lambda x: float(x) / 1000000.0 } table_html = table.plot(data, headers, {'id': 'gatk_compare_overlap', 'table_title': 'GATK - Compare Overlap'}) return table_html
[ "def", "comp_overlap_table", "(", "data", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'comp_rate'", "]", "=", "{", "'title'", ":", "'Compare rate'", ",", "'description'", ":", "'Ratio of known variants found in the reference set.'", ",", "'na...
Build a table from the comp overlaps output.
[ "Build", "a", "table", "from", "the", "comp", "overlaps", "output", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/gatk/varianteval.py#L177-L222
224,592
ewels/MultiQC
multiqc/modules/gatk/varianteval.py
VariantEvalMixin.parse_gatk_varianteval
def parse_gatk_varianteval(self): """ Find GATK varianteval logs and parse their data """ self.gatk_varianteval = dict() for f in self.find_log_files('gatk/varianteval', filehandles=True): parsed_data = parse_single_report(f['f']) if len(parsed_data) > 0: if f['s_name'] in self.gatk_varianteval: log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) self.add_data_source(f, section='varianteval') self.gatk_varianteval[f['s_name']] = parsed_data # Filter to strip out ignored sample names self.gatk_varianteval = self.ignore_samples(self.gatk_varianteval) n_reports_found = len(self.gatk_varianteval) if n_reports_found > 0: log.info("Found {} VariantEval reports".format(n_reports_found)) # Write parsed report data to a file (restructure first) self.write_data_file(self.gatk_varianteval, 'multiqc_gatk_varianteval') # Get consensus TiTv references titv_ref = None for s_name in self.gatk_varianteval: if titv_ref is None: titv_ref = self.gatk_varianteval[s_name]['titv_reference'] elif titv_ref != self.gatk_varianteval[s_name]['titv_reference']: titv_ref = 'Multiple' break # General Stats Table varianteval_headers = dict() varianteval_headers['known_titv'] = { 'title': 'TiTV ratio (known)', 'description': "TiTV ratio from variants found in '{}'".format(titv_ref), 'min': 0, 'scale': 'Blues', 'shared_key': 'titv_ratio' } varianteval_headers['novel_titv'] = { 'title': 'TiTV ratio (novel)', 'description': "TiTV ratio from variants NOT found in '{}'".format(titv_ref), 'min': 0, 'scale': 'Blues', 'shared_key': 'titv_ratio' } self.general_stats_addcols(self.gatk_varianteval, varianteval_headers, 'GATK VariantEval') # Variant Counts plot self.add_section ( name = 'Variant Counts', anchor = 'gatk-count-variants', plot = count_variants_barplot(self.gatk_varianteval) ) # Compare Overlap Table self.add_section ( name = 'Compare Overlap', anchor = 'gatk-compare-overlap', plot = comp_overlap_table(self.gatk_varianteval) ) return n_reports_found
python
def parse_gatk_varianteval(self): self.gatk_varianteval = dict() for f in self.find_log_files('gatk/varianteval', filehandles=True): parsed_data = parse_single_report(f['f']) if len(parsed_data) > 0: if f['s_name'] in self.gatk_varianteval: log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name'])) self.add_data_source(f, section='varianteval') self.gatk_varianteval[f['s_name']] = parsed_data # Filter to strip out ignored sample names self.gatk_varianteval = self.ignore_samples(self.gatk_varianteval) n_reports_found = len(self.gatk_varianteval) if n_reports_found > 0: log.info("Found {} VariantEval reports".format(n_reports_found)) # Write parsed report data to a file (restructure first) self.write_data_file(self.gatk_varianteval, 'multiqc_gatk_varianteval') # Get consensus TiTv references titv_ref = None for s_name in self.gatk_varianteval: if titv_ref is None: titv_ref = self.gatk_varianteval[s_name]['titv_reference'] elif titv_ref != self.gatk_varianteval[s_name]['titv_reference']: titv_ref = 'Multiple' break # General Stats Table varianteval_headers = dict() varianteval_headers['known_titv'] = { 'title': 'TiTV ratio (known)', 'description': "TiTV ratio from variants found in '{}'".format(titv_ref), 'min': 0, 'scale': 'Blues', 'shared_key': 'titv_ratio' } varianteval_headers['novel_titv'] = { 'title': 'TiTV ratio (novel)', 'description': "TiTV ratio from variants NOT found in '{}'".format(titv_ref), 'min': 0, 'scale': 'Blues', 'shared_key': 'titv_ratio' } self.general_stats_addcols(self.gatk_varianteval, varianteval_headers, 'GATK VariantEval') # Variant Counts plot self.add_section ( name = 'Variant Counts', anchor = 'gatk-count-variants', plot = count_variants_barplot(self.gatk_varianteval) ) # Compare Overlap Table self.add_section ( name = 'Compare Overlap', anchor = 'gatk-compare-overlap', plot = comp_overlap_table(self.gatk_varianteval) ) return n_reports_found
[ "def", "parse_gatk_varianteval", "(", "self", ")", ":", "self", ".", "gatk_varianteval", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'gatk/varianteval'", ",", "filehandles", "=", "True", ")", ":", "parsed_data", "=", "parse_...
Find GATK varianteval logs and parse their data
[ "Find", "GATK", "varianteval", "logs", "and", "parse", "their", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/gatk/varianteval.py#L15-L78
224,593
ewels/MultiQC
multiqc/modules/sargasso/sargasso.py
MultiqcModule.parse_sargasso_logs
def parse_sargasso_logs(self, f): """ Parse the sargasso log file. """ species_name = list() items = list() header = list() is_first_line = True for l in f['f'].splitlines(): s = l.split(",") # Check that this actually is a Sargasso file if is_first_line and s[0]!='Sample': return None if len(s) < 7: continue if is_first_line: #prepare header is_first_line = False header = s for i in header[1:]: #find out what species included sname = i.split('-')[-1] if sname not in species_name: species_name.append(sname) #find out what is being counted kname = ("-".join(i.split('-')[-3:-1])) if kname not in items: items.append(kname) else: #start sample lines. sample_name = s.pop(0) chunk_by_species = [s[i:i + len(items)] for i in range(0, len(s), len(items))]; for idx,v in enumerate(chunk_by_species): #adding species name to the sample name for easy interpretation new_sample_name = '_'.join([sample_name,species_name[idx]]) # Clean up sample name new_sample_name = self.clean_s_name(new_sample_name, f['root']) if new_sample_name in self.sargasso_data.keys(): log.debug("Duplicate sample name found! Overwriting: {}".format(new_sample_name)) try: self.sargasso_data[new_sample_name] = dict(zip(items,map(int, v))) except ValueError: pass self.sargasso_keys = items for idx, f_name in enumerate(self.sargasso_data.keys()): # Reorganised parsed data for this sample # Collect total READ count number self.sargasso_data[f_name]['Total'] = 0; for key, value in list(self.sargasso_data[f_name].items()): # iter on both keys and values if key.endswith("Reads"): self.sargasso_data[f_name]['Total'] += value # Calculate the percent aligned if we can try: self.sargasso_data[f_name]['sargasso_percent_assigned'] = (float(self.sargasso_data[f_name]['Assigned-Reads'])/float(self.sargasso_data[f_name]['Total'])) * 100.0 except (KeyError, ZeroDivisionError): pass
python
def parse_sargasso_logs(self, f): species_name = list() items = list() header = list() is_first_line = True for l in f['f'].splitlines(): s = l.split(",") # Check that this actually is a Sargasso file if is_first_line and s[0]!='Sample': return None if len(s) < 7: continue if is_first_line: #prepare header is_first_line = False header = s for i in header[1:]: #find out what species included sname = i.split('-')[-1] if sname not in species_name: species_name.append(sname) #find out what is being counted kname = ("-".join(i.split('-')[-3:-1])) if kname not in items: items.append(kname) else: #start sample lines. sample_name = s.pop(0) chunk_by_species = [s[i:i + len(items)] for i in range(0, len(s), len(items))]; for idx,v in enumerate(chunk_by_species): #adding species name to the sample name for easy interpretation new_sample_name = '_'.join([sample_name,species_name[idx]]) # Clean up sample name new_sample_name = self.clean_s_name(new_sample_name, f['root']) if new_sample_name in self.sargasso_data.keys(): log.debug("Duplicate sample name found! Overwriting: {}".format(new_sample_name)) try: self.sargasso_data[new_sample_name] = dict(zip(items,map(int, v))) except ValueError: pass self.sargasso_keys = items for idx, f_name in enumerate(self.sargasso_data.keys()): # Reorganised parsed data for this sample # Collect total READ count number self.sargasso_data[f_name]['Total'] = 0; for key, value in list(self.sargasso_data[f_name].items()): # iter on both keys and values if key.endswith("Reads"): self.sargasso_data[f_name]['Total'] += value # Calculate the percent aligned if we can try: self.sargasso_data[f_name]['sargasso_percent_assigned'] = (float(self.sargasso_data[f_name]['Assigned-Reads'])/float(self.sargasso_data[f_name]['Total'])) * 100.0 except (KeyError, ZeroDivisionError): pass
[ "def", "parse_sargasso_logs", "(", "self", ",", "f", ")", ":", "species_name", "=", "list", "(", ")", "items", "=", "list", "(", ")", "header", "=", "list", "(", ")", "is_first_line", "=", "True", "for", "l", "in", "f", "[", "'f'", "]", ".", "split...
Parse the sargasso log file.
[ "Parse", "the", "sargasso", "log", "file", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/sargasso/sargasso.py#L55-L121
224,594
ewels/MultiQC
multiqc/modules/sargasso/sargasso.py
MultiqcModule.sargasso_stats_table
def sargasso_stats_table(self): """ Take the parsed stats from the sargasso report and add them to the basic stats table at the top of the report """ headers = OrderedDict() headers['sargasso_percent_assigned'] = { 'title': '% Assigned', 'description': 'Sargasso % Assigned reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn' } headers['Assigned-Reads'] = { 'title': '{} Assigned'.format(config.read_count_prefix), 'description': 'Sargasso 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.sargasso_data, headers)
python
def sargasso_stats_table(self): headers = OrderedDict() headers['sargasso_percent_assigned'] = { 'title': '% Assigned', 'description': 'Sargasso % Assigned reads', 'max': 100, 'min': 0, 'suffix': '%', 'scale': 'RdYlGn' } headers['Assigned-Reads'] = { 'title': '{} Assigned'.format(config.read_count_prefix), 'description': 'Sargasso 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.sargasso_data, headers)
[ "def", "sargasso_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'sargasso_percent_assigned'", "]", "=", "{", "'title'", ":", "'% Assigned'", ",", "'description'", ":", "'Sargasso % Assigned reads'", ",", "'max'", ":"...
Take the parsed stats from the sargasso report and add them to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "sargasso", "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/sargasso/sargasso.py#L124-L145
224,595
ewels/MultiQC
multiqc/modules/sargasso/sargasso.py
MultiqcModule.sargasso_chart
def sargasso_chart (self): """ Make the sargasso plot """ # Config for the plot config = { 'id': 'sargasso_assignment_plot', 'title': 'Sargasso: Assigned Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } #We only want to plot the READs at the moment return bargraph.plot(self.sargasso_data, [name for name in self.sargasso_keys if 'Reads' in name], config)
python
def sargasso_chart (self): # Config for the plot config = { 'id': 'sargasso_assignment_plot', 'title': 'Sargasso: Assigned Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } #We only want to plot the READs at the moment return bargraph.plot(self.sargasso_data, [name for name in self.sargasso_keys if 'Reads' in name], config)
[ "def", "sargasso_chart", "(", "self", ")", ":", "# Config for the plot", "config", "=", "{", "'id'", ":", "'sargasso_assignment_plot'", ",", "'title'", ":", "'Sargasso: Assigned Reads'", ",", "'ylab'", ":", "'# Reads'", ",", "'cpswitch_counts_label'", ":", "'Number of...
Make the sargasso plot
[ "Make", "the", "sargasso", "plot" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/sargasso/sargasso.py#L148-L160
224,596
ewels/MultiQC
multiqc/modules/bbmap/plot_aqhist.py
plot_aqhist
def plot_aqhist(samples, file_type, **plot_args): """ Create line graph plot of histogram data for BBMap 'aqhist' output. 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) columns_to_plot = { 'Counts': { 0: 'Read1', 2: 'Read2' }, 'Proportions': { 1: 'Read1', 3: 'Read2' } } plot_data = [] for column_type in columns_to_plot: plot_data.append( { sample+'.'+column_name: { x: samples[sample]['data'][x][column] if x in samples[sample]['data'] else 0 for x in all_x } for sample in samples for column, column_name in columns_to_plot[column_type].items() } ) plot_params = { 'id': 'bbmap-' + file_type + '_plot', 'title': 'BBTools: ' + plot_args['plot_title'], 'xmax': xmax, 'xlab': 'Quality score', 'data_labels': [ {'name': 'Count data', 'ylab': 'Read count'}, {'name': 'Proportion data', 'ylab': 'Proportion of reads'}, ] } plot_params.update(plot_args['plot_params']) plot = linegraph.plot( plot_data, plot_params ) return plot
python
def plot_aqhist(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) columns_to_plot = { 'Counts': { 0: 'Read1', 2: 'Read2' }, 'Proportions': { 1: 'Read1', 3: 'Read2' } } plot_data = [] for column_type in columns_to_plot: plot_data.append( { sample+'.'+column_name: { x: samples[sample]['data'][x][column] if x in samples[sample]['data'] else 0 for x in all_x } for sample in samples for column, column_name in columns_to_plot[column_type].items() } ) plot_params = { 'id': 'bbmap-' + file_type + '_plot', 'title': 'BBTools: ' + plot_args['plot_title'], 'xmax': xmax, 'xlab': 'Quality score', 'data_labels': [ {'name': 'Count data', 'ylab': 'Read count'}, {'name': 'Proportion data', 'ylab': 'Proportion of reads'}, ] } plot_params.update(plot_args['plot_params']) plot = linegraph.plot( plot_data, plot_params ) return plot
[ "def", "plot_aqhist", "(", "samples", ",", "file_type", ",", "*", "*", "plot_args", ")", ":", "sumy", "=", "sum", "(", "[", "int", "(", "samples", "[", "sample", "]", "[", "'data'", "]", "[", "x", "]", "[", "0", "]", ")", "for", "sample", "in", ...
Create line graph plot of histogram data for BBMap 'aqhist' output. The 'samples' parameter could be from the bbmap mod_data dictionary: samples = bbmap.MultiqcModule.mod_data[file_type]
[ "Create", "line", "graph", "plot", "of", "histogram", "data", "for", "BBMap", "aqhist", "output", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bbmap/plot_aqhist.py#L5-L70
224,597
ewels/MultiQC
multiqc/modules/vcftools/tstv_summary.py
TsTvSummaryMixin.parse_tstv_summary
def parse_tstv_summary(self): """ Create the HTML for the TsTv summary plot. """ self.vcftools_tstv_summary = dict() for f in self.find_log_files('vcftools/tstv_summary', filehandles=True): d = {} for line in f['f'].readlines()[1:]: # don't add the header line (first row) key = line.split()[0] # taking the first column (MODEL) as key val = int(line.split()[1]) # taking the second column (COUNT) as value d[key] = val self.vcftools_tstv_summary[f['s_name']] = d # Filter out ignored sample names self.vcftools_tstv_summary = self.ignore_samples(self.vcftools_tstv_summary) if len(self.vcftools_tstv_summary) == 0: return 0 # Specifying the categories of the bargraph keys = OrderedDict() keys = ['AC', 'AG', 'AT', 'CG', 'CT', 'GT', 'Ts', 'Tv'] pconfig = { 'id': 'vcftools_tstv_summary', 'title': 'VCFTools: TsTv Summary', 'ylab': 'Counts', } self.add_section( name = 'TsTv Summary', anchor = 'vcftools-tstv-summary', description = "Plot of `TSTV-SUMMARY` - count of different types of transition and transversion SNPs.", plot = bargraph.plot(self.vcftools_tstv_summary,keys,pconfig) ) return len(self.vcftools_tstv_summary)
python
def parse_tstv_summary(self): self.vcftools_tstv_summary = dict() for f in self.find_log_files('vcftools/tstv_summary', filehandles=True): d = {} for line in f['f'].readlines()[1:]: # don't add the header line (first row) key = line.split()[0] # taking the first column (MODEL) as key val = int(line.split()[1]) # taking the second column (COUNT) as value d[key] = val self.vcftools_tstv_summary[f['s_name']] = d # Filter out ignored sample names self.vcftools_tstv_summary = self.ignore_samples(self.vcftools_tstv_summary) if len(self.vcftools_tstv_summary) == 0: return 0 # Specifying the categories of the bargraph keys = OrderedDict() keys = ['AC', 'AG', 'AT', 'CG', 'CT', 'GT', 'Ts', 'Tv'] pconfig = { 'id': 'vcftools_tstv_summary', 'title': 'VCFTools: TsTv Summary', 'ylab': 'Counts', } self.add_section( name = 'TsTv Summary', anchor = 'vcftools-tstv-summary', description = "Plot of `TSTV-SUMMARY` - count of different types of transition and transversion SNPs.", plot = bargraph.plot(self.vcftools_tstv_summary,keys,pconfig) ) return len(self.vcftools_tstv_summary)
[ "def", "parse_tstv_summary", "(", "self", ")", ":", "self", ".", "vcftools_tstv_summary", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'vcftools/tstv_summary'", ",", "filehandles", "=", "True", ")", ":", "d", "=", "{", "}",...
Create the HTML for the TsTv summary plot.
[ "Create", "the", "HTML", "for", "the", "TsTv", "summary", "plot", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/vcftools/tstv_summary.py#L14-L49
224,598
ewels/MultiQC
multiqc/modules/homer/findpeaks.py
FindPeaksReportMixin.parse_homer_findpeaks
def parse_homer_findpeaks(self): """ Find HOMER findpeaks logs and parse their data """ self.homer_findpeaks = dict() for f in self.find_log_files('homer/findpeaks', filehandles=True): self.parse_findPeaks(f) # Filter to strip out ignored sample names self.homer_findpeaks = self.ignore_samples(self.homer_findpeaks) if len(self.homer_findpeaks) > 0: # Write parsed report data to a file self.write_data_file(self.homer_findpeaks, 'multiqc_homer_findpeaks') # General Stats Table stats_headers = OrderedDict() stats_headers['approximate_ip_efficiency'] = { 'title': '% Efficiency', 'description': 'Approximate IP efficiency', 'min': 0, 'max': 100, 'suffix': '%', 'scale': 'RdYlGn' } stats_headers['total_peaks'] = { 'title': 'Total Peaks', 'min': 0, 'format': '{:,.0f}', 'scale': 'GnBu' } stats_headers['expected_tags_per_peak'] = { 'title': 'Tags/Peak', 'description': 'Expected tags per peak', 'min': 0, 'format': '{:,.0f}', 'scale': 'PuRd' } self.general_stats_addcols(self.homer_findpeaks, stats_headers, 'HOMER findpeaks') return len(self.homer_findpeaks)
python
def parse_homer_findpeaks(self): self.homer_findpeaks = dict() for f in self.find_log_files('homer/findpeaks', filehandles=True): self.parse_findPeaks(f) # Filter to strip out ignored sample names self.homer_findpeaks = self.ignore_samples(self.homer_findpeaks) if len(self.homer_findpeaks) > 0: # Write parsed report data to a file self.write_data_file(self.homer_findpeaks, 'multiqc_homer_findpeaks') # General Stats Table stats_headers = OrderedDict() stats_headers['approximate_ip_efficiency'] = { 'title': '% Efficiency', 'description': 'Approximate IP efficiency', 'min': 0, 'max': 100, 'suffix': '%', 'scale': 'RdYlGn' } stats_headers['total_peaks'] = { 'title': 'Total Peaks', 'min': 0, 'format': '{:,.0f}', 'scale': 'GnBu' } stats_headers['expected_tags_per_peak'] = { 'title': 'Tags/Peak', 'description': 'Expected tags per peak', 'min': 0, 'format': '{:,.0f}', 'scale': 'PuRd' } self.general_stats_addcols(self.homer_findpeaks, stats_headers, 'HOMER findpeaks') return len(self.homer_findpeaks)
[ "def", "parse_homer_findpeaks", "(", "self", ")", ":", "self", ".", "homer_findpeaks", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'homer/findpeaks'", ",", "filehandles", "=", "True", ")", ":", "self", ".", "parse_findPeaks"...
Find HOMER findpeaks logs and parse their data
[ "Find", "HOMER", "findpeaks", "logs", "and", "parse", "their", "data" ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/findpeaks.py#L15-L55
224,599
ewels/MultiQC
multiqc/modules/homer/findpeaks.py
FindPeaksReportMixin.parse_findPeaks
def parse_findPeaks(self, f): """ Parse HOMER findPeaks file headers. """ parsed_data = dict() s_name = f['s_name'] for l in f['f']: # Start of data if l.strip() and not l.strip().startswith('#'): break # Automatically parse header lines by = symbol s = l[2:].split('=') if len(s) > 1: k = s[0].strip().replace(' ','_').lower() v = s[1].strip().replace('%','') try: parsed_data[k] = float(v) except ValueError: parsed_data[k] = v if k == 'tag_directory': s_name = self.clean_s_name(os.path.basename(v), os.path.dirname(v)) if len(parsed_data) > 0: if s_name in self.homer_findpeaks: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name)) self.add_data_source(f, s_name, section='findPeaks') self.homer_findpeaks[s_name] = parsed_data
python
def parse_findPeaks(self, f): parsed_data = dict() s_name = f['s_name'] for l in f['f']: # Start of data if l.strip() and not l.strip().startswith('#'): break # Automatically parse header lines by = symbol s = l[2:].split('=') if len(s) > 1: k = s[0].strip().replace(' ','_').lower() v = s[1].strip().replace('%','') try: parsed_data[k] = float(v) except ValueError: parsed_data[k] = v if k == 'tag_directory': s_name = self.clean_s_name(os.path.basename(v), os.path.dirname(v)) if len(parsed_data) > 0: if s_name in self.homer_findpeaks: log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name)) self.add_data_source(f, s_name, section='findPeaks') self.homer_findpeaks[s_name] = parsed_data
[ "def", "parse_findPeaks", "(", "self", ",", "f", ")", ":", "parsed_data", "=", "dict", "(", ")", "s_name", "=", "f", "[", "'s_name'", "]", "for", "l", "in", "f", "[", "'f'", "]", ":", "# Start of data", "if", "l", ".", "strip", "(", ")", "and", "...
Parse HOMER findPeaks file headers.
[ "Parse", "HOMER", "findPeaks", "file", "headers", "." ]
2037d6322b2554146a74efbf869156ad20d4c4ec
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/homer/findpeaks.py#L57-L81