jcmsuite 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. jcmsuite/__init__.py +49 -0
  2. jcmsuite/_build_info.py +4 -0
  3. jcmsuite/context/__init__.py +44 -0
  4. jcmsuite/context/interface_metadata.py +158 -0
  5. jcmsuite/context/models.py +213 -0
  6. jcmsuite/context/scope.py +210 -0
  7. jcmsuite/context/solver_context.py +569 -0
  8. jcmsuite/context/subprocess_tools.py +172 -0
  9. jcmsuite/contract.py +47 -0
  10. jcmsuite/daemon/__init__.py +19 -0
  11. jcmsuite/daemon/handler.py +925 -0
  12. jcmsuite/daemon/internal/__init__.py +4 -0
  13. jcmsuite/daemon/internal/bundle_protocol.py +64 -0
  14. jcmsuite/daemon/internal/handler_helpers.py +368 -0
  15. jcmsuite/daemon/internal/handler_resource_jobs.py +227 -0
  16. jcmsuite/daemon/internal/handler_wait.py +564 -0
  17. jcmsuite/daemon/models.py +349 -0
  18. jcmsuite/daemon/namespaces.py +250 -0
  19. jcmsuite/daemon/protocol.py +801 -0
  20. jcmsuite/daemon/resources.py +407 -0
  21. jcmsuite/daemon/scope.py +53 -0
  22. jcmsuite/daemon/transport.py +223 -0
  23. jcmsuite/editing/__init__.py +10 -0
  24. jcmsuite/editing/editor.py +274 -0
  25. jcmsuite/exceptions/__init__.py +32 -0
  26. jcmsuite/exceptions/errors.py +173 -0
  27. jcmsuite/geo/__init__.py +10 -0
  28. jcmsuite/geo/mesh.py +302 -0
  29. jcmsuite/info/__init__.py +10 -0
  30. jcmsuite/info/runtime_info.py +45 -0
  31. jcmsuite/internal/__init__.py +2 -0
  32. jcmsuite/internal/diagnostics.py +74 -0
  33. jcmsuite/internal/progress.py +80 -0
  34. jcmsuite/loaders/__init__.py +18 -0
  35. jcmsuite/loaders/blob_header.py +315 -0
  36. jcmsuite/loaders/cartesian_field_reader.py +249 -0
  37. jcmsuite/loaders/cartesian_fields.py +324 -0
  38. jcmsuite/loaders/nested_mapping.py +69 -0
  39. jcmsuite/loaders/powerflux.py +136 -0
  40. jcmsuite/loaders/table.py +573 -0
  41. jcmsuite/logging/__init__.py +22 -0
  42. jcmsuite/logging/runtime.py +210 -0
  43. jcmsuite/results/__init__.py +126 -0
  44. jcmsuite/results/artifacts.py +778 -0
  45. jcmsuite/results/discovery.py +82 -0
  46. jcmsuite/results/field_exports.py +897 -0
  47. jcmsuite/results/field_payloads.py +453 -0
  48. jcmsuite/results/internal/__init__.py +4 -0
  49. jcmsuite/results/internal/export/__init__.py +4 -0
  50. jcmsuite/results/internal/export/common.py +28 -0
  51. jcmsuite/results/internal/export/companion.py +16 -0
  52. jcmsuite/results/internal/export/companion_xarray.py +16 -0
  53. jcmsuite/results/internal/export/pandas/__init__.py +4 -0
  54. jcmsuite/results/internal/export/pandas/common.py +105 -0
  55. jcmsuite/results/internal/export/pandas/payload.py +415 -0
  56. jcmsuite/results/internal/export/preview.py +178 -0
  57. jcmsuite/results/internal/export/xarray/__init__.py +4 -0
  58. jcmsuite/results/internal/export/xarray/types.py +28 -0
  59. jcmsuite/results/internal/models/__init__.py +4 -0
  60. jcmsuite/results/internal/models/batch.py +1087 -0
  61. jcmsuite/results/internal/models/batch_postprocess.py +1503 -0
  62. jcmsuite/results/internal/models/bundle.py +343 -0
  63. jcmsuite/results/internal/models/core.py +556 -0
  64. jcmsuite/results/internal/models/submission.py +1157 -0
  65. jcmsuite/results/internal/resultbag/__init__.py +4 -0
  66. jcmsuite/results/internal/resultbag/access.py +531 -0
  67. jcmsuite/results/internal/resultbag/iteration.py +199 -0
  68. jcmsuite/results/internal/resultbag/query.py +230 -0
  69. jcmsuite/results/internal/resultbag/raw.py +407 -0
  70. jcmsuite/results/internal/resultbag/source_files.py +142 -0
  71. jcmsuite/results/internal/resultbag/store.py +882 -0
  72. jcmsuite/results/internal/resultbag/utils.py +258 -0
  73. jcmsuite/results/models.py +76 -0
  74. jcmsuite/results/opening.py +55 -0
  75. jcmsuite/results/pandas_export.py +165 -0
  76. jcmsuite/results/payloads.py +458 -0
  77. jcmsuite/results/postprocess.py +97 -0
  78. jcmsuite/results/postprocess_payloads.py +762 -0
  79. jcmsuite/results/postprocess_record.py +406 -0
  80. jcmsuite/results/resultbag.py +285 -0
  81. jcmsuite/results/resultbag_management.py +433 -0
  82. jcmsuite/results/structured_derivatives.py +387 -0
  83. jcmsuite/solve/__init__.py +10 -0
  84. jcmsuite/solve/daemon_bundle_staging.py +100 -0
  85. jcmsuite/solve/daemon_bundle_wait.py +89 -0
  86. jcmsuite/solve/orchestration.py +1576 -0
  87. jcmsuite/solve/orchestration_execution.py +180 -0
  88. jcmsuite/solve/orchestration_routing.py +128 -0
  89. jcmsuite/solve/orchestration_support.py +323 -0
  90. jcmsuite/solve/path_resolution.py +98 -0
  91. jcmsuite/solve/progress.py +20 -0
  92. jcmsuite/solve/solver.py +709 -0
  93. jcmsuite/solve/staging.py +276 -0
  94. jcmsuite/solve/types.py +25 -0
  95. jcmsuite/solve/working_dirs.py +227 -0
  96. jcmsuite/templates/__init__.py +11 -0
  97. jcmsuite/templates/converter.py +71 -0
  98. jcmsuite/templates/formatting.py +335 -0
  99. jcmsuite/templates/formatting_cli.py +47 -0
  100. jcmsuite/templates/rendering.py +666 -0
  101. jcmsuite/view/__init__.py +10 -0
  102. jcmsuite/view/viewer.py +122 -0
  103. jcmsuite-1.0.0.dist-info/METADATA +194 -0
  104. jcmsuite-1.0.0.dist-info/RECORD +106 -0
  105. jcmsuite-1.0.0.dist-info/WHEEL +4 -0
  106. jcmsuite-1.0.0.dist-info/entry_points.txt +3 -0
