meshparty package

Subpackages

Submodules

meshparty.iterator module

Mesh Iterator Classes

class meshparty.iterator.LocalViewIterator(mesh, n_points, batch_size=1, order='random', pc_align=False, pc_norm=False, adaptnorm=False, fisheye=False, sample_n_points=None, verbose=False)[source]

Bases: object

Iterator class which samples local views that cover an entire mesh. Each mesh vertex is counted as “covered” if it’s included in at least one local view across the iterator.

meshparty.mesh_filters module

meshparty.mesh_filters.filter_close_to_line(mesh, line_end_pts, line_dist_th, axis=1, endcap_buffer=0, sphere_ends=False, map_to_unmasked=True)[source]

Given a mesh and a line segment defined by two end points, make a filter leaving only those nodes within a certain distance of the line segment in a plane defined by a normal axis (e.g. the y axis defines distances in the xy plane)

Parameters:
  • mesh (meshparty.trimesh_io.Mesh) – Trimesh-like mesh with N vertices

  • line_end_pts (numpy.array) – 2x3 numpy array defining the two end points

  • line_dist_th (numeric) – numeric, distance threshold

  • axis (int) – integer 0-2. Defines which axis is normal to the plane in which distances is computed. optional, default 1 (y-axis).

Returns:

N-length boolean array

Return type:

numpy.array

meshparty.mesh_filters.filter_components_by_size(mesh, min_size=0, max_size=inf, map_to_unmasked=True)[source]

returns a boolean mask for vertices that are part of components in a size range

Parameters:
  • mesh (meshparty.trimesh_io.Mesh) – A Trimesh-like mesh with N vertices

  • min_size (int) – the minimum number of vertices in compoment (default 0)

  • max_size (int) – the maximum number of vertices in compoment (default infinity)

Returns:

N-length boolean array

Return type:

np.array

meshparty.mesh_filters.filter_geodesic_distance(mesh, points, max_distance, max_valid_mapping=inf, map_to_unmasked=True)[source]

Returns a boolean array of mesh points within a max distance of points along the mesh graph.

Parameters:
  • mesh (meshparty.trimesh_io.Mesh) – A Trimesh-like mesh with N vertices

  • points (numpy.array) – An Mx3 array of points in space or M-length array of mesh indices

  • max_distance (float) – Max distance along the mesh graph to include in the filter.

  • max_valid_mapping (float) – If points are used, sets the max distance for valid mesh point mapping.

  • map_to_unmasked (bool) – If True, returns mask in indexing of the Nu-length unmasked mesh.

Returns:

mask – Boolean array with Nu (or N) entries, True where vertices are close to any of the points/indices provided.

Return type:

np.array

meshparty.mesh_filters.filter_largest_component(mesh, map_to_unmasked=True)[source]

returns a boolean mask for vertices that are part of the largest component

Parameters:

mesh (meshparty.trimesh_io.Mesh) – A Trimesh-like mesh with N vertices

Returns:

N-length boolean array

Return type:

np.array

meshparty.mesh_filters.filter_spatial_distance_from_points(mesh, pts, d_max, map_to_unmasked=True)[source]

returns a boolean mask for vertices near a set of points

Parameters:
  • mesh (meshparty.trimesh_io.Mesh) – A Trimesh-like mesh with N vertices

  • pts (numpy.array) – a Kx3 set of points

  • d_max (float) – the maximum distance to points to include (same units as mesh.vertices)

Returns:

N-length boolean array

Return type:

np.array

meshparty.mesh_filters.filter_two_point_distance(mesh, pts_foci, d_pad, indices=None, power=1, map_to_unmasked=True)[source]

Returns a boolean array of mesh points such that the sum of the distance from a point to each of the two foci are less than a constant. The constant is set by the distance between the two foci plus a user-specified padding. Optionally, use other Minkowski-like metrics (i.e. x^n + y^n < d^n where x and y are the distances to the foci.)

Parameters:
  • mesh (meshparty.trimesh_io.Mesh) – A Trimesh-like mesh with N vertices

  • pts_foci (numpy.array) – 2x3 array with the two foci in 3d space.

  • d_pad (float) – Extra padding of the threhold distance beyond the distance between foci.

  • indices (iterator) – Instead of pts_foci, one can specify a len(2) list of two indices into the mesh.vertices default None. Will override pts_foci.

  • power (int) – what power to use in Minkowski-like metrics for distance metric.

Returns:

N-length boolean array

Return type:

np.array

meshparty.mesh_skel_utils module

meshparty.mesh_skel_utils.point_to_skel_meshpath(mesh, sk, pt, filterpts=None)[source]

Given a mesh, a skeleton and a point, find the path along the mesh between a point on the mesh and the skeleton (closest skeleton point). If the point is not on the mesh, the point used is the mesh vertex that is closest to the point.

Parameters:
  • mesh (meshparty.trimesh_io.Mesh) – Trimesh-like mesh with N vertices

  • sk (meshparty.trimesh_io.Mesh) – Skeleton whose vertices are a subset of the vertices of mesh

  • pt (1 x 3 numpy.array) – Array specifying a point location

  • filterpts (Bool array) – Filter that was used to generate “mesh”, If “mesh” is a filtered version of the mesh that was used to generate the skeleton “sk”. If sk was generated from mesh as is, then use filter=None.

Returns:

path – Indices of vertices on mesh which trace the path from the point (pt) to the skeleton (sk)

Return type:

int array

meshparty.meshlabserver module

meshparty.meshlabserver.run_meshlab_script(script_name, arg_dict)[source]

Runs meshlabserver script –headless

No X-Server required

Parameters:
  • script_name – str

  • arg_dict – dict [str: str]

meshparty.meshlabserver.run_meshlab_script_on_dir(script_name, in_dir, out_dir, suffix, arg_dict={}, n_threads=1)[source]

meshparty.ray_tracing module

meshparty.skeleton module

class meshparty.skeleton.Skeleton(vertices, edges, root=None, radius=None, mesh_to_skel_map=None, mesh_index=None, vertex_properties={}, node_mask=None, voxel_scaling=None, remove_zero_length_edges=True, skeleton_index=None, meta={})[source]

Bases: object

property SkeletonIndex
apply_mask(new_mask, in_place=False)[source]
property branch_points

Indices of branch points on the skeleton (pottentially including root)

Type:

numpy.array

property branch_points_undirected
child_nodes(vinds)[source]

Get a list of all immediate children of list of indices

Parameters:

vinds (Collection of ints) – Collection of vertex indices

Returns:

A list whose ith element is the children of the ith element of vinds.

Return type:

List of arrays

copy()[source]
property cover_paths

List of numpy.array objects with self.n_end_points elements, each a rootward path (ordered set of indices) starting from an endpoint and continuing until it reaches a point on a path earlier on the list. Paths are ordered by end point distance from root, starting with the most distal. When traversed from begining to end, gives the longest rootward path down each major branch first. When traversed from end to begining, guarentees every branch point is visited at the end of all its downstream paths before being traversed along a path.

Type:

list

cover_paths_specific(end_points, include_parent=False)[source]

Compute nonoverlapping paths from specified endpoints

Parameters:

end_points (array-like) – Array of skeleton vertices to use as end points

Returns:

List of cover paths using the specified end points. Note that this is not sorted in the same order (or necessarily the same length) as specified end points.

Return type:

array

cover_paths_with_parent()[source]

Compute minimally overlapping paths toward root, including a single parent vertex where the path originates.

property csgraph
property csgraph_binary
property csgraph_binary_undirected
property csgraph_undirected
cut_graph(vinds, directed=True, euclidean_weight=True)[source]

