spateo.tdr ========== .. py:module:: spateo.tdr Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/spateo/tdr/interpolations/index /autoapi/spateo/tdr/models/index /autoapi/spateo/tdr/morphometrics/index /autoapi/spateo/tdr/widgets/index Functions --------- .. autoapisummary:: spateo.tdr.deep_intepretation spateo.tdr.gp_interpolation spateo.tdr.kernel_interpolation spateo.tdr.vtk_interpolation spateo.tdr.ElPiGraph_method spateo.tdr.PrinCurve_method spateo.tdr.SimplePPT_method spateo.tdr.backbone_scc spateo.tdr.construct_backbone spateo.tdr.map_gene_to_backbone spateo.tdr.map_points_to_backbone spateo.tdr.update_backbone spateo.tdr.construct_cells spateo.tdr.construct_pc spateo.tdr.construct_surface spateo.tdr.voxelize_mesh spateo.tdr.voxelize_pc spateo.tdr.construct_align_lines spateo.tdr.construct_arrow spateo.tdr.construct_arrows spateo.tdr.construct_axis_line spateo.tdr.construct_field spateo.tdr.construct_field_streams spateo.tdr.construct_genesis spateo.tdr.construct_genesis_X spateo.tdr.construct_line spateo.tdr.construct_lines spateo.tdr.construct_trajectory spateo.tdr.construct_trajectory_X spateo.tdr.add_model_labels spateo.tdr.center_to_zero spateo.tdr.collect_models spateo.tdr.merge_models spateo.tdr.multiblock2model spateo.tdr.read_model spateo.tdr.rotate_model spateo.tdr.save_model spateo.tdr.scale_model spateo.tdr.translate_model spateo.tdr.cell_directions spateo.tdr.morphofield_gp spateo.tdr.morphofield_sparsevfc spateo.tdr.morphopath spateo.tdr.morphofield_acceleration spateo.tdr.morphofield_curl spateo.tdr.morphofield_curvature spateo.tdr.morphofield_divergence spateo.tdr.morphofield_jacobian spateo.tdr.morphofield_torsion spateo.tdr.morphofield_velocity spateo.tdr.model_morphology spateo.tdr.pc_KDE spateo.tdr.pairwise_shape_similarity spateo.tdr.interactive_box_clip spateo.tdr.interactive_rectangle_clip spateo.tdr.interactive_pick spateo.tdr.overlap_mesh_pick spateo.tdr.overlap_pc_pick spateo.tdr.overlap_pick spateo.tdr.three_d_pick spateo.tdr.interactive_slice spateo.tdr.three_d_slice Package Contents ---------------- .. py:function:: deep_intepretation(source_adata: anndata.AnnData, target_points: Optional[numpy.ndarray] = None, keys: Union[str, list] = None, spatial_key: str = 'spatial', layer: str = 'X', max_iter: int = 1000, data_batch_size: int = 2000, autoencoder_batch_size: int = 50, data_lr: float = 0.0001, autoencoder_lr: float = 0.0001, **kwargs) -> anndata.AnnData Learn a continuous mapping from space to gene expression pattern with the deep neural net model. :param source_adata: AnnData object that contains spatial (numpy.ndarray) in the `obsm` attribute. :param target_points: The spatial coordinates of new data point. If target_coords is None, generate new points based on grid_num. :param keys: Gene list or info list in the `obs` attribute whose interpolate expression across space needs to learned. :param spatial_key: The key in ``.obsm`` that corresponds to the spatial coordinate of each bucket. :param layer: If ``'X'``, uses ``.X``, otherwise uses the representation given by ``.layers[layer]``. :param max_iter: The maximum iteration the network will be trained. :param data_batch_size: The size of the data sample batches to be generated in each iteration. :param autoencoder_batch_size: The size of the auto-encoder training batches to be generated in each iteration. Must be no greater than batch_size. . :param data_lr: The learning rate for network training. :param autoencoder_lr: The learning rate for network training the auto-encoder. Will have no effect if network_dim equal data_dim. :param \*\*kwargs: Additional parameters that will be passed to the training step of the deep neural net. :returns: an anndata object that has interpolated expression. :rtype: interp_adata .. py:function:: gp_interpolation(source_adata: anndata.AnnData, target_points: Optional[numpy.ndarray] = None, keys: Union[str, list] = None, spatial_key: str = 'spatial', layer: str = 'X', training_iter: int = 50, device: str = 'cpu', method: Literal['SVGP', 'ExactGP'] = 'SVGP', batch_size: int = 1024, shuffle: bool = True, inducing_num: int = 512, verbose: bool = True) -> anndata.AnnData Learn a continuous mapping from space to gene expression pattern with the Gaussian Process method. :param source_adata: AnnData object that contains spatial (numpy.ndarray) in the `obsm` attribute. :param target_points: The spatial coordinates of new data point. If target_coords is None, generate new points based on grid_num. :param keys: Gene list or info list in the `obs` attribute whose interpolate expression across space needs to learned. :param spatial_key: The key in ``.obsm`` that corresponds to the spatial coordinate of each bucket. :param layer: If ``'X'``, uses ``.X``, otherwise uses the representation given by ``.layers[layer]``. :param training_iter: Max number of iterations for training. :param device: Equipment used to run the program. You can also set the specified GPU for running. ``E.g.: '0'``. :returns: an anndata object that has interpolated expression. :rtype: interp_adata .. py:function:: kernel_interpolation(source_adata: anndata.AnnData, target_points: Optional[numpy.ndarray] = None, keys: Union[str, list] = None, spatial_key: str = 'spatial', layer: str = 'X', lambda_: float = 0.02, lstsq_method: str = 'scipy', **kwargs) -> anndata.AnnData Learn a continuous mapping from space to gene expression pattern with Kernel method (sparseVFC). :param source_adata: AnnData object that contains spatial (numpy.ndarray) in the `obsm` attribute. :param target_points: The spatial coordinates of new data point. If target_coords is None, generate new points based on grid_num. :param keys: Gene list or info list in the `obs` attribute whose interpolate expression across space needs to learned. :param spatial_key: The key in ``.obsm`` that corresponds to the spatial coordinate of each bucket. :param layer: If ``'X'``, uses ``.X``, otherwise uses the representation given by ``.layers[layer]``. :param lambda_: Represents the trade-off between the goodness of data fit and regularization. Larger Lambda_ put more weights on regularization. :param lstsq_method: The name of the linear least square solver, can be either 'scipy` or `douin`. :param \*\*kwargs: Additional parameters that will be passed to SparseVFC function. :returns: an anndata object that has interpolated expression. :rtype: interp_adata .. py:function:: vtk_interpolation(source_adata: anndata.AnnData, target_points: Optional[numpy.ndarray] = None, keys: Union[str, list] = None, spatial_key: str = 'spatial', layer: str = 'X', radius: Optional[float] = None, n_points: Optional[int] = None, kernel: Literal['shepard', 'gaussian', 'linear'] = 'shepard', null_strategy: Literal[0, 1, 2] = 1, null_value: Union[int, float] = 0) -> anndata.AnnData Learn a continuous mapping from space to gene expression pattern with the method contained in VTK. :param source_adata: AnnData object that contains spatial (numpy.ndarray) in the `obsm` attribute. :param target_points: The spatial coordinates of new data point. If target_coords is None, generate new points based on grid_num. :param keys: Gene list or info list in the `obs` attribute whose interpolate expression across space needs to learned. :param spatial_key: The key in ``.obsm`` that corresponds to the spatial coordinate of each bucket. :param layer: If ``'X'``, uses ``.X``, otherwise uses the representation given by ``.layers[layer]``. :param radius: Set the radius of the point cloud. If you are generating a Gaussian distribution, then this is the standard deviation for each of x, y, and z. :param n_points: Specify the number of points for the source object to hold. If n_points (number of the closest points to use) is set then radius value is ignored. :param kernel: The kernel of interpolations kernel. Available `kernels` are: * `shepard`: vtkShepardKernel is an interpolations kernel that uses the method of Shepard to perform interpolations. The weights are computed as 1/r^p, where r is the distance to a neighbor point within the kernel radius R; and p (the power parameter) is a positive exponent (typically p=2). * `gaussian`: vtkGaussianKernel is an interpolations kernel that simply returns the weights for all points found in the sphere defined by radius R. The weights are computed as: exp(-(s*r/R)^2) where r is the distance from the point to be interpolated to a neighboring point within R. The sharpness s simply affects the rate of fall off of the Gaussian. * `linear`: vtkLinearKernel is an interpolations kernel that averages the contributions of all points in the basis. :param null_strategy: Specify a strategy to use when encountering a "null" point during the interpolations process. Null points occur when the local neighborhood(of nearby points to interpolate from) is empty. * Case 0: an output array is created that marks points as being valid (=1) or null (invalid =0), and the nullValue is set as well * Case 1: the output data value(s) are set to the provided nullValue * Case 2: simply use the closest point to perform the interpolations. :param null_value: see above. :returns: an anndata object that has interpolated expression. :rtype: interp_adata .. py:function:: ElPiGraph_method(X: numpy.ndarray, NumNodes: int = 50, topology: Literal['tree', 'circle', 'curve'] = 'curve', Lambda: float = 0.01, Mu: float = 0.1, alpha: float = 0.0, FinalEnergy: Literal['Base', 'Penalized'] = 'Penalized', **kwargs) -> Tuple[numpy.ndarray, numpy.ndarray] Generate a principal elastic tree. Reference: Albergante et al. (2020), Robust and Scalable Learning of Complex Intrinsic Dataset Geometry via ElPiGraph. :param X: DxN, data matrix list. :param NumNodes: The number of nodes of the principal graph. Use a range of 10 to 100 for ElPiGraph approach. :param topology: The appropriate topology used to fit a principal graph for each dataset. :param Lambda: The attractive strength of edges between nodes (constrains edge lengths) :param Mu: The repulsive strength of a node’s neighboring nodes (constrains angles to be close to harmonic) :param alpha: Branching penalty (penalizes number of branches for the principal tree) :param FinalEnergy: Indicating the final elastic emergy associated with the configuration. Currently it can be “Base” or “Penalized” :param \*\*kwargs: Other parameters used in elpigraph.computeElasticPrincipalTree. For details, please see: https://elpigraph-python.readthedocs.io/en/latest/basics.html :returns: The nodes in the principal tree. edges: The edges between nodes in the principal tree. :rtype: nodes .. py:function:: PrinCurve_method(X: numpy.ndarray, NumNodes: int = 50, epochs: int = 500, lr: float = 0.01, scale_factor: Union[int, float] = 1, **kwargs) -> Tuple[numpy.ndarray, numpy.ndarray] This is the global module that contains principal curve and nonlinear principal component analysis algorithms that work to optimize a line over an entire dataset. Reference: Chen et al. (2016), Constraint local principal curve: Concept, algorithms and applications. :param X: DxN, data matrix list. :param NumNodes: Number of nodes for the construction layers. Defaults to 50. The more complex the curve, the higher this number should be. :param epochs: Number of epochs to train neural network, defaults to 500. :param lr: Learning rate for backprop. Defaults to .01 :param scale_factor: :param \*\*kwargs: Other parameters used in global algorithms. For details, please see: https://github.com/artusoma/prinPy/blob/master/prinpy/glob.py :returns: The nodes in the principal tree. edges: The edges between nodes in the principal tree. :rtype: nodes .. py:function:: SimplePPT_method(X: numpy.ndarray, NumNodes: int = 50, sigma: Optional[Union[float, int]] = 0.1, lam: Optional[Union[float, int]] = 1, metric: str = 'euclidean', nsteps: int = 50, err_cut: float = 0.005, seed: Optional[int] = 1, **kwargs) -> Tuple[numpy.ndarray, numpy.ndarray] Generate a simple principal tree. Reference: Mao et al. (2015), SimplePPT: A simple principal tree algorithm, SIAM International Conference on Data Mining. :param X: DxN, data matrix list. :param NumNodes: The number of nodes of the principal graph. Use a range of 100 to 2000 for PPT approach. :param sigma: Regularization parameter. :param lam: Penalty for the tree length. :param metric: The metric to use to compute distances in high dimensional space. For compatible metrics, check the documentation of sklearn.metrics.pairwise_distances. :param nsteps: Number of steps for the optimisation process. :param err_cut: Stop algorithm if proximity of principal points between iterations less than defined value. :param seed: A numpy random seed. :param \*\*kwargs: Other parameters used in simpleppt.ppt. For details, please see: https://github.com/LouisFaure/simpleppt/blob/main/simpleppt/ppt.py :returns: The nodes in the principal tree. edges: The edges between nodes in the principal tree. :rtype: nodes .. py:function:: backbone_scc(adata: anndata.AnnData, backbone: pyvista.PolyData, genes: Optional[list] = None, adata_nodes_key: str = 'backbone_nodes', backbone_nodes_key: str = 'updated_nodes', key_added: Optional[str] = 'backbone_scc', layer: Optional[str] = None, e_neigh: int = 10, s_neigh: int = 6, cluster_method: Literal['leiden', 'louvain'] = 'leiden', resolution: Optional[float] = None, inplace: bool = True) -> Optional[anndata.AnnData] Spatially constrained clustering (scc) along the backbone. :param adata: The anndata object. :param backbone: The backbone model. :param genes: The list of genes that will be used to subset the data for clustering. If ``genes = None``, all genes will be used. :param adata_nodes_key: The key that corresponds to the nodes in the adata. :param backbone_nodes_key: The key that corresponds to the nodes in the backbone. :param key_added: adata.obs key under which to add the cluster labels. :param layer: The layer that will be used to retrieve data for dimension reduction and clustering. If ``layer = None``, ``.X`` is used. :param e_neigh: the number of nearest neighbor in gene expression space. :param s_neigh: the number of nearest neighbor in physical space. :param cluster_method: the method that will be used to cluster the cells. :param resolution: the resolution parameter of the louvain clustering algorithm. :param inplace: Whether to copy adata or modify it inplace. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` in the ``.obs`` attribute, storing the clustering results. .. py:function:: construct_backbone(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid], spatial_key: Optional[str] = None, nodes_key: str = 'nodes', rd_method: Literal['ElPiGraph', 'SimplePPT', 'PrinCurve'] = 'ElPiGraph', num_nodes: int = 50, color: str = 'gainsboro', **kwargs) -> Tuple[pyvista.PolyData, float, Optional[str]] Organ's backbone construction based on 3D point cloud model. :param model: A point cloud model. :param spatial_key: If spatial_key is None, the spatial coordinates are in model.points, otherwise in model[spatial_key]. :param nodes_key: The key that corresponds to the coordinates of the nodes in the backbone. :param rd_method: The method of constructing a backbone model. Available ``rd_method`` are: * ``'ElPiGraph'``: Generate a principal elastic tree. * ``'SimplePPT'``: Generate a simple principal tree. * ``'PrinCurve'``: This is the global module that contains principal curve and nonlinear principal component analysis algorithms that work to optimize a line over an entire dataset. :param num_nodes: Number of nodes for the backbone model. :param color: Color to use for plotting backbone model. :param \*\*kwargs: Additional parameters that will be passed to ``ElPiGraph_method``, ``SimplePPT_method`` or ``PrinCurve_method`` function. :returns: A three-dims backbone model. backbone_length: The length of the backbone model. plot_cmap: Recommended colormap parameter values for plotting. :rtype: backbone_model .. py:function:: map_gene_to_backbone(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid], tree: pyvista.PolyData, key: Union[str, list], nodes_key: Optional[str] = 'nodes', inplace: bool = False) Find the closest principal tree node to any point in the model through KDTree. :param model: A reconstructed model contains the gene expression label. :param tree: A three-dims principal tree model contains the nodes label. :param key: The key that corresponds to the gene expression. :param nodes_key: The key that corresponds to the coordinates of the nodes in the tree. :param inplace: Updates tree model in-place. :returns: `tree.point_data[key]`, the gene expression array. :rtype: A tree, which contains the following properties .. py:function:: map_points_to_backbone(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid], backbone_model: pyvista.PolyData, nodes_key: str = 'nodes', key_added: Optional[str] = 'nodes', inplace: bool = False, **kwargs) Find the closest principal tree node to any point in the model through KDTree. :param model: The reconstructed model. :param backbone_model: The constructed backbone model. :param nodes_key: The key that corresponds to the coordinates of the nodes in the backbone. :param key_added: The key under which to add the nodes labels. :param inplace: Updates model in-place. :param \*\*kwargs: Additional parameters that will be passed to ``scipy.spatial.KDTree.`` function. :returns: `model.point_data[key_added]`, the nodes labels array. :rtype: A model, which contains the following properties .. py:function:: update_backbone(backbone: pyvista.PolyData, nodes_key: str = 'nodes', key_added: str = 'updated_nodes', select_nodes: Optional[Union[list, numpy.ndarray]] = None, interactive: Optional[bool] = True, model_size: Union[float, list] = 8.0, colormap: str = 'Spectral') -> Union[pyvista.PolyData, pyvista.UnstructuredGrid] Update the bakcbone through interaction or input of selected nodes. :param backbone: The backbone model. :param nodes_key: The key that corresponds to the coordinates of the nodes in the backbone. :param key_added: The key under which to add the labels of new nodes. :param select_nodes: Nodes that need to be retained. :param interactive: Whether to delete useless nodes interactively. When ``interactive`` is True, ``select_nodes`` is invalid. :param model_size: Thickness of backbone. When ``interactive`` is False, ``model_size`` is invalid. :param colormap: Colormap of backbone. When ``interactive`` is False, ``colormap`` is invalid. :returns: The updated backbone model. :rtype: updated_backbone .. py:function:: construct_cells(pc: pyvista.PolyData, cell_size: numpy.ndarray, geometry: Literal['cube', 'sphere', 'ellipsoid'] = 'cube', xyz_scale: tuple = (1, 1, 1), n_scale: tuple = (1, 1), factor: float = 0.5) Reconstructing cells from point clouds. :param pc: A point cloud object, including ``pc.point_data["obs_index"]``. :param geometry: The geometry of generating cells. Available ``geometry`` are: * geometry = ``'cube'`` * geometry = ``'sphere'`` * geometry = ``'ellipsoid'`` :param cell_size: A numpy.ndarray object including the relative radius/length size of each cell. :param xyz_scale: The scale factor for the x-axis, y-axis and z-axis. :param n_scale: The ``squareness`` parameter in the x-y plane adn z axis. Only works if ``geometry = 'ellipsoid'``. :param factor: Scale factor applied to scaling array. :returns: A cells mesh including `ds_glyph.point_data["cell_size"]`, `ds_glyph.point_data["cell_centroid"]` and the data contained in the pc. :rtype: ds_glyph .. py:function:: construct_pc(adata: anndata.AnnData, layer: str = 'X', spatial_key: str = 'spatial', groupby: Union[str, tuple] = None, key_added: str = 'groups', mask: Union[str, int, float, list] = None, colormap: Union[str, list, dict] = 'rainbow', alphamap: Union[float, list, dict] = 1.0) -> Tuple[pyvista.PolyData, Optional[str]] Construct a point cloud model based on 3D coordinate information. :param adata: AnnData object. :param layer: If ``'X'``, uses ``.X``, otherwise uses the representation given by ``.layers[layer]``. :param spatial_key: The key in ``.obsm`` that corresponds to the spatial coordinate of each bucket. :param groupby: The key that stores clustering or annotation information in ``.obs``, a gene name or a list of gene names in ``.var``. :param key_added: The key under which to add the labels. :param mask: The part that you don't want to be displayed. :param colormap: Colors to use for plotting pc. The default colormap is ``'rainbow'``. :param alphamap: The opacity of the colors to use for plotting pc. The default alphamap is ``1.0``. :returns: A point cloud, which contains the following properties: ``pc.point_data[key_added]``, the ``groupby`` information. ``pc.point_data[f'{key_added}_rgba']``, the rgba colors of the ``groupby`` information. ``pc.point_data['obs_index']``, the obs_index of each coordinate in the original adata. plot_cmap: Recommended colormap parameter values for plotting. :rtype: pc .. py:function:: construct_surface(pc: pyvista.PolyData, key_added: str = 'groups', label: str = 'surface', color: Optional[str] = 'gainsboro', alpha: Union[float, int] = 1.0, uniform_pc: bool = False, uniform_pc_alpha: Union[float, int] = 0, cs_method: Literal['pyvista', 'alpha_shape', 'ball_pivoting', 'poisson', 'marching_cube'] = 'marching_cube', cs_args: Optional[dict] = None, nsub: Optional[int] = 3, nclus: int = 20000, smooth: Optional[int] = 3000, scale_distance: Union[float, int, list, tuple] = None, scale_factor: Union[float, int, list, tuple] = None) -> Tuple[Union[pyvista.PolyData, pyvista.UnstructuredGrid, None], pyvista.PolyData, Optional[str]] Surface mesh reconstruction based on 3D point cloud model. :param pc: A point cloud model. :param key_added: The key under which to add the labels. :param label: The label of reconstructed surface mesh model. :param color: Color to use for plotting mesh. The default ``color`` is ``'gainsboro'``. :param alpha: The opacity of the color to use for plotting mesh. The default ``alpha`` is ``0.8``. :param uniform_pc: Generates a uniform point cloud with a larger number of points. :param uniform_pc_alpha: Specify alpha (or distance) value to control output of this filter. :param cs_method: The methods of generating a surface mesh. Available ``cs_method`` are: * ``'pyvista'``: Generate a 3D tetrahedral mesh based on pyvista. * ``'alpha_shape'``: Computes a triangle mesh on the alpha shape algorithm. * ``'ball_pivoting'``: Computes a triangle mesh based on the Ball Pivoting algorithm. * ``'poisson'``: Computes a triangle mesh based on thee Screened Poisson Reconstruction. * ``'marching_cube'``: Computes a triangle mesh based on the marching cube algorithm. :param cs_args: Parameters for various surface reconstruction methods. Available ``cs_args`` are: * ``'pyvista'``: {'alpha': 0} * ``'alpha_shape'``: {'alpha': 2.0} * ``'ball_pivoting'``: {'radii': [1]} * ``'poisson'``: {'depth': 8, 'width'=0, 'scale'=1.1, 'linear_fit': False, 'density_threshold': 0.01} * ``'marching_cube'``: {'levelset': 0, 'mc_scale_factor': 1, 'dist_sample_num': 100} :param nsub: Number of subdivisions. Each subdivision creates 4 new triangles, so the number of resulting triangles is nface*4**nsub where nface is the current number of faces. :param nclus: Number of voronoi clustering. :param smooth: Number of iterations for Laplacian smoothing. :param scale_distance: The distance by which the model is scaled. If ``scale_distance`` is float, the model is scaled same distance along the xyz axis; when the ``scale factor`` is list, the model is scaled along the xyz axis at different distance. If ``scale_distance`` is None, there will be no scaling based on distance. :param scale_factor: The scale by which the model is scaled. If ``scale factor`` is float, the model is scaled along the xyz axis at the same scale; when the ``scale factor`` is list, the model is scaled along the xyz axis at different scales. If ``scale_factor`` is None, there will be no scaling based on scale factor. :returns: A reconstructed surface mesh, which contains the following properties: ``uniform_surf.cell_data[key_added]``, the ``label`` array; ``uniform_surf.cell_data[f'{key_added}_rgba']``, the rgba colors of the ``label`` array. inside_pc: A point cloud, which contains the following properties: ``inside_pc.point_data['obs_index']``, the obs_index of each coordinate in the original adata. ``inside_pc.point_data[key_added]``, the ``groupby`` information. ``inside_pc.point_data[f'{key_added}_rgba']``, the rgba colors of the ``groupby`` information. plot_cmap: Recommended colormap parameter values for plotting. :rtype: uniform_surf .. py:function:: voxelize_mesh(mesh: Union[pyvista.PolyData, pyvista.UnstructuredGrid], voxel_pc: Union[pyvista.PolyData, pyvista.UnstructuredGrid] = None, key_added: str = 'groups', label: str = 'voxel', color: Optional[str] = 'gainsboro', alpha: Union[float, int] = 1.0, smooth: Optional[int] = 200) -> Tuple[Union[pyvista.UnstructuredGrid, Any], Optional[str]] Construct a volumetric mesh based on surface mesh. :param mesh: A surface mesh model. :param voxel_pc: A voxel model which contains the ``voxel_pc.cell_data['obs_index']`` and ``voxel_pc.cell_data[key_added]``. :param key_added: The key under which to add the labels. :param label: The label of reconstructed voxel model. :param color: Color to use for plotting mesh. The default color is ``'gainsboro'``. :param alpha: The opacity of the color to use for plotting model. The default alpha is ``0.8``. :param smooth: The smoothness of the voxel model. :returns: A reconstructed voxel model, which contains the following properties: `voxel_model.cell_data[key_added]`, the `label` array; `voxel_model.cell_data[f'{key_added}_rgba']`, the rgba colors of the `label` array. `voxel_model.cell_data['obs_index']`, the cell labels if not (voxel_pc is None). plot_cmap: Recommended colormap parameter values for plotting. :rtype: voxel_model .. py:function:: voxelize_pc(pc: pyvista.PolyData, voxel_size: Optional[numpy.ndarray] = None) -> pyvista.UnstructuredGrid Voxelize the point cloud. :param pc: A point cloud model. :param voxel_size: The size of the voxelized points. The shape of voxel_size is (pc.n_points, 3). :returns: A voxel model. :rtype: voxel .. py:function:: construct_align_lines(model1_points: numpy.ndarray, model2_points: numpy.ndarray, key_added: str = 'check_alignment', label: Union[str, list, numpy.ndarray] = 'align_mapping', color: Union[str, list, dict, numpy.ndarray] = 'gainsboro', alpha: Union[float, int, list, dict, numpy.ndarray] = 1.0) -> Tuple[pyvista.PolyData, Optional[str]] Construct alignment lines between models after model alignment. :param model1_points: Start location in model1 of the line. :param model2_points: End location in model2 of the line. :param key_added: The key under which to add the labels. :param label: The label of alignment lines model. :param color: Color to use for plotting model. :param alpha: The opacity of the color to use for plotting model. :returns: Alignment lines model. plot_cmap: Recommended colormap parameter values for plotting. :rtype: model .. py:function:: construct_arrow(start_point: Union[list, tuple, numpy.ndarray], direction: Union[list, tuple, numpy.ndarray], arrow_scale: Optional[Union[int, float]] = None, key_added: Optional[str] = 'arrow', label: str = 'arrow', color: str = 'gainsboro', alpha: float = 1.0, **kwargs) -> Tuple[pyvista.PolyData, Optional[str]] Create a 3D arrow model. :param start_point: Start location in [x, y, z] of the arrow. :param direction: Direction the arrow points to in [x, y, z]. :param arrow_scale: Scale factor of the entire object. 'auto' scales to length of direction array. :param key_added: The key under which to add the labels. :param label: The label of arrow model. :param color: Color to use for plotting model. :param alpha: The opacity of the color to use for plotting model. :param \*\*kwargs: Additional parameters that will be passed to ``_construct_arrow`` function. :returns: Arrow model. plot_cmap: Recommended colormap parameter values for plotting. :rtype: model .. py:function:: construct_arrows(start_points: numpy.ndarray, direction: numpy.ndarray = None, arrows_scale: Optional[numpy.ndarray] = None, n_sampling: Optional[Union[int, numpy.ndarray]] = None, sampling_method: str = 'trn', factor: float = 1.0, key_added: Optional[str] = 'arrow', label: Union[str, list, numpy.ndarray] = 'arrows', color: Union[str, list, dict, numpy.ndarray] = 'gainsboro', alpha: Union[float, int, list, dict, numpy.ndarray] = 1.0, **kwargs) -> Tuple[pyvista.PolyData, Optional[str]] Create multiple 3D arrows model. :param start_points: List of Start location in [x, y, z] of the arrows. :param direction: Direction the arrows points to in [x, y, z]. :param arrows_scale: Scale factor of the entire object. :param n_sampling: n_sampling is the number of coordinates to keep after sampling. If there are too many coordinates in start_points, the generated arrows model will be too complex and unsightly, so sampling is used to reduce the number of coordinates. :param sampling_method: The method to sample data points, can be one of ``['trn', 'kmeans', 'random']``. :param factor: Scale factor applied to scaling array. :param key_added: The key under which to add the labels. :param label: The label of arrows models. :param color: Color to use for plotting model. :param alpha: The opacity of the color to use for plotting model. :param \*\*kwargs: Additional parameters that will be passed to ``_construct_arrow`` function. :returns: Arrows model. plot_cmap: Recommended colormap parameter values for plotting. :rtype: model .. py:function:: construct_axis_line(axis_points: numpy.ndarray, key_added: str = 'axis', label: str = 'axis_line', color: str = 'gainsboro', alpha: Union[float, int, list, dict, numpy.ndarray] = 1.0) -> Tuple[pyvista.PolyData, Optional[str]] Construct axis line. :param axis_points: List of points defining an axis. :param key_added: The key under which to add the labels. :param label: The label of axis line model. :param color: Color to use for plotting model. :param alpha: The opacity of the color to use for plotting model. :returns: Axis line model. plot_cmap: Recommended colormap parameter values for plotting. :rtype: axis_line .. py:function:: construct_field(model: pyvista.PolyData, vf_key: str = 'VecFld_morpho', arrows_scale_key: Optional[str] = None, n_sampling: Optional[Union[int, numpy.ndarray]] = None, sampling_method: str = 'trn', factor: float = 1.0, key_added: str = 'v_arrows', label: Union[str, list, numpy.ndarray] = 'vector field', color: Union[str, list, dict, numpy.ndarray] = 'gainsboro', alpha: float = 1.0, **kwargs) -> Tuple[pyvista.PolyData, Optional[str]] Create a 3D vector field arrows model. :param model: A model that provides coordinate information and vector information for constructing vector field models. :param vf_key: The key under which are the vector information. :param arrows_scale_key: The key under which are scale factor of the entire object. :param n_sampling: n_sampling is the number of coordinates to keep after sampling. If there are too many coordinates in start_points, the generated arrows model will be too complex and unsightly, so sampling is used to reduce the number of coordinates. :param sampling_method: The method to sample data points, can be one of ``['trn', 'kmeans', 'random']``. :param factor: Scale factor applied to scaling array. :param key_added: The key under which to add the labels. :param label: The label of arrows models. :param color: Color to use for plotting model. :param alpha: The opacity of the color to use for plotting model. :param \*\*kwargs: Additional parameters that will be passed to ``construct_arrows`` function. :returns: A 3D vector field arrows model. plot_cmap: Recommended colormap parameter values for plotting. .. py:function:: construct_field_streams(model: pyvista.PolyData, vf_key: str = 'VecFld_morpho', source_center: Optional[Tuple[float]] = None, source_radius: Optional[float] = None, tip_factor: Union[int, float] = 10, tip_radius: float = 0.2, key_added: str = 'v_streams', label: Union[str, list, numpy.ndarray] = 'vector field', stream_color: str = 'gainsboro', tip_color: str = 'orangered', alpha: float = 1.0, **kwargs) Integrate a vector field to generate streamlines. :param model: A model that provides coordinate information and vector information for constructing vector field models. :param vf_key: The key under which are the active vector field information. :param source_center: Length 3 tuple of floats defining the center of the source particles. Defaults to the center of the dataset. :param source_radius: Float radius of the source particle cloud. Defaults to one-tenth of the diagonal of the dataset’s spatial extent. :param tip_factor: Scale factor applied to scaling the tips. :param tip_radius: Radius of the tips. :param key_added: The key under which to add the labels. :param label: The label of arrows models. :param stream_color: Color to use for plotting streamlines. :param tip_color: Color to use for plotting tips. :param alpha: The opacity of the color to use for plotting model. :param \*\*kwargs: Additional parameters that will be passed to ``streamlines`` function. :returns: 3D vector field streamlines model. src: The source particles as pyvista.PolyData as well as the streamlines. plot_cmap: Recommended colormap parameter values for plotting. :rtype: streams_model .. py:function:: construct_genesis(adata: anndata.AnnData, fate_key: str = 'fate_morpho', n_steps: int = 100, logspace: bool = False, t_end: Optional[Union[int, float]] = None, key_added: str = 'genesis', label: Optional[Union[str, list, numpy.ndarray]] = None, color: Union[str, list, dict] = 'skyblue', alpha: Union[float, list, dict] = 1.0) -> Tuple[pyvista.MultiBlock, Optional[str]] Reconstruction of cell-level cell developmental change model based on the cell fate prediction results. Here we only need to enter the three-dimensional coordinates of the cells at different developmental stages. :param adata: AnnData object that contains the fate prediction in the ``.uns`` attribute. :param fate_key: The key under which are the active fate information. :param n_steps: The number of times steps fate prediction will take. :param logspace: Whether or to sample time points linearly on log space. If not, the sorted unique set of all times points from all cell states' fate prediction will be used and then evenly sampled up to `n_steps` time points. :param t_end: The length of the time period from which to predict cell state forward or backward over time. :param key_added: The key under which to add the labels. :param label: The label of cell developmental change model. If ``label == None``, the label will be automatically generated. :param color: Color to use for plotting model. :param alpha: The opacity of the color to use for plotting model. :returns: A MultiBlock contains cell models for all stages. plot_cmap: Recommended colormap parameter values for plotting. .. py:function:: construct_genesis_X(stages_X: List[numpy.ndarray], n_spacing: Optional[int] = None, key_added: str = 'genesis', label: Optional[Union[str, list, numpy.ndarray]] = None, color: Union[str, list, dict] = 'skyblue', alpha: Union[float, list, dict] = 1.0) -> Tuple[pyvista.MultiBlock, Optional[str]] Reconstruction of cell-level cell developmental change model based on the cell fate prediction results. Here we only need to enter the three-dimensional coordinates of the cells at different developmental stages. :param stages_X: The three-dimensional coordinates of the cells at different developmental stages. :param n_spacing: Subdivided into ``n_spacing`` time points between two periods. :param key_added: The key under which to add the labels. :param label: The label of cell developmental change model. If ``label == None``, the label will be automatically generated. :param color: Color to use for plotting model. :param alpha: The opacity of the color to use for plotting model. :returns: A MultiBlock contains cell models for all stages. plot_cmap: Recommended colormap parameter values for plotting. .. py:function:: construct_line(start_point: Union[list, tuple, numpy.ndarray], end_point: Union[list, tuple, numpy.ndarray], key_added: Optional[str] = 'line', label: str = 'line', color: str = 'gainsboro', alpha: float = 1.0) -> Tuple[pyvista.PolyData, Optional[str]] Create a 3D line model. :param start_point: Start location in [x, y, z] of the line. :param end_point: End location in [x, y, z] of the line. :param key_added: The key under which to add the labels. :param label: The label of line model. :param color: Color to use for plotting model. :param alpha: The opacity of the color to use for plotting model. :returns: Line model. plot_cmap: Recommended colormap parameter values for plotting. :rtype: model .. py:function:: construct_lines(points: numpy.ndarray, edges: numpy.ndarray, key_added: Optional[str] = 'line', label: Union[str, list, numpy.ndarray] = 'lines', color: Union[str, list, dict] = 'gainsboro', alpha: Union[float, int, list, dict] = 1.0) -> Tuple[pyvista.PolyData, Optional[str]] Create 3D lines model. :param points: List of points. :param edges: The edges between points. :param key_added: The key under which to add the labels. :param label: The label of lines model. :param color: Color to use for plotting model. :param alpha: The opacity of the color to use for plotting model. :returns: Lines model. plot_cmap: Recommended colormap parameter values for plotting. :rtype: model .. py:function:: construct_trajectory(adata: anndata.AnnData, fate_key: str = 'fate_develop', n_sampling: Optional[Union[int, numpy.ndarray]] = None, sampling_method: str = 'trn', key_added: str = 'trajectory', label: Optional[Union[str, list, numpy.ndarray]] = None, tip_factor: Union[int, float] = 5, tip_radius: float = 0.2, trajectory_color: Union[str, list, dict] = 'gainsboro', tip_color: Union[str, list, dict] = 'orangered', alpha: float = 1.0) -> Tuple[Any, Optional[str]] Reconstruction of cell developmental trajectory model based on cell fate prediction. :param adata: AnnData object that contains the fate prediction in the ``.uns`` attribute. :param fate_key: The key under which are the active fate information. :param n_sampling: n_sampling is the number of coordinates to keep after sampling. If there are too many coordinates in start_points, the generated arrows model will be too complex and unsightly, so sampling is used to reduce the number of coordinates. :param sampling_method: The method to sample data points, can be one of ``['trn', 'kmeans', 'random']``. :param key_added: The key under which to add the labels. :param label: The label of trajectory model. :param tip_factor: Scale factor applied to scaling the tips. :param tip_radius: Radius of the tips. :param trajectory_color: Color to use for plotting trajectory model. :param tip_color: Color to use for plotting tips. :param alpha: The opacity of the color to use for plotting model. :returns: 3D cell developmental trajectory model. plot_cmap: Recommended colormap parameter values for plotting. :rtype: trajectory_model .. py:function:: construct_trajectory_X(cells_states: Union[numpy.ndarray, List[numpy.ndarray]], init_states: Optional[numpy.ndarray] = None, n_sampling: Optional[Union[int, numpy.ndarray]] = None, sampling_method: str = 'trn', key_added: str = 'trajectory', label: Optional[Union[str, list, numpy.ndarray]] = None, tip_factor: Union[int, float] = 5, tip_radius: float = 0.2, trajectory_color: Union[str, list, dict] = 'gainsboro', tip_color: Union[str, list, dict] = 'orangered', alpha: Union[float, list, dict] = 1.0) -> Tuple[Any, Optional[str]] Reconstruction of cell developmental trajectory model. :param cells_states: Three-dimensional coordinates of all cells at all times points. :param init_states: Three-dimensional coordinates of all cells at the starting time point. :param n_sampling: n_sampling is the number of coordinates to keep after sampling. If there are too many coordinates in start_points, the generated arrows model will be too complex and unsightly, so sampling is used to reduce the number of coordinates. :param sampling_method: The method to sample data points, can be one of ``['trn', 'kmeans', 'random']``. :param key_added: The key under which to add the labels. :param label: The label of trajectory model. :param tip_factor: Scale factor applied to scaling the tips. :param tip_radius: Radius of the tips. :param trajectory_color: Color to use for plotting trajectory model. :param tip_color: Color to use for plotting tips. :param alpha: The opacity of the color to use for plotting model. :returns: 3D cell developmental trajectory model. plot_cmap: Recommended colormap parameter values for plotting. :rtype: trajectory_model .. py:function:: add_model_labels(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid], labels: numpy.ndarray, key_added: str = 'groups', where: Literal['point_data', 'cell_data'] = 'cell_data', colormap: Union[str, list, dict, numpy.ndarray] = 'rainbow', alphamap: Union[float, list, dict, numpy.ndarray] = 1.0, mask_color: Optional[str] = 'gainsboro', mask_alpha: Optional[float] = 0.0, inplace: bool = False) -> Tuple[Optional[PolyData or UnstructuredGrid], Optional[Union[str]]] Add rgba color to each point of model based on labels. :param model: A reconstructed model. :param labels: An array of labels of interest. :param key_added: The key under which to add the labels. :param where: The location where the label information is recorded in the model. :param colormap: Colors to use for plotting data. :param alphamap: The opacity of the color to use for plotting data. :param mask_color: Color to use for plotting mask information. :param mask_alpha: The opacity of the color to use for plotting mask information. :param inplace: Updates model in-place. :returns: ``model.cell_data[key_added]`` or ``model.point_data[key_added]``, the labels array; ``model.cell_data[f'{key_added}_rgba']`` or ``model.point_data[f'{key_added}_rgba']``, the rgba colors of the labels. plot_cmap: Recommended colormap parameter values for plotting. :rtype: A model, which contains the following properties .. py:function:: center_to_zero(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid], inplace: bool = False) Translate the center point of the model to the (0, 0, 0). :param model: A 3D reconstructed model. :param inplace: Updates model in-place. :returns: Model with center point at (0, 0, 0). :rtype: model_z .. py:function:: collect_models(models: List[PolyData or UnstructuredGrid or DataSet], models_name: Optional[List[str]] = None) -> pyvista.MultiBlock A composite class to hold many data sets which can be iterated over. You can think of MultiBlock like lists or dictionaries as we can iterate over this data structure by index and we can also access blocks by their string name. If the input is a dictionary, it can be iterated in the following ways: >>> blocks = collect_models(models, models_name) >>> for name in blocks.keys(): ... print(blocks[name]) If the input is a list, it can be iterated in the following ways: >>> blocks = collect_models(models) >>> for block in blocks: ... print(block) .. py:function:: merge_models(models: List[PolyData or UnstructuredGrid or DataSet]) -> PolyData or UnstructuredGrid Merge all models in the `models` list. The format of all models must be the same. .. py:function:: multiblock2model(model, message=None) Merge all models in MultiBlock into one model .. py:function:: read_model(filename: str) Read any file type supported by vtk or meshio. :param filename: The string path to the file to read. :returns: Wrapped PyVista dataset. .. py:function:: rotate_model(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid], angle: Union[list, tuple] = (0, 0, 0), rotate_center: Union[list, tuple] = None, inplace: bool = False) -> Union[pyvista.PolyData, pyvista.UnstructuredGrid, None] Rotate the model around the rotate_center. :param model: A 3D reconstructed model. :param angle: Angles in degrees to rotate about the x-axis, y-axis, z-axis. Length 3 list or tuple. :param rotate_center: Rotation center point. The default is the center of the model. Length 3 list or tuple. :param inplace: Updates model in-place. :returns: The rotated model. :rtype: model_r .. py:function:: save_model(model: Union[pyvista.DataSet, pyvista.MultiBlock], filename: str, binary: bool = True, texture: Union[str, numpy.ndarray] = None) Save the pvvista/vtk model to vtk/vtm file. :param model: A reconstructed model. :param filename: Filename of output file. Writer type is inferred from the extension of the filename. If model is a pyvista.MultiBlock object, please enter a filename ending with ``.vtm``; else please enter a filename ending with ``.vtk``. :param binary: If True, write as binary. Otherwise, write as ASCII. Binary files write much faster than ASCII and have a smaller file size. :param texture: Write a single texture array to file when using a PLY file. Texture array must be a 3 or 4 component array with the datatype np.uint8. Array may be a cell array or a point array, and may also be a string if the array already exists in the PolyData. If a string is provided, the texture array will be saved to disk as that name. If an array is provided, the texture array will be saved as 'RGBA' .. py:function:: scale_model(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid], distance: Union[float, int, list, tuple] = None, scale_factor: Union[float, int, list, tuple] = 1, scale_center: Union[list, tuple] = None, inplace: bool = False) -> Union[pyvista.PolyData, pyvista.UnstructuredGrid, None] Scale the model around the center of the model. :param model: A 3D reconstructed model. :param distance: The distance by which the model is scaled. If `distance` is float, the model is scaled same distance along the xyz axis; when the `scale factor` is list, the model is scaled along the xyz axis at different distance. If `distance` is None, there will be no scaling based on distance. :param scale_factor: The scale by which the model is scaled. If `scale factor` is float, the model is scaled along the xyz axis at the same scale; when the `scale factor` is list, the model is scaled along the xyz axis at different scales. If `scale_factor` is None, there will be no scaling based on scale factor. :param scale_center: Scaling center. If `scale factor` is None, the `scale_center` will default to the center of the model. :param inplace: Updates model in-place. :returns: The scaled model. :rtype: model_s .. py:function:: translate_model(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid], distance: Union[list, tuple] = (0, 0, 0), inplace: bool = False) -> Union[pyvista.PolyData, pyvista.UnstructuredGrid, None] Translate the mesh. :param model: A 3D reconstructed model. :param distance: Distance to translate about the x-axis, y-axis, z-axis. Length 3 list or tuple. :param inplace: Updates model in-place. :returns: The translated model. :rtype: model_t .. py:function:: cell_directions(adataA: anndata.AnnData, adataB: anndata.AnnData, layer: str = 'X', genes: Optional[Union[list, numpy.ndarray]] = None, spatial_key: str = 'align_spatial', key_added: str = 'mapping', alpha: float = 0.001, numItermax: int = 200, numItermaxEmd: int = 100000, dtype: str = 'float32', device: str = 'cpu', keep_all: bool = False, inplace: bool = True, **kwargs) -> Tuple[Optional[anndata.AnnData], numpy.ndarray] Obtain the optimal mapping relationship and developmental direction between cells for samples between continuous developmental stages. :param adataA: AnnData object of sample A from continuous developmental stages. :param adataB: AnnData object of sample B from continuous developmental stages. :param layer: If ``'X'``, uses ``.X`` to calculate dissimilarity between spots, otherwise uses the representation given by ``.layers[layer]``. :param genes: Genes used for calculation. If None, use all common genes for calculation. :param spatial_key: The key in ``.obsm`` that corresponds to the spatial coordinate of each cell. :param The key that will be used for the vector field key in ``.uns``.: :param key_added: The key that will be used in ``.obsm``. * ``X_{key_added}``-The ``X_{key_added}`` that will be used for the coordinates of the cell that maps optimally in the next stage. * ``V_{key_added}``-The ``V_{key_added}`` that will be used for the cell developmental directions. :param alpha: Alignment tuning parameter. Note: 0 <= alpha <= 1. When ``alpha = 0`` only the gene expression data is taken into account, while when ``alpha =1`` only the spatial coordinates are taken into account. :param numItermax: Max number of iterations for cg during FGW-OT. :param numItermaxEmd: Max number of iterations for emd during FGW-OT. :param dtype: The floating-point number type. Only ``float32`` and ``float64``. :param device: Equipment used to run the program. You can also set the specified GPU for running. ``E.g.: '0'`` :param keep_all: Whether to retain all the optimal relationships obtained only based on the pi matrix, If ``keep_all`` is False, the optimal relationships obtained based on the pi matrix and the nearest coordinates. :param inplace: Whether to copy adata or modify it inplace. :param \*\*kwargs: Additional parameters that will be passed to ``pairwise_align`` function. :returns: An ``AnnData`` object of sample A is updated/copied with the ``X_{key_added}`` and ``V_{key_added}`` in the ``.obsm`` attribute. A pi metrix. .. py:function:: morphofield_gp(adata: anndata.AnnData, spatial_key: str = 'align_spatial', vf_key: str = 'VecFld_morpho', NX: Optional[numpy.ndarray] = None, grid_num: Optional[List[int]] = None, nonrigid_only: bool = False, inplace: bool = True) -> Optional[anndata.AnnData] Calculating and predicting the vector field during development by the Gaussian Process method. :param adata: AnnData object that contains the cell coordinates of the two states after alignment. :param spatial_key: The key from the ``.obsm`` that corresponds to the spatial coordinates of each cell. :param vf_key: The key in ``.uns`` that corresponds to the reconstructed vector field. :param key_added: The key that will be used for the vector field key in ``.uns``. :param NX: The spatial coordinates of new data point. If NX is None, generate new points based on grid_num. :param grid_num: The number of grids in each dimension for generating the grid velocity. Default is ``[50, 50, 50]``. :param nonrigid_only: If True, only the nonrigid part of the vector field will be calculated. :param inplace: Whether to copy adata or modify it inplace. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` dictionary in the ``.uns`` attribute. The ``key_added`` dictionary which contains: X: Cell coordinates of the current state. V: Developmental direction of the X. grid: Grid coordinates of current state. grid_V: Prediction of developmental direction of the grid. method: The method of learning vector field. Here method == 'gaussian_process'. .. py:function:: morphofield_sparsevfc(adata: anndata.AnnData, spatial_key: str = 'align_spatial', V_key: str = 'V_mapping', key_added: str = 'VecFld_morpho', NX: Optional[numpy.ndarray] = None, grid_num: Optional[List[int]] = None, M: int = 100, lambda_: float = 0.02, lstsq_method: str = 'scipy', min_vel_corr: float = 0.8, restart_num: int = 10, restart_seed: Union[List[int], Tuple[int], numpy.ndarray] = (0, 100, 200, 300, 400), inplace: bool = True, **kwargs) -> Optional[anndata.AnnData] Calculating and predicting the vector field during development by the Kernel method (sparseVFC). :param adata: AnnData object that contains the cell coordinates of the two states after alignment. :param spatial_key: The key from the ``.obsm`` that corresponds to the spatial coordinates of each cell. :param V_key: The key from the ``.obsm`` that corresponds to the developmental direction of each cell. :param key_added: The key that will be used for the vector field key in ``.uns``. :param NX: The spatial coordinates of new data point. If NX is None, generate new points based on grid_num. :param grid_num: The number of grids in each dimension for generating the grid velocity. Default is ``[50, 50, 50]``. :param M: The number of basis functions to approximate the vector field. :param lambda_: Represents the trade-off between the goodness of data fit and regularization. Larger Lambda_ put more weights on regularization. :param lstsq_method: The name of the linear least square solver, can be either ``'scipy'`` or ``'douin'``. :param min_vel_corr: The minimal threshold for the cosine correlation between input velocities and learned velocities to consider as a successful vector field reconstruction procedure. If the cosine correlation is less than this threshold and ``restart_num`` > 1, ``restart_num`` trials will be attempted with different seeds to reconstruct the vector field function. This can avoid some reconstructions to be trapped in some local optimal. :param restart_num: The number of retrials for vector field reconstructions. :param restart_seed: A list of seeds for each retrial. Must be the same length as ``restart_num`` or None. :param inplace: Whether to copy adata or modify it inplace. :param \*\*kwargs: Additional parameters that will be passed to ``SparseVFC`` function. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` dictionary in the ``.uns`` attribute. The ``key_added`` dictionary which contains: X: Current state. valid_ind: The indices of cells that have finite velocity values. X_ctrl: Sample control points of current state. ctrl_idx: Indices for the sampled control points. Y: Velocity estimates in delta t. beta: Parameter of the Gaussian Kernel for the kernel matrix (Gram matrix). V: Prediction of velocity of X. C: Finite set of the coefficients for the P: Posterior probability Matrix of inliers. VFCIndex: Indexes of inliers found by sparseVFC. sigma2: Energy change rate. grid: Grid of current state. grid_V: Prediction of velocity of the grid. iteration: Number of the last iteration. tecr_vec: Vector of relative energy changes rate comparing to previous step. E_traj: Vector of energy at each iteration. method: The method of learning vector field. Here method == 'sparsevfc'. Here the most important results are X, V, grid and grid_V. X: Cell coordinates of the current state. V: Developmental direction of the X. grid: Grid coordinates of current state. grid_V: Prediction of developmental direction of the grid. .. py:function:: morphopath(adata: anndata.AnnData, vf_key: str = 'VecFld_morpho', key_added: str = 'fate_morpho', layer: str = 'X', direction: str = 'forward', interpolation_num: int = 250, t_end: Optional[Union[int, float]] = None, average: bool = False, cores: int = 1, nonrigid_only: bool = False, inplace: bool = True, **kwargs) -> Optional[anndata.AnnData] Prediction of cell developmental trajectory based on reconstructed vector field. :param adata: AnnData object that contains the reconstructed vector field function in the ``.uns`` attribute. :param vf_key: The key in ``.uns`` that corresponds to the reconstructed vector field. :param key_added: The key under which to add the dictionary Fate (includes ``t`` and ``prediction`` keys). :param layer: Which layer of the data will be used for predicting cell fate with the reconstructed vector field function. :param direction: The direction to predict the cell fate. One of the ``forward``, ``backward`` or ``both`` string. :param interpolation_num: The number of uniformly interpolated time points. :param t_end: The length of the time period from which to predict cell state forward or backward over time. :param average: The method to calculate the average cell state at each time step, can be one of ``origin`` or ``trajectory``. If ``origin`` used, the average expression state from the init_cells will be calculated and the fate prediction is based on this state. If ``trajectory`` used, the average expression states of all cells predicted from the vector field function at each time point will be used. If ``average`` is ``False``, no averaging will be applied. :param cores: Number of cores to calculate path integral for predicting cell fate. If cores is set to be > 1, multiprocessing will be used to parallel the fate prediction. :param nonrigid_only: If True, only the nonrigid part of the vector field will be calculated. :param inplace: Whether to copy adata or modify it inplace. :param \*\*kwargs: Additional parameters that will be passed into the ``fate`` function. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` dictionary in the ``.uns`` attribute. The ``key_added`` dictionary which contains: t: The time at which the cell state are predicted. prediction: Predicted cells states at different time points. Row order corresponds to the element order in t. If init_states corresponds to multiple cells, the expression dynamics over time for each cell is concatenated by rows. That is, the final dimension of prediction is (len(t) * n_cells, n_features). n_cells: number of cells; n_features: number of genes or number of low dimensional embeddings. Of note, if the average is set to be True, the average cell state at each time point is calculated for all cells. .. py:function:: morphofield_acceleration(adata: anndata.AnnData, vf_key: str = 'VecFld_morpho', key_added: str = 'acceleration', method: str = 'analytical', nonrigid_only: bool = False, inplace: bool = True) -> Optional[anndata.AnnData] Calculate acceleration for each cell with the reconstructed vector field function. :param adata: AnnData object that contains the reconstructed vector field. :param vf_key: The key in ``.uns`` that corresponds to the reconstructed vector field. :param key_added: The key that will be used for the acceleration key in ``.obs`` and ``.obsm``. :param method: The method that will be used for calculating acceleration field, either ``'analytical'`` or ``'numerical'``. ``'analytical'`` method uses the analytical expressions for calculating acceleration while ``'numerical'`` method uses numdifftools, a numerical differentiation tool, for computing acceleration. ``'analytical'`` method is much more efficient. :param nonrigid_only: If True, only the nonrigid part of the vector field will be calculated. :param inplace: Whether to copy adata or modify it inplace. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` in the ``.obs`` and ``.obsm`` attribute. The ``key_added`` in the ``.obs`` which contains acceleration. The ``key_added`` in the ``.obsm`` which contains acceleration vectors. .. py:function:: morphofield_curl(adata: anndata.AnnData, vf_key: str = 'VecFld_morpho', key_added: str = 'curl', method: str = 'analytical', nonrigid_only: bool = False, inplace: bool = True) -> Optional[anndata.AnnData] Calculate curl for each cell with the reconstructed vector field function. :param adata: AnnData object that contains the reconstructed vector field. :param vf_key: The key in ``.uns`` that corresponds to the reconstructed vector field. :param key_added: The key that will be used for the torsion key in ``.obs``. :param method: The method that will be used for calculating torsion field, either ``'analytical'`` or ``'numerical'``. ``'analytical'`` method uses the analytical expressions for calculating torsion while ``'numerical'`` method uses numdifftools, a numerical differentiation tool, for computing torsion. ``'analytical'`` method is much more efficient. :param nonrigid_only: If True, only the nonrigid part of the vector field will be calculated. :param inplace: Whether to copy adata or modify it inplace. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` in the ``.obs`` and ``.obsm`` attribute. The ``key_added`` in the ``.obs`` which contains magnitude of curl. The ``key_added`` in the ``.obsm`` which contains curl vectors. .. py:function:: morphofield_curvature(adata: anndata.AnnData, vf_key: str = 'VecFld_morpho', key_added: str = 'curvature', formula: int = 2, method: str = 'analytical', nonrigid_only: bool = False, inplace: bool = True) -> Optional[anndata.AnnData] Calculate curvature for each cell with the reconstructed vector field function. :param adata: AnnData object that contains the reconstructed vector field. :param vf_key: The key in ``.uns`` that corresponds to the reconstructed vector field. :param key_added: The key that will be used for the curvature key in ``.obs`` and ``.obsm``. :param formula: Which formula of curvature will be used, there are two formulas, so formula can be either ``{1, 2}``. By default it is 2 and returns both the curvature vectors and the norm of the curvature. The formula one only gives the norm of the curvature. :param method: The method that will be used for calculating curvature field, either ``'analytical'`` or ``'numerical'``. ``'analytical'`` method uses the analytical expressions for calculating curvature while ``'numerical'`` method uses numdifftools, a numerical differentiation tool, for computing curvature. ``'analytical'`` method is much more efficient. :param nonrigid_only: If True, only the nonrigid part of the vector field will be calculated. :param inplace: Whether to copy adata or modify it inplace. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` in the ``.obs`` and ``.obsm`` attribute. The ``key_added`` in the ``.obs`` which contains curvature. The ``key_added`` in the ``.obsm`` which contains curvature vectors. .. py:function:: morphofield_divergence(adata: anndata.AnnData, vf_key: str = 'VecFld_morpho', key_added: str = 'divergence', method: str = 'analytical', vectorize_size: Optional[int] = 1000, nonrigid_only: bool = False, inplace: bool = True) -> Optional[anndata.AnnData] Calculate divergence for each cell with the reconstructed vector field function. :param adata: AnnData object that contains the reconstructed vector field. :param vf_key: The key in ``.uns`` that corresponds to the reconstructed vector field. :param key_added: The key that will be used for the acceleration key in ``.obs`` and ``.obsm``. :param method: The method that will be used for calculating acceleration field, either ``'analytical'`` or ``'numerical'``. ``'analytical'`` method uses the analytical expressions for calculating acceleration while ``'numerical'`` method uses numdifftools, a numerical differentiation tool, for computing acceleration. ``'analytical'`` method is much more efficient. :param vectorize_size: vectorize_size is used to control the number of samples computed in each vectorized batch. * If vectorize_size = 1, there's no vectorization whatsoever. * If vectorize_size = None, all samples are vectorized. :param nonrigid_only: If True, only the nonrigid part of the vector field will be calculated. :param inplace: Whether to copy adata or modify it inplace. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` in the ``.obs`` attribute. The ``key_added`` in the ``.obs`` which contains divergence. .. py:function:: morphofield_jacobian(adata: anndata.AnnData, vf_key: str = 'VecFld_morpho', key_added: str = 'jacobian', method: str = 'analytical', nonrigid_only: bool = False, inplace: bool = True) -> Optional[anndata.AnnData] Calculate jacobian for each cell with the reconstructed vector field function. :param adata: AnnData object that contains the reconstructed vector field. :param vf_key: The key in ``.uns`` that corresponds to the reconstructed vector field. :param key_added: The key that will be used for the jacobian key in ``.obs`` and ``.obsm``. :param method: The method that will be used for calculating jacobian field, either ``'analytical'`` or ``'numerical'``. ``'analytical'`` method uses the analytical expressions for calculating jacobian while ``'numerical'`` method uses numdifftools, a numerical differentiation tool, for computing jacobian. ``'analytical'`` method is much more efficient. :param nonrigid_only: If True, only the nonrigid part of the vector field will be calculated. :param inplace: Whether to copy adata or modify it inplace. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` in the ``.obs`` and ``.uns`` attribute. The ``key_added`` in the ``.obs`` which contains jacobian. The ``key_added`` in the ``.uns`` which contains jacobian tensor. .. py:function:: morphofield_torsion(adata: anndata.AnnData, vf_key: str = 'VecFld_morpho', key_added: str = 'torsion', method: str = 'analytical', nonrigid_only: bool = False, inplace: bool = True) -> Optional[anndata.AnnData] Calculate torsion for each cell with the reconstructed vector field function. :param adata: AnnData object that contains the reconstructed vector field. :param vf_key: The key in ``.uns`` that corresponds to the reconstructed vector field. :param key_added: The key that will be used for the torsion key in ``.obs`` and ``.obsm``. :param method: The method that will be used for calculating torsion field, either ``'analytical'`` or ``'numerical'``. ``'analytical'`` method uses the analytical expressions for calculating torsion while ``'numerical'`` method uses numdifftools, a numerical differentiation tool, for computing torsion. ``'analytical'`` method is much more efficient. :param nonrigid_only: If True, only the nonrigid part of the vector field will be calculated. :param inplace: Whether to copy adata or modify it inplace. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` in the ``.obs`` and ``.uns`` attribute. The ``key_added`` in the ``.obs`` which contains torsion. The ``key_added`` in the ``.uns`` which contains torsion matrix. .. py:function:: morphofield_velocity(adata: anndata.AnnData, vf_key: str = 'VecFld_morpho', key_added: str = 'velocity', nonrigid_only: bool = False, inplace: bool = True) -> Optional[anndata.AnnData] Calculate the velocity for each cell with the reconstructed vector field function. :param adata: AnnData object that contains the reconstructed vector field. :param vf_key: The key in ``.uns`` that corresponds to the reconstructed vector field. :param key_added: The key that will be used for the velocity key in ``.obsm``. :param nonrigid_only: If True, only the nonrigid part of the vector field will be calculated. :param inplace: Whether to copy adata or modify it inplace. :returns: An ``AnnData`` object is updated/copied with the ``key_added`` in the ``.obsm`` attribute which contains velocities. .. py:function:: model_morphology(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid], pc: Optional[PolyData or UnstructuredGrid] = None) -> Dict[str, Union[float, Any]] Return the basic morphological characteristics of model, including model volume, model surface area, volume / surface area ratio,etc. :param model: A reconstructed surface model or volume model. :param pc: A point cloud representing the number of cells. :returns: A dictionary containing the following model morphological features: morphology['Length(x)']: Length (x) of model. morphology['Width(y)']: Width (y) of model. morphology['Height(z)']: Height (z) of model. morphology['Surface_area']: Surface area of model. morphology['Volume']: Volume of model. morphology['V/SA_ratio']: Volume / surface area ratio of model; morphology['cell_density']: Cell density of model. :rtype: morphology .. py:function:: pc_KDE(pc: pyvista.PolyData, key_added: str = 'kde', kernel: str = 'gaussian', bandwidth: float = 1.0, colormap: Union[str, list, dict] = 'hot_r', alphamap: Union[float, list, dict] = 1.0, inplace: bool = False) -> Tuple[Union[pyvista.DataSet, pyvista.PolyData, None], Optional[str]] Calculate the kernel density of a 3D point cloud model. :param pc: A point cloud model. :param key_added: The key under which to add the labels. :param kernel: The kernel to use. Available `kernel` are: * `'gaussian'` * `'tophat'` * `'epanechnikov'` * `'exponential'` * `'linear'` * `'cosine'` :param bandwidth: The bandwidth of the kernel. :param colormap: Colors to use for plotting pcd. The default colormap is `'hot_r'`. :param alphamap: The opacity of the colors to use for plotting pcd. The default alphamap is `1.0`. :param inplace: Updates model in-place. :returns: Reconstructed 3D point cloud, which contains the following properties: `pc[key_added]`, the kernel density. plot_cmap: Recommended colormap parameter values for plotting. :rtype: pc .. py:function:: pairwise_shape_similarity(model1_pcs: numpy.ndarray, model2_pcs: numpy.ndarray, n_subspace: int = 20, m: int = 10, s: int = 5) -> float Calculate the shape similarity of pairwise 3D point cloud models based on the eigenvectors of the 3D point cloud model subspace. References: Hu Xiaotong, Wang Jiandong. Similarity analysis of three-dimensional point cloud based on eigenvector of subspace. :param model1_pcs: The coordinates of the 3D point cloud model1. :param model2_pcs: The coordinates of the 3D point cloud model2. :param n_subspace: The number of subspaces initially divided is ``n_subspace``**3. :param m: The number of eigenvalues contained in the eigenvector is m*s. :param s: The number of eigenvalues contained in the eigenvector is m*s. :returns: Shape similarity score. :rtype: similarity_score .. py:function:: interactive_box_clip(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid, pyvista.MultiBlock], key: str = 'groups', invert: bool = False) -> pyvista.MultiBlock Pick the interested part of a model using a 3D box widget. Only one model can be generated. :param model: Reconstructed 3D model. :param key: The key under which are the labels. :param invert: Flag on whether to flip/invert the pick. :returns: A MultiBlock that contains all models you picked. :rtype: picked_model .. py:function:: interactive_rectangle_clip(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid, pyvista.MultiBlock], key: str = 'groups', model_style: Union[Literal['points', 'surface', 'wireframe'], list] = 'points', model_size: Union[float, list] = 8.0, colormap: str = 'Spectral', invert: bool = False, bg_model=None) -> pyvista.MultiBlock Pick the interested part of a model using a 2D rectangle widget. Multiple models can be generated at the same time. :param model: Reconstructed 3D model. :param key: The key under which are the labels. :param invert: Flag on whether to flip/invert the pick. :param bg_model: A visualization-only background model to help clip our target model. :returns: A MultiBlock that contains all models you picked. :rtype: picked_model .. py:function:: interactive_pick(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid, pyvista.MultiBlock], key: str = 'groups', checkbox_size: int = 27, label_size: int = 12) -> pyvista.MultiBlock Add a checkbox button widget to pick the desired groups through the interactive window and output the picked groups. :param model: Reconstructed 3D model. :param key: The key under which are the groups. :param checkbox_size: The size of the button in number of pixels. :param label_size: The font size of the checkbox labels. :returns: A MultiBlock that contains all models you picked. .. py:function:: overlap_mesh_pick(mesh1: pyvista.PolyData, mesh2: pyvista.PolyData) -> pyvista.PolyData Pick the intersection between two mesh models. :param mesh1: Reconstructed 3D mesh model. :param mesh2: Reconstructed 3D mesh model. :returns: The intersection mesh model. :rtype: select_mesh .. py:function:: overlap_pc_pick(pc: pyvista.PolyData, mesh: pyvista.PolyData) -> [pyvista.PolyData, pyvista.PolyData] Pick the point cloud inside the mesh model and point cloud outside the mesh model. :param pc: Reconstructed 3D point cloud model corresponding to mesh. :param mesh: Reconstructed 3D mesh model. :returns: Point cloud inside the mesh model. outside_pc: Point cloud outside the mesh model. :rtype: inside_pc .. py:function:: overlap_pick(main_mesh: pyvista.PolyData, other_mesh: pyvista.PolyData, main_pc: Optional[pyvista.PolyData] = None, other_pc: Optional[pyvista.PolyData] = None) Add a checkbox button widget to pick the desired groups through the interactive window and output the picked groups. :param main_mesh: Reconstructed 3D mesh model. :param other_mesh: Reconstructed 3D mesh model. :param main_pc: Reconstructed 3D point cloud model corresponding to main_mesh. :param other_pc: Reconstructed 3D point cloud model corresponding to other_mesh. :returns: A MultiBlock that contains all models you picked. .. py:function:: three_d_pick(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid, pyvista.MultiBlock], key: str = 'groups', picked_groups: Union[str, list] = None) -> pyvista.MultiBlock Pick the desired groups. .. py:function:: interactive_slice(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid, pyvista.MultiBlock], key: str = 'groups', method: Literal['axis', 'orthogonal'] = 'axis', axis: Literal['x', 'y', 'z'] = 'x') -> pyvista.MultiBlock Create a slice of the input dataset along a specified axis or create three orthogonal slices through the dataset on the three cartesian planes. :param model: Reconstructed 3D model. :param key: The key under which are the labels. :param method: The methods of slicing a model. Available `method` are: * `'axis'`: Create a slice of the input dataset along a specified axis. * `'orthogonal'`: Create three orthogonal slices through the dataset on the three cartesian planes. :param axis: The axis to generate the slices along. Only works when `method` is 'axis'. :returns: A MultiBlock that contains all models you sliced. :rtype: sliced_model .. py:function:: three_d_slice(model: Union[pyvista.PolyData, pyvista.UnstructuredGrid], method: Literal['axis', 'orthogonal', 'line'] = 'axis', n_slices: int = 10, axis: Literal['x', 'y', 'z'] = 'x', vec: Union[tuple, list] = (1, 0, 0), center: Union[tuple, list] = None) -> Union[pyvista.PolyData, Tuple[pyvista.MultiBlock, pyvista.MultiBlock, pyvista.PolyData]] Create many slices of the input dataset along a specified axis or create three orthogonal slices through the dataset on the three cartesian planes or slice a model along a vector direction perpendicularly. :param model: Reconstructed 3D model. :param method: The methods of slicing a model. Available `method` are: * `'axis'`: Create many slices of the input dataset along a specified axis. * `'orthogonal'`: Create three orthogonal slices through the dataset on the three cartesian planes. This method is usually used interactively without entering a position which slices are taken. * `'line'`: Slice a model along a vector direction perpendicularly. :param n_slices: The number of slices to create along a specified axis. Only works when `method` is 'axis' or 'line'. :param axis: The axis to generate the slices along. Only works when `method` is 'axis'. :param vec: The vector direction. Only works when `method` is 'line'. :param center: A 3-length sequence specifying the position which slices are taken. Defaults to the center of the model. :returns: If method is 'axis' or 'orthogonal', return a MultiBlock that contains all models you sliced; else return a tuple that contains line model, all models you sliced and intersections of slices model and line model.