Search is not available for this dataset
text
stringlengths
75
104k
def npz_generator(npz_path): """Generate data from an npz file.""" npz_data = np.load(npz_path) X = npz_data['X'] # Y is a binary maxtrix with shape=(n, k), each y will have shape=(k,) y = npz_data['Y'] n = X.shape[0] while True: i = np.random.randint(0, n) yield {'X': X[i]...
def phyper(k, good, bad, N): """ Current hypergeometric implementation in scipy is broken, so here's the correct version """ pvalues = [phyper_single(x, good, bad, N) for x in range(k + 1, N + 1)] return np.sum(pvalues)
def write_equalwidth_bedfile(bedfile, width, outfile): """Read input from <bedfile>, set the width of all entries to <width> and write the result to <outfile>. Input file needs to be in BED or WIG format.""" BUFSIZE = 10000 f = open(bedfile) out = open(outfile, "w") lines = f.readlines(BUF...
def calc_motif_enrichment(sample, background, mtc=None, len_sample=None, len_back=None): """Calculate enrichment based on hypergeometric distribution""" INF = "Inf" if mtc not in [None, "Bonferroni", "Benjamini-Hochberg", "None"]: raise RuntimeError("Unknown correction: %s" % mtc) sig = ...
def parse_cutoff(motifs, cutoff, default=0.9): """ Provide either a file with one cutoff per motif or a single cutoff returns a hash with motif id as key and cutoff as value """ cutoffs = {} if os.path.isfile(str(cutoff)): for i,line in enumerate(open(cutoff)): if line !...
def determine_file_type(fname): """ Detect file type. The following file types are supported: BED, narrowPeak, FASTA, list of chr:start-end regions If the extension is bed, fa, fasta or narrowPeak, we will believe this without checking! Parameters ---------- fname : str Fil...
def get_seqs_type(seqs): """ automagically determine input type the following types are detected: - Fasta object - FASTA file - list of regions - region file - BED file """ region_p = re.compile(r'^(.+):(\d+)-(\d+)$') if isinstance(seqs, Fasta): re...
def file_checksum(fname): """Return md5 checksum of file. Note: only works for files < 4GB. Parameters ---------- filename : str File used to calculate checksum. Returns ------- checkum : str """ size = os.path.getsize(fname) with open(fname, "r+") as f: ...
def download_annotation(genomebuild, gene_file): """ Download gene annotation from UCSC based on genomebuild. Will check UCSC, Ensembl and RefSeq annotation. Parameters ---------- genomebuild : str UCSC genome name. gene_file : str Output file name. """ pred_bin = ...
def _check_dir(self, dirname): """ Check if dir exists, if not: give warning and die""" if not os.path.exists(dirname): print("Directory %s does not exist!" % dirname) sys.exit(1)
def _make_index(self, fasta, index): """ Index a single, one-sequence fasta-file""" out = open(index, "wb") f = open(fasta) # Skip first line of fasta-file line = f.readline() offset = f.tell() line = f.readline() while line: out.write(pack(sel...
def create_index(self,fasta_dir=None, index_dir=None): """Index all fasta-files in fasta_dir (one sequence per file!) and store the results in index_dir""" # Use default directories if they are not supplied if not fasta_dir: fasta_dir = self.fasta_dir if not...
def _read_index_file(self): """read the param_file, index_dir should already be set """ param_file = os.path.join(self.index_dir, self.param_file) with open(param_file) as f: for line in f.readlines(): (name, fasta_file, index_file, line_size, total_size) = line.strip...
def _read_seq_from_fasta(self, fasta, offset, nr_lines): """ retrieve a number of lines from a fasta file-object, starting at offset""" fasta.seek(offset) lines = [fasta.readline().strip() for _ in range(nr_lines)] return "".join(lines)
def get_sequences(self, chr, coords): """ Retrieve multiple sequences from same chr (RC not possible yet)""" # Check if we have an index_dir if not self.index_dir: print("Index dir is not defined!") sys.exit() # retrieve all information for this specific sequ...
def get_sequence(self, chrom, start, end, strand=None): """ Retrieve a sequence """ # Check if we have an index_dir if not self.index_dir: print("Index dir is not defined!") sys.exit() # retrieve all information for this specific sequence fasta_file =...
def get_size(self, chrom=None): """ Return the sizes of all sequences in the index, or the size of chrom if specified as an optional argument """ if len(self.size) == 0: raise LookupError("no chromosomes in index, is the index correct?") if chrom: if chrom in sel...
def get_tool(name): """ Returns an instance of a specific tool. Parameters ---------- name : str Name of the tool (case-insensitive). Returns ------- tool : MotifProgram instance """ tool = name.lower() if tool not in __tools__: raise ValueError("Tool {0} n...
def locate_tool(name, verbose=True): """ Returns the binary of a tool. Parameters ---------- name : str Name of the tool (case-insensitive). Returns ------- tool_bin : str Binary of tool. """ m = get_tool(name) tool_bin = which(m.cmd) if tool_bin: ...
def bin(self): """ Get the command used to run the tool. Returns ------- command : str The tool system command. """ if self.local_bin: return self.local_bin else: return self.config.bin(self.name)
def is_installed(self): """ Check if the tool is installed. Returns ------- is_installed : bool True if the tool is installed. """ return self.is_configured() and os.access(self.bin(), os.X_OK)
def run(self, fastafile, params=None, tmp=None): """ Run the tool and predict motifs from a FASTA file. Parameters ---------- fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools require...
def _parse_params(self, params=None): """ Parse parameters. Combine default and user-defined parameters. """ prm = self.default_params.copy() if params is not None: prm.update(params) if prm["background"]: # Absolute path, just to be su...
def _run_program(self, bin, fastafile, params=None): """ Run XXmotif and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict,...
def _parse_params(self, params=None): """ Parse parameters. Combine default and user-defined parameters. """ prm = self.default_params.copy() if params is not None: prm.update(params) # Background file is essential! if not prm["background"]...
def _run_program(self, bin, fastafile, params=None): """ Run Homer and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, o...
def parse(self, fo): """ Convert BioProspector output to motifs Parameters ---------- fo : file-like File object containing BioProspector output. Returns ------- motifs : list List of Motif instances. """ m...
def _run_program(self, bin, fastafile, params=None): """ Run HMS and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, opt...
def parse(self, fo): """ Convert HMS output to motifs Parameters ---------- fo : file-like File object containing HMS output. Returns ------- motifs : list List of Motif instances. """ motifs = [] m...
def _run_program(self, bin, fastafile, params=None): """ Run AMD and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, opt...
def parse(self, fo): """ Convert AMD output to motifs Parameters ---------- fo : file-like File object containing AMD output. Returns ------- motifs : list List of Motif instances. """ motifs = [] ...
def parse(self, fo): """ Convert Improbizer output to motifs Parameters ---------- fo : file-like File object containing Improbizer output. Returns ------- motifs : list List of Motif instances. """ motifs ...
def _run_program(self, bin, fastafile, params=None): """ Run Trawler and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict,...
def _run_program(self, bin,fastafile, params=None): """ Run Weeder and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, o...
def _parse_params(self, params=None): """ Parse parameters. Combine default and user-defined parameters. """ prm = self.default_params.copy() if params is not None: prm.update(params) if prm["background_model"]: # Absolute path, just to...
def _run_program(self, bin, fastafile, params=None): """ Run MotifSampler and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : ...
def parse(self, fo): """ Convert MotifSampler output to motifs Parameters ---------- fo : file-like File object containing MotifSampler output. Returns ------- motifs : list List of Motif instances. """ mot...
def parse_out(self, fo): """ Convert MotifSampler output to motifs Parameters ---------- fo : file-like File object containing MotifSampler output. Returns ------- motifs : list List of Motif instances. """ ...
def _run_program(self, bin, fastafile, params=None): """ Run MDmodule and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict...
def parse(self, fo): """ Convert MDmodule output to motifs Parameters ---------- fo : file-like File object containing MDmodule output. Returns ------- motifs : list List of Motif instances. """ motifs = []...
def _parse_params(self, params=None): """ Parse parameters. Combine default and user-defined parameters. """ prm = self.default_params.copy() if params is not None: prm.update(params) return prm
def _run_program(self, bin, fastafile, params=None): """ Run ChIPMunk and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict...
def parse(self, fo): """ Convert ChIPMunk output to motifs Parameters ---------- fo : file-like File object containing ChIPMunk output. Returns ------- motifs : list List of Motif instances. """ #KDIC|6.124...
def _run_program(self, bin, fastafile, params=None): """ Run Posmo and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, o...
def parse(self, fo, width, seed=None): """ Convert Posmo output to motifs Parameters ---------- fo : file-like File object containing Posmo output. Returns ------- motifs : list List of Motif instances. """ ...
def parse(self, fo): """ Convert GADEM output to motifs Parameters ---------- fo : file-like File object containing GADEM output. Returns ------- motifs : list List of Motif instances. """ motifs = [] ...
def _run_program(self, bin, fastafile, params=None): """ Get enriched JASPAR motifs in a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optio...
def _run_program(self, bin, fastafile, params=None): """ Run MEME and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, op...
def parse(self, fo): """ Convert MEME output to motifs Parameters ---------- fo : file-like File object containing MEME output. Returns ------- motifs : list List of Motif instances. """ motifs = [] ...
def scan_to_table(input_table, genome, scoring, pwmfile=None, ncpus=None): """Scan regions in input table with motifs. Parameters ---------- input_table : str Filename of input table. Can be either a text-separated tab file or a feather file. genome : str Genome name. C...
def run_maelstrom(infile, genome, outdir, pwmfile=None, plot=True, cluster=False, score_table=None, count_table=None, methods=None, ncpus=None): """Run maelstrom on an input table. Parameters ---------- infile : str Filename of input table. Can be either a text-separated tab file o...
def plot_heatmap(self, kind="final", min_freq=0.01, threshold=2, name=True, max_len=50, aspect=1, **kwargs): """Plot clustered heatmap of predicted motif activity. Parameters ---------- kind : str, optional Which data type to use for plotting. Default is 'final', whi...
def plot_scores(self, motifs, name=True, max_len=50): """Create motif scores boxplot of different clusters. Motifs can be specified as either motif or factor names. The motif scores will be scaled and plotted as z-scores. Parameters ---------- motifs : iterable o...
def get_version(package, url_pattern=URL_PATTERN): """Return version of package on pypi.python.org using json. Adapted from https://stackoverflow.com/a/34366589""" req = requests.get(url_pattern.format(package=package)) version = parse('0') if req.status_code == requests.codes.ok: # j = json.loa...
def get_args(parser): """ Converts arguments extracted from a parser to a dict, and will dismiss arguments which default to NOT_SET. :param parser: an ``argparse.ArgumentParser`` instance. :type parser: argparse.ArgumentParser :return: Dictionary with the configs found in the parsed CLI argumen...
def parse_value(val, parsebool=False): """Parse input string and return int, float or str depending on format. @param val: Input string. @param parsebool: If True parse yes / no, on / off as boolean. @return: Value of type int, float or str. """ try: return i...
def socket_read(fp): """Buffered read from socket. Reads all data available from socket. @fp: File pointer for socket. @return: String of characters read from buffer. """ response = '' oldlen = 0 newlen = 0 while True: response += fp.read(buffSize) newlen = ...
def exec_command(args, env=None): """Convenience function that executes command and returns result. @param args: Tuple of command and arguments. @param env: Dictionary of environment variables. (Environment is not modified if None.) @return: Command output. """ t...
def set_nested(self, klist, value): """D.set_nested((k1, k2,k3, ...), v) -> D[k1][k2][k3] ... = v""" keys = list(klist) if len(keys) > 0: curr_dict = self last_key = keys.pop() for key in keys: if not curr_dict.has_key(key) or not isinstance(cu...
def registerFilter(self, column, patterns, is_regex=False, ignore_case=False): """Register filter on a column of table. @param column: The column name. @param patterns: A single pattern or a list of patterns used for matching ...
def unregisterFilter(self, column): """Unregister filter on a column of the table. @param column: The column header. """ if self._filters.has_key(column): del self._filters[column]
def registerFilters(self, **kwargs): """Register multiple filters at once. @param **kwargs: Multiple filters are registered using keyword variables. Each keyword must correspond to a field name with an optional suffix: ...
def applyFilters(self, headers, table): """Apply filter on ps command result. @param headers: List of column headers. @param table: Nested list of rows and columns. @return: Nested list of rows and columns filtered using registered filters. ...
def open(self, host=None, port=0, socket_file=None, timeout=socket.getdefaulttimeout()): """Connect to a host. With a host argument, it connects the instance using TCP; port number and timeout are optional, socket_file must be None. The port number defaults to the standar...
def analyze(egg, subjgroup=None, listgroup=None, subjname='Subject', listname='List', analysis=None, position=0, permute=False, n_perms=1000, parallel=False, match='exact', distance='euclidean', features=None, ts=None): """ General analysis function that groups data by subjec...
def _analyze_chunk(data, subjgroup=None, subjname='Subject', listgroup=None, listname='List', analysis=None, analysis_type=None, pass_features=False, features=None, parallel=False, **kwargs): """ Private function that groups data by subject/list number an...
def retrieveVals(self): """Retrieve values for graphs.""" if self.hasGraph('tomcat_memory'): stats = self._tomcatInfo.getMemoryStats() self.setGraphVal('tomcat_memory', 'used', stats['total'] - stats['free']) self.setGraphVal('tomcat_memo...
def function(data, maxt=None): """ Calculate the autocorrelation function for a 1D time series. Parameters ---------- data : numpy.ndarray (N,) The time series. Returns ------- rho : numpy.ndarray (N,) An autocorrelation function. """ data = np.atleast_1d(data)...
def retrieveVals(self): """Retrieve values for graphs.""" nginxInfo = NginxInfo(self._host, self._port, self._user, self._password, self._statuspath, self._ssl) stats = nginxInfo.getServerStats() if stats: if...
def autoconf(self): """Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise. """ nginxInfo = NginxInfo(self._host, self._port, self._user, self._password, ...
def getStats(self): """Query and parse Web Server Status Page. """ url = "%s://%s:%d/%s" % (self._proto, self._host, self._port, self._monpath) response = util.get_url(url, self._user, self._password) stats = {} for line in respo...
def retrieveVals(self): """Retrieve values for graphs.""" apcinfo = APCinfo(self._host, self._port, self._user, self._password, self._monpath, self._ssl, self._extras) stats = apcinfo.getAllStats() if self.hasGraph('php_apc_memory') and stats: ...
def autoconf(self): """Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise. """ apcinfo = APCinfo(self._host, self._port, self._user, self._password, self._monpath, self....
def getStats(self): """Runs varnishstats command to get stats from Varnish Cache. @return: Dictionary of stats. """ info_dict = {} args = [varnishstatCmd, '-1'] if self._instance is not None: args.extend(['-n', self._instance]) output = util....
def getDesc(self, entry): """Returns description for stat entry. @param entry: Entry name. @return: Description for entry. """ if len(self._descDict) == 0: self.getStats() return self._descDict.get(entry)
def retrieveVals(self): """Retrieve values for graphs.""" opcinfo = OPCinfo(self._host, self._port, self._user, self._password, self._monpath, self._ssl) stats = opcinfo.getAllStats() if self.hasGraph('php_opc_memory') and stats: mem = stat...
def autoconf(self): """Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise. """ opcinfo = OPCinfo(self._host, self._port, self._user, self._password, self._monpath, self....
def fingerprint_helper(egg, permute=False, n_perms=1000, match='exact', distance='euclidean', features=None): """ Computes clustering along a set of feature dimensions Parameters ---------- egg : quail.Egg Data to analyze dist_funcs : dict Dictionary of d...
def compute_feature_weights(pres_list, rec_list, feature_list, distances): """ Compute clustering scores along a set of feature dimensions Parameters ---------- pres_list : list list of presented words rec_list : list list of recalled words feature_list : list list...
def lagcrp_helper(egg, match='exact', distance='euclidean', ts=None, features=None): """ Computes probabilities for each transition distance (probability that a word recalled will be a given distance--in presentation order--from the previous recalled word). Parameters --------...
def retrieveVals(self): """Retrieve values for graphs.""" if self._diskList: self._fetchDevAll('disk', self._diskList, self._info.getDiskStats) if self._mdList: self._fetchDevAll('md', self._mdList, self._info....
def _configDevRequests(self, namestr, titlestr, devlist): """Generate configuration for I/O Request stats. @param namestr: Field name component indicating device type. @param titlestr: Title component indicating device type. @param devlist: List of devices. ""...
def _configDevActive(self, namestr, titlestr, devlist): """Generate configuration for I/O Queue Length. @param namestr: Field name component indicating device type. @param titlestr: Title component indicating device type. @param devlist: List of devices. """ ...
def _fetchDevAll(self, namestr, devlist, statsfunc): """Initialize I/O stats for devices. @param namestr: Field name component indicating device type. @param devlist: List of devices. @param statsfunc: Function for retrieving stats for device. """ fo...
def retrieveVals(self): """Retrieve values for graphs.""" for graph_name in self.getGraphList(): for field_name in self.getGraphFieldList(graph_name): self.setGraphVal(graph_name, field_name, self._stats.get(field_name))
def retrieveVals(self): """Retrieve values for graphs.""" if self.hasGraph('sys_loadavg'): self._loadstats = self._sysinfo.getLoadAvg() if self._loadstats: self.setGraphVal('sys_loadavg', 'load15min', self._loadstats[2]) self.setGraphVal('sys_loada...
def get(key, default=None): """ Searches os.environ. If a key is found try evaluating its type else; return the string. returns: k->value (type as defined by ast.literal_eval) """ try: # Attempt to evaluate into python literal return ast.literal_eval(os.environ.get(k...
def save(filepath=None, **kwargs): """ Saves a list of keyword arguments as environment variables to a file. If no filepath given will default to the default `.env` file. """ if filepath is None: filepath = os.path.join('.env') with open(filepath, 'wb') as file_handle: f...
def load(filepath=None): """ Reads a .env file into os.environ. For a set filepath, open the file and read contents into os.environ. If filepath is not set then look in current dir for a .env file. """ if filepath and os.path.exists(filepath): pass else: if not o...
def _get_line_(filepath): """ Gets each line from the file and parse the data. Attempt to translate the value into a python type is possible (falls back to string). """ for line in open(filepath): line = line.strip() # allows for comments in the file if line.startswith('#...
def initStats(self): """Query and parse Apache Web Server Status Page.""" url = "%s://%s:%d/%s?auto" % (self._proto, self._host, self._port, self._statuspath) response = util.get_url(url, self._user, self._password) self._statusDict = {} f...
def get_pres_features(self, features=None): """ Returns a df of features for presented items """ if features is None: features = self.dist_funcs.keys() elif not isinstance(features, list): features = [features] return self.pres.applymap(lambda x: {...
def get_rec_features(self, features=None): """ Returns a df of features for recalled items """ if features is None: features = self.dist_funcs.keys() elif not isinstance(features, list): features = [features] return self.rec.applymap(lambda x: {k:v...
def info(self): """ Print info about the data egg """ print('Number of subjects: ' + str(self.n_subjects)) print('Number of lists per subject: ' + str(self.n_lists)) print('Number of words per list: ' + str(self.list_length)) print('Date created: ' + str(self.date...
def save(self, fname, compression='blosc'): """ Save method for the Egg object The data will be saved as a 'egg' file, which is a dictionary containing the elements of a Egg saved in the hd5 format using `deepdish`. Parameters ---------- fname : str ...
def save(self, fname, compression='blosc'): """ Save method for the FriedEgg object The data will be saved as a 'fegg' file, which is a dictionary containing the elements of a FriedEgg saved in the hd5 format using `deepdish`. Parameters ---------- fnam...
def pnr_helper(egg, position, match='exact', distance='euclidean', features=None): """ Computes probability of a word being recalled nth (in the appropriate recall list), given its presentation position. Note: zero indexed Parameters ---------- egg : quail.Egg Data to a...
def retrieveVals(self): """Retrieve values for graphs.""" apacheInfo = ApacheInfo(self._host, self._port, self._user, self._password, self._statuspath, self._ssl) stats = apacheInfo.getServerStats() if self.hasGraph('apache...
def autoconf(self): """Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise. """ apacheInfo = ApacheInfo(self._host, self._port, self._user, self._password, ...
def retrieveVals(self): """Retrieve values for graphs.""" ntpinfo = NTPinfo() ntpstats = ntpinfo.getHostOffsets(self._remoteHosts) if ntpstats: for host in self._remoteHosts: hostkey = re.sub('\.', '_', host) hoststats = ntpstats.get(host) ...