Return a csgraph for the skeleton with specified vertices cut off from their parent vertex.

Parameters:
  • vinds – Collection of indices to cut off from their parent.

  • directed (bool, optional) – Return the graph as directed, by default True

  • euclidean_weight (bool, optional) – Return the graph with euclidean weights, by default True. If false, the unweighted.

Returns:

Graph with vertices in vinds cutt off from parents.

Return type:

scipy.sparse.csr.csr_matrix

property distance_to_root

Distance to root (even if root is not in the mask)

downstream_nodes(vinds, inclusive=True)[source]

Get a list of all nodes downstream of a collection of indices

Parameters:

vinds (Collection of ints) – Collection of vertex indices

Returns:

List whose ith element is an array of all vertices downstream of the ith element of vinds.

Return type:

List of arrays

property edges
property end_points

Indices of end points on the skeleton (pottentially including root)

Type:

numpy.array

property end_points_undirected

End points without skeleton orientation, including root and disconnected components.

export_to_swc(filename, node_labels=None, radius=None, header=None, xyz_scaling=1000, resample_spacing=None, interp_kind='linear', tip_length_ratio=0.5, avoid_root=True)[source]

Export a skeleton file to an swc file (see http://research.mssm.edu/cnic/swc.html for swc definition)

Parameters:
  • filename (str) – Name of the file to save the swc to

  • node_labels (np.array) – None (default) or an interable of ints co-indexed with vertices. Corresponds to the swc node categories. Defaults to setting all odes to label 3, dendrite.

  • radius (iterable) – None (default) or an iterable of floats. This should be co-indexed with vertices. Radius values are assumed to be in the same units as the node vertices.

  • header (dict) – default None. Each key value pair in the dict becomes a parameter line in the swc header.

  • xyz_scaling (Number) – default 1000. Down-scales spatial units from the skeleton’s units to whatever is desired by the swc. E.g. nm to microns has scaling=1000.

filter_unmasked_boolean(unmasked_boolean)[source]

For an unmasked boolean slice, returns a boolean slice filtered to the masked mesh

Parameters:

unmasked_boolean (np.array) – a bool array in the original mesh index space

Returns:

returns the elements of unmasked_boolean that are still relevant in the masked index space

Return type:

np.array

filter_unmasked_indices(unmasked_shape, mask=None)[source]

filters a set of indices in the original mesh space and returns it in the masked space

Parameters:
  • unmasked_shape (np.array) – a set of indices into vertices in the unmasked index space

  • mask (np.array or None) – the mask to apply. default None will use this Mesh node_mask

Returns:

the unmasked_shape indices mapped into the masked index space

Return type:

np.array

filter_unmasked_indices_padded(unmasked_shape, mask=None)[source]

filters a set of indices in the original mesh space and returns it in the masked space

Parameters:
  • unmasked_shape (np.array) – a set of indices into vertices in the unmasked index space

  • mask (np.array or None) – the mask to apply. default None will use this Mesh node_mask

Returns:

the unmasked_shape indices mapped into the masked index space, with -1 where the original index did not map into the masked mesh.

Return type:

np.array

property hops_to_root
property indices_unmasked

Gets the indices of nodes in the filtered mesh in the unmasked index array

Type:

np.array

property kdtree

k-D tree from scipy.spatial.

Type:

scipy.spatial.kdtree

map_boolean_to_unmasked(unmapped_boolean)[source]

For a boolean index in the masked indices, returns the corresponding unmasked boolean index

Parameters:

unmapped_boolean (np.array) – a bool array in the masked index space

Returns:

a bool array in the original index space. Is True if the unmapped_boolean suggests it should be.

Return type:

np.array

map_indices_to_unmasked(unmapped_indices)[source]

For a set of masked indices, returns the corresponding unmasked indices

Parameters:

unmapped_indices (np.array) – a set of indices in the masked index space

Returns:

the indices mapped back to the original mesh index space

Return type:

np.array

mask_from_indices(mask_indices)[source]
property mesh_index
property mesh_to_skel_map

N_mesh length array giving the associated skeleton vertex for each mesh vertex

Type:

numpy.array

property mesh_to_skel_map_base

N_mesh length array giving the associated skeleton vertex for each mesh vertex

Type:

numpy.array

property meta
property n_branch_points
property n_end_points
property n_vertices

Number of vertices in the skeleton

Type:

int

property node_mask
parent_nodes(vinds)[source]

Get a list of parent nodes for specified vertices

Parameters:

vinds (Collection of ints) – Collection of vertex indices

Returns:

The parent node of each vertex index in vinds.

Return type:

numpy.array

path_between(s_ind, t_ind)[source]
path_length(paths=None)[source]

Returns the length of a path (described as an ordered collection of connected indices) :param path: :type path: Path or collection of paths, a path being an ordered list of linked vertex indices.

Returns:

Float or list of floats

Return type:

The length of each path.

path_to_root(v_ind)[source]

Path stops if it leaves masked region

property pykdtree
property radius
reroot(new_root)[source]
reset_mask(in_place=False)[source]
property root
property root_position
property segment_map

N set of of indices between 0 and len(self.segments)-1, denoting which segment a given skeleton vertex is in.

Type:

np.array

property segments

A list of numpy.array indicies of segments, paths from each branch or end point (inclusive) to the next rootward branch/root point (exclusive), that cover the skeleton

Type:

list

property segments_plus

A list of array indices of segments, including the segment parent in the next segmetn

Type:

list

property topo_points
property unmasked_size
property vertices
property voxel_scaling
write_to_h5(filename, overwrite=True)[source]

Write the skeleton to an HDF5 file. Note that this is done in the original dimensons, not the scaled dimensions.

Parameters:
  • filename (str) – Filename to save file

  • overwrite (bool, optional) – Flag to specify whether to overwrite existing files, by default True

class meshparty.skeleton.SkeletonMetadata(**kwargs)[source]

Bases: object

cc_vertex_thresh: int = None
collapse_function: str = None
collapse_params: dict = None
collapse_soma: bool = None
compute_radius: bool = None
invalidation_d: float = None
meta: object = None
remove_zero_length_edges: bool = None
root_id: int = None
shape_function: str = None
skeleton_type: str = None
skeletonize_kwargs()[source]
smooth_iterations: int = None
smooth_neighborhood: int = None
smooth_r: float = None
smooth_vertices: bool = None
soma_pt_x: float = None
soma_pt_y: float = None
soma_pt_z: float = None
soma_radius: float = None
timestamp: float = None
update_metameta(metameta)[source]
class meshparty.skeleton.StaticSkeleton(vertices, edges, root=None, radius=None, mesh_to_skel_map=None, mesh_index=None, vertex_properties=None, voxel_scaling=None)[source]

Bases: object

property csgraph
property csgraph_binary
property csgraph_binary_undirected
property csgraph_undirected
property distance_to_root

N length array with the distance to the root node along the skeleton.

Type:

np.array

property edges
property hops_to_root

N length array with the number of hops to the root node along the skeleton.

Type:

np.array

property inverse_voxel_scaling
property mesh_index
property mesh_to_skel_map
property n_vertices

Number of vertices in the skeleton

Type:

int

parent_nodes(vinds)[source]

Get a list of parent nodes for specified vertices

Parameters:

vinds (Collection of ints) – Collection of vertex indices

Returns:

The parent node of each vertex index in vinds.

Return type:

numpy.array

path_to_root(v_ind)[source]

Gives the path to root from a specified vertex.

Parameters:

v_ind (int) – Vertex index

Returns:

numpy.array

Return type:

Ordered set of indices from v_ind to root, inclusive of both.

property radius
reroot(new_root, reset_other_components=False)[source]

Change the skeleton root index.

Parameters:
  • new_root (Int) – Skeleton vertex index to be the new root.

  • reset_other_components (Bool) – Orders non-root components accoring to a local default “root”. Should not often be set to True by a user.

property root

Index of the skeleton root

Type:

int

property vertices
property voxel_scaling
meshparty.skeleton.resample(sk, spacing, kind='linear', tip_length_ratio=0.5, avoid_root=True)[source]

Resample a skeleton’s vertices

Parameters:
  • sk (Skeleton) – Input skeleton file with a skeleton

  • spacing (numeric) – Desired spacing in nanometers

  • kind (str, optional) – Type of interpolation to use when resampling. Options follow scipy.interpolate.interp1d. By default “linear”

  • tip_length_ratio (float, optional) – The ratio of spacing to branch tip length that a branch tip must have in order to be included in the final skeleton for example: spacing is 10 and branch length is 8. do you want to include that final 8 length tip? then perhaps consider a tip_length_ratio of .75, by default 0.25

Returns:

  • Skeleton – New skeleton with resampled vertices.

  • resample_map – Array where the ith index corresponds to the ith vertex of the resampled skeleton and the value is the associated index in the original skeleton. To assign vertices, we assign a “domain” to each vertex in the original skeleton that is halfway between the vertex and its neighbors. Resampled vertices that fall within that domain (based on topology and distance-to-root) are then associated with the original vertex.

meshparty.skeleton_io module

meshparty.skeleton_io.export_to_swc(skel, filename, node_labels=None, radius=None, header=None, xyz_scaling=1000, resample_spacing=None, interp_kind='linear', tip_length_ratio=0.5, avoid_root=True)[source]

Export a skeleton file to an swc file (see http://www.neuronland.org/NLMorphologyConverter/MorphologyFormats/SWC/Spec.html for swc definition)

Parameters:
  • filename (str) – path to the file to save the swc to

  • node_labels (iterable) – None (default) or an interable of ints co-indexed with vertices. Corresponds to the swc node categories. Defaults to setting all nodes to label 3, dendrite.

  • radius (iterable) – None (default) or an iterable of floats. This should be co-indexed with vertices. Radius values are assumed to be in the same units as the node vertices.

  • header (str or list, default None.) – An optional header string for the file. Each element of the list

  • xyz_scaling (Number, default 1000. Down-scales spatial units from the skeleton's units to) – whatever is desired by the swc. E.g. nm to microns has scaling=1000.

meshparty.skeleton_io.read_skeleton_h5(filename, remove_zero_length_edges=False)[source]

Reads a skeleton and its properties from an hdf5 file.

Parameters:
  • filename (str) – path to skeleton file

  • remove_zero_length_edges (bool, optional) – If True, post-processes the skeleton data to removes any zero length edges. Default is False.

Returns:

skeleton object loaded from the h5 file

Return type:

meshparty.skeleton.Skeleton

meshparty.skeleton_io.read_skeleton_h5_by_part(filename)[source]

Helper function for extracting all parts of a skeleton file from an h5.

Parameters:

filename (str) – path to a h5 file with skeletons

Returns:

  • str – filename, path to write

  • np.array – vertices, Nx3 numpy array of vertex locations

  • np.array – edges , Kx2 numpy array of vertex indices for edges

  • np.array – mesh_to_skel_map , M long numpy array. M is the number of vertices in a mesh that this is associated with. The entries are indices into the N skeleton vertices

  • dict – vertex_properties, a dictionary of np.arrays, were keys are descriptive labels and the values are arrays that quantify that label at each vertex examples.. mesh_index) the mesh index of this vertex rs) the sdf (local caliber/thickness) of the mesh at each index

  • int – root, which vertex index is root

  • bool – overwrite, whether to overwrite file

meshparty.skeleton_io.swc_node_labels(sk, dendrite_indices=None, apical_indices=None, soma_indices=None, axon_indices=None, dendrite_default=True)[source]

Assemble swc node labels based on compartment labels. By default, unlabeled indices are considered dendrite.

Parameters:
  • sk (Skeleton) – Neuron skeleton object with N vertices

  • dendrite_indices (array, optional) – Array of indices associated with the dendrites (or basal dendrites if apicals are distinct), by default None.

  • apical_indices (array, optional) – Array of indices (or boolean mask) for the apical dendrite, by default None.

  • soma_indices (array, optional) – Array of indices (or boolean mask) for the soma, by default None.

  • axon_indices (axon, optional) – Array of indices (or boolean mask) for the axon, by default None.

  • dendrite_default (bool, optional,) – If True, assumed unlabeled vertices are dendrite. Otherwise, give a label of 0.

Returns:

N-length vector with the appropriate SWC label for each compartment. Unlabeled vertices are given a default label. Default label is 3 (basal dendrite) if dendrite default is True, else 0.

Return type:

nodelabels

meshparty.skeleton_io.write_skeleton_h5(sk, filename, overwrite=False)[source]

Write a skeleton and its properties to an hdf5 file.

Parameters:
  • sk (meshparty.skeleton.Skeleton) – new_mesh_filt

  • filename (str) – Filename of skeleton file.

  • overwrite (bool) – Allows overwriting.(default False).

meshparty.skeleton_io.write_skeleton_h5_by_part(filename, vertices, edges, meta, mesh_to_skel_map=None, vertex_properties={}, root=None, overwrite=False)[source]

Helper function for writing all parts of a skeleton file to an h5.

Parameters:
  • filename (str) – path to write

  • vertices (np.array) – Nx3 numpy array of vertex locations

  • edges (np.array) – Kx2 numpy array of vertex indices for edges

  • mesh_to_skel_map (np.array) – M long numpy array. M is the number of vertices in a mesh that this is associated with. The entries are indices into the N skeleton vertices

  • vertex_properties (dict) – a dictionary of np.arrays, were keys are descriptive labels and the values are arrays that quantify that label at each vertex examples.. mesh_index) the mesh index of this vertex rs) the sdf (local caliber/thickness) of the mesh at each index

  • root (int) – which vertex index is root

  • overwrite (bool) – whether to overwrite file

