# /// script # requires-python = ">=3.11" # dependencies = [] # /// # Source: astrologer repository ea2a9d657451cd04615a3a7108dc92666dc8340c. # ─── How to run ─── # .venv/bin/python -m pytest -q tests/test_active_rectification_candidates.py """Sample candidate birth times and group them by material chart differences. This module implements the "Candidate Difference Contract" (candidate-driven rectification plan Task 2). It never approves a birth time. It answers one question only: inside the user's uncertain interval, which minutes are materially the same chart, where do the material boundaries fall, and which technique dimensions actually discriminate between adjacent candidate groups. Design rules: - Every sampled candidate stays inside the user interval (reversed or out-of-bounds intervals are rejected). - Adjacent samples with an identical material signature merge into one group. - Group boundaries are reported as discriminators with from/to values, so a reader can say "08:03 and 08:12 differ because D9 ascendant moves X -> Y". - All results are plain JSON-compatible dictionaries; no prose conclusions. - The shared native calculation path is reused (same as the event engine): domain_calculation_service.compute_chart + varga.calc_all_vargas + jaimini.calc_arudha_padas + dasha_analyzer.lon_to_nakshatra. """ from __future__ import annotations import sys from collections.abc import Sequence from datetime import date, datetime, time, timedelta from pathlib import Path from typing import Final, TypedDict from uuid import NAMESPACE_URL, uuid5 SCRIPTS = Path(__file__).resolve().parents[1] if str(SCRIPTS) not in sys.path: sys.path.insert(0, str(SCRIPTS)) import domain_calculation_service # noqa: E402 import dasha_analyzer # noqa: E402 import jaimini # noqa: E402 import narayana_dasha # noqa: E402 import varga # noqa: E402 SCHEMA_VERSION: Final = "jyotish.active_rectification_candidates.v1" # Divisions whose ascendant sign we fingerprint. Classical local path is the # same production line the event engine uses for its evidence rows. RELEVANT_DIVISIONS: Final[tuple[int, ...]] = (2, 3, 4, 7, 9, 10, 11, 12, 24, 30, 60) # Arudha padas tracked as derived points: A1 = arudha lagna (self), A7 = spouse, # A10 = career visibility, UL = upapada (marriage visibility). TRACKED_ARUDHAS: Final[tuple[str, ...]] = ("A1", "A7", "A10", "UL") MAX_WINDOW_MINUTES: Final = 240 MAX_SAMPLE_STEP: Final = 15 SIGNS: Final = narayana_dasha.SIGNS FINGERPRINT_DIMENSION_ORDER: Final = ( "lagna_sign", "lagna_nakshatra", "moon_sign", "moon_nakshatra", "vimshottari_md_lord", *(f"varga_asc.D{division}" for division in RELEVANT_DIVISIONS), "arudha.A1", "arudha.A7", "arudha.A10", "arudha.UL", ) def _sign_name(sign_index: int) -> str: return str(SIGNS[sign_index % 12]) class CandidateDifferenceRequest(TypedDict): birth_date: str start_time: str end_time: str lat: float lon: float tz: float ayanamsa: str node_mode: str sample_step_minutes: int def _candidate_times(request: CandidateDifferenceRequest) -> list[datetime]: """Return sampled candidate datetimes strictly inside the user interval.""" birth_date = date.fromisoformat(request["birth_date"]) try: start_time = time.fromisoformat(request["start_time"]) end_time = time.fromisoformat(request["end_time"]) except ValueError as exc: raise ValueError("candidate_times_invalid_format") from exc step = int(request.get("sample_step_minutes", 1)) if step < 1 or step > MAX_SAMPLE_STEP: raise ValueError("candidate_sample_step_out_of_bounds") start = datetime.combine(birth_date, start_time) end = datetime.combine(birth_date, end_time) if end < start: raise ValueError("candidate_interval_reversed") total_minutes = int((end - start).total_seconds() // 60) + 1 if total_minutes < 2: raise ValueError("candidate_interval_too_short") if total_minutes > MAX_WINDOW_MINUTES: raise ValueError("candidate_interval_out_of_bounds") sampled = [start + timedelta(minutes=offset) for offset in range(0, total_minutes, step)] if len(sampled) < 2: raise ValueError("candidate_sample_step_too_coarse") if sampled[-1] != end and (end - sampled[-1]).total_seconds() // 60 >= 1: # Keep the user-visible end minute as the final sample so the reported # contract always covers the declared interval edge. sampled.append(end) return sampled def _varga_chart(varga_results: dict, division: int) -> dict | None: return next( (chart for name, chart in varga_results.items() if name.startswith(f"D{division}_")), None, ) def _material_signature(chart: dict, planet_longitudes: dict[str, float]) -> dict[str, str]: """Compute the material chart fingerprint for one sampled candidate.""" ascendant_longitude = float(chart["ascendant"]["lon"]) ascendant_index = int(ascendant_longitude // 30) moon_longitude = float(planet_longitudes["Moon"]) asc_nak = dasha_analyzer.lon_to_nakshatra(ascendant_longitude) moon_nak = dasha_analyzer.lon_to_nakshatra(moon_longitude) signature: dict[str, str] = { "lagna_sign": _sign_name(ascendant_index), "lagna_nakshatra": f"{asc_nak[0][0]} p{asc_nak[2]}", "moon_sign": _sign_name(int(moon_longitude // 30)), "moon_nakshatra": f"{moon_nak[0][0]} p{moon_nak[2]}", # Vimshottari Mahadasha lord is the Moon nakshatra lord. "vimshottari_md_lord": str(moon_nak[0][1]), } varga_results = varga.calc_all_vargas( planet_longitudes, ascendant_longitude, divisions=list(RELEVANT_DIVISIONS), ) for division in RELEVANT_DIVISIONS: dimension = f"varga_asc.D{division}" varga_chart = _varga_chart(varga_results, division) ascendant = varga_chart.get("Ascendant") if isinstance(varga_chart, dict) else None sign_index = ascendant.get("sign_idx") if isinstance(ascendant, dict) else None signature[dimension] = _sign_name(sign_index) if isinstance(sign_index, int) else "blocked" arudha_result = jaimini.calc_arudha_padas(ascendant_index, planet_longitudes) padas = arudha_result.get("padas") if isinstance(arudha_result, dict) else None for key in TRACKED_ARUDHAS: pada = (padas or {}).get(key) if isinstance(padas, dict) else None sign_index = pada.get("sign_idx") if isinstance(pada, dict) else None signature[f"arudha.{key}"] = _sign_name(sign_index) if isinstance(sign_index, int) else "unavailable" return signature def _compute_chart_for_candidate(request: CandidateDifferenceRequest, candidate_at: datetime) -> tuple[dict, dict[str, float]]: chart = domain_calculation_service.compute_chart({ "year": candidate_at.year, "month": candidate_at.month, "day": candidate_at.day, "hour": candidate_at.hour, "minute": candidate_at.minute, "lat": request["lat"], "lon": request["lon"], "tz": request["tz"], "ayanamsa": request["ayanamsa"], "node_mode": request["node_mode"], }) planet_longitudes = { name: float(data["lon"]) for name, data in chart.get("planets", {}).items() if isinstance(data, dict) and isinstance(data.get("lon"), int | float) } if "Moon" not in planet_longitudes: raise ValueError("candidate_chart_missing_moon") return chart, planet_longitudes def _merge_signature_groups(rows: Sequence[tuple[datetime, dict[str, str]]]) -> list[dict]: groups: list[dict] = [] for candidate_at, signature in rows: if groups and groups[-1]["signature"] == signature: group = groups[-1] group["end_time"] = candidate_at.strftime("%H:%M") group["width_minutes"] = _width_minutes(group["start_time"], group["end_time"]) group["sample_count"] += 1 continue groups.append({ "group_id": f"g{len(groups) + 1}", "start_time": candidate_at.strftime("%H:%M"), "end_time": candidate_at.strftime("%H:%M"), "representative_time": candidate_at.strftime("%H:%M"), "width_minutes": 1, "sample_count": 1, "signature": dict(signature), }) for group in groups: group["signature"] = {key: group["signature"][key] for key in FINGERPRINT_DIMENSION_ORDER if key in group["signature"]} return groups def _width_minutes(start_time: str, end_time: str) -> int: start = datetime.strptime(start_time, "%H:%M") end = datetime.strptime(end_time, "%H:%M") return int((end - start).total_seconds() // 60) + 1 def _build_discriminators(groups: Sequence[dict]) -> list[dict]: discriminators: list[dict] = [] for previous, current in zip(groups, groups[1:]): changed: list[dict[str, str]] = [] stable_dimensions: list[str] = [] for dimension, current_value in current["signature"].items(): previous_value = previous["signature"].get(dimension) if previous_value == current_value: stable_dimensions.append(dimension) else: changed.append({ "dimension": dimension, "from": previous_value, "to": current_value, }) discriminators.append({ # First sample in the new group; the exact crossing is not solved here. "boundary_time": current["start_time"], "from_group": previous["group_id"], "to_group": current["group_id"], "changed_dimensions": changed, "stable_dimensions": sorted(stable_dimensions), }) return discriminators def _build_dimension_sensitivity(groups: Sequence[dict]) -> dict: dimensions = FINGERPRINT_DIMENSION_ORDER if groups else () rows: dict[str, dict] = {} for dimension in dimensions: values: list[str] = [] for group in groups: value = group["signature"].get(dimension) if value is not None and value not in values: values.append(value) changed = len(values) > 1 rows[dimension] = { "values": values, "distinct_value_count": len(values), "group_count": len(groups), "kind": "sensitive" if changed else "stable", "usable_discriminator": changed, } ranking = sorted( (dimension for dimension in dimensions if rows[dimension]["usable_discriminator"]), key=lambda dimension: (-rows[dimension]["distinct_value_count"], dimension), ) return {"dimensions": rows, "ranking": ranking} def _adapter_status(groups: Sequence[dict]) -> dict: blocked_layers: list[str] = [] for group in groups: for dimension, value in group["signature"].items(): if value in {"blocked", "unavailable"} and dimension not in blocked_layers: blocked_layers.append(dimension) return { "native_calculation": "available", "blocked_layers": sorted(blocked_layers), "note": "Layers listed in blocked_layers could not be computed and never count as evidence.", } def build_candidate_difference_contract(request: CandidateDifferenceRequest) -> dict: """Sample candidate times and return groups plus discriminators (no approval).""" if not all(isinstance(request.get(key), str) and request[key].strip() for key in ("ayanamsa", "node_mode")): raise ValueError("candidate_explicit_ayanamsa_and_node_mode_required") sampled = _candidate_times(request) rows: list[tuple[datetime, dict[str, str]]] = [] for candidate_at in sampled: chart, planet_longitudes = _compute_chart_for_candidate(request, candidate_at) rows.append((candidate_at, _material_signature(chart, planet_longitudes))) groups = _merge_signature_groups(rows) discriminators = _build_discriminators(groups) sensitivity = _build_dimension_sensitivity(groups) fingerprint = ( f"{request['birth_date']}|{request['start_time']}|{request['end_time']}|" f"{request['lat']}|{request['lon']}|{request['tz']}|" f"{request['ayanamsa']}|{request['node_mode']}|" f"{request.get('sample_step_minutes', 1)}" ) return { "schema_version": SCHEMA_VERSION, "contract_id": str(uuid5(NAMESPACE_URL, f"{SCHEMA_VERSION}:{fingerprint}")), "request_profile": { "birth_date": request["birth_date"], "start_time": request["start_time"], "end_time": request["end_time"], "lat": request["lat"], "lon": request["lon"], "tz": request["tz"], "ayanamsa": request["ayanamsa"], "node_mode": request["node_mode"], "sample_step_minutes": int(request.get("sample_step_minutes", 1)), }, "sample": { "candidate_count": len(sampled), "first_candidate_time": sampled[0].strftime("%H:%M"), "last_candidate_time": sampled[-1].strftime("%H:%M"), "all_candidates_within_interval": True, }, "groups": groups, "discriminators": discriminators, "dimension_sensitivity": sensitivity, "adapter_status": _adapter_status(groups), "status": "candidate_groups_only", "claim_boundary": ( "Candidate difference contract only; it shows where material chart " "changes fall inside the uncertain interval and cannot approve a birth time." ), }