INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Translates a row and column cell address to A1 notation. :param row: The row of the cell to be converted. Rows start at index 1. :type row: int, str :param col: The column of the cell to be converted. Columns start at index 1. :type row: int, str :returns: a string...
def rowcol_to_a1(row, col): """Translates a row and column cell address to A1 notation. :param row: The row of the cell to be converted. Rows start at index 1. :type row: int, str :param col: The column of the cell to be converted. Columns start at index 1. :type ro...
Translates a cell's address in A1 notation to a tuple of integers. :param label: A cell label in A1 notation, e.g. 'B1'. Letter case is ignored. :type label: str :returns: a tuple containing `row` and `column` numbers. Both indexed from 1 (one). Example: >>> a1_to...
def a1_to_rowcol(label): """Translates a cell's address in A1 notation to a tuple of integers. :param label: A cell label in A1 notation, e.g. 'B1'. Letter case is ignored. :type label: str :returns: a tuple containing `row` and `column` numbers. Both indexed from 1 (on...
Decorator function casts wrapped arguments to A1 notation in range method calls.
def cast_to_a1_notation(method): """ Decorator function casts wrapped arguments to A1 notation in range method calls. """ @wraps(method) def wrapper(self, *args, **kwargs): try: if len(args): int(args[0]) # Convert to A1 notation range...
Calculate gid of a worksheet from its wid.
def wid_to_gid(wid): """Calculate gid of a worksheet from its wid.""" widval = wid[1:] if len(wid) > 3 else wid xorval = 474 if len(wid) > 3 else 31578 return str(int(widval, 36) ^ xorval)
Authorize client.
def login(self): """Authorize client.""" if not self.auth.access_token or \ (hasattr(self.auth, 'access_token_expired') and self.auth.access_token_expired): import httplib2 http = httplib2.Http() self.auth.refresh(http) self.session.headers.u...
Opens all available spreadsheets. :param title: (optional) If specified can be used to filter spreadsheets by title. :type title: str :returns: a list of :class:`~gspread.models.Spreadsheet` instances.
def openall(self, title=None): """Opens all available spreadsheets. :param title: (optional) If specified can be used to filter spreadsheets by title. :type title: str :returns: a list of :class:`~gspread.models.Spreadsheet` instances. """ spreads...
Opens a spreadsheet. :param title: A title of a spreadsheet. :type title: str :returns: a :class:`~gspread.models.Spreadsheet` instance. If there's more than one spreadsheet with same title the first one will be opened. :raises gspread.SpreadsheetNotFound: if no sprea...
def open(self, title): """Opens a spreadsheet. :param title: A title of a spreadsheet. :type title: str :returns: a :class:`~gspread.models.Spreadsheet` instance. If there's more than one spreadsheet with same title the first one will be opened. :raises gsprea...
Creates a new spreadsheet. :param title: A title of a new spreadsheet. :type title: str :returns: a :class:`~gspread.models.Spreadsheet` instance. .. note:: In order to use this method, you need to add ``https://www.googleapis.com/auth/drive`` to your oAuth scop...
def create(self, title): """Creates a new spreadsheet. :param title: A title of a new spreadsheet. :type title: str :returns: a :class:`~gspread.models.Spreadsheet` instance. .. note:: In order to use this method, you need to add ``https://www.googleapis...
Copies a spreadsheet. :param file_id: A key of a spreadsheet to copy. :type title: str :param title: (optional) A title for the new spreadsheet. :type title: str :param copy_permissions: (optional) If True, copy permissions from original spreadsheet to new sprea...
def copy(self, file_id, title=None, copy_permissions=False): """Copies a spreadsheet. :param file_id: A key of a spreadsheet to copy. :type title: str :param title: (optional) A title for the new spreadsheet. :type title: str :param copy_permissions: (optional) If True...
Deletes a spreadsheet. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str
def del_spreadsheet(self, file_id): """Deletes a spreadsheet. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str """ url = '{0}/{1}'.format( DRIVE_FILES_API_V2_URL, file_id ) self.request('delete', url)
Imports data into the first page of the spreadsheet. :param str data: A CSV string of data. Example: .. code:: # Read CSV file contents content = open('file_to_import.csv', 'r').read() gc.import_csv(spreadsheet.id, content) .. note:: ...
def import_csv(self, file_id, data): """Imports data into the first page of the spreadsheet. :param str data: A CSV string of data. Example: .. code:: # Read CSV file contents content = open('file_to_import.csv', 'r').read() gc.import_csv(spreadsh...
Retrieve a list of permissions for a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str
def list_permissions(self, file_id): """Retrieve a list of permissions for a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str """ url = '{0}/{1}/permissions'.format(DRIVE_FILES_API_V2_URL, file_id) r = self.request('get', url) return r.j...
Creates a new permission for a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str :param value: user or group e-mail address, domain name or None for 'default' type. :type value: str, None :param perm_type: (optional) The account type....
def insert_permission( self, file_id, value, perm_type, role, notify=True, email_message=None, with_link=False ): """Creates a new permission for a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str ...
Deletes a permission from a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str :param permission_id: an ID for the permission. :type permission_id: str
def remove_permission(self, file_id, permission_id): """Deletes a permission from a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str :param permission_id: an ID for the permission. :type permission_id: str """ url = '{0}/{1}/permissions/{2...
A fast (pseudo)-random number generator. Parameters ---------- state: array of int64, shape (3,) The internal state of the rng Returns ------- A (pseudo)-random int32 value
def tau_rand_int(state): """A fast (pseudo)-random number generator. Parameters ---------- state: array of int64, shape (3,) The internal state of the rng Returns ------- A (pseudo)-random int32 value """ state[0] = (((state[0] & 4294967294) << 12) & 0xffffffff) ^ ( ...
Compute the (standard l2) norm of a vector. Parameters ---------- vec: array of shape (dim,) Returns ------- The l2 norm of vec.
def norm(vec): """Compute the (standard l2) norm of a vector. Parameters ---------- vec: array of shape (dim,) Returns ------- The l2 norm of vec. """ result = 0.0 for i in range(vec.shape[0]): result += vec[i] ** 2 return np.sqrt(result)
Generate n_samples many integers from 0 to pool_size such that no integer is selected twice. The duplication constraint is achieved via rejection sampling. Parameters ---------- n_samples: int The number of random samples to select from the pool pool_size: int The size of the t...
def rejection_sample(n_samples, pool_size, rng_state): """Generate n_samples many integers from 0 to pool_size such that no integer is selected twice. The duplication constraint is achieved via rejection sampling. Parameters ---------- n_samples: int The number of random samples to sele...
Constructor for the numba enabled heap objects. The heaps are used for approximate nearest neighbor search, maintaining a list of potential neighbors sorted by their distance. We also flag if potential neighbors are newly added to the list or not. Internally this is stored as a single ndarray; the first...
def make_heap(n_points, size): """Constructor for the numba enabled heap objects. The heaps are used for approximate nearest neighbor search, maintaining a list of potential neighbors sorted by their distance. We also flag if potential neighbors are newly added to the list or not. Internally this is sto...
Restore the heap property for a heap with an out of place element at position ``elt``. This works with a heap pair where heap1 carries the weights and heap2 holds the corresponding elements.
def siftdown(heap1, heap2, elt): """Restore the heap property for a heap with an out of place element at position ``elt``. This works with a heap pair where heap1 carries the weights and heap2 holds the corresponding elements.""" while elt * 2 + 1 < heap1.shape[0]: left_child = elt * 2 + 1 ...
Given an array of heaps (of indices and weights), unpack the heap out to give and array of sorted lists of indices and weights by increasing weight. This is effectively just the second half of heap sort (the first half not being required since we already have the data in a heap). Parameters -------...
def deheap_sort(heap): """Given an array of heaps (of indices and weights), unpack the heap out to give and array of sorted lists of indices and weights by increasing weight. This is effectively just the second half of heap sort (the first half not being required since we already have the data in a heap...
Search the heap for the smallest element that is still flagged. Parameters ---------- heap: array of shape (3, n_samples, n_neighbors) The heaps to search row: int Which of the heaps to search Returns ------- index: int The index of the smallest flagged element...
def smallest_flagged(heap, row): """Search the heap for the smallest element that is still flagged. Parameters ---------- heap: array of shape (3, n_samples, n_neighbors) The heaps to search row: int Which of the heaps to search Returns ------- index: int T...
Build a heap of candidate neighbors for nearest neighbor descent. For each vertex the candidate neighbors are any current neighbors, and any vertices that have the vertex as one of their nearest neighbors. Parameters ---------- current_graph: heap The current state of the graph for nearest ...
def build_candidates(current_graph, n_vertices, n_neighbors, max_candidates, rng_state): """Build a heap of candidate neighbors for nearest neighbor descent. For each vertex the candidate neighbors are any current neighbors, and any vertices that have the vertex as one of their nearest neighbors. Param...
Build a heap of candidate neighbors for nearest neighbor descent. For each vertex the candidate neighbors are any current neighbors, and any vertices that have the vertex as one of their nearest neighbors. Parameters ---------- current_graph: heap The current state of the graph for nearest ...
def new_build_candidates( current_graph, n_vertices, n_neighbors, max_candidates, rng_state, rho=0.5 ): # pragma: no cover """Build a heap of candidate neighbors for nearest neighbor descent. For each vertex the candidate neighbors are any current neighbors, and any vertices that have the vertex as one...
Return a submatrix given an orginal matrix and the indices to keep. Parameters ---------- mat: array, shape (n_samples, n_samples) Original matrix. indices_col: array, shape (n_samples, n_neighbors) Indices to keep. Each row consists of the indices of the columns. n_neighbors: int...
def submatrix(dmat, indices_col, n_neighbors): """Return a submatrix given an orginal matrix and the indices to keep. Parameters ---------- mat: array, shape (n_samples, n_samples) Original matrix. indices_col: array, shape (n_samples, n_neighbors) Indices to keep. Each row consist...
Standard euclidean distance. ..math:: D(x, y) = \sqrt{\sum_i (x_i - y_i)^2}
def euclidean(x, y): """Standard euclidean distance. ..math:: D(x, y) = \sqrt{\sum_i (x_i - y_i)^2} """ result = 0.0 for i in range(x.shape[0]): result += (x[i] - y[i]) ** 2 return np.sqrt(result)
Euclidean distance standardised against a vector of standard deviations per coordinate. ..math:: D(x, y) = \sqrt{\sum_i \frac{(x_i - y_i)**2}{v_i}}
def standardised_euclidean(x, y, sigma=_mock_ones): """Euclidean distance standardised against a vector of standard deviations per coordinate. ..math:: D(x, y) = \sqrt{\sum_i \frac{(x_i - y_i)**2}{v_i}} """ result = 0.0 for i in range(x.shape[0]): result += ((x[i] - y[i]) ** 2) ...
Manhatten, taxicab, or l1 distance. ..math:: D(x, y) = \sum_i |x_i - y_i|
def manhattan(x, y): """Manhatten, taxicab, or l1 distance. ..math:: D(x, y) = \sum_i |x_i - y_i| """ result = 0.0 for i in range(x.shape[0]): result += np.abs(x[i] - y[i]) return result
Chebyshev or l-infinity distance. ..math:: D(x, y) = \max_i |x_i - y_i|
def chebyshev(x, y): """Chebyshev or l-infinity distance. ..math:: D(x, y) = \max_i |x_i - y_i| """ result = 0.0 for i in range(x.shape[0]): result = max(result, np.abs(x[i] - y[i])) return result
Minkowski distance. ..math:: D(x, y) = \left(\sum_i |x_i - y_i|^p\right)^{\frac{1}{p}} This is a general distance. For p=1 it is equivalent to manhattan distance, for p=2 it is Euclidean distance, and for p=infinity it is Chebyshev distance. In general it is better to use the more speciali...
def minkowski(x, y, p=2): """Minkowski distance. ..math:: D(x, y) = \left(\sum_i |x_i - y_i|^p\right)^{\frac{1}{p}} This is a general distance. For p=1 it is equivalent to manhattan distance, for p=2 it is Euclidean distance, and for p=infinity it is Chebyshev distance. In general it is be...
Create a numba accelerated version of nearest neighbor descent specialised for the given distance metric and metric arguments. Numba doesn't support higher order functions directly, but we can instead JIT compile the version of NN-descent for any given metric. Parameters ---------- dist: functi...
def make_nn_descent(dist, dist_args): """Create a numba accelerated version of nearest neighbor descent specialised for the given distance metric and metric arguments. Numba doesn't support higher order functions directly, but we can instead JIT compile the version of NN-descent for any given metric. ...
Provide a layout relating the separate connected components. This is done by taking the centroid of each component and then performing a spectral embedding of the centroids. Parameters ---------- data: array of shape (n_samples, n_features) The source data -- required so we can generate cen...
def component_layout( data, n_components, component_labels, dim, metric="euclidean", metric_kwds={} ): """Provide a layout relating the separate connected components. This is done by taking the centroid of each component and then performing a spectral embedding of the centroids. Parameters ----...
Specialised layout algorithm for dealing with graphs with many connected components. This will first fid relative positions for the components by spectrally embedding their centroids, then spectrally embed each individual connected component positioning them according to the centroid embeddings. This provid...
def multi_component_layout( data, graph, n_components, component_labels, dim, random_state, metric="euclidean", metric_kwds={}, ): """Specialised layout algorithm for dealing with graphs with many connected components. This will first fid relative positions for the components by ...
Given a graph compute the spectral embedding of the graph. This is simply the eigenvectors of the laplacian of the graph. Here we use the normalized laplacian. Parameters ---------- data: array of shape (n_samples, n_features) The source data graph: sparse matrix The (weighted)...
def spectral_layout(data, graph, dim, random_state, metric="euclidean", metric_kwds={}): """Given a graph compute the spectral embedding of the graph. This is simply the eigenvectors of the laplacian of the graph. Here we use the normalized laplacian. Parameters ---------- data: array of shape ...
Given a set of ``indices`` for data points from a sparse data set presented in csr sparse format as inds, indptr and data, create a random hyperplane to split the data, returning two arrays indices that fall on either side of the hyperplane. This is the basis for a random projection tree, which simply u...
def sparse_angular_random_projection_split(inds, indptr, data, indices, rng_state): """Given a set of ``indices`` for data points from a sparse data set presented in csr sparse format as inds, indptr and data, create a random hyperplane to split the data, returning two arrays indices that fall on either...
Given a set of ``indices`` for data points from a sparse data set presented in csr sparse format as inds, indptr and data, create a random hyperplane to split the data, returning two arrays indices that fall on either side of the hyperplane. This is the basis for a random projection tree, which simply u...
def sparse_euclidean_random_projection_split(inds, indptr, data, indices, rng_state): """Given a set of ``indices`` for data points from a sparse data set presented in csr sparse format as inds, indptr and data, create a random hyperplane to split the data, returning two arrays indices that fall on eith...
Construct a random projection tree based on ``data`` with leaves of size at most ``leaf_size``. Parameters ---------- data: array of shape (n_samples, n_features) The original data to be split rng_state: array of int64, shape (3,) The internal state of the rng leaf_size: int (opt...
def make_tree(data, rng_state, leaf_size=30, angular=False): """Construct a random projection tree based on ``data`` with leaves of size at most ``leaf_size``. Parameters ---------- data: array of shape (n_samples, n_features) The original data to be split rng_state: array of int64, shap...
Determine the number of nodes in a tree
def num_nodes(tree): """Determine the number of nodes in a tree""" if tree.is_leaf: return 1 else: return 1 + num_nodes(tree.left_child) + num_nodes(tree.right_child)
Determine the number of leaves in a tree
def num_leaves(tree): """Determine the number of leaves in a tree""" if tree.is_leaf: return 1 else: return num_leaves(tree.left_child) + num_leaves(tree.right_child)
Determine the most number on non zeros in a hyperplane entry
def max_sparse_hyperplane_size(tree): """Determine the most number on non zeros in a hyperplane entry""" if tree.is_leaf: return 0 else: return max( tree.hyperplane.shape[1], max_sparse_hyperplane_size(tree.left_child), max_sparse_hyperplane_size(tree.righ...
Build a random projection forest with ``n_trees``. Parameters ---------- data n_neighbors n_trees rng_state angular Returns ------- forest: list A list of random projection trees.
def make_forest(data, n_neighbors, n_trees, rng_state, angular=False): """Build a random projection forest with ``n_trees``. Parameters ---------- data n_neighbors n_trees rng_state angular Returns ------- forest: list A list of random projection trees. """ ...
Generate an array of sets of candidate nearest neighbors by constructing a random projection forest and taking the leaves of all the trees. Any given tree has leaves that are a set of potential nearest neighbors. Given enough trees the set of all such leaves gives a good likelihood of getting a good set...
def rptree_leaf_array(rp_forest): """Generate an array of sets of candidate nearest neighbors by constructing a random projection forest and taking the leaves of all the trees. Any given tree has leaves that are a set of potential nearest neighbors. Given enough trees the set of all such leaves gives a ...
Compute a continuous version of the distance to the kth nearest neighbor. That is, this is similar to knn-distance but allows continuous k values rather than requiring an integral k. In esscence we are simply computing the distance such that the cardinality of fuzzy set we generate is k. Parameters...
def smooth_knn_dist(distances, k, n_iter=64, local_connectivity=1.0, bandwidth=1.0): """Compute a continuous version of the distance to the kth nearest neighbor. That is, this is similar to knn-distance but allows continuous k values rather than requiring an integral k. In esscence we are simply computi...
Compute the ``n_neighbors`` nearest points for each data point in ``X`` under ``metric``. This may be exact, but more likely is approximated via nearest neighbor descent. Parameters ---------- X: array of shape (n_samples, n_features) The input data to compute the k-neighbor graph of. ...
def nearest_neighbors( X, n_neighbors, metric, metric_kwds, angular, random_state, verbose=False ): """Compute the ``n_neighbors`` nearest points for each data point in ``X`` under ``metric``. This may be exact, but more likely is approximated via nearest neighbor descent. Parameters ----------...
Construct the membership strength data for the 1-skeleton of each local fuzzy simplicial set -- this is formed as a sparse matrix where each row is a local fuzzy simplicial set, with a membership strength for the 1-simplex to each other data point. Parameters ---------- knn_indices: array of sh...
def compute_membership_strengths(knn_indices, knn_dists, sigmas, rhos): """Construct the membership strength data for the 1-skeleton of each local fuzzy simplicial set -- this is formed as a sparse matrix where each row is a local fuzzy simplicial set, with a membership strength for the 1-simplex to eac...
Given a set of data X, a neighborhood size, and a measure of distance compute the fuzzy simplicial set (here represented as a fuzzy graph in the form of a sparse matrix) associated to the data. This is done by locally approximating geodesic distance at each point, creating a fuzzy simplicial set for eac...
def fuzzy_simplicial_set( X, n_neighbors, random_state, metric, metric_kwds={}, knn_indices=None, knn_dists=None, angular=False, set_op_mix_ratio=1.0, local_connectivity=1.0, verbose=False, ): """Given a set of data X, a neighborhood size, and a measure of distance co...
Under the assumption of categorical distance for the intersecting simplicial set perform a fast intersection. Parameters ---------- rows: array An array of the row of each non-zero in the sparse matrix representation. cols: array An array of the column of each non-zero in t...
def fast_intersection(rows, cols, values, target, unknown_dist=1.0, far_dist=5.0): """Under the assumption of categorical distance for the intersecting simplicial set perform a fast intersection. Parameters ---------- rows: array An array of the row of each non-zero in the sparse matrix ...
Reset the local connectivity requirement -- each data sample should have complete confidence in at least one 1-simplex in the simplicial set. We can enforce this by locally rescaling confidences, and then remerging the different local simplicial sets together. Parameters ---------- simplicial_s...
def reset_local_connectivity(simplicial_set): """Reset the local connectivity requirement -- each data sample should have complete confidence in at least one 1-simplex in the simplicial set. We can enforce this by locally rescaling confidences, and then remerging the different local simplicial sets toge...
Combine a fuzzy simplicial set with another fuzzy simplicial set generated from categorical data using categorical distances. The target data is assumed to be categorical label data (a vector of labels), and this will update the fuzzy simplicial set to respect that label data. TODO: optional category c...
def categorical_simplicial_set_intersection( simplicial_set, target, unknown_dist=1.0, far_dist=5.0 ): """Combine a fuzzy simplicial set with another fuzzy simplicial set generated from categorical data using categorical distances. The target data is assumed to be categorical label data (a vector of lab...
Given a set of weights and number of epochs generate the number of epochs per sample for each weight. Parameters ---------- weights: array of shape (n_1_simplices) The weights ofhow much we wish to sample each 1-simplex. n_epochs: int The total number of epochs we want to train for...
def make_epochs_per_sample(weights, n_epochs): """Given a set of weights and number of epochs generate the number of epochs per sample for each weight. Parameters ---------- weights: array of shape (n_1_simplices) The weights ofhow much we wish to sample each 1-simplex. n_epochs: int ...
Reduced Euclidean distance. Parameters ---------- x: array of shape (embedding_dim,) y: array of shape (embedding_dim,) Returns ------- The squared euclidean distance between x and y
def rdist(x, y): """Reduced Euclidean distance. Parameters ---------- x: array of shape (embedding_dim,) y: array of shape (embedding_dim,) Returns ------- The squared euclidean distance between x and y """ result = 0.0 for i in range(x.shape[0]): result += (x[i] - ...
Improve an embedding using stochastic gradient descent to minimize the fuzzy set cross entropy between the 1-skeletons of the high dimensional and low dimensional fuzzy simplicial sets. In practice this is done by sampling edges based on their membership strength (with the (1-p) terms coming from negati...
def optimize_layout( head_embedding, tail_embedding, head, tail, n_epochs, n_vertices, epochs_per_sample, a, b, rng_state, gamma=1.0, initial_alpha=1.0, negative_sample_rate=5.0, verbose=False, ): """Improve an embedding using stochastic gradient descent to mi...
Perform a fuzzy simplicial set embedding, using a specified initialisation method and then minimizing the fuzzy set cross entropy between the 1-skeletons of the high and low dimensional fuzzy simplicial sets. Parameters ---------- data: array of shape (n_samples, n_features) The source ...
def simplicial_set_embedding( data, graph, n_components, initial_alpha, a, b, gamma, negative_sample_rate, n_epochs, init, random_state, metric, metric_kwds, verbose, ): """Perform a fuzzy simplicial set embedding, using a specified initialisation method a...
Fit a, b params for the differentiable curve used in lower dimensional fuzzy simplicial complex construction. We want the smooth curve (from a pre-defined family with simple gradient) that best matches an offset exponential decay.
def find_ab_params(spread, min_dist): """Fit a, b params for the differentiable curve used in lower dimensional fuzzy simplicial complex construction. We want the smooth curve (from a pre-defined family with simple gradient) that best matches an offset exponential decay. """ def curve(x, a, b):...
Fit X into an embedded space. Optionally use y for supervised dimension reduction. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance matrix. Otherwise it contains a...
def fit(self, X, y=None): """Fit X into an embedded space. Optionally use y for supervised dimension reduction. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance ...
Fit X into an embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance matrix. Otherwise it contains a sample per row. ...
def fit_transform(self, X, y=None): """Fit X into an embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance mat...
Transform X into the existing embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) New data to be transformed. Returns ------- X_new : array, shape (n_samples, n_components) Emb...
def transform(self, X): """Transform X into the existing embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) New data to be transformed. Returns ------- X_new : array, shape (n_sam...
Create a numba accelerated version of nearest neighbor descent specialised for the given distance metric and metric arguments on sparse matrix data provided in CSR ind, indptr and data format. Numba doesn't support higher order functions directly, but we can instead JIT compile the version of NN-descent...
def make_sparse_nn_descent(sparse_dist, dist_args): """Create a numba accelerated version of nearest neighbor descent specialised for the given distance metric and metric arguments on sparse matrix data provided in CSR ind, indptr and data format. Numba doesn't support higher order functions directly, b...
Get an InterfaceOptions for the config.
def interface_options(score=False, raw=False, features=None, rgb=None): """Get an InterfaceOptions for the config.""" interface = sc_pb.InterfaceOptions() interface.score = score interface.raw = raw if features: interface.feature_layer.width = 24 interface.feature_layer.resolution.x = features int...
Registers a flag whose value parses as a point.
def DEFINE_point(name, default, help): # pylint: disable=invalid-name,redefined-builtin """Registers a flag whose value parses as a point.""" flags.DEFINE(PointParser(), name, default, help)
Choose the action space for the action proto.
def spatial(action, action_space): """Choose the action space for the action proto.""" if action_space == ActionSpace.FEATURES: return action.action_feature_layer elif action_space == ActionSpace.RGB: return action.action_render else: raise ValueError("Unexpected value for action_space: %s" % action...
Move the camera.
def move_camera(action, action_space, minimap): """Move the camera.""" minimap.assign_to(spatial(action, action_space).camera_move.center_minimap)
Select a unit at a point.
def select_point(action, action_space, select_point_act, screen): """Select a unit at a point.""" select = spatial(action, action_space).unit_selection_point screen.assign_to(select.selection_screen_coord) select.type = select_point_act
Select units within a rectangle.
def select_rect(action, action_space, select_add, screen, screen2): """Select units within a rectangle.""" select = spatial(action, action_space).unit_selection_rect out_rect = select.selection_screen_coord.add() screen_rect = point.Rect(screen, screen2) screen_rect.tl.assign_to(out_rect.p0) screen_rect.br....
Select an idle worker.
def select_idle_worker(action, action_space, select_worker): """Select an idle worker.""" del action_space action.action_ui.select_idle_worker.type = select_worker
Select the entire army.
def select_army(action, action_space, select_add): """Select the entire army.""" del action_space action.action_ui.select_army.selection_add = select_add
Select all warp gates.
def select_warp_gates(action, action_space, select_add): """Select all warp gates.""" del action_space action.action_ui.select_warp_gates.selection_add = select_add
Select a specific unit from the multi-unit selection.
def select_unit(action, action_space, select_unit_act, select_unit_id): """Select a specific unit from the multi-unit selection.""" del action_space select = action.action_ui.multi_panel select.type = select_unit_act select.unit_index = select_unit_id
Act on a control group, selecting, setting, etc.
def control_group(action, action_space, control_group_act, control_group_id): """Act on a control group, selecting, setting, etc.""" del action_space select = action.action_ui.control_group select.action = control_group_act select.control_group_index = control_group_id
Unload a unit from a transport/bunker/nydus/etc.
def unload(action, action_space, unload_id): """Unload a unit from a transport/bunker/nydus/etc.""" del action_space action.action_ui.cargo_panel.unit_index = unload_id
Cancel a unit in the build queue.
def build_queue(action, action_space, build_queue_id): """Cancel a unit in the build queue.""" del action_space action.action_ui.production_panel.unit_index = build_queue_id
Do a quick command like 'Stop' or 'Stim'.
def cmd_quick(action, action_space, ability_id, queued): """Do a quick command like 'Stop' or 'Stim'.""" action_cmd = spatial(action, action_space).unit_command action_cmd.ability_id = ability_id action_cmd.queue_command = queued
Do a command that needs a point on the screen.
def cmd_screen(action, action_space, ability_id, queued, screen): """Do a command that needs a point on the screen.""" action_cmd = spatial(action, action_space).unit_command action_cmd.ability_id = ability_id action_cmd.queue_command = queued screen.assign_to(action_cmd.target_screen_coord)
Do a command that needs a point on the minimap.
def cmd_minimap(action, action_space, ability_id, queued, minimap): """Do a command that needs a point on the minimap.""" action_cmd = spatial(action, action_space).unit_command action_cmd.ability_id = ability_id action_cmd.queue_command = queued minimap.assign_to(action_cmd.target_minimap_coord)
Toggle autocast.
def autocast(action, action_space, ability_id): """Toggle autocast.""" del action_space action.action_ui.toggle_autocast.ability_id = ability_id
Create an ArgumentType where you choose one of a set of known values.
def enum(cls, options, values): """Create an ArgumentType where you choose one of a set of known values.""" names, real = zip(*options) del names # unused def factory(i, name): return cls(i, name, (len(real),), lambda a: real[a[0]], values) return factory
Create an ArgumentType with a single scalar in range(value).
def scalar(cls, value): """Create an ArgumentType with a single scalar in range(value).""" return lambda i, name: cls(i, name, (value,), lambda a: a[0], None)
Create an ArgumentType that is represented by a point.Point.
def point(cls): # No range because it's unknown at this time. """Create an ArgumentType that is represented by a point.Point.""" def factory(i, name): return cls(i, name, (0, 0), lambda a: point.Point(*a).floor(), None) return factory
Create an Arguments of the possible Types.
def types(cls, **kwargs): """Create an Arguments of the possible Types.""" named = {name: factory(Arguments._fields.index(name), name) for name, factory in six.iteritems(kwargs)} return cls(**named)
Define a function representing a ui action.
def ui_func(cls, id_, name, function_type, avail_fn=always): """Define a function representing a ui action.""" return cls(id_, name, 0, 0, function_type, FUNCTION_TYPES[function_type], avail_fn)
Define a function represented as a game ability.
def ability(cls, id_, name, function_type, ability_id, general_id=0): """Define a function represented as a game ability.""" assert function_type in ABILITY_FUNCTIONS return cls(id_, name, ability_id, general_id, function_type, FUNCTION_TYPES[function_type], None)
String version. Set space=True to line them all up nicely.
def str(self, space=False): """String version. Set space=True to line them all up nicely.""" return "%s/%s (%s)" % (str(int(self.id)).rjust(space and 4), self.name.ljust(space and 50), "; ".join(str(a) for a in self.args))
Return a `FunctionCall` given some validation for the function and args. Args: function: A function name or id, to be converted into a function id enum. arguments: An iterable of function arguments. Arguments that are enum types can be passed by name. Arguments that only take one value (ie ...
def init_with_validation(cls, function, arguments): """Return a `FunctionCall` given some validation for the function and args. Args: function: A function name or id, to be converted into a function id enum. arguments: An iterable of function arguments. Arguments that are enum types can b...
Helper function for creating `FunctionCall`s with `Arguments`. Args: function: The value to store for the action function. arguments: The values to store for the arguments of the action. Can either be an `Arguments` object, a `dict`, or an iterable. If a `dict` or an iterable is provide...
def all_arguments(cls, function, arguments): """Helper function for creating `FunctionCall`s with `Arguments`. Args: function: The value to store for the action function. arguments: The values to store for the arguments of the action. Can either be an `Arguments` object, a `dict`, or an ite...
Print the valid actions.
def main(unused_argv): """Print the valid actions.""" feats = features.Features( # Actually irrelevant whether it's feature or rgb size. features.AgentInterfaceFormat( feature_dimensions=features.Dimensions( screen=FLAGS.screen_size, minimap=FLAGS.minimap_size))) ...
Reserves and returns a list of `num_ports` unused ports.
def pick_unused_ports(num_ports, retry_interval_secs=3, retry_attempts=5): """Reserves and returns a list of `num_ports` unused ports.""" ports = set() for _ in range(retry_attempts): ports.update( portpicker.pick_unused_port() for _ in range(num_ports - len(ports))) ports.discard(None) # portpic...
Reserves and returns a list of `num_ports` contiguous unused ports.
def pick_contiguous_unused_ports( num_ports, retry_interval_secs=3, retry_attempts=5): """Reserves and returns a list of `num_ports` contiguous unused ports.""" for _ in range(retry_attempts): start_port = portpicker.pick_unused_port() if start_port is not None: ports = [start_port + p for...
Run one thread worth of the environment with agents.
def run_thread(agent_classes, players, map_name, visualize): """Run one thread worth of the environment with agents.""" with sc2_env.SC2Env( map_name=map_name, players=players, agent_interface_format=sc2_env.parse_agent_interface_format( feature_screen=FLAGS.feature_screen_size, ...
Run an agent.
def main(unused_argv): """Run an agent.""" stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace stopwatch.sw.trace = FLAGS.trace map_inst = maps.get(FLAGS.map) agent_classes = [] players = [] agent_module, agent_name = FLAGS.agent.rsplit(".", 1) agent_cls = getattr(importlib.import_module(agent_module...
Raise if the result has an error, otherwise return the result.
def check_error(res, error_enum): """Raise if the result has an error, otherwise return the result.""" if res.HasField("error"): enum_name = error_enum.DESCRIPTOR.full_name error_name = error_enum.Name(res.error) details = getattr(res, "error_details", "<none>") raise RequestError("%s.%s: '%s'" % (e...
Decorator to call `check_error` on the return value.
def decorate_check_error(error_enum): """Decorator to call `check_error` on the return value.""" def decorator(func): @functools.wraps(func) def _check_error(*args, **kwargs): return check_error(func(*args, **kwargs), error_enum) return _check_error return decorator
Decorator to skip this call if we're in one of the skipped states.
def skip_status(*skipped): """Decorator to skip this call if we're in one of the skipped states.""" def decorator(func): @functools.wraps(func) def _skip_status(self, *args, **kwargs): if self.status not in skipped: return func(self, *args, **kwargs) return _skip_status return decorator
Decorator to assert that we're in a valid state.
def valid_status(*valid): """Decorator to assert that we're in a valid state.""" def decorator(func): @functools.wraps(func) def _valid_status(self, *args, **kwargs): if self.status not in valid: raise protocol.ProtocolError( "`%s` called while in state: %s, valid: (%s)" % ( ...
Decorator to handle 'Game has already ended' exceptions.
def catch_game_end(func): """Decorator to handle 'Game has already ended' exceptions.""" @functools.wraps(func) def _catch_game_end(self, *args, **kwargs): """Decorator to handle 'Game has already ended' exceptions.""" prev_status = self.status try: return func(self, *args, **kwargs) except ...
Connect to the websocket, retrying as needed. Returns the socket.
def _connect(self, host, port, proc, timeout_seconds): """Connect to the websocket, retrying as needed. Returns the socket.""" if ":" in host and not host.startswith("["): # Support ipv6 addresses. host = "[%s]" % host url = "ws://%s:%s/sc2api" % (host, port) was_running = False for i in ran...
Save a map into temp dir so create game can access it in multiplayer.
def save_map(self, map_path, map_data): """Save a map into temp dir so create game can access it in multiplayer.""" return self._client.send(save_map=sc_pb.RequestSaveMap( map_path=map_path, map_data=map_data))
Get the raw static data for the current game. Prefer `data` instead.
def data_raw(self): """Get the raw static data for the current game. Prefer `data` instead.""" return self._client.send(data=sc_pb.RequestData( ability_id=True, unit_type_id=True))
Step the engine forward by one (or more) step.
def step(self, count=1): """Step the engine forward by one (or more) step.""" return self._client.send(step=sc_pb.RequestStep(count=count))
Send a `sc_pb.RequestAction`, which may include multiple actions.
def actions(self, req_action): """Send a `sc_pb.RequestAction`, which may include multiple actions.""" if FLAGS.sc2_log_actions: for action in req_action.actions: sys.stderr.write(str(action)) sys.stderr.flush() return self._client.send(action=req_action)
Send a single action. This is a shortcut for `actions`.
def act(self, action): """Send a single action. This is a shortcut for `actions`.""" if action and action.ListFields(): # Skip no-ops. return self.actions(sc_pb.RequestAction(actions=[action]))
Send chat message as a broadcast.
def chat(self, message): """Send chat message as a broadcast.""" if message: action_chat = sc_pb.ActionChat( channel=sc_pb.ActionChat.Broadcast, message=message) action = sc_pb.Action(action_chat=action_chat) return self.act(action)