### Start Broker Command (Bash) Source: https://context7.com/zincware/aserpc/llms.txt Starts the message broker from the command line with configurable options. Supports default settings, custom frontend/backend IPC addresses, timeouts, and log levels. Can also be influenced by environment variables. No external dependencies beyond the installed 'aserpc' package. ```bash # Start broker with default settings aserpc broker # Custom configuration aserpc broker \ --frontend ipc:///tmp/aserpc/frontend.ipc \ --backend ipc:///tmp/aserpc/backend.ipc \ --timeout 30.0 \ --queue-timeout 60.0 \ --log-level DEBUG # With environment variables export ASERPC_IPC_DIR=/tmp/aserpc export ASERPC_WORKER_TIMEOUT=45.0 aserpc broker ``` -------------------------------- ### Start ASERPC Broker Source: https://github.com/zincware/aserpc/blob/main/README.md Initiates the ASERPC broker service, which manages communication between clients and workers. This is the first step in setting up a remote ASE calculation environment. ```bash aserpc broker ``` -------------------------------- ### Start Worker Command (Bash) Source: https://context7.com/zincware/aserpc/llms.txt Starts a worker process for a specific calculator type with automatic discovery. Supports specifying the calculator name, custom registry files, broker addresses, idle timeouts, heartbeats, and log levels. Can be used to start multiple workers in parallel. Requires the 'aserpc' package. ```bash # Start worker for built-in calculator aserpc worker LJ # Start worker with custom registry file aserpc worker LJ --registry tmp/registry.py:CALCULATORS # Worker with custom configuration aserpc worker mace_mp \ --broker ipc:///tmp/aserpc/backend.ipc \ --idle-timeout 600 \ --heartbeat 10.0 \ --log-level INFO # Start multiple workers in parallel aserpc worker LJ & aserpc worker LJ & aserpc worker EMT & ``` -------------------------------- ### ASERPC Calculator Entry Point (pyproject.toml) Source: https://context7.com/zincware/aserpc/llms.txt Defines the entry point for ASERPC calculators within the pyproject.toml file. This allows the 'aserpc list' command to discover and list available calculators after installation. ```toml [project.entry-points."aserpc.calculators"] mypackage = "mypackage.aserpc:get_calculators" ``` -------------------------------- ### ASERPC Calculator Registry File Example Source: https://github.com/zincware/aserpc/blob/main/README.md Defines a Python module that acts as a registry for ASE calculators. It maps calculator names to their factory classes, allowing ASERPC workers to instantiate them. ```python # tmp/registry.py from ase.calculators.lj import LennardJones # Registry: name -> calculator factory CALCULATORS = { "LJ": LennardJones, } ``` -------------------------------- ### ASERPC Command Line Usage Source: https://context7.com/zincware/aserpc/llms.txt Demonstrates basic ASERPC command-line operations after installation. This includes listing available calculators, and starting a worker for a specific calculator. ```bash # After installation, calculators are automatically available pip install mypackage aserpc list aserpc worker mace_mp ``` -------------------------------- ### ASERPC Calculator Provider Function Example Source: https://github.com/zincware/aserpc/blob/main/README.md A Python function designed to be registered as an entry point for ASERPC. It returns metadata about available calculators, including their factory modules and optional arguments, checking for dependencies like 'mace' without importing them directly. ```python # mypackage/aserpc.py import importlib.util def get_calculators() -> dict[str, dict]: """Return metadata for available calculators. Each entry is: {"factory": "module:class", "args": [...], "kwargs": {...}} Use importlib.util.find_spec() to check availability without importing. """ calcs = {} # Simple calculators (always available with ASE) calcs["LJ"] = {"factory": "ase.calculators.lj:LennardJones"} calcs["EMT"] = {"factory": "ase.calculators.emt:EMT"} # Check if mace is installed (without importing torch!) if importlib.util.find_spec("mace") is not None: calcs["mace_mp"] = { "factory": "mace.calculators:mace_mp", "kwargs": {"model": "medium"}, } # Check if chgnet is installed if importlib.util.find_spec("chgnet") is not None: calcs["chgnet"] = {"factory": "chgnet.model:CHGNetCalculator"} return calcs ``` -------------------------------- ### ASERPC Environment Configuration (Bash) Source: https://context7.com/zincware/aserpc/llms.txt Configures ASERPC behavior using environment variables. This includes settings for IPC communication directories, timeouts, and heartbeats. It also shows starting the broker and a worker. ```bash # Environment variables export ASERPC_IPC_DIR=/tmp/aserpc export ASERPC_IPC_FRONTEND="ipc:///tmp/aserpc/frontend.ipc" export ASERPC_IPC_BACKEND="ipc:///tmp/aserpc/backend.ipc" export ASERPC_WORKER_TIMEOUT=30.0 export ASERPC_HEARTBEAT_INTERVAL=5.0 export ASERPC_IDLE_TIMEOUT=300.0 export ASERPC_REQUEST_QUEUE_TIMEOUT=60.0 export ASERPC_CLIENT_TIMEOUT_MS=60000 aserpc broker aserpc worker LJ ``` -------------------------------- ### CLI - Broker Command Source: https://context7.com/zincware/aserpc/llms.txt Start the message broker from the command line with configurable options. The broker is essential for managing communication between workers and clients. ```APIDOC ## Broker Command ### Description Start the message broker from the command line with configurable options. ### Method CLI command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash # Start broker with default settings aserpc broker # Custom configuration aserpc broker \ --frontend ipc:///tmp/aserpc/frontend.ipc \ --backend ipc:///tmp/aserpc/backend.ipc \ --timeout 30.0 \ --queue-timeout 60.0 \ --log-level DEBUG # With environment variables export ASERPC_IPC_DIR=/tmp/aserpc export ASERPC_WORKER_TIMEOUT=45.0 aserpc broker ``` ### Response #### Success Response (0) Broker starts successfully. #### Response Example No direct output for success, broker runs in the background or foreground depending on execution. #### Error Response Error messages related to configuration or startup failures. ``` -------------------------------- ### Start ASERPC Worker for a Specific Calculator Source: https://github.com/zincware/aserpc/blob/main/README.md Launches an ASERPC worker process that can execute a specified ASE calculator remotely. It can optionally be directed to a specific calculator registry. ```bash aserpc worker LJ # optional --registry tmp/registry.py:CALCULATORS aserpc worker mace_mp ``` -------------------------------- ### CLI - Worker Command Source: https://context7.com/zincware/aserpc/llms.txt Start a worker process for a specific calculator type with automatic discovery. Workers execute computational tasks requested by the broker. ```APIDOC ## Worker Command ### Description Start a worker process for a specific calculator type with automatic discovery. ### Method CLI command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters - **calc_name** (string) - Required - The name of the calculator for which to start workers. - **--registry** (string) - Optional - Path to a Python file defining custom calculators (e.g., `tmp/registry.py:CALCULATORS`). - **--broker** (string) - Optional - The address of the backend broker (default: `ipc:///tmp/aserpc/backend.ipc`). - **--idle-timeout** (float) - Optional - Timeout in seconds for workers to remain idle before shutting down. - **--heartbeat** (float) - Optional - Interval in seconds for sending heartbeat signals. - **--log-level** (string) - Optional - Set the logging level (e.g., `DEBUG`, `INFO`, `WARNING`, `ERROR`). ### Request Example ```bash # Start worker for built-in calculator aserpc worker LJ # Start worker with custom registry file aserpc worker LJ --registry tmp/registry.py:CALCULATORS # Worker with custom configuration aserpc worker mace_mp \ --broker ipc:///tmp/aserpc/backend.ipc \ --idle-timeout 600 \ --heartbeat 10.0 \ --log-level INFO # Start multiple workers in parallel aserpc worker LJ & aserpc worker LJ & aserpc worker EMT & ``` ### Response #### Success Response (0) Worker process starts successfully. #### Response Example No direct output for success, worker runs in the background. #### Error Response Error messages related to calculator name, registry file, or broker connection failures. ``` -------------------------------- ### Request/Response Serialization with ASERPC Protocol (Python) Source: https://context7.com/zincware/aserpc/llms.txt Example of packing and unpacking ASE Atoms objects and calculation results for network transfer using ASERPC's protocol functions. It covers both successful responses and error handling. ```python from aserpc.protocol import pack_request, unpack_request, pack_response, unpack_response from ase.build import molecule import numpy as np # Client side: pack request atoms = molecule("H2O") properties = ["energy", "forces", "stress"] request_data = pack_request(atoms, properties) print(f"Request size: {len(request_data)} bytes") # Worker side: unpack request atoms_received, properties_received = unpack_request(request_data) print(f"Atoms: {len(atoms_received)} atoms") print(f"Properties: {properties_received}") # Worker side: pack response (success) results = { "energy": -10.5, "forces": np.array([[-0.1, 0.2, 0.0], [0.05, -0.1, 0.0], [0.05, -0.1, 0.0]]), "stress": np.array([0.1, 0.1, 0.1, 0.0, 0.0, 0.0]) } response_data = pack_response(results=results) # Worker side: pack response (error) error_data = pack_response(error="Calculator initialization failed") # Client side: unpack response try: results_received = unpack_response(response_data, n_atoms=len(atoms)) print(f"Energy: {results_received['energy']}") print(f"Forces shape: {results_received['forces'].shape}") except RuntimeError as e: print(f"Calculation error: {e}") ``` -------------------------------- ### broker_status - Get Detailed Broker Status Source: https://context7.com/zincware/aserpc/llms.txt Retrieve detailed information about worker states and pending requests from the broker. This endpoint is useful for monitoring the health and load of the AseRpc system. ```APIDOC ## Get Detailed Broker Status ### Description Retrieve detailed information about worker states and pending requests from the broker. ### Method Not Applicable (Python function) ### Endpoint Not Applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from aserpc import broker_status try: status = broker_status(broker="ipc:///tmp/aserpc/frontend.ipc") # Access worker information for calc_name, info in status['workers'].items(): print(f"\nCalculator: {calc_name}") print(f" Total workers: {info['total']}") print(f" Idle workers: {info['idle']}") print(f" Busy workers: {info['busy']}") # Check pending requests if status['pending_requests']: print("\nPending requests:") for calc_name, count in status['pending_requests'].items(): print(f" {calc_name}: {count} queued") else: print("\nNo pending requests") except TimeoutError: print("Broker not responding") ``` ### Response #### Success Response (200) - **workers** (dict) - A dictionary containing information about worker states for each calculator. - **calc_name** (str) - The name of the calculator. - **info** (dict) - Information about the workers for the calculator. - **total** (int) - Total number of workers for this calculator. - **idle** (int) - Number of idle workers. - **busy** (int) - Number of busy workers. - **pending_requests** (dict) - A dictionary showing the number of pending requests for each calculator. - **calc_name** (str) - The name of the calculator. - **count** (int) - The number of queued requests. #### Response Example ```json { "workers": { "LJ": {"total": 3, "idle": 2, "busy": 1}, "mace_mp": {"total": 2, "idle": 0, "busy": 2} }, "pending_requests": { "mace_mp": 5 } } ``` ``` -------------------------------- ### Get Detailed Broker Status (Python) Source: https://context7.com/zincware/aserpc/llms.txt Retrieves detailed information about worker states and pending requests from the broker. It accesses worker counts (total, idle, busy) and counts of pending requests per calculator. Requires the 'aserpc' library and a running broker. ```python from aserpc import broker_status try: status = broker_status(broker="ipc:///tmp/aserpc/frontend.ipc") # Access worker information for calc_name, info in status['workers'].items(): print(f"\nCalculator: {calc_name}") print(f" Total workers: {info['total']}") print(f" Idle workers: {info['idle']}") print(f" Busy workers: {info['busy']}") # Check pending requests if status['pending_requests']: print("\nPending requests:") for calc_name, count in status['pending_requests'].items(): print(f" {calc_name}: {count} queued") else: print("\nNo pending requests") except TimeoutError: print("Broker not responding") ``` -------------------------------- ### ASERPC Configuration via pyproject.toml Source: https://github.com/zincware/aserpc/blob/main/README.md Illustrates how to configure ASERPC settings within a project's `pyproject.toml` file. This allows for project-specific defaults for IPC paths, timeouts, and other operational parameters. ```toml [tool.aserpc] ipc_dir = "/tmp/aserpc" worker_timeout = 30.0 heartbeat_interval = 5.0 idle_timeout = 300.0 request_queue_timeout = 60.0 client_timeout_ms = 60000 ``` -------------------------------- ### ASERPC Configuration via Environment Variables Source: https://github.com/zincware/aserpc/blob/main/README.md Lists environment variables that can be used to configure ASERPC's behavior, such as socket locations, timeouts, and heartbeat intervals. These settings provide flexibility in deployment. ```text | Variable | |----------|------------------------------------| | `ASERPC_IPC_DIR` | `.aserpc` (cwd) | Directory for IPC sockets | | `ASERPC_IPC_FRONTEND` | `ipc://{IPC_DIR}/frontend.ipc` | Client socket address | | `ASERPC_IPC_BACKEND` | `ipc://{IPC_DIR}/backend.ipc` | Worker socket address | | `ASERPC_WORKER_TIMEOUT` | 30.0 | Seconds before broker considers worker dead | | `ASERPC_HEARTBEAT_INTERVAL` | 5.0 | Seconds between heartbeats | | `ASERPC_IDLE_TIMEOUT` | 300.0 | Seconds before idle worker shuts down | | `ASERPC_REQUEST_QUEUE_TIMEOUT` | 60.0 | Seconds before queued request expires | | `ASERPC_CLIENT_TIMEOUT_MS` | 60000 | Client timeout in milliseconds | ``` -------------------------------- ### List Available ASE Calculators with ASERPC Source: https://github.com/zincware/aserpc/blob/main/README.md Displays the calculators that ASERPC can discover and use. This can be done globally, from a specific registry file, or by querying a running broker. Useful for verifying calculator availability. ```bash aserpc list # or aserpc list --registry tmp/registry.py:CALCULATORS # or aserpc list --broker ipc:///tmp/aserpc/frontend.ipc ``` -------------------------------- ### List Calculators Command (Bash) Source: https://context7.com/zincware/aserpc/llms.txt Lists available calculators from entry points, registry files, or a running broker. Supports specifying a custom broker address or registry file. Outputs results in a table format by default, with a JSON option for scripting. Requires the 'aserpc' package. ```bash # List from entry points (installed packages) aserpc list # List from registry file aserpc list --registry tmp/registry.py:CALCULATORS # List from running broker aserpc list --broker ipc:///tmp/aserpc/frontend.ipc # Example output: # ┏━━━━━━━━━━┳━━━━━━━━┓ # ┃ Name ┃ Workers┃ # ┣━━━━━━━━━━╋━━━━━━━━┫ # ┃ LJ ┃ 2 ┃ # ┃ EMT ┃ 1 ┃ # ┗━━━━━━━━━━┻━━━━━━━━┛ ``` -------------------------------- ### Use Registry File with Aserpc CLI (Bash) Source: https://context7.com/zincware/aserpc/llms.txt Demonstrates how to use a custom Python registry file with the Aserpc CLI for worker startup and calculator listing. The `--registry` flag points to the file and the Python object containing the calculator definitions. Requires the 'aserpc' package and a defined registry file. ```bash # Use registry with CLI aserpc worker LJ --registry tmp/registry.py:CALCULATORS aserpc list --registry tmp/registry.py:CALCULATORS ``` -------------------------------- ### Register ASERPC Calculator via Python Entry Points Source: https://github.com/zincware/aserpc/blob/main/README.md Configures a Python package to expose its ASE calculators to ASERPC using standard Python entry points. This method allows for automatic discovery of calculators by ASERPC workers. ```toml # pyproject.toml [project.entry-points."aserpc.calculators"] mypackage = "mypackage.aserpc:get_calculators" ``` -------------------------------- ### Entry Point Provider - Package Calculator Discovery Source: https://context7.com/zincware/aserpc/llms.txt Register calculators from Python packages using entry points for automatic discovery by AseRpc workers, without explicit imports in the registry file. ```APIDOC ## Entry Point Provider - Package Calculator Discovery ### Description Register calculators from Python packages for automatic discovery without imports. ### Method Python package setup (using `entry_points` in `setup.py` or `pyproject.toml`) ### Endpoint N/A ### Parameters None directly in AseRpc for this mechanism. Configuration happens within the Python package's setup. ### Request Example (Conceptual - `setup.py`) ```python from setuptools import setup, find_packages setup( name='my_ase_package', version='0.1.0', packages=find_packages(), entry_points={ 'ase.calculators': [ 'MyCustomCalc = my_ase_package.calculators:MyCalculatorClass', 'AnotherCalc = my_ase_package.calculators:AnotherCalculatorFactory', ] }, ) ``` ### Response #### Success Response Calculators registered via entry points are automatically discovered by `aserpc list` and `aserpc worker` commands when the package is installed. #### Response Example When `aserpc list` is run after installing `my_ase_package`, 'MyCustomCalc' and 'AnotherCalc' would appear in the list of available calculators. ``` -------------------------------- ### ASERPC Environment Configuration (TOML) Source: https://context7.com/zincware/aserpc/llms.txt Configures ASERPC behavior using the pyproject.toml file. This allows for centralized configuration of IPC paths, timeouts, and other operational parameters. ```toml [tool.aserpc] ipc_dir = "/tmp/aserpc" worker_timeout = 30.0 heartbeat_interval = 5.0 idle_timeout = 300.0 request_queue_timeout = 60.0 client_timeout_ms = 60000 ``` -------------------------------- ### CLI - List Command Source: https://context7.com/zincware/aserpc/llms.txt List available calculators from entry points, registry files, or the running broker. This command helps discover which computational capabilities are available in the system. ```APIDOC ## List Command ### Description List available calculators from entry points, registry files, or running broker. ### Method CLI command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters - **--registry** (string) - Optional - Path to a Python file defining custom calculators (e.g., `tmp/registry.py:CALCULATORS`). - **--broker** (string) - Optional - The address of the frontend broker to query for available calculators. ### Request Example ```bash # List from entry points (installed packages) aserpc list # List from registry file aserpc list --registry tmp/registry.py:CALCULATORS # List from running broker aserpc list --broker ipc:///tmp/aserpc/frontend.ipc ``` ### Response #### Success Response (0) - A table listing available calculators and their worker counts. #### Response Example ``` ┏━━━━━━━━━━┳━━━━━━━━┓ ┃ Name ┃ Workers┃ ┣━━━━━━━━━━╋━━━━━━━━┫ ┃ LJ ┃ 2 ┃ ┃ EMT ┃ 1 ┃ ┗━━━━━━━━━━┻━━━━━━━━┛ ``` #### Error Response Error messages related to registry file not found or broker connection failures. ``` -------------------------------- ### Status Command (Bash) Source: https://context7.com/zincware/aserpc/llms.txt Queries and displays broker status, including worker and queue information. Supports specifying a custom broker address and outputting in JSON format for scripting. Displays a table by default. Requires the 'aserpc' package. ```bash # Get broker status (table format) aserpc status # Custom broker address aserpc status --broker ipc:///tmp/aserpc/frontend.ipc # JSON output for scripting aserpc status --json # Example table output: # ┏━━━━━━━━━━━┳━━━━━━━┳━━━━━━┳━━━━━━┳━━━━━━━━━┓ # ┃ Calculator┃ Total ┃ Idle ┃ Busy ┃ Pending ┃ # ┣━━━━━━━━━━━╋━━━━━━━╋━━━━━━╋━━━━━━╋━━━━━━━━━┫ # ┃ LJ ┃ 3 ┃ 2 ┃ 1 ┃ 0 ┃ # ┃ mace_mp ┃ 2 ┃ 0 ┃ 2 ┃ 5 ┃ # ┗━━━━━━━━━━━┻━━━━━━━┻━━━━━━┻━━━━━━┻━━━━━━━━━┛ ``` -------------------------------- ### Use Remote ASE Calculator in Python Source: https://github.com/zincware/aserpc/blob/main/README.md Demonstrates how to instantiate and use a remote ASE calculator within a Python script. It replaces a local calculator with a `RemoteCalculator` instance, enabling computations to be offloaded to ASERPC workers. ```python from aserpc import RemoteCalculator from ase.build import molecule water = molecule("H2O") water.calc = RemoteCalculator("LJ") energy = water.get_potential_energy() ``` -------------------------------- ### ASERPC Python API with Custom Configuration Source: https://context7.com/zincware/aserpc/llms.txt Demonstrates programmatic configuration of ASERPC components (Broker, Worker, RemoteCalculator) using Python. This allows for fine-grained control over connection details and timeouts. ```python # Python API with custom configuration from aserpc import Broker, Worker, RemoteCalculator broker = Broker( frontend="ipc:///tmp/custom/frontend.ipc", backend="ipc:///tmp/custom/backend.ipc", worker_timeout=45.0, request_queue_timeout=90.0 ) worker = Worker( name="LJ", calculator_factory=LennardJones, broker="ipc:///tmp/custom/backend.ipc", idle_timeout=600.0, heartbeat_interval=10.0 ) calc = RemoteCalculator( calc_name="LJ", broker="ipc:///tmp/custom/frontend.ipc", timeout=120000 ) ``` -------------------------------- ### CLI - Status Command Source: https://context7.com/zincware/aserpc/llms.txt Query and display broker status with worker and queue information. Provides a snapshot of the system's current operational state. ```APIDOC ## Status Command ### Description Query and display broker status with worker and queue information. ### Method CLI command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters - **--broker** (string) - Optional - The address of the frontend broker to query (default: `ipc:///tmp/aserpc/frontend.ipc`). - **--json** (boolean) - Optional - Output status in JSON format for scripting. ### Request Example ```bash # Get broker status (table format) aserpc status # Custom broker address aserpc status --broker ipc:///tmp/aserpc/frontend.ipc # JSON output for scripting aserpc status --json ``` ### Response #### Success Response (0) - **Table Format**: A table summarizing calculator status, including total, idle, busy workers, and pending requests. - **JSON Format**: A JSON object with detailed status information. #### Response Example (Table Format) ``` ┏━━━━━━━━━━━┳━━━━━━━┳━━━━━━┳━━━━━━┳━━━━━━━━━┓ ┃ Calculator┃ Total ┃ Idle ┃ Busy ┃ Pending ┃ ┣━━━━━━━━━━━╋━━━━━━━╋━━━━━━╋━━━━━━╋━━━━━━━━━┫ ┃ LJ ┃ 3 ┃ 2 ┃ 1 ┃ 0 ┃ ┃ mace_mp ┃ 2 ┃ 0 ┃ 2 ┃ 5 ┃ ┗━━━━━━━━━━━┻━━━━━━━┻━━━━━━┻━━━━━━┻━━━━━━━━━┛ ``` #### Response Example (JSON Format) ```json { "workers": { "LJ": {"total": 3, "idle": 2, "busy": 1}, "mace_mp": {"total": 2, "idle": 0, "busy": 2} }, "pending_requests": { "mace_mp": 5 } } ``` #### Error Response Error messages related to broker connection failures. ``` -------------------------------- ### Define Custom Calculators in Registry File (Python) Source: https://context7.com/zincware/aserpc/llms.txt Defines custom calculators in a Python registry file for discovery by workers. Supports simple registries with calculator classes and registries with factory functions for configured calculators. Used in conjunction with Aserpc CLI commands. ```python # tmp/registry.py from ase.calculators.lj import LennardJones from ase.calculators.emt import EMT # Simple registry with bare calculator classes CALCULATORS = { "LJ": LennardJones, "EMT": EMT, } # Registry with configured calculors def create_lj_custom(): return LennardJones(sigma=2.5, epsilon=0.5) CALCULATORS_CUSTOM = { "LJ_custom": create_lj_custom, } ``` -------------------------------- ### Broker for Message Routing and Load Balancing Source: https://context7.com/zincware/aserpc/llms.txt The Broker class manages the core routing and load balancing logic within the ASERPC framework. It handles connections between clients and workers, monitors worker health, and manages request queues with configurable timeouts. The broker is run as an asynchronous event loop. ```python from aserpc import Broker import asyncio # Create broker with custom configuration broker = Broker( frontend="ipc:///tmp/aserpc/frontend.ipc", backend="ipc:///tmp/aserpc/backend.ipc", worker_timeout=30.0, # Consider worker dead after 30s request_queue_timeout=60.0 # Expire queued requests after 60s ) # Run broker (blocking) async def main(): try: await broker.run() except KeyboardInterrupt: broker.stop() # Using uvloop for better performance import uvloop uvloop.run(main()) ``` -------------------------------- ### list_calculators Utility to Query Available Calculators Source: https://context7.com/zincware/aserpc/llms.txt The list_calculators function queries the ASERPC broker to retrieve a list of available calculator services and the number of active workers for each. It supports querying the default broker or a custom broker address with a specified timeout. The output is a dictionary mapping calculator names to worker counts. ```python from aserpc import list_calculators # List calculators from default broker try: calculators = list_calculators() for name, count in calculators.items(): print(f"{name}: {count} workers") except TimeoutError: print("Broker not responding") # List from custom broker address calculators = list_calculators( broker="ipc:///tmp/aserpc/frontend.ipc", timeout=5000 ) # Example output: {'LJ': 2, 'EMT': 1, 'mace_mp': 3} ``` -------------------------------- ### Calculator Registry - Custom Calculator Discovery Source: https://context7.com/zincware/aserpc/llms.txt Define custom calculators in a registry file (Python module) for discovery by AseRpc workers. This allows users to integrate their own or pre-configured calculators. ```APIDOC ## Calculator Registry - Custom Calculator Discovery ### Description Define custom calculators in a registry file for discovery by workers. ### Method Python file definition & CLI usage ### Endpoint N/A ### Parameters None for the registry definition itself. Parameters apply when using the registry with CLI commands. ### Request Example (Registry File) ```python # tmp/registry.py from ase.calculators.lj import LennardJones from ase.calculators.emt import EMT # Simple registry with bare calculator classes CALCULATORS = { "LJ": LennardJones, "EMT": EMT, } # Registry with configured calculors def create_lj_custom(): return LennardJones(sigma=2.5, epsilon=0.5) CALCULATORS_CUSTOM = { "LJ_custom": create_lj_custom, } ``` ### Request Example (CLI Usage) ```bash # Use registry with CLI aserpc worker LJ --registry tmp/registry.py:CALCULATORS aserpc list --registry tmp/registry.py:CALCULATORS ``` ### Response #### Success Response Calculators defined in the registry are recognized and used by AseRpc commands. #### Response Example Output will vary based on the command used (e.g., `aserpc list` showing the custom calculators). ``` -------------------------------- ### Broker - Message Routing and Load Balancing Source: https://context7.com/zincware/aserpc/llms.txt The Broker class is the central component responsible for managing connections between clients and workers. It handles request routing, load balancing, and monitors the health of connected workers. ```APIDOC ## Broker - Message Routing and Load Balancing ### Description Manages connections between clients and workers, handling request routing, load balancing, and worker health monitoring. ### Method N/A (Class) ### Endpoint N/A (Server-side) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from aserpc import Broker import asyncio # Create broker with custom configuration broker = Broker( frontend="ipc:///tmp/aserpc/frontend.ipc", backend="ipc:///tmp/aserpc/backend.ipc", worker_timeout=30.0, # Consider worker dead after 30s request_queue_timeout=60.0 # Expire queued requests after 60s ) # Run broker (blocking) async def main(): try: await broker.run() except KeyboardInterrupt: broker.stop() # Using uvloop for better performance import uvloop uvloop.run(main()) ``` ### Response #### Success Response (200) N/A (Server-side process) #### Response Example N/A (Server-side process) ``` -------------------------------- ### RemoteCalculator Client for ASE Calculations Source: https://context7.com/zincware/aserpc/llms.txt The RemoteCalculator class acts as a drop-in replacement for ASE calculators, allowing seamless execution of computations on remote workers. It supports basic usage with default settings and custom configurations for broker address, timeouts, and broker reachability checks. Error handling for timeouts and calculation failures is included. ```python from aserpc import RemoteCalculator from ase.build import molecule, bulk import numpy as np # Basic usage with H2O molecule water = molecule("H2O") water.calc = RemoteCalculator("LJ") energy = water.get_potential_energy() forces = water.get_forces() print(f"Energy: {energy:.4f} eV") print(f"Forces shape: {forces.shape}") # Custom broker address and timeout calc = RemoteCalculator( calc_name="mace_mp", broker="ipc:///tmp/aserpc/frontend.ipc", timeout=120000, # 120 seconds check_broker=True # Verify broker is reachable on init ) # Use with any ASE atoms object cu_bulk = bulk("Cu", "fcc", a=3.6) cu_bulk.calc = calc try: stress = cu_bulk.get_stress() print(f"Stress: {stress}") except TimeoutError as e: print(f"Calculation timed out: {e}") except RuntimeError as e: print(f"Calculation failed: {e}") ``` -------------------------------- ### Gracefully Shutdown Workers (Python) Source: https://context7.com/zincware/aserpc/llms.txt Sends a shutdown signal to all workers running a specific calculator type. It allows specifying the calculator name, broker address, and a timeout. Includes error handling for timeouts and runtime errors. Requires the 'aserpc' library. ```python from aserpc import shutdown_workers # Shutdown all workers for a specific calculator count = shutdown_workers( calc_name="LJ", broker="ipc:///tmp/aserpc/frontend.ipc", timeout=5000 ) print(f"Shutdown {count} workers") # Error handling try: count = shutdown_workers("mace_mp") if count == 0: print("No workers found for mace_mp") except TimeoutError: print("Broker not responding") except RuntimeError as e: print(f"Shutdown failed: {e}") ``` -------------------------------- ### Register Calculators in Python (mypackage/aserpc.py) Source: https://context7.com/zincware/aserpc/llms.txt Registers available calculators for ASERPC. It dynamically checks for optional dependencies like 'mace' and 'chgnet' using importlib.util.find_spec(). The function returns a dictionary mapping calculator names to their factory details. ```python import importlib.util def get_calculators() -> dict[str, dict]: """Return metadata for available calculators. Each entry: {"factory": "module:class", "args": [...], "kwargs": {...}} Use importlib.util.find_spec() to check availability without importing. """ calcs = {} # Always available calculators calcs["LJ"] = {"factory": "ase.calculators.lj:LennardJones"} calcs["EMT"] = {"factory": "ase.calculators.emt:EMT"} # Conditional registration (check without importing torch) if importlib.util.find_spec("mace") is not None: calcs["mace_mp"] = { "factory": "mace.calculators:mace_mp", "kwargs": {"model": "medium", "device": "cuda"} } if importlib.util.find_spec("chgnet") is not None: calcs["chgnet"] = { "factory": "chgnet.model:CHGNetCalculator" } return calcs ``` -------------------------------- ### list_calculators - Query Available Calculators Source: https://context7.com/zincware/aserpc/llms.txt This function queries the ASERPC broker to retrieve a list of available calculators and the number of workers currently serving each type. ```APIDOC ## list_calculators - Query Available Calculators ### Description Query the broker to get a list of available calculators and their worker counts. ### Method N/A (Function) ### Endpoint N/A (Client-side query) ### Parameters #### Path Parameters None #### Query Parameters - **broker** (str) - Optional - The address of the broker to query. - **timeout** (int) - Optional - The timeout in milliseconds for the query. #### Request Body None ### Request Example ```python from aserpc import list_calculators # List calculators from default broker try: calculators = list_calculators() for name, count in calculators.items(): print(f"{name}: {count} workers") except TimeoutError: print("Broker not responding") # List from custom broker address calculators = list_calculators( broker="ipc:///tmp/aserpc/frontend.ipc", timeout=5000 ) # Example output: {'LJ': 2, 'EMT': 1, 'mace_mp': 3} ``` ### Response #### Success Response (200) - **calculators** (dict) - A dictionary where keys are calculator names (str) and values are the number of available workers (int). #### Response Example ```json { "LJ": 2, "EMT": 1, "mace_mp": 3 } ``` ``` -------------------------------- ### Worker - Calculator Service Process Source: https://context7.com/zincware/aserpc/llms.txt The Worker class runs calculator instances and processes calculation requests received from the broker. It supports features like heartbeats for connection health and automatic shutdown after periods of inactivity. ```APIDOC ## Worker - Calculator Service Process ### Description Runs calculator instances and processes calculation requests from the broker, with support for heartbeats and automatic idle shutdown. ### Method N/A (Class) ### Endpoint N/A (Server-side) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from aserpc import Worker from ase.calculators.lj import LennardJones import uvloop # Simple worker with default configuration worker = Worker( name="LJ", calculator_factory=LennardJones, broker="ipc:///tmp/aserpc/backend.ipc" ) # Worker with custom settings def create_mace_calculator(): from mace.calculators import mace_mp return mace_mp(model="medium", device="cuda") worker = Worker( name="mace_mp", calculator_factory=create_mace_calculator, broker="ipc:///tmp/aserpc/backend.ipc", idle_timeout=300.0, # Shutdown after 5 minutes idle heartbeat_interval=5.0 # Send heartbeat every 5 seconds ) # Run worker (blocking) try: uvloop.run(worker.run()) except KeyboardInterrupt: worker.stop() # Access worker statistics print(f"Requests handled: {worker.requests_handled}") ``` ### Response #### Success Response (200) N/A (Server-side process) #### Response Example N/A (Server-side process) ``` -------------------------------- ### shutdown_workers - Gracefully Shutdown Workers Source: https://context7.com/zincware/aserpc/llms.txt Send a shutdown signal to all workers running a specific calculator type. This allows for graceful termination of worker processes. ```APIDOC ## Gracefully Shutdown Workers ### Description Send shutdown signal to all workers running a specific calculator type. ### Method Not Applicable (Python function) ### Endpoint Not Applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from aserpc import shutdown_workers # Shutdown all workers for a specific calculator count = shutdown_workers( calc_name="LJ", broker="ipc:///tmp/aserpc/frontend.ipc", timeout=5000 ) print(f"Shutdown {count} workers") # Error handling try: count = shutdown_workers("mace_mp") if count == 0: print("No workers found for mace_mp") except TimeoutError: print("Broker not responding") except RuntimeError as e: print(f"Shutdown failed: {e}") ``` ### Response #### Success Response (200) - **count** (int) - The number of workers that were shut down. #### Response Example ``` Shutdown 5 workers ``` ``` -------------------------------- ### Worker Process for Calculator Service Source: https://context7.com/zincware/aserpc/llms.txt The Worker class serves calculator instances and processes incoming requests from the broker. It supports features like heartbeat signals for connection health, automatic shutdown after idle periods, and configurable calculator factories. The worker is run within an event loop. ```python from aserpc import Worker from ase.calculators.lj import LennardJones import uvloop # Simple worker with default configuration worker = Worker( name="LJ", calculator_factory=LennardJones, broker="ipc:///tmp/aserpc/backend.ipc" ) # Worker with custom settings def create_mace_calculator(): from mace.calculators import mace_mp return mace_mp(model="medium", device="cuda") worker = Worker( name="mace_mp", calculator_factory=create_mace_calculator, broker="ipc:///tmp/aserpc/backend.ipc", idle_timeout=300.0, # Shutdown after 5 minutes idle heartbeat_interval=5.0 # Send heartbeat every 5 seconds ) # Run worker (blocking) try: uvloop.run(worker.run()) except KeyboardInterrupt: worker.stop() # Access worker statistics print(f"Requests handled: {worker.requests_handled}") ``` -------------------------------- ### RemoteCalculator - Client Interface Source: https://context7.com/zincware/aserpc/llms.txt The RemoteCalculator class acts as a client to interact with remote ASE calculators served by ASERPC workers. It implements the standard ASE Calculator interface, allowing seamless integration into existing ASE workflows. ```APIDOC ## RemoteCalculator - Remote ASE Calculator Client ### Description Provides a transparent interface for performing calculations on remote workers, implementing the standard ASE Calculator interface. ### Method N/A (Class) ### Endpoint N/A (Client-side) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from aserpc import RemoteCalculator from ase.build import molecule, bulk import numpy as np # Basic usage with H2O molecule water = molecule("H2O") water.calc = RemoteCalculator("LJ") energy = water.get_potential_energy() forces = water.get_forces() print(f"Energy: {energy:.4f} eV") print(f"Forces shape: {forces.shape}") # Custom broker address and timeout calc = RemoteCalculator( calc_name="mace_mp", broker="ipc:///tmp/aserpc/frontend.ipc", timeout=120000, # 120 seconds check_broker=True # Verify broker is reachable on init ) # Use with any ASE atoms object cu_bulk = bulk("Cu", "fcc", a=3.6) cu_bulk.calc = calc try: stress = cu_bulk.get_stress() print(f"Stress: {stress}") except TimeoutError as e: print(f"Calculation timed out: {e}") except RuntimeError as e: print(f"Calculation failed: {e}") ``` ### Response #### Success Response (200) N/A (Client-side interaction) #### Response Example N/A (Client-side interaction) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.