sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def summary(self, campaign_id=None): """ Returns the campaign summary """ resource_cls = CampaignSummary single_resource = False if not campaign_id: resource_cls = CampaignSummaries single_resource = True return super(API, self).get( resource...
Returns the campaign summary
entailment
def results(self, campaign_id): """ Returns just the results for a given campaign """ return super(API, self).get( resource_id=campaign_id, resource_action='results', resource_cls=CampaignResults)
Returns just the results for a given campaign
entailment
def set_path(self, file_path): """ Set the path of the database. Create the file if it does not exist. """ if not file_path: self.read_data = self.memory_read self.write_data = self.memory_write elif not is_valid(file_path): self.write_...
Set the path of the database. Create the file if it does not exist.
entailment
def delete(self, key): """ Removes the specified key from the database. """ obj = self._get_content() obj.pop(key, None) self.write_data(self.path, obj)
Removes the specified key from the database.
entailment
def data(self, **kwargs): """ If a key is passed in, a corresponding value will be returned. If a key-value pair is passed in then the corresponding key in the database will be set to the specified value. A dictionary can be passed in as well. If a key does not exist and ...
If a key is passed in, a corresponding value will be returned. If a key-value pair is passed in then the corresponding key in the database will be set to the specified value. A dictionary can be passed in as well. If a key does not exist and a value is provided then an entry will...
entailment
def filter(self, filter_arguments): """ Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters. """ results = self._get_content() # Filter based on a dictionary of search parameters if isinstance(filter_arguments, dict): ...
Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters.
entailment
def drop(self): """ Remove the database by deleting the JSON file. """ import os if self.path: if os.path.exists(self.path): os.remove(self.path) else: # Clear the in-memory data if there is no file path self._data = {}
Remove the database by deleting the JSON file.
entailment
def read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """ if not is_valid(file_path): write_data(file_path, {}) db = open_file_for_reading(file_path) content = db.read() obj = decode(content) db.close() return obj
Reads a file and returns a json encoded representation of the file.
entailment
def write_data(path, obj): """ Writes to a file and returns the updated file content. """ with open_file_for_writing(path) as db: db.write(encode(obj)) return obj
Writes to a file and returns the updated file content.
entailment
def is_valid(file_path): """ Check to see if a file exists or is empty. """ from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(fil...
Check to see if a file exists or is empty.
entailment
def _refine(node_coords, cells_nodes, edge_nodes, cells_edges): """Canonically refine a mesh by inserting nodes at all edge midpoints and make four triangular elements where there was one. This is a very crude refinement; don't use for actual applications. """ num_nodes = len(node_coords) num_ne...
Canonically refine a mesh by inserting nodes at all edge midpoints and make four triangular elements where there was one. This is a very crude refinement; don't use for actual applications.
entailment
def create_edges(cells_nodes): """Setup edge-node and edge-cell relations. Adapted from voropy. """ # Create the idx_hierarchy (nodes->edges->cells), i.e., the value of # `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge # 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3...
Setup edge-node and edge-cell relations. Adapted from voropy.
entailment
def plot2d(points, cells, mesh_color="k", show_axes=False): """Plot a 2D mesh using matplotlib. """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection fig = plt.figure() ax = fig.gca() plt.axis("equal") if not show_axes: ax.set_axis_off() xmin...
Plot a 2D mesh using matplotlib.
entailment
def put(self, job, result): "Perform a job by a member in the pool and return the result." self.job.put(job) r = result.get() return r
Perform a job by a member in the pool and return the result.
entailment
def contract(self, jobs, result): """ Perform a contract on a number of jobs and block until a result is retrieved for each job. """ for j in jobs: WorkerPool.put(self, j) r = [] for i in xrange(len(jobs)): r.append(result.get()) ...
Perform a contract on a number of jobs and block until a result is retrieved for each job.
entailment
def cube( xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, zmin=0.0, zmax=1.0, nx=11, ny=11, nz=11 ): """Canonical tetrahedrization of the cube. Input: Edge lenghts of the cube Number of nodes along the edges. """ # Generate suitable ranges for parametrization x_range = numpy.linspace(xmin, xmax,...
Canonical tetrahedrization of the cube. Input: Edge lenghts of the cube Number of nodes along the edges.
entailment
def grow(self): "Add another worker to the pool." t = self.worker_factory(self) t.start() self._size += 1
Add another worker to the pool.
entailment
def shrink(self): "Get rid of one worker from the pool. Raises IndexError if empty." if self._size <= 0: raise IndexError("pool is already empty") self._size -= 1 self.put(SuicideJob())
Get rid of one worker from the pool. Raises IndexError if empty.
entailment
def map(self, fn, *seq): "Perform a map operation distributed among the workers. Will " "block until done." results = Queue() args = zip(*seq) for seq in args: j = SimpleJob(results, fn, seq) self.put(j) # Aggregate results r = [] ...
Perform a map operation distributed among the workers. Will
entailment
def moebius( num_twists=1, # How many twists are there in the 'paper'? nl=60, # Number of nodes along the length of the strip nw=11, # Number of nodes along the width of the strip (>= 2) mode="classical", ): """Creates a simplistic triangular mesh on a slightly Möbius strip. The Möbius strip ...
Creates a simplistic triangular mesh on a slightly Möbius strip. The Möbius strip here deviates slightly from the ordinary geometry in that it is constructed in such a way that the two halves can be exchanged as to allow better comparison with the pseudo-Möbius geometry. The mode is either `'classical'...
entailment
def run(self): "Get jobs from the queue and perform them as they arrive." while 1: # Sleep until there is a job to perform. job = self.jobs.get() # Yawn. Time to get some work done. try: job.run() self.jobs.task_done() ...
Get jobs from the queue and perform them as they arrive.
entailment
def display(contents, domain=DEFAULT_DOMAIN, force_gist=False): """ Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the cont...
Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the content is small, this step is not needed as the data can be included in the...
entailment
def embed(contents='', width='100%', height=512, *args, **kwargs): """ Embed geojson.io in an iframe in Jupyter/IPython notebook. Parameters ---------- contents - see make_url() width - string, default '100%' - width of the iframe height - string / int, default 512 - height of the iframe ...
Embed geojson.io in an iframe in Jupyter/IPython notebook. Parameters ---------- contents - see make_url() width - string, default '100%' - width of the iframe height - string / int, default 512 - height of the iframe kwargs - additional arguments are passed to `make_url()`
entailment
def make_url(contents, domain=DEFAULT_DOMAIN, force_gist=False, size_for_gist=MAX_URL_LEN): """ Returns the URL to open given the domain and contents. If the file contents are large, an anonymous gist will be created. Parameters ---------- contents * string - assumed to be...
Returns the URL to open given the domain and contents. If the file contents are large, an anonymous gist will be created. Parameters ---------- contents * string - assumed to be GeoJSON * an object that implements __geo_interface__ A FeatureCollection will be constructed wi...
entailment
def make_geojson(contents): """ Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string """ if isinstance(contents, six.string_types): return contents if hasattr(contents, '__g...
Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string
entailment
def data_url(contents, domain=DEFAULT_DOMAIN): """ Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io """ url = (domain + '#data=data:application/json,' + urllib.parse.qu...
Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io
entailment
def _make_gist(contents, description='', filename='data.geojson'): """ Create and return an anonymous gist with a single file and specified contents """ ghapi = github3.GitHub() files = {filename: {'content': contents}} gist = ghapi.create_gist(description, files) return gist
Create and return an anonymous gist with a single file and specified contents
entailment
def clenshaw(a, alpha, beta, t): """Clenshaw's algorithm for evaluating S(t) = \\sum a_k P_k(alpha, beta)(t) where P_k(alpha, beta) is the kth orthogonal polynomial defined by the recurrence coefficients alpha, beta. See <https://en.wikipedia.org/wiki/Clenshaw_algorithm> for details. """ ...
Clenshaw's algorithm for evaluating S(t) = \\sum a_k P_k(alpha, beta)(t) where P_k(alpha, beta) is the kth orthogonal polynomial defined by the recurrence coefficients alpha, beta. See <https://en.wikipedia.org/wiki/Clenshaw_algorithm> for details.
entailment
def tree(X, n, alpha=0, symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. Set alpha=0 (default) to get classical Laguerre. """ args = recurrence_coefficients(n, alpha=alpha, symbolic=symbolic) return line_tree(X, *args)
Recurrence coefficients for generalized Laguerre polynomials. Set alpha=0 (default) to get classical Laguerre.
entailment
def recurrence_coefficients(n, alpha, standardization="normal", symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k """ S = sympy.S if symbolic else lambda x: x sqrt = sympy.sqrt if symbolic else numpy.sqrt ...
Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k
entailment
def jacobi(n, alpha, beta, standardization, symbolic=False): """Generate the recurrence coefficients a_k, b_k, c_k in P_{k+1}(x) = (a_k x - b_k)*P_{k}(x) - c_k P_{k-1}(x) for the Jacobi polynomials which are orthogonal on [-1, 1] with respect to the weight w(x)=[(1-x)^alpha]*[(1+x)^beta]; see <htt...
Generate the recurrence coefficients a_k, b_k, c_k in P_{k+1}(x) = (a_k x - b_k)*P_{k}(x) - c_k P_{k-1}(x) for the Jacobi polynomials which are orthogonal on [-1, 1] with respect to the weight w(x)=[(1-x)^alpha]*[(1+x)^beta]; see <https://en.wikipedia.org/wiki/Jacobi_polynomials#Recurrence_relations>.
entailment
def plot(f, lcar=1.0e-1): """Plot function over a disk. """ import matplotlib import matplotlib.pyplot as plt import pygmsh geom = pygmsh.built_in.Geometry() geom.add_circle([0.0, 0.0, 0.0], 1.0, lcar, num_sections=4, compound=True) points, cells, _, _, _ = pygmsh.generate_mesh(geom, ve...
Plot function over a disk.
entailment
def tree(X, n, symbolic=False): """Evaluates the entire tree of orthogonal polynomials for the n-cube The computation is organized such that tree returns a list of arrays, L={0, ..., dim}, where each level corresponds to the polynomial degree L. Further, each level is organized like a discrete (dim-1)-...
Evaluates the entire tree of orthogonal polynomials for the n-cube The computation is organized such that tree returns a list of arrays, L={0, ..., dim}, where each level corresponds to the polynomial degree L. Further, each level is organized like a discrete (dim-1)-dimensional simplex. Let's demonstr...
entailment
def line_evaluate(t, p0, a, b, c): """Evaluate the orthogonal polynomial defined by its recurrence coefficients a, b, and c at the point(s) t. """ vals1 = numpy.zeros_like(t, dtype=int) # The order is important here; see # <https://github.com/sympy/sympy/issues/13637>. vals2 = numpy.ones_lik...
Evaluate the orthogonal polynomial defined by its recurrence coefficients a, b, and c at the point(s) t.
entailment
def plot(corners, f, n=100): """Plot function over a triangle. """ import matplotlib.tri import matplotlib.pyplot as plt # discretization points def partition(boxes, balls): # <https://stackoverflow.com/a/36748940/353337> def rec(boxes, balls, parent=tuple()): if box...
Plot function over a triangle.
entailment
def _iget(key, lookup_dict): """ Case-insensitive search for `key` within keys of `lookup_dict`. """ for k, v in lookup_dict.items(): if k.lower() == key.lower(): return v return None
Case-insensitive search for `key` within keys of `lookup_dict`.
entailment
def getlang_by_name(name): """ Try to lookup a Language object by name, e.g. 'English', in internal language list. Returns None if lookup by language name fails in resources/languagelookup.json. """ direct_match = _iget(name, _LANGUAGE_NAME_LOOKUP) if direct_match: return direct_match ...
Try to lookup a Language object by name, e.g. 'English', in internal language list. Returns None if lookup by language name fails in resources/languagelookup.json.
entailment
def getlang_by_native_name(native_name): """ Try to lookup a Language object by native_name, e.g. 'English', in internal language list. Returns None if lookup by language name fails in resources/languagelookup.json. """ direct_match = _iget(native_name, _LANGUAGE_NATIVE_NAME_LOOKUP) if direct_ma...
Try to lookup a Language object by native_name, e.g. 'English', in internal language list. Returns None if lookup by language name fails in resources/languagelookup.json.
entailment
def getlang_by_alpha2(code): """ Lookup a Language object for language code `code` based on these strategies: - Special case rules for Hebrew and Chinese Hans/Hant scripts - Using `alpha_2` lookup in `pycountry.languages` followed by lookup for a language with the same `name` in the internal...
Lookup a Language object for language code `code` based on these strategies: - Special case rules for Hebrew and Chinese Hans/Hant scripts - Using `alpha_2` lookup in `pycountry.languages` followed by lookup for a language with the same `name` in the internal representaion Returns `None` if no m...
entailment
def write(filename, f): """Write a function `f` defined in terms of spherical coordinates to a file. """ import meshio import meshzoo points, cells = meshzoo.iso_sphere(5) # get spherical coordinates from points polar = numpy.arccos(points[:, 2]) azimuthal = numpy.arctan2(points[:, 1], ...
Write a function `f` defined in terms of spherical coordinates to a file.
entailment
def tree_sph(polar, azimuthal, n, standardization, symbolic=False): """Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`. """ cos = numpy.vectorize(sympy.cos) if symbolic else numpy.cos # Conventions from # <https://en.wikipedia.org/wiki/Spherical_harmonics#O...
Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`.
entailment
def tree_alp( x, n, standardization, phi=None, with_condon_shortley_phase=True, symbolic=False ): """Evaluates the entire tree of associated Legendre polynomials up to depth n. There are many recurrence relations that can be used to construct the associated Legendre polynomials. However, only few ar...
Evaluates the entire tree of associated Legendre polynomials up to depth n. There are many recurrence relations that can be used to construct the associated Legendre polynomials. However, only few are numerically stable. Many implementations (including this one) use the classical Legendre recurrence...
entailment
def tree(X, n, symbolic=False): """Evaluates the entire tree of orthogonal polynomials on the unit disk. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ... ....
Evaluates the entire tree of orthogonal polynomials on the unit disk. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ... ... ...
entailment
def tree(bary, n, standardization, symbolic=False): """Evaluates the entire tree of orthogonal triangle polynomials. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ...
Evaluates the entire tree of orthogonal triangle polynomials. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ... ... ... For reference, see Abedal...
entailment
def check_if_this_file_exist(filename): """Check if this file exist and if it's a directory This function will check if the given filename actually exists and if it's not a Directory Arguments: filename {string} -- filename Return: True : if it's not a directory and if this file ...
Check if this file exist and if it's a directory This function will check if the given filename actually exists and if it's not a Directory Arguments: filename {string} -- filename Return: True : if it's not a directory and if this file exist False : If it's not a file and if...
entailment
def command_line(cmd): """Handle the command line call keyword arguments: cmd = a list return 0 if error or a string for the command line output """ try: s = subprocess.Popen(cmd, stdout=subprocess.PIPE) s = s.stdout.read() return s.strip() except subproce...
Handle the command line call keyword arguments: cmd = a list return 0 if error or a string for the command line output
entailment
def information(filename): """Returns the file exif""" check_if_this_file_exist(filename) filename = os.path.abspath(filename) result = get_json(filename) result = result[0] return result
Returns the file exif
entailment
def get_json(filename): """ Return a json value of the exif Get a filename and return a JSON object Arguments: filename {string} -- your filename Returns: [JSON] -- Return a JSON object """ check_if_this_file_exist(filename) #Process this function filename = os.path.a...
Return a json value of the exif Get a filename and return a JSON object Arguments: filename {string} -- your filename Returns: [JSON] -- Return a JSON object
entailment
def get_csv(filename): """ Return a csv representation of the exif get a filename and returns a unicode string with a CSV format Arguments: filename {string} -- your filename Returns: [unicode] -- unicode string """ check_if_this_file_exist(filename) #Process this functio...
Return a csv representation of the exif get a filename and returns a unicode string with a CSV format Arguments: filename {string} -- your filename Returns: [unicode] -- unicode string
entailment
def print_a_header(message="-"): """Header This function will output a message in a header Keyword Arguments: message {str} -- [the message string] (default: {"-"}) """ print("-".center(60,'-')) print(message.center(60,'-')) print("-".center(60,'-')) print()
Header This function will output a message in a header Keyword Arguments: message {str} -- [the message string] (default: {"-"})
entailment
def check_if_exiftool_is_already_installed(): """Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not """ result = 1; command = ["exiftool", "-ver"] with open(os.devnull, "w") as fnull: res...
Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not
entailment
def render(self, context=None, clean=False): """ Render email with provided context Arguments --------- context : dict |context| If not specified then the :attr:`~mail_templated.EmailMessage.context` property is used. Keyword Argument...
Render email with provided context Arguments --------- context : dict |context| If not specified then the :attr:`~mail_templated.EmailMessage.context` property is used. Keyword Arguments ----------------- clean : bool If `...
entailment
def send(self, *args, **kwargs): """ Send email message, render if it is not rendered yet. Note ---- Any extra arguments are passed to :class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`. Keyword Arguments ----------------- cle...
Send email message, render if it is not rendered yet. Note ---- Any extra arguments are passed to :class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`. Keyword Arguments ----------------- clean : bool If ``True``, remove any templat...
entailment
def send_mail(template_name, context, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, **kwargs): """ Easy wrapper for sending a single email message to a recipient list using django template system. It works almost the sa...
Easy wrapper for sending a single email message to a recipient list using django template system. It works almost the same way as the standard :func:`send_mail()<django.core.mail.send_mail>` function. .. |main_difference| replace:: The main difference is that two first arguments ``subject`` an...
entailment
def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b...
Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. To clarify, ``b`` is the di...
entailment
def silhouette_samples(X, labels, metric='euclidean', **kwds): """Compute the Silhouette Coefficient for each sample. The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to b...
Compute the Silhouette Coefficient for each sample. The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to be dense, where samples in the same cluster are similar to each oth...
entailment
def calinski_harabaz_score(X, labels): """Compute the Calinski and Harabaz score. The score is defined as ratio between the within-cluster dispersion and the between-cluster dispersion. Read more in the :ref:`User Guide <calinski_harabaz_index>`. Parameters ---------- X : array-like, shap...
Compute the Calinski and Harabaz score. The score is defined as ratio between the within-cluster dispersion and the between-cluster dispersion. Read more in the :ref:`User Guide <calinski_harabaz_index>`. Parameters ---------- X : array-like, shape (``n_samples``, ``n_features``) List...
entailment
def handle_zeros_in_scale(scale, copy=True): ''' Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features. Adapted from sklearn.preprocessing.data''' # if we are fitting on 1D arrays, scale might be a scalar if np.isscalar(scale): ...
Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features. Adapted from sklearn.preprocessing.data
entailment
def _joint_probabilities(distances, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances. Parameters ---------- distances : array, shape (n_samples * (n_samples-1) / 2,) Distances of samples are stored as condensed matrices, i.e. we omit the diagonal and dupl...
Compute joint probabilities p_ij from distances. Parameters ---------- distances : array, shape (n_samples * (n_samples-1) / 2,) Distances of samples are stored as condensed matrices, i.e. we omit the diagonal and duplicate entries and store everything in a one-dimensional array. ...
entailment
def _joint_probabilities_nn(distances, neighbors, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances using just nearest neighbors. This method is approximately equal to _joint_probabilities. The latter is O(N), but limiting the joint probability to nearest neighbors improv...
Compute joint probabilities p_ij from distances using just nearest neighbors. This method is approximately equal to _joint_probabilities. The latter is O(N), but limiting the joint probability to nearest neighbors improves this substantially to O(uN). Parameters ---------- distances : arra...
entailment
def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components, skip_num_points=0): """t-SNE objective function: gradient of the KL divergence of p_ijs and q_ijs and the absolute error. Parameters ---------- params : array, shape (n_params,) Unraveled embedding...
t-SNE objective function: gradient of the KL divergence of p_ijs and q_ijs and the absolute error. Parameters ---------- params : array, shape (n_params,) Unraveled embedding. P : array, shape (n_samples * (n_samples-1) / 2,) Condensed joint probability matrix. degrees_of_free...
entailment
def _kl_divergence_bh(params, P, degrees_of_freedom, n_samples, n_components, angle=0.5, skip_num_points=0, verbose=False): """t-SNE objective function: KL divergence of p_ijs and q_ijs. Uses Barnes-Hut tree methods to calculate the gradient that runs in O(NlogN) instead of O(N^2) ...
t-SNE objective function: KL divergence of p_ijs and q_ijs. Uses Barnes-Hut tree methods to calculate the gradient that runs in O(NlogN) instead of O(N^2) Parameters ---------- params : array, shape (n_params,) Unraveled embedding. P : csr sparse matrix, shape (n_samples, n_sample) ...
entailment
def _gradient_descent(objective, p0, it, n_iter, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7, verbose=0, args=None, kwargs=None): """Batch gradient descent with momentum and indivi...
Batch gradient descent with momentum and individual gains. Parameters ---------- objective : function or callable Should return a tuple of cost and gradient for a given parameter vector. When expensive to compute, the cost can optionally be None and can be computed every n_iter_chec...
entailment
def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): """Expresses to what extent the local structure is retained. The trustworthiness is within [0, 1]. It is defined as .. math:: T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} \sum_{j \in U^{(k)}_i} (r(i, j) - k) ...
Expresses to what extent the local structure is retained. The trustworthiness is within [0, 1]. It is defined as .. math:: T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} \sum_{j \in U^{(k)}_i} (r(i, j) - k) where :math:`r(i, j)` is the rank of the embedded datapoint j accordi...
entailment
def _fit(self, X, skip_num_points=0): """Fit the model using X as training data. Note that sparse arrays can only be handled by method='exact'. It is recommended that you convert your sparse array to dense (e.g. `X.toarray()`) if it fits in memory, or otherwise using a dimension...
Fit the model using X as training data. Note that sparse arrays can only be handled by method='exact'. It is recommended that you convert your sparse array to dense (e.g. `X.toarray()`) if it fits in memory, or otherwise using a dimensionality reduction technique (e.g. TruncatedSVD). ...
entailment
def _tsne(self, P, degrees_of_freedom, n_samples, random_state, X_embedded, neighbors=None, skip_num_points=0): """Runs t-SNE.""" # t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P # and the Student's t-distributions Q. The optimization algorithm that # we ...
Runs t-SNE.
entailment
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...
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. ...
entailment
def correct(datasets_full, genes_list, return_dimred=False, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, return_dense=False, hvg=None, union=False, geosketch=False, geosketch_max=20000): """Int...
Integrate and batch correct a list of data sets. Parameters ---------- datasets_full : `list` of `scipy.sparse.csr_matrix` or of `numpy.ndarray` Data sets to integrate and correct. genes_list: `list` of `list` of `string` List of genes for each data set. return_dimred: `bool`, optio...
entailment
def integrate(datasets_full, genes_list, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, geosketch=False, geosketch_max=20000, n_iter=1, union=False, hvg=None): """Integrate a list of data sets. Pa...
Integrate a list of data sets. Parameters ---------- datasets_full : `list` of `scipy.sparse.csr_matrix` or of `numpy.ndarray` Data sets to integrate and correct. genes_list: `list` of `list` of `string` List of genes for each data set. batch_size: `int`, optional (default: `5000`) ...
entailment
def correct_scanpy(adatas, **kwargs): """Batch correct a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate and/or correct. kwargs : `dict` See documentation for the `correct()` method for a full list of paramet...
Batch correct a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate and/or correct. kwargs : `dict` See documentation for the `correct()` method for a full list of parameters to use for batch correction. Returns...
entailment
def integrate_scanpy(adatas, **kwargs): """Integrate a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate. kwargs : `dict` See documentation for the `integrate()` method for a full list of parameters to use for ...
Integrate a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate. kwargs : `dict` See documentation for the `integrate()` method for a full list of parameters to use for batch correction. Returns ------- ...
entailment
def augknt(knots, order): """Augment a knot vector. Parameters: knots: Python list or rank-1 array, the original knot vector (without endpoint repeats) order: int, >= 0, order of spline Returns: list_of_knots: rank-1 array that has (`order` + 1) copies of ``knots[0]``, then ``k...
Augment a knot vector. Parameters: knots: Python list or rank-1 array, the original knot vector (without endpoint repeats) order: int, >= 0, order of spline Returns: list_of_knots: rank-1 array that has (`order` + 1) copies of ``knots[0]``, then ``knots[1:-1]``, and finally (`order...
entailment
def aveknt(t, k): """Compute the running average of `k` successive elements of `t`. Return the averaged array. Parameters: t: Python list or rank-1 array k: int, >= 2, how many successive elements to average Returns: rank-1 array, averaged data. If k > len(t), returns a zero-length arr...
Compute the running average of `k` successive elements of `t`. Return the averaged array. Parameters: t: Python list or rank-1 array k: int, >= 2, how many successive elements to average Returns: rank-1 array, averaged data. If k > len(t), returns a zero-length array. Caveat: This is ...
entailment
def aptknt(tau, order): """Create an acceptable knot vector. Minimal emulation of MATLAB's ``aptknt``. The returned knot vector can be used to generate splines of desired `order` that are suitable for interpolation to the collocation sites `tau`. Note that this is only possible when ``len(tau)`` >= `order` + 1. ...
Create an acceptable knot vector. Minimal emulation of MATLAB's ``aptknt``. The returned knot vector can be used to generate splines of desired `order` that are suitable for interpolation to the collocation sites `tau`. Note that this is only possible when ``len(tau)`` >= `order` + 1. When this condition does not h...
entailment
def knt2mlt(t): """Count multiplicities of elements in a sorted list or rank-1 array. Minimal emulation of MATLAB's ``knt2mlt``. Parameters: t: Python list or rank-1 array. Must be sorted! Returns: out rank-1 array such that out[k] = #{ t[i] == t[k] for i < k } Example: If ``...
Count multiplicities of elements in a sorted list or rank-1 array. Minimal emulation of MATLAB's ``knt2mlt``. Parameters: t: Python list or rank-1 array. Must be sorted! Returns: out rank-1 array such that out[k] = #{ t[i] == t[k] for i < k } Example: If ``t = [1, 1, 2, 3, 3, 3]`...
entailment
def spcol(knots, order, tau): """Return collocation matrix. Minimal emulation of MATLAB's ``spcol``. Parameters: knots: rank-1 array, knot vector (with appropriately repeated endpoints; see `augknt`, `aptknt`) order: int, >= 0, order of spline tau: rank-1 array, collocation sit...
Return collocation matrix. Minimal emulation of MATLAB's ``spcol``. Parameters: knots: rank-1 array, knot vector (with appropriately repeated endpoints; see `augknt`, `aptknt`) order: int, >= 0, order of spline tau: rank-1 array, collocation sites Returns: rank-2 array A such ...
entailment
def __basis0(self, xi): """Order zero basis (for internal use).""" return np.where(np.all([self.knot_vector[:-1] <= xi, xi < self.knot_vector[1:]],axis=0), 1.0, 0.0)
Order zero basis (for internal use).
entailment
def __basis(self, xi, p, compute_derivatives=False): """Recursive Cox - de Boor function (for internal use). Compute basis functions and optionally their first derivatives. """ if p == 0: return self.__basis0(xi) else: basis_p_minus_1 = self.__basis(xi, ...
Recursive Cox - de Boor function (for internal use). Compute basis functions and optionally their first derivatives.
entailment
def d(self, xi): """Convenience function to compute first derivative of basis functions. 'Memoized' for speed.""" return self.__basis(xi, self.p, compute_derivatives=True)
Convenience function to compute first derivative of basis functions. 'Memoized' for speed.
entailment
def plot(self): """Plot basis functions over full range of knots. Convenience function. Requires matplotlib. """ try: import matplotlib.pyplot as plt except ImportError: from sys import stderr print("ERROR: matplotlib.pyplot not found, matplo...
Plot basis functions over full range of knots. Convenience function. Requires matplotlib.
entailment
def __diff_internal(self): """Differentiate a B-spline once, and return the resulting coefficients and Bspline objects. This preserves the Bspline object nature of the data, enabling recursive implementation of higher-order differentiation (see `diff`). The value of the first derivative of `B` at a point `x` ...
Differentiate a B-spline once, and return the resulting coefficients and Bspline objects. This preserves the Bspline object nature of the data, enabling recursive implementation of higher-order differentiation (see `diff`). The value of the first derivative of `B` at a point `x` can be obtained as:: def diff1(B,...
entailment
def diff(self, order=1): """Differentiate a B-spline `order` number of times. Parameters: order: int, >= 0 Returns: **lambda** `x`: ... that evaluates the `order`-th derivative of `B` at the point `x`. The returned function internally uses __call__, which is 'memoized' for ...
Differentiate a B-spline `order` number of times. Parameters: order: int, >= 0 Returns: **lambda** `x`: ... that evaluates the `order`-th derivative of `B` at the point `x`. The returned function internally uses __call__, which is 'memoized' for speed.
entailment
def collmat(self, tau, deriv_order=0): """Compute collocation matrix. Parameters: tau: Python list or rank-1 array, collocation sites deriv_order: int, >=0, order of derivative for which to compute the collocation matrix. The default is 0, which means the function value itself. ...
Compute collocation matrix. Parameters: tau: Python list or rank-1 array, collocation sites deriv_order: int, >=0, order of derivative for which to compute the collocation matrix. The default is 0, which means the function value itself. Returns: A: if len(tau) > 1, rank-2 a...
entailment
def build_interfaces_by_method(interfaces): """ Create new dictionary from INTERFACES hashed by method then the endpoints name. For use when using the disqusapi by the method interface instead of the endpoint interface. For instance: 'blacklists': { 'add': { 'formats': ['jso...
Create new dictionary from INTERFACES hashed by method then the endpoints name. For use when using the disqusapi by the method interface instead of the endpoint interface. For instance: 'blacklists': { 'add': { 'formats': ['json', 'jsonp'], 'method': 'POST', ...
entailment
def get_normalized_request_string(method, url, nonce, params, ext='', body_hash=None): """ Returns a normalized request string as described iN OAuth2 MAC spec. http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.3.1 """ urlparts = urlparse.urlparse(url) if urlparts.query: ...
Returns a normalized request string as described iN OAuth2 MAC spec. http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.3.1
entailment
def get_body_hash(params): """ Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec. http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2 """ norm_params = get_normalized_params(params) return binascii.b2a_base64(hashlib.sha1(norm_params).digest())[:-1]
Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec. http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2
entailment
def get_mac_signature(api_secret, norm_request_string): """ Returns HMAC-SHA1 (api secret, normalized request string) """ hashed = hmac.new(str(api_secret), norm_request_string, hashlib.sha1) return binascii.b2a_base64(hashed.digest())[:-1]
Returns HMAC-SHA1 (api secret, normalized request string)
entailment
def open_file(self, access_mode="r"): """ input: filename and path. output: file contents. """ try: with open(self, access_mode, encoding='utf-8') as file: return file.read() except IOError: print(self + " File not found."...
input: filename and path. output: file contents.
entailment
def _forward_backward(self, itraj): """ Estimation step: Runs the forward-back algorithm on trajectory with index itraj Parameters ---------- itraj : int index of the observation trajectory to process Results ------- logprob : float ...
Estimation step: Runs the forward-back algorithm on trajectory with index itraj Parameters ---------- itraj : int index of the observation trajectory to process Results ------- logprob : float The probability to observe the observation sequence g...
entailment
def _update_model(self, gammas, count_matrices, maxiter=10000000): """ Maximization step: Updates the HMM model given the hidden state assignment and count matrices Parameters ---------- gamma : [ ndarray(T,N, dtype=float) ] list of state probabilities for each traje...
Maximization step: Updates the HMM model given the hidden state assignment and count matrices Parameters ---------- gamma : [ ndarray(T,N, dtype=float) ] list of state probabilities for each trajectory count_matrix : [ ndarray(N,N, dtype=float) ] list of the Baum...
entailment
def compute_viterbi_paths(self): """ Computes the viterbi paths using the current HMM model """ # get parameters K = len(self._observations) A = self._hmm.transition_matrix pi = self._hmm.initial_distribution # compute viterbi path for each trajectory ...
Computes the viterbi paths using the current HMM model
entailment
def fit(self): """ Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm Returns ------- model : HMM The maximum likelihood HMM model. """ logger().info("=================================================================") lo...
Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm Returns ------- model : HMM The maximum likelihood HMM model.
entailment
def sample_gaussian(mean, covar, covariance_type='diag', n_samples=1, random_state=None): """Generate random samples from a Gaussian distribution. Parameters ---------- mean : array_like, shape (n_features,) Mean of the distribution. covar : array_like, optional ...
Generate random samples from a Gaussian distribution. Parameters ---------- mean : array_like, shape (n_features,) Mean of the distribution. covar : array_like, optional Covariance of the distribution. The shape depends on `covariance_type`: scalar if 'spherical', ...
entailment
def _covar_mstep_diag(gmm, X, responsibilities, weighted_X_sum, norm, min_covar): """Performing the covariance M step for diagonal cases""" avg_X2 = np.dot(responsibilities.T, X * X) * norm avg_means2 = gmm.means_ ** 2 avg_X_means = gmm.means_ * weighted_X_sum * norm return avg...
Performing the covariance M step for diagonal cases
entailment
def _covar_mstep_spherical(*args): """Performing the covariance M step for spherical cases""" cv = _covar_mstep_diag(*args) return np.tile(cv.mean(axis=1)[:, np.newaxis], (1, cv.shape[1]))
Performing the covariance M step for spherical cases
entailment
def _covar_mstep_full(gmm, X, responsibilities, weighted_X_sum, norm, min_covar): """Performing the covariance M step for full cases""" # Eq. 12 from K. Murphy, "Fitting a Conditional Linear Gaussian # Distribution" n_features = X.shape[1] cv = np.empty((gmm.n_components, n_fea...
Performing the covariance M step for full cases
entailment
def _get_covars(self): """Covariance parameters for each mixture component. The shape depends on `cvtype`:: (`n_states`, 'n_features') if 'spherical', (`n_features`, `n_features`) if 'tied', (`n_states`, `n_features`) if 'di...
Covariance parameters for each mixture component. The shape depends on `cvtype`:: (`n_states`, 'n_features') if 'spherical', (`n_features`, `n_features`) if 'tied', (`n_states`, `n_features`) if 'diag', (`n_states`, `n_f...
entailment
def _set_covars(self, covars): """Provide values for covariance""" covars = np.asarray(covars) _validate_covars(covars, self.covariance_type, self.n_components) self.covars_ = covars
Provide values for covariance
entailment
def score_samples(self, X): """Return the per-sample likelihood of the data under the model. Compute the log probability of X under the model and return the posterior distribution (responsibilities) of each mixture component for each element of X. Parameters ---------- ...
Return the per-sample likelihood of the data under the model. Compute the log probability of X under the model and return the posterior distribution (responsibilities) of each mixture component for each element of X. Parameters ---------- X: array_like, shape (n_samples...
entailment
def score(self, X, y=None): """Compute the log probability under the model. Parameters ---------- X : array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ----...
Compute the log probability under the model. Parameters ---------- X : array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- logprob : array_like, shape...
entailment