meshparty.skeleton_utils module

meshparty.skeleton_utils.assign_windows(des_d, init_d)[source]

Assign desired distances to windows determined from the initial distances for each vertex

meshparty.skeleton_utils.make_windows(input_d)[source]
meshparty.skeleton_utils.resample_path(path, sk, path_counter, spacing, kind, tip_length_ratio, branch_d, avoid_root)[source]

Resample a specific path to get a desired spacing

meshparty.skeletonize module

meshparty.skeletonize.calculate_skeleton_paths_on_mesh(mesh, soma_pt=None, soma_thresh=7500, invalidation_d=10000, smooth_neighborhood=2, smooth_iterations=12, cc_vertex_thresh=100, large_skel_path_threshold=5000, return_map=False, root_index=None)[source]

function to turn a trimesh object of a neuron into a skeleton, without running soma collapse, or recasting result into a Skeleton. Used by meshparty.skeletonize.skeletonize_mesh() and makes use of meshparty.skeletonize.skeletonize_components()

Parameters:
  • mesh (meshparty.trimesh_io.Mesh) – the mesh to skeletonize, defaults assume vertices in nm

  • soma_pt (np.array) – a length 3 array specifying to soma location to make the root default=None, in which case a heuristic root will be chosen in units of mesh vertices

  • soma_thresh (float) – distance in mesh vertex units over which to consider mesh vertices close to soma_pt to belong to soma these vertices will automatically be invalidated and no skeleton branches will attempt to reach them. This distance will also be used to collapse all skeleton points within this distance to the soma_pt root if collpase_soma is true. (default=7500 (nm))

  • invalidation_d (float) – the distance along the mesh to invalidate when applying TEASAR like algorithm. Controls how detailed a structure the skeleton algorithm reaches. default (10000 (nm))

  • smooth_neighborhood (int) – the neighborhood in edge hopes over which to smooth skeleton locations. This controls the smoothing of the skeleton (default 5)

  • large_skel_path_threshold (int) – the threshold in terms of skeleton vertices that skeletons will be nominated for tip merging. Smaller skeleton fragments will not be merged at their tips (default 5000)

  • cc_vertex_thresh (int) – the threshold in terms of vertex numbers that connected components of the mesh will be considered for skeletonization. mesh connected components with fewer than these number of vertices will be ignored by skeletonization algorithm. (default 100)

  • return_map (bool) – whether to return a map of how each mesh vertex maps onto each skeleton vertex based upon how it was invalidated.

  • root_index (int or None) – Mesh vertex to set as initial root node. Overides soma_pt if provided. Default is None.

