feat(timeline): one boundary rule, full instants and continuity checks for every period table
Astrologer third-round review 2026-11-07, item 3. timeline_boundaries checks end == next start on full timestamps (start inclusive, end exclusive) and lists every gap or overlap. The solar-return report and annual pack expose the real return interval (this return to the next actual return, computed), the Mudda 365.25-day year and the shown window separately. The annual package checks the year chain, each year's Mudda, Patyayini, monthly and Varsha Narayana rows, natal Vimshottari / Narayana, and Mudda across years (a ~8-minute hole the fixed year leaves before the next return). Consultation dasha rows gain start_at / end_at with the birth offset and a per-system continuity check; the card carries continuity_issue only when a table is not continuous. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
This commit is contained in:
@@ -1282,6 +1282,8 @@ const DASHA_ROW_KEYS = [
|
||||
"date_basis", "cycle_end", "md", "ad", "pd",
|
||||
// 产品 2026-11-07: the next Narayana AD; where a ported upstream row came from and its status.
|
||||
"next_ad", "source", "status_note",
|
||||
// 占星师第三轮审查 2026-11-07: a gap / overlap between consecutive periods (absent when continuous).
|
||||
"continuity_issue",
|
||||
] as const;
|
||||
|
||||
function baseExtras(context: unknown, base: EvidenceCard["base"], gaps: string[]) {
|
||||
@@ -1309,7 +1311,12 @@ function baseExtras(context: unknown, base: EvidenceCard["base"], gaps: string[]
|
||||
table[row.system] = pickKeys(row, DASHA_ROW_KEYS);
|
||||
}
|
||||
const houseRule = copy(dashas.house_rule);
|
||||
base.timing.dasha_systems = { ...(houseRule !== undefined ? { house_rule: houseRule } : {}), systems: table };
|
||||
// 占星师第三轮审查 2026-11-07: one boundary rule and the time basis of start_at / end_at.
|
||||
base.timing.dasha_systems = {
|
||||
...(houseRule !== undefined ? { house_rule: houseRule } : {}),
|
||||
...pickKeys(dashas, ["boundary_rule", "time_basis"]),
|
||||
systems: table,
|
||||
};
|
||||
} else {
|
||||
gaps.push("base.dasha_systems");
|
||||
}
|
||||
|
||||
@@ -48,6 +48,11 @@ from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
try: # scripts/ on sys.path (API and tests)
|
||||
import timeline_boundaries as tb
|
||||
except ImportError: # pragma: no cover - package import
|
||||
from scripts import timeline_boundaries as tb
|
||||
|
||||
SCHEMA = "jyotish.annual_package.v1"
|
||||
ANNUAL_PACKAGE_VERSION = 1
|
||||
RANGE_KINDS = ("birthday_year", "calendar_year", "next_12_months")
|
||||
@@ -535,6 +540,17 @@ def build_annual_package(request: dict[str, Any], *, detail: str = "full") -> di
|
||||
"computation_boundaries": _boundaries(ctx),
|
||||
"not_included": NOT_INCLUDED,
|
||||
}
|
||||
# 占星师第三轮审查 2026-11-07:统一起点含、终点不含;逐段核对 end == 下一段 start。
|
||||
package["timeline_continuity"] = {
|
||||
"rule": tb.BOUNDARY_RULE,
|
||||
"rule_text": tb.BOUNDARY_RULE_TEXT,
|
||||
"year_charts": _year_chain_continuity(year_charts),
|
||||
"mudda_across_years": _annual_dasha_across_years(year_charts, "mudda_dasha"),
|
||||
"patyayini_across_years": _annual_dasha_across_years(year_charts, "patyayini"),
|
||||
"natal_periods": _natal_continuity(_plain(natal_periods)),
|
||||
"per_year": {str(chart.get("target_year")): (chart.get("continuity") or {}).get("status")
|
||||
for chart in year_charts},
|
||||
}
|
||||
package = _plain(package)
|
||||
package["block_index"] = list(_walk_blocks(package, ""))
|
||||
package["blocked_count"] = sum(1 for row in package["block_index"] if row["status"] == "blocked")
|
||||
@@ -789,6 +805,9 @@ def _year_chart(ctx: _Context, year: int, range_start: datetime | None, range_en
|
||||
**block("computed", "annual_tajika_pack.build_annual_tajika_pack"),
|
||||
"validity": validity,
|
||||
"in_report_range": overlap,
|
||||
# 占星师第三轮审查 2026-11-07:真实返照区间、各年运大运的年长、展示窗口分开给。
|
||||
"interval": _year_interval(validity, blocks, overlap),
|
||||
"continuity": _year_continuity(validity, blocks),
|
||||
"return_location": {
|
||||
"mode": ctx.request["return_location"]["mode"],
|
||||
"latitude": location.get("latitude"),
|
||||
@@ -807,6 +826,124 @@ def _year_chart(ctx: _Context, year: int, range_start: datetime | None, range_en
|
||||
}
|
||||
|
||||
|
||||
def _year_interval(validity: dict, blocks: dict, overlap: dict | None) -> dict[str, Any]:
|
||||
"""This return → next actual return; each annual dasha's own year; the shown window."""
|
||||
next_return = validity["end"]
|
||||
dasha_years = []
|
||||
for system in ("mudda_dasha", "patyayini"):
|
||||
year = (blocks.get(system) or {}).get("year_length")
|
||||
if not isinstance(year, dict) or not isinstance(year.get("end"), dict):
|
||||
continue
|
||||
gap = round((float(year["end"]["jd_ut"]) - float(next_return["jd_ut"])) * 86400.0, 1)
|
||||
dasha_years.append({"system": system, "days": year.get("days"), "basis": year.get("basis"),
|
||||
"start": year.get("start"), "end": year["end"],
|
||||
"end_minus_next_return_seconds": gap})
|
||||
return {
|
||||
"rule": tb.BOUNDARY_RULE,
|
||||
"solar_return_interval": {"start": validity["start"], "end": next_return,
|
||||
"duration_days": validity.get("duration_days"), "end_source": "next_solar_return"},
|
||||
"dasha_years": dasha_years,
|
||||
"displayed_window": overlap,
|
||||
"note": "the dasha years keep their own length and are cut, never stretched, at their own end; "
|
||||
"the year chart is valid to the next actual solar return",
|
||||
}
|
||||
|
||||
|
||||
def _runs(rows: list[dict], key: str) -> list[list[dict]]:
|
||||
"""Consecutive runs of rows sharing ``row[key]`` (a sign can recur in a later cycle)."""
|
||||
runs: list[list[dict]] = []
|
||||
for row in rows:
|
||||
if runs and runs[-1][0].get(key) == row.get(key):
|
||||
runs[-1].append(row)
|
||||
else:
|
||||
runs.append([row])
|
||||
return runs
|
||||
|
||||
|
||||
def _year_continuity(validity: dict, blocks: dict) -> dict[str, Any]:
|
||||
checks = []
|
||||
|
||||
def rows_of(name: str, key: str = "periods") -> list[dict]:
|
||||
value = (blocks.get(name) or {}).get(key)
|
||||
return [row for row in value or [] if isinstance(row, dict)]
|
||||
|
||||
for name in ("mudda_dasha", "patyayini"):
|
||||
year = (blocks.get(name) or {}).get("year_length") or {}
|
||||
periods = rows_of(name)
|
||||
if periods:
|
||||
checks.append(tb.check_continuity(periods, label=f"{name}.periods",
|
||||
expected_start=year.get("start"), expected_end=year.get("end")))
|
||||
main_key = "main_order"
|
||||
for run in _runs(rows_of(name, "antardasha_periods"), main_key):
|
||||
checks.append(tb.check_continuity(run, label=f"{name}.antardasha_periods[{main_key}={run[0].get(main_key)}]"))
|
||||
months = [row for row in rows_of("monthly_charts", "rows") if row.get("status") == "computed"]
|
||||
if months:
|
||||
checks.append(tb.check_continuity(months, label="monthly_charts.rows",
|
||||
expected_start=validity["start"], expected_end=validity["end"]))
|
||||
for index, md in enumerate(rows_of("varsha_narayana")):
|
||||
if index == 0:
|
||||
checks.append(tb.check_continuity(rows_of("varsha_narayana"), label="varsha_narayana.periods"))
|
||||
ads = [row for row in md.get("antardashas") or [] if isinstance(row, dict)]
|
||||
if ads:
|
||||
checks.append(tb.check_continuity(ads, label=f"varsha_narayana.periods[{index}].antardashas",
|
||||
expected_start=md.get("start"), expected_end=md.get("end")))
|
||||
return {**tb.summarize(checks), "checks": checks}
|
||||
|
||||
|
||||
def _natal_continuity(natal_periods: dict) -> dict[str, Any]:
|
||||
"""Vimshottari MD / AD / PD and Narayana MD / AD rows inside the report range."""
|
||||
checks = []
|
||||
vim = [row for row in (natal_periods.get("vimshottari") or {}).get("rows") or [] if isinstance(row, dict)]
|
||||
if vim:
|
||||
checks.append(tb.check_continuity([r for r in vim if r.get("level") == "MD"], label="vimshottari.MD"))
|
||||
# Rows are nested in order (MD, its ADs, each AD's PDs), so a new MD
|
||||
# opens a new AD group and a new AD a new PD group.
|
||||
ads: list[list[dict]] = [[]]
|
||||
pds: list[list[dict]] = [[]]
|
||||
for row in vim:
|
||||
if row.get("level") == "MD":
|
||||
ads.append([])
|
||||
elif row.get("level") == "AD":
|
||||
ads[-1].append(row)
|
||||
pds.append([])
|
||||
elif row.get("level") == "PD":
|
||||
pds[-1].append(row)
|
||||
for index, run in enumerate(group for group in ads if group):
|
||||
checks.append(tb.check_continuity(run, label=f"vimshottari.AD[md#{index}]"))
|
||||
for index, run in enumerate(group for group in pds if group):
|
||||
checks.append(tb.check_continuity(run, label=f"vimshottari.PD[ad#{index}]"))
|
||||
for profile in ("rath", "legacy"):
|
||||
rows = [row for row in ((natal_periods.get("narayana") or {}).get(profile) or {}).get("rows") or []
|
||||
if isinstance(row, dict)]
|
||||
if not rows:
|
||||
continue
|
||||
checks.append(tb.check_continuity([r for r in rows if r.get("level") == "MD"], label=f"narayana.{profile}.MD"))
|
||||
for run in _runs([r for r in rows if r.get("level") == "AD"], "parent_md"):
|
||||
checks.append(tb.check_continuity(run, label=f"narayana.{profile}.AD[{run[0].get('parent_md')}]"))
|
||||
return {**tb.summarize(checks), "checks": checks}
|
||||
|
||||
|
||||
def _year_chain_continuity(year_charts: list[dict]) -> dict[str, Any]:
|
||||
rows = [{"start": chart["validity"]["start"], "end": chart["validity"]["end"]}
|
||||
for chart in year_charts if isinstance(chart.get("validity"), dict)]
|
||||
return tb.check_continuity(rows, label="year_charts.validity")
|
||||
|
||||
|
||||
def _annual_dasha_across_years(year_charts: list[dict], system: str) -> dict[str, Any]:
|
||||
"""One annual dasha's year windows end to end across the year charts.
|
||||
|
||||
Each year's Mudda / Patyayini keeps its own 365.25-day year from its solar
|
||||
return; the next year starts at the next actual return, so a few minutes
|
||||
between them belong to no period. That hole is reported, not hidden.
|
||||
"""
|
||||
rows = []
|
||||
for chart in year_charts:
|
||||
year = (((chart.get("blocks") or {}).get(system) or {}).get("year_length")) if isinstance(chart, dict) else None
|
||||
if isinstance(year, dict) and year.get("start") and year.get("end"):
|
||||
rows.append({"start": year["start"], "end": year["end"]})
|
||||
return tb.check_continuity(rows, label=f"{system}.year_windows_across_years")
|
||||
|
||||
|
||||
def _chart_block(report: dict, houses: dict, sr: dict) -> dict[str, Any]:
|
||||
chart = report.get("sr_chart") if isinstance(report.get("sr_chart"), dict) else None
|
||||
if not chart or houses.get("status") == "blocked":
|
||||
@@ -1618,6 +1755,7 @@ def _boundaries(ctx: _Context) -> dict[str, Any]:
|
||||
"instant_format": "every boundary has utc, local (ISO with offset), utc_offset, timezone_id and jd_ut",
|
||||
"local_zone": "return location zone (the birth place by default, the current city when given); IANA zone when timezone_id is given, else the fixed birth offset",
|
||||
"year_chart_validity": "this solar return (inclusive) to the next solar return (exclusive)",
|
||||
"boundary_rule": "every period table: start inclusive, end exclusive; timeline_continuity checks end == next start",
|
||||
"clipping": "period rows keep their native bounds; in_report_range is the part inside the report range; nothing is stretched",
|
||||
"period_year_lengths": [
|
||||
{"system": "mudda_dasha", "days": 365.25, "anchor": "solar return instant"},
|
||||
|
||||
@@ -1344,6 +1344,10 @@ def _year_overview(chart: dict) -> dict[str, Any]:
|
||||
return {
|
||||
"target_year": chart["target_year"],
|
||||
"validity": chart["validity"],
|
||||
# 占星师第三轮审查 2026-11-07:真实返照区间 / 年运大运年长 / 展示窗口分开;本年各表连续性。
|
||||
"interval": chart.get("interval"),
|
||||
"continuity_status": (chart.get("continuity") or {}).get("status"),
|
||||
"continuity_problems": (chart.get("continuity") or {}).get("tables_not_continuous") or [],
|
||||
"in_report_range": chart.get("in_report_range"),
|
||||
"ascendant": asc_sign,
|
||||
"ascendant_lord": chart_block.get("ascendant_lord"),
|
||||
@@ -1373,6 +1377,23 @@ def _year_overview(chart: dict) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _timeline_summary(continuity: Any) -> dict[str, Any] | None:
|
||||
"""Rule plus every gap / overlap the package found, without the passing checks."""
|
||||
if not isinstance(continuity, dict):
|
||||
return None
|
||||
problems = []
|
||||
for key in ("year_charts", "mudda_across_years", "patyayini_across_years"):
|
||||
check = continuity.get(key)
|
||||
if isinstance(check, dict) and check.get("status") not in (None, "continuous"):
|
||||
problems.append({key: {k: check.get(k) for k in ("status", "gaps", "overlaps", "reason") if check.get(k)}})
|
||||
natal = continuity.get("natal_periods") or {}
|
||||
for check in natal.get("checks") or []:
|
||||
if isinstance(check, dict) and check.get("status") != "continuous":
|
||||
problems.append({check.get("table"): {k: check.get(k) for k in ("status", "gaps", "overlaps", "reason") if check.get(k)}})
|
||||
return {"rule": continuity.get("rule"), "rule_text": continuity.get("rule_text"),
|
||||
"per_year": continuity.get("per_year"), "problems": problems}
|
||||
|
||||
|
||||
def _harsha_completeness(rows: dict) -> dict[str, Any]:
|
||||
"""Harsha rows whose day/night component is unknown: total withheld, known part kept."""
|
||||
known = {planet: (row or {}).get("known_score") for planet, row in rows.items()
|
||||
@@ -1615,4 +1636,6 @@ def build_annual_report_facts(request: dict[str, Any], *, birth_window: Any = No
|
||||
"natal_base": public_natal,
|
||||
"cards": cards,
|
||||
"technique_audit": audit,
|
||||
# 占星师第三轮审查 2026-11-07:起点含、终点不含;跨年 / 跨表的断口与重叠。
|
||||
"timeline_continuity": _timeline_summary(package.get("timeline_continuity")),
|
||||
})
|
||||
|
||||
@@ -97,6 +97,8 @@ def build_annual_tajika_pack(
|
||||
# Mudda 三种余额口径(默认仍是出生月亮口径,BUG-1216)。
|
||||
"annual_special_points": _annual_special_points(payload, solar_return, annual_chart),
|
||||
"mudda_profiles": _mudda_profiles(solar_return, annual_chart, year_lord, mudda_dasha),
|
||||
# 占星师第三轮审查 2026-11-07:真实返照区间 / Mudda 年长 / 展示窗口分开,带连续性检查。
|
||||
"annual_interval": solar_report.get("annual_interval") if isinstance(solar_report, dict) else None,
|
||||
}
|
||||
pack["exports"] = _exports(pack)
|
||||
return pack
|
||||
|
||||
@@ -1325,6 +1325,55 @@ def _iso(value: Any) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _stamp(value: Any, tz: timezone | None) -> str | None:
|
||||
"""Full timestamp with its UTC offset, when the producer has a time of day.
|
||||
|
||||
占星师第三轮审查 2026-11-07: the card's `start` / `end` stay dates for
|
||||
display; `start_at` / `end_at` carry the producer's full instant. Naive
|
||||
producer values are the birth local clock and get the birth UTC offset.
|
||||
"""
|
||||
if isinstance(value, datetime):
|
||||
moment = value
|
||||
elif isinstance(value, str) and len(value.strip()) > 10:
|
||||
try:
|
||||
moment = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
if moment.tzinfo is None and tz is not None:
|
||||
moment = moment.replace(tzinfo=tz)
|
||||
return moment.isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _birth_zone(birth_payload: dict) -> timezone:
|
||||
return timezone(timedelta(hours=float(birth_payload.get("tz") or 0)))
|
||||
|
||||
|
||||
def _fmt_tz(zone: timezone) -> str:
|
||||
offset = zone.utcoffset(None) or timedelta(0)
|
||||
minutes = int(offset.total_seconds() // 60)
|
||||
sign = "+" if minutes >= 0 else "-"
|
||||
return f"{sign}{abs(minutes) // 60:02d}:{abs(minutes) % 60:02d}"
|
||||
|
||||
|
||||
def _sequence_check(items: list, start_key: str, end_key: str, tz: timezone | None, label: str) -> dict:
|
||||
"""Continuity of one period list on full timestamps (dates when that is all there is)."""
|
||||
_scripts_on_path()
|
||||
import timeline_boundaries as tb
|
||||
|
||||
rows = []
|
||||
for item in items:
|
||||
record = _record(item)
|
||||
start = _stamp(record.get(start_key), tz) or _iso(record.get(start_key))
|
||||
end = _stamp(record.get(end_key), tz) or _iso(record.get(end_key))
|
||||
rows.append({"start": start, "end": end})
|
||||
check = tb.check_continuity(rows, label=label)
|
||||
if rows and all(len(str(row.get("start") or "")) == 10 for row in rows):
|
||||
check["resolution"] = "date_only"
|
||||
return check
|
||||
|
||||
|
||||
def _owned_houses(modules: dict) -> dict:
|
||||
return _record(_record(modules.get("functional_benefic_malefic")).get("owned_houses"))
|
||||
|
||||
@@ -1352,7 +1401,7 @@ def _running(rows: list, at: str, start_key: str = "start", end_key: str = "end"
|
||||
|
||||
|
||||
def _period(item: dict | None, chart: dict, modules: dict, *, start_key: str = "start", end_key: str = "end",
|
||||
lord_key: str | None = None) -> dict | None:
|
||||
lord_key: str | None = None, tz: timezone | None = None) -> dict | None:
|
||||
if not item:
|
||||
return None
|
||||
out: dict[str, Any] = {}
|
||||
@@ -1366,6 +1415,9 @@ def _period(item: dict | None, chart: dict, modules: dict, *, start_key: str = "
|
||||
for key, name in ((start_key, "start"), (end_key, "end")):
|
||||
if _iso(item.get(key)):
|
||||
out[name] = _iso(item.get(key))
|
||||
full = _stamp(item.get(key), tz)
|
||||
if full:
|
||||
out[f"{name}_at"] = full
|
||||
if isinstance(sign, str):
|
||||
house = _whole_sign_house(sign, lagna_idx)
|
||||
if house is not None:
|
||||
@@ -1379,9 +1431,12 @@ def _period(item: dict | None, chart: dict, modules: dict, *, start_key: str = "
|
||||
|
||||
def _timeline_row(system: str, periods: list, chart: dict, modules: dict, at: str, *,
|
||||
start_key: str = "start", end_key: str = "end", child_key: str = "antardasha",
|
||||
grandchild_key: str = "pratyantardasha", **extra: Any) -> dict:
|
||||
grandchild_key: str = "pratyantardasha", tz: timezone | None = None, **extra: Any) -> dict:
|
||||
md = _running(periods, at, start_key, end_key)
|
||||
row: dict[str, Any] = {"system": system, "applicable": True, **{k: v for k, v in extra.items() if v is not None}}
|
||||
_attach_continuity(row, [_sequence_check(periods, start_key, end_key, tz, f"{system}.md")] + (
|
||||
[_sequence_check(list(md.get(child_key) or []), start_key, end_key, tz, f"{system}.running_md.{child_key}")]
|
||||
if md and md.get(child_key) else []))
|
||||
if not md:
|
||||
ends = [_iso(_record(item).get(end_key)) for item in periods]
|
||||
last = max((end for end in ends if end), default=None)
|
||||
@@ -1393,16 +1448,28 @@ def _timeline_row(system: str, periods: list, chart: dict, modules: dict, at: st
|
||||
else:
|
||||
row["status"] = "no_period_at_reference_date"
|
||||
return row
|
||||
row["md"] = _period(md, chart, modules, start_key=start_key, end_key=end_key)
|
||||
row["md"] = _period(md, chart, modules, start_key=start_key, end_key=end_key, tz=tz)
|
||||
ad = _running(list(md.get(child_key) or []), at, start_key, end_key)
|
||||
if ad:
|
||||
row["ad"] = _period(ad, chart, modules, start_key=start_key, end_key=end_key)
|
||||
row["ad"] = _period(ad, chart, modules, start_key=start_key, end_key=end_key, tz=tz)
|
||||
pd = _running(list(ad.get(grandchild_key) or []), at, start_key, end_key)
|
||||
if pd:
|
||||
row["pd"] = _period(pd, chart, modules, start_key=start_key, end_key=end_key)
|
||||
row["pd"] = _period(pd, chart, modules, start_key=start_key, end_key=end_key, tz=tz)
|
||||
return row
|
||||
|
||||
|
||||
def _attach_continuity(row: dict, checks: list[dict]) -> None:
|
||||
"""Every check on the row; `continuity_issue` (card) only when one is not continuous."""
|
||||
checks = [check for check in checks if check.get("segments")]
|
||||
if not checks:
|
||||
return
|
||||
row["continuity"] = [{k: check.get(k) for k in ("table", "status", "resolution", "gaps", "overlaps", "reason")
|
||||
if check.get(k) not in (None, [])} for check in checks]
|
||||
issues = [entry for entry in row["continuity"] if entry.get("status") != "continuous"]
|
||||
if issues:
|
||||
row["continuity_issue"] = issues
|
||||
|
||||
|
||||
# 产品 2026-11-07: dashas the upstream technique layer now computes (BUG-1704) replace
|
||||
# the dasha table's not_available_yet rows. Age-based periods are dated like Narayana.
|
||||
UPSTREAM_DASHA_SECTIONS = {
|
||||
@@ -1419,6 +1486,7 @@ def merge_upstream_dashas(layers: dict, chart: dict, modules: dict, *, birth_pay
|
||||
if not isinstance(rows, list) or not sections:
|
||||
return
|
||||
birth = _birth_datetime(birth_payload)
|
||||
zone = _birth_zone(birth_payload)
|
||||
at = reference.strftime("%Y-%m-%d")
|
||||
by_system = {row.get("system"): index for index, row in enumerate(rows) if isinstance(row, dict)}
|
||||
for system, key in UPSTREAM_DASHA_SECTIONS.items():
|
||||
@@ -1432,9 +1500,12 @@ def merge_upstream_dashas(layers: dict, chart: dict, modules: dict, *, birth_pay
|
||||
for item in periods:
|
||||
item = dict(_record(item))
|
||||
if "start" not in item and isinstance(item.get("start_age"), (int, float)):
|
||||
item.update(_narayana_dates(birth, item))
|
||||
item.update(_narayana_dates(birth, item, zone))
|
||||
# Full instants for the period check; the dates above stay for display.
|
||||
item["start"], item["end"] = item.pop("start_at", item["start"]), item.pop("end_at", item.get("end"))
|
||||
dated.append(item)
|
||||
row = _timeline_row(system, dated, chart, modules, at, source="upstream_technique_layers", status_note=status)
|
||||
row = _timeline_row(system, dated, chart, modules, at, source="upstream_technique_layers", status_note=status,
|
||||
tz=zone)
|
||||
else:
|
||||
row = {"system": system, "applicable": False, "status": section.get("status") or "blocked",
|
||||
"reason": section.get("reason") or "; ".join(str(item) for item in (section.get("blockers") or [])) or None,
|
||||
@@ -1452,14 +1523,14 @@ def merge_upstream_dashas(layers: dict, chart: dict, modules: dict, *, birth_pay
|
||||
lons = {name: lon for name, pdata in _record(chart.get("planets")).items()
|
||||
if (lon := _planet_lon(pdata)) is not None}
|
||||
asc = _planet_lon(chart.get("ascendant"))
|
||||
tz = timezone(timedelta(hours=float(birth_payload.get("tz") or 0)))
|
||||
sudasa = sudasa_birth(float(asc), lons, birth.replace(tzinfo=tz), 365.25)
|
||||
periods = [dict(_record(item), start=str(_record(item).get("start"))[:10], end=str(_record(item).get("end"))[:10],
|
||||
antardashas=[dict(_record(c), start=str(_record(c).get("start"))[:10], end=str(_record(c).get("end"))[:10])
|
||||
sudasa = sudasa_birth(float(asc), lons, birth.replace(tzinfo=zone), 365.25)
|
||||
# 原值:start / end 截成日期;新值:保留完整时刻(_period 另给日期);原因:占星师第三轮审查 2026-11-07
|
||||
periods = [dict(_record(item), start=str(_record(item).get("start")), end=str(_record(item).get("end")),
|
||||
antardashas=[dict(_record(c), start=str(_record(c).get("start")), end=str(_record(c).get("end")))
|
||||
for c in (_record(item).get("antardashas") or [])])
|
||||
for item in sudasa.get("periods") or []]
|
||||
row = _timeline_row("sudasa", periods, chart, modules, at, child_key="antardashas",
|
||||
source="research_timing.families.sudasa_birth", status_note="parameter_sensitive")
|
||||
source="research_timing.families.sudasa_birth", status_note="parameter_sensitive", tz=zone)
|
||||
except (KeyError, TypeError, ValueError, ImportError) as exc:
|
||||
row = {"system": "sudasa", "applicable": False, "status": "blocked", "reason": str(exc)}
|
||||
if "sudasa" in by_system:
|
||||
@@ -1468,20 +1539,26 @@ def merge_upstream_dashas(layers: dict, chart: dict, modules: dict, *, birth_pay
|
||||
rows.append(row)
|
||||
|
||||
|
||||
def _narayana_dates(birth: datetime, row: dict) -> dict:
|
||||
def _narayana_dates(birth: datetime, row: dict, tz: timezone | None = None) -> dict:
|
||||
"""Dates of one Narayana row: the engine's own (unrounded) dates when present.
|
||||
|
||||
Rows straight from `narayana_rath` carry unrounded ages and are converted
|
||||
with the same rule as `narayana_legacy_label.age_to_date`.
|
||||
with the same rule as `narayana_legacy_label.age_to_date`. `start_at` /
|
||||
`end_at` keep the full instant (占星师第三轮审查 2026-11-07).
|
||||
"""
|
||||
out: dict[str, Any] = {}
|
||||
for key, date_key, name in (("start_age", "start_date", "start"), ("end_age", "end_date", "end")):
|
||||
if isinstance(row.get(date_key), str):
|
||||
out[name] = row[date_key][:10]
|
||||
full = _stamp(row[date_key], tz)
|
||||
if full:
|
||||
out[f"{name}_at"] = full
|
||||
continue
|
||||
age = row.get(key)
|
||||
if isinstance(age, (int, float)):
|
||||
out[name] = (birth + timedelta(days=float(age) * 365.25)).strftime("%Y-%m-%d")
|
||||
moment = birth + timedelta(days=float(age) * 365.25)
|
||||
out[name] = moment.strftime("%Y-%m-%d")
|
||||
out[f"{name}_at"] = (moment.replace(tzinfo=tz) if tz else moment).isoformat(timespec="seconds")
|
||||
return out
|
||||
|
||||
|
||||
@@ -1502,15 +1579,19 @@ def build_dasha_systems(chart: dict, modules: dict, *, birth_payload: dict, refe
|
||||
|
||||
at = reference.strftime("%Y-%m-%d")
|
||||
birth = _birth_datetime(birth_payload)
|
||||
zone = _birth_zone(birth_payload)
|
||||
rows: list[dict] = []
|
||||
sub = _record(modules.get("dasha_sub_periods"))
|
||||
current = _record(sub.get("current"))
|
||||
vim: dict[str, Any] = {"system": "vimshottari", "applicable": True}
|
||||
for level, value in (("md", current.get("mahadasha")), ("ad", current.get("antardasha")),
|
||||
("pd", _record(sub.get("pratyantar_dasha_timeline")).get("current"))):
|
||||
period = _period(_record(value) or None, chart, modules)
|
||||
period = _period(_record(value) or None, chart, modules, tz=zone)
|
||||
if period:
|
||||
vim[level] = period
|
||||
timeline = sub.get("timeline") if isinstance(sub.get("timeline"), list) else None
|
||||
if timeline:
|
||||
_attach_continuity(vim, [_sequence_check(timeline, "start", "end", zone, "vimshottari.md")])
|
||||
rows.append(vim)
|
||||
|
||||
narayana = _record(modules.get("narayana_dasha"))
|
||||
@@ -1520,13 +1601,13 @@ def build_dasha_systems(chart: dict, modules: dict, *, birth_payload: dict, refe
|
||||
for level in ("md", "ad", "pd"):
|
||||
item = _record(nar_current.get(level))
|
||||
if item:
|
||||
period = _period(item, chart, modules) or {}
|
||||
period = _period(item, chart, modules, tz=zone) or {}
|
||||
period.pop("lord_houses", None)
|
||||
if isinstance(item.get("lord"), str):
|
||||
houses = _lord_houses(chart, modules, item["lord"])
|
||||
if houses:
|
||||
period["lord_houses"] = houses
|
||||
period.update(_narayana_dates(birth, item))
|
||||
period.update(_narayana_dates(birth, item, zone))
|
||||
nar[level] = period
|
||||
# 产品 2026-11-07: the next Narayana AD with its dates (Rath equal ADs, narayana_rath.antardasha).
|
||||
md_item = _record(nar_current.get("md"))
|
||||
@@ -1551,20 +1632,24 @@ def build_dasha_systems(chart: dict, modules: dict, *, birth_payload: dict, refe
|
||||
current_row = next((row for row in ordered if row.get("sign") == ad_item.get("sign")
|
||||
and abs(float(row["start_age"]) - float(ad_item["start_age"])) < 0.02), None)
|
||||
if current_row is not None and isinstance(nar.get("ad"), dict):
|
||||
nar["ad"].update(_narayana_dates(birth, current_row))
|
||||
nar["ad"].update(_narayana_dates(birth, current_row, zone))
|
||||
later = [row for row in ordered if row["start_age"] > float((current_row or ad_item)["start_age"]) + 1e-6]
|
||||
if later:
|
||||
nxt = later[0]
|
||||
period = _period(nxt, chart, modules) or {}
|
||||
period = _period(nxt, chart, modules, tz=zone) or {}
|
||||
period.pop("lord_houses", None)
|
||||
if isinstance(nxt.get("lord"), str):
|
||||
houses = _lord_houses(chart, modules, nxt["lord"])
|
||||
if houses:
|
||||
period["lord_houses"] = houses
|
||||
period.update(_narayana_dates(birth, nxt))
|
||||
period.update(_narayana_dates(birth, nxt, zone))
|
||||
nar["next_ad"] = period
|
||||
if isinstance(nar.get("ad"), dict) and nar["ad"].get("end") != period.get("start"):
|
||||
nar["continuity"] = f"gap: running AD ends {nar['ad'].get('end')}, next starts {period.get('start')}"
|
||||
# 占星师第三轮审查 2026-11-07: the whole AD row set of the running MD, on full
|
||||
# instants (start inclusive, end exclusive), replaces the running/next date compare.
|
||||
if ordered:
|
||||
dated = [{"start": dates.get("start_at"), "end": dates.get("end_at")}
|
||||
for dates in (_narayana_dates(birth, row, zone) for row in ordered)]
|
||||
_attach_continuity(nar, [_sequence_check(dated, "start", "end", zone, "narayana.running_md.ad")])
|
||||
if narayana.get("status") == "blocked":
|
||||
nar["status"] = "blocked"
|
||||
nar["reason"] = narayana.get("blocked_note") or narayana.get("reason")
|
||||
@@ -1587,7 +1672,7 @@ def build_dasha_systems(chart: dict, modules: dict, *, birth_payload: dict, refe
|
||||
for key in ("year_rule_status", "confidence_status"):
|
||||
if section.get(key):
|
||||
extra[key] = section[key]
|
||||
rows.append(_timeline_row(name, section["periods"], chart, modules, at, **extra))
|
||||
rows.append(_timeline_row(name, section["periods"], chart, modules, at, tz=zone, **extra))
|
||||
|
||||
body = {**birth_payload, "today": at}
|
||||
for key in ("yogini", "kalachakra"):
|
||||
@@ -1595,7 +1680,7 @@ def build_dasha_systems(chart: dict, modules: dict, *, birth_payload: dict, refe
|
||||
periods = registry.compute_dasha(key, birth_dt=birth, planets=_record(chart.get("planets")),
|
||||
ascendant=_record(chart.get("ascendant")), body=body)["periods"]
|
||||
rows.append(_timeline_row(key, periods, chart, modules, at, start_key="start_date", end_key="end_date",
|
||||
lord_key=None))
|
||||
lord_key=None, tz=zone))
|
||||
except Exception as exc:
|
||||
rows.append({"system": key, "applicable": False, **_blocked(exc)})
|
||||
|
||||
@@ -1615,7 +1700,7 @@ def build_dasha_systems(chart: dict, modules: dict, *, birth_payload: dict, refe
|
||||
row["reason"] = payload["reason"]
|
||||
return row
|
||||
periods = registry._major_rows(payload)
|
||||
timeline = _timeline_row(key, periods, chart, modules, at, start_key="start_date", end_key="end_date")
|
||||
timeline = _timeline_row(key, periods, chart, modules, at, start_key="start_date", end_key="end_date", tz=zone)
|
||||
timeline.update({k: v for k, v in row.items() if k not in timeline})
|
||||
if payload.get("confidence_status"):
|
||||
timeline["confidence_status"] = payload["confidence_status"]
|
||||
@@ -1657,6 +1742,9 @@ def build_dasha_systems(chart: dict, modules: dict, *, birth_payload: dict, refe
|
||||
"source": "dasha_sub_periods, narayana_dasha, rashi_dashas_native, dasha_registry, ashtottari / tribhagi / conditional dasha modules",
|
||||
"reference_date": at,
|
||||
"house_rule": "house: whole-sign house of the period sign from the natal lagna; lord_houses: the lord's natal house (in) and the houses it rules (owns)",
|
||||
# 占星师第三轮审查 2026-11-07: one boundary rule; full instants beside the display dates.
|
||||
"boundary_rule": "start_inclusive_end_exclusive",
|
||||
"time_basis": f"start_at / end_at: producer instant; naive producer times are the birth clock at UTC{_fmt_tz(zone)}",
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
@@ -457,6 +457,9 @@ def calc_solar_return_chart(
|
||||
'asc_sign_idx': sr_asc_idx,
|
||||
'birth_asc_sign_idx': birth_asc_idx,
|
||||
'birth_moon_longitude': birth_moon_lon,
|
||||
# 占星师第三轮审查 2026-11-07:下一次真实返照用同一目标经度与求解器。
|
||||
'birth_jd_ut': birth_jd_ut,
|
||||
'target_sun_longitude': birth_sun_lon,
|
||||
'target_year': target_year,
|
||||
'birth_year': birth_year,
|
||||
'annual_location': {'latitude': annual_lat, 'longitude': annual_lon,
|
||||
@@ -718,6 +721,14 @@ def solar_return_full_report(
|
||||
except Exception as e:
|
||||
result['tajika_strength'] = {'error': str(e)}
|
||||
|
||||
# 8b. 年界三种区间分开(占星师第三轮审查 2026-11-07):真实返照区间(本次 → 下一次
|
||||
# 真实返照)、大运算法年长(Mudda 365.25 天)、展示截断窗口;Mudda 段连续性检查。
|
||||
if not degraded:
|
||||
try:
|
||||
result['annual_interval'] = _annual_interval(sr, result.get('mudda_dasha'), target_year, ayanamsa_name)
|
||||
except Exception as e: # noqa: BLE001 - reported on the field, the report continues
|
||||
result['annual_interval'] = {'status': 'blocked', 'reason': f'{type(e).__name__}: {e}'}
|
||||
|
||||
# 9. 综合总结
|
||||
result['summary'] = _make_sr_summary(result)
|
||||
# Keep the longitudes already calculated above so the report pack can print
|
||||
@@ -737,6 +748,79 @@ def solar_return_full_report(
|
||||
|
||||
return result
|
||||
|
||||
def _annual_interval(sr: Dict, mudda: Optional[Dict], target_year: int, ayanamsa_name: str) -> Dict:
|
||||
"""This return → next actual return, the dasha year length, and the shown window.
|
||||
|
||||
Mudda keeps its own 365.25-day year (BUG-1216); the real interval between
|
||||
two sidereal solar returns is about 365.256 days and varies, so the two
|
||||
ends differ by minutes. Both are exposed; neither is stretched to the other.
|
||||
"""
|
||||
try:
|
||||
from timeline_boundaries import BOUNDARY_RULE, BOUNDARY_RULE_TEXT_ZH, check_continuity
|
||||
except ImportError: # package import
|
||||
from scripts.timeline_boundaries import BOUNDARY_RULE, BOUNDARY_RULE_TEXT_ZH, check_continuity
|
||||
this = sr.get('solar_return') or {}
|
||||
location = sr.get('annual_location') or {}
|
||||
birth_jd, target_lon = sr.get('birth_jd_ut'), sr.get('target_sun_longitude')
|
||||
if not isinstance(this.get('dt_ut'), datetime) or birth_jd is None or target_lon is None:
|
||||
return {'status': 'blocked', 'reason': 'solar_return_instant_missing'}
|
||||
nxt = find_solar_return_ut(float(birth_jd), float(target_lon), int(target_year) + 1, ayanamsa_name=ayanamsa_name)
|
||||
if 'error' in nxt or not isinstance(nxt.get('dt_ut'), datetime):
|
||||
return {'status': 'blocked', 'reason': f"next_solar_return_unavailable:{nxt.get('error')}"}
|
||||
offset, zone_id = float(location.get('utc_offset') or 0.0), location.get('timezone_id')
|
||||
start = this['dt_ut'].replace(tzinfo=timezone.utc)
|
||||
end = nxt['dt_ut'].replace(tzinfo=timezone.utc)
|
||||
|
||||
def stamp(moment: datetime, jd_ut: Optional[float] = None) -> Dict:
|
||||
local = _localize_return_datetime(moment.replace(tzinfo=None), offset, zone_id)
|
||||
jd = jd_ut if isinstance(jd_ut, (int, float)) else _datetime_to_jd_ut(moment.replace(tzinfo=None))
|
||||
return {'utc': moment.isoformat(), 'local': local.isoformat(), 'timezone_id': zone_id,
|
||||
'jd_ut': round(float(jd), 6)}
|
||||
|
||||
out: Dict = {
|
||||
'status': 'computed',
|
||||
'boundary_rule': BOUNDARY_RULE,
|
||||
'boundary_rule_text': BOUNDARY_RULE_TEXT_ZH,
|
||||
'solar_return_interval': {
|
||||
'start': stamp(start, this.get('jd_ut')), 'end': stamp(end, nxt.get('jd_ut')),
|
||||
'duration_days': round(float(nxt['jd_ut']) - float(this['jd_ut']), 6)
|
||||
if isinstance(this.get('jd_ut'), (int, float)) and isinstance(nxt.get('jd_ut'), (int, float))
|
||||
else round((end - start).total_seconds() / 86400.0, 6),
|
||||
'source': 'find_solar_return_ut(target_year) → find_solar_return_ut(target_year + 1), same target longitude and solver',
|
||||
'next_return_residual_degrees': nxt.get('error_deg'),
|
||||
},
|
||||
}
|
||||
if isinstance(mudda, dict) and mudda.get('annual_start') and mudda.get('annual_end'):
|
||||
# Mudda dates are naive local wall time = SR local + elapsed days, i.e.
|
||||
# in the UTC offset at the return instant.
|
||||
local_offset = timezone(_localize_return_datetime(this['dt_ut'], offset, zone_id).utcoffset())
|
||||
dasha_end = datetime.fromisoformat(str(mudda['annual_end'])).replace(tzinfo=local_offset)
|
||||
days = mudda.get('annual_duration_days')
|
||||
out['dasha_year'] = {
|
||||
'system': 'mudda_dasha', 'days': days, 'basis': mudda.get('year_length_basis'),
|
||||
'start': stamp(start, this.get('jd_ut')), 'end': stamp(dasha_end.astimezone(timezone.utc)),
|
||||
'end_minus_next_return_seconds': round((dasha_end - end).total_seconds(), 1),
|
||||
'note': 'Mudda keeps its own year (365.25 days); it is not stretched to the next solar return',
|
||||
}
|
||||
periods = mudda.get('periods') or []
|
||||
out['displayed_window'] = {
|
||||
'start': periods[0]['start'] if periods else None,
|
||||
'end': periods[-1]['end'] if periods else None,
|
||||
'truncated_at': 'dasha_year_end',
|
||||
'time_basis': f"naive local wall time in the return-instant offset {local_offset}",
|
||||
'note': 'Mudda rows are cut at the dasha-year end; the full 10th group stays in periods_full',
|
||||
}
|
||||
out['mudda_continuity'] = check_continuity(
|
||||
periods, label='mudda_dasha.periods',
|
||||
expected_start=mudda.get('annual_start'), expected_end=mudda.get('annual_end'))
|
||||
gap = out['dasha_year']['end_minus_next_return_seconds']
|
||||
out['dasha_year_vs_return'] = (
|
||||
'equal' if abs(gap) <= 1 else
|
||||
f"Mudda year ends {abs(gap):.0f} s {'after' if gap > 0 else 'before'} the next actual solar return"
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _interpret_muntha_sign(sign_idx: int) -> str:
|
||||
"""Muntha 在12星座的解读"""
|
||||
interp = {
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One boundary rule and one continuity check for every exposed period table.
|
||||
|
||||
占星师第三轮审查 2026-11-07 (item 10 of her review): two adjacent periods
|
||||
both shown as "12 月 8 日" do not prove the underlying timeline has no hole.
|
||||
Every dasha / Mudda / Narayana / annual period table we expose follows one
|
||||
rule -- start inclusive, end exclusive -- and is checked on its full
|
||||
timestamps: each segment's end must equal the next segment's start.
|
||||
|
||||
Inputs may be datetimes, ISO strings (with or without offset), package
|
||||
``instant`` dicts (``{"utc": ..., "jd_ut": ...}``) or Julian days. Aware and
|
||||
naive values are never compared with each other; such a table is reported as
|
||||
``not_comparable`` instead of being guessed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Iterable
|
||||
|
||||
BOUNDARY_RULE = "start_inclusive_end_exclusive"
|
||||
BOUNDARY_RULE_TEXT = "Each period starts at its start instant (inclusive) and ends just before its end instant (exclusive)."
|
||||
BOUNDARY_RULE_TEXT_ZH = "每段从起点时刻起算(含),到终点时刻前结束(不含);下一段从同一时刻开始。"
|
||||
|
||||
# Producers write seconds with microseconds; anything at or below this is the
|
||||
# same instant. Larger mismatches are reported with their size.
|
||||
DEFAULT_TOLERANCE_SECONDS = 1.0
|
||||
_JD_UNIX_EPOCH = 2440587.5
|
||||
|
||||
|
||||
def parse_instant(value: Any) -> datetime | None:
|
||||
"""A boundary value as a datetime (aware when the source carries a zone)."""
|
||||
if isinstance(value, datetime):
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
if isinstance(value.get("jd_ut"), (int, float)) and not isinstance(value.get("jd_ut"), bool):
|
||||
return _from_jd(float(value["jd_ut"]))
|
||||
for key in ("utc", "local", "at", "instant"):
|
||||
if value.get(key) is not None:
|
||||
return parse_instant(value[key])
|
||||
return None
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
return _from_jd(float(value)) if value > 1_000_000 else None
|
||||
if isinstance(value, str) and len(value) >= 10:
|
||||
text = value.strip().replace("Z", "+00:00")
|
||||
try:
|
||||
return datetime.fromisoformat(text)
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _from_jd(jd_ut: float) -> datetime:
|
||||
return datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(days=jd_ut - _JD_UNIX_EPOCH)
|
||||
|
||||
|
||||
def check_continuity(
|
||||
rows: Iterable[Any],
|
||||
*,
|
||||
start_key: str = "start",
|
||||
end_key: str = "end",
|
||||
label: str | None = None,
|
||||
expected_start: Any = None,
|
||||
expected_end: Any = None,
|
||||
tolerance_seconds: float = DEFAULT_TOLERANCE_SECONDS,
|
||||
) -> dict[str, Any]:
|
||||
"""Check that consecutive rows meet exactly: ``rows[i].end == rows[i+1].start``.
|
||||
|
||||
``expected_start`` / ``expected_end`` (optional) are the window the table
|
||||
claims to cover; a first start after it or a last end before it is a gap
|
||||
at the edge. Returns ``status`` ``continuous`` / ``discontinuous`` /
|
||||
``not_comparable`` / ``insufficient`` with every gap and overlap.
|
||||
"""
|
||||
items = [row for row in rows if isinstance(row, dict)]
|
||||
out: dict[str, Any] = {"rule": BOUNDARY_RULE, "segments": len(items)}
|
||||
if label:
|
||||
out["table"] = label
|
||||
spans = []
|
||||
for index, row in enumerate(items):
|
||||
start, end = parse_instant(row.get(start_key)), parse_instant(row.get(end_key))
|
||||
if start is None or end is None:
|
||||
out.update(status="insufficient", reason=f"row_{index}_boundary_unparsed")
|
||||
return out
|
||||
spans.append((start, end))
|
||||
edges = [parse_instant(expected_start), parse_instant(expected_end)]
|
||||
instants = [moment for span in spans for moment in span] + [moment for moment in edges if moment is not None]
|
||||
if len({moment.tzinfo is None for moment in instants}) > 1:
|
||||
out.update(status="not_comparable", reason="aware_and_naive_boundaries_mixed")
|
||||
return out
|
||||
if not spans:
|
||||
out.update(status="insufficient", reason="no_rows")
|
||||
return out
|
||||
|
||||
def seconds(a: datetime, b: datetime) -> float:
|
||||
return round((b - a).total_seconds(), 3)
|
||||
|
||||
gaps: list[dict[str, Any]] = []
|
||||
overlaps: list[dict[str, Any]] = []
|
||||
reversed_rows = [index for index, (start, end) in enumerate(spans) if end < start]
|
||||
for index in range(len(spans) - 1):
|
||||
end, next_start = spans[index][1], spans[index + 1][0]
|
||||
delta = seconds(end, next_start)
|
||||
if abs(delta) <= tolerance_seconds:
|
||||
continue
|
||||
entry = {"after_index": index, "end": end.isoformat(), "next_start": next_start.isoformat(), "seconds": delta}
|
||||
(gaps if delta > 0 else overlaps).append(entry)
|
||||
if edges[0] is not None and abs(seconds(edges[0], spans[0][0])) > tolerance_seconds:
|
||||
delta = seconds(edges[0], spans[0][0])
|
||||
(gaps if delta > 0 else overlaps).append(
|
||||
{"edge": "window_start", "expected": edges[0].isoformat(), "first_start": spans[0][0].isoformat(), "seconds": delta})
|
||||
if edges[1] is not None and abs(seconds(spans[-1][1], edges[1])) > tolerance_seconds:
|
||||
delta = seconds(spans[-1][1], edges[1])
|
||||
(gaps if delta > 0 else overlaps).append(
|
||||
{"edge": "window_end", "last_end": spans[-1][1].isoformat(), "expected": edges[1].isoformat(), "seconds": delta})
|
||||
out.update(
|
||||
status="continuous" if not (gaps or overlaps or reversed_rows) else "discontinuous",
|
||||
first_start=spans[0][0].isoformat(),
|
||||
last_end=spans[-1][1].isoformat(),
|
||||
gaps=gaps,
|
||||
overlaps=overlaps,
|
||||
tolerance_seconds=tolerance_seconds,
|
||||
)
|
||||
if reversed_rows:
|
||||
out["reversed_rows"] = reversed_rows
|
||||
return out
|
||||
|
||||
|
||||
def summarize(checks: Iterable[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""One line over several checks: which tables are not continuous."""
|
||||
checks = [check for check in checks if isinstance(check, dict)]
|
||||
bad = [check.get("table") or f"#{index}" for index, check in enumerate(checks)
|
||||
if check.get("status") not in ("continuous",)]
|
||||
return {"rule": BOUNDARY_RULE, "tables_checked": len(checks),
|
||||
"status": "continuous" if not bad else "discontinuous_or_unchecked", "tables_not_continuous": bad}
|
||||
@@ -86,10 +86,12 @@ def test_package_shape_and_version() -> None:
|
||||
assert package["schema"] == "jyotish.annual_package.v1"
|
||||
# 原值:无 transit_context;新值:slow_transits 后加 transit_context(Sade Sati / AV / Vedha)
|
||||
# 原因:产品 2026-11-07 占星师方案:年报/合盘完整运行 skill
|
||||
# 原值:not_included 之后直接是 block_index;新值:中间加 timeline_continuity(起点含 / 终点不含,逐段连续性)
|
||||
# 原因:占星师第三轮审查 2026-11-07
|
||||
assert list(package) == [
|
||||
"schema", "annual_package_version", "parameters", "report_range", "year_charts",
|
||||
"natal_periods", "slow_transits", "transit_context", "independent_annual_views", "computation_boundaries",
|
||||
"not_included", "block_index", "blocked_count",
|
||||
"not_included", "timeline_continuity", "block_index", "blocked_count",
|
||||
]
|
||||
json.dumps(package) # plain JSON, no datetime / circular references
|
||||
for chart in package["year_charts"]:
|
||||
|
||||
@@ -64,6 +64,10 @@ def test_builds_annual_tajika_pack_contract() -> None:
|
||||
"raman_sahams",
|
||||
"annual_special_points",
|
||||
"mudda_profiles",
|
||||
# 原值:止于 mudda_profiles
|
||||
# 新值:加 annual_interval(真实返照区间、Mudda 年长、展示窗口、连续性检查)
|
||||
# 原因:占星师第三轮审查 2026-11-07
|
||||
"annual_interval",
|
||||
]
|
||||
assert pack["schema"] == "jyotish.annual_tajika_pack.v1"
|
||||
assert pack["profile"]["profile_id"]
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""占星师第三轮审查 2026-11-07, item 3: one boundary rule and a continuity check.
|
||||
|
||||
Rule: every exposed period starts inclusive and ends exclusive; the check
|
||||
compares full timestamps, so two periods both shown as the same date cannot
|
||||
hide a hole. The annual data separates the real solar-return interval (this
|
||||
return to the next actual return), the dasha year length (365.25 days) and
|
||||
the shown window.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path[:0] = [ROOT, os.path.join(ROOT, "scripts")]
|
||||
|
||||
import consultation_native_layers as cnl # noqa: E402
|
||||
import solar_return # noqa: E402
|
||||
import timeline_boundaries as tb # noqa: E402
|
||||
from annual_service import api as annual_api # noqa: E402
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
|
||||
def _rows(*pairs):
|
||||
return [{"start": a, "end": b} for a, b in pairs]
|
||||
|
||||
|
||||
def test_check_reports_gap_overlap_and_window_edges() -> None:
|
||||
# 原值: 无统一检查;相邻两段同显示「12 月 8 日」即被当作连续
|
||||
# 新值: 按完整时刻逐段核对 end == 下一段 start;断口 / 重叠 / 窗口边缘逐条列出
|
||||
# 原因: 占星师第三轮审查 2026-11-07
|
||||
t0 = datetime(2026, 12, 8, 1, 0, tzinfo=UTC)
|
||||
same_day_hole = _rows((t0 - timedelta(days=30), t0), (t0 + timedelta(hours=5), t0 + timedelta(days=30)))
|
||||
check = tb.check_continuity(same_day_hole)
|
||||
assert check["status"] == "discontinuous" and check["gaps"][0]["seconds"] == 5 * 3600
|
||||
overlap = tb.check_continuity(_rows((t0, t0 + timedelta(days=2)), (t0 + timedelta(days=1), t0 + timedelta(days=3))))
|
||||
assert overlap["overlaps"][0]["seconds"] == -86400
|
||||
ok = tb.check_continuity(_rows((t0, t0 + timedelta(days=1)), (t0 + timedelta(days=1), t0 + timedelta(days=2))),
|
||||
expected_start=t0, expected_end=t0 + timedelta(days=3))
|
||||
assert ok["status"] == "discontinuous" and ok["gaps"][0]["edge"] == "window_end"
|
||||
mixed = tb.check_continuity(_rows((t0, t0 + timedelta(days=1)), (datetime(2026, 12, 9, 1), datetime(2026, 12, 10))))
|
||||
assert mixed["status"] == "not_comparable"
|
||||
assert tb.check_continuity(_rows((t0.isoformat(), "2026-12-09T01:00:00+00:00"),
|
||||
({"jd_ut": 2461383.5 + 1 / 24}, {"utc": "2026-12-10T00:00:00Z"})))["status"] == "continuous"
|
||||
|
||||
|
||||
def test_solar_return_report_separates_real_interval_dasha_year_and_window() -> None:
|
||||
# 原值: 只有 annual_end = SR + 365.25 天,被当作年终;没有下一次真实返照
|
||||
# 新值: annual_interval.solar_return_interval(本次 → 下一次真实返照,约 365.256 天)、
|
||||
# dasha_year(Mudda 365.25 天)、displayed_window(截断窗口)与 Mudda 段连续性
|
||||
# 原因: 占星师第三轮审查 2026-11-07
|
||||
report = solar_return.solar_return_full_report(1955, 2, 24, 19, 15, 37.7749, -122.4194, -8, 2026)
|
||||
interval = report["annual_interval"]
|
||||
assert interval["boundary_rule"] == tb.BOUNDARY_RULE
|
||||
real = interval["solar_return_interval"]
|
||||
assert 365.2 < real["duration_days"] < 365.3 and real["duration_days"] != 365.25
|
||||
nxt = solar_return.solar_return_full_report(1955, 2, 24, 19, 15, 37.7749, -122.4194, -8, 2027)
|
||||
assert real["end"]["jd_ut"] == pytest.approx(nxt["solar_return"]["jd_ut"], abs=1e-6)
|
||||
dasha = interval["dasha_year"]
|
||||
assert dasha["days"] == 365.25
|
||||
seconds = (datetime.fromisoformat(dasha["end"]["utc"]) - datetime.fromisoformat(real["end"]["utc"])).total_seconds()
|
||||
assert dasha["end_minus_next_return_seconds"] == pytest.approx(seconds, abs=1)
|
||||
assert abs(seconds) > 60 # the two year ends are not the same instant
|
||||
assert interval["mudda_continuity"]["status"] == "continuous"
|
||||
assert interval["displayed_window"]["end"] == report["mudda_dasha"]["annual_end"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def package() -> dict:
|
||||
body = {
|
||||
"mode": "package", "year": 1990, "month": 6, "day": 15, "hour": 12, "minute": 0, "second": 0,
|
||||
"lat": 39.9042, "lon": 116.4074, "tz": 8, "timezone_id": "Asia/Shanghai",
|
||||
"ayanamsa": "raman", "node_mode": "mean",
|
||||
"report_range": {"kind": "calendar_year", "year": 2026}, "observation_date": "2026-11-01",
|
||||
}
|
||||
return annual_api.compute_annual_package(body)["package"]
|
||||
|
||||
|
||||
def test_annual_package_checks_every_period_table(package) -> None:
|
||||
# 原值: 年运包没有连续性检查;Mudda 年终与下一次真实返照之间的空档不可见
|
||||
# 新值: timeline_continuity(年盘链、各年 Mudda / Patyayini / 月盘 / Varsha Narayana、本命 Vimshottari / Narayana);
|
||||
# 每张年盘带 interval(真实返照区间、各大运年长、展示窗口)
|
||||
# 原因: 占星师第三轮审查 2026-11-07
|
||||
continuity = package["timeline_continuity"]
|
||||
assert continuity["rule"] == tb.BOUNDARY_RULE
|
||||
assert continuity["year_charts"]["status"] == "continuous"
|
||||
assert continuity["natal_periods"]["status"] == "continuous"
|
||||
assert set(continuity["per_year"].values()) == {"continuous"}
|
||||
first = package["year_charts"][0]
|
||||
mudda = next(row for row in first["interval"]["dasha_years"] if row["system"] == "mudda_dasha")
|
||||
assert mudda["days"] == 365.25
|
||||
assert first["interval"]["solar_return_interval"]["end"] == first["validity"]["end"]
|
||||
# The 365.25-day Mudda year ends before the next actual return: a hole of
|
||||
# a few minutes between two years' Mudda windows, reported, not hidden.
|
||||
across = continuity["mudda_across_years"]
|
||||
assert across["status"] == "discontinuous"
|
||||
assert across["gaps"][0]["seconds"] == pytest.approx(-mudda["end_minus_next_return_seconds"], abs=1)
|
||||
assert json.dumps(package, ensure_ascii=False) # still plain JSON
|
||||
|
||||
|
||||
def test_consultation_dasha_rows_carry_full_instants_and_report_gaps() -> None:
|
||||
# 原值: dasha_systems 只给日期(YYYY-MM-DD);Narayana 只比较当前 AD 止与下一 AD 起的日期字符串
|
||||
# 新值: start_at / end_at 带时区的完整时刻;每个体系按完整时刻做连续性检查,有断口时 continuity_issue
|
||||
# 原因: 占星师第三轮审查 2026-11-07
|
||||
zone = timezone(timedelta(hours=-8))
|
||||
periods = [
|
||||
{"sign": "Leo", "start": "2020-01-01T10:00:00", "end": "2026-12-08T01:00:00"},
|
||||
{"sign": "Virgo", "start": "2026-12-08T09:00:00", "end": "2030-01-01T00:00:00"},
|
||||
]
|
||||
row = cnl._timeline_row("chara", periods, {"ascendant": {"sign": "Aries"}}, {}, "2026-11-07", tz=zone)
|
||||
assert row["md"]["start"] == "2020-01-01" and row["md"]["start_at"] == "2020-01-01T10:00:00-08:00"
|
||||
issue = row["continuity_issue"][0]
|
||||
assert issue["status"] == "discontinuous" and issue["gaps"][0]["seconds"] == 8 * 3600
|
||||
dates = cnl._narayana_dates(datetime(1955, 2, 24, 19, 15), {"start_age": 71.0, "end_age": 72.0}, zone)
|
||||
assert dates["start"] == "2026-02-24" and dates["start_at"].endswith("-08:00")
|
||||
Reference in New Issue
Block a user