Files
Aislo/common_util/common_util_station_key.py
T
eomsangdonandClaude Opus 5.5 a02367e615 feat(475-3 요구 275-3): 노선이 바뀌면 자리 칸(암 경계 · 2단 경사 · 손 상단측)은 같은 자리 측점만 넘김 — 새 자리 = 기본값
- 자리 칸 목록 한 벌 = TS `SEAT_KEYS`(Station_Swap · 파이썬 Router_Design 이 그 글을 읽음) — two_stage_slope · rock_boundary_offset_m · cut_slope_ratio_user · section_mode · ditch_side
- 자리 판정 한 벌 = `sameSeat` ↔ 파이썬 `same_seat`(중심 0.01 m · 왼쪽 축 1e-3 · 모르면 같은 자리 = 옛 동작)
- 끌기 세션 넘김 · Node stations.carry = `carryKeyedStates`(목록 측점 자리 · 값마다 쓴 때 자리 `@seat` — 되돌리기로 되살린 값도 제 자리로)
- 미리보기 = `pipelineCrossSource` 가 저장분 · 세션 자리 칸에 자리째 실음 → `crossAtSeat` 가 새 자리면 뺌
- B06 갈아끼움(노선 초안) = 자리 바뀐 측점 설계의 자리 칸 걷고 기본값(`unseated` · 브레인 덧)
- 서버 노선 저장 = `carry_cross_inputs` 자리 칸 같은 자리만 · 손 단면 유형 · 측구 방향 = `compute_default_designs` 입력
- 옛 단언 시험 고침(자리 모름 목록 = 같은 자리 = 손 상단측도 넘김 · 「@seat」 칸 거름) · 새 시험 test_475_3_seat_carry
- 위키 rules 넘김 규칙 줄

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:29:38 +09:00

142 lines
5.7 KiB
Python

