Coder Social home page Coder Social logo

wolframresearch / wolframclientforpython Goto Github PK

View Code? Open in Web Editor NEW
432.0 36.0 45.0 8.94 MB

Call Wolfram Language functions from Python

Home Page: https://wolfr.am/wolframclientdoc

License: MIT License

Mathematica 1.96% Python 98.04%
wolfram-language python mathematica wolframlanguage python-api

wolframclientforpython's Introduction

Wolfram Logo

Wolfram Client library for Python

The Wolfram Client Library provides seamless Wolfram Language integration in Python. A list of features provided by the library:

  • evaluate arbitrary code on a local kernel,
  • evaluate arbitrary code on Wolfram cloud, public or private,
  • call deployed APIFunction,
  • build Python functions on top of Wolfram Language functions,
  • represent arbitrary Wolfram Language code as Python object,
  • serialize Python object to Wolfram Language string InputForm,
  • serialize Python object to WXF,
  • extend serialization to any arbitrary Python class,
  • parse WXF encoded expressions.

Links

Project Information

Licencing

This project is released under the MIT licence.

Contributions

The library is maintained by Wolfram Research. The code is on Github. Pull requests and suggestions are always welcomed.

wolframclientforpython's People

Contributors

arnoudbuzing avatar bwhaines avatar clives avatar crazyeng avatar jfultz avatar riccardodivirgilio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wolframclientforpython's Issues

how

how solve determinants

invalid kernel

Hello, I have just tested the following and on 2 different op. systems (Mac 10.14.4 and Cent OS 7) I have similar issues with python 3.7:

Cent OS:

$ cd wolframclient-1.0.2/
$ pip install .
(no errors...)
$ python
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from wolframclient.evaluation import WolframLanguageSession
>>> from wolframclient.language import wl, wlexpr
>>> session = WolframLanguageSession()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/mnt/test/wolframclient-1.0.2/wolframclient/evaluation/kernel/localsession.py", line 121, in __init__
    **kwargs)
  File "/mnt/test/wolframclient-1.0.2/wolframclient/evaluation/kernel/kernelcontroller.py", line 132, in __init__
    'Invalid kernel value. Expecting a filepath as a string.')
ValueError: Invalid kernel value. Expecting a filepath as a string.

Mac:

$ python
Python 3.7.1 | packaged by conda-forge | (default, Nov 13 2018, 10:30:07)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from wolframclient.evaluation import WolframLanguageSession
>>> from wolframclient.language import wl, wlexpr
>>> session = WolframLanguageSession()
>>> session.evaluate(wlexpr('Range[5]'))
Failed to start.
Traceback (most recent call last):
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py", line 431, in _kernel_start
    self.trigger_termination_requested))
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/zmqsocket.py", line 54, in recv_abortable
    raise SocketAborted('Socket operation aborted.')
wolframclient.evaluation.kernel.zmqsocket.SocketAborted: Socket operation aborted.

During handling of the above exception, another exception occurred:

```Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/localsession.py", line 259, in evaluate
    result = self.evaluate_wrap(expr, **kwargs)
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/localsession.py", line 256, in evaluate_wrap
    return self.evaluate_wrap_future(expr, **kwargs).result()
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/localsession.py", line 252, in evaluate_wrap_future
    self.ensure_started()
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/localsession.py", line 203, in ensure_started
    self.start(block=True, timeout=None)
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/localsession.py", line 157, in start
    raise e
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/localsession.py", line 152, in start
    future.result(timeout=timeout)
  File "/anaconda3/lib/python3.7/concurrent/futures/_base.py", line 432, in result
    return self.__get_result()
  File "/anaconda3/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py", line 517, in run
    self._safe_kernel_start()
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py", line 364, in _safe_kernel_start
    raise e
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py", line 358, in _safe_kernel_start
    self._kernel_start()
  File "/anaconda3/lib/python3.7/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py", line 443, in _kernel_start
    'Wolfram kernel version is not supported. Please consult library prerequisites.'
wolframclient.exception.WolframKernelException: Wolfram kernel version is not supported. Please consult library prerequisites.
>>>

Thanks for helping,
Balint

Port 36154 error, not startup an kernel server

I'm run:
from wolframclient.evaluation import WolframLanguageSession kernel = '/home/homework/user/mm/Wolfram/Mathematica/bin/wolfram' session = WolframLanguageSession(kernel) sesstion.start()
and get such error. It seems i haven't startup a kernel server. But i'm a new beginner.Please wise author help me.
`Traceback (most recent call last):
File "/home/homework/user/liaochangzeng/anaconda2/envs/python3.6/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelsession.py", line 491, in _start
sleep=self._socket_read_sleep_func)
File "/home/homework/user/liaochangzeng/anaconda2/envs/python3.6/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelsession.py", line 662, in read_timeout
% (self.uri, time.perf_counter() - start, retry))
wolframclient.evaluation.kernel.kernelsession.SocketException: Read time out. Failed to read any message from socket tcp://127.0.0.1:36154 after 20.0 seconds and 14259 retries.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "", line 1, in
File "/home/homework/user/liaochangzeng/anaconda2/envs/python3.6/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelsession.py", line 421, in start
raise e
File "/home/homework/user/liaochangzeng/anaconda2/envs/python3.6/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelsession.py", line 414, in start
self._start()
File "/home/homework/user/liaochangzeng/anaconda2/envs/python3.6/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelsession.py", line 504, in _start
% self.kernel)
wolframclient.exception.WolframKernelException: Failed to communicate with the kernel /home/homework/user/cuiyinsheng/Wolfram/Mathematica/bin/wolfram. Could not read from ZMQ socket.`

Restarting a session if underlying kernel process is down

Hi,

I was wondering if it is possible to restart a session if the underlying kernel process is down (either killed or if it randomly stops after running for a long time). In such a case, both session.terminate() and session.restart() hang and seem unable to complete.

Any pointers would be highly appreciated. Thanks.

Truncation of exponents

The package yields different results when done in python compared to mathematica.
Here's a working example.

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

session = WolframLanguageSession()

sys1 = '{-4.0*t0*t1 - 4.0*t0*t2 - 8.0*t0*t4 + 4.0*t1*t3 + 4.0*t2*t3 + 8.0*t3*t4, 4.0*t0*t2 - 4.0*t0*t3 - 8.0*t0*t4 + 8.0*t1*t2 + 4.0*t1*t3 + 8.0*t1*t4 + 8.0*t2*t3 + 12.0*t2*t4 + 4.0*t4^2, 8.0*t0*t4 - 4.0*t1*t3 + 4.0*t1*t4 - 4.0*t2*t3 + 4.0*t2*t4 + 8.0*t4^2, 4.0*t0*t1 - 4.0*t0*t2 + 4.0*t1*t3 + 4.0*t1*t4 - 4.0*t2*t3 - 4.0*t2*t4, 4.0*t0*t2 + 4.0*t0*t3 + 8.0*t0*t4 - 8.0*t1*t2 - 8.0*t1*t3 - 16.0*t1*t4 - 4.0*t2*t3 - 12.0*t2*t4 - 8.0*t3*t4 - 12.0*t4^2}'
sys2 = str(['t'+str(i)+'> 1' for i in range(5)]).replace('\'', '').replace('[','{').replace(']', '}')
variables =str(['t'+str(i) for i in range(5)]).replace('\'', '').replace('[','{').replace(']', '}')

expression = 'NMinimize[Join[{{Plus @@ (#^2 & /@ {})}}, '.format(sys1)
expression += '{}],'.format(sys2)
expression += '{}, AccuracyGoal -> 20, PrecisionGoal -> 20, WorkingPrecision -> 20]'.format(variables)

optimize = wlexpr(expression)
results = session.evaluate(optimize)
results

yields

(Decimal('4.590261537982443550669979993291708325478875'),
 (Rule[Global`t0, Decimal('6.06493241687450887611738251710439317786')],
  Rule[Global`t1, Decimal('1.49023396370430740218122509461758089564')],
  Rule[Global`t2, Decimal('1.49023396380763117160348778583728320911')],
  Rule[Global`t3, Decimal('6.06493241776108712714104622341693698113')],
  Rule[Global`t4, Decimal('1.05028414801046224445183878123997337742')]))

