meshparty package

trimesh_io module

Mesh objects, and loading functionality

exception meshparty.trimesh_io.EmptyMaskException[source]

Bases: Exception

Raised when applying a mask that has all zeros

class meshparty.trimesh_io.MaskedMesh(*args, **kwargs)[source]

Bases: meshparty.trimesh_io.Mesh

class meshparty.trimesh_io.Mesh(*args, node_mask=None, unmasked_size=None, apply_mask=False, link_edges=None, **kwargs)[source]

Bases: trimesh.base.Trimesh

An extension of trimesh.Trimesh class to allow more features

Parameters
  • *args (a list of trimesh.Trimesh arguments) –

    the first most commonly used… vertices : np.array

    a Nx3 array of x,y,z of vertex positions

    faces: np.array

    a Mx3 array of abc indices into vertices that form triangle faces

    normals: np.array

    a Mx3 array of face normals

  • node_mask (np.array) – a N long boolean array of which vertices are masked

  • unmasked_size (np.array) – how long the original vertex list is (relevant for masked meshes)

  • apply_mask (bool) – whether to apply the node_mask to the result

  • link_edges (np.array) – a Kx2 array of indices into vertices that represent extra edges you want to store in the mesh graph

  • **kwargs – all the other keyword args you want to pass to trimesh.Trimesh

add a set of link edges to this mesh from a PyChunkedGraph endpoint This will ask the pcg server where merges were done and try to calculate where edges should be added to reflect the merge operations that have been done on this mesh, linking disconnected portions of the mesh.

