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/tolerance.py ADDED
@@ -0,0 +1,363 @@
1
+ """Tolerance analysis with CODE V's TOR (wavefront differential tolerancing).
2
+
3
+ TOR's results exist only in its listing, so this module parses it. Per field
4
+ and zoom position TOR prints a sensitivity block: the nominal
5
+ performance (RMS wavefront or MTF), one row per tolerance with the change in
6
+ performance for plus and minus errors and the compensator moves, the
7
+ probable change, and a cumulative-probability table. A closing PERFORMANCE
8
+ SUMMARY gives each field's design value and its value with tolerances.
9
+
10
+ TOR has two modes. Sensitivity (SNS) evaluates the tolerances as they are;
11
+ inverse sensitivity (INV, TOR's own default) resizes each variable tolerance
12
+ so that it alone causes a set degradation, and writes those sizes into the
13
+ lens. When the lens has no tolerances TOR generates its default set, and the
14
+ back focus as compensator when none is defined. In every case this module
15
+ leaves the lens's tolerances and compensators as they were.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import re
21
+ import time
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from codev_mcp import snapshots, toldata
26
+ from codev_mcp.engine import CodeVEngine, Ops
27
+
28
+ NUM = r"-?\d+\.\d*(?:[eE][-+]?\d+)?"
29
+ ROW = re.compile(rf"^\s+([A-Z]{{2,4}}(?:\s+[A-Z]{{1,3}}\d*)?\s+S[\dI][\d.I]*(?:\s+[A-Z0-9']+)?)\s+({NUM})([a-z]?)\s+({NUM})\s+({NUM})((?:\s+{NUM})*)\s*$")
30
+ CUMULATIVE = re.compile(rf"^\s*(\d+\.\d)\s+PCT\.\s+({NUM})")
31
+ # Inverse mode heads each block INVERSE SENSITIVITY, sensitivity mode SENSITIVITY ANALYSIS.
32
+ BLOCK = r"(?:I N V E R S E\s+)?S E N S I T I V I T Y(?:\s+A N A L Y S I S)?"
33
+
34
+
35
+ def _ordered(name: str) -> str:
36
+ """TOR can print a range backwards (RLY S8..7); list it low to high, as TLI does."""
37
+ return re.sub(r"S(\d+)\.\.(\d+)", lambda m: f"S{min(int(m.group(1)), int(m.group(2)))}.."
38
+ f"{max(int(m.group(1)), int(m.group(2)))}", name)
39
+
40
+
41
+ def _blocks(listing: str) -> list[str]:
42
+ parts = re.split(BLOCK, listing)
43
+ return parts[1:]
44
+
45
+
46
+ def _field_block(block: str, position: int) -> dict[str, Any]:
47
+ out: dict[str, Any] = {"zoom": position}
48
+ criterion = "mtf" if "MODULATION TRANSFER FUNCTION" in block[:400] else "rms"
49
+ out["criterion"] = criterion
50
+ if m := re.search(r"FIELD \(X,Y\) = \(\s*(" + NUM + r"),\s*(" + NUM + r")\)MAX,\s*\(\s*(" + NUM + r"),\s*(" + NUM
51
+ + r")\)(\w+)", block):
52
+ out["field_relative"] = [float(m.group(1)), float(m.group(2))]
53
+ out["field_value"] = [float(m.group(3)), float(m.group(4))]
54
+ out["field_units"] = m.group(5).lower()
55
+ if m := re.search(r"FIELD WEIGHT =\s*(" + NUM + ")", block):
56
+ out["field_weight"] = float(m.group(1))
57
+ if m := re.search(r"NOMINAL (?:RMS|MTF)\s+=\s*(" + NUM + ")", block):
58
+ out["nominal"] = float(m.group(1))
59
+ if criterion == "mtf":
60
+ if m := re.search(r"FREQUENCY =\s*(" + NUM + ")", block):
61
+ out["frequency"] = float(m.group(1))
62
+ if m := re.search(r"AZIMUTH\s+=\s*(\w+)", block):
63
+ out["azimuth"] = m.group(1).lower()
64
+ if m := re.search(r"DIFFRACTION LIMITED MTF =\s*(" + NUM + ")", block):
65
+ out["diffraction_limit"] = float(m.group(1))
66
+
67
+ header = re.search(r"TYPE\s+CHANGE\s+MANUFACTURING ERRORS\s*(.*)", block)
68
+ compensators = re.findall(r"[A-Z]{2,4}\s+S[\dI][\d.I]*", header.group(1)) if header else []
69
+ out["compensators"] = compensators
70
+ rows = []
71
+ for line in block.splitlines():
72
+ m = ROW.match(line)
73
+ if not m:
74
+ continue
75
+ moves = [float(v) for v in m.group(6).split()]
76
+ rows.append({
77
+ "tolerance": _ordered(re.sub(r"\s+", " ", m.group(1).strip())),
78
+ "value": float(m.group(2)),
79
+ "variable": m.group(3) == "v",
80
+ "change_plus": float(m.group(4)),
81
+ "change_minus": float(m.group(5)),
82
+ "compensator_moves": dict(zip(compensators, moves)),
83
+ })
84
+ out["tolerances_listed"] = len(rows)
85
+ out["sensitivities"] = rows
86
+ if m := re.search(r"PROBABLE CHANGE IN (?:RMS|MTF)\s+(" + NUM + ")", block):
87
+ out["probable_change"] = float(m.group(1))
88
+ if m := re.search(r"PROBABLE CHANGE OF COMPENSATORS \(\+/-\)\s+((?:" + NUM + r"\s*)+)", block):
89
+ out["compensator_range"] = dict(zip(compensators, [float(v) for v in m.group(1).split()]))
90
+ cumulative = {}
91
+ for line in block.splitlines():
92
+ if m := CUMULATIVE.match(line):
93
+ cumulative[m.group(1) + "%"] = float(m.group(2))
94
+ out["cumulative"] = cumulative
95
+ # Printed beside the cumulative table, so other text sits between the words.
96
+ if m := re.search(r"97\.7 percent.*?probable change in (?:RMS|MTF) is\s+(" + NUM + ")", block, re.S):
97
+ out["extreme_97_7"] = float(m.group(1))
98
+ return out
99
+
100
+
101
+ def parse_listing(listing: str) -> dict[str, Any]:
102
+ fields = []
103
+ positions = [int(p) for p in re.findall(r"POSITION\s+(\d+)\s*\n\s*\n?\s*" + BLOCK, listing)]
104
+ for i, block in enumerate(_blocks(listing)):
105
+ fields.append(_field_block(block, positions[i] if i < len(positions) else 1))
106
+ summary = []
107
+ if "P E R F O R M A N C E" in listing:
108
+ tail = listing.split("P E R F O R M A N C E", 1)[1]
109
+ # RMS rows: field, weight, design, design+tol, compensators. MTF rows add
110
+ # frequency and azimuth (TAN, RAD or degrees) before the weight. Decide
111
+ # from the header, not per row: a numeric azimuth would otherwise be
112
+ # indistinguishable from a weight followed by a design value.
113
+ mtf = bool(re.search(r"RELATIVE\s+FREQ", tail))
114
+ extra = rf"{NUM}\s+(?:TAN|RAD|{NUM})\s+" if mtf else ""
115
+ for m in re.finditer(rf"^\s+({NUM}),\s*({NUM})\s+{extra}({NUM})\s+({NUM})\s+({NUM})"
116
+ rf"((?:\s+{NUM})*)\s*$", tail, re.M):
117
+ summary.append({"field_relative": [float(m.group(1)), float(m.group(2))], "weight": float(m.group(3)),
118
+ "design": float(m.group(4)), "design_plus_tolerances": float(m.group(5))})
119
+ return {"fields": fields, "summary": summary}
120
+
121
+
122
+ def _report(parsed: dict, top: int) -> dict[str, Any]:
123
+ fields = parsed["fields"]
124
+ if not fields:
125
+ return {"ok": False, "error_detail": "No sensitivity tables found in the TOR listing."}
126
+ criterion = fields[0]["criterion"]
127
+ by_field = []
128
+ for i, f in enumerate(fields):
129
+ rows = sorted(f["sensitivities"], key=lambda r: -max(abs(r["change_plus"]), abs(r["change_minus"])))
130
+ entry = {k: f.get(k) for k in ("zoom", "field_relative", "field_value", "field_units", "nominal",
131
+ "probable_change", "cumulative", "extreme_97_7", "compensator_range",
132
+ "frequency", "azimuth", "diffraction_limit") if f.get(k) is not None}
133
+ if i < len(parsed["summary"]):
134
+ entry["with_tolerances_97_7"] = parsed["summary"][i]["design_plus_tolerances"]
135
+ entry["top_sensitivities"] = rows[:top]
136
+ entry["tolerances_listed"] = f["tolerances_listed"]
137
+ by_field.append(entry)
138
+ sign = 1.0 if criterion == "rms" else -1.0 # RMS grows when worse, MTF falls
139
+
140
+ def as_built(e: dict) -> float:
141
+ value = e.get("with_tolerances_97_7")
142
+ if value is None:
143
+ value = (e.get("nominal") or 0.0) + (e.get("probable_change") or 0.0)
144
+ return sign * value
145
+
146
+ def summary(e: dict) -> dict:
147
+ return {"field_relative": e.get("field_relative"), "zoom": e.get("zoom"),
148
+ "probable_change": e.get("probable_change"), "with_tolerances_97_7": e.get("with_tolerances_97_7")}
149
+
150
+ # Worst field: the poorest performance with tolerances (what a threshold is checked
151
+ # against); the largest change can be a field with margin to spare.
152
+ worst = max(by_field, key=as_built)
153
+ largest = max(by_field, key=lambda e: sign * (e.get("probable_change") or 0.0))
154
+ return {
155
+ "criterion": criterion,
156
+ "units": "waves RMS" if criterion == "rms" else "MTF modulation",
157
+ "compensators": fields[0]["compensators"],
158
+ "fields": by_field,
159
+ "worst_field": summary(worst),
160
+ "largest_change_field": summary(largest),
161
+ "note": "Probable change is the 97.7% value assuming a Gaussian distribution of the performance; "
162
+ "with_tolerances_97_7 is the design value plus that change (CODE V's PERFORMANCE SUMMARY). "
163
+ "Changes are for plus and minus errors of the listed size; compensator moves are in lens units "
164
+ "or radians. variable: inverse mode may resize the tolerance (the 'v' in CODE V's listing). "
165
+ "worst_field has the poorest value with tolerances; largest_change_field the largest change.",
166
+ }
167
+
168
+
169
+ def _split_name(name: str) -> dict[str, Any] | None:
170
+ """'RLY S8..7 R' -> type, surfaces (in order) and qualifiers, as set_tolerances takes them."""
171
+ m = re.match(r"^([A-Z]{2,4})\s+S(\d+|I)(?:\.\.(\d+|I))?\s*(.*)$", name)
172
+ if not m or "I" in (m.group(2), m.group(3)):
173
+ return None
174
+ first, end = int(m.group(2)), int(m.group(3)) if m.group(3) else None
175
+ if end is not None and end < first:
176
+ first, end = end, first
177
+ out: dict[str, Any] = {"type": m.group(1), "surface": first}
178
+ if end is not None and end != first:
179
+ out["end_surface"] = end
180
+ if m.group(4).strip():
181
+ out["qualifiers"] = " ".join(m.group(4).split())
182
+ return out
183
+
184
+
185
+ def budget(parsed: dict, lens_rows: list[dict], target: float) -> list[dict]:
186
+ """Every tolerance inverse mode sized, with the lens's value and whether a limit clipped it.
187
+
188
+ Inverse mode sizes each variable tolerance so that it alone changes
189
+ performance by the target, then clips the size to the tolerance type's
190
+ limits. A worst change far from the target therefore means the size sits
191
+ at a limit: below it (too sensitive, at the minimum) or above it
192
+ (insensitive, at the maximum).
193
+ """
194
+ criterion = parsed["fields"][0]["criterion"] if parsed["fields"] else "rms"
195
+ sign = 1.0 if criterion == "rms" else -1.0
196
+ rows: dict[str, dict[str, Any]] = {}
197
+ for f in parsed["fields"]:
198
+ for r in f["sensitivities"]:
199
+ harm = max(sign * r["change_plus"], sign * r["change_minus"])
200
+ entry = rows.setdefault(r["tolerance"], {"tolerance": r["tolerance"], "value": r["value"],
201
+ "variable": r["variable"], "worst_change": harm})
202
+ entry["worst_change"] = max(entry["worst_change"], harm)
203
+ by_name = {}
204
+ for lr in lens_rows:
205
+ key = (lr["type"], lr["surface"], lr.get("end_surface"), lr.get("qualifiers", ""))
206
+ by_name[key] = lr["value"]
207
+ out = []
208
+ for name, entry in rows.items():
209
+ spec = _split_name(name)
210
+ row: dict[str, Any] = {"tolerance": name, "sized_value": entry["value"],
211
+ "worst_change": round(sign * entry["worst_change"], 6), "variable": entry["variable"]}
212
+ if spec:
213
+ key = (spec["type"], spec["surface"], spec.get("end_surface"), spec.get("qualifiers", ""))
214
+ if key in by_name:
215
+ row["lens_value"] = by_name[key]
216
+ row["entry"] = {**spec, "value": entry["value"]}
217
+ if entry["variable"]:
218
+ if entry["worst_change"] > 1.5 * target:
219
+ row["limited"] = "at its minimum: the change exceeds the target even at the smallest size allowed"
220
+ elif entry["worst_change"] < 0.5 * target:
221
+ row["limited"] = "at its maximum: insensitive, the change stays below the target"
222
+ out.append(row)
223
+ out.sort(key=lambda r: -abs(r["worst_change"]))
224
+ return out
225
+
226
+
227
+ MODES = {"sensitivity": "SNS", "inverse": "INV"}
228
+
229
+
230
+ def build_command(criterion: str, frequency: float | None, azimuth: str, mode: str = "sensitivity",
231
+ degradation: float | None = None) -> str:
232
+ if mode not in MODES:
233
+ raise ValueError("mode must be 'sensitivity' or 'inverse'.")
234
+ head = ["TOR", MODES[mode]]
235
+ if degradation is not None:
236
+ if mode != "inverse":
237
+ raise ValueError("degradation applies only to mode 'inverse'.")
238
+ if not float(degradation) > 0:
239
+ raise ValueError("degradation must be positive (an RMS increase or an MTF drop).")
240
+ head[1] = f"INV {float(degradation):.12g}"
241
+ if criterion == "rms":
242
+ return "; ".join(head + ["GO"])
243
+ if criterion != "mtf":
244
+ raise ValueError("criterion must be 'rms' or 'mtf'.")
245
+ if frequency is None or not float(frequency) > 0:
246
+ raise ValueError("MTF tolerancing needs a positive frequency (cycles/mm).")
247
+ if azimuth not in ("tan", "rad"):
248
+ raise ValueError("azimuth must be 'tan' or 'rad'.")
249
+ return "; ".join(head + [f"FRE {float(frequency):.12g}", f"AZI {azimuth.upper()}", "GO"])
250
+
251
+
252
+ def _backup_path(engine: CodeVEngine) -> Path:
253
+ folder = Path(engine.start_dir) / "tolerancing"
254
+ folder.mkdir(parents=True, exist_ok=True)
255
+ return folder / "before-tor.len"
256
+
257
+
258
+ def run(engine: CodeVEngine, criterion: str, frequency: float | None, azimuth: str, top: int,
259
+ wait_s: float, mode: str = "sensitivity", degradation: float | None = None) -> dict:
260
+ command = build_command(criterion, frequency, azimuth, mode, degradation)
261
+ top = max(1, min(int(top), 50))
262
+ backup = _backup_path(engine)
263
+
264
+ def prepare(ops: Ops) -> dict:
265
+ state = {"tolerances": int(ops.eva("(NUM TOL)")), "compensators": int(ops.eva("(NUM CMP)")),
266
+ "last": int(ops.cv.SurfaceCount) - 1, "backup": None}
267
+ # Inverse mode rewrites the lens's variable tolerances with the values
268
+ # it generates; keep a copy so they can be put back.
269
+ if mode == "inverse" and state["tolerances"]:
270
+ backup.unlink(missing_ok=True)
271
+ r = ops.cmd(f'sav "{backup}"')
272
+ if r["errors"] or not backup.is_file():
273
+ return {"ok": False, "error_detail": "Could not save a copy of the lens before TOR.",
274
+ "codev_errors": r["errors"]}
275
+ state["backup"] = str(backup)
276
+ state["fingerprint"] = snapshots.fingerprint(ops)
277
+ # TOR generates its default set itself only the first time in a session;
278
+ # after that a lens without tolerances gets a broken set. So generate
279
+ # the same defaults explicitly (with the focus compensator TOR would add)
280
+ # and remove them afterwards.
281
+ if state["tolerances"] == 0:
282
+ r = ops.cmd(f"DEF TOL S1..{state['last'] - 1}")
283
+ state["generated"] = int(ops.eva("(NUM TOL)"))
284
+ if r["errors"] or not state["generated"]:
285
+ return {"ok": False, "error_detail": "Could not generate default tolerances for TOR.",
286
+ "codev_errors": r["errors"]}
287
+ if state["compensators"] == 0:
288
+ ops.cmd(f"CMP DLZ S{state['last']}")
289
+ if mode == "inverse":
290
+ # The values before TOR resizes them, for the budget.
291
+ state["lens_tolerances"] = toldata.parse_tli(ops.cmd("TLI SA FUL ALL")["output"], state["last"])["tolerances"]
292
+ return state
293
+
294
+ before = engine.with_ops(prepare)
295
+ if not before.get("ok", True) or "tolerances" not in before:
296
+ return before
297
+ started = engine.async_start(command)
298
+ if not started.get("started"):
299
+ return started
300
+ errors, warnings = list(started.get("errors", [])), list(started.get("warnings", []))
301
+ deadline = time.time() + max(0.0, min(float(wait_s), 600.0))
302
+ while time.time() < deadline:
303
+ poll = engine.async_poll(1000)
304
+ errors += poll.get("errors", [])
305
+ warnings += poll.get("warnings", [])
306
+ if not poll.get("executing"):
307
+ break
308
+ else:
309
+ return {"executing": True, "command": command,
310
+ "hint": "TOR is still running. Call poll_long_command, or stop_long_command to halt it. Tolerances "
311
+ "TOR generated or resized stay in the lens; check with list_tolerances."}
312
+
313
+ def finish(ops: Ops) -> dict:
314
+ # The full listing: command output returned elsewhere is clipped for size.
315
+ out = {"listing": engine.command_output()}
316
+ last = before["last"]
317
+ if before["tolerances"] == 0:
318
+ out["tolerances_used"] = (f"CODE V's default set ({before['generated']} tolerances), generated for this "
319
+ "run and removed after")
320
+ ops.cmd(f"DEL TOL S0..{last} ALL")
321
+ else:
322
+ out["tolerances_used"] = f"the lens's own {before['tolerances']} tolerances"
323
+ if before["compensators"] == 0 and int(ops.eva("(NUM CMP)")) > 0:
324
+ ops.cmd(f"DEL CMP S0..{last}")
325
+ out["compensators_used"] = f"focus (DLZ S{last}), added for this run and removed after"
326
+ if before["backup"]:
327
+ r = ops.cmd(f'res "{before["backup"]}"')
328
+ diffs = snapshots._differences(before["fingerprint"], snapshots.fingerprint(ops))
329
+ if r["errors"] or diffs:
330
+ out["restore_problem"] = {"errors": r["errors"], "differences": diffs[:10],
331
+ "backup": before["backup"]}
332
+ else:
333
+ Path(before["backup"]).unlink(missing_ok=True)
334
+ out["lens_tolerances_after"] = int(ops.eva("(NUM TOL)"))
335
+ return out
336
+
337
+ done = engine.with_ops(finish)
338
+ listing = done.pop("listing", "")
339
+ errors += done.get("errors", [])
340
+ warnings += done.get("warnings", [])
341
+ parsed = parse_listing(listing)
342
+ report = _report(parsed, top)
343
+ report.update(command=command, mode=mode, errors=errors + report.get("errors", []), warnings=warnings,
344
+ **{k: done[k] for k in ("tolerances_used", "compensators_used", "restore_problem") if k in done})
345
+ if mode == "inverse" and parsed["fields"]:
346
+ report["budget"] = budget(parsed, before.get("lens_tolerances", []), degradation or 0.01)
347
+ report["note"] = INVERSE_NOTE + " " + report.get("note", "")
348
+ report.setdefault("ok", True)
349
+ if errors or "restore_problem" in done:
350
+ report["ok"] = False
351
+ if not report.get("ok", True) and "error_detail" in report:
352
+ report["listing_tail"] = listing[-1500:]
353
+ return report
354
+
355
+
356
+ INVERSE_NOTE = ("Inverse mode: TOR sized each variable tolerance so that it alone degrades performance by the "
357
+ "target (default 0.01), within its limits; the values listed are those sizes, not the lens's "
358
+ "own tolerances, which are left as they were. budget lists every tolerance with its sized "
359
+ "value, the lens's value, its worst change over the fields, and `limited` where a size sits at "
360
+ "the type's minimum or maximum; each `entry` can be passed to set_tolerances as it is.")
361
+
362
+
363
+ __all__ = ["parse_listing", "build_command", "run"]