I'm trying to solve multiple ordinary differential equations in Python using odeint. A simple version would look like:
import numpy as np
from scipy.integrate import odeint
def lotka_volterra(xy, t):
x, y = xy
dxdt = x - x * y
dydt = x * y - y
return [dxdt, dydt]
Solving:
x0 = 40 #Initial prey population
y0 = 9 #Initial predator population
initial_conditions = [x0, y0]
t = np.linspace(0, 300, 4000)
solution = odeint(lotka_volterra, initial_conditions, t)
However, I have a more complicated system where I need to generate variables within the function and then write the DEs - the number of species and so on is not constant and is in the hundreds.
I have come up with the following code:
def setofequations(variables, t):
species = []
ucarrier = []
R = []
O = []
for i in range(1, nspecies + 1):
species.append('N_' + str(i))
ucarrier.append('ucarrier_' + str(i))
for i in range(1, nreactions+1):
R.append('R_'+str(i))
O.append('O_'+str(i))
Here, every element of every list species, ucarrier, R, I is a variable that has its own ODE that needs to be solved.
I want to be able to make each string in those lists a variable that can then be used in equations. Every solution I can find such as globals(), locals() doesn't seem to work for my specific requirement - they all have you outright assign some value to it.
I also require that the variable within a list be called using the corresponding index. For example, R[i] should give R_i.
Any help is appreciated, thanks!
'N_1', which is what's stored in the lists, be different from the variableN_1 = 1, for example? JNevill: If I were to write it as a dictionary, should the corresponding values just be variables with the same name as the strings (keys)? That would serve the purpose, but wouldn't those variables need to be previously defined?