Returns:

  • skel_verts (np.array) – a Nx3 matrix of skeleton vertex positions

  • skel_edges (np.array) – a Kx2 matrix of skeleton edge indices into skel_verts

  • smooth_verts (np.array) – a Nx3 matrix of vertex positions after smoothing

  • skel_verts_orig (np.array) – a N long index of skeleton vertices in the original mesh vertex index

  • (mesh_to_skeleton_map) (np.array) – a Mx2 map of mesh vertex indices to skeleton vertex indices

meshparty.skeletonize.collapse_soma_skeleton(soma_verts, soma_pt, verts, edges, mesh_to_skeleton_map=None, collapse_index=None, return_filter=False, return_soma_ind=False)[source]

function to adjust skeleton result to move root to soma_pt

Parameters:
  • soma_pt (numpy.array) – a 3 long vector of xyz locations of the soma (None to just remove duplicate )

  • verts (numpy.array) – a Nx3 array of xyz vertex locations

  • edges (numpy.array) – a Kx2 array of edges of the skeleton

  • soma_d_thresh (float) – distance from soma_pt to collapse skeleton nodes

  • mesh_to_skeleton_map (np.array) – a M long array of how each mesh index maps to a skeleton vertex (default None). The function will update this as it collapses vertices to root.

  • soma_mesh_indices (np.array) – a K long array of indices in the mesh that should be considered soma Any skeleton vertex on these vertices will all be collapsed to root.

  • return_filter (bool) – whether to return a list of which skeleton vertices were used in the end for the reduced set of skeleton vertices

  • only_soma_component (bool) – whether to collapse only the skeleton connected component which is closest to the soma_pt (default True)

  • return_soma_ind (bool) – whether to return which skeleton index that is the soma_pt

Returns:

  • np.array – verts, Px3 array of xyz skeleton vertices

  • np.array – edges, Qx2 array of skeleton edges

  • (np.array) – new_mesh_to_skeleton_map, returned if mesh_to_skeleton_map and soma_pt passed

  • (np.array) – used_vertices, if return_filter this contains the indices into the passed verts which the return verts is using

  • int – an index into the returned verts that is the root of the skeleton node, only returned if return_soma_ind is True

meshparty.skeletonize.mesh_teasar(mesh, root=None, valid=None, root_ds=None, root_pred=None, soma_pt=None, soma_thresh=7500, invalidation_d=10000, return_timing=False, return_map=False, exclude_edges_sigma=None)[source]

core skeletonization function used to skeletonize a single component of a mesh

meshparty.skeletonize.reduce_verts(verts, faces)[source]

removes unused vertices from a graph or mesh

Parameters:
  • verts (numpy.array) – NxD numpy array of vertex locations

  • faces (numpy.array) – MxK numpy array of connected shapes (i.e. edges or tris) (entries are indices into verts)

Returns:

  • np.array – new_verts, a filtered set of vertices

  • np.array – new_face, a reindexed set of faces (or edges)

  • np.array – used_verts, the index of the new_verts in the old verts

meshparty.skeletonize.resample(sk, spacing, kind='linear', tip_length_ratio=0.25)[source]

Resample a skeleton’s vertices

Parameters:
  • sk (Skeleton) – Input skeleton file with a skeleton

  • spacing (numeric) – Desired spacing in nanometers

  • kind (str, optional) – Type of interpolation to use when resampling. Options follow scipy.interpolate.interp1d. By default “linear”

  • tip_length_ratio (float, optional) – The ratio of spacing to branch tip length that a branch tip must have in order to be included in the final skeleton for example: spacing is 10 and branch length is 8. do you want to include that final 8 length tip? then perhaps consider a tip_length_ratio of .75, by default 0.25

Returns:

  • Skeleton – New skeleton with resampled vertices.

  • resample_map – Array where the ith index corresponds to the ith vertex of the resampled skeleton and the value is the associated index in the original skeleton. To assign vertices, we assign a “domain” to each vertex in the original skeleton that is halfway between the vertex and its neighbors. Resampled vertices that fall within that domain (based on topology and distance-to-root) are then associated with the original vertex.

meshparty.skeletonize.setup_root(mesh, is_soma_pt=None, soma_d=None, is_valid=None)[source]

function to find the root index to use for this mesh

meshparty.skeletonize.skeletonize_components(mesh, soma_pt=None, soma_thresh=10000, invalidation_d=10000, cc_vertex_thresh=100, return_map=False, root_index=None)[source]

core skeletonization routine, used by meshparty.skeletonize.calculate_skeleton_paths_on_mesh() to calculate skeleton on all components of mesh, with no post processing

meshparty.skeletonize.skeletonize_mesh(mesh, soma_pt=None, soma_radius=7500, collapse_soma=True, collapse_function='sphere', invalidation_d=12000, smooth_vertices=False, compute_radius=True, shape_function='single', compute_original_index=True, verbose=True, smooth_iterations=12, smooth_neighborhood=2, smooth_r=0.1, cc_vertex_thresh=100, root_index=None, remove_zero_length_edges=True, collapse_params={}, meta={})[source]

Build skeleton object from mesh skeletonization

Parameters:
  • mesh (meshparty.trimesh_io.Mesh) – the mesh to skeletonize, defaults assume vertices in nm

  • soma_pt (np.array) – a length 3 array specifying to soma location to make the root default=None, in which case a heuristic root will be chosen in units of mesh vertices.

  • soma_radius (float) – distance in mesh vertex units over which to consider mesh vertices close to soma_pt to belong to soma these vertices will automatically be invalidated and no skeleton branches will attempt to reach them. This distance will also be used to collapse all skeleton points within this distance to the soma_pt root if collpase_soma is true. (default=7500 (nm))

  • collapse_soma (bool) – whether to collapse the skeleton around the soma point (default True)

  • collapse_function ('sphere' or 'branch') – Determines which soma collapse function to use. Sphere uses the soma_radius and collapses all vertices within that radius to the soma. Branch is an experimental approach that tries to compute the right boundary for each branch into soma.

  • invalidation_d (float) – the distance along the mesh to invalidate when applying TEASAR like algorithm. Controls how detailed a structure the skeleton algorithm reaches. default (12000 (nm))

  • smooth_vertices (bool) – whether to smooth the vertices of the skeleton

  • compute_radius (bool) – whether to calculate the radius of the skeleton at each point on the skeleton (default True)

  • shape_function ('single' or 'cone') – Selects how to compute the radius, either with a single ray or a cone of rays. Default is ‘single’.

  • compute_original_index (bool) – whether to calculate how each of the mesh nodes maps onto the skeleton (default True)

  • smooth_iterations (int, optional) – Number of iterations to smooth (default is 12)

  • smooth_neighborhood (int, optional) – Size of neighborhood to look at for smoothing

  • smooth_r (float, optional) – Weight of update step in smoothing algorithm, default is 0.2

  • root_index (int or None, optional) – A precise mesh vertex to use as the skeleton root. If provided, the vertex location overrides soma_pt. By default, None.

  • remove_zero_length_edges (bool) – If True, removes vertices involved in zero length edges, which can disrupt graph computations. Default True.

  • collapse_params (dict) – Extra keyword arguments for the collapse function. See soma_via_sphere and soma_via_branch_starts for specifics.

  • cc_vertex_thresh (int, optional) – Smallest number of vertices in a connected component to skeletonize.

  • verbose (bool) – whether to print verbose logging

  • meta (dict) – Skeletonization metadata to add to the skeleton. See skeleton.SkeletonMetadata for keys.

