text
stringlengths
81
112k
Theta = (theta_1, theta_2, ... theta_M) Likelihood of mixture parameters given data: L(Theta | X) = product_i P(x_i | Theta) log likelihood: log L(Theta | X) = sum_i log(P(x_i | Theta)) and note that p(x_i | Theta) = sum_j prior_j * p(x_i | theta_j) Probability of sample x being generated fro...
Validation Check for M.L. paramateres def _validate_params(priors, means, covars): """ Validation Check for M.L. paramateres """ for i,(p,m,cv) in enumerate(zip(priors, means, covars)): if np.any(np.isinf(p)) or np.any(np.isnan(p)): raise ValueError("Component %d of priors is not valid...
Update class parameters as below: priors: P(w_i) = sum_x P(w_i | x) ==> Then normalize to get in [0,1] Class means: center_w_i = sum_x P(w_i|x)*x / sum_i sum_x P(w_i|x) def _maximization_step(X, posteriors): """ Update class parameters as below: priors: P(w_i) = sum_x P(w_i | x) ==> ...
Fit mixture-density parameters with EM algorithm def fit(self, X): """ Fit mixture-density parameters with EM algorithm """ params_dict = _fit_gmm_params(X=X, n_mixtures=self.n_clusters, \ n_init=self.n_trials, init_method=self.init_method, \ n_it...
Initialize k=n_clusters centroids randomly def _kmeans_init(X, n_clusters, method='balanced', rng=None): """ Initialize k=n_clusters centroids randomly """ n_samples = X.shape[0] if rng is None: cent_idx = np.random.choice(n_samples, replace=False, size=n_clusters) else: #print('Gen...
Assignment Step: assign each point to the closet cluster center def _assign_clusters(X, centers): """ Assignment Step: assign each point to the closet cluster center """ dist2cents = scipy.spatial.distance.cdist(X, centers, metric='seuclidean') membs = np.argmin(dist2cents, axis=1...
Calculate the SSE to the cluster center def _cal_dist2center(X, center): """ Calculate the SSE to the cluster center """ dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean') return(np.sum(dmemb2cen))
Update Cluster Centers: calculate the mean of feature vectors for each cluster def _update_centers(X, membs, n_clusters): """ Update Cluster Centers: calculate the mean of feature vectors for each cluster """ centers = np.empty(shape=(n_clusters, X.shape[1]), dtype=float) sse = np...
Run a single trial of k-means clustering on dataset X, and given number of clusters def _kmeans_run(X, n_clusters, max_iter, tol): """ Run a single trial of k-means clustering on dataset X, and given number of clusters """ membs = np.empty(shape=X.shape[0], dtype=int) centers = _kmeans_...
Run multiple trials of k-means clustering, and outputt he best centers, and cluster labels def _kmeans(X, n_clusters, max_iter, n_trials, tol): """ Run multiple trials of k-means clustering, and outputt he best centers, and cluster labels """ n_samples, n_features = X.shape[0], X.shape[1] ...
Apply KMeans Clustering X: dataset with feature vectors def fit(self, X): """ Apply KMeans Clustering X: dataset with feature vectors """ self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \ _kmeans(X, self.n_clusters, self.max_iter, self.n_tria...
Cut the tree to get desired number of clusters as n_clusters 2 <= n_desired <= n_clusters def _cut_tree(tree, n_clusters, membs): """ Cut the tree to get desired number of clusters as n_clusters 2 <= n_desired <= n_clusters """ ## starting from root, ## a node is added to the cu...
Add a node to the tree if parent is not known, the node is a root The nodes of this tree keep properties of each cluster/subcluster: size --> cluster size as the number of points in the cluster center --> mean of the cluster label --> cluster label sse ...
Apply Bisecting Kmeans clustering to reach n_clusters number of clusters def _bisect_kmeans(X, n_clusters, n_trials, max_iter, tol): """ Apply Bisecting Kmeans clustering to reach n_clusters number of clusters """ membs = np.empty(shape=X.shape[0], dtype=int) centers = dict() #np.empty(...
r""" Returns the corrected Deviance Information Criterion (DIC) for all chains loaded into ChainConsumer. If a chain does not have a posterior, this method will return `None` for that chain. **Note that the DIC metric is only valid on posterior surfaces which closely resemble multivariate normals!** ...
r""" Returns the corrected Bayesian Information Criterion (BIC) for all chains loaded into ChainConsumer. If a chain does not have a posterior, number of data points, and number of free parameters loaded, this method will return `None` for that chain. Formally, the BIC is defined as .. math:: ...
r""" Returns the corrected Akaike Information Criterion (AICc) for all chains loaded into ChainConsumer. If a chain does not have a posterior, number of data points, and number of free parameters loaded, this method will return `None` for that chain. Formally, the AIC is defined as .. math:: ...
Return a LaTeX ready table of model comparisons. Parameters ---------- caption : str, optional The table caption to insert. label : str, optional The table label to insert. hlines : bool, optional Whether to insert hlines in the table or not. ...
Estimate un-normalised probability density at target points Parameters ---------- data : np.ndarray A `(num_targets, num_dim)` array of points to investigate. Returns ------- np.ndarray A `(num_targets)` length array of estimates...
Plot the chain! Parameters ---------- figsize : str|tuple(float)|float, optional The figure size to generate. Accepts a regular two tuple of size in inches, or one of several key words. The default value of ``COLUMN`` creates a figure of appropriate size of i...
Plots the chain walk; the parameter values as a function of step index. This plot is more for a sanity or consistency check than for use with final results. Plotting this before plotting with :func:`plot` allows you to quickly see if the chains are well behaved, or if certain parameters are sus...
Plots the 1D parameter distributions for verification purposes. This plot is more for a sanity or consistency check than for use with final results. Plotting this before plotting with :func:`plot` allows you to quickly see if the chains give well behaved distributions, or if certain parameters ...
Plots parameter summaries This plot is more for a sanity or consistency check than for use with final results. Plotting this before plotting with :func:`plot` allows you to quickly see if the chains give well behaved distributions, or if certain parameters are suspect or require a great...
r""" Runs the Gelman Rubin diagnostic on the supplied chains. Parameters ---------- chain : int|str, optional Which chain to run the diagnostic on. By default, this is `None`, which will run the diagnostic on all chains. You can also supply and integer (the c...
Runs the Geweke diagnostic on the supplied chains. Parameters ---------- chain : int|str, optional Which chain to run the diagnostic on. By default, this is `None`, which will run the diagnostic on all chains. You can also supply and integer (the chain index)...
Generates a LaTeX table from parameter summaries. Parameters ---------- parameters : list[str], optional A list of what parameters to include in the table. By default, includes all parameters transpose : bool, optional Defaults to False, which gives each column a...
Gets a summary of the marginalised parameter distributions. Parameters ---------- squeeze : bool, optional Squeeze the summaries. If you only have one chain, squeeze will not return a length one list, just the single summary. If this is false, you will get a ...
Gets the maximum posterior point in parameter space from the passed parameters. Requires the chains to have set `posterior` values. Parameters ---------- parameters : str|list[str] The parameters to find squeeze : bool, optional Squeeze the summa...
Takes a chain and returns the correlation between chain parameters. Parameters ---------- chain : int|str, optional The chain index or name. Defaults to first chain. parameters : list[str], optional The list of parameters to compute correlations. Defaults to all ...
Takes a chain and returns the covariance between chain parameters. Parameters ---------- chain : int|str, optional The chain index or name. Defaults to first chain. parameters : list[str], optional The list of parameters to compute correlations. Defaults to all p...
Gets a LaTeX table of parameter correlations. Parameters ---------- chain : int|str, optional The chain index or name. Defaults to first chain. parameters : list[str], optional The list of parameters to compute correlations. Defaults to all parameters ...
Gets a LaTeX table of parameter covariance. Parameters ---------- chain : int|str, optional The chain index or name. Defaults to first chain. parameters : list[str], optional The list of parameters to compute correlations. Defaults to all parameters f...
Generates LaTeX appropriate text from marginalised parameter bounds. Parameters ---------- lower : float The lower bound on the parameter maximum : float The value of the parameter with maximum probability upper : float The upper bound on the ...
Add a chain to the consumer. Parameters ---------- chain : str|ndarray|dict The chain to load. Normally a ``numpy.ndarray``. If a string is found, it interprets the string as a filename and attempts to load it in. If a ``dict`` is passed in, it assumes the di...
Removes a chain from ChainConsumer. Calling this will require any configurations set to be redone! Parameters ---------- chain : int|str, list[str|int] The chain(s) to remove. You can pass in either the chain index, or the chain name, to remove it. By default removes the...
r""" Configure the general plotting parameters common across the bar and contour plots. If you do not call this explicitly, the :func:`plot` method will invoke this method automatically. Please ensure that you call this method *after* adding all the relevant data to the chain c...
Configure the arguments passed to the ``axvline`` and ``axhline`` methods when plotting truth values. If you do not call this explicitly, the :func:`plot` method will invoke this method automatically. Recommended to set the parameters ``linestyle``, ``color`` and/or ``alpha`` i...
Returns a ChainConsumer instance containing all the walks of a given chain as individual chains themselves. This method might be useful if, for example, your chain was made using MCMC with 4 walkers. To check the sampling of all 4 walkers agree, you could call this to get a ChainConsume...
Calculate motif score threshold for a given FPR. def threshold(args): """Calculate motif score threshold for a given FPR.""" if args.fpr < 0 or args.fpr > 1: print("Please specify a FPR between 0 and 1") sys.exit(1) motifs = read_motifs(args.pwmfile) s = Scanner() s.set_motifs...
Convert two arrays of values to an array of labels and an array of scores. Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. Returns ------- y_true : array Labels. y...
Computes the recall at a specific FDR (default 10%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fdr : float, optional The FDR (between 0.0 and 1.0). Returns ...
Computes the hypergeometric p-value at a specific FPR (default 1%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fpr : float, optional The FPR (between 0.0 and 1.0). ...
Computes the hypergeometric p-value at a specific FPR (default 1%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fpr : float, optional The FPR (between 0.0 and 1.0). ...
Computes the fraction positives at a specific FPR (default 1%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fpr : float, optional The FPR (between 0.0 and 1.0). ...
Returns the motif score at a specific FPR (default 1%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fpr : float, optional The FPR (between 0.0 and 1.0). Retur...
Computes the enrichment at a specific FPR (default 1%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fpr : float, optional The FPR (between 0.0 and 1.0). Retur...
Computes the maximum enrichment. Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. minbg : int, optional Minimum number of matches in background. The default is 2. ...
Computes the Mean Normalized Conditional Probability (MNCP). MNCP is described in Clarke & Granek, Bioinformatics, 2003. Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. Retur...
Computes the Precision-Recall Area Under Curve (PR AUC) Parameters ---------- fg_vals : array_like list of values for positive set bg_vals : array_like list of values for negative set Returns ------- score : float PR AUC score def pr_auc(fg_vals, bg_vals): ...
Computes the ROC Area Under Curve (ROC AUC) Parameters ---------- fg_vals : array_like list of values for positive set bg_vals : array_like list of values for negative set Returns ------- score : float ROC AUC score def roc_auc(fg_vals, bg_vals): """ C...
Computes the ROC Area Under Curve until a certain FPR value. Parameters ---------- fg_vals : array_like list of values for positive set bg_vals : array_like list of values for negative set xlim : float, optional FPR value Returns ------- score : float ...
Return fpr (x) and tpr (y) of the ROC curve. Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. Returns ------- fpr : array False positive rate. tpr : array T...
Computes the maximum F-measure. Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. Returns ------- f : float Maximum f-measure. def max_fmeasure(fg_vals, bg_vals): ...
Computes the Kolmogorov-Smirnov p-value of position distribution. Parameters ---------- fg_pos : array_like The list of values for the positive set. bg_pos : array_like, optional The list of values for the negative set. Returns ------- p : float KS p-value. de...
Computes the -log10 of Kolmogorov-Smirnov p-value of position distribution. Parameters ---------- fg_pos : array_like The list of values for the positive set. bg_pos : array_like, optional The list of values for the negative set. Returns ------- p : float -log1...
Load and shape data for training with Keras + Pescador. Returns ------- input_shape : tuple, len=3 Shape of each sample; adapts to channel configuration of Keras. X_train, y_train : np.ndarrays Images and labels for training. X_test, y_test : np.ndarrays Images and labels ...
Create a compiled Keras model. Parameters ---------- input_shape : tuple, len=3 Shape of each image sample. Returns ------- model : keras.Model Constructed model. def build_model(input_shape): """Create a compiled Keras model. Parameters ---------- input_shape...
A basic generator for sampling data. Parameters ---------- X : np.ndarray, len=n_samples, ndim=4 Image data. y : np.ndarray, len=n_samples, ndim=2 One-hot encoded class vectors. Yields ------ data : dict Single image sample, like {X: np.ndarray, y: np.ndarray} def...
Add noise to a data stream. Parameters ---------- stream : iterable A stream that yields data objects. key : string, default='X' Name of the field to add noise. scale : float, default=0.1 Scale factor for gaussian noise. Yields ------ data : dict Updat...
Return default GimmeMotifs parameters. Defaults will be replaced with parameters defined in user_params. Parameters ---------- user_params : dict, optional User-defined parameters. Returns ------- params : dict def parse_denovo_params(user_params=None): """Return default Gim...
Return aggregated ranks as implemented in the RobustRankAgg R package. This function is now deprecated. References: Kolde et al., 2012, DOI: 10.1093/bioinformatics/btr709 Stuart et al., 2003, DOI: 10.1126/science.1087447 Parameters ---------- df : pandas.DataFrame DataFr...
Return aggregated ranks. Implementation is ported from the RobustRankAggreg R package References: Kolde et al., 2012, DOI: 10.1093/bioinformatics/btr709 Stuart et al., 2003, DOI: 10.1126/science.1087447 Parameters ---------- df : pandas.DataFrame DataFrame with value...
Yield data, while optionally burning compute cycles. Parameters ---------- n_ops : int, default=100 Number of operations to run between yielding data. Returns ------- data : dict A object which looks like it might come from some machine learning problem, with X as featu...
Parallel calculation of motif statistics. def mp_calc_stats(motifs, fg_fa, bg_fa, bg_name=None): """Parallel calculation of motif statistics.""" try: stats = calc_stats(motifs, fg_fa, bg_fa, ncpus=1) except Exception as e: raise sys.stderr.write("ERROR: {}\n".format(str(e))) ...
Parallel motif prediction. def _run_tool(job_name, t, fastafile, params): """Parallel motif prediction.""" try: result = t.run(fastafile, params, mytmpdir()) except Exception as e: result = ([], "", "{} failed to run: {}".format(job_name, e)) return job_name, result
Parallel prediction of motifs. Utility function for gimmemotifs.denovo.gimme_motifs. Probably better to use that, instead of this function directly. def pp_predict_motifs(fastafile, outfile, analysis="small", organism="hg18", single=False, background="", tools=None, job_server=None, ncpus=8, max_time=-1, sta...
Predict motifs, input is a FASTA-file def predict_motifs(infile, bgfile, outfile, params=None, stats_fg=None, stats_bg=None): """ Predict motifs, input is a FASTA-file""" # Parse parameters required_params = ["tools", "available_tools", "analysis", "genome", "use_strand", ...
Add motifs to the result object. def add_motifs(self, args): """Add motifs to the result object.""" self.lock.acquire() # Callback function for motif programs if args is None or len(args) != 2 or len(args[1]) != 3: try: job = args[0] logger.wa...
Make sure all jobs are finished. def wait_for_stats(self): """Make sure all jobs are finished.""" logging.debug("waiting for statistics to finish") for job in self.stat_jobs: job.get() sleep(2)
Callback to add motif statistics. def add_stats(self, args): """Callback to add motif statistics.""" bg_name, stats = args logger.debug("Stats: %s %s", bg_name, stats) for motif_id in stats.keys(): if motif_id not in self.stats: self.stats[motif_id] ...
Prepare a narrowPeak file for de novo motif prediction. All regions to same size; split in test and validation set; converted to FASTA. Parameters ---------- inputfile : str BED file with input regions. params : dict Dictionary with parameters. outdir : str Output...
Prepare a BED file for de novo motif prediction. All regions to same size; split in test and validation set; converted to FASTA. Parameters ---------- inputfile : str BED file with input regions. params : dict Dictionary with parameters. outdir : str Output direct...
Create all the FASTA files for de novo motif prediction and validation. Parameters ---------- def prepare_denovo_input_fa(inputfile, params, outdir): """Create all the FASTA files for de novo motif prediction and validation. Parameters ---------- """ fraction = float(params["fract...
Create background of a specific type. Parameters ---------- bg_type : str Name of background type. fafile : str Name of input FASTA file. outfile : str Name of output FASTA file. genome : str, optional Genome name. width : int, optional Size of re...
Create different backgrounds for motif prediction and validation. Parameters ---------- outdir : str Directory to save results. background : list, optional Background types to create, default is 'random'. genome : str, optional Genome name (for genomic and gc backgroun...
Filter significant motifs based on several statistics. Parameters ---------- stats : dict Statistics disctionary object. metrics : sequence Metric with associated minimum values. The default is (("max_enrichment", 3), ("roc_auc", 0.55), ("enr_at_fpr", 0.55)) Return...
Filter significant motifs based on several statistics. Parameters ---------- fname : str Filename of output file were significant motifs will be saved. result : PredictionResult instance Contains motifs and associated statistics. bg : str Name of background type to use. ...
Return the best motif per cluster for a clustering results. The motif can be either the average motif or one of the clustered motifs. Parameters ---------- single_pwm : str Filename of motifs. clus_pwm : str Filename of motifs. clusters : Motif clustering result. ...
Rename motifs to GimmeMotifs_1..GimmeMotifs_N. If stats object is passed, stats will be copied. def rename_motifs(motifs, stats=None): """Rename motifs to GimmeMotifs_1..GimmeMotifs_N. If stats object is passed, stats will be copied.""" final_motifs = [] for i, motif in enumerate(motifs):...
De novo motif prediction based on an ensemble of different tools. Parameters ---------- inputfile : str Filename of input. Can be either BED, narrowPeak or FASTA. outdir : str Name of output directory. params : dict, optional Optional parameters. filter_significant : ...
Register method to keep list of dbs. def register_db(cls, dbname): """Register method to keep list of dbs.""" def decorator(subclass): """Register as decorator function.""" cls._dbs[dbname] = subclass subclass.name = dbname return subclass return ...
Run a single motif activity prediction algorithm. Parameters ---------- inputfile : str :1File with regions (chr:start-end) in first column and either cluster name in second column or a table with values. method : str, optional Motif activity method to use. Any of 'hyp...
Create a Moap instance based on the predictor name. Parameters ---------- name : str Name of the predictor (eg. Xgboost, BayesianRidge, ...) ncpus : int, optional Number of threads. Default is the number specified in the config. Returns ...
Register method to keep list of predictors. def register_predictor(cls, name): """Register method to keep list of predictors.""" def decorator(subclass): """Register as decorator function.""" cls._predictors[name.lower()] = subclass subclass.name = name.lower() ...
List available classification predictors. def list_classification_predictors(self): """List available classification predictors.""" preds = [self.create(x) for x in self._predictors.keys()] return [x.name for x in preds if x.ptype == "classification"]
Activates the stream. def _activate(self): """Activates the stream.""" if six.callable(self.streamer): # If it's a function, create the stream. self.stream_ = self.streamer(*(self.args), **(self.kwargs)) else: # If it's iterable, use it directly. ...
Instantiate an iterator. Parameters ---------- max_iter : None or int > 0 Maximum number of iterations to yield. If ``None``, exhaust the stream. Yields ------ obj : Objects yielded by the streamer provided on init. See Also ----...
Iterate from the streamer infinitely. This function will force an infinite stream, restarting the streamer even if a StopIteration is raised. Parameters ---------- max_iter : None or int > 0 Maximum number of iterations to yield. If `None`, iterate indef...
Calculate motif enrichment metrics. Parameters ---------- motifs : str, list or Motif instance A file with motifs in pwm format, a list of Motif instances or a single Motif instance. fg_file : str Filename of a FASTA, BED or region file with positive sequences. bg_file : ...
Calculate motif enrichment metrics. Parameters ---------- motifs : str, list or Motif instance A file with motifs in pwm format, a list of Motif instances or a single Motif instance. fg_file : str Filename of a FASTA, BED or region file with positive sequences. bg_file : ...
Determine mean rank of motifs based on metrics. def rank_motifs(stats, metrics=("roc_auc", "recall_at_fdr")): """Determine mean rank of motifs based on metrics.""" rank = {} combined_metrics = [] motif_ids = stats.keys() background = list(stats.values())[0].keys() for metric in metrics: ...
write motif statistics to text file. def write_stats(stats, fname, header=None): """write motif statistics to text file.""" # Write stats output to file for bg in list(stats.values())[0].keys(): f = open(fname.format(bg), "w") if header: f.write(header) stat_ke...
Calculate ROC AUC values for ROC plots. def get_roc_values(motif, fg_file, bg_file): """Calculate ROC AUC values for ROC plots.""" #print(calc_stats(motif, fg_file, bg_file, stats=["roc_values"], ncpus=1)) #["roc_values"]) try: # fg_result = motif.pwm_scan_score(Fasta(fg_file), cutoff=0.0, ...
Make ROC plots for all motifs. def create_roc_plots(pwmfile, fgfa, background, outdir): """Make ROC plots for all motifs.""" motifs = read_motifs(pwmfile, fmt="pwm", as_dict=True) ncpus = int(MotifConfig().get_default_params()['ncpus']) pool = Pool(processes=ncpus) jobs = {} for bg,fname in bac...
Create text report of motifs with statistics and database match. def _create_text_report(inputfile, motifs, closest_match, stats, outdir): """Create text report of motifs with statistics and database match.""" my_stats = {} for motif in motifs: match = closest_match[motif.id] my_stats[str(m...
Create main gimme_motifs output html report. def _create_graphical_report(inputfile, pwm, background, closest_match, outdir, stats, best_id=None): """Create main gimme_motifs output html report.""" if best_id is None: best_id = {} logger.debug("Creating graphical report") class ReportMoti...
Create text and graphical (.html) motif reports. def create_denovo_motif_report(inputfile, pwmfile, fgfa, background, locfa, outdir, params, stats=None): """Create text and graphical (.html) motif reports.""" logger.info("creating reports") motifs = read_motifs(pwmfile, fmt="pwm") # ROC plots ...
Get rid of all axis ticks, lines, etc. def axes_off(ax): """Get rid of all axis ticks, lines, etc. """ ax.set_frame_on(False) ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False)
Plot list of motifs with database match and p-value "param plotdata: list of (motif, dbmotif, pval) def match_plot(plotdata, outfile): """Plot list of motifs with database match and p-value "param plotdata: list of (motif, dbmotif, pval) """ fig_h = 2 fig_w = 7 nrows = len(plotdata) n...
Plot a "phylogenetic" tree def motif_tree_plot(outfile, tree, data, circle=True, vmin=None, vmax=None, dpi=300): """ Plot a "phylogenetic" tree """ try: from ete3 import Tree, faces, AttrFace, TreeStyle, NodeStyle except ImportError: print("Please install ete3 to use this functiona...