From 4c0cebf1a0ee04d8f6321392641ca38ecef3656d Mon Sep 17 00:00:00 2001 From: Yashvi-Sharma Date: Mon, 9 Nov 2026 15:40:48 -0800 Subject: [PATCH 1/3] Narrow observation-info exception handling and drop dead moon helpers get_observation_info_from_cmds wrapped a single from_currsys call in a bare except, so a missing !OBS coordinate key and a genuine failure were handled identically. from_currsys raises ValueError when a bang-key is absent; catch only that. Anything else now propagates instead of being flattened to None and resurfacing as a misleading "No valid target coordinates provided". get_next_moon and _get_next_moon_cached had no live callers; their only call site has been commented out since it was written. The cache was also keyed to the calendar day while calling Time.now() inside the cached body, so it could return a result up to 24h stale, and it raised when location_key was None despite that being the default. Co-Authored-By: Claude Opus 5 --- scopesim/tests/test_utils_functions.py | 35 +++++++++++++++++++ scopesim/utils.py | 48 ++------------------------ 2 files changed, 38 insertions(+), 45 deletions(-) diff --git a/scopesim/tests/test_utils_functions.py b/scopesim/tests/test_utils_functions.py index 1469b32d..93c79c1f 100644 --- a/scopesim/tests/test_utils_functions.py +++ b/scopesim/tests/test_utils_functions.py @@ -338,3 +338,38 @@ def test_2d_from_3d(self): }) data = utils.zeros_from_header(hdr, ndims=2) assert data.shape == (5, 3) + + +class TestGetObservationInfoFromCmds: + """A missing !OBS coordinate key is optional; a real failure is not.""" + + @staticmethod + def _cmds(**extra): + from scopesim.commands import UserCommands + properties = {"!ATMO.longitude": -70.19, "!ATMO.latitude": -24.59, + "!ATMO.altitude": 3060, "!OBS.mjdobs": 60310.25} + properties.update(extra) + return UserCommands(properties=properties) + + def test_absent_coordinate_keys_fall_back_to_alt_az(self): + # !OBS.ra/!OBS.dec/!OBS.airmass are simply not configured here. + target, location, time, brightness = utils.get_observation_info_from_cmds( + self._cmds(**{"!OBS.alt": 60, "!OBS.az": 0})) + assert target.alt.to_value(u.deg) == approx(60) + assert location.lat.to_value(u.deg) == approx(-24.59) + assert time.mjd == approx(60310.25) + assert brightness is None + + def test_unrelated_failure_propagates_instead_of_becoming_none(self, monkeypatch): + # A bare except here used to turn any error into a missing coordinate, + # which then surfaced as a misleading "No valid target coordinates". + real_from_currsys = utils.from_currsys + + def exploding_from_currsys(item, cmds=None, **kwargs): + if item == "!OBS.ra": + raise RuntimeError("entirely unrelated failure") + return real_from_currsys(item, cmds, **kwargs) + + monkeypatch.setattr(utils, "from_currsys", exploding_from_currsys) + with pytest.raises(RuntimeError, match="entirely unrelated failure"): + utils.get_observation_info_from_cmds(self._cmds(**{"!OBS.alt": 60, "!OBS.az": 0})) diff --git a/scopesim/utils.py b/scopesim/utils.py index a6c60801..a035ae8d 100644 --- a/scopesim/utils.py +++ b/scopesim/utils.py @@ -1071,7 +1071,9 @@ def get_observation_info_from_cmds(cmds): for k, v in target_kwargs.items(): try: target_kwargs[k] = from_currsys(v, cmds) - except: + except ValueError: + # from_currsys raises ValueError when the bang-key is absent. + # Anything else is a real failure and must not be flattened to None. logger.debug(f'Target coord {v} not set in !OBS config.') target_kwargs[k] = None target_kwargs["obstime"] = time @@ -1187,10 +1189,6 @@ def resolve_time(time_str: int | float | Literal['bright', 'gray', 'grey', 'dark logger.error(f"Invalid time input type: {type(time_str)}, should be a string or numeric MJD value.") raise ValueError(f"Invalid time input type: {type(time_str)}, should be a string or numeric MJD value.") - # if t is None: - # kw = {"bright":"full", "gray":"half", "dark":"new"} - # t = Time(get_next_moon(kw[time_str], location), format="isot", location=location) - # check if t is at night if location is not None: nighttime = is_night(t, location, return_midnight=True) @@ -1225,43 +1223,3 @@ def get_moon_fli(phase_angle: u.Quantity): return (1 + np.cos(phase_angle.to(u.rad).value)) / 2 else: raise ValueError(f"Invalid phase angle type: {type(phase_angle)}, should be astropy Quantity object with angle units.") - -def get_next_moon(moontype="full", location: EarthLocation = None): - """ - Get time of the next closest moon phase of given moon type (full, half or new). - """ - geodetic = location.to_geodetic() - location_key = (float(geodetic.lon.to_value(u.deg)), float(geodetic.lat.to_value(u.deg)), - float(geodetic.height.to_value(u.m))) - today = Time.now().isot.split("T")[0] - return _get_next_moon_cached(moontype, today, location_key) - -@functools.lru_cache(maxsize=32) -def _get_next_moon_cached(moontype="full", today=None, location_key=None): - if location_key is None: - raise ValueError("location_key must be provided.") - lon_deg, lat_deg, height_m = location_key - location = EarthLocation.from_geodetic(lon=lon_deg * u.deg, lat=lat_deg * u.deg, height=height_m * u.m) - - now = Time.now() - utctimes = now + np.linspace(0, 28, 1000) * u.day - sunalts = np.array([get_sun(utctime).transform_to(AltAz(obstime=utctime, location=location)).alt.deg - for utctime in utctimes]) - - times = utctimes[sunalts < 0.0] # sun down - flis = get_moon_fli(get_moon_phase(times)) # fractional lunar illum - moonalts = np.array([get_body("moon", utctime).transform_to(AltAz(obstime=utctime, location=location)).alt.deg - for utctime in times]) - - if moontype == "full": - mask = (flis > 0.95) & (moonalts > 0.0) # few days around full moon, moon is up - nextm = (times[mask])[np.argmax(moonalts[mask])] # when moon is at peak altitude during full moon - elif moontype == "new": - mask = (flis < 0.05) & (moonalts < 0.0) # few days around new moon, moon is down - nextm = times[mask][np.argmin(flis[mask])] - elif moontype == "half": - mask = (moonalts > 0.0) & (flis > 0.4) & (flis < 0.6) # few days around half moon, moon is up - nextm = times[mask][np.argmax(moonalts[mask])] - else: - raise ValueError(f"Invalid moon type: {moontype}, should be 'full', 'new' or 'half'.") - return nextm From 127dcdcbf914258d32fe58ece482f04a4e07d7b4 Mon Sep 17 00:00:00 2001 From: Yashvi-Sharma Date: Mon, 9 Nov 2026 16:31:14 -0800 Subject: [PATCH 2/3] Add PR description for the observation-helper cleanups Co-Authored-By: Claude Opus 5 --- tb-01-utils-observation-helpers_changes.md | 88 ++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 tb-01-utils-observation-helpers_changes.md diff --git a/tb-01-utils-observation-helpers_changes.md b/tb-01-utils-observation-helpers_changes.md new file mode 100644 index 00000000..c9d1fc5c --- /dev/null +++ b/tb-01-utils-observation-helpers_changes.md @@ -0,0 +1,88 @@ +# tb-01-utils-observation-helpers + +Two unrelated cleanups in `scopesim/utils.py`, in the observation-info block +added to support the sky, PSF and atmospheric-dispersion effects. No behaviour +change on any path that currently works. + +## 1. Narrow the bare `except` + +`get_observation_info_from_cmds` resolves the optional `!OBS` pointing keys and +treats a missing one as "not configured": + +```python +for k, v in target_kwargs.items(): + try: + target_kwargs[k] = from_currsys(v, cmds) + except: # <- bare + logger.debug(f'Target coord {v} not set in !OBS config.') + target_kwargs[k] = None +``` + +The `try` wraps a single call where `v` is always a literal `"!OBS.*"` string. +The only failure it is meant to absorb is `from_currsys`'s own +`raise ValueError(f"{item} was not found in rc.__currsys__")`. + +As written it also swallowed `KeyboardInterrupt`, `SystemExit`, `MemoryError`, +`RecursionError`, and any `AttributeError` or `TypeError` from a malformed +`cmds` — converting each into `target_kwargs[k] = None`. Those `None`s then +flow into `get_target`, which raises +`ValueError("No valid target coordinates provided...")`. So a real failure +anywhere underneath surfaced as a confident, wrong diagnosis about pointing +configuration. + +Now `except ValueError:`. A missing key still behaves exactly as before. + +This matters because all three consumers call it during `__init__`: +`PalaceAirglowEmission`, `SkyBackgroundTERCurve` and `TAPASTERCurve` in +`sky_ter_curves.py`, plus `ADShift`/`ADCShift`. A swallowed error at +construction is hard to trace back. + +## 2. Delete `get_next_moon` and `_get_next_moon_cached` + +Both are dead. The only call site has been commented out since it was written, +in `resolve_time`: + +```python +# if t is None: +# kw = {"bright":"full", "gray":"half", "dark":"new"} +# t = Time(get_next_moon(kw[time_str], location), format="isot", location=location) +``` + +They are also wrong in two ways that would bite if revived: + +- `_get_next_moon_cached` is decorated `@functools.lru_cache(maxsize=32)` but + calls `Time.now()` **inside** the cached body, against a cache key whose time + component has only calendar-day resolution. Within one day the result is + frozen at the first call's wall clock, so it can be up to 24 hours stale. +- It raises `ValueError("location_key must be provided.")` when `location_key` + is `None`, which is its own default. + +Removed along with the commented call site. Recoverable from history if the +brightness-word moon-phase path is ever finished. + +No imports became unused: `functools` is still used by `@functools.wraps`, +`get_body` by `get_moon_phase`, and `get_sun`/`AltAz`/`EarthLocation` by +`is_night`, `get_zenith_angle` and `get_location`. + +## Tests + +- `test_absent_coordinate_keys_fall_back_to_alt_az` — with `!OBS.ra`, + `!OBS.dec` and `!OBS.airmass` unconfigured, the target still resolves from + alt/az, i.e. the optional-key behaviour is preserved. +- `test_unrelated_failure_propagates_instead_of_becoming_none` — monkeypatches + `from_currsys` to raise `RuntimeError` for one key and asserts it propagates + rather than being flattened to `None`. + +## Review notes + +- `is_night` returns `bool | Time` depending on `return_midnight`, and + `resolve_time` disambiguates with `isinstance(nighttime, Time)`. Latent type + confusion if that default ever flips. Not touched here. +- When `!OBS.brightness` is a word rather than an MJD, `resolve_time` falls back + to `Time.now()` and the brightness is not used to pick a moon phase. That is + the feature the deleted helpers were written for; it remains unimplemented. + +## Verification + +`scopesim/tests`: 4 failed, 1378 passed. Same four pre-existing failures as on +`main`; the two added tests pass. From 8b31a727a539f7c53c9bafc060856face75a856b Mon Sep 17 00:00:00 2001 From: Yashvi-Sharma Date: Mon, 9 Nov 2026 16:56:25 -0800 Subject: [PATCH 3/3] Move the PR description into rework_summaries/ Co-Authored-By: Claude Opus 5 --- .../tb-01-utils-observation-helpers_changes.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tb-01-utils-observation-helpers_changes.md => rework_summaries/tb-01-utils-observation-helpers_changes.md (100%) diff --git a/tb-01-utils-observation-helpers_changes.md b/rework_summaries/tb-01-utils-observation-helpers_changes.md similarity index 100% rename from tb-01-utils-observation-helpers_changes.md rename to rework_summaries/tb-01-utils-observation-helpers_changes.md