Search is not available for this dataset
text stringlengths 75 104k |
|---|
def update_params(self, parameters):
"""Pass in a dictionary to update url parameters for NBA stats API
Parameters
----------
parameters : dict
A dict containing key, value pairs that correspond with NBA stats
API parameters.
Returns
-------
... |
def get_shots(self):
"""Returns the shot chart data as a pandas DataFrame."""
shots = self.response.json()['resultSets'][0]['rowSet']
headers = self.response.json()['resultSets'][0]['headers']
return pd.DataFrame(shots, columns=headers) |
def connect(self):
"""
Connect will attempt to connect to the NATS server. The url can
contain username/password semantics.
"""
self._build_socket()
self._connect_socket()
self._build_file_socket()
self._send_connect_msg() |
def subscribe(self, subject, callback, queue=''):
"""
Subscribe will express interest in the given subject. The subject can
have wildcards (partial:*, full:>). Messages will be delivered to the
associated callback.
Args:
subject (string): a string with the subject
... |
def unsubscribe(self, subscription, max=None):
"""
Unsubscribe will remove interest in the given subject. If max is
provided an automatic Unsubscribe that is processed by the server
when max messages have been received
Args:
subscription (pynats.Subscription): a Subs... |
def publish(self, subject, msg, reply=None):
"""
Publish publishes the data argument to the given subject.
Args:
subject (string): a string with the subject
msg (string): payload string
reply (string): subject used in the reply
"""
if msg is N... |
def request(self, subject, callback, msg=None):
"""
ublish a message with an implicit inbox listener as the reply.
Message is optional.
Args:
subject (string): a string with the subject
callback (function): callback to be called
msg (string=None): pay... |
def wait(self, duration=None, count=0):
"""
Publish publishes the data argument to the given subject.
Args:
duration (float): will wait for the given number of seconds
count (count): stop of wait after n messages from any subject
"""
start = time.time()
... |
def draw_court(ax=None, color='gray', lw=1, outer_lines=False):
"""Returns an axes with a basketball court drawn onto to it.
This function draws a court based on the x and y-axis values that the NBA
stats API provides for the shot chart data. For example the center of the
hoop is located at the (0,0) ... |
def shot_chart(x, y, kind="scatter", title="", color="b", cmap=None,
xlim=(-250, 250), ylim=(422.5, -47.5),
court_color="gray", court_lw=1, outer_lines=False,
flip_court=False, kde_shade=True, gridsize=None, ax=None,
despine=False, **kwargs):
"""
Retur... |
def shot_chart_jointgrid(x, y, data=None, joint_type="scatter", title="",
joint_color="b", cmap=None, xlim=(-250, 250),
ylim=(422.5, -47.5), court_color="gray", court_lw=1,
outer_lines=False, flip_court=False,
joint_kde... |
def shot_chart_jointplot(x, y, data=None, kind="scatter", title="", color="b",
cmap=None, xlim=(-250, 250), ylim=(422.5, -47.5),
court_color="gray", court_lw=1, outer_lines=False,
flip_court=False, size=(12, 11), space=0,
... |
def heatmap(x, y, z, title="", cmap=plt.cm.YlOrRd, bins=20,
xlim=(-250, 250), ylim=(422.5, -47.5),
facecolor='lightgray', facecolor_alpha=0.4,
court_color="black", court_lw=0.5, outer_lines=False,
flip_court=False, ax=None, **kwargs):
"""
Returns an AxesImage obj... |
def bokeh_draw_court(figure, line_color='gray', line_width=1):
"""Returns a figure with the basketball court lines drawn onto it
This function draws a court based on the x and y-axis values that the NBA
stats API provides for the shot chart data. For example the center of the
hoop is located at the (0... |
def bokeh_shot_chart(data, x="LOC_X", y="LOC_Y", fill_color="#1f77b4",
scatter_size=10, fill_alpha=0.4, line_alpha=0.4,
court_line_color='gray', court_line_width=1,
hover_tool=False, tooltips=None, **kwargs):
# TODO: Settings for hover tooltip
"""
... |
def _update_centers(X, membs, n_clusters, distance):
""" Update Cluster Centers:
calculate the mean of feature vectors for each cluster.
distance can be a string or callable.
"""
centers = np.empty(shape=(n_clusters, X.shape[1]), dtype=float)
sse = np.empty(shape=n_clusters, dtype=fl... |
def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng):
""" Run a single trial of k-medoids clustering
on dataset X, and given number of clusters
"""
membs = np.empty(shape=X.shape[0], dtype=int)
centers = kmeans._kmeans_init(X, n_clusters, method='', rng=rng)
sse_last = 9999.9
... |
def fit(self, X):
""" Apply KMeans Clustering
X: dataset with feature vectors
"""
self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \
_kmedoids(X, self.n_clusters, self.distance, self.max_iter, self.n_trials, self.tol, self.rng) |
def _kernelized_dist2centers(K, n_clusters, wmemb, kernel_dist):
""" Computin the distance in transformed feature space to
cluster centers.
K is the kernel gram matrix.
wmemb contains cluster assignment. {0,1}
Assume j is the cluster id:
||phi(x_i) - Phi_center_j|| = K_i... |
def _init_mixture_params(X, n_mixtures, init_method):
"""
Initialize mixture density parameters with
equal priors
random means
identity covariance matrices
"""
init_priors = np.ones(shape=n_mixtures, dtype=float) / n_mixtures
if init_method == 'kmeans':
km = _km... |
def __log_density_single(x, mean, covar):
""" This is just a test function to calculate
the normal density at x given mean and covariance matrix.
Note: this function is not efficient, so
_log_multivariate_density is recommended for use.
"""
n_dim = mean.shape[0]
dx = x - ... |
def _log_multivariate_density(X, means, covars):
"""
Class conditional density:
P(x | mu, Sigma) = 1/((2pi)^d/2 * |Sigma|^1/2) * exp(-1/2 * (x-mu)^T * Sigma^-1 * (x-mu))
log of class conditional density:
log P(x | mu, Sigma) = -1/2*(d*log(2pi) + log(|Sigma|) + (x-mu)^T * Sigma^-1 * (x-m... |
def _log_likelihood_per_sample(X, means, covars):
"""
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_... |
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 " % i)
if np.any(np.isinf(m))... |
def _maximization_step(X, posteriors):
"""
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)
"""
### Prior probabilities or class weights
sum_post_proba = np.sum... |
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_iter=self.max_iter, tol=self.tol)
self.prior... |
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('Generate random centers using RNG')
cen... |
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)
return(membs) |
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)) |
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.empty(shape=n_clusters, dtype=float)
for clust_id in range(n_clusters):
memb_i... |
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_init(X, n_clusters)
sse_last = 9999.9
n_iter = 0
for it in range(1,max_iter):
... |
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]
centers_best = np.empty(shape=(n_clusters,n_features), dtype=float)
labels_best = np.empty(... |
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_trials, self.tol) |
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 cut_set or
## its children are added to node_set
assert(n_clusters >= 2)
assert(n_clusters <... |
def _add_tree_node(tree, label, ilev, X=None, size=None, center=None, sse=None, parent=None):
""" 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 ... |
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(shape=(n_clusters,X.shape[1]), dtype=float)
sse_arr = dict() #-1.0*np.ones(sha... |
def dic(self):
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 mul... |
def bic(self):
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... |
def aic(self):
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 ... |
def comparison_table(self, caption=None, label="tab:model_comp", hlines=True,
aic=True, bic=True, dic=True, sort="bic", descending=True): # pragma: no cover
"""
Return a LaTeX ready table of model comparisons.
Parameters
----------
caption : str, option... |
def evaluate(self, data):
""" 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 `(n... |
def plot(self, figsize="GROW", parameters=None, chains=None, extents=None, filename=None,
display=False, truth=None, legend=None, blind=None, watermark=None): # pragma: no cover
""" Plot the chain!
Parameters
----------
figsize : str|tuple(float)|float, optional
... |
def plot_walks(self, parameters=None, truth=None, extents=None, display=False,
filename=None, chains=None, convolve=None, figsize=None,
plot_weights=True, plot_posterior=True, log_weight=None): # pragma: no cover
""" Plots the chain walk; the parameter values as a function... |
def plot_distributions(self, parameters=None, truth=None, extents=None, display=False,
filename=None, chains=None, col_wrap=4, figsize=None, blind=None): # pragma: no cover
""" Plots the 1D parameter distributions for verification purposes.
This plot is more for a sanity or ... |
def plot_summary(self, parameters=None, truth=None, extents=None, display=False,
filename=None, chains=None, figsize=1.0, errorbar=False, include_truth_chain=True,
blind=None, watermark=None, extra_parameter_spacing=0.5,
vertical_spacing_ratio=1.0, show_nam... |
def gelman_rubin(self, chain=None, threshold=0.05):
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 al... |
def geweke(self, chain=None, first=0.1, last=0.5, threshold=0.05):
""" 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 diagnost... |
def get_latex_table(self, parameters=None, transpose=False, caption=None,
label="tab:model_params", hlines=True, blank_fill="--"): # pragma: no cover
""" Generates a LaTeX table from parameter summaries.
Parameters
----------
parameters : list[str], optional
... |
def get_summary(self, squeeze=True, parameters=None, chains=None):
""" 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 ... |
def get_max_posteriors(self, parameters=None, squeeze=True, chains=None):
""" 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]
... |
def get_correlations(self, chain=0, parameters=None):
"""
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
... |
def get_covariance(self, chain=0, parameters=None):
"""
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
... |
def get_correlation_table(self, chain=0, parameters=None, caption="Parameter Correlations",
label="tab:parameter_correlations"):
"""
Gets a LaTeX table of parameter correlations.
Parameters
----------
chain : int|str, optional
The chain ... |
def get_covariance_table(self, chain=0, parameters=None, caption="Parameter Covariance",
label="tab:parameter_covariance"):
"""
Gets a LaTeX table of parameter covariance.
Parameters
----------
chain : int|str, optional
The chain index o... |
def get_parameter_text(self, lower, maximum, upper, wrap=False):
""" 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 ... |
def add_chain(self, chain, parameters=None, name=None, weights=None, posterior=None, walkers=None,
grid=False, num_eff_data_points=None, num_free_params=None, color=None, linewidth=None,
linestyle=None, kde=None, shade=None, shade_alpha=None, power=None, marker_style=None, marker_siz... |
def remove_chain(self, chain=-1):
"""
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 ... |
def configure(self, statistics="max", max_ticks=5, plot_hists=True, flip=True,
serif=True, sigma2d=False, sigmas=None, summary=None, bins=None, rainbow=None,
colors=None, linestyles=None, linewidths=None, kde=False, smooth=None,
cloud=None, shade=None, shade_alpha=N... |
def configure_truth(self, **kwargs): # pragma: no cover
""" 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 s... |
def divide_chain(self, chain=0):
"""
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 agr... |
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(args.pwmfile)
s.set_threshold(args.fpr, filen... |
def values_to_labels(fg_vals, bg_vals):
"""
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
... |
def recall_at_fdr(fg_vals, bg_vals, fdr_cutoff=0.1):
"""
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, ... |
def matches_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
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... |
def phyper_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
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 ... |
def fraction_fpr(fg_vals, bg_vals, fpr=0.01):
"""
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 : flo... |
def score_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
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, opti... |
def enr_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
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, option... |
def max_enrichment(fg_vals, bg_vals, minbg=2):
"""
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 n... |
def mncp(fg_vals, bg_vals):
"""
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 val... |
def pr_auc(fg_vals, bg_vals):
"""
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 AU... |
def roc_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_xlim(x_bla, y_bla, xlim=0.1):
"""
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 val... |
def roc_values(fg_vals, bg_vals):
"""
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
... |
def max_fmeasure(fg_vals, bg_vals):
"""
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... |
def ks_pvalue(fg_pos, bg_pos=None):
"""
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
... |
def ks_significance(fg_pos, bg_pos=None):
"""
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.
... |
def setup_data():
"""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
... |
def build_model(input_shape):
"""Create a compiled Keras model.
Parameters
----------
input_shape : tuple, len=3
Shape of each image sample.
Returns
-------
model : keras.Model
Constructed model.
"""
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),... |
def sampler(X, y):
'''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.nd... |
def additive_noise(stream, key='X', scale=1e-1):
'''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 noi... |
def parse_denovo_params(user_params=None):
"""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
"""
config ... |
def rankagg_R(df, method="stuart"):
"""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
--------... |
def rankagg(df, method="stuart"):
"""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 : pand... |
def data_gen(n_ops=100):
"""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 l... |
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)))
stats = {}
if not bg_name:
bg... |
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 |
def pp_predict_motifs(fastafile, outfile, analysis="small", organism="hg18", single=False, background="", tools=None, job_server=None, ncpus=8, max_time=-1, stats_fg=None, stats_bg=None):
"""Parallel prediction of motifs.
Utility function for gimmemotifs.denovo.gimme_motifs. Probably better to
use that, i... |
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", "max_time"]
if params is None:
... |
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.warn("job %s failed", job)
... |
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) |
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] = {}
self.stat... |
def prepare_denovo_input_narrowpeak(inputfile, params, outdir):
"""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 : di... |
def prepare_denovo_input_bed(inputfile, params, outdir):
"""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
Dic... |
def prepare_denovo_input_fa(inputfile, params, outdir):
"""Create all the FASTA files for de novo motif prediction and validation.
Parameters
----------
"""
fraction = float(params["fraction"])
abs_max = int(params["abs_max"])
logger.info("preparing input (FASTA)")
pred_fa = os.pa... |
def create_background(bg_type, fafile, outfile, genome="hg18", width=200, nr_times=10, custom_background=None):
"""Create background of a specific type.
Parameters
----------
bg_type : str
Name of background type.
fafile : str
Name of input FASTA file.
outfile : str
Na... |
def create_backgrounds(outdir, background=None, genome="hg38", width=200, custom_background=None):
"""Create different backgrounds for motif prediction and validation.
Parameters
----------
outdir : str
Directory to save results.
background : list, optional
Background types to ... |
def _is_significant(stats, metrics=None):
"""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_a... |
def filter_significant_motifs(fname, result, bg, metrics=None):
"""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 associat... |
def best_motif_in_cluster(single_pwm, clus_pwm, clusters, fg_fa, background, stats=None, metrics=("roc_auc", "recall_at_fdr")):
"""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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.