codev-mcp 0.1.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.
codev_mcp/settings.py ADDED
@@ -0,0 +1,100 @@
1
+ """The server's settings, all read from environment variables.
2
+
3
+ Every channel (the plugin, the Desktop Extension, a hand-written MCP config)
4
+ passes the same three user settings:
5
+
6
+ - ``CODEV_IDLE_MINUTES`` idle timeout before CODE V is stopped (default 20, 0 = off)
7
+ - ``CODEV_MCP_DATA`` data folder (default ``%USERPROFILE%\\codev-mcp``)
8
+ - ``CODEV_DIR`` CODE V install folder, used only to build the reference data
9
+
10
+ and two advanced ones, ``CODEV_PROGID`` and ``CODEV_START_DIR``.
11
+
12
+ An extension manifest passes an empty string, or sometimes the unexpanded
13
+ ``${user_config.x}`` placeholder, for an option the user left blank. Both mean
14
+ "use the default", so read settings through :func:`env`, never ``os.environ``.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ from pathlib import Path
21
+
22
+ DEFAULT_IDLE_MINUTES = 20.0
23
+ DEFAULT_PROGID = "CodeV.Application"
24
+
25
+
26
+ def env(name: str) -> str | None:
27
+ """The setting's value, or None when it is unset, blank or an unexpanded placeholder."""
28
+ raw = os.environ.get(name)
29
+ if raw is None:
30
+ return None
31
+ value = raw.strip().strip('"').strip()
32
+ if not value or (value.startswith("${") and value.endswith("}")):
33
+ return None
34
+ return value
35
+
36
+
37
+ def idle_minutes() -> tuple[float, str | None]:
38
+ """(minutes, warning): CODEV_IDLE_MINUTES, 0 or less meaning off; a bad value gives the default."""
39
+ raw = env("CODEV_IDLE_MINUTES")
40
+ if raw is None:
41
+ return DEFAULT_IDLE_MINUTES, None
42
+ try:
43
+ return float(raw), None
44
+ except ValueError:
45
+ return DEFAULT_IDLE_MINUTES, (f"CODEV_IDLE_MINUTES={raw!r} is not a number; "
46
+ f"using {DEFAULT_IDLE_MINUTES:g} minutes")
47
+
48
+
49
+ def progid() -> str:
50
+ return env("CODEV_PROGID") or DEFAULT_PROGID
51
+
52
+
53
+ def data_dir() -> Path:
54
+ value = env("CODEV_MCP_DATA")
55
+ return Path(value).expanduser() if value else Path.home() / "codev-mcp"
56
+
57
+
58
+ def start_dir() -> Path:
59
+ value = env("CODEV_START_DIR")
60
+ return Path(value).expanduser() if value else data_dir() / "work"
61
+
62
+
63
+ def codev_dir() -> Path | None:
64
+ value = env("CODEV_DIR")
65
+ return Path(value).expanduser() if value else None
66
+
67
+
68
+ def under_appdata(path: Path) -> bool:
69
+ """True if the path is under %LOCALAPPDATA% or %APPDATA%.
70
+
71
+ Inside a packaged (MSIX) app such as the Claude desktop app, folders
72
+ created there are redirected into the app's private store, where CODE V,
73
+ which COM starts outside the package, cannot see them.
74
+ """
75
+ for var in ("LOCALAPPDATA", "APPDATA"):
76
+ root = os.environ.get(var)
77
+ if not root:
78
+ continue
79
+ try:
80
+ path.resolve().relative_to(Path(root).resolve())
81
+ return True
82
+ except (ValueError, OSError):
83
+ pass
84
+ return False
85
+
86
+
87
+ def warnings() -> list[str]:
88
+ """Problems with the current settings that a user should fix."""
89
+ out = []
90
+ _, idle_warning = idle_minutes()
91
+ if idle_warning:
92
+ out.append(idle_warning)
93
+ for name, path in (("data folder", data_dir()), ("starting directory", start_dir())):
94
+ if under_appdata(path):
95
+ out.append(f"The {name} {path} is under %LOCALAPPDATA% or %APPDATA%. Inside the Claude desktop app "
96
+ "Windows redirects it where CODE V cannot see it; choose a folder elsewhere.")
97
+ folder = codev_dir()
98
+ if folder is not None and not folder.is_dir():
99
+ out.append(f"The CODE V install folder {folder} does not exist; the reference build will fail.")
100
+ return out
codev_mcp/snapshots.py ADDED
@@ -0,0 +1,199 @@
1
+ """Named lens snapshots: save before a risky change, restore if it goes wrong.
2
+
3
+ A snapshot is a CODE V .len file (it carries everything, including variable
4
+ codes, solves and apertures) plus a fingerprint of the lens taken at save
5
+ time. A restore is accepted only when the restored lens matches that
6
+ fingerprint, so "restored" means verified, not just "RES returned".
7
+
8
+ Snapshots live in ``<CODE V starting directory>/snapshots`` with an
9
+ ``index.json`` beside them, so they survive a server restart. The default
10
+ starting directory is the ``work`` folder under ``~/codev-mcp`` (see paths.py);
11
+ snapshots from the old %TEMP% default are copied across the first time.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import math
18
+ import re
19
+ import shutil
20
+ import time
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from codev_mcp.engine import CodeVEngine, CodeVError, Ops
25
+ from codev_mcp.paths import LEGACY_START_DIR, default_start_dir
26
+
27
+ AUTO_PREFIX = "auto-"
28
+ KEEP_AUTO = 20
29
+ _LABEL = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,59}$")
30
+
31
+
32
+ def _dir(engine: CodeVEngine) -> Path:
33
+ d = Path(engine.start_dir) / "snapshots"
34
+ d.mkdir(parents=True, exist_ok=True)
35
+ _adopt_legacy(engine, d)
36
+ return d
37
+
38
+
39
+ def _adopt_legacy(engine: CodeVEngine, d: Path) -> None:
40
+ """Copy snapshots from the old %TEMP% location the first time, once.
41
+
42
+ Only for the default starting directory, only when it has no snapshots of
43
+ its own yet, and by copying: the old files are left where they are.
44
+ """
45
+ if (d / "index.json").exists() or Path(engine.start_dir) != Path(default_start_dir()):
46
+ return
47
+ old = Path(LEGACY_START_DIR) / "snapshots"
48
+ if not (old / "index.json").is_file():
49
+ return
50
+ for f in old.iterdir():
51
+ if f.suffix in (".len", ".json") and f.is_file():
52
+ shutil.copy2(f, d / f.name)
53
+
54
+
55
+ def _load_index(engine: CodeVEngine) -> dict[str, dict]:
56
+ path = _dir(engine) / "index.json"
57
+ try:
58
+ return json.loads(path.read_text(encoding="utf-8"))
59
+ except (OSError, ValueError):
60
+ return {}
61
+
62
+
63
+ def _save_index(engine: CodeVEngine, index: dict[str, dict]) -> None:
64
+ path = _dir(engine) / "index.json"
65
+ tmp = path.with_suffix(".tmp")
66
+ tmp.write_text(json.dumps(index, indent=1), encoding="utf-8")
67
+ tmp.replace(path)
68
+
69
+
70
+ def fingerprint(ops: Ops) -> dict:
71
+ """Enough of the lens to tell whether a restore brought back the right one."""
72
+ n = int(ops.cv.SurfaceCount)
73
+ surfaces = []
74
+ for s in range(n):
75
+ q = "SO" if s == 0 else ("SI" if s == n - 1 else f"S{s}")
76
+ surfaces.append([ops.eva(f"(RDY {q})"), ops.eva(f"(THI {q})"), str(ops.eva(f"(GLA {q})"))])
77
+ return {
78
+ "title": str(ops.eva("(TIT)")),
79
+ "efl": ops.eva("(EFL)"),
80
+ "stop": int(ops.eva("(STO)")),
81
+ "fields": int(ops.cv.FieldCount),
82
+ "wavelengths": int(ops.cv.WavelengthCount),
83
+ "zooms": int(ops.cv.ZoomCount),
84
+ "surfaces": surfaces,
85
+ }
86
+
87
+
88
+ def _differences(want: dict, got: dict) -> list[str]:
89
+ def same(a: Any, b: Any) -> bool:
90
+ if isinstance(a, float) and isinstance(b, float):
91
+ return math.isclose(a, b, rel_tol=1e-12, abs_tol=1e-12)
92
+ return a == b
93
+
94
+ diffs = [f"{k}: {want[k]!r} -> {got.get(k)!r}" for k in want if k != "surfaces" and not same(want[k], got.get(k))]
95
+ ws, gs = want["surfaces"], got["surfaces"]
96
+ if len(ws) != len(gs):
97
+ diffs.append(f"surface count: {len(ws)} -> {len(gs)}")
98
+ else:
99
+ for i, (a, b) in enumerate(zip(ws, gs)):
100
+ if not all(same(x, y) for x, y in zip(a, b)):
101
+ diffs.append(f"surface {i}: {a} -> {b}")
102
+ return diffs
103
+
104
+
105
+ def _summary(fp: dict) -> dict:
106
+ return {"title": fp["title"], "efl": fp["efl"], "surfaces": len(fp["surfaces"]), "stop": fp["stop"]}
107
+
108
+
109
+ def save_in(engine: CodeVEngine, ops: Ops, label: str | None, note: str | None, overwrite: bool) -> dict:
110
+ """Same as ``save_snapshot``, inside an existing COM call (used by the idle timeout)."""
111
+ index = _load_index(engine)
112
+ name = label
113
+ if name is None:
114
+ used = [int(m.group(1)) for k in index if (m := re.fullmatch(r"snap-(\d+)", k))]
115
+ name = f"snap-{max(used, default=0) + 1:03d}"
116
+ if not _LABEL.match(name):
117
+ raise ValueError("Labels are 1-60 characters: letters, digits, '.', '_' or '-', starting with a letter or digit.")
118
+ if name in index and not overwrite:
119
+ return {"ok": False, "error_detail": f"Snapshot {name!r} exists; pass overwrite to replace it."}
120
+
121
+ path = _dir(engine) / f"{name}.len"
122
+ fp = fingerprint(ops)
123
+ r = ops.cmd(f'sav "{path}"')
124
+ if r["errors"] or not path.is_file():
125
+ return {"ok": False, "error_detail": "CODE V did not write the snapshot file.", "codev_errors": r["errors"]}
126
+ index[name] = {
127
+ "file": path.name,
128
+ "saved_at": time.strftime("%Y-%m-%d %H:%M:%S"),
129
+ "note": note or "",
130
+ "fingerprint": fp,
131
+ }
132
+ _prune_auto(engine, index)
133
+ _save_index(engine, index)
134
+ return {"label": name, "saved": _summary(fp), "path": str(path)}
135
+
136
+
137
+ def save_snapshot(engine: CodeVEngine, label: str | None, note: str | None, overwrite: bool) -> dict:
138
+ return engine.with_ops(lambda ops: save_in(engine, ops, label, note, overwrite))
139
+
140
+
141
+ def _prune_auto(engine: CodeVEngine, index: dict[str, dict]) -> None:
142
+ autos = sorted((k for k in index if k.startswith(AUTO_PREFIX)), key=lambda k: index[k]["saved_at"])
143
+ for k in autos[:-KEEP_AUTO]:
144
+ (_dir(engine) / index[k]["file"]).unlink(missing_ok=True)
145
+ del index[k]
146
+
147
+
148
+ def restore_in(engine: CodeVEngine, ops: Ops, label: str) -> dict:
149
+ """Same as ``restore_snapshot``, inside an existing COM call (used by the idle timeout)."""
150
+ index = _load_index(engine)
151
+ entry = index.get(label)
152
+ if entry is None:
153
+ return {"ok": False, "error_detail": f"No snapshot named {label!r}.", "available": sorted(index)}
154
+ path = _dir(engine) / entry["file"]
155
+ if not path.is_file():
156
+ return {"ok": False, "error_detail": f"Snapshot file is missing: {path}"}
157
+ r = ops.cmd(f'res "{path}"')
158
+ if r["errors"]:
159
+ return {"ok": False, "error_detail": "CODE V could not restore the file; the current lens is unchanged.",
160
+ "codev_errors": r["errors"]}
161
+ got = fingerprint(ops)
162
+ diffs = _differences(entry["fingerprint"], got)
163
+ out: dict[str, Any] = {"label": label, "restored": _summary(got), "saved_at": entry["saved_at"]}
164
+ if diffs:
165
+ out["ok"] = False
166
+ out["error_detail"] = "The restored lens does not match the snapshot's fingerprint."
167
+ out["differences"] = diffs[:20]
168
+ return out
169
+
170
+
171
+ def restore_snapshot(engine: CodeVEngine, label: str) -> dict:
172
+ return engine.with_ops(lambda ops: restore_in(engine, ops, label))
173
+
174
+
175
+ def list_snapshots(engine: CodeVEngine) -> dict:
176
+ index = _load_index(engine)
177
+ rows = [
178
+ {"label": k, "saved_at": v["saved_at"], "note": v["note"], **_summary(v["fingerprint"]),
179
+ "file_present": (_dir(engine) / v["file"]).is_file()}
180
+ for k, v in sorted(index.items(), key=lambda kv: kv[1]["saved_at"])
181
+ ]
182
+ return {"ok": True, "snapshots": rows, "directory": str(_dir(engine))}
183
+
184
+
185
+ def delete_snapshot(engine: CodeVEngine, label: str) -> dict:
186
+ index = _load_index(engine)
187
+ if label not in index:
188
+ return {"ok": False, "error_detail": f"No snapshot named {label!r}."}
189
+ (_dir(engine) / index[label]["file"]).unlink(missing_ok=True)
190
+ del index[label]
191
+ _save_index(engine, index)
192
+ return {"ok": True, "deleted": label}
193
+
194
+
195
+ def auto_label() -> str:
196
+ return f"{AUTO_PREFIX}{time.strftime('%Y%m%d-%H%M%S')}-{int(time.time() * 1000) % 1000:03d}"
197
+
198
+
199
+ __all__ = ["save_snapshot", "save_in", "restore_snapshot", "restore_in", "list_snapshots", "delete_snapshot", "auto_label", "CodeVError"]
codev_mcp/sysdata.py ADDED
@@ -0,0 +1,262 @@
1
+ """System data: fields, wavelengths and the aperture (pupil specification).
2
+
3
+ Each setter is confirmed by reading the result back. Two CODE V behaviours
4
+ are handled explicitly because they fail silently:
5
+
6
+ - Vignetting factors are stored per field number and do not follow the
7
+ fields: change three fields to four and the old factors stay on fields 2
8
+ and 3 (now different angles) while field 4 gets none. CODE V only warns.
9
+ set_fields therefore recomputes them from the apertures (SET VIG) by
10
+ default, or clears them, and reports them before and after.
11
+ - Object-space settings on an object at infinity are accepted but
12
+ meaningless (object-height fields, object NA); they are refused.
13
+
14
+ The pupil type (which of EPD, FNO, NA, NAO is held fixed) has no database
15
+ item; it is read from the SPECIFICATION DATA section of the lens listing.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import re
22
+ from typing import Any
23
+
24
+ from codev_mcp.engine import CodeVEngine, CodeVError, Ops
25
+
26
+ FIELD_TYPES = {
27
+ # name: (CODE V prefix, TYP FLD value)
28
+ "angle": ("AN", "ANG"),
29
+ "object_height": ("OB", "OBJ"),
30
+ "image_height": ("IM", "IMG"),
31
+ "real_image_height": ("RI", "RIH"),
32
+ }
33
+ TYPE_NAMES = {v[1]: k for k, v in FIELD_TYPES.items()}
34
+ PUPIL_TYPES = {"epd": "EPD", "fno": "FNO", "na": "NA", "nao": "NAO"}
35
+ UNITS = {"M": "mm", "C": "cm", "I": "inch"}
36
+ MAX_FIELDS, MAX_WAVELENGTHS = 25, 21
37
+ INFINITE = 1e9
38
+
39
+
40
+ def _num(x: float) -> str:
41
+ return f"{float(x):.12g}"
42
+
43
+
44
+ def _close(a: Any, b: float, rel: float = 1e-9) -> bool:
45
+ return isinstance(a, (int, float)) and math.isclose(float(a), float(b), rel_tol=rel, abs_tol=1e-9)
46
+
47
+
48
+ def _infinite_object(ops: Ops) -> bool:
49
+ return float(ops.eva("(THI SO)")) >= INFINITE
50
+
51
+
52
+ def pupil_type(ops: Ops) -> str | None:
53
+ text = ops.cmd("LIS")["output"]
54
+ i = text.find("SPECIFICATION DATA")
55
+ if i < 0:
56
+ return None
57
+ for line in text[i:].splitlines()[1:6]:
58
+ word = line.split()[0] if line.split() else ""
59
+ if word in PUPIL_TYPES.values():
60
+ return word
61
+ return None
62
+
63
+
64
+ def _fields(ops: Ops) -> dict:
65
+ n = int(ops.cv.FieldCount)
66
+ typ = str(ops.eva("(TYP FLD)")).strip()
67
+ prefix = FIELD_TYPES.get(TYPE_NAMES.get(typ, "angle"))[0]
68
+ rows = []
69
+ for f in range(1, n + 1):
70
+ row: dict[str, Any] = {"field": f, "x": ops.eva(f"(X{prefix} F{f})"), "y": ops.eva(f"(Y{prefix} F{f})"),
71
+ "weight": ops.eva(f"(WTF F{f})")}
72
+ vig = {}
73
+ for key in ("VUY", "VLY", "VUX", "VLX"):
74
+ value, errors, _ = ops.soft(lambda key=key: ops.eva(f"({key} F{f})"))
75
+ vig[key.lower()] = None if errors else value
76
+ row["vignetting"] = vig
77
+ rows.append(row)
78
+ return {"type": TYPE_NAMES.get(typ, typ), "count": n, "fields": rows}
79
+
80
+
81
+ def _wavelengths(ops: Ops) -> dict:
82
+ n = int(ops.cv.WavelengthCount)
83
+ rows = [{"wavelength": w, "nm": ops.eva(f"(WL W{w})"), "weight": ops.eva(f"(WTW W{w})")} for w in range(1, n + 1)]
84
+ return {"count": n, "wavelengths": rows, "reference": int(ops.eva("(REF)"))}
85
+
86
+
87
+ def _pupil(ops: Ops) -> dict:
88
+ out = {"type": None}
89
+ kind = pupil_type(ops)
90
+ out["type"] = next((k for k, v in PUPIL_TYPES.items() if v == kind), kind)
91
+ for key, item in PUPIL_TYPES.items():
92
+ value, errors, _ = ops.soft(lambda item=item: ops.eva(f"({item})"))
93
+ out[key] = None if errors else value
94
+ return out
95
+
96
+
97
+ def system_data_in(ops: Ops) -> dict:
98
+ thi_so = float(ops.eva("(THI SO)"))
99
+ return {
100
+ "units": UNITS.get(str(ops.eva("(DIM)")).strip(), str(ops.eva("(DIM)"))),
101
+ "object_distance": None if thi_so >= INFINITE else thi_so,
102
+ "object_at_infinity": thi_so >= INFINITE,
103
+ "afocal": float(ops.eva("(AFC)")) == 1.0,
104
+ "pupil": _pupil(ops),
105
+ "fields": _fields(ops),
106
+ "wavelengths": _wavelengths(ops),
107
+ }
108
+
109
+
110
+ def get_system_data(engine: CodeVEngine) -> dict:
111
+ return engine.with_ops(system_data_in)
112
+
113
+
114
+ # -- setters --------------------------------------------------------------------
115
+
116
+
117
+ def set_fields(engine: CodeVEngine, field_type: str, y: list[float], x: list[float] | None,
118
+ weights: list[float] | None, vignetting: str) -> dict:
119
+ if field_type not in FIELD_TYPES:
120
+ raise ValueError(f"field_type must be one of {sorted(FIELD_TYPES)}.")
121
+ if not 1 <= len(y) <= MAX_FIELDS:
122
+ raise ValueError(f"Give 1 to {MAX_FIELDS} fields.")
123
+ for name, values in (("x", x), ("weights", weights)):
124
+ if values is not None and len(values) != len(y):
125
+ raise ValueError(f"{name} must have one value per field ({len(y)}).")
126
+ if weights is not None and any(float(w) < 0 for w in weights):
127
+ raise ValueError("Field weights must not be negative.")
128
+ if field_type == "angle" and any(abs(float(v)) >= 90 for v in list(y) + list(x or [])):
129
+ raise ValueError("Field angles must be below 90 degrees (CODE V needs WID Y for wider fields).")
130
+ if vignetting not in ("recompute", "clear", "keep"):
131
+ raise ValueError("vignetting must be 'recompute', 'clear' or 'keep'.")
132
+ prefix, typ = FIELD_TYPES[field_type]
133
+
134
+ def fn(ops: Ops) -> dict:
135
+ if field_type == "object_height" and _infinite_object(ops):
136
+ return {"ok": False, "error_detail": "The object is at infinity, so object heights are meaningless; "
137
+ "use field_type 'angle' (or 'image_height')."}
138
+ before = _fields(ops)
139
+ errors: list[str] = []
140
+ warnings: list[str] = []
141
+
142
+ def run(text: str) -> None:
143
+ r = ops.cmd(text)
144
+ errors.extend(r["errors"])
145
+ warnings.extend(w for w in r["warnings"] if "check your vignetting" not in w)
146
+
147
+ run(f"Y{prefix} " + " ".join(_num(v) for v in y))
148
+ if x is not None:
149
+ run(f"X{prefix} " + " ".join(_num(v) for v in x))
150
+ if weights is not None:
151
+ run("WTF " + " ".join(_num(w) for w in weights))
152
+ n = len(y)
153
+ if vignetting == "recompute":
154
+ run("SET VIG")
155
+ elif vignetting == "clear":
156
+ for key in ("VUY", "VLY", "VUX", "VLX"):
157
+ run(f"{key} " + " ".join(["0"] * n))
158
+ after = _fields(ops)
159
+
160
+ problems = []
161
+ if after["type"] != field_type:
162
+ problems.append(f"field type reads back as {after['type']}, not {field_type}")
163
+ if after["count"] != n:
164
+ problems.append(f"{after['count']} fields read back, not {n}")
165
+ else:
166
+ for i, row in enumerate(after["fields"]):
167
+ if not _close(row["y"], y[i], 1e-7):
168
+ problems.append(f"field {i + 1} y reads back as {row['y']}, not {y[i]}")
169
+ if x is not None and not _close(row["x"], x[i], 1e-7):
170
+ problems.append(f"field {i + 1} x reads back as {row['x']}, not {x[i]}")
171
+ if weights is not None and not _close(row["weight"], weights[i]):
172
+ problems.append(f"field {i + 1} weight reads back as {row['weight']}")
173
+ out: dict[str, Any] = {"before": before, "after": after, "vignetting": vignetting,
174
+ "codev_warnings": warnings}
175
+ if vignetting == "keep" and before["count"] != n:
176
+ out["warning"] = ("Vignetting factors are stored per field number and were kept, so they no longer "
177
+ "match the fields. Recompute them (vignetting='recompute') unless you set them yourself.")
178
+ if errors or problems:
179
+ out["ok"] = False
180
+ out["error_detail"] = "; ".join(problems) or "CODE V reported errors"
181
+ return out
182
+
183
+ return engine.with_ops(fn)
184
+
185
+
186
+ def set_wavelengths(engine: CodeVEngine, nm: list[float], weights: list[int] | None, reference: int | None) -> dict:
187
+ if not 1 <= len(nm) <= MAX_WAVELENGTHS:
188
+ raise ValueError(f"Give 1 to {MAX_WAVELENGTHS} wavelengths.")
189
+ if any(float(w) <= 0 for w in nm):
190
+ raise ValueError("Wavelengths are in nm and must be positive.")
191
+ if weights is not None:
192
+ if len(weights) != len(nm):
193
+ raise ValueError(f"weights must have one value per wavelength ({len(nm)}).")
194
+ if any(int(w) != w or w < 0 for w in weights):
195
+ raise ValueError("Wavelength weights are non-negative integers in CODE V.")
196
+ if reference is not None and not 1 <= reference <= len(nm):
197
+ raise ValueError(f"reference must be a wavelength number, 1..{len(nm)}.")
198
+
199
+ def fn(ops: Ops) -> dict:
200
+ before = _wavelengths(ops)
201
+ errors, warnings = [], []
202
+ for text in (["WL " + " ".join(_num(v) for v in nm)]
203
+ + (["WTW " + " ".join(str(int(w)) for w in weights)] if weights is not None else [])
204
+ + ([f"REF {int(reference)}"] if reference is not None else [])):
205
+ r = ops.cmd(text)
206
+ errors += r["errors"]
207
+ warnings += r["warnings"]
208
+ after = _wavelengths(ops)
209
+ problems = []
210
+ if after["count"] != len(nm):
211
+ problems.append(f"{after['count']} wavelengths read back, not {len(nm)}")
212
+ else:
213
+ problems += [f"wavelength {i + 1} reads back as {row['nm']}" for i, row in enumerate(after["wavelengths"])
214
+ if not _close(row["nm"], nm[i], 1e-7)]
215
+ if weights is not None:
216
+ problems += [f"weight {i + 1} reads back as {row['weight']}" for i, row in enumerate(after["wavelengths"])
217
+ if not _close(row["weight"], weights[i])]
218
+ if reference is not None and after["reference"] != reference:
219
+ problems.append(f"reference reads back as {after['reference']}")
220
+ out: dict[str, Any] = {"before": before, "after": after, "codev_warnings": warnings}
221
+ if list(nm) != sorted(nm, reverse=True):
222
+ out["note"] = "CODE V recommends entering wavelengths from red to blue (descending)."
223
+ if errors or problems:
224
+ out["ok"] = False
225
+ out["error_detail"] = "; ".join(problems) or "CODE V reported errors"
226
+ return out
227
+
228
+ return engine.with_ops(fn)
229
+
230
+
231
+ def set_aperture(engine: CodeVEngine, kind: str, value: float) -> dict:
232
+ if kind not in PUPIL_TYPES:
233
+ raise ValueError(f"kind must be one of {sorted(PUPIL_TYPES)}.")
234
+ if not float(value) > 0:
235
+ raise ValueError("The aperture value must be positive.")
236
+ if kind in ("na", "nao") and float(value) >= 1.5:
237
+ raise ValueError("A numerical aperture of 1.5 or more is not physical here.")
238
+ item = PUPIL_TYPES[kind]
239
+
240
+ def fn(ops: Ops) -> dict:
241
+ if kind == "nao" and _infinite_object(ops):
242
+ return {"ok": False, "error_detail": "The object is at infinity, so an object-space NA is meaningless; "
243
+ "use 'epd', 'fno' or 'na'."}
244
+ before = _pupil(ops)
245
+ r = ops.cmd(f"{item} {_num(value)}")
246
+ after = _pupil(ops)
247
+ problems = []
248
+ if after["type"] != kind:
249
+ problems.append(f"pupil type reads back as {after['type']}, not {kind}")
250
+ if not _close(after.get(kind), value, 1e-7):
251
+ problems.append(f"{item} reads back as {after.get(kind)}, not {value}")
252
+ out: dict[str, Any] = {"before": before, "after": after, "codev_warnings": r["warnings"],
253
+ "note": f"{item} is now the fixed aperture setting; the others follow from it."}
254
+ if r["errors"] or problems:
255
+ out["ok"] = False
256
+ out["error_detail"] = "; ".join(problems) or "CODE V reported errors"
257
+ return out
258
+
259
+ return engine.with_ops(fn)
260
+
261
+
262
+ __all__ = ["get_system_data", "set_fields", "set_wavelengths", "set_aperture", "CodeVError"]