code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' return one item ''' try: items = [item for item in self._get_with_criteria(criteria, limit=1)] return items[0] except: return None
def get_one(self, criteria)
return one item
5.761514
5.501992
1.047169
''' perform autocommit ''' # commit() self._commit_counter += 1 # autocommit as boolean if isinstance(self._autocommit, bool) and self._autocommit: self.commit() self._commit_counter = 0 # autocommit as counter elif isinstance(self...
def _do_autocommit(self)
perform autocommit
2.860395
2.818394
1.014902
''' store item in sqlite database ''' if isinstance(item, self._item_class): self._put_one(item) elif isinstance(item, (list, tuple)): self._put_many(item) else: raise RuntimeError('Unknown item(s) type, %s' % type(item))
def put(self, item)
store item in sqlite database
3.97412
3.721147
1.067983
''' store one item in database ''' # prepare values values = [] for k, v in item.items(): if k == '_id': continue if 'dblite_serializer' in item.fields[k]: serializer = item.fields[k]['dblite_serializer'] v =...
def _put_one(self, item)
store one item in database
3.080457
3.051344
1.009541
''' store items in sqlite database ''' for item in items: if not isinstance(item, self._item_class): raise RuntimeError('Items mismatch for %s and %s' % (self._item_class, type(item))) self._put_one(item)
def _put_many(self, items)
store items in sqlite database
4.97017
4.349788
1.142624
''' execute sql request and return items ''' def _items(items): for item in items: yield self._item_class(item) sql = sql.strip() try: self._cursor.execute(sql, params) except sqlite3.OperationalError, err: raise SQLErr...
def sql(self, sql, params=())
execute sql request and return items
3.252424
3.071307
1.05897
''' delete dictionary(ies) in sqlite database _all = True - delete all items ''' if isinstance(criteria, self._item_class): criteria = {'_id': criteria['_id']} if criteria is None and not _all: raise RuntimeError('Criteria is not defined') SQL =...
def delete(self, criteria=None, _all=False)
delete dictionary(ies) in sqlite database _all = True - delete all items
6.56806
4.609684
1.424839
futures = set() if use_processes: get_executor = concurrent.futures.ProcessPoolExecutor else: get_executor = concurrent.futures.ThreadPoolExecutor with get_executor(max_workers) as executor: def execute(function, name): future = executor.submit(fun...
def run_tasks(tasks, max_workers=None, use_processes=False)
Run an iterable of tasks. tasks: The iterable of tasks max_workers: (optional, None) The maximum number of workers to use. As of Python 3.5, if None is passed to the thread executor will default to 5 * the number of processors and the process executor will default to the number of proce...
2.494411
2.632984
0.94737
assert isinstance(interval, (int, float)) assert interval >= 0.1 status = 'RUNNING' progress = 0 LOGGER.info('Waiting for zone operation "%s" to finish...', name) while status != 'DONE': # print('\rRunning! Progress: %d %%' % progress, end='') r = requests.get('http...
def wait_for_zone_op(access_token, project, zone, name, interval=1.0)
Wait until a zone operation is finished. TODO: docstring
2.705809
2.694823
1.004077
d = {'score': 0, 'pointer': None, 'ins': 0, 'del': 0} cols = len(self.seq1Seq) + 1 rows = len(self.seq2Seq) + 1 # Note that this puts a ref to the same dict (d) into each cell of # the table. Hopefully that is what was intended. Eyeballing the # code below that u...
def _initialise(self)
Initialises table with dictionary.
9.557365
8.590152
1.112596
cigar = [] count = 0 align1 = output[0] align2 = output[2] for nt1, nt2 in zip(align1, align2): if nt1 == nt2: cigar.append('=') elif nt1 == '-': cigar.append('I') elif nt2 == '-': cigar....
def _cigarString(self, output)
Return a cigar string of aligned sequences. @param output: a C{tup} of strings (align1, align, align2) @return: a C{str} containing the cigar string. Eg with input: 'GGCCCGCA' and 'GG-CTGCA', return 2=1D1=1X3=
3.220034
3.120803
1.031797
if result is None: return ('\nNo alignment between %s and %s\n' % ( self.seq1ID, self.seq2ID)) else: header = ( '\nCigar string of aligned region: %s\n' '%s Match start: %d Match end: %d\n' '%s Match start: ...
def _alignmentToStr(self, result)
Make a textual representation of an alignment result. @param result: A C{dict}, as returned by C{self.createAlignment}. @return: A C{str} desription of a result. For every three lines the first and third contain the input sequences, possibly padded with '-'. The second contains ...
3.393359
2.802169
1.210976
table = self._initialise() alignment = self._fillAndTraceback(table) output = alignment[0] if output[0] == '' or output[2] == '': result = None else: indexes = alignment[1] result = { 'cigar': self._cigarString(output),...
def createAlignment(self, resultFormat=dict)
Run the alignment algorithm. @param resultFormat: Either C{dict} or C{str}, giving the desired result format. @return: If C{resultFormat} is C{dict}, a C{dict} containing information about the match (or C{None}) if there is no match. If C{resultFormat} is C{str}, a C...
4.868144
4.230285
1.150784
''' return SELECT SQL ''' # base SQL SQL = 'SELECT %s FROM %s' % (','.join(fields), self._table) # selectors if self._selectors: SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip() # modifiers if self._modifiers: ...
def select(self, fields=['rowid', '*'], offset=None, limit=None)
return SELECT SQL
2.808371
2.726012
1.030212
''' return DELETE SQL ''' SQL = 'DELETE FROM %s' % self._table if self._selectors: SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip() return SQL
def delete(self)
return DELETE SQL
8.611515
6.495565
1.325753
''' parse parameters and return SQL ''' if not isinstance(params, dict): return None, None if len(params) == 0: return None, None selectors = list() modifiers = list() for k in params.keys(): if k in LOGICAL_OPERATO...
def _parse(self, params)
parse parameters and return SQL
3.031506
2.896636
1.046561
''' $and: joins query clauses with a logical AND returns all items that match the conditions of both clauses $or: joins query clauses with a logical OR returns all items that match the conditions of either clause. ''' result = list() ...
def _logical(self, operator, params)
$and: joins query clauses with a logical AND returns all items that match the conditions of both clauses $or: joins query clauses with a logical OR returns all items that match the conditions of either clause.
3.54208
2.366043
1.497048
''' $orderby: sorts the results of a query in ascending (1) or descending (-1) order. ''' if operator == '$orderby': order_types = {-1: 'DESC', 1: 'ASC'} if not isinstance(params, dict): raise RuntimeError('Incorrect parameter type, %s' % param...
def _modifier(self, operator, params)
$orderby: sorts the results of a query in ascending (1) or descending (-1) order.
4.824964
3.327199
1.450158
''' wrapper for values ''' if isinstance(value, (int, float,)): return '=%s' % value elif isinstance(value, (str, unicode)): value = value.strip() # LIKE if RE_LIKE.match(value): return ' LIKE %s' % repr(RE_LIKE.match(value...
def _value_wrapper(self, value)
wrapper for values
3.129648
3.127591
1.000658
routes = [] for routing in routings: methods, regex, app = routing[:3] if isinstance(methods, basestring): methods = (methods,) vars = routing[3] if len(routing) >= 4 else {} routes.append((methods, re.compile(unicode(regex)), app, vars)) def router(environ,...
def make_router(*routings)
Return a WSGI application that dispatches requests to controllers
2.609405
2.54268
1.026242
# uri = uri if isinstance(uri, ParseResult) else urlparse(uri) if not uri.scheme: raise ValueError("uri has no scheme: " + uri) f = _connect_fns.get(uri.scheme.lower(), None) if not f: err = "No connect function registered for scheme `%s`" % uri.scheme raise Exception(er...
def connect(uri)
Connects to an nREPL endpoint identified by the given URL/URI. Valid examples include: nrepl://192.168.0.12:7889 telnet://localhost:5000 http://your-app-name.heroku.com/repl This fn delegates to another looked up in that dispatches on the scheme of the URI provided (which can be a stri...
3.612591
3.500056
1.032152
if hasattr(criteria, '__call__'): pred = criteria else: pred = lambda incoming: _match_criteria(criteria, incoming) with self._watches_lock: self._watches[key] = (pred, callback)
def watch(self, key, criteria, callback)
Registers a new watch under [key] (which can be used with `unwatch()` to remove the watch) that filters messages using [criteria] (may be a predicate or a 'criteria dict' [see the README for more info there]). Matching messages are passed to [callback], which must accept three arguments:...
4.107218
3.904495
1.05192
if isinstance(data, collections.Mapping): # Remove null properties as recommended by Google JSON Style Guide. data = type(data)( (name, value) for name, value in data.iteritems() if value is not None ) error = data.get('error') if ...
def respond_json(ctx, data, code = None, headers = [], json_dumps_default = None, jsonp = None)
Return a JSON response. This function is optimized for JSON following `Google JSON Style Guide <http://google-styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml>`_, but will handle any JSON except for HTTP errors.
2.46436
2.414934
1.020467
global rar_executable_cached if rar_executable_cached is None: for command in ('unrar', 'rar'): try: subprocess.Popen([command], stdout=subprocess.PIPE) rar_executable_cached = command break except OSError: pass...
def call_unrar(params)
Calls rar/unrar command line executable, returns stdout pipe
3.039844
2.913275
1.043446
return [ n.replace(".json.gz", "") for n in pkg_resources.resource_listdir(__name__, _assy_dir) if n.endswith(".json.gz") ]
def get_assembly_names()
return list of available assemblies >>> assy_names = get_assembly_names() >>> 'GRCh37.p13' in assy_names True
5.398615
5.466826
0.987523
fn = pkg_resources.resource_filename( __name__, _assy_path_fmt.format(name=name)) return json.load(gzip.open(fn, mode="rt", encoding="utf-8"))
def get_assembly(name)
read a single assembly by name, returning a dictionary of assembly data >>> assy = get_assembly('GRCh37.p13') >>> assy['name'] 'GRCh37.p13' >>> assy['description'] 'Genome Reference Consortium Human Build 37 patch release 13 (GRCh37.p13)' >>> assy['refseq_ac'] 'GCF_000001405.25' >>>...
4.799896
5.445418
0.881456
if names == []: names = get_assembly_names() return {a['name']: a for a in (get_assembly(n) for n in names)}
def get_assemblies(names=[])
read specified assemblies, or all if none specified, returning a dictionary of assembly-name: assembly. See get_assembly() function for the structure of assembly data. >>> assemblies = get_assemblies(names=['GRCh37.p13']) >>> assy = assemblies['GRCh37.p13'] >>> assemblies = get_assemblies() >...
3.748496
4.029341
0.9303
return { s['name']: s['refseq_ac'] for s in get_assembly(assy_name)['sequences'] if (not primary_only or _is_primary(s)) }
def make_name_ac_map(assy_name, primary_only=False)
make map from sequence name to accession for given assembly name >>> grch38p5_name_ac_map = make_name_ac_map('GRCh38.p5') >>> grch38p5_name_ac_map['1'] 'NC_000001.11'
4.445643
5.87237
0.757044
return { s['refseq_ac']: s['name'] for s in get_assembly(assy_name)['sequences'] if (not primary_only or _is_primary(s)) }
def make_ac_name_map(assy_name, primary_only=False)
make map from accession (str) to sequence name (str) for given assembly name >>> grch38p5_ac_name_map = make_ac_name_map('GRCh38.p5') >>> grch38p5_ac_name_map['NC_000001.11'] '1'
4.656339
5.843079
0.796898
if args is None: parser = get_argument_parser() args = parser.parse_args() input_file = args.annotation_file output_file = args.output_file species = args.species chrom_pat = args.chromosome_pattern field_name = args.field_name log_file = args.log_file quiet = arg...
def main(args=None)
Extract all exon annotations of protein-coding genes.
2.949145
2.944642
1.001529
titles = defaultdict(int) for readAlignments in readsAlignments: for alignment in readAlignments: titles[alignment.subjectTitle] += 1 return titles
def titleCounts(readsAlignments)
Count the number of times each title in a readsAlignments instance is matched. This is useful for rapidly discovering what titles were matched and with what frequency. @param readsAlignments: A L{dark.alignments.ReadsAlignments} instance. @return: A C{dict} whose keys are titles and whose values are th...
3.351187
3.870104
0.865916
return { 'hsps': [hsp.toDict() for hsp in self.hsps], 'read': self.read.toDict(), }
def toDict(self)
Get information about a title alignment as a dictionary. @return: A C{dict} representation of the title aligment.
3.653403
4.852345
0.752915
# Note: Do not assume that HSPs in an alignment are sorted in # decreasing order (as they are in BLAST output). If we could # assume that, we could just check the first HSP in each alignment. for hsp in self.hsps(): if hsp.betterThan(score): return Tr...
def hasScoreBetterThan(self, score)
Is there an HSP with a score better than a given value? @return: A C{bool}, C{True} if there is at least one HSP in the alignments for this title with a score better than C{score}.
6.497233
5.812286
1.117845
intervals = ReadIntervals(self.subjectLength) for hsp in self.hsps(): intervals.add(hsp.subjectStart, hsp.subjectEnd) return intervals.coverage()
def coverage(self)
Get the fraction of this title sequence that is matched by its reads. @return: The C{float} fraction of the title sequence matched by its reads.
7.584831
6.668014
1.137495
result = defaultdict(list) for titleAlignment in self: for hsp in titleAlignment.hsps: score = hsp.score.score for (subjectOffset, base, _) in titleAlignment.read.walkHSP( hsp, includeWhiskers=False): resul...
def coverageInfo(self)
Return information about the bases found at each location in our title sequence. @return: A C{dict} whose keys are C{int} subject offsets and whose values are unsorted lists of (score, base) 2-tuples, giving all the bases from reads that matched the subject at subject location, ...
10.186002
6.114756
1.665807
if convertCaseTo == 'none': def convert(x): return x elif convertCaseTo == 'lower': convert = str.lower elif convertCaseTo == 'upper': convert = str.upper else: raise ValueError( "convertCaseTo must ...
def residueCounts(self, convertCaseTo='upper')
Count residue frequencies at all sequence locations matched by reads. @param convertCaseTo: A C{str}, 'upper', 'lower', or 'none'. If 'none', case will not be converted (both the upper and lower case string of a residue will be present in the result if they are present in th...
3.547339
2.983907
1.188824
return { 'bestScore': self.bestHsp().score.score, 'coverage': self.coverage(), 'hspCount': self.hspCount(), 'medianScore': self.medianScore(), 'readCount': self.readCount(), 'subjectLength': self.subjectLength, 'subject...
def summary(self)
Summarize the alignments for this subject. @return: A C{dict} with C{str} keys: bestScore: The C{float} best score of the matching reads. coverage: The C{float} fraction of the subject genome that is matched by at least one read. hspCount: The C{int} number o...
4.70883
2.178811
2.161193
return { 'titleAlignments': [titleAlignment.toDict() for titleAlignment in self], 'subjectTitle': self.subjectTitle, 'subjectLength': self.subjectLength, }
def toDict(self)
Get information about the title's alignments as a dictionary. @return: A C{dict} representation of the title's aligments.
6.366706
5.547715
1.147627
if title in self: raise KeyError('Title %r already present in TitlesAlignments ' 'instance.' % title) else: self[title] = titleAlignments
def addTitle(self, title, titleAlignments)
Add a new title to self. @param title: A C{str} title. @param titleAlignments: An instance of L{TitleAlignments}. @raises KeyError: If the title is already present.
6.518959
4.410783
1.477959
# Use a ReadSetFilter only if we're checking that read sets are # sufficiently new. if minNewReads is None: readSetFilter = None else: if self.readSetFilter is None: self.readSetFilter = ReadSetFilter(minNewReads) readSetFilter...
def filter(self, minMatchingReads=None, minMedianScore=None, withScoreBetterThan=None, minNewReads=None, minCoverage=None, maxTitles=None, sortOn='maxScore')
Filter the titles in self to create another TitlesAlignments. @param minMatchingReads: titles that are matched by fewer reads are unacceptable. @param minMedianScore: sequences that are matched with a median bit score that is less are unacceptable. @param withScoreBetter...
4.215709
3.978718
1.059565
return (hsp for titleAlignments in self.values() for alignment in titleAlignments for hsp in alignment.hsps)
def hsps(self)
Get all HSPs for all the alignments for all titles. @return: A generator yielding L{dark.hsp.HSP} instances.
9.217981
5.29482
1.740943
# First sort titles by the secondary key, which is always the title. titles = sorted(iter(self)) # Then sort on the primary key (if any). if by == 'length': return sorted( titles, reverse=True, key=lambda title: self[title].subjectLen...
def sortTitles(self, by)
Sort titles by a given attribute and then by title. @param by: A C{str}, one of 'length', 'maxScore', 'medianScore', 'readCount', or 'title'. @raise ValueError: If an unknown C{by} value is given. @return: A sorted C{list} of titles.
3.41531
2.716383
1.257301
titles = self if sortOn is None else self.sortTitles(sortOn) for title in titles: yield self[title].summary()
def summary(self, sortOn=None)
Summarize all the alignments for this title. @param sortOn: A C{str} attribute to sort titles on. One of 'length', 'maxScore', 'medianScore', 'readCount', or 'title'. @raise ValueError: If an unknown C{sortOn} value is given. @return: A generator that yields C{dict} instances as pro...
7.18783
8.364568
0.859319
# The order of the fields returned here is somewhat arbitrary. The # subject titles are last because they are so variable in length. # Putting them last makes it more likely that the initial columns in # printed output will be easier to read down. # # Note that p...
def tabSeparatedSummary(self, sortOn=None)
Summarize all the alignments for this title as multi-line string with TAB-separated values on each line. @param sortOn: A C{str} attribute to sort titles on. One of 'length', 'maxScore', 'medianScore', 'readCount', or 'title'. @raise ValueError: If an unknown C{sortOn} value is give...
8.572236
7.798213
1.099257
return { 'scoreClass': self.scoreClass.__name__, 'titles': dict((title, titleAlignments.toDict()) for title, titleAlignments in self.items()), }
def toDict(self)
Get information about the titles alignments as a dictionary. @return: A C{dict} representation of the titles aligments.
8.126116
5.855817
1.3877
parser.add_argument( '--minLength', type=int, help='The minimum sequence length') parser.add_argument( '--maxLength', type=int, help='The maximum sequence length') parser.add_argument( '--whitelist', action='append', help='Sequence titles (ids) that sho...
def addFASTAFilteringCommandLineOptions(parser)
Add standard FASTA filtering command-line options to an argparse parser. These are options that can be used to select or omit entire FASTA records, NOT options that change them (for that see addFASTAEditingCommandLineOptions). @param parser: An C{argparse.ArgumentParser} instance.
2.552302
2.564453
0.995262
keepSequences = ( parseRangeString(args.keepSequences, convertToZeroBased=True) if args.keepSequences else None) removeSequences = ( parseRangeString(args.removeSequences, convertToZeroBased=True) if args.removeSequences else None) return reads.filter( minLengt...
def parseFASTAFilteringCommandLineOptions(args, reads)
Examine parsed FASTA filtering command-line options and return filtered reads. @param args: An argparse namespace, as returned by the argparse C{parse_args} function. @param reads: A C{Reads} instance to filter. @return: The filtered C{Reads} instance.
2.963195
3.178868
0.932154
# A mutually exclusive group for --keepSites, --keepSitesFile, # --removeSites, and --removeSitesFile. group = parser.add_mutually_exclusive_group() # In the 4 options below, the 'indices' alternate names are kept for # backwards compatibility. group.add_argument( '--keepSites', '-...
def addFASTAEditingCommandLineOptions(parser)
Add standard FASTA editing command-line options to an argparse parser. These are options that can be used to alter FASTA records, NOT options that simply select or reject those things (for those see addFASTAFilteringCommandLineOptions). @param parser: An C{argparse.ArgumentParser} instance.
3.083691
3.114889
0.989984
removeGaps = args.removeGaps removeDescriptions = args.removeDescriptions truncateTitlesAfter = args.truncateTitlesAfter keepSites = ( parseRangeString(args.keepSites, convertToZeroBased=True) if args.keepSites else None) if args.keepSitesFile: keepSites = keepSites or ...
def parseFASTAEditingCommandLineOptions(args, reads)
Examine parsed FASTA editing command-line options and return information about kept sites and sequences. @param args: An argparse namespace, as returned by the argparse C{parse_args} function. @param reads: A C{Reads} instance to filter. @return: The filtered C{Reads} instance.
2.30043
2.262376
1.01682
if self._whitelist and title in self._whitelist: return self.WHITELIST_ACCEPT if self._blacklist and title in self._blacklist: return self.REJECT # If we have a positive regex but we don't match it, reject. if self._positiveRegex and self._positiveRegex...
def accept(self, title)
Return a value (see below) to indicate if a title is acceptable (and, if so, in what way). @param title: A C{str} sequence title. @return: An C{int} to indicate an acceptable title or not. This will be C{self.REJECT} if the title is unacceptable. C{self.WHITELIST_ACCEPT...
3.328922
3.037908
1.095794
# Sanity check: titles can only be passed once. assert title not in self._titles, ( 'Title %r seen multiple times.' % title) readIds = titleAlignments.readIds() newReadsRequired = ceil(self._minNew * len(readIds)) for readSet, invalidatedTitles in self._ti...
def accept(self, title, titleAlignments)
Return C{True} if the read id set in C{titleAlignments} is sufficiently different from all previously seen read sets. @param title: A C{str} sequence title. @param titleAlignments: An instance of L{TitleAlignment}. @return: A C{bool} indicating whether a title has an acceptably novel ...
6.570258
5.197623
1.264089
alignments = [] for alignment in record.alignments: hsps = [] for hsp in alignment.hsps: hsps.append({ 'bits': hsp.bits, 'expect': hsp.expect, 'frame': hsp.frame, 'identicalCo...
def _convertBlastRecordToDict(self, record)
Pull (only) the fields we use out of the record and return them as a dict. Although we take the title from each alignment description, we save space in the JSON output by storing it in the alignment dict (not in a separated 'description' dict). When we undo this conversion (in JSONRecor...
1.609372
1.621582
0.99247
result = {} for attr in ( # From Bio.Blast.Record.Header 'application', 'version', 'date', 'reference', 'query', 'query_letters', 'database', 'database...
def _convertBlastParamsToDict(self, record)
Pull the global BLAST parameters out of a BLAST record and return them as a C{dict}. Some of these attributes are useless (not filled in), but we record them all just in case we one day need them or they start to be used or they disappear etc. Any of those changes might alert us that so...
4.876113
4.67567
1.042869
first = True with as_handle(self._filename) as fp: for record in NCBIXML.parse(fp): if first: self.params = self._convertBlastParamsToDict(record) first = False yield record
def records(self)
Yield BLAST records, as read by the BioPython NCBIXML.parse method. Set self.params from data in the first record.
6.91568
3.76109
1.838744
first = True for record in self.records(): if first: print(dumps(self.params, separators=(',', ':')), file=fp) first = False print(dumps(self._convertBlastRecordToDict(record), separators=(',', ':')), file=fp)
def saveAsJSON(self, fp)
Write the records out as JSON. The first JSON object saved contains the BLAST parameters. @param fp: A C{str} file pointer to write to.
4.310594
3.782169
1.139715
if filename.endswith('.bz2'): if six.PY3: self._fp = bz2.open(filename, mode='rt', encoding='UTF-8') else: self._fp = bz2.BZ2File(filename) else: self._fp = open(filename) line = self._fp.readline() if not line...
def _open(self, filename)
Open the input file. Set self._fp to point to it. Read the first line of parameters. @param filename: A C{str} filename containing JSON BLAST records. @raise ValueError: if the first line of the file isn't valid JSON, if the input file is empty, or if the JSON does not contain an ...
3.071413
2.643916
1.161691
if (blastDict['query'] != read.id and blastDict['query'].split()[0] != read.id): raise ValueError( 'The reads you have provided do not match the BLAST output: ' 'BLAST record query id (%s) does not match the id of the ' 'suppos...
def _dictToAlignments(self, blastDict, read)
Take a dict (made by XMLRecordsReader._convertBlastRecordToDict) and convert it to a list of alignments. @param blastDict: A C{dict}, from convertBlastRecordToDict. @param read: A C{Read} instance, containing the read that BLAST used to create this record. @raise ValueError:...
4.067842
4.005987
1.01544
if self._fp is None: self._open(self._filename) reads = iter(reads) try: for lineNumber, line in enumerate(self._fp, start=2): try: record = loads(line[:-1]) except ValueError as e: raise V...
def readAlignments(self, reads)
Read lines of JSON from self._filename, convert them to read alignments and yield them. @param reads: An iterable of L{Read} instances, corresponding to the reads that were given to BLAST. @raise ValueError: If any of the lines in the file cannot be converted to JSON. ...
3.414195
2.859408
1.194022
table = list(range(256)) for _from, to in complementData.items(): table[ord(_from[0].lower())] = ord(to[0].lower()) table[ord(_from[0].upper())] = ord(to[0].upper()) return ''.join(map(chr, table))
def _makeComplementTable(complementData)
Make a sequence complement table. @param complementData: A C{dict} whose keys and values are strings of length one. A key, value pair indicates a substitution that should be performed during complementation. @return: A 256 character string that can be used as a translation table by the ...
2.598305
2.515372
1.032971
parser.add_argument( '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME', help=('The name of the FASTA input file. Standard input will be read ' 'if no file name is given.')) parser.add_argument( '--readClass', default='DNARead', choices=readClassNameToCl...
def addFASTACommandLineOptions(parser)
Add standard command-line options to an argparse parser. @param parser: An C{argparse.ArgumentParser} instance.
2.910221
2.892554
1.006108
# Set default FASTA type. if not (args.fasta or args.fastq or args.fasta_ss): args.fasta = True readClass = readClassNameToClass[args.readClass] if args.fasta: from dark.fasta import FastaReads return FastaReads(args.fastaFile, readClass=readClass) elif args.fastq: ...
def parseFASTACommandLineOptions(args)
Examine parsed command-line options and return a Reads instance. @param args: An argparse namespace, as returned by the argparse C{parse_args} function. @return: A C{Reads} subclass instance, depending on the type of FASTA file given.
3.054145
2.954462
1.03374
rc = self.reverseComplement().sequence for reverseComplemented in False, True: for frame in 0, 1, 2: seq = rc if reverseComplemented else self.sequence # Get the suffix of the sequence for translation. I.e., # skip 0, 1, or 2 initial b...
def translations(self)
Yield all six translations of a nucleotide sequence. @return: A generator that produces six L{TranslatedRead} instances.
6.492556
5.710402
1.13697
quality = None if self.quality is None else self.quality[::-1] sequence = self.sequence.translate(self.COMPLEMENT_TABLE)[::-1] return self.__class__(self.id, sequence, quality)
def reverseComplement(self)
Reverse complement a nucleotide sequence. @return: The reverse complemented sequence as an instance of the current class.
4.157396
4.372279
0.950853
if six.PY3: readLetters = super().checkAlphabet(count) else: readLetters = Read.checkAlphabet(self, count) if len(self) > 10 and readLetters.issubset(set('ACGT')): raise ValueError('It looks like a DNA sequence has been passed to ' ...
def checkAlphabet(self, count=10)
A function which checks if an AA read really contains amino acids. This additional testing is needed, because the letters in the DNA alphabet are also in the AA alphabet. @param count: An C{int}, indicating how many bases or amino acids at the start of the sequence should be conside...
7.045592
4.95453
1.422051
# Return open ORFs to the left and right and closed ORFs within the # sequence. if openORFs: ORFStart = 0 inOpenORF = True # open on the left inORF = False for index, residue in enumerate(self.sequence): if residue == '*...
def ORFs(self, openORFs=False)
Find all ORFs in our sequence. @param openORFs: If C{True} allow ORFs that do not have a start codon and/or do not have a stop codon. @return: A generator that yields AAReadORF instances that correspond to the ORFs found in the AA sequence.
2.619685
2.372202
1.104326
if six.PY3: result = super().toDict() else: result = AARead.toDict(self) result.update({ 'start': self.start, 'stop': self.stop, 'openLeft': self.openLeft, 'openRight': self.openRight, }) return re...
def toDict(self)
Get information about this read in a dictionary. @return: A C{dict} with keys/values for the attributes of self.
3.63442
3.615444
1.005249
# Make a dummy instance whose attributes we can set explicitly. new = cls(AARead('', ''), 0, 0, True, True) new.id = d['id'] new.sequence = d['sequence'] new.quality = d.get('quality') new.start = d['start'] new.stop = d['stop'] new.openLeft = d['...
def fromDict(cls, d)
Create a new instance from attribute values provided in a dictionary. @param d: A C{dict} with keys/values for the attributes of a new instance of this class. Keys 'id' and 'sequence' with C{str} values must be provided. A 'quality' C{str} key is optional. Keys 'start' and '...
4.767246
3.116961
1.529454
if format_ == 'fasta-ss': return '>%s\n%s\n>%s%s\n%s\n' % ( self.id, self.sequence, self.id, structureSuffix, self.structure) else: if six.PY3: return super().toString(format_=format_) else: retu...
def toString(self, format_='fasta-ss', structureSuffix=':structure')
Convert the read to a string in PDB format (sequence & structure). This consists of two FASTA records, one for the sequence then one for the structure. @param format_: Either 'fasta-ss' or 'fasta'. In the former case, the structure information is returned. Otherwise, plain FASTA is ...
2.844688
2.763518
1.029372
if exclude: sites = set(range(len(self))) - sites newSequence = [] newStructure = [] for index, (base, structure) in enumerate(zip(self.sequence, self.structure)): if index in sites: n...
def newFromSites(self, sites, exclude=False)
Create a new read from self, with only certain sites. @param sites: A set of C{int} 0-based sites (i.e., indices) in sequences that should be kept. If C{None} (the default), all sites are kept. @param exclude: If C{True} the C{sites} will be excluded, not included.
3.412342
3.046306
1.120157
if six.PY3: result = super().toDict() else: result = AARead.toDict(self) result.update({ 'frame': self.frame, 'reverseComplemented': self.reverseComplemented, }) return result
def toDict(self)
Get information about this read in a dictionary. @return: A C{dict} with keys/values for the attributes of self.
4.953971
4.657014
1.063766
# Make a dummy instance whose attributes we can set explicitly. new = cls(AARead('', ''), 0, True) new.id = d['id'] new.sequence = d['sequence'] new.quality = d.get('quality') new.frame = d['frame'] new.reverseComplemented = d['reverseComplemented'] ...
def fromDict(cls, d)
Create a new instance from attribute values provided in a dictionary. @param d: A C{dict} with keys/values for the attributes of a new instance of this class. Keys 'id' and 'sequence' with C{str} values must be provided. A 'quality' C{str} key is optional. Key 'frame' must h...
6.341354
3.936917
1.610741
return max(len(orf) for orf in self.ORFs(openORFs))
def maximumORFLength(self, openORFs=True)
Return the length of the longest (possibly partial) ORF in a translated read. The ORF may originate or terminate outside the sequence, which is why the length is just a lower bound.
3.903171
3.89193
1.002888
self.readIndex += 1 if self.alwaysFalse: return False if self.wantedSequenceNumberGeneratorExhausted: return False if self.nextWantedSequenceNumber is not None: if self.readIndex + 1 == self.nextWantedSequenceNumber: # We wa...
def filter(self, read)
Check if a read passes the filter. @param read: A C{Read} instance. @return: C{read} if C{read} passes the filter, C{False} if not.
3.011095
3.040162
0.990439
for filterFunc in self._filters: filteredRead = filterFunc(read) if filteredRead is False: return False else: read = filteredRead return read
def filterRead(self, read)
Filter a read, according to our set of filters. @param read: A C{Read} instance or one of its subclasses. @return: C{False} if the read fails any of our filters, else the C{Read} instance returned by our list of filters.
3.521732
3.374926
1.043499
format_ = format_.lower() count = 0 if isinstance(filename, str): try: with open(filename, 'w') as fp: for read in self: fp.write(read.toString(format_)) count += 1 except ValueE...
def save(self, filename, format_='fasta')
Write the reads to C{filename} in the requested format. @param filename: Either a C{str} file name to save into (the file will be overwritten) or an open file descriptor (e.g., sys.stdout). @param format_: A C{str} format to save as, either 'fasta', 'fastq' or 'fasta-ss'. ...
2.854789
2.789082
1.023559
readFilter = ReadFilter(**kwargs) self._filters.append(readFilter.filter) return self
def filter(self, **kwargs)
Add a filter to this C{Reads} instance. @param kwargs: Keyword arguments, as accepted by C{ReadFilter}. @return: C{self}.
8.593692
7.770416
1.10595
countAtPosition = Counter() excludedCount = 0 for read in self: try: countAtPosition[read.sequence[index]] += 1 except IndexError: excludedCount += 1 return { 'excludedCount': excludedCount, 'count...
def summarizePosition(self, index)
Compute residue counts at a specific sequence index. @param index: an C{int} index into the sequence. @return: A C{dict} with the count of too-short (excluded) sequences, and a Counter instance giving the residue counts.
4.093483
3.674447
1.114041
# If case is unimportant, we convert everything (target bases and # sequences, as we read them) to lower case. if not matchCase: targets = set(map(str.lower, targets)) result = set() if any_ else None for read in self: sequence = read.sequence if...
def sitesMatching(self, targets, matchCase, any_)
Find sites (i.e., sequence indices) that match a given set of target sequence bases. @param targets: A C{set} of sequence bases to look for. @param matchCase: If C{True}, case will be considered in matching. @param any_: If C{True}, return sites that match in any read. Else ...
4.215194
3.677861
1.146099
if isinstance(condition, string_types): def smatcher(info): return fnmatch.fnmatch(info.filename, condition) return smatcher elif isinstance(condition, (list, tuple)) and isinstance(condition[0], integer_types): ...
def condition2checker(condition)
Converts different condition types to callback
3.113472
3.140017
0.991546
checker = condition2checker(condition) return RarFileImplementation.read_files(self, checker)
def read_files(self, condition='*')
Read specific files from archive into memory. If "condition" is a list of numbers, then return files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a function, it is treated as a callback funct...
23.421019
18.159563
1.289735
checker = condition2checker(condition) return RarFileImplementation.extract(self, checker, path, withSubpath, overwrite)
def extract(self, condition='*', path='.', withSubpath=True, overwrite=True)
Extract specific files from archive to disk. If "condition" is a list of numbers, then extract files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a function, it is treated as a callb...
11.530013
12.431386
0.927492
if read_only: scopes = ['https://www.googleapis.com/auth/devstorage.read_only'] else: scopes = ['https://www.googleapis.com/auth/devstorage.read_write'] credentials = service_account.Credentials.from_service_account_info( client_secrets) scoped_credentials = creden...
def authenticate_storage(client_secrets, read_only=False)
Authenticates a service account for reading and/or writing on a bucket. TODO: docstring
1.887992
1.771713
1.065631
scopes = ['https://www.googleapis.com/auth/compute'] credentials = ServiceAccountCredentials.from_json_keyfile_dict( client_secrets, scopes=scopes) return credentials
def authenticate_compute(client_secrets)
Authenticates a service account for the compute engine. TODO: docstring
2.265559
2.605757
0.869444
if args is None: # parse command-line arguments parser = get_argument_parser() args = parser.parse_args() input_file = args.annotation_file output_file = args.output_file species = args.species chrom_pat = args.chromosome_pattern field_name = args.field_name lo...
def main(args=None)
Extract Ensembl IDs and store in tab-delimited text file. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module. Returns ------- int ...
3.056543
3.065064
0.99722
if not connection: config = configparser.ConfigParser() cfp = defaults.config_file_path if os.path.exists(cfp): log.info('fetch database configuration from %s', cfp) config.read(cfp) connection = config['database']['sqlalchemy_connection_string'] ...
def get_connection_string(connection=None)
return SQLAlchemy connection string if it is set :param connection: get the SQLAlchemy connection string #TODO :rtype: str
2.717774
2.717176
1.00022
if isinstance(taxids, int): taxids = (taxids,) db = DbManager(connection) db.db_import_xml(urls, force_download, taxids, silent) db.session.close()
def update(connection=None, urls=None, force_download=False, taxids=None, silent=False)
Updates CTD database :param urls: list of urls to download :type urls: iterable :param connection: custom database connection string :type connection: str :param force_download: force method to download :type force_download: bool :param int,list,tuple taxids: int or iterable of NCBI taxonom...
4.736777
5.297883
0.894089
db = DbManager(connection) db.export_obo(path_to_export_file=path_to_file) db.session.close()
def export_obo(path_to_file, connection=None)
export database to obo file :param path_to_file: path to export file :param connection: connection string (optional) :return:
4.755346
4.810848
0.988463
log.info('Update UniProt database from {}'.format(url)) self._drop_tables() xml_gzipped_file_path, version_file_path = self.download(url, force_download) self._create_tables() self.import_version(version_file_path) self.import_xml(xml_gzipped_file_path, taxids, ...
def db_import_xml(self, url=None, force_download=False, taxids=None, silent=False)
Updates the CTD database 1. downloads gzipped XML 2. drops all tables in database 3. creates all tables in database 4. import XML 5. close session :param Optional[list[int]] taxids: list of NCBI taxonomy identifier :param str url: iterable of URL strings...
4.198947
3.989532
1.052491
version = self.session.query(models.Version).filter(models.Version.knowledgebase == 'Swiss-Prot').first() version.import_start_date = datetime.now() entry_xml = '<entries>' number_of_entries = 0 interval = 1000 start = False if sys.platform in ('linux',...
def import_xml(self, xml_gzipped_file_path, taxids=None, silent=False)
Imports XML :param str xml_gzipped_file_path: path to XML file :param Optional[list[int]] taxids: NCBI taxonomy identifier :param bool silent: no output if True
3.177995
3.196025
0.994359
entries = etree.fromstring(entries_xml) del entries_xml for entry in entries: self.insert_entry(entry, taxids) entry.clear() del entry entries.clear() del entries self.session.commit()
def insert_entries(self, entries_xml, taxids=None)
Inserts UniProt entries from XML :param str entries_xml: XML string :param Optional[list[int]] taxids: NCBI taxonomy IDs
3.216543
3.857774
0.833782
entry_dict = entry.attrib entry_dict['created'] = datetime.strptime(entry_dict['created'], '%Y-%m-%d') entry_dict['modified'] = datetime.strptime(entry_dict['modified'], '%Y-%m-%d') taxid = self.get_taxid(entry) if taxids is None or taxid in taxids: entry_d...
def insert_entry(self, entry, taxids)
Insert UniProt entry" :param entry: XML node entry :param taxids: Optional[iter[int]] taxids: NCBI taxonomy IDs
2.464061
2.411471
1.021808
seq_tag = entry.find("./sequence") seq = seq_tag.text seq_tag.clear() return models.Sequence(sequence=seq)
def get_sequence(cls, entry)
get models.Sequence object from XML node entry :param entry: XML node entry :return: :class:`pyuniprot.manager.models.Sequence` object
6.481195
6.70868
0.966091
tissue_in_references = [] query = "./reference/source/tissue" tissues = {x.text for x in entry.iterfind(query)} for tissue in tissues: if tissue not in self.tissues: self.tissues[tissue] = models.TissueInReference(tissue=tissue) tissue_i...
def get_tissue_in_references(self, entry)
get list of models.TissueInReference from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.TissueInReference` objects
2.911203
2.691654
1.081566
tissue_specificities = [] query = "./comment[@type='tissue specificity']/text" for ts in entry.iterfind(query): tissue_specificities.append(models.TissueSpecificity(comment=ts.text)) return tissue_specificities
def get_tissue_specificities(cls, entry)
get list of :class:`pyuniprot.manager.models.TissueSpecificity` object from XML node entry :param entry: XML node entry :return: models.TissueSpecificity object
4.813138
4.479447
1.074494
subcellular_locations = [] query = './comment/subcellularLocation/location' sls = {x.text for x in entry.iterfind(query)} for sl in sls: if sl not in self.subcellular_locations: self.subcellular_locations[sl] = models.SubcellularLocation(location=sl...
def get_subcellular_locations(self, entry)
get list of models.SubcellularLocation object from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.SubcellularLocation` object
3.188833
2.985786
1.068005
keyword_objects = [] for keyword in entry.iterfind("./keyword"): identifier = keyword.get('id') name = keyword.text keyword_hash = hash(identifier) if keyword_hash not in self.keywords: self.keywords[keyword_hash] = models.Keywor...
def get_keywords(self, entry)
get list of models.Keyword objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Keyword` objects
2.958192
2.720196
1.087492
disease_comments = [] query = "./comment[@type='disease']" for disease_comment in entry.iterfind(query): value_dict = {'comment': disease_comment.find('./text').text} disease = disease_comment.find("./disease") if disease is not None: ...
def get_disease_comments(self, entry)
get list of models.Disease objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Disease` objects
2.590186
2.586489
1.001429
names = [] query = "./protein/alternativeName/fullName" for name in entry.iterfind(query): names.append(models.AlternativeFullName(name=name.text)) return names
def get_alternative_full_names(cls, entry)
get list of models.AlternativeFullName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeFullName` objects
8.194226
5.701442
1.43722
names = [] query = "./protein/alternativeName/shortName" for name in entry.iterfind(query): names.append(models.AlternativeShortName(name=name.text)) return names
def get_alternative_short_names(cls, entry)
get list of models.AlternativeShortName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeShortName` objects
7.843431
5.751498
1.36372
ec_numbers = [] for ec in entry.iterfind("./protein/recommendedName/ecNumber"): ec_numbers.append(models.ECNumber(ec_number=ec.text)) return ec_numbers
def get_ec_numbers(cls, entry)
get list of models.ECNumber objects from XML node entry :param entry: XML node entry :return: list of models.ECNumber objects
4.850818
4.138889
1.17201