首页 > 编程问答 >使用solve_ivp求解二维热方程

使用solve_ivp求解二维热方程

时间:2024-07-22 05:33:25浏览次数:8  
标签:python ode pde heat

我正在尝试使用有限差分法作为使用solve_ivp 方法的图像过滤技术来求解二维热方程。我的代码显示了一条错误消息“ y0 必须是一维的”,我不明白为什么会这样。

import numpy as np
import imageio.v2 as imageio
from skimage import color
from skimage import io
import scipy.sparse as sp
from scipy.integrate import solve_ivp

im3 = imageio.imread('photo.jpg')

#convert the image to a numpy array for easier mathematical use
nparray3 = np.asarray(im3)

#convert the image to its grayscle version
grayimg3 = color.rgb2gray(nparray3)

#add noise on the gray image: The result is the initial condition of our system
noisygrayimg3 = grayimg3+1.5*np.random.rand(grayimg3.shape[0],grayimg3.shape[1])

#Reshape the initial conditions into a vector so it can be passed into the ODE solver
U0 = np.reshape(noisygrayimg3, (width3*height3, 1)) 


#solve the diffusion equation
#STEP 1: define the function that returns du/dt which computes the right hand side of     
the heat equation
def Diffusion_rhs(t,u):
    # Read an image 
    im3 = imageio.imread('photo.jpg')

    #find out the dimsnions of the image
    height3, width3, colours3 = im3.shape

    #Define a grid of x and y variables and their derivatives
    #x variable
    x = np.linspace(0,1,width3) #patial vector
    dx = x[1]-x[0] #spatial step size
    onex = np.ones(width3)
    Ix = np.eye(width3)
    Dx = sp.spdiags([onex , -2*onex , onex], [-1, 0, 1], width3, width3) #x 1D matrix     
    500x500
    #y variable
    y = np.linspace(0,1,height3) #patial vector
    dy = y[1]-y[0] #spatial step size
    oney = np.ones(height3)
    Iy = np.eye(height3)
    Dy = sp.spdiags([oney , -2*oney , oney], [-1, 0, 1], height3, height3) #y 1D matrix 
    400x400

    #create the 2D Laplacian
    A = sp.kron(Dx,Iy) + sp.kron(Ix,Dy) 

    #Define the Diffusion coefficient
    D = 0.005

    #caluclate the right-hand side
    dudt = D * A* u
    return dudt

#STEP 2: define  the Time variable for the integration
tspan = np.array([0, 2])

#STEP 3: solve the system
sol = solve_ivp(Diffusion_rhs, tspan, U0)

任何帮助将不胜感激。 谢谢。


错误信息“ y0 必须是一维的”来自 solve_ivp ,因为它被设计为处理一阶常微分方程(ODE)系统,其中未知函数是一维向量。在你的情况下,你试图求解一个偏微分方程(PDE),即二维热方程。

虽然你可以使用 solve_ivp 求解 PDE,但你需要将二维空间问题离散化为一维 ODE 系统。这可以使用有限差分法(你已经提到的)完成。这个想法是用有限差分逼近空间导数,这会产生一个关于每个网格点上未知函数值的 ODE 系统。

下面是如何使用 solve_ivp 通过有限差分法求解二维热方程的更详细的细分:

  1. 空间离散化:
  2. 创建一个网格,覆盖你的图像域。你已经用 x y 完成了此操作。
  3. 用中心差分逼近拉普拉斯算子: u_xx[i, j] ≈ (u[i+1, j] - 2*u[i, j] + u[i-1, j]) / dx**2 u_yy[i, j] ≈ (u[i, j+1] - 2*u[i, j] + u[i, j-1]) / dy**2 其中 u[i, j] 表示网格点 (x[i], y[j]) 处的温度。

  4. ODE 系统:

  5. 将每个网格点上的偏微分方程转换为一个常微分方程: du[i, j]/dt = D * (u_xx[i, j] + u_yy[i, j])
  6. 这将为你提供 width3 * height3 个 ODE 的一个系统。

  7. 向量化:

  8. 将二维数组 u[i, j] 转换为 solve_ivp 可以处理的一维向量 u_vec 。你可以通过堆叠列来做到这一点。
  9. 调整拉普拉斯逼近,以便它在 u_vec 上运行。这可以使用矩阵乘法来完成,其中矩阵表示了有限差分方案。

  10. 求解 ODE 系统:

  11. 定义一个函数 diffusion_rhs(t, u_vec) ,该函数计算 ODE 系统的右侧。
  12. 使用 solve_ivp 求解系统,并将初始条件作为展平的噪声图像传递。

  13. 重塑:

  14. solve_ivp 返回的解也将是一维向量。你需要将其重塑回二维数组,以获得每个网格点和时间步长的温度。

以下是用 solve_ivp 求解二维热方程的 Python 代码:

import numpy as np
import imageio.v2 as imageio
from skimage import color
from scipy.integrate import solve_ivp

# Load and preprocess the image
im3 = imageio.imread('photo.jpg')
grayimg3 = color.rgb2gray(im3)
noisygrayimg3 = grayimg3 + 1.5 * np.random.rand(grayimg3.shape[0], grayimg3.shape[1])

# Spatial discretization
height3, width3 = grayimg3.shape
x = np.linspace(0, 1, width3)
y = np.linspace(0, 1, height3)
dx = x[1] - x[0]
dy = y[1] - y[0]

