code stringlengths 1 18.2k |
|---|
def delete(self, criteria=None, _all=False): ''' delete dictionary(ies) in sqlite database _all = True - delete all items ''' if isinstance(criteria, self._item_class): criteria = {'_id': criteria['_id']} if criteria is None and not _all: raise RuntimeError('Criteria is not defined') SQL = SQLBuilder(self._table, crite... |
def run_tasks(tasks, max_workers=None, use_processes=False): """ Run an iterable of tasks. tasks: The iterable of tasks max_workers: (optional, None) The maximum number of workers to use. As of Python 3.5, if None is passed to the thread executor will default to 5 * the number of processors and the process executor wil... |
results = [] waited = concurrent.futures.wait( futures, return_when=concurrent.futures.FIRST_COMPLETED ) for future in waited.done: exc = future.exception() if exc is None: results.append( TaskResult( future.name, True, None, future.result() ) ) else: results.append(TaskResult(future.name, False, exc, None)) futures.re... |
def wait_for_zone_op(access_token, project, zone, name, interval=1.0): """Wait until a zone operation is finished. TODO: docstring""" assert isinstance(interval, (int, float)) assert interval >= 0.1 status = 'RUNNING' progress = 0 LOGGER.info('Waiting for zone operation "%s" to finish...', name) while status != 'DONE':... |
def _initialise(self): """ Initialises table with dictionary. """ d = {'score': 0, 'pointer': None, 'ins': 0, 'del': 0} cols = len(self.seq1Seq) + 1 rows = len(self.seq2Seq) + 1 # Note that this puts a ref to the same dict (d) into each cell of # the table. Hopefully that is what was intended. Eyeballing the # code bel... |
def _fillAndTraceback(self, table): """ Perform Local Alignment according to Smith-Waterman Algorithm. Fills the table and then traces back from the highest score. NB left = deletion and up = insertion wrt seq1 """ # Fill max_score = 0 max_row = 0 max_col = 0 for row in range(1, len(self.seq2Seq) + 1): for col in range... |
else: if self.gapExtend + ins_run * self.gapExtendDecay <= 0.0: ins_score = (table[row - 1][col]['score'] + self.gapExtend + ins_run * self.gapExtendDecay) else: ins_score = table[row - 1][col]['score'] if table[row - 1][col]['del'] <= 0: del_score = table[row][col - 1]['score'] + self.gapOpen else: if self.gapExtend +... |
'del': del_run + 1} table[row][col] = deletion else: # up diag if ins_score >= del_score: # up diag/lef insertion = {'score': ins_score, 'pointer': 'ins', 'ins': ins_run + 1, 'del': 0} table[row][col] = insertion else: # lef up diag deletion = {'score': del_score, 'pointer': 'del', 'ins': 0, 'del': del_run + 1} table[r... |
= current_col + 1 break elif arrow == 'diagonal': align1 += self.seq1Seq[current_col - 1] align2 += self.seq2Seq[current_row - 1] if self.seq1Seq[current_col - 1] == self.seq2Seq[ current_row - 1]: align += '|' else: align += ' ' current_row -= 1 current_col -= 1 elif arrow == 'del': align1 += self.seq1Seq[current_col ... |
def _cigarString(self, output): """ Return a cigar string of aligned sequences. @param output: a C{tup} of strings (align1, align, align2) @return: a C{str} containing the cigar string. Eg with input: 'GGCCCGCA' and 'GG-CTGCA', return 2=1D1=1X3= """ cigar = [] count = 0 align1 = output[0] align2 = output[2] for nt1, nt... |
character == previousCharacter: count += 1 else: cigarString += (str(count) + str(previousCharacter)) count = 1 previousCharacter = character return cigarString |
def _alignmentToStr(self, result): """ Make a textual representation of an alignment result. @param result: A C{dict}, as returned by C{self.createAlignment}. @return: A C{str} desription of a result. For every three lines the first and third contain the input sequences, possibly padded with '-'. The second contains '|... |
'%s Match start: %d Match end: %d\n' % (result['cigar'], self.seq1ID, result['sequence1Start'], result['sequence1End'], self.seq2ID, result['sequence2Start'], result['sequence2End']) ) text = '\n'.join(result['text']) return header + text |
def createAlignment(self, resultFormat=dict): """ Run the alignment algorithm. @param resultFormat: Either C{dict} or C{str}, giving the desired result format. @return: If C{resultFormat} is C{dict}, a C{dict} containing information about the match (or C{None}) if there is no match. If C{resultFormat} is C{str}, a C{st... |
def select(self, fields=['rowid', '*'], offset=None, limit=None): ''' return SELECT SQL ''' # base SQL SQL = 'SELECT %s FROM %s' % (','.join(fields), self._table) # selectors if self._selectors: SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip() # modifiers if self._modifiers: SQL = ' '.join([SQL, self._modifiers]... |
def delete(self): ''' return DELETE SQL ''' SQL = 'DELETE FROM %s' % self._table if self._selectors: SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip() return SQL |
def _parse(self, params): ''' parse parameters and return SQL ''' if not isinstance(params, dict): return None, None if len(params) == 0: return None, None selectors = list() modifiers = list() for k in params.keys(): if k in LOGICAL_OPERATORS: selectors.append(self._logical(k, params[k])) elif k in QUERY_MODIFIERS: mo... |
def _logical(self, operator, params): ''' $and: joins query clauses with a logical AND returns all items that match the conditions of both clauses $or: joins query clauses with a logical OR returns all items that match the conditions of either clause. ''' result = list() if isinstance(params, dict): for k,v in params.i... |
def _modifier(self, operator, params): ''' $orderby: sorts the results of a query in ascending (1) or descending (-1) order. ''' if operator == '$orderby': order_types = {-1: 'DESC', 1: 'ASC'} if not isinstance(params, dict): raise RuntimeError('Incorrect parameter type, %s' % params) return 'ORDER BY %s' % ','.join(["... |
def _value_wrapper(self, value): ''' wrapper for values ''' if isinstance(value, (int, float,)): return '=%s' % value elif isinstance(value, (str, unicode)): value = value.strip() # LIKE if RE_LIKE.match(value): return ' LIKE %s' % repr(RE_LIKE.match(value).group('RE_LIKE')) # REGEXP elif RE_REGEXP.match(value): return... |
def make_router(*routings): """Return a WSGI application that dispatches requests to controllers """ routes = [] for routing in routings: methods, regex, app = routing[:3] if isinstance(methods, basestring): methods = (methods,) vars = routing[3] if len(routing) >= 4 else {} routes.append((methods, re.compile(unicode(r... |
match = regex.match(req.path_info) if match is not None: if methods is not None and req.method not in methods: ctx = contexts.Ctx(req) headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx) return wsgihelpers.respond_json(ctx, dict( apiVersion = 1, error = dict( code = 405, message = ctx._(u"You cannot use HTT... |
def connect(uri): """ Connects to an nREPL endpoint identified by the given URL/URI. Valid examples include: nrepl://192.168.0.12:7889 telnet://localhost:5000 http://your-app-name.heroku.com/repl This fn delegates to another looked up in that dispatches on the scheme of the URI provided (which can be a string or java.n... |
def watch(self, key, criteria, callback): """ Registers a new watch under [key] (which can be used with `unwatch()` to remove the watch) that filters messages using [criteria] (may be a predicate or a 'criteria dict' [see the README for more info there]). Matching messages are passed to [callback], which must accept th... |
def fifo_async(wrst, rrst, wclk, rclk, wfull, we, wdata, rempty, re, rdata, depth=None, width=None): ''' Asynchronous FIFO Implements the design described in: Clifford E. Cummings, "Simulation and Synthesis Techniques for Asynchronous FIFO Design," SNUG 2002 (Synopsys Users Group Conference, San Jose, CA, 2002) User Pa... |
not set, default 4 is used. Must be >=4. Must be power of 2 width - data width. If not set, data with equals len(wdata). Can be [0,1,2,3...) It is possible to instantiate a fifo with data width 0 (no data) if width=0 or width=None and wdata=None ''' if (width == None): width = 0 if wdata is not None: width = len(wdata)... |
len(rd_ptr) rd_ptr_bin = Signal(intbv(0)[WIDTH+1:]) rd_ptr_bin_new = Signal(intbv(0)[WIDTH+1:]) rd_ptr_gray = Signal(intbv(0)[WIDTH+1:]) rd_ptr_gray_new = Signal(intbv(0)[WIDTH+1:]) rd_ptr_gray_sync1 = Signal(intbv(0)[WIDTH+1:]) rd_ptr_gray_sync2 = Signal(intbv(0)[WIDTH+1:]) wr_ptr_bin = Signal(intbv(0)[WIDTH+1:]) wr_p... |
(rd_ptr_bin + 1) % rd_ptr_bin.max @always_comb def gray_comb(): wr_ptr_gray_new.next = (wr_ptr_bin_new >> 1) ^ wr_ptr_bin_new rd_ptr_gray_new.next = (rd_ptr_bin_new >> 1) ^ rd_ptr_bin_new @always_comb def full_empty_comb(): empty_val.next = (rd_ptr_gray_new == wr_ptr_gray_sync2) full_val.next = (wr_ptr_gray_new[WIDTH] ... |
= wclk, we = mem_we, addrw = mem_addrw, addrr = mem_addrr, di = mem_di, do = mem_do ) @always_comb def mem_connect(): mem_we.next = we_safe mem_addrw.next = wr_ptr_bin[WIDTH:] mem_addrr.next = rd_ptr_bin[WIDTH:] mem_di.next = wdata rdata.next = mem_do return instances() |
def respond_json(ctx, data, code = None, headers = [], json_dumps_default = None, jsonp = None): """Return a JSON response. This function is optimized for JSON following `Google JSON Style Guide <http://google-styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml>`_, but will handle any JSON except for HTTP errors. "... |
if code == 204: # No content return response if error.get('code') is None: error['code'] = code if error.get('message') is None: title = errors_title.get(code) title = ctx._(title) if title is not None else response.status error['message'] = title else: response = ctx.req.response response.content_type = content_type i... |
def call_unrar(params): """Calls rar/unrar command line executable, returns stdout pipe""" global rar_executable_cached if rar_executable_cached is None: for command in ('unrar', 'rar'): try: subprocess.Popen([command], stdout=subprocess.PIPE) rar_executable_cached = command break except OSError: pass if rar_executable... |
def get_assembly_names(): """return list of available assemblies >>> assy_names = get_assembly_names() >>> 'GRCh37.p13' in assy_names True """ return [ n.replace(".json.gz", "") for n in pkg_resources.resource_listdir(__name__, _assy_dir) if n.endswith(".json.gz") ] |
def get_assembly(name): """read a single assembly by name, returning a dictionary of assembly data >>> assy = get_assembly('GRCh37.p13') >>> assy['name'] 'GRCh37.p13' >>> assy['description'] 'Genome Reference Consortium Human Build 37 patch release 13 (GRCh37.p13)' >>> assy['refseq_ac'] 'GCF_000001405.25' >>> assy['gen... |
def get_assemblies(names=[]): """read specified assemblies, or all if none specified, returning a dictionary of assembly-name: assembly. See get_assembly() function for the structure of assembly data. >>> assemblies = get_assemblies(names=['GRCh37.p13']) >>> assy = assemblies['GRCh37.p13'] >>> assemblies = get_assembli... |
def make_name_ac_map(assy_name, primary_only=False): """make map from sequence name to accession for given assembly name >>> grch38p5_name_ac_map = make_name_ac_map('GRCh38.p5') >>> grch38p5_name_ac_map['1'] 'NC_000001.11' """ return { s['name']: s['refseq_ac'] for s in get_assembly(assy_name)['sequences'] if (not prim... |
def make_ac_name_map(assy_name, primary_only=False): """make map from accession (str) to sequence name (str) for given assembly name >>> grch38p5_ac_name_map = make_ac_name_map('GRCh38.p5') >>> grch38p5_ac_name_map['NC_000001.11'] '1' """ return { s['refseq_ac']: s['name'] for s in get_assembly(assy_name)['sequences'] ... |
def main(args=None): """Extract all exon annotations of protein-coding genes.""" if args is None: 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 = ... |
'rb', try_gzip = True) as fh, \ misc.smart_open_write(output_file) as ofh: #if i >= 500000: break reader = csv.reader(fh, dialect = 'excel-tab') writer = csv.writer(ofh, dialect = 'excel-tab', lineterminator = os.linesep, quoting = csv.QUOTE_NONE , quotechar = '|') for l in reader: i += 1 #if i % int(1e5) == 0: # print... |
%d' %(exons)) return 0 |
def titleCounts(readsAlignments): """ Count the number of times each title in a readsAlignments instance is matched. This is useful for rapidly discovering what titles were matched and with what frequency. @param readsAlignments: A L{dark.alignments.ReadsAlignments} instance. @return: A C{dict} whose keys are titles an... |
def toDict(self): """ Get information about a title alignment as a dictionary. @return: A C{dict} representation of the title aligment. """ return { 'hsps': [hsp.toDict() for hsp in self.hsps], 'read': self.read.toDict(), } |
def hasScoreBetterThan(self, score): """ Is there an HSP with a score better than a given value? @return: A C{bool}, C{True} if there is at least one HSP in the alignments for this title with a score better than C{score}. """ # Note: Do not assume that HSPs in an alignment are sorted in # decreasing order (as they are ... |
def coverage(self): """ Get the fraction of this title sequence that is matched by its reads. @return: The C{float} fraction of the title sequence matched by its reads. """ intervals = ReadIntervals(self.subjectLength) for hsp in self.hsps(): intervals.add(hsp.subjectStart, hsp.subjectEnd) return intervals.coverage() |
def coverageInfo(self): """ Return information about the bases found at each location in our title sequence. @return: A C{dict} whose keys are C{int} subject offsets and whose values are unsorted lists of (score, base) 2-tuples, giving all the bases from reads that matched the subject at subject location, along with th... |
def residueCounts(self, convertCaseTo='upper'): """ Count residue frequencies at all sequence locations matched by reads. @param convertCaseTo: A C{str}, 'upper', 'lower', or 'none'. If 'none', case will not be converted (both the upper and lower case string of a residue will be present in the result if they are presen... |
= defaultdict(Counter) for titleAlignment in self: read = titleAlignment.read for hsp in titleAlignment.hsps: for (subjectOffset, residue, inMatch) in read.walkHSP(hsp): counts[subjectOffset][convert(residue)] += 1 return counts |
def summary(self): """ Summarize the alignments for this subject. @return: A C{dict} with C{str} keys: bestScore: The C{float} best score of the matching reads. coverage: The C{float} fraction of the subject genome that is matched by at least one read. hspCount: The C{int} number of hsps that match the subject. medianS... |
def toDict(self): """ Get information about the title's alignments as a dictionary. @return: A C{dict} representation of the title's aligments. """ return { 'titleAlignments': [titleAlignment.toDict() for titleAlignment in self], 'subjectTitle': self.subjectTitle, 'subjectLength': self.subjectLength, } |
def addTitle(self, title, titleAlignments): """ Add a new title to self. @param title: A C{str} title. @param titleAlignments: An instance of L{TitleAlignments}. @raises KeyError: If the title is already present. """ if title in self: raise KeyError('Title %r already present in TitlesAlignments ' 'instance.' % title) e... |
def filter(self, minMatchingReads=None, minMedianScore=None, withScoreBetterThan=None, minNewReads=None, minCoverage=None, maxTitles=None, sortOn='maxScore'): """ Filter the titles in self to create another TitlesAlignments. @param minMatchingReads: titles that are matched by fewer reads are unacceptable. @param minMed... |
non-negative C{int} maximum number of titles to keep. If more titles than this are present, titles will be sorted (according to C{sortOn}) and only the best will be retained. @param sortOn: A C{str} attribute to sort on, used only if C{maxTitles} is not C{None}. See the C{sortTitles} method below for the legal values. ... |
if maxTitles < 0: raise ValueError('maxTitles (%r) cannot be negative.' % maxTitles) else: # There are too many titles. Make a sorted list of them so # we loop through them (below) in the desired order and can # break when/if we've reached the maximum. We can't just # take the first maxTitles titles from the sorted lis... |
< minMatchingReads): continue # To compare the median score with another score, we must # convert both values to instances of the score class used in # this data set so they can be compared without us needing to # know if numerically greater scores are considered better or # not. if (minMedianScore is not None and self... |
def hsps(self): """ Get all HSPs for all the alignments for all titles. @return: A generator yielding L{dark.hsp.HSP} instances. """ return (hsp for titleAlignments in self.values() for alignment in titleAlignments for hsp in alignment.hsps) |
def sortTitles(self, by): """ Sort titles by a given attribute and then by title. @param by: A C{str}, one of 'length', 'maxScore', 'medianScore', 'readCount', or 'title'. @raise ValueError: If an unknown C{by} value is given. @return: A sorted C{list} of titles. """ # First sort titles by the secondary key, which is a... |
"readCount", "title".') |
def summary(self, sortOn=None): """ Summarize all the alignments for this title. @param sortOn: A C{str} attribute to sort titles on. One of 'length', 'maxScore', 'medianScore', 'readCount', or 'title'. @raise ValueError: If an unknown C{sortOn} value is given. @return: A generator that yields C{dict} instances as prod... |
def tabSeparatedSummary(self, sortOn=None): """ Summarize all the alignments for this title as multi-line string with TAB-separated values on each line. @param sortOn: A C{str} attribute to sort titles on. One of 'length', 'maxScore', 'medianScore', 'readCount', or 'title'. @raise ValueError: If an unknown C{sortOn} va... |
just add fields. It's probably safe # to add them at the end, but be careful / think. # # A TAB-separated file can easily be read by awk using e.g., # awk 'BEGIN {FS = "\t"} ...' result = [] for titleSummary in self.summary(sortOn): result.append('\t'.join([ '%(coverage)f', '%(medianScore)f', '%(bestScore)f', '%(readCo... |
def toDict(self): """ Get information about the titles alignments as a dictionary. @return: A C{dict} representation of the titles aligments. """ return { 'scoreClass': self.scoreClass.__name__, 'titles': dict((title, titleAlignments.toDict()) for title, titleAlignments in self.items()), } |
def addFASTAFilteringCommandLineOptions(parser): """ Add standard FASTA filtering command-line options to an argparse parser. These are options that can be used to select or omit entire FASTA records, NOT options that change them (for that see addFASTAEditingCommandLineOptions). @param parser: An C{argparse.ArgumentPar... |
help='A regex that sequence titles (ids) must not match.') # A mutually exclusive group for --keepSequences and --removeSequences. group = parser.add_mutually_exclusive_group() group.add_argument( '--keepSequences', help=('Specify (1-based) ranges of sequence numbers that should be ' 'kept. E.g., --keepSequences 1-3,5 ... |
only on ' 'read id. The first occurrence is kept.')) # See the docstring for dark.reads.Reads.filter for more detail on # randomSubset. parser.add_argument( '--randomSubset', type=int, help=('An integer giving the number of sequences that should be kept. ' 'These will be selected at random.')) # See the docstring for d... |
sequence numbers to retain. Numbers must ' 'be one per line.')) |
def parseFASTAFilteringCommandLineOptions(args, reads): """ Examine parsed FASTA filtering command-line options and return filtered reads. @param args: An argparse namespace, as returned by the argparse C{parse_args} function. @param reads: A C{Reads} instance to filter. @return: The filtered C{Reads} instance. """ kee... |
def addFASTAEditingCommandLineOptions(parser): """ Add standard FASTA editing command-line options to an argparse parser. These are options that can be used to alter FASTA records, NOT options that simply select or reject those things (for those see addFASTAFilteringCommandLineOptions). @param parser: An C{argparse.Arg... |
get you the same ' 'result as --keepSites 8-10,5.')) group.add_argument( '--keepSitesFile', '--keepIndicesFile', help=('Specify a file containing 1-based sites to keep. All other ' 'sequence sites will be removed. Lines in the file must be ' 'given in the form e.g., 24,100-200,260. See --keepSites for ' 'more detail.')... |
will be removed.") parser.add_argument( '--truncateTitlesAfter', help=('A string that sequence titles (ids) will be truncated beyond. ' 'If the truncated version of a title has already been seen, ' 'that title will be skipped.')) parser.add_argument( '--removeDescriptions', action='store_true', default=False, help=('Re... |
length of a FASTQ sequence. If the ' 'function returns None, the read will be filtered out. The ' 'function will be passed to eval with the dark.reads classes ' 'Read, DNARead, AARead, etc. all in scope.')) parser.add_argument( '--reverse', action='store_true', default=False, help=('Reverse the sequences. Note that thi... |
def parseFASTAEditingCommandLineOptions(args, reads): """ Examine parsed FASTA editing command-line options and return information about kept sites and sequences. @param args: An argparse namespace, as returned by the argparse C{parse_args} function. @param reads: A C{Reads} instance to filter. @return: The filtered C{... |
try: removeSites.update( parseRangeString(line, convertToZeroBased=True)) except ValueError as e: raise ValueError( 'Remove sites file %r line %d parse error: %s' % (args.removeSitesFile, lineNumber, e)) return reads.filter( removeGaps=removeGaps, truncateTitlesAfter=truncateTitlesAfter, removeDescriptions=removeDescri... |
def accept(self, title): """ Return a value (see below) to indicate if a title is acceptable (and, if so, in what way). @param title: A C{str} sequence title. @return: An C{int} to indicate an acceptable title or not. This will be C{self.REJECT} if the title is unacceptable. C{self.WHITELIST_ACCEPT} if the title is whi... |
if (self._negativeRegex and self._negativeRegex.search(title) is not None): return self.REJECT if self._truncated is not None: truncated = simplifyTitle(title, self._truncateAfter) if truncated in self._truncated: # We've already seen this (truncated) title. Reject unless # this is the original title that we truncated ... |
def accept(self, title, titleAlignments): """ Return C{True} if the read id set in C{titleAlignments} is sufficiently different from all previously seen read sets. @param title: A C{str} sequence title. @param titleAlignments: An instance of L{TitleAlignment}. @return: A C{bool} indicating whether a title has an accept... |
[]) return True |
def _convertBlastRecordToDict(self, record): """ Pull (only) the fields we use out of the record and return them as a dict. Although we take the title from each alignment description, we save space in the JSON output by storing it in the alignment dict (not in a separated 'description' dict). When we undo this conversi... |
'bits': hsp.bits, 'expect': hsp.expect, 'frame': hsp.frame, 'identicalCount': hsp.identities, 'positiveCount': hsp.positives, 'query': hsp.query, 'query_start': hsp.query_start, 'query_end': hsp.query_end, 'sbjct': hsp.sbjct, 'sbjct_start': hsp.sbjct_start, 'sbjct_end': hsp.sbjct_end, }) alignments.append({ 'hsps': hsp... |
def _convertBlastParamsToDict(self, record): """ Pull the global BLAST parameters out of a BLAST record and return them as a C{dict}. Some of these attributes are useless (not filled in), but we record them all just in case we one day need them or they start to be used or they disappear etc. Any of those changes might ... |
'posted_date', 'num_letters_in_database', 'num_sequences_in_database', 'ka_params', 'gapped', 'ka_params_gap', # From Bio.Blast.Record.Parameters 'matrix', 'gap_penalties', 'sc_match', 'sc_mismatch', 'num_hits', 'num_sequences', 'num_good_extends', 'num_seqs_better_e', 'hsps_no_gap', 'hsps_prelim_gapped', 'hsps_prelim_... |
def records(self): """ Yield BLAST records, as read by the BioPython NCBIXML.parse method. Set self.params from data in the first record. """ first = True with as_handle(self._filename) as fp: for record in NCBIXML.parse(fp): if first: self.params = self._convertBlastParamsToDict(record) first = False yield record |
def saveAsJSON(self, fp): """ Write the records out as JSON. The first JSON object saved contains the BLAST parameters. @param fp: A C{str} file pointer to write to. """ first = True for record in self.records(): if first: print(dumps(self.params, separators=(',', ':')), file=fp) first = False print(dumps(self._convert... |
def _open(self, filename): """ Open the input file. Set self._fp to point to it. Read the first line of parameters. @param filename: A C{str} filename containing JSON BLAST records. @raise ValueError: if the first line of the file isn't valid JSON, if the input file is empty, or if the JSON does not contain an 'applica... |
be an old JSON file with no BLAST global ' 'parameters. Please re-run convert-blast-xml-to-json.py ' 'to convert it to the newest format.' % self._filename) |
def _dictToAlignments(self, blastDict, read): """ Take a dict (made by XMLRecordsReader._convertBlastRecordToDict) and convert it to a list of alignments. @param blastDict: A C{dict}, from convertBlastRecordToDict. @param read: A C{Read} instance, containing the read that BLAST used to create this record. @raise ValueE... |
for blastHsp in blastAlignment['hsps']: score = getScore(blastHsp) normalized = normalizeHSP(blastHsp, len(read), self.application) hsp = self._hspClass( score, readStart=normalized['readStart'], readEnd=normalized['readEnd'], readStartInSubject=normalized['readStartInSubject'], readEndInSubject=normalized['readEndInSu... |
def readAlignments(self, reads): """ Read lines of JSON from self._filename, convert them to read alignments and yield them. @param reads: An iterable of L{Read} instances, corresponding to the reads that were given to BLAST. @raise ValueError: If any of the lines in the file cannot be converted to JSON. @return: A gen... |
1, self._filename)) else: alignments = self._dictToAlignments(record, read) yield ReadAlignments(read, alignments) finally: self._fp.close() self._fp = None |
def _makeComplementTable(complementData): """ Make a sequence complement table. @param complementData: A C{dict} whose keys and values are strings of length one. A key, value pair indicates a substitution that should be performed during complementation. @return: A 256 character string that can be used as a translation ... |
def addFASTACommandLineOptions(parser): """ Add standard command-line options to an argparse parser. @param parser: An C{argparse.ArgumentParser} instance. """ parser.add_argument( '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME', help=('The name of the FASTA input file. Standard input will be read ' 'if... |
followed by its ' 'structure).')) |
def parseFASTACommandLineOptions(args): """ Examine parsed command-line options and return a Reads instance. @param args: An argparse namespace, as returned by the argparse C{parse_args} function. @return: A C{Reads} subclass instance, depending on the type of FASTA file given. """ # Set default FASTA type. if not (arg... |
def translations(self): """ Yield all six translations of a nucleotide sequence. @return: A generator that produces six L{TranslatedRead} instances. """ rc = self.reverseComplement().sequence for reverseComplemented in False, True: for frame in 0, 1, 2: seq = rc if reverseComplemented else self.sequence # Get the suffi... |
def reverseComplement(self): """ Reverse complement a nucleotide sequence. @return: The reverse complemented sequence as an instance of the current class. """ quality = None if self.quality is None else self.quality[::-1] sequence = self.sequence.translate(self.COMPLEMENT_TABLE)[::-1] return self.__class__(self.id, seq... |
def checkAlphabet(self, count=10): """ A function which checks if an AA read really contains amino acids. This additional testing is needed, because the letters in the DNA alphabet are also in the AA alphabet. @param count: An C{int}, indicating how many bases or amino acids at the start of the sequence should be consi... |
has been passed to ' 'AARead().') return readLetters |
def ORFs(self, openORFs=False): """ Find all ORFs in our sequence. @param openORFs: If C{True} allow ORFs that do not have a start codon and/or do not have a stop codon. @return: A generator that yields AAReadORF instances that correspond to the ORFs found in the AA sequence. """ # Return open ORFs to the left and righ... |
= index + 1 inORF = True # End of sequence. Yield the final ORF, open to the right, if # there is one and it has non-zero length. length = len(self.sequence) if inOpenORF and length > 0: yield AAReadORF(self, ORFStart, length, True, True) elif inORF and ORFStart < length: yield AAReadORF(self, ORFStart, length, False, ... |
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({ 'start': self.start, 'stop': self.stop, 'openLeft': self.openLeft, 'openRight': self.openRig... |
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. Keys 'start' and 'stop' must have C{i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.