"""Shared Raman Vol2 p99-100 deductions, not a generic Dasha dispatcher.""" from fractions import Fraction from itertools import product PLANETS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn") HARANA_FLAGS = ("retrograde", "inimical_sign", "combust") def unresolved_strength_selections(conditions, selectors): """Enumerate validated missing selectors, never assign astrological strength.""" groups = {} for planet in PLANETS: house = conditions[planet]['bhava'] if house >= 7: groups.setdefault(str(house), []).append(planet) unresolved = {h:ps for h,ps in groups.items() if len(ps)>1 and h not in selectors} keys = sorted(unresolved, key=int) return unresolved, [dict(selectors, **dict(zip(keys, choices))) for choices in product(*(unresolved[h] for h in keys))] def strength_candidate_report(baseline, branches, unresolved, title): """Shared presentation only; every branch was computed by its named producer.""" import copy import json result = dict(status='parameter_sensitive' if any(b['result']['status']=='executed' for b in branches) else 'blocked', execution_status='executed', input_status=baseline['status'], profile_id=baseline['profile_id'], mode='all_unresolved_strength_candidates', selected_branch=None, unresolved_houses=unresolved, baseline=baseline, branches=branches, customer_export_admitted=False, limits=['Each branch assumes its listed strongest planets; no automatic winner or probabilities', 'Only missing crowded-visible-house strength choices are varied; other blockers remain', 'Nominal contribution totals are not lifespan, death dates or MD/AD/PD', 'Existing named algorithm and supplied-condition boundaries remain in force']) lines = [f'# {title} — conditional strongest-planet candidates', '', 'No branch selected. Nominal totals are conditional calculations, not lifespan predictions.', '', '| Branch | Assumed strongest by Bhava | State | Exact nominal total |', '| --- | --- | --- | --- |'] for branch in branches: r = branch['result'] total = r['total']['years_exact'] if r['total'] is not None else 'blocked' lines.append(f'| {branch["branch_key"]} | {json.dumps(branch["strongest_by_bhava"],sort_keys=True)} | {r["status"]} | {total} |') lines += ['', '## Full evidence', '```json', json.dumps(result,indent=2), '```'] return dict(status=result['status'], customer_export_admitted=False, evidence_appendix=[result], exports=dict(markdown='\n'.join(lines), ai_evidence_bundle=copy.deepcopy(result))) def term(years): days = Fraction(years) * 360 rounded = (days.numerator * 2 + days.denominator) // (2 * days.denominator) return {"years_exact": str(Fraction(years)), "nominal_days_exact": str(days), "display_360_day_term": {"years": rounded // 360, "months": rounded % 360 // 30, "days": rounded % 30}} def nature(planet, condition): return condition["nature"] if planet == "Mercury" else ( "benefic" if planet in ("Moon", "Jupiter", "Venus") else "malefic") def validate_conditions(longitude_minutes, conditions, condition_profile, strongest_by_bhava, flags): if not isinstance(condition_profile, str) or not condition_profile.strip(): raise ValueError("condition_profile must identify supplied bhava/dignity/combustion choices") if not isinstance(longitude_minutes, dict) or set(longitude_minutes) != set(PLANETS) | {"Lagna"}: raise ValueError("longitude_minutes requires exactly seven planets and Lagna") if any(type(x) is not int or not 0 <= x < 21600 for x in longitude_minutes.values()): raise ValueError("longitude_minutes must be integers in [0,21600)") if not isinstance(conditions, dict) or set(conditions) != set(PLANETS): raise ValueError("conditions requires exactly seven planets") houses = {} for planet in PLANETS: row = conditions[planet] required = set(flags) | {"bhava"} | ({"nature"} if planet == "Mercury" else set()) if not isinstance(row, dict) or set(row) != required: raise ValueError(f"{planet}: required fields {sorted(required)}") if any(type(row[f]) is not bool for f in flags): raise ValueError(f"{planet}: condition flags must be boolean") if type(row["bhava"]) is not int or not 1 <= row["bhava"] <= 12: raise ValueError(f"{planet}: bhava must be integer 1..12") if planet == "Mercury" and row["nature"] not in ("benefic", "malefic"): raise ValueError("Mercury nature must be benefic or malefic") if planet in ("Sun", "Moon") and row["retrograde"]: raise ValueError(f"{planet} cannot be retrograde") if planet == "Sun" and row["combust"]: raise ValueError("Sun cannot be combust by itself") houses.setdefault(row["bhava"], []).append(planet) selectors = {} if strongest_by_bhava is None else strongest_by_bhava if not isinstance(selectors, dict): raise ValueError("strongest_by_bhava must be a mapping with string house keys") for key, planet in selectors.items(): if key not in {str(h) for h in houses if h >= 7 and len(houses[h]) > 1}: raise ValueError("strength selectors apply only to crowded visible bhavas") if planet not in houses[int(key)]: raise ValueError("strongest planet must occupy the selected bhava") return houses, selectors def apply_haranas(planet, years, condition, houses, selectors): """Three sequential deductions; caller owns Bharana and Krurodaya rules.""" h = condition["bhava"] if h >= 7 and len(houses[h]) > 1 and str(h) not in selectors: return None, [], f"strongest_by_bhava.{h} required for {','.join(houses[h])}" selected = h >= 7 and (len(houses[h]) == 1 or selectors[str(h)] == planet) role = nature(planet, condition) fraction = Fraction(1, (13-h) * (2 if role == "benefic" else 1)) if selected else Fraction(0) years *= 1 - fraction trace = [{"rule": "chakrapatha", "deduct_fraction": str(fraction), "bhava": h, "nature": role, "selected": selected, "remaining": term(years)}] fraction = Fraction(1, 3) if condition["inimical_sign"] and planet != "Mars" and not condition["retrograde"] else Fraction(0) years *= 1 - fraction trace.append({"rule": "satrukshetra", "deduct_fraction": str(fraction), "remaining": term(years)}) fraction = Fraction(1, 2) if condition["combust"] and planet not in ("Venus", "Saturn") else Fraction(0) years *= 1 - fraction trace.append({"rule": "astangata", "deduct_fraction": str(fraction), "remaining": term(years)}) return years, trace, None