### WolframClient Setup Module Commands Source: https://reference.wolfram.com/language/WolframClientForPython/api/wolframclient.cli Documentation for the setup module within the WolframClient CLI. This covers the Command class for setup operations and the 'dependencies' attribute and function, which lists or retrieves required packages. ```APIDOC wolframclient.cli.commands.setup.Command Bases: SimpleCommand Run test suites from the tests modules. A list of patterns can be provided to specify the tests to run. dependencies List of dependencies required for setup: ('pytz', 'aiohttp', 'numpy', 'oauthlib', 'pandas', 'pillow', 'pyzmq', 'requests', 'unittest-xml-reporting', 'certifi>=2017.4.17'). wolframclient.cli.commands.setup.dependencies() Retrieves the list of dependencies for the setup process. ``` -------------------------------- ### Install Wolfram Client Library Source: https://reference.wolfram.com/language/WolframClientForPython/index Installs the Wolfram Client Library for Python using pip. ```bash $ pip ``` -------------------------------- ### Start an Authenticated Cloud Session Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/toc Shows how to start an authenticated session with the Wolfram Cloud using a secured authentication key. ```python from wolframclient.evaluation import WolframCloudSession # Assumes you have generated a secured authentication key # The key is typically stored in ~/.WolframLanguage/security/publickeys/ cloud_session = WolframCloudSession() print("Authenticated cloud session started.") # Evaluate an expression in the cloud result = cloud_session.evaluate('CloudDeploy[Function[{x}, x^2], "MySquareFunction"]') print(result) cloud_session.terminate() ``` -------------------------------- ### Install Wolfram Client for Python using pip Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/toc This snippet shows the recommended method for installing the Wolfram Client for Python using pip, the standard package installer for Python. ```bash pip install wolframclient ``` -------------------------------- ### Install Wolfram Client Library using Git Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/install Installs the Wolfram Client Library for Python from its GitHub repository. This method is suitable for developers who need the full source code. ```bash git clone https://github.com/WolframResearch/WolframClientForPython.git cd WolframClientForPython pip install . ``` -------------------------------- ### Start External Wolfram Kernel Evaluation Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/cli/commands/start_externalevaluate This Python code defines a command to start an external Wolfram Language kernel evaluation. It sets environment variables for Wolfram installation and kernel version, checks for the pyzmq dependency, and starts the ZMQ loop for communication. It includes argument parsing for port, installpath, and kernelversion. ```python from__future__import absolute_import, print_function, unicode_literals importos importsys fromwolframclient.cli.utilsimport SimpleCommand fromwolframclient.utils.apiimport externalevaluate as ev fromwolframclient.utils.apiimport zmq classCommand(SimpleCommand): dependencies = () defadd_arguments(self, parser): parser.add_argument("--port", dest="port", default=None) parser.add_argument("--installpath", dest="installpath", default=None) parser.add_argument("--kernelversion", dest="kernelversion", default=None) defhandle(self, port=None, installpath=None, kernelversion=None, **opts): for key, value in ( ("WOLFRAM_INSTALLATION_DIRECTORY", installpath), ("WOLFRAM_KERNEL_VERSION", kernelversion), ): if value: os.environ[key] = value try: zmq.Context except ImportError as e: print( 'Error importing zmq: {}. Please install zmq by running:\nExternalEvaluate[{{"Shell", "Target" :> $SystemShell}}, "{}" -> {{'-m', 'pip', 'install', 'pyzmq', '--user', '--no-input'}}]'.format( e, sys.executable ), file=sys.stderr, ) sys.stderr.flush() sys.exit(1) ev.start_zmq_loop(port=port) ``` -------------------------------- ### Start ZMQ Instance Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/externalevaluate Starts a ZMQ instance by creating a PAIR socket and binding it to a specified or random port on localhost. It optionally writes the bound endpoint to stdout. ```python def start_zmq_instance(port=None, write_to_stdout=True, **opts): # make a reply socket sock = zmq.Context.instance().socket(zmq.PAIR) # now bind to a open port on localhost if port: sock.bind("tcp://127.0.0.1:%s" % port) else: sock.bind_to_random_port("tcp://127.0.0.1") if write_to_stdout: sys.stdout.write(force_text(sock.getsockopt(zmq.LAST_ENDPOINT))) sys.stdout.write(os.linesep) # writes \n sys.stdout.flush() return sock ``` -------------------------------- ### Wolfram Client Python Setup Dependencies Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/cli/commands/setup This Python code defines a function `dependencies` that yields a list of required Python packages for the Wolfram Client Library setup. It conditionally includes packages like `aiohttp`, `numpy`, and `pandas` for non-Python 2 environments. ```python from__future__import absolute_import, print_function, unicode_literals fromwolframclient.cli.utilsimport SimpleCommand fromwolframclient.utilsimport six fromwolframclient.utils.decoratorsimport to_tuple @to_tuple defdependencies(): yield "pytz" if not six.PY2: yield "aiohttp" yield "numpy" yield "oauthlib" yield "pandas" yield "pillow" yield "pyzmq" yield "requests" yield "unittest-xml-reporting" yield "certifi>=2017.4.17" classCommand(SimpleCommand): """Run test suites from the tests modules. A list of patterns can be provided to specify the tests to run. """ dependencies = dependencies() ``` -------------------------------- ### Wolfram Language Session Management: Manual Start and Terminate Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Illustrates how to manually start and terminate a Wolfram Language session, including checking its status. ```Python >>> session = WolframLanguageSession() >>> session.start() >>> session.started True >>> session.terminate() ``` -------------------------------- ### Setup Logging to File (Python 2) Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/logger Configures basic Python logging to a specified file with a predefined format. This version is for Python 2 environments. ```python from__future__import absolute_import, print_function, unicode_literals importlogging fromwolframclient.utilsimport six fromwolframclient.utils.encodingimport force_text if six.PY2: defsetup_logging_to_file(path, level=None): logging.basicConfig( filename=path, filemode="a", format="%(asctime)s, %(name)s%(levelname)s%(message)s", level=(level is not None) or logging.INFO, ) ``` -------------------------------- ### Install Wolfram Client Library using pip Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/install Installs the latest stable version of the Wolfram Client Library for Python from PyPI using pip. This is the recommended method for most users. ```bash pip install wolframclient ``` -------------------------------- ### Session Management Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/toc Demonstrates basic session management, including starting and terminating a Wolfram Language session. ```python from wolframclient.evaluation import WolframLanguageSession # Start a session session = WolframLanguageSession() print("Session started.") # Perform some operations... # Terminate the session session.terminate() print("Session terminated.") ``` -------------------------------- ### Initialize Wolfram Language Session Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Demonstrates how to import and initialize a WolframLanguageSession, with examples for default paths and specific kernel executable paths on different operating systems. ```python from wolframclient.evaluation import WolframLanguageSession ``` ```python session = WolframLanguageSession() ``` ```python session = WolframLanguageSession('/Applications/Wolfram Desktop.app/Contents/MacOS/WolframKernel') ``` ```python session = WolframLanguageSession('C:\\Program Files\\Wolfram Research\\Wolfram Desktop\\11.3\\WolframKernel.exe') ``` ```python session = WolframLanguageSession('/usr/local/Wolfram/Desktop/11.3/Executables/WolframKernel') ``` -------------------------------- ### Wolfram Client Library for Python Overview Source: https://reference.wolfram.com/language/WolframClientForPython/api/wolframclient.evaluation Provides an overview of the Wolfram Client Library for Python, including installation prerequisites, basic usage patterns like expression representation and evaluation, and advanced topics such as local kernel evaluation and extending serialization. ```Python from wolframclient.evaluation import WolframLanguageSession from wolframclient.language import wl # Example of basic expression evaluation with WolframLanguageSession() as session: expr = wl.Table(wl.Times(2, 'x'), ['x', 1, 5]) result = session.evaluate(expr) print(result) # Example of local kernel evaluation setup # session = WolframLanguageSession('/path/to/WolframKernel') # result = session.evaluate(wl.Integrate('x^2', 'x')) # print(result) ``` -------------------------------- ### Setup Logging to File (Python 3) Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/logger Configures basic Python logging to a specified file with a predefined format. This version is for Python 3 environments and uses FileHandler with UTF-8 encoding. ```python else: [docs][](https://reference.wolfram.com/language/WolframClientForPython/api/wolframclient.utils.html#wolframclient.utils.logger.setup_logging_to_file) defsetup_logging_to_file(path, level=None): """Setup a basic Python logging configuration to a given file.""" logging.basicConfig( format="%(asctime)s, %(name)s%(levelname)s%(message)s", handlers=[logging.FileHandler(path, mode="a", encoding="utf-8")], level=(level is not None) or logging.INFO, ) ``` -------------------------------- ### Wolfram Client for Python Usage Documentation Source: https://reference.wolfram.com/language/WolframClientForPython/py-modindex Provides links to documentation pages covering installation, basic usage (expression representation, evaluation, cloud interactions, serialization), and advanced usage of the Wolfram Client for Python. ```APIDOC Overview: https://reference.wolfram.com/language/WolframClientForPython/index.html Installation and Prerequisites: Prerequisites: https://reference.wolfram.com/language/WolframClientForPython/docpages/install.html#prerequisites Installation: https://reference.wolfram.com/language/WolframClientForPython/docpages/install.html#installation Basic Usage: Expression Representation: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages.html#expression-representation Expression Evaluation: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages.html#expression-evaluation Wolfram Cloud Interactions: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages.html#wolfram-cloud-interactions Serialization: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages.html#serialization Advanced Usage: https://reference.wolfram.com/language/WolframClientForPython/docpages/advanced_usages.html ``` -------------------------------- ### Start Authenticated Cloud Session Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Establishes an authenticated session with the Wolfram Cloud using previously generated credentials. This session is required for cloud evaluations. ```python from wolframclient.evaluation import SecuredAuthenticationKey, WolframCloudSession ``` ```python sak = SecuredAuthenticationKey( 'T2ghIEhpISDinIw=', 'VGhhdCdzIE1ZIHNlY3JldCE=') session = WolframCloudSession(credentials=sak) session.start() session.authorized() # True ``` -------------------------------- ### Start ZMQ Loop Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/externalevaluate Starts the ZMQ event loop, processing messages until a message limit is reached. It sets up a consumer, handler, and socket writer, and logs side effects. ```python def start_zmq_loop( message_limit=float("inf"), exception_class=None, routes_registry={}, ): consumer = ExternalEvaluateConsumer(routes_registry=routes_registry) handler = to_wl( exception_class=exception_class, object_processor=lambda serializer, instance: serializer.encode( to_external_object(instance, consumer.objects_registry) ), target_format="wxf", )(handle_message) socket = start_zmq_instance(**opts) stream = SocketWriter(socket) messages = 0 class SideEffectSender(logging.Handler): def emit(self, record): stream.send_side_effect(record.msg) side_effect_logger.addHandler(SideEffectSender()) # now sit in a while loop, evaluating input while messages < message_limit: stream.write(handler(socket, consumer=consumer)) messages += 1 ``` -------------------------------- ### WXFParser Initialization and Token Generation - Python Source: https://reference.wolfram.com/language/WolframClientForPython/api/wolframclient.deserializers Demonstrates how to initialize the WXFParser with a file-like object and iterate through the generated WXF tokens. This is a low-level example for parsing WXF data. ```python with open('/tmp/data.wxf', 'rb') as fp: parser = WXFParser(fp) gen = parser.tokens() print(next(gen)) ``` -------------------------------- ### Navigate to Wolfram Client for Python Directory Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/install This snippet shows how to change the current directory to the Wolfram Client for Python installation path. This is a common step before running commands or scripts related to the library. ```bash cd ``` -------------------------------- ### Parallel Evaluation Example Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/advanced_usages Demonstrates parallel evaluation of expressions that return the kernel process ID after a delay. It shows how to build a list of expressions and then evaluate them in parallel. ```python expressions = ['Pause[1]; $ProcessID' for _ in range(10)] parallel_evaluate(expressions) ``` -------------------------------- ### WolframClientForPython start_externalevaluate Command API Source: https://reference.wolfram.com/language/WolframClientForPython/api/wolframclient.cli Documentation for the Command class within the start_externalevaluate module. This class is responsible for handling the start external evaluate functionality. ```APIDOC wolframclient.cli.commands.start_externalevaluate.Command: Bases: wolframclient.cli.utils.SimpleCommand add_arguments(parser): Adds arguments to the parser for this command. dependencies = () handle(port=None, installpath=None, kernelversion=None, **opts): Handles the execution of the start external evaluate command with specified options. ``` -------------------------------- ### WolframClientForPython Utility and Exception Methods Source: https://reference.wolfram.com/language/WolframClientForPython/genindex API documentation for utility functions and methods within WolframClientForPython, including data structure manipulation, logging setup, and exception handling. ```APIDOC externalevaluate.Set() - Represents a Set operation. WolframLanguageException.set_traceback() - Sets the traceback for a WolframLanguageException. WolframClientForPython.language.exceptions.WolframLanguageException.set_traceback() - Sets the traceback for a WolframLanguageException. externalevaluate.SetAttribute() - Represents a SetAttribute operation. immutabledict.setdefault() - Returns the value of a key, or sets it to a default if not present. externalevaluate.SetItem() - Represents a SetItem operation. Settings (class in wolframclient.utils.datastructures) - A class for managing settings. wolframclient.utils.logger.setup_logging_to_file() - Sets up logging to a file. WolframLanguageException.show_traceback() - Displays the traceback for a WolframLanguageException. WolframClientForPython.language.exceptions.WolframLanguageException.show_traceback() - Displays the traceback for a WolframLanguageException. SimpleCommand (class in wolframclient.cli.utils) - Represents a simple command in the CLI. ``` -------------------------------- ### Deploy API to Get Image Dimensions Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Shows how to deploy a Wolfram Language API that accepts an image and returns its dimensions as a JSON array using ImageDimensions. ```Wolfram Language CloudDeploy[ APIFunction[{"image"->"Image"}, ImageDimensions[#image]&, "JSON" ], CloudObject["api/private/imagedimensions"] ] ``` -------------------------------- ### Get Installed Modules Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/require Retrieves a dictionary of installed Python modules and their versions using pip. ```python from __future__ import absolute_import, print_function, unicode_literals from functools import wraps from wolframclient.utils.api import pip def installed_modules(): return {i.key: i.version for i in pip.get_installed_distributions()} ``` -------------------------------- ### Get Wolfram Kernel Installation Version Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/environment Retrieves the installed Wolfram Kernel version from the environment variable WOLFRAM_KERNEL_VERSION. If the variable is not set, it defaults to 12.0. ```python from__future__import absolute_import, print_function, unicode_literals fromwolframclient.utilsimport six fromwolframclient.utils.apiimport os definstallation_version(): v = os.environ.get("WOLFRAM_KERNEL_VERSION", None) if v: return float(v) return 12.0 ``` -------------------------------- ### Combined Python and Kernel Logging Example Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/advanced_usages Illustrates controlling log levels at both the Python and Wolfram Language kernel levels. It starts a session with kernel logging enabled at INFO level, sends messages from the kernel, and then disables kernel logging. ```python import logging from wolframclient.evaluation import WolframLanguageSession logging.basicConfig(level=logging.INFO) with WolframLanguageSession(kernel_loglevel=logging.INFO) as session: session.evaluate('ClientLibrary`info["ON -- Example message printed from the kernel \nwith log level INFO --"]') session.evaluate('ClientLibrary`debug["OFF -- Debug message."]') session.evaluate('ClientLibrary`DisableKernelLogging[]') session.evaluate('ClientLibrary`fatal["OFF -- Fatal message. Not printed"]') session.evaluate('ClientLibrary`info["OFF -- End of kernel evaluation. Not printed"]') ``` -------------------------------- ### Install Missing Modules Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/require Installs any missing Python modules required by the application. It handles installation within virtual environments and user-specific installations. ```python def require_module(*modules): commands = list(missing_requirements(*modules)) if commands: print("Update in progress: pip install %s --user" % " ".join(commands)) if pip.running_under_virtualenv(): pip.main(["install", *commands]) else: pip.main(["install", "--user", *commands]) ``` -------------------------------- ### Get Length of an Object Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/externalevaluate Returns the length (number of items) of an object. This is a generic way to get the size of collections or sequences. ```python from wolframclient.utils import externalevaluate # Example usage: my_list = [10, 20, 30, 40] consumer = None # Placeholder for consumer object length = externalevaluate.Len(consumer, my_list) print(length) # Output: 4 ``` -------------------------------- ### System and Global Context Factories Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/public_api Demonstrates the use of pre-instantiated factories for 'System' and 'Global' contexts for easy symbol representation. ```Python from wolframclient.language import System, Global # Represent a symbol in the System context print(System.ImageIdentify) # Represent a symbol in the Global context print(Global.mySymbol) # Represent a function call in the Global context print(Global.myFunction('foo')) ``` -------------------------------- ### Decorator for Module Requirements Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/require A decorator factory that ensures specified modules are installed before executing a function. It wraps the target function, performing the module check and installation if necessary. ```python def require(*modules): def outer(func): @wraps(func) def inner(*args, **kw): require_module(*modules) return func(*args, **kw) return inner return outer ``` -------------------------------- ### Call Wolfram API with Parameters Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Demonstrates how to initiate a WolframAPICall, set input parameters, perform the call, and retrieve the result. Requires an authenticated session and a deployed API. ```Python from wolframclient.evaluation import WolframAPICall # Assuming 'session' is an authenticated Wolfram Language session call = WolframAPICall(session, ('MyWolframID', 'api/private/xsquared')) call.set_parameter('x', 4) result = call.perform() print(result.get()) ``` -------------------------------- ### Get Length - WolframClientForPython Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/serializers/wxf Determines the length of an iterable. If length is provided, it's used directly. Otherwise, it attempts to get the length using safe_len or by converting to a tuple. ```python def get_length(iterable, length=None): if length is not None: return iterable, length length = safe_len(iterable) if length is not None: return iterable, length iterable = tuple(iterable) return iterable, len(iterable) ``` -------------------------------- ### Benchmark Report Generation Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/cli/commands/benchmark Generates a comprehensive benchmark report. It sets up the temporary directory, prepares benchmark data, runs initial deserialization for lazy loading, and then prints formatted tables for binary deserialization times across different complexities and export formats. ```python def report(self): path = tempfile.gettempdir() benchmarks = [(c, self.expression_handler(c)) for c in self.complexity] self.table_line("dumping results in %s" % path) self.table_line() # running export to do all lazy loadings binary_deserialize(export(1, target_format="wxf")) self.table_line("* Binary deserialize") self.table_line() self.table_line( "Memory", *(force_text(c).ljust(self.col_size) for c in self.complexity) ) self.table_divider(len(self.complexity) + 1) for label, opts in (("wxf", {}), ("wxf zip", {"compress": True})): self.table_line( label, *( self.formatted_time( ``` -------------------------------- ### Check for Missing Requirements Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/require Yields a list of modules that are either not installed or do not match the specified version. ```python def missing_requirements(*modules): distributions = installed_modules() for module in modules: version = None if isinstance(module, (tuple, list)): module, version = module if module not in distributions or (version and distributions[module] != version): yield version and "{}=={}".format(module, version) or module ``` -------------------------------- ### Functional Utilities Source: https://reference.wolfram.com/language/WolframClientForPython/genindex Utility functions for functional programming, including getting the first element of a sequence and flattening lists. ```APIDOC wolframclient.utils.functional.first(seq) Returns the first element of a sequence. Parameters: seq: The input sequence. Returns: The first element of the sequence. wolframclient.utils.functional.flatten(seq) Flattens a nested sequence. Parameters: seq: The sequence to flatten. Returns: A flattened sequence. ``` -------------------------------- ### Local Session Initialization and Expression Evaluation Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/toc Demonstrates how to initialize a local Wolfram Language session and evaluate expressions using the Wolfram Client for Python. It covers basic evaluation and options. ```python from wolframclient.evaluation import WolframLanguageSession # Initialize a local session session = WolframLanguageSession() # Evaluate an expression result = session.evaluate('2 + 2') print(result) # Evaluate an expression with options result_with_options = session.evaluate('Plot[Sin[x], {x, 0, 2 Pi}]', options={'ImageSize': (300, 200)}) print(result_with_options) session.terminate() ``` -------------------------------- ### Get Boolean Value of an Object Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/externalevaluate Returns the boolean representation of an object. This is useful for conditional checks in external evaluations. ```python from wolframclient.utils import externalevaluate # Example usage: consumer = None # Placeholder for consumer object non_empty_list = [1] empty_list = [] print(f"Boolean of non-empty list: {externalevaluate.Bool(consumer, non_empty_list)}") # Output: True print(f"Boolean of empty list: {externalevaluate.Bool(consumer, empty_list)}") # Output: False ``` -------------------------------- ### Query Wolfram|Alpha Directly Source: https://reference.wolfram.com/language/WolframClientForPython/index Queries Wolfram|Alpha directly from Python to get specific information, like the number of moons of Saturn. ```python >>> session.evaluate(wl.WolframAlpha("number of moons of Saturn", "Result")) 62 ``` -------------------------------- ### Import WXF File in Wolfram Desktop Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Demonstrates how to import a WXF file using Wolfram Desktop. ```Wolfram Language Import("/path/to/file.wxf") ``` -------------------------------- ### Get First Element of an Iterable Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/functional Retrieves the first element from an iterable. If the iterable is empty, it returns a default value. ```python from wolframclient.utils.functional import first my_list = [1, 2, 3] print(first(my_list)) # Output: 1 empty_list = [] print(first(empty_list, default=0)) # Output: 0 ``` -------------------------------- ### Get Attribute of an Object Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/externalevaluate Retrieves an attribute from an object, supporting nested attribute access. Used for accessing properties of external objects. ```python from wolframclient.utils import externalevaluate from wolframclient.utils.iterate import iterate # Example usage: class MyClass: def __init__(self): self.nested = NestedClass() class NestedClass: def __init__(self): self.value = 42 consumer = None # Placeholder for consumer object obj = MyClass() attribute_names = ['nested', 'value'] attribute_value = externalevaluate.GetAttribute(consumer, obj, attribute_names) print(attribute_value) # Output: 42 ``` -------------------------------- ### Wolfram Client Library for Python - wolframclient.evaluation package structure Source: https://reference.wolfram.com/language/WolframClientForPython/api/wolframclient This documentation outlines the structure of the wolframclient.evaluation package, including its subpackages and modules. It provides links to detailed API documentation for each component. ```APIDOC wolframclient.evaluation package: Subpackages: - wolframclient.evaluation.cloud package - Submodules: - wolframclient.evaluation.cloud.asynccloudsession module - wolframclient.evaluation.cloud.asyncoauth module - wolframclient.evaluation.cloud.base module - wolframclient.evaluation.cloud.cloudsession module - wolframclient.evaluation.cloud.oauth module - wolframclient.evaluation.cloud.request_adapter module - wolframclient.evaluation.cloud.server module - wolframclient.evaluation.kernel package - Submodules: - wolframclient.evaluation.kernel.asyncsession module - wolframclient.evaluation.kernel.kernelcontroller module - wolframclient.evaluation.kernel.localsession module - wolframclient.evaluation.kernel.zmqsocket module Submodules: - wolframclient.evaluation.base module - wolframclient.evaluation.pool module - wolframclient.evaluation.result module ``` -------------------------------- ### WolframClient Benchmark Command Class Source: https://reference.wolfram.com/language/WolframClientForPython/api/wolframclient.cli Documentation for the Command class within the wolframclient.cli.commands.benchmark module. This class handles benchmark operations, including argument parsing, expression handling, and reporting. ```APIDOC wolframclient.cli.commands.benchmark.Command: Bases: SimpleCommand Attributes: col_size: int = 8 complexity: list[int] = [1, 2, 5, 10, 100, 1000] repetitions: int = 10 title_size: int = 14 Methods: add_arguments(parser): Adds command-line arguments to the parser for benchmark configuration. expression_handler(complexity): Handles the processing of expressions based on a given complexity level. formatted_time(function, *args, **opts): Measures and formats the execution time of a given function with its arguments and options. handle(profile, **opts): Main handler for the benchmark command, orchestrating the benchmarking process. report(): Generates and displays the benchmark report. stream_generators(path): Streams data generators from a specified path. table_divider(length): Generates a table divider string of a given length. table_line(*iterable): Formats an iterable into a table row string. ``` -------------------------------- ### Generate a Secured Authentication Key Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/toc Provides instructions on how to generate a secured authentication key for Wolfram Cloud interactions. ```bash wolframscript -activate-user ``` -------------------------------- ### Get Last Element of an Iterable Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/functional Retrieves the last element from an iterable. If the iterable is empty, it returns a default value. Note: This may not be efficient for all iterable types. ```python from wolframclient.utils.functional import last my_list = [1, 2, 3] print(last(my_list)) # Output: 3 empty_list = [] print(last(empty_list, default=0)) # Output: 0 ``` -------------------------------- ### Deploy a Wolfram Language API Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/toc Illustrates the process of deploying a Wolfram Language function as an API in the Wolfram Cloud. ```python from wolframclient.evaluation import WolframCloudSession session = WolframCloudSession() # Deploy a simple Wolfram Language function as an API api_name = 'SimpleAdder' api_code = f'CloudDeploy[Function[{{x, y}}, x + y], "{api_name}"]' result = session.evaluate(api_code) print(f'API "{api_name}" deployed. Result: {result}') session.terminate() ``` -------------------------------- ### Representing Wolfram Language Symbol Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Demonstrates how to represent a Wolfram Language symbol, such as 'Now', using the `wl` factory. ```Python wl.Now ``` -------------------------------- ### Use WolframAPICall Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/toc Demonstrates the usage of the WolframAPICall utility for interacting with Wolfram Language APIs. ```python from wolframclient.api import WolframAPICall # Example: Calling a hypothetical Wolfram Language API that returns a list api_url = 'YOUR_WOLFRAM_CLOUD_API_URL/GetData' api_caller = WolframAPICall() # Call the API without arguments result = api_caller.call(api_url) print(f'Data from API: {result}') # Call the API with specific arguments result_with_args = api_caller.call(api_url, arguments={'param1': 'value1', 'param2': 10}) print(f'Data with arguments: {result_with_args}') ``` -------------------------------- ### WolframClient for Python API Documentation Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/cli/commands/benchmark This section outlines the core functionalities and methods available in the Wolfram Client for Python library, including expression handling, evaluation, serialization, and cloud interactions. ```APIDOC wolframclient.cli.commands.benchmark.Command.handle(profile, **opts) Handles the execution of benchmark tests. If 'profile' is True, it uses cProfile to report performance metrics; otherwise, it directly calls the report method. Parameters: profile (bool): If True, enables profiling. **opts: Additional options. wolframclient.cli.commands.benchmark.Command.report() Generates and displays benchmark reports for various operations. safe_import_string_and_call(import_string, function_string, function_args, global_vars) Safely imports a module and calls a function within it. Used for dynamic execution of profiling or reporting functions. Parameters: import_string (str): The string representation of the module to import (e.g., 'cProfile.runctx'). function_string (str): The name of the function to call within the imported module. function_args (dict): Arguments to pass to the function. global_vars (dict): Global variables to be available during function execution. export(expr, target_format="wxf", **opts) Exports a Wolfram Language expression to a specified format. Supports formats like 'wxf' with optional compression. Parameters: expr: The Wolfram Language expression to export. target_format (str): The desired output format (default is 'wxf'). **opts: Additional options for the export process, such as compression settings. binary_deserialize(data, **opts) Deserializes binary data into a Wolfram Language expression. Parameters: data: The binary data to deserialize. **opts: Additional options for deserialization. stream_generators(path) Provides generators for streaming data, likely used in conjunction with export operations. Parameters: path: Path information relevant to the stream generation. formatted_time(func, *args, **kwargs) A utility function to time the execution of a given function and format the output. Parameters: func: The function to execute and time. *args: Positional arguments to pass to the function. **kwargs: Keyword arguments to pass to the function. table_line(*args) Writes a line of data to a table format, used for displaying benchmark results. table_divider(num_columns) Writes a table divider line, used to structure the output table. complexity Attribute representing the complexity levels for benchmarking. col_size Attribute representing the column size for formatted output. force_text(obj) Ensures an object is converted to its text representation. ``` -------------------------------- ### Extending Serialization: Writing an Encoder Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/serializers/encoder Guides on how to extend the serialization capabilities of the Wolfram Client for Python by writing custom encoders for specific Python data types. ```Python # Example structure for a custom encoder # from wolframclient.serializers.encoder import WolframFunctionEncoder # from wolframclient.language import wl # class CustomObjectEncoder(WolframFunctionEncoder): # def __call__(self, obj, serializer): # if isinstance(obj, MyCustomClass): # return wl.MyWolframFunction(obj.attribute1, obj.attribute2) # return super().__call__(obj, serializer) # To use the custom encoder: # serializer = WolframSerializer(encoders={'MyCustomClass': CustomObjectEncoder()}) ``` -------------------------------- ### One-Shot Cloud Evaluation Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/toc Demonstrates how to perform a single evaluation in the Wolfram Cloud without establishing a persistent session. ```python from wolframclient.evaluation import WolframCloudSession # Evaluate an expression directly in the cloud result = WolframCloudSession().evaluate('1 + 1') print(result) ``` -------------------------------- ### Serializer Methods Source: https://reference.wolfram.com/language/WolframClientForPython/genindex Defines methods for generating byte representations of data using different serializer formats like WL and WXF. Includes methods for getting length and properties. ```python from wolframclient.serializers.base import FormatSerializer from wolframclient.serializers.wl import WLSerializer from wolframclient.serializers.wxf import WXFSerializer, get_length from wolframclient.serializers.encoder import Encoder # Example usage (conceptual): # serializer = WLSerializer() # byte_data = serializer.generate_bytes(data) # length = get_length(data) # property = encoder.get_property(key) ``` -------------------------------- ### Wolfram Client for Python CLI Dispatch Methods Source: https://reference.wolfram.com/language/WolframClientForPython/genindex Documentation for methods related to command dispatching in the CLI, including subcommand argument retrieval and listing available subcommands. ```APIDOC DispatchCommand.subcommand_args(self, subcommand): Description: Retrieves arguments for a specific subcommand. Parameters: subcommand: The name of the subcommand. Returns: A list of argument specifications. DispatchCommand.subcommands(self): Description: Returns a list of available subcommands. Returns: A dictionary mapping subcommand names to their configurations. ``` -------------------------------- ### Get Item from an Object Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/externalevaluate Retrieves an item from an object using key-based access (like dictionaries or lists), supporting nested access. Used for accessing elements within collections. ```python from wolframclient.utils import externalevaluate from wolframclient.utils.iterate import iterate # Example usage: my_dict = {'a': {'b': 100}} consumer = None # Placeholder for consumer object item_keys = ['a', 'b'] item_value = externalevaluate.GetItem(consumer, my_dict, item_keys) print(item_value) # Output: 100 ``` -------------------------------- ### Representing Wolfram Language Function Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Shows how to construct a Wolfram Language function call, like `Select[PrimeQ, Range[5]]`, using the `wl` factory. ```Python wl.Select(wl.PrimeQ, wl.Range(5)) ``` -------------------------------- ### Get Pandas Series Encoder from Index Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/serializers/encoders/pandas Determines the appropriate encoder for a pandas Series based on its index type, a flag for using time series, and a specified form. ```python defget_series_encoder_from_index(index, use_ts, form): ``` -------------------------------- ### Create Pandas DataFrame Source: https://reference.wolfram.com/language/WolframClientForPython/index Demonstrates creating a Pandas DataFrame, which can be used with the Wolfram Client Library. ```python >>> import pandas >>> df = pandas.DataFrame({'A': [1, 2], 'B': [11, 12]}, index=['id1', 'id2']) >>> df A B id1 1 11 id2 2 12 ``` -------------------------------- ### Dispatch Class API Documentation Source: https://reference.wolfram.com/language/WolframClientForPython/_modules/wolframclient/utils/dispatch API documentation for the Dispatch class, covering its initialization, registration of functions with type annotations, updating mappings, and unregistering implementations. ```APIDOC class Dispatch: """A method dispatcher class allowing for multiple implementations of a function. Each implementation is associated to a specific input type. Implementations are registered with the annotation :meth:`~wolframclient.utils.dispatch.Dispatch.dispatch`. The Dispatch class is callable, it behaves as a function that uses the implementation corresponding to the input parameter. When a type is a subtype, the type and its parents are checked in the order given by :data:`__mro__` (method resolution order). *Example:* method :meth:`~wolframclient.utils.dispatch.Dispatch.resolve` applied to an instance of :class:`collections.OrderedDict`, check for the first implementation to match with :class:`collections.OrderedDict`, then with :class:`dict`, and ultimately to :data:`object`. Once the mapping is determined, it is cached for later use. """ def __init__(self): """Initializes the Dispatch object and clears any existing mappings.""" self.clear() def dispatch(self, *args, **opts): """Annotate a function and map it to a given set of type(s). Declare an implementation to use on :data:`bytearray` input:: @dispatcher.dispatch(bytearray) def my_func(...) The default implementation is associated with :data:`object`. Set a default:: @dispatcher.dispatch(object) def my_default_func(...) A tuple can be used as input to associate more than one type with a function. Declare a function used for both :data:`bytes` and :data:`bytearray`:: @dispatcher.dispatch((bytes, bytearray)) def my_func(...) Implementation must be unique. By default, registering the same combination of types will raise an error. Set `replace_existing` to :data:`True` to update the current mapping. Or, set `keep_existing` to :data:`True` to ignore duplicate registration and keep the existing mapping. """ def register(func): return self.register(func, *args, **opts) return register def update(self, dispatch, **opts): """Update current mapping with the one from `dispatch`. `dispatch` can be a Dispatch instance or a :class:`dict`. `**opts` are passed to :meth:`~wolframclient.utils.dispatch.Dispatch.register` """ if isinstance(dispatch, Dispatch): dispatchmapping = dispatch.dispatch_dict elif isinstance(dispatch, dict): dispatchmapping = dispatch else: raise ValueError("%s is not an instance of Dispatch" % dispatch) for t, function in dispatchmapping.items(): self.register(function, t, **opts) def validate_types(self, types): """Validates that the provided types are classes.""" for t in frozenset(flatten(types)): if not inspect.isclass(t): raise ValueError("%s is not a class" % t) yield t def register(self, function, types=object, keep_existing=False, replace_existing=False): """Equivalent to annotation :meth:`~wolframclient.utils.dispatch.Dispatch.dispatch` but as a function. Registers a function with a given set of types. Args: function: The function to register. types: The type(s) to associate the function with. Defaults to `object`. keep_existing: If True, ignores duplicate registrations and keeps the existing mapping. replace_existing: If True, updates the mapping for existing types. Raises: ValueError: If `keep_existing` and `replace_existing` are both True, or if a type is not a class. TypeError: If a duplicate registration occurs and `keep_existing` is False. """ if not callable(function): raise ValueError("Function %s is not callable" % function) if keep_existing and replace_existing: raise ValueError( "Option values keep_existing and replace_existing cannot be both True." ) self.clear_cache() for t in self.validate_types(types): if replace_existing: self.dispatch_dict[t] = function elif t in self.dispatch_dict: if not keep_existing: raise TypeError("Duplicated registration for input type(s): {}".format(t)) else: self.dispatch_dict[t] = function return function def unregister(self, types=object): """Remove implementations associated with types.""" self.clear_cache() for t in self.validate_types(types): try: del self.dispatch_dict[t] except KeyError: pass ``` -------------------------------- ### Representing Function with Options Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Illustrates how to represent a Wolfram Language function with options, such as `ArrayPad` with the `Padding` option. ```Python wl.ArrayPad([[0]], 1, Padding=1) ``` -------------------------------- ### Get Image Dimensions using Wolfram Language Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Loads an image using PIL and then uses the Wolfram Language to compute its dimensions, demonstrating inter-process communication and evaluation. ```Python >>> from PIL import Image >>> img = Image.open('/tmp/data.png') >>> session.evaluate(wl.ImageDimensions(img)) [360, 219] ``` -------------------------------- ### Create Parser Utility Source: https://reference.wolfram.com/language/WolframClientForPython/genindex The create_parser method from the SimpleCommand class in wolframclient.cli.utils is used for creating command-line argument parsers. ```APIDOC create_parser() - Creates an argument parser for command-line interfaces. - Part of the SimpleCommand class in wolframclient.cli.utils. ``` -------------------------------- ### WolframClient Refactor Module Commands Source: https://reference.wolfram.com/language/WolframClientForPython/api/wolframclient.cli Documentation for the refactor module within the WolframClient CLI. This includes the Command class, its methods for handling operations, managing modules, and running processes, as well as a utility function for waiting on process completion. ```APIDOC wolframclient.cli.commands.refactor.Command Bases: SimpleCommand handle(**opts) Handles refactoring operations. modules List of modules associated with refactoring. run(pre, *args) Executes the refactoring process. wolframclient.cli.commands.refactor.wait_for_process(processes, raise_errors=True, show_output=False) Waits for a list of processes to complete. Parameters: processes: A list of process objects to wait for. raise_errors: If True, raises an exception if any process fails. show_output: If True, displays the output of the processes. ``` -------------------------------- ### Create Bar Chart and Export to PNG Source: https://reference.wolfram.com/language/WolframClientForPython/docpages/basic_usages Demonstrates creating a BarChart from Python data and exporting it to a PNG file using Wolfram Language functions via the WolframClient for Python. ```Python >>> data = [.3, 2, 4, 5, 5.5] >>> graphic = wl.BarChart(data) >>> path = "/tmp/data.png" >>> png_export = wl.Export(path, graphic, "PNG") >>> session.evaluate(png_export) '/tmp/data.png' ```