首页/文章/ 详情

能用ChatGPT写一个CFD求解器吗?

8天前浏览951

ChatGPT是啥?我就不在这里展开了,因为这是街知巷闻的了。


用CFD时使用ChatGPT吗?


   

嗯,你可以在几乎所有项目中使用ChatGPT来满足你的兴趣。但一个大问题是:你对工具有什么期望?正如你们可能知道的,CFD是一个需要广泛经验和比ChatGPT目前能力(至少在目前)更详细建模的复杂主题。然而,你仍然可以使用它来生成2D/3D典型流动的简单CFD求解器。一旦你增加了问题的复杂性,你就必须非常小心地处理你输入给模型的内容(这需要你自己编写代码的经验水平)。我不是说这个工具在这方面没用;我是说为了使用它,你必须有基础水平的知识,成为工具输出给你的内容的一个好的裁判。换句话说,让工具提高你的效率,但不要盲目跟随输出的文本。

例如,我让ChatGPT为使用有限差分法(FDM)的层流2D盖驱动腔流编写了一个Python脚本。第一次它给了我一个非常基础的脚本,它不起作用,我不断细化我的输入(通过非常具体地说明代码结构、问题设置和编写解决方案结果的方式)。这是结果:

正方形腔盖驱动流动

在Paraview中可视化输出vtk文件如下:

[代码片段见下面]:






import numpy as nimport sysfrom datetime import datetimeimport datetime as dt

# clock starts to tick              T0 = datetime.now()
# Defining spatial resolution  def create_mesh(nx, ny, Lx, Ly):    dx = Lx / (nx - 1)    dy = Ly / (ny - 1)    x = np.linspace(0, Lx, nx)    y = np.linspace(0, Ly, ny)    X, Y = np.meshgrid(x, y)    return X, Y, dx, dy
# Initializing the domaindef initial_conditions(X, Y, nx, ny, U_top):    U = np.zeros((ny, nx))    V = np.zeros((ny, nx))    P = np.zeros((ny, nx))    U[-1, :] = U_top    return U, V, P
# pressure Poisson equationdef pressure_poisson(P, dx, dy, U, V, rho, dt, n_iter_pressure):    P_new = np.copy(P)    b = np.zeros_like(P)        b[1:-1, 1:-1] = (rho * (1 / dt * ((U[1:-1, 2:] - U[1:-1, 0:-2]) / (2 * dx) + (V[2:, 1:-1] - V[0:-2, 1:-1]) / (2 * dy)) - ((U[1:-1, 2:] - U[1:-1, 0:-2]) / (2 * dx)) ** 2 - 2 * ((U[2:, 1:-1] - U[0:-2, 1:-1]) / (2 * dy) * (V[1:-1, 2:] - V[1:-1, 0:-2]) / (2 * dx)) - ((V[2:, 1:-1] - V[0:-2, 1:-1]) / (2 * dy)) ** 2))

   #for _ in range(n_iter_pressure):    #    P_new[1:-1, 1:-1] = (((P[1:-1, 2:] + P[1:-1, 0:-2]) * dy ** 2 + (P[2:, 1:-1] + P[0:-2, 1:-1]) * dx ** 2) / (2 * (dx ** 2 + dy ** 2)) - dx ** 2 * dy ** 2 / (2 * (dx ** 2 + dy ** 2)) * b[1:-1, 1:-1])            #    P_new[:, 0] = P_new[:, 1]  # Left boundary    #    P_new[:, -1] = P_new[:, -2]  # Right boundary    #    P_new[0, :] = P_new[1, :]  # Bottom boundary    #    P_new[-1, :] = P_new[-2, :]  # Top boundary    # Iterate over the pressure solver for a specified number of iterations        for _ in range(n_iter_pressure):        # Update the pressure field using the finite volume method        P_new[1:-1, 1:-1] = (            (                # Pressure values from the neighboring cells in the x and y directions                (P[1:-1, 2:] + P[1:-1, 0:-2]) * dy ** 2                + (P[2:, 1:-1] + P[0:-2, 1:-1]) * dx ** 2            )            / (2 * (dx ** 2 + dy ** 2))  # Divide by the sum of squared distances in x and y directions            - dx ** 2 * dy ** 2 / (2 * (dx ** 2 + dy ** 2)) * b[1:-1, 1:-1]  # Subtract the pressure correction term        )

       # Update boundary conditions for pressure        P_new[:, 0] = P_new[:, 1]  # Left boundary        P_new[:, -1] = P_new[:, -2]  # Right boundary        P_new[0, :] = P_new[1, :]  # Bottom boundary        P_new[-1, :] = P_new[-2, :]  # Top boundary

   return P_new    # Update the velocity field     def velocity_field(U, V, P, dx, dy, dt, nu, rho, U_top):    U_new = np.copy(U)    V_new = np.copy(V)

   U_new[1:-1, 1:-1] = (U[1:-1, 1:-1] - U[1:-1, 1:-1] * dt / dx * (U[1:-1, 1:-1] - U[1:-1, 0:-2]) - V[1:-1, 1:-1] * dt / dy * (U[1:-1, 1:-1] - U[0:-2, 1:-1]) - dt / (2 * rho * dx) * (P[1:-1, 2:] - P[1:-1, 0:-2]) + nu * (dt / (dx ** 2) * (U[1:-1, 2:] - 2 * U[1:-1, 1:-1] + U[1:-1, 0:-2]) + dt / (dy ** 2) * (U[2:, 1:-1] - 2 * U[1:-1, 1:-1] + U[0:-2, 1:-1])))    V_new[1:-1, 1:-1] = (V[1:-1, 1:-1] - U[1:-1, 1:-1] * dt / dx * (V[1:-1, 1:-1] - V[1:-1, 0:-2]) - V[1:-1, 1:-1] * dt / dy * (V[1:-1, 1:-1] - V[0:-2, 1:-1]) - dt / (2 * rho * dy) * (P[2:, 1:-1] - P[0:-2, 1:-1]) + nu * (dt / (dx ** 2) * (V[1:-1, 2:] - 2 * V[1:-1, 1:-1] + V[1:-1, 0:-2]) + dt / (dy ** 2) * (V[2:, 1:-1] - 2 * V[1:-1, 1:-1] + V[0:-2, 1:-1])))

   # Boundary conditions    U_new[0, :] = 0    U_new[-1, :] = U_top        U_new[:, 0] = 0    U_new[:, -1] = 0    V_new[0, :] = 0    V_new[-1, :] = 0    V_new[:, 0] = 0    V_new[:, -1] = 0

   return U_new, V_new
