Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can odeint_adjoint solve parametric ODEs? #227

Open
mayar-shahin opened this issue Apr 7, 2023 · 3 comments
Open

Can odeint_adjoint solve parametric ODEs? #227

mayar-shahin opened this issue Apr 7, 2023 · 3 comments

Comments

@mayar-shahin
Copy link

mayar-shahin commented Apr 7, 2023

Let's say I have some linear system of parametric ODEs:

def f(t, y, params):
    a, b, c = params 
    dydt = torch.zeros_like(y)
    dydt[0] = a*y[0] - b*y[1]
    dydt[1] = b*y[0] - c*y[1]
    return dydt

How do I pass the parameters to odeint/odeint_adjoint? In scipy.integrate.odeint, this would look like this:

odeint(f, y0, t, args=(a,b,c))
@iranroman
Copy link

can someone please answer this question?

@ftavella
Copy link

ftavella commented Aug 3, 2023

Hi! I'm not one of the developers but I think you can do it this way:

import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from torchdiffeq import odeint, odeint_adjoint


class ODEfunc(nn.Module):
    def __init__(self, params):
        super(ODEfunc, self).__init__()
        self.params = params
    
    def forward(self, t, y):
        a, b, c = self.params
        dydt = torch.zeros_like(y)
        dydt[0] = a*y[0] - b*y[1]
        dydt[1] = b*y[0] - c*y[1]
        return dydt

time = torch.linspace(0.0, 10.0, 100)
params = torch.Tensor([1.0, 2.0, 3.0])
y0 = torch.Tensor([1.5, 0.25])

func = ODEfunc(params)
result = odeint(func, y0, time)
result_adjoint = odeint_adjoint(func, y0, time)

plt.plot(time, result[:, 0], color='tab:blue', zorder=0, label="odeint")
plt.scatter(time, result_adjoint[:, 0], color='tab:blue')

plt.plot(time, result[:, 1], color='tab:red', zorder=0)
plt.scatter(time, result_adjoint[:, 1], color='tab:red')

plt.xlabel('Time')
plt.ylabel('Y')
plt.show()

Output:
download

@Mr-Markovian
Copy link

Do this approach work when the parameters are not constant, but different for the samples we want to train on?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants