# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH
"""ContextVar-backed scope and default-context resolution helpers."""
from __future__ import annotations
import contextvars
from pathlib import Path
from threading import RLock
from typing import TYPE_CHECKING, Final
from ..exceptions import RuntimeContextError
from .models import BackendMode, GPUSelection
if TYPE_CHECKING:
from .solver_context import SolverContext
_CURRENT_CONTEXT: contextvars.ContextVar[SolverContext | None] = contextvars.ContextVar(
"jcmsuite_current_context",
default=None,
)
_CONTEXT_TOKEN_STACK: contextvars.ContextVar[
tuple[contextvars.Token[SolverContext | None], ...]
] = contextvars.ContextVar("jcmsuite_context_token_stack", default=())
_DEFAULT_CONTEXT: SolverContext | None = None
_CONTEXT_LOCK: Final[RLock] = RLock()
def _push_current_context(context: SolverContext) -> None:
"""Bind a task-local context and track the token for nested scopes."""
token: contextvars.Token[SolverContext | None] = _CURRENT_CONTEXT.set(context)
token_stack: tuple[contextvars.Token[SolverContext | None], ...] = (
_CONTEXT_TOKEN_STACK.get()
)
_CONTEXT_TOKEN_STACK.set((*token_stack, token))
def _pop_current_context() -> None:
"""Restore the previous task-local context from the token stack."""
token_stack: tuple[contextvars.Token[SolverContext | None], ...] = (
_CONTEXT_TOKEN_STACK.get()
)
if not token_stack:
raise RuntimeContextError("SolverContext exit called without a matching enter.")
token_to_reset: contextvars.Token[SolverContext | None] = token_stack[-1]
_CURRENT_CONTEXT.reset(token_to_reset)
_CONTEXT_TOKEN_STACK.set(token_stack[:-1])
[docs]
def create_context(
*,
jcm_root: str | 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: str | Path | None = None,
debug: bool = False,
logging_level: int | None = None,
log_dir: Path | None = None,
skip_logger: bool = False,
) -> SolverContext:
"""Create a set of JCMsuite settings.
Parameters
----------
jcm_root : str | 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 : str | Path | None, optional
Directory in which JCMsuite creates temporary working directories.
debug : bool, optional
If `True`, enable debug logging.
logging_level : int | None, optional
Amount of information to write to the log.
log_dir : Path | None, optional
Directory for log files.
skip_logger : bool, optional
If `True`, do not configure logging during context creation.
Returns
-------
SolverContext
New JCMsuite settings.
"""
from .solver_context import SolverContext
normalized_root: Path | None = None
if jcm_root is not None:
normalized_root = Path(jcm_root).expanduser().resolve()
normalized_temp_dir_root: Path | None = None
if temp_dir_root is not None:
normalized_temp_dir_root = Path(temp_dir_root).expanduser().resolve()
return SolverContext(
jcm_root_dir=normalized_root,
backend_mode=backend_mode,
num_threads=num_threads,
memory_limit_mb=memory_limit_mb,
gpus=gpus,
temp_dir_root=normalized_temp_dir_root,
debug=debug,
skip_logger=skip_logger,
logging_level=logging_level,
log_dir=log_dir,
)
[docs]
def set_default_context(context: SolverContext) -> None:
"""Set the default JCMsuite settings.
Parameters
----------
context : SolverContext
Settings to use when a function does not receive `context=`.
Returns
-------
None
This function has no return value.
"""
global _DEFAULT_CONTEXT
with _CONTEXT_LOCK:
_DEFAULT_CONTEXT = context
[docs]
def get_current_context() -> SolverContext | None:
"""Return the context for the current scope.
Returns
-------
SolverContext | None
Active scoped context, or `None` if no scoped context is active.
"""
return _CURRENT_CONTEXT.get()
[docs]
def get_default_context() -> SolverContext:
"""Return the default JCMsuite settings.
Returns
-------
SolverContext
Default context. If no default context exists, create one.
"""
from .solver_context import SolverContext
global _DEFAULT_CONTEXT
with _CONTEXT_LOCK:
if _DEFAULT_CONTEXT is None:
_DEFAULT_CONTEXT = SolverContext()
return _DEFAULT_CONTEXT
[docs]
def resolve_context(context: SolverContext | None = None) -> SolverContext:
"""Select the JCMsuite settings for an operation.
Parameters
----------
context : SolverContext | None, optional
Settings supplied directly to the operation.
Returns
-------
SolverContext
Selected context. An explicit `context` has first priority. A context
from the current scope has second priority. The default context has
last priority.
"""
if context is not None:
return context
task_local_context: SolverContext | None = get_current_context()
if task_local_context is not None:
return task_local_context
return get_default_context()
[docs]
def reset_default_context() -> None:
"""Remove the default JCMsuite settings.
Returns
-------
None
This function has no return value.
"""
global _DEFAULT_CONTEXT
with _CONTEXT_LOCK:
_DEFAULT_CONTEXT = None