# content of VTK files for solution results def write_vtk(X, Y, U, V, P, file_name, nx, ny):    with open(file_name, 'w') as f:        f.write('# vtk DataFile Version 3.0\n')        f.write('2D Cavity Flow\n')        f.write('ASCII\n')        f.write('DATASET STRUCTURED_GRID\n')        f.write('DIMENSIONS {0} {1} 1\n'.format(nx, ny))        f.write('POINTS {0} float\n'.format(nx * ny))        for j in range(ny):            for i in range(nx):                f.write('{0} {1} 0\n'.format(X[j, i], Y[j, i]))
       f.write('POINT_DATA {0}\n'.format(nx * ny))        f.write('VECTORS velocity float\n')        for j in range(ny):            for i in range(nx):                f.write('{0} {1} 0\n'.format(U[j, i], V[j, i]))

       f.write('SCALARS pressure float\n')        f.write('LOOKUP_TABLE default\n')        for j in range(ny):            for i in range(nx):                f.write('{0}\n'.format(P[j, i]))

def main():    Lx, Ly = 1.0, 1.0    nx, ny = 41, 41    n_iter_pressure = 50    n_time_steps = 10000    U_top = 0.5    rho = 1.0    nu = 0.01    dt = 0.001

   # Create mesh    X, Y, dx, dy = create_mesh(nx, ny, Lx, Ly)

   # Initialize velocity and pressure fields    U, V, P = initial_conditions(X, Y, nx, ny, U_top)

   # Time-stepping loop            for n in range(n_time_steps):        # Update pressure field        P = pressure_poisson(P, dx, dy, U, V, rho, dt, n_iter_pressure)

       # Update velocity field        U, V = velocity_field(U, V, P, dx, dy, dt, nu, rho, U_top)                # Save results every N time steps        N = 200        if n % N == 0:            file_name = f'cavity_flow_2D_{n:04d}.vtk'            print('====================================')            print('Writing solution for time step:', n)            #print('====================================')            write_vtk(X, Y, U, V, P, file_name, nx, ny)

   if n == n_time_steps:        print('====================================')        print('Job is completed successfully ')        print('====================================')    # Write results to a VTK file [when uncommented, will write the solution at every time step!]    #write_vtk(X, Y, U, V, P, 'cavity_flow.vtk', nx, ny)

if __name__ == '__main__':    main()

