agent2mesh 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.
agent2mesh/__init__.py ADDED
File without changes
agent2mesh/auto.py ADDED
@@ -0,0 +1,195 @@
1
+ """One-call reconstruction: the parameter search an agent would do, done in code.
2
+
3
+ ``reconstruct_building`` runs import/footprint/planes/LoD2/evaluation and, when the
4
+ result fails the acceptance test, tries a few alternative settings and keeps the
5
+ best one. ``batch_reconstruct`` does that for a folder and reports only failures.
6
+ Both return short summaries so an agent spends few tokens per building.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ import time
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from . import ops
18
+ from .workspace import Workspace, WorkspaceError
19
+
20
+ RMSE_OK = 0.3
21
+ UNCOVERED_OK = 0.03
22
+
23
+ # tried in order; the first one that passes wins, otherwise the best score wins
24
+ CANDIDATES: list[dict[str, Any]] = [
25
+ {"name": "compact", "simplify": 0.5},
26
+ # small roof parts (dormers, roof boxes, low canopies) and curved roofs
27
+ {"name": "detail", "simplify": 0.3, "plane_min_points": 10, "min_region_area": 1.5},
28
+ {"name": "fine", "simplify": None},
29
+ {"name": "loose_planes", "simplify": 0.5, "plane_factor": 1.5},
30
+ ]
31
+ # if roof points stay outside the model, the outline was cut too hard: redo it finer
32
+ FOOTPRINT_FALLBACK = {"min_feature": 0.5}
33
+
34
+
35
+ def safe_name(stem: str) -> str:
36
+ return re.sub(r"[^A-Za-z0-9_.\-]", "_", stem)
37
+
38
+
39
+ def _score(ev: dict[str, Any]) -> float:
40
+ a = ev["accuracy"]
41
+ rmse = a.get("rmse_m") if a.get("rmse_m") is not None else 9.0
42
+ return rmse + 3.0 * a["uncovered_fraction"] + (0.0 if ev["topology"]["watertight"] else 10.0)
43
+
44
+
45
+ def _passes(ev: dict[str, Any]) -> bool:
46
+ a = ev["accuracy"]
47
+ return bool(ev["topology"]["watertight"] and (a.get("rmse_m") or 9.0) <= RMSE_OK and a["uncovered_fraction"] <= UNCOVERED_OK)
48
+
49
+
50
+ def _reason(ev: dict[str, Any]) -> str:
51
+ a, t = ev["accuracy"], ev["topology"]
52
+ out = []
53
+ if not t["watertight"]:
54
+ out.append(f"open:{t['open_edges']}")
55
+ if (a.get("rmse_m") or 9.0) > RMSE_OK:
56
+ out.append(f"rmse:{a.get('rmse_m')}")
57
+ if a["uncovered_fraction"] > UNCOVERED_OK:
58
+ out.append(f"uncovered:{a['uncovered_fraction']:.0%}")
59
+ return ",".join(out)
60
+
61
+
62
+ def _attempt(ws: Workspace, name: str, cfg: dict[str, Any], base_distance: float, overrides: dict[str, Any]) -> tuple[dict, dict]:
63
+ distance = overrides.get("plane_distance") or base_distance * cfg.get("plane_factor", 1.0)
64
+ min_points = overrides.get("plane_min_points") or cfg.get("plane_min_points")
65
+ ops.detect_roof_planes(ws, name, distance, 15.0, min_points, 70.0, True)
66
+ simplify = overrides["simplify"] if "simplify" in overrides else cfg.get("simplify")
67
+ rep = ops.reconstruct_model(
68
+ ws, name, overrides.get("lod", "2.2"), None, None, None,
69
+ overrides.get("min_region_area", cfg.get("min_region_area", 4.0)), simplify, overrides.get("snap", 0.3), True,
70
+ )
71
+ ev, _ = ops.evaluate_mesh(ws, name, rep["mesh"], RMSE_OK, write_png=False)
72
+ return rep, ev
73
+
74
+
75
+ def reconstruct_building(
76
+ ws: Workspace,
77
+ source: str,
78
+ *,
79
+ name: str | None = None,
80
+ epsg: int | None = None,
81
+ ground_z: float | None = None,
82
+ overrides: dict[str, Any] | None = None,
83
+ search: bool = True,
84
+ visual_mesh: bool = False,
85
+ ) -> dict[str, Any]:
86
+ """``source``: an XYZ file (one building) or the name of an existing building folder."""
87
+ overrides = dict(overrides or {})
88
+ t0 = time.time()
89
+ src = ws.root / source
90
+ if src.is_file():
91
+ name = name or safe_name(src.stem)
92
+ ops.import_building_xyz(ws, source, name, epsg, ground_z, True)
93
+ refresh_fp = True
94
+ else:
95
+ name = source
96
+ ws.building(name)
97
+ refresh_fp = "min_feature" in overrides or not ws.building(name).meta().get("footprint")
98
+ if refresh_fp:
99
+ ops.derive_footprint(ws, name, None, None, 2, 4.0, True, True, min_feature=overrides.get("min_feature", 1.0))
100
+ meta = ws.building(name).meta()
101
+ base_distance = float((meta.get("suggested") or {}).get("plane_distance_m", 0.15))
102
+
103
+ lod = overrides.get("lod", "2.2")
104
+ user_set = {"simplify", "plane_distance", "min_region_area", "plane_min_points"} & overrides.keys()
105
+ cands = CANDIDATES if (search and lod == "2.2" and not user_set) else [CANDIDATES[0]]
106
+ tried: list[dict[str, Any]] = []
107
+ best = None
108
+
109
+ def run(cfgs, fp_tag):
110
+ nonlocal best
111
+ for cfg in cfgs:
112
+ try:
113
+ rep, ev = _attempt(ws, name, cfg, base_distance, overrides)
114
+ except (WorkspaceError, ValueError) as exc:
115
+ tried.append({"cfg": cfg["name"] + fp_tag, "error": str(exc)[:80]})
116
+ continue
117
+ sc = _score(ev)
118
+ tried.append({"cfg": cfg["name"] + fp_tag, "score": round(sc, 3), "ok": _passes(ev)})
119
+ if best is None or sc < best[0]:
120
+ best = (sc, cfg, fp_tag, rep, ev)
121
+ if _passes(ev):
122
+ return True
123
+ return False
124
+
125
+ done = run(cands, "")
126
+ fp_derived = ws.building(name).meta().get("footprint", "").startswith("footprint_derived")
127
+ if not done and search and fp_derived and "min_feature" not in overrides and best is not None:
128
+ # (tag, min_feature, regularize): finer outlines, finally an unregularised one
129
+ outlines = [("", 1.0, True), ("+outline0.5", FOOTPRINT_FALLBACK["min_feature"], True), ("+outline0.0", 0.0, True), ("+outline_raw", 0.0, False)]
130
+ for tag, mf, reg in outlines[1:]:
131
+ ops.derive_footprint(ws, name, None, None, 2, 4.0, True, reg, min_feature=mf)
132
+ done = run(cands[:2], tag)
133
+ if done:
134
+ break
135
+ if not done and best is not None and best[2] != outlines[-1][0]:
136
+ # re-derive the outline that produced the best result
137
+ _, mf, reg = next(o for o in outlines if o[0] == best[2])
138
+ ops.derive_footprint(ws, name, None, None, 2, 4.0, True, reg, min_feature=mf)
139
+ tried.append({"cfg": "restore_outline"})
140
+ if best is None:
141
+ raise WorkspaceError(f"{name}: every attempt failed: {tried}")
142
+ _, cfg, fp_tag, rep, ev = best
143
+ if tried[-1].get("cfg") != cfg["name"] + fp_tag: # re-create the best result (deterministic)
144
+ rep, ev = _attempt(ws, name, cfg, base_distance, overrides)
145
+ cfg = {**cfg, "name": cfg["name"] + fp_tag}
146
+ if visual_mesh:
147
+ ops.build_visual_mesh(ws, name, None, True, None, True)
148
+ a = ev["accuracy"]
149
+ out = {
150
+ "building": name,
151
+ "ok": _passes(ev),
152
+ "lod": rep["params"]["lod"],
153
+ "config": cfg["name"],
154
+ "rmse_m": a.get("rmse_m"),
155
+ "uncovered": round(a["uncovered_fraction"], 3),
156
+ "watertight": ev["topology"]["watertight"],
157
+ "planes": rep.get("roof_regions"),
158
+ "faces": rep["faces"],
159
+ "corners": rep.get("wireframe_size", {}).get("corners"),
160
+ "files": [rep["mesh"], rep["cityjson"]],
161
+ "seconds": round(time.time() - t0, 1),
162
+ }
163
+ if not out["ok"]:
164
+ out["reason"] = _reason(ev)
165
+ out["hotspots"] = [h["real_xy"] + [h["mean_abs_err_m"]] for h in ev["hotspots"][:3]]
166
+ out["tried"] = [t["cfg"] for t in tried]
167
+ return out
168
+
169
+
170
+ def batch_reconstruct(ws: Workspace, folder: str, *, pattern: str = "*.xyz", epsg: int | None = None, max_failures: int = 30) -> dict[str, Any]:
171
+ root = ws.resolve(folder)
172
+ files = sorted(root.glob(pattern))
173
+ if not files:
174
+ raise WorkspaceError(f"no {pattern} files in {folder}")
175
+ t0 = time.time()
176
+ rows = []
177
+ for f in files:
178
+ try:
179
+ rows.append(reconstruct_building(ws, ws.relative(f), epsg=epsg))
180
+ except Exception as exc: # noqa: BLE001 - keep going, report the failure
181
+ rows.append({"building": safe_name(f.stem), "ok": False, "reason": f"error:{type(exc).__name__}:{str(exc)[:60]}"})
182
+ summary = ws.buildings_dir / f"summary_{Path(folder).name}.json"
183
+ summary.write_text(json.dumps(rows, indent=1, ensure_ascii=False), encoding="utf-8")
184
+ ok = [r for r in rows if r.get("ok")]
185
+ rm = sorted(r["rmse_m"] for r in ok if r.get("rmse_m") is not None)
186
+ fails = [[r["building"], r.get("reason", "")] for r in rows if not r.get("ok")]
187
+ return {
188
+ "buildings": len(rows),
189
+ "passed": len(ok),
190
+ "median_rmse_m": rm[len(rm) // 2] if rm else None,
191
+ "seconds": round(time.time() - t0),
192
+ "summary": ws.relative(summary),
193
+ "failures": fails[:max_failures],
194
+ "more_failures": max(0, len(fails) - max_failures),
195
+ }