sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
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
-------
... | 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
-------
self : TeamLog
The TeamLog objec... | entailment |
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) | Returns the shot chart data as a pandas DataFrame. | entailment |
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() | Connect will attempt to connect to the NATS server. The url can
contain username/password semantics. | entailment |
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
... | 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
callback (function): callback to be called | entailment |
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... | 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 Subscription object
max (int=None): number of messages | entailment |
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... | 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 | entailment |
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... | 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): payload string | entailment |
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()
... | 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 | entailment |
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) ... | 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) coordinate. Twenty-two feet from the left of
the center of the hoo... | entailment |
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... | Returns an Axes object with player shots plotted.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as columns from the pandas
DataFrame passed into ``data``.
data : DataFrame... | entailment |
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... | Returns a JointGrid object containing the shot chart.
This function allows for more flexibility in customizing your shot chart
than the ``shot_chart_jointplot`` function.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
... | entailment |
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,
... | Returns a seaborn JointGrid using sns.jointplot
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as column names from the pandas
DataFrame passed into ``data``.
data : DataFr... | entailment |
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... | Returns an AxesImage object that contains a heatmap.
TODO: Redo some code and explain parameters | entailment |
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... | 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,0) coordinate. Twenty-two feet from the left of
the center of th... | entailment |
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
"""
... | Returns a figure with both FGA and basketball court lines drawn onto it.
This function expects data to be a ColumnDataSource with the x and y values
named "LOC_X" and "LOC_Y". Otherwise specify x and y.
Parameters
----------
data : DataFrame
The DataFrame that contains the shot chart dat... | entailment |
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... | Update Cluster Centers:
calculate the mean of feature vectors for each cluster.
distance can be a string or callable. | entailment |
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
... | Run a single trial of k-medoids clustering
on dataset X, and given number of clusters | entailment |
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) | Apply KMeans Clustering
X: dataset with feature vectors | entailment |
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... | 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_ii - 2 sum w_jh K_ih +
sum_r sum_s ... | entailment |
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... | Initialize mixture density parameters with
equal priors
random means
identity covariance matrices | entailment |
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 - ... | 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. | entailment |
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... | 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-mu)) | entailment |
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_... | 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... | entailment |
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))... | Validation Check for M.L. paramateres | entailment |
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... | 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) | entailment |
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... | Fit mixture-density parameters with EM algorithm | entailment |
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... | Initialize k=n_clusters centroids randomly | entailment |
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) | Assignment Step:
assign each point to the closet cluster center | entailment |
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)) | Calculate the SSE to the cluster center | entailment |
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... | Update Cluster Centers:
calculate the mean of feature vectors for each cluster | entailment |
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):
... | Run a single trial of k-means clustering
on dataset X, and given number of clusters | entailment |
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(... | Run multiple trials of k-means clustering,
and outputt he best centers, and cluster labels | entailment |
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) | Apply KMeans Clustering
X: dataset with feature vectors | entailment |
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 <... | Cut the tree to get desired number of clusters as n_clusters
2 <= n_desired <= n_clusters | entailment |
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 ... | 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 ... | entailment |
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... | Apply Bisecting Kmeans clustering
to reach n_clusters number of clusters | entailment |
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... | 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!**
... | entailment |
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... | 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::
... | entailment |
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 ... | 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::
... | entailment |
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... | 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.
... | entailment |
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... | 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... | entailment |
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
... | 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... | entailment |
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... | 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... | entailment |
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 ... | 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 ... | entailment |
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... | 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... | entailment |
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... | 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... | entailment |
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... | 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)... | entailment |
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
... | 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... | entailment |
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 ... | 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 ... | entailment |
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]
... | 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... | entailment |
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
... | 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 ... | entailment |
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
... | 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... | entailment |
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 ... | 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
... | entailment |
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... | 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... | entailment |
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 ... | 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 ... | entailment |
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... | 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... | entailment |
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 ... | 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... | entailment |
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... | 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... | entailment |
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... | 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... | entailment |
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... | 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... | entailment |
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... | Calculate motif score threshold for a given FPR. | entailment |
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
... | 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... | entailment |
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, ... | 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
... | entailment |
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... | 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).
... | entailment |
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 ... | 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).
... | entailment |
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... | 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).
... | entailment |
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... | 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... | entailment |
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... | 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... | entailment |
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... | 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.
... | entailment |
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... | 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... | entailment |
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... | 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 | entailment |
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
... | 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 | entailment |
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... | 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
... | entailment |
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
... | 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... | entailment |
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... | 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. | entailment |
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
... | 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. | entailment |
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.
... | 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... | entailment |
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
... | 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 ... | entailment |
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),... | Create a compiled Keras model.
Parameters
----------
input_shape : tuple, len=3
Shape of each image sample.
Returns
-------
model : keras.Model
Constructed model. | entailment |
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... | 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} | entailment |
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... | 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... | entailment |
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 ... | 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 | entailment |
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
--------... | 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... | entailment |
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... | 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... | entailment |
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... | 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... | entailment |
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... | Parallel calculation of motif statistics. | entailment |
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 motif prediction. | entailment |
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... | Parallel prediction of motifs.
Utility function for gimmemotifs.denovo.gimme_motifs. Probably better to
use that, instead of this function directly. | entailment |
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:
... | Predict motifs, input is a FASTA-file | entailment |
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)
... | Add motifs to the result object. | entailment |
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) | Make sure all jobs are finished. | entailment |
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... | Callback to add motif statistics. | entailment |
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... | 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... | entailment |
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... | 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... | entailment |
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... | Create all the FASTA files for de novo motif prediction and validation.
Parameters
---------- | entailment |
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... | 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... | entailment |
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 ... | 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... | entailment |
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... | 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... | entailment |
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... | 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.
... | entailment |
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 ... | 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.
... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.