code stringlengths 1 18.2k |
|---|
def toString(self, format_='fasta-ss', structureSuffix=':structure'): """ Convert the read to a string in PDB format (sequence & structure). This consists of two FASTA records, one for the sequence then one for the structure. @param format_: Either 'fasta-ss' or 'fasta'. In the former case, the structure information is... |
def newFromSites(self, sites, exclude=False): """ Create a new read from self, with only certain sites. @param sites: A set of C{int} 0-based sites (i.e., indices) in sequences that should be kept. If C{None} (the default), all sites are kept. @param exclude: If C{True} the C{sites} will be excluded, not included. """ ... |
def toDict(self): """ Get information about this read in a dictionary. @return: A C{dict} with keys/values for the attributes of self. """ if six.PY3: result = super().toDict() else: result = AARead.toDict(self) result.update({ 'frame': self.frame, 'reverseComplemented': self.reverseComplemented, }) return result |
def fromDict(cls, d): """ Create a new instance from attribute values provided in a dictionary. @param d: A C{dict} with keys/values for the attributes of a new instance of this class. Keys 'id' and 'sequence' with C{str} values must be provided. A 'quality' C{str} key is optional. Key 'frame' must have an C{int} value... |
def maximumORFLength(self, openORFs=True): """ Return the length of the longest (possibly partial) ORF in a translated read. The ORF may originate or terminate outside the sequence, which is why the length is just a lower bound. """ return max(len(orf) for orf in self.ORFs(openORFs)) |
def filter(self, read): """ Check if a read passes the filter. @param read: A C{Read} instance. @return: C{read} if C{read} passes the filter, C{False} if not. """ self.readIndex += 1 if self.alwaysFalse: return False if self.wantedSequenceNumberGeneratorExhausted: return False if self.nextWantedSequenceNumber is not N... |
(self.sampleFraction is not None and uniform(0.0, 1.0) > self.sampleFraction): # Note that we don't have to worry about the 0.0 or 1.0 # cases in the above 'if', as they have been dealt with # in self.__init__. return False if self.randomSubset is not None: if self.yieldCount == self.randomSubset: # The random subset h... |
self.removeGaps: if read.quality is None: read = read.__class__(read.id, read.sequence.replace('-', '')) else: newSequence = [] newQuality = [] for base, quality in zip(read.sequence, read.quality): if base != '-': newSequence.append(base) newQuality.append(quality) read = read.__class__( read.id, ''.join(newSequence),... |
self.removeSites is not None: read = read.newFromSites(self.removeSites, exclude=True) if self.idLambda: newId = self.idLambda(read.id) if newId is None: return False else: read.id = newId if self.readLambda: newRead = self.readLambda(read) if newRead is None: return False else: read = newRead if self.removeDescription... |
def filterRead(self, read): """ Filter a read, according to our set of filters. @param read: A C{Read} instance or one of its subclasses. @return: C{False} if the read fails any of our filters, else the C{Read} instance returned by our list of filters. """ for filterFunc in self._filters: filteredRead = filterFunc(read... |
def save(self, filename, format_='fasta'): """ Write the reads to C{filename} in the requested format. @param filename: Either a C{str} file name to save into (the file will be overwritten) or an open file descriptor (e.g., sys.stdout). @param format_: A C{str} format to save as, either 'fasta', 'fastq' or 'fasta-ss'. ... |
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 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 ... |
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 r... |
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 si... |
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): r... |
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 ... |
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 "co... |
"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 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. pva... |
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.inde... |
+= 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 * ... |
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_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: ""... |
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 ... |
[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 significa... |
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])... |
< 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 pre... |
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 se... |
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... |
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 l... |
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(... |
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 = ... |
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 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 e... |
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() ge... |
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 ... |
csv.QUOTE_NONE) for g in sorted(genes.keys()): writer.writerow([g, genes[g]]) return 0 |
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 configura... |
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: boo... |
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 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: it... |
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... |
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 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 entri... |
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['modi... |
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_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(qu... |
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... |
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... |
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 =... |
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 = {'co... |
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): na... |
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)... |
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_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_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... |
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_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... |
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.att... |
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/... |
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 ... |
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_numbe... |
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.... |
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 ... |
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 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... |
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: c... |
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 depe... |
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 c... |
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 plot... |
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 ... |
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... |
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 ch... |
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... |
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('Unsupp... |
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, otherwis... |
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/... |
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 n... |
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 f... |
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 f... |
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 sequ... |
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... |
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 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 a... |
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... |
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_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]... |
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 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_... |
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 ... |
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:... |
%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 = ('SELEC... |
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 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 ... |
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 (lis... |
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 ValueEr... |
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( "Ma... |
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 Non... |
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 ''... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.