1

我有这个 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

提前感谢您的帮助!

4

1 回答 1

2

这是使用numpy提供的矢量化运算符对您的问题的重新处理。

import numpy as np

#define triangles
triangles = np.array([[coords[e] for e in elem] for elem in elems])

#find centroid of each triangle
CM = np.mean(triangles,axis=1)

#find vector from each point in triangle pointing towards centroid
point_to_CM_vectors = CM[:,np.newaxis] - triangles

#calculate similar triangles 1% smaller
new_triangle = triangles + 0.01*point_to_CM_vectors
于 2013-04-13T23:48:19.780 回答