_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q23100
Trimesh.vertex_neighbors
train
def vertex_neighbors(self): """ The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent. Returns ---------- vertex_neighbors : (len(self.vertices),) int Represents immediate neighbors of each vertex along the edge of a triangle Examples ---------- This is useful for getting nearby vertices for a given vertex, potentially for some simple smoothing techniques.
python
{ "resource": "" }
q23101
Trimesh.is_winding_consistent
train
def is_winding_consistent(self): """ Does the mesh have consistent winding or not. A mesh with consistent winding has each shared edge going in an opposite direction from the other in the pair. Returns -------- consistent : bool Is winding is consistent or not """ if self.is_empty:
python
{ "resource": "" }
q23102
Trimesh.is_watertight
train
def is_watertight(self): """ Check if a mesh is watertight by making sure every edge is included in two faces. Returns ---------- is_watertight : bool Is mesh watertight or not """ if self.is_empty:
python
{ "resource": "" }
q23103
Trimesh.is_volume
train
def is_volume(self): """ Check if a mesh has all the properties required to represent a valid volume, rather than just a surface. These properties include being watertight, having consistent winding and outward facing normals.
python
{ "resource": "" }
q23104
Trimesh.is_convex
train
def is_convex(self): """ Check if a mesh is convex or not. Returns ---------- is_convex: bool Is mesh convex or not """ if self.is_empty:
python
{ "resource": "" }
q23105
Trimesh.kdtree
train
def kdtree(self): """ Return a scipy.spatial.cKDTree of the vertices of the mesh. Not cached as this lead to observed memory issues and segfaults. Returns --------- tree : scipy.spatial.cKDTree
python
{ "resource": "" }
q23106
Trimesh.facets_area
train
def facets_area(self): """ Return an array containing the area of each facet. Returns --------- area : (len(self.facets),) float Total area of each facet (group of faces) """ # avoid thrashing the cache inside a loop area_faces = self.area_faces # sum the area of each group of faces represented by facets # use native python sum in
python
{ "resource": "" }
q23107
Trimesh.facets_normal
train
def facets_normal(self): """ Return the normal of each facet Returns --------- normals: (len(self.facets), 3) float A unit normal vector for each facet """ if len(self.facets) == 0: return np.array([]) area_faces = self.area_faces # sum the area of each group of faces represented by facets # the face index of the first face in each facet index = np.array([i[area_faces[i].argmax()] for i in self.facets])
python
{ "resource": "" }
q23108
Trimesh.facets_boundary
train
def facets_boundary(self): """ Return the edges which represent the boundary of each facet Returns --------- edges_boundary : sequence of (n, 2) int Indices of self.vertices """ # make each row correspond to a single face edges = self.edges_sorted.reshape((-1, 6)) # get the edges for each facet
python
{ "resource": "" }
q23109
Trimesh.facets_on_hull
train
def facets_on_hull(self): """ Find which facets of the mesh are on the convex hull. Returns --------- on_hull : (len(mesh.facets),) bool is A facet on the meshes convex hull or not """ # facets plane, origin and normal normals = self.facets_normal origins = self.facets_origin # (n,3) convex hull vertices
python
{ "resource": "" }
q23110
Trimesh.fix_normals
train
def fix_normals(self, multibody=None): """ Find and fix problems with self.face_normals and self.faces winding direction. For face normals ensure that vectors are consistently pointed outwards, and that self.faces is wound in the correct
python
{ "resource": "" }
q23111
Trimesh.subdivide
train
def subdivide(self, face_index=None): """ Subdivide a mesh, with each subdivided face replaced with four smaller faces. Parameters ---------- face_index: (m,) int or None If None all faces of mesh will be subdivided If (m,) int array of indices: only specified faces will be subdivided. Note that in this case the mesh will generally no longer be manifold, as the additional vertex on the midpoint will not be used by the adjacent faces to the faces specified, and an additional postprocessing step will be required to
python
{ "resource": "" }
q23112
Trimesh.smoothed
train
def smoothed(self, angle=.4): """ Return a version of the current mesh which will render nicely, without changing source mesh. Parameters ------------- angle : float Angle in radians, face pairs with angles smaller than this value will appear smoothed Returns --------- smoothed : trimesh.Trimesh Non watertight version of current mesh which will render nicely with smooth shading """ #
python
{ "resource": "" }
q23113
Trimesh.section
train
def section(self, plane_normal, plane_origin): """ Returns a 3D cross section of the current mesh and a plane defined by origin and normal. Parameters --------- plane_normal: (3) vector for plane normal Normal vector of section plane plane_origin : (3,) float Point on the cross section plane Returns --------- intersections: Path3D or None Curve of intersection """ # turn line segments into Path2D/Path3D objects from .exchange.load import load_path # return a single cross section in 3D
python
{ "resource": "" }
q23114
Trimesh.section_multiplane
train
def section_multiplane(self, plane_origin, plane_normal, heights): """ Return multiple parallel cross sections of the current mesh in 2D. Parameters --------- plane_normal: (3) vector for plane normal Normal vector of section plane plane_origin : (3,) float Point on the cross section plane heights : (n,) float Each section is offset by height along the plane normal. Returns --------- paths : (n,) Path2D
python
{ "resource": "" }
q23115
Trimesh.slice_plane
train
def slice_plane(self, plane_origin, plane_normal, **kwargs): """ Returns another mesh that is the current mesh sliced by the plane defined by origin and normal. Parameters --------- plane_normal: (3) vector for plane normal Normal vector of slicing plane plane_origin : (3,) float Point on the slicing plane Returns --------- new_mesh: trimesh.Trimesh or
python
{ "resource": "" }
q23116
Trimesh.sample
train
def sample(self, count, return_index=False): """ Return random samples distributed normally across the surface of the mesh Parameters --------- count : int Number of points to sample return_index : bool If True will also return the index of which face each sample was taken from. Returns --------- samples : (count, 3) float Points on surface
python
{ "resource": "" }
q23117
Trimesh.remove_unreferenced_vertices
train
def remove_unreferenced_vertices(self): """ Remove all vertices in the current mesh which are not referenced by a face. """ referenced = np.zeros(len(self.vertices), dtype=np.bool) referenced[self.faces] = True
python
{ "resource": "" }
q23118
Trimesh.unmerge_vertices
train
def unmerge_vertices(self): """ Removes all face references so that every face contains three unique vertex indices and no faces are adjacent. """ # new faces are incrementing so every vertex is unique faces = np.arange(len(self.faces) * 3,
python
{ "resource": "" }
q23119
Trimesh.apply_obb
train
def apply_obb(self): """ Apply the oriented bounding box transform to the current mesh. This will result in a mesh with an AABB centered at the origin and the same dimensions as the OBB.
python
{ "resource": "" }
q23120
Trimesh.apply_transform
train
def apply_transform(self, matrix): """ Transform mesh by a homogenous transformation matrix. Does the bookkeeping to avoid recomputing things so this function should be used rather than directly modifying self.vertices if possible. Parameters ---------- matrix : (4, 4) float Homogenous transformation matrix """ # get c-order float64 matrix matrix = np.asanyarray(matrix, order='C', dtype=np.float64) # only support homogenous transformations if matrix.shape != (4, 4): raise ValueError('Transformation matrix must be (4,4)!') # exit early if we've been passed an identity matrix # np.allclose is surprisingly slow so do this test elif np.abs(matrix - np.eye(4)).max() < 1e-8: log.debug('apply_tranform passed identity matrix') return # new vertex positions new_vertices = transformations.transform_points( self.vertices, matrix=matrix) # overridden center of mass if self._center_mass is not None: self._center_mass = transformations.transform_points( np.array([self._center_mass, ]), matrix)[0] # preserve face normals if we have them stored new_face_normals = None if 'face_normals' in self._cache: # transform face normals by rotation component new_face_normals = util.unitize( transformations.transform_points( self.face_normals, matrix=matrix, translate=False)) # preserve vertex normals if we have them stored new_vertex_normals = None if 'vertex_normals' in self._cache: new_vertex_normals = util.unitize( transformations.transform_points( self.vertex_normals, matrix=matrix, translate=False)) # a test triangle pre and post transform triangle_pre = self.vertices[self.faces[:5]] # we don't care about scale so make sure they aren't tiny triangle_pre /= np.abs(triangle_pre).max() # do the same for the post- transform test triangle_post = new_vertices[self.faces[:5]] triangle_post /= np.abs(triangle_post).max() # compute triangle normal before and after transform normal_pre, valid_pre = triangles.normals(triangle_pre) normal_post, valid_post = triangles.normals(triangle_post) # check the first few faces against normals to check winding aligned_pre
python
{ "resource": "" }
q23121
Trimesh.voxelized
train
def voxelized(self, pitch, **kwargs): """ Return a Voxel object representing the current mesh discretized into voxels at the specified pitch Parameters ---------- pitch : float
python
{ "resource": "" }
q23122
Trimesh.outline
train
def outline(self, face_ids=None, **kwargs): """ Given a list of face indexes find the outline of those faces and return it as a Path3D. The outline is defined here as every edge which is only included by a single triangle. Note that this implies a non-watertight mesh as the outline of a watertight mesh is an empty path. Parameters ---------- face_ids : (n,) int Indices to compute the outline of. If None, outline of full mesh will be computed. **kwargs: passed to Path3D constructor
python
{ "resource": "" }
q23123
Trimesh.area_faces
train
def area_faces(self): """ The area of each face in the mesh. Returns --------- area_faces : (n,) float Area of each face """ area_faces =
python
{ "resource": "" }
q23124
Trimesh.mass_properties
train
def mass_properties(self): """ Returns the mass properties of the current mesh. Assumes uniform density, and result is probably garbage if mesh isn't watertight. Returns ---------- properties : dict With keys: 'volume' : in global units^3 'mass' : From specified density 'density' : Included again for convenience (same as kwarg density) 'inertia' : Taken at the center of mass and aligned with global coordinate system 'center_mass' : Center of mass location, in global coordinate system """ mass = triangles.mass_properties(triangles=self.triangles, crosses=self.triangles_cross, density=self._density, center_mass=self._center_mass,
python
{ "resource": "" }
q23125
Trimesh.invert
train
def invert(self): """ Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache. Alters --------- self.faces : columns reversed self.face_normals : negated if defined self.vertex_normals : negated if defined """ with self._cache: if 'face_normals' in self._cache: self.face_normals *= -1.0
python
{ "resource": "" }
q23126
Trimesh.submesh
train
def submesh(self, faces_sequence, **kwargs): """ Return a subset of the mesh. Parameters ---------- faces_sequence : sequence (m,) int Face indices of mesh only_watertight : bool Only return submeshes which are watertight append : bool Return a single mesh which has the faces appended. if this flag is set, only_watertight is ignored Returns ---------
python
{ "resource": "" }
q23127
Trimesh.export
train
def export(self, file_obj=None, file_type=None, **kwargs): """ Export the current mesh to a file object. If file_obj is a filename, file will be written there. Supported formats are stl, off, ply, collada, json, dict, glb, dict64, msgpack. Parameters --------- file_obj: open writeable file object str, file name where to save the mesh None, if you would like this function to return the export blob file_type: str
python
{ "resource": "" }
q23128
Trimesh.intersection
train
def intersection(self, other, engine=None): """ Boolean intersection between this mesh and n other meshes Parameters --------- other : trimesh.Trimesh, or list of trimesh.Trimesh objects Meshes to calculate intersections with Returns ---------
python
{ "resource": "" }
q23129
Trimesh.contains
train
def contains(self, points): """ Given a set of points, determine whether or not they are inside the mesh. This raises an error if called on a non- watertight mesh. Parameters --------- points : (n, 3) float Points in cartesian space Returns --------- contains : (n, ) bool Whether or not each point is inside the mesh
python
{ "resource": "" }
q23130
Trimesh.face_adjacency_tree
train
def face_adjacency_tree(self): """ An R-tree of face adjacencies. Returns -------- tree: rtree.index Where each edge in self.face_adjacency has a rectangular cell """ # the (n,6) interleaved bounding box for every line segment
python
{ "resource": "" }
q23131
Trimesh.copy
train
def copy(self): """ Safely get a copy of the current mesh. Copied objects will have emptied caches to avoid memory issues and so may be slow on initial operations until caches are regenerated. Current object will *not* have its cache cleared. Returns --------- copied : trimesh.Trimesh Copy of current mesh """ copied = Trimesh() # copy vertex and face data copied._data.data = copy.deepcopy(self._data.data) # copy visual information copied.visual = self.visual.copy()
python
{ "resource": "" }
q23132
Trimesh.eval_cached
train
def eval_cached(self, statement, *args): """ Evaluate a statement and cache the result before returning. Statements are evaluated inside the Trimesh object, and Parameters ----------- statement : str Statement of valid python code *args : list Available inside statement as args[0], etc Returns ----------- result : result of running eval on statement with args Examples ----------- r = mesh.eval_cached('np.dot(self.vertices, args[0])', [0,0,1])
python
{ "resource": "" }
q23133
fix_winding
train
def fix_winding(mesh): """ Traverse and change mesh faces in-place to make sure winding is correct, with edges on adjacent faces in opposite directions. Parameters ------------- mesh: Trimesh object Alters ------------- mesh.face: will reverse columns of certain faces """ # anything we would fix is already done if mesh.is_winding_consistent: return graph_all = nx.from_edgelist(mesh.face_adjacency) flipped = 0 faces = mesh.faces.view(np.ndarray).copy() # we are going to traverse the graph using BFS # start a traversal for every connected component for components in nx.connected_components(graph_all): # get a subgraph for this component g = graph_all.subgraph(components) # get the first node in the graph in a way that works on nx's # new API and their old API start = next(iter(g.nodes())) # we traverse every pair of faces in the graph # we modify mesh.faces and mesh.face_normals in place for face_pair in nx.bfs_edges(g, start): # for each pair of faces, we convert them into edges, # find the edge that both faces share and then see if edges # are reversed in order as you would
python
{ "resource": "" }
q23134
fix_inversion
train
def fix_inversion(mesh, multibody=False): """ Check to see if a mesh has normals pointing "out." Parameters ------------- mesh: Trimesh object multibody: bool, if True will try to fix normals on every body Alters ------------- mesh.face: may reverse faces """ if multibody: groups = graph.connected_components(mesh.face_adjacency) # escape early for single body if len(groups) == 1: if mesh.volume < 0.0: mesh.invert() return # mask of faces to flip flip = np.zeros(len(mesh.faces), dtype=np.bool) # save these to avoid thrashing cache tri = mesh.triangles cross = mesh.triangles_cross # indexes of mesh.faces, not actual faces for faces in groups: # calculate the volume of the submesh faces volume = triangles.mass_properties( tri[faces], crosses=cross[faces], skip_inertia=True)['volume'] # if that volume is negative it is either
python
{ "resource": "" }
q23135
fix_normals
train
def fix_normals(mesh, multibody=False): """ Fix the winding and direction of a mesh face and face normals in-place. Really only meaningful on watertight meshes, but will orient all faces and winding in a uniform way for non-watertight face patches as well. Parameters ------------- mesh: Trimesh object multibody: bool, if True try to correct normals direction on every body. Alters --------------
python
{ "resource": "" }
q23136
broken_faces
train
def broken_faces(mesh, color=None): """ Return the index of faces in the mesh which break the watertight status of the mesh. Parameters -------------- mesh: Trimesh object color: (4,) uint8, will set broken faces to this color None, will not alter mesh colors Returns ---------------
python
{ "resource": "" }
q23137
mesh_multiplane
train
def mesh_multiplane(mesh, plane_origin, plane_normal, heights): """ A utility function for slicing a mesh by multiple parallel planes, which caches the dot product operation. Parameters ------------- mesh : trimesh.Trimesh Geometry to be sliced by planes plane_normal : (3,) float Normal vector of plane plane_origin : (3,) float Point on a plane heights : (m,) float Offset distances from plane to slice at Returns -------------- lines : (m,) sequence of (n, 2, 2) float Lines in space for m planes to_3D : (m, 4, 4) float Transform to move each section back to 3D face_index : (m,) sequence of (n,) int Indexes of mesh.faces for each segment """ # check input plane plane_normal = util.unitize(plane_normal) plane_origin = np.asanyarray(plane_origin, dtype=np.float64) heights = np.asanyarray(heights, dtype=np.float64) # dot product of every vertex with plane vertex_dots = np.dot(plane_normal, (mesh.vertices - plane_origin).T) # reconstruct transforms for each 2D section base_transform = geometry.plane_transform(origin=plane_origin, normal=plane_normal) base_transform = np.linalg.inv(base_transform) # alter translation Z inside loop translation = np.eye(4) # store results transforms = [] face_index = [] segments = [] # loop through user specified heights for height in heights: # offset the origin by the height new_origin = plane_origin + (plane_normal * height) # offset the dot products by height and index by faces new_dots = (vertex_dots - height)[mesh.faces] # run the intersection with the cached dot products lines, index = mesh_plane(mesh=mesh, plane_origin=new_origin, plane_normal=plane_normal,
python
{ "resource": "" }
q23138
plane_lines
train
def plane_lines(plane_origin, plane_normal, endpoints, line_segments=True): """ Calculate plane-line intersections Parameters --------- plane_origin : (3,) float Point on plane plane_normal : (3,) float Plane normal vector endpoints : (2, n, 3) float Points defining lines to be tested line_segments : bool If True, only returns intersections as valid if vertices from endpoints are on different sides of the plane. Returns --------- intersections : (m, 3) float Cartesian intersection points valid : (n, 3) bool Indicate whether a valid intersection exists for each input line segment """ endpoints = np.asanyarray(endpoints) plane_origin = np.asanyarray(plane_origin).reshape(3) line_dir = util.unitize(endpoints[1] - endpoints[0]) plane_normal = util.unitize(np.asanyarray(plane_normal).reshape(3)) t = np.dot(plane_normal, (plane_origin - endpoints[0]).T) b = np.dot(plane_normal, line_dir.T) # If the plane normal and line direction are perpendicular, it means # the vector is 'on plane', and there
python
{ "resource": "" }
q23139
planes_lines
train
def planes_lines(plane_origins, plane_normals, line_origins, line_directions): """ Given one line per plane, find the intersection points. Parameters ----------- plane_origins : (n,3) float Point on each plane plane_normals : (n,3) float Normal vector of each plane line_origins : (n,3) float Point at origin of each line line_directions : (n,3) float Direction vector of each line Returns ---------- on_plane : (n,3) float Points on specified planes valid : (n,) bool Did plane intersect line or not """ # check input types plane_origins = np.asanyarray(plane_origins, dtype=np.float64) plane_normals = np.asanyarray(plane_normals, dtype=np.float64) line_origins = np.asanyarray(line_origins, dtype=np.float64) line_directions = np.asanyarray(line_directions, dtype=np.float64)
python
{ "resource": "" }
q23140
slice_mesh_plane
train
def slice_mesh_plane(mesh, plane_normal, plane_origin, **kwargs): """ Slice a mesh with a plane, returning a new mesh that is the portion of the original mesh to the positive normal side of the plane Parameters --------- mesh : Trimesh object Source mesh to slice plane_normal : (3,) float Normal vector of plane to intersect with mesh plane_origin: (3,) float Point on plane to intersect with mesh cached_dots : (n, 3) float If an external function has stored dot products pass them here to avoid recomputing Returns ---------- new_mesh : Trimesh object Sliced mesh """ # check input for none if mesh is None: return None # avoid circular import from .base import Trimesh # check input plane plane_normal = np.asanyarray(plane_normal, dtype=np.float64) plane_origin = np.asanyarray(plane_origin, dtype=np.float64) # check to make sure origins and normals have acceptable shape shape_ok = ((plane_origin.shape == (3,) or util.is_shape(plane_origin, (-1, 3))) and (plane_normal.shape == (3,) or
python
{ "resource": "" }
q23141
create_scene
train
def create_scene(): """ Create a scene with a Fuze bottle, some cubes, and an axis. Returns ---------- scene : trimesh.Scene Object with geometry """ scene = trimesh.Scene() # plane geom = trimesh.creation.box((0.5, 0.5, 0.01)) geom.apply_translation((0, 0, -0.005)) geom.visual.face_colors = (.6, .6, .6) scene.add_geometry(geom) # axis geom = trimesh.creation.axis(0.02) scene.add_geometry(geom) box_size = 0.1 # box1 geom = trimesh.creation.box((box_size,) * 3) geom.visual.face_colors = np.random.uniform( 0, 1, (len(geom.faces), 3)) transform = tf.translation_matrix([0.1, 0.1, box_size / 2]) scene.add_geometry(geom, transform=transform) # box2 geom = trimesh.creation.box((box_size,) * 3) geom.visual.face_colors = np.random.uniform( 0, 1, (len(geom.faces), 3)) transform = tf.translation_matrix([-0.1, 0.1, box_size
python
{ "resource": "" }
q23142
face_angles_sparse
train
def face_angles_sparse(mesh): """ A sparse matrix representation of the face angles. Returns ---------- sparse: scipy.sparse.coo_matrix with: dtype: float
python
{ "resource": "" }
q23143
discrete_gaussian_curvature_measure
train
def discrete_gaussian_curvature_measure(mesh, points, radius): """ Return the discrete gaussian curvature measure of a sphere centered at a point as detailed in 'Restricted Delaunay triangulations and normal cycle', Cohen-Steiner and Morvan. Parameters ---------- points : (n,3) float, list of points in space radius : float, the sphere radius Returns -------- gaussian_curvature: (n,) float, discrete gaussian curvature measure.
python
{ "resource": "" }
q23144
discrete_mean_curvature_measure
train
def discrete_mean_curvature_measure(mesh, points, radius): """ Return the discrete mean curvature measure of a sphere centered at a point as detailed in 'Restricted Delaunay triangulations and normal cycle', Cohen-Steiner and Morvan. Parameters ---------- points : (n,3) float, list of points in space radius : float, the sphere radius Returns -------- mean_curvature: (n,) float, discrete mean curvature measure. """ points = np.asanyarray(points, dtype=np.float64) if not util.is_shape(points, (-1, 3)): raise ValueError('points must be (n,3)!') # axis aligned bounds bounds = np.column_stack((points - radius, points + radius)) # line segments that intersect axis aligned bounding box
python
{ "resource": "" }
q23145
line_ball_intersection
train
def line_ball_intersection(start_points, end_points, center, radius): """ Compute the length of the intersection of a line segment with a ball. Parameters ---------- start_points : (n,3) float, list of points in space end_points : (n,3) float, list of points in space center : (3,) float, the sphere center radius : float, the sphere radius Returns -------- lengths: (n,) float, the lengths. """ # We solve for the intersection of |x-c|**2 = r**2 and # x = o + dL. This yields # d = (-l.(o-c) +- sqrt[ l.(o-c)**2 - l.l((o-c).(o-c) - r^**2) ]) / l.l L = end_points - start_points oc = start_points - center # o-c r = radius ldotl = np.einsum('ij, ij->i', L, L) # l.l ldotoc = np.einsum('ij, ij->i', L, oc) # l.(o-c) ocdotoc = np.einsum('ij, ij->i', oc, oc) #
python
{ "resource": "" }
q23146
uv_to_color
train
def uv_to_color(uv, image): """ Get the color in a texture image. Parameters ------------- uv : (n, 2) float UV coordinates on texture image image : PIL.Image Texture image Returns ---------- colors : (n, 4) float RGBA color at each of the UV coordinates """ if image is None or uv is None: return None # UV coordinates should be (n, 2) float uv = np.asanyarray(uv, dtype=np.float64) # get texture image pixel positions of UV coordinates x = (uv[:, 0] * (image.width - 1)) y = ((1 - uv[:, 1]) * (image.height - 1)) # convert to int and wrap to image # size in the manner of GL_REPEAT x =
python
{ "resource": "" }
q23147
TextureVisuals.uv
train
def uv(self, values): """ Set the UV coordinates. Parameters -------------- values : (n, 2) float Pixel locations on a texture per- vertex """ if values
python
{ "resource": "" }
q23148
TextureVisuals.copy
train
def copy(self): """ Return a copy of the current TextureVisuals object. Returns ---------- copied : TextureVisuals Contains the same information in a new object """ uv = self.uv if
python
{ "resource": "" }
q23149
TextureVisuals.to_color
train
def to_color(self): """ Convert textured visuals to a ColorVisuals with vertex color calculated from texture. Returns ----------- vis : trimesh.visuals.ColorVisuals Contains vertex color from texture """ # find the color
python
{ "resource": "" }
q23150
TextureVisuals.update_vertices
train
def update_vertices(self, mask): """ Apply a mask to remove or duplicate vertex properties. """
python
{ "resource": "" }
q23151
load_stl
train
def load_stl(file_obj, file_type=None, **kwargs): """ Load an STL file from a file object. Parameters ---------- file_obj: open file- like object file_type: not used Returns ---------- loaded: kwargs for a Trimesh constructor with keys: vertices: (n,3) float, vertices faces: (m,3) int, indexes of vertices face_normals: (m,3) float, normal vector of each face """ # save start of file obj file_pos = file_obj.tell() try: # check the file for a header which matches the file length # if that is true, it is almost certainly a binary STL file
python
{ "resource": "" }
q23152
load_stl_binary
train
def load_stl_binary(file_obj): """ Load a binary STL file from a file object. Parameters ---------- file_obj: open file- like object Returns ---------- loaded: kwargs for a Trimesh constructor with keys: vertices: (n,3) float, vertices faces: (m,3) int, indexes of vertices face_normals: (m,3) float, normal vector of each face """ # the header is always 84 bytes long, we just reference the dtype.itemsize # to be explicit about where that magical number comes from header_length = _stl_dtype_header.itemsize header_data = file_obj.read(header_length) if len(header_data) < header_length: raise HeaderError('Binary STL shorter than a fixed header!') try: header = np.frombuffer(header_data, dtype=_stl_dtype_header) except BaseException: raise HeaderError('Binary header incorrect type') try: # save the header block as a string # there could be any garbage in there so wrap in try metadata = {'header': bytes(header['header'][0]).decode('utf-8').strip()} except BaseException: metadata = {} # now we check the length from the header versus the length of the file # data_start should always be position 84, but hard coding that felt ugly data_start = file_obj.tell() # this seeks to the end of the file # position 0, relative to the end of the file 'whence=2' file_obj.seek(0, 2) # we save the location of the end of the file and seek back to where we # started from
python
{ "resource": "" }
q23153
load_stl_ascii
train
def load_stl_ascii(file_obj): """ Load an ASCII STL file from a file object. Parameters ---------- file_obj: open file- like object Returns ---------- loaded: kwargs for a Trimesh constructor with keys: vertices: (n,3) float, vertices faces: (m,3) int, indexes of vertices face_normals: (m,3) float, normal vector of each face """ # the first line is the header header = file_obj.readline() # make sure header is a string, not bytes if hasattr(header, 'decode'): try: header = header.decode('utf-8') except BaseException: header = '' # save header to metadata metadata = {'header': header} # read all text into one string text = file_obj.read() # convert bytes to string if hasattr(text, 'decode'): text = text.decode('utf-8') # split by endsolid keyword text = text.lower().split('endsolid')[0] # create array of splits blob = np.array(text.strip().split()) # there are 21 'words' in each face face_len = 21 # length of blob should be multiple of face_len if (len(blob) % face_len) != 0: raise HeaderError('Incorrect length STL file!') face_count = int(len(blob) / face_len) # this offset is to be added to a fixed set of tiled indices
python
{ "resource": "" }
q23154
export_stl
train
def export_stl(mesh): """ Convert a Trimesh object into a binary STL file. Parameters --------- mesh: Trimesh object Returns --------- export: bytes, representing mesh in binary STL form """ header = np.zeros(1, dtype=_stl_dtype_header) header['face_count']
python
{ "resource": "" }
q23155
export_stl_ascii
train
def export_stl_ascii(mesh): """ Convert a Trimesh object into an ASCII STL file. Parameters --------- mesh : trimesh.Trimesh Returns --------- export : str Mesh represented as an ASCII STL file """ # move all the data that's going into the STL file into one array blob = np.zeros((len(mesh.faces), 4, 3)) blob[:, 0, :] = mesh.face_normals blob[:, 1:, :] = mesh.triangles # create a lengthy format string for the data section of
python
{ "resource": "" }
q23156
vertex_graph
train
def vertex_graph(entities): """ Given a set of entity objects generate a networkx.Graph that represents their vertex nodes. Parameters -------------- entities : list Objects with 'closed' and 'nodes' attributes Returns ------------- graph : networkx.Graph
python
{ "resource": "" }
q23157
vertex_to_entity_path
train
def vertex_to_entity_path(vertex_path, graph, entities, vertices=None): """ Convert a path of vertex indices to a path of entity indices. Parameters ---------- vertex_path : (n,) int Ordered list of vertex indices representing a path graph : nx.Graph Vertex connectivity entities : (m,) list Entity objects vertices : (p, dimension) float Vertex points in space Returns ---------- entity_path : (q,) int Entity indices which make up vertex_path """ def edge_direction(a, b): """ Given two edges, figure out if the first needs to be reversed to keep the progression forward. [1,0] [1,2] -1 1 [1,0] [2,1] -1 -1 [0,1] [1,2] 1 1 [0,1] [2,1] 1 -1 Parameters ------------ a : (2,) int b : (2,) int Returns ------------ a_direction : int b_direction : int """ if a[0] == b[0]: return -1, 1 elif a[0] == b[1]: return -1, -1 elif a[1] == b[0]: return 1, 1 elif a[1] == b[1]: return 1, -1 else: msg = 'edges not connected!' msg += '\nvertex_path: {}'.format(vertex_path) msg
python
{ "resource": "" }
q23158
closed_paths
train
def closed_paths(entities, vertices): """ Paths are lists of entity indices. We first generate vertex paths using graph cycle algorithms, and then convert them to entity paths. This will also change the ordering of entity.points in place so a path may be traversed without having to reverse the entity. Parameters ------------- entities : (n,) entity objects Entity objects vertices : (m, dimension) float Vertex points in space Returns ------------- entity_paths : sequence of (n,) int Ordered traversals of entities """ # get a networkx graph of entities graph, closed = vertex_graph(entities) # add entities that are closed as single- entity paths entity_paths = np.reshape(closed, (-1, 1)).tolist() # look for cycles in the graph, or closed loops vertex_paths = np.array(nx.cycles.cycle_basis(graph))
python
{ "resource": "" }
q23159
discretize_path
train
def discretize_path(entities, vertices, path, scale=1.0): """ Turn a list of entity indices into a path of connected points. Parameters ----------- entities : (j,) entity objects Objects like 'Line', 'Arc', etc. vertices: (n, dimension) float Vertex points in space. path : (m,) int Indexes of entities scale : float Overall scale of drawing used for numeric tolerances in certain cases Returns ----------- discrete : (p, dimension) float Connected points in space that lie on the path and can be connected with line segments. """ # make sure vertices are numpy array vertices = np.asanyarray(vertices) path_len = len(path) if path_len == 0: raise ValueError('Cannot discretize empty path!') if path_len == 1: # case where we only have one entity discrete = np.asanyarray(entities[path[0]].discrete( vertices, scale=scale)) else: # run through path appending each entity discrete = [] for i, entity_id in enumerate(path): # the current (n, dimension) discrete curve of an entity current = entities[entity_id].discrete(vertices, scale=scale)
python
{ "resource": "" }
q23160
split
train
def split(self): """ Split a Path2D into multiple Path2D objects where each one has exactly one root curve. Parameters -------------- self : trimesh.path.Path2D Input geometry Returns ------------- split : list of trimesh.path.Path2D Original geometry as separate paths """ # avoid a circular import by referencing class of self Path2D = type(self) # save the results of the split to an array split = [] # get objects from cache to avoid a bajillion # cache checks inside the tight loop paths = self.paths discrete = self.discrete polygons_closed = self.polygons_closed enclosure_directed = self.enclosure_directed for root_index, root in enumerate(self.root): # get a list of the root curve's children connected = list(enclosure_directed[root].keys()) # add the root node to the list connected.append(root) # store new paths and entities new_paths = [] new_entities = [] for index in connected: path = paths[index] # add a path which is just sequential indexes new_paths.append(np.arange(len(path)) + len(new_entities))
python
{ "resource": "" }
q23161
ray_triangle_id
train
def ray_triangle_id(triangles, ray_origins, ray_directions, triangles_normal=None, tree=None, multiple_hits=True): """ Find the intersections between a group of triangles and rays Parameters ------------- triangles : (n, 3, 3) float Triangles in space ray_origins : (m, 3) float Ray origin points ray_directions : (m, 3) float Ray direction vectors triangles_normal : (n, 3) float Normal vector of triangles, optional tree : rtree.Index Rtree object holding triangle bounds Returns ----------- index_triangle : (h,) int Index of triangles hit index_ray : (h,) int Index of ray that hit triangle locations : (h, 3) float Position of intersection in space """ triangles = np.asanyarray(triangles, dtype=np.float64) ray_origins = np.asanyarray(ray_origins, dtype=np.float64) ray_directions = np.asanyarray(ray_directions, dtype=np.float64) # if we didn't get passed an r-tree for the bounds of each # triangle create one here if tree is None: tree = triangles_mod.bounds_tree(triangles) # find the list of likely triangles and which ray they # correspond with, via rtree queries ray_candidates, ray_id = ray_triangle_candidates( ray_origins=ray_origins, ray_directions=ray_directions, tree=tree) # get subsets which are corresponding rays and triangles # (c,3,3) triangle candidates triangle_candidates = triangles[ray_candidates] # (c,3) origins and vectors for the rays line_origins = ray_origins[ray_id] line_directions = ray_directions[ray_id] # get the plane origins and normals from the triangle candidates plane_origins = triangle_candidates[:, 0, :] if triangles_normal is None: plane_normals, triangle_ok = triangles_mod.normals( triangle_candidates) if not triangle_ok.all(): raise ValueError('Invalid triangles!') else: plane_normals = triangles_normal[ray_candidates] # find the intersection location of the rays with the planes location, valid = intersections.planes_lines( plane_origins=plane_origins, plane_normals=plane_normals, line_origins=line_origins, line_directions=line_directions) if (len(triangle_candidates) == 0 or not valid.any()): return [], [], [] # find the barycentric coordinates of each plane intersection on the # triangle candidates barycentric = triangles_mod.points_to_barycentric( triangle_candidates[valid], location) # the plane intersection is inside the triangle if all barycentric coordinates # are between 0.0 and 1.0 hit = np.logical_and((barycentric > -tol.zero).all(axis=1),
python
{ "resource": "" }
q23162
ray_triangle_candidates
train
def ray_triangle_candidates(ray_origins, ray_directions, tree): """ Do broad- phase search for triangles that the rays may intersect. Does this by creating a bounding box for the ray as it passes through the volume occupied by the tree Parameters ------------ ray_origins: (m,3) float, ray origin points ray_directions: (m,3) float, ray direction vectors tree: rtree object, contains AABB of each triangle Returns
python
{ "resource": "" }
q23163
ray_bounds
train
def ray_bounds(ray_origins, ray_directions, bounds, buffer_dist=1e-5): """ Given a set of rays and a bounding box for the volume of interest where the rays will be passing through, find the bounding boxes of the rays as they pass through the volume. Parameters ------------ ray_origins: (m,3) float, ray origin points ray_directions: (m,3) float, ray direction vectors bounds: (2,3) bounding box (min, max) buffer_dist: float, distance to pad zero width bounding boxes Returns --------- ray_bounding: (n) set of AABB of rays passing through volume """ ray_origins = np.asanyarray(ray_origins, dtype=np.float64) ray_directions = np.asanyarray(ray_directions, dtype=np.float64) # bounding box we are testing against bounds = np.asanyarray(bounds) # find the primary axis of the vector axis = np.abs(ray_directions).argmax(axis=1) axis_bound = bounds.reshape((2, -1)).T[axis] axis_ori = np.array([ray_origins[i][a] for i, a in enumerate(axis)]).reshape((-1, 1)) axis_dir = np.array([ray_directions[i][a] for i, a in enumerate(axis)]).reshape((-1, 1)) # parametric equation of a line # point = direction*t + origin # p = dt + o # t = (p-o)/d t = (axis_bound - axis_ori) / axis_dir # prevent the bounding box from including
python
{ "resource": "" }
q23164
RayMeshIntersector.intersects_id
train
def intersects_id(self, ray_origins, ray_directions, return_locations=False, multiple_hits=True, **kwargs): """ Find the intersections between the current mesh and a list of rays. Parameters ------------ ray_origins: (m,3) float, ray origin points ray_directions: (m,3) float, ray direction vectors multiple_hits: bool, consider multiple hits of each ray or not return_locations: bool, return hit locations or not Returns ----------- index_triangle: (h,) int, index of triangles hit index_ray: (h,) int, index of ray that hit triangle locations: (h,3) float, (optional) position of intersection in space """ (index_tri, index_ray, locations) = ray_triangle_id(triangles=self.mesh.triangles, ray_origins=ray_origins,
python
{ "resource": "" }
q23165
RayMeshIntersector.intersects_any
train
def intersects_any(self, ray_origins, ray_directions, **kwargs): """ Find out if each ray hit any triangle on the mesh. Parameters ------------ ray_origins: (m,3) float, ray origin points ray_directions: (m,3) float, ray direction vectors Returns --------- hit: boolean, whether any ray hit any triangle on the mesh """ index_tri, index_ray = self.intersects_id(ray_origins,
python
{ "resource": "" }
q23166
dict_to_path
train
def dict_to_path(as_dict): """ Turn a pure dict into a dict containing entity objects that can be sent directly to a Path constructor. Parameters ----------- as_dict : dict Has keys: 'vertices', 'entities' Returns ------------ kwargs : dict Has keys: 'vertices', 'entities' """ # start kwargs with initial value result = as_dict.copy() # map of constructors loaders = {'Arc': Arc, 'Line': Line}
python
{ "resource": "" }
q23167
lines_to_path
train
def lines_to_path(lines): """ Turn line segments into a Path2D or Path3D object. Parameters ------------ lines : (n, 2, dimension) or (n, dimension) float Line segments or connected polyline curve in 2D or 3D Returns ----------- kwargs : dict kwargs for Path constructor """ lines = np.asanyarray(lines, dtype=np.float64) if util.is_shape(lines, (-1, (2, 3))): # the case where we have a list of points # we are going to assume they are connected result = {'entities': np.array([Line(np.arange(len(lines)))]), 'vertices': lines} return result elif util.is_shape(lines, (-1, 2, (2, 3))): # case where we have line segments in 2D or 3D dimension = lines.shape[-1]
python
{ "resource": "" }
q23168
polygon_to_path
train
def polygon_to_path(polygon): """ Load shapely Polygon objects into a trimesh.path.Path2D object Parameters ------------- polygon : shapely.geometry.Polygon Input geometry Returns ------------- kwargs : dict Keyword arguments for Path2D constructor """ # start with a single polyline for the exterior entities = deque([Line(points=np.arange( len(polygon.exterior.coords)))]) # start vertices vertices = np.array(polygon.exterior.coords).tolist() # append interiors as single Line objects
python
{ "resource": "" }
q23169
linestrings_to_path
train
def linestrings_to_path(multi): """ Load shapely LineString objects into a trimesh.path.Path2D object Parameters ------------- multi : shapely.geometry.LineString or MultiLineString Input 2D geometry Returns ------------- kwargs : dict Keyword arguments for Path2D constructor """ # append to result as we go entities = [] vertices = [] if not util.is_sequence(multi): multi = [multi] for line in multi: # only append geometry with points if hasattr(line, 'coords'):
python
{ "resource": "" }
q23170
faces_to_path
train
def faces_to_path(mesh, face_ids=None, **kwargs): """ Given a mesh and face indices find the outline edges and turn them into a Path3D. Parameters --------- mesh : trimesh.Trimesh Triangulated surface in 3D face_ids : (n,) int Indexes referencing mesh.faces Returns --------- kwargs : dict Kwargs for Path3D constructor """ if face_ids is None: edges = mesh.edges_sorted else: # take advantage of edge ordering to index as single row edges = mesh.edges_sorted.reshape( (-1,
python
{ "resource": "" }
q23171
edges_to_path
train
def edges_to_path(edges, vertices, **kwargs): """ Given an edge list of indices and associated vertices representing lines, generate kwargs for a Path object. Parameters ----------- edges : (n, 2) int Vertex indices of line segments vertices : (m, dimension) float Vertex positions where dimension is 2 or 3 Returns ---------- kwargs: dict, kwargs for Path constructor """ # sequence of ordered traversals dfs = graph.traversals(edges, mode='dfs') # make sure every consecutive index in DFS # traversal is an edge in the source edge list
python
{ "resource": "" }
q23172
point_plane_distance
train
def point_plane_distance(points, plane_normal, plane_origin=[0.0, 0.0, 0.0]): """ The minimum perpendicular distance of a point to a plane. Parameters ----------- points: (n, 3) float, points in space plane_normal: (3,) float, normal vector plane_origin: (3,) float, plane origin in space Returns ------------
python
{ "resource": "" }
q23173
major_axis
train
def major_axis(points): """ Returns an approximate vector representing the major axis of points Parameters ------------- points: (n, dimension) float, points in space Returns -------------
python
{ "resource": "" }
q23174
plane_fit
train
def plane_fit(points): """ Given a set of points, find an origin and normal using SVD. Parameters --------- points : (n,3) float Points in 3D space Returns --------- C : (3,) float Point on the plane N : (3,) float Normal vector of plane """ # make sure input is numpy array points = np.asanyarray(points,
python
{ "resource": "" }
q23175
tsp
train
def tsp(points, start=0): """ Find an ordering of points where each is visited and the next point is the closest in euclidean distance, and if there are multiple points with equal distance go to an arbitrary one. Assumes every point is visitable from every other point, i.e. the travelling salesman problem on a fully connected graph. It is not a MINIMUM traversal; rather it is a "not totally goofy traversal, quickly." On random points this traversal is often ~20x shorter than random ordering. Parameters --------------- points : (n, dimension) float ND points in space start : int The index of points we should start at Returns --------------- traversal : (n,) int Ordered traversal visiting every point distances : (n - 1,) float The euclidean distance between points in traversal """ # points should be float points = np.asanyarray(points, dtype=np.float64) if len(points.shape) != 2: raise ValueError('points must be (n, dimension)!') # start should be an index start = int(start) # a mask of unvisited points by index unvisited = np.ones(len(points), dtype=np.bool) unvisited[start] = False # traversal of points by index traversal = np.zeros(len(points), dtype=np.int64) - 1 traversal[0] = start # list of distances distances = np.zeros(len(points) - 1, dtype=np.float64) # a mask of indexes in order index_mask = np.arange(len(points), dtype=np.int64) # in the loop we want to call distances.sum(axis=1) # a lot and it's actually kind of slow for "reasons" #
python
{ "resource": "" }
q23176
PointCloud.copy
train
def copy(self): """ Safely get a copy of the current point cloud. Copied objects will have emptied caches to avoid memory issues and so may be slow on initial operations until caches are regenerated. Current object will *not* have its cache cleared. Returns --------- copied : trimesh.PointCloud Copy of current point cloud """ copied = PointCloud(vertices=None)
python
{ "resource": "" }
q23177
PointCloud.apply_transform
train
def apply_transform(self, transform): """ Apply a homogenous transformation to the PointCloud object in- place. Parameters -------------- transform : (4, 4) float Homogenous transformation to apply to PointCloud
python
{ "resource": "" }
q23178
PointCloud.bounds
train
def bounds(self): """ The axis aligned bounds of the PointCloud Returns ------------ bounds : (2, 3) float Miniumum, Maximum verteex """
python
{ "resource": "" }
q23179
reflection_matrix
train
def reflection_matrix(point, normal): """Return matrix to mirror at plane defined by point and normal vector. >>> v0 = np.random.random(4) - 0.5 >>> v0[3] = 1. >>> v1 = np.random.random(3) - 0.5 >>> R = reflection_matrix(v0, v1) >>> np.allclose(2, np.trace(R)) True >>> np.allclose(v0, np.dot(R, v0)) True >>> v2 = v0.copy() >>> v2[:3] += v1
python
{ "resource": "" }
q23180
reflection_from_matrix
train
def reflection_from_matrix(matrix): """Return mirror plane point and normal vector from reflection matrix. >>> v0 = np.random.random(3) - 0.5 >>> v1 = np.random.random(3) - 0.5 >>> M0 = reflection_matrix(v0, v1) >>> point, normal = reflection_from_matrix(M0) >>> M1 = reflection_matrix(point, normal) >>> is_same_transform(M0, M1) True """ M = np.array(matrix, dtype=np.float64, copy=False)
python
{ "resource": "" }
q23181
clip_matrix
train
def clip_matrix(left, right, bottom, top, near, far, perspective=False): """Return matrix to obtain normalized device coordinates from frustum. The frustum bounds are axis-aligned along x (left, right), y (bottom, top) and z (near, far). Normalized device coordinates are in range [-1, 1] if coordinates are inside the frustum. If perspective is True the frustum is a truncated pyramid with the perspective point at origin and direction along z axis, otherwise an orthographic canonical view volume (a box). Homogeneous coordinates transformed by the perspective clip matrix need to be dehomogenized (divided by w coordinate). >>> frustum = np.random.rand(6) >>> frustum[1] += frustum[0] >>> frustum[3] += frustum[2] >>> frustum[5] += frustum[4] >>> M = clip_matrix(perspective=False, *frustum) >>> a = np.dot(M, [frustum[0], frustum[2], frustum[4], 1]) >>> np.allclose(a, [-1., -1., -1., 1.]) True >>> b = np.dot(M, [frustum[1], frustum[3], frustum[5], 1]) >>> np.allclose(b, [ 1., 1., 1., 1.]) True >>> M = clip_matrix(perspective=True, *frustum) >>> v = np.dot(M, [frustum[0], frustum[2], frustum[4], 1]) >>> c = v / v[3] >>> np.allclose(c, [-1., -1., -1., 1.]) True >>> v = np.dot(M, [frustum[1], frustum[3], frustum[4], 1]) >>> d = v / v[3] >>> np.allclose(d, [ 1., 1., -1., 1.]) True """
python
{ "resource": "" }
q23182
shear_matrix
train
def shear_matrix(angle, direction, point, normal): """Return matrix to shear by angle along direction vector on shear plane. The shear plane is defined by a point and normal vector. The direction vector must be orthogonal to the plane's normal vector. A point P is transformed by the shear matrix into P" such that the vector P-P" is parallel to the direction vector and its extent is given by the angle of P-P'-P", where P' is the orthogonal projection of P onto the shear plane. >>> angle = (random.random() - 0.5) * 4*math.pi >>> direct = np.random.random(3) - 0.5 >>> point = np.random.random(3) - 0.5 >>> normal = np.cross(direct, np.random.random(3)) >>> S = shear_matrix(angle, direct, point, normal) >>> np.allclose(1, np.linalg.det(S))
python
{ "resource": "" }
q23183
shear_from_matrix
train
def shear_from_matrix(matrix): """Return shear angle, direction and plane from shear matrix. >>> angle = np.pi / 2.0 >>> direct = [0.0, 1.0, 0.0] >>> point = [0.0, 0.0, 0.0] >>> normal = np.cross(direct, np.roll(direct,1)) >>> S0 = shear_matrix(angle, direct, point, normal) >>> angle, direct, point, normal = shear_from_matrix(S0) >>> S1 = shear_matrix(angle, direct, point, normal) >>> is_same_transform(S0, S1) True """ M = np.array(matrix, dtype=np.float64, copy=False) M33 = M[:3, :3] # normal: cross independent eigenvectors corresponding to the eigenvalue 1 w, V = np.linalg.eig(M33) i = np.where(abs(np.real(w) - 1.0) < 1e-4)[0] if len(i) < 2: raise ValueError("no two linear independent eigenvectors found %s" % w) V = np.real(V[:, i]).squeeze().T lenorm = -1.0 for i0, i1 in ((0, 1), (0, 2), (1, 2)): n = np.cross(V[i0], V[i1]) w = vector_norm(n) if w > lenorm: lenorm = w normal = n normal
python
{ "resource": "" }
q23184
compose_matrix
train
def compose_matrix(scale=None, shear=None, angles=None, translate=None, perspective=None): """Return transformation matrix from sequence of transformations. This is the inverse of the decompose_matrix function. Sequence of transformations: scale : vector of 3 scaling factors shear : list of shear factors for x-y, x-z, y-z axes angles : list of Euler angles about static x, y, z axes translate : translation vector along x, y, z axes perspective : perspective partition of matrix >>> scale = np.random.random(3) - 0.5 >>> shear = np.random.random(3) - 0.5 >>> angles = (np.random.random(3) - 0.5) * (2*math.pi) >>> trans = np.random.random(3) - 0.5 >>> persp = np.random.random(4) - 0.5 >>> M0 = compose_matrix(scale, shear, angles, trans, persp) >>> result = decompose_matrix(M0) >>> M1 = compose_matrix(*result) >>> is_same_transform(M0, M1) True """ M = np.identity(4) if perspective is not None: P = np.identity(4) P[3, :] = perspective[:4] M = np.dot(M, P) if translate is not None: T = np.identity(4)
python
{ "resource": "" }
q23185
euler_matrix
train
def euler_matrix(ai, aj, ak, axes='sxyz'): """Return homogeneous rotation matrix from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> R = euler_matrix(1, 2, 3, 'syxz') >>> np.allclose(np.sum(R[0]), -1.34786452) True >>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1)) >>> np.allclose(np.sum(R[0]), -0.383436184) True >>> ai, aj, ak = (4*math.pi) * (np.random.random(3) - 0.5) >>> for axes in _AXES2TUPLE.keys(): ... R = euler_matrix(ai, aj, ak, axes) >>> for axes in _TUPLE2AXES.keys(): ... R = euler_matrix(ai, aj, ak, axes) """ try: firstaxis, parity, repetition, frame = _AXES2TUPLE[axes] except (AttributeError, KeyError): _TUPLE2AXES[axes] # validation firstaxis, parity, repetition, frame = axes i = firstaxis j = _NEXT_AXIS[i + parity] k = _NEXT_AXIS[i - parity + 1] if frame: ai, ak = ak, ai if parity: ai, aj, ak = -ai, -aj, -ak si, sj, sk = math.sin(ai), math.sin(aj), math.sin(ak) ci, cj, ck = math.cos(ai), math.cos(aj), math.cos(ak) cc, cs = ci * ck, ci * sk sc,
python
{ "resource": "" }
q23186
euler_from_matrix
train
def euler_from_matrix(matrix, axes='sxyz'): """Return Euler angles from rotation matrix for specified axis sequence. axes : One of 24 axis sequences as string or encoded tuple Note that many Euler angle triplets can describe one matrix. >>> R0 = euler_matrix(1, 2, 3, 'syxz') >>> al, be, ga = euler_from_matrix(R0, 'syxz') >>> R1 = euler_matrix(al, be, ga, 'syxz') >>> np.allclose(R0, R1) True >>> angles = (4*math.pi) * (np.random.random(3) - 0.5) >>> for axes in _AXES2TUPLE.keys(): ... R0 = euler_matrix(axes=axes, *angles) ... R1 = euler_matrix(axes=axes, *euler_from_matrix(R0, axes)) ... if not np.allclose(R0, R1): print(axes, "failed") """ try: firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()] except (AttributeError, KeyError): _TUPLE2AXES[axes] # validation firstaxis, parity, repetition, frame = axes i = firstaxis j = _NEXT_AXIS[i + parity] k = _NEXT_AXIS[i - parity + 1] M = np.array(matrix, dtype=np.float64, copy=False)[:3, :3] if repetition: sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k]) if sy > _EPS: ax = math.atan2(M[i, j], M[i, k]) ay =
python
{ "resource": "" }
q23187
quaternion_from_euler
train
def quaternion_from_euler(ai, aj, ak, axes='sxyz'): """Return quaternion from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> q = quaternion_from_euler(1, 2, 3, 'ryxz') >>> np.allclose(q, [0.435953, 0.310622, -0.718287, 0.444435]) True """ try: firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()] except (AttributeError, KeyError): _TUPLE2AXES[axes] # validation firstaxis, parity, repetition, frame = axes i = firstaxis + 1 j = _NEXT_AXIS[i + parity - 1] + 1 k = _NEXT_AXIS[i - parity] + 1 if frame: ai, ak = ak, ai if parity: aj = -aj ai /= 2.0 aj /= 2.0 ak /= 2.0 ci = math.cos(ai) si = math.sin(ai) cj = math.cos(aj) sj = math.sin(aj) ck = math.cos(ak) sk = math.sin(ak) cc =
python
{ "resource": "" }
q23188
arcball_constrain_to_axis
train
def arcball_constrain_to_axis(point, axis): """Return sphere point perpendicular to axis.""" v = np.array(point, dtype=np.float64, copy=True) a = np.array(axis, dtype=np.float64, copy=True) v -= a * np.dot(a, v) # on plane n = vector_norm(v) if n > _EPS:
python
{ "resource": "" }
q23189
arcball_nearest_axis
train
def arcball_nearest_axis(point, axes): """Return axis, which arc is nearest to point.""" point = np.array(point, dtype=np.float64, copy=False)
python
{ "resource": "" }
q23190
vector_norm
train
def vector_norm(data, axis=None, out=None): """Return length, i.e. Euclidean norm, of ndarray along axis. >>> v = np.random.random(3) >>> n = vector_norm(v) >>> np.allclose(n, np.linalg.norm(v)) True >>> v = np.random.rand(6, 5, 3) >>> n = vector_norm(v, axis=-1) >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=2))) True >>> n = vector_norm(v, axis=1) >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=1))) True >>> v = np.random.rand(5, 4, 3) >>> n = np.empty((5, 3)) >>> vector_norm(v, axis=1, out=n) >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=1))) True >>> vector_norm([]) 0.0 >>> vector_norm([1]) 1.0
python
{ "resource": "" }
q23191
is_same_transform
train
def is_same_transform(matrix0, matrix1): """Return True if two matrices perform same transformation. >>> is_same_transform(np.identity(4), np.identity(4)) True >>> is_same_transform(np.identity(4), random_rotation_matrix()) False """ matrix0 =
python
{ "resource": "" }
q23192
is_same_quaternion
train
def is_same_quaternion(q0, q1): """Return True if two quaternions are equal."""
python
{ "resource": "" }
q23193
transform_around
train
def transform_around(matrix, point): """ Given a transformation matrix, apply its rotation around a point in space. Parameters ---------- matrix: (4,4) or (3, 3) float, transformation matrix point: (3,) or (2,) float, point in space Returns --------- result: (4,4) transformation matrix """ point = np.asanyarray(point) matrix = np.asanyarray(matrix) dim = len(point) if matrix.shape != (dim + 1, dim + 1):
python
{ "resource": "" }
q23194
planar_matrix
train
def planar_matrix(offset=None, theta=None, point=None): """ 2D homogeonous transformation matrix Parameters ---------- offset : (2,) float XY offset theta : float Rotation around Z in radians point : (2, ) float point to rotate around Returns ---------- matrix : (3, 3) flat Homogenous 2D transformation matrix """ if offset is None: offset = [0.0, 0.0] if theta is None: theta = 0.0 offset = np.asanyarray(offset, dtype=np.float64) theta = float(theta) if not np.isfinite(theta):
python
{ "resource": "" }
q23195
planar_matrix_to_3D
train
def planar_matrix_to_3D(matrix_2D): """ Given a 2D homogenous rotation matrix convert it to a 3D rotation matrix that is rotating around the Z axis Parameters ---------- matrix_2D: (3,3) float, homogenous 2D rotation matrix Returns ---------- matrix_3D: (4,4) float, homogenous 3D rotation matrix """ matrix_2D = np.asanyarray(matrix_2D, dtype=np.float64) if matrix_2D.shape != (3, 3):
python
{ "resource": "" }
q23196
transform_points
train
def transform_points(points, matrix, translate=True): """ Returns points, rotated by transformation matrix If points is (n,2), matrix must be (3,3) if points is (n,3), matrix must be (4,4) Parameters ---------- points : (n, d) float Points where d is 2 or 3 matrix : (3,3) or (4,4) float Homogenous rotation matrix translate : bool Apply translation from matrix or not Returns ---------- transformed : (n,d) float Transformed points """ points = np.asanyarray(points, dtype=np.float64) # no points no cry if len(points) == 0: return points.copy() matrix = np.asanyarray(matrix, dtype=np.float64) if (len(points.shape) != 2 or (points.shape[1] + 1 != matrix.shape[1])): raise ValueError('matrix
python
{ "resource": "" }
q23197
is_rigid
train
def is_rigid(matrix): """ Check to make sure a homogeonous transformation matrix is a rigid body transform. Parameters ----------- matrix: possibly a transformation matrix Returns ----------- check: bool, True if matrix is a valid (4,4) rigid body transform. """ matrix = np.asanyarray(matrix, dtype=np.float64) if matrix.shape != (4, 4):
python
{ "resource": "" }
q23198
Arcball.setaxes
train
def setaxes(self, *axes): """Set axes to constrain rotations.""" if axes is None: self._axes = None
python
{ "resource": "" }
q23199
Arcball.down
train
def down(self, point): """Set initial cursor window coordinates and pick constrain-axis.""" self._vdown = arcball_map_to_sphere(point, self._center, self._radius) self._qdown = self._qpre
python
{ "resource": "" }