repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
savvastj/nbashots
nbashots/api.py
TeamLog.update_params
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 ------- ...
python
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", "update_params", "(", "self", ",", "parameters", ")", ":", "self", ".", "url_paramaters", ".", "update", "(", "parameters", ")", "self", ".", "response", "=", "requests", ".", "get", "(", "self", ".", "base_url", ",", "params", "=", "self", ".", ...
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...
[ "Pass", "in", "a", "dictionary", "to", "update", "url", "parameters", "for", "NBA", "stats", "API" ]
train
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L64-L84
savvastj/nbashots
nbashots/api.py
Shots.get_shots
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)
python
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", "get_shots", "(", "self", ")", ":", "shots", "=", "self", ".", "response", ".", "json", "(", ")", "[", "'resultSets'", "]", "[", "0", "]", "[", "'rowSet'", "]", "headers", "=", "self", ".", "response", ".", "json", "(", ")", "[", "'resultSet...
Returns the shot chart data as a pandas DataFrame.
[ "Returns", "the", "shot", "chart", "data", "as", "a", "pandas", "DataFrame", "." ]
train
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L218-L222
mcuadros/pynats
pynats/connection.py
Connection.connect
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()
python
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", "connect", "(", "self", ")", ":", "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.
[ "Connect", "will", "attempt", "to", "connect", "to", "the", "NATS", "server", ".", "The", "url", "can", "contain", "username", "/", "password", "semantics", "." ]
train
https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L45-L53
mcuadros/pynats
pynats/connection.py
Connection.subscribe
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 ...
python
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", "subscribe", "(", "self", ",", "subject", ",", "callback", ",", "queue", "=", "''", ")", ":", "s", "=", "Subscription", "(", "sid", "=", "self", ".", "_next_sid", ",", "subject", "=", "subject", ",", "queue", "=", "queue", ",", "callback", "="...
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
[ "Subscribe", "will", "express", "interest", "in", "the", "given", "subject", ".", "The", "subject", "can", "have", "wildcards", "(", "partial", ":", "*", "full", ":", ">", ")", ".", "Messages", "will", "be", "delivered", "to", "the", "associated", "callbac...
train
https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L93-L115
mcuadros/pynats
pynats/connection.py
Connection.unsubscribe
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...
python
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", "unsubscribe", "(", "self", ",", "subscription", ",", "max", "=", "None", ")", ":", "if", "max", "is", "None", ":", "self", ".", "_send", "(", "'UNSUB %d'", "%", "subscription", ".", "sid", ")", "self", ".", "_subscriptions", ".", "pop", "(", ...
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
[ "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" ]
train
https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L117-L132
mcuadros/pynats
pynats/connection.py
Connection.publish
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...
python
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", "publish", "(", "self", ",", "subject", ",", "msg", ",", "reply", "=", "None", ")", ":", "if", "msg", "is", "None", ":", "msg", "=", "''", "if", "reply", "is", "None", ":", "command", "=", "'PUB %s %d'", "%", "(", "subject", ",", "len", "(...
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
[ "Publish", "publishes", "the", "data", "argument", "to", "the", "given", "subject", "." ]
train
https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L134-L152
mcuadros/pynats
pynats/connection.py
Connection.request
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...
python
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", "request", "(", "self", ",", "subject", ",", "callback", ",", "msg", "=", "None", ")", ":", "inbox", "=", "self", ".", "_build_inbox", "(", ")", "s", "=", "self", ".", "subscribe", "(", "inbox", ",", "callback", ")", "self", ".", "unsubscribe"...
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
[ "ublish", "a", "message", "with", "an", "implicit", "inbox", "listener", "as", "the", "reply", ".", "Message", "is", "optional", "." ]
train
https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L154-L169
mcuadros/pynats
pynats/connection.py
Connection.wait
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() ...
python
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", "wait", "(", "self", ",", "duration", "=", "None", ",", "count", "=", "0", ")", ":", "start", "=", "time", ".", "time", "(", ")", "total", "=", "0", "while", "True", ":", "type", ",", "result", "=", "self", ".", "_recv", "(", "MSG", ",",...
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
[ "Publish", "publishes", "the", "data", "argument", "to", "the", "given", "subject", "." ]
train
https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L175-L199
savvastj/nbashots
nbashots/charts.py
draw_court
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) ...
python
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", "draw_court", "(", "ax", "=", "None", ",", "color", "=", "'gray'", ",", "lw", "=", "1", ",", "outer_lines", "=", "False", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "# Create the various parts of an NBA bask...
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...
[ "Returns", "an", "axes", "with", "a", "basketball", "court", "drawn", "onto", "to", "it", "." ]
train
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L15-L103
savvastj/nbashots
nbashots/charts.py
shot_chart
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...
python
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", "(", "x", ",", "y", ",", "kind", "=", "\"scatter\"", ",", "title", "=", "\"\"", ",", "color", "=", "\"b\"", ",", "cmap", "=", "None", ",", "xlim", "=", "(", "-", "250", ",", "250", ")", ",", "ylim", "=", "(", "422.5", ",", ...
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...
[ "Returns", "an", "Axes", "object", "with", "player", "shots", "plotted", "." ]
train
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L106-L219
savvastj/nbashots
nbashots/charts.py
shot_chart_jointgrid
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...
python
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_jointgrid", "(", "x", ",", "y", ",", "data", "=", "None", ",", "joint_type", "=", "\"scatter\"", ",", "title", "=", "\"\"", ",", "joint_color", "=", "\"b\"", ",", "cmap", "=", "None", ",", "xlim", "=", "(", "-", "250", ",", "250", ...
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 ...
[ "Returns", "a", "JointGrid", "object", "containing", "the", "shot", "chart", "." ]
train
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L222-L398
savvastj/nbashots
nbashots/charts.py
shot_chart_jointplot
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, ...
python
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", "shot_chart_jointplot", "(", "x", ",", "y", ",", "data", "=", "None", ",", "kind", "=", "\"scatter\"", ",", "title", "=", "\"\"", ",", "color", "=", "\"b\"", ",", "cmap", "=", "None", ",", "xlim", "=", "(", "-", "250", ",", "250", ")", ","...
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...
[ "Returns", "a", "seaborn", "JointGrid", "using", "sns", ".", "jointplot" ]
train
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L401-L514
savvastj/nbashots
nbashots/charts.py
heatmap
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...
python
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", "heatmap", "(", "x", ",", "y", ",", "z", ",", "title", "=", "\"\"", ",", "cmap", "=", "plt", ".", "cm", ".", "YlOrRd", ",", "bins", "=", "20", ",", "xlim", "=", "(", "-", "250", ",", "250", ")", ",", "ylim", "=", "(", "422.5", ",", ...
Returns an AxesImage object that contains a heatmap. TODO: Redo some code and explain parameters
[ "Returns", "an", "AxesImage", "object", "that", "contains", "a", "heatmap", "." ]
train
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L517-L559
savvastj/nbashots
nbashots/charts.py
bokeh_draw_court
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...
python
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_draw_court", "(", "figure", ",", "line_color", "=", "'gray'", ",", "line_width", "=", "1", ")", ":", "# hoop", "figure", ".", "circle", "(", "x", "=", "0", ",", "y", "=", "0", ",", "radius", "=", "7.5", ",", "fill_alpha", "=", "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...
[ "Returns", "a", "figure", "with", "the", "basketball", "court", "lines", "drawn", "onto", "it" ]
train
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L563-L641
savvastj/nbashots
nbashots/charts.py
bokeh_shot_chart
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 """ ...
python
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", "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", "=...
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...
[ "Returns", "a", "figure", "with", "both", "FGA", "and", "basketball", "court", "lines", "drawn", "onto", "it", "." ]
train
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L644-L704
vmirly/pyclust
pyclust/_kmedoids.py
_update_centers
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...
python
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", "_update_centers", "(", "X", ",", "membs", ",", "n_clusters", ",", "distance", ")", ":", "centers", "=", "np", ".", "empty", "(", "shape", "=", "(", "n_clusters", ",", "X", ".", "shape", "[", "1", "]", ")", ",", "dtype", "=", "float", ")", ...
Update Cluster Centers: calculate the mean of feature vectors for each cluster. distance can be a string or callable.
[ "Update", "Cluster", "Centers", ":", "calculate", "the", "mean", "of", "feature", "vectors", "for", "each", "cluster", "." ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmedoids.py#L8-L27
vmirly/pyclust
pyclust/_kmedoids.py
_kmedoids_run
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 ...
python
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", "_kmedoids_run", "(", "X", ",", "n_clusters", ",", "distance", ",", "max_iter", ",", "tol", ",", "rng", ")", ":", "membs", "=", "np", ".", "empty", "(", "shape", "=", "X", ".", "shape", "[", "0", "]", ",", "dtype", "=", "int", ")", "center...
Run a single trial of k-medoids clustering on dataset X, and given number of clusters
[ "Run", "a", "single", "trial", "of", "k", "-", "medoids", "clustering", "on", "dataset", "X", "and", "given", "number", "of", "clusters" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmedoids.py#L31-L49
vmirly/pyclust
pyclust/_kmedoids.py
KMedoids.fit
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)
python
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", "fit", "(", "self", ",", "X", ")", ":", "self", ".", "centers_", ",", "self", ".", "labels_", ",", "self", ".", "sse_arr_", ",", "self", ".", "n_iter_", "=", "_kmedoids", "(", "X", ",", "self", ".", "n_clusters", ",", "self", ".", "distance"...
Apply KMeans Clustering X: dataset with feature vectors
[ "Apply", "KMeans", "Clustering", "X", ":", "dataset", "with", "feature", "vectors" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmedoids.py#L129-L134
vmirly/pyclust
pyclust/_kernel_kmeans.py
_kernelized_dist2centers
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...
python
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", "_kernelized_dist2centers", "(", "K", ",", "n_clusters", ",", "wmemb", ",", "kernel_dist", ")", ":", "n_samples", "=", "K", ".", "shape", "[", "0", "]", "for", "j", "in", "range", "(", "n_clusters", ")", ":", "memb_j", "=", "np", ".", "where", ...
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 ...
[ "Computin", "the", "distance", "in", "transformed", "feature", "space", "to", "cluster", "centers", ".", "K", "is", "the", "kernel", "gram", "matrix", ".", "wmemb", "contains", "cluster", "assignment", ".", "{", "0", "1", "}" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kernel_kmeans.py#L29-L51
vmirly/pyclust
pyclust/_gaussian_mixture_model.py
_init_mixture_params
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...
python
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", "_init_mixture_params", "(", "X", ",", "n_mixtures", ",", "init_method", ")", ":", "init_priors", "=", "np", ".", "ones", "(", "shape", "=", "n_mixtures", ",", "dtype", "=", "float", ")", "/", "n_mixtures", "if", "init_method", "==", "'kmeans'", ":"...
Initialize mixture density parameters with equal priors random means identity covariance matrices
[ "Initialize", "mixture", "density", "parameters", "with", "equal", "priors", "random", "means", "identity", "covariance", "matrices" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_gaussian_mixture_model.py#L8-L35
vmirly/pyclust
pyclust/_gaussian_mixture_model.py
__log_density_single
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 - ...
python
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_density_single", "(", "x", ",", "mean", ",", "covar", ")", ":", "n_dim", "=", "mean", ".", "shape", "[", "0", "]", "dx", "=", "x", "-", "mean", "covar_inv", "=", "scipy", ".", "linalg", ".", "inv", "(", "covar", ")", "covar_det", "=",...
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.
[ "This", "is", "just", "a", "test", "function", "to", "calculate", "the", "normal", "density", "at", "x", "given", "mean", "and", "covariance", "matrix", "." ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_gaussian_mixture_model.py#L39-L54
vmirly/pyclust
pyclust/_gaussian_mixture_model.py
_log_multivariate_density
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...
python
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_multivariate_density", "(", "X", ",", "means", ",", "covars", ")", ":", "n_samples", ",", "n_dim", "=", "X", ".", "shape", "n_components", "=", "means", ".", "shape", "[", "0", "]", "assert", "(", "means", ".", "shape", "[", "0", "]", "=...
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))
[ "Class", "conditional", "density", ":", "P", "(", "x", "|", "mu", "Sigma", ")", "=", "1", "/", "((", "2pi", ")", "^d", "/", "2", "*", "|Sigma|^1", "/", "2", ")", "*", "exp", "(", "-", "1", "/", "2", "*", "(", "x", "-", "mu", ")", "^T", "*...
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_gaussian_mixture_model.py#L57-L90
vmirly/pyclust
pyclust/_gaussian_mixture_model.py
_log_likelihood_per_sample
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_...
python
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", "_log_likelihood_per_sample", "(", "X", ",", "means", ",", "covars", ")", ":", "logden", "=", "_log_multivariate_density", "(", "X", ",", "means", ",", "covars", ")", "logden_max", "=", "logden", ".", "max", "(", "axis", "=", "1", ")", "log_likeliho...
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...
[ "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", ...
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_gaussian_mixture_model.py#L95-L120
vmirly/pyclust
pyclust/_gaussian_mixture_model.py
_validate_params
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))...
python
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", "_validate_params", "(", "priors", ",", "means", ",", "covars", ")", ":", "for", "i", ",", "(", "p", ",", "m", ",", "cv", ")", "in", "enumerate", "(", "zip", "(", "priors", ",", "means", ",", "covars", ")", ")", ":", "if", "np", ".", "an...
Validation Check for M.L. paramateres
[ "Validation", "Check", "for", "M", ".", "L", ".", "paramateres" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_gaussian_mixture_model.py#L124-L139
vmirly/pyclust
pyclust/_gaussian_mixture_model.py
_maximization_step
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...
python
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", "_maximization_step", "(", "X", ",", "posteriors", ")", ":", "### Prior probabilities or class weights", "sum_post_proba", "=", "np", ".", "sum", "(", "posteriors", ",", "axis", "=", "0", ")", "prior_proba", "=", "sum_post_proba", "/", "(", "sum_post_proba"...
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)
[ "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", "=...
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_gaussian_mixture_model.py#L143-L173
vmirly/pyclust
pyclust/_gaussian_mixture_model.py
GMM.fit
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...
python
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", "fit", "(", "self", ",", "X", ")", ":", "params_dict", "=", "_fit_gmm_params", "(", "X", "=", "X", ",", "n_mixtures", "=", "self", ".", "n_clusters", ",", "n_init", "=", "self", ".", "n_trials", ",", "init_method", "=", "self", ".", "init_method...
Fit mixture-density parameters with EM algorithm
[ "Fit", "mixture", "-", "density", "parameters", "with", "EM", "algorithm" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_gaussian_mixture_model.py#L247-L258
vmirly/pyclust
pyclust/_kmeans.py
_kmeans_init
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...
python
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", "_kmeans_init", "(", "X", ",", "n_clusters", ",", "method", "=", "'balanced'", ",", "rng", "=", "None", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "if", "rng", "is", "None", ":", "cent_idx", "=", "np", ".", "random", ".", ...
Initialize k=n_clusters centroids randomly
[ "Initialize", "k", "=", "n_clusters", "centroids", "randomly" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmeans.py#L4-L20
vmirly/pyclust
pyclust/_kmeans.py
_assign_clusters
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)
python
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", "_assign_clusters", "(", "X", ",", "centers", ")", ":", "dist2cents", "=", "scipy", ".", "spatial", ".", "distance", ".", "cdist", "(", "X", ",", "centers", ",", "metric", "=", "'seuclidean'", ")", "membs", "=", "np", ".", "argmin", "(", "dist2c...
Assignment Step: assign each point to the closet cluster center
[ "Assignment", "Step", ":", "assign", "each", "point", "to", "the", "closet", "cluster", "center" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmeans.py#L23-L30
vmirly/pyclust
pyclust/_kmeans.py
_cal_dist2center
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))
python
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", "_cal_dist2center", "(", "X", ",", "center", ")", ":", "dmemb2cen", "=", "scipy", ".", "spatial", ".", "distance", ".", "cdist", "(", "X", ",", "center", ".", "reshape", "(", "1", ",", "X", ".", "shape", "[", "1", "]", ")", ",", "metric", ...
Calculate the SSE to the cluster center
[ "Calculate", "the", "SSE", "to", "the", "cluster", "center" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmeans.py#L32-L36
vmirly/pyclust
pyclust/_kmeans.py
_update_centers
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...
python
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", "_update_centers", "(", "X", ",", "membs", ",", "n_clusters", ")", ":", "centers", "=", "np", ".", "empty", "(", "shape", "=", "(", "n_clusters", ",", "X", ".", "shape", "[", "1", "]", ")", ",", "dtype", "=", "float", ")", "sse", "=", "np"...
Update Cluster Centers: calculate the mean of feature vectors for each cluster
[ "Update", "Cluster", "Centers", ":", "calculate", "the", "mean", "of", "feature", "vectors", "for", "each", "cluster" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmeans.py#L38-L53
vmirly/pyclust
pyclust/_kmeans.py
_kmeans_run
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): ...
python
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_run", "(", "X", ",", "n_clusters", ",", "max_iter", ",", "tol", ")", ":", "membs", "=", "np", ".", "empty", "(", "shape", "=", "X", ".", "shape", "[", "0", "]", ",", "dtype", "=", "int", ")", "centers", "=", "_kmeans_init", "(", "...
Run a single trial of k-means clustering on dataset X, and given number of clusters
[ "Run", "a", "single", "trial", "of", "k", "-", "means", "clustering", "on", "dataset", "X", "and", "given", "number", "of", "clusters" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmeans.py#L57-L75
vmirly/pyclust
pyclust/_kmeans.py
_kmeans
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(...
python
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", "_kmeans", "(", "X", ",", "n_clusters", ",", "max_iter", ",", "n_trials", ",", "tol", ")", ":", "n_samples", ",", "n_features", "=", "X", ".", "shape", "[", "0", "]", ",", "X", ".", "shape", "[", "1", "]", "centers_best", "=", "np", ".", "...
Run multiple trials of k-means clustering, and outputt he best centers, and cluster labels
[ "Run", "multiple", "trials", "of", "k", "-", "means", "clustering", "and", "outputt", "he", "best", "centers", "and", "cluster", "labels" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmeans.py#L78-L101
vmirly/pyclust
pyclust/_kmeans.py
KMeans.fit
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)
python
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", "fit", "(", "self", ",", "X", ")", ":", "self", ".", "centers_", ",", "self", ".", "labels_", ",", "self", ".", "sse_arr_", ",", "self", ".", "n_iter_", "=", "_kmeans", "(", "X", ",", "self", ".", "n_clusters", ",", "self", ".", "max_iter", ...
Apply KMeans Clustering X: dataset with feature vectors
[ "Apply", "KMeans", "Clustering", "X", ":", "dataset", "with", "feature", "vectors" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmeans.py#L137-L142
vmirly/pyclust
pyclust/_bisect_kmeans.py
_cut_tree
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 <...
python
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", "_cut_tree", "(", "tree", ",", "n_clusters", ",", "membs", ")", ":", "## 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", "<=", "len",...
Cut the tree to get desired number of clusters as n_clusters 2 <= n_desired <= n_clusters
[ "Cut", "the", "tree", "to", "get", "desired", "number", "of", "clusters", "as", "n_clusters", "2", "<", "=", "n_desired", "<", "=", "n_clusters" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_bisect_kmeans.py#L27-L70
vmirly/pyclust
pyclust/_bisect_kmeans.py
_add_tree_node
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 ...
python
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", "_add_tree_node", "(", "tree", ",", "label", ",", "ilev", ",", "X", "=", "None", ",", "size", "=", "None", ",", "center", "=", "None", ",", "sse", "=", "None", ",", "parent", "=", "None", ")", ":", "if", "size", "is", "None", ":", "size", ...
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 ...
[ "Add", "a", "node", "to", "the", "tree", "if", "parent", "is", "not", "known", "the", "node", "is", "a", "root" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_bisect_kmeans.py#L73-L105
vmirly/pyclust
pyclust/_bisect_kmeans.py
_bisect_kmeans
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...
python
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", "_bisect_kmeans", "(", "X", ",", "n_clusters", ",", "n_trials", ",", "max_iter", ",", "tol", ")", ":", "membs", "=", "np", ".", "empty", "(", "shape", "=", "X", ".", "shape", "[", "0", "]", ",", "dtype", "=", "int", ")", "centers", "=", "d...
Apply Bisecting Kmeans clustering to reach n_clusters number of clusters
[ "Apply", "Bisecting", "Kmeans", "clustering", "to", "reach", "n_clusters", "number", "of", "clusters" ]
train
https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_bisect_kmeans.py#L110-L157
Samreay/ChainConsumer
chainconsumer/comparisons.py
Comparison.dic
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...
python
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", "dic", "(", "self", ")", ":", "dics", "=", "[", "]", "dics_bool", "=", "[", "]", "for", "i", ",", "chain", "in", "enumerate", "(", "self", ".", "parent", ".", "chains", ")", ":", "p", "=", "chain", ".", "posterior", "if", "p", "is", "Non...
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", "Deviance", "Information", "Criterion", "(", "DIC", ")", "for", "all", "chains", "loaded", "into", "ChainConsumer", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/comparisons.py#L13-L65
Samreay/ChainConsumer
chainconsumer/comparisons.py
Comparison.bic
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...
python
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", "bic", "(", "self", ")", ":", "bics", "=", "[", "]", "bics_bool", "=", "[", "]", "for", "i", ",", "chain", "in", "enumerate", "(", "self", ".", "parent", ".", "chains", ")", ":", "p", ",", "n_data", ",", "n_free", "=", "chain", ".", "pos...
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", "Bayesian", "Information", "Criterion", "(", "BIC", ")", "for", "all", "chains", "loaded", "into", "ChainConsumer", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/comparisons.py#L67-L113
Samreay/ChainConsumer
chainconsumer/comparisons.py
Comparison.aic
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 ...
python
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", "aic", "(", "self", ")", ":", "aics", "=", "[", "]", "aics_bool", "=", "[", "]", "for", "i", ",", "chain", "in", "enumerate", "(", "self", ".", "parent", ".", "chains", ")", ":", "p", ",", "n_data", ",", "n_free", "=", "chain", ".", "pos...
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:: ...
[ "r", "Returns", "the", "corrected", "Akaike", "Information", "Criterion", "(", "AICc", ")", "for", "all", "chains", "loaded", "into", "ChainConsumer", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/comparisons.py#L115-L168
Samreay/ChainConsumer
chainconsumer/comparisons.py
Comparison.comparison_table
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...
python
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", "comparison_table", "(", "self", ",", "caption", "=", "None", ",", "label", "=", "\"tab:model_comp\"", ",", "hlines", "=", "True", ",", "aic", "=", "True", ",", "bic", "=", "True", ",", "dic", "=", "True", ",", "sort", "=", "\"bic\"", ",", "de...
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. ...
[ "Return", "a", "LaTeX", "ready", "table", "of", "model", "comparisons", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/comparisons.py#L170-L270
Samreay/ChainConsumer
chainconsumer/kde.py
MegKDE.evaluate
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...
python
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", "evaluate", "(", "self", ",", "data", ")", ":", "if", "len", "(", "data", ".", "shape", ")", "==", "1", "and", "self", ".", "num_dim", "==", "1", ":", "data", "=", "np", ".", "atleast_2d", "(", "data", ")", ".", "T", "_d", "=", "np", "...
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...
[ "Estimate", "un", "-", "normalised", "probability", "density", "at", "target", "points", "Parameters", "----------", "data", ":", "np", ".", "ndarray", "A", "(", "num_targets", "num_dim", ")", "array", "of", "points", "to", "investigate", ".", "Returns", "----...
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/kde.py#L52-L84
Samreay/ChainConsumer
chainconsumer/plotter.py
Plotter.plot
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 ...
python
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", "(", "self", ",", "figsize", "=", "\"GROW\"", ",", "parameters", "=", "None", ",", "chains", "=", "None", ",", "extents", "=", "None", ",", "filename", "=", "None", ",", "display", "=", "False", ",", "truth", "=", "None", ",", "legend"...
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...
[ "Plot", "the", "chain!" ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/plotter.py#L20-L283
Samreay/ChainConsumer
chainconsumer/plotter.py
Plotter.plot_walks
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...
python
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_walks", "(", "self", ",", "parameters", "=", "None", ",", "truth", "=", "None", ",", "extents", "=", "None", ",", "display", "=", "False", ",", "filename", "=", "None", ",", "chains", "=", "None", ",", "convolve", "=", "None", ",", "figs...
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", "chain", "walk", ";", "the", "parameter", "values", "as", "a", "function", "of", "step", "index", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/plotter.py#L319-L426
Samreay/ChainConsumer
chainconsumer/plotter.py
Plotter.plot_distributions
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 ...
python
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_distributions", "(", "self", ",", "parameters", "=", "None", ",", "truth", "=", "None", ",", "extents", "=", "None", ",", "display", "=", "False", ",", "filename", "=", "None", ",", "chains", "=", "None", ",", "col_wrap", "=", "4", ",", ...
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", "the", "1D", "parameter", "distributions", "for", "verification", "purposes", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/plotter.py#L428-L536
Samreay/ChainConsumer
chainconsumer/plotter.py
Plotter.plot_summary
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...
python
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", "plot_summary", "(", "self", ",", "parameters", "=", "None", ",", "truth", "=", "None", ",", "extents", "=", "None", ",", "display", "=", "False", ",", "filename", "=", "None", ",", "chains", "=", "None", ",", "figsize", "=", "1.0", ",", "erro...
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...
[ "Plots", "parameter", "summaries" ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/plotter.py#L538-L724
Samreay/ChainConsumer
chainconsumer/diagnostic.py
Diagnostic.gelman_rubin
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...
python
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", "gelman_rubin", "(", "self", ",", "chain", "=", "None", ",", "threshold", "=", "0.05", ")", ":", "if", "chain", "is", "None", ":", "return", "np", ".", "all", "(", "[", "self", ".", "gelman_rubin", "(", "k", ",", "threshold", "=", "threshold",...
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...
[ "r", "Runs", "the", "Gelman", "Rubin", "diagnostic", "on", "the", "supplied", "chains", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/diagnostic.py#L11-L76
Samreay/ChainConsumer
chainconsumer/diagnostic.py
Diagnostic.geweke
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...
python
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", "geweke", "(", "self", ",", "chain", "=", "None", ",", "first", "=", "0.1", ",", "last", "=", "0.5", ",", "threshold", "=", "0.05", ")", ":", "if", "chain", "is", "None", ":", "return", "np", ".", "all", "(", "[", "self", ".", "geweke", ...
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)...
[ "Runs", "the", "Geweke", "diagnostic", "on", "the", "supplied", "chains", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/diagnostic.py#L78-L128
Samreay/ChainConsumer
chainconsumer/analysis.py
Analysis.get_latex_table
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 ...
python
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_latex_table", "(", "self", ",", "parameters", "=", "None", ",", "transpose", "=", "False", ",", "caption", "=", "None", ",", "label", "=", "\"tab:model_params\"", ",", "hlines", "=", "True", ",", "blank_fill", "=", "\"--\"", ")", ":", "# pragma...
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...
[ "Generates", "a", "LaTeX", "table", "from", "parameter", "summaries", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/analysis.py#L27-L107
Samreay/ChainConsumer
chainconsumer/analysis.py
Analysis.get_summary
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 ...
python
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_summary", "(", "self", ",", "squeeze", "=", "True", ",", "parameters", "=", "None", ",", "chains", "=", "None", ")", ":", "results", "=", "[", "]", "if", "chains", "is", "None", ":", "chains", "=", "self", ".", "parent", ".", "chains", ...
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", "a", "summary", "of", "the", "marginalised", "parameter", "distributions", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/analysis.py#L109-L147
Samreay/ChainConsumer
chainconsumer/analysis.py
Analysis.get_max_posteriors
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] ...
python
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_max_posteriors", "(", "self", ",", "parameters", "=", "None", ",", "squeeze", "=", "True", ",", "chains", "=", "None", ")", ":", "results", "=", "[", "]", "if", "chains", "is", "None", ":", "chains", "=", "self", ".", "parent", ".", "chai...
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...
[ "Gets", "the", "maximum", "posterior", "point", "in", "parameter", "space", "from", "the", "passed", "parameters", ".", "Requires", "the", "chains", "to", "have", "set", "posterior", "values", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/analysis.py#L149-L195
Samreay/ChainConsumer
chainconsumer/analysis.py
Analysis.get_correlations
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 ...
python
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_correlations", "(", "self", ",", "chain", "=", "0", ",", "parameters", "=", "None", ")", ":", "parameters", ",", "cov", "=", "self", ".", "get_covariance", "(", "chain", "=", "chain", ",", "parameters", "=", "parameters", ")", "diag", "=", ...
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", "correlation", "between", "chain", "parameters", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/analysis.py#L204-L226
Samreay/ChainConsumer
chainconsumer/analysis.py
Analysis.get_covariance
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 ...
python
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_covariance", "(", "self", ",", "chain", "=", "0", ",", "parameters", "=", "None", ")", ":", "index", "=", "self", ".", "parent", ".", "_get_chain", "(", "chain", ")", "assert", "len", "(", "index", ")", "==", "1", ",", "\"Please specify onl...
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...
[ "Takes", "a", "chain", "and", "returns", "the", "covariance", "between", "chain", "parameters", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/analysis.py#L228-L255
Samreay/ChainConsumer
chainconsumer/analysis.py
Analysis.get_correlation_table
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 ...
python
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_correlation_table", "(", "self", ",", "chain", "=", "0", ",", "parameters", "=", "None", ",", "caption", "=", "\"Parameter Correlations\"", ",", "label", "=", "\"tab:parameter_correlations\"", ")", ":", "parameters", ",", "cor", "=", "self", ".", "...
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", "correlations", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/analysis.py#L257-L280
Samreay/ChainConsumer
chainconsumer/analysis.py
Analysis.get_covariance_table
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...
python
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_covariance_table", "(", "self", ",", "chain", "=", "0", ",", "parameters", "=", "None", ",", "caption", "=", "\"Parameter Covariance\"", ",", "label", "=", "\"tab:parameter_covariance\"", ")", ":", "parameters", ",", "cov", "=", "self", ".", "get_c...
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...
[ "Gets", "a", "LaTeX", "table", "of", "parameter", "covariance", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/analysis.py#L282-L305
Samreay/ChainConsumer
chainconsumer/analysis.py
Analysis.get_parameter_text
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 ...
python
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", "get_parameter_text", "(", "self", ",", "lower", ",", "maximum", ",", "upper", ",", "wrap", "=", "False", ")", ":", "if", "lower", "is", "None", "or", "upper", "is", "None", ":", "return", "\"\"", "upper_error", "=", "upper", "-", "maximum", "lo...
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 ...
[ "Generates", "LaTeX", "appropriate", "text", "from", "marginalised", "parameter", "bounds", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/analysis.py#L355-L429
Samreay/ChainConsumer
chainconsumer/chainconsumer.py
ChainConsumer.add_chain
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...
python
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", "add_chain", "(", "self", ",", "chain", ",", "parameters", "=", "None", ",", "name", "=", "None", ",", "weights", "=", "None", ",", "posterior", "=", "None", ",", "walkers", "=", "None", ",", "grid", "=", "False", ",", "num_eff_data_points", "="...
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...
[ "Add", "a", "chain", "to", "the", "consumer", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/chainconsumer.py#L49-L234
Samreay/ChainConsumer
chainconsumer/chainconsumer.py
ChainConsumer.remove_chain
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 ...
python
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", "remove_chain", "(", "self", ",", "chain", "=", "-", "1", ")", ":", "if", "isinstance", "(", "chain", ",", "str", ")", "or", "isinstance", "(", "chain", ",", "int", ")", ":", "chain", "=", "[", "chain", "]", "chain", "=", "sorted", "(", "[...
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...
[ "Removes", "a", "chain", "from", "ChainConsumer", ".", "Calling", "this", "will", "require", "any", "configurations", "set", "to", "be", "redone!" ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/chainconsumer.py#L236-L266
Samreay/ChainConsumer
chainconsumer/chainconsumer.py
ChainConsumer.configure
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...
python
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", "(", "self", ",", "statistics", "=", "\"max\"", ",", "max_ticks", "=", "5", ",", "plot_hists", "=", "True", ",", "flip", "=", "True", ",", "serif", "=", "True", ",", "sigma2d", "=", "False", ",", "sigmas", "=", "None", ",", "summa...
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...
[ "r", "Configure", "the", "general", "plotting", "parameters", "common", "across", "the", "bar", "and", "contour", "plots", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/chainconsumer.py#L268-L750
Samreay/ChainConsumer
chainconsumer/chainconsumer.py
ChainConsumer.configure_truth
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...
python
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", "configure_truth", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "if", "kwargs", ".", "get", "(", "\"ls\"", ")", "is", "None", "and", "kwargs", ".", "get", "(", "\"linestyle\"", ")", "is", "None", ":", "kwargs", "[", "\"l...
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...
[ "Configure", "the", "arguments", "passed", "to", "the", "axvline", "and", "axhline", "methods", "when", "plotting", "truth", "values", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/chainconsumer.py#L752-L781
Samreay/ChainConsumer
chainconsumer/chainconsumer.py
ChainConsumer.divide_chain
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...
python
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", "divide_chain", "(", "self", ",", "chain", "=", "0", ")", ":", "indexes", "=", "self", ".", "_get_chain", "(", "chain", ")", "con", "=", "ChainConsumer", "(", ")", "for", "index", "in", "indexes", ":", "chain", "=", "self", ".", "chains", "[",...
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...
[ "Returns", "a", "ChainConsumer", "instance", "containing", "all", "the", "walks", "of", "a", "given", "chain", "as", "individual", "chains", "themselves", "." ]
train
https://github.com/Samreay/ChainConsumer/blob/902288e4d85c2677a9051a2172e03128a6169ad7/chainconsumer/chainconsumer.py#L783-L816
vanheeringen-lab/gimmemotifs
gimmemotifs/commands/threshold.py
threshold
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...
python
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", "threshold", "(", "args", ")", ":", "if", "args", ".", "fpr", "<", "0", "or", "args", ".", "fpr", ">", "1", ":", "print", "(", "\"Please specify a FPR between 0 and 1\"", ")", "sys", ".", "exit", "(", "1", ")", "motifs", "=", "read_motifs", "(",...
Calculate motif score threshold for a given FPR.
[ "Calculate", "motif", "score", "threshold", "for", "a", "given", "FPR", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/commands/threshold.py#L13-L34
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
values_to_labels
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 ...
python
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", "values_to_labels", "(", "fg_vals", ",", "bg_vals", ")", ":", "y_true", "=", "np", ".", "hstack", "(", "(", "np", ".", "ones", "(", "len", "(", "fg_vals", ")", ")", ",", "np", ".", "zeros", "(", "len", "(", "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 ------- y_true : array Labels. y...
[ "Convert", "two", "arrays", "of", "values", "to", "an", "array", "of", "labels", "and", "an", "array", "of", "scores", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L42-L64
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
recall_at_fdr
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, ...
python
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", "recall_at_fdr", "(", "fg_vals", ",", "bg_vals", ",", "fdr_cutoff", "=", "0.1", ")", ":", "if", "len", "(", "fg_vals", ")", "==", "0", ":", "return", "0.0", "y_true", ",", "y_score", "=", "values_to_labels", "(", "fg_vals", ",", "bg_vals", ")", ...
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", "recall", "at", "a", "specific", "FDR", "(", "default", "10%", ")", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L67-L95
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
matches_at_fpr
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...
python
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", "matches_at_fpr", "(", "fg_vals", ",", "bg_vals", ",", "fpr", "=", "0.01", ")", ":", "fg_vals", "=", "np", ".", "array", "(", "fg_vals", ")", "s", "=", "scoreatpercentile", "(", "bg_vals", ",", "100", "-", "fpr", "*", "100", ")", "return", "["...
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%", ")", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L98-L121
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
phyper_at_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 ...
python
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", "phyper_at_fpr", "(", "fg_vals", ",", "bg_vals", ",", "fpr", "=", "0.01", ")", ":", "fg_vals", "=", "np", ".", "array", "(", "fg_vals", ")", "s", "=", "scoreatpercentile", "(", "bg_vals", ",", "100", "-", "fpr", "*", "100", ")", "table", "=", ...
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%", ")", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L124-L152
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
fraction_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...
python
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", "fraction_fpr", "(", "fg_vals", ",", "bg_vals", ",", "fpr", "=", "0.01", ")", ":", "fg_vals", "=", "np", ".", "array", "(", "fg_vals", ")", "s", "=", "scoreatpercentile", "(", "bg_vals", ",", "100", "-", "100", "*", "fpr", ")", "return", "len"...
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). ...
[ "Computes", "the", "fraction", "positives", "at", "a", "specific", "FPR", "(", "default", "1%", ")", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L155-L177
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
score_at_fpr
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...
python
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", "score_at_fpr", "(", "fg_vals", ",", "bg_vals", ",", "fpr", "=", "0.01", ")", ":", "bg_vals", "=", "np", ".", "array", "(", "bg_vals", ")", "return", "scoreatpercentile", "(", "bg_vals", ",", "100", "-", "100", "*", "fpr", ")" ]
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...
[ "Returns", "the", "motif", "score", "at", "a", "specific", "FPR", "(", "default", "1%", ")", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L180-L201
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
enr_at_fpr
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...
python
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", "enr_at_fpr", "(", "fg_vals", ",", "bg_vals", ",", "fpr", "=", "0.01", ")", ":", "pos", "=", "np", ".", "array", "(", "fg_vals", ")", "neg", "=", "np", ".", "array", "(", "bg_vals", ")", "s", "=", "scoreatpercentile", "(", "neg", ",", "100",...
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", "enrichment", "at", "a", "specific", "FPR", "(", "default", "1%", ")", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L204-L230
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
max_enrichment
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...
python
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", "max_enrichment", "(", "fg_vals", ",", "bg_vals", ",", "minbg", "=", "2", ")", ":", "scores", "=", "np", ".", "hstack", "(", "(", "fg_vals", ",", "bg_vals", ")", ")", "idx", "=", "np", ".", "argsort", "(", "scores", ")", "x", "=", "np", "....
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", "maximum", "enrichment", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L233-L268
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
mncp
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...
python
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", "mncp", "(", "fg_vals", ",", "bg_vals", ")", ":", "fg_len", "=", "len", "(", "fg_vals", ")", "total_len", "=", "len", "(", "fg_vals", ")", "+", "len", "(", "bg_vals", ")", "if", "not", "isinstance", "(", "fg_vals", ",", "np", ".", "ndarray", ...
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", "Mean", "Normalized", "Conditional", "Probability", "(", "MNCP", ")", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L271-L307
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
pr_auc
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...
python
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", "pr_auc", "(", "fg_vals", ",", "bg_vals", ")", ":", "# Create y_labels", "y_true", ",", "y_score", "=", "values_to_labels", "(", "fg_vals", ",", "bg_vals", ")", "return", "average_precision_score", "(", "y_true", ",", "y_score", ")" ]
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
[ "Computes", "the", "Precision", "-", "Recall", "Area", "Under", "Curve", "(", "PR", "AUC", ")" ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L310-L330
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
roc_auc
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 ...
python
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", "(", "fg_vals", ",", "bg_vals", ")", ":", "# Create y_labels", "y_true", ",", "y_score", "=", "values_to_labels", "(", "fg_vals", ",", "bg_vals", ")", "return", "roc_auc_score", "(", "y_true", ",", "y_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
[ "Computes", "the", "ROC", "Area", "Under", "Curve", "(", "ROC", "AUC", ")" ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L333-L353
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
roc_auc_xlim
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...
python
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_auc_xlim", "(", "x_bla", ",", "y_bla", ",", "xlim", "=", "0.1", ")", ":", "x", "=", "x_bla", "[", ":", "]", "y", "=", "y_bla", "[", ":", "]", "x", ".", "sort", "(", ")", "y", ".", "sort", "(", ")", "u", "=", "{", "}", "for", "...
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 ...
[ "Computes", "the", "ROC", "Area", "Under", "Curve", "until", "a", "certain", "FPR", "value", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L357-L444
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
roc_values
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 ...
python
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", "roc_values", "(", "fg_vals", ",", "bg_vals", ")", ":", "if", "len", "(", "fg_vals", ")", "==", "0", ":", "return", "0", "y_true", ",", "y_score", "=", "values_to_labels", "(", "fg_vals", ",", "bg_vals", ")", "fpr", ",", "tpr", ",", "_thresholds...
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...
[ "Return", "fpr", "(", "x", ")", "and", "tpr", "(", "y", ")", "of", "the", "ROC", "curve", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L447-L473
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
max_fmeasure
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...
python
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", "max_fmeasure", "(", "fg_vals", ",", "bg_vals", ")", ":", "x", ",", "y", "=", "roc_values", "(", "fg_vals", ",", "bg_vals", ")", "x", ",", "y", "=", "x", "[", "1", ":", "]", ",", "y", "[", "1", ":", "]", "# don't include origin", "p", "=",...
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.
[ "Computes", "the", "maximum", "F", "-", "measure", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L476-L506
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
ks_pvalue
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 ...
python
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_pvalue", "(", "fg_pos", ",", "bg_pos", "=", "None", ")", ":", "if", "len", "(", "fg_pos", ")", "==", "0", ":", "return", "1.0", "a", "=", "np", ".", "array", "(", "fg_pos", ",", "dtype", "=", "\"float\"", ")", "/", "max", "(", "fg_pos"...
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.
[ "Computes", "the", "Kolmogorov", "-", "Smirnov", "p", "-", "value", "of", "position", "distribution", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L509-L530
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
ks_significance
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. ...
python
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", "ks_significance", "(", "fg_pos", ",", "bg_pos", "=", "None", ")", ":", "p", "=", "ks_pvalue", "(", "fg_pos", ",", "max", "(", "fg_pos", ")", ")", "if", "p", ">", "0", ":", "return", "-", "np", ".", "log10", "(", "p", ")", "else", ":", "...
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...
[ "Computes", "the", "-", "log10", "of", "Kolmogorov", "-", "Smirnov", "p", "-", "value", "of", "position", "distribution", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L533-L554
pescadores/pescador
examples/frameworks/keras_example.py
setup_data
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 ...
python
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", "setup_data", "(", ")", ":", "# The data, shuffled and split between train and test sets", "(", "x_train", ",", "y_train", ")", ",", "(", "x_test", ",", "y_test", ")", "=", "mnist", ".", "load_data", "(", ")", "if", "K", ".", "image_data_format", "(", "...
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 ...
[ "Load", "and", "shape", "data", "for", "training", "with", "Keras", "+", "Pescador", "." ]
train
https://github.com/pescadores/pescador/blob/786e2b5f882d13ea563769fbc7ad0a0a10c3553d/examples/frameworks/keras_example.py#L41-L79
pescadores/pescador
examples/frameworks/keras_example.py
build_model
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),...
python
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", "build_model", "(", "input_shape", ")", ":", "model", "=", "Sequential", "(", ")", "model", ".", "add", "(", "Conv2D", "(", "32", ",", "kernel_size", "=", "(", "3", ",", "3", ")", ",", "activation", "=", "'relu'", ",", "input_shape", "=", "inp...
Create a compiled Keras model. Parameters ---------- input_shape : tuple, len=3 Shape of each image sample. Returns ------- model : keras.Model Constructed model.
[ "Create", "a", "compiled", "Keras", "model", "." ]
train
https://github.com/pescadores/pescador/blob/786e2b5f882d13ea563769fbc7ad0a0a10c3553d/examples/frameworks/keras_example.py#L86-L117
pescadores/pescador
examples/frameworks/keras_example.py
sampler
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...
python
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", "sampler", "(", "X", ",", "y", ")", ":", "X", "=", "np", ".", "atleast_2d", "(", "X", ")", "# y's are binary vectors, and should be of shape (10,) after this.", "y", "=", "np", ".", "atleast_1d", "(", "y", ")", "n", "=", "X", ".", "shape", "[", "0...
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}
[ "A", "basic", "generator", "for", "sampling", "data", "." ]
train
https://github.com/pescadores/pescador/blob/786e2b5f882d13ea563769fbc7ad0a0a10c3553d/examples/frameworks/keras_example.py#L124-L148
pescadores/pescador
examples/frameworks/keras_example.py
additive_noise
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...
python
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", "additive_noise", "(", "stream", ",", "key", "=", "'X'", ",", "scale", "=", "1e-1", ")", ":", "for", "data", "in", "stream", ":", "noise_shape", "=", "data", "[", "key", "]", ".", "shape", "noise", "=", "scale", "*", "np", ".", "random", "."...
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...
[ "Add", "noise", "to", "a", "data", "stream", "." ]
train
https://github.com/pescadores/pescador/blob/786e2b5f882d13ea563769fbc7ad0a0a10c3553d/examples/frameworks/keras_example.py#L155-L178
vanheeringen-lab/gimmemotifs
gimmemotifs/config.py
parse_denovo_params
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 ...
python
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", "parse_denovo_params", "(", "user_params", "=", "None", ")", ":", "config", "=", "MotifConfig", "(", ")", "if", "user_params", "is", "None", ":", "user_params", "=", "{", "}", "params", "=", "config", ".", "get_default_params", "(", ")", "params", "...
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
[ "Return", "default", "GimmeMotifs", "parameters", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/config.py#L248-L296
vanheeringen-lab/gimmemotifs
gimmemotifs/rank.py
rankagg_R
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 --------...
python
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_R", "(", "df", ",", "method", "=", "\"stuart\"", ")", ":", "tmpdf", "=", "NamedTemporaryFile", "(", ")", "tmpscript", "=", "NamedTemporaryFile", "(", "mode", "=", "\"w\"", ")", "tmpranks", "=", "NamedTemporaryFile", "(", ")", "df", ".", "to...
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", "as", "implemented", "in", "the", "RobustRankAgg", "R", "package", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rank.py#L15-L53
vanheeringen-lab/gimmemotifs
gimmemotifs/rank.py
rankagg
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...
python
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", "rankagg", "(", "df", ",", "method", "=", "\"stuart\"", ")", ":", "rmat", "=", "pd", ".", "DataFrame", "(", "index", "=", "df", ".", "iloc", "[", ":", ",", "0", "]", ")", "step", "=", "1", "/", "rmat", ".", "shape", "[", "0", "]", "for...
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...
[ "Return", "aggregated", "ranks", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rank.py#L71-L100
pescadores/pescador
examples/zmq_example.py
data_gen
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...
python
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", "data_gen", "(", "n_ops", "=", "100", ")", ":", "while", "True", ":", "X", "=", "np", ".", "random", ".", "uniform", "(", "size", "=", "(", "64", ",", "64", ")", ")", "yield", "dict", "(", "X", "=", "costly_function", "(", "X", ",", "n_o...
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...
[ "Yield", "data", "while", "optionally", "burning", "compute", "cycles", "." ]
train
https://github.com/pescadores/pescador/blob/786e2b5f882d13ea563769fbc7ad0a0a10c3553d/examples/zmq_example.py#L41-L58
vanheeringen-lab/gimmemotifs
gimmemotifs/prediction.py
mp_calc_stats
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...
python
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", "mp_calc_stats", "(", "motifs", ",", "fg_fa", ",", "bg_fa", ",", "bg_name", "=", "None", ")", ":", "try", ":", "stats", "=", "calc_stats", "(", "motifs", ",", "fg_fa", ",", "bg_fa", ",", "ncpus", "=", "1", ")", "except", "Exception", "as", "e"...
Parallel calculation of motif statistics.
[ "Parallel", "calculation", "of", "motif", "statistics", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/prediction.py#L42-L54
vanheeringen-lab/gimmemotifs
gimmemotifs/prediction.py
_run_tool
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
python
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", "_run_tool", "(", "job_name", ",", "t", ",", "fastafile", ",", "params", ")", ":", "try", ":", "result", "=", "t", ".", "run", "(", "fastafile", ",", "params", ",", "mytmpdir", "(", ")", ")", "except", "Exception", "as", "e", ":", "result", ...
Parallel motif prediction.
[ "Parallel", "motif", "prediction", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/prediction.py#L56-L63
vanheeringen-lab/gimmemotifs
gimmemotifs/prediction.py
pp_predict_motifs
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...
python
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", "pp_predict_motifs", "(", "fastafile", ",", "outfile", ",", "analysis", "=", "\"small\"", ",", "organism", "=", "\"hg18\"", ",", "single", "=", "False", ",", "background", "=", "\"\"", ",", "tools", "=", "None", ",", "job_server", "=", "None", ",", ...
Parallel prediction of motifs. Utility function for gimmemotifs.denovo.gimme_motifs. Probably better to use that, instead of this function directly.
[ "Parallel", "prediction", "of", "motifs", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/prediction.py#L163-L298
vanheeringen-lab/gimmemotifs
gimmemotifs/prediction.py
predict_motifs
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: ...
python
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", "predict_motifs", "(", "infile", ",", "bgfile", ",", "outfile", ",", "params", "=", "None", ",", "stats_fg", "=", "None", ",", "stats_bg", "=", "None", ")", ":", "# Parse parameters", "required_params", "=", "[", "\"tools\"", ",", "\"available_tools\"",...
Predict motifs, input is a FASTA-file
[ "Predict", "motifs", "input", "is", "a", "FASTA", "-", "file" ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/prediction.py#L300-L350
vanheeringen-lab/gimmemotifs
gimmemotifs/prediction.py
PredictionResult.add_motifs
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) ...
python
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", "add_motifs", "(", "self", ",", "args", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "# Callback function for motif programs", "if", "args", "is", "None", "or", "len", "(", "args", ")", "!=", "2", "or", "len", "(", "args", "[", "1", ...
Add motifs to the result object.
[ "Add", "motifs", "to", "the", "result", "object", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/prediction.py#L90-L130
vanheeringen-lab/gimmemotifs
gimmemotifs/prediction.py
PredictionResult.wait_for_stats
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)
python
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", "wait_for_stats", "(", "self", ")", ":", "logging", ".", "debug", "(", "\"waiting for statistics to finish\"", ")", "for", "job", "in", "self", ".", "stat_jobs", ":", "job", ".", "get", "(", ")", "sleep", "(", "2", ")" ]
Make sure all jobs are finished.
[ "Make", "sure", "all", "jobs", "are", "finished", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/prediction.py#L132-L137
vanheeringen-lab/gimmemotifs
gimmemotifs/prediction.py
PredictionResult.add_stats
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...
python
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", "add_stats", "(", "self", ",", "args", ")", ":", "bg_name", ",", "stats", "=", "args", "logger", ".", "debug", "(", "\"Stats: %s %s\"", ",", "bg_name", ",", "stats", ")", "for", "motif_id", "in", "stats", ".", "keys", "(", ")", ":", "if", "mot...
Callback to add motif statistics.
[ "Callback", "to", "add", "motif", "statistics", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/prediction.py#L139-L148
vanheeringen-lab/gimmemotifs
gimmemotifs/denovo.py
prepare_denovo_input_narrowpeak
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...
python
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_narrowpeak", "(", "inputfile", ",", "params", ",", "outdir", ")", ":", "bedfile", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "\"input.from.narrowpeak.bed\"", ")", "p", "=", "re", ".", "compile", "(", "r'^(#|track|brow...
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", "narrowPeak", "file", "for", "de", "novo", "motif", "prediction", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/denovo.py#L50-L96
vanheeringen-lab/gimmemotifs
gimmemotifs/denovo.py
prepare_denovo_input_bed
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...
python
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_bed", "(", "inputfile", ",", "params", ",", "outdir", ")", ":", "logger", ".", "info", "(", "\"preparing input (BED)\"", ")", "# Create BED file with regions of equal size", "width", "=", "int", "(", "params", "[", "\"width\"", "]", ")",...
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...
[ "Prepare", "a", "BED", "file", "for", "de", "novo", "motif", "prediction", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/denovo.py#L98-L151
vanheeringen-lab/gimmemotifs
gimmemotifs/denovo.py
prepare_denovo_input_fa
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...
python
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", "prepare_denovo_input_fa", "(", "inputfile", ",", "params", ",", "outdir", ")", ":", "fraction", "=", "float", "(", "params", "[", "\"fraction\"", "]", ")", "abs_max", "=", "int", "(", "params", "[", "\"abs_max\"", "]", ")", "logger", ".", "info", ...
Create all the FASTA files for de novo motif prediction and validation. Parameters ----------
[ "Create", "all", "the", "FASTA", "files", "for", "de", "novo", "motif", "prediction", "and", "validation", ".", "Parameters", "----------" ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/denovo.py#L153-L183
vanheeringen-lab/gimmemotifs
gimmemotifs/denovo.py
create_background
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...
python
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_background", "(", "bg_type", ",", "fafile", ",", "outfile", ",", "genome", "=", "\"hg18\"", ",", "width", "=", "200", ",", "nr_times", "=", "10", ",", "custom_background", "=", "None", ")", ":", "width", "=", "int", "(", "width", ")", "c...
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", "background", "of", "a", "specific", "type", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/denovo.py#L185-L273
vanheeringen-lab/gimmemotifs
gimmemotifs/denovo.py
create_backgrounds
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 ...
python
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", "create_backgrounds", "(", "outdir", ",", "background", "=", "None", ",", "genome", "=", "\"hg38\"", ",", "width", "=", "200", ",", "custom_background", "=", "None", ")", ":", "if", "background", "is", "None", ":", "background", "=", "[", "\"random\...
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...
[ "Create", "different", "backgrounds", "for", "motif", "prediction", "and", "validation", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/denovo.py#L275-L329
vanheeringen-lab/gimmemotifs
gimmemotifs/denovo.py
_is_significant
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...
python
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", "_is_significant", "(", "stats", ",", "metrics", "=", "None", ")", ":", "if", "metrics", "is", "None", ":", "metrics", "=", "(", "(", "\"max_enrichment\"", ",", "3", ")", ",", "(", "\"roc_auc\"", ",", "0.55", ")", ",", "(", "\"enr_at_fpr\"", ","...
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", "----------", "stats", ":", "dict", "Statistics", "disctionary", "object", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/denovo.py#L332-L355
vanheeringen-lab/gimmemotifs
gimmemotifs/denovo.py
filter_significant_motifs
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...
python
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", "filter_significant_motifs", "(", "fname", ",", "result", ",", "bg", ",", "metrics", "=", "None", ")", ":", "sig_motifs", "=", "[", "]", "with", "open", "(", "fname", ",", "\"w\"", ")", "as", "f", ":", "for", "motif", "in", "result", ".", "mot...
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. ...
[ "Filter", "significant", "motifs", "based", "on", "several", "statistics", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/denovo.py#L357-L393
vanheeringen-lab/gimmemotifs
gimmemotifs/denovo.py
best_motif_in_cluster
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 ...
python
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 ...
[ "def", "best_motif_in_cluster", "(", "single_pwm", ",", "clus_pwm", ",", "clusters", ",", "fg_fa", ",", "background", ",", "stats", "=", "None", ",", "metrics", "=", "(", "\"roc_auc\"", ",", "\"recall_at_fdr\"", ")", ")", ":", "# combine original and clustered mot...
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. ...
[ "Return", "the", "best", "motif", "per", "cluster", "for", "a", "clustering", "results", "." ]
train
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/denovo.py#L395-L466