Files
Aislo/B04_PreProcess/B04_PreProcess_Engine_ModelBuild.py
T
eomsangdonandClaude Opus 5.5 11c75f022a refactor(767-1): 안 쓰는 지면 필터 · 서피스 지움 — 필터 넷(CSF · 격자 최저 · PMF · RANSAC) · 표현 셋(TIN + Taubin 평활 · NURBS · meshfree) · 수치지형도 비교 방식 다섯 · 안 부르는 길 정리
- 필터 = 업체 분류 · 점진 TIN · 둘의 다듬기 판만 · 분석 허용 목록 = Ground 등록부(available_filters) 한 벌
- 표현 = DTM · implicit 만 · 평활 = DTM 만 · config 기본 목록 · PRECOMPUTE · 설정 사전 맞춤(설정 지문 바뀜 — 768 에서 다시 지음)
- 등고선 = 격자 · 굳힌 격자만(삼각망 굽기 · 외곽 맞춤 · implicit RBF 폴백 걷음) · 표본기 · 경로 찾기 tin · nurbs · meshfree 갈래 걷음
- 수치지형도 = 라플라스만(TIN 둘 · TPS · ANUDEM형 · 다중해상도 걷음) · B04 단추 하나
- 안 부르는 길 — B04 JSON 점군 GET · ground-stats GET + TS · B07 옛 계획평면도(라이다) 짓기 · lidar_source · LIDAR_ID · plan_lidar 종류 이름 · SOURCE_FILTER_LABELS · MODEL_METHODS(py) · MESH_* 설정
- 옛 manifest 의 지운 갈래 줄은 DB 로 되살리지 않음 · 옛 csf 행은 미리보기 · 등고선 그대로 열림 · 지운 이름 요청 = 400
- 낡은 글 — Ground · Pipeline 머리 · WF1 「없으면 csf」 · B07 음영 기본 「csf」 → 빈 값 · 등고선 폴백 「csf」 → 404 · B04 3D 보기 처음값 · B05 Schema · B06 Prebuild · 씨닝 설명
- 시험 지움 2 — test_b04_contour_raster · test_b04_contour_equivalence(지운 삼각망 굽기 · 없는 프로젝트를 봐 건너뛰던 것)
- 시험 덜어냄 — test_b04_ground_filters CSF · 격자 최저 네 경우(지운 필터)
- 시험 고침 — 허용 목록 · 형 검사에 걸린 csf · tin · grid_min_z · meshfree · tin_sheet 견본을 ptd · implicit · laplace 로(54_22 · 238_1 · 443 · 342_2 · 346_3 · 351_1 · 442_2 · 271 + helper · 344_1 · 133_1 · 343_2 · 637 · 754_1 · 763_1 깨진 tin → 깨진 implicit · 763_3 · b05 둘 · b06 · sheet_surface TIN(도엽선) 경우 지움) · 이름만 바꿈(273_2 · 343_1 · 343_3 · 624_1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 16:35:12 +09:00

147 lines
5.6 KiB
Python

"""B04 지표면 표현 빌더 (DTM/implicit).
TerrainContext에서 파생 격자·샘플을 받아 각 표현의 모델(npz)과 프리뷰
(GLB)를 저장하고 메타데이터를 반환한다.
"""
from contextlib import suppress
from pathlib import Path
from typing import Any
import numpy as np
from scipy.interpolate import RBFInterpolator
from B04_PreProcess.B04_PreProcess_Engine_ModelContext import (
ProgressCallback,
TerrainContext,
artifact_size,
atomic_npz,
clip_and_compact_mesh,
grid_faces,
grid_vertices,
with_footprint,
write_glb,
)
from common_util.common_util_surface_sampler import implicit_grid_npz
def build_dtm(
context: TerrainContext, output_dir: Path, stem: str, progress: ProgressCallback
) -> dict[str, Any]:
progress(10)
resolution = float(context.config["dtm_grid_resolution_meters"])
x_coords, y_coords, z_grid = context.grid(resolution)
progress(55)
preview_x, preview_y, preview_z = context.preview_grid(resolution)
vertices = grid_vertices(preview_x, preview_y, preview_z)
faces = grid_faces(len(preview_y), len(preview_x))
valid_grid = context.contains_xy(*np.meshgrid(x_coords, y_coords)).reshape(
len(y_coords), len(x_coords)
)
preview_valid = context.contains_xy(vertices[:, 0], vertices[:, 1])
vertices, faces = clip_and_compact_mesh(vertices, faces, preview_valid)
model_path = output_dir / f"{stem}.npz"
preview_path = output_dir / f"{stem}_preview.glb"
atomic_npz(
model_path,
x=x_coords,
y=y_coords,
z=z_grid,
valid_mask=valid_grid,
filled_mask=context.filled(resolution) & valid_grid,
resolution=np.array([resolution], np.float32),
)
progress(75)
write_glb(preview_path, vertices, faces, context.bounds)
progress(100)
return with_footprint(
context,
{
"representation": "regular_grid",
"model_file": model_path.name,
"preview_file": preview_path.name,
"preview_media_type": "model/gltf-binary",
"grid_rows": int(len(y_coords)),
"grid_columns": int(len(x_coords)),
"grid_resolution_meters": resolution,
"vertex_count": int(len(vertices)),
"face_count": int(len(faces)),
"artifact_bytes": artifact_size(model_path, preview_path),
},
)
def implicit_point_count(ground_count: int, config: dict[str, Any]) -> int:
"""implicit 중심점 수 = clip(지면점 × 비율, 하한, 상한) · 지면점이 하한보다 적으면 전부."""
minimum = int(config["implicit_min_points"])
if ground_count <= minimum:
return int(ground_count)
ratio = round(ground_count * float(config["implicit_point_ratio"]))
return int(min(max(ratio, minimum), int(config["implicit_max_points"])))
def build_implicit(
context: TerrainContext, output_dir: Path, stem: str, progress: ProgressCallback
) -> dict[str, Any]:
count = implicit_point_count(context.source_count, context.config)
# 구멍(766-2)은 메운 dtm 칸을 중심점으로 더해 dtm 과 같은 면으로 이음
points = np.concatenate([context.grid_sample(count), context.hole_guides()])
unique_xy, unique_indices = np.unique(points[:, :2], axis=0, return_index=True)
points = points[unique_indices]
if len(points) < 4:
raise ValueError("Implicit 생성에 필요한 포인트가 부족합니다.")
progress(20)
interpolator = RBFInterpolator(
unique_xy.astype(np.float64),
points[:, 2].astype(np.float64),
neighbors=min(64, len(points)),
smoothing=float(context.config["implicit_smoothing"]),
kernel="thin_plate_spline",
)
x_preview, y_preview, _ = context.preview_grid(
float(context.config["dtm_grid_resolution_meters"])
)
xx, yy = np.meshgrid(x_preview, y_preview)
query = np.column_stack([xx.ravel(), yy.ravel()])
z_values = np.empty(len(query), dtype=np.float32)
for start in range(0, len(query), 50_000):
end = min(start + 50_000, len(query))
z_values[start:end] = interpolator(query[start:end]).astype(np.float32)
progress(25 + int(45 * end / len(query)))
z_grid = z_values.reshape(len(y_preview), len(x_preview))
vertices = grid_vertices(x_preview, y_preview, z_grid)
faces = grid_faces(len(y_preview), len(x_preview))
valid_preview = context.contains_xy(vertices[:, 0], vertices[:, 1])
vertices, faces = clip_and_compact_mesh(vertices, faces, valid_preview)
model_path = output_dir / f"{stem}.npz"
preview_path = output_dir / f"{stem}_preview.glb"
atomic_npz(
model_path,
centers_xy=unique_xy.astype(np.float32),
center_z=points[:, 2].astype(np.float32),
smoothing=np.array([float(context.config["implicit_smoothing"])], np.float32),
)
write_glb(preview_path, vertices, faces, context.bounds)
with suppress(OSError, ValueError): # 641-1 굳힌 격자 — 못 지으면 처음 읽을 때 지음
implicit_grid_npz(output_dir, stem.removeprefix("implicit_"))
progress(100)
return with_footprint(
context,
{
"representation": "local_rbf_height_field",
"model_file": model_path.name,
"preview_file": preview_path.name,
"preview_media_type": "model/gltf-binary",
"center_count": int(len(points)),
"vertex_count": int(len(vertices)),
"face_count": int(len(faces)),
"artifact_bytes": artifact_size(model_path, preview_path),
},
)
BUILDERS = {
"dtm": build_dtm,
"implicit": build_implicit,
}