Files
Aislo/common_util/common_util_structure_station.py
T
eomsangdonandClaude Opus 5.5 69ffd17317 feat(380-3): 노선 따라간 사토장 · 토취장 = 새 노선 일반 측점 맞춤 · test_322_2 마스터 판 독립
- follow_structures ↔ followStructures(intervalM): site 꼴 = 새 노선 일반 측점(격자 · 끝) 중 가장 가까운 곳 · 그 밖 정수 m 그대로
- 파이썬 snap_existing_station ↔ TS snapExistingStation · general_stations ↔ gridStations 짝
- 브라우저 노선 초안 따라감(Pipeline_Grade) = 측점 간격 넘김 · 서버 노선 저장 따라감 = 서버 간격
- test_322_2: B05 목록 고정 수 23 대신 both 목록 수와 같음(M02 켬끔 판마다 다름)
- 시험 test_380_3_site_follow(거울 · 가운데면 앞 측점 · 좌표 없음 그대로)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VmC34fsxxbweEG3RUjs3Mn
2026-10-17 15:40:32 +09:00

209 lines
8.9 KiB
Python

"""구조물 · 관 기준 측점 = 정수 m(반올림 · .5 는 올림) · 노선 끝 안쪽(요구 167 · 272).
측점 값(측점 + 거리 · 누가거리)에 소수를 안 씀 — 일반 측점(격자)과 같은 m 면 서버 측점
만들기가 한 측점으로 합침(구조물 측점이 위 · `B05_Profile_Engine_Sections_Core`).
234-1 의 「일반 측점 1 m 안 붙기」는 뺌(그냥 정수 · 사용자 167).
TS 짝 = `common_util/common_util_structure_station.ts`
(화면 입력 · 끌기 · 방향키 · 옛 자료 정수 옮김 ·
측점 계획 `plan_stations` ↔ `planStations` · 322-3 · 추가 측점 `plus` 368-2).
거울 시험 = `resources/tester/test_234_1_structure_station.py`.
일반 측점 = 격자(간격) · 시종점 — 끝(노선 길이)을 넘지 않게 자르는 데만 씀.
"""
from __future__ import annotations
import math
from collections.abc import Sequence
from dataclasses import replace
from typing import TypeVar
from common_util.common_util_route_geometry import RouteVertex, interpolate_vertex
from config.config_system_design import SECTION_STATION_INTERVAL_M
_Candidate = TypeVar("_Candidate")
_EPS = 1e-6
def general_stations(total_m: float, interval_m: float) -> list[float]:
"""격자 측점 + 끝 측점(`Sections_Core._chainages` 와 같은 줄)."""
if not (total_m > 0 and interval_m > 0):
return [0.0]
values = [index * interval_m for index in range(int(total_m // interval_m) + 1)]
if total_m - values[-1] > _EPS:
values.append(float(total_m))
return values
def snap_structure_station(chainage_m: float, stations: Sequence[float]) -> float:
"""기준 측점 = 정수 m(.5 는 올림) · 0 ~ 노선 끝(소수 끝은 그 아래 정수) 안 · 멱등."""
value = float(chainage_m)
if not math.isfinite(value):
return value
end = max(stations) if stations else math.inf
whole = float(math.floor(value + 0.5))
return max(0.0, min(whole, float(math.floor(end + _EPS))))
def snap_existing_station(chainage_m: float, stations: Sequence[float]) -> float:
"""가장 가까운 기존 측점(가운데면 앞) · 비면 정수 m — TS `snapExistingStation` 짝."""
value = float(chainage_m)
if not math.isfinite(value) or not stations:
return snap_structure_station(value, stations)
return float(min(stations, key=lambda at: (round(abs(float(at) - value), 6), float(at))))
def route_general_stations(total_m: float) -> list[float]:
"""노선 길이의 일반 측점 — 서버 측점 간격(`SECTION_STATION_INTERVAL_M`)."""
return general_stations(total_m, SECTION_STATION_INTERVAL_M)
def snap_candidates(
candidates: Sequence[_Candidate], vertices: Sequence[RouteVertex]
) -> list[_Candidate]:
"""자동 배치 관 자리 맞춤 — 좌표는 맞춘 자리로 다시 찍고, 같은 자리로 모이면 앞선 것만.
`candidates` 는 `chainage_m · x · y` 를 가진 dataclass(`StructureCandidate`)."""
total_m = float(vertices[-1].chainage_m)
stations = route_general_stations(total_m)
snapped: list[_Candidate] = []
taken: set[float] = set()
for candidate in candidates:
at = snap_structure_station(candidate.chainage_m, stations)
if at in taken:
continue
taken.add(at)
x, y, _ = interpolate_vertex(list(vertices), at)
snapped.append(replace(candidate, chainage_m=at, x=x, y=y))
return snapped
# ── 측점 계획 한 벌(322-3 · TS `planStations` 짝 · 거울 = test_322_3_plan_mirror.py) ──
# ── 같은 자리 거리 한 곳(323-7 · 파이썬은 여기서 가져다 씀 · TS 짝은 이름이 같은 상수) ──
#: 같은 측점으로 볼 거리(m) — 측점 계획 · 반올림 차이만 · TS `SAME_STATION_M` 짝
SAME_STATION_M = 0.005
#: 구간 끝 · 관 세트가 걸치는 측점을 같은 자리로 볼 폭(m) — 정본이 누가거리를 0.01 m 로 끊어 씀 ·
#: TS `EDGE_TOLERANCE_M`(벽 · 포장 · 맹암거) · `CHAINAGE_TOLERANCE_M`(관 세트) 짝
EDGE_TOLERANCE_M = 0.02
#: 관 · 구조물 자리와 측점 · 고름을 같은 자리로 볼 폭(m) — 정수 m 기준 측점 · 옛 소수 자료 · TS
#: `design_selection.PIPE_MATCH_M` 짝
PIPE_MATCH_M = 0.51
def _empty(value: object) -> bool:
return value is None or value == ""
def blank_keys(type_id: str, options: dict | None) -> list[str]:
"""형상 부품 필수 칸 중 값이 빈 키(정의 기본값으로 안 채움 · TS `blankKeys` 짝)."""
from common_util.common_util_structure_catalog import shape_needs
return [key for key in shape_needs(type_id) if _empty((options or {}).get(key))]
def _station_marks(
start: object, anchor: object, end: object, span3: bool
) -> list[tuple[str, float]]:
"""TS `marksOf` 짝 — 수인 자리만 (역할, 누가거리)."""
marks = [("start", start), ("anchor", anchor), ("end", end)] if span3 else [("anchor", anchor)]
return [
(role, float(at))
for role, at in marks
if isinstance(at, (int, float)) and not isinstance(at, bool) and math.isfinite(at)
]
#: 추가 측점 주인 id 앞머리(368-2) — TS `PLUS_OWNER_PREFIX` 짝
PLUS_OWNER_PREFIX = "plus-"
def plan_stations(
pipes: Sequence[object], structures: Sequence[object], plus: Sequence[float] = ()
) -> list[dict[str, object]]:
"""관 · 구조물(현황) + 구조물 표 → 측점 계획 `[{chainage_m, role, title, owners, blank}]`.
오름차순 · 같은 m(0.005) 는 하나 — 이름 = 관이 있으면 첫 관 · 아니면 앞선 구조물(표 카드 이름)
· 덮는 구조물 id(관 = 자리 이름 `pipe-{누가거리}` · 구조물 = structure_id) · 빈칸 경고(형상
부품 필수 칸 중 값이 빈 옵션 키). 표에 없는 종류는 뺌.
`plus` = 추가 측점(정수 m · 368-2) — 주인 `plus-{m}` · 이름 "" · 같은 m 에 관 · 구조물이
있으면 뺌.
"""
from common_util.common_util_structure_catalog import card_title, catalog_row
blank = blank_keys
marks: list[dict[str, object]] = []
for pipe in pipes:
facility = getattr(pipe, "facility", None) or "pipe"
row = catalog_row(facility)
if row is None:
continue
options = getattr(pipe, "options", None)
chainage = float(getattr(pipe, "chainage_m"))
station = row["station"]
for role, at in (
[]
if station == "none"
else _station_marks(
getattr(pipe, "start_m", None),
chainage,
getattr(pipe, "end_m", None),
station == "span3",
)
):
marks.append(
{
"chainage_m": at,
"role": role,
"title": card_title(facility, options),
"owner": getattr(pipe, "id", None) or f"pipe-{chainage:.2f}",
"blank": blank(facility, options),
"pipe": True,
}
)
for item in structures:
row = catalog_row(item.type_id)
if row is None or row["owner"] == "pipe_points" or row["station"] == "none":
continue
anchor = item.chainage_m if item.chainage_m is not None else item.start_m
found = _station_marks(item.start_m, anchor, item.end_m, row["station"] == "span3")
base = next((at for role, at in found if role == "anchor"), 0.0)
for role, at in found:
marks.append(
{
"chainage_m": at,
"role": role,
"title": card_title(item.type_id, item.options),
"owner": item.structure_id or f"structure-{base:.2f}",
"blank": blank(item.type_id, item.options),
"pipe": False,
}
)
own = list(marks)
for at in plus:
if all(abs(float(at) - mark["chainage_m"]) >= SAME_STATION_M for mark in own):
marks.append(
{
"chainage_m": float(at),
"role": "anchor",
"title": "",
"owner": f"{PLUS_OWNER_PREFIX}{round(float(at))}",
"blank": [],
"pipe": False,
}
)
marks.sort(key=lambda mark: mark["chainage_m"])
out: list[dict[str, object]] = []
for mark in marks:
last = out[-1] if out else None
if last is not None and abs(mark["chainage_m"] - last["chainage_m"]) < SAME_STATION_M:
if mark["pipe"] and not last["pipe"]:
last["title"], last["pipe"] = mark["title"], True
if mark["owner"] not in last["owners"]:
last["owners"].append(mark["owner"])
last["blank"] += [key for key in mark["blank"] if key not in last["blank"]]
continue
out.append({**mark, "owners": [mark["owner"]], "blank": list(mark["blank"])})
return [{k: v for k, v in station.items() if k not in ("pipe", "owner")} for station in out]