wolframclient.evaluation package

Submodules

wolframclient.evaluation.base module

class wolframclient.evaluation.base.WolframAsyncEvaluator(loop=None, **kwargs)[source]

Bases: wolframclient.evaluation.base.WolframEvaluatorBase

Asynchronous evaluators are similar to synchronous ones except that they make heavy use of coroutines and need an event loop.

Most methods from this class are similar to their counterpart from WolframEvaluator, except that they are coroutines.

evaluate(expr)[source]
evaluate_many(expr_list)[source]
evaluate_wrap(expr)[source]
function(expr)[source]

Return a coroutine from a Wolfram Language function.

The coroutine returned is attached to a given asynchronous evaluator.

restart()[source]
start()[source]
stop()[source]
terminate()[source]
class wolframclient.evaluation.base.WolframEvaluator(inputform_string_evaluation=True, **kwargs)[source]

Bases: wolframclient.evaluation.base.WolframEvaluatorBase

Synchronous evaluator abstract class.

evaluate(expr)[source]

Evaluate a given Wolfram Language expression.

evaluate_future(expr)[source]

Evaluate a given Wolfram Language expression asynchronously.

Return a Future object.

evaluate_many(expr_list)[source]

Evaluate a given list of Wolfram Language expressions.

The list is provided as an iterable object.

evaluate_wrap(expr)[source]

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

evaluate_wrap_future(expr)[source]

Asynchronously call evaluate_wrap.

Return a Future object.

function(expr)[source]

Return a Python function from a Wolfram Language function expr.

The object returned can be applied on arguments as any other Python function and is evaluated using the underlying Wolfram evaluator.

function_future(expr)[source]

Return a Python function from a Wolfram Language function expr, that evaluates asynchronously, returning a future object.

restart()[source]

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

start()[source]

Start the evaluator.

Once this function is called, the evaluator must be ready to evaluate incoming expressions.

stop()[source]

Gracefully stop the evaluator. Try to stop the evaluator but wait for the current evaluation to finish first.

terminate()[source]

Immediately stop the evaluator, which will kill the running jobs, resulting in cancelled evaluations.

class wolframclient.evaluation.base.WolframEvaluatorBase(inputform_string_evaluation=True, **kwargs)[source]

Bases: object

All evaluators should inherit from this base class.

string_as_inputform specifies if strings should be treated
as input form strings and wrapped into wlexpr()
duplicate()[source]

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

normalize_input(expr)[source]

Normalize a given Python object representing an expr to as object as expected by evaluators.

started
stopped = True

wolframclient.evaluation.pool module

class wolframclient.evaluation.pool.WolframEvaluatorPool(async_evaluators=None, poolsize=4, load_factor=0, loop=None, async_language_session_class=<class 'wolframclient.evaluation.kernel.asyncsession.WolframLanguageAsyncSession'>, **kwargs)[source]

Bases: wolframclient.evaluation.base.WolframAsyncEvaluator

A pool of kernels to dispatch one-shot evaluations asynchronously.

Evaluators can be specified in various ways: as a string representing the path to a local kernel, a WolframCloudAsyncSession or an instance of a WolframLanguageAsyncSession. More than one evaluator specification can be provided in the form of an iterable object, yielding the abovementioned specification. If the number of evaluators is less than the requested pool size (poolsize), elements are duplicated until the requested number of evaluators is reached.

Create a pool from a Wolfram kernel default location:

async with WolframEvaluatorPool() as pool:
    await pool.evaluate('$InstallationDirectory')

Create a pool from a specific Wolfram kernel:

async with WolframEvaluatorPool('/path/to/local/kernel') as pool:
    await pool.evaluate('1+1')

Create a pool from a cloud evaluator:

cloud_session = WolframCloudAsyncSession(credentials=myCredentials)
async with WolframEvaluatorPool(cloud_session) as pool:
    await pool.evaluate('$MachineName')

Create a pool from a list of specifications:

evaluators = [
    WolframCloudAsyncSession(credentials=myCredentials),
    '/path/to/local/kernel'
    ]
async with WolframEvaluatorPool(evaluators) as pool:
    await pool.evaluate('$MachineName')

Set poolsize to the number of kernel instances. The requested size may not be reached due to licencing restrictions.

Set load_factor to specify how many workloads are queued per kernel before a new evaluation becomes a blocking operation. Values below or equal to 0 mean an infinite queue size.

Set loop to the event loop to use.

kwargs are passed to WolframLanguageAsyncSession during initialization.

ensure_started()[source]
evaluate(expr, **kwargs)[source]
evaluate_all(iterable)[source]
evaluate_wrap(expr, **kwargs)[source]
evaluate_wxf(expr, **kwargs)[source]
start()[source]

Start a pool of kernels and wait for at least one of them to be ready for evaluation.

This method is a coroutine. If not all the kernels were able to start, it fails and terminates the pool.

started
stop()[source]
terminate()[source]
wolframclient.evaluation.pool.parallel_evaluate(expressions, evaluator_spec=None, max_evaluators=4, loop=None)[source]

Start a kernel pool and evaluate the expressions in parallel.

The pool is created with the value of evaluator_spec. The pool is automatically stopped when it is no longer needed. The expressions are evaluated and returned in order.

Note that each evaluation should be independent and not rely on any previous one. There is no guarantee that two given expressions evaluate on the same kernel.

wolframclient.evaluation.result module

class wolframclient.evaluation.result.WolframResult(result=None, failure=None)[source]

Bases: wolframclient.evaluation.result.WolframResultBase

The most generic result object.

The actual result is returned via the method get(). If the result is a success, the field result is returned; otherwise, failure is returned and most likely contains an error message.

get()[source]

Return the result or raise an exception based on the success status.

class wolframclient.evaluation.result.WolframAPIResponseBuilder[source]

Bases: object

Map error code to handler building the appropriate WolframAPIResponse

async_response_mapper = {200: <class 'wolframclient.evaluation.result.WolframAPIResponse200Async'>, 301: <class 'wolframclient.evaluation.result.WolframAPIResponse301Async'>, 302: <class 'wolframclient.evaluation.result.WolframAPIResponse302Async'>, 400: <class 'wolframclient.evaluation.result.WolframAPIResponse400Async'>, 401: <class 'wolframclient.evaluation.result.WolframAPIResponse401Async'>, 404: <class 'wolframclient.evaluation.result.WolframAPIResponse404Async'>, 500: <class 'wolframclient.evaluation.result.WolframAPIResponse500Async'>}
static build(response, decoder=None)[source]
static map(status_code, response_class)[source]
response_mapper = {200: <class 'wolframclient.evaluation.result.WolframAPIResponse200'>, 301: <class 'wolframclient.evaluation.result.WolframAPIResponse301'>, 302: <class 'wolframclient.evaluation.result.WolframAPIResponse302'>, 400: <class 'wolframclient.evaluation.result.WolframAPIResponse400'>, 401: <class 'wolframclient.evaluation.result.WolframAPIResponse401'>, 404: <class 'wolframclient.evaluation.result.WolframAPIResponse404'>, 500: <class 'wolframclient.evaluation.result.WolframAPIResponse500'>}
class wolframclient.evaluation.result.WolframAPIResponse(response, decoder=None)[source]

Bases: wolframclient.evaluation.result.WolframResult

A generic API response.

This class is lazily constructed when the response body becomes available.

A decoder is inferred from the content type. Currently JSON and WXF formats are supported.

build()[source]
failure()[source]
get()[source]

Return the result or raise an exception based on the success status.

class wolframclient.evaluation.result.WolframCloudEvaluationResponse(response)[source]

Bases: wolframclient.evaluation.result.WolframEvaluationResultBase

Result object associated with cloud kernel evaluation.

The response body associated to this type of result is encoded. Other fields provide additional information. The HTTP response object is stored as http_response and when HTTP error occurred it is stored in request_error.

build()[source]
get(silent=False)[source]

Return the result or raise an exception.

silent can be set to False to log all messages with warning severity.

class wolframclient.evaluation.result.WolframCloudEvaluationWXFResponse(response)[source]

Bases: wolframclient.evaluation.result.WolframCloudEvaluationResponse

Result object associated with cloud evaluation request WXF encoded.

parse_response()[source]

Parse the result input and set the attribute parsed_response.

The result input can be encoded in various formats such as WXF, JSON, etc. The parsed_response dict is expected to have keys corresponding to those of the association returned by EvaluationData.

class wolframclient.evaluation.result.WolframCloudEvaluationJSONResponse(response)[source]

Bases: wolframclient.evaluation.result.WolframCloudEvaluationResponse

Result object associated with cloud evaluation request JSON encoded.

parse_response()[source]

Parse the result input and set the attribute parsed_response.

The result input can be encoded in various formats such as WXF, JSON, etc. The parsed_response dict is expected to have keys corresponding to those of the association returned by EvaluationData.

class wolframclient.evaluation.result.WolframKernelEvaluationResult(wxf_eval_data, consumer=None)[source]

Bases: wolframclient.evaluation.result.WolframEvaluationResultBase

A Wolfram result with WXF encoded data.

Messages can be issued during a kernel evaluation. Those are stored as messages. If any message was returned by the kernel then the success status is False.

The evaluation result is lazily computed when accessing the field result. The WXF bytes holding the evaluation result are stored in wxf and thus can be later parsed with a customized parser if necessary.

All strings printed during the evaluation (e.g. Print[“something”]) are stored in property output as a list. The dict holding evaluation data is available in evaluation_data.

parse_response()[source]

Parse the result input and set the attribute parsed_response.

The result input can be encoded in various formats such as WXF, JSON, etc. The parsed_response dict is expected to have keys corresponding to those of the association returned by EvaluationData.

result
class wolframclient.evaluation.result.WolframAPIResponseAsync(response, decoder=None)[source]

Bases: wolframclient.evaluation.result.WolframAPIResponse

Asynchronous counterpart of WolframAPIResponse, awaiting for the response body.

Most of the class logic is implemented in WolframAPIResponse, except the build method which has to be a coroutine.

build()[source]
get()[source]

Return the result or raise an exception based on the success status.

This is a coroutine.

class wolframclient.evaluation.result.WolframEvaluationJSONResponseAsync(response)[source]

Bases: wolframclient.evaluation.result.WolframCloudEvaluationResponseAsync

Asynchronous result object associated with cloud evaluation request encoded with JSON.

parse_response()[source]

Parse the result input and set the attribute parsed_response.

The result input can be encoded in various formats such as WXF, JSON, etc. The parsed_response dict is expected to have keys corresponding to those of the association returned by EvaluationData.

class wolframclient.evaluation.result.WolframEvaluationWXFResponseAsync(response)[source]

Bases: wolframclient.evaluation.result.WolframCloudEvaluationResponseAsync

Asynchronous result object associated with cloud evaluation request encoded with WXF.

parse_response()[source]

Parse the result input and set the attribute parsed_response.

The result input can be encoded in various formats such as WXF, JSON, etc. The parsed_response dict is expected to have keys corresponding to those of the association returned by EvaluationData.

Module contents

class wolframclient.evaluation.SecuredAuthenticationKey(consumer_key, consumer_secret)[source]

Bases: object

Represents a Secured Authentication Key generated using the Wolfram Language function GenerateSecuredAuthenticationKey[]

It is used as an input when authenticating a cloud session.

is_xauth = False
class wolframclient.evaluation.UserIDPassword(user, password)[source]

Bases: object

Represents user credentials used to login to a cloud.

It is used as an input when authenticating a cloud session.

is_xauth = True
class wolframclient.evaluation.WolframAPICall(target, api, permission_key=None)[source]

Bases: wolframclient.evaluation.cloud.base.WolframAPICallBase

Helper class to perform an API call using a cloud session.

perform(**kwargs)[source]

Make the API call and return the result.

perform_future(**kwargs)[source]

Make the API call asynchronously and return a future object.

class wolframclient.evaluation.WolframAPICall(target, api, permission_key=None)[source]

Bases: wolframclient.evaluation.cloud.base.WolframAPICallBase

Helper class to perform an API call using a cloud session.

perform(**kwargs)[source]

Make the API call and return the result.

perform_future(**kwargs)[source]

Make the API call asynchronously and return a future object.

class wolframclient.evaluation.WolframAPICallAsync(target, api, permission_key=None)[source]

Bases: wolframclient.evaluation.cloud.base.WolframAPICallBase

Perform an API call using an asynchronous cloud session.

perform(**kwargs)[source]

Make the API call and return the result.

class wolframclient.evaluation.WolframAPIResponse(response, decoder=None)[source]

Bases: wolframclient.evaluation.result.WolframResult

A generic API response.

This class is lazily constructed when the response body becomes available.

A decoder is inferred from the content type. Currently JSON and WXF formats are supported.

build()[source]
failure()[source]
get()[source]

Return the result or raise an exception based on the success status.

class wolframclient.evaluation.WolframAPIResponseAsync(response, decoder=None)[source]

Bases: wolframclient.evaluation.result.WolframAPIResponse

Asynchronous counterpart of WolframAPIResponse, awaiting for the response body.

Most of the class logic is implemented in WolframAPIResponse, except the build method which has to be a coroutine.

build()[source]
get()[source]

Return the result or raise an exception based on the success status.

This is a coroutine.

class wolframclient.evaluation.WolframCloudAsyncSession(credentials=None, server=None, loop=None, inputform_string_evaluation=True, oauth_session_class=None, xauth_session_class=None, http_sessionclass=None, ssl_context_class=None)[source]

Bases: wolframclient.evaluation.base.WolframAsyncEvaluator

Interact with a Wolfram Cloud asynchronously using coroutines.

Asynchronous cloud operations are provided through coroutines using modules asyncio and aiohttp.

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

async with WolframCloudAsyncSession() as session:
    await session.call(...)

An event loop can be explicitly passed using the named parameter loop; otherwise, the one returned by get_event_loop() is used. The initialization options of the class WolframCloudSession are also supported by this class.

anonymous()[source]
authorized()[source]
call(api, input_parameters={}, files={}, target_format='wl', permissions_key=None, **kwargv)[source]

Call a given API using the provided input parameters.

api can be a string url or a tuple (username, api name). The username is generally the Wolfram Language symbol $UserName. The API name can be a UUID or a relative path, e.g. myapi/foo/bar.

The input parameters are provided as a dictionary with string keys being the name of the parameters associated to their value.

Files are passed in a dictionary. Values can have multiple forms:

{'parameter name': file_pointer}

It is possible to explicitly specify a filename and a content type:

{'parameter name': ('filename', file_pointer, 'content-type')}

Bytes can also be passed as files:

{'parameter name': ('filename', b'...binary...data...', 'content-type')}

It is possible to pass a PermissionsKey to the server alongside the query and get access to a given resource.

duplicate()[source]

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

evaluate(expr, **kwargs)[source]

Send expr to the cloud for evaluation and return the result.

expr can be a Python object serializable by export() or the string InputForm of an expression to evaluate.

evaluate_wrap(expr, **kwargs)[source]

Similar to evaluate() but return the result as a WolframEvaluationJSONResponseAsync.

start()[source]
started
stop()[source]
terminate()[source]
wolfram_api_call(api, **kwargs)[source]

Build an helper class instance to call a given API.

class wolframclient.evaluation.WolframCloudEvaluationJSONResponse(response)[source]

Bases: wolframclient.evaluation.result.WolframCloudEvaluationResponse

Result object associated with cloud evaluation request JSON encoded.

parse_response()[source]

Parse the result input and set the attribute parsed_response.

