diff --git a/backend/crud/sky_crud.py b/backend/crud/sky_crud.py index 0938bf9..cc39202 100644 --- a/backend/crud/sky_crud.py +++ b/backend/crud/sky_crud.py @@ -58,5 +58,9 @@ class SkyCRUD: ) return list((await s.scalars(stmt)).all()) + async def west_open_spots(self, s: AsyncSession) -> list[SunsetSpot]: + """서쪽이 트인 노을 명소 (sort_order 0).""" + return list((await s.scalars(select(SunsetSpot).where(SunsetSpot.sort_order == 0))).all()) + async def ranking_regions(self, s: AsyncSession) -> list[Region]: return list((await s.scalars(select(Region).where(Region.is_ranking_spot.is_(True)))).all()) diff --git a/backend/docs/openmeteo-data.md b/backend/docs/openmeteo-data.md index 30eab53..ab8999d 100644 --- a/backend/docs/openmeteo-data.md +++ b/backend/docs/openmeteo-data.md @@ -40,18 +40,19 @@ Open-Meteo(`api.open-meteo.com/v1/forecast`)에서 받는 데이터와 저장 ``` canvas = max(mid20, high20) -f_canvas = 0.2 + 0.8 × canvas/50 (canvas ≤ 50) / max(0, 1 - (canvas-50)/50) (canvas > 50) +f_canvas = 0.4 + 0.6 × canvas/50 (canvas ≤ 50) / max(0, 1 - (canvas-50)/50) (canvas > 50) f_near = 1 - 0.8 × low20 / 100 light = 1 - min(low100 + 0.5×mid100, 100) / 100 구름 점수 = 100 × (0.75×f_canvas + 0.25×f_near) × (0.25 + 0.75×light) 점수 = min(100, round(모델 평균 구름 점수 × 공기 보정)) ``` -- 맑은 하늘(구름 0%)은 40점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 10% 미만을 0.3으로 고정해 맑은 날 전국이 48점에 몰리고, 10%에서 점수가 오히려 떨어졌다. -- 공기 보정 (`air_factor`, 구 중심 해 질·뜰 무렵 값. 값이 없으면 ×1.0): - - 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 40km 이상 ×1.0 ~ 5km 이하 ×0.6. 뿌연 공기는 색을 흐린다. - - 습도(`weather_hourly.humidity`, 가장 가까운 정시): 50% 이하 ×1.0 ~ 90% 이상 ×0.75. +- 맑은 하늘(구름 0%)은 55점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 10% 미만을 0.3으로 고정해 맑은 날 전국이 48점에 몰리고, 10%에서 점수가 오히려 떨어졌다. +- 공기 보정 (`air_factor`, 구 중심 해 질·뜰 무렵 값. 값이 없으면 ×1.0). 평소 공기(가시거리 20km·습도 60%)를 ×1.0 으로 두고 좋으면 올리고 나쁘면 내린다. 맑은 날 전국이 한 점수(구름 0% = 55점)에 몰리지 않게 하려는 것: + - 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 5km 이하 ×0.8 · 20km ×1.0 · 40km 이상 ×1.12, 사이는 직선. 뿌연 공기는 색을 흐리고 맑은 공기는 더 선명하다. + - 습도(`weather_hourly.humidity`, 가장 가까운 정시): 40% 이하 ×1.06 · 60% ×1.0 · 90% 이상 ×0.85, 사이는 직선. - 비 갠 뒤: 2~6시간 전 비 확률 60% 이상이고 그 시각 비 확률 40% 미만이면 ×1.15. +- 서쪽이 트인 곳 (노을만): 구 중심 20km 안에 서쪽이 트인 노을 명소(`sunset_spot.sort_order` 0 = `sunset_spot.csv`의 `west_open` 1)가 있으면 ×1.1. 산·건물에 가리지 않고 해가 지평선까지 보이는 곳이라서. 명소에는 바다뿐 아니라 강변·높은 전망대도 있어 서울 마포·강남, 대구 수성 같은 내륙 구도 받는다. 일출은 동쪽이 트였는지 데이터가 없어 넣지 않는다. - 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음. 신뢰도는 공기 보정 전 구름 점수로 본다. - 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림. @@ -140,17 +141,19 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100 | 지수 | 새 비중 | 바뀐 기존 비중 (기온·비·바람·습도·공기) | 추가 0점 조건 | |---|---|---|---| | 빨래각 | 햇빛 25 | 15·30·15·10·0 | | -| 멍뭉산책각 | 자외선 5 | 35·25·10·5·15 | 지표면 온도 45° 이상 | -| 피크닉각 | 자외선 10 | 25·25·15·5·10 | | -| 등산각 | 자외선 5, 가시거리 5 | 25·25·20·5·10 | | -| 러닝각 | 자외선 5 | 35·20·10·15·10 | | -| 가드닝각 | 자외선 5 | 25·30·10·15·10 | | +| 피크닉각 | 자외선 10, 햇빛 10 | 20·20·15·5·10 | | +| 등산각 | 자외선 10, 햇빛 10, 가시거리 5 | 20·20·15·5·10 | | +| 자전거각 | 자외선 10, 햇빛 10 | 20·20·20·5·10 | 돌풍 15m/s 이상 | +| 가드닝각 | 자외선 10, 햇빛 10 | 20·25·10·10·10 | | +| 세차각 | 자외선 10, 햇빛 10 | 5·40·10·10·10 | | | 별보기각 | 가시거리 15 | 5·10·5·5·15 (시간대 45 그대로) | | | 사진산책각 | 가시거리 10 | 10·25·10·5·10 (시간대 30 그대로) | | -| 자전거각 | | 변경 없음 | 돌풍 15m/s 이상 | +| 멍뭉산책각 | | 40·25·10·5·15 | 지표면 온도 45° 이상 | +| 러닝각 | | 35·20·10·15·15 | | | 캠핑각 | | 변경 없음 | 돌풍 15m/s 이상 | -- 나머지 17개 지수는 점수가 바뀌지 않는다 (적용 전후 비교로 확인). +- 해가 떠 있는 시간대의 야외 활동(피크닉·등산·자전거·가드닝·세차)은 햇빛과 자외선을 **같은 비중(10씩)으로 함께** 둔다. 햇빛은 많을수록, 자외선은 낮을수록 점수가 높다. 자외선만 있으면 흐린 날이 "자외선 낮음 = 좋음"으로 맑은 날보다 높게 나오고, 햇빛만 있으면 한여름 강한 자외선을 놓친다. +- 러닝각(6~8·19~22시)·멍뭉산책각(7~9·17~20시)은 자외선을 뺐다. 이른 아침·저녁이라 자외선이 늘 0이라 점수를 가르지 못했다. 그 비중은 러닝은 공기, 멍뭉산책은 기온으로 옮겼다. 사진산책각(일몰 무렵)도 같은 이유로 햇빛·자외선을 두지 않는다. - 비중·기준값은 초안이다. 수치는 `seed/index_definition.json`에서 바꾸고 `load_seed.py`로 다시 넣는다. ### 3시간 구간을 계산 창에 연결하는 규칙 diff --git a/backend/seed/index_definition.json b/backend/seed/index_definition.json index 37f60de..1beecf4 100644 --- a/backend/seed/index_definition.json +++ b/backend/seed/index_definition.json @@ -88,13 +88,13 @@ "to": 16 } ], - "weight_temp": 25, - "weight_rain": 25, + "weight_temp": 20, + "weight_rain": 20, "weight_wind": 15, "weight_humidity": 5, "weight_air": 10, "weight_uv": 10, - "weight_sun": 0, + "weight_sun": 10, "weight_view": 0, "weight_time": 10, "factor_rules": { @@ -127,6 +127,10 @@ "uv": { "zero": 8, "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ @@ -381,13 +385,13 @@ "to": 12 } ], - "weight_temp": 25, - "weight_rain": 25, - "weight_wind": 20, + "weight_temp": 20, + "weight_rain": 20, + "weight_wind": 15, "weight_humidity": 5, "weight_air": 10, - "weight_uv": 5, - "weight_sun": 0, + "weight_uv": 10, + "weight_sun": 10, "weight_view": 5, "weight_time": 5, "factor_rules": { @@ -425,6 +429,10 @@ "view": { "zero": 5, "full": 20 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ @@ -466,12 +474,12 @@ } ], "weight_temp": 5, - "weight_rain": 60, + "weight_rain": 40, "weight_wind": 10, "weight_humidity": 10, "weight_air": 10, - "weight_uv": 0, - "weight_sun": 0, + "weight_uv": 10, + "weight_sun": 10, "weight_view": 0, "weight_time": 5, "factor_rules": { @@ -494,6 +502,14 @@ "time": { "type": "fixed", "value": 100 + }, + "uv": { + "zero": 8, + "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ @@ -612,8 +628,8 @@ "weight_rain": 20, "weight_wind": 10, "weight_humidity": 15, - "weight_air": 10, - "weight_uv": 5, + "weight_air": 15, + "weight_uv": 0, "weight_sun": 0, "weight_view": 0, "weight_time": 5, @@ -637,10 +653,6 @@ "time": { "type": "fixed", "value": 100 - }, - "uv": { - "zero": 8, - "full": 2 } }, "zero_rules": [ @@ -982,13 +994,13 @@ "to": 19 } ], - "weight_temp": 25, - "weight_rain": 25, - "weight_wind": 25, + "weight_temp": 20, + "weight_rain": 20, + "weight_wind": 20, "weight_humidity": 5, "weight_air": 10, - "weight_uv": 5, - "weight_sun": 0, + "weight_uv": 10, + "weight_sun": 10, "weight_view": 0, "weight_time": 5, "factor_rules": { @@ -1021,6 +1033,10 @@ "uv": { "zero": 8, "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ @@ -1069,12 +1085,12 @@ "to": 20 } ], - "weight_temp": 35, + "weight_temp": 40, "weight_rain": 25, "weight_wind": 10, "weight_humidity": 5, "weight_air": 15, - "weight_uv": 5, + "weight_uv": 0, "weight_sun": 0, "weight_view": 0, "weight_time": 5, @@ -1101,10 +1117,6 @@ "time": { "type": "fixed", "value": 100 - }, - "uv": { - "zero": 8, - "full": 2 } }, "zero_rules": [ @@ -1431,13 +1443,13 @@ "to": 10 } ], - "weight_temp": 25, - "weight_rain": 30, + "weight_temp": 20, + "weight_rain": 25, "weight_wind": 10, - "weight_humidity": 15, + "weight_humidity": 10, "weight_air": 10, - "weight_uv": 5, - "weight_sun": 0, + "weight_uv": 10, + "weight_sun": 10, "weight_view": 0, "weight_time": 5, "factor_rules": { @@ -1467,6 +1479,10 @@ "uv": { "zero": 8, "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ diff --git a/backend/services/calc/sky_score.py b/backend/services/calc/sky_score.py index cc2109e..7cb9c6b 100644 --- a/backend/services/calc/sky_score.py +++ b/backend/services/calc/sky_score.py @@ -6,10 +6,12 @@ from typing import Optional from common.enums import Confidence, SkyGrade, SkySituation, SkyType DISTANCES_KM = (20, 100) -# 물들 구름이 하나도 없을 때의 canvas 값. 50% 까지 곧게 올라가 맑은 날도 구름 몇 % 차이로 점수가 갈린다 (맑은 하늘 40점 = 은은함). -_CLEAR_CANVAS = 0.2 +# 물들 구름이 하나도 없을 때의 canvas 값. 50% 까지 곧게 올라가 맑은 날도 구름 몇 % 차이로 점수가 갈린다 (맑은 하늘 55점 = 은은함). +_CLEAR_CANVAS = 0.4 # 해 지기(뜨기) 이만큼 전 사이에 비가 왔다가 그 시각엔 개면 공기가 맑고 구름이 남아 더 붉다. RAIN_BEFORE_HOURS = (2, 6) +# 서쪽이 바다·강·전망대로 트여 해가 지평선까지 보이는 곳은 산·건물에 가리지 않아 노을이 더 잘 보인다. +OPEN_WEST_BONUS = 1.1 @dataclass(frozen=True) @@ -26,6 +28,7 @@ class Air: humidity: float | None = None rain_before: int | None = None # RAIN_BEFORE_HOURS 사이 가장 높은 비 확률 rain_now: int | None = None + open_west: bool = False # 가까이 서쪽이 트인 노을 명소가 있음 (노을만) def score(near20: Layers, far100: Layers) -> int: @@ -37,21 +40,32 @@ def score(near20: Layers, far100: Layers) -> int: return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light)) -def _ramp(v: float, bad: float, good: float, low: float) -> float: - """good 쪽은 1.0, bad 쪽은 low, 사이는 직선.""" - t = max(0.0, min(1.0, (v - bad) / (good - bad))) - return low + (1 - low) * t +# 공기 보정 기준점 (값, 배수). 평소 공기(가시거리 20km, 습도 60%)가 ×1.0 이고 좋으면 올리고 나쁘면 내린다. 양 끝 밖은 끝 값 그대로. +_VISIBILITY_FACTOR = ((5, 0.8), (20, 1.0), (40, 1.12)) +_HUMIDITY_FACTOR = ((40, 1.06), (60, 1.0), (90, 0.85)) + + +def _interp(v: float, points: tuple[tuple[float, float], ...]) -> float: + """기준점 사이를 직선으로 잇는다.""" + if v <= points[0][0]: + return points[0][1] + for (x0, f0), (x1, f1) in zip(points, points[1:]): + if v <= x1: + return f0 + (f1 - f0) * (v - x0) / (x1 - x0) + return points[-1][1] def air_factor(air: Air) -> float: - """공기로 구름 점수를 보정하는 배수. 뿌연 공기·높은 습도는 색을 흐리게 하고, 비 갠 뒤는 더 붉다.""" + """공기로 구름 점수를 보정하는 배수. 맑고 건조하면 올리고 뿌옇거나 습하면 내린다. 비 갠 뒤는 더 붉다.""" f = 1.0 if air.visibility_km is not None: - f *= _ramp(air.visibility_km, 5, 40, 0.6) + f *= _interp(air.visibility_km, _VISIBILITY_FACTOR) if air.humidity is not None: - f *= _ramp(air.humidity, 90, 50, 0.75) + f *= _interp(air.humidity, _HUMIDITY_FACTOR) if air.rain_before is not None and air.rain_before >= 60 and (air.rain_now or 0) < 40: f *= 1.15 + if air.open_west: + f *= OPEN_WEST_BONUS return f diff --git a/backend/services/sky_service.py b/backend/services/sky_service.py index 95b88ac..8b20637 100644 --- a/backend/services/sky_service.py +++ b/backend/services/sky_service.py @@ -1,7 +1,7 @@ import asyncio import math import statistics -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from datetime import date, datetime, timedelta, timezone from typing import Optional @@ -31,6 +31,7 @@ DAYS = 3 SPOT_RADIUS_KM = EVENT_RADIUS_KM SPOT_LIMIT = 3 _MARKER_TTL = 24 * 3600 +OPEN_WEST_KM = 20 # 이 안에 서쪽이 트인 명소가 있으면 노을 가산 (부안 채석강·진도 세방낙조가 구 중심에서 10km 넘게 떨어져 있어 20km) _background: set[asyncio.Task] = set() @@ -222,11 +223,19 @@ def _air( ) +def _open_west(region: Region, spots: list[SunsetSpot]) -> bool: + """구 중심 OPEN_WEST_KM 안에 서쪽이 트인 노을 명소가 있는지.""" + lat, lon = float(region.lat), float(region.lon) + return any(haversine_km(lat, lon, float(p.lat), float(p.lon)) <= OPEN_WEST_KM for p in spots) + + def _score_rows( region: Region, today: date, clouds: dict, now: datetime, hourly: Optional[dict[tuple[str, datetime], WeatherHourly]] = None, om: Optional[dict[tuple[str, datetime], OpenMeteoHourly]] = None, + open_west: bool = False, ) -> list[dict]: - """구름 점수(모델 평균)에 공기 보정(가시거리·습도·비 갠 뒤)을 곱한다. 공기 값이 없으면 구름 점수 그대로.""" + """구름 점수(모델 평균)에 공기 보정(가시거리·습도·비 갠 뒤)을 곱한다. 공기 값이 없으면 구름 점수 그대로. + open_west 면 노을에만 서쪽이 트인 곳 가산을 더한다.""" rows = [] for kind in (SkyType.SUNSET, SkyType.SUNRISE): for i in range(DAYS): @@ -244,7 +253,7 @@ def _score_rows( model_layers.append(layers) if not per_model: continue - air = _air(region.code, sun_at, hourly or {}, om or {}) + air = replace(_air(region.code, sun_at, hourly or {}, om or {}), open_west=open_west and kind is SkyType.SUNSET) factor = air_factor(air) value = min(100, round(statistics.mean(per_model) * factor)) sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(len(DISTANCES_KM)))) @@ -417,7 +426,10 @@ class SkyService: LOG.error(f"[sky] air openmeteo: {err.name}") hourly = {(w.region_code, w.forecast_at): w for w in hourly_rows or []} om = {(o.region_code, o.forecast_at): o for o in om_rows or []} - score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now, hourly, om)] + err, west_spots = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.west_open_spots(s)) + if err is not ErrorType.SUCCESS: + LOG.error(f"[sky] west spots: {err.name}") + score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now, hourly, om, _open_west(r, west_spots or []))] err = await DB_SESSION_MNG.execute_lambda_run([ lambda s: self.crud.upsert_clouds(s, cloud_rows), lambda s: self.crud.upsert_scores(s, score_rows), diff --git a/backend/tests/test_sky_api.py b/backend/tests/test_sky_api.py index 68fa6d2..659a887 100644 --- a/backend/tests/test_sky_api.py +++ b/backend/tests/test_sky_api.py @@ -156,8 +156,8 @@ def test_score_rows_apply_air_at_sunset_and_keep_cloud_score_without_air(): hourly = {("R", hour): SimpleNamespace(humidity=90, rain_prob=0)} om = {("R", sky_service._nearest_slot(hour)): SimpleNamespace(visibility_m=5000)} hazy = sky_service._score_rows(region, today, clouds, now, hourly, om)[0]["score"] - assert hazy == round(plain * 0.6 * 0.75) - rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=50, rain_prob=80), ("R", hour): SimpleNamespace(humidity=50, rain_prob=10)} + assert hazy == round(plain * 0.8 * 0.85) + rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=60, rain_prob=80), ("R", hour): SimpleNamespace(humidity=60, rain_prob=10)} assert sky_service._score_rows(region, today, clouds, now, rain, {})[0]["score"] == min(100, round(plain * 1.15)) @@ -165,3 +165,30 @@ def test_nearest_slot_is_closest_three_hour_end(): from datetime import datetime, timezone at = lambda h, m=0: datetime(2026, 10, 7, h, m, tzinfo=timezone.utc) # noqa: E731 assert [sky_service._nearest_slot(at(h, m)).hour for h, m in ((8, 0), (9, 0), (10, 29), (10, 31))] == [9, 9, 9, 12] + + +def test_open_west_bonus_applies_to_sunset_only_and_needs_a_spot_nearby(): + from datetime import date, datetime, timezone + from types import SimpleNamespace + + from common.enums import SkyType + from services.calc.sky_score import Layers + from services.calc.sun import sun_times + + region = SimpleNamespace(code="R", lat=37.56, lon=126.91) + today = date(2026, 10, 7) + st = sun_times(today, region.lat, region.lon) + clouds = { + ("R", kind.value, km, sky_service._nearest_hour(at), 3): Layers(0, 20, 0) + for kind, at in ((SkyType.SUNSET, st.sunset_at), (SkyType.SUNRISE, st.sunrise_at)) for km in (20, 100) + } + now = datetime(2026, 10, 7, 3, tzinfo=timezone.utc) + by = lambda rows: {(r["sky_type"], r["score_date"]): r["score"] for r in rows} # noqa: E731 + plain = by(sky_service._score_rows(region, today, clouds, now)) + west = by(sky_service._score_rows(region, today, clouds, now, open_west=True)) + assert west[(SkyType.SUNSET.value, today)] == min(100, round(plain[(SkyType.SUNSET.value, today)] * 1.1)) + assert west[(SkyType.SUNRISE.value, today)] == plain[(SkyType.SUNRISE.value, today)] + + near = SimpleNamespace(lat=37.5555, lon=126.895) # 망원한강공원, 약 1.5km + far = SimpleNamespace(lat=37.0, lon=126.0) + assert sky_service._open_west(region, [near]) and not sky_service._open_west(region, [far]) and not sky_service._open_west(region, []) diff --git a/backend/tests/test_sky_score.py b/backend/tests/test_sky_score.py index c9c39ce..33b08b3 100644 --- a/backend/tests/test_sky_score.py +++ b/backend/tests/test_sky_score.py @@ -24,15 +24,21 @@ def test_score_rises_steadily_with_a_few_clouds(): assert scores == sorted(scores) and len(set(scores)) == len(scores) # 맑은 날도 구름 몇 %로 갈리고 10%에서 꺾이지 않는다 -def test_air_factor_hazy_humid_lowers_and_clearing_rain_raises(): +def test_air_factor_centers_on_usual_air_and_clearing_rain_raises(): assert air_factor(Air()) == 1.0 - assert air_factor(Air(visibility_km=40, humidity=50)) == 1.0 - assert air_factor(Air(visibility_km=5)) == 0.6 and air_factor(Air(humidity=90)) == 0.75 - assert 0.6 < air_factor(Air(visibility_km=30)) < 1.0 + assert air_factor(Air(visibility_km=20, humidity=60)) == 1.0 # 평소 공기 + assert air_factor(Air(visibility_km=5)) == 0.8 and air_factor(Air(humidity=90)) == 0.85 + assert air_factor(Air(visibility_km=40)) == 1.12 and air_factor(Air(humidity=40)) == 1.06 # 맑고 건조하면 올라간다 + assert 0.8 < air_factor(Air(visibility_km=12.5)) < 1.0 < air_factor(Air(visibility_km=30)) < 1.12 assert air_factor(Air(rain_before=70, rain_now=10)) == 1.15 assert air_factor(Air(rain_before=70, rain_now=60)) == 1.0 # 아직 비 오는 중이면 가산 없음 +def test_open_west_horizon_adds_bonus(): + assert air_factor(Air(open_west=True)) == 1.1 + assert air_factor(Air(open_west=True, rain_before=70, rain_now=10)) == 1.15 * 1.1 + + def test_low_clouds_toward_sun_block_the_light(): canvas = Layers(low=0, mid=20, high=50) assert grade(score(canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY