<p>编辑:</em></p>
<p>如果内存有问题,也可以使用“批处理”版本的算法,一次只处理有限数量的面:</p>
<p>将numpy作为np导入</p>
<pre><code>def face2vertVal(faces, faces_values, batch_size=None):
batch_size = batch_size or len(faces)
faces = np.asarray(faces)
faces_values = np.asarray(faces_values)
vert_idx = np.arange(faces.max() + 1)
vertex_values = np.zeros(len(vert_idx))
vertex_counts = np.zeros(len(vert_idx))
for i in range(0, len(faces), batch_size):
faces_batch = faces[i:i + batch_size]
faces_values_batch = faces_values[i:i + batch_size]
vertex_faces = np.any(faces_batch == vert_idx[:, np.newaxis, np.newaxis], axis=-1)
vertex_values += np.sum(vertex_faces * faces_values_batch, axis=1)
vertex_counts += np.count_nonzero(vertex_faces, axis=1)
return vertex_values / np.maximum(vertex_counts, 0)
# All at once
vertex_values = face2vertVal([[0, 1, 2], [1, 2, 3], [2, 3, 0]], [1, 2, 3])
print(*vertex_values, sep=', ')
# 2.0, 1.5, 2.0, 2.5
# In batches of two
vertex_values_1b = face2vertVal([[0, 1, 2], [1, 2, 3], [2, 3, 0]], [1, 2, 3], 2)
print(*vertex_values_1b, sep=', ')
# 2.0, 1.5, 2.0, 2.5
</code></pre>
<p>您可以手动选择<code>batch_size</code>(或者根据要使用的内存或其他内容使用一些公式)来平衡速度和内存之间的平衡。你知道吗</p>
<hr/>
<p>你应该以矢量化的方式进行计算,否则会慢得多。这是一种方法:</p>
<pre><code>import numpy as np
def face2vertVal(faces, faces_values):
faces = np.asarray(faces)
faces_values = np.asarray(faces_values)
vert_idx = np.arange(faces.max() + 1)
vertex_faces = np.any(faces == vert_idx[:, np.newaxis, np.newaxis], axis=-1)
vertex_values = np.sum(vertex_faces * faces_values, axis=1) / np.maximum(np.count_nonzero(vertex_faces, axis=1), 0)
return vertex_values
vertex_values = face2vertVal([[0, 1, 2], [1, 2, 3], [2, 3, 0]], [1, 2, 3])
print(*vertex_values, sep=', ')
# 2.0, 1.5, 2.0, 2.5
</code></pre>
<p>请注意,这种方法的缺点是,给定具有<code>P</code>顶点的<code>N</code>面,它需要<code>O(N*P)</code>内存,而非矢量化算法使用<code>O(max(N, P))</code>内存。你知道吗</p>