The result input can be encoded in various formats such as WXF, JSON, etc. The parsed_response dict is expected to have keys corresponding to those of the association returned by EvaluationData.

class wolframclient.evaluation.WolframCloudSession(credentials=None, server=None, inputform_string_evaluation=True, oauth_session_class=None, xauth_session_class=None, http_sessionclass=None, max_workers=4)[source]

Bases: wolframclient.evaluation.base.WolframEvaluator

Represent a session to a given cloud enabling simple API call.

This is the central class of the cloud evaluation package. It is initialized with a server instance representing a given cloud. By default, a session targets the Wolfram Public Cloud.

Most of the time it is necessary to authenticate with the server before issuing requests. A session supports two forms of authentication:

  • 2-legged oauth using a secured authentication key
  • xauth using the user ID and password

Calling an API is done through the method call(), which will return an instance of WolframAPIResponse. It is strongly advised to reuse a session to make multiple calls to mitigate the cost of initialization.

max_workers can be specified and is passed to the ThreadPoolExecutor used for future methods.

anonymous()[source]
authorized()[source]
call(api, input_parameters={}, files={}, target_format='wl', permissions_key=None, **kwargv)[source]

Call a given API using the provided input parameters.

api can be a string url or a tuple (username, api name). The username is generally the Wolfram Language symbol $UserName. The API name can be a UUID or a relative path, e.g. myapi/foo/bar.

The input parameters are provided as a dictionary with string keys being the name of the parameters associated to their value.

Files are passed in a dictionary. Values can have multiple forms:

{'parameter name': file_pointer}

It is possible to explicitly specify a filename and a content type:

{'parameter name': ('filename', file_pointer, 'content-type')}

String can also be passed as files:

{'parameter name': ('filename', '...string...data...', 'content-type')}

It is possible to pass a PermissionsKey to the server alongside the query and get access to a given resource.

call_future(api, input_parameters={}, target_format='wl', permissions_key=None, **kwargv)[source]

Call a given API asynchronously and return a Future object.

See WolframCloudSession.call() for more details about input parameters.

duplicate()[source]

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

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

Send expr to the cloud for evaluation and return the result.

expr can be a Python object serializable by export() or the string InputForm of an expression to evaluate.

evaluate_future(expr, **kwargs)[source]

Send expr to the cloud for asynchronous evaluation and return a Future object.

expr can be a Python object serializable by export() or the string InputForm of an expression to evaluate.

evaluate_wrap(expr, **kwargs)[source]

Similar to evaluate() but return the result as a WolframCloudEvaluationResponse.

evaluate_wrap_future(expr, **kwargs)[source]

Asynchronously call evaluate_wrap.

Return a Future object.

pool
start()[source]

Start the evaluator.

Once this function is called, the evaluator must be ready to evaluate incoming expressions.

started
stop()[source]

Gracefully stop the evaluator. Try to stop the evaluator but wait for the current evaluation to finish first.

terminate()[source]

Immediately stop the evaluator, which will kill the running jobs, resulting in cancelled evaluations.

wolfram_api_call(api, **kwargs)[source]

Build an helper class instance to call a given API.

class wolframclient.evaluation.WolframEvaluationJSONResponseAsync(response)[source]

Bases: wolframclient.evaluation.result.WolframCloudEvaluationResponseAsync

Asynchronous result object associated with cloud evaluation request encoded with JSON.

parse_response()[source]

Parse the result input and set the attribute parsed_response.

The result input can be encoded in various formats such as WXF, JSON, etc. The parsed_response dict is expected to have keys corresponding to those of the association returned by EvaluationData.

class wolframclient.evaluation.WolframEvaluatorPool(async_evaluators=None, poolsize=4, load_factor=0, loop=None, async_language_session_class=<class 'wolframclient.evaluation.kernel.asyncsession.WolframLanguageAsyncSession'>, **kwargs)[source]

Bases: wolframclient.evaluation.base.WolframAsyncEvaluator

A pool of kernels to dispatch one-shot evaluations asynchronously.

