0

Is there a way to read ODEs from a text format into an object that scipy's odeint can use? this was raised here: How to read a system of differential equations from a text file to solve the system with scipy.odeint? but this question uses sympy unnecessarily, are there other solutions? scipy's odeint expects a function to be made dynamically.

Community
  • 1
  • 1
jll
  • 805
  • 2
  • 8
  • 16

1 Answers1

0

The ODE has to be a Python function. Normally that's created with a def or as a lambda.

eval can create a function from a string

In [183]: f=eval('lambda x: x**2')
In [184]: f(10)

But it is considered unsafe: Using python's eval() vs. ast.literal_eval()?

But the safe alternative can't create a function

In [185]: f=ast.literal_eval('lambda x: x**2')
...
ValueError: malformed node or string: <_ast.Lambda object at 0xa749882c>

For a more recent discussion of creating a function with sympy or direct see: Parsing Complex Mathematical Functions in Python


The cleanest solution is to write valid Python code in the text file, name it a .py, and import it.

Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353