Files
Jyotisha/scripts/tara_dasha.py
T
ClaudeandClaude Opus 5.5 ac9be6f88c feat(techniques): port the astrologer upstream skill's missing techniques
Port from yinduzhanxing 5fb8379c (MIT): Naisargika, Kaala, Karaka, Tara,
Lagnamsaka, Yogardha, Mandooka, Paryaaya and Padanadhamsa dashas;
Sarvatobhadra, Kota and Kalanala chakras; Nakshatra Latta; Pachakadi;
Raman Amsayu and Pindayu. Producers and their upstream tests are copied;
scripts/upstream_technique_layers.py feeds them our natal and transit
positions and attaches chart.consultation_native_layers.upstream_techniques.

- dasha_registry: kaala and padanadhamsa keys (35 -> 37); the nine ported
  dashas are served by compute_dasha or fail closed with upstream's reason.
- technique_registry.json: 16 partial entries; README badges follow.
- Evidence lookup section `upstream_techniques` in the consultation tool.
- Boundaries: Kalanala carries no PyJHora (AGPL) grid coordinates;
  Padanadhamsa/Lagnamsaka run on our Narayana engine (no Rath Table 12,
  PVR co-lord variants or second cycle). PyJHora observers and the Amsayu
  worked-example scaffold live in scripts/research (root .py budget).
- PyJHora black-box cross-checks: Naisargika (lords/years) and Kaala
  (seed segment and fraction within 5e-4) on a public chart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-07 14:44:37 +08:00

215 lines
12 KiB
Python