Evaluators can be specified in various ways: as a string representing the path to a local kernel, a WolframCloudAsyncSession or an instance of a WolframLanguageAsyncSession. More than one evaluator specification can be provided in the form of an iterable object, yielding the abovementioned specification. If the number of evaluators is less than the requested pool size (poolsize), elements are duplicated until the requested number of evaluators is reached.

Create a pool from a Wolfram kernel default location:

async with WolframEvaluatorPool() as pool:
    await pool.evaluate('$InstallationDirectory')

Create a pool from a specific Wolfram kernel:

async with WolframEvaluatorPool('/path/to/local/kernel') as pool:
    await pool.evaluate('1+1')

Create a pool from a cloud evaluator:

cloud_session = WolframCloudAsyncSession(credentials=myCredentials)
async with WolframEvaluatorPool(cloud_session) as pool:
    await pool.evaluate('$MachineName')

Create a pool from a list of specifications:

evaluators = [
    WolframCloudAsyncSession(credentials=myCredentials),
    '/path/to/local/kernel'
    ]
async with WolframEvaluatorPool(evaluators) as pool:
    await pool.evaluate('$MachineName')

Set poolsize to the number of kernel instances. The requested size may not be reached due to licencing restrictions.

Set load_factor to specify how many workloads are queued per kernel before a new evaluation becomes a blocking operation. Values below or equal to 0 mean an infinite queue size.

Set loop to the event loop to use.

kwargs are passed to WolframLanguageAsyncSession during initialization.

ensure_started()[source]
evaluate(expr, **kwargs)[source]
evaluate_all(iterable)[source]
evaluate_wrap(expr, **kwargs)[source]
evaluate_wxf(expr, **kwargs)[source]
start()[source]

Start a pool of kernels and wait for at least one of them to be ready for evaluation.

This method is a coroutine. If not all the kernels were able to start, it fails and terminates the pool.

started
stop()[source]
terminate()[source]
class wolframclient.evaluation.WolframKernelEvaluationResult(wxf_eval_data, consumer=None)[source]

Bases: wolframclient.evaluation.result.WolframEvaluationResultBase

A Wolfram result with WXF encoded data.

Messages can be issued during a kernel evaluation. Those are stored as messages. If any message was returned by the kernel then the success status is False.

The evaluation result is lazily computed when accessing the field result. The WXF bytes holding the evaluation result are stored in wxf and thus can be later parsed with a customized parser if necessary.

All strings printed during the evaluation (e.g. Print[“something”]) are stored in property output as a list. The dict holding evaluation data is available in evaluation_data.

parse_response()[source]

Parse the result input and set the attribute parsed_response.

The result input can be encoded in various formats such as WXF, JSON, etc. The parsed_response dict is expected to have keys corresponding to those of the association returned by EvaluationData.

result
class wolframclient.evaluation.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.

class wolframclient.evaluation.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.WolframResult(result=None, failure=None)[source]

Bases: wolframclient.evaluation.result.WolframResultBase

The most generic result object.

The actual result is returned via the method get(). If the result is a success, the field result is returned; otherwise, failure is returned and most likely contains an error message.

get()[source]

Return the result or raise an exception based on the success status.

class wolframclient.evaluation.WolframServer(cloudbase, request_token_endpoint, access_token_endpoint, xauth_consumer_key=None, xauth_consumer_secret=None, certificate=None)[source]

Bases: object

Represents the cloud server.

Contains the authentication endpoints information, the API endpoint aka. the cloud base ($CloudBase in the Wolfram Language), and eventually the xauth consumer key and secret.

is_xauth()[source]
wolframclient.evaluation.parallel_evaluate(expressions, evaluator_spec=None, max_evaluators=4, loop=None)[source]

Start a kernel pool and evaluate the expressions in parallel.

The pool is created with the value of evaluator_spec. The pool is automatically stopped when it is no longer needed. The expressions are evaluated and returned in order.

Note that each evaluation should be independent and not rely on any previous one. There is no guarantee that two given expressions evaluate on the same kernel.