在函数内部将set_f_params设置为set_solout [英] scipy ode update set_f_params inside function set as set_solout

查看:149
本文介绍了在函数内部将set_f_params设置为set_solout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将ode与scipy集成时,ode接受一个函数,其参数比t和y多.例如:

When integrating an ode with scipy, ode accepts a function with more arguments than t and y. For example:

def fun(t, y, param1, param2):

,这些参数的值可以使用set_f_params方法设置.

and the value of these arguments can be set using set_f_params method.

但是,当还使用set_solout方法并尝试在此函数内部使用set_f_params更新参数时,集成保持不变,就像未修改参数一样.

However, when using also set_solout method and trying to update the params with set_f_params inside this function, the integration remains the same as if the params were not being modified.

如何使用sol_out修改参数? 我想受益于dopri5密集输出,但是我需要在每个时间步更新非均质术语.

How would you modify the the params using sol_out? I would like to benefit from dopri5 dense output, but I need the non-homogeneous terms to be updated at every time step.

下面显示了一个最小示例.

A minimal example is shown below.

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

def fun(t, x, param):
    return x - param

def f_param(t):
    return t

ode1 = ode(fun).set_integrator('dopri5').set_initial_value([10.0])
ode1.set_f_params(f_param(0))
results1 = ([], [])

ode2 = ode(fun).set_integrator('dopri5').set_initial_value([10.0])
ode2.set_f_params(f_param(0))
results2 = ([], [])

def callback1(t, x):
    results1[0].append(t)
    results1[1].append(x.copy())

def callback2(t, x):
    results2[0].append(t)
    results2[1].append(x.copy())
    ode2.set_f_params(f_param(t))

ode1.set_solout(callback1)
ode2.set_solout(callback2)

ode1.integrate(3)
ode2.integrate(3)

plt.plot(results1[0], results1[1], 'o-', alpha=0.7, label='ode1')
plt.plot(results2[0], results2[1], '.--', label='ode2')
plt.legend()

,结果显示在这里:

推荐答案

这就是使用

这篇关于在函数内部将set_f_params设置为set_solout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