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.
@@ -0,0 +1,278 @@
1
+ """Monte Carlo tolerancing with CODE V's TOLMONTE macro, for yield.
2
+
3
+ TOLMONTE reads a saved .len file, perturbs it by all its tolerances at once
4
+ for each trial, compensates with AUT (the TOLCOMP macro) on whatever the lens
5
+ has as variables, and evaluates a metric per zoom and field. So the run is
6
+ prepared on a copy: every variable is frozen, the requested compensators are
7
+ made variables, and that copy is saved. Afterwards the session is put back to
8
+ the lens as it was.
9
+
10
+ Trial values come from the ``.dat`` file TOLMONTE writes beside the lens (one
11
+ line per trial and zoom, one column per field); the nominal values and the
12
+ cumulative table of changes come from the listing.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ import re
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from codev_mcp import edits, snapshots
24
+ from codev_mcp.engine import CodeVEngine, Ops
25
+
26
+ NUM = r"-?\d+\.\d*(?:[eE][-+]?\d+)?"
27
+ METRICS = {
28
+ "spot": ("tolspot", "geometric RMS spot diameter, lens units"),
29
+ "mtf": ("tolmtf", "MTF modulation"),
30
+ "strehl": ("tolstrehl", "Strehl ratio (from the PSF)"),
31
+ "encircled_energy": ("tolenc", "diameter enclosing the given energy, lens units"),
32
+ }
33
+ # Output options, one Y/N each: tolerance summary, plot, plot per zoom, per-trial
34
+ # listing, write trial sequences, reference rays, accumulate, compensate the
35
+ # nominal first, uniform 2D decenters. Trial values are read from the .dat file.
36
+ OPTIONS = "NNNNNNNYN"
37
+ CODES = edits.PARAMETER_CODES
38
+ _pending: dict[int, dict[str, Any]] = {}
39
+
40
+
41
+ def build_command(lens: str, metric: str, trials: int, frequency: float | None, azimuth: str,
42
+ percent: float | None) -> str:
43
+ if metric not in METRICS:
44
+ raise ValueError(f"metric must be one of {', '.join(METRICS)}.")
45
+ if not 1 <= int(trials) <= 10000:
46
+ raise ValueError("trials must be 1 to 10000.")
47
+ params = ""
48
+ if metric == "mtf":
49
+ if frequency is None or not float(frequency) > 0:
50
+ raise ValueError("The MTF metric needs a positive frequency (cycles/mm).")
51
+ if azimuth not in ("tan", "rad"):
52
+ raise ValueError("azimuth must be 'tan' or 'rad'.")
53
+ # MTF_1FLD azimuth in degrees: 90 tangential, 0 radial; 64 rays across the pupil.
54
+ params = f" {float(frequency):.12g} {90 if azimuth == 'tan' else 0} 64"
55
+ elif metric == "encircled_energy":
56
+ p = 80.0 if percent is None else float(percent)
57
+ if not 0 < p < 100:
58
+ raise ValueError("percent must be between 0 and 100.")
59
+ params = f" {p:.12g}"
60
+ return f'in cv_macro:tolmonte "{lens}" {METRICS[metric][0]} tolcomp {int(trials)} {OPTIONS}{params}'
61
+
62
+
63
+ def parse_listing(text: str) -> dict[str, Any]:
64
+ out: dict[str, Any] = {"compensators": [], "cumulative": []}
65
+ if m := re.search(r"AUTO variables used for compensation\s*\n((?:\s*\d+\s+[A-Z]{3}\s+S\w+\s*\n)+)", text):
66
+ out["compensators"] = [" ".join(x.split()[1:]) for x in m.group(1).strip().splitlines()]
67
+ if "CUMULATIVE PROBABILITY" in text:
68
+ tail = text.split("CUMULATIVE PROBABILITY", 1)[1]
69
+ has_zoom = bool(re.search(r"^\s*Zoom\s+Field\s+50", tail, re.M))
70
+ zoom = 1
71
+ for line in tail.splitlines():
72
+ if "TOLERANCE SUMMARY" in line or "Data for plotting" in line:
73
+ break
74
+ m = re.match(rf"^\s+(\d+)(?:\s+(\d+))?\s+({NUM})\s+({NUM})\s+({NUM})\s+({NUM})\s*$", line)
75
+ if not m:
76
+ continue
77
+ if m.group(2):
78
+ zoom, field = int(m.group(1)), int(m.group(2))
79
+ else:
80
+ field = int(m.group(1))
81
+ zoom = zoom if has_zoom else 1
82
+ out["cumulative"].append({"zoom": zoom, "field": field, "change": dict(zip(
83
+ ("50.0%", "84.1%", "97.7%", "99.9%"), (float(m.group(i)) for i in range(3, 7))))})
84
+ if m := re.search(r"Monte-Carlo analysis - (\d+) trials", text):
85
+ out["trials_reported"] = int(m.group(1))
86
+ return out
87
+
88
+
89
+ def parse_dat(text: str) -> dict[str, Any]:
90
+ """TOLMONTE's plot data: header, per-zoom summary lines, then trials x zooms lines."""
91
+ lines = [ln for ln in text.splitlines() if ln.strip()]
92
+ head = lines[0].split("\t")
93
+ zooms = int(lines[1].split("\t")[0])
94
+ fields = int(lines[2].split("\t")[0])
95
+ summaries = [[float(v) for v in ln.split()] for ln in lines[3:3 + zooms]]
96
+ rows = [[float(v) for v in ln.split()] for ln in lines[3 + zooms:]]
97
+ trials = len(rows) // zooms
98
+ values = {(z + 1, f + 1): [rows[t * zooms + z][f] for t in range(trials)]
99
+ for z in range(zooms) for f in range(fields)}
100
+ nominal = {(z + 1, f + 1): summaries[z][3 * f] for z in range(zooms) for f in range(fields)}
101
+ return {"description": head[0].strip(), "degradation": int(float(head[2])), "zooms": zooms, "fields": fields,
102
+ "trials": trials, "values": values, "nominal": nominal}
103
+
104
+
105
+ def _quantile(sorted_values: list[float], q: float) -> float:
106
+ if len(sorted_values) == 1:
107
+ return sorted_values[0]
108
+ pos = q * (len(sorted_values) - 1)
109
+ lo = math.floor(pos)
110
+ hi = min(lo + 1, len(sorted_values) - 1)
111
+ return sorted_values[lo] + (sorted_values[hi] - sorted_values[lo]) * (pos - lo)
112
+
113
+
114
+ def summarize(dat: dict, listing: dict, threshold: float | None) -> dict[str, Any]:
115
+ worse_up = dat["degradation"] >= 0 # +1: a larger value is worse (spot); -1: smaller is worse (MTF)
116
+ cumulative = {(c["zoom"], c["field"]): c["change"] for c in listing.get("cumulative", [])}
117
+ per_field = []
118
+ passes_all = [True] * dat["trials"]
119
+ for key, vals in dat["values"].items():
120
+ s = sorted(vals)
121
+ n = len(s)
122
+ mean = sum(s) / n
123
+ std = math.sqrt(sum((v - mean) ** 2 for v in s) / (n - 1)) if n > 1 else 0.0
124
+ # "p% of builds are at least this good": an upper quantile when larger is worse.
125
+ good = {f"{p}%": round(_quantile(s, p / 100 if worse_up else 1 - p / 100), 6) for p in (50, 84.1, 97.7)}
126
+ entry: dict[str, Any] = {"zoom": key[0], "field": key[1], "nominal": dat["nominal"][key],
127
+ "mean": round(mean, 6), "std": round(std, 6), "best": s[0] if worse_up else s[-1],
128
+ "worst": s[-1] if worse_up else s[0], "builds_at_least_this_good": good}
129
+ if key in cumulative:
130
+ entry["codev_change_cumulative"] = cumulative[key]
131
+ if threshold is not None:
132
+ ok = [(v <= threshold) if worse_up else (v >= threshold) for v in vals]
133
+ entry["yield"] = round(sum(ok) / n, 4)
134
+ passes_all = [a and b for a, b in zip(passes_all, ok)]
135
+ per_field.append(entry)
136
+ out: dict[str, Any] = {"trials": dat["trials"], "metric_description": dat["description"],
137
+ "larger_is_worse": worse_up, "fields": per_field}
138
+ if threshold is not None:
139
+ out["threshold"] = threshold
140
+ out["yield_all_fields"] = round(sum(passes_all) / dat["trials"], 4) if dat["trials"] else None
141
+ worst = min(per_field, key=lambda e: e["yield"])
142
+ out["lowest_yield_field"] = {"zoom": worst["zoom"], "field": worst["field"], "yield": worst["yield"]}
143
+ return out
144
+
145
+
146
+ def _paths(engine: CodeVEngine) -> dict[str, Path]:
147
+ folder = Path(engine.start_dir) / "tolerancing"
148
+ folder.mkdir(parents=True, exist_ok=True)
149
+ return {"before": folder / "before-monte-carlo.len", "lens": folder / "monte-carlo.len",
150
+ "dat": folder / "monte-carlo.dat"}
151
+
152
+
153
+ def start(engine: CodeVEngine, trials: int, metric: str, frequency: float | None, azimuth: str,
154
+ percent: float | None, compensators: list[dict] | None, threshold: float | None,
155
+ wait_s: float) -> dict:
156
+ if id(engine) in _pending:
157
+ return {"ok": False, "error_detail": "A Monte Carlo run is already in progress; call get_monte_carlo_result."}
158
+ paths = _paths(engine)
159
+ command = build_command(str(paths["lens"]), metric, trials, frequency, azimuth, percent)
160
+
161
+ def prepare(ops: Ops) -> dict:
162
+ tolerances = int(ops.eva("(NUM TOL)"))
163
+ if tolerances == 0:
164
+ return {"ok": False, "error_detail": "The lens has no tolerances. Add them with set_tolerances "
165
+ "(defaults generates CODE V's standard set) first."}
166
+ last = int(ops.cv.SurfaceCount) - 1
167
+ comps = compensators if compensators is not None else [{"surface": last - 1, "parameter": "thickness"}]
168
+ for c in comps:
169
+ if not (isinstance(c.get("surface"), int) and 0 <= c["surface"] < last and c.get("parameter") in CODES):
170
+ return {"ok": False, "error_detail": f"Compensator {c} needs a surface 0..{last - 1} and a "
171
+ "parameter: radius, thickness or glass."}
172
+ for p in paths.values():
173
+ p.unlink(missing_ok=True)
174
+ fingerprint = snapshots.fingerprint(ops)
175
+ r = ops.cmd(f'sav "{paths["before"]}"')
176
+ if r["errors"] or not paths["before"].is_file():
177
+ return {"ok": False, "error_detail": "Could not save a copy of the lens.", "codev_errors": r["errors"]}
178
+ # Freeze everything, then vary only the compensators. Solves are kept,
179
+ # except on a compensator (varying a solved value replaces the solve).
180
+ ops.cmd("CCY SA 100; THC SA 100; GLC SA 100")
181
+ setup_warnings = []
182
+ for c in comps:
183
+ r = ops.cmd(f"{CODES[c['parameter']]} S{c['surface']} 0")
184
+ setup_warnings += r["warnings"]
185
+ # Informational only: what TOLMONTE will see as variables.
186
+ listed, _, _ = ops.soft(lambda: edits.list_variables_in(ops)["variables"])
187
+ variables = listed or []
188
+ r = ops.cmd(f'sav "{paths["lens"]}"')
189
+ if r["errors"] or not paths["lens"].is_file():
190
+ ops.cmd(f'res "{paths["before"]}"')
191
+ return {"ok": False, "error_detail": "Could not save the prepared lens.", "codev_errors": r["errors"]}
192
+ return {"tolerances": tolerances, "variables": variables, "fingerprint": fingerprint,
193
+ "setup_notes": [w.split("\n")[0].strip() for w in setup_warnings]}
194
+
195
+ prep = engine.with_ops(prepare)
196
+ if not prep.get("ok", True) or "fingerprint" not in prep:
197
+ return prep
198
+ started = engine.async_start(command)
199
+ if not started.get("started"):
200
+ engine.with_ops(lambda ops: {"restore": ops.cmd(f'res "{paths["before"]}"')["errors"]})
201
+ return started
202
+ _pending[id(engine)] = {
203
+ "paths": paths, "command": command, "metric": metric, "threshold": threshold, "trials": trials,
204
+ "fingerprint": prep["fingerprint"], "compensators_requested": prep["variables"],
205
+ "tolerances": prep["tolerances"], "setup_notes": prep["setup_notes"], "started": time.time(),
206
+ "errors": list(started.get("errors", [])), "warnings": list(started.get("warnings", [])),
207
+ }
208
+ return result(engine, wait_s)
209
+
210
+
211
+ def result(engine: CodeVEngine, wait_s: float) -> dict:
212
+ job = _pending.get(id(engine))
213
+ if job is None:
214
+ return {"ok": False, "error_detail": "No Monte Carlo run is in progress. Start one with monte_carlo."}
215
+ deadline = time.time() + max(0.0, min(float(wait_s), 1800.0))
216
+ while True:
217
+ poll = engine.async_poll(1000)
218
+ job["errors"] += poll.get("errors", [])
219
+ job["warnings"] += poll.get("warnings", [])
220
+ if not poll.get("executing"):
221
+ break
222
+ if time.time() >= deadline:
223
+ return {"executing": True, "elapsed_s": round(time.time() - job["started"]),
224
+ "trials": job["trials"],
225
+ "hint": "Still running. Call get_monte_carlo_result again to wait; stop_long_command "
226
+ "halts it (then call get_monte_carlo_result to put the lens back)."}
227
+ paths = job["paths"]
228
+
229
+ def finish(ops: Ops) -> dict:
230
+ listing = engine.command_output()
231
+ r = ops.cmd(f'res "{paths["before"]}"')
232
+ diffs = snapshots._differences(job["fingerprint"], snapshots.fingerprint(ops))
233
+ out: dict[str, Any] = {"listing": listing}
234
+ if r["errors"] or diffs:
235
+ out["restore_problem"] = {"errors": r["errors"], "differences": diffs[:10], "copy": str(paths["before"])}
236
+ return out
237
+
238
+ try:
239
+ done = engine.with_ops(finish)
240
+ finally:
241
+ _pending.pop(id(engine), None)
242
+ listing_text = done.get("listing", "")
243
+ listing = parse_listing(listing_text)
244
+ errors = job["errors"] + done.get("errors", [])
245
+ warnings = job["warnings"] + done.get("warnings", [])
246
+ report: dict[str, Any] = {"metric": job["metric"], "units": METRICS[job["metric"]][1],
247
+ "tolerances": job["tolerances"], "seconds": round(time.time() - job["started"], 1)}
248
+ if paths["dat"].is_file():
249
+ try:
250
+ report.update(summarize(parse_dat(paths["dat"].read_text(encoding="utf-8", errors="replace")),
251
+ listing, job["threshold"]))
252
+ except (ValueError, IndexError) as exc:
253
+ report["ok"] = False
254
+ report["error_detail"] = f"Could not read TOLMONTE's data file: {exc}"
255
+ else:
256
+ report["ok"] = False
257
+ report["error_detail"] = "TOLMONTE wrote no data file; it may have failed or been stopped."
258
+ report["compensators"] = listing["compensators"]
259
+ if not listing["compensators"]:
260
+ report["compensators_note"] = "No compensation: the trials were evaluated as perturbed."
261
+ if job["setup_notes"]:
262
+ report["setup_notes"] = job["setup_notes"]
263
+ report["note"] = ("Each trial applies all tolerances at once with random values (truncated Gaussian), "
264
+ "compensates with AUT on the listed variables, and evaluates the metric. The nominal is "
265
+ "first re-optimized on the compensators, so it can differ slightly from the session's lens. "
266
+ "builds_at_least_this_good gives the value that 50/84.1/97.7% of trials meet or beat. "
267
+ "The session's lens is put back as it was.")
268
+ report["errors"], report["warnings"] = errors, warnings
269
+ if "restore_problem" in done:
270
+ report["restore_problem"] = done["restore_problem"]
271
+ report["ok"] = False
272
+ report.setdefault("ok", not errors)
273
+ if not report["ok"]:
274
+ report["listing_tail"] = listing_text[-1500:]
275
+ return report
276
+
277
+
278
+ __all__ = ["build_command", "parse_listing", "parse_dat", "summarize", "start", "result"]
codev_mcp/optimize.py ADDED
@@ -0,0 +1,279 @@
1
+ """Typed optimization: build the AUT run from structured input, run it, read the result.
2
+
3
+ The run is assembled from validated parts (no free command text), the lens is
4
+ snapshotted first, and the result is read from CODE V's own database items
5
+ (AUT.ERF for the error function and its parts) rather than parsed from the
6
+ listing; only the per-cycle history comes from the listing. Each constraint's
7
+ achieved value is read back so the caller can see whether it was met.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import time
14
+ from typing import Any
15
+
16
+ from codev_mcp import edits, snapshots
17
+ from codev_mcp.engine import CodeVEngine, CodeVError, Ops
18
+
19
+ QUANTITY = re.compile(r"^[A-Z][A-Z0-9]{1,5}$")
20
+ QUALIFIERS = re.compile(r"^[A-Za-z0-9 .]*$") # e.g. "S3", "S1..11", "Z2 F3", "MEC"
21
+ INVALID_ERF = 9.999e9
22
+ EQUALITY_TOLERANCE = 1e-4
23
+
24
+ THICKNESS_LIMITS = {
25
+ "max_center": "MXT",
26
+ "min_center": "MNT",
27
+ "min_edge": "MNE",
28
+ "min_air_axial": "MNA",
29
+ "min_air_edge": "MAE",
30
+ }
31
+
32
+ # The last run's specification, so a result can be collected after a long run.
33
+ _last: dict[str, Any] = {}
34
+
35
+
36
+ def _number(value: Any, label: str) -> str:
37
+ try:
38
+ x = float(value)
39
+ except (TypeError, ValueError):
40
+ raise ValueError(f"{label} must be a number, not {value!r}.")
41
+ return f"{x:.12g}"
42
+
43
+
44
+ def build_command(
45
+ constraints: list[dict] | None,
46
+ thickness_limits: dict | None,
47
+ field_weights: list[float] | None,
48
+ error_function: str,
49
+ cycles: int,
50
+ min_improvement: float | None = None,
51
+ ) -> tuple[str, list[dict]]:
52
+ """The AUT command and a normalised list of the constraints it contains."""
53
+ if not 1 <= int(cycles) <= 500:
54
+ raise ValueError("cycles must be 1..500.")
55
+ parts = ["AUT", f"MXC {int(cycles)}"]
56
+ if min_improvement is not None:
57
+ if not 0 <= float(min_improvement) < 1:
58
+ raise ValueError("min_improvement is a fraction per cycle, 0 to below 1 (CODE V's default is 0.05).")
59
+ parts.append(f"IMP {float(min_improvement):.12g}")
60
+ if error_function == "wavefront":
61
+ parts.append("WFR Yes")
62
+ elif error_function != "ray":
63
+ raise ValueError("error_function must be 'ray' or 'wavefront'.")
64
+ for key, value in (thickness_limits or {}).items():
65
+ if key not in THICKNESS_LIMITS:
66
+ raise ValueError(f"thickness_limits keys are {sorted(THICKNESS_LIMITS)}, not {key!r}.")
67
+ if value is not None:
68
+ parts.append(f"{THICKNESS_LIMITS[key]} {_number(value, key)}")
69
+ for i, w in enumerate(field_weights or [], start=1):
70
+ parts.append(f"WTF F{i} {_number(w, f'field_weights[{i - 1}]')}")
71
+ normalised = []
72
+ for c in constraints or []:
73
+ q = str(c.get("quantity", "")).strip().upper()
74
+ quals = str(c.get("qualifiers") or "").strip()
75
+ if not QUANTITY.match(q):
76
+ raise ValueError(f"Constraint quantity {q!r} is not a CODE V constraint keyword (e.g. EFL, OAL, BFL, CT).")
77
+ if not QUALIFIERS.match(quals):
78
+ raise ValueError(f"Constraint qualifiers {quals!r} may contain only letters, digits, spaces and '.'.")
79
+ eq, lo, hi = c.get("equals"), c.get("min"), c.get("max")
80
+ if eq is not None and (lo is not None or hi is not None):
81
+ raise ValueError(f"{q}: give either equals, or min and/or max.")
82
+ if eq is None and lo is None and hi is None:
83
+ raise ValueError(f"{q}: give equals, min or max.")
84
+ text = f"{q} {quals}".strip()
85
+ if eq is not None:
86
+ text += f" = {_number(eq, q)}"
87
+ else:
88
+ if lo is not None:
89
+ text += f" > {_number(lo, q)}"
90
+ if hi is not None:
91
+ text += f" < {_number(hi, q)}"
92
+ parts.append(text)
93
+ normalised.append({"quantity": q, "qualifiers": quals, "equals": eq, "min": lo, "max": hi})
94
+ parts.append("GO")
95
+ return "; ".join(parts), normalised
96
+
97
+
98
+ def _variable_values(ops: Ops) -> dict[str, Any]:
99
+ out = {}
100
+ for v in edits.list_variables_in(ops)["variables"]:
101
+ s, param = v["surface"], v["parameter"]
102
+ q = edits._name(ops, s)
103
+ expr = {"radius": f"(RDY {q})", "thickness": f"(THI {q})", "glass": f"(GLA {q})"}[param]
104
+ value, errors, _ = ops.soft(lambda expr=expr: ops.eva(expr))
105
+ out[f"S{s} {param}"] = None if errors else value
106
+ return out
107
+
108
+
109
+ def _erf(ops: Ops) -> dict[str, Any]:
110
+ out = {}
111
+ for key, expr in (("total", "(AUT.ERF ALL)"), ("aberration", "(AUT.ERF ABR)"), ("constraint", "(AUT.ERF CON)")):
112
+ value, errors, _ = ops.soft(lambda expr=expr: ops.eva(expr))
113
+ out[key] = None if errors or value is None or (isinstance(value, float) and (value < 0 or value >= INVALID_ERF)) else value
114
+ valid, errors, _ = ops.soft(lambda: ops.eva("(OPT ERF)"))
115
+ out["valid"] = None if errors else (valid == 1.0)
116
+ return out
117
+
118
+
119
+ def _constraint_values(ops: Ops, constraints: list[dict]) -> list[dict]:
120
+ rows = []
121
+ for c in constraints:
122
+ expr = f"({c['quantity']} {c['qualifiers']})".replace(" )", ")")
123
+ value, errors, _ = ops.soft(lambda expr=expr: ops.eva(expr))
124
+ row = {**c, "value": None if errors else value}
125
+ if row["value"] is None:
126
+ row["status"] = "value not readable as a database item"
127
+ elif isinstance(row["value"], (int, float)):
128
+ v = float(row["value"])
129
+ if c["equals"] is not None:
130
+ # AUT solves constraints with Lagrange multipliers to a small residual,
131
+ # typically a few parts in 1e5; judge equality at 1e-4 relative.
132
+ tol = EQUALITY_TOLERANCE * max(1.0, abs(c["equals"]))
133
+ row["deviation"] = float(f"{v - c['equals']:.6g}")
134
+ row["status"] = "met" if abs(v - c["equals"]) <= tol else f"off by {v - c['equals']:.6g}"
135
+ else:
136
+ low_ok = c["min"] is None or v >= c["min"] - 1e-9
137
+ high_ok = c["max"] is None or v <= c["max"] + 1e-9
138
+ row["status"] = "met" if low_ok and high_ok else "violated"
139
+ rows.append(row)
140
+ return rows
141
+
142
+
143
+ def _history(listing: str) -> list[float]:
144
+ """Error function per cycle. CODE V prints each cycle's block twice, so key by cycle number."""
145
+ by_cycle: dict[int, float] = {}
146
+ for m in re.finditer(r"CYCLE NUMBER\s+(\d+):\s*ERR\.\s*F\.\s*=\s*(-?[\d.]+(?:[eE][-+]?\d+)?)", listing):
147
+ by_cycle.setdefault(int(m.group(1)), float(m.group(2)))
148
+ return [by_cycle[k] for k in sorted(by_cycle)]
149
+
150
+
151
+ def _stop_reason(listing: str, history: list[float], cycles_limit: int | None) -> dict[str, Any]:
152
+ """Why AUT stopped (its closing message), and whether another run looks worthwhile."""
153
+ out: dict[str, Any] = {}
154
+ messages = re.findall(r"^\s*(\S[^\n]*\bAUTO\b[^\n]*?)\s*$", listing, re.M)
155
+ if messages:
156
+ out["stopped_because"] = messages[-1].strip()
157
+ gain = (history[-2] - history[-1]) / history[-2] if len(history) >= 2 and history[-2] else None
158
+ if gain is not None:
159
+ out["last_cycle_gain"] = round(gain, 4)
160
+ if "less than IMP" in out.get("stopped_because", "") and gain is not None and gain > 0.01:
161
+ out["hint"] = (f"AUT stopped on its improvement rule (cycles gaining under the IMP fraction, default 5%) "
162
+ f"while the last cycle still gained {gain:.1%}. Run optimize again, or pass a smaller "
163
+ "min_improvement.")
164
+ elif cycles_limit is not None and len(history) - 1 >= cycles_limit:
165
+ out["hint"] = "AUT used every allowed cycle; raise cycles to let it continue."
166
+ if m := list(re.finditer(r"Frozen Thickness Violations:\s*\n([^\n]*)", listing)):
167
+ found = re.findall(r"(M[nx]\s+[A-Z]{2}\s+S\w+)", m[-1].group(1))
168
+ if found:
169
+ out["thickness_violations"] = [" ".join(f.split()) for f in found]
170
+ return out
171
+
172
+
173
+ def start(engine: CodeVEngine, variables: list[dict] | None, constraints: list[dict] | None,
174
+ thickness_limits: dict | None, field_weights: list[float] | None, error_function: str,
175
+ cycles: int, release_solves: bool, min_improvement: float | None = None) -> dict:
176
+ command, normalised = build_command(constraints, thickness_limits, field_weights, error_function, cycles,
177
+ min_improvement)
178
+ if variables:
179
+ r = edits.set_variables(engine, variables, release_solves)
180
+ if not r["ok"]:
181
+ return {**r, "ok": False, "note": "Variables could not be set; optimization not started."}
182
+
183
+ def fn(ops: Ops) -> dict:
184
+ if ops.cv.IsExecutingCommand:
185
+ return {"ok": False, "error_detail": "A long command is already running."}
186
+ varying = edits.list_variables_in(ops)["variables"]
187
+ if not varying:
188
+ return {"ok": False, "error_detail": "Nothing is variable. Pass variables, or use set_variables first."}
189
+ snap = snapshots.save_in(engine, ops, snapshots.auto_label(), f"before optimize: {command[:100]}", True)
190
+ if not snap.get("ok", True):
191
+ return {"ok": False, "error_detail": "Snapshot failed; optimization not started.", "snapshot": snap}
192
+ before = {"variables": _variable_values(ops), "efl": ops.soft(lambda: ops.eva("(EFL)"))[0]}
193
+ ops.cv.AsyncCommand(command)
194
+ _last.clear()
195
+ _last.update(command=command, constraints=normalised, before=before, snapshot=snap["label"],
196
+ started=time.time(), cycles=int(cycles))
197
+ return {"started": True, "command": command, "snapshot": snap["label"], "variable_count": len(varying)}
198
+
199
+ return engine.with_ops(fn)
200
+
201
+
202
+ def result(engine: CodeVEngine, listing: str | None = None) -> dict:
203
+ if not _last:
204
+ return {"ok": False, "error_detail": "No optimization has been started by this server."}
205
+
206
+ def fn(ops: Ops) -> dict:
207
+ if ops.cv.IsExecutingCommand:
208
+ return {"executing": True, "elapsed_s": round(time.time() - _last["started"], 1)}
209
+ text = listing if listing is not None else engine.command_output()
210
+ history = _history(text)
211
+ after = {"variables": _variable_values(ops), "efl": ops.soft(lambda: ops.eva("(EFL)"))[0]}
212
+ changes = {
213
+ k: {"before": _last["before"]["variables"].get(k), "after": v}
214
+ for k, v in after["variables"].items()
215
+ }
216
+ out: dict[str, Any] = {
217
+ "executing": False,
218
+ "command": _last["command"],
219
+ "snapshot": _last["snapshot"],
220
+ "error_function": _erf(ops),
221
+ "history": {"cycles": max(len(history) - 1, 0), "first": history[0] if history else None,
222
+ "last": history[-1] if history else None, "values": history[:60]},
223
+ "variables": changes,
224
+ "constraints": _constraint_values(ops, _last["constraints"]),
225
+ "efl": {"before": _last["before"]["efl"], "after": after["efl"]},
226
+ **_stop_reason(text, history, _last.get("cycles")),
227
+ "note": f"Undo with restore_snapshot('{_last['snapshot']}'). Equality constraints count as met within "
228
+ f"{EQUALITY_TOLERANCE:g} relative; each row gives its deviation.",
229
+ }
230
+ unmet = [c for c in out["constraints"] if c.get("status") not in ("met", "value not readable as a database item")]
231
+ if unmet:
232
+ out["warning"] = f"{len(unmet)} constraint(s) not met."
233
+ if out.get("thickness_violations"):
234
+ out["warning"] = (out.get("warning", "") + " " if out.get("warning") else "") + \
235
+ "AUT reported thickness limit violations: " + ", ".join(out["thickness_violations"]) + "."
236
+ if not history:
237
+ out["listing_tail"] = text[-1500:]
238
+ return out
239
+
240
+ return engine.with_ops(fn)
241
+
242
+
243
+ def run(engine: CodeVEngine, wait_s: float, **spec: Any) -> dict:
244
+ started = start(engine, **spec)
245
+ if not started.get("started"):
246
+ return started
247
+ deadline = time.time() + max(0.0, min(float(wait_s), 600.0))
248
+ # CODE V reports problems in the run (a rejected constraint, ray failures)
249
+ # as events, at the start or while it executes; keep them for the report.
250
+ errors: list[str] = list(started.get("errors", []))
251
+ warnings: list[str] = list(started.get("warnings", []))
252
+ while time.time() < deadline:
253
+ poll = engine.async_poll(1000)
254
+ errors += poll.get("errors", [])
255
+ warnings += poll.get("warnings", [])
256
+ if not poll.get("executing"):
257
+ break
258
+ r = result(engine)
259
+ r["errors"] = errors + r.get("errors", [])
260
+ r["warnings"] = warnings + r.get("warnings", [])
261
+ if r["errors"]:
262
+ r["ok"] = False
263
+ # CODE V skips a constraint it does not accept (e.g. "Invalid constraint
264
+ # BFL") and runs on without it; say so on that constraint's row.
265
+ rejected = {m.group(1).upper() for e in r["errors"] if (m := re.search(r"Invalid constraint\s+(\w+)", e))}
266
+ for c in r.get("constraints", []):
267
+ if c["quantity"] in rejected:
268
+ c["status"] = "rejected by CODE V: not a valid constraint, so the run went ahead without it"
269
+ if rejected:
270
+ r["warning"] = (r.get("warning", "") + " " if r.get("warning") else "") + \
271
+ f"CODE V rejected constraint(s) {sorted(rejected)}; the result was optimized without them."
272
+ if r.get("executing"):
273
+ r["hint"] = "Still running. Call get_optimization_result later, or stop_long_command to halt it."
274
+ r["snapshot"] = started["snapshot"]
275
+ r["command"] = started["command"]
276
+ return r
277
+
278
+
279
+ __all__ = ["build_command", "run", "start", "result", "CodeVError"]
codev_mcp/paths.py ADDED
@@ -0,0 +1,35 @@
1
+ """Where codev-mcp keeps its files.
2
+
3
+ Everything lives under one folder, ``%USERPROFILE%\\codev-mcp`` by default
4
+ (override with CODEV_MCP_DATA):
5
+
6
+ - ``work`` CODE V's starting directory, with ``snapshots`` and ``plots``
7
+ - ``reference.db`` the locally built manual and glass database
8
+
9
+ Not %LOCALAPPDATA%: when the server runs inside a packaged (MSIX) app such as
10
+ the Claude desktop app, Windows redirects folders it creates there into the
11
+ app's private store. CODE V, which COM starts outside the package, cannot see
12
+ them, so StartCodeV fails and SAV/RES miss their files. Not %TEMP% either,
13
+ which cleanup tools empty.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import tempfile
20
+ from pathlib import Path
21
+
22
+ from codev_mcp import settings
23
+
24
+
25
+ def data_dir() -> Path:
26
+ return settings.data_dir()
27
+
28
+
29
+ def default_start_dir() -> str:
30
+ return str(settings.data_dir() / "work")
31
+
32
+
33
+ # Earlier defaults, read once for migration or as a fallback.
34
+ LEGACY_START_DIR = Path(tempfile.gettempdir()) / "codev-mcp"
35
+ LEGACY_DATA_DIR = Path(os.environ.get("LOCALAPPDATA") or Path.home()) / "codev-mcp"