我有这个 Python 脚本,它应该调整一组三角形元素的坐标。该脚本应将节点的坐标从元素更改为元素的重心。下图是我为这个问题制作的草图。
但是我的脚本有问题,我不知道是什么。坐标不会在正确的方向上改变,并且会生成额外的新坐标,而我只想调整现有坐标。
有谁知道如何在 Python 中正确编程?
coords = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 1.0], [1.0, 1.0], [0.0, 2.0], [0.0, 2.0], [1.0, 1.0], [1.0, 2.0], [1.0, 1.0], [2.0, 1.0], [1.0, 2.0], [1.0, 2.0], [2.0, 1.0], [2.0, 2.0], [1.0, 1.0], [2.0, 0.0], [2.0, 1.0], [1.0, 0.0], [2.0, 0.0], [1.0, 1.0]]
elems = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20], [21, 22, 23]]
#define vectors
def add_vectors(*points):
new_x = 0.0
new_y = 0.0
for point in points:
new_x += point[0]
new_y += point[1]
return [new_x, new_y]
def subtract_vectors(a, b):
new_x = a[0] - b[0]
new_y = a[1] - b[1]
return [new_x, new_y]
def mul_by_scalar(vector, scalar):
new_x = vector[0] * scalar
new_y = vector[1] * scalar
return [new_x, new_y]
#define triangles
triangles = []
for elem in elems:
triangles += [coords[e] for e in elem]
#adjust coordinates
CM = mul_by_scalar(add_vectors(*triangles), 1.0/3)
point_to_CM_vectors = []
for point in triangles:
point_to_CM_vectors.append(subtract_vectors(CM, point))
new_triangle = []
for elem in elems:
for point, motion in zip(triangles, point_to_CM_vectors):
new_triangle.append(add_vectors(point, mul_by_scalar(motion, 0.01)))
print 'triangles =', triangles
print 'new_triangle =', new_triangle
提前感谢您的帮助!