# Print inital and final timesTf = datetime.now()print()print('+++++++++++++++++++++++++++++++++++++++++++')print('--------------- DATE & TIME ---------------')print(T0)print('+++++++++++++++++++++++++++++++++++++++++++')print(Tf)print('+++++++++++++++++++++++++++++++++++++++++++')

#=========# Summary # ========# This Python code is a script for simulating 2D incompressible flow in a cavity using the finite difference method. The cavity has a top lid that is moving at a constant velocity, while the other three walls are stationary. The simulation aims to solve the Navier-Stokes equations for fluid flow, which describe the conservation of momentum, and the pressure Poisson equation, which is derived from the continuity equation to maintain the incompressible flow condition.
# Here's a brief overview of the code:
# Import the necessary libraries: numpy and sys.# Define a function create_mesh() to create a structured grid in the x-y plane with specified dimensions and number of points in each direction.# Define a function initial_conditions() to set the initial values for the velocity (U and V) and pressure (P) fields. The top lid is initialized with a given velocity (U_top).# Define a function pressure_poisson() to solve the pressure Poisson equation using given number of iterations.# Define a function velocity_field() to update the velocity fields (U and V) using the updated pressure field and the given parameters (time step, fluid viscosity, fluid density, and lid velocity).# Define a function write_vtk() to output the results (velocity and pressure fields) to a VTK file, which can be visualized using a software like ParaView.# Define the main() function, which initializes the simulation parameters, creates the mesh, sets the initial conditions, runs the time-stepping loop for updating the pressure and velocity fields, and writes the results to a VTK file.# Finally, the script checks if it is being run as the main module and calls the main() function.# The code is structured and written in a way that it can be easily modified to accommodate different simulation parameters or other boundary conditions.

注意!正如我上面提到的,你不应该直接信任来自ChatGPT的代码生成的代码必须逐行追踪,并且在使用前必须经过验证和测试。这只是一个说明性的例子,用来展示到目前为止这个工具能走多远。


Visual Chat-GPT在CFD中的应用


   

你可能听说过,Visual-ChatGPT是ChatGPT架构的一个最新扩展,专门设计用来根据视觉输入(如图像或视频)生成自然语言文本。该模型是在大量图像-标题对的数据集上训练的,每张图像都与一个或多个描述图像内容的自然语言标题相关联。

到目前为止,Visual-ChatGPT在生成图像的自然语言描述、回答视觉场景的问题,甚至根据文本描述生成新图像方面,都显示出了非常令人印象深刻的结果。这些能力可能在优化CFD模拟中的网格时非常有用,例如,允许用户使用自然语言文本描述几何形状,结果将是:基于这些描述生成高质量的网格🤯这将是CFD领域真正的游戏规则改变者。

例如,你可以提供所需的网格特性描述,如“一个高质量的网格,具有统一的单元大小和低畸变,集中在锐利边缘周围的区域,并在靠近墙壁的地方至少生成15层棱柱层”,Visual-ChatGPT可以生成满足这些要求的相应网格。这可以帮助简化网格生成过程,使其更容易为非专家使用,同时也提高了CFD模拟的准确性和效率。另一个特性可能是提供网格的快照,并要求在某些区域提高质量。或者输入一个网格图片,比如说2D网格,然后让ChatGPT为这个网格生成一个可定制的脚本。

再次强调,这只是一个语言模型。因此,请记住,生成高质量的网格不仅需要描述所需的网格特性,还需要理解被模拟的物理几何和流场,这可能需要事先在网格生成方面拥有现有的专业知识。


如何更好使用ChatGPT


   

1)记住,这是一个AI语言模型!这意味着什么?这意味着,尽管这个工具非常能够生成优化的基于文本的输出,但它仍然容易"出错"

2)请记住,ChatGPT以块结构化的方式工作,这意味着你必须逐步构建块才能得到你需要的东西。如果你从一个非常详细的问题开始,提出一个高度技术性的问题,它可能会给你一个非常通用的答案(这里我指的是它可能给出的最通用的答案)。相反,给出你来自哪里和你去哪里的想法(介绍性背景 --> 明确定义的问题 --> 有用的答案)。