# Construct the Laplacian matrix
D = 0.005  # Diffusion coefficient
A = (np.eye(width3 * height3, k=-1) + np.eye(width3 * height3, k=1) - 4 * np.eye(width3 * height3)) / dx**2
A += (np.eye(width3 * height3, k=-width3) + np.eye(width3 * height3, k=width3)) / dy**2
A = D * A

# Define the RHS of the ODE system
def diffusion_rhs(t, u_vec):
    return A.dot(u_vec)

# Set up initial condition and time span
u0_vec = noisygrayimg3.flatten()
tspan = (0, 2)

# Solve the ODE system
sol = solve_ivp(diffusion_rhs, tspan, u0_vec, t_eval=np.linspace(tspan[0], tspan[1], 50))

# Reshape the solution back to a 2D array
u_sol = np.reshape(sol.y, (height3, width3, -1))

# Now u_sol contains the temperature at each grid point and time step

这段代码首先创建了表示二维拉普拉斯算子的稀疏矩阵 A 。然后,它定义了一个函数 diffusion_rhs ,该函数将展平的温度向量作为输入,并返回相同长度的导数向量。最后,它使用 solve_ivp 求解 ODE 系统,并将初始条件作为展平的噪声图像传递。该解决方案然后被重塑回二维数组,以获得每个网格点和时间步长的温度。

标签:python,ode,pde,heat
From: 78776392

相关文章

  • 在Spyder(Python 3.6)中导入cv2时出现导入错误
    我已经在Windows操作系统中安装了opencv3.0.0。我已运行该应用程序并已成功将其安装在C:\驱动器中,并且还将cv2.pyd文件复制到C:\Python27\Lib\site-packages中,正如我在几个教程视频中看到的那样在我的Python2.7.5Shell中,即当我键入>>>i......
  • Python + VS Code 调试器:可视化我的程序当前正在执行的源代码中的位置?
    当我使用VSCodePython调试器时:我可以执行我的程序,以便编辑器将我逐行带到源代码中的任何位置(跳转到相关文件/如果尚未打开则将其打开)目前的执行情况是?是的,VSCode的Python调试器可以让你逐行执行代码,并实时显示当前执行的位置。以下是操作方法:1.设置断点:......
  • 如何立即取消使用 Ollama Python 库生成答案的 Asyncio 任务?
    我正在使用Ollama通过OllamaPythonAPI从大型语言模型(LLM)生成答案。我想通过单击停止按钮取消响应生成。问题在于,只有当响应生成已经开始打印时,任务取消才会起作用。如果任务仍在处理并准备打印,则取消不起作用,并且无论如何都会打印响应。更具体地说,即使单击按钮后,此函数......
  • 使用 np.array 索引过滤 Python 列表
    谁能向我解释一下列表self.data如何使用numpy索引数组selec_idx进行索引/过滤?完整的课程可在https://github.com/kaidic/LDAM-DRW/blob/master/imbalance_cifar.pydefgen_imbalanced_data(self,img_num_per_cls):new_data=[]n......
  • 尝试在cmd(python)中安装turtle
    当我在cmd中编写pipinstallturtle后,这条消息出现在我面前。有人知道该怎么办吗?C:\>pipinstallturtleCollectingturtleUsingcachedturtle-0.0.2.tar.gz(11kB)ERROR:Commanderroredoutwithexitstatus1:command:'C:\Users\Bruger\App......
  • Python + Polars:如何有效地“fill_null”仅 DataFrame 的某些列?
    例如,假设我只想fill_null(strategy="zero")DataFrame的数字列。我当前的策略是这样做:final_df=df.select(cs.exclude(cs.numeric()))final_df.with_columns(df.select(cs.numeric()).fill_null(strategy="zero"))是否有替代的、更惯用或更有效的方法来实现我......
  • 如何找到 Windows 上 Python 的安装位置?
    我想找出我的Python在Windows上的安装路径。例如:C:\Python25如何找到Python的安装位置?在Windows上查找Python安装位置的方法有很多种:1.使用where命令(推荐方法):打开命令提示符(cmd)。输入以下命令并按回车键:wherepython......
  • Python Pandas:如何解析没有行结尾的 CSV
    如何解析没有行结尾的CSV文件?示例数据sep=;Id;Date;1;1980-02-29;2;1980-03-10;3;;可以使用lineterminator参数指定行终止符来解析没有行尾的CSV文件。在这种情况下,你可以将lineterminator设置为一个空字符串('')。以下是使用......
  • Python 中的 azure.ai.translation.document - 无法使用当前权限访问源文档位置
    我在使用Python中的azure.ai.translation.document库时遇到问题。我已经在Azure中设置了翻译服务以及带有两个容器的Blob存储。我已使用“用户委托密钥”创建了SAS连接。一种用于源(读取/列表),一种用于目标(写入/列表)。例如我尝试运行Python程序,但源b......
  • 博文标题:探索Python中的元编程:装饰器的魔法
    引言在Python的世界里,装饰器(Decorators)是一种非常强大的特性,它允许程序员在不修改原始函数代码的情况下,为函数添加新的功能。这种机制不仅增强了代码的可读性和可维护性,还提供了高度的灵活性和扩展性。本文将深入探讨装饰器的基本概念、工作原理以及如何利用它们来简化和......