_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q23000 | Path.layers | train | def layers(self):
"""
If entities have a layer defined, return it.
Returns
---------
layers: (len(entities), ) list of str
"""
layer = ['NONE'] * len(self.entities)
for i, | python | {
"resource": ""
} |
q23001 | Path.crc | train | def crc(self):
"""
A CRC of the current vertices and entities.
Returns
------------
crc: int, CRC of entity points and vertices
"""
# first CRC the points in every entity
target = caching.crc32(bytes().join(e._bytes()
| python | {
"resource": ""
} |
q23002 | Path.md5 | train | def md5(self):
"""
An MD5 hash of the current vertices and entities.
Returns
------------
md5: str, two appended MD5 hashes
"""
# first MD5 the points in every entity
target = '{}{}'.format(
| python | {
"resource": ""
} |
q23003 | Path.paths | train | def paths(self):
"""
Sequence of closed paths, encoded by entity index.
Returns
---------
paths: (n,) sequence of (*,) int referencing self.entities
"""
| python | {
"resource": ""
} |
q23004 | Path.dangling | train | def dangling(self):
"""
List of entities that aren't included in a closed path
Returns
----------
dangling: (n,) int, index of self.entities
"""
if len(self.paths) == 0:
return np.arange(len(self.entities))
| python | {
"resource": ""
} |
q23005 | Path.kdtree | train | def kdtree(self):
"""
A KDTree object holding the vertices of the path.
Returns
----------
kdtree: scipy.spatial.cKDTree object holding self.vertices
| python | {
"resource": ""
} |
q23006 | Path.scale | train | def scale(self):
"""
What is a representitive number that reflects the magnitude
of the world holding the paths, for numerical comparisons.
Returns
----------
scale : float
Approximate size of the | python | {
"resource": ""
} |
q23007 | Path.bounds | train | def bounds(self):
"""
Return the axis aligned bounding box of the current path.
Returns
----------
bounds: (2, dimension) float, (min, max) coordinates
"""
# get the exact bounds of each entity
# some entities (aka 3- point Arc) have bounds that can't
# be generated from just bound box of vertices
points = np.array([e.bounds(self.vertices)
for e in self.entities],
| python | {
"resource": ""
} |
q23008 | Path.explode | train | def explode(self):
"""
Turn every multi- segment entity into single segment entities, in- place
"""
new_entities = collections.deque()
| python | {
"resource": ""
} |
q23009 | Path.is_closed | train | def is_closed(self):
"""
Are all entities connected to other entities.
Returns
-----------
closed : bool
Every entity is connected at its ends
"""
| python | {
"resource": ""
} |
q23010 | Path.vertex_nodes | train | def vertex_nodes(self):
"""
Get a list of which vertex indices are nodes,
which are either endpoints or points where the
entity makes a direction change.
Returns
--------------
nodes : (n, 2) int | python | {
"resource": ""
} |
q23011 | Path.rezero | train | def rezero(self):
"""
Translate so that every vertex is positive in the current
mesh is positive.
Returns
-----------
matrix : (dimension + 1, dimension + 1) float
Homogenous transformation that was applied
to the current Path object.
| python | {
"resource": ""
} |
q23012 | Path.merge_vertices | train | def merge_vertices(self, digits=None):
"""
Merges vertices which are identical and replace references.
Parameters
--------------
digits : None, or int
How many digits to consider when merging vertices
Alters
-----------
self.entities : entity.points re- referenced
self.vertices : duplicates removed
"""
if len(self.vertices) == 0:
return
if digits is None:
digits = util.decimal_to_digits(tol.merge * self.scale,
min_digits=1)
unique, inverse = grouping.unique_rows(self.vertices,
digits=digits)
self.vertices = self.vertices[unique]
entities_ok = np.ones(len(self.entities), dtype=np.bool)
for index, entity in enumerate(self.entities):
# what kind of entity are we dealing with
kind = type(entity).__name__
# entities that don't need runs merged
# don't screw up control- point- knot relationship
if kind in 'BSpline Bezier Text':
entity.points = inverse[entity.points]
continue
| python | {
"resource": ""
} |
q23013 | Path.replace_vertex_references | train | def replace_vertex_references(self, mask):
"""
Replace the vertex index references in every entity.
Parameters
------------
mask : (len(self.vertices), ) int
Contains new vertex indexes
Alters
------------
| python | {
"resource": ""
} |
q23014 | Path.remove_entities | train | def remove_entities(self, entity_ids):
"""
Remove entities by index.
Parameters
-----------
entity_ids : (n,) int
Indexes of self.entities to remove
"""
if len(entity_ids) == 0: | python | {
"resource": ""
} |
q23015 | Path.remove_invalid | train | def remove_invalid(self):
"""
Remove entities which declare themselves invalid
Alters
----------
| python | {
"resource": ""
} |
q23016 | Path.remove_duplicate_entities | train | def remove_duplicate_entities(self):
"""
Remove entities that are duplicated
Alters
-------
self.entities: length same or shorter
"""
entity_hashes = np.array([hash(i) for i in self.entities])
unique, inverse = | python | {
"resource": ""
} |
q23017 | Path.referenced_vertices | train | def referenced_vertices(self):
"""
Which vertices are referenced by an entity.
Returns
-----------
referenced_vertices: (n,) int, indexes of self.vertices
"""
# no entities no reference
if len(self.entities) == 0:
| python | {
"resource": ""
} |
q23018 | Path.remove_unreferenced_vertices | train | def remove_unreferenced_vertices(self):
"""
Removes all vertices which aren't used by an entity.
Alters
---------
self.vertices: reordered and shortened
self.entities: entity.points references updated
"""
unique = self.referenced_vertices
mask = np.ones(len(self.vertices), | python | {
"resource": ""
} |
q23019 | Path.discretize_path | train | def discretize_path(self, path):
"""
Given a list of entities, return a list of connected points.
Parameters
-----------
path: (n,) int, indexes of self.entities
Returns
-----------
discrete: (m, dimension)
"""
discrete = traversal.discretize_path(self.entities,
| python | {
"resource": ""
} |
q23020 | Path.discrete | train | def discrete(self):
"""
A sequence of connected vertices in space, corresponding to
self.paths.
Returns
---------
discrete : (len(self.paths),)
A sequence of (m*, dimension) float
| python | {
"resource": ""
} |
q23021 | Path.export | train | def export(self,
file_obj=None,
file_type=None,
**kwargs):
"""
Export the path to a file object or return data.
Parameters
---------------
file_obj : None, str, or file object
File object or string to export to
file_type : None or str
Type of file: dxf, dict, svg
Returns
---------------
exported : bytes or | python | {
"resource": ""
} |
q23022 | Path.copy | train | def copy(self):
"""
Get a copy of the current mesh
Returns
---------
copied: Path object, copy of self
"""
metadata = {}
# grab all the keys into a list so if something is added
# in another thread it probably doesn't stomp on our loop
for key in list(self.metadata.keys()):
try:
metadata[key] = copy.deepcopy(self.metadata[key])
except RuntimeError:
# multiple threads
log.warning('key {} changed during copy'.format(key))
# copy the core data
copied = type(self)(entities=copy.deepcopy(self.entities),
vertices=copy.deepcopy(self.vertices),
metadata=metadata)
cache = {}
# try to copy the cache over to the new object
try:
# save dict keys before doing slow iteration
keys = list(self._cache.cache.keys())
| python | {
"resource": ""
} |
q23023 | Path3D.to_planar | train | def to_planar(self,
to_2D=None,
normal=None,
check=True):
"""
Check to see if current vectors are all coplanar.
If they are, return a Path2D and a transform which will
transform the 2D representation back into 3 dimensions
Parameters
-----------
to_2D: (4,4) float
Homogenous transformation matrix to apply,
If not passed a plane will be fitted to vertices.
normal: (3,) float, or None
Approximate normal of direction of plane
If to_2D is not specified sign
will be applied to fit plane normal
check: bool
If True: Raise a ValueError if
points aren't coplanar
Returns
-----------
planar : trimesh.path.Path2D
Current path transformed onto plane
to_3D : (4,4) float
Homeogenous transformation to move planar
back into 3D space
"""
# which vertices are actually referenced
referenced = self.referenced_vertices
# if nothing is referenced return an empty path
if len(referenced) == 0:
return Path2D(), np.eye(4)
# no explicit transform passed
if to_2D is None:
# fit a plane to our vertices
C, N = plane_fit(self.vertices[referenced])
# apply the normal sign hint
if normal is not None:
normal = np.asanyarray(normal, dtype=np.float64)
if normal.shape == (3,):
N *= np.sign(np.dot(N, normal))
N = normal
else:
log.warning(
"passed normal not used: {}".format(
normal.shape))
# create a transform from fit plane to XY
to_2D = plane_transform(origin=C,
normal=N)
# make sure we've extracted a transform
to_2D = np.asanyarray(to_2D, dtype=np.float64)
if to_2D.shape != (4, 4):
| python | {
"resource": ""
} |
q23024 | Path3D.plot_discrete | train | def plot_discrete(self, show=False):
"""
Plot closed curves
Parameters
------------
show : bool
If False will not execute matplotlib.pyplot.show
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # NOQA
| python | {
"resource": ""
} |
q23025 | Path3D.plot_entities | train | def plot_entities(self, show=False):
"""
Plot discrete version of entities without regards
for connectivity.
Parameters
-------------
show : bool
If False will not execute matplotlib.pyplot.show
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # NOQA | python | {
"resource": ""
} |
q23026 | Path2D.show | train | def show(self, annotations=True):
"""
Plot the current Path2D object using matplotlib.
"""
if self.is_closed:
| python | {
"resource": ""
} |
q23027 | Path2D.apply_obb | train | def apply_obb(self):
"""
Transform the current path so that its OBB is axis aligned
and OBB center is at the origin.
"""
if len(self.root) == 1:
matrix, bounds = polygons.polygon_obb(
self.polygons_closed[self.root[0]])
| python | {
"resource": ""
} |
q23028 | Path2D.to_3D | train | def to_3D(self, transform=None):
"""
Convert 2D path to 3D path on the XY plane.
Parameters
-------------
transform : (4, 4) float
If passed, will transform vertices.
If not passed and 'to_3D' is in metadata
that transform will be used.
Returns
-----------
path_3D: Path3D version of current path
"""
# if there is a stored 'to_3D' transform in metadata use it
if transform is None and 'to_3D' in self.metadata:
transform = self.metadata['to_3D']
# copy vertices and stack with zeros from (n, 2) to (n, 3)
vertices = np.column_stack((copy.deepcopy(self.vertices),
| python | {
"resource": ""
} |
q23029 | Path2D.polygons_full | train | def polygons_full(self):
"""
A list of shapely.geometry.Polygon objects with interiors created
by checking which closed polygons enclose which other polygons.
Returns
---------
full : (len(self.root),) shapely.geometry.Polygon
Polygons containing interiors
"""
# pre- allocate the list to avoid indexing problems
full = [None] * len(self.root)
# store the graph to avoid cache thrashing
enclosure = self.enclosure_directed
# store closed polygons to avoid cache hits
closed = self.polygons_closed
# loop through root curves
for i, root in enumerate(self.root):
# a list of multiple Polygon objects that
# are fully contained by the root curve
children = [closed[child]
for child in enclosure[root].keys()]
# all polygons_closed are CCW, so for interiors reverse them
| python | {
"resource": ""
} |
q23030 | Path2D.area | train | def area(self):
"""
Return the area of the polygons interior.
Returns
---------
area: float, total area of polygons minus interiors
| python | {
"resource": ""
} |
q23031 | Path2D.length | train | def length(self):
"""
The total discretized length of every entity.
Returns
--------
length: float, summed length of every entity
| python | {
"resource": ""
} |
q23032 | Path2D.extrude | train | def extrude(self, height, **kwargs):
"""
Extrude the current 2D path into a 3D mesh.
Parameters
----------
height: float, how far to extrude the profile
kwargs: passed directly to meshpy.triangle.build:
triangle.build(mesh_info,
verbose=False,
refinement_func=None,
attributes=False,
volume_constraints=True,
max_volume=None,
allow_boundary_steiner=True,
allow_volume_steiner=True,
quality_meshing=True,
| python | {
"resource": ""
} |
q23033 | Path2D.triangulate | train | def triangulate(self, **kwargs):
"""
Create a region- aware triangulation of the 2D path.
Parameters
-------------
**kwargs : dict
Passed to trimesh.creation.triangulate_polygon
Returns
-------------
vertices : (n, 2) float
2D vertices of triangulation
faces : (n, 3) int
Indexes of vertices for triangles
"""
from ..creation import triangulate_polygon
# append vertices and faces into sequence
| python | {
"resource": ""
} |
q23034 | Path2D.medial_axis | train | def medial_axis(self, resolution=None, clip=None):
"""
Find the approximate medial axis based
on a voronoi diagram of evenly spaced points on the
boundary of the polygon.
Parameters
----------
resolution : None or float
Distance between each sample on the polygon boundary
clip : None, or (2,) float
Min, max number of samples
Returns
----------
medial : Path2D object
Contains only medial axis of Path
"""
if resolution is None:
resolution = self.scale / 1000.0
| python | {
"resource": ""
} |
q23035 | Path2D.connected_paths | train | def connected_paths(self, path_id, include_self=False):
"""
Given an index of self.paths find other paths which
overlap with that path.
Parameters
-----------
path_id : int
Index of self.paths
include_self : bool
Should the result include path_id or not
Returns
-----------
path_ids : (n, ) int
Indexes of self.paths that overlap input path_id
"""
if len(self.root) == 1: | python | {
"resource": ""
} |
q23036 | Path2D.simplify_spline | train | def simplify_spline(self, path_indexes=None, smooth=.0002):
"""
Convert paths into b-splines.
Parameters
-----------
path_indexes : (n) int
List of indexes of self.paths to convert
| python | {
"resource": ""
} |
q23037 | Path2D.plot_discrete | train | def plot_discrete(self, show=False, annotations=True):
"""
Plot the closed curves of the path.
"""
import matplotlib.pyplot as plt
axis = plt.axes()
axis.set_aspect('equal', 'datalim')
for i, points in enumerate(self.discrete):
color = ['g', 'k'][i in self.root]
axis.plot(*points.T, color=color) | python | {
"resource": ""
} |
q23038 | Path2D.plot_entities | train | def plot_entities(self, show=False, annotations=True, color=None):
"""
Plot the entities of the path, with no notion of topology
"""
import matplotlib.pyplot as plt
plt.axes().set_aspect('equal', 'datalim')
eformat = {'Line0': {'color': 'g', 'linewidth': 1},
'Line1': {'color': 'y', 'linewidth': 1},
'Arc0': {'color': 'r', 'linewidth': 1},
'Arc1': {'color': 'b', 'linewidth': 1},
'Bezier0': {'color': 'k', 'linewidth': 1},
'Bezier1': {'color': 'k', 'linewidth': 1},
'BSpline0': {'color': 'm', 'linewidth': 1},
'BSpline1': {'color': 'm', 'linewidth': 1}}
for entity in self.entities:
if annotations and hasattr(entity, 'plot'):
entity.plot(self.vertices)
continue
discrete = entity.discrete(self.vertices)
| python | {
"resource": ""
} |
q23039 | Path2D.identifier | train | def identifier(self):
"""
A unique identifier for the path.
Returns
---------
identifier: (5,) float, unique identifier
"""
if len(self.polygons_full) != 1:
raise | python | {
"resource": ""
} |
q23040 | Path2D.identifier_md5 | train | def identifier_md5(self):
"""
Return an MD5 of the identifier
"""
as_int = (self.identifier * 1e4).astype(np.int64)
| python | {
"resource": ""
} |
q23041 | Path2D.enclosure_directed | train | def enclosure_directed(self):
"""
Networkx DiGraph of polygon enclosure
| python | {
"resource": ""
} |
q23042 | Path2D.enclosure_shell | train | def enclosure_shell(self):
"""
A dictionary of path indexes which are 'shell' paths, and values
of 'hole' paths.
Returns
----------
corresponding: dict, {index of self.paths of shell : [indexes of holes]}
"""
pairs = [(r, self.connected_paths(r, include_self=False))
| python | {
"resource": ""
} |
q23043 | log_time | train | def log_time(method):
"""
A decorator for methods which will time the method
and then emit a log.debug message with the method name
and how long it took to execute.
"""
def timed(*args, **kwargs):
tic = time_function()
result = method(*args, **kwargs)
log.debug('%s executed in %.4f seconds.', | python | {
"resource": ""
} |
q23044 | nearby_faces | train | def nearby_faces(mesh, points):
"""
For each point find nearby faces relatively quickly.
The closest point on the mesh to the queried point is guaranteed to be
on one of the faces listed.
Does this by finding the nearest vertex on the mesh to each point, and
then returns all the faces that intersect the axis aligned bounding box
centered at the queried point and extending to the nearest vertex.
Parameters
----------
mesh : Trimesh object
points : (n,3) float , points in space
Returns
-----------
candidates : (points,) int, sequence of indexes for mesh.faces
"""
points = np.asanyarray(points, dtype=np.float64)
if not util.is_shape(points, (-1, 3)):
raise ValueError('points must be (n,3)!')
# an r-tree containing the axis aligned bounding box for every triangle
rtree = mesh.triangles_tree
# a | python | {
"resource": ""
} |
q23045 | signed_distance | train | def signed_distance(mesh, points):
"""
Find the signed distance from a mesh to a list of points.
* Points OUTSIDE the mesh will have NEGATIVE distance
* Points within tol.merge of the surface will have POSITIVE distance
* Points INSIDE the mesh will have POSITIVE distance
Parameters
-----------
mesh : Trimesh object
points : (n,3) float, list of points in space
Returns
----------
signed_distance : (n,3) float, signed distance from point to mesh
"""
# make sure we have a numpy array
points = np.asanyarray(points, dtype=np.float64)
# find the closest point on the mesh to the queried points
closest, distance, triangle_id = closest_point(mesh, points)
# we | python | {
"resource": ""
} |
q23046 | longest_ray | train | def longest_ray(mesh, points, directions):
"""
Find the lengths of the longest rays which do not intersect the mesh
cast from a list of points in the provided directions.
Parameters
-----------
points : (n,3) float, list of points in space
directions : (n,3) float, directions of rays
Returns
----------
signed_distance : (n,) float, length of rays
"""
points = np.asanyarray(points, dtype=np.float64)
if not util.is_shape(points, (-1, 3)):
raise ValueError('points must be (n,3)!')
directions = np.asanyarray(directions, dtype=np.float64)
if not util.is_shape(directions, (-1, 3)):
raise ValueError('directions must be (n,3)!')
if len(points) != len(directions):
raise ValueError('number of points must equal number of directions!')
faces, rays, locations = mesh.ray.intersects_id(points, directions,
return_locations=True,
multiple_hits=True)
| python | {
"resource": ""
} |
q23047 | thickness | train | def thickness(mesh,
points,
exterior=False,
normals=None,
method='max_sphere'):
"""
Find the thickness of the mesh at the given points.
Parameters
----------
points : (n,3) float, list of points in space
exterior : bool, whether to compute the exterior thickness
(a.k.a. reach)
normals : (n,3) float, normals of the mesh at the given points
None, compute this automatically.
method : string, one of 'max_sphere' or 'ray'
Returns
----------
thickness : (n,) float, thickness
"""
points = np.asanyarray(points, dtype=np.float64)
if not util.is_shape(points, (-1, 3)):
| python | {
"resource": ""
} |
q23048 | ProximityQuery.vertex | train | def vertex(self, points):
"""
Given a set of points, return the closest vertex index to each point
Parameters
----------
points : (n,3) float, list of points in space
Returns
----------
distance : (n,) float, | python | {
"resource": ""
} |
q23049 | procrustes | train | def procrustes(a,
b,
reflection=True,
translation=True,
scale=True,
return_cost=True):
"""
Perform Procrustes' analysis subject to constraints. Finds the
transformation T mapping a to b which minimizes the square sum
distances between Ta and b, also called the cost.
Parameters
----------
a : (n,3) float
List of points in space
b : (n,3) float
List of points in space
reflection : bool
If the transformation is allowed reflections
translation : bool
If the transformation is allowed translations
scale : bool
If the transformation is allowed scaling
return_cost : bool
Whether to return the cost and transformed a as well
Returns
----------
matrix : (4,4) float
The transformation matrix sending a to b
transformed : (n,3) float
The image of a under the transformation
cost : float
The cost of the transformation
"""
a = np.asanyarray(a, dtype=np.float64)
b = np.asanyarray(b, dtype=np.float64)
if not util.is_shape(a, (-1, 3)) or not util.is_shape(b, (-1, 3)):
raise ValueError('points must be (n,3)!')
if len(a) != len(b):
raise ValueError('a and b must contain same number of points!')
# Remove translation component
if translation:
acenter = a.mean(axis=0)
bcenter = b.mean(axis=0)
else:
acenter = np.zeros(a.shape[1])
bcenter = np.zeros(b.shape[1])
# Remove scale component
if scale:
ascale = np.sqrt(((a - | python | {
"resource": ""
} |
q23050 | concatenate | train | def concatenate(visuals, *args):
"""
Concatenate multiple visual objects.
Parameters
----------
visuals: ColorVisuals object, or list of same
*args: ColorVisuals object, or list of same
Returns
----------
concat: ColorVisuals object
"""
# get a flat list of ColorVisuals objects
if len(args) > 0:
visuals = np.append(visuals, args)
else:
visuals = np.array(visuals)
# get the type of visuals (vertex or face) removing undefined
modes = {v.kind for v in visuals}.difference({None})
if len(modes) == 0:
# none of the visuals have anything defined
return ColorVisuals()
else:
# if we have visuals with different modes defined
| python | {
"resource": ""
} |
q23051 | to_rgba | train | def to_rgba(colors, dtype=np.uint8):
"""
Convert a single or multiple RGB colors to RGBA colors.
Parameters
----------
colors: (n,[3|4]) list of RGB or RGBA colors
Returns
----------
colors: (n,4) list of RGBA colors
(4,) single RGBA color
"""
if not util.is_sequence(colors):
return
# colors as numpy array
colors = np.asanyarray(colors)
# integer value for opaque alpha given our datatype
opaque = np.iinfo(dtype).max
if (colors.dtype.kind == 'f' and colors.max() < (1.0 + 1e-8)):
colors = (colors * opaque).astype(dtype)
elif (colors.max() <= opaque):
colors = colors.astype(dtype)
else:
raise ValueError('colors non- convertible!')
if util.is_shape(colors, (-1, 3)):
| python | {
"resource": ""
} |
q23052 | random_color | train | def random_color(dtype=np.uint8):
"""
Return a random RGB color using datatype specified.
Parameters
----------
dtype: numpy dtype of result
Returns
----------
color: (4,) dtype, random color that looks OK
"""
hue = np.random.random() + .61803
hue %= 1.0
color = np.array(colorsys.hsv_to_rgb(hue, .99, .99))
| python | {
"resource": ""
} |
q23053 | vertex_to_face_color | train | def vertex_to_face_color(vertex_colors, faces):
"""
Convert a list of vertex colors to face colors.
Parameters
----------
vertex_colors: (n,(3,4)), colors
faces: (m,3) int, face indexes
Returns
-----------
face_colors: (m,4) | python | {
"resource": ""
} |
q23054 | face_to_vertex_color | train | def face_to_vertex_color(mesh, face_colors, dtype=np.uint8):
"""
Convert a list of face colors into a list of vertex colors.
Parameters
-----------
mesh : trimesh.Trimesh object
face_colors: (n, (3,4)) int, face colors
dtype: data type of output
Returns
-----------
vertex_colors: (m,4) dtype, colors for each | python | {
"resource": ""
} |
q23055 | colors_to_materials | train | def colors_to_materials(colors, count=None):
"""
Convert a list of colors into a list of unique materials
and material indexes.
Parameters
-----------
colors : (n, 3) or (n, 4) float
RGB or RGBA colors
count : int
Number of entities to apply color to
Returns
-----------
diffuse : (m, 4) int
Colors
index : (count,) int
Index of each color
"""
# convert RGB to RGBA
rgba = to_rgba(colors)
# if we were only passed a single color
if util.is_shape(rgba, (4,)) and count is not None:
diffuse = rgba.reshape((-1, 4))
index = | python | {
"resource": ""
} |
q23056 | linear_color_map | train | def linear_color_map(values, color_range=None):
"""
Linearly interpolate between two colors.
If colors are not specified the function will
interpolate between 0.0 values as red and 1.0 as green.
Parameters
--------------
values : (n, ) float
Values to interpolate
color_range : None, or (2, 4) uint8
What colors should extrema be set to
Returns
---------------
colors : (n, 4) uint8
RGBA colors for interpolated values
"""
if color_range is None:
color_range = np.array([[255, 0, 0, 255],
[0, 255, 0, 255]],
dtype=np.uint8)
else:
color_range = np.asanyarray(color_range,
dtype=np.uint8)
if color_range.shape != (2, 4):
raise ValueError('color_range must be | python | {
"resource": ""
} |
q23057 | interpolate | train | def interpolate(values, color_map=None, dtype=np.uint8):
"""
Given a 1D list of values, return interpolated colors
for the range.
Parameters
---------------
values : (n, ) float
Values to be interpolated over
color_map : None, or str
Key to a colormap contained in:
matplotlib.pyplot.colormaps()
e.g: 'viridis'
Returns
-------------
interpolated : (n, 4) dtype
Interpolated RGBA colors
"""
# get a color interpolation function
if color_map is None:
cmap = linear_color_map
else:
from matplotlib.pyplot | python | {
"resource": ""
} |
q23058 | ColorVisuals.transparency | train | def transparency(self):
"""
Does the current object contain any transparency.
Returns
----------
transparency: bool, does the current visual contain transparency
"""
if 'vertex_colors' in self._data:
a_min = self._data['vertex_colors'][:, | python | {
"resource": ""
} |
q23059 | ColorVisuals.kind | train | def kind(self):
"""
What color mode has been set.
Returns
----------
mode: 'face', 'vertex', or None
"""
self._verify_crc()
if 'vertex_colors' in self._data:
mode = 'vertex' | python | {
"resource": ""
} |
q23060 | ColorVisuals.crc | train | def crc(self):
"""
A checksum for the current visual object and its parent mesh.
Returns
----------
crc: int, checksum of data in visual object and its parent mesh
"""
# will make sure everything has been transferred
# to datastore that needs to be before returning crc
| python | {
"resource": ""
} |
q23061 | ColorVisuals.copy | train | def copy(self):
"""
Return a copy of the current ColorVisuals object.
Returns
----------
copied : ColorVisuals
Contains the same information as self
"""
| python | {
"resource": ""
} |
q23062 | ColorVisuals.face_colors | train | def face_colors(self, values):
"""
Set the colors for each face of a mesh.
This will apply these colors and delete any previously specified
color information.
Parameters
------------
colors: (len(mesh.faces), 3), set each face to the specified color
(len(mesh.faces), 4), set each face to the specified color
(3,) int, set the whole mesh this color
(4,) int, set the whole mesh this color
"""
if values is None:
if 'face_colors' in self._data:
| python | {
"resource": ""
} |
q23063 | ColorVisuals.vertex_colors | train | def vertex_colors(self, values):
"""
Set the colors for each vertex of a mesh
This will apply these colors and delete any previously specified
color information.
Parameters
------------
colors: (len(mesh.vertices), 3), set each face to the color
(len(mesh.vertices), 4), set each face to the color
(3,) int, set the whole mesh this color
(4,) int, set the whole mesh this color
"""
if values is None:
if 'vertex_colors' in self._data:
self._data.data.pop('vertex_colors')
return
# make sure passed values are numpy array
values = np.asanyarray(values)
# Ensure the color shape is sane
if (self.mesh is not None and not
(values.shape == (len(self.mesh.vertices), 3) or
values.shape == (len(self.mesh.vertices), 4) or
| python | {
"resource": ""
} |
q23064 | ColorVisuals._get_colors | train | def _get_colors(self,
name):
"""
A magical function which maintains the sanity of vertex and face colors.
* If colors have been explicitly stored or changed, they are considered
user data, stored in self._data (DataStore), and are returned immediately
when requested.
* If colors have never been set, a (count,4) tiled copy of the default diffuse
color will be stored in the cache
** the CRC on creation for these cached default colors will also be stored
** if the cached color array is altered (different CRC than when it was
created) we consider that now to be user data and the array is moved from
the cache to the DataStore.
Parameters
-----------
name: str, 'face', or 'vertex'
Returns
-----------
colors: (count, 4) uint8, RGBA colors
"""
try:
counts = {'face': len(self.mesh.faces),
'vertex': len(self.mesh.vertices)}
count = counts[name]
except AttributeError:
count = None
# the face or vertex colors
key_colors = str(name) + '_colors'
# the initial crc of the
key_crc = key_colors + '_crc'
if key_colors in self._data:
# if a user has explicitly stored or changed the color it
# will be in data
return self._data[key_colors]
elif key_colors in self._cache:
# if the colors have been autogenerated already they
# will be in the cache
colors = self._cache[key_colors]
# if the cached colors have been changed since creation we move
# them to data
if colors.crc() != self._cache[key_crc]:
# call the setter on the property using exec
# this avoids having to pass a setter to this function
if name == 'face':
self.face_colors = colors
elif name == 'vertex':
self.vertex_colors = colors
| python | {
"resource": ""
} |
q23065 | ColorVisuals._verify_crc | train | def _verify_crc(self):
"""
Verify the checksums of cached face and vertex color, to verify
that a user hasn't altered them since they were generated from
defaults.
If the colors have been altered since creation, move them into
the DataStore at self._data since the user action has made them
user data.
"""
if not hasattr(self, '_cache') or len(self._cache) == 0:
return
for name in ['face', 'vertex']:
# the face or vertex colors
key_colors = str(name) + '_colors'
# the initial crc of the
key_crc = key_colors + '_crc'
if key_colors not in self._cache:
continue
colors = self._cache[key_colors]
# if the cached colors have been changed since creation
| python | {
"resource": ""
} |
q23066 | ColorVisuals.face_subset | train | def face_subset(self, face_index):
"""
Given a mask of face indices, return a sliced version.
Parameters
----------
face_index: (n,) int, mask for faces
(n,) bool, mask for faces
Returns
----------
visual: ColorVisuals object containing a | python | {
"resource": ""
} |
q23067 | ColorVisuals.main_color | train | def main_color(self):
"""
What is the most commonly occurring color.
Returns
------------
color: (4,) uint8, most common color
"""
if self.kind is None:
return DEFAULT_COLOR
elif self.kind == 'face':
colors = self.face_colors
elif self.kind == 'vertex':
colors = self.vertex_colors
else:
raise ValueError('color kind incorrect!')
# find the unique colors
| python | {
"resource": ""
} |
q23068 | ColorVisuals.concatenate | train | def concatenate(self, other, *args):
"""
Concatenate two or more ColorVisuals objects into a single object.
Parameters
-----------
other : ColorVisuals
Object to append
*args: ColorVisuals objects
Returns
-----------
result: ColorVisuals object containing information from current | python | {
"resource": ""
} |
q23069 | ColorVisuals._update_key | train | def _update_key(self, mask, key):
"""
Mask the value contained in the DataStore at a specified key.
Parameters
-----------
mask: (n,) int
(n,) bool
key: | python | {
"resource": ""
} |
q23070 | Trimesh.process | train | def process(self):
"""
Do the bare minimum processing to make a mesh useful.
Does this by:
1) removing NaN and Inf values
2) merging duplicate vertices
If self._validate:
3) Remove triangles which have one edge of their rectangular 2D
oriented bounding box shorter than tol.merge
4) remove duplicated triangles
Returns
------------
self: trimesh.Trimesh
Current mesh
"""
# if there are no vertices or faces exit early
if self.is_empty:
return self
# avoid clearing the cache during operations
with self._cache:
self.remove_infinite_values()
self.merge_vertices()
# if we're cleaning remove duplicate
# and degenerate faces
if self._validate:
self.remove_duplicate_faces()
| python | {
"resource": ""
} |
q23071 | Trimesh.faces | train | def faces(self, values):
"""
Set the vertex indexes that make up triangular faces.
Parameters
--------------
values : (n, 3) int
Indexes of self.vertices
"""
if values is None:
values = []
values = np.asanyarray(values, dtype=np.int64)
| python | {
"resource": ""
} |
q23072 | Trimesh.faces_sparse | train | def faces_sparse(self):
"""
A sparse matrix representation of the faces.
Returns
----------
sparse : scipy.sparse.coo_matrix
Has properties:
dtype : bool
shape : (len(self.vertices), len(self.faces)) | python | {
"resource": ""
} |
q23073 | Trimesh.face_normals | train | def face_normals(self):
"""
Return the unit normal vector for each face.
If a face is degenerate and a normal can't be generated
a zero magnitude unit vector will be returned for that face.
Returns
-----------
normals : (len(self.faces), 3) np.float64
Normal vectors of each face
"""
# check shape of cached normals
cached = self._cache['face_normals']
if np.shape(cached) == np.shape(self._data['faces']):
return cached
log.debug('generating face normals')
# use cached triangle cross products to generate normals
| python | {
"resource": ""
} |
q23074 | Trimesh.face_normals | train | def face_normals(self, values):
"""
Assign values to face normals.
Parameters
-------------
values : (len(self.faces), 3) float
Unit face normals
"""
if values is not None:
# make sure face normals are C- contiguous float
values = np.asanyarray(values,
order='C',
dtype=np.float64)
# check if any values are larger than tol.merge
# this check is equivalent to but 25% faster than:
# `np.abs(values) > tol.merge`
nonzero = np.logical_or(values > tol.merge,
values < -tol.merge)
# don't set the normals if they are all zero
if not nonzero.any():
log.warning('face_normals all zero, ignoring!')
| python | {
"resource": ""
} |
q23075 | Trimesh.vertices | train | def vertices(self, values):
"""
Assign vertex values to the mesh.
Parameters
--------------
values : (n, 3) float
Points in space
"""
self._data['vertices'] = np.asanyarray(values,
| python | {
"resource": ""
} |
q23076 | Trimesh.vertex_normals | train | def vertex_normals(self):
"""
The vertex normals of the mesh. If the normals were loaded
we check to make sure we have the same number of vertex
normals and vertices before returning them. If there are
no vertex normals defined or a shape mismatch we calculate
the vertex normals from the mean normals of the faces the
vertex is used in.
Returns
----------
vertex_normals : (n,3) float
Represents the surface normal at each vertex.
Where n | python | {
"resource": ""
} |
q23077 | Trimesh.vertex_normals | train | def vertex_normals(self, values):
"""
Assign values to vertex normals
Parameters
-------------
values : (len(self.vertices), 3) float
Unit normal vectors for each vertex
"""
if values is not None:
values = np.asanyarray(values,
| python | {
"resource": ""
} |
q23078 | Trimesh.bounds | train | def bounds(self):
"""
The axis aligned bounds of the faces of the mesh.
Returns
-----------
bounds : (2, 3) float
Bounding box with [min, max] coordinates
"""
# return bounds including ONLY referenced vertices
in_mesh = self.vertices[self.referenced_vertices]
# get mesh bounds with min and max
| python | {
"resource": ""
} |
q23079 | Trimesh.extents | train | def extents(self):
"""
The length, width, and height of the bounding box of the mesh.
Returns
-----------
extents : (3,) float
Array containing axis aligned [length, width, height]
| python | {
"resource": ""
} |
q23080 | Trimesh.centroid | train | def centroid(self):
"""
The point in space which is the average of the triangle centroids
weighted by the area of each triangle.
This will be valid even for non- watertight meshes,
unlike self.center_mass
Returns
----------
centroid : (3,) float
The average vertex weighted by face area
"""
# use the centroid of each triangle weighted by
# the area of the triangle to find the overall | python | {
"resource": ""
} |
q23081 | Trimesh.density | train | def density(self, value):
"""
Set the density of the mesh.
Parameters
-------------
density : float
Specify the density of the | python | {
"resource": ""
} |
q23082 | Trimesh.principal_inertia_components | train | def principal_inertia_components(self):
"""
Return the principal components of inertia
Ordering corresponds to mesh.principal_inertia_vectors
Returns
----------
components : (3,) float
Principal components of inertia
"""
# both | python | {
"resource": ""
} |
q23083 | Trimesh.principal_inertia_transform | train | def principal_inertia_transform(self):
"""
A transform which moves the current mesh so the principal
inertia vectors are on the X,Y, and Z axis, and the centroid is
at the origin.
Returns
----------
transform : (4, 4) float
Homogenous transformation matrix
"""
order = np.argsort(self.principal_inertia_components)[1:][::-1]
vectors = self.principal_inertia_vectors[order]
| python | {
"resource": ""
} |
q23084 | Trimesh.edges_unique | train | def edges_unique(self):
"""
The unique edges of the mesh.
Returns
----------
edges_unique : (n, 2) int
Vertex indices for unique edges
"""
unique, inverse = grouping.unique_rows(self.edges_sorted)
edges_unique = self.edges_sorted[unique]
# edges_unique will be added automatically by the decorator
| python | {
"resource": ""
} |
q23085 | Trimesh.edges_unique_length | train | def edges_unique_length(self):
"""
How long is each unique edge.
Returns
----------
length : (len(self.edges_unique), ) float
Length of each unique edge
"""
vector = | python | {
"resource": ""
} |
q23086 | Trimesh.edges_sparse | train | def edges_sparse(self):
"""
Edges in sparse bool COO graph format where connected
vertices are True.
Returns
----------
sparse: (len(self.vertices), len(self.vertices)) bool
Sparse graph in COO format
"""
| python | {
"resource": ""
} |
q23087 | Trimesh.body_count | train | def body_count(self):
"""
How many connected groups of vertices exist in this mesh.
Note that this number may differ from result in mesh.split,
which is calculated from FACE rather than vertex adjacency.
Returns
| python | {
"resource": ""
} |
q23088 | Trimesh.faces_unique_edges | train | def faces_unique_edges(self):
"""
For each face return which indexes in mesh.unique_edges constructs
that face.
Returns
---------
faces_unique_edges : (len(self.faces), 3) int
Indexes of self.edges_unique that
construct self.faces
Examples
---------
In [0]: mesh.faces[0:2]
Out[0]:
TrackedArray([[ 1, 6946, 24224],
[ 6946, 1727, 24225]])
In [1]: mesh.edges_unique[mesh.faces_unique_edges[0:2]]
Out[1]:
array([[[ 1, 6946],
[ 6946, 24224],
[ 1, 24224]],
[[ 1727, 6946],
| python | {
"resource": ""
} |
q23089 | Trimesh.referenced_vertices | train | def referenced_vertices(self):
"""
Which vertices in the current mesh are referenced by a face.
Returns
-------------
referenced : (len(self.vertices),) bool
Which vertices are referenced by a face
"""
| python | {
"resource": ""
} |
q23090 | Trimesh.convert_units | train | def convert_units(self, desired, guess=False):
"""
Convert the units of the mesh into a specified unit.
Parameters
----------
desired : string
Units to convert to (eg 'inches')
guess : boolean
| python | {
"resource": ""
} |
q23091 | Trimesh.merge_vertices | train | def merge_vertices(self, digits=None, textured=True):
"""
If a mesh has vertices that are closer than
trimesh.constants.tol.merge reindex faces to reference
the same index for both vertices.
Parameters
| python | {
"resource": ""
} |
q23092 | Trimesh.update_vertices | train | def update_vertices(self, mask, inverse=None):
"""
Update vertices with a mask.
Parameters
----------
vertex_mask : (len(self.vertices)) bool
Array of which vertices to keep
inverse : (len(self.vertices)) int
Array to reconstruct vertex references
such as output by np.unique
"""
# if the mesh is already empty we can't remove anything
if self.is_empty:
return
# make sure mask is a numpy array
mask = np.asanyarray(mask)
if ((mask.dtype.name == 'bool' and mask.all()) or
len(mask) == 0 or self.is_empty):
# mask doesn't remove any vertices so exit early
return
# create the inverse mask if not passed
if inverse is None:
inverse = np.zeros(len(self.vertices), dtype=np.int64)
if mask.dtype.kind == 'b':
inverse[mask] = np.arange(mask.sum())
elif mask.dtype.kind == 'i':
inverse[mask] = np.arange(len(mask))
else:
| python | {
"resource": ""
} |
q23093 | Trimesh.update_faces | train | def update_faces(self, mask):
"""
In many cases, we will want to remove specific faces.
However, there is additional bookkeeping to do this cleanly.
This function updates the set of faces with a validity mask,
as well as keeping track of normals and colors.
Parameters
---------
valid : (m) int or (len(self.faces)) bool
Mask to remove faces
"""
# if the mesh is already empty we can't remove anything
if self.is_empty:
return
mask = np.asanyarray(mask)
if mask.dtype.name == 'bool' and mask.all():
# mask removes no faces so exit early
return
# try to save face normals before dumping cache
| python | {
"resource": ""
} |
q23094 | Trimesh.remove_infinite_values | train | def remove_infinite_values(self):
"""
Ensure that every vertex and face consists of finite numbers.
This will remove vertices or faces containing np.nan and np.inf
Alters
----------
self.faces : masked to remove np.inf/np.nan
self.vertices : masked to remove np.inf/np.nan
| python | {
"resource": ""
} |
q23095 | Trimesh.remove_duplicate_faces | train | def remove_duplicate_faces(self):
"""
On the current mesh remove any faces which are duplicates.
Alters
----------
self.faces : removes duplicates
"""
| python | {
"resource": ""
} |
q23096 | Trimesh.split | train | def split(self, only_watertight=True, adjacency=None, **kwargs):
"""
Returns a list of Trimesh objects, based on face connectivity.
Splits into individual components, sometimes referred to as 'bodies'
Parameters
---------
only_watertight : bool
Only return watertight meshes and discard remainder
adjacency : None or (n, 2) int
Override face adjacency with custom values
Returns
---------
meshes : (n,) trimesh.Trimesh
| python | {
"resource": ""
} |
q23097 | Trimesh.face_adjacency | train | def face_adjacency(self):
"""
Find faces that share an edge, which we call here 'adjacent'.
Returns
----------
adjacency : (n,2) int
Pairs of faces which share an edge
Examples
---------
In [1]: mesh = trimesh.load('models/featuretype.STL')
In [2]: mesh.face_adjacency
Out[2]:
array([[ 0, 1],
[ 2, 3],
[ 0, 3],
...,
[1112, 949],
[3467, 3475],
[1113, 3475]])
In [3]: mesh.faces[mesh.face_adjacency[0]]
Out[3]:
TrackedArray([[ 1, 0, 408],
[1239, 0, | python | {
"resource": ""
} |
q23098 | Trimesh.face_adjacency_angles | train | def face_adjacency_angles(self):
"""
Return the angle between adjacent faces
Returns
--------
adjacency_angle : (n,) float
Angle between adjacent faces
Each value corresponds with self.face_adjacency
| python | {
"resource": ""
} |
q23099 | Trimesh.face_adjacency_radius | train | def face_adjacency_radius(self):
"""
The approximate radius of a cylinder that fits inside adjacent faces.
Returns
------------
radii : (len(self.face_adjacency),) float
Approximate radius formed by triangle pair
"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.