diff --git a/D03_PlanAnalysis/logic/D03_PlanAnalysis_Expect.ts b/D03_PlanAnalysis/logic/D03_PlanAnalysis_Expect.ts new file mode 100644 index 000000000..3a6c10e0c --- /dev/null +++ b/D03_PlanAnalysis/logic/D03_PlanAnalysis_Expect.ts @@ -0,0 +1,124 @@ +/* ============================================================================= + * D03_PlanAnalysis_Expect.ts + * D03 예상 횡단(PLAN 544-1 · 요구 363-1) — 측점 지반 → 표준 횡단 기본값 설계선 · 절 · 성토 ㎡. + * 셈 = 공용 `computeCrossDesign`(① 짝 `compute_cross_design` · 거울 `test_b06_cross_design_mirror.py`) + * · 기본 = B 초기 설계와 같음(리핑암 · 산쪽 절토 · 일반 측구 · 암 경계 = 서버 기본) · 계획고 = 측점 중심 지반고 + * · 미교차 = `extendUnclosed`(격자 있을 때) · 곡선 확폭 없음 · 보기만(저장 없음). + * 3D = 같은 단면을 B05 `buildCorridor` 가 읽는 측점 꼴로(`expectSections`). + * 시험 `resources/tester/test_544_1_plan_expect.py`. + * ========================================================================== */ + +import { + computeCrossDesign, + type CrossDesignOptions, + type CrossDesignResult, + type StandardCrossSectionSpec, +} from "../../common_util/common_util_cross_design"; +import type { DtmGrid } from "../../common_util/common_util_surface_sampler"; +import { + extendUnclosed, + type CrossGroundPoint, + type StationGround, +} from "../../B05_Profile/logic/B05_Profile_Sections_Ground"; + +/** 서버 `sections/context` 의 표준 횡단(config) · 암 경계 기본 오프셋. */ +export interface ExpectStandard { + standard: StandardCrossSectionSpec; + rockBoundaryM: number | null; +} + +export interface ExpectCross { + design: CrossDesignResult; + /** 설계에 쓴 지반 표본(미교차로 넓혔으면 넓힌 것). */ + samples: CrossGroundPoint[]; +} + +/** B 초기 설계 기본 — 리핑암 · 산쪽 절토(모르면 좌) · 일반 측구. */ +export function expectOptions( + uphill: "left" | "right" | null, + std: ExpectStandard, +): CrossDesignOptions { + return { + groundType: "ripping_rock", + sectionMode: `${uphill ?? "left"}_cut`, + ditchType: "standard", + standard: std.standard, + rockBoundaryOffsetM: std.rockBoundaryM, + }; +} + +/** 측점 하나 예상 단면 — 지반고 · 표본이 없으면 null. */ +export function expectCross( + station: StationGround, + std: ExpectStandard, + grid?: DtmGrid | null, +): ExpectCross | null { + const elevation = station.center_z; + if (elevation === null) return null; + const options = expectOptions(station.uphill_side, std); + try { + let samples = station.samples; + let design = computeCrossDesign(samples, elevation, options); + const wide = + design.slope_unclosed && grid + ? extendUnclosed( + samples, + [station.center_x, station.center_y], + station.left_xy, + (next) => computeCrossDesign(next, elevation, options), + grid, + ) + : null; + if (wide) { + samples = wide.samples as CrossGroundPoint[]; + design = computeCrossDesign(samples, elevation, options); + } + return { design, samples }; + } catch { + return null; // 표본 부족 — B 와 같은 태도(그 측점 건너뜀) + } +} + +/** B06 `CrossSection` 중 `buildCorridor` 가 읽는 칸(B06 형 파일은 별칭 import 라 여기 안 끌어옴). */ +export interface ExpectSection { + station_id: string; + chainage_m: number; + label: string; + kind: "regular"; + center_z: number | null; + azimuth_deg: null; + center_x: number; + center_y: number; + uphill_side: "left" | "right" | null; + frame: { left_xy: [number, number] }; + samples: CrossGroundPoint[]; + design: CrossDesignResult; +} + +/** 3D 코리도 입력 — 측점마다 예상 단면(못 세운 측점 뺌) · 누가 = 연도 노선 위 누가. */ +export function expectSections( + stations: StationGround[], + std: ExpectStandard, + grid?: DtmGrid | null, +): ExpectSection[] { + return stations.flatMap((station) => { + const cross = expectCross(station, std, grid); + if (!cross) return []; + return [ + { + station_id: String(station.chainage_m), + chainage_m: station.chainage_m, + label: "", + kind: "regular", + center_z: station.center_z, + azimuth_deg: null, + center_x: station.center_x, + center_y: station.center_y, + uphill_side: station.uphill_side, + frame: { left_xy: station.left_xy }, + samples: cross.samples, + design: cross.design, + }, + ]; + }); +} diff --git a/resources/tester/test_544_1_plan_expect.py b/resources/tester/test_544_1_plan_expect.py new file mode 100644 index 000000000..eadfcde49 --- /dev/null +++ b/resources/tester/test_544_1_plan_expect.py @@ -0,0 +1,187 @@ +"""D03 예상 횡단(PLAN 544-1) — TS `logic/D03_PlanAnalysis_Expect.ts` 값 = 파이썬 `compute_cross_design`. + +기본 = 리핑암 · 산쪽 절토(모르면 좌) · 일반 측구 · 암 경계 = config 기본 · 계획고 = 측점 중심 지반고. +미교차 = 격자로 넓힌 표본 · 넓힌 표본으로 파이썬이 다시 셈한 값과 같음 · 코리도 측점 꼴. + +./venv/Scripts/python.exe -m pytest resources/tester/test_544_1_plan_expect.py -q +""" + +from __future__ import annotations + +import json +import re +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from B06_Section.B06_Section_Engine_Design import compute_cross_design # noqa: E402 +from config.config_system_design import ( # noqa: E402 + STANDARD_CROSS_SECTION, + STANDARD_ROCK_BOUNDARY_DEFAULT_OFFSET_M, +) + +TS_FILE = ROOT / "D03_PlanAnalysis" / "logic" / "D03_PlanAnalysis_Expect.ts" +TSC = ROOT / "config" / "node_modules" / "typescript" / "bin" / "tsc" + +_RUNNER = """ +import { readFileSync, writeFileSync } from "node:fs"; +import * as expect from "./D03_PlanAnalysis/logic/D03_PlanAnalysis_Expect.js"; +const job = JSON.parse(readFileSync(process.argv[2], "utf8")); +const std = { standard: job.standard, rockBoundaryM: job.rock }; +// 평면 격자 — z = 100 + slope * y(좌 축 = +y) · 1 m · ±100 m +const n = 201; +const axis = Float64Array.from({ length: n }, (_, i) => i - 100); +const z = new Float64Array(n * n); +for (let iy = 0; iy < n; iy += 1) + for (let ix = 0; ix < n; ix += 1) z[iy * n + ix] = 100 + job.wideSlope * axis[iy]; +const grid = { x: axis, y: axis, z, validBits: new Uint8Array(Math.ceil((n * n) / 8)).fill(255) }; +const cross = job.stations.map((s) => expect.expectCross(s, std)); +const wide = expect.expectCross(job.wide, std, grid); +const sections = expect.expectSections([...job.stations, job.wide], std, grid); +writeFileSync(process.argv[3], JSON.stringify({ cross, wide, sections })); +""" + + +def _station(slope: float, uphill: str | None, *, half: float = 20.0) -> dict: + samples = [] + count = int(half * 2 / 0.5) + 1 + for i in range(count): + offset = -half + i * 0.5 + z = round(100.0 + slope * offset, 6) + samples.append( + {"offset_m": offset, "x": 0.0, "y": offset, "z": z, "elevation_m": z, "valid": True} + ) + return { + "chainage_m": 40.0, + "center_x": 0.0, + "center_y": 0.0, + "center_z": 100.0, + "tangent_xy": [1.0, 0.0], + "left_xy": [0.0, 1.0], + "uphill_side": uphill, + "samples": samples, + } + + +_STATIONS = [ + _station(0.30, "left"), + _station(-0.45, "right"), + _station(0.05, None), + {**_station(0.2, "left"), "center_z": None}, +] +_WIDE_SLOPE = 0.8 + + +def _run_ts(tmp_path: Path) -> dict: + out = tmp_path / "js" + subprocess.run( # noqa: S603 — 고정 실행 파일 + [ + "node", + str(TSC), + str(TS_FILE), + "--outDir", + str(out), + "--rootDir", + str(ROOT), + "--module", + "esnext", + "--target", + "es2022", + "--moduleResolution", + "bundler", + "--ignoreConfig", + ], + cwd=str(ROOT), + check=True, + capture_output=True, + ) + for emitted in out.rglob("*.js"): + emitted.write_text( + re.sub(r'(from\s+"\.\.?/[^"]+)"', r'\1.js"', emitted.read_text(encoding="utf-8")), + encoding="utf-8", + ) + (out / "runner.mjs").write_text(_RUNNER, encoding="utf-8") + job = tmp_path / "job.json" + result = tmp_path / "out.json" + job.write_text( + json.dumps( + { + "standard": STANDARD_CROSS_SECTION, + "rock": STANDARD_ROCK_BOUNDARY_DEFAULT_OFFSET_M, + "stations": _STATIONS, + "wide": _station(_WIDE_SLOPE, "left"), + "wideSlope": _WIDE_SLOPE, + } + ), + encoding="utf-8", + ) + subprocess.run( # noqa: S603 + ["node", str(out / "runner.mjs"), str(job), str(result)], + cwd=str(ROOT), + check=True, + capture_output=True, + ) + return json.loads(result.read_text(encoding="utf-8")) + + +def _python(samples: list[dict], elevation: float, uphill: str | None) -> dict: + return compute_cross_design( + samples, + elevation, + ground_type="ripping_rock", + section_mode=f"{uphill or 'left'}_cut", + ditch_type="standard", + standard=STANDARD_CROSS_SECTION, + rock_boundary_offset_m=STANDARD_ROCK_BOUNDARY_DEFAULT_OFFSET_M, + ) + + +def _same(ts: dict, py: dict) -> None: + assert ts["section_mode"] == py["section_mode"] + assert ts["ground_type"] == "ripping_rock" and ts["ditch_type"] == "standard" + assert abs(ts["cut_area_m2"] - py["cut_area_m2"]) < 1e-9 + assert abs(ts["fill_area_m2"] - py["fill_area_m2"]) < 1e-9 + assert len(ts["design_line"]) == len(py["design_line"]) + for a, b in zip(ts["design_line"], py["design_line"]): + assert abs(a["offset_m"] - b["offset_m"]) < 1e-9 + assert abs(a["elevation_m"] - b["elevation_m"]) < 1e-9 + + +def test_expect_matches_python(tmp_path: Path) -> None: + got = _run_ts(tmp_path) + for station, ts in zip(_STATIONS, got["cross"]): + if station["center_z"] is None: + assert ts is None # 지반고 없음 = 못 세움 + continue + py = _python(station["samples"], station["center_z"], station["uphill_side"]) + _same(ts["design"], py) + assert ts["design"]["design_elevation_m"] == station["center_z"] + # 산쪽 절토 · 모르면 좌 + assert [c and c["design"]["section_mode"] for c in got["cross"]] == [ + "left_cut", + "right_cut", + "left_cut", + None, + ] + # 비탈 표본 — 절토 · 성토 둘 다 섬 + assert got["cross"][0]["design"]["cut_area_m2"] > 0 + assert got["cross"][0]["design"]["fill_area_m2"] > 0 + + +def test_unclosed_extends_and_sections(tmp_path: Path) -> None: + got = _run_ts(tmp_path) + wide = got["wide"] + narrow = _python(_station(_WIDE_SLOPE, "left")["samples"], 100.0, "left") + assert narrow["slope_unclosed"] is True # ±20 m 안에선 안 닫힘 + assert wide["design"]["slope_unclosed"] is False + assert min(s["offset_m"] for s in wide["samples"]) < -20.0 + _same(wide["design"], _python(wide["samples"], 100.0, "left")) + # 코리도 측점 = 세운 측점만(지반고 없는 측점 뺌) · 좌 축 · 설계 실음 + sections = got["sections"] + assert len(sections) == 4 + assert all(s["frame"]["left_xy"] == [0.0, 1.0] and s["design"]["design_line"] for s in sections) + assert sections[-1]["samples"] == wide["samples"]