Now, running the same code in a mathematica kernel

In[1] := NMinimize[Join[{Plus @@ (#^2 & /@ {-4.0*t0*t1 - 4.0*t0*t2 - 8.0*t0*t4 + 4.0*t1*t3 + 4.0*t2*t3 + 8.0*t3*t4, 4.0*t0*t2 - 4.0*t0*t3 - 8.0*t0*t4 + 8.0*t1*t2 + 4.0*t1*t3 + 8.0*t1*t4 + 8.0*t2*t3 + 12.0*t2*t4 + 4.0*t4^2, 8.0*t0*t4 - 4.0*t1*t3 + 4.0*t1*t4 - 4.0*t2*t3 + 4.0*t2*t4 + 8.0*t4^2, 4.0*t0*t1 - 4.0*t0*t2 + 4.0*t1*t3 + 4.0*t1*t4 - 4.0*t2*t3 - 4.0*t2*t4, 4.0*t0*t2 + 4.0*t0*t3 + 8.0*t0*t4 - 8.0*t1*t2 - 8.0*t1*t3 - 16.0*t1*t4 - 4.0*t2*t3 - 12.0*t2*t4 - 8.0*t3*t4 - 12.0*t4^2})}, {t0> 1, t1> 1, t2> 1, t3> 1, t4> 1}],{t0, t1, t2, t3, t4}, AccuracyGoal -> 20, PrecisionGoal -> 20, WorkingPrecision -> 20]
Out[1]= {4.5902615379824435507 10^-16   , 
 
>    {t0 -> 6.0649324168745088761, t1 -> 1.4902339637043074022, 
 
>     t2 -> 1.4902339638076311716, t3 -> 6.0649324177610871271, 
 
>     t4 -> 1.0502841480104622445}}

shows that the 10^-16 has been lost. The same holds true for exponents in the variabes ti if they occur.

Stuck at ExportByteArray

session=WolframLanguageSession()
img = Image.open("path_to_image")
data = session.evaluate(wl.CurvatureFlowFilter(img, 50))
z = session.evaluate(wl.ExportByteArray(data, "PNG"))

Changing CurvatureFlowFilter to other functions like 'Binarize' gives the desired output but gets stuck at ExportByteArray.

This is the Trace when process is manually interrupted:

File "/home/nikhal/.PyCharmCE2019.1/config/scratches/scratch_82.py", line 25, in Binarize
z = session.evaluate(wl.ExportByteArray(data, "PNG"))
File "/usr/local/lib/python3.6/dist-packages/wolframclient/evaluation/kernel/localsession.py", line 259, in evaluate
result = self.evaluate_wrap(expr, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/wolframclient/evaluation/kernel/localsession.py", line 256, in evaluate_wrap
return self.evaluate_wrap_future(expr, **kwargs).result()
File "/usr/lib/python3.6/concurrent/futures/_base.py", line 427, in result
self._condition.wait(timeout)
File "/usr/lib/python3.6/threading.py", line 295, in wait
waiter.acquire()
KeyboardInterrupt

Here is my code:
binarize.txt

Fail to serializer PyTorch model as WXF

I am trying to convert some PyTorch models into WLNet models.

PyTorch models are generally saved as pth files.

A *.pth file is a collections.OrderedDict of torch.tensor, it looks like:

OrderedDict([
	('name.weights', tensor([64×3×3×3])),
	('name.biases', tensor([64])),
])

I expect them to be converted into the following results:

<|
	"name.weights" -> RawData[64×3×3×3],
	"name.biases" -> RawData[64]
|>

But I have encountered some problems, torch.tensor can not be converted.

import torch
import wolframclient.serializers as wxf
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(x)
wxf.export(x, 'tensor.wxf', target_format='wxf')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Anaconda3\lib\wolframclient\serializers\__init__.py", line 60, in export data, stream=stream)
File "C:\Anaconda3\lib\wolframclient\serializers\base.py", line 22, in export self.dump(data, file)
File "C:\Anaconda3\lib\wolframclient\serializers\wxf.py", line 54, in dump for payload in self.normalize(data):
File "C:\Anaconda3\lib\wolframclient\utils\dispatch.py", line 96, in inner return self.resolve(function, *args)(obj, *args, **opts)
File "C:\Anaconda3\lib\wolframclient\serializers\normalizer\__init__.py", line 21, in normalizer return self.serialize_iterable(self.normalize(value) for value in o)
File "C:\Anaconda3\lib\wolframclient\serializers\base.py", line 72, in serialize_iterable self.serialize_symbol(b'List'), iterable, **opts)
File "C:\Anaconda3\lib\wolframclient\serializers\wxf.py", line 67, in serialize_function iterable, length = get_length(args, **opts)
File "C:\Anaconda3\lib\wolframclient\serializers\wxf.py", line 27, in get_length iterable = tuple(iterable)
File "C:\Anaconda3\lib\wolframclient\serializers\normalizer\__init__.py", line 21, in <genexpr> return self.serialize_iterable(self.normalize(value) for value in o)
File "C:\Anaconda3\lib\wolframclient\utils\dispatch.py", line 96, in inner return self.resolve(function, *args)(obj, *args, **opts)
File "C:\Anaconda3\lib\wolframclient\serializers\normalizer\__init__.py", line 21, in normalizer return self.serialize_iterable(self.normalize(value) for value in o)
File "C:\Anaconda3\lib\wolframclient\serializers\base.py", line 72, in serialize_iterable self.serialize_symbol(b'List'), iterable, **opts)
File "C:\Anaconda3\lib\wolframclient\serializers\wxf.py", line 67, in serialize_function iterable, length = get_length(args, **opts)
File "C:\Anaconda3\lib\wolframclient\serializers\wxf.py", line 27, in get_length iterable = tuple(iterable)
File "C:\Anaconda3\lib\wolframclient\serializers\normalizer\__init__.py", line 21, in <genexpr> return self.serialize_iterable(self.normalize(value) for value in o)
File "C:\Anaconda3\lib\wolframclient\utils\dispatch.py", line 96, in inner return self.resolve(function, *args)(obj, *args, **opts)
File "C:\Anaconda3\lib\wolframclient\serializers\normalizer\__init__.py", line 21, in normalizer return self.serialize_iterable(self.normalize(value) for value in o)
File "C:\Anaconda3\lib\torch\tensor.py", line 381, in __iter__ raise TypeError('iteration over a 0-d tensor')
TypeError: iteration over a 0-d tensor

But I think torch.tensor just the same as numpy.ndarray.

How can I solve this problem.

Is it possible to avoid writing FullForm?

If I want to reverse the color of a picture in mma, I would

1-pic

But to the same thing with this, I have to write.

session.evaluate ( wl.Plus (1, wl.Times (-1, pic)))

So long. Any shortcuts?

client hangs

In [1]: from wolframclient.evaluation import WolframLanguageSession
In [2]: from wolframclient.language import wl, wlexpr
In [3]: session = WolframLanguageSession('/opt/WolframEngine/12.1/Executables/WolframKernel')
In [4]: session.evaluate(wl.WolframAlpha("number of moons of Saturn", "Result"))
<<< hangs here indefinitely

In [5]: session.evaluate(wlexpr('Range[5]'))
<<< hangs here indefinitely

Steps:
Ubuntu 18.04.5 LTS
conda version : 4.8.4
python version : 3.7.7.final.0

  1. install development engine
  2. activate
  3. install client using pip

socket failures that take hours to heal

I use a Wolfram session to compute the integrand in the Vegas algorithm in Python.

I use MPI to call a session in each core on a high-performance cluster.

Before I start a session, I want to kill any floating Mathematica processes, so I use the kernelcontroller as follows:

controller = kernelcontroller.WolframKernelController(kernel='path', kernel_loglevel=1)

controller._kernel_stop()

Now, if I wait 10 minutes after this clean-up, my actual code

with WolframLanguageSession('path') as session:...

works fine most of the time.

But at seemingly random times, I get socket failures when I run the two-step process (cleanup, then run session), with multiple instances of the following error message:

Socket exception: Failed to read any message from socket tcp://127.0.0.1:39237 after 20.0 seconds and 199 retries.
Failed to start.
Traceback (most recent call last):
File "/home/sjsuh/anaconda3/lib/python3.9/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py", line 435, in _kernel_start
response = self.kernel_socket_in.recv_abortable(
File "/home/sjsuh/anaconda3/lib/python3.9/site-packages/wolframclient/evaluation/kernel/zmqsocket.py", line 53, in recv_abortable
raise SocketOperationTimeout(
wolframclient.evaluation.kernel.zmqsocket.SocketOperationTimeout: Failed to read any message from socket tcp://127.0.0.1:39237 after 20.0 seconds and 199 retries.

Now, to be able to run my code again, I find that I have to wait around 3 hours and run my routine. Otherwise, this socket failure persists.

So my questions are i) is there a better way to kill stray processes than what I have used, ii) why am I getting the socket failures, and is there a way to heal the socket failures faster?

Can not timeout a session properly

To reproduce:

session = WolframLanguageSession()

expr = "Pause[10]"
session.evaluate(f"{expr}", timeout=1)
session.stop()

The culprit might be:

def evaluate_wrap(self, expr, **kwargs):
return self.evaluate_wrap_future(expr, **kwargs).result()

A potential fix:

return self.evaluate_wrap_future(expr, **kwargs).result(timeout=kwargs.get('timeout'))

Which, however, introduces another issue where the session cannot be terminated, as the lock is not released, requiring a manual interruption (CTRL-C).

SocketAborted problem

My Environment:
Activated MMA 12.0 works correctly on my Ubuntu 16.04 system.

I install WolframClient with following code:

pip install wolframclient -i https://pypi.doubanio.com/simple

Then I execute following codes in python 3.6.10:

from wolframclient.evaluation import WolframLanguageSession 
sess = WolframLanguageSession(path) 
sess.start() 

where, the path I try different values like the result of :

$ which WolframKernel

in my case, it's '/usr/local/bin/WolframKernel' , or the output of

First@$CommandLine 

which is
'/usr/local/Wolfram/Mathematica/12.0/SystemFiles/Kernel/Binaries/Linux-x86-64/WolframKernel'
or use this path
'/usr/local/Wolfram/Mathematica/12.0/Executables/WolframKernel' which is default path of WolframLanguageSession().

Then errors are vary when I choose different paths, but can be concluded into 2 types.

  1. When path = '/usr/local/Wolfram/Mathematica/12.0/SystemFiles/Kernel/Binaries/Linux-x86-64/WolframKernel' , it immediately returns following errors info:
Socket exception: Socket operation aborted.
Failed to start.
---------------------------------------------------------------------------
SocketAborted                             Traceback (most recent call last)
~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py in _kernel_start(self)
    436                 timeout=self.get_parameter("STARTUP_TIMEOUT"),
--> 437                 abort_event=_StartEvent(self.kernel_proc, self.trigger_termination_requested),
    438             )

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/zmqsocket.py in recv_abortable(socket, timeout, abort_check_period, abort_event, **kwargs)
     49                     if abort_event.is_set():
---> 50                         raise SocketAborted("Socket operation aborted.")
     51                 if timeout and (time.perf_counter() - start > timeout):

SocketAborted: Socket operation aborted.

During handling of the above exception, another exception occurred:

WolframKernelException                    Traceback (most recent call last)
<ipython-input-4-84c234a8332d> in <module>
----> 1 sess.start()

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/localsession.py in start(self, block, timeout)
    155                 self.terminate()
    156             finally:
--> 157                 raise e
    158 
    159     def start_future(self):

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/localsession.py in start(self, block, timeout)
    150             future = self.start_future()
    151             if future and block:
--> 152                 future.result(timeout=timeout)
    153         except Exception as e:
    154             try:

~/anaconda3/envs/detectron2/lib/python3.6/concurrent/futures/_base.py in result(self, timeout)
    430                 raise CancelledError()
    431             elif self._state == FINISHED:
--> 432                 return self.__get_result()
    433             else:
    434                 raise TimeoutError()

~/anaconda3/envs/detectron2/lib/python3.6/concurrent/futures/_base.py in __get_result(self)
    382     def __get_result(self):
    383         if self._exception:
--> 384             raise self._exception
    385         else:
    386             return self._result

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py in run(self)
    525             # Kernel start requested.
    526             if payload is self.START:
--> 527                 self._safe_kernel_start()
    528                 future.set_result(True)
    529                 future = None

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py in _safe_kernel_start(self)
    364                 self._kernel_terminate()
    365             finally:
--> 366                 raise e
    367 
    368     _KERNEL_OK = b"OK"

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py in _safe_kernel_start(self)
    358         """ Start a kernel. If something went wrong, clean-up resources that may have been created. """
    359         try:
--> 360             self._kernel_start()
    361         except Exception as e:
    362             logger.warning("Failed to start.")

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py in _kernel_start(self)
    454             logger.warning("Socket exception: %s", se)
    455             raise WolframKernelException(
--> 456                 "Failed to communicate with kernel: %s." % self.kernel
    457             )
    458 

WolframKernelException: Failed to communicate with kernel: [path].
  1. When path != '/usr/local/Wolfram/Mathematica/12.0/SystemFiles/Kernel/Binaries/Linux-x86-64/WolframKernel', it will wait for several seconds and return following errors:
Socket exception: Failed to read any message from socket tcp://127.0.0.1:39963 after 20.1 seconds and 200 retries.
Failed to start.
---------------------------------------------------------------------------
SocketOperationTimeout                    Traceback (most recent call last)
~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py in _kernel_start(self)
    436                 timeout=self.get_parameter("STARTUP_TIMEOUT"),
--> 437                 abort_event=_StartEvent(self.kernel_proc, self.trigger_termination_requested),
    438             )

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/zmqsocket.py in recv_abortable(socket, timeout, abort_check_period, abort_event, **kwargs)
     54                 "Failed to read any message from socket %s after %.1f seconds and %i retries."
---> 55                 % (socket.uri, time.perf_counter() - start, retry)
     56             )