Parameters
  • seg_id (int) – the seg_id of this mesh

  • dataset_name (str) – the dataset name this mesh can be found in

  • close_map_distance (float) – the distance in mesh vertex coordinates to consider a mapping to be ‘close’

  • server_address (str) – the server address to find the pcg endpoint (default https://www.dynamicannotationframework.com)

apply_mask(new_mask, **kwargs)[source]

Makes a new Mesh by adding a new mask to the existing one. new_mask is a boolean array, either of the original vertex space or the current masked length (in which case it is padded with zeros appropriately).

Parameters
  • new_mask (np.array) – a N long array of bool where False correponds to vertices that should be masked N needs to equal to mesh.vertices.shape[0] (or the original vertex shape if you are operating on an already masked mesh)

  • kwargs – keyword arguments to pass on to the new Mesh.__init__ function

Returns

the mesh with the mask applied

Return type

trimesh_io.Mesh

property csgraph

graph of the mesh

Type

scipy.sparse.csgraph

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

fix_mesh(wiggle_vertices=False, verbose=False)[source]

Executes rudimentary fixing function from pymeshfix

Good for closing holes, fixes mesh in place will recalculate normals

Parameters
  • wiggle_vertices (bool) – adds robustness for smaller components (default False)

  • verbose (bool) – whether to print out debug statements (default False)

get_local_mesh(n_points=None, max_dist=inf, center_node_id=None, center_coord=None, pc_align=True, pc_norm=False)[source]

Single version of get_local_meshes

get_local_meshes(n_points, max_dist=inf, center_node_ids=None, center_coords=None, pc_align=False, pc_norm=False, fix_meshes=False)[source]

Extracts a local mesh

Parameters
  • n_points (int) –

  • max_dist (float) –

  • enter_node_ids (list of ints) –

  • center_coords (list (n, 3) of floats) –

  • pc_align (bool) –

  • pc_norm (bool) –

  • fix_meshes (bool) –

get_local_view(n_points=None, max_dist=inf, sample_n_points=None, adapt_unit_sphere_norm=False, fisheye=False, pc_align=False, center_node_id=None, center_coord=None, method='kdtree', verbose=False, return_node_ids=False, svd_solver='auto', return_faces=False, pc_norm=False)[source]

Single version of get_local_views for backwards compatibility

get_local_views(n_points=None, max_dist=inf, sample_n_points=None, fisheye=False, pc_align=False, center_node_ids=None, center_coords=None, verbose=False, return_node_ids=False, svd_solver='auto', return_faces=False, adapt_unit_sphere_norm=False, pc_norm=False)[source]

Extracts a local view (points)

Parameters
  • n_points (int) – number of points to sample, default None will use the full mesh vertices

  • max_dist (float) – sets an upper limit for distance of any sampled mesh point. Might reduce n_points

  • sample_n_points (int) – has to be >= n_points; if > n_points more points are sampled and a subset randomly chosen

  • fisheye (bool) – addition to sample_n_points; subset is sampled such that a fisheye effect is generated (default False)

  • pc_align (bool) – computes PCA and orients mesh along PCs (default False)

  • center_node_ids (list of ints) – mesh vertices at the center of the local views (default None)

  • center_coords (list (n, 3) of floats) – coordinates at the center of the local views (default None) will override center_node_ids if both center_node_ids and center_coors are None will choose random spots equal to the length of vertices

  • verbose (bool) – whether to print more debugging (default False)

  • return_node_ids (bool) – sampled node ids are returned as well, changes the output format (default False)

  • svd_solver (str) – PCA solver passed to sklearn.decomposition.PCA (default “auto”)

  • return_faces (bool) – sampled faces are returned as well, changes the output format (default False)

  • adapt_unit_sphere_norm (bool) – NOT FUNCTIONAL (default False)

  • pc_norm (bool) – if True: normalize point cloud to mean 0 and std 1 before PCA (default False)

Returns

  • np.array – local_vertices, a list of n_points or n_sample_points x 3 matrix of points len(local_vertices)=K will depend on center_coords or center_coords_ind

  • np.array – center_node_ids, a K long array of center node ids.. useful if you had it choose random points if you had passed center_coords this will not accurately reflect the centers used

  • np.array – return_node_ids, Optional depending on whether return_node_ids. A K long list of

  • np.array – return_faces, Optional depending on return_faces. faces on the local views, a K list of mx3 triangle faces.

property graph_edges

a Nx2 of the edges from triangle faces, plus the link_edges

Type

np.array

property index_map

A dict mapping global indices into the masked mesh indices.

property indices_unmasked

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

Type

np.array

property kdtree

kdtree of the mesh vertices

Parameters

balanced_tree (bool) – passed on to scipy.spatial.cKDTree

Type

scipy.spatial.cKDTree

a Kx2 set of textra edges you want to store in the mesh graph, edges() will return this plus face_edges()

Type

numpy.array

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

merge_large_components(size_threshold=100, max_dist=1000, dist_step=100)[source]

Finds edges between disconnected components will add the edges to the existing set of link_edges or start a set of link_edges if there are None Note: can cause self-contacts to be innapropriately merged

Parameters
  • size_threshold (int) – will merge components that have more than this many vertices (default 100)

  • max_dist (float) – will only merge components that are closer than this (default 1000 in units of mesh.vertices, usually nm)

  • dist_step (int) – will merge by marching in steps to look for things to merge this is the distance of each step (default 100 in units of mesh.vertices)

property n_faces

how many faces are in the mesh

Type

int

property n_vertices

how many vertices are in the mesh

Type

int

property node_mask

Returns the node/vertex mask currently applied to the data

Type

np.array

property nxgraph

networkx graph of the mesh

Type

networkx.Graph

property pykdtree

KDTree of the mesh vertices

Type

pykdtree.KDTree

property unmasked_size

Returns the unmasked number of nodes in the mesh

write_to_file(filename)[source]

Exports the mesh to any format supported by trimesh

Parameters

filename (str) – the path to where to write the filename. Will use extension to infer format ‘.h5’ for hdf5 ‘.obj’ for wavefront all others supported by trimesh.exchange.export.export_mesh()

class meshparty.trimesh_io.MeshMeta(cache_size=400, cv_path=None, disk_cache_path=None, map_gs_to_https=True)[source]

Bases: object

Manager class to keep meshes in memory and seemingless download them

Parameters
  • cache_size (int) – number of meshes to keep in memory adapt this to your available memory and size of meshes set to zero to use less memory but read from disk cache

  • cv_path (str) – path to pass to cloudvolume.CloudVolume

  • disk_cache_path (str) – meshes are dumped to this directory => should be equal to target_dir in download_meshes (default None will not cache meshes)

  • map_gs_to_https (bool) – whether to change gs paths to https paths, via cloudvolume’s use_https option

property cache_size

the size of the cache

property cv

the cloudvolume object

Type

cloudvoume.CloudVolume

property cv_path

the path passed to cloudvolume.CloudVolume

Type

str

property disk_cache_path

the path where meshes are saved

Type

str

mesh(filename=None, seg_id=None, cache_mesh=True, merge_large_components=False, stitch_mesh_chunks=True, overwrite_merge_large_components=False, remove_duplicate_vertices=False, force_download=False)[source]

Loads mesh either from cache, disk or google storage

Note, if the mesh is in a cache (memory or disk) you will get exactly what was in the cache irrespective of the other options you specified unless force_download is set

Parameters
  • filename (str) – the full path to a file to load (default None)

  • seg_id (uint64) – the mesh_id to get (default None, requires cv_path)

  • cache_mesh (bool) – if True: mesh is cached in a dictionary. The user is responsible for avoiding a memory overflow (default True)

  • merge_large_components (bool) – if True: large (>100 vx) mesh connected components are linked and the additional edges strored in .link_edges this information is cached as well (default False)

  • stitch_mesh_chunks (bool) – if True it will stitch the mesh fragments together into a single graph (default True)

  • overwrite_merge_large_components (bool) – if True: recalculate large components (default False)

  • remove_duplicate_vertices (bool) – whether to bluntly removed duplicate vertices (default False)

  • force_download (bool) – whether to force the mesh to be redownloaded from cloudvolume

Returns

The mesh object of this seg_id

Return type

Mesh

Raises

AssertionError – if filename is not None, and seg_id and cv_path are not both set then it doesn’t know how to get your mesh

meshparty.trimesh_io.download_meshes(seg_ids, target_dir, cv_path, overwrite=True, n_threads=1, verbose=False, stitch_mesh_chunks=True, merge_large_components=False, remove_duplicate_vertices=False, map_gs_to_https=True, fmt='hdf5', progress=False)[source]

Downloads meshes in target directory (in parallel) will break up the seg_ids into n_threads*3 job blocks or fewer and download them all

Parameters
  • seg_ids (iterator of ids) – the seg ids (with filenames = f”{seg_id}.h5”) in the target_dir

  • target_dir (str) – a path to the diretory to save the meshes

  • cv_path (str) – the cloudvolume path passed to cloudvolume.CloudVolume

  • n_threads (int) – how many parallel processes to use when downloading (default 1)

  • overwrite (bool) – whether to overwrite the meshes if they already exist. will do no work if those don’t exist (default True)

  • stitch_mesh_chunks (bool) – whether to stitch mesh chunks across meshes after downloading fragments (default True)

  • merge_large_components (bool) – whether to merge all the large components using ‘func’:trimesh_io.Mesh.merge_large_components with default parameters (default False)

  • remove_duplicate_vertices (bool) – whether to bluntly merge duplicate vertices (default False)

  • map_gs_to_https (bool) – whether to trigger cloudvolume.CloudVolume use_https option. Probably should be true unless you have a private bucket and have ~/.cloudvolume/secrets setup properly (default True)

  • fmt (str) – ‘hdf5’, ‘obj’, ‘stl’ or any format supported by meshparty.trimesh_io.Mesh.write_to_file() (default ‘hdf5’)

  • progress (bool) –

meshparty.trimesh_io.read_mesh(filename)[source]

Reads a mesh from obj or h5 file

Parameters

filename (str) – a path to a obj or h5 file to read a mesh

Returns

  • numpy.array – vertices, a Nx3 x,y,z coordinates (float)

  • numpy.array – faces, a Mx3 a,b,c index into vertices for triangle faces np.int32

  • numpy.array – normals, A Mx3 x,y,z direction for face normals, np.float32 None if it doesn’t exist

  • numpy.array – link_edges, a Kx2 a,b list of extra link edges to add to the mesh graph np.int32 None if this doesn’t exist or is an obj file

  • numpy.array – node_mask, a N length np.bool area of whether to mask this index (None if doesn’t exist) None if this doesn’t exist or is an obj file

meshparty.trimesh_io.read_mesh_h5(filename)[source]

Reads a mesh’s vertices, faces and normals from an hdf5 file assert’s that this file exists. Will load normals, link_edges, and node_mask if they exist.

Parameters

filename (str) – a path to a h5 file

Returns

  • np.array – vertices, a Nx3 x,y,z coordinates (float)

  • np.array – faces, a Mx3 a,b,c index into vertices for triangle faces np.int32

  • np.array – normals, A Mx3 x,y,z direction for face normals, np.float32 [] if it doesn’t exist

  • np.array – link_edges, a Kx2 a,b list of extra link edges to add to the mesh graph np.int32 None if this doesn’t exist

  • np.array – node_mask, a N length np.bool area of whether to mask this index (None if doesn’t exist) None if this doesn’t exist

Raises

AssertionError – if the filename is not a file

meshparty.trimesh_io.write_mesh_h5(filename, vertices, faces, normals=None, link_edges=None, node_mask=None, overwrite=False)[source]

Writes a mesh’s vertices, faces (and normals) to an hdf5 file

Parameters
  • filename (str) – a path to a h5 file to write a mesh

  • vertices (np.array) – a Nx3 x,y,z coordinates (float)

  • faces (np.array) – a Mx3 a,b,c index into vertices for triangle faces np.int32

  • normals (np.array) – a Mx3 x,y,z direction for face normals, np.float32 if it doesn’t exist (default None)

  • link_edges (np.array) – a Kx2 a,b list of extra link edges to add to the mesh graph np.int32 None if this doesn’t exist (default None)

  • node_mask (np.array) – a N length np.bool area of whether to mask this index (None if doesn’t exist) None if this doesn’t exist (default None)

  • overwrite (False) – whether to overwrite the file, will return silently if mesh file exists already

mesh_filters module

Functions for creating mesh masks

meshparty.mesh_filters.filter_close_to_line(mesh, line_end_pts, line_dist_th, axis=1, endcap_buffer=0, sphere_ends=False)[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)[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_largest_component(mesh)[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)[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)[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

trimesh_repair module

Functions for adding edges to meshes

meshparty.trimesh_repair.find_all_close_edges(vertices, labels, ccs)[source]

Find all the mutually closest edges between all components of the mesh

Parameters
  • vertices (np.array) – a Nx3 array of xyz vertex position

  • labels (np.array) – a labelling of the vertices that reflect components of the mesh

  • ccs (int) – the number of connected components in the mesh

Returns

a Kx2 array of vertex indices that are mutually closest to each other across all combinations of components

Return type

np.array

meshparty.trimesh_repair.find_close_edges(vertices, labels, label_a, label_b)[source]

a function to find the closest vertex in one compoment for every vertex of another component

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

  • labels (np.array) – A N np.array of ints across vertices where connected components have the same label

  • label_a (int) – the label of the first connected component

  • label_b (int) – the label of the second connected component

Returns

close_edges, a Kx2 array (where K is the np.sum(labels==label_a) of vertex indices, where the first column entry is all the vertices in component a and the second column entry is the index of the vertex in component b that is closest to the vertex in the first column.

Return type

np.array

meshparty.trimesh_repair.find_close_edges_sym(vertices, labels, label_a, label_b)[source]

a function to find the mutually closest vertices between two compoments of a mesh meaning.. vertex 1 is the closest vertex from component a to vertex 2 and vertex 2 is the closest vertex in component b to vertex 1.

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

  • labels (np.array) – A N np.array of ints across vertices where connected components have the same label

  • label_a (int) – the label of the first connected component

  • label_b (int) – the label of the second connected component

Returns

close_edges, a Kx2 array of vertex indices, where the first column entry is an index in component a the second column entry is an index in component b and each vertex is mutually the closest vertex to the other component

Return type

np.array

Given a mesh and two points on that mesh find a way to add edges to the mesh graph so that those indices are on the same connected component

Parameters
  • mesh (trimesh_io.Mesh) – a mesh to find edges on

  • vert_ind_a (int) – one index into mesh.vertices, the first point

  • vert_ind_b (int) – a second index into mesh.vertices, the second point

  • distance_upper_bound (float) – a maximum distance to (default 2500 in units of mesh.vertices)

  • verbose (bool) – whether to print debug info

Returns

a Kx2 array of mesh indices that represent edges to add to the mesh to link the two points in a way that creates the shortest path between the points across mututally closest vertices from connected components.. not adding edges if they are larger than distance_upper_bound TODO: distance_upper_bound not presently implemented

Return type

np.array

function to get a set of edges that should be added to a mesh

Parameters
  • mesh (trimesh_io.Mesh) – the mesh to add edges to

  • seg_id (np.uint64 or int) – the seg_id to query the PCG endpoint for merges

  • dataset_name (str) – the name of the dataset to query

  • close_map_distance (int or float) – the maximum distance to map (default 300 in units of mesh.vertices)

  • server_address (str) – the url to the root of the framework deployment default “https://www.dynamicannotationframework.com

  • verbose (bool) – whether to print debug statements

Returns

link_edges, a Kx2 array of mesh.vertices indices representing edges that should be added to the mesh graph

Return type

np.array

meshparty.trimesh_repair.merge_points_to_merge_indices(mesh, merge_event_points, close_map_distance=300)[source]

function to take merge points in 3d space and find the right mesh.vertices indices filtering out merge events that merge the same component or are far away

Parameters
  • mesh (trimesh_io.Mesh) – mesh to map points to

  • merge_event_points (np.array) – a Nx2x3 matrix of merge points, where the last dimension is xyz

  • close_map_distance (float or int) – a maximum distance to map points to indices (default 300)

Returns

close_inds, a Mx2 matrix of indices into mesh.vertices M<N because some merge pairs might not have been able to both be mapped in under close_map_distance, and merge_points that only seem to connect already connected components are not added.

Return type

np.array

meshparty.trimesh_repair.np_shared_rows(A, B)[source]

a utility to find intersection of two arrays

Parameters
  • A (np.array) – a Nx2 array of np.int32 values

  • B (np.array) – a Mx2 array of np.int32 values

Returns

a Kx2 array of np.int32 values where the rows of A were also in B

Return type

np.array

skeletonize module

Functions for turnings meshes into skeletons

meshparty.skeletonize.calculate_skeleton_paths_on_mesh(mesh, soma_pt=None, soma_thresh=7500, invalidation_d=10000, smooth_neighborhood=5, large_skel_path_threshold=5000, cc_vertex_thresh=100, return_map=False)[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.

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_pt, verts, edges, soma_d_thresh=12000, mesh_to_skeleton_map=None, soma_mesh_indices=None, return_filter=False, only_soma_component=True, 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)[source]

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

meshparty.skeletonize.ray_trace_distance(vertex_inds, mesh, max_iter=10, rand_jitter=0.001, verbose=False, ray_inter=None)[source]

Compute distance to opposite side of the mesh for specified vertex indices on the mesh.

Parameters
  • vertex_inds (np.array) – a K long set of indices into the mesh.vertices that you want to perform ray tracing on

  • mesh (meshparty.trimesh_io.Mesh) – mesh to perform ray tracing on

  • max_iter (int) – maximum retries to attempt in order to get a proper sdf measure (default 10)

  • rand_jitter (float) – the amplitude of gaussian jitter on the vertex normal to add on each iteration (default .001)

  • verbose (bool) – whether to print debug statements (default False)

  • ray_inter (ray_pyembree.RayMeshIntersector) – a ray intercept object pre-initialized with a mesh, in case y ou are doing this many times and want to avoid paying initialization costs. (default None) will initialize it for you

Returns

rs, a K long array of sdf values. rays with no result after max_iters will contain zeros.

Return type

np.array

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.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)[source]

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

meshparty.skeletonize.skeletonize_mesh(mesh, soma_pt=None, soma_radius=7500, collapse_soma=True, invalidation_d=12000, smooth_vertices=False, compute_radius=True, compute_original_index=True, verbose=True)[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)

  • 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)

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

  • verbose (bool) – whether to print verbose logging

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

skeleton module

Skeleton class with useful methods for skeleton analysis

class meshparty.skeleton.Skeleton(vertices, edges, mesh_to_skel_map=None, vertex_properties={}, root=None)[source]

Bases: object

Class to manage skeleton data

Parameters
  • vertices (np.array) – a Nx3 list of xyz locations of skeleton nodes

  • edges (np.array) – a Kx2 list of edges in the skeleton where each row is a connected pair of vertex indices.

  • mesh_to_skel_map (np.array) – For a skeleton derived from a mesh with N_mesh vertices, a length N_mesh array where that gives the closest on-graph skeleton vertex for each mesh vertex (or -1 if None). (default is None)

  • vertex_properties (dict) – a dictionary of keys with strings where each value is a numpy.array of len(N) of properties of skeleton vertices

  • root (None) – what vertex index should be root (default None will find a vertex far from others)

property branch_points

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

Type

numpy.array

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

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

property csgraph

Directed sparse graph representation of the skeleton vertex connectivity. The i,jth element is the distance from a vertex i to its parent j, 0 otherwise.

Type

scipy.sparse.csr.csr_matrix

property csgraph_binary

Directed binary sparse graph representation of skeleton vertex connectivity. The i,jth element is 1 if vertex i has parent j, 0 otherwise.

Type

scipy.sparse.csr.csr_matrix

property csgraph_binary_undirected

Undirected sparse graph representation of skeleton vertex connectivity. The i,jth element is 1 if vertex i is connected to vertex j, 0 otherwise.

Type

scipy.sparse.csr_matrix

property csgraph_undirected

Undirected sparse graph representation of skeleton vertex connectivity. The i,jth element is the distance from vertex i to any connected vertex j, 0 otherwise.

Type

scipy.sparse.csr_matrix

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

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

Type

np.array

downstream_nodes(vinds)[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

Mx2 set of edges as indices into vertices

Type

numpy.array

property end_points

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

Type

numpy.array

export_to_swc(filename, node_labels=None, radius=None, header=None, xyz_scaling=1000)[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.

property kdtree

k-D tree from scipy.spatial.

Type

scipy.spatial.kdtree

property mesh_to_skel_map

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

Type

numpy.array

property n_branch_points

Number of branch points on the skeleton

Type

int

property n_end_points

Number of end points on the skeleton

Type

int

property n_vertices

Number of vertices in the skeleton

Type

int

parent_node(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_length(paths)[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]

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 pykdtree

k-D tree from pykdtree (a bit faster but fewer functions)

Type

pykdtree.pyKDTree object

reroot(new_root)[source]

Change the skeleton root index.

Parameters

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

property root

Index of the skeleton root

Type

int

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 vertices

Nx3 set of xyz coordinates of skeletons

Type

numpy.array

skeleton_io module

Functions for reading and writing skeletons to disk

meshparty.skeleton_io.export_to_swc(skel, filename, node_labels=None, radius=None, header=None, xyz_scaling=1000)[source]

Export a skeleton file to an swc file (see http://research.mssm.edu/cnic/swc.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 (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.

meshparty.skeleton_io.read_skeleton_h5(filename)[source]

Reads a skeleton and its properties from an hdf5 file.

Parameters

filename (str) – path to skeleton file

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.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, 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

trimesh_vtk module

Functions for creating vtk objects and visualizing meshes, skeletons and points

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.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

Parameters
  • color (np.array) – a Nx3, or a N long, or a 3 long iterator the represents the color or colors you want to label xyz with

  • 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.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.trimesh_vtk.render_actors(actors, camera=None, do_save=False, filename=None, scale=4, back_color=(1, 1, 1), 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))[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

utils module

Utility functions used in other modules

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.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.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.

mesh_skel_utils module

Functions for mapping skeletons and meshes together

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

meshlabserver module

Facilities for interacting with meshlab

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]

iterator module

Facilities for iterating over views of a mesh. Useful for ML applications.

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.