feat: 지금 날씨 점수를 평균 60 정규분포로 (가장 낮은 요소로 깎기 제거, 구간별 바꾸기 표, 90점 이상 약 2.4%)

- 지금 날씨 점수는 '가장 낮은 요소로 깎기'를 하지 않는다 (밤엔 해 난 비율이 늘 0점이라 밤 점수가 62점을 못 넘었음). 각 점수는 그대로
- 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 보고 평균 60·표준편차 15 정규분포 점수로 바꿔 보여 준다
- 바꾸기 표는 scripts/gen_weather_score_table.py 가 Open-Meteo 과거 예보로 만든다 (weather_score_table.json)
This commit is contained in:
skkim committed 2026-10-22 13:33:50 +09:00
1 parent 61fefd200a
commit 3b5afba8a1
6 files changed
+655 -8

No files matched your search

+133
View File
@@ -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()