_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q23300 | boolean_sparse | train | def boolean_sparse(a, b, operation=np.logical_and):
"""
Find common rows between two arrays very quickly
using 3D boolean sparse matrices.
Parameters
-----------
a: (n, d) int, coordinates in space
b: (m, d) int, coordinates in space
operation: numpy operation function, ie:
... | python | {
"resource": ""
} |
q23301 | VoxelBase.marching_cubes | train | def marching_cubes(self):
"""
A marching cubes Trimesh representation of the voxels.
No effort was made to clean or smooth the result in any way;
it is merely the result of applying the scikit-image
measure.marching_cubes function to self.matrix.
Returns
-------... | python | {
"resource": ""
} |
q23302 | VoxelBase.points | train | def points(self):
"""
The center of each filled cell as a list of points.
Returns
----------
points: (self.filled, 3) float, list of points
"""
points = matrix_to_points(matrix=self.matrix,
pitch=self.pitch,
... | python | {
"resource": ""
} |
q23303 | VoxelBase.point_to_index | train | def point_to_index(self, point):
"""
Convert a point to an index in the matrix array.
Parameters
----------
point: (3,) float, point in space
Returns
---------
index: (3,) int tuple, index in self.matrix
"""
indices = points_to_indices(po... | python | {
"resource": ""
} |
q23304 | VoxelBase.is_filled | train | def is_filled(self, point):
"""
Query a point to see if the voxel cell it lies in is filled or not.
Parameters
----------
point: (3,) float, point in space
Returns
---------
is_filled: bool, is cell occupied or not
"""
index = self.point_... | python | {
"resource": ""
} |
q23305 | VoxelMesh.sparse_surface | train | def sparse_surface(self):
"""
Filled cells on the surface of the mesh.
Returns
----------------
voxels: (n, 3) int, filled cells on mesh surface
"""
if self._method == 'ray':
func = voxelize_ray
elif self._method == 'subdivide':
fu... | python | {
"resource": ""
} |
q23306 | simulated_brick | train | def simulated_brick(face_count, extents, noise, max_iter=10):
"""
Produce a mesh that is a rectangular solid with noise
with a random transform.
Parameters
-------------
face_count : int
Approximate number of faces desired
extents : (n,3) float
Dimensions of brick
noise : fl... | python | {
"resource": ""
} |
q23307 | unitize | train | def unitize(vectors,
check_valid=False,
threshold=None):
"""
Unitize a vector or an array or row- vectors.
Parameters
---------
vectors : (n,m) or (j) float
Vector or vectors to be unitized
check_valid : bool
If set, will return mask of nonzero vectors
... | python | {
"resource": ""
} |
q23308 | euclidean | train | def euclidean(a, b):
"""
Euclidean distance between vectors a and b.
Parameters
------------
a : (n,) float
First vector
b : (n,) float
Second vector
Returns
------------
distance : float
Euclidean distance between A and B
"""
a = np.asanyarray(a, dtyp... | python | {
"resource": ""
} |
q23309 | is_none | train | def is_none(obj):
"""
Check to see if an object is None or not.
Handles the case of np.array(None) as well.
Parameters
-------------
obj : object
Any object type to be checked
Returns
-------------
is_none : bool
True if obj is None or numpy None-like
"""
if ... | python | {
"resource": ""
} |
q23310 | is_sequence | train | def is_sequence(obj):
"""
Check if an object is a sequence or not.
Parameters
-------------
obj : object
Any object type to be checked
Returns
-------------
is_sequence : bool
True if object is sequence
"""
seq = (not hasattr(obj, "strip") and
hasattr(o... | python | {
"resource": ""
} |
q23311 | is_shape | train | def is_shape(obj, shape):
"""
Compare the shape of a numpy.ndarray to a target shape,
with any value less than zero being considered a wildcard
Note that if a list- like object is passed that is not a numpy
array, this function will not convert it and will return False.
Parameters
--------... | python | {
"resource": ""
} |
q23312 | make_sequence | train | def make_sequence(obj):
"""
Given an object, if it is a sequence return, otherwise
add it to a length 1 sequence and return.
Useful for wrapping functions which sometimes return single
objects and other times return lists of objects.
Parameters
--------------
obj : object
An obje... | python | {
"resource": ""
} |
q23313 | vector_hemisphere | train | def vector_hemisphere(vectors, return_sign=False):
"""
For a set of 3D vectors alter the sign so they are all in the
upper hemisphere.
If the vector lies on the plane all vectors with negative Y
will be reversed.
If the vector has a zero Z and Y value vectors with a
negative X value will b... | python | {
"resource": ""
} |
q23314 | pairwise | train | def pairwise(iterable):
"""
For an iterable, group values into pairs.
Parameters
-----------
iterable : (m, ) list
A sequence of values
Returns
-----------
pairs: (n, 2)
Pairs of sequential values
Example
-----------
In [1]: data
Out[1]: [0, 1, 2, 3, 4, 5,... | python | {
"resource": ""
} |
q23315 | diagonal_dot | train | def diagonal_dot(a, b):
"""
Dot product by row of a and b.
There are a lot of ways to do this though
performance varies very widely. This method
uses the dot product to sum the row and avoids
function calls if at all possible.
Comparing performance of some equivalent versions:
```
... | python | {
"resource": ""
} |
q23316 | grid_linspace | train | def grid_linspace(bounds, count):
"""
Return a grid spaced inside a bounding box with edges spaced using np.linspace.
Parameters
---------
bounds: (2,dimension) list of [[min x, min y, etc], [max x, max y, etc]]
count: int, or (dimension,) int, number of samples per side
Returns
-----... | python | {
"resource": ""
} |
q23317 | multi_dict | train | def multi_dict(pairs):
"""
Given a set of key value pairs, create a dictionary.
If a key occurs multiple times, stack the values into an array.
Can be called like the regular dict(pairs) constructor
Parameters
----------
pairs: (n,2) array of key, value pairs
Returns
----------
... | python | {
"resource": ""
} |
q23318 | distance_to_end | train | def distance_to_end(file_obj):
"""
For an open file object how far is it to the end
Parameters
----------
file_obj: open file- like object
Returns
----------
distance: int, bytes to end of file
"""
position_current = file_obj.tell()
file_obj.seek(0, 2)
position_end = fi... | python | {
"resource": ""
} |
q23319 | decimal_to_digits | train | def decimal_to_digits(decimal, min_digits=None):
"""
Return the number of digits to the first nonzero decimal.
Parameters
-----------
decimal: float
min_digits: int, minimum number of digits to return
Returns
-----------
digits: int, number of digits to the first nonzero decima... | python | {
"resource": ""
} |
q23320 | hash_file | train | def hash_file(file_obj,
hash_function=hashlib.md5):
"""
Get the hash of an open file- like object.
Parameters
---------
file_obj: file like object
hash_function: function to use to hash data
Returns
---------
hashed: str, hex version of result
"""
# before we ... | python | {
"resource": ""
} |
q23321 | md5_object | train | def md5_object(obj):
"""
If an object is hashable, return the string of the MD5.
Parameters
-----------
obj: object
Returns
----------
md5: str, MD5 hash
"""
hasher = hashlib.md5()
if isinstance(obj, basestring) and PY3:
# in python3 convert strings to bytes before ... | python | {
"resource": ""
} |
q23322 | attach_to_log | train | def attach_to_log(level=logging.DEBUG,
handler=None,
loggers=None,
colors=True,
capture_warnings=True,
blacklist=None):
"""
Attach a stream handler to all loggers.
Parameters
------------
level: logging le... | python | {
"resource": ""
} |
q23323 | stack_lines | train | def stack_lines(indices):
"""
Stack a list of values that represent a polyline into
individual line segments with duplicated consecutive values.
Parameters
----------
indices: sequence of items
Returns
---------
stacked: (n,2) set of items
In [1]: trimesh.util.stack_lines([0,1... | python | {
"resource": ""
} |
q23324 | append_faces | train | def append_faces(vertices_seq, faces_seq):
"""
Given a sequence of zero- indexed faces and vertices
combine them into a single array of faces and
a single array of vertices.
Parameters
-----------
vertices_seq : (n, ) sequence of (m, d) float
Multiple arrays of verticesvertex arrays
... | python | {
"resource": ""
} |
q23325 | array_to_string | train | def array_to_string(array,
col_delim=' ',
row_delim='\n',
digits=8,
value_format='{}'):
"""
Convert a 1 or 2D array into a string with a specified number
of digits and delimiter. The reason this exists is that the
basic nump... | python | {
"resource": ""
} |
q23326 | array_to_encoded | train | def array_to_encoded(array, dtype=None, encoding='base64'):
"""
Export a numpy array to a compact serializable dictionary.
Parameters
------------
array : array
Any numpy array
dtype : str or None
Optional dtype to encode array
encoding : str
'base64' or 'binary'
Retu... | python | {
"resource": ""
} |
q23327 | decode_keys | train | def decode_keys(store, encoding='utf-8'):
"""
If a dictionary has keys that are bytes decode them to a str.
Parameters
---------
store : dict
Dictionary with data
Returns
---------
result : dict
Values are untouched but keys that were bytes
are converted to ASCII stri... | python | {
"resource": ""
} |
q23328 | encoded_to_array | train | def encoded_to_array(encoded):
"""
Turn a dictionary with base64 encoded strings back into a numpy array.
Parameters
------------
encoded : dict
Has keys:
dtype: string of dtype
shape: int tuple of shape
base64: base64 encoded string of flat array
binary: deco... | python | {
"resource": ""
} |
q23329 | type_bases | train | def type_bases(obj, depth=4):
"""
Return the bases of the object passed.
"""
bases = collections.deque([list(obj.__class__.__bases__)])
for i in range(depth):
bases.append([i.__base__ for i in bases[-1] if i is not None])
try:
bases = np.hstack(bases)
except IndexError:
... | python | {
"resource": ""
} |
q23330 | concatenate | train | def concatenate(a, b=None):
"""
Concatenate two or more meshes.
Parameters
----------
a: Trimesh object, or list of such
b: Trimesh object, or list of such
Returns
----------
result: Trimesh object containing concatenated mesh
"""
if b is None:
b = []
# stack me... | python | {
"resource": ""
} |
q23331 | submesh | train | def submesh(mesh,
faces_sequence,
only_watertight=False,
append=False):
"""
Return a subset of a mesh.
Parameters
----------
mesh : Trimesh
Source mesh to take geometry from
faces_sequence : sequence (p,) int
Indexes of mesh.faces
only_wate... | python | {
"resource": ""
} |
q23332 | jsonify | train | def jsonify(obj, **kwargs):
"""
A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON- serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
dumped : str
JSON dum... | python | {
"resource": ""
} |
q23333 | convert_like | train | def convert_like(item, like):
"""
Convert an item to have the dtype of another item
Parameters
----------
item: item to be converted
like: object with target dtype. If None, item is returned unmodified
Returns
--------
result: item, but in dtype of like
"""
if isinstance(li... | python | {
"resource": ""
} |
q23334 | bounds_tree | train | def bounds_tree(bounds):
"""
Given a set of axis aligned bounds, create an r-tree for broad- phase
collision detection
Parameters
---------
bounds: (n, dimension*2) list of non- interleaved bounds
for a 2D bounds tree:
[(minx, miny, maxx, maxy), ...]
Returns
-... | python | {
"resource": ""
} |
q23335 | wrap_as_stream | train | def wrap_as_stream(item):
"""
Wrap a string or bytes object as a file object.
Parameters
----------
item: str or bytes
Item to be wrapped
Returns
---------
wrapped: file-like object
"""
if not PY3:
return StringIO(item)
if isinstance(item, str):
return... | python | {
"resource": ""
} |
q23336 | sigfig_round | train | def sigfig_round(values, sigfig=1):
"""
Round a single value to a specified number of significant figures.
Parameters
----------
values: float, value to be rounded
sigfig: int, number of significant figures to reduce to
Returns
----------
rounded: values, but rounded to the specif... | python | {
"resource": ""
} |
q23337 | sigfig_int | train | def sigfig_int(values, sigfig):
"""
Convert a set of floating point values into integers with a specified number
of significant figures and an exponent.
Parameters
------------
values: (n,) float or int, array of values
sigfig: (n,) int, number of significant figures to keep
Returns
... | python | {
"resource": ""
} |
q23338 | decompress | train | def decompress(file_obj, file_type):
"""
Given an open file object and a file type, return all components
of the archive as open file objects in a dict.
Parameters
-----------
file_obj : file-like
Containing compressed data
file_type : str
File extension, 'zip', 'tar.gz', etc
... | python | {
"resource": ""
} |
q23339 | compress | train | def compress(info):
"""
Compress data stored in a dict.
Parameters
-----------
info : dict
Data to compress in form:
{file name in archive: bytes or file-like object}
Returns
-----------
compressed : bytes
Compressed file data
"""
if PY3:
file_obj = By... | python | {
"resource": ""
} |
q23340 | vstack_empty | train | def vstack_empty(tup):
"""
A thin wrapper for numpy.vstack that ignores empty lists.
Parameters
------------
tup: tuple or list of arrays with the same number of columns
Returns
------------
stacked: (n,d) array, with same number of columns as
constituent arrays.
"""
... | python | {
"resource": ""
} |
q23341 | write_encoded | train | def write_encoded(file_obj,
stuff,
encoding='utf-8'):
"""
If a file is open in binary mode and a string is passed, encode and write
If a file is open in text mode and bytes are passed, decode and write
Parameters
-----------
file_obj: file object, with 'wr... | python | {
"resource": ""
} |
q23342 | unique_id | train | def unique_id(length=12, increment=0):
"""
Generate a decent looking alphanumeric unique identifier.
First 16 bits are time- incrementing, followed by randomness.
This function is used as a nicer looking alternative to:
>>> uuid.uuid4().hex
Follows the advice in:
https://eager.io/blog/how-... | python | {
"resource": ""
} |
q23343 | isclose | train | def isclose(a, b, atol):
"""
A replacement for np.isclose that does fewer checks
and validation and as a result is roughly 4x faster.
Note that this is used in tight loops, and as such
a and b MUST be np.ndarray, not list or "array-like"
Parameters
----------
a : np.ndarray
To be... | python | {
"resource": ""
} |
q23344 | svg_to_path | train | def svg_to_path(file_obj, file_type=None):
"""
Load an SVG file into a Path2D object.
Parameters
-----------
file_obj : open file object
Contains SVG data
file_type: None
Not used
Returns
-----------
loaded : dict
With kwargs for Path2D constructor
"""
de... | python | {
"resource": ""
} |
q23345 | transform_to_matrices | train | def transform_to_matrices(transform):
"""
Convert an SVG transform string to an array of matrices.
> transform = "rotate(-10 50 100)
translate(-36 45.5)
skewX(40)
scale(1 0.5)"
Parameters
-----------
transform : str
Contains trans... | python | {
"resource": ""
} |
q23346 | _svg_path_convert | train | def _svg_path_convert(paths):
"""
Convert an SVG path string into a Path2D object
Parameters
-------------
paths: list of tuples
Containing (path string, (3,3) matrix)
Returns
-------------
drawing : dict
Kwargs for Path2D constructor
"""
def complex_to_float(values... | python | {
"resource": ""
} |
q23347 | _orient3dfast | train | def _orient3dfast(plane, pd):
"""
Performs a fast 3D orientation test.
Parameters
----------
plane: (3,3) float, three points in space that define a plane
pd: (3,) float, a single point
Returns
-------
result: float, if greater than zero then pd is above the plane through
... | python | {
"resource": ""
} |
q23348 | _compute_static_prob | train | def _compute_static_prob(tri, com):
"""
For an object with the given center of mass, compute
the probability that the given tri would be the first to hit the
ground if the object were dropped with a pose chosen uniformly at random.
Parameters
----------
tri: (3,3) float, the vertices of a t... | python | {
"resource": ""
} |
q23349 | _create_topple_graph | train | def _create_topple_graph(cvh_mesh, com):
"""
Constructs a toppling digraph for the given convex hull mesh and
center of mass.
Each node n_i in the digraph corresponds to a face f_i of the mesh and is
labelled with the probability that the mesh will land on f_i if dropped
randomly. Not all faces... | python | {
"resource": ""
} |
q23350 | transform | train | def transform(mesh, translation_scale=1000.0):
"""
Return a permutated variant of a mesh by randomly reording faces
and rotatating + translating a mesh by a random matrix.
Parameters
----------
mesh: Trimesh object (input will not be altered by this function)
Returns
----------
p... | python | {
"resource": ""
} |
q23351 | noise | train | def noise(mesh, magnitude=None):
"""
Add gaussian noise to every vertex of a mesh.
Makes no effort to maintain topology or sanity.
Parameters
----------
mesh: Trimesh object (will not be mutated)
magnitude: float, what is the maximum distance per axis we can displace a vertex.
... | python | {
"resource": ""
} |
q23352 | tessellation | train | def tessellation(mesh):
"""
Subdivide each face of a mesh into three faces with the new vertex
randomly placed inside the old face.
This produces a mesh with exactly the same surface area and volume
but with different tessellation.
Parameters
----------
mesh: Trimesh object
Return... | python | {
"resource": ""
} |
q23353 | load_ply | train | def load_ply(file_obj,
resolver=None,
fix_texture=True,
*args,
**kwargs):
"""
Load a PLY file from an open file object.
Parameters
---------
file_obj : an open file- like object
Source data, ASCII or binary PLY
resolver : trimesh.visual.... | python | {
"resource": ""
} |
q23354 | export_ply | train | def export_ply(mesh,
encoding='binary',
vertex_normal=None):
"""
Export a mesh in the PLY format.
Parameters
----------
mesh : Trimesh object
encoding : ['ascii'|'binary_little_endian']
vertex_normal : include vertex normals
Returns
----------
expo... | python | {
"resource": ""
} |
q23355 | parse_header | train | def parse_header(file_obj):
"""
Read the ASCII header of a PLY file, and leave the file object
at the position of the start of data but past the header.
Parameters
-----------
file_obj : open file object
Positioned at the start of the file
Returns
-----------
elements : colle... | python | {
"resource": ""
} |
q23356 | ply_ascii | train | def ply_ascii(elements, file_obj):
"""
Load data from an ASCII PLY file into an existing elements data structure.
Parameters
------------
elements: OrderedDict object, populated from the file header.
object will be modified to add data by this function.
file_obj: open file object... | python | {
"resource": ""
} |
q23357 | ply_binary | train | def ply_binary(elements, file_obj):
"""
Load the data from a binary PLY file into the elements data structure.
Parameters
------------
elements: OrderedDict object, populated from the file header.
object will be modified to add data by this function.
file_obj: open file object, w... | python | {
"resource": ""
} |
q23358 | export_draco | train | def export_draco(mesh):
"""
Export a mesh using Google's Draco compressed format.
Only works if draco_encoder is in your PATH:
https://github.com/google/draco
Parameters
----------
mesh : Trimesh object
Returns
----------
data : str or bytes
DRC file bytes
"""
wi... | python | {
"resource": ""
} |
q23359 | load_draco | train | def load_draco(file_obj, **kwargs):
"""
Load a mesh from Google's Draco format.
Parameters
----------
file_obj : file- like object
Contains data
Returns
----------
kwargs : dict
Keyword arguments to construct a Trimesh object
"""
with tempfile.NamedTemporaryFile(s... | python | {
"resource": ""
} |
q23360 | boolean_automatic | train | def boolean_automatic(meshes, operation):
"""
Automatically pick an engine for booleans based on availability.
Parameters
--------------
meshes : list of Trimesh
Meshes to be booleaned
operation : str
Type of boolean, i.e. 'union', 'intersection', 'difference'
Returns
-----... | python | {
"resource": ""
} |
q23361 | subdivide | train | def subdivide(vertices,
faces,
face_index=None):
"""
Subdivide a mesh into smaller triangles.
Note that if `face_index` is passed, only those faces will
be subdivided and their neighbors won't be modified making
the mesh no longer "watertight."
Parameters
------... | python | {
"resource": ""
} |
q23362 | subdivide_to_size | train | def subdivide_to_size(vertices,
faces,
max_edge,
max_iter=10):
"""
Subdivide a mesh until every edge is shorter than a
specified length.
Will return a triangle soup, not a nicely structured mesh.
Parameters
------------
vert... | python | {
"resource": ""
} |
q23363 | load_dwg | train | def load_dwg(file_obj, **kwargs):
"""
Load DWG files by converting them to DXF files using
TeighaFileConverter.
Parameters
-------------
file_obj : file- like object
Returns
-------------
loaded : dict
kwargs for a Path2D constructor
"""
# read the DWG data into a b... | python | {
"resource": ""
} |
q23364 | cross | train | def cross(triangles):
"""
Returns the cross product of two edges from input triangles
Parameters
--------------
triangles: (n, 3, 3) float
Vertices of triangles
Returns
--------------
crosses : (n, 3) float
Cross product of two edge vectors
"""
vectors = np.diff(tri... | python | {
"resource": ""
} |
q23365 | area | train | def area(triangles=None, crosses=None, sum=False):
"""
Calculates the sum area of input triangles
Parameters
----------
triangles : (n, 3, 3) float
Vertices of triangles
crosses : (n, 3) float or None
As a speedup don't re- compute cross products
sum : bool
Return summed a... | python | {
"resource": ""
} |
q23366 | normals | train | def normals(triangles=None, crosses=None):
"""
Calculates the normals of input triangles
Parameters
------------
triangles : (n, 3, 3) float
Vertex positions
crosses : (n, 3) float
Cross products of edge vectors
Returns
------------
normals : (m, 3) float
Normal v... | python | {
"resource": ""
} |
q23367 | angles | train | def angles(triangles):
"""
Calculates the angles of input triangles.
Parameters
------------
triangles : (n, 3, 3) float
Vertex positions
Returns
------------
angles : (n, 3) float
Angles at vertex positions, in radians
"""
# get a vector for each edge of the trian... | python | {
"resource": ""
} |
q23368 | all_coplanar | train | def all_coplanar(triangles):
"""
Check to see if a list of triangles are all coplanar
Parameters
----------------
triangles: (n, 3, 3) float
Vertices of triangles
Returns
---------------
all_coplanar : bool
True if all triangles are coplanar
"""
triangles = np.asany... | python | {
"resource": ""
} |
q23369 | windings_aligned | train | def windings_aligned(triangles, normals_compare):
"""
Given a list of triangles and a list of normals determine if the
two are aligned
Parameters
----------
triangles : (n, 3, 3) float
Vertex locations in space
normals_compare : (n, 3) float
List of normals to compare
Retur... | python | {
"resource": ""
} |
q23370 | bounds_tree | train | def bounds_tree(triangles):
"""
Given a list of triangles, create an r-tree for broad- phase
collision detection
Parameters
---------
triangles : (n, 3, 3) float
Triangles in space
Returns
---------
tree : rtree.Rtree
One node per triangle
"""
triangles = np.asa... | python | {
"resource": ""
} |
q23371 | nondegenerate | train | def nondegenerate(triangles, areas=None, height=None):
"""
Find all triangles which have an oriented bounding box
where both of the two sides is larger than a specified height.
Degenerate triangles can be when:
1) Two of the three vertices are colocated
2) All three vertices are unique but coli... | python | {
"resource": ""
} |
q23372 | extents | train | def extents(triangles, areas=None):
"""
Return the 2D bounding box size of each triangle.
Parameters
----------
triangles : (n, 3, 3) float
Triangles in space
areas : (n,) float
Optional area of input triangles
Returns
----------
box : (n, 2) float
The size of ea... | python | {
"resource": ""
} |
q23373 | barycentric_to_points | train | def barycentric_to_points(triangles, barycentric):
"""
Convert a list of barycentric coordinates on a list of triangles
to cartesian points.
Parameters
------------
triangles : (n, 3, 3) float
Triangles in space
barycentric : (n, 2) float
Barycentric coordinates
Returns
... | python | {
"resource": ""
} |
q23374 | points_to_barycentric | train | def points_to_barycentric(triangles,
points,
method='cramer'):
"""
Find the barycentric coordinates of points relative to triangles.
The Cramer's rule solution implements:
http://blackpawn.com/texts/pointinpoly
The cross product solution impl... | python | {
"resource": ""
} |
q23375 | to_kwargs | train | def to_kwargs(triangles):
"""
Convert a list of triangles to the kwargs for the Trimesh
constructor.
Parameters
---------
triangles : (n, 3, 3) float
Triangles in space
Returns
---------
kwargs : dict
Keyword arguments for the trimesh.Trimesh constructor
Includes ... | python | {
"resource": ""
} |
q23376 | _Primitive.copy | train | def copy(self):
"""
Return a copy of the Primitive object.
"""
result = copy.deepcopy(self)
result._cache.clear()
return result | python | {
"resource": ""
} |
q23377 | _Primitive.to_mesh | train | def to_mesh(self):
"""
Return a copy of the Primitive object as a Trimesh object.
"""
result = Trimesh(vertices=self.vertices.copy(),
faces=self.faces.copy(),
face_normals=self.face_normals.copy(),
process=False)
... | python | {
"resource": ""
} |
q23378 | Cylinder.volume | train | def volume(self):
"""
The analytic volume of the cylinder primitive.
Returns
---------
volume : float
Volume of the cylinder
"""
volume = ((np.pi * self.primitive.radius ** 2) *
self.primitive.height)
return volume | python | {
"resource": ""
} |
q23379 | Cylinder.moment_inertia | train | def moment_inertia(self):
"""
The analytic inertia tensor of the cylinder primitive.
Returns
----------
tensor: (3,3) float, 3D inertia tensor
"""
tensor = inertia.cylinder_inertia(
mass=self.volume,
radius=self.primitive.radius,
... | python | {
"resource": ""
} |
q23380 | Cylinder.segment | train | def segment(self):
"""
A line segment which if inflated by cylinder radius
would represent the cylinder primitive.
Returns
-------------
segment : (2, 3) float
Points representing a single line segment
"""
# half the height
half = self.p... | python | {
"resource": ""
} |
q23381 | Sphere.apply_transform | train | def apply_transform(self, matrix):
"""
Apply a transform to the sphere primitive
Parameters
------------
matrix: (4,4) float, homogenous transformation
"""
matrix = np.asanyarray(matrix, dtype=np.float64)
if matrix.shape != (4, 4):
raise Value... | python | {
"resource": ""
} |
q23382 | Sphere.moment_inertia | train | def moment_inertia(self):
"""
The analytic inertia tensor of the sphere primitive.
Returns
----------
tensor: (3,3) float, 3D inertia tensor
"""
tensor = inertia.sphere_inertia(mass=self.volume,
radius=self.primitive.radius... | python | {
"resource": ""
} |
q23383 | Box.sample_volume | train | def sample_volume(self, count):
"""
Return random samples from inside the volume of the box.
Parameters
-------------
count : int
Number of samples to return
Returns
----------
samples : (count, 3) float
Points inside the volume
... | python | {
"resource": ""
} |
q23384 | Box.sample_grid | train | def sample_grid(self, count=None, step=None):
"""
Return a 3D grid which is contained by the box.
Samples are either 'step' distance apart, or there are
'count' samples per box side.
Parameters
-----------
count : int or (3,) int
If specified samples ar... | python | {
"resource": ""
} |
q23385 | Box.is_oriented | train | def is_oriented(self):
"""
Returns whether or not the current box is rotated at all.
"""
if util.is_shape(self.primitive.transform, (4, 4)):
return not np.allclose(self.primitive.transform[
0:3, 0:3], np.eye(3))
else:
ret... | python | {
"resource": ""
} |
q23386 | Box.volume | train | def volume(self):
"""
Volume of the box Primitive.
Returns
--------
volume: float, volume of box
"""
volume = float(np.product(self.primitive.extents))
return volume | python | {
"resource": ""
} |
q23387 | Extrusion.area | train | def area(self):
"""
The surface area of the primitive extrusion.
Calculated from polygon and height to avoid mesh creation.
Returns
----------
area: float, surface area of 3D extrusion
"""
# area of the sides of the extrusion
area = abs(self.prim... | python | {
"resource": ""
} |
q23388 | Extrusion.volume | train | def volume(self):
"""
The volume of the primitive extrusion.
Calculated from polygon and height to avoid mesh creation.
Returns
----------
volume: float, volume of 3D extrusion
"""
volume = abs(self.primitive.polygon.area *
self.prim... | python | {
"resource": ""
} |
q23389 | Extrusion.direction | train | def direction(self):
"""
Based on the extrudes transform, what is the vector along
which the polygon will be extruded
Returns
---------
direction: (3,) float vector. If self.primitive.transform is an
identity matrix this will be [0.0, 0.0, 1.0]
... | python | {
"resource": ""
} |
q23390 | Extrusion.slide | train | def slide(self, distance):
"""
Alter the transform of the current extrusion to slide it
along its extrude_direction vector
Parameters
-----------
distance: float, distance along self.extrude_direction to move
"""
distance = float(distance)
transla... | python | {
"resource": ""
} |
q23391 | Extrusion.buffer | train | def buffer(self, distance):
"""
Return a new Extrusion object which is expanded in profile and
in height by a specified distance.
Returns
----------
buffered: Extrusion object
"""
distance = float(distance)
# start with current height
hei... | python | {
"resource": ""
} |
q23392 | enclosure_tree | train | def enclosure_tree(polygons):
"""
Given a list of shapely polygons with only exteriors,
find which curves represent the exterior shell or root curve
and which represent holes which penetrate the exterior.
This is done with an R-tree for rough overlap detection,
and then exact polygon queries fo... | python | {
"resource": ""
} |
q23393 | edges_to_polygons | train | def edges_to_polygons(edges, vertices):
"""
Given an edge list of indices and associated vertices
representing lines, generate a list of polygons.
Parameters
-----------
edges : (n, 2) int
Indexes of vertices which represent lines
vertices : (m, 2) float
Vertices in 2D space
... | python | {
"resource": ""
} |
q23394 | polygons_obb | train | def polygons_obb(polygons):
"""
Find the OBBs for a list of shapely.geometry.Polygons
"""
rectangles = [None] * len(polygons)
transforms = [None] * len(polygons)
for i, p in enumerate(polygons):
transforms[i], rectangles[i] = polygon_obb(p)
return np.array(transforms), np.array(recta... | python | {
"resource": ""
} |
q23395 | polygon_obb | train | def polygon_obb(polygon):
"""
Find the oriented bounding box of a Shapely polygon.
The OBB is always aligned with an edge of the convex hull of the polygon.
Parameters
-------------
polygons: shapely.geometry.Polygon
Returns
-------------
transform: (3,3) float, transformation mat... | python | {
"resource": ""
} |
q23396 | transform_polygon | train | def transform_polygon(polygon, matrix):
"""
Transform a polygon by a a 2D homogenous transform.
Parameters
-------------
polygon : shapely.geometry.Polygon
2D polygon to be transformed.
matrix : (3, 3) float
2D homogenous transformation.
Returns
-----... | python | {
"resource": ""
} |
q23397 | plot_polygon | train | def plot_polygon(polygon, show=True, **kwargs):
"""
Plot a shapely polygon using matplotlib.
Parameters
------------
polygon : shapely.geometry.Polygon
Polygon to be plotted
show : bool
If True will display immediately
**kwargs
Passed to plt.plot
"""
import matplot... | python | {
"resource": ""
} |
q23398 | resample_boundaries | train | def resample_boundaries(polygon, resolution, clip=None):
"""
Return a version of a polygon with boundaries resampled
to a specified resolution.
Parameters
-------------
polygon: shapely.geometry.Polygon object
resolution: float, desired distance between points on boundary
clip: ... | python | {
"resource": ""
} |
q23399 | medial_axis | train | def medial_axis(polygon,
resolution=None,
clip=None):
"""
Given a shapely polygon, find the approximate medial axis
using a voronoi diagram of evenly spaced points on the
boundary of the polygon.
Parameters
----------
polygon : shapely.geometry.Polygon
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.