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/toldata.py ADDED
@@ -0,0 +1,339 @@
1
+ """Tolerances and compensators stored in the lens (LDM), with read-back.
2
+
3
+ Commands: ``DEF TOL Si..j`` generates CODE V's default set for a centred
4
+ system; ``<type> Sk|Si..j [Zk] [C] [V|F] [R] [L'label'] [value]`` enters one
5
+ tolerance (without a value, its default); ``CMP <type> ...`` enters a
6
+ compensator; ``DEL <type> ...``, ``DEL TOL Si..j ALL`` and ``DEL CMP ...``
7
+ delete. There is no database item per tolerance, so read-back parses
8
+ ``TLI SA FUL ALL``.
9
+
10
+ Qualifiers are part of a tolerance's identity: CODE V's defaults include
11
+ rolls of cemented groups with ``R`` (``RLY S7..8 R``), and entering
12
+ ``RLY S7..8`` adds a second, separate tolerance rather than changing it.
13
+
14
+ The ``v`` after a value in TLI and TOR listings marks a tolerance that TOR's
15
+ inverse-sensitivity mode may resize (qualifier ``V``, the default); without it
16
+ the tolerance is frozen at its value (``F``).
17
+
18
+ Changes are all or nothing: the lens is saved first and put back if any
19
+ command is rejected or any read-back disagrees.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+ from pathlib import Path
26
+ from typing import Any, Callable
27
+
28
+ from codev_mcp import snapshots
29
+ from codev_mcp.engine import CodeVEngine, Ops
30
+
31
+ NUM = r"-?\d+\.\d*(?:[eE][-+]?\d+)?"
32
+ ROW = re.compile(rf"^\s*(\d+)\s+([A-Z]{{2,4}})\s+S([\dIO]+)(?:\.\.([\dIO]+))?((?:\s+[A-Z][\w'.]*)*?)\s+({NUM})(?:\s*([a-z]))?\s*$")
33
+ TYPE = re.compile(r"^[A-Z]{2,4}$")
34
+ RESERVED = {"TOL", "CMP", "DEF", "DEL", "TLI", "TOR", "SAV", "RES", "LIS", "GO", "CAN", "END", "IN", "OUT"}
35
+ # Qualifier tokens in the order CODE V's syntax gives them.
36
+ QUALIFIER_ORDER = [("Z", re.compile(r"^Z\d+$")), ("C", re.compile(r"^C\d*$")), ("VF", re.compile(r"^[VF]$")),
37
+ ("R", re.compile(r"^R$")), ("L", re.compile(r"^L'[^']{0,3}'$"))]
38
+ UNITS = {
39
+ **dict.fromkeys(("DLF", "IRR", "CYD", "CYN"), "fringes"),
40
+ **dict.fromkeys(("BTX", "BTY", "BTI"), "radians"),
41
+ **dict.fromkeys(("TRX", "TRY", "TIR"), "lens units (TIR)"),
42
+ "DLN": "index", "DLV": "fraction of the V-number",
43
+ }
44
+
45
+
46
+ def units_of(kind: str) -> str:
47
+ return UNITS.get(kind, "lens units")
48
+
49
+
50
+ def _last(ops: Ops) -> int:
51
+ return int(ops.cv.SurfaceCount) - 1
52
+
53
+
54
+ def _surface_number(token: str, last: int) -> int:
55
+ if token == "O":
56
+ return 0
57
+ if token == "I":
58
+ return last
59
+ return int(token)
60
+
61
+
62
+ def normalize_qualifiers(text: str | None) -> tuple[str, str | None]:
63
+ """Qualifiers in CODE V's order, and the V/F flag split out (None if not given).
64
+
65
+ Raises ValueError for a token CODE V would not take as a qualifier.
66
+ """
67
+ tokens = re.findall(r"L'[^']*'|\S+", (text or "").strip())
68
+ slots: dict[str, str] = {}
69
+ for raw in tokens:
70
+ tok = raw if raw.startswith("L'") else raw.upper()
71
+ for slot, pattern in QUALIFIER_ORDER:
72
+ if pattern.match(tok):
73
+ if slot in slots:
74
+ raise ValueError(f"qualifier {tok!r} repeats {slots[slot]!r}.")
75
+ slots[slot] = tok
76
+ break
77
+ else:
78
+ raise ValueError(f"{raw!r} is not a tolerance qualifier (Zk, C, V, F, R or L'abc').")
79
+ flag = slots.pop("VF", None)
80
+ return " ".join(slots[s] for s, _ in QUALIFIER_ORDER if s in slots), flag
81
+
82
+
83
+ def parse_tli(text: str, last: int) -> dict[str, Any]:
84
+ """Tolerance and compensator rows from a ``TLI ... FUL`` listing."""
85
+ out: dict[str, Any] = {"tolerances": [], "compensators": []}
86
+ section = None
87
+ for line in text.splitlines():
88
+ stripped = line.strip()
89
+ if stripped == "TOLERANCES":
90
+ section = "tolerances"
91
+ continue
92
+ if stripped == "COMPENSATORS":
93
+ section = "compensators"
94
+ continue
95
+ if m := re.search(r"Maximum number of compensators:\s*(\d+)", line):
96
+ out["max_compensators"] = int(m.group(1))
97
+ if section is None or not (m := ROW.match(line)):
98
+ continue
99
+ first = _surface_number(m.group(3), last)
100
+ end = _surface_number(m.group(4), last) if m.group(4) else None
101
+ if end is not None and end < first:
102
+ first, end = end, first
103
+ row: dict[str, Any] = {
104
+ "index": int(m.group(1)),
105
+ "type": m.group(2),
106
+ "surface": first,
107
+ "value": float(m.group(6)),
108
+ "units": units_of(m.group(2)),
109
+ "variable": m.group(7) == "v",
110
+ }
111
+ if end is not None:
112
+ row["end_surface"] = end
113
+ if m.group(5).strip():
114
+ row["qualifiers"] = " ".join(m.group(5).split())
115
+ out[section].append(row)
116
+ return out
117
+
118
+
119
+ def _surfaces(first: int, end: int | None) -> str:
120
+ return f"S{first}" if end is None or end == first else f"S{first}..{end}"
121
+
122
+
123
+ def describe(row: dict) -> str:
124
+ text = f"{row['type']} {_surfaces(row['surface'], row.get('end_surface'))}"
125
+ return f"{text} {row['qualifiers']}" if row.get("qualifiers") else text
126
+
127
+
128
+ def _read(ops: Ops) -> dict[str, Any]:
129
+ last = _last(ops)
130
+ parsed = parse_tli(ops.cmd("TLI SA FUL ALL")["output"], last)
131
+ parsed["tolerance_count"] = int(ops.eva("(NUM TOL)"))
132
+ parsed["compensator_count"] = int(ops.eva("(NUM CMP)"))
133
+ return parsed
134
+
135
+
136
+ def _validate(entry: dict, last: int, what: str, need_type: bool = True) -> str | None:
137
+ kind = entry.get("type")
138
+ if not (kind is None and not need_type) and (not isinstance(kind, str) or not TYPE.match(kind) or kind in RESERVED):
139
+ return f"{what}: type must be a CODE V tolerance code such as DLT, DLR, DSY (got {kind!r})."
140
+ s, e = entry.get("surface"), entry.get("end_surface")
141
+ if not isinstance(s, int) or not 0 <= s <= last:
142
+ return f"{what}: surface must be 0..{last}."
143
+ if e is not None and (not isinstance(e, int) or not s <= e <= last):
144
+ return f"{what}: end_surface must be {s}..{last}."
145
+ v = entry.get("value")
146
+ if v is not None and not float(v) > 0:
147
+ return f"{what}: value must be positive (tolerances apply as plus and minus)."
148
+ try:
149
+ normalize_qualifiers(entry.get("qualifiers"))
150
+ except ValueError as exc:
151
+ return f"{what}: {exc}"
152
+ return None
153
+
154
+
155
+ def _find(rows: list[dict], kind: str | None, first: int, end: int | None, qualifiers: str | None,
156
+ any_qualifiers: bool = False) -> list[dict]:
157
+ """Rows with this type, range and qualifiers (V/F aside: TLI shows them as the 'v' flag)."""
158
+ end = None if end == first else end
159
+ want = normalize_qualifiers(qualifiers)[0]
160
+ return [r for r in rows if (kind is None or r["type"] == kind) and r["surface"] == first
161
+ and r.get("end_surface") == end and (any_qualifiers or r.get("qualifiers", "") == want)]
162
+
163
+
164
+ def _same(a: float, b: float) -> bool:
165
+ return abs(a - b) <= 1e-9 + 1e-6 * abs(b)
166
+
167
+
168
+ def _entry_command(prefix: str, entry: dict) -> str:
169
+ quals, flag = normalize_qualifiers(entry.get("qualifiers"))
170
+ parts = [prefix + entry["type"], _surfaces(entry["surface"], entry.get("end_surface"))]
171
+ # CODE V's order: Zk C V|F R L'label'.
172
+ tokens = quals.split()
173
+ head = [t for t in tokens if t[0] in "ZC" and not t.startswith("L'")]
174
+ tail = [t for t in tokens if t not in head]
175
+ parts += head + ([flag] if flag else []) + tail
176
+ if entry.get("value") is not None:
177
+ parts.append(f"{float(entry['value']):.12g}")
178
+ return " ".join(parts)
179
+
180
+
181
+ def _backup(engine: CodeVEngine) -> Path:
182
+ folder = Path(engine.start_dir) / "tolerancing"
183
+ folder.mkdir(parents=True, exist_ok=True)
184
+ return folder / "before-tolerance-change.len"
185
+
186
+
187
+ def _atomic(engine: CodeVEngine, ops: Ops, change: Callable[[], dict]) -> dict:
188
+ """Run ``change``; if it reports rejected or failed steps, put the lens back."""
189
+ backup = _backup(engine)
190
+ backup.unlink(missing_ok=True)
191
+ fingerprint = snapshots.fingerprint(ops)
192
+ r = ops.cmd(f'sav "{backup}"')
193
+ if r["errors"] or not backup.is_file():
194
+ return {"ok": False, "error_detail": "Could not save a copy of the lens before the change; nothing was changed.",
195
+ "codev_errors": r["errors"]}
196
+ out = change()
197
+ if out.get("rejected") or out.get("failed") or out.get("still_present"):
198
+ _, errors, warnings = ops.soft(lambda: ops.cmd(f'res "{backup}"'))
199
+ diffs = snapshots._differences(fingerprint, snapshots.fingerprint(ops))
200
+ state = _read(ops)
201
+ out.update(ok=False, tolerance_count=state["tolerance_count"], compensator_count=state["compensator_count"])
202
+ if errors or diffs:
203
+ out["rolled_back"] = False
204
+ out["restore_problem"] = {"errors": errors, "differences": diffs[:10], "copy": str(backup)}
205
+ else:
206
+ out["rolled_back"] = True
207
+ out["note"] = "Nothing was changed: the lens was put back as it was before this call."
208
+ if out.get("rolled_back") is not False:
209
+ backup.unlink(missing_ok=True)
210
+ return out
211
+
212
+
213
+ def list_tolerances(engine: CodeVEngine) -> dict:
214
+ def fn(ops: Ops) -> dict:
215
+ out = _read(ops)
216
+ out["note"] = ("variable: TOR's inverse-sensitivity mode may resize it; otherwise it is frozen at its value. "
217
+ "qualifiers are part of a tolerance's identity (e.g. R on a cemented roll): give them to "
218
+ "set_tolerances or delete_tolerances to address that row. index is the number TLI gives; it "
219
+ "shifts when tolerances are deleted.")
220
+ return out
221
+ return engine.with_ops(fn)
222
+
223
+
224
+ def set_tolerances(engine: CodeVEngine, defaults: dict | None, tolerances: list[dict],
225
+ compensators: list[dict]) -> dict:
226
+ def fn(ops: Ops) -> dict:
227
+ last = _last(ops)
228
+ problems = []
229
+ if defaults is not None:
230
+ a, b = defaults.get("first"), defaults.get("last")
231
+ if not (isinstance(a, int) and isinstance(b, int) and 0 <= a <= b <= last):
232
+ problems.append(f"defaults: first and last must satisfy 0 <= first <= last <= {last}.")
233
+ problems += [p for i, t in enumerate(tolerances) if (p := _validate(t, last, f"tolerances[{i}]"))]
234
+ problems += [p for i, c in enumerate(compensators) if (p := _validate(c, last, f"compensators[{i}]"))]
235
+ if problems:
236
+ return {"ok": False, "error_detail": " ".join(problems)}
237
+ if not (defaults or tolerances or compensators):
238
+ return {"ok": False, "error_detail": "Nothing to set: give defaults, tolerances or compensators."}
239
+
240
+ steps: list[tuple[str, str, dict | None]] = []
241
+ if defaults is not None:
242
+ steps.append(("defaults", f"DEF TOL S{defaults['first']}..{defaults['last']}", None))
243
+ steps += [("tolerance", _entry_command("", t), t) for t in tolerances]
244
+ steps += [("compensator", _entry_command("CMP ", c), c) for c in compensators]
245
+
246
+ def change() -> dict:
247
+ initial = _read(ops)
248
+ rejected = []
249
+ for _kind, command, _entry in steps:
250
+ r = ops.cmd(command)
251
+ if r["errors"]:
252
+ rejected.append({"command": command, "errors": r["errors"]})
253
+ state = _read(ops)
254
+ applied, failed, notes = [], [], []
255
+ for kind, command, entry in steps:
256
+ if kind == "defaults":
257
+ continue
258
+ section = "tolerances" if kind == "tolerance" else "compensators"
259
+ rows = state[section]
260
+ found = _find(rows, entry["type"], entry["surface"], entry.get("end_surface"), entry.get("qualifiers"))
261
+ flag = normalize_qualifiers(entry.get("qualifiers"))[1]
262
+ if not found:
263
+ failed.append({"command": command, "reason": "not in the lens after the command"})
264
+ elif entry.get("value") is not None and not _same(found[0]["value"], float(entry["value"])):
265
+ failed.append({"command": command, "reason": f"read back {found[0]['value']}"})
266
+ elif flag is not None and found[0]["variable"] != (flag == "V"):
267
+ failed.append({"command": command, "reason": f"read back as {'variable' if found[0]['variable'] else 'frozen'}"})
268
+ else:
269
+ applied.append({"command": command, "read_back": found[0]})
270
+ # Same type and range under other qualifiers: usually a duplicate by mistake.
271
+ others = [r for r in _find(initial[section], entry["type"], entry["surface"],
272
+ entry.get("end_surface"), None, any_qualifiers=True)
273
+ if r.get("qualifiers", "") != found[0].get("qualifiers", "")]
274
+ if others:
275
+ notes.append(f"{command}: the lens also has {', '.join(describe(o) for o in others)}; "
276
+ "pass its qualifiers to change that one instead of adding another.")
277
+ out: dict[str, Any] = {"applied": applied, "tolerance_count": state["tolerance_count"],
278
+ "compensator_count": state["compensator_count"]}
279
+ if defaults is not None:
280
+ out["defaults_added"] = state["tolerance_count"] - initial["tolerance_count"]
281
+ for key, value in (("rejected", rejected), ("failed", failed), ("notes", notes)):
282
+ if value:
283
+ out[key] = value
284
+ return out
285
+
286
+ return _atomic(engine, ops, change)
287
+ return engine.with_ops(fn)
288
+
289
+
290
+ def delete_tolerances(engine: CodeVEngine, tolerances: list[dict], compensators: list[dict],
291
+ everything: bool) -> dict:
292
+ def fn(ops: Ops) -> dict:
293
+ last = _last(ops)
294
+ problems = [p for i, t in enumerate(tolerances) if (p := _validate(t, last, f"tolerances[{i}]", False))]
295
+ problems += [p for i, c in enumerate(compensators) if (p := _validate(c, last, f"compensators[{i}]", False))]
296
+ if problems:
297
+ return {"ok": False, "error_detail": " ".join(problems)}
298
+ if not (everything or tolerances or compensators):
299
+ return {"ok": False, "error_detail": "Nothing to delete: give tolerances, compensators or everything."}
300
+ commands = [f"DEL TOL S0..{last} ALL", f"DEL CMP S0..{last}"] if everything else []
301
+ # DEL takes no V|F flag.
302
+ tol_refs = [{**t, "qualifiers": normalize_qualifiers(t.get("qualifiers"))[0]} for t in tolerances]
303
+ cmp_refs = [{**c, "qualifiers": normalize_qualifiers(c.get("qualifiers"))[0]} for c in compensators]
304
+ for t in tol_refs:
305
+ commands.append(_entry_command("DEL ", t) if t.get("type") else
306
+ f"DEL TOL {_surfaces(t['surface'], t.get('end_surface'))}")
307
+ for c in cmp_refs:
308
+ commands.append(_entry_command("DEL CMP ", c) if c.get("type") else
309
+ f"DEL CMP {_surfaces(c['surface'], c.get('end_surface'))}")
310
+
311
+ def change() -> dict:
312
+ rejected = []
313
+ for command in commands:
314
+ r = ops.cmd(command)
315
+ if r["errors"]:
316
+ rejected.append({"command": command, "errors": r["errors"]})
317
+ state = _read(ops)
318
+ remaining = []
319
+ for section, refs, prefix in (("tolerances", tol_refs, ""), ("compensators", cmp_refs, "CMP ")):
320
+ for t in refs:
321
+ remaining += [prefix + describe(r) for r in _find(
322
+ state[section], t.get("type"), t["surface"], t.get("end_surface"), t.get("qualifiers"),
323
+ any_qualifiers=not t.get("type"))]
324
+ if everything and (state["tolerance_count"] or state["compensator_count"]):
325
+ remaining.append(f"{state['tolerance_count']} tolerances and {state['compensator_count']} compensators")
326
+ out: dict[str, Any] = {"commands": commands, "tolerance_count": state["tolerance_count"],
327
+ "compensator_count": state["compensator_count"]}
328
+ if rejected:
329
+ out["rejected"] = rejected
330
+ if remaining:
331
+ out["still_present"] = remaining
332
+ return out
333
+
334
+ return _atomic(engine, ops, change)
335
+ return engine.with_ops(fn)
336
+
337
+
338
+ __all__ = ["parse_tli", "list_tolerances", "set_tolerances", "delete_tolerances", "describe",
339
+ "normalize_qualifiers", "units_of"]