219 lines
10 KiB
Python
219 lines
10 KiB
Python
"""조후(한난조습): 내 사주의 차고 더움·마르고 젖음과 오늘 날씨가 잘 맞는지."""
|
|
|
|
from dataclasses import dataclass
|
|
from typing import Iterable
|
|
|
|
from services.saju.pillars import Chart
|
|
from services.saju.strength import POSITION_POINTS, Strength, chart_strength
|
|
|
|
# 글자별 (한난, 조습) 초안 — 주인 확인 필요. 한난: 차가움 −1 … 따뜻함 +1, 조습: 마름 −1 … 습함 +1
|
|
# 丙丁巳午는 불이라 따뜻하고 말리며, 壬癸亥子는 물이라 차고 젖는다. 庚辛申酉는 가을 쇠라 서늘하고 마르고,
|
|
# 戊未戌는 마른 흙(조토), 己丑辰은 젖은 흙(습토)이다. 甲乙寅卯 나무는 온화하되 寅卯는 초봄 남은 추위로 조금 서늘하게 둔다
|
|
CHAR_CLIMATE: dict[str, tuple[float, float]] = {
|
|
"甲": (0.0, 0.1), "乙": (0.0, 0.2),
|
|
"丙": (1.0, -0.5), "丁": (0.7, -0.3),
|
|
"戊": (0.3, -0.6), "己": (0.0, 0.6),
|
|
"庚": (-0.5, -0.5), "辛": (-0.4, -0.4),
|
|
"壬": (-0.7, 0.9), "癸": (-0.6, 1.0),
|
|
"子": (-1.0, 0.8), "丑": (-0.8, 0.6), # 한겨울 물, 언 젖은 흙
|
|
"寅": (-0.3, 0.0), "卯": (-0.1, 0.2),
|
|
"辰": (0.0, 0.6), # 봄 젖은 흙 (물 창고)
|
|
"巳": (0.8, -0.3), "午": (1.0, -0.5),
|
|
"未": (0.9, -0.7), # 대서가 든 한여름 마른 흙 (지장간 丁火)
|
|
"申": (-0.3, -0.3), "酉": (-0.5, -0.5),
|
|
"戌": (0.2, -0.8), # 가을 마른 흙 (불 창고)
|
|
"亥": (-0.7, 0.8),
|
|
}
|
|
SEASONS = {"寅卯辰": "봄", "巳午未": "여름", "申酉戌": "가을", "亥子丑": "겨울"}
|
|
# 월령: 태어난 달이 다른 글자를 데우거나 식힌다 (『궁통보감』 조후). 달별 한난, 계절별 조습
|
|
MONTH_TEMP = {"寅": -0.4, "卯": -0.1, "辰": 0.2, "巳": 0.6, "午": 0.9, "未": 1.0, "申": 0.4, "酉": -0.1, "戌": -0.3, "亥": -0.6, "子": -0.9, "丑": -1.0}
|
|
SEASON_MOIST = {"봄": 0.3, "여름": -1.0, "가을": -0.5, "겨울": 1.0}
|
|
# 월령을 받는 세기. 흙(戊己辰戌丑未)은 계절 따라 마른 흙·젖은 흙이 되므로 더 크게 받는다 (三夏己土 取癸為要, 六月土燥)
|
|
SEASON_PULL = {"earth": {"temp": 0.5, "moist": 0.8}, "other": {"temp": 0.3, "moist": 0.2}}
|
|
EARTH = set("戊己辰戌丑未")
|
|
# 축이 균형(±balanced 안)일 때 이름(따뜻/서늘, 촉촉/마름)을 정할 기울기: 가장 센 오행. 토와 목은 월령을 따른다
|
|
ELEMENT_LEAN = {"火": (1.0, -0.5), "金": (-0.5, -0.5), "水": (-0.7, 0.9)}
|
|
|
|
# 날씨 → 같은 두 축. 한난: 체감 15°C 가 0, 15°C 차이마다 ±1. 조습: 습도 55% 가 0, 35%p 차이마다 ±1, 비가 오면 최소 +0.8
|
|
WEATHER_SCALE = {"neutral_c": 15.0, "span_c": 15.0, "neutral_humidity": 55.0, "span_humidity": 35.0, "rain_moist": 0.8}
|
|
# 맞춤 점수 (초안)
|
|
MATCH = {
|
|
"pull": 0.3, # 날씨가 사주를 움직이는 정도 (날씨 1 이 사주 축을 0.3 옮긴다)
|
|
"balanced": 0.1, # 사주 축 값이 이보다 작으면 이미 균형
|
|
"mild": 0.3, # 날씨 축 값이 이보다 작으면 순한 날씨
|
|
"keep_gain": 0.3, # 균형인 축에서 순한 날씨면 +, 거센 날씨면 − 를 주는 세기
|
|
"axis_share": {"temp": 0.6, "moist": 0.4}, # 한난을 조습보다 먼저 본다
|
|
"scale": 120, # 효과 합을 점수로 바꾸는 배율 (50 ± scale × 효과)
|
|
"trim": 5, # 3시간 창 끝 시간이 나머지 평균보다 이만큼 낮으면 빼고 2시간으로
|
|
}
|
|
DAY_HOURS = range(6, 22) # 하루 점수·좋은 시간대를 볼 시각 (06~21시)
|
|
AXES = ("temp", "moist")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class HourWeather:
|
|
hour: int # 0~23
|
|
feels_c: float
|
|
humidity: float # %
|
|
raining: bool = False
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ChartClimate:
|
|
temp: float
|
|
moist: float
|
|
label: str # 따뜻·마름 / 따뜻·촉촉 / 서늘·마름 / 서늘·촉촉
|
|
season: str # 월지 계절
|
|
strength: Strength
|
|
need: dict[str, str] # {"temp": warm|cool|mild, "moist": dry|moist|mild}
|
|
parts: tuple[dict, ...] # 글자별 기여 {"position", "part", "char", "temp", "moist", "weight"} (월령 보정 뒤 값)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class HourMatch:
|
|
hour: int
|
|
score: int
|
|
weather: dict[str, float] # 날씨를 두 축으로 바꾼 값
|
|
effect: dict[str, float] # 축별 효과 (+ 균형 쪽, − 반대쪽)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ClimateMatch:
|
|
chart: ChartClimate
|
|
score: int # 50 이 보통
|
|
hours: tuple[HourMatch, ...]
|
|
best_hours: tuple[int, ...]
|
|
reasons: tuple[dict, ...] # 좋은 시간대의 축별 이유
|
|
|
|
|
|
def _clamp(x: float, lo: float = -1.0, hi: float = 1.0) -> float:
|
|
return max(lo, min(hi, x))
|
|
|
|
|
|
def season_of(branch: str) -> str:
|
|
return next(name for group, name in SEASONS.items() if branch in group)
|
|
|
|
|
|
def seasoned(char: str, month_branch: str) -> tuple[float, float]:
|
|
"""월령을 받은 글자의 (한난, 조습). 월지 자신은 계절 그 자체라 그대로 둔다."""
|
|
t, m = CHAR_CLIMATE[char]
|
|
pull = SEASON_PULL["earth" if char in EARTH else "other"]
|
|
t += pull["temp"] * MONTH_TEMP[month_branch]
|
|
m += pull["moist"] * SEASON_MOIST[season_of(month_branch)]
|
|
return round(_clamp(t), 3), round(_clamp(m), 3)
|
|
|
|
|
|
def _lean(strength: Strength, month_branch: str) -> tuple[float, float]:
|
|
return ELEMENT_LEAN.get(strength.top) or CHAR_CLIMATE[month_branch]
|
|
|
|
|
|
def chart_climate(chart: Chart) -> ChartClimate:
|
|
mb = chart.month.branch
|
|
parts = []
|
|
for pos, p in chart.pillars().items():
|
|
for part, char in (("stem", p.stem), ("branch", p.branch)):
|
|
t, m = CHAR_CLIMATE[char] if (pos, part) == ("month", "branch") else seasoned(char, mb)
|
|
parts.append({"position": pos, "part": part, "char": char, "temp": t, "moist": m, "weight": POSITION_POINTS[(pos, part)]})
|
|
total = sum(x["weight"] for x in parts)
|
|
temp = round(sum(x["temp"] * x["weight"] for x in parts) / total, 3)
|
|
moist = round(sum(x["moist"] * x["weight"] for x in parts) / total, 3)
|
|
b = MATCH["balanced"]
|
|
need = {
|
|
"temp": "warm" if temp < -b else "cool" if temp > b else "mild",
|
|
"moist": "dry" if moist > b else "moist" if moist < -b else "mild",
|
|
}
|
|
strength = chart_strength(chart)
|
|
lean_t, lean_m = _lean(strength, mb)
|
|
warm = temp > 0 if abs(temp) > b else lean_t >= 0
|
|
wet = moist > 0 if abs(moist) > b else lean_m >= 0
|
|
label = f"{'따뜻' if warm else '서늘'}·{'촉촉' if wet else '마름'}"
|
|
return ChartClimate(temp, moist, label, season_of(mb), strength, need, tuple(parts))
|
|
|
|
|
|
def weather_vector(w: HourWeather) -> dict[str, float]:
|
|
s = WEATHER_SCALE
|
|
temp = _clamp((w.feels_c - s["neutral_c"]) / s["span_c"])
|
|
moist = _clamp((w.humidity - s["neutral_humidity"]) / s["span_humidity"])
|
|
if w.raining:
|
|
moist = max(moist, s["rain_moist"])
|
|
return {"temp": round(temp, 3), "moist": round(moist, 3)}
|
|
|
|
|
|
def axis_effect(chart_value: float, weather_value: float) -> float:
|
|
"""균형(0)에 얼마나 가까워지는지. 이미 균형인 축은 순한 날씨를 반긴다."""
|
|
moved = abs(chart_value) - abs(chart_value + MATCH["pull"] * weather_value)
|
|
calm = max(0.0, 1 - abs(chart_value) / MATCH["balanced"])
|
|
keep = MATCH["keep_gain"] * calm * (MATCH["mild"] - abs(weather_value))
|
|
return moved + keep
|
|
|
|
|
|
def _hour_score(effect: dict[str, float]) -> float:
|
|
total = sum(MATCH["axis_share"][a] * effect[a] for a in AXES)
|
|
return _clamp(50 + MATCH["scale"] * total, 0, 100)
|
|
|
|
|
|
def best_window(scores: dict[int, float]) -> tuple[int, ...]:
|
|
"""06~21시 중 평균 점수가 가장 높은 연속 3시간(같으면 이른 쪽). 끝 시간이 처지면 2시간으로 줄인다."""
|
|
for size in (3, 2, 1):
|
|
windows = [tuple(range(s, s + size)) for s in DAY_HOURS if all(h in scores and h in DAY_HOURS for h in range(s, s + size))]
|
|
if windows:
|
|
break
|
|
else:
|
|
return ()
|
|
best = max(windows, key=lambda hs: (sum(scores[h] for h in hs) / len(hs), -hs[0]))
|
|
if len(best) == 3:
|
|
first, mid, last = (scores[h] for h in best)
|
|
if first < (mid + last) / 2 - MATCH["trim"]:
|
|
best = best[1:]
|
|
elif last < (first + mid) / 2 - MATCH["trim"]:
|
|
best = best[:2]
|
|
return best
|
|
|
|
|
|
def _weather_text(rows: list[HourWeather]) -> str:
|
|
feels = sum(r.feels_c for r in rows) / len(rows)
|
|
humidity = sum(r.humidity for r in rows) / len(rows)
|
|
rain = ", 비" if any(r.raining for r in rows) else ""
|
|
return f"체감 {feels:.0f}°, 습도 {humidity:.0f}%{rain}"
|
|
|
|
|
|
def _reasons(climate: ChartClimate, rows: list[HourWeather], matches: list[HourMatch]) -> tuple[dict, ...]:
|
|
mild = MATCH["mild"]
|
|
words = {"temp": ("warms", "cools"), "moist": ("moistens", "dries")}
|
|
out = []
|
|
for axis in AXES:
|
|
w = sum(m.weather[axis] for m in matches) / len(matches)
|
|
effect = sum(m.effect[axis] for m in matches) / len(matches)
|
|
up, down = words[axis]
|
|
out.append({
|
|
"axis": axis,
|
|
"need": climate.need[axis],
|
|
"effect": up if w > mild else down if w < -mild else "mild",
|
|
"helps": effect > 0,
|
|
"points": round(MATCH["scale"] * MATCH["axis_share"][axis] * effect, 1),
|
|
"weather": _weather_text(rows),
|
|
})
|
|
return tuple(out)
|
|
|
|
|
|
def climate_match(chart: Chart, weather: Iterable[HourWeather]) -> ClimateMatch:
|
|
"""시간별 날씨가 사주를 균형 쪽으로 옮기는지. 점수 50 이 보통, 높을수록 잘 맞는다."""
|
|
climate = chart_climate(chart)
|
|
rows = sorted(weather, key=lambda w: w.hour)
|
|
if not rows:
|
|
raise ValueError("시간별 날씨가 없습니다")
|
|
raw: dict[int, float] = {}
|
|
matches = []
|
|
for w in rows:
|
|
if not 0 <= w.hour <= 23 or w.hour in raw:
|
|
raise ValueError(f"시각은 0~23 에서 한 번씩: {w.hour}")
|
|
vec = weather_vector(w)
|
|
effect = {"temp": axis_effect(climate.temp, vec["temp"]), "moist": axis_effect(climate.moist, vec["moist"])}
|
|
raw[w.hour] = _hour_score(effect)
|
|
matches.append(HourMatch(w.hour, round(raw[w.hour]), vec, {a: round(v, 3) for a, v in effect.items()}))
|
|
day = [raw[h] for h in raw if h in DAY_HOURS] or list(raw.values())
|
|
best = best_window(raw)
|
|
picked = [m for m in matches if m.hour in best]
|
|
reasons = _reasons(climate, [w for w in rows if w.hour in best], picked) if best else ()
|
|
return ClimateMatch(climate, round(sum(day) / len(day)), tuple(matches), best, reasons)
|