Returns:

a Skeleton object for this mesh

Return type:

meshparty.skeleton.Skeleton

meshparty.skeletonize.smooth_graph(values, edges, mask=None, neighborhood=2, iterations=100, r=0.1)[source]

smooths a spatial graph via iterative local averaging calculates the average value of neighboring values and relaxes the values toward that average

Parameters:
  • values (numpy.array) – a NxK numpy array of values, for example xyz positions

  • edges (numpy.array) – a Mx2 numpy array of indices into values that are edges

  • mask (numpy.array) – NOT yet implemented optional N boolean vector of values to mask the vert locations. the result will return a result at every vert but the values that are false in this mask will be ignored and not factored into the smoothing.

  • neighborhood (int) – an integer of how far in the graph to relax over as being local to any vertex (default = 2)

  • iterations (int) – number of relaxation iterations (default = 100)

  • r (float) – relaxation factor at each iteration new_vertex = (1-r)*old_vertex*mask + (r+(1-r)*(1-mask))*(local_avg) default = .1

Returns:

new_verts, a Nx3 list of new smoothed vertex positions

Return type:

np.array

meshparty.skeletonize.soma_via_branch_starts(sk, mesh, soma_pt, rs, search_radius=20000, fallback_radius=15000, cutoff_threshold=0.2, min_cutoff=0.1, dynamic_range=1, dynamic_threshold=False)[source]

Runs down paths into the soma region and finds onset of each branch.

meshparty.skeletonize.soma_via_sphere(soma_pt, verts, edges, soma_d_thresh)[source]

Get indices within soma_d_thresh of a soma_pt. Exclude vertices that left and come back.

meshparty.spatial_annotations module

meshparty.spatial_annotations.annotation_location_indices(mesh, anno_df, pos_column, sk_map=None, max_dist=inf, voxel_resolution=array([4, 4, 40]))[source]

For a synapse dataframe associated with a given neuron, find the mesh indices associated with each synapse.

Parameters:
  • mesh – trimesh Mesh

  • synapse_df – DataFrame with at least one position column

  • pos_column – string, column of dataframe to use for annotation positions

  • sk_map – Optional, Numpy array with skeleton vertex index for every mesh vertex index.

  • max_dist – Optional, Maximum distance to the mesh allowed for assignment, else return -1.

  • voxel_resolution – Optional, default is [4,4,40] nm/voxel.

Returns:

Mesh indices and, if desired, skeleton indices.

meshparty.spatial_annotations.annotation_skeleton_segments(sk, anno_df, pos_column, mesh=None, max_dist=inf, voxel_resolution=array([4, 4, 40]), skeleton_index_col_name=None)[source]

Attach skeleton segment index to an annotation dataframe :param sk: Skeleton :param anno_df: Annotation dataframe :param pos_column: String. Column name in dataframe with position values :param mesh: optional, mesh object. Needed if skeleton_index_col_name is not specified. :param max_dist: optional, float. Max distance to mesh for attaching annotations. Default is inf. :param voxel_resolution: optional, length 3 array. Default is [4,4,40] nm/pixel. :param skeleton_index_col_name: optional, string. Column name of skeleton vertex in dataframe.

meshparty.spatial_annotations.axon_split_quality(is_axon, pre_inds, post_inds)[source]

Returns a quality index (0-1, higher is a cleaner split) for split quality, defined as best separating input and output sites.

meshparty.spatial_annotations.find_axon_split_vertex_by_synapse_betweenness(sk, pre_inds, post_inds, return_quality=True, extend_to_segment=True)[source]

Find the skeleton vertex at which to split the axon from the dendrite. Assumes skeleton root is on dendritic side. :param sk: Skeleton :param pre_inds: List of skeleton indices with an input synapse (Duplicate indices with more than one) :param post_inds: List of skeleton indices with an output synapse (Duplicate indices with more than one) :param return_quality: Compute split quality at the split point. Always computer for true split point, not shifted one. :param extend_to_segment: Shift split point to the closest-to-root location on the same segment as the split node. :returns: int, skeleton index :returns: float, optional split quality index.

meshparty.spatial_annotations.skind_to_anno_map(sk, anno_df, pos_column=None, mesh=None, max_dist=inf, voxel_resolution=array([4, 4, 40]), skeleton_index_col_name=None)[source]

Make a dict with key skeleton index and values a list of annotation ids at that index.

meshparty.spatial_annotations.split_axon_by_synapse_betweenness(sk, pre_inds, post_inds, return_quality=True, extend_to_segment=True)[source]

Find the is_axon boolean label for all vertices in the skeleton. Assumes skeleton root is not on the axon side. :param sk: Skeleton :param pre_inds: List of skeleton indices with an input synapse (Duplicate indices with more than one) :param post_inds: List of skeleton indices with an output synapse (Duplicate indices with more than one) :param return_quality: Compute split quality at the split point. Always computer for true split point, not shifted one. :param extend_to_segment: Shift split point to the closest-to-root location on the same segment as the split node. :returns: boolean array, True for axon vertices. :returns: float, optional split quality index.

meshparty.spatial_annotations.synapse_betweenness(sk, pre_inds, post_inds)[source]

Compute synapse betweeness (number of paths from an input to an output) for all nodes of a skeleton. :param sk: Skeleton :param pre_inds: List of skeleton indices with an input synapse (Duplicate indices with more than one) :param post_inds: List of skeleton indices with an output synapse (Duplicate indices with more than one)

Returns:

Array of synapse betweenness for every vertex in the skeleton.

meshparty.trimesh_io module

meshparty.trimesh_repair module

meshparty.trimesh_vtk module

meshparty.trimesh_vtk.camera_from_ngl_state(state_d, zoom_factor=300.0)[source]

define a vtk camera from a neuroglancer state dictionary

Parameters:
  • state_d (dict) – an neuroglancer state dictionary

  • zoom_factor (float) – how much to multiply zoom by to get camera backoff distance default = 300 > ngl_zoom = 1 > 300 nm backoff distance

Returns:

a vtk camera setup that mathces this state

Return type:

vtk.vtkCamera

meshparty.trimesh_vtk.camera_from_quat(pos_nm, orient_quat, camera_distance=10000, ngl_correct=True)[source]

define a vtk camera with a particular orientation

Parameters:
  • pos_nm (np.array, list, tuple) – an iterator of length 3 containing the focus point of the camera

  • orient_quat (np.array, list, tuple) – a len(4) quatenerion (x,y,z,w) describing the rotation of the camera such as returned by neuroglancer x,y,z,w all in [0,1] range

  • camera_distance (float) – the desired distance from pos_nm to the camera (default = 10000 nm)

