From cb09bd53740e8b2e9e73857d21f033bec733c4ae Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:30:06 +0000 Subject: [PATCH 01/13] Tabulate the statistics-spec, collect and wave-certificate refusals Ten standalone refusals of StatsSpec and collect in tests/test_stats.py become two parametrised tables, and the cut-off crossing refusal in tests/test_adiabatic.py becomes a row of the wave certificate's existing table. Every call, exception class and match string is kept as a row; the docstrings and comments stay as row comments. Counts (before -> after): tests/test_stats.py lines 875->855, tests 84->84, assert 54->54, assert_* 28->28, raises 17->9, match= 19->11 tests/test_adiabatic.py lines 501->488, tests 34->34, assert 31->31, assert_* 4->4, raises 12->11, match= 12->11 Every raises/match= drop is a site moved into a table row; all base match= strings are present. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/test_adiabatic.py | 19 ++------- tests/test_stats.py | 90 ++++++++++++++++------------------------- 2 files changed, 38 insertions(+), 71 deletions(-) diff --git a/tests/test_adiabatic.py b/tests/test_adiabatic.py index bc6f2ea85..f4e630d8e 100644 --- a/tests/test_adiabatic.py +++ b/tests/test_adiabatic.py @@ -338,6 +338,9 @@ def test_the_budgets_must_be_finite_and_positive(value): ([math.nan], [0.0], (0.0, 1e-3), "finite positive frequencies"), ([OMEGA], [-1.0], (0.0, 1e-3), "finite and >= 0"), ([OMEGA], [math.inf], (0.0, 1e-3), "finite and >= 0"), + # q^2 = k0^2 (1 + rho) - k_perp^2 changes sign when k_perp^2 sits between the + # two ends' k^2. + ([OMEGA], [0.0, K0**2 * (1 + 0.5e-3)], (0.0, 1e-3), "crosses q = 0"), ], ) def test_the_wave_certificate_refuses_an_invalid_input(omega, kperp_sq, z_span, match): @@ -358,22 +361,6 @@ def test_the_bounds_are_stable_for_tiny_variation(): assert field_error_bound(1e-12) == pytest.approx(1e-24, rel=4 * EPS) -def test_a_column_crossing_cutoff_refuses(): - # q^2 = k0^2 (1 + rho) - k_perp^2 changes sign when k_perp^2 sits between the - # two ends' k^2. - path = Linear(0.0, 1e-3, 1e-3) - between = K0**2 * (1 + 0.5e-3) - with pytest.raises(MaterialError, match="crosses q = 0"): - certify_wave_path( - np.array([OMEGA]), - np.ones(1, dtype=complex), - np.ones((1, 1), dtype=complex), - [path], - np.array([0.0, between]), - (0.0, 1e-3), - ) - - def test_a_column_nonpropagating_everywhere_is_outside_the_certificate(): path = Linear(0.0, 1e-3, 1e-3) admission = certify_wave_path( diff --git a/tests/test_stats.py b/tests/test_stats.py index 7fa20820e..f2cf2c830 100644 --- a/tests/test_stats.py +++ b/tests/test_stats.py @@ -393,9 +393,25 @@ def test_a_spec_freezes_its_windows(): spec.energy_windows[0, 0] = 3.0 -def test_a_spec_refuses_an_unknown_statistic(): - with pytest.raises(OutputError, match="unknown statistics"): - StatsSpec(names=("energy", "banana")) +@pytest.mark.parametrize( + ("keywords", "message"), + [ + ({"names": ("energy", "banana")}, "unknown statistics"), + ({"names": ("energy", "energy")}, "these repeat"), + ({"names": ("energy",), "periodic": ("peak_power",)}, "periodic subset"), + ({"names": ("energy",), "period": 0}, "at least 1"), + ({"energy_windows": np.array([[np.nan, 1.0]])}, "NaN edge"), + ({"energy_windows": np.array([[2.0, 1.0]])}, r"lo < hi"), + # Fluence widths are implemented at saved planes, with an explicit trait. + ( + {"names": ("fwhm_r",), "periodic": ("fwhm_r",)}, + "cannot be evaluated between save planes", + ), + ], +) +def test_a_spec_refuses_a_bad_selection(keywords, message): + with pytest.raises(OutputError, match=message): + StatsSpec(**keywords) def test_a_spec_accepts_the_implemented_radial_width(): @@ -431,31 +447,6 @@ def test_the_field_statistics_are_not_backend_owned(): ) -def test_a_spec_refuses_a_repeated_statistic(): - with pytest.raises(OutputError, match="these repeat"): - StatsSpec(names=("energy", "energy")) - - -def test_a_spec_refuses_a_periodic_statistic_it_does_not_record(): - with pytest.raises(OutputError, match="periodic subset"): - StatsSpec(names=("energy",), periodic=("peak_power",)) - - -def test_a_spec_refuses_a_period_below_one(): - with pytest.raises(OutputError, match="at least 1"): - StatsSpec(names=("energy",), period=0) - - -def test_a_spec_refuses_a_window_with_a_nan_edge(): - with pytest.raises(OutputError, match="NaN edge"): - StatsSpec(energy_windows=np.array([[np.nan, 1.0]])) - - -def test_a_spec_refuses_a_window_that_is_not_ordered(): - with pytest.raises(OutputError, match=r"lo < hi"): - StatsSpec(energy_windows=np.array([[2.0, 1.0]])) - - def test_a_spec_accepts_a_periodic_subset(): spec = StatsSpec(names=("energy", "peak_power"), periodic=("energy",), period=10) assert spec.periodic == ("energy",) @@ -470,12 +461,6 @@ def test_a_spec_refuses_a_periodic_statistic_no_backend_evaluates_between_planes StatsSpec(names=("energy", name), periodic=(name,)) -def test_a_spec_refuses_spatial_widths_between_planes(): - """Fluence widths are implemented at saved planes, with an explicit trait.""" - with pytest.raises(OutputError, match="cannot be evaluated between save planes"): - StatsSpec(names=("fwhm_r",), periodic=("fwhm_r",)) - - def test_every_periodic_default_is_one_the_catalogue_allows(): """Every name a run may put in `periodic` is one `_check_between_planes` admits.""" allowed = {name for name, entry in CATALOGUE.items() if entry.between_planes} @@ -583,17 +568,23 @@ def test_collect_agrees_with_the_statistics_it_calls(envelope_grid): assert np.array_equal(values["peak_power"], peak_power(envelope_grid, field)) -def test_collect_refuses_a_windowed_statistic_without_windows(envelope_grid): - field = gaussian(envelope_grid, energy_j=ENERGY) - spec = StatsSpec(names=("energy_window",)) - with pytest.raises(OutputError, match="at least one energy window"): - collect(spec, envelope_grid, plane_of(field)) - - -def test_collect_refuses_zdw_without_modes(envelope_grid): +@pytest.mark.parametrize( + ("spec", "profiles", "message"), + [ + (StatsSpec(names=("energy_window",)), None, "at least one energy window"), + (StatsSpec(names=("zdw",)), None, "needs the propagated modes"), + ( + StatsSpec(names=("pressure",)), + {"density": Constant(1.0)}, + r"collect was given \['density'\]", + ), + ], +) +def test_collect_refuses_what_it_cannot_form(envelope_grid, spec, profiles, message): field = gaussian(envelope_grid, energy_j=ENERGY) - with pytest.raises(OutputError, match="needs the propagated modes"): - collect(StatsSpec(names=("zdw",)), envelope_grid, plane_of(field)) + given = {} if profiles is None else {"profiles": profiles} + with pytest.raises(OutputError, match=message): + collect(spec, envelope_grid, plane_of(field), **given) @pytest.mark.parametrize("name", PROFILE_STATISTICS) @@ -603,17 +594,6 @@ def test_collect_refuses_a_profile_statistic_without_its_profile(envelope_grid, collect(StatsSpec(names=(name,)), envelope_grid, plane_of(field)) -def test_collect_names_the_profiles_it_was_given(envelope_grid): - field = gaussian(envelope_grid, energy_j=ENERGY) - with pytest.raises(OutputError, match=r"collect was given \['density'\]"): - collect( - StatsSpec(names=("pressure",)), - envelope_grid, - plane_of(field), - profiles={"density": Constant(1.0)}, - ) - - def test_the_manual_page_states_the_trait_the_catalogue_holds(): """Keep the manual's between-plane traits consistent with the catalogue. From 8db81973c0929e98bb8bb57e2cbd8ae0046795c5 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:31:00 +0000 Subject: [PATCH 02/13] Driver tests: refusal guards as parametrised tables Nine capillary build/run refusals become BUILD_REFUSALS, placed in the refusals section. Seven prop_gnlse cheap() refusals become one table. The two SimulationSettings save-plane refusals become one table. Five mixture construct() refusals, three of them already parametrised, become CONSTRUCT_REFUSALS. Four compatible_groups refusals become GROUP_REFUSALS. Each row keeps its call, exception class and exact match string, and the comments that explained a guard move to its row. Per module (before -> after); tests, assert and assert_* are unchanged: test_prop_capillary 161 tests, raises 21->13, match= 29->21, lines 4520->4509 test_prop_gnlse 54 tests, raises 13->8, match= 13->8, lines 890->872 test_run 23 tests, raises 7->6, match= 7->6, lines 748->744 test_mixture_interface 35 tests, raises 10->6, match= 10->6, lines 445->441 test_batch 22 tests, raises 7->4, match= 7->4, lines 249->247 Every match= string removed is a literal in a table row. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/driver/test_batch.py | 38 ++++++----- tests/driver/test_mixture_interface.py | 56 ++++++++-------- tests/driver/test_prop_capillary.py | 89 +++++++++++--------------- tests/driver/test_prop_gnlse.py | 48 +++++--------- tests/driver/test_run.py | 22 +++---- 5 files changed, 107 insertions(+), 146 deletions(-) diff --git a/tests/driver/test_batch.py b/tests/driver/test_batch.py index 758f49a53..abac79cf7 100644 --- a/tests/driver/test_batch.py +++ b/tests/driver/test_batch.py @@ -76,9 +76,24 @@ def points(): assert [point.index for point in next(groups)] == [4] -def test_batch_groups_reject_negative_global_index(): - with pytest.raises(DriverError, match="nonnegative global indices"): - list(compatible_groups([member(-1)], 2)) +# Each row is a set of members (built when the test runs) and a group size that +# `compatible_groups` refuses, with the exact match. +GROUP_REFUSALS = [ + (lambda: [member(-1)], 2, "nonnegative global indices"), + ( + lambda: [member(0, backend="numpy_ref"), member(1, backend="native")], + 2, + "mixed backends", + ), + (lambda: [member(0, fixed=False)], 2, "explicit fixed schedule"), + *((lambda: [], size, "positive integer") for size in (0, -1, True)), +] + + +@pytest.mark.parametrize(("members", "size", "message"), GROUP_REFUSALS) +def test_batch_groups_refuse_an_unbatchable_request(members, size, message): + with pytest.raises(DriverError, match=message): + list(compatible_groups(members(), size)) def test_batch_different_schedule_starts_a_separate_group(): @@ -137,17 +152,6 @@ def test_batch_prepares_each_backend_without_changing_selection(backend): assert all(point.simulation.settings.backend == backend for point in points) -def test_batch_refuses_mixed_backend_scan(): - points = [member(0, backend="numpy_ref"), member(1, backend="native")] - with pytest.raises(DriverError, match="mixed backends"): - list(compatible_groups(points, 2)) - - -def test_batch_refuses_implicit_adaptive_execution(): - with pytest.raises(DriverError, match="explicit fixed schedule"): - list(compatible_groups([member(0, fixed=False)], 2)) - - def test_batch_refuses_spatial_geometry_before_selecting_a_backend(): base = member(0, backend="numpy_ref").simulation simulation = Simulation.from_free( @@ -186,12 +190,6 @@ def test_a_native_batch_groups_z_table_members(): ] == [[0]] -@pytest.mark.parametrize("size", [0, -1, True]) -def test_batch_refuses_invalid_size(size): - with pytest.raises(DriverError, match="positive integer"): - list(compatible_groups([], size)) - - @requires_typecheck @pytest.mark.parametrize("size", [1.5]) def test_batch_size_rejects_fractional_type(size): diff --git a/tests/driver/test_mixture_interface.py b/tests/driver/test_mixture_interface.py index baef37cb7..065077130 100644 --- a/tests/driver/test_mixture_interface.py +++ b/tests/driver/test_mixture_interface.py @@ -75,11 +75,33 @@ def construct(mixture, grid, **options): ) -@pytest.mark.parametrize("pressure", [1.0, (1.0, 0.0), Constant(1.0)]) -def test_mixture_refuses_every_explicit_pressure(material_grid, pressure): +# Each row is a keyword `construct` refuses for a mixture: the keywords, the exception +# class (or classes) and the exact match. +CONSTRUCT_REFUSALS = [ + *( + ({"pressure": pressure}, DriverError, r"Mixture.*pressure") + for pressure in (1.0, (1.0, 0.0), Constant(1.0)) + ), + ({"pressure_floor": 0.0}, DriverError, "pressure_floor"), + *( + ({option: {"misspelled": False}}, (DriverError, MaterialError), "misspelled") + for option in ("plasma", "raman", "preionisation") + ), + *( + ({"preionisation": fraction}, MaterialError, "preionisation") + for fraction in (-0.1, 1.1, np.nan) + ), + ({"modes": 0}, DriverError, "at least one mode"), +] + + +@pytest.mark.parametrize(("options", "error", "message"), CONSTRUCT_REFUSALS) +def test_a_mixture_construction_refuses_a_bad_keyword( + material_grid, options, error, message +): mixture, grid = material_grid - with pytest.raises(DriverError, match=r"Mixture.*pressure"): - construct(mixture, grid, pressure=pressure) + with pytest.raises(error, match=message): + construct(mixture, grid, **options) @pytest.mark.parametrize("fractions", [False, True]) @@ -181,12 +203,6 @@ def test_analytic_plasma_with_temporal_collar_matches_the_reference(material_gri ) -def test_mixture_refuses_pressure_floor(material_grid): - mixture, grid = material_grid - with pytest.raises(DriverError, match="pressure_floor"): - construct(mixture, grid, pressure_floor=0.0) - - def test_pressure_floor_beside_a_constant_pressure_is_refused(): # The constructors route pressure_floor through the fill's pressure path, which # refuses a floor that a constant pressure has no end to apply to. @@ -205,13 +221,6 @@ def test_pressure_floor_beside_a_constant_pressure_is_refused(): ) -@pytest.mark.parametrize("option", ["plasma", "raman", "preionisation"]) -def test_unknown_component_selection_fails_by_name(material_grid, option): - mixture, grid = material_grid - with pytest.raises((DriverError, MaterialError), match="misspelled"): - construct(mixture, grid, **{option: {"misspelled": False}}) - - def test_preionisation_preserves_omitted_components(material_grid): _, grid = material_grid mixture, _, _, _, _ = mixture_case() @@ -247,13 +256,6 @@ def test_a_preionisation_no_plasma_channel_carries_is_refused_by_label(material_ assert construct(zeroed, grid).modes -@pytest.mark.parametrize("fraction", [-0.1, 1.1, np.nan]) -def test_invalid_initial_fraction_is_refused(material_grid, fraction): - mixture, grid = material_grid - with pytest.raises(MaterialError, match="preionisation"): - construct(mixture, grid, preionisation=fraction) - - def test_per_label_rates_and_inactive_species_retain_order(material_grid): mixture, grid = material_grid simulation = construct(mixture, grid, plasma={mixture.labels[1]: AnalyticRate()}) @@ -402,12 +404,6 @@ def test_changed_temperature_rebuilds_rotational_populations(material_grid, capl assert "undamped Raman model" in caplog.text -def test_zero_supplied_mode_count_is_refused(material_grid): - material, grid = material_grid - with pytest.raises(DriverError, match="at least one mode"): - construct(material, grid, modes=0) - - def test_multimode_update_keeps_the_shared_material_and_transform(material_grid): material, grid = material_grid source = construct(material, grid, modes=2, n_r=16) diff --git a/tests/driver/test_prop_capillary.py b/tests/driver/test_prop_capillary.py index c1490e620..8b7395b27 100644 --- a/tests/driver/test_prop_capillary.py +++ b/tests/driver/test_prop_capillary.py @@ -287,18 +287,6 @@ def test_a_linear_fill_to_exact_vacuum_runs_and_ends_in_vacuum(): assert density[-1] == 0.0 -def test_an_unreadable_pressure_is_refused_by_name(): - with pytest.raises(DriverError, match="p_in, p_out"): - build(pressure=(1.0, 2.0, 3.0)) - - -def test_a_malformed_staged_fill_is_refused_by_the_profile_that_knows_the_rule(): - # One pressure for two positions: the profile names the rule, so the driver does - # not restate it in a message of its own. - with pytest.raises(TranslationError, match="one pressure per position"): - build(pressure=([0.0, SHORT], [1.0])) - - # ------------------------------------------------------------------- the mode set @@ -364,11 +352,6 @@ def test_the_rule_is_kronrod_so_the_alarm_has_an_estimate(): assert rule.n_nodes == 33 -def test_azimuthal_nodes_are_refused_for_a_radial_set(): - with pytest.raises(DriverError, match="azimuthal order zero"): - build(modes=2, n_theta=16) - - def test_azimuthal_nodes_are_taken_when_a_mode_has_angular_structure(): # HE_21 has azimuthal order one, so its quartic reaches degree four and the rule # has to resolve the angle; the exactness bound is 4 * 1 + 1. No plasma, because @@ -490,11 +473,6 @@ def test_thg_defaults_to_on_for_a_field_grid(): assert not kerr_of(build(thg=False)).thg -def test_a_run_with_no_nonlinearity_is_refused(): - with pytest.raises(DriverError, match="no nonlinearity"): - build(kerr=False, plasma=False) - - # ------------------------------------------------------------- the CtC keywords # # The keywords milestone M4's target asks for, in solprop's names. Luna's call is @@ -622,6 +600,45 @@ def test_the_ctc_temperature_reaches_the_rotational_populations(): # ------------------------------------------------------------------------- refusals +# Each row builds (or runs) the cheap capillary with the given keywords and names the +# refusal: the entry, the keywords, the exception class and the exact match. +BUILD_REFUSALS = [ + (build, {"pressure": (1.0, 2.0, 3.0)}, DriverError, "p_in, p_out"), + # One pressure for two positions: the profile names the rule, so the driver does + # not restate it in a message of its own. + ( + build, + {"pressure": ([0.0, SHORT], [1.0])}, + TranslationError, + "one pressure per position", + ), + (build, {"modes": 2, "n_theta": 16}, DriverError, "azimuthal order zero"), + (build, {"kerr": False, "plasma": False}, DriverError, "no nonlinearity"), + # optmat names the atom (SEP 3, Phase 1c). + (build, {"raman": True}, MaterialError, "no molecular Raman response"), + ( + build, + {"gas": "H2", "raman": True, "kerr": False}, + DriverError, + "needs kerr=True", + ), + (build, {"polarisation": "circular"}, DriverError, "this path is scalar"), + ( + build, + {"envelope": True, "plasma": True, "thg": True}, + DriverError, + "envelope plasma cannot be combined with THG", + ), + (run, {"save_planes": [SHORT], "n_save": 3}, DriverError, "not both"), +] + + +@pytest.mark.parametrize(("entry", "overrides", "error", "message"), BUILD_REFUSALS) +def test_the_capillary_refuses_a_bad_request(entry, overrides, error, message): + with pytest.raises(error, match=message): + entry(**overrides) + + @pytest.mark.parametrize("gas", ["H2", "O2"]) def test_raman_true_adds_the_molecular_response_of_the_fill(gas): # plasma=False so that this is about the Raman response alone; the plasma beside it @@ -633,12 +650,6 @@ def test_raman_true_adds_the_molecular_response_of_the_fill(gas): assert simulation.translate().flags.has_raman -def test_raman_true_is_refused_for_a_gas_without_raman_data(): - # optmat names the atom (SEP 3, Phase 1c). - with pytest.raises(MaterialError, match="no molecular Raman response"): - build(raman=True) - - @pytest.mark.parametrize("gas", ["N2", "O2", "H2", "D2", "CH4", "SF6"]) def test_raman_is_on_by_default_for_a_molecule_with_data(gas): # raman=None means on where optmat's response is validated; False switches it off. @@ -730,29 +741,12 @@ def test_oxygen_raman_propagates_through_both_cpu_backends(): ) -def test_raman_true_needs_the_kerr_term_it_drives_beside(): - with pytest.raises(DriverError, match="needs kerr=True"): - build(gas="H2", raman=True, kerr=False) - - -def test_a_vector_request_is_refused_as_scalar_only(): - with pytest.raises(DriverError, match="this path is scalar"): - build(polarisation="circular") - - def test_an_envelope_grid_with_explicit_plasma_selects_cycle_averaging(): simulation = build(envelope=True, plasma=True) assert any(isinstance(one, EnvelopePlasmaResponse) for one in simulation.responses) assert not kerr_of(simulation).thg -def test_envelope_plasma_with_thg_is_refused_by_name(): - with pytest.raises( - DriverError, match="envelope plasma cannot be combined with THG" - ): - build(envelope=True, plasma=True, thg=True) - - def test_an_envelope_grid_turns_plasma_and_thg_off_by_itself(): # Luna's defaults: `plasma` and `thg` are both `!envelope`, so an envelope run # asks for neither unless it is told to. @@ -904,11 +898,6 @@ def test_n_save_counts_the_entrance(): assert run(n_save=4)["z"].size == 4 -def test_save_planes_and_n_save_are_exclusive(): - with pytest.raises(DriverError, match="not both"): - run(save_planes=[SHORT], n_save=3) - - def test_explicit_planes_are_used_as_given(): planes = [SHORT / 2, SHORT] np.testing.assert_allclose(run(save_planes=planes, n_save=None)["z"][1:], planes) diff --git a/tests/driver/test_prop_gnlse.py b/tests/driver/test_prop_gnlse.py index bce267e14..740401da9 100644 --- a/tests/driver/test_prop_gnlse.py +++ b/tests/driver/test_prop_gnlse.py @@ -514,14 +514,21 @@ def test_a_field_grid_is_refused_by_name(soliton): cheap(grid=grid, wavelength_limits=None, trange=None) -def test_a_gaussian_asked_for_by_its_natural_width_is_refused(): - with pytest.raises(DriverError, match="intensity fwhm"): - cheap(shape="gauss", width=100e-15) - - -def test_an_unknown_pulse_shape_is_refused(): - with pytest.raises(DriverError, match="'gauss' or 'sech'"): - cheap(shape="lorentz", width=None, fwhm=100e-15) +@pytest.mark.parametrize( + ("keywords", "message"), + [ + ({"shape": "gauss", "width": 100e-15}, "intensity fwhm"), + ({"shape": "lorentz", "width": None, "fwhm": 100e-15}, "'gauss' or 'sech'"), + ({"betas": None}, "exactly one of betas"), + ({"beta": (np.zeros(4), np.zeros(4))}, "exactly one of betas"), + ({"wavelength_limits": None}, "wavelength_limits and trange"), + ({"n_save": 4, "save_planes": [SHORT]}, "not both"), + ({"n_save": 1}, "at least 2"), + ], +) +def test_the_gnlse_refuses_a_bad_request(keywords, message): + with pytest.raises(DriverError, match=message): + cheap(**keywords) def test_an_unknown_noise_model_is_refused(narrow_grid): @@ -532,37 +539,12 @@ def test_an_unknown_noise_model_is_refused(narrow_grid): _shot_noise("thermal", narrow_grid, 3) -@pytest.mark.parametrize( - "keywords", - [{"betas": None}, {"beta": (np.zeros(4), np.zeros(4))}], - ids=["neither", "both"], -) -def test_exactly_one_dispersion_must_be_given(keywords): - with pytest.raises(DriverError, match="exactly one of betas"): - cheap(**keywords) - - def test_a_dispersion_that_is_neither_a_table_nor_a_callable_is_refused(narrow_grid): # Through the helper directly, for the reason above. with pytest.raises(DriverError, match="pair of arrays or a callable"): _dispersion_table("beta", narrow_grid) -def test_a_grid_cannot_be_left_unspecified(): - with pytest.raises(DriverError, match="wavelength_limits and trange"): - cheap(wavelength_limits=None) - - -def test_both_ways_of_asking_for_planes_at_once_are_refused(): - with pytest.raises(DriverError, match="not both"): - cheap(n_save=4, save_planes=[SHORT]) - - -def test_a_run_must_store_more_than_the_entrance(): - with pytest.raises(DriverError, match="at least 2"): - cheap(n_save=1) - - # ------------------------------------------------------------- the periodic progress diff --git a/tests/driver/test_run.py b/tests/driver/test_run.py index 1aeb624da..ba0c8b410 100644 --- a/tests/driver/test_run.py +++ b/tests/driver/test_run.py @@ -583,21 +583,17 @@ def test_the_loop_runs_without_a_simulation(narrow_grid, soliton): assert handler["z"].tolist() == [0.0, 0.005, 0.01] -def test_the_settings_refuse_save_planes_that_are_not_increasing(): - with pytest.raises(DriverError, match="positive and increasing"): - SimulationSettings( - controller=PIController(rtol=1e-8, atol=1e-18), - save_planes=[1.0, 0.5], - dz_max=0.1, - dz_init=1e-3, - ) - - -def test_the_settings_refuse_a_plane_at_the_entrance(): - with pytest.raises(DriverError, match="saved anyway"): +@pytest.mark.parametrize( + ("save_planes", "message"), + [([1.0, 0.5], "positive and increasing"), ([0.0, 0.5], "saved anyway")], +) +def test_the_settings_refuse_save_planes_out_of_order_or_at_the_entrance( + save_planes, message +): + with pytest.raises(DriverError, match=message): SimulationSettings( controller=PIController(rtol=1e-8, atol=1e-18), - save_planes=[0.0, 0.5], + save_planes=save_planes, dz_max=0.1, dz_init=1e-3, ) From afa4524ec28f2bfd5973ad98bf389a6ac9e151c6 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:31:01 +0000 Subject: [PATCH 03/13] Backend tests: the Raman pass's two shape refusals as one table The vector-field and mismatched-spectrum refusals of passes.raman_polarisation become one parametrised test. Each row keeps its field, spectrum and exact match, with its docstring reason as a comment. 56 tests, 42 asserts, 4 assert_* calls unchanged; raises 5->4, match= 5->4, lines 947->937. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/backends/test_numpy_ref_raman.py | 38 ++++++++++---------------- 1 file changed, 14 insertions(+), 24 deletions(-) diff --git a/tests/backends/test_numpy_ref_raman.py b/tests/backends/test_numpy_ref_raman.py index b3c91458e..01d9308ba 100644 --- a/tests/backends/test_numpy_ref_raman.py +++ b/tests/backends/test_numpy_ref_raman.py @@ -208,30 +208,20 @@ def test_the_spectrum_needs_one_rate_for_every_row(raman_field_grid): passes.raman_spectrum(kernels.undamped, [0.0], 1.0, raman_field_grid.dt_fine) -def test_a_vector_field_is_refused_by_the_pass(): - """``raman_drive`` takes the first component and says nothing about the rest, so a - two-component chunk would be convolved without half of itself.""" - with pytest.raises(BackendError, match="tensor"): - passes.raman_polarisation( - np.zeros((1, 2, 16)), - np.zeros(17, dtype=complex), - kind="field", - thg=True, - density=1.0, - ) - - -def test_a_mismatched_convolution_is_refused(): - """The doubled grid is built from the field's own length; a spectrum of another - length would convolve against the wrong axis rather than raise.""" - with pytest.raises(BackendError, match="kernel spectrum has shape"): - passes.raman_polarisation( - np.zeros((1, 1, 16)), - np.zeros(5, dtype=complex), - kind="field", - thg=True, - density=1.0, - ) +@pytest.mark.parametrize( + ("field", "spectrum", "message"), + [ + # ``raman_drive`` takes the first component and says nothing about the rest, + # so a two-component chunk would be convolved without half of itself. + (np.zeros((1, 2, 16)), np.zeros(17, dtype=complex), "tensor"), + # The doubled grid is built from the field's own length; a spectrum of another + # length would convolve against the wrong axis rather than raise. + (np.zeros((1, 1, 16)), np.zeros(5, dtype=complex), "kernel spectrum has shape"), + ], +) +def test_the_raman_pass_refuses_a_field_it_cannot_convolve(field, spectrum, message): + with pytest.raises(BackendError, match=message): + passes.raman_polarisation(field, spectrum, kind="field", thg=True, density=1.0) def test_a_declared_raman_stage_without_a_spectrum_is_refused(raman_capillary): From 6a2b1c41408a5a8ff0cc3c65b1d82df3087f90e6 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:31:38 +0000 Subject: [PATCH 04/13] Turn the modes guard tests into parametrised tables The one-call refusals of the quadrature rules, the mode collection, the dispersion helpers, the connection's step and the step-index root recovery become rows of one table each. Every row keeps its call, ModeError and exact match string, and the docstrings and comments that said why become comments on the row. Per module (lines, collected tests, assert, assert_*, raises, match=): - test_base.py 346->344, 30->30, 17->17, 9->9, 6->4, 6->4 - test_collection.py 350->340, 35->35, 41->41, 7->7, 8->2, 8->2 - test_modal_connection.py 769->767, 31->31, 33->33, 11->11, 7->6, 8->7 - test_quadrature.py 915->903, 94->94, 69->69, 28->28, 17->12, 19->14 - test_stepindex.py 1180->1177, 93->93, 69->69, 37->37, 25->24, 24->23 Each drop in raises/match= is a site merged into a table row; every base match string is still present. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/modes/test_base.py | 24 +++++----- tests/modes/test_collection.py | 70 ++++++++++++---------------- tests/modes/test_modal_connection.py | 28 ++++++----- tests/modes/test_quadrature.py | 50 ++++++++------------ tests/modes/test_stepindex.py | 53 ++++++++++----------- 5 files changed, 98 insertions(+), 127 deletions(-) diff --git a/tests/modes/test_base.py b/tests/modes/test_base.py index 4c25a2d44..e04a0d6ef 100644 --- a/tests/modes/test_base.py +++ b/tests/modes/test_base.py @@ -155,11 +155,6 @@ def test_beta3_matches_the_third_derivative_of_a_mode_with_a_known_expansion(): assert np.max(np.abs(beta3(evacuated, omega) / expected - 1.0)) < 5e-6 -def test_beta3_refuses_a_non_positive_frequency(mode): - with pytest.raises(ModeError, match="beta3 differences beta1"): - beta3(mode, np.array([0.0])) - - def test_beta2_is_negative_above_the_zero_dispersion_wavelength(mode): """Anomalous dispersion above the ZDW: the regime every RDW experiment uses. @@ -171,11 +166,6 @@ def test_beta2_is_negative_above_the_zero_dispersion_wavelength(mode): assert beta2(mode, omega_of(np.array([440e-9])))[0] > 0.0 -def test_beta2_refuses_a_non_positive_frequency(mode): - with pytest.raises(ModeError, match="must be positive"): - beta2(mode, np.array([0.0])) - - def test_the_beta2_step_is_documented_and_small(): assert 1e-6 < BETA2_RELATIVE_STEP < 1e-2 @@ -332,9 +322,17 @@ def test_transmission_composes_over_adjacent_sections(): np.testing.assert_allclose(whole, halves, rtol=1e-9) -def test_transmission_refuses_a_negative_length(mode): - with pytest.raises(ModeError, match="must not be negative"): - transmission(mode, band(), -1.0) +@pytest.mark.parametrize( + ("call", "message"), + [ + (lambda mode: beta3(mode, np.array([0.0])), "beta3 differences beta1"), + (lambda mode: beta2(mode, np.array([0.0])), "must be positive"), + (lambda mode: transmission(mode, band(), -1.0), "must not be negative"), + ], +) +def test_a_dispersion_or_loss_query_outside_its_domain_is_refused(mode, call, message): + with pytest.raises(ModeError, match=message): + call(mode) # ----------------------------------------------------------------------- aeff diff --git a/tests/modes/test_collection.py b/tests/modes/test_collection.py index 384d94707..4586e9598 100644 --- a/tests/modes/test_collection.py +++ b/tests/modes/test_collection.py @@ -94,16 +94,6 @@ def test_hybrid_and_transverse_families_are_orthogonal(): assert overlap(hybrid, transverse) == pytest.approx(0.0, abs=1e-9) -def test_an_overlap_needs_one_cross_section(): - with pytest.raises(ModeError, match="needs one cross-section"): - overlap(MarcatiliMode(RADIUS, "He", 1.0), MarcatiliMode(2 * RADIUS, "He", 1.0)) - - -def test_an_overlap_needs_a_closed_form_normalisation(): - with pytest.raises(ModeError, match="provides no normalisation"): - overlap(DummyMode(), DummyMode()) - - # --------------------------------------------------------------- orthonormality @@ -124,11 +114,6 @@ def test_orthonormality_is_symmetric(): np.testing.assert_allclose(matrix, matrix.T, rtol=0.0, atol=0.0) -def test_orthonormality_needs_a_mode(): - with pytest.raises(ModeError, match="at least one mode"): - orthonormality([]) - - def test_the_fixed_rule_reproduces_the_adaptive_overlaps(): """The two ways of asking the same question, which is the point of having both. @@ -183,11 +168,6 @@ def test_the_partner_of_a_higher_order_hybrid_turns_by_a_quarter_of_its_period() assert overlap(mode, partner) == pytest.approx(0.0, abs=1e-9) -def test_a_mode_that_cannot_say_is_refused(): - with pytest.raises(ModeError, match="orthogonal polarisation"): - polarisation_pairs([DummyMode()]) - - # ------------------------------------------------------------- the collection @@ -199,21 +179,36 @@ def test_a_collection_is_an_ordered_sequence(): assert list(collection) == modes -def test_a_collection_needs_a_mode(): - with pytest.raises(ModeError, match="at least one mode"): - ModeCollection(()) - - -def test_a_collection_refuses_mismatched_cross_sections(): - # Two *different* channels, so that it is the cross-section that is refused - # and not the repeated channel a collection also refuses. - with pytest.raises(ModeError, match="share a cross-section"): - ModeCollection( - [ - MarcatiliMode(RADIUS, "He", 1.0), - MarcatiliMode(2 * RADIUS, "He", 1.0, m=2), - ] - ) +@pytest.mark.parametrize( + ("call", "message"), + [ + ( + lambda: overlap( + MarcatiliMode(RADIUS, "He", 1.0), MarcatiliMode(2 * RADIUS, "He", 1.0) + ), + "needs one cross-section", + ), + (lambda: overlap(DummyMode(), DummyMode()), "provides no normalisation"), + (lambda: orthonormality([]), "at least one mode"), + (lambda: polarisation_pairs([DummyMode()]), "orthogonal polarisation"), + (lambda: ModeCollection(()), "at least one mode"), + # Two *different* channels, so that it is the cross-section that is refused + # and not the repeated channel a collection also refuses. + ( + lambda: ModeCollection( + [ + MarcatiliMode(RADIUS, "He", 1.0), + MarcatiliMode(2 * RADIUS, "He", 1.0, m=2), + ] + ), + "share a cross-section", + ), + (lambda: ModeCollection.he1m(RADIUS, "He", 0.8, 0), "at least one mode"), + ], +) +def test_a_set_that_is_not_one_guide_is_refused(call, message): + with pytest.raises(ModeError, match=message): + call() def test_a_collection_reports_the_shared_cross_section(): @@ -343,8 +338,3 @@ def test_he1m_matches_the_modes_built_by_hand(): omega = np.array([2.356e15]) for one, other in zip(got, by_hand, strict=True): np.testing.assert_array_equal(one.neff(omega), other.neff(omega)) - - -def test_he1m_refuses_an_empty_set(): - with pytest.raises(ModeError, match="at least one mode"): - ModeCollection.he1m(RADIUS, "He", 0.8, 0) diff --git a/tests/modes/test_modal_connection.py b/tests/modes/test_modal_connection.py index 2e36512f3..b2e368ad6 100644 --- a/tests/modes/test_modal_connection.py +++ b/tests/modes/test_modal_connection.py @@ -562,10 +562,19 @@ def test_the_stencil_never_crosses_a_declared_kink(): assert float(np.real(below.matrix[0, 1])) * float(np.real(above.matrix[0, 1])) < 0.0 -@pytest.mark.parametrize("step", [0.0, -1e-9, float("inf")]) -def test_a_step_outside_its_range_is_refused_by_name(step): - """Zero, negative and infinite steps are named, not silently clamped.""" - with pytest.raises(ModeError, match="positive finite step"): +@pytest.mark.parametrize( + ("step", "message"), + [ + # Zero, negative and infinite steps are named, not silently clamped. + (0.0, "positive finite step"), + (-1e-9, "positive finite step"), + (float("inf"), "positive finite step"), + # A secant across a quarter of the scale is not a derivative. + (2.0 * MAX_STENCIL_SPAN * TAPER_LENGTH, "is a secant"), + ], +) +def test_a_step_outside_its_range_is_refused_by_name(step, message): + with pytest.raises(ModeError, match=message): modal_connection(tapered_step_index(), OMEGA, MIDDLE, step=step) @@ -590,17 +599,6 @@ def test_a_coarse_declared_step_warns_against_its_own_certificate(): assert coarse.antisymmetry > CERTIFICATE_WARNING_RTOL * np.max(abs(coarse.matrix)) -def test_a_stencil_wider_than_its_scale_is_refused_by_name(): - """A secant across a quarter of the scale is not a derivative.""" - with pytest.raises(ModeError, match="is a secant"): - modal_connection( - tapered_step_index(), - OMEGA, - MIDDLE, - step=2.0 * MAX_STENCIL_SPAN * TAPER_LENGTH, - ) - - def test_a_rule_that_declares_no_panel_edges_is_refused_by_name(): """The refinement needs the rule's own edges, resolution and truncation radius.""" provider = tapered_step_index() diff --git a/tests/modes/test_quadrature.py b/tests/modes/test_quadrature.py index f7efdcfe1..ee240946d 100644 --- a/tests/modes/test_quadrature.py +++ b/tests/modes/test_quadrature.py @@ -143,11 +143,6 @@ def test_the_embedded_gauss_rule_is_exact_to_its_own_degree(n): assert float(np.sum(coarse * nodes**degree)) == pytest.approx(exact, abs=1e-13) -def test_the_kronrod_order_must_be_positive(): - with pytest.raises(ModeError, match="needs n >= 1"): - gauss_kronrod(0) - - @pytest.mark.parametrize("key", sorted(REFERENCE["kronrod"])) def test_the_kronrod_rule_matches_quadgks(key): """Laurie's algorithm computed here against QuadGK's implementation of it. @@ -301,24 +296,33 @@ def test_the_cartesian_rule_integrates_a_rectangle(): assert value == pytest.approx((2.0 * 8.0 / 3.0) * (2.0 / 3.0), rel=1e-14) -def test_a_cartesian_rule_cannot_be_azimuthally_symmetric(): - with pytest.raises(ModeError, match="no azimuthally symmetric form"): - quadrature_rule("cartesian", full=False, n_r=8) - - # ------------------------------------------------------------------ validation @pytest.mark.parametrize( - ("kwargs", "message"), + ("call", "message"), [ - ({"kind": "polar", "full": False, "n_r": 1}, "n_r >= 2"), - ({"kind": "polar", "full": True, "n_r": 8, "n_theta": 1}, "n_theta >= 2"), + (lambda: gauss_kronrod(0), "needs n >= 1"), + (lambda: quadrature_rule("polar", full=False, n_r=1), "n_r >= 2"), + (lambda: quadrature_rule("polar", full=True, n_r=8, n_theta=1), "n_theta >= 2"), + ( + lambda: quadrature_rule("cartesian", full=False, n_r=8), + "no azimuthally symmetric form", + ), + ( + lambda: quadrature_rule("cartesian", full=True, n_r=8, breaks=(0.5,)), + "radial breaks", + ), + (lambda: transverse_quadrature([], n_r=8), "at least one mode"), + ( + lambda: mode_matrix([], quadrature_rule("polar", full=False, n_r=8)), + "at least one mode", + ), ], ) -def test_a_bad_rule_is_refused(kwargs, message): +def test_a_bad_rule_is_refused(call, message): with pytest.raises(ModeError, match=message): - quadrature_rule(**kwargs) + call() def test_an_unknown_cross_section_is_refused(): @@ -394,11 +398,6 @@ def test_the_full_rule_can_be_forced_either_way(): assert not transverse_quadrature(modes, n_r=8, n_theta=8, full=False).full -def test_a_rule_needs_a_mode(): - with pytest.raises(ModeError, match="at least one mode"): - transverse_quadrature([], n_r=8) - - # ------------------------------------------------------------ the mode matrices @@ -439,12 +438,6 @@ def test_bad_components_are_refused(components): mode_matrix(modes, rule, components=components) -def test_mode_matrices_need_a_mode(): - rule = quadrature_rule("polar", full=False, n_r=8) - with pytest.raises(ModeError, match="at least one mode"): - mode_matrix([], rule) - - def test_modes_with_different_cross_sections_are_refused(): modes = [ MarcatiliMode(RADIUS, "He", 1.0), @@ -908,8 +901,3 @@ def test_the_fixed_rules_are_what_they_were_before_radial_breaks(): def test_invalid_radial_breaks_are_refused(breaks): with pytest.raises(ModeError, match="radial breaks"): quadrature_rule("polar", full=False, n_r=8, breaks=breaks) - - -def test_cartesian_radial_breaks_are_refused(): - with pytest.raises(ModeError, match="radial breaks"): - quadrature_rule("cartesian", full=True, n_r=8, breaks=(0.5,)) diff --git a/tests/modes/test_stepindex.py b/tests/modes/test_stepindex.py index d6373214c..8757f3a2f 100644 --- a/tests/modes/test_stepindex.py +++ b/tests/modes/test_stepindex.py @@ -767,31 +767,28 @@ def short(nodes, values, v, ratio, n, kind): ) -def test_stepindex_ambiguous_recovery_is_refused(monkeypatch): - # One cutoff interval holds one guided root, so a factor that changes sign - # three times in an empty one is refused, and the message says why, instead - # of guessing which candidate is the root. - real = stepindex._refined_roots - - def short(nodes, values, v, ratio, n, kind): - found = real(nodes, values, v, ratio, n, kind) - found[kind] = found[kind][1:] - return found - - monkeypatch.setattr(stepindex, "_refined_roots", short) - monkeypatch.setattr( - stepindex, - "_branch", - lambda u, v, ratio, n, kind: (u - 0.5) * (u - 1.0) * (u - 1.5), - ) - with pytest.raises(ModeError, match="changes sign 3 times"): - _roots(6.0, (1.45 / 1.47) ** 2, 1, "HE") - - -def test_stepindex_unresolved_root_below_the_scan_top_is_refused(monkeypatch): - # With the scan capped below V, a missing root cannot be the one within - # rounding of V, so it is refused with its own cause rather than reported - # short for the caller to call a near-cutoff mode. +@pytest.mark.parametrize( + ("branch", "scan", "message"), + [ + # One cutoff interval holds one guided root, so a factor that changes sign + # three times in an empty one is refused, and the message says why, instead + # of guessing which candidate is the root. + ( + lambda u, v, ratio, n, kind: (u - 0.5) * (u - 1.0) * (u - 1.5), + (), + "changes sign 3 times", + ), + # With the scan capped below V, a missing root cannot be the one within + # rounding of V, so it is refused with its own cause rather than reported + # short for the caller to call a near-cutoff mode. + ( + lambda u, v, ratio, n, kind: u + 1.0, + (1,), + "a root away from V could not be resolved", + ), + ], +) +def test_stepindex_an_unrecoverable_root_is_refused(monkeypatch, branch, scan, message): real = stepindex._refined_roots def short(nodes, values, v, ratio, n, kind): @@ -800,9 +797,9 @@ def short(nodes, values, v, ratio, n, kind): return found monkeypatch.setattr(stepindex, "_refined_roots", short) - monkeypatch.setattr(stepindex, "_branch", lambda u, v, ratio, n, kind: u + 1.0) - with pytest.raises(ModeError, match="a root away from V could not be resolved"): - _roots(6.0, (1.45 / 1.47) ** 2, 1, "HE", 1) + monkeypatch.setattr(stepindex, "_branch", branch) + with pytest.raises(ModeError, match=message): + _roots(6.0, (1.45 / 1.47) ** 2, 1, "HE", *scan) @pytest.mark.parametrize( From b16014fe16932d74104a0d99594738da2713b30b Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:31:38 +0000 Subject: [PATCH 05/13] Turn the processing and plotting guard tests into tables bandpass's out-of-range bands and widths, _plane_field's two refusals and the style helpers' empty requests become one table each, with every call, exception and exact match string kept. Per module (lines, collected tests, assert, assert_*, raises, match=): - processing/test_axes.py 349->347, 66->66, 41->41, 0->0, 16->15, 15->14 - processing/test_spectra.py 278->276, 51->51, 27->27, 3->3, 11->9, 11->9 - plotting/test_style.py 215->213, 44->44, 31->31, 0->0, 5->3, 5->3 Each drop is a site merged into a table row; every base match string is still present. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/plotting/test_style.py | 24 +++++++++++------------- tests/processing/test_axes.py | 14 ++++++-------- tests/processing/test_spectra.py | 26 ++++++++++++-------------- 3 files changed, 29 insertions(+), 35 deletions(-) diff --git a/tests/plotting/test_style.py b/tests/plotting/test_style.py index 90ccb53b6..e54a99c1b 100644 --- a/tests/plotting/test_style.py +++ b/tests/plotting/test_style.py @@ -30,11 +30,6 @@ def test_cmap_colours_returns_distinct_colours(): assert len({tuple(one) for one in colours}) == 4 -def test_cmap_colours_needs_at_least_one(): - with pytest.raises(ProcessingError, match="at least one colour"): - style.cmap_colours(0) - - @pytest.mark.parametrize(("count", "portrait"), [(1, True), (5, True), (5, False)]) def test_subplot_grid_makes_exactly_the_axes_asked_for(count, portrait): figure, axes = style.subplot_grid(count, portrait=portrait) @@ -53,11 +48,6 @@ def geometry(**kwargs): assert geometry(portrait=False) == (2, 3) -def test_subplot_grid_needs_at_least_one_axis(): - with pytest.raises(ProcessingError, match="at least one axis"): - style.subplot_grid(0) - - @pytest.mark.parametrize( ("peak", "unit"), [(2.5e3, "kW"), (2.5e6, "MW"), (2.5e9, "GW"), (2.5e12, "TW"), (2.5e15, "PW")], @@ -75,9 +65,17 @@ def test_power_unit_clamps_to_the_ends_of_the_scale(peak): assert factor > 0.0 -def test_power_unit_needs_a_value(): - with pytest.raises(ProcessingError, match="empty array"): - style.power_unit(np.array([])) +@pytest.mark.parametrize( + ("call", "message"), + [ + (lambda: style.cmap_colours(0), "at least one colour"), + (lambda: style.subplot_grid(0), "at least one axis"), + (lambda: style.power_unit(np.array([])), "empty array"), + ], +) +def test_a_helper_refuses_an_empty_request(call, message): + with pytest.raises(ProcessingError, match=message): + call() @pytest.mark.parametrize( diff --git a/tests/processing/test_axes.py b/tests/processing/test_axes.py index d786cec34..25dbc06da 100644 --- a/tests/processing/test_axes.py +++ b/tests/processing/test_axes.py @@ -119,14 +119,12 @@ def test_nearest_plane_needs_a_saved_plane(): axes._nearest_plane(MemoryOutput(), 0.0) -def test_plane_field_refuses_a_plane_and_a_position_together(output): - with pytest.raises(OutputError, match="not both"): - axes._plane_field(output, 0, 0.0, convention="fft") - - -def test_plane_field_refuses_an_index_out_of_range(output): - with pytest.raises(OutputError, match="out of range"): - axes._plane_field(output, 9, None, convention="fft") +@pytest.mark.parametrize( + ("index", "z", "message"), [(0, 0.0, "not both"), (9, None, "out of range")] +) +def test_plane_field_refuses_a_plane_it_cannot_name(output, index, z, message): + with pytest.raises(OutputError, match=message): + axes._plane_field(output, index, z, convention="fft") def test_plane_field_counts_a_negative_index_from_the_end(output): diff --git a/tests/processing/test_spectra.py b/tests/processing/test_spectra.py index 4ae3f97d0..5be2029f2 100644 --- a/tests/processing/test_spectra.py +++ b/tests/processing/test_spectra.py @@ -87,15 +87,18 @@ def test_an_empty_band_needs_an_explicit_width(grid): assert spectra.bandpass(grid, (800e-9, 800e-9), width=4 * grid.d_omega).max() > 0.0 -@pytest.mark.parametrize("limits", [(0.0, 900e-9), (-1e-6, 900e-9)]) -def test_bandpass_refuses_a_non_positive_wavelength(grid, limits): - with pytest.raises(ProcessingError, match="must be positive"): - spectra.bandpass(grid, limits) - - -def test_bandpass_refuses_a_non_positive_width(grid): - with pytest.raises(ProcessingError, match="width must be positive"): - spectra.bandpass(grid, (700e-9, 900e-9), width=0.0) +@pytest.mark.parametrize( + ("limits", "options", "message"), + [ + ((0.0, 900e-9), {}, "must be positive"), + ((-1e-6, 900e-9), {}, "must be positive"), + ((700e-9, 900e-9), {"width": 0.0}, "width must be positive"), + ((-1e14, 1e15), {"axis": "f"}, "must not be negative"), + ], +) +def test_bandpass_refuses_a_band_or_width_out_of_range(grid, limits, options, message): + with pytest.raises(ProcessingError, match=message): + spectra.bandpass(grid, limits, **options) @pytest.mark.parametrize(("axis", "turn"), [("f", C), ("omega", 2 * np.pi * C)]) @@ -114,11 +117,6 @@ def test_a_frequency_band_may_start_at_zero(grid): assert np.all(window[blue] == 0.0) -def test_bandpass_refuses_a_negative_frequency(grid): - with pytest.raises(ProcessingError, match="must not be negative"): - spectra.bandpass(grid, (-1e14, 1e15), axis="f") - - def test_a_passband_builds_the_window_of_its_axis_and_width(grid): band = spectra.Passband((1e14, 4e14), "f", width=8 * grid.d_omega) np.testing.assert_array_equal( From 6bd0541b91867753f749ed9d1564a326ca9c14de Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:31:57 +0000 Subject: [PATCH 06/13] Start tests/builders.py: the launch derivative and the dispersive capillary Four modules opened numpy_ref, loaded the launch, hoisted to z = 0 and took the nonlinear stage with unit weights in the same eight lines. That body is now builders.launch_derivative, and the open-run-close wrapper two of them defined identically (stage_derivative) is builders.numpy_ref_launch_derivative. The call is the same code, so what each test measures is unchanged. test_dispersive_kerr.py's own capillary repeated backends/dispersive_cases.py's with one mode; it now calls that one with modes=1 (from_capillary's default). Pinned before the old copy was deleted: the configuration hash of the old and the new builder agree for every call shape the module makes (the four grid cases under three policies, the two mixtures, thg on and off, and the lossless replay's grid/schedule/integrator overrides) - 18 hashes equal. Counts (lines, tests, assert, assert_*, raises, match=), before -> after: backends/test_dispersive_kerr.py 415->378, 17->17, 14->14, 5->5, 3->3, 3->3 backends/test_dispersive_kerr_routes.py 995->981, 44->44, 59->59, 12->12, 6->6, 6->6 backends/test_radial_nonlinear.py 542->537, 64->64, 6->6, 9->9, 2->2, 2->2 optmat_parity.py 421->416, helper, 13->13 asserts builders.py new, 48 lines Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/backends/test_dispersive_kerr.py | 51 +++---------------- tests/backends/test_dispersive_kerr_routes.py | 18 +------ tests/backends/test_radial_nonlinear.py | 9 +--- tests/builders.py | 48 +++++++++++++++++ tests/optmat_parity.py | 9 +--- 5 files changed, 61 insertions(+), 74 deletions(-) create mode 100644 tests/builders.py diff --git a/tests/backends/test_dispersive_kerr.py b/tests/backends/test_dispersive_kerr.py index cfce084a0..5dd5f64bb 100644 --- a/tests/backends/test_dispersive_kerr.py +++ b/tests/backends/test_dispersive_kerr.py @@ -17,20 +17,20 @@ """ import dataclasses -import warnings -from collections.abc import Mapping from typing import Any, cast import numpy as np import pytest +from backends.dispersive_cases import capillary as dispersive_capillary from backends.matched import dispersive_response_bound from bounds import assert_within +from builders import numpy_ref_launch_derivative as stage_derivative from solprop.backends.numpy_ref import NumpyRefBackend, passes from solprop.boundaries import Absorber from solprop.constants import EPS0 from solprop.driver import Simulation -from solprop.exceptions import BackendError, MaterialRangeWarning +from solprop.exceptions import BackendError from solprop.grid import FieldGrid, RadialGrid from solprop.nonlinear.responses import ( DispersiveKerrResponse, @@ -40,7 +40,7 @@ mixture_filter, ) from solprop.output import MemoryOutput -from solprop.physdata import MaterialSelection, Mixture +from solprop.physdata import Mixture from solprop.physdata.nonlinear_data import DispersiveKerrModel, OptmatKerr from solprop.pulses import GaussianPulse, SpatialPulse from solprop.spatial import SpatialMedium @@ -67,31 +67,9 @@ } -def capillary( - policy: str = "gas-polynomial", - *, - gas: str | Mapping[str, float] = "Ar", - **overrides: object, -) -> Simulation: - """Return a short single-mode argon capillary under an electronic policy.""" - # The keywords of one entry point, of as many types as it takes. - arguments: dict[str, Any] = { - "wavelength": 800e-9, - "wavelength_limits": (150e-9, 4e-6), - "trange": 150e-15, - "fwhm": 10e-15, - "energy": 30e-6, - "materials": MaterialSelection(electronic=policy), - "plasma": False, - "raman": False, - "backend": "numpy_ref", - "n_save": 2, - } | overrides - with warnings.catch_warnings(): - warnings.simplefilter("ignore", MaterialRangeWarning) - return Simulation.from_capillary( - 75e-6, LENGTH, gas, 2.0, **{"noise": None, **arguments} - ) +def capillary(policy: str = "gas-polynomial", **overrides: object) -> Simulation: + """Return :func:`backends.dispersive_cases.capillary` with one mode, the HE11.""" + return dispersive_capillary(policy, **{"modes": 1, **overrides}) def node_field(problem, bundle): @@ -232,21 +210,6 @@ def test_a_symmetric_mixture_is_one_cubic_under_its_mixture_filter(): assert_within(got[0], expected, bound, what="polarisation") -def stage_derivative(problem, run_request, grid): - """Return ``numpy_ref``'s stage derivative at the launch.""" - backend = NumpyRefBackend(problem, run_request, grid=grid) - try: - backend.set_initial(problem.initial.field0, None) - backend._hoist(0.0) - return backend._nonlinear( - backend._require_state(), - backend._stage_scalars(0.0, 0.0), - np.ones((1, *problem.shape), complex), - ) - finally: - backend.close() - - @pytest.mark.parametrize("thg", [True, False]) def test_without_dispersion_the_mode_averaged_derivative_is_the_constant_one(thg): """The whole fused path -- projection, transforms, prefactor -- around the leaf. diff --git a/tests/backends/test_dispersive_kerr_routes.py b/tests/backends/test_dispersive_kerr_routes.py index 0294ed0c9..01ab66993 100644 --- a/tests/backends/test_dispersive_kerr_routes.py +++ b/tests/backends/test_dispersive_kerr_routes.py @@ -37,11 +37,12 @@ from backends.matched import dispersive_response_bound from bounds import assert_within +from builders import numpy_ref_launch_derivative as stage_derivative from legacy_geometry import LEGACY_GRID, bare_absorber from modal_provider_cases import GENERAL_Z_END, WAVELENGTH, general_grid from solprop.backends import node_chunk from solprop.backends.node_chunk import DEFAULT_NODE_BUDGET -from solprop.backends.numpy_ref import NumpyRefBackend, general_modal, passes +from solprop.backends.numpy_ref import general_modal, passes from solprop.backends.numpy_ref.backend import _general_maps from solprop.boundaries import Absorber from solprop.driver import Simulation, SimulationSettings @@ -144,21 +145,6 @@ def unit_collar(translation): ) -def stage_derivative(problem, run_request, grid): - """Return ``numpy_ref``'s stage derivative at the launch.""" - backend = NumpyRefBackend(problem, run_request, grid=grid) - try: - backend.set_initial(problem.initial.field0, None) - backend._hoist(0.0) - return backend._nonlinear( - backend._require_state(), - backend._stage_scalars(0.0, 0.0), - np.ones((1, *problem.shape), complex), - ) - finally: - backend.close() - - def assert_same_derivative(got, expected): """Hold two stage derivatives to the few FFT round trips the leaf adds. diff --git a/tests/backends/test_radial_nonlinear.py b/tests/backends/test_radial_nonlinear.py index 68ba1408f..fc55285e8 100644 --- a/tests/backends/test_radial_nonlinear.py +++ b/tests/backends/test_radial_nonlinear.py @@ -16,6 +16,7 @@ from backends.test_polarised_runs import QuadraticRate as EnergyRate from backends.test_polarised_runs import plasma_work_bound from bounds import gamma, ladder_bound +from builders import launch_derivative from legacy_geometry import LEGACY_GRID from sessions.runs import native_trial, run from solprop.backends.numpy_ref import NumpyRefBackend @@ -114,13 +115,7 @@ def derivative(spatial_backend_class, problem, run_request, grid, options=None): backend = spatial_backend_class(problem, run_request, grid=grid, options=options) try: if isinstance(backend, NumpyRefBackend): - backend.set_initial(problem.initial.field0, None) - backend._hoist(0.0) - return backend._nonlinear( - backend._require_state(), - backend._stage_scalars(0.0, 0.0), - np.ones((1, *problem.shape), complex), - )[0] + return launch_derivative(backend, problem)[0] return _native_first_stage(backend, problem) finally: backend.close() diff --git a/tests/builders.py b/tests/builders.py new file mode 100644 index 000000000..b83d12d9b --- /dev/null +++ b/tests/builders.py @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: 2026 John C. Travers and contributors +# +# SPDX-License-Identifier: GPL-3.0-or-later + +"""Shared builders for tests: construction code several test modules repeated. + +A builder here replaces copies that were the same code, so a migrated test builds +exactly what it built before; a builder that assembles a problem or a simulation was +pinned, when it was migrated, by the configuration hash of what the old copies built. +""" + +from typing import Any + +import numpy as np + +from solprop.backends.numpy_ref import NumpyRefBackend +from solprop.grid import TimeGrid +from solprop.translate.problem import PropagationProblem +from solprop.translate.run_request import RunRequest + +__all__ = ["launch_derivative", "numpy_ref_launch_derivative"] + + +def launch_derivative(backend: NumpyRefBackend, problem: PropagationProblem) -> Any: + """Return an open ``numpy_ref`` backend's stage derivative ``N(E, z=0)`` at launch. + + The backend is loaded with the problem's launch field, hoisted to z = 0 and asked + for its nonlinear stage there with unit stage weights, as the first stage of a + trial is. + """ + backend.set_initial(problem.initial.field0, None) + backend._hoist(0.0) + return backend._nonlinear( + backend._require_state(), + backend._stage_scalars(0.0, 0.0), + np.ones((1, *problem.shape), complex), + ) + + +def numpy_ref_launch_derivative( + problem: PropagationProblem, run_request: RunRequest, grid: TimeGrid +) -> Any: + """Open ``numpy_ref`` on the problem, return :func:`launch_derivative`, close it.""" + backend = NumpyRefBackend(problem, run_request, grid=grid) + try: + return launch_derivative(backend, problem) + finally: + backend.close() diff --git a/tests/optmat_parity.py b/tests/optmat_parity.py index a8d3764dc..0656e7c15 100644 --- a/tests/optmat_parity.py +++ b/tests/optmat_parity.py @@ -51,6 +51,7 @@ import numpy as np from bounds import rate_log_sensitivity +from builders import launch_derivative from optmat_parity_cases import Case, build_case from sessions.runs import load_native, native_trial, saved, to_planes from sessions.runs import run as run_session @@ -152,13 +153,7 @@ def derivative(backend_class, case: Case) -> np.ndarray: backend = _backend(backend_class, case) try: if isinstance(backend, NumpyRefBackend): - backend.set_initial(problem.initial.field0, None) - backend._hoist(0.0) - return backend._nonlinear( - backend._require_state(), - backend._stage_scalars(0.0, 0.0), - np.ones((1, *problem.shape), complex), - )[0] + return launch_derivative(backend, problem)[0] # The native state itself, loaded with the launch, takes the zero-length trial # on the staged rows, as the native backend's own trial does (SEP 47 phase 5). assert backend.name == "native" From d9fe50849a449c6e7166abac0898edad3b5fd5d8 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:33:11 +0000 Subject: [PATCH 07/13] Fold nonlinear and physdata guard tests into argument tables Guards that make the same refusing call with different arguments become one parametrised table each, and one standalone guard joins the existing problem_from table. Every site keeps its exception class, call and exact match string as a table row, and the comments move onto their rows. (The old explicit KerrResponse(1.0, thg=True) is the default KerrResponse(1.0).) Collected tests, asserts and assert calls are unchanged per module: - nonlinear/test_plasma.py: lines 709->705, tests 51->51, assert 52->52, raises 14->11, match= 14->11 - nonlinear/test_responses.py: lines 315->303, tests 27->27, assert 17->17, raises 10->3, match= 10->3 - nonlinear/test_gnlse.py: lines 616->613, tests 61->61, assert 88->88, raises 13->12, match= 13->12 - nonlinear/test_envelope_plasma.py: lines 412->406, tests 55->55, assert 22->22, raises 19->16, match= 19->16 - physdata/test_optmat_bridge.py: lines 295->289, tests 29->29, assert 56->56, warns 7->5, match= 10->8 - physdata/test_sellmeier.py: lines 449->444, tests 235->235, assert 36->36, raises 7->4, match= 9->6 - physdata/test_raman_data.py: lines 173->169, tests 26->26, assert 10->10, raises 5->4, match= 4->3 Each dropped raises/warns/match= site is now a table row whose match string is a literal in the same file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/nonlinear/test_envelope_plasma.py | 50 ++++++------ tests/nonlinear/test_gnlse.py | 17 ++-- tests/nonlinear/test_plasma.py | 34 ++++---- tests/nonlinear/test_responses.py | 100 +++++++++++------------- tests/physdata/test_optmat_bridge.py | 32 +++----- tests/physdata/test_raman_data.py | 30 +++---- tests/physdata/test_sellmeier.py | 41 +++++----- 7 files changed, 132 insertions(+), 172 deletions(-) diff --git a/tests/nonlinear/test_envelope_plasma.py b/tests/nonlinear/test_envelope_plasma.py index f7e46d4c0..b248c6835 100644 --- a/tests/nonlinear/test_envelope_plasma.py +++ b/tests/nonlinear/test_envelope_plasma.py @@ -299,34 +299,34 @@ def test_invalid_initial_fraction_is_refused(value): EnvelopePlasmaResponse("Ar", PolynomialRate(), preionisation=value) -@pytest.mark.parametrize("value", [0.0, -1.0, np.nan, np.inf]) -def test_invalid_dt_is_refused(value): - with pytest.raises(GridError, match="dt"): - EnvelopePlasmaResponse("Ar", PolynomialRate()).sources( - np.zeros((1, 1), complex), 1, dt=value - ) - - -@pytest.mark.parametrize("value", [-1.0, np.nan, np.inf]) -def test_invalid_density_is_refused(value): - with pytest.raises(GridError, match="density"): - EnvelopePlasmaResponse("Ar", PolynomialRate()).sources( - np.zeros((1, 1), complex), value, dt=1 - ) +ZERO = np.zeros((1, 1), complex) @pytest.mark.parametrize( - "field", + ("field", "density", "dt", "match"), [ - np.zeros((3, 1), complex), - np.zeros((1, 0), complex), - np.full((1, 1), np.nan + 0j), - np.full((1, 1), np.inf + 0j), + (ZERO, 1, 0.0, "dt"), + (ZERO, 1, -1.0, "dt"), + (ZERO, 1, np.nan, "dt"), + (ZERO, 1, np.inf, "dt"), + (ZERO, -1.0, 1, "density"), + (ZERO, np.nan, 1, "density"), + (ZERO, np.inf, 1, "density"), + (np.zeros((3, 1), complex), 1, 1, "field"), + (np.zeros((1, 0), complex), 1, 1, "field"), + (np.full((1, 1), np.nan + 0j), 1, 1, "field"), + (np.full((1, 1), np.inf + 0j), 1, 1, "field"), + ( + np.full((2, 1), np.finfo(float).max, complex), + 1.0, + 1.0, + "magnitude is not representable", + ), ], ) -def test_invalid_field_is_refused(field): - with pytest.raises(GridError, match="field"): - EnvelopePlasmaResponse("Ar", PolynomialRate()).sources(field, 1, dt=1) +def test_invalid_sources_inputs_are_refused(field, density, dt, match): + with pytest.raises(GridError, match=match): + EnvelopePlasmaResponse("Ar", PolynomialRate()).sources(field, density, dt=dt) def test_source_container_copies_inputs_and_validates(): @@ -368,12 +368,6 @@ def test_invalid_binding_and_nonzero_dark_rate_are_refused(): EnvelopePlasmaResponse("Ar", PolynomialRate(power=0)) -def test_unrepresentable_physical_magnitude_is_refused(): - field = np.full((2, 1), np.finfo(float).max, complex) - with pytest.raises(GridError, match="magnitude is not representable"): - EnvelopePlasmaResponse("Ar", PolynomialRate()).sources(field, 1.0, dt=1.0) - - def test_adaptive_cycle_failure_is_reported(monkeypatch): def failed_integral(*args, **kwargs): return np.zeros(2, complex), np.inf, SimpleNamespace(success=False) diff --git a/tests/nonlinear/test_gnlse.py b/tests/nonlinear/test_gnlse.py index 909831aee..43986c38c 100644 --- a/tests/nonlinear/test_gnlse.py +++ b/tests/nonlinear/test_gnlse.py @@ -450,16 +450,6 @@ def test_the_raman_response_integrates_to_its_share(mode): assert integral == pytest.approx(expected, rel=1e-5) -def test_raman_with_a_zero_fraction_is_refused(): - # A declared response that carries none of the nonlinearity would pay for a - # convolution at every stage and change nothing; RamanResponse refuses the fraction - # in any case. - with pytest.raises(ModeError, match="carries none of the nonlinearity"): - problem_from( - BETAS, omega_ref=OMEGA_REF, gamma=0.1, raman=True, raman_fraction=0.0 - ) - - def test_the_default_fraction_is_silica_s_with_raman_on_and_none_with_it_off(): on = problem_from(BETAS, omega_ref=OMEGA_REF, gamma=0.1, raman=True) off = problem_from(BETAS, omega_ref=OMEGA_REF, gamma=0.1, raman=False) @@ -550,6 +540,13 @@ def test_the_mapping_records_what_it_was_given(): r"raman_fraction must lie in \[0, 1\]", ), ({"gamma": 0.1, "aeff": 0.0}, "aeff must be positive"), + # A declared response that carries none of the nonlinearity would pay for a + # convolution at every stage and change nothing; RamanResponse refuses the + # fraction in any case. + ( + {"gamma": 0.1, "raman": True, "raman_fraction": 0.0}, + "carries none of the nonlinearity", + ), ], ) def test_a_bad_mapping_request_is_rejected(kwargs, message): diff --git a/tests/nonlinear/test_plasma.py b/tests/nonlinear/test_plasma.py index 1bd74d4c2..91242cb87 100644 --- a/tests/nonlinear/test_plasma.py +++ b/tests/nonlinear/test_plasma.py @@ -607,14 +607,21 @@ def test_an_envelope_grid_is_rejected(response): ) -def test_a_complex_array_is_rejected(response): - with pytest.raises(GridError, match="real field"): - response.evaluate(np.zeros((1, 8), dtype=complex), 1.0, dt=1e-16, kind="field") - - -def test_too_many_polarisation_components_are_rejected(response): - with pytest.raises(GridError, match="n_pol must be 1 or 2"): - response.evaluate(np.zeros((3, 8)), 1.0, dt=1e-16, kind="field") +@pytest.mark.parametrize( + ("field", "density", "dt", "match"), + [ + (np.zeros((1, 8), dtype=complex), 1.0, 1e-16, "real field"), + (np.zeros((3, 8)), 1.0, 1e-16, "n_pol must be 1 or 2"), + (np.zeros((1, 8)), 1.0, 0.0, "dt must be positive"), + (np.zeros((1, 8)), 1.0, -1e-16, "dt must be positive"), + (np.zeros((1, 8)), 1.0, math.inf, "dt must be positive"), + (np.zeros((1, 8)), 1.0, math.nan, "dt must be positive"), + (np.zeros((1, 8)), -1.0, 1e-16, "density must be non-negative"), + ], +) +def test_a_bad_field_step_or_density_is_rejected(response, field, density, dt, match): + with pytest.raises(GridError, match=match): + response.evaluate(field, density, dt=dt, kind="field") @pytest.mark.parametrize("shape", [(8,), (1, 2, 8)]) @@ -624,17 +631,6 @@ def test_an_array_that_is_not_two_dimensional_is_rejected(shape): _check_plasma(np.zeros(shape), "field", 1e-16) -@pytest.mark.parametrize("bad", [0.0, -1e-16, math.inf, math.nan]) -def test_a_bad_time_step_is_rejected(bad, response): - with pytest.raises(GridError, match="dt must be positive"): - response.evaluate(np.zeros((1, 8)), 1.0, dt=bad, kind="field") - - -def test_a_negative_density_is_rejected(response): - with pytest.raises(GridError, match="density must be non-negative"): - response.evaluate(np.zeros((1, 8)), -1.0, dt=1e-16, kind="field") - - @pytest.mark.parametrize("bad", [-0.1, 1.1]) def test_an_impossible_pre_ionisation_is_rejected(bad): with pytest.raises(MaterialError, match=r"preionisation must be in \[0, 1\]"): diff --git a/tests/nonlinear/test_responses.py b/tests/nonlinear/test_responses.py index c64a17bc4..3dff9ef46 100644 --- a/tests/nonlinear/test_responses.py +++ b/tests/nonlinear/test_responses.py @@ -257,59 +257,47 @@ def test_thg_carrier_rejects_a_non_positive_frequency(): # ------------------------------------------------------------------- error paths -def test_evaluate_rejects_an_unknown_layout(): - with pytest.raises(GridError, match="kind must be"): - _check_evaluate(np.zeros((1, 4)), "spectral", None, needs_carrier=False) - - -def test_evaluate_rejects_more_than_two_polarisation_components(): - with pytest.raises(GridError, match="n_pol must be 1 or 2"): - KerrResponse(1.0).evaluate(np.zeros((3, 4)), 1.0, kind="field") - - -@pytest.mark.parametrize("shape", [(4,), (1, 2, 4)]) -def test_evaluate_rejects_an_array_that_is_not_two_dimensional(shape): - # Through the guard directly: the jaxtyping hook rejects the rank before the - # library's own check is reached, exactly as for `fourier._check_kind`. - with pytest.raises(GridError, match="field_t must have shape"): - _check_evaluate(np.zeros(shape), "field", None, needs_carrier=False) - - -def test_field_layout_rejects_a_complex_array(): - with pytest.raises(GridError, match="real field"): - KerrResponse(1.0).evaluate(np.zeros((1, 4), dtype=complex), 1.0, kind="field") - - -def test_envelope_layout_rejects_a_real_array(): - with pytest.raises(GridError, match="complex envelope"): - KerrResponse(1.0).evaluate(np.zeros((1, 4)), 1.0, kind="envelope") - - -def test_envelope_third_harmonic_needs_a_carrier(): - with pytest.raises(GridError, match="needs the carrier"): - KerrResponse(1.0, thg=True).evaluate( - np.zeros((1, 4), dtype=complex), 1.0, kind="envelope" - ) - - -def test_a_carrier_is_rejected_where_it_would_be_ignored(): - with pytest.raises(GridError, match="only used on an envelope grid"): - KerrResponse(1.0).evaluate( - np.zeros((1, 4)), 1.0, kind="field", carrier=np.ones(4, dtype=complex) - ) - - -def test_a_carrier_of_the_wrong_length_is_rejected(): - # Through the guard directly, for the same reason as the rank check above. - with pytest.raises(GridError, match="carrier has shape"): - _check_evaluate( - np.zeros((1, 4), dtype=complex), - "envelope", - np.ones(5, dtype=complex), - needs_carrier=True, - ) - - -def test_a_negative_density_is_rejected(): - with pytest.raises(GridError, match="density must be non-negative"): - KerrResponse(1.0).evaluate(np.zeros((1, 4)), -1.0, kind="field") +REAL = np.zeros((1, 4)) +COMPLEX = np.zeros((1, 4), dtype=complex) + + +@pytest.mark.parametrize( + ("field", "kind", "carrier", "needs_carrier", "match"), + [ + (REAL, "spectral", None, False, "kind must be"), + # Through the guard directly: the jaxtyping hook rejects the rank before the + # library's own check is reached, exactly as for `fourier._check_kind`. + (np.zeros(4), "field", None, False, "field_t must have shape"), + (np.zeros((1, 2, 4)), "field", None, False, "field_t must have shape"), + # Through the guard directly, for the same reason as the rank check. + (COMPLEX, "envelope", np.ones(5, dtype=complex), True, "carrier has shape"), + ], +) +def test_the_evaluate_guard_rejects_a_bad_layout( + field, kind, carrier, needs_carrier, match +): + with pytest.raises(GridError, match=match): + _check_evaluate(field, kind, carrier, needs_carrier=needs_carrier) + + +# The Kerr response's own refusals (thg on, its default). +@pytest.mark.parametrize( + ("field", "density", "kind", "carrier", "match"), + [ + (np.zeros((3, 4)), 1.0, "field", None, "n_pol must be 1 or 2"), + (COMPLEX, 1.0, "field", None, "real field"), + (REAL, 1.0, "envelope", None, "complex envelope"), + (COMPLEX, 1.0, "envelope", None, "needs the carrier"), + ( + REAL, + 1.0, + "field", + np.ones(4, dtype=complex), + "only used on an envelope grid", + ), + (REAL, -1.0, "field", None, "density must be non-negative"), + ], +) +def test_evaluate_rejects_a_bad_field(field, density, kind, carrier, match): + with pytest.raises(GridError, match=match): + KerrResponse(1.0).evaluate(field, density, kind=kind, carrier=carrier) diff --git a/tests/physdata/test_optmat_bridge.py b/tests/physdata/test_optmat_bridge.py index e7f12db75..680830c58 100644 --- a/tests/physdata/test_optmat_bridge.py +++ b/tests/physdata/test_optmat_bridge.py @@ -246,28 +246,22 @@ def test_translated_turns_optmat_range_warnings_into_one_material_warning(): assert "optmat:" in message -def test_translated_without_a_band_names_the_range(): - with ( - pytest.warns(MaterialRangeWarning, match="qualified range"), - _optmat.translated(ARGON, "polarizability", material="Ar"), - ): - warnings.warn("outside", ModelRangeWarning, stacklevel=1) - - -def test_translated_passes_other_warnings_through(): - with ( - pytest.warns(RuntimeWarning, match="unrelated"), - _optmat.translated(ARGON, "polarizability", material="Ar"), - ): - warnings.warn("unrelated", RuntimeWarning, stacklevel=1) - - -def test_translated_converts_absorption_warnings(): +@pytest.mark.parametrize( + ("message", "category", "expected", "match"), + [ + # Without a band, the warning names the qualified range. + ("outside", ModelRangeWarning, MaterialRangeWarning, "qualified range"), + # Other warnings pass through unchanged. + ("unrelated", RuntimeWarning, RuntimeWarning, "unrelated"), + ("absorbs", ModelAbsorptionWarning, MaterialRangeWarning, "Ar: absorbs"), + ], +) +def test_translated_converts_optmat_warnings(message, category, expected, match): with ( - pytest.warns(MaterialRangeWarning, match="Ar: absorbs"), + pytest.warns(expected, match=match), _optmat.translated(ARGON, "polarizability", material="Ar"), ): - warnings.warn("absorbs", ModelAbsorptionWarning, stacklevel=1) + warnings.warn(message, category, stacklevel=1) def test_translated_turns_optmat_errors_into_material_errors(): diff --git a/tests/physdata/test_raman_data.py b/tests/physdata/test_raman_data.py index 218958f22..014941eef 100644 --- a/tests/physdata/test_raman_data.py +++ b/tests/physdata/test_raman_data.py @@ -122,24 +122,20 @@ def test_a_supplied_line_set_counts_its_lines(): assert lines.n_lines == 2 -def test_a_line_set_with_mismatched_lengths_is_rejected(): - with pytest.raises(MaterialError, match="same length"): - IntermediateBroadeningRaman( - frequencies=(1.0, 2.0), - amplitudes=(1.0,), - gaussian_widths=(1.0, 2.0), - lorentzian_widths=(1.0, 2.0), - citation="test", - ) - - -def test_an_empty_line_set_is_rejected(): - with pytest.raises(MaterialError, match="at least one line"): +@pytest.mark.parametrize( + ("frequencies", "amplitudes", "widths", "match"), + [ + ((1.0, 2.0), (1.0,), (1.0, 2.0), "same length"), + ((), (), (), "at least one line"), + ], +) +def test_a_malformed_line_set_is_rejected(frequencies, amplitudes, widths, match): + with pytest.raises(MaterialError, match=match): IntermediateBroadeningRaman( - frequencies=(), - amplitudes=(), - gaussian_widths=(), - lorentzian_widths=(), + frequencies=frequencies, + amplitudes=amplitudes, + gaussian_widths=widths, + lorentzian_widths=widths, citation="test", ) diff --git a/tests/physdata/test_sellmeier.py b/tests/physdata/test_sellmeier.py index fd368399b..0aa586350 100644 --- a/tests/physdata/test_sellmeier.py +++ b/tests/physdata/test_sellmeier.py @@ -182,29 +182,24 @@ def test_unknown_gas_is_rejected(): refractive_index("Argon", 1e15, pressure=1.0) -@pytest.mark.parametrize("bad", [-1.0, np.array([1e15, -1e15])]) -def test_negative_frequency_is_rejected(bad): - with pytest.raises(MaterialError, match="must not be negative"): - refractive_index(Gas.Ar, bad, pressure=1.0) - - -@pytest.mark.parametrize("bad", [np.nan, np.inf, np.array([1e15, np.nan])]) -def test_non_finite_frequency_is_rejected(bad): - with pytest.raises(MaterialError, match="must be finite"): - refractive_index(Gas.Ar, bad, pressure=1.0) - - -@pytest.mark.parametrize("bad", [1e15 + 1j, np.array([1e15 + 0j])]) -def test_complex_frequency_is_rejected(bad): - # numpy would cast a complex argument to float with a ComplexWarning rather than - # refusing it, so it is caught at the boundary instead. - with pytest.raises(MaterialError, match="must be real, got a complex value"): - refractive_index(Gas.Ar, bad, pressure=1.0) - - -@pytest.mark.parametrize("bad", ["800 nm", ["a", "b"]]) -def test_non_numeric_frequency_is_rejected(bad): - with pytest.raises(MaterialError, match="must be real"): +@pytest.mark.parametrize( + ("bad", "match"), + [ + (-1.0, "must not be negative"), + (np.array([1e15, -1e15]), "must not be negative"), + (np.nan, "must be finite"), + (np.inf, "must be finite"), + (np.array([1e15, np.nan]), "must be finite"), + # numpy would cast a complex argument to float with a ComplexWarning rather + # than refusing it, so it is caught at the boundary instead. + (1e15 + 1j, "must be real, got a complex value"), + (np.array([1e15 + 0j]), "must be real, got a complex value"), + ("800 nm", "must be real"), + (["a", "b"], "must be real"), + ], +) +def test_a_bad_frequency_is_rejected(bad, match): + with pytest.raises(MaterialError, match=match): refractive_index(Gas.Ar, bad, pressure=1.0) From 073eb3875a6417ebae904748f0453ca0b459c1c6 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:33:11 +0000 Subject: [PATCH 08/13] Fold repeated translate guard scaffolding into parametrised tables Guards that rebuild the same constructor, assemble call or corrupted problem now share one parametrised body; each row keeps its call, exception and exact match. - test_problem.py: twenty validate_run refusals of a corrupted field become SPOILED rows (problem fixture, group, field, spoiled value, match), and nine assemble refusals join the existing bad-request table, with the state and the mode set as overridable entries. The non-contiguity assert is kept in its helper. 1676 -> 1555 lines; tests 99 -> 99; assert 107 -> 107; assert_* 5 -> 5; raises 56 -> 29; match= 54 -> 27. - test_compiled_responses.py: 4 CompiledResponses refusals -> one table (1009 -> 995 lines; tests 81 -> 81; assert 125 -> 125; raises 25 -> 22; match= 25 -> 22) - test_general_route.py: 3 general-route assemble refusals -> one table (1003 -> 987; tests 52 -> 52; assert 113 -> 113; raises 38 -> 36; match= 37 -> 35) - test_linop.py: 4 LinearOperator member refusals (5 cases) -> one table (1393 -> 1378; tests 87 -> 87; assert 140 -> 140; raises 18 -> 15; match= 18 -> 15) Collected tests, assert statements and assert_* calls are unchanged in each module and every base match= string is a row literal; no tolerance, marker or fixture changed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/translate/test_compiled_responses.py | 128 ++--- tests/translate/test_general_route.py | 64 +-- tests/translate/test_linop.py | 83 ++- tests/translate/test_problem.py | 639 +++++++++------------ 4 files changed, 374 insertions(+), 540 deletions(-) diff --git a/tests/translate/test_compiled_responses.py b/tests/translate/test_compiled_responses.py index 69d5540d8..dd42ab659 100644 --- a/tests/translate/test_compiled_responses.py +++ b/tests/translate/test_compiled_responses.py @@ -599,41 +599,63 @@ def test_no_absorber_means_no_rates(envelope_grid, mode): assert compiled.temporal_absorber_fine is None -def test_one_rate_without_the_other_is_refused(envelope_grid, mode): - compiled = compile_for(envelope_grid, mode, absorber=absorber(envelope_grid)) - with pytest.raises(TranslationError, match="must both be present"): - CompiledResponses( - kerr_coefficients=None, - ionisation_table=(), - plasma_channels=(), - raman_terms=(), - density=compiled.density, - prefactor_representation=compiled.prefactor_representation, - prefactor=compiled.prefactor, - prefactor_expansion=compiled.prefactor_expansion, - prefactor_constant=compiled.prefactor_constant, - temporal_absorber=compiled.temporal_absorber, - temporal_absorber_fine=None, - ) - - -def test_a_prefactor_representation_without_its_member_is_refused(envelope_grid, mode): - """The kind and the member that carries it are one statement, checked both ways.""" - compiled = compile_for(envelope_grid, mode) - with pytest.raises(TranslationError, match="prefactor_expansion must be present"): - CompiledResponses( - kerr_coefficients=None, - ionisation_table=(), - plasma_channels=(), - raman_terms=(), - density=compiled.density, - prefactor_representation="expansion", - prefactor=compiled.prefactor, - prefactor_expansion=None, - prefactor_constant=None, - temporal_absorber=None, - temporal_absorber_fine=None, - ) +# Each row builds the group by hand from a compiled one, `changes(compiled)` replacing +# members of the plain constructor call below, and names the refusal. The kind and the +# members that carry the prefactor are one statement, checked both ways. +@pytest.mark.parametrize( + ("absorbed", "changes", "message"), + [ + ( + True, + lambda c: {"temporal_absorber": c.temporal_absorber}, + "must both be present", + ), + ( + False, + lambda c: { + "prefactor_representation": "expansion", + "prefactor_expansion": None, + "prefactor_constant": None, + }, + "prefactor_expansion must be present", + ), + ( + False, + lambda c: {"prefactor_constant": np.zeros((1, 1, 7), dtype=complex)}, + "prefactor_constant has shape", + ), + ( + False, + lambda c: { + "prefactor_representation": "table", + "prefactor": None, + "prefactor_expansion": None, + "prefactor_constant": None, + }, + "prefactor must be present", + ), + ], +) +def test_the_group_refuses_inconsistent_members( + envelope_grid, mode, absorbed, changes, message +): + extra = {"absorber": absorber(envelope_grid)} if absorbed else {} + compiled = compile_for(envelope_grid, mode, **extra) + members = { + "kerr_coefficients": None, + "ionisation_table": (), + "plasma_channels": (), + "raman_terms": (), + "density": compiled.density, + "prefactor_representation": compiled.prefactor_representation, + "prefactor": compiled.prefactor, + "prefactor_expansion": compiled.prefactor_expansion, + "prefactor_constant": compiled.prefactor_constant, + "temporal_absorber": None, + "temporal_absorber_fine": None, + } | changes(compiled) + with pytest.raises(TranslationError, match=message): + CompiledResponses(**members) # ------------------------------------------------------------------------- the density @@ -669,24 +691,6 @@ def test_an_empty_mode_set_is_refused(envelope_grid): compile_for(envelope_grid, []) -def test_a_constant_prefactor_of_the_wrong_shape_is_refused(envelope_grid, mode): - compiled = compile_for(envelope_grid, mode) - with pytest.raises(TranslationError, match="prefactor_constant has shape"): - CompiledResponses( - kerr_coefficients=None, - ionisation_table=(), - plasma_channels=(), - raman_terms=(), - density=compiled.density, - prefactor_representation=compiled.prefactor_representation, - prefactor=compiled.prefactor, - prefactor_expansion=compiled.prefactor_expansion, - prefactor_constant=np.zeros((1, 1, 7), dtype=complex), - temporal_absorber=None, - temporal_absorber_fine=None, - ) - - def test_a_path_two_modes_share_is_resolved_once(envelope_grid): """Two modes of one tapered fibre carry the same bore object, not copies.""" bore = Linear(125e-6, 75e-6, 0.8) @@ -977,24 +981,6 @@ def test_the_raman_leaf_accepts_the_shape_the_compiler_gives_it(): assert not leaf.undamped.flags.writeable -def test_a_prefactor_table_without_its_kind_is_refused(envelope_grid, mode): - compiled = compile_for(envelope_grid, mode) - with pytest.raises(TranslationError, match="prefactor must be present"): - CompiledResponses( - kerr_coefficients=None, - ionisation_table=(), - plasma_channels=(), - raman_terms=(), - density=compiled.density, - prefactor_representation="table", - prefactor=None, - prefactor_expansion=None, - prefactor_constant=None, - temporal_absorber=None, - temporal_absorber_fine=None, - ) - - def test_the_group_refuses_a_constant_beside_a_kind_that_is_not_one( envelope_grid, mode ): diff --git a/tests/translate/test_general_route.py b/tests/translate/test_general_route.py index 8fb289680..30d4cccc0 100644 --- a/tests/translate/test_general_route.py +++ b/tests/translate/test_general_route.py @@ -361,50 +361,34 @@ def test_a_legacy_knob_beside_a_general_route_is_refused_by_name( problem_of(case, **override) -def test_a_declared_response_beside_a_general_route_is_refused(case): - state = np.zeros((1, 1, case.grid.n_omega), dtype=complex) - state[0, 0, 30] = 1.0 - with pytest.raises(TranslationError, match="declared response"): - assemble( - case.grid, - list(case.guide.mode_collection), - [KerrResponse(chi3=GENERAL_CHI3)], - state, - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[GENERAL_Z_END], - dz_max=GENERAL_Z_END / 10, - dz_init=GENERAL_Z_END / 20, - general=case.route, - ) - +@pytest.mark.parametrize( + ("envelope", "n_pol", "kerr", "message"), + [ + (False, 1, True, "declared response"), + # A leaf is tabulated on the canonical coarse grid. + (True, 1, False, "field-grid route"), + (False, 2, False, "keeps n_pol = 1"), + ], +) +def test_assemble_refuses_what_a_general_route_does_not_carry( + case, envelope, n_pol, kerr, message +): + """A declared response, an envelope grid or two polarisations beside the route. -def test_an_envelope_grid_cannot_carry_a_general_modal_route(case): - """A leaf is tabulated on the canonical coarse grid.""" - grid = EnvelopeGrid.from_limits(GENERAL_Z_END, 835e-9, (815e-9, 860e-9), 60e-15) - state = np.zeros((1, 1, grid.n_omega), dtype=complex) - state[0, 0, 3] = 1.0 - with pytest.raises(TranslationError, match="field-grid route"): + The state is one unit bin, at bin 3 of the envelope grid and bin 30 of the case's. + """ + grid = ( + EnvelopeGrid.from_limits(GENERAL_Z_END, 835e-9, (815e-9, 860e-9), 60e-15) + if envelope + else case.grid + ) + state = np.zeros((1, n_pol, grid.n_omega), dtype=complex) + state[0, :, 3 if envelope else 30] = 1.0 + with pytest.raises(TranslationError, match=message): assemble( grid, list(case.guide.mode_collection), - [], - state, - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[GENERAL_Z_END], - dz_max=GENERAL_Z_END / 10, - dz_init=GENERAL_Z_END / 20, - general=case.route, - ) - - -def test_a_state_with_two_polarisations_is_refused(case): - state = np.zeros((1, 2, case.grid.n_omega), dtype=complex) - state[0, :, 30] = 1.0 - with pytest.raises(TranslationError, match="keeps n_pol = 1"): - assemble( - case.grid, - list(case.guide.mode_collection), - [], + [KerrResponse(chi3=GENERAL_CHI3)] if kerr else [], state, controller=PIController(rtol=1e-8, atol=1e-14), save_planes=[GENERAL_Z_END], diff --git a/tests/translate/test_linop.py b/tests/translate/test_linop.py index 37e3abb19..a866d7f86 100644 --- a/tests/translate/test_linop.py +++ b/tests/translate/test_linop.py @@ -776,57 +776,42 @@ def test_the_tables_translation_builds_are_held_and_not_copied_again(): assert tabulated.hard_kinks.size and is_held(tabulated.hard_kinks) -def test_the_group_refuses_a_breakpoint_count_that_does_not_match(): - with pytest.raises(TranslationError, match="phi_breakpoints has"): - LinearOperator( - phi_representation="table", - phi_breakpoints=np.array([0.0, 0.5, 1.0]), - phi_coefficients=np.zeros((1, 2, 1, 1, 1, 3), dtype=complex), - phi_degrees=np.array([1]), - hard_kinks=np.empty(0), - phi_constant=None, - ) - - -def test_the_group_refuses_a_degree_count_that_does_not_match(): - """The degrees say how many intervals there are; the coefficients must agree.""" - with pytest.raises(TranslationError, match="phi_degrees has"): - LinearOperator( - phi_representation="table", - phi_breakpoints=np.array([0.0, 1.0]), - phi_coefficients=np.zeros((2, 2, 1, 1, 1, 3), dtype=complex), - phi_degrees=np.array([1]), - hard_kinks=np.empty(0), - phi_constant=None, - ) - - +# Each row changes members of a one-interval table group (the base below) and names +# the refusal. The degrees say how many intervals there are; the coefficients must +# agree. @pytest.mark.parametrize( - ("kind", "constant"), - [("constant", None), ("table", np.zeros((1, 1, 1, 3), dtype=complex))], + ("changes", "message"), + [ + ({"phi_breakpoints": np.array([0.0, 0.5, 1.0])}, "phi_breakpoints has"), + ( + {"phi_coefficients": np.zeros((2, 2, 1, 1, 1, 3), dtype=complex)}, + "phi_degrees has", + ), + ({"phi_representation": "constant"}, "phi_constant must be present"), + ( + {"phi_constant": np.zeros((1, 1, 1, 3), dtype=complex)}, + "phi_constant must be present", + ), + ( + { + "phi_representation": "constant", + "phi_constant": np.zeros((1, 1, 1, 4), dtype=complex), + }, + "phi_constant has shape", + ), + ], ) -def test_the_group_refuses_a_constant_that_disagrees_with_the_kind(kind, constant): - with pytest.raises(TranslationError, match="phi_constant must be present"): - LinearOperator( - phi_representation=kind, - phi_breakpoints=np.array([0.0, 1.0]), - phi_coefficients=np.zeros((1, 2, 1, 1, 1, 3), dtype=complex), - phi_degrees=np.array([1]), - hard_kinks=np.empty(0), - phi_constant=constant, - ) - - -def test_the_group_refuses_a_constant_of_the_wrong_shape(): - with pytest.raises(TranslationError, match="phi_constant has shape"): - LinearOperator( - phi_representation="constant", - phi_breakpoints=np.array([0.0, 1.0]), - phi_coefficients=np.zeros((1, 2, 1, 1, 1, 3), dtype=complex), - phi_degrees=np.array([1]), - hard_kinks=np.empty(0), - phi_constant=np.zeros((1, 1, 1, 4), dtype=complex), - ) +def test_the_group_refuses_inconsistent_members(changes, message): + members = { + "phi_representation": "table", + "phi_breakpoints": np.array([0.0, 1.0]), + "phi_coefficients": np.zeros((1, 2, 1, 1, 1, 3), dtype=complex), + "phi_degrees": np.array([1]), + "hard_kinks": np.empty(0), + "phi_constant": None, + } | changes + with pytest.raises(TranslationError, match=message): + LinearOperator(**members) def test_the_group_reports_its_size_and_its_polynomial(): diff --git a/tests/translate/test_problem.py b/tests/translate/test_problem.py index 6c850c304..3cc21cb94 100644 --- a/tests/translate/test_problem.py +++ b/tests/translate/test_problem.py @@ -367,24 +367,62 @@ def test_the_polarisation_taper_is_off_unless_asked_for(envelope_grid, gnlse): assert np.array_equal(tapered.grids.omega_window, envelope_grid.omega_window) -def test_a_stacked_initial_state_is_refused_by_name(envelope_grid, gnlse): - # A group of trajectories is a sequence of problems (SEP 47 section 6.7), never a - # leading axis of one problem's state. +@pytest.mark.parametrize( + ("overrides", "message"), + [ + ({"save_planes": [0.0]}, "must contain a positive position"), + ({"save_planes": []}, "must contain a positive position"), + ({"save_planes": [-0.5, 1.0]}, "save_planes must be positive"), + ({"dz_max": 1e-9, "dz_init": 1e-3}, "dz_min <= dz_init <= dz_max"), + ({"stretch": 0.5}, "stretch must be at least 1"), + ( + { + "save_planes": [0.37, 1.0], + "schedule": FixedSchedule.uniform(0.0, 1.0, 0.05, save_planes=[1.0]), + }, + "does not land on the save plane", + ), + ({"components": ("x", "y")}, "resolves no components"), + # A group of trajectories is a sequence of problems (SEP 47 section 6.7), + # never a leading axis of one problem's state. + ( + {"state": lambda start: np.stack([start, 2.0 * start])}, + r"\(n_modes, n_pol, n_omega\)", + ), + ( + {"state": lambda start: np.zeros(start.shape[-1], dtype=complex)}, + "field0 must have shape", + ), + ( + {"state": lambda start: np.zeros((1, 1, 7), dtype=complex)}, + "spectral bins, expected", + ), + ({"modes": lambda mode: [mode, mode]}, "modes but 2 were given"), + ( + { + "modes": lambda mode: [mode, mode], + "state": lambda start: np.stack([start[0], start[0]]), + }, + "without a transverse quadrature", + ), + ], +) +def test_assemble_rejects_a_bad_request(envelope_grid, gnlse, overrides, message): + """`state(start)` and `modes(mode)`, when given, replace the state and the modes.""" start = SechPulse(wavelength=WAVELENGTH, width=TAU0, peak_power=1.0).build( envelope_grid ) - with pytest.raises(TranslationError, match=r"\(n_modes, n_pol, n_omega\)"): - assemble( - envelope_grid, - gnlse.mode, - [gnlse.kerr], - np.stack([start, 2.0 * start]), - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[1.0], - dz_max=0.05, - dz_init=1e-4, - **GNLSE, - ) + request = { + "controller": PIController(rtol=1e-8, atol=1e-14), + "save_planes": [1.0], + "dz_max": 0.05, + "dz_init": 1e-4, + **GNLSE, + } | overrides + state = request.pop("state", lambda start: start)(start) + modes = request.pop("modes", lambda mode: mode)(gnlse.mode) + with pytest.raises(TranslationError, match=message): + assemble(envelope_grid, modes, [gnlse.kerr], state, **request) def test_a_noise_realisation_is_carried_in_the_canonical_layout(envelope_grid, gnlse): @@ -480,152 +518,231 @@ def corrupt_statistics(run_request, name, value): return run_request.for_run(stats=stats) -def test_validate_rejects_a_not_finite_array(soliton, soliton_request): - spoiled = np.array(soliton.grids.omega, copy=True) +def _with_nan(values): + spoiled = np.array(values, copy=True) spoiled[3] = np.nan - spoiled.setflags(write=False) - with pytest.raises(TranslationError, match="not finite"): - validate_run(corrupt(soliton, "grids", "omega", spoiled), soliton_request) - - -def test_validate_admits_infinite_energy_window_edges_but_not_nan( - soliton, soliton_request -): - # A half-open window may run to either end of the axis, as the manual shows. - windows = np.array([[-np.inf, 2.4e15], [2.4e15, np.inf]]) - spec = StatsSpec(names=("energy_window",), energy_windows=windows) - validate_run( - soliton, - corrupt_statistics(soliton_request, "energy_windows", spec.energy_windows), - ) - spoiled = np.array([[np.nan, 2.4e15]]) - spoiled.setflags(write=False) - with pytest.raises(TranslationError, match="not finite"): - validate_run( - soliton, corrupt_statistics(soliton_request, "energy_windows", spoiled) - ) - - -def test_validate_rejects_a_wrong_dtype(soliton, soliton_request): - spoiled = np.asarray(soliton.grids.omega, dtype=np.float32) - spoiled.setflags(write=False) - with pytest.raises(TranslationError, match="dtype"): - validate_run(corrupt(soliton, "grids", "omega", spoiled), soliton_request) + return frozen(spoiled) -def test_validate_rejects_a_non_contiguous_array(soliton, soliton_request): - spoiled = np.repeat(np.asarray(soliton.grids.omega), 2)[::2] +def _strided(values): + spoiled = np.repeat(np.asarray(values), 2)[::2] spoiled.setflags(write=False) assert not spoiled.flags.c_contiguous - with pytest.raises(TranslationError, match="C-contiguous"): - validate_run(corrupt(soliton, "grids", "omega", spoiled), soliton_request) + return spoiled -def test_validate_rejects_a_writeable_array(soliton, soliton_request): - with pytest.raises(TranslationError, match="writeable"): - validate_run( - corrupt( - soliton, "grids", "omega", np.array(soliton.grids.omega, copy=True) - ), - soliton_request, - ) +def _zeros_like_field(problem, group, name, shape): + return frozen(np.zeros(shape, dtype=getattr(getattr(problem, group), name).dtype)) -def test_validate_rejects_a_non_boolean_mask(soliton, soliton_request): - spoiled = np.asarray(soliton.grids.active_mask, dtype=np.float64) - spoiled.setflags(write=False) - with pytest.raises(TranslationError, match="must be Boolean"): - validate_run(corrupt(soliton, "grids", "active_mask", spoiled), soliton_request) +def _prefactor_over_half(problem): + # The same values over half the run: the shape is right and the span is not. + prefactor = cast("PiecewiseChebyshev", problem.responses.prefactor) + return dataclasses.replace(prefactor, breakpoints=frozen(np.array([0.0, 0.5]))) -@pytest.mark.parametrize( - ("group", "name", "shape", "message"), - [ - ("initial", "field0", (1, 1, 7), "field0 has shape"), - ("grids", "omega", (7,), "bins, expected"), - ], -) -def test_validate_rejects_an_inconsistent_shape( - soliton, group, name, shape, message, soliton_request -): - dtype = getattr(getattr(soliton, group), name).dtype - spoiled = np.zeros(shape, dtype=dtype) - spoiled.setflags(write=False) - with pytest.raises(TranslationError, match=message): - validate_run(corrupt(soliton, group, name, spoiled), soliton_request) +def _stale_raman_rates(problem, get): + # The decay-rate tables of a Raman kernel are tables along z like the density, and + # validate checks their span with the rest; a stale one from another run is refused + # by name, through the leaf that holds it. + stale = dataclasses.replace( + problem.responses.raman_coefficients, + decay_rates=(get("gradient").responses.density,), + ) + return (stale,) -def test_validate_rejects_a_phi_table_of_the_wrong_value_shape( - soliton, soliton_request -): - """Whichever representation carries the operator, its value is the state.""" - spoiled = np.zeros((1, 2, 1, 1, 1, 3), dtype=np.complex128) - spoiled.setflags(write=False) - with pytest.raises(TranslationError, match="linear carries values"): - validate_run( - corrupt(soliton, "linear", "phi_coefficients", spoiled), soliton_request - ) +def _raman_kernel_off_the_doubled_grid(problem, get): + # The convolution is built from n_to; a kernel of any other length would be + # convolved against the wrong axis rather than raise. + leaf = problem.responses.raman_coefficients + return (dataclasses.replace(leaf, undamped=np.zeros((1, problem.grids.n_to))),) + + +# Each row corrupts one field of a valid problem as a stale cache or a hand-built +# object would (`corrupt`), and names the refusal `validate_run` gives: the problem's +# fixture, the group and field, the spoiled value `value(problem, get)` (`get` fetches +# another fixture) and the exact match. +SPOILED = [ + ( + "soliton", + "grids", + "omega", + lambda p, get: _with_nan(p.grids.omega), + "not finite", + ), + ( + "soliton", + "grids", + "omega", + lambda p, get: frozen(np.asarray(p.grids.omega, dtype=np.float32)), + "dtype", + ), + ( + "soliton", + "grids", + "omega", + lambda p, get: _strided(p.grids.omega), + "C-contiguous", + ), + ( + "soliton", + "grids", + "omega", + lambda p, get: np.array(p.grids.omega, copy=True), + "writeable", + ), + ( + "soliton", + "grids", + "active_mask", + lambda p, get: frozen(np.asarray(p.grids.active_mask, dtype=np.float64)), + "must be Boolean", + ), + ( + "soliton", + "initial", + "field0", + lambda p, get: _zeros_like_field(p, "initial", "field0", (1, 1, 7)), + "field0 has shape", + ), + ( + "soliton", + "grids", + "omega", + lambda p, get: _zeros_like_field(p, "grids", "omega", (7,)), + "bins, expected", + ), + # Whichever representation carries the operator, its value is the state. + ( + "soliton", + "linear", + "phi_coefficients", + lambda p, get: frozen(np.zeros((1, 2, 1, 1, 1, 3), dtype=np.complex128)), + "linear carries values", + ), + ( + "soliton", + "transform", + "synthesis", + lambda p, get: frozen(np.zeros((1, 2))), + "transform carries", + ), + ( + "gradient", + "responses", + "temporal_absorber", + lambda p, get: frozen(np.zeros(7)), + "temporal_absorber has", + ), + ( + "soliton", + "linear", + "phi_breakpoints", + lambda p, get: frozen(np.array([0.0, 2.0, 1.0])), + "strictly increasing", + ), + ( + "soliton", + "linear", + "phi_breakpoints", + lambda p, get: frozen(np.array([0.0, 0.5])), + "does not contain the run", + ), + ( + "gradient", + "linear", + "hard_kinks", + lambda p, get: frozen(np.array([0.123])), + "is not an interval edge", + ), + ( + "soliton", + "responses", + "density", + lambda p, get: get("gradient").responses.density, + "every table along z must span", + ), + ( + "raman_soliton", + "responses", + "raman_terms", + _stale_raman_rates, + r"raman_terms\[0\]\.decay_rates\[0\] covers", + ), + ( + "raman_soliton", + "responses", + "raman_terms", + _raman_kernel_off_the_doubled_grid, + "on the doubled fine grid", + ), + ( + "soliton", + "responses", + "prefactor", + lambda p, get: dataclasses.replace( + p.responses.prefactor, + coefficients=p.responses.prefactor.coefficients[..., :7], + ), + "prefactor carries values", + ), + ( + "soliton", + "responses", + "prefactor", + lambda p, get: _prefactor_over_half(p), + r"responses\.prefactor covers", + ), + # A gradient's prefactor varies, so no array may stand in for it. + ( + "gradient", + "responses", + "prefactor_constant", + lambda p, get: frozen(prefactor_at(p.responses, 0.0)), + "fast path is only for a prefactor", + ), + ( + "soliton", + "responses", + "prefactor_constant", + lambda p, get: frozen(2.0 * prefactor_at(p.responses, 0.0)), + "does not agree with the prefactor", + ), + # The carrier is present exactly when the term that needs it is compiled. + ( + "soliton", + "grids", + "carrier_2w0", + lambda p, get: frozen(np.ones(p.grids.n_to, dtype=np.complex128)), + "carrier_2w0 must be present", + ), +] + + +@pytest.mark.parametrize(("which", "group", "name", "value", "message"), SPOILED) +def test_validate_rejects_a_spoiled_field(request, which, group, name, value, message): + problem = request.getfixturevalue(which) + spoiled = corrupt(problem, group, name, value(problem, request.getfixturevalue)) + with pytest.raises(TranslationError, match=message): + validate_run(spoiled, request.getfixturevalue(f"{which}_request")) -def test_validate_rejects_a_transform_with_the_wrong_mode_count( +def test_validate_admits_infinite_energy_window_edges_but_not_nan( soliton, soliton_request ): - spoiled = np.zeros((1, 2)) - spoiled.setflags(write=False) - with pytest.raises(TranslationError, match="transform carries"): - validate_run( - corrupt(soliton, "transform", "synthesis", spoiled), soliton_request - ) - - -def test_validate_rejects_a_temporal_rate_of_the_wrong_length( - gradient, gradient_request -): - spoiled = np.zeros(7) - spoiled.setflags(write=False) - with pytest.raises(TranslationError, match="temporal_absorber has"): - validate_run( - corrupt(gradient, "responses", "temporal_absorber", spoiled), - gradient_request, - ) - - -def test_validate_rejects_breakpoints_that_do_not_increase(soliton, soliton_request): - spoiled = np.array([0.0, 2.0, 1.0]) - spoiled.setflags(write=False) - with pytest.raises(TranslationError, match="strictly increasing"): - validate_run( - corrupt(soliton, "linear", "phi_breakpoints", spoiled), soliton_request - ) - - -def test_validate_rejects_a_table_that_does_not_cover_the_run(soliton, soliton_request): - spoiled = np.array([0.0, 0.5]) - spoiled.setflags(write=False) - with pytest.raises(TranslationError, match="does not contain the run"): - validate_run( - corrupt(soliton, "linear", "phi_breakpoints", spoiled), soliton_request - ) - - -def test_validate_rejects_a_kink_that_is_not_an_interval_edge( - gradient, gradient_request -): - spoiled = np.array([0.123]) + # A half-open window may run to either end of the axis, as the manual shows. + windows = np.array([[-np.inf, 2.4e15], [2.4e15, np.inf]]) + spec = StatsSpec(names=("energy_window",), energy_windows=windows) + validate_run( + soliton, + corrupt_statistics(soliton_request, "energy_windows", spec.energy_windows), + ) + spoiled = np.array([[np.nan, 2.4e15]]) spoiled.setflags(write=False) - with pytest.raises(TranslationError, match="is not an interval edge"): - validate_run( - corrupt(gradient, "linear", "hard_kinks", spoiled), gradient_request - ) - - -def test_validate_rejects_a_profile_table_over_a_different_range( - soliton, gradient, soliton_request -): - with pytest.raises(TranslationError, match="every table along z must span"): + with pytest.raises(TranslationError, match="not finite"): validate_run( - corrupt(soliton, "responses", "density", gradient.responses.density), - soliton_request, + soliton, corrupt_statistics(soliton_request, "energy_windows", spoiled) ) @@ -648,26 +765,6 @@ def test_validate_still_rejects_a_negative_density(gradient, density, gradient_r validate_run(corrupt(gradient, "responses", "density", table), gradient_request) -def test_validate_walks_the_raman_rate_tables_too( - raman_soliton, gradient, raman_soliton_request -): - # The decay-rate tables of a Raman kernel are tables along z like the density, and - # validate checks their span with the rest; a stale one from another run is refused - # by name, through the leaf that holds it. - stale = dataclasses.replace( - raman_soliton.responses.raman_coefficients, - decay_rates=(gradient.responses.density,), - ) - with pytest.raises( - TranslationError, - match=r"raman_terms\[0\]\.decay_rates\[0\] covers", - ): - validate_run( - corrupt(raman_soliton, "responses", "raman_terms", (stale,)), - raman_soliton_request, - ) - - @pytest.fixture(scope="module") def raman_soliton_translation(envelope_grid, gnlse): """The soliton problem with a fused-silica Raman response beside its Kerr term.""" @@ -693,20 +790,6 @@ def test_validate_accepts_the_compiled_raman_rows(raman_soliton, raman_soliton_r assert validate_run(raman_soliton, raman_soliton_request) is None -def test_validate_rejects_a_kernel_that_is_not_on_the_doubled_grid( - raman_soliton, raman_soliton_request -): - # The convolution is built from n_to; a kernel of any other length would be - # convolved against the wrong axis rather than raise. - leaf = raman_soliton.responses.raman_coefficients - stale = dataclasses.replace(leaf, undamped=np.zeros((1, raman_soliton.grids.n_to))) - with pytest.raises(TranslationError, match="on the doubled fine grid"): - validate_run( - corrupt(raman_soliton, "responses", "raman_terms", (stale,)), - raman_soliton_request, - ) - - def test_the_leaf_refuses_a_kernel_with_no_table_for_a_row(raman_soliton): leaf = raman_soliton.responses.raman_coefficients with pytest.raises(TranslationError, match="one rate per row"): @@ -735,25 +818,6 @@ def test_validate_rejects_a_raman_kernel_on_a_vector_problem( validate_run(stale, raman_soliton_request) -def test_validate_rejects_a_schedule_that_misses_a_save_plane(envelope_grid, gnlse): - start = SechPulse(wavelength=WAVELENGTH, width=TAU0, peak_power=1.0).build( - envelope_grid - ) - with pytest.raises(TranslationError, match="does not land on the save plane"): - assemble( - envelope_grid, - gnlse.mode, - [gnlse.kerr], - start, - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[0.37, 1.0], - dz_max=0.05, - dz_init=1e-4, - schedule=FixedSchedule.uniform(0.0, 1.0, 0.05, save_planes=[1.0]), - **GNLSE, - ) - - def test_validate_rejects_a_schedule_that_misses_a_hard_kink(field_grid, capillary): start = GaussianPulse(wavelength=800e-9, fwhm=10e-15, energy=1e-6).build(field_grid) with ( @@ -776,56 +840,6 @@ def test_validate_rejects_a_schedule_that_misses_a_hard_kink(field_grid, capilla ) -def test_validate_rejects_a_prefactor_of_the_wrong_value_shape( - soliton, soliton_request -): - spoiled = dataclasses.replace( - soliton.responses.prefactor, - coefficients=soliton.responses.prefactor.coefficients[..., :7], - ) - with pytest.raises(TranslationError, match="prefactor carries values"): - validate_run( - corrupt(soliton, "responses", "prefactor", spoiled), soliton_request - ) - - -def test_validate_rejects_a_prefactor_table_over_a_different_range( - soliton, soliton_request -): - # The same values over half the run: the shape is right and the span is not. - edges = np.array([0.0, 0.5]) - edges.setflags(write=False) - short = dataclasses.replace( - cast("PiecewiseChebyshev", soliton.responses.prefactor), breakpoints=edges - ) - with pytest.raises(TranslationError, match=r"responses\.prefactor covers"): - validate_run(corrupt(soliton, "responses", "prefactor", short), soliton_request) - - -def test_validate_rejects_a_constant_prefactor_beside_a_varying_prefactor( - gradient, gradient_request -): - """A gradient's prefactor varies, so no array may stand in for it.""" - constant = np.ascontiguousarray(prefactor_at(gradient.responses, 0.0)) - constant.setflags(write=False) - with pytest.raises(TranslationError, match="fast path is only for a prefactor"): - validate_run( - corrupt(gradient, "responses", "prefactor_constant", constant), - gradient_request, - ) - - -def test_validate_rejects_a_constant_prefactor_that_disagrees_with_the_rest( - soliton, soliton_request -): - wrong = np.ascontiguousarray(2.0 * prefactor_at(soliton.responses, 0.0)) - wrong.setflags(write=False) - with pytest.raises(TranslationError, match="does not agree with the prefactor"): - validate_run( - corrupt(soliton, "responses", "prefactor_constant", wrong), soliton_request - ) - - def test_validate_allows_a_fixed_fibre_to_go_without_the_fast_path( soliton, soliton_request ): @@ -852,96 +866,6 @@ def test_the_problem_cannot_be_mutated(soliton): # --------------------------------------------------------------- assemble rejects -@pytest.mark.parametrize( - ("overrides", "message"), - [ - ({"save_planes": [0.0]}, "must contain a positive position"), - ({"save_planes": []}, "must contain a positive position"), - ({"dz_max": 1e-9, "dz_init": 1e-3}, "dz_min <= dz_init <= dz_max"), - ({"stretch": 0.5}, "stretch must be at least 1"), - ], -) -def test_assemble_rejects_a_bad_request(envelope_grid, gnlse, overrides, message): - start = SechPulse(wavelength=WAVELENGTH, width=TAU0, peak_power=1.0).build( - envelope_grid - ) - request = { - "controller": PIController(rtol=1e-8, atol=1e-14), - "save_planes": [1.0], - "dz_max": 0.05, - "dz_init": 1e-4, - **GNLSE, - } | overrides - with pytest.raises(TranslationError, match=message): - assemble(envelope_grid, gnlse.mode, [gnlse.kerr], start, **request) - - -def test_assemble_rejects_a_state_of_the_wrong_rank(envelope_grid, gnlse): - with pytest.raises(TranslationError, match="field0 must have shape"): - assemble( - envelope_grid, - gnlse.mode, - [gnlse.kerr], - np.zeros(envelope_grid.n_omega, dtype=complex), - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[1.0], - dz_max=0.05, - dz_init=1e-4, - **GNLSE, - ) - - -def test_assemble_rejects_a_state_of_the_wrong_width(envelope_grid, gnlse): - with pytest.raises(TranslationError, match="spectral bins, expected"): - assemble( - envelope_grid, - gnlse.mode, - [gnlse.kerr], - np.zeros((1, 1, 7), dtype=complex), - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[1.0], - dz_max=0.05, - dz_init=1e-4, - **GNLSE, - ) - - -def test_assemble_rejects_a_mode_set_the_state_does_not_match(envelope_grid, gnlse): - start = SechPulse(wavelength=WAVELENGTH, width=TAU0, peak_power=1.0).build( - envelope_grid - ) - with pytest.raises(TranslationError, match="modes but 2 were given"): - assemble( - envelope_grid, - [gnlse.mode, gnlse.mode], - [gnlse.kerr], - start, - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[1.0], - dz_max=0.05, - dz_init=1e-4, - **GNLSE, - ) - - -def test_assemble_rejects_a_mode_set_without_a_quadrature(envelope_grid, gnlse): - start = SechPulse(wavelength=WAVELENGTH, width=TAU0, peak_power=1.0).build( - envelope_grid - ) - with pytest.raises(TranslationError, match="without a transverse quadrature"): - assemble( - envelope_grid, - [gnlse.mode, gnlse.mode], - [gnlse.kerr], - np.stack([start[0], start[0]]), - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[1.0], - dz_max=0.05, - dz_init=1e-4, - **GNLSE, - ) - - # --------------------------------------------------------------------------- the groups @@ -1204,24 +1128,6 @@ def test_a_kernel_problem_can_be_built_by_hand_from_its_groups( assert math.isclose(rebuilt.linear.z_span[1], 1.05) -def test_a_save_plane_at_or_below_zero_is_refused(envelope_grid, gnlse): - start = SechPulse(wavelength=WAVELENGTH, width=TAU0, peak_power=1.0).build( - envelope_grid - ) - with pytest.raises(TranslationError, match="save_planes must be positive"): - assemble( - envelope_grid, - gnlse.mode, - [gnlse.kerr], - start, - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[-0.5, 1.0], - dz_max=0.05, - dz_init=1e-4, - **GNLSE, - ) - - def test_a_multimode_problem_assembles_with_a_quadrature(field_grid): """A multimode problem assembles with a quadrature; the contract carries the set.""" modes = [MarcatiliMode(125e-6, "He", 1.0, m=m, cladding=1.45) for m in (1, 2, 3)] @@ -1324,25 +1230,6 @@ def test_inferred_vector_rows_require_an_explicit_product_choice(field_grid): ) -def test_components_without_a_quadrature_are_refused(envelope_grid, gnlse): - start = SechPulse(wavelength=WAVELENGTH, width=TAU0, peak_power=1.0).build( - envelope_grid - ) - with pytest.raises(TranslationError, match="resolves no components"): - assemble( - envelope_grid, - gnlse.mode, - [gnlse.kerr], - start, - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[1.0], - dz_max=0.05, - dz_init=1e-4, - components=("x", "y"), - **GNLSE, - ) - - @pytest.mark.parametrize("bad", [(), ("z",), ("x", "r")]) def test_components_outside_the_transverse_pair_are_refused(field_grid, bad): modes = [MarcatiliMode(125e-6, "He", 1.0, cladding=1.45)] @@ -1498,14 +1385,6 @@ def test_validate_rejects_a_transform_and_a_state_that_both_carry_the_components validate_run(doubled, run_request) -def test_validate_rejects_a_carrier_without_a_harmonic_term(soliton, soliton_request): - """The carrier is present exactly when the term that needs it is compiled.""" - stray = np.ones(soliton.grids.n_to, dtype=np.complex128) - stray.setflags(write=False) - with pytest.raises(TranslationError, match="carrier_2w0 must be present"): - validate_run(corrupt(soliton, "grids", "carrier_2w0", stray), soliton_request) - - def test_validate_rejects_a_harmonic_term_without_its_carrier(): """A third-harmonic envelope problem carries the carrier, and needs it.""" grid = EnvelopeGrid.from_limits(1.0, WAVELENGTH, (500e-9, 2e-6), 1e-12, thg=True) From 99614426d12071c2522630384e06e2098c4ae7d2 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:33:30 +0000 Subject: [PATCH 09/13] Keep one copy of the dispersive cases' run and disagreement backends/dispersive_route_cases.py repeated dispersive_cases.py's `run` (open a backend, march to the last plane with no statistics, return the field and the run's summary) and `disagreement` (relative L2 difference, asserting a nonzero reference) token for token. The two modules that imported them from the route cases now import the dispersive cases' copy. Counts (lines, tests, assert, assert_*), before -> after: dispersive_route_cases.py 352->318, helper, assert 2->1 test_native_dispersive_routes.py 626->625, 103->103, 36->36, 21->21 test_native_dispersive_pathological.py 170->169, 6->6, 10->10, 3->3 The one assert dropped is `assert scale > 0` of the deleted copy; the same statement in dispersive_cases.disagreement runs on every call that ran it. 109 tests of the two modules pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/backends/dispersive_route_cases.py | 34 ------------------- .../test_native_dispersive_pathological.py | 5 ++- .../backends/test_native_dispersive_routes.py | 3 +- 3 files changed, 3 insertions(+), 39 deletions(-) diff --git a/tests/backends/dispersive_route_cases.py b/tests/backends/dispersive_route_cases.py index b7d8bc81a..7d7cadd28 100644 --- a/tests/backends/dispersive_route_cases.py +++ b/tests/backends/dispersive_route_cases.py @@ -29,8 +29,6 @@ from legacy_geometry import LEGACY_GRID, bare_absorber from modal_provider_cases import GENERAL_Z_END, WAVELENGTH, general_grid from sessions.runs import native_source -from sessions.runs import run as session_run -from sessions.runs import summary as run_summary from solprop.backends.numpy_ref.passes import apply_hard_mask from solprop.backends.session import ExecutionOptions from solprop.boundaries import absorber @@ -215,38 +213,6 @@ def source( backend.close() -def run( - backend_class: type, - problem: PropagationProblem, - run_request, - grid: TimeGrid, - **options: object, -) -> tuple[np.ndarray, Any]: - """Run the session to the last save plane; return the field and the run's summary. - - The summary spans the run, every plane's attempts together - (:func:`sessions.runs.summary`). - """ - backend = backend_class(problem, run_request, grid=grid, **options) - try: - # The step driver's march computed no statistic, which a case's profiles - # would be needed for. - result = session_run( - backend, problem, backend.request.for_run(stats=StatsSpec()) - ) - return result.fields[-1], run_summary(result) - finally: - backend.close() - - -def disagreement(ours: np.ndarray, theirs: np.ndarray) -> float: - """Return the relative L2 difference of two arrays of the same size.""" - ours, theirs = np.ravel(ours), np.ravel(theirs) - scale = float(np.linalg.norm(theirs)) - assert scale > 0 - return float(np.linalg.norm(ours - theirs) / scale) - - def evaluation_bound(problem: PropagationProblem) -> float: """Bound one evaluation's rounding on a spatial or general route (the docstring).""" leaf = problem.responses.dispersive_kerr diff --git a/tests/backends/test_native_dispersive_pathological.py b/tests/backends/test_native_dispersive_pathological.py index abfd2c59b..e9f63eb55 100644 --- a/tests/backends/test_native_dispersive_pathological.py +++ b/tests/backends/test_native_dispersive_pathological.py @@ -26,15 +26,14 @@ import numpy as np import pytest -from backends.dispersive_cases import LENGTH, POLICIES, STEPS +from backends.dispersive_cases import LENGTH, POLICIES, STEPS, disagreement +from backends.dispersive_cases import run as march from backends.dispersive_route_cases import ( ARGON_FILL, - disagreement, evaluation_bound, general_problem, strand, ) -from backends.dispersive_route_cases import run as march from backends.dispersive_route_cases import source as launch_source from bounds import assert_within, step_evaluations from sessions.runs import native_source diff --git a/tests/backends/test_native_dispersive_routes.py b/tests/backends/test_native_dispersive_routes.py index af37a53a0..2bf6b8aca 100644 --- a/tests/backends/test_native_dispersive_routes.py +++ b/tests/backends/test_native_dispersive_routes.py @@ -33,6 +33,7 @@ import pytest import flow_parity +from backends.dispersive_cases import disagreement, run from backends.dispersive_route_cases import ( ARGON, ARGON_FILL, @@ -43,13 +44,11 @@ HELIUM, STEPS, STRANDS, - disagreement, free_grid, free_problem, general_problem, planar_problem, raman, - run, source, strand, ) From e520691acaf3894eb3c6458e8e8044321aec0de2 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:36:20 +0000 Subject: [PATCH 10/13] Run a recipe's written script through builders.run_python Five recipe tests ran the script they wrote in the same eight lines: this interpreter, the script's path, captured text, cwd the script's folder, and an assert of a clean exit showing standard error. That is now builders.run_python(path), which asserts the exit status itself. Counts (lines, tests, assert), before -> after: recipe/test_examples.py 356->349, 81->81, 8->7 recipe/test_free_space.py 664->656, 40->40, 70->69 recipe/test_pins.py 424->409, 41->41, 44->42 recipe/test_waveguide.py 267->259, 10->10, 17->16 builders.py 48->68, +1 assert Each assert dropped is the `returncode == 0` check, now the one statement in run_python that every former site executes. 104 tests of the four modules pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/builders.py | 22 +++++++++++++++++++++- tests/recipe/test_examples.py | 11 ++--------- tests/recipe/test_free_space.py | 12 ++---------- tests/recipe/test_pins.py | 21 +++------------------ tests/recipe/test_waveguide.py | 12 ++---------- 5 files changed, 30 insertions(+), 48 deletions(-) diff --git a/tests/builders.py b/tests/builders.py index b83d12d9b..59593360f 100644 --- a/tests/builders.py +++ b/tests/builders.py @@ -9,6 +9,9 @@ pinned, when it was migrated, by the configuration hash of what the old copies built. """ +import subprocess +import sys +from pathlib import Path from typing import Any import numpy as np @@ -18,7 +21,7 @@ from solprop.translate.problem import PropagationProblem from solprop.translate.run_request import RunRequest -__all__ = ["launch_derivative", "numpy_ref_launch_derivative"] +__all__ = ["launch_derivative", "numpy_ref_launch_derivative", "run_python"] def launch_derivative(backend: NumpyRefBackend, problem: PropagationProblem) -> Any: @@ -46,3 +49,20 @@ def numpy_ref_launch_derivative( return launch_derivative(backend, problem) finally: backend.close() + + +def run_python(path: Path) -> "subprocess.CompletedProcess[str]": + """Run a written script with this interpreter in its own folder, as a person would. + + A fresh process, so without the tests' type hook; asserts it exits cleanly, showing + its standard error if not, and returns the completed process. + """ + result = subprocess.run( + [sys.executable, str(path)], + capture_output=True, + text=True, + check=False, + cwd=path.parent, + ) + assert result.returncode == 0, result.stderr + return result diff --git a/tests/recipe/test_examples.py b/tests/recipe/test_examples.py index ae69d38cc..fc36c8658 100644 --- a/tests/recipe/test_examples.py +++ b/tests/recipe/test_examples.py @@ -28,7 +28,6 @@ import logging import re import runpy -import subprocess import sys import textwrap import warnings @@ -42,6 +41,7 @@ import numpy.random.bit_generator import pytest +from builders import run_python from solprop.driver.simulation import Simulation from solprop.recipe import Recipe @@ -345,12 +345,5 @@ def test_an_example_s_python_export_builds_the_same_run(name, tmp_path, monkeypa recipe = Recipe.example(name) path = tmp_path / f"{name}.py" path.write_text(_PROBE.format(entropy=ENTROPY) + recipe.to_python()) - result = subprocess.run( - [sys.executable, str(path)], - capture_output=True, - text=True, - check=False, - cwd=tmp_path, - ) - assert result.returncode == 0, result.stderr + result = run_python(path) assert json.loads(result.stdout.splitlines()[-1]) == record(built(recipe)) diff --git a/tests/recipe/test_free_space.py b/tests/recipe/test_free_space.py index 9ee2def0f..637917073 100644 --- a/tests/recipe/test_free_space.py +++ b/tests/recipe/test_free_space.py @@ -13,14 +13,13 @@ """ import json -import subprocess -import sys import textwrap import warnings import numpy as np import pytest +from builders import run_python from recipe.test_examples import _PROBE, ENTROPY, record from solprop.boundaries import SpatialAbsorber, absorber from solprop.capabilities import route @@ -521,14 +520,7 @@ def test_the_python_export_builds_the_same_run(name, tmp_path, monkeypatch): script = recipe.to_python() path = tmp_path / f"{name}.py" path.write_text(_PROBE.format(entropy=ENTROPY) + script, encoding="utf-8") - result = subprocess.run( - [sys.executable, str(path)], - capture_output=True, - text=True, - check=False, - cwd=tmp_path, - ) - assert result.returncode == 0, result.stderr + result = run_python(path) with warnings.catch_warnings(): warnings.simplefilter("ignore") expected = record(recipe.build()) diff --git a/tests/recipe/test_pins.py b/tests/recipe/test_pins.py index ed90b8e0d..ce68bcf20 100644 --- a/tests/recipe/test_pins.py +++ b/tests/recipe/test_pins.py @@ -4,14 +4,13 @@ """Pins: recipe values set from a design target (SEP 41, S1 and S7).""" -import subprocess -import sys import warnings from typing import cast import numpy as np import pytest +from builders import run_python from solprop.modes import MarcatiliMode from solprop.modes.base import beta2 from solprop.recipe import Recipe, RecipeError @@ -254,14 +253,7 @@ def test_the_export_solves_the_pins_before_the_route_s_call(tmp_path): path = tmp_path / "pinned.py" path.write_text(_PROBE + script) # A subprocess, as a person runs the script: without the tests' type hook. - result = subprocess.run( - [sys.executable, str(path)], - capture_output=True, - text=True, - check=False, - cwd=tmp_path, - ) - assert result.returncode == 0, result.stderr + result = run_python(path) with warnings.catch_warnings(): warnings.simplefilter("ignore") expected = quiet_build(recipe).metadata().configuration_hash() @@ -414,11 +406,4 @@ def test_an_rdw_pin_with_its_pulse_exports_its_solver_call(tmp_path): assert "RDW(keywords['wavelength'], 2e-07, peak_power=1000000000.0" in script path = tmp_path / "rdw.py" path.write_text(_PROBE + script) - result = subprocess.run( - [sys.executable, str(path)], - capture_output=True, - text=True, - check=False, - cwd=tmp_path, - ) - assert result.returncode == 0, result.stderr + run_python(path) diff --git a/tests/recipe/test_waveguide.py b/tests/recipe/test_waveguide.py index 231460e6e..9ea8d19ad 100644 --- a/tests/recipe/test_waveguide.py +++ b/tests/recipe/test_waveguide.py @@ -12,12 +12,11 @@ """ import json -import subprocess -import sys import textwrap import pytest +from builders import run_python from solprop.driver import Simulation from solprop.modes import MarcatiliMode, ModeCollection, RectMode from solprop.recipe import Recipe, RecipeError, parameters, provenance @@ -256,12 +255,5 @@ def test_the_python_export_builds_the_same_run(name, tmp_path): assert "prop_waveguide(" in script path = tmp_path / f"{name}.py" path.write_text(_PROBE + script, encoding="utf-8") - result = subprocess.run( - [sys.executable, str(path)], - capture_output=True, - text=True, - check=False, - cwd=tmp_path, - ) - assert result.returncode == 0, result.stderr + result = run_python(path) assert json.loads(result.stdout.splitlines()[-1]) == _hash(recipe.build()) From 73d4572dd32c069e489aa94ee2015a9960accbc2 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:40:17 +0000 Subject: [PATCH 11/13] Parametrise near-duplicate tests and share their repeated scaffolds Same-file near-duplicates (shingle overlap >= 0.55) merged where the result is shorter and as strong; every case keeps its inputs, bound and assertions. - output/test_checkpoints.py: the read and appended disagreeing-closing- record tests are one test over [read, appended]; a local stopped() writes the save-then-fail-with-checkpoint file six tests built inline. 669->637 lines, tests 45->45, assert 61->61, raises 16->15, match= 16->15 (the two "no matching execution outcome" sites are one site run for both cases). - driver/test_restart_record.py: warned_once_and_reset() holds the "one warning, history reset for " tail of five tests; its three asserts run for each of them. 420->403, tests 19->19, assert 73->61. - driver/test_plasma_band_propagation.py: the two reference-statistics refusals are one test over (statistic, match). 321->306, tests 13->13, raises 7->6, match= 7->6. - test_pulses.py: the clean time-record arrivals are three rows of the measured-record table (disturbance 0.0, so the record is bitwise the same; bound 5e-10 kept); one assert runs for all seven cases. 1321->1317, tests 161->161, assert 57->56. - driver/test_estimate.py: the low-storage soliton two tests built verbatim is low_storage_soliton(backend). 316->301, tests 13->13. - test_monitor.py: the two split-guard verdicts are one test over the share the split left (1.0, 1e-15). 1671->1667, tests 93->93, raises 19->18, match= 19->18. Collected tests are unchanged per module; every dropped assert or match= site is one shared statement executed for every former case. No test that writes records changed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/driver/test_estimate.py | 69 ++++++---------- tests/driver/test_plasma_band_propagation.py | 35 +++----- tests/driver/test_restart_record.py | 55 +++++-------- tests/output/test_checkpoints.py | 86 ++++++-------------- tests/test_monitor.py | 32 ++++---- tests/test_pulses.py | 34 ++++---- 6 files changed, 112 insertions(+), 199 deletions(-) diff --git a/tests/driver/test_estimate.py b/tests/driver/test_estimate.py index a6d3ae5d5..487b6c581 100644 --- a/tests/driver/test_estimate.py +++ b/tests/driver/test_estimate.py @@ -33,6 +33,31 @@ def _built(name, backend): return recipe.build() +def low_storage_soliton(backend): + """Return an N = 1 soliton over 2 cm in eight fixed low-storage steps.""" + length = 0.02 + schedule = FixedSchedule.uniform(0.0, length, length / 8, save_planes=[length / 2]) + return Simulation.from_gnlse( + 0.11, + length, + [0.0, 0.0, -11.83e-27], + wavelength=835e-9, + wavelength_limits=(500e-9, 2e-6), + trange=1e-12, + width=100e-15, + peak_power=9.8, + shape="sech", + save_planes=[length / 2, length], + schedule=schedule, + integrator=LowStorageRungeKutta(), + backend=backend, + dz_max=schedule.max_step, + dz_init=schedule.max_step, + absorber=False, + noise=None, + ) + + @pytest.mark.parametrize( "backend", [ @@ -109,27 +134,7 @@ def test_a_low_storage_run_takes_four_calls_a_step(): ) def test_a_low_storage_estimate_times_the_march_s_own_step(backend, monkeypatch): # #492: the Runge-Kutta trial step isn't this march's; on native it has no views. - length = 0.02 - schedule = FixedSchedule.uniform(0.0, length, length / 8, save_planes=[length / 2]) - simulation = Simulation.from_gnlse( - 0.11, - length, - [0.0, 0.0, -11.83e-27], - wavelength=835e-9, - wavelength_limits=(500e-9, 2e-6), - trange=1e-12, - width=100e-15, - peak_power=9.8, - shape="sech", - save_planes=[length / 2, length], - schedule=schedule, - integrator=LowStorageRungeKutta(), - backend=backend, - dz_max=schedule.max_step, - dz_init=schedule.max_step, - absorber=False, - noise=None, - ) + simulation = low_storage_soliton(backend) taken = [] build = estimate_module._timed_step @@ -285,27 +290,7 @@ def test_a_timing_probe_commits_nothing_and_reads_back_its_trial(backend): @pytest.mark.parametrize("backend", BACKENDS) def test_a_low_storage_probe_has_no_trial_field(backend): - length = 0.02 - schedule = FixedSchedule.uniform(0.0, length, length / 8, save_planes=[length / 2]) - simulation = Simulation.from_gnlse( - 0.11, - length, - [0.0, 0.0, -11.83e-27], - wavelength=835e-9, - wavelength_limits=(500e-9, 2e-6), - trange=1e-12, - width=100e-15, - peak_power=9.8, - shape="sech", - save_planes=[length / 2, length], - schedule=schedule, - integrator=LowStorageRungeKutta(), - backend=backend, - dz_max=schedule.max_step, - dz_init=schedule.max_step, - absorber=False, - noise=None, - ) + simulation = low_storage_soliton(backend) problem, probed = _backend(simulation) try: probe = probed.timing_probe(Start.entrance(problem)) diff --git a/tests/driver/test_plasma_band_propagation.py b/tests/driver/test_plasma_band_propagation.py index 21b62fbb6..b46b13521 100644 --- a/tests/driver/test_plasma_band_propagation.py +++ b/tests/driver/test_plasma_band_propagation.py @@ -283,29 +283,16 @@ def test_a_band_rule_needs_field_plasma_channels(): dataclasses.replace(problem.responses, plasma_integral=rule) -def test_the_reference_s_diagnostics_refuse_a_problem_with_no_plasma_column(): - """The reference's own check, for a caller that asks its statistics directly.""" - simulation = build( - plasma=False, backend="numpy_ref", stats=StatsSpec(names=("plasma_undershoot",)) - ) - problem = simulation.translate() - backend = select( - "numpy_ref", problem, simulation._run_request(), grid=simulation.grid - ) - try: - state = simulation._field0[np.newaxis] - with pytest.raises(BackendError, match="carries none"): - cast("NumpyRefBackend", backend)._backend_statistics( - ("plasma_undershoot",), state - ) - finally: - backend.close() - - -def test_the_reference_s_ionisation_refuses_a_problem_with_no_plasma(): +@pytest.mark.parametrize( + ("name", "message"), + [("plasma_undershoot", "carries none"), ("electron_density", "declares none")], +) +def test_the_reference_s_plasma_statistics_refuse_a_problem_with_no_plasma( + name, message +): """The reference's own check, for a caller that asks its statistics directly.""" simulation = build( - plasma=False, backend="numpy_ref", stats=StatsSpec(names=("electron_density",)) + plasma=False, backend="numpy_ref", stats=StatsSpec(names=(name,)) ) problem = simulation.translate() backend = select( @@ -313,9 +300,7 @@ def test_the_reference_s_ionisation_refuses_a_problem_with_no_plasma(): ) try: state = simulation._field0[np.newaxis] - with pytest.raises(BackendError, match="declares none"): - cast("NumpyRefBackend", backend)._backend_statistics( - ("electron_density",), state - ) + with pytest.raises(BackendError, match=message): + cast("NumpyRefBackend", backend)._backend_statistics((name,), state) finally: backend.close() diff --git a/tests/driver/test_restart_record.py b/tests/driver/test_restart_record.py index 911b3510c..e7b7bf838 100644 --- a/tests/driver/test_restart_record.py +++ b/tests/driver/test_restart_record.py @@ -65,6 +65,15 @@ def resumed(build, path) -> list[warnings.WarningMessage]: ] +def warned_once_and_reset(build, path, text, reason) -> None: + """Resume, warned once with `text`; the history is recorded reset for `reason`.""" + caught = resumed(build, path) + assert len(caught) == 1 + assert text in str(caught[0].message) + restoration = restart(path)["restoration"] + assert (restoration["state"], restoration["reason"]) == ("reset", reason) + + def interrupted(build, path) -> float: """Run into `path`, stop after two planes and return where it stopped.""" run_until(build(), path, after=2) @@ -140,13 +149,8 @@ def test_a_history_over_the_automatic_limit_warns_once_on_resume( assert retention["reason"] == "automatic_size_limit" assert retention["z"] == z assert retention["limit"] == 1 - caught = resumed(build, path) - assert len(caught) == 1 - assert "resume_history=True keeps it" in str(caught[0].message) - restoration = restart(path)["restoration"] - assert (restoration["state"], restoration["reason"]) == ( - "reset", - "automatic_size_limit", + warned_once_and_reset( + build, path, "resume_history=True keeps it", "automatic_size_limit" ) @@ -156,14 +160,7 @@ def test_a_kept_history_that_cannot_be_read_back_warns_once(build_simulation, tm interrupted(build, path) with h5py.File(path, "r+") as file: del file["march_snapshot"] - caught = resumed(build, path) - assert len(caught) == 1 - assert "cannot be read back" in str(caught[0].message) - restoration = restart(path)["restoration"] - assert (restoration["state"], restoration["reason"]) == ( - "reset", - "unavailable_history", - ) + warned_once_and_reset(build, path, "cannot be read back", "unavailable_history") def test_a_history_this_backend_cannot_install_is_recorded_as_incompatible( @@ -175,13 +172,8 @@ def test_a_history_this_backend_cannot_install_is_recorded_as_incompatible( monkeypatch.setattr( HostDriver, "restore_march", lambda self, snapshot: "refused by the test" ) - caught = resumed(build, path) - assert len(caught) == 1 - assert "refused by the test" in str(caught[0].message) - restoration = restart(path)["restoration"] - assert (restoration["state"], restoration["reason"]) == ( - "reset", - "incompatible_representation", + warned_once_and_reset( + build, path, "refused by the test", "incompatible_representation" ) @@ -334,14 +326,7 @@ def torn(self, snapshot): retention = restart(path)["retention"] assert (retention["state"], retention["reason"]) == ("omitted", "write_failed") assert resume(path).march is None - caught = resumed(build, path) - assert len(caught) == 1 - assert "write failed" in str(caught[0].message) - restoration = restart(path)["restoration"] - assert (restoration["state"], restoration["reason"]) == ( - "reset", - "unavailable_history", - ) + warned_once_and_reset(build, path, "write failed", "unavailable_history") def test_a_monitor_continuation_is_given_once_and_before_it_watches(): @@ -410,11 +395,9 @@ def test_a_history_the_writing_engine_could_not_export_warns_once_on_resume( "omitted", "incompatible_representation", ) - caught = resumed(build, path) - assert len(caught) == 1 - assert "the run's engine does not export it" in str(caught[0].message) - restoration = restart(path)["restoration"] - assert (restoration["state"], restoration["reason"]) == ( - "reset", + warned_once_and_reset( + build, + path, + "the run's engine does not export it", "incompatible_representation", ) diff --git a/tests/output/test_checkpoints.py b/tests/output/test_checkpoints.py index 8a0f40ea2..9d954d1ac 100644 --- a/tests/output/test_checkpoints.py +++ b/tests/output/test_checkpoints.py @@ -60,6 +60,18 @@ def plane(metadata, z, *, history=False): ) +def stopped(metadata, path, z, *, saved=(), history=False): + """Write a run that saved the planes `saved`, then failed at `z`, checkpointed.""" + with HDF5Output(path) as handler: + handler.open(metadata) + for one in saved: + handler.save(plane(metadata, one)) + handler.record_outcome( + RunOutcome("failed", z), + TerminalCheckpoint(plane(metadata, z, history=history), 0), + ) + + def test_memory_checkpoint_round_trip_preserves_counts_and_fft(metadata, tmp_path): memory = MemoryOutput() memory.open(metadata) @@ -95,13 +107,7 @@ def test_memory_checkpoint_round_trip_preserves_counts_and_fft(metadata, tmp_pat def test_checkpoint_history_moves_to_next_regular_save_once(metadata, tmp_path): path = tmp_path / "resume.h5" - with HDF5Output(path) as handler: - handler.open(metadata) - handler.save(plane(metadata, 0.0)) - handler.record_outcome( - RunOutcome("failed", 0.25), - TerminalCheckpoint(plane(metadata, 0.25, history=True), 0), - ) + stopped(metadata, path, 0.25, saved=(0.0,), history=True) with HDF5Output(path, append=True) as handler: handler.open(metadata) handler.record_outcome(RunOutcome("running", 0.25)) @@ -119,13 +125,7 @@ def test_checkpoint_history_moves_to_next_regular_save_once(metadata, tmp_path): def test_second_stop_retains_previous_unsaved_attempts(metadata, tmp_path): path = tmp_path / "repeated.h5" - with HDF5Output(path) as handler: - handler.open(metadata) - handler.save(plane(metadata, 0.0)) - handler.record_outcome( - RunOutcome("failed", 0.25), - TerminalCheckpoint(plane(metadata, 0.25, history=True), 0), - ) + stopped(metadata, path, 0.25, saved=(0.0,), history=True) with HDF5Output(path, append=True) as handler: handler.open(metadata) handler.record_outcome(RunOutcome("running", 0.25)) @@ -140,11 +140,7 @@ def test_second_stop_retains_previous_unsaved_attempts(metadata, tmp_path): def test_checkpoint_can_exist_before_first_regular_save(metadata, tmp_path): path = tmp_path / "entrance-failure.h5" - with HDF5Output(path) as handler: - handler.open(metadata) - handler.record_outcome( - RunOutcome("failed", 0.0), TerminalCheckpoint(plane(metadata, 0.0), 0) - ) + stopped(metadata, path, 0.0) state = resume(path) assert state.n_saved == 0 and state.plane.z == 0.0 assert state.checkpoint is not None @@ -398,11 +394,7 @@ def test_read_refuses_malformed_checkpoint_scalar_attributes( metadata, tmp_path, name, value ): path = tmp_path / "malformed-scalar.h5" - with HDF5Output(path) as handler: - handler.open(metadata) - handler.record_outcome( - RunOutcome("failed", 0.1), TerminalCheckpoint(plane(metadata, 0.1), 0) - ) + stopped(metadata, path, 0.1) with h5py.File(path, "r+") as stored: stored["terminal_checkpoint"].attrs[name] = value with pytest.raises(OutputError, match="typed scalars"): @@ -427,12 +419,7 @@ def test_new_checkpoint_replaces_an_interrupted_staging_group(metadata, tmp_path def test_resume_refuses_checkpoint_older_than_last_regular_save(metadata, tmp_path): path = tmp_path / "outdated-checkpoint.h5" - with HDF5Output(path) as handler: - handler.open(metadata) - handler.save(plane(metadata, 0.25)) - handler.record_outcome( - RunOutcome("failed", 0.5), TerminalCheckpoint(plane(metadata, 0.5), 0) - ) + stopped(metadata, path, 0.5, saved=(0.25,)) with h5py.File(path, "r+") as stored: stored["terminal_checkpoint"].attrs["z"] = 0.1 with pytest.raises(OutputError, match="precedes the last saved plane"): @@ -630,40 +617,21 @@ def test_a_stale_running_checkpoint_is_ignored_rather_than_refused( assert_array_equal(stored["step_history/z"], [0.0, 0.125, 0.25]) -def test_an_appending_writer_keeps_a_disagreeing_closing_checkpoint_as_read( - metadata, tmp_path +@pytest.mark.parametrize("append", [False, True], ids=["read", "appended"]) +def test_a_closing_record_disagreeing_with_its_checkpoint_is_refused( + metadata, tmp_path, append ): # Only a reader refuses the inconsistent state; a writer continuing the file keeps # its checkpoint as read, and the next read still refuses it. - path = tmp_path / "closing-append.h5" - with HDF5Output(path) as handler: - handler.open(metadata) - handler.save(plane(metadata, 0.0)) - handler.record_outcome( - RunOutcome("failed", 0.25), TerminalCheckpoint(plane(metadata, 0.25), 0) - ) - with h5py.File(path, "r+") as file: - file["terminal_checkpoint"].attrs["z"] = 0.375 - with HDF5Output(path, append=True) as handler: - handler.open(metadata) - kept = handler.terminal_checkpoint - assert kept is not None - assert kept.plane.z == 0.375 - with pytest.raises(OutputError, match="no matching execution outcome"): - resume(path) - - -def test_a_closing_record_disagreeing_with_its_checkpoint_is_still_refused( - metadata, tmp_path -): path = tmp_path / "closing.h5" - with HDF5Output(path) as handler: - handler.open(metadata) - handler.save(plane(metadata, 0.0)) - handler.record_outcome( - RunOutcome("failed", 0.25), TerminalCheckpoint(plane(metadata, 0.25), 0) - ) + stopped(metadata, path, 0.25, saved=(0.0,)) with h5py.File(path, "r+") as file: file["terminal_checkpoint"].attrs["z"] = 0.375 + if append: + with HDF5Output(path, append=True) as handler: + handler.open(metadata) + kept = handler.terminal_checkpoint + assert kept is not None + assert kept.plane.z == 0.375 with pytest.raises(OutputError, match="no matching execution outcome"): resume(path) diff --git a/tests/test_monitor.py b/tests/test_monitor.py index fcb84ae82..3bdc79f54 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -873,13 +873,23 @@ def test_the_split_s_removal_is_what_the_backend_took() -> None: assert summary["removed_fraction"] == summary["raw_removed_fraction"] -def test_under_the_split_the_guards_are_judged_on_what_it_found() -> None: - # The state the split left shows empty guards; what it found holds a tenth of - # the energy in the high guard, which stops the run under the default check. +@pytest.mark.parametrize( + "left_share", + [ + # The state the split left shows empty guards; what it found holds a tenth of + # the energy in the high guard, which stops the run under the default check. + 1.0, + # One energy for one verdict: the split took nearly everything, below the + # no-light floor of the state it left, but what it found filled the guard. + 1e-15, + ], + ids=["guards", "emptied"], +) +def test_under_the_split_the_guards_are_judged_on_what_it_found(left_share) -> None: monitor, _, reading = _split_monitor() monitor.check = BoundaryCheck() left = BoundaryEnergies( - reading.total, + left_share * reading.total, np.zeros(4), found=reading.total * np.array([1.0, 0.0, 0.1, 0.2]), ) @@ -887,20 +897,6 @@ def test_under_the_split_the_guards_are_judged_on_what_it_found() -> None: monitor.step(left, 0.1) -def test_a_state_the_split_emptied_is_still_judged_on_what_it_found() -> None: - # One energy for one verdict: the split took nearly everything, below the - # no-light floor of the state it left, but what it found filled the guard. - monitor, _, reading = _split_monitor() - monitor.check = BoundaryCheck() - emptied = BoundaryEnergies( - 1e-15 * reading.total, - np.zeros(4), - found=reading.total * np.array([1.0, 0.0, 0.1, 0.2]), - ) - with pytest.raises(BoundaryError, match="guards"): - monitor.step(emptied, 0.1) - - def test_the_collar_share_is_of_what_the_split_found() -> None: monitor, _, reading = _split_monitor() found = reading.total * np.array([1.0, 0.0, 0.0, 0.25]) diff --git a/tests/test_pulses.py b/tests/test_pulses.py index 050c7b8b6..0f3c73ecb 100644 --- a/tests/test_pulses.py +++ b/tests/test_pulses.py @@ -717,24 +717,6 @@ def test_a_time_record_that_is_not_centred_still_lands_where_it_sat(field_grid): assert_allclose(arrival, 100e-15, rtol=0.0, atol=1e-3 * 100e-15) -@pytest.mark.parametrize("arrival", [100e-15, 500e-15, 700e-15]) -def test_a_time_record_lands_anywhere_in_the_record(arrival, chirped_grid): - t = np.linspace(0.0, 800e-15, 8192) - omega_p = 2.0 * np.pi * C / WAVELENGTH - width = 20e-15 - record = np.exp(-(((t - arrival) / width) ** 2)) * np.cos(omega_p * t) - built = TimeDataPulse(t=t, field=record, energy=ENERGY).build(chirped_grid)[0, 0] - # The record's transform, analytically: a Gaussian about the carrier, whose phase - # is the arrival time alone. - omega = np.linspace(0.8 * omega_p, 1.2 * omega_p, 4001) - offset = omega - omega_p - reference = DataPulse.from_spectral_density( - omega, np.exp(-0.5 * (offset * width) ** 2), offset * arrival, energy=ENERGY - ).build(chirped_grid)[0, 0] - # Measured as 6.6e-11 at every arrival. - assert relative_l2(built, reference) < 5e-10 - - def test_a_chirped_time_record_lands_past_the_middle(chirped_grid): t = np.linspace(0.0, 2000e-15, 16384) omega_p = 2.0 * np.pi * C / WAVELENGTH @@ -806,6 +788,12 @@ def test_a_time_record_matches_the_analytic_transform_of_what_it_holds( @pytest.mark.parametrize( ("arrival", "disturbance", "tolerance"), [ + # A clean record lands anywhere in the record: 6.6e-11 measured at every + # arrival. Its reference is the record's transform, analytically: a Gaussian + # about the carrier, whose phase is the arrival time alone. + (100e-15, 0.0, 5e-10), + (500e-15, 0.0, 5e-10), + (700e-15, 0.0, 5e-10), # A baseline is taken out: 6.6e-11 measured, the same as with none. (500e-15, 0.01 * np.ones(8192), 5e-10), (100e-15, 0.1 * np.ones(8192), 5e-10), @@ -815,7 +803,15 @@ def test_a_time_record_matches_the_analytic_transform_of_what_it_holds( # White noise of 1 % of the peak, which the spectrum then holds: 1.9 % measured. (500e-15, 0.01 * np.random.default_rng(1).standard_normal(8192), 3e-2), ], - ids=["baseline_late", "baseline_early", "periodic_background", "noise"], + ids=[ + "clean_early", + "clean_middle", + "clean_late", + "baseline_late", + "baseline_early", + "periodic_background", + "noise", + ], ) def test_a_measured_time_record_stays_where_it_sat( arrival, disturbance, tolerance, chirped_grid From 82a15b5d128fbcf8cf1316cca37a37126de16134 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:41:14 +0000 Subject: [PATCH 12/13] Share the configuration-hash probe of the recipe export tests Three export tests prefixed the script they wrote with the same probe (a Simulation.run that prints the configuration hash and exits) and ran it the same way. The probe is builders.HASH_PROBE, and the run is builders.run_python: the same interpreter and script, run in the script's folder, with a clean exit asserted (check=True before). The hash each test compares is unchanged; the probe with its own JSON payload in test_recipe.py stays local. Counts (lines, tests, assert, raises, match=), before -> after: recipe/test_fibres.py 455->422, 28->28, 42->42, 6->6, 6->6 recipe/test_recipe.py 767->749, 67->67, 102->102, 26->26, 23->23 builders.py 68->87 94 tests of the two modules pass (one deselected by the default lane). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/builders.py | 21 +++++++++++++++++- tests/recipe/test_fibres.py | 43 +++++-------------------------------- tests/recipe/test_recipe.py | 24 +++------------------ 3 files changed, 28 insertions(+), 60 deletions(-) diff --git a/tests/builders.py b/tests/builders.py index 59593360f..4c6376ab4 100644 --- a/tests/builders.py +++ b/tests/builders.py @@ -11,6 +11,7 @@ import subprocess import sys +import textwrap from pathlib import Path from typing import Any @@ -21,7 +22,25 @@ from solprop.translate.problem import PropagationProblem from solprop.translate.run_request import RunRequest -__all__ = ["launch_derivative", "numpy_ref_launch_derivative", "run_python"] +__all__ = [ + "HASH_PROBE", + "launch_derivative", + "numpy_ref_launch_derivative", + "run_python", +] + +HASH_PROBE = textwrap.dedent( + """\ + from solprop.driver.simulation import Simulation + + def run(self, *args, **kwargs): + print(self.metadata().configuration_hash()) + raise SystemExit(0) + + Simulation.run = run + """ +) +"""A prefix for an exported script: its run prints the configuration hash and exits.""" def launch_derivative(backend: NumpyRefBackend, problem: PropagationProblem) -> Any: diff --git a/tests/recipe/test_fibres.py b/tests/recipe/test_fibres.py index f4b036cdf..08f8d459c 100644 --- a/tests/recipe/test_fibres.py +++ b/tests/recipe/test_fibres.py @@ -4,14 +4,13 @@ """Recipes for solid-core fibres: a step-index GNLSE fibre and a graded-index guide.""" -import subprocess -import sys import textwrap from typing import cast import numpy as np import pytest +from builders import HASH_PROBE, run_python from solprop.driver import Simulation from solprop.grid import EnvelopeGrid, FieldGrid from solprop.modes import ( @@ -159,25 +158,9 @@ def test_the_python_export_of_a_step_index_recipe_builds_the_same_run(tmp_path): recipe = recipe_of(fibre) script = recipe.to_python() assert "glass(name='BK7')" in script - probe = textwrap.dedent( - """\ - from solprop.driver.simulation import Simulation - - def run(self, *args, **kwargs): - print(self.metadata().configuration_hash()) - raise SystemExit(0) - - Simulation.run = run - """ - ) path = tmp_path / "export.py" - path.write_text(probe + script, encoding="utf-8") - result = subprocess.run( - [sys.executable, str(path)], - capture_output=True, - check=True, - encoding="utf-8", - ) + path.write_text(HASH_PROBE + script, encoding="utf-8") + result = run_python(path) expected = recipe.build().metadata().configuration_hash() assert result.stdout.strip() == expected @@ -433,23 +416,7 @@ def test_the_python_export_of_a_graded_index_recipe_builds_the_same_run(tmp_path recipe = grin_of() script = recipe.to_python() assert "ModalGuide.on_grid(grid, " in script - probe = textwrap.dedent( - """\ - from solprop.driver.simulation import Simulation - - def run(self, *args, **kwargs): - print(self.metadata().configuration_hash()) - raise SystemExit(0) - - Simulation.run = run - """ - ) path = tmp_path / "export.py" - path.write_text(probe + script, encoding="utf-8") - result = subprocess.run( - [sys.executable, str(path)], - capture_output=True, - check=True, - encoding="utf-8", - ) + path.write_text(HASH_PROBE + script, encoding="utf-8") + result = run_python(path) assert result.stdout.strip() == recipe.build().metadata().configuration_hash() diff --git a/tests/recipe/test_recipe.py b/tests/recipe/test_recipe.py index d1d13b5af..f4c365238 100644 --- a/tests/recipe/test_recipe.py +++ b/tests/recipe/test_recipe.py @@ -16,6 +16,7 @@ import numpy as np import pytest +from builders import HASH_PROBE, run_python from solprop.cli import main from solprop.driver import Simulation from solprop.exceptions import BackendError, MaterialRangeWarning @@ -587,19 +588,6 @@ def run(self, *args, **kwargs): assert "output='run.h5'" in recipe.to_python("run.h5") -_HASH_PROBE = textwrap.dedent( - """\ - from solprop.driver.simulation import Simulation - - def run(self, *args, **kwargs): - print(self.metadata().configuration_hash()) - raise SystemExit(0) - - Simulation.run = run - """ -) - - def _data_file(path, data): path.write_bytes(data) return {"file": path.name, "sha256": hashlib.sha256(data).hexdigest()} @@ -648,14 +636,8 @@ def test_the_export_writes_data_files_and_plain_tables(kind, tmp_path): else: assert "gas={'He': 0.5, 'Ne': 0.5}" in script path = tmp_path / "export.py" - path.write_text(_HASH_PROBE + script) - result = subprocess.run( - [sys.executable, str(path)], - capture_output=True, - text=True, - check=True, - cwd=tmp_path, - ) + path.write_text(HASH_PROBE + script) + result = run_python(path) with warnings.catch_warnings(): warnings.simplefilter("ignore", MaterialRangeWarning) built = recipe.build() From 70898a31c4ac5ca0ad8a0fd6c67cbe574cd1725d Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 12 Nov 2026 17:44:00 +0000 Subject: [PATCH 13/13] Backend and session tests: shared scaffolds for near-duplicate tests Near-duplicate tests whose shared setup was copied now share one helper or one parametrised body; every former case runs the same inputs, asserts and bounds. - test_native_edge_collar.py: the three line-current tests share _line_current (894->871 lines; tests 77->77; assert 82->76, the three scaffold asserts of three copies now one helper's, run for every case) - test_native_planar_statistics.py: the three split-step finish tests share _split_step_finish (245->233; tests 6->6; asserts unchanged; the xfail mark kept) - test_native_far_field.py: the two line parity tests become one test over LINE_APERTURES (859->855; tests 176->176; assert_* 20->19, one assert_matches for both; the partials assert now runs on both lines) - test_numpy_ref_multimode.py: the one-mode test and the convergence ladder become one (n_r, bound) table (716->706; tests 45->43; assert 36->35). The dropped case (one per backend) is the n_r = 24 rung at 1e-10, the same computation the one-mode test holds to 1e-14. Mutation check, Gauss-Kronrod weights in modes/quadrature.py scaled locally: x(1+1e-6) fails both the dropped rung and the kept case; x(1+1e-9) fails only the kept 1e-14 case. Reverted; src unchanged. - test_low_storage.py: the two noise tests share noisy_free_case (1823->1807; tests, asserts unchanged; called with the old lengths, seeds, step counts and responses) - sessions/test_group.py: the two window-failure tests share assert_drained_after_failure (875->870; tests 32->32; assert 149->141, assert calls 1->3: one helper's eleven asserts run for both, in each test's old place) No test that writes records changed. The modules pass (-n 2/4). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HAYtF5P9QqEd3HQx3WJkA3 --- tests/backends/test_low_storage.py | 50 +++------ tests/backends/test_native_edge_collar.py | 103 +++++++----------- tests/backends/test_native_far_field.py | 66 ++++++----- .../backends/test_native_planar_statistics.py | 52 ++++----- tests/backends/test_numpy_ref_multimode.py | 48 ++++---- tests/sessions/test_group.py | 39 +++---- 6 files changed, 144 insertions(+), 214 deletions(-) diff --git a/tests/backends/test_low_storage.py b/tests/backends/test_low_storage.py index c6d950f80..f70f55217 100644 --- a/tests/backends/test_low_storage.py +++ b/tests/backends/test_low_storage.py @@ -1367,26 +1367,28 @@ def test_the_ledger_holds_three_registers_the_scratch_and_the_table(mode, collar # --- the noise (section 7.1, Q3) ---------------------------------------------------- -def test_the_noise_draw_never_enters_the_propagating_field(): - """With the draw and no response the state is the pure flow of its input.""" - length = 1e-3 +def noisy_free_case(length, seed, steps, responses): + """A Cartesian envelope case with a modified-noise draw, on `steps` equal steps. + + Returns the grid, the space, the draw, the schedule, the problem and its request. + """ grid = EnvelopeGrid.from_limits( length, 800e-9, (600e-9, 1.2e-6), 150e-15, thg=False ) space = FreeGrid(3e-4, 9, 4e-4, 12, collar_fraction=0) noise = spatial_noise( SpatialFlux.resolve(grid, space, SpatialMedium()), - np.random.default_rng(3), + np.random.default_rng(seed), model="modified", ) pulse = SpatialPulse( GaussianPulse(wavelength=800e-9, fwhm=30e-15, energy=1e-7), 80e-6 ) - schedule = FixedSchedule.uniform(0.0, length, length / 8) + schedule = FixedSchedule.uniform(0.0, length, length / steps) problem, run_request = assemble( grid, None, - [], + responses, pulse.build(grid, space, medium=SpatialMedium()), spatial_grid=space, medium=SpatialMedium(), @@ -1398,6 +1400,13 @@ def test_the_noise_draw_never_enters_the_propagating_field(): schedule=schedule, integrator=MARCH, ) + return grid, space, noise, schedule, problem, run_request + + +def test_the_noise_draw_never_enters_the_propagating_field(): + """With the draw and no response the state is the pure flow of its input.""" + length = 1e-3 + grid, _, noise, schedule, problem, run_request = noisy_free_case(length, 3, 8, []) backend = NumpyRefBackend(problem, run_request, grid=grid) backend.set_initial(problem.initial.field0, noise) backend.propagate_to(length) @@ -1413,33 +1422,8 @@ def test_each_pass_carries_the_draw_at_its_own_position(monkeypatch): every active bin, as ``test_free_noise`` forms it; the bound is that test's. """ length = 1e-4 - grid = EnvelopeGrid.from_limits( - length, 800e-9, (600e-9, 1.2e-6), 150e-15, thg=False - ) - space = FreeGrid(3e-4, 9, 4e-4, 12, collar_fraction=0) - noise = spatial_noise( - SpatialFlux.resolve(grid, space, SpatialMedium()), - np.random.default_rng(94), - model="modified", - ) - pulse = SpatialPulse( - GaussianPulse(wavelength=800e-9, fwhm=30e-15, energy=1e-7), 80e-6 - ) - schedule = FixedSchedule.uniform(0.0, length, length / 2) - problem, run_request = assemble( - grid, - None, - [KerrResponse(1e-22, thg=False)], - pulse.build(grid, space, medium=SpatialMedium()), - spatial_grid=space, - medium=SpatialMedium(), - noise=noise, - controller=PIController(rtol=1e-8, atol=1e-14), - save_planes=[length], - dz_max=schedule.max_step, - dz_init=schedule.max_step, - schedule=schedule, - integrator=MARCH, + grid, space, noise, schedule, problem, run_request = noisy_free_case( + length, 94, 2, [KerrResponse(1e-22, thg=False)] ) backend = NumpyRefBackend(problem, run_request, grid=grid) backend.set_initial(problem.initial.field0, noise) diff --git a/tests/backends/test_native_edge_collar.py b/tests/backends/test_native_edge_collar.py index 627b13753..52eaa4038 100644 --- a/tests/backends/test_native_edge_collar.py +++ b/tests/backends/test_native_edge_collar.py @@ -13,6 +13,7 @@ import math import threading import warnings +from collections.abc import Callable from pathlib import Path from typing import Any, cast @@ -262,10 +263,15 @@ def test_native_reads_a_collars_strip_and_current_as_the_host_does( ) -def test_a_plane_wave_reads_its_exact_current() -> None: - # On a uniform grid the central difference of exp(i kappa s) is exactly - # i sin(kappa h) / h times it, so J = |E|^2 sin(kappa h) / (h k). It flows towards - # smaller s on the face where it's inward, and the other face rectifies it away. +def _line_current( + bins: Callable[[np.ndarray, float], dict[int, np.ndarray]], +) -> tuple[float, float, float, Any, int]: + """Read the line case's current from a state of transverse waves in its bins. + + `bins(x, kappa)` maps an active bin's index to its field along the line, for + kappa forty cycles over the line. Returns the native current, kappa, the spacing + h, the attached edge and the line's point count. + """ simulation = _case("line") problem = simulation.translate() monitor = simulation._boundary_monitor() @@ -276,12 +282,11 @@ def test_a_plane_wave_reads_its_exact_current() -> None: assert isinstance(space, LineGrid) x = np.asarray(space.x) h = float(x[1] - x[0]) - mode = 40 - kappa = 2 * math.pi * mode / (space.n_x * h) - wave = np.exp(1j * kappa * x) + kappa = 2 * math.pi * 40 / (space.n_x * h) active = np.nonzero(np.asarray(problem.grids.active_mask))[0] state = np.zeros(problem.shape, dtype=np.complex128) - state[:, 0, active[3]] = np.fft.fft(wave) + for index, wave in bins(x, kappa).items(): + state[:, 0, active[index]] = np.fft.fft(wave) backend, edge = _attached(simulation, state) try: native = backend._edge_reading( @@ -289,38 +294,40 @@ def test_a_plane_wave_reads_its_exact_current() -> None: ) finally: backend.close() + return native.current, kappa, h, edge, space.n_x + + +def test_a_plane_wave_reads_its_exact_current() -> None: + # On a uniform grid the central difference of exp(i kappa s) is exactly + # i sin(kappa h) / h times it, so J = |E|^2 sin(kappa h) / (h k). It flows towards + # smaller s on the face where it's inward, and the other face rectifies it away. + current, kappa, h, edge, n_x = _line_current( + lambda x, kappa: {3: np.exp(1j * kappa * x)} + ) expected = math.sin(kappa * h) / h / edge.k_min - assert native.current == pytest.approx(expected, rel=64 * fft_bound(space.n_x)) + assert current == pytest.approx(expected, rel=64 * fft_bound(n_x)) def test_the_current_is_rectified_per_row_and_not_after_summing() -> None: # One bin inward and one outward at one amplitude: their fluxes cancel in a sum, # and a current rectified after summing would read nothing on either face. - simulation = _case("line") - problem = simulation.translate() - monitor = simulation._boundary_monitor() - assert monitor is not None - edge = monitor.transverse - assert edge is not None - space = edge.space - assert isinstance(space, LineGrid) - x = np.asarray(space.x) - h = float(x[1] - x[0]) - mode = 40 - kappa = 2 * math.pi * mode / (space.n_x * h) - active = np.nonzero(np.asarray(problem.grids.active_mask))[0] - state = np.zeros(problem.shape, dtype=np.complex128) - state[:, 0, active[3]] = np.fft.fft(np.exp(1j * kappa * x)) - state[:, 0, active[5]] = np.fft.fft(np.exp(-1j * kappa * x)) - backend, edge = _attached(simulation, state) - try: - native = backend._edge_reading( - backend._native_state, edge, faces=False, current=True - ) - finally: - backend.close() + current, kappa, h, edge, n_x = _line_current( + lambda x, kappa: {3: np.exp(1j * kappa * x), 5: np.exp(-1j * kappa * x)} + ) expected = 2 * math.sin(kappa * h) / h / edge.k_min - assert native.current == pytest.approx(expected, rel=64 * fft_bound(space.n_x)) + assert current == pytest.approx(expected, rel=64 * fft_bound(n_x)) + + +def test_a_standing_wave_reads_almost_no_current() -> None: + # A real field carries no flux, so each row's product cancels to rounding: there the + # bound is absolute, set by the terms and not by the result. + current, _, h, edge, n_x = _line_current( + lambda x, kappa: {3: np.cos(kappa * x).astype(np.complex128)} + ) + # Unit field: |v| |s| / k, for |s| at most 2 / (2 h), times the transform's + # rounding, on each of the two lines, which rectification can only keep. + bound = 2 * fft_bound(n_x) / h / edge.k_min + assert 0.0 <= current <= bound def _packet(space: LineGrid, centre: float, kappa: float) -> np.ndarray: @@ -524,36 +531,6 @@ def test_a_lit_node_reads_the_collars_rate_from_its_design() -> None: assert read.totals[1] == pytest.approx(expected, rel=64 * fft_bound(space.n_x)) -def test_a_standing_wave_reads_almost_no_current() -> None: - # A real field carries no flux, so each row's product cancels to rounding: there the - # bound is absolute, set by the terms and not by the result. - simulation = _case("line") - problem = simulation.translate() - monitor = simulation._boundary_monitor() - assert monitor is not None - edge = monitor.transverse - assert edge is not None - space = edge.space - assert isinstance(space, LineGrid) - x = np.asarray(space.x) - h = float(x[1] - x[0]) - kappa = 2 * math.pi * 40 / (space.n_x * h) - active = np.nonzero(np.asarray(problem.grids.active_mask))[0] - state = np.zeros(problem.shape, dtype=np.complex128) - state[:, 0, active[3]] = np.fft.fft(np.cos(kappa * x).astype(np.complex128)) - backend, edge = _attached(simulation, state) - try: - native = backend._edge_reading( - backend._native_state, edge, faces=False, current=True - ) - finally: - backend.close() - # Unit field: |v| |s| / k, for |s| at most 2 / (2 h), times the transform's - # rounding, on each of the two lines, which rectification can only keep. - bound = 2 * fft_bound(space.n_x) / h / edge.k_min - assert 0.0 <= native.current <= bound - - class _StopAtFirstPlane(NullReporter): """Set a run's stop flag at its first saved plane, between two edge reads.""" diff --git a/tests/backends/test_native_far_field.py b/tests/backends/test_native_far_field.py index 974e423d6..ea7335a78 100644 --- a/tests/backends/test_native_far_field.py +++ b/tests/backends/test_native_far_field.py @@ -256,44 +256,40 @@ def test_the_native_shapes_sum_each_half_plane_and_its_complement_to_the_beam(): assert_within(np.sum(spectra, axis=0), beam, bound, elementwise=True) -def test_the_native_pass_matches_the_reference_on_a_line_of_shapes(): - grid = time_grid("envelope") - space = LineGrid(8e-3, 130, collar_fraction=0) # three blocks of columns - apertures = ApertureSet( - centres=[[6e-5, 0.0], [6e-5, 0.0], [2e-5, 0.0], [-1e-4, 0.0]], - diameters=[0.0, 0.0, 0.0, 3e-4], - distances=[DISTANCE] * 4, - edges=[1e-5, 1e-5, 1e-5, 2e-5], - shapes=("half_plane_x_ge", "half_plane_x_lt", "rectangle", "circle"), - extents=[[0.0, 0.0], [0.0, 0.0], [1.6e-4, 1.6e-4], [0.0, 0.0]], - profile="rcos", - weighting="quadrature", - ) - regions = np.array([[-np.inf, 0.0, -1.0, 1.0], [0.0, 2e4, -np.inf, np.inf]]) - spec = spec_of(apertures, regions=regions) - field = random_field(space, 1, grid, seed=11) - problem, run_request = problem_of(grid, space, field, spec) - tables = aperture_tables(spec, problem.grids, problem.transform.geometry) - values, field = native_stats(problem, run_request, grid, field, WITH_AXIS) - assert_matches( - values, - reference(WITH_AXIS, grid, problem, field, tables), - magnitudes(WITH_AXIS, grid, problem, field, tables), - problem, - ) +LINE_APERTURES = { + "shapes": ( + 8e-3, + ApertureSet( + centres=[[6e-5, 0.0], [6e-5, 0.0], [2e-5, 0.0], [-1e-4, 0.0]], + diameters=[0.0, 0.0, 0.0, 3e-4], + distances=[DISTANCE] * 4, + edges=[1e-5, 1e-5, 1e-5, 2e-5], + shapes=("half_plane_x_ge", "half_plane_x_lt", "rectangle", "circle"), + extents=[[0.0, 0.0], [0.0, 0.0], [1.6e-4, 1.6e-4], [0.0, 0.0]], + profile="rcos", + weighting="quadrature", + ), + ), + "circles": ( + 4e-4, + ApertureSet( + centres=[[0.0, 0.0], [1.2e-3, 0.0]], + diameters=[1e-3, 6e-4], + distances=[DISTANCE, 0.5], + edges=[5e-5, 5e-5], + profile="rcos", + weighting="quadrature", + ), + ), +} +"""A line's half-width and apertures: the shaped rows, and two circles' slits.""" -def test_the_native_pass_matches_the_reference_on_a_line(): +@pytest.mark.parametrize("name", list(LINE_APERTURES)) +def test_the_native_pass_matches_the_reference_on_a_line(name): + width, apertures = LINE_APERTURES[name] grid = time_grid("envelope") - space = LineGrid(4e-4, 130, collar_fraction=0) # three blocks of columns - apertures = ApertureSet( - centres=[[0.0, 0.0], [1.2e-3, 0.0]], - diameters=[1e-3, 6e-4], - distances=[DISTANCE, 0.5], - edges=[5e-5, 5e-5], - profile="rcos", - weighting="quadrature", - ) + space = LineGrid(width, 130, collar_fraction=0) # three blocks of columns regions = np.array([[-np.inf, 0.0, -1.0, 1.0], [0.0, 2e4, -np.inf, np.inf]]) spec = spec_of(apertures, regions=regions) field = random_field(space, 1, grid, seed=11) diff --git a/tests/backends/test_native_planar_statistics.py b/tests/backends/test_native_planar_statistics.py index c2dfd9d18..37171dd60 100644 --- a/tests/backends/test_native_planar_statistics.py +++ b/tests/backends/test_native_planar_statistics.py @@ -172,19 +172,16 @@ def finished(problem, run_request, grid, rows, dz, options=None): return expected, actual -def test_the_hard_mask_takes_the_rows_to_the_state(): - """The split-step finish leaves exact zeros off the band, on native and the oracle. +def _split_step_finish(off_band: complex): + """Finish the split-step collar case's launch rows set to `off_band` off the band. - A load masks its field, so the rows with content off the band reach the finish - directly: ``adopt`` on native, ``_finish`` on the reference, each the whole step's - finish on rows it is handed. Off the band the zeros are exact (class P, - ``docs/dev/testing.md`` section 3): any other value would be real content. + Returns the problem, its active mask and the reference's and native's finished + rows (:func:`finished`) over one step of the schedule. """ grid, space, problem, run_request = collar_family_case("collar_split_step") active = np.asarray(problem.grids.active_mask) - assert not np.all(active) rows = np.array(problem.initial.field0, dtype=complex) - rows[..., ~active] = 1.0 + 1.0j + rows[..., ~active] = off_band expected, actual = finished( problem, run_request, @@ -193,6 +190,19 @@ def test_the_hard_mask_takes_the_rows_to_the_state(): float(run_request.stepper.schedule.max_step), # pyright: ignore[reportOptionalMemberAccess] chunked(space), ) + return problem, active, expected, actual + + +def test_the_hard_mask_takes_the_rows_to_the_state(): + """The split-step finish leaves exact zeros off the band, on native and the oracle. + + A load masks its field, so the rows with content off the band reach the finish + directly: ``adopt`` on native, ``_finish`` on the reference, each the whole step's + finish on rows it is handed. Off the band the zeros are exact (class P, + ``docs/dev/testing.md`` section 3): any other value would be real content. + """ + _, active, expected, actual = _split_step_finish(1.0 + 1.0j) + assert not np.all(active) np.testing.assert_array_equal(expected[..., ~active], 0.0) np.testing.assert_array_equal(actual[..., ~active], 0.0) assert np.max(np.abs(actual[..., active])) > 0.0 @@ -200,18 +210,7 @@ def test_the_hard_mask_takes_the_rows_to_the_state(): def test_the_finish_on_the_band_is_the_reference_s(): """The same finish on rows with nothing off the band, as every march's are.""" - grid, space, problem, run_request = collar_family_case("collar_split_step") - active = np.asarray(problem.grids.active_mask) - rows = np.array(problem.initial.field0, dtype=complex) - rows[..., ~active] = 0.0 - expected, actual = finished( - problem, - run_request, - grid, - rows, - float(run_request.stepper.schedule.max_step), # pyright: ignore[reportOptionalMemberAccess] - chunked(space), - ) + problem, _, expected, actual = _split_step_finish(0.0) assert_within(actual, expected, finish_bound(problem), what="the finish") @@ -230,16 +229,5 @@ def test_a_finish_with_content_off_the_band_is_the_reference_s_on_it(): source's prefactor and the in-stage term are zero there, and the flow is the identity there. Measured 1.1e-8 at unit content off the band, 4.4e6 V/m at the peak. """ - grid, space, problem, run_request = collar_family_case("collar_split_step") - active = np.asarray(problem.grids.active_mask) - rows = np.array(problem.initial.field0, dtype=complex) - rows[..., ~active] = 1.0 + 1.0j - expected, actual = finished( - problem, - run_request, - grid, - rows, - float(run_request.stepper.schedule.max_step), # pyright: ignore[reportOptionalMemberAccess] - chunked(space), - ) + problem, _, expected, actual = _split_step_finish(1.0 + 1.0j) assert_within(actual, expected, finish_bound(problem), what="the finish") diff --git a/tests/backends/test_numpy_ref_multimode.py b/tests/backends/test_numpy_ref_multimode.py index 15d6914b4..f4a85e26b 100644 --- a/tests/backends/test_numpy_ref_multimode.py +++ b/tests/backends/test_numpy_ref_multimode.py @@ -149,50 +149,40 @@ def pulse(grid, count=1, energy=ENERGY): # --------------------------------------------------- one node is the mode-averaged case -def test_a_one_mode_multimode_run_reproduces_the_mode_averaged_one( - backend_class, grid, capillary +@pytest.mark.parametrize( + ("n_r", "bound"), + [ + # Measured 1.1e-11 and 2.9e-18 at n_r = 8 and 16: the rule converges + # spectrally and is already at round-off by 16. The bound is the coarsest of + # them with a decade in hand. + (8, 1e-10), + (16, 1e-10), + # Measured 1.3e-16 at n_r = 24: by this order the rule is exact on the quartic + # and what is left is the round-off of two different orderings of the same sum + # -- the machine epsilon times a 257-bin reduction -- and not the quadrature. + (CONVERGED_N_R, 1e-14), + ], +) +def test_the_quadrature_converges_towards_the_mode_averaged_answer( + backend_class, grid, capillary, n_r, bound ): """The mode-averaged path is the n_nodes = 1 case of this pipeline. The mode-averaged run converts with ``1/sqrt(eps0 c A_eff/2)`` and projects with 1; the multimode run synthesises the Bessel profile at the nodes and integrates the quartic on the rule. They are the same number by the definition of ``A_eff``, so - what is left is the quadrature's own error. + what is left is the quadrature's own error: coarse rules are wrong by the rule's + error and by nothing systematic. """ start = pulse(grid) averaged, _ = propagate(backend_class, *build(grid, capillary, start), grid) - rule = transverse_quadrature( - [capillary], n_r=CONVERGED_N_R, radial_rule="gauss_kronrod" - ) - multimode, _ = propagate( - backend_class, - *build(grid, [capillary], start, quadrature=rule), - grid, - ) - # Measured 1.3e-16 at n_r = 24, against 1.1e-11 at n_r = 8: by this order the rule - # is exact on the quartic and what is left is the round-off of two different - # orderings of the same sum -- the machine epsilon times a 257-bin reduction -- and - # not the quadrature at all. - assert peak_gap(multimode.field, averaged.field) < 1e-14 - - -@pytest.mark.parametrize("n_r", [8, 16, CONVERGED_N_R]) -def test_the_quadrature_converges_towards_the_mode_averaged_answer( - backend_class, grid, capillary, n_r -): - """Coarse rules are wrong by the rule's error and by nothing systematic.""" - start = pulse(grid) - averaged, _ = propagate(backend_class, *build(grid, capillary, start), grid) rule = transverse_quadrature([capillary], n_r=n_r, radial_rule="gauss_kronrod") multimode, _ = propagate( backend_class, *build(grid, [capillary], start, quadrature=rule), grid, ) - # Measured 1.1e-11, 2.9e-18 and 1.3e-16 at n_r = 8, 16 and 24: the rule converges - # spectrally and is already at round-off by 16. The bound is the coarsest of them - # with a decade in hand. - assert peak_gap(multimode.field, averaged.field) < 1e-10 + assert peak_gap(multimode.field, averaged.field) < bound # ------------------------------------------------------------------- the linear flow diff --git a/tests/sessions/test_group.py b/tests/sessions/test_group.py index 4b4e246f6..0459cc41f 100644 --- a/tests/sessions/test_group.py +++ b/tests/sessions/test_group.py @@ -496,6 +496,21 @@ def abandoned(dz, end, slack): assert group.finished +def assert_drained_after_failure(group, ended): + """A failed window's terminals deliver its two fixed steps, once, at its plane.""" + assert ended.outcome is Outcome.FAILED + assert isinstance(ended.error, RuntimeError) + for index, events in enumerate(ended.members): + (terminal,) = events + assert isinstance(terminal, Terminal) + assert terminal.history is not None + # The first window's two fixed steps, delivered once. + assert terminal.history.n_steps == 2 + assert group.member_status(index).attempts == 2 + assert terminal.z == pytest.approx(PLANES[0]) + assert terminal.eligibility is Eligibility.ELIGIBLE + + @pytest.mark.parametrize("backend", LOCKSTEP) def test_a_window_s_failure_delivers_the_attempts_it_drained(backend, monkeypatch): available(backend) @@ -514,17 +529,7 @@ def broken(self, spec): monkeypatch.setattr(type(owners[0]), "stats", broken) ended = group.advance() - assert ended.outcome is Outcome.FAILED - assert isinstance(ended.error, RuntimeError) - for index, events in enumerate(ended.members): - (terminal,) = events - assert isinstance(terminal, Terminal) - assert terminal.history is not None - # The first window's two fixed steps, delivered once. - assert terminal.history.n_steps == 2 - assert group.member_status(index).attempts == 2 - assert terminal.z == pytest.approx(PLANES[0]) - assert terminal.eligibility is Eligibility.ELIGIBLE + assert_drained_after_failure(group, ended) group.acknowledge(ended.receipt) @@ -675,17 +680,7 @@ def broken(self, spec): monkeypatch.setattr(type(runner_of(group)), "stats", broken) ended = group.advance() group.acknowledge(ended.receipt) - assert ended.outcome is Outcome.FAILED - assert isinstance(ended.error, RuntimeError) - for index, events in enumerate(ended.members): - (terminal,) = events - assert isinstance(terminal, Terminal) - assert terminal.history is not None - # The first window's two fixed steps, delivered once. - assert terminal.history.n_steps == 2 - assert group.member_status(index).attempts == 2 - assert terminal.z == pytest.approx(PLANES[0]) - assert terminal.eligibility is Eligibility.ELIGIBLE + assert_drained_after_failure(group, ended) @pytest.mark.parametrize("backend", LOCKSTEP)