3)你必须充分意识到ChatGPT不是谷歌那样的搜索引擎。除了每个工具给出的单一/多重输出外,ChatGPT基于它的训练数据和它接收到的输入。也就是说,除非你用正确的输入喂养它,否则ChatGPT不会给你你寻求的效率 - 你需要具体(记住我们关于注意力基础变换器的话)。假设你需要知道你想承担的项目预算的大致估计。不要输入像“为巧克力工厂的平面设计项目可能的预算是多少”这样的内容,你需要更详细,并为模型提供“参数”,以便它考虑计算你项目的预算。你可以写一些像 “我是一名有XX年经验的平面设计师,我即将承担一个为巧克力工厂设计标志的项目。这个标志需要以动画版本交付,可能需要像Adobe软件包这样的复杂工具。设计可能需要一个高规格的图形卡进行渲染。考虑到设计可能需要多次迭代直到最终标志被同意,你能给我一个这个项目应该花费多少的大致估计吗”。

4)为了最大限度地利用ChatGPT(如第2点所述),你需要花些时间首先了解你的情况。当ChatGPT在任何领域通过复 制粘贴的方式使用时,这是毫无意义的。

5)你必须意识到,除了ChatGPT可能存在的文字/编码错误外,它也可能给出不完整的答案(特别是当你的输入不足时) - 因为简单地说,它没有足够的数据来知道你想知道什么。


来源:CFD饭圈
ACTSTEPS通用pythonUM理论科普游戏工厂渲染ParaView
著作权归作者所有,欢迎分享,未经许可,不得转载
首次发布时间:2024-09-08
最近编辑:8天前
CFD饭圈
硕士 分享CFD文章,感谢关注
获赞 9粉丝 4文章 345课程 0
点赞
收藏
作者推荐

介绍一款免费且开源的硬件加速多物理场仿真平台

Advanced Simulation Library(ASL)是一个免费且开源的硬件加速多物理场仿真平台。它使用户能够用 C++ 编写定制的数值求解器,并将其部署在从廉价的 FPGA、DSP 和 GPU到异构集群和超级计算机等各种大规模并行架构上。其内部计算引擎用 OpenCL 编写,并采用无矩阵解决方案技术。ASL 实现了多种现代数值方法,包括水平集方法、格子玻尔兹曼、浸入边界等。无网格的浸入边界方法使用户能够直接从 CAD 到仿真,减少预处理工作量和潜在错误数量。ASL 可用于模拟各种耦合的物理和化学现象,特别是在计算流体动力学领域。它在自由的 GNU Affero 通用公共许可证下分发,并可选择基于宽松的 MIT 许可证的商业许可证。 历史 Advanced Simulation Library由以色列公司 Avtech Scientific 开发。其源代码于 2015 年 5 月 14 日发布给社区,社区成员随后不久就为所有主要 Linux 发行版的科学部分打包了它。随后,Khronos 组织承认了 ASL 的重要性,并将其列为其网站上基于 OpenCL 的资源之一。 应用领域 1) 计算流体动力学2) 计算机辅助手术3) 虚拟传感4) 工业过程数据验证和协调5) 多学科设计优化6) 设计空间探索7) 计算机辅助工程8) 晶体学9) 微流体学优点 1) C++ API(无需 OpenCL 知识) 2) 无网格的浸入边界方法允许用户从 CAD 直接到计算,减少预处理工作3) 动态编译在运行时提供了额外的优化层(即对于特定的参数集,提供了应用程序)4) 自动硬件加速和应用程序的并行化5) 在各种并行架构上部署相同程序 - GPU、APU、FPGA、DSP、多核 CPU6) 处理复杂边界的能力7) 纳入微观交互的能力8) 源代码的可用性缺点 1) 缺乏详细的文档(除了从源代码注释生成的开发者指南)2) 并非所有的 OpenCL 驱动程序都足够成熟,适用于该库图:采用物理气相沉积(PVD)方法的涂层过程仿真 图:图像引导神经外科手术,脑变形模拟仿真图:机车在隧道中的气动力学仿真功能 ASL 提供了一系列功能,以解决从涉及化学反应、湍流和热传递的复杂流体流动,到固体力学和弹性等一系列问题。1)接口:VTK/ParaView、MATLAB(导出)。导入文件格式:.stl .vtp .vtk .vti .mnc .dcm导出文件格式:.vti .mat2)几何:使用简单的矩形网格灵活创建复杂几何形状无网格,浸入边界方法几何原形的生成和操作3)实现的现象:传输过程多组分传输过程可压缩和不可压缩流体流动化学反应电极反应弹性均匀各向同性弹性均匀各向同性孔隙弹性界面跟踪界面的演变晶体学动力学界面的演变 来源:CFD饭圈

未登录
还没有评论
课程
培训
服务
行家
VIP会员 学习 福利任务 兑换礼品
下载APP
联系我们
帮助与反馈