"""Numerical Swiss Ephemeris searches used by transit surfaces.""" from __future__ import annotations from datetime import datetime, timedelta import math import swisseph as swe try: from .ayanamsa_utils import apply_ayanamsa, normalize_ayanamsa_name except ImportError: # Existing direct-script imports. from ayanamsa_utils import apply_ayanamsa, normalize_ayanamsa_name PLANET_IDS = { "Sun": swe.SUN, "Moon": swe.MOON, "Mars": swe.MARS, "Mercury": swe.MERCURY, "Jupiter": swe.JUPITER, "Venus": swe.VENUS, "Saturn": swe.SATURN, "Rahu": swe.MEAN_NODE, } def _parse(value: str) -> datetime: stamp = datetime.fromisoformat(value) if stamp.tzinfo is not None: raise ValueError('supply naive local civil time and explicit numeric tz') return stamp def sidereal_position_at(planet: str, timestamp: str, tz: float, ayanamsa: str, *, position_mode=None) -> dict: if planet not in PLANET_IDS: raise ValueError(f"unsupported transit planet: {planet}") if isinstance(tz, bool) or not isinstance(tz, (int, float)) or not math.isfinite(tz) or abs(tz) > 14: raise ValueError('finite numeric UTC offset in [-14,14] required') if not isinstance(ayanamsa, str) or not ayanamsa.strip(): raise ValueError('explicit ayanamsa required') local = _parse(timestamp) name = normalize_ayanamsa_name(ayanamsa) apply_ayanamsa(name, swe) jd = swe.julday(local.year, local.month, local.day, local.hour + local.minute / 60 + (local.second + local.microsecond / 1e6) / 3600 - tz) if position_mode is None: # Preserve the historical standalone transit convention. flags, offset = 0, swe.get_ayanamsa_ut(jd) else: import jyotish_engine as engine engine._configure_ephemeris_path() apply_ayanamsa(name, swe) _, flags, offset = engine._sidereal_calculation_profile(jd, position_mode) pos, _ = swe.calc_ut(jd, PLANET_IDS[planet], flags | swe.FLG_SPEED) return {"longitude": (pos[0] - offset) % 360, "speed": pos[3]} def _signed_distance(longitude: float, target: float) -> float: return (longitude - target + 180) % 360 - 180 def _bisect_zero(value, left, right): low = value(left) if low == 0: return left if value(right) == 0: return right for _ in range(40): mid = left + (right - left) / 2 current = value(mid) if low * current <= 0: right = mid else: left, low = mid, current return left + (right - left) / 2 def _angular_roots(longitude, target, start, days): """Split coarse intervals at detected extrema before angular root search.""" end = start + timedelta(days=days) samples = [start + timedelta(hours=i * 6) for i in range(days * 4 + 1)] def value(stamp): return _signed_distance(longitude(stamp), target) def derivative(stamp): delta = timedelta(seconds=30) return _signed_distance(longitude(stamp + delta), longitude(stamp - delta)) * 1440 extrema = [] for left, right in zip(samples, samples[1:]): a, b = derivative(left), derivative(right) if a * b <= 0 and not a == b == 0: extrema.append(_bisect_zero(derivative, left, right)) knots = sorted(set(samples + extrema)) candidates = [point for point in extrema if abs(value(point)) < 1e-5] for left, right in zip(knots, knots[1:]): a, b = value(left), value(right) if a * b <= 0 and abs(b - a) < 180 and not a == b == 0: candidates.append(_bisect_zero(value, left, right)) roots = [] for point in sorted(candidates): error = abs(value(point)) if start <= point < end and error < 1e-5 and all(abs((point-r[0]).total_seconds()) > .01 for r in roots): roots.append((point, error)) return roots def find_exact_conjunctions(planet: str, target_longitude: float, reference_date: str, tz: float, ayanamsa: str, days: int) -> list[dict]: if isinstance(target_longitude, bool) or not math.isfinite(float(target_longitude)) or not 0 <= float(target_longitude) < 360: raise ValueError("target_longitude must be in [0, 360)") if type(days) is not int or days < 1: raise ValueError('days must be a positive integer') start = _parse(reference_date) coordinate = lambda stamp: sidereal_position_at(planet, stamp.isoformat(), tz, ayanamsa)['longitude'] return [{'planet': planet, 'timestamp_local': point.isoformat(timespec='microseconds'), 'target_longitude': float(target_longitude), 'angular_error_degrees': error} for point, error in _angular_roots(coordinate, float(target_longitude), start, days)] def find_moving_aspects(planet: str, other: str, angle: float, reference_date: str, tz: float, ayanamsa: str, days: int) -> list[dict]: """Directed angle (planet-other)%360, not an orb or interpretive aspect.""" if planet not in PLANET_IDS or other not in PLANET_IDS or planet == other: raise ValueError('two distinct supported planets required') if isinstance(angle, bool) or not isinstance(angle, (int, float)) or not math.isfinite(angle) or not 0 <= angle < 360: raise ValueError('directed angle must be finite in [0,360)') if type(days) is not int or days < 1: raise ValueError('days must be a positive integer') def coordinate(stamp): a = sidereal_position_at(planet, stamp.isoformat(), tz, ayanamsa)['longitude'] b = sidereal_position_at(other, stamp.isoformat(), tz, ayanamsa)['longitude'] return (a-b) % 360 return [{'planet': planet, 'other': other, 'angle': angle, 'timestamp_local': point.isoformat(timespec='microseconds'), 'angular_error_degrees': error} for point, error in _angular_roots(coordinate, angle, _parse(reference_date), days)] def find_stations(planet: str, reference_date: str, tz: float, ayanamsa: str, days: int, *, position_mode=None) -> list[dict]: """Zero crossings of native tropical longitude speed, matching retrograde flags.""" if planet not in PLANET_IDS or type(days) is not int or days < 1: raise ValueError('supported planet and positive integer days required') start = _parse(reference_date) end = start + timedelta(days=days) options = {} if position_mode is None else {'position_mode': position_mode} speed = lambda stamp: sidereal_position_at(planet, stamp.isoformat(), tz, ayanamsa, **options)['speed'] points = [start + timedelta(hours=i * 6) for i in range(days * 4 + 1)] rows = [] for left, right in zip(points, points[1:]): a, b = speed(left), speed(right) if a * b > 0 or a == b == 0: continue root = _bisect_zero(speed, left, right) error = abs(speed(root)) if start <= root < end and error < 1e-7 and all(abs((root-_parse(r['timestamp_local'])).total_seconds()) > .01 for r in rows): rows.append({'planet': planet, 'timestamp_local': root.isoformat(timespec='microseconds'), 'speed_residual_degrees_per_day': error, 'direction_after': 'retrograde' if speed(root + timedelta(seconds=60)) < 0 else 'direct', 'station_basis': 'native_tropical_longitude_speed'}) return rows def _refine_station(planet: str, left: datetime, right: datetime, tz: float, ayanamsa: str) -> dict: """Bisect a daily speed-sign bracket to the native station instant.""" for _ in range(32): middle = left + (right - left) / 2 left_speed = sidereal_position_at(planet, left.isoformat(), tz, ayanamsa)["speed"] middle_speed = sidereal_position_at(planet, middle.isoformat(), tz, ayanamsa)["speed"] if left_speed == 0 or left_speed * middle_speed <= 0: right = middle else: left = middle timestamp = left + (right - left) / 2 speed = sidereal_position_at(planet, timestamp.isoformat(), tz, ayanamsa)["speed"] return { "timestamp_local": timestamp.isoformat(timespec="seconds"), "speed_degrees_per_day": speed, } def find_profiled_sign_ingresses(start_date, end_date, *, tz, ayanamsa, node_mode, position_mode): """Sign crossings for annual use with the natal request's exact profile. Reuses native positions and the existing root finder; never interprets an ingress as an outcome. Cached shared samples avoid twelve repeated scans. """ from functools import lru_cache import jyotish_engine as engine start, end = _parse(start_date), _parse(end_date) if end <= start or (end - start).days > 367: raise ValueError('Annual ingress interval must be positive and at most 367 days') if node_mode not in ('mean', 'true') or position_mode not in ('legacy', 'mean', 'apparent'): raise ValueError('Explicit node and position profiles required') engine._configure_ephemeris_path() @lru_cache(maxsize=10000) def positions(stamp): jd = swe.julday(stamp.year, stamp.month, stamp.day, stamp.hour + stamp.minute / 60 + (stamp.second + stamp.microsecond / 1e6) / 3600 - tz) return engine._calc_sidereal_planets_for_jd(jd, node_mode=node_mode, include_ketu=True, position_mode=position_mode, ayanamsa_name=ayanamsa)[0] days = math.ceil((end - start).total_seconds() / 86400) events = [] for planet in ('Jupiter', 'Saturn', 'Rahu', 'Ketu'): def longitude(stamp): row = positions(stamp)[planet] return row['degree_raw'] for sign in range(12): for stamp, error in _angular_roots(longitude, sign * 30, start, days): if stamp >= end: continue before = int(longitude(stamp - timedelta(seconds=1)) // 30) after = int(longitude(stamp + timedelta(seconds=1)) // 30) if before != after: events.append({'planet': planet, 'timestamp_local': stamp.isoformat(), 'from_sign_idx': before, 'to_sign_idx': after, 'root_error_degrees': error}) return {'execution_status': 'executed', 'events': sorted(events, key=lambda x: x['timestamp_local']), 'range': {'start': start_date, 'end_exclusive': end_date}, 'profile': {'tz': tz, 'ayanamsa': ayanamsa, 'node_mode': node_mode, 'position_mode': position_mode}, 'scope': 'Jupiter/Saturn/nodes sign crossings only; not all aspects or outcome windows', 'method': 'native sidereal positions; six-hour samples plus extrema/root refinement'} def build_tajika_motion_timeline(reference_date: str, days: int, tz: float, ayanamsa: str, *, position_mode=None, end_exclusive=None) -> dict: """Actual common-epoch seven-body motion, not a named-yoga verdict. Fixed profile matches sidereal_position_at: apparent tropical positions minus ayanamsa, and tropical longitude speed for stations. The interval is half-open. Numerical resolution is not evidence for a life-event date. """ from functools import lru_cache from itertools import combinations if type(days) is not int or not 1 <= days <= 367: raise ValueError('days must be an integer in [1,367]') start = _parse(reference_date) end = _parse(end_exclusive) if end_exclusive is not None else start + timedelta(days=days) if not start < end <= start + timedelta(days=days): raise ValueError('end_exclusive must be after start and within the scan horizon') if position_mode is not None and position_mode not in ('legacy', 'mean', 'apparent'): raise ValueError('unsupported position_mode') bodies = tuple(p for p in PLANET_IDS if p != 'Rahu') options = {} if position_mode is None else {'position_mode': position_mode} @lru_cache(maxsize=100000) def position(planet, stamp): return sidereal_position_at(planet, stamp.isoformat(), tz, ayanamsa, **options) initial = {p: position(p, start) for p in bodies} events = [] for first, second in combinations(bodies, 2): def separation(stamp): return (position(first, stamp)['longitude'] - position(second, stamp)['longitude']) % 360 for angle in (0, 60, 90, 120, 180, 240, 270, 300): for stamp, error in _angular_roots(separation, angle, start, days): events.append({'kind': 'exact_contact', 'planets': [first, second], 'directed_angle': angle, 'timestamp_local': stamp.isoformat(), 'angular_error_degrees': error}) for planet in bodies: longitude = lambda stamp: position(planet, stamp)['longitude'] for sign in range(12): for stamp, error in _angular_roots(longitude, sign * 30, start, days): before = int(longitude(stamp - timedelta(seconds=1)) // 30) after = int(longitude(stamp + timedelta(seconds=1)) // 30) if before != after: events.append({'kind': 'ingress', 'planets': [planet], 'timestamp_local': stamp.isoformat(), 'from_sign_idx': before, 'to_sign_idx': after, 'angular_error_degrees': error}) for station in find_stations(planet, reference_date, tz, ayanamsa, days, **options): events.append({'kind': 'station', 'planets': [planet], **station}) events = [event for event in events if _parse(event['timestamp_local']) < end] events.sort(key=lambda row: (row['timestamp_local'], row['kind'], row['planets'])) for event in events: if event['kind'] == 'exact_contact': event['prior_motion_changes'] = [ {'kind': earlier['kind'], 'planets': earlier['planets'], 'timestamp_local': earlier['timestamp_local']} for earlier in events if earlier['timestamp_local'] < event['timestamp_local'] and earlier['kind'] in ('ingress', 'station') and set(earlier['planets']) & set(event['planets'])] return {'execution_status': 'executed', 'initial_positions': initial, 'events': events, 'range': {'start': start.isoformat(), 'end_exclusive': end.isoformat()}, 'profile': {'tz': tz, 'ayanamsa': normalize_ayanamsa_name(ayanamsa), 'position_mode': position_mode or 'historical_apparent_minus_mean_ayanamsa_ut', 'station_basis': 'tropical_longitude_speed'}, 'method': 'Swiss Ephemeris; shared epoch; six-hour brackets, extrema and refined roots', 'claim_boundary': 'Computed motion only; no automatic named-yoga perfection or life-event prediction.'} def build_retrograde_calendar(reference_date: str, months: int, tz: float, ayanamsa: str) -> dict: if not 1 <= months <= 24: raise ValueError("months must be between 1 and 24") start = _parse(reference_date) end = start + timedelta(days=months * 31) calendar = {} for planet in PLANET_IDS: cursor = start active_start = None station_start = None while cursor <= end: retrograde = sidereal_position_at(planet, cursor.isoformat(), tz, ayanamsa)["speed"] < 0 if retrograde and active_start is None: active_start = cursor station_start = _refine_station(planet, cursor - timedelta(days=1), cursor, tz, ayanamsa) if active_start and (not retrograde or cursor == end): period_end = cursor if not retrograde: station_end = _refine_station(planet, cursor - timedelta(days=1), cursor, tz, ayanamsa) else: station_end = { "timestamp_local": cursor.isoformat(timespec="seconds"), "speed_degrees_per_day": sidereal_position_at(planet, cursor.isoformat(), tz, ayanamsa)["speed"], "boundary": "range_end", } month_cursor = active_start.replace(day=1) while month_cursor <= period_end: key = month_cursor.strftime("%Y-%m") bucket = calendar.setdefault(key, {"retrograde": [], "periods": []}) if planet not in bucket["retrograde"]: bucket["retrograde"].append(planet) bucket["periods"].append({ "planet": planet, "start": active_start.isoformat(timespec="seconds"), "end": period_end.isoformat(timespec="seconds"), "station_start_local": station_start["timestamp_local"], "station_start_speed_degrees_per_day": station_start["speed_degrees_per_day"], "station_end_local": station_end["timestamp_local"], "station_end_speed_degrees_per_day": station_end["speed_degrees_per_day"], **({"station_end_boundary": station_end["boundary"]} if "boundary" in station_end else {}), }) month_cursor = (month_cursor.replace(day=28) + timedelta(days=4)).replace(day=1) active_start = None station_start = None cursor += timedelta(days=1) return calendar