SocketOperationTimeout: Failed to read any message from socket tcp://127.0.0.1:39963 after 20.1 seconds and 200 retries.

During handling of the above exception, another exception occurred:

WolframKernelException                    Traceback (most recent call last)
<ipython-input-3-84c234a8332d> in <module>
----> 1 sess.start()

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/localsession.py in start(self, block, timeout)
    155                 self.terminate()
    156             finally:
--> 157                 raise e
    158 
    159     def start_future(self):

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/localsession.py in start(self, block, timeout)
    150             future = self.start_future()
    151             if future and block:
--> 152                 future.result(timeout=timeout)
    153         except Exception as e:
    154             try:

~/anaconda3/envs/detectron2/lib/python3.6/concurrent/futures/_base.py in result(self, timeout)
    430                 raise CancelledError()
    431             elif self._state == FINISHED:
--> 432                 return self.__get_result()
    433             else:
    434                 raise TimeoutError()

~/anaconda3/envs/detectron2/lib/python3.6/concurrent/futures/_base.py in __get_result(self)
    382     def __get_result(self):
    383         if self._exception:
--> 384             raise self._exception
    385         else:
    386             return self._result

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py in run(self)
    525             # Kernel start requested.
    526             if payload is self.START:
--> 527                 self._safe_kernel_start()
    528                 future.set_result(True)
    529                 future = None

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py in _safe_kernel_start(self)
    364                 self._kernel_terminate()
    365             finally:
