_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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:
np.logical_and
np.logical_or
Returns
-----------
coords: (q, d) int, coordinates in space
"""
# 3D sparse arrays, using wrapped scipy.sparse
# pip install sparse
import sparse
# find the bounding box of both arrays
extrema = np.array([a.min(axis=0),
a.max(axis=0),
b.min(axis=0),
b.max(axis=0)])
origin = extrema.min(axis=0) - 1
size = tuple(extrema.ptp(axis=0) + 2)
# put nearby voxel arrays into same shape sparse array
sp_a = sparse.COO((a - origin).T,
| 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
---------
meshed: Trimesh object representing the current voxel
object, as returned by marching cubes algorithm.
| 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,
| 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
"""
| 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
"""
| 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
| 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 : float
Magnitude of vertex noise to apply
"""
# create the mesh as a simple box
mesh = trimesh.creation.box(extents=extents)
# add some systematic error pre- tesselation
mesh.vertices[0] += mesh.vertex_normals[0] + (noise * 2)
# subdivide until we have more faces than we want
for i in range(max_iter):
if len(mesh.vertices) > face_count:
break | 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
threshold : float
Cutoff for a value to be considered zero.
Returns
---------
unit : (n,m) or (j) float
Input vectors but unitized
valid : (n,) bool or bool
Mask of nonzero vectors returned if `check_valid`
"""
# make sure we have a numpy array
vectors = np.asanyarray(vectors)
# allow user to set zero threshold
if threshold is None:
threshold = TOL_ZERO
if len(vectors.shape) == 2:
# for (m, d) arrays take the per- row unit vector
# using sqrt and avoiding exponents is slightly faster
# also dot with ones is faser than .sum(axis=1)
norm = np.sqrt(np.dot(vectors * vectors,
[1.0] * vectors.shape[1]))
# non-zero norms
valid = norm > threshold
| 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 | 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 | 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(obj, "__getitem__") or
hasattr(obj, "__iter__"))
# check to make sure it is not a set, string, or dictionary
seq = seq and all(not isinstance(obj, i) for i in (dict,
set,
basestring))
# PointCloud | 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
---------
obj : np.ndarray
Array to check the shape on
shape : list or tuple
Any negative term will be considered a wildcard
Any tuple term will be evaluated as an OR
Returns
---------
shape_ok: bool, True if shape of obj matches query shape
Examples
------------------------
In [1]: a = np.random.random((100, 3))
In [2]: a.shape
Out[2]: (100, 3)
In [3]: trimesh.util.is_shape(a, (-1, 3))
Out[3]: True
In [4]: trimesh.util.is_shape(a, (-1, 3, 5))
Out[4]: False
In [5]: trimesh.util.is_shape(a, (100, -1))
Out[5]: True
In [6]: trimesh.util.is_shape(a, (-1, (3, 4)))
Out[6]: True
In [7]: trimesh.util.is_shape(a, (-1, (4, 5)))
Out[7]: False
"""
# if the obj.shape is different length than
# the goal shape it means they have different number
# of dimensions and thus the obj is not the query shape
if (not hasattr(obj, 'shape') or
len(obj.shape) != len(shape)):
return False
# loop through each integer of the two shapes
# multiple values are sequences
# wildcards are less than zero (i.e. -1)
| 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 object to be made a sequence | 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 be reversed.
Parameters
----------
vectors : (n,3) float
Input vectors
return_sign : bool
Return the sign mask or not
Returns
----------
oriented: (n, 3) float
Vectors with same magnitude as source
but possibly reversed to ensure all vectors
are in the same hemisphere.
sign : (n,) float
"""
# vectors as numpy array
vectors = np.asanyarray(vectors, dtype=np.float64)
if is_shape(vectors, (-1, 2)):
# 2D vector case
# check the Y value and reverse vector
# direction if negative.
negative = vectors < -TOL_ZERO
zero = np.logical_not(
np.logical_or(negative, vectors > TOL_ZERO))
signs = np.ones(len(vectors), dtype=np.float64)
# negative Y values are reversed
signs[negative[:, 1]] = -1.0
# zero Y and negative X are reversed
signs[np.logical_and(zero[:, 1], negative[:, 0])] = -1.0
elif is_shape(vectors, (-1, 3)):
# 3D vector case
negative = vectors < -TOL_ZERO
zero = np.logical_not(
np.logical_or(negative, | 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, 6]
In [2]: list(trimesh.util.pairwise(data))
Out[2]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
"""
# looping through a giant numpy array would be dumb
# so special case ndarrays and use numpy operations
if isinstance(iterable, np.ndarray):
iterable = iterable.reshape(-1)
stacked = | 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:
```
In [1]: import numpy as np; import trimesh
In [2]: a = np.random.random((10000, 3))
In [3]: b = np.random.random((10000, 3))
In [4]: %timeit (a * b).sum(axis=1)
1000 loops, best of 3: 181 us per loop
In [5]: %timeit np.einsum('ij,ij->i', a, b)
10000 loops, best | 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
-------
grid: (n, dimension) float, points in the specified bounds
"""
bounds = np.asanyarray(bounds, dtype=np.float64)
if len(bounds) != 2:
raise | 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)
| 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 decimal
| 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 read the file data save the current position
# in the file (which is probably 0)
file_position = file_obj.tell()
# create an | 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 | 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 level
handler: log handler object
loggers: list of loggers to attach to
if None, will try to attach to all available
colors: bool, if True try to use colorlog formatter
blacklist: list of str, names of loggers NOT to attach to
"""
if blacklist is None:
blacklist = ['TerminalIPythonApp',
'PYREADLINE',
'pyembree',
'shapely.geos',
'shapely.speedups._speedups',
'parso.cache',
'parso.python.diff']
# make sure we log warnings from the warnings module
logging.captureWarnings(capture_warnings)
formatter = logging.Formatter(
"[%(asctime)s] %(levelname)-7s (%(filename)s:%(lineno)3s) %(message)s",
"%Y-%m-%d %H:%M:%S")
if colors:
try:
from colorlog import ColoredFormatter
formatter = ColoredFormatter(
("%(log_color)s%(levelname)-8s%(reset)s " +
"%(filename)17s:%(lineno)-4s %(blue)4s%(message)s"),
datefmt=None,
reset=True,
log_colors={'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red'})
except ImportError:
pass | 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,2])
Out[1]:
array([[0, 1],
[1, 2]])
In [2]: trimesh.util.stack_lines([0,1,2,4,5])
Out[2]:
array([[0, 1],
[1, 2],
[2, 4],
[4, 5]])
In [3]: trimesh.util.stack_lines([[0,0],[1,1],[2,2], [3,3]])
Out[3]:
array([[0, 0],
| 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
faces_seq : (n, ) sequence of (p, j) int
Zero indexed faces for matching vertices
Returns
----------
vertices : (i, d) float
Points in space
faces : (j, 3) int
Reference vertex indices
"""
# the length of each vertex array
vertices_len = np.array([len(i) for i in vertices_seq])
# how much each group of faces needs to be offset
| 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 numpy array to string conversions are surprisingly bad.
Parameters
----------
array : (n,) or (n, d) float or int
Data to be converted
If shape is (n,) only column delimiter will be used
col_delim : str
What string should separate values in a column
row_delim : str
What string should separate values in a row
digits : int
How many digits should floating point numbers include
value_format : str
Format string for each value or sequence of values
If multiple values per value_format it must divide
into array evenly.
Returns
----------
formatted : str
String representation of original array
"""
# convert inputs to correct types
array = np.asanyarray(array)
digits = int(digits)
row_delim = str(row_delim)
col_delim = str(col_delim)
value_format = str(value_format)
# abort for non- flat arrays
if len(array.shape) > 2:
raise ValueError('conversion only works on 1D/2D arrays not %s!',
str(array.shape))
# allow a value to be repeated in a value format
repeats = value_format.count('{}')
if array.dtype.kind == 'i':
# integer types don't need a specified precision
| 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'
Returns
---------
encoded : dict
Has keys:
'dtype': str, of dtype
'shape': tuple of shape
'base64': str, base64 encoded string
"""
array = np.asanyarray(array)
shape = array.shape
# ravel also forces contiguous
flat = np.ravel(array)
if dtype is None:
dtype = array.dtype
encoded = {'dtype': np.dtype(dtype).str,
| 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 strings.
| 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: decode result coming from numpy.tostring
Returns
----------
array: numpy array
"""
if not isinstance(encoded, dict):
if is_sequence(encoded):
as_array = np.asanyarray(encoded)
return as_array
else:
raise ValueError('Unable to extract numpy array from input')
| 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 meshes into flat list
meshes = np.append(a, b)
# extract the trimesh type to avoid a circular import
# and assert that both inputs are Trimesh objects
trimesh_type = type_named(meshes[0], 'Trimesh')
# append faces and vertices of meshes
vertices, faces = append_faces(
[m.vertices.copy() for m in meshes],
[m.faces.copy() for m in meshes])
# only save face normals if already calculated
face_normals = None
if all('face_normals' | 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_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
---------
if append : Trimesh object
else list of Trimesh objects
"""
# evaluate generators so we can escape early
faces_sequence = list(faces_sequence)
if len(faces_sequence) == 0:
return []
# check to make sure we're not doing a whole bunch of work
# to deliver a subset which ends up as the whole mesh
if len(faces_sequence[0]) == len(mesh.faces):
all_faces = np.array_equal(np.sort(faces_sequence),
np.arange(len(faces_sequence)))
if all_faces:
log.debug('entire mesh requested, returning copy')
return mesh.copy()
# avoid nuking the cache on the original mesh
original_faces = mesh.faces.view(np.ndarray)
original_vertices = mesh.vertices.view(np.ndarray)
faces = []
vertices = []
normals = []
visuals = []
# for reindexing faces
mask = np.arange(len(original_vertices))
for faces_index in faces_sequence: | 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 dump of obj
"""
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
# will work for numpy.ndarrays
# as well as their int64/etc objects
| 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(like, np.ndarray):
return np.asanyarray(item, dtype=like.dtype)
if isinstance(item, | 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
---------
tree: Rtree object
"""
bounds = np.asanyarray(copy.deepcopy(bounds), dtype=np.float64)
if len(bounds.shape) != 2:
raise ValueError('Bounds must be (n,dimension*2)!')
dimension = bounds.shape[1]
if (dimension % 2) != 0:
raise ValueError('Bounds must be (n,dimension*2)!')
dimension = int(dimension / 2)
import rtree
# some versions of rtree screw up indexes on stream loading | 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): | 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 specified number of significant figures
Examples
----------
In [1]: trimesh.util.round_sigfig(-232453.00014045456, 1)
Out[1]: -200000.0
| 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
------------
as_int: (n,) int, every value[i] has sigfig[i] digits
multiplier: (n, int), exponent, so as_int * 10 ** multiplier is
the same order of magnitude as the input
"""
values = np.asanyarray(values).reshape(-1)
sigfig = np.asanyarray(sigfig, dtype=np.int).reshape(-1)
if sigfig.shape != values.shape:
| 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
Returns
---------
decompressed : dict
Data from archive in format {file name : file-like}
"""
def is_zip():
archive = zipfile.ZipFile(file_obj)
result = {name: wrap_as_stream(archive.read(name))
for name in archive.namelist()}
return result
def is_tar():
import tarfile
| 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 = BytesIO()
else:
file_obj = StringIO()
with zipfile.ZipFile(
file_obj,
mode='w',
compression=zipfile.ZIP_DEFLATED) as zipper:
| 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.
"""
# filter out empty arrays
stackable = [i for i in tup if len(i) > 0]
# if we only have one array just return it
if len(stackable) == 1:
| 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 'write' and 'mode'
stuff: str or bytes, stuff to be written
encoding: str, encoding of text
"""
binary_file = 'b' in file_obj.mode
string_stuff = isinstance(stuff, basestring)
binary_stuff = isinstance(stuff, bytes)
if not PY3:
| 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-long-does-an-id-need-to-be/
Parameters
------------
length: int, length of resulting identifier
increment: int, number to add to header uint16
useful if calling this function repeatedly
| 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"
| 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
"""
def element_transform(e, max_depth=100):
"""
Find a transformation matrix for an XML element.
"""
matrices = []
current = e
for i in range(max_depth):
if 'transform' in current.attrib:
mat = transform_to_matrices(current.attrib['transform'])
matrices.extend(mat)
# cached[current] = mat
current = current.getparent()
if current is None:
break
if len(matrices) == 0:
return np.eye(3)
elif len(matrices) == 1:
| 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 transformation information in SVG form
Returns
-----------
matrices : (n, 3, 3) float
Multiple transformation matrices from input transform string
"""
# split the transform string in to components of:
# (operation, args) i.e. (translate, '-1.0, 2.0')
components = [
[j.strip() for j in i.strip().split('(') if len(j) > 0]
for i in transform.lower().split(')') if len(i) > 0]
# store each matrix without dotting
matrices = []
for line in components:
if len(line) == 0:
continue
elif len(line) != 2:
raise ValueError('should always have two components!')
| 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):
return np.array([[i.real, i.imag] for i in values])
def load_line(svg_line):
points = complex_to_float([svg_line.point(0.0),
svg_line.point(1.0)])
if starting:
# return every vertex and use it
return (entities_mod.Line(np.arange(2) + len(vertices)), points)
else:
# we are not starting so use the last referenced vertex as the
# start point
return (entities_mod.Line(
np.arange(2) + len(vertices) - 1), points[1:])
def load_arc(svg_arc):
points = complex_to_float([svg_arc.start,
svg_arc.point(.5),
svg_arc.end])
if starting:
# return every vertex and use it
return (entities_mod.Arc(np.arange(3) + len(vertices)), points)
else:
# we are not starting so use the last referenced vertex as the
# start point
return (entities_mod.Arc(np.arange(3) +
len(vertices) - 1), points[1:])
def load_quadratic(svg_quadratic):
points = complex_to_float([svg_quadratic.start,
svg_quadratic.control,
svg_quadratic.end])
if starting:
# return every vertex and use it
return (entities_mod.Bezier(np.arange(3) + len(vertices)), points)
else:
# we are not starting so use the last referenced vertex as the
# start point
return (entities_mod.Bezier(
np.arange(3) + len(vertices) - 1), points[1:])
def load_cubic(svg_cubic):
points = complex_to_float([svg_cubic.start,
| 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
the given three points, if less than zero then pd is below
the given plane, and if equal to zero then pd is on the
given plane.
"""
pa, pb, pc | 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 triangle
cm: (3,) float, the center of mass of the object
Returns
-------
prob: float, the probability in [0,1] for the given triangle
"""
sv = [(v - com) / np.linalg.norm(v - com) for v in tri]
# Use L'Huilier's Formula to compute spherical area
a = np.arccos(min(1, max(-1, np.dot(sv[0], sv[1]))))
b = np.arccos(min(1, max(-1, np.dot(sv[1], sv[2]))))
c = np.arccos(min(1, max(-1, np.dot(sv[2], sv[0]))))
s = (a + | 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 are stable, and node n_i has a directed edge to
node n_j if the object will quasi-statically topple from f_i to f_j if it
lands on f_i initially.
This computation is described in detail in
http://goldberg.berkeley.edu/pubs/eps.pdf.
Parameters
----------
cvh_mesh : trimesh.Trimesh
Rhe convex hull of the target shape
com : (3,) float
The 3D location of the target shape's center of mass
Returns
-------
graph : networkx.DiGraph
Graph representing static probabilities and toppling
order for the convex hull
"""
adj_graph = nx.Graph()
topple_graph = nx.DiGraph()
# Create face adjacency graph
face_pairs = cvh_mesh.face_adjacency
edges = cvh_mesh.face_adjacency_edges
graph_edges = []
for fp, e in zip(face_pairs, edges):
verts = cvh_mesh.vertices[e]
graph_edges.append([fp[0], fp[1], {'verts': verts}])
adj_graph.add_edges_from(graph_edges)
# Compute static probabilities of landing on each face
for i, tri in enumerate(cvh_mesh.triangles):
prob = _compute_static_prob(tri, com)
topple_graph.add_node(i, prob=prob)
# Compute COM projections onto planes of each triangle in cvh_mesh
proj_dists = np.einsum('ij,ij->i', cvh_mesh.face_normals,
com - cvh_mesh.triangles[:, | 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
----------
permutated: Trimesh object, same faces as input mesh but
rotated and reordered.
"""
matrix | 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.
Default value is mesh.scale/100.0
| 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
Returns
----------
permutated: Trimesh object with remeshed facets
"""
# create random barycentric coordinates for each face
# pad all coordinates by a small amount to bias new vertex towards center
barycentric = np.random.random(mesh.faces.shape) + .05
barycentric /= barycentric.sum(axis=1).reshape((-1, 1))
# create one new vertex somewhere in a face
vertex_face = (barycentric.reshape((-1, 3, 1))
* mesh.triangles).sum(axis=1)
vertex_face_id = np.arange(len(vertex_face)) + len(mesh.vertices)
# new vertices are the old vertices stacked on the vertices in the faces | 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.resolvers.Resolver
Object which can resolve assets
fix_texture : bool
If True, will re- index vertices and faces
so vertices with different UV coordinates
are disconnected.
Returns
---------
mesh_kwargs : dict
Data which can be passed to
Trimesh constructor, eg: a = Trimesh(**mesh_kwargs)
"""
# OrderedDict which is populated from the header
elements, is_ascii, image_name = parse_header(file_obj)
# functions will fill in elements from file_obj
if is_ascii:
| 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
----------
export : bytes of result
"""
# evaluate input args
# allow a shortcut for binary
if encoding == 'binary':
encoding = 'binary_little_endian'
elif encoding not in ['binary_little_endian', 'ascii']:
raise ValueError('encoding must be binary or ascii')
# if vertex normals aren't specifically asked for
# only export them if they are stored in cache
if vertex_normal is None:
vertex_normal = 'vertex_normal' in mesh._cache
# custom numpy dtypes for exporting
dtype_face = [('count', '<u1'),
('index', '<i4', (3))]
dtype_vertex = [('vertex', '<f4', (3))]
# will be appended to main dtype if needed
dtype_vertex_normal = ('normals', '<f4', (3))
dtype_color = ('rgba', '<u1', (4))
# get template strings in dict
templates = json.loads(get_resource('ply.template'))
# start collecting elements into a string for the header
header = templates['intro']
header += templates['vertex']
# if we're exporting vertex normals add them
# to the header and dtype
if vertex_normal:
header += templates['vertex_normal']
dtype_vertex.append(dtype_vertex_normal)
# if mesh has a vertex coloradd it to the header
if mesh.visual.kind == 'vertex' and encoding != 'ascii':
header += templates['color']
dtype_vertex.append(dtype_color)
# create and populate the custom dtype for vertices
vertex = np.zeros(len(mesh.vertices),
dtype=dtype_vertex)
vertex['vertex'] = mesh.vertices
if vertex_normal:
vertex['normals'] = mesh.vertex_normals
if mesh.visual.kind == 'vertex':
vertex['rgba'] = mesh.visual.vertex_colors
header += templates['face']
if mesh.visual.kind == 'face' and encoding != 'ascii':
header += templates['color']
dtype_face.append(dtype_color)
# put mesh face data into custom dtype to export
faces = np.zeros(len(mesh.faces), dtype=dtype_face)
faces['count'] = 3
faces['index'] = mesh.faces
if mesh.visual.kind == 'face' and encoding != 'ascii':
faces['rgba'] = mesh.visual.face_colors
header += templates['outro']
header_params = {'vertex_count': len(mesh.vertices),
'face_count': len(mesh.faces),
'encoding': encoding}
export = | 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 : collections.OrderedDict
Fields and data types populated
is_ascii : bool
Whether the data is ASCII or binary
image_name : None or str
File name of TextureFile
"""
if 'ply' not in str(file_obj.readline()):
raise ValueError('not a ply file!')
# collect the encoding: binary or ASCII
encoding = file_obj.readline().decode('utf-8').strip().lower()
is_ascii = 'ascii' in encoding
# big or little endian
endian = ['<', '>'][int('big' in encoding)]
elements = collections.OrderedDict()
# store file name of TextureFiles in the header
image_name = None
while True:
line = file_obj.readline()
if line is None:
raise ValueError("Header not terminated properly!")
line = line.decode('utf-8').strip().split()
# we're done
if 'end_header' in line:
break
# elements are groups of properties
if 'element' in line[0]:
# we got a new element so add it
name, length = line[1:]
elements[name] = {
'length': int(length),
'properties': collections.OrderedDict()}
# a property is a member of an element
elif 'property' in line[0]:
# is the property a simple single value, like:
# `propert float x`
if len(line) == 3:
dtype, field = line[1:]
elements[name]['properties'][
| 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, with current position at the start
of the data section (past the header)
"""
# get the file contents as a string
text = str(file_obj.read().decode('utf-8'))
# split by newlines
lines = str.splitlines(text)
# get each line as an array split by whitespace
array = np.array([np.fromstring(i, sep=' ')
for i in lines])
# store the line position in the file
position = 0
# loop through data we need
for key, values in elements.items():
# will store (start, end) column index of data
columns = collections.deque()
| 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, with current position at the start
of the data section (past the header)
"""
def populate_listsize(file_obj, elements):
"""
Given a set of elements populated from the header if there are any
list properties seek in the file the length of the list.
Note that if you have a list where each instance is different length
(if for example you mixed triangles and quads) this won't work at all
"""
p_start = file_obj.tell()
p_current = file_obj.tell()
for element_key, element in elements.items():
props = element['properties']
prior_data = ''
for k, dtype in props.items():
if '$LIST' in dtype:
# every list field has two data types:
# the list length (single value), and the list data (multiple)
# here we are only reading the single value for list length
field_dtype = np.dtype(dtype.split(',')[0])
if len(prior_data) == 0:
offset = 0
else:
offset = np.dtype(prior_data).itemsize
file_obj.seek(p_current + offset)
size = np.frombuffer(file_obj.read(field_dtype.itemsize),
dtype=field_dtype)[0]
props[k] = props[k].replace('$LIST', str(size))
prior_data += props[k] + ','
itemsize = np.dtype(', '.join(props.values())).itemsize
p_current += element['length'] * itemsize
file_obj.seek(p_start)
def populate_data(file_obj, elements):
"""
Given the data type and field information from the header,
read the data and add it to a 'data' field in the element.
"""
for key in elements.keys():
items = list(elements[key]['properties'].items())
dtype = np.dtype(items)
| 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
"""
with tempfile.NamedTemporaryFile(suffix='.ply') as temp_ply:
temp_ply.write(export_ply(mesh))
temp_ply.flush()
with tempfile.NamedTemporaryFile(suffix='.drc') as encoded:
subprocess.check_output([draco_encoder,
'-qp', # bits of quantization for position
'28', # since our tol.merge is 1e-8, 25 bits
| 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(suffix='.drc') as temp_drc:
temp_drc.write(file_obj.read())
temp_drc.flush()
with tempfile.NamedTemporaryFile(suffix='.ply') as temp_ply:
subprocess.check_output([draco_decoder,
| 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
---------------
result : trimesh.Trimesh
Result of boolean operation
"""
| 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
----------
vertices : (n, 3) float
Vertices in space
faces : (n, 3) int
Indexes of vertices which make up triangular faces
face_index : faces to subdivide.
if None: all faces of mesh will be subdivided
if (n,) int array of indices: only specified faces
Returns
----------
new_vertices : (n, 3) float
Vertices in space
new_faces : (n, 3) int
Remeshed faces
"""
if face_index is None:
face_index = np.arange(len(faces))
else:
face_index = np.asanyarray(face_index)
# the (c,3) int set of vertex indices
faces = faces[face_index]
# the (c, 3, 3) float set of points in the triangles
triangles = vertices[faces]
# the 3 midpoints of each triangle edge
# stacked to a (3 * c, 3) float
mid = np.vstack([triangles[:, g, :].mean(axis=1)
for g in [[0, 1],
[1, 2],
[2, 0]]])
| 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
------------
vertices : (n, 3) float
Vertices in space
faces : (m, 3) int
Indices of vertices which make up triangles
max_edge : float
Maximum length of any edge in the result
max_iter : int
The maximum number of times to run subdivision
Returns
------------
vertices : (j, 3) float
Vertices in space
faces : (q, 3) int
Indices of vertices
"""
# store completed
done_face = []
done_vert = []
# copy inputs and make sure dtype is correct
current_faces = np.array(faces,
dtype=np.int64,
| 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 | 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 | 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 area or individual triangle area
Returns
----------
| 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 vectors
valid | 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 triangle
u = triangles[:, 1] - triangles[:, 0]
v = triangles[:, 2] - triangles[:, 0]
w = triangles[:, 2] - triangles[:, 1]
# normalize each vector in place
| 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.asanyarray(triangles, dtype=np.float64)
if not util.is_shape(triangles, (-1, 3, 3)):
raise ValueError('Triangles must be (n,3,3)!')
test_normal = normals(triangles)[0]
| 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
Returns
----------
aligned : (n,) bool
Are normals aligned with triangles
"""
triangles = np.asanyarray(triangles, dtype=np.float64)
| 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.asanyarray(triangles, dtype=np.float64)
if not util.is_shape(triangles, (-1, 3, 3)):
raise ValueError('Triangles must be (n,3,3)!') | 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 colinear
Parameters
----------
triangles : (n, 3, 3) float
Triangles in space
height : float
Minimum edge length of a triangle to keep
Returns
----------
nondegenerate : (n,) bool
True if a triangle meets required minimum height
"""
triangles = np.asanyarray(triangles, dtype=np.float64)
if not | 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 each triangle's 2D oriented bounding box
"""
triangles = np.asanyarray(triangles, dtype=np.float64)
if not util.is_shape(triangles, (-1, 3, 3)):
raise ValueError('Triangles must be (n,3,3)!')
if areas is None:
areas = area(triangles=triangles,
sum=False)
# the edge vectors which define the triangle
a = triangles[:, 1] - triangles[:, 0]
b = triangles[:, 2] - triangles[:, 0]
| 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
-----------
points : (m, 3) float
Points in space
"""
barycentric = np.asanyarray(barycentric, dtype=np.float64)
triangles = np.asanyarray(triangles, dtype=np.float64)
if not util.is_shape(triangles, (-1, 3, 3)):
raise ValueError('Triangles must be (n,3,3)!')
if barycentric.shape == (2,):
barycentric = np.ones((len(triangles), 2),
| 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 implements:
https://www.cs.ubc.ca/~heidrich/Papers/JGT.05.pdf
Parameters
-----------
triangles : (n, 3, 3) float
Triangles vertices in space
points : (n, 3) float
Point in space associated with a triangle
method : str
Which method to compute the barycentric coordinates with:
- 'cross': uses a method using cross products, roughly 2x slower but
different numerical robustness properties
- anything else: uses a cramer's rule solution
Returns
-----------
barycentric : (n, 3) float
Barycentric coordinates of each point
"""
def method_cross():
n = np.cross(edge_vectors[:, 0], edge_vectors[:, 1])
denominator = util.diagonal_dot(n, n)
barycentric = np.zeros((len(triangles), 3), dtype=np.float64)
barycentric[:, 2] = util.diagonal_dot(
np.cross(edge_vectors[:, 0], w), n) / denominator
barycentric[:, 1] = util.diagonal_dot(
np.cross(w, edge_vectors[:, 1]), n) / denominator
barycentric[:, 0] = 1 - barycentric[:, 1] - barycentric[:, 2]
return barycentric
def method_cramer():
dot00 = util.diagonal_dot(edge_vectors[:, 0], edge_vectors[:, 0])
dot01 = util.diagonal_dot(edge_vectors[:, 0], edge_vectors[:, 1])
dot02 = util.diagonal_dot(edge_vectors[:, 0], w)
dot11 = | 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 keys 'vertices' and 'faces'
Examples
---------
>>> mesh = trimesh.Trimesh(**trimesh.triangles.to_kwargs(triangles))
"""
triangles = np.asanyarray(triangles, dtype=np.float64)
| python | {
"resource": ""
} |
q23376 | _Primitive.copy | train | def copy(self):
"""
Return a copy of the Primitive object.
"""
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(),
| python | {
"resource": ""
} |
q23378 | Cylinder.volume | train | def volume(self):
"""
The analytic volume of the cylinder primitive.
Returns
---------
volume : float
Volume of the cylinder
"""
| 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,
| 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 = | 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):
| 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
| 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
| 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 are spaced with np.linspace
step : float or (3,) float
If specified samples are spaced with np.arange
Returns
-----------
grid : (n, 3) float
Points inside the box
"""
if (count is not None and
step is not None):
raise ValueError('only step OR count can be specified!')
# create pre- transform bounds from extents
bounds = np.array([-self.primitive.extents,
self.primitive.extents]) * .5
if step | 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, | python | {
"resource": ""
} |
q23386 | Box.volume | train | def volume(self):
"""
Volume of the box Primitive.
Returns
--------
volume: float, volume of box
| 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
| 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
| 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)
translation = np.eye(4)
| 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
| 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 for a final result.
Parameters
-----------
polygons : (n,) shapely.geometry.Polygon
Polygons which only have exteriors and may overlap
Returns
-----------
roots : (m,) int
Index of polygons which are root
contains : networkx.DiGraph
Edges indicate a polygon is
contained by another polygon
"""
tree = Rtree()
# nodes are indexes in polygons
contains = nx.DiGraph()
for i, polygon in enumerate(polygons):
# if a polygon is None it means creation
# failed due to weird geometry so ignore it
if polygon is None or len(polygon.bounds) != 4:
continue
# insert polygon bounds into rtree
tree.insert(i, polygon.bounds)
# make sure every valid polygon has a node
contains.add_node(i)
# loop through every polygon
for i | 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
Returns
----------
polygons : (p,) shapely.geometry.Polygon
Polygon objects with interiors
"""
# create closed polygon objects
polygons = []
# loop through a sequence of ordered traversals
for dfs in graph.traversals(edges, mode='dfs'):
try:
# try to recover polygons before they are more complicated
polygons.append(repair_invalid(Polygon(vertices[dfs])))
except ValueError:
| 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): | 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 matrix
which will move input polygon from its original position
to the first quadrant where the AABB is the OBB
extents: (2,) float, extents of transformed polygon
"""
if hasattr(polygon, | 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
--------------
result : shapely.geometry.Polygon
Polygon transformed by matrix.
"""
matrix = np.asanyarray(matrix, dtype=np.float64)
if util.is_sequence(polygon):
result = [transform_polygon(p, t)
for p, t in zip(polygon, matrix)]
return result
# transform the | 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 matplotlib.pyplot as plt
def plot_single(single):
plt.plot(*single.exterior.xy, **kwargs)
| 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: (2,) int, upper and lower bounds to clip
number of samples to (to avoid exploding counts)
Returns
------------
kwargs: dict, keyword args for a Polygon(**kwargs)
"""
def resample_boundary(boundary):
# add a polygon.exterior or polygon.interior to
# the deque after resampling based on our resolution
count = boundary.length / resolution
count = int(np.clip(count, | 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
The source geometry
resolution : float
Distance between each sample on the polygon boundary
clip : None, or (2,) int
Clip sample count to min of clip[0] and max of clip[1]
Returns
----------
edges : (n, 2) int
Vertex indices representing line segments
on the polygon's medial axis
vertices : (m, 2) float
Vertex positions in space
"""
from scipy.spatial import Voronoi
if resolution is None:
resolution = .01
# get evenly spaced points on the polygons boundaries
samples = resample_boundaries(polygon=polygon,
resolution=resolution,
clip=clip)
# stack the boundary into a (m,2) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.