Files
ClaudeandClaude Opus 5.5 8f83eb2c25 fix(report): Kalachakra uses the classical sign periods from the Moon longitude (BUG-1656)
The full reading and the dasha registry called the Kalachakra module without
the Moon longitude, so BUG-1487's PVR ch.24 sign periods never ran in the
product. The report printed the legacy approximation (planet lords, 7..18
years) under a "simplified model" label.

Both callers now pass the Moon longitude. The dasha family carries
method_profile. Classical results keep their own AD/PD rows instead of the
rotated simplified table, and the reader and research tables list signs.
The PyJHora comparison was rerun: majors now agree, sub-period division still
differs (documented).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyeZrYn6ryNcSe5Y2Y
2026-11-06 17:23:21 +08:00

325 lines
13 KiB
Python

"""Attach sourced dasha children onto a master-pack copy.
The natal modules keep their own rows. This module never imports PyJHora.
Kalachakra children are the upstream proportional model, labeled simplified,
and they hang on the majors this repository already calculated.
"""
from __future__ import annotations
import logging
from copy import deepcopy
from datetime import datetime, timedelta
from typing import Any
logger = logging.getLogger(__name__)
def _rotate_cycle_rows(cycle_rows: list[dict], start_rashi: str | None) -> list[dict]:
if not cycle_rows:
return []
if not start_rashi:
return list(cycle_rows)
start_index = next(
(index for index, row in enumerate(cycle_rows) if row.get("rashi") == start_rashi),
0,
)
return list(cycle_rows[start_index:]) + list(cycle_rows[:start_index])
def _build_subperiods(
parent_period: dict,
cycle_rows: list[dict],
total_cycle_years: float,
level_key: str,
year_days: float = 365.25,
) -> list[dict]:
"""Proportional Kalachakra children. Last child ends on the parent end."""
if not cycle_rows:
return []
rotated_rows = _rotate_cycle_rows(cycle_rows, parent_period.get("rashi"))
cycle_basis_total = sum(float(row.get("years") or 0.0) for row in rotated_rows)
denominator = cycle_basis_total if cycle_basis_total > 0 else float(total_cycle_years or 0.0)
if denominator <= 0:
return []
start_dt = datetime.fromisoformat(str(parent_period["start_date"]))
current_dt = start_dt
child_periods = []
for row in rotated_rows:
child_years = float(parent_period["years"]) * float(row["years"]) / denominator
end_dt = current_dt + timedelta(days=child_years * year_days)
child_periods.append({
"level": level_key,
"lord": row.get("lord"),
"rashi": row.get("rashi"),
"sign": row.get("rashi"),
"rashi_index": row.get("rashi_index"),
"years": child_years,
"start_date": current_dt.isoformat(),
"end_date": end_dt.isoformat(),
"status": "parameter_sensitive",
"derivation": "native_kalachakra_recursive_proportional_variant",
"model": "simplified",
})
current_dt = end_dt
if child_periods:
child_periods[-1]["end_date"] = parent_period["end_date"]
return child_periods
def attach_kalachakra_simplified_children(
major_periods: list[dict],
total_cycle_years: float | None = None,
year_days: float = 365.25,
) -> tuple[list[dict], list[dict], list[dict]]:
"""Return a copy of the existing majors with simplified AD and PD rows.
The caller's major rows are not modified. Replacing those majors is out of
scope: if a row has no start_date, this raises instead of inventing one.
"""
majors = deepcopy(major_periods)
cycle_rows = [
{
"lord": row.get("lord"),
"rashi": row.get("rashi"),
"rashi_index": row.get("rashi_index"),
"years": row.get("years"),
}
for row in majors
if isinstance(row, dict)
]
if total_cycle_years is None:
total_cycle_years = sum(float(row.get("years") or 0.0) for row in cycle_rows)
all_antardashas: list[dict] = []
all_pratyantardashas: list[dict] = []
for period in majors:
if not isinstance(period, dict):
continue
antardasha = _build_subperiods(period, cycle_rows, float(total_cycle_years), "antardasha", year_days)
for child in antardasha:
child["parent_lord"] = period.get("lord")
child["parent_rashi"] = period.get("rashi")
child["parent_sign"] = period.get("rashi")
period["antardasha"] = antardasha
all_antardashas.extend(antardasha)
for child in antardasha:
pratyantardasha = _build_subperiods(
child, cycle_rows, float(total_cycle_years), "pratyantardasha", year_days,
)
for grand in pratyantardasha:
grand["parent_lord"] = child.get("lord")
grand["parent_rashi"] = child.get("rashi")
grand["parent_sign"] = child.get("rashi")
grand["main"] = period.get("rashi") or period.get("lord")
grand["parent_antardasha"] = child.get("rashi") or child.get("lord")
child["pratyantardasha"] = pratyantardasha
all_pratyantardashas.extend(pratyantardasha)
return majors, all_antardashas, all_pratyantardashas
def _copy_rows(rows: list[dict]) -> list[dict]:
return deepcopy([row for row in rows if isinstance(row, dict)])
def _narayana_children(module: dict) -> dict[str, list[dict]]:
children_by_parent: dict[str, list[dict]] = {}
boundaries = module.get("dense_boundaries")
if isinstance(boundaries, list):
for row in boundaries:
if not isinstance(row, dict) or row.get("level") != "AD" or not row.get("sign"):
continue
parent = str(row.get("parent_period_key") or row.get("parent_md") or "")
children_by_parent.setdefault(parent, []).append({
"level": "antardasha",
"sign": row.get("sign"),
"lord": row.get("lord"),
"years": row.get("duration_years"),
"start": row.get("start_age"),
"end": row.get("end_age"),
"parent_sign": row.get("parent_md"),
"parent_lord": row.get("parent_md"),
"source": "narayana_dense_boundaries",
})
return children_by_parent
def _rath_narayana_periods(module: dict) -> list[dict]:
"""BUG-1601 (#166 Q9): the product object is Sanjay Rath on top. Its MD
rows are the periods; only the running MD has its ADs (the Rath view
computes them for that MD only). The legacy rows stay under `legacy`."""
current = (module.get("current_dasha") or {}).get("md") or {}
running_ads = [row for row in module.get("current_md_antardasha") or [] if isinstance(row, dict)]
periods = []
for row in module.get("mahadasha") or []:
if not isinstance(row, dict):
continue
is_current = bool(current) and row.get("sign") == current.get("sign") and row.get("start_age") == current.get("start_age")
periods.append({
"sign": row.get("sign"),
"lord": row.get("lord"),
"years": row.get("years"),
"start": row.get("start_age"),
"end": row.get("end_age"),
"antardasha": [{
"level": "antardasha",
"sign": ad.get("sign"),
"lord": ad.get("lord"),
"years": ad.get("years"),
"start": ad.get("start_age"),
"end": ad.get("end_age"),
"parent_sign": row.get("sign"),
"parent_lord": row.get("lord"),
"source": "narayana_rath_current_md_antardasha",
} for ad in running_ads] if is_current else [],
})
return periods
def _narayana_periods(module: dict, rows: list[dict] | None = None) -> list[dict]:
if not rows and isinstance(module.get("mahadasha"), list):
return _rath_narayana_periods(module)
if not rows and isinstance(module.get("legacy"), dict) and not module.get("mahadasha"):
# Rath blocked: no default periods; the legacy rows are not promoted.
return []
children_by_parent = _narayana_children(module)
if rows:
# Keep every field already on the row. Only attach children.
periods = []
for row in rows:
copied = deepcopy(row)
if not (isinstance(copied.get("antardasha"), list) and copied.get("antardasha")):
sign = copied.get("sign") or copied.get("rashi")
parent_key = str(copied.get("period_key") or sign or "")
copied["antardasha"] = children_by_parent.get(parent_key, [])
periods.append(copied)
return periods
sequence = module.get("mahadasha_sequence")
if not isinstance(sequence, list):
return []
periods = []
for row in sequence:
if not isinstance(row, dict):
continue
sign = row.get("sign")
parent_key = str(row.get("period_key") or sign or "")
periods.append({
"sign": sign,
"lord": row.get("lord"),
"years": row.get("years"),
"start": row.get("start_age"),
"end": row.get("end_age"),
"antardasha": children_by_parent.get(parent_key, []),
})
return periods
def _yogini_call_row(row: dict) -> dict:
"""Fields the antardasha formula reads. Nested raw_period fills gaps only."""
source = dict(row)
raw = row.get("raw_period") if isinstance(row.get("raw_period"), dict) else {}
for name in ("yogini", "full_years", "unclipped_start_date", "end_date", "start_date"):
if source.get(name) is None and raw.get(name) is not None:
source[name] = raw[name]
return source
def _yogini_periods(module: dict, rows: list[dict]) -> list[dict]:
if any(isinstance(row.get("antardasha"), list) and row.get("antardasha") for row in rows):
return rows
try:
from yogini_dasha import yogini_antardashas
except ImportError:
from scripts.yogini_dasha import yogini_antardashas
year_days = module.get("dasha_year_days") or 365.25
birth = None
if rows:
birth = rows[0].get("start_date")
if birth is None:
raw = rows[0].get("raw_period") if isinstance(rows[0].get("raw_period"), dict) else {}
birth = raw.get("start_date")
attached = []
for row in rows:
copied = deepcopy(row)
source = _yogini_call_row(copied)
missing = [
name for name in ("yogini", "full_years", "unclipped_start_date", "end_date")
if source.get(name) is None
]
if not birth or missing:
logger.warning(
"yogini antardasha left off for %s: missing %s",
copied.get("yogini"),
",".join(missing) or "start_date",
)
attached.append(copied)
continue
try:
children = yogini_antardashas(source, birth_dt=birth, year_days=float(year_days))
except (KeyError, TypeError, ValueError) as exc:
logger.warning(
"yogini antardasha left off for %s: %s",
copied.get("yogini"),
exc,
)
attached.append(copied)
continue
for child in children:
child["parent_lord"] = copied.get("planet") or copied.get("lord")
child["main"] = copied.get("yogini")
copied["antardasha"] = children
attached.append(copied)
return attached
CLASSICAL_KALACHAKRA_PROFILE = "pvr_classical_nine_sign_md_ad"
def _with_classical_parents(row: dict) -> dict:
"""Name each classical child's parent sign so tables can show the chain."""
if not isinstance(row, dict):
return row
for child in row.get("antardasha") or []:
if isinstance(child, dict):
child.setdefault("parent_lord", row.get("lord"))
child.setdefault("parent_rashi", row.get("rashi"))
child.setdefault("parent_sign", row.get("rashi"))
for grand in child.get("pratyantardasha") or []:
if isinstance(grand, dict):
grand.setdefault("parent_lord", child.get("lord"))
grand.setdefault("parent_rashi", child.get("rashi"))
grand.setdefault("parent_sign", child.get("rashi"))
return row
def enrich_master_family(key: str, module: dict | None, periods: list | None) -> list[dict]:
"""Copy family rows and attach children that already have a sourced rule.
Vimshottari is left untouched: its three layers are rendered from the
dasha timeline, not from this pack.
"""
module = module if isinstance(module, dict) else {}
rows = _copy_rows(periods or [])
if key == "vimshottari":
return rows
if key == "narayana":
return _narayana_periods(module, rows)
if key == "yogini":
return _yogini_periods(module, rows)
if key == "kala_chakra":
if not rows:
return rows
if module.get("method_profile") == CLASSICAL_KALACHAKRA_PROFILE:
# BUG-1656: the classical module already carries PVR ch.24 AD/PD.
# The rotated simplified table would overwrite them.
return [_with_classical_parents(row) for row in rows]
try:
enriched, _ad, _pd = attach_kalachakra_simplified_children(
rows,
module.get("total_cycle"),
)
except (KeyError, TypeError, ValueError) as exc:
logger.warning("kalachakra children left off: %s", exc)
return rows
return enriched
return rows