From 0edb7059c8b58fd18df63eb562402aa7a8aaea95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Fri, 23 Oct 2026 15:02:09 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=A3=BC=EB=A7=90=20=EB=82=98=EB=93=A4?= =?UTF-8?q?=EC=9D=B4=20=EC=A0=90=EC=88=98=EB=A5=BC=20=ED=8F=89=EA=B7=A0=20?= =?UTF-8?q?60=20=EC=A0=95=EA=B7=9C=EB=B6=84=ED=8F=AC=EB=A1=9C=20=EB=B3=B4?= =?UTF-8?q?=EC=A0=95,=20=EC=A7=80=EA=B8=88=20=EB=82=A0=EC=94=A8=C2=B7?= =?UTF-8?q?=EB=82=98=EB=93=A4=EC=9D=B4=20=EC=A0=90=EC=88=98=20100=EC=A0=90?= =?UTF-8?q?=EC=9D=80=20=EC=99=84=EB=B2=BD=ED=95=9C=20=EB=82=A0=EB=A7=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 나들이 점수(주말 전국 순위·당일치기)에 지금 날씨 점수와 같은 방식의 바꾸기 표를 적용: 원래 점수를 1년 치 분포의 순위로 보고 평균 60·표준편차 15 정규분포 점수로 바꿈 (weekend_rank.py, outing_score_table.json, scripts/gen_outing_score_table.py) - 나들이 점수 만점 조건을 엄격하게: 체감온도 최적 21°±0.5°, 바람 초속 1m 이하일 때만 100점 (같은 예보를 받는 여러 지역이 한꺼번에 100점이 되던 것을 줄임) - 표 맨 위가 100으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 되던 것을 막기 위해 straighten_top 추가: 표시 점수 83 이하인 마지막 원래 점수에서 100점까지 직선으로 이어, 100점은 구간에서 나올 수 있는 가장 높은 원래 점수(밤은 85)일 때만 나옴. 지금 날씨 점수 표도 다시 만듦 (90점 이상 약 2.4% → 1.5%) - 당일치기 최소 점수는 원래 50점과 같은 날씨 수준(표시 62점)으로 옮김 - 주말 순위 캐시 키를 weekend_rank:v2:<날짜>로 올려 옛 점수 캐시를 쓰지 않게 함 - 테스트 추가: test_outing_score_table, test_weather_score_table(straighten_top·100점 조건) - docs/점수_계산식.md의 지금 날씨 점수·나들이 점수 항목을 새 기준과 숫자로 갱신 --- backend/scripts/gen_outing_score_table.py | 76 ++++++++++++ backend/scripts/gen_weather_score_table.py | 19 ++- backend/services/calc/index_calc.py | 3 +- backend/services/calc/outing_score_table.json | 112 ++++++++++++++++++ .../services/calc/weather_score_table.json | 56 ++++----- backend/services/weekend_rank.py | 23 +++- backend/tests/test_outing_score_table.py | 58 +++++++++ backend/tests/test_weather_score_table.py | 17 +++ docs/점수_계산식.md | 12 +- 9 files changed, 337 insertions(+), 39 deletions(-) create mode 100644 backend/scripts/gen_outing_score_table.py create mode 100644 backend/services/calc/outing_score_table.json create mode 100644 backend/tests/test_outing_score_table.py diff --git a/backend/scripts/gen_outing_score_table.py b/backend/scripts/gen_outing_score_table.py new file mode 100644 index 0000000..03989b4 --- /dev/null +++ b/backend/scripts/gen_outing_score_table.py @@ -0,0 +1,76 @@ +"""나들이 점수 바꾸기 표(services/calc/outing_score_table.json)를 다시 만든다. + +나들이 점수(index_calc.outing: 낮 10~17시, 기온·비·하늘·바람)의 원래 점수를 1년 치 분포의 순위로 보고, +평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다 (지금 날씨 점수와 같은 방식, scripts/gen_weather_score_table.py). +1년 치 날씨는 Open-Meteo 과거 예보로, region.csv 에서 8개마다 1곳(32곳)을 쓴다. 하늘은 구름양 40%·80% 이상을 구름 많음·흐림으로 본다. + +나들이 점수 규칙(OUTING_*)이 바뀌면 실행: cd backend && python scripts/gen_outing_score_table.py +""" + +import csv +import json +import os +import sys +import time +from datetime import date, timedelta + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from common.enums import RainType, Sky # noqa: E402 +from common.logger import LOG # noqa: E402 +from scripts.gen_weather_score_table import _WEATHER, DAYS, EVERY, MEAN, SIGMA, fetch, straighten_top, table # noqa: E402 +from services.calc.index_calc import OUTING_HOURS, Hour, outing # noqa: E402 + +BACKEND = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +REGIONS = os.path.join(BACKEND, "seed", "region.csv") +OUT = os.path.join(BACKEND, "services", "calc", "outing_score_table.json") +_HOURLY = "apparent_temperature,precipitation,precipitation_probability,wind_speed_10m,cloud_cover" + + +def region_scores(lat: float, lon: float, start: date, end: date) -> list[int]: + """한 지점의 날마다 나들이 점수(원래 점수). 10~17시가 모두 있는 날만.""" + base = dict(latitude=lat, longitude=lon, start_date=start.isoformat(), end_date=end.isoformat(), timezone="Asia/Seoul") + w = fetch(_WEATHER, base | dict(hourly=_HOURLY, wind_speed_unit="ms"))["hourly"] + at_index = {t: i for i, t in enumerate(w["time"])} + out = [] + day = start + while day <= end: + hours = [] + for h in range(*OUTING_HOURS): + i = at_index.get(f"{day.isoformat()}T{h:02d}:00") + if i is None or w["apparent_temperature"][i] is None: + break + cloud = w["cloud_cover"][i] or 0 + hours.append(Hour( + hour=h, feels_c=w["apparent_temperature"][i], rain_type=RainType.RAIN if (w["precipitation"][i] or 0) >= 0.1 else RainType.NONE, + rain_prob=int(w["precipitation_probability"][i] or 0), wind_ms=w["wind_speed_10m"][i], humidity=50, + sky=Sky.CLOUDY if cloud >= 80 else Sky.PARTLY if cloud >= 40 else Sky.CLEAR, + )) + result = outing(hours) if len(hours) == OUTING_HOURS[1] - OUTING_HOURS[0] else None + if result is not None: + out.append(result.score) + day += timedelta(days=1) + return out + + +def main() -> None: + end = date.today() - timedelta(days=2) + start = end - timedelta(days=DAYS) + regions = list(csv.DictReader(open(REGIONS, encoding="utf-8")))[::EVERY] + scores: list[int] = [] + for r in regions: + scores += region_scores(float(r["lat"]), float(r["lon"]), start, end) + LOG.info(f"[outing-table] {r['name']} 완료") + time.sleep(1) + doc = { + "about": f"나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 {MEAN}·표준편차 {SIGMA}. scripts/gen_outing_score_table.py 가 만든다", + "period": [start.isoformat(), end.isoformat()], "regions": len(regions), "samples": len(scores), + "table": straighten_top(table(scores)), # 100점은 원래 점수 100(완벽한 날)일 때만 + } + with open(OUT, "w", encoding="utf-8") as f: + json.dump(doc, f, ensure_ascii=False, indent=1) + print(len(regions), "regions", len(scores), "samples") + + +if __name__ == "__main__": + main() diff --git a/backend/scripts/gen_weather_score_table.py b/backend/scripts/gen_weather_score_table.py index 8c14bfd..61a611a 100644 --- a/backend/scripts/gen_weather_score_table.py +++ b/backend/scripts/gen_weather_score_table.py @@ -1,7 +1,7 @@ """지금 날씨 점수 바꾸기 표(services/calc/weather_score_table.json)를 다시 만든다. 지금 날씨 점수 공식(WEATHER_SCORE_DEF)으로 나온 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 바꾼 뒤, -평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다. 90점 이상은 구간마다 약 2.5%가 나온다. +평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다. 90점 이상은 구간마다 약 2.5%가 나온다. 맨 위는 straighten_top 으로 100점이 가장 좋은 원래 점수에서만 나오게 한다. 1년 치 날씨는 Open-Meteo 과거 예보(강수확률 포함)와 대기질(초미세먼지)로, region.csv 에서 8개마다 1곳(32곳)을 쓴다. WEATHER_SCORE_DEF 가 바뀌면 실행: cd backend && python scripts/gen_weather_score_table.py @@ -109,6 +109,20 @@ def table(scores: list[int]) -> list[int]: return out +ANCHOR_SCORE = 83 # 위쪽 끝을 직선으로 잇기 시작하는 표시 점수 + + +def straighten_top(t: list[int], top: int = 100) -> list[int]: + """표 맨 위가 100으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 되던 것을 막는다. + 표시 점수가 ANCHOR_SCORE 이하인 마지막 원래 점수에서 top(그 구간에서 나올 수 있는 가장 높은 원래 점수)의 100점까지 직선으로 잇는다. + 100점은 원래 점수가 top 이상일 때만 나온다. 그 아래 점수는 바뀌지 않는다.""" + anchor = max(i for i, v in enumerate(t[: top + 1]) if v <= ANCHOR_SCORE) + out = list(t) + for raw in range(anchor + 1, 101): + out[raw] = 100 if raw >= top else min(99, round(t[anchor] + (100 - t[anchor]) * (raw - anchor) / (top - anchor))) + return out + + def main() -> None: end = date.today() - timedelta(days=2) start = end - timedelta(days=DAYS) @@ -122,7 +136,8 @@ def main() -> None: doc = { "about": f"지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 {MEAN}·표준편차 {SIGMA}. scripts/gen_weather_score_table.py 가 만든다", "period": [start.isoformat(), end.isoformat()], "regions": len(regions), "samples": {s: len(v) for s, v in scores.items()}, - "slots": {s: table(v) for s, v in scores.items()}, + # 밤은 해 난 비율이 늘 0점이라 원래 점수가 100 - 그 비중까지만 나온다 + "slots": {s: straighten_top(table(v), 100 - WEATHER_SCORE_DEF.weight_sun if s == "night" else 100) for s, v in scores.items()}, } with open(OUT, "w", encoding="utf-8") as f: json.dump(doc, f, ensure_ascii=False, indent=1) diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index 284358a..f807a15 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -423,7 +423,8 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context # 나들이 날씨 점수: 낮 10~17시에 바깥에서 놀기 좋은 정도. 주말 전국 순위·당일치기 추천에 쓴다. OUTING_HOURS = (10, 18) _OUTING_WEIGHTS = {"temp": 35, "rain": 40, "sky": 15, "wind": 10} -_OUTING_RULES = {"temp": {"type": "range", "lo": 17, "hi": 24, "best": 21}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12}} +# 만점 조건을 엄격하게: 기온은 최적 21° ±0.5°, 바람은 초속 1m 이하(ok/2)여야 100점 — 같은 예보를 받는 여러 지역이 한꺼번에 100점이 되던 것을 줄인다 +_OUTING_RULES = {"temp": {"type": "range", "lo": 17, "hi": 24, "best": 21, "plateau": 0.5}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 2, "limit": 12}} _OUTING_SKY = {Sky.CLEAR: 100, Sky.PARTLY: 80, Sky.CLOUDY: 50} _OUTING_RAIN_PROB, _OUTING_RAIN_CAP = 60, 30 diff --git a/backend/services/calc/outing_score_table.json b/backend/services/calc/outing_score_table.json new file mode 100644 index 0000000..a6efa74 --- /dev/null +++ b/backend/services/calc/outing_score_table.json @@ -0,0 +1,112 @@ +{ + "about": "나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 60·표준편차 15. scripts/gen_outing_score_table.py 가 만든다", + "period": [ + "2025-10-22", + "2026-10-21" + ], + "regions": 32, + "samples": 11680, + "table": [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 8, + 13, + 17, + 22, + 25, + 28, + 30, + 32, + 34, + 36, + 37, + 37, + 38, + 38, + 39, + 39, + 40, + 41, + 41, + 42, + 42, + 47, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 51, + 51, + 51, + 51, + 52, + 54, + 57, + 61, + 62, + 62, + 62, + 63, + 63, + 63, + 63, + 63, + 64, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 65, + 65, + 66, + 66, + 66, + 66, + 67, + 67, + 67, + 68, + 68, + 68, + 69, + 69, + 70, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 78, + 79, + 81, + 83, + 85, + 86, + 88, + 90, + 92, + 93, + 95, + 97, + 98, + 100 + ] +} \ No newline at end of file diff --git a/backend/services/calc/weather_score_table.json b/backend/services/calc/weather_score_table.json index d9a9521..8fd2cc0 100644 --- a/backend/services/calc/weather_score_table.json +++ b/backend/services/calc/weather_score_table.json @@ -1,8 +1,8 @@ { "about": "지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 60·표준편차 15. scripts/gen_weather_score_table.py 가 만든다", "period": [ - "2025-10-21", - "2026-10-20" + "2025-10-22", + "2026-10-21" ], "regions": 32, "samples": { @@ -59,12 +59,12 @@ 44, 45, 46, - 46, + 47, 47, 48, 49, 50, - 51, + 52, 53, 54, 55, @@ -101,18 +101,18 @@ 80, 82, 83, - 85, + 84, + 86, + 87, 88, 90, + 91, + 92, 93, + 95, 96, + 97, 99, - 100, - 100, - 100, - 100, - 100, - 100, 100 ], "day": [ @@ -211,11 +211,11 @@ 79, 81, 83, - 85, - 87, - 91, + 86, + 89, + 92, + 94, 97, - 100, 100 ], "evening": [ @@ -303,7 +303,7 @@ 69, 70, 71, - 72, + 71, 72, 74, 75, @@ -311,14 +311,14 @@ 78, 79, 81, - 84, - 86, + 83, + 85, + 87, 89, 92, + 94, 96, - 100, - 100, - 100, + 98, 100 ], "night": [ @@ -365,7 +365,7 @@ 43, 44, 45, - 47, + 46, 48, 49, 50, @@ -373,7 +373,7 @@ 53, 55, 57, - 59, + 60, 62, 63, 65, @@ -399,14 +399,14 @@ 78, 80, 82, - 85, + 84, + 86, 88, + 90, 92, + 94, 96, - 100, - 100, - 100, - 100, + 98, 100, 100, 100, diff --git a/backend/services/weekend_rank.py b/backend/services/weekend_rank.py index 952ac48..87f25ed 100644 --- a/backend/services/weekend_rank.py +++ b/backend/services/weekend_rank.py @@ -22,7 +22,7 @@ from crud.region_crud import RegionCRUD from crud.sky_crud import SkyCRUD from crud.weather_crud import WeatherCRUD from crud.week_crud import WeekCRUD -from services.calc.index_calc import OUTING_HOURS, outing, outing_estimate +from services.calc.index_calc import OUTING_HOURS, Outing, outing, outing_estimate from services.index_service import day_forecast, windows_for from services.weather_service import WeatherService from services.week_service import _icon @@ -30,14 +30,29 @@ from services.week_service import _icon # 주말 전국 날씨 순위·당일치기 추천. 대표 지역(노을 순위 30곳)과 당일치기 후보 도시의 토·일 나들이 점수를 # 워커가 하루 두 번(06:40·18:40) 미리 계산해 Redis 에 둔다. 없으면 순위 API 가 그 자리에서 계산한다. _SEED = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "trip_city.csv") -_KEY = "weekend_rank:{:%Y%m%d}" +_KEY = "weekend_rank:v2:{:%Y%m%d}" # v2: 점수를 바꾸기 표로 보정한 값 (옛 점수 캐시를 쓰지 않게 키를 바꿨다) _TTL = 13 * 3600 _PARALLEL = 4 # 기상청 동시 호출 수 _WAIT_STEPS, _WAIT_SEC = 60, 0.5 _WINDOW = SimpleNamespace(windows=[{"from": OUTING_HOURS[0], "to": OUTING_HOURS[1]}]) +# 나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_outing_score_table.py 가 만든다 +OUTING_SCORE_TABLE: list[int] = json.loads( + open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "calc", "outing_score_table.json"), encoding="utf-8").read() +)["table"] + + +def calibrated_outing(score: int) -> int: + return OUTING_SCORE_TABLE[score] + + +def outing_day_score(result: Outing) -> int: + """순위·당일치기에 쓰는 하루 나들이 점수. 시간별 예보로 낸 점수와 중기예보 예상 점수 모두 같은 표를 거친다.""" + return calibrated_outing(result.score) + + # 당일치기: 내 지역에서 직선 이 거리 안의 후보 도시만 (1~2시간 거리), 너무 가까운 곳(같은 동네)은 뺀다. TRIP_MIN_KM, TRIP_MAX_KM = 20, 200 -TRIP_MIN_SCORE = 50 +TRIP_MIN_SCORE = calibrated_outing(50) # 원래 점수 50점과 같은 날씨 수준 @dataclass @@ -205,7 +220,7 @@ class WeekendRank: if result is None or row is None: continue out.append(DayScore( - region_code=region.code, day=d, score=result.score, reason=result.reason, icon=_icon(Sky(row.sky), RainType(row.rain_type)), + region_code=region.code, day=d, score=outing_day_score(result), reason=result.reason, icon=_icon(Sky(row.sky), RainType(row.rain_type)), temp_min_c=float(row.temp_min_c) if row.temp_min_c is not None else None, temp_max_c=float(row.temp_max_c) if row.temp_max_c is not None else None, rain_prob=row.rain_prob, estimated=result.estimated, diff --git a/backend/tests/test_outing_score_table.py b/backend/tests/test_outing_score_table.py new file mode 100644 index 0000000..0749b7d --- /dev/null +++ b/backend/tests/test_outing_score_table.py @@ -0,0 +1,58 @@ +from common.enums import RainType, Sky +from services.calc.index_calc import Hour, Outing, outing +from services.weekend_rank import OUTING_SCORE_TABLE, TRIP_MIN_SCORE, calibrated_outing, outing_day_score + + +def test_table_is_a_monotonic_0_to_100_lookup(): + assert len(OUTING_SCORE_TABLE) == 101 + assert all(0 <= v <= 100 for v in OUTING_SCORE_TABLE) + assert all(a <= b for a, b in zip(OUTING_SCORE_TABLE, OUTING_SCORE_TABLE[1:])) + assert OUTING_SCORE_TABLE[0] < OUTING_SCORE_TABLE[100] == 100 + + +def test_table_makes_top_scores_rare_and_centers_60(): + """원래 점수가 높을수록 표시 점수가 오르되, 90점 이상으로 가는 원래 점수는 위쪽 일부뿐.""" + assert any(55 <= v <= 65 for v in OUTING_SCORE_TABLE) + assert sum(v >= 90 for v in OUTING_SCORE_TABLE) <= 15 + # 맑고 알맞은 날(원래 100)과 조금 못 미치는 날(원래 97)이 모두 100점으로 몰리지 않는다 + assert calibrated_outing(95) < 100 + + +def test_calibrated_outing_reads_the_table(): + assert calibrated_outing(70) == OUTING_SCORE_TABLE[70] + assert calibrated_outing(0) == OUTING_SCORE_TABLE[0] + + +def test_day_score_uses_calibrated_value_for_hourly_and_estimated_results(): + for estimated in (False, True): + r = Outing(score=80, factors={}, notes={}, reason="비 0% · 체감 21° · 맑음", capped=False, estimated=estimated) + assert outing_day_score(r) == OUTING_SCORE_TABLE[80] + + +def test_trip_min_score_keeps_the_same_weather_quality(): + """당일치기 최소 기준은 원래 점수 50과 같은 날씨 수준을 표시 점수로 옮긴 값.""" + assert TRIP_MIN_SCORE == calibrated_outing(50) + # 표는 가까운 원래 점수끼리 같은 값이 될 수 있어, 눈에 띄게 낮은 날은 빠지고 높은 날은 들어가는지만 본다 + assert calibrated_outing(45) < TRIP_MIN_SCORE <= calibrated_outing(55) + + +def _day(feels: float = 21.0, wind: float = 0.5, prob: int = 0, sky: Sky = Sky.CLEAR) -> list[Hour]: + return [Hour(hour=h, feels_c=feels, rain_type=RainType.NONE, rain_prob=prob, wind_ms=wind, humidity=50, sky=sky) for h in range(10, 18)] + + +def test_outing_100_needs_exact_temperature_and_very_calm_wind(): + """맑고 비 없는 날도 체감 21° 근처(±0.5°)·바람 초속 1m 이하여야 100점. 그래야 같은 예보의 여러 지역이 한꺼번에 100점이 되지 않는다.""" + assert outing(_day()).score == 100 + assert outing(_day(feels=21.4)).factors["temp"] == 100 + assert outing(_day(feels=22.3)).factors["temp"] < 100 + assert outing(_day(wind=1.0)).factors["wind"] == 100 + assert outing(_day(wind=1.8)).factors["wind"] < 95 + assert outing(_day(wind=1.2)).score > outing(_day(wind=1.8)).score > outing(_day(wind=2.0)).score + + +def test_100_only_for_a_perfect_original_score_and_top_scores_stay_distinct(): + """맨 위가 100으로 잘려 원래 96·97·99가 모두 100점이 되던 것을 막는다: 100점은 원래 100뿐, 그 아래는 서로 다른 점수.""" + assert OUTING_SCORE_TABLE[100] == 100 + assert OUTING_SCORE_TABLE[99] < 100 + top = OUTING_SCORE_TABLE[90:] + assert all(a < b for a, b in zip(top, top[1:])) diff --git a/backend/tests/test_weather_score_table.py b/backend/tests/test_weather_score_table.py index 0d0a515..2cb8f84 100644 --- a/backend/tests/test_weather_score_table.py +++ b/backend/tests/test_weather_score_table.py @@ -2,6 +2,7 @@ from dataclasses import replace from datetime import date from services.calc.index_calc import Context, evaluate +from scripts.gen_weather_score_table import straighten_top from services.index_service import EARLY, WEATHER_SCORE_DEF, WEATHER_SCORE_TABLE, calibrated_weather, weather_slot_scores from tests.test_index_calc import _defn, _h @@ -55,3 +56,19 @@ def test_weather_slot_scores_keeps_results_with_calibrated_scores(): assert {k: r.score for k, r in shown.items()} == {"morning": WEATHER_SCORE_TABLE["morning"][40], "night": WEATHER_SCORE_TABLE["night"][60], EARLY: WEATHER_SCORE_TABLE["night"][60]} assert all(shown[k].factors == results[k].factors for k in results) assert results["morning"].score == 40 # 원래 결과는 바뀌지 않는다 + + +def test_straighten_top_makes_100_only_at_the_top_and_keeps_the_rest(): + clamped = list(range(0, 80)) + [85, 90, 95] + [100] * 18 # 맨 위가 100으로 잘린 표 (원래 80~82 → 85·90·95, 83 이상은 모두 100) + fixed = straighten_top(clamped, top=100) + assert fixed[:80] == clamped[:80] # 아래쪽은 그대로 + assert fixed[100] == 100 and max(fixed[:100]) < 100 + above = fixed[80:] + assert all(a < b for a, b in zip(above, above[1:])) or above[-1] == 100 # 위쪽은 구별되는 점수로 오른다 + assert straighten_top(clamped, top=90)[90] == 100 # 완벽한 점수가 100보다 낮은 구간(밤)은 거기서 100 + + +def test_weather_table_gives_100_only_at_the_best_reachable_original_score(): + assert WEATHER_SCORE_TABLE["day"][99] < 100 == WEATHER_SCORE_TABLE["day"][100] + night_top = 100 - WEATHER_SCORE_DEF.weight_sun # 밤은 해 난 비율이 늘 0점이라 원래 점수가 85까지만 나온다 + assert WEATHER_SCORE_TABLE["night"][night_top - 1] < 100 == WEATHER_SCORE_TABLE["night"][night_top] diff --git a/docs/점수_계산식.md b/docs/점수_계산식.md index 55a177a..3775d8a 100644 --- a/docs/점수_계산식.md +++ b/docs/점수_계산식.md @@ -73,7 +73,8 @@ 원래 점수는 40~60점대에 몰리고 좋은 계절 낮에 90점 이상이 자주 나와 점수 분포가 고르지 않았습니다. 그래서 원래 점수를 **구간(아침·낮·저녁·밤)마다 1년 치 분포에서의 순위**로 보고, 평균 60·표준편차 15인 정규분포의 같은 위치 점수로 바꿔 보여 줍니다. 순서는 그대로라 더 좋은 날씨가 더 낮은 점수를 받는 일은 없습니다. -- 표시 점수 평균은 구간마다 60. 90점 이상은 약 2.4% (구간마다 2~3%), 80점 이상은 약 9%, 40점 미만도 약 9%입니다. 100점은 약 0.35%. 계절 차이는 남습니다 (가을 평균 약 68, 겨울 약 54). +- 표시 점수 평균은 구간마다 60. 90점 이상은 약 1.5% (낮 약 2.7%, 그 밖 구간 약 1%), 80점 이상은 약 9%, 40점 미만도 약 9%입니다. 100점은 구간에서 나올 수 있는 가장 높은 원래 점수일 때만 나와 1년에 거의 안 나옵니다. 계절 차이는 남습니다 (가을 평균 약 68, 겨울 약 54). +- **위쪽 끝은 직선으로 이어 100점이 잘리지 않게 합니다.** 순위로만 바꾸면 위쪽 0.4%가 한꺼번에 100점으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 됩니다. 그래서 표시 점수 83 이하인 마지막 원래 점수에서 100점까지 직선으로 이어(`straighten_top`), 100점은 원래 점수 100(밤은 해 난 비율이 0점이라 85)에서만, 그 아래는 서로 다른 점수가 되게 했습니다. - 구간마다 따로 바꾸는 이유: 한 표로 하면 밤 점수가 최대 70점대 초반에 머뭅니다. 구간별 표는 "그 시간대치고 얼마나 좋은 날씨인가"를 뜻합니다. - 0~5시(전날 밤 구간)는 밤 표를 씁니다. - 바꾸기 표: `backend/services/calc/weather_score_table.json` (`calibrated_weather`). 만드는 법: `cd backend && python scripts/gen_weather_score_table.py`. 지금 날씨 점수의 요소·비중·기준값(`WEATHER_SCORE_DEF`)이 바뀌면 다시 만들어야 합니다. @@ -101,15 +102,18 @@ | 요소 | 비중 | 계산 | |---|---:|---| | 비 | 40% | 마른 날 규칙 (1 참고) | -| 체감온도 | 35% | 편한 범위 17~24°, 최적 21° | +| 체감온도 | 35% | 편한 범위 17~24°, 최적 21° (21°±0.5°만 100점, 만점 폭을 좁혀 같은 예보의 여러 지역이 다 100점이 되지 않게 함) | | 하늘 | 15% | 시간마다 맑음 100 · 구름많음 80 · 흐림 50의 평균 | -| 바람 | 10% | 4m/s 이하 100 → 12m/s 0 | +| 바람 | 10% | 초속 1m 이하 100 → 2m에서 85 → 12m에서 0 | - 1처럼 가장 낮은 요소로 깎습니다. - 비 소식이 있거나 비 확률 60% 이상이면 **최대 30점**. - 중기예보뿐인 날은 기온을 어림하고 바람은 70점입니다. +- 위 계산으로 나온 점수가 **원래 점수**이고, 화면에는 지금 날씨 점수(3절)와 같은 방식으로 **표시 점수로 바꿔** 보여 줍니다. 1년 치 원래 점수 분포의 순위를 평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾸는 것으로, 순서는 그대로입니다. 구간은 낮 하나라 표도 하나입니다. 원래 점수 50은 62점이고, 90점 이상은 원래 점수 94 이상에서만 나옵니다. 위쪽 끝은 3절처럼 직선으로 이어(`straighten_top`) **100점은 원래 점수 100(완벽한 날)일 때만** 나오고, 그 아래는 99→98, 97→95, 96→93, 95→92, 94→90처럼 서로 다른 점수가 됩니다. 맑고 알맞은 날이 100점으로 몰려 동점이 되던 것을 막습니다. +- 바꾸기 표: `backend/services/calc/outing_score_table.json` (`calibrated_outing`, `weekend_rank.py`). 만드는 법: `cd backend && python scripts/gen_outing_score_table.py`. 나들이 점수 규칙이 바뀌면 다시 만들어야 합니다. 표는 Open-Meteo 과거 예보(32개 지역, 364일)로 만들어 기상청 예보와 분포가 조금 다를 수 있습니다. 중기예보로 어림한 예상 점수에도 같은 표를 씁니다. +- 순위 캐시(`weekend_rank:v2:<토요일 날짜>`)는 표시 점수를 담습니다. 바꾸기 표를 적용하면서 키를 올려 옛 점수 캐시를 쓰지 않게 했습니다. - 전국 순위: 노을 순위 대표 30곳을 점수순으로 정렬합니다. -- 당일치기: 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 중 더 좋은 날 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳 → 이른 날 → 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보이지 않습니다. +- 당일치기: 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 중 더 좋은 날 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳 → 이른 날 → 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보이지 않습니다. 표시 점수 기준 최소 62점(원래 점수 50과 같은 날씨 수준, `TRIP_MIN_SCORE`) 이상이어야 추천합니다. ## 6. 노을 점수