code stringlengths 1 18.2k |
|---|
def basePlotter(blastHits, title): """ Plot the reads and the subject, so that bases in the reads which are different from the subject are shown. Else a '.' is shown. like so: subject_gi ATGCGTACGTACGACACC read_1 A......TTC..T @param blastHits: A L{dark.blast.BlastHits} instance. @param title: A C{str} sequence title t... |
count += 1 hsp = item['hsp'] queryTitle = blastHits.fasta[item['readNum']].id # If the product of the subject and query frame values is +ve, # then they're either both +ve or both -ve, so we just use the # query as is. Otherwise, we need to reverse complement it. if item['frame']['subject'] * item['frame']['query'] > 0... |
parts need to be taken into account: # 1) the left offset (if the query doesn't stick out to the left) # 2) the query. if the frame is -1, it has to be reversed. # The query consists of 3 parts: left, middle (control for gaps) # 3) the right offset # Do part 1) and 2). if queryStart < 0: # The query is sticking out to ... |
# The query is not sticking out to the left # make the left offset. leftQuery = queryStart * ' ' leftQueryOffset = subjectStart - queryStart middleLeftQuery = query[:leftQueryOffset] # Do part 3). # Disregard gaps in subject while adding. matchQuery = item['origHsp'].query matchSubject = item['origHsp'].sbjct index = 0... |
not-matching part of the query rightQueryOffset = queryEnd - subjectEnd rightQuery = query[-rightQueryOffset:] middleQuery += rightQuery read = leftQuery + middleQuery # do part 3) offset = len(subject) - len(read) # if the read is sticking out to the right # chop it off if offset < 0: read = read[:offset] # if it's no... |
comparison += '.' elif readBase != subjectBase: comparison += readBase index += 1 que = '%s \t %s' % (queryTitle, comparison) result.append(que) # sanity checks assert (len(comparison) == len(subject)), ( '%d != %d' % (len(comparison), len(subject))) index = 0 if comparison[index] == ' ': index += 1 else: start = index... |
def getAPOBECFrequencies(dotAlignment, orig, new, pattern): """ Gets mutation frequencies if they are in a certain pattern. @param dotAlignment: result from calling basePlotter @param orig: A C{str}, naming the original base @param new: A C{str}, what orig was mutated to @param pattern: A C{str}m which pattern we're lo... |
patterns: freqs[pattern] = 0 # get the subject sequence from dotAlignment subject = dotAlignment[0].split('\t')[3] # exclude the subject from the dotAlignment, so just the queries # are left over queries = dotAlignment[1:] for item in queries: query = item.split('\t')[1] index = 0 for queryBase in query: qBase = query[... |
def getCompleteFreqs(blastHits): """ Make a dictionary which collects all mutation frequencies from all reads. Calls basePlotter to get dotAlignment, which is passed to getAPOBECFrequencies with the respective parameter, to collect the frequencies. @param blastHits: A L{dark.blast.BlastHits} instance. """ allFreqs = {}... |
def makeFrequencyGraph(allFreqs, title, substitution, pattern, color='blue', createFigure=True, showFigure=True, readsAx=False): """ For a title, make a graph showing the frequencies. @param allFreqs: result from getCompleteFreqs @param title: A C{str}, title of virus of which frequencies should be plotted. @param subs... |
['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG', 'CTT', 'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC', 'TTG', 'TTT'] # choose the right pattern if pattern == 'cPattern': patterns = cPattern else: patterns = tPattern fig = plt.figure(figsize=(10, 10)) ax = readsAx or fig.add_subplot(111) # how many bars N = 16 ind = np.aran... |
Mutations', fontsize=16) ax.set_xticks(ind + width) ax.set_xticklabels(patterns, rotation=45, fontsize=8) if createFigure is False: ax.set_xticks(ind + width) ax.set_xticklabels(patterns, rotation=45, fontsize=0) else: if showFigure: plt.show() return maxY |
def makeFrequencyPanel(allFreqs, patientName): """ For a title, make a graph showing the frequencies. @param allFreqs: result from getCompleteFreqs @param patientName: A C{str}, title for the panel """ titles = sorted( iter(allFreqs.keys()), key=lambda title: (allFreqs[title]['bitScoreMax'], title)) origMaxY = 0 cols =... |
will have to be adapted. if index == 0: gi = title.split('|')[1] titles = title.split(' ') try: typeIndex = titles.index('type') except ValueError: typeNumber = 'gi: %s' % gi else: typeNumber = titles[typeIndex + 1] ax[i][index].set_ylabel(('Type %s \n maxBitScore: %s' % ( typeNumber, allFreqs[title]['bitScoreMax'])), ... |
ax[i][index] a.set_ylim([0, origMaxY]) # add title of whole panel figure.suptitle('Mutation Signatures in %s' % patientName, fontsize=20) figure.set_size_inches(5 * cols, 3 * rows, forward=True) figure.show() return allFreqs |
def mutateString(original, n, replacements='acgt'): """ Mutate C{original} in C{n} places with chars chosen from C{replacements}. @param original: The original C{str} to mutate. @param n: The C{int} number of locations to mutate. @param replacements: The C{str} of replacement letters. @return: A new C{str} with C{n} pl... |
ValueError('Impossible replacement') result = list(original) length = len(original) for offset in range(length): if uniform(0.0, 1.0) < float(n) / (length - offset): # Mutate. while True: new = choice(replacements) if new != result[offset]: result[offset] = new break n -= 1 if n == 0: break return ''.join(result) |
def writeDetails(accept, readId, taxonomy, fp): """ Write read and taxonomy details. @param accept: A C{bool} indicating whether the read was accepted, according to its taxonomy. @param readId: The C{str} id of the read. @taxonomy: A C{list} of taxonomy C{str} levels. @fp: An open file pointer to write to. """ fp.write... |
def build(self, docs=None, filename=None): """Build FM-index Params: <iterator> | <generator> docs <str> filename """ if docs: if hasattr(docs, 'items'): for (idx, doc) in sorted(getattr(docs, 'items')(), key=lambda x: x[0]): self.fm.push_back(doc) else: for doc in filter(bool, docs): self.fm.push_back(doc) self.fm.bui... |
def _merge_search_result(self, search_results, _or=False): """Merge of filter search results Params: <str> | <Sequential> query <bool> _or Return: <list> computed_dids """ all_docids = reduce(add, [list(x.keys()) for x in search_results]) if _or: return sorted(set(all_docids), key=all_docids.index) return [docid for do... |
def search(self, query, _or=False, ignores=[]): """Search word from FM-index Params: <str> | <Sequential> query <bool> _or <list <str> > ignores Return: <list>SEARCH_RESULT(<int> document_id, <list <int> > counts <str> doc) """ if isinstance(query, str): dids = MapIntInt({}) self.fm.search(query, dids) dids = dids.asdi... |
def count(self, query, _or=False): """Count word from FM-index Params: <str> | <Sequential> query <bool> _or <list <str> > ignores Return: <int> counts """ if isinstance(query, str): return self.fm.count(query, MapIntInt({})) else: search_results = [] for q in query: dids = MapIntInt({}) self.fm.search(q, dids) search_... |
def add(self, name, parents=None): """ add a node to the graph. Raises an exception if the node cannot be added (i.e., if a node that name already exists, or if it would create a cycle. NOTE: A node can be added before its parents are added. name: The name of the node to add to the graph. Name can be any unique Hashabl... |
ValueError(parent) elif parent == name: raise ValueError(parent) # Node safe to add if is_stub: self._stubs.remove(name) if parents: for parent_name in parents: parent_node = self._nodes.get(parent_name) if parent_node is not None: parent_node.children.add(name) else: # add stub self._nodes[parent_name] = Node( name=pa... |
def remove(self, name, strategy=Strategy.promote): """ Remove a node from the graph. Returns the set of nodes that were removed. If the node doesn't exist, an exception will be raised. name: The name of the node to remove. strategy: (Optional, Strategy.promote) What to do with children or removed nodes. The options are... |
node.parents: parent_node = self._nodes[parent_name] parent_node.children.add(child_name) child_node.parents.add(parent_name) if not child_node.parents: self._roots.add(child_name) if current in self._stubs: self._stubs.remove(current) elif current in self._roots: self._roots.remove(current) else: # stubs and roots (by... |
def ancestor_of(self, name, ancestor, visited=None): """ Check whether a node has another node as an ancestor. name: The name of the node being checked. ancestor: The name of the (possible) ancestor node. visited: (optional, None) If given, a set of nodes that have already been traversed. NOTE: The set will be updated ... |
def prune(self): """ Remove any tasks that have stubs as ancestors (and the stubs themselves). Returns the set of nodes which were removed. """ pruned = set() stubs = frozenset(self._stubs) for stub in stubs: pruned.update(self.remove(stub, strategy=Strategy.remove)) return pruned - stubs |
def respond(template, context={}, request=None, **kwargs): "Calls render_to_response with a RequestConext" from django.http import HttpResponse from django.template import RequestContext from django.template.loader import render_to_string if request: default = context_processors.default(request) default.update(context)... |
def index(request): "Displays a list of all services and their current status." service_list = Service.objects.all() event_list = list(Event.objects\ .filter(Q(status__gt=0) | Q(date_updated__gte=datetime.datetime.now()-datetime.timedelta(days=1)))\ .order_by('-date_created')[0:6]) if event_list: latest_event, event_li... |
def service(request, slug): "Displays a list of all services and their current status." try: service = Service.objects.get(slug=slug) except Service.DoesNotExist: return HttpResponseRedirect(reverse('overseer:index')) event_list = service.event_set.order_by('-date_created') return respond('overseer/service.html', { 'se... |
def event(request, id): "Displays a list of all services and their current status." try: evt = Event.objects.get(pk=id) except Event.DoesNotExist: return HttpResponseRedirect(reverse('overseer:index')) update_list = list(evt.eventupdate_set.order_by('-date_created')) return respond('overseer/event.html', { 'event': evt... |
def last_event(request, slug): "Displays a list of all services and their current status." try: service = Service.objects.get(slug=slug) except Service.DoesNotExist: return HttpResponseRedirect(reverse('overseer:index')) try: evt = service.event_set.order_by('-date_created')[0] except IndexError: return HttpResponseRed... |
def update_subscription(request, ident): "Shows subscriptions options for a verified subscriber." try: subscription = Subscription.objects.get(ident=ident) except Subscription.DoesNotExist: return respond('overseer/invalid_subscription_token.html', {}, request) if request.POST: form = UpdateSubscriptionForm(request.POS... |
def create_subscription(request): "Shows subscriptions options for a new subscriber." if request.POST: form = NewSubscriptionForm(request.POST) if form.is_valid(): unverified = form.save() body = """Please confirm your email address to subscribe to status updates from %(name)s:\n\n%(link)s""" % dict( name=conf.NAME, li... |
def verify_subscription(request, ident): """ Verifies an unverified subscription and create or appends to an existing subscription. """ try: unverified = UnverifiedSubscription.objects.get(ident=ident) except UnverifiedSubscription.DoesNotExist: return respond('overseer/invalid_subscription_token.html', {}, request) su... |
def get_client(key, project): """Gets a `Client` object (required by the other functions). TODO: docstring""" cred = get_storage_credentials(key) return storage.Client(project=project, credentials=cred) |
def get_files(client, bucket, prefix=''): """Lists files/objects on a bucket. TODO: docstring""" bucket = client.get_bucket(bucket) files = list(bucket.list_blobs(prefix=prefix)) return files |
def download_file(client, bucket, remote_path, local_path, overwrite=False): """Downloads a file from a bucket. TODO: docstring""" bucket = client.get_bucket(bucket) if (not overwrite) and os.path.isfile(local_path): raise OSError('File already exists!') with open(local_path, 'wb') as ofh: bucket.get_blob(remote_path).... |
def delete_file(client, bucket, remote_path): """Deletes a file from a bucket. TODO: docstring""" bucket = client.get_bucket(bucket) bucket.delete_blob(remote_path) |
def upload_file(client, bucket, local_path, remote_path, overwrite=False): """Uploads a file to a bucket. TODO: docstring""" bucket = client.get_bucket(bucket) blob = storage.Blob(remote_path, bucket) if (not overwrite) and blob.exists(): raise Conflict('File/object already exists on the bucket!') blob.upload_from_file... |
def filter(self, readAlignments): """ Filter a read's alignments. @param readAlignments: A C{ReadAlignments} instance. @return: A C{ReadAlignments} instance if the passed C{readAlignments} is not filtered out, else C{False}. """ # Implementation notes: # # 1. The order in which we carry out the filtering actions can ma... |
# # 2. This function could be made faster if it first looked at its # arguments and dynamically created an acceptance function # (taking a readAlignments as an argument). The acceptance # function would run without examining the desired filtering # settings on each call the way the current code does. # # 3. A better ap... |
the read id. if (self.readIdRegex and self.readIdRegex.search(readAlignments.read.id) is None): return False if self.titleFilter: # Remove alignments against sequences whose titles are # unacceptable. wantedAlignments = [] for alignment in readAlignments: if (self.titleFilter.accept(alignment.subjectTitle) != TitleFilt... |
taxonomyIdAndScientificName in lineage: if self.taxonomy in taxonomyIdAndScientificName: wantedAlignments.append(alignment) else: # No lineage info was found. Keep the alignment # since we can't rule it out. We could add another # option to control this. wantedAlignments.append(alignment) if wantedAlignments: readAlign... |
wantedHsps wantedAlignments.append(alignment) if wantedAlignments: readAlignments[:] = wantedAlignments else: return False # Throw out HSPs that don't match in the desired place on the # matched sequence. minStart = self.minStart maxStop = self.maxStop if minStart is not None or maxStop is not None: wantedAlignments = ... |
def hsps(self): """ Provide access to all HSPs for all alignments of all reads. @return: A generator that yields HSPs (or LSPs). """ for readAlignments in self: for alignment in readAlignments: for hsp in alignment.hsps: yield hsp |
def filter(self, **kwargs): """ Add a filter to this C{readsAlignments}. @param kwargs: Keyword arguments, as accepted by C{ReadsAlignmentsFilter}. @return: C{self} """ self._filters.append(ReadsAlignmentsFilter(**kwargs).filter) return self |
def get_annotation_urls_and_checksums(species, release=None, ftp=None): """Get FTP URLs and checksums for Ensembl genome annotations. Parameters ---------- species : str or list of str The species or list of species for which to get genome annotations (e.g., "Homo_sapiens"). release : int, optional The release number t... |
### determine release if necessary if release is None: # use latest release release = util.get_latest_release(ftp=ftp) species_data = OrderedDict() if isinstance(species, (str, _oldstr)): species_list = [species] else: species_list = species for spec in species_list: # get the GTF file URL # => since the naming scheme ... |
gtf_checksum) gtf_url = 'ftp://%s%s/%s' %(ftp_server, species_dir, gtf_file) species_data[spec] = (gtf_url, gtf_checksum) # close FTP connection, if we opened it if close_connection: ftp.close() return species_data |
def get_genes( path_or_buffer, valid_biotypes, chunksize=10000, chromosome_pattern=None, #chromosome_pattern=r'(?:\d\d?|MT|X|Y)$', only_manual=False, remove_duplicates=True, sort_by='name'): """Get all genes of a specific a biotype from an Ensembl GTF file. Parameters ---------- path_or_buffer : str or buffer The GTF f... |
name - 'position': Genes are sorted by their position in the genome.abs Genes are first sorted by chromosome, then by their starting base pair position on the chromosome. - 'position_fancy': Like 'position', but attempts to sort the chromosomes in a more logical order than strictly alphabetically. This currently works ... |
product of the automated Ensembl "genebuild" pipeline. The other set consists of genes that are manually annotated by the HAVANA team (source "havana"), some of which have been merged with the automatic annotations (source "ensembl_havana"). There seems to be no overlap between genes annotated with "havana" and "ensemb... |
of genes. For example, for MATR3, there are ENSG00000015479 and ENSG00000280987, both of type "ensembl_havana". There seems to be no clear criterion by which we could rationally and automatically choose one ID over the other, at least based on information contained in the GTF file. We therefore remove duplicates accord... |
the original order. """ chrompat = None if chromosome_pattern is not None: chrompat = re.compile(chromosome_pattern) # make sure this is a set valid_biotypes = set(valid_biotypes) c = 0 num_lines = 0 num_chunks = 0 t0 = time.time() reader = pd.read_csv(path_or_buffer, encoding='ascii', sep='\t', header=None, comment='#... |
attribute in 9th column attr = gtf.parse_attributes(row[8].lstrip(' ')) # check if biotype is valid biotype = attr['gene_biotype'] if biotype not in valid_biotypes: continue chrom = str(row[0]) source = row[1] if chrompat is not None: match = chrompat.match(chrom) if match is None: excluded_chromosomes.add(chrom) conti... |
if row[6] == '+': pos = int(row[3])-1 elif row[6] == '-': pos = -(int(row[4])-1) else: raise ValueError('Invalid strand information: %s' % str(row[6])) length = abs(int(row[4]) - int(row[3])) + 1 #data.append([gene_name, ensembl_id, chrom, pos, length, # source, biotype]) data.append([ensembl_id, gene_name, chrom, pos,... |
& sel_pc) redundant_ensembl_genes = set(df.loc[sel_ensembl, 'name'].values) \ & set(df.loc[sel_manual, 'name'].values) sel_redund = sel_ensembl & df['name'].isin(redundant_ensembl_genes) num_genes_before = df.shape[0] df = df.loc[~sel_redund] num_genes_after = df.shape[0] _LOGGER.info('Removed %d protein-coding genes w... |
= df.shape[0] _LOGGER.info('Removed %d duplicate protein-coding gene entries', num_genes_before - num_genes_after) else: # print names of genes with duplicate IDs sel = df['type'] == 'protein_coding' counts = df.loc[sel]['name'].value_counts() sel = counts > 1 if sel.sum() > 0: _LOGGER.info('Protein-coding genes with m... |
order.""" try: c = int(chrom) except: if chrom in ['X', 'Y']: return chrom elif chrom == 'MT': return '_MT' # sort to the end else: return '__' + chrom # sort to the very end else: # make sure numbered chromosomes are sorted numerically return '%02d' % c chrom_for_sorting = df['chromosome'].apply(transform_chrom) a = c... |
types:') for i, c in df['type'].value_counts().iteritems(): _LOGGER.info('- %s: %d', i, c) return df |
def get_protein_coding_genes( path_or_buffer, include_polymorphic_pseudogenes=True, remove_duplicates=True, **kwargs): r"""Get list of all protein-coding genes based on Ensembl GTF file. Parameters ---------- See :func:`get_genes` function. Returns ------- `pandas.DataFrame` Table with rows corresponding to protein-cod... |
def get_linc_rna_genes( path_or_buffer, remove_duplicates=True, **kwargs): r"""Get list of all protein-coding genes based on Ensembl GTF file. Parameters ---------- See :func:`get_genes` function. Returns ------- `pandas.DataFrame` Table with rows corresponding to protein-coding genes. """ valid_biotypes = set(['lincRN... |
def payload_generator(levels=0, dimensions=None, sequential=True, string=True, max_int=255, max_pkt_len=150, max_dim_size=3): """ Generates random data in a form of nested lists, to be used as a test packet payload levels - nesting levels: 0 - list of integers (single packet payload) 1 - list of lists of integers (list... |
integer list of random length in the range [1, max_pkt_len] dimensions=5 - list of length 5, each element is an integer list of random length in the range [1, max_pkt_len] dimensions=[2, 3] - list of 2 elements, each element is an integer list, the first one of length 2, the second on of length 3 if level=2: dimensions... |
integer list of random length in the range [1, max_pkt_len] dimensions=[2, 3] - list of 2 elements, each element is a list, the first one of length 2, the second on of length 3, each element of the second level lists is an integer list of random length in the range [1, max_pkt_len] dimensions=[[3, 5], [6, 7, 8]] - list... |
sequential - if True, the payload is a cyclic sequence if integers in the range [0, max_int] if False, the payload is a sequence of random integers in the range [0, max_int] string - if True, the payload is a byte string, e.g. '\x04\x05\x06\x07' as each byte is in the range [0, min(255, max_int)] if False, the payload ... |
= (next_i.i+1)%(MAX_INT+1) return next_i.i next_i.i = 0; def payload(length): ''' Generates payload of given length ''' if (sequential) : pld = [next_i() for _ in xrange(length)] else: pld = [random.randint(0, MAX_INT) for _ in xrange(length)] if string: pld = str(bytearray(pld)) return pld def next_level(level, pld): ... |
got {}".format(level)) pld = copy.deepcopy(dimensions) pld = next_level(levels, pld) return pld |
def getSequence(title, db='nucleotide'): """ Get information about a sequence from Genbank. @param title: A C{str} sequence title from a BLAST hit. Of the form 'gi|63148399|gb|DQ011818.1| Description...'. @param db: The C{str} name of the Entrez database to consult. NOTE: this uses the network! Also, there is a 3 reque... |
def get_ceiling_cloud_layer(self): """ Returns the lowest layer of broken or overcast clouds. :rtype: CloudLayer|None """ lowest_layer = None for layer in self.cloud_layers: if layer.coverage not in [CloudLayer.BROKEN, CloudLayer.OVERCAST]: continue if lowest_layer is None: lowest_layer = layer continue if layer.height... |
def parse_xml_data(self): """ Parses `xml_data` and loads it into object properties. """ self.raw_text = self.xml_data.find('raw_text').text self.station = WeatherStation(self.xml_data.find('station_id').text) self.station.latitude = float(self.xml_data.find('latitude').text) self.station.longitude = float(self.xml_dat... |
def download_data(self, mock_response=None): """ Loads XML data into the `xml_data` attribute. """ if mock_response is not None: body = mock_response else: api_url = self.get_api_url() body = urlopen(api_url).read() xml_root = ElementTree.fromstring(body) xml_warnings = xml_root.find('warnings') if len(xml_warnings.att... |
def summarizeReads(file_handle, file_type): """ open a fasta or fastq file, prints number of of reads, average length of read, total number of bases, longest, shortest and median read, total number and average of individual base (A, T, G, C, N). """ base_counts = defaultdict(int) read_number = 0 total_length = 0 length... |
def sequenceCategoryLengths(read, categories, defaultCategory=None, suppressedCategory='...', minLength=1): """ Summarize the nucleotides or AAs found in a read by assigning each to a category and reporting the lengths of the contiguous category classes found along the sequence. @param read: A C{Read} instance or one o... |
C{list} of 2-C{tuples}. Each tuple contains a (category, count). """ result = [] append = result.append get = categories.get first = True currentCategory = None currentCount = 0 suppressing = False suppressedCount = 0 if minLength < 1: raise ValueError('minLength must be at least 1') for base in read.sequence: thisCate... |
Start suppressing. suppressedCount = currentCount suppressing = True else: if suppressing: append((suppressedCategory, suppressedCount)) suppressedCount = 0 suppressing = False append((currentCategory, currentCount)) currentCategory = thisCategory currentCount = 1 if suppressing: append((suppressedCategory, suppressedC... |
def simplifyTitle(title, target): """ Simplify a given sequence title. Given a title, look for the first occurrence of target anywhere in any of its words. Return a space-separated string of the words of the title up to and including the occurrence of the target. Ignore case. E.g., # Suffix simplifyTitle('Bovine polyom... |
targetLen]) break result.append(word) return ' '.join(result) |
def registerSimulator(self, name=None, hdl=None, analyze_cmd=None, elaborate_cmd=None, simulate_cmd=None): ''' Registers an HDL _simulator name - str, user defined name, used to identify this _simulator record hdl - str, case insensitive, (verilog, vhdl), the HDL to which the simulated MyHDL code will be converted anal... |
ValueError("Invalid hdl {}".format(hdl)) if not isinstance(analyze_cmd, str) or (analyze_cmd.strip() == ""): raise ValueError("Invalid analyzer command") if elaborate_cmd is not None: if not isinstance(elaborate_cmd, str) or (elaborate_cmd.strip() == ""): raise ValueError("Invalid elaborate_cmd command") if not isinsta... |
def _getCosimulation(self, func, **kwargs): ''' Returns a co-simulation instance of func. Uses the _simulator specified by self._simulator. Enables traces if self._trace is True func - MyHDL function to be simulated kwargs - dict of func interface assignments: for signals and parameters ''' vals = {} vals['topname'] = ... |
def _enableTracesVerilog(self, verilogFile): ''' Enables traces in a Verilog file''' fname, _ = os.path.splitext(verilogFile) inserted = False for _, line in enumerate(fileinput.input(verilogFile, inplace = 1)): sys.stdout.write(line) if line.startswith("end") and not inserted: sys.stdout.write('\n\n') sys.stdout.write... |
def _getDut(self, func, **kwargs): ''' Returns a simulation instance of func. Uses the simulator specified by self._simulator. Enables traces if self._trace is True func - MyHDL function to be simulated kwargs - dict of func interface assignments: for signals and parameters ''' if self._simulator=="myhdl": if not self.... |
def iter(self): """ Iterate over the sequences in the files in self.files_, yielding each as an instance of the desired read class. """ for _file in self._files: with asHandle(_file) as fp: # Use FastqGeneralIterator because it provides access to # the unconverted quality string (i.e., it doesn't try to # figure out th... |
def splitFASTA(params): """ Read the FASTA file named params['fastaFile'] and print out its sequences into files named 0.fasta, 1.fasta, etc. with params['seqsPerJob'] sequences per file. """ assert params['fastaFile'][-1] == 'a', ('You must specify a file in ' 'fasta-format that ends in ' '.fasta') fileCount = count =... |
def add_task(self, task): """ Add a task to the scheduler. task: The task to add. """ if not self._valid_name(task.name): raise ValueError(task.name) self._tasks[task.name] = task incomplete_dependencies = set() for dependency in task.dependencies: if not self._valid_name(dependency) or dependency in self._failed: # th... |
def start_task(self, name=None): """ Start a task. Returns the task that was started (or None if no task has been started). name: (optional, None) The task to start. If a name is given, Scheduler will attempt to start the task (and raise an exception if the task doesn't exist or isn't runnable). If no name is given, a ... |
def end_task(self, name, success=True): """ End a running task. Raises an exception if the task isn't running. name: The name of the task to complete. success: (optional, True) Whether the task was successful. """ self._running.remove(name) if success: self._completed.add(name) self._graph.remove(name, strategy=Strateg... |
def fail_remaining(self): """ Mark all unfinished tasks (including currently running ones) as failed. """ self._failed.update(self._graph.nodes) self._graph = Graph() self._running = set() |
def _cascade_failure(self, name): """ Mark a task (and anything that depends on it) as failed. name: The name of the offending task """ if name in self._graph: self._failed.update( self._graph.remove(name, strategy=Strategy.remove) ) else: self._failed.add(name) |
def main(gi, ranges): """ Print the features of the genbank entry given by gi. If ranges is non-emtpy, only print features that include the ranges. gi: either a hit from a BLAST record, in the form 'gi|63148399|gb|DQ011818.1|' or a gi number (63148399 in this example). ranges: a possibly empty list of ranges to print i... |
for feature in record.features: print(feature) |
def create_instance(credentials, project, zone, name, startup_script=None, startup_script_url=None, metadata=None, machine_type='f1-micro', tags=None, disk_size_gb=10, wait_until_done=False): """Create instance with startup script. TODO: docstring""" if startup_script is not None and startup_script_url is not None: rai... |
"READ_WRITE", "autoDelete": True, "deviceName": name, "initializeParams": { "sourceImage": "projects/ubuntu-os-cloud/global/images/ubuntu-1604-xenial-v20170815a", "diskType": "projects/%s/zones/%s/diskTypes/pd-standard" % (project, zone), "diskSizeGb": str(disk_size_gb) } } ], "canIpForward": False, "networkInterfaces"... |
until operation is done...') wait_for_zone_op(access_token, project, zone, op_name) return op_name |
def delete_instance(credentials, project, zone, name, wait_until_done=False): """Delete an instance. TODO: docstring """ access_token = credentials.get_access_token() headers = { 'Authorization': 'Bearer %s' % access_token.access_token } r = requests.delete('https://www.googleapis.com/compute/v1/' 'projects/%s/zones/%s... |
def wait_for_instance_deletion(credentials, project, zone, instance_name, interval_seconds=5): """Wait until an instance is deleted. We require that initially, the specified instance exists. TODO: docstring """ t0 = time.time() access_token = credentials.get_access_token() headers = { 'Authorization': 'Bearer %s' % acc... |
def samReferencesToStr(filenameOrSamfile, indent=0): """ List SAM/BAM file reference names and lengths. @param filenameOrSamfile: Either a C{str} SAM/BAM file name or an instance of C{pysam.AlignmentFile}. @param indent: An C{int} number of spaces to indent each line. @return: A C{str} describing known reference names ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.