Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions rework_summaries/tb-01-utils-observation-helpers_changes.md
Original file line number Diff line number Diff line change
@@ -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.
35 changes: 35 additions & 0 deletions scopesim/tests/test_utils_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}))
48 changes: 3 additions & 45 deletions scopesim/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Loading