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/edits.py ADDED
@@ -0,0 +1,410 @@
1
+ """Typed lens edits that read every change back.
2
+
3
+ CODE V accepts some edits it then ignores: a thickness held by a solve keeps
4
+ its solved value, and a variable code can be overridden. So every change here
5
+ is confirmed by reading the lens afterwards, and a change that did not stick
6
+ is reported as a failure rather than assumed.
7
+
8
+ Edits stop at the first failure; ``applied`` lists what was changed before it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ import re
15
+ from typing import Any
16
+
17
+ from codev_mcp.engine import CodeVEngine, CodeVError, Ops
18
+
19
+ FLAT = 1e10 # CODE V reports a flat surface as radius 1e18
20
+ PARAMETER_CODES = {"radius": "CCY", "thickness": "THC", "glass": "GLC"}
21
+
22
+
23
+ # -- helpers --------------------------------------------------------------------
24
+
25
+
26
+ def _last(ops: Ops) -> int:
27
+ return int(ops.cv.SurfaceCount) - 1
28
+
29
+
30
+ def _name(ops: Ops, s: int) -> str:
31
+ """CODE V surface qualifier: SO for the object, SI for the image."""
32
+ last = _last(ops)
33
+ if not 0 <= s <= last:
34
+ raise ValueError(f"Surface {s} is outside 0..{last} (0 is the object, {last} the image).")
35
+ return "SO" if s == 0 else ("SI" if s == last else f"S{s}")
36
+
37
+
38
+ def _close(a: float, b: float) -> bool:
39
+ return math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-9)
40
+
41
+
42
+ def _first_order(ops: Ops) -> dict:
43
+ out = {}
44
+ for key, expr in (("efl", "(EFL)"), ("overall_length", "(OAL)"), ("stop_surface", "(STO)")):
45
+ try:
46
+ out[key] = ops.eva(expr)
47
+ except CodeVError:
48
+ out[key] = None
49
+ out["surfaces"] = _last(ops) + 1
50
+ return out
51
+
52
+
53
+ def _solve(ops: Ops, kind: str, s: int) -> str:
54
+ """Active solve on a surface's thickness (THI) or curvature (CUY), or ''."""
55
+ try:
56
+ return str(ops.eva(f"(TYP SOL {kind} {_name(ops, s)})") or "")
57
+ except CodeVError:
58
+ return ""
59
+
60
+
61
+ def _release(ops: Ops, kind: str, s: int, solve: str) -> dict:
62
+ # PIM is a system solve on the thickness before the image.
63
+ text = "PIM No" if solve == "PIM" else f"DEL SOL {kind} {_name(ops, s)}"
64
+ return ops.cmd(text)
65
+
66
+
67
+ def _clear_aperture(ops: Ops, n: str) -> float | None:
68
+ """Circular clear aperture, or None when the surface has none.
69
+
70
+ CODE V answers (CIR Sk) on such a surface with 0 and the warning
71
+ "Aperture has not been defined"; that warning comes from this read-back,
72
+ not from the caller's edit, so it is kept out of the envelope.
73
+ """
74
+ value, undefined = ops.eva_expecting(f"(CIR {n})", "Aperture has not been defined")
75
+ return None if undefined else value
76
+
77
+
78
+ def _surface_state(ops: Ops, s: int) -> dict:
79
+ n = _name(ops, s)
80
+ return {
81
+ "surface": s,
82
+ "radius": ops.eva(f"(RDY {n})"),
83
+ "thickness": ops.eva(f"(THI {n})"),
84
+ "glass": ops.eva(f"(GLA {n})"),
85
+ "clear_aperture": _clear_aperture(ops, n),
86
+ # No semi-diameter here: SD needs a ray trace, which fails (with
87
+ # errors) on intermediate lenses an edit can produce.
88
+ "thickness_solve": _solve(ops, "THI", s),
89
+ "curvature_solve": _solve(ops, "CUY", s),
90
+ }
91
+
92
+
93
+ def _glass_matches(requested: str, readback: Any) -> bool:
94
+ req, got = requested.strip().strip("'\"").upper(), str(readback).strip().upper()
95
+ if req in ("AIR", ""):
96
+ return got in ("AIR", "")
97
+ # CODE V reads back NBK7 for NBK7_SCHOTT.
98
+ return got == req or req.startswith(got + "_")
99
+
100
+
101
+ # -- control codes from the lens listing ----------------------------------------
102
+
103
+ _ROW = re.compile(r"^\s*>?\s*(OBJ|STO|IMG|\d+):")
104
+
105
+
106
+ def control_codes(ops: Ops) -> list[dict]:
107
+ """Per-surface CCY/THC/GLC codes, parsed from LIS.
108
+
109
+ The (VAR Ik) database items go stale after a variable is frozen or
110
+ coupled, so the listing is the reliable source.
111
+ """
112
+ text = ops.cmd("LIS")["output"]
113
+ lines = text.splitlines()
114
+ header_i = next((i for i, ln in enumerate(lines) if re.search(r"\bRDY\b.*\bTHI\b.*\bCCY\b", ln)), None)
115
+ if header_i is None:
116
+ raise CodeVError("Could not find the surface table in the lens listing.")
117
+ header = lines[header_i]
118
+ ends = {code: m.end() for code in ("CCY", "THC", "GLC") if (m := re.search(rf"\b{code}\b", header))}
119
+ first_col = min(m.start() for code in ends if (m := re.search(rf"\b{code}\b", header))) - 4
120
+ last, stop = _last(ops), int(ops.eva("(STO)"))
121
+ rows = []
122
+ for ln in lines[header_i + 1 :]:
123
+ if not ln.strip():
124
+ break
125
+ m = _ROW.match(ln)
126
+ if not m:
127
+ continue # continuation lines such as glass details
128
+ label = m.group(1)
129
+ surface = {"OBJ": 0, "IMG": last, "STO": stop}.get(label)
130
+ surface = int(label) if surface is None else surface
131
+ row: dict[str, Any] = {"surface": surface}
132
+ for tok in re.finditer(r"\S+", ln):
133
+ if tok.start() < first_col:
134
+ continue
135
+ code = min(ends, key=lambda c: abs(ends[c] - tok.end()))
136
+ if abs(ends[code] - tok.end()) <= 3:
137
+ row[code] = tok.group()
138
+ rows.append(row)
139
+ return rows
140
+
141
+
142
+ def _describe_code(value: str | None) -> str:
143
+ if value is None:
144
+ return "not applicable"
145
+ if value == "0":
146
+ return "variable"
147
+ if value == "100":
148
+ return "frozen"
149
+ if re.fullmatch(r"-?\d+", value):
150
+ return f"coupled (group {value})"
151
+ return f"solve {value}"
152
+
153
+
154
+ # -- tools ----------------------------------------------------------------------
155
+
156
+
157
+ def set_surface(
158
+ engine: CodeVEngine,
159
+ surface: int,
160
+ radius: float | None,
161
+ thickness: float | None,
162
+ glass: str | None,
163
+ clear_aperture: float | None,
164
+ release_solves: bool,
165
+ ) -> dict:
166
+ def fn(ops: Ops) -> dict:
167
+ n = _name(ops, surface)
168
+ before = _surface_state(ops, surface)
169
+ applied: list[dict] = []
170
+
171
+ def fail(field: str, message: str, **extra: Any) -> dict:
172
+ return {
173
+ "ok": False,
174
+ "surface": surface,
175
+ "failed_field": field,
176
+ "error_detail": message,
177
+ **extra,
178
+ "applied": applied,
179
+ "before": before,
180
+ "after": _surface_state(ops, surface),
181
+ }
182
+
183
+ if thickness is not None:
184
+ solve = before["thickness_solve"]
185
+ if solve:
186
+ if not release_solves:
187
+ return fail("thickness", f"Thickness is held by solve {solve}; pass release_solves to remove it.")
188
+ r = _release(ops, "THI", surface, solve)
189
+ if r["errors"]:
190
+ return fail("thickness", f"Could not remove solve {solve}.", codev_errors=r["errors"])
191
+ applied.append({"field": "thickness_solve", "removed": solve})
192
+ r = ops.cmd(f"THI {n} {thickness:.15g}")
193
+ got = ops.eva(f"(THI {n})")
194
+ if r["errors"] or not _close(got, thickness):
195
+ return fail("thickness", f"Thickness reads back as {got}, not {thickness}.", codev_errors=r["errors"])
196
+ applied.append({"field": "thickness", "from": before["thickness"], "to": got})
197
+
198
+ if radius is not None:
199
+ solve = before["curvature_solve"]
200
+ if solve:
201
+ if not release_solves:
202
+ return fail("radius", f"Curvature is held by solve {solve}; pass release_solves to remove it.")
203
+ r = _release(ops, "CUY", surface, solve)
204
+ if r["errors"]:
205
+ return fail("radius", f"Could not remove solve {solve}.", codev_errors=r["errors"])
206
+ applied.append({"field": "curvature_solve", "removed": solve})
207
+ flat = radius == 0 or math.isinf(radius) or abs(radius) >= FLAT
208
+ r = ops.cmd(f"CUY {n} 0" if flat else f"RDY {n} {radius:.15g}")
209
+ got = ops.eva(f"(RDY {n})")
210
+ ok = abs(got) >= FLAT if flat else _close(got, radius)
211
+ if r["errors"] or not ok:
212
+ return fail("radius", f"Radius reads back as {got}, not {radius}.", codev_errors=r["errors"])
213
+ applied.append({"field": "radius", "from": before["radius"], "to": "flat" if flat else got})
214
+
215
+ if glass is not None:
216
+ name = glass.strip() or "AIR"
217
+ r = ops.cmd(f"GLA {n} {name}")
218
+ got = ops.eva(f"(GLA {n})")
219
+ if r["errors"] or not _glass_matches(name, got):
220
+ return fail(
221
+ "glass",
222
+ f"Glass reads back as {got!r}, not {name!r}. Catalog glasses are NAME or "
223
+ "NAME_CATALOG, e.g. NBK7_SCHOTT; check the name with lookup_glass.",
224
+ codev_errors=r["errors"],
225
+ )
226
+ applied.append({"field": "glass", "from": before["glass"], "to": got, "codev_warnings": r["warnings"]})
227
+
228
+ if clear_aperture is not None:
229
+ r = ops.cmd(f"CIR {n} {clear_aperture:.15g}")
230
+ got = ops.eva(f"(CIR {n})")
231
+ if r["errors"] or not _close(got, clear_aperture):
232
+ return fail("clear_aperture", f"Clear aperture reads back as {got}.", codev_errors=r["errors"])
233
+ applied.append({"field": "clear_aperture", "from": before["clear_aperture"], "to": got})
234
+
235
+ if not applied:
236
+ return {"ok": False, "error_detail": "Nothing to change: give at least one field."}
237
+ return {
238
+ "surface": surface,
239
+ "applied": applied,
240
+ "before": before,
241
+ "after": _surface_state(ops, surface),
242
+ "first_order": _first_order(ops),
243
+ }
244
+
245
+ return engine.with_ops(fn)
246
+
247
+
248
+ def set_variables(engine: CodeVEngine, changes: list[dict], release_solves: bool = False) -> dict:
249
+ def fn(ops: Ops) -> dict:
250
+ if not changes:
251
+ return {"ok": False, "error_detail": "Give at least one change."}
252
+ commands = []
253
+ for ch in changes:
254
+ s, param, vary = int(ch["surface"]), ch["parameter"], bool(ch["vary"])
255
+ if param not in PARAMETER_CODES:
256
+ raise ValueError(f"parameter must be one of {sorted(PARAMETER_CODES)}, not {param!r}.")
257
+ commands.append((s, param, vary, f"{PARAMETER_CODES[param]} {_name(ops, s)} {0 if vary else 100}"))
258
+
259
+ # Varying a solved value makes CODE V delete the solve with only a
260
+ # warning (e.g. THC on the PIM thickness drops the image solve), so
261
+ # check every change first and apply none if any would do that.
262
+ conflicts = []
263
+ for s, param, vary, _ in commands:
264
+ if vary and param in ("radius", "thickness"):
265
+ kind = "CUY" if param == "radius" else "THI"
266
+ solve = _solve(ops, kind, s)
267
+ if solve:
268
+ conflicts.append({"surface": s, "parameter": param, "solve": solve, "kind": kind})
269
+ notes: list[str] = []
270
+ if conflicts and not release_solves:
271
+ return {
272
+ "ok": False,
273
+ "error_detail": "Some of these values are held by solves; varying them would delete "
274
+ "the solve. Nothing was changed. Pass release_solves to remove the solves and proceed.",
275
+ "solve_conflicts": [{k: c[k] for k in ("surface", "parameter", "solve")} for c in conflicts],
276
+ }
277
+ for c in conflicts:
278
+ r = _release(ops, c["kind"], c["surface"], c["solve"])
279
+ if r["errors"]:
280
+ return {"ok": False, "error_detail": f"Could not remove solve {c['solve']} on surface {c['surface']}.",
281
+ "codev_errors": r["errors"]}
282
+ notes.append(f"Removed solve {c['solve']} on surface {c['surface']} {c['parameter']}.")
283
+
284
+ results, failed = [], 0
285
+ for s, param, vary, text in commands:
286
+ r = ops.cmd(text)
287
+ results.append({"surface": s, "parameter": param, "requested": "vary" if vary else "freeze",
288
+ "command": text, "codev_errors": r["errors"]})
289
+ if param == "glass" and vary:
290
+ notes.append(
291
+ f"Surface {s}: a variable glass is replaced by a fictitious glass model "
292
+ "(shown as its glass code). Pick a real glass afterwards with set_surface."
293
+ )
294
+
295
+ # Read every code back from the listing, after all changes.
296
+ codes = {row["surface"]: row for row in control_codes(ops)}
297
+ for res in results:
298
+ code = PARAMETER_CODES[res["parameter"]]
299
+ got = codes.get(res["surface"], {}).get(code)
300
+ res["now"] = _describe_code(got)
301
+ want = "variable" if res["requested"] == "vary" else "frozen"
302
+ if res["codev_errors"] or res["now"] != want:
303
+ res["error"] = f"Reads back as {res['now']}, not {want}."
304
+ failed += 1
305
+ if not res["codev_errors"]:
306
+ del res["codev_errors"]
307
+ out: dict[str, Any] = {"results": results, "notes": notes}
308
+ if failed:
309
+ out["ok"] = False
310
+ out["failed_rows"] = failed
311
+ return out
312
+
313
+ return engine.with_ops(fn)
314
+
315
+
316
+ def list_variables_in(ops: Ops) -> dict:
317
+ """Same as ``list_variables``, inside an existing COM call."""
318
+ variables, coupled, solves = [], [], []
319
+ for row in control_codes(ops):
320
+ for param, code in PARAMETER_CODES.items():
321
+ value = row.get(code)
322
+ desc = _describe_code(value)
323
+ entry = {"surface": row["surface"], "parameter": param}
324
+ if desc == "variable":
325
+ variables.append(entry)
326
+ elif desc.startswith("coupled"):
327
+ coupled.append({**entry, "group": int(value)})
328
+ elif desc.startswith("solve"):
329
+ solves.append({**entry, "solve": value})
330
+ return {
331
+ "variables": variables,
332
+ "coupled": coupled,
333
+ "solves": solves,
334
+ "note": "Everything not listed is frozen. Coupled entries with the same group vary "
335
+ "together; a negative group varies with opposite sign.",
336
+ }
337
+
338
+
339
+ def list_variables(engine: CodeVEngine) -> dict:
340
+ return engine.with_ops(list_variables_in)
341
+
342
+
343
+ def insert_surface(
344
+ engine: CodeVEngine, at: int, radius: float | None, thickness: float | None, glass: str | None
345
+ ) -> dict:
346
+ def fn(ops: Ops) -> dict:
347
+ last = _last(ops)
348
+ if not 1 <= at <= last:
349
+ raise ValueError(f"Insert position must be 1..{last}; the new surface goes before the current surface {at}.")
350
+ n_before, stop_before = last + 1, int(ops.eva("(STO)"))
351
+ r = ops.cmd(f"INS S{at}")
352
+ n_after = _last(ops) + 1
353
+ if r["errors"] or n_after != n_before + 1:
354
+ return {"ok": False, "error_detail": f"Surface count went {n_before} -> {n_after}.",
355
+ "codev_errors": r["errors"]}
356
+ return {
357
+ "inserted_at": at,
358
+ "surfaces": n_after,
359
+ "stop_surface": {"before": stop_before, "after": int(ops.eva("(STO)"))},
360
+ "new_surface": _surface_state(ops, at),
361
+ "note": "The new surface is flat, air and zero thickness until set; "
362
+ "surfaces from here on are renumbered up by one.",
363
+ }
364
+
365
+ result = engine.with_ops(fn)
366
+ if result["ok"] and any(v is not None for v in (radius, thickness, glass)):
367
+ result["set"] = set_surface(engine, at, radius, thickness, glass, None, False)
368
+ result["ok"] = result["set"]["ok"]
369
+ return result
370
+
371
+
372
+ def delete_surface(engine: CodeVEngine, surface: int) -> dict:
373
+ def fn(ops: Ops) -> dict:
374
+ last = _last(ops)
375
+ if not 1 <= surface <= last - 1:
376
+ raise ValueError(f"Only surfaces 1..{last - 1} can be deleted (not the object or image).")
377
+ stop_before = int(ops.eva("(STO)"))
378
+ removed = _surface_state(ops, surface)
379
+ r = ops.cmd(f"DEL S{surface}")
380
+ n_after = _last(ops) + 1
381
+ if r["errors"] or n_after != last:
382
+ return {"ok": False, "error_detail": f"Surface count went {last + 1} -> {n_after}.",
383
+ "codev_errors": r["errors"]}
384
+ stop_after = int(ops.eva("(STO)"))
385
+ out = {
386
+ "deleted": removed,
387
+ "surfaces": n_after,
388
+ "stop_surface": {"before": stop_before, "after": stop_after},
389
+ "first_order": _first_order(ops),
390
+ }
391
+ if surface == stop_before:
392
+ out["warning"] = f"The deleted surface was the stop; CODE V moved it to surface {stop_after}."
393
+ return out
394
+
395
+ return engine.with_ops(fn)
396
+
397
+
398
+ def set_stop(engine: CodeVEngine, surface: int) -> dict:
399
+ def fn(ops: Ops) -> dict:
400
+ last = _last(ops)
401
+ if not 1 <= surface <= last - 1:
402
+ raise ValueError(f"The stop must be on surface 1..{last - 1}.")
403
+ before = int(ops.eva("(STO)"))
404
+ r = ops.cmd(f"STO S{surface}")
405
+ after = int(ops.eva("(STO)"))
406
+ if r["errors"] or after != surface:
407
+ return {"ok": False, "error_detail": f"Stop reads back as surface {after}.", "codev_errors": r["errors"]}
408
+ return {"stop_surface": {"before": before, "after": after}, "first_order": _first_order(ops)}
409
+
410
+ return engine.with_ops(fn)