Skip to content

Instantly share code, notes, and snippets.

@mzucker
Created March 15, 2020 23:06
Show Gist options
  • Save mzucker/b0846f304b48702ff2530294134ae879 to your computer and use it in GitHub Desktop.
Save mzucker/b0846f304b48702ff2530294134ae879 to your computer and use it in GitHub Desktop.
Demo for attributes in triangle, see https://github.com/drufat/triangle/issues/43
import triangle
import numpy
import matplotlib.pyplot as plt
# monkey-patch triangle library to enable -A option (see what happens
# if do_patch is false)
do_patch = True
if do_patch:
terms = triangle.tri.terms
terms = terms + ( ('triangleattributelist', 'triangle_attributes'), )
triangle.tri.translate_frw = {_0: _1 for _0, _1 in terms}
triangle.tri.translate_inv = {_1: _0 for _0, _1 in terms}
print('monkey-patched to convert triangleattributelist <=> triangle_attributes')
# arrays to fill in with input
vertices = []
segments = []
regions = []
# make a box with given dims and place given attribute at its center
def make_box(x, y, w, h, attribute):
i = len(vertices)
vertices.append([x, y])
vertices.append([x+w, y])
vertices.append([x+w, y+h])
vertices.append([x, y+h])
segments.append((i+0, i+1))
segments.append((i+1, i+2))
segments.append((i+2, i+3))
segments.append((i+3, i+0))
regions.append([x+0.5*w, y+0.5*h, attribute, 0])
# generate some input
make_box(0, 0, 5, 5, 1)
make_box(1, 1, 3, 1, 2)
make_box(1, 3, 1, 1, 3)
make_box(3, 3, 1, 1, 4)
# convert to dictionary of numpy arrays
tri_input = dict(vertices=numpy.array(vertices),
segments=numpy.array(segments),
regions=numpy.array(regions))
# plot input to triangle library
triangle.plot(plt.axes(), **tri_input)
for x, y, attr, _ in regions:
plt.plot(x, y, 'm.')
plt.text(x, y, ' {:g}'.format(attr), color='m')
plt.savefig('tri_input.png')
print('wrote tri_input.png')
# triangulate with p (because PSLG) and A (to get attributes)
tri_output = triangle.triangulate(tri_input, 'pA')
# now plot the output
plt.clf()
triangle.plot(plt.axes(), **tri_output)
for tidx, attr in zip(tri_output['triangles'],
tri_output['triangle_attributes'].flatten()):
tri_verts = tri_output['vertices'][tidx]
x, y = tri_verts.mean(axis=0)
plt.plot(x, y, 'm.')
plt.text(x, y, ' {:g}'.format(attr), color='m')
plt.savefig('tri_output.png')
print('wrote tri_output.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment