sim-cli-core 0.2.4__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.
@@ -0,0 +1,161 @@
1
+ """Driver registry for sim — lazy-loaded.
2
+
3
+ Each driver is identified by a stable name and resolved lazily via importlib.
4
+ A broken import in one driver no longer crashes the entire CLI: callers that
5
+ walk the registry (`iter_drivers`) get a per-driver error; callers that ask
6
+ for a specific driver (`get_driver`) get the original ImportError raised so
7
+ they can present it directly.
8
+
9
+ Plugin discovery
10
+ ----------------
11
+ External drivers register themselves via the ``sim.drivers`` entry-point group:
12
+
13
+ [project.entry-points."sim.drivers"]
14
+ myname = "my_pkg.module:MyDriver"
15
+
16
+ These are discovered at import time, validated, sorted by name, and **appended
17
+ after** the built-in registry. This ordering is contract: built-ins always
18
+ take precedence in `lint` first-match resolution and `solvers list` output;
19
+ externals cannot override a built-in name (collisions are logged and skipped).
20
+ External `module:Class` strings are stored as-is and resolved lazily by
21
+ `_resolve` — discovery never imports the plugin module.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import importlib
26
+ import logging
27
+ from importlib.metadata import entry_points
28
+ from typing import Iterator
29
+
30
+ from sim.driver import DriverProtocol
31
+
32
+
33
+ log = logging.getLogger(__name__)
34
+
35
+ _ENTRY_POINT_GROUP = "sim.drivers"
36
+
37
+
38
+ # (driver_name, "module:Class") — order controls `solvers list` output order
39
+ # and `lint` first-match priority.
40
+ _BUILTIN_REGISTRY: list[tuple[str, str]] = [
41
+ # openfoam: Phase 3a plugin-extraction canary (2026-04-28). Held as the
42
+ # soak safety net while sim-plugin-openfoam ships the external counter-
43
+ # part. Earlier "has a real session implementation, not a drop-in
44
+ # extraction candidate" framing was wrong — the driver is a generic
45
+ # HTTP client over sim-server's normal endpoints, structurally identical
46
+ # to coolprop. Empty-registry cut tracked in svd-ai-lab/sim-proj#69.
47
+ ("openfoam", "sim.drivers.openfoam:OpenFOAMDriver"),
48
+ # coolprop: Phase 1 plugin-extraction canary. Held in the registry as
49
+ # the safety net during the 1-week soak; sim-plugin-coolprop ships the
50
+ # external counterpart. Removal lands in a follow-up PR after soak.
51
+ ("coolprop", "sim.drivers.coolprop:CoolPropDriver"),
52
+ ]
53
+
54
+
55
+ def _is_valid_spec(spec: str) -> bool:
56
+ """Cheap shape check for ``"module.path:ClassName"`` — no import."""
57
+ if not isinstance(spec, str) or ":" not in spec:
58
+ return False
59
+ module_path, _, cls_name = spec.rpartition(":")
60
+ if not module_path or not cls_name:
61
+ return False
62
+ if not all(p.isidentifier() for p in module_path.split(".")):
63
+ return False
64
+ return cls_name.isidentifier()
65
+
66
+
67
+ def _discover_external() -> list[tuple[str, str]]:
68
+ """Find external drivers registered via the ``sim.drivers`` entry-point group.
69
+
70
+ Validation rules (all violations are logged + skipped, never raised):
71
+ * ``ep.value`` must look like ``"module.path:ClassName"``.
72
+ * Names already in ``_BUILTIN_REGISTRY`` are ignored — built-in wins.
73
+ * Duplicate external names: first-seen wins; rest skipped.
74
+
75
+ Returns a list sorted by driver name for deterministic ordering.
76
+ """
77
+ builtin_names = {n for n, _ in _BUILTIN_REGISTRY}
78
+ found: dict[str, str] = {}
79
+ try:
80
+ eps = entry_points(group=_ENTRY_POINT_GROUP)
81
+ except Exception as e: # noqa: BLE001 — entry-point machinery itself failed; degrade gracefully
82
+ log.warning("entry_points(%s) lookup failed: %s", _ENTRY_POINT_GROUP, e)
83
+ return []
84
+ for ep in eps:
85
+ name, spec = ep.name, ep.value
86
+ if name in builtin_names:
87
+ log.warning(
88
+ "external driver %r (from %s) shadows a built-in; skipping",
89
+ name, spec,
90
+ )
91
+ continue
92
+ if name in found:
93
+ log.warning(
94
+ "duplicate external driver %r (from %s); keeping first-seen %r",
95
+ name, spec, found[name],
96
+ )
97
+ continue
98
+ if not _is_valid_spec(spec):
99
+ log.warning(
100
+ "external driver %r has malformed entry-point value %r; skipping",
101
+ name, spec,
102
+ )
103
+ continue
104
+ found[name] = spec
105
+ return sorted(found.items())
106
+
107
+
108
+ _REGISTRY: list[tuple[str, str]] = _BUILTIN_REGISTRY + _discover_external()
109
+
110
+ # Cache: name -> instance. Populated on first successful resolve.
111
+ _INSTANCE_CACHE: dict[str, DriverProtocol] = {}
112
+
113
+
114
+ def driver_names() -> list[str]:
115
+ """Stable list of all registered driver names."""
116
+ return [n for n, _ in _REGISTRY]
117
+
118
+
119
+ def _resolve(name: str) -> DriverProtocol:
120
+ """Import + instantiate the driver, caching the result. Raises on failure."""
121
+ if name in _INSTANCE_CACHE:
122
+ return _INSTANCE_CACHE[name]
123
+ spec = next((s for n, s in _REGISTRY if n == name), None)
124
+ if spec is None:
125
+ raise KeyError(name)
126
+ module_path, cls_name = spec.split(":", 1)
127
+ mod = importlib.import_module(module_path)
128
+ cls = getattr(mod, cls_name)
129
+ instance = cls()
130
+ _INSTANCE_CACHE[name] = instance
131
+ return instance
132
+
133
+
134
+ def get_driver(name: str) -> DriverProtocol | None:
135
+ """Lazily resolve a driver by name.
136
+
137
+ Returns None if `name` is not a registered driver.
138
+ Raises ImportError (or whatever the driver's import raises) if `name` is
139
+ registered but the underlying module fails to import — callers that asked
140
+ for a specific driver should see the real failure, not a misleading
141
+ "no driver named X".
142
+ """
143
+ try:
144
+ return _resolve(name)
145
+ except KeyError:
146
+ return None
147
+
148
+
149
+ def iter_drivers() -> Iterator[tuple[str, DriverProtocol | None, BaseException | None]]:
150
+ """Walk all registered drivers, tolerating per-driver import failure.
151
+
152
+ Yields (name, instance, error). When import fails, instance is None and
153
+ error holds the exception. Use this for `solvers list`, `lint`
154
+ auto-detection, or anywhere you need to enumerate without a single broken
155
+ driver killing the walk.
156
+ """
157
+ for name, _ in _REGISTRY:
158
+ try:
159
+ yield name, _resolve(name), None
160
+ except Exception as e: # noqa: BLE001 — any import-time failure; KeyboardInterrupt/SystemExit propagate
161
+ yield name, None, e
@@ -0,0 +1,3 @@
1
+ from .driver import CoolPropDriver
2
+
3
+ __all__ = ["CoolPropDriver"]
@@ -0,0 +1,183 @@
1
+ """CoolProp driver for sim.
2
+
3
+ CoolProp is an open-source thermophysical-property database (Bell et al.,
4
+ Fundamentals of CoolProp, IECR 2014). REFPROP-equivalent for ~120 pure
5
+ fluids and humid-air psychrometrics. Pip-installable
6
+ (`pip install CoolProp`); ships compiled C++ kernel + Python bindings.
7
+
8
+ Scripts are plain `.py`:
9
+ from CoolProp.CoolProp import PropsSI
10
+ h = PropsSI('H', 'T', 300, 'P', 101325, 'Water')
11
+ T_sat = PropsSI('T', 'P', 101325, 'Q', 0, 'Water') # at 1 atm
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import ast
16
+ import json
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ from sim.driver import ConnectionInfo, Diagnostic, LintResult, SolverInstall
24
+ from sim.runner import run_subprocess
25
+
26
+
27
+ _IMPORT_RE = re.compile(
28
+ r"^\s*(import\s+CoolProp|from\s+CoolProp\b)", re.MULTILINE,
29
+ )
30
+ _USAGE_RE = re.compile(
31
+ r"\b(PropsSI|HAPropsSI|AbstractState|PhaseSI|generate_update_pair)\b",
32
+ )
33
+
34
+
35
+ def _probe_python_for_coolprop(python_exe: Path) -> str | None:
36
+ if not python_exe.is_file():
37
+ return None
38
+ try:
39
+ proc = subprocess.run(
40
+ [str(python_exe), "-c", "import CoolProp; print(CoolProp.__version__)"],
41
+ capture_output=True, text=True, timeout=20,
42
+ )
43
+ except (subprocess.TimeoutExpired, OSError):
44
+ return None
45
+ if proc.returncode != 0:
46
+ return None
47
+ v = (proc.stdout or "").strip()
48
+ return v or None
49
+
50
+
51
+ class CoolPropDriver:
52
+ """Sim driver for CoolProp (thermophysical properties)."""
53
+
54
+ @property
55
+ def name(self) -> str:
56
+ return "coolprop"
57
+
58
+ @property
59
+ def supports_session(self) -> bool:
60
+ return False
61
+
62
+ def detect(self, script: Path) -> bool:
63
+ try:
64
+ if script.suffix.lower() != ".py":
65
+ return False
66
+ text = script.read_text(encoding="utf-8", errors="replace")
67
+ return bool(_IMPORT_RE.search(text))
68
+ except (OSError, UnicodeDecodeError):
69
+ return False
70
+
71
+ def lint(self, script: Path) -> LintResult:
72
+ diagnostics: list[Diagnostic] = []
73
+ if script.suffix.lower() != ".py":
74
+ return LintResult(
75
+ ok=False,
76
+ diagnostics=[Diagnostic(
77
+ level="error",
78
+ message=f"Unsupported file type: {script.suffix} (expected .py)",
79
+ )],
80
+ )
81
+ try:
82
+ text = script.read_text(encoding="utf-8", errors="replace")
83
+ except OSError as e:
84
+ return LintResult(
85
+ ok=False,
86
+ diagnostics=[Diagnostic(level="error", message=f"Cannot read: {e}")],
87
+ )
88
+
89
+ if not _IMPORT_RE.search(text):
90
+ diagnostics.append(Diagnostic(
91
+ level="error", message="No `import CoolProp` / `from CoolProp` found",
92
+ ))
93
+
94
+ try:
95
+ ast.parse(text)
96
+ except SyntaxError as e:
97
+ diagnostics.append(Diagnostic(
98
+ level="error", message=f"Syntax error: {e}", line=e.lineno,
99
+ ))
100
+
101
+ if _IMPORT_RE.search(text) and not _USAGE_RE.search(text):
102
+ diagnostics.append(Diagnostic(
103
+ level="warning",
104
+ message=(
105
+ "No PropsSI / HAPropsSI / AbstractState / PhaseSI call — "
106
+ "script may not do anything"
107
+ ),
108
+ ))
109
+
110
+ ok = not any(d.level == "error" for d in diagnostics)
111
+ return LintResult(ok=ok, diagnostics=diagnostics)
112
+
113
+ def connect(self) -> ConnectionInfo:
114
+ installs = self.detect_installed()
115
+ if not installs:
116
+ return ConnectionInfo(
117
+ solver="coolprop", version=None, status="not_installed",
118
+ message="CoolProp not importable from any known Python env",
119
+ )
120
+ top = installs[0]
121
+ return ConnectionInfo(
122
+ solver="coolprop", version=top.version, status="ok",
123
+ message=f"CoolProp {top.version} in {top.path}",
124
+ solver_version=top.version,
125
+ )
126
+
127
+ def detect_installed(self) -> list[SolverInstall]:
128
+ found: dict[str, SolverInstall] = {}
129
+
130
+ def _record(python: Path, source: str) -> None:
131
+ ver = _probe_python_for_coolprop(python)
132
+ if ver is None:
133
+ return
134
+ key = str(python.resolve())
135
+ if key in found:
136
+ return
137
+ short = ".".join(ver.split(".")[:2])
138
+ found[key] = SolverInstall(
139
+ name="coolprop", version=short,
140
+ path=str(python.parent), source=source,
141
+ extra={"raw_version": ver, "python": str(python)},
142
+ )
143
+
144
+ _record(Path(sys.executable), "sys.executable")
145
+ for name in ("python3", "python"):
146
+ p = shutil.which(name)
147
+ if p:
148
+ _record(Path(p), f"which:{name}")
149
+ return sorted(found.values(), key=lambda i: i.version, reverse=True)
150
+
151
+ def parse_output(self, stdout: str) -> dict:
152
+ for line in reversed(stdout.strip().splitlines()):
153
+ line = line.strip()
154
+ if line.startswith("{"):
155
+ try:
156
+ return json.loads(line)
157
+ except json.JSONDecodeError:
158
+ continue
159
+ return {}
160
+
161
+ def run_file(self, script: Path):
162
+ if script.suffix.lower() != ".py":
163
+ raise RuntimeError(
164
+ f"coolprop driver only accepts .py scripts (got {script.suffix})"
165
+ )
166
+ installs = self.detect_installed()
167
+ if not installs:
168
+ raise RuntimeError("CoolProp is not installed in any known Python env")
169
+ python_exe = installs[0].extra.get("python", sys.executable)
170
+ return run_subprocess(
171
+ [python_exe, str(script)], script=script, solver=self.name,
172
+ )
173
+
174
+ # Session lifecycle stubs — CoolProp is one-shot, but DriverProtocol is
175
+ # runtime_checkable so every method must exist. See `sim.driver`.
176
+ def launch(self, **kwargs) -> dict:
177
+ raise NotImplementedError("coolprop driver does not support sessions")
178
+
179
+ def run(self, code: str, label: str = "") -> dict:
180
+ raise NotImplementedError("coolprop driver does not support sessions")
181
+
182
+ def disconnect(self) -> dict:
183
+ return {"ok": True, "disconnected": True}
@@ -0,0 +1,4 @@
1
+ """OpenFOAM driver for sim — remote execution via sim-server."""
2
+ from sim.drivers.openfoam.driver import OpenFOAMDriver
3
+
4
+ __all__ = ["OpenFOAMDriver"]
@@ -0,0 +1,37 @@
1
+ # sim-cli — OpenFOAM driver compatibility matrix.
2
+ #
3
+ # OpenFOAM has no Python binding. The "SDK" is the OpenFOAM bashrc itself
4
+ # — the inline OpenFOAMDriver sources it and shells out to solver binaries
5
+ # (blockMesh, simpleFoam, pisoFoam, …).
6
+ #
7
+ # Detection inputs (see driver.py detect_installed):
8
+ # - WM_PROJECT_DIR / WM_PROJECT_VERSION env vars (set by etc/bashrc)
9
+ # - /opt/openfoam* /usr/lib/openfoam* ~/OpenFOAM/OpenFOAM-* defaults
10
+ # - which simpleFoam (PATH probe as last resort)
11
+ #
12
+ # Version normalization: ESI releases are "v2312" / "v2406" — we strip the
13
+ # leading "v" and use the YYMM short form ("23.12", "24.06") so the same
14
+ # resolver helper that handles Ansys "25.2" can match these too.
15
+
16
+ driver: openfoam
17
+ # (no sdk_package — OpenFOAM has no Python binding)
18
+
19
+ profiles:
20
+
21
+ - name: openfoam_v2406
22
+ solver_versions: ["24.06", "v2406"]
23
+ active_solver_layer: "v2406"
24
+ notes: |
25
+ ESI OpenFOAM v2406 (June 2024). Latest stable at time of writing.
26
+
27
+ - name: openfoam_v2312
28
+ solver_versions: ["23.12", "v2312"]
29
+ active_solver_layer: "v2312"
30
+ notes: |
31
+ ESI OpenFOAM v2312 (December 2023).
32
+
33
+ - name: openfoam_v2206
34
+ solver_versions: ["22.06", "v2206"]
35
+ active_solver_layer: "v2206"
36
+ notes: |
37
+ ESI OpenFOAM v2206. Older but still common in production.