diff --git a/B04_PreProcess/B04_PreProcess_Engine_Watershed_Descent.py b/B04_PreProcess/B04_PreProcess_Engine_Watershed_Descent.py index 5f7a54e7..e854be43 100644 --- a/B04_PreProcess/B04_PreProcess_Engine_Watershed_Descent.py +++ b/B04_PreProcess/B04_PreProcess_Engine_Watershed_Descent.py @@ -72,12 +72,25 @@ class ContourDescent: levels: list[float] # 사용된 등고 표고(내림차순) -def rasterize_contours( - spec: GridSpec, - contour_features: list[dict[str, Any]], - elevation_floor_m: float | None = None, -) -> tuple[np.ndarray, list[float]]: - """등고선을 격자에 굽는다. 셀마다 그 위를 지나는 등고 라인의 표고(없으면 NaN).""" +_LINES_CACHE: list[tuple[Any, int, float | None, dict[float, list[Any]]]] = [] + + +def _lines_by_level( + contour_features: list[dict[str, Any]], elevation_floor_m: float | None +) -> dict[float, list[Any]]: + """등고선 피처를 표고별 선 묶음으로 푼다 — **격자와 무관**하므로 한 번만 푼다. + + 확장 회차마다 다시 부르는데 피처 4,200개를 매번 `shape()` 로 푸는 비용이 그대로 + 붙었다. 같은 목록·같은 하한이면 그대로 돌려준다(목록 객체를 함께 들고 있어 id 가 + 다른 목록에 재사용되지 않는다). + """ + for holder, count, floor, cached in _LINES_CACHE: + if ( + holder is contour_features + and count == len(contour_features) + and floor == elevation_floor_m + ): + return cached by_level: dict[float, list[Any]] = {} for feature in contour_features: geometry = feature.get("geometry") @@ -96,7 +109,18 @@ def rasterize_contours( if line.length < DRAINAGE_CONTOUR_MIN_LENGTH_M: continue by_level.setdefault(float(elevation), []).append(line) + _LINES_CACHE.append((contour_features, len(contour_features), elevation_floor_m, by_level)) + del _LINES_CACHE[:-2] + return by_level + +def rasterize_contours( + spec: GridSpec, + contour_features: list[dict[str, Any]], + elevation_floor_m: float | None = None, +) -> tuple[np.ndarray, list[float]]: + """등고선을 격자에 굽는다. 셀마다 그 위를 지나는 등고 라인의 표고(없으면 NaN).""" + by_level = _lines_by_level(contour_features, elevation_floor_m) burned = np.full((spec.n_rows, spec.n_cols), np.nan, dtype=np.float32) levels = sorted(by_level, reverse=True) transform = grid_transform(spec)