diff --git a/backend/scripts/gen_weather_score_table.py b/backend/scripts/gen_weather_score_table.py new file mode 100644 index 0000000..8c14bfd --- /dev/null +++ b/backend/scripts/gen_weather_score_table.py @@ -0,0 +1,133 @@ +"""지금 날씨 점수 바꾸기 표(services/calc/weather_score_table.json)를 다시 만든다. + +지금 날씨 점수 공식(WEATHER_SCORE_DEF)으로 나온 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 바꾼 뒤, +평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다. 90점 이상은 구간마다 약 2.5%가 나온다. +1년 치 날씨는 Open-Meteo 과거 예보(강수확률 포함)와 대기질(초미세먼지)로, region.csv 에서 8개마다 1곳(32곳)을 쓴다. + +WEATHER_SCORE_DEF 가 바뀌면 실행: cd backend && python scripts/gen_weather_score_table.py +""" + +import csv +import json +import os +import sys +import time +import urllib.parse +import urllib.request +from datetime import date, datetime, timedelta +from statistics import NormalDist + +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 services.calc.day_slot import SLOTS, slot_hours # noqa: E402 +from services.calc.index_calc import Context, Hour, evaluate # noqa: E402 +from services.calc.sun import sun_times # noqa: E402 +from services.index_service import WEATHER_SCORE_DEF # 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", "weather_score_table.json") + +MEAN, SIGMA = 60, 15 +DAYS = 364 +EVERY = 8 +_WEATHER = "https://historical-forecast-api.open-meteo.com/v1/forecast" +_AIR = "https://air-quality-api.open-meteo.com/v1/air-quality" +_HOURLY = "apparent_temperature,precipitation,snowfall,precipitation_probability,wind_speed_10m,relative_humidity_2m,sunshine_duration,cloud_cover" + + +def fetch(url: str, params: dict) -> dict: + """잠깐 막히면 쉬었다가 다시 부른다. 네 번 모두 안 되면 멈춘다.""" + query = urllib.parse.urlencode(params) + for attempt in range(4): + try: + with urllib.request.urlopen(f"{url}?{query}", timeout=60) as r: + return json.load(r) + except OSError as e: + LOG.error(f"[weather-table] {url} 실패 {attempt + 1}회: {e}") + time.sleep(10 * (attempt + 1)) + raise RuntimeError(f"{url} 를 받지 못함") + + +def region_scores(lat: float, lon: float, start: date, end: date) -> dict[str, list[int]]: + """한 지점의 날마다 구간별 원래 점수. 앱과 같은 입력으로 맞춘다 (일조는 그 시각을 덮는 3시간 합 ÷ 3시간, 미세먼지는 구간 평균).""" + base = dict(latitude=lat, longitude=lon, start_date=start.isoformat(), end_date=(end + timedelta(days=1)).isoformat(), timezone="Asia/Seoul") + w = fetch(_WEATHER, base | dict(hourly=_HOURLY, wind_speed_unit="ms"))["hourly"] + air = fetch(_AIR, base | dict(hourly="pm2_5"))["hourly"] + pm = dict(zip(air["time"], air["pm2_5"])) + at_index = {t: i for i, t in enumerate(w["time"])} + + def key(at: datetime) -> str: + return at.strftime("%Y-%m-%dT%H:%M") + + def hour_at(at: datetime, h: int) -> tuple[Hour | None, float | None]: + i = at_index.get(key(at)) + if i is None or w["apparent_temperature"][i] is None: + return None, None + end_at = datetime.combine(at.date(), datetime.min.time()) + timedelta(hours=(at.hour + 3) // 3 * 3) + sun = [w["sunshine_duration"][j] for j in (at_index.get(key(end_at - timedelta(hours=k))) for k in (3, 2, 1)) if j is not None and w["sunshine_duration"][j] is not None] + wet = (w["precipitation"][i] or 0) >= 0.1 + cloud = w["cloud_cover"][i] or 0 + return Hour( + hour=h, feels_c=w["apparent_temperature"][i], + rain_type=(RainType.SNOW if (w["snowfall"][i] or 0) > 0 else RainType.RAIN) if wet else RainType.NONE, + rain_prob=int(w["precipitation_probability"][i] or 0), wind_ms=w["wind_speed_10m"][i], humidity=int(w["relative_humidity_2m"][i]), + sky=Sky.CLOUDY if cloud >= 80 else Sky.PARTLY if cloud >= 40 else Sky.CLEAR, + sunshine_ratio=min(sum(sun) / 10800, 1.0) if len(sun) == 3 else None, + ), pm.get(key(at)) + + out: dict[str, list[int]] = {s: [] for s in SLOTS} + day = start + while day <= end: + midnight = datetime.combine(day, datetime.min.time()) + for slot, hours in slot_hours(day, sun_times(day, lat, lon).sunset_at).items(): + got = [hour_at(midnight + timedelta(hours=h), h) for h in sorted(hours)] + if any(x is None for x, _ in got): + continue + pms = [p for _, p in got if p is not None] + ctx = Context(day=day, is_holiday=False, pm25=round(sum(pms) / len(pms)) if pms else None, air_label=None, moon=0, sunset_score=None, + wind_warning=False, lookahead_rain_prob=0) + r = evaluate(WEATHER_SCORE_DEF, [[x for x, _ in got]], ctx) + if r is not None: + out[slot].append(r.score) + day += timedelta(days=1) + return out + + +def table(scores: list[int]) -> list[int]: + """원래 점수 0~100 각각을 '분포에서의 가운데 순위'로 정규분포 점수에 맞춘다. 순서는 그대로 (줄어들지 않게).""" + n = len(scores) + out = [] + for v in range(101): + below = sum(1 for s in scores if s < v) + same = sum(1 for s in scores if s == v) + out.append(max(0, min(100, round(MEAN + SIGMA * NormalDist().inv_cdf((below + same / 2 + 0.5) / (n + 1)))))) + for i in range(1, 101): + out[i] = max(out[i], out[i - 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: dict[str, list[int]] = {s: [] for s in SLOTS} + for r in regions: + for slot, got in region_scores(float(r["lat"]), float(r["lon"]), start, end).items(): + scores[slot] += got + LOG.info(f"[weather-table] {r['name']} 완료") + time.sleep(1) + 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()}, + } + with open(OUT, "w", encoding="utf-8") as f: + json.dump(doc, f, ensure_ascii=False, indent=1) + print(len(regions), "regions", doc["samples"]) + + +if __name__ == "__main__": + main() diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index ab01444..87ec931 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -296,9 +296,13 @@ def _summary(hours: list[Hour]) -> str: return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}" -def _weighted(factors: dict[str, int], weights: dict[str, int]) -> int: +def _weighted(factors: dict[str, int], weights: dict[str, int], worst_pull: bool = True) -> int: + """비중대로 섞고, worst_pull 이면 가장 낮은 요소로 최대 25% 깎는다 (지금 날씨 점수는 깎지 않는다).""" + mixed = sum(factors[a] * weights[a] for a in AXES) / 100 + if not worst_pull: + return round(mixed) worst = min((factors[a] for a in AXES if weights[a]), default=100) - return round(sum(factors[a] * weights[a] for a in AXES) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100)) + return round(mixed * (1 - _WORST_PULL + _WORST_PULL * worst / 100)) def _until(definition) -> str: @@ -338,7 +342,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re } factors = {a: v for a, (v, _) in scored.items()} notes = {a: n for a, (_, n) in scored.items()} - score = _weighted(factors, weights) + score = _weighted(factors, weights, getattr(definition, "worst_pull", True)) agg = { "rain_prob": max_prob, "wind_ms": max(winds) if winds else None, "pm25": ctx.pm25, "feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)), @@ -395,7 +399,7 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context } factors = {a: v for a, (v, _) in scored.items()} notes = {a: n for a, (_, n) in scored.items()} - score = _weighted(factors, weights) + score = _weighted(factors, weights, getattr(definition, "worst_pull", True)) # 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다 # 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다 known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"} diff --git a/backend/services/calc/weather_score_table.json b/backend/services/calc/weather_score_table.json new file mode 100644 index 0000000..d9a9521 --- /dev/null +++ b/backend/services/calc/weather_score_table.json @@ -0,0 +1,428 @@ +{ + "about": "지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 60·표준편차 15. scripts/gen_weather_score_table.py 가 만든다", + "period": [ + "2025-10-21", + "2026-10-20" + ], + "regions": 32, + "samples": { + "morning": 11680, + "day": 11680, + "evening": 11680, + "night": 11680 + }, + "slots": { + "morning": [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 4, + 5, + 5, + 9, + 11, + 14, + 16, + 17, + 18, + 20, + 21, + 23, + 25, + 26, + 28, + 29, + 31, + 31, + 32, + 33, + 33, + 34, + 34, + 35, + 35, + 35, + 36, + 37, + 37, + 38, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 46, + 47, + 48, + 49, + 50, + 51, + 53, + 54, + 55, + 57, + 59, + 61, + 62, + 63, + 64, + 64, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 69, + 70, + 71, + 71, + 72, + 73, + 73, + 74, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 82, + 83, + 85, + 88, + 90, + 93, + 96, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 100 + ], + "day": [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 4, + 6, + 9, + 12, + 15, + 19, + 22, + 24, + 26, + 27, + 28, + 29, + 30, + 31, + 31, + 32, + 32, + 33, + 33, + 34, + 35, + 36, + 37, + 37, + 38, + 39, + 40, + 41, + 41, + 42, + 42, + 43, + 43, + 44, + 44, + 45, + 45, + 46, + 46, + 47, + 47, + 47, + 48, + 48, + 48, + 49, + 49, + 50, + 50, + 51, + 52, + 54, + 56, + 59, + 61, + 62, + 63, + 63, + 64, + 64, + 64, + 65, + 65, + 66, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 76, + 77, + 79, + 81, + 83, + 85, + 87, + 91, + 97, + 100, + 100 + ], + "evening": [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 7, + 11, + 14, + 17, + 20, + 23, + 25, + 27, + 28, + 29, + 30, + 31, + 32, + 32, + 33, + 34, + 34, + 35, + 36, + 37, + 38, + 38, + 39, + 39, + 40, + 40, + 41, + 41, + 42, + 42, + 43, + 43, + 44, + 45, + 45, + 46, + 46, + 47, + 47, + 48, + 48, + 48, + 49, + 50, + 50, + 51, + 52, + 53, + 55, + 56, + 59, + 60, + 62, + 63, + 63, + 64, + 64, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 69, + 69, + 70, + 71, + 72, + 72, + 74, + 75, + 76, + 78, + 79, + 81, + 84, + 86, + 89, + 92, + 96, + 100, + 100, + 100, + 100 + ], + "night": [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 4, + 7, + 10, + 11, + 13, + 15, + 17, + 20, + 22, + 26, + 28, + 30, + 32, + 33, + 34, + 34, + 35, + 35, + 35, + 36, + 36, + 37, + 38, + 38, + 39, + 40, + 41, + 41, + 42, + 43, + 44, + 45, + 47, + 48, + 49, + 50, + 52, + 53, + 55, + 57, + 59, + 62, + 63, + 65, + 65, + 66, + 66, + 66, + 67, + 68, + 68, + 69, + 69, + 70, + 70, + 71, + 71, + 72, + 73, + 74, + 74, + 75, + 77, + 78, + 80, + 82, + 85, + 88, + 92, + 96, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100 + ] + } +} \ No newline at end of file diff --git a/backend/services/index_service.py b/backend/services/index_service.py index a615e8c..c9b427c 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -1,6 +1,8 @@ import asyncio +import json from dataclasses import dataclass, field, replace from datetime import date, datetime, time, timedelta +from pathlib import Path from types import SimpleNamespace from typing import Optional @@ -39,8 +41,13 @@ WEATHER_SCORE_DEF = SimpleNamespace( "air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100}, }, zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}], + # 가장 낮은 요소로 깎지 않는다: 밤엔 해 난 비율이 늘 0점이라 깎기가 밤 점수를 눌렀다 + worst_pull=False, ) +# 지금 날씨 점수 바꾸기 표: 구간마다 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_weather_score_table.py 가 만든다 +WEATHER_SCORE_TABLE: dict[str, list[int]] = json.loads((Path(__file__).parent / "calc" / "weather_score_table.json").read_text(encoding="utf-8"))["slots"] + SEASONS = ("겨울", "봄", "여름", "가을") @@ -193,6 +200,16 @@ def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]: return {k: shown[k] for k in SLOTS if k in shown} +def calibrated_weather(slot: str, score: int) -> int: + """지금 날씨 점수의 원래 점수를 그 구간 표로 바꾼다. 0~5시(전날 밤 구간)는 밤 표.""" + return WEATHER_SCORE_TABLE[shown_slot(slot)][score] + + +def weather_slot_scores(results: dict[str, Result]) -> dict[str, int]: + """구간별 날씨 점수 결과를 표시 점수로.""" + return {k: calibrated_weather(k, r.score) for k, r in results.items()} + + def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]: """그날 비·눈 오는 시각(0~23).""" start = kst_midnight(day) @@ -396,7 +413,7 @@ class IndexService: ) today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx) sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at - weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()} + weather_parts = weather_slot_scores(slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now)) issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []]) inputs_at = max(issued, air.measured_at) if air else issued diff --git a/backend/tests/test_weather_score_table.py b/backend/tests/test_weather_score_table.py new file mode 100644 index 0000000..dd8cb02 --- /dev/null +++ b/backend/tests/test_weather_score_table.py @@ -0,0 +1,53 @@ +from datetime import date +from types import SimpleNamespace + +from services.calc.index_calc import Context, evaluate +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 + +PERFECT = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0) +SLOTS = ("morning", "day", "evening", "night") + + +def test_weather_score_has_no_worst_factor_pull(): + """해 난 비율만 0점(밤)이어도 나머지가 만점이면 비중대로 85점. 가장 낮은 요소로 25% 더 깎지 않는다.""" + hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=0.0) for h in range(19, 23)] + r = evaluate(WEATHER_SCORE_DEF, [hours], PERFECT) + assert r.factors["sun"] == 0 + assert r.score == 85 + + +def test_gak_scores_keep_worst_factor_pull(): + """각 점수는 그대로: 한 요소가 0점이면 섞은 점수에서 25% 깎인다.""" + defn = _defn(zero_rules=[]) + r = evaluate(defn, [[_h(19, wind=12.0)]], PERFECT) + assert r.factors["wind"] == 0 + plain = round(sum(r.factors[a] * getattr(defn, f"weight_{a}", 0) for a in r.factors) / 100) + assert r.score == round(plain * 0.75) + + +def test_table_covers_every_slot_and_never_goes_down(): + for slot in SLOTS: + table = WEATHER_SCORE_TABLE[slot] + assert len(table) == 101 + assert all(0 <= v <= 100 for v in table) + assert all(a <= b for a, b in zip(table, table[1:])) + assert table[100] == 100 + + +def test_table_makes_90_rare_and_centers_60(): + """구간마다 원래 점수 중앙값 근처가 60점 근처로, 90점 이상은 원래 점수 상위 몇 칸뿐.""" + for slot in SLOTS: + table = WEATHER_SCORE_TABLE[slot] + assert any(55 <= v <= 65 for v in table) + assert sum(v >= 90 for v in table) < sum(v < 90 for v in table) + + +def test_calibrated_uses_slot_table_and_last_night_for_early(): + assert calibrated_weather("day", 70) == WEATHER_SCORE_TABLE["day"][70] + assert calibrated_weather(EARLY, 70) == WEATHER_SCORE_TABLE["night"][70] + + +def test_weather_slot_scores_shows_calibrated_values(): + results = {k: SimpleNamespace(score=s) for k, s in {"morning": 40, "night": 60, EARLY: 60}.items()} + assert weather_slot_scores(results) == {"morning": WEATHER_SCORE_TABLE["morning"][40], "night": WEATHER_SCORE_TABLE["night"][60], EARLY: WEATHER_SCORE_TABLE["night"][60]} diff --git a/docs/점수_계산식.md b/docs/점수_계산식.md index 341a8ac..0c54fb9 100644 --- a/docs/점수_계산식.md +++ b/docs/점수_계산식.md @@ -56,7 +56,7 @@ ## 3. 지금 날씨 점수 -**지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 1의 방식으로 계산합니다. 밤에는 밤 날씨 기준이라 낮보다 낮게 나오기 쉽습니다. +**지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 1의 방식으로 섞되 **'가장 낮은 요소로 깎기'(1의 3번)는 하지 않고**, 섞은 점수를 아래 '표시 점수로 바꾸기'로 바꿔 보여 줍니다. 밤엔 해 난 비율이 늘 0점이라 깎기를 하면 밤 점수가 62점을 못 넘었습니다 (`WEATHER_SCORE_DEF.worst_pull = False`). | 요소 | 비중 | 100점 조건 | |---|---:|---| @@ -67,9 +67,21 @@ | 초미세먼지 | 10% | 10㎍/㎥ 이하 (75에서 0점) | | 해 난 비율 (Open-Meteo) | 15% | 90% 이상 (20%에서 0점), 정보 없으면 70점 | -여섯 가지가 동시에 맞아야 100점입니다. 기준값은 눈대중으로 잡은 것이며 (낮 기준 최적값을 밤에도 똑같이 씀), 실제로 1년에 며칠 나오는지는 확인하지 않았습니다. +위 표의 점수가 **원래 점수**입니다. 밤엔 해 난 비율이 0점이라 나머지가 모두 만점이어도 85점이 최대입니다. + +### 표시 점수로 바꾸기 + +원래 점수는 40~60점대에 몰리고 좋은 계절 낮에 90점 이상이 자주 나와 점수 분포가 고르지 않았습니다. 그래서 원래 점수를 **구간(아침·낮·저녁·밤)마다 1년 치 분포에서의 순위**로 보고, 평균 60·표준편차 15인 정규분포의 같은 위치 점수로 바꿔 보여 줍니다. 순서는 그대로라 더 좋은 날씨가 더 낮은 점수를 받는 일은 없습니다. + +- 표시 점수 평균은 구간마다 60. 90점 이상은 약 2.4% (구간마다 2~3%), 80점 이상은 약 9%, 40점 미만도 약 9%입니다. 100점은 약 0.35%. 계절 차이는 남습니다 (가을 평균 약 68, 겨울 약 54). +- 구간마다 따로 바꾸는 이유: 한 표로 하면 밤 점수가 최대 70점대 초반에 머뭅니다. 구간별 표는 "그 시간대치고 얼마나 좋은 날씨인가"를 뜻합니다. +- 0~5시(전날 밤 구간)는 밤 표를 씁니다. +- 바꾸기 표: `backend/services/calc/weather_score_table.json` (`calibrated_weather`). 만드는 법: `cd backend && python scripts/gen_weather_score_table.py`. 지금 날씨 점수의 요소·비중·기준값(`WEATHER_SCORE_DEF`)이 바뀌면 다시 만들어야 합니다. +- 표 재료: Open-Meteo 과거 예보로 32개 지역(region.csv 8곳마다 1곳)의 최근 364일을 계산. 실제 앱은 기상청 단기예보를 쓰므로 분포가 조금 다를 수 있어, 기상청 자료가 쌓이면 다시 만드는 게 좋습니다. +- **각 점수에는 적용하지 않습니다.** + +예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 원래 점수는 95점 미만(깎기를 뺀 값). -예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 95점 미만. ## 4. 각 점수