"""Rath Lesson4 Tara MD with explicit strength, balance and calendar inputs.
This is planetary Kendradi progression, not ninefold Tara Bala or Tara Lagna.
"""
from copy import deepcopy
from datetime import datetime, timedelta, timezone
import json
import math
from pathlib import Path
import sys
if __package__ in (None, ''):
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from scripts.dasha_calculator import VIMSHOTTARI_PERIODS
PROFILE = 'tara_rath_lesson4_explicit_strength_md_v1'
HIMALAYA_PROFILE = 'tara_himalaya_parashari_candidate_v1'
SOURCE = 'https://srath.com/jyoti%E1%B9%A3a/dasa/vimsottari-dasa/'
HIMALAYA_SOURCE = 'https://himalayavedicworld.com/tara-dasha-and-timing-of-events.php'
HIMALAYA_ORDER = ('Sun', 'Moon', 'Mars', 'Rahu', 'Jupiter', 'Saturn', 'Mercury', 'Ketu', 'Venus')
HIMALAYA_YEARS = dict(Sun=6, Moon=10, Mars=7, Rahu=18, Jupiter=16, Saturn=19, Mercury=17, Ketu=7, Venus=20)
def build_tara_himalaya_candidate_report(*, selected_planet, planet_longitude,
nakshatra_number, **request):
"""Opt-in Tara candidate using the published remaining-nakshatra rule.
Strength selection stays explicit; this function only derives the balance
fraction from the selected planet's longitude and 1-based nakshatra.
"""
if not isinstance(selected_planet, str):
raise ValueError('selected_planet required')
if type(nakshatra_number) is not int or not 1 <= nakshatra_number <= 27:
raise ValueError('nakshatra_number must be 1..27')
if type(planet_longitude) not in (int, float) or not math.isfinite(planet_longitude) or not 0 <= planet_longitude < 360:
raise ValueError('planet_longitude must be finite 0..360')
start = (nakshatra_number - 1) * (40 / 3)
end = nakshatra_number * (40 / 3)
if not start <= planet_longitude < end:
raise ValueError('planet_longitude is outside selected nakshatra')
fraction = (end - planet_longitude) / (40 / 3)
order = request.get('strength_order')
if not isinstance(order, list) or not order or order[0] != selected_planet:
raise ValueError('strength_order must explicitly start with selected_planet')
birth_epoch = request.get('birth_epoch')
year_days = request.get('year_days', 365.2425)
if not isinstance(birth_epoch, str) or type(year_days) not in (int, float) or not math.isfinite(year_days) or not 350 <= year_days <= 370:
raise ValueError('aware birth_epoch and explicit year_days required')
birth = datetime.fromisoformat(birth_epoch)
if birth.utcoffset() is None:
raise ValueError('birth_epoch requires UTC offset')
birth = birth.astimezone(timezone.utc)
duration = HIMALAYA_YEARS[selected_planet]
balance_years = duration * fraction
periods, full_periods = [], []
offset = -balance_years
for lord in HIMALAYA_ORDER:
years = HIMALAYA_YEARS[lord]
start = birth + timedelta(days=offset * year_days)
offset += years
end = birth + timedelta(days=offset * year_days)
effective_years = balance_years if lord == selected_planet else years
children = []
child_offset = 0.0
for child_lord in HIMALAYA_ORDER:
child_years = effective_years * HIMALAYA_YEARS[child_lord] / 120
child_start = start + timedelta(days=child_offset * year_days)
child_offset += child_years
children.append(dict(lord=child_lord, years=child_years,
start_datetime_utc=child_start.isoformat(),
end_datetime_utc=(start + timedelta(days=child_offset * year_days)).isoformat()))
row = dict(lord=lord, nominal_years=years,
start_datetime_utc=start.isoformat(), end_datetime_utc=end.isoformat(),
birth_clipped=start < birth,
remaining_years=effective_years, children=children)
full_periods.append(row)
if end > birth:
periods.append(dict(row, start_datetime_utc=max(start, birth).isoformat()))
result = dict(status='parameter_sensitive', periods=periods, full_periods=full_periods,
customer_export_admitted=False,
balance_years=balance_years, year_days=year_days,
next_step='Verify a second independently dated worked case before any customer routing.',
child_status='source_bounded',
limits=['Himalaya web rule profile; explicit selected planet and balance; no automatic strength inference.',
'Bhukti/Antara uses the published same-order proportional split; independent dated second case remains pending.'])
result['variant_profile_id'] = HIMALAYA_PROFILE
result['tradition_profile'] = 'himalaya_parashari_tara_candidate'
result['source_url'] = HIMALAYA_SOURCE
result['candidate_observation'] = dict(selected_planet=selected_planet,
planet_longitude=planet_longitude, nakshatra_number=nakshatra_number,
remaining_fraction=fraction, source_formula='(nakshatra_end - longitude) / (40/3)',
strength_selection='caller supplied; no automatic strongest-planet inference')
result['limits'].append('Independent web candidate; not merged with Rath/BPHS and not default customer routing')
return result
def calculate_tara_md(*, ascendant_sign, planet_signs, strength_order,
strength_basis, birth_epoch, remaining_fraction, balance_basis,
year_days, profile):
"""Nine source-grouped MD; no inferred strength, balance, AD or PD.
strength_order is strongest-first within each group, not an imposed MD order.
Full first MD starts before birth when a partial balance is supplied.
"""
if profile != PROFILE:
raise ValueError('explicit supported Tara profile required')
planets = set(VIMSHOTTARI_PERIODS)
if type(ascendant_sign) is not int or not 0 <= ascendant_sign < 12:
raise ValueError('ascendant_sign must be 0..11')
if not isinstance(planet_signs, dict) or set(planet_signs) != planets:
raise ValueError('planet_signs must contain all nine planets including nodes')
if any(type(n) is not int or not 0 <= n < 12 for n in planet_signs.values()):
raise ValueError('planet signs must be integer 0..11')
if not isinstance(strength_order, list) or len(strength_order) != 9 or any(not isinstance(p, str) for p in strength_order) or set(strength_order) != planets:
raise ValueError('strength_order must rank each of nine planets exactly once')
for name, value in (('strength_basis', strength_basis), ('balance_basis', balance_basis)):
if not isinstance(value, str) or not value.strip():
raise ValueError(f'explicit {name} required')
if type(remaining_fraction) not in (int, float) or not math.isfinite(remaining_fraction) or not 0 <= remaining_fraction <= 1:
raise ValueError('finite remaining_fraction in [0,1] required')
if type(year_days) not in (int, float) or not math.isfinite(year_days) or not 350 <= year_days <= 370:
raise ValueError('explicit finite year_days in [350,370] required')
if not isinstance(birth_epoch, str):
raise ValueError('aware ISO birth_epoch required')
birth = datetime.fromisoformat(birth_epoch)
if birth.utcoffset() is None:
raise ValueError('birth_epoch requires UTC offset')
birth = birth.astimezone(timezone.utc)
houses = {p: (s-ascendant_sign) % 12 + 1 for p, s in planet_signs.items()}
groups = {name: [p for p in strength_order if (houses[p]-1) % 3 == residue]
for residue, name in enumerate(('kendra', 'panapara', 'apoklima'))}
base = dict(variant_profile_id=PROFILE, tradition_profile='rath_lesson4_kendradi_tara',
source_url=SOURCE, houses=houses, groups=groups, strength_basis=strength_basis,
strength_order=list(strength_order), birth_balance=dict(remaining_fraction=remaining_fraction,
basis=balance_basis, automatic_balance=False), year_days=year_days,
child_status='blocked', child_reason='Source-specific AD/PD order and birth clipping not established',
periods=[], full_periods=[], limits=[
'Supplied natal D1 signs and strength ranking, including nodes; no automatic Shadbala proxy',
'Explicit remaining fraction and fixed-day year are caller conventions, not recovered author calendar',
'Rath Lesson4 Lagna applicability, not the Crux stronger-Lagna/Moon variant',
'MD only; no event verification, customer export or global closure'])
if len(groups['kendra']) < 4:
return dict(base, status='not_applicable', reason='rath_lesson4_requires_four_planets_in_lagna_kendras')
order = [p for group in groups.values() for p in group]
first_years = VIMSHOTTARI_PERIODS[order[0]]
elapsed_years = first_years*(1-remaining_fraction)
offset = -elapsed_years
for i, planet in enumerate(order):
years = VIMSHOTTARI_PERIODS[planet]
start = birth + timedelta(days=offset*year_days)
offset += years
end = birth + timedelta(days=offset*year_days)
row = dict(period_key=f'tara:md:{i+1}', lord=planet, house=houses[planet],
group=next(g for g, members in groups.items() if planet in members),
nominal_years=years, start_datetime_utc=start.isoformat(), end_datetime_utc=end.isoformat())
base['full_periods'].append(row)
if end > birth:
base['periods'].append(dict(row, start_datetime_utc=max(start, birth).isoformat(),
birth_clipped=start < birth, remaining_years=years-elapsed_years if i == 0 else years))
return dict(base, status='parameter_sensitive', order=order, cycle_years=sum(VIMSHOTTARI_PERIODS.values()),
interval_contract='start inclusive, end exclusive; full first MD retained separately')
def build_tara_native_report(*, query_datetime=None, **request):
stamp = None
if query_datetime is not None:
if not isinstance(query_datetime, str):
raise ValueError('query_datetime requires aware ISO datetime')
stamp = datetime.fromisoformat(query_datetime)
if stamp.utcoffset() is None:
raise ValueError('query_datetime requires UTC offset')
stamp = stamp.astimezone(timezone.utc)
# Upstream routes through jyotish_engine.cmd_dasha(tara_native_request=...),
# which only forwards to calculate_tara_md; ours calls it directly.
result = calculate_tara_md(**request)
if stamp is not None:
active = next((deepcopy(row) for row in result['periods']
if datetime.fromisoformat(row['start_datetime_utc']) <= stamp <
datetime.fromisoformat(row['end_datetime_utc'])), None)
result['query'] = dict(query_datetime_utc=stamp.isoformat(),
status='not_applicable' if result['status']=='not_applicable' else
('executed' if active is not None else 'outside_calculated_window'),
active_period=active, interval_contract='start_inclusive_end_exclusive',
child_status=result['child_status'], child_reason=result['child_reason'])
lines = ['# Tara Dasha — Rath explicit-strength MD', '', result['status'], '',
f'Strength: {result["strength_basis"]}', f'Balance: {result["birth_balance"]["basis"]}',
f'Fixed days/year: {result["year_days"]}', '', *result['limits'], '',
'AD/PD: blocked — '+result['child_reason'], '',
'| Lord | Group | Full years | Start UTC | End UTC (exclusive) |',
'| --- | --- | --- | --- | --- |']
for row in result['periods']:
lines.append(f'| {row["lord"]} | {row["group"]} | {row["nominal_years"]} | {row["start_datetime_utc"]} | {row["end_datetime_utc"]} |')
if result['status'] == 'not_applicable':
lines += ['', result['reason']]
if 'query' in result:
lines += ['', '## Requested-time MD', '```json', json.dumps(result['query'],indent=2), '```']
lines += ['', SOURCE]
return dict(status=result['status'], customer_export_admitted=False, evidence_appendix=[result],
exports=dict(markdown='\n'.join(lines), ai_evidence_bundle=deepcopy(result)))
# build_tara_from_birth is not ported: our natal positions come from the chart
# (scripts/upstream_technique_layers.py), not a second compute_chart_data run.
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--request', required=True)
parser.add_argument('--format', choices=['json', 'markdown'], default='json')
args = parser.parse_args()
request = json.loads(Path(args.request).read_text())
report = build_tara_native_report(**request)
print(report['exports']['markdown'] if args.format == 'markdown' else json.dumps(report, indent=2))