"""B04 등고선 추출 엔진. 5종 표현(regular_grid/triangular_mesh/bspline_surface/local_rbf_height_field/ meshfree_surfels)의 npz 모델에서 표고 격자를 환원하고, marching squares로 지정 간격 등고선 라인을 추출한다. DTM valid_mask를 footprint로 사용해 경계 누출을 차단한다. """ from pathlib import Path from typing import Any import numpy as np from scipy.interpolate import RBFInterpolator, RectBivariateSpline from skimage import measure # 등고선 캐시 형식/추출 규칙이 바뀔 때 증가시킨다. CONTOUR_EXTRACTOR_VERSION = 3 def extract_contours_from_grid( x_coords: np.ndarray, y_coords: np.ndarray, z_grid: np.ndarray, valid_mask: np.ndarray | None, interval: float, min_interval: float = 0.5, scene_center: tuple[float, float, float] | None = None, ) -> list[dict[str, Any]]: """정규 표고 격자로부터 등고선 라인을 추출한다.""" interval = max(interval, min_interval) finite_mask = np.isfinite(z_grid) if valid_mask is not None: finite_mask &= valid_mask if not finite_mask.any(): return [] z_min = float(np.min(z_grid[finite_mask])) z_max = float(np.max(z_grid[finite_mask])) start_level = np.ceil(z_min / interval) * interval levels = np.arange(start_level, z_max, interval) if len(levels) == 0: return [] if len(levels) > 500: new_interval = (z_max - z_min) / 100.0 levels = np.arange(np.ceil(z_min / new_interval) * new_interval, z_max, new_interval) interval = new_interval contours_geojson_list: list[dict[str, Any]] = [] # marching squares의 NaN 문제 예방: 무효 영역을 sentinel(z_min-1000)로 채운다. z_grid_masked = z_grid.copy() if valid_mask is not None: z_grid_masked[~valid_mask] = z_min - 1000.0 invalid_mask = ~np.isfinite(z_grid_masked) if invalid_mask.any(): z_grid_masked[invalid_mask] = z_min - 1000.0 cx, cy, cz = scene_center if scene_center is not None else (0.0, 0.0, 0.0) for level in levels: for contour in measure.find_contours(z_grid_masked, level): current_segment: list[list[float]] = [] for y_idx, x_idx in contour: x_idx_c = np.clip(x_idx, 0, len(x_coords) - 1) y_idx_c = np.clip(y_idx, 0, len(y_coords) - 1) x_0, x_1 = int(np.floor(x_idx_c)), int(np.ceil(x_idx_c)) y_0, y_1 = int(np.floor(y_idx_c)), int(np.ceil(y_idx_c)) is_valid = True if valid_mask is not None and not ( valid_mask[y_0, x_0] and valid_mask[y_0, x_1] and valid_mask[y_1, x_0] and valid_mask[y_1, x_1] ): is_valid = False if not is_valid: if len(current_segment) >= 2: mid_idx = len(current_segment) // 2 contours_geojson_list.append( { "level": float(level), "coordinates": current_segment, "label_position": current_segment[mid_idx], } ) current_segment = [] continue tx = x_idx_c - x_0 ty = y_idx_c - y_0 x_val = (1.0 - tx) * x_coords[x_0] + tx * x_coords[x_1] y_val = (1.0 - ty) * y_coords[y_0] + ty * y_coords[y_1] if scene_center is not None: current_segment.append( [ round(float(x_val - cx), 3), round(float(level - cz), 3), round(float(-(y_val - cy)), 3), ] ) else: current_segment.append( [round(float(x_val), 3), round(float(y_val), 3), round(float(level), 3)] ) if len(current_segment) >= 2: mid_idx = len(current_segment) // 2 contours_geojson_list.append( { "level": float(level), "coordinates": current_segment, "label_position": current_segment[mid_idx], } ) return contours_geojson_list def _load_footprint_mask( model_npz_path: Path, x_coords: np.ndarray, y_coords: np.ndarray ) -> np.ndarray | None: """같은 source filter의 DTM valid_mask를 현재 격자에 최근접 리샘플한다.""" stem = Path(model_npz_path).stem if stem.endswith("_smooth"): stem = stem[:-7] parts = stem.split("_", 1) if len(parts) < 2: return None filter_key = parts[1] dtm_path = Path(model_npz_path).parent / f"dtm_{filter_key}.npz" if not dtm_path.exists(): return None try: d = np.load(dtm_path) dtm_x = np.asarray(d["x"]).ravel() dtm_y = np.asarray(d["y"]).ravel() dtm_mask = np.asarray(d["valid_mask"], dtype=bool) except Exception: return None if len(dtm_x) < 2 or len(dtm_y) < 2: return None def _nearest_idx(axis: np.ndarray, coords: np.ndarray) -> np.ndarray: ascending = bool(axis[0] <= axis[-1]) a = axis if ascending else axis[::-1] idx = np.clip(np.searchsorted(a, coords), 1, len(a) - 1) idx = np.where(np.abs(a[idx - 1] - coords) <= np.abs(a[idx] - coords), idx - 1, idx) return idx if ascending else (len(axis) - 1 - idx) xi = _nearest_idx(dtm_x, np.asarray(x_coords, dtype=np.float64)) yi = _nearest_idx(dtm_y, np.asarray(y_coords, dtype=np.float64)) return dtm_mask[np.ix_(yi, xi)] def _apply_footprint( model_npz_path: Path, x_coords: np.ndarray, y_coords: np.ndarray, valid_mask: np.ndarray ) -> np.ndarray: """valid_mask에 DTM footprint를 교집합으로 적용한다 (형상 다르면 최근접 리샘플).""" fp = _load_footprint_mask(model_npz_path, x_coords, y_coords) if fp is not None: if fp.shape == valid_mask.shape: return valid_mask & fp from scipy.ndimage import zoom zoom_y = valid_mask.shape[0] / fp.shape[0] zoom_x = valid_mask.shape[1] / fp.shape[1] fp_resized = zoom(fp.astype(float), (zoom_y, zoom_x), order=0) > 0.5 if fp_resized.shape == valid_mask.shape: return valid_mask & fp_resized return valid_mask def _tin_face_coverage_mask( vertices: np.ndarray, faces: np.ndarray, xx: np.ndarray, yy: np.ndarray ) -> np.ndarray: """저장된 TIN 면이 실제로 덮는 XY 영역만 True로 반환한다.""" vertices = np.asarray(vertices) faces = np.asarray(faces, dtype=np.int64) if vertices.ndim != 2 or vertices.shape[1] < 2 or not len(faces): return np.zeros(xx.shape, dtype=bool) edges = np.vstack((faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [2, 0]])) edges = np.sort(edges, axis=1) unique_edges, counts = np.unique(edges, axis=0, return_counts=True) boundary_edges = unique_edges[counts == 1] if not len(boundary_edges): return np.zeros(xx.shape, dtype=bool) from shapely import get_parts, intersects_xy, linestrings, polygonize, union_all boundary_lines = linestrings(vertices[boundary_edges, :2]) polygons = list(get_parts(polygonize(boundary_lines))) if not polygons: return np.zeros(xx.shape, dtype=bool) coverage = union_all(polygons) xx_flat = np.asarray(xx, dtype=np.float64).ravel() yy_flat = np.asarray(yy, dtype=np.float64).ravel() res_flat = np.asarray(intersects_xy(coverage, xx_flat, yy_flat), dtype=bool) return res_flat.reshape(xx.shape) def _grid_axes(x_min: float, x_max: float, y_min: float, y_max: float, target_grid_m: float): cols = max(2, int(np.ceil((x_max - x_min) / target_grid_m)) + 1) rows = max(2, int(np.ceil((y_max - y_min) / target_grid_m)) + 1) x_coords = np.linspace(x_min, x_max, cols, dtype=np.float32) y_coords = np.linspace(y_min, y_max, rows, dtype=np.float32) return x_coords, y_coords def extract_contours( model_npz_path: Path, representation: str, interval: float, target_grid_m: float = 1.0, scene_center: tuple[float, float, float] | None = None, ) -> list[dict[str, Any]]: """표현별 npz 모델에서 표고 격자를 환원한 뒤 등고선 리스트를 추출한다.""" model_npz_path = Path(model_npz_path) if not model_npz_path.exists(): raise FileNotFoundError(f"모델 파일이 존재하지 않습니다: {model_npz_path}") data = np.load(model_npz_path) if representation == "regular_grid": x_coords, y_coords, z_grid, valid_mask = ( data["x"], data["y"], data["z"], data["valid_mask"], ) current_res = (x_coords[-1] - x_coords[0]) / (len(x_coords) - 1) step = max(1, int(round(target_grid_m / current_res))) if step > 1: return extract_contours_from_grid( x_coords[::step], y_coords[::step], z_grid[::step, ::step], valid_mask[::step, ::step], interval, scene_center=scene_center, ) return extract_contours_from_grid( x_coords, y_coords, z_grid, valid_mask, interval, scene_center=scene_center ) if representation == "triangular_mesh": from scipy.interpolate import griddata vertices, faces = data["vertices"], data["faces"] x_min, x_max = float(np.min(vertices[:, 0])), float(np.max(vertices[:, 0])) y_min, y_max = float(np.min(vertices[:, 1])), float(np.max(vertices[:, 1])) x_coords, y_coords = _grid_axes(x_min, x_max, y_min, y_max, target_grid_m) xx, yy = np.meshgrid(x_coords, y_coords) z_grid = griddata(vertices[:, :2], vertices[:, 2], (xx, yy), method="linear") face_mask = _tin_face_coverage_mask(vertices, faces, xx, yy) valid_mask = np.isfinite(z_grid) & face_mask valid_mask = _apply_footprint(model_npz_path, x_coords, y_coords, valid_mask) return extract_contours_from_grid( x_coords, y_coords, z_grid, valid_mask, interval, scene_center=scene_center ) if representation == "bspline_surface": control_x, control_y, control_z = data["control_x"], data["control_y"], data["control_z"] degree = int(data["degree"][0]) spline = RectBivariateSpline( control_y, control_x, control_z, kx=min(degree, len(control_y) - 1), ky=min(degree, len(control_x) - 1), s=float(len(control_x) * len(control_y)) * 0.01, ) x_coords, y_coords = _grid_axes( float(control_x[0]), float(control_x[-1]), float(control_y[0]), float(control_y[-1]), target_grid_m, ) z_grid = np.asarray(spline(y_coords, x_coords), dtype=np.float32) valid_mask = _apply_footprint( model_npz_path, x_coords, y_coords, np.ones_like(z_grid, dtype=bool) ) return extract_contours_from_grid( x_coords, y_coords, z_grid, valid_mask, interval, scene_center=scene_center ) if representation == "local_rbf_height_field": centers_xy, center_z = data["centers_xy"], data["center_z"] smoothing = float(data["smoothing"][0]) interpolator = RBFInterpolator( centers_xy.astype(np.float64), center_z.astype(np.float64), neighbors=min(64, len(centers_xy)), smoothing=smoothing, kernel="thin_plate_spline", ) x_min, x_max = float(np.min(centers_xy[:, 0])), float(np.max(centers_xy[:, 0])) y_min, y_max = float(np.min(centers_xy[:, 1])), float(np.max(centers_xy[:, 1])) x_coords, y_coords = _grid_axes(x_min, x_max, y_min, y_max, target_grid_m) xx, yy = np.meshgrid(x_coords, y_coords) z_values = interpolator(np.column_stack([xx.ravel(), yy.ravel()])).astype(np.float32) z_grid = z_values.reshape(len(y_coords), len(x_coords)) valid_mask = _apply_footprint( model_npz_path, x_coords, y_coords, np.ones_like(z_grid, dtype=bool) ) return extract_contours_from_grid( x_coords, y_coords, z_grid, valid_mask, interval, scene_center=scene_center ) if representation == "meshfree_surfels": from scipy.interpolate import griddata from scipy.spatial import Delaunay points = data["points"] x_min, x_max = float(np.min(points[:, 0])), float(np.max(points[:, 0])) y_min, y_max = float(np.min(points[:, 1])), float(np.max(points[:, 1])) x_coords, y_coords = _grid_axes(x_min, x_max, y_min, y_max, target_grid_m) xx, yy = np.meshgrid(x_coords, y_coords) z_grid = griddata(points[:, :2], points[:, 2], (xx, yy), method="linear") valid_mask = np.isfinite(z_grid) try: tri = Delaunay(points[:, :2]) hull_inside = tri.find_simplex(np.column_stack([xx.ravel(), yy.ravel()])) >= 0 valid_mask = valid_mask & hull_inside.reshape(xx.shape) except Exception: pass valid_mask = _apply_footprint(model_npz_path, x_coords, y_coords, valid_mask) return extract_contours_from_grid( x_coords, y_coords, z_grid, valid_mask, interval, scene_center=scene_center ) raise ValueError(f"지원하지 않는 표현 방식입니다: {representation}")