wolframclient.evaluation.kernel package

Submodules

wolframclient.evaluation.kernel.asyncsession module

class wolframclient.evaluation.kernel.asyncsession.WolframLanguageAsyncSession(kernel=None, consumer=None, loop=None, initfile=None, kernel_loglevel=0, stdin=-1, stdout=-1, stderr=-1, inputform_string_evaluation=True, **kwargs)[source]

Bases: wolframclient.evaluation.base.WolframAsyncEvaluator, wolframclient.evaluation.kernel.localsession.WolframLanguageSession

Evaluate expressions asynchronously using coroutines.

Asynchronous evaluations are provided through coroutines and the asyncio modules.

Instances of this class can be managed with an asynchronous context manager:

async with WolframLanguageAsyncSession() as session:
    await session.evaluate('Now')

An event loop can be explicitly passed using the named parameter loop; otherwise, the one returned by get_event_loop() is used.

Coroutines all run in a unique thread. Since a Wolfram kernel is single threaded, there can be only one evaluation at a time. In a sense, from the event loop point of view, evaluations are atomic operations. Even when many asynchronous sessions are started, the number of threads equals the number of kernel instances running and should not be problematic. Ensuring that only one thread runs all operations of a given Wolfram kernel significantly reduces the complexity of the code without any real drawback.

do_evaluate_future(expr, result_update_callback=None, **kwargs)[source]
duplicate()[source]

Build a new instance using the same configuration as the one being duplicated.

ensure_started()[source]
evaluate(expr, **kwargs)[source]

Evaluate an expression asynchronously.

This method is a coroutine.

evaluate_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the evaluated expression. See evaluate().

evaluate_many(expr_list)[source]

Evaluate a given list of Wolfram Language expressions.

The list is provided as an iterable object.

evaluate_wrap(expr, **kwargs)[source]

Evaluate an expression and return a result object asynchronously.

This method is a coroutine.

evaluate_wrap_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the result object with the evaluated expression and meta information. See evaluate_wrap().

evaluate_wxf(expr, **kwargs)[source]

Evaluate an expression and return the WXF output asynchronously.

This method is a coroutine.

evaluate_wxf_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the WXF serialization of the evaluated expression. See evaluate_wxf().

restart()[source]

Restart a given evaluator by stopping it in cases where it is already started.

start()[source]

Asynchronously start the session.

This method is a coroutine.

stop()[source]

Asynchronously stop the session (graceful termination).

This method is a coroutine.

terminate()[source]

Asynchronously terminate the session.

This method is a coroutine.

wolframclient.evaluation.kernel.kernelcontroller module

class wolframclient.evaluation.kernel.kernelcontroller.WolframKernelController(kernel=None, initfile=None, consumer=None, kernel_loglevel=0, stdin=-1, stdout=-1, stderr=-1, **kwargs)[source]

Bases: threading.Thread

Control a Wolfram kernel from a Python thread.

A controller can start and stop a Wolfram kernel specified by its path kernel. It can evaluate expression, one at a time.

Most methods from this class return instances of Future.

This class is a low level component of the library which is used by local evaluators.

ZMQ sockets are not thread safe, this class ensures encapsulation of them, while enabling asynchronous operations.

START = <object object>
STOP = <object object>
default_kernel_path()[source]
duplicate()[source]

Build a new object using the same configuration as the current one.

enqueue_task(payload, future, callback)[source]
evaluate_future(wxf, future, result_update_callback=None, **kwargs)[source]
get_parameter(parameter_name)[source]

Return the value of a given session parameter.

Session parameters are:

  • 'STARTUP_TIMEOUT': time to wait, in seconds, after the kernel startup is requested. Default is 20 seconds.
  • 'TERMINATE_TIMEOUT': time to wait, in seconds, after the Quit[] command is sent to the kernel. The kernel is killed after this duration. Default is 3 seconds.
is_kernel_alive()[source]

Return the status of the kernel process.

join(timeout=None)[source]

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

pid

Return the PID of the Wolfram kernel process, if any, or None.

request_kernel_start()[source]

