Three-way parity audit 2026-11-07 (U ea2a9d65 / F frozen / P f70ae94e):
- Vimsopaka: look vargas up by "D{n}_" prefix (D60 key was misspelt, every
D60 fell to Neutral) and score only the sign-owner relation (upstream
ab5b8709, BPHS 7.21-27). All 16 varga scores now equal U on 3 charts.
- Narayana: age = total_seconds / (86400 x 365.25) keeping the birth time
(upstream ab5b8709); Rath rows carry start_date / end_date from the
unrounded ages; consult layer, report facts, API and calendar read them.
- Ascendant degree_raw / lon unrounded (engine and chart API).
- position_mode label: legacy is the apparent frame since BUG-1275; the
profile and module labels now say "apparent" (legacy still accepted).
- Functional profile label v2 -> v3_166q4 (the table actually used).
- full-reading Sade Sati uses the dated transit Saturn (upstream e628118d):
Jobs 2026-11-07 peak, owner / Obama not active, as U.
Consult evidence card golden recaptured.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
746 lines
33 KiB
Python
746 lines
33 KiB
Python
"""Facts for the model-written reading at the front of the report (issue #113 R1).
|
||
|
||
The reading is written by a model, but only from what the engine already
|
||
computed. This module copies the consult-card leaves (the same facts the chat
|
||
uses) from the report's own full-data packet and adds the rest of the
|
||
calculation the astrologer's skill asks a reading to stand on.
|
||
|
||
产品 2026-11-07 占星师方案 item 10 (reading_facts contract): one contract with
|
||
birth parameters, all houses, every domain's vargas, lords, functional roles,
|
||
yogas with their conditions, all current dasha layers (Vimshottari and
|
||
Narayana with dates, plus every other family's current period and status),
|
||
transits, strengths, Ashtakavarga, KP, Jaimini, the annual chart, evidence
|
||
paths, method differences and blocked states. Nothing here is a new
|
||
algorithm: values are packet leaves, a date is the birth date plus the age the
|
||
packet gives, and a conflict is a comparison of two packet values.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import copy
|
||
from datetime import date, timedelta
|
||
from typing import Any
|
||
|
||
try:
|
||
from scripts.consult_card_domain_facts import (
|
||
PLANETS,
|
||
PRECISION_SENTENCE,
|
||
PRECISION_VARGA,
|
||
_house_record,
|
||
_varga_chart,
|
||
_varga_planet_path,
|
||
assert_fact_leaves,
|
||
build_consult_card_facts,
|
||
dig,
|
||
)
|
||
from scripts.consult_full_data_cache import _attach_graha_drishti
|
||
from scripts.pl9_full_data_export import full_data_domain_base, read_full_data_domain
|
||
except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path
|
||
from consult_card_domain_facts import (
|
||
PLANETS,
|
||
PRECISION_SENTENCE,
|
||
PRECISION_VARGA,
|
||
_house_record,
|
||
_varga_chart,
|
||
_varga_planet_path,
|
||
assert_fact_leaves,
|
||
build_consult_card_facts,
|
||
dig,
|
||
)
|
||
from consult_full_data_cache import _attach_graha_drishti
|
||
from pl9_full_data_export import full_data_domain_base, read_full_data_domain
|
||
|
||
# 原值:report-reading-facts-v1(只有 varga / houses / planets_in_varga / significators 与 Vimshottari)
|
||
# 新值:v2,按占星师方案 item 10 的完整契约
|
||
# 原因:产品 2026-11-07 占星师方案:报告完整运行 skill、导出保留审计
|
||
READING_FACTS_SCHEMA = "report-reading-facts-v2"
|
||
READING_DOMAINS = ("general", "career", "wealth", "marriage", "health")
|
||
TIMING = "worksheets.timing_and_predictive_systems"
|
||
DASHA = f"{TIMING}.dasha.current_dasha"
|
||
NARAYANA = f"{TIMING}.narayana_dasha"
|
||
FAMILIES = f"{TIMING}.dasha_master_pack.families"
|
||
TRANSIT = f"{TIMING}.transit_positions"
|
||
TRANSIT_REF = f"{TIMING}.transit_multi_reference"
|
||
DOUBLE_TRANSIT = f"{TIMING}.double_transit_pac"
|
||
ANNUAL = f"{TIMING}.annual_tajika_pack"
|
||
FUNCTIONAL = "worksheets.strengths_and_scores.functional_benefic_malefic"
|
||
ASHTAKAVARGA = "worksheets.strengths_and_scores.ashtakavarga"
|
||
VIMSOPAKA = "worksheets.strengths_and_scores.vimsopaka"
|
||
AVASTHA = "worksheets.advanced_systems.avasthas"
|
||
KP = "worksheets.advanced_systems.kp"
|
||
JAIMINI = "worksheets.advanced_systems.jaimini"
|
||
YOGA = "worksheets.advanced_systems.yoga"
|
||
SADE_SATI = "worksheets.advanced_systems.yogas_doshas.sade_sati"
|
||
LAGNAS = "worksheets.divisional_and_special_charts.special_lagnas"
|
||
LEDGER = "full_report_pack.sections.d1_d60_ledger"
|
||
UPCOMING_SUB_PERIODS = 2
|
||
UPCOMING_NARAYANA = 2
|
||
SLOW_TRANSITS = ("Jupiter", "Saturn", "Rahu", "Ketu")
|
||
NATURAL_BENEFICS = ("Jupiter", "Venus", "Mercury", "Moon")
|
||
PRECISION_POINTS = ("Ghati_Lagna", "ViGhati_Lagna", "Pranapada_Lagna")
|
||
NOTE_LIMIT = 280
|
||
# Statuses that keep a technique out of the judgment (interpretation_status_contract.md).
|
||
BLOCKED_STATES = {"blocked", "gap", "error", "missing"}
|
||
CONDITIONAL_STATES = {"parameter_sensitive", "partial", "partial_verified", "conflict", "conditional"}
|
||
|
||
|
||
def _compact(node: Any) -> Any:
|
||
"""Leaf values only. Gaps, withheld and blocked leaves are left out."""
|
||
if isinstance(node, dict):
|
||
if "status" in node and "check" in node:
|
||
return node.get("value") if node["status"] == "value" else None
|
||
out = {}
|
||
for key, value in node.items():
|
||
kept = _compact(value)
|
||
if kept is not None and kept != {} and kept != []:
|
||
out[key] = kept
|
||
return out
|
||
if isinstance(node, list):
|
||
return [item for item in (_compact(entry) for entry in node) if item is not None]
|
||
return node
|
||
|
||
|
||
def _pick(node: Any, keys: tuple[str, ...]) -> dict[str, Any]:
|
||
if not isinstance(node, dict):
|
||
return {}
|
||
return {key: node[key] for key in keys if node.get(key) not in (None, "", [], {})}
|
||
|
||
|
||
def _day(value: Any) -> str | None:
|
||
return value[:10] if isinstance(value, str) and len(value) >= 10 else None
|
||
|
||
|
||
def _period(row: Any) -> dict[str, Any] | None:
|
||
if not isinstance(row, dict) or not isinstance(row.get("lord"), str):
|
||
return None
|
||
out = {"lord": row["lord"]}
|
||
for key in ("start", "end"):
|
||
if isinstance(row.get(key), str):
|
||
out[key] = row[key]
|
||
return out
|
||
|
||
|
||
def _vimshottari(packet: dict) -> dict[str, Any]:
|
||
current = dig(packet, DASHA)
|
||
if not isinstance(current, dict):
|
||
return {}
|
||
dates: dict[str, Any] = {}
|
||
md = _period(current)
|
||
if md:
|
||
dates["mahadasha"] = md
|
||
rows = current.get("antardasha_timeline")
|
||
if isinstance(rows, list):
|
||
index = next((i for i, row in enumerate(rows) if isinstance(row, dict) and row.get("is_current") is True), None)
|
||
if index is not None:
|
||
now = _period(rows[index])
|
||
if now:
|
||
dates["antardasha"] = now
|
||
nested = rows[index].get("pratyantar_dasha_timeline")
|
||
if isinstance(nested, list):
|
||
pd = next((_period(item) for item in nested if isinstance(item, dict) and item.get("is_current") is True), None)
|
||
if pd:
|
||
dates["pratyantardasha"] = pd
|
||
upcoming = [_period(row) for row in rows[index + 1:index + 1 + UPCOMING_SUB_PERIODS]]
|
||
dates["next_antardashas"] = [row for row in upcoming if row]
|
||
return dates
|
||
|
||
|
||
def _birth_date(packet: dict) -> date | None:
|
||
raw = dig(packet, "birth_info.date")
|
||
try:
|
||
return date.fromisoformat(str(raw)[:10])
|
||
except (TypeError, ValueError):
|
||
return None
|
||
|
||
|
||
def _age_date(birth: date | None, age: Any) -> str | None:
|
||
"""Birth date plus an age in years: whole years land on the birthday."""
|
||
if birth is None or not isinstance(age, (int, float)) or isinstance(age, bool) or age < 0:
|
||
return None
|
||
whole = int(age)
|
||
try:
|
||
anchor = birth.replace(year=birth.year + whole)
|
||
except ValueError: # 29 February
|
||
anchor = birth.replace(year=birth.year + whole, day=28)
|
||
return (anchor + timedelta(days=round((age - whole) * 365.2425))).isoformat()
|
||
|
||
|
||
def _narayana_row(row: Any, birth: date | None) -> dict[str, Any] | None:
|
||
if not isinstance(row, dict) or not isinstance(row.get("sign"), str):
|
||
return None
|
||
out = _pick(row, ("sign", "lord", "start_age", "end_age"))
|
||
# The Rath rows carry engine dates from the unrounded ages (三方对照 2026-11-07);
|
||
# the legacy rows do not, and keep the birthday-anchored conversion.
|
||
if isinstance(row.get("start_date"), str) and isinstance(row.get("end_date"), str):
|
||
start, end = row["start_date"][:10], row["end_date"][:10]
|
||
else:
|
||
start, end = _age_date(birth, row.get("start_age")), _age_date(birth, row.get("end_age"))
|
||
if start and end:
|
||
out["start"], out["end"] = start, end
|
||
return out
|
||
|
||
|
||
def _following(rows: Any, current: dict | None, birth: date | None, count: int) -> list[dict[str, Any]]:
|
||
if not isinstance(rows, list) or not current:
|
||
return []
|
||
index = next((i for i, row in enumerate(rows) if isinstance(row, dict)
|
||
and row.get("sign") == current.get("sign") and row.get("start_age") == current.get("start_age")), None)
|
||
if index is None:
|
||
return []
|
||
following = [_narayana_row(row, birth) for row in rows[index + 1:index + 1 + count]]
|
||
return [row for row in following if row]
|
||
|
||
|
||
def _narayana(packet: dict) -> dict[str, Any]:
|
||
"""Sanjay Rath Narayana (product default) with dates, and the legacy one beside it."""
|
||
node = dig(packet, NARAYANA)
|
||
if not isinstance(node, dict):
|
||
return {}
|
||
birth = _birth_date(packet)
|
||
current = node.get("current_dasha") if isinstance(node.get("current_dasha"), dict) else {}
|
||
out: dict[str, Any] = {
|
||
**_pick(node, ("profile", "algorithm_label", "direction_text", "status")),
|
||
"date_basis": "birth_date_plus_age",
|
||
}
|
||
md = _narayana_row(current.get("md"), birth)
|
||
ad = _narayana_row(current.get("ad"), birth)
|
||
if md:
|
||
out["mahadasha"] = md
|
||
out["next_mahadashas"] = _following(node.get("mahadasha"), md, birth, UPCOMING_NARAYANA)
|
||
if ad:
|
||
out["antardasha"] = ad
|
||
out["next_antardashas"] = _following(node.get("current_md_antardasha"), ad, birth, UPCOMING_SUB_PERIODS)
|
||
legacy = node.get("legacy") if isinstance(node.get("legacy"), dict) else {}
|
||
legacy_md = _narayana_row(dig(legacy, "current_dasha.md"), birth)
|
||
if legacy_md:
|
||
out["legacy_comparison"] = {"mahadasha": legacy_md, **_pick(legacy, ("algorithm_label",))}
|
||
return out
|
||
|
||
|
||
def _current_row(rows: Any, today: str) -> tuple[int, dict] | None:
|
||
if not isinstance(rows, list):
|
||
return None
|
||
for index, row in enumerate(rows):
|
||
if not isinstance(row, dict):
|
||
continue
|
||
start, end = _day(row.get("start") or row.get("start_date")), _day(row.get("end") or row.get("end_date"))
|
||
if start and end and start <= today < end:
|
||
return index, row
|
||
return None
|
||
|
||
|
||
def _family_period(row: dict) -> dict[str, Any]:
|
||
out = _pick(row, ("lord", "sign"))
|
||
if not out.get("lord") and isinstance(row.get("planet"), str):
|
||
out["lord"] = row["planet"]
|
||
if not out.get("sign") and isinstance(row.get("rashi"), str):
|
||
out["sign"] = row["rashi"]
|
||
for key, alt in (("start", "start_date"), ("end", "end_date")):
|
||
value = _day(row.get(key) or row.get(alt))
|
||
if value:
|
||
out[key] = value
|
||
return out
|
||
|
||
|
||
def _dasha_families(packet: dict, today: str) -> list[dict[str, Any]]:
|
||
"""Every dasha family the engine ran: status and its running period on `today`."""
|
||
families = dig(packet, FAMILIES)
|
||
if not isinstance(families, dict):
|
||
return []
|
||
out = []
|
||
for name, family in families.items():
|
||
if not isinstance(family, dict):
|
||
continue
|
||
row: dict[str, Any] = {"family": name, **_pick(family, ("status", "execution_status"))}
|
||
found = _current_row(family.get("periods"), today)
|
||
if found:
|
||
period = found[1]
|
||
row["current"] = _family_period(period)
|
||
sub = _current_row(period.get("antardasha"), today)
|
||
if sub:
|
||
row["current_sub"] = _family_period(sub[1])
|
||
elif family.get("reason"):
|
||
row["reason"] = str(family["reason"])[:NOTE_LIMIT]
|
||
out.append(row)
|
||
return out
|
||
|
||
|
||
def _functional(packet: dict) -> dict[str, Any]:
|
||
table = dig(packet, FUNCTIONAL)
|
||
if not isinstance(table, dict):
|
||
return {"status": "blocked"}
|
||
out = _pick(table, (
|
||
"status", "lagna_lord", "functional_benefics", "functional_malefics",
|
||
"functional_neutrals", "yogakarakas", "owned_houses", "effect_on_confidence",
|
||
))
|
||
benefic = set(table.get("functional_benefics") or []) | set(table.get("yogakarakas") or [])
|
||
malefic = set(table.get("functional_malefics") or [])
|
||
conflicts = []
|
||
for planet in PLANETS:
|
||
if planet in ("Rahu", "Ketu"):
|
||
continue
|
||
natural = "benefic" if planet in NATURAL_BENEFICS else "malefic"
|
||
functional = "benefic" if planet in benefic else "malefic" if planet in malefic else None
|
||
if functional and functional != natural:
|
||
conflicts.append({"planet": planet, "natural": natural, "functional": functional})
|
||
out["natural_vs_functional_conflicts"] = conflicts
|
||
return out
|
||
|
||
|
||
def _avastha(packet: dict, name: str) -> dict[str, Any]:
|
||
states = dig(packet, f"{AVASTHA}.{name}.avasthas")
|
||
if not isinstance(states, dict):
|
||
return {}
|
||
return {key: row["state"] for key, row in states.items() if isinstance(row, dict) and isinstance(row.get("state"), str)}
|
||
|
||
|
||
def _kp_lords(node: Any) -> dict[str, Any]:
|
||
lords = node.get("kp_lords") if isinstance(node, dict) else None
|
||
return _pick(lords, ("sign", "rasi_lord", "nakshatra", "nakshatra_lord", "sub_lord", "sub_sub_lord"))
|
||
|
||
|
||
def _planet_extras(packet: dict, name: str) -> dict[str, Any]:
|
||
extra: dict[str, Any] = {"natural": "benefic" if name in NATURAL_BENEFICS else "malefic"}
|
||
owned = dig(packet, f"{FUNCTIONAL}.owned_houses.{name}")
|
||
if isinstance(owned, list) and owned:
|
||
extra["owns_houses"] = owned
|
||
degree = dig(packet, f"core_chart.planets.{name}.degree_in_sign")
|
||
if isinstance(degree, (int, float)) and not isinstance(degree, bool):
|
||
extra["d1_degree"] = round(float(degree), 2)
|
||
for key in ("nakshatra", "retrograde"):
|
||
value = dig(packet, f"core_chart.planets.{name}.{key}")
|
||
if value not in (None, ""):
|
||
extra[key] = value
|
||
avastha = _avastha(packet, name)
|
||
if avastha:
|
||
extra["avastha"] = avastha
|
||
vimsopaka = dig(packet, f"{VIMSOPAKA}.{name}")
|
||
if isinstance(vimsopaka, dict):
|
||
extra["vimsopaka"] = _pick(vimsopaka, ("total_score", "category"))
|
||
kp = _kp_lords(dig(packet, f"{KP}.planets.{name}"))
|
||
if kp:
|
||
extra["kp"] = kp
|
||
return extra
|
||
|
||
|
||
def _houses(view: dict, packet: dict) -> dict[str, Any]:
|
||
out = {}
|
||
for number in range(1, 13):
|
||
record = _compact(_house_record(view, number))
|
||
cusp = _kp_lords(dig(packet, f"{KP}.houses.{number}"))
|
||
if cusp:
|
||
record["kp_cusp"] = cusp
|
||
out[str(number)] = record
|
||
return out
|
||
|
||
|
||
def _participation(rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[str]]:
|
||
"""Each technique's state for the domain; small values ride along."""
|
||
out, not_executed = [], []
|
||
for item in rows:
|
||
if not isinstance(item, dict) or not isinstance(item.get("id"), str):
|
||
continue
|
||
status = item.get("status")
|
||
state = {"value": "executed", "withheld": "withheld"}.get(str(status), "blocked")
|
||
row: dict[str, Any] = {"id": item["id"], "state": state}
|
||
value = item.get("value")
|
||
if state == "executed" and isinstance(value, (str, int, float, bool)):
|
||
row["value"] = value
|
||
if state == "withheld":
|
||
row["reason"] = PRECISION_SENTENCE
|
||
if isinstance(item.get("citation"), str):
|
||
row["source"] = item["citation"]
|
||
if state != "executed":
|
||
not_executed.append(item["id"])
|
||
out.append(row)
|
||
return out, not_executed
|
||
|
||
|
||
def _domain_factors(row: dict) -> list[dict[str, Any]]:
|
||
factors = []
|
||
for factor in row.get("factors") or []:
|
||
if isinstance(factor, dict) and factor.get("kind") == "planet" and isinstance(factor.get("planet"), str):
|
||
factors.append({"role": factor.get("role"), "planet": factor["planet"]})
|
||
return factors
|
||
|
||
|
||
SIGN_ORDER = ("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio",
|
||
"Sagittarius", "Capricorn", "Aquarius", "Pisces")
|
||
|
||
|
||
def _varga_signs(view: dict, code: str, minute_confirmed: bool) -> Any:
|
||
"""The varga as the packet holds it: ascendant sign, each planet's sign and dignity.
|
||
|
||
A house the packet does not give is counted whole-sign from that varga's
|
||
own ascendant (``house_basis``); nothing else is derived.
|
||
"""
|
||
if code in PRECISION_VARGA and not minute_confirmed:
|
||
return PRECISION_SENTENCE
|
||
chart, chart_path = _varga_chart(view, code)
|
||
if not chart_path or not isinstance(chart, dict):
|
||
return None
|
||
ascendant = chart.get("Ascendant") if isinstance(chart.get("Ascendant"), dict) else chart.get("ascendant")
|
||
asc_sign = ascendant.get("sign") if isinstance(ascendant, dict) else None
|
||
out: dict[str, Any] = {"ascendant": asc_sign} if asc_sign else {}
|
||
dignities = chart.get("_dignity") if isinstance(chart.get("_dignity"), dict) else {}
|
||
for planet in PLANETS:
|
||
path = _varga_planet_path(chart_path, chart, planet)
|
||
node = dig(view, path) if path else None
|
||
if not isinstance(node, dict) or not node.get("sign"):
|
||
continue
|
||
row = {"sign": node["sign"]}
|
||
house = node.get("house")
|
||
if not isinstance(house, int) and asc_sign in SIGN_ORDER and node["sign"] in SIGN_ORDER:
|
||
house = (SIGN_ORDER.index(node["sign"]) - SIGN_ORDER.index(asc_sign)) % 12 + 1
|
||
out["house_basis"] = "whole_sign_from_varga_ascendant"
|
||
if isinstance(house, int):
|
||
row["house"] = house
|
||
dignity = dignities.get(planet) or node.get("dignity")
|
||
if isinstance(dignity, str) and dignity:
|
||
row["dignity"] = dignity
|
||
out[planet] = row
|
||
return out
|
||
|
||
|
||
def _domain(row: dict, view: dict, shared: set[str]) -> dict[str, Any]:
|
||
primary = row["domain_varga"]
|
||
vargas = list(row.get("domain_vargas") or [primary])
|
||
varga_houses: dict[str, dict[str, Any]] = {}
|
||
for code in vargas:
|
||
houses = {}
|
||
for planet, record in row["planets"].items():
|
||
leaves = record.get("domain_varga_houses") or {}
|
||
leaf = leaves.get(code) if code in leaves else (record.get("domain_varga_house") if code == primary else None)
|
||
house = _compact(leaf)
|
||
if house is not None:
|
||
houses[planet] = house
|
||
if houses:
|
||
varga_houses[code] = houses
|
||
participation, not_executed = _participation(
|
||
[item for item in row.get("participation") or [] if item.get("id") not in shared]
|
||
)
|
||
charts = {code: chart for code in vargas if (chart := _varga_signs(view, code, row["minute_confirmed"])) is not None}
|
||
return {
|
||
"varga": primary,
|
||
"vargas": vargas,
|
||
"houses": _compact(row["houses"]),
|
||
"planets_in_varga": varga_houses.get(primary, {}),
|
||
"varga_charts": charts,
|
||
"significators": _domain_factors(row),
|
||
"participation": participation,
|
||
"not_executed": not_executed,
|
||
}
|
||
|
||
|
||
def _special_points(packet: dict, minute_confirmed: bool) -> dict[str, Any]:
|
||
out: dict[str, Any] = {}
|
||
lagnas = dig(packet, LAGNAS)
|
||
if isinstance(lagnas, dict):
|
||
for key, node in lagnas.items():
|
||
if not isinstance(node, dict) or not node.get("sign"):
|
||
continue
|
||
if key in PRECISION_POINTS and not minute_confirmed:
|
||
out[key] = PRECISION_SENTENCE
|
||
continue
|
||
out[key] = _pick(node, ("sign", "house"))
|
||
padas = dig(packet, f"{JAIMINI}.arudha_padas.padas")
|
||
if isinstance(padas, dict):
|
||
out["arudha_padas"] = {
|
||
key: _pick(node, ("sign", "house_num", "lord"))
|
||
for key, node in sorted(padas.items())
|
||
if isinstance(node, dict) and node.get("sign")
|
||
}
|
||
return out
|
||
|
||
|
||
def _jaimini(packet: dict) -> dict[str, Any]:
|
||
out: dict[str, Any] = {}
|
||
for scheme, folder, key in (("7", "chara_karaka_7", "karaka_table"), ("8", "chara_karaka_8", "karaka_table_8")):
|
||
table = dig(packet, f"{JAIMINI}.{folder}.{key}")
|
||
if isinstance(table, dict):
|
||
out[f"karakas_{scheme}"] = {
|
||
role: node["planet"] for role, node in table.items()
|
||
if isinstance(node, dict) and isinstance(node.get("planet"), str)
|
||
}
|
||
karakamsha = dig(packet, f"{JAIMINI}.karakamsha")
|
||
if isinstance(karakamsha, dict):
|
||
out["karakamsha"] = _pick(karakamsha, ("karakamsha_sign", "karakamsha_lord"))
|
||
chara = dig(packet, f"{JAIMINI}.chara_dasha")
|
||
if isinstance(chara, dict):
|
||
out["chara_dasha"] = _pick(chara, ("method", "capability_status", "variant_profile", "variant_profile_status"))
|
||
return out
|
||
|
||
|
||
def _yogas(packet: dict) -> list[dict[str, Any]]:
|
||
rows = dig(packet, f"{YOGA}.yogas")
|
||
if not isinstance(rows, list):
|
||
return []
|
||
out = []
|
||
for row in rows:
|
||
if not isinstance(row, dict) or not row.get("name"):
|
||
continue
|
||
out.append({
|
||
**_pick(row, ("name", "name_cn", "category", "source", "planets")),
|
||
# The detector's own wording of the rule it matched (成立条件).
|
||
**({"conditions": row["combination"]} if row.get("combination") else {}),
|
||
**({"detector_strength": row["strength"]} if row.get("strength") else {}),
|
||
# Matched by rule; cancellation and real events are not checked.
|
||
"state": "candidate",
|
||
})
|
||
return out
|
||
|
||
|
||
def _transits(packet: dict) -> dict[str, Any]:
|
||
out: dict[str, Any] = {}
|
||
positions = dig(packet, TRANSIT)
|
||
if isinstance(positions, dict):
|
||
out.update(_pick(positions, ("target_date", "ayanamsa", "node_mode")))
|
||
planets = positions.get("planets") if isinstance(positions.get("planets"), dict) else {}
|
||
out["planets"] = {}
|
||
for name in PLANETS:
|
||
node = planets.get(name)
|
||
if not isinstance(node, dict):
|
||
continue
|
||
row = _pick(node, ("sign", "retrograde"))
|
||
if isinstance(node.get("degree_in_sign"), (int, float)):
|
||
row["degree_in_sign"] = round(float(node["degree_in_sign"]), 2)
|
||
houses = dig(packet, f"{TRANSIT_REF}.transit_analysis.{name}.house_from_ref")
|
||
if isinstance(houses, dict):
|
||
row["house_from"] = houses
|
||
out["planets"][name] = row
|
||
divergences = dig(packet, f"{TRANSIT_REF}.divergences")
|
||
if isinstance(divergences, list):
|
||
out["reference_divergences"] = [
|
||
_pick(row, ("planet", "houses")) for row in divergences
|
||
if isinstance(row, dict) and row.get("planet") in SLOW_TRANSITS
|
||
]
|
||
sade = dig(packet, SADE_SATI)
|
||
if isinstance(sade, dict):
|
||
out["sade_sati"] = _pick(sade, ("is_active", "phase", "moon_sign", "phases"))
|
||
double = dig(packet, DOUBLE_TRANSIT)
|
||
if isinstance(double, dict):
|
||
out["double_transit"] = {
|
||
**_pick(double, ("status", "summary", "event_house", "transit_date", "claim_boundary")),
|
||
"hits": [
|
||
_pick(row, ("layer", "target", "strength"))
|
||
for row in (double.get("double_transit") or []) if isinstance(row, dict)
|
||
][:8],
|
||
}
|
||
return out
|
||
|
||
|
||
def _annual(packet: dict) -> dict[str, Any]:
|
||
pack = dig(packet, ANNUAL)
|
||
if not isinstance(pack, dict):
|
||
return {"status": "blocked"}
|
||
out: dict[str, Any] = {}
|
||
target = dig(pack, "profile.target_year")
|
||
if target is not None:
|
||
out["target_year"] = target
|
||
muntha = dig(pack, "muntha.data")
|
||
if isinstance(muntha, dict):
|
||
out["muntha"] = {**_pick(muntha, ("muntha_sign", "muntha_lord")), **_pick(pack.get("muntha"), ("status",))}
|
||
year_lord = dig(pack, "year_lord.data")
|
||
if isinstance(year_lord, dict):
|
||
out["year_lord"] = {
|
||
**_pick(year_lord, ("year_lord", "year_lord_sign", "year_lord_house", "annual_asc_sign")),
|
||
**_pick(pack.get("year_lord"), ("status",)),
|
||
}
|
||
periods = dig(pack, "mudda_dasha.periods")
|
||
if isinstance(periods, list):
|
||
out["mudda_dasha"] = [
|
||
{**_pick(row, ("lord",)), **{key: _day(row.get(key)) for key in ("start", "end") if _day(row.get(key))}}
|
||
for row in periods if isinstance(row, dict)
|
||
]
|
||
return out
|
||
|
||
|
||
def _clean_note(note: Any) -> str:
|
||
text = str(note or "")
|
||
return text if len(text) <= NOTE_LIMIT else text[:NOTE_LIMIT] + "…"
|
||
|
||
|
||
def _evidence(packet: dict) -> dict[str, Any]:
|
||
audit = packet.get("technique_audit_table") if isinstance(packet.get("technique_audit_table"), list) else []
|
||
ledger = dig(packet, LEDGER)
|
||
summary = ledger.get("summary") if isinstance(ledger, dict) and isinstance(ledger.get("summary"), dict) else {}
|
||
gate = packet.get("report_quality_gate") if isinstance(packet.get("report_quality_gate"), dict) else {}
|
||
return {
|
||
"technique_audit": [
|
||
{"technique": row.get("technique"), "status": row.get("status"), "note": _clean_note(row.get("note"))}
|
||
for row in audit if isinstance(row, dict) and row.get("technique")
|
||
],
|
||
"d1_d60_ledger": {
|
||
**_pick(ledger, ("status",)),
|
||
**_pick(summary, ("formal_traditional_division_count", "research_generic_dn_division_count")),
|
||
"boundary": "D-N research rows are raw data only; they cannot carry a thematic conclusion.",
|
||
},
|
||
**({"report_quality_gate": gate.get("status")} if gate.get("status") else {}),
|
||
# Where each layer lives in the report's own packet (evidence paths).
|
||
"evidence_paths": {
|
||
"functional": FUNCTIONAL,
|
||
"vimshottari": DASHA,
|
||
"narayana": NARAYANA,
|
||
"dasha_families": FAMILIES,
|
||
"transits": TRANSIT,
|
||
"transit_references": TRANSIT_REF,
|
||
"double_transit": DOUBLE_TRANSIT,
|
||
"ashtakavarga": ASHTAKAVARGA,
|
||
"shadbala": "worksheets.strengths_and_scores.shadbala",
|
||
"kp": KP,
|
||
"jaimini": JAIMINI,
|
||
"yogas": f"{YOGA}.yogas",
|
||
"annual": ANNUAL,
|
||
"d1_d60_ledger": LEDGER,
|
||
"technique_audit": "technique_audit_table",
|
||
},
|
||
}
|
||
|
||
|
||
def _method_differences(packet: dict, narayana: dict, functional: dict, transits: dict) -> list[dict[str, Any]]:
|
||
"""Places where two methods or two parameters give different answers."""
|
||
out: list[dict[str, Any]] = []
|
||
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
|
||
kp_profile = dig(packet, f"{KP}.kp_profile")
|
||
if isinstance(kp_profile, dict) and kp_profile.get("house_system") != profile.get("house_system"):
|
||
out.append({
|
||
"topic": "kp_vs_parashari_houses",
|
||
"parashari": _pick(profile, ("ayanamsa", "house_system")),
|
||
"kp": _pick(kp_profile, ("ayanamsa", "house_system", "status")),
|
||
"note": "KP cusps (Placidus, KP ayanamsa) can put a planet in a different house than whole-sign houses.",
|
||
})
|
||
legacy = dig(narayana, "legacy_comparison.mahadasha")
|
||
current = narayana.get("mahadasha")
|
||
if isinstance(legacy, dict) and isinstance(current, dict) and legacy.get("sign") != current.get("sign"):
|
||
out.append({"topic": "narayana_variant", "default": current, "legacy": legacy})
|
||
for row in functional.get("natural_vs_functional_conflicts") or []:
|
||
out.append({"topic": "natural_vs_functional", **row})
|
||
for row in transits.get("reference_divergences") or []:
|
||
out.append({"topic": "transit_reference_points", **row})
|
||
if dig(packet, "worksheets.strengths_and_scores.shadbala") not in (None, {}, []):
|
||
out.append({
|
||
"topic": "shadbala_components",
|
||
"note": "Shadbala follows the component method the astrologer chose (#166); other software can flip whether a planet meets its minimum.",
|
||
})
|
||
return out
|
||
|
||
|
||
def _blocked_states(
|
||
domains: dict, shared: list[dict], families: list[dict], evidence: dict, transits: dict, annual: dict,
|
||
) -> dict[str, Any]:
|
||
labels: dict[str, list[str]] = {"blocked": [], "parameter_sensitive": [], "not_applicable": [], "withheld": []}
|
||
for name, row in domains.items():
|
||
for item in [*(row.get("participation") or []), *(shared if name == "general" else [])]:
|
||
if item["state"] == "blocked":
|
||
labels["blocked"].append(f"{name}:{item['id']}")
|
||
elif item["state"] == "withheld":
|
||
labels["withheld"].append(f"{name}:{item['id']}")
|
||
for family in families:
|
||
status = str(family.get("status") or "")
|
||
if status in BLOCKED_STATES:
|
||
labels["blocked"].append(f"dasha:{family['family']}")
|
||
elif status == "not_applicable":
|
||
labels["not_applicable"].append(f"dasha:{family['family']}")
|
||
elif status in CONDITIONAL_STATES:
|
||
labels["parameter_sensitive"].append(f"dasha:{family['family']}")
|
||
for row in evidence.get("technique_audit") or []:
|
||
status = str(row.get("status") or "")
|
||
if status in BLOCKED_STATES:
|
||
labels["blocked"].append(f"audit:{row['technique']}")
|
||
elif status in CONDITIONAL_STATES:
|
||
labels["parameter_sensitive"].append(f"audit:{row['technique']}")
|
||
if not transits.get("planets"):
|
||
labels["blocked"].append("transits")
|
||
if annual.get("status") == "blocked":
|
||
labels["blocked"].append("annual")
|
||
labels["parameter_sensitive"].append("kp")
|
||
return {key: value for key, value in labels.items() if value}
|
||
|
||
|
||
def _birth_parameters(packet: dict, minute_confirmed: bool) -> dict[str, Any]:
|
||
"""The chart's calculation inputs. No name and no coordinates."""
|
||
birth = packet.get("birth_info") if isinstance(packet.get("birth_info"), dict) else {}
|
||
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
|
||
return {
|
||
**_pick(birth, ("date", "time", "tz")),
|
||
**_pick(profile, ("ayanamsa", "node_mode", "house_system", "position_mode", "dasha_year_days")),
|
||
"minute_confirmed": minute_confirmed,
|
||
}
|
||
|
||
|
||
def build_report_reading_facts(
|
||
packet: dict,
|
||
full_reading: dict,
|
||
*,
|
||
minute_confirmed: bool,
|
||
today: str | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Packet-sourced facts for the reading. Raises on any non-packet consult leaf."""
|
||
working = _attach_graha_drishti(copy.deepcopy(packet), full_reading)
|
||
# One detached copy of the packet serves every domain's facts and their leaf check (issue #122).
|
||
base = full_data_domain_base(working)
|
||
raw = build_consult_card_facts(working, list(READING_DOMAINS), minute_confirmed=minute_confirmed, base=base)
|
||
rows = {row["domain"]: row for row in raw["domains"]}
|
||
for row in rows.values():
|
||
assert_fact_leaves(working, row, base=base)
|
||
general = rows["general"]
|
||
planets = {}
|
||
for name, record in general["planets"].items():
|
||
kept = _compact({key: value for key, value in record.items() if key not in ("domain_varga_house", "domain_varga_houses")})
|
||
if kept.get("present"):
|
||
kept.pop("present")
|
||
planets[name] = {**kept, **_planet_extras(working, name)}
|
||
ids = [{item.get("id") for item in row.get("participation") or []} for row in rows.values()]
|
||
shared = set.intersection(*ids) if ids else set()
|
||
shared_rows, _ = _participation([item for item in general.get("participation") or [] if item.get("id") in shared])
|
||
view = read_full_data_domain(working, "general", base=base)
|
||
domains = {name: _domain(row, view, shared) for name, row in rows.items()}
|
||
ascendant = dig(packet, "core_chart.ascendant")
|
||
reference_day = str(today or dig(packet, f"{TRANSIT}.target_date") or date.today().isoformat())[:10]
|
||
narayana = _narayana(working)
|
||
functional = _functional(working)
|
||
transits = _transits(working)
|
||
families = [
|
||
row for row in _dasha_families(working, reference_day)
|
||
# The dated Narayana is in `timing`; the master pack's copy is not run.
|
||
if not (row["family"] == "narayana" and narayana.get("mahadasha"))
|
||
]
|
||
annual = _annual(working)
|
||
evidence = _evidence(working)
|
||
sav = dig(working, f"{ASHTAKAVARGA}.sav")
|
||
return {
|
||
"schema": READING_FACTS_SCHEMA,
|
||
"minute_confirmed": minute_confirmed,
|
||
**({"today": today} if today else {}),
|
||
"birth_parameters": _birth_parameters(working, minute_confirmed),
|
||
"ascendant": _compact({
|
||
key: {"status": "value", "check": "path", "value": ascendant.get(key)}
|
||
for key in ("sign", "lord", "nakshatra", "degree_in_sign")
|
||
if isinstance(ascendant, dict) and ascendant.get(key) is not None
|
||
}),
|
||
"functional": functional,
|
||
"planets": planets,
|
||
"houses": _houses(view, working),
|
||
# Techniques every domain runs (shadbala, aspects, dashas, transits …), listed once.
|
||
"shared_techniques": shared_rows,
|
||
"domains": domains,
|
||
"special_points": _special_points(working, minute_confirmed),
|
||
"jaimini": _jaimini(working),
|
||
"yogas": _yogas(working),
|
||
"timing": {**_compact(general["timing"]), **_vimshottari(working), "narayana": narayana},
|
||
"dasha_families": families,
|
||
"transits": transits,
|
||
"strengths": {
|
||
"ashtakavarga_sav": _pick(sav, ("total", "expected_total", "valid")),
|
||
"vimsopaka_total": _pick(dig(working, VIMSOPAKA), ("total_score", "total_score_max", "status")),
|
||
},
|
||
"kp": {
|
||
"profile": _pick(dig(working, f"{KP}.kp_profile"), ("ayanamsa", "house_system", "cusp_source", "status")),
|
||
"state": "parameter_sensitive",
|
||
},
|
||
"annual": annual,
|
||
"evidence": evidence,
|
||
"method_differences": _method_differences(working, narayana, functional, transits),
|
||
"blocked_states": _blocked_states(domains, shared_rows, families, evidence, transits, annual),
|
||
}
|