Source code for jcmsuite.context.models

# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH

"""Data models and type aliases for runtime context behavior."""

from __future__ import annotations

import multiprocessing
import sys
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Literal

BackendMode = Literal["auto", "local", "daemon"]
GPUSelection = Literal["all", "no"] | int | Sequence[int]


def normalize_gpu_usage(gpus: GPUSelection | None) -> str | None:
    """Normalize a local GPU selection for the solver environment.

    Parameters
    ----------
    gpus : GPUSelection | None
        GPU selection. If the value is ``None``, the inherited process
        environment remains unchanged.

    Returns
    -------
    str | None
        ``"all"``, ``"no"``, a comma-separated GPU identifier list, or
        ``None``.

    Raises
    ------
    ValueError
        If the selection is not supported.
    """

    if gpus is None:
        return None
    if isinstance(gpus, str):
        if gpus in {"all", "no"}:
            return gpus
        raise ValueError("GPU selection must be 'all', 'no', or non-negative integers.")
    if isinstance(gpus, int):
        if gpus >= 0:
            return str(gpus)
        raise ValueError("GPU identifiers must be non-negative integers.")

    try:
        gpu_values: tuple[int, ...] = tuple(gpus)
    except (TypeError, ValueError) as error:
        raise ValueError(
            "GPU selection must be 'all', 'no', or non-negative integers."
        ) from error
    if not gpu_values or any(not isinstance(gpu, int) or gpu < 0 for gpu in gpu_values):
        raise ValueError(
            "GPU identifiers must be a non-empty sequence of non-negative integers."
        )
    return ",".join(str(gpu) for gpu in gpu_values)


[docs] @dataclass(slots=True) class JCMInstallationDetails: """Information about the installed JCMsuite version. Attributes ---------- jcm_root : Path JCMsuite installation directory. version : str | None JCMsuite version reported by `JCMsolve --version`. buildtag : str | None JCMsuite build tag reported by `JCMsolve --version`. """ jcm_root: Path version: str | None = None buildtag: str | None = None
[docs] @dataclass(slots=True, frozen=True) class JCMInterfaceDetails: """Information about the installed `jcmsuite` Python interface. Attributes ---------- package_name : str Installed package name. version : str | None Installed package version. git_commit_sha : str | None Git commit identifier for the package build, if known. git_commit_sha_source : str Source of `git_commit_sha`. The value is `"embedded"`, `"environment"`, `"git"`, or `"unknown"`. build_timestamp : str | None Package build date and time in ISO 8601 UTC format, if known. """ package_name: str version: str | None = None git_commit_sha: str | None = None git_commit_sha_source: str = "unknown" build_timestamp: str | None = None
[docs] @dataclass(slots=True, frozen=True) class JCMLicenseDetails: """Information about the active JCMsuite license. Attributes ---------- period : str License period reported by JCMsuite. file : Path | None License file, if JCMsuite uses a license file. server : str | None License server address, if JCMsuite uses a license server. """ period: str file: Path | None = None server: str | None = None
[docs] @dataclass(slots=True) class JCMSystemDetails: """Computer information and solver settings. Attributes ---------- os : str Operating system name. n_cores : int Number of detected CPU cores. binext : str Program file extension. The value is `.exe` on Windows and an empty string on Linux. n_threads : int | None Number of solver threads, or `None` to use the JCMsuite default. nodes : str | None Compute nodes for distributed solves, if configured. ooc_dir : Path | None Directory for out-of-core data, if configured. temp_dir_root : Path | None Directory that contains temporary working directories. max_core_size_mb : int | None Maximum memory for each solver core in megabytes. max_memory_mb : int | None Maximum total solver memory in megabytes. gpu_usage : str | None Local GPU selection as ``"all"``, ``"no"``, or a comma-separated list of GPU identifiers. ``None`` means no context-specific selection. """ os: str n_cores: int binext: str n_threads: int | None = None nodes: str | None = None ooc_dir: Path | None = None temp_dir_root: Path | None = None max_core_size_mb: int | None = None max_memory_mb: int | None = None gpu_usage: str | None = None @classmethod def detect(cls) -> "JCMSystemDetails": """Detect operating system and CPU capabilities.""" platform_upper: str = sys.platform.upper() detected_os: str binext: str if "LINUX" in platform_upper: detected_os = "LINUX" binext = "" elif "WIN" in platform_upper: detected_os = "WINDOWS" binext = ".exe" else: detected_os = "UNKNOWN" binext = "" try: n_cores: int = multiprocessing.cpu_count() except NotImplementedError: n_cores = 1 return cls(os=detected_os, n_cores=max(1, n_cores), binext=binext)
[docs] @dataclass(slots=True, frozen=True) class JCMInfoDetails: """Information returned by `jcmsuite.info(...)`. Attributes ---------- installation : JCMInstallationDetails Installed JCMsuite version and directory. interface : JCMInterfaceDetails Installed `jcmsuite` interface version and build information. system : JCMSystemDetails Computer information and solver settings. license : JCMLicenseDetails Active JCMsuite license information. """ installation: JCMInstallationDetails interface: JCMInterfaceDetails system: JCMSystemDetails license: JCMLicenseDetails