signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def to_affine(self):
X, Y, Z = self.x, self.y, self.inverse(self.z)<EOL>return ((X * Z ** <NUM_LIT:2>) % P, (Y * Z ** <NUM_LIT:3>) % P)<EOL>
Converts this point to an affine representation. Returns: AffinePoint: The affine reprsentation.
f11841:c2:m6
def __mul__(self, other):
r0 = AffinePoint(<NUM_LIT:0>, <NUM_LIT:0>, True)<EOL>r = [r0, self]<EOL>for i in reversed(range(other.bit_length())):<EOL><INDENT>di = (other >> i) & <NUM_LIT><EOL>r[(di + <NUM_LIT:1>) % <NUM_LIT:2>] = r[<NUM_LIT:0>] + r[<NUM_LIT:1>]<EOL>r[di] = r[di].double()<EOL><DEDENT>return r[<NUM_LIT:0>]<EOL>
Implements the scalar multiplication via the Montgomery ladder tech- nique.
f11841:c3:m4
def double(self):
X1, Y1, a, P = self.X, self.Y, self.a, self.P<EOL>if self.infinity:<EOL><INDENT>return self<EOL><DEDENT>S = ((<NUM_LIT:3> * X1 ** <NUM_LIT:2> + a) * self.inverse(<NUM_LIT:2> * Y1)) % P<EOL>X2 = (S ** <NUM_LIT:2> - (<NUM_LIT:2> * X1)) % P<EOL>Y2 = (S * (X1 - X2) - Y1) % P<EOL>return AffinePoint(X2, Y2)<EOL>
Doubles this point. Returns: AffinePoint: The point corresponding to `2 * self`.
f11841:c3:m8
def slope(self, other):
X1, Y1, X2, Y2 = self.X, self.Y, other.X, other.Y<EOL>Y3 = Y1 - Y2<EOL>X3 = X1 - X2<EOL>return (Y3 * self.inverse(X3)) % self.P<EOL>
Determines the slope between this point and another point. Args: other (AffinePoint): The second point. Returns: int: Slope between self and other.
f11841:c3:m9
def to_jacobian(self):
if not self:<EOL><INDENT>return JacobianPoint(X=<NUM_LIT:0>, Y=<NUM_LIT:0>, Z=<NUM_LIT:0>)<EOL><DEDENT>return JacobianPoint(X=self.X, Y=self.Y, Z=<NUM_LIT:1>)<EOL>
Converts this point to a Jacobian representation. Returns: JacobianPoint: The Jacobian representation.
f11841:c3:m10
@classmethod<EOL><INDENT>def make_controller(cls, config, session, left_menu_items=None):<DEDENT>
m = config.model<EOL>Controller = config.defaultCrudRestController<EOL>class ModelController(Controller):<EOL><INDENT>model = m<EOL>table = config.table_type(session)<EOL>table_filler = config.table_filler_type(session)<EOL>new_form = config.new_form_type(session)<EOL>new_filler = config.new_filler_type(session)<EOL>edit_form = config.edit_form_type(session)<EOL>edit_filler = config.edit_filler_type(session)<EOL>allow_only = config.allow_only<EOL>if hasattr(config.layout, '<STR_LIT>'):<EOL><INDENT>resources = config.layout.crud_resources<EOL><DEDENT>def _before(self, *args, **kw):<EOL><INDENT>super(self.__class__, self)._before(*args, **kw)<EOL>tmpl_context.make_pager_args = make_pager_args<EOL>if request.response_type not in ('<STR_LIT:application/json>',):<EOL><INDENT>default_renderer = AdminController._get_default_renderer()<EOL>for action in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>for template in config.layout.crud_templates.get(action, []):<EOL><INDENT>if template.startswith(default_renderer):<EOL><INDENT>override_template(getattr(self, action), template)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return ModelController(session, left_menu_items)<EOL>
New CRUD controllers using the admin configuration can be created using this.
f11846:c0:m4
@classmethod<EOL><INDENT>def by_email_address(cls, email):<DEDENT>
return DBSession.query(cls).filter(cls.email_address==email).first()<EOL>
A class method that can be used to search users based on their email addresses since it is unique.
f11854:c2:m2
@classmethod<EOL><INDENT>def by_user_name(cls, username):<DEDENT>
return DBSession.query(cls).filter(cls.user_name==username).first()<EOL>
A class method that permits to search users based on their user_name attribute.
f11854:c2:m3
def _set_password(self, password):
<EOL>
encrypts password on the fly using the encryption algo defined in the configuration
f11854:c2:m4
def _get_password(self):
return self._password<EOL>
returns password
f11854:c2:m5
def _encrypt_password(self, algorithm, password):
hashed_password = password<EOL>if isinstance(password, unicode):<EOL><INDENT>password_8bit = password.encode('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>password_8bit = password<EOL><DEDENT>salt = sha1()<EOL>salt.update(os.urandom(<NUM_LIT>))<EOL>hash = sha1()<EOL>hash.update(password_8bit + salt.hexdigest())<EOL>hashed_password = salt.hexdigest() + hash.hexdigest()<EOL>if not isinstance(hashed_password, unicode):<EOL><INDENT>hashed_password = hashed_password.decode('<STR_LIT>')<EOL><DEDENT>return hashed_password<EOL>
Hash the given password with the specified algorithm. Valid values for algorithm are 'md5' and 'sha1'. All other algorithm values will be essentially a no-op.
f11854:c2:m6
def validate_password(self, password):
hashed_pass = sha1()<EOL>hashed_pass.update(password + self.password[:<NUM_LIT>])<EOL>return self.password[<NUM_LIT>:] == hashed_pass.hexdigest()<EOL>
Check the password against existing credentials. this method _MUST_ return a boolean. @param password: the password that was provided by the user to try and authenticate. This is the clear text version that we will need to match against the (possibly) encrypted one in the database. @type password: unicode object
f11854:c2:m7
def make_app(controller_klass=None, environ=None):
if environ is None:<EOL><INDENT>environ = {}<EOL><DEDENT>environ['<STR_LIT>'] = {}<EOL>environ['<STR_LIT>']['<STR_LIT:action>'] = "<STR_LIT>"<EOL>if controller_klass is None:<EOL><INDENT>controller_klass = TGController<EOL><DEDENT>app = ControllerWrap(controller_klass)<EOL>app = SetupCacheGlobal(app, environ, setup_cache=True, setup_session=True)<EOL>app = RegistryManager(app)<EOL>app = beaker.middleware.SessionMiddleware(app, {}, data_dir=session_dir)<EOL>app = CacheMiddleware(app, {}, data_dir=os.path.join(data_dir, '<STR_LIT>'))<EOL>app = httpexceptions.make_middleware(app)<EOL>return TestApp(app)<EOL>
Creates a `TestApp` instance.
f11856:m2
def cmdscale_fast(D, ndim):
tasklogger.log_debug("<STR_LIT>".format(<EOL>type(D).__name__, D.shape))<EOL>D = D**<NUM_LIT:2><EOL>D = D - D.mean(axis=<NUM_LIT:0>)[None, :]<EOL>D = D - D.mean(axis=<NUM_LIT:1>)[:, None]<EOL>pca = PCA(n_components=ndim, svd_solver='<STR_LIT>')<EOL>Y = pca.fit_transform(D)<EOL>return Y<EOL>
Fast CMDS using random SVD Parameters ---------- D : array-like, input data [n_samples, n_dimensions] ndim : int, number of dimensions in which to embed `D` Returns ------- Y : array-like, embedded data [n_sample, ndim]
f11864:m0
def embed_MDS(X, ndim=<NUM_LIT:2>, how='<STR_LIT>', distance_metric='<STR_LIT>',<EOL>n_jobs=<NUM_LIT:1>, seed=None, verbose=<NUM_LIT:0>):
if how not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(how))<EOL><DEDENT>X_dist = squareform(pdist(X, distance_metric))<EOL>Y = cmdscale_fast(X_dist, ndim)<EOL>if how in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>tasklogger.log_debug("<STR_LIT>"<EOL>"<STR_LIT>".format(type(X_dist),<EOL>X_dist.shape))<EOL>Y, _ = smacof(X_dist, n_components=ndim, metric=True, max_iter=<NUM_LIT>,<EOL>eps=<NUM_LIT>, random_state=seed, n_jobs=n_jobs,<EOL>n_init=<NUM_LIT:1>, init=Y, verbose=verbose)<EOL><DEDENT>if how == '<STR_LIT>':<EOL><INDENT>tasklogger.log_debug(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(type(X_dist),<EOL>X_dist.shape))<EOL>Y, _ = smacof(X_dist, n_components=ndim, metric=True, max_iter=<NUM_LIT>,<EOL>eps=<NUM_LIT>, random_state=seed, n_jobs=n_jobs,<EOL>n_init=<NUM_LIT:1>, init=Y, verbose=verbose)<EOL><DEDENT>return Y<EOL>
Performs classic, metric, and non-metric MDS Metric MDS is initialized using classic MDS, non-metric MDS is initialized using metric MDS. Parameters ---------- X: ndarray [n_samples, n_samples] 2 dimensional input data array with n_samples embed_MDS does not check for matrix squareness, but this is necessary for PHATE n_dim : int, optional, default: 2 number of dimensions in which the data will be embedded how : string, optional, default: 'classic' choose from ['classic', 'metric', 'nonmetric'] which MDS algorithm is used for dimensionality reduction distance_metric : string, optional, default: 'euclidean' choose from ['cosine', 'euclidean'] distance metric for MDS n_jobs : integer, optional, default: 1 The number of jobs to use for the computation. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used seed: integer or numpy.RandomState, optional The generator used to initialize SMACOF (metric, nonmetric) MDS If an integer is given, it fixes the seed Defaults to the global numpy random number generator Returns ------- Y : ndarray [n_samples, n_dim] low dimensional embedding of X using MDS
f11864:m1
def _get_plot_data(data, ndim=None):
out = data<EOL>if isinstance(data, PHATE):<EOL><INDENT>out = data.transform()<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>if isinstance(data, anndata.AnnData):<EOL><INDENT>try:<EOL><INDENT>out = data.obsm['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>except NameError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if ndim is not None and out[<NUM_LIT:0>].shape[<NUM_LIT:0>] < ndim:<EOL><INDENT>if isinstance(data, PHATE):<EOL><INDENT>data.set_params(n_components=ndim)<EOL>out = data.transform()<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(<EOL>ndim, out[<NUM_LIT:0>].shape[<NUM_LIT:0>]))<EOL><DEDENT><DEDENT>return out<EOL>
Get plot data out of an input object Parameters ---------- data : array-like, `phate.PHATE` or `scanpy.AnnData` ndim : int, optional (default: None) Minimum number of dimensions
f11866:m0
def scatter(x, y, z=None,<EOL>c=None, cmap=None, s=None, discrete=None,<EOL>ax=None, legend=None, figsize=None,<EOL>xticks=False,<EOL>yticks=False,<EOL>zticks=False,<EOL>xticklabels=True,<EOL>yticklabels=True,<EOL>zticklabels=True,<EOL>label_prefix="<STR_LIT>",<EOL>xlabel=None,<EOL>ylabel=None,<EOL>zlabel=None,<EOL>title=None,<EOL>legend_title="<STR_LIT>",<EOL>legend_loc='<STR_LIT>',<EOL>filename=None,<EOL>dpi=None,<EOL>**plot_kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>return scprep.plot.scatter(x=x, y=y, z=z,<EOL>c=c, cmap=cmap, s=s, discrete=discrete,<EOL>ax=ax, legend=legend, figsize=figsize,<EOL>xticks=xticks,<EOL>yticks=yticks,<EOL>zticks=zticks,<EOL>xticklabels=xticklabels,<EOL>yticklabels=yticklabels,<EOL>zticklabels=zticklabels,<EOL>label_prefix=label_prefix,<EOL>xlabel=xlabel,<EOL>ylabel=ylabel,<EOL>zlabel=zlabel,<EOL>title=title,<EOL>legend_title=legend_title,<EOL>legend_loc=legend_loc,<EOL>filename=filename,<EOL>dpi=dpi,<EOL>**plot_kwargs)<EOL>
Create a scatter plot Builds upon `matplotlib.pyplot.scatter` with nice defaults and handles categorical colors / legends better. For easy access, use `scatter2d` or `scatter3d`. Parameters ---------- x : list-like data for x axis y : list-like data for y axis z : list-like, optional (default: None) data for z axis c : list-like or None, optional (default: None) Color vector. Can be a single color value (RGB, RGBA, or named matplotlib colors), an array of these of length n_samples, or a list of discrete or continuous values of any data type. If `c` is not a single or list of matplotlib colors, the values in `c` will be used to populate the legend / colorbar with colors from `cmap` cmap : `matplotlib` colormap, str, dict or None, optional (default: None) matplotlib colormap. If None, uses `tab20` for discrete data and `inferno` for continuous data. If a dictionary, expects one key for every unique value in `c`, where values are valid matplotlib colors (hsv, rbg, rgba, or named colors) s : float, optional (default: 1) Point size. discrete : bool or None, optional (default: None) If True, the legend is categorical. If False, the legend is a colorbar. If None, discreteness is detected automatically. Data containing non-numeric `c` is always discrete, and numeric data with 20 or less unique values is discrete. ax : `matplotlib.Axes` or None, optional (default: None) axis on which to plot. If None, an axis is created legend : bool, optional (default: True) States whether or not to create a legend. If data is continuous, the legend is a colorbar. figsize : tuple, optional (default: None) Tuple of floats for creation of new `matplotlib` figure. Only used if `ax` is None. xticks : True, False, or list-like (default: False) If True, keeps default x ticks. If False, removes x ticks. If a list, sets custom x ticks yticks : True, False, or list-like (default: False) If True, keeps default y ticks. If False, removes y ticks. If a list, sets custom y ticks zticks : True, False, or list-like (default: False) If True, keeps default z ticks. If False, removes z ticks. If a list, sets custom z ticks. Only used for 3D plots. xticklabels : True, False, or list-like (default: True) If True, keeps default x tick labels. If False, removes x tick labels. If a list, sets custom x tick labels yticklabels : True, False, or list-like (default: True) If True, keeps default y tick labels. If False, removes y tick labels. If a list, sets custom y tick labels zticklabels : True, False, or list-like (default: True) If True, keeps default z tick labels. If False, removes z tick labels. If a list, sets custom z tick labels. Only used for 3D plots. label_prefix : str or None (default: "PHATE") Prefix for all axis labels. Axes will be labelled `label_prefix`1, `label_prefix`2, etc. Can be overriden by setting `xlabel`, `ylabel`, and `zlabel`. xlabel : str or None (default : None) Label for the x axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. ylabel : str or None (default : None) Label for the y axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. zlabel : str or None (default : None) Label for the z axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. Only used for 3D plots. title : str or None (default: None) axis title. If None, no title is set. legend_title : str (default: "") title for the colorbar of legend. Only used for discrete data. legend_loc : int or string or pair of floats, default: 'best' Matplotlib legend location. Only used for discrete data. See <https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html> for details. filename : str or None (default: None) file to which the output is saved dpi : int or None, optional (default: None) The resolution in dots per inch. If None it will default to the value savefig.dpi in the matplotlibrc file. If 'figure' it will set the dpi to be the value of the figure. Only used if filename is not None. **plot_kwargs : keyword arguments Extra arguments passed to `matplotlib.pyplot.scatter`. Returns ------- ax : `matplotlib.Axes` axis on which plot was drawn Examples -------- >>> import phate >>> import matplotlib.pyplot as plt >>> ### >>> # Running PHATE >>> ### >>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20, ... branch_length=100) >>> tree_data.shape (2000, 100) >>> phate_operator = phate.PHATE(k=5, a=20, t=150) >>> tree_phate = phate_operator.fit_transform(tree_data) >>> tree_phate.shape (2000, 2) >>> ### >>> # Plotting using phate.plot >>> ### >>> phate.plot.scatter2d(tree_phate, c=tree_clusters) >>> # You can also pass the PHATE operator instead of data >>> phate.plot.scatter2d(phate_operator, c=tree_clusters) >>> phate.plot.scatter3d(phate_operator, c=tree_clusters) >>> ### >>> # Using a cmap dictionary >>> ### >>> import numpy as np >>> X = np.random.normal(0,1,[1000,2]) >>> c = np.random.choice(['a','b'], 1000, replace=True) >>> X[c=='a'] += 10 >>> phate.plot.scatter2d(X, c=c, cmap={'a' : [1,0,0,1], 'b' : 'xkcd:sky blue'})
f11866:m1
def scatter2d(data, **kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>data = _get_plot_data(data, ndim=<NUM_LIT:2>)<EOL>return scprep.plot.scatter2d(data, **kwargs)<EOL>
Create a 2D scatter plot Builds upon `matplotlib.pyplot.scatter` with nice defaults and handles categorical colors / legends better. Parameters ---------- data : array-like, shape=[n_samples, n_features] Input data. Only the first two components will be used. c : list-like or None, optional (default: None) Color vector. Can be a single color value (RGB, RGBA, or named matplotlib colors), an array of these of length n_samples, or a list of discrete or continuous values of any data type. If `c` is not a single or list of matplotlib colors, the values in `c` will be used to populate the legend / colorbar with colors from `cmap` cmap : `matplotlib` colormap, str, dict or None, optional (default: None) matplotlib colormap. If None, uses `tab20` for discrete data and `inferno` for continuous data. If a dictionary, expects one key for every unique value in `c`, where values are valid matplotlib colors (hsv, rbg, rgba, or named colors) s : float, optional (default: 1) Point size. discrete : bool or None, optional (default: None) If True, the legend is categorical. If False, the legend is a colorbar. If None, discreteness is detected automatically. Data containing non-numeric `c` is always discrete, and numeric data with 20 or less unique values is discrete. ax : `matplotlib.Axes` or None, optional (default: None) axis on which to plot. If None, an axis is created legend : bool, optional (default: True) States whether or not to create a legend. If data is continuous, the legend is a colorbar. figsize : tuple, optional (default: None) Tuple of floats for creation of new `matplotlib` figure. Only used if `ax` is None. xticks : True, False, or list-like (default: False) If True, keeps default x ticks. If False, removes x ticks. If a list, sets custom x ticks yticks : True, False, or list-like (default: False) If True, keeps default y ticks. If False, removes y ticks. If a list, sets custom y ticks zticks : True, False, or list-like (default: False) If True, keeps default z ticks. If False, removes z ticks. If a list, sets custom z ticks. Only used for 3D plots. xticklabels : True, False, or list-like (default: True) If True, keeps default x tick labels. If False, removes x tick labels. If a list, sets custom x tick labels yticklabels : True, False, or list-like (default: True) If True, keeps default y tick labels. If False, removes y tick labels. If a list, sets custom y tick labels zticklabels : True, False, or list-like (default: True) If True, keeps default z tick labels. If False, removes z tick labels. If a list, sets custom z tick labels. Only used for 3D plots. label_prefix : str or None (default: "PHATE") Prefix for all axis labels. Axes will be labelled `label_prefix`1, `label_prefix`2, etc. Can be overriden by setting `xlabel`, `ylabel`, and `zlabel`. xlabel : str or None (default : None) Label for the x axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. ylabel : str or None (default : None) Label for the y axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. zlabel : str or None (default : None) Label for the z axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. Only used for 3D plots. title : str or None (default: None) axis title. If None, no title is set. legend_title : str (default: "") title for the colorbar of legend legend_loc : int or string or pair of floats, default: 'best' Matplotlib legend location. Only used for discrete data. See <https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html> for details. filename : str or None (default: None) file to which the output is saved dpi : int or None, optional (default: None) The resolution in dots per inch. If None it will default to the value savefig.dpi in the matplotlibrc file. If 'figure' it will set the dpi to be the value of the figure. Only used if filename is not None. **plot_kwargs : keyword arguments Extra arguments passed to `matplotlib.pyplot.scatter`. Returns ------- ax : `matplotlib.Axes` axis on which plot was drawn Examples -------- >>> import phate >>> import matplotlib.pyplot as plt >>> ### >>> # Running PHATE >>> ### >>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20, ... branch_length=100) >>> tree_data.shape (2000, 100) >>> phate_operator = phate.PHATE(k=5, a=20, t=150) >>> tree_phate = phate_operator.fit_transform(tree_data) >>> tree_phate.shape (2000, 2) >>> ### >>> # Plotting using phate.plot >>> ### >>> phate.plot.scatter2d(tree_phate, c=tree_clusters) >>> # You can also pass the PHATE operator instead of data >>> phate.plot.scatter2d(phate_operator, c=tree_clusters) >>> phate.plot.scatter3d(phate_operator, c=tree_clusters) >>> ### >>> # Using a cmap dictionary >>> ### >>> import numpy as np >>> X = np.random.normal(0,1,[1000,2]) >>> c = np.random.choice(['a','b'], 1000, replace=True) >>> X[c=='a'] += 10 >>> phate.plot.scatter2d(X, c=c, cmap={'a' : [1,0,0,1], 'b' : 'xkcd:sky blue'})
f11866:m2
def scatter3d(data, **kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>data = _get_plot_data(data, ndim=<NUM_LIT:3>)<EOL>return scprep.plot.scatter3d(data, **kwargs)<EOL>
Create a 3D scatter plot Builds upon `matplotlib.pyplot.scatter` with nice defaults and handles categorical colors / legends better. Parameters ---------- data : array-like, shape=[n_samples, n_features] to be the value of the figure. Only used if filename is not None. Input data. Only the first three components will be used. c : list-like or None, optional (default: None) Color vector. Can be a single color value (RGB, RGBA, or named matplotlib colors), an array of these of length n_samples, or a list of discrete or continuous values of any data type. If `c` is not a single or list of matplotlib colors, the values in `c` will be used to populate the legend / colorbar with colors from `cmap` cmap : `matplotlib` colormap, str, dict or None, optional (default: None) matplotlib colormap. If None, uses `tab20` for discrete data and `inferno` for continuous data. If a dictionary, expects one key for every unique value in `c`, where values are valid matplotlib colors (hsv, rbg, rgba, or named colors) s : float, optional (default: 1) Point size. discrete : bool or None, optional (default: None) If True, the legend is categorical. If False, the legend is a colorbar. If None, discreteness is detected automatically. Data containing non-numeric `c` is always discrete, and numeric data with 20 or less unique values is discrete. ax : `matplotlib.Axes` or None, optional (default: None) axis on which to plot. If None, an axis is created legend : bool, optional (default: True) States whether or not to create a legend. If data is continuous, the legend is a colorbar. figsize : tuple, optional (default: None) Tuple of floats for creation of new `matplotlib` figure. Only used if `ax` is None. xticks : True, False, or list-like (default: False) If True, keeps default x ticks. If False, removes x ticks. If a list, sets custom x ticks yticks : True, False, or list-like (default: False) If True, keeps default y ticks. If False, removes y ticks. If a list, sets custom y ticks zticks : True, False, or list-like (default: False) If True, keeps default z ticks. If False, removes z ticks. If a list, sets custom z ticks. Only used for 3D plots. xticklabels : True, False, or list-like (default: True) If True, keeps default x tick labels. If False, removes x tick labels. If a list, sets custom x tick labels yticklabels : True, False, or list-like (default: True) If True, keeps default y tick labels. If False, removes y tick labels. If a list, sets custom y tick labels zticklabels : True, False, or list-like (default: True) If True, keeps default z tick labels. If False, removes z tick labels. If a list, sets custom z tick labels. Only used for 3D plots. label_prefix : str or None (default: "PHATE") Prefix for all axis labels. Axes will be labelled `label_prefix`1, `label_prefix`2, etc. Can be overriden by setting `xlabel`, `ylabel`, and `zlabel`. xlabel : str or None (default : None) Label for the x axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. ylabel : str or None (default : None) Label for the y axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. zlabel : str or None (default : None) Label for the z axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. Only used for 3D plots. title : str or None (default: None) axis title. If None, no title is set. legend_title : str (default: "") title for the colorbar of legend legend_loc : int or string or pair of floats, default: 'best' Matplotlib legend location. Only used for discrete data. See <https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html> for details. filename : str or None (default: None) file to which the output is saved dpi : int or None, optional (default: None) The resolution in dots per inch. If None it will default to the value savefig.dpi in the matplotlibrc file. If 'figure' it will set the dpi to be the value of the figure. Only used if filename is not None. **plot_kwargs : keyword arguments Extra arguments passed to `matplotlib.pyplot.scatter`. Returns ------- ax : `matplotlib.Axes` axis on which plot was drawn Examples -------- >>> import phate >>> import matplotlib.pyplot as plt >>> ### >>> # Running PHATE >>> ### >>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20, ... branch_length=100) >>> tree_data.shape (2000, 100) >>> phate_operator = phate.PHATE(k=5, a=20, t=150) >>> tree_phate = phate_operator.fit_transform(tree_data) >>> tree_phate.shape (2000, 2) >>> ### >>> # Plotting using phate.plot >>> ### >>> phate.plot.scatter2d(tree_phate, c=tree_clusters) >>> # You can also pass the PHATE operator instead of data >>> phate.plot.scatter2d(phate_operator, c=tree_clusters) >>> phate.plot.scatter3d(phate_operator, c=tree_clusters) >>> ### >>> # Using a cmap dictionary >>> ### >>> import numpy as np >>> X = np.random.normal(0,1,[1000,2]) >>> c = np.random.choice(['a','b'], 1000, replace=True) >>> X[c=='a'] += 10 >>> phate.plot.scatter2d(X, c=c, cmap={'a' : [1,0,0,1], 'b' : 'xkcd:sky blue'})
f11866:m3
def rotate_scatter3d(data,<EOL>filename=None,<EOL>elev=<NUM_LIT:30>,<EOL>rotation_speed=<NUM_LIT:30>,<EOL>fps=<NUM_LIT:10>,<EOL>ax=None,<EOL>figsize=None,<EOL>dpi=None,<EOL>ipython_html="<STR_LIT>",<EOL>**kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>return scprep.plot.rotate_scatter3d(data,<EOL>filename=filename,<EOL>elev=elev,<EOL>rotation_speed=rotation_speed,<EOL>fps=fps,<EOL>ax=ax,<EOL>figsize=figsize,<EOL>dpi=dpi,<EOL>ipython_html=ipython_html,<EOL>**kwargs)<EOL>
Create a rotating 3D scatter plot Builds upon `matplotlib.pyplot.scatter` with nice defaults and handles categorical colors / legends better. Parameters ---------- data : array-like, `phate.PHATE` or `scanpy.AnnData` Input data. Only the first three dimensions are used. filename : str, optional (default: None) If not None, saves a .gif or .mp4 with the output elev : float, optional (default: 30) Elevation of viewpoint from horizontal, in degrees rotation_speed : float, optional (default: 30) Speed of axis rotation, in degrees per second fps : int, optional (default: 10) Frames per second. Increase this for a smoother animation ax : `matplotlib.Axes` or None, optional (default: None) axis on which to plot. If None, an axis is created figsize : tuple, optional (default: None) Tuple of floats for creation of new `matplotlib` figure. Only used if `ax` is None. dpi : number, optional (default: None) Controls the dots per inch for the movie frames. This combined with the figure's size in inches controls the size of the movie. If None, defaults to rcParams["savefig.dpi"] ipython_html : {'html5', 'jshtml'} which html writer to use if using a Jupyter Notebook **kwargs : keyword arguments See :~func:`phate.plot.scatter3d`. Returns ------- ani : `matplotlib.animation.FuncAnimation` animation object Examples -------- >>> import phate >>> import matplotlib.pyplot as plt >>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20, ... branch_length=100) >>> tree_data.shape (2000, 100) >>> phate_operator = phate.PHATE(n_components=3, k=5, a=20, t=150) >>> tree_phate = phate_operator.fit_transform(tree_data) >>> tree_phate.shape (2000, 2) >>> phate.plot.rotate_scatter3d(tree_phate, c=tree_clusters)
f11866:m4
def compute_von_neumann_entropy(data, t_max=<NUM_LIT:100>):
_, eigenvalues, _ = svd(data)<EOL>entropy = []<EOL>eigenvalues_t = np.copy(eigenvalues)<EOL>for _ in range(t_max):<EOL><INDENT>prob = eigenvalues_t / np.sum(eigenvalues_t)<EOL>prob = prob + np.finfo(float).eps<EOL>entropy.append(-np.sum(prob * np.log(prob)))<EOL>eigenvalues_t = eigenvalues_t * eigenvalues<EOL><DEDENT>entropy = np.array(entropy)<EOL>return np.array(entropy)<EOL>
Determines the Von Neumann entropy of data at varying matrix powers. The user should select a value of t around the "knee" of the entropy curve. Parameters ---------- t_max : int, default: 100 Maximum value of t to test Returns ------- entropy : array, shape=[t_max] The entropy of the diffusion affinities for each value of t Examples -------- >>> import numpy as np >>> import phate >>> X = np.eye(10) >>> X[0,0] = 5 >>> X[3,2] = 4 >>> h = phate.vne.compute_von_neumann_entropy(X) >>> phate.vne.find_knee_point(h) 23
f11867:m0
def find_knee_point(y, x=None):
try:<EOL><INDENT>y.shape<EOL><DEDENT>except AttributeError:<EOL><INDENT>y = np.array(y)<EOL><DEDENT>if len(y) < <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif len(y.shape) > <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if x is None:<EOL><INDENT>x = np.arange(len(y))<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>x.shape<EOL><DEDENT>except AttributeError:<EOL><INDENT>x = np.array(x)<EOL><DEDENT>if not x.shape == y.shape:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>idx = np.argsort(x)<EOL>x = x[idx]<EOL>y = y[idx]<EOL><DEDENT><DEDENT>n = np.arange(<NUM_LIT:2>, len(y) + <NUM_LIT:1>).astype(np.float32)<EOL>sigma_xy = np.cumsum(x * y)[<NUM_LIT:1>:]<EOL>sigma_x = np.cumsum(x)[<NUM_LIT:1>:]<EOL>sigma_y = np.cumsum(y)[<NUM_LIT:1>:]<EOL>sigma_xx = np.cumsum(x * x)[<NUM_LIT:1>:]<EOL>det = (n * sigma_xx - sigma_x * sigma_x)<EOL>mfwd = (n * sigma_xy - sigma_x * sigma_y) / det<EOL>bfwd = -(sigma_x * sigma_xy - sigma_xx * sigma_y) / det<EOL>sigma_xy = np.cumsum(x[::-<NUM_LIT:1>] * y[::-<NUM_LIT:1>])[<NUM_LIT:1>:]<EOL>sigma_x = np.cumsum(x[::-<NUM_LIT:1>])[<NUM_LIT:1>:]<EOL>sigma_y = np.cumsum(y[::-<NUM_LIT:1>])[<NUM_LIT:1>:]<EOL>sigma_xx = np.cumsum(x[::-<NUM_LIT:1>] * x[::-<NUM_LIT:1>])[<NUM_LIT:1>:]<EOL>det = (n * sigma_xx - sigma_x * sigma_x)<EOL>mbck = ((n * sigma_xy - sigma_x * sigma_y) / det)[::-<NUM_LIT:1>]<EOL>bbck = (-(sigma_x * sigma_xy - sigma_xx * sigma_y) / det)[::-<NUM_LIT:1>]<EOL>error_curve = np.full_like(y, np.float('<STR_LIT>'))<EOL>for breakpt in np.arange(<NUM_LIT:1>, len(y) - <NUM_LIT:1>):<EOL><INDENT>delsfwd = (mfwd[breakpt - <NUM_LIT:1>] * x[:breakpt + <NUM_LIT:1>] +<EOL>bfwd[breakpt - <NUM_LIT:1>]) - y[:breakpt + <NUM_LIT:1>]<EOL>delsbck = (mbck[breakpt - <NUM_LIT:1>] * x[breakpt:] +<EOL>bbck[breakpt - <NUM_LIT:1>]) - y[breakpt:]<EOL>error_curve[breakpt] = np.sum(np.abs(delsfwd)) +np.sum(np.abs(delsbck))<EOL><DEDENT>loc = np.argmin(error_curve[<NUM_LIT:1>:-<NUM_LIT:1>]) + <NUM_LIT:1><EOL>knee_point = x[loc]<EOL>return knee_point<EOL>
Returns the x-location of a (single) knee of curve y=f(x) Parameters ---------- y : array, shape=[n] data for which to find the knee point x : array, optional, shape=[n], default=np.arange(len(y)) indices of the data points of y, if these are not in order and evenly spaced Returns ------- knee_point : int The index (or x value) of the knee point on y Examples -------- >>> import numpy as np >>> import phate >>> x = np.arange(20) >>> y = np.exp(-x/10) >>> phate.vne.find_knee_point(y,x) 8
f11867:m1
def check_positive(**params):
for p in params:<EOL><INDENT>if not isinstance(params[p], numbers.Number) or params[p] <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(p, params[p]))<EOL><DEDENT><DEDENT>
Check that parameters are positive as expected Raises ------ ValueError : unacceptable choice of parameters
f11869:m0
def check_int(**params):
for p in params:<EOL><INDENT>if not isinstance(params[p], numbers.Integral):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(p, params[p]))<EOL><DEDENT><DEDENT>
Check that parameters are integers as expected Raises ------ ValueError : unacceptable choice of parameters
f11869:m1
def check_if_not(x, *checks, **params):
for p in params:<EOL><INDENT>if params[p] is not x and params[p] != x:<EOL><INDENT>[check(**{p: params[p]}) for check in checks]<EOL><DEDENT><DEDENT>
Run checks only if parameters are not equal to a specified value Parameters ---------- x : excepted value Checks not run if parameters equal x checks : function Unnamed arguments, check functions to be run params : object Named arguments, parameters to be checked Raises ------ ValueError : unacceptable choice of parameters
f11869:m2
def check_in(choices, **params):
for p in params:<EOL><INDENT>if params[p] not in choices:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(<EOL>p, params[p], choices))<EOL><DEDENT><DEDENT>
Checks parameters are in a list of allowed parameters Parameters ---------- choices : array-like, accepted values params : object Named arguments, parameters to be checked Raises ------ ValueError : unacceptable choice of parameters
f11869:m3
def check_between(v_min, v_max, **params):
for p in params:<EOL><INDENT>if params[p] < v_min or params[p] > v_max:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(p, v_min, v_max, params[p]))<EOL><DEDENT><DEDENT>
Checks parameters are in a specified range Parameters ---------- v_min : float, minimum allowed value (inclusive) v_max : float, maximum allowed value (inclusive) params : object Named arguments, parameters to be checked Raises ------ ValueError : unacceptable choice of parameters
f11869:m4
def matrix_is_equivalent(X, Y):
return X is Y or (isinstance(X, Y.__class__) and X.shape == Y.shape and<EOL>np.sum((X != Y).sum()) == <NUM_LIT:0>)<EOL>
Checks matrix equivalence with numpy, scipy and pandas
f11869:m5
def in_ipynb():
__VALID_NOTEBOOKS = ["<STR_LIT>",<EOL>"<STR_LIT>"]<EOL>try:<EOL><INDENT>return str(type(get_ipython())) in __VALID_NOTEBOOKS<EOL><DEDENT>except NameError:<EOL><INDENT>return False<EOL><DEDENT>
Check if we are running in a Jupyter Notebook Credit to https://stackoverflow.com/a/24937408/3996580
f11869:m6
@property<EOL><INDENT>def diff_op(self):<DEDENT>
if self.graph is not None:<EOL><INDENT>if isinstance(self.graph, graphtools.graphs.LandmarkGraph):<EOL><INDENT>diff_op = self.graph.landmark_op<EOL><DEDENT>else:<EOL><INDENT>diff_op = self.graph.diff_op<EOL><DEDENT>if sparse.issparse(diff_op):<EOL><INDENT>diff_op = diff_op.toarray()<EOL><DEDENT>return diff_op<EOL><DEDENT>else:<EOL><INDENT>raise NotFittedError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>
The diffusion operator calculated from the data
f11870:c0:m1
def _check_params(self):
utils.check_positive(n_components=self.n_components,<EOL>k=self.knn)<EOL>utils.check_int(n_components=self.n_components,<EOL>k=self.knn,<EOL>n_jobs=self.n_jobs)<EOL>utils.check_between(<NUM_LIT:0>, <NUM_LIT:1>, gamma=self.gamma)<EOL>utils.check_if_not(None, utils.check_positive, a=self.decay)<EOL>utils.check_if_not(None, utils.check_positive, utils.check_int,<EOL>n_landmark=self.n_landmark,<EOL>n_pca=self.n_pca)<EOL>utils.check_if_not('<STR_LIT>', utils.check_positive, utils.check_int,<EOL>t=self.t)<EOL>if not callable(self.knn_dist):<EOL><INDENT>utils.check_in(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'],<EOL>knn_dist=self.knn_dist)<EOL><DEDENT>if not callable(self.mds_dist):<EOL><INDENT>utils.check_in(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>mds_dist=self.mds_dist)<EOL><DEDENT>utils.check_in(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>mds=self.mds)<EOL>
Check PHATE parameters This allows us to fail early - otherwise certain unacceptable parameter choices, such as mds='mmds', would only fail after minutes of runtime. Raises ------ ValueError : unacceptable choice of parameters
f11870:c0:m2
def set_params(self, **params):
reset_kernel = False<EOL>reset_potential = False<EOL>reset_embedding = False<EOL>if '<STR_LIT>' in params andparams['<STR_LIT>'] != self.n_components:<EOL><INDENT>self.n_components = params['<STR_LIT>']<EOL>reset_embedding = True<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in params and params['<STR_LIT>'] != self.mds:<EOL><INDENT>self.mds = params['<STR_LIT>']<EOL>reset_embedding = True<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in params and params['<STR_LIT>'] != self.mds_dist:<EOL><INDENT>self.mds_dist = params['<STR_LIT>']<EOL>reset_embedding = True<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT:t>' in params and params['<STR_LIT:t>'] != self.t:<EOL><INDENT>self.t = params['<STR_LIT:t>']<EOL>reset_potential = True<EOL>del params['<STR_LIT:t>']<EOL><DEDENT>if '<STR_LIT>' in params:<EOL><INDENT>if params['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>params['<STR_LIT>'] = <NUM_LIT:1><EOL><DEDENT>elif params['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>params['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>params['<STR_LIT>']))<EOL><DEDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>params['<STR_LIT>'],<EOL>params['<STR_LIT>']),<EOL>FutureWarning)<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in params andparams['<STR_LIT>'] != self.gamma:<EOL><INDENT>self.gamma = params['<STR_LIT>']<EOL>reset_potential = True<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT:k>' in params and params['<STR_LIT:k>'] != self.knn:<EOL><INDENT>self.knn = params['<STR_LIT:k>']<EOL>reset_kernel = True<EOL>del params['<STR_LIT:k>']<EOL><DEDENT>if '<STR_LIT:a>' in params and params['<STR_LIT:a>'] != self.decay:<EOL><INDENT>self.decay = params['<STR_LIT:a>']<EOL>reset_kernel = True<EOL>del params['<STR_LIT:a>']<EOL><DEDENT>if '<STR_LIT>' in params and params['<STR_LIT>'] != self.knn:<EOL><INDENT>self.knn = params['<STR_LIT>']<EOL>reset_kernel = True<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in params and params['<STR_LIT>'] != self.decay:<EOL><INDENT>self.decay = params['<STR_LIT>']<EOL>reset_kernel = True<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in params:<EOL><INDENT>if self.X is not None and params['<STR_LIT>'] >= np.min(self.X.shape):<EOL><INDENT>params['<STR_LIT>'] = None<EOL><DEDENT>if params['<STR_LIT>'] != self.n_pca:<EOL><INDENT>self.n_pca = params['<STR_LIT>']<EOL>reset_kernel = True<EOL>del params['<STR_LIT>']<EOL><DEDENT><DEDENT>if '<STR_LIT>' in params and params['<STR_LIT>'] != self.knn_dist:<EOL><INDENT>self.knn_dist = params['<STR_LIT>']<EOL>reset_kernel = True<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in params and params['<STR_LIT>'] != self.n_landmark:<EOL><INDENT>if self.n_landmark is None or params['<STR_LIT>'] is None:<EOL><INDENT>self._reset_graph()<EOL><DEDENT>else:<EOL><INDENT>self._set_graph_params(n_landmark=params['<STR_LIT>'])<EOL><DEDENT>self.n_landmark = params['<STR_LIT>']<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in params:<EOL><INDENT>self.n_jobs = params['<STR_LIT>']<EOL>self._set_graph_params(n_jobs=params['<STR_LIT>'])<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in params:<EOL><INDENT>self.random_state = params['<STR_LIT>']<EOL>self._set_graph_params(random_state=params['<STR_LIT>'])<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in params:<EOL><INDENT>self.verbose = params['<STR_LIT>']<EOL>tasklogger.set_level(self.verbose)<EOL>self._set_graph_params(verbose=params['<STR_LIT>'])<EOL>del params['<STR_LIT>']<EOL><DEDENT>if reset_kernel:<EOL><INDENT>self._reset_graph()<EOL><DEDENT>if reset_potential:<EOL><INDENT>self._reset_potential()<EOL><DEDENT>if reset_embedding:<EOL><INDENT>self._reset_embedding()<EOL><DEDENT>self._set_graph_params(**params)<EOL>self._check_params()<EOL>return self<EOL>
Set the parameters on this estimator. Any parameters not given as named arguments will be left at their current value. Parameters ---------- n_components : int, optional, default: 2 number of dimensions in which the data will be embedded knn : int, optional, default: 5 number of nearest neighbors on which to build kernel decay : int, optional, default: 40 sets decay rate of kernel tails. If None, alpha decaying kernel is not used n_landmark : int, optional, default: 2000 number of landmarks to use in fast PHATE t : int, optional, default: 'auto' power to which the diffusion operator is powered. This sets the level of diffusion. If 'auto', t is selected according to the knee point in the Von Neumann Entropy of the diffusion operator gamma : float, optional, default: 1 Informational distance constant between -1 and 1. `gamma=1` gives the PHATE log potential, `gamma=0` gives a square root potential. n_pca : int, optional, default: 100 Number of principal components to use for calculating neighborhoods. For extremely large datasets, using n_pca < 20 allows neighborhoods to be calculated in roughly log(n_samples) time. knn_dist : string, optional, default: 'euclidean' recommended values: 'euclidean', 'cosine', 'precomputed' Any metric from `scipy.spatial.distance` can be used distance metric for building kNN graph. Custom distance functions of form `f(x, y) = d` are also accepted. If 'precomputed', `data` should be an n_samples x n_samples distance or affinity matrix. Distance matrices are assumed to have zeros down the diagonal, while affinity matrices are assumed to have non-zero values down the diagonal. This is detected automatically using `data[0,0]`. You can override this detection with `knn_dist='precomputed_distance'` or `knn_dist='precomputed_affinity'`. mds_dist : string, optional, default: 'euclidean' recommended values: 'euclidean' and 'cosine' Any metric from `scipy.spatial.distance` can be used distance metric for MDS mds : string, optional, default: 'metric' choose from ['classic', 'metric', 'nonmetric']. Selects which MDS algorithm is used for dimensionality reduction n_jobs : integer, optional, default: 1 The number of jobs to use for the computation. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used random_state : integer or numpy.RandomState, optional, default: None The generator used to initialize SMACOF (metric, nonmetric) MDS If an integer is given, it fixes the seed Defaults to the global `numpy` random number generator verbose : `int` or `boolean`, optional (default: 1) If `True` or `> 0`, print status messages k : Deprecated for `knn` a : Deprecated for `decay` Examples -------- >>> import phate >>> import matplotlib.pyplot as plt >>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=50, n_branch=5, ... branch_length=50) >>> tree_data.shape (250, 50) >>> phate_operator = phate.PHATE(k=5, a=20, t=150) >>> tree_phate = phate_operator.fit_transform(tree_data) >>> tree_phate.shape (250, 2) >>> phate_operator.set_params(n_components=10) PHATE(a=20, alpha_decay=None, k=5, knn_dist='euclidean', mds='metric', mds_dist='euclidean', n_components=10, n_jobs=1, n_landmark=2000, n_pca=100, njobs=None, potential_method='log', random_state=None, t=150, verbose=1) >>> tree_phate = phate_operator.transform() >>> tree_phate.shape (250, 10) >>> # plt.scatter(tree_phate[:,0], tree_phate[:,1], c=tree_clusters) >>> # plt.show() Returns ------- self
f11870:c0:m7
def reset_mds(self, **kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>self.set_params(**kwargs)<EOL>
Deprecated. Reset parameters related to multidimensional scaling Parameters ---------- n_components : int, optional, default: None If given, sets number of dimensions in which the data will be embedded mds : string, optional, default: None choose from ['classic', 'metric', 'nonmetric'] If given, sets which MDS algorithm is used for dimensionality reduction mds_dist : string, optional, default: None recommended values: 'euclidean' and 'cosine' Any metric from scipy.spatial.distance can be used If given, sets the distance metric for MDS
f11870:c0:m8
def reset_potential(self, **kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>self.set_params(**kwargs)<EOL>
Deprecated. Reset parameters related to the diffusion potential Parameters ---------- t : int or 'auto', optional, default: None Power to which the diffusion operator is powered If given, sets the level of diffusion potential_method : string, optional, default: None choose from ['log', 'sqrt'] If given, sets which transformation of the diffusional operator is used to compute the diffusion potential
f11870:c0:m9
def fit(self, X):
X, n_pca, precomputed, update_graph = self._parse_input(X)<EOL>if precomputed is None:<EOL><INDENT>tasklogger.log_info(<EOL>"<STR_LIT>".format(<EOL>X.shape[<NUM_LIT:0>], X.shape[<NUM_LIT:1>]))<EOL><DEDENT>else:<EOL><INDENT>tasklogger.log_info(<EOL>"<STR_LIT>".format(<EOL>precomputed, X.shape[<NUM_LIT:0>]))<EOL><DEDENT>if self.n_landmark is None or X.shape[<NUM_LIT:0>] <= self.n_landmark:<EOL><INDENT>n_landmark = None<EOL><DEDENT>else:<EOL><INDENT>n_landmark = self.n_landmark<EOL><DEDENT>if self.graph is not None and update_graph:<EOL><INDENT>self._update_graph(X, precomputed, n_pca, n_landmark)<EOL><DEDENT>self.X = X<EOL>if self.graph is None:<EOL><INDENT>tasklogger.log_start("<STR_LIT>")<EOL>self.graph = graphtools.Graph(<EOL>X,<EOL>n_pca=n_pca,<EOL>n_landmark=n_landmark,<EOL>distance=self.knn_dist,<EOL>precomputed=precomputed,<EOL>knn=self.knn,<EOL>decay=self.decay,<EOL>thresh=<NUM_LIT>,<EOL>n_jobs=self.n_jobs,<EOL>verbose=self.verbose,<EOL>random_state=self.random_state,<EOL>**(self.kwargs))<EOL>tasklogger.log_complete("<STR_LIT>")<EOL><DEDENT>self.diff_op<EOL>return self<EOL>
Computes the diffusion operator Parameters ---------- X : array, shape=[n_samples, n_features] input data with `n_samples` samples and `n_dimensions` dimensions. Accepted data types: `numpy.ndarray`, `scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData`. If `knn_dist` is 'precomputed', `data` should be a n_samples x n_samples distance or affinity matrix Returns ------- phate_operator : PHATE The estimator object
f11870:c0:m12
def transform(self, X=None, t_max=<NUM_LIT:100>, plot_optimal_t=False, ax=None):
if self.graph is None:<EOL><INDENT>raise NotFittedError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>elif X is not None and not utils.matrix_is_equivalent(X, self.X):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>RuntimeWarning)<EOL>if isinstance(self.graph, graphtools.graphs.TraditionalGraph) andself.graph.precomputed is not None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>transitions = self.graph.extend_to_data(X)<EOL>return self.graph.interpolate(self.embedding,<EOL>transitions)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>diff_potential = self.calculate_potential(<EOL>t_max=t_max, plot_optimal_t=plot_optimal_t, ax=ax)<EOL>if self.embedding is None:<EOL><INDENT>tasklogger.log_start("<STR_LIT>".format(self.mds))<EOL>self.embedding = mds.embed_MDS(<EOL>diff_potential, ndim=self.n_components, how=self.mds,<EOL>distance_metric=self.mds_dist, n_jobs=self.n_jobs,<EOL>seed=self.random_state, verbose=max(self.verbose - <NUM_LIT:1>, <NUM_LIT:0>))<EOL>tasklogger.log_complete("<STR_LIT>".format(self.mds))<EOL><DEDENT>if isinstance(self.graph, graphtools.graphs.LandmarkGraph):<EOL><INDENT>tasklogger.log_debug("<STR_LIT>")<EOL>return self.graph.interpolate(self.embedding)<EOL><DEDENT>else:<EOL><INDENT>return self.embedding<EOL><DEDENT><DEDENT>
Computes the position of the cells in the embedding space Parameters ---------- X : array, optional, shape=[n_samples, n_features] input data with `n_samples` samples and `n_dimensions` dimensions. Not required, since PHATE does not currently embed cells not given in the input matrix to `PHATE.fit()`. Accepted data types: `numpy.ndarray`, `scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData`. If `knn_dist` is 'precomputed', `data` should be a n_samples x n_samples distance or affinity matrix t_max : int, optional, default: 100 maximum t to test if `t` is set to 'auto' plot_optimal_t : boolean, optional, default: False If true and `t` is set to 'auto', plot the Von Neumann entropy used to select t ax : matplotlib.axes.Axes, optional If given and `plot_optimal_t` is true, plot will be drawn on the given axis. Returns ------- embedding : array, shape=[n_samples, n_dimensions] The cells embedded in a lower dimensional space using PHATE
f11870:c0:m13
def fit_transform(self, X, **kwargs):
tasklogger.log_start('<STR_LIT>')<EOL>self.fit(X)<EOL>embedding = self.transform(**kwargs)<EOL>tasklogger.log_complete('<STR_LIT>')<EOL>return embedding<EOL>
Computes the diffusion operator and the position of the cells in the embedding space Parameters ---------- X : array, shape=[n_samples, n_features] input data with `n_samples` samples and `n_dimensions` dimensions. Accepted data types: `numpy.ndarray`, `scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData` If `knn_dist` is 'precomputed', `data` should be a n_samples x n_samples distance or affinity matrix kwargs : further arguments for `PHATE.transform()` Keyword arguments as specified in :func:`~phate.PHATE.transform` Returns ------- embedding : array, shape=[n_samples, n_dimensions] The cells embedded in a lower dimensional space using PHATE
f11870:c0:m14
def calculate_potential(self, t=None,<EOL>t_max=<NUM_LIT:100>, plot_optimal_t=False, ax=None):
if t is None:<EOL><INDENT>t = self.t<EOL><DEDENT>if self.diff_potential is None:<EOL><INDENT>if t == '<STR_LIT>':<EOL><INDENT>t = self.optimal_t(t_max=t_max, plot=plot_optimal_t, ax=ax)<EOL><DEDENT>else:<EOL><INDENT>t = self.t<EOL><DEDENT>tasklogger.log_start("<STR_LIT>")<EOL>diff_op_t = np.linalg.matrix_power(self.diff_op, t)<EOL>if self.gamma == <NUM_LIT:1>:<EOL><INDENT>diff_op_t = diff_op_t + <NUM_LIT><EOL>self.diff_potential = -<NUM_LIT:1> * np.log(diff_op_t)<EOL><DEDENT>elif self.gamma == -<NUM_LIT:1>:<EOL><INDENT>self.diff_potential = diff_op_t<EOL><DEDENT>else:<EOL><INDENT>c = (<NUM_LIT:1> - self.gamma) / <NUM_LIT:2><EOL>self.diff_potential = ((diff_op_t)**c) / c<EOL><DEDENT>tasklogger.log_complete("<STR_LIT>")<EOL><DEDENT>elif plot_optimal_t:<EOL><INDENT>self.optimal_t(t_max=t_max, plot=plot_optimal_t, ax=ax)<EOL><DEDENT>return self.diff_potential<EOL>
Calculates the diffusion potential Parameters ---------- t : int power to which the diffusion operator is powered sets the level of diffusion t_max : int, default: 100 Maximum value of `t` to test plot_optimal_t : boolean, default: False If true, plots the Von Neumann Entropy and knee point ax : matplotlib.Axes, default: None If plot=True and ax is not None, plots the VNE on the given axis Otherwise, creates a new axis and displays the plot Returns ------- diff_potential : array-like, shape=[n_samples, n_samples] The diffusion potential fit on the input data
f11870:c0:m15
def von_neumann_entropy(self, t_max=<NUM_LIT:100>):
t = np.arange(t_max)<EOL>return t, vne.compute_von_neumann_entropy(self.diff_op, t_max=t_max)<EOL>
Calculate Von Neumann Entropy Determines the Von Neumann entropy of the diffusion affinities at varying levels of `t`. The user should select a value of `t` around the "knee" of the entropy curve. We require that 'fit' stores the value of `PHATE.diff_op` in order to calculate the Von Neumann entropy. Parameters ---------- t_max : int, default: 100 Maximum value of `t` to test Returns ------- entropy : array, shape=[t_max] The entropy of the diffusion affinities for each value of `t`
f11870:c0:m16
def optimal_t(self, t_max=<NUM_LIT:100>, plot=False, ax=None):
tasklogger.log_start("<STR_LIT>")<EOL>t, h = self.von_neumann_entropy(t_max=t_max)<EOL>t_opt = vne.find_knee_point(y=h, x=t)<EOL>tasklogger.log_info("<STR_LIT>".format(t_opt))<EOL>tasklogger.log_complete("<STR_LIT>")<EOL>if plot:<EOL><INDENT>if ax is None:<EOL><INDENT>fig, ax = plt.subplots()<EOL>show = True<EOL><DEDENT>else:<EOL><INDENT>show = False<EOL><DEDENT>ax.plot(t, h)<EOL>ax.scatter(t_opt, h[t == t_opt], marker='<STR_LIT:*>', c='<STR_LIT:k>', s=<NUM_LIT:50>)<EOL>ax.set_xlabel("<STR_LIT:t>")<EOL>ax.set_ylabel("<STR_LIT>")<EOL>ax.set_title("<STR_LIT>".format(t_opt))<EOL>if show:<EOL><INDENT>plt.show()<EOL><DEDENT><DEDENT>return t_opt<EOL>
Find the optimal value of t Selects the optimal value of t based on the knee point of the Von Neumann Entropy of the diffusion operator. Parameters ---------- t_max : int, default: 100 Maximum value of t to test plot : boolean, default: False If true, plots the Von Neumann Entropy and knee point ax : matplotlib.Axes, default: None If plot=True and ax is not None, plots the VNE on the given axis Otherwise, creates a new axis and displays the plot Returns ------- t_opt : int The optimal value of t
f11870:c0:m17
def kmeans(phate_op, k=<NUM_LIT:8>, random_state=None):
if phate_op.graph is not None:<EOL><INDENT>diff_potential = phate_op.calculate_potential()<EOL>if isinstance(phate_op.graph, graphtools.graphs.LandmarkGraph):<EOL><INDENT>diff_potential = phate_op.graph.interpolate(diff_potential)<EOL><DEDENT>return cluster.KMeans(k, random_state=random_state).fit_predict(diff_potential)<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.NotFittedError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>
KMeans on the PHATE potential Clustering on the PHATE operator as introduced in Moon et al. This is similar to spectral clustering. Parameters ---------- phate_op : phate.PHATE Fitted PHATE operator k : int, optional (default: 8) Number of clusters random_state : int or None, optional (default: None) Random seed for k-means Returns ------- clusters : np.ndarray Integer array of cluster assignments
f11872:m0
@staticmethod<EOL><INDENT>def get_constraints(model):<DEDENT>
with connection.cursor() as cursor:<EOL><INDENT>return connection.introspection.get_constraints(cursor, model._meta.db_table)<EOL><DEDENT>
Get the indexes on the table using a new cursor.
f11883:c1:m1
def validate_partial_unique(self):
<EOL>unique_idxs = [idx for idx in self._meta.indexes if isinstance(idx, PartialIndex) and idx.unique]<EOL>if unique_idxs:<EOL><INDENT>model_fields = set(f.name for f in self._meta.get_fields(include_parents=True, include_hidden=True))<EOL>for idx in unique_idxs:<EOL><INDENT>where = idx.where<EOL>if not isinstance(where, Q):<EOL><INDENT>raise ImproperlyConfigured(<EOL>'<STR_LIT>' +<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>mentioned_fields = set(idx.fields) | set(query.q_mentioned_fields(where, self.__class__))<EOL>missing_fields = mentioned_fields - model_fields<EOL>if missing_fields:<EOL><INDENT>raise RuntimeError('<STR_LIT>' +<EOL>'<STR_LIT>')<EOL><DEDENT>values = {field_name: getattr(self, field_name) for field_name in mentioned_fields}<EOL>conflict = self.__class__.objects.filter(**values) <EOL>conflict = conflict.filter(where) <EOL>if self.pk:<EOL><INDENT>conflict = conflict.exclude(pk=self.pk) <EOL><DEDENT>if conflict.exists():<EOL><INDENT>raise PartialUniqueValidationError('<STR_LIT>' % (<EOL>self.__class__.__name__,<EOL>'<STR_LIT:U+002CU+0020>'.join(sorted(idx.fields)),<EOL>))<EOL><DEDENT><DEDENT><DEDENT>
Check partial unique constraints on the model and raise ValidationError if any failed. We want to check if another instance already exists with the fields mentioned in idx.fields, but only if idx.where matches. But can't just check for the fields in idx.fields - idx.where may refer to other fields on the current (or other) models. Also can't check for all fields on the current model - should not include irrelevant fields which may hide duplicates. To find potential conflicts, we need to build a queryset which: 1. Filters by idx.fields with their current values on this instance, 2. Filters on idx.where 3. Filters by fields mentioned in idx.where, with their current values on this instance, 4. Excludes current object if it does not match the where condition. Note that step 2 ensures the lookup only looks for conflicts among rows covered by the PartialIndes, and steps 2+3 ensures that the QuerySet is empty if the PartialIndex does not cover the current object.
f11891:c1:m1
def set_name_with_model(self, model):
table_name = model._meta.db_table<EOL>column_names = [model._meta.get_field(field_name).column for field_name, order in self.fields_orders]<EOL>column_names_with_order = [<EOL>(('<STR_LIT>' if order else '<STR_LIT:%s>') % column_name)<EOL>for column_name, (field_name, order) in zip(column_names, self.fields_orders)<EOL>]<EOL>hash_data = [table_name] + column_names_with_order + [self.suffix] + self.name_hash_extra_data()<EOL>self.name = '<STR_LIT>' % (<EOL>table_name[:<NUM_LIT:11>],<EOL>column_names[<NUM_LIT:0>][:<NUM_LIT:7>],<EOL>'<STR_LIT>' % (self._hash_generator(*hash_data), self.suffix),<EOL>)<EOL>assert len(self.name) <= self.max_name_length, (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL>self.check_name()<EOL>
Sets an unique generated name for the index. PartialIndex would like to only override "hash_data = ...", but the entire method must be duplicated for that.
f11892:c0:m6
def q_mentioned_fields(q, model):
query = Query(model)<EOL>where = query._add_q(q, used_aliases=set(), allow_joins=False)[<NUM_LIT:0>]<EOL>return list(sorted(set(expression_mentioned_fields(where))))<EOL>
Returns list of field names mentioned in Q object. Q(a__isnull=True, b=F('c')) -> ['a', 'b', 'c']
f11893:m3
def __eq__(self, other):
if self.__class__ != other.__class__:<EOL><INDENT>return False<EOL><DEDENT>if (self.connector, self.negated) == (other.connector, other.negated):<EOL><INDENT>return self.children == other.children<EOL><DEDENT>return False<EOL>
Copied from Django 2.0 django.utils.tree.Node.__eq__()
f11893:c1:m0
def deconstruct(self):
path = '<STR_LIT>' % (self.__class__.__module__, self.__class__.__name__)<EOL>if path.startswith('<STR_LIT>'):<EOL><INDENT>path = path.replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>args, kwargs = (), {}<EOL>if len(self.children) == <NUM_LIT:1> and not isinstance(self.children[<NUM_LIT:0>], Q):<EOL><INDENT>child = self.children[<NUM_LIT:0>]<EOL>kwargs = {child[<NUM_LIT:0>]: child[<NUM_LIT:1>]}<EOL><DEDENT>else:<EOL><INDENT>args = tuple(self.children)<EOL>if self.connector != self.default:<EOL><INDENT>kwargs = {'<STR_LIT>': self.connector}<EOL><DEDENT><DEDENT>if self.negated:<EOL><INDENT>kwargs['<STR_LIT>'] = True<EOL><DEDENT>return path, args, kwargs<EOL>
Copied from Django 2.0 django.db.models.query_utils.Q.deconstruct()
f11893:c1:m1
def func_():
function
f11896:m4
@classmethod<EOL><INDENT>def classmethod_(cls):<DEDENT>
function decorated by @classmethod
f11896:c0:m0
@decorator_<EOL><INDENT>def decorated_method_(self):<DEDENT>
decorated method
f11896:c0:m1
def method_(self):
method
f11896:c0:m2
@property<EOL><INDENT>def property_(self):<DEDENT>
property
f11896:c0:m3
def fullqualname_py3(obj):
if type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return _fullqualname_builtin_py3(obj)<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return _fullqualname_function_py3(obj)<EOL><DEDENT>elif type(obj).__name__ in ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']:<EOL><INDENT>return obj.__objclass__.__module__ + '<STR_LIT:.>' + obj.__qualname__<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return _fullqualname_method_py3(obj)<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return fullqualname_py3(obj.__self__) + '<STR_LIT:.>' + obj.__name__<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return obj.__name__<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return obj.fget.__module__ + '<STR_LIT:.>' + obj.fget.__qualname__<EOL><DEDENT>elif inspect.isclass(obj):<EOL><INDENT>return obj.__module__ + '<STR_LIT:.>' + obj.__qualname__<EOL><DEDENT>return obj.__class__.__module__ + '<STR_LIT:.>' + obj.__class__.__qualname__<EOL>
Fully qualified name for objects in Python 3.
f11897:m0
def _fullqualname_builtin_py3(obj):
if obj.__module__ is not None:<EOL><INDENT>module = obj.__module__<EOL><DEDENT>else:<EOL><INDENT>if inspect.isclass(obj.__self__):<EOL><INDENT>module = obj.__self__.__module__<EOL><DEDENT>else:<EOL><INDENT>module = obj.__self__.__class__.__module__<EOL><DEDENT><DEDENT>return module + '<STR_LIT:.>' + obj.__qualname__<EOL>
Fully qualified name for 'builtin_function_or_method' objects in Python 3.
f11897:m1
def _fullqualname_function_py3(obj):
if hasattr(obj, "<STR_LIT>"):<EOL><INDENT>qualname = obj.__wrapped__.__qualname__<EOL><DEDENT>else:<EOL><INDENT>qualname = obj.__qualname__<EOL><DEDENT>return obj.__module__ + '<STR_LIT:.>' + qualname<EOL>
Fully qualified name for 'function' objects in Python 3.
f11897:m2
def _fullqualname_method_py3(obj):
if inspect.isclass(obj.__self__):<EOL><INDENT>cls = obj.__self__.__qualname__<EOL><DEDENT>else:<EOL><INDENT>cls = obj.__self__.__class__.__qualname__<EOL><DEDENT>return obj.__self__.__module__ + '<STR_LIT:.>' + cls + '<STR_LIT:.>' + obj.__name__<EOL>
Fully qualified name for 'method' objects in Python 3.
f11897:m3
def fullqualname_py2(obj):
if type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return _fullqualname_builtin_py2(obj)<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return obj.__module__ + '<STR_LIT:.>' + obj.__name__<EOL><DEDENT>elif type(obj).__name__ in ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']:<EOL><INDENT>return (obj.__objclass__.__module__ + '<STR_LIT:.>' +<EOL>obj.__objclass__.__name__ + '<STR_LIT:.>' +<EOL>obj.__name__)<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return _fullqualname_method_py2(obj)<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return fullqualname_py2(obj.__self__) + '<STR_LIT:.>' + obj.__name__<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return obj.__name__<EOL><DEDENT>elif inspect.isclass(obj):<EOL><INDENT>return obj.__module__ + '<STR_LIT:.>' + obj.__name__<EOL><DEDENT>return obj.__class__.__module__ + '<STR_LIT:.>' + obj.__class__.__name__<EOL>
Fully qualified name for objects in Python 2.
f11897:m4
def _fullqualname_builtin_py2(obj):
if obj.__self__ is None:<EOL><INDENT>module = obj.__module__<EOL>qualname = obj.__name__<EOL><DEDENT>else:<EOL><INDENT>if inspect.isclass(obj.__self__):<EOL><INDENT>cls = obj.__self__<EOL><DEDENT>else:<EOL><INDENT>cls = obj.__self__.__class__<EOL><DEDENT>module = cls.__module__<EOL>qualname = cls.__name__ + '<STR_LIT:.>' + obj.__name__<EOL><DEDENT>return module + '<STR_LIT:.>' + qualname<EOL>
Fully qualified name for 'builtin_function_or_method' objects in Python 2.
f11897:m5
def _fullqualname_method_py2(obj):
if obj.__self__ is None:<EOL><INDENT>module = obj.im_class.__module__<EOL>cls = obj.im_class.__name__<EOL><DEDENT>else:<EOL><INDENT>if inspect.isclass(obj.__self__):<EOL><INDENT>module = obj.__self__.__module__<EOL>cls = obj.__self__.__name__<EOL><DEDENT>else:<EOL><INDENT>module = obj.__self__.__class__.__module__<EOL>cls = obj.__self__.__class__.__name__<EOL><DEDENT><DEDENT>return module + '<STR_LIT:.>' + cls + '<STR_LIT:.>' + obj.__func__.__name__<EOL>
Fully qualified name for 'instancemethod' objects in Python 2.
f11897:m6
def create_switch(type, settings, pin):
switch = None<EOL>if type == "<STR_LIT:A>":<EOL><INDENT>group, device = settings.split("<STR_LIT:U+002C>")<EOL>switch = pi_switch.RCSwitchA(group, device)<EOL><DEDENT>elif type == "<STR_LIT:B>":<EOL><INDENT>addr, channel = settings.split("<STR_LIT:U+002C>")<EOL>addr = int(addr)<EOL>channel = int(channel)<EOL>switch = pi_switch.RCSwitchB(addr, channel)<EOL><DEDENT>elif type == "<STR_LIT:C>":<EOL><INDENT>family, group, device = settings.split("<STR_LIT:U+002C>")<EOL>group = int(group)<EOL>device = int(device)<EOL>switch = pi_switch.RCSwitchC(family, group, device)<EOL><DEDENT>elif type == "<STR_LIT:D>":<EOL><INDENT>group, device = settings.split("<STR_LIT:U+002C>")<EOL>device = int(device)<EOL>switch = pi_switch.RCSwitchD(group, device)<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % type)<EOL>sys.exit()<EOL><DEDENT>switch.enableTransmit(pin)<EOL>return switch<EOL>
Create a switch. Args: type: (str): type of the switch [A,B,C,D] settings (str): a comma separted list pin (int): wiringPi pin Returns: switch
f11904:m0
def toggle(switch, command):
if command in ["<STR_LIT>"]:<EOL><INDENT>switch.switchOn()<EOL><DEDENT>if command in ["<STR_LIT>"]:<EOL><INDENT>switch.switchOff()<EOL><DEDENT>
Toggles a switch on or off. Args: switch (switch): a switch command (str): "on" or "off"
f11904:m1
def normalizeCountry(country_str, target="<STR_LIT>", title_case=False):
iso2 = "<STR_LIT>"<EOL>iso3 = "<STR_LIT>"<EOL>raw = "<STR_LIT>"<EOL>if country_str is None:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>if len(country_str) == <NUM_LIT:2>:<EOL><INDENT>cc = countrycode(country_str.upper(), origin=iso2, target=target)<EOL>if not cc:<EOL><INDENT>cc = countrycode(country_str, origin=raw, target=target)<EOL><DEDENT><DEDENT>elif len(country_str) == <NUM_LIT:3>:<EOL><INDENT>cc = countrycode(country_str.upper(), origin=iso3, target=target)<EOL>if not cc:<EOL><INDENT>cc = countrycode(country_str, origin=raw, target=target)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>cc = countrycode(country_str, origin=raw, target=target)<EOL><DEDENT>cc = countrycode(cc, origin=target, target=target) if cc else None<EOL>if not cc:<EOL><INDENT>raise ValueError("<STR_LIT>" % (country_str))<EOL><DEDENT>return cc.title() if title_case else cc<EOL>
Return a normalized name/code for country in ``country_str``. The input can be a code or name, the ``target`` determines output value. 3 character ISO code is the default (iso3c), 'country_name', and 'iso2c' are common also. See ``countrycode.countrycode`` for details and other options. Raises ``ValueError`` if the country is unrecognized.
f11914:m2
def mostCommonItem(lst):
<EOL>lst = [l for l in lst if l]<EOL>if lst:<EOL><INDENT>return max(set(lst), key=lst.count)<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Choose the most common item from the list, or the first item if all items are unique.
f11914:m4
def safeDbUrl(db_url):
url = urlparse(db_url)<EOL>return db_url.replace(url.password, "<STR_LIT>") if url.password else db_url<EOL>
Obfuscates password from a database URL.
f11914:m5
def __init__(self, arg_parser):
super().__init__(arg_parser, cache_files=True, track_images=True)<EOL>eyed3.main.setFileScannerOpts(<EOL>arg_parser, paths_metavar="<STR_LIT>",<EOL>paths_help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>arg_parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>arg_parser.add_argument(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>arg_parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>arg_parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>arg_parser.add_argument(<EOL>"<STR_LIT>", default="<STR_LIT>", choices=("<STR_LIT>", "<STR_LIT>"),<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>self.monitor_proc = None<EOL>
Constructor
f11919:c0:m0
def syncImage(img, current, session):
def _img_str(i):<EOL><INDENT>return "<STR_LIT>" % (i.type, i.description)<EOL><DEDENT>for db_img in current.images:<EOL><INDENT>img_info = (img.type, img.md5, img.size)<EOL>db_img_info = (db_img.type, db_img.md5, db_img.size)<EOL>if db_img_info == img_info:<EOL><INDENT>img = None<EOL>break<EOL><DEDENT>elif (db_img.type == img.type and<EOL>db_img.description == img.description):<EOL><INDENT>if img.md5 != db_img.md5:<EOL><INDENT>current.images.remove(db_img)<EOL>current.images.append(img)<EOL>session.add(current)<EOL>pout(Fg.green("<STR_LIT>") + "<STR_LIT>" + _img_str(img))<EOL><DEDENT>img = None<EOL>break<EOL><DEDENT><DEDENT>if img:<EOL><INDENT>current.images.append(img)<EOL>session.add(current)<EOL>pout(Fg.green("<STR_LIT>") + "<STR_LIT>" + _img_str(img))<EOL><DEDENT>
Add or updated the Image.
f11922:m1
def _run(self):
all_procs = []<EOL>MishMashProc("<STR_LIT:info>", config=self.args.config).start().join(check=True)<EOL>sync = MishMashProc("<STR_LIT>", "<STR_LIT>", "<STR_LIT>", config=self.args.config)if self.args.config.getboolean("<STR_LIT>", "<STR_LIT>", fallback=True) else None<EOL>web = MishMashProc("<STR_LIT>", config=self.args.config)if self.args.config.getboolean("<STR_LIT>", "<STR_LIT>", fallback=True) else None<EOL>unsonic = self._createUnsonic()<EOL>for p in (sync, web, unsonic):<EOL><INDENT>if p:<EOL><INDENT>all_procs.append(p)<EOL>p.start()<EOL><DEDENT><DEDENT>try:<EOL><INDENT>while True:<EOL><INDENT>for proc in all_procs:<EOL><INDENT>proc.join(<NUM_LIT:1>, check=True)<EOL><DEDENT>time.sleep(<NUM_LIT:5>)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>for proc in all_procs:<EOL><INDENT>proc.kill()<EOL><DEDENT><DEDENT>
main
f11923:c2:m0
def run_migrations_offline():
url = config.get_main_option("<STR_LIT>")<EOL>context.configure(<EOL>url=url, target_metadata=target_metadata, literal_binds=True)<EOL>with context.begin_transaction():<EOL><INDENT>context.run_migrations()<EOL><DEDENT>
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
f11928:m0
def run_migrations_online():
connectable = engine_from_config(<EOL>config.get_section(config.config_ini_section),<EOL>prefix='<STR_LIT>',<EOL>poolclass=pool.NullPool)<EOL>with connectable.connect() as connection:<EOL><INDENT>context.configure(<EOL>connection=connection,<EOL>target_metadata=target_metadata,<EOL>render_as_batch=True, <EOL>)<EOL>with context.begin_transaction():<EOL><INDENT>context.run_migrations()<EOL><DEDENT><DEDENT>
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
f11928:m1
def search(session, query):
flat_query = "<STR_LIT>".join(query.split())<EOL>artists = session.query(Artist).filter(<EOL>or_(Artist.name.ilike(f"<STR_LIT>"),<EOL>Artist.name.ilike(f"<STR_LIT>"))<EOL>).all()<EOL>albums = session.query(Album).filter(<EOL>Album.title.ilike(f"<STR_LIT>")).all()<EOL>tracks = session.query(Track).filter(<EOL>Track.title.ilike(f"<STR_LIT>")).all()<EOL>return dict(artists=artists,<EOL>albums=albums,<EOL>tracks=tracks)<EOL>
Naive search of the database for `query`. :return: A dict with keys 'artists', 'albums', and 'tracks'. Each containing a list of the respective ORM type.
f11931:m3
@event.listens_for(Engine, "<STR_LIT>")<EOL>def set_sqlite_pragma(dbapi_connection, connection_record):
import sqlite3<EOL>if dbapi_connection.__class__ is sqlite3.Connection:<EOL><INDENT>cursor = dbapi_connection.cursor()<EOL>cursor.execute("<STR_LIT>")<EOL>cursor.close()<EOL><DEDENT>
Allows foreign keys to work in sqlite.
f11937:m1
def __repr__(self):
attrs = []<EOL>for key in self.__dict__:<EOL><INDENT>if not key.startswith('<STR_LIT:_>'):<EOL><INDENT>attrs.append((key, getattr(self, key)))<EOL><DEDENT><DEDENT>return self.__class__.__name__ + '<STR_LIT:(>' +'<STR_LIT:U+002CU+0020>'.join(x[<NUM_LIT:0>] + '<STR_LIT:=>' + repr(x[<NUM_LIT:1>]) for x in attrs) + '<STR_LIT:)>'<EOL>
Dump the object state and return it as a strings.
f11937:c0:m1
def __init__(self, **kwargs):
if "<STR_LIT>" in kwargs:<EOL><INDENT>self.update(kwargs["<STR_LIT>"])<EOL>del kwargs["<STR_LIT>"]<EOL><DEDENT>super(Track, self).__init__(**kwargs)<EOL>
Along with the column args a ``audio_file`` keyword may be passed for this class to use for initialization.
f11937:c5:m0
@classmethod<EOL><INDENT>def iterall(Class, session, names=None):<DEDENT>
names = set(names if names else [])<EOL>for lib in session.query(Class).filter(Class.id > NULL_LIB_ID).all():<EOL><INDENT>if not names or (lib.name in names):<EOL><INDENT>yield lib<EOL><DEDENT><DEDENT>
Iterate over all Library rows found in `session`. :param names: Optional sequence of names to filter on.
f11937:c8:m2
@contextlib.contextmanager<EOL>def capture_logger(name):
import logging<EOL>logger = logging.getLogger(name)<EOL>try:<EOL><INDENT>import StringIO<EOL>stream = StringIO.StringIO()<EOL><DEDENT>except ImportError:<EOL><INDENT>from io import StringIO<EOL>stream = StringIO()<EOL><DEDENT>handler = logging.StreamHandler(stream)<EOL>logger.addHandler(handler)<EOL>try:<EOL><INDENT>yield stream<EOL><DEDENT>finally:<EOL><INDENT>logger.removeHandler(handler)<EOL><DEDENT>
Context manager to capture a logger output with a StringIO stream.
f11942:m0
def bumpversion(self, part, commit=True, tag=False, message=None,<EOL>allow_dirty=False):
import bumpversion<EOL>args = (<EOL>(['<STR_LIT>'] if self.verbose > <NUM_LIT:1> else []) +<EOL>(['<STR_LIT>'] if allow_dirty else []) +<EOL>(['<STR_LIT>'] if commit else ['<STR_LIT>']) +<EOL>(['<STR_LIT>'] if tag else ['<STR_LIT>']) +<EOL>(['<STR_LIT>', message] if message is not None else []) +<EOL>['<STR_LIT>', part]<EOL>)<EOL>log.debug(<EOL>"<STR_LIT>" % "<STR_LIT:U+0020>".join(a.replace("<STR_LIT:U+0020>", "<STR_LIT>") for a in args))<EOL>with capture_logger("<STR_LIT>") as out:<EOL><INDENT>bumpversion.main(args)<EOL><DEDENT>last_line = out.getvalue().splitlines()[-<NUM_LIT:1>]<EOL>new_version = last_line.replace("<STR_LIT>", "<STR_LIT>")<EOL>return new_version<EOL>
Run bumpversion.main() with the specified arguments, and return the new computed version string.
f11942:c0:m2
@staticmethod<EOL><INDENT>def edit_release_notes():<DEDENT>
from tempfile import mkstemp<EOL>import os<EOL>import shlex<EOL>import subprocess<EOL>text_editor = shlex.split(os.environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>fd, tmp = mkstemp(prefix='<STR_LIT>')<EOL>try:<EOL><INDENT>os.close(fd)<EOL>with open(tmp, '<STR_LIT:w>') as f:<EOL><INDENT>f.write("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>subprocess.check_call(text_editor + [tmp])<EOL>with open(tmp, '<STR_LIT:r>') as f:<EOL><INDENT>changes = "<STR_LIT>".join(<EOL>l for l in f.readlines() if not l.startswith('<STR_LIT:#>'))<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>os.remove(tmp)<EOL><DEDENT>return changes<EOL>
Use the default text $EDITOR to write release notes. If $EDITOR is not set, use 'nano'.
f11942:c1:m2
def buildMutator(items, axes=None, bias=None):
from mutatorMath.objects.bender import Bender<EOL>items = [(Location(loc),obj) for loc, obj in items]<EOL>m = Mutator()<EOL>if axes is not None:<EOL><INDENT>bender = Bender(axes)<EOL>m.setBender(bender)<EOL><DEDENT>else:<EOL><INDENT>bender = noBend<EOL><DEDENT>items = sorted(items)<EOL>if not bias:<EOL><INDENT>bias = biasFromLocations([bender(loc) for loc, obj in items], True)<EOL><DEDENT>else:<EOL><INDENT>bias = bender(bias)<EOL><DEDENT>m.setBias(bias)<EOL>n = None<EOL>ofx = []<EOL>onx = []<EOL>for loc, obj in items:<EOL><INDENT>loc = bender(loc)<EOL>if (loc-bias).isOrigin():<EOL><INDENT>m.setNeutral(obj)<EOL>break<EOL><DEDENT><DEDENT>if m.getNeutral() is None:<EOL><INDENT>raise MutatorError("<STR_LIT>", m)<EOL><DEDENT>for loc, obj in items:<EOL><INDENT>locbent = bender(loc)<EOL>lb = locbent-bias<EOL>if lb.isOrigin(): continue<EOL>if lb.isOnAxis():<EOL><INDENT>onx.append((lb, obj-m.getNeutral()))<EOL><DEDENT>else:<EOL><INDENT>ofx.append((lb, obj-m.getNeutral()))<EOL><DEDENT><DEDENT>for loc, obj in onx:<EOL><INDENT>m.addDelta(loc, obj, punch=False, axisOnly=True)<EOL><DEDENT>for loc, obj in ofx:<EOL><INDENT>m.addDelta(loc, obj, punch=True, axisOnly=True)<EOL><DEDENT>return bias, m<EOL>
Build a mutator with the (location, obj) pairs in items. Determine the bias based on the given locations.
f11943:m1
def getLimits(locations, current, sortResults=True, verbose=False):
limit = {}<EOL>for l in locations:<EOL><INDENT>a, b = current.common(l)<EOL>if a is None:<EOL><INDENT>continue<EOL><DEDENT>for name, value in b.items():<EOL><INDENT>f = a[name]<EOL>if name not in limit:<EOL><INDENT>limit[name] = {}<EOL>limit[name]['<STR_LIT:<>'] = {}<EOL>limit[name]['<STR_LIT:=>'] = {}<EOL>limit[name]['<STR_LIT:>>'] = {}<EOL>if f > <NUM_LIT:0>:<EOL><INDENT>limit[name]['<STR_LIT:>>'] = {<NUM_LIT:0>: [Location()]}<EOL><DEDENT>elif f<<NUM_LIT:0>:<EOL><INDENT>limit[name]['<STR_LIT:<>'] = {<NUM_LIT:0>: [Location()]}<EOL><DEDENT>else:<EOL><INDENT>limit[name]['<STR_LIT:=>'] = {<NUM_LIT:0>: [Location()]}<EOL><DEDENT><DEDENT>if current[name] < value - _EPSILON:<EOL><INDENT>if value not in limit[name]["<STR_LIT:<>"]:<EOL><INDENT>limit[name]["<STR_LIT:<>"][value] = []<EOL><DEDENT>limit[name]["<STR_LIT:<>"][value].append(l)<EOL><DEDENT>elif current[name] > value + _EPSILON:<EOL><INDENT>if value not in limit[name]["<STR_LIT:>>"]:<EOL><INDENT>limit[name]["<STR_LIT:>>"][value] = []<EOL><DEDENT>limit[name]["<STR_LIT:>>"][value].append(l)<EOL><DEDENT>else:<EOL><INDENT>if value not in limit[name]["<STR_LIT:=>"]:<EOL><INDENT>limit[name]["<STR_LIT:=>"][value] = []<EOL><DEDENT>limit[name]["<STR_LIT:=>"][value].append(l)<EOL><DEDENT><DEDENT><DEDENT>if not sortResults:<EOL><INDENT>return limit<EOL><DEDENT>l = {}<EOL>for name, lims in limit.items():<EOL><INDENT>less = []<EOL>more = []<EOL>if lims["<STR_LIT:>>"].keys():<EOL><INDENT>less = sorted(lims["<STR_LIT:>>"].keys())<EOL>lim_min = less[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>lim_min = None<EOL><DEDENT>if lims["<STR_LIT:<>"].keys():<EOL><INDENT>more = sorted(lims["<STR_LIT:<>"].keys())<EOL>lim_max = more[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>lim_max = None<EOL><DEDENT>if lim_min is None and lim_max is not None:<EOL><INDENT>if len(limit[name]['<STR_LIT:=>'])><NUM_LIT:0>:<EOL><INDENT>l[name] = (None, list(limit[name]['<STR_LIT:=>'].keys())[<NUM_LIT:0>], None)<EOL><DEDENT>elif len(more) > <NUM_LIT:1> and len(limit[name]['<STR_LIT:=>'])==<NUM_LIT:0>:<EOL><INDENT>l[name] = (None, more[<NUM_LIT:0>], more[<NUM_LIT:1>])<EOL><DEDENT><DEDENT>elif lim_min is not None and lim_max is None:<EOL><INDENT>if len(limit[name]['<STR_LIT:=>'])><NUM_LIT:0>:<EOL><INDENT>l[name] = (None, limit[name]['<STR_LIT:=>'], None)<EOL><DEDENT>elif len(less) > <NUM_LIT:1> and len(limit[name]['<STR_LIT:=>'])==<NUM_LIT:0>:<EOL><INDENT>l[name] = (less[-<NUM_LIT:2>], less[-<NUM_LIT:1>], None)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if len(limit[name]['<STR_LIT:=>']) > <NUM_LIT:0>:<EOL><INDENT>l[name] = (None, list(limit[name]['<STR_LIT:=>'].keys())[<NUM_LIT:0>], None)<EOL><DEDENT>else:<EOL><INDENT>l[name] = (lim_min, None, lim_max)<EOL><DEDENT><DEDENT><DEDENT>return l<EOL>
Find the projections for each delta in the list of locations, relative to the current location. Return only the dimensions that are relevant for current.
f11943:m2
def setNeutral(self, aMathObject, deltaName="<STR_LIT>"):
self._neutral = aMathObject<EOL>self.addDelta(Location(), aMathObject-aMathObject, deltaName, punch=False, axisOnly=True)<EOL>
Set the neutral object.
f11943:c0:m4
def getNeutral(self):
return self._neutral<EOL>
Get the neutral object.
f11943:c0:m5
def addDelta(self, location, aMathObject, deltaName = None, punch=False, axisOnly=True):
<EOL>if punch:<EOL><INDENT>r = self.getInstance(location, axisOnly=axisOnly)<EOL>if r is not None:<EOL><INDENT>self[location.asTuple()] = aMathObject-r, deltaName<EOL><DEDENT>else:<EOL><INDENT>raise MutatorError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self[location.asTuple()] = aMathObject, deltaName<EOL><DEDENT>
Add a delta at this location. * location: a Location object * mathObject: a math-sensitive object * deltaName: optional string/token * punch: * True: add the difference with the instance value at that location and the delta * False: just add the delta.
f11943:c0:m6
def getAxisNames(self):
s = {}<EOL>for l, x in self.items():<EOL><INDENT>s.update(dict.fromkeys([k for k, v in l], None))<EOL><DEDENT>return set(s.keys())<EOL>
Collect a set of axis names from all deltas.
f11943:c0:m7
def _collectAxisPoints(self):
for l, (value, deltaName) in self.items():<EOL><INDENT>location = Location(l)<EOL>name = location.isOnAxis()<EOL>if name is not None and name is not False:<EOL><INDENT>if name not in self._axes:<EOL><INDENT>self._axes[name] = []<EOL><DEDENT>if l not in self._axes[name]:<EOL><INDENT>self._axes[name].append(l)<EOL><DEDENT><DEDENT><DEDENT>return self._axes<EOL>
Return a dictionary with all on-axis locations.
f11943:c0:m8
def _collectOffAxisPoints(self):
offAxis = {}<EOL>for l, (value, deltaName) in self.items():<EOL><INDENT>location = Location(l)<EOL>name = location.isOnAxis()<EOL>if name is None or name is False:<EOL><INDENT>offAxis[l] = <NUM_LIT:1><EOL><DEDENT><DEDENT>return list(offAxis.keys())<EOL>
Return a dictionary with all off-axis locations.
f11943:c0:m9
def collectLocations(self):
pts = []<EOL>for l, (value, deltaName) in self.items():<EOL><INDENT>pts.append(Location(l))<EOL><DEDENT>return pts<EOL>
Return a dictionary with all objects.
f11943:c0:m10
def _allLocations(self):
l = []<EOL>for locationTuple in self.keys():<EOL><INDENT>l.append(Location(locationTuple))<EOL><DEDENT>return l<EOL>
Return a list of all locations of all objects.
f11943:c0:m11
def getInstance(self, aLocation, axisOnly=False, getFactors=False):
self._collectAxisPoints()<EOL>factors = self.getFactors(aLocation, axisOnly)<EOL>total = None<EOL>for f, item, name in factors:<EOL><INDENT>if total is None:<EOL><INDENT>total = f * item<EOL>continue<EOL><DEDENT>total += f * item<EOL><DEDENT>if total is None:<EOL><INDENT>total = <NUM_LIT:0> * self._neutral<EOL><DEDENT>if getFactors:<EOL><INDENT>return total, factors<EOL><DEDENT>return total<EOL>
Calculate the delta at aLocation. * aLocation: a Location object, expected to be in bent space * axisOnly: * True: calculate an instance only with the on-axis masters. * False: calculate an instance with on-axis and off-axis masters. * getFactors: * True: return a list of the calculated factors.
f11943:c0:m12
def makeInstance(self, aLocation, bend=True):
if bend:<EOL><INDENT>aLocation = self._bender(Location(aLocation))<EOL><DEDENT>if not aLocation.isAmbivalent():<EOL><INDENT>instanceObject = self.getInstance(aLocation-self._bias)<EOL><DEDENT>else:<EOL><INDENT>locX, locY = aLocation.split()<EOL>instanceObject = self.getInstance(locX-self._bias)*(<NUM_LIT:1>,<NUM_LIT:0>)+self.getInstance(locY-self._bias)*(<NUM_LIT:0>,<NUM_LIT:1>)<EOL><DEDENT>return instanceObject+self._neutral<EOL>
Calculate an instance with the right bias and add the neutral. aLocation: expected to be in input space
f11943:c0:m13
def getFactors(self, aLocation, axisOnly=False, allFactors=False):
deltas = []<EOL>aLocation.expand(self.getAxisNames())<EOL>limits = getLimits(self._allLocations(), aLocation)<EOL>for deltaLocationTuple, (mathItem, deltaName) in sorted(self.items()):<EOL><INDENT>deltaLocation = Location(deltaLocationTuple)<EOL>deltaLocation.expand( self.getAxisNames())<EOL>factor = self._accumulateFactors(aLocation, deltaLocation, limits, axisOnly)<EOL>if not (factor-_EPSILON < <NUM_LIT:0> < factor+_EPSILON) or allFactors:<EOL><INDENT>deltas.append((factor, mathItem, deltaName))<EOL><DEDENT><DEDENT>deltas = sorted(deltas, key=itemgetter(<NUM_LIT:0>), reverse=True)<EOL>return deltas<EOL>
Return a list of all factors and math items at aLocation. factor, mathItem, deltaName all = True: include factors that are zero or near-zero
f11943:c0:m14
def _accumulateFactors(self, aLocation, deltaLocation, limits, axisOnly):
relative = []<EOL>deltaAxis = deltaLocation.isOnAxis()<EOL>if deltaAxis is None:<EOL><INDENT>relative.append(<NUM_LIT:1>)<EOL><DEDENT>elif deltaAxis:<EOL><INDENT>deltasOnSameAxis = self._axes.get(deltaAxis, [])<EOL>d = ((deltaAxis, <NUM_LIT:0>),)<EOL>if d not in deltasOnSameAxis:<EOL><INDENT>deltasOnSameAxis.append(d)<EOL><DEDENT>if len(deltasOnSameAxis) == <NUM_LIT:1>:<EOL><INDENT>relative.append(aLocation[deltaAxis] * deltaLocation[deltaAxis])<EOL><DEDENT>else:<EOL><INDENT>factor = self._calcOnAxisFactor(aLocation, deltaAxis, deltasOnSameAxis, deltaLocation)<EOL>relative.append(factor)<EOL><DEDENT><DEDENT>elif not axisOnly:<EOL><INDENT>factor = self._calcOffAxisFactor(aLocation, deltaLocation, limits)<EOL>relative.append(factor)<EOL><DEDENT>if not relative:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>f = None<EOL>for v in relative:<EOL><INDENT>if f is None: f = v<EOL>else:<EOL><INDENT>f *= v<EOL><DEDENT><DEDENT>return f<EOL>
Calculate the factors of deltaLocation towards aLocation,
f11943:c0:m15
def _calcOnAxisFactor(self, aLocation, deltaAxis, deltasOnSameAxis, deltaLocation):
if deltaAxis == "<STR_LIT>":<EOL><INDENT>f = <NUM_LIT:0><EOL>v = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>f = aLocation[deltaAxis]<EOL>v = deltaLocation[deltaAxis]<EOL><DEDENT>i = []<EOL>iv = {}<EOL>for value in deltasOnSameAxis:<EOL><INDENT>iv[Location(value)[deltaAxis]]=<NUM_LIT:1><EOL><DEDENT>i = sorted(iv.keys())<EOL>r = <NUM_LIT:0><EOL>B, M, A = [], [], []<EOL>mA, mB, mM = None, None, None<EOL>for value in i:<EOL><INDENT>if value < f: B.append(value)<EOL>elif value > f: A.append(value)<EOL>else: M.append(value)<EOL><DEDENT>if len(B) > <NUM_LIT:0>:<EOL><INDENT>mB = max(B)<EOL>B.sort()<EOL><DEDENT>if len(A) > <NUM_LIT:0>:<EOL><INDENT>mA = min(A)<EOL>A.sort()<EOL><DEDENT>if len(M) > <NUM_LIT:0>:<EOL><INDENT>mM = min(M)<EOL>M.sort()<EOL><DEDENT>if mM is not None:<EOL><INDENT>if ((f-_EPSILON < v) and (f+_EPSILON > v)) or f==v: r = <NUM_LIT:1><EOL>else: r = <NUM_LIT:0><EOL><DEDENT>elif mB is not None and mA is not None:<EOL><INDENT>if v < mB or v > mA: r = <NUM_LIT:0><EOL>else:<EOL><INDENT>if v == mA:<EOL><INDENT>r = float(f-mB)/(mA-mB)<EOL><DEDENT>else:<EOL><INDENT>r = float(f-mA)/(mB-mA)<EOL><DEDENT><DEDENT><DEDENT>elif mB is None and mA is not None:<EOL><INDENT>if v==A[<NUM_LIT:1>]:<EOL><INDENT>r = float(f-A[<NUM_LIT:0>])/(A[<NUM_LIT:1>]-A[<NUM_LIT:0>])<EOL><DEDENT>elif v == A[<NUM_LIT:0>]:<EOL><INDENT>r = float(f-A[<NUM_LIT:1>])/(A[<NUM_LIT:0>]-A[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>r = <NUM_LIT:0><EOL><DEDENT><DEDENT>elif mB is not None and mA is None:<EOL><INDENT>if v == B[-<NUM_LIT:2>]:<EOL><INDENT>r = float(f-B[-<NUM_LIT:1>])/(B[-<NUM_LIT:2>]-B[-<NUM_LIT:1>])<EOL><DEDENT>elif v == mB:<EOL><INDENT>r = float(f-B[-<NUM_LIT:2>])/(B[-<NUM_LIT:1>]-B[-<NUM_LIT:2>])<EOL><DEDENT>else:<EOL><INDENT>r = <NUM_LIT:0><EOL><DEDENT><DEDENT>return r<EOL>
Calculate the on-axis factors.
f11943:c0:m16
def _calcOffAxisFactor(self, aLocation, deltaLocation, limits):
relative = []<EOL>for dim in limits.keys():<EOL><INDENT>f = aLocation[dim]<EOL>v = deltaLocation[dim]<EOL>mB, M, mA = limits[dim]<EOL>r = <NUM_LIT:0><EOL>if mA is not None and v > mA:<EOL><INDENT>relative.append(<NUM_LIT:0>)<EOL>continue<EOL><DEDENT>elif mB is not None and v < mB:<EOL><INDENT>relative.append(<NUM_LIT:0>)<EOL>continue<EOL><DEDENT>if f < v-_EPSILON:<EOL><INDENT>if mB is None:<EOL><INDENT>if M is not None and mA is not None:<EOL><INDENT>if v == M:<EOL><INDENT>r = (float(max(f,mA)-min(f, mA))/float(max(M,mA)-min(M, mA)))<EOL><DEDENT>else:<EOL><INDENT>r = -(float(max(f,mA)-min(f, mA))/float(max(M,mA)-min(M, mA)) -<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else: r = <NUM_LIT:0><EOL><DEDENT>elif mA is None: r = <NUM_LIT:0><EOL>else: r = float(f-mB)/(mA-mB)<EOL><DEDENT>elif f > v+_EPSILON:<EOL><INDENT>if mB is None: r = <NUM_LIT:0><EOL>elif mA is None:<EOL><INDENT>if M is not None and mB is not None:<EOL><INDENT>if v == M:<EOL><INDENT>r = (float(max(f,mB)-min(f, mB))/(max(mB, M)-min(mB, M)))<EOL><DEDENT>else:<EOL><INDENT>r = -(float(max(f,mB)-min(f, mB))/(max(mB, M)-min(mB, M)) - <NUM_LIT:1>)<EOL><DEDENT><DEDENT>else: r = <NUM_LIT:0><EOL><DEDENT>else: r = float(mA-f)/(mA-mB)<EOL><DEDENT>else: r = <NUM_LIT:1><EOL>relative.append(r)<EOL><DEDENT>f = <NUM_LIT:1><EOL>for i in relative:<EOL><INDENT>f *= i<EOL><DEDENT>return f<EOL>
Calculate the off-axis factors.
f11943:c0:m17
def sortLocations(locations):
onAxis = []<EOL>onAxisValues = {}<EOL>offAxis = []<EOL>offAxis_projecting = []<EOL>offAxis_wild = []<EOL>for l in locations:<EOL><INDENT>if l.isOrigin():<EOL><INDENT>continue<EOL><DEDENT>if l.isOnAxis():<EOL><INDENT>onAxis.append(l)<EOL>for axis in l.keys():<EOL><INDENT>if axis not in onAxisValues:<EOL><INDENT>onAxisValues[axis] = []<EOL><DEDENT>onAxisValues[axis].append(l[axis])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>offAxis.append(l)<EOL><DEDENT><DEDENT>for l in offAxis:<EOL><INDENT>ok = False<EOL>for axis in l.keys():<EOL><INDENT>if axis not in onAxisValues:<EOL><INDENT>continue<EOL><DEDENT>if l[axis] in onAxisValues[axis]:<EOL><INDENT>ok = True<EOL><DEDENT><DEDENT>if ok:<EOL><INDENT>offAxis_projecting.append(l)<EOL><DEDENT>else:<EOL><INDENT>offAxis_wild.append(l)<EOL><DEDENT><DEDENT>return onAxis, offAxis_projecting, offAxis_wild<EOL>
Sort the locations by ranking: 1. all on-axis points 2. all off-axis points which project onto on-axis points these would be involved in master to master interpolations necessary for patching. Projecting off-axis masters have at least one coordinate in common with an on-axis master. 3. non-projecting off-axis points, 'wild' off axis points These would be involved in projecting limits and need to be patched.
f11945:m1
def biasFromLocations(locs, preferOrigin=True):
dims = {}<EOL>locs.sort()<EOL>for l in locs:<EOL><INDENT>for d in l.keys():<EOL><INDENT>if not d in dims:<EOL><INDENT>dims[d] = []<EOL><DEDENT>v = l[d]<EOL>if type(v)==tuple:<EOL><INDENT>dims[d].append(v[<NUM_LIT:0>])<EOL>dims[d].append(v[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>dims[d].append(v)<EOL><DEDENT><DEDENT><DEDENT>candidate = Location()<EOL>for k in dims.keys():<EOL><INDENT>dims[k].sort()<EOL>v = mostCommon(dims[k])<EOL>if dims[k].count(v) > <NUM_LIT:1>:<EOL><INDENT>candidate[k] = mostCommon(dims[k])<EOL><DEDENT><DEDENT>matches = []<EOL>for l in locs:<EOL><INDENT>if candidate == l:<EOL><INDENT>return l<EOL><DEDENT><DEDENT>for l in locs:<EOL><INDENT>ok = True<EOL>for k, v in candidate.items():<EOL><INDENT>if l.get(k)!=v:<EOL><INDENT>ok = False<EOL>break<EOL><DEDENT><DEDENT>if ok:<EOL><INDENT>if not l in matches:<EOL><INDENT>matches.append(l)<EOL><DEDENT><DEDENT><DEDENT>matches.sort()<EOL>if len(matches)><NUM_LIT:0>:<EOL><INDENT>if preferOrigin:<EOL><INDENT>for c in matches:<EOL><INDENT>if c.isOrigin():<EOL><INDENT>return c<EOL><DEDENT><DEDENT><DEDENT>return matches[<NUM_LIT:0>]<EOL><DEDENT>results = {}<EOL>for bias in locs:<EOL><INDENT>rel = []<EOL>for l in locs:<EOL><INDENT>rel.append((l - bias).isOnAxis())<EOL><DEDENT>c = rel.count(False)<EOL>if not c in results:<EOL><INDENT>results[c] = []<EOL><DEDENT>results[c].append(bias)<EOL><DEDENT>if results:<EOL><INDENT>candidates = results[min(results.keys())]<EOL>if preferOrigin:<EOL><INDENT>for c in candidates:<EOL><INDENT>if c.isOrigin():<EOL><INDENT>return c<EOL><DEDENT><DEDENT><DEDENT>candidates.sort()<EOL>return candidates[<NUM_LIT:0>]<EOL><DEDENT>return Location()<EOL>
Find the vector that translates the whole system to the origin.
f11945:m2
def mostCommon(L):
<EOL>SL = sorted((x, i) for i, x in enumerate(L))<EOL>groups = itertools.groupby(SL, key=operator.itemgetter(<NUM_LIT:0>))<EOL>def _auxfun(g):<EOL><INDENT>item, iterable = g<EOL>count = <NUM_LIT:0><EOL>min_index = len(L)<EOL>for _, where in iterable:<EOL><INDENT>count += <NUM_LIT:1><EOL>min_index = min(min_index, where)<EOL><DEDENT>return count, -min_index<EOL><DEDENT>return max(groups, key=_auxfun)[<NUM_LIT:0>]<EOL>
# http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list >>> mostCommon([1, 2, 2, 3]) 2 >>> mostCommon([1, 2, 3]) 1 >>> mostCommon([-1, 2, 3]) -1 >>> mostCommon([-1, -2, -3]) -1 >>> mostCommon([-1, -2, -3, -1]) -1 >>> mostCommon([-1, -1, -2, -2]) -1 >>> mostCommon([0, 0.125, 0.275, 1]) 0 >>> mostCommon([0, 0.1, 0.4, 0.4]) 0.4
f11945:m3
def expand(self, axisNames):
for k in axisNames:<EOL><INDENT>if k not in self:<EOL><INDENT>self[k] = <NUM_LIT:0><EOL><DEDENT><DEDENT>
Expand the location with zero values for all axes in axisNames that aren't filled in the current location. :: >>> l = Location(pop=1) >>> l.expand(['snap', 'crackle']) >>> print(l) <Location crackle:0, pop:1, snap:0 >
f11945:c0:m2
def copy(self):
new = self.__class__()<EOL>new.update(self)<EOL>return new<EOL>
Return a copy of this location. :: >>> l = Location(pop=1, snap=0) >>> l.copy() <Location pop:1, snap:0 >
f11945:c0:m3
def fromTuple(self, locationTuple):
for key, value in locationTuple:<EOL><INDENT>try:<EOL><INDENT>self[key] = float(value)<EOL><DEDENT>except TypeError:<EOL><INDENT>self[key] = tuple([float(v) for v in value])<EOL><DEDENT><DEDENT>
Read the coordinates from a tuple. :: >>> t = (('pop', 1), ('snap', -100)) >>> l = Location() >>> l.fromTuple(t) >>> print(l) <Location pop:1, snap:-100 >
f11945:c0:m4
def asTuple(self):
t = []<EOL>k = sorted(self.keys())<EOL>for key in k:<EOL><INDENT>t.append((key, self[key]))<EOL><DEDENT>return tuple(t)<EOL>
Return the location as a tuple. Sort the dimension names alphabetically. :: >>> l = Location(pop=1, snap=-100) >>> l.asTuple() (('pop', 1), ('snap', -100))
f11945:c0:m5