Start the thread and the associated kernel. Return a future object indicating the kernel status.

The future object result is True once the kernel is successfully started. Exception raised in the process and passed to the future object.

Calling this method twice is a no-op.

run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

set_parameter(parameter_name, parameter_value)[source]

Set a new value for a given parameter. The new value only applies for this session.

Session parameters are:

  • 'STARTUP_TIMEOUT': time to wait, in seconds, after the kernel startup is requested. Default is 20 seconds.
  • 'TERMINATE_TIMEOUT': time to wait, in seconds, after the Quit[] command is sent to the kernel. The kernel is killed after this duration. Default is 3 seconds.
started

Is the kernel starting or being started.

stop()[source]
terminate()[source]
terminated

Is the kernel terminated. Terminated kernel no more handle evaluations.

wolframclient.evaluation.kernel.localsession module

class wolframclient.evaluation.kernel.localsession.WolframLanguageSession(kernel=None, consumer=None, initfile=None, kernel_loglevel=0, stdin=-1, stdout=-1, stderr=-1, inputform_string_evaluation=True, wxf_bytes_evaluation=True, controller_class=<class 'wolframclient.evaluation.kernel.kernelcontroller.WolframKernelController'>, **kwargs)[source]

Bases: wolframclient.evaluation.base.WolframEvaluator

A session to a Wolfram kernel enabling evaluation of Wolfram Language expressions.

Start a new session and send an expression for evaluation:

with WolframLanguageSession() as session:
    session.evaluate('Range[3]')

Set timeout to a number to set an evaluation timeout in seconds. If the evaluation time extends the timeout, a TimeoutError is raised.

Evaluate an expression taking 10 seconds to return using a 5-second timeout:

long_evaluation = wl.Pause(10)
with WolframLanguageSession() as session:
    session.evaluate(long_evaluation, timeout=5)

The asynchronous evaluation method evaluate_future() returns an instance of Future class wrapping the evaluation result:

with WolframLanguageSession() as session:
    future = session.evaluate_future('1+1')
    result = future.result()

When consumer is set to a WXFConsumer instance, this instance is passed to binary_deserialize() when deserializing the WXF output.

By default, packed arrays are deserialized as list. Specify a consumer instance that supports NumPy arrays WXFConsumerNumpy:

from wolframclient.deserializers import WXFConsumerNumpy

with WolframLanguageSession(consumer=WXFConsumerNumpy()) as session:
    numpy_array = session.evaluate('Range[3]')

Communication with a given kernel is based on ZMQ sockets:

  • one PUSH socket to send expressions for evaluation
  • one PULL socket to receive evaluation results

Kernel logging is disabled by default and is done through a third socket (type SUB). The initial log level is specified by the parameter kernel_loglevel. If the log level was not set at initialization, logging is not available for the entire session.

