INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Performs a keyboard key release ( without the press down beforehand ).
def keyUp(key, pause=None, _pause=True): """Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in KEYBOARD_KEYS. Returns: None """ if len(key) > 1: key = key.lower() _failSafeChe...
Performs a keyboard key press down followed by a release.
def press(keys, presses=1, interval=0.0, pause=None, _pause=True): """Performs a keyboard key press down, followed by a release. Args: key (str, list): The key to be pressed. The valid names are listed in KEYBOARD_KEYS. Can also be a list of such strings. presses (integer, optiional): the num...
Performs a keyboard key press down followed by a release for each of the characters in message.
def typewrite(message, interval=0.0, pause=None, _pause=True): """Performs a keyboard key press down, followed by a release, for each of the characters in message. The message argument can also be list of strings, in which case any valid keyboard name can be used. Since this performs a sequence of...
Performs key down presses on the arguments passed in order then performs key releases in reverse order.
def hotkey(*args, **kwargs): """Performs key down presses on the arguments passed in order, then performs key releases in reverse order. The effect is that calling hotkey('ctrl', 'shift', 'c') would perform a "Ctrl-Shift-C" hotkey/keyboard shortcut press. Args: key(s) (str): The series of ke...
This function is meant to be run from the command line. It will automatically display the location and RGB of the mouse cursor.
def displayMousePosition(xOffset=0, yOffset=0): """This function is meant to be run from the command line. It will automatically display the location and RGB of the mouse cursor.""" print('Press Ctrl-C to quit.') if xOffset != 0 or yOffset != 0: print('xOffset: %s yOffset: %s' % (xOffset, yOffse...
Performs a keyboard key press without the release. This will put that key in a held down state.
def _keyDown(key): """Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down....
Returns the current xy coordinates of the mouse cursor as a two - integer tuple by calling the GetCursorPos () win32 function.
def _position(): """Returns the current xy coordinates of the mouse cursor as a two-integer tuple by calling the GetCursorPos() win32 function. Returns: (x, y) tuple of the current xy coordinates of the mouse cursor. """ cursor = POINT() ctypes.windll.user32.GetCursorPos(ctypes.byref(cur...
Send the mouse down event to Windows by calling the mouse_event () win32 function.
def _mouseDown(x, y, button): """Send the mouse down event to Windows by calling the mouse_event() win32 function. Args: x (int): The x position of the mouse event. y (int): The y position of the mouse event. button (str): The mouse button, either 'left', 'middle', or 'right' Returns...
Send the mouse up event to Windows by calling the mouse_event () win32 function.
def _mouseUp(x, y, button): """Send the mouse up event to Windows by calling the mouse_event() win32 function. Args: x (int): The x position of the mouse event. y (int): The y position of the mouse event. button (str): The mouse button, either 'left', 'middle', or 'right' Returns: ...
Send the mouse click event to Windows by calling the mouse_event () win32 function.
def _click(x, y, button): """Send the mouse click event to Windows by calling the mouse_event() win32 function. Args: button (str): The mouse button, either 'left', 'middle', or 'right' x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: ...
The helper function that actually makes the call to the mouse_event () win32 function.
def _sendMouseEvent(ev, x, y, dwData=0): """The helper function that actually makes the call to the mouse_event() win32 function. Args: ev (int): The win32 code for the mouse event. Use one of the MOUSEEVENTF_* constants for this argument. x (int): The x position of the mouse event. ...
Send the mouse vertical scroll event to Windows by calling the mouse_event () win32 function.
def _scroll(clicks, x=None, y=None): """Send the mouse vertical scroll event to Windows by calling the mouse_event() win32 function. Args: clicks (int): The amount of scrolling to do. A positive value is the mouse wheel moving forward (scrolling up), a negative value is backwards (down). ...
Login to Google API using OAuth2 credentials. This is a shortcut function which instantiates: class: gspread. client. Client and performs login right away.
def authorize(credentials, client_class=Client): """Login to Google API using OAuth2 credentials. This is a shortcut function which instantiates :class:`gspread.client.Client` and performs login right away. :returns: :class:`gspread.Client` instance. """ client = client_class(auth=credentia...
Spreadsheet title.
def title(self): """Spreadsheet title.""" try: return self._properties['title'] except KeyError: metadata = self.fetch_sheet_metadata() self._properties.update(metadata['properties']) return self._properties['title']
Lower - level method that directly calls spreadsheets. batchUpdate <https:// developers. google. com/ sheets/ api/ reference/ rest/ v4/ spreadsheets/ batchUpdate > _.
def batch_update(self, body): """Lower-level method that directly calls `spreadsheets.batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate>`_. :param dict body: `Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate...
Lower - level method that directly calls spreadsheets. values. append <https:// developers. google. com/ sheets/ api/ reference/ rest/ v4/ spreadsheets. values/ append > _.
def values_append(self, range, params, body): """Lower-level method that directly calls `spreadsheets.values.append <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_...
Lower - level method that directly calls spreadsheets. values. clear <https:// developers. google. com/ sheets/ api/ reference/ rest/ v4/ spreadsheets. values/ clear > _.
def values_clear(self, range): """Lower-level method that directly calls `spreadsheets.values.clear <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of th...
Lower - level method that directly calls spreadsheets. values. get <https:// developers. google. com/ sheets/ api/ reference/ rest/ v4/ spreadsheets. values/ get > _.
def values_get(self, range, params=None): """Lower-level method that directly calls `spreadsheets.values.get <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`...
Lower - level method that directly calls spreadsheets. values. update <https:// developers. google. com/ sheets/ api/ reference/ rest/ v4/ spreadsheets. values/ update > _.
def values_update(self, range, params=None, body=None): """Lower-level method that directly calls `spreadsheets.values.update <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/co...
Returns a worksheet with specified index.
def get_worksheet(self, index): """Returns a worksheet with specified `index`. :param index: An index of a worksheet. Indexes start from zero. :type index: int :returns: an instance of :class:`gsperad.models.Worksheet` or `None` if the worksheet is not found. ...
Returns a list of all: class: worksheets <gsperad. models. Worksheet > in a spreadsheet.
def worksheets(self): """Returns a list of all :class:`worksheets <gsperad.models.Worksheet>` in a spreadsheet. """ sheet_data = self.fetch_sheet_metadata() return [Worksheet(self, x['properties']) for x in sheet_data['sheets']]
Returns a worksheet with specified title.
def worksheet(self, title): """Returns a worksheet with specified `title`. :param title: A title of a worksheet. If there're multiple worksheets with the same title, first one will be returned. :type title: int :returns: an instance of :class...
Adds a new worksheet to a spreadsheet.
def add_worksheet(self, title, rows, cols): """Adds a new worksheet to a spreadsheet. :param title: A title of a new worksheet. :type title: str :param rows: Number of rows. :type rows: int :param cols: Number of columns. :type cols: int :returns: a newl...
Duplicates the contents of a sheet.
def duplicate_sheet( self, source_sheet_id, insert_sheet_index=None, new_sheet_id=None, new_sheet_name=None ): """Duplicates the contents of a sheet. :param int source_sheet_id: The sheet ID to duplicate. :param int insert_sheet_index: (optional) The ...
Share the spreadsheet with other accounts.
def share(self, value, perm_type, role, notify=True, email_message=None, with_link=False): """Share the spreadsheet with other accounts. :param value: user or group e-mail address, domain name or None for 'default' type. :type value: str, None :param perm_type: The...
Remove permissions from a user or domain.
def remove_permissions(self, value, role='any'): """Remove permissions from a user or domain. :param value: User or domain to remove permissions from :type value: str :param role: (optional) Permission to remove. Defaults to all permissions. :type role: str ...
Returns an instance of a: class: gspread. models. Cell.
def acell(self, label, value_render_option='FORMATTED_VALUE'): """Returns an instance of a :class:`gspread.models.Cell`. :param label: Cell label in A1 notation Letter case is ignored. :type label: str :param value_render_option: (optional) Determines how values sh...
Returns an instance of a: class: gspread. models. Cell located at row and col column.
def cell(self, row, col, value_render_option='FORMATTED_VALUE'): """Returns an instance of a :class:`gspread.models.Cell` located at `row` and `col` column. :param row: Row number. :type row: int :param col: Column number. :type col: int :param value_render_optio...
Returns a list of: class: Cell objects from a specified range.
def range(self, name): """Returns a list of :class:`Cell` objects from a specified range. :param name: A string with range value in A1 notation, e.g. 'A1:A5'. :type name: str Alternatively, you may specify numeric boundaries. All values index from 1 (one): :param first...
Returns a list of lists containing all cells values as strings.
def get_all_values(self): """Returns a list of lists containing all cells' values as strings. .. note:: Empty trailing rows and columns will not be included. """ data = self.spreadsheet.values_get(self.title) try: return fill_gaps(data['values']) ...
Returns a list of dictionaries all of them having the contents of the spreadsheet with the head row as keys and each of these dictionaries holding the contents of subsequent rows of cells as values.
def get_all_records( self, empty2zero=False, head=1, default_blank="", allow_underscores_in_numeric_literals=False, ): """Returns a list of dictionaries, all of them having the contents of the spreadsheet with the head row as keys and each of these ...
Returns a list of all values in a row.
def row_values(self, row, value_render_option='FORMATTED_VALUE'): """Returns a list of all values in a `row`. Empty cells in this list will be rendered as :const:`None`. :param row: Row number. :type row: int :param value_render_option: (optional) Determines how values should b...
Returns a list of all values in column col.
def col_values(self, col, value_render_option='FORMATTED_VALUE'): """Returns a list of all values in column `col`. Empty cells in this list will be rendered as :const:`None`. :param col: Column number. :type col: int :param value_render_option: (optional) Determines how values ...
Updates the value of a cell.
def update_acell(self, label, value): """Updates the value of a cell. :param label: Cell label in A1 notation. Letter case is ignored. :type label: str :param value: New value. Example:: worksheet.update_acell('A1', '42') """ ...
Updates the value of a cell.
def update_cell(self, row, col, value): """Updates the value of a cell. :param row: Row number. :type row: int :param col: Column number. :type col: int :param value: New value. Example:: worksheet.update_cell(1, 1, '42') """ range_...
Updates many cells at once.
def update_cells(self, cell_list, value_input_option='RAW'): """Updates many cells at once. :param cell_list: List of :class:`Cell` objects to update. :param value_input_option: (optional) Determines how input data should be interpreted. See `ValueInputOption...
Resizes the worksheet. Specify one of rows or cols.
def resize(self, rows=None, cols=None): """Resizes the worksheet. Specify one of ``rows`` or ``cols``. :param rows: (optional) New number of rows. :type rows: int :param cols: (optional) New number columns. :type cols: int """ grid_properties = {} if row...
Renames the worksheet.
def update_title(self, title): """Renames the worksheet. :param title: A new title. :type title: str """ body = { 'requests': [{ 'updateSheetProperties': { 'properties': { 'sheetId': self.id, ...
Adds a row to the worksheet and populates it with values. Widens the worksheet if there are more values than columns.
def append_row(self, values, value_input_option='RAW'): """Adds a row to the worksheet and populates it with values. Widens the worksheet if there are more values than columns. :param values: List of values for the new row. :param value_input_option: (optional) Determines how input data...
Adds a row to the worksheet at the specified index and populates it with values.
def insert_row( self, values, index=1, value_input_option='RAW' ): """Adds a row to the worksheet at the specified index and populates it with values. Widens the worksheet if there are more values than columns. :param values: List of values for the n...
Deletes the row from the worksheet at the specified index.
def delete_row(self, index): """"Deletes the row from the worksheet at the specified index. :param index: Index of a row for deletion. :type index: int """ body = { "requests": [{ "deleteDimension": { "range": { ...
Finds the first cell matching the query.
def find(self, query): """Finds the first cell matching the query. :param query: A literal string to match or compiled regular expression. :type query: str, :py:class:`re.RegexObject` """ try: return self._finder(finditem, query) except StopIteration: ...
Duplicate the sheet.
def duplicate( self, insert_sheet_index=None, new_sheet_id=None, new_sheet_name=None ): """Duplicate the sheet. :param int insert_sheet_index: (optional) The zero-based index where the new sheet should be inserted. ...
Returns a value that depends on the input string: - Float if input can be converted to Float - Integer if input can be converted to integer - Zero if the input string is empty and empty2zero flag is set - The same input string empty or not otherwise.
def numericise(value, empty2zero=False, default_blank="", allow_underscores_in_numeric_literals=False): """Returns a value that depends on the input string: - Float if input can be converted to Float - Integer if input can be converted to integer - Zero if the input string is empty and empty...
Returns a list of numericised values from strings
def numericise_all(input, empty2zero=False, default_blank="", allow_underscores_in_numeric_literals=False): """Returns a list of numericised values from strings""" return [numericise(s, empty2zero, default_blank, allow_underscores_in_numeric_literals) for s in input]
Translates a row and column cell address to A1 notation.
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.
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 a spreadsheet.
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...
Opens all available spreadsheets.
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...
Creates a new spreadsheet.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 axis determines...
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 ).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 provides a decent e...
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.
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 uses this splitting recur...
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 uses this splitting recur...
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 ( optional default 30 ) The maximum size of any lea...
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.
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 of nearest neig...
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.
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.
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.
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 each such point and ...
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.
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.
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.
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.
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.
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 negative sampli...
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.
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...
Given indices and weights and an original embeddings initialize the positions of new points relative to the indices and weights ( of their neighbors in the source data ).
def init_transform(indices, weights, embedding): """Given indices and weights and an original embeddings initialize the positions of new points relative to the indices and weights (of their neighbors in the source data). Parameters ---------- indices: array of shape (n_new_samples, n_neighbors)...
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.
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 ...