code
stringlengths
1
18.2k
def check_chain(chain): """Verify a merkle chain to see if the Merkle root can be reproduced. """ link = chain[0][0] for i in range(1, len(chain) - 1): if chain[i][1] == 'R': link = hash_function(link + chain[i][0]).digest() elif chain[i][1] == 'L': link = hash_function(chain[i][0] + link).digest() else: raise MerkleEr...
def check_hex_chain(chain): """Verify a merkle chain, with hashes hex encoded, to see if the Merkle root can be reproduced. """ return codecs.encode(check_chain([(codecs.decode(i[0], 'hex_codec'), i[1]) for i in chain]), 'hex_codec')
def add_hash(self, value): """Add a Node based on a precomputed, hex encoded, hash value. """ self.leaves.append(Node(codecs.decode(value, 'hex_codec'), prehashed=True))
def clear(self): """Clears the Merkle Tree by releasing the Merkle root and each leaf's references, the rest should be garbage collected. This may be useful for situations where you want to take an existing tree, make changes to the leaves, but leave it uncalculated for some time, without node references that are no lo...
def build_fun(self, layer=None): """Calculate the merkle root and make references between nodes in the tree. Written in functional style purely for fun. """ if not layer: if not self.leaves: raise MerkleError('The tree has no leaves and cannot be calculated.') layer = self.leaves[::] layer = self._build(layer) if len(l...
def _build(self, leaves): """Private helper function to create the next aggregation level and put all references in place. """ new, odd = [], None # check if even number of leaves, promote odd leaf to next level, if not if len(leaves) % 2 == 1: odd = leaves.pop(-1) for i in range(0, len(leaves), 2): newnode = Node(leav...
def get_chain(self, index): """Assemble and return the chain leading from a given node to the merkle root of this tree. """ chain = [] this = self.leaves[index] chain.append((this.val, 'SELF')) while this.p: chain.append((this.sib.val, this.sib.side)) this = this.p chain.append((this.val, 'ROOT')) return chain
def get_all_chains(self): """Assemble and return a list of all chains for all leaf nodes to the merkle root. """ return [self.get_chain(i) for i in range(len(self.leaves))]
def get_hex_chain(self, index): """Assemble and return the chain leading from a given node to the merkle root of this tree with hash values in hex form """ return [(codecs.encode(i[0], 'hex_codec'), i[1]) for i in self.get_chain(index)]
def get_all_hex_chains(self): """Assemble and return a list of all chains for all nodes to the merkle root, hex encoded. """ return [[(codecs.encode(i[0], 'hex_codec'), i[1]) for i in j] for j in self.get_all_chains()]
def _get_whole_subtrees(self): """Returns an array of nodes in the tree that have balanced subtrees beneath them, moving from left to right. """ subtrees = [] loose_leaves = len(self.leaves) - 2**int(log(len(self.leaves), 2)) the_node = self.root while loose_leaves: subtrees.append(the_node.l) the_node = the_node.r loo...
def add_adjust(self, data, prehashed=False): """Add a new leaf, and adjust the tree, without rebuilding the whole thing. """ subtrees = self._get_whole_subtrees() new_node = Node(data, prehashed=prehashed) self.leaves.append(new_node) for node in reversed(subtrees): new_parent = Node(node.val + new_node.val) node.p, ne...
def fold_enrichment(self): """Returns the fold enrichment of the gene set. Fold enrichment is defined as ratio between the observed and the expected number of gene set genes present. """ expected = self.K * (self.n/float(self.N)) return self.k / expected
def get_pretty_format(self, max_name_length=0): """Returns a nicely formatted string describing the result. Parameters ---------- max_name_length: int [0] The maximum length of the gene set name (in characters). If the gene set name is longer than this number, it will be truncated and "..." will be appended to it, so t...
gs_name[:(max_name_length - 3)] + '...' param_str = '(%d/%d @ %d/%d, pval=%.1e, fe=%.1fx)' \ % (self.k, self.K, self.n, self.N, self.pval, self.fold_enrichment) return '%s %s' % (gs_name, param_str)
def main(recordFilenames, fastaFilename, title, xRange, bitRange): """ Print reads that match in a specified X-axis and bit score range. @param recordFilenames: A C{list} of C{str} file names contain results of a BLAST run, in JSON format. @param fastaFilename: The C{str} name of the FASTA file that was originally BLAS...
titlesAlignments: print('%s: Title %r not found in BLAST output' % (sys.argv[0], title)) sys.exit(3) for titleAlignment in titlesAlignments[title]: for hsp in titleAlignment.hsps: if ((xRange is None or (xRange[0] <= hsp.subjectEnd and xRange[1] >= hsp.subjectStart)) and (bitRange is None or (bitRange[0] <= hsp.score.s...
def fetch_seq(ac, start_i=None, end_i=None): """Fetches sequences and subsequences from NCBI eutils and Ensembl REST interfaces. :param string ac: accession of sequence to fetch :param int start_i: start position of *interbase* interval :param int end_i: end position of *interbase* interval **IMPORTANT** start_i and en...
interval, one would receive 250MB of chr1 plus overhead! Essentially any RefSeq, Genbank, BIC, or Ensembl sequence may be fetched: >> [(ac,fetch_seq(ac,0,25)) ... for ac in ['NG_032072.1', 'NW_003571030.1', 'NT_113901.1', ... 'NC_000001.10','NP_056374.2', 'GL000191.1', 'KB663603.1', ... 'ENST00000288602', 'ENSP00000288...
fetcher for {ac}".format(ac=ac)) if len(eligible_fetchers) >= 1: # pragma: nocover (no way to test) _logger.debug("Multiple sequence fetchers found for " "{ac}; using first".format(ac=ac)) fetcher = eligible_fetchers[0] _logger.debug("fetching {ac} with {f}".format(ac=ac, f=fetcher)) try: return fetcher(ac, start_i, en...
def _fetch_seq_ensembl(ac, start_i=None, end_i=None): """Fetch the specified sequence slice from Ensembl using the public REST interface. An interbase interval may be optionally provided with start_i and end_i. However, the Ensembl REST interface does not currently accept intervals, so the entire sequence is returned a...
def _fetch_seq_ncbi(ac, start_i=None, end_i=None): """Fetch sequences from NCBI using the eutils interface. An interbase interval may be optionally provided with start_i and end_i. NCBI eutils will return just the requested subsequence, which might greatly reduce payload sizes (especially with chromosome-scale sequence...
if start_i is None or end_i is None: url = url_fmt.format(db=db, ac=ac) else: url_fmt += "&seq_start={start}&seq_stop={stop}" url = url_fmt.format(db=db, ac=ac, start=start_i + 1, stop=end_i) url += "&tool={tool}&email={email}".format(tool=ncbi_tool, email=ncbi_email) url = _add_eutils_api_key(url) n_retries = 0 while ...
def _add_eutils_api_key(url): """Adds eutils api key to the query :param url: eutils url with a query string :return: url with api_key parameter set to the value of environment variable 'NCBI_API_KEY' if available """ apikey = os.environ.get("NCBI_API_KEY") if apikey: url += "&api_key={apikey}".format(apikey=apikey) re...
def rom(addr, dout, CONTENT): ''' CONTENT == tuple of non-sparse values ''' @always_comb def read(): dout.next = CONTENT[int(addr)] return read
def ram_sp_ar(clk, we, addr, di, do): ''' RAM: Single-Port, Asynchronous Read ''' memL = [Signal(intbv(0)[len(di):]) for _ in range(2**len(addr))] @always(clk.posedge) def write(): if we: memL[int(addr)].next = di @always_comb def read(): do.next = memL[int(addr)] return write, read
def ram_sdp_rf(clk, we, addrw, addrr, di, do): ''' RAM: Simple-Dual-Port, Read-First ''' memL = [Signal(intbv(0)[len(di):]) for _ in range(2**len(addrr))] @always(clk.posedge) def write(): if we: memL[int(addrw)].next = di do.next = memL[int(addrr)] return write
def ram_dp_rf(clka, clkb, wea, web, addra, addrb, dia, dib, doa, dob): ''' RAM: Dual-Port, Read-First ''' memL = [Signal(intbv(0)[len(dia):]) for _ in range(2**len(addra))] @always(clka.posedge) def writea(): if wea: memL[int(addra)].next = dia doa.next = memL[int(addra)] @always(clkb.posedge) def writeb(): if web: mem...
def convert_rom(ADDR_WIDTH=8, DATA_WIDTH=8, CONTENT=(4,5,6,7)): ''' Convert ROM''' addr = Signal(intbv(0)[ADDR_WIDTH:]) dout = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(rom, addr, dout, CONTENT)
def convert_ram_sp_rf(ADDR_WIDTH=8, DATA_WIDTH=8): ''' Convert RAM: Single-Port, Read-First ''' clk = Signal(bool(0)) we = Signal(bool(0)) addr = Signal(intbv(0)[ADDR_WIDTH:]) di = Signal(intbv(0)[DATA_WIDTH:]) do = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(ram_sp_rf, clk, we, addr, di, do)
def convert_ram_sp_wf(ADDR_WIDTH=8, DATA_WIDTH=8): ''' Convert RAM: Single-Port, Write-First ''' clk = Signal(bool(0)) we = Signal(bool(0)) addr = Signal(intbv(0)[ADDR_WIDTH:]) di = Signal(intbv(0)[DATA_WIDTH:]) do = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(ram_sp_wf, clk, we, addr, di, do)
def convert_ram_sp_ar(ADDR_WIDTH=8, DATA_WIDTH=8): ''' Convert RAM: Single-Port, Asynchronous Read ''' clk = Signal(bool(0)) we = Signal(bool(0)) addr = Signal(intbv(0)[ADDR_WIDTH:]) di = Signal(intbv(0)[DATA_WIDTH:]) do = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(ram_sp_ar, clk, we, addr, di, do)
def convert_ram_sdp_rf(ADDR_WIDTH=8, DATA_WIDTH=8): ''' Convert RAM: Simple-Dual-Port, Read-First ''' clk = Signal(bool(0)) we = Signal(bool(0)) addrw = Signal(intbv(0)[ADDR_WIDTH:]) addrr = Signal(intbv(0)[ADDR_WIDTH:]) di = Signal(intbv(0)[DATA_WIDTH:]) do = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(ram_sdp_rf, clk, we...
def convert_ram_sdp_wf(ADDR_WIDTH=8, DATA_WIDTH=8): ''' Convert RAM: Simple-Dual-Port, Write-First ''' clk = Signal(bool(0)) we = Signal(bool(0)) addrw = Signal(intbv(0)[ADDR_WIDTH:]) addrr = Signal(intbv(0)[ADDR_WIDTH:]) di = Signal(intbv(0)[DATA_WIDTH:]) do = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(ram_sdp_wf, clk, w...
def convert_ram_sdp_ar(ADDR_WIDTH=8, DATA_WIDTH=8): ''' Convert RAM: Simple-Dual-Port, Asynchronous Read''' clk = Signal(bool(0)) we = Signal(bool(0)) addrw = Signal(intbv(0)[ADDR_WIDTH:]) addrr = Signal(intbv(0)[ADDR_WIDTH:]) di = Signal(intbv(0)[DATA_WIDTH:]) do = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(ram_sdp_ar, c...
def convert_ram_dp_ar(ADDR_WIDTH=8, DATA_WIDTH=8): ''' Convert RAM: Dual-Port, Asynchronous Read ''' clka = Signal(bool(0)) clkb = Signal(bool(0)) wea = Signal(bool(0)) web = Signal(bool(0)) addra = Signal(intbv(0)[ADDR_WIDTH:]) addrb = Signal(intbv(0)[ADDR_WIDTH:]) dia = Signal(intbv(0)[DATA_WIDTH:]) dib = Signal(intb...
def post_to_twitter(self, message=None): """Update twitter status, i.e., post a tweet""" consumer = oauth2.Consumer(key=conf.TWITTER_CONSUMER_KEY, secret=conf.TWITTER_CONSUMER_SECRET) token = oauth2.Token(key=conf.TWITTER_ACCESS_TOKEN, secret=conf.TWITTER_ACCESS_SECRET) client = SimpleTwitterClient(consumer=consumer, t...
def get_gaf_gene_ontology_file(path): """Extract the gene ontology file associated with a GO annotation file. Parameters ---------- path: str The path name of the GO annotation file. Returns ------- str The URL of the associated gene ontology file. """ assert isinstance(path, str) version = None with misc.smart_open_re...
def apply(self, im): """ Apply an n-dimensional displacement by shifting an image or volume. Parameters ---------- im : ndarray The image or volume to shift """ from scipy.ndimage.interpolation import shift return shift(im, map(lambda x: -x, self.delta), mode='nearest')
def compute(a, b): """ Compute an optimal displacement between two ndarrays. Finds the displacement between two ndimensional arrays. Arrays must be of the same size. Algorithm uses a cross correlation, computed efficiently through an n-dimensional fft. Parameters ---------- a : ndarray The first array b : ndarray The s...
n) in pairs] return Displacement(adjusted)
def compute(a, b, axis): """ Finds optimal displacements localized along an axis """ delta = [] for aa, bb in zip(rollaxis(a, axis, 0), rollaxis(b, axis, 0)): delta.append(Displacement.compute(aa, bb).delta) return LocalDisplacement(delta, axis=axis)
def apply(self, im): """ Apply axis-localized displacements. Parameters ---------- im : ndarray The image or volume to shift """ from scipy.ndimage.interpolation import shift im = rollaxis(im, self.axis) im.setflags(write=True) for ind in range(0, im.shape[0]): im[ind] = shift(im[ind], map(lambda x: -x, self.delta[ind]...
def write_sample_sheet(output_file, accessions, names, celfile_urls, sel=None): """Generate a sample sheet in tab-separated text format. The columns contain the following sample attributes: 1) accession 2) name 3) CEL file name 4) CEL file URL Parameters ---------- output_file: str The path of the output file. accessio...
str) if sel is not None: assert isinstance(sel, Iterable) for i in sel: assert isinstance(i, (int, np.integer)) with open(output_file, 'wb') as ofh: writer = csv.writer(ofh, dialect='excel-tab', lineterminator=os.linesep, quoting=csv.QUOTE_NONE) # write header writer.writerow(['Accession', 'Name', 'CEL file name', 'CEL...
def execute(self, command): """ Execute (or simulate) a command. Add to our log. @param command: Either a C{str} command (which will be passed to the shell) or a C{list} of command arguments (including the executable name), in which case the shell is not used. @return: A C{CompletedProcess} instance. This has attribute...
universal_newlines=True) except CalledProcessError as e: from sys import stderr print('CalledProcessError:', e, file=stderr) print('STDOUT:\n%s' % e.stdout, file=stderr) print('STDERR:\n%s' % e.stderr, file=stderr) raise else: try: result = check_call(command, stdout=PIPE, stderr=PIPE, shell=shell, universal_newlines=T...
def NCBISequenceLinkURL(title, default=None): """ Given a sequence title, like "gi|42768646|gb|AY516849.1| Homo sapiens", return the URL of a link to the info page at NCBI. title: the sequence title to produce a link URL for. default: the value to return if the title cannot be parsed. """ try: ref = title.split('|')[3]...
def NCBISequenceLink(title, default=None): """ Given a sequence title, like "gi|42768646|gb|AY516849.1| Homo sapiens", return an HTML A tag dispalying a link to the info page at NCBI. title: the sequence title to produce an HTML link for. default: the value to return if the title cannot be parsed. """ url = NCBISequenc...
def _sortHTML(titlesAlignments, by, limit=None): """ Return an C{IPython.display.HTML} object with the alignments sorted by the given attribute. @param titlesAlignments: A L{dark.titles.TitlesAlignments} instance. @param by: A C{str}, one of 'length', 'maxScore', 'medianScore', 'readCount', or 'title'. @param limit: An...
def _writeFASTA(self, i, image): """ Write a FASTA file containing the set of reads that hit a sequence. @param i: The number of the image in self._images. @param image: A member of self._images. @return: A C{str}, either 'fasta' or 'fastq' indicating the format of the reads in C{self._titlesAlignments}. """ if isinsta...
def _writeFeatures(self, i, image): """ Write a text file containing the features as a table. @param i: The number of the image in self._images. @param image: A member of self._images. @return: The C{str} features file name - just the base name, not including the path to the file. """ basename = 'features-%d.txt' % i f...
def DosDateTimeToTimeTuple(dosDateTime): """Convert an MS-DOS format date time to a Python time tuple. """ dos_date = dosDateTime >> 16 dos_time = dosDateTime & 0xffff day = dos_date & 0x1f month = (dos_date >> 5) & 0xf year = 1980 + (dos_date >> 9) second = 2 * (dos_time & 0x1f) minute = (dos_time >> 5) & 0x3f hour = ...
def bitScoreToEValue(bitScore, dbSize, dbSequenceCount, queryLength, lengthAdjustment): """ Convert a bit score to an e-value. @param bitScore: The C{float} bit score to convert. @param dbSize: The C{int} total size of the database (i.e., the sum of the lengths of all sequences in the BLAST database). @param dbSequence...
def eValueToBitScore(eValue, dbSize, dbSequenceCount, queryLength, lengthAdjustment): """ Convert an e-value to a bit score. @param eValue: The C{float} e-value to convert. @param dbSize: The C{int} total size of the database (i.e., the sum of the lengths of all sequences in the BLAST database). @param dbSequenceCount:...
def parseBtop(btopString): """ Parse a BTOP string. The format is described at https://www.ncbi.nlm.nih.gov/books/NBK279682/ @param btopString: A C{str} BTOP sequence. @raise ValueError: If C{btopString} is not valid BTOP. @return: A generator that yields a series of integers and 2-tuples of letters, as found in the BT...
char else: if queryLetter == '-' and char == '-': raise ValueError( 'BTOP string %r has two consecutive gaps at ' 'offset %d' % (btopString, offset - 1)) elif queryLetter == char: raise ValueError( 'BTOP string %r has two consecutive identical %r ' 'letters at offset %d' % (btopString, char, offset - 1)) yield (queryLe...
def countGaps(btopString): """ Count the query and subject gaps in a BTOP string. @param btopString: A C{str} BTOP sequence. @raise ValueError: If L{parseBtop} finds an error in the BTOP string C{btopString}. @return: A 2-tuple of C{int}s, with the (query, subject) gaps counts as found in C{btopString}. """ queryGaps =...
def btop2cigar(btopString, concise=False, aa=False): """ Convert a BTOP string to a CIGAR string. @param btopString: A C{str} BTOP sequence. @param concise: If C{True}, use 'M' for matches and mismatches instead of the more specific 'X' and '='. @param aa: If C{True}, C{btopString} will be interpreted as though it refe...
or if C{aa} and C{concise} are both C{True}. @return: A C{str} CIGAR string. """ if aa and concise: raise ValueError('aa and concise cannot both be True') result = [] thisLength = thisOperation = currentLength = currentOperation = None for item in parseBtop(btopString): if isinstance(item, int): thisLength = item thisO...
thisOperation = CINS else: # A substitution was needed. assert query != reference thisOperation = CDIFF if concise else CMATCH if thisOperation == currentOperation: currentLength += thisLength else: if currentOperation: result.append( '%d%s' % ((3 * currentLength) if aa else currentLength, currentOperation)) currentLen...
def progress_callback(self, action, node, elapsed_time=None): """ Callback to report progress :param str action: :param list node: app, module :param int | None elapsed_time: """ if action == 'load_start': self.stdout.write('Loading fixture {}.{}...'.format(*node), ending='') self.stdout.flush() elif action == 'load_su...
def get_pretty_format(self, include_id=True, max_name_length=0, abbreviate=True): """Returns a nicely formatted string with the GO term information. Parameters ---------- include_id: bool, optional Include the GO term ID. max_name_length: int, optional Truncate the formatted string so that its total length does not exc...
def quantile_normalize(matrix, inplace=False, target=None): """Quantile normalization, allowing for missing values (NaN). In case of nan values, this implementation will calculate evenly distributed quantiles and fill in the missing data with those values. Quantile normalization is then performed on the filled-in matri...
np.ndarray) and \ np.issubdtype(target.dtype, np.float) if not inplace: # make a copy of the original data matrix = matrix.copy() X = matrix.X _, n = X.shape nan = [] # fill in missing values with evenly spaced quantiles for j in range(n): nan.append(np.nonzero(np.isnan(X[:, j]))[0]) if nan[j].size > 0: q = np.arange(1...
distribution (after sorting). target = np.sort(target) # generate indices to reverse sorting A = np.argsort(A, axis=0, kind='mergesort') # mergesort is stable # quantile-normalize for j in range(n): matrix.iloc[:, j] = target[A[:, j]] # set missing values to NaN again for j in range(n): if nan[j].size > 0: matrix.iloc[...
def toDict(self): """ Get information about the HSP as a dictionary. @return: A C{dict} representation of the HSP. """ result = _Base.toDict(self) result['score'] = self.score.score return result
def get_argument_parser(): """Returns an argument parser object for the script.""" desc = 'Filter FASTA file by chromosome names.' parser = cli.get_argument_parser(desc=desc) parser.add_argument( '-f', '--fasta-file', default='-', type=str, help=textwrap.dedent("""\ Path of the FASTA file. The file may be gzip'ed. If s...
def main(args=None): """Script body.""" if args is None: # parse command-line arguments parser = get_argument_parser() args = parser.parse_args() fasta_file = args.fasta_file species = args.species chrom_pat = args.chromosome_pattern output_file = args.output_file log_file = args.log_file quiet = args.quiet verbose = a...
encoding='ascii' ) as ofh: # inside = False reader = FastaReader(fh) for seq in reader: chrom = seq.name.split(' ', 1)[0] if chrom_re.match(chrom) is None: logger.info('Ignoring chromosome "%s"...', chrom) continue seq.name = chrom seq.append_fasta(ofh) return 0
def ensure_json_content_type(req, app): """ ErrorMiddleware returns hard-coded content-type text/html. Here we force it to be application/json. """ res = req.get_response(app, catch_exc_info=True) res.content_type = 'application/json; charset=utf-8' return res
def make_app(global_conf, **app_conf): """Create a WSGI application and return it ``global_conf`` The inherited configuration for this application. Normally from the [DEFAULT] section of the Paste ini file. ``app_conf`` The application's local configuration. Normally specified in the [app:<name>] section of the Paste i...
json_error_template app = weberror.errormiddleware.ErrorMiddleware(app, global_conf, **conf['errorware']) app = ensure_json_content_type(app) app = add_x_api_version_header(app) if conf['debug'] and ipdb is not None: app = launch_debugger_on_exception(app) return app
def fifo_speculative(rst, clk, full, we, din, empty, re, dout, wr_commit=None, wr_discard=None, rd_commit=None, rd_discard=None, afull=None, aempty=None, count=None, afull_th=None, aempty_th=None, ovf=None, udf=None, count_max=None, depth=None, width=None): """ Speculative FIFO Input interface: full, we, din, wr_commit...
can be later restored) rd_commit (i) - removes the speculatively read data at once rd_discard (i) - restores the speculatively read data (will be read again) empty (o) - asserted when there are no committed date to be read If re is asserted together with the rd_commit or rd_discards, the data being read is affected by ...
aempty_th afull_th (i) - almost full threshold, in terms of fifo cells; Optional, default depth/2 aempty_th (i) - almost empty threshold, in terms of fifo cells; Optional, default depth/2 count (o) - number of occupied fifo cells, committed and not committed (speculatively written/read) count_max (o) - max number of oc...
wr_discard must be either both used or both left unused" assert ((rd_commit != None) and (rd_discard != None)) or ((rd_commit == None) and (rd_discard == None)), "SFIFO ERROR: Interface signals rd_commit and rd_discard must be either both used or both left unused" wr_commit = wr_commit if (wr_commit != None) else Signa...
(aempty_th == None): aempty_th = depth//2 afull = afull if (afull != None) else Signal(bool(0)) aempty = aempty if (aempty != None) else Signal(bool(0)) count = count if (count != None) else Signal(intbv(0, min=0, max=depth + 1)) ovf = ovf if (ovf != None) else Signal(bool(0)) udf = udf if (udf != None) else Signal(boo...
empty_flg afull.next = afull_flg aempty.next = aempty_flg count.next = data_count count_max.next = data_count_max @always_comb def safe_read_write(): we_safe.next = we and not full_flg re_safe.next = re and not empty_flg @always_comb def non_zero_commits(): wr_commit_non0.next = wr_commit and (swr_non0 or we_safe) and ...
def state_main(): if (rst): wr_ptr.next = 0 rd_ptr.next = 0 swr_ptr.next = 0 srd_ptr.next = 0 swr_non0.next = 0 srd_non0.next = 0 full_flg.next = 0 empty_flg.next = 1 else: # Speculative Write pointer swr_ptr.next = swr_ptr_new # Speculative Read pointer srd_ptr.next = srd_ptr_new # Write pointer if (wr_commit): wr_ptr...
rd srd wr swr rd ^ ^ v v ^ |#########################|%%%%%%%%%%%%%%|*************************|..............| |<------ srd_count ------>|<------------>|<------ swr_count ------>|<------------>| |<--------------- wr_count ------------->|<--------------- rd_count ------------->| |<----------------------------------- dep...
if (not wr_commit and not wr_discard): swr_count_new = int((swr_count + 1) if (we_safe) else swr_count) swr_count.next = swr_count_new srd_count_new = 0 if (not rd_commit and not rd_discard): srd_count_new = int((srd_count + 1 if (re_safe) else srd_count)) srd_count.next = srd_count_new wr_add_new = 0 if (wr_commit and...
data_count_new ''' Overflow flag ''' if (ovf != None): @always(clk.posedge) def ovf_proc(): if (rst): ovf.next = 0 else: if (we and full_flg ): ovf.next = 1 ''' Underflow flag ''' if (udf != None): @always(clk.posedge) def udf_proc(): if (rst): udf.next = 0 else: if (re and empty_flg): udf.next = 1 """ ----------------...
def dimensionalIterator(dimensions, maxItems=-1): """ Given a list of n positive integers, return a generator that yields n-tuples of coordinates to 'fill' the dimensions. This is like an odometer in a car, but the dimensions do not each have to be 10. For example: dimensionalIterator((2, 3)) will yield in order (0, 0)...
== 0: return if any(map(lambda x: x != '*' and x <= 0, dimensions)): raise ValueError odometer = [0, ] * nDimensions while maxItems != 0: yield tuple(odometer) maxItems -= 1 wheel = nDimensions - 1 while (dimensions[wheel] != '*' and odometer[wheel] == dimensions[wheel] - 1 and wheel >= 0): odometer[wheel] = 0 wheel -=...
def matchToString(dnaMatch, read1, read2, matchAmbiguous=True, indent='', offsets=None): """ Format a DNA match as a string. @param dnaMatch: A C{dict} returned by C{compareDNAReads}. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of one of its ...
match['gapMismatchCount'] gapGapMismatchCount = match['gapGapMismatchCount'] nonGapMismatchCount = match['nonGapMismatchCount'] if offsets: len1 = len2 = len(offsets) else: len1, len2 = map(len, (read1, read2)) result = [] append = result.append append(countPrint('%sExact matches' % indent, identicalMatchCount, len1, l...
% (indent, read.id)) length = len(read) append('%s Length: %d' % (indent, length)) gapCount = len(dnaMatch[key]['gapOffsets']) append(countPrint('%s Gaps' % indent, gapCount, length)) if gapCount: append( '%s Gap locations (1-based): %s' % (indent, ', '.join(map(lambda offset: str(offset + 1), sorted(dnaMatch[key]['gap...
def compareDNAReads(read1, read2, matchAmbiguous=True, gapChars='-', offsets=None): """ Compare two DNA sequences. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of one of its subclasses. @param matchAmbiguous: If C{True}, count ambiguous nucleo...
= 0 gapMismatchCount = nonGapMismatchCount = gapGapMismatchCount = 0 read1ExtraCount = read2ExtraCount = 0 read1GapOffsets = [] read2GapOffsets = [] read1AmbiguousOffsets = [] read2AmbiguousOffsets = [] empty = set() def _identicalMatch(a, b): return a == b and len(AMBIGUOUS[a]) == 1 def _ambiguousMatch(a, b, matchAmbi...
1: read1AmbiguousOffsets.append(offset) if len(AMBIGUOUS.get(b, '')) > 1: read2AmbiguousOffsets.append(offset) if a is None: # b has an extra character at its end (it cannot be None). assert b is not None read2ExtraCount += 1 if b in gapChars: read2GapOffsets.append(offset) elif b is None: # a has an extra character at...
is not. gapMismatchCount += 1 read2GapOffsets.append(offset) else: # Neither is a gap character. if _identicalMatch(a, b): identicalMatchCount += 1 elif _ambiguousMatch(a, b, matchAmbiguous): ambiguousMatchCount += 1 else: nonGapMismatchCount += 1 return { 'match': { 'identicalMatchCount': identicalMatchCount, 'ambiguo...
def findKozakConsensus(read): """ In a given DNA sequence, search for a Kozak consensus: (gcc)gccRccATGG. The upper case bases in that pattern are required, and the lower case bases are the ones most frequently found at the given positions. The initial 'gcc' sequence (in parentheses) is of uncertain significance and is...
- 4] == 'C', readSeq[offset - 5] == 'C', readSeq[offset - 6] == 'G')) kozakQualityPercent = kozakQualityCount / 5.0 * 100 yield DNAKozakRead(read, offset - 6, offset + 4, kozakQualityPercent) offset += 1
def check(fastaFile, jsonFiles): """ Check for simple consistency between the FASTA file and the JSON files. Note that some checking is already performed by the BlastReadsAlignments class. That includes checking the number of reads matches the number of BLAST records and that read ids and BLAST record read ids match. @...
in readAlignments: for hsp in readAlignment.hsps: # The FASTA sequence should be at least as long as the # query in the JSON BLAST record (minus any gaps). assert (fastaLen >= len(hsp.query) - hsp.query.count('-')), ( 'record %d: FASTA len %d < HSP query len %d.\n' 'FASTA: %s\nQuery match: %s' % ( index, fastaLen, len(...
both read ' 'offsets (%d - %d), or read offsets are non-increasing. ' 'FASTA: %s\nQuery match: %s' % ( index, fastaLen, hsp.readStart, hsp.readEnd, readAlignments.read.sequence, hsp.query))
def thresholdForIdentity(identity, colors): """ Get the best identity threshold for a specific identity value. @param identity: A C{float} nucleotide identity. @param colors: A C{list} of (threshold, color) tuples, where threshold is a C{float} and color is a C{str} to be used as a cell background. This is as returned ...
def parseColors(colors, defaultColor): """ Parse command line color information. @param colors: A C{list} of space separated "value color" strings, such as ["0.9 red", "0.75 rgb(23, 190, 207)", "0.1 #CF3CF3"]. @param defaultColor: The C{str} color to use for cells that do not reach the identity fraction threshold of an...
threshold. Your value %r is not ' 'numeric.' % threshold, file=sys.stderr) sys.exit(1) if 0.0 > threshold > 1.0: print('--color arguments must be given as space-separated ' 'pairs of "value color" where the value is a ' 'numeric identity threshold from 0.0 to 1.0. Your ' 'value %r is not in that range.' % threshold, fi...