text
stringlengths
81
112k
Check if the inputfile is a valid bed-file def check_bed_file(fname): """ Check if the inputfile is a valid bed-file """ if not os.path.exists(fname): logger.error("Inputfile %s does not exist!", fname) sys.exit(1) for i, line in enumerate(open(fname)): if line.startswith("#") or l...
Check if an input file is valid, which means BED, narrowPeak or FASTA def check_denovo_input(inputfile, params): """ Check if an input file is valid, which means BED, narrowPeak or FASTA """ background = params["background"] input_type = determine_file_type(inputfile) if input_type ==...
Scan a FASTA file with motifs. Scan a FASTA file and return a dictionary with the best match per motif. Parameters ---------- fname : str Filename of a sequence file in FASTA format. motifs : list List of motif instances. Returns ------- result : dict Dictiona...
Set the background to use for FPR and z-score calculations. Background can be specified either as a genome name or as the name of a FASTA file. Parameters ---------- fname : str, optional Name of FASTA file to use as background. genome : str, optio...
Set motif scanning threshold based on background sequences. Parameters ---------- fpr : float, optional Desired FPR, between 0.0 and 1.0. threshold : float or str, optional Desired motif threshold, expressed as the fraction of the difference between...
count the number of matches above the cutoff returns an iterator of lists containing integer counts def count(self, seqs, nreport=100, scan_rc=True): """ count the number of matches above the cutoff returns an iterator of lists containing integer counts """ for matches i...
count the number of matches above the cutoff returns an iterator of lists containing integer counts def total_count(self, seqs, nreport=100, scan_rc=True): """ count the number of matches above the cutoff returns an iterator of lists containing integer counts """ ...
give the score of the best match of each motif in each sequence returns an iterator of lists containing floats def best_score(self, seqs, scan_rc=True, normalize=False): """ give the score of the best match of each motif in each sequence returns an iterator of lists containing floats ...
give the best match of each motif in each sequence returns an iterator of nested lists containing tuples: (score, position, strand) def best_match(self, seqs, scan_rc=True): """ give the best match of each motif in each sequence returns an iterator of nested lists containing tup...
scan a set of regions / sequences def scan(self, seqs, nreport=100, scan_rc=True, normalize=False): """ scan a set of regions / sequences """ if not self.threshold: sys.stderr.write( "Using default threshold of 0.95. " "This is likely not opt...
Calculate ROC_AUC and other metrics and optionally plot ROC curve. def roc(args): """ Calculate ROC_AUC and other metrics and optionally plot ROC curve.""" outputfile = args.outfile # Default extension for image if outputfile and not outputfile.endswith(".png"): outputfile += ".png" mo...
Calculates motif position similarity based on sum of squared distances. Parameters ---------- p1 : list Motif position 1. p2 : list Motif position 2. Returns ------- score : float def ssd(p1, p2): """Calculates motif position similarity based on sum of squ...
Calculates motif similarity based on Pearson correlation of scores. Based on Kielbasa (2015) and Grau (2015). Scores are calculated based on scanning a de Bruijn sequence of 7-mers. This sequence is taken from ShortCAKE (Orenstein & Shamir, 2015). Optionally another sequence can be given as an argumen...
Compare two motifs. The similarity metric can be any of seqcor, pcc, ed, distance, wic, chisq, akl or ssd. If match is 'total' the similarity score is calculated for the whole match, including positions that are not present in both motifs. If match is partial or subtotal, onl...
Pairwise comparison of a set of motifs compared to reference motifs. Parameters ---------- motifs : list List of Motif instances. dbmotifs : list List of Motif instances. match : str Match can be "partial", "subtotal" or "total". Not all met...
Return best match in database for motifs. Parameters ---------- motifs : list or str Filename of motifs or list of motifs. dbmotifs : list or str, optional Database motifs, default will be used if not specified. match : str, optional metric : s...
List regions for the service def list_regions(service): """ List regions for the service """ for region in service.regions(): print '%(name)s: %(endpoint)s' % { 'name': region.name, 'endpoint': region.endpoint, }
Print nice looking table of information from list of load balancers def elb_table(balancers): """ Print nice looking table of information from list of load balancers """ t = prettytable.PrettyTable(['Name', 'DNS', 'Ports', 'Zones', 'Created']) t.align = 'l' for b in balancers: ports = [...
Print nice looking table of information from list of instances def ec2_table(instances): """ Print nice looking table of information from list of instances """ t = prettytable.PrettyTable(['ID', 'State', 'Monitored', 'Image', 'Name', 'Type', 'SSH key', 'DNS']) t.align = 'l' for i in instances: ...
Print nice looking table of information from images def ec2_image_table(images): """ Print nice looking table of information from images """ t = prettytable.PrettyTable(['ID', 'State', 'Name', 'Owner', 'Root device', 'Is public', 'Description']) t.align = 'l' for i in images: t.add_row(...
Run Fabric commands against EC2 instances def ec2_fab(service, args): """ Run Fabric commands against EC2 instances """ instance_ids = args.instances instances = service.list(elb=args.elb, instance_ids=instance_ids) hosts = service.resolve_hosts(instances) fab.env.hosts = hosts fab.env...
AWS support script's main method def main(): """ AWS support script's main method """ p = argparse.ArgumentParser(description='Manage Amazon AWS services', prog='aws', version=__version__) subparsers = p.add_subparsers(help='Select Ama...
Buffer "data" from an stream into one data object. Parameters ---------- stream : stream The stream to buffer buffer_size : int > 0 The number of examples to retain per batch. partial : bool, default=False If True, yield a final partial batch on under-run. axis : int ...
Reformat data as tuples. Parameters ---------- stream : iterable Stream of data objects. *keys : strings Keys to use for ordering data. Yields ------ items : tuple of np.ndarrays Data object reformated as a tuple. Raises ------ DataError If the...
Reformat data objects as keras-compatible tuples. For more detail: https://keras.io/models/model/#fit Parameters ---------- stream : iterable Stream of data objects. inputs : string or iterable of strings, None Keys to use for ordered input data. If not specified, returns ...
Creates histrogram of motif location. Parameters ---------- args : argparse object Command line arguments. def location(args): """ Creates histrogram of motif location. Parameters ---------- args : argparse object Command line arguments. """ fastafile = args.fa...
Find location of executable. def which(fname): """Find location of executable.""" if "PATH" not in os.environ or not os.environ["PATH"]: path = os.defpath else: path = os.environ["PATH"] for p in [fname] + [os.path.join(x, fname) for x in path.split(os.pathsep)]: p = os.path.ab...
Find all files in a directory by extension. def find_by_ext(dirname, ext): """Find all files in a directory by extension.""" # Get all fasta-files try: files = os.listdir(dirname) except OSError: if os.path.exists(dirname): cmd = "find {0} -maxdepth 1 -name \"*\"".format...
Return list of Motif instances from default motif database. def default_motifs(): """Return list of Motif instances from default motif database.""" config = MotifConfig() d = config.get_motif_dir() m = config.get_default_params()['motif_db'] if not d or not m: raise ValueError("default mot...
Convert alignment to motif. Converts a list with sequences to a motif. Sequences should be the same length. Parameters ---------- align : list List with sequences (A,C,G,T). Returns ------- m : Motif instance Motif created from the aligned sequences. def motif_fr...
Convert consensus sequence to motif. Converts a consensus sequences using the nucleotide IUPAC alphabet to a motif. Parameters ---------- cons : str Consensus sequence using the IUPAC alphabet. n : int , optional Count used to convert the sequence to a PFM. Returns ...
Parse motifs in a variety of formats to return a list of motifs. Parameters ---------- motifs : list or str Filename of motif, list of motifs or single Motif instance. Returns ------- motifs : list List of Motif instances. def parse_motifs(motifs): """Parse motifs in a ...
Read motifs from a file-like object. Parameters ---------- handle : file-like object Motifs. fmt : string, optional Motif format, can be 'pwm', 'transfac', 'xxmotif', 'jaspar' or 'align'. Returns ------- motifs : list List of Motif instances. def _read_motifs_f...
Read motifs from a file or stream or file-like object. Parameters ---------- infile : string or file-like object, optional Motif database, filename of motif file or file-like object. If infile is not specified the default motifs as specified in the config file will be returned. ...
Return the total information content of the motif. Return ------ ic : float Motif information content. def information_content(self): """Return the total information content of the motif. Return ------ ic : float Motif information conten...
Return the minimum PWM score. Returns ------- score : float Minimum PWM score. def pwm_min_score(self): """Return the minimum PWM score. Returns ------- score : float Minimum PWM score. """ if self.min_score is None: ...
Return the maximum PWM score. Returns ------- score : float Maximum PWM score. def pwm_max_score(self): """Return the maximum PWM score. Returns ------- score : float Maximum PWM score. """ if self.max_score is None: ...
Calculate the log-odds score for a specific k-mer. Parameters ---------- kmer : str String representing a kmer. Should be the same length as the motif. Returns ------- score : float Log-odd score. def score_kmer(self, kmer): """C...
Convert PFM with counts to a PFM with fractions. Parameters ---------- pfm : list 2-dimensional list with counts. pseudo : float Pseudocount used in conversion. Returns ------- pwm : list 2-dimensional list with fracti...
Return motif formatted in MotEvo (TRANSFAC-like) format Returns ------- m : str String of motif in MotEvo format. def to_motevo(self): """Return motif formatted in MotEvo (TRANSFAC-like) format Returns ------- m : str Str...
Return motif formatted in TRANSFAC format Returns ------- m : str String of motif in TRANSFAC format. def to_transfac(self): """Return motif formatted in TRANSFAC format Returns ------- m : str String of motif in TRANSFAC...
Return motif formatted in MEME format Returns ------- m : str String of motif in MEME format. def to_meme(self): """Return motif formatted in MEME format Returns ------- m : str String of motif in MEME format. """...
Calculate the information content of one position. Returns ------- score : float Information content. def ic_pos(self, row1, row2=None): """Calculate the information content of one position. Returns ------- score : float Information cont...
Calculate the Pearson correlation coefficient of one position compared to another position. Returns ------- score : float Pearson correlation coefficient. def pcc_pos(self, row1, row2): """Calculate the Pearson correlation coefficient of one position compare...
Return the reverse complemented motif. Returns ------- m : Motif instance New Motif instance with the reverse complement of the input motif. def rc(self): """Return the reverse complemented motif. Returns ------- m : Motif instance New M...
Trim positions with an information content lower than the threshold. The default threshold is set to 0.4. The Motif will be changed in-place. Parameters ---------- edge_ic_cutoff : float, optional Information content threshold. All motif positions at the flanks ...
Scan FASTA with the motif as a consensus sequence. Parameters ---------- fa : Fasta object Fasta object to scan Returns ------- matches : dict Dictionaru with matches. def consensus_scan(self, fa): """Scan FASTA with the motif as...
Scan sequences with this motif. Scan sequences from a FASTA object with this motif. Less efficient than using a Scanner object. By setting the cutoff to 0.0 and nreport to 1, the best match for every sequence will be returned. Only the position of the matches is returned. Par...
Scan sequences with this motif. Scan sequences from a FASTA object with this motif. Less efficient than using a Scanner object. By setting the cutoff to 0.0 and nreport to 1, the best match for every sequence will be returned. The score, position and strand for every match is returned...
Scan sequences with this motif and save to a GFF file. Scan sequences from a FASTA object with this motif. Less efficient than using a Scanner object. By setting the cutoff to 0.0 and nreport to 1, the best match for every sequence will be returned. The output is save to a file in GFF...
Return the average of two motifs. Combine this motif with another motif and return the average as a new Motif object. The position and orientatien need to be supplied. The pos parameter is the position of the second motif relative to this motif. For example, take the following ...
Return string representation of pwm. Parameters ---------- precision : int, optional, default 4 Floating-point precision. Returns ------- pwm_string : str def _pwm_to_str(self, precision=4): """Return string representation of pwm. Parameter...
Return pwm as string. Parameters ---------- precision : int, optional, default 4 Floating-point precision. extra_str |: str, optional Extra text to include with motif id line. Returns ------- motif_str : str M...
Create a sequence logo using seqlogo. Create a sequence logo and save it to a file. Valid formats are: PNG, EPS, GIF and PDF. Parameters ---------- fname : str Output filename. fmt : str , optional Output format (case-insensitive). Valid format...
Create a new motif with shuffled positions. Shuffle the positions of this motif and return a new Motif instance. Returns ------- m : Motif instance Motif instance with shuffled positions. def randomize(self): """Create a new motif with shuffled positions. ...
Run the maelstrom method. def maelstrom(args): """Run the maelstrom method.""" infile = args.inputfile genome = args.genome outdir = args.outdir pwmfile = args.pwmfile methods = args.methods ncpus = args.ncpus if not os.path.exists(infile): raise ValueError("file {} does no...
Send data, e.g. {key: np.ndarray}, with metadata def zmq_send_data(socket, data, flags=0, copy=True, track=False): """Send data, e.g. {key: np.ndarray}, with metadata""" header, payload = [], [] for key in sorted(data.keys()): arr = data[key] if not isinstance(arr, np.ndarray): ...
Receive data over a socket. def zmq_recv_data(socket, flags=0, copy=True, track=False): """Receive data over a socket.""" data = dict() msg = socket.recv_multipart(flags=flags, copy=copy, track=track) headers = json.loads(msg[0].decode('ascii')) if len(headers) == 0: raise StopIteration...
Note: A ZMQStreamer does not activate its stream, but allows the zmq_worker to do that. Yields ------ data : dict Data drawn from `streamer(max_iter)`. def iterate(self, max_iter=None): """ Note: A ZMQStreamer does not activate its stream, but allows...
Mask all lowercase nucleotides with N's def hardmask(self): """ Mask all lowercase nucleotides with N's """ p = re.compile("a|c|g|t|n") for seq_id in self.fasta_dict.keys(): self.fasta_dict[seq_id] = p.sub("N", self.fasta_dict[seq_id]) return self
Return n random sequences from this Fasta object def get_random(self, n, l=None): """ Return n random sequences from this Fasta object """ random_f = Fasta() if l: ids = self.ids[:] random.shuffle(ids) i = 0 while (i < n) and (len(ids) > 0): ...
Write sequences to FASTA formatted file def writefasta(self, fname): """ Write sequences to FASTA formatted file""" f = open(fname, "w") fa_str = "\n".join([">%s\n%s" % (id, self._format_seq(seq)) for id, seq in self.items()]) f.write(fa_str) f.close()
Clusters a set of sequence motifs. Required arg 'motifs' is a file containing positional frequency matrices or an array with motifs. Optional args: 'match', 'metric' and 'combine' specify the method used to compare and score the motifs. By default the WIC score is used (metric='wic'), using the the ...
Determine the number of samples in a batch. Parameters ---------- batch : dict A batch dictionary. Each value must implement `len`. All values must have the same `len`. Returns ------- n : int >= 0 or None The number of samples in this batch. If the batch has n...
Activates a number of streams def _activate(self): """Activates a number of streams""" self.distribution_ = 1. / self.n_streams * np.ones(self.n_streams) self.valid_streams_ = np.ones(self.n_streams, dtype=bool) self.streams_ = [None] * self.k self.stream_weights_ = np.zeros(s...
Randomly select and create a stream. Parameters ---------- idx : int, [0:n_streams - 1] The stream index to replace def _new_stream(self, idx): '''Randomly select and create a stream. Parameters ---------- idx : int, [0:n_streams - 1] Th...
Yields items from the mux, and handles stream exhaustion and replacement. def iterate(self, max_iter=None): """Yields items from the mux, and handles stream exhaustion and replacement. """ if max_iter is None: max_iter = np.inf # Calls Streamer's __enter__, ...
StochasticMux chooses its next sample stream randomly def _next_sample_index(self): """StochasticMux chooses its next sample stream randomly""" return self.rng.choice(self.n_active, p=(self.stream_weights_ / self.weight_norm_))
Randomly select and create a stream. StochasticMux adds mode handling to _activate_stream, making it so that if we're not sampling "with_replacement", the distribution for this chosen streamer is set to 0, causing the streamer not to be available until it is exhausted. Paramete...
Randomly select and create a new stream. Parameters ---------- idx : int, [0:n_streams - 1] The stream index to replace def _new_stream(self, idx): '''Randomly select and create a new stream. Parameters ---------- idx : int, [0:n_streams - 1] ...
ShuffledMux's activate is similar to StochasticMux, but there is no 'n_active', since all the streams are always available. def _activate(self): """ShuffledMux's activate is similar to StochasticMux, but there is no 'n_active', since all the streams are always available. """ sel...
ShuffledMux chooses its next sample stream randomly, conditioned on the stream weights. def _next_sample_index(self): """ShuffledMux chooses its next sample stream randomly, conditioned on the stream weights. """ return self.rng.choice(self.n_streams, ...
Randomly select and create a new stream. Parameters ---------- idx : int, [0:n_streams - 1] The stream index to replace def _new_stream(self, idx): '''Randomly select and create a new stream. Parameters ---------- idx : int, [0:n_streams - 1] ...
Rotates through each active sampler by incrementing the index def _next_sample_index(self): """Rotates through each active sampler by incrementing the index""" # Return the next streamer index where the streamer is not None, # wrapping around. idx = self.active_index_ self.activ...
Activate a new stream, given the index into the stream pool. BaseMux's _new_stream simply chooses a new stream and activates it. For special behavior (ie Weighted streams), you must override this in a child class. Parameters ---------- idx : int, [0:n_streams - 1] ...
Called by `BaseMux`'s iterate() when a stream is exhausted. Set the stream to None so it is ignored once exhausted. Parameters ---------- idx : int or None Raises ------ StopIteration If all streams are consumed, and `mode`=="exahustive" def _replac...
Grab the next stream from the input streamers, and start it. Raises ------ StopIteration When the input list or generator of streamers is complete, will raise a StopIteration. If `mode == cycle`, it will instead restart iterating from the beginning of the seq...
Shuffle X and Y into n / len(paths) datasets, and save them to disk at the locations provided in paths. def split_and_save_datasets(X, Y, paths): """Shuffle X and Y into n / len(paths) datasets, and save them to disk at the locations provided in paths. """ shuffled_idxs = np.random.permutation(np.a...
Generate data from an npz file. 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.randi...
Current hypergeometric implementation in scipy is broken, so here's the correct version 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)
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. def write_equalwidth_bedfile(bedfile, width, outfile): """Read input from <bedfile>, set the width of all entries to <width> and write the result to <outf...
Calculate enrichment based on hypergeometric distribution 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"]: rai...
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 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 ...
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 File name. Returns ------- filetyp...
automagically determine input type the following types are detected: - Fasta object - FASTA file - list of regions - region file - BED file def get_seqs_type(seqs): """ automagically determine input type the following types are detected: - Fasta object ...
Return md5 checksum of file. Note: only works for files < 4GB. Parameters ---------- filename : str File used to calculate checksum. Returns ------- checkum : str def file_checksum(fname): """Return md5 checksum of file. Note: only works for files < 4GB. Paramet...
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. def download_annotation(genomebuild, gene_file): """ Download gene annotati...
Check if dir exists, if not: give warning and die 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)
Index a single, one-sequence fasta-file 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() w...
Index all fasta-files in fasta_dir (one sequence per file!) and store the results in index_dir 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 i...
read the param_file, index_dir should already be set 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...
retrieve a number of lines from a fasta file-object, starting at offset 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)] ...
Retrieve multiple sequences from same chr (RC not possible yet) 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....
Retrieve a sequence 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...
Return the sizes of all sequences in the index, or the size of chrom if specified as an optional argument 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: ...
Returns an instance of a specific tool. Parameters ---------- name : str Name of the tool (case-insensitive). Returns ------- tool : MotifProgram instance def get_tool(name): """ Returns an instance of a specific tool. Parameters ---------- name : str Nam...
Returns the binary of a tool. Parameters ---------- name : str Name of the tool (case-insensitive). Returns ------- tool_bin : str Binary of tool. def locate_tool(name, verbose=True): """ Returns the binary of a tool. Parameters ---------- name : str ...
Get the command used to run the tool. Returns ------- command : str The tool system command. def bin(self): """ Get the command used to run the tool. Returns ------- command : str The tool system command. """ if s...
Check if the tool is installed. Returns ------- is_installed : bool True if the tool is installed. def is_installed(self): """ Check if the tool is installed. Returns ------- is_installed : bool True if the tool i...
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 required parameters are passed using this dictionary. t...