【问题标题】:How can I plot 2d FEM results using matplotlib?如何使用 matplotlib 绘制 2d FEM 结果?
【发布时间】:2019-02-11 14:17:59
【问题描述】:

我正在开发一个二维平面有限元工具。其中一项功能是能够可视化特定对象上的应力。

此工具使用以下数据创建四边形网格:

  • 节点:numpy 数组[[x1 y1], [x2 y2], etc] -> xy 网格中每个节点的坐标

  • 元素:numpy 数组[[1 2 3 4], [2 3 5 6]] -> 数组的每一行对应于网格中一个特定元素的4 个点。

我能够实现一种绘制网格的方法:

import matplotlib.pyplot as plt
import matplotlib.collections
import matplotlib.cm as cm

import numpy as np


def showMeshPlot(nodes, elements):

    y = nodes[:,0]
    z = nodes[:,1]

    #https://stackoverflow.com/questions/49640311/matplotlib-unstructered-quadrilaterals-instead-of-triangles
    def quatplot(y,z, quatrangles, ax=None, **kwargs):

        if not ax: ax=plt.gca()
        yz = np.c_[y,z]
        verts= yz[quatrangles]
        pc = matplotlib.collections.PolyCollection(verts, **kwargs)
        ax.add_collection(pc)
        ax.autoscale()

    plt.figure()
    plt.gca().set_aspect('equal')

    quatplot(y,z, np.asarray(elements), ax=None, color="crimson", facecolor="None")
    if nodes:            
        plt.plot(y,z, marker="o", ls="", color="crimson")

    plt.title('This is the plot for: quad')
    plt.xlabel('Y Axis')
    plt.ylabel('Z Axis')


    plt.show()

nodes = np.array([[0,0], [0,0.5],[0,1],[0.5,0], [0.5,0.5], [0.5,1], [1,0], 
                  [1,0.5],[1,1]])
elements = np.array([[0,3,4,1],[1,4,5,2],[3,6,7,4],[4,7,8,5]])
stresses = np.array([1,2,3,4])

showMeshPlot(nodes, elements)

这会产生这样的情节:

现在,我有一个一维数组,其中包含对象上的应力,长度与元素数组相同。

我的问题是如何使用 matplotlib 可视化这些压力(带有标量条)?我查看了 pcolormesh,但我不明白它如何处理我的数据。这是我想要实现的一个示例(robbievanleeuwen 的学分):

注意:我无法复制上面的示例,因为他使用三角形网格而不是四边形。

提前致谢!

【问题讨论】:

  • 代码中没有stress,代码一般是不可运行的,这里很难给出答案。这里的主要想法当然是为 PolyCollection 提供一个颜色图、一个规范和一个数组,并为该 PolyCollection 创建一个颜色条。
  • 这只是我必须创建常规线框网格的方法的一个示例。我只想通过应力数组(与元素数组长度相同的一维数组)为元素赋予颜色。基本上,我想找到一种方法将我的元素数组(使用问题中显示的格式)关联到压力数组。
  • 我目前看不出我上面的建议不起作用的任何原因。但是,如果您希望将其作为答案,我想确保确实如此。我只能使用问题中提供的可运行代码来做到这一点。
  • 感谢您的回答,我更改了示例,现在可以使用了。基本上我希望,例如,强调[0] 与元素[0] 等相关。

标签: python matplotlib data-visualization mesh


【解决方案1】:

我认为您最好的选择是使用tricontour。你已经有了三角测量,对吧?

它会创建这样的图:

(from here)

https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tricontour.html

【讨论】:

  • 问题是我本身没有三角测量。我有 4 个节点的元素,我认为 tricontour 仅适用于三角形..
  • 分割四边形? ;)
  • 另外,您不需要三角测量。如果您只传递 x,y,该函数将使用 Delaunay 创建它。 tricontour(x, y, ...) 那么你不是在绘制你计算的网格,但谁在乎它是否是彩色图。 :)
  • 您好,谢谢您的回答!但我不太明白你的意思。你能用我在我的问题中发布的更新代码做一个例子吗?基本上我希望,例如,stress[0] 与 elements[0] 等相关
  • 原则上您是对的,您可以将积分直接传递给tricontour。这适用于一般情况;但是在这里您会遇到两个问题:首先,应力值的数量与生成的三角形的数量不匹配,并且很难将这些创建的三角形映射到颜色。其次,如果网格包含示例图片中的“孔”,它将失败,因为三角剖分只会在孔内产生三角形。
【解决方案2】:

PolyCollection 是ScalarMappable。它可以有一个值数组、一个颜色图和一个标准化集。在这里,您将向 PolyCollection 提供 stresses 数组并选择一些要使用的颜色图。 剩下的就是重新排列函数,这样可以将额外的数据作为输入并创建一个颜色条。

import matplotlib.pyplot as plt
import matplotlib.collections
import numpy as np


