caltib 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. caltib/__init__.py +57 -0
  2. caltib/api.py +268 -0
  3. caltib/api_init.py +5 -0
  4. caltib/attributes/__init__.py +4 -0
  5. caltib/attributes/registry.py +23 -0
  6. caltib/attributes/standard.py +20 -0
  7. caltib/bootstrap.py +10 -0
  8. caltib/cli.py +360 -0
  9. caltib/core/__init__.py +0 -0
  10. caltib/core/engine.py +23 -0
  11. caltib/core/errors.py +5 -0
  12. caltib/core/time.py +124 -0
  13. caltib/core/types.py +131 -0
  14. caltib/design/__init__.py +0 -0
  15. caltib/design/dyadic_params.py +161 -0
  16. caltib/design/ephem/__init__.py +5 -0
  17. caltib/design/ephem/rational_planets.py +207 -0
  18. caltib/design/float_params.py +146 -0
  19. caltib/design/int_tables.py +140 -0
  20. caltib/design/minimax_polys.py +202 -0
  21. caltib/design/month_constants.py +180 -0
  22. caltib/design/pade_arctan.py +132 -0
  23. caltib/design/rational_params.py +199 -0
  24. caltib/design/rational_params_b.py +175 -0
  25. caltib/design/sine_tables.py +96 -0
  26. caltib/diagnostics/__init__.py +7 -0
  27. caltib/diagnostics/analysis.py +345 -0
  28. caltib/diagnostics/anomaly.py +287 -0
  29. caltib/diagnostics/anomaly_elong.py +232 -0
  30. caltib/diagnostics/anomaly_forward.py +264 -0
  31. caltib/diagnostics/anomaly_sun.py +263 -0
  32. caltib/diagnostics/assign_day.py +262 -0
  33. caltib/diagnostics/assign_month.py +285 -0
  34. caltib/diagnostics/compare_sunrise.py +164 -0
  35. caltib/diagnostics/drift.py +202 -0
  36. caltib/diagnostics/drift_quad.py +350 -0
  37. caltib/diagnostics/ephem/__init__.py +5 -0
  38. caltib/diagnostics/ephem/analysis_trads.py +355 -0
  39. caltib/diagnostics/ephem/anomaly.py +205 -0
  40. caltib/diagnostics/ephem/anomaly_trads.py +202 -0
  41. caltib/diagnostics/ephem/drift_quad_fit.py +311 -0
  42. caltib/diagnostics/ephem/drift_trads.py +224 -0
  43. caltib/diagnostics/ephem/offsets_trads.py +199 -0
  44. caltib/diagnostics/ephem/sky.py +273 -0
  45. caltib/diagnostics/ephem/validate_ref_helio.py +142 -0
  46. caltib/diagnostics/ephem/validate_ref_planets.py +149 -0
  47. caltib/diagnostics/ephem/validate_ref_rahu.py +101 -0
  48. caltib/diagnostics/ephem/validate_ref_sm.py +145 -0
  49. caltib/diagnostics/ephem/validate_ref_stars.py +168 -0
  50. caltib/diagnostics/equinox.py +216 -0
  51. caltib/diagnostics/leap_months.py +223 -0
  52. caltib/diagnostics/losar_scatter.py +192 -0
  53. caltib/diagnostics/new_years_table.py +112 -0
  54. caltib/diagnostics/offsets.py +228 -0
  55. caltib/diagnostics/planets.py +154 -0
  56. caltib/diagnostics/pretty_month.py +164 -0
  57. caltib/diagnostics/round_trip.py +110 -0
  58. caltib/diagnostics/solar_lon.py +221 -0
  59. caltib/engines/__init__.py +0 -0
  60. caltib/engines/arithmetic_day.py +200 -0
  61. caltib/engines/arithmetic_month.py +357 -0
  62. caltib/engines/astro/affine_series.py +243 -0
  63. caltib/engines/astro/deltat.py +126 -0
  64. caltib/engines/astro/float_series.py +185 -0
  65. caltib/engines/astro/fp_math.py +141 -0
  66. caltib/engines/astro/sin_tables.py +115 -0
  67. caltib/engines/astro/sunrise.py +258 -0
  68. caltib/engines/astro/tables.py +228 -0
  69. caltib/engines/calendar.py +439 -0
  70. caltib/engines/factory.py +69 -0
  71. caltib/engines/fp_day.py +214 -0
  72. caltib/engines/interfaces.py +208 -0
  73. caltib/engines/l6/__init__.py +0 -0
  74. caltib/engines/l6/engine.py +8 -0
  75. caltib/engines/rational_day.py +307 -0
  76. caltib/engines/rational_month.py +306 -0
  77. caltib/engines/rational_planets.py +113 -0
  78. caltib/engines/specs.py +1247 -0
  79. caltib/engines/trad_attr.py +63 -0
  80. caltib/engines/trad_day.py +256 -0
  81. caltib/engines/trad_planets.py +141 -0
  82. caltib/ephemeris/__init__.py +14 -0
  83. caltib/ephemeris/de422.py +229 -0
  84. caltib/ephemeris/update_deltat_table.py +363 -0
  85. caltib/i18n.py +1778 -0
  86. caltib/reference/__init__.py +0 -0
  87. caltib/reference/astro_args.py +403 -0
  88. caltib/reference/build_micro_vsop.py +117 -0
  89. caltib/reference/build_stars.py +118 -0
  90. caltib/reference/coords.py +142 -0
  91. caltib/reference/data/__init__.py +0 -0
  92. caltib/reference/data/deltat_iers_monthly.csv +650 -0
  93. caltib/reference/deltat.py +352 -0
  94. caltib/reference/events.py +217 -0
  95. caltib/reference/kepler.py +194 -0
  96. caltib/reference/lunar.py +214 -0
  97. caltib/reference/planets.py +776 -0
  98. caltib/reference/planets_tmpl.py +182 -0
  99. caltib/reference/solar.py +182 -0
  100. caltib/reference/stars.py +282 -0
  101. caltib/reference/stars_tmpl.py +111 -0
  102. caltib/reference/time_scales.py +232 -0
  103. caltib/web_diag/__init__.py +0 -0
  104. caltib/web_diag/api.py +1011 -0
  105. caltib-0.3.0.dist-info/METADATA +116 -0
  106. caltib-0.3.0.dist-info/RECORD +109 -0
  107. caltib-0.3.0.dist-info/WHEEL +4 -0
  108. caltib-0.3.0.dist-info/entry_points.txt +2 -0
  109. caltib-0.3.0.dist-info/licenses/LICENSE +21 -0