The kernel associated with a given session provides the following logging functions:

  • ClientLibrary`debug corresponding to logging.Logger.debug()
  • ClientLibrary`info corresponding to logging.Logger.info()
  • ClientLibrary`warn corresponding to logging.Logger.warning()
  • ClientLibrary`error corresponding to logging.Logger.error()
  • ClientLibrary`SetDebugLogLevel[] send debug messages and above
  • ClientLibrary`SetInfoLogLevel[] send info messages and above
  • ClientLibrary`SetWarnLogLevel[] send warning messages and above
  • ClientLibrary`SetErrorLogLevel[] only send error messages
  • ClientLibrary`DisableKernelLogging[] stop sending error message to the logging socket

The standard input, output and error file handles can be specified with stdin, stdout and stderr named parameters. Valid values are those accepted by subprocess.Popen (e.g. sys.stdout). Those parameters should be handled with care as deadlocks can arise from misconfiguration.

static CALLBACK_GET(result)
static CALLBACK_GET_WXF(result)
do_evaluate_future(expr, result_update_callback=None, **kwargs)[source]
duplicate()[source]

Build a new instance using the same configuration as the one being duplicated.

ensure_started()[source]
evaluate(expr, **kwargs)[source]

Evaluate a given Wolfram Language expression.

evaluate_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the evaluated expression. See evaluate().

evaluate_wrap(expr, **kwargs)[source]

Evaluate a given Wolfram Language expression and return a result object with the result and meta information.

evaluate_wrap_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the result object with the evaluated expression and meta information. See evaluate_wrap().

evaluate_wxf(expr, **kwargs)[source]

Evaluate an expression and return the serialized expression.

This method does not deserialize the Wolfram kernel input.

evaluate_wxf_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the WXF serialization of the evaluated expression. See evaluate_wxf().

get_parameter(parameter_name)[source]

Return the value of a given session parameter.

Session parameters are:

  • 'STARTUP_TIMEOUT': time to wait, in seconds, after the kernel startup is requested. Default is 20 seconds.
  • 'TERMINATE_TIMEOUT': time to wait, in seconds, after the Quit[] command is sent to the kernel. The kernel is killed after this duration. Default is 3 seconds.
log_message_from_result(result)[source]
restart(block=True, timeout=None)[source]

Restart a given evaluator by stopping it in cases where it is already started.

set_parameter(parameter_name, parameter_value)[source]

Set a new value for a given parameter. The new value only applies for this session.

Session parameters are:

  • 'STARTUP_TIMEOUT': time to wait, in seconds, after the kernel startup is requested. Default is 20 seconds.
  • 'TERMINATE_TIMEOUT': time to wait, in seconds, after the Quit[] command is sent to the kernel. The kernel is killed after this duration. Default is 3 seconds.
start(block=True, timeout=None)[source]

Start a kernel controller and eventually start a fresh one if the previous one was terminated.

Set block to True (default is False) to wait for the kernel to be up and running before returning. Optionally, set a timeout in seconds. If the timeout is reached, a TimeoutError will be raised and the kernel is terminated.

start_future()[source]

Request the Wolfram kernel to start and return a future object.

The result of the future object is True when the kernel is ready to evaluate input.

started
stop()[source]

Request the Wolfram kernel to stop gracefully.

stop_future(gracefully=True)[source]

Request the Wolfram kernel to stop and return a future object.

The result of the future object is True when the controller thread is no longer alive. Set gracefully to False to request an immediate stop, eventually cancelling ongoing evaluations.

terminate()[source]

Request the Wolfram kernel to stop immediately.

Ongoing evaluations may be cancelled.

wolframclient.evaluation.kernel.path module

wolframclient.evaluation.kernel.path.exe_path()[source]
wolframclient.evaluation.kernel.path.explore_paths(*paths)[source]
wolframclient.evaluation.kernel.path.find_default_kernel_path()[source]

Look for the most recent installed kernel.

wolframclient.evaluation.kernel.path.installation_directories()[source]

wolframclient.evaluation.kernel.zmqsocket module

class wolframclient.evaluation.kernel.zmqsocket.Socket(protocol='tcp', host='127.0.0.1', port=None, zmq_type=0)[source]

Bases: object

Wrapper around ZMQ socket

bind(protocol='tcp', host='127.0.0.1', port=None)[source]
bind_to_uri(uri)[source]
can_bind_or_fail()[source]
close()[source]
poll(*args, **kwargs)[source]
recv(*args, **kwargs)[source]
recv_abortable(**kwargs)[source]

Read a socket in a non-blocking fashion, until a timeout is reached, or until an abort Event is set.

recv_json(*args, **kwargs)[source]
recv_json_abortable(**kwargs)[source]

Read a socket for a json message, in a non-blocking fashion, until a timeout is reached, or until an abort Event is set.

send(*args, **kwargs)[source]
exception wolframclient.evaluation.kernel.zmqsocket.SocketAborted(payload, exec_info=None)[source]

Bases: wolframclient.evaluation.kernel.zmqsocket.SocketException

exception wolframclient.evaluation.kernel.zmqsocket.SocketException(payload, exec_info=None)[source]

Bases: wolframclient.language.exceptions.WolframLanguageException

exception wolframclient.evaluation.kernel.zmqsocket.SocketOperationTimeout(payload, exec_info=None)[source]

Bases: wolframclient.evaluation.kernel.zmqsocket.SocketException

wolframclient.evaluation.kernel.zmqsocket.abortable()[source]

Module contents

class wolframclient.evaluation.kernel.WolframLanguageSession(kernel=None, consumer=None, initfile=None, kernel_loglevel=0, stdin=-1, stdout=-1, stderr=-1, inputform_string_evaluation=True, wxf_bytes_evaluation=True, controller_class=<class 'wolframclient.evaluation.kernel.kernelcontroller.WolframKernelController'>, **kwargs)[source]

Bases: wolframclient.evaluation.base.WolframEvaluator

A session to a Wolfram kernel enabling evaluation of Wolfram Language expressions.

Start a new session and send an expression for evaluation:

with WolframLanguageSession() as session:
    session.evaluate('Range[3]')

Set timeout to a number to set an evaluation timeout in seconds. If the evaluation time extends the timeout, a TimeoutError is raised.

Evaluate an expression taking 10 seconds to return using a 5-second timeout:

long_evaluation = wl.Pause(10)
with WolframLanguageSession() as session:
    session.evaluate(long_evaluation, timeout=5)

The asynchronous evaluation method evaluate_future() returns an instance of Future class wrapping the evaluation result:

with WolframLanguageSession() as session:
    future = session.evaluate_future('1+1')
    result = future.result()

When consumer is set to a WXFConsumer instance, this instance is passed to binary_deserialize() when deserializing the WXF output.

By default, packed arrays are deserialized as list. Specify a consumer instance that supports NumPy arrays WXFConsumerNumpy:

from wolframclient.deserializers import WXFConsumerNumpy

with WolframLanguageSession(consumer=WXFConsumerNumpy()) as session:
    numpy_array = session.evaluate('Range[3]')

Communication with a given kernel is based on ZMQ sockets:

  • one PUSH socket to send expressions for evaluation
  • one PULL socket to receive evaluation results

Kernel logging is disabled by default and is done through a third socket (type SUB). The initial log level is specified by the parameter kernel_loglevel. If the log level was not set at initialization, logging is not available for the entire session.

The kernel associated with a given session provides the following logging functions:

  • ClientLibrary`debug corresponding to logging.Logger.debug()
  • ClientLibrary`info corresponding to logging.Logger.info()
  • ClientLibrary`warn corresponding to logging.Logger.warning()
  • ClientLibrary`error corresponding to logging.Logger.error()
  • ClientLibrary`SetDebugLogLevel[] send debug messages and above
  • ClientLibrary`SetInfoLogLevel[] send info messages and above
  • ClientLibrary`SetWarnLogLevel[] send warning messages and above
  • ClientLibrary`SetErrorLogLevel[] only send error messages
  • ClientLibrary`DisableKernelLogging[] stop sending error message to the logging socket