Returns:

a vtk camera setup according to these rules

Return type:

vtk.vtkCamera

meshparty.trimesh_vtk.decimate_trimesh(trimesh, reduction=0.1)[source]

routine to decimate a mesh through vtk

Parameters:
  • trimesh (trimesh_io.Mesh) – a mesh to decimate

  • reduction (float) – factor to decimate (default .1)

Returns:

  • np.array – points, the Nx3 mesh of vertices

  • np.array – tris, the Kx3 indices of faces

meshparty.trimesh_vtk.graph_to_vtk(vertices, edges)[source]
converts a numpy representation of vertices and edges

to a vtkPolyData object

Parameters:
  • vertices (np.array) – a Nx3 numpy array of vertex locations

  • edges (np.array) – a Mx2 numpy array of vertex connectivity where the values are the indexes of connected vertices

Returns:

a polydata object with point set according to vertices and edges as its Lines

Return type:

vtk.vtkPolyData

Raises:

ValueError – if edges is not 2d or refers to out of bounds vertices

meshparty.trimesh_vtk.linked_point_actor(vertices_a, vertices_b, inds_a=None, inds_b=None, line_width=1, color=(0, 0, 0), opacity=0.2)[source]

function for making polydata with lines between pairs of points

Parameters:
  • vertices_a (np.array) – a Nx3 array of point locations in xyz

  • vertices_b (np.array) – a Nx3 array of point locations in xyz

  • inds_a (np.array) – the indices in vertices_a to use (default None is all of them)

  • inds_b (np.array) – the indices in vertices_b to use (default None is all of them)

  • line_width (int) – the width of lines to draw (default 1)

  • color (iterator) – a len(3) iterator (tuple, list, np.array) with the color [0,1] to use

  • opacity (float) – a [0,1] opacity to render the lines

Returns:

an actor representing the lines between the points given with the color and opacity specified. To be passed to render_actors

Return type:

vtk.vtkActor

meshparty.trimesh_vtk.make_camera_interpolator(times, cameras, linear=False)[source]
meshparty.trimesh_vtk.mesh_actor(mesh, color=(0, 1, 0), opacity=0.1, vertex_colors=None, face_colors=None, lut=None, calc_normals=True, show_link_edges=False, line_width=3)[source]

function for producing a vtkActor from a trimesh_io.Mesh

Parameters:
  • mesh (trimesh_io.Mesh) – a mesh to visualize

  • color (various) – a len 3 iterator of a solid color to label mesh overridden by vertex_colors if passed

  • opacity (float) – the opacity of the mesh (default .1)

  • vertex_colors (np.array) – a np.array Nx3 list of explicit colors (where N is len(mesh.vertices)) OR a np.array of len(N) list of values to map through a colormap default (None) will use color to color mesh

  • face_colors (np.array) – a np.array of Mx3 list of explicit colors (where M is the len(mesh.faces)) OR a np.array of len(M) list of values to map through a colormap (default None will use color for mesh)

  • lut (np.array) – not implemented

  • calc_normals (bool) – whether to calculate normals on the mesh. Default (True) will take more time, but will render a smoother mesh not compatible with sbow_link_edges. default True

  • show_link_edges (bool) – whether to show the link_edges as lines. Will prevent calc_normals. default False

  • line_width (int) – how thick to show lines (default 3)

Returns:

vtkActor representing the mesh (to be passed to render_actors)

Return type:

vtk.vtkActor

meshparty.trimesh_vtk.numpy_rep_to_vtk(vertices, shapes, edges=None)[source]
converts a numpy representation of vertices and vertex connection graph

to a polydata object and corresponding cell array

Parameters:
  • vertices (a Nx3 numpy array of vertex locations) –

  • shapes (a MxK numpy array of vertex connectivity) – (could be triangles (K=3) or edges (K=2))

Returns:

  • vtk.vtkPolyData – a polydata object with point set according to vertices,

  • vtkCellArray – a vtkCellArray of the shapes

meshparty.trimesh_vtk.numpy_to_vtk_cells(mat)[source]

function to convert a numpy array of integers to a vtkCellArray

Parameters:

mat (np.array) – MxN array to be converted

Returns:

representing the numpy array, has the same shaped cell (N) at each of the M indices

Return type:

vtk.vtkCellArray

meshparty.trimesh_vtk.oriented_camera(center, up_vector=(0, - 1, 0), backoff=500, backoff_vector=(0, 0, 1))[source]

Generate a camera pointed at a specific location, oriented with a given up direction, set to a backoff of the center a fixed distance with a particular direction

Parameters:
  • center (iterator) – a len 3 iterator (tuple, list, np.array) with the x,y,z location of the camera’s focus point

  • up_vector (iterator) – a len 3 iterator (tuple, list, np.array) with the dx,dy,dz direction of the camera’s up direction default (0,-1,0) negative y is up.

  • backoff (float) – distance in global space for the camera to be moved backward from the center point (default 500)

  • backoff_vector (iterator) – a len 3 iterator (tuple, list, np.array) with the dx,dy,dz direction to back camera off of the focus point

Returns:

the camera object representing the desired camera location, orientation and focus parameters

Return type:

vtk.vtkCamera

meshparty.trimesh_vtk.point_cloud_actor(xyz, size=100, color=(0, 0, 0), opacity=1)[source]

function to make a vtk.vtkActor from a set of xyz points that renders them as spheres

Parameters:
  • xyz (np.array) – a Nx3 array of points

  • size (float or np.array) – the size of each of the points, or a N long array of sizes of each point

  • color (len(3) iterator or np.array) – the color of all the points, or the color of each point individually as a N long array or a Nx3 list of explicit colors [0,1] range

  • opacity (float) – the [0,1] opacity of mesh

Returns:

an actor with each of the xyz points as spheres of the specified size and color

Return type:

vtk.vtkActor

meshparty.trimesh_vtk.poly_to_mesh_components(poly)[source]

converts a vtkPolyData to its numpy components

Parameters:

poly (vtk.vtkPolyData) – a polydate object to convert to numpy components

Returns:

  • np.array – points, the Nx3 set of vertex locations

  • np.array – tris, the KxD set of faces (assumes a uniform cellarray)

  • np.array – edges, if exists uses the GetLines to make edges

meshparty.trimesh_vtk.process_colors(color, xyz)[source]

utility function to normalize colors on an set of things :param color: a Nx3, or a N long, or a 3 long iterator the represents the

color or colors you want to label xyz with

Parameters:

xyz (np.array) – a NxD matrix you wish to ‘color’

Returns:

  • np.array – a Nx3 or N long array of color values

  • bool – map_colors, whether the colors should be mapped through a colormap or used as is

meshparty.trimesh_vtk.render_actors(actors, camera=None, do_save=False, filename=None, scale=4, back_color=(1, 1, 1), VIDEO_WIDTH=None, VIDEO_HEIGHT=None, video_width=1080, video_height=720, return_keyframes=False)[source]

Visualize a set of actors in a 3d scene, optionally saving a snapshot. Creates a window, renderer, interactor, add the actors and starts the visualization (can save images and close render window)

Parameters:
  • actors (list[vtkActor]) – list of actors to render (see mesh_actor, point_cloud_actor, skeleton_actor)

  • camera (vtkCamera) – camera to use for scence (optional..default to fit scene)

  • do_save (bool) – write png image to disk, if false will open interactive window (default False)

  • filename (str) – filepath to save png image to (default None)

  • scale – scale factor to use when saving images to disk (default 4) for higher res images

  • back_color (Iterable) – rgb values (0,1) to determine for background color (default 1,1,1 = white)

  • return_keyframes (bool) – whether to save a new camera as a keyframes when you press ‘k’ with window open