jcmsuite/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Top-level public API surface for `jcmsuite`."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from importlib import import_module
9
+ from pkgutil import extend_path
10
+ from types import ModuleType
11
+ from typing import TYPE_CHECKING
12
+
13
+ # The optional lockstep distribution owns jcmsuite.torch. Extend the package
14
+ # search path for editable installs as well as wheels installed side by side.
15
+ __path__ = extend_path(__path__, __name__)
16
+
17
+ from . import context as context
18
+ from . import daemon as daemon
19
+ from . import editing as editing
20
+ from . import results as results
21
+ from . import templates as templates
22
+ from .contract import NAMESPACED_API_MODULE_MAP as NAMESPACED_API_MODULE_MAP
23
+ from .contract import PUBLIC_API_EXPORTS as PUBLIC_API_EXPORTS
24
+ from .contract import PUBLIC_API_MODULE_MAP as PUBLIC_API_MODULE_MAP
25
+ from .geo import geo as geo
26
+ from .info import info as info
27
+ from .solve import solve as solve
28
+ from .view import view as view
29
+
30
+ __all__ = ["info", "solve", "geo", "view"]
31
+
32
+ if TYPE_CHECKING:
33
+ from . import torch as torch
34
+
35
+
36
+ def __getattr__(name: str) -> ModuleType:
37
+ if name != "torch":
38
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
39
+ try:
40
+ module: ModuleType = import_module(".torch", __name__)
41
+ except ModuleNotFoundError as error:
42
+ if error.name != "jcmsuite.torch":
43
+ raise
44
+ raise ModuleNotFoundError(
45
+ 'Install the matching Torch integration with pip install "jcmsuite[torch]".',
46
+ name="jcmsuite.torch",
47
+ ) from error
48
+ globals()[name] = module
49
+ return module
@@ -0,0 +1,4 @@
1
+ """Auto-generated build metadata embedded into package artifacts."""
2
+
3
+ BUILD_GIT_SHA: str = "18c1f48b69f0f45995b77fccfff34287d881023d"
4
+ BUILD_TIMESTAMP: str = "2026-11-11T11:22:00Z"
@@ -0,0 +1,44 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Public runtime context API for `jcmsuite`."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from ..exceptions import RuntimeContextError
9
+ from .models import (
10
+ BackendMode,
11
+ GPUSelection,
12
+ JCMInfoDetails,
13
+ JCMInstallationDetails,
14
+ JCMInterfaceDetails,
15
+ JCMLicenseDetails,
16
+ JCMSystemDetails,
17
+ )
18
+ from .scope import (
19
+ create_context,
20
+ get_current_context,
21
+ get_default_context,
22
+ reset_default_context,
23
+ resolve_context,
24
+ set_default_context,
25
+ )
26
+ from .solver_context import SolverContext
27
+
28
+ __all__: list[str] = [
29
+ "BackendMode",
30
+ "GPUSelection",
31
+ "JCMInfoDetails",
32
+ "JCMInterfaceDetails",
33
+ "JCMInstallationDetails",
34
+ "JCMLicenseDetails",
35
+ "JCMSystemDetails",
36
+ "RuntimeContextError",
37
+ "SolverContext",
38
+ "create_context",
39
+ "get_current_context",
40
+ "get_default_context",
41
+ "resolve_context",
42
+ "reset_default_context",
43
+ "set_default_context",
44
+ ]
@@ -0,0 +1,158 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Helpers for Python-interface package metadata shown by ``jcmsuite.info``."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import subprocess
10
+ import tomllib
11
+ from importlib import import_module, metadata
12
+ from pathlib import Path
13
+
14
+ from .models import JCMInterfaceDetails
15
+
16
+ PACKAGE_NAME: str = "jcmsuite"
17
+ UNKNOWN_BUILD_SHA: str = "unknown"
18
+ UNKNOWN_BUILD_TIMESTAMP: str = "unknown"
19
+
20
+
21
+ def _load_embedded_git_sha() -> str | None:
22
+ """Return the git SHA baked into the installed package when available."""
23
+
24
+ try:
25
+ build_info_module = import_module(f"{PACKAGE_NAME}._build_info")
26
+ except ImportError:
27
+ return None
28
+
29
+ raw_sha: object = getattr(build_info_module, "BUILD_GIT_SHA", None)
30
+ if not isinstance(raw_sha, str):
31
+ return None
32
+
33
+ git_sha: str = raw_sha.strip()
34
+ if not git_sha or git_sha == UNKNOWN_BUILD_SHA:
35
+ return None
36
+ return git_sha
37
+
38
+
39
+ def _load_embedded_build_timestamp() -> str | None:
40
+ """Return the build timestamp baked into the installed package."""
41
+
42
+ try:
43
+ build_info_module = import_module(f"{PACKAGE_NAME}._build_info")
44
+ except ImportError:
45
+ return None
46
+
47
+ raw_timestamp: object = getattr(build_info_module, "BUILD_TIMESTAMP", None)
48
+ if not isinstance(raw_timestamp, str):
49
+ return None
50
+
51
+ build_timestamp: str = raw_timestamp.strip()
52
+ if not build_timestamp or build_timestamp == UNKNOWN_BUILD_TIMESTAMP:
53
+ return None
54
+ return build_timestamp
55
+
56
+
57
+ def _load_environment_git_sha() -> str | None:
58
+ """Return an interface git SHA from well-known CI/build env vars."""
59
+
60
+ env_key: str
61
+ for env_key in ("JCMSUITE_INTERFACE_GIT_SHA", "CI_COMMIT_SHA"):
62
+ raw_value: str | None = os.environ.get(env_key)
63
+ if raw_value is None:
64
+ continue
65
+ git_sha: str = raw_value.strip()
66
+ if git_sha:
67
+ return git_sha
68
+ return None
69
+
70
+
71
+ def _load_checkout_git_sha() -> str | None:
72
+ """Return the current checkout SHA when running from a git worktree."""
73
+
74
+ source_path: Path = Path(__file__).resolve()
75
+ candidate_root: Path
76
+ for candidate_root in (source_path.parent, *source_path.parents):
77
+ if not (candidate_root / ".git").exists():
78
+ continue
79
+ completed: subprocess.CompletedProcess[str] = subprocess.run(
80
+ ["git", "-C", str(candidate_root), "rev-parse", "HEAD"],
81
+ check=False,
82
+ text=True,
83
+ capture_output=True,
84
+ )
85
+ if completed.returncode != 0:
86
+ return None
87
+ git_sha: str = completed.stdout.strip()
88
+ return git_sha or None
89
+ return None
90
+
91
+
92
+ def _load_package_version() -> str | None:
93
+ """Return the local source-tree version or the installed package version."""
94
+
95
+ source_path: Path = Path(__file__).resolve()
96
+ candidate_root: Path
97
+ for candidate_root in (source_path.parent, *source_path.parents):
98
+ pyproject_path: Path = candidate_root / "pyproject.toml"
99
+ if not pyproject_path.is_file():
100
+ continue
101
+ pyproject_data: dict[str, object] = tomllib.loads(
102
+ pyproject_path.read_text(encoding="utf-8")
103
+ )
104
+ project_data: object = pyproject_data.get("project")
105
+ if not isinstance(project_data, dict):
106
+ return None
107
+ raw_version: object = project_data.get("version")
108
+ if isinstance(raw_version, str) and raw_version.strip():
109
+ return raw_version.strip()
110
+ return None
111
+
112
+ try:
113
+ return metadata.version(PACKAGE_NAME)
114
+ except metadata.PackageNotFoundError:
115
+ return None
116
+
117
+
118
+ def load_interface_details() -> JCMInterfaceDetails:
119
+ """Resolve structured metadata for the Python interface package."""
120
+
121
+ embedded_git_sha: str | None = _load_embedded_git_sha()
122
+ embedded_build_timestamp: str | None = _load_embedded_build_timestamp()
123
+ if embedded_git_sha is not None:
124
+ return JCMInterfaceDetails(
125
+ package_name=PACKAGE_NAME,
126
+ version=_load_package_version(),
127
+ git_commit_sha=embedded_git_sha,
128
+ git_commit_sha_source="embedded",
129
+ build_timestamp=embedded_build_timestamp,
130
+ )
131
+
132
+ environment_git_sha: str | None = _load_environment_git_sha()
133
+ if environment_git_sha is not None:
134
+ return JCMInterfaceDetails(
135
+ package_name=PACKAGE_NAME,
136
+ version=_load_package_version(),
137
+ git_commit_sha=environment_git_sha,
138
+ git_commit_sha_source="environment",
139
+ build_timestamp=embedded_build_timestamp,
140
+ )
141
+
142
+ checkout_git_sha: str | None = _load_checkout_git_sha()
143
+ if checkout_git_sha is not None:
144
+ return JCMInterfaceDetails(
145
+ package_name=PACKAGE_NAME,
146
+ version=_load_package_version(),
147
+ git_commit_sha=checkout_git_sha,
148
+ git_commit_sha_source="git",
149
+ build_timestamp=embedded_build_timestamp,
150
+ )
151
+
152
+ return JCMInterfaceDetails(
153
+ package_name=PACKAGE_NAME,
154
+ version=_load_package_version(),
155
+ git_commit_sha=None,
156
+ git_commit_sha_source="unknown",
157
+ build_timestamp=embedded_build_timestamp,
158
+ )
@@ -0,0 +1,213 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Data models and type aliases for runtime context behavior."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import multiprocessing
9
+ import sys
10
+ from collections.abc import Sequence
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Literal
14
+
15
+ BackendMode = Literal["auto", "local", "daemon"]
16
+ GPUSelection = Literal["all", "no"] | int | Sequence[int]
17
+
18
+
19
+ def normalize_gpu_usage(gpus: GPUSelection | None) -> str | None:
20
+ """Normalize a local GPU selection for the solver environment.
21
+
22
+ Parameters
23
+ ----------
24
+ gpus : GPUSelection | None
25
+ GPU selection. If the value is ``None``, the inherited process
26
+ environment remains unchanged.
27
+
28
+ Returns
29
+ -------
30
+ str | None
31
+ ``"all"``, ``"no"``, a comma-separated GPU identifier list, or
32
+ ``None``.
33
+
34
+ Raises
35
+ ------
36
+ ValueError
37
+ If the selection is not supported.
38
+ """
39
+
40
+ if gpus is None:
41
+ return None
42
+ if isinstance(gpus, str):
43
+ if gpus in {"all", "no"}:
44
+ return gpus
45
+ raise ValueError("GPU selection must be 'all', 'no', or non-negative integers.")
46
+ if isinstance(gpus, int):
47
+ if gpus >= 0:
48
+ return str(gpus)
49
+ raise ValueError("GPU identifiers must be non-negative integers.")
50
+
51
+ try:
52
+ gpu_values: tuple[int, ...] = tuple(gpus)
53
+ except (TypeError, ValueError) as error:
54
+ raise ValueError(
55
+ "GPU selection must be 'all', 'no', or non-negative integers."
56
+ ) from error
57
+ if not gpu_values or any(not isinstance(gpu, int) or gpu < 0 for gpu in gpu_values):
58
+ raise ValueError(
59
+ "GPU identifiers must be a non-empty sequence of non-negative integers."
60
+ )
61
+ return ",".join(str(gpu) for gpu in gpu_values)
62
+
63
+
64
+ @dataclass(slots=True)
65
+ class JCMInstallationDetails:
66
+ """Information about the installed JCMsuite version.
67
+
68
+ Attributes
69
+ ----------
70
+ jcm_root : Path
71
+ JCMsuite installation directory.
72
+ version : str | None
73
+ JCMsuite version reported by `JCMsolve --version`.
74
+ buildtag : str | None
75
+ JCMsuite build tag reported by `JCMsolve --version`.
76
+ """
77
+
78
+ jcm_root: Path
79
+ version: str | None = None
80
+ buildtag: str | None = None
81
+
82
+
83
+ @dataclass(slots=True, frozen=True)
84
+ class JCMInterfaceDetails:
85
+ """Information about the installed `jcmsuite` Python interface.
86
+
87
+ Attributes
88
+ ----------
89
+ package_name : str
90
+ Installed package name.
91
+ version : str | None
92
+ Installed package version.
93
+ git_commit_sha : str | None
94
+ Git commit identifier for the package build, if known.
95
+ git_commit_sha_source : str
96
+ Source of `git_commit_sha`. The value is `"embedded"`,
97
+ `"environment"`, `"git"`, or `"unknown"`.
98
+ build_timestamp : str | None
99
+ Package build date and time in ISO 8601 UTC format, if known.
100
+ """
101
+
102
+ package_name: str
103
+ version: str | None = None
104
+ git_commit_sha: str | None = None
105
+ git_commit_sha_source: str = "unknown"
106
+ build_timestamp: str | None = None
107
+
108
+
109
+ @dataclass(slots=True, frozen=True)
110
+ class JCMLicenseDetails:
111
+ """Information about the active JCMsuite license.
112
+
113
+ Attributes
114
+ ----------
115
+ period : str
116
+ License period reported by JCMsuite.
117
+ file : Path | None
118
+ License file, if JCMsuite uses a license file.
119
+ server : str | None
120
+ License server address, if JCMsuite uses a license server.
121
+ """
122
+
123
+ period: str
124
+ file: Path | None = None
125
+ server: str | None = None
126
+
127
+
128
+ @dataclass(slots=True)
129
+ class JCMSystemDetails:
130
+ """Computer information and solver settings.
131
+
132
+ Attributes
133
+ ----------
134
+ os : str
135
+ Operating system name.
136
+ n_cores : int
137
+ Number of detected CPU cores.
138
+ binext : str
139
+ Program file extension. The value is `.exe` on Windows and an empty
140
+ string on Linux.
141
+ n_threads : int | None
142
+ Number of solver threads, or `None` to use the JCMsuite default.
143
+ nodes : str | None
144
+ Compute nodes for distributed solves, if configured.
145
+ ooc_dir : Path | None
146
+ Directory for out-of-core data, if configured.
147
+ temp_dir_root : Path | None
148
+ Directory that contains temporary working directories.
149
+ max_core_size_mb : int | None
150
+ Maximum memory for each solver core in megabytes.
151
+ max_memory_mb : int | None
152
+ Maximum total solver memory in megabytes.
153
+ gpu_usage : str | None
154
+ Local GPU selection as ``"all"``, ``"no"``, or a comma-separated list
155
+ of GPU identifiers. ``None`` means no context-specific selection.
156
+ """
157
+
158
+ os: str
159
+ n_cores: int
160
+ binext: str
161
+ n_threads: int | None = None
162
+ nodes: str | None = None
163
+ ooc_dir: Path | None = None
164
+ temp_dir_root: Path | None = None
165
+ max_core_size_mb: int | None = None
166
+ max_memory_mb: int | None = None
167
+ gpu_usage: str | None = None
168
+
169
+ @classmethod
170
+ def detect(cls) -> "JCMSystemDetails":
171
+ """Detect operating system and CPU capabilities."""
172
+
173
+ platform_upper: str = sys.platform.upper()
174
+ detected_os: str
175
+ binext: str
176
+ if "LINUX" in platform_upper:
177
+ detected_os = "LINUX"
178
+ binext = ""
179
+ elif "WIN" in platform_upper:
180
+ detected_os = "WINDOWS"
181
+ binext = ".exe"
182
+ else:
183
+ detected_os = "UNKNOWN"
184
+ binext = ""
185
+
186
+ try:
187
+ n_cores: int = multiprocessing.cpu_count()
188
+ except NotImplementedError:
189
+ n_cores = 1
190
+
191
+ return cls(os=detected_os, n_cores=max(1, n_cores), binext=binext)
192
+
193
+
194
+ @dataclass(slots=True, frozen=True)
195
+ class JCMInfoDetails:
196
+ """Information returned by `jcmsuite.info(...)`.
197
+
198
+ Attributes
199
+ ----------
200
+ installation : JCMInstallationDetails
201
+ Installed JCMsuite version and directory.
202
+ interface : JCMInterfaceDetails
203
+ Installed `jcmsuite` interface version and build information.
204
+ system : JCMSystemDetails
205
+ Computer information and solver settings.
206
+ license : JCMLicenseDetails
207
+ Active JCMsuite license information.
208
+ """
209
+
210
+ installation: JCMInstallationDetails
211
+ interface: JCMInterfaceDetails
212
+ system: JCMSystemDetails
213
+ license: JCMLicenseDetails
@@ -0,0 +1,210 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """ContextVar-backed scope and default-context resolution helpers."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import contextvars
9
+ from pathlib import Path
10
+ from threading import RLock
11
+ from typing import TYPE_CHECKING, Final
12
+
13
+ from ..exceptions import RuntimeContextError
14
+ from .models import BackendMode, GPUSelection
15
+
16
+ if TYPE_CHECKING:
17
+ from .solver_context import SolverContext
18
+
19
+ _CURRENT_CONTEXT: contextvars.ContextVar[SolverContext | None] = contextvars.ContextVar(
20
+ "jcmsuite_current_context",
21
+ default=None,
22
+ )
23
+ _CONTEXT_TOKEN_STACK: contextvars.ContextVar[
24
+ tuple[contextvars.Token[SolverContext | None], ...]
25
+ ] = contextvars.ContextVar("jcmsuite_context_token_stack", default=())
26
+
27
+ _DEFAULT_CONTEXT: SolverContext | None = None
28
+ _CONTEXT_LOCK: Final[RLock] = RLock()
29
+
30
+
31
+ def _push_current_context(context: SolverContext) -> None:
32
+ """Bind a task-local context and track the token for nested scopes."""
33
+
34
+ token: contextvars.Token[SolverContext | None] = _CURRENT_CONTEXT.set(context)
35
+ token_stack: tuple[contextvars.Token[SolverContext | None], ...] = (
36
+ _CONTEXT_TOKEN_STACK.get()
37
+ )
38
+ _CONTEXT_TOKEN_STACK.set((*token_stack, token))
39
+
40
+
41
+ def _pop_current_context() -> None:
42
+ """Restore the previous task-local context from the token stack."""
43
+
44
+ token_stack: tuple[contextvars.Token[SolverContext | None], ...] = (
45
+ _CONTEXT_TOKEN_STACK.get()
46
+ )
47
+ if not token_stack:
48
+ raise RuntimeContextError("SolverContext exit called without a matching enter.")
49
+
50
+ token_to_reset: contextvars.Token[SolverContext | None] = token_stack[-1]
51
+ _CURRENT_CONTEXT.reset(token_to_reset)
52
+ _CONTEXT_TOKEN_STACK.set(token_stack[:-1])
53
+
54
+
55
+ def create_context(
56
+ *,
57
+ jcm_root: str | Path | None = None,
58
+ backend_mode: BackendMode = "auto",
59
+ num_threads: int | None = None,
60
+ memory_limit_mb: int | None = None,
61
+ gpus: GPUSelection | None = None,
62
+ temp_dir_root: str | Path | None = None,
63
+ debug: bool = False,
64
+ logging_level: int | None = None,
65
+ log_dir: Path | None = None,
66
+ skip_logger: bool = False,
67
+ ) -> SolverContext:
68
+ """Create a set of JCMsuite settings.
69
+
70
+ Parameters
71
+ ----------
72
+ jcm_root : str | Path | None, optional
73
+ JCMsuite installation root. If omitted, use the `JCMROOT` environment
74
+ variable.
75
+ backend_mode : Literal["auto", "local", "daemon"], optional
76
+ Default execution method for `solve(...)`.
77
+ num_threads : int | None, optional
78
+ Number of solver threads.
79
+ memory_limit_mb : int | None, optional
80
+ Solver memory limit in megabytes.
81
+ gpus : GPUSelection | None, optional
82
+ Local GPU selection. Use ``"all"`` or ``"no"``. You can also give one
83
+ non-negative GPU identifier or a non-empty sequence of GPU identifiers.
84
+ temp_dir_root : str | Path | None, optional
85
+ Directory in which JCMsuite creates temporary working directories.
86
+ debug : bool, optional
87
+ If `True`, enable debug logging.
88
+ logging_level : int | None, optional
89
+ Amount of information to write to the log.
90
+ log_dir : Path | None, optional
91
+ Directory for log files.
92
+ skip_logger : bool, optional
93
+ If `True`, do not configure logging during context creation.
94
+
95
+ Returns
96
+ -------
97
+ SolverContext
98
+ New JCMsuite settings.
99
+ """
100
+
101
+ from .solver_context import SolverContext
102
+
103
+ normalized_root: Path | None = None
104
+ if jcm_root is not None:
105
+ normalized_root = Path(jcm_root).expanduser().resolve()
106
+ normalized_temp_dir_root: Path | None = None
107
+ if temp_dir_root is not None:
108
+ normalized_temp_dir_root = Path(temp_dir_root).expanduser().resolve()
109
+
110
+ return SolverContext(
111
+ jcm_root_dir=normalized_root,
112
+ backend_mode=backend_mode,
113
+ num_threads=num_threads,
114
+ memory_limit_mb=memory_limit_mb,
115
+ gpus=gpus,
116
+ temp_dir_root=normalized_temp_dir_root,
117
+ debug=debug,
118
+ skip_logger=skip_logger,
119
+ logging_level=logging_level,
120
+ log_dir=log_dir,
121
+ )
122
+
123
+
124
+ def set_default_context(context: SolverContext) -> None:
125
+ """Set the default JCMsuite settings.
126
+
127
+ Parameters
128
+ ----------
129
+ context : SolverContext
130
+ Settings to use when a function does not receive `context=`.
131
+
132
+ Returns
133
+ -------
134
+ None
135
+ This function has no return value.
136
+ """
137
+
138
+ global _DEFAULT_CONTEXT
139
+ with _CONTEXT_LOCK:
140
+ _DEFAULT_CONTEXT = context
141
+
142
+
143
+ def get_current_context() -> SolverContext | None:
144
+ """Return the context for the current scope.
145
+
146
+ Returns
147
+ -------
148
+ SolverContext | None
149
+ Active scoped context, or `None` if no scoped context is active.
150
+ """
151
+
152
+ return _CURRENT_CONTEXT.get()
153
+
154
+
155
+ def get_default_context() -> SolverContext:
156
+ """Return the default JCMsuite settings.
157
+
158
+ Returns
159
+ -------
160
+ SolverContext
161
+ Default context. If no default context exists, create one.
162
+ """
163
+
164
+ from .solver_context import SolverContext
165
+
166
+ global _DEFAULT_CONTEXT
167
+ with _CONTEXT_LOCK:
168
+ if _DEFAULT_CONTEXT is None:
169
+ _DEFAULT_CONTEXT = SolverContext()
170
+ return _DEFAULT_CONTEXT
171
+
172
+
173
+ def resolve_context(context: SolverContext | None = None) -> SolverContext:
174
+ """Select the JCMsuite settings for an operation.
175
+
176
+ Parameters
177
+ ----------
178
+ context : SolverContext | None, optional
179
+ Settings supplied directly to the operation.
180
+
181
+ Returns
182
+ -------
183
+ SolverContext
184
+ Selected context. An explicit `context` has first priority. A context
185
+ from the current scope has second priority. The default context has
186
+ last priority.
187
+ """
188
+
189
+ if context is not None:
190
+ return context
191
+
192
+ task_local_context: SolverContext | None = get_current_context()
193
+ if task_local_context is not None:
194
+ return task_local_context
195
+
196
+ return get_default_context()
197
+
198
+
199
+ def reset_default_context() -> None:
200
+ """Remove the default JCMsuite settings.
201
+
202
+ Returns
203
+ -------
204
+ None
205
+ This function has no return value.
206
+ """
207
+
208
+ global _DEFAULT_CONTEXT
209
+ with _CONTEXT_LOCK:
210
+ _DEFAULT_CONTEXT = None