Message Boards Message Boards

Running the Wolfram Engine from Python

Posted 2 months ago

Hi Guys There seemed to be some interest in my last post which was a general question which I inevitably developed a solution for.

The below is basic example of writing a Mathematica script and solving it in Python, thereafter the data is extracted and plotted in Python using Matplotlib. This example can be expanded to more complex problems allowing one to get the best of both worlds.

from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, wlexpr
import matplotlib.pyplot as plt
import numpy as np

session = WolframLanguageSession()



wolfram_code = """
    s = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}];
    Table[{x, y[x] /. s}, {x, 0, 30, 0.1}]
"""

# Evaluate the Wolfram code
result = session.evaluate(wlexpr(wolfram_code))

# Terminate the Wolfram session
session.terminate()

# Extract x and y values from the result
x_vals = [pair[0] for pair in result]
y_vals = [pair[1] for pair in result]

# Plot the solution using matplotlib
plt.plot(x_vals, y_vals, label='y(x)')
plt.xlabel('x')
plt.ylabel('y(x)')
plt.title('Solution of y\'[x] = y[x] Cos[x + y[x]]')
plt.grid(True)
plt.legend()

# Show the plot
plt.show()
POSTED BY: Mishal Mohanlal
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract