Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

พล็อตผลลัพธ์ FEM 2 มิติด้วย Matplotlib ใช้ tricontourf

วิธีการองค์ประกอบจำกัด (Finite Element Method - FEM) แบ่งโดเมนใหญ่เป็นองค์ประกอบเล็กๆ เพื่อจำลองทางฟิสิกส์ สามารถแสดงผล 2D ได้ด้วย tricontourf() ของ Matplotlib ซึ่งรองรับ unstructured triangular grid

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้างข้อมูล nodes (จุด), elements (สามเหลี่ยม), และ values (ค่าที่โนด)
  3. Transpose nodes เพื่อแยก x, y
  4. ใช้ plt.tricontourf(x, y, elements-1, values, levels, cmap)
  5. แสดงผลด้วย show()

ตัวอย่างโค้ด

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# จุด (nodes)
nodes = np.array([
    [0.0, 0.0],
    [1.0, 0.0],
    [2.0, 0.5],
    [0.0, 1.0],
    [1.0, 1.0],
    [1.7, 1.3],
    [1.0, 1.7]
])

# องค์ประกอบ (elements) - ดัชนีเริ่มที่ 1
elements = np.array([
    [1, 2, 5],
    [5, 4, 1],
    [2, 3, 6],
    [6, 5, 2],
    [4, 5, 7],
    [5, 6, 7]
])

# ค่าที่โนด
values = [1, 2, 1, 2, 7, 4, 5]

x, y = nodes.T
plt.tricontourf(x, y, elements - 1, values, 12, cmap='copper')
plt.colorbar(label='Value')
plt.title('2D FEM Result Visualization')
plt.show()

ผลลัพธ์

จะแสดงกราฟ contour เติมสี (filled contour) แสดงการกระจายค่า FEM บนโดเมน 2D