# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH
"""SolverContext class implementation."""
from __future__ import annotations
import asyncio
import builtins
import datetime as dt
import os
import re
from logging import Logger
from pathlib import Path
from types import TracebackType
from typing import TYPE_CHECKING
from ..exceptions import InvalidConfigurationError, RuntimeContextError
from ..logging import TRACE, get_logger, setup_logger
from .interface_metadata import load_interface_details
from .models import (
BackendMode,
GPUSelection,
JCMInfoDetails,
JCMInstallationDetails,
JCMInterfaceDetails,
JCMLicenseDetails,
JCMSystemDetails,
normalize_gpu_usage,
)
from .scope import _pop_current_context, _push_current_context
_logger: Logger = get_logger(__name__)
if TYPE_CHECKING:
from ..daemon.handler import DaemonHandler
[docs]
class SolverContext:
"""Store settings for JCMsuite operations.
Parameters
----------
jcm_root_dir : Path | None, optional
JCMsuite installation root. If omitted, use the `JCMROOT` environment
variable.
backend_mode : Literal["auto", "local", "daemon"], optional
Default execution method for `solve(...)`.
num_threads : int | None, optional
Number of solver threads.
memory_limit_mb : int | None, optional
Solver memory limit in megabytes.
gpus : GPUSelection | None, optional
Local GPU selection. Use ``"all"`` or ``"no"``. You can also give one
non-negative GPU identifier or a non-empty sequence of GPU identifiers.
temp_dir_root : Path | None, optional
Directory in which JCMsuite creates temporary working directories.
debug : bool, optional
If `True`, enable debug logging.
skip_logger : bool, optional
If `True`, do not configure logging.
logging_level : int | None, optional
Amount of information to write to the log.
log_dir : Path | None, optional
Directory for `jcmsuite.log`.
"""
def __init__(
self,
*,
jcm_root_dir: Path | None = None,
backend_mode: BackendMode = "auto",
num_threads: int | None = None,
memory_limit_mb: int | None = None,
gpus: GPUSelection | None = None,
temp_dir_root: Path | None = None,
debug: bool = False,
skip_logger: bool = False,
logging_level: int | None = None,
log_dir: Path | None = None,
) -> None:
if not skip_logger:
setup_logger(
logging_level=logging_level,
log_dir=log_dir,
debug=debug,
)
self.backend_mode: BackendMode = backend_mode
self._jcm_root: Path | None = self._resolve_jcm_root(jcm_root_dir)
self._system: JCMSystemDetails = JCMSystemDetails.detect()
self._system.n_threads = num_threads
self._system.max_memory_mb = memory_limit_mb
try:
self._system.gpu_usage = normalize_gpu_usage(gpus)
except ValueError as error:
raise InvalidConfigurationError(str(error)) from error
self._system.temp_dir_root = (
None if temp_dir_root is None else temp_dir_root.expanduser().resolve()
)
self.jcm_geo: Path | None = None
self.jcm_solve: Path | None = None
self.jcm_view: Path | None = None
self.jcm_edit: Path | None = None
self.jcm_control: Path | None = None
self._has_binaries: bool = False
if self._jcm_root is not None:
self._initialize_binary_paths()
self._installation: JCMInstallationDetails | None = None
self._license: JCMLicenseDetails | None = None
self._has_startup_run: bool = False
self._daemon_handler: DaemonHandler | None = None
def __enter__(self) -> "SolverContext":
"""Bind this context as the active task-local context."""
_push_current_context(self)
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
"""Restore the previously active task-local context."""
del exc_type, exc, tb
_pop_current_context()
@staticmethod
def _resolve_jcm_root(jcm_root_dir: Path | None) -> Path | None:
"""Resolve explicit or environment-provided JCMROOT path."""
resolved_input: Path | None = jcm_root_dir
if resolved_input is None:
jcm_root_env: str | None = os.environ.get("JCMROOT")
if jcm_root_env is None:
return None
resolved_input = Path(jcm_root_env)
resolved_root: Path = resolved_input.expanduser().resolve()
if not resolved_root.is_dir():
raise RuntimeContextError(f"JCMROOT is not a directory: {resolved_root}")
return resolved_root
def _initialize_binary_paths(self) -> None:
"""Initialize binary paths and availability flags from JCMROOT."""
if self._jcm_root is None:
return
binary_dir: Path = self._jcm_root / "bin"
binext: str = self._system.binext
def _binary_path(directory: Path, binary_name: str) -> Path:
"""Build the full binary path for a named JCM executable.
Parameters
----------
directory : Path
Directory that contains JCM executable binaries.
binary_name : str
Binary basename (for example ``\"JCMsolve\"``).
Returns
-------
Path
Absolute executable path with platform-specific suffix.
Notes
-----
Internal API: this helper is an implementation detail and may change
without notice.
"""
return (directory / binary_name).with_suffix(binext)
self.jcm_geo = _binary_path(binary_dir, "JCMgeo")
self.jcm_solve = _binary_path(binary_dir, "JCMsolve")
self.jcm_view = _binary_path(binary_dir, "JCMview")
self.jcm_edit = _binary_path(binary_dir, "JCMedit")
self.jcm_control = _binary_path(binary_dir, "JCMcontrol")
self._has_binaries = self.jcm_solve.is_file()
if not self._has_binaries:
_logger.warning(
"JCMsolve binary not found at %s; startup-dependent operations are unavailable.",
self.jcm_solve,
)
[docs]
async def startup(self) -> None:
"""Load the JCMsuite installation and license information.
Call this method with `await` before you use `info()` in asynchronous
code. A second call reuses the information from the first call.
Returns
-------
None
This method has no return value.
Raises
------
RuntimeContextError
If the JCMsuite installation is not configured, `JCMsolve` is not
available, or installation or license information cannot be read.
"""
if self._has_startup_run:
_logger.log(TRACE, "SolverContext.startup() already completed; skipping.")
return
if self.jcm_solve is None or not self._has_binaries:
if self._jcm_root is None:
raise RuntimeContextError(
"JCMROOT is not configured, so JCMsuite binary discovery did not run. "
"Set the JCMROOT environment variable or call "
"`create_context(jcm_root=...)`."
)
raise RuntimeContextError(
"JCMsolve binary is not available; cannot execute startup probes. "
f"Expected binary at: {self.jcm_solve}."
)
self._installation = await self._get_installation_info()
self._license = await self._get_license_info()
self._has_startup_run = True
[docs]
def info(
self,
*,
print: bool = True,
verbose: bool = False,
) -> JCMInfoDetails:
"""Return installation, system, and license information.
Parameters
----------
print : bool, optional
If `True`, show the information in the terminal.
verbose : bool, optional
If `True`, also show the interface build time and Git commit
identifier.
Returns
-------
JCMInfoDetails
Installation, computer, interface, and license information.
Raises
------
RuntimeError
If asynchronous code calls this method before `startup()` is
complete.
"""
if not self._has_startup_run:
try:
asyncio.get_running_loop()
except RuntimeError:
asyncio.run(self.startup())
else:
raise RuntimeError(
"SolverContext.info() is synchronous. "
"Run `await context.startup()` first when calling inside "
"a running event loop."
)
installation_info: JCMInstallationDetails = self.installation
interface_info: JCMInterfaceDetails = load_interface_details()
system_info: JCMSystemDetails = self.system
license_info: JCMLicenseDetails = self.license
info_details: JCMInfoDetails = JCMInfoDetails(
installation=installation_info,
interface=interface_info,
system=system_info,
license=license_info,
)
if not print:
return info_details
year: int = dt.datetime.now().year
builtins.print(
f"\nCopyright (c) 2001-{year} JCMwave GmbH, Berlin. All Rights Reserved"
)
builtins.print("\n\n")
builtins.print(f"{'JCMROOT'.rjust(20)} : {installation_info.jcm_root}")
builtins.print(f"{'JCMsuite version'.rjust(20)} : {installation_info.version}")
builtins.print(f"{'Buildtag'.rjust(20)} : {installation_info.buildtag}")
builtins.print(f"{'Number CPUs'.rjust(20)} : {system_info.n_cores}")
builtins.print(
f"{'Number threads'.rjust(20)} : {system_info.n_threads if system_info.n_threads is not None else 'default'}"
)
if system_info.nodes is not None:
builtins.print(f"{'Nodes'.rjust(20)} : {system_info.nodes}")
if system_info.ooc_dir is not None:
builtins.print(f"{'OOC directory'.rjust(20)} : {system_info.ooc_dir}")
if system_info.temp_dir_root is not None:
builtins.print(f"{'Temp dir root'.rjust(20)} : {system_info.temp_dir_root}")
if system_info.max_core_size_mb is not None:
builtins.print(
f"{'Maximum core size'.rjust(20)} : {system_info.max_core_size_mb} [MB]"
)
if system_info.max_memory_mb is not None:
builtins.print(
f"{'Memory limit'.rjust(20)} : {system_info.max_memory_mb} [MB]"
)
if system_info.gpu_usage is not None:
builtins.print(f"{'GPUs'.rjust(20)} : {system_info.gpu_usage}")
if license_info.file is not None:
builtins.print(f"{'License file'.rjust(20)} : {license_info.file}")
builtins.print(f"{'License period'.rjust(20)} : {license_info.period}")
elif license_info.server is not None:
builtins.print(f"{'License server'.rjust(20)} : {license_info.server}")
else:
builtins.print("\n\n No valid license found.")
if verbose:
builtins.print("")
builtins.print("Interface metadata")
builtins.print(f"{'Package'.rjust(20)} : {interface_info.package_name}")
builtins.print(
f"{'Version'.rjust(20)} : {interface_info.version if interface_info.version is not None else 'unknown'}"
)
builtins.print(
f"{'Build time'.rjust(20)} : {interface_info.build_timestamp if interface_info.build_timestamp is not None else 'unknown'}"
)
builtins.print(
f"{'Git SHA'.rjust(20)} : {interface_info.git_commit_sha if interface_info.git_commit_sha is not None else 'unknown'}"
)
builtins.print(
f"{'SHA source'.rjust(20)} : {interface_info.git_commit_sha_source}"
)
builtins.print("\n\n")
return info_details
def _get_or_create_daemon_handler(self) -> DaemonHandler:
"""Return the context-owned daemon handler instance."""
if self._daemon_handler is None:
from ..daemon.handler import DaemonHandler
self._daemon_handler = DaemonHandler(context=self)
return self._daemon_handler
def _get_daemon_handler(self) -> DaemonHandler | None:
"""Return the context-owned daemon handler when it already exists."""
return self._daemon_handler
def _subprocess_environment(self) -> dict[str, str]:
"""Return an environment with this context's local GPU setting applied."""
environment: dict[str, str] = dict(os.environ)
if self._jcm_root is not None:
environment["JCMROOT"] = str(self._jcm_root)
if self.system.gpu_usage == "no":
environment.pop("JCM_USE_GPUS", None)
elif self.system.gpu_usage is not None:
environment["JCM_USE_GPUS"] = self.system.gpu_usage
return environment
async def _get_installation_info(self) -> JCMInstallationDetails:
"""Call `JCMsolve --version` and parse version/build metadata."""
from .subprocess_tools import _call_binary
if self.jcm_solve is None or self._jcm_root is None:
raise RuntimeContextError("JCMsolve path is not initialized.")
stdout: str
stderr: str
return_code: int | None
stdout, stderr, return_code = await _call_binary(self.jcm_solve, "--version")
if return_code not in (0, None):
raise RuntimeContextError(
f"Failed to probe installation info (exit={return_code}): {stderr}"
)
# Matches and captures into the groups `version_tag` and `build_tag`:
# - `Version[ ]*` -> matches the literal "Version" token and optional spaces.
# - `(?P<version_tag>\d+\.\d+\.\d+)` -> captures semantic version components
# (major.minor.patch).
# - `.*` -> consumes any intermediate text between version and build tag.
# `re.DOTALL` below allows this to cross line breaks in multiline output.
# - `Buildtag:[ ]*` -> matches the build tag label with optional spaces.
# - `(?P<build_tag>.*-\d+\.\d+\.\d+\.\d+\.\d+)` -> captures the full build tag,
# anchored by the legacy numeric tail pattern.
# Parsing is intentionally strict so malformed or changed upstream output fails
# fast with a clear context-level error.
version_and_build: re.Match[str] | None = re.search(
r"Version[ ]*(?P<version_tag>\d+\.\d+\.\d+).*Buildtag:[ ]*(?P<build_tag>.*-\d+\.\d+\.\d+\.\d+\.\d+)",
stdout,
flags=re.DOTALL,
)
if version_and_build is None:
raise RuntimeContextError(
"Could not parse JCMsuite version/buildtag output."
)
return JCMInstallationDetails(
jcm_root=self._jcm_root,
version=version_and_build.group("version_tag"),
buildtag=version_and_build.group("build_tag"),
)
async def _get_license_info(self) -> JCMLicenseDetails:
"""Call `JCMsolve --license_info` and parse license metadata."""
from .subprocess_tools import _call_binary
if self.jcm_solve is None:
raise RuntimeContextError("JCMsolve path is not initialized.")
stdout: str
stderr: str
return_code: int | None
stdout, stderr, return_code = await _call_binary(
self.jcm_solve, "--license_info"
)
if return_code not in (0, None):
raise RuntimeContextError(
f"Failed to probe license info (exit={return_code}): {stderr}"
)
# Matches and captures into the group `license_file`:
# - `(?im)` -> enables case-insensitive and multiline matching.
# - `^\s*License File:` -> matches the start of a line, optional leading spaces,
# and the "License File:" label.
# - `\s*` -> allows flexible whitespace after the colon.
# - `(?:File\s*)?` -> optional literal "File" token used by some builds.
# - `(?: ... | ... )` -> two capture variants:
# 1) `"(?P<license_file>[^"]+)"` captures a quoted path (keeps spaces in path
# segments; supports Linux and Windows paths).
# 2) `(\S+)` fallback for unquoted, no-whitespace paths.
# We preserve this dual-branch behavior for parity with historical output variants
# seen in legacy environments.
license_file: re.Match[str] | None = re.search(
r'(?im)^\s*License File:\s*(?:File\s*)?(?:"(?P<license_file>[^"]+)"|(\S+))',
stdout,
)
# Matches and captures into the group `license_period`:
# - `(?im)` -> enables case-insensitive and multiline matching.
# - `^\s*License period:` -> matches the labeled line with optional
# leading spaces.
# - `[ ]*` -> allows optional spaces after the colon.
# - `(?P<license_period>...)` captures exactly one of:
# 1) `perpetual`
# 2) `YYYY-MM-DD -> YYYY-MM-DD`
# This pattern stays intentionally strict to reject ambiguous or malformed
# values instead of silently accepting them.
license_period: re.Match[str] | None = re.search(
r"(?im)^\s*License period:[ ]*(?P<license_period>perpetual|\d{4}-\d{2}-\d{2} -> \d{4}-\d{2}-\d{2})",
stdout,
)
# Matches and captures into the group `license_server`:
# - `(?im)` -> enables case-insensitive and multiline matching.
# - `^\s*server\s+address\s*:` -> matches the label while allowing
# flexible spaces and capitalization (`server address:` variants).
# - `\s*` -> allows spaces after the colon.
# - `(?P<license_server>[^\r\n]*)` -> captures the rest of the line up to
# newline as the server endpoint text.
# We trim surrounding spaces after capture so downstream state is normalized
# while preserving the original legacy extraction semantics.
license_server: re.Match[str] | None = re.search(
r"(?im)^\s*server\s+address\s*:\s*(?P<license_server>[^\r\n]*)",
stdout,
)
if license_server is not None and license_period is not None:
return JCMLicenseDetails(
server=license_server.group("license_server").strip(),
period=license_period.group("license_period").strip(),
)
if license_file is not None and license_period is not None:
file_match: str | None = license_file.group("license_file")
license_path: Path | None = None
if file_match is not None:
license_path = Path(file_match.strip())
return JCMLicenseDetails(
file=license_path,
period=license_period.group("license_period").strip(),
)
raise RuntimeContextError(
"Could not parse JCMsuite license information output."
)
@property
def jcm_root(self) -> Path | None:
"""Return the JCMsuite installation directory.
Returns
-------
Path | None
Installation directory, or `None` if JCMsuite is not configured.
"""
return self._jcm_root
@property
def system(self) -> JCMSystemDetails:
"""Return the computer and solver settings.
Returns
-------
JCMSystemDetails
Detected computer information and configured solver limits.
"""
return self._system
@property
def installation(self) -> JCMInstallationDetails:
"""Return the JCMsuite installation information.
Call `startup()` before you read this property.
Returns
-------
JCMInstallationDetails
Installed JCMsuite version and directory.
Raises
------
RuntimeContextError
If `startup()` has not loaded the installation information.
"""
if self._installation is None:
raise RuntimeContextError(
"Installation information is unavailable; call startup() first."
)
return self._installation
@property
def license(self) -> JCMLicenseDetails:
"""Return the JCMsuite license information.
Call `startup()` before you read this property.
Returns
-------
JCMLicenseDetails
Active JCMsuite license information.
Raises
------
RuntimeContextError
If `startup()` has not loaded the license information.
"""
if self._license is None:
raise RuntimeContextError(
"License information is unavailable; call startup() first."
)
return self._license