日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python繪制正二十面體圖形示例_python

作者:微小冷 ? 更新時間: 2023-02-01 編程語言

正二十面體的頂點

正20面體的12個頂點剛好可以分為三組,每一組都是一個符合黃金分割比例的長方形,而且這三個長方形是互相正交的。

所以,想繪制一個正二十面體是比較容易的

import numpy as np
from itertools import product
G = (np.sqrt(5)-1)/2
def getVertex():
    pt2 =  [(a,b) for a,b in product([1,-1], [G, -G])]
    pts =  [(a,b,0) for a,b in pt2]
    pts += [(0,a,b) for a,b in pt2]
    pts += [(b,0,a) for a,b in pt2]
    return np.array(pts)

xs, ys zs = getVertex().T
ax = plt.subplot(projection='3d')
ax.scatter(xs, ys, zs)
plt.show()

得到頂點

繪制棱

接下來將這些頂點連接成線,由于總共只有12個頂點,所以兩兩相連,也不至于導致運算量爆炸。另一方面,正二十面體的邊長是相同的,而這些相同的邊連接的也必然是最近的點,所以接下來只需建立頂點之間的距離矩陣,然后將距離最短的線抽出來即可。

def getDisMat(pts):
    N = len(pts)
    dMat = np.ones([N,N])*np.inf
    for i in range(N):
        for j in range(i):
            dMat[i,j] = np.linalg.norm([pts[i]-pts[j]])
    return dMat

pts = getVertex()
dMat = getDisMat(pts)
# 由于存在舍入誤差,所以得到的邊的數值可能不唯一
ix, jx = np.where((dMat-np.min(dMat))<0.01)

接下來,繪制正二十面體的棱

edges = [pts[[i,j]] for i,j in zip(ix, jx)]

ax = plt.subplot(projection='3d')
for pt in edges:
    ax.plot(*pt.T)

plt.show()

效果如圖所示

繪制面

當然,只是有棱還顯得不太好看,接下來要對正二十面體的面進行上色。由于三條棱構成一個面,所以只需得到所有三條棱的組合,然后判定這三條棱是否可以組成一個三角形,就可以獲取所有的三角面。當然,這一切的前提是,正二十面體只有30個棱,即使遍歷多次,也無非27k的計算量,是完全沒問題的。

def isFace(e1, e2, e3):
    pts = np.vstack([e1, e2, e3])
    pts = np.unique(pts, axis=0)
    return len(pts)==3

from itertools import combinations
faces = [es for es in combinations(edges, 3) 
    if isFace(*es)]

接下來繪制一下

ax = plt.subplot(projection='3d')
for f in faces:
    pt = np.unique(np.vstack(f), axis=0)
    try:
        ax.plot_trisurf(*pt.T)
    except:
        pass

plt.show()

如圖所示

由于plot_trisurf的畫圖邏輯是,先繪制xy坐標系上的三角形,然后再以此為三角形建立z軸坐標。所以這會導致一個Bug,即所繪制的三角面不能垂直于xy坐標系,為了讓正二十面體被完整地繪制出來,可以對其繞著x和y軸旋轉一下,當然首先要建立一個旋轉矩陣。三維空間中的旋轉矩陣如下表所示。詳情可參考博客:Python動態演示旋轉矩陣的作用

寫成代碼為

# 將角度轉弧度后再求余弦
cos = lambda th : np.cos(np.deg2rad(th))
sin = lambda th : np.sin(np.deg2rad(th))

# 即 Rx(th) => Matrix
Rx = lambda th : np.array([
    [1, 0,       0],
    [0, cos(th), -sin(th)],
    [0, sin(th), cos(th)]])
Ry = lambda th : np.array([
    [cos(th),  0, sin(th)],
    [0      ,  1, 0],
    [-sin(th), 0, cos(th)]
])

然后繪圖函數

ax = plt.subplot(projection='3d')
for f in faces:
    pt = np.unique(np.vstack(f), axis=0)
    pt = Rx(1)@Ry(1)@pt.T
    ax.plot_trisurf(*pt)

for pt in edges:
    pt = Rx(1)@Ry(1)@pt.T
    ax.plot(*pt, lw=2, color='blue')

plt.show()  

效果如下

總結

原文鏈接:https://blog.csdn.net/m0_37816922/article/details/128258800

欄目分類
最近更新