2
$\begingroup$

I really like the idea of the Wolfram Engine, and in particular using it via the python client library. However, I've having trouble understanding the syntax for even simple commands: is there some documentation anywhere (beyond the very limited reference docs)? In particular, is there documentation of the API and how standard commands from Mathematica map across?

The particular simple example I'm unable to get work is just a simple Sum call. I expected this to be accessed via something like

from wolframclient.language import wl
wl.Sum(1, ['i', 1, 5])

but this gives a list of errors (Raw object i cannot be used as an iterator. etc). How is it intended to use simple functions like this?

$\endgroup$
4
  • $\begingroup$ Why not something like wlexpr('Sum[1, {i, 1, 5}]'), which you can pass along to session.evaluate()? $\endgroup$ Commented Dec 12, 2021 at 18:37
  • $\begingroup$ I'm looking to programmatically generate the arguments, so wlexpr will be just a bit more painful as everything's a string -- fine if that's the only option though! $\endgroup$ Commented Dec 12, 2021 at 19:12
  • $\begingroup$ I get the same error in Mathematica from Sum[1, {"i", 1, 5}]. Maybe your 'i' is translated to a string, not a Symbol. $\endgroup$
    – Michael E2
    Commented Dec 12, 2021 at 19:15
  • 1
    $\begingroup$ wl.Sum(1, [wl.Symbol('i'), 1, 5]) gives a similar error (Tag Symbol in Symbol[i] is Protected) - how are symbols treated by Mathematica when used as dummy variables? $\endgroup$ Commented Dec 12, 2021 at 19:26

1 Answer 1

9
$\begingroup$

Here is working example that may be useful as a starting point. Note that the fourth line (with ... as s:) contains a linux path name that may have to be removed and/or replaced for other systems.

from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, wlexpr
import sys

with WolframLanguageSession("/usr/local/bin/MathKernel") as s:
    ## print("session is open", s, "\n\n")

    # summand is equal to the index
    try :
        i = wl.expr('i')
        f = i
        result = s.evaluate(wl.Sum(f, [i, 1, 5]))
        print(result,"\n")
    except :
        print("first one failed")
        print(sys.exc_info()[1])

    # summand is a pure function evaluated at the index
    try :
        i = wl.expr('i')
        f = wlexpr('1/(2^#) &')                         # it's wlexpr, not wl.expr
        result = s.evaluate(wl.Sum(f(i), [i, 1, 5]))
        print(result,"\n")
    except :
        print("second one failed")
        print(sys.exc_info()[1])

(*   15 

     Rational[31, 32]   *)
$\endgroup$

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.