caltib/__init__.py ADDED
@@ -0,0 +1,57 @@
1
+ """caltib public API.
2
+
3
+ Users should mostly interact with functions re-exported here.
4
+ """
5
+
6
+ # Initialize registry on import
7
+ from . import api_init as _api_init # noqa: F401
8
+
9
+ __version__ = "0.3.0"
10
+
11
+ from .api import (
12
+ day_info,
13
+ to_gregorian,
14
+ explain,
15
+ list_engines,
16
+ engine_info,
17
+ get_calendar,
18
+ make_engine,
19
+ register_engine,
20
+ month_info,
21
+ month_from_n,
22
+ days_in_month,
23
+ true_date_dn,
24
+ end_jd_dn,
25
+ civil_month_n,
26
+ prev_month,
27
+ next_month,
28
+ month_bounds,
29
+ new_year_day,
30
+ first_day_of_month,
31
+ last_day_of_month
32
+ )
33
+ from .core.types import TibetanDate
34
+
35
+ __all__ = [
36
+ "day_info",
37
+ "to_gregorian",
38
+ "explain",
39
+ "list_engines",
40
+ "engine_info",
41
+ "get_calendar",
42
+ "make_engine",
43
+ "register_engine",
44
+ "month_info",
45
+ "month_from_n",
46
+ "TibetanDate",
47
+ "days_in_month",
48
+ "true_date_dn",
49
+ "end_jd_dn",
50
+ "civil_month_n",
51
+ "prev_month",
52
+ "next_month",
53
+ "month_bounds",
54
+ "new_year_day",
55
+ "first_day_of_month",
56
+ "last_day_of_month",
57
+ ]
caltib/api.py ADDED
@@ -0,0 +1,268 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import replace
5
+ from datetime import date
6
+ from typing import Any, Dict, List, Optional, Sequence
7
+ from fractions import Fraction
8
+
9
+ from .core.engine import CalendarEngine, EngineRegistry
10
+ from .core.types import DayInfo, TibetanDate, MonthInfo, YearInfo, LocationSpec, CalendarSpec
11
+ from .core.time import from_jdn
12
+ from .attributes.registry import compute_attributes
13
+ from .engines.factory import make_engine as _make_engine
14
+
15
+
16
+ JD_J2000 = Fraction(2451545, 1)
17
+ _registry: Optional[EngineRegistry] = None
18
+
19
+ def set_registry(reg: EngineRegistry) -> None:
20
+ global _registry
21
+ _registry = reg
22
+
23
+ def _reg() -> EngineRegistry:
24
+ if _registry is None:
25
+ raise RuntimeError("Engine registry not initialized")
26
+ return _registry
27
+
28
+ def list_engines() -> List[str]:
29
+ return _reg().list()
30
+
31
+ def engine_info(engine: str) -> Dict[str, Any]:
32
+ return _reg().get(engine).info()
33
+
34
+ def day_info(
35
+ d: date,
36
+ *,
37
+ engine: str = "phugpa",
38
+ attributes: Sequence[str] = (),
39
+ debug: bool = False,
40
+ ) -> DayInfo:
41
+ info = _reg().get(engine).day_info(d, debug=debug)
42
+ if attributes:
43
+ attrs = compute_attributes(info, attributes)
44
+ info = replace(info, attributes=attrs)
45
+ return info
46
+
47
+ def to_gregorian(t: TibetanDate, *, engine: Optional[str] = None, policy: str = "all") -> List[date]:
48
+ eng = _reg().get(engine) if engine is not None else _reg().get(t.engine.name)
49
+ return eng.to_gregorian(t, policy=policy)
50
+
51
+ def explain(d: date, *, engine: str = "phugpa") -> Dict[str, Any]:
52
+ return _reg().get(engine).explain(d)
53
+
54
+ def get_calendar(name: str, *, location: Optional[LocationSpec] = None) -> CalendarEngine:
55
+ from .engines.specs import ALL_SPECS
56
+ if name not in ALL_SPECS:
57
+ raise KeyError(f"Unknown engine spec '{name}'")
58
+
59
+ # spec is now natively a CalendarSpec!
60
+ spec = ALL_SPECS[name]
61
+
62
+ # 2. Use our new cascading builder pattern to swap the location
63
+ if location is not None:
64
+ if hasattr(spec, 'with_location'):
65
+ spec = spec.with_location(location)
66
+ else:
67
+ raise ValueError(f"Calendar '{name}' does not support location overrides.")
68
+
69
+ return _make_engine(spec)
70
+
71
+ # 3. Updated type hint to natively expect CalendarSpec
72
+ def make_engine(spec: CalendarSpec) -> CalendarEngine:
73
+ return _make_engine(spec)
74
+
75
+ def register_engine(name: str, engine: CalendarEngine, *, overwrite: bool = False) -> None:
76
+ _reg().register(name, engine, overwrite=overwrite)
77
+
78
+ # ============================================================
79
+ # Helpers for API Diagnostics
80
+ # ============================================================
81
+
82
+ def _get_n_m(eng: CalendarEngine, Y: int, M: int, is_leap: bool) -> int:
83
+ """Helper to resolve the specific lunation index from the new get_lunations API."""
84
+ lunations = eng.month.get_lunations(Y, M)
85
+ if len(lunations) == 1:
86
+ return lunations[0]
87
+ if eng.leap_labeling == "first_is_leap":
88
+ return lunations[0] if is_leap else lunations[1]
89
+ return lunations[1] if is_leap else lunations[0]
90
+
91
+ # ============================================================
92
+ # High-Level Bulk Data API (Modern Interface)
93
+ # ============================================================
94
+
95
+ def month_info(Y: int, M: int, *, is_leap_month: bool = False, engine: str = "phugpa") -> MonthInfo:
96
+ """Returns a fully populated MonthInfo dataclass, including all days and alignments."""
97
+ return _reg().get(engine).month_info(Y, M, is_leap_month)
98
+
99
+ def year_info(Y: int, *, engine: str = "phugpa") -> YearInfo:
100
+ """Returns a fully populated YearInfo dataclass, including all active months and days."""
101
+ return _reg().get(engine).year_info(Y)
102
+
103
+ def new_year_day(Y: int, *, engine: str = "phugpa", as_date: bool = True) -> Any:
104
+ """
105
+ Returns the Gregorian date for Losar/Tsagaan Sar.
106
+ If as_date is True, returns a pure datetime.date object.
107
+ Otherwise, returns a dictionary with physical diagnostic data.
108
+ """
109
+ eng = _reg().get(engine)
110
+ if eng.leap_labeling == "first_is_leap":
111
+ Y_last, M_last, L_last = Y - 1, 12, False
112
+ else:
113
+ n1 = _get_n_m(eng, Y, 1, False)
114
+ Y_last, M_last, leap_state = eng.month.label_from_lunation(n1 - 1)
115
+ L_last = (leap_state == 2)
116
+
117
+ n_last = _get_n_m(eng, Y_last, M_last, L_last)
118
+ n_last_d = n_last + eng.delta_k
119
+ jdn = end_jd_dn(30, n_last_d, engine=engine) + 1
120
+
121
+ if as_date:
122
+ return from_jdn(jdn)
123
+
124
+ return {
125
+ "Y": Y,
126
+ "jdn": jdn,
127
+ "prev_month": {"Y": Y_last, "M": M_last, "is_leap_month": L_last},
128
+ "n_last": n_last,
129
+ "date": from_jdn(jdn)
130
+ }
131
+
132
+ # ============================================================
133
+ # Diagnostic & Legacy API
134
+ # ============================================================
135
+
136
+ def debug_month_labels(Y: int, M: int, *, engine: str = "phugpa", debug: bool = False) -> Dict[str, Any]:
137
+ """Formerly called 'month_info'. Returns internal math labels."""
138
+ eng = _reg().get(engine)
139
+ if hasattr(eng.month, "debug_label"):
140
+ out = eng.month.debug_label(Y, M)
141
+ if debug:
142
+ out["engine"] = eng.info()
143
+ return out
144
+ raise TypeError(f"Engine '{engine}' does not expose month-layer info")
145
+
146
+ def debug_lunation_n(n: int, *, engine: str = "phugpa", debug: bool = False) -> Dict[str, Any]:
147
+ """Formerly called 'month_from_n'. Returns internal math labels for absolute n."""
148
+ eng = _reg().get(engine)
149
+ if hasattr(eng.month, "debug_lunation"):
150
+ out = eng.month.debug_lunation(n)
151
+ if debug:
152
+ out["engine"] = eng.info()
153
+ return out
154
+ raise TypeError(f"Engine '{engine}' does not expose month-layer info")
155
+
156
+ # ============================================================
157
+ # Month-level debug API
158
+ # ============================================================
159
+
160
+ def intercalation_index(Y: int, M: int, *, engine: str = "phugpa") -> int:
161
+ # This works only for traditional engines
162
+ eng = _reg().get(engine)
163
+ return eng.trad.intercalation_index(Y, M)
164
+
165
+ def month_from_n(n: int, *, engine: str = "phugpa", debug: bool = False) -> Dict[str, Any]:
166
+ eng = _reg().get(engine)
167
+ if hasattr(eng.month, "debug_lunation"):
168
+ out = eng.month.debug_lunation(n)
169
+ if debug:
170
+ out["engine"] = eng.info()
171
+ return out
172
+ raise TypeError(f"Engine '{engine}' does not expose month-layer info")
173
+
174
+ def days_in_month(Y: int, M: int, *, is_leap_month: bool = False, engine: str = "phugpa"):
175
+ eng = _reg().get(engine)
176
+ n_m = _get_n_m(eng, Y, M, is_leap_month)
177
+ n_d = n_m + eng.delta_k
178
+
179
+ # Use the orchestrator's civil map instead of the old DayEngine hits
180
+ month_map = eng.build_civil_month(n_d)
181
+
182
+ rows = []
183
+ for jdn, info in sorted(month_map.items()):
184
+ # Calculate skipped labels if needed (for display consistency)
185
+ skipped_labels = [info["day"] - 1] if info["skipped"] else []
186
+ rows.append({
187
+ "date": from_jdn(jdn),
188
+ "jdn": jdn,
189
+ "tithi": info["day"],
190
+ "occ": 2 if info["repeated"] else 1,
191
+ "repeated": info["repeated"],
192
+ "skipped_labels": skipped_labels,
193
+ })
194
+ return rows
195
+
196
+ def true_date_dn(d: int, n: int, *, engine: str = "phugpa"):
197
+ """Returns absolute true_date (Days since J2000.0) via continuous x."""
198
+ eng = _reg().get(engine)
199
+ x = Fraction(30 * n + d, 1)
200
+ return eng.day.true_date(x)
201
+
202
+ def end_jd_dn(d: int, n: int, *, engine: str = "phugpa") -> int:
203
+ """Returns absolute Julian Day Number via continuous x."""
204
+ eng = _reg().get(engine)
205
+ x = Fraction(30 * n + d, 1)
206
+ return math.floor(eng.day.local_civil_date(x) + JD_J2000)
207
+
208
+ def civil_month_n(n: int, *, engine: str = "phugpa") -> List[Dict[str, Any]]:
209
+ """Diagnostic: list civil day records for a specific lunation n."""
210
+ eng = _reg().get(engine)
211
+ # Convert month engine n to day engine n_d
212
+ n_d = n + eng.delta_k
213
+ month_map = eng.build_civil_month(n_d)
214
+
215
+ out = []
216
+ for jdn, info in sorted(month_map.items()):
217
+ out.append({
218
+ "jd": jdn,
219
+ "label": info["day"],
220
+ "repeated": info["repeated"],
221
+ "skipped": info["skipped"],
222
+ "date": from_jdn(jdn)
223
+ })
224
+ return out
225
+
226
+ def month_bounds(Y: int, M: int, *, is_leap_month: bool = False, engine: str = "phugpa", debug: bool = False, as_date: bool = True) -> dict:
227
+ eng = _reg().get(engine)
228
+ n_m = _get_n_m(eng, Y, M, is_leap_month)
229
+ n_d = n_m + eng.delta_k
230
+
231
+ first_jdn = end_jd_dn(30, n_d - 1, engine=engine) + 1
232
+ last_jdn = end_jd_dn(30, n_d, engine=engine)
233
+
234
+ out = {"Y": Y, "M": M, "is_leap_month": is_leap_month, "n": n_m, "first_jdn": first_jdn, "last_jdn": last_jdn}
235
+ if as_date:
236
+ out["first_date"] = from_jdn(first_jdn)
237
+ out["last_date"] = from_jdn(last_jdn)
238
+ return out
239
+
240
+ def prev_month(Y: int, M: int, *, is_leap_month: bool = False, engine: str = "phugpa", debug: bool = False) -> dict:
241
+ eng = _reg().get(engine)
242
+ n = _get_n_m(eng, Y, M, is_leap_month)
243
+ Y2, M2, leap_state = eng.month.label_from_lunation(n - 1)
244
+
245
+ L2 = False
246
+ if leap_state == 1: L2 = (eng.leap_labeling == "first_is_leap")
247
+ elif leap_state == 2: L2 = (eng.leap_labeling == "second_is_leap")
248
+
249
+ return {"Y": Y2, "M": M2, "is_leap_month": L2, "n": n - 1}
250
+
251
+ def next_month(Y: int, M: int, *, is_leap_month: bool = False, engine: str = "phugpa", debug: bool = False) -> dict:
252
+ eng = _reg().get(engine)
253
+ n = _get_n_m(eng, Y, M, is_leap_month)
254
+ Y2, M2, leap_state = eng.month.label_from_lunation(n + 1)
255
+
256
+ L2 = False
257
+ if leap_state == 1: L2 = (eng.leap_labeling == "first_is_leap")
258
+ elif leap_state == 2: L2 = (eng.leap_labeling == "second_is_leap")
259
+
260
+ return {"Y": Y2, "M": M2, "is_leap_month": L2, "n": n + 1}
261
+
262
+ def first_day_of_month(Y: int, M: int, *, is_leap_month: bool = False, engine: str = "phugpa") -> date:
263
+ b = month_bounds(Y, M, is_leap_month=is_leap_month, engine=engine, debug=False)
264
+ return b["first_date"]
265
+
266
+ def last_day_of_month(Y: int, M: int, *, is_leap_month: bool = False, engine: str = "phugpa") -> date:
267
+ b = month_bounds(Y, M, is_leap_month=is_leap_month, engine=engine, debug=False)
268
+ return b["last_date"]
caltib/api_init.py ADDED
@@ -0,0 +1,5 @@
1
+ """Registry bootstrap (import side-effect)."""
2
+ from .api import set_registry
3
+ from .bootstrap import build_registry
4
+
5
+ set_registry(build_registry())
@@ -0,0 +1,4 @@
1
+ from .registry import register_attribute
2
+ from . import standard as _standard # noqa: F401 (register built-ins)
3
+
4
+ __all__ = ["register_attribute"]
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+ from typing import Any, Callable, Dict, Sequence
3
+
4
+ from ..core.types import DayInfo
5
+ from ..core.time import to_jdn
6
+
7
+ AttrFunc = Callable[[DayInfo], Dict[str, Any]]
8
+ _REGISTRY: Dict[str, AttrFunc] = {}
9
+
10
+ def register_attribute(name: str, fn: AttrFunc) -> None:
11
+ _REGISTRY[name] = fn
12
+
13
+ def compute_attributes(info: DayInfo, names: Sequence[str]) -> Dict[str, Any]:
14
+ out: Dict[str, Any] = {}
15
+ for name in names:
16
+ if name not in _REGISTRY:
17
+ raise KeyError(f"Unknown attribute '{name}'. Available: {sorted(_REGISTRY)}")
18
+ out.update(_REGISTRY[name](info))
19
+ return out
20
+
21
+ # helper for attribute implementations
22
+ def jdn(info: DayInfo) -> int:
23
+ return to_jdn(info.civil_date)
@@ -0,0 +1,20 @@
1
+ from __future__ import annotations
2
+ from typing import Any, Dict
3
+
4
+ from .registry import register_attribute, jdn
5
+
6
+ def weekday(info) -> Dict[str, Any]:
7
+ # Convention: 0=Mon..6=Sun (ISO-like). Adjust offset if desired.
8
+ return {"weekday": int((jdn(info) + 1) % 7)}
9
+
10
+ def sexagenary_year(info) -> Dict[str, Any]:
11
+ # Placeholder: anchor offsets can be fixed later.
12
+ y = info.tibetan.tib_year
13
+ return {
14
+ "animal_mod12": y % 12,
15
+ "element_mod5": y % 5,
16
+ "stem_mod10": y % 10,
17
+ }
18
+
19
+ register_attribute("weekday", weekday)
20
+ register_attribute("sexagenary_year", sexagenary_year)
caltib/bootstrap.py ADDED
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+ from caltib.core.engine import EngineRegistry
3
+ from caltib.engines.specs import ALL_SPECS
4
+ from caltib.engines.factory import make_engine
5
+
6
+ def build_registry() -> EngineRegistry:
7
+ engines = {}
8
+ for name, spec in ALL_SPECS.items():
9
+ engines[name] = make_engine(spec)
10
+ return EngineRegistry(engines)