feat: 지금 날씨를 초단기실황 관측값으로, 각 점수에서 시간대 알맞음 제거·우산각 계산식 변경

- 초단기실황(getUltraSrtNcst)을 받아 지금 정시 한 시각의 비·기온·습도·바람을 예보 대신 관측값으로 덮어씀 (체감·불쾌지수는 다시 계산). 지역별 1시간 캐시, 실패하면 초단기예보·단기예보로 되돌아감, 새 시각 실황이 나오면 각 점수를 다시 계산. 가이드대로 ±900 이상은 결측 처리. 테스트가 실제 기상청을 부르지 않게 실황 호출을 기본으로 막음
- 시간대 알맞음 요소를 31개 각에서 빼고 비중을 5% 단위로 나눔. 요소가 3개 미만이 된 뜨아각·파전각·감성노래각·감사각·선크림각에 요소를 더함. 러닝각의 활동 시간대 밖 점수 상한도 없앰. 요소가 하나뿐인 각은 가장 낮은 요소로 깎지 않음
- 우산각은 비 한 가지: 남은 하루(지금~자정) 비 확률 평균이 점수, 지금 비가 오면 70점에서 시작해 평균 × 30점을 더함. 내일·토·일 칸은 그날 6~24시 평균 × 100. 우산분실각도 비 한 가지
- 각 계산 기준 문서는 생성기를 새 규칙에 맞게 고쳐 다시 생성, 점수 계산식·서비스 동작 안내 문서 갱신
This commit is contained in:
skkim committed 2026-11-23 14:51:04 +09:00
1 parent 8ea9f8f04b
commit 5ab2381f79
19 files changed
+737 -243

No files matched your search

