diff --git a/.gitignore b/.gitignore index 7392bc9..7f38461 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,5 @@ backend/openapi.json # 디자인 도구(impeccable) 캐시 .impeccable/ + +/zzz \ No newline at end of file diff --git a/backend/docs/openmeteo-data.md b/backend/docs/openmeteo-data.md index 6d8fecc..637e61d 100644 --- a/backend/docs/openmeteo-data.md +++ b/backend/docs/openmeteo-data.md @@ -118,10 +118,12 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100 | 축 | 값 (지수 계산 창 안에서) | 점수 규칙 (기본값, 지수별로 시드 JSON에서 바꿈) | 칼럼 | |---|---|---|---| -| `uv` 자외선 | `uv_index` **최대** | 2 이하 100점, 8 이상 0점, 사이는 선형 | `weight_uv`, `uv_score` | -| `sun` 햇빛 | 해 난 비율(`sunshine_s ÷ 10,800`)의 **평균** | 80% 이상 100점, 20% 이하 0점, 사이는 선형 | `weight_sun`, `sun_score` | -| `view` 가시거리 | `visibility_m` **최소**(km) | 20km 이상 100점, 5km 이하 0점, 사이는 선형 | `weight_view`, `view_score` | +| `uv` 자외선 | `uv_index` **최대** | 2 이하 100점, 8 이상 0점, 사이는 완만한 곡선 | `weight_uv`, `uv_score` | +| `sun` 햇빛 | 해 난 비율(`sunshine_s ÷ 10,800`)의 **평균** | 80% 이상 100점, 20% 이하 0점, 사이는 완만한 곡선 | `weight_sun`, `sun_score` | +| `view` 가시거리 | `visibility_m` **최소**(km) | 20km 이상 100점, 5km 이하 0점, 사이는 완만한 곡선 | `weight_view`, `view_score` | +- 완만한 곡선: 만점 구간 끝에서 0점 지점까지를 정규분포 곡선(σ = 그 거리) 모양으로 내려간다 (`index_calc._fall`). 가운데 지점이 50점이 아니라 70점이라 만점 근처는 천천히, 0점 근처는 빨리 내려간다. 모든 축(기온·비·바람·습도·미세먼지 포함)에 같은 곡선을 쓰고, 만점 기준·0점 지점·0점 조건은 그대로다. +- 기온·습도 편한 범위(`range`): 최적값(`best`, 없으면 범위 가운데) ±2°(습도 ±5%p)는 100점, 범위 끝은 85점, 사이는 완만한 곡선. 100점 구간은 최적값~범위 끝 거리의 1/3을 넘지 않는다 (`index_calc._range`). 100점은 완벽에 가까운 조건에만 준다는 10/2 회의 결정을 따른 것이다. - 값이 없으면(수집 전, 구간 없음) 미세먼지처럼 **70점(정보 없음)**. - 비중이 0인 지수에서는 점수에 영향이 없고, 상세 API(`/v1/index/{id}`)에도 나오지 않는다. 기존 6개 축도 같은 규칙으로, 비중이 0이면 나오지 않는다. - 중기예보로 내는 예상 점수(`estimate`)에서는 값이 없으므로 비중이 있으면 70점(정보 없음)이다. diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index 2938758..1ca37d8 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -1,7 +1,7 @@ from collections import Counter from dataclasses import dataclass, field from datetime import date -from math import cos, pi +from math import cos, exp, pi from statistics import mean from typing import Optional @@ -14,6 +14,10 @@ _WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일") _UNKNOWN = 70 _EDGE = 85 _WORST_PULL = 0.25 +_FALL_FLOOR = exp(-0.5) +# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p) +_TEMP_PLATEAU = 2 +_HUMIDITY_PLATEAU = 5 @dataclass(frozen=True) @@ -70,17 +74,33 @@ def _clamp(v: float) -> int: return round(max(0.0, min(100.0, v))) +def _fall(t: float) -> float: + """만점 구간 끝(t=0)에서 0점 지점(t=1)까지 1→0. 정규분포 곡선(σ = 그 거리) 모양이라 만점 근처는 천천히 내려간다.""" + if t <= 0: + return 1.0 + if t >= 1: + return 0.0 + return (exp(-t * t / 2) - _FALL_FLOOR) / (1 - _FALL_FLOOR) + + def _linear(v: float, zero: float, full: float) -> int: - return _clamp((v - zero) / (full - zero) * 100) + """full 쪽은 100, zero 에서 0. 사이는 _fall 곡선.""" + return _clamp(100 * _fall((v - full) / (zero - full))) -def _peak(v: float, lo: float, hi: float, best: Optional[float], per_out: float) -> int: - """최적값에서만 100. 편한 범위 끝은 _EDGE, 범위 밖은 한 단위마다 per_out 씩 깎는다.""" - best = (lo + hi) / 2 if best is None else best +def _range(v: float, lo: float, hi: float, best: Optional[float], plateau: float, per_out: float) -> int: + """편한 범위 안: 최적값 ±plateau 는 100, 범위 끝으로 갈수록 _EDGE 까지 _fall 곡선으로 내려간다. + 100점 구간은 최적값~범위 끝 거리의 1/3 을 넘지 않아 범위가 좁아도 끝에서 뚝 떨어지지 않는다. + 범위 밖: _EDGE 에서 예전 직선(한 단위마다 per_out)이 0이 되던 거리까지 _fall 곡선으로 0.""" if v < lo or v > hi: - return _clamp(_EDGE - per_out * min(abs(v - lo), abs(v - hi))) - side = (best - lo) if v < best else (hi - best) - return _clamp(100 - (100 - _EDGE) * (abs(v - best) / side if side else 0)) + return _clamp(_EDGE * _fall(min(abs(v - lo), abs(v - hi)) * per_out / _EDGE)) + best = (lo + hi) / 2 if best is None else best + side = abs((lo if v < best else hi) - best) + flat = min(plateau, side / 3) + off = abs(v - best) - flat + if off <= 0: + return 100 + return _clamp(_EDGE + (100 - _EDGE) * _fall(off / (side - flat))) def temp_score(rule: dict, feels: float) -> tuple[int, str]: @@ -88,7 +108,7 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]: shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°" if rule["type"] == "range": lo, hi = rule["lo"], rule["hi"] - return _peak(t, lo, hi, rule.get("best"), 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}" + return _range(t, lo, hi, rule.get("best"), _TEMP_PLATEAU, 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}" if rule["type"] == "away": lo, hi = rule["lo"], rule["hi"] dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi)) @@ -99,8 +119,8 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]: def rain_score(rule: dict, max_prob: int, raining: bool, until: str = "") -> tuple[int, str]: prob = f"{until} 비 확률 {max_prob}%" if until else f"비 확률 {max_prob}%" if rule["dir"] == "wet": - return (100 if raining else _clamp(max_prob)), (f"비 소식, {prob}" if raining else f"{prob}, 비 오면 올라가요") - return (0 if raining else _clamp(100 - max_prob)), (f"비 소식, {prob}" if raining else prob) + return (100 if raining else _linear(max_prob, 0, 100)), (f"비 소식, {prob}" if raining else f"{prob}, 비 오면 올라가요") + return (0 if raining else _linear(max_prob, 100, 0)), (f"비 소식, {prob}" if raining else prob) def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]: @@ -115,7 +135,7 @@ def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]: return 100, note if wind <= ok: return _clamp(100 - (100 - _EDGE) * (wind - ok / 2) / (ok / 2)), note - return _clamp(_EDGE * (rule["limit"] - wind) / (rule["limit"] - ok)), note + return _clamp(_EDGE * _fall((wind - ok) / (rule["limit"] - ok))), note if rule["type"] == "moderate": if 2 <= wind <= 5: return 100, note @@ -126,7 +146,7 @@ def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]: def humidity_score(rule: dict, humidity: float) -> tuple[int, str]: note = f"습도 {round(humidity)}%" if rule["type"] == "range": - return _peak(humidity, rule["lo"], rule["hi"], rule.get("best"), 2), note + return _range(humidity, rule["lo"], rule["hi"], rule.get("best"), _HUMIDITY_PLATEAU, 2), note if rule["type"] == "higher": return _linear(humidity, 40, 90), note if rule["type"] == "lower": diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py index c94590e..0800a43 100644 --- a/backend/tests/test_index_calc.py +++ b/backend/tests/test_index_calc.py @@ -39,15 +39,17 @@ def test_good_but_not_perfect_stays_below_100(): def test_one_bad_factor_pulls_total_down(): - assert evaluate(_defn(), [[_h(19, wind=1.0, prob=60)]], CTX).score < 80 + assert evaluate(_defn(), [[_h(19, wind=1.0, prob=75)]], CTX).score < 75 -def test_temp_peaks_at_best_and_loses_8_per_degree_outside(): - assert temp_score({"type": "range", "lo": 18, "hi": 24}, 21)[0] == 100 - assert temp_score({"type": "range", "lo": 18, "hi": 24}, 24)[0] == 85 +def test_temp_is_full_near_best_and_falls_gently_to_zero_outside(): + rule = {"type": "range", "lo": 14, "hi": 28} # 최적 21 ±2 = 19~23 은 100 + assert [temp_score(rule, t)[0] for t in (19, 21, 23)] == [100, 100, 100] + assert 85 < temp_score(rule, 25)[0] < 100 and temp_score(rule, 28)[0] == 85 # 범위 끝으로 갈수록 85까지 assert temp_score({"type": "range", "lo": 18, "hi": 24, "best": 22}, 22)[0] == 100 - assert temp_score({"type": "range", "lo": 18, "hi": 24}, 15)[0] == 61 - assert temp_score({"type": "lower", "zero": 25, "full": 5}, 15)[0] == 50 + assert temp_score({"type": "range", "lo": 18, "hi": 24}, 15)[0] == 77 # 범위 밖 3° + assert temp_score({"type": "range", "lo": 18, "hi": 24}, 18 - 85 / 8)[0] == 0 # 예전 직선이 0이 되던 거리에서 0 + assert temp_score({"type": "lower", "zero": 25, "full": 5}, 15)[0] == 70 assert temp_score({"type": "range", "lo": 10, "hi": 20, "offset": -6}, 21)[1].startswith("산 정상 기준 15°") @@ -59,7 +61,8 @@ def test_temp_away_rises_outside_comfort(): def test_rain_dry_and_wet(): - assert rain_score({"dir": "dry"}, 30, False)[0] == 70 + assert rain_score({"dir": "dry"}, 30, False)[0] == 89 + assert rain_score({"dir": "dry"}, 100, False)[0] == 0 assert rain_score({"dir": "dry"}, 30, True)[0] == 0 assert rain_score({"dir": "wet"}, 30, True)[0] == 100 @@ -111,10 +114,10 @@ def test_moon_full_and_new(): assert illumination(datetime(2000, 1, 21, 12, tzinfo=timezone.utc)) > 0.95 -def test_uv_sun_view_scores_are_linear_and_unknown_is_70(): - assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 50 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0 - assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 50 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100 - assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 50 and view_score({"zero": 5, "full": 20}, 3)[0] == 0 +def test_uv_sun_view_scores_fall_gently_and_unknown_is_70(): + assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 70 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0 + assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 70 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100 + assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 70 and view_score({"zero": 5, "full": 20}, 3)[0] == 0 assert (uv_score({"zero": 8, "full": 2}, None)[0], sun_score({"zero": 0.2, "full": 0.8}, None)[0], view_score({"zero": 5, "full": 20}, None)[0]) == (70, 70, 70) assert uv_score({"zero": 8, "full": 2}, 5)[1] == "자외선 5.0" assert view_score({"zero": 5, "full": 20}, 12.5)[1] == "가시거리 12.5km" and view_score({"zero": 5, "full": 20}, None)[1] == "가시거리 정보 없음" @@ -175,7 +178,7 @@ def test_estimate_is_flagged_and_unknown_factors_are_70(): def test_estimate_uses_rain_prob_of_the_window_half_day(): morning, evening = estimate(_defn(), _fc(am=60, pm=0), [[9, 10]], CTX), estimate(_defn(), _fc(am=60, pm=0), [[19, 20]], CTX) - assert morning.factors["rain"] == 40 and evening.factors["rain"] == 100 + assert morning.factors["rain"] == 58 and evening.factors["rain"] == 100 def test_estimate_applies_rain_zero_rule_only(): diff --git a/backend/tests/test_index_slots.py b/backend/tests/test_index_slots.py index d375039..13207af 100644 --- a/backend/tests/test_index_slots.py +++ b/backend/tests/test_index_slots.py @@ -61,7 +61,7 @@ def test_weekend_in_short_range_uses_hourly_score(): def test_weekend_beyond_short_range_uses_mid_forecast_estimate(): r = day_result(DEFN, SAT, REGION, {}, FC, CTX, short=False) - assert r.estimated is True and r.factors["wind"] == 70 and r.factors["rain"] == 80 + assert r.estimated is True and r.factors["wind"] == 70 and r.factors["rain"] == 95 def test_partial_hourly_falls_back_to_estimate():