code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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,...
def read_sparse(cls, file_path: str)
Read a sparse representation from a tab-delimited text file. TODO: docstring
2.905541
2.770621
1.048697
_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' % prefi...
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
2.148445
2.119383
1.013712
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, ...
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 f...
2.969509
3.013604
0.985368
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 ...
def check_chain(chain)
Verify a merkle chain to see if the Merkle root can be reproduced.
2.967644
2.677709
1.108277
return codecs.encode(check_chain([(codecs.decode(i[0], 'hex_codec'), i[1]) for i in chain]), 'hex_codec')
def check_hex_chain(chain)
Verify a merkle chain, with hashes hex encoded, to see if the Merkle root can be reproduced.
5.62314
4.564363
1.231966
self.leaves.append(Node(codecs.decode(value, 'hex_codec'), prehashed=True))
def add_hash(self, value)
Add a Node based on a precomputed, hex encoded, hash value.
12.582748
7.882706
1.596247
self.root = None for leaf in self.leaves: leaf.p, leaf.sib, leaf.side = (None, ) * 3
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 ...
11.361009
7.808292
1.454993
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_fu...
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.
4.667953
3.639081
1.282728
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....
def _build(self, leaves)
Private helper function to create the next aggregation level and put all references in place.
2.782431
2.657649
1.046952
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)
Assemble and return the chain leading from a given node to the merkle root of this tree.
4.085468
3.934052
1.038489
return [self.get_chain(i) for i in range(len(self.leaves))]
def get_all_chains(self)
Assemble and return a list of all chains for all leaf nodes to the merkle root.
5.456807
3.091251
1.765242
return [(codecs.encode(i[0], 'hex_codec'), i[1]) for i in self.get_chain(index)]
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
5.157916
5.07471
1.016396
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)
Assemble and return a list of all chains for all nodes to the merkle root, hex encoded.
4.855982
4.252654
1.141871
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)) subt...
def _get_whole_subtrees(self)
Returns an array of nodes in the tree that have balanced subtrees beneath them, moving from left to right.
3.081178
2.7682
1.113062
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, ...
def add_adjust(self, data, prehashed=False)
Add a new leaf, and adjust the tree, without rebuilding the whole thing.
3.094433
2.82604
1.094971
expected = self.K * (self.n/float(self.N)) return self.k / expected
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.
15.02685
12.674497
1.185597
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: ...
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 t...
3.406607
3.166561
1.075806
reads = FastaReads(fastaFilename) blastReadsAlignments = BlastReadsAlignments(reads, recordFilenames) filtered = blastReadsAlignments.filter(whitelist=set([title]), negativeTitleRegex='.') titlesAlignments = TitlesAlignments(filtered) if title not in ...
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...
3.423365
3.574873
0.957618
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)
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(_fetc...
2.065499
2.159491
0.956475
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...
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` ...
2.507235
2.459257
1.019509
apikey = os.environ.get("NCBI_API_KEY") if apikey: url += "&api_key={apikey}".format(apikey=apikey) return url
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
2.665385
2.841957
0.937869
''' CONTENT == tuple of non-sparse values ''' @always_comb def read(): dout.next = CONTENT[int(addr)] return read
def rom(addr, dout, CONTENT)
CONTENT == tuple of non-sparse values
13.660092
7.695675
1.775035
''' 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)
RAM: Single-Port, Asynchronous Read
3.846531
3.339586
1.151799
''' 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)
RAM: Simple-Dual-Port, Read-First
5.009535
3.983195
1.257668
''' 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: ...
def ram_dp_rf(clka, clkb, wea, web, addra, addrb, dia, dib, doa, dob)
RAM: Dual-Port, Read-First
3.266864
3.045406
1.072719
''' 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))
Convert ROM
4.240197
4.292175
0.98789
''' 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)
Convert RAM: Single-Port, Read-First
3.122067
2.603705
1.199086
''' 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)
Convert RAM: Single-Port, Write-First
3.157034
2.578049
1.224583
''' 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)
Convert RAM: Single-Port, Asynchronous Read
3.302594
2.594547
1.272898
''' 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, ...
def convert_ram_sdp_rf(ADDR_WIDTH=8, DATA_WIDTH=8)
Convert RAM: Simple-Dual-Port, Read-First
3.128492
2.543439
1.230024
''' 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,...
def convert_ram_sdp_wf(ADDR_WIDTH=8, DATA_WIDTH=8)
Convert RAM: Simple-Dual-Port, Write-First
3.126171
2.538168
1.231665
''' 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...
def convert_ram_sdp_ar(ADDR_WIDTH=8, DATA_WIDTH=8)
Convert RAM: Simple-Dual-Port, Asynchronous Read
3.183099
2.539987
1.253195
''' 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...
def convert_ram_dp_ar(ADDR_WIDTH=8, DATA_WIDTH=8)
Convert RAM: Dual-Port, Asynchronous Read
2.351377
2.099118
1.120174
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) ...
def post_to_twitter(self, message=None)
Update twitter status, i.e., post a tweet
2.368004
2.368075
0.99997
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 re...
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.
5.462505
6.713616
0.813646
from scipy.ndimage.interpolation import shift return shift(im, map(lambda x: -x, self.delta), mode='nearest')
def apply(self, im)
Apply an n-dimensional displacement by shifting an image or volume. Parameters ---------- im : ndarray The image or volume to shift
6.16823
11.529823
0.53498
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 ind...
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 ...
5.478985
5.605196
0.977483
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)
Finds optimal displacements localized along an axis
5.347695
5.08781
1.05108
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) retur...
def apply(self, im)
Apply axis-localized displacements. Parameters ---------- im : ndarray The image or volume to shift
3.887159
4.691864
0.828489
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 c...
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 ...
1.872772
1.746824
1.072101
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...
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 ...
2.423978
2.409489
1.006013
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)
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.
2.872159
2.934621
0.978716
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)
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.
2.627096
2.872003
0.914726
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=%...
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 ...
4.729101
4.535634
1.042655
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']] ...
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}.
4.77493
3.156522
1.512719
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)
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.
4.132473
3.854507
1.072115
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, m...
def DosDateTimeToTimeTuple(dosDateTime)
Convert an MS-DOS format date time to a Python time tuple.
1.869158
1.811082
1.032067
effectiveDbSize = ( (dbSize - dbSequenceCount * lengthAdjustment) * (queryLength - lengthAdjustment) ) return effectiveDbSize * (2.0 ** (-1.0 * bitScore))
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 query...
5.073643
6.612438
0.767288
effectiveDbSize = ( (dbSize - dbSequenceCount * lengthAdjustment) * (queryLength - lengthAdjustment) ) return -1.0 * (log(eValue / effectiveDbSize) / _LOG2)
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 queryLeng...
5.155477
7.781071
0.662567
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 ...
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 st...
2.395905
2.289998
1.046248
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)
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}.
3.814353
3.225693
1.182491
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 ...
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...
3.719936
3.583326
1.038124
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 += ' ({...
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:
4.204842
4.464473
0.941845
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_shor...
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. ...
2.381019
2.650614
0.898289
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 = m...
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....
2.798203
2.667421
1.04903
result = _Base.toDict(self) result['score'] = self.score.score return result
def toDict(self)
Get information about the HSP as a dictionary. @return: A C{dict} representation of the HSP.
7.804825
8.681642
0.899003
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()) parser.add_argument( '-s', '--species', type=str, choices=sorted(ensembl.SPECIES_CHROMPAT....
def get_argument_parser()
Returns an argument parser object for the script.
3.153215
3.115187
1.012207
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...
def main(args=None)
Script body.
3.861693
3.882966
0.994521
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)
ErrorMiddleware returns hard-coded content-type text/html. Here we force it to be application/json.
3.872367
3.14435
1.231532
# 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...
def make_app(global_conf, **app_conf)
Create a WSGI application and return it ``global_conf`` The inherited configuration for this application. Normally from the [DEFAULT] section of the Paste ini file. ``app_conf`` The application's local configuration. Normally specified in the [app:<name>] section of the Paste i...
5.906558
6.385227
0.925035
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...
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.845207
2.694358
1.055987
match = dnaMatch['match'] identicalMatchCount = match['identicalMatchCount'] ambiguousMatchCount = match['ambiguousMatchCount'] gapMismatchCount = match['gapMismatchCount'] gapGapMismatchCount = match['gapGapMismatchCount'] nonGapMismatchCount = match['nonGapMismatchCount'] if offsets:...
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 ar...
2.380488
2.400735
0.991566
identicalMatchCount = ambiguousMatchCount = 0 gapMismatchCount = nonGapMismatchCount = gapGapMismatchCount = 0 read1ExtraCount = read2ExtraCount = 0 read1GapOffsets = [] read2GapOffsets = [] read1AmbiguousOffsets = [] read2AmbiguousOffsets = [] empty = set() def _identicalMatch...
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 scor...
2.239887
2.213843
1.011764
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': ...
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 ac...
2.966254
2.757936
1.075534
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 #...
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 ...
3.839148
3.692118
1.039823
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)
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}. ...
9.796693
10.403144
0.941705
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: pr...
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{color...
2.381288
2.111253
1.127903
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)
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.
3.341651
3.734157
0.894888
result = [] if matchAmbiguous: result.append('nucleotides plus the number of ambiguously matching ' 'nucleotides.') else: result.append('nucleotides.') result.append() if showLengths or showGaps or showNs or matchAmbiguous or not concise: result....
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. @par...
2.900011
2.657542
1.091238
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: ...
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 ...
3.277799
3.232717
1.013945
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='...
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 ta...
2.991355
2.991419
0.999979
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 k...
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.
2.236213
2.353017
0.95036
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_...
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)
2.123238
2.079538
1.021014
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_...
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)
2.025706
1.987839
1.019049
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: ...
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)
2.069874
2.050186
1.009603
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: ...
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)
2.032315
1.989925
1.021302
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 = Sign...
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 ...
3.392533
3.337729
1.01642
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 = Sign...
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...
3.594328
3.599083
0.998679
with open(path, 'rb') as fh: h = str(hashlib.md5(fh.read()).hexdigest()) return h
def get_file_md5sum(path)
Calculate the MD5 hash for a file.
3.065634
2.980263
1.028645
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: ...
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).
2.892778
2.931153
0.986908
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...
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).
2.739126
3.305869
0.828565
r = requests.head(url, headers={'Accept-Encoding': 'identity'}) size = int(r.headers['content-length']) return 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.
2.638475
3.201633
0.824103
assert isinstance(url, (str, _oldstr)) return urlparse.urlparse(url).path.split('/')[-1]
def get_url_file_name(url)
Get the file name from an url Parameters ---------- url : str Returns ------- str The file name
7.048747
8.462541
0.832935
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)
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] ...
2.55353
3.080615
0.828903
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)
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.
4.17428
5.310442
0.786051
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" do...
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.
3.813938
3.737925
1.020336
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 ...
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,...
2.798813
2.960355
0.945432
i = bisect.bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError
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.
1.798989
2.906211
0.619015
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')
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...
4.97324
5.304985
0.937465
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), ] } ],...
def add_tcp_firewall_rule(project, access_token, name, tag, port)
Adds a TCP firewall rule. TODO: docstring
2.341675
2.356663
0.99364
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 " ...
def update(taxids, conn, force_download, silent)
Update local UniProt database
4.698131
4.397506
1.068363
from .webserver.web import get_app get_app().run(host=host, port=port)
def web(host, port)
Start web application
5.722502
6.076243
0.941783
database.set_connection(connection=connection) if not without_connection_test: test_connection(connection)
def connection(connection, without_connection_test)
Set MySQL/MariaDB connection
5.035047
5.354592
0.940323
# 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. ...
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 differenc...
4.863316
4.842925
1.00421
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)
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.
7.241364
6.342672
1.14169
id_ = l[0] name = l[3] genes = l[4].split(',') src = l[1] or None coll = l[2] or None desc = l[5] or None return cls(id_, name, genes, src, coll, desc)
def from_list(cls, l)
Generate an GeneSet object from a list of strings. Note: See also :meth:`to_list`. Parameters ---------- l: list or tuple of str A list of strings representing gene set ID, name, genes, source, collection, and description. The genes must be comma-sep...
3.934135
3.013084
1.305684
offsets = [] seq = seq.upper() primer = primer.upper() primerLen = len(primer) discarded = 0 offset = seq.find(primer) while offset > -1: offsets.append(discarded + offset) seq = seq[offset + primerLen:] discarded += offset + primerLen offset = seq.find(...
def findPrimer(primer, seq)
Look for a primer sequence. @param primer: A C{str} primer sequence. @param seq: A BioPython C{Bio.Seq} sequence. @return: A C{list} of zero-based offsets into the sequence at which the primer can be found. If no instances are found, return an empty C{list}.
2.688977
3.008914
0.89367
# Note that we reverse complement the primer to find the reverse # matches. This is much simpler than reverse complementing the sequence # because it allows us to use findPrimer and to deal with overlapping # matches correctly. forward = findPrimer(primer, seq) reverse = findPrimer(reverse_...
def findPrimerBidi(primer, seq)
Look for a primer in a sequence and its reverse complement. @param primer: A C{str} primer sequence. @param seq: A BioPython C{Bio.Seq} sequence. @return: A C{tuple} of two lists. The first contains (zero-based) ascending offsets into the sequence at which the primer can be found. The seco...
6.074802
6.913578
0.878677
forward, reverse = findPrimerBidi(primer, seq) if forward: start = forward[-1] + len(primer) end = len(seq) for offset in reverse: if offset >= start: end = offset break else: start = 0 end = reverse[0] if reverse else ...
def findPrimerBidiLimits(primer, seq)
Report the extreme (inner) offsets of primer in a sequence and its reverse complement. @param primer: A C{str} primer sequence. @param seq: A BioPython C{Bio.Seq} sequence. @return: A C{tuple} of two C{int} offsets. The first is a (zero-based) offset into the sequence that is beyond the first ...
2.98639
3.220836
0.927209
def numericPrefix(name): count = 0 for ch in name: if ch in string.digits: count += 1 else: break return 0 if count == 0 else int(name[0:count]) return sorted(names, key=lambda name: numericPrefix(basename(name)))
def numericallySortFilenames(names)
Sort (ascending) a list of file names by their numerical prefixes. The number sorted on is the numeric prefix of the basename of the given filename. E.g., '../output/1.json.bz2' will sort before '../output/10.json.bz2'. @param: A C{list} of file names, each of whose basename starts with a strin...
3.700717
3.88903
0.951579