+123 -21
View File
@@ -327,9 +327,11 @@ def test_running_clear_cool_morning_and_evening_stay_good(hour, feels):
@pytest.mark.parametrize("hour, feels", [(12, 12), (12, 14), (12, 25), (22, 12), (26, 12)])
def test_running_outside_activity_hours_stays_low(hour, feels):
result = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], replace(CTX, time_matches=False))
assert result.factors["time"] == 0 and result.score <= 50
def test_running_can_be_done_at_any_hour(hour, feels):
"""러닝각은 활동 시간대 밖이라고 점수 상한을 두지 않는다."""
outside = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], replace(CTX, time_matches=False))
inside = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], replace(CTX, time_matches=True))
assert outside.score == inside.score
@pytest.mark.parametrize("wind, ceiling", [(6, 30), (8, 0)])
@@ -351,29 +353,73 @@ def test_running_wind_warning_is_zero():
@pytest.mark.parametrize("hour", [dict(prob=60, feels=3), dict(prob=60, feels=35), dict(prob=60, wind=8)])
@pytest.mark.parametrize("time_matches", [True, False])
def test_running_stricter_limits_win_when_conditions_overlap(hour, time_matches):
result = evaluate(_SEED["running"], [[_h(6, **(dict(feels=12) | hour))]], replace(CTX, time_matches=time_matches))
def test_running_stricter_limits_win_when_conditions_overlap(hour):
result = evaluate(_SEED["running"], [[_h(6, **(dict(feels=12) | hour))]], CTX)
assert result.score <= (30 if hour.get("feels") == 3 else 0)
@pytest.mark.parametrize("time_matches", [True, False])
@pytest.mark.parametrize("hour", [dict(feels=12), dict(feels=20, hum=80), dict(feels=3, prob=60), dict(feels=12, wind=8, rain=RainType.RAIN)])
def test_other_definitions_ignore_unused_time_match_condition(time_matches, hour):
from unittest.mock import patch
from services.calc import index_calc
ctx = replace(CTX, time_matches=time_matches, pm25=30)
def test_activity_hours_never_change_any_gak_score(hour):
"""어느 각도 활동 시간대에 해당하는지로 점수나 0점 조건이 달라지지 않는다."""
windows = [[_h(7, **hour)]]
zero = index_calc._zero
for code, defn in _SEED.items():
if code == "running":
continue
assert all(r["field"] != "time_matches" for r in defn.zero_rules)
actual = evaluate(defn, windows, ctx)
with patch.object(index_calc, "_zero", side_effect=lambda rules, agg: zero(rules, {k: v for k, v in agg.items() if k != "time_matches"})):
assert actual == evaluate(defn, windows, ctx), code
assert all(r["field"] != "time_matches" for r in defn.zero_rules), code
on, off = (evaluate(defn, windows, replace(CTX, time_matches=m, pm25=30)) for m in (True, False))
assert (on.score, on.zero_reason) == (off.score, off.zero_reason), code
_AXES = ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")
def _weights(code):
return {a: getattr(_SEED[code], f"weight_{a}") for a in _AXES if getattr(_SEED[code], f"weight_{a}")}
def test_no_gak_scores_activity_hours_as_a_factor():
assert [c for c, d in _SEED.items() if d.factor_rules["time"]["type"] == "fixed" and d.weight_time] == []
def test_gak_weights_are_5_percent_steps_that_sum_to_100():
for code in _SEED:
weights = _weights(code)
assert sum(weights.values()) == 100 and all(v % 5 == 0 for v in weights.values()), code
def test_every_gak_has_three_factors_except_the_two_umbrella_gak():
assert {c for c in _SEED if len(_weights(c)) < 3} == {"umbrella", "umbrella_lost"}
@pytest.mark.parametrize("code, expected", [
("umbrella", {"rain": 100}),
("umbrella_lost", {"rain": 100}),
("iced_hot", {"temp": 80, "rain": 10, "wind": 10}),
("pajeon", {"temp": 20, "rain": 65, "humidity": 15}),
("mood_song", {"temp": 30, "rain": 55, "humidity": 15}),
("thanks", {"temp": 50, "rain": 30, "wind": 20}),
("sunscreen", {"uv": 70, "sun": 15, "temp": 15}),
("walk", {"temp": 35, "rain": 25, "wind": 15, "humidity": 10, "air": 15}),
("running", {"temp": 40, "rain": 20, "wind": 10, "humidity": 15, "air": 15}),
("sentimental", {"temp": 40, "rain": 35, "wind": 15, "humidity": 10}),
("selfie", {"rain": 20, "wind": 15, "humidity": 35, "sun": 30}),
])
def test_gak_weights_after_removing_activity_hours(code, expected):
assert _weights(code) == expected
def test_umbrella_gak_use_the_rain_rules_the_owner_asked_for():
assert _SEED["umbrella"].factor_rules["rain"] == {"dir": "wet", "span": "rest_of_day", "now_base": 70}
assert _SEED["umbrella_lost"].factor_rules["rain"]["dir"] == "dry"
@pytest.mark.parametrize("code, calm, lively", [
("iced_hot", dict(feels=8.0, prob=0), dict(feels=8.0, prob=0, wind=7.0)),
("thanks", dict(feels=0.0, wind=0.5), dict(feels=0.0, wind=7.0)),
("pajeon", dict(feels=15.0, prob=90, rain=RainType.RAIN, hum=40), dict(feels=15.0, prob=90, rain=RainType.RAIN, hum=90)),
("mood_song", dict(feels=15.0, prob=90, rain=RainType.RAIN, hum=40), dict(feels=15.0, prob=90, rain=RainType.RAIN, hum=90)),
("sunscreen", dict(feels=26.0, uv=6.0, sunshine_ratio=0.1), dict(feels=26.0, uv=6.0, sunshine_ratio=0.9)),
])
def test_added_factor_raises_the_score_in_the_direction_the_gak_means(code, calm, lively):
assert _seed_score(code, **lively) > _seed_score(code, **calm)
@pytest.mark.parametrize("code, good, bad", [
@@ -416,7 +462,7 @@ def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad):
("mosquito", dict(feels=27.0, hum=85, wind=0.5), dict(feels=15.0, hum=40, wind=6.0)),
("tennis", dict(feels=18.0, wind=1.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
("hyodo", dict(feels=20.0, wind=1.5), dict(feels=20.0, prob=80, rain=RainType.RAIN)),
("thanks", dict(feels=0.0, prob=90, rain=RainType.RAIN), dict(feels=20.0)),
("thanks", dict(feels=0.0, prob=90, rain=RainType.RAIN, wind=6.0), dict(feels=20.0)),
("gift", dict(feels=17.0, wind=1.5), dict(feels=17.0, prob=80, rain=RainType.RAIN)),
("party", dict(feels=3.0, prob=90, rain=RainType.RAIN), dict(day=_WED, feels=20.0)),
("game", dict(feels=3.0, prob=90, rain=RainType.RAIN, pm25=70), dict(day=_WED, feels=20.0)),
@@ -473,6 +519,62 @@ def test_umbrella_lost_needs_rain_that_stopped():
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
def _umbrella_defn():
"""우산각 방식: 요소는 비 하나. 지금 비가 오면 70점에서 시작해 남은 시각의 비 확률 평균으로 30점까지, 아니면 평균 × 100."""
return _defn(
weight_temp=0, weight_rain=100, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0,
factor_rules=_defn().factor_rules | {"rain": {"dir": "wet", "span": "rest_of_day", "now_base": 70}}, zero_rules=[],
)
def _umbrella(probs, raining_now, at_now=True):
"""11시부터 시각마다 비 확률 probs. raining_now 면 첫 시각(지금)에 비가 오는 중."""
hours = [_h(11 + i, prob=p, rain=RainType.RAIN if i == 0 and raining_now else RainType.NONE) for i, p in enumerate(probs)]
return evaluate(_umbrella_defn(), [hours], replace(CTX, at_now=at_now))
def test_umbrella_is_100_only_when_raining_now_and_every_remaining_hour_is_certain():
assert _umbrella([100] * 13, raining_now=True).score == 100
assert _umbrella([100] * 12 + [0], raining_now=True).score == 98
@pytest.mark.parametrize("probs, score", [([100] + [0] * 12, 72), ([100] * 4 + [0] * 9, 79)])
def test_umbrella_raining_now_starts_at_70_and_adds_up_to_30_by_remaining_hours(probs, score):
assert _umbrella(probs, raining_now=True).score == score
def test_umbrella_raining_now_counts_current_hour_as_certain_even_if_its_forecast_is_low():
assert _umbrella([40] + [0] * 12, raining_now=True).score == 72
@pytest.mark.parametrize("probs, score", [([0] * 7 + [100] * 6, 46), ([30] * 13, 30), ([100] * 13, 100), ([0] * 13, 0)])
def test_umbrella_not_raining_now_is_the_time_weighted_probability_out_of_100(probs, score):
assert _umbrella(probs, raining_now=False).score == score
def test_umbrella_has_no_raining_now_bonus_unless_the_evaluation_starts_now():
"""다른 구간·내일 칸은 '지금'이 없다. 첫 시각에 비가 와도 평균 × 100 만."""
assert _umbrella([100] + [0] * 12, raining_now=True, at_now=False).score == 8
def test_umbrella_note_says_it_counts_the_rest_of_the_day():
assert "남은 시간" in _umbrella([100] * 13, raining_now=True).notes["rain"]
assert "지금 비" in _umbrella([100] * 13, raining_now=True).notes["rain"]
assert "지금 비" not in _umbrella([30] * 13, raining_now=False).notes["rain"]
def test_umbrella_estimate_averages_the_window_hours_of_the_mid_forecast():
"""중기예보 날: 오전(~11시) 비 100%, 오후 0% 이면 6~23시 중 6시간 → 33점."""
r = estimate(_umbrella_defn(), _fc(am=100, pm=0), [list(range(6, 24))], CTX)
assert r.score == 33
def test_single_factor_gak_is_not_pulled_down_by_its_own_weakest_factor():
"""요소가 하나면 '가장 낮은 요소로 깎기'를 하지 않는다. 안 그러면 72점이 67점이 된다."""
r = _umbrella([100] + [0] * 12, raining_now=True)
assert r.score == r.factors["rain"] == 72
def test_weather_why_lists_every_condition_heaviest_first():
from services.index_service import WEATHER_SCORE_DEF, weather_why