"""측점 열쇠 한 규칙(PLAN 344-3) — 노선이 바뀌어도 같은 측점을 같은 이름으로 부름.
일반 = ``grid:k``(누가거리 ÷ 측점 간격 반올림) · 관 = ``pipe:<id>`` · 구조물 = ``structure:<id>`` ·
시종점 = ``end:BP`` · ``end:EP`` · id 를 모르는 구조물 측점 = ``at:<누가거리 0.01 m>`` ·
곡선 측점(MC · 252-2) = ``curve:<누가거리 0.01 m>``.
구간형 구조물 시작 · 끝 측점 = ``structure:<id>:start`` · ``:end``(기준 측점은 ``structure:<id>``).
한 목록에 같은 열쇠가 둘이면 둘째부터 ``at:<누가거리>``(``dedupe_station_keys``).
MC 가 움직여 곡선 열쇠가 바뀌면 넘길 때 가까운 새 곡선 측점으로 이음(``curve_moves`` · 432-3).
⚠ 파이썬·TS 짝 — ``common_util_station_key.ts`` ``stationKey`` ↔ ``station_key``.
한쪽을 고치면 다른 쪽도 고치고 거울 시험 ``resources/tester/test_344_3_station_key_mirror.py``.
"""
from __future__ import annotations
import math
import re
_LOOSE = re.compile(r"^-?\d+(\.\d+)?$")
def _half_up(value: float) -> int:
"""JS ``Math.round`` 와 같은 반올림(0.5 는 위로)."""
return math.floor(value + 0.5)
def chainage_key(chainage_m: float) -> str:
"""누가거리 0.01 m — 옛 초안 열쇠(``toFixed(2)``)와 같은 자릿수."""
return f"{_half_up(chainage_m * 100) / 100:.2f}"
def station_key(
kind: str,
chainage_m: float,
interval_m: float | None,
station_id: str | None = None,
id_kind: str = "structure",
role: str = "anchor",
) -> str:
"""측점 열쇠 — irregular 는 id 가 있으면 pipe: · structure:(``id_kind``) · 없으면 at:.
구간형 시작 · 끝은 ``role`` 로 ``:start`` · ``:end``. ``grid`` · ``end`` 는 ``station_id`` 에
원래 격자 번호 · BP/EP(없으면 누가거리 ÷ 간격 반올림 · 0 이면 BP).
"""
loose = f"at:{chainage_key(chainage_m)}"
suffix = "" if role == "anchor" else f":{role}"
if kind == "bp":
return "end:BP"
if kind == "ep":
return "end:EP"
if kind == "end":
return (
f"end:{station_id if station_id is not None else ('BP' if chainage_m <= 0 else 'EP')}"
)
if kind == "curve":
return f"curve:{chainage_key(chainage_m)}"
if kind in ("pipe", "structure"):
return f"{kind}:{station_id}{suffix}" if station_id else loose
if kind == "irregular":
return f"{id_kind}:{station_id}{suffix}" if station_id else loose
if kind == "grid" and station_id is not None:
return f"grid:{station_id}"
if interval_m and interval_m > 0:
return f"grid:{_half_up(chainage_m / interval_m)}"
return loose
def dedupe_station_keys(keys: list[str], chainages: list[float]) -> list[str]:
"""한 목록에 같은 열쇠가 둘이면 둘째부터 ``at:<누가거리>`` — 열쇠마다 측점 하나."""
seen: set[str] = set()
out: list[str] = []
for key, chainage in zip(keys, chainages, strict=True):
unique = f"at:{chainage_key(chainage)}" if key in seen else key
seen.add(unique)
out.append(unique)
return out
def loose_chainage(key: str) -> float | None:
"""옛 초안 열쇠(누가거리 글) · ``at:`` 열쇠의 누가거리 — 측점 열쇠면 None."""
text = key[3:] if key.startswith("at:") else key
return float(text) if _LOOSE.match(text) else None
#: 옮긴 곡선 측점으로 보는 거리(m) — 옛 MC 자리에서 이 안의 새 MC.
CURVE_NEAR_M = 10.0
def curve_moves(before: list[tuple[str, float]], after: list[tuple[str, float]]) -> dict[str, str]:
"""MC 가 움직여 바뀐 ``curve:`` 열쇠 → 가까운 새 곡선 열쇠.
옛 목록에만 있는 곡선 열쇠 → 새 목록에만 있는 가장 가까운 곡선 열쇠(``CURVE_NEAR_M`` 안 ·
새 열쇠 하나에 옛 열쇠 하나 · 옛 누가거리 차례).
"""
was = {key for key, _ in before}
kept = {key for key, _ in after}
free = [(key, at) for key, at in after if key.startswith("curve:") and key not in was]
out: dict[str, str] = {}
for key, at in sorted(before, key=lambda item: item[1]):
if not key.startswith("curve:") or key in kept:
continue
best = -1
for index, (_, to) in enumerate(free):
gap = abs(to - at)
if gap <= CURVE_NEAR_M and (best < 0 or gap < abs(free[best][1] - at)):
best = index
if best >= 0:
out[key] = free.pop(best)[0]
return out
#: 같은 자리로 보는 중심 차(m) · 축 차 — 브라우저 틀 ↔ 서버 틀 차(467)를 넘김.
SEAT_XY_M = 0.01
SEAT_AXIS = 1e-3
def station_seat(station: dict | None) -> tuple[float, float, tuple[float, float] | None] | None:
"""종단 측점 줄(``center_x`` · ``center_y`` · ``frame.left_xy``) → 자리 · 모르면 None."""
if not isinstance(station, dict):
return None
try:
x, y = float(station["center_x"]), float(station["center_y"])
except (KeyError, TypeError, ValueError):
return None
left = (station.get("frame") or {}).get("left_xy")
axis = (float(left[0]), float(left[1])) if isinstance(left, list) and len(left) == 2 else None
return x, y, axis
def same_seat(a, b) -> bool:
"""노선이 바뀐 뒤 그 측점이 같은 자리인가(요구 275-3) — 짝 ``sameSeat`` · 거울 475-3.
자리 = (x, y, 왼쪽 단위 벡터 | None) · 한쪽을 모르면 같은 자리로 봄(옛 동작).
"""
if a is None or b is None:
return True
if math.hypot(a[0] - b[0], a[1] - b[1]) > SEAT_XY_M:
return False
if a[2] is None or b[2] is None:
return True
return abs(a[2][0] - b[2][0]) <= SEAT_AXIS and abs(a[2][1] - b[2][1]) <= SEAT_AXIS