code stringlengths 1 18.2k |
|---|
basename(path) if reindex: self._index_file(root, f, domains) else: f = self._make_file_object(root, f) tags = {k: Tag(self.entities[k], v) for k, v in ents.items()} f.tags = tags self.files[f.path] = f for ent, val in f.entities.items(): self.entities[ent].add_file(f.path, val) |
def add_entity(self, domain, **kwargs): ''' Add a new Entity to tracking. ''' # Set the entity's mapping func if one was specified map_func = kwargs.get('map_func', None) if map_func is not None and not callable(kwargs['map_func']): if self.entity_mapper is None: raise ValueError("Mapping function '%s' specified for En... |
def get(self, return_type='tuple', target=None, extensions=None, domains=None, regex_search=None, **kwargs): """ Retrieve files and/or metadata from the current Layout. Args: return_type (str): Type of result to return. Valid values: 'tuple': returns a list of namedtuples containing file name as well as attribute/value... |
files. If None, all available domains are scanned. regex_search (bool or None): Whether to require exact matching (False) or regex search (True) when comparing the query string to each entity. If None (default), uses the value found in self. kwargs (dict): Any optional key/values to filter the entities on. Keys are ent... |
in enumerate(result): f = copy(f) f.path = relpath(f.path, self.root) result[i] = f if return_type == 'file': return natural_sort([f.path for f in result]) if return_type == 'tuple': result = [r.as_named_tuple() for r in result] return natural_sort(result, field='filename') if return_type.startswith('obj'): return resu... |
template to_rep = re.findall('\{(.*?)\}', template) for ent in to_rep: patt = valid_entities[ent].pattern template = template.replace('{%s}' % ent, patt) template += '[^\%s]*$' % os.path.sep matches = [f.dirname for f in result if re.search(template, f.dirname)] return natural_sort(list(set(matches))) else: raise Value... |
def count(self, entity, files=False): """ Return the count of unique values or files for the named entity. Args: entity (str): The name of the entity. files (bool): If True, counts the number of filenames that contain at least one value of the entity, rather than the number of unique values of the entity. """ return se... |
def as_data_frame(self, **kwargs): """ Return information for all Files tracked in the Layout as a pandas DataFrame. Args: kwargs: Optional keyword arguments passed on to get(). This allows one to easily select only a subset of files for export. Returns: A pandas DataFrame, where each row is a file, and each column is ... |
def get_nearest(self, path, return_type='file', strict=True, all_=False, ignore_strict_entities=None, full_search=False, **kwargs): ''' Walk up the file tree from the specified path and return the nearest matching file(s). Args: path (str): The file to search from. return_type (str): What to return; must be one of 'fil... |
all other entities perfectly by passing ignore_strict_entities=['type']. full_search (bool): If True, searches all indexed files, even if they don't share a common root with the provided path. If False, only files that share a common root will be scanned. kwargs: Optional keywords to pass on to .get(). ''' entities = {... |
[] search_paths = [] while True: if path in folders and folders[path]: search_paths.append(path) parent = dirname(path) if parent == path: break path = parent if full_search: unchecked = set(folders.keys()) - set(search_paths) search_paths.extend(path for path in unchecked if folders[path]) for path in search_paths: # ... |
all_ else matches[0] if matches else None |
def build_path(self, source, path_patterns=None, strict=False, domains=None): ''' Constructs a target filename for a file or dictionary of entities. Args: source (str, File, dict): The source data to use to construct the new file path. Must be one of: - A File object - A string giving the path of a File contained withi... |
Optional name(s) of domain(s) to scan for path patterns. If None, all domains are scanned. If two or more domains are provided, the order determines the precedence of path patterns (i.e., earlier domains will have higher precedence). ''' if isinstance(source, six.string_types): if source not in self.files: source = joi... |
def write_contents_to_file(self, entities, path_patterns=None, contents=None, link_to=None, content_mode='text', conflicts='fail', strict=False, domains=None, index=False, index_domains=None): """ Write arbitrary data to a file defined by the passed entities and path patterns. Args: entities (dict): A dictionary of ent... |
to each file copy, starting with 1. Default is 'fail'. strict (bool): If True, all entities must be matched inside a pattern in order to be a valid match. If False, extra entities will be ignored so long as all mandatory entities are found. domains (list): List of Domains to scan for path_patterns. Order determines pre... |
any valid filename for " "the passed entities given available path " "patterns.") write_contents_to_file(path, contents=contents, link_to=link_to, content_mode=content_mode, conflicts=conflicts, root=self.root) if index: # TODO: Default to using only domains that have at least one # tagged entity in the generated file.... |
def configure_logger(name, log_stream=sys.stdout, log_file=None, log_level=logging.INFO, keep_old_handlers=False, propagate=False): """Configures and returns a logger. This function serves to simplify the configuration of a logger that writes to a file and/or to a stream (e.g., stdout). Parameters ---------- name: str ... |
to the logger. The default value is ``False``. propagate: bool, optional If set to ``True``, propagate the loggers messages to the parent logger. The default value is ``False``. Returns ------- `logging.Logger` The logger. Notes ----- Note that if ``log_stream`` and ``log_file`` are both ``None``, no handlers will be c... |
is not None: # create a FileHandler file_handler = logging.FileHandler(log_file) file_handler.setFormatter(formatter) logger.addHandler(file_handler) if log_stream is None and log_file is None: # "no handler" => use NullHandler logger.addHandler(logging.NullHandler()) return logger |
def get_logger(name='', log_stream=None, log_file=None, quiet=False, verbose=False): """Convenience function for getting a logger.""" # configure root logger log_level = logging.INFO if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG if log_stream is None: log_stream = sys.stdout new_logger =... |
def start(milliseconds, func, *args, **kwargs): """ Call function every interval. Starts the timer at call time. Although this could also be a decorator, that would not initiate the time at the same time, so would require additional work. Arguments following function will be sent to function. Note that these args are p... |
time.sleep(6) TickTock 1.. TickTock 2.. TickTock 3.. """ stopper = threading.Event() def interval(seconds, func, *args, **kwargs): """outer wrapper""" def wrapper(): """inner wrapper""" if stopper.isSet(): return interval(seconds, func, *args, **kwargs) try: func(*args, **kwargs) except: # pylint: disable=bare-except l... |
def codonInformation(codons1, codons2): """ Take two C{list} of codons, and returns information about the min and max distance between them. @param codon1: a C{list} of codons. @param codon2: a C{list} of codons. @return: a dict whose keys are C{int} distances and whose values are lists of pairs of codons. """ result =... |
def example_async_client(api_client): """Example async client. """ try: pprint((yield from api_client.echo())) except errors.RequestError as exc: log.exception('Exception occurred: %s', exc) yield gen.Task(lambda *args, **kwargs: ioloop.IOLoop.current().stop()) |
def example_sync_client(api_client): """Example sync client use with. """ try: pprint(api_client.echo()) except errors.RequestError as exc: log.exception('Exception occurred: %s', exc) |
def main(): """Run the examples. """ logging.basicConfig(level=logging.INFO) example_sync_client(SyncAPIClient()) example_async_client(AsyncAPIClient()) io_loop = ioloop.IOLoop.current() io_loop.start() |
def main(args=None): """Extract protein-coding genes 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 Exit code (... |
if output_file == '-': # if we print output to stdout, redirect log messages to stderr log_stream = sys.stderr logger = misc.get_logger(log_stream=log_stream, log_file=log_file, quiet=quiet, verbose=verbose) #if chrom_pat is None: # chrom_pat = ensembl.SPECIES_CHROMPAT[species] if chrom_pat is not None: logger.info('Re... |
def read_stats(self, *stats): """ Read port statistics from chassis. :param stats: list of requested statistics to read, if empty - read all statistics. """ self.statistics = OrderedDict() for port in self.ports: port_stats = IxeStatTotal(port).get_attributes(FLAG_RDONLY, *stats) port_stats.update({c + '_rate': v for c... |
def read_stats(self, *stats): """ Read stream statistics from chassis. :param stats: list of requested statistics to read, if empty - read all statistics. """ from ixexplorer.ixe_stream import IxePacketGroupStream sleep_time = 0.1 # in cases we only want few counters but very fast we need a smaller sleep time if not st... |
= IxePacketGroupStream(stream).groupId stream_stats_pg = pg_stats_dict() for port in self.session.ports.values(): stream_stats_pg[str(port)] = OrderedDict(zip(stats, [-1] * len(stats))) for rx_port in self.rx_ports: if not stream.rx_ports or rx_port in stream.rx_ports: rx_port.api.call_rc('packetGroupStats get {} 0 655... |
def arbiter(rst, clk, req_vec, gnt_vec=None, gnt_idx=None, gnt_vld=None, gnt_rdy=None, ARBITER_TYPE="priority"): ''' Wrapper that provides common interface to all arbiters ''' if ARBITER_TYPE == "priority": _arb = arbiter_priority(req_vec, gnt_vec, gnt_idx, gnt_vld) elif (ARBITER_TYPE == "roundrobin"): _arb = arbiter_r... |
def arbiter_priority(req_vec, gnt_vec=None, gnt_idx=None, gnt_vld=None): """ Static priority arbiter: grants the request with highest priority, which is the lower index req_vec - (i) vector of request signals, req_vec[0] is with the highest priority gnt_vec - (o) optional, vector of grants, one grant per request, only ... |
if gnt_idx!=None: _idx = assign(gnt_idx, gnt_idx_s) if gnt_vld!=None: _vld = assign(gnt_vld, gnt_vld_s) return instances() |
def arbiter_roundrobin(rst, clk, req_vec, gnt_vec=None, gnt_idx=None, gnt_vld=None, gnt_rdy=None): """ Round Robin arbiter: finds the active request with highest priority and presents its index on the gnt_idx output. req_vec - (i) vector of request signals, priority changes dynamically gnt_vec - (o) optional, vector of... |
the highest priority. gnt_rdy should be activated in the same clock cycle when output the grant is used """ REQ_NUM = len(req_vec) ptr = Signal(intbv(0, min=0, max=REQ_NUM)) gnt_vec_s = Signal(intbv(0)[REQ_NUM:]) gnt_idx_s = Signal(intbv(0, min=0, max=REQ_NUM)) gnt_vld_s = Signal(bool(0)) @always(clk.posedge) def ptr_p... |
def seq_seqhash(seq, normalize=True): """returns 24-byte Truncated Digest sequence `seq` >>> seq_seqhash("") 'z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXc' >>> seq_seqhash("ACGT") 'aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2' >>> seq_seqhash("acgt") 'aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2' >>> seq_seqhash("acgt", normalize=False) 'eFwawHHdibaZBDcs... |
def seq_seguid(seq, normalize=True): """returns seguid for sequence `seq` This seguid is compatible with BioPython's seguid. >>> seq_seguid('') '2jmj7l5rSw0yVb/vlWAYkK/YBwk' >>> seq_seguid('ACGT') 'IQiZThf2zKn/I1KtqStlEdsHYDQ' >>> seq_seguid('acgt') 'IQiZThf2zKn/I1KtqStlEdsHYDQ' >>> seq_seguid('acgt', normalize=False) ... |
def seq_md5(seq, normalize=True): """returns unicode md5 as hex digest for sequence `seq`. >>> seq_md5('') 'd41d8cd98f00b204e9800998ecf8427e' >>> seq_md5('ACGT') 'f1f8f4bf413b16ad135722aa4591043e' >>> seq_md5('ACGT*') 'f1f8f4bf413b16ad135722aa4591043e' >>> seq_md5(' A C G T ') 'f1f8f4bf413b16ad135722aa4591043e' >>> seq... |
def seq_sha1(seq, normalize=True): """returns unicode sha1 hexdigest for sequence `seq`. >>> seq_sha1('') 'da39a3ee5e6b4b0d3255bfef95601890afd80709' >>> seq_sha1('ACGT') '2108994e17f6cca9ff2352ada92b6511db076034' >>> seq_sha1('acgt') '2108994e17f6cca9ff2352ada92b6511db076034' >>> seq_sha1('acgt', normalize=False) '9482... |
def seq_sha512(seq, normalize=True): """returns unicode sequence sha512 hexdigest for sequence `seq`. >>> seq_sha512('') 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e' >>> seq_sha512('ACGT') '68a178f7c740c5c240aa67ba41843b119d3bf9f8b0f0... |
def seq_vmc_identifier(seq, normalize=True): """returns VMC identifier (record) for sequence `seq` See https://github.com/ga4gh/vmc >>> seq_vmc_identifier("") == {'namespace': 'VMC', 'accession': 'GS_z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXc'} True >>> seq_vmc_identifier("ACGT") == {'namespace': 'VMC', 'accession': 'GS_aKF498dA... |
def map_single_end(credentials, instance_config, instance_name, script_dir, index_dir, fastq_file, output_dir, num_threads=None, seed_start_lmax=None, mismatch_nmax=None, multimap_nmax=None, splice_min_overhang=None, out_mult_nmax=None, sort_bam=True, keep_unmapped=False, self_destruct=True, compressed=True, **kwargs):... |
bytes!') #print(startup_script) op_name = instance_config.create_instance( credentials, instance_name, startup_script=startup_script, **kwargs) return op_name |
def generate_index(credentials, instance_config, instance_name, script_dir, genome_file, output_dir, annotation_file=None, splice_overhang=100, num_threads=8, chromosome_bin_bits=18, genome_memory_limit=31000000000, self_destruct=True, **kwargs): """Generates a STAR index. Recommended machine type: "n1-highmem-8" (52 G... |
def fifo(rst, clk, full, we, din, empty, re, dout, afull=None, aempty=None, afull_th=None, aempty_th=None, ovf=None, udf=None, count=None, count_max=None, depth=None, width=None): """ Synchronous FIFO Input interface: full, we, din Output interface: empty, re, dout It s possible to set din and dout to None. Then the fi... |
fifo cells count_max (o) - max number of occupied fifo cells reached since the last reset ovf (o) - overflow flag, set at the first write in a full fifo, cleared at reset udf (o) - underflow flag, set at the first read from an empty fifo, cleared at reset Parameters: depth - fifo depth, must be >= 1; if not set or set ... |
rd_ptr = Signal(intbv(0, min=0, max=depth)) rd_ptr_new = Signal(intbv(0, min=0, max=depth)) wr_ptr = Signal(intbv(0, min=0, max=depth)) wr_ptr_new = Signal(intbv(0, min=0, max=depth)) @always_comb def safe_read_write(): full.next = full_flg empty.next = empty_flg we_safe.next = we and not full_flg re_safe.next = re and... |
== rd_ptr)): full_flg.next = 1 #=========================================================================== # Count, CountMax #=========================================================================== ''' Count ''' if (count != None) or (count_max != None) or (afull != None) or (aempty != None): count_r = Signal(intb... |
= count_max_r #=========================================================================== # AlmostFull, AlmostEmpty #=========================================================================== ''' AlmostFull flag ''' if (afull != None): if (afull_th == None): afull_th = depth//2 @always(clk.posedge) def afull_proc(): ... |
Signal(bool(0)) mem_addrw = Signal(intbv(0, min=0, max=depth)) mem_addrr = Signal(intbv(0, min=0, max=depth)) mem_di = Signal(intbv(0)[width:0]) mem_do = Signal(intbv(0)[width:0]) # RAM: Simple-Dual-Port, Asynchronous read mem = ram_sdp_ar( clk = clk, we = mem_we, addrw = mem_addrw, addrr = mem_addrr, di = mem_di, do =... |
def get_file_checksums(url, ftp=None): """Download and parse an Ensembl CHECKSUMS file and obtain checksums. Parameters ---------- url : str The URL of the CHECKSUM file. ftp : `ftplib.FTP` or `None`, optional An FTP connection. Returns ------- `collections.OrderedDict` An ordered dictionary containing file names as ke... |
d in data: file_name = d[(d.rindex(' ') + 1):] sum_ = int(d[:d.index(' ')]) file_checksums[file_name] = sum_ logger.debug('Obtained checksums for %d files', len(file_checksums)) # close FTP connection if we opened it if close_connection: ftp.close() return file_checksums |
def listify(obj, ignore=(list, tuple, type(None))): ''' Wraps all non-list or tuple objects in a list; provides a simple way to accept flexible arguments. ''' return obj if isinstance(obj, ignore) else [obj] |
def _get_divisions(taxdump_file): """Returns a dictionary mapping division names to division IDs.""" with tarfile.open(taxdump_file) as tf: with tf.extractfile('division.dmp') as fh: df = pd.read_csv(fh, header=None, sep='|', encoding='ascii') # only keep division ids and names df = df.iloc[:, [0, 2]] # remove tab char... |
def _get_species_taxon_ids(taxdump_file, select_divisions=None, exclude_divisions=None): """Get a list of species taxon IDs (allow filtering by division).""" if select_divisions and exclude_divisions: raise ValueError('Cannot specify "select_divisions" and ' '"exclude_divisions" at the same time.') select_division_ids ... |
= df.iloc[:, 1].str.strip('\t') # get taxon IDs for all species taxon_ids = df.iloc[:, 0].loc[df.iloc[:, 1] == 'species'].values return taxon_ids |
def get_species(taxdump_file, select_divisions=None, exclude_divisions=None, nrows=None): """Get a dataframe with species information.""" if select_divisions and exclude_divisions: raise ValueError('Cannot specify "select_divisions" and ' '"exclude_divisions" at the same time.') select_taxon_ids = _get_species_taxon_id... |
2] == 'common name'] for _, row in cn.iterrows(): common_names[row.iloc[0]].append(row.iloc[1]) # build final dataframe (this is very slow) sn = df.loc[df.iloc[:, 2] == 'scientific name'] species = [] for i, row in sn.iterrows(): species.append([row.iloc[0], row.iloc[1], '|'.join(common_names[row.iloc[0]])]) species_df... |
def set_attributes(self, **attributes): """ Set group of attributes without calling set between attributes regardless of global auto_set. Set will be called only after all attributes are set based on global auto_set. :param attributes: dictionary of <attribute, value> to set. """ auto_set = IxeObject.get_auto_set() Ixe... |
def consensusSequence(recordFilename, hitId, fastaFilename, eCutoff=None, db='nt', actualSequenceId=None): """ Build a consensus sequence against a target sequence. recordFilename: the BLAST XML output file. hitId: the str sequence id to examine the BLAST output for hits against. fastaFilename: The name of the FASTA fi... |
= summarizeHits(allhits, fastaFilename, eCutoff=eCutoff) minX, maxX = summary['minX'], summary['maxX'] if actualSequenceId: # UNUSED. # actualSequence = getSequence(actualSequenceId, db) pass print(summary['hitCount']) print('seq len =', len(sequence)) fasta = summary['fasta'] # The length of the consensus depends on w... |
index in range(hsp['subjectStart'], hsp['subjectEnd']): queryIndex = index - hsp['queryStart'] match.append('.' if query[queryIndex] == sequence[index] else '*') print(' match: %s%s' % ( ' ' * (hsp['subjectStart'] - hsp['queryStart']), ''.join(match))) print(' score:', item['convertedE']) print(' match len:', hsp['subj... |
# There's nothing left in the consensus, so we're done. break for index in range(len(sequence), maxX): consensusIndex = index - minX if consensus[consensusIndex]: print('%d: %r' % (index, consensus[consensusIndex])) stop = time() report('Consensus sequence generated in %.3f mins.' % ((stop - start) / 60.0)) return summ... |
def detalhe(self, posicao=0): """Retorna o detalhe de um CEP da última lista de resultados""" handle = self._url_open('detalheCEPAction.do', {'Metodo': 'detalhe', 'TipoCep': 2, 'Posicao': posicao + 1, 'CEP': ''}) html = handle.read() return self._parse_detalhe(html) |
def consulta_faixa(self, localidade, uf): """Consulta site e retorna faixa para localidade""" url = 'consultaFaixaCepAction.do' data = { 'UF': uf, 'Localidade': localidade.encode('cp1252'), 'cfm': '1', 'Metodo': 'listaFaixaCEP', 'TipoConsulta': 'faixaCep', 'StartRow': '1', 'EndRow': '10', } html = self._url_open(url, d... |
def consulta(self, endereco, primeiro=False, uf=None, localidade=None, tipo=None, numero=None): """Consulta site e retorna lista de resultados""" if uf is None: url = 'consultaEnderecoAction.do' data = { 'relaxation': endereco.encode('ISO-8859-1'), 'TipoCep': 'ALL', 'semelhante': 'N', 'cfm': 1, 'Metodo': 'listaLogradou... |
def _request(self, url, *, method='GET', headers=None, data=None, result_callback=None): """Perform synchronous request. :param str url: request URL. :param str method: request method. :param object data: JSON-encodable object. :param object -> object result_callback: result callback. :rtype: dict :raise: APIError """ ... |
err: raise MalformedResponse(err) from None return response.content except (requests.exceptions.RequestException, requests.exceptions.BaseHTTPError) as exc: if self._conn_retries is None or retries_left <= 0: raise CommunicationError(exc) from None else: retries_left -= 1 retry_in = (self._conn_retries - retries_left) ... |
def _make_session(): """Create session object. :rtype: requests.Session """ sess = requests.Session() sess.mount('http://', requests.adapters.HTTPAdapter(max_retries=False)) sess.mount('https://', requests.adapters.HTTPAdapter(max_retries=False)) return sess |
def get_clinical_data(tcga_id): """Get clinical data for a TCGA project. Parameters ---------- tcga_id : str The TCGA project ID. Returns ------- `pandas.DataFrame` The clinical data.abs Notes ----- Clinical data is associated with individual cases (patients). These correspond to rows in the returned data frame, and ar... |
clinical[tcga_id] = diag logger.info('Found clinical data for %d cases.', valid) df = pd.DataFrame.from_dict(clinical).T df.sort_index(inplace=True) return df |
def get_biospecimen_data(tcga_id): """Get biospecimen data for a TCGA project. Parameters ---------- tcga_id : str The TCGA project ID. Returns ------- `pandas.DataFrame` The biospecmin data. Notes ----- Biospecimen data is associated with individual vials. TCGA vials correspond to portions of a sample, and are uniquel... |
= requests.get('https://gdc-api.nci.nih.gov/cases', params=payload) j = json.loads(r.content.decode()) biospec = {} valid = 0 for case in j: if 'samples' not in case: continue valid += 1 for s in case['samples']: tcga_id = s['submitter_id'][:16] del s['portions'] del s['submitter_id'] biospec[tcga_id] = s logger.info('... |
def get_masked_cnv_manifest(tcga_id): """Get manifest for masked TCGA copy-number variation data. Params ------ tcga_id : str The TCGA project ID. download_file : str The path of the download file. Returns ------- `pandas.DataFrame` The manifest. """ payload = { "filters": json.dumps({ "op": "and", "content" : [ { "op"... |
def get_file_samples(file_ids): """Get TCGA associated sample barcodes for a list of file IDs. Params ------ file_ids : Iterable The file IDs. Returns ------- `pandas.Series` Series containing file IDs as index and corresponding sample barcodes. """ assert isinstance(file_ids, Iterable) # query TCGA API to get sample b... |
def get_unique_sample_files(file_samples): """Filter file_sample data frame to only keep one file per sample. Params ------ file_samples : `pandas.DataFrame` A data frame containing a mapping between file IDs and sample barcodes. This type of data frame is returned by :meth:`get_file_samples`. Returns ------- `pandas.D... |
logger.info('Number of files after removing duplicates from different ' 'aliquots: %d', len(df.index)) # - some samples also have multiple files corresponding to different vials # add an auxilliary column that contains the sample barcode without the # vial tag (first 15 characters) df['sample_barcode15'] = df['sample_b... |
def get_fresh_primary_tumors(biospecimen): """Filter biospecimen data to only keep non-FFPE primary tumor samples. Parameters ---------- biospecimen : `pandas.DataFrame` The biospecimen data frame. This type of data frame is returned by :meth:`get_biospecimen_data`. Returns ------- `pandas.DataFrame` The filtered data ... |
def dedupFasta(reads): """ Remove sequence duplicates (based on sequence) from FASTA. @param reads: a C{dark.reads.Reads} instance. @return: a generator of C{dark.reads.Read} instances with no duplicates. """ seen = set() add = seen.add for read in reads: hash_ = md5(read.sequence.encode('UTF-8')).digest() if hash_ not... |
def dePrefixAndSuffixFasta(sequences): """ sequences: an iterator producing Bio.Seq sequences. return: a generator of sequences with no duplicates and no fully contained subsequences. """ sequences = sorted(sequences, key=lambda s: len(s.seq), reverse=True) seen = set() for s in sequences: thisSeq = str(s.seq) thisHash... |
def fastaSubtract(fastaFiles): """ Given a list of open file descriptors, each with FASTA content, remove the reads found in the 2nd, 3rd, etc files from the first file in the list. @param fastaFiles: a C{list} of FASTA filenames. @raises IndexError: if passed an empty list. @return: An iterator producing C{Bio.SeqReco... |
def combineReads(filename, sequences, readClass=DNARead, upperCase=False, idPrefix='command-line-read-'): """ Combine FASTA reads from a file and/or sequence strings. @param filename: A C{str} file name containing FASTA reads. @param sequences: A C{list} of C{str} sequences. If a sequence contains spaces, the last fiel... |
file, if given. So output might be ambiguous. That's why we allow the caller to specify a custom prefix. @return: A C{FastaReads} instance. """ # Read sequences from a FASTA file, if given. if filename: reads = FastaReads(filename, readClass=readClass, upperCase=upperCase) else: reads = Reads() # Add any individually s... |
def iter(self): """ Iterate over the sequences in the files in self.files_, yielding each as an instance of the desired read class. """ count = 0 for _file in self._files: with asHandle(_file) as fp: # Duplicate some code here so as not to test # self._upperCase in the loop. if self._upperCase: for seq in SeqIO.parse(f... |
def iter(self): """ Iterate over the sequences in the files in self.files_, yielding each as an instance of the desired read class. """ if self._upperCase: for id_ in self._fasta: yield self._readClass(id_, str(self._fasta[id_]).upper()) else: for id_ in self._fasta: yield self._readClass(id_, str(self._fasta[id_])) |
def _getFilename(self, fileNumber): """ Given a file number, get its name (if any). @param fileNumber: An C{int} file number. @return: A C{str} file name or C{None} if a file with that number has not been added. """ cur = self._connection.cursor() cur.execute('SELECT name FROM files WHERE id = ?', (fileNumber,)) row = ... |
def _getFileNumber(self, filename): """ Given a file name, get its file number (if any). @param filename: A C{str} file name. @return: An C{int} file number or C{None} if no file with that name has been added. """ cur = self._connection.cursor() cur.execute('SELECT id FROM files WHERE name = ?', (filename,)) row = cur.... |
def _addFilename(self, filename): """ Add a new file name. @param filename: A C{str} file name. @raise ValueError: If a file with this name has already been added. @return: The C{int} id of the newly added file. """ cur = self._connection.cursor() try: cur.execute('INSERT INTO files(name) VALUES (?)', (filename,)) exce... |
def addFile(self, filename): """ Add a new FASTA file of sequences. @param filename: A C{str} file name, with the file in FASTA format. This file must (obviously) exist at indexing time. When __getitem__ is used to access sequences, it is possible to provide a C{fastaDirectory} argument to our C{__init__} to indicate t... |
C{int} number of sequences added from the file. """ endswith = filename.lower().endswith if endswith('.bgz') or endswith('.gz'): useBgzf = True elif endswith('.bz2'): raise ValueError( 'Compressed FASTA is only supported in BGZF format. Use ' 'bgzip to compresss your FASTA.') else: useBgzf = False fileNumber = self._ad... |
else: with open(filename) as fp: offset = 0 for line in fp: offset += len(line) if line[0] == '>': count += 1 id_ = line[1:].rstrip(' \t\n\r') connection.execute( 'INSERT INTO sequences(id, fileNumber, ' 'offset) VALUES (?, ?, ?)', (id_, fileNumber, offset)) except sqlite3.IntegrityError as e: if str(e).find('UNIQUE co... |
raise else: return count |
def _find(self, id_): """ Find the filename and offset of a sequence, given its id. @param id_: A C{str} sequence id. @return: A 2-tuple, containing the C{str} file name and C{int} offset within that file of the sequence. """ cur = self._connection.cursor() cur.execute( 'SELECT fileNumber, offset FROM sequences WHERE i... |
def parse_attributes(s): """ Parses the ``attribute`` string of a GFF/GTF annotation. Parameters ---------- s : str The attribute string. Returns ------- dict A dictionary containing attribute name/value pairs. Notes ----- The ``attribute`` string is the 9th field of each annotation (row), as described in the `GTF form... |
def printBlastRecordForDerek(record): """ This is a hacked version of printBlastRecord that I wrote in Addenbrookes hospital so Derek could try hacking on the reads that had low e values. It's called by bin/print-blast-xml-for-derek.py """ if len(record.alignments) == 0: return 0 if record.descriptions[0].e > 1e-120: r... |
def splitNames(names): """ Split a sequence id string like "Protein name [pathogen name]" into two pieces using the final square brackets to delimit the pathogen name. @param names: A C{str} "protein name [pathogen name]" string. @return: A 2-C{tuple} giving the C{str} protein name and C{str} pathogen name. If C{names}... |
def getPathogenProteinCounts(filenames): """ Get the number of proteins for each pathogen in C{filenames}. @param filenames: Either C{None} or a C{list} of C{str} FASTA file names. If C{None} an empty C{Counter} is returned. If FASTA file names are given, their sequence ids should have the format used in the NCBI bacte... |
def add(self, pathogenName, sampleName): """ Add a (pathogen name, sample name) combination and get its FASTA/FASTQ file name and unique read count. Write the FASTA/FASTQ file if it does not already exist. Save the unique read count into C{self._proteinGrouper}. @param pathogenName: A C{str} pathogen name. @param sampl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.