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.
@@ -0,0 +1,550 @@
1
+ """Tile inspection, building candidates, single-building extraction, footprints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ import shapely
10
+ from scipy import ndimage
11
+ from scipy.spatial import cKDTree
12
+ from shapely.geometry import MultiPoint, Polygon
13
+
14
+ from . import geom
15
+ from .las_io import Cloud, class_histogram, read_las, write_las
16
+ from .workspace import BuildingDir, WorkspaceError
17
+
18
+ GROUND = 2
19
+ VEGETATION = (3, 4, 5)
20
+ NOISE = (7, 18)
21
+
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # inspection
25
+ # ---------------------------------------------------------------------------
26
+ def suggested_params(spacing: float, density: float | None = None) -> dict[str, float]:
27
+ """Parameters from the areal density (points/m2); falls back to NN spacing.
28
+
29
+ Scan-line data has a small nearest-neighbour spacing along the lines but big
30
+ gaps between them, so the effective spacing 1/sqrt(density) is used.
31
+ """
32
+ if density is not None and np.isfinite(density) and density > 0:
33
+ s = 1.0 / np.sqrt(density)
34
+ else:
35
+ s = spacing if np.isfinite(spacing) and spacing > 0 else 0.5
36
+ s = s * 2.0 # median NN distance is about half the mean spacing
37
+ dens = 1.0 / (s * s)
38
+ return {
39
+ "effective_spacing_m": round(float(s), 3),
40
+ "cluster_tolerance_m": round(max(1.0, 3.0 * s), 2),
41
+ "footprint_cell_m": round(max(0.3, 1.5 * s), 2),
42
+ "plane_distance_m": round(min(0.3, max(0.1, 0.5 * s)), 2),
43
+ "plane_min_points": int(max(15, round(3.0 * dens))), # about 3 m2 of roof
44
+ "lod2_cell_m": round(max(0.2, 0.75 * s), 2),
45
+ }
46
+
47
+
48
+ def inspect_tile(cloud: Cloud) -> dict[str, Any]:
49
+ xyz = cloud.xyz
50
+ mn, mx = xyz.min(axis=0), xyz.max(axis=0)
51
+ area = float(max((mx[0] - mn[0]) * (mx[1] - mn[1]), 1e-9))
52
+ spacing = geom.point_spacing(xyz[:, :2])
53
+ hist = class_histogram(cloud.classification)
54
+ classes = set(np.unique(cloud.classification).tolist())
55
+ warnings = []
56
+ if cloud.epsg is None and cloud.crs_wkt is None:
57
+ warnings.append("No CRS in the LAS header. Outputs will have no reference system.")
58
+ if 6 not in classes:
59
+ warnings.append(
60
+ "No building class (6). list_buildings will fall back to height-above-ground, "
61
+ "which also picks up trees. Classify the tile first if possible (e.g. PDAL, lastools, CloudCompare)."
62
+ )
63
+ if GROUND not in classes:
64
+ warnings.append("No ground class (2). Ground height will be estimated from the lowest points.")
65
+ if max(abs(mn[0]), abs(mn[1]), abs(mx[0]), abs(mx[1])) > 1e5:
66
+ warnings.append(
67
+ "Large projected coordinates: building folders store geometry relative to a local origin "
68
+ "(see building.json 'origin') to keep float32 precision."
69
+ )
70
+ return {
71
+ "points": cloud.n,
72
+ "bounds_min": mn.round(3).tolist(),
73
+ "bounds_max": mx.round(3).tolist(),
74
+ "extent_m": (mx - mn).round(2).tolist(),
75
+ "epsg": cloud.epsg,
76
+ "has_crs": cloud.crs_wkt is not None,
77
+ "classes": hist,
78
+ "density_pts_per_m2": round(cloud.n / area, 2),
79
+ "median_spacing_m": round(spacing, 3),
80
+ "suggested": suggested_params(spacing, geom.areal_density(xyz[:, :2])),
81
+ "warnings": warnings,
82
+ }
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # ground / building masks
87
+ # ---------------------------------------------------------------------------
88
+ def _ground_points(cloud: Cloud) -> np.ndarray:
89
+ g = cloud.classification == GROUND
90
+ if g.sum() >= 10:
91
+ return cloud.xyz[g]
92
+ # fallback: lowest point per 5 m cell
93
+ xy = cloud.xyz[:, :2]
94
+ ij = np.floor((xy - xy.min(axis=0)) / 5.0).astype(np.int64)
95
+ key = ij[:, 0] * (ij[:, 1].max() + 1) + ij[:, 1]
96
+ order = np.lexsort((cloud.xyz[:, 2], key))
97
+ first = order[np.r_[True, key[order][1:] != key[order][:-1]]]
98
+ return cloud.xyz[first]
99
+
100
+
101
+ def _height_above_ground(cloud: Cloud) -> np.ndarray:
102
+ ground = _ground_points(cloud)
103
+ tree = cKDTree(ground[:, :2])
104
+ _, idx = tree.query(cloud.xyz[:, :2], k=min(8, len(ground)))
105
+ gz = np.median(ground[np.atleast_2d(idx), 2], axis=-1) if idx.ndim > 1 else ground[idx, 2]
106
+ return cloud.xyz[:, 2] - gz
107
+
108
+
109
+ def building_mask(cloud: Cloud, building_classes: list[int], min_height: float) -> tuple[np.ndarray, str]:
110
+ present = np.isin(cloud.classification, building_classes)
111
+ if present.any():
112
+ return present, "classification"
113
+ hag = _height_above_ground(cloud)
114
+ excluded = np.isin(cloud.classification, (GROUND, *NOISE, *VEGETATION))
115
+ return (hag > min_height) & ~excluded, "height_above_ground"
116
+
117
+
118
+ def _components(xy: np.ndarray, cell: float) -> tuple[np.ndarray, int]:
119
+ origin = xy.min(axis=0)
120
+ ij = np.floor((xy - origin) / cell).astype(np.int64)
121
+ shape = tuple(ij.max(axis=0) + 1)
122
+ grid = np.zeros(shape, dtype=bool)
123
+ grid[ij[:, 0], ij[:, 1]] = True
124
+ lab, n = ndimage.label(grid, structure=np.ones((3, 3), dtype=bool))
125
+ return lab[ij[:, 0], ij[:, 1]], n
126
+
127
+
128
+ def _ground_z_near(ground: np.ndarray, hull: Polygon, ring: float) -> tuple[float | None, int]:
129
+ if len(ground) == 0:
130
+ return None, 0
131
+ near = shapely.dwithin(shapely.points(ground[:, :2]), hull, ring) & ~shapely.contains_xy(hull, ground[:, 0], ground[:, 1])
132
+ if near.sum() < 5:
133
+ return None, int(near.sum())
134
+ return float(np.median(ground[near, 2])), int(near.sum())
135
+
136
+
137
+ # ---------------------------------------------------------------------------
138
+ # candidates
139
+ # ---------------------------------------------------------------------------
140
+ def list_buildings(
141
+ cloud: Cloud,
142
+ building_classes: list[int],
143
+ tolerance: float,
144
+ min_area: float,
145
+ min_height: float,
146
+ max_results: int,
147
+ ) -> dict[str, Any]:
148
+ mask, source = building_mask(cloud, building_classes, min_height)
149
+ pts = cloud.xyz[mask]
150
+ if len(pts) == 0:
151
+ raise WorkspaceError("no building points found (check building_classes / min_height)")
152
+ labels, n = _components(pts[:, :2], tolerance)
153
+ counts = np.bincount(labels, minlength=n + 1)
154
+ ground = _ground_points(cloud)
155
+ gtree = cKDTree(ground[:, :2])
156
+ cell_area = tolerance * tolerance
157
+ found = []
158
+ for lab in np.argsort(-counts):
159
+ if lab == 0 or counts[lab] < 10:
160
+ continue
161
+ p = pts[labels == lab]
162
+ ij = np.unique(np.floor(p[:, :2] / tolerance).astype(np.int64), axis=0)
163
+ area = len(ij) * cell_area
164
+ if area < min_area:
165
+ continue
166
+ centroid = p[:, :2].mean(axis=0)
167
+ seed = p[np.argmin(np.hypot(*(p[:, :2] - centroid).T)), :2]
168
+ _, gi = gtree.query(seed, k=min(16, len(ground)))
169
+ gz = float(np.median(ground[np.atleast_1d(gi), 2]))
170
+ found.append(
171
+ {
172
+ "id": f"b{len(found) + 1:04d}",
173
+ "seed_x": round(float(seed[0]), 3),
174
+ "seed_y": round(float(seed[1]), 3),
175
+ "points": int(len(p)),
176
+ "approx_area_m2": round(area, 1),
177
+ "approx_height_m": round(float(np.percentile(p[:, 2], 95) - gz), 1),
178
+ "bbox": [round(float(v), 2) for v in (*p[:, :2].min(axis=0), *p[:, :2].max(axis=0))],
179
+ }
180
+ )
181
+ if len(found) >= max_results:
182
+ break
183
+ return {
184
+ "selection_source": source,
185
+ "cluster_tolerance_m": tolerance,
186
+ "buildings_found": len(found),
187
+ "buildings": found,
188
+ "note": "Pass seed_x/seed_y and the same cluster_tolerance_m to extract_building.",
189
+ }
190
+
191
+
192
+ # ---------------------------------------------------------------------------
193
+ # extraction
194
+ # ---------------------------------------------------------------------------
195
+ def extract_building(
196
+ cloud: Cloud,
197
+ bdir: BuildingDir,
198
+ *,
199
+ source_rel: str,
200
+ building_classes: list[int],
201
+ min_height: float,
202
+ seed: tuple[float, float] | None,
203
+ tolerance: float,
204
+ footprint: Polygon | None,
205
+ footprint_props: dict[str, Any] | None,
206
+ footprint_buffer: float,
207
+ ground_ring: float,
208
+ ) -> dict[str, Any]:
209
+ mask, source = building_mask(cloud, building_classes, min_height)
210
+ idx_all = np.flatnonzero(mask)
211
+ xy_all = cloud.xyz[:, :2]
212
+ if footprint is not None:
213
+ region = footprint.buffer(footprint_buffer)
214
+ inside = shapely.contains_xy(region, xy_all[idx_all, 0], xy_all[idx_all, 1])
215
+ sel = idx_all[inside]
216
+ selection = {"mode": "footprint", "buffer_m": footprint_buffer, "properties": footprint_props or {}}
217
+ elif seed is not None:
218
+ if len(idx_all) == 0:
219
+ raise WorkspaceError("no building points in the tile")
220
+ labels, _ = _components(xy_all[idx_all], tolerance)
221
+ d, i = cKDTree(xy_all[idx_all]).query(seed)
222
+ if d > 2 * tolerance:
223
+ raise WorkspaceError(f"no building point within {2 * tolerance:.1f} m of the seed ({d:.1f} m away)")
224
+ sel = idx_all[labels == labels[i]]
225
+ selection = {"mode": "seed", "seed": list(seed), "cluster_tolerance_m": tolerance}
226
+ else:
227
+ raise WorkspaceError("give either seed_x/seed_y or a footprint")
228
+ if len(sel) < 20:
229
+ raise WorkspaceError(f"only {len(sel)} building points selected; check the footprint/seed")
230
+
231
+ bxyz = cloud.xyz[sel]
232
+ hull = footprint if footprint is not None else MultiPoint(bxyz[:, :2]).convex_hull
233
+ ground_all = cloud.classification == GROUND
234
+ lo, hi = bxyz[:, :2].min(axis=0) - ground_ring, bxyz[:, :2].max(axis=0) + ground_ring
235
+ gsel = np.flatnonzero(ground_all & np.all((xy_all >= lo) & (xy_all <= hi), axis=1))
236
+ gz, gcount = _ground_z_near(cloud.xyz[gsel], hull, ground_ring)
237
+ ground_source = "ground_class_ring"
238
+ if gz is None:
239
+ near = np.flatnonzero(np.all((xy_all >= lo) & (xy_all <= hi), axis=1))
240
+ others = np.setdiff1d(near, sel)
241
+ if len(others) >= 5:
242
+ gz, ground_source = float(np.percentile(cloud.xyz[others, 2], 2)), "lowest_points_ring"
243
+ else:
244
+ gz, ground_source = float(bxyz[:, 2].min() - 3.0), "guess_min_roof_minus_3m"
245
+
246
+ out = cloud.subset(np.concatenate([sel, gsel]))
247
+ cls = np.array(out.classification, dtype=np.uint8)
248
+ cls[: len(sel)] = 6 # building points are class 6 in the building copy
249
+ out.classification = cls
250
+ las_path = bdir.path / "points.laz"
251
+ write_las(out, las_path)
252
+
253
+ origin = geom.local_origin(bxyz)
254
+ spacing = geom.point_spacing(bxyz[:, :2])
255
+ density = geom.areal_density(bxyz[:, :2])
256
+ warnings = []
257
+ if ground_source != "ground_class_ring":
258
+ warnings.append(f"ground height from {ground_source}; check ground_z ({gz:.2f})")
259
+ if source == "height_above_ground":
260
+ warnings.append("building points chosen by height above ground; trees touching the roof may be included")
261
+ meta = bdir.update_meta(
262
+ name=bdir.name,
263
+ source=source_rel,
264
+ selection=selection,
265
+ selection_source=source,
266
+ epsg=cloud.epsg,
267
+ crs_wkt=cloud.crs_wkt,
268
+ origin=origin,
269
+ ground_z=round(gz, 3),
270
+ ground_source=ground_source,
271
+ ground_points_used=gcount,
272
+ building_points=int(len(sel)),
273
+ ground_points=int(len(gsel)),
274
+ spacing_m=round(spacing, 3),
275
+ density_pts_m2=round(density, 2),
276
+ suggested=suggested_params(spacing, density),
277
+ roof_z_range=[round(float(bxyz[:, 2].min()), 2), round(float(bxyz[:, 2].max()), 2)],
278
+ bbox_real=[round(float(v), 3) for v in (*bxyz[:, :2].min(axis=0), *bxyz[:, :2].max(axis=0))],
279
+ footprint=None,
280
+ )
281
+ if footprint is not None:
282
+ geom.write_footprint(bdir.path / "footprint.geojson", footprint, cloud.epsg, {"source": "provided", **(footprint_props or {})})
283
+ meta = bdir.update_meta(footprint="footprint.geojson")
284
+ return {
285
+ "building": bdir.name,
286
+ "folder": bdir.rel(bdir.path),
287
+ "files": bdir.files(),
288
+ "building_points": meta["building_points"],
289
+ "ground_points": meta["ground_points"],
290
+ "ground_z": meta["ground_z"],
291
+ "approx_height_m": round(float(np.percentile(bxyz[:, 2], 95) - gz), 2),
292
+ "spacing_m": meta["spacing_m"],
293
+ "suggested": meta["suggested"],
294
+ "footprint": meta["footprint"],
295
+ "warnings": warnings,
296
+ }
297
+
298
+
299
+ # ---------------------------------------------------------------------------
300
+ # loading a building folder
301
+ # ---------------------------------------------------------------------------
302
+ @dataclass
303
+ class BuildingData:
304
+ meta: dict[str, Any]
305
+ origin: np.ndarray
306
+ roof: np.ndarray # (N,3) local
307
+ ground: np.ndarray # (M,3) local
308
+ other: np.ndarray # (K,3) local: walls/facades (class 1), only from XYZ imports
309
+
310
+ @property
311
+ def ground_z(self) -> float:
312
+ return float(self.meta["ground_z"]) - float(self.origin[2])
313
+
314
+ def to_real(self, xyz: np.ndarray) -> np.ndarray:
315
+ return xyz + self.origin
316
+
317
+
318
+ def load_building(bdir: BuildingDir) -> BuildingData:
319
+ meta = bdir.meta()
320
+ cloud = read_las(bdir.file("points.laz"))
321
+ origin = np.asarray(meta["origin"], dtype=np.float64)
322
+ local = cloud.xyz - origin
323
+ roof = local[cloud.classification == 6]
324
+ ground = local[cloud.classification == GROUND]
325
+ other = local[cloud.classification == 1] if meta.get("selection_source") == "xyz_import" else local[:0]
326
+ return BuildingData(meta=meta, origin=origin, roof=roof, ground=ground, other=other)
327
+
328
+
329
+ def footprint_local(bdir: BuildingDir, data: BuildingData, name: str | None = None):
330
+ fname = name or data.meta.get("footprint")
331
+ if not fname:
332
+ raise WorkspaceError("this building has no footprint yet; run derive_footprint or pass a footprint to extract_building")
333
+ _, fp = geom.read_footprints(bdir.file(fname))[0]
334
+ return geom.translate_geom(fp, -data.origin[0], -data.origin[1]), fname
335
+
336
+
337
+ # ---------------------------------------------------------------------------
338
+ # footprint from roof points
339
+ # ---------------------------------------------------------------------------
340
+ def derive_footprint(
341
+ bdir: BuildingDir,
342
+ *,
343
+ cell: float | None,
344
+ simplify: float | None,
345
+ closing: int,
346
+ min_hole_area: float,
347
+ regularize: bool = True,
348
+ use_wall_points: bool = True,
349
+ min_feature: float = 1.0,
350
+ min_part_area: float = 10.0,
351
+ overwrite: bool,
352
+ ) -> dict[str, Any]:
353
+ """Roofprint from roof (+ wall) points.
354
+
355
+ Keeps every part larger than ``min_part_area`` (detached wings, separate roof
356
+ blocks), removes protrusions and notches narrower than ``min_feature`` (balcony
357
+ rails, facade scan lines, small recesses) and regularises each part to the
358
+ building axes.
359
+ """
360
+ data = load_building(bdir)
361
+ xy = data.roof[:, :2]
362
+ outline_xy = np.vstack([xy, data.other[:, :2]]) if use_wall_points and len(data.other) else xy
363
+ s = float(data.meta.get("spacing_m") or geom.point_spacing(xy))
364
+ sug = data.meta.get("suggested") or suggested_params(s)
365
+ cell = cell or sug["footprint_cell_m"]
366
+ s = sug.get("effective_spacing_m", s)
367
+ simplify = cell if simplify is None else simplify
368
+ theta = geom.dominant_angle(outline_xy)
369
+ r = geom.rotate_xy(outline_xy, -theta)
370
+ pad = closing + 2
371
+ mn = r.min(axis=0) - pad * cell
372
+ ij = np.floor((r - mn) / cell).astype(np.int64)
373
+ grid = np.zeros(tuple(ij.max(axis=0) + pad + 1), dtype=bool)
374
+ grid[ij[:, 0], ij[:, 1]] = True
375
+ if closing > 0:
376
+ grid = ndimage.binary_closing(grid, structure=np.ones((3, 3), bool), iterations=closing)
377
+ # fill small holes only (keep courtyards)
378
+ holes, nh = ndimage.label(~grid)
379
+ if nh:
380
+ sizes = np.bincount(holes.ravel())
381
+ border = np.unique(np.concatenate([holes[0], holes[-1], holes[:, 0], holes[:, -1]]))
382
+ small = np.flatnonzero(sizes * cell * cell < min_hole_area)
383
+ fill = np.setdiff1d(small, border)
384
+ grid |= np.isin(holes, fill) & (holes > 0)
385
+ lab, n = ndimage.label(grid, structure=np.ones((3, 3), bool))
386
+ sizes = np.bincount(lab.ravel()).astype(float) * cell * cell
387
+ sizes[0] = 0
388
+ biggest = float(sizes.max())
389
+ keep_labels = [k for k in range(1, n + 1) if sizes[k] >= max(min_part_area, 0.02 * biggest)]
390
+ dropped = float(sizes.sum() - sizes[keep_labels].sum())
391
+ d = 0.5 * min_feature
392
+ parts = []
393
+ regularized = 0
394
+ for k in keep_labels:
395
+ ci, cj = np.nonzero(lab == k)
396
+ poly = geom.largest_polygon(geom.cells_to_polygon(ci, cj, mn[0], mn[1], cell))
397
+ if d > 0:
398
+ cleaned = poly.buffer(-d, join_style="mitre").buffer(d, join_style="mitre") # remove thin protrusions
399
+ cleaned = cleaned.buffer(d, join_style="mitre").buffer(-d, join_style="mitre") # fill thin notches
400
+ cand = [q for q in geom.polygons_of(shapely.make_valid(cleaned)) if q.area >= min_part_area]
401
+ poly = max(cand, key=lambda q: q.area) if cand and max(q.area for q in cand) > 0.8 * poly.area else poly
402
+ if simplify > 0:
403
+ poly = geom.largest_polygon(shapely.make_valid(poly.simplify(simplify, preserve_topology=True)))
404
+ if regularize:
405
+ reg = _regularize(poly, r, band=2.0 * cell, merge_tol=max(1.5 * cell, d), axis_tol=1.5 * cell)
406
+ if reg is not None:
407
+ poly = reg
408
+ regularized += 1
409
+ parts.append(poly)
410
+ fp_r = geom.footprint_parts(shapely.union_all(parts), min_area=min_part_area)
411
+ fp = shapely.transform(fp_r, lambda c: geom.rotate_xy(c, theta))
412
+ fp = geom.footprint_parts(shapely.set_precision(fp, 0.001), min_area=min_part_area)
413
+ inside = shapely.contains_xy(fp.buffer(0.1), xy[:, 0], xy[:, 1]).mean()
414
+ real = geom.translate_geom(fp, data.origin[0], data.origin[1])
415
+ out = bdir.new_file("footprint_derived", ".geojson", overwrite)
416
+ geom.write_footprint(out, real, data.meta.get("epsg"), {"source": "derived_from_points", "cell_m": cell})
417
+ bdir.update_meta(footprint=out.name)
418
+ polys = geom.polygons_of(fp)
419
+ warnings = []
420
+ if dropped > 0.1 * fp.area:
421
+ warnings.append(f"dropped {dropped:.0f} m2 of small detached parts")
422
+ if inside < 0.97:
423
+ warnings.append(f"only {inside:.1%} of roof points fall inside the footprint")
424
+ return {
425
+ "footprint": out.name,
426
+ "parts": len(polys),
427
+ "area_m2": round(fp.area, 1),
428
+ "vertices": sum(len(q.exterior.coords) - 1 + sum(len(h.coords) - 1 for h in q.interiors) for q in polys),
429
+ "holes": sum(len(q.interiors) for q in polys),
430
+ "roof_points_inside": round(float(inside), 4),
431
+ "cell_m": round(cell, 3),
432
+ "min_feature_m": min_feature,
433
+ "regularized_parts": regularized,
434
+ "warnings": warnings,
435
+ }
436
+
437
+
438
+ def _regularize(
439
+ poly: Polygon, pts: np.ndarray, *, band: float, merge_tol: float, angle_tol_deg: float = 12.0, axis_tol: float = 0.0
440
+ ) -> Polygon | None:
441
+ """Snap near-axis edges (in the building-aligned frame) to the outermost roof points.
442
+
443
+ Horizontal/vertical edges are refitted to the 1st/99th percentile of the
444
+ roof points in a band along the edge; neighbouring parallel edges closer
445
+ than ``merge_tol`` are merged; corners are rebuilt as line intersections.
446
+ Returns None when the result is invalid or changes the area by >15%.
447
+ """
448
+ from shapely.geometry.polygon import orient as _orient
449
+
450
+ poly = _orient(poly, 1.0)
451
+ P = np.asarray(poly.exterior.coords)[:-1]
452
+ n = len(P)
453
+ if n < 3:
454
+ return None
455
+ lines: list[list[Any]] = []
456
+ for i in range(n):
457
+ a, b = P[i], P[(i + 1) % n]
458
+ d = b - a
459
+ L = float(np.hypot(*d))
460
+ ang = np.degrees(np.arctan2(abs(d[1]), abs(d[0])))
461
+ if L < 1e-9:
462
+ lines.append(["o", a, d, L])
463
+ continue
464
+ # near an axis by angle, or (short edges) off the axis by at most one raster cell
465
+ near_h = ang < angle_tol_deg or abs(d[1]) <= axis_tol < abs(d[0])
466
+ near_v = ang > 90 - angle_tol_deg or abs(d[0]) <= axis_tol < abs(d[1])
467
+ if near_h or near_v:
468
+ axis = 1 if near_h else 0 # coordinate that is constant along the edge
469
+ along = 1 - axis
470
+ lo, hi = sorted([a[along], b[along]])
471
+ shrink = min(0.5, 0.25 * (hi - lo))
472
+ c0 = 0.5 * (a[axis] + b[axis])
473
+ outward = np.array([d[1], -d[0]])[axis] # right-hand normal points outward for CCW rings
474
+ m = (pts[:, along] > lo + shrink) & (pts[:, along] < hi - shrink) & (np.abs(pts[:, axis] - c0) < band)
475
+ c = float(np.percentile(pts[m, axis], 99 if outward > 0 else 1)) if m.sum() >= 5 else c0
476
+ lines.append(["h" if axis == 1 else "v", c, L])
477
+ else:
478
+ lines.append(["o", a, d, L])
479
+ # drop short oblique "chamfer" edges between an axis edge pair of different kinds
480
+ starts = [P[i] for i in range(n)]
481
+ i = 0
482
+ while i < len(lines) and len(lines) > 3:
483
+ e, prev, nxt = lines[i], lines[i - 1], lines[(i + 1) % len(lines)]
484
+ length = e[3] if e[0] == "o" else e[2]
485
+ chamfer = e[0] == "o" and length < 2 * merge_tol and prev[0] in "hv" and nxt[0] in "hv" and prev[0] != nxt[0]
486
+ # tiny step between two parallel edges at almost the same offset (raster corner artefact)
487
+ jog = (
488
+ length < 2 * merge_tol
489
+ and prev[0] in "hv"
490
+ and prev[0] == nxt[0]
491
+ and e[0] != prev[0]
492
+ and abs(prev[1] - nxt[1]) < merge_tol
493
+ )
494
+ if chamfer or jog:
495
+ del lines[i]
496
+ del starts[i]
497
+ continue
498
+ i += 1
499
+ P = np.asarray(starts)
500
+ n = len(lines)
501
+ # merge neighbouring parallel axis edges with nearly equal offsets
502
+ for _ in range(2):
503
+ for i in range(n):
504
+ e, f = lines[i], lines[(i + 1) % n]
505
+ if e[0] in "hv" and e[0] == f[0] and abs(e[1] - f[1]) < merge_tol:
506
+ c = (e[1] * e[2] + f[1] * f[2]) / max(e[2] + f[2], 1e-9)
507
+ e[1] = f[1] = c
508
+
509
+ def as_line(e):
510
+ if e[0] == "h":
511
+ return np.array([0.0, e[1]]), np.array([1.0, 0.0])
512
+ if e[0] == "v":
513
+ return np.array([e[1], 0.0]), np.array([0.0, 1.0])
514
+ return e[1], e[2]
515
+
516
+ out = []
517
+ for i in range(n):
518
+ e, f = lines[i - 1], lines[i]
519
+ if e[0] in "hv" and e[0] == f[0]:
520
+ if abs(e[1] - f[1]) < 1e-9:
521
+ continue # collinear: drop the vertex
522
+ if e[0] == "h":
523
+ out += [(P[i][0], e[1]), (P[i][0], f[1])]
524
+ else:
525
+ out += [(e[1], P[i][1]), (f[1], P[i][1])]
526
+ continue
527
+ p1, d1 = as_line(e)
528
+ p2, d2 = as_line(f)
529
+ den = d1[0] * d2[1] - d1[1] * d2[0]
530
+ if abs(den) < 1e-9 * max(np.hypot(*d1) * np.hypot(*d2), 1e-12):
531
+ out.append(tuple(P[i]))
532
+ continue
533
+ t = ((p2[0] - p1[0]) * d2[1] - (p2[1] - p1[1]) * d2[0]) / den
534
+ out.append(tuple(p1 + t * d1))
535
+ if len(out) < 3:
536
+ return None
537
+ holes = [list(r.coords) for r in poly.interiors]
538
+ cand = Polygon(out, holes)
539
+ if not cand.is_valid:
540
+ cand = shapely.make_valid(cand)
541
+ try:
542
+ cand = geom.largest_polygon(cand)
543
+ except WorkspaceError:
544
+ return None
545
+ cand = cand.simplify(0.01)
546
+ if not isinstance(cand, Polygon) or cand.is_empty or not cand.is_valid:
547
+ return None
548
+ if not 0.85 < cand.area / poly.area < 1.15:
549
+ return None
550
+ return cand
agent2mesh/evaluate.py ADDED
@@ -0,0 +1,127 @@
1
+ """Mesh checks against the building's own ALS points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import matplotlib
9
+
10
+ matplotlib.use("Agg")
11
+ import matplotlib.pyplot as plt # noqa: E402
12
+ import numpy as np # noqa: E402
13
+ import trimesh # noqa: E402
14
+
15
+
16
+ def topology(mesh: trimesh.Trimesh) -> dict[str, Any]:
17
+ edges = mesh.edges_sorted
18
+ _, counts = np.unique(edges, axis=0, return_counts=True)
19
+ try:
20
+ bodies = len(mesh.split(only_watertight=False))
21
+ except Exception: # noqa: BLE001
22
+ bodies = None
23
+ return {
24
+ "vertices": int(len(mesh.vertices)),
25
+ "faces": int(len(mesh.faces)),
26
+ "watertight": bool(mesh.is_watertight),
27
+ "winding_consistent": bool(mesh.is_winding_consistent),
28
+ "open_edges": int((counts == 1).sum()),
29
+ "non_manifold_edges": int((counts > 2).sum()),
30
+ "bodies": bodies,
31
+ "volume_m3": round(float(mesh.volume), 2) if mesh.is_watertight else None,
32
+ "area_m2": round(float(mesh.area), 2),
33
+ }
34
+
35
+
36
+ def vertical_errors(mesh: trimesh.Trimesh, pts: np.ndarray, max_points: int = 60000, seed: int = 0):
37
+ if len(pts) > max_points:
38
+ pts = pts[np.random.default_rng(seed).choice(len(pts), max_points, replace=False)]
39
+ top = float(max(mesh.bounds[1, 2], pts[:, 2].max())) + 5.0
40
+ origins = np.column_stack([pts[:, :2], np.full(len(pts), top)])
41
+ dirs = np.tile([0.0, 0.0, -1.0], (len(pts), 1))
42
+ loc, ray_idx, _ = mesh.ray.intersects_location(origins, dirs, multiple_hits=False)
43
+ surf = np.full(len(pts), np.nan)
44
+ surf[ray_idx] = loc[:, 2]
45
+ return pts, pts[:, 2] - surf
46
+
47
+
48
+ def evaluate(
49
+ mesh: trimesh.Trimesh,
50
+ roof: np.ndarray,
51
+ *,
52
+ threshold: float,
53
+ origin: np.ndarray,
54
+ error_png: Path | None,
55
+ title: str,
56
+ ) -> dict[str, Any]:
57
+ topo = topology(mesh)
58
+ pts, err = vertical_errors(mesh, roof)
59
+ hit = np.isfinite(err)
60
+ e = err[hit]
61
+ acc: dict[str, Any] = {"points_checked": int(len(pts)), "uncovered_fraction": round(float(1 - hit.mean()), 4)}
62
+ if len(e):
63
+ ae = np.abs(e)
64
+ acc.update(
65
+ rmse_m=round(float(np.sqrt(np.mean(e**2))), 3),
66
+ mae_m=round(float(ae.mean()), 3),
67
+ median_abs_m=round(float(np.median(ae)), 3),
68
+ p95_abs_m=round(float(np.percentile(ae, 95)), 3),
69
+ max_abs_m=round(float(ae.max()), 3),
70
+ bias_m=round(float(e.mean()), 3),
71
+ within_threshold=round(float((ae <= threshold).mean()), 4),
72
+ threshold_m=threshold,
73
+ )
74
+ # hotspots on a 2 m grid
75
+ hotspots = []
76
+ if len(e):
77
+ cell = 2.0
78
+ ij = np.floor(pts[hit, :2] / cell).astype(np.int64)
79
+ keys, inv = np.unique(ij, axis=0, return_inverse=True)
80
+ inv = inv.ravel()
81
+ s = np.bincount(inv, weights=np.abs(e))
82
+ c = np.bincount(inv)
83
+ mean = s / np.maximum(c, 1)
84
+ for k in np.argsort(-mean):
85
+ if c[k] < 3 or mean[k] <= threshold:
86
+ break
87
+ cx, cy = (keys[k] + 0.5) * cell
88
+ hotspots.append(
89
+ {
90
+ "local_xy": [round(float(cx), 1), round(float(cy), 1)],
91
+ "real_xy": [round(float(cx + origin[0]), 2), round(float(cy + origin[1]), 2)],
92
+ "mean_abs_err_m": round(float(mean[k]), 2),
93
+ "points": int(c[k]),
94
+ }
95
+ )
96
+ if len(hotspots) >= 3:
97
+ break
98
+ issues = []
99
+ if not topo["watertight"]:
100
+ issues.append(f"not watertight ({topo['open_edges']} open edges)")
101
+ if topo["non_manifold_edges"]:
102
+ issues.append(f"{topo['non_manifold_edges']} non-manifold edges")
103
+ if acc.get("rmse_m") is not None and acc["rmse_m"] > threshold:
104
+ issues.append(f"roof RMSE {acc['rmse_m']} m above threshold {threshold} m")
105
+ if acc["uncovered_fraction"] > 0.03:
106
+ issues.append(f"{acc['uncovered_fraction']:.1%} of roof points lie outside the model (footprint too small or wrong)")
107
+ if error_png is not None:
108
+ _error_map(pts, err, threshold, error_png, title)
109
+ return {"topology": topo, "accuracy": acc, "hotspots": hotspots, "issues": issues, "ok": not issues}
110
+
111
+
112
+ def _error_map(pts, err, threshold, path: Path, title: str) -> None:
113
+ fig, ax = plt.subplots(figsize=(7, 6), dpi=90)
114
+ hit = np.isfinite(err)
115
+ lim = max(3 * threshold, 0.3)
116
+ sc = ax.scatter(pts[hit, 0], pts[hit, 1], c=err[hit], s=3, cmap="RdBu_r", vmin=-lim, vmax=lim)
117
+ if (~hit).any():
118
+ ax.scatter(pts[~hit, 0], pts[~hit, 1], c="k", s=6, marker="x", label="outside model")
119
+ ax.legend(loc="upper right", fontsize=8)
120
+ fig.colorbar(sc, ax=ax, label="point z - model z (m)")
121
+ ax.set_aspect("equal")
122
+ ax.set_title(title, fontsize=10)
123
+ ax.set_xlabel("local x (m)")
124
+ ax.set_ylabel("local y (m)")
125
+ fig.tight_layout()
126
+ fig.savefig(path)
127
+ plt.close(fig)