repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
acorg/dark-matter
dark/reads.py
Reads.filter
def filter(self, **kwargs): """ Add a filter to this C{Reads} instance. @param kwargs: Keyword arguments, as accepted by C{ReadFilter}. @return: C{self}. """ readFilter = ReadFilter(**kwargs) self._filters.append(readFilter.filter) return self
python
def filter(self, **kwargs): """ Add a filter to this C{Reads} instance. @param kwargs: Keyword arguments, as accepted by C{ReadFilter}. @return: C{self}. """ readFilter = ReadFilter(**kwargs) self._filters.append(readFilter.filter) return self
[ "def", "filter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "readFilter", "=", "ReadFilter", "(", "*", "*", "kwargs", ")", "self", ".", "_filters", ".", "append", "(", "readFilter", ".", "filter", ")", "return", "self" ]
Add a filter to this C{Reads} instance. @param kwargs: Keyword arguments, as accepted by C{ReadFilter}. @return: C{self}.
[ "Add", "a", "filter", "to", "this", "C", "{", "Reads", "}", "instance", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L1354-L1363
acorg/dark-matter
dark/reads.py
Reads.summarizePosition
def summarizePosition(self, index): """ Compute residue counts at a specific sequence index. @param index: an C{int} index into the sequence. @return: A C{dict} with the count of too-short (excluded) sequences, and a Counter instance giving the residue counts. """ countAtPosition = Counter() excludedCount = 0 for read in self: try: countAtPosition[read.sequence[index]] += 1 except IndexError: excludedCount += 1 return { 'excludedCount': excludedCount, 'countAtPosition': countAtPosition }
python
def summarizePosition(self, index): """ Compute residue counts at a specific sequence index. @param index: an C{int} index into the sequence. @return: A C{dict} with the count of too-short (excluded) sequences, and a Counter instance giving the residue counts. """ countAtPosition = Counter() excludedCount = 0 for read in self: try: countAtPosition[read.sequence[index]] += 1 except IndexError: excludedCount += 1 return { 'excludedCount': excludedCount, 'countAtPosition': countAtPosition }
[ "def", "summarizePosition", "(", "self", ",", "index", ")", ":", "countAtPosition", "=", "Counter", "(", ")", "excludedCount", "=", "0", "for", "read", "in", "self", ":", "try", ":", "countAtPosition", "[", "read", ".", "sequence", "[", "index", "]", "]"...
Compute residue counts at a specific sequence index. @param index: an C{int} index into the sequence. @return: A C{dict} with the count of too-short (excluded) sequences, and a Counter instance giving the residue counts.
[ "Compute", "residue", "counts", "at", "a", "specific", "sequence", "index", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L1374-L1394
acorg/dark-matter
dark/reads.py
Reads.sitesMatching
def sitesMatching(self, targets, matchCase, any_): """ Find sites (i.e., sequence indices) that match a given set of target sequence bases. @param targets: A C{set} of sequence bases to look for. @param matchCase: If C{True}, case will be considered in matching. @param any_: If C{True}, return sites that match in any read. Else return sites that match in all reads. @return: A C{set} of 0-based sites that indicate where the target bases occur in our reads. An index will be in this set if any of our reads has any of the target bases in that location. """ # If case is unimportant, we convert everything (target bases and # sequences, as we read them) to lower case. if not matchCase: targets = set(map(str.lower, targets)) result = set() if any_ else None for read in self: sequence = read.sequence if matchCase else read.sequence.lower() matches = set(index for (index, base) in enumerate(sequence) if base in targets) if any_: result |= matches else: if result is None: result = matches else: result &= matches # We can exit early if we run out of possible sites. if not result: break # Make sure we don't return None. return result or set()
python
def sitesMatching(self, targets, matchCase, any_): """ Find sites (i.e., sequence indices) that match a given set of target sequence bases. @param targets: A C{set} of sequence bases to look for. @param matchCase: If C{True}, case will be considered in matching. @param any_: If C{True}, return sites that match in any read. Else return sites that match in all reads. @return: A C{set} of 0-based sites that indicate where the target bases occur in our reads. An index will be in this set if any of our reads has any of the target bases in that location. """ # If case is unimportant, we convert everything (target bases and # sequences, as we read them) to lower case. if not matchCase: targets = set(map(str.lower, targets)) result = set() if any_ else None for read in self: sequence = read.sequence if matchCase else read.sequence.lower() matches = set(index for (index, base) in enumerate(sequence) if base in targets) if any_: result |= matches else: if result is None: result = matches else: result &= matches # We can exit early if we run out of possible sites. if not result: break # Make sure we don't return None. return result or set()
[ "def", "sitesMatching", "(", "self", ",", "targets", ",", "matchCase", ",", "any_", ")", ":", "# If case is unimportant, we convert everything (target bases and", "# sequences, as we read them) to lower case.", "if", "not", "matchCase", ":", "targets", "=", "set", "(", "m...
Find sites (i.e., sequence indices) that match a given set of target sequence bases. @param targets: A C{set} of sequence bases to look for. @param matchCase: If C{True}, case will be considered in matching. @param any_: If C{True}, return sites that match in any read. Else return sites that match in all reads. @return: A C{set} of 0-based sites that indicate where the target bases occur in our reads. An index will be in this set if any of our reads has any of the target bases in that location.
[ "Find", "sites", "(", "i", ".", "e", ".", "sequence", "indices", ")", "that", "match", "a", "given", "set", "of", "target", "sequence", "bases", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L1396-L1431
kyegupov/py-unrar2
UnRAR2/__init__.py
condition2checker
def condition2checker(condition): """Converts different condition types to callback""" if isinstance(condition, string_types): def smatcher(info): return fnmatch.fnmatch(info.filename, condition) return smatcher elif isinstance(condition, (list, tuple)) and isinstance(condition[0], integer_types): def imatcher(info): return info.index in condition return imatcher elif callable(condition): return condition else: raise TypeError
python
def condition2checker(condition): """Converts different condition types to callback""" if isinstance(condition, string_types): def smatcher(info): return fnmatch.fnmatch(info.filename, condition) return smatcher elif isinstance(condition, (list, tuple)) and isinstance(condition[0], integer_types): def imatcher(info): return info.index in condition return imatcher elif callable(condition): return condition else: raise TypeError
[ "def", "condition2checker", "(", "condition", ")", ":", "if", "isinstance", "(", "condition", ",", "string_types", ")", ":", "def", "smatcher", "(", "info", ")", ":", "return", "fnmatch", ".", "fnmatch", "(", "info", ".", "filename", ",", "condition", ")",...
Converts different condition types to callback
[ "Converts", "different", "condition", "types", "to", "callback" ]
train
https://github.com/kyegupov/py-unrar2/blob/186a4c1feb9ef3d96a2331f8fb3ebf88036e15e5/UnRAR2/__init__.py#L177-L193
kyegupov/py-unrar2
UnRAR2/__init__.py
RarFile.read_files
def read_files(self, condition='*'): """Read specific files from archive into memory. If "condition" is a list of numbers, then return files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object and returns boolean True (extract) or False (skip). If "condition" is omitted, all files are returned. Returns list of tuples (RarInfo info, str contents) """ checker = condition2checker(condition) return RarFileImplementation.read_files(self, checker)
python
def read_files(self, condition='*'): """Read specific files from archive into memory. If "condition" is a list of numbers, then return files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object and returns boolean True (extract) or False (skip). If "condition" is omitted, all files are returned. Returns list of tuples (RarInfo info, str contents) """ checker = condition2checker(condition) return RarFileImplementation.read_files(self, checker)
[ "def", "read_files", "(", "self", ",", "condition", "=", "'*'", ")", ":", "checker", "=", "condition2checker", "(", "condition", ")", "return", "RarFileImplementation", ".", "read_files", "(", "self", ",", "checker", ")" ]
Read specific files from archive into memory. If "condition" is a list of numbers, then return files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object and returns boolean True (extract) or False (skip). If "condition" is omitted, all files are returned. Returns list of tuples (RarInfo info, str contents)
[ "Read", "specific", "files", "from", "archive", "into", "memory", ".", "If", "condition", "is", "a", "list", "of", "numbers", "then", "return", "files", "which", "have", "those", "positions", "in", "infolist", ".", "If", "condition", "is", "a", "string", "...
train
https://github.com/kyegupov/py-unrar2/blob/186a4c1feb9ef3d96a2331f8fb3ebf88036e15e5/UnRAR2/__init__.py#L137-L148
kyegupov/py-unrar2
UnRAR2/__init__.py
RarFile.extract
def extract(self, condition='*', path='.', withSubpath=True, overwrite=True): """Extract specific files from archive to disk. If "condition" is a list of numbers, then extract files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object and returns either boolean True (extract) or boolean False (skip). DEPRECATED: If "condition" callback returns string (only supported for Windows) - that string will be used as a new name to save the file under. If "condition" is omitted, all files are extracted. "path" is a directory to extract to "withSubpath" flag denotes whether files are extracted with their full path in the archive. "overwrite" flag denotes whether extracted files will overwrite old ones. Defaults to true. Returns list of RarInfos for extracted files.""" checker = condition2checker(condition) return RarFileImplementation.extract(self, checker, path, withSubpath, overwrite)
python
def extract(self, condition='*', path='.', withSubpath=True, overwrite=True): """Extract specific files from archive to disk. If "condition" is a list of numbers, then extract files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object and returns either boolean True (extract) or boolean False (skip). DEPRECATED: If "condition" callback returns string (only supported for Windows) - that string will be used as a new name to save the file under. If "condition" is omitted, all files are extracted. "path" is a directory to extract to "withSubpath" flag denotes whether files are extracted with their full path in the archive. "overwrite" flag denotes whether extracted files will overwrite old ones. Defaults to true. Returns list of RarInfos for extracted files.""" checker = condition2checker(condition) return RarFileImplementation.extract(self, checker, path, withSubpath, overwrite)
[ "def", "extract", "(", "self", ",", "condition", "=", "'*'", ",", "path", "=", "'.'", ",", "withSubpath", "=", "True", ",", "overwrite", "=", "True", ")", ":", "checker", "=", "condition2checker", "(", "condition", ")", "return", "RarFileImplementation", "...
Extract specific files from archive to disk. If "condition" is a list of numbers, then extract files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object and returns either boolean True (extract) or boolean False (skip). DEPRECATED: If "condition" callback returns string (only supported for Windows) - that string will be used as a new name to save the file under. If "condition" is omitted, all files are extracted. "path" is a directory to extract to "withSubpath" flag denotes whether files are extracted with their full path in the archive. "overwrite" flag denotes whether extracted files will overwrite old ones. Defaults to true. Returns list of RarInfos for extracted files.
[ "Extract", "specific", "files", "from", "archive", "to", "disk", ".", "If", "condition", "is", "a", "list", "of", "numbers", "then", "extract", "files", "which", "have", "those", "positions", "in", "infolist", ".", "If", "condition", "is", "a", "string", "...
train
https://github.com/kyegupov/py-unrar2/blob/186a4c1feb9ef3d96a2331f8fb3ebf88036e15e5/UnRAR2/__init__.py#L150-L169
flo-compbio/genometools
genometools/enrichment/analysis.py
GeneSetEnrichmentAnalysis.get_static_enrichment
def get_static_enrichment( self, genes: Iterable[str], pval_thresh: float, adjust_pval_thresh: bool = True, K_min: int = 3, gene_set_ids: Iterable[str] = None) -> StaticGSEResult: """Find enriched gene sets in a set of genes. Parameters ---------- genes : set of str The set of genes to test for gene set enrichment. pval_thresh : float The significance level (p-value threshold) to use in the analysis. adjust_pval_thresh : bool, optional Whether to adjust the p-value threshold using a Bonferroni correction. (Warning: This is a very conservative correction!) [True] K_min : int, optional The minimum number of gene set genes present in the analysis. [3] gene_set_ids : Iterable or None A list of gene set IDs to test. If ``None``, all gene sets are tested that meet the :attr:`K_min` criterion. Returns ------- list of `StaticGSEResult` A list of all significantly enriched gene sets. """ genes = set(genes) gene_set_coll = self._gene_set_coll gene_sets = self._gene_set_coll.gene_sets gene_memberships = self._gene_memberships sorted_genes = sorted(genes) # test only some terms? if gene_set_ids is not None: gs_indices = np.int64([self._gene_set_coll.index(id_) for id_ in gene_set_ids]) gene_sets = [gene_set_coll[id_] for id_ in gene_set_ids] # gene_set_coll = GeneSetCollection(gene_sets) gene_memberships = gene_memberships[:, gs_indices] # not a view! # determine K's K_vec = np.sum(gene_memberships, axis=0, dtype=np.int64) # exclude terms with too few genes sel = np.nonzero(K_vec >= K_min)[0] K_vec = K_vec[sel] gene_sets = [gene_sets[j] for j in sel] gene_memberships = gene_memberships[:, sel] # determine k's, ignoring unknown genes unknown = 0 sel = [] filtered_genes = [] logger.debug('Looking up indices for %d genes...', len(sorted_genes)) for i, g in enumerate(sorted_genes): try: idx = self._gene_indices[g] except KeyError: unknown += 1 else: sel.append(idx) filtered_genes.append(g) sel = np.int64(sel) gene_indices = np.int64(sel) # gene_memberships = gene_memberships[sel, :] k_vec = np.sum(gene_memberships[sel, :], axis=0, dtype=np.int64) if unknown > 0: logger.warn('%d / %d unknown genes (%.1f %%), will be ignored.', unknown, len(genes), 100 * (unknown / float(len(genes)))) # determine n and N n = len(filtered_genes) N, m = gene_memberships.shape logger.info('Conducting %d tests.', m) # correct p-value threshold, if specified final_pval_thresh = pval_thresh if adjust_pval_thresh: final_pval_thresh /= float(m) logger.info('Using Bonferroni-corrected p-value threshold: %.1e', final_pval_thresh) # calculate p-values and get significantly enriched gene sets enriched = [] logger.debug('N=%d, n=%d', N, n) sys.stdout.flush() genes = self._valid_genes for j in range(m): pval = hypergeom.sf(k_vec[j] - 1, N, K_vec[j], n) if pval <= final_pval_thresh: # found significant enrichment # sel_genes = [filtered_genes[i] for i in np.nonzero(gene_memberships[:, j])[0]] sel_genes = [genes[i] for i in np.nonzero(gene_memberships[gene_indices, j])[0]] enriched.append( StaticGSEResult(gene_sets[j], N, n, set(sel_genes), pval)) return enriched
python
def get_static_enrichment( self, genes: Iterable[str], pval_thresh: float, adjust_pval_thresh: bool = True, K_min: int = 3, gene_set_ids: Iterable[str] = None) -> StaticGSEResult: """Find enriched gene sets in a set of genes. Parameters ---------- genes : set of str The set of genes to test for gene set enrichment. pval_thresh : float The significance level (p-value threshold) to use in the analysis. adjust_pval_thresh : bool, optional Whether to adjust the p-value threshold using a Bonferroni correction. (Warning: This is a very conservative correction!) [True] K_min : int, optional The minimum number of gene set genes present in the analysis. [3] gene_set_ids : Iterable or None A list of gene set IDs to test. If ``None``, all gene sets are tested that meet the :attr:`K_min` criterion. Returns ------- list of `StaticGSEResult` A list of all significantly enriched gene sets. """ genes = set(genes) gene_set_coll = self._gene_set_coll gene_sets = self._gene_set_coll.gene_sets gene_memberships = self._gene_memberships sorted_genes = sorted(genes) # test only some terms? if gene_set_ids is not None: gs_indices = np.int64([self._gene_set_coll.index(id_) for id_ in gene_set_ids]) gene_sets = [gene_set_coll[id_] for id_ in gene_set_ids] # gene_set_coll = GeneSetCollection(gene_sets) gene_memberships = gene_memberships[:, gs_indices] # not a view! # determine K's K_vec = np.sum(gene_memberships, axis=0, dtype=np.int64) # exclude terms with too few genes sel = np.nonzero(K_vec >= K_min)[0] K_vec = K_vec[sel] gene_sets = [gene_sets[j] for j in sel] gene_memberships = gene_memberships[:, sel] # determine k's, ignoring unknown genes unknown = 0 sel = [] filtered_genes = [] logger.debug('Looking up indices for %d genes...', len(sorted_genes)) for i, g in enumerate(sorted_genes): try: idx = self._gene_indices[g] except KeyError: unknown += 1 else: sel.append(idx) filtered_genes.append(g) sel = np.int64(sel) gene_indices = np.int64(sel) # gene_memberships = gene_memberships[sel, :] k_vec = np.sum(gene_memberships[sel, :], axis=0, dtype=np.int64) if unknown > 0: logger.warn('%d / %d unknown genes (%.1f %%), will be ignored.', unknown, len(genes), 100 * (unknown / float(len(genes)))) # determine n and N n = len(filtered_genes) N, m = gene_memberships.shape logger.info('Conducting %d tests.', m) # correct p-value threshold, if specified final_pval_thresh = pval_thresh if adjust_pval_thresh: final_pval_thresh /= float(m) logger.info('Using Bonferroni-corrected p-value threshold: %.1e', final_pval_thresh) # calculate p-values and get significantly enriched gene sets enriched = [] logger.debug('N=%d, n=%d', N, n) sys.stdout.flush() genes = self._valid_genes for j in range(m): pval = hypergeom.sf(k_vec[j] - 1, N, K_vec[j], n) if pval <= final_pval_thresh: # found significant enrichment # sel_genes = [filtered_genes[i] for i in np.nonzero(gene_memberships[:, j])[0]] sel_genes = [genes[i] for i in np.nonzero(gene_memberships[gene_indices, j])[0]] enriched.append( StaticGSEResult(gene_sets[j], N, n, set(sel_genes), pval)) return enriched
[ "def", "get_static_enrichment", "(", "self", ",", "genes", ":", "Iterable", "[", "str", "]", ",", "pval_thresh", ":", "float", ",", "adjust_pval_thresh", ":", "bool", "=", "True", ",", "K_min", ":", "int", "=", "3", ",", "gene_set_ids", ":", "Iterable", ...
Find enriched gene sets in a set of genes. Parameters ---------- genes : set of str The set of genes to test for gene set enrichment. pval_thresh : float The significance level (p-value threshold) to use in the analysis. adjust_pval_thresh : bool, optional Whether to adjust the p-value threshold using a Bonferroni correction. (Warning: This is a very conservative correction!) [True] K_min : int, optional The minimum number of gene set genes present in the analysis. [3] gene_set_ids : Iterable or None A list of gene set IDs to test. If ``None``, all gene sets are tested that meet the :attr:`K_min` criterion. Returns ------- list of `StaticGSEResult` A list of all significantly enriched gene sets.
[ "Find", "enriched", "gene", "sets", "in", "a", "set", "of", "genes", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/enrichment/analysis.py#L126-L229
flo-compbio/genometools
genometools/enrichment/analysis.py
GeneSetEnrichmentAnalysis.get_rank_based_enrichment
def get_rank_based_enrichment( self, ranked_genes: List[str], pval_thresh: float = 0.05, X_frac: float = 0.25, X_min: int = 5, L: int = None, adjust_pval_thresh: bool = True, escore_pval_thresh: float = None, exact_pval: str = 'always', gene_set_ids: List[str] = None, table: np.ndarray = None) -> RankBasedGSEResult: """Test for gene set enrichment at the top of a ranked list of genes. This function uses the XL-mHG test to identify enriched gene sets. This function also calculates XL-mHG E-scores for the enriched gene sets, using ``escore_pval_thresh`` as the p-value threshold "psi". Parameters ---------- ranked_gene_ids : list of str The ranked list of gene IDs. pval_thresh : float, optional The p-value threshold used to determine significance. See also ``adjust_pval_thresh``. [0.05] X_frac : float, optional The min. fraction of genes from a gene set required for enrichment. [0.25] X_min : int, optional The min. no. of genes from a gene set required for enrichment. [5] L : int, optional The lowest cutoff to test for enrichment. If ``None``, int(0.25*(no. of genes)) will be used. [None] adjust_pval_thresh : bool, optional Whether to adjust the p-value thershold for multiple testing, using the Bonferroni method. [True] escore_pval_thresh : float or None, optional The "psi" p-value threshold used in calculating E-scores. If ``None``, will be set to p-value threshold. [None] exact_pval : str Choices are: "always", "if_significant", "if_necessary". Parameter will be passed to `xlmhg.get_xlmhg_test_result`. ["always"] gene_set_ids : list of str or None, optional A list of gene set IDs to specify which gene sets should be tested for enrichment. If ``None``, all gene sets will be tested. [None] table : 2-dim numpy.ndarray of type numpy.longdouble or None, optional The dynamic programming table used by the algorithm for calculating XL-mHG p-values. Passing this avoids memory re-allocation when calling this function repetitively. [None] Returns ------- list of `RankBasedGSEResult` A list of all significantly enriched gene sets. """ # make sure X_frac is a float (e.g., if specified as 0) X_frac = float(X_frac) if table is not None: if not np.issubdtype(table.dtype, np.longdouble): raise TypeError('The provided array for storing the dynamic ' 'programming table must be of type ' '"longdouble"!') if L is None: L = int(len(ranked_genes)/4.0) gene_set_coll = self._gene_set_coll gene_memberships = self._gene_memberships # postpone this if escore_pval_thresh is None: # if no separate E-score p-value threshold is specified, use the # p-value threshold (this results in conservative E-scores) logger.warning('No E-score p-value threshold supplied. ' 'The E-score p-value threshold will be set to the' 'global significance threshold. This will result ' 'in conservative E-scores.') # test only some terms? if gene_set_ids is not None: gs_indices = np.int64([self._gene_set_coll.index(id_) for id_ in gene_set_ids]) gene_sets = [gene_set_coll[id_] for id_ in gene_set_ids] gene_set_coll = GeneSetCollection(gene_sets) gene_memberships = gene_memberships[:, gs_indices] # not a view! # reorder rows in annotation matrix to match the given gene ranking # also exclude genes not in the ranking unknown = 0 L_adj = L sel = [] filtered_genes = [] logger.debug('Looking up indices for %d genes...' % len(ranked_genes)) for i, g in enumerate(ranked_genes): try: idx = self._gene_indices[g] except KeyError: unknown += 1 # adjust L if the gene was above the original L cutoff if i < L: L_adj -= 1 else: sel.append(idx) filtered_genes.append(g) sel = np.int64(sel) logger.debug('Adjusted L: %d', L_adj) # the following also copies the data (not a view) gene_memberships = gene_memberships[sel, :] N, m = gene_memberships.shape if unknown > 0: # Some genes in the ranked list were unknown (i.e., not present in # the specified genome). logger.warn('%d / %d unknown genes (%.1f %%), will be ignored.', unknown, len(ranked_genes), 100 * (unknown / float(len(ranked_genes)))) # Determine the number of gene set genes above the L'th cutoff, # for all gene sets. This quantity is useful, because we don't need # to perform any more work for gene sets that have less than X genes # above the cutoff. k_above_L = np.sum(gene_memberships[:L_adj, :], axis=0, dtype=np.int64) # Determine the number of genes below the L'th cutoff, for all gene # sets. k_below_L = np.sum(gene_memberships[L_adj:, :], axis=0, dtype=np.int64) # Determine the total number K of genes in each gene set that are # present in the ranked list (this is equal to k_above_L + k_below_L) K_vec = k_above_L + k_below_L # Determine the largest K across all gene sets. K_max = np.amax(K_vec) # Determine X for all gene sets. X = np.amax( np.c_[np.tile(X_min, m), np.int64(np.ceil(X_frac * K_vec))], axis=1) # Determine the number of tests (we do not conduct a test if the # total number of gene set genes in the ranked list is below X). num_tests = np.sum(K_vec-X >= 0) logger.info('Conducting %d tests.', num_tests) # determine Bonferroni-corrected p-value, if desired final_pval_thresh = pval_thresh if adjust_pval_thresh and num_tests > 0: final_pval_thresh /= float(num_tests) logger.info('Using Bonferroni-corrected p-value threshold: %.1e', final_pval_thresh) if escore_pval_thresh is None: escore_pval_thresh = final_pval_thresh elif escore_pval_thresh < final_pval_thresh: logger.warning('The E-score p-value threshold is smaller than ' 'the p-value threshold. Setting E-score p-value ' 'threshold to the p-value threshold.') escore_pval_thresh = final_pval_thresh # Prepare the matrix that holds the dynamic programming table for # the calculation of the XL-mHG p-value. if table is None: table = np.empty((K_max+1, N+1), dtype=np.longdouble) else: if table.shape[0] < K_max+1 or table.shape[1] < N+1: raise ValueError( 'The supplied array is too small (%d x %d) to hold the ' 'entire dynamic programming table. The required size is' '%d x %d (rows x columns).' % (table.shape[0], table.shape[1], K_max+1, N+1)) # find enriched GO terms # logger.info('Testing %d gene sets for enrichment...', m) logger.debug('(N=%d, X_frac=%.2f, X_min=%d, L=%d; K_max=%d)', len(ranked_genes), X_frac, X_min, L, K_max) enriched = [] num_tests = 0 # number of tests conducted for j in range(m): # determine gene set-specific value for X X = max(X_min, int(ceil(X_frac * float(K_vec[j])))) # Determine significance of gene set enrichment using the XL-mHG # test (only if there are at least X gene set genes in the list). if K_vec[j] >= X: num_tests += 1 # We only need to perform the XL-mHG test if there are enough # gene set genes above the L'th cutoff (otherwise, pval = 1.0). if k_above_L[j] >= X: # perform test # Determine the ranks of the gene set genes in the # ranked list. indices = np.uint16(np.nonzero(gene_memberships[:, j])[0]) res = xlmhg.get_xlmhg_test_result( N, indices, X, L, pval_thresh=final_pval_thresh, escore_pval_thresh=escore_pval_thresh, exact_pval=exact_pval, table=table) # check if gene set is significantly enriched if res.pval <= final_pval_thresh: # generate RankedGSEResult ind_genes = [ranked_genes[i] for i in indices] gse_result = RankBasedGSEResult( gene_set_coll[j], N, indices, ind_genes, X, L, res.stat, res.cutoff, res.pval, escore_pval_thresh=escore_pval_thresh ) enriched.append(gse_result) # report results q = len(enriched) ignored = m - num_tests if ignored > 0: logger.debug('%d / %d gene sets (%.1f%%) had less than X genes ' 'annotated with them and were ignored.', ignored, m, 100 * (ignored / float(m))) logger.info('%d / %d gene sets were found to be significantly ' 'enriched (p-value <= %.1e).', q, m, final_pval_thresh) return enriched
python
def get_rank_based_enrichment( self, ranked_genes: List[str], pval_thresh: float = 0.05, X_frac: float = 0.25, X_min: int = 5, L: int = None, adjust_pval_thresh: bool = True, escore_pval_thresh: float = None, exact_pval: str = 'always', gene_set_ids: List[str] = None, table: np.ndarray = None) -> RankBasedGSEResult: """Test for gene set enrichment at the top of a ranked list of genes. This function uses the XL-mHG test to identify enriched gene sets. This function also calculates XL-mHG E-scores for the enriched gene sets, using ``escore_pval_thresh`` as the p-value threshold "psi". Parameters ---------- ranked_gene_ids : list of str The ranked list of gene IDs. pval_thresh : float, optional The p-value threshold used to determine significance. See also ``adjust_pval_thresh``. [0.05] X_frac : float, optional The min. fraction of genes from a gene set required for enrichment. [0.25] X_min : int, optional The min. no. of genes from a gene set required for enrichment. [5] L : int, optional The lowest cutoff to test for enrichment. If ``None``, int(0.25*(no. of genes)) will be used. [None] adjust_pval_thresh : bool, optional Whether to adjust the p-value thershold for multiple testing, using the Bonferroni method. [True] escore_pval_thresh : float or None, optional The "psi" p-value threshold used in calculating E-scores. If ``None``, will be set to p-value threshold. [None] exact_pval : str Choices are: "always", "if_significant", "if_necessary". Parameter will be passed to `xlmhg.get_xlmhg_test_result`. ["always"] gene_set_ids : list of str or None, optional A list of gene set IDs to specify which gene sets should be tested for enrichment. If ``None``, all gene sets will be tested. [None] table : 2-dim numpy.ndarray of type numpy.longdouble or None, optional The dynamic programming table used by the algorithm for calculating XL-mHG p-values. Passing this avoids memory re-allocation when calling this function repetitively. [None] Returns ------- list of `RankBasedGSEResult` A list of all significantly enriched gene sets. """ # make sure X_frac is a float (e.g., if specified as 0) X_frac = float(X_frac) if table is not None: if not np.issubdtype(table.dtype, np.longdouble): raise TypeError('The provided array for storing the dynamic ' 'programming table must be of type ' '"longdouble"!') if L is None: L = int(len(ranked_genes)/4.0) gene_set_coll = self._gene_set_coll gene_memberships = self._gene_memberships # postpone this if escore_pval_thresh is None: # if no separate E-score p-value threshold is specified, use the # p-value threshold (this results in conservative E-scores) logger.warning('No E-score p-value threshold supplied. ' 'The E-score p-value threshold will be set to the' 'global significance threshold. This will result ' 'in conservative E-scores.') # test only some terms? if gene_set_ids is not None: gs_indices = np.int64([self._gene_set_coll.index(id_) for id_ in gene_set_ids]) gene_sets = [gene_set_coll[id_] for id_ in gene_set_ids] gene_set_coll = GeneSetCollection(gene_sets) gene_memberships = gene_memberships[:, gs_indices] # not a view! # reorder rows in annotation matrix to match the given gene ranking # also exclude genes not in the ranking unknown = 0 L_adj = L sel = [] filtered_genes = [] logger.debug('Looking up indices for %d genes...' % len(ranked_genes)) for i, g in enumerate(ranked_genes): try: idx = self._gene_indices[g] except KeyError: unknown += 1 # adjust L if the gene was above the original L cutoff if i < L: L_adj -= 1 else: sel.append(idx) filtered_genes.append(g) sel = np.int64(sel) logger.debug('Adjusted L: %d', L_adj) # the following also copies the data (not a view) gene_memberships = gene_memberships[sel, :] N, m = gene_memberships.shape if unknown > 0: # Some genes in the ranked list were unknown (i.e., not present in # the specified genome). logger.warn('%d / %d unknown genes (%.1f %%), will be ignored.', unknown, len(ranked_genes), 100 * (unknown / float(len(ranked_genes)))) # Determine the number of gene set genes above the L'th cutoff, # for all gene sets. This quantity is useful, because we don't need # to perform any more work for gene sets that have less than X genes # above the cutoff. k_above_L = np.sum(gene_memberships[:L_adj, :], axis=0, dtype=np.int64) # Determine the number of genes below the L'th cutoff, for all gene # sets. k_below_L = np.sum(gene_memberships[L_adj:, :], axis=0, dtype=np.int64) # Determine the total number K of genes in each gene set that are # present in the ranked list (this is equal to k_above_L + k_below_L) K_vec = k_above_L + k_below_L # Determine the largest K across all gene sets. K_max = np.amax(K_vec) # Determine X for all gene sets. X = np.amax( np.c_[np.tile(X_min, m), np.int64(np.ceil(X_frac * K_vec))], axis=1) # Determine the number of tests (we do not conduct a test if the # total number of gene set genes in the ranked list is below X). num_tests = np.sum(K_vec-X >= 0) logger.info('Conducting %d tests.', num_tests) # determine Bonferroni-corrected p-value, if desired final_pval_thresh = pval_thresh if adjust_pval_thresh and num_tests > 0: final_pval_thresh /= float(num_tests) logger.info('Using Bonferroni-corrected p-value threshold: %.1e', final_pval_thresh) if escore_pval_thresh is None: escore_pval_thresh = final_pval_thresh elif escore_pval_thresh < final_pval_thresh: logger.warning('The E-score p-value threshold is smaller than ' 'the p-value threshold. Setting E-score p-value ' 'threshold to the p-value threshold.') escore_pval_thresh = final_pval_thresh # Prepare the matrix that holds the dynamic programming table for # the calculation of the XL-mHG p-value. if table is None: table = np.empty((K_max+1, N+1), dtype=np.longdouble) else: if table.shape[0] < K_max+1 or table.shape[1] < N+1: raise ValueError( 'The supplied array is too small (%d x %d) to hold the ' 'entire dynamic programming table. The required size is' '%d x %d (rows x columns).' % (table.shape[0], table.shape[1], K_max+1, N+1)) # find enriched GO terms # logger.info('Testing %d gene sets for enrichment...', m) logger.debug('(N=%d, X_frac=%.2f, X_min=%d, L=%d; K_max=%d)', len(ranked_genes), X_frac, X_min, L, K_max) enriched = [] num_tests = 0 # number of tests conducted for j in range(m): # determine gene set-specific value for X X = max(X_min, int(ceil(X_frac * float(K_vec[j])))) # Determine significance of gene set enrichment using the XL-mHG # test (only if there are at least X gene set genes in the list). if K_vec[j] >= X: num_tests += 1 # We only need to perform the XL-mHG test if there are enough # gene set genes above the L'th cutoff (otherwise, pval = 1.0). if k_above_L[j] >= X: # perform test # Determine the ranks of the gene set genes in the # ranked list. indices = np.uint16(np.nonzero(gene_memberships[:, j])[0]) res = xlmhg.get_xlmhg_test_result( N, indices, X, L, pval_thresh=final_pval_thresh, escore_pval_thresh=escore_pval_thresh, exact_pval=exact_pval, table=table) # check if gene set is significantly enriched if res.pval <= final_pval_thresh: # generate RankedGSEResult ind_genes = [ranked_genes[i] for i in indices] gse_result = RankBasedGSEResult( gene_set_coll[j], N, indices, ind_genes, X, L, res.stat, res.cutoff, res.pval, escore_pval_thresh=escore_pval_thresh ) enriched.append(gse_result) # report results q = len(enriched) ignored = m - num_tests if ignored > 0: logger.debug('%d / %d gene sets (%.1f%%) had less than X genes ' 'annotated with them and were ignored.', ignored, m, 100 * (ignored / float(m))) logger.info('%d / %d gene sets were found to be significantly ' 'enriched (p-value <= %.1e).', q, m, final_pval_thresh) return enriched
[ "def", "get_rank_based_enrichment", "(", "self", ",", "ranked_genes", ":", "List", "[", "str", "]", ",", "pval_thresh", ":", "float", "=", "0.05", ",", "X_frac", ":", "float", "=", "0.25", ",", "X_min", ":", "int", "=", "5", ",", "L", ":", "int", "="...
Test for gene set enrichment at the top of a ranked list of genes. This function uses the XL-mHG test to identify enriched gene sets. This function also calculates XL-mHG E-scores for the enriched gene sets, using ``escore_pval_thresh`` as the p-value threshold "psi". Parameters ---------- ranked_gene_ids : list of str The ranked list of gene IDs. pval_thresh : float, optional The p-value threshold used to determine significance. See also ``adjust_pval_thresh``. [0.05] X_frac : float, optional The min. fraction of genes from a gene set required for enrichment. [0.25] X_min : int, optional The min. no. of genes from a gene set required for enrichment. [5] L : int, optional The lowest cutoff to test for enrichment. If ``None``, int(0.25*(no. of genes)) will be used. [None] adjust_pval_thresh : bool, optional Whether to adjust the p-value thershold for multiple testing, using the Bonferroni method. [True] escore_pval_thresh : float or None, optional The "psi" p-value threshold used in calculating E-scores. If ``None``, will be set to p-value threshold. [None] exact_pval : str Choices are: "always", "if_significant", "if_necessary". Parameter will be passed to `xlmhg.get_xlmhg_test_result`. ["always"] gene_set_ids : list of str or None, optional A list of gene set IDs to specify which gene sets should be tested for enrichment. If ``None``, all gene sets will be tested. [None] table : 2-dim numpy.ndarray of type numpy.longdouble or None, optional The dynamic programming table used by the algorithm for calculating XL-mHG p-values. Passing this avoids memory re-allocation when calling this function repetitively. [None] Returns ------- list of `RankBasedGSEResult` A list of all significantly enriched gene sets.
[ "Test", "for", "gene", "set", "enrichment", "at", "the", "top", "of", "a", "ranked", "list", "of", "genes", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/enrichment/analysis.py#L232-L455
flo-compbio/genometools
genometools/gcloud/auth.py
authenticate_storage
def authenticate_storage(client_secrets, read_only=False): """Authenticates a service account for reading and/or writing on a bucket. TODO: docstring""" if read_only: scopes = ['https://www.googleapis.com/auth/devstorage.read_only'] else: scopes = ['https://www.googleapis.com/auth/devstorage.read_write'] credentials = service_account.Credentials.from_service_account_info( client_secrets) scoped_credentials = credentials.with_scopes(scopes) return scoped_credentials
python
def authenticate_storage(client_secrets, read_only=False): """Authenticates a service account for reading and/or writing on a bucket. TODO: docstring""" if read_only: scopes = ['https://www.googleapis.com/auth/devstorage.read_only'] else: scopes = ['https://www.googleapis.com/auth/devstorage.read_write'] credentials = service_account.Credentials.from_service_account_info( client_secrets) scoped_credentials = credentials.with_scopes(scopes) return scoped_credentials
[ "def", "authenticate_storage", "(", "client_secrets", ",", "read_only", "=", "False", ")", ":", "if", "read_only", ":", "scopes", "=", "[", "'https://www.googleapis.com/auth/devstorage.read_only'", "]", "else", ":", "scopes", "=", "[", "'https://www.googleapis.com/auth/...
Authenticates a service account for reading and/or writing on a bucket. TODO: docstring
[ "Authenticates", "a", "service", "account", "for", "reading", "and", "/", "or", "writing", "on", "a", "bucket", ".", "TODO", ":", "docstring" ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/auth.py#L14-L28
flo-compbio/genometools
genometools/gcloud/auth.py
authenticate_compute
def authenticate_compute(client_secrets): """Authenticates a service account for the compute engine. TODO: docstring""" scopes = ['https://www.googleapis.com/auth/compute'] credentials = ServiceAccountCredentials.from_json_keyfile_dict( client_secrets, scopes=scopes) return credentials
python
def authenticate_compute(client_secrets): """Authenticates a service account for the compute engine. TODO: docstring""" scopes = ['https://www.googleapis.com/auth/compute'] credentials = ServiceAccountCredentials.from_json_keyfile_dict( client_secrets, scopes=scopes) return credentials
[ "def", "authenticate_compute", "(", "client_secrets", ")", ":", "scopes", "=", "[", "'https://www.googleapis.com/auth/compute'", "]", "credentials", "=", "ServiceAccountCredentials", ".", "from_json_keyfile_dict", "(", "client_secrets", ",", "scopes", "=", "scopes", ")", ...
Authenticates a service account for the compute engine. TODO: docstring
[ "Authenticates", "a", "service", "account", "for", "the", "compute", "engine", ".", "TODO", ":", "docstring" ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/auth.py#L31-L40
flo-compbio/genometools
genometools/ensembl/cli/extract_protein_coding_gene_ids.py
main
def main(args=None): """Extract Ensembl IDs and store in tab-delimited text file. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module. Returns ------- int Exit code (0 if no error occurred). """ if args is None: # parse command-line arguments parser = get_argument_parser() args = parser.parse_args() input_file = args.annotation_file output_file = args.output_file species = args.species chrom_pat = args.chromosome_pattern field_name = args.field_name log_file = args.log_file quiet = args.quiet verbose = args.verbose # configure logger log_stream = sys.stdout if output_file == '-': # if we print output to stdout, redirect log messages to stderr log_stream = sys.stderr logger = misc.get_logger(log_stream = log_stream, log_file = log_file, quiet = quiet, verbose = verbose) if chrom_pat is None: chrom_pat = re.compile(ensembl.SPECIES_CHROMPAT[species]) else: chrom_pat = re.compile(chrom_pat) logger.info('Regular expression used for filtering chromosome names: "%s"', chrom_pat.pattern) # for statistics types = Counter() sources = Counter() # primary information genes = Counter() gene_chroms = dict() gene_ids = dict() # secondary information genes2 = Counter() polymorphic = set() # list of chromosomes chromosomes = set() excluded_chromosomes = set() transcripts = {} gene_id = None gene_name = None i = 0 missing = 0 logger.info('Parsing data...') if input_file == '-': input_file = None with misc.smart_open_read(input_file, mode = 'rb', try_gzip = True) as fh: #if i >= 500000: break reader = csv.reader(fh, dialect = 'excel-tab') for l in reader: i += 1 #if i % int(1e5) == 0: # print '\r%d...' %(i), ; sys.stdout.flush() # report progress if len(l) > 1 and l[2] == field_name: attr = parse_attributes(l[8]) type_ = attr['gene_biotype'] if type_ not in ['protein_coding', 'polymorphic_pseudogene']: continue chrom = l[0] # test whether chromosome is valid m = chrom_pat.match(chrom) if m is None: excluded_chromosomes.add(chrom) continue chromosomes.add(m.group()) source = l[1] gene_id = attr['gene_id'] try: gene_name = attr['gene_name'] except KeyError as e: missing += 1 continue if gene_id in genes: if genes[gene_id] != gene_name: raise ValueError('Ensembl ID "%s" ' %(gene_id) + 'associated with multiple gene symbols.') else: genes[gene_id] = gene_name logger.info('Done! (Parsed %d lines.)', i) logger.info('Excluded %d chromosomes:', len(excluded_chromosomes)) logger.info(', '.join(sorted(excluded_chromosomes))) n = len(genes) m = len(set(genes.values())) logger.info('No. of chromosomes: %d', len(chromosomes)) logger.info('No. of genes IDs: %d', n) logger.info('No. of gene names: %d', m) with misc.smart_open_write(output_file) as ofh: writer = csv.writer(ofh, dialect = 'excel-tab', lineterminator = os.linesep, quoting = csv.QUOTE_NONE) for g in sorted(genes.keys()): writer.writerow([g, genes[g]]) return 0
python
def main(args=None): """Extract Ensembl IDs and store in tab-delimited text file. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module. Returns ------- int Exit code (0 if no error occurred). """ if args is None: # parse command-line arguments parser = get_argument_parser() args = parser.parse_args() input_file = args.annotation_file output_file = args.output_file species = args.species chrom_pat = args.chromosome_pattern field_name = args.field_name log_file = args.log_file quiet = args.quiet verbose = args.verbose # configure logger log_stream = sys.stdout if output_file == '-': # if we print output to stdout, redirect log messages to stderr log_stream = sys.stderr logger = misc.get_logger(log_stream = log_stream, log_file = log_file, quiet = quiet, verbose = verbose) if chrom_pat is None: chrom_pat = re.compile(ensembl.SPECIES_CHROMPAT[species]) else: chrom_pat = re.compile(chrom_pat) logger.info('Regular expression used for filtering chromosome names: "%s"', chrom_pat.pattern) # for statistics types = Counter() sources = Counter() # primary information genes = Counter() gene_chroms = dict() gene_ids = dict() # secondary information genes2 = Counter() polymorphic = set() # list of chromosomes chromosomes = set() excluded_chromosomes = set() transcripts = {} gene_id = None gene_name = None i = 0 missing = 0 logger.info('Parsing data...') if input_file == '-': input_file = None with misc.smart_open_read(input_file, mode = 'rb', try_gzip = True) as fh: #if i >= 500000: break reader = csv.reader(fh, dialect = 'excel-tab') for l in reader: i += 1 #if i % int(1e5) == 0: # print '\r%d...' %(i), ; sys.stdout.flush() # report progress if len(l) > 1 and l[2] == field_name: attr = parse_attributes(l[8]) type_ = attr['gene_biotype'] if type_ not in ['protein_coding', 'polymorphic_pseudogene']: continue chrom = l[0] # test whether chromosome is valid m = chrom_pat.match(chrom) if m is None: excluded_chromosomes.add(chrom) continue chromosomes.add(m.group()) source = l[1] gene_id = attr['gene_id'] try: gene_name = attr['gene_name'] except KeyError as e: missing += 1 continue if gene_id in genes: if genes[gene_id] != gene_name: raise ValueError('Ensembl ID "%s" ' %(gene_id) + 'associated with multiple gene symbols.') else: genes[gene_id] = gene_name logger.info('Done! (Parsed %d lines.)', i) logger.info('Excluded %d chromosomes:', len(excluded_chromosomes)) logger.info(', '.join(sorted(excluded_chromosomes))) n = len(genes) m = len(set(genes.values())) logger.info('No. of chromosomes: %d', len(chromosomes)) logger.info('No. of genes IDs: %d', n) logger.info('No. of gene names: %d', m) with misc.smart_open_write(output_file) as ofh: writer = csv.writer(ofh, dialect = 'excel-tab', lineterminator = os.linesep, quoting = csv.QUOTE_NONE) for g in sorted(genes.keys()): writer.writerow([g, genes[g]]) return 0
[ "def", "main", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "# parse command-line arguments", "parser", "=", "get_argument_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "input_file", "=", "args", ".", "annot...
Extract Ensembl IDs and store in tab-delimited text file. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module. Returns ------- int Exit code (0 if no error occurred).
[ "Extract", "Ensembl", "IDs", "and", "store", "in", "tab", "-", "delimited", "text", "file", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ensembl/cli/extract_protein_coding_gene_ids.py#L53-L184
cebel/pyuniprot
src/pyuniprot/manager/database.py
get_connection_string
def get_connection_string(connection=None): """return SQLAlchemy connection string if it is set :param connection: get the SQLAlchemy connection string #TODO :rtype: str """ if not connection: config = configparser.ConfigParser() cfp = defaults.config_file_path if os.path.exists(cfp): log.info('fetch database configuration from %s', cfp) config.read(cfp) connection = config['database']['sqlalchemy_connection_string'] log.info('load connection string from %s: %s', cfp, connection) else: with open(cfp, 'w') as config_file: connection = defaults.sqlalchemy_connection_string_default config['database'] = {'sqlalchemy_connection_string': connection} config.write(config_file) log.info('create configuration file %s', cfp) return connection
python
def get_connection_string(connection=None): """return SQLAlchemy connection string if it is set :param connection: get the SQLAlchemy connection string #TODO :rtype: str """ if not connection: config = configparser.ConfigParser() cfp = defaults.config_file_path if os.path.exists(cfp): log.info('fetch database configuration from %s', cfp) config.read(cfp) connection = config['database']['sqlalchemy_connection_string'] log.info('load connection string from %s: %s', cfp, connection) else: with open(cfp, 'w') as config_file: connection = defaults.sqlalchemy_connection_string_default config['database'] = {'sqlalchemy_connection_string': connection} config.write(config_file) log.info('create configuration file %s', cfp) return connection
[ "def", "get_connection_string", "(", "connection", "=", "None", ")", ":", "if", "not", "connection", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "cfp", "=", "defaults", ".", "config_file_path", "if", "os", ".", "path", ".", "exists", ...
return SQLAlchemy connection string if it is set :param connection: get the SQLAlchemy connection string #TODO :rtype: str
[ "return", "SQLAlchemy", "connection", "string", "if", "it", "is", "set" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L48-L69
cebel/pyuniprot
src/pyuniprot/manager/database.py
update
def update(connection=None, urls=None, force_download=False, taxids=None, silent=False): """Updates CTD database :param urls: list of urls to download :type urls: iterable :param connection: custom database connection string :type connection: str :param force_download: force method to download :type force_download: bool :param int,list,tuple taxids: int or iterable of NCBI taxonomy identifiers (default is None = load all) """ if isinstance(taxids, int): taxids = (taxids,) db = DbManager(connection) db.db_import_xml(urls, force_download, taxids, silent) db.session.close()
python
def update(connection=None, urls=None, force_download=False, taxids=None, silent=False): """Updates CTD database :param urls: list of urls to download :type urls: iterable :param connection: custom database connection string :type connection: str :param force_download: force method to download :type force_download: bool :param int,list,tuple taxids: int or iterable of NCBI taxonomy identifiers (default is None = load all) """ if isinstance(taxids, int): taxids = (taxids,) db = DbManager(connection) db.db_import_xml(urls, force_download, taxids, silent) db.session.close()
[ "def", "update", "(", "connection", "=", "None", ",", "urls", "=", "None", ",", "force_download", "=", "False", ",", "taxids", "=", "None", ",", "silent", "=", "False", ")", ":", "if", "isinstance", "(", "taxids", ",", "int", ")", ":", "taxids", "=",...
Updates CTD database :param urls: list of urls to download :type urls: iterable :param connection: custom database connection string :type connection: str :param force_download: force method to download :type force_download: bool :param int,list,tuple taxids: int or iterable of NCBI taxonomy identifiers (default is None = load all)
[ "Updates", "CTD", "database" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L812-L827
cebel/pyuniprot
src/pyuniprot/manager/database.py
export_obo
def export_obo(path_to_file, connection=None): """export database to obo file :param path_to_file: path to export file :param connection: connection string (optional) :return: """ db = DbManager(connection) db.export_obo(path_to_export_file=path_to_file) db.session.close()
python
def export_obo(path_to_file, connection=None): """export database to obo file :param path_to_file: path to export file :param connection: connection string (optional) :return: """ db = DbManager(connection) db.export_obo(path_to_export_file=path_to_file) db.session.close()
[ "def", "export_obo", "(", "path_to_file", ",", "connection", "=", "None", ")", ":", "db", "=", "DbManager", "(", "connection", ")", "db", ".", "export_obo", "(", "path_to_export_file", "=", "path_to_file", ")", "db", ".", "session", ".", "close", "(", ")" ...
export database to obo file :param path_to_file: path to export file :param connection: connection string (optional) :return:
[ "export", "database", "to", "obo", "file" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L879-L888
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.db_import_xml
def db_import_xml(self, url=None, force_download=False, taxids=None, silent=False): """Updates the CTD database 1. downloads gzipped XML 2. drops all tables in database 3. creates all tables in database 4. import XML 5. close session :param Optional[list[int]] taxids: list of NCBI taxonomy identifier :param str url: iterable of URL strings :param bool force_download: force method to download :param bool silent: """ log.info('Update UniProt database from {}'.format(url)) self._drop_tables() xml_gzipped_file_path, version_file_path = self.download(url, force_download) self._create_tables() self.import_version(version_file_path) self.import_xml(xml_gzipped_file_path, taxids, silent) self.session.close()
python
def db_import_xml(self, url=None, force_download=False, taxids=None, silent=False): """Updates the CTD database 1. downloads gzipped XML 2. drops all tables in database 3. creates all tables in database 4. import XML 5. close session :param Optional[list[int]] taxids: list of NCBI taxonomy identifier :param str url: iterable of URL strings :param bool force_download: force method to download :param bool silent: """ log.info('Update UniProt database from {}'.format(url)) self._drop_tables() xml_gzipped_file_path, version_file_path = self.download(url, force_download) self._create_tables() self.import_version(version_file_path) self.import_xml(xml_gzipped_file_path, taxids, silent) self.session.close()
[ "def", "db_import_xml", "(", "self", ",", "url", "=", "None", ",", "force_download", "=", "False", ",", "taxids", "=", "None", ",", "silent", "=", "False", ")", ":", "log", ".", "info", "(", "'Update UniProt database from {}'", ".", "format", "(", "url", ...
Updates the CTD database 1. downloads gzipped XML 2. drops all tables in database 3. creates all tables in database 4. import XML 5. close session :param Optional[list[int]] taxids: list of NCBI taxonomy identifier :param str url: iterable of URL strings :param bool force_download: force method to download :param bool silent:
[ "Updates", "the", "CTD", "database", "1", ".", "downloads", "gzipped", "XML", "2", ".", "drops", "all", "tables", "in", "database", "3", ".", "creates", "all", "tables", "in", "database", "4", ".", "import", "XML", "5", ".", "close", "session" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L135-L156
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.import_xml
def import_xml(self, xml_gzipped_file_path, taxids=None, silent=False): """Imports XML :param str xml_gzipped_file_path: path to XML file :param Optional[list[int]] taxids: NCBI taxonomy identifier :param bool silent: no output if True """ version = self.session.query(models.Version).filter(models.Version.knowledgebase == 'Swiss-Prot').first() version.import_start_date = datetime.now() entry_xml = '<entries>' number_of_entries = 0 interval = 1000 start = False if sys.platform in ('linux', 'linux2', 'darwin'): log.info('Load gzipped XML from {}'.format(xml_gzipped_file_path)) zcat_command = 'gzcat' if sys.platform == 'darwin' else 'zcat' number_of_lines = int(getoutput("{} {} | wc -l".format(zcat_command, xml_gzipped_file_path))) tqdm_desc = 'Import {} lines'.format(number_of_lines) else: print('bin was anderes') number_of_lines = None tqdm_desc = None with gzip.open(xml_gzipped_file_path) as fd: for line in tqdm(fd, desc=tqdm_desc, total=number_of_lines, mininterval=1, disable=silent): end_of_file = line.startswith(b"</uniprot>") if line.startswith(b"<entry "): start = True elif end_of_file: start = False if start: entry_xml += line.decode("utf-8") if line.startswith(b"</entry>") or end_of_file: number_of_entries += 1 start = False if number_of_entries == interval or end_of_file: entry_xml += "</entries>" self.insert_entries(entry_xml, taxids) if end_of_file: break else: entry_xml = "<entries>" number_of_entries = 0 version.import_completed_date = datetime.now() self.session.commit()
python
def import_xml(self, xml_gzipped_file_path, taxids=None, silent=False): """Imports XML :param str xml_gzipped_file_path: path to XML file :param Optional[list[int]] taxids: NCBI taxonomy identifier :param bool silent: no output if True """ version = self.session.query(models.Version).filter(models.Version.knowledgebase == 'Swiss-Prot').first() version.import_start_date = datetime.now() entry_xml = '<entries>' number_of_entries = 0 interval = 1000 start = False if sys.platform in ('linux', 'linux2', 'darwin'): log.info('Load gzipped XML from {}'.format(xml_gzipped_file_path)) zcat_command = 'gzcat' if sys.platform == 'darwin' else 'zcat' number_of_lines = int(getoutput("{} {} | wc -l".format(zcat_command, xml_gzipped_file_path))) tqdm_desc = 'Import {} lines'.format(number_of_lines) else: print('bin was anderes') number_of_lines = None tqdm_desc = None with gzip.open(xml_gzipped_file_path) as fd: for line in tqdm(fd, desc=tqdm_desc, total=number_of_lines, mininterval=1, disable=silent): end_of_file = line.startswith(b"</uniprot>") if line.startswith(b"<entry "): start = True elif end_of_file: start = False if start: entry_xml += line.decode("utf-8") if line.startswith(b"</entry>") or end_of_file: number_of_entries += 1 start = False if number_of_entries == interval or end_of_file: entry_xml += "</entries>" self.insert_entries(entry_xml, taxids) if end_of_file: break else: entry_xml = "<entries>" number_of_entries = 0 version.import_completed_date = datetime.now() self.session.commit()
[ "def", "import_xml", "(", "self", ",", "xml_gzipped_file_path", ",", "taxids", "=", "None", ",", "silent", "=", "False", ")", ":", "version", "=", "self", ".", "session", ".", "query", "(", "models", ".", "Version", ")", ".", "filter", "(", "models", "...
Imports XML :param str xml_gzipped_file_path: path to XML file :param Optional[list[int]] taxids: NCBI taxonomy identifier :param bool silent: no output if True
[ "Imports", "XML" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L177-L238
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.insert_entries
def insert_entries(self, entries_xml, taxids=None): """Inserts UniProt entries from XML :param str entries_xml: XML string :param Optional[list[int]] taxids: NCBI taxonomy IDs """ entries = etree.fromstring(entries_xml) del entries_xml for entry in entries: self.insert_entry(entry, taxids) entry.clear() del entry entries.clear() del entries self.session.commit()
python
def insert_entries(self, entries_xml, taxids=None): """Inserts UniProt entries from XML :param str entries_xml: XML string :param Optional[list[int]] taxids: NCBI taxonomy IDs """ entries = etree.fromstring(entries_xml) del entries_xml for entry in entries: self.insert_entry(entry, taxids) entry.clear() del entry entries.clear() del entries self.session.commit()
[ "def", "insert_entries", "(", "self", ",", "entries_xml", ",", "taxids", "=", "None", ")", ":", "entries", "=", "etree", ".", "fromstring", "(", "entries_xml", ")", "del", "entries_xml", "for", "entry", "in", "entries", ":", "self", ".", "insert_entry", "(...
Inserts UniProt entries from XML :param str entries_xml: XML string :param Optional[list[int]] taxids: NCBI taxonomy IDs
[ "Inserts", "UniProt", "entries", "from", "XML" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L240-L258
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.insert_entry
def insert_entry(self, entry, taxids): """Insert UniProt entry" :param entry: XML node entry :param taxids: Optional[iter[int]] taxids: NCBI taxonomy IDs """ entry_dict = entry.attrib entry_dict['created'] = datetime.strptime(entry_dict['created'], '%Y-%m-%d') entry_dict['modified'] = datetime.strptime(entry_dict['modified'], '%Y-%m-%d') taxid = self.get_taxid(entry) if taxids is None or taxid in taxids: entry_dict = self.update_entry_dict(entry, entry_dict, taxid) entry_obj = models.Entry(**entry_dict) del entry_dict self.session.add(entry_obj)
python
def insert_entry(self, entry, taxids): """Insert UniProt entry" :param entry: XML node entry :param taxids: Optional[iter[int]] taxids: NCBI taxonomy IDs """ entry_dict = entry.attrib entry_dict['created'] = datetime.strptime(entry_dict['created'], '%Y-%m-%d') entry_dict['modified'] = datetime.strptime(entry_dict['modified'], '%Y-%m-%d') taxid = self.get_taxid(entry) if taxids is None or taxid in taxids: entry_dict = self.update_entry_dict(entry, entry_dict, taxid) entry_obj = models.Entry(**entry_dict) del entry_dict self.session.add(entry_obj)
[ "def", "insert_entry", "(", "self", ",", "entry", ",", "taxids", ")", ":", "entry_dict", "=", "entry", ".", "attrib", "entry_dict", "[", "'created'", "]", "=", "datetime", ".", "strptime", "(", "entry_dict", "[", "'created'", "]", ",", "'%Y-%m-%d'", ")", ...
Insert UniProt entry" :param entry: XML node entry :param taxids: Optional[iter[int]] taxids: NCBI taxonomy IDs
[ "Insert", "UniProt", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L261-L278
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_sequence
def get_sequence(cls, entry): """ get models.Sequence object from XML node entry :param entry: XML node entry :return: :class:`pyuniprot.manager.models.Sequence` object """ seq_tag = entry.find("./sequence") seq = seq_tag.text seq_tag.clear() return models.Sequence(sequence=seq)
python
def get_sequence(cls, entry): """ get models.Sequence object from XML node entry :param entry: XML node entry :return: :class:`pyuniprot.manager.models.Sequence` object """ seq_tag = entry.find("./sequence") seq = seq_tag.text seq_tag.clear() return models.Sequence(sequence=seq)
[ "def", "get_sequence", "(", "cls", ",", "entry", ")", ":", "seq_tag", "=", "entry", ".", "find", "(", "\"./sequence\"", ")", "seq", "=", "seq_tag", ".", "text", "seq_tag", ".", "clear", "(", ")", "return", "models", ".", "Sequence", "(", "sequence", "=...
get models.Sequence object from XML node entry :param entry: XML node entry :return: :class:`pyuniprot.manager.models.Sequence` object
[ "get", "models", ".", "Sequence", "object", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L336-L346
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_tissue_in_references
def get_tissue_in_references(self, entry): """ get list of models.TissueInReference from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.TissueInReference` objects """ tissue_in_references = [] query = "./reference/source/tissue" tissues = {x.text for x in entry.iterfind(query)} for tissue in tissues: if tissue not in self.tissues: self.tissues[tissue] = models.TissueInReference(tissue=tissue) tissue_in_references.append(self.tissues[tissue]) return tissue_in_references
python
def get_tissue_in_references(self, entry): """ get list of models.TissueInReference from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.TissueInReference` objects """ tissue_in_references = [] query = "./reference/source/tissue" tissues = {x.text for x in entry.iterfind(query)} for tissue in tissues: if tissue not in self.tissues: self.tissues[tissue] = models.TissueInReference(tissue=tissue) tissue_in_references.append(self.tissues[tissue]) return tissue_in_references
[ "def", "get_tissue_in_references", "(", "self", ",", "entry", ")", ":", "tissue_in_references", "=", "[", "]", "query", "=", "\"./reference/source/tissue\"", "tissues", "=", "{", "x", ".", "text", "for", "x", "in", "entry", ".", "iterfind", "(", "query", ")"...
get list of models.TissueInReference from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.TissueInReference` objects
[ "get", "list", "of", "models", ".", "TissueInReference", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L348-L365
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_tissue_specificities
def get_tissue_specificities(cls, entry): """ get list of :class:`pyuniprot.manager.models.TissueSpecificity` object from XML node entry :param entry: XML node entry :return: models.TissueSpecificity object """ tissue_specificities = [] query = "./comment[@type='tissue specificity']/text" for ts in entry.iterfind(query): tissue_specificities.append(models.TissueSpecificity(comment=ts.text)) return tissue_specificities
python
def get_tissue_specificities(cls, entry): """ get list of :class:`pyuniprot.manager.models.TissueSpecificity` object from XML node entry :param entry: XML node entry :return: models.TissueSpecificity object """ tissue_specificities = [] query = "./comment[@type='tissue specificity']/text" for ts in entry.iterfind(query): tissue_specificities.append(models.TissueSpecificity(comment=ts.text)) return tissue_specificities
[ "def", "get_tissue_specificities", "(", "cls", ",", "entry", ")", ":", "tissue_specificities", "=", "[", "]", "query", "=", "\"./comment[@type='tissue specificity']/text\"", "for", "ts", "in", "entry", ".", "iterfind", "(", "query", ")", ":", "tissue_specificities",...
get list of :class:`pyuniprot.manager.models.TissueSpecificity` object from XML node entry :param entry: XML node entry :return: models.TissueSpecificity object
[ "get", "list", "of", ":", "class", ":", "pyuniprot", ".", "manager", ".", "models", ".", "TissueSpecificity", "object", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L368-L382
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_subcellular_locations
def get_subcellular_locations(self, entry): """ get list of models.SubcellularLocation object from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.SubcellularLocation` object """ subcellular_locations = [] query = './comment/subcellularLocation/location' sls = {x.text for x in entry.iterfind(query)} for sl in sls: if sl not in self.subcellular_locations: self.subcellular_locations[sl] = models.SubcellularLocation(location=sl) subcellular_locations.append(self.subcellular_locations[sl]) return subcellular_locations
python
def get_subcellular_locations(self, entry): """ get list of models.SubcellularLocation object from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.SubcellularLocation` object """ subcellular_locations = [] query = './comment/subcellularLocation/location' sls = {x.text for x in entry.iterfind(query)} for sl in sls: if sl not in self.subcellular_locations: self.subcellular_locations[sl] = models.SubcellularLocation(location=sl) subcellular_locations.append(self.subcellular_locations[sl]) return subcellular_locations
[ "def", "get_subcellular_locations", "(", "self", ",", "entry", ")", ":", "subcellular_locations", "=", "[", "]", "query", "=", "'./comment/subcellularLocation/location'", "sls", "=", "{", "x", ".", "text", "for", "x", "in", "entry", ".", "iterfind", "(", "quer...
get list of models.SubcellularLocation object from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.SubcellularLocation` object
[ "get", "list", "of", "models", ".", "SubcellularLocation", "object", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L384-L401
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_keywords
def get_keywords(self, entry): """ get list of models.Keyword objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Keyword` objects """ keyword_objects = [] for keyword in entry.iterfind("./keyword"): identifier = keyword.get('id') name = keyword.text keyword_hash = hash(identifier) if keyword_hash not in self.keywords: self.keywords[keyword_hash] = models.Keyword(**{'identifier': identifier, 'name': name}) keyword_objects.append(self.keywords[keyword_hash]) return keyword_objects
python
def get_keywords(self, entry): """ get list of models.Keyword objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Keyword` objects """ keyword_objects = [] for keyword in entry.iterfind("./keyword"): identifier = keyword.get('id') name = keyword.text keyword_hash = hash(identifier) if keyword_hash not in self.keywords: self.keywords[keyword_hash] = models.Keyword(**{'identifier': identifier, 'name': name}) keyword_objects.append(self.keywords[keyword_hash]) return keyword_objects
[ "def", "get_keywords", "(", "self", ",", "entry", ")", ":", "keyword_objects", "=", "[", "]", "for", "keyword", "in", "entry", ".", "iterfind", "(", "\"./keyword\"", ")", ":", "identifier", "=", "keyword", ".", "get", "(", "'id'", ")", "name", "=", "ke...
get list of models.Keyword objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Keyword` objects
[ "get", "list", "of", "models", ".", "Keyword", "objects", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L403-L422
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_disease_comments
def get_disease_comments(self, entry): """ get list of models.Disease objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Disease` objects """ disease_comments = [] query = "./comment[@type='disease']" for disease_comment in entry.iterfind(query): value_dict = {'comment': disease_comment.find('./text').text} disease = disease_comment.find("./disease") if disease is not None: disease_dict = {'identifier': disease.get('id')} for element in disease: key = element.tag if key in ['acronym', 'description', 'name']: disease_dict[key] = element.text if key == 'dbReference': disease_dict['ref_id'] = element.get('id') disease_dict['ref_type'] = element.get('type') disease_obj = models.get_or_create(self.session, models.Disease, **disease_dict) self.session.add(disease_obj) self.session.flush() value_dict['disease_id'] = disease_obj.id disease_comments.append(models.DiseaseComment(**value_dict)) return disease_comments
python
def get_disease_comments(self, entry): """ get list of models.Disease objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Disease` objects """ disease_comments = [] query = "./comment[@type='disease']" for disease_comment in entry.iterfind(query): value_dict = {'comment': disease_comment.find('./text').text} disease = disease_comment.find("./disease") if disease is not None: disease_dict = {'identifier': disease.get('id')} for element in disease: key = element.tag if key in ['acronym', 'description', 'name']: disease_dict[key] = element.text if key == 'dbReference': disease_dict['ref_id'] = element.get('id') disease_dict['ref_type'] = element.get('type') disease_obj = models.get_or_create(self.session, models.Disease, **disease_dict) self.session.add(disease_obj) self.session.flush() value_dict['disease_id'] = disease_obj.id disease_comments.append(models.DiseaseComment(**value_dict)) return disease_comments
[ "def", "get_disease_comments", "(", "self", ",", "entry", ")", ":", "disease_comments", "=", "[", "]", "query", "=", "\"./comment[@type='disease']\"", "for", "disease_comment", "in", "entry", ".", "iterfind", "(", "query", ")", ":", "value_dict", "=", "{", "'c...
get list of models.Disease objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Disease` objects
[ "get", "list", "of", "models", ".", "Disease", "objects", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L435-L470
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_alternative_full_names
def get_alternative_full_names(cls, entry): """ get list of models.AlternativeFullName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeFullName` objects """ names = [] query = "./protein/alternativeName/fullName" for name in entry.iterfind(query): names.append(models.AlternativeFullName(name=name.text)) return names
python
def get_alternative_full_names(cls, entry): """ get list of models.AlternativeFullName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeFullName` objects """ names = [] query = "./protein/alternativeName/fullName" for name in entry.iterfind(query): names.append(models.AlternativeFullName(name=name.text)) return names
[ "def", "get_alternative_full_names", "(", "cls", ",", "entry", ")", ":", "names", "=", "[", "]", "query", "=", "\"./protein/alternativeName/fullName\"", "for", "name", "in", "entry", ".", "iterfind", "(", "query", ")", ":", "names", ".", "append", "(", "mode...
get list of models.AlternativeFullName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeFullName` objects
[ "get", "list", "of", "models", ".", "AlternativeFullName", "objects", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L473-L485
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_alternative_short_names
def get_alternative_short_names(cls, entry): """ get list of models.AlternativeShortName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeShortName` objects """ names = [] query = "./protein/alternativeName/shortName" for name in entry.iterfind(query): names.append(models.AlternativeShortName(name=name.text)) return names
python
def get_alternative_short_names(cls, entry): """ get list of models.AlternativeShortName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeShortName` objects """ names = [] query = "./protein/alternativeName/shortName" for name in entry.iterfind(query): names.append(models.AlternativeShortName(name=name.text)) return names
[ "def", "get_alternative_short_names", "(", "cls", ",", "entry", ")", ":", "names", "=", "[", "]", "query", "=", "\"./protein/alternativeName/shortName\"", "for", "name", "in", "entry", ".", "iterfind", "(", "query", ")", ":", "names", ".", "append", "(", "mo...
get list of models.AlternativeShortName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeShortName` objects
[ "get", "list", "of", "models", ".", "AlternativeShortName", "objects", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L488-L500
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_ec_numbers
def get_ec_numbers(cls, entry): """ get list of models.ECNumber objects from XML node entry :param entry: XML node entry :return: list of models.ECNumber objects """ ec_numbers = [] for ec in entry.iterfind("./protein/recommendedName/ecNumber"): ec_numbers.append(models.ECNumber(ec_number=ec.text)) return ec_numbers
python
def get_ec_numbers(cls, entry): """ get list of models.ECNumber objects from XML node entry :param entry: XML node entry :return: list of models.ECNumber objects """ ec_numbers = [] for ec in entry.iterfind("./protein/recommendedName/ecNumber"): ec_numbers.append(models.ECNumber(ec_number=ec.text)) return ec_numbers
[ "def", "get_ec_numbers", "(", "cls", ",", "entry", ")", ":", "ec_numbers", "=", "[", "]", "for", "ec", "in", "entry", ".", "iterfind", "(", "\"./protein/recommendedName/ecNumber\"", ")", ":", "ec_numbers", ".", "append", "(", "models", ".", "ECNumber", "(", ...
get list of models.ECNumber objects from XML node entry :param entry: XML node entry :return: list of models.ECNumber objects
[ "get", "list", "of", "models", ".", "ECNumber", "objects", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L503-L514
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_gene_name
def get_gene_name(cls, entry): """ get primary gene name from XML node entry :param entry: XML node entry :return: str """ gene_name = entry.find("./gene/name[@type='primary']") return gene_name.text if gene_name is not None and gene_name.text.strip() else None
python
def get_gene_name(cls, entry): """ get primary gene name from XML node entry :param entry: XML node entry :return: str """ gene_name = entry.find("./gene/name[@type='primary']") return gene_name.text if gene_name is not None and gene_name.text.strip() else None
[ "def", "get_gene_name", "(", "cls", ",", "entry", ")", ":", "gene_name", "=", "entry", ".", "find", "(", "\"./gene/name[@type='primary']\"", ")", "return", "gene_name", ".", "text", "if", "gene_name", "is", "not", "None", "and", "gene_name", ".", "text", "."...
get primary gene name from XML node entry :param entry: XML node entry :return: str
[ "get", "primary", "gene", "name", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L517-L526
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_other_gene_names
def get_other_gene_names(cls, entry): """ get list of `models.OtherGeneName` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.models.OtherGeneName` objects """ alternative_gene_names = [] for alternative_gene_name in entry.iterfind("./gene/name"): if alternative_gene_name.attrib['type'] != 'primary': alternative_gene_name_dict = { 'type_': alternative_gene_name.attrib['type'], 'name': alternative_gene_name.text } alternative_gene_names.append(models.OtherGeneName(**alternative_gene_name_dict)) return alternative_gene_names
python
def get_other_gene_names(cls, entry): """ get list of `models.OtherGeneName` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.models.OtherGeneName` objects """ alternative_gene_names = [] for alternative_gene_name in entry.iterfind("./gene/name"): if alternative_gene_name.attrib['type'] != 'primary': alternative_gene_name_dict = { 'type_': alternative_gene_name.attrib['type'], 'name': alternative_gene_name.text } alternative_gene_names.append(models.OtherGeneName(**alternative_gene_name_dict)) return alternative_gene_names
[ "def", "get_other_gene_names", "(", "cls", ",", "entry", ")", ":", "alternative_gene_names", "=", "[", "]", "for", "alternative_gene_name", "in", "entry", ".", "iterfind", "(", "\"./gene/name\"", ")", ":", "if", "alternative_gene_name", ".", "attrib", "[", "'typ...
get list of `models.OtherGeneName` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.models.OtherGeneName` objects
[ "get", "list", "of", "models", ".", "OtherGeneName", "objects", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L529-L549
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_accessions
def get_accessions(cls, entry): """ get list of models.Accession from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Accession` objects """ return [models.Accession(accession=x.text) for x in entry.iterfind("./accession")]
python
def get_accessions(cls, entry): """ get list of models.Accession from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Accession` objects """ return [models.Accession(accession=x.text) for x in entry.iterfind("./accession")]
[ "def", "get_accessions", "(", "cls", ",", "entry", ")", ":", "return", "[", "models", ".", "Accession", "(", "accession", "=", "x", ".", "text", ")", "for", "x", "in", "entry", ".", "iterfind", "(", "\"./accession\"", ")", "]" ]
get list of models.Accession from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Accession` objects
[ "get", "list", "of", "models", ".", "Accession", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L552-L559
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_db_references
def get_db_references(cls, entry): """ get list of `models.DbReference` from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.DbReference` """ db_refs = [] for db_ref in entry.iterfind("./dbReference"): db_ref_dict = {'identifier': db_ref.attrib['id'], 'type_': db_ref.attrib['type']} db_refs.append(models.DbReference(**db_ref_dict)) return db_refs
python
def get_db_references(cls, entry): """ get list of `models.DbReference` from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.DbReference` """ db_refs = [] for db_ref in entry.iterfind("./dbReference"): db_ref_dict = {'identifier': db_ref.attrib['id'], 'type_': db_ref.attrib['type']} db_refs.append(models.DbReference(**db_ref_dict)) return db_refs
[ "def", "get_db_references", "(", "cls", ",", "entry", ")", ":", "db_refs", "=", "[", "]", "for", "db_ref", "in", "entry", ".", "iterfind", "(", "\"./dbReference\"", ")", ":", "db_ref_dict", "=", "{", "'identifier'", ":", "db_ref", ".", "attrib", "[", "'i...
get list of `models.DbReference` from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.DbReference`
[ "get", "list", "of", "models", ".", "DbReference", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L562-L576
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_features
def get_features(cls, entry): """ get list of `models.Feature` from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Feature` """ features = [] for feature in entry.iterfind("./feature"): feature_dict = { 'description': feature.attrib.get('description'), 'type_': feature.attrib['type'], 'identifier': feature.attrib.get('id') } features.append(models.Feature(**feature_dict)) return features
python
def get_features(cls, entry): """ get list of `models.Feature` from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Feature` """ features = [] for feature in entry.iterfind("./feature"): feature_dict = { 'description': feature.attrib.get('description'), 'type_': feature.attrib['type'], 'identifier': feature.attrib.get('id') } features.append(models.Feature(**feature_dict)) return features
[ "def", "get_features", "(", "cls", ",", "entry", ")", ":", "features", "=", "[", "]", "for", "feature", "in", "entry", ".", "iterfind", "(", "\"./feature\"", ")", ":", "feature_dict", "=", "{", "'description'", ":", "feature", ".", "attrib", ".", "get", ...
get list of `models.Feature` from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Feature`
[ "get", "list", "of", "models", ".", "Feature", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L589-L608
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_recommended_protein_name
def get_recommended_protein_name(cls, entry): """ get recommended full and short protein name as tuple from XML node :param entry: XML node entry :return: (str, str) => (full, short) """ query_full = "./protein/recommendedName/fullName" full_name = entry.find(query_full).text short_name = None query_short = "./protein/recommendedName/shortName" short_name_tag = entry.find(query_short) if short_name_tag is not None: short_name = short_name_tag.text return full_name, short_name
python
def get_recommended_protein_name(cls, entry): """ get recommended full and short protein name as tuple from XML node :param entry: XML node entry :return: (str, str) => (full, short) """ query_full = "./protein/recommendedName/fullName" full_name = entry.find(query_full).text short_name = None query_short = "./protein/recommendedName/shortName" short_name_tag = entry.find(query_short) if short_name_tag is not None: short_name = short_name_tag.text return full_name, short_name
[ "def", "get_recommended_protein_name", "(", "cls", ",", "entry", ")", ":", "query_full", "=", "\"./protein/recommendedName/fullName\"", "full_name", "=", "entry", ".", "find", "(", "query_full", ")", ".", "text", "short_name", "=", "None", "query_short", "=", "\"....
get recommended full and short protein name as tuple from XML node :param entry: XML node entry :return: (str, str) => (full, short)
[ "get", "recommended", "full", "and", "short", "protein", "name", "as", "tuple", "from", "XML", "node" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L621-L637
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_organism_hosts
def get_organism_hosts(cls, entry): """ get list of `models.OrganismHost` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.OrganismHost` objects """ query = "./organismHost/dbReference[@type='NCBI Taxonomy']" return [models.OrganismHost(taxid=x.get('id')) for x in entry.iterfind(query)]
python
def get_organism_hosts(cls, entry): """ get list of `models.OrganismHost` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.OrganismHost` objects """ query = "./organismHost/dbReference[@type='NCBI Taxonomy']" return [models.OrganismHost(taxid=x.get('id')) for x in entry.iterfind(query)]
[ "def", "get_organism_hosts", "(", "cls", ",", "entry", ")", ":", "query", "=", "\"./organismHost/dbReference[@type='NCBI Taxonomy']\"", "return", "[", "models", ".", "OrganismHost", "(", "taxid", "=", "x", ".", "get", "(", "'id'", ")", ")", "for", "x", "in", ...
get list of `models.OrganismHost` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.OrganismHost` objects
[ "get", "list", "of", "models", ".", "OrganismHost", "objects", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L640-L649
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_pmids
def get_pmids(self, entry): """ get `models.Pmid` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Pmid` objects """ pmids = [] for citation in entry.iterfind("./reference/citation"): for pubmed_ref in citation.iterfind('dbReference[@type="PubMed"]'): pmid_number = pubmed_ref.get('id') if pmid_number in self.pmids: pmid_sqlalchemy_obj = self.session.query(models.Pmid)\ .filter(models.Pmid.pmid == pmid_number).one() pmids.append(pmid_sqlalchemy_obj) else: pmid_dict = citation.attrib if not re.search('^\d+$', pmid_dict['volume']): pmid_dict['volume'] = -1 del pmid_dict['type'] # not needed because already filtered for PubMed pmid_dict.update(pmid=pmid_number) title_tag = citation.find('./title') if title_tag is not None: pmid_dict.update(title=title_tag.text) pmid_sqlalchemy_obj = models.Pmid(**pmid_dict) self.session.add(pmid_sqlalchemy_obj) self.session.flush() pmids.append(pmid_sqlalchemy_obj) self.pmids |= set([pmid_number, ]) # extend the cache of identifiers return pmids
python
def get_pmids(self, entry): """ get `models.Pmid` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Pmid` objects """ pmids = [] for citation in entry.iterfind("./reference/citation"): for pubmed_ref in citation.iterfind('dbReference[@type="PubMed"]'): pmid_number = pubmed_ref.get('id') if pmid_number in self.pmids: pmid_sqlalchemy_obj = self.session.query(models.Pmid)\ .filter(models.Pmid.pmid == pmid_number).one() pmids.append(pmid_sqlalchemy_obj) else: pmid_dict = citation.attrib if not re.search('^\d+$', pmid_dict['volume']): pmid_dict['volume'] = -1 del pmid_dict['type'] # not needed because already filtered for PubMed pmid_dict.update(pmid=pmid_number) title_tag = citation.find('./title') if title_tag is not None: pmid_dict.update(title=title_tag.text) pmid_sqlalchemy_obj = models.Pmid(**pmid_dict) self.session.add(pmid_sqlalchemy_obj) self.session.flush() pmids.append(pmid_sqlalchemy_obj) self.pmids |= set([pmid_number, ]) # extend the cache of identifiers return pmids
[ "def", "get_pmids", "(", "self", ",", "entry", ")", ":", "pmids", "=", "[", "]", "for", "citation", "in", "entry", ".", "iterfind", "(", "\"./reference/citation\"", ")", ":", "for", "pubmed_ref", "in", "citation", ".", "iterfind", "(", "'dbReference[@type=\"...
get `models.Pmid` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Pmid` objects
[ "get", "models", ".", "Pmid", "objects", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L651-L694
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_functions
def get_functions(cls, entry): """ get `models.Function` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Function` objects """ comments = [] query = "./comment[@type='function']" for comment in entry.iterfind(query): text = comment.find('./text').text comments.append(models.Function(text=text)) return comments
python
def get_functions(cls, entry): """ get `models.Function` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Function` objects """ comments = [] query = "./comment[@type='function']" for comment in entry.iterfind(query): text = comment.find('./text').text comments.append(models.Function(text=text)) return comments
[ "def", "get_functions", "(", "cls", ",", "entry", ")", ":", "comments", "=", "[", "]", "query", "=", "\"./comment[@type='function']\"", "for", "comment", "in", "entry", ".", "iterfind", "(", "query", ")", ":", "text", "=", "comment", ".", "find", "(", "'...
get `models.Function` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Function` objects
[ "get", "models", ".", "Function", "objects", "from", "XML", "node", "entry" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L697-L710
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.download
def download(cls, url=None, force_download=False): """Downloads uniprot_sprot.xml.gz and reldate.txt (release date information) from URL or file path .. note:: only URL/path of xml.gz is needed and valid value for parameter url. URL/path for reldate.txt have to be the same folder :param str url: UniProt gzipped URL or file path :param force_download: force method to download :type force_download: bool """ if url: version_url = os.path.join(os.path.dirname(url), defaults.VERSION_FILE_NAME) else: url = os.path.join(defaults.XML_DIR_NAME, defaults.SWISSPROT_FILE_NAME) version_url = os.path.join(defaults.XML_DIR_NAME, defaults.VERSION_FILE_NAME) xml_file_path = cls.get_path_to_file_from_url(url) version_file_path = cls.get_path_to_file_from_url(version_url) if force_download or not os.path.exists(xml_file_path): log.info('download {} and {}'.format(xml_file_path, version_file_path)) scheme = urlsplit(url).scheme if scheme in ('ftp', 'http'): urlretrieve(version_url, version_file_path) urlretrieve(url, xml_file_path) elif not scheme and os.path.isfile(url): shutil.copyfile(url, xml_file_path) shutil.copyfile(version_url, version_file_path) return xml_file_path, version_file_path
python
def download(cls, url=None, force_download=False): """Downloads uniprot_sprot.xml.gz and reldate.txt (release date information) from URL or file path .. note:: only URL/path of xml.gz is needed and valid value for parameter url. URL/path for reldate.txt have to be the same folder :param str url: UniProt gzipped URL or file path :param force_download: force method to download :type force_download: bool """ if url: version_url = os.path.join(os.path.dirname(url), defaults.VERSION_FILE_NAME) else: url = os.path.join(defaults.XML_DIR_NAME, defaults.SWISSPROT_FILE_NAME) version_url = os.path.join(defaults.XML_DIR_NAME, defaults.VERSION_FILE_NAME) xml_file_path = cls.get_path_to_file_from_url(url) version_file_path = cls.get_path_to_file_from_url(version_url) if force_download or not os.path.exists(xml_file_path): log.info('download {} and {}'.format(xml_file_path, version_file_path)) scheme = urlsplit(url).scheme if scheme in ('ftp', 'http'): urlretrieve(version_url, version_file_path) urlretrieve(url, xml_file_path) elif not scheme and os.path.isfile(url): shutil.copyfile(url, xml_file_path) shutil.copyfile(version_url, version_file_path) return xml_file_path, version_file_path
[ "def", "download", "(", "cls", ",", "url", "=", "None", ",", "force_download", "=", "False", ")", ":", "if", "url", ":", "version_url", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "url", ")", ",", "defaults", ...
Downloads uniprot_sprot.xml.gz and reldate.txt (release date information) from URL or file path .. note:: only URL/path of xml.gz is needed and valid value for parameter url. URL/path for reldate.txt have to be the same folder :param str url: UniProt gzipped URL or file path :param force_download: force method to download :type force_download: bool
[ "Downloads", "uniprot_sprot", ".", "xml", ".", "gz", "and", "reldate", ".", "txt", "(", "release", "date", "information", ")", "from", "URL", "or", "file", "path" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L719-L754
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_path_to_file_from_url
def get_path_to_file_from_url(cls, url): """standard file path :param str url: download URL """ file_name = urlparse(url).path.split('/')[-1] return os.path.join(PYUNIPROT_DATA_DIR, file_name)
python
def get_path_to_file_from_url(cls, url): """standard file path :param str url: download URL """ file_name = urlparse(url).path.split('/')[-1] return os.path.join(PYUNIPROT_DATA_DIR, file_name)
[ "def", "get_path_to_file_from_url", "(", "cls", ",", "url", ")", ":", "file_name", "=", "urlparse", "(", "url", ")", ".", "path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "return", "os", ".", "path", ".", "join", "(", "PYUNIPROT_DATA_DIR", ...
standard file path :param str url: download URL
[ "standard", "file", "path", ":", "param", "str", "url", ":", "download", "URL" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L757-L763
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.export_obo
def export_obo(self, path_to_export_file, name_of_ontology="uniprot", taxids=None): """ export complete database to OBO (http://www.obofoundry.org/) file :param path_to_export_file: path to export file :param taxids: NCBI taxonomy identifiers to export (optional) """ fd = open(path_to_export_file, 'w') header = "format-version: 0.1\ndata: {}\n".format(time.strftime("%d:%m:%Y %H:%M")) header += "ontology: {}\n".format(name_of_ontology) header += 'synonymtypedef: GENE_NAME "GENE NAME"\nsynonymtypedef: ALTERNATIVE_NAME "ALTERNATIVE NAME"\n' fd.write(header) query = self.session.query(models.Entry).limit(100) if taxids: query = query.filter(models.Entry.taxid.in_(taxids)) for entry in query.all(): fd.write('\n[Term]\nid: SWISSPROT:{}\n'.format(entry.accessions[0])) if len(entry.accessions) > 1: for accession in entry.accessions[1:]: fd.write('alt_id: {}\n'.format(accession)) fd.write('name: {}\n'.format(entry.recommended_full_name)) for alternative_full_name in entry.alternative_full_names: fd.write('synonym: "{}" EXACT ALTERNATIVE_NAME []\n'.format(alternative_full_name.name)) for alternative_short_name in entry.alternative_short_names: fd.write('synonym: "{}" EXACT ALTERNATIVE_NAME []\n'.format(alternative_short_name.name)) fd.write('synonym: "{}" EXACT GENE_NAME []\n'.format(entry.gene_name)) for xref in entry.db_references: if xref.type_ in ['GO', 'HGNC']: xref.identifier = ':'.join(xref.identifier.split(':')[1:]) fd.write('xref: {}:{}\n'.format(xref.type_, xref.identifier.replace('\\', '\\\\'))) fd.close()
python
def export_obo(self, path_to_export_file, name_of_ontology="uniprot", taxids=None): """ export complete database to OBO (http://www.obofoundry.org/) file :param path_to_export_file: path to export file :param taxids: NCBI taxonomy identifiers to export (optional) """ fd = open(path_to_export_file, 'w') header = "format-version: 0.1\ndata: {}\n".format(time.strftime("%d:%m:%Y %H:%M")) header += "ontology: {}\n".format(name_of_ontology) header += 'synonymtypedef: GENE_NAME "GENE NAME"\nsynonymtypedef: ALTERNATIVE_NAME "ALTERNATIVE NAME"\n' fd.write(header) query = self.session.query(models.Entry).limit(100) if taxids: query = query.filter(models.Entry.taxid.in_(taxids)) for entry in query.all(): fd.write('\n[Term]\nid: SWISSPROT:{}\n'.format(entry.accessions[0])) if len(entry.accessions) > 1: for accession in entry.accessions[1:]: fd.write('alt_id: {}\n'.format(accession)) fd.write('name: {}\n'.format(entry.recommended_full_name)) for alternative_full_name in entry.alternative_full_names: fd.write('synonym: "{}" EXACT ALTERNATIVE_NAME []\n'.format(alternative_full_name.name)) for alternative_short_name in entry.alternative_short_names: fd.write('synonym: "{}" EXACT ALTERNATIVE_NAME []\n'.format(alternative_short_name.name)) fd.write('synonym: "{}" EXACT GENE_NAME []\n'.format(entry.gene_name)) for xref in entry.db_references: if xref.type_ in ['GO', 'HGNC']: xref.identifier = ':'.join(xref.identifier.split(':')[1:]) fd.write('xref: {}:{}\n'.format(xref.type_, xref.identifier.replace('\\', '\\\\'))) fd.close()
[ "def", "export_obo", "(", "self", ",", "path_to_export_file", ",", "name_of_ontology", "=", "\"uniprot\"", ",", "taxids", "=", "None", ")", ":", "fd", "=", "open", "(", "path_to_export_file", ",", "'w'", ")", "header", "=", "\"format-version: 0.1\\ndata: {}\\n\"",...
export complete database to OBO (http://www.obofoundry.org/) file :param path_to_export_file: path to export file :param taxids: NCBI taxonomy identifiers to export (optional)
[ "export", "complete", "database", "to", "OBO", "(", "http", ":", "//", "www", ".", "obofoundry", ".", "org", "/", ")", "file" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L765-L809
Peter-Slump/django-dynamic-fixtures
src/dynamic_fixtures/fixtures/loader.py
Graph.resolve_nodes
def resolve_nodes(self, nodes): """ Resolve a given set of nodes. Dependencies of the nodes, even if they are not in the given list will also be resolved! :param list nodes: List of nodes to be resolved :return: A list of resolved nodes """ if not nodes: return [] resolved = [] for node in nodes: if node in resolved: continue self.resolve_node(node, resolved) return resolved
python
def resolve_nodes(self, nodes): """ Resolve a given set of nodes. Dependencies of the nodes, even if they are not in the given list will also be resolved! :param list nodes: List of nodes to be resolved :return: A list of resolved nodes """ if not nodes: return [] resolved = [] for node in nodes: if node in resolved: continue self.resolve_node(node, resolved) return resolved
[ "def", "resolve_nodes", "(", "self", ",", "nodes", ")", ":", "if", "not", "nodes", ":", "return", "[", "]", "resolved", "=", "[", "]", "for", "node", "in", "nodes", ":", "if", "node", "in", "resolved", ":", "continue", "self", ".", "resolve_node", "(...
Resolve a given set of nodes. Dependencies of the nodes, even if they are not in the given list will also be resolved! :param list nodes: List of nodes to be resolved :return: A list of resolved nodes
[ "Resolve", "a", "given", "set", "of", "nodes", "." ]
train
https://github.com/Peter-Slump/django-dynamic-fixtures/blob/da99b4b12b11be28ea4b36b6cf2896ca449c73c1/src/dynamic_fixtures/fixtures/loader.py#L117-L134
Peter-Slump/django-dynamic-fixtures
src/dynamic_fixtures/fixtures/loader.py
Graph.resolve_node
def resolve_node(self, node=None, resolved=None, seen=None): """ Resolve a single node or all when node is omitted. """ if seen is None: seen = [] if resolved is None: resolved = [] if node is None: dependencies = sorted(self._nodes.keys()) else: dependencies = self._nodes[node] seen.append(node) for dependency in dependencies: if dependency in resolved: continue if dependency in seen: raise Exception('Circular dependency %s > %s', str(node), str(dependency)) self.resolve_node(dependency, resolved, seen) if node is not None: resolved.append(node) return resolved
python
def resolve_node(self, node=None, resolved=None, seen=None): """ Resolve a single node or all when node is omitted. """ if seen is None: seen = [] if resolved is None: resolved = [] if node is None: dependencies = sorted(self._nodes.keys()) else: dependencies = self._nodes[node] seen.append(node) for dependency in dependencies: if dependency in resolved: continue if dependency in seen: raise Exception('Circular dependency %s > %s', str(node), str(dependency)) self.resolve_node(dependency, resolved, seen) if node is not None: resolved.append(node) return resolved
[ "def", "resolve_node", "(", "self", ",", "node", "=", "None", ",", "resolved", "=", "None", ",", "seen", "=", "None", ")", ":", "if", "seen", "is", "None", ":", "seen", "=", "[", "]", "if", "resolved", "is", "None", ":", "resolved", "=", "[", "]"...
Resolve a single node or all when node is omitted.
[ "Resolve", "a", "single", "node", "or", "all", "when", "node", "is", "omitted", "." ]
train
https://github.com/Peter-Slump/django-dynamic-fixtures/blob/da99b4b12b11be28ea4b36b6cf2896ca449c73c1/src/dynamic_fixtures/fixtures/loader.py#L136-L158
acorg/dark-matter
dark/orfs.py
findCodons
def findCodons(seq, codons): """ Find all instances of the codons in 'codons' in the given sequence. seq: A Bio.Seq.Seq instance. codons: A set of codon strings. Return: a generator yielding matching codon offsets. """ seqLen = len(seq) start = 0 while start < seqLen: triplet = str(seq[start:start + 3]) if triplet in codons: yield start start = start + 3
python
def findCodons(seq, codons): """ Find all instances of the codons in 'codons' in the given sequence. seq: A Bio.Seq.Seq instance. codons: A set of codon strings. Return: a generator yielding matching codon offsets. """ seqLen = len(seq) start = 0 while start < seqLen: triplet = str(seq[start:start + 3]) if triplet in codons: yield start start = start + 3
[ "def", "findCodons", "(", "seq", ",", "codons", ")", ":", "seqLen", "=", "len", "(", "seq", ")", "start", "=", "0", "while", "start", "<", "seqLen", ":", "triplet", "=", "str", "(", "seq", "[", "start", ":", "start", "+", "3", "]", ")", "if", "...
Find all instances of the codons in 'codons' in the given sequence. seq: A Bio.Seq.Seq instance. codons: A set of codon strings. Return: a generator yielding matching codon offsets.
[ "Find", "all", "instances", "of", "the", "codons", "in", "codons", "in", "the", "given", "sequence", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/orfs.py#L7-L22
acorg/dark-matter
dark/orfs.py
addORFs
def addORFs(fig, seq, minX, maxX, offsetAdjuster): """ fig is a matplotlib figure. seq is a Bio.Seq.Seq. minX: the smallest x coordinate. maxX: the largest x coordinate. featureEndpoints: an array of features as returned by addFeatures (may be empty). offsetAdjuster: a function to adjust feature X axis offsets for plotting. """ for frame in range(3): target = seq[frame:] for (codons, codonType, color) in ( (START_CODONS, 'start', 'green'), (STOP_CODONS, 'stop', 'red')): offsets = list(map(offsetAdjuster, findCodons(target, codons))) if offsets: fig.plot(offsets, np.tile(frame, len(offsets)), marker='.', markersize=4, color=color, linestyle='None') fig.axis([minX, maxX, -1, 3]) fig.set_yticks(np.arange(3)) fig.set_ylabel('Frame', fontsize=17) fig.set_title('Subject start (%s) and stop (%s) codons' % ( ', '.join(sorted(START_CODONS)), ', '.join(sorted(STOP_CODONS))), fontsize=20)
python
def addORFs(fig, seq, minX, maxX, offsetAdjuster): """ fig is a matplotlib figure. seq is a Bio.Seq.Seq. minX: the smallest x coordinate. maxX: the largest x coordinate. featureEndpoints: an array of features as returned by addFeatures (may be empty). offsetAdjuster: a function to adjust feature X axis offsets for plotting. """ for frame in range(3): target = seq[frame:] for (codons, codonType, color) in ( (START_CODONS, 'start', 'green'), (STOP_CODONS, 'stop', 'red')): offsets = list(map(offsetAdjuster, findCodons(target, codons))) if offsets: fig.plot(offsets, np.tile(frame, len(offsets)), marker='.', markersize=4, color=color, linestyle='None') fig.axis([minX, maxX, -1, 3]) fig.set_yticks(np.arange(3)) fig.set_ylabel('Frame', fontsize=17) fig.set_title('Subject start (%s) and stop (%s) codons' % ( ', '.join(sorted(START_CODONS)), ', '.join(sorted(STOP_CODONS))), fontsize=20)
[ "def", "addORFs", "(", "fig", ",", "seq", ",", "minX", ",", "maxX", ",", "offsetAdjuster", ")", ":", "for", "frame", "in", "range", "(", "3", ")", ":", "target", "=", "seq", "[", "frame", ":", "]", "for", "(", "codons", ",", "codonType", ",", "co...
fig is a matplotlib figure. seq is a Bio.Seq.Seq. minX: the smallest x coordinate. maxX: the largest x coordinate. featureEndpoints: an array of features as returned by addFeatures (may be empty). offsetAdjuster: a function to adjust feature X axis offsets for plotting.
[ "fig", "is", "a", "matplotlib", "figure", ".", "seq", "is", "a", "Bio", ".", "Seq", ".", "Seq", ".", "minX", ":", "the", "smallest", "x", "coordinate", ".", "maxX", ":", "the", "largest", "x", "coordinate", ".", "featureEndpoints", ":", "an", "array", ...
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/orfs.py#L25-L50
acorg/dark-matter
bin/compare-sequences.py
needle
def needle(reads): """ Run a Needleman-Wunsch alignment and return the two sequences. @param reads: An iterable of two reads. @return: A C{Reads} instance with the two aligned sequences. """ from tempfile import mkdtemp from shutil import rmtree dir = mkdtemp() file1 = join(dir, 'file1.fasta') with open(file1, 'w') as fp: print(reads[0].toString('fasta'), end='', file=fp) file2 = join(dir, 'file2.fasta') with open(file2, 'w') as fp: print(reads[1].toString('fasta'), end='', file=fp) out = join(dir, 'result.fasta') Executor().execute("needle -asequence '%s' -bsequence '%s' -auto " "-outfile '%s' -aformat fasta" % ( file1, file2, out)) # Use 'list' in the following to force reading the FASTA from disk. result = Reads(list(FastaReads(out))) rmtree(dir) return result
python
def needle(reads): """ Run a Needleman-Wunsch alignment and return the two sequences. @param reads: An iterable of two reads. @return: A C{Reads} instance with the two aligned sequences. """ from tempfile import mkdtemp from shutil import rmtree dir = mkdtemp() file1 = join(dir, 'file1.fasta') with open(file1, 'w') as fp: print(reads[0].toString('fasta'), end='', file=fp) file2 = join(dir, 'file2.fasta') with open(file2, 'w') as fp: print(reads[1].toString('fasta'), end='', file=fp) out = join(dir, 'result.fasta') Executor().execute("needle -asequence '%s' -bsequence '%s' -auto " "-outfile '%s' -aformat fasta" % ( file1, file2, out)) # Use 'list' in the following to force reading the FASTA from disk. result = Reads(list(FastaReads(out))) rmtree(dir) return result
[ "def", "needle", "(", "reads", ")", ":", "from", "tempfile", "import", "mkdtemp", "from", "shutil", "import", "rmtree", "dir", "=", "mkdtemp", "(", ")", "file1", "=", "join", "(", "dir", ",", "'file1.fasta'", ")", "with", "open", "(", "file1", ",", "'w...
Run a Needleman-Wunsch alignment and return the two sequences. @param reads: An iterable of two reads. @return: A C{Reads} instance with the two aligned sequences.
[ "Run", "a", "Needleman", "-", "Wunsch", "alignment", "and", "return", "the", "two", "sequences", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/compare-sequences.py#L18-L48
vovanec/httputil
httputil/httputil.py
read_until
def read_until(stream, delimiter, max_bytes=16): """Read until we have found the given delimiter. :param file stream: readable file-like object. :param bytes delimiter: delimiter string. :param int max_bytes: maximum bytes to read. :rtype: bytes|None """ buf = bytearray() delim_len = len(delimiter) while len(buf) < max_bytes: c = stream.read(1) if not c: break buf += c if buf[-delim_len:] == delimiter: return bytes(buf[:-delim_len])
python
def read_until(stream, delimiter, max_bytes=16): """Read until we have found the given delimiter. :param file stream: readable file-like object. :param bytes delimiter: delimiter string. :param int max_bytes: maximum bytes to read. :rtype: bytes|None """ buf = bytearray() delim_len = len(delimiter) while len(buf) < max_bytes: c = stream.read(1) if not c: break buf += c if buf[-delim_len:] == delimiter: return bytes(buf[:-delim_len])
[ "def", "read_until", "(", "stream", ",", "delimiter", ",", "max_bytes", "=", "16", ")", ":", "buf", "=", "bytearray", "(", ")", "delim_len", "=", "len", "(", "delimiter", ")", "while", "len", "(", "buf", ")", "<", "max_bytes", ":", "c", "=", "stream"...
Read until we have found the given delimiter. :param file stream: readable file-like object. :param bytes delimiter: delimiter string. :param int max_bytes: maximum bytes to read. :rtype: bytes|None
[ "Read", "until", "we", "have", "found", "the", "given", "delimiter", "." ]
train
https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/httputil.py#L94-L115
vovanec/httputil
httputil/httputil.py
dechunk
def dechunk(stream): """De-chunk HTTP body stream. :param file stream: readable file-like object. :rtype: __generator[bytes] :raise: DechunkError """ # TODO(vovan): Add support for chunk extensions: # TODO(vovan): http://tools.ietf.org/html/rfc2616#section-3.6.1 while True: chunk_len = read_until(stream, b'\r\n') if chunk_len is None: raise DechunkError( 'Could not extract chunk size: unexpected end of data.') try: chunk_len = int(chunk_len.strip(), 16) except (ValueError, TypeError) as err: raise DechunkError('Could not parse chunk size: %s' % (err,)) if chunk_len == 0: break bytes_to_read = chunk_len while bytes_to_read: chunk = stream.read(bytes_to_read) bytes_to_read -= len(chunk) yield chunk # chunk ends with \r\n crlf = stream.read(2) if crlf != b'\r\n': raise DechunkError('No CR+LF at the end of chunk!')
python
def dechunk(stream): """De-chunk HTTP body stream. :param file stream: readable file-like object. :rtype: __generator[bytes] :raise: DechunkError """ # TODO(vovan): Add support for chunk extensions: # TODO(vovan): http://tools.ietf.org/html/rfc2616#section-3.6.1 while True: chunk_len = read_until(stream, b'\r\n') if chunk_len is None: raise DechunkError( 'Could not extract chunk size: unexpected end of data.') try: chunk_len = int(chunk_len.strip(), 16) except (ValueError, TypeError) as err: raise DechunkError('Could not parse chunk size: %s' % (err,)) if chunk_len == 0: break bytes_to_read = chunk_len while bytes_to_read: chunk = stream.read(bytes_to_read) bytes_to_read -= len(chunk) yield chunk # chunk ends with \r\n crlf = stream.read(2) if crlf != b'\r\n': raise DechunkError('No CR+LF at the end of chunk!')
[ "def", "dechunk", "(", "stream", ")", ":", "# TODO(vovan): Add support for chunk extensions:", "# TODO(vovan): http://tools.ietf.org/html/rfc2616#section-3.6.1", "while", "True", ":", "chunk_len", "=", "read_until", "(", "stream", ",", "b'\\r\\n'", ")", "if", "chunk_len", "...
De-chunk HTTP body stream. :param file stream: readable file-like object. :rtype: __generator[bytes] :raise: DechunkError
[ "De", "-", "chunk", "HTTP", "body", "stream", "." ]
train
https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/httputil.py#L118-L154
vovanec/httputil
httputil/httputil.py
to_chunks
def to_chunks(stream_or_generator): """This generator function receives file-like or generator as input and returns generator. :param file|__generator[bytes] stream_or_generator: readable stream or generator. :rtype: __generator[bytes] :raise: TypeError """ if isinstance(stream_or_generator, types.GeneratorType): yield from stream_or_generator elif hasattr(stream_or_generator, 'read'): while True: chunk = stream_or_generator.read(CHUNK_SIZE) if not chunk: break # no more data yield chunk else: raise TypeError('Input must be either readable or generator.')
python
def to_chunks(stream_or_generator): """This generator function receives file-like or generator as input and returns generator. :param file|__generator[bytes] stream_or_generator: readable stream or generator. :rtype: __generator[bytes] :raise: TypeError """ if isinstance(stream_or_generator, types.GeneratorType): yield from stream_or_generator elif hasattr(stream_or_generator, 'read'): while True: chunk = stream_or_generator.read(CHUNK_SIZE) if not chunk: break # no more data yield chunk else: raise TypeError('Input must be either readable or generator.')
[ "def", "to_chunks", "(", "stream_or_generator", ")", ":", "if", "isinstance", "(", "stream_or_generator", ",", "types", ".", "GeneratorType", ")", ":", "yield", "from", "stream_or_generator", "elif", "hasattr", "(", "stream_or_generator", ",", "'read'", ")", ":", ...
This generator function receives file-like or generator as input and returns generator. :param file|__generator[bytes] stream_or_generator: readable stream or generator. :rtype: __generator[bytes] :raise: TypeError
[ "This", "generator", "function", "receives", "file", "-", "like", "or", "generator", "as", "input", "and", "returns", "generator", "." ]
train
https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/httputil.py#L157-L180
vovanec/httputil
httputil/httputil.py
decompress
def decompress(chunks, compression): """Decompress :param __generator[bytes] chunks: compressed body chunks. :param str compression: compression constant. :rtype: __generator[bytes] :return: decompressed chunks. :raise: TypeError, DecompressError """ if compression not in SUPPORTED_COMPRESSIONS: raise TypeError('Unsupported compression type: %s' % (compression,)) de_compressor = DECOMPRESSOR_FACTORIES[compression]() try: for chunk in chunks: try: yield de_compressor.decompress(chunk) except OSError as err: # BZ2Decompressor: invalid data stream raise DecompressError(err) from None # BZ2Decompressor does not support flush() method. if hasattr(de_compressor, 'flush'): yield de_compressor.flush() except zlib.error as err: raise DecompressError(err) from None
python
def decompress(chunks, compression): """Decompress :param __generator[bytes] chunks: compressed body chunks. :param str compression: compression constant. :rtype: __generator[bytes] :return: decompressed chunks. :raise: TypeError, DecompressError """ if compression not in SUPPORTED_COMPRESSIONS: raise TypeError('Unsupported compression type: %s' % (compression,)) de_compressor = DECOMPRESSOR_FACTORIES[compression]() try: for chunk in chunks: try: yield de_compressor.decompress(chunk) except OSError as err: # BZ2Decompressor: invalid data stream raise DecompressError(err) from None # BZ2Decompressor does not support flush() method. if hasattr(de_compressor, 'flush'): yield de_compressor.flush() except zlib.error as err: raise DecompressError(err) from None
[ "def", "decompress", "(", "chunks", ",", "compression", ")", ":", "if", "compression", "not", "in", "SUPPORTED_COMPRESSIONS", ":", "raise", "TypeError", "(", "'Unsupported compression type: %s'", "%", "(", "compression", ",", ")", ")", "de_compressor", "=", "DECOM...
Decompress :param __generator[bytes] chunks: compressed body chunks. :param str compression: compression constant. :rtype: __generator[bytes] :return: decompressed chunks. :raise: TypeError, DecompressError
[ "Decompress" ]
train
https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/httputil.py#L183-L212
vovanec/httputil
httputil/httputil.py
read_body_stream
def read_body_stream(stream, chunked=False, compression=None): """Read HTTP body stream, yielding blocks of bytes. De-chunk and de-compress data if needed. :param file stream: readable stream. :param bool chunked: whether stream is chunked. :param str|None compression: compression type is stream is compressed, otherwise None. :rtype: __generator[bytes] :raise: TypeError, BodyStreamError """ if not (chunked or compression): return to_chunks(stream) generator = stream if chunked: generator = dechunk(generator) if compression: generator = decompress(to_chunks(generator), compression) return generator
python
def read_body_stream(stream, chunked=False, compression=None): """Read HTTP body stream, yielding blocks of bytes. De-chunk and de-compress data if needed. :param file stream: readable stream. :param bool chunked: whether stream is chunked. :param str|None compression: compression type is stream is compressed, otherwise None. :rtype: __generator[bytes] :raise: TypeError, BodyStreamError """ if not (chunked or compression): return to_chunks(stream) generator = stream if chunked: generator = dechunk(generator) if compression: generator = decompress(to_chunks(generator), compression) return generator
[ "def", "read_body_stream", "(", "stream", ",", "chunked", "=", "False", ",", "compression", "=", "None", ")", ":", "if", "not", "(", "chunked", "or", "compression", ")", ":", "return", "to_chunks", "(", "stream", ")", "generator", "=", "stream", "if", "c...
Read HTTP body stream, yielding blocks of bytes. De-chunk and de-compress data if needed. :param file stream: readable stream. :param bool chunked: whether stream is chunked. :param str|None compression: compression type is stream is compressed, otherwise None. :rtype: __generator[bytes] :raise: TypeError, BodyStreamError
[ "Read", "HTTP", "body", "stream", "yielding", "blocks", "of", "bytes", ".", "De", "-", "chunk", "and", "de", "-", "compress", "data", "if", "needed", "." ]
train
https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/httputil.py#L215-L238
vovanec/httputil
httputil/httputil.py
DeflateDecompressor.decompress
def decompress(self, chunk): """Decompress the chunk of data. :param bytes chunk: data chunk :rtype: bytes """ try: return self._decompressobj.decompress(chunk) except zlib.error: # ugly hack to work with raw deflate content that may # be sent by microsoft servers. For more information, see: # http://carsten.codimi.de/gzip.yaws/ # http://www.port80software.com/200ok/archive/2005/10/31/868.aspx # http://www.gzip.org/zlib/zlib_faq.html#faq38 if self._first_chunk: self._decompressobj = zlib.decompressobj(-zlib.MAX_WBITS) return self._decompressobj.decompress(chunk) raise finally: self._first_chunk = False
python
def decompress(self, chunk): """Decompress the chunk of data. :param bytes chunk: data chunk :rtype: bytes """ try: return self._decompressobj.decompress(chunk) except zlib.error: # ugly hack to work with raw deflate content that may # be sent by microsoft servers. For more information, see: # http://carsten.codimi.de/gzip.yaws/ # http://www.port80software.com/200ok/archive/2005/10/31/868.aspx # http://www.gzip.org/zlib/zlib_faq.html#faq38 if self._first_chunk: self._decompressobj = zlib.decompressobj(-zlib.MAX_WBITS) return self._decompressobj.decompress(chunk) raise finally: self._first_chunk = False
[ "def", "decompress", "(", "self", ",", "chunk", ")", ":", "try", ":", "return", "self", ".", "_decompressobj", ".", "decompress", "(", "chunk", ")", "except", "zlib", ".", "error", ":", "# ugly hack to work with raw deflate content that may", "# be sent by microsoft...
Decompress the chunk of data. :param bytes chunk: data chunk :rtype: bytes
[ "Decompress", "the", "chunk", "of", "data", "." ]
train
https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/httputil.py#L31-L53
acorg/dark-matter
bin/compare-consensuses.py
makeOuputDir
def makeOuputDir(outputDir, force): """ Create or check for an output directory. @param outputDir: A C{str} output directory name, or C{None}. @param force: If C{True}, allow overwriting of pre-existing files. @return: The C{str} output directory name. """ if outputDir: if exists(outputDir): if not force: print('Will not overwrite pre-existing files. Use --force to ' 'make me.', file=sys.stderr) sys.exit(1) else: mkdir(outputDir) else: outputDir = mkdtemp() print('Writing output files to %s' % outputDir) return outputDir
python
def makeOuputDir(outputDir, force): """ Create or check for an output directory. @param outputDir: A C{str} output directory name, or C{None}. @param force: If C{True}, allow overwriting of pre-existing files. @return: The C{str} output directory name. """ if outputDir: if exists(outputDir): if not force: print('Will not overwrite pre-existing files. Use --force to ' 'make me.', file=sys.stderr) sys.exit(1) else: mkdir(outputDir) else: outputDir = mkdtemp() print('Writing output files to %s' % outputDir) return outputDir
[ "def", "makeOuputDir", "(", "outputDir", ",", "force", ")", ":", "if", "outputDir", ":", "if", "exists", "(", "outputDir", ")", ":", "if", "not", "force", ":", "print", "(", "'Will not overwrite pre-existing files. Use --force to '", "'make me.'", ",", "file", "...
Create or check for an output directory. @param outputDir: A C{str} output directory name, or C{None}. @param force: If C{True}, allow overwriting of pre-existing files. @return: The C{str} output directory name.
[ "Create", "or", "check", "for", "an", "output", "directory", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/compare-consensuses.py#L14-L34
acorg/dark-matter
bin/compare-consensuses.py
samtoolsMpileup
def samtoolsMpileup(outFile, referenceFile, alignmentFile, executor): """ Use samtools mpileup to generate VCF. @param outFile: The C{str} name to write the output to. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param alignmentFile: The C{str} name of the SAM or BAM alignment file. @param executor: An C{Executor} instance. """ executor.execute( 'samtools mpileup -u -v -f %s %s > %s' % (referenceFile, alignmentFile, outFile))
python
def samtoolsMpileup(outFile, referenceFile, alignmentFile, executor): """ Use samtools mpileup to generate VCF. @param outFile: The C{str} name to write the output to. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param alignmentFile: The C{str} name of the SAM or BAM alignment file. @param executor: An C{Executor} instance. """ executor.execute( 'samtools mpileup -u -v -f %s %s > %s' % (referenceFile, alignmentFile, outFile))
[ "def", "samtoolsMpileup", "(", "outFile", ",", "referenceFile", ",", "alignmentFile", ",", "executor", ")", ":", "executor", ".", "execute", "(", "'samtools mpileup -u -v -f %s %s > %s'", "%", "(", "referenceFile", ",", "alignmentFile", ",", "outFile", ")", ")" ]
Use samtools mpileup to generate VCF. @param outFile: The C{str} name to write the output to. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param alignmentFile: The C{str} name of the SAM or BAM alignment file. @param executor: An C{Executor} instance.
[ "Use", "samtools", "mpileup", "to", "generate", "VCF", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/compare-consensuses.py#L37-L49
acorg/dark-matter
bin/compare-consensuses.py
bcftoolsMpileup
def bcftoolsMpileup(outFile, referenceFile, alignmentFile, executor): """ Use bcftools mpileup to generate VCF. @param outFile: The C{str} name to write the output to. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param alignmentFile: The C{str} name of the SAM or BAM alignment file. @param executor: An C{Executor} instance. """ executor.execute( 'bcftools mpileup -Ov -f %s %s > %s' % (referenceFile, alignmentFile, outFile))
python
def bcftoolsMpileup(outFile, referenceFile, alignmentFile, executor): """ Use bcftools mpileup to generate VCF. @param outFile: The C{str} name to write the output to. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param alignmentFile: The C{str} name of the SAM or BAM alignment file. @param executor: An C{Executor} instance. """ executor.execute( 'bcftools mpileup -Ov -f %s %s > %s' % (referenceFile, alignmentFile, outFile))
[ "def", "bcftoolsMpileup", "(", "outFile", ",", "referenceFile", ",", "alignmentFile", ",", "executor", ")", ":", "executor", ".", "execute", "(", "'bcftools mpileup -Ov -f %s %s > %s'", "%", "(", "referenceFile", ",", "alignmentFile", ",", "outFile", ")", ")" ]
Use bcftools mpileup to generate VCF. @param outFile: The C{str} name to write the output to. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param alignmentFile: The C{str} name of the SAM or BAM alignment file. @param executor: An C{Executor} instance.
[ "Use", "bcftools", "mpileup", "to", "generate", "VCF", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/compare-consensuses.py#L52-L64
acorg/dark-matter
bin/compare-consensuses.py
bcftoolsConsensus
def bcftoolsConsensus(outFile, vcfFile, id_, referenceFile, executor): """ Use bcftools to extract consensus FASTA. @param outFile: The C{str} name to write the output to. @param vcfFile: The C{str} name of the VCF file with the calls from the pileup. @param id_: The C{str} identifier to use in the resulting FASTA sequence. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param executor: An C{Executor} instance. """ bgz = vcfFile + '.gz' executor.execute('bgzip -c %s > %s' % (vcfFile, bgz)) executor.execute('tabix %s' % bgz) executor.execute( 'bcftools consensus %s < %s | ' 'filter-fasta.py --idLambda \'lambda id: "%s"\' > %s' % (bgz, referenceFile, id_, outFile))
python
def bcftoolsConsensus(outFile, vcfFile, id_, referenceFile, executor): """ Use bcftools to extract consensus FASTA. @param outFile: The C{str} name to write the output to. @param vcfFile: The C{str} name of the VCF file with the calls from the pileup. @param id_: The C{str} identifier to use in the resulting FASTA sequence. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param executor: An C{Executor} instance. """ bgz = vcfFile + '.gz' executor.execute('bgzip -c %s > %s' % (vcfFile, bgz)) executor.execute('tabix %s' % bgz) executor.execute( 'bcftools consensus %s < %s | ' 'filter-fasta.py --idLambda \'lambda id: "%s"\' > %s' % (bgz, referenceFile, id_, outFile))
[ "def", "bcftoolsConsensus", "(", "outFile", ",", "vcfFile", ",", "id_", ",", "referenceFile", ",", "executor", ")", ":", "bgz", "=", "vcfFile", "+", "'.gz'", "executor", ".", "execute", "(", "'bgzip -c %s > %s'", "%", "(", "vcfFile", ",", "bgz", ")", ")", ...
Use bcftools to extract consensus FASTA. @param outFile: The C{str} name to write the output to. @param vcfFile: The C{str} name of the VCF file with the calls from the pileup. @param id_: The C{str} identifier to use in the resulting FASTA sequence. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param executor: An C{Executor} instance.
[ "Use", "bcftools", "to", "extract", "consensus", "FASTA", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/compare-consensuses.py#L95-L113
acorg/dark-matter
bin/compare-consensuses.py
vcfutilsConsensus
def vcfutilsConsensus(outFile, vcfFile, id_, _, executor): """ Use vcftools to extract consensus FASTA. @param outFile: The C{str} name to write the output to. @param vcfFile: The C{str} name of the VCF file with the calls from the pileup. @param id_: The C{str} identifier to use in the resulting FASTA sequence. @param executor: An C{Executor} instance. """ executor.execute( 'vcfutils.pl vcf2fq < %s | ' 'filter-fasta.py --fastq --quiet --saveAs fasta ' '--idLambda \'lambda id: "%s"\' > %s' % (vcfFile, id_, outFile))
python
def vcfutilsConsensus(outFile, vcfFile, id_, _, executor): """ Use vcftools to extract consensus FASTA. @param outFile: The C{str} name to write the output to. @param vcfFile: The C{str} name of the VCF file with the calls from the pileup. @param id_: The C{str} identifier to use in the resulting FASTA sequence. @param executor: An C{Executor} instance. """ executor.execute( 'vcfutils.pl vcf2fq < %s | ' 'filter-fasta.py --fastq --quiet --saveAs fasta ' '--idLambda \'lambda id: "%s"\' > %s' % (vcfFile, id_, outFile))
[ "def", "vcfutilsConsensus", "(", "outFile", ",", "vcfFile", ",", "id_", ",", "_", ",", "executor", ")", ":", "executor", ".", "execute", "(", "'vcfutils.pl vcf2fq < %s | '", "'filter-fasta.py --fastq --quiet --saveAs fasta '", "'--idLambda \\'lambda id: \"%s\"\\' > %s'", "%...
Use vcftools to extract consensus FASTA. @param outFile: The C{str} name to write the output to. @param vcfFile: The C{str} name of the VCF file with the calls from the pileup. @param id_: The C{str} identifier to use in the resulting FASTA sequence. @param executor: An C{Executor} instance.
[ "Use", "vcftools", "to", "extract", "consensus", "FASTA", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/compare-consensuses.py#L116-L130
acorg/dark-matter
dark/baseimage.py
BaseImage.set
def set(self, x, y, value): """ Set the data at (x, y) to value. """ xBase = int(x) * self.xScale yBase = int(y) * self.yScale for xOffset in range(self.xScale): for yOffset in range(self.yScale): self.data[yBase + yOffset, xBase + xOffset] = value
python
def set(self, x, y, value): """ Set the data at (x, y) to value. """ xBase = int(x) * self.xScale yBase = int(y) * self.yScale for xOffset in range(self.xScale): for yOffset in range(self.yScale): self.data[yBase + yOffset, xBase + xOffset] = value
[ "def", "set", "(", "self", ",", "x", ",", "y", ",", "value", ")", ":", "xBase", "=", "int", "(", "x", ")", "*", "self", ".", "xScale", "yBase", "=", "int", "(", "y", ")", "*", "self", ".", "yScale", "for", "xOffset", "in", "range", "(", "self...
Set the data at (x, y) to value.
[ "Set", "the", "data", "at", "(", "x", "y", ")", "to", "value", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/baseimage.py#L17-L25
flo-compbio/genometools
genometools/cli.py
get_argument_parser
def get_argument_parser(prog=None, desc=None, formatter_class=None): """Create an argument parser. Parameters ---------- prog: str The program name. desc: str The program description. formatter_class: argparse formatter class, optional The argparse formatter class to use. Returns ------- `argparse.ArgumentParser` The arguemnt parser created. """ if formatter_class is None: formatter_class = argparse.RawTextHelpFormatter parser = argparse.ArgumentParser( prog=prog, description=desc, formatter_class=formatter_class, add_help=False ) g = parser.add_argument_group('Help') g.add_argument('-h', '--help', action='help', help='Show this help message and exit.') v = genometools.__version__ g.add_argument('--version', action='version', version='GenomeTools ' + v, help='Output the GenomeTools version and exit.') return parser
python
def get_argument_parser(prog=None, desc=None, formatter_class=None): """Create an argument parser. Parameters ---------- prog: str The program name. desc: str The program description. formatter_class: argparse formatter class, optional The argparse formatter class to use. Returns ------- `argparse.ArgumentParser` The arguemnt parser created. """ if formatter_class is None: formatter_class = argparse.RawTextHelpFormatter parser = argparse.ArgumentParser( prog=prog, description=desc, formatter_class=formatter_class, add_help=False ) g = parser.add_argument_group('Help') g.add_argument('-h', '--help', action='help', help='Show this help message and exit.') v = genometools.__version__ g.add_argument('--version', action='version', version='GenomeTools ' + v, help='Output the GenomeTools version and exit.') return parser
[ "def", "get_argument_parser", "(", "prog", "=", "None", ",", "desc", "=", "None", ",", "formatter_class", "=", "None", ")", ":", "if", "formatter_class", "is", "None", ":", "formatter_class", "=", "argparse", ".", "RawTextHelpFormatter", "parser", "=", "argpar...
Create an argument parser. Parameters ---------- prog: str The program name. desc: str The program description. formatter_class: argparse formatter class, optional The argparse formatter class to use. Returns ------- `argparse.ArgumentParser` The arguemnt parser created.
[ "Create", "an", "argument", "parser", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/cli.py#L53-L86
flo-compbio/genometools
genometools/cli.py
add_reporting_args
def add_reporting_args(parser): """Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created. """ g = parser.add_argument_group('Reporting options') g.add_argument( '-l', '--log-file', default=None, type=str, metavar=file_mv, help='Path of log file (if specified, report to stdout AND file.' ) g.add_argument('-q', '--quiet', action='store_true', help='Only output errors and warnings.') g.add_argument( '-v', '--verbose', action='store_true', help='Enable verbose output. Ignored if --quiet is specified.' ) return g
python
def add_reporting_args(parser): """Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created. """ g = parser.add_argument_group('Reporting options') g.add_argument( '-l', '--log-file', default=None, type=str, metavar=file_mv, help='Path of log file (if specified, report to stdout AND file.' ) g.add_argument('-q', '--quiet', action='store_true', help='Only output errors and warnings.') g.add_argument( '-v', '--verbose', action='store_true', help='Enable verbose output. Ignored if --quiet is specified.' ) return g
[ "def", "add_reporting_args", "(", "parser", ")", ":", "g", "=", "parser", ".", "add_argument_group", "(", "'Reporting options'", ")", "g", ".", "add_argument", "(", "'-l'", ",", "'--log-file'", ",", "default", "=", "None", ",", "type", "=", "str", ",", "me...
Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created.
[ "Add", "reporting", "arguments", "to", "an", "argument", "parser", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/cli.py#L89-L117
shmir/PyIxExplorer
ixexplorer/ixe_hw.py
IxeCard.get_resource_groups
def get_resource_groups(self): """ :return: dictionary {resource group id: object} of all resource groups. """ resource_groups = {r.index: r for r in self.get_objects_by_type('resourceGroupEx')} return OrderedDict(sorted(resource_groups.items()))
python
def get_resource_groups(self): """ :return: dictionary {resource group id: object} of all resource groups. """ resource_groups = {r.index: r for r in self.get_objects_by_type('resourceGroupEx')} return OrderedDict(sorted(resource_groups.items()))
[ "def", "get_resource_groups", "(", "self", ")", ":", "resource_groups", "=", "{", "r", ".", "index", ":", "r", "for", "r", "in", "self", ".", "get_objects_by_type", "(", "'resourceGroupEx'", ")", "}", "return", "OrderedDict", "(", "sorted", "(", "resource_gr...
:return: dictionary {resource group id: object} of all resource groups.
[ ":", "return", ":", "dictionary", "{", "resource", "group", "id", ":", "object", "}", "of", "all", "resource", "groups", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_hw.py#L92-L98
shmir/PyIxExplorer
ixexplorer/ixe_hw.py
IxeCard.get_active_ports
def get_active_ports(self): """ :return: dictionary {index: object} of all ports. """ if not self.resource_groups: return self.ports else: active_ports = OrderedDict() for resource_group in self.resource_groups.values(): for active_port in resource_group.active_ports: active_ports[active_port] = self.ports[active_port] return active_ports
python
def get_active_ports(self): """ :return: dictionary {index: object} of all ports. """ if not self.resource_groups: return self.ports else: active_ports = OrderedDict() for resource_group in self.resource_groups.values(): for active_port in resource_group.active_ports: active_ports[active_port] = self.ports[active_port] return active_ports
[ "def", "get_active_ports", "(", "self", ")", ":", "if", "not", "self", ".", "resource_groups", ":", "return", "self", ".", "ports", "else", ":", "active_ports", "=", "OrderedDict", "(", ")", "for", "resource_group", "in", "self", ".", "resource_groups", ".",...
:return: dictionary {index: object} of all ports.
[ ":", "return", ":", "dictionary", "{", "index", ":", "object", "}", "of", "all", "ports", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_hw.py#L101-L113
shmir/PyIxExplorer
ixexplorer/ixe_hw.py
IxeResourceGroup.enable_capture_state
def enable_capture_state(self, state, writeToHw=False): """ Enable/Disable capture on resource group """ if state: activePorts = self.rePortInList.findall(self.activePortList) self.activeCapturePortList = "{{" + activePorts[0] + "}}" else: self.activeCapturePortList = "{{""}}" if (writeToHw): self.ix_command('write')
python
def enable_capture_state(self, state, writeToHw=False): """ Enable/Disable capture on resource group """ if state: activePorts = self.rePortInList.findall(self.activePortList) self.activeCapturePortList = "{{" + activePorts[0] + "}}" else: self.activeCapturePortList = "{{""}}" if (writeToHw): self.ix_command('write')
[ "def", "enable_capture_state", "(", "self", ",", "state", ",", "writeToHw", "=", "False", ")", ":", "if", "state", ":", "activePorts", "=", "self", ".", "rePortInList", ".", "findall", "(", "self", ".", "activePortList", ")", "self", ".", "activeCapturePortL...
Enable/Disable capture on resource group
[ "Enable", "/", "Disable", "capture", "on", "resource", "group" ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_hw.py#L272-L282
openfisca/openfisca-web-api
openfisca_web_api/contexts.py
Ctx.get_containing
def get_containing(self, name, depth = 0): """Return the n-th (n = ``depth``) context containing attribute named ``name``.""" ctx_dict = object.__getattribute__(self, '__dict__') if name in ctx_dict: if depth <= 0: return self depth -= 1 parent = ctx_dict.get('_parent') if parent is None: return None return parent.get_containing(name, depth = depth)
python
def get_containing(self, name, depth = 0): """Return the n-th (n = ``depth``) context containing attribute named ``name``.""" ctx_dict = object.__getattribute__(self, '__dict__') if name in ctx_dict: if depth <= 0: return self depth -= 1 parent = ctx_dict.get('_parent') if parent is None: return None return parent.get_containing(name, depth = depth)
[ "def", "get_containing", "(", "self", ",", "name", ",", "depth", "=", "0", ")", ":", "ctx_dict", "=", "object", ".", "__getattribute__", "(", "self", ",", "'__dict__'", ")", "if", "name", "in", "ctx_dict", ":", "if", "depth", "<=", "0", ":", "return", ...
Return the n-th (n = ``depth``) context containing attribute named ``name``.
[ "Return", "the", "n", "-", "th", "(", "n", "=", "depth", ")", "context", "containing", "attribute", "named", "name", "." ]
train
https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/contexts.py#L62-L72
openfisca/openfisca-web-api
openfisca_web_api/contexts.py
Ctx.translator
def translator(self): """Get a valid translator object from one or several languages names.""" if self._translator is None: languages = self.lang if not languages: return gettext.NullTranslations() if not isinstance(languages, list): languages = [languages] translator = gettext.NullTranslations() for name, i18n_dir in [ ( 'biryani', os.path.join(pkg_resources.get_distribution('biryani').location, 'biryani', 'i18n'), ), ( conf['country_package'].replace('_', '-'), os.path.join(pkg_resources.get_distribution(conf['country_package']).location, conf['country_package'], 'i18n'), ), ]: if i18n_dir is not None: translator = new_translator(name, i18n_dir, languages, fallback = translator) translator = new_translator(conf['package_name'], conf['i18n_dir'], languages, fallback = translator) self._translator = translator return self._translator
python
def translator(self): """Get a valid translator object from one or several languages names.""" if self._translator is None: languages = self.lang if not languages: return gettext.NullTranslations() if not isinstance(languages, list): languages = [languages] translator = gettext.NullTranslations() for name, i18n_dir in [ ( 'biryani', os.path.join(pkg_resources.get_distribution('biryani').location, 'biryani', 'i18n'), ), ( conf['country_package'].replace('_', '-'), os.path.join(pkg_resources.get_distribution(conf['country_package']).location, conf['country_package'], 'i18n'), ), ]: if i18n_dir is not None: translator = new_translator(name, i18n_dir, languages, fallback = translator) translator = new_translator(conf['package_name'], conf['i18n_dir'], languages, fallback = translator) self._translator = translator return self._translator
[ "def", "translator", "(", "self", ")", ":", "if", "self", ".", "_translator", "is", "None", ":", "languages", "=", "self", ".", "lang", "if", "not", "languages", ":", "return", "gettext", ".", "NullTranslations", "(", ")", "if", "not", "isinstance", "(",...
Get a valid translator object from one or several languages names.
[ "Get", "a", "valid", "translator", "object", "from", "one", "or", "several", "languages", "names", "." ]
train
https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/contexts.py#L141-L165
acorg/dark-matter
dark/taxonomy.py
LineageFetcher.lineage
def lineage(self, title): """ Get lineage information from the taxonomy database for a given title. @param title: A C{str} sequence title (e.g., from a BLAST hit). Of the form 'gi|63148399|gb|DQ011818.1| Description...'. It is the gi number (63148399 in this example) that is looked up in the taxonomy database. @return: A C{list} of the taxonomic categories of the title. Each list element is an (C{int}, C{str}) 2-tuple, giving a taxonomy id and a scientific name. The first element in the list will correspond to C{title}, and each successive element is the parent of the preceeding one. If no taxonomy is found, the returned list will be empty. """ if title in self._cache: return self._cache[title] lineage = [] gi = int(title.split('|')[1]) query = 'SELECT taxID from gi_taxid where gi = %d' % gi try: while True: self._cursor.execute(query) taxID = self._cursor.fetchone()[0] if taxID == 1: break query = 'SELECT name from names where taxId = %s' % taxID self._cursor.execute(query) scientificName = self._cursor.fetchone()[0] lineage.append((taxID, scientificName)) # Move up to the parent. query = ('SELECT parent_taxID from nodes where taxID = %s' % taxID) except TypeError: lineage = [] self._cache[title] = lineage return lineage
python
def lineage(self, title): """ Get lineage information from the taxonomy database for a given title. @param title: A C{str} sequence title (e.g., from a BLAST hit). Of the form 'gi|63148399|gb|DQ011818.1| Description...'. It is the gi number (63148399 in this example) that is looked up in the taxonomy database. @return: A C{list} of the taxonomic categories of the title. Each list element is an (C{int}, C{str}) 2-tuple, giving a taxonomy id and a scientific name. The first element in the list will correspond to C{title}, and each successive element is the parent of the preceeding one. If no taxonomy is found, the returned list will be empty. """ if title in self._cache: return self._cache[title] lineage = [] gi = int(title.split('|')[1]) query = 'SELECT taxID from gi_taxid where gi = %d' % gi try: while True: self._cursor.execute(query) taxID = self._cursor.fetchone()[0] if taxID == 1: break query = 'SELECT name from names where taxId = %s' % taxID self._cursor.execute(query) scientificName = self._cursor.fetchone()[0] lineage.append((taxID, scientificName)) # Move up to the parent. query = ('SELECT parent_taxID from nodes where taxID = %s' % taxID) except TypeError: lineage = [] self._cache[title] = lineage return lineage
[ "def", "lineage", "(", "self", ",", "title", ")", ":", "if", "title", "in", "self", ".", "_cache", ":", "return", "self", ".", "_cache", "[", "title", "]", "lineage", "=", "[", "]", "gi", "=", "int", "(", "title", ".", "split", "(", "'|'", ")", ...
Get lineage information from the taxonomy database for a given title. @param title: A C{str} sequence title (e.g., from a BLAST hit). Of the form 'gi|63148399|gb|DQ011818.1| Description...'. It is the gi number (63148399 in this example) that is looked up in the taxonomy database. @return: A C{list} of the taxonomic categories of the title. Each list element is an (C{int}, C{str}) 2-tuple, giving a taxonomy id and a scientific name. The first element in the list will correspond to C{title}, and each successive element is the parent of the preceeding one. If no taxonomy is found, the returned list will be empty.
[ "Get", "lineage", "information", "from", "the", "taxonomy", "database", "for", "a", "given", "title", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/taxonomy.py#L14-L53
acorg/dark-matter
dark/taxonomy.py
LineageFetcher.close
def close(self): """ Close the database connection and render self invalid. Any subsequent re-use of self will raise an error. """ self._cursor.close() self._db.close() self._cursor = self._db = self._cache = None
python
def close(self): """ Close the database connection and render self invalid. Any subsequent re-use of self will raise an error. """ self._cursor.close() self._db.close() self._cursor = self._db = self._cache = None
[ "def", "close", "(", "self", ")", ":", "self", ".", "_cursor", ".", "close", "(", ")", "self", ".", "_db", ".", "close", "(", ")", "self", ".", "_cursor", "=", "self", ".", "_db", "=", "self", ".", "_cache", "=", "None" ]
Close the database connection and render self invalid. Any subsequent re-use of self will raise an error.
[ "Close", "the", "database", "connection", "and", "render", "self", "invalid", ".", "Any", "subsequent", "re", "-", "use", "of", "self", "will", "raise", "an", "error", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/taxonomy.py#L55-L62
invenia/Arbiter
arbiter/utils.py
retry_handler
def retry_handler(retries=0, delay=timedelta(), conditions=[]): """ A simple wrapper function that creates a handler function by using on the retry_loop function. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount time to delay between retries. conditions (list): A list of retry conditions. Returns: function: The retry_loop function partialed. """ delay_in_seconds = delay.total_seconds() return partial(retry_loop, retries, delay_in_seconds, conditions)
python
def retry_handler(retries=0, delay=timedelta(), conditions=[]): """ A simple wrapper function that creates a handler function by using on the retry_loop function. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount time to delay between retries. conditions (list): A list of retry conditions. Returns: function: The retry_loop function partialed. """ delay_in_seconds = delay.total_seconds() return partial(retry_loop, retries, delay_in_seconds, conditions)
[ "def", "retry_handler", "(", "retries", "=", "0", ",", "delay", "=", "timedelta", "(", ")", ",", "conditions", "=", "[", "]", ")", ":", "delay_in_seconds", "=", "delay", ".", "total_seconds", "(", ")", "return", "partial", "(", "retry_loop", ",", "retrie...
A simple wrapper function that creates a handler function by using on the retry_loop function. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount time to delay between retries. conditions (list): A list of retry conditions. Returns: function: The retry_loop function partialed.
[ "A", "simple", "wrapper", "function", "that", "creates", "a", "handler", "function", "by", "using", "on", "the", "retry_loop", "function", "." ]
train
https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/utils.py#L57-L71
invenia/Arbiter
arbiter/utils.py
retry
def retry(retries=0, delay=timedelta(), conditions=[]): """ A decorator for making a function that retries on failure. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount of time to delay between retries. conditions (list): A list of retry conditions. """ delay_in_seconds = delay.total_seconds() def decorator(function): """ The actual decorator for retrying. """ @wraps(function) def wrapper(*args, **kwargs): """ The actual wrapper for retrying. """ func = partial(function, *args, **kwargs) return retry_loop(retries, delay_in_seconds, conditions, func) return wrapper return decorator
python
def retry(retries=0, delay=timedelta(), conditions=[]): """ A decorator for making a function that retries on failure. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount of time to delay between retries. conditions (list): A list of retry conditions. """ delay_in_seconds = delay.total_seconds() def decorator(function): """ The actual decorator for retrying. """ @wraps(function) def wrapper(*args, **kwargs): """ The actual wrapper for retrying. """ func = partial(function, *args, **kwargs) return retry_loop(retries, delay_in_seconds, conditions, func) return wrapper return decorator
[ "def", "retry", "(", "retries", "=", "0", ",", "delay", "=", "timedelta", "(", ")", ",", "conditions", "=", "[", "]", ")", ":", "delay_in_seconds", "=", "delay", ".", "total_seconds", "(", ")", "def", "decorator", "(", "function", ")", ":", "\"\"\"\n ...
A decorator for making a function that retries on failure. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount of time to delay between retries. conditions (list): A list of retry conditions.
[ "A", "decorator", "for", "making", "a", "function", "that", "retries", "on", "failure", "." ]
train
https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/utils.py#L74-L100
invenia/Arbiter
arbiter/utils.py
retry_loop
def retry_loop(retries, delay_in_seconds, conditions, function): """ Actually performs the retry loop used by the retry decorator and handler functions. Failures for retrying are defined by the RetryConditions passed in. If the maximum number of retries has been reached then it raises the most recent error or a ValueError on the most recent result value. Args: retries (Integral): Maximum number of times to retry. delay_in_seconds (Integral): Number of seconds to wait between retries. conditions (list): A list of retry conditions the can trigger a retry on a return value or exception. function (function): The function to wrap. Returns: value: The return value from function """ if not isinstance(retries, Integral): raise TypeError(retries) if delay_in_seconds < 0: raise TypeError(delay_in_seconds) attempts = 0 value = None err = None while attempts <= retries: try: value = function() for condition in conditions: if condition.on_value(value): break else: return value except Exception as exc: err = exc for condition in conditions: if condition.on_exception(exc): break else: raise attempts += 1 sleep(delay_in_seconds) else: if err: raise err else: raise ValueError( "Max retries ({}) reached and return the value is still {}." .format(attempts, value) ) return value
python
def retry_loop(retries, delay_in_seconds, conditions, function): """ Actually performs the retry loop used by the retry decorator and handler functions. Failures for retrying are defined by the RetryConditions passed in. If the maximum number of retries has been reached then it raises the most recent error or a ValueError on the most recent result value. Args: retries (Integral): Maximum number of times to retry. delay_in_seconds (Integral): Number of seconds to wait between retries. conditions (list): A list of retry conditions the can trigger a retry on a return value or exception. function (function): The function to wrap. Returns: value: The return value from function """ if not isinstance(retries, Integral): raise TypeError(retries) if delay_in_seconds < 0: raise TypeError(delay_in_seconds) attempts = 0 value = None err = None while attempts <= retries: try: value = function() for condition in conditions: if condition.on_value(value): break else: return value except Exception as exc: err = exc for condition in conditions: if condition.on_exception(exc): break else: raise attempts += 1 sleep(delay_in_seconds) else: if err: raise err else: raise ValueError( "Max retries ({}) reached and return the value is still {}." .format(attempts, value) ) return value
[ "def", "retry_loop", "(", "retries", ",", "delay_in_seconds", ",", "conditions", ",", "function", ")", ":", "if", "not", "isinstance", "(", "retries", ",", "Integral", ")", ":", "raise", "TypeError", "(", "retries", ")", "if", "delay_in_seconds", "<", "0", ...
Actually performs the retry loop used by the retry decorator and handler functions. Failures for retrying are defined by the RetryConditions passed in. If the maximum number of retries has been reached then it raises the most recent error or a ValueError on the most recent result value. Args: retries (Integral): Maximum number of times to retry. delay_in_seconds (Integral): Number of seconds to wait between retries. conditions (list): A list of retry conditions the can trigger a retry on a return value or exception. function (function): The function to wrap. Returns: value: The return value from function
[ "Actually", "performs", "the", "retry", "loop", "used", "by", "the", "retry", "decorator", "and", "handler", "functions", ".", "Failures", "for", "retrying", "are", "defined", "by", "the", "RetryConditions", "passed", "in", ".", "If", "the", "maximum", "number...
train
https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/utils.py#L103-L158
flo-compbio/genometools
genometools/ontology/annotation.py
GOAnnotation.from_list
def from_list(cls, gene_ontology, l): """Initialize a `GOAnnotation` object from a list (in GAF2.1 order). TODO: docstring """ assert isinstance(gene_ontology, GeneOntology) assert isinstance(l, list) assert len(l) == 17 go_term = gene_ontology[l[4]] qualifier = l[3] or [] with_from = l[7] or None db_name = l[9] or None db_syn = l[10] or [] ext = l[15] or [] product_id = l[16] or None annotation = cls( db=l[0], db_id=l[1], db_symbol=l[2], go_term=go_term, db_ref=l[5], ev_code=l[6], db_type=l[11], taxon=l[12], date=l[13], assigned_by=l[14], qualifier=qualifier, with_from=with_from, db_name=db_name, db_syn=db_syn, ext=ext, product_id=product_id, ) return annotation
python
def from_list(cls, gene_ontology, l): """Initialize a `GOAnnotation` object from a list (in GAF2.1 order). TODO: docstring """ assert isinstance(gene_ontology, GeneOntology) assert isinstance(l, list) assert len(l) == 17 go_term = gene_ontology[l[4]] qualifier = l[3] or [] with_from = l[7] or None db_name = l[9] or None db_syn = l[10] or [] ext = l[15] or [] product_id = l[16] or None annotation = cls( db=l[0], db_id=l[1], db_symbol=l[2], go_term=go_term, db_ref=l[5], ev_code=l[6], db_type=l[11], taxon=l[12], date=l[13], assigned_by=l[14], qualifier=qualifier, with_from=with_from, db_name=db_name, db_syn=db_syn, ext=ext, product_id=product_id, ) return annotation
[ "def", "from_list", "(", "cls", ",", "gene_ontology", ",", "l", ")", ":", "assert", "isinstance", "(", "gene_ontology", ",", "GeneOntology", ")", "assert", "isinstance", "(", "l", ",", "list", ")", "assert", "len", "(", "l", ")", "==", "17", "go_term", ...
Initialize a `GOAnnotation` object from a list (in GAF2.1 order). TODO: docstring
[ "Initialize", "a", "GOAnnotation", "object", "from", "a", "list", "(", "in", "GAF2", ".", "1", "order", ")", ".", "TODO", ":", "docstring" ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/annotation.py#L314-L352
flo-compbio/genometools
genometools/ontology/annotation.py
GOAnnotation.as_list
def as_list(self): """Returns GO annotation as a flat list (in GAF 2.1 format order).""" go_id = self.go_term.id qual_str = '|'.join(self.qualifier) db_ref_str = '|'.join(self.db_ref) taxon_str = '|'.join(self.taxon) # with_from is currently left as a string # with_from = '|'.join() with_from_str = self.with_from or '' db_name_str = self.db_name or '' db_syn_str = '|'.join(self.db_syn) ext_str = '|'.join(self.ext) product_id_str = self.product_id or '' l = [ self.db, self.db_id, self.db_symbol, qual_str, go_id, db_ref_str, self.ev_code, with_from_str, self.aspect, db_name_str, db_syn_str, self.db_type, taxon_str, self.date, self.assigned_by, ext_str, product_id_str, ] return l
python
def as_list(self): """Returns GO annotation as a flat list (in GAF 2.1 format order).""" go_id = self.go_term.id qual_str = '|'.join(self.qualifier) db_ref_str = '|'.join(self.db_ref) taxon_str = '|'.join(self.taxon) # with_from is currently left as a string # with_from = '|'.join() with_from_str = self.with_from or '' db_name_str = self.db_name or '' db_syn_str = '|'.join(self.db_syn) ext_str = '|'.join(self.ext) product_id_str = self.product_id or '' l = [ self.db, self.db_id, self.db_symbol, qual_str, go_id, db_ref_str, self.ev_code, with_from_str, self.aspect, db_name_str, db_syn_str, self.db_type, taxon_str, self.date, self.assigned_by, ext_str, product_id_str, ] return l
[ "def", "as_list", "(", "self", ")", ":", "go_id", "=", "self", ".", "go_term", ".", "id", "qual_str", "=", "'|'", ".", "join", "(", "self", ".", "qualifier", ")", "db_ref_str", "=", "'|'", ".", "join", "(", "self", ".", "db_ref", ")", "taxon_str", ...
Returns GO annotation as a flat list (in GAF 2.1 format order).
[ "Returns", "GO", "annotation", "as", "a", "flat", "list", "(", "in", "GAF", "2", ".", "1", "format", "order", ")", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/annotation.py#L356-L391
acorg/dark-matter
dark/diamond/conversion.py
diamondTabularFormatToDicts
def diamondTabularFormatToDicts(filename, fieldNames=None): """ Read DIAMOND tabular (--outfmt 6) output and convert lines to dictionaries. @param filename: Either a C{str} file name or an open file pointer. @param fieldNames: A C{list} or C{tuple} of C{str} DIAMOND field names. Run 'diamond -help' to see the full list. If C{None}, a default set of fields will be used, as compatible with convert-diamond-to-sam.py @raise ValueError: If a line of C{filename} does not have the expected number of TAB-separated fields (i.e., len(fieldNames)). Or if C{fieldNames} is empty or contains duplicates. @return: A generator that yields C{dict}s with keys that are the DIAMOND field names and values as converted by DIAMOND_FIELD_CONVERTER. """ fieldNames = fieldNames or FIELDS.split() nFields = len(fieldNames) if not nFields: raise ValueError('fieldNames cannot be empty.') c = Counter(fieldNames) if c.most_common(1)[0][1] > 1: raise ValueError( 'fieldNames contains duplicated names: %s.' % (', '.join(sorted(x[0] for x in c.most_common() if x[1] > 1)))) def identity(x): return x convertFunc = DIAMOND_FIELD_CONVERTER.get with as_handle(filename) as fp: for count, line in enumerate(fp, start=1): result = {} line = line[:-1] values = line.split('\t') if len(values) != nFields: raise ValueError( 'Line %d of %s had %d field values (expected %d). ' 'To provide input for this function, DIAMOND must be ' 'called with "--outfmt 6 %s" (without the quotes). ' 'The offending input line was %r.' % (count, (filename if isinstance(filename, six.string_types) else 'input'), len(values), nFields, FIELDS, line)) for fieldName, value in zip(fieldNames, values): value = convertFunc(fieldName, identity)(value) result[fieldName] = value yield result
python
def diamondTabularFormatToDicts(filename, fieldNames=None): """ Read DIAMOND tabular (--outfmt 6) output and convert lines to dictionaries. @param filename: Either a C{str} file name or an open file pointer. @param fieldNames: A C{list} or C{tuple} of C{str} DIAMOND field names. Run 'diamond -help' to see the full list. If C{None}, a default set of fields will be used, as compatible with convert-diamond-to-sam.py @raise ValueError: If a line of C{filename} does not have the expected number of TAB-separated fields (i.e., len(fieldNames)). Or if C{fieldNames} is empty or contains duplicates. @return: A generator that yields C{dict}s with keys that are the DIAMOND field names and values as converted by DIAMOND_FIELD_CONVERTER. """ fieldNames = fieldNames or FIELDS.split() nFields = len(fieldNames) if not nFields: raise ValueError('fieldNames cannot be empty.') c = Counter(fieldNames) if c.most_common(1)[0][1] > 1: raise ValueError( 'fieldNames contains duplicated names: %s.' % (', '.join(sorted(x[0] for x in c.most_common() if x[1] > 1)))) def identity(x): return x convertFunc = DIAMOND_FIELD_CONVERTER.get with as_handle(filename) as fp: for count, line in enumerate(fp, start=1): result = {} line = line[:-1] values = line.split('\t') if len(values) != nFields: raise ValueError( 'Line %d of %s had %d field values (expected %d). ' 'To provide input for this function, DIAMOND must be ' 'called with "--outfmt 6 %s" (without the quotes). ' 'The offending input line was %r.' % (count, (filename if isinstance(filename, six.string_types) else 'input'), len(values), nFields, FIELDS, line)) for fieldName, value in zip(fieldNames, values): value = convertFunc(fieldName, identity)(value) result[fieldName] = value yield result
[ "def", "diamondTabularFormatToDicts", "(", "filename", ",", "fieldNames", "=", "None", ")", ":", "fieldNames", "=", "fieldNames", "or", "FIELDS", ".", "split", "(", ")", "nFields", "=", "len", "(", "fieldNames", ")", "if", "not", "nFields", ":", "raise", "...
Read DIAMOND tabular (--outfmt 6) output and convert lines to dictionaries. @param filename: Either a C{str} file name or an open file pointer. @param fieldNames: A C{list} or C{tuple} of C{str} DIAMOND field names. Run 'diamond -help' to see the full list. If C{None}, a default set of fields will be used, as compatible with convert-diamond-to-sam.py @raise ValueError: If a line of C{filename} does not have the expected number of TAB-separated fields (i.e., len(fieldNames)). Or if C{fieldNames} is empty or contains duplicates. @return: A generator that yields C{dict}s with keys that are the DIAMOND field names and values as converted by DIAMOND_FIELD_CONVERTER.
[ "Read", "DIAMOND", "tabular", "(", "--", "outfmt", "6", ")", "output", "and", "convert", "lines", "to", "dictionaries", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/conversion.py#L55-L103
acorg/dark-matter
dark/diamond/conversion.py
DiamondTabularFormatReader.records
def records(self): """ Parse the DIAMOND output and yield records. This will be used to read original DIAMOND output (either from stdin or from a file) to turn the DIAMOND results into Python dictionaries that will then be stored in our JSON format. @return: A generator that produces C{dict}s containing 'alignments' and 'query' C{str} keys. """ with as_handle(self._filename) as fp: previousQtitle = None subjectsSeen = {} record = {} for line in fp: line = line[:-1] try: (qtitle, stitle, bitscore, evalue, qframe, qseq, qstart, qend, sseq, sstart, send, slen, btop, nident, positive) = line.split('\t') except ValueError as e: # We may not be able to find 'nident' and 'positives' # because they were added in version 2.0.3 and will not # be present in any of our JSON output generated before # that. So those values will be None when reading # DIAMOND output without those fields, but that's much # better than no longer being able to read that data. if six.PY2: error = 'need more than 13 values to unpack' else: error = ( 'not enough values to unpack (expected 15, ' 'got 13)') if str(e) == error: (qtitle, stitle, bitscore, evalue, qframe, qseq, qstart, qend, sseq, sstart, send, slen, btop) = line.split('\t') nident = positive = None else: raise hsp = { 'bits': float(bitscore), 'btop': btop, 'expect': float(evalue), 'frame': int(qframe), 'identicalCount': None if nident is None else int(nident), 'positiveCount': ( None if positive is None else int(positive)), 'query': qseq, 'query_start': int(qstart), 'query_end': int(qend), 'sbjct': sseq, 'sbjct_start': int(sstart), 'sbjct_end': int(send), } if previousQtitle == qtitle: # We have already started accumulating alignments for this # query. if stitle not in subjectsSeen: # We have not seen this subject before, so this is a # new alignment. subjectsSeen.add(stitle) alignment = { 'hsps': [hsp], 'length': int(slen), 'title': stitle, } record['alignments'].append(alignment) else: # We have already seen this subject, so this is another # HSP in an already existing alignment. for alignment in record['alignments']: if alignment['title'] == stitle: alignment['hsps'].append(hsp) break else: # All alignments for the previous query id (if any) # have been seen. if previousQtitle is not None: yield record # Start building up the new record. record = {} subjectsSeen = {stitle} alignment = { 'hsps': [hsp], 'length': int(slen), 'title': stitle, } record['alignments'] = [alignment] record['query'] = qtitle previousQtitle = qtitle # Yield the last record, if any. if record: yield record
python
def records(self): """ Parse the DIAMOND output and yield records. This will be used to read original DIAMOND output (either from stdin or from a file) to turn the DIAMOND results into Python dictionaries that will then be stored in our JSON format. @return: A generator that produces C{dict}s containing 'alignments' and 'query' C{str} keys. """ with as_handle(self._filename) as fp: previousQtitle = None subjectsSeen = {} record = {} for line in fp: line = line[:-1] try: (qtitle, stitle, bitscore, evalue, qframe, qseq, qstart, qend, sseq, sstart, send, slen, btop, nident, positive) = line.split('\t') except ValueError as e: # We may not be able to find 'nident' and 'positives' # because they were added in version 2.0.3 and will not # be present in any of our JSON output generated before # that. So those values will be None when reading # DIAMOND output without those fields, but that's much # better than no longer being able to read that data. if six.PY2: error = 'need more than 13 values to unpack' else: error = ( 'not enough values to unpack (expected 15, ' 'got 13)') if str(e) == error: (qtitle, stitle, bitscore, evalue, qframe, qseq, qstart, qend, sseq, sstart, send, slen, btop) = line.split('\t') nident = positive = None else: raise hsp = { 'bits': float(bitscore), 'btop': btop, 'expect': float(evalue), 'frame': int(qframe), 'identicalCount': None if nident is None else int(nident), 'positiveCount': ( None if positive is None else int(positive)), 'query': qseq, 'query_start': int(qstart), 'query_end': int(qend), 'sbjct': sseq, 'sbjct_start': int(sstart), 'sbjct_end': int(send), } if previousQtitle == qtitle: # We have already started accumulating alignments for this # query. if stitle not in subjectsSeen: # We have not seen this subject before, so this is a # new alignment. subjectsSeen.add(stitle) alignment = { 'hsps': [hsp], 'length': int(slen), 'title': stitle, } record['alignments'].append(alignment) else: # We have already seen this subject, so this is another # HSP in an already existing alignment. for alignment in record['alignments']: if alignment['title'] == stitle: alignment['hsps'].append(hsp) break else: # All alignments for the previous query id (if any) # have been seen. if previousQtitle is not None: yield record # Start building up the new record. record = {} subjectsSeen = {stitle} alignment = { 'hsps': [hsp], 'length': int(slen), 'title': stitle, } record['alignments'] = [alignment] record['query'] = qtitle previousQtitle = qtitle # Yield the last record, if any. if record: yield record
[ "def", "records", "(", "self", ")", ":", "with", "as_handle", "(", "self", ".", "_filename", ")", "as", "fp", ":", "previousQtitle", "=", "None", "subjectsSeen", "=", "{", "}", "record", "=", "{", "}", "for", "line", "in", "fp", ":", "line", "=", "...
Parse the DIAMOND output and yield records. This will be used to read original DIAMOND output (either from stdin or from a file) to turn the DIAMOND results into Python dictionaries that will then be stored in our JSON format. @return: A generator that produces C{dict}s containing 'alignments' and 'query' C{str} keys.
[ "Parse", "the", "DIAMOND", "output", "and", "yield", "records", ".", "This", "will", "be", "used", "to", "read", "original", "DIAMOND", "output", "(", "either", "from", "stdin", "or", "from", "a", "file", ")", "to", "turn", "the", "DIAMOND", "results", "...
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/conversion.py#L131-L227
acorg/dark-matter
dark/diamond/conversion.py
DiamondTabularFormatReader.saveAsJSON
def saveAsJSON(self, fp, writeBytes=False): """ Write the records out as JSON. The first JSON object saved contains information about the DIAMOND algorithm. @param fp: A C{str} file pointer to write to. @param writeBytes: If C{True}, the JSON will be written out as bytes (not strings). This is required when we are writing to a BZ2 file. """ if writeBytes: fp.write(dumps(self.params, sort_keys=True).encode('UTF-8')) fp.write(b'\n') for record in self.records(): fp.write(dumps(record, sort_keys=True).encode('UTF-8')) fp.write(b'\n') else: fp.write(six.u(dumps(self.params, sort_keys=True))) fp.write(six.u('\n')) for record in self.records(): fp.write(six.u(dumps(record, sort_keys=True))) fp.write(six.u('\n'))
python
def saveAsJSON(self, fp, writeBytes=False): """ Write the records out as JSON. The first JSON object saved contains information about the DIAMOND algorithm. @param fp: A C{str} file pointer to write to. @param writeBytes: If C{True}, the JSON will be written out as bytes (not strings). This is required when we are writing to a BZ2 file. """ if writeBytes: fp.write(dumps(self.params, sort_keys=True).encode('UTF-8')) fp.write(b'\n') for record in self.records(): fp.write(dumps(record, sort_keys=True).encode('UTF-8')) fp.write(b'\n') else: fp.write(six.u(dumps(self.params, sort_keys=True))) fp.write(six.u('\n')) for record in self.records(): fp.write(six.u(dumps(record, sort_keys=True))) fp.write(six.u('\n'))
[ "def", "saveAsJSON", "(", "self", ",", "fp", ",", "writeBytes", "=", "False", ")", ":", "if", "writeBytes", ":", "fp", ".", "write", "(", "dumps", "(", "self", ".", "params", ",", "sort_keys", "=", "True", ")", ".", "encode", "(", "'UTF-8'", ")", "...
Write the records out as JSON. The first JSON object saved contains information about the DIAMOND algorithm. @param fp: A C{str} file pointer to write to. @param writeBytes: If C{True}, the JSON will be written out as bytes (not strings). This is required when we are writing to a BZ2 file.
[ "Write", "the", "records", "out", "as", "JSON", ".", "The", "first", "JSON", "object", "saved", "contains", "information", "about", "the", "DIAMOND", "algorithm", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/conversion.py#L229-L249
acorg/dark-matter
dark/diamond/conversion.py
JSONRecordsReader._dictToAlignments
def _dictToAlignments(self, diamondDict, read): """ Take a dict (made by DiamondTabularFormatReader.records) and convert it to a list of alignments. @param diamondDict: A C{dict}, from records(). @param read: A C{Read} instance, containing the read that DIAMOND used to create this record. @return: A C{list} of L{dark.alignment.Alignment} instances. """ alignments = [] getScore = itemgetter('bits' if self._hspClass is HSP else 'expect') for diamondAlignment in diamondDict['alignments']: alignment = Alignment(diamondAlignment['length'], diamondAlignment['title']) alignments.append(alignment) for diamondHsp in diamondAlignment['hsps']: score = getScore(diamondHsp) normalized = normalizeHSP(diamondHsp, len(read), self.diamondTask) hsp = self._hspClass( score, readStart=normalized['readStart'], readEnd=normalized['readEnd'], readStartInSubject=normalized['readStartInSubject'], readEndInSubject=normalized['readEndInSubject'], readFrame=diamondHsp['frame'], subjectStart=normalized['subjectStart'], subjectEnd=normalized['subjectEnd'], readMatchedSequence=diamondHsp['query'], subjectMatchedSequence=diamondHsp['sbjct'], # Use blastHsp.get on identicalCount and positiveCount # because they were added in version 2.0.3 and will not # be present in any of our JSON output generated before # that. Those values will be None for those JSON files, # but that's much better than no longer being able to # read all that data. identicalCount=diamondHsp.get('identicalCount'), positiveCount=diamondHsp.get('positiveCount')) alignment.addHsp(hsp) return alignments
python
def _dictToAlignments(self, diamondDict, read): """ Take a dict (made by DiamondTabularFormatReader.records) and convert it to a list of alignments. @param diamondDict: A C{dict}, from records(). @param read: A C{Read} instance, containing the read that DIAMOND used to create this record. @return: A C{list} of L{dark.alignment.Alignment} instances. """ alignments = [] getScore = itemgetter('bits' if self._hspClass is HSP else 'expect') for diamondAlignment in diamondDict['alignments']: alignment = Alignment(diamondAlignment['length'], diamondAlignment['title']) alignments.append(alignment) for diamondHsp in diamondAlignment['hsps']: score = getScore(diamondHsp) normalized = normalizeHSP(diamondHsp, len(read), self.diamondTask) hsp = self._hspClass( score, readStart=normalized['readStart'], readEnd=normalized['readEnd'], readStartInSubject=normalized['readStartInSubject'], readEndInSubject=normalized['readEndInSubject'], readFrame=diamondHsp['frame'], subjectStart=normalized['subjectStart'], subjectEnd=normalized['subjectEnd'], readMatchedSequence=diamondHsp['query'], subjectMatchedSequence=diamondHsp['sbjct'], # Use blastHsp.get on identicalCount and positiveCount # because they were added in version 2.0.3 and will not # be present in any of our JSON output generated before # that. Those values will be None for those JSON files, # but that's much better than no longer being able to # read all that data. identicalCount=diamondHsp.get('identicalCount'), positiveCount=diamondHsp.get('positiveCount')) alignment.addHsp(hsp) return alignments
[ "def", "_dictToAlignments", "(", "self", ",", "diamondDict", ",", "read", ")", ":", "alignments", "=", "[", "]", "getScore", "=", "itemgetter", "(", "'bits'", "if", "self", ".", "_hspClass", "is", "HSP", "else", "'expect'", ")", "for", "diamondAlignment", ...
Take a dict (made by DiamondTabularFormatReader.records) and convert it to a list of alignments. @param diamondDict: A C{dict}, from records(). @param read: A C{Read} instance, containing the read that DIAMOND used to create this record. @return: A C{list} of L{dark.alignment.Alignment} instances.
[ "Take", "a", "dict", "(", "made", "by", "DiamondTabularFormatReader", ".", "records", ")", "and", "convert", "it", "to", "a", "list", "of", "alignments", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/conversion.py#L302-L345
closeio/cleancat
cleancat/sqla.py
object_as_dict
def object_as_dict(obj): """Turn an SQLAlchemy model into a dict of field names and values. Based on https://stackoverflow.com/a/37350445/1579058 """ return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs}
python
def object_as_dict(obj): """Turn an SQLAlchemy model into a dict of field names and values. Based on https://stackoverflow.com/a/37350445/1579058 """ return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs}
[ "def", "object_as_dict", "(", "obj", ")", ":", "return", "{", "c", ".", "key", ":", "getattr", "(", "obj", ",", "c", ".", "key", ")", "for", "c", "in", "inspect", "(", "obj", ")", ".", "mapper", ".", "column_attrs", "}" ]
Turn an SQLAlchemy model into a dict of field names and values. Based on https://stackoverflow.com/a/37350445/1579058
[ "Turn", "an", "SQLAlchemy", "model", "into", "a", "dict", "of", "field", "names", "and", "values", "." ]
train
https://github.com/closeio/cleancat/blob/59df1422b3ebea9477026ca80cd7af1ae9734d89/cleancat/sqla.py#L12-L18
closeio/cleancat
cleancat/sqla.py
SQLAReference.fetch_object
def fetch_object(self, model_id): """Fetch the model by its ID.""" pk_field_instance = getattr(self.object_class, self.pk_field) qs = self.object_class.query.filter(pk_field_instance == model_id) model = qs.one_or_none() if not model: raise ReferenceNotFoundError return model
python
def fetch_object(self, model_id): """Fetch the model by its ID.""" pk_field_instance = getattr(self.object_class, self.pk_field) qs = self.object_class.query.filter(pk_field_instance == model_id) model = qs.one_or_none() if not model: raise ReferenceNotFoundError return model
[ "def", "fetch_object", "(", "self", ",", "model_id", ")", ":", "pk_field_instance", "=", "getattr", "(", "self", ".", "object_class", ",", "self", ".", "pk_field", ")", "qs", "=", "self", ".", "object_class", ".", "query", ".", "filter", "(", "pk_field_ins...
Fetch the model by its ID.
[ "Fetch", "the", "model", "by", "its", "ID", "." ]
train
https://github.com/closeio/cleancat/blob/59df1422b3ebea9477026ca80cd7af1ae9734d89/cleancat/sqla.py#L54-L61
nkavaldj/myhdl_lib
myhdl_lib/stream.py
bytecount
def bytecount(rst, clk, rx_vld, rx_sop, rx_eop, rx_dat, rx_mty, count, MAX_BYTES=1500 ): """ Counts bytes in a stream of packetised data rx_vld - (i) valid data rx_sop - (i) start of packet rx_eop - (i) end of packet rx_dat - (i) data rx_mty - (i) empty bits when rx_eop count - (o) byte count MAX_BYTES - a limit: maximum number of bytes that may arrive in a single packet The result is ready in the first clock cycle after rx_eop """ DATA_WIDTH = len(rx_dat) assert DATA_WIDTH%8==0, "bytecount: expects len(rx_dat)=8*x, but len(rx_dat)={}".format(DATA_WIDTH) NUM_BYTES = DATA_WIDTH // 8 MAX_BYTES_LG = floor(log(MAX_BYTES,2)) MIN_COUNT_WIDTH = int(MAX_BYTES_LG) + 1 assert len(count)>=MIN_COUNT_WIDTH, "bytecount: expects len(count)>={}, but len(count)={}".format(MIN_COUNT_WIDTH, len(count)) count_s = Signal(intbv(0)[MIN_COUNT_WIDTH:]) @always_seq(clk.posedge, reset=rst) def _count(): if (rx_vld): x = NUM_BYTES if (rx_eop==1): x = x -rx_mty if (rx_sop==1): count_s.next = x else: count_s.next = count_s + x @always_comb def out_comb(): count.next = count_s return instances()
python
def bytecount(rst, clk, rx_vld, rx_sop, rx_eop, rx_dat, rx_mty, count, MAX_BYTES=1500 ): """ Counts bytes in a stream of packetised data rx_vld - (i) valid data rx_sop - (i) start of packet rx_eop - (i) end of packet rx_dat - (i) data rx_mty - (i) empty bits when rx_eop count - (o) byte count MAX_BYTES - a limit: maximum number of bytes that may arrive in a single packet The result is ready in the first clock cycle after rx_eop """ DATA_WIDTH = len(rx_dat) assert DATA_WIDTH%8==0, "bytecount: expects len(rx_dat)=8*x, but len(rx_dat)={}".format(DATA_WIDTH) NUM_BYTES = DATA_WIDTH // 8 MAX_BYTES_LG = floor(log(MAX_BYTES,2)) MIN_COUNT_WIDTH = int(MAX_BYTES_LG) + 1 assert len(count)>=MIN_COUNT_WIDTH, "bytecount: expects len(count)>={}, but len(count)={}".format(MIN_COUNT_WIDTH, len(count)) count_s = Signal(intbv(0)[MIN_COUNT_WIDTH:]) @always_seq(clk.posedge, reset=rst) def _count(): if (rx_vld): x = NUM_BYTES if (rx_eop==1): x = x -rx_mty if (rx_sop==1): count_s.next = x else: count_s.next = count_s + x @always_comb def out_comb(): count.next = count_s return instances()
[ "def", "bytecount", "(", "rst", ",", "clk", ",", "rx_vld", ",", "rx_sop", ",", "rx_eop", ",", "rx_dat", ",", "rx_mty", ",", "count", ",", "MAX_BYTES", "=", "1500", ")", ":", "DATA_WIDTH", "=", "len", "(", "rx_dat", ")", "assert", "DATA_WIDTH", "%", "...
Counts bytes in a stream of packetised data rx_vld - (i) valid data rx_sop - (i) start of packet rx_eop - (i) end of packet rx_dat - (i) data rx_mty - (i) empty bits when rx_eop count - (o) byte count MAX_BYTES - a limit: maximum number of bytes that may arrive in a single packet The result is ready in the first clock cycle after rx_eop
[ "Counts", "bytes", "in", "a", "stream", "of", "packetised", "data", "rx_vld", "-", "(", "i", ")", "valid", "data", "rx_sop", "-", "(", "i", ")", "start", "of", "packet", "rx_eop", "-", "(", "i", ")", "end", "of", "packet", "rx_dat", "-", "(", "i", ...
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/stream.py#L6-L45
nkavaldj/myhdl_lib
myhdl_lib/stream.py
checksum
def checksum(rst, clk, rx_vld, rx_sop, rx_eop, rx_dat, rx_mty, chksum, sum16=None, sumN=None, init_sum=None, MAX_BYTES=1500): """ Calculates checksum on a stream of packetised data rx_vld - (i) valid data rx_sop - (i) start of packet rx_eop - (i) end of packet rx_dat - (i) data rx_mty - (i) empty bits when rx_eop init_sum - (i) initial value for the sum (e.g. sum of the some fields from a packet header) sumN - (o) optional, plane sum sum16 - (o) optional, 16 bit sum (every time the sum overflows, the overflow is added to the sum) chksum - (o) optional, checksum (~sum16) MAX_BYTES - a limit: maximum number of bytes that may arrive in a single packet Assumes Big-endian data. The results are ready in the first clock cycle after rx_eop """ DATA_WIDTH = len(rx_dat) assert DATA_WIDTH%16==0, "checksum: expects len(rx_dat)=16*x, but len(tx_dat)={}".format(DATA_WIDTH) NUM_BYTES = DATA_WIDTH // 8 NUM_WORDS = DATA_WIDTH // 16 SUM_WIDTH = 16 + int(ceil(log(MAX_BYTES/2,2))) + 1 SUM16_WIDTH = 16 + int(ceil(log(NUM_WORDS,2))) + 1 if (init_sum != None): assert len(init_sum)<=16, "checksum: expects len(init_sum)<={}, but len(init_sum)={}".format(16, len(init_sum)) SUM_WIDTH += 1 SUM16_WIDTH += 1 else: init_sum = 0 FF_MASK = intbv(0)[DATA_WIDTH:].max-1 mdata = Signal(intbv(0)[DATA_WIDTH:]) @always_comb def _mask_empty(): mdata.next = rx_dat if rx_eop: mdata.next = rx_dat & (FF_MASK<<(rx_mty*8)) # Slice masked data in 16 bit words mdata16 = [Signal(intbv(0)[16:]) for _ in range(NUM_WORDS)] _ass = [assign(mdata16[w], mdata((w+1)*16, w*16)) for w in range(NUM_WORDS)] if sumN!=None: assert len(sumN)>=SUM_WIDTH, "checksum: expects len(sumN)>={}, but len(sumN)={}".format(SUM_WIDTH, len(sumN)) sumN_reg = Signal(intbv(0)[SUM_WIDTH:]) @always_seq(clk.posedge, reset=rst) def _accuN(): ''' Accumulate ''' if (rx_vld): s = 0 if (rx_sop): s = int(init_sum) else: s = int(sumN_reg) for w in range(NUM_WORDS): s += mdata16[w] sumN_reg.next = s @always_comb def _passN(): sumN.next = sumN_reg if chksum!=None or sum16!=None: sum16_reg = Signal(intbv(0)[SUM16_WIDTH:]) @always_seq(clk.posedge, reset=rst) def _accu16(): ''' Accumulate 16 bit words''' if (rx_vld): s = 0 if (rx_sop): s = int(init_sum) else: s = int(sum16_reg) for w in range(NUM_WORDS): s += mdata16[w] ss = intbv(s)[SUM16_WIDTH:] sum16_reg.next = ss[:2*8] + ss[2*8:] if sum16!=None: assert len(sum16)>=16, "checksum: expects len(sum16)>={}, but len(sum16)={}".format(16, len(sum16)) @always_comb def _pass16(): sum16.next = sum16_reg[16:] if chksum!=None: assert len(chksum)>=16, "checksum: expects len(chksum)>={}, but len(chksum)={}".format(16, len(chksum)) @always_comb def _invert(): chksum.next = ~sum16_reg[16:] & 0xFFFF return instances()
python
def checksum(rst, clk, rx_vld, rx_sop, rx_eop, rx_dat, rx_mty, chksum, sum16=None, sumN=None, init_sum=None, MAX_BYTES=1500): """ Calculates checksum on a stream of packetised data rx_vld - (i) valid data rx_sop - (i) start of packet rx_eop - (i) end of packet rx_dat - (i) data rx_mty - (i) empty bits when rx_eop init_sum - (i) initial value for the sum (e.g. sum of the some fields from a packet header) sumN - (o) optional, plane sum sum16 - (o) optional, 16 bit sum (every time the sum overflows, the overflow is added to the sum) chksum - (o) optional, checksum (~sum16) MAX_BYTES - a limit: maximum number of bytes that may arrive in a single packet Assumes Big-endian data. The results are ready in the first clock cycle after rx_eop """ DATA_WIDTH = len(rx_dat) assert DATA_WIDTH%16==0, "checksum: expects len(rx_dat)=16*x, but len(tx_dat)={}".format(DATA_WIDTH) NUM_BYTES = DATA_WIDTH // 8 NUM_WORDS = DATA_WIDTH // 16 SUM_WIDTH = 16 + int(ceil(log(MAX_BYTES/2,2))) + 1 SUM16_WIDTH = 16 + int(ceil(log(NUM_WORDS,2))) + 1 if (init_sum != None): assert len(init_sum)<=16, "checksum: expects len(init_sum)<={}, but len(init_sum)={}".format(16, len(init_sum)) SUM_WIDTH += 1 SUM16_WIDTH += 1 else: init_sum = 0 FF_MASK = intbv(0)[DATA_WIDTH:].max-1 mdata = Signal(intbv(0)[DATA_WIDTH:]) @always_comb def _mask_empty(): mdata.next = rx_dat if rx_eop: mdata.next = rx_dat & (FF_MASK<<(rx_mty*8)) # Slice masked data in 16 bit words mdata16 = [Signal(intbv(0)[16:]) for _ in range(NUM_WORDS)] _ass = [assign(mdata16[w], mdata((w+1)*16, w*16)) for w in range(NUM_WORDS)] if sumN!=None: assert len(sumN)>=SUM_WIDTH, "checksum: expects len(sumN)>={}, but len(sumN)={}".format(SUM_WIDTH, len(sumN)) sumN_reg = Signal(intbv(0)[SUM_WIDTH:]) @always_seq(clk.posedge, reset=rst) def _accuN(): ''' Accumulate ''' if (rx_vld): s = 0 if (rx_sop): s = int(init_sum) else: s = int(sumN_reg) for w in range(NUM_WORDS): s += mdata16[w] sumN_reg.next = s @always_comb def _passN(): sumN.next = sumN_reg if chksum!=None or sum16!=None: sum16_reg = Signal(intbv(0)[SUM16_WIDTH:]) @always_seq(clk.posedge, reset=rst) def _accu16(): ''' Accumulate 16 bit words''' if (rx_vld): s = 0 if (rx_sop): s = int(init_sum) else: s = int(sum16_reg) for w in range(NUM_WORDS): s += mdata16[w] ss = intbv(s)[SUM16_WIDTH:] sum16_reg.next = ss[:2*8] + ss[2*8:] if sum16!=None: assert len(sum16)>=16, "checksum: expects len(sum16)>={}, but len(sum16)={}".format(16, len(sum16)) @always_comb def _pass16(): sum16.next = sum16_reg[16:] if chksum!=None: assert len(chksum)>=16, "checksum: expects len(chksum)>={}, but len(chksum)={}".format(16, len(chksum)) @always_comb def _invert(): chksum.next = ~sum16_reg[16:] & 0xFFFF return instances()
[ "def", "checksum", "(", "rst", ",", "clk", ",", "rx_vld", ",", "rx_sop", ",", "rx_eop", ",", "rx_dat", ",", "rx_mty", ",", "chksum", ",", "sum16", "=", "None", ",", "sumN", "=", "None", ",", "init_sum", "=", "None", ",", "MAX_BYTES", "=", "1500", "...
Calculates checksum on a stream of packetised data rx_vld - (i) valid data rx_sop - (i) start of packet rx_eop - (i) end of packet rx_dat - (i) data rx_mty - (i) empty bits when rx_eop init_sum - (i) initial value for the sum (e.g. sum of the some fields from a packet header) sumN - (o) optional, plane sum sum16 - (o) optional, 16 bit sum (every time the sum overflows, the overflow is added to the sum) chksum - (o) optional, checksum (~sum16) MAX_BYTES - a limit: maximum number of bytes that may arrive in a single packet Assumes Big-endian data. The results are ready in the first clock cycle after rx_eop
[ "Calculates", "checksum", "on", "a", "stream", "of", "packetised", "data", "rx_vld", "-", "(", "i", ")", "valid", "data", "rx_sop", "-", "(", "i", ")", "start", "of", "packet", "rx_eop", "-", "(", "i", ")", "end", "of", "packet", "rx_dat", "-", "(", ...
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/stream.py#L48-L155
flo-compbio/genometools
genometools/rnaseq/stringtie_gene_level_expression.py
get_argument_parser
def get_argument_parser(): """Function to obtain the argument parser. Returns ------- A fully configured `argparse.ArgumentParser` object. Notes ----- This function is used by the `sphinx-argparse` extension for sphinx. """ file_mv = cli.file_mv desc = 'Extracts gene-level expression data from StringTie output.' parser = cli.get_argument_parser(desc) parser.add_argument( '-s', '--stringtie-file', type=str, required=True, metavar=file_mv, help="""Path of the StringTie output file .""" ) parser.add_argument( '-g', '--gene-file', type=str, required=True, metavar=file_mv, help="""File containing a list of protein-coding genes.""" ) parser.add_argument( '--no-novel-transcripts', action='store_true', help="""Ignore novel transcripts.""" ) # parser.add_argument( # '--ambiguous-transcripts', default = 'ignore', # help='Strategy for counting expression of ambiguous novel ' # 'transcripts.' # ) # possible strategies for ambiguous transcripts: 'ignore','highest','all' parser.add_argument( '-o', '--output-file', type=str, required=True, metavar=file_mv, help="""Path of output file.""" ) cli.add_reporting_args(parser) return parser
python
def get_argument_parser(): """Function to obtain the argument parser. Returns ------- A fully configured `argparse.ArgumentParser` object. Notes ----- This function is used by the `sphinx-argparse` extension for sphinx. """ file_mv = cli.file_mv desc = 'Extracts gene-level expression data from StringTie output.' parser = cli.get_argument_parser(desc) parser.add_argument( '-s', '--stringtie-file', type=str, required=True, metavar=file_mv, help="""Path of the StringTie output file .""" ) parser.add_argument( '-g', '--gene-file', type=str, required=True, metavar=file_mv, help="""File containing a list of protein-coding genes.""" ) parser.add_argument( '--no-novel-transcripts', action='store_true', help="""Ignore novel transcripts.""" ) # parser.add_argument( # '--ambiguous-transcripts', default = 'ignore', # help='Strategy for counting expression of ambiguous novel ' # 'transcripts.' # ) # possible strategies for ambiguous transcripts: 'ignore','highest','all' parser.add_argument( '-o', '--output-file', type=str, required=True, metavar=file_mv, help="""Path of output file.""" ) cli.add_reporting_args(parser) return parser
[ "def", "get_argument_parser", "(", ")", ":", "file_mv", "=", "cli", ".", "file_mv", "desc", "=", "'Extracts gene-level expression data from StringTie output.'", "parser", "=", "cli", ".", "get_argument_parser", "(", "desc", ")", "parser", ".", "add_argument", "(", "...
Function to obtain the argument parser. Returns ------- A fully configured `argparse.ArgumentParser` object. Notes ----- This function is used by the `sphinx-argparse` extension for sphinx.
[ "Function", "to", "obtain", "the", "argument", "parser", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/rnaseq/stringtie_gene_level_expression.py#L42-L88
flo-compbio/genometools
genometools/rnaseq/stringtie_gene_level_expression.py
main
def main(args=None): """Extracts gene-level expression data from StringTie output. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module. Returns ------- int Exit code (0 if no error occurred). """ if args is None: # parse command-line arguments parser = get_argument_parser() args = parser.parse_args() stringtie_file = args.stringtie_file gene_file = args.gene_file no_novel_transcripts = args.no_novel_transcripts output_file = args.output_file log_file = args.log_file quiet = args.quiet verbose = args.verbose logger = misc.get_logger(log_file=log_file, quiet=quiet, verbose=verbose) # read list of gene symbols logger.info('Reading gene data...') genes = misc.read_single(gene_file) # read StringTie output file and summarize FPKM and TPM per gene logger.info('Parsing StringTie output...') logger.info('Associating StringTie gene IDs with gene symbols...') stringtie_genes = {} with open(stringtie_file) as fh: reader = csv.reader(fh, dialect='excel-tab') for l in reader: if l[0][0] == '#': continue assert len(l) == 9 if l[2] != 'transcript': continue attr = parse_attributes(l[8]) try: ref_gene = attr['ref_gene_name'] except KeyError: continue else: # entry has a "ref_gene_name" attribute try: g = stringtie_genes[attr['gene_id']] except KeyError: stringtie_genes[attr['gene_id']] = {ref_gene, } else: g.add(ref_gene) logger.info('Associated %d gene IDs with gene symbols.', len(stringtie_genes)) # C = Counter(len(v) for v in stringtie_genes.itervalues()) gene_ids_ambiguous = [k for k, v in stringtie_genes.items() if len(v) > 1] n = len(gene_ids_ambiguous) logger.info('%d / %d associated with multiple gene symbols (%.1f%%).', n, len(stringtie_genes), 100*(n/float(len(stringtie_genes)))) # read StringTie output file and summarize FPKM and TPM per gene n = len(genes) fpkm = np.zeros(n, dtype=np.float64) tpm = np.zeros(n, dtype=np.float64) fpkm_novel_gene = 0 fpkm_unknown_gene_name = 0 fpkm_novel_trans = 0 fpkm_ambig = 0 with open(stringtie_file) as fh: reader = csv.reader(fh, dialect='excel-tab') for l in reader: if l[0][0] == '#': # skip header continue assert len(l) == 9 if l[2] != 'transcript': # skip exon lines continue attr = parse_attributes(l[8]) f = float(attr['FPKM']) try: g = attr['ref_gene_name'] except KeyError: if no_novel_transcripts: # ignore this transcript fpkm_novel_trans += f continue else: # see if we can assign a gene name based on the gene ID try: assoc = stringtie_genes[attr['gene_id']] except KeyError: # gene_id not associated with any reference gene fpkm_novel_gene += f continue else: if len(assoc) > 1: # gene ID associated with multiple ref. genes # => ingored fpkm_ambig += f continue else: # gene ID associated with exactly one ref. gene g = list(assoc)[0] try: idx = misc.bisect_index(genes, g) except ValueError: fpkm_unknown_gene_name += f logger.warning('Unknown gene name: "%s".', g) continue t = float(attr['TPM']) fpkm[idx] += f tpm[idx] += t # ignored_fpkm = None if no_novel_transcripts: ignored_fpkm = fpkm_novel_trans + fpkm_unknown_gene_name else: ignored_fpkm = fpkm_novel_gene + fpkm_ambig + fpkm_unknown_gene_name total_fpkm = np.sum(fpkm) + ignored_fpkm logger.info('Ignored %.1f / %.1f FPKM (%.1f%%)', ignored_fpkm, total_fpkm, 100*(ignored_fpkm/total_fpkm)) if no_novel_transcripts and fpkm_novel_trans > 0: logger.info('Ignored %.1f FPKM from novel transcripts (%.1f%%).', fpkm_novel_trans, 100*(fpkm_novel_trans/total_fpkm)) else: if fpkm_novel_gene > 0: logger.info('Ignored %.1f FPKM from transcripts of novel genes ' '(%.1f%%).', fpkm_novel_gene, 100*(fpkm_novel_gene/total_fpkm)) if fpkm_ambig > 0: logger.info('Ignored %.1f FPKM from transcripts with ambiguous ' 'gene membership (%.1f%%).', fpkm_ambig, 100*(fpkm_ambig/total_fpkm)) if fpkm_unknown_gene_name > 0: logger.info('Ignored %.1f FPKM from transcripts of genes with unknown ' 'names (%.1f%%).', fpkm_unknown_gene_name, 100*(fpkm_unknown_gene_name/total_fpkm)) # write output file E = np.c_[fpkm, tpm] with open(output_file, 'w') as ofh: writer = csv.writer(ofh, dialect='excel-tab', lineterminator=os.linesep, quoting=csv.QUOTE_NONE) for i, g in enumerate(genes): writer.writerow([g] + ['%.5f' % e for e in E[i, :]]) return 0
python
def main(args=None): """Extracts gene-level expression data from StringTie output. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module. Returns ------- int Exit code (0 if no error occurred). """ if args is None: # parse command-line arguments parser = get_argument_parser() args = parser.parse_args() stringtie_file = args.stringtie_file gene_file = args.gene_file no_novel_transcripts = args.no_novel_transcripts output_file = args.output_file log_file = args.log_file quiet = args.quiet verbose = args.verbose logger = misc.get_logger(log_file=log_file, quiet=quiet, verbose=verbose) # read list of gene symbols logger.info('Reading gene data...') genes = misc.read_single(gene_file) # read StringTie output file and summarize FPKM and TPM per gene logger.info('Parsing StringTie output...') logger.info('Associating StringTie gene IDs with gene symbols...') stringtie_genes = {} with open(stringtie_file) as fh: reader = csv.reader(fh, dialect='excel-tab') for l in reader: if l[0][0] == '#': continue assert len(l) == 9 if l[2] != 'transcript': continue attr = parse_attributes(l[8]) try: ref_gene = attr['ref_gene_name'] except KeyError: continue else: # entry has a "ref_gene_name" attribute try: g = stringtie_genes[attr['gene_id']] except KeyError: stringtie_genes[attr['gene_id']] = {ref_gene, } else: g.add(ref_gene) logger.info('Associated %d gene IDs with gene symbols.', len(stringtie_genes)) # C = Counter(len(v) for v in stringtie_genes.itervalues()) gene_ids_ambiguous = [k for k, v in stringtie_genes.items() if len(v) > 1] n = len(gene_ids_ambiguous) logger.info('%d / %d associated with multiple gene symbols (%.1f%%).', n, len(stringtie_genes), 100*(n/float(len(stringtie_genes)))) # read StringTie output file and summarize FPKM and TPM per gene n = len(genes) fpkm = np.zeros(n, dtype=np.float64) tpm = np.zeros(n, dtype=np.float64) fpkm_novel_gene = 0 fpkm_unknown_gene_name = 0 fpkm_novel_trans = 0 fpkm_ambig = 0 with open(stringtie_file) as fh: reader = csv.reader(fh, dialect='excel-tab') for l in reader: if l[0][0] == '#': # skip header continue assert len(l) == 9 if l[2] != 'transcript': # skip exon lines continue attr = parse_attributes(l[8]) f = float(attr['FPKM']) try: g = attr['ref_gene_name'] except KeyError: if no_novel_transcripts: # ignore this transcript fpkm_novel_trans += f continue else: # see if we can assign a gene name based on the gene ID try: assoc = stringtie_genes[attr['gene_id']] except KeyError: # gene_id not associated with any reference gene fpkm_novel_gene += f continue else: if len(assoc) > 1: # gene ID associated with multiple ref. genes # => ingored fpkm_ambig += f continue else: # gene ID associated with exactly one ref. gene g = list(assoc)[0] try: idx = misc.bisect_index(genes, g) except ValueError: fpkm_unknown_gene_name += f logger.warning('Unknown gene name: "%s".', g) continue t = float(attr['TPM']) fpkm[idx] += f tpm[idx] += t # ignored_fpkm = None if no_novel_transcripts: ignored_fpkm = fpkm_novel_trans + fpkm_unknown_gene_name else: ignored_fpkm = fpkm_novel_gene + fpkm_ambig + fpkm_unknown_gene_name total_fpkm = np.sum(fpkm) + ignored_fpkm logger.info('Ignored %.1f / %.1f FPKM (%.1f%%)', ignored_fpkm, total_fpkm, 100*(ignored_fpkm/total_fpkm)) if no_novel_transcripts and fpkm_novel_trans > 0: logger.info('Ignored %.1f FPKM from novel transcripts (%.1f%%).', fpkm_novel_trans, 100*(fpkm_novel_trans/total_fpkm)) else: if fpkm_novel_gene > 0: logger.info('Ignored %.1f FPKM from transcripts of novel genes ' '(%.1f%%).', fpkm_novel_gene, 100*(fpkm_novel_gene/total_fpkm)) if fpkm_ambig > 0: logger.info('Ignored %.1f FPKM from transcripts with ambiguous ' 'gene membership (%.1f%%).', fpkm_ambig, 100*(fpkm_ambig/total_fpkm)) if fpkm_unknown_gene_name > 0: logger.info('Ignored %.1f FPKM from transcripts of genes with unknown ' 'names (%.1f%%).', fpkm_unknown_gene_name, 100*(fpkm_unknown_gene_name/total_fpkm)) # write output file E = np.c_[fpkm, tpm] with open(output_file, 'w') as ofh: writer = csv.writer(ofh, dialect='excel-tab', lineterminator=os.linesep, quoting=csv.QUOTE_NONE) for i, g in enumerate(genes): writer.writerow([g] + ['%.5f' % e for e in E[i, :]]) return 0
[ "def", "main", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "# parse command-line arguments", "parser", "=", "get_argument_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "stringtie_file", "=", "args", ".", "s...
Extracts gene-level expression data from StringTie output. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module. Returns ------- int Exit code (0 if no error occurred).
[ "Extracts", "gene", "-", "level", "expression", "data", "from", "StringTie", "output", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/rnaseq/stringtie_gene_level_expression.py#L91-L260
shmir/PyIxExplorer
ixexplorer/ixe_app.py
init_ixe
def init_ixe(logger, host, port=4555, rsa_id=None): """ Connect to Tcl Server and Create IxExplorer object. :param logger: python logger object :param host: host (IxTclServer) IP address :param port: Tcl Server port :param rsa_id: full path to RSA ID file for Linux based IxVM :return: IXE object """ return IxeApp(logger, IxTclHalApi(TclClient(logger, host, port, rsa_id)))
python
def init_ixe(logger, host, port=4555, rsa_id=None): """ Connect to Tcl Server and Create IxExplorer object. :param logger: python logger object :param host: host (IxTclServer) IP address :param port: Tcl Server port :param rsa_id: full path to RSA ID file for Linux based IxVM :return: IXE object """ return IxeApp(logger, IxTclHalApi(TclClient(logger, host, port, rsa_id)))
[ "def", "init_ixe", "(", "logger", ",", "host", ",", "port", "=", "4555", ",", "rsa_id", "=", "None", ")", ":", "return", "IxeApp", "(", "logger", ",", "IxTclHalApi", "(", "TclClient", "(", "logger", ",", "host", ",", "port", ",", "rsa_id", ")", ")", ...
Connect to Tcl Server and Create IxExplorer object. :param logger: python logger object :param host: host (IxTclServer) IP address :param port: Tcl Server port :param rsa_id: full path to RSA ID file for Linux based IxVM :return: IXE object
[ "Connect", "to", "Tcl", "Server", "and", "Create", "IxExplorer", "object", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L17-L27
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeApp.connect
def connect(self, user=None): """ Connect to host. :param user: if user - login session. """ self.api._tcl_handler.connect() if user: self.session.login(user)
python
def connect(self, user=None): """ Connect to host. :param user: if user - login session. """ self.api._tcl_handler.connect() if user: self.session.login(user)
[ "def", "connect", "(", "self", ",", "user", "=", "None", ")", ":", "self", ".", "api", ".", "_tcl_handler", ".", "connect", "(", ")", "if", "user", ":", "self", ".", "session", ".", "login", "(", "user", ")" ]
Connect to host. :param user: if user - login session.
[ "Connect", "to", "host", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L42-L50
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeApp.add
def add(self, chassis): """ add chassis. :param chassis: chassis IP address. """ self.chassis_chain[chassis] = IxeChassis(self.session, chassis, len(self.chassis_chain) + 1) self.chassis_chain[chassis].connect()
python
def add(self, chassis): """ add chassis. :param chassis: chassis IP address. """ self.chassis_chain[chassis] = IxeChassis(self.session, chassis, len(self.chassis_chain) + 1) self.chassis_chain[chassis].connect()
[ "def", "add", "(", "self", ",", "chassis", ")", ":", "self", ".", "chassis_chain", "[", "chassis", "]", "=", "IxeChassis", "(", "self", ".", "session", ",", "chassis", ",", "len", "(", "self", ".", "chassis_chain", ")", "+", "1", ")", "self", ".", ...
add chassis. :param chassis: chassis IP address.
[ "add", "chassis", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L58-L65
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.reserve_ports
def reserve_ports(self, ports_locations, force=False, clear=True, phy_mode=IxePhyMode.ignore): """ Reserve ports and reset factory defaults. :param ports_locations: list of ports ports_locations <ip, card, port> to reserve :param force: True - take forcefully, False - fail if port is reserved by other user :param clear: True - clear port configuration and statistics, False - leave port as is :param phy_mode: requested PHY mode. :return: ports dictionary (port uri, port object) """ for port_location in ports_locations: ip, card, port = port_location.split('/') chassis = self.get_objects_with_attribute('chassis', 'ipAddress', ip)[0].id uri = '{} {} {}'.format(chassis, card, port) port = IxePort(parent=self, uri=uri) port._data['name'] = port_location port.reserve(force=force) if clear: port.clear() return self.ports
python
def reserve_ports(self, ports_locations, force=False, clear=True, phy_mode=IxePhyMode.ignore): """ Reserve ports and reset factory defaults. :param ports_locations: list of ports ports_locations <ip, card, port> to reserve :param force: True - take forcefully, False - fail if port is reserved by other user :param clear: True - clear port configuration and statistics, False - leave port as is :param phy_mode: requested PHY mode. :return: ports dictionary (port uri, port object) """ for port_location in ports_locations: ip, card, port = port_location.split('/') chassis = self.get_objects_with_attribute('chassis', 'ipAddress', ip)[0].id uri = '{} {} {}'.format(chassis, card, port) port = IxePort(parent=self, uri=uri) port._data['name'] = port_location port.reserve(force=force) if clear: port.clear() return self.ports
[ "def", "reserve_ports", "(", "self", ",", "ports_locations", ",", "force", "=", "False", ",", "clear", "=", "True", ",", "phy_mode", "=", "IxePhyMode", ".", "ignore", ")", ":", "for", "port_location", "in", "ports_locations", ":", "ip", ",", "card", ",", ...
Reserve ports and reset factory defaults. :param ports_locations: list of ports ports_locations <ip, card, port> to reserve :param force: True - take forcefully, False - fail if port is reserved by other user :param clear: True - clear port configuration and statistics, False - leave port as is :param phy_mode: requested PHY mode. :return: ports dictionary (port uri, port object)
[ "Reserve", "ports", "and", "reset", "factory", "defaults", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L94-L114
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.wait_for_up
def wait_for_up(self, timeout=16, ports=None): """ Wait until ports reach up state. :param timeout: seconds to wait. :param ports: list of ports to wait for. :return: """ port_list = [] for port in ports: port_list.append(self.set_ports_list(port)) t_end = time.time() + timeout ports_not_in_up = [] ports_in_up = [] while time.time() < t_end: # ixCheckLinkState can take few seconds on some ports when link is down. for port in port_list: call = self.api.call('ixCheckLinkState {}'.format(port)) if call == '0': ports_in_up.append("{}".format(port)) else: pass ports_in_up = list(set(ports_in_up)) if len(port_list) == len(ports_in_up): return time.sleep(1) for port in port_list: if port not in ports_in_up: ports_not_in_up.append(port) raise TgnError('{}'.format(ports_not_in_up))
python
def wait_for_up(self, timeout=16, ports=None): """ Wait until ports reach up state. :param timeout: seconds to wait. :param ports: list of ports to wait for. :return: """ port_list = [] for port in ports: port_list.append(self.set_ports_list(port)) t_end = time.time() + timeout ports_not_in_up = [] ports_in_up = [] while time.time() < t_end: # ixCheckLinkState can take few seconds on some ports when link is down. for port in port_list: call = self.api.call('ixCheckLinkState {}'.format(port)) if call == '0': ports_in_up.append("{}".format(port)) else: pass ports_in_up = list(set(ports_in_up)) if len(port_list) == len(ports_in_up): return time.sleep(1) for port in port_list: if port not in ports_in_up: ports_not_in_up.append(port) raise TgnError('{}'.format(ports_not_in_up))
[ "def", "wait_for_up", "(", "self", ",", "timeout", "=", "16", ",", "ports", "=", "None", ")", ":", "port_list", "=", "[", "]", "for", "port", "in", "ports", ":", "port_list", ".", "append", "(", "self", ".", "set_ports_list", "(", "port", ")", ")", ...
Wait until ports reach up state. :param timeout: seconds to wait. :param ports: list of ports to wait for. :return:
[ "Wait", "until", "ports", "reach", "up", "state", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L116-L144
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.clear_all_stats
def clear_all_stats(self, *ports): """ Clear all statistic counters (port, streams and packet groups) on list of ports. :param ports: list of ports to clear. """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixClearStats {}'.format(port_list)) self.api.call_rc('ixClearPacketGroups {}'.format(port_list))
python
def clear_all_stats(self, *ports): """ Clear all statistic counters (port, streams and packet groups) on list of ports. :param ports: list of ports to clear. """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixClearStats {}'.format(port_list)) self.api.call_rc('ixClearPacketGroups {}'.format(port_list))
[ "def", "clear_all_stats", "(", "self", ",", "*", "ports", ")", ":", "port_list", "=", "self", ".", "set_ports_list", "(", "*", "ports", ")", "self", ".", "api", ".", "call_rc", "(", "'ixClearStats {}'", ".", "format", "(", "port_list", ")", ")", "self", ...
Clear all statistic counters (port, streams and packet groups) on list of ports. :param ports: list of ports to clear.
[ "Clear", "all", "statistic", "counters", "(", "port", "streams", "and", "packet", "groups", ")", "on", "list", "of", "ports", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L146-L154
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.start_transmit
def start_transmit(self, blocking=False, start_packet_groups=True, *ports): """ Start transmit on ports. :param blocking: True - wait for traffic end, False - return after traffic start. :param start_packet_groups: True - clear time stamps and start collecting packet groups stats, False - don't. :param ports: list of ports to start traffic on, if empty start on all ports. """ port_list = self.set_ports_list(*ports) if start_packet_groups: port_list_for_packet_groups = self.ports.values() port_list_for_packet_groups = self.set_ports_list(*port_list_for_packet_groups) self.api.call_rc('ixClearTimeStamp {}'.format(port_list_for_packet_groups)) self.api.call_rc('ixStartPacketGroups {}'.format(port_list_for_packet_groups)) self.api.call_rc('ixStartTransmit {}'.format(port_list)) time.sleep(0.2) if blocking: self.wait_transmit(*ports)
python
def start_transmit(self, blocking=False, start_packet_groups=True, *ports): """ Start transmit on ports. :param blocking: True - wait for traffic end, False - return after traffic start. :param start_packet_groups: True - clear time stamps and start collecting packet groups stats, False - don't. :param ports: list of ports to start traffic on, if empty start on all ports. """ port_list = self.set_ports_list(*ports) if start_packet_groups: port_list_for_packet_groups = self.ports.values() port_list_for_packet_groups = self.set_ports_list(*port_list_for_packet_groups) self.api.call_rc('ixClearTimeStamp {}'.format(port_list_for_packet_groups)) self.api.call_rc('ixStartPacketGroups {}'.format(port_list_for_packet_groups)) self.api.call_rc('ixStartTransmit {}'.format(port_list)) time.sleep(0.2) if blocking: self.wait_transmit(*ports)
[ "def", "start_transmit", "(", "self", ",", "blocking", "=", "False", ",", "start_packet_groups", "=", "True", ",", "*", "ports", ")", ":", "port_list", "=", "self", ".", "set_ports_list", "(", "*", "ports", ")", "if", "start_packet_groups", ":", "port_list_f...
Start transmit on ports. :param blocking: True - wait for traffic end, False - return after traffic start. :param start_packet_groups: True - clear time stamps and start collecting packet groups stats, False - don't. :param ports: list of ports to start traffic on, if empty start on all ports.
[ "Start", "transmit", "on", "ports", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L156-L174
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.start_packet_groups
def start_packet_groups(self, clear_time_stamps=True, *ports): """ Start packet groups on ports. :param clear_time_stamps: True - clear time stamps, False - don't. :param ports: list of ports to start traffic on, if empty start on all ports. """ port_list = self.set_ports_list(*ports) if clear_time_stamps: self.api.call_rc('ixClearTimeStamp {}'.format(port_list)) self.api.call_rc('ixStartPacketGroups {}'.format(port_list))
python
def start_packet_groups(self, clear_time_stamps=True, *ports): """ Start packet groups on ports. :param clear_time_stamps: True - clear time stamps, False - don't. :param ports: list of ports to start traffic on, if empty start on all ports. """ port_list = self.set_ports_list(*ports) if clear_time_stamps: self.api.call_rc('ixClearTimeStamp {}'.format(port_list)) self.api.call_rc('ixStartPacketGroups {}'.format(port_list))
[ "def", "start_packet_groups", "(", "self", ",", "clear_time_stamps", "=", "True", ",", "*", "ports", ")", ":", "port_list", "=", "self", ".", "set_ports_list", "(", "*", "ports", ")", "if", "clear_time_stamps", ":", "self", ".", "api", ".", "call_rc", "(",...
Start packet groups on ports. :param clear_time_stamps: True - clear time stamps, False - don't. :param ports: list of ports to start traffic on, if empty start on all ports.
[ "Start", "packet", "groups", "on", "ports", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L176-L185
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.stop_transmit
def stop_transmit(self, *ports): """ Stop traffic on ports. :param ports: list of ports to stop traffic on, if empty start on all ports. """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixStopTransmit {}'.format(port_list)) time.sleep(0.2)
python
def stop_transmit(self, *ports): """ Stop traffic on ports. :param ports: list of ports to stop traffic on, if empty start on all ports. """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixStopTransmit {}'.format(port_list)) time.sleep(0.2)
[ "def", "stop_transmit", "(", "self", ",", "*", "ports", ")", ":", "port_list", "=", "self", ".", "set_ports_list", "(", "*", "ports", ")", "self", ".", "api", ".", "call_rc", "(", "'ixStopTransmit {}'", ".", "format", "(", "port_list", ")", ")", "time", ...
Stop traffic on ports. :param ports: list of ports to stop traffic on, if empty start on all ports.
[ "Stop", "traffic", "on", "ports", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L187-L195
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.wait_transmit
def wait_transmit(self, *ports): """ Wait for traffic end on ports. :param ports: list of ports to wait for, if empty wait for all ports. """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixCheckTransmitDone {}'.format(port_list))
python
def wait_transmit(self, *ports): """ Wait for traffic end on ports. :param ports: list of ports to wait for, if empty wait for all ports. """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixCheckTransmitDone {}'.format(port_list))
[ "def", "wait_transmit", "(", "self", ",", "*", "ports", ")", ":", "port_list", "=", "self", ".", "set_ports_list", "(", "*", "ports", ")", "self", ".", "api", ".", "call_rc", "(", "'ixCheckTransmitDone {}'", ".", "format", "(", "port_list", ")", ")" ]
Wait for traffic end on ports. :param ports: list of ports to wait for, if empty wait for all ports.
[ "Wait", "for", "traffic", "end", "on", "ports", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L197-L204
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.start_capture
def start_capture(self, *ports): """ Start capture on ports. :param ports: list of ports to start capture on, if empty start on all ports. """ IxeCapture.current_object = None IxeCaptureBuffer.current_object = None if not ports: ports = self.ports.values() for port in ports: port.captureBuffer = None port_list = self.set_ports_list(*ports) self.api.call_rc('ixStartCapture {}'.format(port_list))
python
def start_capture(self, *ports): """ Start capture on ports. :param ports: list of ports to start capture on, if empty start on all ports. """ IxeCapture.current_object = None IxeCaptureBuffer.current_object = None if not ports: ports = self.ports.values() for port in ports: port.captureBuffer = None port_list = self.set_ports_list(*ports) self.api.call_rc('ixStartCapture {}'.format(port_list))
[ "def", "start_capture", "(", "self", ",", "*", "ports", ")", ":", "IxeCapture", ".", "current_object", "=", "None", "IxeCaptureBuffer", ".", "current_object", "=", "None", "if", "not", "ports", ":", "ports", "=", "self", ".", "ports", ".", "values", "(", ...
Start capture on ports. :param ports: list of ports to start capture on, if empty start on all ports.
[ "Start", "capture", "on", "ports", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L206-L219
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.stop_capture
def stop_capture(self, cap_file_name=None, cap_file_format=IxeCapFileFormat.mem, *ports): """ Stop capture on ports. :param cap_file_name: prefix for the capture file name. Capture files for each port are saved as individual pcap file named 'prefix' + 'URI'.pcap. :param cap_file_format: exported file format :param ports: list of ports to stop traffic on, if empty stop all ports. :return: dictionary (port, nPackets) """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixStopCapture {}'.format(port_list)) nPackets = {} for port in (ports if ports else self.ports.values()): nPackets[port] = port.capture.nPackets if nPackets[port]: if cap_file_format is not IxeCapFileFormat.mem: port.cap_file_name = cap_file_name + '-' + port.uri.replace(' ', '_') + '.' + cap_file_format.name port.captureBuffer.export(port.cap_file_name) return nPackets
python
def stop_capture(self, cap_file_name=None, cap_file_format=IxeCapFileFormat.mem, *ports): """ Stop capture on ports. :param cap_file_name: prefix for the capture file name. Capture files for each port are saved as individual pcap file named 'prefix' + 'URI'.pcap. :param cap_file_format: exported file format :param ports: list of ports to stop traffic on, if empty stop all ports. :return: dictionary (port, nPackets) """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixStopCapture {}'.format(port_list)) nPackets = {} for port in (ports if ports else self.ports.values()): nPackets[port] = port.capture.nPackets if nPackets[port]: if cap_file_format is not IxeCapFileFormat.mem: port.cap_file_name = cap_file_name + '-' + port.uri.replace(' ', '_') + '.' + cap_file_format.name port.captureBuffer.export(port.cap_file_name) return nPackets
[ "def", "stop_capture", "(", "self", ",", "cap_file_name", "=", "None", ",", "cap_file_format", "=", "IxeCapFileFormat", ".", "mem", ",", "*", "ports", ")", ":", "port_list", "=", "self", ".", "set_ports_list", "(", "*", "ports", ")", "self", ".", "api", ...
Stop capture on ports. :param cap_file_name: prefix for the capture file name. Capture files for each port are saved as individual pcap file named 'prefix' + 'URI'.pcap. :param cap_file_format: exported file format :param ports: list of ports to stop traffic on, if empty stop all ports. :return: dictionary (port, nPackets)
[ "Stop", "capture", "on", "ports", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L221-L241
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.get_cap_files
def get_cap_files(self, *ports): """ :param ports: list of ports to get capture files names for. :return: dictionary (port, capture file) """ cap_files = {} for port in ports: if port.cap_file_name: with open(port.cap_file_name) as f: cap_files[port] = f.read().splitlines() else: cap_files[port] = None return cap_files
python
def get_cap_files(self, *ports): """ :param ports: list of ports to get capture files names for. :return: dictionary (port, capture file) """ cap_files = {} for port in ports: if port.cap_file_name: with open(port.cap_file_name) as f: cap_files[port] = f.read().splitlines() else: cap_files[port] = None return cap_files
[ "def", "get_cap_files", "(", "self", ",", "*", "ports", ")", ":", "cap_files", "=", "{", "}", "for", "port", "in", "ports", ":", "if", "port", ".", "cap_file_name", ":", "with", "open", "(", "port", ".", "cap_file_name", ")", "as", "f", ":", "cap_fil...
:param ports: list of ports to get capture files names for. :return: dictionary (port, capture file)
[ ":", "param", "ports", ":", "list", "of", "ports", "to", "get", "capture", "files", "names", "for", ".", ":", "return", ":", "dictionary", "(", "port", "capture", "file", ")" ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L243-L255
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.set_stream_stats
def set_stream_stats(self, rx_ports=None, tx_ports=None, start_offset=40, sequence_checking=True, data_integrity=True, timestamp=True): """ Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX pgs. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX pgs. If empty set for all streams. :type tx_ports: dict[ixexplorer.ixe_port.IxePort, list[ixexplorer.ixe_stream.IxeStream]] :param sequence_checking: True - enable sequence checkbox, False - disable :param data_integrity: True - enable data integrity checkbox, False - disable :param timestamp: True - enable timestamp checkbox, False - disable :param start_offset: start offset for signatures (group ID, signature, sequence) """ if not rx_ports: rx_ports = self.ports.values() if not tx_ports: tx_ports = {} for port in self.ports.values(): tx_ports[port] = port.streams.values() groupIdOffset = start_offset signatureOffset = start_offset + 4 next_offset = start_offset + 8 if sequence_checking: sequenceNumberOffset = next_offset next_offset += 4 if data_integrity: di_signatureOffset = next_offset for port in rx_ports: modes = [] modes.append(IxeReceiveMode.widePacketGroup) port.packetGroup.groupIdOffset = groupIdOffset port.packetGroup.signatureOffset = signatureOffset if sequence_checking and int(port.isValidFeature('portFeatureRxSequenceChecking')): modes.append(IxeReceiveMode.sequenceChecking) port.packetGroup.sequenceNumberOffset = sequenceNumberOffset if data_integrity and int(port.isValidFeature('portFeatureRxDataIntegrity')): modes.append(IxeReceiveMode.dataIntegrity) port.dataIntegrity.signatureOffset = di_signatureOffset if timestamp and int(port.isValidFeature('portFeatureRxFirstTimeStamp')): port.dataIntegrity.enableTimeStamp = True else: port.dataIntegrity.enableTimeStamp = False port.set_receive_modes(*modes) port.write() for port, streams in tx_ports.items(): for stream in streams: stream.packetGroup.insertSignature = True stream.packetGroup.groupIdOffset = groupIdOffset stream.packetGroup.signatureOffset = signatureOffset if sequence_checking: stream.packetGroup.insertSequenceSignature = True stream.packetGroup.sequenceNumberOffset = sequenceNumberOffset if data_integrity and int(port.isValidFeature('portFeatureRxDataIntegrity')): stream.dataIntegrity.insertSignature = True stream.dataIntegrity.signatureOffset = di_signatureOffset if timestamp: stream.enableTimestamp = True else: stream.enableTimestamp = False port.write()
python
def set_stream_stats(self, rx_ports=None, tx_ports=None, start_offset=40, sequence_checking=True, data_integrity=True, timestamp=True): """ Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX pgs. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX pgs. If empty set for all streams. :type tx_ports: dict[ixexplorer.ixe_port.IxePort, list[ixexplorer.ixe_stream.IxeStream]] :param sequence_checking: True - enable sequence checkbox, False - disable :param data_integrity: True - enable data integrity checkbox, False - disable :param timestamp: True - enable timestamp checkbox, False - disable :param start_offset: start offset for signatures (group ID, signature, sequence) """ if not rx_ports: rx_ports = self.ports.values() if not tx_ports: tx_ports = {} for port in self.ports.values(): tx_ports[port] = port.streams.values() groupIdOffset = start_offset signatureOffset = start_offset + 4 next_offset = start_offset + 8 if sequence_checking: sequenceNumberOffset = next_offset next_offset += 4 if data_integrity: di_signatureOffset = next_offset for port in rx_ports: modes = [] modes.append(IxeReceiveMode.widePacketGroup) port.packetGroup.groupIdOffset = groupIdOffset port.packetGroup.signatureOffset = signatureOffset if sequence_checking and int(port.isValidFeature('portFeatureRxSequenceChecking')): modes.append(IxeReceiveMode.sequenceChecking) port.packetGroup.sequenceNumberOffset = sequenceNumberOffset if data_integrity and int(port.isValidFeature('portFeatureRxDataIntegrity')): modes.append(IxeReceiveMode.dataIntegrity) port.dataIntegrity.signatureOffset = di_signatureOffset if timestamp and int(port.isValidFeature('portFeatureRxFirstTimeStamp')): port.dataIntegrity.enableTimeStamp = True else: port.dataIntegrity.enableTimeStamp = False port.set_receive_modes(*modes) port.write() for port, streams in tx_ports.items(): for stream in streams: stream.packetGroup.insertSignature = True stream.packetGroup.groupIdOffset = groupIdOffset stream.packetGroup.signatureOffset = signatureOffset if sequence_checking: stream.packetGroup.insertSequenceSignature = True stream.packetGroup.sequenceNumberOffset = sequenceNumberOffset if data_integrity and int(port.isValidFeature('portFeatureRxDataIntegrity')): stream.dataIntegrity.insertSignature = True stream.dataIntegrity.signatureOffset = di_signatureOffset if timestamp: stream.enableTimestamp = True else: stream.enableTimestamp = False port.write()
[ "def", "set_stream_stats", "(", "self", ",", "rx_ports", "=", "None", ",", "tx_ports", "=", "None", ",", "start_offset", "=", "40", ",", "sequence_checking", "=", "True", ",", "data_integrity", "=", "True", ",", "timestamp", "=", "True", ")", ":", "if", ...
Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX pgs. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX pgs. If empty set for all streams. :type tx_ports: dict[ixexplorer.ixe_port.IxePort, list[ixexplorer.ixe_stream.IxeStream]] :param sequence_checking: True - enable sequence checkbox, False - disable :param data_integrity: True - enable data integrity checkbox, False - disable :param timestamp: True - enable timestamp checkbox, False - disable :param start_offset: start offset for signatures (group ID, signature, sequence)
[ "Set", "TX", "ports", "and", "RX", "streams", "for", "stream", "statistics", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L266-L332
shmir/PyIxExplorer
ixexplorer/ixe_app.py
IxeSession.set_prbs
def set_prbs(self, rx_ports=None, tx_ports=None): """ Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX PRBS. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX PRBS. If empty set for all streams. :type tx_ports: dict[ixexplorer.ixe_port.IxePort, list[ixexplorer.ixe_stream.IxeStream]] """ if not rx_ports: rx_ports = self.ports.values() if not tx_ports: tx_ports = {} for port in self.ports.values(): tx_ports[port] = port.streams.values() for port in rx_ports: port.set_receive_modes(IxeReceiveMode.widePacketGroup, IxeReceiveMode.sequenceChecking, IxeReceiveMode.prbs) port.enableAutoDetectInstrumentation = True port.autoDetectInstrumentation.ix_set_default() port.write() for port, streams in tx_ports.items(): for stream in streams: stream.autoDetectInstrumentation.enableTxAutomaticInstrumentation = True stream.autoDetectInstrumentation.enablePRBS = True port.write()
python
def set_prbs(self, rx_ports=None, tx_ports=None): """ Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX PRBS. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX PRBS. If empty set for all streams. :type tx_ports: dict[ixexplorer.ixe_port.IxePort, list[ixexplorer.ixe_stream.IxeStream]] """ if not rx_ports: rx_ports = self.ports.values() if not tx_ports: tx_ports = {} for port in self.ports.values(): tx_ports[port] = port.streams.values() for port in rx_ports: port.set_receive_modes(IxeReceiveMode.widePacketGroup, IxeReceiveMode.sequenceChecking, IxeReceiveMode.prbs) port.enableAutoDetectInstrumentation = True port.autoDetectInstrumentation.ix_set_default() port.write() for port, streams in tx_ports.items(): for stream in streams: stream.autoDetectInstrumentation.enableTxAutomaticInstrumentation = True stream.autoDetectInstrumentation.enablePRBS = True port.write()
[ "def", "set_prbs", "(", "self", ",", "rx_ports", "=", "None", ",", "tx_ports", "=", "None", ")", ":", "if", "not", "rx_ports", ":", "rx_ports", "=", "self", ".", "ports", ".", "values", "(", ")", "if", "not", "tx_ports", ":", "tx_ports", "=", "{", ...
Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX PRBS. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX PRBS. If empty set for all streams. :type tx_ports: dict[ixexplorer.ixe_port.IxePort, list[ixexplorer.ixe_stream.IxeStream]]
[ "Set", "TX", "ports", "and", "RX", "streams", "for", "stream", "statistics", "." ]
train
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L334-L362
biocommons/bioutils
src/bioutils/accessions.py
chr22XY
def chr22XY(c): """force to name from 1..22, 23, 24, X, Y, M to in chr1..chr22, chrX, chrY, chrM str or ints accepted >>> chr22XY('1') 'chr1' >>> chr22XY(1) 'chr1' >>> chr22XY('chr1') 'chr1' >>> chr22XY(23) 'chrX' >>> chr22XY(24) 'chrY' >>> chr22XY("X") 'chrX' >>> chr22XY("23") 'chrX' >>> chr22XY("M") 'chrM' """ c = str(c) if c[0:3] == 'chr': c = c[3:] if c == '23': c = 'X' if c == '24': c = 'Y' return 'chr' + c
python
def chr22XY(c): """force to name from 1..22, 23, 24, X, Y, M to in chr1..chr22, chrX, chrY, chrM str or ints accepted >>> chr22XY('1') 'chr1' >>> chr22XY(1) 'chr1' >>> chr22XY('chr1') 'chr1' >>> chr22XY(23) 'chrX' >>> chr22XY(24) 'chrY' >>> chr22XY("X") 'chrX' >>> chr22XY("23") 'chrX' >>> chr22XY("M") 'chrM' """ c = str(c) if c[0:3] == 'chr': c = c[3:] if c == '23': c = 'X' if c == '24': c = 'Y' return 'chr' + c
[ "def", "chr22XY", "(", "c", ")", ":", "c", "=", "str", "(", "c", ")", "if", "c", "[", "0", ":", "3", "]", "==", "'chr'", ":", "c", "=", "c", "[", "3", ":", "]", "if", "c", "==", "'23'", ":", "c", "=", "'X'", "if", "c", "==", "'24'", "...
force to name from 1..22, 23, 24, X, Y, M to in chr1..chr22, chrX, chrY, chrM str or ints accepted >>> chr22XY('1') 'chr1' >>> chr22XY(1) 'chr1' >>> chr22XY('chr1') 'chr1' >>> chr22XY(23) 'chrX' >>> chr22XY(24) 'chrY' >>> chr22XY("X") 'chrX' >>> chr22XY("23") 'chrX' >>> chr22XY("M") 'chrM'
[ "force", "to", "name", "from", "1", "..", "22", "23", "24", "X", "Y", "M", "to", "in", "chr1", "..", "chr22", "chrX", "chrY", "chrM", "str", "or", "ints", "accepted" ]
train
https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/accessions.py#L81-L111
biocommons/bioutils
src/bioutils/accessions.py
infer_namespace
def infer_namespace(ac): """Infer the single namespace of the given accession This function is convenience wrapper around infer_namespaces(). Returns: * None if no namespaces are inferred * The (single) namespace if only one namespace is inferred * Raises an exception if more than one namespace is inferred >>> infer_namespace("ENST00000530893.6") 'ensembl' >>> infer_namespace("NM_01234.5") 'refseq' >>> infer_namespace("A2BC19") 'uniprot' N.B. The following test is disabled because Python 2 and Python 3 handle doctest exceptions differently. :-( X>>> infer_namespace("P12345") Traceback (most recent call last): ... bioutils.exceptions.BioutilsError: Multiple namespaces possible for P12345 >>> infer_namespace("BOGUS99") is None True """ namespaces = infer_namespaces(ac) if not namespaces: return None if len(namespaces) > 1: raise BioutilsError("Multiple namespaces possible for {}".format(ac)) return namespaces[0]
python
def infer_namespace(ac): """Infer the single namespace of the given accession This function is convenience wrapper around infer_namespaces(). Returns: * None if no namespaces are inferred * The (single) namespace if only one namespace is inferred * Raises an exception if more than one namespace is inferred >>> infer_namespace("ENST00000530893.6") 'ensembl' >>> infer_namespace("NM_01234.5") 'refseq' >>> infer_namespace("A2BC19") 'uniprot' N.B. The following test is disabled because Python 2 and Python 3 handle doctest exceptions differently. :-( X>>> infer_namespace("P12345") Traceback (most recent call last): ... bioutils.exceptions.BioutilsError: Multiple namespaces possible for P12345 >>> infer_namespace("BOGUS99") is None True """ namespaces = infer_namespaces(ac) if not namespaces: return None if len(namespaces) > 1: raise BioutilsError("Multiple namespaces possible for {}".format(ac)) return namespaces[0]
[ "def", "infer_namespace", "(", "ac", ")", ":", "namespaces", "=", "infer_namespaces", "(", "ac", ")", "if", "not", "namespaces", ":", "return", "None", "if", "len", "(", "namespaces", ")", ">", "1", ":", "raise", "BioutilsError", "(", "\"Multiple namespaces ...
Infer the single namespace of the given accession This function is convenience wrapper around infer_namespaces(). Returns: * None if no namespaces are inferred * The (single) namespace if only one namespace is inferred * Raises an exception if more than one namespace is inferred >>> infer_namespace("ENST00000530893.6") 'ensembl' >>> infer_namespace("NM_01234.5") 'refseq' >>> infer_namespace("A2BC19") 'uniprot' N.B. The following test is disabled because Python 2 and Python 3 handle doctest exceptions differently. :-( X>>> infer_namespace("P12345") Traceback (most recent call last): ... bioutils.exceptions.BioutilsError: Multiple namespaces possible for P12345 >>> infer_namespace("BOGUS99") is None True
[ "Infer", "the", "single", "namespace", "of", "the", "given", "accession" ]
train
https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/accessions.py#L114-L149
biocommons/bioutils
src/bioutils/accessions.py
infer_namespaces
def infer_namespaces(ac): """infer possible namespaces of given accession based on syntax Always returns a list, possibly empty >>> infer_namespaces("ENST00000530893.6") ['ensembl'] >>> infer_namespaces("ENST00000530893") ['ensembl'] >>> infer_namespaces("ENSQ00000530893") [] >>> infer_namespaces("NM_01234") ['refseq'] >>> infer_namespaces("NM_01234.5") ['refseq'] >>> infer_namespaces("NQ_01234.5") [] >>> infer_namespaces("A2BC19") ['uniprot'] >>> sorted(infer_namespaces("P12345")) ['insdc', 'uniprot'] >>> infer_namespaces("A0A022YWF9") ['uniprot'] """ return [v for k, v in ac_namespace_regexps.items() if k.match(ac)]
python
def infer_namespaces(ac): """infer possible namespaces of given accession based on syntax Always returns a list, possibly empty >>> infer_namespaces("ENST00000530893.6") ['ensembl'] >>> infer_namespaces("ENST00000530893") ['ensembl'] >>> infer_namespaces("ENSQ00000530893") [] >>> infer_namespaces("NM_01234") ['refseq'] >>> infer_namespaces("NM_01234.5") ['refseq'] >>> infer_namespaces("NQ_01234.5") [] >>> infer_namespaces("A2BC19") ['uniprot'] >>> sorted(infer_namespaces("P12345")) ['insdc', 'uniprot'] >>> infer_namespaces("A0A022YWF9") ['uniprot'] """ return [v for k, v in ac_namespace_regexps.items() if k.match(ac)]
[ "def", "infer_namespaces", "(", "ac", ")", ":", "return", "[", "v", "for", "k", ",", "v", "in", "ac_namespace_regexps", ".", "items", "(", ")", "if", "k", ".", "match", "(", "ac", ")", "]" ]
infer possible namespaces of given accession based on syntax Always returns a list, possibly empty >>> infer_namespaces("ENST00000530893.6") ['ensembl'] >>> infer_namespaces("ENST00000530893") ['ensembl'] >>> infer_namespaces("ENSQ00000530893") [] >>> infer_namespaces("NM_01234") ['refseq'] >>> infer_namespaces("NM_01234.5") ['refseq'] >>> infer_namespaces("NQ_01234.5") [] >>> infer_namespaces("A2BC19") ['uniprot'] >>> sorted(infer_namespaces("P12345")) ['insdc', 'uniprot'] >>> infer_namespaces("A0A022YWF9") ['uniprot']
[ "infer", "possible", "namespaces", "of", "given", "accession", "based", "on", "syntax", "Always", "returns", "a", "list", "possibly", "empty" ]
train
https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/accessions.py#L152-L177
intiocean/pyinter
pyinter/interval_set.py
IntervalSet._add
def _add(self, other): """Add a interval to the underlying IntervalSet data store. This does not perform any tests as we assume that any requirements have already been checked and that this function is being called by an internal function such as union(), intersection() or add(). :param other: An Interval to add to this one """ if len([interval for interval in self if other in interval]) > 0: # if other is already represented return # remove any intervals which are fully represented by the interval we are adding to_remove = [interval for interval in self if interval in other] self._data.difference_update(to_remove) self._data.add(other)
python
def _add(self, other): """Add a interval to the underlying IntervalSet data store. This does not perform any tests as we assume that any requirements have already been checked and that this function is being called by an internal function such as union(), intersection() or add(). :param other: An Interval to add to this one """ if len([interval for interval in self if other in interval]) > 0: # if other is already represented return # remove any intervals which are fully represented by the interval we are adding to_remove = [interval for interval in self if interval in other] self._data.difference_update(to_remove) self._data.add(other)
[ "def", "_add", "(", "self", ",", "other", ")", ":", "if", "len", "(", "[", "interval", "for", "interval", "in", "self", "if", "other", "in", "interval", "]", ")", ">", "0", ":", "# if other is already represented", "return", "# remove any intervals which are f...
Add a interval to the underlying IntervalSet data store. This does not perform any tests as we assume that any requirements have already been checked and that this function is being called by an internal function such as union(), intersection() or add(). :param other: An Interval to add to this one
[ "Add", "a", "interval", "to", "the", "underlying", "IntervalSet", "data", "store", ".", "This", "does", "not", "perform", "any", "tests", "as", "we", "assume", "that", "any", "requirements", "have", "already", "been", "checked", "and", "that", "this", "funct...
train
https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval_set.py#L36-L47
intiocean/pyinter
pyinter/interval_set.py
IntervalSet.intersection
def intersection(self, other): """Returns a new IntervalSet which represents the intersection of each of the intervals in this IntervalSet with each of the intervals in the other IntervalSet. :param other: An IntervalSet to intersect with this one. """ # if self or other is empty the intersection will be empty result = IntervalSet() for other_inter in other: for interval in self: this_intervals_intersection = other_inter.intersect(interval) if this_intervals_intersection is not None: result._add(this_intervals_intersection) return result
python
def intersection(self, other): """Returns a new IntervalSet which represents the intersection of each of the intervals in this IntervalSet with each of the intervals in the other IntervalSet. :param other: An IntervalSet to intersect with this one. """ # if self or other is empty the intersection will be empty result = IntervalSet() for other_inter in other: for interval in self: this_intervals_intersection = other_inter.intersect(interval) if this_intervals_intersection is not None: result._add(this_intervals_intersection) return result
[ "def", "intersection", "(", "self", ",", "other", ")", ":", "# if self or other is empty the intersection will be empty", "result", "=", "IntervalSet", "(", ")", "for", "other_inter", "in", "other", ":", "for", "interval", "in", "self", ":", "this_intervals_intersecti...
Returns a new IntervalSet which represents the intersection of each of the intervals in this IntervalSet with each of the intervals in the other IntervalSet. :param other: An IntervalSet to intersect with this one.
[ "Returns", "a", "new", "IntervalSet", "which", "represents", "the", "intersection", "of", "each", "of", "the", "intervals", "in", "this", "IntervalSet", "with", "each", "of", "the", "intervals", "in", "the", "other", "IntervalSet", ".", ":", "param", "other", ...
train
https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval_set.py#L53-L65