Returns:

  • vtk.vtkRenderer – renderer when code was finished (useful for retrieving user input camera position ren.GetActiveCamera())

  • (list[vtk.vtkCamera]) – list of vtk cameras when user pressed ‘k’ (only if return_keyframes=True)

meshparty.trimesh_vtk.render_actors_360(actors, directory, nframes, camera_start=None, start_frame=0, video_width=1280, video_height=720, scale=4, do_save=True, back_color=(1, 1, 1))[source]

Function to create a series of png frames which rotates around the Azimuth angle of a starting camera This will save images as a series of png images in the directory specified. The movie will start at time 0 and will go to frame nframes, completing a 360 degree rotation in that many frames. Keep in mind that typical movies are encoded at 15-30 frames per second and nframes is units of frames.

Parameters:
  • actors (list of vtkActor's) – list of vtkActors to render

  • directory (str) – folder to save images into

  • nframes (int) – number of frames to render

  • camera_start (vtk.Camera) – camera to start rotation, default=None will fit actors in scene

  • start_frame (int) – number to save the first frame number as… (default 0) i.e. frames will start_frame = 5, first file would be 005.png

  • video_width (int) – size of video in pixels

  • video_height (int) – size of the video in pixels

  • scale (int) – how much to expand the image

  • do_save (bool) – whether to save the images to disk or just play interactively

  • back_color (iterable) – a len(3) iterable with the background color [0,1]rgb

Returns:

  • vtkRenderer – the renderer used to render

  • endframe – the last frame written

Example

from meshparty import trimesh_io, trimesh_vtk
mm = trimesh_io.MeshMeta(disk_cache_path = 'meshes')
mesh = mm.mesh(filename='mymesh.obj')
mesh_actor = trimesh_vtk.mesh_actor(mesh)
mesh_center = np.mean(mesh.vertices, axis=0)
camera_start = trimesh_vtk.oriented_camera(mesh_center)

render_actors_360([mesh_actor], 'movie', 360, camera_start=camera_start)
meshparty.trimesh_vtk.render_movie(actors, directory, times, cameras, start_frame=0, video_width=1280, video_height=720, scale=4, do_save=True, back_color=(1, 1, 1), linear=False)[source]

Function to create a series of png frames based upon a defining a set of cameras at a set of times. This will save images as a series of png images in the directory specified. The movie will start at time 0 and will go to frame np.max(times) Reccomend to make times start at 0 and the length of the movie you want. Keep in mind that typical movies are encoded at 15-30 frames per second and times is units of frames.

Parameters:
  • actors (list of vtkActor's) – list of vtkActors to render

  • directory (str) – folder to save images into

  • times (np.array) – array of K frame times to set the camera to

  • cameras (list of vtkCamera's) – array of K vtkCamera objects. movie with have cameras[k] at times[k].

  • start_frame (int) – number to save the first frame number as… (default 0) i.e. frames will start_frame = 5, first file would be 005.png

  • video_width (int) – size of video in pixels

  • video_height (int) – size of the video in pixels

  • scale (int) – how much to expand the image

  • do_save (bool) – whether to save the images to disk or just play interactively

Returns:

  • vtkRenderer – the renderer used to render

  • endframe – the last frame written

Example

from meshparty import trimesh_io, trimesh_vtk
mm = trimesh_io.MeshMeta(disk_cache_path = 'meshes')
mesh = mm.mesh(filename='mymesh.obj')
mesh_actor = trimesh_vtk.mesh_actor(mesh)
mesh_center = np.mean(mesh.vertices, axis=0)

camera_start = trimesh_vtk.oriented_camera(mesh_center, backoff = 10000, backoff_vector=(0, 0, 1))
camera_180 = trimesh_vtk.oriented_camera(mesh_center, backoff = 10000, backoff_vector=(0, 0, -1))
times = np.array([0, 90, 180])
cameras = [camera_start, camera_180, camera_start]
render_movie([mesh_actor],
        'movie',
        times,
        cameras)
meshparty.trimesh_vtk.render_movie_flexible(actors, directory, times, frame_change_function, start_frame=0, video_width=1280, video_height=720, scale=4, camera=None, do_save=True, back_color=(1, 1, 1))[source]

Function to create a series of png frames based upon a defining a frame change function that will alter actors and camera at each time point This will save images as a series of png images in the directory specified. The movie will start at time 0 and will go to frame np.max(times) Reccomend to make times start at 0 and the length of the movie you want. Keep in mind that typical movies are encoded at 15-30 frames per second and times is units of frames.

This is the most general of the movie making functions, and can be used to custom change coloring of actors or their positions over time using tranformations.

Parameters:
  • actors (list of vtkActor's) – list of vtkActors to render

  • directory (str) – folder to save images into

  • times (np.array) – array of K frame times to set the camera to

  • frame_change_function (func) – a function that takes (actors, camera, t) as arguments. where actors are the list of actors passed here, camera is the camera for the rendering, and t is the current frame number. This function may alter the actors and camera as a function of time in some user defined manner.

  • start_frame (int) – number to save the first frame number as… (default 0) i.e. frames will start_frame = 5, first file would be 005.png

  • video_width (int) – size of video in pixels

  • video_height (int) – size of the video in pixels

  • scale (int) – how much to expand the image

  • do_save (bool) – whether to save the images to disk or just play interactively

Returns:

  • vtkRenderer – the renderer used to render

  • endframe – the last frame written

Example

from meshparty import trimesh_io, trimesh_vtk
mm = trimesh_io.MeshMeta(disk_cache_path = 'meshes')
mesh = mm.mesh(filename='mymesh.obj')
mesh_actor = trimesh_vtk.mesh_actor(mesh)
mesh_center = np.mean(mesh.vertices, axis=0)

camera_start = trimesh_vtk.oriented_camera(mesh_center, backoff = 10000, backoff_vector=(0, 0, 1))
camera_180 = trimesh_vtk.oriented_camera(mesh_center, backoff = 10000, backoff_vector=(0, 0, -1))
times = np.array([0, 90, 180])
cameras = [camera_start, camera_180, camera_start]
render_movie([mesh_actor],
        'movie',
        times,
        cameras)
meshparty.trimesh_vtk.scale_bar_actor(center, camera, length=10000, color=(0, 0, 0), linewidth=5, font_size=20)[source]

Creates a xyz 3d scale bar actor located at a specific location with a given size

Parameters:
  • center (iterable) – a length 3 iterable of xyz position

  • camera (vtk.vtkCamera) – the camera the scale bar should follow

  • length (int, optional) – length of each of the xyz axis, by default 10000

  • color (tuple, optional) – color of text and lines, by default (0,0,0)

  • linewidth (int, optional) – width of line in pixels, by default 5

  • font_size (int, optional) – font size of xyz labels, by default 20

Returns:

scale bar actor to add to render_actors

Return type:

vtk.vktActor

meshparty.trimesh_vtk.skeleton_actor(sk, edge_property=None, vertex_property=None, vertex_data=None, normalize_property=True, color=(0, 0, 0), line_width=3, opacity=0.7, lut_map=None)[source]

function to make a vtkActor from a skeleton class with different coloring options

Parameters:
  • sk (skeleton.Skeleton) – the skeleton class to create a render

  • edge_property (str) – the key to the edge_properties dictionary on the sk object to use for coloring default None .. use color instead

  • vertex_property (str) – the key to the vertex_properteis dictionary on the sk object to use for coloring default NOne … use color instead

  • vertex_data (np.array) – what data to color skeleton vertices by default None… use color intead

  • normalize_property (bool) – whether to normalize the property data (edge/vertex) with dividing by np.nanmax

  • color (tuple) – a 3 tuple in the [0,1] range of the color of the skeletoni

  • line_width (int) – the width of the skeleton (default 3)

  • opacity (float) – the opacity [0,1] of the mesh (1 = opaque, 0 = invisible)

  • lut_map (np.array) – not implemented

Returns:

actor representing the skeleton

Return type:

vtk.vtkActor

meshparty.trimesh_vtk.trimesh_to_vtk(vertices, tris, graph_edges=None)[source]

Return a vtkPolyData representation of a TriMesh instance

Parameters:
  • vertices (np.array) – numpy array of Nx3 vertex positions (x,y,z)

  • tris (np.array) – numpy array of Mx3 triangle vertex indices (int64)

  • graph_edges (np.array) – numpy array of Kx2 of edges to set as the vtkPolyData.Lines

Returns:

vtk_mesh – A VTK mesh representation of the mesh trimesh.TriMesh data

Return type:

vtk.vtkPolyData

Raises:

ValueError: – If the input trimesh is not 3D or tris refers to out of bounds vertex indices

meshparty.trimesh_vtk.values_to_colors(values, cmap, vmin=None, vmax=None)[source]

Function to map a set of values through a colormap to get RGB values in order to facilitate coloring of meshes.

Parameters:
  • values (array-like, (n_vertices, )) – values to pass through colormap

  • cmap (array-like, (n_colors, 3)) – colormap describing the RGB values from vmin to vmax

  • vmin (float) – (optional) value that should receive minimum of colormap. default to minimum of values

  • vmax (float) – (optional) values that should receive maximum of colormap default to maximum of values

  • Output

  • ------

  • colors (array-like, (n_vertices, 3)) – RGB values for each entry in values (as np.uint8 [0-255])

Example

Assuming mesh object and ‘values’ have been calculated already

import seaborn as sns

cmap = np.array(sns.color_palette('viridis', 1000))
clrs = trimesh_vtk.values_to_colors(values, cmap)
mesh_actor = trimesh_io.mesh_actor(mesh, vertex_colors = clrs, opacity=1.0)
trimesh_vtk.render_actors([mesh_actor])
meshparty.trimesh_vtk.vtk_cellarray_to_shape(vtk_cellarray, ncells)[source]

Turn a vtkCellArray into a numpyarray of a fixed shape assumes your cell array has uniformed sized cells

Parameters:
  • vtk_cellarray (vtk.vtkCellArray) – a cell array to convert

  • ncells (int) – how many cells are in array

Returns:

cellarray, a ncells x K array of cells, where K is the uniform shape of the cells. Will error if cells are not uniform

Return type:

np.array

meshparty.utils module

meshparty.utils.array_if_scalar(values)[source]

If values is a single number or 0-dim array, make a shaped array

meshparty.utils.collapse_zero_length_edges(vertices, edges, root, radius, mesh_to_skel_map, mesh_index, node_mask, vertex_properties={})[source]

Remove zero length edges from a skeleton

meshparty.utils.connected_component_slice(G, ind=None, return_boolean=False)[source]

Gets a numpy slice of the connected component corresponding to a given index. If no index is specified, the slice is of the largest connected component.

meshparty.utils.create_csgraph(vertices, edges, euclidean_weight=True, directed=False)[source]

Builds a csr graph from vertices and edges, with optional control over weights as boolean or based on Euclidean distance.

meshparty.utils.create_nxgraph(vertices, edges, euclidean_weight=True, directed=False)[source]
meshparty.utils.dist_from_line(pts, line_bound_pts, axis)[source]
meshparty.utils.edge_averaged_vertex_property(edge_property, vertices, edges)[source]

Converts a per-edge property to a vertex property by taking the mean of the adjacent edges.

meshparty.utils.filter_close_to_line(mesh, line_bound_pts, line_dist_th, axis=1)[source]
meshparty.utils.filter_shapes(node_ids, shapes)[source]

node_ids has to be sorted!

meshparty.utils.filter_unmasked_boolean(node_mask, unmasked_boolean)[source]

For an unmasked boolean slice, returns a boolean slice filtered to the masked mesh

Parameters:

unmasked_boolean (np.array) – a bool array in the original mesh index space

Returns:

returns the elements of unmasked_boolean that are still relevant in the masked index space

Return type:

np.array

meshparty.utils.filter_unmasked_indices(node_mask, unmasked_shape)[source]

filters a set of indices in the original mesh space and returns it in the masked space

Parameters:
  • mask (np.array or None) – the mask to apply. default None will use this Mesh node_mask

  • unmasked_shape (np.array) – a set of indices into vertices in the unmasked index space

Returns:

the unmasked_shape indices mapped into the masked index space

Return type:

np.array

meshparty.utils.filter_unmasked_indices_padded(node_mask, unmasked_shape)[source]
meshparty.utils.find_far_points(trimesh, start_ind=None, multicomponent=False)[source]

Wraps find_far_points_graph for meshes instead of csgraphs.

meshparty.utils.find_far_points_graph(mesh_graph, start_ind=None, multicomponent=False)[source]

Finds the maximally far point along a graph by bouncing from farthest point to farthest point.

meshparty.utils.get_path(root, target, pred)[source]

Using a predecessor matrix from scipy.csgraph.shortest_paths, get all indices on the path from a root node to a target node.

meshparty.utils.indices_to_slice(inds, total_length)[source]
meshparty.utils.map_boolean_to_unmasked(unmasked_size, node_mask, unmapped_boolean)[source]

For a boolean index in the masked indices, returns the corresponding unmasked boolean index

Parameters:

unmapped_boolean (np.array) – a bool array in the masked index space

Returns:

a bool array in the original index space. Is True if the unmapped_boolean suggests it should be.

Return type:

np.array

meshparty.utils.map_indices_to_unmasked(indices_unmasked, unmapped_indices)[source]

For a set of masked indices, returns the corresponding unmasked indices

Parameters:

unmapped_indices (np.array) – a set of indices in the masked index space

Returns:

the indices mapped back to the original mesh index space

Return type:

np.array

meshparty.utils.mutual_closest_edges(mesh_a, mesh_b, distance_upper_bound=250)[source]
meshparty.utils.nanfilter_shapes(node_ids, shapes)[source]

Wraps filter_shapes to handle shapes with nans.

meshparty.utils.path_from_predecessors(Ps, ind_start)[source]

Build a path from an initial index to a target node based on the target node predecessor row from a shortest path query.

meshparty.utils.paths_to_edges(path_list)[source]

Turn an ordered path into an edge list.

meshparty.utils.reduce_vertices(vertices, vertex_shape, v_filter=None, e_filter=None, return_filter_inds=False)[source]

Given a vertex and edge list, filters them down and remaps indices in the edge list. If no v or e filters are given, reduces the vertex list down to only those vertices with values in the vertex_shape object.

meshparty.utils.remap_dict(n_vertices, map_dict)[source]

Assumes only do remap of indices that are keys in map dict

meshparty.utils.remove_unused_verts(verts, faces)[source]

removes unused vertices from a graph or mesh

Parameters:
  • verts (np.array) – NxD numpy array of vertex locations

  • faces (np.array) – MxK numpy array of connected shapes (i.e. edges or tris) (entries are indices into verts)

Returns:

  • np.array – new_verts a filtered set of vertices s

  • new_face – a reindexed set of faces

meshparty.utils_io module

class meshparty.utils_io.NumpyEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

default(obj)[source]

Module contents