def showMeshPlot(nodes, elements, values):

    y = nodes[:,0]
    z = nodes[:,1]

    def quatplot(y,z, quatrangles, values, ax=None, **kwargs):

        if not ax: ax=plt.gca()
        yz = np.c_[y,z]
        verts= yz[quatrangles]
        pc = matplotlib.collections.PolyCollection(verts, **kwargs)
        pc.set_array(values)
        ax.add_collection(pc)
        ax.autoscale()
        return pc

    fig, ax = plt.subplots()
    ax.set_aspect('equal')

    pc = quatplot(y,z, np.asarray(elements), values, ax=ax, 
             edgecolor="crimson", cmap="rainbow")
    fig.colorbar(pc, ax=ax)        
    ax.plot(y,z, marker="o", ls="", color="crimson")

    ax.set(title='This is the plot for: quad', xlabel='Y Axis', ylabel='Z Axis')

    plt.show()

nodes = np.array([[0,0], [0,0.5],[0,1],[0.5,0], [0.5,0.5], [0.5,1], [1,0], 
                  [1,0.5],[1,1]])
elements = np.array([[0,3,4,1],[1,4,5,2],[3,6,7,4],[4,7,8,5]])
stresses = np.array([1,2,3,4])

showMeshPlot(nodes, elements, stresses)

【讨论】:

  • 是否有可能以某种方式在四边形之间进行平滑过渡?
  • 这会抵消绘制四边形的最初想法。您可以使用其他答案中的tricontour 来获得平滑的形状。
【解决方案3】:

经过一段时间的思考,以下代码是使用matplotlib 绘制 FEM 网格(具有节点标量场)的最简单方法之一。

此解决方案基于matplotlib.pyplot.tricontourf()。不幸的是,如果有限元网格中有四边形或更高阶元素,matplotlib 没有简单的方法来绘制填充轮廓。为了绘制轮廓,必须首先将所有元素“切割”成三角形,例如,可以将一个四边形分割或切割成 2 个三角形,依此类推...

还必须使用自定义方法来绘制网格线,因为matplotlib.pyplot.tricontourf() 仅适用于三角形网格/网格。为此,使用了matplotlib.pyplot.fill()

下面是完整的代码和一个简单的例子:

import matplotlib.pyplot as plt
import matplotlib.tri as tri

# converts quad elements into tri elements
def quads_to_tris(quads):
    tris = [[None for j in range(3)] for i in range(2*len(quads))]
    for i in range(len(quads)):
        j = 2*i
        n0 = quads[i][0]
        n1 = quads[i][1]
        n2 = quads[i][2]
        n3 = quads[i][3]
        tris[j][0] = n0
        tris[j][1] = n1
        tris[j][2] = n2
        tris[j + 1][0] = n2
        tris[j + 1][1] = n3
        tris[j + 1][2] = n0
    return tris

# plots a finite element mesh
def plot_fem_mesh(nodes_x, nodes_y, elements):
    for element in elements:
        x = [nodes_x[element[i]] for i in range(len(element))]
        y = [nodes_y[element[i]] for i in range(len(element))]
        plt.fill(x, y, edgecolor='black', fill=False)

# FEM data
nodes_x = [0.0, 1.0, 2.0, 0.0, 1.0, 2.0, 3.0, 0.0, 1.0, 2.0, 3.0]
nodes_y = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0]
nodal_values = [1.0, 0.9, 1.1, 0.9, 2.1, 2.1, 0.9, 1.0, 1.0, 0.9, 0.8]
elements_tris = [[2, 6, 5], [5, 6, 10], [10, 9, 5]]
elements_quads = [[0, 1, 4, 3], [1, 2, 5, 4], [3, 4, 8, 7], [4, 5, 9, 8]]
elements = elements_tris + elements_quads

# convert all elements into triangles
elements_all_tris = elements_tris + quads_to_tris(elements_quads)

# create an unstructured triangular grid instance
triangulation = tri.Triangulation(nodes_x, nodes_y, elements_all_tris)

# plot the finite element mesh
plot_fem_mesh(nodes_x, nodes_y, elements)

# plot the contours
plt.tricontourf(triangulation, nodal_values)

# show
plt.colorbar()
plt.axis('equal')
plt.show()

哪些输出:

只需更改 FEM 数据(节点、节点值、元素),上面的代码就可以用于更复杂的网格,但是,该代码仅准备处理包含三角形和四边形的网格:

您可能会注意到,对于大型网格,matplotlib 会变慢。还有matplotlib 您无法可视化 3D 元素。因此,为了提高效率和更多功能,请考虑改用 VTK。

【讨论】:

  • Mayavi 是一个在 Python 中使用 VTK 的好模块。
【解决方案4】:

pyvista 是一种更简单的绘制 fem 网格的方法,而不是使用 matplotlib。您可以使用我可以用meshio 重现的任意 vtk 网格。通过节点上的位移属性或应力或应变的整个元素上的属性,您可以轻松实现 2D 和 3D 可视化。

【讨论】:

    猜你喜欢
    • 2017-12-13
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多