horizonchart 0.1.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.
@@ -0,0 +1,32 @@
1
+ """Clean horizon-view sky charts built on starplot."""
2
+
3
+ import os
4
+ from importlib.metadata import PackageNotFoundError, version
5
+ from pathlib import Path
6
+
7
+ try:
8
+ __version__ = version("horizonchart")
9
+ except PackageNotFoundError: # running from a source tree without installing
10
+ __version__ = "0.0.0"
11
+
12
+ SHARED_DATA_PATH = Path("/var/data")
13
+
14
+
15
+ def _data_path() -> Path:
16
+ """Where catalogs, ephemerides and caches go: $STARPLOT_DATA_PATH if set,
17
+ else /var/data if it exists and is writable, else the per-user cache
18
+ folder for this platform."""
19
+ if os.environ.get("STARPLOT_DATA_PATH"):
20
+ return Path(os.environ["STARPLOT_DATA_PATH"])
21
+ if SHARED_DATA_PATH.is_dir() and os.access(SHARED_DATA_PATH, os.W_OK):
22
+ return SHARED_DATA_PATH
23
+ from platformdirs import user_cache_path
24
+
25
+ return user_cache_path("horizonchart", appauthor=False)
26
+
27
+
28
+ DATA_PATH = _data_path()
29
+ DATA_PATH.mkdir(parents=True, exist_ok=True)
30
+ # Starplot fixes its data path when it's first imported, so this has to happen
31
+ # before anything imports starplot (importing horizonchart does it first)
32
+ os.environ["STARPLOT_DATA_PATH"] = str(DATA_PATH)
horizonchart/cli.py ADDED
@@ -0,0 +1,252 @@
1
+ """Command line interface: horizonchart target ... / horizonchart twilight ..."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import re
7
+ import sys
8
+ from datetime import date, datetime
9
+ from pathlib import Path
10
+ from zoneinfo import ZoneInfo
11
+
12
+ from timezonefinder import TimezoneFinder
13
+
14
+ from horizonchart import DATA_PATH, __version__
15
+ from horizonchart.skyview import (
16
+ LIMITING_MAGNITUDE,
17
+ plot_targets,
18
+ plot_twilight_views,
19
+ twilight_times,
20
+ )
21
+
22
+ GEOCODE_CACHE = DATA_PATH / "horizonchart-geocode.json"
23
+ # Nominatim's usage policy asks applications to identify themselves, ideally
24
+ # with a contact address (set HORIZONCHART_CONTACT, e.g. to an email address),
25
+ # and to make at most one request per second
26
+ GEOCODER_URL = "https://github.com/rtphokie/horizonchart"
27
+ GEOCODER_MIN_DELAY = 1.0
28
+
29
+ # "35.78,-78.64", "35.78 -78.64" or "35.78N 78.64W" (comma optional)
30
+ SIGNED_COORDINATES = re.compile(r"^\s*(-?\d+(?:\.\d+)?)\s*[,\s]\s*(-?\d+(?:\.\d+)?)\s*$")
31
+ HEMISPHERE_COORDINATES = re.compile(
32
+ r"^\s*(\d+(?:\.\d+)?)\s*°?\s*([NS])\s*[,\s]\s*(\d+(?:\.\d+)?)\s*°?\s*([EW])\s*$",
33
+ re.IGNORECASE,
34
+ )
35
+
36
+
37
+ def parse_coordinates(text: str) -> tuple[float, float] | None:
38
+ """Latitude and longitude from "35.78,-78.64" or "35.78N 78.64W", else None."""
39
+ if match := SIGNED_COORDINATES.match(text):
40
+ lat, lon = float(match[1]), float(match[2])
41
+ elif match := HEMISPHERE_COORDINATES.match(text):
42
+ lat = float(match[1]) * (-1 if match[2].upper() == "S" else 1)
43
+ lon = float(match[3]) * (-1 if match[4].upper() == "W" else 1)
44
+ else:
45
+ return None
46
+ if not (-90 <= lat <= 90 and -180 <= lon <= 180):
47
+ raise ValueError(f"Coordinates out of range: {text!r}")
48
+ return lat, lon
49
+
50
+
51
+ def geocode(place: str) -> tuple[float, float]:
52
+ """Coordinates of a place name such as "Raleigh, NC" or "Ottawa, ON", looked
53
+ up with OpenStreetMap's Nominatim service and cached on disk."""
54
+ try:
55
+ cache = json.loads(GEOCODE_CACHE.read_text())
56
+ except (OSError, ValueError):
57
+ cache = {}
58
+ key = place.strip().lower()
59
+ if key not in cache:
60
+ found = _rate_limited_geocode()(place, timeout=10)
61
+ if found is None:
62
+ raise ValueError(f"Couldn't find a location named {place!r}")
63
+ cache[key] = [found.latitude, found.longitude]
64
+ try:
65
+ GEOCODE_CACHE.write_text(json.dumps(cache, indent=1))
66
+ except OSError:
67
+ pass # the lookup still worked; it just isn't cached
68
+ lat, lon = cache[key]
69
+ return lat, lon
70
+
71
+
72
+ def geocoder_user_agent() -> str:
73
+ """e.g. "horizonchart/0.1.0 (+https://github.com/rtphokie/horizonchart; you@example.com)"."""
74
+ contact = os.environ.get("HORIZONCHART_CONTACT")
75
+ details = f"+{GEOCODER_URL}" + (f"; {contact}" if contact else "")
76
+ return f"horizonchart/{__version__} ({details})"
77
+
78
+
79
+ _geocoder = None
80
+
81
+
82
+ def _rate_limited_geocode():
83
+ """Nominatim geocoding, at most one request per GEOCODER_MIN_DELAY seconds."""
84
+ global _geocoder
85
+ if _geocoder is None:
86
+ from geopy.extra.rate_limiter import RateLimiter
87
+ from geopy.geocoders import Nominatim
88
+
89
+ nominatim = Nominatim(user_agent=geocoder_user_agent())
90
+ _geocoder = RateLimiter(nominatim.geocode, min_delay_seconds=GEOCODER_MIN_DELAY)
91
+ return _geocoder
92
+
93
+
94
+ def resolve_location(text: str) -> tuple[float, float]:
95
+ """Coordinates from either a coordinate pair or a place name."""
96
+ return parse_coordinates(text) or geocode(text)
97
+
98
+
99
+ def local_zone(lat: float, lon: float, tz: str | None) -> ZoneInfo:
100
+ return ZoneInfo(tz or TimezoneFinder().timezone_at(lat=lat, lng=lon))
101
+
102
+
103
+ # With no --time, target charts show the sky this long after today's sunset
104
+ DEFAULT_HOURS_AFTER_SUNSET = 2
105
+
106
+
107
+ def default_target_time(lat: float, lon: float, zone: ZoneInfo) -> datetime:
108
+ """DEFAULT_HOURS_AFTER_SUNSET after today's sunset at `lat`/`lon`,
109
+ rounded to the nearest half hour."""
110
+ today = datetime.now(zone).date()
111
+ return twilight_times(lat, lon, today, zone.key, DEFAULT_HOURS_AFTER_SUNSET)[1]
112
+
113
+
114
+ def parse_local_datetime(text: str, zone: ZoneInfo) -> datetime:
115
+ """ "2026-10-02 22:00" (or "2026-10-02T22:00") as local time in `zone`."""
116
+ parsed = datetime.fromisoformat(text.strip())
117
+ if parsed.tzinfo is None:
118
+ return parsed.replace(tzinfo=zone)
119
+ return parsed.astimezone(zone)
120
+
121
+
122
+ def build_parser() -> argparse.ArgumentParser:
123
+ parser = argparse.ArgumentParser(
124
+ prog="horizonchart",
125
+ description="Clean horizon-view sky charts.",
126
+ )
127
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
128
+ commands = parser.add_subparsers(dest="command", required=True)
129
+
130
+ location_help = (
131
+ 'where you are: coordinates ("35.78,-78.64" or "35.78N 78.64W") or a '
132
+ 'place name ("Raleigh, NC", "Ottawa, ON")'
133
+ )
134
+ common = argparse.ArgumentParser(add_help=False)
135
+ common.add_argument("-l", "--location", required=True, help=location_help)
136
+ common.add_argument(
137
+ "--tz", help="time zone name (default: looked up from the location)"
138
+ )
139
+ common.add_argument(
140
+ "-o", "--output-dir", default=".", type=Path, help="where to write the PNG"
141
+ )
142
+ common.add_argument(
143
+ "--no-timestamp",
144
+ dest="timestamp",
145
+ action="store_false",
146
+ help="leave off the date, time and place in the lower right corner",
147
+ )
148
+ common.add_argument(
149
+ "--no-labels",
150
+ dest="labels",
151
+ action="store_false",
152
+ help="leave off the names of planets, the Moon, stars, deep-sky objects, "
153
+ "asterisms and constellations",
154
+ )
155
+
156
+ target = commands.add_parser(
157
+ "target",
158
+ parents=[common],
159
+ help="finder chart for one or more objects at a given time",
160
+ description="Finder chart for planets, the Moon, stars or deep-sky objects.",
161
+ )
162
+ target.add_argument(
163
+ "targets",
164
+ nargs="+",
165
+ metavar="TARGET",
166
+ help='e.g. Saturn, Moon, "saturn barycenter", Pleiades, M31, "NGC 1976", Vega',
167
+ )
168
+ target.add_argument(
169
+ "-t",
170
+ "--time",
171
+ help='local date and time, e.g. "2026-10-02 22:00" (default: 2 hours after '
172
+ "today's sunset, to the nearest half hour)",
173
+ )
174
+
175
+ twilight = commands.add_parser(
176
+ "twilight",
177
+ parents=[common],
178
+ help="morning and evening twilight views for a date",
179
+ description=(
180
+ "Views before sunrise and after sunset, looking east or west, "
181
+ "whichever shows more."
182
+ ),
183
+ )
184
+ twilight.add_argument(
185
+ "-d", "--date", type=date.fromisoformat, help="e.g. 2026-10-02 (default: today)"
186
+ )
187
+ twilight.add_argument(
188
+ "-m",
189
+ "--limiting-magnitude",
190
+ type=float,
191
+ default=LIMITING_MAGNITUDE,
192
+ help=f"faintest stars and deep-sky objects to show (default: {LIMITING_MAGNITUDE}, "
193
+ "suburban twilight; dark skies 4-6)",
194
+ )
195
+ twilight.add_argument(
196
+ "--no-title",
197
+ dest="title",
198
+ action="store_false",
199
+ help='leave off the title ("Looking east, 1 hour before sunrise")',
200
+ )
201
+ return parser
202
+
203
+
204
+ def main(argv: list[str] | None = None) -> int:
205
+ args = build_parser().parse_args(argv)
206
+ try:
207
+ lat, lon = resolve_location(args.location)
208
+ zone = local_zone(lat, lon, args.tz)
209
+ args.output_dir.mkdir(parents=True, exist_ok=True)
210
+
211
+ if args.command == "target":
212
+ when = (
213
+ parse_local_datetime(args.time, zone)
214
+ if args.time
215
+ else default_target_time(lat, lon, zone)
216
+ )
217
+ paths = [
218
+ plot_targets(
219
+ lat,
220
+ lon,
221
+ args.targets,
222
+ when,
223
+ args.output_dir,
224
+ timestamp=args.timestamp,
225
+ labels=args.labels,
226
+ )
227
+ ]
228
+ else:
229
+ day = args.date or datetime.now(zone).date()
230
+ views = plot_twilight_views(
231
+ lat,
232
+ lon,
233
+ day,
234
+ tz=zone.key,
235
+ output_dir=args.output_dir,
236
+ limiting_magnitude=args.limiting_magnitude,
237
+ title=args.title,
238
+ timestamp=args.timestamp,
239
+ labels=args.labels,
240
+ )
241
+ paths = list(views.values())
242
+ except ValueError as error:
243
+ print(f"horizonchart: {error}", file=sys.stderr)
244
+ return 1
245
+
246
+ for path in paths:
247
+ print(path)
248
+ return 0
249
+
250
+
251
+ if __name__ == "__main__":
252
+ sys.exit(main())
Binary file
@@ -0,0 +1,93 @@
1
+ Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.