accuratum 0.2.1__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.
Potentially problematic release.
This version of accuratum might be problematic. Click here for more details.
- accuratum/__init__.py +0 -0
- accuratum/__main__.py +4 -0
- accuratum/cli.py +386 -0
- accuratum/core/__init__.py +0 -0
- accuratum/core/astronomy.py +76 -0
- accuratum/core/builder.py +123 -0
- accuratum/core/hints.py +50 -0
- accuratum/core/metadata.py +23 -0
- accuratum/core/plot.py +88 -0
- accuratum/core/project.py +148 -0
- accuratum/core/project_io.py +119 -0
- accuratum/core/spec.py +182 -0
- accuratum/core/timegrid.py +80 -0
- accuratum/defaults/__init__.py +0 -0
- accuratum/defaults/labels.py +63 -0
- accuratum/defaults/overlays.py +38 -0
- accuratum/defaults/placement.py +136 -0
- accuratum/defaults/titles.py +22 -0
- accuratum/fig/escola_nas_estrelas.jpeg +0 -0
- accuratum/fig/logo.png +0 -0
- accuratum/fig/rosa.png +0 -0
- accuratum/fig/unb.jpg +0 -0
- accuratum/fig/unb_basic.jpg +0 -0
- accuratum/location.py +55 -0
- accuratum/projections/__init__.py +0 -0
- accuratum/projections/accuratum.py +28 -0
- accuratum/renderers/__init__.py +0 -0
- accuratum/renderers/matplotlib_backend.py +100 -0
- accuratum-0.2.1.dist-info/METADATA +201 -0
- accuratum-0.2.1.dist-info/RECORD +33 -0
- accuratum-0.2.1.dist-info/WHEEL +4 -0
- accuratum-0.2.1.dist-info/entry_points.txt +3 -0
- accuratum-0.2.1.dist-info/licenses/LICENSE.md +7 -0
accuratum/__init__.py
ADDED
|
File without changes
|
accuratum/__main__.py
ADDED
accuratum/cli.py
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
"""Accuratum CLI — generates a project folder, or renders a saved one.
|
|
2
|
+
|
|
3
|
+
The CLI is the only place I/O lives: argv parsing, geocoding, timezone
|
|
4
|
+
lookup, current time, file output. Everything below the
|
|
5
|
+
``SundialSpec`` construction is pure (see :func:`accuratum.core.builder.build_plot`).
|
|
6
|
+
|
|
7
|
+
Two modes:
|
|
8
|
+
|
|
9
|
+
- **generate** (a location or ``--lat-long``): compute the sundial and save it
|
|
10
|
+
as a project folder (``project.json`` + ``polylines.npz``), then render it;
|
|
11
|
+
- **render** (``--project DIR``): load a saved project, including hand-edited
|
|
12
|
+
labels, and render it without recomputing. ``--regenerate`` recomputes it
|
|
13
|
+
from its (edited) spec instead.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import shutil
|
|
21
|
+
import sys
|
|
22
|
+
from dataclasses import replace
|
|
23
|
+
from datetime import datetime
|
|
24
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Sequence
|
|
27
|
+
from zoneinfo import ZoneInfo
|
|
28
|
+
|
|
29
|
+
from matplotlib.colors import to_hex
|
|
30
|
+
from timezonefinder import timezone_at
|
|
31
|
+
|
|
32
|
+
from accuratum.core.builder import build_plot
|
|
33
|
+
from accuratum.core.hints import RenderHints
|
|
34
|
+
from accuratum.core.plot import Plot
|
|
35
|
+
from accuratum.core.project import Project, hints_from_dict
|
|
36
|
+
from accuratum.core.project_io import PROJECT_FILE, StaleProjectError, load_project, save_project
|
|
37
|
+
from accuratum.core.spec import (
|
|
38
|
+
MAX_LATITUDE,
|
|
39
|
+
GridConfig,
|
|
40
|
+
Location,
|
|
41
|
+
SundialSpec,
|
|
42
|
+
solstice_timeframe,
|
|
43
|
+
spec_from_dict,
|
|
44
|
+
)
|
|
45
|
+
from accuratum.defaults.overlays import DEFAULT_OVERLAYS, default_render_hints, resolve_image_path
|
|
46
|
+
from accuratum.defaults.titles import default_subtitle, default_title
|
|
47
|
+
from accuratum.location import location_to_latitude_longitude
|
|
48
|
+
from accuratum.renderers import matplotlib_backend
|
|
49
|
+
|
|
50
|
+
DEFAULT_OUTPUT_NAME = "accuratum.png"
|
|
51
|
+
DEFAULT_LINE_POINTS = 500
|
|
52
|
+
DEFAULT_TIME_STEP_MIN = 20
|
|
53
|
+
DEFAULT_DAYLINE_DAY_STEP = 7
|
|
54
|
+
DEFAULT_HOURLINE_DAY_STEP = 1
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def parse_lat_long(value: str) -> tuple[float, float]:
|
|
58
|
+
cleaned = value.strip().lstrip("(").rstrip(")")
|
|
59
|
+
parts = [p.strip() for p in cleaned.split(",")]
|
|
60
|
+
if len(parts) != 2:
|
|
61
|
+
raise ValueError(f"expected 'LAT,LON', got {value!r}")
|
|
62
|
+
try:
|
|
63
|
+
return float(parts[0]), float(parts[1])
|
|
64
|
+
except ValueError:
|
|
65
|
+
raise ValueError(f"could not parse {value!r} as two floats.")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def parse_rect(value: str) -> tuple[float, float, float, float]:
|
|
69
|
+
cleaned = value.strip().lstrip("(").rstrip(")")
|
|
70
|
+
parts = [p.strip() for p in cleaned.split(",")]
|
|
71
|
+
if len(parts) != 4:
|
|
72
|
+
raise ValueError(f"expected 'LEFT,BOTTOM,WIDTH,HEIGHT', got {value!r}")
|
|
73
|
+
try:
|
|
74
|
+
return tuple(float(p) for p in parts) # type: ignore[return-value]
|
|
75
|
+
except ValueError:
|
|
76
|
+
raise ValueError(f"could not parse {value!r} as four floats.")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def parse_color(value: str) -> str:
|
|
80
|
+
"""Any matplotlib color (``orange``, ``#123ABC``, ``C0``), saved as ``#rrggbb``."""
|
|
81
|
+
try:
|
|
82
|
+
return to_hex(value)
|
|
83
|
+
except ValueError:
|
|
84
|
+
raise ValueError(f"not a color: {value!r}")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
88
|
+
parser = argparse.ArgumentParser(
|
|
89
|
+
prog="accuratum",
|
|
90
|
+
description=(
|
|
91
|
+
"Generate an Accuratum sundial for a location and save it as a project folder "
|
|
92
|
+
"(project.json + polylines.npz), or render a saved project with --project."
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
parser.add_argument("location", nargs="?", default=None)
|
|
96
|
+
parser.add_argument(
|
|
97
|
+
"--lat-long",
|
|
98
|
+
type=parse_lat_long,
|
|
99
|
+
default=None,
|
|
100
|
+
metavar="LAT,LON",
|
|
101
|
+
help=f"Latitude within ±{MAX_LATITUDE:g}°. Negative values need '=': --lat-long=-15.78,-47.92.",
|
|
102
|
+
)
|
|
103
|
+
parser.add_argument(
|
|
104
|
+
"--output",
|
|
105
|
+
"-o",
|
|
106
|
+
default=None,
|
|
107
|
+
help=f"Image to write (.png, .pdf, .svg). Defaults to {DEFAULT_OUTPUT_NAME} in the project folder.",
|
|
108
|
+
)
|
|
109
|
+
parser.add_argument("--plumb-length", type=float, default=1.0)
|
|
110
|
+
parser.add_argument("--year", type=int, default=None, help="Defaults to the current year.")
|
|
111
|
+
parser.add_argument(
|
|
112
|
+
"--period",
|
|
113
|
+
type=int,
|
|
114
|
+
choices=(0, 1),
|
|
115
|
+
default=0,
|
|
116
|
+
help="0 = Dec(year-1) -> Jun(year), 1 = Jun(year) -> Dec(year).",
|
|
117
|
+
)
|
|
118
|
+
parser.add_argument("--timezone", default=None)
|
|
119
|
+
parser.add_argument("--line-points", type=int, default=DEFAULT_LINE_POINTS)
|
|
120
|
+
parser.add_argument("--time-step", type=int, default=DEFAULT_TIME_STEP_MIN, metavar="MINUTES")
|
|
121
|
+
parser.add_argument("--dayline-day-step", type=int, default=DEFAULT_DAYLINE_DAY_STEP, metavar="DAYS")
|
|
122
|
+
parser.add_argument("--hourline-day-step", type=int, default=DEFAULT_HOURLINE_DAY_STEP, metavar="DAYS")
|
|
123
|
+
parser.add_argument("--logo", default=None, metavar="PATH")
|
|
124
|
+
parser.add_argument("--logo-rect", type=parse_rect, default=None, metavar="LEFT,BOTTOM,WIDTH,HEIGHT")
|
|
125
|
+
parser.add_argument("--compass", default=None, metavar="PATH")
|
|
126
|
+
parser.add_argument("--compass-rect", type=parse_rect, default=None, metavar="LEFT,BOTTOM,WIDTH,HEIGHT")
|
|
127
|
+
parser.add_argument("--label-fontsize", type=float, default=None, metavar="PT")
|
|
128
|
+
parser.add_argument(
|
|
129
|
+
"--dayline-color",
|
|
130
|
+
type=parse_color,
|
|
131
|
+
default=None,
|
|
132
|
+
metavar="COLOR",
|
|
133
|
+
help=f"Name or #rrggbb. Default {RenderHints.dayline_color}.",
|
|
134
|
+
)
|
|
135
|
+
parser.add_argument(
|
|
136
|
+
"--hourline-color",
|
|
137
|
+
type=parse_color,
|
|
138
|
+
default=None,
|
|
139
|
+
metavar="COLOR",
|
|
140
|
+
help=f"Name or #rrggbb. Default {RenderHints.hourline_color}.",
|
|
141
|
+
)
|
|
142
|
+
parser.add_argument(
|
|
143
|
+
"--title",
|
|
144
|
+
default=None,
|
|
145
|
+
help="Defaults to the location name, or its coordinates. '' for none. With --project: this run only.",
|
|
146
|
+
)
|
|
147
|
+
parser.add_argument(
|
|
148
|
+
"--subtitle", default=None, help="Defaults to the timeframe. '' for none. With --project: this run only."
|
|
149
|
+
)
|
|
150
|
+
parser.add_argument(
|
|
151
|
+
"--project-dir",
|
|
152
|
+
default=None,
|
|
153
|
+
metavar="DIR",
|
|
154
|
+
help="Folder for a new project. Defaults to <location>_<year>_p<period> in the current directory.",
|
|
155
|
+
)
|
|
156
|
+
parser.add_argument("--force", action="store_true", help="Overwrite an existing project folder.")
|
|
157
|
+
parser.add_argument(
|
|
158
|
+
"--project",
|
|
159
|
+
default=None,
|
|
160
|
+
metavar="DIR",
|
|
161
|
+
help=(
|
|
162
|
+
"Render a saved project folder without recomputing it. Render flags "
|
|
163
|
+
"(--logo, --label-fontsize, ...) override its saved render settings for this run."
|
|
164
|
+
),
|
|
165
|
+
)
|
|
166
|
+
parser.add_argument(
|
|
167
|
+
"--regenerate",
|
|
168
|
+
action="store_true",
|
|
169
|
+
help=(
|
|
170
|
+
"With --project: recompute geometry and labels from the project's spec "
|
|
171
|
+
"(after editing it). The old project.json is kept as project.json.bak."
|
|
172
|
+
),
|
|
173
|
+
)
|
|
174
|
+
return parser
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _parse_args(argv: Sequence[str] | None) -> argparse.Namespace:
|
|
178
|
+
parser = build_parser()
|
|
179
|
+
args = parser.parse_args(argv)
|
|
180
|
+
if args.location is not None and args.lat_long is not None:
|
|
181
|
+
parser.error("provide either a location string or --lat-long, not both.")
|
|
182
|
+
if args.project is not None and (args.location is not None or args.lat_long is not None):
|
|
183
|
+
parser.error("--project renders a saved project; don't give a location with it.")
|
|
184
|
+
if args.regenerate and args.project is None:
|
|
185
|
+
parser.error("--regenerate needs --project.")
|
|
186
|
+
return args
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def resolve_location(args: argparse.Namespace) -> tuple[float, float]:
|
|
190
|
+
if args.lat_long is not None:
|
|
191
|
+
return args.lat_long
|
|
192
|
+
if args.location is None:
|
|
193
|
+
raise SystemExit("error: provide a location string or --lat-long")
|
|
194
|
+
latlon = location_to_latitude_longitude(args.location)
|
|
195
|
+
if latlon is None:
|
|
196
|
+
raise SystemExit(f"error: could not resolve location {args.location!r} via geocoder.")
|
|
197
|
+
return latlon
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _spec_from_args(args: argparse.Namespace) -> SundialSpec:
|
|
201
|
+
"""Build a SundialSpec from CLI args."""
|
|
202
|
+
lat, lon = resolve_location(args)
|
|
203
|
+
if abs(lat) > MAX_LATITUDE:
|
|
204
|
+
raise SystemExit(f"error: latitude {lat:g}° is outside the supported range ±{MAX_LATITUDE:g}°.")
|
|
205
|
+
tz_str = args.timezone or timezone_at(lat=lat, lng=lon) or "UTC"
|
|
206
|
+
tz = ZoneInfo(tz_str)
|
|
207
|
+
year = args.year if args.year is not None else datetime.now(tz=tz).year
|
|
208
|
+
try:
|
|
209
|
+
return SundialSpec(
|
|
210
|
+
location=Location(lat=lat, lon=lon, timezone=tz_str, name=args.location),
|
|
211
|
+
timeframe=solstice_timeframe(year, args.period, tz),
|
|
212
|
+
plumb_length=args.plumb_length,
|
|
213
|
+
grid=GridConfig(
|
|
214
|
+
dayline_day_step_days=args.dayline_day_step,
|
|
215
|
+
line_points=args.line_points,
|
|
216
|
+
hourline_day_step_days=args.hourline_day_step,
|
|
217
|
+
time_step_minutes=args.time_step,
|
|
218
|
+
),
|
|
219
|
+
year=year,
|
|
220
|
+
period=args.period,
|
|
221
|
+
)
|
|
222
|
+
except ValueError as exc:
|
|
223
|
+
raise SystemExit(f"error: {exc}")
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _default_project_dir(spec: SundialSpec) -> Path:
|
|
227
|
+
"""``<location-slug>_<year>_p<period>``, e.g. ``planaltina-df_2026_p0``."""
|
|
228
|
+
loc = spec.location
|
|
229
|
+
if loc.name:
|
|
230
|
+
base = re.sub(r"[^a-z0-9]+", "-", loc.name.lower()).strip("-")
|
|
231
|
+
else:
|
|
232
|
+
base = f"lat{loc.lat:.2f}_lon{loc.lon:.2f}"
|
|
233
|
+
return Path(f"{base}_{spec.year}_p{spec.period}")
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _provenance() -> dict[str, str]:
|
|
237
|
+
def _version(pkg: str) -> str:
|
|
238
|
+
try:
|
|
239
|
+
return version(pkg)
|
|
240
|
+
except PackageNotFoundError:
|
|
241
|
+
return "unknown"
|
|
242
|
+
|
|
243
|
+
return {
|
|
244
|
+
"accuratum": _version("accuratum"),
|
|
245
|
+
"astropy": _version("astropy"),
|
|
246
|
+
"created": datetime.now().astimezone().isoformat(timespec="seconds"),
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
# --- render hints ------------------------------------------------------------
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _render_hints(args: argparse.Namespace, saved: RenderHints | None) -> RenderHints:
|
|
254
|
+
"""Merge render flags over *saved* hints (or the defaults). Flags win."""
|
|
255
|
+
base = saved or default_render_hints()
|
|
256
|
+
overlays = list(base.overlays)
|
|
257
|
+
for name, path, rect in (("logo", args.logo, args.logo_rect), ("compass", args.compass, args.compass_rect)):
|
|
258
|
+
if path is None and rect is None:
|
|
259
|
+
continue
|
|
260
|
+
index = next((i for i, o in enumerate(overlays) if o.name == name), None)
|
|
261
|
+
current = overlays[index] if index is not None else DEFAULT_OVERLAYS[name]
|
|
262
|
+
updated = replace(
|
|
263
|
+
current,
|
|
264
|
+
image_path=_portable_path(path) if path is not None else current.image_path,
|
|
265
|
+
rect=rect if rect is not None else current.rect,
|
|
266
|
+
)
|
|
267
|
+
if index is None:
|
|
268
|
+
overlays.append(updated)
|
|
269
|
+
else:
|
|
270
|
+
overlays[index] = updated
|
|
271
|
+
return replace(
|
|
272
|
+
base,
|
|
273
|
+
overlays=overlays,
|
|
274
|
+
label_fontsize=args.label_fontsize if args.label_fontsize is not None else base.label_fontsize,
|
|
275
|
+
dayline_color=args.dayline_color or base.dayline_color,
|
|
276
|
+
hourline_color=args.hourline_color or base.hourline_color,
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _portable_path(path: str) -> str:
|
|
281
|
+
"""User-given image paths are stored absolute, so the project works from any directory."""
|
|
282
|
+
return os.path.abspath(path)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _resolved(hints: RenderHints) -> RenderHints:
|
|
286
|
+
"""Resolve ``accuratum:`` image paths and check that every overlay file exists."""
|
|
287
|
+
overlays = []
|
|
288
|
+
for overlay in hints.overlays:
|
|
289
|
+
try:
|
|
290
|
+
path = resolve_image_path(overlay.image_path)
|
|
291
|
+
except ValueError as exc:
|
|
292
|
+
raise SystemExit(f"error: {overlay.name or 'overlay'} {exc}")
|
|
293
|
+
if not os.path.isfile(path):
|
|
294
|
+
raise SystemExit(f"error: {overlay.name or 'overlay'} file not found: {path}")
|
|
295
|
+
overlays.append(replace(overlay, image_path=path))
|
|
296
|
+
return replace(hints, overlays=overlays)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _titled(plot: Plot, args: argparse.Namespace) -> Plot:
|
|
300
|
+
"""Replace the plot's title and subtitle with the ones given by flag."""
|
|
301
|
+
return replace(
|
|
302
|
+
plot,
|
|
303
|
+
title=args.title if args.title is not None else plot.title,
|
|
304
|
+
subtitle=args.subtitle if args.subtitle is not None else plot.subtitle,
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _kept(saved: str | None, old_default: str, new_default: str) -> str:
|
|
309
|
+
"""A text edited by hand survives a regenerate; a default one follows the new spec."""
|
|
310
|
+
return new_default if saved is None or saved == old_default else saved
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
# --- modes -------------------------------------------------------------------
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _generate(args: argparse.Namespace) -> tuple[Project, Path]:
|
|
317
|
+
spec = _spec_from_args(args)
|
|
318
|
+
folder = Path(args.project_dir) if args.project_dir else _default_project_dir(spec)
|
|
319
|
+
if (folder / PROJECT_FILE).exists() and not args.force:
|
|
320
|
+
raise SystemExit(
|
|
321
|
+
f"error: {folder} already holds a project; use --project {folder} to render it, or --force to overwrite."
|
|
322
|
+
)
|
|
323
|
+
render = _render_hints(args, None)
|
|
324
|
+
_resolved(render) # fail on a missing image before the slow computation
|
|
325
|
+
project = Project(spec=spec, plot=_titled(build_plot(spec), args), render=render, provenance=_provenance())
|
|
326
|
+
save_project(project, folder)
|
|
327
|
+
print(f"Saved project to {folder}/")
|
|
328
|
+
return project, folder
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _regenerate(folder: Path) -> Project:
|
|
332
|
+
"""Recompute *folder*'s project from its spec; the timeframe follows year/period."""
|
|
333
|
+
data = json.loads((folder / PROJECT_FILE).read_text(encoding="utf-8"))
|
|
334
|
+
spec = spec_from_dict(data["spec"])
|
|
335
|
+
old_title, old_subtitle = default_title(spec), default_subtitle(spec)
|
|
336
|
+
if spec.year is not None and spec.period is not None:
|
|
337
|
+
spec.timeframe = solstice_timeframe(spec.year, spec.period, ZoneInfo(spec.location.timezone))
|
|
338
|
+
render = hints_from_dict(data.get("render", {}))
|
|
339
|
+
shutil.copyfile(folder / PROJECT_FILE, folder / (PROJECT_FILE + ".bak"))
|
|
340
|
+
plot = build_plot(spec)
|
|
341
|
+
plot = replace(
|
|
342
|
+
plot,
|
|
343
|
+
title=_kept(data.get("title"), old_title, plot.title),
|
|
344
|
+
subtitle=_kept(data.get("subtitle"), old_subtitle, plot.subtitle),
|
|
345
|
+
)
|
|
346
|
+
project = Project(spec=spec, plot=plot, render=render, provenance=_provenance())
|
|
347
|
+
save_project(project, folder)
|
|
348
|
+
print(f"Regenerated {folder}/ (previous file kept as {PROJECT_FILE}.bak)")
|
|
349
|
+
return project
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _open(args: argparse.Namespace) -> tuple[Project, Path]:
|
|
353
|
+
folder = Path(args.project)
|
|
354
|
+
if not (folder / PROJECT_FILE).is_file():
|
|
355
|
+
raise SystemExit(f"error: no {PROJECT_FILE} in {folder}")
|
|
356
|
+
try:
|
|
357
|
+
if args.regenerate:
|
|
358
|
+
return _regenerate(folder), folder
|
|
359
|
+
return load_project(folder), folder
|
|
360
|
+
except StaleProjectError as exc:
|
|
361
|
+
raise SystemExit(f"error: {exc} Run with --project {folder} --regenerate.")
|
|
362
|
+
except ValueError as exc:
|
|
363
|
+
raise SystemExit(f"error: {folder / PROJECT_FILE}: {exc}")
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
367
|
+
args = _parse_args(argv)
|
|
368
|
+
project, folder = _open(args) if args.project is not None else _generate(args)
|
|
369
|
+
hints = _resolved(_render_hints(args, project.render))
|
|
370
|
+
output = args.output or str(folder / DEFAULT_OUTPUT_NAME)
|
|
371
|
+
_save(_titled(project.plot, args), hints, output)
|
|
372
|
+
print(f"Saved Accuratum clock to {output}")
|
|
373
|
+
return 0
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _save(plot: Plot, hints: RenderHints, output: str) -> None:
|
|
377
|
+
"""Render with matplotlib; the extension (.png, .pdf, .svg, ...) picks the format."""
|
|
378
|
+
fig, _ = matplotlib_backend.render(plot, hints)
|
|
379
|
+
fig.savefig(output, dpi=200, bbox_inches="tight")
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
__all__ = ["build_parser", "main", "parse_lat_long", "parse_rect", "resolve_location"]
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
if __name__ == "__main__":
|
|
386
|
+
sys.exit(main())
|
|
File without changes
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Solar geometry — Sun position and sunrise/sunset queries.
|
|
2
|
+
|
|
3
|
+
This is the bottom of the core stack. It knows about astropy and astroplan,
|
|
4
|
+
but nothing about sundial types, grids, or rendering.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import warnings
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from astroplan import Observer, TargetNeverUpWarning
|
|
11
|
+
from astropy.coordinates import AltAz, EarthLocation, get_sun
|
|
12
|
+
from astropy.time import Time
|
|
13
|
+
from astropy.units import deg
|
|
14
|
+
from astropy.utils import iers
|
|
15
|
+
|
|
16
|
+
# Use the IERS and leap-second tables bundled with astropy (astropy-iers-data,
|
|
17
|
+
# pinned by uv.lock) instead of downloading fresh ones at run time. A server
|
|
18
|
+
# instance then needs no network, no writable home and no IERS server. The
|
|
19
|
+
# cost is up to ~0.9 s of UT1-UTC error, invisible on a sundial.
|
|
20
|
+
iers.conf.auto_download = False
|
|
21
|
+
iers.conf.auto_max_age = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def build_altaz_frame(lat: float, lon: float) -> AltAz:
|
|
25
|
+
"""Local AltAz frame at *(lat, lon)*. Pressure = 0 skips refraction."""
|
|
26
|
+
location = EarthLocation(lat=lat * deg, lon=lon * deg)
|
|
27
|
+
return AltAz(location=location, pressure=0)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def get_sun_altaz(times: np.ndarray, frame: AltAz) -> tuple[np.ndarray, np.ndarray]:
|
|
31
|
+
"""Solar (alt_deg, az_deg) for each ``datetime64`` in *times*."""
|
|
32
|
+
sun = get_sun(Time(times)).transform_to(frame)
|
|
33
|
+
return sun.alt.value, sun.az.value # type: ignore[return-value]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def local_mean_midnights(dates: np.ndarray, lon: float) -> np.ndarray:
|
|
37
|
+
"""Local mean midnight of each date, as UTC ``datetime64[s]``.
|
|
38
|
+
|
|
39
|
+
That is 00 UTC shifted by the longitude (4 min per degree, rounded to
|
|
40
|
+
the minute). Anchoring days at 00 UTC instead splits the local day in
|
|
41
|
+
two wherever it straddles 00 UTC (the Americas' west, Asia, Oceania).
|
|
42
|
+
"""
|
|
43
|
+
return dates.astype("datetime64[D]").astype("datetime64[s]") - np.timedelta64(round(lon * 4), "m")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def get_sunrises_and_sunsets(
|
|
47
|
+
dates: np.ndarray,
|
|
48
|
+
lat: float,
|
|
49
|
+
lon: float,
|
|
50
|
+
horizon_deg: float = 0.0,
|
|
51
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
52
|
+
"""``(sunrises, sunsets)`` as ``datetime64[s]`` arrays for each date in *dates*.
|
|
53
|
+
|
|
54
|
+
*dates* is an array of ``datetime64`` (any time-of-day component is
|
|
55
|
+
ignored). The search starts at each date's local mean midnight (see
|
|
56
|
+
:func:`local_mean_midnights`), so rise and set belong to the same local
|
|
57
|
+
day at any longitude. *horizon_deg* is the altitude in degrees that defines
|
|
58
|
+
rise/set; ``0`` is the geometric horizon. Days when the sun never
|
|
59
|
+
climbs above it (high-latitude winters) are ``NaT`` in both arrays.
|
|
60
|
+
"""
|
|
61
|
+
observer = Observer(location=EarthLocation(lat=lat * deg, lon=lon * deg))
|
|
62
|
+
midnights = Time(local_mean_midnights(dates, lon), scale="utc")
|
|
63
|
+
with warnings.catch_warnings():
|
|
64
|
+
# Expected past |lat| ≈ 56.5° with a 10° cut; those days become NaT.
|
|
65
|
+
warnings.simplefilter("ignore", TargetNeverUpWarning)
|
|
66
|
+
sunrises = observer.sun_rise_time(midnights, which="next", horizon=horizon_deg * deg)
|
|
67
|
+
never_up = np.broadcast_to(np.ma.getmaskarray(sunrises.jd), midnights.shape)
|
|
68
|
+
# A masked Time can't feed sun_set_time, so search from midnight on those days.
|
|
69
|
+
sunrises = Time(np.where(never_up, midnights.jd, sunrises.unmasked.jd), format="jd", scale="utc")
|
|
70
|
+
sunsets = observer.sun_set_time(sunrises, which="next", horizon=horizon_deg * deg)
|
|
71
|
+
never_up = never_up | np.ma.getmaskarray(sunsets.jd)
|
|
72
|
+
nat = np.datetime64("NaT", "s")
|
|
73
|
+
return (
|
|
74
|
+
np.where(never_up, nat, sunrises.datetime64.astype("datetime64[s]")), # type: ignore[attr-defined]
|
|
75
|
+
np.where(never_up, nat, sunsets.unmasked.datetime64.astype("datetime64[s]")), # type: ignore[attr-defined]
|
|
76
|
+
)
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""``build_plot`` — orchestrates the Spec → Plot pipeline.
|
|
2
|
+
|
|
3
|
+
Pure top of the core stack: given a :class:`SundialSpec`, generate the
|
|
4
|
+
time grids, project them through the sundial type's projection, attach
|
|
5
|
+
metadata, select and place the default labels, add the default title and
|
|
6
|
+
subtitle, and return a :class:`Plot`.
|
|
7
|
+
|
|
8
|
+
No I/O, no matplotlib. The renderer consumes the returned ``Plot``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from datetime import datetime, timedelta, timezone
|
|
12
|
+
from zoneinfo import ZoneInfo
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from accuratum.core.astronomy import build_altaz_frame, get_sun_altaz
|
|
17
|
+
from accuratum.core.plot import Plot, Polyline, data_extent
|
|
18
|
+
from accuratum.core.spec import SundialSpec
|
|
19
|
+
from accuratum.core.timegrid import dayline_grid, hourline_grid
|
|
20
|
+
from accuratum.defaults.labels import select_dayline_labels, select_hourline_labels
|
|
21
|
+
from accuratum.defaults.placement import place_labels
|
|
22
|
+
from accuratum.defaults.titles import default_subtitle, default_title
|
|
23
|
+
from accuratum.projections.accuratum import project as project_accuratum
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_plot(spec: SundialSpec) -> Plot:
|
|
27
|
+
"""Return a :class:`Plot` for *spec*. Pure function (no I/O)."""
|
|
28
|
+
if spec.sundial_type != "accuratum":
|
|
29
|
+
raise ValueError(f"unsupported sundial_type: {spec.sundial_type!r}")
|
|
30
|
+
|
|
31
|
+
tz = ZoneInfo(spec.location.timezone)
|
|
32
|
+
frame = build_altaz_frame(spec.location.lat, spec.location.lon)
|
|
33
|
+
|
|
34
|
+
dl_grid = dayline_grid(spec.timeframe, spec.location, spec.grid)
|
|
35
|
+
hl_grid = hourline_grid(spec.timeframe, spec.location, spec.grid)
|
|
36
|
+
|
|
37
|
+
dayline_polys = [_row_to_dayline(row, frame, tz, spec.plumb_length) for row in dl_grid]
|
|
38
|
+
hourline_polys = [_row_to_hourline(row, frame, tz, spec.plumb_length) for row in hl_grid]
|
|
39
|
+
# Rows with no sun above the horizon cut (high-latitude winter days) are empty.
|
|
40
|
+
polylines = [p for p in dayline_polys + hourline_polys if p.xs.size]
|
|
41
|
+
|
|
42
|
+
extent = data_extent(polylines)
|
|
43
|
+
|
|
44
|
+
dl_labels = select_dayline_labels(polylines)
|
|
45
|
+
hl_labels = select_hourline_labels(polylines, spec.grid.time_step_minutes)
|
|
46
|
+
|
|
47
|
+
labels = place_labels(
|
|
48
|
+
polylines,
|
|
49
|
+
dl_labels,
|
|
50
|
+
hl_labels,
|
|
51
|
+
data_extent=extent,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
return Plot(
|
|
55
|
+
polylines=polylines,
|
|
56
|
+
labels=labels,
|
|
57
|
+
plumb_xy=(0.0, 0.0),
|
|
58
|
+
data_extent=extent,
|
|
59
|
+
title=default_title(spec),
|
|
60
|
+
subtitle=default_subtitle(spec),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# --- internals ---------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _row_to_dayline(row: np.ndarray, frame, tz: ZoneInfo, plumb_length: float) -> Polyline:
|
|
68
|
+
valid = row[~np.isnat(row)]
|
|
69
|
+
if valid.size == 0:
|
|
70
|
+
return Polyline(kind="dayline", xs=np.empty(0), ys=np.empty(0), metadata={})
|
|
71
|
+
|
|
72
|
+
alt, az = get_sun_altaz(valid, frame)
|
|
73
|
+
xs, ys = project_accuratum(alt, az, plumb_length)
|
|
74
|
+
|
|
75
|
+
local = _utc_dt64_to_local_datetime(valid[0], tz)
|
|
76
|
+
return Polyline(
|
|
77
|
+
kind="dayline",
|
|
78
|
+
xs=xs,
|
|
79
|
+
ys=ys,
|
|
80
|
+
metadata={"kind": "dayline", "date": local.strftime("%Y-%m-%d")},
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _row_to_hourline(row: np.ndarray, frame, tz: ZoneInfo, plumb_length: float) -> Polyline:
|
|
85
|
+
valid = row[~np.isnat(row)]
|
|
86
|
+
if valid.size == 0:
|
|
87
|
+
return Polyline(kind="hourline", xs=np.empty(0), ys=np.empty(0), metadata={})
|
|
88
|
+
|
|
89
|
+
alt, az = get_sun_altaz(valid, frame)
|
|
90
|
+
xs, ys = project_accuratum(alt, az, plumb_length)
|
|
91
|
+
|
|
92
|
+
local = _utc_dt64_to_standard_time(valid[valid.size // 2], tz)
|
|
93
|
+
target_hour, minute_offset = _canonical_hour(local.hour, local.minute)
|
|
94
|
+
return Polyline(
|
|
95
|
+
kind="hourline",
|
|
96
|
+
xs=xs,
|
|
97
|
+
ys=ys,
|
|
98
|
+
metadata={"kind": "hourline", "hour": target_hour, "minute_offset": minute_offset},
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _utc_dt64_to_local_datetime(dt64: np.datetime64, tz: ZoneInfo) -> datetime:
|
|
103
|
+
utc_dt = dt64.astype("datetime64[s]").astype(datetime).replace(tzinfo=timezone.utc)
|
|
104
|
+
return utc_dt.astimezone(tz)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _utc_dt64_to_standard_time(dt64: np.datetime64, tz: ZoneInfo) -> datetime:
|
|
108
|
+
"""Local *standard* time (DST removed) of *dt64*.
|
|
109
|
+
|
|
110
|
+
An hour line is one fixed UTC time of day across the frame, so it can
|
|
111
|
+
carry only one clock reading; a DST switch mid-frame would otherwise
|
|
112
|
+
label neighbouring lines with different clocks. Sundials read standard
|
|
113
|
+
time.
|
|
114
|
+
"""
|
|
115
|
+
local = _utc_dt64_to_local_datetime(dt64, tz)
|
|
116
|
+
return local - (local.dst() or timedelta(0))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _canonical_hour(hour: int, minute: int) -> tuple[int, int]:
|
|
120
|
+
"""Return ``(target_hour, signed_offset_min)`` snapping to the nearest hour."""
|
|
121
|
+
if minute <= 30:
|
|
122
|
+
return hour, minute
|
|
123
|
+
return (hour + 1) % 24, minute - 60
|
accuratum/core/hints.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Render-side knobs — separate from :class:`SundialSpec` to keep specs portable.
|
|
2
|
+
|
|
3
|
+
``RenderHints`` carries how a plot is drawn: overlay images, figure size,
|
|
4
|
+
fonts, colors. A project saves them next to the spec (in
|
|
5
|
+
``project.json``'s ``render`` section) but outside ``spec_hash``, so changing
|
|
6
|
+
them never invalidates the computed geometry. Renderers take ``(plot, hints)``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Overlay:
|
|
14
|
+
"""An image drawn over the figure; ``rect`` is in figure coords (0-1).
|
|
15
|
+
|
|
16
|
+
``name`` (e.g. ``"logo"``) lets the CLI replace one overlay of a saved
|
|
17
|
+
project by flag.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
image_path: str
|
|
21
|
+
rect: tuple[float, float, float, float]
|
|
22
|
+
name: str = ""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class RenderHints:
|
|
27
|
+
"""``axes_rect`` (figure coords) holds the drawing, pinned to its top edge.
|
|
28
|
+
The band above it is the header, where the default overlays sit; the
|
|
29
|
+
drawing's shape changes with latitude and period, so overlays placed on
|
|
30
|
+
top of it would cover lines somewhere.
|
|
31
|
+
|
|
32
|
+
The plot's title and subtitle go in the header too, between the default
|
|
33
|
+
overlays, at ``title_xy`` and ``subtitle_xy``.
|
|
34
|
+
|
|
35
|
+
Daylines and hourlines differ in color so the two families read apart.
|
|
36
|
+
The defaults are the Okabe-Ito vermillion and blue, which stay distinct
|
|
37
|
+
under protan-, deutan- and tritanopia. Colors are ``#rrggbb`` strings."""
|
|
38
|
+
|
|
39
|
+
overlays: list[Overlay] = field(default_factory=list)
|
|
40
|
+
figsize: tuple[float, float] = (8.0, 6.0)
|
|
41
|
+
axes_rect: tuple[float, float, float, float] = (0.07, 0.05, 0.9, 0.75)
|
|
42
|
+
dayline_color: str = "#d55e00"
|
|
43
|
+
hourline_color: str = "#0072b2"
|
|
44
|
+
line_width: float = 0.5
|
|
45
|
+
label_color: str = "black"
|
|
46
|
+
label_fontsize: float = 7.0
|
|
47
|
+
title_xy: tuple[float, float] = (0.51, 0.9)
|
|
48
|
+
subtitle_xy: tuple[float, float] = (0.51, 0.85)
|
|
49
|
+
title_fontsize: float = 14.0
|
|
50
|
+
subtitle_fontsize: float = 10.0
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Polyline metadata contract.
|
|
2
|
+
|
|
3
|
+
``Polyline.metadata`` identifies a line independently of its rendered text.
|
|
4
|
+
A label's ``selector`` is the same identity plus ``end`` (``"start"`` or
|
|
5
|
+
``"end"``), naming which endpoint the label sits at.
|
|
6
|
+
|
|
7
|
+
Built-in kinds are documented here as ``TypedDict``s so type checkers can
|
|
8
|
+
catch shape mistakes. Plugins are free to define their own kinds; the
|
|
9
|
+
contract is purely structural.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from typing import Literal, TypedDict
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class DaylineMetadata(TypedDict):
|
|
16
|
+
kind: Literal["dayline"]
|
|
17
|
+
date: str # "YYYY-MM-DD" in the spec's local timezone
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class HourlineMetadata(TypedDict):
|
|
21
|
+
kind: Literal["hourline"]
|
|
22
|
+
hour: int # canonical target hour in 0..23, local timezone — stable identity
|
|
23
|
+
minute_offset: int # signed minutes between the sampled middle and ``hour:00``
|