Hi all,
I’ve registered Python as external evaluator and when I am going to find the external evaluator with
FindExternalEvaluator[“Python”], I got the correct python version and executable but I have “missing dependencies”.
Any idea how to solve the issue?
Thanks and regards
Paolo
You need to specify where to find Python:
RegisterExternalEvaluator[
"Python",
"C:\\bin\\Anaconda3\\python.EXE"]
Register a Python-Numpy library:
RegisterExternalEvaluator[
"Python-NumPy",
"C:\\bin\\Anaconda3\\python.EXE"]
How to import a Numpy library
ExternalEvaluate[
"Python",
"import numpy; x = numpy.pi; x**2"
]
Import any libraries:
ExternalEvaluate[
"Python",
"from sympy import isprime; isprime(7)"
]
Examples from the following websites: How to call Python from Mathematica, including NumPy.
In current versions of the Wolfram Language you can simply start a Python session in a virtual environment as follows (here I am using astropy as an example, but you can do this with any Python package):
session = StartExternalSession[<|
"System" -> "Python",
"Evaluator" -> <|"Dependencies" -> {"astropy"}|>,
"SessionProlog" -> {
"from astropy.time import Time",
"from astropy.coordinates import get_body_barycentric",
"from astropy import units as u"
}|>]
Note how I specify the dependent astropy package and how I am also running session initialization code. Now we can define a callable function with some python code:
EarthMarsDistance = ExternalFunction[session, "
def distance_earth_mars(date_str):
try:
time = Time(date_str)
earth = get_body_barycentric('earth', time)
mars = get_body_barycentric('mars', time)
separation = (mars - earth).norm()
distance_au = separation.to(u.au)
return distance_au.value
except ValueError:
return None
"]
This function computes the distance from Earth to Mars for a given ISO date string. You can call it directly from the Wolfram Language:
EarthMarsDistance[DateString[Now, "ISODateTime"]]
This gave the answer of 1.29486 (astronomial units) at the time of evaluation.
You can then also use the EarthMarsDistance function in other Wolfram Language code, for example a plot over time:
ListLinePlot[
Table[
EarthMarsDistance[DateString[t, "ISODateTime"]],
{t, DateRange[Now, Now + Quantity[1000, "Days"]]}]]
Which gives a nice plot:
In this case you can do this directly in the Wolfram Language with the AstroDistance function:
AstroDistance[Entity["Planet", "Mars"]]
But if you have Python code that you would like to call from the Wolfram Language, then this is the route I suggest you take. I have attached a notebook with all the inputs from this comment.
astropy-01.nb (116 KB)
