Python Scipy Solve_ivp / odeint:打印和绘制时间/解决方案相关的参数 执行求解程序系数作为状态函数

如何解决Python Scipy Solve_ivp / odeint:打印和绘制时间/解决方案相关的参数 执行求解程序系数作为状态函数

我一直在使用scipy.integrate.solve_ivp来求解二阶ODE系统。

假设此处提供了代码(请注意,此代码使用odeint,但与solve_ivp类似,但使用的方法):https://scipy-cookbook.readthedocs.io/items/CoupledSpringMassSystem.html

现在,使某些参数(b1和b2)与时间和解相关,例如:

b1 = 0.8 * x1

if (x2 >= 1.0):
    b2 = 20*x2
else:
    b2 = 1.0

solve_ivp解决方案可以轻松打印和绘制。

我还可以通过在定义的函数中插入print(b1)来打印部分与时间/解决方案有关的参数。但是我对此输出感到困惑。我要做的是打印和绘制在解决方案时间戳记要解决的定义函数中设置的与时间/解决方案相关的参数: print(t,b1)

希望这很有意义。任何提示都会很棒。

欢呼

示例代码(以odeint以及b1和b2作为动态参数):

    def vectorfield(w,t,p):
    """
    Defines the differential equations for the coupled spring-mass system.

    Arguments:
        w :  vector of the state variables:
                  w = [x1,y1,x2,y2]
        t :  time
        p :  vector of the parameters:
                  p = [m1,m2,k1,k2,L1,L2,b1,b2]
    """
    x1,y2 = w
    m1,= p
    
    # Friction coefficients
    b1 = 0.8 * x1
    
    if (x2 >= 1.0):
        b2 = 20*x2
    else:
        b2 = 1.0
    
    # Create f = (x1',y1',x2',y2'):
    f = [y1,(-b1 * y1 - k1 * (x1 - L1) + k2 * (x2 - x1 - L2)) / m1,y2,(-b2 * y2 - k2 * (x2 - x1 - L2)) / m2]
    
    print('b1',b1)
    # print('b2',b2)
    
    return f

# Use ODEINT to solve the differential equations defined by the vector field
from scipy.integrate import odeint

# Parameter values
# Masses:
m1 = 1.0
m2 = 1.5
# Spring constants
k1 = 8.0
k2 = 40.0
# Natural lengths
L1 = 0.5
L2 = 1.0

# Initial conditions
# x1 and x2 are the initial displacements; y1 and y2 are the initial velocities
x1 = 0.5
y1 = 0.0
x2 = 2.25
y2 = 0.0

# ODE solver parameters
abserr = 1.0e-8
relerr = 1.0e-6
stoptime = 10.0
numpoints = 101

# Create the time samples for the output of the ODE solver.
t = [stoptime * float(i) / (numpoints - 1) for i in range(numpoints)]

# Pack up the parameters and initial conditions:
p = [m1,L2]
w0 = [x1,y2]

# Call the ODE solver.
wsol = odeint(vectorfield,w0,args=(p,),atol=abserr,rtol=relerr)

# Print Output
print(t)
# print(wsol)
# print(t,b1)
# print(t,b2)


# Plot the solution that was generated
from numpy import loadtxt
from pylab import figure,plot,xlabel,grid,legend,title,savefig
from matplotlib.font_manager import FontProperties

figure(1,figsize=(6,4.5))

xlabel('t')
grid(True)
lw = 1

plot(t,wsol[:,0],'b',linewidth=lw)
plot(t,1],'g',2],'r',3],'c',linewidth=lw)
# plot(t,'k',linewidth=lw)

legend((r'$x_1$',r'$x_2$',r'$x_3$',r'$x_4$'),prop=FontProperties(size=16))
title('Mass Displacements for the\nCoupled Spring-Mass System')
# savefig('two_springs.png',dpi=100)

解决方法

新的ODE解算器API

使您的代码适应使用solve_ivp(这是现代的scipy API来解决ODE),我们可以采用非侵入性的方式来解决系统:

import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt

numpoints = 1001
t0 = np.linspace(0,stoptime,numpoints)

def func(t,x0,beta):
    return vectorfield(x0,t,beta)

#sol1 = odeint(vectorfield,w0,t0,args=(p,),atol=abserr,rtol=relerr)
sol2 = solve_ivp(func,[t0[0],t0[-1]],t_eval=t0,method='LSODA')

新的API返回的结果与old API odeint相似。 solve_ivp返回的解决方案对象提供了有关作业执行的多个额外信息:

  message: 'The solver successfully reached the end of the integration interval.'
     nfev: 553
     njev: 29
      nlu: 29
      sol: None
   status: 0
  success: True
        t: array([ 0.,0.01,0.02,...,9.98,9.99,10.  ])
 t_events: None
        y: array([[ 0.5,0.50149705,0.50596959,0.60389634,0.60370222,0.6035087 ],[ 0.,0.29903815,0.59476327,-0.01944383,-0.01937904,-0.01932493],[ 2.25,2.24909287,2.24669965,1.62461438,1.62435635,1.62409906],-0.17257692,-0.29938513,-0.02583719,-0.02576507,-0.02569245]])
 y_events: None

捕获动态参数

如果我正确理解了您的问题,那么您也希望将摩擦参数作为时间序列。

执行求解程序

这可以通过使用callback function或通过传递额外的数据结构并在评估 ODE函数时存储系数值来实现。

如果要跟踪求解器的执行情况,这将很有帮助,但结果将取决于求解器集成网格,而不是所需的求解时间范围。

无论如何,只要愿意,就可以调整您的功能:

def vectorfield2(w,p,store):
   # ...
   store.append({'time': t,'coefs': [b1,b2]})
   # ...

c = []
sol1 = odeint(vectorfield2,c),rtol=relerr)

如您所见,结果不遵循求解时间尺度,而是遵循求解器集成网格:

[{'time': 0.0,'coefs': [0.4,45.0]},{'time': 3.331483023263848e-07,'coefs': [0.4000000000026638,44.999999999955605]},{'time': 6.662966046527696e-07,'coefs': [0.4000000000053275,44.99999999991122]},'coefs': [0.40000000000799124,44.99999999986683]},{'time': 0.0001385450759485236,'coefs': [0.4000002303394594,44.99999616108455]},...]

系数作为状态函数

另一方面,您的系数仅取决于系统状态,这意味着我们可以在ODE函数中(每次求解程序调用它时),然后在与时间有关的解已知时对其进行计算。

我建议如下重写您的系统:

def coefs(x):
    # Ensure signature:
    if isinstance(x,(list,tuple)):
        x = np.array(x)
    if len(x.shape) == 1:
        x = x.reshape(1,-1)
    # Compute coefficients
    b1 = 0.8 * x[:,0]
    b2 = 20. * x[:,2]
    q2 = (x[:,2] < 1.0)
    b2[q2] = 1.0
    return np.stack([b1,b2]).T

def system(t,w,p):
    x1,y1,x2,y2 = w
    m1,m2,k1,k2,L1,L2,= p
    b = coefs(w)
    return [
        y1,(-b[:,0] * y1 - k1 * (x1 - L1) + k2 * (x2 - x1 - L2)) / m1,y2,1] * y2 - k2 * (x2 - x1 - L2)) / m2,]

sol3 = solve_ivp(system,method='LSODA')

请注意,coefs方法的接口旨在在简单状态(列表或向量)和时间解(矩阵)上运行。

然后,很容易显示时间解决方案:

fig,axe = plt.subplots()
axe.plot(t0,sol3.y.T)
axe.set_title("Dynamic System: Coupled Spring Mass")
axe.set_xlabel("Time,$t$")
axe.set_ylabel("System Coordinates,$x_i(t)$")
axe.legend([r'$x_%d$' % i for i in range(sol3.y.T.shape[1])])
axe.grid()

enter image description here

和系数:

fig,axes = plt.subplots(2,1,sharex=True,sharey=False)
axes[0].plot(t0,coefs(sol3.y.T)[:,0])
axes[1].plot(t0,1])
axes[0].set_title("Dynamic System: Coupled Spring Mass")
axes[1].set_xlabel("Time,$t$")
axes[0].set_ylabel("$b_0(t)$")
axes[1].set_ylabel("$b_1(t)$")
for i in range(2):
    axes[i].grid()

enter image description here

您似乎更想实现什么目标。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-