487 lines
23 KiB
Python
487 lines
23 KiB
Python
from collections import Counter
|
|
from dataclasses import dataclass, field
|
|
from datetime import date
|
|
from math import cos, exp, pi
|
|
from statistics import mean
|
|
from typing import Optional
|
|
|
|
from common.enums import RainType, Sky
|
|
from common.utils.text import hour_label
|
|
|
|
AXES = ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")
|
|
_WEEKDAY = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
|
|
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
|
_UNKNOWN = 70
|
|
_EDGE = 85
|
|
_WORST_PULL = 0.25
|
|
_FALL_FLOOR = exp(-0.5)
|
|
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
|
|
_TEMP_PLATEAU = 2
|
|
_HUMIDITY_PLATEAU = 5
|
|
PRIORITY_WEIGHT = {1: 1.0, 2: 0.85, 3: 0.7}
|
|
|
|
|
|
def priority_score(score: int, priority: int) -> int:
|
|
"""중요도 배율을 한 번 적용하고 정수로 반올림한 표시·순위 공통 점수."""
|
|
return round(score * PRIORITY_WEIGHT[priority])
|
|
|
|
|
|
def rank_score(score: int, priority: int) -> tuple[int, int]:
|
|
"""중요도 반영이 끝난 표시 점수 내림차순. 동점이면 중요도 순."""
|
|
return score, -priority
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Hour:
|
|
hour: int
|
|
feels_c: float
|
|
rain_type: RainType
|
|
rain_prob: int
|
|
wind_ms: Optional[float]
|
|
humidity: int
|
|
sky: Sky
|
|
# Open-Meteo 보조값. 3시간 구간에서 가져오며 수집 전이면 None.
|
|
uv: Optional[float] = None
|
|
sunshine_ratio: Optional[float] = None # 해 난 비율 0~1
|
|
visibility_km: Optional[float] = None
|
|
gust_ms: Optional[float] = None
|
|
ground_c: Optional[float] = None
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Context:
|
|
day: date
|
|
is_holiday: bool
|
|
pm25: Optional[int]
|
|
air_label: Optional[str]
|
|
moon: float
|
|
sunset_score: Optional[int]
|
|
wind_warning: bool
|
|
lookahead_rain_prob: int
|
|
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
|
|
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
|
|
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
|
|
time_matches: bool = True # 평가하는 시간대가 각의 활동 시간대에 해당하는지
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DayForecast:
|
|
"""중기예보(일 단위) 하루치. 시간별 예보가 닿지 않는 날의 예상 점수 재료."""
|
|
temp_min_c: Optional[float]
|
|
temp_max_c: Optional[float]
|
|
rain_prob_am: int
|
|
rain_prob_pm: int
|
|
sky: Sky
|
|
|
|
|
|
@dataclass
|
|
class Result:
|
|
score: int
|
|
factors: dict[str, int]
|
|
notes: dict[str, str]
|
|
zero_reason: Optional[str]
|
|
summary: str
|
|
window: tuple[int, int] = field(default=(0, 0))
|
|
estimated: bool = False
|
|
|
|
|
|
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:
|
|
"""full 쪽은 100, zero 에서 0. 사이는 _fall 곡선."""
|
|
return _clamp(100 * _fall((v - full) / (zero - full)))
|
|
|
|
|
|
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 * _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]:
|
|
t = feels + rule.get("offset", 0)
|
|
shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
|
if rule["type"] == "range":
|
|
lo, hi = rule["lo"], rule["hi"]
|
|
return _range(t, lo, hi, rule.get("best"), rule.get("plateau", _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))
|
|
return _clamp(30 + 7 * dist), f"{shown}, 편한 범위 {lo}~{hi}°에서 멀수록 올라가요"
|
|
return _linear(t, rule["zero"], rule["full"]), shown
|
|
|
|
|
|
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 _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]:
|
|
if wind is None:
|
|
return _UNKNOWN, f"바람 정보가 없어 {_UNKNOWN}점으로 둬요"
|
|
if rule["type"] == "ignore":
|
|
return 50, f"바람 초속 {wind:g}m, 이 각엔 상관없어 50점으로 둬요"
|
|
note = f"바람 초속 {wind:g}m"
|
|
if rule["type"] == "calm":
|
|
ok = rule["ok"]
|
|
if wind <= ok / 2:
|
|
return 100, note
|
|
if wind <= ok:
|
|
return _clamp(100 - (100 - _EDGE) * (wind - ok / 2) / (ok / 2)), note
|
|
return _clamp(_EDGE * _fall((wind - ok) / (rule["limit"] - ok))), note
|
|
if rule["type"] == "moderate":
|
|
if 2 <= wind <= 5:
|
|
return 100, note
|
|
return (_clamp(60 + 20 * wind) if wind < 2 else _linear(wind, 12, 5)), note
|
|
return _linear(wind, 0, 8), note
|
|
|
|
|
|
def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
|
|
note = f"습도 {round(humidity)}%"
|
|
if rule["type"] == "range":
|
|
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":
|
|
return _linear(humidity, 90, 40), note
|
|
return 50, f"{note}, 이 각엔 상관없어 50점으로 둬요"
|
|
|
|
|
|
_AIR_RULE = {"zero": 75, "full": 15}
|
|
|
|
|
|
def air_score(pm25: Optional[int], label: Optional[str], rule: Optional[dict] = None) -> tuple[int, str]:
|
|
"""rule 이 없으면 맑을수록 좋음. 집콕각처럼 탁할수록 좋은 각은 {"zero": 15, "full": 75} 로 뒤집는다."""
|
|
if pm25 is None:
|
|
return _UNKNOWN, f"미세먼지 정보가 없어 {_UNKNOWN}점으로 둬요"
|
|
rule = rule or _AIR_RULE
|
|
return _linear(pm25, rule["zero"], rule["full"]), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
|
|
|
|
|
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
|
|
if uv is None:
|
|
return _UNKNOWN, "자외선 정보 없음"
|
|
return _linear(uv, rule["zero"], rule["full"]), f"자외선 {uv:.1f}"
|
|
|
|
|
|
def sun_score(rule: dict, ratio: Optional[float]) -> tuple[int, str]:
|
|
if ratio is None:
|
|
return _UNKNOWN, "햇빛 정보 없음"
|
|
return _linear(ratio, rule["zero"], rule["full"]), f"해 난 비율 {round(ratio * 100)}%"
|
|
|
|
|
|
def view_score(rule: dict, km: Optional[float]) -> tuple[int, str]:
|
|
if km is None:
|
|
return _UNKNOWN, "가시거리 정보 없음"
|
|
return _linear(km, rule["zero"], rule["full"]), f"가시거리 {km:.1f}km"
|
|
|
|
|
|
def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
|
kind = rule["type"]
|
|
if kind == "weekday":
|
|
key = "holiday" if ctx.is_holiday and "holiday" in rule else _WEEKDAY[ctx.day.weekday()]
|
|
v = rule.get(key, rule.get("default", 100))
|
|
return _clamp(v), f"{_WEEKDAY_KO[ctx.day.weekday()]}요일{' 공휴일' if ctx.is_holiday else ''}"
|
|
if kind == "moon":
|
|
return _clamp(20 + 80 * (1 - ctx.moon)), ctx.moon_note or f"달이 비추는 정도 {round(ctx.moon * 100)}%"
|
|
if kind == "sunset_score":
|
|
return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), (
|
|
f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
|
)
|
|
if kind == "sunrise_score":
|
|
return (ctx.sunrise_score if ctx.sunrise_score is not None else _UNKNOWN), (
|
|
f"일출 하늘 점수 {ctx.sunrise_score}" if ctx.sunrise_score is not None else f"일출 하늘 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
|
)
|
|
return (100, "활동 시간대에 해당해요") if ctx.time_matches else (0, "활동 시간대가 아니에요")
|
|
|
|
|
|
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
|
|
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
|
|
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
|
|
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "sunrise_score": "일출 하늘 예쁨", "fixed": "시간대 알맞음"}
|
|
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
|
|
_OM_LABEL = {"uv": "자외선 약함", "sun": "햇빛", "view": "가시거리"}
|
|
|
|
|
|
def axis_label(axis: str, rules: dict) -> str:
|
|
"""축 값은 '이 각에 좋은 정도'라서, 라벨도 바깥으로 갈수록 좋아지는 쪽으로 읽히게 쓴다."""
|
|
if axis in _OM_LABEL:
|
|
return _OM_LABEL[axis]
|
|
if axis == "rain":
|
|
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
|
|
if axis == "air":
|
|
rule = rules.get("air", _AIR_RULE)
|
|
return "공기 탁함" if rule["full"] > rule["zero"] else "공기 맑음"
|
|
table = {"temp": _TEMP_LABEL, "wind": _WIND_LABEL, "humidity": _HUMIDITY_LABEL, "time": _TIME_LABEL}[axis]
|
|
return rules[axis].get("label") or table[rules[axis]["type"]]
|
|
|
|
|
|
def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
|
"""걸린 조건의 이유와 상한(cap). cap 이 없으면 0점. (최소, 최대) 값은 '이상'이면 최대, '미만'이면 최소로 본다."""
|
|
for r in rules:
|
|
v = agg.get(r["field"])
|
|
if isinstance(v, tuple):
|
|
v = v[1] if r["op"] == ">=" else v[0]
|
|
if v is None:
|
|
continue
|
|
hit = (v >= r["value"]) if r["op"] == ">=" else (v < r["value"]) if r["op"] == "<" else (v == r["value"])
|
|
if hit:
|
|
cap = r.get("cap", 0)
|
|
return f"{_cond(r)[0]} {_tail(cap)}", cap
|
|
return None, None
|
|
|
|
|
|
_FIELD_TEXT = {
|
|
"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘",
|
|
"gust_ms": "돌풍", "ground_c": "지표면 온도", "humidity": "습도",
|
|
}
|
|
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°", "humidity": "%"}
|
|
|
|
|
|
def _cond(r: dict) -> tuple[str, str, str]:
|
|
"""조건 하나를 (이유, '…이거나', '…이면') 꼴로."""
|
|
if r["field"] == "warning":
|
|
return "강풍 특보가 있어", "강풍 특보가 있거나", "강풍 특보가 있으면"
|
|
if r["field"] == "snow":
|
|
return "눈 소식이 없어", "눈 소식이 없거나", "눈 소식이 없으면"
|
|
if r["field"] == "rain":
|
|
return "비 소식이 있어", "비 소식이 있거나", "비 소식이 있으면"
|
|
if r["field"] == "rain_before":
|
|
return "앞서 내린 비가 없어", "앞서 내린 비가 없거나", "앞서 내린 비가 없으면"
|
|
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
|
|
return f"{base}이라", f"{base}이거나", f"{base}이면"
|
|
|
|
|
|
def _tail(cap: int) -> str:
|
|
return f"최대 {cap}점" if cap else "0점"
|
|
|
|
|
|
def zero_rules_text(rules: list[dict]) -> str:
|
|
if not rules:
|
|
return "없음 (재미로 보는 지수)"
|
|
groups: dict[int, list[dict]] = {}
|
|
for r in rules:
|
|
groups.setdefault(r.get("cap", 0), []).append(r)
|
|
return ", ".join(
|
|
" ".join([_cond(r)[1] for r in rs[:-1]] + [_cond(rs[-1])[2]]) + f" {_tail(cap)}" for cap, rs in groups.items()
|
|
)
|
|
|
|
|
|
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
|
|
|
|
|
def _summary(hours: list[Hour]) -> str:
|
|
mid = hours[len(hours) // 2]
|
|
wind = mid.wind_ms
|
|
tag = f"비 {mid.rain_prob}%" if mid.rain_prob >= 50 else (
|
|
"바람 살랑" if wind is not None and wind <= 2 else "바람 조금" if wind is not None and wind <= 5 else "바람 강함" if wind is not None else _SKY_WORD[mid.sky]
|
|
)
|
|
return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}"
|
|
|
|
|
|
def _weighted(factors: dict[str, int], weights: dict[str, int], worst_pull: bool = True, time_is_binary: bool = False) -> 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] and not (time_is_binary and a == "time")), default=100)
|
|
return round(mixed * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
|
|
|
|
|
|
def _until(definition) -> str:
|
|
ahead = max((w.get("lookahead_days", 0) for w in getattr(definition, "windows", None) or []), default=0)
|
|
return {1: "내일까지", 2: "모레까지"}.get(ahead, f"{ahead}일 뒤까지") if ahead else ""
|
|
|
|
|
|
def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Result]:
|
|
"""지수 하나를 하루치로 계산한다. 시간대가 여러 개면 가장 좋은 쪽."""
|
|
best: Optional[Result] = None
|
|
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
|
|
rules = definition.factor_rules
|
|
until = _until(definition)
|
|
for hours in windows:
|
|
if not hours:
|
|
continue
|
|
own_prob = max(h.rain_prob for h in hours)
|
|
max_prob = max(own_prob, ctx.lookahead_rain_prob)
|
|
raining = any(h.rain_type is not RainType.NONE for h in hours)
|
|
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
|
|
feels = mean(h.feels_c for h in hours)
|
|
uvs = [h.uv for h in hours if h.uv is not None]
|
|
suns = [h.sunshine_ratio for h in hours if h.sunshine_ratio is not None]
|
|
views = [h.visibility_km for h in hours if h.visibility_km is not None]
|
|
gusts = [h.gust_ms for h in hours if h.gust_ms is not None]
|
|
grounds = [h.ground_c for h in hours if h.ground_c is not None]
|
|
scored = {
|
|
"temp": temp_score(rules["temp"], feels),
|
|
"rain": rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else ""),
|
|
"wind": wind_score(rules["wind"], max(winds) if winds else None),
|
|
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
|
|
"air": air_score(ctx.pm25, ctx.air_label, rules.get("air")),
|
|
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
|
|
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
|
|
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
|
|
"time": time_score(rules["time"], ctx),
|
|
}
|
|
factors = {a: v for a, (v, _) in scored.items()}
|
|
notes = {a: n for a, (_, n) in scored.items()}
|
|
score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
|
|
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)),
|
|
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
|
|
"warning": "wind" if ctx.wind_warning else None,
|
|
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
|
|
"snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no",
|
|
"rain": "yes" if raining else "no", "humidity": round(mean(h.humidity for h in hours)),
|
|
"rain_before": "yes" if any(h < hours[0].hour for h in ctx.rain_hours) else "no",
|
|
}
|
|
reason, cap = _zero(definition.zero_rules, agg)
|
|
if reason is not None:
|
|
score = min(score, cap)
|
|
result = Result(score=score, factors=factors, notes=notes, zero_reason=reason, summary=_summary(hours), window=(hours[0].hour, hours[-1].hour))
|
|
if best is None or result.score > best.score:
|
|
best = result
|
|
return best
|
|
|
|
|
|
def hour_temp(lo: float, hi: float, hour: int) -> float:
|
|
"""최저·최고 기온으로 그 시각 기온을 어림한다. 새벽 6시 최저, 오후 3시 최고. 24시 넘으면 다음 날 같은 시각."""
|
|
h = hour % 24
|
|
f = (1 - cos(pi * (h - 6) / 9)) / 2 if 6 <= h <= 15 else (1 + cos(pi * ((h - 15) % 24) / 15)) / 2
|
|
return round(lo + (hi - lo) * f, 1)
|
|
|
|
|
|
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
|
|
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률과 눈(늘 없음으로 봄)만 본다."""
|
|
if fc.temp_min_c is None or fc.temp_max_c is None:
|
|
return None
|
|
best: Optional[Result] = None
|
|
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
|
|
rules = definition.factor_rules
|
|
until = _until(definition)
|
|
after = next_fc or fc
|
|
for hours in windows:
|
|
if not hours:
|
|
continue
|
|
temps = [hour_temp(fc.temp_min_c, fc.temp_max_c, h) for h in hours]
|
|
own_prob = max(fc.rain_prob_am if h < 12 else fc.rain_prob_pm if h < 24 else after.rain_prob_am for h in hours)
|
|
max_prob = max(own_prob, ctx.lookahead_rain_prob)
|
|
humidity = (50, "습도 이 각엔 상관없어 50점으로 둬요") if rules["humidity"]["type"] == "ignore" else (
|
|
_UNKNOWN, f"습도 정보가 없어 {_UNKNOWN}점으로 둬요"
|
|
)
|
|
temp, temp_note = temp_score(rules["temp"], mean(temps))
|
|
scored = {
|
|
"temp": (temp, f"{temp_note} (최저·최고 기온으로 어림)"),
|
|
"rain": rain_score(rules["rain"], max_prob, False, until if max_prob > own_prob else ""),
|
|
"wind": wind_score(rules["wind"], None),
|
|
"humidity": humidity,
|
|
"air": air_score(None, None),
|
|
**{a: (_UNKNOWN, f"{_OM_LABEL[a]} 정보가 없어 {_UNKNOWN}점으로 둬요") if weights[a] else (0, "") for a in _OM_LABEL},
|
|
"time": time_score(rules["time"], ctx),
|
|
}
|
|
factors = {a: v for a, (v, _) in scored.items()}
|
|
notes = {a: n for a, (_, n) in scored.items()}
|
|
score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
|
|
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
|
|
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
|
|
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
|
|
reason, cap = _zero([r for r in definition.zero_rules if r["field"] in known], known)
|
|
if reason is not None:
|
|
score = min(score, cap)
|
|
mid = hours[len(hours) // 2]
|
|
summary = f"{hour_label(mid % 24)} {round(hour_temp(fc.temp_min_c, fc.temp_max_c, mid))}° 예상, 비 {max_prob}%"
|
|
result = Result(score=score, factors=factors, notes=notes, zero_reason=reason, summary=summary, window=(hours[0], hours[-1]), estimated=True)
|
|
if best is None or result.score > best.score:
|
|
best = result
|
|
return best
|
|
|
|
|
|
# 나들이 날씨 점수: 낮 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}}
|
|
_OUTING_SKY = {Sky.CLEAR: 100, Sky.PARTLY: 80, Sky.CLOUDY: 50}
|
|
_OUTING_RAIN_PROB, _OUTING_RAIN_CAP = 60, 30
|
|
|
|
|
|
@dataclass
|
|
class Outing:
|
|
score: int
|
|
factors: dict[str, int]
|
|
notes: dict[str, str]
|
|
reason: str # 순위 옆 한 줄 근거 ("비 10% · 체감 21° · 맑음")
|
|
capped: bool # 비 때문에 최대 30점으로 묶였는지
|
|
estimated: bool = False
|
|
|
|
|
|
def _outing(scored: dict[str, tuple[int, str]], prob: int, raining: bool, temp_word: str, sky: Sky, estimated: bool) -> Outing:
|
|
factors = {a: v for a, (v, _) in scored.items()}
|
|
notes = {a: n for a, (_, n) in scored.items()}
|
|
worst = min(factors.values())
|
|
score = round(sum(factors[a] * w for a, w in _OUTING_WEIGHTS.items()) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
|
|
capped = raining or prob >= _OUTING_RAIN_PROB
|
|
if capped:
|
|
score = min(score, _OUTING_RAIN_CAP)
|
|
notes["rain"] += f", 비 확률 {_OUTING_RAIN_PROB}% 이상이거나 비 소식이면 최대 {_OUTING_RAIN_CAP}점"
|
|
reason = " · ".join(["비 소식" if raining else f"비 {prob}%", temp_word, _SKY_WORD[sky]])
|
|
return Outing(score=score, factors=factors, notes=notes, reason=reason, capped=capped, estimated=estimated)
|
|
|
|
|
|
def outing(hours: list[Hour]) -> Optional[Outing]:
|
|
"""시간별 예보로 내는 나들이 점수. 10~17시가 다 있어야 한다."""
|
|
if len(hours) < OUTING_HOURS[1] - OUTING_HOURS[0]:
|
|
return None
|
|
prob = max(h.rain_prob for h in hours)
|
|
raining = any(h.rain_type is not RainType.NONE for h in hours)
|
|
feels = mean(h.feels_c for h in hours)
|
|
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
|
|
sky = Counter(h.sky for h in hours).most_common(1)[0][0]
|
|
scored = {
|
|
"temp": temp_score(_OUTING_RULES["temp"], feels),
|
|
"rain": rain_score(_OUTING_RULES["rain"], prob, raining),
|
|
"sky": (round(mean(_OUTING_SKY[h.sky] for h in hours)), f"하늘 {_SKY_WORD[sky]}"),
|
|
"wind": wind_score(_OUTING_RULES["wind"], max(winds) if winds else None),
|
|
}
|
|
return _outing(scored, prob, raining, f"체감 {round(feels)}°", sky, False)
|
|
|
|
|
|
def outing_estimate(fc: DayForecast) -> Optional[Outing]:
|
|
"""중기예보(하루 단위)로 내는 예상 나들이 점수. 바람은 정보 없음으로 둔다."""
|
|
if fc.temp_min_c is None or fc.temp_max_c is None:
|
|
return None
|
|
hours = range(*OUTING_HOURS)
|
|
temp = mean(hour_temp(fc.temp_min_c, fc.temp_max_c, h) for h in hours)
|
|
prob = max(fc.rain_prob_am, fc.rain_prob_pm)
|
|
value, note = temp_score(_OUTING_RULES["temp"], temp)
|
|
scored = {
|
|
"temp": (value, f"{note} (최저·최고 기온으로 어림)"),
|
|
"rain": rain_score(_OUTING_RULES["rain"], prob, False),
|
|
"sky": (_OUTING_SKY[fc.sky], f"하늘 {_SKY_WORD[fc.sky]}"),
|
|
"wind": wind_score(_OUTING_RULES["wind"], None),
|
|
}
|
|
return _outing(scored, prob, False, f"낮 {round(temp)}°", fc.sky, True)
|