--> 366                 raise e
    367 
    368     _KERNEL_OK = b"OK"

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py in _safe_kernel_start(self)
    358         """ Start a kernel. If something went wrong, clean-up resources that may have been created. """
    359         try:
--> 360             self._kernel_start()
    361         except Exception as e:
    362             logger.warning("Failed to start.")

~/anaconda3/envs/detectron2/lib/python3.6/site-packages/wolframclient/evaluation/kernel/kernelcontroller.py in _kernel_start(self)
    454             logger.warning("Socket exception: %s", se)
    455             raise WolframKernelException(
--> 456                 "Failed to communicate with kernel: %s." % self.kernel
    457             )
    458 

WolframKernelException: Failed to communicate with kernel: [path]

Example of generating Wolfram Plot in Jupyter Notebook?

Can you provide an example of using WolframClientForPython to generate a Mathematica/Wolfram plot from Python that can be displayed inside a Python IDE such as a Jupyter Notebook or Spyder? I hope this can be done as it would be very useful.

Feature Request: Initiate WolframKernel with a specified entitlement

We require the execution of Wolfram in a dynamic cloud environment, where fixed containers, IPs, or machines are not employed. Utilizing entitlements in WolframScript has proven effective, as illustrated by the command wolframscript -entitlement "O-WSDS-....". However, our preference is to integrate Wolfram into our stack using a Python client. Unfortunately, it appears that the Python client does not currently support entitlements.

We express the need for the ability to incorporate entitlements when utilizing the Wolfram client for Python. This enhancement would greatly facilitate the seamless integration of Wolfram into our overall system architecture.

TypeError when running setup.py test

I'd like to package wolframclient for NixOS and I encounter this error when our build system runs python setup.py test:

