3
$\begingroup$

I encountered the following issue with WolframClient. I have a my.function file which contains some function that takes some parameters (7 floats) as input and returns a nested list of complex numbers in Mathematica. I want to call it via python and treat the output as a numpy.ndarray of complex numbers. I do the following:

with WolframLanguageSession() as session:
        my_function = session.function(wl.Get(path_to_function))

        x = my_function(0.1, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)

        print(x)

which gives me something like this:

((((Complex[-2.9851335011862212, -0.5581051654634444], Complex[-0.34914756979863104, 0.38713532072098944], Complex[0.02846108320428109, 0.03283335816887564]), (Complex[2.9114417580613257, -0.058550143608501304], Complex[0.041982819472082836, -0.2399283469968325], 0), (Complex[-0.29788041688768496, 0.16668305088796254], 0, 0)), ((Complex[1.607048536309744, 0.054911153529431656], Complex[0.03322853020335367, -0.11167319057887276], 0), (Complex[-0.3015173117518156, 0.12541388543997334], 0, 0), (0, 0, 0)), ((Complex[-0.07510109944668442, 0.02144870241235377], 0, 0), (0, 0, 0), (0, 0, 0))), (((Complex[1.7446313085976066, 0.9785287503847628], Complex[0.15511366918115133, -0.17146659375916984], 0), (Complex[-0.6471782663657613, -0.03367309746041122], 0, 0), (0, 0, 0)), ((Complex[-0.3056298195051441, -0.05182365243220163], 0, 0), (0, 0, 0), (0, 0, 0)), ((0, 0, 0), (0, 0, 0), (0, 0, 0))), (((Complex[-0.25138505704186276, -0.17724520875129096], 0, 0), (0, 0, 0), (0, 0, 0)), ((0, 0, 0), (0, 0, 0), (0, 0, 0)), ((0, 0, 0), (0, 0, 0), (0, 0, 0))))

which python parses as a tuple, which is fine because I can convert a tuple to array. However, I've got a problem with the complex numbers: each non-zero element of the tuples is a wolframclient.language.expression.WLFunction which I don't know how to convert to a python number. How do I solve this?

$\endgroup$

1 Answer 1

0
$\begingroup$

Have you found a solution to do the casting?

A workaround of course is to return the real and imaginary part of the result seperately:

Return[{Re[res],Im[res]}];
$\endgroup$
1
  • $\begingroup$ In most cases you do not need Return to return a value from a function. Functions just return the last value you calculate in them. You can also take advantage of ReIm to return ReIm[res], which accomplishes the same thing you propose. $\endgroup$
    – MarcoB
    Jun 30, 2022 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.