diff --git a/autonerves/fitsable.py b/autonerves/fitsable.py index 505ecf6..3424421 100644 --- a/autonerves/fitsable.py +++ b/autonerves/fitsable.py @@ -25,6 +25,28 @@ SMALL_DATASETS_HEADER_KEY = "SMALLDAT" SMALL_DATASETS_HEADER_COMMENT = "PYAUTO_SMALL_DATASETS active at write time" +# The cap in force in the writing process, as ``"x"``. Absent on +# every file written before this card existed -- and on every file written at +# full resolution, where there is no cap to record -- both of which readers must +# treat as "unknown" and fall back on their existing behaviour for. +# +# It exists because ``SMALLDAT`` records the wrong proposition for the question +# a reader actually asks. ``SMALLDAT = T`` means "the env var was set at write +# time", not "capped at today's cap", so +# ``autoarray.util.dataset_util._is_capped_at_the_current_cap`` has to +# corroborate the card against the measured shape of ``data.fits`` -- which +# interferometer data ``(n_visibilities, 2)`` and multi_dataset's prefixed +# ``{waveband}_data.fits`` structurally cannot do, so those families are +# re-simulated on every run. Recording the cap itself makes the card answer the +# question directly and needs no corroboration. +# +# Same 8-character ceiling as the key above, and for the same load-bearing +# reason: a 9-character keyword is silently promoted to HIERARCH and missed by +# ``header.get()``, which reads as absent -- safe, but silently un-fixes the +# case this card exists for. +SMALL_DATASETS_SHAPE_HEADER_KEY = "SMALLSHP" +SMALL_DATASETS_SHAPE_HEADER_COMMENT = "small-datasets cap at write time (rowsxcols)" + def stamp_small_datasets_regime(header): """ @@ -72,16 +94,33 @@ def stamp_small_datasets_regime(header): ``autoarray.util.dataset_util.should_simulate``, whose predicate ends in ``shutil.rmtree``. + Beside the regime card, a capped write also records the cap it used, as + ``SMALLSHP = '16x16'`` (:data:`SMALL_DATASETS_SHAPE_HEADER_KEY`). ``SMALLDAT + = T`` alone says only that the env var was set, which is not the + proposition a reader deciding whether to reuse a dataset needs; the cap + shape is. It is written only in the capped regime -- a full-resolution write + has no cap to record -- so its absence means "unknown cap", never "no cap", + and readers fall back to whatever they did before it existed. + Assignment (not ``append``) is deliberate -- it is idempotent, so the two call sites below can both stamp the same header without duplicating the card. """ - from autonerves.test_mode import small_datasets + from autonerves.test_mode import SMALL_DATASETS_SHAPE_NATIVE, small_datasets + + is_capped = small_datasets() header[SMALL_DATASETS_HEADER_KEY] = ( - small_datasets(), + is_capped, SMALL_DATASETS_HEADER_COMMENT, ) + + if is_capped: + header[SMALL_DATASETS_SHAPE_HEADER_KEY] = ( + "%dx%d" % SMALL_DATASETS_SHAPE_NATIVE, + SMALL_DATASETS_SHAPE_HEADER_COMMENT, + ) + return header diff --git a/autonerves/test_mode.py b/autonerves/test_mode.py index e0474b6..7baa968 100644 --- a/autonerves/test_mode.py +++ b/autonerves/test_mode.py @@ -234,3 +234,38 @@ def small_datasets(): mean "full resolution". """ return os.environ.get("PYAUTO_SMALL_DATASETS") == "1" + + +# The small-datasets cap, as ``(rows, columns)``. Canonical home: the regime +# switch it belongs to (:func:`small_datasets`) lives here, and the writer that +# records the cap in force at write time +# (:func:`autonerves.fitsable.stamp_small_datasets_regime`) is in this package +# too, one layer below the library that applies it. +# +# ``autoarray.util.dataset_util`` deliberately keeps its own literal of the same +# value rather than importing this one, for the reason recorded there against +# ``SMALL_DATASETS_HEADER_KEY``: an editable checkout or a ``--no-deps`` install +# can put a pre-stamp autonerves on the path, and a literal degrades safely +# there ("card absent" -> the shape heuristic) where an import would be an +# ``ImportError`` at module load. A test in that repo pins the two to agree +# whenever a stamp-aware autonerves is installed, which is the drift guard the +# duplication needs and the import would not provide. +SMALL_DATASETS_SHAPE_NATIVE = (16, 16) + + +def disable_jax(): + """ + Return True if the JAX backend is disabled for this process. + + ``PYAUTO_DISABLE_JAX=1`` is the documented global switch for forcing the + NumPy path (the workspace ``start_here`` guides name it beside the + per-call ``use_jax=False``), used by the smoke profiles so a fast run does + not pay a JIT compile. It is a *harness-level override*, not a preference: + code that takes a ``use_jax`` argument must let this variable win over an + explicit ``True``, or the harness pays for a backend it asked to disable. + + The env var is compared against the exact string ``"1"``, matching every + other ``PYAUTO_*`` switch in this module. ``"0"``, ``"true"`` and the unset + case all mean "JAX is available". + """ + return os.environ.get("PYAUTO_DISABLE_JAX") == "1" diff --git a/test_autonerves/test_fitsable.py b/test_autonerves/test_fitsable.py index 58409ff..577e655 100644 --- a/test_autonerves/test_fitsable.py +++ b/test_autonerves/test_fitsable.py @@ -246,3 +246,98 @@ def test__header_dict_cards_carry_no_junk_comment(tmp_path): # The regime stamp keeps its real comment -- this is about junk, not about # removing every comment. assert fitsable.SMALL_DATASETS_HEADER_COMMENT in str(header.cards[KEY]) + + +""" +__small-datasets cap shape card (PyAutoNerves#159)__ + +`SMALLDAT = T` records that the env var was set at write time, which is not the +proposition a reader deciding whether to reuse a dataset asks -- that one is +"capped at today's cap". `autoarray.util.dataset_util` had to corroborate the +card against the measured shape of `data.fits`, which interferometer data +`(n_visibilities, 2)` and multi_dataset's prefixed `{waveband}_data.fits` +structurally cannot do, so those families re-simulated on every run. `SMALLSHP` +records the cap itself, so no corroboration is needed. +""" + +SHAPE_KEY = fitsable.SMALL_DATASETS_SHAPE_HEADER_KEY + + +def _cap_card(file_path, hdu=0): + with fits.open(file_path) as hdu_list: + return hdu_list[hdu].header.get(SHAPE_KEY) + + +def test__capped_write__records_the_cap_in_force(tmp_path, monkeypatch): + from autonerves.test_mode import SMALL_DATASETS_SHAPE_NATIVE + + monkeypatch.setenv("PYAUTO_SMALL_DATASETS", "1") + fitsable.output_to_fits(np.ones((4, 4)), file_path=tmp_path / "small.fits") + + assert _cap_card(tmp_path / "small.fits") == "%dx%d" % SMALL_DATASETS_SHAPE_NATIVE + + +def test__full_resolution_write__omits_the_card(tmp_path, monkeypatch): + # A full-resolution write has no cap to record, so the card is absent -- + # which readers must treat as "unknown cap", exactly as they treat every + # file written before the card existed. Writing something like "none" here + # would give a reader a value to compare and a way to get it wrong. + monkeypatch.setenv("PYAUTO_SMALL_DATASETS", "0") + fitsable.output_to_fits(np.ones((4, 4)), file_path=tmp_path / "full.fits") + + assert _cap_card(tmp_path / "full.fits") is None + + monkeypatch.delenv("PYAUTO_SMALL_DATASETS", raising=False) + fitsable.output_to_fits(np.ones((4, 4)), file_path=tmp_path / "unset.fits") + + assert _cap_card(tmp_path / "unset.fits") is None + + +def test__cap_card_round_trips_as_a_string_readable_by_the_short_key( + tmp_path, monkeypatch +): + # The 8-character ceiling is load-bearing: a 9-character keyword is + # silently promoted to a HIERARCH card, which `header.get(SHORT_KEY)` then + # misses and every reader treats as absent -- a silent un-fix, not a + # failure. Pin both the key length and the on-disk type. + monkeypatch.setenv("PYAUTO_SMALL_DATASETS", "1") + fitsable.output_to_fits(np.ones((4, 4)), file_path=tmp_path / "t.fits") + + assert len(SHAPE_KEY) <= 8 + + with fits.open(tmp_path / "t.fits") as hdu_list: + value = hdu_list[0].header[SHAPE_KEY] + + assert isinstance(value, str) + + +def test__multi_hdu_funnel__records_the_cap_on_every_hdu(tmp_path, monkeypatch): + # The path PyAutoArray's fits_imaging/fits_interferometer take -- the one + # the interferometer datasets that motivated this card are written by. + monkeypatch.setenv("PYAUTO_SMALL_DATASETS", "1") + + hdu_list = fitsable.hdu_list_for_output_from( + values_list=[np.ones((4, 4)), np.zeros((4, 4))], + ext_name_list=["data", "noise_map"], + ) + fitsable.write_hdu_list(hdu_list, file_path=tmp_path / "dataset.fits") + + from autonerves.test_mode import SMALL_DATASETS_SHAPE_NATIVE + + expected = "%dx%d" % SMALL_DATASETS_SHAPE_NATIVE + + assert _cap_card(tmp_path / "dataset.fits", hdu=0) == expected + assert _cap_card(tmp_path / "dataset.fits", hdu=1) == expected + + +def test__stamping_twice_is_idempotent(tmp_path, monkeypatch): + # Both call sites in this module stamp the same header; assignment (not + # append) must keep that from duplicating either card. + monkeypatch.setenv("PYAUTO_SMALL_DATASETS", "1") + + header = fits.Header() + fitsable.stamp_small_datasets_regime(header) + fitsable.stamp_small_datasets_regime(header) + + assert [card.keyword for card in header.cards].count(SHAPE_KEY) == 1 + assert [card.keyword for card in header.cards].count(KEY) == 1 diff --git a/test_autonerves/test_test_mode.py b/test_autonerves/test_test_mode.py index 3870502..e5aa0fa 100644 --- a/test_autonerves/test_test_mode.py +++ b/test_autonerves/test_test_mode.py @@ -9,6 +9,8 @@ import pytest from autonerves.test_mode import ( + SMALL_DATASETS_SHAPE_NATIVE, + disable_jax, is_test_mode, with_test_mode_segment, ) @@ -82,3 +84,40 @@ def test__values_below_four_raise(self): os.environ["PYAUTO_TEST_MODE_SAMPLES"] = "3" with pytest.raises(ValueError): _test_mode_samples() + + +class TestDisableJax: + """``PYAUTO_DISABLE_JAX`` is the documented global switch for forcing the + NumPy path. It had no predicate before this class existed, which is why it + was honoured in exactly one place in the stack while two workspace guides + documented it as global.""" + + def test__env_unset_is_false(self, monkeypatch): + monkeypatch.delenv("PYAUTO_DISABLE_JAX", raising=False) + + assert disable_jax() is False + + def test__env_one_is_true(self, monkeypatch): + monkeypatch.setenv("PYAUTO_DISABLE_JAX", "1") + + assert disable_jax() is True + + @pytest.mark.parametrize("value", ["0", "true", "True", "yes", ""]) + def test__only_the_exact_string_one_enables_it(self, monkeypatch, value): + # Matching every other PYAUTO_* switch in the module: a truthy-looking + # string is not "1", and reading it as one would silently disable JAX + # for anyone who wrote PYAUTO_DISABLE_JAX=0 to mean "no". + monkeypatch.setenv("PYAUTO_DISABLE_JAX", value) + + assert disable_jax() is False + + +def test__small_datasets_cap_shape_is_the_two_axis_tuple_readers_compare(): + # The cap is stamped into FITS headers as "x" and compared back + # against this constant by ``autoarray.util.dataset_util``. Pin its shape + # and type: a scalar or a 3-tuple here would produce a card no reader can + # parse, which reads as "absent" and silently un-fixes the re-simulation + # case the card exists for. + assert isinstance(SMALL_DATASETS_SHAPE_NATIVE, tuple) + assert len(SMALL_DATASETS_SHAPE_NATIVE) == 2 + assert all(isinstance(axis, int) for axis in SMALL_DATASETS_SHAPE_NATIVE)