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
flo-compbio/genometools
genometools/expression/matrix.py
ExpMatrix.write_tsv
def write_tsv(self, file_path: str, encoding: str = 'UTF-8', sep: str = '\t'): """Write expression matrix to a tab-delimited text file. Parameters ---------- file_path: str The path of the output file. encoding: str, optional The file encoding. ("UTF-8") Returns ------- None """ #if six.PY2: # sep = sep.encode('UTF-8') self.to_csv( file_path, sep=sep, float_format='%.5f', mode='w', encoding=encoding, quoting=csv.QUOTE_NONE ) _LOGGER.info('Wrote %d x %d expression matrix to "%s".', self.p, self.n, file_path)
python
def write_tsv(self, file_path: str, encoding: str = 'UTF-8', sep: str = '\t'): """Write expression matrix to a tab-delimited text file. Parameters ---------- file_path: str The path of the output file. encoding: str, optional The file encoding. ("UTF-8") Returns ------- None """ #if six.PY2: # sep = sep.encode('UTF-8') self.to_csv( file_path, sep=sep, float_format='%.5f', mode='w', encoding=encoding, quoting=csv.QUOTE_NONE ) _LOGGER.info('Wrote %d x %d expression matrix to "%s".', self.p, self.n, file_path)
[ "def", "write_tsv", "(", "self", ",", "file_path", ":", "str", ",", "encoding", ":", "str", "=", "'UTF-8'", ",", "sep", ":", "str", "=", "'\\t'", ")", ":", "#if six.PY2:", "# sep = sep.encode('UTF-8')", "self", ".", "to_csv", "(", "file_path", ",", "sep...
Write expression matrix to a tab-delimited text file. Parameters ---------- file_path: str The path of the output file. encoding: str, optional The file encoding. ("UTF-8") Returns ------- None
[ "Write", "expression", "matrix", "to", "a", "tab", "-", "delimited", "text", "file", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L469-L493
flo-compbio/genometools
genometools/expression/matrix.py
ExpMatrix.write_sparse
def write_sparse(self, file_path: str): """Write a sparse representation to a tab-delimited text file. TODO: docstring""" coo = sparse.coo_matrix(self.X) data = OrderedDict([(0, coo.row+1), (1, coo.col+1), (2, coo.data)]) df = pd.DataFrame(data, columns=data.keys()) with open(file_path, 'w') as ofh: ofh.write('%%MatrixMarket matrix coordinate real general\n') ofh.write('%%%s\n' % '\t'.join(self.genes.astype(str))) ofh.write('%%%s\n' % '\t'.join(self.cells.astype(str))) ofh.write('%\n') ofh.write('%d %d %d\n' % (coo.shape[0], coo.shape[1], coo.nnz)) df.to_csv(ofh, sep=' ', float_format='%.5f', header=None, index=None)
python
def write_sparse(self, file_path: str): """Write a sparse representation to a tab-delimited text file. TODO: docstring""" coo = sparse.coo_matrix(self.X) data = OrderedDict([(0, coo.row+1), (1, coo.col+1), (2, coo.data)]) df = pd.DataFrame(data, columns=data.keys()) with open(file_path, 'w') as ofh: ofh.write('%%MatrixMarket matrix coordinate real general\n') ofh.write('%%%s\n' % '\t'.join(self.genes.astype(str))) ofh.write('%%%s\n' % '\t'.join(self.cells.astype(str))) ofh.write('%\n') ofh.write('%d %d %d\n' % (coo.shape[0], coo.shape[1], coo.nnz)) df.to_csv(ofh, sep=' ', float_format='%.5f', header=None, index=None)
[ "def", "write_sparse", "(", "self", ",", "file_path", ":", "str", ")", ":", "coo", "=", "sparse", ".", "coo_matrix", "(", "self", ".", "X", ")", "data", "=", "OrderedDict", "(", "[", "(", "0", ",", "coo", ".", "row", "+", "1", ")", ",", "(", "1...
Write a sparse representation to a tab-delimited text file. TODO: docstring
[ "Write", "a", "sparse", "representation", "to", "a", "tab", "-", "delimited", "text", "file", ".", "TODO", ":", "docstring" ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L496-L511
flo-compbio/genometools
genometools/expression/matrix.py
ExpMatrix.read_sparse
def read_sparse(cls, file_path: str): """Read a sparse representation from a tab-delimited text file. TODO: docstring""" with open(file_path) as fh: next(fh) # skip header line genes = next(fh)[1:-1].split('\t') cells = next(fh)[1:-1].split('\t') next(fh) m, n, nnz = [int(s) for s in next(fh)[:-1].split(' ')] t = pd.read_csv(file_path, sep=' ', skiprows=5, header=None, dtype={0: np.uint32, 1: np.uint32}) i = t[0].values - 1 j = t[1].values - 1 data = t[2].values assert data.size == nnz X = sparse.coo_matrix((data, (i,j)), shape=[m, n]).todense() return cls(X=X, genes=genes, cells=cells)
python
def read_sparse(cls, file_path: str): """Read a sparse representation from a tab-delimited text file. TODO: docstring""" with open(file_path) as fh: next(fh) # skip header line genes = next(fh)[1:-1].split('\t') cells = next(fh)[1:-1].split('\t') next(fh) m, n, nnz = [int(s) for s in next(fh)[:-1].split(' ')] t = pd.read_csv(file_path, sep=' ', skiprows=5, header=None, dtype={0: np.uint32, 1: np.uint32}) i = t[0].values - 1 j = t[1].values - 1 data = t[2].values assert data.size == nnz X = sparse.coo_matrix((data, (i,j)), shape=[m, n]).todense() return cls(X=X, genes=genes, cells=cells)
[ "def", "read_sparse", "(", "cls", ",", "file_path", ":", "str", ")", ":", "with", "open", "(", "file_path", ")", "as", "fh", ":", "next", "(", "fh", ")", "# skip header line", "genes", "=", "next", "(", "fh", ")", "[", "1", ":", "-", "1", "]", "....
Read a sparse representation from a tab-delimited text file. TODO: docstring
[ "Read", "a", "sparse", "representation", "from", "a", "tab", "-", "delimited", "text", "file", ".", "TODO", ":", "docstring" ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L515-L538
flo-compbio/genometools
genometools/expression/matrix.py
ExpMatrix.read_10xgenomics
def read_10xgenomics(cls, tarball_fpath: str, prefix: str, use_ensembl_ids: bool = False): """Read a 10X genomics compressed tarball containing expression data. Note: common prefix patterns: - "filtered_gene_bc_matrices/[annotations]/" - "filtered_matrices_mex/[annotations]/" TODO: docstring""" _LOGGER.info('Reading file: %s', tarball_fpath) with tarfile.open(tarball_fpath, mode='r:gz') as tf: ti = tf.getmember('%smatrix.mtx' % prefix) with tf.extractfile(ti) as fh: mtx = scipy.io.mmread(fh) ti = tf.getmember('%sgenes.tsv' % prefix) with tf.extractfile(ti) as fh: wrapper = io.TextIOWrapper(fh, encoding='ascii') i = 1 if use_ensembl_ids: i = 0 gene_names = \ [row[i] for row in csv.reader(wrapper, delimiter='\t')] ti = tf.getmember('%sbarcodes.tsv' % prefix) with tf.extractfile(ti) as fh: wrapper = io.TextIOWrapper(fh, encoding='ascii') barcodes = \ [row[0] for row in csv.reader(wrapper, delimiter='\t')] assert mtx.shape[0] == len(gene_names) assert mtx.shape[1] == len(barcodes) _LOGGER.info('Matrix dimensions: %s', str(mtx.shape)) X = mtx.todense() matrix = cls(X=X, genes=gene_names, cells=barcodes) return matrix
python
def read_10xgenomics(cls, tarball_fpath: str, prefix: str, use_ensembl_ids: bool = False): """Read a 10X genomics compressed tarball containing expression data. Note: common prefix patterns: - "filtered_gene_bc_matrices/[annotations]/" - "filtered_matrices_mex/[annotations]/" TODO: docstring""" _LOGGER.info('Reading file: %s', tarball_fpath) with tarfile.open(tarball_fpath, mode='r:gz') as tf: ti = tf.getmember('%smatrix.mtx' % prefix) with tf.extractfile(ti) as fh: mtx = scipy.io.mmread(fh) ti = tf.getmember('%sgenes.tsv' % prefix) with tf.extractfile(ti) as fh: wrapper = io.TextIOWrapper(fh, encoding='ascii') i = 1 if use_ensembl_ids: i = 0 gene_names = \ [row[i] for row in csv.reader(wrapper, delimiter='\t')] ti = tf.getmember('%sbarcodes.tsv' % prefix) with tf.extractfile(ti) as fh: wrapper = io.TextIOWrapper(fh, encoding='ascii') barcodes = \ [row[0] for row in csv.reader(wrapper, delimiter='\t')] assert mtx.shape[0] == len(gene_names) assert mtx.shape[1] == len(barcodes) _LOGGER.info('Matrix dimensions: %s', str(mtx.shape)) X = mtx.todense() matrix = cls(X=X, genes=gene_names, cells=barcodes) return matrix
[ "def", "read_10xgenomics", "(", "cls", ",", "tarball_fpath", ":", "str", ",", "prefix", ":", "str", ",", "use_ensembl_ids", ":", "bool", "=", "False", ")", ":", "_LOGGER", ".", "info", "(", "'Reading file: %s'", ",", "tarball_fpath", ")", "with", "tarfile", ...
Read a 10X genomics compressed tarball containing expression data. Note: common prefix patterns: - "filtered_gene_bc_matrices/[annotations]/" - "filtered_matrices_mex/[annotations]/" TODO: docstring
[ "Read", "a", "10X", "genomics", "compressed", "tarball", "containing", "expression", "data", ".", "Note", ":", "common", "prefix", "patterns", ":", "-", "filtered_gene_bc_matrices", "/", "[", "annotations", "]", "/", "-", "filtered_matrices_mex", "/", "[", "anno...
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L541-L581
flo-compbio/genometools
genometools/expression/convert_entrez2gene.py
get_argument_parser
def get_argument_parser(): """Function to obtain the argument parser. Parameters ---------- Returns ------- `argparse.ArgumentParser` A fully configured `argparse.ArgumentParser` object. Notes ----- This function can also be used by the `sphinx-argparse` extension for sphinx to generate documentation for this script. """ desc = 'Convert Entrez IDs to gene symbols.' parser = cli.get_argument_parser(desc=desc) file_mv = cli.file_mv g = parser.add_argument_group('Input and output files') g.add_argument('-e', '--expression-file', required=True, type=cli.str_type, metavar=file_mv, help='The expression file.') g.add_argument('-g', '--gene-file', required=True, type=cli.str_type, metavar=file_mv, help=textwrap.dedent('''\ The gene file (e.g., generated by the ensembl_extract_protein_coding_genes.py script).''')) g.add_argument('-c', '--entrez2gene-file', required=True, type=cli.str_type, metavar=file_mv, help=textwrap.dedent('''\ The entrez2gene file (.e.g., generated by the ncbi_extract_entrez2gene.py script).''')) g.add_argument('-o', '--output-file', required=True, type=cli.str_type, metavar=file_mv, help='The output file.') g = parser.add_argument_group('Conversion options') g.add_argument('-s', '--strip-affy-suffix', action='store_true', help=textwrap.dedent('''\ Strip the suffix "_at" from all Entrez IDs. (For use in affymetrix microarray pipeline.)''')) cli.add_reporting_args(parser) return parser
python
def get_argument_parser(): """Function to obtain the argument parser. Parameters ---------- Returns ------- `argparse.ArgumentParser` A fully configured `argparse.ArgumentParser` object. Notes ----- This function can also be used by the `sphinx-argparse` extension for sphinx to generate documentation for this script. """ desc = 'Convert Entrez IDs to gene symbols.' parser = cli.get_argument_parser(desc=desc) file_mv = cli.file_mv g = parser.add_argument_group('Input and output files') g.add_argument('-e', '--expression-file', required=True, type=cli.str_type, metavar=file_mv, help='The expression file.') g.add_argument('-g', '--gene-file', required=True, type=cli.str_type, metavar=file_mv, help=textwrap.dedent('''\ The gene file (e.g., generated by the ensembl_extract_protein_coding_genes.py script).''')) g.add_argument('-c', '--entrez2gene-file', required=True, type=cli.str_type, metavar=file_mv, help=textwrap.dedent('''\ The entrez2gene file (.e.g., generated by the ncbi_extract_entrez2gene.py script).''')) g.add_argument('-o', '--output-file', required=True, type=cli.str_type, metavar=file_mv, help='The output file.') g = parser.add_argument_group('Conversion options') g.add_argument('-s', '--strip-affy-suffix', action='store_true', help=textwrap.dedent('''\ Strip the suffix "_at" from all Entrez IDs. (For use in affymetrix microarray pipeline.)''')) cli.add_reporting_args(parser) return parser
[ "def", "get_argument_parser", "(", ")", ":", "desc", "=", "'Convert Entrez IDs to gene symbols.'", "parser", "=", "cli", ".", "get_argument_parser", "(", "desc", "=", "desc", ")", "file_mv", "=", "cli", ".", "file_mv", "g", "=", "parser", ".", "add_argument_grou...
Function to obtain the argument parser. Parameters ---------- Returns ------- `argparse.ArgumentParser` A fully configured `argparse.ArgumentParser` object. Notes ----- This function can also be used by the `sphinx-argparse` extension for sphinx to generate documentation for this script.
[ "Function", "to", "obtain", "the", "argument", "parser", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/convert_entrez2gene.py#L39-L91
jvsteiner/merkletree
merkle.py
check_chain
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 MerkleError('Link %s has no side value: %s' % (str(i), str(codecs.encode(chain[i][0], 'hex_codec')))) if link == chain[-1][0]: return link else: raise MerkleError('The Merkle Chain is not valid.')
python
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 MerkleError('Link %s has no side value: %s' % (str(i), str(codecs.encode(chain[i][0], 'hex_codec')))) if link == chain[-1][0]: return link else: raise MerkleError('The Merkle Chain is not valid.')
[ "def", "check_chain", "(", "chain", ")", ":", "link", "=", "chain", "[", "0", "]", "[", "0", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "chain", ")", "-", "1", ")", ":", "if", "chain", "[", "i", "]", "[", "1", "]", "==", "...
Verify a merkle chain to see if the Merkle root can be reproduced.
[ "Verify", "a", "merkle", "chain", "to", "see", "if", "the", "Merkle", "root", "can", "be", "reproduced", "." ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L174-L188
jvsteiner/merkletree
merkle.py
check_hex_chain
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')
python
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", "check_hex_chain", "(", "chain", ")", ":", "return", "codecs", ".", "encode", "(", "check_chain", "(", "[", "(", "codecs", ".", "decode", "(", "i", "[", "0", "]", ",", "'hex_codec'", ")", ",", "i", "[", "1", "]", ")", "for", "i", "in", "ch...
Verify a merkle chain, with hashes hex encoded, to see if the Merkle root can be reproduced.
[ "Verify", "a", "merkle", "chain", "with", "hashes", "hex", "encoded", "to", "see", "if", "the", "Merkle", "root", "can", "be", "reproduced", "." ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L191-L194
jvsteiner/merkletree
merkle.py
MerkleTree.add_hash
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))
python
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", "add_hash", "(", "self", ",", "value", ")", ":", "self", ".", "leaves", ".", "append", "(", "Node", "(", "codecs", ".", "decode", "(", "value", ",", "'hex_codec'", ")", ",", "prehashed", "=", "True", ")", ")" ]
Add a Node based on a precomputed, hex encoded, hash value.
[ "Add", "a", "Node", "based", "on", "a", "precomputed", "hex", "encoded", "hash", "value", "." ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L57-L60
jvsteiner/merkletree
merkle.py
MerkleTree.clear
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 longer correct still hanging around. Usually it is better just to make a new tree. """ self.root = None for leaf in self.leaves: leaf.p, leaf.sib, leaf.side = (None, ) * 3
python
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 longer correct still hanging around. Usually it is better just to make a new tree. """ self.root = None for leaf in self.leaves: leaf.p, leaf.sib, leaf.side = (None, ) * 3
[ "def", "clear", "(", "self", ")", ":", "self", ".", "root", "=", "None", "for", "leaf", "in", "self", ".", "leaves", ":", "leaf", ".", "p", ",", "leaf", ".", "sib", ",", "leaf", ".", "side", "=", "(", "None", ",", ")", "*", "3" ]
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 longer correct still hanging around. Usually it is better just to make a new tree.
[ "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", ...
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L62-L71
jvsteiner/merkletree
merkle.py
MerkleTree.build_fun
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(layer) == 1: self.root = layer[0] else: self.build_fun(layer=layer) return self.root.val
python
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(layer) == 1: self.root = layer[0] else: self.build_fun(layer=layer) return self.root.val
[ "def", "build_fun", "(", "self", ",", "layer", "=", "None", ")", ":", "if", "not", "layer", ":", "if", "not", "self", ".", "leaves", ":", "raise", "MerkleError", "(", "'The tree has no leaves and cannot be calculated.'", ")", "layer", "=", "self", ".", "leav...
Calculate the merkle root and make references between nodes in the tree. Written in functional style purely for fun.
[ "Calculate", "the", "merkle", "root", "and", "make", "references", "between", "nodes", "in", "the", "tree", ".", "Written", "in", "functional", "style", "purely", "for", "fun", "." ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L84-L97
jvsteiner/merkletree
merkle.py
MerkleTree._build
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(leaves[i].val + leaves[i + 1].val) newnode.l, newnode.r = leaves[i], leaves[i + 1] leaves[i].side, leaves[i + 1].side, leaves[i].p, leaves[i + 1].p = 'L', 'R', newnode, newnode leaves[i].sib, leaves[i + 1].sib = leaves[i + 1], leaves[i] new.append(newnode) if odd: new.append(odd) return new
python
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(leaves[i].val + leaves[i + 1].val) newnode.l, newnode.r = leaves[i], leaves[i + 1] leaves[i].side, leaves[i + 1].side, leaves[i].p, leaves[i + 1].p = 'L', 'R', newnode, newnode leaves[i].sib, leaves[i + 1].sib = leaves[i + 1], leaves[i] new.append(newnode) if odd: new.append(odd) return new
[ "def", "_build", "(", "self", ",", "leaves", ")", ":", "new", ",", "odd", "=", "[", "]", ",", "None", "# check if even number of leaves, promote odd leaf to next level, if not", "if", "len", "(", "leaves", ")", "%", "2", "==", "1", ":", "odd", "=", "leaves",...
Private helper function to create the next aggregation level and put all references in place.
[ "Private", "helper", "function", "to", "create", "the", "next", "aggregation", "level", "and", "put", "all", "references", "in", "place", "." ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L99-L114
jvsteiner/merkletree
merkle.py
MerkleTree.get_chain
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
python
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_chain", "(", "self", ",", "index", ")", ":", "chain", "=", "[", "]", "this", "=", "self", ".", "leaves", "[", "index", "]", "chain", ".", "append", "(", "(", "this", ".", "val", ",", "'SELF'", ")", ")", "while", "this", ".", "p", ":...
Assemble and return the chain leading from a given node to the merkle root of this tree.
[ "Assemble", "and", "return", "the", "chain", "leading", "from", "a", "given", "node", "to", "the", "merkle", "root", "of", "this", "tree", "." ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L116-L126
jvsteiner/merkletree
merkle.py
MerkleTree.get_all_chains
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))]
python
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_all_chains", "(", "self", ")", ":", "return", "[", "self", ".", "get_chain", "(", "i", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "leaves", ")", ")", "]" ]
Assemble and return a list of all chains for all leaf nodes to the merkle root.
[ "Assemble", "and", "return", "a", "list", "of", "all", "chains", "for", "all", "leaf", "nodes", "to", "the", "merkle", "root", "." ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L128-L131
jvsteiner/merkletree
merkle.py
MerkleTree.get_hex_chain
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)]
python
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_hex_chain", "(", "self", ",", "index", ")", ":", "return", "[", "(", "codecs", ".", "encode", "(", "i", "[", "0", "]", ",", "'hex_codec'", ")", ",", "i", "[", "1", "]", ")", "for", "i", "in", "self", ".", "get_chain", "(", "index", ...
Assemble and return the chain leading from a given node to the merkle root of this tree with hash values in hex form
[ "Assemble", "and", "return", "the", "chain", "leading", "from", "a", "given", "node", "to", "the", "merkle", "root", "of", "this", "tree", "with", "hash", "values", "in", "hex", "form" ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L133-L137
jvsteiner/merkletree
merkle.py
MerkleTree.get_all_hex_chains
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()]
python
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_all_hex_chains", "(", "self", ")", ":", "return", "[", "[", "(", "codecs", ".", "encode", "(", "i", "[", "0", "]", ",", "'hex_codec'", ")", ",", "i", "[", "1", "]", ")", "for", "i", "in", "j", "]", "for", "j", "in", "self", ".", "...
Assemble and return a list of all chains for all nodes to the merkle root, hex encoded.
[ "Assemble", "and", "return", "a", "list", "of", "all", "chains", "for", "all", "nodes", "to", "the", "merkle", "root", "hex", "encoded", "." ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L139-L142
jvsteiner/merkletree
merkle.py
MerkleTree._get_whole_subtrees
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 loose_leaves = loose_leaves - 2**int(log(loose_leaves, 2)) subtrees.append(the_node) return subtrees
python
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 loose_leaves = loose_leaves - 2**int(log(loose_leaves, 2)) subtrees.append(the_node) return subtrees
[ "def", "_get_whole_subtrees", "(", "self", ")", ":", "subtrees", "=", "[", "]", "loose_leaves", "=", "len", "(", "self", ".", "leaves", ")", "-", "2", "**", "int", "(", "log", "(", "len", "(", "self", ".", "leaves", ")", ",", "2", ")", ")", "the_...
Returns an array of nodes in the tree that have balanced subtrees beneath them, moving from left to right.
[ "Returns", "an", "array", "of", "nodes", "in", "the", "tree", "that", "have", "balanced", "subtrees", "beneath", "them", "moving", "from", "left", "to", "right", "." ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L144-L156
jvsteiner/merkletree
merkle.py
MerkleTree.add_adjust
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, new_node.p = new_parent, new_parent new_parent.l, new_parent.r = node, new_node node.sib, new_node.sib = new_node, node node.side, new_node.side = 'L', 'R' new_node = new_node.p self.root = new_node
python
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, new_node.p = new_parent, new_parent new_parent.l, new_parent.r = node, new_node node.sib, new_node.sib = new_node, node node.side, new_node.side = 'L', 'R' new_node = new_node.p self.root = new_node
[ "def", "add_adjust", "(", "self", ",", "data", ",", "prehashed", "=", "False", ")", ":", "subtrees", "=", "self", ".", "_get_whole_subtrees", "(", ")", "new_node", "=", "Node", "(", "data", ",", "prehashed", "=", "prehashed", ")", "self", ".", "leaves", ...
Add a new leaf, and adjust the tree, without rebuilding the whole thing.
[ "Add", "a", "new", "leaf", "and", "adjust", "the", "tree", "without", "rebuilding", "the", "whole", "thing", "." ]
train
https://github.com/jvsteiner/merkletree/blob/0d9284f9f90fab3b8c2ef4d356d0947719950bc2/merkle.py#L158-L171
flo-compbio/genometools
genometools/enrichment/result.py
StaticGSEResult.fold_enrichment
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
python
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", "fold_enrichment", "(", "self", ")", ":", "expected", "=", "self", ".", "K", "*", "(", "self", ".", "n", "/", "float", "(", "self", ".", "N", ")", ")", "return", "self", ".", "k", "/", "expected" ]
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.
[ "Returns", "the", "fold", "enrichment", "of", "the", "gene", "set", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/enrichment/result.py#L112-L119
flo-compbio/genometools
genometools/enrichment/result.py
StaticGSEResult.get_pretty_format
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 that the final string exactly meets the length requirement. If 0 (default), no truncation is performed. If not 0, must be at least 3. Returns ------- str The formatted string. Raises ------ ValueError If an invalid length value is specified. """ assert isinstance(max_name_length, (int, np.integer)) if max_name_length < 0 or (1 <= max_name_length <= 2): raise ValueError('max_name_length must be 0 or >= 3.') gs_name = self.gene_set._name if max_name_length > 0 and len(gs_name) > max_name_length: assert max_name_length >= 3 gs_name = 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)
python
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 that the final string exactly meets the length requirement. If 0 (default), no truncation is performed. If not 0, must be at least 3. Returns ------- str The formatted string. Raises ------ ValueError If an invalid length value is specified. """ assert isinstance(max_name_length, (int, np.integer)) if max_name_length < 0 or (1 <= max_name_length <= 2): raise ValueError('max_name_length must be 0 or >= 3.') gs_name = self.gene_set._name if max_name_length > 0 and len(gs_name) > max_name_length: assert max_name_length >= 3 gs_name = 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", "get_pretty_format", "(", "self", ",", "max_name_length", "=", "0", ")", ":", "assert", "isinstance", "(", "max_name_length", ",", "(", "int", ",", "np", ".", "integer", ")", ")", "if", "max_name_length", "<", "0", "or", "(", "1", "<=", "max_name_...
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 that the final string exactly meets the length requirement. If 0 (default), no truncation is performed. If not 0, must be at least 3. Returns ------- str The formatted string. Raises ------ ValueError If an invalid length value is specified.
[ "Returns", "a", "nicely", "formatted", "string", "describing", "the", "result", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/enrichment/result.py#L121-L158
acorg/dark-matter
bin/get-reads.py
main
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 BLASTed. @param title: The C{str} title of the subject sequence, as output by BLAST. @param xRange: A (start, end) list of C{int}s, giving an X-axis range or C{None} if the entire X axis range should be printed. @param bitRange: A (start, end) list of C{int}s, giving a bit score range or C{None} if the entire bit score range should be printed. """ reads = FastaReads(fastaFilename) blastReadsAlignments = BlastReadsAlignments(reads, recordFilenames) filtered = blastReadsAlignments.filter(whitelist=set([title]), negativeTitleRegex='.') titlesAlignments = TitlesAlignments(filtered) if title not in 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.score <= bitRange[1]))): print(('query: %s, start: %d, end: %d, score: %d' % ( titleAlignment.read.id, hsp.subjectStart, hsp.subjectEnd, hsp.score.score)))
python
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 BLASTed. @param title: The C{str} title of the subject sequence, as output by BLAST. @param xRange: A (start, end) list of C{int}s, giving an X-axis range or C{None} if the entire X axis range should be printed. @param bitRange: A (start, end) list of C{int}s, giving a bit score range or C{None} if the entire bit score range should be printed. """ reads = FastaReads(fastaFilename) blastReadsAlignments = BlastReadsAlignments(reads, recordFilenames) filtered = blastReadsAlignments.filter(whitelist=set([title]), negativeTitleRegex='.') titlesAlignments = TitlesAlignments(filtered) if title not in 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.score <= bitRange[1]))): print(('query: %s, start: %d, end: %d, score: %d' % ( titleAlignment.read.id, hsp.subjectStart, hsp.subjectEnd, hsp.score.score)))
[ "def", "main", "(", "recordFilenames", ",", "fastaFilename", ",", "title", ",", "xRange", ",", "bitRange", ")", ":", "reads", "=", "FastaReads", "(", "fastaFilename", ")", "blastReadsAlignments", "=", "BlastReadsAlignments", "(", "reads", ",", "recordFilenames", ...
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 BLASTed. @param title: The C{str} title of the subject sequence, as output by BLAST. @param xRange: A (start, end) list of C{int}s, giving an X-axis range or C{None} if the entire X axis range should be printed. @param bitRange: A (start, end) list of C{int}s, giving a bit score range or C{None} if the entire bit score range should be printed.
[ "Print", "reads", "that", "match", "in", "a", "specified", "X", "-", "axis", "and", "bit", "score", "range", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/get-reads.py#L14-L46
biocommons/bioutils
src/bioutils/seqfetcher.py
fetch_seq
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 end_i specify 0-based interbase coordinates, which refer to junctions between nucleotides. This is numerically equivalent to 0-based, right-open nucleotide coordinates. Without an interval, the full sequence is returned:: >> len(fetch_seq('NP_056374.2')) 1596 Therefore, it's preferable to provide the interval rather than using Python slicing sequence on the delivered sequence:: >> fetch_seq('NP_056374.2',0,10) # This! 'MESRETLSSS' >> fetch_seq('NP_056374.2')[0:10] # Not this! 'MESRETLSSS' >> fetch_seq('NP_056374.2',0,10) == fetch_seq('NP_056374.2')[0:10] True Providing intervals is especially important for large sequences:: >> fetch_seq('NC_000001.10',2000000,2000030) 'ATCACACGTGCAGGAACCCTTTTCCAAAGG' This call will pull back 30 bases plus overhead; without the 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', 'ENSP00000288602']] # doctest: +NORMALIZE_WHITESPACE [('NG_032072.1', 'AAAATTAAATTAAAATAAATAAAAA'), ('NW_003571030.1', 'TTGTGTGTTAGGGTGCTCTAAGCAA'), ('NT_113901.1', 'GAATTCCTCGTTCACACAGTTTCTT'), ('NC_000001.10', 'NNNNNNNNNNNNNNNNNNNNNNNNN'), ('NP_056374.2', 'MESRETLSSSRQRGGESDFLPVSSA'), ('GL000191.1', 'GATCCACCTGCCTCAGCCTCCCAGA'), ('KB663603.1', 'TTTATTTATTTTAGATACTTATCTC'), ('ENST00000288602', u'CGCCTCCCTTCCCCCTCCCCGCCCG'), ('ENSP00000288602', u'MAALSGGGGGGAEPGQALFNGDMEP')] RuntimeError is thrown in the case of errors:: >> fetch_seq('NM_9.9') Traceback (most recent call last): ... RuntimeError: No sequence available for NM_9.9 >> fetch_seq('QQ01234') Traceback (most recent call last): ... RuntimeError: No sequence fetcher for QQ01234 """ ac_dispatch = [ { "re": re.compile(r"^(?:AC|N[CGMPRTW])_|^[A-L]\w\d|^U\d"), "fetcher": _fetch_seq_ncbi }, { "re": re.compile(r"^ENS[TP]\d+"), "fetcher": _fetch_seq_ensembl }, ] eligible_fetchers = [ dr["fetcher"] for dr in ac_dispatch if dr["re"].match(ac) ] if len(eligible_fetchers) == 0: raise RuntimeError("No sequence 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, end_i) except requests.RequestException as ex: raise RuntimeError("Failed to fetch {ac} ({ex})".format(ac=ac, ex=ex))
python
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 end_i specify 0-based interbase coordinates, which refer to junctions between nucleotides. This is numerically equivalent to 0-based, right-open nucleotide coordinates. Without an interval, the full sequence is returned:: >> len(fetch_seq('NP_056374.2')) 1596 Therefore, it's preferable to provide the interval rather than using Python slicing sequence on the delivered sequence:: >> fetch_seq('NP_056374.2',0,10) # This! 'MESRETLSSS' >> fetch_seq('NP_056374.2')[0:10] # Not this! 'MESRETLSSS' >> fetch_seq('NP_056374.2',0,10) == fetch_seq('NP_056374.2')[0:10] True Providing intervals is especially important for large sequences:: >> fetch_seq('NC_000001.10',2000000,2000030) 'ATCACACGTGCAGGAACCCTTTTCCAAAGG' This call will pull back 30 bases plus overhead; without the 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', 'ENSP00000288602']] # doctest: +NORMALIZE_WHITESPACE [('NG_032072.1', 'AAAATTAAATTAAAATAAATAAAAA'), ('NW_003571030.1', 'TTGTGTGTTAGGGTGCTCTAAGCAA'), ('NT_113901.1', 'GAATTCCTCGTTCACACAGTTTCTT'), ('NC_000001.10', 'NNNNNNNNNNNNNNNNNNNNNNNNN'), ('NP_056374.2', 'MESRETLSSSRQRGGESDFLPVSSA'), ('GL000191.1', 'GATCCACCTGCCTCAGCCTCCCAGA'), ('KB663603.1', 'TTTATTTATTTTAGATACTTATCTC'), ('ENST00000288602', u'CGCCTCCCTTCCCCCTCCCCGCCCG'), ('ENSP00000288602', u'MAALSGGGGGGAEPGQALFNGDMEP')] RuntimeError is thrown in the case of errors:: >> fetch_seq('NM_9.9') Traceback (most recent call last): ... RuntimeError: No sequence available for NM_9.9 >> fetch_seq('QQ01234') Traceback (most recent call last): ... RuntimeError: No sequence fetcher for QQ01234 """ ac_dispatch = [ { "re": re.compile(r"^(?:AC|N[CGMPRTW])_|^[A-L]\w\d|^U\d"), "fetcher": _fetch_seq_ncbi }, { "re": re.compile(r"^ENS[TP]\d+"), "fetcher": _fetch_seq_ensembl }, ] eligible_fetchers = [ dr["fetcher"] for dr in ac_dispatch if dr["re"].match(ac) ] if len(eligible_fetchers) == 0: raise RuntimeError("No sequence 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, end_i) except requests.RequestException as ex: raise RuntimeError("Failed to fetch {ac} ({ex})".format(ac=ac, ex=ex))
[ "def", "fetch_seq", "(", "ac", ",", "start_i", "=", "None", ",", "end_i", "=", "None", ")", ":", "ac_dispatch", "=", "[", "{", "\"re\"", ":", "re", ".", "compile", "(", "r\"^(?:AC|N[CGMPRTW])_|^[A-L]\\w\\d|^U\\d\"", ")", ",", "\"fetcher\"", ":", "_fetch_seq_...
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 end_i specify 0-based interbase coordinates, which refer to junctions between nucleotides. This is numerically equivalent to 0-based, right-open nucleotide coordinates. Without an interval, the full sequence is returned:: >> len(fetch_seq('NP_056374.2')) 1596 Therefore, it's preferable to provide the interval rather than using Python slicing sequence on the delivered sequence:: >> fetch_seq('NP_056374.2',0,10) # This! 'MESRETLSSS' >> fetch_seq('NP_056374.2')[0:10] # Not this! 'MESRETLSSS' >> fetch_seq('NP_056374.2',0,10) == fetch_seq('NP_056374.2')[0:10] True Providing intervals is especially important for large sequences:: >> fetch_seq('NC_000001.10',2000000,2000030) 'ATCACACGTGCAGGAACCCTTTTCCAAAGG' This call will pull back 30 bases plus overhead; without the 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', 'ENSP00000288602']] # doctest: +NORMALIZE_WHITESPACE [('NG_032072.1', 'AAAATTAAATTAAAATAAATAAAAA'), ('NW_003571030.1', 'TTGTGTGTTAGGGTGCTCTAAGCAA'), ('NT_113901.1', 'GAATTCCTCGTTCACACAGTTTCTT'), ('NC_000001.10', 'NNNNNNNNNNNNNNNNNNNNNNNNN'), ('NP_056374.2', 'MESRETLSSSRQRGGESDFLPVSSA'), ('GL000191.1', 'GATCCACCTGCCTCAGCCTCCCAGA'), ('KB663603.1', 'TTTATTTATTTTAGATACTTATCTC'), ('ENST00000288602', u'CGCCTCCCTTCCCCCTCCCCGCCCG'), ('ENSP00000288602', u'MAALSGGGGGGAEPGQALFNGDMEP')] RuntimeError is thrown in the case of errors:: >> fetch_seq('NM_9.9') Traceback (most recent call last): ... RuntimeError: No sequence available for NM_9.9 >> fetch_seq('QQ01234') Traceback (most recent call last): ... RuntimeError: No sequence fetcher for QQ01234
[ "Fetches", "sequences", "and", "subsequences", "from", "NCBI", "eutils", "and", "Ensembl", "REST", "interfaces", "." ]
train
https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/seqfetcher.py#L24-L123
biocommons/bioutils
src/bioutils/seqfetcher.py
_fetch_seq_ensembl
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 and sliced locally. >> len(_fetch_seq_ensembl('ENSP00000288602')) 766 >> _fetch_seq_ensembl('ENSP00000288602',0,10) u'MAALSGGGGG' >> _fetch_seq_ensembl('ENSP00000288602')[0:10] u'MAALSGGGGG' >> ac = 'ENSP00000288602' >> _fetch_seq_ensembl(ac ,0, 10) == _fetch_seq_ensembl(ac)[0:10] True """ url_fmt = "http://rest.ensembl.org/sequence/id/{ac}" url = url_fmt.format(ac=ac) r = requests.get(url, headers={"Content-Type": "application/json"}) r.raise_for_status() seq = r.json()["seq"] return seq if (start_i is None or end_i is None) else seq[start_i:end_i]
python
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 and sliced locally. >> len(_fetch_seq_ensembl('ENSP00000288602')) 766 >> _fetch_seq_ensembl('ENSP00000288602',0,10) u'MAALSGGGGG' >> _fetch_seq_ensembl('ENSP00000288602')[0:10] u'MAALSGGGGG' >> ac = 'ENSP00000288602' >> _fetch_seq_ensembl(ac ,0, 10) == _fetch_seq_ensembl(ac)[0:10] True """ url_fmt = "http://rest.ensembl.org/sequence/id/{ac}" url = url_fmt.format(ac=ac) r = requests.get(url, headers={"Content-Type": "application/json"}) r.raise_for_status() seq = r.json()["seq"] return seq if (start_i is None or end_i is None) else seq[start_i:end_i]
[ "def", "_fetch_seq_ensembl", "(", "ac", ",", "start_i", "=", "None", ",", "end_i", "=", "None", ")", ":", "url_fmt", "=", "\"http://rest.ensembl.org/sequence/id/{ac}\"", "url", "=", "url_fmt", ".", "format", "(", "ac", "=", "ac", ")", "r", "=", "requests", ...
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 and sliced locally. >> len(_fetch_seq_ensembl('ENSP00000288602')) 766 >> _fetch_seq_ensembl('ENSP00000288602',0,10) u'MAALSGGGGG' >> _fetch_seq_ensembl('ENSP00000288602')[0:10] u'MAALSGGGGG' >> ac = 'ENSP00000288602' >> _fetch_seq_ensembl(ac ,0, 10) == _fetch_seq_ensembl(ac)[0:10] True
[ "Fetch", "the", "specified", "sequence", "slice", "from", "Ensembl", "using", "the", "public", "REST", "interface", "." ]
train
https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/seqfetcher.py#L130-L159
biocommons/bioutils
src/bioutils/seqfetcher.py
_fetch_seq_ncbi
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 sequences). The request includes `tool` and `email` arguments to identify the caller as the bioutils package. According to https://www.ncbi.nlm.nih.gov/books/NBK25497/, these values should correspond to the library, not the library client. Using the defaults is recommended. Nonetheless, callers may set `bioutils.seqfetcher.ncbi_tool` and `bioutils.seqfetcher.ncbi_email` to custom values if that is desired. >> len(_fetch_seq_ncbi('NP_056374.2')) 1596 Pass the desired interval rather than using Python's [] slice operator. >> _fetch_seq_ncbi('NP_056374.2',0,10) 'MESRETLSSS' >> _fetch_seq_ncbi('NP_056374.2')[0:10] 'MESRETLSSS' >> _fetch_seq_ncbi('NP_056374.2',0,10) == _fetch_seq_ncbi('NP_056374.2')[0:10] True """ db = "protein" if ac[1] == "P" else "nucleotide" url_fmt = ("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" "db={db}&id={ac}&rettype=fasta") 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 True: resp = requests.get(url) if resp.ok: seq = "".join(resp.text.splitlines()[1:]) return seq if n_retries >= retry_limit: break if n_retries == 0: _logger.warning("Failed to fetch {}".format(url)) sleeptime = random.randint(n_retries,3) ** n_retries _logger.warning("Failure {}/{}; retry in {} seconds".format(n_retries, retry_limit, sleeptime)) time.sleep(sleeptime) n_retries += 1 # Falls through only on failure resp.raise_for_status()
python
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 sequences). The request includes `tool` and `email` arguments to identify the caller as the bioutils package. According to https://www.ncbi.nlm.nih.gov/books/NBK25497/, these values should correspond to the library, not the library client. Using the defaults is recommended. Nonetheless, callers may set `bioutils.seqfetcher.ncbi_tool` and `bioutils.seqfetcher.ncbi_email` to custom values if that is desired. >> len(_fetch_seq_ncbi('NP_056374.2')) 1596 Pass the desired interval rather than using Python's [] slice operator. >> _fetch_seq_ncbi('NP_056374.2',0,10) 'MESRETLSSS' >> _fetch_seq_ncbi('NP_056374.2')[0:10] 'MESRETLSSS' >> _fetch_seq_ncbi('NP_056374.2',0,10) == _fetch_seq_ncbi('NP_056374.2')[0:10] True """ db = "protein" if ac[1] == "P" else "nucleotide" url_fmt = ("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" "db={db}&id={ac}&rettype=fasta") 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 True: resp = requests.get(url) if resp.ok: seq = "".join(resp.text.splitlines()[1:]) return seq if n_retries >= retry_limit: break if n_retries == 0: _logger.warning("Failed to fetch {}".format(url)) sleeptime = random.randint(n_retries,3) ** n_retries _logger.warning("Failure {}/{}; retry in {} seconds".format(n_retries, retry_limit, sleeptime)) time.sleep(sleeptime) n_retries += 1 # Falls through only on failure resp.raise_for_status()
[ "def", "_fetch_seq_ncbi", "(", "ac", ",", "start_i", "=", "None", ",", "end_i", "=", "None", ")", ":", "db", "=", "\"protein\"", "if", "ac", "[", "1", "]", "==", "\"P\"", "else", "\"nucleotide\"", "url_fmt", "=", "(", "\"https://eutils.ncbi.nlm.nih.gov/entre...
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 sequences). The request includes `tool` and `email` arguments to identify the caller as the bioutils package. According to https://www.ncbi.nlm.nih.gov/books/NBK25497/, these values should correspond to the library, not the library client. Using the defaults is recommended. Nonetheless, callers may set `bioutils.seqfetcher.ncbi_tool` and `bioutils.seqfetcher.ncbi_email` to custom values if that is desired. >> len(_fetch_seq_ncbi('NP_056374.2')) 1596 Pass the desired interval rather than using Python's [] slice operator. >> _fetch_seq_ncbi('NP_056374.2',0,10) 'MESRETLSSS' >> _fetch_seq_ncbi('NP_056374.2')[0:10] 'MESRETLSSS' >> _fetch_seq_ncbi('NP_056374.2',0,10) == _fetch_seq_ncbi('NP_056374.2')[0:10] True
[ "Fetch", "sequences", "from", "NCBI", "using", "the", "eutils", "interface", "." ]
train
https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/seqfetcher.py#L162-L226
biocommons/bioutils
src/bioutils/seqfetcher.py
_add_eutils_api_key
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) return url
python
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) return url
[ "def", "_add_eutils_api_key", "(", "url", ")", ":", "apikey", "=", "os", ".", "environ", ".", "get", "(", "\"NCBI_API_KEY\"", ")", "if", "apikey", ":", "url", "+=", "\"&api_key={apikey}\"", ".", "format", "(", "apikey", "=", "apikey", ")", "return", "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
[ "Adds", "eutils", "api", "key", "to", "the", "query" ]
train
https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/seqfetcher.py#L229-L239
nkavaldj/myhdl_lib
myhdl_lib/mem.py
rom
def rom(addr, dout, CONTENT): ''' CONTENT == tuple of non-sparse values ''' @always_comb def read(): dout.next = CONTENT[int(addr)] return read
python
def rom(addr, dout, CONTENT): ''' CONTENT == tuple of non-sparse values ''' @always_comb def read(): dout.next = CONTENT[int(addr)] return read
[ "def", "rom", "(", "addr", ",", "dout", ",", "CONTENT", ")", ":", "@", "always_comb", "def", "read", "(", ")", ":", "dout", ".", "next", "=", "CONTENT", "[", "int", "(", "addr", ")", "]", "return", "read" ]
CONTENT == tuple of non-sparse values
[ "CONTENT", "==", "tuple", "of", "non", "-", "sparse", "values" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L3-L9
nkavaldj/myhdl_lib
myhdl_lib/mem.py
ram_sp_ar
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
python
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_sp_ar", "(", "clk", ",", "we", ",", "addr", ",", "di", ",", "do", ")", ":", "memL", "=", "[", "Signal", "(", "intbv", "(", "0", ")", "[", "len", "(", "di", ")", ":", "]", ")", "for", "_", "in", "range", "(", "2", "**", "len", ...
RAM: Single-Port, Asynchronous Read
[ "RAM", ":", "Single", "-", "Port", "Asynchronous", "Read" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L43-L57
nkavaldj/myhdl_lib
myhdl_lib/mem.py
ram_sdp_rf
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
python
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_sdp_rf", "(", "clk", ",", "we", ",", "addrw", ",", "addrr", ",", "di", ",", "do", ")", ":", "memL", "=", "[", "Signal", "(", "intbv", "(", "0", ")", "[", "len", "(", "di", ")", ":", "]", ")", "for", "_", "in", "range", "(", "2",...
RAM: Simple-Dual-Port, Read-First
[ "RAM", ":", "Simple", "-", "Dual", "-", "Port", "Read", "-", "First" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L60-L71
nkavaldj/myhdl_lib
myhdl_lib/mem.py
ram_dp_rf
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: memL[int(addrb)].next = dib dob.next = memL[int(addrb)] return writea, writeb
python
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: memL[int(addrb)].next = dib dob.next = memL[int(addrb)] return writea, writeb
[ "def", "ram_dp_rf", "(", "clka", ",", "clkb", ",", "wea", ",", "web", ",", "addra", ",", "addrb", ",", "dia", ",", "dib", ",", "doa", ",", "dob", ")", ":", "memL", "=", "[", "Signal", "(", "intbv", "(", "0", ")", "[", "len", "(", "dia", ")", ...
RAM: Dual-Port, Read-First
[ "RAM", ":", "Dual", "-", "Port", "Read", "-", "First" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L110-L129
nkavaldj/myhdl_lib
myhdl_lib/mem.py
convert_rom
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)
python
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_rom", "(", "ADDR_WIDTH", "=", "8", ",", "DATA_WIDTH", "=", "8", ",", "CONTENT", "=", "(", "4", ",", "5", ",", "6", ",", "7", ")", ")", ":", "addr", "=", "Signal", "(", "intbv", "(", "0", ")", "[", "ADDR_WIDTH", ":", "]", ")", ...
Convert ROM
[ "Convert", "ROM" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L186-L190
nkavaldj/myhdl_lib
myhdl_lib/mem.py
convert_ram_sp_rf
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)
python
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_rf", "(", "ADDR_WIDTH", "=", "8", ",", "DATA_WIDTH", "=", "8", ")", ":", "clk", "=", "Signal", "(", "bool", "(", "0", ")", ")", "we", "=", "Signal", "(", "bool", "(", "0", ")", ")", "addr", "=", "Signal", "(", "intbv", "(",...
Convert RAM: Single-Port, Read-First
[ "Convert", "RAM", ":", "Single", "-", "Port", "Read", "-", "First" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L193-L200
nkavaldj/myhdl_lib
myhdl_lib/mem.py
convert_ram_sp_wf
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)
python
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_wf", "(", "ADDR_WIDTH", "=", "8", ",", "DATA_WIDTH", "=", "8", ")", ":", "clk", "=", "Signal", "(", "bool", "(", "0", ")", ")", "we", "=", "Signal", "(", "bool", "(", "0", ")", ")", "addr", "=", "Signal", "(", "intbv", "(",...
Convert RAM: Single-Port, Write-First
[ "Convert", "RAM", ":", "Single", "-", "Port", "Write", "-", "First" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L203-L210
nkavaldj/myhdl_lib
myhdl_lib/mem.py
convert_ram_sp_ar
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)
python
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_sp_ar", "(", "ADDR_WIDTH", "=", "8", ",", "DATA_WIDTH", "=", "8", ")", ":", "clk", "=", "Signal", "(", "bool", "(", "0", ")", ")", "we", "=", "Signal", "(", "bool", "(", "0", ")", ")", "addr", "=", "Signal", "(", "intbv", "(",...
Convert RAM: Single-Port, Asynchronous Read
[ "Convert", "RAM", ":", "Single", "-", "Port", "Asynchronous", "Read" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L213-L220
nkavaldj/myhdl_lib
myhdl_lib/mem.py
convert_ram_sdp_rf
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, addrw, addrr, di, do)
python
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, addrw, addrr, di, do)
[ "def", "convert_ram_sdp_rf", "(", "ADDR_WIDTH", "=", "8", ",", "DATA_WIDTH", "=", "8", ")", ":", "clk", "=", "Signal", "(", "bool", "(", "0", ")", ")", "we", "=", "Signal", "(", "bool", "(", "0", ")", ")", "addrw", "=", "Signal", "(", "intbv", "(...
Convert RAM: Simple-Dual-Port, Read-First
[ "Convert", "RAM", ":", "Simple", "-", "Dual", "-", "Port", "Read", "-", "First" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L223-L231
nkavaldj/myhdl_lib
myhdl_lib/mem.py
convert_ram_sdp_wf
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, we, addrw, addrr, di, do)
python
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, we, addrw, addrr, di, do)
[ "def", "convert_ram_sdp_wf", "(", "ADDR_WIDTH", "=", "8", ",", "DATA_WIDTH", "=", "8", ")", ":", "clk", "=", "Signal", "(", "bool", "(", "0", ")", ")", "we", "=", "Signal", "(", "bool", "(", "0", ")", ")", "addrw", "=", "Signal", "(", "intbv", "(...
Convert RAM: Simple-Dual-Port, Write-First
[ "Convert", "RAM", ":", "Simple", "-", "Dual", "-", "Port", "Write", "-", "First" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L234-L242
nkavaldj/myhdl_lib
myhdl_lib/mem.py
convert_ram_sdp_ar
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, clk, we, addrw, addrr, di, do)
python
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, clk, we, addrw, addrr, di, do)
[ "def", "convert_ram_sdp_ar", "(", "ADDR_WIDTH", "=", "8", ",", "DATA_WIDTH", "=", "8", ")", ":", "clk", "=", "Signal", "(", "bool", "(", "0", ")", ")", "we", "=", "Signal", "(", "bool", "(", "0", ")", ")", "addrw", "=", "Signal", "(", "intbv", "(...
Convert RAM: Simple-Dual-Port, Asynchronous Read
[ "Convert", "RAM", ":", "Simple", "-", "Dual", "-", "Port", "Asynchronous", "Read" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L245-L253
nkavaldj/myhdl_lib
myhdl_lib/mem.py
convert_ram_dp_ar
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(intbv(0)[DATA_WIDTH:]) doa = Signal(intbv(0)[DATA_WIDTH:]) dob = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(ram_dp_ar, clka, clkb, wea, web, addra, addrb, dia, dib, doa, dob)
python
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(intbv(0)[DATA_WIDTH:]) doa = Signal(intbv(0)[DATA_WIDTH:]) dob = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(ram_dp_ar, clka, clkb, wea, web, addra, addrb, dia, dib, doa, dob)
[ "def", "convert_ram_dp_ar", "(", "ADDR_WIDTH", "=", "8", ",", "DATA_WIDTH", "=", "8", ")", ":", "clka", "=", "Signal", "(", "bool", "(", "0", ")", ")", "clkb", "=", "Signal", "(", "bool", "(", "0", ")", ")", "wea", "=", "Signal", "(", "bool", "("...
Convert RAM: Dual-Port, Asynchronous Read
[ "Convert", "RAM", ":", "Dual", "-", "Port", "Asynchronous", "Read" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L286-L298
disqus/overseer
overseer/models.py
Event.post_to_twitter
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, token=token) if not message: message = self.get_message() hash_tag = '#status' if conf.BASE_URL: permalink = urlparse.urljoin(conf.BASE_URL, reverse('overseer:event_short', args=[self.pk])) if len(message) + len(permalink) + len(hash_tag) > 138: message = '%s.. %s %s' % (message[:140-4-len(hash_tag)-len(permalink)], permalink, hash_tag) else: message = '%s %s %s' % (message, permalink, hash_tag) else: if len(message) + len(hash_tag) > 139: message = '%s.. %s' % (message[:140-3-len(hash_tag)], hash_tag) else: message = '%s %s' % (message, hash_tag) return client.update_status(message)
python
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, token=token) if not message: message = self.get_message() hash_tag = '#status' if conf.BASE_URL: permalink = urlparse.urljoin(conf.BASE_URL, reverse('overseer:event_short', args=[self.pk])) if len(message) + len(permalink) + len(hash_tag) > 138: message = '%s.. %s %s' % (message[:140-4-len(hash_tag)-len(permalink)], permalink, hash_tag) else: message = '%s %s %s' % (message, permalink, hash_tag) else: if len(message) + len(hash_tag) > 139: message = '%s.. %s' % (message[:140-3-len(hash_tag)], hash_tag) else: message = '%s %s' % (message, hash_tag) return client.update_status(message)
[ "def", "post_to_twitter", "(", "self", ",", "message", "=", "None", ")", ":", "consumer", "=", "oauth2", ".", "Consumer", "(", "key", "=", "conf", ".", "TWITTER_CONSUMER_KEY", ",", "secret", "=", "conf", ".", "TWITTER_CONSUMER_SECRET", ")", "token", "=", "...
Update twitter status, i.e., post a tweet
[ "Update", "twitter", "status", "i", ".", "e", ".", "post", "a", "tweet" ]
train
https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/models.py#L176-L201
flo-compbio/genometools
genometools/ebi/uniprot_goa.py
get_gaf_gene_ontology_file
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_read(path, encoding='UTF-8', try_gzip=True) as fh: for l in fh: if l[0] != '!': break if l.startswith('!GO-version:'): version = l.split(' ')[1] break return version
python
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_read(path, encoding='UTF-8', try_gzip=True) as fh: for l in fh: if l[0] != '!': break if l.startswith('!GO-version:'): version = l.split(' ')[1] break return version
[ "def", "get_gaf_gene_ontology_file", "(", "path", ")", ":", "assert", "isinstance", "(", "path", ",", "str", ")", "version", "=", "None", "with", "misc", ".", "smart_open_read", "(", "path", ",", "encoding", "=", "'UTF-8'", ",", "try_gzip", "=", "True", ")...
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.
[ "Extract", "the", "gene", "ontology", "file", "associated", "with", "a", "GO", "annotation", "file", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ebi/uniprot_goa.py#L27-L50
thunder-project/thunder-registration
registration/transforms.py
Displacement.apply
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')
python
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", "apply", "(", "self", ",", "im", ")", ":", "from", "scipy", ".", "ndimage", ".", "interpolation", "import", "shift", "return", "shift", "(", "im", ",", "map", "(", "lambda", "x", ":", "-", "x", ",", "self", ".", "delta", ")", ",", "mode", ...
Apply an n-dimensional displacement by shifting an image or volume. Parameters ---------- im : ndarray The image or volume to shift
[ "Apply", "an", "n", "-", "dimensional", "displacement", "by", "shifting", "an", "image", "or", "volume", "." ]
train
https://github.com/thunder-project/thunder-registration/blob/286f091e6c402d592e9686d4821e0fd80dbf86ec/registration/transforms.py#L36-L46
thunder-project/thunder-registration
registration/transforms.py
Displacement.compute
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 second array """ from numpy.fft import rfftn, irfftn from numpy import unravel_index, argmax # compute real-valued cross-correlation in fourier domain s = a.shape f = rfftn(a) f *= rfftn(b).conjugate() c = abs(irfftn(f, s)) # find location of maximum inds = unravel_index(argmax(c), s) # fix displacements that are greater than half the total size pairs = zip(inds, a.shape) # cast to basic python int for serialization adjusted = [int(d - n) if d > n // 2 else int(d) for (d, n) in pairs] return Displacement(adjusted)
python
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 second array """ from numpy.fft import rfftn, irfftn from numpy import unravel_index, argmax # compute real-valued cross-correlation in fourier domain s = a.shape f = rfftn(a) f *= rfftn(b).conjugate() c = abs(irfftn(f, s)) # find location of maximum inds = unravel_index(argmax(c), s) # fix displacements that are greater than half the total size pairs = zip(inds, a.shape) # cast to basic python int for serialization adjusted = [int(d - n) if d > n // 2 else int(d) for (d, n) in pairs] return Displacement(adjusted)
[ "def", "compute", "(", "a", ",", "b", ")", ":", "from", "numpy", ".", "fft", "import", "rfftn", ",", "irfftn", "from", "numpy", "import", "unravel_index", ",", "argmax", "# compute real-valued cross-correlation in fourier domain", "s", "=", "a", ".", "shape", ...
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 second array
[ "Compute", "an", "optimal", "displacement", "between", "two", "ndarrays", "." ]
train
https://github.com/thunder-project/thunder-registration/blob/286f091e6c402d592e9686d4821e0fd80dbf86ec/registration/transforms.py#L49-L82
thunder-project/thunder-registration
registration/transforms.py
LocalDisplacement.compute
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)
python
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", "compute", "(", "a", ",", "b", ",", "axis", ")", ":", "delta", "=", "[", "]", "for", "aa", ",", "bb", "in", "zip", "(", "rollaxis", "(", "a", ",", "axis", ",", "0", ")", ",", "rollaxis", "(", "b", ",", "axis", ",", "0", ")", ")", "...
Finds optimal displacements localized along an axis
[ "Finds", "optimal", "displacements", "localized", "along", "an", "axis" ]
train
https://github.com/thunder-project/thunder-registration/blob/286f091e6c402d592e9686d4821e0fd80dbf86ec/registration/transforms.py#L114-L121
thunder-project/thunder-registration
registration/transforms.py
LocalDisplacement.apply
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]), mode='nearest') im = rollaxis(im, 0, self.axis+1) return im
python
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]), mode='nearest') im = rollaxis(im, 0, self.axis+1) return im
[ "def", "apply", "(", "self", ",", "im", ")", ":", "from", "scipy", ".", "ndimage", ".", "interpolation", "import", "shift", "im", "=", "rollaxis", "(", "im", ",", "self", ".", "axis", ")", "im", ".", "setflags", "(", "write", "=", "True", ")", "for...
Apply axis-localized displacements. Parameters ---------- im : ndarray The image or volume to shift
[ "Apply", "axis", "-", "localized", "displacements", "." ]
train
https://github.com/thunder-project/thunder-registration/blob/286f091e6c402d592e9686d4821e0fd80dbf86ec/registration/transforms.py#L123-L139
flo-compbio/genometools
genometools/ncbi/geo/functions.py
write_sample_sheet
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. accessions: list or tuple of str The sample accessions. names: list or tuple of str The sample names. celfile_urls: list or tuple of str The sample CEL file URLs. sel: Iterable, optional A list of sample indices to include. If None, all samples are included. [None] Returns ------- None """ assert isinstance(output_file, str) assert isinstance(accessions, (list, tuple)) for acc in accessions: assert isinstance(acc, str) assert isinstance(names, (list, tuple)) for n in names: assert isinstance(n, str) assert isinstance(celfile_urls, (list, tuple)) for u in celfile_urls: assert isinstance(u, 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 file URL']) n = len(list(names)) if sel is None: sel = range(n) for i in sel: cf = celfile_urls[i].split('/')[-1] # row = [accessions[i], names[i], cf, celfile_urls[i]] writer.writerow([accessions[i], names[i], cf, celfile_urls[i]])
python
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. accessions: list or tuple of str The sample accessions. names: list or tuple of str The sample names. celfile_urls: list or tuple of str The sample CEL file URLs. sel: Iterable, optional A list of sample indices to include. If None, all samples are included. [None] Returns ------- None """ assert isinstance(output_file, str) assert isinstance(accessions, (list, tuple)) for acc in accessions: assert isinstance(acc, str) assert isinstance(names, (list, tuple)) for n in names: assert isinstance(n, str) assert isinstance(celfile_urls, (list, tuple)) for u in celfile_urls: assert isinstance(u, 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 file URL']) n = len(list(names)) if sel is None: sel = range(n) for i in sel: cf = celfile_urls[i].split('/')[-1] # row = [accessions[i], names[i], cf, celfile_urls[i]] writer.writerow([accessions[i], names[i], cf, celfile_urls[i]])
[ "def", "write_sample_sheet", "(", "output_file", ",", "accessions", ",", "names", ",", "celfile_urls", ",", "sel", "=", "None", ")", ":", "assert", "isinstance", "(", "output_file", ",", "str", ")", "assert", "isinstance", "(", "accessions", ",", "(", "list"...
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. accessions: list or tuple of str The sample accessions. names: list or tuple of str The sample names. celfile_urls: list or tuple of str The sample CEL file URLs. sel: Iterable, optional A list of sample indices to include. If None, all samples are included. [None] Returns ------- None
[ "Generate", "a", "sample", "sheet", "in", "tab", "-", "separated", "text", "format", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/geo/functions.py#L83-L137
acorg/dark-matter
dark/process.py
Executor.execute
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 attributes such as C{returncode}, C{stdout}, and C{stderr}. See pydoc subprocess. """ if isinstance(command, six.string_types): # Can't have newlines in a command given to the shell. strCommand = command = command.replace('\n', ' ').strip() shell = True else: strCommand = ' '.join(command) shell = False if self._dryRun: self.log.append('$ ' + strCommand) return start = time() self.log.extend([ '# Start command (shell=%s) at %s' % (shell, ctime(start)), '$ ' + strCommand, ]) if six.PY3: try: result = run(command, check=True, stdout=PIPE, stderr=PIPE, shell=shell, 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=True) except CalledProcessError as e: from sys import stderr print('CalledProcessError:', e, file=stderr) print('Return code: %s' % e.returncode, file=stderr) print('Output:\n%s' % e.output, file=stderr) raise stop = time() elapsed = (stop - start) self.log.extend([ '# Stop command at %s' % ctime(stop), '# Elapsed = %f seconds' % elapsed, ]) return result
python
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 attributes such as C{returncode}, C{stdout}, and C{stderr}. See pydoc subprocess. """ if isinstance(command, six.string_types): # Can't have newlines in a command given to the shell. strCommand = command = command.replace('\n', ' ').strip() shell = True else: strCommand = ' '.join(command) shell = False if self._dryRun: self.log.append('$ ' + strCommand) return start = time() self.log.extend([ '# Start command (shell=%s) at %s' % (shell, ctime(start)), '$ ' + strCommand, ]) if six.PY3: try: result = run(command, check=True, stdout=PIPE, stderr=PIPE, shell=shell, 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=True) except CalledProcessError as e: from sys import stderr print('CalledProcessError:', e, file=stderr) print('Return code: %s' % e.returncode, file=stderr) print('Output:\n%s' % e.output, file=stderr) raise stop = time() elapsed = (stop - start) self.log.extend([ '# Stop command at %s' % ctime(stop), '# Elapsed = %f seconds' % elapsed, ]) return result
[ "def", "execute", "(", "self", ",", "command", ")", ":", "if", "isinstance", "(", "command", ",", "six", ".", "string_types", ")", ":", "# Can't have newlines in a command given to the shell.", "strCommand", "=", "command", "=", "command", ".", "replace", "(", "...
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 attributes such as C{returncode}, C{stdout}, and C{stderr}. See pydoc subprocess.
[ "Execute", "(", "or", "simulate", ")", "a", "command", ".", "Add", "to", "our", "log", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/process.py#L23-L79
acorg/dark-matter
dark/html.py
NCBISequenceLinkURL
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].split('.')[0] except IndexError: return default else: return 'http://www.ncbi.nlm.nih.gov/nuccore/%s' % (ref,)
python
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].split('.')[0] except IndexError: return default else: return 'http://www.ncbi.nlm.nih.gov/nuccore/%s' % (ref,)
[ "def", "NCBISequenceLinkURL", "(", "title", ",", "default", "=", "None", ")", ":", "try", ":", "ref", "=", "title", ".", "split", "(", "'|'", ")", "[", "3", "]", ".", "split", "(", "'.'", ")", "[", "0", "]", "except", "IndexError", ":", "return", ...
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.
[ "Given", "a", "sequence", "title", "like", "gi|42768646|gb|AY516849", ".", "1|", "Homo", "sapiens", "return", "the", "URL", "of", "a", "link", "to", "the", "info", "page", "at", "NCBI", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/html.py#L8-L21
acorg/dark-matter
dark/html.py
NCBISequenceLink
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 = NCBISequenceLinkURL(title) if url is None: return default else: return '<a href="%s" target="_blank">%s</a>' % (url, title)
python
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 = NCBISequenceLinkURL(title) if url is None: return default else: return '<a href="%s" target="_blank">%s</a>' % (url, title)
[ "def", "NCBISequenceLink", "(", "title", ",", "default", "=", "None", ")", ":", "url", "=", "NCBISequenceLinkURL", "(", "title", ")", "if", "url", "is", "None", ":", "return", "default", "else", ":", "return", "'<a href=\"%s\" target=\"_blank\">%s</a>'", "%", ...
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.
[ "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", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/html.py#L24-L36
acorg/dark-matter
dark/html.py
_sortHTML
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 C{int} limit on the number of results to show. @return: An HTML instance with sorted titles and information about hit read count, length, and e-values. """ out = [] for i, title in enumerate(titlesAlignments.sortTitles(by), start=1): if limit is not None and i > limit: break titleAlignments = titlesAlignments[title] link = NCBISequenceLink(title, title) out.append( '%3d: reads=%d, len=%d, max=%s median=%s<br/>' '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%s' % (i, titleAlignments.readCount(), titleAlignments.subjectLength, titleAlignments.bestHsp().score.score, titleAlignments.medianScore(), link)) return HTML('<pre>' + '<br/>'.join(out) + '</pre>')
python
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 C{int} limit on the number of results to show. @return: An HTML instance with sorted titles and information about hit read count, length, and e-values. """ out = [] for i, title in enumerate(titlesAlignments.sortTitles(by), start=1): if limit is not None and i > limit: break titleAlignments = titlesAlignments[title] link = NCBISequenceLink(title, title) out.append( '%3d: reads=%d, len=%d, max=%s median=%s<br/>' '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%s' % (i, titleAlignments.readCount(), titleAlignments.subjectLength, titleAlignments.bestHsp().score.score, titleAlignments.medianScore(), link)) return HTML('<pre>' + '<br/>'.join(out) + '</pre>')
[ "def", "_sortHTML", "(", "titlesAlignments", ",", "by", ",", "limit", "=", "None", ")", ":", "out", "=", "[", "]", "for", "i", ",", "title", "in", "enumerate", "(", "titlesAlignments", ".", "sortTitles", "(", "by", ")", ",", "start", "=", "1", ")", ...
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 C{int} limit on the number of results to show. @return: An HTML instance with sorted titles and information about hit read count, length, and e-values.
[ "Return", "an", "C", "{", "IPython", ".", "display", ".", "HTML", "}", "object", "with", "the", "alignments", "sorted", "by", "the", "given", "attribute", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/html.py#L39-L63
acorg/dark-matter
dark/html.py
AlignmentPanelHTMLWriter._writeFASTA
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 isinstance(self._titlesAlignments.readsAlignments.reads, FastqReads): format_ = 'fastq' else: format_ = 'fasta' filename = '%s/%d.%s' % (self._outputDir, i, format_) titleAlignments = self._titlesAlignments[image['title']] with open(filename, 'w') as fp: for titleAlignment in titleAlignments: fp.write(titleAlignment.read.toString(format_)) return format_
python
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 isinstance(self._titlesAlignments.readsAlignments.reads, FastqReads): format_ = 'fastq' else: format_ = 'fasta' filename = '%s/%d.%s' % (self._outputDir, i, format_) titleAlignments = self._titlesAlignments[image['title']] with open(filename, 'w') as fp: for titleAlignment in titleAlignments: fp.write(titleAlignment.read.toString(format_)) return format_
[ "def", "_writeFASTA", "(", "self", ",", "i", ",", "image", ")", ":", "if", "isinstance", "(", "self", ".", "_titlesAlignments", ".", "readsAlignments", ".", "reads", ",", "FastqReads", ")", ":", "format_", "=", "'fastq'", "else", ":", "format_", "=", "'f...
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}.
[ "Write", "a", "FASTA", "file", "containing", "the", "set", "of", "reads", "that", "hit", "a", "sequence", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/html.py#L274-L293
acorg/dark-matter
dark/html.py
AlignmentPanelHTMLWriter._writeFeatures
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 filename = '%s/%s' % (self._outputDir, basename) featureList = image['graphInfo']['features'] with open(filename, 'w') as fp: for feature in featureList: fp.write('%s\n\n' % feature.feature) return basename
python
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 filename = '%s/%s' % (self._outputDir, basename) featureList = image['graphInfo']['features'] with open(filename, 'w') as fp: for feature in featureList: fp.write('%s\n\n' % feature.feature) return basename
[ "def", "_writeFeatures", "(", "self", ",", "i", ",", "image", ")", ":", "basename", "=", "'features-%d.txt'", "%", "i", "filename", "=", "'%s/%s'", "%", "(", "self", ".", "_outputDir", ",", "basename", ")", "featureList", "=", "image", "[", "'graphInfo'", ...
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.
[ "Write", "a", "text", "file", "containing", "the", "features", "as", "a", "table", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/html.py#L295-L310
kyegupov/py-unrar2
UnRAR2/windows.py
DosDateTimeToTimeTuple
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 = dos_time >> 11 return time.localtime( time.mktime((year, month, day, hour, minute, second, 0, 1, -1)))
python
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 = dos_time >> 11 return time.localtime( time.mktime((year, month, day, hour, minute, second, 0, 1, -1)))
[ "def", "DosDateTimeToTimeTuple", "(", "dosDateTime", ")", ":", "dos_date", "=", "dosDateTime", ">>", "16", "dos_time", "=", "dosDateTime", "&", "0xffff", "day", "=", "dos_date", "&", "0x1f", "month", "=", "(", "dos_date", ">>", "5", ")", "&", "0xf", "year"...
Convert an MS-DOS format date time to a Python time tuple.
[ "Convert", "an", "MS", "-", "DOS", "format", "date", "time", "to", "a", "Python", "time", "tuple", "." ]
train
https://github.com/kyegupov/py-unrar2/blob/186a4c1feb9ef3d96a2331f8fb3ebf88036e15e5/UnRAR2/windows.py#L150-L162
acorg/dark-matter
dark/blast/score.py
bitScoreToEValue
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 dbSequenceCount: The C{int} number of sequences in the database. @param queryLength: The C{int} length of the query. @param lengthAdjustment: The C{int} length adjustment (BLAST XML output calls this the Statistics_hsp-len). @return: A C{float} e-value. """ effectiveDbSize = ( (dbSize - dbSequenceCount * lengthAdjustment) * (queryLength - lengthAdjustment) ) return effectiveDbSize * (2.0 ** (-1.0 * bitScore))
python
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 dbSequenceCount: The C{int} number of sequences in the database. @param queryLength: The C{int} length of the query. @param lengthAdjustment: The C{int} length adjustment (BLAST XML output calls this the Statistics_hsp-len). @return: A C{float} e-value. """ effectiveDbSize = ( (dbSize - dbSequenceCount * lengthAdjustment) * (queryLength - lengthAdjustment) ) return effectiveDbSize * (2.0 ** (-1.0 * bitScore))
[ "def", "bitScoreToEValue", "(", "bitScore", ",", "dbSize", ",", "dbSequenceCount", ",", "queryLength", ",", "lengthAdjustment", ")", ":", "effectiveDbSize", "=", "(", "(", "dbSize", "-", "dbSequenceCount", "*", "lengthAdjustment", ")", "*", "(", "queryLength", "...
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 dbSequenceCount: The C{int} number of sequences in the database. @param queryLength: The C{int} length of the query. @param lengthAdjustment: The C{int} length adjustment (BLAST XML output calls this the Statistics_hsp-len). @return: A C{float} e-value.
[ "Convert", "a", "bit", "score", "to", "an", "e", "-", "value", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/score.py#L24-L42
acorg/dark-matter
dark/blast/score.py
eValueToBitScore
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: The C{int} number of sequences in the database. @param queryLength: The C{int} length of the query. @param lengthAdjustment: The C{int} length adjustment (BLAST XML output calls this the Statistics_hsp-len). @return: A C{float} bit score. """ effectiveDbSize = ( (dbSize - dbSequenceCount * lengthAdjustment) * (queryLength - lengthAdjustment) ) return -1.0 * (log(eValue / effectiveDbSize) / _LOG2)
python
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: The C{int} number of sequences in the database. @param queryLength: The C{int} length of the query. @param lengthAdjustment: The C{int} length adjustment (BLAST XML output calls this the Statistics_hsp-len). @return: A C{float} bit score. """ effectiveDbSize = ( (dbSize - dbSequenceCount * lengthAdjustment) * (queryLength - lengthAdjustment) ) return -1.0 * (log(eValue / effectiveDbSize) / _LOG2)
[ "def", "eValueToBitScore", "(", "eValue", ",", "dbSize", ",", "dbSequenceCount", ",", "queryLength", ",", "lengthAdjustment", ")", ":", "effectiveDbSize", "=", "(", "(", "dbSize", "-", "dbSequenceCount", "*", "lengthAdjustment", ")", "*", "(", "queryLength", "-"...
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: The C{int} number of sequences in the database. @param queryLength: The C{int} length of the query. @param lengthAdjustment: The C{int} length adjustment (BLAST XML output calls this the Statistics_hsp-len). @return: A C{float} bit score.
[ "Convert", "an", "e", "-", "value", "to", "a", "bit", "score", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/score.py#L45-L63
acorg/dark-matter
dark/btop.py
parseBtop
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 BTOP string C{btopString}. """ isdigit = str.isdigit value = None queryLetter = None for offset, char in enumerate(btopString): if isdigit(char): if queryLetter is not None: raise ValueError( 'BTOP string %r has a query letter %r at offset %d with ' 'no corresponding subject letter' % (btopString, queryLetter, offset - 1)) value = int(char) if value is None else value * 10 + int(char) else: if value is not None: yield value value = None queryLetter = char else: if queryLetter is None: queryLetter = 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 (queryLetter, char) queryLetter = None if value is not None: yield value elif queryLetter is not None: raise ValueError( 'BTOP string %r has a trailing query letter %r with ' 'no corresponding subject letter' % (btopString, queryLetter))
python
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 BTOP string C{btopString}. """ isdigit = str.isdigit value = None queryLetter = None for offset, char in enumerate(btopString): if isdigit(char): if queryLetter is not None: raise ValueError( 'BTOP string %r has a query letter %r at offset %d with ' 'no corresponding subject letter' % (btopString, queryLetter, offset - 1)) value = int(char) if value is None else value * 10 + int(char) else: if value is not None: yield value value = None queryLetter = char else: if queryLetter is None: queryLetter = 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 (queryLetter, char) queryLetter = None if value is not None: yield value elif queryLetter is not None: raise ValueError( 'BTOP string %r has a trailing query letter %r with ' 'no corresponding subject letter' % (btopString, queryLetter))
[ "def", "parseBtop", "(", "btopString", ")", ":", "isdigit", "=", "str", ".", "isdigit", "value", "=", "None", "queryLetter", "=", "None", "for", "offset", ",", "char", "in", "enumerate", "(", "btopString", ")", ":", "if", "isdigit", "(", "char", ")", "...
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 BTOP string C{btopString}.
[ "Parse", "a", "BTOP", "string", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/btop.py#L5-L53
acorg/dark-matter
dark/btop.py
countGaps
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 = subjectGaps = 0 for countOrMismatch in parseBtop(btopString): if isinstance(countOrMismatch, tuple): queryChar, subjectChar = countOrMismatch queryGaps += int(queryChar == '-') subjectGaps += int(subjectChar == '-') return (queryGaps, subjectGaps)
python
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 = subjectGaps = 0 for countOrMismatch in parseBtop(btopString): if isinstance(countOrMismatch, tuple): queryChar, subjectChar = countOrMismatch queryGaps += int(queryChar == '-') subjectGaps += int(subjectChar == '-') return (queryGaps, subjectGaps)
[ "def", "countGaps", "(", "btopString", ")", ":", "queryGaps", "=", "subjectGaps", "=", "0", "for", "countOrMismatch", "in", "parseBtop", "(", "btopString", ")", ":", "if", "isinstance", "(", "countOrMismatch", ",", "tuple", ")", ":", "queryChar", ",", "subje...
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}.
[ "Count", "the", "query", "and", "subject", "gaps", "in", "a", "BTOP", "string", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/btop.py#L56-L73
acorg/dark-matter
dark/btop.py
btop2cigar
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 refers to amino acids (as in the BTOP string produced by DIAMOND). In that case, it is not possible to use the 'precise' CIGAR characters because amino acids have multiple codons so we cannot know whether an amino acid match is due to an exact nucleotide matches or not. Also, the numbers in the BTOP string will be multiplied by 3 since they refer to a number of amino acids matching. @raise ValueError: If L{parseBtop} finds an error in C{btopString} 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 thisOperation = CEQUAL if concise else CMATCH else: thisLength = 1 query, reference = item if query == '-': # The query has a gap. That means that in matching the # query to the reference a deletion is needed in the # reference. assert reference != '-' thisOperation = CDEL elif reference == '-': # The reference has a gap. That means that in matching the # query to the reference an insertion is needed in the # reference. 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)) currentLength, currentOperation = thisLength, thisOperation # We reached the end of the BTOP string. If there was an operation # underway, emit it. The 'if' here should only be needed to catch the # case where btopString was empty. assert currentOperation or btopString == '' if currentOperation: result.append( '%d%s' % ((3 * currentLength) if aa else currentLength, currentOperation)) return ''.join(result)
python
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 refers to amino acids (as in the BTOP string produced by DIAMOND). In that case, it is not possible to use the 'precise' CIGAR characters because amino acids have multiple codons so we cannot know whether an amino acid match is due to an exact nucleotide matches or not. Also, the numbers in the BTOP string will be multiplied by 3 since they refer to a number of amino acids matching. @raise ValueError: If L{parseBtop} finds an error in C{btopString} 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 thisOperation = CEQUAL if concise else CMATCH else: thisLength = 1 query, reference = item if query == '-': # The query has a gap. That means that in matching the # query to the reference a deletion is needed in the # reference. assert reference != '-' thisOperation = CDEL elif reference == '-': # The reference has a gap. That means that in matching the # query to the reference an insertion is needed in the # reference. 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)) currentLength, currentOperation = thisLength, thisOperation # We reached the end of the BTOP string. If there was an operation # underway, emit it. The 'if' here should only be needed to catch the # case where btopString was empty. assert currentOperation or btopString == '' if currentOperation: result.append( '%d%s' % ((3 * currentLength) if aa else currentLength, currentOperation)) return ''.join(result)
[ "def", "btop2cigar", "(", "btopString", ",", "concise", "=", "False", ",", "aa", "=", "False", ")", ":", "if", "aa", "and", "concise", ":", "raise", "ValueError", "(", "'aa and concise cannot both be True'", ")", "result", "=", "[", "]", "thisLength", "=", ...
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 refers to amino acids (as in the BTOP string produced by DIAMOND). In that case, it is not possible to use the 'precise' CIGAR characters because amino acids have multiple codons so we cannot know whether an amino acid match is due to an exact nucleotide matches or not. Also, the numbers in the BTOP string will be multiplied by 3 since they refer to a number of amino acids matching. @raise ValueError: If L{parseBtop} finds an error in C{btopString} or if C{aa} and C{concise} are both C{True}. @return: A C{str} CIGAR string.
[ "Convert", "a", "BTOP", "string", "to", "a", "CIGAR", "string", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/btop.py#L76-L142
Peter-Slump/django-dynamic-fixtures
src/dynamic_fixtures/management/commands/load_dynamic_fixtures.py
Command.progress_callback
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_success': message = 'SUCCESS' if elapsed_time: message += ' ({:.03} seconds) '.format(elapsed_time) self.stdout.write(message)
python
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_success': message = 'SUCCESS' if elapsed_time: message += ' ({:.03} seconds) '.format(elapsed_time) self.stdout.write(message)
[ "def", "progress_callback", "(", "self", ",", "action", ",", "node", ",", "elapsed_time", "=", "None", ")", ":", "if", "action", "==", "'load_start'", ":", "self", ".", "stdout", ".", "write", "(", "'Loading fixture {}.{}...'", ".", "format", "(", "*", "no...
Callback to report progress :param str action: :param list node: app, module :param int | None elapsed_time:
[ "Callback", "to", "report", "progress" ]
train
https://github.com/Peter-Slump/django-dynamic-fixtures/blob/da99b4b12b11be28ea4b36b6cf2896ca449c73c1/src/dynamic_fixtures/management/commands/load_dynamic_fixtures.py#L61-L78
flo-compbio/genometools
genometools/ontology/term.py
GOTerm.get_pretty_format
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 exceed this value. abbreviate: bool, optional Do not use abberviations (see ``_abbrev``) to shorten the GO term name. Returns ------- str The formatted string. """ name = self.name if abbreviate: for abb in self._abbrev: name = re.sub(abb[0], abb[1], name) if 3 <= max_name_length < len(name): name = name[:(max_name_length-3)] + '...' if include_id: return "%s: %s (%s)" % (self.domain_short, name, self.id) else: return "%s: %s" % (self.domain_short, name)
python
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 exceed this value. abbreviate: bool, optional Do not use abberviations (see ``_abbrev``) to shorten the GO term name. Returns ------- str The formatted string. """ name = self.name if abbreviate: for abb in self._abbrev: name = re.sub(abb[0], abb[1], name) if 3 <= max_name_length < len(name): name = name[:(max_name_length-3)] + '...' if include_id: return "%s: %s (%s)" % (self.domain_short, name, self.id) else: return "%s: %s" % (self.domain_short, name)
[ "def", "get_pretty_format", "(", "self", ",", "include_id", "=", "True", ",", "max_name_length", "=", "0", ",", "abbreviate", "=", "True", ")", ":", "name", "=", "self", ".", "name", "if", "abbreviate", ":", "for", "abb", "in", "self", ".", "_abbrev", ...
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 exceed this value. abbreviate: bool, optional Do not use abberviations (see ``_abbrev``) to shorten the GO term name. Returns ------- str The formatted string.
[ "Returns", "a", "nicely", "formatted", "string", "with", "the", "GO", "term", "information", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/term.py#L196-L225
flo-compbio/genometools
genometools/expression/normalize.py
quantile_normalize
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 matrix, and the nan values are restored afterwards. Parameters ---------- matrix: `ExpMatrix` The expression matrix (rows = genes, columns = samples). inplace: bool Whether or not to perform the operation in-place. [False] target: `numpy.ndarray` Target distribution to use. needs to be a vector whose first dimension matches that of the expression matrix. If ``None``, the target distribution is calculated based on the matrix itself. [None] Returns ------- numpy.ndarray (ndim = 2) The normalized matrix. """ assert isinstance(matrix, ExpMatrix) assert isinstance(inplace, bool) if target is not None: assert isinstance(target, 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, nan[j].size + 1, dtype=np.float64) / \ (nan[j].size + 1.0) fill = np.nanpercentile(X[:, j], 100 * q) X[nan[j], j] = fill # generate sorting indices A = np.argsort(X, axis=0, kind='mergesort') # mergesort is stable # reorder matrix for j in range(n): matrix.iloc[:, j] = matrix.X[A[:, j], j] # determine target distribution if target is None: # No target distribution is specified, calculate one based on the # expression matrix. target = np.mean(matrix.X, axis=1) else: # Use specified target 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[nan[j], j] = np.nan return matrix
python
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 matrix, and the nan values are restored afterwards. Parameters ---------- matrix: `ExpMatrix` The expression matrix (rows = genes, columns = samples). inplace: bool Whether or not to perform the operation in-place. [False] target: `numpy.ndarray` Target distribution to use. needs to be a vector whose first dimension matches that of the expression matrix. If ``None``, the target distribution is calculated based on the matrix itself. [None] Returns ------- numpy.ndarray (ndim = 2) The normalized matrix. """ assert isinstance(matrix, ExpMatrix) assert isinstance(inplace, bool) if target is not None: assert isinstance(target, 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, nan[j].size + 1, dtype=np.float64) / \ (nan[j].size + 1.0) fill = np.nanpercentile(X[:, j], 100 * q) X[nan[j], j] = fill # generate sorting indices A = np.argsort(X, axis=0, kind='mergesort') # mergesort is stable # reorder matrix for j in range(n): matrix.iloc[:, j] = matrix.X[A[:, j], j] # determine target distribution if target is None: # No target distribution is specified, calculate one based on the # expression matrix. target = np.mean(matrix.X, axis=1) else: # Use specified target 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[nan[j], j] = np.nan return matrix
[ "def", "quantile_normalize", "(", "matrix", ",", "inplace", "=", "False", ",", "target", "=", "None", ")", ":", "assert", "isinstance", "(", "matrix", ",", "ExpMatrix", ")", "assert", "isinstance", "(", "inplace", ",", "bool", ")", "if", "target", "is", ...
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 matrix, and the nan values are restored afterwards. Parameters ---------- matrix: `ExpMatrix` The expression matrix (rows = genes, columns = samples). inplace: bool Whether or not to perform the operation in-place. [False] target: `numpy.ndarray` Target distribution to use. needs to be a vector whose first dimension matches that of the expression matrix. If ``None``, the target distribution is calculated based on the matrix itself. [None] Returns ------- numpy.ndarray (ndim = 2) The normalized matrix.
[ "Quantile", "normalization", "allowing", "for", "missing", "values", "(", "NaN", ")", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/normalize.py#L31-L106
acorg/dark-matter
dark/hsp.py
HSP.toDict
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
python
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", "toDict", "(", "self", ")", ":", "result", "=", "_Base", ".", "toDict", "(", "self", ")", "result", "[", "'score'", "]", "=", "self", ".", "score", ".", "score", "return", "result" ]
Get information about the HSP as a dictionary. @return: A C{dict} representation of the HSP.
[ "Get", "information", "about", "the", "HSP", "as", "a", "dictionary", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/hsp.py#L133-L141
flo-compbio/genometools
genometools/ensembl/filter_fasta.py
get_argument_parser
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 set to ``-``, read from ``stdin``.""")) parser.add_argument( '-s', '--species', type=str, choices=sorted(ensembl.SPECIES_CHROMPAT.keys()), default='human', help=textwrap.dedent("""\ Species for which to extract genes. (This parameter is ignored if ``--chromosome-pattern`` is specified.)""") ) parser.add_argument( '-c', '--chromosome-pattern', type=str, required=False, default=None, help=textwrap.dedent("""\ Regular expression that chromosome names have to match. If not specified, determine pattern based on the setting of ``--species``.""") ) parser.add_argument( '-o', '--output-file', type=str, required=True, help=textwrap.dedent("""\ Path of output file. If set to ``-``, print to ``stdout``, and redirect logging messages to ``stderr``.""")) parser = cli.add_reporting_args(parser) return parser
python
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 set to ``-``, read from ``stdin``.""")) parser.add_argument( '-s', '--species', type=str, choices=sorted(ensembl.SPECIES_CHROMPAT.keys()), default='human', help=textwrap.dedent("""\ Species for which to extract genes. (This parameter is ignored if ``--chromosome-pattern`` is specified.)""") ) parser.add_argument( '-c', '--chromosome-pattern', type=str, required=False, default=None, help=textwrap.dedent("""\ Regular expression that chromosome names have to match. If not specified, determine pattern based on the setting of ``--species``.""") ) parser.add_argument( '-o', '--output-file', type=str, required=True, help=textwrap.dedent("""\ Path of output file. If set to ``-``, print to ``stdout``, and redirect logging messages to ``stderr``.""")) parser = cli.add_reporting_args(parser) return parser
[ "def", "get_argument_parser", "(", ")", ":", "desc", "=", "'Filter FASTA file by chromosome names.'", "parser", "=", "cli", ".", "get_argument_parser", "(", "desc", "=", "desc", ")", "parser", ".", "add_argument", "(", "'-f'", ",", "'--fasta-file'", ",", "default"...
Returns an argument parser object for the script.
[ "Returns", "an", "argument", "parser", "object", "for", "the", "script", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ensembl/filter_fasta.py#L49-L84
flo-compbio/genometools
genometools/ensembl/filter_fasta.py
main
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 = args.verbose # configure root 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) # generate regular expression object from the chromosome pattern if chrom_pat is None: chrom_pat = ensembl.SPECIES_CHROMPAT[species] chrom_re = re.compile(chrom_pat) # filter the FASTA file # note: each chromosome sequence is temporarily read into memory, # so this script has a large memory footprint with \ misc.smart_open_read( fasta_file, mode='r', encoding='ascii', try_gzip=True ) as fh, \ misc.smart_open_write( output_file, mode='w', 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
python
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 = args.verbose # configure root 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) # generate regular expression object from the chromosome pattern if chrom_pat is None: chrom_pat = ensembl.SPECIES_CHROMPAT[species] chrom_re = re.compile(chrom_pat) # filter the FASTA file # note: each chromosome sequence is temporarily read into memory, # so this script has a large memory footprint with \ misc.smart_open_read( fasta_file, mode='r', encoding='ascii', try_gzip=True ) as fh, \ misc.smart_open_write( output_file, mode='w', 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", "main", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "# parse command-line arguments ", "parser", "=", "get_argument_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "fasta_file", "=", "args", ".", "fast...
Script body.
[ "Script", "body", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ensembl/filter_fasta.py#L87-L139
openfisca/openfisca-web-api
openfisca_web_api/application.py
ensure_json_content_type
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
python
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", "ensure_json_content_type", "(", "req", ",", "app", ")", ":", "res", "=", "req", ".", "get_response", "(", "app", ",", "catch_exc_info", "=", "True", ")", "res", ".", "content_type", "=", "'application/json; charset=utf-8'", "return", "res" ]
ErrorMiddleware returns hard-coded content-type text/html. Here we force it to be application/json.
[ "ErrorMiddleware", "returns", "hard", "-", "coded", "content", "-", "type", "text", "/", "html", ".", "Here", "we", "force", "it", "to", "be", "application", "/", "json", "." ]
train
https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/application.py#L41-L48
openfisca/openfisca-web-api
openfisca_web_api/application.py
make_app
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 ini file (where <name> defaults to main). """ # Configure the environment and fill conf dictionary. environment.load_environment(global_conf, app_conf) # Dispatch request to controllers. app = controllers.make_router() # Init request-dependant environment app = set_application_url(app) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) # Handle Python exceptions if not conf['debug']: def json_error_template(head_html, exception, extra): error_json = { 'code': 500, 'hint': u'See the HTTP server log to see the exception traceback.', 'message': exception, } if head_html: error_json['head_html'] = head_html if extra: error_json['extra'] = extra return json.dumps({'error': error_json}) weberror.errormiddleware.error_template = 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
python
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 ini file (where <name> defaults to main). """ # Configure the environment and fill conf dictionary. environment.load_environment(global_conf, app_conf) # Dispatch request to controllers. app = controllers.make_router() # Init request-dependant environment app = set_application_url(app) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) # Handle Python exceptions if not conf['debug']: def json_error_template(head_html, exception, extra): error_json = { 'code': 500, 'hint': u'See the HTTP server log to see the exception traceback.', 'message': exception, } if head_html: error_json['head_html'] = head_html if extra: error_json['extra'] = extra return json.dumps({'error': error_json}) weberror.errormiddleware.error_template = 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", "make_app", "(", "global_conf", ",", "*", "*", "app_conf", ")", ":", "# Configure the environment and fill conf dictionary.", "environment", ".", "load_environment", "(", "global_conf", ",", "app_conf", ")", "# Dispatch request to controllers.", "app", "=", "contro...
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 ini file (where <name> defaults to main).
[ "Create", "a", "WSGI", "application", "and", "return", "it" ]
train
https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/application.py#L58-L103
nkavaldj/myhdl_lib
myhdl_lib/fifo_speculative.py
fifo_speculative
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, wr_discard Output interface: empty, re, dout, rd_commit, rd_discard we (i) - writes data speculatively (the data can be later removed from the fifo) wr_commit (i) - accept the speculatively written data (can be read) wr_discard (i) - remove the speculatively written data at once full (o) - asserted when there are no empty cells to write data speculatively If we is asserted together with the wr_commit or wr_discard, the data being written is affected by the commit/discard command. If wr_commit and wr_discard are asserted simultaneously, the wr_discard wins. re (i) - reads data speculatively (the data 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 the commit/discard command. If rd_commit and rd_discard are asserted simultaneously, the rd_discard wins. Note: This fifo can be Full and Empty at the same time - all fifo cells are occupied by data that are either speculatively written or speculatively read Extra interface: afull (o) - almost full flag, asserted when the number of empty cells <= afull_th aempty (o) - almost empty flag, asserted when the number of full cells <= 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 occupied fifo cells reached since the last reset ovf (o) - overflow flag, set at the first write in a full fifo, cleared at reset udf (o) - underflow flag, set at the first read from an empty fifo, cleared at reset """ if (width == None): width = len(din) if (depth == None): depth = 2 assert ((wr_commit != None) and (wr_discard != None)) or ((wr_commit == None) and (wr_discard == None)), "SFIFO ERROR: Interface signals wr_commit and 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 Signal(bool(1)) wr_discard = wr_discard if (wr_discard != None) else Signal(bool(0)) rd_commit = rd_commit if (rd_commit != None) else Signal(bool(1)) rd_discard = rd_discard if (rd_discard != None) else Signal(bool(0)) full_flg = Signal(bool(1)) empty_flg = Signal(bool(1)) we_safe = Signal(bool(0)) re_safe = Signal(bool(0)) swr_non0 = Signal(bool(0)) srd_non0 = Signal(bool(0)) wr_commit_non0 = Signal(bool(0)) rd_commit_non0 = Signal(bool(0)) wr_discard_non0 = Signal(bool(0)) rd_discard_non0 = Signal(bool(0)) # Almost full/empty and their thresholds afull_flg = Signal(bool(0)) aempty_flg = Signal(bool(0)) if (afull_th == None): afull_th = depth//2 if (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(bool(0)) count_max = count_max if (count_max != None) else Signal(intbv(0, min=0, max=depth+1)) rd_ptr = Signal(intbv(0, min=0, max=depth)) wr_ptr = Signal(intbv(0, min=0, max=depth)) srd_ptr = Signal(intbv(0, min=0, max=depth)) srd_ptr_new = Signal(intbv(0, min=0, max=depth)) swr_ptr = Signal(intbv(0, min=0, max=depth)) swr_ptr_new = Signal(intbv(0, min=0, max=depth)) # Data written in the fifo (committed and not committed) data_count = Signal(intbv(0, min=0, max=depth + 1)) data_count_max = Signal(intbv(0, min=0, max=depth + 1)) @always_comb def out_assign(): full.next = full_flg empty.next = 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 not wr_discard rd_commit_non0.next = rd_commit and (srd_non0 or re_safe) and not rd_discard # wr_discard_non0.next = wr_discard and (swr_non0 or we_safe) rd_discard_non0.next = rd_discard and (srd_non0 or re_safe) """ ---------------------------- """ """ - Write, Read, Full, Empty - """ """ ---------------------------- """ @always_comb def sptrs_new(): """ Next value for the speculative pointers """ if (wr_discard): swr_ptr_new.next = wr_ptr elif (we_safe): swr_ptr_new.next = ((swr_ptr + 1) % depth) else: swr_ptr_new.next = swr_ptr if (rd_discard): srd_ptr_new.next = rd_ptr elif (re_safe): srd_ptr_new.next = ((srd_ptr + 1) % depth) else: srd_ptr_new.next = srd_ptr @always(clk.posedge) 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.next = swr_ptr_new # Read pointer if (rd_commit): rd_ptr.next = srd_ptr_new # Empty flag if (wr_commit_non0 or rd_discard_non0): empty_flg.next = 0 elif (re_safe and (srd_ptr_new == wr_ptr)): empty_flg.next = 1 # Full flag if (rd_commit_non0 or wr_discard_non0): full_flg.next = 0 elif (we_safe and (swr_ptr_new == rd_ptr)): full_flg.next = 1 # swr_non0 flag if (wr_commit or wr_discard): swr_non0.next = 0 elif (we_safe): swr_non0.next = 1 # srd_non0 flag if (rd_commit or rd_discard): srd_non0.next = 0 elif (re_safe): srd_non0.next = 1 """ rd srd wr swr rd ^ ^ v v ^ |#########################|%%%%%%%%%%%%%%|*************************|..............| |<------ srd_count ------>|<------------>|<------ swr_count ------>|<------------>| |<--------------- wr_count ------------->|<--------------- rd_count ------------->| |<----------------------------------- depth ------------------------------------->| """ """ ------------------------------------ """ """ - Almost_Full, Almost_Empty, Count - """ """ ------------------------------------ """ # count of the speculatively written data swr_count = Signal(intbv(0, min=0, max=depth + 1)) # count of the speculatively read data srd_count = Signal(intbv(0, min=0, max=depth + 1)) # count of the write committed data wr_count = Signal(intbv(0, min=0, max=depth + 1)) # count of the not write committed positions rd_count = Signal(intbv(0, min=0, max=depth + 1)) @always(clk.posedge) def state_extra(): if (rst): swr_count.next = 0 srd_count.next = 0 wr_count.next = 0 rd_count.next = depth data_count.next = 0 afull_flg.next = 0 aempty_flg.next = 1 data_count_max.next = 0 else: swr_count_new = 0 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 not wr_discard): wr_add_new = int((swr_count + 1) if (we_safe) else swr_count) rd_add_new = 0 if (rd_commit and not rd_discard): rd_add_new = int((srd_count + 1) if (re_safe) else srd_count) wr_count_new = wr_count + wr_add_new - rd_add_new rd_count_new = rd_count - wr_add_new + rd_add_new wr_count.next = wr_count_new rd_count.next = rd_count_new aempty_flg.next = ((wr_count_new - srd_count_new) <= aempty_th) afull_flg.next = ((rd_count_new - swr_count_new) <= afull_th ) # Count data in the fifo data_count_new = wr_count_new + swr_count_new data_count.next = data_count_new if (data_count_max < data_count_new): data_count_max.next = 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 """ ------------------- """ """ - Memory instance - """ """ ------------------- """ mem_we = Signal(bool(0)) mem_addrw = Signal(intbv(0, min=0, max=depth)) mem_addrr = Signal(intbv(0, min=0, max=depth)) mem_di = Signal(intbv(0)[width:0]) mem_do = Signal(intbv(0)[width:0]) # RAM: Simple-Dual-Port, Asynchronous Read mem = ram_sdp_ar( clk = clk, 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 = swr_ptr mem_addrr.next = srd_ptr mem_di.next = din dout.next = mem_do return instances()
python
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, wr_discard Output interface: empty, re, dout, rd_commit, rd_discard we (i) - writes data speculatively (the data can be later removed from the fifo) wr_commit (i) - accept the speculatively written data (can be read) wr_discard (i) - remove the speculatively written data at once full (o) - asserted when there are no empty cells to write data speculatively If we is asserted together with the wr_commit or wr_discard, the data being written is affected by the commit/discard command. If wr_commit and wr_discard are asserted simultaneously, the wr_discard wins. re (i) - reads data speculatively (the data 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 the commit/discard command. If rd_commit and rd_discard are asserted simultaneously, the rd_discard wins. Note: This fifo can be Full and Empty at the same time - all fifo cells are occupied by data that are either speculatively written or speculatively read Extra interface: afull (o) - almost full flag, asserted when the number of empty cells <= afull_th aempty (o) - almost empty flag, asserted when the number of full cells <= 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 occupied fifo cells reached since the last reset ovf (o) - overflow flag, set at the first write in a full fifo, cleared at reset udf (o) - underflow flag, set at the first read from an empty fifo, cleared at reset """ if (width == None): width = len(din) if (depth == None): depth = 2 assert ((wr_commit != None) and (wr_discard != None)) or ((wr_commit == None) and (wr_discard == None)), "SFIFO ERROR: Interface signals wr_commit and 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 Signal(bool(1)) wr_discard = wr_discard if (wr_discard != None) else Signal(bool(0)) rd_commit = rd_commit if (rd_commit != None) else Signal(bool(1)) rd_discard = rd_discard if (rd_discard != None) else Signal(bool(0)) full_flg = Signal(bool(1)) empty_flg = Signal(bool(1)) we_safe = Signal(bool(0)) re_safe = Signal(bool(0)) swr_non0 = Signal(bool(0)) srd_non0 = Signal(bool(0)) wr_commit_non0 = Signal(bool(0)) rd_commit_non0 = Signal(bool(0)) wr_discard_non0 = Signal(bool(0)) rd_discard_non0 = Signal(bool(0)) # Almost full/empty and their thresholds afull_flg = Signal(bool(0)) aempty_flg = Signal(bool(0)) if (afull_th == None): afull_th = depth//2 if (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(bool(0)) count_max = count_max if (count_max != None) else Signal(intbv(0, min=0, max=depth+1)) rd_ptr = Signal(intbv(0, min=0, max=depth)) wr_ptr = Signal(intbv(0, min=0, max=depth)) srd_ptr = Signal(intbv(0, min=0, max=depth)) srd_ptr_new = Signal(intbv(0, min=0, max=depth)) swr_ptr = Signal(intbv(0, min=0, max=depth)) swr_ptr_new = Signal(intbv(0, min=0, max=depth)) # Data written in the fifo (committed and not committed) data_count = Signal(intbv(0, min=0, max=depth + 1)) data_count_max = Signal(intbv(0, min=0, max=depth + 1)) @always_comb def out_assign(): full.next = full_flg empty.next = 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 not wr_discard rd_commit_non0.next = rd_commit and (srd_non0 or re_safe) and not rd_discard # wr_discard_non0.next = wr_discard and (swr_non0 or we_safe) rd_discard_non0.next = rd_discard and (srd_non0 or re_safe) """ ---------------------------- """ """ - Write, Read, Full, Empty - """ """ ---------------------------- """ @always_comb def sptrs_new(): """ Next value for the speculative pointers """ if (wr_discard): swr_ptr_new.next = wr_ptr elif (we_safe): swr_ptr_new.next = ((swr_ptr + 1) % depth) else: swr_ptr_new.next = swr_ptr if (rd_discard): srd_ptr_new.next = rd_ptr elif (re_safe): srd_ptr_new.next = ((srd_ptr + 1) % depth) else: srd_ptr_new.next = srd_ptr @always(clk.posedge) 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.next = swr_ptr_new # Read pointer if (rd_commit): rd_ptr.next = srd_ptr_new # Empty flag if (wr_commit_non0 or rd_discard_non0): empty_flg.next = 0 elif (re_safe and (srd_ptr_new == wr_ptr)): empty_flg.next = 1 # Full flag if (rd_commit_non0 or wr_discard_non0): full_flg.next = 0 elif (we_safe and (swr_ptr_new == rd_ptr)): full_flg.next = 1 # swr_non0 flag if (wr_commit or wr_discard): swr_non0.next = 0 elif (we_safe): swr_non0.next = 1 # srd_non0 flag if (rd_commit or rd_discard): srd_non0.next = 0 elif (re_safe): srd_non0.next = 1 """ rd srd wr swr rd ^ ^ v v ^ |#########################|%%%%%%%%%%%%%%|*************************|..............| |<------ srd_count ------>|<------------>|<------ swr_count ------>|<------------>| |<--------------- wr_count ------------->|<--------------- rd_count ------------->| |<----------------------------------- depth ------------------------------------->| """ """ ------------------------------------ """ """ - Almost_Full, Almost_Empty, Count - """ """ ------------------------------------ """ # count of the speculatively written data swr_count = Signal(intbv(0, min=0, max=depth + 1)) # count of the speculatively read data srd_count = Signal(intbv(0, min=0, max=depth + 1)) # count of the write committed data wr_count = Signal(intbv(0, min=0, max=depth + 1)) # count of the not write committed positions rd_count = Signal(intbv(0, min=0, max=depth + 1)) @always(clk.posedge) def state_extra(): if (rst): swr_count.next = 0 srd_count.next = 0 wr_count.next = 0 rd_count.next = depth data_count.next = 0 afull_flg.next = 0 aempty_flg.next = 1 data_count_max.next = 0 else: swr_count_new = 0 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 not wr_discard): wr_add_new = int((swr_count + 1) if (we_safe) else swr_count) rd_add_new = 0 if (rd_commit and not rd_discard): rd_add_new = int((srd_count + 1) if (re_safe) else srd_count) wr_count_new = wr_count + wr_add_new - rd_add_new rd_count_new = rd_count - wr_add_new + rd_add_new wr_count.next = wr_count_new rd_count.next = rd_count_new aempty_flg.next = ((wr_count_new - srd_count_new) <= aempty_th) afull_flg.next = ((rd_count_new - swr_count_new) <= afull_th ) # Count data in the fifo data_count_new = wr_count_new + swr_count_new data_count.next = data_count_new if (data_count_max < data_count_new): data_count_max.next = 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 """ ------------------- """ """ - Memory instance - """ """ ------------------- """ mem_we = Signal(bool(0)) mem_addrw = Signal(intbv(0, min=0, max=depth)) mem_addrr = Signal(intbv(0, min=0, max=depth)) mem_di = Signal(intbv(0)[width:0]) mem_do = Signal(intbv(0)[width:0]) # RAM: Simple-Dual-Port, Asynchronous Read mem = ram_sdp_ar( clk = clk, 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 = swr_ptr mem_addrr.next = srd_ptr mem_di.next = din dout.next = mem_do return instances()
[ "def", "fifo_speculative", "(", "rst", ",", "clk", ",", "full", ",", "we", ",", "din", ",", "empty", ",", "re", ",", "dout", ",", "wr_commit", "=", "None", ",", "wr_discard", "=", "None", ",", "rd_commit", "=", "None", ",", "rd_discard", "=", "None",...
Speculative FIFO Input interface: full, we, din, wr_commit, wr_discard Output interface: empty, re, dout, rd_commit, rd_discard we (i) - writes data speculatively (the data can be later removed from the fifo) wr_commit (i) - accept the speculatively written data (can be read) wr_discard (i) - remove the speculatively written data at once full (o) - asserted when there are no empty cells to write data speculatively If we is asserted together with the wr_commit or wr_discard, the data being written is affected by the commit/discard command. If wr_commit and wr_discard are asserted simultaneously, the wr_discard wins. re (i) - reads data speculatively (the data 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 the commit/discard command. If rd_commit and rd_discard are asserted simultaneously, the rd_discard wins. Note: This fifo can be Full and Empty at the same time - all fifo cells are occupied by data that are either speculatively written or speculatively read Extra interface: afull (o) - almost full flag, asserted when the number of empty cells <= afull_th aempty (o) - almost empty flag, asserted when the number of full cells <= 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 occupied fifo cells reached since the last reset ovf (o) - overflow flag, set at the first write in a full fifo, cleared at reset udf (o) - underflow flag, set at the first read from an empty fifo, cleared at reset
[ "Speculative", "FIFO" ]
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/fifo_speculative.py#L6-L301
acorg/dark-matter
dark/dimension.py
dimensionalIterator
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, 1), (0, 2), (1, 0), (1, 1), (1, 2). See the tests in test_dimension.py for many more examples. A dimension may also be given as '*', to provide a dimension that is never exhausted. For example, dimensionalIterator(('*', 2)) yields the infinite series (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), .... maxItems can be used to limit the number of tuples yielded. """ nDimensions = len(dimensions) if nDimensions == 0 or maxItems == 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 -= 1 if wheel < 0: return odometer[wheel] += 1
python
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, 1), (0, 2), (1, 0), (1, 1), (1, 2). See the tests in test_dimension.py for many more examples. A dimension may also be given as '*', to provide a dimension that is never exhausted. For example, dimensionalIterator(('*', 2)) yields the infinite series (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), .... maxItems can be used to limit the number of tuples yielded. """ nDimensions = len(dimensions) if nDimensions == 0 or maxItems == 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 -= 1 if wheel < 0: return odometer[wheel] += 1
[ "def", "dimensionalIterator", "(", "dimensions", ",", "maxItems", "=", "-", "1", ")", ":", "nDimensions", "=", "len", "(", "dimensions", ")", "if", "nDimensions", "==", "0", "or", "maxItems", "==", "0", ":", "return", "if", "any", "(", "map", "(", "lam...
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, 1), (0, 2), (1, 0), (1, 1), (1, 2). See the tests in test_dimension.py for many more examples. A dimension may also be given as '*', to provide a dimension that is never exhausted. For example, dimensionalIterator(('*', 2)) yields the infinite series (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), .... maxItems can be used to limit the number of tuples yielded.
[ "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"...
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/dimension.py#L1-L34
acorg/dark-matter
dark/dna.py
matchToString
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 subclasses. @param matchAmbiguous: If C{True}, ambiguous nucleotides that are possibly correct were counted as actually being correct. Otherwise, the match was done strictly, insisting that only non-ambiguous nucleotides could contribute to the matching nucleotide count. @param indent: A C{str} to indent all returned lines with. @param offsets: If not C{None}, a C{set} of offsets of interest that were only considered when making C{match}. @return: A C{str} describing the match. """ match = dnaMatch['match'] identicalMatchCount = match['identicalMatchCount'] ambiguousMatchCount = match['ambiguousMatchCount'] gapMismatchCount = 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, len2)) append(countPrint('%sAmbiguous matches' % indent, ambiguousMatchCount, len1, len2)) if ambiguousMatchCount and identicalMatchCount: anyMatchCount = identicalMatchCount + ambiguousMatchCount append(countPrint('%sExact or ambiguous matches' % indent, anyMatchCount, len1, len2)) mismatchCount = (gapMismatchCount + gapGapMismatchCount + nonGapMismatchCount) append(countPrint('%sMismatches' % indent, mismatchCount, len1, len2)) conflicts = 'conflicts' if matchAmbiguous else 'conflicts or ambiguities' append(countPrint('%s Not involving gaps (i.e., %s)' % (indent, conflicts), nonGapMismatchCount, len1, len2)) append(countPrint('%s Involving a gap in one sequence' % indent, gapMismatchCount, len1, len2)) append(countPrint('%s Involving a gap in both sequences' % indent, gapGapMismatchCount, len1, len2)) for read, key in zip((read1, read2), ('read1', 'read2')): append('%s Id: %s' % (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]['gapOffsets']))))) ambiguousCount = len(dnaMatch[key]['ambiguousOffsets']) append(countPrint('%s Ambiguous' % indent, ambiguousCount, length)) extraCount = dnaMatch[key]['extraCount'] if extraCount: append(countPrint('%s Extra nucleotides at end' % indent, extraCount, length)) return '\n'.join(result)
python
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 subclasses. @param matchAmbiguous: If C{True}, ambiguous nucleotides that are possibly correct were counted as actually being correct. Otherwise, the match was done strictly, insisting that only non-ambiguous nucleotides could contribute to the matching nucleotide count. @param indent: A C{str} to indent all returned lines with. @param offsets: If not C{None}, a C{set} of offsets of interest that were only considered when making C{match}. @return: A C{str} describing the match. """ match = dnaMatch['match'] identicalMatchCount = match['identicalMatchCount'] ambiguousMatchCount = match['ambiguousMatchCount'] gapMismatchCount = 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, len2)) append(countPrint('%sAmbiguous matches' % indent, ambiguousMatchCount, len1, len2)) if ambiguousMatchCount and identicalMatchCount: anyMatchCount = identicalMatchCount + ambiguousMatchCount append(countPrint('%sExact or ambiguous matches' % indent, anyMatchCount, len1, len2)) mismatchCount = (gapMismatchCount + gapGapMismatchCount + nonGapMismatchCount) append(countPrint('%sMismatches' % indent, mismatchCount, len1, len2)) conflicts = 'conflicts' if matchAmbiguous else 'conflicts or ambiguities' append(countPrint('%s Not involving gaps (i.e., %s)' % (indent, conflicts), nonGapMismatchCount, len1, len2)) append(countPrint('%s Involving a gap in one sequence' % indent, gapMismatchCount, len1, len2)) append(countPrint('%s Involving a gap in both sequences' % indent, gapGapMismatchCount, len1, len2)) for read, key in zip((read1, read2), ('read1', 'read2')): append('%s Id: %s' % (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]['gapOffsets']))))) ambiguousCount = len(dnaMatch[key]['ambiguousOffsets']) append(countPrint('%s Ambiguous' % indent, ambiguousCount, length)) extraCount = dnaMatch[key]['extraCount'] if extraCount: append(countPrint('%s Extra nucleotides at end' % indent, extraCount, length)) return '\n'.join(result)
[ "def", "matchToString", "(", "dnaMatch", ",", "read1", ",", "read2", ",", "matchAmbiguous", "=", "True", ",", "indent", "=", "''", ",", "offsets", "=", "None", ")", ":", "match", "=", "dnaMatch", "[", "'match'", "]", "identicalMatchCount", "=", "match", ...
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 subclasses. @param matchAmbiguous: If C{True}, ambiguous nucleotides that are possibly correct were counted as actually being correct. Otherwise, the match was done strictly, insisting that only non-ambiguous nucleotides could contribute to the matching nucleotide count. @param indent: A C{str} to indent all returned lines with. @param offsets: If not C{None}, a C{set} of offsets of interest that were only considered when making C{match}. @return: A C{str} describing the match.
[ "Format", "a", "DNA", "match", "as", "a", "string", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/dna.py#L39-L110
acorg/dark-matter
dark/dna.py
compareDNAReads
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 nucleotides that are possibly correct as actually being correct, and score these in the ambiguousMatchCount. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @param gapChars: An object supporting __contains__ with characters that should be considered to be gaps. @param offsets: If not C{None}, a C{set} of offsets of interest. Offsets not in the set will not be considered. @return: A C{dict} with information about the match and the individual sequences (see below). """ identicalMatchCount = ambiguousMatchCount = 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, matchAmbiguous): """ Checks if two characters match ambiguously if matchAmbiguous is True. A match is an ambiguous match if it is not an identical match, but the sets of ambiguous characters overlap. """ return (matchAmbiguous and not _identicalMatch(a, b) and AMBIGUOUS.get(a, empty) & AMBIGUOUS.get(b, empty)) for offset, (a, b) in enumerate(zip_longest(read1.sequence.upper(), read2.sequence.upper())): # Use 'is not None' in the following to allow an empty offsets set # to be passed. if offsets is not None and offset not in offsets: continue if len(AMBIGUOUS.get(a, '')) > 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 its end. read1ExtraCount += 1 if a in gapChars: read1GapOffsets.append(offset) else: # We have a character from both sequences (they could still be # gap characters). if a in gapChars: read1GapOffsets.append(offset) if b in gapChars: # Both are gaps. This can happen (though hopefully not # if the sequences were pairwise aligned). gapGapMismatchCount += 1 read2GapOffsets.append(offset) else: # a is a gap, b is not. gapMismatchCount += 1 else: if b in gapChars: # b is a gap, a 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, 'ambiguousMatchCount': ambiguousMatchCount, 'gapMismatchCount': gapMismatchCount, 'gapGapMismatchCount': gapGapMismatchCount, 'nonGapMismatchCount': nonGapMismatchCount, }, 'read1': { 'ambiguousOffsets': read1AmbiguousOffsets, 'extraCount': read1ExtraCount, 'gapOffsets': read1GapOffsets, }, 'read2': { 'ambiguousOffsets': read2AmbiguousOffsets, 'extraCount': read2ExtraCount, 'gapOffsets': read2GapOffsets, }, }
python
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 nucleotides that are possibly correct as actually being correct, and score these in the ambiguousMatchCount. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @param gapChars: An object supporting __contains__ with characters that should be considered to be gaps. @param offsets: If not C{None}, a C{set} of offsets of interest. Offsets not in the set will not be considered. @return: A C{dict} with information about the match and the individual sequences (see below). """ identicalMatchCount = ambiguousMatchCount = 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, matchAmbiguous): """ Checks if two characters match ambiguously if matchAmbiguous is True. A match is an ambiguous match if it is not an identical match, but the sets of ambiguous characters overlap. """ return (matchAmbiguous and not _identicalMatch(a, b) and AMBIGUOUS.get(a, empty) & AMBIGUOUS.get(b, empty)) for offset, (a, b) in enumerate(zip_longest(read1.sequence.upper(), read2.sequence.upper())): # Use 'is not None' in the following to allow an empty offsets set # to be passed. if offsets is not None and offset not in offsets: continue if len(AMBIGUOUS.get(a, '')) > 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 its end. read1ExtraCount += 1 if a in gapChars: read1GapOffsets.append(offset) else: # We have a character from both sequences (they could still be # gap characters). if a in gapChars: read1GapOffsets.append(offset) if b in gapChars: # Both are gaps. This can happen (though hopefully not # if the sequences were pairwise aligned). gapGapMismatchCount += 1 read2GapOffsets.append(offset) else: # a is a gap, b is not. gapMismatchCount += 1 else: if b in gapChars: # b is a gap, a 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, 'ambiguousMatchCount': ambiguousMatchCount, 'gapMismatchCount': gapMismatchCount, 'gapGapMismatchCount': gapGapMismatchCount, 'nonGapMismatchCount': nonGapMismatchCount, }, 'read1': { 'ambiguousOffsets': read1AmbiguousOffsets, 'extraCount': read1ExtraCount, 'gapOffsets': read1GapOffsets, }, 'read2': { 'ambiguousOffsets': read2AmbiguousOffsets, 'extraCount': read2ExtraCount, 'gapOffsets': read2GapOffsets, }, }
[ "def", "compareDNAReads", "(", "read1", ",", "read2", ",", "matchAmbiguous", "=", "True", ",", "gapChars", "=", "'-'", ",", "offsets", "=", "None", ")", ":", "identicalMatchCount", "=", "ambiguousMatchCount", "=", "0", "gapMismatchCount", "=", "nonGapMismatchCou...
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 nucleotides that are possibly correct as actually being correct, and score these in the ambiguousMatchCount. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @param gapChars: An object supporting __contains__ with characters that should be considered to be gaps. @param offsets: If not C{None}, a C{set} of offsets of interest. Offsets not in the set will not be considered. @return: A C{dict} with information about the match and the individual sequences (see below).
[ "Compare", "two", "DNA", "sequences", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/dna.py#L113-L220
acorg/dark-matter
dark/dna.py
findKozakConsensus
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 not taken into account here. @param read: A C{DNARead} instance to be checked for Kozak consensi. @return: A generator that yields C{DNAKozakRead} instances. """ readLen = len(read) if readLen > 9: offset = 6 readSeq = read.sequence while offset < readLen - 3: triplet = readSeq[offset:offset + 3] if triplet == 'ATG': if readSeq[offset + 3] == 'G': if readSeq[offset - 3] in 'GA': kozakQualityCount = sum(( readSeq[offset - 1] == 'C', readSeq[offset - 2] == 'C', readSeq[offset - 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
python
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 not taken into account here. @param read: A C{DNARead} instance to be checked for Kozak consensi. @return: A generator that yields C{DNAKozakRead} instances. """ readLen = len(read) if readLen > 9: offset = 6 readSeq = read.sequence while offset < readLen - 3: triplet = readSeq[offset:offset + 3] if triplet == 'ATG': if readSeq[offset + 3] == 'G': if readSeq[offset - 3] in 'GA': kozakQualityCount = sum(( readSeq[offset - 1] == 'C', readSeq[offset - 2] == 'C', readSeq[offset - 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", "findKozakConsensus", "(", "read", ")", ":", "readLen", "=", "len", "(", "read", ")", "if", "readLen", ">", "9", ":", "offset", "=", "6", "readSeq", "=", "read", ".", "sequence", "while", "offset", "<", "readLen", "-", "3", ":", "triplet", "="...
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 not taken into account here. @param read: A C{DNARead} instance to be checked for Kozak consensi. @return: A generator that yields C{DNAKozakRead} instances.
[ "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",...
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/dna.py#L223-L253
acorg/dark-matter
bin/check-fasta-json-blast-consistency.py
check
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. @param jsonFiles: A C{list} of names of our BLAST JSON. These may may be compressed (as bz2). @param fastaFile: The C{str} name of a FASTA-containing file. """ reads = FastaReads(fastaFile) readsAlignments = BlastReadsAlignments(reads, jsonFiles) for index, readAlignments in enumerate(readsAlignments): # Check that all the alignments in the BLAST JSON do not have query # sequences or query offsets that are greater than the length of # the sequence given in the FASTA file. fastaLen = len(readAlignments.read) for readAlignment 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(hsp.query), readAlignments.read.sequence, hsp.query)) # The FASTA sequence length should be larger than either of # the query offsets mentioned in the JSON BLAST # record. That's because readStart and readEnd are offsets # into the read - so they can't be bigger than the read # length. # # TODO: These asserts should be more informative when they # fail. assert fastaLen >= hsp.readEnd >= hsp.readStart, ( 'record %d: FASTA len %d not greater than 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))
python
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. @param jsonFiles: A C{list} of names of our BLAST JSON. These may may be compressed (as bz2). @param fastaFile: The C{str} name of a FASTA-containing file. """ reads = FastaReads(fastaFile) readsAlignments = BlastReadsAlignments(reads, jsonFiles) for index, readAlignments in enumerate(readsAlignments): # Check that all the alignments in the BLAST JSON do not have query # sequences or query offsets that are greater than the length of # the sequence given in the FASTA file. fastaLen = len(readAlignments.read) for readAlignment 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(hsp.query), readAlignments.read.sequence, hsp.query)) # The FASTA sequence length should be larger than either of # the query offsets mentioned in the JSON BLAST # record. That's because readStart and readEnd are offsets # into the read - so they can't be bigger than the read # length. # # TODO: These asserts should be more informative when they # fail. assert fastaLen >= hsp.readEnd >= hsp.readStart, ( 'record %d: FASTA len %d not greater than 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", "check", "(", "fastaFile", ",", "jsonFiles", ")", ":", "reads", "=", "FastaReads", "(", "fastaFile", ")", "readsAlignments", "=", "BlastReadsAlignments", "(", "reads", ",", "jsonFiles", ")", "for", "index", ",", "readAlignments", "in", "enumerate", "(",...
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. @param jsonFiles: A C{list} of names of our BLAST JSON. These may may be compressed (as bz2). @param fastaFile: The C{str} name of a FASTA-containing file.
[ "Check", "for", "simple", "consistency", "between", "the", "FASTA", "file", "and", "the", "JSON", "files", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/check-fasta-json-blast-consistency.py#L19-L62
acorg/dark-matter
bin/fasta-identity-table.py
thresholdForIdentity
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 by C{parseColors}. @return: The first C{float} threshold that the given identity is at least as big as. """ for threshold, _ in colors: if identity >= threshold: return threshold raise ValueError('This should never happen! Last threshold is not 0.0?')
python
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 by C{parseColors}. @return: The first C{float} threshold that the given identity is at least as big as. """ for threshold, _ in colors: if identity >= threshold: return threshold raise ValueError('This should never happen! Last threshold is not 0.0?')
[ "def", "thresholdForIdentity", "(", "identity", ",", "colors", ")", ":", "for", "threshold", ",", "_", "in", "colors", ":", "if", "identity", ">=", "threshold", ":", "return", "threshold", "raise", "ValueError", "(", "'This should never happen! Last threshold is not...
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 by C{parseColors}. @return: The first C{float} threshold that the given identity is at least as big as.
[ "Get", "the", "best", "identity", "threshold", "for", "a", "specific", "identity", "value", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/fasta-identity-table.py#L29-L43
acorg/dark-matter
bin/fasta-identity-table.py
parseColors
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 any color in C{colors}. @return: A C{list} of (threshold, color) tuples, where threshold is a C{float} (from C{colors}) and color is a C{str} (from C{colors}). The list will be sorted by decreasing threshold values. """ result = [] if colors: for colorInfo in colors: fields = colorInfo.split(maxsplit=1) if len(fields) == 2: threshold, color = fields try: threshold = float(threshold) except ValueError: print('--color arguments must be given as space-separated ' 'pairs of "value color" where the value is a ' 'numeric identity 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, file=sys.stderr) sys.exit(1) result.append((threshold, color)) else: print('--color arguments must be given as space-separated ' 'pairs of "value color". You have given %r, which does ' 'not contain a space.' % colorInfo, file=sys.stderr) sys.exit(1) result.sort(key=itemgetter(0), reverse=True) if not result or result[-1][0] > 0.0: result.append((0.0, defaultColor)) return result
python
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 any color in C{colors}. @return: A C{list} of (threshold, color) tuples, where threshold is a C{float} (from C{colors}) and color is a C{str} (from C{colors}). The list will be sorted by decreasing threshold values. """ result = [] if colors: for colorInfo in colors: fields = colorInfo.split(maxsplit=1) if len(fields) == 2: threshold, color = fields try: threshold = float(threshold) except ValueError: print('--color arguments must be given as space-separated ' 'pairs of "value color" where the value is a ' 'numeric identity 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, file=sys.stderr) sys.exit(1) result.append((threshold, color)) else: print('--color arguments must be given as space-separated ' 'pairs of "value color". You have given %r, which does ' 'not contain a space.' % colorInfo, file=sys.stderr) sys.exit(1) result.sort(key=itemgetter(0), reverse=True) if not result or result[-1][0] > 0.0: result.append((0.0, defaultColor)) return result
[ "def", "parseColors", "(", "colors", ",", "defaultColor", ")", ":", "result", "=", "[", "]", "if", "colors", ":", "for", "colorInfo", "in", "colors", ":", "fields", "=", "colorInfo", ".", "split", "(", "maxsplit", "=", "1", ")", "if", "len", "(", "fi...
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 any color in C{colors}. @return: A C{list} of (threshold, color) tuples, where threshold is a C{float} (from C{colors}) and color is a C{str} (from C{colors}). The list will be sorted by decreasing threshold values.
[ "Parse", "command", "line", "color", "information", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/fasta-identity-table.py#L46-L92
acorg/dark-matter
bin/fasta-identity-table.py
getReadLengths
def getReadLengths(reads, gapChars): """ Get all read lengths, excluding gap characters. @param reads: A C{Reads} instance. @param gapChars: A C{str} of sequence characters considered to be gaps. @return: A C{dict} keyed by read id, with C{int} length values. """ gapChars = set(gapChars) result = {} for read in reads: result[read.id] = len(read) - sum( character in gapChars for character in read.sequence) return result
python
def getReadLengths(reads, gapChars): """ Get all read lengths, excluding gap characters. @param reads: A C{Reads} instance. @param gapChars: A C{str} of sequence characters considered to be gaps. @return: A C{dict} keyed by read id, with C{int} length values. """ gapChars = set(gapChars) result = {} for read in reads: result[read.id] = len(read) - sum( character in gapChars for character in read.sequence) return result
[ "def", "getReadLengths", "(", "reads", ",", "gapChars", ")", ":", "gapChars", "=", "set", "(", "gapChars", ")", "result", "=", "{", "}", "for", "read", "in", "reads", ":", "result", "[", "read", ".", "id", "]", "=", "len", "(", "read", ")", "-", ...
Get all read lengths, excluding gap characters. @param reads: A C{Reads} instance. @param gapChars: A C{str} of sequence characters considered to be gaps. @return: A C{dict} keyed by read id, with C{int} length values.
[ "Get", "all", "read", "lengths", "excluding", "gap", "characters", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/fasta-identity-table.py#L95-L108
acorg/dark-matter
bin/fasta-identity-table.py
explanation
def explanation(matchAmbiguous, concise, showLengths, showGaps, showNs): """ Make an explanation of the output HTML table. @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @param concise: If C{True}, do not show match detail abbreviations. @param showLengths: If C{True}, include the lengths of sequences. @param showGaps: If C{True}, include the number of gaps in sequences. @param showNs: If C{True}, include the number of N characters in sequences. @return: A C{str} of HTML. """ result = [""" <h1>Sequence versus sequence identity table</h1> <p> The table cells below show the nucleotide identity fraction for the sequences (<span class="best">like this</span> for the best value in each row). The identity fraction numerator is the sum of the number of identical """] if matchAmbiguous: result.append('nucleotides plus the number of ambiguously matching ' 'nucleotides.') else: result.append('nucleotides.') result.append("""The denominator is the length of the sequence <em>for the row</em>. Sequence gaps are not included when calculating their lengths. </p> """) if showLengths or showGaps or showNs or matchAmbiguous or not concise: result.append(""" <p> Key to abbreviations: <ul> """) if showLengths: result.append('<li>L: sequence Length.</li>') if showGaps: result.append('<li>G: number of Gaps in sequence.</li>') if showNs: result.append('<li>N: number of N characters in sequence.</li>') if not concise: result.append('<li>IM: Identical nucleotide Matches.</li>') if matchAmbiguous: result.append('<li>AM: Ambiguous nucleotide Matches.</li>') result.append(""" <li>GG: Gap/Gap matches (both sequences have gaps).</li> <li>G?: Gap/Non-gap mismatches (one sequence has a gap).</li> <li>NE: Non-equal nucleotide mismatches.</li> </ul> </p> """) return '\n'.join(result)
python
def explanation(matchAmbiguous, concise, showLengths, showGaps, showNs): """ Make an explanation of the output HTML table. @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @param concise: If C{True}, do not show match detail abbreviations. @param showLengths: If C{True}, include the lengths of sequences. @param showGaps: If C{True}, include the number of gaps in sequences. @param showNs: If C{True}, include the number of N characters in sequences. @return: A C{str} of HTML. """ result = [""" <h1>Sequence versus sequence identity table</h1> <p> The table cells below show the nucleotide identity fraction for the sequences (<span class="best">like this</span> for the best value in each row). The identity fraction numerator is the sum of the number of identical """] if matchAmbiguous: result.append('nucleotides plus the number of ambiguously matching ' 'nucleotides.') else: result.append('nucleotides.') result.append("""The denominator is the length of the sequence <em>for the row</em>. Sequence gaps are not included when calculating their lengths. </p> """) if showLengths or showGaps or showNs or matchAmbiguous or not concise: result.append(""" <p> Key to abbreviations: <ul> """) if showLengths: result.append('<li>L: sequence Length.</li>') if showGaps: result.append('<li>G: number of Gaps in sequence.</li>') if showNs: result.append('<li>N: number of N characters in sequence.</li>') if not concise: result.append('<li>IM: Identical nucleotide Matches.</li>') if matchAmbiguous: result.append('<li>AM: Ambiguous nucleotide Matches.</li>') result.append(""" <li>GG: Gap/Gap matches (both sequences have gaps).</li> <li>G?: Gap/Non-gap mismatches (one sequence has a gap).</li> <li>NE: Non-equal nucleotide mismatches.</li> </ul> </p> """) return '\n'.join(result)
[ "def", "explanation", "(", "matchAmbiguous", ",", "concise", ",", "showLengths", ",", "showGaps", ",", "showNs", ")", ":", "result", "=", "[", "\"\"\"\n<h1>Sequence versus sequence identity table</h1>\n\n<p>\n\nThe table cells below show the nucleotide identity fraction for the seq...
Make an explanation of the output HTML table. @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @param concise: If C{True}, do not show match detail abbreviations. @param showLengths: If C{True}, include the lengths of sequences. @param showGaps: If C{True}, include the number of gaps in sequences. @param showNs: If C{True}, include the number of N characters in sequences. @return: A C{str} of HTML.
[ "Make", "an", "explanation", "of", "the", "output", "HTML", "table", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/fasta-identity-table.py#L111-L179
acorg/dark-matter
bin/fasta-identity-table.py
collectData
def collectData(reads1, reads2, square, matchAmbiguous): """ Get pairwise matching statistics for two sets of reads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. """ result = defaultdict(dict) for id1, read1 in reads1.items(): for id2, read2 in reads2.items(): if id1 != id2 or not square: match = compareDNAReads( read1, read2, matchAmbiguous=matchAmbiguous)['match'] if not matchAmbiguous: assert match['ambiguousMatchCount'] == 0 result[id1][id2] = result[id2][id1] = match return result
python
def collectData(reads1, reads2, square, matchAmbiguous): """ Get pairwise matching statistics for two sets of reads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. """ result = defaultdict(dict) for id1, read1 in reads1.items(): for id2, read2 in reads2.items(): if id1 != id2 or not square: match = compareDNAReads( read1, read2, matchAmbiguous=matchAmbiguous)['match'] if not matchAmbiguous: assert match['ambiguousMatchCount'] == 0 result[id1][id2] = result[id2][id1] = match return result
[ "def", "collectData", "(", "reads1", ",", "reads2", ",", "square", ",", "matchAmbiguous", ")", ":", "result", "=", "defaultdict", "(", "dict", ")", "for", "id1", ",", "read1", "in", "reads1", ".", "items", "(", ")", ":", "for", "id2", ",", "read2", "...
Get pairwise matching statistics for two sets of reads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count.
[ "Get", "pairwise", "matching", "statistics", "for", "two", "sets", "of", "reads", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/fasta-identity-table.py#L182-L208
acorg/dark-matter
bin/fasta-identity-table.py
simpleTable
def simpleTable(tableData, reads1, reads2, square, matchAmbiguous, gapChars): """ Make a text table showing inter-sequence distances. @param tableData: A C{defaultdict(dict)} keyed by read ids, whose values are the dictionaries returned by compareDNAReads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @param gapChars: A C{str} of sequence characters considered to be gaps. """ readLengths1 = getReadLengths(reads1.values(), gapChars) print('ID\t' + '\t'.join(reads2)) for id1, read1 in reads1.items(): read1Len = readLengths1[id1] print(id1, end='') for id2, read2 in reads2.items(): if id1 == id2 and square: print('\t', end='') else: stats = tableData[id1][id2] identity = ( stats['identicalMatchCount'] + (stats['ambiguousMatchCount'] if matchAmbiguous else 0) ) / read1Len print('\t%.4f' % identity, end='') print()
python
def simpleTable(tableData, reads1, reads2, square, matchAmbiguous, gapChars): """ Make a text table showing inter-sequence distances. @param tableData: A C{defaultdict(dict)} keyed by read ids, whose values are the dictionaries returned by compareDNAReads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @param gapChars: A C{str} of sequence characters considered to be gaps. """ readLengths1 = getReadLengths(reads1.values(), gapChars) print('ID\t' + '\t'.join(reads2)) for id1, read1 in reads1.items(): read1Len = readLengths1[id1] print(id1, end='') for id2, read2 in reads2.items(): if id1 == id2 and square: print('\t', end='') else: stats = tableData[id1][id2] identity = ( stats['identicalMatchCount'] + (stats['ambiguousMatchCount'] if matchAmbiguous else 0) ) / read1Len print('\t%.4f' % identity, end='') print()
[ "def", "simpleTable", "(", "tableData", ",", "reads1", ",", "reads2", ",", "square", ",", "matchAmbiguous", ",", "gapChars", ")", ":", "readLengths1", "=", "getReadLengths", "(", "reads1", ".", "values", "(", ")", ",", "gapChars", ")", "print", "(", "'ID\\...
Make a text table showing inter-sequence distances. @param tableData: A C{defaultdict(dict)} keyed by read ids, whose values are the dictionaries returned by compareDNAReads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @param gapChars: A C{str} of sequence characters considered to be gaps.
[ "Make", "a", "text", "table", "showing", "inter", "-", "sequence", "distances", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/fasta-identity-table.py#L211-L246
acorg/dark-matter
bin/fasta-identity-table.py
htmlTable
def htmlTable(tableData, reads1, reads2, square, matchAmbiguous, colors, concise=False, showLengths=False, showGaps=False, showNs=False, footer=False, div=False, gapChars='-'): """ Make an HTML table showing inter-sequence distances. @param tableData: A C{defaultdict(dict)} keyed by read ids, whose values are the dictionaries returned by compareDNAReads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @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 by C{parseColors}. @param concise: If C{True}, do not show match details. @param showLengths: If C{True}, include the lengths of sequences. @param showGaps: If C{True}, include the number of gaps in sequences. @param showGaps: If C{True}, include the number of N characters in sequences. @param footer: If C{True}, incude a footer row giving the same information as found in the table header. @param div: If C{True}, return an HTML <div> fragment only, not a full HTML document. @param gapChars: A C{str} of sequence characters considered to be gaps. @return: An HTML C{str} showing inter-sequence distances. """ readLengths1 = getReadLengths(reads1.values(), gapChars) readLengths2 = getReadLengths(reads2.values(), gapChars) result = [] append = result.append def writeHeader(): # The header row of the table. append(' <tr>') append(' <td>&nbsp;</td>') for read2 in reads2.values(): append(' <td class="title"><span class="name">%s</span>' % read2.id) if showLengths and not square: append(' <br>L:%d' % readLengths2[read2.id]) if showGaps and not square: append(' <br>G:%d' % (len(read2) - readLengths2[read2.id])) if showNs and not square: append(' <br>N:%d' % read2.sequence.count('N')) append(' </td>') append(' </tr>') if div: append('<div>') else: append('<!DOCTYPE HTML>') append('<html>') append('<head>') append('<meta charset="UTF-8">') append('</head>') append('<body>') append('<style>') append(""" table { border-collapse: collapse; } table, td { border: 1px solid #ccc; } tr:hover { background-color: #f2f2f2; } td { vertical-align: top; font-size: 14px; } span.name { font-weight: bold; } span.best { font-weight: bold; } """) # Add color style information for the identity thresholds. for threshold, color in colors: append('.%s { background-color: %s; }' % ( thresholdToCssName(threshold), color)) append('</style>') if not div: append(explanation( matchAmbiguous, concise, showLengths, showGaps, showNs)) append('<div style="overflow-x:auto;">') append('<table>') append(' <tbody>') # Pre-process to find the best identities in each sample row. bestIdentityForId = {} for id1, read1 in reads1.items(): # Look for best identity for the sample. read1Len = readLengths1[id1] bestIdentity = -1.0 for id2, read2 in reads2.items(): if id1 != id2 or not square: stats = tableData[id1][id2] identity = ( stats['identicalMatchCount'] + (stats['ambiguousMatchCount'] if matchAmbiguous else 0) ) / read1Len if identity > bestIdentity: bestIdentity = identity bestIdentityForId[id1] = bestIdentity writeHeader() # The main body of the table. for id1, read1 in reads1.items(): read1Len = readLengths1[id1] append(' <tr>') append(' <td class="title"><span class="name">%s</span>' % id1) if showLengths: append('<br/>L:%d' % read1Len) if showGaps: append('<br/>G:%d' % (len(read1) - read1Len)) if showNs: append('<br/>N:%d' % read1.sequence.count('N')) append('</td>') for id2, read2 in reads2.items(): if id1 == id2 and square: append('<td>&nbsp;</td>') continue stats = tableData[id1][id2] identity = ( stats['identicalMatchCount'] + (stats['ambiguousMatchCount'] if matchAmbiguous else 0) ) / read1Len append(' <td class="%s">' % thresholdToCssName( thresholdForIdentity(identity, colors))) # The maximum percent identity. if identity == bestIdentityForId[id1]: scoreStyle = ' class="best"' else: scoreStyle = '' append('<span%s>%.4f</span>' % (scoreStyle, identity)) if not concise: append('<br/>IM:%d' % stats['identicalMatchCount']) if matchAmbiguous: append('<br/>AM:%d' % stats['ambiguousMatchCount']) append( '<br/>GG:%d' '<br/>G?:%d' '<br/>NE:%d' % (stats['gapGapMismatchCount'], stats['gapMismatchCount'], stats['nonGapMismatchCount'])) append(' </td>') append(' </tr>') if footer: writeHeader() append(' </tbody>') append('</table>') append('</div>') if div: append('</div>') else: append('</body>') append('</html>') return '\n'.join(result)
python
def htmlTable(tableData, reads1, reads2, square, matchAmbiguous, colors, concise=False, showLengths=False, showGaps=False, showNs=False, footer=False, div=False, gapChars='-'): """ Make an HTML table showing inter-sequence distances. @param tableData: A C{defaultdict(dict)} keyed by read ids, whose values are the dictionaries returned by compareDNAReads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @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 by C{parseColors}. @param concise: If C{True}, do not show match details. @param showLengths: If C{True}, include the lengths of sequences. @param showGaps: If C{True}, include the number of gaps in sequences. @param showGaps: If C{True}, include the number of N characters in sequences. @param footer: If C{True}, incude a footer row giving the same information as found in the table header. @param div: If C{True}, return an HTML <div> fragment only, not a full HTML document. @param gapChars: A C{str} of sequence characters considered to be gaps. @return: An HTML C{str} showing inter-sequence distances. """ readLengths1 = getReadLengths(reads1.values(), gapChars) readLengths2 = getReadLengths(reads2.values(), gapChars) result = [] append = result.append def writeHeader(): # The header row of the table. append(' <tr>') append(' <td>&nbsp;</td>') for read2 in reads2.values(): append(' <td class="title"><span class="name">%s</span>' % read2.id) if showLengths and not square: append(' <br>L:%d' % readLengths2[read2.id]) if showGaps and not square: append(' <br>G:%d' % (len(read2) - readLengths2[read2.id])) if showNs and not square: append(' <br>N:%d' % read2.sequence.count('N')) append(' </td>') append(' </tr>') if div: append('<div>') else: append('<!DOCTYPE HTML>') append('<html>') append('<head>') append('<meta charset="UTF-8">') append('</head>') append('<body>') append('<style>') append(""" table { border-collapse: collapse; } table, td { border: 1px solid #ccc; } tr:hover { background-color: #f2f2f2; } td { vertical-align: top; font-size: 14px; } span.name { font-weight: bold; } span.best { font-weight: bold; } """) # Add color style information for the identity thresholds. for threshold, color in colors: append('.%s { background-color: %s; }' % ( thresholdToCssName(threshold), color)) append('</style>') if not div: append(explanation( matchAmbiguous, concise, showLengths, showGaps, showNs)) append('<div style="overflow-x:auto;">') append('<table>') append(' <tbody>') # Pre-process to find the best identities in each sample row. bestIdentityForId = {} for id1, read1 in reads1.items(): # Look for best identity for the sample. read1Len = readLengths1[id1] bestIdentity = -1.0 for id2, read2 in reads2.items(): if id1 != id2 or not square: stats = tableData[id1][id2] identity = ( stats['identicalMatchCount'] + (stats['ambiguousMatchCount'] if matchAmbiguous else 0) ) / read1Len if identity > bestIdentity: bestIdentity = identity bestIdentityForId[id1] = bestIdentity writeHeader() # The main body of the table. for id1, read1 in reads1.items(): read1Len = readLengths1[id1] append(' <tr>') append(' <td class="title"><span class="name">%s</span>' % id1) if showLengths: append('<br/>L:%d' % read1Len) if showGaps: append('<br/>G:%d' % (len(read1) - read1Len)) if showNs: append('<br/>N:%d' % read1.sequence.count('N')) append('</td>') for id2, read2 in reads2.items(): if id1 == id2 and square: append('<td>&nbsp;</td>') continue stats = tableData[id1][id2] identity = ( stats['identicalMatchCount'] + (stats['ambiguousMatchCount'] if matchAmbiguous else 0) ) / read1Len append(' <td class="%s">' % thresholdToCssName( thresholdForIdentity(identity, colors))) # The maximum percent identity. if identity == bestIdentityForId[id1]: scoreStyle = ' class="best"' else: scoreStyle = '' append('<span%s>%.4f</span>' % (scoreStyle, identity)) if not concise: append('<br/>IM:%d' % stats['identicalMatchCount']) if matchAmbiguous: append('<br/>AM:%d' % stats['ambiguousMatchCount']) append( '<br/>GG:%d' '<br/>G?:%d' '<br/>NE:%d' % (stats['gapGapMismatchCount'], stats['gapMismatchCount'], stats['nonGapMismatchCount'])) append(' </td>') append(' </tr>') if footer: writeHeader() append(' </tbody>') append('</table>') append('</div>') if div: append('</div>') else: append('</body>') append('</html>') return '\n'.join(result)
[ "def", "htmlTable", "(", "tableData", ",", "reads1", ",", "reads2", ",", "square", ",", "matchAmbiguous", ",", "colors", ",", "concise", "=", "False", ",", "showLengths", "=", "False", ",", "showGaps", "=", "False", ",", "showNs", "=", "False", ",", "foo...
Make an HTML table showing inter-sequence distances. @param tableData: A C{defaultdict(dict)} keyed by read ids, whose values are the dictionaries returned by compareDNAReads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. @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 by C{parseColors}. @param concise: If C{True}, do not show match details. @param showLengths: If C{True}, include the lengths of sequences. @param showGaps: If C{True}, include the number of gaps in sequences. @param showGaps: If C{True}, include the number of N characters in sequences. @param footer: If C{True}, incude a footer row giving the same information as found in the table header. @param div: If C{True}, return an HTML <div> fragment only, not a full HTML document. @param gapChars: A C{str} of sequence characters considered to be gaps. @return: An HTML C{str} showing inter-sequence distances.
[ "Make", "an", "HTML", "table", "showing", "inter", "-", "sequence", "distances", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/fasta-identity-table.py#L249-L434
invenia/Arbiter
arbiter/task.py
create_task
def create_task(function, *args, **kwargs): """ Create a task object name: The name of the task. function: The actual task function. It should take no arguments, and return a False-y value if it fails. dependencies: (optional, ()) Any dependencies that this task relies on. """ name = "{}".format(uuid4()) handler = None deps = set() if 'name' in kwargs: name = kwargs['name'] del kwargs['name'] elif function is not None: name = "{}-{}".format(function.__name__, name) if 'handler' in kwargs: handler = kwargs['handler'] del kwargs['handler'] if 'dependencies' in kwargs: for dep in kwargs['dependencies']: deps.add(dep) del kwargs['dependencies'] for arg in args: if isinstance(arg, Task): deps.add(arg.name) for key in kwargs: if isinstance(kwargs[key], Task): deps.add(kwargs[key].name) return Task(name, function, handler, frozenset(deps), args, kwargs)
python
def create_task(function, *args, **kwargs): """ Create a task object name: The name of the task. function: The actual task function. It should take no arguments, and return a False-y value if it fails. dependencies: (optional, ()) Any dependencies that this task relies on. """ name = "{}".format(uuid4()) handler = None deps = set() if 'name' in kwargs: name = kwargs['name'] del kwargs['name'] elif function is not None: name = "{}-{}".format(function.__name__, name) if 'handler' in kwargs: handler = kwargs['handler'] del kwargs['handler'] if 'dependencies' in kwargs: for dep in kwargs['dependencies']: deps.add(dep) del kwargs['dependencies'] for arg in args: if isinstance(arg, Task): deps.add(arg.name) for key in kwargs: if isinstance(kwargs[key], Task): deps.add(kwargs[key].name) return Task(name, function, handler, frozenset(deps), args, kwargs)
[ "def", "create_task", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "\"{}\"", ".", "format", "(", "uuid4", "(", ")", ")", "handler", "=", "None", "deps", "=", "set", "(", ")", "if", "'name'", "in", "kwargs", "...
Create a task object name: The name of the task. function: The actual task function. It should take no arguments, and return a False-y value if it fails. dependencies: (optional, ()) Any dependencies that this task relies on.
[ "Create", "a", "task", "object", "name", ":", "The", "name", "of", "the", "task", ".", "function", ":", "The", "actual", "task", "function", ".", "It", "should", "take", "no", "arguments", "and", "return", "a", "False", "-", "y", "value", "if", "it", ...
train
https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/task.py#L14-L50
nkavaldj/myhdl_lib
myhdl_lib/handshake.py
hs_join
def hs_join(ls_hsi, hso): """ [Many-to-one] Synchronizes (joins) a list of input handshake interfaces: output is ready when ALL inputs are ready ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) an output handshake tuple (ready, valid) """ N = len(ls_hsi) ls_hsi_rdy, ls_hsi_vld = zip(*ls_hsi) ls_hsi_rdy, ls_hsi_vld = list(ls_hsi_rdy), list(ls_hsi_vld) hso_rdy, hso_vld = hso @always_comb def _hsjoin(): all_vld = True for i in range(N): all_vld = all_vld and ls_hsi_vld[i] hso_vld.next = all_vld for i in range(N): ls_hsi_rdy[i].next = all_vld and hso_rdy return _hsjoin
python
def hs_join(ls_hsi, hso): """ [Many-to-one] Synchronizes (joins) a list of input handshake interfaces: output is ready when ALL inputs are ready ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) an output handshake tuple (ready, valid) """ N = len(ls_hsi) ls_hsi_rdy, ls_hsi_vld = zip(*ls_hsi) ls_hsi_rdy, ls_hsi_vld = list(ls_hsi_rdy), list(ls_hsi_vld) hso_rdy, hso_vld = hso @always_comb def _hsjoin(): all_vld = True for i in range(N): all_vld = all_vld and ls_hsi_vld[i] hso_vld.next = all_vld for i in range(N): ls_hsi_rdy[i].next = all_vld and hso_rdy return _hsjoin
[ "def", "hs_join", "(", "ls_hsi", ",", "hso", ")", ":", "N", "=", "len", "(", "ls_hsi", ")", "ls_hsi_rdy", ",", "ls_hsi_vld", "=", "zip", "(", "*", "ls_hsi", ")", "ls_hsi_rdy", ",", "ls_hsi_vld", "=", "list", "(", "ls_hsi_rdy", ")", ",", "list", "(", ...
[Many-to-one] Synchronizes (joins) a list of input handshake interfaces: output is ready when ALL inputs are ready ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) an output handshake tuple (ready, valid)
[ "[", "Many", "-", "to", "-", "one", "]", "Synchronizes", "(", "joins", ")", "a", "list", "of", "input", "handshake", "interfaces", ":", "output", "is", "ready", "when", "ALL", "inputs", "are", "ready", "ls_hsi", "-", "(", "i", ")", "list", "of", "inp...
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/handshake.py#L63-L82
nkavaldj/myhdl_lib
myhdl_lib/handshake.py
hs_fork
def hs_fork(hsi, ls_hso): """ [One-to-many] Synchronizes (forks) to a list of output handshake interfaces: input is ready when ALL outputs are ready hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid) """ N = len(ls_hso) hsi_rdy, hsi_vld = hsi ls_hso_rdy, ls_hso_vld = zip(*ls_hso) ls_hso_rdy, ls_hso_vld = list(ls_hso_rdy), list(ls_hso_vld) @always_comb def _hsfork(): all_rdy = True for i in range(N): all_rdy = all_rdy and ls_hso_rdy[i] hsi_rdy.next = all_rdy for i in range(N): ls_hso_vld[i].next = all_rdy and hsi_vld return _hsfork
python
def hs_fork(hsi, ls_hso): """ [One-to-many] Synchronizes (forks) to a list of output handshake interfaces: input is ready when ALL outputs are ready hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid) """ N = len(ls_hso) hsi_rdy, hsi_vld = hsi ls_hso_rdy, ls_hso_vld = zip(*ls_hso) ls_hso_rdy, ls_hso_vld = list(ls_hso_rdy), list(ls_hso_vld) @always_comb def _hsfork(): all_rdy = True for i in range(N): all_rdy = all_rdy and ls_hso_rdy[i] hsi_rdy.next = all_rdy for i in range(N): ls_hso_vld[i].next = all_rdy and hsi_vld return _hsfork
[ "def", "hs_fork", "(", "hsi", ",", "ls_hso", ")", ":", "N", "=", "len", "(", "ls_hso", ")", "hsi_rdy", ",", "hsi_vld", "=", "hsi", "ls_hso_rdy", ",", "ls_hso_vld", "=", "zip", "(", "*", "ls_hso", ")", "ls_hso_rdy", ",", "ls_hso_vld", "=", "list", "("...
[One-to-many] Synchronizes (forks) to a list of output handshake interfaces: input is ready when ALL outputs are ready hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid)
[ "[", "One", "-", "to", "-", "many", "]", "Synchronizes", "(", "forks", ")", "to", "a", "list", "of", "output", "handshake", "interfaces", ":", "input", "is", "ready", "when", "ALL", "outputs", "are", "ready", "hsi", "-", "(", "i", ")", "input", "hand...
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/handshake.py#L85-L104
nkavaldj/myhdl_lib
myhdl_lib/handshake.py
hs_mux
def hs_mux(sel, ls_hsi, hso): """ [Many-to-one] Multiplexes a list of input handshake interfaces sel - (i) selects an input handshake interface to be connected to the output ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) output handshake tuple (ready, valid) """ N = len(ls_hsi) ls_hsi_rdy, ls_hsi_vld = zip(*ls_hsi) ls_hsi_rdy, ls_hsi_vld = list(ls_hsi_rdy), list(ls_hsi_vld) hso_rdy, hso_vld = hso @always_comb def _hsmux(): hso_vld.next = 0 for i in range(N): ls_hsi_rdy[i].next = 0 if i == sel: hso_vld.next = ls_hsi_vld[i] ls_hsi_rdy[i].next = hso_rdy return _hsmux
python
def hs_mux(sel, ls_hsi, hso): """ [Many-to-one] Multiplexes a list of input handshake interfaces sel - (i) selects an input handshake interface to be connected to the output ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) output handshake tuple (ready, valid) """ N = len(ls_hsi) ls_hsi_rdy, ls_hsi_vld = zip(*ls_hsi) ls_hsi_rdy, ls_hsi_vld = list(ls_hsi_rdy), list(ls_hsi_vld) hso_rdy, hso_vld = hso @always_comb def _hsmux(): hso_vld.next = 0 for i in range(N): ls_hsi_rdy[i].next = 0 if i == sel: hso_vld.next = ls_hsi_vld[i] ls_hsi_rdy[i].next = hso_rdy return _hsmux
[ "def", "hs_mux", "(", "sel", ",", "ls_hsi", ",", "hso", ")", ":", "N", "=", "len", "(", "ls_hsi", ")", "ls_hsi_rdy", ",", "ls_hsi_vld", "=", "zip", "(", "*", "ls_hsi", ")", "ls_hsi_rdy", ",", "ls_hsi_vld", "=", "list", "(", "ls_hsi_rdy", ")", ",", ...
[Many-to-one] Multiplexes a list of input handshake interfaces sel - (i) selects an input handshake interface to be connected to the output ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) output handshake tuple (ready, valid)
[ "[", "Many", "-", "to", "-", "one", "]", "Multiplexes", "a", "list", "of", "input", "handshake", "interfaces", "sel", "-", "(", "i", ")", "selects", "an", "input", "handshake", "interface", "to", "be", "connected", "to", "the", "output", "ls_hsi", "-", ...
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/handshake.py#L107-L127
nkavaldj/myhdl_lib
myhdl_lib/handshake.py
hs_demux
def hs_demux(sel, hsi, ls_hso): """ [One-to-many] Demultiplexes to a list of output handshake interfaces sel - (i) selects an output handshake interface to connect to the input hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid) """ N = len(ls_hso) hsi_rdy, hsi_vld = hsi ls_hso_rdy, ls_hso_vld = zip(*ls_hso) ls_hso_rdy, ls_hso_vld = list(ls_hso_rdy), list(ls_hso_vld) @always_comb def _hsdemux(): hsi_rdy.next = 0 for i in range(N): ls_hso_vld[i].next = 0 if i == sel: hsi_rdy.next = ls_hso_rdy[i] ls_hso_vld[i].next = hsi_vld return _hsdemux
python
def hs_demux(sel, hsi, ls_hso): """ [One-to-many] Demultiplexes to a list of output handshake interfaces sel - (i) selects an output handshake interface to connect to the input hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid) """ N = len(ls_hso) hsi_rdy, hsi_vld = hsi ls_hso_rdy, ls_hso_vld = zip(*ls_hso) ls_hso_rdy, ls_hso_vld = list(ls_hso_rdy), list(ls_hso_vld) @always_comb def _hsdemux(): hsi_rdy.next = 0 for i in range(N): ls_hso_vld[i].next = 0 if i == sel: hsi_rdy.next = ls_hso_rdy[i] ls_hso_vld[i].next = hsi_vld return _hsdemux
[ "def", "hs_demux", "(", "sel", ",", "hsi", ",", "ls_hso", ")", ":", "N", "=", "len", "(", "ls_hso", ")", "hsi_rdy", ",", "hsi_vld", "=", "hsi", "ls_hso_rdy", ",", "ls_hso_vld", "=", "zip", "(", "*", "ls_hso", ")", "ls_hso_rdy", ",", "ls_hso_vld", "="...
[One-to-many] Demultiplexes to a list of output handshake interfaces sel - (i) selects an output handshake interface to connect to the input hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid)
[ "[", "One", "-", "to", "-", "many", "]", "Demultiplexes", "to", "a", "list", "of", "output", "handshake", "interfaces", "sel", "-", "(", "i", ")", "selects", "an", "output", "handshake", "interface", "to", "connect", "to", "the", "input", "hsi", "-", "...
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/handshake.py#L130-L150
nkavaldj/myhdl_lib
myhdl_lib/handshake.py
hs_arbmux
def hs_arbmux(rst, clk, ls_hsi, hso, sel, ARBITER_TYPE="priority"): """ [Many-to-one] Arbitrates a list of input handshake interfaces. Selects one of the active input interfaces and connects it to the output. Active input is an input interface with asserted "valid" signal ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) output handshake tuple (ready, valid) sel - (o) indicates the currently selected input handshake interface ARBITER_TYPE - selects the arbiter type to be used, "priority" or "roundrobin" """ N = len(ls_hsi) ls_hsi_rdy, ls_hsi_vld = zip(*ls_hsi) ls_hsi_vld = list(ls_hsi_vld) # Needed to avoid: "myhdl.ConversionError: Signal in multiple list is not supported:" ls_vld = [Signal(bool(0)) for _ in range(N)] _a = [assign(ls_vld[i], ls_hsi_vld[i]) for i in range(N)] sel_s = Signal(intbv(0, min=0, max=N)) @always_comb def _sel(): sel.next = sel_s priority_update = None if (ARBITER_TYPE == "roundrobin"): hso_rdy, hso_vld = hso priority_update = Signal(bool(0)) @always_comb def _prio(): priority_update.next = hso_rdy and hso_vld _arb = arbiter(rst=rst, clk=clk, req_vec=ls_vld, gnt_idx=sel_s, gnt_rdy=priority_update, ARBITER_TYPE=ARBITER_TYPE) _mux = hs_mux(sel=sel_s, ls_hsi=ls_hsi, hso=hso) return instances()
python
def hs_arbmux(rst, clk, ls_hsi, hso, sel, ARBITER_TYPE="priority"): """ [Many-to-one] Arbitrates a list of input handshake interfaces. Selects one of the active input interfaces and connects it to the output. Active input is an input interface with asserted "valid" signal ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) output handshake tuple (ready, valid) sel - (o) indicates the currently selected input handshake interface ARBITER_TYPE - selects the arbiter type to be used, "priority" or "roundrobin" """ N = len(ls_hsi) ls_hsi_rdy, ls_hsi_vld = zip(*ls_hsi) ls_hsi_vld = list(ls_hsi_vld) # Needed to avoid: "myhdl.ConversionError: Signal in multiple list is not supported:" ls_vld = [Signal(bool(0)) for _ in range(N)] _a = [assign(ls_vld[i], ls_hsi_vld[i]) for i in range(N)] sel_s = Signal(intbv(0, min=0, max=N)) @always_comb def _sel(): sel.next = sel_s priority_update = None if (ARBITER_TYPE == "roundrobin"): hso_rdy, hso_vld = hso priority_update = Signal(bool(0)) @always_comb def _prio(): priority_update.next = hso_rdy and hso_vld _arb = arbiter(rst=rst, clk=clk, req_vec=ls_vld, gnt_idx=sel_s, gnt_rdy=priority_update, ARBITER_TYPE=ARBITER_TYPE) _mux = hs_mux(sel=sel_s, ls_hsi=ls_hsi, hso=hso) return instances()
[ "def", "hs_arbmux", "(", "rst", ",", "clk", ",", "ls_hsi", ",", "hso", ",", "sel", ",", "ARBITER_TYPE", "=", "\"priority\"", ")", ":", "N", "=", "len", "(", "ls_hsi", ")", "ls_hsi_rdy", ",", "ls_hsi_vld", "=", "zip", "(", "*", "ls_hsi", ")", "ls_hsi_...
[Many-to-one] Arbitrates a list of input handshake interfaces. Selects one of the active input interfaces and connects it to the output. Active input is an input interface with asserted "valid" signal ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) output handshake tuple (ready, valid) sel - (o) indicates the currently selected input handshake interface ARBITER_TYPE - selects the arbiter type to be used, "priority" or "roundrobin"
[ "[", "Many", "-", "to", "-", "one", "]", "Arbitrates", "a", "list", "of", "input", "handshake", "interfaces", ".", "Selects", "one", "of", "the", "active", "input", "interfaces", "and", "connects", "it", "to", "the", "output", ".", "Active", "input", "is...
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/handshake.py#L153-L189
nkavaldj/myhdl_lib
myhdl_lib/handshake.py
hs_arbdemux
def hs_arbdemux(rst, clk, hsi, ls_hso, sel, ARBITER_TYPE="priority"): """ [One-to-many] Arbitrates a list output handshake interfaces Selects one of the active output interfaces and connects it to the input. Active is an output interface with asserted "ready" signal hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid) sel - (o) indicates the currently selected output handshake interface ARBITER_TYPE - selects the type of arbiter to be used, "priority" or "roundrobin" """ N = len(ls_hso) ls_hso_rdy, ls_hso_vld = zip(*ls_hso) ls_hso_rdy = list(ls_hso_rdy) # Needed to avoid: "myhdl.ConversionError: Signal in multiple list is not supported:" ls_rdy = [Signal(bool(0)) for _ in range(N)] _a = [assign(ls_rdy[i], ls_hso_rdy[i]) for i in range(N)] sel_s = Signal(intbv(0, min=0, max=len(ls_rdy))) @always_comb def _sel(): sel.next = sel_s priority_update = None if (ARBITER_TYPE == "roundrobin"): shi_rdy, hsi_vld = hsi priority_update = Signal(bool(0)) @always_comb def _prio(): priority_update.next = shi_rdy and hsi_vld _arb = arbiter(rst=rst, clk=clk, req_vec=ls_rdy, gnt_idx=sel_s, gnt_rdy=priority_update, ARBITER_TYPE=ARBITER_TYPE) _demux = hs_demux(sel_s, hsi, ls_hso) return instances()
python
def hs_arbdemux(rst, clk, hsi, ls_hso, sel, ARBITER_TYPE="priority"): """ [One-to-many] Arbitrates a list output handshake interfaces Selects one of the active output interfaces and connects it to the input. Active is an output interface with asserted "ready" signal hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid) sel - (o) indicates the currently selected output handshake interface ARBITER_TYPE - selects the type of arbiter to be used, "priority" or "roundrobin" """ N = len(ls_hso) ls_hso_rdy, ls_hso_vld = zip(*ls_hso) ls_hso_rdy = list(ls_hso_rdy) # Needed to avoid: "myhdl.ConversionError: Signal in multiple list is not supported:" ls_rdy = [Signal(bool(0)) for _ in range(N)] _a = [assign(ls_rdy[i], ls_hso_rdy[i]) for i in range(N)] sel_s = Signal(intbv(0, min=0, max=len(ls_rdy))) @always_comb def _sel(): sel.next = sel_s priority_update = None if (ARBITER_TYPE == "roundrobin"): shi_rdy, hsi_vld = hsi priority_update = Signal(bool(0)) @always_comb def _prio(): priority_update.next = shi_rdy and hsi_vld _arb = arbiter(rst=rst, clk=clk, req_vec=ls_rdy, gnt_idx=sel_s, gnt_rdy=priority_update, ARBITER_TYPE=ARBITER_TYPE) _demux = hs_demux(sel_s, hsi, ls_hso) return instances()
[ "def", "hs_arbdemux", "(", "rst", ",", "clk", ",", "hsi", ",", "ls_hso", ",", "sel", ",", "ARBITER_TYPE", "=", "\"priority\"", ")", ":", "N", "=", "len", "(", "ls_hso", ")", "ls_hso_rdy", ",", "ls_hso_vld", "=", "zip", "(", "*", "ls_hso", ")", "ls_hs...
[One-to-many] Arbitrates a list output handshake interfaces Selects one of the active output interfaces and connects it to the input. Active is an output interface with asserted "ready" signal hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid) sel - (o) indicates the currently selected output handshake interface ARBITER_TYPE - selects the type of arbiter to be used, "priority" or "roundrobin"
[ "[", "One", "-", "to", "-", "many", "]", "Arbitrates", "a", "list", "output", "handshake", "interfaces", "Selects", "one", "of", "the", "active", "output", "interfaces", "and", "connects", "it", "to", "the", "input", ".", "Active", "is", "an", "output", ...
train
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/handshake.py#L192-L227
flo-compbio/genometools
genometools/misc/functions.py
get_file_md5sum
def get_file_md5sum(path): """Calculate the MD5 hash for a file.""" with open(path, 'rb') as fh: h = str(hashlib.md5(fh.read()).hexdigest()) return h
python
def get_file_md5sum(path): """Calculate the MD5 hash for a file.""" with open(path, 'rb') as fh: h = str(hashlib.md5(fh.read()).hexdigest()) return h
[ "def", "get_file_md5sum", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "fh", ":", "h", "=", "str", "(", "hashlib", ".", "md5", "(", "fh", ".", "read", "(", ")", ")", ".", "hexdigest", "(", ")", ")", "return", "h" ...
Calculate the MD5 hash for a file.
[ "Calculate", "the", "MD5", "hash", "for", "a", "file", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L65-L69
flo-compbio/genometools
genometools/misc/functions.py
smart_open_read
def smart_open_read(path=None, mode='rb', encoding=None, try_gzip=False): """Open a file for reading or return ``stdin``. Adapted from StackOverflow user "Wolph" (http://stackoverflow.com/a/17603000). """ assert mode in ('r', 'rb') assert path is None or isinstance(path, (str, _oldstr)) assert isinstance(mode, (str, _oldstr)) assert encoding is None or isinstance(encoding, (str, _oldstr)) assert isinstance(try_gzip, bool) fh = None binfh = None gzfh = None if path is None: # open stdin fh = io.open(sys.stdin.fileno(), mode=mode, encoding=encoding) else: # open an actual file if try_gzip: # gzip.open defaults to mode 'rb' gzfh = try_open_gzip(path) if gzfh is not None: logger.debug('Opening gzip''ed file.') # wrap gzip stream binfh = io.BufferedReader(gzfh) if 'b' not in mode: # add a text wrapper on top logger.debug('Adding text wrapper.') fh = io.TextIOWrapper(binfh, encoding=encoding) else: fh = io.open(path, mode=mode, encoding=encoding) yield_fh = fh if fh is None: yield_fh = binfh try: yield yield_fh finally: # close all open files if fh is not None: # make sure we don't close stdin if fh.fileno() != sys.stdin.fileno(): fh.close() if binfh is not None: binfh.close() if gzfh is not None: gzfh.close()
python
def smart_open_read(path=None, mode='rb', encoding=None, try_gzip=False): """Open a file for reading or return ``stdin``. Adapted from StackOverflow user "Wolph" (http://stackoverflow.com/a/17603000). """ assert mode in ('r', 'rb') assert path is None or isinstance(path, (str, _oldstr)) assert isinstance(mode, (str, _oldstr)) assert encoding is None or isinstance(encoding, (str, _oldstr)) assert isinstance(try_gzip, bool) fh = None binfh = None gzfh = None if path is None: # open stdin fh = io.open(sys.stdin.fileno(), mode=mode, encoding=encoding) else: # open an actual file if try_gzip: # gzip.open defaults to mode 'rb' gzfh = try_open_gzip(path) if gzfh is not None: logger.debug('Opening gzip''ed file.') # wrap gzip stream binfh = io.BufferedReader(gzfh) if 'b' not in mode: # add a text wrapper on top logger.debug('Adding text wrapper.') fh = io.TextIOWrapper(binfh, encoding=encoding) else: fh = io.open(path, mode=mode, encoding=encoding) yield_fh = fh if fh is None: yield_fh = binfh try: yield yield_fh finally: # close all open files if fh is not None: # make sure we don't close stdin if fh.fileno() != sys.stdin.fileno(): fh.close() if binfh is not None: binfh.close() if gzfh is not None: gzfh.close()
[ "def", "smart_open_read", "(", "path", "=", "None", ",", "mode", "=", "'rb'", ",", "encoding", "=", "None", ",", "try_gzip", "=", "False", ")", ":", "assert", "mode", "in", "(", "'r'", ",", "'rb'", ")", "assert", "path", "is", "None", "or", "isinstan...
Open a file for reading or return ``stdin``. Adapted from StackOverflow user "Wolph" (http://stackoverflow.com/a/17603000).
[ "Open", "a", "file", "for", "reading", "or", "return", "stdin", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L73-L129
flo-compbio/genometools
genometools/misc/functions.py
smart_open_write
def smart_open_write(path=None, mode='wb', encoding=None): """Open a file for writing or return ``stdout``. Adapted from StackOverflow user "Wolph" (http://stackoverflow.com/a/17603000). """ if path is not None: # open a file fh = io.open(path, mode=mode, encoding=encoding) else: # open stdout fh = io.open(sys.stdout.fileno(), mode=mode, encoding=encoding) #fh = sys.stdout try: yield fh finally: # make sure we don't close stdout if fh.fileno() != sys.stdout.fileno(): fh.close()
python
def smart_open_write(path=None, mode='wb', encoding=None): """Open a file for writing or return ``stdout``. Adapted from StackOverflow user "Wolph" (http://stackoverflow.com/a/17603000). """ if path is not None: # open a file fh = io.open(path, mode=mode, encoding=encoding) else: # open stdout fh = io.open(sys.stdout.fileno(), mode=mode, encoding=encoding) #fh = sys.stdout try: yield fh finally: # make sure we don't close stdout if fh.fileno() != sys.stdout.fileno(): fh.close()
[ "def", "smart_open_write", "(", "path", "=", "None", ",", "mode", "=", "'wb'", ",", "encoding", "=", "None", ")", ":", "if", "path", "is", "not", "None", ":", "# open a file", "fh", "=", "io", ".", "open", "(", "path", ",", "mode", "=", "mode", ","...
Open a file for writing or return ``stdout``. Adapted from StackOverflow user "Wolph" (http://stackoverflow.com/a/17603000).
[ "Open", "a", "file", "for", "writing", "or", "return", "stdout", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L133-L153
flo-compbio/genometools
genometools/misc/functions.py
get_url_size
def get_url_size(url): """Get the size of a URL. Note: Uses requests, so it does not work for FTP URLs. Source: StackOverflow user "Burhan Khalid". (http://stackoverflow.com/a/24585314/5651021) Parameters ---------- url : str The URL. Returns ------- int The size of the URL in bytes. """ r = requests.head(url, headers={'Accept-Encoding': 'identity'}) size = int(r.headers['content-length']) return size
python
def get_url_size(url): """Get the size of a URL. Note: Uses requests, so it does not work for FTP URLs. Source: StackOverflow user "Burhan Khalid". (http://stackoverflow.com/a/24585314/5651021) Parameters ---------- url : str The URL. Returns ------- int The size of the URL in bytes. """ r = requests.head(url, headers={'Accept-Encoding': 'identity'}) size = int(r.headers['content-length']) return size
[ "def", "get_url_size", "(", "url", ")", ":", "r", "=", "requests", ".", "head", "(", "url", ",", "headers", "=", "{", "'Accept-Encoding'", ":", "'identity'", "}", ")", "size", "=", "int", "(", "r", ".", "headers", "[", "'content-length'", "]", ")", "...
Get the size of a URL. Note: Uses requests, so it does not work for FTP URLs. Source: StackOverflow user "Burhan Khalid". (http://stackoverflow.com/a/24585314/5651021) Parameters ---------- url : str The URL. Returns ------- int The size of the URL in bytes.
[ "Get", "the", "size", "of", "a", "URL", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L214-L234
flo-compbio/genometools
genometools/misc/functions.py
get_url_file_name
def get_url_file_name(url): """Get the file name from an url Parameters ---------- url : str Returns ------- str The file name """ assert isinstance(url, (str, _oldstr)) return urlparse.urlparse(url).path.split('/')[-1]
python
def get_url_file_name(url): """Get the file name from an url Parameters ---------- url : str Returns ------- str The file name """ assert isinstance(url, (str, _oldstr)) return urlparse.urlparse(url).path.split('/')[-1]
[ "def", "get_url_file_name", "(", "url", ")", ":", "assert", "isinstance", "(", "url", ",", "(", "str", ",", "_oldstr", ")", ")", "return", "urlparse", ".", "urlparse", "(", "url", ")", ".", "path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]" ...
Get the file name from an url Parameters ---------- url : str Returns ------- str The file name
[ "Get", "the", "file", "name", "from", "an", "url", "Parameters", "----------", "url", ":", "str" ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L237-L251
flo-compbio/genometools
genometools/misc/functions.py
make_sure_dir_exists
def make_sure_dir_exists(dir_, create_subfolders=False): """Ensures that a directory exists. Adapted from StackOverflow users "Bengt" and "Heikki Toivonen" (http://stackoverflow.com/a/5032238). Parameters ---------- dir_: str The directory path. create_subfolders: bool, optional Whether to create any inexistent subfolders. [False] Returns ------- None Raises ------ OSError If a file system error occurs. """ assert isinstance(dir_, (str, _oldstr)) assert isinstance(create_subfolders, bool) try: if create_subfolders: os.makedirs(dir_) else: os.mkdir(dir_) except OSError as exception: if exception.errno != errno.EEXIST: raise
python
def make_sure_dir_exists(dir_, create_subfolders=False): """Ensures that a directory exists. Adapted from StackOverflow users "Bengt" and "Heikki Toivonen" (http://stackoverflow.com/a/5032238). Parameters ---------- dir_: str The directory path. create_subfolders: bool, optional Whether to create any inexistent subfolders. [False] Returns ------- None Raises ------ OSError If a file system error occurs. """ assert isinstance(dir_, (str, _oldstr)) assert isinstance(create_subfolders, bool) try: if create_subfolders: os.makedirs(dir_) else: os.mkdir(dir_) except OSError as exception: if exception.errno != errno.EEXIST: raise
[ "def", "make_sure_dir_exists", "(", "dir_", ",", "create_subfolders", "=", "False", ")", ":", "assert", "isinstance", "(", "dir_", ",", "(", "str", ",", "_oldstr", ")", ")", "assert", "isinstance", "(", "create_subfolders", ",", "bool", ")", "try", ":", "i...
Ensures that a directory exists. Adapted from StackOverflow users "Bengt" and "Heikki Toivonen" (http://stackoverflow.com/a/5032238). Parameters ---------- dir_: str The directory path. create_subfolders: bool, optional Whether to create any inexistent subfolders. [False] Returns ------- None Raises ------ OSError If a file system error occurs.
[ "Ensures", "that", "a", "directory", "exists", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L253-L285
flo-compbio/genometools
genometools/misc/functions.py
get_file_size
def get_file_size(path): """The the size of a file in bytes. Parameters ---------- path: str The path of the file. Returns ------- int The size of the file in bytes. Raises ------ IOError If the file does not exist. OSError If a file system error occurs. """ assert isinstance(path, (str, _oldstr)) if not os.path.isfile(path): raise IOError('File "%s" does not exist.', path) return os.path.getsize(path)
python
def get_file_size(path): """The the size of a file in bytes. Parameters ---------- path: str The path of the file. Returns ------- int The size of the file in bytes. Raises ------ IOError If the file does not exist. OSError If a file system error occurs. """ assert isinstance(path, (str, _oldstr)) if not os.path.isfile(path): raise IOError('File "%s" does not exist.', path) return os.path.getsize(path)
[ "def", "get_file_size", "(", "path", ")", ":", "assert", "isinstance", "(", "path", ",", "(", "str", ",", "_oldstr", ")", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "raise", "IOError", "(", "'File \"%s\" does not exist.'",...
The the size of a file in bytes. Parameters ---------- path: str The path of the file. Returns ------- int The size of the file in bytes. Raises ------ IOError If the file does not exist. OSError If a file system error occurs.
[ "The", "the", "size", "of", "a", "file", "in", "bytes", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L287-L312
flo-compbio/genometools
genometools/misc/functions.py
get_file_checksum
def get_file_checksum(path): """Get the checksum of a file (using ``sum``, Unix-only). This function is only available on certain platforms. Parameters ---------- path: str The path of the file. Returns ------- int The checksum. Raises ------ IOError If the file does not exist. """ if not (sys.platform.startswith('linux') or \ sys.platform in ['darwin', 'cygwin']): raise OSError('This function is not available on your platform.') assert isinstance(path, (str, _oldstr)) if not os.path.isfile(path): # not a file raise IOError('File "%s" does not exist.' %(path)) # calculate checksum sub = subproc.Popen('sum "%s"' %(path), bufsize=-1, shell=True, stdout=subproc.PIPE) stdoutdata = sub.communicate()[0] assert sub.returncode == 0 # in Python 3, communicate() returns bytes that need to be decoded encoding = locale.getpreferredencoding() stdoutstr = str(stdoutdata, encoding=encoding) file_checksum = int(stdoutstr.split(' ')[0]) logger.debug('Checksum of file "%s": %d', path, file_checksum) return file_checksum
python
def get_file_checksum(path): """Get the checksum of a file (using ``sum``, Unix-only). This function is only available on certain platforms. Parameters ---------- path: str The path of the file. Returns ------- int The checksum. Raises ------ IOError If the file does not exist. """ if not (sys.platform.startswith('linux') or \ sys.platform in ['darwin', 'cygwin']): raise OSError('This function is not available on your platform.') assert isinstance(path, (str, _oldstr)) if not os.path.isfile(path): # not a file raise IOError('File "%s" does not exist.' %(path)) # calculate checksum sub = subproc.Popen('sum "%s"' %(path), bufsize=-1, shell=True, stdout=subproc.PIPE) stdoutdata = sub.communicate()[0] assert sub.returncode == 0 # in Python 3, communicate() returns bytes that need to be decoded encoding = locale.getpreferredencoding() stdoutstr = str(stdoutdata, encoding=encoding) file_checksum = int(stdoutstr.split(' ')[0]) logger.debug('Checksum of file "%s": %d', path, file_checksum) return file_checksum
[ "def", "get_file_checksum", "(", "path", ")", ":", "if", "not", "(", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", "or", "sys", ".", "platform", "in", "[", "'darwin'", ",", "'cygwin'", "]", ")", ":", "raise", "OSError", "(", "'This fu...
Get the checksum of a file (using ``sum``, Unix-only). This function is only available on certain platforms. Parameters ---------- path: str The path of the file. Returns ------- int The checksum. Raises ------ IOError If the file does not exist.
[ "Get", "the", "checksum", "of", "a", "file", "(", "using", "sum", "Unix", "-", "only", ")", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L314-L356
flo-compbio/genometools
genometools/misc/functions.py
gzip_open_text
def gzip_open_text(path, encoding=None): """Opens a plain-text file that may be gzip'ed. Parameters ---------- path : str The file. encoding : str, optional The encoding to use. Returns ------- file-like A file-like object. Notes ----- Generally, reading gzip'ed files with gzip.open is very slow, and it is preferable to pipe the file into the python script using ``gunzip -c``. The script then reads the file from stdin. """ if encoding is None: encoding = sys.getdefaultencoding() assert os.path.isfile(path) is_compressed = False try: gzip.open(path, mode='rb').read(1) except IOError: pass else: is_compressed = True if is_compressed: if six.PY2: import codecs zf = gzip.open(path, 'rb') reader = codecs.getreader(encoding) fh = reader(zf) else: fh = gzip.open(path, mode='rt', encoding=encoding) else: # the following works in Python 2.7, thanks to future fh = open(path, mode='r', encoding=encoding) return fh
python
def gzip_open_text(path, encoding=None): """Opens a plain-text file that may be gzip'ed. Parameters ---------- path : str The file. encoding : str, optional The encoding to use. Returns ------- file-like A file-like object. Notes ----- Generally, reading gzip'ed files with gzip.open is very slow, and it is preferable to pipe the file into the python script using ``gunzip -c``. The script then reads the file from stdin. """ if encoding is None: encoding = sys.getdefaultencoding() assert os.path.isfile(path) is_compressed = False try: gzip.open(path, mode='rb').read(1) except IOError: pass else: is_compressed = True if is_compressed: if six.PY2: import codecs zf = gzip.open(path, 'rb') reader = codecs.getreader(encoding) fh = reader(zf) else: fh = gzip.open(path, mode='rt', encoding=encoding) else: # the following works in Python 2.7, thanks to future fh = open(path, mode='r', encoding=encoding) return fh
[ "def", "gzip_open_text", "(", "path", ",", "encoding", "=", "None", ")", ":", "if", "encoding", "is", "None", ":", "encoding", "=", "sys", ".", "getdefaultencoding", "(", ")", "assert", "os", ".", "path", ".", "isfile", "(", "path", ")", "is_compressed",...
Opens a plain-text file that may be gzip'ed. Parameters ---------- path : str The file. encoding : str, optional The encoding to use. Returns ------- file-like A file-like object. Notes ----- Generally, reading gzip'ed files with gzip.open is very slow, and it is preferable to pipe the file into the python script using ``gunzip -c``. The script then reads the file from stdin.
[ "Opens", "a", "plain", "-", "text", "file", "that", "may", "be", "gzip", "ed", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L390-L438
flo-compbio/genometools
genometools/misc/functions.py
bisect_index
def bisect_index(a, x): """ Find the leftmost index of an element in a list using binary search. Parameters ---------- a: list A sorted list. x: arbitrary The element. Returns ------- int The index. """ i = bisect.bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError
python
def bisect_index(a, x): """ Find the leftmost index of an element in a list using binary search. Parameters ---------- a: list A sorted list. x: arbitrary The element. Returns ------- int The index. """ i = bisect.bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError
[ "def", "bisect_index", "(", "a", ",", "x", ")", ":", "i", "=", "bisect", ".", "bisect_left", "(", "a", ",", "x", ")", "if", "i", "!=", "len", "(", "a", ")", "and", "a", "[", "i", "]", "==", "x", ":", "return", "i", "raise", "ValueError" ]
Find the leftmost index of an element in a list using binary search. Parameters ---------- a: list A sorted list. x: arbitrary The element. Returns ------- int The index.
[ "Find", "the", "leftmost", "index", "of", "an", "element", "in", "a", "list", "using", "binary", "search", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L470-L489
flo-compbio/genometools
genometools/misc/functions.py
read_single
def read_single(path, encoding = 'UTF-8'): """ Reads the first column of a tab-delimited text file. The file can either be uncompressed or gzip'ed. Parameters ---------- path: str The path of the file. enc: str The file encoding. Returns ------- List of str A list containing the elements in the first column. """ assert isinstance(path, (str, _oldstr)) data = [] with smart_open_read(path, mode='rb', try_gzip=True) as fh: reader = csv.reader(fh, dialect='excel-tab', encoding=encoding) for l in reader: data.append(l[0]) return data
python
def read_single(path, encoding = 'UTF-8'): """ Reads the first column of a tab-delimited text file. The file can either be uncompressed or gzip'ed. Parameters ---------- path: str The path of the file. enc: str The file encoding. Returns ------- List of str A list containing the elements in the first column. """ assert isinstance(path, (str, _oldstr)) data = [] with smart_open_read(path, mode='rb', try_gzip=True) as fh: reader = csv.reader(fh, dialect='excel-tab', encoding=encoding) for l in reader: data.append(l[0]) return data
[ "def", "read_single", "(", "path", ",", "encoding", "=", "'UTF-8'", ")", ":", "assert", "isinstance", "(", "path", ",", "(", "str", ",", "_oldstr", ")", ")", "data", "=", "[", "]", "with", "smart_open_read", "(", "path", ",", "mode", "=", "'rb'", ","...
Reads the first column of a tab-delimited text file. The file can either be uncompressed or gzip'ed. Parameters ---------- path: str The path of the file. enc: str The file encoding. Returns ------- List of str A list containing the elements in the first column.
[ "Reads", "the", "first", "column", "of", "a", "tab", "-", "delimited", "text", "file", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/functions.py#L548-L572
flo-compbio/genometools
genometools/gcloud/compute/network.py
add_tcp_firewall_rule
def add_tcp_firewall_rule(project, access_token, name, tag, port): """Adds a TCP firewall rule. TODO: docstring""" headers = { 'Authorization': 'Bearer %s' % access_token.access_token } payload = { "name": name, "kind": "compute#firewall", "sourceRanges": [ "0.0.0.0/0" ], "targetTags": [ tag ], "allowed": [ { "IPProtocol": "tcp", "ports": [ str(port), ] } ], "network": "projects/%s/global/networks/default" % project } r = requests.post('https://www.googleapis.com/compute/v1/' 'projects/%s/global/firewalls' % project, headers=headers, json=payload) r.raise_for_status() op = r.json()['name'] LOGGER.info('Requested to add firewall rule for tag "%s" ' '(operation "%s")...', tag, op) return op
python
def add_tcp_firewall_rule(project, access_token, name, tag, port): """Adds a TCP firewall rule. TODO: docstring""" headers = { 'Authorization': 'Bearer %s' % access_token.access_token } payload = { "name": name, "kind": "compute#firewall", "sourceRanges": [ "0.0.0.0/0" ], "targetTags": [ tag ], "allowed": [ { "IPProtocol": "tcp", "ports": [ str(port), ] } ], "network": "projects/%s/global/networks/default" % project } r = requests.post('https://www.googleapis.com/compute/v1/' 'projects/%s/global/firewalls' % project, headers=headers, json=payload) r.raise_for_status() op = r.json()['name'] LOGGER.info('Requested to add firewall rule for tag "%s" ' '(operation "%s")...', tag, op) return op
[ "def", "add_tcp_firewall_rule", "(", "project", ",", "access_token", ",", "name", ",", "tag", ",", "port", ")", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer %s'", "%", "access_token", ".", "access_token", "}", "payload", "=", "{", "\"name\"", "...
Adds a TCP firewall rule. TODO: docstring
[ "Adds", "a", "TCP", "firewall", "rule", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/compute/network.py#L8-L35
cebel/pyuniprot
src/pyuniprot/cli.py
update
def update(taxids, conn, force_download, silent): """Update local UniProt database""" if not silent: click.secho("WARNING: Update is very time consuming and can take several " "hours depending which organisms you are importing!", fg="yellow") if not taxids: click.echo("Please note that you can restrict import to organisms by " "NCBI taxonomy IDs") click.echo("Example (human, mouse, rat):\n") click.secho("\tpyuniprot update --taxids 9606,10090,10116\n\n", fg="green") if taxids: taxids = [int(taxid.strip()) for taxid in taxids.strip().split(',') if re.search('^ *\d+ *$', taxid)] database.update(taxids=taxids, connection=conn, force_download=force_download, silent=silent)
python
def update(taxids, conn, force_download, silent): """Update local UniProt database""" if not silent: click.secho("WARNING: Update is very time consuming and can take several " "hours depending which organisms you are importing!", fg="yellow") if not taxids: click.echo("Please note that you can restrict import to organisms by " "NCBI taxonomy IDs") click.echo("Example (human, mouse, rat):\n") click.secho("\tpyuniprot update --taxids 9606,10090,10116\n\n", fg="green") if taxids: taxids = [int(taxid.strip()) for taxid in taxids.strip().split(',') if re.search('^ *\d+ *$', taxid)] database.update(taxids=taxids, connection=conn, force_download=force_download, silent=silent)
[ "def", "update", "(", "taxids", ",", "conn", ",", "force_download", ",", "silent", ")", ":", "if", "not", "silent", ":", "click", ".", "secho", "(", "\"WARNING: Update is very time consuming and can take several \"", "\"hours depending which organisms you are importing!\"",...
Update local UniProt database
[ "Update", "local", "UniProt", "database" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/cli.py#L57-L72
cebel/pyuniprot
src/pyuniprot/cli.py
web
def web(host, port): """Start web application""" from .webserver.web import get_app get_app().run(host=host, port=port)
python
def web(host, port): """Start web application""" from .webserver.web import get_app get_app().run(host=host, port=port)
[ "def", "web", "(", "host", ",", "port", ")", ":", "from", ".", "webserver", ".", "web", "import", "get_app", "get_app", "(", ")", ".", "run", "(", "host", "=", "host", ",", "port", "=", "port", ")" ]
Start web application
[ "Start", "web", "application" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/cli.py#L99-L102
cebel/pyuniprot
src/pyuniprot/cli.py
connection
def connection(connection, without_connection_test): """Set MySQL/MariaDB connection""" database.set_connection(connection=connection) if not without_connection_test: test_connection(connection)
python
def connection(connection, without_connection_test): """Set MySQL/MariaDB connection""" database.set_connection(connection=connection) if not without_connection_test: test_connection(connection)
[ "def", "connection", "(", "connection", ",", "without_connection_test", ")", ":", "database", ".", "set_connection", "(", "connection", "=", "connection", ")", "if", "not", "without_connection_test", ":", "test_connection", "(", "connection", ")" ]
Set MySQL/MariaDB connection
[ "Set", "MySQL", "/", "MariaDB", "connection" ]
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/cli.py#L108-L113
acorg/dark-matter
dark/blast/params.py
checkCompatibleParams
def checkCompatibleParams(initialParams, laterParams): """ Check a later set of BLAST parameters against those originally found. @param initialParams: A C{dict} with the originally encountered BLAST parameter settings. @param laterParams: A C{dict} with BLAST parameter settings encountered later. @return: A C{str} summary of the parameter differences if the parameter sets differ, else C{None}. """ # Note that although the params contains a 'date', its value is empty # (as far as I've seen). This could become an issue one day if it # becomes non-empty and differs between JSON files that we cat # together. In that case we may need to be more specific in our params # compatible checking. err = [] for param in initialParams: if param in laterParams: if (param not in VARIABLE_PARAMS and initialParams[param] != laterParams[param]): err.append( '\tParam %r initial value %r differs from ' 'later value %r' % (param, initialParams[param], laterParams[param])) else: err.append('\t%r found in initial parameters, not found ' 'in later parameters' % param) for param in laterParams: if param not in initialParams: err.append('\t%r found in later parameters, not seen in ' 'initial parameters' % param) return 'Summary of differences:\n%s' % '\n'.join(err) if err else None
python
def checkCompatibleParams(initialParams, laterParams): """ Check a later set of BLAST parameters against those originally found. @param initialParams: A C{dict} with the originally encountered BLAST parameter settings. @param laterParams: A C{dict} with BLAST parameter settings encountered later. @return: A C{str} summary of the parameter differences if the parameter sets differ, else C{None}. """ # Note that although the params contains a 'date', its value is empty # (as far as I've seen). This could become an issue one day if it # becomes non-empty and differs between JSON files that we cat # together. In that case we may need to be more specific in our params # compatible checking. err = [] for param in initialParams: if param in laterParams: if (param not in VARIABLE_PARAMS and initialParams[param] != laterParams[param]): err.append( '\tParam %r initial value %r differs from ' 'later value %r' % (param, initialParams[param], laterParams[param])) else: err.append('\t%r found in initial parameters, not found ' 'in later parameters' % param) for param in laterParams: if param not in initialParams: err.append('\t%r found in later parameters, not seen in ' 'initial parameters' % param) return 'Summary of differences:\n%s' % '\n'.join(err) if err else None
[ "def", "checkCompatibleParams", "(", "initialParams", ",", "laterParams", ")", ":", "# Note that although the params contains a 'date', its value is empty", "# (as far as I've seen). This could become an issue one day if it", "# becomes non-empty and differs between JSON files that we cat", "#...
Check a later set of BLAST parameters against those originally found. @param initialParams: A C{dict} with the originally encountered BLAST parameter settings. @param laterParams: A C{dict} with BLAST parameter settings encountered later. @return: A C{str} summary of the parameter differences if the parameter sets differ, else C{None}.
[ "Check", "a", "later", "set", "of", "BLAST", "parameters", "against", "those", "originally", "found", "." ]
train
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/params.py#L12-L46
flo-compbio/genometools
genometools/basic/gene_set.py
GeneSet.to_list
def to_list(self): """Converts the GeneSet object to a flat list of strings. Note: see also :meth:`from_list`. Parameters ---------- Returns ------- list of str The data from the GeneSet object as a flat list. """ src = self._source or '' coll = self._collection or '' desc = self._description or '' l = [self._id, src, coll, self._name, ','.join(sorted(self._genes)), desc] return l
python
def to_list(self): """Converts the GeneSet object to a flat list of strings. Note: see also :meth:`from_list`. Parameters ---------- Returns ------- list of str The data from the GeneSet object as a flat list. """ src = self._source or '' coll = self._collection or '' desc = self._description or '' l = [self._id, src, coll, self._name, ','.join(sorted(self._genes)), desc] return l
[ "def", "to_list", "(", "self", ")", ":", "src", "=", "self", ".", "_source", "or", "''", "coll", "=", "self", ".", "_collection", "or", "''", "desc", "=", "self", ".", "_description", "or", "''", "l", "=", "[", "self", ".", "_id", ",", "src", ","...
Converts the GeneSet object to a flat list of strings. Note: see also :meth:`from_list`. Parameters ---------- Returns ------- list of str The data from the GeneSet object as a flat list.
[ "Converts", "the", "GeneSet", "object", "to", "a", "flat", "list", "of", "strings", "." ]
train
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/basic/gene_set.py#L165-L184