The standard input, output and error file handles can be specified with stdin, stdout and stderr named parameters. Valid values are those accepted by subprocess.Popen (e.g. sys.stdout). Those parameters should be handled with care as deadlocks can arise from misconfiguration.

static CALLBACK_GET(result)
static CALLBACK_GET_WXF(result)
do_evaluate_future(expr, result_update_callback=None, **kwargs)[source]
duplicate()[source]

Build a new instance using the same configuration as the one being duplicated.

ensure_started()[source]
evaluate(expr, **kwargs)[source]

Evaluate a given Wolfram Language expression.

evaluate_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the evaluated expression. See evaluate().

evaluate_wrap(expr, **kwargs)[source]

Evaluate a given Wolfram Language expression and return a result object with the result and meta information.

evaluate_wrap_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the result object with the evaluated expression and meta information. See evaluate_wrap().

evaluate_wxf(expr, **kwargs)[source]

Evaluate an expression and return the serialized expression.

This method does not deserialize the Wolfram kernel input.

evaluate_wxf_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the WXF serialization of the evaluated expression. See evaluate_wxf().

get_parameter(parameter_name)[source]

Return the value of a given session parameter.

Session parameters are:

  • 'STARTUP_TIMEOUT': time to wait, in seconds, after the kernel startup is requested. Default is 20 seconds.
  • 'TERMINATE_TIMEOUT': time to wait, in seconds, after the Quit[] command is sent to the kernel. The kernel is killed after this duration. Default is 3 seconds.
