291 lines
17 KiB
Python
291 lines
17 KiB
Python
from datetime import date, datetime, time, timedelta
|
||
|
||
import pytest
|
||
|
||
from common.utils.kma_time import KST
|
||
from services.saju.birth import to_solar_time
|
||
from services.saju.climate import HourWeather, axis_effect, chart_climate, climate_match, seasoned
|
||
from services.saju.daily import SCORE_WEIGHTS, daily_facts
|
||
from services.saju.pillars import day_pillar, make_chart
|
||
from services.saju.rules import (
|
||
branch_relations, branch_ten_god, chart_ten_gods, dohwa_of, hongyeom_of, stem_relations, ten_god, triple_relations,
|
||
)
|
||
from services.saju.solar_terms import JEOL, jeol_of_year, nutation_longitude, sun_apparent_longitude
|
||
from services.saju.strength import chart_strength
|
||
|
||
EXAMPLE = make_chart(date(1995, 3, 14))
|
||
|
||
# 한국천문연구원(KASI) 발표 절입 시각 (KST, 월일시분). 순서: 소한 입춘 경칩 청명 입하 망종 소서 입추 백로 한로 입동 대설
|
||
# - 2000~2028: KASI 특일 정보 API 24절기 조회(get24DivisionsInfo, kst 필드)
|
||
# https://www.data.go.kr/data/15012690/openapi.do · http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/get24DivisionsInfo
|
||
# - 2023·2024 는 KASI 역서 '24기와 기타 명절과 잡절' 표와도 같다
|
||
# https://astro.kasi.re.kr/file/astro_almanac_pdf/20221209095149975.pdf (2023 역서 8쪽)
|
||
# https://astro.kasi.re.kr/file/astro_almanac_pdf/20231023135218580.pdf (2024 역서 8쪽)
|
||
# 2011 입동은 API 가 11-08 09:26 을 주지만 계산값 03:35 와 약 6시간 어긋나고 민간 만세력도 03:35 라 API 자료 오류로 보고 뺀다 (--------)
|
||
KASI_JEOL = {
|
||
2000: "01061001 02042140 03051543 04042032 05051350 06051759 07070414 08071403 09071659 10080838 11071148 12070437",
|
||
2001: "01051549 02040329 03052133 04050224 05051945 06052354 07071007 08071952 09072246 10081425 11071737 12071029",
|
||
2002: "01052144 02040924 03060328 04050818 05060137 06060545 07071556 08080139 09080431 10082009 11072322 12071614",
|
||
2003: "01060328 02041505 03060905 04051352 05060710 06061120 07072136 08080724 09081020 10090201 11080513 12072205",
|
||
2004: "01060919 02042056 03051456 04041943 05051302 06051714 07070331 08071320 09071613 10080749 11071059 12070349",
|
||
2005: "01051503 02040243 03052045 04050134 05051853 06052302 07070917 08071903 09072157 10081333 11071642 12070933",
|
||
2006: "01052047 02040827 03060229 04050715 05060031 06060437 07071451 08080041 09080339 10081921 11072235 12071527",
|
||
2007: "01060240 02041418 03060818 04051305 05060620 06061027 07072042 08080631 09080929 10090111 11080424 12072114",
|
||
2008: "01060825 02042000 03051359 04041846 05051203 06051612 07070227 08071216 09071514 10080657 11071010 12070302",
|
||
2009: "01051414 02040150 03051947 04050034 05051751 06052159 07070813 08071801 09072058 10081240 11071556 12070852",
|
||
2010: "01052009 02040748 03060146 04050630 05052344 06060349 07071402 08072349 09080245 10081826 11072142 12071438",
|
||
2011: "01060155 02041333 03060730 04051212 05060523 06060927 07071942 08080533 09080834 10090019 -------- 12072029",
|
||
2012: "01060744 02041922 03051321 04041805 05051120 06051526 07070141 08071130 09071429 10080612 11070926 12070219",
|
||
2013: "01051334 02040113 03051915 04050002 05051718 06052123 07070734 08071720 09072016 10081158 11071514 12070808",
|
||
2014: "01051924 02040703 03060102 04050547 05052259 06060303 07071315 08072302 09080201 10081747 11072107 12071404",
|
||
2015: "01060120 02041258 03060656 04051139 05060452 06060858 07071912 08080501 09080759 10082343 11080258 12071953",
|
||
2016: "01060708 02041846 03051243 04041727 05051042 06051448 07070103 08071053 09071351 10080533 11070848 12070141",
|
||
2017: "01051256 02040034 03051833 04042317 05051631 06052037 07070651 08071640 09071939 10081122 11071438 12070733",
|
||
2018: "01051849 02040628 03060028 04050513 05052225 06060229 07071242 08072231 09080130 10081715 11072032 12071326",
|
||
2019: "01060039 02041214 03060610 04051051 05060403 06060806 07071821 08080413 09080717 10082306 11080224 12071918",
|
||
2020: "01060630 02041803 03051157 04041638 05050951 06051358 07070014 08071006 09071308 10080455 11070814 12070109",
|
||
2021: "01051223 02032359 03051754 04042235 05051547 06051952 07070605 08071554 09071853 10081039 11071359 12070657",
|
||
2022: "01051814 02040551 03052344 04050420 05052126 06060126 07071138 08072129 09080032 10081622 11071945 12071246",
|
||
2023: "01060005 02041143 03060536 04051013 05060319 06060718 07071731 08080323 09080627 10082216 11080136 12071833",
|
||
2024: "01060549 02041727 03051123 04041602 05050910 06051310 07062320 08070909 09071211 10080400 11070720 12070017",
|
||
2025: "01051133 02032310 03051707 04042149 05051457 06051857 07070505 08071452 09071752 10080941 11071304 12070605",
|
||
2026: "01051723 02040502 03052259 04050340 05052049 06060048 07071057 08072043 09072341 10081529 11071852 12071153",
|
||
2027: "01052310 02041046 03060440 04050917 05060225 06060626 07071637 08080227 09080528 10082117 11080039 12071738",
|
||
2028: "01060455 02041631 03051025 04041503 05050812 06051216 07062230 08070821 09071122 10080309 11070627 12062325",
|
||
}
|
||
|
||
|
||
def test_sun_longitude_and_nutation_match_meeus_examples():
|
||
# Meeus 예제 25.b (1992-10-13 0h TD): 시황경 199°54′21.818″, 예제 22.a·25.b 의 Δψ
|
||
assert sun_apparent_longitude(2448908.5) == pytest.approx(199 + 54 / 60 + 21.818 / 3600, abs=0.5 / 3600)
|
||
assert nutation_longitude(2446895.5) == pytest.approx(-3.788, abs=0.05)
|
||
assert nutation_longitude(2448908.5) == pytest.approx(15.908, abs=0.05)
|
||
|
||
|
||
def test_jeol_times_within_a_minute_of_kasi():
|
||
worst = 0.0
|
||
for year, row in KASI_JEOL.items():
|
||
mine = jeol_of_year(year)
|
||
for j, token in zip(mine, row.split()):
|
||
if token.startswith("-"):
|
||
continue
|
||
kasi = datetime(year, int(token[:2]), int(token[2:4]), int(token[4:6]), int(token[6:]), tzinfo=KST)
|
||
worst = max(worst, abs((j.at - kasi).total_seconds()))
|
||
# KASI 는 분 단위로 발표하므로 반올림 오차 30초 + 계산 오차
|
||
assert worst < 60
|
||
|
||
|
||
def test_jeol_order_holds_for_whole_range():
|
||
names = [name for name, _, _ in JEOL]
|
||
prev = None
|
||
for year in range(1900, 2101):
|
||
terms = jeol_of_year(year)
|
||
assert [t.name for t in terms] == names
|
||
assert date(year, 2, 3) <= terms[1].at.date() <= date(year, 2, 5) # 입춘
|
||
for t in terms:
|
||
if prev:
|
||
assert timedelta(days=29) < t.at - prev < timedelta(days=32)
|
||
prev = t.at
|
||
|
||
|
||
def test_day_pillars():
|
||
assert day_pillar(date(1900, 1, 1)).name == "甲戌"
|
||
assert day_pillar(date(2000, 1, 1)).name == "戊午"
|
||
assert day_pillar(date(2024, 1, 1)).name == "甲子"
|
||
assert day_pillar(date(2026, 10, 28)).name == "乙亥"
|
||
assert day_pillar(date(2026, 10, 28)).ko == "을해"
|
||
|
||
|
||
def test_example_chart_without_birth_time():
|
||
c = EXAMPLE
|
||
assert (c.year.name, c.month.name, c.day.name) == ("乙亥", "己卯", "甲辰")
|
||
assert c.hour is None and not c.hour_known and c.solar is None
|
||
assert c.jeol.name == "경칩" and not c.jeol_on_birth_day
|
||
assert list(c.pillars()) == ["year", "month", "day"]
|
||
# 2000-01-01 은 소한·입춘 전이라 전해 己卯년 子월
|
||
c2000 = make_chart(date(2000, 1, 1))
|
||
assert (c2000.year.name, c2000.month.name, c2000.day.name) == ("己卯", "丙子", "戊午")
|
||
|
||
|
||
def test_ipchun_boundary_ten_minutes_each_side():
|
||
# 2024 입춘 02-04 17:27 KST (KASI). 시계 시각 기준으로 10분 전·후
|
||
before = make_chart(date(2024, 2, 4), time(17, 17))
|
||
after = make_chart(date(2024, 2, 4), time(17, 37))
|
||
assert (before.year.name, before.month.name) == ("癸卯", "乙丑")
|
||
assert (after.year.name, after.month.name) == ("甲辰", "丙寅")
|
||
# 2023 입춘 02-04 11:43
|
||
assert make_chart(date(2023, 2, 4), time(11, 33)).year.name == "壬寅"
|
||
assert make_chart(date(2023, 2, 4), time(11, 53)).year.name == "癸卯"
|
||
# 시간을 모르는 절입일은 표시
|
||
assert make_chart(date(2024, 2, 4)).jeol_on_birth_day
|
||
|
||
|
||
def test_hour_pillars_and_zi_rule():
|
||
# 서울은 지방평균시가 약 32분 늦다: 10:00 → 09:28 巳시, 甲일 巳시 = 己巳
|
||
c = make_chart(date(1995, 3, 14), time(10, 0))
|
||
assert round(c.solar.correction_min) == -32 and c.hour.name == "己巳"
|
||
assert make_chart(date(1995, 3, 14), time(13, 40)).hour.name == "辛未" # 13:08 未시
|
||
# 경도 135 (보정 0) 에서 23:30: 자정 기준이면 날은 그대로 甲辰, 시주는 다음 자시 丙子
|
||
late = make_chart(date(1995, 3, 14), time(23, 30), longitude=135)
|
||
assert (late.day.name, late.hour.name) == ("甲辰", "丙子")
|
||
# 23시 기준이면 날이 乙巳 로 넘어가고 시주는 같다
|
||
late23 = make_chart(date(1995, 3, 14), time(23, 30), longitude=135, zi_rule="23h")
|
||
assert (late23.day.name, late23.hour.name) == ("乙巳", "丙子")
|
||
# 서울 23:30 은 지방평균시 22:58 이라 아직 亥시
|
||
assert make_chart(date(1995, 3, 14), time(23, 30)).hour.name == "乙亥"
|
||
# 서울 00:10 은 지방평균시로 전날 23:38 → 전날 癸卯일, 시주 甲子
|
||
early = make_chart(date(1995, 3, 14), time(0, 10))
|
||
assert (early.day.name, early.hour.name) == ("癸卯", "甲子")
|
||
|
||
|
||
def test_dst_is_removed():
|
||
# 1988-05-08 02:00 ~ 10-09 03:00 서머타임. 시계 10:00 = 표준시 09:00 → 서울 지방평균시 08:28 辰시
|
||
s = to_solar_time(date(1988, 7, 1), time(10, 0))
|
||
assert s.dst and s.utc_offset_min == 600 and round(s.correction_min) == -92
|
||
assert make_chart(date(1988, 7, 1), time(10, 0)).hour.branch == "辰"
|
||
assert not to_solar_time(date(1988, 11, 1), time(10, 0)).dst
|
||
assert not to_solar_time(date(1987, 5, 10), time(1, 59)).dst and to_solar_time(date(1987, 5, 10), time(3, 0)).dst
|
||
# 1954-03-21 ~ 1961-08-09 표준시는 UTC+8:30, 그 위에 서머타임
|
||
s58 = to_solar_time(date(1958, 6, 15), time(12, 0))
|
||
assert s58.dst and s58.utc_offset_min == 570 and round(s58.correction_min) == -62
|
||
assert to_solar_time(date(1958, 12, 1), time(12, 0)).utc_offset_min == 510
|
||
|
||
|
||
def test_out_of_range_dates_are_rejected():
|
||
with pytest.raises(ValueError):
|
||
make_chart(date(1899, 12, 31))
|
||
with pytest.raises(ValueError):
|
||
make_chart(date(2101, 1, 1))
|
||
|
||
|
||
def test_ten_gods():
|
||
expected = {"甲": "비견", "乙": "겁재", "丙": "식신", "丁": "상관", "戊": "편재", "己": "정재", "庚": "편관", "辛": "정관", "壬": "편인", "癸": "정인"}
|
||
assert {s: ten_god("甲", s) for s in expected} == expected
|
||
assert branch_ten_god("甲", "亥") == "편인" # 정기 壬
|
||
assert branch_ten_god("甲", "子") == "정인" # 정기 癸
|
||
assert chart_ten_gods("甲", EXAMPLE.pillars())["month"] == {"stem": "정재", "branch": "겁재"}
|
||
|
||
|
||
def _kinds(rels):
|
||
return {r.kind for r in rels}
|
||
|
||
|
||
def test_stem_and_branch_relations():
|
||
assert stem_relations("甲", "己")[0].element == "土"
|
||
assert _kinds(stem_relations("庚", "甲")) == {"천간충"}
|
||
assert _kinds(stem_relations("甲", "乙")) == set()
|
||
assert branch_relations("子", "丑")[0].kind == "육합"
|
||
assert _kinds(branch_relations("亥", "卯")) == {"반합"}
|
||
assert _kinds(branch_relations("卯", "未")) == {"반합"}
|
||
assert _kinds(branch_relations("亥", "未")) == set() # 생지+묘지는 반합으로 보지 않음
|
||
assert _kinds(branch_relations("午", "子")) == {"충"}
|
||
assert _kinds(branch_relations("寅", "巳")) == {"형", "해"}
|
||
assert _kinds(branch_relations("巳", "申")) == {"육합", "형", "파"}
|
||
assert branch_relations("子", "卯")[0].group == "子卯"
|
||
assert _kinds(branch_relations("午", "午")) == {"자형"}
|
||
assert _kinds(branch_relations("子", "子")) == set()
|
||
assert _kinds(branch_relations("子", "未")) == {"해", "원진"}
|
||
assert _kinds(branch_relations("辰", "亥")) == {"원진"}
|
||
assert _kinds(branch_relations("子", "酉")) == {"파"}
|
||
assert _kinds(triple_relations(["申", "子", "辰"])) == {"삼합"}
|
||
assert _kinds(triple_relations(["丑", "戌", "未"])) == {"삼형"}
|
||
|
||
|
||
def test_dohwa_and_hongyeom_tables():
|
||
assert dohwa_of("亥") == "子" and dohwa_of("辰") == "酉" and dohwa_of("午") == "卯" and dohwa_of("丑") == "午"
|
||
assert hongyeom_of("甲") == hongyeom_of("乙") == "午"
|
||
assert hongyeom_of("丁") == "未" and hongyeom_of("癸") == "申"
|
||
|
||
|
||
def test_daily_facts_for_example_chart():
|
||
f = daily_facts(EXAMPLE, date(2026, 10, 28))
|
||
assert f.pillar.name == "乙亥"
|
||
assert f.stem_ten_god == "겁재"
|
||
assert f.branch_main_stem == "壬" and f.branch_ten_god == "편인"
|
||
found = {(i.position, i.relation.kind, i.relation.chars) for i in f.interactions}
|
||
assert found == {("month", "반합", "亥卯"), ("day", "원진", "亥辰"), ("year", "자형", "亥亥")}
|
||
assert {i.palace for i in f.interactions} == {"부모·직장", "나·배우자", "조상·사회"}
|
||
assert f.dohwa == () and not f.hongyeom
|
||
# 성별을 모르면 일지 관계만 연애 사실로
|
||
assert f.love.relevant and f.love.reasons == ({"kind": "일지", "relation": "원진", "chars": "亥辰"},)
|
||
assert f.score == round(SCORE_WEIGHTS["base"] + sum(c.points for c in f.contributions))
|
||
assert {c.fact for c in f.contributions} == {"겁재", "편인", "반합", "원진", "자형"}
|
||
|
||
|
||
def test_daily_dohwa_hongyeom_and_love_by_gender():
|
||
dohwa_day = daily_facts(EXAMPLE, date(2026, 10, 29)) # 丙子: 연지 亥 의 도화
|
||
assert dohwa_day.pillar.name == "丙子" and dohwa_day.dohwa == ({"basis": "year", "branch": "子"},)
|
||
assert any(c.fact == "도화" for c in dohwa_day.contributions)
|
||
hongyeom_day = daily_facts(EXAMPLE, date(2026, 11, 4)) # 壬午: 甲 일간의 홍염
|
||
assert hongyeom_day.pillar.name == "壬午" and hongyeom_day.hongyeom
|
||
wealth_day = date(2026, 10, 31) # 戊寅: 甲 에게 편재
|
||
assert daily_facts(EXAMPLE, wealth_day).pillar.name == "戊寅"
|
||
male = daily_facts(EXAMPLE, wealth_day, gender="male").love
|
||
assert male.relevant and male.reasons[0] == {"kind": "재성", "part": "stem", "ten_god": "편재"}
|
||
assert not daily_facts(EXAMPLE, wealth_day, gender="female").love.relevant
|
||
assert not daily_facts(EXAMPLE, wealth_day).love.relevant
|
||
officer = daily_facts(EXAMPLE, date(2026, 11, 2), gender="female") # 庚辰: 편관, 일지 辰辰
|
||
assert officer.pillar.name == "庚辰" and {"kind": "관성", "part": "stem", "ten_god": "편관"} in officer.love.reasons
|
||
|
||
|
||
def test_daily_samhap_completed_by_today():
|
||
# 원국 庚申 甲申 丙辰 에 오늘 丙子 가 오면 申子辰 삼합. 같은 묶음 반합은 사실로는 남기고 점수에서는 겹쳐 세지 않는다
|
||
c = make_chart(date(1980, 8, 11))
|
||
assert (c.year.name, c.month.name, c.day.name) == ("庚申", "甲申", "丙辰")
|
||
f = daily_facts(c, date(2026, 10, 29))
|
||
samhap = [i for i in f.interactions if i.relation.kind == "삼합"]
|
||
assert len(samhap) == 1 and samhap[0].relation.group == "申子辰" and samhap[0].positions == ("year", "month", "day")
|
||
assert sum(i.relation.kind == "반합" for i in f.interactions) == 3
|
||
assert [c.fact for c in f.contributions] == ["비견", "정관", "삼합"]
|
||
|
||
|
||
def test_example_chart_climate_and_best_window():
|
||
climate = chart_climate(EXAMPLE)
|
||
assert climate.label == "서늘·촉촉" and climate.season == "봄"
|
||
assert climate.need == {"temp": "warm", "moist": "dry"}
|
||
feels = [0, 0, -1, -1, 0, 1, 2, 3, 5, 7, 9, 11, 12, 13, 13, 13, 11, 9, 7, 5, 4, 3, 2, 1]
|
||
weather = [HourWeather(h, feels[h], 45 if h < 13 else 40 if h <= 15 else 50, False) for h in range(24)]
|
||
m = climate_match(EXAMPLE, weather)
|
||
assert m.best_hours == (13, 14, 15)
|
||
scores = {h.hour: h.score for h in m.hours}
|
||
assert scores[14] > scores[6]
|
||
assert 0 <= m.score <= 100
|
||
temp, moist = m.reasons
|
||
assert temp["axis"] == "temp" and temp["need"] == "warm"
|
||
assert moist == {"axis": "moist", "need": "dry", "effect": "dries", "helps": True, "points": moist["points"], "weather": "체감 13°, 습도 40%"}
|
||
|
||
|
||
|
||
def test_example_strength_counts_hidden_stems_and_month_branch():
|
||
s = chart_strength(EXAMPLE) # 乙亥 己卯 甲辰
|
||
assert s.elements == {"木": 58.3, "火": 0.0, "土": 24.3, "金": 0.0, "水": 7.3}
|
||
assert s.top == "木" and s.strong and s.support == 0.696
|
||
|
||
|
||
def test_summer_earth_chart_reads_hot_and_dry_not_rainy():
|
||
chart = make_chart(date(1959, 7, 16)) # 己亥 辛未 己亥: 未월 토가 많고 물이 둘
|
||
climate = chart_climate(chart)
|
||
assert climate.season == "여름" and climate.label == "따뜻·마름" and climate.need["temp"] == "cool"
|
||
assert climate.strength.top == "土" and climate.strength.strong
|
||
|
||
|
||
def test_month_rooted_day_master_stays_strong_whatever_the_hour():
|
||
# 未월 己土는 득령(월령 土) — 시주가 물·쇠라도 신강, 득령 없는 같은 몫이면 낮게
|
||
for h in range(0, 24, 2):
|
||
s = chart_strength(make_chart(date(1959, 7, 16), time(h, 30)))
|
||
assert s.deuk_ryeong and s.label == "신강", (h, s)
|
||
winter = chart_strength(make_chart(date(1959, 12, 20))) # 子월 — 己土 득령 아님
|
||
assert not winter.deuk_ryeong
|
||
|
||
|
||
def test_month_dries_summer_earth_and_soaks_winter_earth():
|
||
assert seasoned("己", "未")[1] < 0 < seasoned("己", "子")[1]
|
||
assert seasoned("壬", "未")[0] > seasoned("壬", "子")[0]
|
||
|
||
def test_balanced_axis_prefers_mild_weather_and_rain_moistens():
|
||
assert axis_effect(0.0, 0.0) > axis_effect(0.0, 0.6) and axis_effect(0.0, 0.0) > axis_effect(0.0, -0.6)
|
||
assert axis_effect(-0.4, 0.8) > axis_effect(-0.4, 0.0) > axis_effect(-0.4, -0.8)
|
||
dry = climate_match(EXAMPLE, [HourWeather(12, 18, 40, False)])
|
||
wet = climate_match(EXAMPLE, [HourWeather(12, 18, 40, True)])
|
||
assert wet.hours[0].weather["moist"] >= 0.8 and wet.score < dry.score
|