Traceback (most recent call last):
  File "nix_run_setup", line 8, in <module>
    exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\\r\\n', '\\n'), __file__, 'exec'))
  File "setup.py", line 78, in <module>
    'wolframclient_serializers_encoder':[]
  File "/nix/store/110cqfw7ncbn4haynn8x8ziwzmr55dlg-python3.7-setuptools-45.2.0/lib/python3.7/site-packages/setuptools/__init__.py", line 144, in setup
    return distutils.core.setup(**attrs)
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/distutils/core.py", line 148, in setup
    dist.run_commands()
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/distutils/dist.py", line 966, in run_commands
    self.run_command(cmd)
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/distutils/dist.py", line 985, in run_command
    cmd_obj.run()
  File "/nix/store/110cqfw7ncbn4haynn8x8ziwzmr55dlg-python3.7-setuptools-45.2.0/lib/python3.7/site-packages/setuptools/command/test.py", line 238, in run
    self.run_tests()
  File "/nix/store/110cqfw7ncbn4haynn8x8ziwzmr55dlg-python3.7-setuptools-45.2.0/lib/python3.7/site-packages/setuptools/command/test.py", line 260, in run_tests
    exit=False,
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/main.py", line 100, in __init__
    self.parseArgs(argv)
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/main.py", line 147, in parseArgs
    self.createTests()
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/main.py", line 159, in createTests
    self.module)
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/loader.py", line 220, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/loader.py", line 220, in <listcomp>
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/loader.py", line 154, in loadTestsFromName
    module = __import__(module_name)
  File "/build/wolframclient-1.1.2/setup.py", line 78, in <module>
    'wolframclient_serializers_encoder':[]
  File "/nix/store/110cqfw7ncbn4haynn8x8ziwzmr55dlg-python3.7-setuptools-45.2.0/lib/python3.7/site-packages/setuptools/__init__.py", line 144, in setup
    return distutils.core.setup(**attrs)
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/distutils/core.py", line 148, in setup
    dist.run_commands()
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/distutils/dist.py", line 966, in run_commands
    self.run_command(cmd)
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/distutils/dist.py", line 985, in run_command
    cmd_obj.run()
  File "/nix/store/110cqfw7ncbn4haynn8x8ziwzmr55dlg-python3.7-setuptools-45.2.0/lib/python3.7/site-packages/setuptools/command/test.py", line 238, in run
    self.run_tests()
  File "/nix/store/110cqfw7ncbn4haynn8x8ziwzmr55dlg-python3.7-setuptools-45.2.0/lib/python3.7/site-packages/setuptools/command/test.py", line 260, in run_tests
    exit=False,
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/main.py", line 100, in __init__
    self.parseArgs(argv)
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/main.py", line 147, in parseArgs
    self.createTests()
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/main.py", line 159, in createTests
    self.module)
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/loader.py", line 220, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/loader.py", line 220, in <listcomp>
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/loader.py", line 205, in loadTestsFromName
    test = obj()
  File "/build/wolframclient-1.1.2/setup.py", line 40, in load_tests
    TestCommand().handle()
  File "/build/wolframclient-1.1.2/wolframclient/cli/commands/test.py", line 84, in handle
    result = runner.run(suite)
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/runner.py", line 153, in run
    result = self._makeResult()
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/runner.py", line 149, in _makeResult
    return self.resultclass(self.stream, self.descriptions, self.verbosity)
  File "/nix/store/xb1mp0f16lv23rwhfdc1665v5r20jfmm-python3-3.7.6/lib/python3.7/unittest/runner.py", line 40, in __init__
    self.showAll = verbosity > 1
TypeError: '>' not supported between instances of 'NoneType' and 'int'

wolframclient cannot locate kernel in Pop!_OS(linux distro)

wolframClientBugScreenshot

I can run the same code with Line 11 in windows10, but when I move to Pop!_OS(linux distro built on ubuntu) it is unable to locate the kernel. I first attempted Line 11, which did not work and then I found in the docs I need to specify the kernel location, which I did but cannot find it for some reason.

I verified this location using mathematica as well as going into the directory itself on the pc to verify it is present. I also tried specifying "WolframKernel.sh" at the end of the file path but that did not help either.

Calling the DSolve function in Python

Hello,
this is a problem regarding the DSolve function from Mathematica, called in Python.

When I try to call an integration statement
`from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, wlexpr
session = WolframLanguageSession()

alpha = wlexpr("Integrate[1/(x^3 + 1), {x, 0, 1}]")
result = session.evaluate(alpha)
print(result," ",type(result))`
everything works fine in Mathematica and in Mathematica called by Python.

When I try to run this
`from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, wlexpr
session = WolframLanguageSession()

diff_0 = "DSolve[y'[x] + y[x] == a Sin[x], y[x], x]"
diff_1 = "DSolve[{y'[x] + y[x] == a Sin[x], y[0] == 0}, y, x]"
diff_2 = "DSolve[y'[x] + y[x] == a Sin[x], y[x], x]"

alpha = wlexpr(diff_0)
result = session.evaluate(alpha)
print(result," ",result)`

I get the error
String expected at position 1 in StringForm[MessageName[General, pkspec1], Slot[1]]. The expression Slot[1] cannot be used as a part specification. String expected at position 1 in StringForm[MessageName[General, pkspec1], i]. The expression i cannot be used as a part specification. String expected at position 1 in StringForm[MessageName[General, pkspec1], Slot[1]]. The expression Slot[1] cannot be used as a part specification. String expected at position 1 in StringForm[MessageName[General, pkspec1], i]. The expression i cannot be used as a part specification.
in Python while it works in Mathematica and I don't understand, why.

'Interpreter' Can't Feedback

When I test this:

from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, Global, wlexpr
session = WolframLanguageSession(r'D:\Program Files\wolf\wolfram.exe')
session.evaluate('Interpreter["TeXExpression"]["2+2"]')

it never feedback and it can't stop, I don't know why, and how can I run it ?

how to find the path of kernel

I want to use the wolframclient by my python in anaconda, but raise the error that:

WolframKernelException: Cannot locate a kernel automatically. Please provide an explicit kernel path.

how can i find the path of kernel

wl.WolframAlpha getting failed in WolframCloudSession

I am trying to execute WolframAlpha query through WolframCloudSession, but getting a failed response. Any mistake here?

MY CODE:

from wolframclient.evaluation import SecuredAuthenticationKey, WolframCloudSession
from wolframclient.language import wl, wlexpr
from PIL import Image

sak = SecuredAuthenticationKey('KEY_1', 'KEY_2')
session = WolframCloudSession(credentials=sak)
session.start()
print(session.authorized())
print(session.evaluate(wl.MinMax([1, 5, -3, 9])))
print(session.evaluate(wl.WolframAlpha("what is the capital of Japan", "Result")))
session.terminate()

OUTPUT:
True
(-3, 9)
$Failed

Example to append a path and get a file?

