Files
Jyotisha/scripts/kaala_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

173 lines
8.7 KiB
Python

"""PVR 2009 Kaala: actual solar sixths and two weighted MD cycles.
Independent implementation of the author's equations, not external software
code. Calendar year length and exact-boundary ownership remain explicit.
"""
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]))
PROFILE = 'kaala_pvr2009_solar_sixths_md_v1'
SOURCE = 'https://www.vedicastrologer.org/articles/kc_dasas.pdf'
LORDS = ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu')
def _stamp(value):
if not isinstance(value, str):
raise ValueError('aware ISO timestamp required')
result = datetime.fromisoformat(value)
if result.utcoffset() is None:
raise ValueError('timestamp requires a UTC offset')
return result.astimezone(timezone.utc)
def _number(value, low, high, name):
if type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high:
raise ValueError(f'{name} must be finite in [{low},{high}]')
def _solar_events(start, latitude, longitude):
import swisseph as swe
midnight = start.replace(hour=0, minute=0, second=0, microsecond=0)
events = []
# Query each actual day. Never manufacture yesterday's events by subtracting
# 24 hours from today's sunrise or sunset.
for offset in range(-3, 4):
jd = (midnight+timedelta(days=offset)).timestamp()/86400 + 2440587.5
for name, mode in (('sunrise', swe.CALC_RISE), ('sunset', swe.CALC_SET)):
status, times = swe.rise_trans(jd, swe.SUN, mode | swe.BIT_HINDU_RISING,
(longitude, latitude, 0.0), flags=swe.FLG_MOSEPH | swe.FLG_TRUEPOS)
if status == 0 and jd <= times[0] < jd+1:
stamp = datetime.fromtimestamp((times[0]-2440587.5)*86400, timezone.utc)
events.append(dict(event=name, datetime_utc=stamp.isoformat()))
return sorted(events, key=lambda e: e['datetime_utc'])
def calculate_kaala_from_events(*, epoch, solar_events, solar_event_profile,
year_days, boundary_policy):
"""Use explicit chronological solar events, including both adjacent nights.
This lower-level entry also permits published idealized solar-event fixtures;
their caller-supplied profile must not be labelled actual astronomy.
"""
start = _stamp(epoch)
_number(year_days, 300, 400, 'year_days')
if boundary_policy != 'start_inclusive':
raise ValueError('explicit boundary_policy=start_inclusive required')
if not isinstance(solar_event_profile, str) or not solar_event_profile.strip():
raise ValueError('solar_event_profile required')
if not isinstance(solar_events, list):
raise ValueError('solar_events must be a chronological list')
events = []
for event in solar_events:
if not isinstance(event, dict) or set(event) != {'event', 'datetime_utc'} or event['event'] not in ('sunrise', 'sunset'):
raise ValueError('each solar event requires event and datetime_utc')
events.append((event['event'], _stamp(event['datetime_utc'])))
if any(b[1] <= a[1] or a[0] == b[0] for a,b in zip(events, events[1:])):
raise ValueError('solar events must strictly increase and alternate')
result = dict(system='kaala_dasha', status='parameter_sensitive',
variant_profile_id=PROFILE, tradition_profile='pvr_kaala_2009', source=SOURCE,
rule_id='web_pvr_kaala_2009_solar_sixths', periods=[],
solar_events=[dict(event=n, datetime_utc=t.isoformat()) for n,t in events],
solar_event_profile=solar_event_profile, year_days=year_days,
boundary_policy=boundary_policy, epoch_utc=start.isoformat(),
child_status='blocked', child_reason='PVR article does not prescribe AD/PD',
limits=['Two MD cycles only; no extrapolation or lifespan interpretation',
'Exact segment boundaries use caller-selected start-inclusive ownership',
'Fixed calendar year length is explicit, not a verified author date convention',
'Kennedy example contains reversed second-cycle dates; not adopted as a date oracle',
'No customer export or event-validation admission'])
selected = None
for i in range(len(events)-3):
group = events[i:i+4]
if [e[0] for e in group] != ['sunset', 'sunrise', 'sunset', 'sunrise']:
continue
previous_set, rise, setting, next_rise = [e[1] for e in group]
if any((b[1]-a[1]).total_seconds() >= 86400 for a,b in zip(group,group[1:])):
continue
day = setting-rise
before_night = rise-previous_set
after_night = next_rise-setting
boundaries = [rise-before_night/6, rise+day/6,
setting-day/6, setting+after_night/6,
next_rise-after_night/6]
for name, a, b in zip(('dawn', 'daytime', 'dusk', 'nighttime'), boundaries, boundaries[1:]):
if a <= start < b:
selected = (name, a, b)
break
if selected is not None:
break
if selected is None:
return dict(result, status='blocked', reason='adjacent_solar_events_unavailable')
name, a, b = selected
fraction = (start-a).total_seconds()/(b-a).total_seconds()
result['seed'] = dict(segment=name, start_datetime_utc=a.isoformat(),
end_datetime_utc=b.isoformat(), elapsed_fraction=fraction,
at_segment_start=start == a)
result['duration_contract'] = dict(cycle_years=[120*fraction, 120*(1-fraction)],
total_years=120, first_balance='whole first phase begins at supplied birth epoch; no nakshatra reduction',
weighting='Sun through Ketu weights 1..9; each phase divided by 45')
elapsed = 0.0
for cycle, years in enumerate(result['duration_contract']['cycle_years'], 1):
cycle_start = elapsed
for ordinal, lord in enumerate(LORDS, 1):
left = cycle_start + years*(ordinal-1)*ordinal/90
right = cycle_start + years*ordinal*(ordinal+1)/90
result['periods'].append(dict(period_key=f'kaala:{cycle}:{ordinal}',
cycle=cycle, lord=lord, years=years*ordinal/45,
start_age=left, end_age=right, zero_duration=years == 0,
start_datetime_utc=(start+timedelta(days=left*year_days)).isoformat(),
end_datetime_utc=(start+timedelta(days=right*year_days)).isoformat()))
elapsed = cycle_start+years
return result
def calculate_kaala_dasha(*, epoch, latitude, longitude, year_days, boundary_policy):
"""Native astronomical entry. Kaala solar timing does not use ayanamsa."""
start = _stamp(epoch)
_number(latitude, -90, 90, 'latitude')
_number(longitude, -180, 180, 'longitude')
_number(year_days, 300, 400, 'year_days')
import swisseph as swe
try:
events = _solar_events(start, latitude, longitude)
except swe.Error:
events = []
result = calculate_kaala_from_events(epoch=epoch, solar_events=events,
solar_event_profile='swisseph_moshier_truepos_hindu_rising_sea_level',
year_days=year_days, boundary_policy=boundary_policy)
result['astronomy_contract'] = dict(solar_center=True, refraction=False,
ecliptic_latitude_ignored=True, altitude_metres=0, ephemeris='Moshier',
ayanamsa='not_used_for_solar_horizon_events')
return result
def build_kaala_report(request):
result = calculate_kaala_dasha(**request)
lines = ['# Kaala — PVR 2009 MD', '', result['status'], '',
'| Cycle | Lord | Start UTC | End UTC (exclusive) | Years |', '|---|---|---|---|---|']
for row in result['periods']:
lines.append(f"| {row['cycle']} | {row['lord']} | {row['start_datetime_utc']} | {row['end_datetime_utc']} | {row['years']:.9f} |")
lines += ['', '## Solar seed and parameters', '', '```json',
json.dumps({k:v for k,v in result.items() if k != 'periods'}, ensure_ascii=False, indent=2), '```',
'', result.get('reason', ''), result['child_reason'], *result['limits'], '', SOURCE]
return dict(status=result['status'], customer_export_admitted=False,
evidence_appendix=[dict(result=result)],
exports=dict(markdown='\n'.join(lines), ai_evidence_bundle=dict(result=deepcopy(result))))
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()
report = build_kaala_report(json.loads(Path(args.request).read_text()))
print(report['exports']['markdown'] if args.format == 'markdown' else json.dumps(report, indent=2))