gpt4 book ai didi

Python:调整坐标

转载 作者:行者123 更新时间:2023-12-01 05:46:22 25 4
gpt4 key购买 nike

我有这个 Python 脚本,它应该调整一组三角形元素的坐标。该脚本应将节点的坐标从元素更改为元素的重心。下图是我针对该问题绘制的草图。

enter image description here

但是我的脚本出了问题,我不知道是什么问题。坐标没有按照正确的方向改变,并且生成了额外的新坐标,而我只想调整现有的坐标。

有人知道如何用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

预先感谢您的帮助!

最佳答案

这里使用 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

关于Python:调整坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15991536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com