Can you provide an example of using WolframClientForPython to append to a path and get a file? I have to file, I know how to work the same in Mathematica it is like

AppendTo[$Path, "/path”] and Get["filename"] but with wolframclient I'm not sure.

Proper way to timeout an evaluation

Hello,

I have been running the following code:

import time

from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl

if __name__ == '__main__':
    session = WolframLanguageSession('/Applications/Mathematica.app/Contents/MacOS/WolframKernel')

    print('start now')
    start = time.time()
    result = session.evaluate(wl.Pause(10), timeout=2.0)
    print('end after: {:.2f} seconds'.format(time.time() - start))
    print('result is:', result)
    print()
    print('start now')
    start = time.time()
    result = session.evaluate(wl.TimeConstrained(wl.Pause(10), 2))
    print('end after: {:.2f} seconds'.format(time.time() - start))
    print('result is:', result)

    session.terminate()

which results in the following output:

start now
end after: 14.29 seconds
result is: None

start now
end after: 2.00 seconds
result is: $Aborted

This makes me think that the timeout argument of session.evaluate(...) does not work as expected, so I will assume that using TimeConstrained is the recommended way to set a timeout to an evaluation, is that right?

Mathematica® version: 12.2
OS version: macOS Big Sur 11.2.3

As a side question, is there any way to "kill" (stop/terminate) a long-running evaluation while keeping the corresponding kernel alive and ready to accept further evaluations?
If no, is it possible to "kill" (stop/terminate) a long-running evaluation together with its kernel?

I tried to dig in a bit in the code but I believe getting a reply directly from the developers will be more reliable and precise. Thank you.

How to specify the path of kernel

Hi All,

I have installed Mathematica in Windows and wolframclient is installed in WSL, Windows Subsystem for Linux.
When I run WolframLanguage Session, the interpreter isn't able to locate the kernel path.

    "Cannot locate a kernel automatically. Please provide an explicit kernel path."
wolframclient.exception.WolframKernelException: Cannot locate a kernel automatically. Please provide an explicit kernel path.

The documentation available here shows how to set the path.
For instance, on linux
session = WolframLanguageSession('/usr/local/Wolfram/Desktop/11.3/Executables/WolframKernel')

Since I haven't installed Mathematica in WSL, I am not sure how to specify the path.

Any suggestions will be really helpful

Slow deserialization

Consider the following

KERNEL_PATH = '/opt/Mathematica/bin/WolframKernel'

import wolframclient.evaluation as w_evaluation


_ = 'Times[Exp[Times[Global`thetarho12, Plus[Times[0.5, Global`thetarho12, Plus[Power[Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Times[Plus[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Times[-1, Exp[Times[-1, Global`thetatheta2, Global`thetax]]]], Global`thetatheta1, Power[Plus[Global`thetatheta2, Times[-1, Global`thetatheta1]], -1]], Global`thetasigma2], Global`y20]]]], 2.], Power[Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Global`thetasigma1], Global`y10]]]], 2.]]], Times[-1, Times[Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Times[Plus[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Times[-1, Exp[Times[-1, Global`thetatheta2, Global`thetax]]]], Global`thetatheta1, Power[Plus[Global`thetatheta2, Times[-1, Global`thetatheta1]], -1]], Global`thetasigma2], Global`y20]]]], Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Global`thetasigma1], Global`y10]]]]]]], Power[Plus[Power[Global`thetarho12, 2.], Times[-1, 1.]], -1]]], Power[Power[Plus[1., Times[-1, Power[Global`thetarho12, 2.]]], 0.5], -1], Exp[Times[Global`thetarho13, Plus[Times[0.5, Global`thetarho13, Plus[Power[Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Plus[1., Times[Plus[Times[-1, Global`thetatheta2, Exp[Times[-1, Global`thetatheta1, Global`thetax]]], Times[Global`thetatheta1, Exp[Times[-1, Global`thetatheta2, Global`thetax]]]], Power[Plus[Global`thetatheta2, Times[-1, Global`thetatheta1]], -1]]], Global`thetasigma3], Global`y30]]]], 2.], Power[Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Global`thetasigma1], Global`y10]]]], 2.]]], Times[-1, Times[Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Plus[1., Times[Plus[Times[-1, Global`thetatheta2, Exp[Times[-1, Global`thetatheta1, Global`thetax]]], Times[Global`thetatheta1, Exp[Times[-1, Global`thetatheta2, Global`thetax]]]], Power[Plus[Global`thetatheta2, Times[-1, Global`thetatheta1]], -1]]], Global`thetasigma3], Global`y30]]]], Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Global`thetasigma1], Global`y10]]]]]]], Power[Plus[Power[Global`thetarho13, 2.], Times[-1, 1.]], -1]]], Power[Power[Plus[1., Times[-1, Power[Global`thetarho13, 2.]]], 0.5], -1], Exp[Times[Global`thetarho23g1, Plus[Times[0.5, Global`thetarho23g1, Plus[Power[Times[Plus[Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Plus[1., Times[Plus[Times[-1, Global`thetatheta2, Exp[Times[-1, Global`thetatheta1, Global`thetax]]], Times[Global`thetatheta1, Exp[Times[-1, Global`thetatheta2, Global`thetax]]]], Power[Plus[Global`thetatheta2, Times[-1, Global`thetatheta1]], -1]]], Global`thetasigma3], Global`y30]]]], Times[-1, Times[Global`thetarho13, Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Global`thetasigma1], Global`y10]]]]]]], Power[Power[Plus[1., Times[-1, Power[Global`thetarho13, 2.]]], 0.5], -1]], 2.], Power[Times[Plus[Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Times[Plus[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Times[-1, Exp[Times[-1, Global`thetatheta2, Global`thetax]]]], Global`thetatheta1, Power[Plus[Global`thetatheta2, Times[-1, Global`thetatheta1]], -1]], Global`thetasigma2], Global`y20]]]], Times[-1, Times[Global`thetarho12, Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Global`thetasigma1], Global`y10]]]]]]], Power[Power[Plus[1., Times[-1, Power[Global`thetarho12, 2.]]], 0.5], -1]], 2.]]], Times[-1, Times[Plus[Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Plus[1., Times[Plus[Times[-1, Global`thetatheta2, Exp[Times[-1, Global`thetatheta1, Global`thetax]]], Times[Global`thetatheta1, Exp[Times[-1, Global`thetatheta2, Global`thetax]]]], Power[Plus[Global`thetatheta2, Times[-1, Global`thetatheta1]], -1]]], Global`thetasigma3], Global`y30]]]], Times[-1, Times[Global`thetarho13, Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Global`thetasigma1], Global`y10]]]]]]], Power[Power[Plus[1., Times[-1, Power[Global`thetarho13, 2.]]], 0.5], -1], Plus[Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Times[Plus[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Times[-1, Exp[Times[-1, Global`thetatheta2, Global`thetax]]]], Global`thetatheta1, Power[Plus[Global`thetatheta2, Times[-1, Global`thetatheta1]], -1]], Global`thetasigma2], Global`y20]]]], Times[-1, Times[Global`thetarho12, Quantile[NormalDistribution[0, 1], Plus[1., Times[-1, CDF[NormalDistribution[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Global`thetasigma1], Global`y10]]]]]]], Power[Power[Plus[1., Times[-1, Power[Global`thetarho12, 2.]]], 0.5], -1]]]], Power[Plus[Power[Global`thetarho23g1, 2.], Times[-1, 1.]], -1]]], Power[Power[Plus[1., Times[-1, Power[Global`thetarho23g1, 2.]]], 0.5], -1], PDF[NormalDistribution[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Global`thetasigma1], Global`y10], PDF[NormalDistribution[Times[Plus[Exp[Times[-1, Global`thetatheta1, Global`thetax]], Times[-1, Exp[Times[-1, Global`thetatheta2, Global`thetax]]]], Global`thetatheta1, Power[Plus[Global`thetatheta2, Times[-1, Global`thetatheta1]], -1]], Global`thetasigma2], Global`y20], PDF[NormalDistribution[Plus[1., Times[Plus[Times[-1, Global`thetatheta2, Exp[Times[-1, Global`thetatheta1, Global`thetax]]], Times[Global`thetatheta1, Exp[Times[-1, Global`thetatheta2, Global`thetax]]]], Power[Plus[Global`thetatheta2, Times[-1, Global`thetatheta1]], -1]]], Global`thetasigma3], Global`y30]]'
_ = 'D[Log[{}], {{{{Global`thetatheta1, Global`thetatheta2, Global`thetasigma1, Global`thetasigma2, Global`thetasigma3, Global`thetarho12, Global`thetarho13, Global`thetarho23g1}}, 2}}]'.format(_)

with w_evaluation.WolframLanguageSession(kernel=KERNEL_PATH) as session:
  result = session.evaluate(_)

print(result)

In the profile I see 50.4s in session.evaluate and 49.9s in binary_deserialize. I assume there is not much asynchronous execution, so timing should be correct. Is there any chance to speed things up? In this case, the result is composed of many similar sub expressions (due to chain rule) which could be cached in transmission.

Error "No module named 'wolframclient.evaluation'" issued

I am trying to do some automation using Mathematica in python. I install the package but I encounter an error "No module named 'wolframclient.evaluation'". I have installed the complete package and there is a folder called evaluation in wolframclient.

How to convert back "WolframObjects" to python objects

e.g.
Table[Values[i], {i, WordData["motorbus", "Synonyms"]}]
Id like to have a python List..
As of now I am doing it like this (which seems very hacky)

raw_results = evaluate('ExportString[Table[Values[i], {i, WordData["motorbus", "Synonyms"]}], "CSV"]')
result_list = results.replace('"', '').replace('\n', '').split(',')

wolframclient.exception.WolframParserException: Invalid version b''.

I am trying to run the client on MacOS and Mathematica 13.3, but I am getting the following error after running:

Python 3.11.5 (main, Aug 24 2023, 15:18:16) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from wolframclient.evaluation import WolframLanguageSession
>>> from wolframclient.language import wl, wlexpr
>>> session.evaluate(wlexpr('Range[5]'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/evaluation/kernel/localsession.py", line 262, in evaluate
    result = self.evaluate_wrap(expr, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/evaluation/kernel/localsession.py", line 259, in evaluate_wrap
    return self.evaluate_wrap_future(expr, **kwargs).result()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/Cellar/[email protected]/3.11.5/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/_base.py", line 456, in result
    return self.__get_result()
           ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/Cellar/[email protected]/3.11.5/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/_base.py", line 401, in __get_result
    raise self._exception
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/evaluation/kernel/kernelcontroller.py", line 583, in run
    self._do_evaluate(payload, future, result_update_callback)
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/evaluation/kernel/kernelcontroller.py", line 543, in _do_evaluate
    for msg in result.iter_messages():
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/evaluation/result.py", line 118, in iter_messages
    if self.messages:
       ^^^^^^^^^^^^^
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/evaluation/result.py", line 103, in messages
    self.build()
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/evaluation/result.py", line 155, in build
    self.parse_response()
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/evaluation/result.py", line 245, in parse_response
    self.parsed_response = binary_deserialize(self.wxf_evaluation_data)
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/deserializers/wxf/__init__.py", line 35, in binary_deserialize
    parser = WXFParser(wxf_input)
             ^^^^^^^^^^^^^^^^^^^^
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/deserializers/wxf/wxfparser.py", line 88, in __init__
    version, compress = self.parse_header()
                        ^^^^^^^^^^^^^^^^^^^
  File "/Applications/Mathematica.app/Contents/SystemFiles/Components/WolframClientForPython/wolframclient/deserializers/wxf/wxfparser.py", line 107, in parse_header
    raise WolframParserException("Invalid version %s." % next_byte)
wolframclient.exception.WolframParserException: Invalid version b''.

What could be the issue? What does the constant WXF_VERSION means?

Cannot serialize object of class numpy.float32

import numpy
import wolframclient.serializers as wxf
wxf.export(numpy.float32(0))

Version:

  • numpy 1.15.3
  • WolframClient1.0.0.dev2
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "c:\Anaconda3\lib\site-packages\wolframclient\serializers\__init__.py", line 60, in export
    data, stream=stream)
  File "c:\Anaconda3\lib\site-packages\wolframclient\serializers\base.py", line 29, in export
    stream = self.dump(data, stream)
  File "c:\Anaconda3\lib\site-packages\wolframclient\serializers\wl.py", line 31, in dump
    for payload in self.normalize(data):
  File "c:\Anaconda3\lib\site-packages\wolframclient\utils\dispatch.py", line 96, in inner
    return self.resolve(function, *args)(obj, *args, **opts)
  File "c:\Anaconda3\lib\site-packages\wolframclient\serializers\normalizer\__init__.py", line 26, in normalizer
    'Cannot serialize object of class %s' % o.__class__)
NotImplementedError: Cannot serialize object of class <class 'numpy.float32'>

issue while evaluating MMA expression in Python

Hi All,
This is a follow up to the question posted here

I've the following MMA code

edges = {1 <-> 2, 1 <-> 3, 1 <-> 4, 2 <-> 5, 2 <-> 6, 5 <-> 6, 
   3 <-> 4, 3 <-> 7, 6 <-> 7, 7 <-> 8, 2 <-> 9};

vd = {{75., 25., 0}, {115., 45., 0}, {10., 5., 0}, {45., 0, 0}, 
  {90., 60., 0}, {45., 55., 0}, {0, 25., 0}, {10., 50., 0}, {115.,  25.,0}};

vl = Range[Length@vd];

vcoords = MapIndexed[#2[[1]] -> # &, vd];
ew = {1 \[UndirectedEdge] 2 -> 49.6, 1 \[UndirectedEdge] 3 -> 74.4, 
 1 \[UndirectedEdge] 4 -> 49.6, 2 \[UndirectedEdge] 5 -> 37.2, 
 2 \[UndirectedEdge] 6 -> 74.4, 5 \[UndirectedEdge] 6 -> 49.6, 
 3 \[UndirectedEdge] 4 -> 37.2, 3 \[UndirectedEdge] 7 -> 24.8, 
 6 \[UndirectedEdge] 7 -> 62, 7 \[UndirectedEdge] 8 -> 37.2, 
 2 \[UndirectedEdge] 9 -> 24.8}

g3d = Graph3D[vl, edges, VertexCoordinates -> vcoords, 
  EdgeWeight -> ew, VertexLabels -> Placed["Name", Center], 
  EdgeLabels -> {e_ :> Placed["EdgeWeight", Center]}, 
  VertexSize -> .3, VertexStyle -> Red]
vars3d = Array[Through[{x, y, z}@#] &, Length @ vd];

λ = 1/100.;

obj3d = Total[(Norm[vars3d[[First@#]] - vars3d[[Last@#]]] - # /. ew)^2 & /@ 
  EdgeList[g3d]] +  λ Total[Norm /@ (vars3d - vd)];

lbnd = 0;
ubnd = 500;

solution3d = Last@Minimize[{obj3d, And @@ Thread[lbnd <= Join @@ vars3d <= ubnd]}, 
    Join @@ vars3d];

edgeLengths3d = # -> Norm[vars3d[[First@#]] - vars3d[[Last@#]]] /. 
     solution3d & /@ EdgeList[g3d];

Grid[Prepend[{#, # /. ew, # /. edgeLengths3d} & /@ 
   EdgeList[g3d], {"edge", "EdgeWeight", "Edge Length"}], 
 Dividers -> All]

Following the suggestions offered in the link shared above I installed wolframclient and tried the following


from wolframclient.evaluation import WolframLanguageSession
session = WolframLanguageSession()
from wolframclient.language import wlexpr


session.evaluate(wlexpr(
'edges = {1 <-> 2, 1 <-> 3, 1 <-> 4, 2 <-> 5, 2 <-> 6, 5 <-> 6, 3 <-> 4, 3 <-> 7, 6 <-> 7, 7 <-> 8, 2 <-> 9};'

'vd = {{75., 25., 0}, {115., 45., 0}, {10., 5., 0}, {45., 0, 0},{90., 60., 0}, {45., 55., 0}, {0, 25., 0}, {10., 50., 0}, {115.,  25.,0}};'

'vl = Range[Length@vd];'
'vcoords = MapIndexed[#2[[1]] -> # &, vd];'
'ew = {1 \[UndirectedEdge] 2 -> 49.6, 1 \[UndirectedEdge] 3 -> 74.4,'
'1 \[UndirectedEdge] 4 -> 49.6, 2 \[UndirectedEdge] 5 -> 37.2,'
'2 \[UndirectedEdge] 6 -> 74.4, 5 \[UndirectedEdge] 6 -> 49.6,'
'3 \[UndirectedEdge] 4 -> 37.2, 3 \[UndirectedEdge] 7 -> 24.8,'
'6 \[UndirectedEdge] 7 -> 62, 7 \[UndirectedEdge] 8 -> 37.2,'
'2 \[UndirectedEdge] 9 -> 24.8};'

'g3d = Graph3D[vl, edges, VertexCoordinates -> vcoords,EdgeWeight -> ew, VertexLabels -> Placed["Name", Center],'
'EdgeLabels -> {e_ :> Placed["EdgeWeight", Center]},'
'VertexSize -> .3, VertexStyle -> Red];'

'vars3d = Array[Through[{x, y, z}@#] &, Length @ vd];'
'λ = 1/100.;'
'obj3d = Total[(Norm[vars3d[[First@#]] - vars3d[[Last@#]]] - # /. ew)^2 & /@EdgeList[g3d]] +  λ Total[Norm /@ (vars3d - vd)];'
'lbnd = 0;'
'ubnd = 500;'

'solution3d = Last@Minimize[{obj3d, And @@ Thread[lbnd <= Join @@ vars3d <= ubnd]},Join @@ vars3d];'

'edgeLengths3d = # -> Norm[vars3d[[First@#]] - vars3d[[Last@#]]] /.solution3d & /@ EdgeList[g3d];'

'Grid[Prepend[{#, # /. ew, # /. edgeLengths3d} & /@EdgeList[g3d], {"edge", "EdgeWeight", "Edge Length"}],Dividers -> All];'

'z1 = Values[solution3d] // Partition[#, 3] &;'

'theFile = File["op.txt"];'

'Export[theFile, z1, "Table"];'
    ))

but I get the following error

String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList].
Undefined message MessageName[Message, msgl] with arguments {$MessageList}
The problem may be unbounded. Specifying a value for MaxIterations greater than 5000 may improve the solution.
String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList].
Undefined message MessageName[Message, msgl] with arguments {$MessageList}
String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList].
Further output of MessageName[StringForm, string] will be suppressed during this calculation.
The problem may be unbounded. Specifying a value for MaxIterations greater than 5000 may improve the solution.
String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList].
Undefined message MessageName[Message, msgl] with arguments {$MessageList}
The problem may be unbounded. Specifying a value for MaxIterations greater than 5000 may improve the solution.
String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList].
Undefined message MessageName[Message, msgl] with arguments {$MessageList}
String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList].
Further output of MessageName[StringForm, string] will be suppressed during this calculation.
The problem may be unbounded. Specifying a value for MaxIterations greater than 5000 may improve the solution.

Suggestions on how to resolve this error will be really helpful.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.