# Python calls Wolfram Language directly with Cloud Product

Posted 9 years ago
3239 Views
|
0 Replies
|
4 Total Likes
|
 This discussion is an extension of this link to the latest release of online programming platform. This type of cloud application is very suitable with deployment on ultra-book or smart phones which does not have too much computation power yet connect to internet for most of the time. First lets take a look at the compound code: sol = NDSolve[{y'[x] == x, y[0] == 1}, y, {x, 0, 1}]; (y[#] /. sol)[[1]]&/@Range[0,1,0.05] (*solution would be y = (1/2)x^2+1, a parabola*) This Wolfram language code snippet solves a simple ODE numerically and use the compiled solution sol to compute a range of points from x=0 to x=1 with delta=0.05 apart. In python, I can call this piece of code directly once I have deployed it correctly online. The WL2Py function converts the raw Wolfram language input into a valid url-encoded string and create a API call to the programming cloud. I wrote a simple parser that later transfers the string returned into a list of floats numbers. To make this app need less bandwith, I plot the result with matplotlib package comes with python. It is very straightforward to make this python-Wolfram-language communication happen. I called two super functions in Wolfram Language online and, surprisingly, they are all you need. One is ToExpression, the other is CloudDeploy. ToExpression turns string into expressions that Mathematica users deal with everyday in the frontend/notebook interface. CloudDeploy, by default, creates a private url for API access. The Python code: import urllib import re def WL2Py(val="Print[\"Welcome to Wolfram programming Cloud\"]"): head = "https://www.wolframcloud.com/objects/e946fe************************?x=" params = urllib.urlencode({'x':val}) req = urllib.urlopen(head,params).read() return req """ WLList2PyList turns '{1,2,3,4}' into [1.,2.,3.,4.] using regular expression""" def WLList2PyList(val): brkList = re.split('[,\{\}]',val) return map(float, brkList[1:-1]) Two things to note here: Since this example is an URL call, I have to use the URL encoding function to create an encoded version of my WL input string WLList2PyList is a simple way to process the output string from the API. You may need other functions to process more complicated results. You have the freedom coming from Python itself Other examples: WL2Py("Factor[1 + 2 x + x^2]") '(1 + x)^2' WL2Py("FiniteGroupData[\"Quaternion\", \"MultiplicationTable\"]") '{{1, 2, 3, 4, 5, 6, 7, 8}, {2, 5, 4, 7, 6, 1, 8, 3}, {3, 8, 5, 2, 7, 4, 1, 6}, {4, 3, 6, 5, 8, 7, 2, 1}, {5, 6, 7, 8, 1, 2, 3, 4}, {6, 1, 8, 3, 2, 5, 4, 7}, {7, 4, 1, 6, 3, 8, 5, 2}, {8, 7, 2, 1, 4, 3, 6, 5}}' WL2Py("Integrate[Sin[x],x]") '-Cos[x]'