log_message_from_result(result)[source]
restart(block=True, timeout=None)[source]

Restart a given evaluator by stopping it in cases where it is already started.

set_parameter(parameter_name, parameter_value)[source]

Set a new value for a given parameter. The new value only applies for this session.

Session parameters are:

  • 'STARTUP_TIMEOUT': time to wait, in seconds, after the kernel startup is requested. Default is 20 seconds.
  • 'TERMINATE_TIMEOUT': time to wait, in seconds, after the Quit[] command is sent to the kernel. The kernel is killed after this duration. Default is 3 seconds.
start(block=True, timeout=None)[source]

Start a kernel controller and eventually start a fresh one if the previous one was terminated.

Set block to True (default is False) to wait for the kernel to be up and running before returning. Optionally, set a timeout in seconds. If the timeout is reached, a TimeoutError will be raised and the kernel is terminated.

start_future()[source]

Request the Wolfram kernel to start and return a future object.

The result of the future object is True when the kernel is ready to evaluate input.

started
stop()[source]

Request the Wolfram kernel to stop gracefully.

stop_future(gracefully=True)[source]

Request the Wolfram kernel to stop and return a future object.

The result of the future object is True when the controller thread is no longer alive. Set gracefully to False to request an immediate stop, eventually cancelling ongoing evaluations.

terminate()[source]

Request the Wolfram kernel to stop immediately.

Ongoing evaluations may be cancelled.

class wolframclient.evaluation.kernel.WolframLanguageAsyncSession(kernel=None, consumer=None, loop=None, initfile=None, kernel_loglevel=0, stdin=-1, stdout=-1, stderr=-1, inputform_string_evaluation=True, **kwargs)[source]

Bases: wolframclient.evaluation.base.WolframAsyncEvaluator, wolframclient.evaluation.kernel.localsession.WolframLanguageSession

Evaluate expressions asynchronously using coroutines.

Asynchronous evaluations are provided through coroutines and the asyncio modules.

Instances of this class can be managed with an asynchronous context manager:

async with WolframLanguageAsyncSession() as session:
    await session.evaluate('Now')

An event loop can be explicitly passed using the named parameter loop; otherwise, the one returned by get_event_loop() is used.

Coroutines all run in a unique thread. Since a Wolfram kernel is single threaded, there can be only one evaluation at a time. In a sense, from the event loop point of view, evaluations are atomic operations. Even when many asynchronous sessions are started, the number of threads equals the number of kernel instances running and should not be problematic. Ensuring that only one thread runs all operations of a given Wolfram kernel significantly reduces the complexity of the code without any real drawback.

do_evaluate_future(expr, result_update_callback=None, **kwargs)[source]
duplicate()[source]

Build a new instance using the same configuration as the one being duplicated.

ensure_started()[source]
evaluate(expr, **kwargs)[source]

Evaluate an expression asynchronously.

This method is a coroutine.

evaluate_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the evaluated expression. See evaluate().

evaluate_many(expr_list)[source]

Evaluate a given list of Wolfram Language expressions.

The list is provided as an iterable object.

evaluate_wrap(expr, **kwargs)[source]

Evaluate an expression and return a result object asynchronously.

This method is a coroutine.

evaluate_wrap_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the result object with the evaluated expression and meta information. See evaluate_wrap().

evaluate_wxf(expr, **kwargs)[source]

Evaluate an expression and return the WXF output asynchronously.

This method is a coroutine.

evaluate_wxf_future(expr, **kwargs)[source]

Evaluate an expression and return a future object.

The future object result is the WXF serialization of the evaluated expression. See evaluate_wxf().

restart()[source]

Restart a given evaluator by stopping it in cases where it is already started.

start()[source]

Asynchronously start the session.

This method is a coroutine.

stop()[source]

Asynchronously stop the session (graceful termination).

This method is a coroutine.

terminate()[source]

Asynchronously terminate the session.

This method is a coroutine.