Add remaining results batch 16
Browse filesFiles changed (50)
- baselines/recovar/tests/unit/test_homogeneous.pyAdded+114
- baselines/recovar/tests/unit/test_image_assignment.pyAdded+115
- baselines/recovar/tests/unit/test_image_backends.pyAdded+1296
- baselines/recovar/tests/unit/test_image_loader.pyAdded+980
- baselines/recovar/tests/unit/test_job_dir.pyAdded+272
- baselines/recovar/tests/unit/test_latent_density.pyAdded+172
- baselines/recovar/tests/unit/test_linalg.pyAdded+349
- baselines/recovar/tests/unit/test_load_utils.pyAdded+339
- baselines/recovar/tests/unit/test_locres.pyAdded+351
- baselines/recovar/tests/unit/test_locres_half_volume.pyAdded+265
- baselines/recovar/tests/unit/test_m_step.pyAdded+193
- baselines/recovar/tests/unit/test_mask.pyAdded+109
- baselines/recovar/tests/unit/test_max_r_default_and_equivalence.pyAdded+560
- baselines/recovar/tests/unit/test_memory_planner.pyAdded+745
- baselines/recovar/tests/unit/test_metadata_readers.pyAdded+349
- baselines/recovar/tests/unit/test_metrics.pyAdded+100
- baselines/recovar/tests/unit/test_metrics_regression_helper.pyAdded+93
- baselines/recovar/tests/unit/test_module_imports.pyAdded+36
- baselines/recovar/tests/unit/test_multi_gpu_utils.pyAdded+88
- baselines/recovar/tests/unit/test_noise.pyAdded+595
- baselines/recovar/tests/unit/test_output.pyAdded+439
- baselines/recovar/tests/unit/test_output_helpers.pyAdded+376
- baselines/recovar/tests/unit/test_output_paths.pyAdded+129
- baselines/recovar/tests/unit/test_packaging_metadata.pyAdded+138
- baselines/recovar/tests/unit/test_padding.pyAdded+94
- baselines/recovar/tests/unit/test_parse_relion5_tomo.pyAdded+1391
- baselines/recovar/tests/unit/test_parse_relion5_tomo_realdata.pyAdded+123
- baselines/recovar/tests/unit/test_parser_args.pyAdded+111
- baselines/recovar/tests/unit/test_pdb_utils.pyAdded+89
- baselines/recovar/tests/unit/test_perf_regression.pyAdded+68
- baselines/recovar/tests/unit/test_pipeline_with_outliers.pyAdded+289
- baselines/recovar/tests/unit/test_plot_utils.pyAdded+95
- baselines/recovar/tests/unit/test_ppca.pyAdded+117
- baselines/recovar/tests/unit/test_principal_components.pyAdded+679
- baselines/recovar/tests/unit/test_project.pyAdded+297
- baselines/recovar/tests/unit/test_regularization.pyAdded+341
- baselines/recovar/tests/unit/test_relion_functions.pyAdded+679
- baselines/recovar/tests/unit/test_run_test_all_metrics.pyAdded+1201
- baselines/recovar/tests/unit/test_simulate_scattering_potential.pyAdded+183
- baselines/recovar/tests/unit/test_simulator.pyAdded+247
- baselines/recovar/tests/unit/test_small_experiment.pyAdded+47
- baselines/recovar/tests/unit/test_staging.pyAdded+271
- baselines/recovar/tests/unit/test_starfile.pyAdded+289
- baselines/recovar/tests/unit/test_synthetic_dataset.pyAdded+105
- baselines/recovar/tests/unit/test_synthetic_pipeline_integration.pyAdded+44
- baselines/recovar/tests/unit/test_tilt_index_consistency.pyAdded+328
- baselines/recovar/tests/unit/test_tiny_synthetic_helper.pyAdded+75
- baselines/recovar/tests/unit/test_trajectory.pyAdded+203
- baselines/recovar/tests/unit/test_trajectory_generation.pyAdded+248
- baselines/recovar/tests/unit/test_utils.pyAdded+388
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114import numpy as npimport pytest
pytest.importorskip("jax")
from recovar.reconstruction import homogeneousfrom recovar.reconstruction import regularizationfrom recovar.reconstruction import relion_functions
pytestmark = pytest.mark.unit
class _FakeHalfsetDataset: def __init__(self, tag, volume_shape): self.tag = tag self.volume_shape = volume_shape
class _FakeDataset: def __init__(self): self.volume_shape = (4,) self.halfset_indices = [ np.array([0, 1], dtype=np.int32), np.array([2, 3], dtype=np.int32), ]
def materialize_halfset_datasets(self): return ( _FakeHalfsetDataset(0, self.volume_shape), _FakeHalfsetDataset(1, self.volume_shape), )
def test_get_mean_conformation_relion_flow_and_restore(monkeypatch): def fake_triangular_kernel(dataset, noise_variance, batch_size, index_subset=None, **kwargs): tag = dataset.tag return ( np.ones(4, dtype=np.float32) * (1 + tag), np.ones(4, dtype=np.float32) * (10 + tag), )
def fake_post_process_from_filter_v2(ft_ctf, ft_y, volume_shape, upsampling_factor, tau=None, **kwargs): base = float(np.mean(ft_ctf) + np.mean(ft_y) + (0 if tau is None else np.mean(tau))) return np.full(4, base, dtype=np.float32)
monkeypatch.setattr(relion_functions, "relion_style_triangular_kernel", fake_triangular_kernel) monkeypatch.setattr(relion_functions, "post_process_from_filter_v2", fake_post_process_from_filter_v2) monkeypatch.setattr( regularization, "compute_relion_prior", lambda dataset, noise, m0, m1, batch: (np.ones(4, dtype=np.float32) * 2.0, np.array([0.9]), np.array([0.0])), )
ds = _FakeDataset() means, mean_prior, fsc = homogeneous.get_mean_conformation_relion( dataset=ds, batch_size=2, noise_variance=np.ones(4, dtype=np.float32), use_regularization=False, upsampling_factor=3, )
assert means.combined is not None assert means.corrected0 is not None assert means.corrected1 is not None assert means.corrected0reg is not None assert means.corrected1reg is not None assert means.lhs is not None assert means.prior is not None assert means.combined.shape == (4,) assert isinstance(mean_prior, np.ndarray) assert np.asarray(fsc).size > 0
def test_get_mean_conformation_relion_use_regularization_switch(monkeypatch): monkeypatch.setattr( relion_functions, "relion_style_triangular_kernel", lambda dataset, *_args, **_kwargs: (np.ones(2, dtype=np.float32), np.ones(2, dtype=np.float32)), )
def fake_pp_v2(ft_ctf, ft_y, volume_shape, upsampling_factor, tau=None, **kwargs): if tau is None: return np.array([1.0, 1.0], dtype=np.float32) return np.array([3.0, 3.0], dtype=np.float32)
monkeypatch.setattr(relion_functions, "post_process_from_filter_v2", fake_pp_v2) monkeypatch.setattr( regularization, "compute_relion_prior", lambda *_args, **_kwargs: (np.ones(2, dtype=np.float32), np.array([0.8]), np.array([0.0])), )
ds = _FakeDataset() ds.volume_shape = (2,) ds.halfset_indices = [np.array([0], dtype=np.int32), np.array([1], dtype=np.int32)]
means_unreg, *_ = homogeneous.get_mean_conformation_relion( dataset=ds, batch_size=1, noise_variance=np.ones(2, dtype=np.float32), use_regularization=False, ) means_reg, *_ = homogeneous.get_mean_conformation_relion( dataset=ds, batch_size=1, noise_variance=np.ones(2, dtype=np.float32), use_regularization=True, )
# unregularized combined = average of tau=None outputs = 1.0 assert np.allclose(means_unreg.combined, 1.0) # regularized combined = average of tau!=None outputs = 3.0 assert np.allclose(means_reg.combined, 3.0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115from types import SimpleNamespace
import numpy as npimport pytestimport scipy.stats
pytest.importorskip("jax")
from recovar.heterogeneity import image_assignment as ia
pytestmark = pytest.mark.unit
def test_compute_residual_uses_forward_model_translation_and_noise_scaling(monkeypatch): images = np.array([[3.0, 5.0], [7.0, 11.0]], dtype=np.float32) projected = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32)
monkeypatch.setattr(ia.core, "translate_images", lambda x, *_args, **_kwargs: x) monkeypatch.setattr(ia.core_forward, "forward_model", lambda *_args, **_kwargs: projected)
config = SimpleNamespace(image_shape=(1, 2)) out = ia.compute_residual( images=images, ctf_params=None, rotation_matrices=None, translations=None, mean_estimate=np.array([0.0], dtype=np.float32), config=config, noise_variance=np.array([4.0, 4.0], dtype=np.float32), ) expected = np.linalg.norm((images - projected) / np.sqrt(4.0), axis=-1) ** 2 assert np.allclose(np.asarray(out), expected)
class _MockDS: """Minimal mock dataset for iter_batches()."""
dtype = np.complex64 dtype_real = np.float32 n_units = 4 volume_shape = (1, 1, 1) image_shape = (1, 2) grid_size = 1 voxel_size = 1.0 padding = 0 premultiplied_ctf = False volume_mask_threshold = 0.25 CTF_params = np.zeros((4, 1), dtype=np.float32) rotation_matrices = np.zeros((4, 3, 3), dtype=np.float32) translations = np.zeros((4, 2), dtype=np.float32) ctf_evaluator = staticmethod(lambda *_args, **_kwargs: None)
def iter_batches(self, batch_size, **kwargs): batch = np.zeros((2, 2), dtype=np.float32) particles_ind = np.array([1, 3], dtype=np.int32) batch_image_ind = np.array([1, 3], dtype=np.int32) yield ( batch, self.rotation_matrices[batch_image_ind], self.translations[batch_image_ind], self.CTF_params[batch_image_ind], None, particles_ind, batch_image_ind, )
def test_compute_image_assignment_fills_residual_matrix(monkeypatch): def fake_compute_residual(images, _ctf_params, _rotation_matrices, _translations, mean_estimate, *_args, **_kwargs): return np.full(images.shape[0], float(np.real(mean_estimate[0])), dtype=np.float32)
monkeypatch.setattr(ia, "compute_residual", fake_compute_residual)
volumes = np.array([[10.0], [20.0], [30.0]], dtype=np.float32) out = ia.compute_image_assignment( _MockDS(), volumes, noise_variance=np.array([1.0]), batch_size=2, disc_type="nearest" )
assert out.shape == (3, 4) assert np.allclose(out[:, 1], [10.0, 20.0, 30.0]) assert np.allclose(out[:, 3], [10.0, 20.0, 30.0]) assert np.allclose(out[:, 0], 0.0) assert np.allclose(out[:, 2], 0.0)
def test_estimate_false_positive_rate_from_mocked_residual(monkeypatch): class _DS2(_MockDS): n_units = 2 CTF_params = np.zeros((2, 1), dtype=np.float32) rotation_matrices = np.zeros((2, 3, 3), dtype=np.float32) translations = np.zeros((2, 2), dtype=np.float32)
def iter_batches(self, batch_size, **kwargs): batch = np.zeros((2, 2), dtype=np.float32) particles_ind = np.array([0, 1], dtype=np.int32) batch_image_ind = np.array([0, 1], dtype=np.int32) yield ( batch, self.rotation_matrices[batch_image_ind], self.translations[batch_image_ind], self.CTF_params[batch_image_ind], None, particles_ind, batch_image_ind, )
monkeypatch.setattr(ia, "compute_residual", lambda *_args, **_kwargs: np.array([4.0, 9.0], dtype=np.float32)) vols = np.array([[1.0], [2.0]], dtype=np.float32) gamma = ia.estimate_false_positive_rate( _DS2(), vols, noise_variance=np.array([1.0]), batch_size=2, disc_type="nearest" )
expected_alphas = 0.5 * np.sqrt(np.array([4.0, 9.0])) expected_gamma = 1 - np.mean(scipy.stats.norm.cdf(expected_alphas)) assert np.isclose(gamma, expected_gamma)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296from types import SimpleNamespace
import numpy as npimport pandas as pdimport pytestfrom helpers import tiny_synthetic
from recovar.core import fourier_transform_utilsfrom recovar.data_io import image_backends
pytestmark = pytest.mark.unit
class _DummySource: def __init__(self, n=6, D=8): self.n = n self.D = D self._store = np.arange(n * D * D, dtype=np.float32).reshape(n, D, D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] if isinstance(index, slice): idx = np.arange(*index.indices(self.n)) return self._store[idx] return self._store[np.asarray(index)]
def test_particle_image_dataset_basic_getitem_and_preprocess(monkeypatch): monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _DummySource(n=4, D=8)) ds = image_backends.ParticleImageDataset("dummy.mrcs", lazy=True, invert_data=True)
imgs, p_idx, t_idx = ds[1] assert imgs.shape == (1, 8, 8) assert p_idx == 1 and t_idx == 1
processed = ds.process_images(imgs, apply_image_mask=False) assert processed.shape[0] == 1 assert processed.dtype == np.complex64
def test_particle_image_dataset_process_images_half_matches_legacy_full_fft_path(monkeypatch): monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _DummySource(n=4, D=8)) ds = image_backends.ParticleImageDataset("dummy.mrcs", lazy=True, invert_data=False)
imgs, _p_idx, _t_idx = ds[2] processed_full = ds.process_images(imgs, apply_image_mask=False) legacy_half = fourier_transform_utils.full_image_to_half_image(processed_full, ds.image_shape) processed_half = ds.process_images_half(imgs, apply_image_mask=False)
np.testing.assert_array_equal(processed_half, legacy_half)
def test_particle_image_dataset_data_multiplier_and_mult_share_state(monkeypatch): monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _DummySource(n=4, D=8)) ds = image_backends.ParticleImageDataset("dummy.mrcs", lazy=True, invert_data=False)
assert ds.data_multiplier == 1 assert ds.mult == 1 assert ds.invert_data is False
ds.mult = -1 assert ds.data_multiplier == -1 assert ds.invert_data is True
ds.data_multiplier = 1 assert ds.mult == 1 assert ds.invert_data is False
def test_particle_image_dataset_subset_generators_preserve_order_and_duplicates(monkeypatch): monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _DummySource(n=5, D=8)) ds = image_backends.ParticleImageDataset("dummy.mrcs", lazy=True, invert_data=False)
subset = np.array([3, 1, 3], dtype=np.int32) batches = list(ds.get_dataset_subset_generator(batch_size=2, subset_indices=subset)) got = [] for _imgs, _pidx, tidx in batches: got.extend(np.array(tidx).reshape(-1).tolist()) assert got == [3, 1, 3]
image_batches = list(ds.get_image_subset_generator(batch_size=2, subset_indices=subset)) got_img = [] for _imgs, _pidx, tidx in image_batches: got_img.extend(np.array(tidx).reshape(-1).tolist()) assert got_img == [3, 1, 3]
def test_particle_image_dataset_subset_generators_accept_boolean_mask(monkeypatch): monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _DummySource(n=5, D=8)) ds = image_backends.ParticleImageDataset("dummy.mrcs", lazy=True, invert_data=False)
mask = np.array([False, True, False, True, False], dtype=bool) batches = list(ds.get_dataset_subset_generator(batch_size=2, subset_indices=mask)) got = [] for _imgs, _pidx, tidx in batches: got.extend(np.array(tidx).reshape(-1).tolist()) assert got == [1, 3]
def test_particle_image_dataset_subset_generators_reject_invalid_masks(monkeypatch): monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _DummySource(n=5, D=8)) ds = image_backends.ParticleImageDataset("dummy.mrcs", lazy=True, invert_data=False)
with pytest.raises(ValueError, match="boolean mask must be 1D"): list(ds.get_dataset_subset_generator(batch_size=2, subset_indices=np.array([[True, False]], dtype=bool))) with pytest.raises(ValueError, match="must match total size"): list(ds.get_dataset_subset_generator(batch_size=2, subset_indices=np.array([True, False], dtype=bool))) with pytest.raises(IndexError, match="negative"): list(ds.get_dataset_subset_generator(batch_size=2, subset_indices=np.array([0, -1], dtype=np.int32))) with pytest.raises(IndexError, match="out-of-range"): list(ds.get_dataset_subset_generator(batch_size=2, subset_indices=np.array([5], dtype=np.int32)))
def test_tiltseries_parse_particle_tilt_and_reverse_map(monkeypatch): df = pd.DataFrame( { "_rlnGroupName": ["g2", "g1", "g2", "g1", "g3"], } ) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df)) p2t, t2p = image_backends.TiltSeriesDataset.parse_particle_tilt("dummy.star") assert len(p2t) == 3 # Canonical sorted groups: g1,g2,g3 assert np.all(p2t[0] == np.array([1, 3])) assert np.all(p2t[1] == np.array([0, 2])) assert np.all(p2t[2] == np.array([4])) assert t2p[1] == 0 and t2p[0] == 1 and t2p[4] == 2
def test_tiltseries_parse_particle_tilt_accepts_boolean_indices(monkeypatch): df = pd.DataFrame( { "_rlnGroupName": ["g2", "g1", "g2", "g1", "g3"], } ) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df)) mask = np.array([False, True, False, True, True], dtype=bool) p2t, t2p = image_backends.TiltSeriesDataset.parse_particle_tilt("dummy.star", indices=mask)
assert len(p2t) == 2 np.testing.assert_array_equal(p2t[0], np.array([1, 3], dtype=int)) # g1 np.testing.assert_array_equal(p2t[1], np.array([4], dtype=int)) # g3 assert t2p == {1: 0, 3: 0, 4: 1}
def test_tiltseries_parse_particle_tilt_rejects_bad_subset_indices(monkeypatch): df = pd.DataFrame( { "_rlnGroupName": ["g2", "g1", "g2", "g1", "g3"], } ) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
with pytest.raises(ValueError, match="must match total size"): image_backends.TiltSeriesDataset.parse_particle_tilt( "dummy.star", indices=np.array([True, False], dtype=bool), ) with pytest.raises(TypeError, match="integer indices or boolean mask"): image_backends.TiltSeriesDataset.parse_particle_tilt( "dummy.star", indices=np.array([0.0, 1.0], dtype=np.float32), )
def test_tiltseries_parse_particle_tilt_missing_group_column_raises(monkeypatch): df = pd.DataFrame({"_rlnImageName": ["1@a.mrcs", "2@a.mrcs"]}) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df)) with pytest.raises(ValueError, match="_rlnGroupName"): image_backends.TiltSeriesDataset.parse_particle_tilt("dummy.star")
def test_tiltseries_parse_micrograph_tilt_mapping(monkeypatch): df = pd.DataFrame( { "_rlnTiltName": ["tA", "tB", "tA", "tC"], } ) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df)) groups, reverse = image_backends.TiltSeriesDataset.parse_micrograph_tilt_mapping("dummy.star") assert len(groups) == 3 assert sorted(reverse.keys()) == [0, 1, 2, 3]
def test_tiltseries_parse_micrograph_tilt_mapping_relion5_micrograph_fallback(monkeypatch): df = pd.DataFrame( { "_rlnMicrographName": ["mic_a.mrc", "mic_a.mrc", "mic_b.mrc"], } ) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df)) groups, reverse = image_backends.TiltSeriesDataset.parse_micrograph_tilt_mapping("dummy.star") assert [group.tolist() for group in groups] == [[0, 1], [2]] assert reverse == {0: 0, 1: 0, 2: 1}
def test_tiltseries_parse_micrograph_tilt_mapping_missing_column(monkeypatch): df = pd.DataFrame({"foo": [1, 2, 3]}) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df)) with pytest.raises(ValueError, match="No tilt name column found"): image_backends.TiltSeriesDataset.parse_micrograph_tilt_mapping("dummy.star")
def test_image_count_batch_loader_batches_and_padding(): class _FakeTiltDataset: def __init__(self): self.particle_groups = {"a": np.array([0, 1]), "b": np.array([2]), "c": np.array([3, 4, 5])} self.num_tilts = None
def __len__(self): return 3
def __getitem__(self, idx): groups = [np.array([0, 1]), np.array([2]), np.array([3, 4, 5])] t = groups[idx] imgs = np.ones((len(t), 8, 8), dtype=np.float32) * (idx + 1) return imgs, idx, t
loader = image_backends._ImageCountBatchLoader(_FakeTiltDataset(), batch_size=4, pad_to_batch=True) batches = list(loader) assert len(batches) >= 1 b0_img, b0_pid, b0_tid = batches[0] assert b0_img.shape[0] == 4 assert b0_pid.shape[0] == 4 assert b0_tid.shape[0] == 4
def test_image_count_batch_loader_rejects_nonpositive_or_noninteger_batch_size(): class _FakeTiltDataset: def __init__(self): self.particle_groups = {"a": np.array([0, 1])} self.num_tilts = None
def __len__(self): return 1
def __getitem__(self, idx): _ = idx imgs = np.ones((2, 8, 8), dtype=np.float32) t = np.array([0, 1], dtype=np.int32) return imgs, 0, t
with pytest.raises(ValueError, match="batch_size must be positive"): image_backends._ImageCountBatchLoader(_FakeTiltDataset(), batch_size=0, pad_to_batch=False) with pytest.raises(ValueError, match="batch_size must be positive"): image_backends._ImageCountBatchLoader(_FakeTiltDataset(), batch_size=-3, pad_to_batch=False) with pytest.raises(TypeError, match="batch_size must be an integer"): image_backends._ImageCountBatchLoader(_FakeTiltDataset(), batch_size=2.5, pad_to_batch=False)
def test_image_count_batch_loader_handles_oversized_single_particle(): class _OversizedDataset: def __init__(self): self.particle_groups = {"a": np.arange(5)} self.num_tilts = None
def __len__(self): return 1
def __getitem__(self, idx): imgs = np.ones((5, 8, 8), dtype=np.float32) t = np.arange(5, dtype=np.int32) return imgs, idx, t
loader = image_backends._ImageCountBatchLoader(_OversizedDataset(), batch_size=2, pad_to_batch=False) batches = list(loader) assert len(batches) == 1 imgs, pidx, tidx = batches[0] assert imgs.shape[0] == 5 np.testing.assert_array_equal(pidx, np.zeros(5, dtype=np.int32)) np.testing.assert_array_equal(tidx, np.arange(5, dtype=np.int32))
def test_image_count_batch_loader_padding_marks_invalid_entries(): class _TinyTiltDataset: def __init__(self): self.particle_groups = {"a": np.array([0]), "b": np.array([1])} self.num_tilts = None
def __len__(self): return 2
def __getitem__(self, idx): imgs = np.ones((1, 8, 8), dtype=np.float32) return imgs, idx, np.array([idx], dtype=np.int32)
loader = image_backends._ImageCountBatchLoader(_TinyTiltDataset(), batch_size=3, pad_to_batch=True) imgs, pidx, tidx = next(iter(loader)) assert imgs.shape[0] == 3 np.testing.assert_array_equal(pidx, np.array([0, 1, -1], dtype=np.int32)) np.testing.assert_array_equal(tidx, np.array([0, 1, -1], dtype=np.int32))
def test_image_count_batch_loader_skips_zero_image_particles(): class _SparseTiltDataset: def __init__(self): self.particle_groups = { "p0": np.array([], dtype=np.int32), # 0 selected "p1": np.array([10, 11], dtype=np.int32), # 2 selected "p2": np.array([], dtype=np.int32), # 0 selected "p3": np.array([30], dtype=np.int32), # 1 selected } self.num_tilts = None
def __len__(self): return 4
def __getitem__(self, idx): tilts = list(self.particle_groups.values())[int(idx)] images = np.ones((len(tilts), 8, 8), dtype=np.float32) * (int(idx) + 1) return images, int(idx), tilts
loader = image_backends._ImageCountBatchLoader(_SparseTiltDataset(), batch_size=2, pad_to_batch=False)
assert loader.total_images == 3 assert len(loader) == 2
batches = list(loader) assert len(batches) == len(loader) np.testing.assert_array_equal( [np.asarray(batch[0]).shape[0] for batch in batches], np.array([2, 1], dtype=np.int32), ) emitted_particles = np.concatenate([np.asarray(b[1]).reshape(-1) for b in batches], axis=0) np.testing.assert_array_equal(emitted_particles, np.array([1, 1, 3], dtype=np.int32))
def test_image_count_batch_loader_all_zero_particles_emits_no_batches(): class _AllZeroTiltDataset: def __init__(self): self.particle_groups = { "p0": np.array([], dtype=np.int32), "p1": np.array([], dtype=np.int32), } self.num_tilts = None
def __len__(self): return 2
def __getitem__(self, idx): _ = idx return ( np.zeros((0, 8, 8), dtype=np.float32), -1, np.zeros((0,), dtype=np.int32), )
loader = image_backends._ImageCountBatchLoader(_AllZeroTiltDataset(), batch_size=3, pad_to_batch=True) assert loader.total_images == 0 assert len(loader) == 0 assert list(loader) == []
def test_image_count_batch_loader_subset_wrapper_preserves_duplicate_parent_mapping(): class _ParentTiltDataset: def __init__(self): self._particle_tilts = [ np.array([10, 11], dtype=np.int32), # 2 images np.array([20, 21, 22], dtype=np.int32), # 3 images np.array([30], dtype=np.int32), # 1 image ] self.num_tilts = None
def __len__(self): return len(self._particle_tilts)
def __getitem__(self, idx): tilt_ids = self._particle_tilts[int(idx)] images = np.ones((len(tilt_ids), 8, 8), dtype=np.float32) * (idx + 1) return images, int(idx), tilt_ids
parent = _ParentTiltDataset() # Exercise Subset path with duplicate/reordered parent indices: [2, 0, 2]. subset = image_backends._SimpleSubset(parent, [2, 0, 2]) loader = image_backends._ImageCountBatchLoader(subset, batch_size=3, pad_to_batch=False)
assert loader.total_images == 4 # 1 + 2 + 1 assert len(loader) == 2
batches = list(loader) assert len(batches) == len(loader)
emitted_particles = np.concatenate([np.asarray(b[1]).reshape(-1) for b in batches], axis=0) emitted_tilts = np.concatenate([np.asarray(b[2]).reshape(-1) for b in batches], axis=0)
np.testing.assert_array_equal(emitted_particles, np.array([2, 0, 0, 2], dtype=np.int32)) np.testing.assert_array_equal(emitted_tilts, np.array([30, 10, 11, 30], dtype=np.int32))
def test_image_count_batch_loader_subset_wrapper_uses_parent_num_tilts_cap(): class _ParentTiltDataset: def __init__(self): self._particle_tilts = [ np.array([0, 1, 2], dtype=np.int32), np.array([10, 11], dtype=np.int32), ] self.num_tilts = 1
def __len__(self): return len(self._particle_tilts)
def __getitem__(self, idx): tilt_ids = self._particle_tilts[int(idx)] tilt_ids = tilt_ids[: self.num_tilts] images = np.ones((len(tilt_ids), 8, 8), dtype=np.float32) return images, int(idx), tilt_ids
subset = image_backends._SimpleSubset(_ParentTiltDataset(), [0, 1, 0]) loader = image_backends._ImageCountBatchLoader(subset, batch_size=2, pad_to_batch=False)
assert loader.total_images == 3 assert len(loader) == 2 batches = list(loader) assert len(batches) == len(loader) emitted_tilts = np.concatenate([np.asarray(b[2]).reshape(-1) for b in batches], axis=0) np.testing.assert_array_equal(emitted_tilts, np.array([0, 10, 0], dtype=np.int32))
def test_image_count_batch_loader_nested_subset_wrapper_preserves_mapping_and_duplicates(): class _ParentTiltDataset: def __init__(self): self._particle_tilts = [ np.array([0, 1], dtype=np.int32), # 2 images np.array([10], dtype=np.int32), # 1 image np.array([20, 21, 22], dtype=np.int32), # 3 images np.array([30], dtype=np.int32), # 1 image ] self.num_tilts = None
def __len__(self): return len(self._particle_tilts)
def __getitem__(self, idx): tilt_ids = self._particle_tilts[int(idx)] images = np.ones((len(tilt_ids), 8, 8), dtype=np.float32) * (int(idx) + 1) return images, int(idx), tilt_ids
parent = _ParentTiltDataset() subset_lvl1 = image_backends._SimpleSubset(parent, [3, 1, 0]) # maps local->[3,1,0] subset_lvl2 = image_backends._SimpleSubset(subset_lvl1, [2, 0, 2]) # maps to base [0,3,0]
loader = image_backends._ImageCountBatchLoader(subset_lvl2, batch_size=3, pad_to_batch=False)
assert loader.total_images == 5 # base[0]=2 + base[3]=1 + base[0]=2 assert len(loader) == 2
batches = list(loader) assert len(batches) == len(loader) emitted_particles = np.concatenate([np.asarray(b[1]).reshape(-1) for b in batches], axis=0) emitted_tilts = np.concatenate([np.asarray(b[2]).reshape(-1) for b in batches], axis=0) np.testing.assert_array_equal(emitted_particles, np.array([0, 0, 3, 0, 0], dtype=np.int32)) np.testing.assert_array_equal(emitted_tilts, np.array([0, 1, 30, 0, 1], dtype=np.int32))
def test_max_tilts_per_dataset_view_uses_parent_particle_tilts_without_particle_groups(): class _ParentTiltDataset: def __init__(self): self._particle_tilts = [ np.array([0, 1, 2], dtype=np.int32), np.array([10, 11], dtype=np.int32), ] self.num_tilts = 2
def __len__(self): return len(self._particle_tilts)
def __getitem__(self, idx): tilt_ids = self._particle_tilts[int(idx)][: self.num_tilts] images = np.ones((len(tilt_ids), 8, 8), dtype=np.float32) return images, int(idx), tilt_ids
subset = image_backends._SimpleSubset(_ParentTiltDataset(), np.array([1, 0, 1], dtype=np.int32)) assert image_backends._max_tilts_per_dataset_view(subset) == 2
def test_max_tilts_per_dataset_view_respects_zero_num_tilts(): class _ParentTiltDataset: def __init__(self): self._particle_tilts = [ np.array([0, 1, 2], dtype=np.int32), np.array([10, 11], dtype=np.int32), ] self.num_tilts = 0
def __len__(self): return len(self._particle_tilts)
def __getitem__(self, idx): _ = idx return np.zeros((0, 8, 8), dtype=np.float32), int(idx), np.zeros((0,), dtype=np.int32)
subset = image_backends._SimpleSubset(_ParentTiltDataset(), np.array([1, 0, 1], dtype=np.int32)) assert image_backends._max_tilts_per_dataset_view(subset) == 0
def test_max_tilts_per_dataset_view_raises_when_parent_has_no_group_metadata(): class _ParentNoGroups: num_tilts = None
def __len__(self): return 2
def __getitem__(self, idx): images = np.ones((1, 8, 8), dtype=np.float32) return images, int(idx), np.array([int(idx)], dtype=np.int32)
subset = image_backends._SimpleSubset(_ParentNoGroups(), np.array([0], dtype=np.int32)) with pytest.raises(AttributeError, match="must expose _particle_tilts"): image_backends._max_tilts_per_dataset_view(subset)
def test_image_count_batch_loader_rejects_dataset_without_group_metadata(): class _NoGroupDataset: num_tilts = None
def __len__(self): return 1
def __getitem__(self, idx): return np.ones((1, 8, 8), dtype=np.float32), int(idx), np.array([0], dtype=np.int32)
with pytest.raises(AttributeError, match="must expose _particle_tilts"): image_backends._ImageCountBatchLoader(_NoGroupDataset(), batch_size=2, pad_to_batch=False)
def test_tiltseries_dataset_getitem_deterministic_selection(monkeypatch): class _Source: def __init__(self): self.n = 6 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g1", "g2", "g2", "g2"], "_rlnMicrographPreExposure": [1.0, 3.0, 2.0, 2.0, 5.0, 1.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -2, -3, -4, -5, -6], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=2, random_tilts=False, tilt_file_option="relion5") imgs, pidx, selected = ds[0]
assert pidx == 0 assert imgs.shape == (2, 8, 8) assert selected.shape == (2,) # Deterministic order induced by _compute_tilt_ordering implementation. np.testing.assert_array_equal(selected, np.array([0, 2]))
def test_tiltseries_dataset_random_selection_clamps_when_num_tilts_exceeds_available(monkeypatch): class _Source: def __init__(self): self.n = 5 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2", "g2"], "_rlnMicrographPreExposure": [1.0, 2.0, 1.0, 2.0, 3.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1.0, -2.0, -3.0, -4.0, -5.0], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
np.random.seed(0) ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=10, random_tilts=True, tilt_file_option="relion5")
# g1 has only 2 tilts; should clamp instead of raising from np.random.choice. imgs0, pidx0, selected0 = ds[0] assert pidx0 == 0 assert len(selected0) == 2 assert len(np.unique(selected0)) == 2 np.testing.assert_allclose(imgs0, _Source()._store[selected0])
# g2 has 3 tilts; clamp there as well. imgs1, pidx1, selected1 = ds[1] assert pidx1 == 1 assert len(selected1) == 3 assert len(np.unique(selected1)) == 3 np.testing.assert_allclose(imgs1, _Source()._store[selected1])
def test_tiltseries_dataset_negative_num_tilts_matches_all_tilts(monkeypatch): class _Source: def __init__(self): self.n = 6 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g1", "g2", "g2", "g2"], "_rlnMicrographPreExposure": [1.0, 3.0, 2.0, 2.0, 5.0, 1.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -2, -3, -4, -5, -6], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds_all = image_backends.TiltSeriesDataset( "dummy.star", num_tilts=None, random_tilts=False, tilt_file_option="relion5" ) ds_neg = image_backends.TiltSeriesDataset( "dummy.star", num_tilts=-1, random_tilts=False, tilt_file_option="relion5" )
assert ds_neg.num_tilts is None for pidx in range(len(ds_all)): _imgs_all, _pid_all, sel_all = ds_all[pidx] _imgs_neg, _pid_neg, sel_neg = ds_neg[pidx] np.testing.assert_array_equal(sel_neg, sel_all)
def test_tiltseries_dataset_non_integer_num_tilts_raises(monkeypatch): class _Source: def __init__(self): self.n = 2 self.D = 8 self._store = np.zeros((2, 8, 8), dtype=np.float32)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1"], "_rlnMicrographPreExposure": [1.0, 2.0], "_rlnCtfScalefactor": [1, 1], "_rlnCtfBfactor": [-1, -1], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
with pytest.raises(TypeError, match="num_tilts must be an integer or None"): image_backends.TiltSeriesDataset("dummy.star", num_tilts=1.5, random_tilts=False, tilt_file_option="relion5")
def test_tiltseries_dataset_getitem_deterministic_selection_warp(monkeypatch): class _Source: def __init__(self): self.n = 4 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g1", "g2"], "_rlnMicrographPreExposure": [1.0, 2.0, 3.0, 4.0], "_rlnCtfScalefactor": [1, 1, 1, 1], "_rlnCtfBfactor": [-5.0, -1.0, -3.0, -2.0], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=2, random_tilts=False, tilt_file_option="warp") _imgs, pidx, selected = ds[0] assert pidx == 0 # Stable expectation from current B-factor ordering implementation. np.testing.assert_array_equal(selected, np.array([1, 2]))
def test_particle_image_backend_getitem_returns_single_image_tuple(monkeypatch): class _Source: def __init__(self): self.n = 3 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2"], "_rlnMicrographPreExposure": [1.0, 2.0, 3.0], "_rlnCtfScalefactor": [1, 1, 1], "_rlnCtfBfactor": [-1.0, -2.0, -3.0], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df)) ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=None, random_tilts=False, tilt_file_option="relion5") img, pidx, tidx = image_backends.ParticleImageDataset.__getitem__(ds, 2) assert img.shape == (1, 8, 8) assert pidx == 2 assert tidx == 2
def test_tiltseries_dataset_images_mode_batch_size_validation(monkeypatch): class _Source: def __init__(self): self.n = 4 self.D = 8 self._store = np.zeros((self.n, self.D, self.D), dtype=np.float32)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g1", "g2"], "_rlnMicrographPreExposure": [1.0, 2.0, 3.0, 4.0], "_rlnCtfScalefactor": [1, 1, 1, 1], "_rlnCtfBfactor": [-1, -1, -1, -1], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=None, random_tilts=False, tilt_file_option="relion5") # max tilts per particle is 3; batch_size=2 should fail in images mode. with pytest.raises(ValueError, match="Batch size"): ds.get_dataset_generator(batch_size=2, mode="images")
def test_tiltseries_subset_generator_images_mode_batch_size_validation(monkeypatch): class _Source: def __init__(self): self.n = 5 self.D = 8 self._store = np.zeros((self.n, self.D, self.D), dtype=np.float32)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g1", "g2", "g2"], "_rlnMicrographPreExposure": [1.0, 2.0, 3.0, 4.0, 5.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -1, -1, -1, -1], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=None, random_tilts=False, tilt_file_option="relion5") # Subset includes particle g1 with 3 tilts; batch_size=2 should fail for images mode. with pytest.raises(ValueError, match="Batch size"): ds.get_dataset_subset_generator(batch_size=2, subset_indices=np.array([0], dtype=np.int32), mode="images")
def test_tilt_series_generator_forces_batch_size_one(monkeypatch): class _Source: def __init__(self): self.n = 4 self.D = 8 self._store = np.zeros((self.n, self.D, self.D), dtype=np.float32)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2"], "_rlnMicrographPreExposure": [1.0, 2.0, 3.0, 4.0], "_rlnCtfScalefactor": [1, 1, 1, 1], "_rlnCtfBfactor": [-1, -1, -1, -1], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=1, random_tilts=False, tilt_file_option="relion5") loader = ds.get_dataset_generator(batch_size=99, mode="tilt_series") assert loader.batch_size == 1
def test_tiltseries_dataset_invalid_mode_raises(monkeypatch): class _Source: def __init__(self): self.n = 2 self.D = 8 self._store = np.zeros((2, 8, 8), dtype=np.float32)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1"], "_rlnMicrographPreExposure": [1.0, 2.0], "_rlnCtfScalefactor": [1, 1], "_rlnCtfBfactor": [-1, -1], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df)) ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=1, random_tilts=False, tilt_file_option="relion5") with pytest.raises(ValueError, match="Invalid mode"): ds.get_dataset_generator(batch_size=2, mode="bad_mode")
def test_tiltseries_dataset_invalid_tilt_file_option_raises(monkeypatch): class _Source: def __init__(self): self.n = 2 self.D = 8 self._store = np.zeros((2, 8, 8), dtype=np.float32)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1"], "_rlnMicrographPreExposure": [1.0, 2.0], "_rlnCtfScalefactor": [1, 1], "_rlnCtfBfactor": [-1, -1], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df)) with pytest.raises(ValueError, match="Invalid tilt ordering method"): image_backends.TiltSeriesDataset("dummy.star", num_tilts=1, random_tilts=False, tilt_file_option="bad")
def test_tiltseries_dataset_missing_group_column_raises(monkeypatch): class _Source: def __init__(self): self.n = 2 self.D = 8 self._store = np.zeros((2, 8, 8), dtype=np.float32)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnMicrographPreExposure": [1.0, 2.0], "_rlnCtfScalefactor": [1.0, 1.0], "_rlnCtfBfactor": [-1.0, -1.0], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
with pytest.raises(ValueError, match="_rlnGroupName"): image_backends.TiltSeriesDataset("dummy.star", num_tilts=1, random_tilts=False, tilt_file_option="relion5")
def test_tiltseries_image_subset_generator_none_matches_full(monkeypatch): class _Source: def __init__(self): self.n = 4 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2"], "_rlnMicrographPreExposure": [1.0, 2.0, 3.0, 4.0], "_rlnCtfScalefactor": [1, 1, 1, 1], "_rlnCtfBfactor": [-1, -1, -1, -1], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df)) ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=1, random_tilts=False, tilt_file_option="relion5") full = list(ds.get_image_generator(batch_size=2)) none_subset = list(ds.get_image_subset_generator(batch_size=2, subset_indices=None)) assert len(full) == len(none_subset) for a, b in zip(full, none_subset): np.testing.assert_array_equal(np.array(a[2]), np.array(b[2]))
def test_collate_to_jax_handles_none_scalar_ndarray_and_nested_sequences(): # ndarray branch arr = [np.ones((1, 2), dtype=np.float32), np.zeros((1, 2), dtype=np.float32)] out = image_backends._collate_batch_to_jax(arr) np.testing.assert_array_equal(np.array(out), np.array([[1.0, 1.0], [0.0, 0.0]], dtype=np.float32))
# scalar branch out_scalar = image_backends._collate_batch_to_jax([1, 2, 3]) np.testing.assert_array_equal(np.array(out_scalar), np.array([1, 2, 3]))
# none branch assert image_backends._collate_batch_to_jax(None) is None
# tuple/list recursion branch nested = [ (np.ones((1, 1), dtype=np.float32), np.array([5], dtype=np.int32)), (np.zeros((1, 1), dtype=np.float32), np.array([7], dtype=np.int32)), ] out_nested = image_backends._collate_batch_to_jax(nested) assert isinstance(out_nested, list) np.testing.assert_array_equal(np.array(out_nested[0]), np.array([[1.0], [0.0]], dtype=np.float32)) np.testing.assert_array_equal(np.array(out_nested[1]), np.array([5, 7], dtype=np.int32))
def test_collate_to_jax_single_numpy_batch_skips_concatenate(monkeypatch): arr = np.arange(6, dtype=np.float32).reshape(1, 2, 3) monkeypatch.setattr( image_backends.np, "concatenate", lambda *_args, **_kwargs: (_ for _ in ()).throw( AssertionError("single-item fast path should skip concatenate") ), )
out = image_backends._collate_batch_to_jax([arr]) np.testing.assert_array_equal(np.array(out), arr)
def test_tiltseries_subset_generator_preserves_subset_order_and_duplicates(monkeypatch): class _Source: def __init__(self): self.n = 6 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2", "g3", "g3"], "_rlnMicrographPreExposure": [1.0, 2.0, 1.0, 2.0, 1.0, 2.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -2, -1, -2, -1, -2], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=1, random_tilts=False, tilt_file_option="relion5") subset_indices = np.array([2, 0, 2], dtype=np.int32) loader = ds.get_dataset_subset_generator(batch_size=8, subset_indices=subset_indices, mode="tilt_series") batches = list(loader)
# Tilt-series iteration remains particle-at-a-time. assert len(batches) == 3 out_particle_ids = [int(np.array(b[1]).reshape(-1)[0]) for b in batches] out_tilt_ids = [int(np.array(b[2]).reshape(-1)[0]) for b in batches] assert out_particle_ids == [2, 0, 2] # For this deterministic setup with num_tilts=1 and relion5 ordering. assert out_tilt_ids == [4, 0, 4]
def test_tiltseries_subset_generator_accepts_boolean_particle_mask(monkeypatch): class _Source: def __init__(self): self.n = 6 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2", "g3", "g3"], "_rlnMicrographPreExposure": [1.0, 2.0, 1.0, 2.0, 1.0, 2.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -2, -1, -2, -1, -2], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=1, random_tilts=False, tilt_file_option="relion5") particle_mask = np.array([True, False, True], dtype=bool) loader = ds.get_dataset_subset_generator(batch_size=8, subset_indices=particle_mask, mode="tilt_series") batches = list(loader) out_particle_ids = [int(np.array(b[1]).reshape(-1)[0]) for b in batches] assert out_particle_ids == [0, 2]
def test_tiltseries_subset_generator_images_mode_accepts_boolean_particle_mask(monkeypatch): class _Source: def __init__(self): self.n = 6 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2", "g3", "g3"], "_rlnMicrographPreExposure": [1.0, 2.0, 1.0, 2.0, 1.0, 2.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -2, -1, -2, -1, -2], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=1, random_tilts=False, tilt_file_option="relion5") particle_mask = np.array([True, False, True], dtype=bool) loader = ds.get_dataset_subset_generator(batch_size=4, subset_indices=particle_mask, mode="images") batches = list(loader)
emitted_particles = np.concatenate([np.asarray(b[1]).reshape(-1) for b in batches], axis=0) # num_tilts=1 means one emitted image per selected particle. np.testing.assert_array_equal(np.sort(emitted_particles), np.array([0, 2], dtype=np.int32))
def test_tiltseries_subset_generator_rejects_bad_particle_masks(monkeypatch): class _Source: def __init__(self): self.n = 6 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2", "g3", "g3"], "_rlnMicrographPreExposure": [1.0, 2.0, 1.0, 2.0, 1.0, 2.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -2, -1, -2, -1, -2], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=1, random_tilts=False, tilt_file_option="relion5") with pytest.raises(ValueError, match="boolean mask must be 1D"): list( ds.get_dataset_subset_generator( batch_size=8, subset_indices=np.array([[True, False, True]], dtype=bool), mode="tilt_series" ) ) with pytest.raises(ValueError, match="must match total size"): list( ds.get_dataset_subset_generator( batch_size=8, subset_indices=np.array([True, False], dtype=bool), mode="tilt_series" ) ) with pytest.raises(IndexError, match="negative"): list( ds.get_dataset_subset_generator( batch_size=8, subset_indices=np.array([-1], dtype=np.int32), mode="tilt_series" ) )
def test_tiltseries_image_subset_generator_preserves_requested_image_order_and_duplicates(monkeypatch): class _Source: def __init__(self): self.n = 5 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2", "g3"], "_rlnMicrographPreExposure": [1.0, 2.0, 1.0, 2.0, 1.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -2, -1, -2, -1], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=None, random_tilts=False, tilt_file_option="relion5") subset_indices = np.array([3, 1, 3], dtype=np.int32) loader = ds.get_image_subset_generator(batch_size=2, subset_indices=subset_indices) batches = list(loader)
got = [] for _imgs, _pidx, tidx in batches: got.extend(np.array(tidx).reshape(-1).tolist()) assert got == [3, 1, 3]
def test_tiltseries_image_subset_generator_accepts_boolean_image_mask(monkeypatch): class _Source: def __init__(self): self.n = 5 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2", "g3"], "_rlnMicrographPreExposure": [1.0, 2.0, 1.0, 2.0, 1.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -2, -1, -2, -1], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=None, random_tilts=False, tilt_file_option="relion5") mask = np.array([False, True, False, True, False], dtype=bool) loader = ds.get_image_subset_generator(batch_size=2, subset_indices=mask) batches = list(loader) got = [] for _imgs, _pidx, tidx in batches: got.extend(np.array(tidx).reshape(-1).tolist()) assert got == [1, 3]
def test_tiltseries_image_subset_generator_rejects_bad_image_masks(monkeypatch): class _Source: def __init__(self): self.n = 5 self.D = 8 self._store = np.arange(self.n * self.D * self.D, dtype=np.float32).reshape(self.n, self.D, self.D)
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2", "g3"], "_rlnMicrographPreExposure": [1.0, 2.0, 1.0, 2.0, 1.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -2, -1, -2, -1], } ) monkeypatch.setattr(image_backends.ImageLoader, "from_file", lambda *args, **kwargs: _Source()) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
ds = image_backends.TiltSeriesDataset("dummy.star", num_tilts=None, random_tilts=False, tilt_file_option="relion5") with pytest.raises(ValueError, match="boolean mask must be 1D"): list(ds.get_image_subset_generator(batch_size=2, subset_indices=np.array([[True, False]], dtype=bool))) with pytest.raises(ValueError, match="must match total size"): list(ds.get_image_subset_generator(batch_size=2, subset_indices=np.array([True, False], dtype=bool))) with pytest.raises(IndexError, match="out-of-range"): list(ds.get_image_subset_generator(batch_size=2, subset_indices=np.array([9], dtype=np.int32)))
def test_tiltseries_dataset_ind_subset_preserves_image_tilt_alignment(monkeypatch): class _Source: def __init__(self, indices=None): base_n = 6 self.D = 8 full = np.arange(base_n * self.D * self.D, dtype=np.float32).reshape(base_n, self.D, self.D) if indices is None: self._store = full else: self._store = full[np.asarray(indices)] self.n = self._store.shape[0]
def images(self, index, require_contiguous=False): _ = require_contiguous if isinstance(index, (int, np.integer)): return self._store[int(index)] return self._store[np.asarray(index)]
df = pd.DataFrame( { "_rlnGroupName": ["g1", "g1", "g2", "g2", "g3", "g3"], "_rlnMicrographPreExposure": [1.0, 2.0, 1.0, 2.0, 5.0, 6.0], "_rlnCtfScalefactor": [1, 1, 1, 1, 1, 1], "_rlnCtfBfactor": [-1, -2, -1, -2, -1, -2], } ) monkeypatch.setattr( image_backends.ImageLoader, "from_file", lambda *_args, **kwargs: _Source(indices=kwargs.get("indices")), ) monkeypatch.setattr(image_backends.starfile.StarFile, "load", lambda _p: SimpleNamespace(df=df))
# Reordered subset over original row indices. subset = np.array([5, 2, 4, 1], dtype=np.int32) ds = image_backends.TiltSeriesDataset( "dummy.star", ind=subset, num_tilts=1, random_tilts=False, tilt_file_option="relion5" ) assert ds.dataset_tilt_indices == [0, 1, 2]
# Direct image fetch should map to subset-local order: local 0 == original 5. img0, _pidx0, tidx0 = image_backends.ParticleImageDataset.__getitem__(ds, 0) assert int(tidx0) == 0 np.testing.assert_array_equal(img0[0], ds.source._store[0])
# For g3 in subset (locals 0 and 2), relion5 ordering picks lower dose first -> local 2. imgs, particle_idx, selected = ds[2] # canonical order: g1, g2, g3 assert int(particle_idx) == 2 np.testing.assert_array_equal(selected, np.array([2], dtype=np.int32)) np.testing.assert_array_equal(imgs[0], ds.source._store[2])
def test_parse_particle_tilt_real_tiny_star_preserves_original_indices_with_subset(tmp_path): files = tiny_synthetic.make_tiny_loader_files(tmp_path, grid_size=8, n_images=6, n_particles=3) subset = np.array([5, 1, 4], dtype=np.int32)
p2t, t2p = image_backends.TiltSeriesDataset.parse_particle_tilt(files["particles_star"], indices=subset)
# Original STAR groups are cyclic: g1,g2,g3,g1,g2,g3. # Keeping rows [5,1,4] leaves groups g2:[1,4], g3:[5] in canonical order. np.testing.assert_array_equal(p2t[0], np.array([1, 4], dtype=np.int32)) np.testing.assert_array_equal(p2t[1], np.array([5], dtype=np.int32)) assert t2p[1] == 0 and t2p[4] == 0 and t2p[5] == 1
def test_parse_particle_tilt_real_tiny_star_subset_with_duplicate_tilt_indices(tmp_path): files = tiny_synthetic.make_tiny_loader_files(tmp_path, grid_size=8, n_images=6, n_particles=3) subset = np.array([5, 1, 5, 4], dtype=np.int32)
p2t, t2p = image_backends.TiltSeriesDataset.parse_particle_tilt(files["particles_star"], indices=subset)
# Groups after subset are g2:[1,4] and g3:[5,5], preserving duplicate tilt requests. np.testing.assert_array_equal(p2t[0], np.array([1, 4], dtype=np.int32)) np.testing.assert_array_equal(p2t[1], np.array([5, 5], dtype=np.int32)) assert t2p[1] == 0 and t2p[4] == 0 and t2p[5] == 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980import numpy as npimport pandas as pdimport pytestfrom pathlib import Path
from recovar.data_io import image_loaderfrom recovar.data_io import starfilefrom recovar import utilsfrom recovar.data_io import image_backends as cryo_dataset
pytestmark = pytest.mark.unit
class _DummyLoader(image_loader.ImageLoader): def __init__(self, n=6, D=4, dtype=np.float32): super().__init__(n, D, dtype=dtype) self._store = np.arange(n * D * D, dtype=dtype).reshape(n, D, D)
def _load(self, indices: np.ndarray) -> np.ndarray: return self._store[indices]
def test_load_images_rejects_unknown_extension(): with pytest.raises(ValueError, match="Unsupported format"): image_loader.load_images("particles.unknown")
def test_parse_indices_int_slice_array_and_bool(): loader = _DummyLoader(n=8, D=2) parsed_none = loader._parse_indices(None) assert parsed_none.dtype == np.int32 assert np.all(parsed_none == np.arange(8))
parsed_int = loader._parse_indices(3) assert parsed_int.dtype == np.int32 assert np.all(parsed_int == np.array([3]))
parsed_slice = loader._parse_indices(slice(2, 6, 2)) assert parsed_slice.dtype == np.int32 assert np.all(parsed_slice == np.array([2, 4]))
parsed_array = loader._parse_indices(np.array([1, 5], dtype=np.int32)) assert parsed_array.dtype == np.int32 assert np.all(parsed_array == np.array([1, 5]))
parsed_bool = loader._parse_indices(np.array([True, False, True, False, False, False, False, False])) assert parsed_bool.dtype == np.int32 assert np.all(parsed_bool == np.array([0, 2]))
def test_parse_indices_rejects_non_1d_arrays_and_bad_boolean_masks(): loader = _DummyLoader(n=4, D=2) with pytest.raises(ValueError, match="Indices array must be 1D"): loader._parse_indices(np.array([[0, 1], [2, 3]], dtype=np.int32))
with pytest.raises(ValueError, match="Boolean indices must be a 1D mask"): loader._parse_indices(np.array([[True, False], [False, True]], dtype=bool))
with pytest.raises(ValueError, match="must match number of images"): loader._parse_indices(np.array([True, False], dtype=bool))
def test_parse_indices_rejects_non_integer_ndarray(): loader = _DummyLoader(n=4, D=2) with pytest.raises(TypeError, match="integer or bool dtype"): loader._parse_indices(np.array([0.0, 1.0], dtype=np.float32))
def test_get_and_cached_loading_and_iter_batches(): loader = _DummyLoader(n=5, D=3, dtype=np.float32) out = loader.get([1, 3]) assert out.shape == (2, 3, 3) # Load cache and ensure get uses it. loader.load_all() out2 = loader.get(np.array([0, 4], dtype=np.int32)) assert np.allclose(out2, loader._store[[0, 4]])
batches = list(loader.iter_batches(batch_size=2)) assert len(batches) == 3 idx0, imgs0 = batches[0] assert np.all(idx0 == np.array([0, 1])) assert imgs0.shape == (2, 3, 3) # Compatibility alias. chunk0 = next(loader.chunks(chunksize=2)) np.testing.assert_array_equal(chunk0[0], np.array([0, 1]))
def test_mrc_loader_reads_real_file_sequential_and_random(tmp_path): data = np.arange(5 * 4 * 4, dtype=np.float32).reshape(5, 4, 4) mrc_path = tmp_path / "particles.mrcs" utils.write_mrc(str(mrc_path), data)
loader = image_loader.MRCLoader(str(mrc_path), lazy=True) seq = loader.get(np.array([0, 1, 2], dtype=np.int32)) rnd = loader.get(np.array([4, 2, 0], dtype=np.int32)) assert seq.shape == (3, 4, 4) assert rnd.shape == (3, 4, 4) np.testing.assert_allclose(seq, data[[0, 1, 2]]) np.testing.assert_allclose(rnd, data[[4, 2, 0]])
def test_mrc_loader_duplicate_indices_preserve_order_and_duplicates(tmp_path): data = np.arange(5 * 4 * 4, dtype=np.float32).reshape(5, 4, 4) mrc_path = tmp_path / "particles.mrcs" utils.write_mrc(str(mrc_path), data)
loader = image_loader.MRCLoader(str(mrc_path), lazy=True) req = np.array([4, 2, 4, 0], dtype=np.int32) out = loader.get(req) np.testing.assert_allclose(out, data[req])
def test_mrc_loader_empty_request_returns_empty_batch(tmp_path): data = np.arange(5 * 4 * 4, dtype=np.float32).reshape(5, 4, 4) mrc_path = tmp_path / "particles.mrcs" utils.write_mrc(str(mrc_path), data)
loader = image_loader.MRCLoader(str(mrc_path), lazy=True) out = loader.get(np.array([], dtype=np.int32)) assert out.shape == (0, 4, 4) assert out.dtype == data.dtype
def test_mrc_loader_deduplicates_disk_reads_for_duplicate_indices(monkeypatch, tmp_path): data = np.arange(6 * 4 * 4, dtype=np.float32).reshape(6, 4, 4) mrc_path = tmp_path / "particles.mrcs" utils.write_mrc(str(mrc_path), data)
loader = image_loader.MRCLoader(str(mrc_path), lazy=True) req = np.array([5, 2, 5, 0], dtype=np.int32) # unique non-sequential: [0,2,5]
orig_fromfile = np.fromfile calls = {"n": 0}
def _counting_fromfile(*args, **kwargs): calls["n"] += 1 return orig_fromfile(*args, **kwargs)
monkeypatch.setattr(np, "fromfile", _counting_fromfile) out = loader.get(req)
np.testing.assert_allclose(out, data[req]) # Random-access path should read once per unique index, not per request element. assert calls["n"] == 3
def test_mrc_loader_deduplicates_disk_reads_when_all_indices_are_same(monkeypatch, tmp_path): data = np.arange(6 * 4 * 4, dtype=np.float32).reshape(6, 4, 4) mrc_path = tmp_path / "particles.mrcs" utils.write_mrc(str(mrc_path), data)
loader = image_loader.MRCLoader(str(mrc_path), lazy=True) req = np.array([3, 3, 3, 3], dtype=np.int32)
orig_fromfile = np.fromfile calls = {"n": 0}
def _counting_fromfile(*args, **kwargs): calls["n"] += 1 return orig_fromfile(*args, **kwargs)
monkeypatch.setattr(np, "fromfile", _counting_fromfile) out = loader.get(req)
np.testing.assert_allclose(out, data[req]) # Single contiguous read for one unique index. assert calls["n"] == 1
def test_mrc_loader_constructor_accepts_boolean_subset_mask(tmp_path): data = np.arange(5 * 4 * 4, dtype=np.float32).reshape(5, 4, 4) mrc_path = tmp_path / "particles.mrcs" utils.write_mrc(str(mrc_path), data)
keep = np.array([True, False, True, False, True], dtype=bool) loader = image_loader.MRCLoader(str(mrc_path), indices=keep, lazy=True) out = loader.get(np.array([0, 1, 2], dtype=np.int32)) np.testing.assert_allclose(out, data[[0, 2, 4]])
def test_mrc_loader_constructor_rejects_bad_subset_masks(tmp_path): data = np.arange(5 * 4 * 4, dtype=np.float32).reshape(5, 4, 4) mrc_path = tmp_path / "particles.mrcs" utils.write_mrc(str(mrc_path), data)
with pytest.raises(ValueError, match="boolean mask must be 1D"): image_loader.MRCLoader( str(mrc_path), indices=np.array([[True, False, True, False, True]], dtype=bool), lazy=True )
with pytest.raises(ValueError, match="boolean mask length.*must match total size"): image_loader.MRCLoader(str(mrc_path), indices=np.array([True, False], dtype=bool), lazy=True)
def test_mrc_loader_rejects_non_square_images(tmp_path): import mrcfile
bad = np.zeros((3, 4, 5), dtype=np.float32) mrc_path = tmp_path / "bad.mrcs" with mrcfile.new(str(mrc_path), overwrite=True) as m: m.set_data(bad) with pytest.raises(ValueError, match="Non-square images not supported"): image_loader.MRCLoader(str(mrc_path), lazy=True)
def test_multi_mrc_loader_from_txt_and_batches(tmp_path): a = (np.arange(3 * 4 * 4, dtype=np.float32) + 10).reshape(3, 4, 4) b = (np.arange(2 * 4 * 4, dtype=np.float32) + 100).reshape(2, 4, 4) a_path = tmp_path / "a.mrcs" b_path = tmp_path / "b.mrcs" utils.write_mrc(str(a_path), a) utils.write_mrc(str(b_path), b)
txt_path = tmp_path / "files.txt" txt_path.write_text(f"{a_path.name}\n{b_path.name}\n")
loader = image_loader.MultiMRCLoader.from_txt(str(txt_path), lazy=True, max_threads=2) # Expect concatenation of all images from a then b assert len(loader) == 5 imgs = loader.get(np.array([0, 2, 3, 4], dtype=np.int32)) assert imgs.shape == (4, 4, 4) np.testing.assert_allclose(imgs[0], a[0]) np.testing.assert_allclose(imgs[1], a[2]) np.testing.assert_allclose(imgs[2], b[0]) np.testing.assert_allclose(imgs[3], b[1])
def test_multi_mrc_loader_indices_filtering_preserves_order(tmp_path): a = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) b = (100 + np.arange(2 * 4 * 4, dtype=np.float32)).reshape(2, 4, 4) a_path = tmp_path / "a.mrcs" b_path = tmp_path / "b.mrcs" utils.write_mrc(str(a_path), a) utils.write_mrc(str(b_path), b)
df = pd.DataFrame( { "mrc_file": [str(a_path), str(a_path), str(a_path), str(b_path), str(b_path)], "mrc_index": [0, 1, 2, 0, 1], } ) loader = image_loader.MultiMRCLoader(df, indices=np.array([4, 1, 3], dtype=np.int32), lazy=True, max_threads=2) out = loader.get(np.array([0, 1, 2], dtype=np.int32)) np.testing.assert_allclose(out[0], b[1]) np.testing.assert_allclose(out[1], a[1]) np.testing.assert_allclose(out[2], b[0])
def test_multi_mrc_loader_constructor_accepts_boolean_subset_mask(tmp_path): a = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) b = (100 + np.arange(2 * 4 * 4, dtype=np.float32)).reshape(2, 4, 4) a_path = tmp_path / "a.mrcs" b_path = tmp_path / "b.mrcs" utils.write_mrc(str(a_path), a) utils.write_mrc(str(b_path), b)
df = pd.DataFrame( { "mrc_file": [str(a_path), str(a_path), str(a_path), str(b_path), str(b_path)], "mrc_index": [0, 1, 2, 0, 1], } ) mask = np.array([False, True, False, True, True], dtype=bool) loader = image_loader.MultiMRCLoader(df, indices=mask, lazy=True, max_threads=2) out = loader.get(np.array([0, 1, 2], dtype=np.int32)) np.testing.assert_allclose(out[0], a[1]) np.testing.assert_allclose(out[1], b[0]) np.testing.assert_allclose(out[2], b[1])
def test_multi_mrc_loader_constructor_rejects_bad_subset_masks(tmp_path): a = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) a_path = tmp_path / "a.mrcs" utils.write_mrc(str(a_path), a) df = pd.DataFrame( { "mrc_file": [str(a_path), str(a_path), str(a_path)], "mrc_index": [0, 1, 2], } )
with pytest.raises(ValueError, match="boolean mask must be 1D"): image_loader.MultiMRCLoader(df, indices=np.array([[True, False, True]], dtype=bool), lazy=True, max_threads=1)
with pytest.raises(ValueError, match="boolean mask length.*must match total size"): image_loader.MultiMRCLoader(df, indices=np.array([True, False], dtype=bool), lazy=True, max_threads=1)
with pytest.raises(ValueError, match="must be 1D"): image_loader.MultiMRCLoader(df, indices=np.array([[0, 1]], dtype=np.int32), lazy=True, max_threads=1)
def test_multi_mrc_loader_get_with_duplicate_indices(tmp_path): a = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) b = (100 + np.arange(2 * 4 * 4, dtype=np.float32)).reshape(2, 4, 4) a_path = tmp_path / "a.mrcs" b_path = tmp_path / "b.mrcs" utils.write_mrc(str(a_path), a) utils.write_mrc(str(b_path), b)
df = pd.DataFrame( { "mrc_file": [str(a_path), str(a_path), str(a_path), str(b_path), str(b_path)], "mrc_index": [0, 1, 2, 0, 1], } ) loader = image_loader.MultiMRCLoader(df, lazy=True, max_threads=2) req = np.array([4, 1, 4, 0], dtype=np.int32) out = loader.get(req) assert out.shape == (4, 4, 4) np.testing.assert_allclose(out[0], b[1]) np.testing.assert_allclose(out[1], a[1]) np.testing.assert_allclose(out[2], b[1]) # duplicate preserved np.testing.assert_allclose(out[3], a[0])
def test_multi_mrc_loader_empty_request_returns_empty_batch(tmp_path): a = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) a_path = tmp_path / "a.mrcs" utils.write_mrc(str(a_path), a) df = pd.DataFrame({"mrc_file": [str(a_path), str(a_path), str(a_path)], "mrc_index": [0, 1, 2]}) loader = image_loader.MultiMRCLoader(df, lazy=True, max_threads=1) out = loader.get(np.array([], dtype=np.int32)) assert out.shape == (0, 4, 4) assert out.dtype == a.dtype
def test_multi_mrc_loader_indices_only_load_selected_files(tmp_path): a = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) a_path = tmp_path / "a.mrcs" utils.write_mrc(str(a_path), a)
missing_path = tmp_path / "missing.mrcs" # intentionally not created df = pd.DataFrame( { "mrc_file": [str(a_path), str(a_path), str(missing_path)], "mrc_index": [0, 1, 0], } )
# Select only rows that point to the existing file. loader = image_loader.MultiMRCLoader(df, indices=np.array([1, 0], dtype=np.int32), lazy=True, max_threads=2) out = loader.get(np.array([0, 1], dtype=np.int32)) np.testing.assert_allclose(out[0], a[1]) np.testing.assert_allclose(out[1], a[0])
def test_multi_mrc_loader_empty_selection_raises_clear_error(tmp_path): a = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) a_path = tmp_path / "a.mrcs" utils.write_mrc(str(a_path), a) df = pd.DataFrame({"mrc_file": [str(a_path), str(a_path)], "mrc_index": [0, 1]}) with pytest.raises(ValueError, match="No images selected"): image_loader.MultiMRCLoader(df, indices=np.array([], dtype=np.int32), lazy=True, max_threads=1)
def test_multi_mrc_loader_rejects_out_of_range_mrc_indices_at_construction(tmp_path): a = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) a_path = tmp_path / "a.mrcs" utils.write_mrc(str(a_path), a) df = pd.DataFrame( { "mrc_file": [str(a_path), str(a_path)], "mrc_index": [0, 2], # second index is out of range for 2-image stack } ) with pytest.raises(ValueError, match="out of range"): image_loader.MultiMRCLoader(df, lazy=True, max_threads=1)
def test_multi_mrc_loader_rejects_negative_mrc_index_values_at_construction(tmp_path): a = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) a_path = tmp_path / "a.mrcs" utils.write_mrc(str(a_path), a) df = pd.DataFrame( { "mrc_file": [str(a_path), str(a_path)], "mrc_index": [0, -1], } ) with pytest.raises(ValueError, match="must be non-negative"): image_loader.MultiMRCLoader(df, lazy=True, max_threads=1)
def test_multi_mrc_loader_rejects_noninteger_mrc_index_values_at_construction(tmp_path): a = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) a_path = tmp_path / "a.mrcs" utils.write_mrc(str(a_path), a) df = pd.DataFrame( { "mrc_file": [str(a_path), str(a_path)], "mrc_index": [0.0, 1.0], # float metadata should be rejected } ) with pytest.raises(ValueError, match="must be integers"): image_loader.MultiMRCLoader(df, lazy=True, max_threads=1)
def test_tilt_series_dataset_strip_prefix_with_tiny_real_files(tmp_path): from helpers import tiny_synthetic
files = tiny_synthetic.make_tiny_loader_files(tmp_path / "tiny", grid_size=8, n_images=6, n_particles=3) bad_prefix = "/unmounted/prefix" mrcs_name = (tmp_path / "tiny" / "particles.mrcs").name
sf = starfile.StarFile.load(files["particles_star"]) sf.df["_rlnImageName"] = [f"{i + 1}@{bad_prefix}/{mrcs_name}" for i in range(files["n_images"])] prefixed_star = tmp_path / "prefixed.star" starfile.write_star(str(prefixed_star), data=sf.df)
# Without strip_prefix the prefixed path is unresolved. with pytest.raises(Exception): cryo_dataset.TiltSeriesDataset( str(prefixed_star), datadir=str(tmp_path / "tiny"), lazy=True, tilt_file_option="relion5" )
ds = cryo_dataset.TiltSeriesDataset( str(prefixed_star), datadir=str(tmp_path / "tiny"), strip_prefix=bad_prefix + "/", lazy=True, tilt_file_option="relion5", random_tilts=False, num_tilts=1, ) assert len(ds) == 3 batches = list(ds.get_image_subset_generator(batch_size=2, subset_indices=np.array([5, 1, 4], dtype=np.int32))) got = [] for _imgs, _pidx, tidx in batches: got.extend(np.array(tidx).reshape(-1).tolist()) assert got == [5, 1, 4]
def test_star_loader_and_strip_prefix(tmp_path): data = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) rel_dir = tmp_path / "rel" rel_dir.mkdir() mrc_path = rel_dir / "stack.mrcs" utils.write_mrc(str(mrc_path), data)
df = pd.DataFrame( { "_rlnImageName": [ "1@prefix/stack.mrcs", "2@prefix/stack.mrcs", "3@prefix/stack.mrcs", ] } ) star_path = tmp_path / "particles.star" starfile.write_star(str(star_path), data=df)
loader = image_loader.StarLoader( str(star_path), datadir=str(rel_dir), strip_prefix="prefix/", lazy=True, ) out = loader.get(np.array([0, 2], dtype=np.int32)) assert out.shape == (2, 4, 4) np.testing.assert_allclose(out[0], data[0]) np.testing.assert_allclose(out[1], data[2])
with pytest.raises(ValueError, match="strip_prefix"): image_loader.StarLoader(str(star_path), datadir=str(rel_dir), strip_prefix="does_not_match/", lazy=True)
def test_star_loader_uses_star_parent_when_datadir_missing(tmp_path): data = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) mrc_path = tmp_path / "stack.mrcs" utils.write_mrc(str(mrc_path), data) df = pd.DataFrame({"_rlnImageName": [f"1@{mrc_path.name}", f"2@{mrc_path.name}"]}) star_path = tmp_path / "particles.star" starfile.write_star(str(star_path), data=df) loader = image_loader.StarLoader(str(star_path), lazy=True) out = loader.get(np.array([1], dtype=np.int32)) np.testing.assert_allclose(out[0], data[1])
def test_star_loader_rejects_missing_rlnimagename_column(tmp_path): df = pd.DataFrame({"_rlnDefocusU": [10000, 11000]}) star_path = tmp_path / "particles.star" starfile.write_star(str(star_path), data=df) with pytest.raises(ValueError, match="_rlnImageName"): image_loader.StarLoader(str(star_path), lazy=True)
def test_star_loader_rejects_nonnumeric_image_index_tokens(tmp_path): data = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) rel_dir = tmp_path / "rel" rel_dir.mkdir() mrc_path = rel_dir / "stack.mrcs" utils.write_mrc(str(mrc_path), data)
# Numeric-looking prefix is required; nonnumeric token should fail clearly. df_bad = pd.DataFrame({"_rlnImageName": [f"one@{mrc_path.name}", f"2@{mrc_path.name}"]}) bad_star = tmp_path / "bad_nonnumeric_token.star" starfile.write_star(str(bad_star), data=df_bad) with pytest.raises(ValueError, match="index part is not an integer"): image_loader.StarLoader(str(bad_star), datadir=str(rel_dir), lazy=True)
def test_star_loader_rejects_malformed_image_name_entries(tmp_path): data = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) rel_dir = tmp_path / "rel" rel_dir.mkdir() mrc_path = rel_dir / "stack.mrcs" utils.write_mrc(str(mrc_path), data)
# Missing '@' separator. df_bad = pd.DataFrame({"_rlnImageName": [f"1{mrc_path.name}", f"2@{mrc_path.name}"]}) bad_star = tmp_path / "bad.star" starfile.write_star(str(bad_star), data=df_bad) with pytest.raises(ValueError, match="Malformed _rlnImageName"): image_loader.StarLoader(str(bad_star), datadir=str(rel_dir), lazy=True)
# Zero index (must be >= 1 in STAR convention). df_zero = pd.DataFrame({"_rlnImageName": [f"0@{mrc_path.name}", f"1@{mrc_path.name}"]}) zero_star = tmp_path / "zero.star" starfile.write_star(str(zero_star), data=df_zero) with pytest.raises(ValueError, match="indices must be >= 1"): image_loader.StarLoader(str(zero_star), datadir=str(rel_dir), lazy=True)
def test_star_loader_rejects_non_integer_image_indices(tmp_path): data = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) rel_dir = tmp_path / "rel" rel_dir.mkdir() mrc_path = rel_dir / "stack.mrcs" utils.write_mrc(str(mrc_path), data)
df_bad = pd.DataFrame({"_rlnImageName": [f"a@{mrc_path.name}", f"2@{mrc_path.name}"]}) bad_star = tmp_path / "bad_non_integer.star" starfile.write_star(str(bad_star), data=df_bad)
with pytest.raises(ValueError, match="index part is not an integer"): image_loader.StarLoader(str(bad_star), datadir=str(rel_dir), lazy=True)
def test_star_loader_rejects_image_indices_out_of_range_for_stack(tmp_path): data = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) rel_dir = tmp_path / "rel" rel_dir.mkdir() mrc_path = rel_dir / "stack.mrcs" utils.write_mrc(str(mrc_path), data)
# Third image requested from a two-image stack. df_bad = pd.DataFrame({"_rlnImageName": [f"1@{mrc_path.name}", f"3@{mrc_path.name}"]}) bad_star = tmp_path / "bad_out_of_range.star" starfile.write_star(str(bad_star), data=df_bad)
with pytest.raises(ValueError, match="out of range"): image_loader.StarLoader(str(bad_star), datadir=str(rel_dir), lazy=True)
def test_cryosparc_loader_reads_structured_cs(tmp_path): data = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) mrc_path = tmp_path / "stack.mrcs" utils.write_mrc(str(mrc_path), data)
cs_dtype = np.dtype([("blob/idx", np.int32), ("blob/path", "U64")]) cs = np.zeros(3, dtype=cs_dtype) cs["blob/idx"] = np.array([0, 1, 2], dtype=np.int32) cs["blob/path"] = np.array([">stack.mrcs", ">stack.mrcs", ">stack.mrcs"]) cs_path = tmp_path / "particles.cs" with open(cs_path, "wb") as f: np.save(f, cs)
loader = image_loader.CryoSparcLoader(str(cs_path), datadir=str(tmp_path), lazy=True) out = loader.get(np.array([1, 2], dtype=np.int32)) assert out.shape == (2, 4, 4) np.testing.assert_allclose(out[0], data[1]) np.testing.assert_allclose(out[1], data[2])
def test_cryosparc_loader_supports_byte_blob_paths(tmp_path): data = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) mrc_path = tmp_path / "stack.mrcs" utils.write_mrc(str(mrc_path), data)
cs_dtype = np.dtype([("blob/idx", np.int32), ("blob/path", "S64")]) cs = np.zeros(3, dtype=cs_dtype) cs["blob/idx"] = np.array([0, 2, 1], dtype=np.int32) cs["blob/path"] = np.array([b">stack.mrcs", b">stack.mrcs", b">stack.mrcs"], dtype="S64") cs_path = tmp_path / "particles_bytes.cs" with open(cs_path, "wb") as f: np.save(f, cs)
loader = image_loader.CryoSparcLoader(str(cs_path), datadir=str(tmp_path), lazy=True) out = loader.get(np.array([0, 1, 2], dtype=np.int32)) np.testing.assert_allclose(out[0], data[0]) np.testing.assert_allclose(out[1], data[2]) np.testing.assert_allclose(out[2], data[1])
def test_cryosparc_loader_rejects_missing_required_fields(tmp_path): cs_dtype = np.dtype([("blob/path", "U64")]) cs = np.zeros(2, dtype=cs_dtype) cs["blob/path"] = np.array([">a.mrcs", ">a.mrcs"]) cs_path = tmp_path / "bad.cs" with open(cs_path, "wb") as f: np.save(f, cs) with pytest.raises(ValueError, match="blob/idx"): image_loader.CryoSparcLoader(str(cs_path), datadir=str(tmp_path), lazy=True)
def test_cryosparc_loader_rejects_blob_indices_out_of_range_for_stack(tmp_path): data = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) mrc_path = tmp_path / "stack.mrcs" utils.write_mrc(str(mrc_path), data)
cs_dtype = np.dtype([("blob/idx", np.int32), ("blob/path", "U64")]) cs = np.zeros(2, dtype=cs_dtype) cs["blob/idx"] = np.array([0, 2], dtype=np.int32) # second index out of range cs["blob/path"] = np.array([">stack.mrcs", ">stack.mrcs"]) cs_path = tmp_path / "bad_out_of_range.cs" with open(cs_path, "wb") as f: np.save(f, cs)
with pytest.raises(ValueError, match="out of range"): image_loader.CryoSparcLoader(str(cs_path), datadir=str(tmp_path), lazy=True)
def test_image_loader_from_file_alias_and_dtype_preserved(): loader = _DummyLoader(n=3, D=2, dtype=np.float32) out = loader.images(np.array([0, 2], dtype=np.int32), require_contiguous=True) assert out.dtype == np.float32 np.testing.assert_array_equal(out, loader._store[[0, 2]])
def test_parse_indices_scalar_ndarray_and_bounds_errors(): loader = _DummyLoader(n=4, D=2) np.testing.assert_array_equal(loader._parse_indices(np.array(2, dtype=np.int64)), np.array([2])) with pytest.raises(IndexError, match="out of range"): loader._parse_indices(9) with pytest.raises(IndexError, match="out of range"): loader._parse_indices(np.array(-1, dtype=np.int64))
def test_image_source_from_file_delegates_to_load_images(monkeypatch): sentinel = object() captured = {}
def _fake_load(filepath, indices=None, datadir="", lazy=True, max_threads=1, strip_prefix=None): captured["args"] = (filepath, indices, datadir, lazy, max_threads, strip_prefix) return sentinel
monkeypatch.setattr(image_loader, "load_images", _fake_load) out = image_loader.ImageLoader.from_file( "particles.star", lazy=False, indices=np.array([0, 3], dtype=np.int32), datadir="/tmp/x", max_threads=8, strip_prefix="abc/", ) assert out is sentinel assert captured["args"][0] == "particles.star" np.testing.assert_array_equal(captured["args"][1], np.array([0, 3], dtype=np.int32)) assert captured["args"][2:] == ("/tmp/x", False, 8, "abc/")
def test_image_loader_parse_indices_rejects_bad_type(): loader = _DummyLoader(n=4, D=2) with pytest.raises(TypeError, match="Cannot index with type"): loader._parse_indices({"bad": "type"})
def test_load_images_dispatches_to_expected_loader(monkeypatch): sentinels = { "mrc": object(), "star": object(), "txt": object(), "cs": object(), } calls = {}
def _fake_mrc(filepath, indices, lazy, skip_staging=False): calls["mrc"] = (filepath, indices, lazy) return sentinels["mrc"]
def _fake_star(filepath, indices, datadir, lazy, max_threads, strip_prefix, skip_staging=False): calls["star"] = (filepath, indices, datadir, lazy, max_threads, strip_prefix) return sentinels["star"]
def _fake_cs(filepath, indices, datadir, lazy, max_threads, strip_prefix=None, skip_staging=False): calls["cs"] = (filepath, indices, datadir, lazy, max_threads, strip_prefix) return sentinels["cs"]
class _FakeMulti: @staticmethod def from_txt(filepath, indices, lazy, max_threads, skip_staging=False): calls["txt"] = (filepath, indices, lazy, max_threads) return sentinels["txt"]
monkeypatch.setattr(image_loader, "MRCLoader", _fake_mrc) monkeypatch.setattr(image_loader, "StarLoader", _fake_star) monkeypatch.setattr(image_loader, "CryoSparcLoader", _fake_cs) monkeypatch.setattr(image_loader, "MultiMRCLoader", _FakeMulti)
idx = np.array([0, 2], dtype=np.int32) assert image_loader.load_images("particles.mrcs", indices=idx, lazy=False) is sentinels["mrc"] assert image_loader.load_images("particles.mrc", indices=idx, lazy=True) is sentinels["mrc"] assert ( image_loader.load_images( "particles.star", indices=idx, datadir="/tmp/data", lazy=True, max_threads=8, strip_prefix="old/", ) is sentinels["star"] ) assert image_loader.load_images("particles.txt", indices=idx, lazy=True, max_threads=4) is sentinels["txt"] assert ( image_loader.load_images("particles.cs", indices=idx, datadir="/tmp/cs", lazy=False, max_threads=2) is sentinels["cs"] )
np.testing.assert_array_equal(calls["mrc"][1], idx) np.testing.assert_array_equal(calls["star"][1], idx) np.testing.assert_array_equal(calls["txt"][1], idx) np.testing.assert_array_equal(calls["cs"][1], idx) assert calls["star"][2:] == ("/tmp/data", True, 8, "old/") assert calls["txt"][2:] == (True, 4) assert calls["cs"][2:] == ("/tmp/cs", False, 2, None)
def test_cryosparc_loader_rejects_negative_blob_indices(tmp_path): cs_dtype = np.dtype([("blob/idx", np.int32), ("blob/path", "U64")]) cs = np.zeros(2, dtype=cs_dtype) cs["blob/idx"] = np.array([0, -1], dtype=np.int32) cs["blob/path"] = np.array([">stack.mrcs", ">stack.mrcs"]) cs_path = tmp_path / "bad_negative.cs" with open(cs_path, "wb") as f: np.save(f, cs)
with pytest.raises(ValueError, match="negative blob/idx"): image_loader.CryoSparcLoader(str(cs_path), datadir=str(tmp_path), lazy=True)
def test_cryosparc_loader_resolves_relative_datadir_against_cs_file(tmp_path): data = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) run_dir = tmp_path / "job" / "run" data_dir = tmp_path / "job" / "data" run_dir.mkdir(parents=True) data_dir.mkdir(parents=True) mrc_path = data_dir / "stack.mrcs" utils.write_mrc(str(mrc_path), data)
cs_dtype = np.dtype([("blob/idx", np.int32), ("blob/path", "U64")]) cs = np.zeros(3, dtype=cs_dtype) cs["blob/idx"] = np.array([2, 0, 1], dtype=np.int32) cs["blob/path"] = np.array([">stack.mrcs", ">stack.mrcs", ">stack.mrcs"]) cs_path = run_dir / "particles.cs" with open(cs_path, "wb") as f: np.save(f, cs)
loader = image_loader.CryoSparcLoader(str(cs_path), datadir="../data", lazy=True) out = loader.get(np.array([0, 1, 2], dtype=np.int32)) np.testing.assert_allclose(out[0], data[2]) np.testing.assert_allclose(out[1], data[0]) np.testing.assert_allclose(out[2], data[1])
def test_load_images_star_from_simulator_tiny_tilt_preserves_duplicates_and_order(tmp_path): from helpers import tiny_synthetic
files = tiny_synthetic.make_tiny_tilt_loader_files_from_simulator( tmp_path / "sim_tiny_tilt", grid_size=8, n_images=18, n_tilts=3, n_volumes=4, ) datadir = str(Path(files["particles_star"]).parent) req = np.array([5, 1, 5, 0], dtype=np.int32)
star_loader = image_loader.load_images(files["particles_star"], indices=None, datadir=datadir, lazy=True) mrc_loader = image_loader.MRCLoader(files["particles_mrcs"], lazy=True) got = star_loader.get(req) expected = mrc_loader.get(req) np.testing.assert_allclose(got, expected)
def test_load_images_star_with_constructor_indices_from_simulator_preserves_local_order_and_duplicates(tmp_path): from helpers import tiny_synthetic
files = tiny_synthetic.make_tiny_tilt_loader_files_from_simulator( tmp_path / "sim_tiny_tilt_subset", grid_size=8, n_images=18, n_tilts=3, n_volumes=4, ) datadir = str(Path(files["particles_star"]).parent) selected_global = np.array([7, 2, 7, 1], dtype=np.int32) local_request = np.array([3, 0, 2, 1], dtype=np.int32)
loader = image_loader.load_images( files["particles_star"], indices=selected_global, datadir=datadir, lazy=True, ) got = loader.get(local_request)
mrc_loader = image_loader.MRCLoader(files["particles_mrcs"], lazy=True) expected = mrc_loader.get(selected_global[local_request]) np.testing.assert_allclose(got, expected)
def test_load_images_star_with_boolean_constructor_mask_from_simulator(tmp_path): from helpers import tiny_synthetic
files = tiny_synthetic.make_tiny_tilt_loader_files_from_simulator( tmp_path / "sim_tiny_tilt_mask", grid_size=8, n_images=18, n_tilts=3, n_volumes=4, ) datadir = str(Path(files["particles_star"]).parent) mask = np.zeros(files["n_images"], dtype=bool) mask[[7, 2, 1]] = True local_request = np.array([2, 0, 1], dtype=np.int32)
loader = image_loader.load_images( files["particles_star"], indices=mask, datadir=datadir, lazy=True, ) got = loader.get(local_request)
mrc_loader = image_loader.MRCLoader(files["particles_mrcs"], lazy=True) # mask selects global indices [1,2,7] in ascending order; local_request [2,0,1] # should map to global [7,1,2]. expected = mrc_loader.get(np.array([7, 1, 2], dtype=np.int32)) np.testing.assert_allclose(got, expected)
def test_load_images_star_rejects_wrong_length_boolean_constructor_mask(tmp_path): from helpers import tiny_synthetic
files = tiny_synthetic.make_tiny_tilt_loader_files_from_simulator( tmp_path / "sim_tiny_tilt_badmask", grid_size=8, n_images=18, n_tilts=3, n_volumes=4, ) datadir = str(Path(files["particles_star"]).parent)
with pytest.raises(ValueError, match="boolean mask length.*must match total size"): image_loader.load_images( files["particles_star"], indices=np.array([True, False, True], dtype=bool), datadir=datadir, lazy=True, )
def test_multi_mrc_loader_mrc_to_mrcs_extension_fallback(tmp_path): """When file_map references .mrc but the file on disk is .mrcs, the loader should find it.""" data = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) mrcs_path = tmp_path / "stack.mrcs" utils.write_mrc(str(mrcs_path), data)
# file_map references .mrc (without the 's'), but the actual file is .mrcs mrc_ref = str(tmp_path / "stack.mrc") df = pd.DataFrame( { "mrc_file": [mrc_ref, mrc_ref, mrc_ref], "mrc_index": [0, 1, 2], } )
loader = image_loader.MultiMRCLoader(df, lazy=True) out = loader.get(np.array([0, 2], dtype=np.int32)) assert out.shape == (2, 4, 4) np.testing.assert_allclose(out[0], data[0]) np.testing.assert_allclose(out[1], data[2])
def test_multi_mrc_loader_mrcs_to_mrc_extension_fallback(tmp_path): """When file_map references .mrcs but the file on disk is .mrc, the loader should find it.""" data = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) mrc_path = tmp_path / "stack.mrc" utils.write_mrc(str(mrc_path), data)
# file_map references .mrcs, but the actual file is .mrc mrcs_ref = str(tmp_path / "stack.mrcs") df = pd.DataFrame( { "mrc_file": [mrcs_ref, mrcs_ref, mrcs_ref], "mrc_index": [0, 1, 2], } )
loader = image_loader.MultiMRCLoader(df, lazy=True) out = loader.get(np.array([1], dtype=np.int32)) assert out.shape == (1, 4, 4) np.testing.assert_allclose(out[0], data[1])
def test_cryosparc_loader_mrc_mrcs_extension_fallback(tmp_path): """CryoSparcLoader should find .mrcs files when CS references .mrc.""" data = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) mrcs_path = tmp_path / "stack.mrcs" utils.write_mrc(str(mrcs_path), data)
# CS file references stack.mrc (no 's'), but file on disk is stack.mrcs cs_dtype = np.dtype([("blob/idx", np.int32), ("blob/path", "U64")]) cs = np.zeros(3, dtype=cs_dtype) cs["blob/idx"] = np.array([0, 1, 2], dtype=np.int32) cs["blob/path"] = np.array([">stack.mrc", ">stack.mrc", ">stack.mrc"]) cs_path = tmp_path / "particles.cs" with open(cs_path, "wb") as f: np.save(f, cs)
loader = image_loader.CryoSparcLoader(str(cs_path), datadir=str(tmp_path), lazy=True) out = loader.get(np.array([0, 2], dtype=np.int32)) assert out.shape == (2, 4, 4) np.testing.assert_allclose(out[0], data[0]) np.testing.assert_allclose(out[1], data[2])
def test_cryosparc_loader_strip_prefix_with_extension_fallback(tmp_path): """CryoSparcLoader with strip-prefix + .mrc->.mrcs fallback.""" data = np.arange(3 * 4 * 4, dtype=np.float32).reshape(3, 4, 4) mrcs_path = tmp_path / "stack.mrcs" utils.write_mrc(str(mrcs_path), data)
# CS file has paths like J3/imported/stack.mrc cs_dtype = np.dtype([("blob/idx", np.int32), ("blob/path", "U64")]) cs = np.zeros(3, dtype=cs_dtype) cs["blob/idx"] = np.array([0, 1, 2], dtype=np.int32) cs["blob/path"] = np.array( [ ">J3/imported/stack.mrc", ">J3/imported/stack.mrc", ">J3/imported/stack.mrc", ] ) cs_path = tmp_path / "particles.cs" with open(cs_path, "wb") as f: np.save(f, cs)
loader = image_loader.CryoSparcLoader( str(cs_path), datadir=str(tmp_path), strip_prefix="J3/imported", lazy=True, ) out = loader.get(np.array([0, 1, 2], dtype=np.int32)) assert out.shape == (3, 4, 4) np.testing.assert_allclose(out, data)
def test_error_hint_shows_raw_metadata_path(tmp_path): """Error hint for missing files should suggest strip-prefix based on raw metadata path.""" cs_dtype = np.dtype([("blob/idx", np.int32), ("blob/path", "U64")]) cs = np.zeros(1, dtype=cs_dtype) cs["blob/idx"] = np.array([0], dtype=np.int32) cs["blob/path"] = np.array([">J3/imported/nonexistent.mrc"]) cs_path = tmp_path / "particles.cs" with open(cs_path, "wb") as f: np.save(f, cs)
with pytest.raises(FileNotFoundError, match="--strip-prefix J3/imported"): image_loader.CryoSparcLoader(str(cs_path), datadir=str(tmp_path), lazy=True)
def test_swap_mrc_ext_helper(): """Test the _swap_mrc_ext helper function.""" assert image_loader._swap_mrc_ext("/path/to/file.mrc") == "/path/to/file.mrcs" assert image_loader._swap_mrc_ext("/path/to/file.mrcs") == "/path/to/file.mrc" assert image_loader._swap_mrc_ext("/path/to/file.txt") is None assert image_loader._swap_mrc_ext("/path/to/file.star") is None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272"""Unit tests for recovar.output.job.JobDir and output_paths.VolumeOutputPaths."""
import jsonimport os
import pytest
from recovar.output.job import ( JobDir, _args_to_dict, _collect_output_manifest, _get_recovar_version,)from recovar.output.output_paths import VolumeOutputPaths, resolve_volume_diag_path
# ---------------------------------------------------------------------------# VolumeOutputPaths tests# ---------------------------------------------------------------------------
class TestVolumeOutputPaths: def test_primary_output_paths(self, tmp_path): vp = VolumeOutputPaths(str(tmp_path), "center", 0) assert vp.stem == "center000" assert vp.filtered == os.path.join(str(tmp_path), "center000.mrc") assert vp.half1_unfil == os.path.join(str(tmp_path), "center000_half1_unfil.mrc") assert vp.half2_unfil == os.path.join(str(tmp_path), "center000_half2_unfil.mrc") assert vp.unfil == os.path.join(str(tmp_path), "center000_unfil.mrc")
def test_diagnostics_paths(self, tmp_path): vp = VolumeOutputPaths(str(tmp_path), "state", 5) diag = os.path.join(str(tmp_path), "diagnostics", "state005") assert vp.diag_dir == diag assert vp.params == os.path.join(diag, "params.pkl") assert vp.split_choice == os.path.join(diag, "split_choice.pkl") assert vp.locres == os.path.join(diag, "local_resolution.mrc") assert vp.sampling == os.path.join(diag, "sampling.mrc") assert vp.heterogeneity_distances == os.path.join(diag, "heterogeneity_distances.txt") assert vp.latent_coords == os.path.join(diag, "latent_coords.txt")
def test_debug_paths(self, tmp_path): vp = VolumeOutputPaths(str(tmp_path), "center", 2) diag = vp.diag_dir assert vp.filtered_smooth == os.path.join(diag, "filtered_smooth.mrc") assert vp.cv_half1_unfil == os.path.join(diag, "CV_estimates_half1_unfil.mrc") assert vp.cv_noise_half2 == os.path.join(diag, "CV_noise_half2.mrc")
def test_estimates_dir(self, tmp_path): vp = VolumeOutputPaths(str(tmp_path), "state", 0) assert vp.estimates_dir(1) == os.path.join(vp.diag_dir, "estimates_half1_unfil") assert vp.estimates_dir(2) == os.path.join(vp.diag_dir, "estimates_half2_unfil") assert vp.estimates_dir(1, filtered=True) == os.path.join(vp.diag_dir, "estimates_filt")
def test_ensure_dirs(self, tmp_path): vp = VolumeOutputPaths(str(tmp_path / "out"), "center", 0) vp.ensure_dirs() assert os.path.isdir(str(tmp_path / "out")) assert os.path.isdir(vp.diag_dir)
def test_different_indices(self, tmp_path): vp0 = VolumeOutputPaths(str(tmp_path), "center", 0) vp19 = VolumeOutputPaths(str(tmp_path), "center", 19) assert vp0.stem == "center000" assert vp19.stem == "center019" assert vp0.filtered != vp19.filtered
# ---------------------------------------------------------------------------# resolve_volume_diag_path tests# ---------------------------------------------------------------------------
class TestResolveVolumeDiagPath: def test_new_layout(self, tmp_path): """Find file in diagnostics/{stem}/ layout.""" diag = tmp_path / "diagnostics" / "center000" diag.mkdir(parents=True) (diag / "params.pkl").write_text("new")
result = resolve_volume_diag_path(str(tmp_path), "params.pkl", "center", 0) assert result == str(diag / "params.pkl")
def test_flat_fallback(self, tmp_path): """Fall back to flat layout when diagnostics/ doesn't exist.""" (tmp_path / "params.pkl").write_text("old")
result = resolve_volume_diag_path(str(tmp_path), "params.pkl", "center", 0) assert result == str(tmp_path / "params.pkl")
def test_new_layout_preferred(self, tmp_path): """New layout is preferred when both exist.""" (tmp_path / "params.pkl").write_text("old") diag = tmp_path / "diagnostics" / "center000" diag.mkdir(parents=True) (diag / "params.pkl").write_text("new")
result = resolve_volume_diag_path(str(tmp_path), "params.pkl", "center", 0) assert "diagnostics" in result
def test_no_prefix(self, tmp_path): """Without prefix/index, just use flat path.""" (tmp_path / "params.pkl").write_text("data") result = resolve_volume_diag_path(str(tmp_path), "params.pkl") assert result == str(tmp_path / "params.pkl")
# ---------------------------------------------------------------------------# JobDir tests# ---------------------------------------------------------------------------
class TestJobDir: def test_basic_properties(self, tmp_path): job = JobDir(str(tmp_path / "myoutput"), "compute_state") assert job.command_name == "compute_state" assert job.job_json.endswith("job.json") assert job.command_txt.endswith("command.txt") assert job.run_log.endswith("run.log")
def test_ensure_dirs(self, tmp_path): job = JobDir(str(tmp_path / "myoutput"), "compute_state") job.ensure_dirs() assert os.path.isdir(job.root)
def test_start_and_complete(self, tmp_path): job = JobDir(str(tmp_path / "myoutput"), "compute_state") job._parent_result_dir = "/some/pipeline"
# Simulate args import argparse
args = argparse.Namespace(outdir=str(tmp_path / "myoutput"), n_bins=50)
job.start(args)
# Check files created assert os.path.isfile(job.job_json) assert os.path.isfile(job.command_txt) assert os.path.isfile(job.run_log)
# Check job.json content at start with open(job.job_json) as f: data = json.load(f) assert data["command"] == "compute_state" assert data["status"] == "running" assert "started_at" in data["timing"] assert data["recovar_version"] == _get_recovar_version() assert data["parameters"]["n_bins"] == 50 assert data["provenance"]["pipeline_result_dir"] == "/some/pipeline" assert "hostname" in data["environment"]
# Write a fake volume to test output manifest with open(os.path.join(job.root, "state000.mrc"), "w") as f: f.write("fake")
job.complete()
with open(job.job_json) as f: data = json.load(f) assert data["status"] == "completed" assert "completed_at" in data["timing"] assert "duration_seconds" in data["timing"] assert "state000.mrc" in data["outputs"].get("volumes", [])
def test_complete_failed(self, tmp_path): job = JobDir(str(tmp_path / "out"), "analyze") job.start() job.complete(status="failed")
with open(job.job_json) as f: data = json.load(f) assert data["status"] == "failed"
# ---------------------------------------------------------------------------# Auto-numbering tests# ---------------------------------------------------------------------------
class TestAutoNumbering: def test_first_job(self, tmp_path): result = JobDir._next_numbered_dir(str(tmp_path), "compute_state") assert result == os.path.join(str(tmp_path), "compute_state_001")
def test_sequential_numbering(self, tmp_path): (tmp_path / "compute_state_001").mkdir() (tmp_path / "compute_state_002").mkdir() result = JobDir._next_numbered_dir(str(tmp_path), "compute_state") assert result == os.path.join(str(tmp_path), "compute_state_003")
def test_gap_in_numbering(self, tmp_path): """Uses max+1, doesn't fill gaps.""" (tmp_path / "compute_state_001").mkdir() (tmp_path / "compute_state_005").mkdir() result = JobDir._next_numbered_dir(str(tmp_path), "compute_state") assert result == os.path.join(str(tmp_path), "compute_state_006")
def test_ignores_other_prefixes(self, tmp_path): (tmp_path / "analyze_001").mkdir() (tmp_path / "compute_state_003").mkdir() result = JobDir._next_numbered_dir(str(tmp_path), "analyze") assert result == os.path.join(str(tmp_path), "analyze_002")
def test_create_with_auto_number(self, tmp_path): job = JobDir.create( outdir=None, command_name="compute_state", parent_result_dir=str(tmp_path), auto_number=True, ) assert job.root == os.path.join(str(tmp_path), "compute_state_001")
def test_create_with_explicit_outdir(self, tmp_path): job = JobDir.create( outdir=str(tmp_path / "my_custom_dir"), command_name="compute_state", ) assert job.root == str(tmp_path / "my_custom_dir")
def test_create_no_outdir_no_auto(self): with pytest.raises(ValueError, match="outdir is required"): JobDir.create(outdir=None, command_name="test")
# ---------------------------------------------------------------------------# Helper function tests# ---------------------------------------------------------------------------
class TestHelpers: def test_args_to_dict(self): import argparse
args = argparse.Namespace( outdir="/path/to/out", n_bins=50, _private="hidden", ) d = _args_to_dict(args) assert d["outdir"] == "/path/to/out" assert d["n_bins"] == 50 assert "_private" not in d
def test_args_to_dict_none(self): assert _args_to_dict(None) == {}
def test_collect_output_manifest(self, tmp_path): # Create some test files (tmp_path / "state000.mrc").write_text("vol") (tmp_path / "state000_half1_unfil.mrc").write_text("hm") (tmp_path / "job.json").write_text("{}") # should be excluded diag = tmp_path / "diagnostics" / "state000" diag.mkdir(parents=True) (diag / "params.pkl").write_text("p") plots = tmp_path / "plots" plots.mkdir() (plots / "fsc.png").write_text("img")
manifest = _collect_output_manifest(str(tmp_path)) assert "state000.mrc" in manifest["volumes"] assert "state000_half1_unfil.mrc" in manifest["halfmaps"] assert any("params.pkl" in p for p in manifest["diagnostics"]) assert any("fsc.png" in p for p in manifest["plots"]) # job.json should not appear for category in manifest.values(): for path in category: assert "job.json" not in path
def test_get_recovar_version(self): v = _get_recovar_version() assert v != "unknown"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import numpy as npimport pytest
pytest.importorskip("jax")
from recovar.heterogeneity import latent_density as ld
pytestmark = pytest.mark.unit
def test_grid_mapping_roundtrip(): bounds = np.array([[-2.0, 2.0], [0.0, 10.0]], dtype=np.float32) num_points = 11 x = np.array([0.4, 6.0], dtype=np.float32) g = ld.pca_coord_to_grid(x, bounds, num_points, to_int=False) x_rt = ld.grid_to_pca_coord(g, bounds, num_points) assert np.allclose(x_rt, x, atol=1e-6)
gi = ld.pca_coord_to_grid(x, bounds, num_points, to_int=True) assert gi.dtype.kind in ("i", "u") assert gi.shape == (2,)
def test_get_grid_z_mappings_callable(): bounds = np.array([[-1.0, 1.0]], dtype=np.float32) grid_to_z, z_to_grid = ld.get_grid_z_mappings(bounds, num_points=5) z = np.array([0.25], dtype=np.float32) g = z_to_grid(z, to_int=False) z_back = grid_to_z(g) assert np.allclose(z_back, z, atol=1e-6)
def test_make_latent_space_grid_from_bounds_shape(): bounds = np.array([[-1.0, 1.0], [0.0, 2.0], [5.0, 6.0]], dtype=np.float32) grid = ld.make_latent_space_grid_from_bounds(bounds, num_points=4) assert grid.shape == (4**3, 3) assert np.all(np.isfinite(np.asarray(grid)))
def test_compute_latent_space_bounds_percentile(): zs = np.array( [ [-10.0, 1.0], [0.0, 2.0], [10.0, 3.0], [100.0, 4.0], ], dtype=np.float32, ) b = ld.compute_latent_space_bounds(zs, percentile=25) assert b.shape == (2, 2) assert b[0, 0] >= -10.0 assert b[0, 1] <= 100.0 assert b[1, 0] >= 1.0 assert b[1, 1] <= 4.0
def test_compute_log_det_cov_identity(): """log det of identity matrix should be 0.""" cov = np.eye(3, dtype=np.float32)[None] result = np.asarray(ld.compute_log_det_cov(cov)) assert result.shape == (1,) np.testing.assert_allclose(result, 0.0, atol=1e-5)
def test_compute_log_det_cov_scaled_identity(): """log det of 2*I should be dim*log(2).""" cov = 2.0 * np.eye(3, dtype=np.float32)[None] result = np.asarray(ld.compute_log_det_cov(cov)) expected = 3 * np.log(2.0) np.testing.assert_allclose(result, expected, atol=1e-5)
def test_compute_log_det_cov_singular_safe(): """Singular matrix should not produce -inf due to our safeguard.""" cov = np.zeros((1, 2, 2), dtype=np.float32) result = np.asarray(ld.compute_log_det_cov(cov)) assert np.all(np.isfinite(result))
def test_compute_latent_quadratic_forms_at_mean_is_zero(): """Quadratic form at the mean should be zero.""" xs = np.array([[1.0, 2.0]], dtype=np.float32) # 1 image, 2D cov = np.eye(2, dtype=np.float32)[None] # identity covariance test_pts = xs.copy() # test at the mean result = np.asarray(ld.compute_latent_quadratic_forms(test_pts, xs, cov)) assert result.shape == (1, 1) np.testing.assert_allclose(result, 0.0, atol=1e-5)
def test_compute_latent_quadratic_forms_away_from_mean(): """Quadratic form should increase with distance from mean.""" xs = np.array([[0.0, 0.0]], dtype=np.float32) cov = np.eye(2, dtype=np.float32)[None] test_pts = np.array([[1.0, 0.0], [2.0, 0.0]], dtype=np.float32) result = np.asarray(ld.compute_latent_quadratic_forms(test_pts, xs, cov)) assert result.shape == (1, 2) # Distance 2 should give 4x the quadratic form of distance 1 np.testing.assert_allclose(result[0, 1] / result[0, 0], 4.0, atol=1e-4)
def test_compute_residuals_single_matches_manual(): """Verify compute_residuals_single = 0.5 * (x-mu)^T Sigma (x-mu).""" import jax.numpy as jnp
mu = np.array([1.0, 2.0], dtype=np.float32) cov = np.array([[2.0, 0.5], [0.5, 3.0]], dtype=np.float32) test_pt = np.array([3.0, 1.0], dtype=np.float32) diff = test_pt - mu expected = 0.5 * diff @ cov @ diff result = float(ld.compute_residuals_single(jnp.array(test_pt), jnp.array(mu), jnp.array(cov))) np.testing.assert_allclose(result, expected, atol=1e-5)
def test_compute_det_cov_xs_normalized_max_is_one(): cov = np.stack( [ np.eye(2, dtype=np.float32), np.array([[2.0, 0.0], [0.0, 2.0]], dtype=np.float32), ], axis=0, ) d = np.asarray(ld.compute_det_cov_xs(cov)) assert d.shape == (2,) assert np.isclose(np.max(d), 1.0) assert np.all(d > 0)
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
import jaximport jax.numpy as jnp
@pytest.mark.gpudef test_grid_mapping_roundtrip_gpu(gpu_device): bounds = np.array([[-2.0, 2.0], [0.0, 10.0]], dtype=np.float32) num_points = 11 x = np.array([0.4, 6.0], dtype=np.float32)
cpu_g = np.asarray(ld.pca_coord_to_grid(x, bounds, num_points, to_int=False)) cpu_rt = np.asarray(ld.grid_to_pca_coord(cpu_g, bounds, num_points))
with jax.default_device(gpu_device): x_g = jax.device_put(jnp.array(x), gpu_device) bounds_g = jax.device_put(jnp.array(bounds), gpu_device) gpu_g = np.asarray(ld.pca_coord_to_grid(x_g, bounds_g, num_points, to_int=False)) gpu_rt = np.asarray(ld.grid_to_pca_coord(gpu_g, bounds_g, num_points))
np.testing.assert_allclose(cpu_g, gpu_g, atol=1e-5, rtol=1e-5) np.testing.assert_allclose(cpu_rt, gpu_rt, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_compute_det_cov_xs_gpu(gpu_device): cov = np.stack( [ np.eye(2, dtype=np.float32), np.array([[2.0, 0.0], [0.0, 2.0]], dtype=np.float32), ], axis=0, )
cpu_d = np.asarray(ld.compute_det_cov_xs(cov))
with jax.default_device(gpu_device): cov_g = jax.device_put(jnp.array(cov), gpu_device) gpu_d = np.asarray(ld.compute_det_cov_xs(cov_g))
np.testing.assert_allclose(cpu_d, gpu_d, atol=1e-5, rtol=1e-5)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349import numpy as npimport pytest
pytest.importorskip("jax")
import recovar.core.fourier_transform_utils as fourier_transform_utilsimport recovar.core.linalg as linalg
pytestmark = pytest.mark.unit
def test_blockwise_xtx_matches_direct(): rng = np.random.default_rng(0) x = (rng.normal(size=(12, 5)) + 1j * rng.normal(size=(12, 5))).astype(np.complex64) out = linalg.blockwise_X_T_X(x, batch_size=4) ref = np.conj(x).T @ x np.testing.assert_allclose(out, ref, atol=5e-3, rtol=5e-3)
def test_broadcast_dot_and_outer(): x = np.array([[1 + 1j, 2 + 0j], [0 + 1j, 3 + 2j]], dtype=np.complex64) y = np.array([[2 + 0j, 1 + 1j], [1 - 1j, 0 + 2j]], dtype=np.complex64)
dot = np.asarray(linalg.broadcast_dot(x, y)) ref_dot = np.sum(np.conj(x) * y, axis=-1) np.testing.assert_allclose(dot, ref_dot, atol=1e-6, rtol=1e-6)
outer = np.asarray(linalg.broadcast_outer(x, y)) ref_outer = np.stack([np.outer(xi, np.conj(yi)) for xi, yi in zip(x, y)], axis=0) np.testing.assert_allclose(outer, ref_outer, atol=1e-6, rtol=1e-6)
def test_inner_product_and_batch_inner_product(): rng = np.random.default_rng(17) x = (rng.normal(size=(4, 6)) + 1j * rng.normal(size=(4, 6))).astype(np.complex64) y = (rng.normal(size=(4, 6)) + 1j * rng.normal(size=(4, 6))).astype(np.complex64)
nonbatch = np.asarray(linalg.inner_product(x[0], y[0])) ref_nonbatch = np.vdot(x[0], y[0]) np.testing.assert_allclose(nonbatch, ref_nonbatch, atol=1e-6, rtol=1e-6)
batch = np.asarray(linalg.batch_inner_product(x, y)) ref_batch = np.array([np.vdot(xi, yi) for xi, yi in zip(x, y)], dtype=np.complex64) np.testing.assert_allclose(batch, ref_batch, atol=1e-6, rtol=1e-6)
def test_inner_product_shape_validation(): with pytest.raises(ValueError, match="same shape"): linalg.inner_product(np.zeros((2,), dtype=np.complex64), np.zeros((3,), dtype=np.complex64)) with pytest.raises(ValueError, match="same shape"): linalg.batch_inner_product(np.zeros((2, 3), dtype=np.complex64), np.zeros((2, 4), dtype=np.complex64)) with pytest.raises(ValueError, match="ndim>=2"): linalg.batch_inner_product(np.zeros((3,), dtype=np.complex64), np.zeros((3,), dtype=np.complex64))
def test_half_spectrum_last_axis_weights_even_and_odd(): np.testing.assert_array_equal( np.asarray(linalg.half_spectrum_last_axis_weights(8)), np.array([1, 2, 2, 2, 1], dtype=np.float32), ) np.testing.assert_array_equal( np.asarray(linalg.half_spectrum_last_axis_weights(7)), np.array([1, 2, 2, 2], dtype=np.float32), )
def test_half_spectrum_inner_product_corrects_naive_dot_and_matches_full_fft(): rng = np.random.default_rng(29) shape = (6, 8) x = rng.normal(size=shape).astype(np.float32) y = rng.normal(size=shape).astype(np.float32)
fx = np.asarray(fourier_transform_utils.get_dft2(x)) fy = np.asarray(fourier_transform_utils.get_dft2(y)) sfx = np.asarray(fourier_transform_utils.get_dft2_real(x)) sfy = np.asarray(fourier_transform_utils.get_dft2_real(y))
full_ip = np.asarray(linalg.inner_product(fx, fy)) naive_half_ip = np.vdot(sfx, sfy) corrected_half_ip = np.asarray(linalg.half_spectrum_inner_product(sfx, sfy, shape))
# Naive packed-spectrum dot product misses Hermitian-pair contributions. assert np.abs(corrected_half_ip - naive_half_ip) > 1e-2 np.testing.assert_allclose(corrected_half_ip, full_ip, atol=1e-5, rtol=1e-5)
# Parseval under "backward" FFT normalization. spatial_ip = np.vdot(x, y) np.testing.assert_allclose(corrected_half_ip / np.prod(shape), spatial_ip, atol=1e-5, rtol=1e-5)
def test_batch_half_spectrum_inner_product_matches_full_fft_and_spatial_scaling(): rng = np.random.default_rng(31) shape = (6, 8) batch = 4 x = rng.normal(size=(batch,) + shape).astype(np.float32) y = rng.normal(size=(batch,) + shape).astype(np.float32)
fx = np.asarray(fourier_transform_utils.get_dft2(x)) fy = np.asarray(fourier_transform_utils.get_dft2(y)) sfx = np.asarray(fourier_transform_utils.get_dft2_real(x)) sfy = np.asarray(fourier_transform_utils.get_dft2_real(y))
full_ip = np.asarray(linalg.batch_inner_product(fx, fy)) corrected_half_ip = np.asarray(linalg.batch_half_spectrum_inner_product(sfx, sfy, shape)) np.testing.assert_allclose(corrected_half_ip, full_ip, atol=1e-5, rtol=1e-5)
spatial_ip = np.sum(np.conj(x) * y, axis=(-2, -1)) np.testing.assert_allclose(corrected_half_ip / np.prod(shape), spatial_ip, atol=1e-5, rtol=1e-5)
@pytest.mark.parametrize("full_shape", [(4, 8), (4, 4, 8)])def test_half_spectrum_inner_products_match_full_case(full_shape): rng = np.random.default_rng(19) if len(full_shape) == 2: x_real = rng.normal(size=full_shape).astype(np.float32) y_real = rng.normal(size=full_shape).astype(np.float32) x_full = np.asarray(fourier_transform_utils.get_dft2(x_real)) y_full = np.asarray(fourier_transform_utils.get_dft2(y_real)) x_half = np.asarray(fourier_transform_utils.get_dft2_real(x_real)) y_half = np.asarray(fourier_transform_utils.get_dft2_real(y_real)) else: x_real = rng.normal(size=full_shape).astype(np.float32) y_real = rng.normal(size=full_shape).astype(np.float32) x_full = np.asarray(fourier_transform_utils.get_dft3(x_real)) y_full = np.asarray(fourier_transform_utils.get_dft3(y_real)) x_half = np.asarray(fourier_transform_utils.get_dft3_real(x_real)) y_half = np.asarray(fourier_transform_utils.get_dft3_real(y_real))
full_ip = np.asarray(linalg.inner_product(x_full, y_full)) half_ip = np.asarray(linalg.half_spectrum_inner_product(x_half, y_half, full_shape)) np.testing.assert_allclose(half_ip, full_ip, atol=1e-3, rtol=1e-4)
@pytest.mark.parametrize("full_shape", [(4, 8), (4, 4, 8)])def test_batch_half_spectrum_inner_products_match_full_case(full_shape): rng = np.random.default_rng(23) batch = 3 if len(full_shape) == 2: x_real = rng.normal(size=(batch,) + full_shape).astype(np.float32) y_real = rng.normal(size=(batch,) + full_shape).astype(np.float32) x_full = np.asarray(fourier_transform_utils.get_dft2(x_real)) y_full = np.asarray(fourier_transform_utils.get_dft2(y_real)) x_half = np.asarray(fourier_transform_utils.get_dft2_real(x_real)) y_half = np.asarray(fourier_transform_utils.get_dft2_real(y_real)) else: x_real = rng.normal(size=(batch,) + full_shape).astype(np.float32) y_real = rng.normal(size=(batch,) + full_shape).astype(np.float32) x_full = np.asarray(fourier_transform_utils.get_dft3(x_real)) y_full = np.asarray(fourier_transform_utils.get_dft3(y_real)) x_half = np.asarray(fourier_transform_utils.get_dft3_real(x_real)) y_half = np.asarray(fourier_transform_utils.get_dft3_real(y_real))
full_ip = np.asarray(linalg.batch_inner_product(x_full, y_full)) half_ip = np.asarray(linalg.batch_half_spectrum_inner_product(x_half, y_half, full_shape)) np.testing.assert_allclose(half_ip, full_ip, atol=1e-3, rtol=1e-4)
def test_half_spectrum_inner_product_rejects_bad_shape(): with pytest.raises(ValueError, match="2 or 3 dims"): linalg.half_spectrum_inner_product( np.zeros((2, 2), dtype=np.complex64), np.zeros((2, 2), dtype=np.complex64), full_shape=(2,), )
def test_multiply_along_axis_and_l2_distance(): a = np.arange(2 * 3 * 4, dtype=np.float32).reshape(2, 3, 4) b = np.array([1.0, 2.0, 3.0], dtype=np.float32) out = np.asarray(linalg.multiply_along_axis(a, b, axis=1)) np.testing.assert_allclose(out[:, 0, :], a[:, 0, :] * 1.0) np.testing.assert_allclose(out[:, 1, :], a[:, 1, :] * 2.0) np.testing.assert_allclose(out[:, 2, :], a[:, 2, :] * 3.0)
x = np.array([[0.0, 0.0], [1.0, 0.0]], dtype=np.float32) y = np.array([[0.0, 1.0], [1.0, 1.0]], dtype=np.float32) d = np.asarray(linalg.l2_distance(x, y)) ref = np.array([[1.0, 2.0], [2.0, 1.0]], dtype=np.float32) np.testing.assert_allclose(d, ref, atol=1e-6, rtol=1e-6)
def test_batch_hermitian_linear_solver(): rng = np.random.default_rng(42) # Create a batch of 3x3 symmetric positive definite matrices raw = rng.normal(size=(5, 3, 3)).astype(np.float32) A = np.array([m @ m.T + 3 * np.eye(3) for m in raw], dtype=np.float32) b = rng.normal(size=(5, 3)).astype(np.float32) x = np.asarray(linalg.batch_hermitian_linear_solver(A, b)) # Check Ax ≈ b for i in range(5): np.testing.assert_allclose(A[i] @ x[i], b[i], atol=1e-4, rtol=1e-4)
def test_batch_linear_solver(): rng = np.random.default_rng(43) A = rng.normal(size=(4, 3, 3)).astype(np.float32) + 3 * np.eye(3, dtype=np.float32) b = rng.normal(size=(4, 3, 1)).astype(np.float32) x = np.asarray(linalg.batch_linear_solver(A, b)) for i in range(4): np.testing.assert_allclose(A[i] @ x[i], b[i], atol=1e-4, rtol=1e-4)
def test_solve_by_SVD(): rng = np.random.default_rng(44) # Batch of well-conditioned systems raw = rng.normal(size=(3, 4, 4)).astype(np.float32) A = np.array([m @ m.T + 5 * np.eye(4) for m in raw], dtype=np.float32) b = rng.normal(size=(3, 4)).astype(np.float32) x = np.asarray(linalg.solve_by_SVD(A, b)) for i in range(3): np.testing.assert_allclose(A[i] @ x[i], b[i], atol=1e-3, rtol=1e-3)
def test_thin_svd_matches_numpy(): rng = np.random.default_rng(45) X = (rng.normal(size=(10, 5)) + 1j * rng.normal(size=(10, 5))).astype(np.complex64) # thin_svd returns (U, sigma, V) where V are right singular vectors (not Vh) U, S, V = linalg.thin_svd(X, np=np) # Singular values should be non-negative and sorted descending assert np.all(S >= 0) assert np.all(S[:-1] >= S[1:]) # Reconstruction: U @ diag(S) @ V^H ≈ X reconstructed = (U * S[None, :]) @ np.conj(V).T np.testing.assert_allclose(reconstructed, X, atol=1e-2, rtol=1e-2)
def test_blockwise_ytx_matches_direct(): rng = np.random.default_rng(46) Y = (rng.normal(size=(12, 4)) + 1j * rng.normal(size=(12, 4))).astype(np.complex64) X = (rng.normal(size=(12, 3)) + 1j * rng.normal(size=(12, 3))).astype(np.complex64) out = linalg.blockwise_Y_T_X(Y, X, batch_size=4) ref = np.conj(Y).T @ X np.testing.assert_allclose(out, ref, atol=5e-3, rtol=5e-3)
def test_blockwise_ax_matches_direct(): rng = np.random.default_rng(47) A = rng.normal(size=(8, 6)).astype(np.float32) X = rng.normal(size=(6, 3)).astype(np.float32) out = linalg.blockwise_A_X(A, X, batch_size=3) ref = A @ X np.testing.assert_allclose(out, ref, atol=1e-4, rtol=1e-4)
def test_batch_dft3_and_idft3_roundtrip(): rng = np.random.default_rng(48) vol_shape = (4, 4, 4) vol_size = np.prod(vol_shape) n_vols = 3 x = rng.normal(size=(vol_size, n_vols)).astype(np.float32) x_ft = linalg.batch_dft3(x, vol_shape, batch_size=2) x_back = linalg.batch_idft3(x_ft, vol_shape, batch_size=2) np.testing.assert_allclose(x_back.real, x, atol=1e-4, rtol=1e-4)
def test_batch_st_end(): assert linalg.batch_st_end(0, 10, 100) == (0, 10) assert linalg.batch_st_end(2, 10, 25) == (20, 25) assert linalg.batch_st_end(9, 10, 100) == (90, 100)
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
import jaximport jax.numpy as jnp
@pytest.mark.gpudef test_blockwise_xtx_gpu(gpu_device): rng = np.random.default_rng(0) x = (rng.normal(size=(12, 5)) + 1j * rng.normal(size=(12, 5))).astype(np.complex64)
cpu_out = np.asarray(linalg.blockwise_X_T_X(x, batch_size=4))
with jax.default_device(gpu_device): x_g = jax.device_put(jnp.array(x), gpu_device) gpu_out = np.asarray(linalg.blockwise_X_T_X(x_g, batch_size=4))
np.testing.assert_allclose(cpu_out, gpu_out, atol=5e-3, rtol=5e-3)
@pytest.mark.gpudef test_broadcast_dot_and_outer_gpu(gpu_device): x = np.array([[1 + 1j, 2 + 0j], [0 + 1j, 3 + 2j]], dtype=np.complex64) y = np.array([[2 + 0j, 1 + 1j], [1 - 1j, 0 + 2j]], dtype=np.complex64)
cpu_dot = np.asarray(linalg.broadcast_dot(x, y)) cpu_outer = np.asarray(linalg.broadcast_outer(x, y))
with jax.default_device(gpu_device): x_g = jax.device_put(jnp.array(x), gpu_device) y_g = jax.device_put(jnp.array(y), gpu_device) gpu_dot = np.asarray(linalg.broadcast_dot(x_g, y_g)) gpu_outer = np.asarray(linalg.broadcast_outer(x_g, y_g))
np.testing.assert_allclose(cpu_dot, gpu_dot, atol=1e-5, rtol=1e-5) np.testing.assert_allclose(cpu_outer, gpu_outer, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_inner_product_gpu(gpu_device): rng = np.random.default_rng(17) x = (rng.normal(size=(4, 6)) + 1j * rng.normal(size=(4, 6))).astype(np.complex64) y = (rng.normal(size=(4, 6)) + 1j * rng.normal(size=(4, 6))).astype(np.complex64)
cpu_batch = np.asarray(linalg.batch_inner_product(x, y))
with jax.default_device(gpu_device): x_g = jax.device_put(jnp.array(x), gpu_device) y_g = jax.device_put(jnp.array(y), gpu_device) gpu_batch = np.asarray(linalg.batch_inner_product(x_g, y_g))
np.testing.assert_allclose(cpu_batch, gpu_batch, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_half_spectrum_inner_product_gpu(gpu_device): rng = np.random.default_rng(29) shape = (6, 8) x = rng.normal(size=shape).astype(np.float32) y = rng.normal(size=shape).astype(np.float32) sfx = np.asarray(fourier_transform_utils.get_dft2_real(x)) sfy = np.asarray(fourier_transform_utils.get_dft2_real(y))
cpu_out = np.asarray(linalg.half_spectrum_inner_product(sfx, sfy, shape))
with jax.default_device(gpu_device): sfx_g = jax.device_put(jnp.array(sfx), gpu_device) sfy_g = jax.device_put(jnp.array(sfy), gpu_device) gpu_out = np.asarray(linalg.half_spectrum_inner_product(sfx_g, sfy_g, shape))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_l2_distance_gpu(gpu_device): x = np.array([[0.0, 0.0], [1.0, 0.0]], dtype=np.float32) y = np.array([[0.0, 1.0], [1.0, 1.0]], dtype=np.float32)
cpu_out = np.asarray(linalg.l2_distance(x, y))
with jax.default_device(gpu_device): x_g = jax.device_put(jnp.array(x), gpu_device) y_g = jax.device_put(jnp.array(y), gpu_device) gpu_out = np.asarray(linalg.l2_distance(x_g, y_g))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339import numpy as npimport pytest
pytest.importorskip("jax")
from recovar.data_io import load_utilsfrom helpers import tiny_syntheticfrom recovar import utils
pytestmark = pytest.mark.unit
def test_load_ctf_params_rescales_apix_and_drops_size_column(monkeypatch): ctf = np.array( [ [128, 1.5, 10000, 11000, 0.0, 300, 2.7, 0.1, 0.0], [128, 1.5, 12000, 13000, 5.0, 300, 2.7, 0.1, 0.0], ], dtype=np.float32, ) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: ctf.copy())
out = load_utils.load_ctf_params(D=64, ctf_params_pkl="dummy.pkl")
assert out.shape == (2, 8) # original_D * original_Apix / D = 128 * 1.5 / 64 = 3.0 assert np.allclose(out[:, 0], 3.0) assert np.allclose(out[:, 1], [10000, 12000])
def test_load_ctf_params_rejects_odd_dimension(): with pytest.raises(ValueError, match="must be even"): load_utils.load_ctf_params(D=65, ctf_params_pkl="dummy.pkl")
def test_load_ctf_params_rejects_bad_param_width(monkeypatch): bad = np.zeros((3, 8), dtype=np.float32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: bad) with pytest.raises(ValueError, match="Expected 9 CTF parameters"): load_utils.load_ctf_params(D=64, ctf_params_pkl="dummy.pkl")
def test_load_ctf_params_accepts_list_payload(monkeypatch): ctf_list = [ [128, 1.5, 10000, 11000, 0.0, 300, 2.7, 0.1, 0.0], [128, 1.5, 12000, 13000, 5.0, 300, 2.7, 0.1, 0.0], ] monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: ctf_list)
out = load_utils.load_ctf_params(D=64, ctf_params_pkl="dummy.pkl") assert out.shape == (2, 8) assert np.allclose(out[:, 0], 3.0)
def test_load_ctf_params_rejects_non_2d_payload(monkeypatch): monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: np.zeros((9,), dtype=np.float32)) with pytest.raises(ValueError, match="must be a 2D array"): load_utils.load_ctf_params(D=64, ctf_params_pkl="dummy.pkl")
def test_load_ctf_params_rejects_nonnumeric_payload(monkeypatch): bad = np.array([["a"] * 9], dtype=object) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: bad) with pytest.raises(ValueError, match="must be numeric"): load_utils.load_ctf_params(D=64, ctf_params_pkl="dummy.pkl")
def test_load_ctf_params_rejects_empty_payload(monkeypatch): monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: np.zeros((0, 9), dtype=np.float32)) with pytest.raises(ValueError, match="are empty"): load_utils.load_ctf_params(D=64, ctf_params_pkl="dummy.pkl")
def test_load_ctf_params_rejects_nonfinite_payload(monkeypatch): bad = np.array([[128, 1.5, np.nan, 11000, 0.0, 300, 2.7, 0.1, 0.0]], dtype=np.float32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: bad) with pytest.raises(ValueError, match="non-finite"): load_utils.load_ctf_params(D=64, ctf_params_pkl="dummy.pkl")
def test_load_poses_single_file_with_translations_scales_by_D(monkeypatch): rots = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 3, axis=0) trans_frac = np.array([[0.0, 0.5], [1.0, 0.25], [0.1, 0.2]], dtype=np.float32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots, trans_frac))
rots_out, trans_out, D_out = load_utils.load_poses("poses.pkl", Nimg=3, D=128)
assert D_out == 128 assert rots_out.shape == (3, 3, 3) assert trans_out.shape == (3, 2) assert np.allclose(trans_out, trans_frac * 128)
def test_load_poses_two_file_input(monkeypatch): rots = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 2, axis=0) trans_frac = np.array([[0.25, 0.75], [0.5, 0.5]], dtype=np.float32)
def fake_pickle_load(path): if path == "rots.pkl": return rots if path == "trans.pkl": return trans_frac raise AssertionError("unexpected path")
monkeypatch.setattr(load_utils.utils, "pickle_load", fake_pickle_load) rots_out, trans_out, _ = load_utils.load_poses(["rots.pkl", "trans.pkl"], Nimg=2, D=64) assert np.allclose(rots_out, rots) assert np.allclose(trans_out, trans_frac * 64)
def test_load_poses_accepts_list_payload_and_applies_indices(monkeypatch): rots_list = [np.eye(3, dtype=np.float32) * (i + 1) for i in range(4)] trans_list = [[0.0, 0.1], [0.2, 0.3], [0.4, 0.5], [0.6, 0.7]] monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots_list, trans_list))
ind = np.array([3, 1, 3], dtype=np.int32) rots_out, trans_out, D_out = load_utils.load_poses("poses.pkl", Nimg=3, D=10, ind=ind) assert D_out == 10 np.testing.assert_allclose(rots_out[:, 0, 0], np.array([4.0, 2.0, 4.0], dtype=np.float32)) np.testing.assert_allclose(trans_out, np.array([[0.6, 0.7], [0.2, 0.3], [0.6, 0.7]], dtype=np.float32) * 10.0)
def test_load_poses_index_filter_applies_when_input_is_longer(monkeypatch): rots_all = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 5, axis=0) trans_all = np.linspace(0.0, 0.9, 10, dtype=np.float32).reshape(5, 2) ind = np.array([0, 2, 4], dtype=np.int32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots_all, trans_all))
rots_out, trans_out, _ = load_utils.load_poses("poses.pkl", Nimg=3, D=100, ind=ind) assert rots_out.shape == (3, 3, 3) assert trans_out.shape == (3, 2) assert np.allclose(trans_out, trans_all[ind] * 100)
def test_load_poses_index_filter_accepts_boolean_mask_when_input_is_longer(monkeypatch): rots_all = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 5, axis=0) trans_all = np.linspace(0.0, 0.9, 10, dtype=np.float32).reshape(5, 2) mask = np.array([True, False, True, False, True], dtype=bool) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots_all, trans_all))
rots_out, trans_out, _ = load_utils.load_poses("poses.pkl", Nimg=3, D=80, ind=mask) assert rots_out.shape == (3, 3, 3) np.testing.assert_allclose(trans_out, trans_all[[0, 2, 4]] * 80.0)
def test_load_poses_applies_index_filter_when_lengths_match_for_duplicate_permuted_indices(monkeypatch): rots_all = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 6, axis=0) rots_all[:, 0, 0] = np.arange(1, 7, dtype=np.float32) trans_all = np.array( [ [0.0, 0.1], [0.2, 0.3], [0.4, 0.5], [0.6, 0.7], [0.8, 0.9], [0.1, 0.0], ], dtype=np.float32, ) requested = np.array([5, 0, 5, 1, 2, 3], dtype=np.int32) # len == Nimg, with duplicates/permutation monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots_all, trans_all))
rots_out, trans_out, _ = load_utils.load_poses("poses.pkl", Nimg=6, D=20, ind=requested)
np.testing.assert_allclose(rots_out[:, 0, 0], rots_all[requested, 0, 0]) np.testing.assert_allclose(trans_out, trans_all[requested] * 20.0)
def test_load_poses_index_filter_rejects_bad_masks_or_indices(monkeypatch): rots_all = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 5, axis=0) trans_all = np.linspace(0.0, 0.9, 10, dtype=np.float32).reshape(5, 2) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots_all, trans_all))
with pytest.raises(ValueError, match="boolean mask must be 1D"): load_utils.load_poses("poses.pkl", Nimg=3, D=64, ind=np.array([[True, False, True, False, True]], dtype=bool)) with pytest.raises(ValueError, match="boolean mask length.*must match total size"): load_utils.load_poses("poses.pkl", Nimg=3, D=64, ind=np.array([True, False], dtype=bool)) with pytest.raises(IndexError, match="negative"): load_utils.load_poses("poses.pkl", Nimg=3, D=64, ind=np.array([0, -1, 2], dtype=np.int32)) with pytest.raises(IndexError, match="out-of-range"): load_utils.load_poses("poses.pkl", Nimg=3, D=64, ind=np.array([0, 2, 9], dtype=np.int32))
def test_load_poses_rejects_old_pixel_translation_format(monkeypatch): rots = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 2, axis=0) trans_pixels = np.array([[2.0, 3.0], [4.0, 5.0]], dtype=np.float32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots, trans_pixels)) with pytest.raises(ValueError, match="fractional units"): load_utils.load_poses("poses.pkl", Nimg=2, D=64)
def test_load_poses_rejects_negative_values_with_abs_gt_one(monkeypatch): rots = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 2, axis=0) trans_bad = np.array([[-1.2, 0.1], [0.2, -1.1]], dtype=np.float32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots, trans_bad)) with pytest.raises(ValueError, match=r"\|value\| <= 1"): load_utils.load_poses("poses.pkl", Nimg=2, D=64)
def test_load_poses_rejects_nonnumeric_rotation_or_translation(monkeypatch): rots_bad = np.array([[["a"] * 3] * 3] * 2, dtype=object) trans_ok = np.array([[0.1, 0.2], [0.3, 0.4]], dtype=np.float32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots_bad, trans_ok)) with pytest.raises(ValueError, match="Rotation array must be numeric"): load_utils.load_poses("poses.pkl", Nimg=2, D=64)
rots_ok = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 2, axis=0) trans_bad = np.array([["x", "y"], ["u", "v"]], dtype=object) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots_ok, trans_bad)) with pytest.raises(ValueError, match="Translation array must be numeric"): load_utils.load_poses("poses.pkl", Nimg=2, D=64)
def test_load_poses_rejects_nonfinite_rotation_or_translation(monkeypatch): rots_bad = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 2, axis=0) rots_bad[1, 0, 0] = np.nan trans_ok = np.array([[0.1, 0.2], [0.3, 0.4]], dtype=np.float32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots_bad, trans_ok)) with pytest.raises(ValueError, match="Rotation array contains non-finite"): load_utils.load_poses("poses.pkl", Nimg=2, D=64)
rots_ok = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 2, axis=0) trans_bad = np.array([[0.1, 0.2], [np.inf, 0.4]], dtype=np.float32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots_ok, trans_bad)) with pytest.raises(ValueError, match="Translation array contains non-finite"): load_utils.load_poses("poses.pkl", Nimg=2, D=64)
def test_load_poses_rejects_bad_shapes(monkeypatch): bad_rots = np.zeros((2, 2, 2), dtype=np.float32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: bad_rots) with pytest.raises(ValueError, match="Rotation array has shape"): load_utils.load_poses("poses.pkl", Nimg=2, D=64)
def test_load_poses_rejects_invalid_number_of_input_files(): with pytest.raises(ValueError, match="Expected 1 or 2 input files"): load_utils.load_poses(["a.pkl", "b.pkl", "c.pkl"], Nimg=2, D=64)
def test_load_poses_rotations_only_returns_none_translation(monkeypatch): rots = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 3, axis=0) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: rots) rots_out, trans_out, D_out = load_utils.load_poses("poses.pkl", Nimg=3, D=32) assert D_out == 32 np.testing.assert_array_equal(rots_out, rots) assert trans_out is None
def test_load_ctf_params_from_tiny_file_roundtrip(tmp_path): files = tiny_synthetic.make_tiny_loader_files(tmp_path, grid_size=8, n_images=5, n_particles=2) out = load_utils.load_ctf_params(D=8, ctf_params_pkl=files["ctf_pkl"]) assert out.shape == (5, 8) # Column 0 in return is Apix and should stay 1.5 when D is unchanged. assert np.allclose(out[:, 0], 1.5) assert np.allclose(out[:, 4], 300.0) # voltage
def test_load_poses_from_tiny_file_roundtrip(tmp_path): files = tiny_synthetic.make_tiny_loader_files(tmp_path, grid_size=8, n_images=6, n_particles=3) rots, trans, D_out = load_utils.load_poses(files["poses_pkl"], Nimg=6, D=8) assert D_out == 8 assert rots.shape == (6, 3, 3) assert trans.shape == (6, 2) # tiny helper writes zero fractional shifts; conversion to pixels keeps zeros. np.testing.assert_array_equal(trans, np.zeros((6, 2), dtype=np.float32))
def test_load_poses_two_file_real_pickles(tmp_path): rots = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 4, axis=0) trans_frac = np.array([[0.0, 0.0], [0.25, 0.5], [0.5, 0.25], [1.0, 1.0]], dtype=np.float32) rots_pkl = tmp_path / "rots.pkl" trans_pkl = tmp_path / "trans.pkl" utils.pickle_dump(rots, str(rots_pkl)) utils.pickle_dump(trans_frac, str(trans_pkl)) rots_out, trans_out, D_out = load_utils.load_poses([str(rots_pkl), str(trans_pkl)], Nimg=4, D=10) assert D_out == 10 np.testing.assert_array_equal(rots_out, rots) np.testing.assert_allclose(trans_out, trans_frac * 10.0)
def test_load_poses_rejects_rotation_translation_count_mismatch(monkeypatch): rots = np.repeat(np.eye(3, dtype=np.float32)[None, :, :], 3, axis=0) trans_frac = np.zeros((4, 2), dtype=np.float32) monkeypatch.setattr(load_utils.utils, "pickle_load", lambda _: (rots, trans_frac))
with pytest.raises(ValueError, match="count mismatch"): load_utils.load_poses("poses.pkl", Nimg=3, D=8)
def test_load_poses_from_tiny_tilt_simulator_subset_preserves_duplicates_and_alignment(tmp_path): files = tiny_synthetic.make_tiny_tilt_loader_files_from_simulator( tmp_path / "tiny_tilt_pose_subset", grid_size=8, n_images=12, n_tilts=3, n_volumes=3, ) requested = np.array([5, 1, 5, 9], dtype=np.int32)
rots_all, trans_all, _ = load_utils.load_poses(files["poses_pkl"], Nimg=12, D=8) rots_sub, trans_sub, D_out = load_utils.load_poses( files["poses_pkl"], Nimg=len(requested), D=8, ind=requested, )
assert D_out == 8 np.testing.assert_allclose(rots_sub, rots_all[requested]) np.testing.assert_allclose(trans_sub, trans_all[requested])
def test_load_poses_from_tiny_tilt_simulator_boolean_mask_subset_matches_integer_selection(tmp_path): files = tiny_synthetic.make_tiny_tilt_loader_files_from_simulator( tmp_path / "tiny_tilt_pose_mask", grid_size=8, n_images=10, n_tilts=2, n_volumes=3, ) mask = np.array([True, False, True, False, False, True, False, True, False, False], dtype=bool) requested = np.flatnonzero(mask)
rots_mask, trans_mask, _ = load_utils.load_poses( files["poses_pkl"], Nimg=int(mask.sum()), D=8, ind=mask, ) rots_idx, trans_idx, _ = load_utils.load_poses( files["poses_pkl"], Nimg=len(requested), D=8, ind=requested, )
np.testing.assert_allclose(rots_mask, rots_idx) np.testing.assert_allclose(trans_mask, trans_idx)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351import numpy as npimport pytest
pytest.importorskip("jax")
import recovar.heterogeneity.locres as locres
pytestmark = pytest.mark.unit
def test_find_first_zero_in_bool_handles_mixed_and_all_ones(): arr = np.array([True, True, False, False]) out = int(np.asarray(locres.find_first_zero_in_bool(arr))) assert out == 2
all_ones = np.array([True, True, True]) out_all = int(np.asarray(locres.find_first_zero_in_bool(all_ones))) assert out_all == 2
def test_integral_fsc_uses_prefix_until_first_negative(): fsc = np.array([0.9, 0.5, -0.1, 0.4], dtype=np.float32) out = float(np.asarray(locres.integral_fsc(fsc, fourier_pixel_size=2.0))) # Only first two entries should contribute. assert out == pytest.approx((0.9 + 0.5) * 2.0)
def test_integral_fsc_all_nonnegative_keeps_full_curve(): fsc = np.array([0.9, 0.5, 0.1, 0.2], dtype=np.float32) out = float(np.asarray(locres.integral_fsc(fsc, fourier_pixel_size=1.5))) assert out == pytest.approx(float(np.sum(fsc)) * 1.5)
def test_local_error_subvolume_size_uses_multiplier(): s1 = locres.get_local_error_subvolume_size(locres_maskrad=6.0, voxel_size=1.0, multiplier=1) s3 = locres.get_local_error_subvolume_size(locres_maskrad=6.0, voxel_size=1.0, multiplier=3) assert s3 == 3 * s1
def test_sampling_points_and_volume_shapes(): sampling_points = np.asarray( locres.get_sampling_points(grid_size=16, locres_sampling=4, locres_maskrad=4, voxel_size=1.0) ) assert sampling_points.ndim == 2 assert sampling_points.shape[1] == 3 assert sampling_points.shape[0] > 0
vol = locres.make_sampling_volume(grid_size=16, locres_sampling=4, voxel_size=1.0, locres_maskrad=4) assert vol.shape == (16, 16, 16) assert np.isfinite(vol).all()
def test_sampling_helpers_accept_none_maskrad_defaults(): sp = np.asarray(locres.get_sampling_points(grid_size=8, locres_sampling=2, locres_maskrad=None, voxel_size=1.5)) assert sp.ndim == 2 and sp.shape[1] == 3 assert sp.shape[0] > 0
vol = np.asarray(locres.make_sampling_volume(grid_size=8, locres_sampling=2, voxel_size=1.5, locres_maskrad=None)) assert vol.shape == (8, 8, 8) assert np.isfinite(vol).all()
def test_find_fsc_resol_basic(): """find_fsc_resol interpolates FSC to find threshold crossing.""" import jax.numpy as jnp
# FSC curve that drops linearly from 1 to 0 fsc = jnp.array([1.0, 0.8, 0.5, 0.2, 0.0], dtype=jnp.float32) # With threshold 1/7 ≈ 0.143, should cross between index 3 (0.2) and 4 (0.0) resol = float(np.asarray(locres.find_fsc_resol(fsc, threshold=0.5))) # threshold 0.5 should cross at index 2 (where fsc == 0.5) assert 1.5 <= resol <= 2.5
resol_low = float(np.asarray(locres.find_fsc_resol(fsc, threshold=0.1))) # threshold 0.1 is between 0.2 (idx 3) and 0.0 (idx 4) assert 3.0 <= resol_low <= 4.0
def test_find_fsc_resol_all_above_threshold(): """If entire FSC is above threshold, return last index.""" import jax.numpy as jnp
fsc = jnp.ones(5, dtype=jnp.float32) * 0.9 resol = float(np.asarray(locres.find_fsc_resol(fsc, threshold=0.5))) assert resol == pytest.approx(4.0, abs=0.1)
def test_apply_fsc_weighting_shape_and_finiteness(): """apply_fsc_weighting should preserve shape and produce finite values.""" import jax.numpy as jnp
rng = np.random.default_rng(0) vol = jnp.array(rng.normal(size=(8, 8, 8)).astype(np.float32)) fsc = jnp.array([1.0, 0.9, 0.7, 0.3], dtype=jnp.float32) out = np.asarray(locres.apply_fsc_weighting(vol, fsc)) assert out.shape == (8, 8, 8) assert np.all(np.isfinite(out))
def test_apply_fsc_weighting_all_positive_fsc_keeps_last_shell_full_and_half(): import jax.numpy as jnp
fsc = jnp.array([1.0, 1.0, 1.0, 1.0], dtype=jnp.float32)
full = jnp.ones((4, 4, 4), dtype=jnp.float32) out_full = np.asarray(locres.apply_fsc_weighting(full, fsc)) np.testing.assert_allclose(out_full, np.ones_like(out_full), rtol=1e-6, atol=1e-6)
half = jnp.ones((4, 4, 3), dtype=jnp.float32) out_half = np.asarray(locres.apply_fsc_weighting(half, fsc, volume_shape=(4, 4, 4))) np.testing.assert_allclose(out_half, np.ones_like(out_half), rtol=1e-6, atol=1e-6)
def test_low_pass_filter_attenuates_high_freq(): """low_pass_filter_map should reduce total energy by removing high frequencies.""" import jax.numpy as jnp import recovar.core.fourier_transform_utils as ftu
rng = np.random.default_rng(1) size = 16 vol = jnp.array(rng.normal(size=(size, size, size)).astype(np.float32)) FT = ftu.get_dft3(vol) # Apply low-pass filter filtered = np.asarray(locres.low_pass_filter_map(FT, size, 8.0, 1.0, 2)) assert filtered.shape == FT.shape # Energy should be reduced (some frequencies zeroed) assert np.sum(np.abs(filtered) ** 2) < np.sum(np.abs(np.asarray(FT)) ** 2) # The output should still be finite assert np.all(np.isfinite(filtered))
def test_get_local_error_subvolume_rad(): """get_local_error_subvolume_rad should return radius in pixels.""" rad = locres.get_local_error_subvolume_rad(locres_maskrad=6.0, voxel_size=1.0, multiplier=3) assert rad == 18 rad2 = locres.get_local_error_subvolume_rad(locres_maskrad=6.0, voxel_size=2.0, multiplier=2) assert rad2 == 6 # round(6/2)*2 = 3*2
def test_expensive_local_error_with_cov_accepts_none_defaults(): rng = np.random.default_rng(0) map1 = rng.normal(size=(8, 8, 8)).astype(np.float32) map2 = rng.normal(size=(8, 8, 8)).astype(np.float32) noise_variance = np.ones((8, 8, 8), dtype=np.float32)
out = locres.expensive_local_error_with_cov( map1=map1, map2=map2, voxel_size=1.5, noise_variance=noise_variance, locres_sampling=2, locres_maskrad=None, locres_edgwidth=None, use_v2=True, split_shell=False, ) out = np.asarray(out) assert out.shape == map1.shape assert np.isfinite(out).all()
def test_split_by_shells_distributes_voxels_by_radial_distance(): """Each shell row should contain only voxels at that radial distance.""" import jax.numpy as jnp
vol_shape = (4, 4, 4) vol_size = 64 input_vec = jnp.arange(vol_size, dtype=jnp.float32) result = np.asarray(locres.split_by_shells(input_vec, vol_shape)) # Shape: (grid_size//2, vol_size) = (2, 64) since input is 1D assert result.shape == (2, vol_size) # Each shell should have some non-zero entries (at least shell 0) assert np.any(result[0] != 0)
def test_subsample_array_extracts_correct_subvolume(): """subsample_array should extract a cube centered at offset.""" import jax.numpy as jnp
vol = jnp.arange(64, dtype=jnp.float32).reshape(4, 4, 4) center = jnp.array([2, 2, 2], dtype=jnp.int32) radius = 1 sub = np.asarray(locres.subsample_array(vol, center, radius)) assert sub.shape == (2, 2, 2) # Should contain the center region assert np.all(np.isfinite(sub))
def test_convolve_mask_at_sampling_points_shape(): """Output shape should match the full mask shape.""" import jax.numpy as jnp
full_mask = jnp.ones((8, 8, 8), dtype=jnp.float32) sampling_pts = jnp.array([[0, 0, 0], [1, 1, 1]], dtype=jnp.int32) values = jnp.array([1.0, 2.0], dtype=jnp.float32) result = np.asarray(locres.convolve_mask_at_sampling_points(sampling_pts, values, full_mask)) assert result.shape == (8, 8, 8) assert np.all(np.isfinite(result))
def test_get_sampling_points_returns_valid_points(): """Sampling points should be within grid bounds.""" grid_size = 16 locres_sampling = 4 locres_maskrad = 2 voxel_size = 1.0 pts = np.asarray(locres.get_sampling_points(grid_size, locres_sampling, locres_maskrad, voxel_size)) assert pts.ndim == 2 assert pts.shape[1] == 3 # Points should be centered around 0 assert np.all(np.abs(pts) < grid_size // 2)
def test_make_sampling_volume_shape(): """make_sampling_volume should return volume of correct grid size.""" vol = np.asarray(locres.make_sampling_volume(8, 2, 1.0, 1.0)) assert vol.shape == (8, 8, 8)
def test_masked_noisy_error_split_over_shells_v1_runs(): """masked_noisy_error_split_over_shells should return finite per-shell norms.""" import jax.numpy as jnp
rng = np.random.default_rng(42) size = 12 diff = jnp.array(rng.normal(size=(size, size, size)).astype(np.float32)) # noise_variance_small matches the subsampled volume size maskrad_pix = 2 multiplier = 3 sub_size = 2 * multiplier * maskrad_pix noise_var = jnp.ones((sub_size, sub_size, sub_size), dtype=jnp.float32) offset = jnp.array([0, 0, 0], dtype=jnp.int32) result = np.asarray( locres.masked_noisy_error_split_over_shells(diff, noise_var, offset, maskrad_pix, 2, multiplier) ) assert result.ndim == 1 assert np.all(np.isfinite(result)) assert np.all(result >= 0)
def test_masked_noisy_error_split_over_shells_v2_runs(): """masked_noisy_error_split_over_shells_v2 should return finite per-shell norms.
This also verifies the fix for the previously undefined `diff_masked` variable. """ import jax.numpy as jnp
rng = np.random.default_rng(42) size = 12 diff = jnp.array(rng.normal(size=(size, size, size)).astype(np.float32)) maskrad_pix = 2 multiplier = 3 sub_size = 2 * multiplier * maskrad_pix noise_var = jnp.ones((sub_size, sub_size, sub_size), dtype=jnp.float32) offset = jnp.array([0, 0, 0], dtype=jnp.int32) result = np.asarray( locres.masked_noisy_error_split_over_shells_v2(diff, noise_var, offset, maskrad_pix, 2, multiplier) ) assert result.ndim == 1 assert np.all(np.isfinite(result)) assert np.all(result >= 0)
def test_masked_noisy_error_basic(): """masked_noisy_error should return a positive finite scalar.""" import jax.numpy as jnp
rng = np.random.default_rng(42) size = 8 diff = jnp.array(rng.normal(size=(size, size, size)).astype(np.float32)) noise_var = jnp.ones((size, size, size), dtype=jnp.float32) offset = jnp.array([0, 0, 0], dtype=jnp.int32) result = float(np.asarray(locres.masked_noisy_error(diff, noise_var, offset, 2, 2))) assert np.isfinite(result) assert result >= 0
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
import jaximport jax.numpy as jnp
@pytest.mark.gpudef test_integral_fsc_gpu(gpu_device): fsc = np.array([0.9, 0.5, -0.1, 0.4], dtype=np.float32)
cpu_out = float(np.asarray(locres.integral_fsc(fsc, fourier_pixel_size=2.0)))
with jax.default_device(gpu_device): fsc_g = jax.device_put(jnp.array(fsc), gpu_device) gpu_out = float(np.asarray(locres.integral_fsc(fsc_g, fourier_pixel_size=2.0)))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_find_first_zero_in_bool_gpu(gpu_device): arr = np.array([True, True, False, False])
cpu_out = int(np.asarray(locres.find_first_zero_in_bool(arr)))
with jax.default_device(gpu_device): arr_g = jax.device_put(jnp.array(arr), gpu_device) gpu_out = int(np.asarray(locres.find_first_zero_in_bool(arr_g)))
assert cpu_out == gpu_out
@pytest.mark.gpudef test_expensive_local_error_with_cov_gpu(gpu_device): rng = np.random.default_rng(0) map1 = rng.normal(size=(8, 8, 8)).astype(np.float32) map2 = rng.normal(size=(8, 8, 8)).astype(np.float32) noise_variance = np.ones((8, 8, 8), dtype=np.float32)
cpu_out = np.asarray( locres.expensive_local_error_with_cov( map1=map1, map2=map2, voxel_size=1.5, noise_variance=noise_variance, locres_sampling=2, locres_maskrad=None, locres_edgwidth=None, use_v2=True, split_shell=False, ) )
with jax.default_device(gpu_device): map1_g = jax.device_put(jnp.array(map1), gpu_device) map2_g = jax.device_put(jnp.array(map2), gpu_device) noise_g = jax.device_put(jnp.array(noise_variance), gpu_device) gpu_out = np.asarray( locres.expensive_local_error_with_cov( map1=map1_g, map2=map2_g, voxel_size=1.5, noise_variance=noise_g, locres_sampling=2, locres_maskrad=None, locres_edgwidth=None, use_v2=True, split_shell=False, ) )
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-4, rtol=1e-4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265import numpy as npimport pytest
pytest.importorskip("jax")
from recovar.core import mask as mask_fnimport recovar.core.fourier_transform_utils as fourier_transform_utilsfrom recovar.heterogeneity import locresfrom recovar.reconstruction import regularization
pytestmark = pytest.mark.unit
def _legacy_sampling_points(grid_size, locres_sampling, locres_maskrad, voxel_size): locres_maskrad = 0.5 * locres_sampling if locres_maskrad is None else locres_maskrad maskrad_pix = np.round(locres_maskrad / voxel_size).astype(int) step_size = np.round(locres_sampling / voxel_size).astype(int) myrad = grid_size // 2 - maskrad_pix
sampling_points = [] grid = np.array(fourier_transform_utils.get_1d_frequency_grid(grid_size, 1, scaled=False)[::step_size]) for kk in grid: for ii in grid: for jj in grid: rad = np.sqrt(kk * kk + ii * ii + jj * jj) if rad < myrad: sampling_points.append((kk, ii, jj)) return np.asarray(sampling_points, dtype=np.int32)
def _legacy_local_error(map1, map2, voxel_size, locres_sampling, locres_maskrad, locres_edgwidth, low_pass_filter_res): locres_maskrad = 0.5 * locres_sampling if locres_maskrad is None else locres_maskrad locres_edgwidth = locres_sampling if locres_edgwidth is None else locres_edgwidth edgewidth_pix = np.round(locres_edgwidth / voxel_size).astype(int)
mask = mask_fn.raised_cosine_mask(map1.shape, locres_maskrad, locres_maskrad + edgewidth_pix, -1) mask = mask / np.linalg.norm(mask)
if low_pass_filter_res is not None: map1_ft = fourier_transform_utils.get_dft3(map1) map1_ft = locres.low_pass_filter_map( map1_ft, map1_ft.shape[0], low_pass_filter_res, voxel_size, edgewidth_pix, do_highpass_instead=False, ) map1 = fourier_transform_utils.get_idft3(map1_ft).real
map2_ft = fourier_transform_utils.get_dft3(map2) map2_ft = locres.low_pass_filter_map( map2_ft, map2_ft.shape[0], low_pass_filter_res, voxel_size, edgewidth_pix, do_highpass_instead=False, ) map2 = fourier_transform_utils.get_idft3(map2_ft).real
mask_ft = fourier_transform_utils.get_dft3(mask) map1_square_ft = fourier_transform_utils.get_dft3(map1 * map1) map2_square_ft = fourier_transform_utils.get_dft3(map2 * map2) map1map2_ft = fourier_transform_utils.get_dft3(map1 * map2)
local_errors = ( fourier_transform_utils.get_idft3(map1_square_ft * mask_ft).real - 2 * fourier_transform_utils.get_idft3(map1map2_ft * mask_ft) + fourier_transform_utils.get_idft3(map2_square_ft * mask_ft) ) return np.asarray(local_errors.real)
def _legacy_local_error_with_cov( map1, map2, voxel_size, locres_sampling, locres_maskrad, locres_edgwidth, low_pass_filter_res, noise_variance,): locres_maskrad = 0.5 * locres_sampling if locres_maskrad is None else locres_maskrad locres_edgwidth = locres_sampling if locres_edgwidth is None else locres_edgwidth edgewidth_pix = np.round(locres_edgwidth / voxel_size).astype(int)
mask = mask_fn.raised_cosine_mask(map1.shape, locres_maskrad, locres_maskrad + edgewidth_pix, -1)
if low_pass_filter_res is not None: map1_ft = fourier_transform_utils.get_dft3(map1) map1_ft = locres.low_pass_filter_map( map1_ft, map1_ft.shape[0], low_pass_filter_res, voxel_size, edgewidth_pix, do_highpass_instead=False, ) map1 = fourier_transform_utils.get_idft3(map1_ft).real
map2_ft = fourier_transform_utils.get_dft3(map2) map2_ft = locres.low_pass_filter_map( map2_ft, map2_ft.shape[0], low_pass_filter_res, voxel_size, edgewidth_pix, do_highpass_instead=False, ) map2 = fourier_transform_utils.get_idft3(map2_ft).real
if noise_variance is not None: noise_variance = noise_variance.reshape(map1.shape) noise_scale = np.sqrt(noise_variance).reshape(map1.shape) map1 = fourier_transform_utils.get_idft3(fourier_transform_utils.get_dft3(map1) * noise_scale).real map2 = fourier_transform_utils.get_idft3(fourier_transform_utils.get_dft3(map2) * noise_scale).real
mask_ft = fourier_transform_utils.get_dft3(mask) map1_square_ft = fourier_transform_utils.get_dft3(map1 * map1) map2_square_ft = fourier_transform_utils.get_dft3(map2 * map2) map1map2_ft = fourier_transform_utils.get_dft3(map1 * map2)
local_errors = ( fourier_transform_utils.get_idft3(map1_square_ft * mask_ft).real - 2 * fourier_transform_utils.get_idft3(map1map2_ft * mask_ft) + fourier_transform_utils.get_idft3(map2_square_ft * mask_ft) ) return np.asarray(local_errors.real)
def test_get_sampling_points_matches_legacy_loop_order_and_values(): got = np.asarray(locres.get_sampling_points(20, 5, 2.0, 1.0)) expected = _legacy_sampling_points(20, 5, 2.0, 1.0) np.testing.assert_array_equal(got, expected)
def test_filter_with_local_fsc_half_matches_full(): rng = np.random.default_rng(0) volume_shape = (12, 12, 12) map1 = rng.standard_normal(volume_shape).astype(np.float32) map2 = rng.standard_normal(volume_shape).astype(np.float32)
fsc = regularization.get_fsc( fourier_transform_utils.get_dft3(map1), fourier_transform_utils.get_dft3(map2), volume_shape=volume_shape, ) ft_full = fourier_transform_utils.get_dft3(0.5 * (map1 + map2)) ft_half = fourier_transform_utils.get_dft3_real(0.5 * (map1 + map2))
out_full = np.asarray( locres.filter_with_local_fsc( ft_full, fsc, local_resol=8.0, voxel_size=1.5, filter_edgewidth=2, volume_shape=volume_shape, ) ) out_half = np.asarray( locres.filter_with_local_fsc( ft_half, fsc, local_resol=8.0, voxel_size=1.5, filter_edgewidth=2, volume_shape=volume_shape, ) ) np.testing.assert_allclose(out_half, out_full, rtol=1e-5, atol=1e-5)
def test_local_error_matches_legacy_full_fft_implementation(): rng = np.random.default_rng(1) volume_shape = (12, 12, 12) map1 = rng.standard_normal(volume_shape).astype(np.float32) map2 = rng.standard_normal(volume_shape).astype(np.float32)
kwargs = dict( voxel_size=1.5, locres_sampling=6, locres_maskrad=3.0, locres_edgwidth=4.5, low_pass_filter_res=8.0, )
expected = _legacy_local_error(map1.copy(), map2.copy(), **kwargs) got = np.asarray(locres.local_error(map1.copy(), map2.copy(), **kwargs)) np.testing.assert_allclose(got, expected, rtol=1e-5, atol=1e-5)
def test_local_error_with_cov_matches_legacy_full_fft_implementation(): rng = np.random.default_rng(2) volume_shape = (12, 12, 12) map1 = rng.standard_normal(volume_shape).astype(np.float32) map2 = rng.standard_normal(volume_shape).astype(np.float32) noise_variance = (0.1 + rng.random(volume_shape)).astype(np.float32)
kwargs = dict( voxel_size=1.5, locres_sampling=6, locres_maskrad=3.0, locres_edgwidth=4.5, low_pass_filter_res=7.0, )
expected = _legacy_local_error_with_cov( map1.copy(), map2.copy(), noise_variance=noise_variance.copy(), **kwargs, ) got = np.asarray( locres.local_error_with_cov( map1.copy(), map2.copy(), noise_variance=noise_variance.copy(), **kwargs, ) ) np.testing.assert_allclose(got, expected, rtol=1e-5, atol=1e-5)
def test_filter_with_global_fsc_half_matches_full(): rng = np.random.default_rng(3) volume_shape = (12, 12, 12) map1 = rng.standard_normal(volume_shape).astype(np.float32) map2 = rng.standard_normal(volume_shape).astype(np.float32)
fsc = regularization.get_fsc( fourier_transform_utils.get_dft3(map1), fourier_transform_utils.get_dft3(map2), volume_shape=volume_shape, ) mask = mask_fn.raised_cosine_mask(volume_shape, 4, 5, -1)
ft_full = 0.5 * (fourier_transform_utils.get_dft3(map1) + fourier_transform_utils.get_dft3(map2)) ft_half = 0.5 * (fourier_transform_utils.get_dft3_real(map1) + fourier_transform_utils.get_dft3_real(map2))
out_full = np.asarray( locres.filter_with_global_fsc( ft_full, fsc, voxel_size=1.5, filter_edgewidth=2, mask=mask, B_factor=20.0, volume_shape=volume_shape, ) ) out_half = np.asarray( locres.filter_with_global_fsc( ft_half, fsc, voxel_size=1.5, filter_edgewidth=2, mask=mask, B_factor=20.0, volume_shape=volume_shape, ) ) np.testing.assert_allclose(out_half, out_full, rtol=1e-5, atol=1e-5)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193"""Tests for the M-step: backprojection and translation summation."""
import numpy as npimport pytest
pytest.importorskip("jax")
import jaximport jax.numpy as jnp
from recovar.em.sampling import translations_to_indices, get_translation_gridfrom recovar.em.m_step import sum_up_translate_one_image
pytestmark = pytest.mark.unit
# ---------------------------------------------------------------------------# translations_to_indices# ---------------------------------------------------------------------------
def test_translations_to_indices_zero_translation(): """Zero translation maps to the center pixel.""" image_shape = (8, 8) translations = jnp.array([[0, 0]], dtype=jnp.int32) indices = translations_to_indices(translations, image_shape) center = (image_shape[0] // 2) * image_shape[1] + (image_shape[0] // 2) assert int(indices[0]) == center
def test_translations_to_indices_batch(): """Multiple translations yield distinct indices.""" image_shape = (8, 8) translations = jnp.array([[0, 0], [1, 0], [0, 1]], dtype=jnp.int32) indices = translations_to_indices(translations, image_shape) assert indices.shape == (3,) # All should be different assert len(set(np.asarray(indices).tolist())) == 3
def test_translations_to_indices_symmetry(): """Opposite translations map symmetrically around center.""" image_shape = (8, 8) center = image_shape[0] // 2 t_pos = jnp.array([[1, 0]], dtype=jnp.int32) t_neg = jnp.array([[-1, 0]], dtype=jnp.int32) idx_pos = int(translations_to_indices(t_pos, image_shape)[0]) idx_neg = int(translations_to_indices(t_neg, image_shape)[0]) # Center index idx_center = int(translations_to_indices(jnp.array([[0, 0]], dtype=jnp.int32), image_shape)[0]) assert idx_pos - idx_center == idx_center - idx_neg
# ---------------------------------------------------------------------------# get_translation_grid# ---------------------------------------------------------------------------
def test_get_translation_grid_includes_zero(): """Translation grid always includes (0, 0).""" grid = get_translation_grid(max_pixel=4, pixel_offset=1) assert any(np.allclose(row, [0, 0]) for row in grid)
def test_get_translation_grid_within_radius(): """All translations are within the specified max_pixel radius.""" max_pixel = 3 grid = get_translation_grid(max_pixel=max_pixel, pixel_offset=1) norms = np.linalg.norm(grid, axis=1) assert np.all(norms <= max_pixel + 0.01)
def test_get_translation_grid_offset_spacing(): """Grid spacing matches pixel_offset.""" grid = get_translation_grid(max_pixel=4, pixel_offset=2) # All coordinates should be multiples of 2 assert np.all(grid % 2 == 0)
# ---------------------------------------------------------------------------# sum_up_translate_one_image# ---------------------------------------------------------------------------
def test_sum_up_translate_one_image_single_translation_fft(): """With one translation at probability 1, image is unchanged (FFT path).""" image_shape = (8, 8) image_size = 64 image = jnp.ones(image_size, dtype=jnp.complex64) probabilities = jnp.array([[1.0]], dtype=jnp.complex64) # (n_rot=1, n_trans=1) translations = jnp.array([[0, 0]], dtype=jnp.int32)
result = sum_up_translate_one_image(image, probabilities, translations, image_shape, "fft") # With prob=1 at zero translation, the result should equal image * DFT(delta) = image * 1 assert result.shape == (1, image_size) assert jnp.all(jnp.isfinite(result))
def test_sum_up_translate_one_image_probabilities_sum(): """Output scales linearly with probability magnitude.""" image_shape = (8, 8) image_size = 64 rng = np.random.default_rng(42) image = jnp.array(rng.standard_normal(image_size) + 1j * rng.standard_normal(image_size), dtype=jnp.complex64) translations = jnp.array([[0, 0]], dtype=jnp.int32)
prob1 = jnp.array([[1.0]], dtype=jnp.complex64) prob2 = jnp.array([[2.0]], dtype=jnp.complex64)
result1 = sum_up_translate_one_image(image, prob1, translations, image_shape, "fft") result2 = sum_up_translate_one_image(image, prob2, translations, image_shape, "fft")
np.testing.assert_allclose(np.asarray(result2), np.asarray(result1) * 2, rtol=1e-5)
def test_sum_up_translate_one_image_zero_probability(): """Zero probability gives zero output.""" image_shape = (8, 8) image_size = 64 image = jnp.ones(image_size, dtype=jnp.complex64) probabilities = jnp.array([[0.0]], dtype=jnp.complex64) translations = jnp.array([[0, 0]], dtype=jnp.int32)
result = sum_up_translate_one_image(image, probabilities, translations, image_shape, "fft") assert jnp.allclose(result, 0.0, atol=1e-7)
def test_sum_up_translate_one_image_non_fft_path(): """Non-FFT path returns valid output.""" image_shape = (8, 8) image_size = 64 image = jnp.ones(image_size, dtype=jnp.complex64) probabilities = jnp.array([[1.0]], dtype=jnp.complex64) translations = jnp.array([[0.0, 0.0]], dtype=jnp.float32)
result = sum_up_translate_one_image(image, probabilities, translations, image_shape, "real") assert result.shape == (1, image_size) assert jnp.all(jnp.isfinite(result))
def test_sum_up_translate_one_image_multiple_translations(): """Multiple translations with equal probability.""" image_shape = (8, 8) image_size = 64 image = jnp.ones(image_size, dtype=jnp.complex64) # Two translations, each with prob 0.5 probabilities = jnp.array([[0.5, 0.5]], dtype=jnp.complex64) translations = jnp.array([[0, 0], [1, 0]], dtype=jnp.int32)
result = sum_up_translate_one_image(image, probabilities, translations, image_shape, "fft") assert result.shape == (1, image_size) assert jnp.all(jnp.isfinite(result))
# ---------------------------------------------------------------------------# GPU tests# ---------------------------------------------------------------------------
@pytest.fixturedef gpu_device(): """Return the first GPU device, or skip.""" try: devs = jax.devices("gpu") if not devs: pytest.skip("No GPU available") return devs[0] except RuntimeError: pytest.skip("No GPU available")
@pytest.mark.gpudef test_sum_up_translate_fft_gpu(gpu_device): """sum_up_translate_one_image works on GPU.""" image_shape = (16, 16) image_size = 256 with jax.default_device(gpu_device): image = jnp.ones(image_size, dtype=jnp.complex64) probabilities = jnp.array([[1.0]], dtype=jnp.complex64) translations = jnp.array([[0, 0]], dtype=jnp.int32) result = sum_up_translate_one_image(image, probabilities, translations, image_shape, "fft") assert result.shape == (1, image_size) assert jnp.all(jnp.isfinite(result))
@pytest.mark.gpudef test_translations_to_indices_gpu(gpu_device): """translations_to_indices works on GPU.""" image_shape = (16, 16) with jax.default_device(gpu_device): translations = jnp.array([[0, 0], [1, -1], [-2, 3]], dtype=jnp.int32) indices = translations_to_indices(translations, image_shape) assert indices.shape == (3,) assert jnp.all(jnp.isfinite(indices))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import numpy as npimport pytest
pytest.importorskip("jax")
import recovar.core.mask as mask
pytestmark = pytest.mark.unit
def test_get_radial_mask_and_window_mask(): m = np.asarray(mask.get_radial_mask((8, 8, 8))) assert m.shape == (8, 8, 8) assert m.dtype == np.bool_ assert m.any()
w = mask.window_mask(8, in_rad=0.2, out_rad=0.8) assert w.shape == (8, 8) assert np.all((w >= 0) & (w <= 1))
def test_raised_cosine_mask_bounds(): rc = np.asarray(mask.raised_cosine_mask((8, 8, 8), radius=2, radius_p=4, offset=-1)) assert rc.shape == (8, 8, 8) assert np.all((rc >= 0) & (rc <= 1)) assert np.max(rc) <= 1.0 + 1e-6
def test_soften_volume_mask_range(): binary = np.zeros((8, 8, 8), dtype=np.float32) binary[2:6, 2:6, 2:6] = 1.0 out = mask.soften_volume_mask(binary, kern_rad=2) assert out.shape == binary.shape assert out.dtype == np.float32 assert np.all((out >= 0) & (out <= 1))
def test_smooth_circular_mask_shape_and_range(): m = mask.smooth_circular_mask(image_size=16, radius=4, thickness=2) assert m.shape == (16, 16) assert np.all((m >= 0.0) & (m <= 1.0))
def test_smooth_circular_mask_interior_is_one(): # Center pixel is at coords (0, 0) so r=0, which is < radius m = mask.smooth_circular_mask(image_size=10, radius=3, thickness=2) half = 10 // 2 # coords[half] = 0 → r = 0 < radius assert m[half, half] == 1.0
def test_smooth_circular_mask_exterior_is_zero(): m = mask.smooth_circular_mask(image_size=10, radius=3, thickness=2) # corner pixel: coords = (-5, -5), r = 5*sqrt(2) ≈ 7.07 >> radius+thickness=5 assert m[0, 0] == 0.0
def test_smooth_circular_mask_exact_formula(): """Verify every pixel matches the raised-cosine formula exactly.""" image_size = 14 radius = 4.0 thickness = 3.0 m = mask.smooth_circular_mask(image_size, radius=radius, thickness=thickness)
half = image_size // 2 coords = np.arange(-half, image_size - half, dtype=float) gx, gy = np.meshgrid(coords, coords, indexing="xy") r = np.sqrt(gx**2 + gy**2)
for i in range(image_size): for j in range(image_size): ri = r[i, j] if ri < radius: expected = 1.0 elif ri <= radius + thickness: expected = 0.5 + 0.5 * np.cos(np.pi * (ri - radius) / thickness) else: expected = 0.0 assert abs(m[i, j] - expected) < 1e-10, ( f"Mismatch at [{i},{j}]: r={ri:.4f}, expected={expected:.6f}, got={m[i, j]:.6f}" )
def test_smooth_circular_mask_symmetric(): """The mask must be centrosymmetric (same value at (i,j) and (j,i)).""" m = mask.smooth_circular_mask(image_size=12, radius=3, thickness=2) np.testing.assert_allclose(m, m.T, atol=1e-12)
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
import jaximport jax.numpy as jnp
@pytest.mark.gpudef test_soften_volume_mask_gpu(gpu_device): binary = np.zeros((8, 8, 8), dtype=np.float32) binary[2:6, 2:6, 2:6] = 1.0
cpu_out = np.asarray(mask.soften_volume_mask(binary, kern_rad=2))
with jax.default_device(gpu_device): binary_g = jax.device_put(jnp.array(binary), gpu_device) gpu_out = np.asarray(mask.soften_volume_mask(binary_g, kern_rad=2))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560"""Tests for default max_r sphere clipping and half/full equivalence.
Verifies: 1. Default max_r = image_shape[0]//2 - 1 is applied when not specified. 2. Explicit max_r=None disables clipping (backward compat). 3. Half-vol/half-img vs full-vol/full-img produce equivalent results under the default max_r (ensures Nyquist-edge exclusion makes them match). 4. Upsampling (volume_shape != image_shape) works with max_r. 5. Project ⟷ backproject adjointness holds with default max_r."""
import numpy as npimport pytest
pytest.importorskip("jax")import jaximport jax.numpy as jnp
import recovar.core as coreimport recovar.core.slicing as slicingimport recovar.core.fourier_transform_utils as ftu
pytestmark = pytest.mark.unit
# ── Helpers ──────────────────────────────────────────────────────────
def _random_rotations(n, seed=42): rng = np.random.default_rng(seed) z = rng.standard_normal((n, 3, 3)) q, r = np.linalg.qr(z) d = np.sign(np.diagonal(r, axis1=1, axis2=2)) q = q * d[:, None, :] det = np.linalg.det(q) q[det < 0] *= -1 return jnp.array(q, dtype=jnp.float32)
def _hermitian_volume(N, seed=0): """Random Hermitian-symmetric full volume (FFT of real data).""" rng = np.random.default_rng(seed) real_vol = rng.standard_normal((N, N, N)).astype(np.float32) ft = np.fft.fftn(real_vol) return jnp.array(ft.ravel(), dtype=jnp.complex64)
def _hermitian_volume_rect(volume_shape, seed=0): """Random Hermitian-symmetric volume for non-cubic shapes.""" rng = np.random.default_rng(seed) real_vol = rng.standard_normal(volume_shape).astype(np.float32) ft = np.fft.fftn(real_vol) return jnp.array(ft.ravel(), dtype=jnp.complex64)
def _random_slices(n_images, n_pix, seed=99): rng = np.random.default_rng(seed) return jnp.array( (rng.standard_normal((n_images, n_pix)) + 1j * rng.standard_normal((n_images, n_pix))).astype(np.complex64) )
# ── 1. Default max_r value ──────────────────────────────────────────
class TestDefaultMaxR: """Verify default max_r = image_shape[0]//2 - 1."""
def test_default_max_r_value(self): assert slicing._default_max_r((128, 128)) == 63 assert slicing._default_max_r((64, 64)) == 31 assert slicing._default_max_r((32, 32)) == 15 assert slicing._default_max_r((16, 16)) == 7 assert slicing._default_max_r((8, 8)) == 3
def test_default_max_r_upsampled(self): """With upsampling, image_shape is smaller, max_r based on image.""" assert slicing._default_max_r((64, 64)) == 31 # ups=2 with 128^3 vol assert slicing._default_max_r((32, 32)) == 15 # ups=4 with 128^3 vol
def test_resolve_auto(self): assert slicing._resolve_max_r(slicing._AUTO, (128, 128)) == 63
def test_resolve_none(self): assert slicing._resolve_max_r(None, (128, 128)) is None
def test_resolve_explicit(self): assert slicing._resolve_max_r(5.0, (128, 128)) == 5.0
def test_cuda_max_r_no_upsampling(self): """With upsampling=1, _cuda_max_r returns the same value.""" assert slicing._cuda_max_r(63, (128, 128), (128, 128, 128)) == 63 assert slicing._cuda_max_r(31, (64, 64), (64, 64, 64)) == 31
def test_cuda_max_r_upsampling_2x(self): """With upsampling=2, _cuda_max_r doubles the radius.""" assert slicing._cuda_max_r(63, (128, 128), (256, 256, 256)) == 126 assert slicing._cuda_max_r(31, (64, 64), (128, 128, 128)) == 62
def test_cuda_max_r_upsampling_4x(self): """With upsampling=4, _cuda_max_r quadruples the radius.""" assert slicing._cuda_max_r(15, (32, 32), (128, 128, 128)) == 60
def test_cuda_max_r_none(self): """_cuda_max_r(None, ...) returns None.""" assert slicing._cuda_max_r(None, (128, 128), (256, 256, 256)) is None
def test_default_clips_more_than_none(self): """Default max_r should produce more zeros than max_r=None.""" N = 16 image_shape = (N, N) volume_shape = (N, N, N) vol = _hermitian_volume(N) rots = _random_rotations(3)
# Default (auto) — clips at N//2-1 = 7 out_default = np.asarray(slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp")) # Explicit None — no clipping out_none = np.asarray(slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp", max_r=None))
n_zero_default = np.sum(np.abs(out_default) < 1e-30) n_zero_none = np.sum(np.abs(out_none) < 1e-30) assert n_zero_default > n_zero_none, f"Default should clip more: {n_zero_default} zeros vs {n_zero_none}"
def test_explicit_none_matches_old_behavior(self): """max_r=None should give same result as the old behavior (no clipping).""" N = 16 image_shape = (N, N) volume_shape = (N, N, N) vol = _hermitian_volume(N) rots = _random_rotations(3)
# max_r=None should produce no zeros from clipping (only from interpolation) out = np.asarray(slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp", max_r=None)) # With a random volume, very few pixels should be exactly zero n_nonzero = np.sum(np.abs(out) > 1e-30) total = out.size assert n_nonzero > 0.8 * total, f"max_r=None should leave most pixels nonzero: {n_nonzero}/{total}"
# ── 2. Half-vol/half-img equivalence under default max_r ────────────
class TestHalfFullEquivalence: """All 4 combos of half_volume/half_image should produce equivalent results.
The default max_r = N//2-1 excludes the Nyquist edge, which is the problematic bin for half/full equivalence. """
@pytest.fixture(params=[16, 32], ids=["N16", "N32"]) def N(self, request): return request.param
def test_project_half_img_matches_full_img(self, N): """full-vol+full-img vs full-vol+half-img should be equivalent.""" image_shape = (N, N) volume_shape = (N, N, N) vol = _hermitian_volume(N) rots = _random_rotations(5, seed=10)
out_full = np.asarray( slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp", half_image=False) ) out_half = np.asarray( slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp", half_image=True) )
# Convert full image to half using proper ftu conversion half_from_full = np.asarray(ftu.full_image_to_half_image(jnp.array(out_full), image_shape))
np.testing.assert_allclose( out_half, half_from_full, atol=1e-5, rtol=1e-5, err_msg=f"N={N}: half_img should match corresponding full_img pixels", )
def test_project_half_vol_matches_full_vol(self, N): """half-vol+half-img vs full-vol+half-img.""" image_shape = (N, N) volume_shape = (N, N, N) vol_full = _hermitian_volume(N) vol_half = ftu.full_volume_to_half_volume(vol_full, volume_shape) rots = _random_rotations(5, seed=20)
out_full = np.asarray( slicing.slice_volume(vol_full, rots, image_shape, volume_shape, "linear_interp", half_image=True) ) out_half = np.asarray( slicing.slice_volume( vol_half, rots, image_shape, volume_shape, "linear_interp", half_volume=True, half_image=True ) )
np.testing.assert_allclose( out_half, out_full, atol=1e-5, rtol=1e-5, err_msg=f"N={N}: half_vol should match full_vol projection" )
def test_project_all_four_combos(self, N): """All 4 half_vol/half_img combos agree on the half-image pixels.""" image_shape = (N, N) volume_shape = (N, N, N) vol_full = _hermitian_volume(N, seed=30) vol_half = ftu.full_volume_to_half_volume(vol_full, volume_shape) rots = _random_rotations(5, seed=30)
results = {} for hv, hi in [(False, False), (False, True), (True, False), (True, True)]: vol = vol_half if hv else vol_full out = np.asarray( slicing.slice_volume( vol, rots, image_shape, volume_shape, "linear_interp", half_volume=hv, half_image=hi ) ) if not hi: # Convert full image to half using proper ftu conversion out = np.asarray(ftu.full_image_to_half_image(jnp.array(out), image_shape)) results[(hv, hi)] = out
ref = results[(False, True)] for key, val in results.items(): np.testing.assert_allclose( val, ref, atol=1e-4, rtol=1e-4, err_msg=f"N={N}: combo {key} differs from (False,True) reference" )
def test_backproject_half_img_matches_full_img(self, N): """Backproject with full-img vs half-img should give same volume.
Half-image backproject uses Hermitian scatter (CONJ_MODE), so the input images must be Hermitian symmetric (DFT of real data) for the two paths to agree. """ image_shape = (N, N) volume_shape = (N, N, N) rots = _random_rotations(5, seed=40)
# Hermitian images: DFT of real data rng = np.random.default_rng(40) real_imgs = rng.standard_normal((5, N, N)).astype(np.float32) full_imgs = jnp.array(ftu.get_dft2(jnp.array(real_imgs))).reshape(5, -1) half_imgs = jnp.array(ftu.get_dft2_real(jnp.array(real_imgs))).reshape(5, -1)
out_full = np.asarray( slicing.adjoint_slice_volume(full_imgs, rots, image_shape, volume_shape, "linear_interp", half_image=False) ) out_half = np.asarray( slicing.adjoint_slice_volume(half_imgs, rots, image_shape, volume_shape, "linear_interp", half_image=True) )
np.testing.assert_allclose( out_half, out_full, atol=1e-4, rtol=1e-4, err_msg=f"N={N}: backproject half_img should match full_img" )
def test_backproject_all_four_combos_self_consistent(self, N): """Backproject all 4 combos should produce volumes that re-project consistently.
Half_vol backproject has 2x weight on interior kz (CONJ_MODE), so direct voxel comparison doesn't work. Instead verify that the full-vol+full-img and full-vol+half-img backproject paths produce the same full volume. """ image_shape = (N, N) volume_shape = (N, N, N) rots = _random_rotations(5, seed=50)
# Hermitian images from real data rng = np.random.default_rng(50) real_imgs = rng.standard_normal((5, N, N)).astype(np.float32) full_imgs = jnp.array(ftu.get_dft2(jnp.array(real_imgs))).reshape(5, -1) half_imgs = jnp.array(ftu.get_dft2_real(jnp.array(real_imgs))).reshape(5, -1)
# Full-vol output from full-img vs half-img should match out_ff = np.asarray( slicing.adjoint_slice_volume( full_imgs, rots, image_shape, volume_shape, "linear_interp", half_image=False, half_volume=False ) ) out_hf = np.asarray( slicing.adjoint_slice_volume( half_imgs, rots, image_shape, volume_shape, "linear_interp", half_image=True, half_volume=False ) )
np.testing.assert_allclose( out_hf, out_ff, atol=1e-4, rtol=1e-4, err_msg=f"N={N}: full-vol from half-img should match full-vol from full-img", )
# ── 3. Upsampling (padding) tests with max_r ────────────────────────
class TestUpsamplingMaxR: """Tests for volume_shape != image_shape (upsampling/padding).
With upsampling=2, image_shape=(N,N) maps to volume_shape=(2N,2N,2N). Image frequencies only reach ±N/2, so max_r = N//2-1 clips just inside. """
@pytest.fixture( params=[ ((16, 16), (32, 32, 32)), ((16, 16), (64, 64, 64)), ((32, 32), (64, 64, 64)), ], ids=["16to32", "16to64", "32to64"], ) def shapes(self, request): return request.param
def test_project_upsampled_default_max_r(self, shapes): """Project with upsampling and default max_r produces valid output.""" image_shape, volume_shape = shapes vol = _hermitian_volume_rect(volume_shape) rots = _random_rotations(3, seed=60)
out = np.asarray(slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp"))
assert out.shape == (3, image_shape[0] * image_shape[1]) # Should have some nonzero pixels assert np.sum(np.abs(out) > 1e-30) > 0
def test_project_upsampled_half_vol_half_img(self, shapes): """Half-vol+half-img with upsampling matches full-vol+half-img.""" image_shape, volume_shape = shapes vol_full = _hermitian_volume_rect(volume_shape) vol_half = ftu.full_volume_to_half_volume(vol_full, volume_shape) rots = _random_rotations(3, seed=70)
out_full = np.asarray( slicing.slice_volume(vol_full, rots, image_shape, volume_shape, "linear_interp", half_image=True) ) out_half = np.asarray( slicing.slice_volume( vol_half, rots, image_shape, volume_shape, "linear_interp", half_volume=True, half_image=True ) )
np.testing.assert_allclose( out_half, out_full, atol=1e-4, rtol=1e-4, err_msg=f"Upsampled half_vol should match full_vol" )
def test_backproject_upsampled_default_max_r(self, shapes): """Backproject with upsampling and default max_r.""" image_shape, volume_shape = shapes rots = _random_rotations(3, seed=80) n_pix = image_shape[0] * image_shape[1] slices = _random_slices(3, n_pix, seed=80)
out = np.asarray(slicing.adjoint_slice_volume(slices, rots, image_shape, volume_shape, "linear_interp"))
vol_size = int(np.prod(volume_shape)) assert out.shape == (vol_size,) assert np.sum(np.abs(out) > 1e-30) > 0
def test_backproject_upsampled_half_img_vs_full_img(self, shapes): """Backproject with upsampling: full-vol from half-img vs full-img should match.""" image_shape, volume_shape = shapes N = image_shape[0] rots = _random_rotations(3, seed=90)
# Hermitian images rng = np.random.default_rng(90) real_imgs = rng.standard_normal((3, N, N)).astype(np.float32) full_imgs = jnp.array(ftu.get_dft2(jnp.array(real_imgs))).reshape(3, -1) half_imgs = jnp.array(ftu.get_dft2_real(jnp.array(real_imgs))).reshape(3, -1)
out_full = np.asarray( slicing.adjoint_slice_volume( full_imgs, rots, image_shape, volume_shape, "linear_interp", half_image=False, half_volume=False ) ) out_half = np.asarray( slicing.adjoint_slice_volume( half_imgs, rots, image_shape, volume_shape, "linear_interp", half_image=True, half_volume=False ) )
np.testing.assert_allclose( out_half, out_full, atol=1e-4, rtol=1e-4, err_msg="Upsampled backproject half_img should match full_img" )
def test_upsampled_default_max_r_preserves_most_pixels(self, shapes): """Default max_r with upsampling should clip ~same fraction as without upsampling.
Before the fix, CUDA clipped at radius 31.5 in image coords instead of 63 (due to unscaled max_r in volume-coord space), zeroing ~75% of pixels. """ image_shape, volume_shape = shapes N = image_shape[0] vol = _hermitian_volume_rect(volume_shape) rots = _random_rotations(3, seed=105)
out = np.asarray(slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp")) n_nonzero = np.sum(np.abs(out) > 1e-30) total = out.size # The inscribed circle of an N×N image at radius N//2-1 has area # ~π*(N//2-1)² / N² ≈ 60% for N=16, 69% for N=32. # The old bug (unscaled max_r) clipped at radius (N//2-1)/ups in image # coords, giving ~15% for N=16 with ups=2. Threshold at 50% catches it. frac = n_nonzero / total assert frac > 0.50, ( f"Upsampled projection preserved only {frac:.1%} of pixels — max_r likely not scaled to volume coordinates" )
def test_max_r_clips_correctly_with_upsampling(self, shapes): """With upsampling, max_r should still zero out high frequencies.""" image_shape, volume_shape = shapes vol = _hermitian_volume_rect(volume_shape) rots = _random_rotations(3, seed=100)
# Small max_r should clip aggressively out_small = np.asarray(slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp", max_r=3.0)) out_none = np.asarray(slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp", max_r=None))
n_zero_small = np.sum(np.abs(out_small) < 1e-30) n_zero_none = np.sum(np.abs(out_none) < 1e-30) assert n_zero_small > n_zero_none
# ── 4. Adjointness test with default max_r ───────────────────────────
class TestAdjointnessWithMaxR: """<Ax, y> should equal <x, A^T y> for project/backproject with max_r."""
@pytest.fixture(params=[16, 32], ids=["N16", "N32"]) def N(self, request): return request.param
def test_adjointness_default_max_r(self, N): """Adjointness holds under default max_r clipping.""" image_shape = (N, N) volume_shape = (N, N, N) n_images = 5 rots = _random_rotations(n_images, seed=110)
rng = np.random.default_rng(110) vol_data = (rng.standard_normal(N**3) + 1j * rng.standard_normal(N**3)).astype(np.complex64) vol = jnp.array(vol_data) img_data = (rng.standard_normal((n_images, N * N)) + 1j * rng.standard_normal((n_images, N * N))).astype( np.complex64 ) imgs = jnp.array(img_data)
# Forward: Ax Ax = slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp") # Adjoint: A^T y ATy = slicing.adjoint_slice_volume(imgs, rots, image_shape, volume_shape, "linear_interp")
# <Ax, y> lhs = float(jnp.real(jnp.vdot(Ax, imgs))) # <x, A^T y> rhs = float(jnp.real(jnp.vdot(vol, ATy)))
rel_err = abs(lhs - rhs) / (abs(lhs) + abs(rhs) + 1e-30) assert rel_err < 1e-4, f"Adjointness failed: lhs={lhs}, rhs={rhs}, rel_err={rel_err}"
def test_adjointness_upsampled_default_max_r(self, N): """Adjointness holds with upsampling_factor=2 and default max_r.""" image_shape = (N, N) volume_shape = (2 * N, 2 * N, 2 * N) n_images = 5 rots = _random_rotations(n_images, seed=120)
rng = np.random.default_rng(120) vol = jnp.array( (rng.standard_normal((2 * N) ** 3) + 1j * rng.standard_normal((2 * N) ** 3)).astype(np.complex64) ) imgs = jnp.array( (rng.standard_normal((n_images, N * N)) + 1j * rng.standard_normal((n_images, N * N))).astype(np.complex64) )
Ax = slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp") ATy = slicing.adjoint_slice_volume(imgs, rots, image_shape, volume_shape, "linear_interp")
lhs = float(jnp.real(jnp.vdot(Ax, imgs))) rhs = float(jnp.real(jnp.vdot(vol, ATy)))
rel_err = abs(lhs - rhs) / (abs(lhs) + abs(rhs) + 1e-30) assert rel_err < 1e-4, f"Upsampled adjointness failed: lhs={lhs}, rhs={rhs}, rel_err={rel_err}"
def test_adjointness_explicit_max_r(self, N): """Adjointness with explicit max_r value.""" image_shape = (N, N) volume_shape = (N, N, N) max_r = N // 4 n_images = 5 rots = _random_rotations(n_images, seed=130)
rng = np.random.default_rng(130) vol = jnp.array((rng.standard_normal(N**3) + 1j * rng.standard_normal(N**3)).astype(np.complex64)) imgs = jnp.array( (rng.standard_normal((n_images, N * N)) + 1j * rng.standard_normal((n_images, N * N))).astype(np.complex64) )
Ax = slicing.slice_volume(vol, rots, image_shape, volume_shape, "linear_interp", max_r=max_r) ATy = slicing.adjoint_slice_volume(imgs, rots, image_shape, volume_shape, "linear_interp", max_r=max_r)
lhs = float(jnp.real(jnp.vdot(Ax, imgs))) rhs = float(jnp.real(jnp.vdot(vol, ATy)))
rel_err = abs(lhs - rhs) / (abs(lhs) + abs(rhs) + 1e-30) assert rel_err < 1e-4, f"Adjointness failed: lhs={lhs}, rhs={rhs}, rel_err={rel_err}"
# ── 5. Batch functions respect default max_r ─────────────────────────
class TestBatchDefaultMaxR: """Batch functions should use the same default max_r as single functions."""
def test_batch_slice_matches_single(self): N = 16 image_shape = (N, N) volume_shape = (N, N, N) n_vols = 3 rots = _random_rotations(5, seed=140)
rng = np.random.default_rng(140) vols = jnp.array( (rng.standard_normal((n_vols, N**3)) + 1j * rng.standard_normal((n_vols, N**3))).astype(np.complex64) )
# Batch call with default max_r batch_out = np.asarray(slicing.batch_slice_volume(vols, rots, image_shape, volume_shape, "linear_interp"))
# Single calls with default max_r for i in range(n_vols): single_out = np.asarray(slicing.slice_volume(vols[i], rots, image_shape, volume_shape, "linear_interp")) np.testing.assert_allclose( batch_out[i], single_out, atol=1e-5, rtol=1e-5, err_msg=f"Batch vol {i} differs from single" )
def test_batch_adjoint_matches_single(self): N = 16 image_shape = (N, N) volume_shape = (N, N, N) n_vols = 3 n_images = 5 rots = _random_rotations(n_images, seed=150) slices_data = _random_slices(n_images, N * N, seed=150) batch_slices = jnp.stack([slices_data] * n_vols)
batch_out = np.asarray( slicing.batch_adjoint_slice_volume(batch_slices, rots, image_shape, volume_shape, "linear_interp") )
for i in range(n_vols): single_out = np.asarray( slicing.adjoint_slice_volume(slices_data, rots, image_shape, volume_shape, "linear_interp") ) np.testing.assert_allclose( batch_out[i], single_out, atol=1e-5, rtol=1e-5, err_msg=f"Batch vol {i} differs from single" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745"""Unit tests for ``recovar.utils.memory_planner``.
No GPU required: NVML / nvidia-smi is monkeypatched to return syntheticdata, and the JAX memory_stats helpers are stubbed via the ``recovar.utils``package re-export so the planner sees deterministic numbers."""
from __future__ import annotations
import json
import pytest
pytestmark = [pytest.mark.unit]
@pytest.fixture(autouse=True)def _reset_planner_globals(monkeypatch): """Force a fresh backend probe per test.""" monkeypatch.delenv("RECOVAR_DISABLE_CUDA", raising=False)
def _stub_helpers(monkeypatch, *, gpu_total: float = 80.0): from recovar import utils as _helpers
monkeypatch.setattr(_helpers, "set_gpu_memory_limit", lambda gb: None) monkeypatch.setattr(_helpers, "get_gpu_memory_total", lambda: gpu_total) monkeypatch.setattr( _helpers, "get_image_batch_size", lambda grid_size, gpu_memory: max(1, int(gpu_memory * 256 / max(1, grid_size**2 / 1024.0))), ) monkeypatch.setattr( _helpers, "get_vol_batch_size", lambda grid_size, gpu_memory: max(1, int(gpu_memory * 100 / max(1, grid_size**3 / 1e6))), ) monkeypatch.setattr( _helpers, "get_column_batch_size", lambda grid_size, gpu_memory: max(1, int(gpu_memory * 200 / max(1, grid_size**3 / 1e6))), )
def _stub_preflight(monkeypatch, *, total: float, free: float): from recovar.utils import gpu_preflight as gp
def fake(_idx=0): return gp.PhysicalGpuMemoryInfo( device_idx=0, total_gb=total, used_gb=total - free, free_gb=free, processes=[], source="stub", )
monkeypatch.setattr(gp, "get_physical_gpu_memory_info", fake)
def _stub_backend_custom(monkeypatch): from recovar.utils import cuda_env
monkeypatch.setattr(cuda_env, "detect_backend", lambda: "custom_cuda")
def test_make_memory_plan_returns_int_batches(monkeypatch): _stub_helpers(monkeypatch) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=10000, requested_gpu_gb=40.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=False, desired_n_pcs=200, ) assert plan.image_batch_size >= 1 assert plan.volume_batch_size >= 1 assert plan.column_batch_size >= 1 assert plan.n_pcs_to_compute == 200 assert plan.budget.effective_budget_gb > 0
def test_low_memory_tightens_batches(monkeypatch): _stub_helpers(monkeypatch) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
base = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=40.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=False, ) low = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=40.0, low_memory=True, very_low_memory=False, adaptive_n_pcs=False, ) very = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=40.0, low_memory=False, very_low_memory=True, adaptive_n_pcs=False, ) assert very.image_batch_size <= low.image_batch_size <= base.image_batch_size assert very.volume_batch_size <= low.volume_batch_size <= base.volume_batch_size assert very.column_batch_size <= low.column_batch_size <= base.column_batch_size
def test_effective_budget_is_min_of_inputs_when_user_asked(monkeypatch): """With a user-supplied --gpu-budget-gb, physical_free-reserve is in the min.""" _stub_helpers(monkeypatch, gpu_total=72.0) _stub_preflight(monkeypatch, total=80.0, free=10.0) # only 10 GB free _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=40.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=False, ) # min(40, 72, 10 - 4_reserve=6) = 6 GB → effective should equal that assert plan.budget.effective_budget_gb == pytest.approx(10.0 - max(2.0, 0.05 * 80.0)) assert plan.budget.source == "physical_free_minus_reserve"
def test_effective_budget_skips_physical_reserve_when_no_user_request(monkeypatch): """Without --gpu-budget-gb, fall through to jax_limit (matches legacy behavior).
Subtracting physical_free-reserve unconditionally would shrink batches by ~5% on a quiet GPU and shift quality baselines (caught in long-test outliers regression). """ _stub_helpers(monkeypatch, gpu_total=80.0) _stub_preflight(monkeypatch, total=80.0, free=78.0) # quiet GPU _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=None, # no user request low_memory=False, very_low_memory=False, adaptive_n_pcs=False, ) # Legacy behavior preserved: effective == jax_limit (80), not 80-reserve. assert plan.budget.effective_budget_gb == pytest.approx(80.0) assert plan.budget.source == "jax_limit_gb"
def test_uncalibrated_with_adaptive_uses_formula_fallback(monkeypatch): """No calibration table + tight budget + --adaptive-n-pcs: planner uses the analytic peak formula instead of returning desired_n_pcs unchanged. (Originally just returned desired_n_pcs; review caught that ``run_test_dataset --adaptive-n-pcs`` was a no-op when the calibration JSON wasn't committed.)
Updated 2026-05-14: the formula was rewritten to model the actual inner-kernel allocations (basis + AUs + n^4 packed matrices). At grid=128, n=200 the formula predicts ~18 GB, so 40 GB budget is enough — use a TIGHT 8 GB budget here to force a shrink.""" _stub_helpers(monkeypatch, gpu_total=8.0) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
monkeypatch.setattr(mp, "load_calibration_table", lambda: None) plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=8.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=True, ) # At grid=128 / budget=8 GB the analytic formula picks n_pcs ~ 151. assert plan.calibration_status == "uncalibrated_formula" assert plan.n_pcs_to_compute < 200 assert plan.n_pcs_to_compute >= 1 # Without a calibration table, no peak prediction. assert plan.predicted_peak_gb_total is None
def test_uncalibrated_without_adaptive_keeps_desired_n_pcs(monkeypatch): """No calibration table AND no --adaptive-n-pcs: keep desired_n_pcs. The formula fallback only kicks in when the user opted into adaptive.""" _stub_helpers(monkeypatch) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
monkeypatch.setattr(mp, "load_calibration_table", lambda: None) plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=40.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=False, ) assert plan.calibration_status == "uncalibrated" assert plan.n_pcs_to_compute == 200 assert plan.predicted_peak_gb_total is None
def _make_calibration_table_for_pipeline(): """Synthetic table with known peaks for adaptive-n_pcs tests.""" from recovar.utils.memory_planner import CalibrationCell, CalibrationTable
cells = [ CalibrationCell( grid_size=128, backend="custom_cuda", n_pcs_or_volumes=4, peak_gb_total=5.0, peak_gb_by_phase={"after_mean": 5.0}, status="ok", ), CalibrationCell( grid_size=128, backend="custom_cuda", n_pcs_or_volumes=20, peak_gb_total=10.0, peak_gb_by_phase={"after_mean": 10.0}, status="ok", ), CalibrationCell( grid_size=128, backend="custom_cuda", n_pcs_or_volumes=50, peak_gb_total=20.0, peak_gb_by_phase={"after_mean": 20.0}, status="ok", ), CalibrationCell( grid_size=128, backend="custom_cuda", n_pcs_or_volumes=200, peak_gb_total=75.0, peak_gb_by_phase={"after_mean": 75.0}, status="ok", ), ] return CalibrationTable( schema_version=1, calibrated_on={"gpu_kind": "H100"}, cells_by_command={"pipeline": cells}, )
def test_adaptive_picks_largest_fitting_n_pcs(monkeypatch): _stub_helpers(monkeypatch) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
table = _make_calibration_table_for_pipeline() monkeypatch.setattr(mp, "load_calibration_table", lambda: table)
# Budget large enough for 50 (peak=20, with 1.2x slack=24 ≤ 30 ✓) # but not 200 (peak=75 with slack=90 > 30 ✗) plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=30.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=True, ) assert plan.n_pcs_to_compute == 50
# Tiny budget → falls back to the smallest calibrated n_pcs plan_small = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=2.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=True, ) assert plan_small.n_pcs_to_compute == 4
# Huge budget AND huge physical_free AND huge jax_limit → keeps all # 200 PCs. effective_budget = min(requested, jax_limit, physical_free # - reserve) so we have to bump all three above the 200-PC peak (75 # GB) plus the 1.2x slack (= 90 GB). _stub_helpers(monkeypatch, gpu_total=240.0) _stub_preflight(monkeypatch, total=240.0, free=240.0) plan_huge = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=200.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=True, ) assert plan_huge.n_pcs_to_compute == 200
def test_round_up_to_calibrated_grid(monkeypatch): _stub_helpers(monkeypatch) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
table = _make_calibration_table_for_pipeline() monkeypatch.setattr(mp, "load_calibration_table", lambda: table)
# Grid 100 has no exact entry; planner rounds up to 128 plan = mp.make_memory_plan( command="pipeline", grid_size=100, n_images=1000, requested_gpu_gb=80.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=False, desired_n_pcs=200, ) assert plan.calibration_status == "rounded_up" assert plan.predicted_peak_gb_total == 75.0
def test_warning_when_predicted_exceeds_budget(monkeypatch, caplog): import logging
_stub_helpers(monkeypatch) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
table = _make_calibration_table_for_pipeline() monkeypatch.setattr(mp, "load_calibration_table", lambda: table)
caplog.set_level(logging.WARNING, logger=mp.logger.name) plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=20.0, # tighter than 200 PC peak low_memory=False, very_low_memory=False, adaptive_n_pcs=False, desired_n_pcs=200, ) # We never refuse — plan still returned assert plan.n_pcs_to_compute == 200 # And a clear warning landed assert any("exceeds the effective budget" in r.message.lower() or "exceeds" in r.message for r in caplog.records)
def test_memory_plan_json_round_trip(tmp_path, monkeypatch): _stub_helpers(monkeypatch) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=40.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=False, ) out = mp.write_memory_plan_json(plan, tmp_path) assert out.exists() with out.open() as fh: data = json.load(fh) assert data["command"] == "pipeline" assert data["budget"]["effective_budget_gb"] == pytest.approx(plan.budget.effective_budget_gb)
def test_trace_writer_records_phase(tmp_path, monkeypatch): _stub_helpers(monkeypatch) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
trace = mp.MemoryTraceWriter(tmp_path, enabled=True) trace.record("after_mean") trace.record("after_covariance") rows = [json.loads(line) for line in (tmp_path / "_diagnostics" / "memory_trace.jsonl").read_text().splitlines()] assert [r["phase"] for r in rows] == ["after_mean", "after_covariance"]
def test_debug_force_peak_gb_overrides_observed(monkeypatch, tmp_path): _stub_helpers(monkeypatch) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch) monkeypatch.setenv("RECOVAR_DEBUG_FORCE_PEAK_GB", "999.0")
from recovar.utils import memory_planner as mp
trace = mp.MemoryTraceWriter(tmp_path, enabled=True) trace.record("after_mean") rows = [json.loads(line) for line in (tmp_path / "_diagnostics" / "memory_trace.jsonl").read_text().splitlines()] assert rows[0]["jax_peak_gb"] == 999.0 assert rows[0]["jax_peak_gb_forced"] is True
# ---------------------------------------------------------------------------# Review-feedback: uncalibrated --adaptive-n-pcs must NOT be a no-op.# Without this fallback, ``run_test_dataset --adaptive-n-pcs`` on a# small GPU still tries 200 PCs and OOMs — the exact scenario the# wrapper exists to prevent.# ---------------------------------------------------------------------------
def test_adaptive_fallback_picks_smaller_n_pcs_when_uncalibrated(monkeypatch): """No calibration table + tight budget → planner uses formula fallback.""" _stub_helpers(monkeypatch, gpu_total=40.0) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
monkeypatch.setattr(mp, "load_calibration_table", lambda: None)
plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=8.0, # tight: 200 PCs predicts ~75 GB, won't fit low_memory=False, very_low_memory=False, adaptive_n_pcs=True, ) # Status reflects the formula path, not "uncalibrated_passthrough". assert plan.calibration_status == "uncalibrated_formula" # And it actually shrunk n_pcs. assert plan.n_pcs_to_compute < 200 assert plan.n_pcs_to_compute >= 1
def test_adaptive_fallback_passthrough_when_budget_huge(monkeypatch): """No table + huge budget → keep desired_n_pcs.""" _stub_helpers(monkeypatch, gpu_total=240.0) _stub_preflight(monkeypatch, total=240.0, free=240.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
monkeypatch.setattr(mp, "load_calibration_table", lambda: None)
plan = mp.make_memory_plan( command="pipeline", grid_size=64, n_images=1000, requested_gpu_gb=200.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=True, ) assert plan.calibration_status == "uncalibrated_passthrough" assert plan.n_pcs_to_compute == 200
# NOTE: ``hard_cap_applied`` / ``hard_cap_skip_reason`` were removed# along with the --gpu-budget-gb auto-cap mechanism. The flag is now a# soft batch-size hint only; capping JAX is the user's responsibility# via XLA_PYTHON_CLIENT_MEM_FRACTION / XLA_PYTHON_CLIENT_PREALLOCATE.# Their replacement tests are in test_cli_memory_args.py# (test_pipeline_parser_rejects_bogus_gpu_gb).
# ---------------------------------------------------------------------------# Backend-aware budget deflation (sweep 8020210 finding).# ---------------------------------------------------------------------------
def test_jax_fallback_deflates_legacy_budget(monkeypatch, tmp_path): """Saturation sweep (8020210) showed jax_fallback overshoots the user's budget by 1.4× at g=64 and OOMs at g=128 under legacy formulas.
``apply_memory_planning_args`` must deflate the value handed to ``set_gpu_memory_limit`` (which drives the legacy batch-size formulas) by a backend-specific divisor — 5.0 for jax_fallback, 1.0 for custom_cuda. """ import argparse
from recovar.utils import helpers as _utils from recovar.utils import parser_args
_stub_helpers(monkeypatch, gpu_total=80.0) _stub_preflight(monkeypatch, total=80.0, free=78.0)
captured = {}
def fake_set_limit(value): captured["value"] = float(value)
monkeypatch.setattr(_utils, "set_gpu_memory_limit", fake_set_limit)
# Force backend to jax_fallback. from recovar.utils import cuda_env
monkeypatch.setattr(cuda_env, "detect_backend", lambda: "jax_fallback")
parser = argparse.ArgumentParser() parser_args.add_memory_planning_args(parser) args = parser.parse_args(["--gpu-budget-gb", "60"])
parser_args.apply_memory_planning_args( args, command="pipeline", grid_size=128, n_images=1000, outdir=tmp_path, ) # Effective budget = min(60, jax_limit=80, physical_free-reserve=74) = 60. # 60 GB / 5.0 would be 12 GB, but PR-138 high-budget fallback cells # need the formula budget capped at the largest passing cell (4.8 GB). assert captured["value"] == pytest.approx(4.8, rel=0.02)
def test_jax_fallback_deflates_central_plan_batch_sizes(monkeypatch): """The centralized plan must also use the fallback divisor.
``pipeline.py`` reads ``plan.image_batch_size`` directly, so only deflating the legacy global helper is insufficient for modern callers. """ _stub_helpers(monkeypatch, gpu_total=80.0) _stub_preflight(monkeypatch, total=80.0, free=78.0)
from recovar.utils import cuda_env from recovar.utils import memory_planner as mp
monkeypatch.setattr(cuda_env, "detect_backend", lambda: "jax_fallback")
plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=60.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=False, )
assert plan.budget.effective_budget_gb == pytest.approx(60.0) # _stub_helpers image formula at grid=128 is int(gpu_memory * 16). assert plan.image_batch_size == 76
def test_custom_cuda_does_not_deflate_legacy_budget(monkeypatch, tmp_path): """Under custom_cuda the planner deliberately does NOT touch the global ``set_gpu_memory_limit``. The saturation sweep showed the custom kernel comfortably fits in budget (ratios 0.09-0.72 across grids). Unconditionally calling set_gpu_memory_limit even with the same value shifts batch sizes off whatever JAX reports as bytes_limit, which is enough delta to flip the noise-floor cryo-ET outlier metrics in long-test (slurm 8025670 caught this). """ import argparse
from recovar.utils import helpers as _utils from recovar.utils import parser_args
_stub_helpers(monkeypatch, gpu_total=80.0) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
captured = {}
def fake_set_limit(value): captured["value"] = float(value)
monkeypatch.setattr(_utils, "set_gpu_memory_limit", fake_set_limit)
parser = argparse.ArgumentParser() parser_args.add_memory_planning_args(parser) args = parser.parse_args(["--gpu-budget-gb", "60"])
parser_args.apply_memory_planning_args( args, command="pipeline", grid_size=128, n_images=1000, outdir=tmp_path, ) # custom_cuda divisor = 1.0; planner must NOT touch the global. # (apply_gpu_memory_arg, called separately, can set it from # --gpu-budget-gb; but apply_memory_planning_args must stay a # no-op for the limit when no deflation is needed.) assert "value" not in captured
def test_grid_256_column_batch_is_capped(monkeypatch): """The planner caps 256^3 covariance-column batches to bound H/B accumulators.""" _stub_helpers(monkeypatch, gpu_total=76.0) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar import utils as _helpers from recovar.utils import memory_planner as mp
monkeypatch.setattr(_helpers, "get_column_batch_size", lambda _grid_size, _gpu_memory: 100)
plan = mp.make_memory_plan( command="pipeline", grid_size=256, n_images=5000, requested_gpu_gb=None, low_memory=False, very_low_memory=False, adaptive_n_pcs=True, ) assert plan.column_batch_size == 50
def test_grid_256_volume_batch_is_capped(monkeypatch): """The planner caps 256^3 PCA FFT batches to bound XLA FFT temporaries.""" _stub_helpers(monkeypatch, gpu_total=76.0) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar import utils as _helpers from recovar.utils import memory_planner as mp
monkeypatch.setattr(_helpers, "get_vol_batch_size", lambda _grid_size, _gpu_memory: 50)
plan = mp.make_memory_plan( command="pipeline", grid_size=256, n_images=5000, requested_gpu_gb=None, low_memory=False, very_low_memory=False, adaptive_n_pcs=True, ) assert plan.volume_batch_size == 10
# ---------------------------------------------------------------------------# Pre-launch OOM warning when fixed allocations exceed budget.## Earlier draft of this PR auto-enabled --adaptive-n-pcs in this case.# The maintainer rejected that: silently flipping user-explicit flags# is wrong. The planner now logs a loud WARNING and lets the run# proceed; if it OOMs, ``error_hints._hint_gpu_oom`` detects that the# predicted_peak exceeded the budget and recommends --adaptive-n-pcs# as the post-crash fix.# ---------------------------------------------------------------------------
def test_warns_but_does_not_auto_enable_adaptive_when_oom_predicted(monkeypatch, caplog): """g=256 + n_pcs=200 → basis term alone is ~27 GB. At budget=20 GB the run is predicted to OOM. The planner MUST NOT silently flip adaptive on; it must log a warning and keep ``n_pcs=200`` so the error_hints layer can recommend the right fix when the run fails.""" import logging
_stub_helpers(monkeypatch, gpu_total=20.0) _stub_preflight(monkeypatch, total=20.0, free=19.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
with caplog.at_level(logging.WARNING, logger="recovar.utils.memory_planner"): plan = mp.make_memory_plan( command="pipeline", grid_size=256, n_images=1000, requested_gpu_gb=20.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=False, desired_n_pcs=200, )
# Adaptive must NOT have been silently enabled — n_pcs stays at 200. assert plan.n_pcs_to_compute == 200 # A loud WARNING must have been emitted recommending --adaptive-n-pcs. warning_texts = "\n".join(r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING) assert "PRE-LAUNCH OOM PREDICTION" in warning_texts assert "--adaptive-n-pcs" in warning_texts
def test_no_warning_when_fixed_allocations_fit(monkeypatch, caplog): """Fixed allocations safely under 50% of budget: no warning, n_pcs unchanged.""" import logging
_stub_helpers(monkeypatch, gpu_total=80.0) _stub_preflight(monkeypatch, total=80.0, free=78.0) _stub_backend_custom(monkeypatch)
from recovar.utils import memory_planner as mp
with caplog.at_level(logging.WARNING, logger="recovar.utils.memory_planner"): plan = mp.make_memory_plan( command="pipeline", grid_size=128, n_images=1000, requested_gpu_gb=80.0, low_memory=False, very_low_memory=False, adaptive_n_pcs=False, desired_n_pcs=200, ) assert plan.n_pcs_to_compute == 200 warning_texts = "\n".join(r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING) assert "PRE-LAUNCH OOM PREDICTION" not in warning_texts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349"""Tests for recovar.metadata_parsing — STAR/CS pose and CTF extraction."""
import osimport tempfile
import numpy as npimport pytestfrom numpy.testing import assert_allclose
from recovar import utilsfrom recovar.data_io import metadata_readers as metadata_parsingfrom recovar.data_io.starfile import StarFile, write_star
# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------
def _make_test_star(n=20, grid_size=64, voxel_size=1.5, seed=42): """Create a temporary STAR file with known poses and CTF parameters.
Returns (path, rotations, translations_pixels, ctf_params_raw). """ rng = np.random.RandomState(seed)
# Random rotation matrices from scipy.spatial.transform import Rotation as R
rots_scipy = R.random(n, random_state=seed) rot_matrices = rots_scipy.as_matrix() # (N, 3, 3)
# Convert to RELION Euler angles and back to get consistent matrices euler_relion = utils.R_to_relion(rot_matrices, degrees=True) # (N, 3) rot_matrices_relion = utils.R_from_relion(euler_relion, degrees=True) # (N, 3, 3)
# Random translations in Angstroms trans_angstrom = rng.uniform(-5, 5, (n, 2))
# Random CTF parameters dfu = rng.uniform(5000, 25000, n) dfv = rng.uniform(5000, 25000, n) dfang = rng.uniform(0, 180, n) voltage = np.full(n, 300.0) cs = np.full(n, 2.7) w = np.full(n, 0.1) phase_shift = rng.uniform(0, 10, n)
# Build CTF params array for write_starfile ctf_params = np.column_stack([dfu, dfv, dfang, voltage, cs, w, phase_shift, np.zeros(n), np.ones(n)])
# Write star file using existing write_starfile import pandas as pd
tmpdir = tempfile.mkdtemp() star_path = os.path.join(tmpdir, "test.star")
# Use write_starfile from utils utils.write_starfile( CTF_params=ctf_params, rotation_matrices=rot_matrices_relion, translations=trans_angstrom, voxel_size=voxel_size, grid_size=grid_size, particles_file="dummy.mrcs", output_filename=star_path, )
return star_path, rot_matrices_relion, trans_angstrom, ctf_params, voxel_size, grid_size
def _make_test_cs(n=20, grid_size=64, voxel_size=1.5, seed=42): """Create a temporary CS file with known poses and CTF parameters.""" rng = np.random.RandomState(seed)
from scipy.spatial.transform import Rotation as R
rots_scipy = R.random(n, random_state=seed) rotvecs = rots_scipy.as_rotvec() # (N, 3) rot_matrices = rots_scipy.as_matrix() # (N, 3, 3)
# Translations in pixels trans_pixels = rng.uniform(-5, 5, (n, 2))
# CTF parameters dfu = rng.uniform(5000, 25000, n) dfv = rng.uniform(5000, 25000, n) dfang_rad = rng.uniform(0, np.pi, n) voltage = np.full(n, 300.0) cs_mm = np.full(n, 2.7) amp_contrast = np.full(n, 0.1) phase_shift_rad = rng.uniform(0, 0.2, n)
# Build structured array dtype = np.dtype( [ ("blob/idx", np.int32), ("blob/path", "U200"), ("blob/shape", np.int32, (2,)), ("blob/psize_A", np.float32), ("alignments3D/pose", np.float32, (3,)), ("alignments3D/shift", np.float32, (2,)), ("ctf/df1_A", np.float32), ("ctf/df2_A", np.float32), ("ctf/df_angle_rad", np.float32), ("ctf/accel_kv", np.float32), ("ctf/cs_mm", np.float32), ("ctf/amp_contrast", np.float32), ("ctf/phase_shift_rad", np.float32), ] )
cs_data = np.zeros(n, dtype=dtype) cs_data["blob/idx"] = np.arange(n) cs_data["blob/path"] = "dummy.mrcs" cs_data["blob/shape"] = [grid_size, grid_size] cs_data["blob/psize_A"] = voxel_size cs_data["alignments3D/pose"] = rotvecs.astype(np.float32) cs_data["alignments3D/shift"] = trans_pixels.astype(np.float32) cs_data["ctf/df1_A"] = dfu.astype(np.float32) cs_data["ctf/df2_A"] = dfv.astype(np.float32) cs_data["ctf/df_angle_rad"] = dfang_rad.astype(np.float32) cs_data["ctf/accel_kv"] = voltage.astype(np.float32) cs_data["ctf/cs_mm"] = cs_mm.astype(np.float32) cs_data["ctf/amp_contrast"] = amp_contrast.astype(np.float32) cs_data["ctf/phase_shift_rad"] = phase_shift_rad.astype(np.float32)
tmpdir = tempfile.mkdtemp() cs_path = os.path.join(tmpdir, "test.cs") # Use file object to prevent np.save from appending .npy to the path with open(cs_path, "wb") as f: np.save(f, cs_data)
return ( cs_path, rot_matrices, trans_pixels, dfu, dfv, dfang_rad, voltage, cs_mm, amp_contrast, phase_shift_rad, voxel_size, grid_size, )
# ---------------------------------------------------------------------------# STAR file tests# ---------------------------------------------------------------------------
class TestParseFromStar: def test_pose_roundtrip(self): """write_starfile → parse_poses_from_star recovers rotation matrices.""" star_path, rot_expected, trans_ang, _, voxel_size, grid_size = _make_test_star()
rots, trans_frac = metadata_parsing.parse_poses_from_star(star_path, grid_size)
assert rots.shape == rot_expected.shape # Rotation matrices should match to reasonable precision assert_allclose(rots, rot_expected, atol=1e-4)
def test_translation_convention(self): """Translations in Angstroms → fractional units.""" star_path, _, trans_ang, _, voxel_size, grid_size = _make_test_star()
_, trans_frac = metadata_parsing.parse_poses_from_star(star_path, grid_size)
# trans_ang are the values written to rlnOriginXAngst/Y (in pixel units by write_starfile) # The parser reads them as Angstroms and divides by Apix # Since write_starfile writes pixel-unit values to the Angstrom fields, # and the parser converts Angstrom → pixel (divide by Apix) then → fractional (divide by resolution), # we need to check the convention carefully. # write_starfile writes translations[:,0] and translations[:,1] directly. # These are in pixel units. The parser treats them as Angstroms. # So parsed_pixels = written_value / apix, and parsed_frac = parsed_pixels / resolution. # For self-consistency, we just check shape and range. assert trans_frac.shape == (20, 2) assert np.all(np.abs(trans_frac) <= 1.0), "Fractional translations should be in [-1, 1]"
def test_ctf_roundtrip(self): """write_starfile → parse_ctf_from_star recovers CTF parameters.""" star_path, _, _, ctf_raw, voxel_size, grid_size = _make_test_star()
ctf = metadata_parsing.parse_ctf_from_star(star_path, grid_size)
assert ctf.shape == (20, 8) # [Apix, DFU, DFV, DFANG, VOLT, CS, W, PHASE_SHIFT]
# Check defocus values match assert_allclose(ctf[:, 1], ctf_raw[:, 0], atol=1e-2) # DFU assert_allclose(ctf[:, 2], ctf_raw[:, 1], atol=1e-2) # DFV assert_allclose(ctf[:, 3], ctf_raw[:, 2], atol=1e-2) # DFANG assert_allclose(ctf[:, 4], ctf_raw[:, 3], atol=1e-2) # VOLT assert_allclose(ctf[:, 5], ctf_raw[:, 4], atol=1e-2) # CS assert_allclose(ctf[:, 6], ctf_raw[:, 5], atol=1e-2) # W
def test_ctf_apix_adjustment(self): """Pixel size is adjusted for target D != original D.""" star_path, _, _, _, voxel_size, grid_size = _make_test_star(grid_size=64, voxel_size=1.5)
# Parse at original D ctf_orig = metadata_parsing.parse_ctf_from_star(star_path, 64) # Parse at half D (downsampled) ctf_ds = metadata_parsing.parse_ctf_from_star(star_path, 32)
# Apix should double when D halves assert_allclose(ctf_ds[:, 0], ctf_orig[:, 0] * 2, rtol=1e-4)
def test_missing_pose_fields_raises(self): """STAR file without Euler angles raises ValueError.""" tmpdir = tempfile.mkdtemp() star_path = os.path.join(tmpdir, "no_poses.star")
import pandas as pd import starfile
optics = pd.DataFrame( { "rlnOpticsGroup": [1], "rlnOpticsGroupName": ["opticsGroup1"], "rlnVoltage": [300.0], "rlnImagePixelSize": [1.5], "rlnImageSize": [64], "rlnImageDimensionality": [2], "rlnAmplitudeContrast": [0.1], "rlnSphericalAberration": [2.7], } ) particles = pd.DataFrame( { "rlnImageName": ["1@dummy.mrcs"], "rlnDefocusU": [10000.0], "rlnDefocusV": [10000.0], "rlnDefocusAngle": [45.0], "rlnOpticsGroup": [1], } ) starfile.write({"optics": optics, "particles": particles}, star_path)
with pytest.raises(ValueError, match="rlnAngleRot"): metadata_parsing.parse_poses_from_star(star_path, 64)
# ---------------------------------------------------------------------------# cryoSPARC CS file tests# ---------------------------------------------------------------------------
class TestParseFromCS: def test_pose_extraction(self): """CS file pose extraction produces correct shape and dtype.""" cs_path, rot_expected, trans_pix, *_, voxel_size, grid_size = _make_test_cs()
rots, trans_frac = metadata_parsing.parse_poses_from_cs(cs_path, grid_size)
assert rots.shape == (20, 3, 3) assert trans_frac.shape == (20, 2)
# Rotations should be proper rotation matrices (det=1, R^T R = I) for i in range(rots.shape[0]): assert_allclose(np.linalg.det(rots[i]), 1.0, atol=1e-5) assert_allclose(rots[i] @ rots[i].T, np.eye(3), atol=1e-5)
def test_translation_fractional(self): """CS translations are correctly converted to fractional units.""" cs_path, _, trans_pix, *_, voxel_size, grid_size = _make_test_cs()
_, trans_frac = metadata_parsing.parse_poses_from_cs(cs_path, grid_size)
expected_frac = trans_pix / float(grid_size) assert_allclose(trans_frac, expected_frac, atol=1e-5)
def test_translation_uses_original_image_size_when_target_D_differs(self): """Downsampled target D must not rescale CS fractional translations.""" cs_path, _, trans_pix, *_, voxel_size, grid_size = _make_test_cs(grid_size=288)
_, trans_frac = metadata_parsing.parse_poses_from_cs(cs_path, 128)
expected_frac = trans_pix / float(grid_size) assert_allclose(trans_frac, expected_frac, atol=1e-5)
def test_ctf_extraction(self): """CS CTF extraction produces correct values.""" cs_path, _, _, dfu, dfv, dfang_rad, volt, cs_mm, amp_c, phase_rad, voxel_size, grid_size = _make_test_cs()
ctf = metadata_parsing.parse_ctf_from_cs(cs_path, grid_size)
assert ctf.shape == (20, 8) assert_allclose(ctf[:, 1], dfu, atol=1) # DFU assert_allclose(ctf[:, 2], dfv, atol=1) # DFV assert_allclose(ctf[:, 3], np.degrees(dfang_rad), atol=0.1) # DFANG in degrees assert_allclose(ctf[:, 4], volt, atol=0.1) # VOLT assert_allclose(ctf[:, 5], cs_mm, atol=0.01) # CS assert_allclose(ctf[:, 6], amp_c, atol=0.01) # W assert_allclose(ctf[:, 7], np.degrees(phase_rad), atol=0.1) # PHASE_SHIFT in degrees
def test_ctf_apix(self): """CS pixel size is correctly reported.""" cs_path, *_, voxel_size, grid_size = _make_test_cs(voxel_size=2.0)
ctf = metadata_parsing.parse_ctf_from_cs(cs_path, grid_size) assert_allclose(ctf[:, 0], 2.0, atol=0.01) # Apix
def test_missing_pose_field_raises(self): """CS file without pose field raises ValueError.""" tmpdir = tempfile.mkdtemp() cs_path = os.path.join(tmpdir, "no_poses.cs")
dtype = np.dtype([("blob/idx", np.int32), ("blob/path", "U200")]) data = np.zeros(5, dtype=dtype) data["blob/idx"] = np.arange(5) data["blob/path"] = "dummy.mrcs" with open(cs_path, "wb") as f: np.save(f, data)
with pytest.raises(ValueError, match="alignments3D/pose"): metadata_parsing.parse_poses_from_cs(cs_path, 64)
# ---------------------------------------------------------------------------# Auto-dispatch tests# ---------------------------------------------------------------------------
class TestAutoDispatch: def test_can_extract_star(self): assert metadata_parsing.can_extract_poses("particles.star")
def test_can_extract_cs(self): assert metadata_parsing.can_extract_poses("data.cs")
def test_cannot_extract_mrcs(self): assert not metadata_parsing.can_extract_poses("particles.mrcs")
def test_auto_parse_star(self): star_path, rot_expected, _, _, _, grid_size = _make_test_star(n=5) rots, _ = metadata_parsing.auto_parse_poses(star_path, grid_size) assert rots.shape == (5, 3, 3)
def test_auto_parse_cs(self): cs_path, _, _, *_, grid_size = _make_test_cs(n=5) rots, _ = metadata_parsing.auto_parse_poses(cs_path, grid_size) assert rots.shape == (5, 3, 3)
def test_auto_parse_unsupported_raises(self): with pytest.raises(ValueError, match="Cannot auto-extract"): metadata_parsing.auto_parse_poses("particles.mrcs", 64)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import numpy as npimport pytest
pytest.importorskip("jax")
from recovar.output import metrics
pytestmark = pytest.mark.unit
def test_variance_of_zs_zero_with_constant_labels(): z = np.array( [ [1.0, 2.0], [1.0, 2.0], [4.0, 5.0], [4.0, 5.0], ], dtype=np.float32, ) labels = np.array([0, 0, 1, 1], dtype=np.int32) label_vars, ratio = metrics.variance_of_zs(z, labels) # This function uses np.var over all elements in each label block. np.testing.assert_allclose(label_vars, np.array([0.25, 0.25], dtype=np.float32)) assert ratio == pytest.approx(0.0)
def test_fro_norm_diff_low_rank_matches_dense(): u = np.eye(2, dtype=np.float32) v = np.array([[0.0, 1.0], [1.0, 0.0]], dtype=np.float32) s = np.array([3.0, 1.0], dtype=np.float32) d = np.array([2.0, 0.5], dtype=np.float32)
out = float(metrics.fro_norm_diff_low_rank(u, s, v, d)) a = u @ np.diag(s) @ u.T b = v @ np.diag(d) @ v.T expected = np.linalg.norm(a - b, ord="fro") assert out == pytest.approx(expected, rel=1e-6, abs=1e-6)
def test_compute_volume_error_metrics_from_gt_aggregates(monkeypatch): monkeypatch.setattr(metrics, "local_fsc_metric", lambda *args, **kwargs: (1.0, 2.0, 3.0, 4.0)) monkeypatch.setattr(metrics, "local_error_metric", lambda *args, **kwargs: (5.0, 6.0))
gt = np.ones((2, 2, 2), dtype=np.float32) est = np.ones((2, 2, 2), dtype=np.float32) mask = np.array( [ [[True, False], [True, False]], [[True, True], [False, False]], ] ) partial_mask = ~mask
out = metrics.compute_volume_error_metrics_from_gt( gt_map=gt, estimate_map=est, voxel_size=1.5, mask=mask, partial_mask=partial_mask, normalize_by_map1=True, )
assert out["median_locres"] == 1.0 assert out["ninety_pc_locres"] == 2.0 assert out["median_auc"] == 3.0 assert out["ten_pc_auc"] == 4.0 assert out["median_error"] == 5.0 assert out["ninety_pc_error"] == 6.0 assert out["partial_median_locres"] == 1.0 assert out["partial_ninety_pc_error"] == 6.0 assert out["mask"] is mask assert out["partial_mask"] is partial_mask
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
import jaximport jax.numpy as jnp
@pytest.mark.gpudef test_fro_norm_diff_low_rank_gpu(gpu_device): u = np.eye(2, dtype=np.float32) v = np.array([[0.0, 1.0], [1.0, 0.0]], dtype=np.float32) s = np.array([3.0, 1.0], dtype=np.float32) d = np.array([2.0, 0.5], dtype=np.float32)
cpu_out = float(metrics.fro_norm_diff_low_rank(u, s, v, d))
with jax.default_device(gpu_device): u_g = jax.device_put(jnp.array(u), gpu_device) v_g = jax.device_put(jnp.array(v), gpu_device) s_g = jax.device_put(jnp.array(s), gpu_device) d_g = jax.device_put(jnp.array(d), gpu_device) gpu_out = float(metrics.fro_norm_diff_low_rank(u_g, s_g, v_g, d_g))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import pytest
from helpers.metrics_regression import compare_metric, metric_absolute_tolerance, metric_direction
pytestmark = pytest.mark.unit
def test_metric_direction_classification(): assert metric_direction("noise_mean_relative_error") == "lower" assert metric_direction("state_0_ninety_pc_locres") == "lower" assert metric_direction("mean_fsc") == "higher" assert metric_direction("noise_correlation") == "higher" assert metric_direction("pcs_relative_variance_4") == "higher" assert metric_direction("pcs_relative_variance_10") == "higher" assert metric_direction("some_unknown_metric") == "ignore"
def test_compare_metric_lower_and_higher(): ok, _ = compare_metric(current=1.05, baseline=1.0, direction="lower", tol_frac=0.1) assert ok ok, _ = compare_metric(current=1.20, baseline=1.0, direction="lower", tol_frac=0.1) assert not ok
ok, _ = compare_metric(current=0.95, baseline=1.0, direction="higher", tol_frac=0.1) assert ok ok, _ = compare_metric(current=0.70, baseline=1.0, direction="higher", tol_frac=0.1) assert not ok
def test_compare_metric_non_finite_fails(): ok, msg = compare_metric(current=float("nan"), baseline=1.0, direction="lower", tol_frac=0.1) assert not ok assert "non-finite" in msg
def test_metric_direction_for_canonical_key_names(): """Verify that renamed canonical keys are classified correctly.""" assert metric_direction("svd_relative_variance_4") == "higher" assert metric_direction("svd_relative_variance_10") == "higher" assert metric_direction("contrast_abs_error_4") == "lower" assert metric_direction("contrast_abs_error_4_noreg") == "lower" assert metric_direction("state_0_locres_90pct") == "lower" assert metric_direction("state_1_locres_median") == "lower"
def test_moving_piece_error_uses_absolute_tolerance_floor(): assert metric_absolute_tolerance("state_0_moving_piece_error_median") == pytest.approx(2e-3) assert metric_absolute_tolerance("state_1_moving_piece_error_90pct") == pytest.approx(3.5e-3)
ok, _ = compare_metric( current=0.019987913494816097, baseline=0.01949449979218878, direction="lower", tol_frac=0.01, metric_name="state_0_moving_piece_error_median", ) assert ok
ok, _ = compare_metric( current=0.0217, baseline=0.01949, direction="lower", tol_frac=0.01, metric_name="state_0_moving_piece_error_median", ) assert not ok
ok, _ = compare_metric( current=0.1377695314573107, baseline=0.13515495160141233, direction="lower", tol_frac=0.01, metric_name="state_1_moving_piece_error_90pct", ) assert ok
ok, _ = compare_metric( current=0.13836238668735856, baseline=0.13515495160141233, direction="lower", tol_frac=0.01, metric_name="state_1_moving_piece_error_90pct", ) assert ok
ok, _ = compare_metric( current=0.1392, baseline=0.13515495160141233, direction="lower", tol_frac=0.01, metric_name="state_1_moving_piece_error_90pct", ) assert not ok123456789101112131415161718192021222324252627282930313233343536import importlibfrom pathlib import Path
import pytest
pytestmark = pytest.mark.unit
SKIP_IMPORT_MODULES = { # CLI entrypoint packages are tested elsewhere. "__init__", "_version",}
# Optional dependency packages used by some modules.OPTIONAL_IMPORT_ERROR_TOKENS = ( "matplotlib_scalebar", "dataframe_image",)
def _module_names(): root = Path(__file__).resolve().parents[2] / "recovar" return sorted(p.stem for p in root.glob("*.py") if p.stem not in SKIP_IMPORT_MODULES)
@pytest.mark.parametrize("mod_name", _module_names())def test_all_top_level_modules_import(mod_name): full_name = f"recovar.{mod_name}" try: importlib.import_module(full_name) except ImportError as e: msg = str(e).lower() if any(tok in msg for tok in OPTIONAL_IMPORT_ERROR_TOKENS): pytest.skip(f"optional dependency missing while importing {full_name}: {e}") raise12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788from types import SimpleNamespace
import numpy as npimport pytest
pytest.importorskip("jax")
from recovar.utils import multi_gpu as mgu
pytestmark = pytest.mark.unit
def test_split_indices_for_gpus_even_and_remainder(): splits = mgu.split_indices_for_gpus(10, 3) assert len(splits) == 3 # np.array_split distributes extra items across first chunks: [4, 3, 3] assert [len(s) for s in splits] == [4, 3, 3] merged = np.concatenate(splits) assert np.all(merged == np.arange(10))
# Even split splits_even = mgu.split_indices_for_gpus(12, 3) assert [len(s) for s in splits_even] == [4, 4, 4] merged_even = np.concatenate(splits_even) assert np.all(merged_even == np.arange(12))
def test_reduce_results_sums_across_devices(): Hs = [np.ones((2, 2), dtype=np.float32), np.full((2, 2), 2.0, dtype=np.float32)] Bs = [np.array([1.0, 2.0], dtype=np.float32), np.array([3.0, 4.0], dtype=np.float32)] H, B = mgu.reduce_results(Hs, Bs) assert np.allclose(H, np.full((2, 2), 3.0)) assert np.allclose(B, np.array([4.0, 6.0]))
def test_estimate_multi_gpu_speedup_basic_monotonic(): s1 = mgu.estimate_multi_gpu_speedup(n_images=1000, n_gpus=1) s4 = mgu.estimate_multi_gpu_speedup(n_images=1000, n_gpus=4) assert s1["expected_speedup"] > 0 assert s4["expected_speedup"] > s1["expected_speedup"] assert s4["images_per_gpu"] == 250
def test_compute_H_B_multi_gpu_single_device_path(monkeypatch): class _FakeCtx: def __init__(self, _d): pass
def __enter__(self): return self
def __exit__(self, exc_type, exc, tb): return False
monkeypatch.setattr(mgu, "get_available_gpus", lambda: [SimpleNamespace(id=0)]) monkeypatch.setattr(mgu.jax, "default_device", lambda d: _FakeCtx(d))
called = {}
def compute_fn(ds, **kwargs): called["n_images"] = ds.n_images called["kwargs"] = kwargs return np.array([[1.0]], dtype=np.float32), np.array([2.0], dtype=np.float32)
ds = SimpleNamespace(n_images=5) H, B = mgu.compute_H_B_multi_gpu(compute_fn, ds, n_gpus=1, foo=3) assert np.allclose(H, np.array([[1.0]], dtype=np.float32)) assert np.allclose(B, np.array([2.0], dtype=np.float32)) assert called["n_images"] == 5 assert called["kwargs"]["foo"] == 3
def test_compute_H_B_multi_gpu_multi_device_reduction(monkeypatch): monkeypatch.setattr(mgu, "get_available_gpus", lambda: [SimpleNamespace(id=0), SimpleNamespace(id=1)]) monkeypatch.setattr(mgu, "split_indices_for_gpus", lambda n_items, n_gpus: [np.array([0, 1]), np.array([2, 3])])
def fake_parallel(_fn, _splits, _devices, *_args, **_kwargs): return [np.array([[1.0]], dtype=np.float32), np.array([[2.0]], dtype=np.float32)], [ np.array([10.0], dtype=np.float32), np.array([20.0], dtype=np.float32), ]
monkeypatch.setattr(mgu, "compute_on_gpus_parallel", fake_parallel) ds = SimpleNamespace(n_images=4)
H, B = mgu.compute_H_B_multi_gpu(lambda *_a, **_k: None, ds, n_gpus=2) assert np.allclose(H, np.array([[3.0]], dtype=np.float32)) assert np.allclose(B, np.array([30.0], dtype=np.float32))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595import numpy as npimport pytest
pytest.importorskip("jax")
import recovar.reconstruction.noise as noise
pytestmark = pytest.mark.unit
def test_radial_noise_model_get_and_average(): radial = np.array([1.0, 2.0, 3.0], dtype=np.float32) model = noise.RadialNoiseModel(radial, image_shape=(8, 8)) out = np.asarray(model.get()) assert out.shape == (1, 64) np.testing.assert_array_equal(np.asarray(model.get_average_radial_noise()), radial)
def test_variable_radial_noise_model_get_and_average(): radials = np.array( [ [1.0, 2.0, 3.0], [2.0, 4.0, 6.0], ], dtype=np.float32, ) dose_idx = np.array([0, 1, 1, 0], dtype=np.int32) model = noise.VariableRadialNoiseModel(radials, dose_idx, image_shape=(8, 8))
out = np.asarray(model.get(np.array([0, 2, 3], dtype=np.int32))) assert out.shape == (3, 64)
avg = np.asarray(model.get_average_radial_noise()) expected = 0.5 * radials[0] + 0.5 * radials[1] np.testing.assert_allclose(avg, expected)
def test_make_radial_noise_scalar_and_vector(): scalar = np.array([2.5], dtype=np.float32) out_scalar = np.asarray(noise.make_radial_noise(scalar, (6, 6))) assert out_scalar.shape == (36,) # flat, consistent with vector path assert np.allclose(out_scalar, 2.5)
vec = np.array([1.0, 2.0], dtype=np.float32) out_vec = np.asarray(noise.make_radial_noise(vec, (6, 6))) assert out_vec.shape == (36,) assert np.isfinite(out_vec).all()
def test_get_masked_noise_variance_from_noise_variance_shape(): image_shape = (4, 4) image_masks = np.ones((2, *image_shape), dtype=np.float32) unmasked_noise = np.arange(np.prod(image_shape), dtype=np.float32) out = np.asarray(noise.get_masked_noise_variance_from_noise_variance(image_masks, unmasked_noise, image_shape)) assert out.shape == (2, 4, 4) assert np.isfinite(out).all()
def test_variable_radial_noise_model_set_variance_1d_broadcast(): """Test that set_variance with 1D input still works for .get() when the model was originally constructed with 2D noise.""" radials_2d = np.array( [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32, ) dose_idx = np.array([0, 1, 1, 0, 0], dtype=np.int32) model = noise.VariableRadialNoiseModel(radials_2d, dose_idx, image_shape=(8, 8))
# Updating with a 2D array should work as before new_2d = np.array( [[10.0, 20.0, 30.0], [40.0, 50.0, 60.0]], dtype=np.float32, ) model.set_variance(new_2d) out = np.asarray(model.get(np.array([0, 1], dtype=np.int32))) assert out.shape == (2, 64)
def test_variable_radial_noise_model_via_dataset_1d_broadcast(): """Test the fix: set_variable_radial_noise_model with 1D input broadcasts to 2D so VariableRadialNoiseModel.get() doesn't crash.""" import jax.numpy as jnp from recovar import core
# Simulate a CryoEMDataset-like object with CTF_params that have # multiple dose levels (7 tilts → 7 unique dose values) n_images = 21 # 3 particles × 7 tilts n_tilts = 7 grid_size = 8
# Build minimal CTF_params with different dose values per tilt ctf_params = np.zeros((n_images, 11), dtype=np.float32) doses = np.repeat(np.arange(n_tilts, dtype=np.float32), 3) # 7 unique doses ctf_params[:, core.CTFParamIndex.DOSE] = doses
# Create a mock dataset class with the method we fixed class MockDataset: def __init__(self): self.CTF_params = ctf_params self.image_shape = (grid_size, grid_size) self.noise = None
def set_variable_radial_noise_model(self, noise_variance_radials): _, dose_indices = jnp.unique(self.CTF_params[:, core.CTFParamIndex.DOSE], return_inverse=True) if noise_variance_radials is not None and np.ndim(noise_variance_radials) == 1: n_doses = int(jnp.max(dose_indices)) + 1 noise_variance_radials = np.tile(noise_variance_radials, (n_doses, 1)) self.noise = noise.VariableRadialNoiseModel( noise_variance_radials, dose_indices, image_shape=self.image_shape )
ds = MockDataset() # 1D noise profile (the case that was crashing) radial_1d = np.array([1.0, 2.0, 3.0], dtype=np.float32) ds.set_variable_radial_noise_model(radial_1d)
# Verify: noise model has 2D noise_variance_radials assert ds.noise.noise_variance_radials.ndim == 2 assert ds.noise.noise_variance_radials.shape == (n_tilts, 3)
# Verify: .get() works for arbitrary image indices out = np.asarray(ds.noise.get(np.array([0, 5, 10, 20], dtype=np.int32))) assert out.shape == (4, grid_size * grid_size) assert np.isfinite(out).all()
# All dose levels should have the same radial profile (broadcast from 1D) for i in range(n_tilts): np.testing.assert_array_equal(ds.noise.noise_variance_radials[i], radial_1d)
def test_upper_bound_noise_dispatched_1d_noise(): """Test that upper_bound_noise_by_signal_p_noise_dispatched handles 1D noise_var_used correctly (doesn't index a scalar from 1D array).""" # This is a shape/indexing test — we verify the dispatching logic # selects the right noise slice for 1D vs 2D inputs. noise_1d = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32) noise_2d = np.array( [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]], dtype=np.float32, )
# For 2D, indexing by tilt gives a row assert noise_2d[0].shape == (4,) assert noise_2d[1].shape == (4,)
# For 2D, indexing by tilt gives a 1D row for tilt_idx in range(noise_2d.shape[0]): noise_for_tilt = noise_2d[tilt_idx] if np.ndim(noise_2d) >= 2 else noise_2d assert noise_for_tilt.ndim == 1
# For 1D, the fix uses the whole array for every tilt index for tilt_idx in range(5): # more tilts than radial bins — should still work noise_for_tilt = noise_1d[tilt_idx] if np.ndim(noise_1d) >= 2 else noise_1d assert noise_for_tilt.ndim == 1 np.testing.assert_array_equal(noise_for_tilt, noise_1d)
def test_batch_make_radial_noise_matches_vmap(): """batch_make_radial_noise should produce the same result as manual vmap.""" radials = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32) image_shape = (6, 6) batch_out = np.asarray(noise.batch_make_radial_noise(radials, image_shape)) assert batch_out.shape == (2, 36) # Compare with individual calls for i in range(2): single = np.asarray(noise.make_radial_noise(radials[i], image_shape)) np.testing.assert_allclose(batch_out[i], single, atol=1e-6)
def test_batch_basis_times_coords2_matches_matmul(): """batch_basis_times_coords2 should match direct basis @ coords.T.""" import jax.numpy as jnp
rng = np.random.default_rng(42) # basis: (pixels, n_basis), coords: (n_images, n_basis) basis = jnp.array(rng.normal(size=(10, 3)).astype(np.float32)) coords = jnp.array(rng.normal(size=(5, 3)).astype(np.float32)) out = np.asarray(noise.batch_basis_times_coords2(basis, coords)) expected = np.asarray(basis @ coords.T).T # (n_images, pixels) assert out.shape == (5, 10) np.testing.assert_allclose(out, expected, atol=1e-5)
def test_to_batched_pixel_noise_normalizes_common_shapes(): image_shape = (4, 4)
n2 = np.arange(16, dtype=np.float32).reshape(4, 4) out2 = np.asarray(noise.to_batched_pixel_noise(n2, image_shape, batch_size=3)) assert out2.shape == (1, 16) # (1, N) — callers broadcast; no explicit repeat
n3 = np.arange(2 * 16, dtype=np.float32).reshape(2, 4, 4) out3 = np.asarray(noise.to_batched_pixel_noise(n3, image_shape)) assert out3.shape == (2, 16)
n1 = np.arange(16, dtype=np.float32) out1 = np.asarray(noise.to_batched_pixel_noise(n1, image_shape)) assert out1.shape == (1, 16)
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
import jaximport jax.numpy as jnp
@pytest.mark.gpudef test_make_radial_noise_gpu(gpu_device): vec = np.array([1.0, 2.0], dtype=np.float32) image_shape = (6, 6)
cpu_out = np.asarray(noise.make_radial_noise(vec, image_shape))
with jax.default_device(gpu_device): vec_g = jax.device_put(jnp.array(vec), gpu_device) gpu_out = np.asarray(noise.make_radial_noise(vec_g, image_shape))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_to_batched_pixel_noise_gpu(gpu_device): image_shape = (4, 4) n2 = np.arange(16, dtype=np.float32).reshape(4, 4)
cpu_out = np.asarray(noise.to_batched_pixel_noise(n2, image_shape, batch_size=3))
with jax.default_device(gpu_device): n2_g = jax.device_put(jnp.array(n2), gpu_device) gpu_out = np.asarray(noise.to_batched_pixel_noise(n2_g, image_shape, batch_size=3))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_radial_noise_model_get_gpu(gpu_device): radial = np.array([1.0, 2.0, 3.0], dtype=np.float32) model = noise.RadialNoiseModel(radial, image_shape=(8, 8))
cpu_out = np.asarray(model.get())
with jax.default_device(gpu_device): model_g = noise.RadialNoiseModel(jax.device_put(jnp.array(radial), gpu_device), image_shape=(8, 8)) gpu_out = np.asarray(model_g.get())
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_variable_radial_noise_model_get_gpu(gpu_device): radials = np.array([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0]], dtype=np.float32) dose_idx = np.array([0, 1, 1, 0], dtype=np.int32) model = noise.VariableRadialNoiseModel(radials, dose_idx, image_shape=(8, 8)) query = np.array([0, 2, 3], dtype=np.int32)
cpu_out = np.asarray(model.get(query))
with jax.default_device(gpu_device): model_g = noise.VariableRadialNoiseModel( jax.device_put(jnp.array(radials), gpu_device), jax.device_put(jnp.array(dose_idx), gpu_device), image_shape=(8, 8), ) gpu_out = np.asarray(model_g.get(jax.device_put(jnp.array(query), gpu_device)))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_get_masked_noise_variance_gpu(gpu_device): image_shape = (4, 4) image_masks = np.ones((2, *image_shape), dtype=np.float32) unmasked_noise = np.arange(np.prod(image_shape), dtype=np.float32)
cpu_out = np.asarray(noise.get_masked_noise_variance_from_noise_variance(image_masks, unmasked_noise, image_shape))
with jax.default_device(gpu_device): masks_g = jax.device_put(jnp.array(image_masks), gpu_device) noise_g = jax.device_put(jnp.array(unmasked_noise), gpu_device) gpu_out = np.asarray(noise.get_masked_noise_variance_from_noise_variance(masks_g, noise_g, image_shape))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
# ---------------------------------------------------------------------------# Half-image noise equivalence tests# ---------------------------------------------------------------------------
import recovar.core.fourier_transform_utils as fourier_transform_utils
def test_make_radial_noise_half_matches_full_extraction(): """Verify make_radial_noise_half matches full_image_to_half_image(make_radial_noise).""" for image_shape in [(8, 8), (6, 10), (4, 8)]: vec = np.array([1.0, 2.0, 3.0], dtype=np.float32) full = np.asarray(noise.make_radial_noise(vec, image_shape)) half_native = np.asarray(noise.make_radial_noise_half(vec, image_shape)) half_from_full = np.asarray( fourier_transform_utils.full_image_to_half_image(full.reshape(1, -1), image_shape) ).ravel() np.testing.assert_allclose( half_native, half_from_full, atol=1e-6, rtol=1e-6, err_msg=f"Failed for image_shape={image_shape}" )
def test_make_radial_noise_half_scalar(): """Verify scalar noise broadcasts correctly in half layout.""" image_shape = (8, 8) scalar = np.array([2.5], dtype=np.float32) half = np.asarray(noise.make_radial_noise_half(scalar, image_shape)) expected_size = image_shape[0] * (image_shape[1] // 2 + 1) assert half.size == expected_size np.testing.assert_allclose(half.ravel(), 2.5, atol=1e-7)
def test_batch_make_radial_noise_half_matches_full(): """Verify batch_make_radial_noise_half matches full_image_to_half_image(batch_make_radial_noise).""" image_shape = (6, 10) radials = np.array( [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32, ) full = np.asarray(noise.batch_make_radial_noise(radials, image_shape)) half_native = np.asarray(noise.batch_make_radial_noise_half(radials, image_shape)) half_from_full = np.asarray(fourier_transform_utils.full_image_to_half_image(full, image_shape)) np.testing.assert_allclose(half_native, half_from_full, atol=1e-6, rtol=1e-6)
def test_radial_noise_model_get_half_matches_full(): """Verify RadialNoiseModel.get_half() matches extraction from get().""" radial = np.array([1.0, 2.0, 3.0], dtype=np.float32) image_shape = (8, 8) model = noise.RadialNoiseModel(radial, image_shape=image_shape) full = np.asarray(model.get()) half = np.asarray(model.get_half()) expected = np.asarray(fourier_transform_utils.full_image_to_half_image(full, image_shape)) np.testing.assert_allclose(half, expected, atol=1e-6, rtol=1e-6)
def test_variable_radial_noise_model_get_half_matches_full(): """Verify VariableRadialNoiseModel.get_half() matches extraction from get().""" radials = np.array( [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0]], dtype=np.float32, ) dose_idx = np.array([0, 1, 1, 0], dtype=np.int32) image_shape = (8, 8) model = noise.VariableRadialNoiseModel(radials, dose_idx, image_shape=image_shape) indices = np.array([0, 2, 3], dtype=np.int32) full = np.asarray(model.get(indices)) half = np.asarray(model.get_half(indices)) expected = np.asarray(fourier_transform_utils.full_image_to_half_image(full, image_shape)) np.testing.assert_allclose(half, expected, atol=1e-6, rtol=1e-6)
def test_to_batched_half_pixel_noise_scalar(): """Scalar noise should expand to (1, N_half) — callers broadcast.""" image_shape = (8, 8) half_pixel_count = image_shape[0] * (image_shape[1] // 2 + 1) out = np.asarray(noise.to_batched_half_pixel_noise(2.5, image_shape, batch_size=3)) assert out.shape == (1, half_pixel_count) # (1, N) — XLA broadcasts to (B, N) np.testing.assert_allclose(out, 2.5, atol=1e-7)
def test_to_batched_half_pixel_noise_passthrough(): """Half-pixel input should pass through unchanged (no explicit repeat).""" image_shape = (8, 8) half_pixel_count = image_shape[0] * (image_shape[1] // 2 + 1) half_input = np.arange(half_pixel_count, dtype=np.float32).reshape(1, -1) out = np.asarray(noise.to_batched_half_pixel_noise(half_input, image_shape, batch_size=2)) assert out.shape == (1, half_pixel_count) # (1, N) — XLA broadcasts to (B, N) np.testing.assert_array_equal(out[0], half_input.ravel())
def test_to_batched_half_pixel_noise_full_converts(): """Full-pixel input should be converted to half-pixel via full_image_to_half_image.""" image_shape = (4, 4) full_pixel_count = 16 half_pixel_count = 4 * 3 # 4*(4//2+1) = 12 full_input = np.arange(full_pixel_count, dtype=np.float32).reshape(1, -1) out = np.asarray(noise.to_batched_half_pixel_noise(full_input, image_shape)) assert out.shape == (1, half_pixel_count) expected = np.asarray(fourier_transform_utils.full_image_to_half_image(full_input, image_shape)) np.testing.assert_allclose(out, expected, atol=1e-6)
class _MockImageSource: def __init__(self, image_shape, scale=1.0): self.mask = np.ones(image_shape, dtype=np.float32) self._scale = np.float32(scale)
def process_images(self, images): return jnp.asarray(images) * self._scale
class _MockNoiseDataset: """Minimal dataset stub to compare legacy loops vs explicit iterator paths."""
def __init__(self, images, image_shape): self._images = jnp.asarray(images) self.n_images = int(images.shape[0]) self.image_shape = tuple(image_shape) self.grid_size = int(image_shape[0]) self.image_size = int(np.prod(image_shape)) self.volume_shape = (self.grid_size, self.grid_size, self.grid_size) self.volume_mask_threshold = 0.0 self.padding = 0 self.voxel_size = 1.0 self.dtype_real = np.float32 self.premultiplied_ctf = False
self.image_source = _MockImageSource(image_shape, scale=1.25) self.translations = jnp.zeros((self.n_images, 2), dtype=jnp.float32) self.rotation_matrices = jnp.tile(jnp.eye(3, dtype=jnp.float32), (self.n_images, 1, 1)) self.CTF_params = jnp.zeros((self.n_images, 1), dtype=jnp.float32)
def process_images(self, images, apply_image_mask=False): _ = apply_image_mask return self.image_source.process_images(images)
@property def image_mask(self): return self.image_source.mask
def ctf_evaluator(self, ctf_params, image_shape, voxel_size): del voxel_size return jnp.ones((ctf_params.shape[0], int(np.prod(image_shape))), dtype=jnp.float32)
def _iter_indices(self, indices, batch_size): idx = np.asarray(indices, dtype=np.int32) for start in range(0, idx.size, batch_size): batch_ind = idx[start : start + batch_size] yield self._images[batch_ind], batch_ind, batch_ind
def iter_batches(self, batch_size, *, indices=None, **kwargs): _ = kwargs if indices is None: indices = np.arange(self.n_images, dtype=np.int32) idx = np.asarray(indices, dtype=np.int32) for start in range(0, idx.size, batch_size): batch_ind = idx[start : start + batch_size] yield ( self._images[batch_ind], self.rotation_matrices[batch_ind], self.translations[batch_ind], self.CTF_params[batch_ind], None, batch_ind, batch_ind, )
def _legacy_estimate_noise_variance(dataset, batch_size, max_images=10000): from recovar.reconstruction import regularization
sum_sq = 0 if dataset.n_images > max_images: subset_indices = np.random.choice(dataset.n_images, size=max_images, replace=False) data_generator = dataset.iter_batches(batch_size=batch_size, indices=subset_indices) n_images_used = max_images else: data_generator = dataset.iter_batches(batch_size=batch_size) n_images_used = dataset.n_images
for ( batch, _rotation_matrices, _translations, _ctf_params, _noise_variance, _particle_indices, _image_indices, ) in data_generator: batch = dataset.image_source.process_images(batch) sum_sq += jnp.sum(jnp.abs(batch) ** 2, axis=0)
mean_ps = sum_sq / n_images_used cov_noise_mask = jnp.median(mean_ps) average_image_ps = regularization.average_over_shells(mean_ps, dataset.image_shape) return np.asarray(cov_noise_mask, dtype=dataset.dtype_real), np.asarray(average_image_ps, dtype=dataset.dtype_real)
def _legacy_estimate_noise_level_no_masks(dataset, image_subset, mean_estimate, batch_size, disc_type="linear_interp"): from recovar import core from recovar.core.configs import ForwardModelConfig from recovar.reconstruction import regularization
lhs = 0 rhs = 0 config = ForwardModelConfig.from_dataset(dataset, disc_type=disc_type) data_generator = dataset.iter_batches(batch_size=batch_size, indices=image_subset)
for ( batch, rotation_matrices, translations, ctf_params, _noise_variance, _particle_indices, batch_ind, ) in data_generator: batch = dataset.image_source.process_images(batch) batch = core.translate_images(batch, dataset.translations[batch_ind], dataset.image_shape) ctf = dataset.ctf_evaluator(ctf_params, dataset.image_shape, dataset.voxel_size)
if mean_estimate is not None: projected_mean = noise.core_forward.forward_model( config, mean_estimate, ctf_params, rotation_matrices, ) if dataset.premultiplied_ctf: batch = batch - projected_mean * ctf else: batch = batch - projected_mean
averaged_ps = regularization.batch_average_over_shells(jnp.abs(batch) ** 2, dataset.image_shape, 0) lhs += jnp.sum(averaged_ps, axis=0) rhs += ( batch.shape[0] if not dataset.premultiplied_ctf else jnp.sum( regularization.batch_average_over_shells(jnp.abs(ctf) ** 2, dataset.image_shape, 0), axis=0, ) )
estimated_noise = lhs / rhs valid_mask = jnp.isfinite(estimated_noise) if not jnp.all(valid_mask): valid_indices = jnp.where(valid_mask)[0] last_valid_value = estimated_noise[valid_indices[-1]] if valid_indices.size > 0 else 1.0 estimated_noise = jnp.where(valid_mask, estimated_noise, last_valid_value) return estimated_noise
def test_estimate_noise_variance_matches_legacy_loop(): rng = np.random.default_rng(7) image_shape = (4, 4) images = ( rng.normal(size=(9, np.prod(image_shape))).astype(np.float32) + 1j * rng.normal(size=(9, np.prod(image_shape))).astype(np.float32) ).astype(np.complex64) ds = _MockNoiseDataset(images, image_shape=image_shape)
expected_cov, expected_radial = _legacy_estimate_noise_variance(ds, batch_size=3, max_images=100) cov, radial = noise.estimate_noise_variance(ds, batch_size=3, max_images=100)
np.testing.assert_allclose(cov, expected_cov, atol=1e-6, rtol=1e-6) np.testing.assert_allclose(radial, expected_radial, atol=1e-6, rtol=1e-6)
def test_estimate_noise_variance_subset_sampling_runs(): """Smoke test: estimate_noise_variance with subsampling runs without error.""" rng = np.random.default_rng(11) image_shape = (4, 4) images = ( rng.normal(size=(10, np.prod(image_shape))).astype(np.float32) + 1j * rng.normal(size=(10, np.prod(image_shape))).astype(np.float32) ).astype(np.complex64) ds = _MockNoiseDataset(images, image_shape=image_shape)
cov, radial = noise.estimate_noise_variance(ds, batch_size=2, max_images=4)
assert np.isfinite(cov) assert np.all(np.isfinite(radial)) assert radial.shape[0] > 0
def test_estimate_noise_level_no_masks_matches_legacy_loop(): rng = np.random.default_rng(19) image_shape = (4, 4) images = ( rng.normal(size=(8, np.prod(image_shape))).astype(np.float32) + 1j * rng.normal(size=(8, np.prod(image_shape))).astype(np.float32) ).astype(np.complex64) ds = _MockNoiseDataset(images, image_shape=image_shape) subset = np.arange(ds.n_images, dtype=np.int32)
expected = _legacy_estimate_noise_level_no_masks( ds, image_subset=subset, mean_estimate=None, batch_size=3, ) got = noise.estimate_noise_level_no_masks( ds, image_subset=subset, mean_estimate=None, batch_size=3, )
np.testing.assert_allclose(np.asarray(got), np.asarray(expected), atol=1e-6, rtol=1e-6)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439import os
import numpy as npimport pytest
pytest.importorskip("jax")
from recovar.output import outputfrom recovar.output import plot_utils
pytestmark = pytest.mark.unit
def test_get_resampled_distances_and_resample_trajectory(): vols = np.array( [ [0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0], ], dtype=np.float32, ) d = output.get_resampled_distances(vols) idx = output.resample_trajectory(vols, n_vols_along_path=3) assert np.all(d[1:] >= d[:-1]) assert idx.shape == (3,) assert idx[0] == 0 assert idx[-1] == 4
def test_sum_over_other_and_slice_helpers(): x = np.arange(2 * 3 * 4, dtype=np.float32).reshape(2, 3, 4) summed = output.sum_over_other(x, use_axis=[0, 2]) assert summed.shape == (2, 4) assert np.allclose(summed, x.sum(axis=1))
density = np.arange(5 * 6 * 7, dtype=np.float32).reshape(5, 6, 7) half = output.half_slice_other(density, axes=[0, 2]) assert half.shape == (5, 7) assert np.allclose(half, density[:, density.shape[1] // 2, :])
pt = [1, 2, 3] sl = output.slice_at_point(density, axes=[0, 2], point=pt) assert sl.shape == (5, 7) assert np.allclose(sl, density[:, pt[1], :])
def test_save_covar_output_volumes_clamps_to_available_pcs(monkeypatch, tmp_path): # Regression test for IndexError when available PCs < default us_to_save. d = 8 vol_size = d**3 n_pcs = 30
mean = np.zeros(vol_size, dtype=np.complex64) u = np.random.randn(vol_size, n_pcs).astype(np.float32) s = {"rescaled": np.abs(np.random.randn(n_pcs)).astype(np.float32) + 1e-3} volume_mask = np.ones((d, d, d), dtype=np.float32)
calls = {"n_eigs": []}
monkeypatch.setattr(output, "save_volumes", lambda vols, *args, **kwargs: calls.setdefault("saved_vols", len(vols))) monkeypatch.setattr(output, "save_volume", lambda *args, **kwargs: None) monkeypatch.setattr( output.linalg, "batch_idft3", lambda arr, volume_shape, vol_batch_size: np.asarray(arr, dtype=np.float32) ) monkeypatch.setattr(output.utils, "estimate_variance", lambda u_t, svals: np.ones(u_t.shape[-1], dtype=np.float32))
output.save_covar_output_volumes( str(tmp_path) + "/", mean=mean, u=u, s=s, mask=volume_mask, volume_shape=(d, d, d), us_to_save=50, # intentionally larger than available us_to_var=[4, 10, 20], # all <= n_pcs voxel_size=1.0, )
# Should save exactly n_pcs eigenvectors, not fail on index n_pcs. assert calls["saved_vols"] == n_pcs
def test_save_covar_output_volumes_skips_variance_when_no_pcs(monkeypatch, tmp_path): d = 8 vol_size = d**3
mean = np.zeros(vol_size, dtype=np.complex64) u = np.zeros((vol_size, 0), dtype=np.float32) # no PCs available s = {"rescaled": np.zeros((0,), dtype=np.float32)} volume_mask = np.ones((d, d, d), dtype=np.float32)
calls = {"save_volumes": 0, "save_volume": 0}
monkeypatch.setattr( output, "save_volumes", lambda vols, *args, **kwargs: calls.__setitem__("save_volumes", calls["save_volumes"] + 1), ) monkeypatch.setattr( output, "save_volume", lambda *args, **kwargs: calls.__setitem__("save_volume", calls["save_volume"] + 1), ) monkeypatch.setattr( output.linalg, "batch_idft3", lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("batch_idft3 should not run for 0 PCs")), )
output.save_covar_output_volumes( str(tmp_path) + "/", mean=mean, u=u, s=s, mask=volume_mask, volume_shape=(d, d, d), us_to_save=50, us_to_var=[4, 10, 20], voxel_size=1.0, )
# Called once for eigen_pos (empty list is fine) and once for mean volume. assert calls["save_volumes"] == 1 assert calls["save_volume"] == 1
def test_save_covar_output_volumes_clamps_variance_rank_to_available_svals(monkeypatch, tmp_path): d = 8 vol_size = d**3 n_pcs = 8 n_svals = 3
mean = np.zeros(vol_size, dtype=np.complex64) u = np.random.randn(vol_size, n_pcs).astype(np.float32) s = {"rescaled": np.abs(np.random.randn(n_svals)).astype(np.float32) + 1e-3} volume_mask = np.ones((d, d, d), dtype=np.float32)
calls = {"ranks": []}
monkeypatch.setattr(output, "save_volumes", lambda *_args, **_kwargs: None) monkeypatch.setattr(output, "save_volume", lambda *_args, **_kwargs: None)
def _fake_batch_idft3(arr, volume_shape, vol_batch_size): _ = volume_shape, vol_batch_size calls["ranks"].append(int(arr.shape[-1])) return np.asarray(arr, dtype=np.float32)
def _fake_estimate_variance(u_t, svals): assert int(u_t.shape[0]) == int(len(svals)) return np.ones(u_t.shape[-1], dtype=np.float32)
monkeypatch.setattr(output.linalg, "batch_idft3", _fake_batch_idft3) monkeypatch.setattr(output.utils, "estimate_variance", _fake_estimate_variance)
output.save_covar_output_volumes( str(tmp_path) + "/", mean=mean, u=u, s=s, mask=volume_mask, volume_shape=(d, d, d), us_to_save=5, us_to_var=[2, 5, 7], # requests above n_svals must clamp to n_svals voxel_size=1.0, )
assert calls["ranks"] == [2, n_svals, n_svals]
def test_save_covar_output_volumes_negative_us_to_save_yields_no_eigenvectors(monkeypatch, tmp_path): d = 8 vol_size = d**3 n_pcs = 4
mean = np.zeros(vol_size, dtype=np.complex64) u = np.random.randn(vol_size, n_pcs).astype(np.float32) s = {"rescaled": np.abs(np.random.randn(n_pcs)).astype(np.float32) + 1e-3} volume_mask = np.ones((d, d, d), dtype=np.float32)
calls = {"save_volumes_sizes": []}
monkeypatch.setattr( output, "save_volumes", lambda vols, *_args, **_kwargs: calls["save_volumes_sizes"].append(len(vols)), ) monkeypatch.setattr(output, "save_volume", lambda *_args, **_kwargs: None) monkeypatch.setattr(output.linalg, "batch_idft3", lambda arr, *_args, **_kwargs: np.asarray(arr, dtype=np.float32)) monkeypatch.setattr(output.utils, "estimate_variance", lambda u_t, svals: np.ones(u_t.shape[-1], dtype=np.float32))
output.save_covar_output_volumes( str(tmp_path) + "/", mean=mean, u=u, s=s, mask=volume_mask, volume_shape=(d, d, d), us_to_save=-5, us_to_var=[], voxel_size=1.0, )
# First call corresponds to eigenvectors export. assert calls["save_volumes_sizes"][0] == 0
def test_save_covar_output_volumes_large_grid_clamps_batch_size_to_one(monkeypatch, tmp_path): mean = np.zeros(8, dtype=np.complex64) u = np.random.randn(8, 2).astype(np.float32) s = {"rescaled": np.array([1.0, 0.5], dtype=np.float32)} volume_mask = np.ones((2, 2, 2), dtype=np.float32)
seen = {"vol_batch_size": []}
monkeypatch.setattr(output, "save_volumes", lambda *_args, **_kwargs: None) monkeypatch.setattr(output, "save_volume", lambda *_args, **_kwargs: None)
def _fake_batch_idft3(arr, volume_shape, vol_batch_size): _ = arr, volume_shape seen["vol_batch_size"].append(int(vol_batch_size)) return np.ones((2, int(arr.shape[-1])), dtype=np.float32)
monkeypatch.setattr(output.linalg, "batch_idft3", _fake_batch_idft3) monkeypatch.setattr(output.utils, "estimate_variance", lambda u_t, svals: np.ones(u_t.shape[-1], dtype=np.float32))
output.save_covar_output_volumes( str(tmp_path) + "/", mean=mean, u=u, s=s, mask=volume_mask, # Very large grid would previously make int((2**24)/(grid_size**3)) == 0. volume_shape=(1024, 1024, 1024), us_to_save=1, us_to_var=[1], voxel_size=1.0, )
assert seen["vol_batch_size"] == [1]
def test_get_nearest_point_finds_closest(): data = np.array([[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]], dtype=np.float32) query = np.array([[0.1, 0.0], [1.9, 0.1]], dtype=np.float32) points, indices = output.get_nearest_point(data, query) assert indices[0] == 0 assert indices[1] == 2 np.testing.assert_allclose(points[0], data[0]) np.testing.assert_allclose(points[1], data[2])
def test_get_nearest_point_single_data_point(): data = np.array([[3.0, 4.0]], dtype=np.float32) query = np.array([[0.0, 0.0], [10.0, 10.0]], dtype=np.float32) points, indices = output.get_nearest_point(data, query) assert list(indices) == [0, 0] np.testing.assert_allclose(points, np.tile(data, (2, 1)))
def test_get_nearest_point_chunked_matches_dense_path(): data = np.array([[0.0, 0.0], [1.0, 0.0], [3.0, 0.0]], dtype=np.float32) query = np.array([[0.1, 0.0], [2.9, 0.0], [1.2, 0.0]], dtype=np.float32) dense_points, dense_indices = output.get_nearest_point(data, query) chunked_points, chunked_indices = output.get_nearest_point(data, query, chunk_size=1) np.testing.assert_array_equal(chunked_indices, dense_indices) np.testing.assert_allclose(chunked_points, dense_points)
def test_standard_pipeline_plots_uses_embedding_component_api(monkeypatch, tmp_path): calls = []
class _PO: def get(self, key): if key in {"latent_coords", "contrasts"}: raise AssertionError(f"standard_pipeline_plots should not call get('{key}')") if key == "s": return np.ones(4, dtype=np.float32) raise KeyError(key)
def get_embedding_keys(self, entry): assert entry == "latent_coords" return [4]
def get_embedding_component(self, entry, key): calls.append((entry, key)) if entry == "contrasts": return np.ones(12, dtype=np.float32) if entry == "latent_coords": return np.arange(48, dtype=np.float32).reshape(12, 4) raise KeyError(entry)
monkeypatch.setattr(output, "mkdir_safe", lambda path: tmp_path.mkdir(exist_ok=True)) monkeypatch.setattr(plot_utils, "plot_summary_t", lambda *_args, **_kwargs: None) monkeypatch.setattr(plot_utils, "plot_contrast_histogram", lambda *_args, **_kwargs: None) monkeypatch.setattr(plot_utils, "plot_eigenvalues", lambda *_args, **_kwargs: None) monkeypatch.setattr(plot_utils, "plot_mean_fsc", lambda *_args, **_kwargs: None) monkeypatch.setattr(plot_utils, "plot_pipeline_summary", lambda *_args, **_kwargs: None)
output.standard_pipeline_plots(_PO(), 4, str(tmp_path))
assert ("contrasts", 4) in calls assert ("latent_coords", 4) in calls
def test_volume_output_paths_places_primary_and_diag_correctly(tmp_path): """VolumeOutputPaths should put primary outputs at root and diagnostics in subdir.""" from recovar.output.output_paths import VolumeOutputPaths
vp = VolumeOutputPaths(str(tmp_path), "state", 0) vp.ensure_dirs()
# Primary outputs should be in tmp_path directly assert vp.filtered == str(tmp_path / "state000.mrc") assert vp.half1_unfil == str(tmp_path / "state000_half1_unfil.mrc") assert vp.half2_unfil == str(tmp_path / "state000_half2_unfil.mrc")
# Diagnostics should be in diagnostics/state000/ assert "diagnostics" in vp.params assert "diagnostics" in vp.split_choice assert os.path.isdir(vp.diag_dir)
def test_make_trajectory_plots_from_results_uses_pipeline_output_helpers(monkeypatch, tmp_path): captured = {} fake_dataset = object() zs = np.array([[0.0, 1.0], [2.0, 3.0]], dtype=np.float32) cov_zs = np.zeros((2, 2, 2), dtype=np.float32) density = np.ones((8, 8), dtype=np.float32) bounds = np.array([[-1.0, 1.0], [-2.0, 2.0]], dtype=np.float32) contrasts = np.array([0.2, 0.8], dtype=np.float32)
class FakePO: def get_embedding_component(self, entry, key): captured.setdefault("embedding_calls", []).append((entry, key)) values = { ("latent_coords", 2): zs, ("latent_precision", 2): cov_zs, ("contrasts", 2): contrasts, } return values[(entry, key)]
def get(self, key): captured.setdefault("get_calls", []).append(key) values = { "dataset": fake_dataset, "density": density, } return values[key]
monkeypatch.setattr(output.ld, "compute_latent_space_bounds", lambda _zs: bounds) monkeypatch.setattr( output.embedding, "set_contrasts_in_cryos", lambda ds, vals: captured.setdefault("contrast_call", (ds, np.array(vals))), )
def fake_make_trajectory_plots(density_arg, zs_arg, cov_arg, *args, **kwargs): captured["make_args"] = (density_arg, zs_arg, cov_arg, args, kwargs) return "full_path", "subsampled_path"
monkeypatch.setattr(output, "make_trajectory_plots", fake_make_trajectory_plots)
result = output.make_trajectory_plots_from_results( pipeline_output=FakePO(), basis_size=2, output_folder=str(tmp_path) + "/", z_st=np.array([0.0, 0.0], dtype=np.float32), z_end=np.array([1.0, 1.0], dtype=np.float32), plot_llh=True, )
assert result == ("full_path", "subsampled_path") assert captured["contrast_call"][0] is fake_dataset np.testing.assert_array_equal(captured["contrast_call"][1], contrasts) np.testing.assert_array_equal(captured["make_args"][0], density) np.testing.assert_array_equal(captured["make_args"][1], zs) np.testing.assert_array_equal(captured["make_args"][2], cov_zs)
def test_cluster_kmeans_shapes_and_label_count(): rng = np.random.default_rng(0) z = rng.standard_normal((60, 2)).astype(np.float32) labels, centers = output.cluster_kmeans(z, K=3) assert labels.shape == (60,) assert centers.shape == (3, 2) assert set(labels) == {0, 1, 2}
def test_cluster_kmeans_reorder_false_skips_sort(): rng = np.random.default_rng(1) z = rng.standard_normal((40, 2)).astype(np.float32) labels, centers = output.cluster_kmeans(z, K=2, reorder=False) assert labels.shape == (40,) assert centers.shape == (2, 2)
def test_scatter_annotate_returns_figure_axes(): import matplotlib
matplotlib.use("Agg") import matplotlib.pyplot as plt
x = np.array([0.0, 1.0, 2.0, 3.0]) y = np.array([0.0, 1.0, 2.0, 3.0]) # annotate=False so no centers are needed fig, ax = output.scatter_annotate(x, y, annotate=False) assert hasattr(fig, "savefig") assert hasattr(ax, "scatter") plt.close(fig)
def test_scatter_annotate_with_centers_ind(): import matplotlib
matplotlib.use("Agg") import matplotlib.pyplot as plt
x = np.array([0.0, 1.0, 2.0, 3.0]) y = np.array([0.0, 1.0, 2.0, 3.0]) fig, ax = output.scatter_annotate(x, y, centers_ind=np.array([0, 2]), annotate=True) assert hasattr(fig, "savefig") plt.close(fig)
def test_scatter_annotate_with_explicit_centers(): import matplotlib
matplotlib.use("Agg") import matplotlib.pyplot as plt
x = np.linspace(0, 1, 20) y = np.linspace(0, 1, 20) centers = np.array([[0.25, 0.25], [0.75, 0.75]]) fig, ax = output.scatter_annotate(x, y, centers=centers, annotate=False) assert hasattr(fig, "savefig") plt.close(fig)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376import numpy as npimport pytestfrom types import SimpleNamespace
pytest.importorskip("jax")from recovar import utilsfrom recovar.output import output
pytestmark = pytest.mark.unit
def test_sum_over_other_matches_manual_reduction(): x = np.arange(24).reshape(2, 3, 4) out = output.sum_over_other(x, use_axis=[1]) expected = np.sum(x, axis=(0, 2)) np.testing.assert_array_equal(out, expected)
def test_half_slice_other_kept_axes(): density = np.arange(27).reshape(3, 3, 3) out = output.half_slice_other(density, axes=[0, 2]) np.testing.assert_array_equal(out, density[:, 1, :])
def test_slice_at_point_kept_axes(): density = np.arange(27).reshape(3, 3, 3) point = np.array([2, 0, 1]) out = output.slice_at_point(density, axes=[0, 2], point=point) np.testing.assert_array_equal(out, density[:, 0, :])
def test_resample_trajectory_uses_interpolated_indices(monkeypatch): monkeypatch.setattr(output, "get_resampled_distances", lambda _: np.array([0.0, 2.0, 4.0])) gt_vols = np.zeros((3, 8)) indices = output.resample_trajectory(gt_vols, n_vols_along_path=5) np.testing.assert_array_equal(indices, np.array([0, 0, 1, 2, 2]))
def test_pipeline_output_get_embedding_component_uses_particle_halfsets(tmp_path): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" model_dir.mkdir(parents=True)
params = { "version": "0.2", "input_args": SimpleNamespace(tilt_series=False, shared_contrast_across_tilts=True), } utils.pickle_dump(params, str(model_dir / "params.pkl")) utils.pickle_dump( { "latent_coords": {2: np.array([[0, 10], [1, 11], [2, 12], [3, 13]], dtype=np.float32)}, "latent_precision": {2: np.zeros((4, 2, 2), dtype=np.float32)}, "contrasts": {2: np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float32)}, }, str(model_dir / "embeddings.pkl"), ) # image halfsets != particle halfsets to make selection explicit. utils.pickle_dump( [np.array([1, 3], dtype=np.int32), np.array([0, 2], dtype=np.int32)], str(model_dir / "halfsets.pkl") ) utils.pickle_dump( [np.array([2, 0], dtype=np.int32), np.array([3, 1], dtype=np.int32)], str(model_dir / "particles_halfsets.pkl"), )
po = output.PipelineOutput(str(result_path)) zs_sel = po.get_embedding_component("latent_coords", 2) contrasts_sel = po.get_embedding_component("contrasts", 2) # Embeddings are returned in sorted-original order (dataset-local) np.testing.assert_array_equal(zs_sel, np.array([[0, 10], [1, 11], [2, 12], [3, 13]], dtype=np.float32)) np.testing.assert_array_equal(contrasts_sel, np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float32))
def test_pipeline_output_get_embedding_component_uses_image_halfsets_for_unshared_tilt_contrast(tmp_path): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" model_dir.mkdir(parents=True)
params = { "version": "0.2", "input_args": SimpleNamespace(tilt_series=True, shared_contrast_across_tilts=False), } utils.pickle_dump(params, str(model_dir / "params.pkl")) utils.pickle_dump( { "latent_coords": {2: np.array([[0, 10], [1, 11], [2, 12], [3, 13]], dtype=np.float32)}, "latent_precision": {2: np.zeros((4, 2, 2), dtype=np.float32)}, "contrasts": {2: np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float32)}, }, str(model_dir / "embeddings.pkl"), ) utils.pickle_dump( [np.array([1, 3], dtype=np.int32), np.array([0, 2], dtype=np.int32)], str(model_dir / "halfsets.pkl") ) utils.pickle_dump( [np.array([2, 0], dtype=np.int32), np.array([3, 1], dtype=np.int32)], str(model_dir / "particles_halfsets.pkl"), )
po = output.PipelineOutput(str(result_path)) contrasts_sel = po.get_embedding_component("contrasts", 2) # Sorted-original order regardless of tilt/shared settings np.testing.assert_array_equal(contrasts_sel, np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float32))
def test_pipeline_output_get_embedding_component_missing_shared_flag_defaults_to_particle_halfsets(tmp_path): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" model_dir.mkdir(parents=True)
# shared_contrast_across_tilts missing: should default to shared=True (particle-halfset path). params = {"version": "0.2", "input_args": SimpleNamespace(tilt_series=True)} utils.pickle_dump(params, str(model_dir / "params.pkl")) utils.pickle_dump( { "latent_coords": {2: np.zeros((4, 2), dtype=np.float32)}, "latent_precision": {2: np.zeros((4, 2, 2), dtype=np.float32)}, "contrasts": {2: np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float32)}, }, str(model_dir / "embeddings.pkl"), ) utils.pickle_dump( [np.array([1, 3], dtype=np.int32), np.array([0, 2], dtype=np.int32)], str(model_dir / "halfsets.pkl") ) utils.pickle_dump( [np.array([2, 0], dtype=np.int32), np.array([3, 1], dtype=np.int32)], str(model_dir / "particles_halfsets.pkl"), )
po = output.PipelineOutput(str(result_path)) contrasts_sel = po.get_embedding_component("contrasts", 2) np.testing.assert_array_equal(contrasts_sel, np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float32))
def test_pipeline_output_get_embedding_component_dict_input_args_unshared_tilt_uses_image_halfsets(tmp_path): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" model_dir.mkdir(parents=True)
params = { "version": "0.2", "input_args": {"tilt_series": True, "shared_contrast_across_tilts": False}, } utils.pickle_dump(params, str(model_dir / "params.pkl")) utils.pickle_dump( { "latent_coords": {2: np.zeros((4, 2), dtype=np.float32)}, "latent_precision": {2: np.zeros((4, 2, 2), dtype=np.float32)}, "contrasts": {2: np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float32)}, }, str(model_dir / "embeddings.pkl"), ) utils.pickle_dump( [np.array([1, 3], dtype=np.int32), np.array([0, 2], dtype=np.int32)], str(model_dir / "halfsets.pkl") ) utils.pickle_dump( [np.array([2, 0], dtype=np.int32), np.array([3, 1], dtype=np.int32)], str(model_dir / "particles_halfsets.pkl"), )
po = output.PipelineOutput(str(result_path)) contrasts_sel = po.get_embedding_component("contrasts", 2) np.testing.assert_array_equal(contrasts_sel, np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float32))
def test_pipeline_output_get_unsorted_embedding_component_returns_raw_component(tmp_path): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" model_dir.mkdir(parents=True)
params = {"version": "0.2", "input_args": SimpleNamespace(tilt_series=False)} utils.pickle_dump(params, str(model_dir / "params.pkl")) utils.pickle_dump( { "latent_coords": {4: np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32)}, "latent_precision": {4: np.zeros((2, 2, 2), dtype=np.float32)}, "contrasts": {4: np.array([0.1, 0.9], dtype=np.float32)}, }, str(model_dir / "embeddings.pkl"), )
po = output.PipelineOutput(str(result_path)) zs = po.get_unsorted_embedding_component("latent_coords", 4) np.testing.assert_array_equal(zs, np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))
def test_pipeline_output_get_u_real_uses_available_saved_eigenvectors(tmp_path, monkeypatch): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" vols_dir = result_path / "output" / "volumes" model_dir.mkdir(parents=True) vols_dir.mkdir(parents=True)
utils.pickle_dump({"version": "0", "volume_shape": (2, 2, 2)}, str(model_dir / "params.pkl")) for i in range(3): (vols_dir / f"eigen_pos{i:04d}.mrc").touch()
calls = []
def _fake_load_mrc(path): calls.append(path) idx = int(path.split("eigen_pos")[-1].split(".mrc")[0]) return np.full((2, 2, 2), idx, dtype=np.float32)
monkeypatch.setattr(output.utils, "load_mrc", _fake_load_mrc)
po = output.PipelineOutput(str(result_path)) u_real = po.get("u_real") assert u_real.shape == (3, 2, 2, 2) assert len(calls) == 3 np.testing.assert_array_equal(u_real[0], np.zeros((2, 2, 2), dtype=np.float32)) np.testing.assert_array_equal(u_real[2], np.full((2, 2, 2), 2, dtype=np.float32))
def test_pipeline_output_get_u_real_method_respects_requested_n_pcs(tmp_path, monkeypatch): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" vols_dir = result_path / "output" / "volumes" model_dir.mkdir(parents=True) vols_dir.mkdir(parents=True)
utils.pickle_dump({"version": "0", "volume_shape": (2, 2, 2)}, str(model_dir / "params.pkl")) for i in range(4): (vols_dir / f"eigen_pos{i:04d}.mrc").touch()
calls = []
def _fake_load_mrc(path): calls.append(path) return np.ones((2, 2, 2), dtype=np.float32)
monkeypatch.setattr(output.utils, "load_mrc", _fake_load_mrc)
po = output.PipelineOutput(str(result_path)) u_real = po.get_u_real(2) assert u_real.shape == (2, 2, 2, 2) assert len(calls) == 2
def test_pipeline_output_get_u_real_caps_to_50_saved_eigenvectors(tmp_path, monkeypatch): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" vols_dir = result_path / "output" / "volumes" model_dir.mkdir(parents=True) vols_dir.mkdir(parents=True)
utils.pickle_dump({"version": "0", "volume_shape": (2, 2, 2)}, str(model_dir / "params.pkl")) for i in range(55): (vols_dir / f"eigen_pos{i:04d}.mrc").touch()
calls = [] monkeypatch.setattr( output.utils, "load_mrc", lambda path: calls.append(path) or np.zeros((2, 2, 2), dtype=np.float32), )
po = output.PipelineOutput(str(result_path)) u_real = po.get("u_real") assert u_real.shape == (50, 2, 2, 2) assert len(calls) == 50
def test_pipeline_output_get_u_real_raises_when_no_eigenvectors_saved(tmp_path): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" vols_dir = result_path / "output" / "volumes" model_dir.mkdir(parents=True) vols_dir.mkdir(parents=True)
utils.pickle_dump({"version": "0", "volume_shape": (2, 2, 2)}, str(model_dir / "params.pkl"))
po = output.PipelineOutput(str(result_path)) with pytest.raises(ValueError, match="No eigenvector volumes found"): po.get("u_real")
def test_pipeline_output_get_u_real_handles_sparse_saved_indices(tmp_path, monkeypatch): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" vols_dir = result_path / "output" / "volumes" model_dir.mkdir(parents=True) vols_dir.mkdir(parents=True)
utils.pickle_dump({"version": "0", "volume_shape": (2, 2, 2)}, str(model_dir / "params.pkl")) # Missing 0001 intentionally. (vols_dir / "eigen_pos0000.mrc").touch() (vols_dir / "eigen_pos0002.mrc").touch()
calls = []
def _fake_load_mrc(path): calls.append(path) idx = int(path.split("eigen_pos")[-1].split(".mrc")[0]) return np.full((2, 2, 2), idx, dtype=np.float32)
monkeypatch.setattr(output.utils, "load_mrc", _fake_load_mrc)
po = output.PipelineOutput(str(result_path)) u_real = po.get("u_real") assert u_real.shape == (2, 2, 2, 2) assert len(calls) == 2 assert calls[0].endswith("eigen_pos0000.mrc") assert calls[1].endswith("eigen_pos0002.mrc") np.testing.assert_array_equal(u_real[0], np.zeros((2, 2, 2), dtype=np.float32)) np.testing.assert_array_equal(u_real[1], np.full((2, 2, 2), 2, dtype=np.float32))
def test_pipeline_output_get_u_frequency_space_shape_for_sparse_indices(tmp_path, monkeypatch): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" vols_dir = result_path / "output" / "volumes" model_dir.mkdir(parents=True) vols_dir.mkdir(parents=True)
utils.pickle_dump({"version": "0", "volume_shape": (2, 2, 2)}, str(model_dir / "params.pkl")) (vols_dir / "eigen_pos0001.mrc").touch() (vols_dir / "eigen_pos0003.mrc").touch()
monkeypatch.setattr(output.utils, "load_mrc", lambda _path: np.ones((2, 2, 2), dtype=np.float32)) seen_shapes = []
def _fake_get_dft3(u): seen_shapes.append(np.asarray(u).shape) return np.asarray(u, dtype=np.float32).astype(np.complex64) * (1 + 1j)
monkeypatch.setattr(output.fourier_transform_utils, "get_dft3", _fake_get_dft3)
po = output.PipelineOutput(str(result_path)) u = po.get("u") assert u.shape == (2, 8) assert np.iscomplexobj(u) # Ensure transform is executed per volume (streaming path), not on a stacked tensor. assert seen_shapes == [(2, 2, 2), (2, 2, 2)]
def test_pipeline_output_get_u_streaming_matches_expected_per_volume_content(tmp_path, monkeypatch): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" vols_dir = result_path / "output" / "volumes" model_dir.mkdir(parents=True) vols_dir.mkdir(parents=True)
utils.pickle_dump({"version": "0", "volume_shape": (2, 2, 2)}, str(model_dir / "params.pkl")) (vols_dir / "eigen_pos0000.mrc").touch() (vols_dir / "eigen_pos0002.mrc").touch()
def _fake_load_mrc(path): idx = int(path.split("eigen_pos")[-1].split(".mrc")[0]) return np.full((2, 2, 2), idx, dtype=np.float32)
monkeypatch.setattr(output.utils, "load_mrc", _fake_load_mrc) monkeypatch.setattr( output.fourier_transform_utils, "get_dft3", lambda u: np.asarray(u, dtype=np.float32).astype(np.complex64), )
po = output.PipelineOutput(str(result_path)) u = po.get("u") assert u.shape == (2, 8) np.testing.assert_array_equal(u[0], np.zeros(8, dtype=np.complex64)) np.testing.assert_array_equal(u[1], np.full(8, 2 + 0j, dtype=np.complex64))
def test_pipeline_output_get_u_real_rejects_nonpositive_n_pcs(tmp_path): result_path = tmp_path / "pipeline_output" model_dir = result_path / "model" vols_dir = result_path / "output" / "volumes" model_dir.mkdir(parents=True) vols_dir.mkdir(parents=True) utils.pickle_dump({"version": "0", "volume_shape": (2, 2, 2)}, str(model_dir / "params.pkl")) (vols_dir / "eigen_pos0000.mrc").touch() po = output.PipelineOutput(str(result_path)) with pytest.raises(ValueError, match="n_pcs must be positive"): po.get_u_real(0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""Tests for recovar.output.output_paths — path management for pipeline output."""
import os
import pytest
from recovar.output.output_paths import ( AnalysisPaths, ResultPaths, eigenvector_filename, variance_filename,)
pytestmark = pytest.mark.unit
# ---------------------------------------------------------------------------# Module-level helpers# ---------------------------------------------------------------------------
def test_eigenvector_filename_zero_padded(): assert eigenvector_filename(0) == "eigen_pos0000.mrc" assert eigenvector_filename(5) == "eigen_pos0005.mrc" assert eigenvector_filename(123) == "eigen_pos0123.mrc"
def test_variance_filename(): assert variance_filename(4) == "variance4.mrc" assert variance_filename(20) == "variance20.mrc"
# ---------------------------------------------------------------------------# ResultPaths# ---------------------------------------------------------------------------
class TestResultPaths: def test_directory_properties(self): rp = ResultPaths("/out") assert rp.model_dir == os.path.join("/out", "model") assert rp.output_dir == os.path.join("/out", "output") assert rp.volumes_dir == os.path.join("/out", "output", "volumes") assert rp.plots_dir == os.path.join("/out", "output", "plots")
def test_model_file_paths(self): rp = ResultPaths("/out") assert rp.params.endswith("model/params.pkl") assert rp.embeddings.endswith("model/embeddings.pkl") assert rp.covariance_cols.endswith("model/covariance_cols.pkl") assert rp.halfsets.endswith("model/halfsets.pkl") assert rp.metadata.endswith("model/metadata.json")
def test_volume_file_paths(self): rp = ResultPaths("/out") assert rp.mean_volume.endswith("volumes/mean.mrc") assert rp.mean_filtered.endswith("volumes/mean_filt.mrc") assert rp.mask_volume.endswith("volumes/mask.mrc")
def test_eigenvector_path(self): rp = ResultPaths("/out") path = rp.eigenvector(3) assert path.endswith("volumes/eigen_pos0003.mrc")
def test_variance_path(self): rp = ResultPaths("/out") path = rp.variance(10) assert path.endswith("volumes/variance10.mrc")
def test_analysis_dir(self): rp = ResultPaths("/out") assert rp.analysis_dir(20) == os.path.join("/out", "analysis_20")
def test_command_txt_and_run_log(self): rp = ResultPaths("/out") assert rp.command_txt == os.path.join("/out", "command.txt") assert rp.run_log == os.path.join("/out", "run.log")
def test_ensure_dirs(self, tmp_path): rp = ResultPaths(str(tmp_path / "pipeline_out")) rp.ensure_dirs() assert os.path.isdir(rp.model_dir) assert os.path.isdir(rp.volumes_dir) assert os.path.isdir(rp.plots_dir)
def test_ensure_model_dir(self, tmp_path): rp = ResultPaths(str(tmp_path / "pipeline_out2")) rp.ensure_model_dir() assert os.path.isdir(rp.model_dir) assert not os.path.isdir(rp.volumes_dir)
def test_ensure_volumes_dir(self, tmp_path): rp = ResultPaths(str(tmp_path / "pipeline_out3")) rp.ensure_volumes_dir() assert os.path.isdir(rp.volumes_dir)
# ---------------------------------------------------------------------------# AnalysisPaths# ---------------------------------------------------------------------------
class TestAnalysisPaths: def test_kmeans_dir(self): ap = AnalysisPaths("/analysis_4") assert ap.kmeans_dir == os.path.join("/analysis_4", "kmeans")
def test_plots_dir(self): ap = AnalysisPaths("/analysis_4") assert ap.plots_dir == os.path.join("/analysis_4", "plots")
def test_traj_dir(self): ap = AnalysisPaths("/analysis_4") assert ap.traj_dir(1) == os.path.join("/analysis_4", "traj001") assert ap.traj_dir(10) == os.path.join("/analysis_4", "traj010")
def test_vol_stem(self): assert AnalysisPaths.vol_stem("center", 0) == "center000" assert AnalysisPaths.vol_stem("state", 5) == "state005"
def test_vol_filename(self): assert AnalysisPaths.vol_filename("center", 1) == "center001.mrc"
def test_halfmap_filename(self): assert AnalysisPaths.halfmap_filename("center", 1, 1) == "center001_half1_unfil.mrc" assert AnalysisPaths.halfmap_filename("center", 1, 2) == "center001_half2_unfil.mrc"
def test_diagnostics_subdir(self): assert AnalysisPaths.diagnostics_subdir("center", 0) == os.path.join("diagnostics", "center000")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138import osimport subprocessimport sysimport tarfileimport tomllibimport zipfilefrom pathlib import Path
import pytest
from setup_helpers import remove_stale_fast_marching_build_artifacts
pytestmark = pytest.mark.unit
REPO_ROOT = Path(__file__).resolve().parents[2]
def _load_toml(path: Path) -> dict: return tomllib.loads(path.read_text(encoding="utf-8"))
def test_psutil_declared_for_runtime_installs(): pyproject = _load_toml(REPO_ROOT / "pyproject.toml") dependencies = pyproject["project"]["dependencies"]
assert any(dep.startswith("psutil") for dep in dependencies)
def test_psutil_declared_for_pixi_dev_env(): pixi = _load_toml(REPO_ROOT / "pixi.toml") dependencies = pixi["dependencies"]
assert "psutil" in dependencies
def test_gpu_extra_matches_cuda_alias(): pyproject = _load_toml(REPO_ROOT / "pyproject.toml") extras = pyproject["project"]["optional-dependencies"]
assert extras["gpu"] == extras["cuda"]
def test_gpu_flexible_extra_matches_cuda_flexible_alias(): pyproject = _load_toml(REPO_ROOT / "pyproject.toml") extras = pyproject["project"]["optional-dependencies"]
assert extras["gpu-flexible"] == extras["cuda-flexible"]
def test_all_extra_prefers_gpu_alias(): pyproject = _load_toml(REPO_ROOT / "pyproject.toml") extras = pyproject["project"]["optional-dependencies"]
assert extras["all"] == ["recovar[gpu,interactive,gui,dev]"]
def test_pixi_declares_build_tools_for_optional_native_extensions(): pixi = _load_toml(REPO_ROOT / "pixi.toml") dependencies = pixi["dependencies"]
assert "cxx-compiler" in dependencies assert "make" in dependencies
def test_remove_stale_fast_marching_build_artifacts_only_removes_legacy_root_entries(tmp_path): build_lib = tmp_path / "build-lib" build_temp = tmp_path / "build-temp" stale_cpp = build_lib / "recovar" / "_fast_marching_native.cpp" stale_so = build_lib / "recovar" / "_fast_marching_native.cpython-311-x86_64-linux-gnu.so" keep_cpp = build_lib / "recovar" / "trajectory" / "_fast_marching_native.cpp" stale_obj = build_temp / "recovar" / "_fast_marching_native.o"
for path in (stale_cpp, stale_so, keep_cpp, stale_obj): path.parent.mkdir(parents=True, exist_ok=True) path.write_text("stub")
removed = remove_stale_fast_marching_build_artifacts(build_lib=build_lib, build_temp=build_temp)
assert set(removed) == {stale_cpp, stale_so, stale_obj} assert not stale_cpp.exists() assert not stale_so.exists() assert not stale_obj.exists() assert keep_cpp.exists()
@pytest.fixture(scope="module")def built_package_artifacts(tmp_path_factory): dist_dir = tmp_path_factory.mktemp("package-dist") env = dict(os.environ, PYTHONNOUSERSITE="1")
subprocess.run( [sys.executable, "setup.py", "sdist", "--dist-dir", str(dist_dir)], cwd=REPO_ROOT, env=env, check=True, capture_output=True, text=True, ) subprocess.run( [sys.executable, "-m", "pip", "wheel", ".", "--no-deps", "--no-build-isolation", "-w", str(dist_dir)], cwd=REPO_ROOT, env=env, check=True, capture_output=True, text=True, )
sdist = next(dist_dir.glob("*.tar.gz")) wheel = next(dist_dir.glob("*.whl")) return sdist, wheel
def test_sdist_and_wheel_include_cuda_build_files(built_package_artifacts): sdist, wheel = built_package_artifacts
with tarfile.open(sdist, "r:gz") as tf: sdist_names = set(tf.getnames())
with zipfile.ZipFile(wheel) as zf: wheel_names = set(zf.namelist())
assert any(name.endswith("/recovar/cuda/Makefile") for name in sdist_names) assert any(name.endswith("/recovar/cuda/cuda_backproject.cu") for name in sdist_names) assert any(name.endswith("/setup_helpers.py") for name in sdist_names)
assert "recovar/cuda/Makefile" in wheel_names assert "recovar/cuda/cuda_backproject.cu" in wheel_names
def test_wheel_excludes_legacy_root_fast_marching_entries(built_package_artifacts): _, wheel = built_package_artifacts
with zipfile.ZipFile(wheel) as zf: wheel_names = set(zf.namelist())
assert any(name.startswith("recovar/trajectory/_fast_marching_native") for name in wheel_names) assert not any(name.startswith("recovar/_fast_marching_native") for name in wheel_names)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import numpy as npimport pytest
pytest.importorskip("jax")
import recovar.core.padding as padding
pytestmark = pytest.mark.unit
def test_pad_unpad_images_spatial_roundtrip(): images = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4) padded = np.asarray(padding.pad_images_spatial_domain(images, padding=2)) assert padded.shape == (2, 6, 6) unpadded = np.asarray(padding.unpad_images_spatial_domain(padded, padding=2)) np.testing.assert_allclose(unpadded, images)
def test_pad_unpad_volume_spatial_roundtrip(): vol = np.arange(4 * 4 * 4, dtype=np.float32).reshape(4, 4, 4) padded = np.asarray(padding.pad_volume_spatial_domain(vol, padding=2)) assert padded.shape == (6, 6, 6) unpadded = np.asarray(padding.unpad_volume_spatial_domain(padded, padding=2)) np.testing.assert_allclose(unpadded, vol)
def test_pad_unpad_images_fourier_roundtrip(): rng = np.random.default_rng(0) images = rng.normal(size=(3, 4, 4)).astype(np.float32) ft_padded = np.asarray(padding.pad_images_fourier_domain(images, image_shape=(4, 4), padding=2)) assert ft_padded.shape == (3, 36) ft_unpadded = np.asarray(padding.unpad_images_fourier_domain(ft_padded, padded_image_shape=(6, 6), padding=2)) assert ft_unpadded.shape == (3, 16)
def test_unpad_volume_fourier_domain_shape(): rng = np.random.default_rng(1) vol = rng.normal(size=(6, 6, 6)).astype(np.float32) out = np.asarray(padding.unpad_volume_fourier_domain(vol.reshape(-1), padded_image_shape=(6, 6, 6), padding=2)) assert out.shape == (4 * 4 * 4,)
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
import jaximport jax.numpy as jnp
@pytest.mark.gpudef test_pad_unpad_images_spatial_gpu(gpu_device): images = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4)
cpu_padded = np.asarray(padding.pad_images_spatial_domain(images, padding=2)) cpu_unpadded = np.asarray(padding.unpad_images_spatial_domain(cpu_padded, padding=2))
with jax.default_device(gpu_device): images_g = jax.device_put(jnp.array(images), gpu_device) gpu_padded = np.asarray(padding.pad_images_spatial_domain(images_g, padding=2)) gpu_unpadded = np.asarray(padding.unpad_images_spatial_domain(gpu_padded, padding=2))
np.testing.assert_allclose(cpu_padded, gpu_padded, atol=1e-5, rtol=1e-5) np.testing.assert_allclose(cpu_unpadded, gpu_unpadded, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_pad_unpad_volume_spatial_gpu(gpu_device): vol = np.arange(4 * 4 * 4, dtype=np.float32).reshape(4, 4, 4)
cpu_padded = np.asarray(padding.pad_volume_spatial_domain(vol, padding=2)) cpu_unpadded = np.asarray(padding.unpad_volume_spatial_domain(cpu_padded, padding=2))
with jax.default_device(gpu_device): vol_g = jax.device_put(jnp.array(vol), gpu_device) gpu_padded = np.asarray(padding.pad_volume_spatial_domain(vol_g, padding=2)) gpu_unpadded = np.asarray(padding.unpad_volume_spatial_domain(gpu_padded, padding=2))
np.testing.assert_allclose(cpu_padded, gpu_padded, atol=1e-5, rtol=1e-5) np.testing.assert_allclose(cpu_unpadded, gpu_unpadded, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_pad_images_fourier_domain_gpu(gpu_device): rng = np.random.default_rng(0) images = rng.normal(size=(3, 4, 4)).astype(np.float32)
cpu_ft_padded = np.asarray(padding.pad_images_fourier_domain(images, image_shape=(4, 4), padding=2))
with jax.default_device(gpu_device): images_g = jax.device_put(jnp.array(images), gpu_device) gpu_ft_padded = np.asarray(padding.pad_images_fourier_domain(images_g, image_shape=(4, 4), padding=2))
np.testing.assert_allclose(cpu_ft_padded, gpu_ft_padded, atol=1e-4, rtol=1e-4)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391"""Tests for recovar.commands.parse_relion5_tomo."""
import osimport textwrap
import numpy as npimport pandas as pdimport pytestfrom scipy.spatial.transform import Rotation as R
from recovar.commands.parse_relion5_tomo import ( Tomogram, _parse_visible_frames, convert,)from recovar.data_io.starfile import StarFile, read_star
pytestmark = pytest.mark.unit
# ---------------------------------------------------------------------------# Fixtures: synthetic RELION5 star files# ---------------------------------------------------------------------------
def _write_text(path, text): with open(path, "w") as f: f.write(textwrap.dedent(text))
def _make_tilt_series_star(path, n_tilts=5): """Write a minimal per-tilt-series .star file.""" header = textwrap.dedent("""\ # version 50001
data_my_ts_001
loop_ _rlnMicrographName #1 _rlnTomoNominalStageTiltAngle #2 _rlnMicrographPreExposure #3 _rlnTomoXTilt #4 _rlnTomoYTilt #5 _rlnTomoZRot #6 _rlnTomoXShiftAngst #7 _rlnTomoYShiftAngst #8 _rlnDefocusU #9 _rlnDefocusV #10 _rlnDefocusAngle #11 _rlnCtfScalefactor #12 """) rows = [] angles = np.linspace(-60, 60, n_tilts) for i, angle in enumerate(angles): dose = (i + 1) * 3.0 dfu = 30000.0 + i * 100 dfv = 31000.0 + i * 100 rows.append( f"mic_{i:03d}.mrc {angle:.3f} {dose:.1f} " f"{angle:.3f} 0.0 {80.0 + i:.3f} " f"{i * 10.0:.1f} {i * -5.0:.1f} " f"{dfu:.1f} {dfv:.1f} 45.0 {1.0 + i * 0.1:.3f}" ) with open(path, "w") as f: f.write(header) f.write("\n".join(rows) + "\n")
def _make_tomograms_star(path, ts_star_relpath, n_tomos=1): """Write a minimal tomograms.star.""" header = textwrap.dedent("""\ # version 50001
data_global
loop_ _rlnTomoName #1 _rlnTomoTiltSeriesStarFile #2 _rlnTomoTiltSeriesPixelSize #3 _rlnTomoHand #4 _rlnTomoSizeX #5 _rlnTomoSizeY #6 """) rows = [] for i in range(n_tomos): name = f"tomo_{i:03d}" if n_tomos > 1 else "tomo_001" rows.append(f"{name} {ts_star_relpath} 1.5 -1 4096 4096") with open(path, "w") as f: f.write(header) f.write("\n".join(rows) + "\n")
def _make_particles_star(path, n_particles=3, n_tilts=5, tomo_name="tomo_001", has_subtomo_rot=False): """Write a minimal RELION5 particles.star with optics + particles blocks.""" visible = "[" + ",".join(["1"] * n_tilts) + "]"
optics_header = textwrap.dedent("""\ # version 50001
data_optics
loop_ _rlnVoltage #1 _rlnSphericalAberration #2 _rlnAmplitudeContrast #3 _rlnOpticsGroup #4 _rlnOpticsGroupName #5 _rlnImagePixelSize #6 _rlnImageSize #7 _rlnImageDimensionality #8 300.0 2.7 0.1 1 opticsGroup1 1.5 128 2 """)
particles_cols = [ "_rlnTomoName", "_rlnCenteredCoordinateXAngst", "_rlnCenteredCoordinateYAngst", "_rlnCenteredCoordinateZAngst", "_rlnOpticsGroup", "_rlnTomoParticleName", "_rlnImageName", "_rlnAngleRot", "_rlnAngleTilt", "_rlnAnglePsi", "_rlnRandomSubset", "_rlnTomoVisibleFrames", ] if has_subtomo_rot: particles_cols += [ "_rlnTomoSubtomogramRot", "_rlnTomoSubtomogramTilt", "_rlnTomoSubtomogramPsi", ]
particles_header = "\n# version 50001\n\ndata_particles\n\nloop_\n" for i, col in enumerate(particles_cols, 1): particles_header += f"{col} #{i}\n"
rng = np.random.RandomState(42) rows = [] for p in range(n_particles): x = rng.uniform(-500, 500) y = rng.uniform(-500, 500) z = rng.uniform(-200, 200) rot, tilt, psi = rng.uniform(-180, 180, 3) subset = (p % 2) + 1 name = f"{tomo_name}/{p + 1}" img = f"Extract/Subtomograms/{tomo_name}/{p + 1}_stack2d.mrcs" row = f"{tomo_name} {x:.3f} {y:.3f} {z:.3f} 1 {name} {img} {rot:.3f} {tilt:.3f} {psi:.3f} {subset} {visible}" if has_subtomo_rot: srot, stilt, spsi = rng.uniform(-10, 10, 3) row += f" {srot:.3f} {stilt:.3f} {spsi:.3f}" rows.append(row)
with open(path, "w") as f: f.write(optics_header) f.write(particles_header) f.write("\n".join(rows) + "\n")
@pytest.fixturedef relion5_data(tmp_path): """Create a full set of synthetic RELION5 tomo star files.""" n_tilts = 5 n_particles = 4
# Tilt series star file ts_dir = tmp_path / "Polish" / "job001" / "tilt_series" ts_dir.mkdir(parents=True) ts_star = ts_dir / "tomo_001.star" _make_tilt_series_star(str(ts_star), n_tilts=n_tilts)
# Tomograms.star tomo_dir = tmp_path / "Polish" / "job001" tomo_star = tomo_dir / "tomograms.star" _make_tomograms_star( str(tomo_star), ts_star_relpath="Polish/job001/tilt_series/tomo_001.star", )
# Particles.star extract_dir = tmp_path / "Extract" / "job002" extract_dir.mkdir(parents=True) particles_star = extract_dir / "particles.star" _make_particles_star(str(particles_star), n_particles=n_particles, n_tilts=n_tilts)
return { "root": tmp_path, "tomograms": str(tomo_star), "particles": str(particles_star), "n_tilts": n_tilts, "n_particles": n_particles, }
# ---------------------------------------------------------------------------# Tests: Tomogram class# ---------------------------------------------------------------------------
class TestTomogram: def test_local_defocus_at_origin_equals_global(self): """At the origin, depth offset is zero so local == global defocus.""" tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([25000.0]), defocus_v=np.array([26000.0]), defocus_angle=np.array([45.0]), x_tilts=np.array([30.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), hand=1, ) u, v, a = tomo.local_defocus(0, np.array([0.0, 0.0, 0.0])) assert u == pytest.approx(25000.0) assert v == pytest.approx(26000.0) assert a == pytest.approx(45.0)
def test_local_defocus_offset_nonzero_for_shifted_particle(self): """Particle displaced in Z should have depth-dependent defocus offset.""" tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([30000.0]), defocus_v=np.array([30000.0]), defocus_angle=np.array([0.0]), x_tilts=np.array([45.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), hand=1, ) u_origin, _, _ = tomo.local_defocus(0, np.array([0.0, 0.0, 0.0])) u_shifted, _, _ = tomo.local_defocus(0, np.array([0.0, 0.0, 500.0])) # With 45-degree tilt and Z=500, there should be a significant offset assert abs(u_shifted - u_origin) > 100
def test_expand_particles_batch_row_count(self): n = 4 tomo = Tomogram( pixel_size=1.0, defocus_u=np.zeros(n), defocus_v=np.zeros(n), defocus_angle=np.zeros(n), x_tilts=np.linspace(-40, 40, n), y_tilts=np.zeros(n), z_rots=np.zeros(n), x_shifts=np.zeros(n), y_shifts=np.zeros(n), hand=1, ) # Build a minimal tilt_df tilt_df = pd.DataFrame( { "_rlnMicrographName": [f"mic_{i}.mrc" for i in range(n)], "_rlnMicrographPreExposure": [str(i * 3.0) for i in range(n)], "_rlnCtfScalefactor": ["1.0"] * n, "_rlnTomoNominalStageTiltAngle": [str(a) for a in np.linspace(-40, 40, n)], } ) base_rot = R.from_euler("ZYZ", [30, 60, 90], degrees=True) df = tomo.expand_particles_batch( np.array([[100.0, 200.0, -50.0]]), ["stack.mrcs"], tilt_df, ["particle/1"], base_rot, np.array([1]), ) assert len(df) == n assert "_rlnImageName" in df.columns assert "_rlnAngleRot" in df.columns # Image names should be 000001@stack.mrcs, 000002@stack.mrcs, ... assert df["_rlnImageName"].iloc[0] == "000001@stack.mrcs" assert df["_rlnImageName"].iloc[-1] == f"{n:06d}@stack.mrcs"
def test_expand_particles_batch_without_orientation(self): """If base_orientation is None, angles should be zero.""" n = 3 tomo = Tomogram( pixel_size=1.0, defocus_u=np.zeros(n), defocus_v=np.zeros(n), defocus_angle=np.zeros(n), x_tilts=np.array([0.0, 20.0, -20.0]), y_tilts=np.zeros(n), z_rots=np.zeros(n), x_shifts=np.zeros(n), y_shifts=np.zeros(n), hand=1, ) tilt_df = pd.DataFrame( { "_rlnMicrographName": [f"mic_{i}.mrc" for i in range(n)], "_rlnMicrographPreExposure": ["3.0", "6.0", "9.0"], "_rlnCtfScalefactor": ["1.0"] * n, "_rlnTomoNominalStageTiltAngle": ["0.0", "20.0", "-20.0"], } ) df = tomo.expand_particles_batch( np.array([[0.0, 0.0, 0.0]]), ["stack.mrcs"], tilt_df, ["p/1"], None, np.array([1]), ) np.testing.assert_array_equal(df["_rlnAngleRot"].values, 0.0) np.testing.assert_array_equal(df["_rlnAngleTilt"].values, 0.0) np.testing.assert_array_equal(df["_rlnAnglePsi"].values, 0.0)
# ---------------------------------------------------------------------------# Tests: visible frames parsing# ---------------------------------------------------------------------------
class TestParseVisibleFrames: def test_all_visible(self): assert _parse_visible_frames("[1,1,1,1]") == [0, 1, 2, 3]
def test_some_invisible(self): assert _parse_visible_frames("[1,0,1,0,1]") == [0, 2, 4]
def test_none_visible(self): assert _parse_visible_frames("[0,0,0]") == []
# ---------------------------------------------------------------------------# Tests: end-to-end conversion# ---------------------------------------------------------------------------
class TestConvert: def test_basic_conversion(self, relion5_data, tmp_path): output = str(tmp_path / "output.star") convert( relion5_data["tomograms"], relion5_data["particles"], output, ) assert os.path.isfile(output)
# Parse output df, optics = read_star(output) assert optics is not None
# Check dimensions n_expected = relion5_data["n_particles"] * relion5_data["n_tilts"] assert len(df) == n_expected
# Check optics fields assert "_rlnImagePixelSize" in optics.columns assert "_rlnVoltage" in optics.columns assert optics["_rlnImageSize"].values[0] == "128" assert optics["_rlnImagePixelSize"].values[0] == "1.5"
def test_output_has_required_columns(self, relion5_data, tmp_path): output = str(tmp_path / "output.star") convert( relion5_data["tomograms"], relion5_data["particles"], output, ) df, _ = read_star(output) required = [ "_rlnDefocusU", "_rlnDefocusV", "_rlnDefocusAngle", "_rlnImageName", "_rlnTiltName", "_rlnGroupName", "_rlnAngleRot", "_rlnAngleTilt", "_rlnAnglePsi", "_rlnOriginXAngst", "_rlnOriginYAngst", "_rlnCtfScalefactor", "_rlnRandomSubset", "_rlnMicrographPreExposure", "_rlnOpticsGroup", ] for col in required: assert col in df.columns, f"Missing column: {col}"
np.testing.assert_array_equal(df["_rlnTiltName"], df["_rlnMicrographName"])
def test_dose_sorted_within_groups(self, relion5_data, tmp_path): output = str(tmp_path / "output.star") convert( relion5_data["tomograms"], relion5_data["particles"], output, ) df, _ = read_star(output) groups = df["_rlnGroupName"].unique() for group in groups: mask = df["_rlnGroupName"] == group doses = df[mask]["_rlnMicrographPreExposure"].values.astype(float) assert np.all(np.diff(doses) >= 0), f"Doses not sorted for group {group}: {doses}"
def test_random_subset_preserved(self, relion5_data, tmp_path): output = str(tmp_path / "output.star") convert( relion5_data["tomograms"], relion5_data["particles"], output, ) df, _ = read_star(output) subsets = df["_rlnRandomSubset"].values.astype(int) assert set(subsets) == {1, 2}
def test_group_names_match_particles(self, relion5_data, tmp_path): output = str(tmp_path / "output.star") convert( relion5_data["tomograms"], relion5_data["particles"], output, ) df, _ = read_star(output) groups = sorted(df["_rlnGroupName"].unique()) expected = sorted([f"tomo_001/{i + 1}" for i in range(relion5_data["n_particles"])]) assert groups == expected
def test_image_names_format(self, relion5_data, tmp_path): output = str(tmp_path / "output.star") convert( relion5_data["tomograms"], relion5_data["particles"], output, ) df, _ = read_star(output) for name in df["_rlnImageName"].values[:10]: idx, stack = name.split("@") assert len(idx) == 6 assert int(idx) >= 1 assert stack.endswith(".mrcs")
def test_loadable_as_starfile(self, relion5_data, tmp_path): """Output should be loadable by RECOVAR's StarFile class.""" output = str(tmp_path / "output.star") convert( relion5_data["tomograms"], relion5_data["particles"], output, ) sf = StarFile.load(output) assert sf.has_optics assert sf.apix is not None assert sf.resolution is not None assert len(sf) == relion5_data["n_particles"] * relion5_data["n_tilts"]
def test_with_subtomogram_orientation(self, tmp_path): """Particles with rlnTomoSubtomogramRot/Tilt/Psi should produce different angles than without.""" n_tilts = 3
ts_dir = tmp_path / "ts" ts_dir.mkdir() _make_tilt_series_star(str(ts_dir / "ts.star"), n_tilts=n_tilts)
tomo_star = tmp_path / "tomos.star" _make_tomograms_star(str(tomo_star), "ts/ts.star")
# Without subtomo orientation p1 = tmp_path / "p1.star" _make_particles_star(str(p1), n_particles=1, n_tilts=n_tilts, has_subtomo_rot=False) out1 = str(tmp_path / "out1.star") convert(str(tomo_star), str(p1), out1)
# With subtomo orientation p2 = tmp_path / "p2.star" _make_particles_star(str(p2), n_particles=1, n_tilts=n_tilts, has_subtomo_rot=True) out2 = str(tmp_path / "out2.star") convert(str(tomo_star), str(p2), out2)
df1, _ = read_star(out1) df2, _ = read_star(out2)
# Angles should differ (subtomo orientation != identity) rot1 = df1["_rlnAngleRot"].values.astype(float) rot2 = df2["_rlnAngleRot"].values.astype(float) assert not np.allclose(rot1, rot2, atol=0.1), "Subtomogram orientation should produce different angles"
def test_partial_visible_frames(self, tmp_path): """Particles with some invisible tilts should produce fewer rows.""" n_tilts = 5
ts_dir = tmp_path / "ts" ts_dir.mkdir() _make_tilt_series_star(str(ts_dir / "ts.star"), n_tilts=n_tilts)
tomo_star = tmp_path / "tomos.star" _make_tomograms_star(str(tomo_star), "ts/ts.star")
# Write particles with partial visible frames visible = "[1,0,1,0,1]" # only 3 of 5 visible particles_text = f"""\ # version 50001
data_optics
loop_ _rlnVoltage #1 _rlnSphericalAberration #2 _rlnAmplitudeContrast #3 _rlnOpticsGroup #4 _rlnOpticsGroupName #5 _rlnImagePixelSize #6 _rlnImageSize #7 _rlnImageDimensionality #8 300.0 2.7 0.1 1 opticsGroup1 1.5 128 2
# version 50001
data_particles
loop_ _rlnTomoName #1 _rlnCenteredCoordinateXAngst #2 _rlnCenteredCoordinateYAngst #3 _rlnCenteredCoordinateZAngst #4 _rlnOpticsGroup #5 _rlnTomoParticleName #6 _rlnImageName #7 _rlnAngleRot #8 _rlnAngleTilt #9 _rlnAnglePsi #10 _rlnRandomSubset #11 _rlnTomoVisibleFrames #12 tomo_001 100.0 200.0 50.0 1 tomo_001/1 Extract/tomo_001/1_stack2d.mrcs 10.0 20.0 30.0 1 {visible} """ p_star = tmp_path / "particles.star" _write_text(str(p_star), particles_text)
output = str(tmp_path / "output.star") convert(str(tomo_star), str(p_star), output)
df, _ = read_star(output) assert len(df) == 3 # only 3 visible tilts
def test_project_root_resolution(self, tmp_path): """Tilt-series star paths relative to project root should be resolved.""" n_tilts = 3
# Create nested structure project = tmp_path / "relion_project" ts_dir = project / "Polish" / "job001" / "tilt_series" ts_dir.mkdir(parents=True) _make_tilt_series_star(str(ts_dir / "tomo_001.star"), n_tilts=n_tilts)
tomo_dir = project / "Polish" / "job001" tomo_star = tomo_dir / "tomograms.star" # Path relative to project root _make_tomograms_star( str(tomo_star), "Polish/job001/tilt_series/tomo_001.star", )
extract_dir = project / "Extract" extract_dir.mkdir() p_star = extract_dir / "particles.star" _make_particles_star(str(p_star), n_particles=2, n_tilts=n_tilts)
output = str(tmp_path / "output.star") convert(str(tomo_star), str(p_star), output)
df, _ = read_star(output) assert len(df) == 2 * n_tilts
# ---------------------------------------------------------------------------# Tests: geometry consistency# ---------------------------------------------------------------------------
class TestGeometryConsistency: def test_hand_affects_defocus(self): """Changing handedness should flip the defocus depth offset.""" n = 1 kwargs = dict( pixel_size=1.0, defocus_u=np.array([30000.0]), defocus_v=np.array([30000.0]), defocus_angle=np.array([0.0]), x_tilts=np.array([30.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), ) tomo_pos = Tomogram(**kwargs, hand=1) tomo_neg = Tomogram(**kwargs, hand=-1)
point = np.array([0.0, 0.0, 500.0]) u_pos, _, _ = tomo_pos.local_defocus(0, point) u_neg, _, _ = tomo_neg.local_defocus(0, point)
# Depth offsets should be opposite base = 30000.0 offset_pos = u_pos - base offset_neg = u_neg - base assert offset_pos == pytest.approx(-offset_neg, abs=1e-6)
def test_orientation_composition_order(self): """R_base = R_particle * R_subtomo, then composed with tilt geometry.""" rp = R.from_euler("ZYZ", [30, 45, 60], degrees=True) rs = R.from_euler("ZYZ", [10, 5, -10], degrees=True) R_base = rp * rs
# The expand_particles_batch method should use R_base @ tilt_rotation tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([0.0]), defocus_v=np.array([0.0]), defocus_angle=np.array([0.0]), x_tilts=np.array([20.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), hand=1, ) tilt_df = pd.DataFrame( { "_rlnMicrographName": ["mic.mrc"], "_rlnMicrographPreExposure": ["3.0"], "_rlnCtfScalefactor": ["1.0"], "_rlnTomoNominalStageTiltAngle": ["20.0"], } ) df = tomo.expand_particles_batch( np.array([[0.0, 0.0, 0.0]]), ["stack.mrcs"], tilt_df, ["p/1"], R_base, np.array([1]), ) # Verify non-zero angles assert float(df["_rlnAngleRot"].iloc[0]) != 0.0 assert float(df["_rlnAngleTilt"].iloc[0]) != 0.0
def test_matches_reference_defocus(self): """Verify our Tomogram class exactly matches the original relion2cryodrgn defocus geometry (Ryan Feathers / Bogdan Toader)."""
def ryan_local_defocus(x_tilt, y_tilt, z_rot, x_shift, y_shift, dfu, dfv, dfa, point, hand): Rx = R.from_euler("x", x_tilt, degrees=True) Ry = R.from_euler("y", y_tilt, degrees=True) Rz = R.from_euler("z", z_rot, degrees=True) Rzyx = (Rz * Ry * Rx).as_matrix() proj_mat = np.eye(4) proj_mat[:3, :3] = Rzyx proj_mat[0, 3] = x_shift proj_mat[1, 3] = y_shift proj_pos = proj_mat @ np.append(point, 1.0) proj_centre = proj_mat @ np.array([0, 0, 0, 1.0]) depth_offset = (proj_pos[2] - proj_centre[2]) * hand return dfu + depth_offset, dfv + depth_offset, dfa
# Test with realistic parameters rng = np.random.RandomState(123) n = 7 x_tilts = rng.uniform(-60, 60, n) y_tilts = rng.uniform(-5, 5, n) z_rots = rng.uniform(70, 90, n) x_shifts = rng.uniform(-500, 500, n) y_shifts = rng.uniform(-500, 500, n) dfu = rng.uniform(20000, 40000, n) dfv = rng.uniform(20000, 40000, n) dfa = rng.uniform(0, 180, n)
tomo = Tomogram( pixel_size=1.5, defocus_u=dfu, defocus_v=dfv, defocus_angle=dfa, x_tilts=x_tilts, y_tilts=y_tilts, z_rots=z_rots, x_shifts=x_shifts, y_shifts=y_shifts, hand=-1, )
point = np.array([300.0, -150.0, 200.0])
for i in range(n): # Defocus our_u, our_v, our_a = tomo.local_defocus(i, point) ref_u, ref_v, ref_a = ryan_local_defocus( x_tilts[i], y_tilts[i], z_rots[i], x_shifts[i], y_shifts[i], dfu[i], dfv[i], dfa[i], point, -1, ) assert our_u == pytest.approx(ref_u, abs=1e-10), f"DefocusU mismatch at tilt {i}" assert our_v == pytest.approx(ref_v, abs=1e-10), f"DefocusV mismatch at tilt {i}" assert our_a == pytest.approx(ref_a, abs=1e-10), f"DefocusAngle mismatch at tilt {i}"
# ---------------------------------------------------------------------------# Tests: Tomogram edge cases# ---------------------------------------------------------------------------
class TestTomogramEdgeCases: def test_defocus_offset_proportional_to_depth(self): """Defocus offset should scale linearly with z displacement.""" tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([30000.0]), defocus_v=np.array([30000.0]), defocus_angle=np.array([0.0]), x_tilts=np.array([45.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), hand=1, ) u0, _, _ = tomo.local_defocus(0, np.array([0.0, 0.0, 0.0])) u1, _, _ = tomo.local_defocus(0, np.array([0.0, 0.0, 100.0])) u2, _, _ = tomo.local_defocus(0, np.array([0.0, 0.0, 200.0]))
offset1 = u1 - u0 offset2 = u2 - u0 assert offset2 == pytest.approx(2 * offset1, abs=1e-6)
def test_defocus_angle_unchanged(self): """Local defocus angle should always equal the global defocus angle.""" rng = np.random.RandomState(999) n = 5 dfa = rng.uniform(0, 180, n) tomo = Tomogram( pixel_size=1.0, defocus_u=rng.uniform(20000, 40000, n), defocus_v=rng.uniform(20000, 40000, n), defocus_angle=dfa, x_tilts=rng.uniform(-60, 60, n), y_tilts=rng.uniform(-5, 5, n), z_rots=rng.uniform(0, 360, n), x_shifts=rng.uniform(-200, 200, n), y_shifts=rng.uniform(-200, 200, n), hand=-1, ) for i in range(n): point = rng.uniform(-500, 500, 3) _, _, a = tomo.local_defocus(i, point) assert a == pytest.approx(dfa[i], abs=1e-12)
def test_expand_particles_batch_dose_columns_are_float(self): """Verify that dose-related columns are numeric after expand.""" n = 3 tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([20000.0, 21000.0, 22000.0]), defocus_v=np.array([20500.0, 21500.0, 22500.0]), defocus_angle=np.zeros(n), x_tilts=np.array([-30.0, 0.0, 30.0]), y_tilts=np.zeros(n), z_rots=np.zeros(n), x_shifts=np.zeros(n), y_shifts=np.zeros(n), hand=1, ) tilt_df = pd.DataFrame( { "_rlnMicrographName": ["m0.mrc", "m1.mrc", "m2.mrc"], "_rlnMicrographPreExposure": ["3.0", "6.0", "9.0"], "_rlnCtfScalefactor": ["1.0", "0.9", "0.8"], "_rlnTomoNominalStageTiltAngle": ["-30.0", "0.0", "30.0"], } ) df = tomo.expand_particles_batch( np.array([[0.0, 0.0, 0.0]]), ["stack.mrcs"], tilt_df, ["p/1"], None, np.array([1]), ) # Should be numeric (float) assert df["_rlnMicrographPreExposure"].dtype in [np.float64, np.float32] assert df["_rlnCtfScalefactor"].dtype in [np.float64, np.float32] np.testing.assert_allclose(df["_rlnDefocusU"].values, [20000.0, 21000.0, 22000.0], atol=1e-6)
def test_expand_particles_batch_infers_missing_ctf_scale_from_tilt(self): """Infer the geometric scale when external RELION-like STARs omit it.""" n = 3 tomo = Tomogram( pixel_size=1.54, defocus_u=np.full(n, 20_000.0), defocus_v=np.full(n, 20_100.0), defocus_angle=np.zeros(n), x_tilts=np.zeros(n), y_tilts=np.linspace(-30.0, 30.0, n), z_rots=np.zeros(n), x_shifts=np.zeros(n), y_shifts=np.zeros(n), hand=1, ) tilt_df = pd.DataFrame( { "_rlnMicrographName": [f"tilt_{i}.mrc" for i in range(n)], "_rlnMicrographPreExposure": [0.0, 2.0, 4.0], "_rlnTomoYTilt": [-30.0, 0.0, 30.0], "_rlnTomoNominalStageTiltAngle": [-30.0, 0.0, 30.0], } )
df = tomo.expand_particles_batch( np.zeros((1, 3)), ["particle.mrcs"], tilt_df, ["particle_1"], R.identity(), np.array([1]), )
np.testing.assert_allclose( df["_rlnCtfScalefactor"].values, np.cos(np.deg2rad([-30.0, 0.0, 30.0])), )
def test_expand_preserves_ctf_scalefactor(self): """CTF scale factors from the tilt series should appear unchanged.""" n = 4 ctf_scales = np.array([1.0, 0.95, 0.85, 0.7]) tomo = Tomogram( pixel_size=1.0, defocus_u=np.zeros(n), defocus_v=np.zeros(n), defocus_angle=np.zeros(n), x_tilts=np.linspace(-40, 40, n), y_tilts=np.zeros(n), z_rots=np.zeros(n), x_shifts=np.zeros(n), y_shifts=np.zeros(n), hand=1, ) tilt_df = pd.DataFrame( { "_rlnMicrographName": [f"m{i}.mrc" for i in range(n)], "_rlnMicrographPreExposure": [str(i * 3.0) for i in range(n)], "_rlnCtfScalefactor": [str(c) for c in ctf_scales], "_rlnTomoNominalStageTiltAngle": [str(a) for a in np.linspace(-40, 40, n)], } ) df = tomo.expand_particles_batch( np.array([[0.0, 0.0, 0.0]]), ["stack.mrcs"], tilt_df, ["p/1"], None, np.array([1]), ) np.testing.assert_allclose(df["_rlnCtfScalefactor"].values, ctf_scales)
def test_identity_orientation_at_zero_tilt(self): """Identity base orientation with zero tilt should give near-zero angles.""" tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([0.0]), defocus_v=np.array([0.0]), defocus_angle=np.array([0.0]), x_tilts=np.array([0.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), hand=1, ) tilt_df = pd.DataFrame( { "_rlnMicrographName": ["mic.mrc"], "_rlnMicrographPreExposure": ["3.0"], "_rlnCtfScalefactor": ["1.0"], "_rlnTomoNominalStageTiltAngle": ["0.0"], } ) # Identity rotation at zero tilt: final rotation is identity @ identity = identity R_identity = R.identity() df = tomo.expand_particles_batch( np.array([[0.0, 0.0, 0.0]]), ["stack.mrcs"], tilt_df, ["p/1"], R_identity, np.array([1]), ) # ZYZ Euler of identity is (0, 0, 0) # But the tilt rotation matrix at zero tilt is also identity # so R_final = I @ I = I -> ZYZ = (0, 0, 0) rot = float(df["_rlnAngleRot"].iloc[0]) tilt = float(df["_rlnAngleTilt"].iloc[0]) psi = float(df["_rlnAnglePsi"].iloc[0]) # sin(tilt) should be ~0; rot+psi is degenerate but tilt should be ~0 assert abs(tilt) < 1e-6
def test_many_tilts_constructor(self): """Sanity check that 100 tilts work without issues.""" n = 100 tomo = Tomogram( pixel_size=1.5, defocus_u=np.linspace(20000, 40000, n), defocus_v=np.linspace(20000, 40000, n), defocus_angle=np.zeros(n), x_tilts=np.linspace(-70, 70, n), y_tilts=np.zeros(n), z_rots=np.full(n, 85.0), x_shifts=np.zeros(n), y_shifts=np.zeros(n), hand=-1, ) assert tomo.n_tilts == n # Verify defocus is finite for a sample point u, v, a = tomo.local_defocus(50, np.array([500.0, -300.0, 200.0])) assert np.isfinite(u) assert np.isfinite(v)
def test_single_tilt(self): """Single tilt should work correctly.""" tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([25000.0]), defocus_v=np.array([26000.0]), defocus_angle=np.array([30.0]), x_tilts=np.array([0.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), hand=1, ) assert tomo.n_tilts == 1 # At origin with zero tilt, defocus should match global u, v, a = tomo.local_defocus(0, np.array([0.0, 0.0, 0.0])) assert u == pytest.approx(25000.0) assert v == pytest.approx(26000.0) assert a == pytest.approx(30.0)
# ---------------------------------------------------------------------------# Tests: visible frames edge cases# ---------------------------------------------------------------------------
class TestParseVisibleFramesEdgeCases: def test_single_visible(self): assert _parse_visible_frames("[1]") == [0]
def test_single_invisible(self): assert _parse_visible_frames("[0]") == []
def test_first_invisible_rest_visible(self): assert _parse_visible_frames("[0,1,1,1]") == [1, 2, 3]
def test_last_invisible(self): assert _parse_visible_frames("[1,1,1,0]") == [0, 1, 2]
def test_alternating(self): assert _parse_visible_frames("[1,0,1,0,1,0]") == [0, 2, 4]
def test_long_list(self): frames = "[" + ",".join(["1"] * 41) + "]" result = _parse_visible_frames(frames) assert len(result) == 41 assert result == list(range(41))
def test_only_middle_visible(self): assert _parse_visible_frames("[0,0,1,0,0]") == [2]
# ---------------------------------------------------------------------------# Tests: convert() edge cases# ---------------------------------------------------------------------------
class TestConvertEdgeCases: def test_multiple_tomograms(self, tmp_path): """Particles from multiple tomograms should all be converted.""" n_tilts = 3
ts_dir = tmp_path / "tilt_series" ts_dir.mkdir() for i in range(2): _make_tilt_series_star(str(ts_dir / f"tomo_{i:03d}.star"), n_tilts=n_tilts)
# Write tomograms.star with 2 tomos pointing to the same tilt series tomo_star = tmp_path / "tomograms.star" header = textwrap.dedent("""\ # version 50001
data_global
loop_ _rlnTomoName #1 _rlnTomoTiltSeriesStarFile #2 _rlnTomoTiltSeriesPixelSize #3 _rlnTomoHand #4 _rlnTomoSizeX #5 _rlnTomoSizeY #6 tomo_000 tilt_series/tomo_000.star 1.5 -1 4096 4096 tomo_001 tilt_series/tomo_001.star 1.5 1 4096 4096 """) _write_text(str(tomo_star), header)
# Particles: 2 from tomo_000, 1 from tomo_001 visible = "[" + ",".join(["1"] * n_tilts) + "]" particles_text = textwrap.dedent(f"""\ # version 50001
data_optics
loop_ _rlnVoltage #1 _rlnSphericalAberration #2 _rlnAmplitudeContrast #3 _rlnOpticsGroup #4 _rlnOpticsGroupName #5 _rlnImagePixelSize #6 _rlnImageSize #7 _rlnImageDimensionality #8 300.0 2.7 0.1 1 opticsGroup1 1.5 128 2
# version 50001
data_particles
loop_ _rlnTomoName #1 _rlnCenteredCoordinateXAngst #2 _rlnCenteredCoordinateYAngst #3 _rlnCenteredCoordinateZAngst #4 _rlnOpticsGroup #5 _rlnTomoParticleName #6 _rlnImageName #7 _rlnAngleRot #8 _rlnAngleTilt #9 _rlnAnglePsi #10 _rlnRandomSubset #11 _rlnTomoVisibleFrames #12 tomo_000 100.0 200.0 50.0 1 tomo_000/1 Extract/tomo_000/1_stack2d.mrcs 10.0 20.0 30.0 1 {visible} tomo_000 -100.0 -200.0 -50.0 1 tomo_000/2 Extract/tomo_000/2_stack2d.mrcs 40.0 50.0 60.0 2 {visible} tomo_001 0.0 0.0 0.0 1 tomo_001/1 Extract/tomo_001/1_stack2d.mrcs 0.0 0.0 0.0 1 {visible} """) p_star = tmp_path / "particles.star" _write_text(str(p_star), particles_text)
output = str(tmp_path / "output.star") convert(str(tomo_star), str(p_star), output)
df, _ = read_star(output) assert len(df) == 3 * n_tilts
# Check that all three groups exist groups = sorted(df["_rlnGroupName"].unique()) assert groups == ["tomo_000/1", "tomo_000/2", "tomo_001/1"]
def test_single_particle(self, tmp_path): """Single particle conversion should work.""" n_tilts = 3 ts_dir = tmp_path / "ts" ts_dir.mkdir() _make_tilt_series_star(str(ts_dir / "ts.star"), n_tilts=n_tilts)
tomo_star = tmp_path / "tomos.star" _make_tomograms_star(str(tomo_star), "ts/ts.star")
p_star = tmp_path / "particles.star" _make_particles_star(str(p_star), n_particles=1, n_tilts=n_tilts)
output = str(tmp_path / "output.star") convert(str(tomo_star), str(p_star), output)
df, _ = read_star(output) assert len(df) == n_tilts assert len(df["_rlnGroupName"].unique()) == 1
def test_missing_optics_raises(self, tmp_path): """particles.star without optics table should raise ValueError.""" n_tilts = 3 ts_dir = tmp_path / "ts" ts_dir.mkdir() _make_tilt_series_star(str(ts_dir / "ts.star"), n_tilts=n_tilts)
tomo_star = tmp_path / "tomos.star" _make_tomograms_star(str(tomo_star), "ts/ts.star")
# Write particles.star without optics table no_optics_text = textwrap.dedent("""\ # version 50001
data_particles
loop_ _rlnTomoName #1 _rlnCenteredCoordinateXAngst #2 _rlnCenteredCoordinateYAngst #3 _rlnCenteredCoordinateZAngst #4 _rlnOpticsGroup #5 _rlnTomoParticleName #6 _rlnImageName #7 _rlnAngleRot #8 _rlnAngleTilt #9 _rlnAnglePsi #10 _rlnRandomSubset #11 _rlnTomoVisibleFrames #12 tomo_001 0.0 0.0 0.0 1 tomo_001/1 img.mrcs 0.0 0.0 0.0 1 [1,1,1] """) p_star = tmp_path / "p.star" _write_text(str(p_star), no_optics_text)
output = str(tmp_path / "output.star") with pytest.raises(ValueError, match="no optics"): convert(str(tomo_star), str(p_star), output)
def test_missing_tomogram_in_tomograms_star_raises(self, tmp_path): """Particle referencing a tomo not in tomograms.star should raise.""" n_tilts = 3 ts_dir = tmp_path / "ts" ts_dir.mkdir() _make_tilt_series_star(str(ts_dir / "ts.star"), n_tilts=n_tilts)
tomo_star = tmp_path / "tomos.star" _make_tomograms_star(str(tomo_star), "ts/ts.star") # has tomo_001
# Particle references "tomo_999" which doesn't exist visible = "[" + ",".join(["1"] * n_tilts) + "]" particles_text = textwrap.dedent(f"""\ # version 50001
data_optics
loop_ _rlnVoltage #1 _rlnSphericalAberration #2 _rlnAmplitudeContrast #3 _rlnOpticsGroup #4 _rlnOpticsGroupName #5 _rlnImagePixelSize #6 _rlnImageSize #7 _rlnImageDimensionality #8 300.0 2.7 0.1 1 opticsGroup1 1.5 128 2
# version 50001
data_particles
loop_ _rlnTomoName #1 _rlnCenteredCoordinateXAngst #2 _rlnCenteredCoordinateYAngst #3 _rlnCenteredCoordinateZAngst #4 _rlnOpticsGroup #5 _rlnTomoParticleName #6 _rlnImageName #7 _rlnAngleRot #8 _rlnAngleTilt #9 _rlnAnglePsi #10 _rlnRandomSubset #11 _rlnTomoVisibleFrames #12 tomo_999 0.0 0.0 0.0 1 tomo_999/1 img.mrcs 0.0 0.0 0.0 1 {visible} """) p_star = tmp_path / "p.star" _write_text(str(p_star), particles_text)
output = str(tmp_path / "output.star") with pytest.raises(ValueError, match="tomo_999"): convert(str(tomo_star), str(p_star), output)
def test_deterministic_output(self, relion5_data, tmp_path): """Running convert() twice on the same input should give identical output.""" out1 = str(tmp_path / "out1.star") out2 = str(tmp_path / "out2.star") convert(relion5_data["tomograms"], relion5_data["particles"], out1) convert(relion5_data["tomograms"], relion5_data["particles"], out2)
df1, op1 = read_star(out1) df2, op2 = read_star(out2)
pd.testing.assert_frame_equal(df1, df2) pd.testing.assert_frame_equal(op1, op2)
def test_origins_are_zero(self, relion5_data, tmp_path): """All _rlnOriginXAngst and _rlnOriginYAngst should be zero.""" output = str(tmp_path / "output.star") convert(relion5_data["tomograms"], relion5_data["particles"], output) df, _ = read_star(output) ox = df["_rlnOriginXAngst"].values.astype(float) oy = df["_rlnOriginYAngst"].values.astype(float) np.testing.assert_array_equal(ox, 0.0) np.testing.assert_array_equal(oy, 0.0)
def test_optics_values_propagated(self, relion5_data, tmp_path): """Verify that optics values from the input are in the output.""" output = str(tmp_path / "output.star") convert(relion5_data["tomograms"], relion5_data["particles"], output) _, optics = read_star(output) assert optics["_rlnVoltage"].values[0] == "300.0" assert optics["_rlnSphericalAberration"].values[0] == "2.7" assert optics["_rlnAmplitudeContrast"].values[0] == "0.1" assert optics["_rlnImageDimensionality"].values[0] == "2" assert optics["_rlnOpticsGroupName"].values[0] == "opticsGroup1"
def test_all_optics_group_one(self, relion5_data, tmp_path): """All particles should have _rlnOpticsGroup = 1.""" output = str(tmp_path / "output.star") convert(relion5_data["tomograms"], relion5_data["particles"], output) df, _ = read_star(output) groups = df["_rlnOpticsGroup"].values assert all(g == "1" for g in groups)
def test_defocus_values_nontrivial(self, relion5_data, tmp_path): """Output defocus should not be all-zero -- should have real values.""" output = str(tmp_path / "output.star") convert(relion5_data["tomograms"], relion5_data["particles"], output) df, _ = read_star(output) dfu = df["_rlnDefocusU"].values.astype(float) dfv = df["_rlnDefocusV"].values.astype(float) assert np.any(dfu != 0) assert np.any(dfv != 0) # The synthetic data has defocus around 30000-31400 assert np.all(dfu > 1000) # should be large values assert np.all(dfv > 1000)
def test_stage_tilt_angle_preserved(self, relion5_data, tmp_path): """_rlnTomoNominalStageTiltAngle should be present and non-trivial.""" output = str(tmp_path / "output.star") convert(relion5_data["tomograms"], relion5_data["particles"], output) df, _ = read_star(output) assert "_rlnTomoNominalStageTiltAngle" in df.columns angles = df["_rlnTomoNominalStageTiltAngle"].values.astype(float) # Our synthetic data has tilts from -60 to 60 assert np.min(angles) < -10 assert np.max(angles) > 10
def test_each_group_has_consistent_random_subset(self, relion5_data, tmp_path): """Each particle group should have the same _rlnRandomSubset for all tilts.""" output = str(tmp_path / "output.star") convert(relion5_data["tomograms"], relion5_data["particles"], output) df, _ = read_star(output) for group in df["_rlnGroupName"].unique(): mask = df["_rlnGroupName"] == group subsets = df[mask]["_rlnRandomSubset"].values.astype(int) assert len(set(subsets)) == 1, f"Group {group} has mixed subsets: {set(subsets)}"
def test_micrograph_name_preserved(self, relion5_data, tmp_path): """_rlnMicrographName should be propagated from tilt series.""" output = str(tmp_path / "output.star") convert(relion5_data["tomograms"], relion5_data["particles"], output) df, _ = read_star(output) assert "_rlnMicrographName" in df.columns names = df["_rlnMicrographName"].values # Should contain mic_000.mrc, mic_001.mrc, etc. from our fixture assert any("mic_" in n for n in names)
# ---------------------------------------------------------------------------# Tests: quantitative geometry checks# ---------------------------------------------------------------------------
class TestQuantitativeGeometry: def test_defocus_offset_at_45deg_tilt_known_value(self): """At 45-degree x-tilt, z-displacement projects to z' = z * cos(45) + ... The depth offset for a pure Z displacement is z * sin(45) * hand.""" tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([10000.0]), defocus_v=np.array([10000.0]), defocus_angle=np.array([0.0]), x_tilts=np.array([45.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), hand=1, ) z_disp = 1000.0 # Angstroms u, _, _ = tomo.local_defocus(0, np.array([0.0, 0.0, z_disp])) # For x-tilt, Rzyx = Rx(45). Point (0,0,z) -> (0, -z*sin45, z*cos45) # depth offset = (z*cos45 - 0) * hand = z * cos(45) expected_offset = z_disp * np.cos(np.deg2rad(45.0)) assert u == pytest.approx(10000.0 + expected_offset, abs=1.0)
def test_defocus_offset_at_zero_tilt_equals_z(self): """At zero tilt, depth offset equals z * hand (particle at different depth along the beam has different defocus).""" tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([25000.0]), defocus_v=np.array([25000.0]), defocus_angle=np.array([0.0]), x_tilts=np.array([0.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), hand=1, ) for z in [-1000.0, 0.0, 500.0, 2000.0]: u, v, a = tomo.local_defocus(0, np.array([0.0, 0.0, z])) # At zero tilt, R=I so depth_offset = z * hand assert u == pytest.approx(25000.0 + z, abs=1e-6) assert v == pytest.approx(25000.0 + z, abs=1e-6)
def test_xy_displacement_no_defocus_offset_at_zero_tilt(self): """XY displacement at zero tilt should produce no defocus change.""" tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([20000.0]), defocus_v=np.array([20000.0]), defocus_angle=np.array([0.0]), x_tilts=np.array([0.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), hand=1, ) u, _, _ = tomo.local_defocus(0, np.array([5000.0, 3000.0, 0.0])) assert u == pytest.approx(20000.0, abs=1e-6)
def test_defocus_u_v_offset_identical(self): """DefocusU and DefocusV should receive the same depth offset.""" tomo = Tomogram( pixel_size=1.0, defocus_u=np.array([25000.0]), defocus_v=np.array([30000.0]), defocus_angle=np.array([45.0]), x_tilts=np.array([40.0]), y_tilts=np.array([0.0]), z_rots=np.array([0.0]), x_shifts=np.array([0.0]), y_shifts=np.array([0.0]), hand=-1, ) pt = np.array([0.0, 0.0, 500.0]) u, v, _ = tomo.local_defocus(0, pt) u0, v0, _ = tomo.local_defocus(0, np.array([0.0, 0.0, 0.0])) # Both U and V should change by the same offset assert (u - u0) == pytest.approx(v - v0, abs=1e-10)
def test_multiple_random_points_defocus_finite(self): """Stress test: many random points and parameters produce finite defocus.""" rng = np.random.RandomState(7777) for trial in range(10): n = rng.randint(3, 15) x_tilts = rng.uniform(-70, 70, n) y_tilts = rng.uniform(-10, 10, n) z_rots = rng.uniform(0, 360, n) x_shifts = rng.uniform(-1000, 1000, n) y_shifts = rng.uniform(-1000, 1000, n) dfu = rng.uniform(10000, 50000, n) dfv = rng.uniform(10000, 50000, n) dfa = rng.uniform(0, 180, n) hand = rng.choice([-1, 1])
tomo = Tomogram( pixel_size=rng.uniform(0.5, 3.0), defocus_u=dfu, defocus_v=dfv, defocus_angle=dfa, x_tilts=x_tilts, y_tilts=y_tilts, z_rots=z_rots, x_shifts=x_shifts, y_shifts=y_shifts, hand=hand, )
for _ in range(5): pt = rng.uniform(-2000, 2000, 3)
for i in range(n): # Verify defocus is finite u, v, a = tomo.local_defocus(i, pt) assert np.isfinite(u), f"Non-finite DefocusU: trial={trial}" assert np.isfinite(v), f"Non-finite DefocusV: trial={trial}" assert a == pytest.approx(dfa[i], abs=1e-10)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""Regression test for parse_relion5_tomo using real RELION5 data subset.
Tests that convert() produces identical output on a small fixture extractedfrom a real ribosome tilt-series dataset (Ryan Feathers, Princeton).
Fixture: tests/fixtures/relion5_tomo_subset/ - tomograms.star (2 tilt series) - particles.star (10 particles, 5 per tilt series) - Polish/job185/tilt_series/*.star (per-tilt geometry) - reference_output.star (expected conversion output) - reference_values.npy (defocus + Euler angles for regression check)"""
import os
import numpy as npimport pytest
from recovar.commands.parse_relion5_tomo import convertfrom recovar.data_io.starfile import read_star
pytestmark = pytest.mark.unit
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), "..", "fixtures", "relion5_tomo_subset")
@pytest.fixturedef fixture_paths(): return { "tomograms": os.path.join(FIXTURE_DIR, "tomograms.star"), "particles": os.path.join(FIXTURE_DIR, "particles.star"), "reference_output": os.path.join(FIXTURE_DIR, "reference_output.star"), "reference_values": os.path.join(FIXTURE_DIR, "reference_values.npy"), }
def test_fixture_exists(fixture_paths): """Sanity check that fixture files exist.""" for name, path in fixture_paths.items(): assert os.path.isfile(path), f"Missing fixture: {name} at {path}"
def test_conversion_row_count(fixture_paths, tmp_path): """Conversion should produce the same number of rows as reference.""" output = str(tmp_path / "output.star") convert(fixture_paths["tomograms"], fixture_paths["particles"], output)
out_df, _ = read_star(output) ref_df, _ = read_star(fixture_paths["reference_output"]) assert len(out_df) == len(ref_df), f"Row count mismatch: got {len(out_df)}, expected {len(ref_df)}"
def test_conversion_columns_match(fixture_paths, tmp_path): """Output should have the same columns as reference.""" output = str(tmp_path / "output.star") convert(fixture_paths["tomograms"], fixture_paths["particles"], output)
out_df, _ = read_star(output) ref_df, _ = read_star(fixture_paths["reference_output"]) assert set(out_df.columns) == set(ref_df.columns)
def test_conversion_string_columns_exact(fixture_paths, tmp_path): """GroupName, ImageName, MicrographName should match exactly.""" output = str(tmp_path / "output.star") convert(fixture_paths["tomograms"], fixture_paths["particles"], output)
out_df, _ = read_star(output) ref_df, _ = read_star(fixture_paths["reference_output"])
# Sort both by GroupName + dose for fair comparison for df in (out_df, ref_df): df["_rlnMicrographPreExposure"] = df["_rlnMicrographPreExposure"].astype(float) out_df = out_df.sort_values(["_rlnGroupName", "_rlnMicrographPreExposure"]).reset_index(drop=True) ref_df = ref_df.sort_values(["_rlnGroupName", "_rlnMicrographPreExposure"]).reset_index(drop=True)
for col in ["_rlnGroupName", "_rlnImageName", "_rlnMicrographName"]: assert (out_df[col].values == ref_df[col].values).all(), f"Column {col} mismatch"
def test_conversion_numerical_regression(fixture_paths, tmp_path): """Defocus and Euler angles should match reference to machine precision.""" output = str(tmp_path / "output.star") convert(fixture_paths["tomograms"], fixture_paths["particles"], output)
out_df, _ = read_star(output) out_df["_rlnMicrographPreExposure"] = out_df["_rlnMicrographPreExposure"].astype(float) out_df = out_df.sort_values(["_rlnGroupName", "_rlnMicrographPreExposure"]).reset_index(drop=True)
ref_values = np.load(fixture_paths["reference_values"])
key_cols = ["_rlnDefocusU", "_rlnDefocusV", "_rlnDefocusAngle", "_rlnAngleRot", "_rlnAngleTilt", "_rlnAnglePsi"] out_values = out_df[key_cols].values.astype(float)
np.testing.assert_allclose( out_values, ref_values, atol=1e-10, rtol=1e-12, err_msg="Numerical regression: defocus/Euler values differ from reference", )
def test_conversion_dose_sorted(fixture_paths, tmp_path): """Within each group, rows should be sorted by dose.""" output = str(tmp_path / "output.star") convert(fixture_paths["tomograms"], fixture_paths["particles"], output)
out_df, _ = read_star(output) for group, sub in out_df.groupby("_rlnGroupName"): doses = sub["_rlnMicrographPreExposure"].values.astype(float) assert (np.diff(doses) >= 0).all(), f"Group {group} not sorted by dose"
def test_conversion_random_subset_preserved(fixture_paths, tmp_path): """Each group should have a consistent _rlnRandomSubset.""" output = str(tmp_path / "output.star") convert(fixture_paths["tomograms"], fixture_paths["particles"], output)
out_df, _ = read_star(output) for group, sub in out_df.groupby("_rlnGroupName"): subsets = sub["_rlnRandomSubset"].values.astype(int) assert len(set(subsets)) == 1, f"Group {group} has mixed random subsets: {set(subsets)}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import argparse
import pytest
from recovar.commands import estimate_conformational_density, estimate_stable_states, postprocessfrom recovar.utils import parser_args
pytestmark = pytest.mark.unit
def test_standard_downstream_args_outdir_optional(): """--outdir is always optional (auto-numbering fills in the default).""" parser = parser_args.standard_downstream_args(argparse.ArgumentParser(), analyze=False) parsed = parser.parse_args(["/tmp/results", "-o", "/tmp/out"]) assert parsed.result_dir == "/tmp/results" assert parsed.outdir == "/tmp/out"
# Without -o, outdir should be None (auto-numbering kicks in at runtime) parsed2 = parser.parse_args(["/tmp/results"]) assert parsed2.outdir is None
def test_standard_downstream_args_outdir_optional_for_analyze(): parser = parser_args.standard_downstream_args(argparse.ArgumentParser(), analyze=True) parsed = parser.parse_args(["/tmp/results"]) assert parsed.result_dir == "/tmp/results" assert parsed.outdir is None
def test_standard_downstream_args_defaults_and_flags(): parser = parser_args.standard_downstream_args(argparse.ArgumentParser(), analyze=True) parsed = parser.parse_args( [ "/tmp/results", "--zdim1", "--no-z-regularization", "--lazy", "--apply-global-filtering", ] ) assert parsed.n_bins == 50 assert parsed.maskrad_fraction == 20 assert parsed.zdim1 is True assert parsed.no_z_regularization is True assert parsed.lazy is True assert parsed.apply_global_filtering is True
def test_standard_downstream_args_project_mode_defaults(): parser = parser_args.standard_downstream_args(argparse.ArgumentParser(), analyze=True) parsed = parser.parse_args(["--project", "/tmp/project", "--output-name", "embedding_k10"]) assert parsed.result_dir is None assert parsed.project == "/tmp/project" assert parsed.output_name == "embedding_k10"
@pytest.mark.parametrize( ("module", "argv", "expected"), [ ( estimate_conformational_density, [ "estimate_conformational_density", "/tmp/pipeline", "--project", "/tmp/project", "--output-name", "density_custom", ], "density_custom", ), ( estimate_stable_states, [ "estimate_stable_states", "/tmp/density.pkl", "-o", "/tmp/stable", "--project", "/tmp/project", "--output-name", "stable_states_custom", ], "stable_states_custom", ), ],)def test_custom_project_parsers_accept_output_name(monkeypatch, module, argv, expected): monkeypatch.setattr("sys.argv", argv) parsed = module.parse_args() assert parsed.project == "/tmp/project" assert parsed.output_name == expected
def test_postprocess_parser_accepts_output_name(): parser = postprocess.add_args(argparse.ArgumentParser()) parsed = parser.parse_args( [ "/tmp/half1.mrc", "--halfmap2", "/tmp/half2.mrc", "--output", "/tmp/postprocess", "--project", "/tmp/project", "--output-name", "postprocess_custom", ] ) assert parsed.project == "/tmp/project" assert parsed.output_name == "postprocess_custom"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""Unit tests for recovar.simulation.pdb_utils."""
import osimport tempfile
import numpy as npimport pytest
from recovar.simulation.pdb_utils import AtomGroup, write_pdb, _parse_pdb_file
pytestmark = pytest.mark.unit
class TestAtomGroup: def test_empty_default(self): ag = AtomGroup() assert ag.numAtoms() == 0 assert ag.getCoords().shape == (0, 3)
def test_set_and_get(self): ag = AtomGroup() coords = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float64) ag.setCoords(coords) np.testing.assert_array_equal(ag.getCoords(), coords) assert ag.numAtoms() == 2
elems = np.array(["C", "N"]) ag.setElements(elems) np.testing.assert_array_equal(ag.getElements(), elems)
chains = np.array(["A", "B"]) ag.setChids(chains) np.testing.assert_array_equal(ag.getChids(), chains)
def test_getData(self): ag = AtomGroup() ag.setElements(np.array(["C"])) assert ag.getData("element")[0] == "C" with pytest.raises(KeyError): ag.getData("unknown_key")
class TestPdbWriteReadRoundtrip: def test_roundtrip(self): ag = AtomGroup() coords = np.array( [ [1.234, 5.678, 9.012], [10.0, -20.5, 30.75], [0.0, 0.0, 0.0], ], dtype=np.float64, ) ag.setCoords(coords) ag.setNames(np.array(["CA", "CB", "N"])) ag.setElements(np.array(["C", "C", "N"]))
with tempfile.NamedTemporaryFile(suffix=".pdb", delete=False) as f: pdb_path = f.name
try: write_pdb(pdb_path, ag) assert os.path.isfile(pdb_path)
loaded = _parse_pdb_file(pdb_path) assert loaded.numAtoms() == 3 np.testing.assert_allclose(loaded.getCoords(), coords, atol=0.002) np.testing.assert_array_equal(loaded.getElements(), ["C", "C", "N"]) finally: os.unlink(pdb_path)
def test_many_atoms(self): n = 500 ag = AtomGroup() rng = np.random.default_rng(99) coords = rng.standard_normal((n, 3)) * 50 ag.setCoords(coords) ag.setNames(np.array(["CA"] * n)) ag.setElements(np.array(["C"] * n))
with tempfile.NamedTemporaryFile(suffix=".pdb", delete=False) as f: pdb_path = f.name try: write_pdb(pdb_path, ag) loaded = _parse_pdb_file(pdb_path) assert loaded.numAtoms() == n np.testing.assert_allclose(loaded.getCoords(), coords, atol=0.002) finally: os.unlink(pdb_path)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import subprocessimport sysfrom types import SimpleNamespace
import pytest
from helpers import perf_regression
pytestmark = pytest.mark.unit
_GB = 1024**3
def test_run_tracked_subprocess_records_polled_peak(monkeypatch): recorded = []
monkeypatch.setattr(perf_regression, "_read_nvidia_smi_gpu_bytes", lambda env=None: 5 * _GB) monkeypatch.setattr(perf_regression, "_record_tracked_gpu_peak_bytes", lambda peak: recorded.append(peak)) monkeypatch.setattr( perf_regression.subprocess, "run", lambda *args, **kwargs: subprocess.CompletedProcess(args[0], 0, stdout="ok", stderr=""), )
result = perf_regression.run_tracked_subprocess(["echo", "hi"], capture_output=True, text=True)
assert recorded == [5 * _GB] assert result.stdout == "ok" assert result.gpu_peak_bytes == 5 * _GB
def test_perf_snapshot_consumes_tracked_gpu_peak(monkeypatch): class _FakeDevice: @staticmethod def memory_stats(): return {}
monkeypatch.setitem(sys.modules, "jax", SimpleNamespace(local_devices=lambda: [_FakeDevice()])) monkeypatch.setattr(perf_regression, "_read_nvidia_smi_gpu_bytes", lambda env=None: 1 * _GB)
perf_regression._record_tracked_gpu_peak_bytes(6 * _GB) first = perf_regression.perf_snapshot() second = perf_regression.perf_snapshot()
assert first["tracked_gpu_peak_bytes"] == 6 * _GB assert second["tracked_gpu_peak_bytes"] == 1 * _GB
def test_stage_perf_uses_tracked_gpu_peak_bytes(): before = { "wall_time": 0.0, "cpu_rss_bytes": 100, "gpu_bytes_in_use": 0, "gpu_peak_bytes": 0, } after = { "wall_time": 2.0, "cpu_rss_bytes": 200, "gpu_bytes_in_use": 1 * _GB, "gpu_peak_bytes": 0, "tracked_gpu_peak_bytes": 6 * _GB, }
perf = perf_regression.stage_perf(before, after)
assert perf["wall_seconds"] == 2.0 assert perf["peak_cpu_memory_gb"] == pytest.approx(0.0) assert perf["peak_gpu_memory_gb"] == pytest.approx(round((6 * _GB) / 1e9, 3))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289import argparseimport osimport pickle
import numpy as npimport pytest
from recovar.commands import pipeline_with_outliers
pytestmark = pytest.mark.unit
class _FakePO: """Fake PipelineOutput that supports .get() for embeddings."""
def get(self, key): return {4: np.zeros((1, 4), dtype=np.float32)}
def get_embedding_component(self, entry, zdim): return np.zeros((1, 4), dtype=np.float32)
def _make_args(tmp_path, *, tilt_series=False): return argparse.Namespace( outdir=str(tmp_path / "pipeline"), zdim=[4], k_rounds=2, no_z_regularization=False, delete_rounds=False, use_contrast_detection=False, use_junk_detection=False, no_plots=True, low_contrast_threshold=0.1, high_contrast_threshold=3.5, max_contrast=4.0, particle_bad_fraction_threshold=0.7, micrograph_bad_fraction_threshold=0.7, junk_threshold=0.5, particles_per_cluster=None, save_pipeline_indices=True, output_format="both", tilt_series=tilt_series, tilt_ind=None, ind=None, particles="particles.mrcs", poses="poses.pkl", ctf="ctf.pkl", mask="mask.mrc", halfsets=None, datadir=None, strip_prefix=None, n_images=-1, lazy=True, uninvert_data="false", downsample=None, no_downsample=False, focus_mask=None, keep_input_mask=False, use_complement_mask=False, mask_dilate_iter=0, dilated_mask_dilation_iters=None, dont_use_image_mask=False, correct_contrast=False, only_mean=False, tilt_series_ctf="cryoem", dose_per_tilt=None, angle_per_tilt=None, ntilts=None, shared_contrast_across_tilts=False, premultiplied_ctf=False, gpu_memory=None, multi_gpu=False, n_gpus=None, accept_cpu=True, low_memory_option=False, very_low_memory_option=False, noise_model="radial", mean_fn="triangular", do_over_with_contrast=False, ignore_zero_frequency=False, padding=0, new_noise_est=False, use_reg_mean_in_contrast=True, keep_intermediate=False, test_covar_options=False, )
def _write_round_artifacts(round_outdir): model_dir = round_outdir / "model" zdim_dir = model_dir / "zdim_4" zdim_dir.mkdir(parents=True, exist_ok=True) np.save(str(zdim_dir / "latent_coords.npy"), np.zeros((1, 4), dtype=np.float32)) with open(round_outdir / "command.txt", "w") as f: f.write("test")
def test_pipeline_with_outliers_uses_original_image_ids_between_rounds(tmp_path, monkeypatch): args = _make_args(tmp_path, tilt_series=False) combined_round_1 = np.array([10, 20, 35], dtype=np.int32) combined_round_2 = np.array([10, 35], dtype=np.int32)
monkeypatch.setattr(pipeline_with_outliers, "add_args", lambda parser: None) monkeypatch.setattr(argparse.ArgumentParser, "parse_args", lambda self: args) monkeypatch.setattr(pipeline_with_outliers.output, "mkdir_safe", os.makedirs) monkeypatch.setattr(pipeline_with_outliers.output, "PipelineOutput", lambda outdir: _FakePO()) monkeypatch.setattr( pipeline_with_outliers.output, "standard_pipeline_plots", lambda *unused, **unused_kwargs: None, )
def fake_standard_recovar_pipeline(pipeline_args): _write_round_artifacts(tmp_path / "pipeline" / f"round_{len(created_rounds) + 1}") if len(created_rounds) == 1: with open(pipeline_args.ind, "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_round_1) created_rounds.append(pipeline_args.outdir)
def fake_outlier_main(): round_outdir = tmp_path / "pipeline" / f"round_{len(outlier_rounds) + 1}" combined_dir = round_outdir / "outlier_detection" / "data" / "combined_results" combined_dir.mkdir(parents=True, exist_ok=True) current = combined_round_1 if not outlier_rounds else combined_round_2 with open(combined_dir / "combined_image_inliers_4.pkl", "wb") as f: pickle.dump(current, f) with open(combined_dir / "combined_image_outliers_4.pkl", "wb") as f: pickle.dump(np.array([], dtype=np.int32), f) outlier_rounds.append(str(round_outdir))
created_rounds = [] outlier_rounds = [] monkeypatch.setattr( pipeline_with_outliers, "standard_recovar_pipeline", fake_standard_recovar_pipeline, ) import recovar.commands.outlier_detection as outlier_detection
monkeypatch.setattr(outlier_detection, "main", fake_outlier_main)
pipeline_with_outliers._run_pipeline_with_outlier_removal_impl(args)
with open(tmp_path / "pipeline" / "inliers_round_1.pkl", "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_round_1) with open(tmp_path / "pipeline" / "round_2" / "inliers_round_1.pkl", "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_round_1)
def test_pipeline_with_outliers_uses_original_particle_ids_between_rounds(tmp_path, monkeypatch): args = _make_args(tmp_path, tilt_series=True) combined_images_round_1 = np.array([100, 110, 120], dtype=np.int32) combined_particles_round_1 = np.array([7, 11], dtype=np.int32) combined_images_round_2 = np.array([100, 120], dtype=np.int32) combined_particles_round_2 = np.array([11], dtype=np.int32)
monkeypatch.setattr(pipeline_with_outliers, "add_args", lambda parser: None) monkeypatch.setattr(argparse.ArgumentParser, "parse_args", lambda self: args) monkeypatch.setattr(pipeline_with_outliers.output, "mkdir_safe", os.makedirs) monkeypatch.setattr(pipeline_with_outliers.output, "PipelineOutput", lambda outdir: _FakePO()) monkeypatch.setattr( pipeline_with_outliers.output, "standard_pipeline_plots", lambda *unused, **unused_kwargs: None, )
def fake_standard_recovar_pipeline(pipeline_args): _write_round_artifacts(tmp_path / "pipeline" / f"round_{len(created_rounds) + 1}") if len(created_rounds) == 1: with open(pipeline_args.ind, "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_images_round_1) with open(pipeline_args.tilt_ind, "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_particles_round_1) created_rounds.append(pipeline_args.outdir)
def fake_outlier_main(): round_outdir = tmp_path / "pipeline" / f"round_{len(outlier_rounds) + 1}" combined_dir = round_outdir / "outlier_detection" / "data" / "combined_results" combined_dir.mkdir(parents=True, exist_ok=True) image_ids = combined_images_round_1 if not outlier_rounds else combined_images_round_2 particle_ids = combined_particles_round_1 if not outlier_rounds else combined_particles_round_2 with open(combined_dir / "combined_image_inliers_4.pkl", "wb") as f: pickle.dump(image_ids, f) with open(combined_dir / "combined_image_outliers_4.pkl", "wb") as f: pickle.dump(np.array([], dtype=np.int32), f) with open(combined_dir / "combined_particle_inliers_4.pkl", "wb") as f: pickle.dump(particle_ids, f) with open(combined_dir / "combined_particle_outliers_4.pkl", "wb") as f: pickle.dump(np.array([], dtype=np.int32), f) outlier_rounds.append(str(round_outdir))
created_rounds = [] outlier_rounds = [] monkeypatch.setattr( pipeline_with_outliers, "standard_recovar_pipeline", fake_standard_recovar_pipeline, ) import recovar.commands.outlier_detection as outlier_detection
monkeypatch.setattr(outlier_detection, "main", fake_outlier_main)
pipeline_with_outliers._run_pipeline_with_outlier_removal_impl(args)
with open(tmp_path / "pipeline" / "particle_inliers_round_1.pkl", "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_particles_round_1) with open(tmp_path / "pipeline" / "round_2" / "particle_inliers_round_1.pkl", "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_particles_round_1)
def test_pipeline_with_outliers_preserves_initial_subset_index_space_between_rounds(tmp_path, monkeypatch): args = _make_args(tmp_path, tilt_series=True) initial_images = np.array([100, 110, 120, 130], dtype=np.int32) initial_particles = np.array([7, 11, 13], dtype=np.int32) initial_ind = tmp_path / "initial_ind.pkl" initial_tilt_ind = tmp_path / "initial_particle_ind.pkl" with open(initial_ind, "wb") as f: pickle.dump(initial_images, f) with open(initial_tilt_ind, "wb") as f: pickle.dump(initial_particles, f) args.ind = str(initial_ind) args.tilt_ind = str(initial_tilt_ind)
combined_images_round_1 = np.array([110, 120], dtype=np.int32) combined_particles_round_1 = np.array([11], dtype=np.int32) combined_images_round_2 = np.array([120], dtype=np.int32) combined_particles_round_2 = np.array([11], dtype=np.int32)
monkeypatch.setattr(pipeline_with_outliers, "add_args", lambda parser: None) monkeypatch.setattr(argparse.ArgumentParser, "parse_args", lambda self: args) monkeypatch.setattr(pipeline_with_outliers.output, "mkdir_safe", os.makedirs) monkeypatch.setattr(pipeline_with_outliers.output, "PipelineOutput", lambda outdir: _FakePO()) monkeypatch.setattr( pipeline_with_outliers.output, "standard_pipeline_plots", lambda *unused, **unused_kwargs: None, )
def fake_standard_recovar_pipeline(pipeline_args): _write_round_artifacts(tmp_path / "pipeline" / f"round_{len(created_rounds) + 1}") if len(created_rounds) == 0: with open(pipeline_args.ind, "rb") as f: np.testing.assert_array_equal(pickle.load(f), initial_images) with open(pipeline_args.tilt_ind, "rb") as f: np.testing.assert_array_equal(pickle.load(f), initial_particles) else: with open(pipeline_args.ind, "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_images_round_1) with open(pipeline_args.tilt_ind, "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_particles_round_1) created_rounds.append(pipeline_args.outdir)
def fake_outlier_main(): round_outdir = tmp_path / "pipeline" / f"round_{len(outlier_rounds) + 1}" combined_dir = round_outdir / "outlier_detection" / "data" / "combined_results" combined_dir.mkdir(parents=True, exist_ok=True) image_ids = combined_images_round_1 if not outlier_rounds else combined_images_round_2 particle_ids = combined_particles_round_1 if not outlier_rounds else combined_particles_round_2 with open(combined_dir / "combined_image_inliers_4.pkl", "wb") as f: pickle.dump(image_ids, f) with open(combined_dir / "combined_image_outliers_4.pkl", "wb") as f: pickle.dump(np.array([], dtype=np.int32), f) with open(combined_dir / "combined_particle_inliers_4.pkl", "wb") as f: pickle.dump(particle_ids, f) with open(combined_dir / "combined_particle_outliers_4.pkl", "wb") as f: pickle.dump(np.array([], dtype=np.int32), f) outlier_rounds.append(str(round_outdir))
created_rounds = [] outlier_rounds = [] monkeypatch.setattr( pipeline_with_outliers, "standard_recovar_pipeline", fake_standard_recovar_pipeline, ) import recovar.commands.outlier_detection as outlier_detection
monkeypatch.setattr(outlier_detection, "main", fake_outlier_main)
pipeline_with_outliers._run_pipeline_with_outlier_removal_impl(args)
with open(tmp_path / "pipeline" / "inliers_round_1.pkl", "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_images_round_1) with open(tmp_path / "pipeline" / "particle_inliers_round_1.pkl", "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_particles_round_1) with open(tmp_path / "pipeline" / "round_2" / "inliers_round_1.pkl", "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_images_round_1) with open(tmp_path / "pipeline" / "round_2" / "particle_inliers_round_1.pkl", "rb") as f: np.testing.assert_array_equal(pickle.load(f), combined_particles_round_1)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495from types import SimpleNamespace
import numpy as npimport pytestimport matplotlib.pyplot as plt
pytest.importorskip("jax")
from recovar.output import plot_utils
pytestmark = pytest.mark.unit
class _FakePipelineOutput: def __init__(self, values): self._values = values
def get(self, key): return self._values.get(key)
def test_plot_noise_profile_1d(): po = _FakePipelineOutput( { "noise_var_used": np.linspace(1.0, 2.0, 16).astype(np.float32), "input_args": SimpleNamespace(ignore_zero_frequency=False), "image_PS": np.linspace(1.2, 2.2, 16).astype(np.float32), "std_image_PS": np.full(16, 0.1, dtype=np.float32), "masked_image_PS": None, "std_masked_image_PS": None, "noise_var_from_hf": None, "radial_noise_var_outside_mask": None, } ) fig, ax = plot_utils.plot_noise_profile(po, yscale="linear") assert fig is not None and ax is not None
def test_plot_noise_profile_2d_per_tilt(): po = _FakePipelineOutput( { "noise_var_used": np.stack( [ np.linspace(1.0, 1.5, 12), np.linspace(1.1, 1.6, 12), np.linspace(1.2, 1.7, 12), ], axis=0, ).astype(np.float32), "input_args": SimpleNamespace(ignore_zero_frequency=True), "image_PS": None, "std_image_PS": None, "masked_image_PS": np.linspace(1.0, 2.0, 12).astype(np.float32), "std_masked_image_PS": np.full(12, 0.05, dtype=np.float32), "noise_var_from_hf": np.linspace(0.8, 0.9, 12).astype(np.float32), "radial_noise_var_outside_mask": np.linspace(0.7, 0.85, 12).astype(np.float32), } ) fig, ax = plot_utils.plot_noise_profile(po, yscale="log") assert fig is not None and ax is not None
def test_plot_summary_t_prefers_selective_get_u_real_api(): calls = {"get_u_real": 0}
class _PO: def get(self, key): if key == "u_real": raise AssertionError("legacy get('u_real') path should not be used") if key in {"mean", "volume_mask", "variance"}: return np.zeros(8, dtype=np.float32) raise KeyError(key)
def get_u_real(self, n_pcs): calls["get_u_real"] += 1 assert n_pcs == 2 return np.zeros((2, 2, 2, 2), dtype=np.float32)
plot_utils.plot_summary_t(_PO(), n_eigs=2, filename=None) assert calls["get_u_real"] == 1 plt.close("all")
def test_plot_summary_t_clamps_n_eigs_to_available_components(): class _PO: def get(self, key): if key in {"mean", "volume_mask", "variance"}: return np.zeros(8, dtype=np.float32) if key == "u_real": return np.zeros((1, 2, 2, 2), dtype=np.float32) raise KeyError(key)
# Request more eigenvectors than available: should not raise. plot_utils.plot_summary_t(_PO(), n_eigs=5, filename=None) plt.close("all")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import numpy as npimport pytest
jax = pytest.importorskip("jax")import jax.numpy as jnp
from recovar.heterogeneity import adaptive_kernel_discretization as akdfrom recovar.heterogeneity import ppcafrom recovar.core import linalg
pytestmark = pytest.mark.unit
def test_batch_vec_and_unvec_roundtrip_real(): x = np.arange(2 * 3 * 3, dtype=np.float32).reshape(2, 3, 3) v = akd.batch_vec(x) x_rt = akd.batch_unvec(v) assert v.shape == (2, 9) assert x_rt.shape == x.shape assert np.allclose(x_rt, x)
def test_batch_vec_and_unvec_roundtrip_complex(): rng = np.random.default_rng(0) xr = rng.normal(size=(4, 2, 2)).astype(np.float32) xi = rng.normal(size=(4, 2, 2)).astype(np.float32) x = xr + 1j * xi v = akd.batch_vec(x) x_rt = akd.batch_unvec(v) assert v.shape == (4, 4) assert x_rt.shape == x.shape assert np.allclose(x_rt, x)
# ---------------------------------------------------------------------------# ppca module tests — M_step_batch, M_step (EM requires full dataset)# ---------------------------------------------------------------------------
def test_M_step_batch_runs_and_accumulates(): """Verify M_step_batch runs without shape errors and accumulates non-trivially.""" from recovar import core
rng = np.random.default_rng(10) grid_size = 4 image_shape = (grid_size, grid_size) volume_shape = (grid_size, grid_size, grid_size) volume_size = int(np.prod(volume_shape)) n_images = 3 basis_size = 2 voxel_size = 1.0
n_pixels = int(np.prod(image_shape)) images = (rng.normal(size=(n_images, n_pixels)) + 1j * rng.normal(size=(n_images, n_pixels))).astype(np.complex64) # Realistic CTF params: DFU, DFV, DFANG, VOLT, CS, W, PHASE_SHIFT, BFACTOR, CONTRAST CTF_params = np.zeros((n_images, 9), dtype=np.float32) CTF_params[:, 0] = 15000.0 # DFU (Angstrom) CTF_params[:, 1] = 15000.0 # DFV (Angstrom) CTF_params[:, 3] = 300.0 # VOLT (kV) CTF_params[:, 4] = 2.7 # CS (mm) CTF_params[:, 5] = 0.1 # W (amplitude contrast) CTF_params[:, 8] = 1.0 # CONTRAST rotation_matrices = np.tile(np.eye(3, dtype=np.float32), (n_images, 1, 1)) translations = np.zeros((n_images, 2), dtype=np.float32) noise_variance = np.ones((n_images, n_pixels), dtype=np.float32)
latent_means = rng.normal(size=(n_images, basis_size)).astype(np.float32) latent_covs = np.tile(np.eye(basis_size, dtype=np.float32), (n_images, 1, 1)) * 0.1
lhs = jnp.zeros((volume_size, basis_size * basis_size), dtype=np.complex64) rhs = jnp.zeros((volume_size, basis_size), dtype=np.complex64)
lhs_out, rhs_out = ppca.M_step_batch( images, lhs, rhs, latent_means, latent_covs, CTF_params, rotation_matrices, translations, image_shape, volume_shape, grid_size, voxel_size, noise_variance, core.CTFEvaluator(), )
assert lhs_out.shape == (volume_size, basis_size * basis_size) assert rhs_out.shape == (volume_size, basis_size) assert np.all(np.isfinite(np.asarray(lhs_out))) assert np.all(np.isfinite(np.asarray(rhs_out))) # At least some voxels should have non-zero accumulations assert np.any(np.asarray(lhs_out) != 0) assert np.any(np.asarray(rhs_out) != 0)
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
@pytest.mark.gpudef test_batch_vec_unvec_roundtrip_gpu(gpu_device): x = np.arange(2 * 3 * 3, dtype=np.float32).reshape(2, 3, 3)
cpu_v = np.asarray(akd.batch_vec(x)) cpu_rt = np.asarray(akd.batch_unvec(cpu_v))
with jax.default_device(gpu_device): x_g = jax.device_put(jnp.array(x), gpu_device) gpu_v = np.asarray(akd.batch_vec(x_g)) gpu_rt = np.asarray(akd.batch_unvec(gpu_v))
np.testing.assert_allclose(cpu_v, gpu_v, atol=1e-5, rtol=1e-5) np.testing.assert_allclose(cpu_rt, gpu_rt, atol=1e-5, rtol=1e-5)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679import numpy as npimport pytest
pytest.importorskip("jax")
from helpers.tiny_synthetic import make_tiny_cryo_dataset_with_images, make_tiny_simulation
import recovar.core as coreimport recovar.heterogeneity.principal_components as pcfrom recovar.data_io import cryoem_dataset as datasetfrom recovar.reconstruction.homogeneous import MeanEstimatefrom recovar.utils.helpers import AlgorithmOptions
def _make_means(vol_size, dtype_real=np.float32, dtype_complex=np.complex64): """Create a MeanEstimate with dummy data for testing.""" return MeanEstimate( combined=np.ones(vol_size, dtype=dtype_complex), corrected0=np.ones(vol_size, dtype=dtype_complex), corrected1=np.ones(vol_size, dtype=dtype_complex), corrected0reg=np.ones(vol_size, dtype=dtype_complex), corrected1reg=np.ones(vol_size, dtype=dtype_complex), lhs=np.ones(vol_size, dtype=dtype_real), prior=np.ones(vol_size, dtype=dtype_real), )
pytestmark = pytest.mark.unit
def test_zero_boundary_mask_has_expected_structure(): m = pc.get_zero_boundary_mask((4, 4, 4), dtype=np.float32).reshape(4, 4, 4) assert np.all(m[0, :, :] == 0) assert np.all(m[:, 0, :] == 0) assert np.all(m[:, :, 0] == 0) assert np.all(m[1:, 1:, 1:] == 1)
def test_minus_index_negates_frequencies(): volume_shape = (4, 4, 4) idx = np.arange(np.prod(volume_shape)) minus_idx = np.asarray(pc.get_minus_vec_index(idx, volume_shape)) freqs = np.asarray(core.vec_indices_to_frequencies(idx, volume_shape)) minus_freqs = np.asarray(core.vec_indices_to_frequencies(minus_idx, volume_shape)) # Exclude Nyquist boundary where mapping is not strictly invertible on the wrapped grid. interior = np.all(np.abs(freqs) < (volume_shape[0] // 2), axis=1) np.testing.assert_array_equal(minus_freqs[interior], -freqs[interior])
def test_make_symmetric_columns_matches_numpy_version(): volume_shape = (4, 4, 4) vol_size = int(np.prod(volume_shape)) n_cols = 5 rng = np.random.default_rng(0)
columns = (rng.normal(size=(vol_size, n_cols)) + 1j * rng.normal(size=(vol_size, n_cols))).astype(np.complex64) picked = rng.choice(vol_size, size=n_cols, replace=False)
cols_a, minus_a, good_a = pc.make_symmetric_columns(columns, picked, volume_shape) cols_b, minus_b, good_b = pc.make_symmetric_columns_np(columns, picked, volume_shape)
np.testing.assert_allclose(np.asarray(cols_a), np.asarray(cols_b), atol=1e-6, rtol=1e-6) np.testing.assert_array_equal(np.asarray(minus_a), np.asarray(minus_b)) np.testing.assert_array_equal(np.asarray(good_a), np.asarray(good_b))
def test_flip_vec_and_batch_flip_vec2_shapes(): volume_shape = (4, 4, 4) vol_size = int(np.prod(volume_shape)) col = np.arange(vol_size, dtype=np.float32).astype(np.complex64) flipped = np.asarray(pc.flip_vec(col, volume_shape)) assert flipped.shape == (vol_size,)
cols = np.stack([col, col * 2], axis=1).astype(np.complex64) out = pc.batch_flip_vec2(cols, volume_shape) assert out.shape == (2, vol_size)
@pytest.mark.parametrize("grid_size", [4, 8, 16, 32])def test_flip_columns_structured_matches_batch_flip_vec2(grid_size): """flip_columns_structured (JAX CPU flip+conj) must return the same result as the legacy batch_flip_vec2 (fancy-indexed flip) for all grid sizes.""" volume_shape = (grid_size, grid_size, grid_size) vol_size = int(np.prod(volume_shape)) n_cols = 5
rng = np.random.default_rng(42) columns = (rng.standard_normal((vol_size, n_cols)) + 1j * rng.standard_normal((vol_size, n_cols))).astype( np.complex64 )
old_result = pc.batch_flip_vec2(columns, volume_shape).T # (vol_size, n_cols) new_result = pc.flip_columns_structured(columns, volume_shape) # (vol_size, n_cols)
assert old_result.shape == new_result.shape np.testing.assert_allclose(new_result, old_result, rtol=1e-6, atol=1e-7)
def test_idft_from_both_sides_calls_batch_idft3(monkeypatch): calls = {"n": 0}
def _fake_batch_idft3(x, shape, batch_size): calls["n"] += 1 return x
monkeypatch.setattr(pc.linalg, "batch_idft3", _fake_batch_idft3) x = np.ones((4, 3), dtype=np.complex64) out = pc.IDFT_from_both_sides(x, (2, 2, 1), (2, 2, 1), 2, 2) assert out.shape == x.shape assert calls["n"] == 2
def test_get_all_copied_columns_shapes(): volume_shape = (4, 4, 4) vol_size = int(np.prod(volume_shape)) rng = np.random.default_rng(0) cols = (rng.normal(size=(vol_size, 4)) + 1j * rng.normal(size=(vol_size, 4))).astype(np.complex64) picked = rng.choice(vol_size, size=4, replace=False)
all_cols, all_freqs = pc.get_all_copied_columns(cols, picked, volume_shape) assert all_cols.shape[0] == vol_size assert all_cols.shape[1] >= cols.shape[1] assert all_freqs.shape[0] == all_cols.shape[1]
def test_expanded_real_column_count_includes_hermitian_copies(): volume_shape = (4, 4, 4) freqs = np.array( [ [0, 0, 0], [1, 0, 0], [-1, 0, 0], [0, 1, 0], ] ) picked = np.asarray(core.frequencies_to_vec_indices(freqs, volume_shape))
assert pc._expanded_real_column_count(picked, volume_shape) == 5
def test_randomized_svd_block_memory_caps_large_grid_only(): assert pc._randomized_svd_block_memory_to_use(80, (128, 128, 128)) == 80 assert pc._randomized_svd_block_memory_to_use(80, (256, 256, 256)) == 16 assert pc._randomized_svd_block_memory_to_use(12, (256, 256, 256)) == 12
def test_randomized_real_svd_caps_sketch_to_expanded_columns(monkeypatch): volume_shape = (4, 4, 4) vol_size = int(np.prod(volume_shape)) picked = np.asarray( core.frequencies_to_vec_indices( np.array( [ [0, 0, 0], [1, 0, 0], [0, 1, 0], ] ), volume_shape, ) ) expanded_count = pc._expanded_real_column_count(picked, volume_shape)
def fake_right_matvec(test_mat, *args, **kwargs): assert test_mat.shape == (vol_size, expanded_count) return np.eye(vol_size, expanded_count, dtype=np.float32)
def fake_left_matvec(q, *args, **kwargs): assert q.shape == (vol_size, expanded_count) return np.eye(expanded_count, dtype=np.float32)
monkeypatch.setattr(pc, "right_matvec_with_spatial_Sigma", fake_right_matvec) monkeypatch.setattr(pc, "left_matvec_with_spatial_Sigma", fake_left_matvec) monkeypatch.setattr(pc.linalg, "batch_dft3", lambda q, volume_shape, vol_batch_size: np.asarray(q)) monkeypatch.setattr(pc.linalg, "blockwise_A_X", lambda a, x, memory_to_use=None: np.asarray(a) @ np.asarray(x))
q, s, v = pc.randomized_real_svd_of_columns( columns=np.ones((vol_size, picked.size), dtype=np.complex64), picked_frequency_indices=picked, volume_mask=np.ones(vol_size, dtype=np.float32), volume_shape=volume_shape, vol_batch_size=1, test_size=10, gpu_memory_to_use=8, random_seed=5, )
assert q.shape == (vol_size, expanded_count) assert s.shape == (expanded_count,) assert v.shape == (expanded_count, expanded_count)
def test_get_cov_svds_delegates_to_randomized_svd(monkeypatch): called = {}
def fake_randomized_real_svd_of_columns(*args, **kwargs): called["args"] = args called["kwargs"] = kwargs u = np.eye(3, dtype=np.float32) s = np.array([3.0, 2.0, 1.0], dtype=np.float32) vh = np.eye(3, dtype=np.float32) return u, s, vh
monkeypatch.setattr(pc, "randomized_real_svd_of_columns", fake_randomized_real_svd_of_columns)
cov_cols = {"est_mask": np.ones((3, 2), dtype=np.complex64)} u_real, s_real = pc.get_cov_svds( covariance_cols=cov_cols, picked_frequencies=np.array([0, 1]), volume_mask=np.ones(3, dtype=np.float32), volume_shape=(1, 1, 3), vol_batch_size=2, gpu_memory_to_use=8, ignore_zero_frequency=False, randomized_sketch_size=5, ) np.testing.assert_array_equal(u_real, np.eye(3, dtype=np.float32)) np.testing.assert_array_equal(s_real, np.array([3.0, 2.0, 1.0], dtype=np.float32)) assert called["kwargs"]["test_size"] == 5
def test_get_cov_svds_passes_random_seed(monkeypatch): called = {}
def fake_randomized_real_svd_of_columns(*args, **kwargs): called["kwargs"] = kwargs return np.eye(3, dtype=np.float32), np.array([3.0, 2.0, 1.0], dtype=np.float32), np.eye(3, dtype=np.float32)
monkeypatch.setattr(pc, "randomized_real_svd_of_columns", fake_randomized_real_svd_of_columns)
pc.get_cov_svds( covariance_cols={"est_mask": np.ones((3, 2), dtype=np.complex64)}, picked_frequencies=np.array([0, 1]), volume_mask=np.ones(3, dtype=np.float32), volume_shape=(1, 1, 3), vol_batch_size=2, gpu_memory_to_use=8, ignore_zero_frequency=False, randomized_sketch_size=5, random_seed=19, )
assert called["kwargs"]["random_seed"] == 19
def test_projected_covariance_batch_size_uses_requested_gpu_budget(monkeypatch): """``_projected_covariance_batch_size`` delegates to ``get_embedding_batch_size`` with the legacy 2·P²·8B reservation.""" calls = {}
def fake_get_embedding_batch_size(basis, image_size, contrast_grid, zdim, gpu_memory): calls["gpu_memory"] = gpu_memory calls["basis_shape"] = basis.shape calls["image_size"] = image_size calls["zdim"] = zdim return 7
monkeypatch.setattr(pc.utils, "get_embedding_batch_size", fake_get_embedding_batch_size) monkeypatch.setattr(pc.utils, "get_gpu_memory_total", lambda: 100.0)
basis = np.ones((8, 3), dtype=np.float32) out = pc._projected_covariance_batch_size( basis=basis, image_size=16, basis_size=3, gpu_memory_to_use=8.0, )
assert out == 7 assert calls["basis_shape"] == basis.shape assert calls["image_size"] == 16 assert calls["zdim"] == 3 lhs_dim = pc.covariance_estimation._symmetric_matrix_packed_size(3) expected_budget = 8.0 - 2 * lhs_dim**2 * 8 / 1e9 assert calls["gpu_memory"] == pytest.approx(expected_budget)
def test_randomized_real_svd_of_columns_is_deterministic_for_fixed_seed(monkeypatch): monkeypatch.setattr(pc.utils, "report_memory_device", lambda logger=None: None) monkeypatch.setattr(pc.jax, "device_put", lambda x, device=None: x) monkeypatch.setattr( pc, "right_matvec_with_spatial_Sigma", lambda test_mat, *args, **kwargs: np.asarray(test_mat[:, :2], dtype=np.float32), ) monkeypatch.setattr( pc, "left_matvec_with_spatial_Sigma", lambda q, *args, **kwargs: np.asarray(q.T, dtype=np.float32), ) monkeypatch.setattr(pc.linalg, "batch_dft3", lambda q, volume_shape, vol_batch_size: np.asarray(q)) monkeypatch.setattr(pc.linalg, "blockwise_A_X", lambda a, x, memory_to_use=None: np.asarray(a) @ np.asarray(x))
common = dict( columns=np.ones((8, 2), dtype=np.complex64), picked_frequency_indices=np.array([0, 1], dtype=np.int32), volume_mask=np.ones(8, dtype=np.float32), volume_shape=(2, 2, 2), vol_batch_size=1, test_size=4, gpu_memory_to_use=8, )
q1, s1, v1 = pc.randomized_real_svd_of_columns(**common, random_seed=5) q2, s2, v2 = pc.randomized_real_svd_of_columns(**common, random_seed=5) q3, s3, v3 = pc.randomized_real_svd_of_columns(**common, random_seed=6)
np.testing.assert_allclose(q1, q2) np.testing.assert_allclose(s1, s2) np.testing.assert_allclose(v1, v2) assert (not np.allclose(q1, q3)) or (not np.allclose(v1, v3)) or (not np.allclose(s1, s3))
def test_pca_by_projected_covariance_sorts_and_clamps_eigs(monkeypatch): cryos = type("Cryo", (), {"image_size": 16})() basis = np.eye(3, dtype=np.float32) mean = np.zeros(3, dtype=np.complex64) volume_mask = np.ones(3, dtype=np.float32)
monkeypatch.setattr(pc.utils, "get_gpu_memory_total", lambda: 100.0) monkeypatch.setattr(pc.utils, "get_embedding_batch_size", lambda *args, **kwargs: 2)
def fake_projected_covariance(*args, **kwargs): # Eigenvalues are [3, -1, 2] => sorted desc [3,2,-1], then clamp last to EPSILON. return np.diag(np.array([3.0, -1.0, 2.0], dtype=np.float64))
monkeypatch.setattr(pc.covariance_estimation, "compute_projected_covariance", fake_projected_covariance)
u, s = pc.pca_by_projected_covariance( dataset=cryos, basis=basis, mean=mean, volume_mask=volume_mask, disc_type="linear_interp", disc_type_u="linear_interp", gpu_memory_to_use=8, n_pcs_to_compute=3, ) assert u.shape == (3, 3) assert s.shape == (3,) assert s[0] >= s[1] >= s[2] assert s[2] == pytest.approx(pc.jax_config.EPSILON)
def test_unused_diagnostic_functions_removed(): assert not hasattr(pc, "test_different_embeddings") assert not hasattr(pc, "test_different_embeddings_from_volumes") assert not hasattr(pc, "test_different_embeddings_from_variance")
def test_estimate_principal_components_high_snr_from_var_est_requires_variance(): mock_cryo = type( "Cryo", (), { "volume_shape": (2, 2, 2), "grid_size": 2, "volume_size": 8, "dtype": np.complex64, "image_size": 4, }, )() cryos = mock_cryo means = _make_means(8) options = AlgorithmOptions( volume_mask_option="none", zs_dim_to_test=[4], contrast="none", ignore_zero_frequency=False, keep_intermediate=True, ) cov_options = { "column_sampling_scheme": "high_snr_from_var_est", "sampling_n_cols": 2, "sampling_avoid_in_radius": 0, "randomize_column_sampling": False, "randomized_sketch_size": 2, "disc_type": "linear_interp", "disc_type_u": "linear_interp", "mask_images_in_proj": False, "n_pcs_to_compute": 2, }
with pytest.raises(ValueError, match="variance_estimate must be provided"): pc.estimate_principal_components( dataset=cryos, options=options, means=means, mean_prior=np.zeros(8, dtype=np.complex64), volume_mask=np.ones(8, dtype=np.float32), dilated_volume_mask=np.ones(8, dtype=np.float32), valid_idx=np.arange(2), batch_size=1, gpu_memory_to_use=8, covariance_options=cov_options, variance_estimate=None, )
def test_estimate_principal_components_low_freqs_pipeline(monkeypatch): mock_cryo = type( "Cryo", (), { "volume_shape": (2, 2, 2), "grid_size": 2, "volume_size": 8, "dtype": np.complex64, "image_size": 4, }, )() cryos = mock_cryo means = _make_means(8) options = AlgorithmOptions( volume_mask_option="none", zs_dim_to_test=[4], contrast="none", ignore_zero_frequency=False, keep_intermediate=False, ) cov_options = { "column_sampling_scheme": "low_freqs", "column_radius": 1, "randomized_sketch_size": 2, "disc_type": "linear_interp", "disc_type_u": "linear_interp", "mask_images_in_proj": False, "n_pcs_to_compute": 2, }
monkeypatch.setattr( pc.utils, "get_vol_batch_size", lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("planner volume batch override ignored")), ) monkeypatch.setattr( pc.covariance_estimation, "compute_regularized_covariance_columns_in_batch", lambda *args, **kwargs: ( {"est_mask": np.ones((8, 2), dtype=np.complex64)}, np.array([0, 1]), np.array([0.1, 0.2]), ), ) captured = {}
def _fake_get_cov_svds(*args, **kwargs): captured["vol_batch_size"] = args[4] return np.ones((8, 2), dtype=np.float32), np.array([2.0, 1.0], dtype=np.float32)
monkeypatch.setattr(pc, "get_cov_svds", _fake_get_cov_svds) monkeypatch.setattr( pc, "pca_by_projected_covariance", lambda *args, **kwargs: ( np.ones((8, 2), dtype=np.complex64), np.array([2.0, 1.0], dtype=np.float32), ), )
u, s, covariance_cols, picked_frequencies, column_fscs = pc.estimate_principal_components( dataset=cryos, options=options, means=means, mean_prior=np.zeros(8, dtype=np.complex64), volume_mask=np.ones(8, dtype=np.float32), dilated_volume_mask=np.ones(8, dtype=np.float32), valid_idx=np.arange(2), batch_size=1, gpu_memory_to_use=8, covariance_options=cov_options, vol_batch_size=3, )
assert u["rescaled"].shape == (8, 2) assert captured["vol_batch_size"] == 3 np.testing.assert_array_equal(s["rescaled"], np.array([2.0, 1.0], dtype=np.float32)) np.testing.assert_array_equal(picked_frequencies, np.array([0, 1])) np.testing.assert_array_equal(column_fscs, np.array([0.1, 0.2])) assert covariance_cols["est_mask"] is None
def test_estimate_principal_components_with_real_tiny_dataset(monkeypatch): # Build a real tiny CryoEMDataset from simulator outputs. _, ctf_params, rots, trans, _, voxel_size, _ = make_tiny_simulation(grid_size=4, n_images=6, seed=0) metadata = dataset.ImageMetadata(rots, trans, ctf_params) cryo = dataset.CryoEMDataset( image_source=None, voxel_size=voxel_size, metadata=metadata, ctf_evaluator=core.CTFEvaluator(), grid_size=4, ) cryos = cryo
means = _make_means(cryo.volume_size) options = AlgorithmOptions( volume_mask_option="none", zs_dim_to_test=[4], contrast="none", ignore_zero_frequency=False, keep_intermediate=False, ) cov_options = { "column_sampling_scheme": "low_freqs", "column_radius": 1, "randomized_sketch_size": 2, "disc_type": "linear_interp", "disc_type_u": "linear_interp", "mask_images_in_proj": False, "n_pcs_to_compute": 2, }
monkeypatch.setattr(pc.utils, "get_vol_batch_size", lambda *args, **kwargs: 1) monkeypatch.setattr( pc.covariance_estimation, "compute_regularized_covariance_columns_in_batch", lambda *args, **kwargs: ( {"est_mask": np.ones((cryo.volume_size, 2), dtype=np.complex64)}, np.array([0, 1]), np.array([0.1, 0.2]), ), ) monkeypatch.setattr( pc, "get_cov_svds", lambda *args, **kwargs: ( np.ones((cryo.volume_size, 2), dtype=np.float32), np.array([2.0, 1.0], dtype=np.float32), ), ) monkeypatch.setattr( pc, "pca_by_projected_covariance", lambda *args, **kwargs: ( np.ones((cryo.volume_size, 2), dtype=np.complex64), np.array([2.0, 1.0], dtype=np.float32), ), )
u, s, covariance_cols, picked_frequencies, column_fscs = pc.estimate_principal_components( dataset=cryos, options=options, means=means, mean_prior=np.zeros(cryo.volume_size, dtype=np.complex64), volume_mask=np.ones(cryo.volume_size, dtype=np.float32), dilated_volume_mask=np.ones(cryo.volume_size, dtype=np.float32), valid_idx=np.arange(cryo.n_images), batch_size=2, gpu_memory_to_use=8, covariance_options=cov_options, )
assert u["rescaled"].shape == (cryo.volume_size, 2) np.testing.assert_array_equal(s["rescaled"], np.array([2.0, 1.0], dtype=np.float32)) np.testing.assert_array_equal(picked_frequencies, np.array([0, 1])) np.testing.assert_array_equal(column_fscs, np.array([0.1, 0.2])) assert covariance_cols["est_mask"] is None
def test_pca_by_projected_covariance_real_tiny_dataset_runs(): # grid_size>=6 required: simulator noise interpolation produces NaN at grid_size=4 # (only 1 radial frequency bin → scipy interp1d divides by zero) cryo = make_tiny_cryo_dataset_with_images(grid_size=6, n_images=6, seed=0) basis = np.eye(cryo.volume_size, 4, dtype=np.complex64)
u, s = pc.pca_by_projected_covariance( dataset=cryo, basis=basis, mean=np.zeros(cryo.volume_size, dtype=np.complex64), volume_mask=np.ones(cryo.volume_shape, dtype=np.float32), disc_type="linear_interp", disc_type_u="linear_interp", gpu_memory_to_use=8, use_mask=False, n_pcs_to_compute=2, )
assert u.shape == (cryo.volume_size, 2) assert s.shape == (2,) assert np.isfinite(s).all() assert np.all(s >= pc.jax_config.EPSILON) assert np.all(s[:-1] >= s[1:]) u_np = np.asarray(u) assert np.isfinite(u_np).all() gram = u_np.T @ u_np np.testing.assert_allclose(gram, np.eye(2), atol=5e-4, rtol=5e-4)
def test_pca_by_projected_covariance_cubic_mean_tiny_dataset_runs(): cryo = make_tiny_cryo_dataset_with_images(grid_size=6, n_images=6, seed=0) basis = np.eye(cryo.volume_size, 4, dtype=np.complex64)
u, s = pc.pca_by_projected_covariance( dataset=cryo, basis=basis, mean=np.zeros(cryo.volume_size, dtype=np.complex64), volume_mask=np.ones(cryo.volume_shape, dtype=np.float32), disc_type="cubic", disc_type_u="linear_interp", gpu_memory_to_use=8, use_mask=False, n_pcs_to_compute=2, )
assert u.shape == (cryo.volume_size, 2) assert s.shape == (2,) assert np.isfinite(s).all() assert np.all(s >= pc.jax_config.EPSILON) assert np.all(s[:-1] >= s[1:]) u_np = np.asarray(u) assert np.isfinite(u_np).all()
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
import jaximport jax.numpy as jnp
@pytest.mark.gpudef test_flip_vec_gpu(gpu_device): volume_shape = (4, 4, 4) vol_size = int(np.prod(volume_shape)) col = np.arange(vol_size, dtype=np.float32).astype(np.complex64)
cpu_flipped = np.asarray(pc.flip_vec(col, volume_shape))
with jax.default_device(gpu_device): col_g = jax.device_put(jnp.array(col), gpu_device) gpu_flipped = np.asarray(pc.flip_vec(col_g, volume_shape))
np.testing.assert_allclose(cpu_flipped, gpu_flipped, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_batch_flip_vec2_gpu(gpu_device): volume_shape = (4, 4, 4) vol_size = int(np.prod(volume_shape)) col = np.arange(vol_size, dtype=np.float32).astype(np.complex64) cols = np.stack([col, col * 2], axis=1).astype(np.complex64)
cpu_out = np.asarray(pc.batch_flip_vec2(cols, volume_shape))
with jax.default_device(gpu_device): cols_g = jax.device_put(jnp.array(cols), gpu_device) gpu_out = np.asarray(pc.batch_flip_vec2(cols_g, volume_shape))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_make_symmetric_columns_gpu(gpu_device): volume_shape = (4, 4, 4) vol_size = int(np.prod(volume_shape)) n_cols = 5 rng = np.random.default_rng(0)
columns = (rng.normal(size=(vol_size, n_cols)) + 1j * rng.normal(size=(vol_size, n_cols))).astype(np.complex64) picked = rng.choice(vol_size, size=n_cols, replace=False)
cpu_cols, cpu_minus, cpu_good = pc.make_symmetric_columns(columns, picked, volume_shape) cpu_cols = np.asarray(cpu_cols) cpu_minus = np.asarray(cpu_minus) cpu_good = np.asarray(cpu_good)
with jax.default_device(gpu_device): columns_g = jax.device_put(jnp.array(columns), gpu_device) picked_g = jax.device_put(jnp.array(picked), gpu_device) gpu_cols, gpu_minus, gpu_good = pc.make_symmetric_columns(columns_g, picked_g, volume_shape) gpu_cols = np.asarray(gpu_cols) gpu_minus = np.asarray(gpu_minus) gpu_good = np.asarray(gpu_good)
np.testing.assert_allclose(cpu_cols, gpu_cols, atol=1e-5, rtol=1e-5) np.testing.assert_array_equal(cpu_minus, gpu_minus) np.testing.assert_array_equal(cpu_good, gpu_good)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297"""Unit tests for recovar.project (RecovarProject, registry, job_context)."""
import argparseimport jsonimport os
import pytest
from recovar.project.project import RecovarProject, default_job_alias, find_project_rootfrom recovar.project.registry import JOB_TYPES, get_job_type
pytestmark = pytest.mark.unit
# ---------------------------------------------------------------------------# Registry tests# ---------------------------------------------------------------------------
class TestRegistry: def test_all_commands_have_types(self): expected = { "pipeline", "analyze", "compute_state", "compute_trajectory", "estimate_conformational_density", "estimate_stable_states", "junk_particle_detection", "outlier_detection", "postprocess", "downsample", "extract_image_subset", "extract_image_subset_from_kmeans", "pipeline_with_outliers", "reconstruct_from_external_embedding", } assert expected.issubset(set(JOB_TYPES.keys()))
def test_get_job_type(self): jt = get_job_type("pipeline") assert jt.name == "Pipeline" assert jt.dir_name == "Pipeline" assert jt.produces_volumes is True
def test_get_job_type_unknown(self): assert get_job_type("nonexistent") is None
def test_dir_names_are_camelcase(self): for jt in JOB_TYPES.values(): assert jt.dir_name[0].isupper(), f"{jt.command} dir_name should be CamelCase"
# ---------------------------------------------------------------------------# RecovarProject tests# ---------------------------------------------------------------------------
class TestRecovarProject: def test_init_creates_project_json(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "myproj")) assert os.path.isfile(os.path.join(proj.root, "project.json")) with open(os.path.join(proj.root, "project.json")) as f: data = json.load(f) assert data["version"] == "1.0" assert data["name"] == "myproj"
def test_init_with_name(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p"), name="My Analysis") with open(os.path.join(proj.root, "project.json")) as f: data = json.load(f) assert data["name"] == "My Analysis"
def test_init_idempotent(self, tmp_path): proj1 = RecovarProject.init(str(tmp_path / "p")) proj2 = RecovarProject.init(str(tmp_path / "p")) assert proj1.root == proj2.root
def test_exists(self, tmp_path): proj = RecovarProject(str(tmp_path / "nope")) assert not proj.exists proj = RecovarProject.init(str(tmp_path / "yes")) assert proj.exists
def test_allocate_job_first(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid, job_dir = proj.allocate_job("compute_state") assert uid == "ReconstructState/job_0001" assert os.path.isdir(job_dir) assert job_dir.endswith("ReconstructState/job_0001")
def test_allocate_job_increments(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid1, _ = proj.allocate_job("compute_state") uid2, _ = proj.allocate_job("compute_state") uid3, _ = proj.allocate_job("compute_state") assert uid1 == "ReconstructState/job_0001" assert uid2 == "ReconstructState/job_0002" assert uid3 == "ReconstructState/job_0003"
def test_allocate_job_per_type(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid_p, _ = proj.allocate_job("pipeline") uid_a, _ = proj.allocate_job("analyze") uid_p2, _ = proj.allocate_job("pipeline") assert uid_p == "Pipeline/job_0001" assert uid_a == "Analyze/job_0001" assert uid_p2 == "Pipeline/job_0002"
def test_register_and_list_jobs(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid, _ = proj.allocate_job("pipeline") proj.register_job_start(uid, "pipeline", "recovar pipeline ...") jobs = proj.list_jobs() assert len(jobs) == 1 assert jobs[0]["uid"] == uid assert jobs[0]["status"] == "running"
def test_register_complete(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid, _ = proj.allocate_job("pipeline") proj.register_job_start(uid, "pipeline") proj.register_job_complete(uid, "completed") jobs = proj.list_jobs() assert jobs[0]["status"] == "completed" assert jobs[0]["completed"] is not None
def test_find_latest_job(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid1, _ = proj.allocate_job("pipeline") proj.register_job_start(uid1, "pipeline") proj.register_job_complete(uid1, "completed") uid2, _ = proj.allocate_job("pipeline") proj.register_job_start(uid2, "pipeline") proj.register_job_complete(uid2, "completed")
latest = proj.find_latest_job("Pipeline") assert latest == "Pipeline/job_0002"
def test_find_latest_job_none(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) assert proj.find_latest_job("Pipeline") is None
def test_resolve_pipeline_absolute(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) abs_path = str(tmp_path / "external_pipeline") os.makedirs(abs_path) resolved = proj.resolve_pipeline(abs_path) assert resolved == abs_path
def test_resolve_pipeline_relative(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid, job_dir = proj.allocate_job("pipeline") resolved = proj.resolve_pipeline("Pipeline/job_0001") assert resolved == job_dir
def test_resolve_pipeline_auto_latest(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid, job_dir = proj.allocate_job("pipeline") proj.register_job_start(uid, "pipeline") proj.register_job_complete(uid, "completed") resolved = proj.resolve_pipeline(None) assert resolved == job_dir
def test_register_job_start_records_unique_alias(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid1, _ = proj.allocate_job("pipeline") proj.register_job_start(uid1, "pipeline", alias="ribosome") uid2, _ = proj.allocate_job("pipeline") proj.register_job_start(uid2, "pipeline", alias="ribosome") jobs = {job["uid"]: job for job in proj.list_jobs()} assert jobs[uid1]["alias"] == "ribosome" assert jobs[uid2]["alias"] == "ribosome_2" assert proj.get_job_alias_map() == {uid1: "ribosome", uid2: "ribosome_2"}
def test_resolve_pipeline_alias(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid, job_dir = proj.allocate_job("pipeline") proj.register_job_start(uid, "pipeline", alias="ribosome_d128") proj.register_job_complete(uid, "completed") assert proj.resolve_pipeline("ribosome_d128") == job_dir
def test_default_job_alias_prefers_explicit_output_name(self): assert default_job_alias("analyze", {"output_name": "My Embedding"}) == "my_embedding"
def test_parent_jobs_tracking(self, tmp_path): proj = RecovarProject.init(str(tmp_path / "p")) uid_p, _ = proj.allocate_job("pipeline") proj.register_job_start(uid_p, "pipeline") proj.register_job_complete(uid_p, "completed")
uid_a, _ = proj.allocate_job("analyze") proj.register_job_start(uid_a, "analyze", parent_jobs=[uid_p]) jobs = proj.list_jobs("Analyze") assert jobs[0]["parent_jobs"] == [uid_p]
# ---------------------------------------------------------------------------# find_project_root tests# ---------------------------------------------------------------------------
class TestFindProjectRoot: def test_finds_in_current_dir(self, tmp_path): (tmp_path / "project.json").write_text("{}") result = find_project_root(str(tmp_path)) assert result == str(tmp_path)
def test_finds_in_parent(self, tmp_path): (tmp_path / "project.json").write_text("{}") subdir = tmp_path / "Pipeline" / "job_0001" subdir.mkdir(parents=True) result = find_project_root(str(subdir)) assert result == str(tmp_path)
def test_returns_none_when_not_found(self, tmp_path): result = find_project_root(str(tmp_path)) assert result is None
# ---------------------------------------------------------------------------# job_context tests# ---------------------------------------------------------------------------
class TestJobContext: def test_project_mode_creates_job_dir(self, tmp_path): from recovar.project.job_context import job_context
proj = RecovarProject.init(str(tmp_path / "p")) args = argparse.Namespace( project=str(tmp_path / "p"), outdir=None, result_dir=None, ) with job_context(args, "pipeline") as ctx: assert ctx.uid == "Pipeline/job_0001" assert os.path.isdir(ctx.output_dir) assert ctx.project is not None
# After context exits, job should be completed jobs = proj.list_jobs() assert any(j["uid"] == "Pipeline/job_0001" and j["status"] == "completed" for j in jobs)
def test_standalone_mode_with_explicit_outdir(self, tmp_path): from recovar.project.job_context import job_context
args = argparse.Namespace( project=None, outdir=str(tmp_path / "my_output"), result_dir=None, ) with job_context(args, "pipeline") as ctx: assert ctx.output_dir == str(tmp_path / "my_output") assert ctx.project is None assert ctx.uid is None
def test_failed_job_records_status(self, tmp_path): from recovar.project.job_context import job_context
proj = RecovarProject.init(str(tmp_path / "p")) args = argparse.Namespace( project=str(tmp_path / "p"), outdir=None, result_dir=None, ) with pytest.raises(RuntimeError): with job_context(args, "pipeline") as ctx: raise RuntimeError("test failure")
jobs = proj.list_jobs() assert any(j["uid"] == "Pipeline/job_0001" and j["status"] == "failed" for j in jobs)
def test_project_mode_resolves_latest_pipeline_when_result_dir_omitted(self, tmp_path): from recovar.project.job_context import job_context
proj = RecovarProject.init(str(tmp_path / "p")) pipeline_uid, pipeline_dir = proj.allocate_job("pipeline") proj.register_job_start(pipeline_uid, "pipeline", alias="sample_pipeline") proj.register_job_complete(pipeline_uid, "completed")
args = argparse.Namespace( project=str(tmp_path / "p"), outdir=None, output_dir=None, output=None, result_dir=None, recovar_result_dir=None, output_name="Embedding K10", ) with job_context(args, "analyze") as ctx: assert ctx.pipeline_dir == pipeline_dir assert ctx.parent_jobs == [pipeline_uid] assert ctx.uid == "Analyze/job_0001"
jobs = proj.list_jobs("Analyze") assert jobs[0]["alias"] == "embedding_k10"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341import numpy as npimport pytest
pytest.importorskip("jax")
from recovar.reconstruction import regularization
pytestmark = pytest.mark.unit
def test_jax_scipy_nd_image_mean_inner_handles_zero_count_indices(): inp = np.array([1.0, 2.0, 3.0], dtype=np.float32) labels = np.array([0, 0, 2], dtype=np.int32) index = np.array([0, 1, 2, 3], dtype=np.int32) out = regularization.jax_scipy_nd_image_mean_inner(inp, labels=labels, index=index) out = np.asarray(out) assert np.all(np.isfinite(out)) assert np.isclose(out[0], 1.5) assert np.isclose(out[1], 0.0) # missing label assert np.isclose(out[2], 3.0) assert np.isclose(out[3], 0.0) # missing label
def test_jax_scipy_nd_image_mean_complex_path_returns_complex64(): inp = np.array([1 + 2j, 3 + 4j], dtype=np.complex64) labels = np.array([0, 0], dtype=np.int32) index = np.array([0], dtype=np.int32) out = regularization.jax_scipy_nd_image_mean(inp, labels=labels, index=index) out = np.asarray(out) assert out.dtype == np.complex64 assert np.isclose(out[0], 2 + 3j)
def test_get_fsc_gpu_returns_finite_values(): shape = (4, 4, 4) rng = np.random.default_rng(0) v1 = (rng.normal(size=np.prod(shape)) + 1j * rng.normal(size=np.prod(shape))).astype(np.complex64) v2 = (rng.normal(size=np.prod(shape)) + 1j * rng.normal(size=np.prod(shape))).astype(np.complex64) fsc = regularization.get_fsc_gpu(v1, v2, shape, substract_shell_mean=False, frequency_shift=0) fsc = np.asarray(fsc) assert fsc.ndim == 1 assert np.all(np.isfinite(fsc))
def test_compute_fsc_prior_gpu_v2_and_prior_iteration_are_finite(): shape = (4, 4, 4) n = int(np.prod(shape)) rng = np.random.default_rng(0)
image0 = (rng.normal(size=n) + 1j * rng.normal(size=n)).astype(np.complex64) image1 = (rng.normal(size=n) + 1j * rng.normal(size=n)).astype(np.complex64) lhs = np.abs(rng.normal(size=n)).astype(np.float32) + 0.5 prior0 = np.ones(n, dtype=np.float32)
prior, fsc_raw, prior_avg = regularization.compute_fsc_prior_gpu_v2( shape, image0, image1, lhs, prior0, frequency_shift=0, substract_shell_mean=False, upsampling_factor=1 ) prior = np.asarray(prior) fsc_raw = np.asarray(fsc_raw) prior_avg = np.asarray(prior_avg)
assert prior.shape == (n,) assert fsc_raw.ndim == 1 assert prior_avg.ndim == 1 assert np.all(np.isfinite(prior)) assert np.all(np.isfinite(fsc_raw)) assert np.all(np.isfinite(prior_avg))
h0 = np.abs(rng.normal(size=n)).astype(np.float32) + 1.0 h1 = np.abs(rng.normal(size=n)).astype(np.float32) + 1.0 b0 = (rng.normal(size=n) + 1j * rng.normal(size=n)).astype(np.complex64) b1 = (rng.normal(size=n) + 1j * rng.normal(size=n)).astype(np.complex64)
p, f = regularization.prior_iteration( H0=h0, H1=h1, B0=b0, B1=b1, frequency_shift=np.array([0, 0, 0], dtype=np.int32), init_regularization=prior0, substract_shell_mean=False, volume_shape=shape, prior_iterations=3, ) p = np.asarray(p) f = np.asarray(f) assert p.shape == (n,) assert f.ndim == 1 assert np.all(np.isfinite(p)) assert np.all(np.isfinite(f))
def test_prior_iteration_relion_style_and_downsample_from_fsc(): shape = (4, 4, 4) n = int(np.prod(shape)) rng = np.random.default_rng(1)
h0 = np.abs(rng.normal(size=n)).astype(np.float32) + 1.0 h1 = np.abs(rng.normal(size=n)).astype(np.float32) + 1.0 b0 = (rng.normal(size=n) + 1j * rng.normal(size=n)).astype(np.complex64) b1 = (rng.normal(size=n) + 1j * rng.normal(size=n)).astype(np.complex64) prior0 = np.ones(n, dtype=np.float32)
cov_col, prior, fsc = regularization.prior_iteration_relion_style( H0=h0, H1=h1, B0=b0, B1=b1, frequency_shift=np.array([0, 0, 0], dtype=np.int32), init_regularization=prior0, substract_shell_mean=False, volume_shape=shape, kernel="triangular", use_spherical_mask=False, grid_correct=False, volume_mask=None, prior_iterations=2, downsample_from_fsc_flag=False, ) cov_col = np.asarray(cov_col) prior = np.asarray(prior) fsc = np.asarray(fsc) assert cov_col.shape == (n,) assert prior.shape == (n,) assert fsc.ndim == 1 assert np.all(np.isfinite(cov_col)) assert np.all(np.isfinite(prior)) assert np.all(np.isfinite(fsc))
# Explicitly exercise downsample masking behavior. arr = np.ones(n, dtype=np.float32) # Keep low-freq bins, drop high-freq bins. fsc_mask = np.array([1.0, 1.0, 0.0], dtype=np.float32) out = regularization.downsample_from_fsc(arr, fsc_mask, shape) out = np.asarray(out) assert out.shape == (n,) assert np.any(out == 0.0)
# ---------------------------------------------------------------------------# covariance_update_col tests# ---------------------------------------------------------------------------
def test_covariance_update_col_basic_formula(): """Verify Wiener filter: cov = B / (H + 1/prior).""" import jax.numpy as jnp
H = np.array([2.0, 4.0], dtype=np.float32) B = np.array([6.0, 8.0], dtype=np.float32) prior = np.array([1.0, 2.0], dtype=np.float32) out = np.asarray(regularization.covariance_update_col(jnp.array(H), jnp.array(B), jnp.array(prior))) expected = B / (H + 1.0 / prior) np.testing.assert_allclose(out, expected, rtol=1e-5)
def test_covariance_update_col_zeros_below_epsilon(): """Voxels with H ~ 0 must produce zero output.""" import jax.numpy as jnp
H = np.array([0.0, 3.0], dtype=np.float32) B = np.array([99.0, 6.0], dtype=np.float32) prior = np.array([1.0, 1.0], dtype=np.float32) out = np.asarray(regularization.covariance_update_col(jnp.array(H), jnp.array(B), jnp.array(prior))) assert float(out[0]) == 0.0, "Uncovered voxel should produce zero" assert np.isfinite(out[1])
def test_covariance_update_col_complex_b(): """Works with complex B (common case).""" import jax.numpy as jnp
H = np.array([2.0], dtype=np.float32) B = np.array([2.0 + 4.0j], dtype=np.complex64) prior = np.array([1.0], dtype=np.float32) out = np.asarray(regularization.covariance_update_col(jnp.array(H), jnp.array(B), jnp.array(prior))) expected = B / (H + 1.0 / prior) np.testing.assert_allclose(out, expected, rtol=1e-5)
# ---------------------------------------------------------------------------# average_over_shells / sum_over_shells tests# ---------------------------------------------------------------------------
def test_average_over_shells_uniform_input(): """Uniform input -> every populated shell average is the uniform value.""" shape = (8, 8, 8) n = int(np.prod(shape)) ones = np.ones(n, dtype=np.float32) out = np.asarray(regularization.average_over_shells(ones, shape)) assert out.shape == (shape[0] // 2 - 1,) populated = out > 0 np.testing.assert_allclose(out[populated], 1.0, rtol=1e-5)
def test_average_over_shells_output_shape(): shape = (6, 6, 6) n = int(np.prod(shape)) x = np.random.default_rng(0).random(n).astype(np.float32) out = np.asarray(regularization.average_over_shells(x, shape)) assert out.shape == (shape[0] // 2 - 1,)
def test_sum_over_shells_output_shape(): shape = (8, 8, 8) n = int(np.prod(shape)) x = np.ones(n, dtype=np.float32) out = np.asarray(regularization.sum_over_shells(x, shape)) assert out.shape == (shape[0] // 2 - 1,)
def test_sum_vs_average_uniform(): """For uniform input, sum >= average for every populated shell.""" shape = (8, 8, 8) n = int(np.prod(shape)) x = np.ones(n, dtype=np.float32) sums = np.asarray(regularization.sum_over_shells(x, shape)) avgs = np.asarray(regularization.average_over_shells(x, shape)) populated = avgs > 0 assert np.all(sums[populated] >= avgs[populated] - 1e-5)
def test_sum_over_shells_nonneg_input(): """Non-negative input produces non-negative sums.""" shape = (8, 8, 8) n = int(np.prod(shape)) x = np.abs(np.random.default_rng(42).random(n)).astype(np.float32) out = np.asarray(regularization.sum_over_shells(x, shape)) assert np.all(out >= -1e-7)
# ---------------------------------------------------------------------------# downsample_lhs tests# ---------------------------------------------------------------------------
def test_downsample_lhs_shape_factor1(): """Factor=1 preserves shape.""" import jax.numpy as jnp
shape = (4, 4, 4) lhs = jnp.ones(shape, dtype=jnp.float32) out = regularization.downsample_lhs(lhs, shape, upsampling_factor=1) assert out.shape == shape
def test_downsample_lhs_shape_factor2(): """Factor=2 halves each dimension.""" import jax.numpy as jnp
shape = (8, 8, 8) lhs = jnp.ones(shape, dtype=jnp.float32) out = regularization.downsample_lhs(lhs, shape, upsampling_factor=2) assert out.shape == (4, 4, 4)
def test_downsample_lhs_nonnegative(): """Output is clipped to >= 0.""" import jax.numpy as jnp
shape = (4, 4, 4) rng = np.random.default_rng(7) lhs = jnp.array(rng.normal(size=shape).astype(np.float32)) out = np.asarray(regularization.downsample_lhs(lhs, shape, upsampling_factor=1)) assert np.all(out >= -1e-7)
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
import jaximport jax.numpy as jnp
@pytest.mark.gpudef test_jax_scipy_nd_image_mean_inner_gpu(gpu_device): inp = np.array([1.0, 2.0, 3.0], dtype=np.float32) labels = np.array([0, 0, 2], dtype=np.int32) index = np.array([0, 1, 2, 3], dtype=np.int32)
cpu_out = np.asarray(regularization.jax_scipy_nd_image_mean_inner(inp, labels=labels, index=index))
with jax.default_device(gpu_device): inp_g = jax.device_put(jnp.array(inp), gpu_device) labels_g = jax.device_put(jnp.array(labels), gpu_device) index_g = jax.device_put(jnp.array(index), gpu_device) gpu_out = np.asarray(regularization.jax_scipy_nd_image_mean_inner(inp_g, labels=labels_g, index=index_g))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_get_fsc_gpu_on_gpu(gpu_device): shape = (4, 4, 4) rng = np.random.default_rng(0) v1 = (rng.normal(size=np.prod(shape)) + 1j * rng.normal(size=np.prod(shape))).astype(np.complex64) v2 = (rng.normal(size=np.prod(shape)) + 1j * rng.normal(size=np.prod(shape))).astype(np.complex64)
cpu_fsc = np.asarray(regularization.get_fsc_gpu(v1, v2, shape, substract_shell_mean=False, frequency_shift=0))
with jax.default_device(gpu_device): v1_g = jax.device_put(jnp.array(v1), gpu_device) v2_g = jax.device_put(jnp.array(v2), gpu_device) gpu_fsc = np.asarray( regularization.get_fsc_gpu(v1_g, v2_g, shape, substract_shell_mean=False, frequency_shift=0) )
np.testing.assert_allclose(cpu_fsc, gpu_fsc, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_compute_fsc_prior_gpu_v2_on_gpu(gpu_device): shape = (4, 4, 4) n = int(np.prod(shape)) rng = np.random.default_rng(0)
image0 = (rng.normal(size=n) + 1j * rng.normal(size=n)).astype(np.complex64) image1 = (rng.normal(size=n) + 1j * rng.normal(size=n)).astype(np.complex64) lhs = np.abs(rng.normal(size=n)).astype(np.float32) + 0.5 prior0 = np.ones(n, dtype=np.float32)
cpu_prior, cpu_fsc, cpu_avg = regularization.compute_fsc_prior_gpu_v2( shape, image0, image1, lhs, prior0, frequency_shift=0, substract_shell_mean=False, upsampling_factor=1 ) cpu_prior, cpu_fsc, cpu_avg = np.asarray(cpu_prior), np.asarray(cpu_fsc), np.asarray(cpu_avg)
with jax.default_device(gpu_device): i0_g = jax.device_put(jnp.array(image0), gpu_device) i1_g = jax.device_put(jnp.array(image1), gpu_device) lhs_g = jax.device_put(jnp.array(lhs), gpu_device) p0_g = jax.device_put(jnp.array(prior0), gpu_device) gpu_prior, gpu_fsc, gpu_avg = regularization.compute_fsc_prior_gpu_v2( shape, i0_g, i1_g, lhs_g, p0_g, frequency_shift=0, substract_shell_mean=False, upsampling_factor=1 ) gpu_prior, gpu_fsc, gpu_avg = np.asarray(gpu_prior), np.asarray(gpu_fsc), np.asarray(gpu_avg)
np.testing.assert_allclose(cpu_prior, gpu_prior, atol=1e-4, rtol=1e-4) np.testing.assert_allclose(cpu_fsc, gpu_fsc, atol=1e-4, rtol=1e-4) np.testing.assert_allclose(cpu_avg, gpu_avg, atol=1e-4, rtol=1e-4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679import numpy as npimport pytestfrom types import SimpleNamespace
pytest.importorskip("jax")import jax.numpy as jnp
from recovar import jax_configfrom recovar import corefrom recovar.reconstruction import relion_functions as rf
def test_gridding_correct_invalid_order_raises(): vol = np.ones((4, 4, 4), dtype=np.float32) with pytest.raises(ValueError): rf.griddingCorrect(vol, ori_size=4, padding_factor=2, order=9)
def test_gridding_correct_variants_return_finite(): vol = np.ones((6, 6, 6), dtype=np.float32) out0, s0 = rf.griddingCorrect(vol, ori_size=6, padding_factor=2, order=0) out1, s1 = rf.griddingCorrect_square(vol, ori_size=6, padding_factor=2, order=1) assert out0.shape == vol.shape assert out1.shape == vol.shape assert np.isfinite(np.asarray(out0)).all() assert np.isfinite(np.asarray(s0)).all() assert np.isfinite(np.asarray(out1)).all() assert np.isfinite(np.asarray(s1)).all()
def test_upscale_tau_shape_and_values(): tau_1d = np.linspace(1.0, 2.0, 16, dtype=np.float32) out = rf.upscale_tau(tau_1d, padding_factor=2, volume_shape=(4, 4, 4), tau_is_1d=True) assert out.shape == (8 * 8 * 8,) assert float(np.min(np.asarray(out))) >= 1.0 assert float(np.max(np.asarray(out))) <= 2.0
def test_adjust_regularization_relion_style_lower_bounded(): filt = np.zeros((4, 4, 4), dtype=np.float32) reg = rf.adjust_regularization_relion_style(filt, volume_shape=(4, 4, 4)) reg_np = np.asarray(reg) assert reg_np.shape == (4, 4, 4) assert (reg_np >= jax_config.EPSILON).all()
def test_adjust_regularization_relion_style_half_matches_full(): import recovar.core.fourier_transform_utils as ftu
rng = np.random.default_rng(123) volume_shape = (6, 6, 6) half_shape = ftu.volume_shape_to_half_volume_shape(volume_shape) half_size = int(np.prod(half_shape)) full_size = int(np.prod(volume_shape))
filt_half = rng.random(half_size).astype(np.float32) + 0.1 tau = rng.random(full_size).astype(np.float32) + 0.2
cpu_device = jax.devices("cpu")[0] with jax.default_device(cpu_device): filt_full = ( np.asarray(ftu.half_volume_to_full_volume(jnp.array(filt_half), volume_shape)) .reshape(-1) .real.astype(np.float32) ) reg_full = np.asarray( rf.adjust_regularization_relion_style(jnp.array(filt_full), volume_shape=volume_shape, tau=jnp.array(tau)) ).reshape(-1) reg_half = np.asarray( rf.adjust_regularization_relion_style( jnp.array(filt_half), volume_shape=volume_shape, tau=jnp.array(tau), half_volume=True ) ).reshape(-1) reg_full_to_half = np.asarray(ftu.full_volume_to_half_volume(jnp.array(reg_full), volume_shape)).reshape(-1)
np.testing.assert_allclose(reg_half, reg_full_to_half, atol=1e-5, rtol=1e-5)
def test_post_process_from_filter_v2_half_matches_full(): import recovar.core.fourier_transform_utils as ftu
rng = np.random.default_rng(124) volume_shape = (6, 6, 6) half_shape = ftu.volume_shape_to_half_volume_shape(volume_shape) half_size = int(np.prod(half_shape))
ft_ctf_half = rng.random(half_size).astype(np.float32) + 0.2 tau = rng.random(int(np.prod(volume_shape))).astype(np.float32) + 0.3
cpu_device = jax.devices("cpu")[0] with jax.default_device(cpu_device): ft_ctf_full = ( np.asarray(ftu.half_volume_to_full_volume(jnp.array(ft_ctf_half), volume_shape)) .reshape(-1) .real.astype(np.float32) ) spatial_rhs = jnp.array(rng.standard_normal(volume_shape).astype(np.float32)) f_ty_half = np.asarray(ftu.get_dft3_real(spatial_rhs)).reshape(-1).astype(np.complex64) f_ty_full = ( np.asarray(ftu.half_volume_to_full_volume(jnp.array(f_ty_half), volume_shape)) .reshape(-1) .astype(np.complex64) )
out_full = np.asarray( rf.post_process_from_filter_v2( jnp.array(ft_ctf_full), jnp.array(f_ty_full), volume_shape, 1, tau=jnp.array(tau), kernel="triangular", use_spherical_mask=False, grid_correct=False, input_half_volume=False, ) ).reshape(-1) out_half = np.asarray( rf.post_process_from_filter_v2( jnp.array(ft_ctf_half), jnp.array(f_ty_half), volume_shape, 1, tau=jnp.array(tau), kernel="triangular", use_spherical_mask=False, grid_correct=False, input_half_volume=True, ) ).reshape(-1) out_real_full = np.asarray( rf.post_process_from_filter_v2( jnp.array(ft_ctf_full), jnp.array(f_ty_full), volume_shape, 1, tau=jnp.array(tau), kernel="triangular", use_spherical_mask=False, grid_correct=False, input_half_volume=False, return_real_space=True, ) ) out_real_half = np.asarray( rf.post_process_from_filter_v2( jnp.array(ft_ctf_half), jnp.array(f_ty_half), volume_shape, 1, tau=jnp.array(tau), kernel="triangular", use_spherical_mask=False, grid_correct=False, input_half_volume=True, return_real_space=True, ) )
# Half/full Fourier layouts can differ at a few conjugate-related bins while # still reconstructing the same real-space volume; assert on real-space output. np.testing.assert_allclose(out_real_half, out_real_full, atol=1e-4, rtol=1e-4)
def test_relion_kernel_batch_normalizes_noise_variance_shapes(): from recovar.core.configs import ForwardModelConfig
def ctf_fun(params, image_shape, voxel_size, *, half_image=False, **kwargs): w = image_shape[1] // 2 + 1 if half_image else image_shape[1] return jnp.ones((params.shape[0], image_shape[0] * w), dtype=jnp.float32)
config = ForwardModelConfig( image_shape=(4, 4), volume_shape=(4, 4, 4), grid_size=4, voxel_size=1.5, padding=0, disc_type="linear_interp", ctf=core.as_ctf_evaluator(ctf_fun), premultiplied_ctf=False, volume_mask_threshold=0.0, )
bsz = 5 images = jnp.ones((bsz, 16), dtype=jnp.complex64) ctf_params = jnp.zeros((bsz, 9), dtype=jnp.float32) rots = jnp.tile(jnp.eye(3, dtype=jnp.float32), (bsz, 1, 1)) trans = jnp.zeros((bsz, 2), dtype=jnp.float32)
# relion_kernel_batch_from_fft accumulates in half-volume layout: 4*4*(4//2+1) = 48 half_vol_size = 4 * 4 * (4 // 2 + 1) candidate_noises = [ jnp.ones((16,), dtype=jnp.float32), jnp.ones((4, 4), dtype=jnp.float32), jnp.ones((1, 4, 4), dtype=jnp.float32), jnp.ones((bsz, 16), dtype=jnp.float32), ] for noise_var in candidate_noises: ft_y, ft_ctf = rf.relion_kernel_batch_from_fft( config, images, ctf_params, rots, trans, noise_var, ) assert np.asarray(ft_y).shape == (half_vol_size,) assert np.asarray(ft_ctf).shape == (half_vol_size,) assert np.isfinite(np.asarray(ft_y)).all()
def test_relion_style_triangular_kernel_respects_by_image_flag(monkeypatch): calls = {}
class _FakeDataset: noise = None
def iter_batches(self, batch_size, *, noise_model=None, indices=None, by_image=True): calls["batch_size"] = batch_size calls["noise_model"] = noise_model calls["indices"] = np.asarray(indices, dtype=np.int32) calls["by_image"] = by_image yield ( np.ones((1, 4, 4), dtype=np.float32), np.tile(np.eye(3, dtype=np.float32), (1, 1, 1)), np.zeros((1, 2), dtype=np.float32), np.zeros((1, 9), dtype=np.float32), None, np.array([0], dtype=np.int32), np.array([3], dtype=np.int32), )
monkeypatch.setattr( rf.ForwardModelConfig, "from_dataset", staticmethod( lambda *_args, **_kwargs: SimpleNamespace( image_shape=(4, 4), volume_shape=(4, 4, 4), premultiplied_ctf=False, compute_ctf_half=lambda ctf_params: jnp.ones((ctf_params.shape[0], 12), dtype=jnp.float32), data_multiplier=1.0, grid_size=4, padding=0, disc_type="linear_interp", ) ), ) monkeypatch.setattr( rf, "relion_kernel_batch", lambda _config, _images, _ctf_params, _rots, _trans, _noise_variance, Ft_y=None, Ft_ctf=None: ( jnp.ones((4 * 4 * (4 // 2 + 1),), dtype=jnp.complex64), jnp.ones((4 * 4 * (4 // 2 + 1),), dtype=jnp.float32), ), )
ft_ctf, ft_y = rf.relion_style_triangular_kernel( _FakeDataset(), cov_noise=None, batch_size=7, index_subset=np.array([1, 5], dtype=np.int32), by_image=False, )
np.testing.assert_array_equal(calls["indices"], np.array([1, 5], dtype=np.int32)) assert calls["by_image"] is False assert calls["batch_size"] == 7 assert np.asarray(ft_ctf).shape == (4 * 4 * 4,) assert np.asarray(ft_y).shape == (4 * 4 * 4,)
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
import jax
@pytest.mark.gpudef test_gridding_correct_gpu(gpu_device): vol = np.ones((6, 6, 6), dtype=np.float32)
cpu_out0, cpu_s0 = rf.griddingCorrect(vol, ori_size=6, padding_factor=2, order=0) cpu_out0, cpu_s0 = np.asarray(cpu_out0), np.asarray(cpu_s0)
with jax.default_device(gpu_device): vol_g = jax.device_put(jnp.array(vol), gpu_device) gpu_out0, gpu_s0 = rf.griddingCorrect(vol_g, ori_size=6, padding_factor=2, order=0) gpu_out0, gpu_s0 = np.asarray(gpu_out0), np.asarray(gpu_s0)
np.testing.assert_allclose(cpu_out0, gpu_out0, atol=1e-5, rtol=1e-5) np.testing.assert_allclose(cpu_s0, gpu_s0, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_gridding_correct_square_gpu(gpu_device): vol = np.ones((6, 6, 6), dtype=np.float32)
cpu_out1, cpu_s1 = rf.griddingCorrect_square(vol, ori_size=6, padding_factor=2, order=1) cpu_out1, cpu_s1 = np.asarray(cpu_out1), np.asarray(cpu_s1)
with jax.default_device(gpu_device): vol_g = jax.device_put(jnp.array(vol), gpu_device) gpu_out1, gpu_s1 = rf.griddingCorrect_square(vol_g, ori_size=6, padding_factor=2, order=1) gpu_out1, gpu_s1 = np.asarray(gpu_out1), np.asarray(gpu_s1)
np.testing.assert_allclose(cpu_out1, gpu_out1, atol=1e-5, rtol=1e-5) np.testing.assert_allclose(cpu_s1, gpu_s1, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_upscale_tau_gpu(gpu_device): tau_1d = np.linspace(1.0, 2.0, 16, dtype=np.float32)
cpu_out = np.asarray(rf.upscale_tau(tau_1d, padding_factor=2, volume_shape=(4, 4, 4), tau_is_1d=True))
with jax.default_device(gpu_device): tau_g = jax.device_put(jnp.array(tau_1d), gpu_device) gpu_out = np.asarray(rf.upscale_tau(tau_g, padding_factor=2, volume_shape=(4, 4, 4), tau_is_1d=True))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
def test_relion_kernel_batch_half_image_matches_full_reference(): """New half-image relion_kernel_batch produces identical output to the old full-image path (padded_dft + translate + full adjoint).""" from recovar.core.configs import ForwardModelConfig from recovar.core.ctf import CTFEvaluator from recovar.core import padding import recovar.core.forward as core_forward from recovar.reconstruction import noise as noise_mod
rng = np.random.default_rng(42) grid_size = 8 pad = 4 image_shape = (grid_size + pad, grid_size + pad) volume_shape = (grid_size + pad,) * 3 voxel_size = 1.5 bsz = 3 data_multiplier = -1.0
config = ForwardModelConfig( image_shape=image_shape, volume_shape=volume_shape, grid_size=grid_size, voxel_size=voxel_size, padding=pad, disc_type="linear_interp", ctf=CTFEvaluator(), premultiplied_ctf=False, volume_mask_threshold=0.0, data_multiplier=data_multiplier, )
raw_images = rng.standard_normal((bsz, grid_size, grid_size)).astype(np.float32) rots = np.stack( [ np.eye(3, dtype=np.float32), rng.standard_normal((3, 3)).astype(np.float32), rng.standard_normal((3, 3)).astype(np.float32), ] ) for i in range(1, bsz): q, _ = np.linalg.qr(rots[i]) rots[i] = q * np.sign(np.linalg.det(q))
trans = rng.standard_normal((bsz, 2)).astype(np.float32) * 0.5 ctf_params = np.zeros((bsz, 9), dtype=np.float32) ctf_params[:, 0] = 300.0 ctf_params[:, 1] = 2.7 ctf_params[:, 2] = 0.1 ctf_params[:, 3] = rng.uniform(1.0, 3.0, bsz) ctf_params[:, 4] = ctf_params[:, 3] ctf_params[:, 6] = 1.0 ctf_params[:, 7] = 10.0 noise_var = rng.uniform(0.5, 2.0, (bsz, np.prod(image_shape))).astype(np.float32)
# --- Reference: old full-image path --- full_images = padding.padded_dft(jnp.array(raw_images) * data_multiplier, grid_size, pad) full_images = core.translate_images(full_images, jnp.array(trans), image_shape) noise_full = noise_mod.to_batched_pixel_noise(jnp.array(noise_var), image_shape, batch_size=bsz) full_images_normed = full_images / noise_full ref_Ft_y = np.asarray( core_forward.adjoint_forward_model( config, full_images_normed, jnp.array(ctf_params), jnp.array(rots), skip_ctf=False, volume=None, half_image=False, ) ) ctf_full = config.compute_ctf(jnp.array(ctf_params)) / noise_full ref_Ft_ctf = np.asarray( core_forward.adjoint_forward_model( config, ctf_full, jnp.array(ctf_params), jnp.array(rots), volume=None, half_image=False, ) )
# --- New: half-image path via relion_kernel_batch (outputs half-volume) --- import recovar.core.fourier_transform_utils as ftu
half_Ft_y, half_Ft_ctf = rf.relion_kernel_batch( config, jnp.array(raw_images), jnp.array(ctf_params), jnp.array(rots), jnp.array(trans), jnp.array(noise_var), ) new_Ft_y = np.asarray(ftu.half_volume_to_full_volume(half_Ft_y, volume_shape)).reshape(-1) new_Ft_ctf = np.asarray(ftu.half_volume_to_full_volume(half_Ft_ctf, volume_shape)).reshape(-1) np.testing.assert_allclose(new_Ft_y, ref_Ft_y, atol=1e-4, rtol=1e-4) np.testing.assert_allclose(new_Ft_ctf, ref_Ft_ctf, atol=1e-4, rtol=1e-4)
def test_relion_kernel_batch_complex_input_matches_full_reference(): """relion_kernel_batch_from_fft with pre-processed complex images matches the full-image reference.""" from recovar.core.configs import ForwardModelConfig from recovar.core.ctf import CTFEvaluator from recovar.core import padding import recovar.core.forward as core_forward from recovar.reconstruction import noise as noise_mod
rng = np.random.default_rng(99) grid_size = 8 pad = 4 image_shape = (grid_size + pad, grid_size + pad) volume_shape = (grid_size + pad,) * 3 bsz = 3
config = ForwardModelConfig( image_shape=image_shape, volume_shape=volume_shape, grid_size=grid_size, voxel_size=1.5, padding=pad, disc_type="linear_interp", ctf=CTFEvaluator(), premultiplied_ctf=False, volume_mask_threshold=0.0, )
raw_images = rng.standard_normal((bsz, grid_size, grid_size)).astype(np.float32) complex_images = padding.padded_dft(jnp.array(raw_images), grid_size, pad) rots = jnp.tile(jnp.eye(3, dtype=jnp.float32), (bsz, 1, 1)) trans = jnp.zeros((bsz, 2), dtype=jnp.float32) ctf_params = np.zeros((bsz, 9), dtype=np.float32) ctf_params[:, 0] = 300.0 ctf_params[:, 1] = 2.7 ctf_params[:, 2] = 0.1 ctf_params[:, 3] = 2.0 ctf_params[:, 4] = 2.0 noise_var = np.ones((1, np.prod(image_shape)), dtype=np.float32)
# --- Reference: full-image path --- full_images = core.translate_images(complex_images, trans, image_shape) noise_full = noise_mod.to_batched_pixel_noise(jnp.array(noise_var), image_shape, batch_size=bsz) full_normed = full_images / noise_full ref_Ft_y = np.asarray( core_forward.adjoint_forward_model( config, full_normed, jnp.array(ctf_params), rots, skip_ctf=False, volume=None, half_image=False, ) ) ctf_full = config.compute_ctf(jnp.array(ctf_params)) / noise_full ref_Ft_ctf = np.asarray( core_forward.adjoint_forward_model( config, ctf_full, jnp.array(ctf_params), rots, volume=None, half_image=False, ) )
# --- New: half-image path (outputs half-volume) --- import recovar.core.fourier_transform_utils as ftu
half_Ft_y, half_Ft_ctf = rf.relion_kernel_batch_from_fft( config, complex_images, jnp.array(ctf_params), rots, trans, jnp.array(noise_var), ) new_Ft_y = np.asarray(ftu.half_volume_to_full_volume(half_Ft_y, volume_shape)).reshape(-1) new_Ft_ctf = np.asarray(ftu.half_volume_to_full_volume(half_Ft_ctf, volume_shape)).reshape(-1) np.testing.assert_allclose(new_Ft_y, ref_Ft_y, atol=1e-4, rtol=1e-4) np.testing.assert_allclose(new_Ft_ctf, ref_Ft_ctf, atol=1e-4, rtol=1e-4)
def test_relion_kernel_batch_accumulator_matches_sequential(): """Calling relion_kernel_batch twice with accumulators matches summing two independent calls.""" from recovar.core.configs import ForwardModelConfig from recovar.core.ctf import CTFEvaluator
rng = np.random.default_rng(77) grid_size = 6 pad = 2 image_shape = (grid_size + pad, grid_size + pad) volume_shape = (grid_size + pad,) * 3
config = ForwardModelConfig( image_shape=image_shape, volume_shape=volume_shape, grid_size=grid_size, voxel_size=1.0, padding=pad, disc_type="linear_interp", ctf=CTFEvaluator(), premultiplied_ctf=False, volume_mask_threshold=0.0, )
bsz = 2 imgs1 = jnp.array(rng.standard_normal((bsz, grid_size, grid_size)).astype(np.float32)) imgs2 = jnp.array(rng.standard_normal((bsz, grid_size, grid_size)).astype(np.float32)) rots = jnp.tile(jnp.eye(3, dtype=jnp.float32), (bsz, 1, 1)) trans = jnp.zeros((bsz, 2), dtype=jnp.float32) ctf_params = jnp.zeros((bsz, 9), dtype=jnp.float32) noise_var = jnp.ones((1, np.prod(image_shape)), dtype=jnp.float32)
# Two independent calls, sum result y1, c1 = rf.relion_kernel_batch(config, imgs1, ctf_params, rots, trans, noise_var) y2, c2 = rf.relion_kernel_batch(config, imgs2, ctf_params, rots, trans, noise_var) sum_Ft_y = np.asarray(y1) + np.asarray(y2) sum_Ft_ctf = np.asarray(c1) + np.asarray(c2)
# Accumulated version acc_y, acc_c = rf.relion_kernel_batch(config, imgs1, ctf_params, rots, trans, noise_var) acc_y, acc_c = rf.relion_kernel_batch(config, imgs2, ctf_params, rots, trans, noise_var, Ft_y=acc_y, Ft_ctf=acc_c)
np.testing.assert_allclose(np.asarray(acc_y), sum_Ft_y, atol=1e-5, rtol=1e-5) np.testing.assert_allclose(np.asarray(acc_c), sum_Ft_ctf, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_relion_kernel_batch_half_volume_output_on_gpu(gpu_device): """relion_kernel_batch on GPU produces finite half-volume outputs.""" from recovar.core.configs import ForwardModelConfig from recovar.core.ctf import CTFEvaluator import recovar.core.fourier_transform_utils as ftu
rng = np.random.default_rng(55) grid_size = 8 pad = 4 image_shape = (grid_size + pad, grid_size + pad) volume_shape = (grid_size + pad,) * 3 bsz = 3
config = ForwardModelConfig( image_shape=image_shape, volume_shape=volume_shape, grid_size=grid_size, voxel_size=1.5, padding=pad, disc_type="linear_interp", ctf=CTFEvaluator(), premultiplied_ctf=False, volume_mask_threshold=0.0, data_multiplier=-1.0, )
raw_images = jnp.array(rng.standard_normal((bsz, grid_size, grid_size)).astype(np.float32)) rots = jnp.tile(jnp.eye(3, dtype=jnp.float32), (bsz, 1, 1)) trans = jnp.array(rng.standard_normal((bsz, 2)).astype(np.float32) * 0.3) ctf_params = jnp.zeros((bsz, 9), dtype=jnp.float32) ctf_params = ctf_params.at[:, 0].set(300.0) ctf_params = ctf_params.at[:, 1].set(2.7) ctf_params = ctf_params.at[:, 2].set(0.1) ctf_params = ctf_params.at[:, 3].set(2.0) ctf_params = ctf_params.at[:, 4].set(2.0) noise_var = jnp.ones((1, np.prod(image_shape)), dtype=jnp.float32) with jax.default_device(gpu_device): half_y, half_c = rf.relion_kernel_batch(config, raw_images, ctf_params, rots, trans, noise_var)
# Expand and verify shape + finiteness full_y = np.asarray(ftu.half_volume_to_full_volume(half_y, volume_shape)).reshape(-1) full_c = np.asarray(ftu.half_volume_to_full_volume(half_c, volume_shape)).reshape(-1) assert full_y.shape == (int(np.prod(volume_shape)),) assert np.isfinite(full_y).all() assert np.isfinite(full_c).all()
@pytest.mark.gpudef test_adjust_regularization_relion_style_gpu(gpu_device): filt = np.zeros((4, 4, 4), dtype=np.float32)
cpu_out = np.asarray(rf.adjust_regularization_relion_style(filt, volume_shape=(4, 4, 4)))
with jax.default_device(gpu_device): filt_g = jax.device_put(jnp.array(filt), gpu_device) gpu_out = np.asarray(rf.adjust_regularization_relion_style(filt_g, volume_shape=(4, 4, 4)))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_post_process_from_filter_v2_half_matches_full_gpu(gpu_device): import recovar.core.fourier_transform_utils as ftu
rng = np.random.default_rng(125) volume_shape = (8, 8, 8) half_shape = ftu.volume_shape_to_half_volume_shape(volume_shape) half_size = int(np.prod(half_shape))
ft_ctf_half = rng.random(half_size).astype(np.float32) + 0.2 cpu_device = jax.devices("cpu")[0] with jax.default_device(cpu_device): ft_ctf_full = ( np.asarray(ftu.half_volume_to_full_volume(jnp.array(ft_ctf_half), volume_shape)) .reshape(-1) .real.astype(np.float32) )
spatial_rhs = jnp.array(rng.standard_normal(volume_shape).astype(np.float32)) f_ty_half = np.asarray(ftu.get_dft3_real(spatial_rhs)).reshape(-1).astype(np.complex64) f_ty_full = ( np.asarray(ftu.half_volume_to_full_volume(jnp.array(f_ty_half), volume_shape)) .reshape(-1) .astype(np.complex64) )
tau = rng.random(int(np.prod(volume_shape))).astype(np.float32) + 0.3
try: with jax.default_device(gpu_device): out_full = np.asarray( rf.post_process_from_filter_v2( jax.device_put(jnp.array(ft_ctf_full), gpu_device), jax.device_put(jnp.array(f_ty_full), gpu_device), volume_shape, 1, tau=jax.device_put(jnp.array(tau), gpu_device), kernel="triangular", use_spherical_mask=False, grid_correct=False, input_half_volume=False, ) ) out_half = np.asarray( rf.post_process_from_filter_v2( jax.device_put(jnp.array(ft_ctf_half), gpu_device), jax.device_put(jnp.array(f_ty_half), gpu_device), volume_shape, 1, tau=jax.device_put(jnp.array(tau), gpu_device), kernel="triangular", use_spherical_mask=False, grid_correct=False, input_half_volume=True, ) ) except jax.errors.JaxRuntimeError as exc: if "Failed to create cuFFT batched plan" in str(exc): pytest.skip("cuFFT plan allocation failed on this GPU runner") raise
cpu_device = jax.devices("cpu")[0] with jax.default_device(cpu_device): vol_full_real = np.asarray(ftu.get_idft3(jnp.array(out_full.reshape(volume_shape)))).real vol_half_real = np.asarray(ftu.get_idft3(jnp.array(out_half.reshape(volume_shape)))).real np.testing.assert_allclose(vol_half_real, vol_full_real, atol=1e-4, rtol=1e-4)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201from types import SimpleNamespacefrom pathlib import Pathimport json
import numpy as npimport pytestimport jax.numpy as jnp
pytest.importorskip("jax")
from recovar.commands import run_test_all_metrics as rtam
pytestmark = pytest.mark.unit
def _logger(): return SimpleNamespace(info=lambda *_: None, warning=lambda *_: None)
def _install_main_runtime_stubs(monkeypatch, tmp_path, *, mean_fsc=0.5, variance_fsc=0.4): class _ArgsParser: def parse_args(self, _cmd): return SimpleNamespace()
monkeypatch.setattr(rtam.pipeline, "add_args", lambda _p: _ArgsParser()) monkeypatch.setattr(rtam.pipeline, "standard_recovar_pipeline", lambda _args: None) monkeypatch.setattr(rtam.compute_state, "add_args", lambda _p: _ArgsParser()) monkeypatch.setattr(rtam.compute_state, "compute_state", lambda _args: None)
monkeypatch.setattr( rtam, "make_big_test_dataset", lambda *_args, **_kwargs: { "image_assignment": np.array([0, 1], dtype=np.int32), "noise_variance": np.array([1.0, 1.0], dtype=np.float32), "dose_indices": None, }, ) monkeypatch.setattr( rtam, "compute_noise_variance_metrics", lambda *_args, **_kwargs: { "noise_mean_relative_error": 0.1, "noise_correlation": 0.9, }, )
def _fake_plot_fsc_new(*_args, **kwargs): name = kwargs.get("name", "") if name == "Mean FSC": return None, float(mean_fsc) if name in ("Variance FSC", "Variance Spatial FSC"): return None, float(variance_fsc) return None, 0.0
monkeypatch.setattr(rtam.plot_utils, "plot_fsc_new", _fake_plot_fsc_new) monkeypatch.setattr( rtam.metrics, "get_all_variance_scores", lambda *_args, **_kwargs: ( None, np.linspace(0.0, 1.0, 20, dtype=np.float32), np.linspace(0.0, 1.0, 20, dtype=np.float32), ), ) monkeypatch.setattr(rtam.metrics, "variance_of_zs", lambda *_args, **_kwargs: (None, 0.01)) monkeypatch.setattr( rtam.metrics, "make_union_gt_mask_from_hvd", lambda *_args, **_kwargs: (np.ones((2, 2, 2), dtype=np.float32), np.ones((2, 2, 2), dtype=bool)), ) monkeypatch.setattr( rtam.metrics, "compute_volume_error_metrics_from_gt", lambda *_args, **_kwargs: {"ninety_pc_locres": 1.0, "median_locres": 1.0, "mask": None}, ) monkeypatch.setattr( rtam.metrics, "subspace_angles", lambda *_args, **_kwargs: np.linspace(0.0, 1.0, 20, dtype=np.float32), )
def _fake_idft3(arr): a = np.asarray(arr) n = round(a.size ** (1 / 3)) return a.reshape(n, n, n)
monkeypatch.setattr(rtam.fourier_transform_utils, "get_idft3", _fake_idft3) monkeypatch.setattr( rtam.utils, "load_mrc", lambda _path: np.zeros((2, 2, 2), dtype=np.float32), )
class _PipelineOutput: def __init__(self, _path): self._embedding = { "latent_coords": { 4: np.array([[0.0, 0.0], [1.0, 1.0]], dtype=np.float32), 10: np.array([[0.0, 0.0], [1.0, 1.0]], dtype=np.float32), }, "contrasts": { 4: np.array([0.25, 0.75], dtype=np.float32), 10: np.array([0.30, 0.70], dtype=np.float32), }, "contrasts_noreg": { 4: np.array([0.20, 0.80], dtype=np.float32), 10: np.array([0.35, 0.65], dtype=np.float32), }, } self._u_real = np.ones((20, 2, 2, 2), dtype=np.float32) self._s = np.linspace(1.0, 2.0, 20, dtype=np.float32) self._cryos = SimpleNamespace(volume_shape=(2, 2, 2), voxel_size=1.0)
def get_embedding_component(self, entry, key): return self._embedding[entry][key]
def get_unsorted_embedding_component(self, entry, key): return self._embedding[entry][key]
def get_u_real(self, n_pcs): return self._u_real[: int(n_pcs)]
def get(self, key): mapping = { "lazy_dataset": self._cryos, "mean": np.zeros((2, 2, 2), dtype=np.float32), "variance": np.zeros((2, 2, 2), dtype=np.float32), "variance_est": {"combined": np.zeros(8, dtype=np.float32)}, "volume_shape": (2, 2, 2), "s": self._s, "noise_var_used": np.array([1.0, 1.0], dtype=np.float32), } return mapping[key]
monkeypatch.setattr(rtam.output, "PipelineOutput", _PipelineOutput)
class _SyntheticGT: def __init__(self): self.contrasts = np.array([0.3, 0.7], dtype=np.float32) self.volumes = np.stack( [ np.zeros((8,), dtype=np.complex64), np.ones((8,), dtype=np.complex64), ], axis=0, )
def get_mean(self): return np.zeros((2, 2, 2), dtype=np.float32)
def get_spatial_variances(self, contrasted=False): _ = contrasted return np.zeros((2, 2, 2), dtype=np.float32)
def get_vol_svd(self, contrasted=False, real_space=True, random_svd_pcs=200): _ = (contrasted, real_space, random_svd_pcs) return ( np.zeros((8, 20), dtype=np.float32), np.ones((20,), dtype=np.float32), np.zeros((20, 8), dtype=np.float32), )
monkeypatch.setattr( rtam.synthetic_dataset, "load_heterogeneous_reconstruction", lambda _path: _SyntheticGT(), )
def test_main_generated_run_writes_default_baseline_when_missing(monkeypatch, tmp_path): _install_main_runtime_stubs(monkeypatch, tmp_path, mean_fsc=0.55, variance_fsc=0.45) monkeypatch.setattr( rtam.sys, "argv", [ "run_test_all_metrics", "--output-dir", str(tmp_path), "--cpu", "--generate-pdb-volumes", "--generated-n-volumes", "3", "--grid-size", "8", ], )
rtam.main()
baseline_path = tmp_path / "generated_volumes" / "metrics_baseline_pdb_grid8_nvol3.json" report_path = tmp_path / "test_dataset" / "metrics_plot" / "metrics_regression_report.json" assert baseline_path.exists() assert report_path.exists()
with open(baseline_path, "r") as f: baseline_scores = json.load(f) with open(report_path, "r") as f: report = json.load(f)
assert baseline_scores["mean_fsc"] == pytest.approx(0.55) assert baseline_scores["variance_fsc"] == pytest.approx(0.45) assert report["status"] == "baseline_written"
def test_main_regression_fail_raises_without_skip(monkeypatch, tmp_path): _install_main_runtime_stubs(monkeypatch, tmp_path, mean_fsc=0.50, variance_fsc=0.40) baseline_path = tmp_path / "baseline.json" with open(baseline_path, "w") as f: json.dump({"mean_fsc": 0.99, "variance_fsc": 0.99}, f, indent=2)
monkeypatch.setattr( rtam.sys, "argv", [ "run_test_all_metrics", "--output-dir", str(tmp_path), "--cpu", "--volume-input", str(tmp_path / "fixed_vol_prefix_"), "--metrics-baseline-json", str(baseline_path), "--metrics-regression-tol-frac", "0.01", ], )
with pytest.raises(SystemExit, match="1"): rtam.main()
report_path = tmp_path / "test_dataset" / "metrics_plot" / "metrics_regression_report.json" assert report_path.exists() with open(report_path, "r") as f: report = json.load(f) assert report["status"] == "checked" assert report["checked_metrics"] >= 2 assert len(report["failures"]) >= 1
def test_main_regression_fail_is_allowed_with_skip_flag(monkeypatch, tmp_path): _install_main_runtime_stubs(monkeypatch, tmp_path, mean_fsc=0.50, variance_fsc=0.40) baseline_path = tmp_path / "baseline.json" with open(baseline_path, "w") as f: json.dump({"mean_fsc": 0.99, "variance_fsc": 0.99}, f, indent=2)
monkeypatch.setattr( rtam.sys, "argv", [ "run_test_all_metrics", "--output-dir", str(tmp_path), "--cpu", "--volume-input", str(tmp_path / "fixed_vol_prefix_"), "--metrics-baseline-json", str(baseline_path), "--metrics-regression-tol-frac", "0.01", "--skip-metrics-regression-check", ], )
rtam.main()
report_path = tmp_path / "test_dataset" / "metrics_plot" / "metrics_regression_report.json" with open(report_path, "r") as f: report = json.load(f) assert report["status"] == "checked" assert len(report["failures"]) >= 1
def test_main_overwrite_metrics_baseline_forces_rewrite(monkeypatch, tmp_path): _install_main_runtime_stubs(monkeypatch, tmp_path, mean_fsc=0.61, variance_fsc=0.51) baseline_path = tmp_path / "baseline.json" with open(baseline_path, "w") as f: json.dump({"mean_fsc": 0.1, "variance_fsc": 0.1}, f, indent=2)
monkeypatch.setattr( rtam.sys, "argv", [ "run_test_all_metrics", "--output-dir", str(tmp_path), "--cpu", "--volume-input", str(tmp_path / "fixed_vol_prefix_"), "--metrics-baseline-json", str(baseline_path), "--overwrite-metrics-baseline", ], )
rtam.main()
report_path = tmp_path / "test_dataset" / "metrics_plot" / "metrics_regression_report.json" with open(baseline_path, "r") as f: baseline_scores = json.load(f) with open(report_path, "r") as f: report = json.load(f)
assert baseline_scores["mean_fsc"] == pytest.approx(0.61) assert baseline_scores["variance_fsc"] == pytest.approx(0.51) assert report["status"] == "baseline_written"
def test_main_regression_pass_writes_checked_report_without_failures(monkeypatch, tmp_path): _install_main_runtime_stubs(monkeypatch, tmp_path, mean_fsc=0.62, variance_fsc=0.52) baseline_path = tmp_path / "baseline.json" with open(baseline_path, "w") as f: json.dump( { "mean_fsc": 0.60, "variance_fsc": 0.50, "noise_mean_relative_error": 0.20, }, f, indent=2, )
monkeypatch.setattr( rtam.sys, "argv", [ "run_test_all_metrics", "--output-dir", str(tmp_path), "--cpu", "--volume-input", str(tmp_path / "fixed_vol_prefix_"), "--metrics-baseline-json", str(baseline_path), "--metrics-regression-tol-frac", "0.001", ], )
rtam.main()
report_path = tmp_path / "test_dataset" / "metrics_plot" / "metrics_regression_report.json" with open(report_path, "r") as f: report = json.load(f)
assert report["status"] == "checked" assert report["checked_metrics"] >= 3 assert report["failures"] == []
def test_main_explicit_volume_without_baseline_skips_regression_report(monkeypatch, tmp_path): _install_main_runtime_stubs(monkeypatch, tmp_path, mean_fsc=0.55, variance_fsc=0.45) monkeypatch.setattr( rtam.sys, "argv", [ "run_test_all_metrics", "--output-dir", str(tmp_path), "--cpu", "--volume-input", str(tmp_path / "fixed_vol_prefix_"), ], )
rtam.main()
scores_path = tmp_path / "test_dataset" / "metrics_plot" / "all_scores.json" report_path = tmp_path / "test_dataset" / "metrics_plot" / "metrics_regression_report.json" assert scores_path.exists() assert not report_path.exists()
def test_main_emits_canonical_metric_keys_and_perf(monkeypatch, tmp_path): """Check that a run emits canonical metric keys and perf metadata.""" _install_main_runtime_stubs(monkeypatch, tmp_path, mean_fsc=0.55, variance_fsc=0.45) monkeypatch.setattr( rtam.sys, "argv", [ "run_test_all_metrics", "--output-dir", str(tmp_path), "--cpu", "--volume-input", str(tmp_path / "fixed_vol_prefix_"), ], )
rtam.main()
scores_path = tmp_path / "test_dataset" / "metrics_plot" / "all_scores.json" with open(scores_path, "r") as f: scores = json.load(f)
# Canonical keys present assert "svd_relative_variance_4" in scores assert "svd_relative_variance_10" in scores assert "contrast_abs_error_4" in scores assert "contrast_abs_error_4_noreg" in scores assert "state_0_locres_90pct" in scores assert "state_0_locres_median" in scores
# Perf dict present with expected structure perf = scores.get("perf") assert isinstance(perf, dict) assert "gpu_name" in perf for stage in ["dataset_generation", "pipeline", "compute_state", "metrics"]: assert stage in perf, f"missing perf stage: {stage}" assert "wall_seconds" in perf[stage] assert "peak_gpu_memory_gb" in perf[stage] assert "peak_cpu_memory_gb" in perf[stage]
def test_main_regression_with_zero_comparable_metrics_writes_checked_report(monkeypatch, tmp_path): _install_main_runtime_stubs(monkeypatch, tmp_path, mean_fsc=0.55, variance_fsc=0.45) baseline_path = tmp_path / "baseline.json" with open(baseline_path, "w") as f: json.dump({"unknown_metric_name": 123.0}, f, indent=2)
monkeypatch.setattr( rtam.sys, "argv", [ "run_test_all_metrics", "--output-dir", str(tmp_path), "--cpu", "--volume-input", str(tmp_path / "fixed_vol_prefix_"), "--metrics-baseline-json", str(baseline_path), ], )
rtam.main()
report_path = tmp_path / "test_dataset" / "metrics_plot" / "metrics_regression_report.json" with open(report_path, "r") as f: report = json.load(f)
assert report["status"] == "checked" assert report["checked_metrics"] == 0 assert report["failures"] == []
def test_compute_noise_variance_metrics_single_noise(tmp_path): gt = np.array([1.0, 2.0, 3.0], dtype=np.float64) est = np.array([1.1, 1.8, 2.9], dtype=np.float64)
scores = rtam.compute_noise_variance_metrics(gt, est, str(tmp_path), _logger())
assert "noise_mean_relative_error" in scores assert "noise_median_relative_error" in scores assert "noise_max_relative_error" in scores assert "noise_correlation" in scores assert (tmp_path / "noise_variance_comparison.png").exists()
def test_compute_noise_variance_metrics_per_tilt(tmp_path): gt = np.array([1.0, 2.0, 3.0], dtype=np.float64) est = np.array( [ [1.0, 2.1, 2.9], [1.2, 2.2, 3.4], ], dtype=np.float64, ) dose_indices = np.array([0, 0, 1, 1], dtype=np.int64)
scores = rtam.compute_noise_variance_metrics( gt, est, str(tmp_path), _logger(), dose_indices=dose_indices, noise_increase_per_tilt=0.1, )
assert "noise_correlation_per_tilt" in scores assert len(scores["noise_correlation_per_tilt"]) == 2 assert len(scores["noise_mean_error_per_tilt"]) == 2 assert len(scores["noise_median_error_per_tilt"]) == 2 assert (tmp_path / "noise_variance_comparison_per_tilt.png").exists()
def test_compute_noise_variance_metrics_missing_gt_returns_empty(tmp_path): scores = rtam.compute_noise_variance_metrics(None, np.array([1.0]), str(tmp_path), _logger()) assert scores == {}
def test_compute_noise_variance_metrics_missing_estimate_returns_empty(tmp_path): gt = np.array([1.0, 2.0, 3.0], dtype=np.float64) scores = rtam.compute_noise_variance_metrics(gt, None, str(tmp_path), _logger()) assert scores == {}
def test_compute_noise_variance_metrics_truncates_mismatched_lengths(tmp_path): gt = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float64) est = np.array([1.1, 1.9], dtype=np.float64) scores = rtam.compute_noise_variance_metrics(gt, est, str(tmp_path), _logger()) assert "noise_mean_relative_error" in scores assert np.isfinite(scores["noise_mean_relative_error"]) assert (tmp_path / "noise_variance_comparison.png").exists()
def test_make_big_test_dataset_uses_detected_state_count(monkeypatch, tmp_path): captured = {}
def fake_isfile(path): return any(path.endswith(f"{i:04d}.mrc") for i in range(3))
def fake_generate_synthetic_dataset(*args, **kwargs): captured["args"] = args captured["kwargs"] = kwargs return None, {"simulated": True}
monkeypatch.setattr(rtam.os.path, "isfile", fake_isfile) monkeypatch.setattr(rtam.output, "mkdir_safe", lambda *_: None) monkeypatch.setattr(rtam.simulator, "generate_synthetic_dataset", fake_generate_synthetic_dataset)
sim_info = rtam.make_big_test_dataset( input_dir="/tmp/vol_prefix_", output_dir=str(tmp_path), n_images=25.0, grid_size=32, contrast_std=0.0, n_tilts=-1, )
assert sim_info == {"simulated": True} volume_distribution = captured["kwargs"]["volume_distribution"] assert volume_distribution.shape == (3,) assert np.isclose(np.sum(volume_distribution), 1.0) assert captured["args"][3] == 25
def test_make_big_test_dataset_raises_when_no_input_volumes(monkeypatch, tmp_path): monkeypatch.setattr(rtam.os.path, "isfile", lambda _p: False) monkeypatch.setattr(rtam.output, "mkdir_safe", lambda *_: None) with pytest.raises(ValueError, match="No volumes found for prefix"): rtam.make_big_test_dataset( input_dir="/tmp/nonexistent_prefix_", output_dir=str(tmp_path), n_images=10, grid_size=16, )
def test_validate_storage_args_for_generated_volumes_requires_explicit_outdir(): args = SimpleNamespace(volume_input=None) with pytest.raises(ValueError, match="must pass --output-dir/-o explicitly"): rtam.validate_storage_args_for_generated_volumes(args, argv=["--grid-size", "32"])
rtam.validate_storage_args_for_generated_volumes(args, argv=["--output-dir", "/scratch/tmp/out"]) rtam.validate_storage_args_for_generated_volumes(args, argv=["-o", "/scratch/tmp/out"])
args_with_input = SimpleNamespace(volume_input="/scratch/vol") rtam.validate_storage_args_for_generated_volumes(args_with_input, argv=["--grid-size", "32"])
def test_validate_storage_args_for_generated_volumes_accepts_equals_style_flags(): args = SimpleNamespace(volume_input=None) rtam.validate_storage_args_for_generated_volumes(args, argv=["--output-dir=/scratch/tmp/out"]) rtam.validate_storage_args_for_generated_volumes(args, argv=["-o=/scratch/tmp/out"])
@pytest.mark.parametrize( ("argv_extra", "msg"), [ (["--grid-size", "0"], "--grid-size must be positive"), (["--n-images", "0"], "--n-images must be positive"), (["--noise-level", "-1"], "--noise-level must be non-negative"), (["--contrast-std", "-0.1"], "--contrast-std must be non-negative"), (["--metrics-regression-tol-frac", "-0.01"], "--metrics-regression-tol-frac must be non-negative"), ],)def test_main_rejects_invalid_numeric_cli_args_early(monkeypatch, tmp_path, argv_extra, msg): monkeypatch.setattr( rtam.sys, "argv", [ "run_test_all_metrics", "--volume-input", str(tmp_path / "vol_prefix_"), "--output-dir", str(tmp_path), "--cpu", *argv_extra, ], ) with pytest.raises(ValueError, match=msg): rtam.main()
def test_main_rejects_nonpositive_generated_n_volumes_when_generating(monkeypatch, tmp_path): monkeypatch.setattr( rtam.sys, "argv", [ "run_test_all_metrics", "--output-dir", str(tmp_path), "--cpu", "--generate-pdb-volumes", "--generated-n-volumes", "0", ], ) with pytest.raises(ValueError, match="--generated-n-volumes must be positive"): rtam.main()
def test_resolve_metrics_baseline_path_defaults_for_generated_volumes(tmp_path): args = SimpleNamespace( metrics_baseline_json=None, generate_pdb_volumes=True, output_dir=str(tmp_path), grid_size=128, generated_n_volumes=50, ) path = rtam.resolve_metrics_baseline_path(args) assert path == tmp_path / "generated_volumes" / "metrics_baseline_pdb_grid128_nvol50.json"
def test_resolve_metrics_baseline_path_explicit_wins(tmp_path): explicit = tmp_path / "my_baseline.json" args = SimpleNamespace( metrics_baseline_json=str(explicit), generate_pdb_volumes=True, output_dir=str(tmp_path), grid_size=64, generated_n_volumes=10, ) assert rtam.resolve_metrics_baseline_path(args) == explicit
def test_resolve_metrics_baseline_path_returns_none_when_not_generated_and_not_explicit(tmp_path): args = SimpleNamespace( metrics_baseline_json=None, generate_pdb_volumes=False, output_dir=str(tmp_path), grid_size=64, generated_n_volumes=10, ) assert rtam.resolve_metrics_baseline_path(args) is None
def test_normalize_scores_for_json_handles_numpy_scalars_and_arrays(): inp = { "a": np.float32(1.25), "b": np.int64(7), "c": np.array([1.0, 2.0], dtype=np.float32), "d": "ok", "flag_py": True, "flag_np": np.bool_(False), } out = rtam.normalize_scores_for_json(inp) assert out["a"] == 1.25 assert out["b"] == 7.0 assert out["c"] == [1.0, 2.0] assert out["d"] == "ok" assert out["flag_py"] is True assert out["flag_np"] is False
def test_normalize_scores_for_json_handles_nested_dicts(): inp = { "mean_fsc": np.float32(0.5), "perf": { "gpu_name": "NVIDIA H100", "pipeline": { "wall_seconds": np.float64(123.4), "peak_gpu_memory_gb": 5.2, }, }, } out = rtam.normalize_scores_for_json(inp) assert out["mean_fsc"] == pytest.approx(0.5) assert out["perf"]["gpu_name"] == "NVIDIA H100" assert out["perf"]["pipeline"]["wall_seconds"] == pytest.approx(123.4) assert out["perf"]["pipeline"]["peak_gpu_memory_gb"] == pytest.approx(5.2)
def test_compare_scores_against_baseline_applies_direction_and_tolerance(): baseline = { "mean_fsc": 0.80, # higher is better "noise_mean_relative_error": 0.20, # lower is better "some_unknown_metric": 3.0, # ignored } current_ok = { "mean_fsc": 0.79, # slight drop (1.25%) "noise_mean_relative_error": 0.205, # slight increase (2.5%) "some_unknown_metric": 10.0, } checked, failures, details = rtam.compare_scores_against_baseline( current_ok, baseline, tol_frac=0.03, ) assert checked == 2 assert failures == [] assert details["mean_fsc"]["ok"] assert details["noise_mean_relative_error"]["ok"]
current_bad = dict(current_ok) current_bad["mean_fsc"] = 0.70 checked, failures, details = rtam.compare_scores_against_baseline( current_bad, baseline, tol_frac=0.03, ) assert checked == 2 assert len(failures) == 1 assert "mean_fsc" in failures[0] assert not details["mean_fsc"]["ok"]
def test_compare_metric_handles_non_finite_values(): ok, msg = rtam.compare_metric(np.nan, 1.0, direction="higher", tol_frac=0.05) assert not ok assert "non-finite values" in msg
ok, msg = rtam.compare_metric(1.0, np.inf, direction="lower", tol_frac=0.05) assert not ok assert "non-finite values" in msg
def test_metric_direction_recognizes_known_tokens_and_defaults_to_ignore(): assert rtam.metric_direction("mean_fsc") == "higher" assert rtam.metric_direction("noise_mean_relative_error") == "lower" assert rtam.metric_direction("unclassified_metric_name") == "ignore" # Canonical renamed keys assert rtam.metric_direction("svd_relative_variance_4") == "higher" assert rtam.metric_direction("contrast_abs_error_10_noreg") == "lower" assert rtam.metric_direction("state_0_locres_90pct") == "lower" assert rtam.metric_direction("state_1_locres_median") == "lower"
def test_load_u_real_for_metrics_prefers_selective_api(): class _PO: def get_u_real(self, n_pcs): assert n_pcs == 3 return np.ones((3, 2, 2, 2), dtype=np.float32)
out = rtam.load_u_real_for_metrics(_PO(), 3) assert out.shape == (3, 2, 2, 2)
def test_load_u_real_for_metrics_rejects_nonpositive_request(): class _PO: def get_u_real(self, _n_pcs): return np.zeros((1, 2), dtype=np.float32)
with pytest.raises(ValueError, match="n_pcs must be positive"): rtam.load_u_real_for_metrics(_PO(), 0)
def test_load_unsorted_embedding_component_caches_by_component(): """Components are cached by (entry, key)."""
class _PO: def __init__(self): self.get_calls = 0
def get_unsorted_embedding_component(self, entry, key): self.get_calls += 1 return { ("latent_coords", 10): np.array([1.0, 10.0], dtype=np.float32), ("latent_coords", 4): np.array([2.0, 4.0], dtype=np.float32), }[(entry, key)]
po = _PO() cache = {}
first = rtam.load_unsorted_embedding_component(po, "latent_coords", 10, cache) second = rtam.load_unsorted_embedding_component(po, "latent_coords", 10, cache) third = rtam.load_unsorted_embedding_component(po, "latent_coords", 4, cache)
assert po.get_calls == 2 np.testing.assert_array_equal(first, second) assert not np.array_equal(first, third)
def test_load_unsorted_embedding_component_caches_multiple_entries(): class _PO: def __init__(self): self.get_calls = 0
def get_unsorted_embedding_component(self, entry, key): self.get_calls += 1 return { ("latent_coords", 4): np.array([[1.0, 2.0]], dtype=np.float32), ("contrasts", 4): np.array([0.5], dtype=np.float32), }[(entry, key)]
po = _PO() cache = {} z_first = rtam.load_unsorted_embedding_component(po, "latent_coords", 4, cache) z_second = rtam.load_unsorted_embedding_component(po, "latent_coords", 4, cache) c_first = rtam.load_unsorted_embedding_component(po, "contrasts", 4, cache) c_second = rtam.load_unsorted_embedding_component(po, "contrasts", 4, cache)
assert po.get_calls == 2 np.testing.assert_array_equal(z_first, z_second) np.testing.assert_array_equal(c_first, c_second)
def test_select_state_target_latent_points_falls_back_to_nonempty_labels(): unsorted_zs = np.array( [ [0.0, 0.0], [2.0, 0.0], [4.0, 0.0], [6.0, 0.0], ], dtype=np.float32, ) particle_assignment = np.array([1, 1, 3, 3], dtype=np.int64)
points, labels = rtam.select_state_target_latent_points( unsorted_zs=unsorted_zs, particle_assignment=particle_assignment, preferred_labels=[0, 25], max_points=2, )
assert labels == [1, 3] np.testing.assert_allclose(points, np.array([[1.0, 0.0], [5.0, 0.0]], dtype=np.float32))
def test_select_state_target_latent_points_filters_nonfinite_rows(): unsorted_zs = np.array( [ [1.0, 2.0], [np.nan, 0.0], [3.0, 4.0], ], dtype=np.float32, ) particle_assignment = np.array([0, 0, 1], dtype=np.int64)
points, labels = rtam.select_state_target_latent_points( unsorted_zs=unsorted_zs, particle_assignment=particle_assignment, preferred_labels=[0, 1], max_points=2, )
assert labels == [0, 1] assert np.all(np.isfinite(points)) np.testing.assert_allclose(points[0], np.array([1.0, 2.0], dtype=np.float32)) np.testing.assert_allclose(points[1], np.array([3.0, 4.0], dtype=np.float32))
def test_select_state_target_latent_points_rejects_length_mismatch(): unsorted_zs = np.array([[0.0, 0.0], [1.0, 1.0]], dtype=np.float32) particle_assignment = np.array([0], dtype=np.int64)
with pytest.raises(ValueError, match="Length mismatch"): rtam.select_state_target_latent_points( unsorted_zs=unsorted_zs, particle_assignment=particle_assignment, preferred_labels=[0, 1], max_points=2, )
def test_select_state_target_latent_points_rejects_nonpositive_max_points(): unsorted_zs = np.array([[0.0, 0.0], [1.0, 1.0]], dtype=np.float32) particle_assignment = np.array([0, 1], dtype=np.int64) with pytest.raises(ValueError, match="max_points must be positive"): rtam.select_state_target_latent_points( unsorted_zs=unsorted_zs, particle_assignment=particle_assignment, preferred_labels=[0, 1], max_points=0, )
def test_select_state_target_latent_points_rejects_non_integer_like_assignments(): unsorted_zs = np.array([[0.0, 0.0], [1.0, 1.0]], dtype=np.float32) particle_assignment = np.array([0.1, 1.9], dtype=np.float32) with pytest.raises(ValueError, match="integer-like"): rtam.select_state_target_latent_points( unsorted_zs=unsorted_zs, particle_assignment=particle_assignment, preferred_labels=[0, 1], max_points=2, )
def test_select_state_target_latent_points_accepts_integer_like_float_assignments(): unsorted_zs = np.array([[0.0, 0.0], [2.0, 0.0], [4.0, 0.0], [6.0, 0.0]], dtype=np.float32) particle_assignment = np.array([0.0, 0.0, 1.0, 1.0], dtype=np.float32) points, labels = rtam.select_state_target_latent_points( unsorted_zs=unsorted_zs, particle_assignment=particle_assignment, preferred_labels=[1, 0], max_points=2, ) assert labels == [1, 0] np.testing.assert_allclose(points, np.array([[5.0, 0.0], [1.0, 0.0]], dtype=np.float32))
def test_select_state_target_latent_points_rejects_all_nonfinite_rows(): unsorted_zs = np.array([[np.nan, 0.0], [np.inf, -1.0]], dtype=np.float32) particle_assignment = np.array([0, 1], dtype=np.int64) with pytest.raises(ValueError, match="All rows in unsorted_zs are non-finite"): rtam.select_state_target_latent_points( unsorted_zs=unsorted_zs, particle_assignment=particle_assignment, preferred_labels=[0, 1], max_points=2, )
def test_compare_scores_against_baseline_checks_shared_canonical_keys(): current = { "svd_relative_variance_4": 0.90, "mean_fsc": 0.80, } baseline = { "svd_relative_variance_4": 0.89, "mean_fsc": 0.79, } checked, failures, details = rtam.compare_scores_against_baseline(current, baseline, tol_frac=0.05) assert checked == 2 assert failures == []
def test_compare_scores_against_baseline_checks_locres_metrics(): current = { "state_0_locres_90pct": 5.0, "state_0_locres_median": 4.0, } baseline = dict(current) checked, failures, details = rtam.compare_scores_against_baseline(current, baseline, tol_frac=0.01) assert checked == 2
def test_compare_scores_against_baseline_skips_non_numeric_values(): current = { "mean_fsc": 0.80, "meta_list": [1, 2, 3], # should be ignored "meta_dict": {"a": 1}, # should be ignored } baseline = { "mean_fsc": 0.79, "meta_list": [1, 2, 3], "meta_dict": {"a": 1}, } checked, failures, details = rtam.compare_scores_against_baseline(current, baseline, tol_frac=0.01) assert checked == 1 assert failures == [] assert sorted(details.keys()) == ["mean_fsc"]
def test_compare_scores_against_baseline_with_no_comparable_metrics(): current = {"meta_a": [1, 2], "meta_b": {"x": 1}} baseline = {"meta_a": [1, 2], "meta_b": {"x": 1}} checked, failures, details = rtam.compare_scores_against_baseline(current, baseline, tol_frac=0.01) assert checked == 0 assert failures == [] assert details == {}
def test_compare_scores_against_baseline_skips_boolean_values(): current = {"flag_metric": True, "mean_fsc": 0.8} baseline = {"flag_metric": False, "mean_fsc": 0.79} checked, failures, details = rtam.compare_scores_against_baseline(current, baseline, tol_frac=0.01) assert checked == 1 assert failures == [] assert "flag_metric" not in details assert "mean_fsc" in details
def test_compare_scores_against_baseline_skips_numpy_boolean_values(): current = {"flag_metric": np.bool_(True), "mean_fsc": 0.8} baseline = {"flag_metric": np.bool_(False), "mean_fsc": 0.79} checked, failures, details = rtam.compare_scores_against_baseline(current, baseline, tol_frac=0.01) assert checked == 1 assert failures == [] assert "flag_metric" not in details assert "mean_fsc" in details
def test_compute_noise_variance_metrics_per_tilt_without_dose_indices_returns_empty(tmp_path): gt = np.array([1.0, 2.0, 3.0], dtype=np.float64) est = np.array( [ [1.0, 2.1, 2.9], [1.2, 2.2, 3.4], ], dtype=np.float64, ) scores = rtam.compute_noise_variance_metrics( gt, est, str(tmp_path), _logger(), dose_indices=None, ) assert scores == {}
def test_compute_noise_variance_metrics_per_tilt_with_empty_dose_indices_returns_empty(tmp_path): gt = np.array([1.0, 2.0, 3.0], dtype=np.float64) est = np.array( [ [1.0, 2.1, 2.9], [1.2, 2.2, 3.4], ], dtype=np.float64, ) scores = rtam.compute_noise_variance_metrics( gt, est, str(tmp_path), _logger(), dose_indices=np.array([], dtype=np.int32), ) assert scores == {}
def test_compute_noise_variance_metrics_per_tilt_handles_noncontiguous_dose_labels(tmp_path): gt = np.array([1.0, 2.0, 3.0], dtype=np.float64) # Two modeled tilt rows, but dose labels are 3 and 7. est = np.array( [ [1.0, 2.1, 2.9], [1.2, 2.2, 3.4], ], dtype=np.float64, ) dose_indices = np.array([3, 3, 7, 7], dtype=np.int64)
scores = rtam.compute_noise_variance_metrics( gt, est, str(tmp_path), _logger(), dose_indices=dose_indices, noise_increase_per_tilt=0.05, ) assert "noise_correlation_per_tilt" in scores assert len(scores["noise_correlation_per_tilt"]) == 2 assert (tmp_path / "noise_variance_comparison_per_tilt.png").exists()
def test_compute_noise_variance_metrics_per_tilt_skips_unmatched_labels_without_zero_bias(tmp_path): gt = np.array([1.0, 2.0, 3.0], dtype=np.float64) # Only one estimated row is available. est = np.array( [ [1.0, 2.1, 2.9], ], dtype=np.float64, ) # Two labels present; second label cannot be matched and should be skipped. dose_indices = np.array([0, 0, 5, 5], dtype=np.int64)
scores = rtam.compute_noise_variance_metrics( gt, est, str(tmp_path), _logger(), dose_indices=dose_indices, noise_increase_per_tilt=0.0, ) assert "noise_correlation_per_tilt" in scores assert len(scores["noise_correlation_per_tilt"]) == 1 assert len(scores["noise_mean_error_per_tilt"]) == 1 assert len(scores["noise_median_error_per_tilt"]) == 1
def test_compute_noise_variance_metrics_per_tilt_all_unmatched_returns_empty(tmp_path): gt = np.array([1.0, 2.0, 3.0], dtype=np.float64) est = np.array([], dtype=np.float64).reshape(0, 3) dose_indices = np.array([4, 4, 9, 9], dtype=np.int64)
scores = rtam.compute_noise_variance_metrics( gt, est, str(tmp_path), _logger(), dose_indices=dose_indices, noise_increase_per_tilt=0.0, ) assert scores == {}
def test_compute_noise_variance_metrics_single_case_zero_overlap_returns_empty(tmp_path): gt = np.array([], dtype=np.float64) est = np.array([], dtype=np.float64) scores = rtam.compute_noise_variance_metrics(gt, est, str(tmp_path), _logger()) assert scores == {}
def test_compute_noise_variance_metrics_per_tilt_zero_overlap_skips_and_returns_empty(tmp_path): gt = np.array([], dtype=np.float64) est = np.array([[]], dtype=np.float64) # shape (1, 0) dose_indices = np.array([0, 0], dtype=np.int64) scores = rtam.compute_noise_variance_metrics( gt, est, str(tmp_path), _logger(), dose_indices=dose_indices, noise_increase_per_tilt=0.0, ) assert scores == {}
def test_compute_noise_variance_metrics_single_case_nonfinite_corr_is_stabilized(tmp_path): # Constant vectors produce NaN correlation from np.corrcoef. gt = np.ones(5, dtype=np.float64) est = np.ones(5, dtype=np.float64) scores = rtam.compute_noise_variance_metrics(gt, est, str(tmp_path), _logger()) assert "noise_correlation" in scores assert np.isfinite(scores["noise_correlation"]) assert scores["noise_correlation"] == 0.0
def test_compute_noise_variance_metrics_per_tilt_nonfinite_corr_is_stabilized(tmp_path): gt = np.ones(4, dtype=np.float64) est = np.ones((2, 4), dtype=np.float64) dose_indices = np.array([0, 0, 1, 1], dtype=np.int64) scores = rtam.compute_noise_variance_metrics( gt, est, str(tmp_path), _logger(), dose_indices=dose_indices, noise_increase_per_tilt=0.0, ) assert "noise_correlation_per_tilt" in scores assert all(np.isfinite(c) for c in scores["noise_correlation_per_tilt"]) assert scores["noise_correlation_per_tilt"] == [0.0, 0.0]
def test_compute_noise_variance_metrics_accepts_jax_arrays_for_per_tilt_branch(tmp_path): gt = jnp.array([1.0, 2.0, 3.0], dtype=jnp.float32) est = jnp.array( [ [1.0, 2.1, 2.9], [1.1, 2.0, 3.1], ], dtype=jnp.float32, ) dose_indices = np.array([0, 0, 1, 1], dtype=np.int32)
scores = rtam.compute_noise_variance_metrics( gt, est, str(tmp_path), _logger(), dose_indices=dose_indices, noise_increase_per_tilt=0.0, )
assert "noise_correlation_per_tilt" in scores assert len(scores["noise_correlation_per_tilt"]) == 2 assert (tmp_path / "noise_variance_comparison_per_tilt.png").exists()
def test_compute_noise_variance_metrics_accepts_jax_arrays_for_single_noise(tmp_path): gt = jnp.array([1.0, 2.0, 3.0, 4.0], dtype=jnp.float32) est = jnp.array([0.9, 2.1, 2.8, 4.2], dtype=jnp.float32)
scores = rtam.compute_noise_variance_metrics(gt, est, str(tmp_path), _logger())
assert "noise_mean_relative_error" in scores assert "noise_correlation" in scores assert np.isfinite(scores["noise_correlation"]) assert (tmp_path / "noise_variance_comparison.png").exists()
def test_compute_noise_variance_metrics_accepts_scalar_estimate(tmp_path): gt = np.array([1.0], dtype=np.float64) est = np.float64(0.8) scores = rtam.compute_noise_variance_metrics(gt, est, str(tmp_path), _logger()) assert "noise_mean_relative_error" in scores assert np.isfinite(scores["noise_correlation"])
def test_compute_noise_variance_metrics_accepts_python_lists_for_per_tilt(tmp_path): gt = [1.0, 2.0, 3.0] est = [[1.0, 2.1, 2.9], [0.9, 2.0, 3.2]] dose_indices = [0, 0, 1, 1]
scores = rtam.compute_noise_variance_metrics( gt, est, str(tmp_path), _logger(), dose_indices=dose_indices, noise_increase_per_tilt=0.0, ) assert "noise_correlation_per_tilt" in scores assert len(scores["noise_correlation_per_tilt"]) == 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183import numpy as npimport pytest
pytest.importorskip("finufft")
from recovar.simulation import simulate_scattering_potential as ssp
pytestmark = pytest.mark.unit
def test_get_exponent_and_constant_of_gaussian_ft_scales_with_sigma(): sigma_small = 0.7 sigma_large = 1.4
tau_small, c_small = ssp.get_exponent_and_constant_of_gaussian_FT(sigma_small, dim=3) tau_large, c_large = ssp.get_exponent_and_constant_of_gaussian_FT(sigma_large, dim=3)
assert tau_small > 0 assert c_small > 0 assert tau_large > tau_small np.testing.assert_allclose( tau_large / tau_small, (sigma_large / sigma_small) ** 2, rtol=1e-12, atol=1e-12, ) np.testing.assert_allclose(c_large, c_small, rtol=1e-12, atol=1e-12) np.testing.assert_allclose(c_small, 1.0, rtol=1e-12, atol=1e-12)
def test_gaussian_fn_on_k_matches_gaussian_atom_shape_fn(): sigma = 1.2 coords = np.array( [ [0.0, 0.0, 0.0], [0.25, -0.5, 0.1], [0.7, 0.1, -0.2], ], dtype=np.float64, )
fn = ssp.get_gaussian_fn_on_k(sigma) expected = ssp.gaussian_atom_shape_fn(coords, sigma) np.testing.assert_allclose(fn(coords), expected, rtol=1e-12, atol=1e-12)
def test_choose_number_of_atoms_is_monotonic_in_radius(): assert ssp.choose_number_of_atoms(8.0) > ssp.choose_number_of_atoms(4.0)
def test_get_random_points_in_unit_ball_are_within_radius_one(): pts = ssp.get_random_points_in_unit_ball(512) assert pts.shape == (512, 3) radii = np.linalg.norm(pts, axis=1) assert np.all(radii <= 1.0 + 1e-12)
def test_get_center_coord_offset_returns_box_midpoint(): coords = np.array( [ [-3.0, 2.0, 1.0], [5.0, -4.0, 7.0], [1.0, 9.0, -2.0], ], dtype=np.float64, ) offset = ssp.get_center_coord_offset(coords) expected = (coords.min(axis=0) + coords.max(axis=0)) / 2.0 np.testing.assert_allclose(offset, expected, rtol=0, atol=0)
def test_voltage_to_wavelength_decreases_with_voltage(): wl_100kv = ssp.voltage_to_wavelength(100.0) wl_300kv = ssp.voltage_to_wavelength(300.0) assert wl_300kv < wl_100kv assert wl_100kv > 0
def test_generate_volume_from_atom_positions_and_types_at_freq_coords_smoke(): atom_coords = np.array( [ [0.0, 0.0, 0.0], [0.5, -0.25, 0.2], ], dtype=np.float64, ) atom_types = np.array(["C", "C"], dtype="<U1") freq_coords = np.array( [ [0.0, 0.0, 0.0], [0.1, 0.0, 0.0], [-0.05, 0.08, -0.02], ], dtype=np.float64, )
density = ssp.generate_volume_from_atom_positions_and_types( atom_coords, atom_types, voxel_size=1.0, freq_coords=freq_coords, )
assert density.shape == (freq_coords.shape[0],) assert np.isfinite(density.real).all() assert np.isfinite(density.imag).all() assert np.abs(density[0]) > 0
def test_generate_volume_from_atom_positions_and_types_accepts_lowercase_atom_types(): atom_coords = np.array( [ [0.0, 0.0, 0.0], [0.25, 0.1, -0.2], ], dtype=np.float64, ) freq_coords = np.array( [ [0.0, 0.0, 0.0], [0.1, -0.05, 0.02], ], dtype=np.float64, ) upper = ssp.generate_volume_from_atom_positions_and_types( atom_coords=atom_coords, atom_types=np.array(["C", "C"], dtype="<U1"), voxel_size=1.0, freq_coords=freq_coords, ) lower = ssp.generate_volume_from_atom_positions_and_types( atom_coords=atom_coords, atom_types=np.array(["c", "c"], dtype="<U1"), voxel_size=1.0, freq_coords=freq_coords, ) np.testing.assert_allclose(lower, upper, rtol=1e-12, atol=1e-12)
def test_generate_volume_from_atom_positions_and_types_rejects_length_mismatch(): atom_coords = np.array([[0.0, 0.0, 0.0], [0.1, 0.2, 0.3]], dtype=np.float64) with pytest.raises(ValueError, match="length mismatch"): ssp.generate_volume_from_atom_positions_and_types( atom_coords=atom_coords, atom_types=np.array(["C"], dtype="<U1"), voxel_size=1.0, freq_coords=np.array([[0.0, 0.0, 0.0]], dtype=np.float64), )
def test_generate_volume_from_atom_positions_and_types_rejects_unknown_atom_types(): atom_coords = np.array([[0.0, 0.0, 0.0]], dtype=np.float64) with pytest.raises(ValueError, match="Unknown atom types"): ssp.generate_volume_from_atom_positions_and_types( atom_coords=atom_coords, atom_types=np.array(["XX"], dtype="<U2"), voxel_size=1.0, freq_coords=np.array([[0.0, 0.0, 0.0]], dtype=np.float64), )
def test_generate_volume_from_atom_positions_and_types_uses_complex64_for_float32_inputs(): atom_coords = np.array([[0.0, 0.0, 0.0], [0.2, -0.1, 0.3]], dtype=np.float32) freq_coords = np.array([[0.0, 0.0, 0.0], [0.1, 0.0, -0.1]], dtype=np.float32) density = ssp.generate_volume_from_atom_positions_and_types( atom_coords=atom_coords, atom_types=np.array(["C", "C"], dtype="<U1"), voxel_size=1.0, freq_coords=freq_coords, ) assert density.dtype == np.complex64
def test_generate_volume_from_atom_positions_and_types_uses_complex128_for_float64_inputs(): atom_coords = np.array([[0.0, 0.0, 0.0], [0.2, -0.1, 0.3]], dtype=np.float64) freq_coords = np.array([[0.0, 0.0, 0.0], [0.1, 0.0, -0.1]], dtype=np.float64) density = ssp.generate_volume_from_atom_positions_and_types( atom_coords=atom_coords, atom_types=np.array(["C", "C"], dtype="<U1"), voxel_size=1.0, freq_coords=freq_coords, ) assert density.dtype == np.complex128123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247import numpy as npimport pytest
pytest.importorskip("jax")pytest.importorskip("scipy")
import recovar.simulation.simulator as simulatorfrom recovar import core
pytestmark = pytest.mark.unit
def test_set_constant_ctf_sets_expected_columns(): params = np.arange(2 * 11, dtype=np.float32).reshape(2, 11) out = simulator.set_constant_ctf(params.copy()) np.testing.assert_array_equal(out[:, 0], 0.0) np.testing.assert_array_equal(out[:, 1], 0.0) np.testing.assert_array_equal(out[:, 4], 0.0) np.testing.assert_array_equal(out[:, 5], -1.0)
def test_uniform_rotation_sampling_reproducible(): r1 = simulator.uniform_rotation_sampling(8, grid_size=64, seed=123) r2 = simulator.uniform_rotation_sampling(8, grid_size=64, seed=123) np.testing.assert_allclose(r1, r2)
def test_nonuniform_rotation_sampling_reproducible(): r1 = simulator.nonuniform_rotation_sampling(8, grid_size=64, seed=123) r2 = simulator.nonuniform_rotation_sampling(8, grid_size=64, seed=123) np.testing.assert_allclose(r1, r2)
def test_cryo_rotation_batch_properties_and_shapes(): single = simulator.cryo_rotation_batch([0.0, 0.0, 2.0], np.pi / 3) assert single.shape == (3, 3) np.testing.assert_allclose(single @ single.T, np.eye(3), atol=1e-6, rtol=1e-6) np.testing.assert_allclose(np.linalg.det(single), 1.0, atol=1e-6, rtol=1e-6)
U = np.array([[0.0, 0.0, 1.0], [1.0, 2.0, 3.0]]) theta = np.array([0.2, -0.1]) batch = simulator.cryo_rotation_batch(U, theta) assert batch.shape == (2, 3, 3) np.testing.assert_allclose( batch @ np.transpose(batch, (0, 2, 1)), np.broadcast_to(np.eye(3), batch.shape), atol=1e-6, rtol=1e-6, )
def test_cryo_rotation_batch_rejects_bad_inputs(): with pytest.raises(ValueError): simulator.cryo_rotation_batch(np.zeros((2, 2)), 0.0) with pytest.raises(ValueError): simulator.cryo_rotation_batch([0.0, 0.0, 0.0], 0.0)
def test_generate_contrast_params_shape(): contrast, noise_scale = simulator.generate_contrast_params(10, noise_scale_std=0.2, contrast_std=0.1) assert contrast.shape == (10,) assert noise_scale.shape == (10,)
def test_get_noise_model_white(): out = simulator.get_noise_model("white", grid_size=16) np.testing.assert_array_equal(out, np.ones(16 // 2 - 1))
def test_get_pose_ctf_generator_dispatch(): assert simulator.get_pose_ctf_generator("uniform") is simulator.random_sampling_scheme assert simulator.get_pose_ctf_generator("noctf") is simulator.noctf_random_sampling_scheme assert simulator.get_pose_ctf_generator("kent") is simulator.kent_sampling_scheme
f_nonuniform = simulator.get_pose_ctf_generator("nonuniform") assert callable(f_nonuniform)
f_kent_args = simulator.get_pose_ctf_generator([10, 5, [1, 0, 0], [0, 1, 0]]) assert callable(f_kent_args)
f_default = simulator.get_pose_ctf_generator("unknown-option") assert callable(f_default)
def _make_fake_param_generator(n_cols=9): def _generator(n_images, grid_size): ctf = np.zeros((n_images, n_cols), dtype=np.float32) ctf[:, core.CTFParamIndex.VOLT] = 300.0 ctf[:, core.CTFParamIndex.CS] = 2.7 ctf[:, core.CTFParamIndex.W] = 0.1 ctf[:, core.CTFParamIndex.CONTRAST] = 1.0 rots = np.tile(np.eye(3, dtype=np.float32), (n_images, 1, 1)) trans = np.zeros((n_images, 2), dtype=np.float32) return ctf, rots, trans
return _generator
def test_generate_simulated_dataset_tilt_branch_wires_ctf_and_metadata(monkeypatch): volumes = np.ones((2, 4**3), dtype=np.complex64) voxel_size = 1.5 n_images = 6 n_tilts = 3 volume_distribution = np.array([0.6, 0.4], dtype=np.float32) noise_variance = np.ones(3, dtype=np.float32)
created = []
def _fake_cryo_dataset(image_stack, voxel_size, metadata, ctf_evaluator=None, grid_size=None, **kwargs): obj = type("FakeDataset", (), {})() obj.n_images = metadata.n_images obj.image_shape = (grid_size, grid_size) obj.CTF_params = metadata._ctf_params obj.ctf_evaluator = ctf_evaluator obj.grid_size = grid_size obj.voxel_size = voxel_size obj.volume_shape = (grid_size, grid_size, grid_size) obj.translations = metadata._translations obj.rotation_matrices = metadata._rotation_matrices created.append(obj) return obj
monkeypatch.setattr(simulator.cryoem_dataset, "CryoEMDataset", _fake_cryo_dataset) monkeypatch.setattr(simulator.utils, "get_gpu_memory_total", lambda: 10) monkeypatch.setattr(simulator.utils, "get_image_batch_size", lambda grid_size, gpu_mem: 2) monkeypatch.setattr( simulator, "simulate_data", lambda experiment_dataset, volumes, noise_variance, batch_size, image_assignments, per_image_contrast, per_image_noise_scale, **kwargs: ( np.zeros( (experiment_dataset.n_images, experiment_dataset.image_shape[0], experiment_dataset.image_shape[1]), dtype=np.float32, ) ), )
out = simulator.generate_simulated_dataset( volumes=volumes, voxel_size=voxel_size, volume_distribution=volume_distribution, n_images=n_images, noise_variance=noise_variance, noise_scale_std=0.0, contrast_std=0.0, put_extra_particles=False, dataset_param_generator=_make_fake_param_generator(), n_tilts=n_tilts, dose_per_tilt=2.0, angle_per_tilt=5.0, image_offset_n_std=0.0, )
main_image_stack, ctf_params, rots, trans, simulation_info, _, tilt_groups = out assert main_image_stack.shape == (n_images, 4, 4) np.testing.assert_array_equal(tilt_groups, np.array([0, 0, 0, 1, 1, 1])) assert ctf_params.shape[1] == 11 # base 9 + dose + angle np.testing.assert_array_equal( ctf_params[:, core.CTFParamIndex.BFACTOR], -4 * ((np.arange(n_images) % n_tilts) + 0.5) * 2.0, ) assert simulation_info["n_tilts"] == n_tilts np.testing.assert_array_equal(simulation_info["tilt_groups"], tilt_groups) assert created[0].ctf_evaluator.mode == core.CTFMode.CRYO_ET
def test_generate_simulated_dataset_extra_particles_and_outliers(monkeypatch): np.random.seed(0) volumes = np.ones((1, 4**3), dtype=np.complex64) voxel_size = 1.0 n_images = 5 volume_distribution = np.array([1.0], dtype=np.float32) noise_variance = np.ones(3, dtype=np.float32) outlier_volume = np.ones((4**3,), dtype=np.complex64)
class _FakeDatasetObj: def __init__(self, n_images, grid_size, ctf_eval, ctf_params, rots, trans): self.n_images = n_images self.image_shape = (grid_size, grid_size) self.ctf_evaluator = ctf_eval self.CTF_params = ctf_params self.rotation_matrices = rots self.translations = trans self.grid_size = grid_size self.voxel_size = voxel_size self.volume_shape = (grid_size, grid_size, grid_size)
def _fake_cryo_dataset(image_stack, voxel_size, metadata, ctf_evaluator=None, grid_size=None, **kwargs): return _FakeDatasetObj( metadata.n_images, grid_size, ctf_evaluator, metadata._ctf_params, metadata._rotation_matrices, metadata._translations, )
monkeypatch.setattr(simulator.cryoem_dataset, "CryoEMDataset", _fake_cryo_dataset) monkeypatch.setattr(simulator.utils, "get_gpu_memory_total", lambda: 10) monkeypatch.setattr(simulator.utils, "get_image_batch_size", lambda grid_size, gpu_mem: 2)
call_values = [1.0, 10.0, 99.0] calls = {"n": 0}
def _fake_simulate_data( experiment_dataset, volumes, noise_variance, batch_size, image_assignments, per_image_contrast, per_image_noise_scale, **kwargs, ): val = call_values[calls["n"]] calls["n"] += 1 return np.full( (experiment_dataset.n_images, experiment_dataset.image_shape[0], experiment_dataset.image_shape[1]), val, dtype=np.float32, )
monkeypatch.setattr(simulator, "simulate_data", _fake_simulate_data)
out = simulator.generate_simulated_dataset( volumes=volumes, voxel_size=voxel_size, volume_distribution=volume_distribution, n_images=n_images, noise_variance=noise_variance, noise_scale_std=0.0, contrast_std=0.0, put_extra_particles=True, percent_outliers=0.4, outlier_volume=outlier_volume, dataset_param_generator=_make_fake_param_generator(), image_offset_n_std=0.0, ) main_image_stack, _, _, _, simulation_info, _, _ = out assert calls["n"] == 3 # main + extra + outlier
image_assignments = simulation_info["image_assignment"] n_outliers = int(np.round(0.4 * n_images)) assert np.sum(image_assignments == -1) == n_outliers
# Non-outliers should be main(1) + extra(10) = 11, outliers replaced by 99. means = main_image_stack.mean(axis=(1, 2)) np.testing.assert_array_equal(np.sort(np.unique(means)), np.array([11.0, 99.0], dtype=np.float32))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import numpy as npimport pytest
pytest.importorskip("jax")
import jax.numpy as jnpfrom jax.experimental import sparse
from recovar.heterogeneity import small_experiment as se
def test_vec_unvec_roundtrip(): x = np.arange(16, dtype=np.float32).reshape(4, 4) v = se.vec(x) x2 = se.unvec(v) assert x2.shape == x.shape assert np.allclose(x2, x)
def test_indices_to_coo_shape_and_values(): indices = np.array([[0, 2], [1, 3]], dtype=np.int32) data = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32) coo = se.indices_to_coo(indices, n=5, data=data) dense = np.array(coo.todense()) assert dense.shape == (2, 5) assert np.allclose(dense[0, [0, 2]], [1.0, 2.0]) assert np.allclose(dense[1, [1, 3]], [3.0, 4.0])
def test_subsample_coo_columns_remaps_columns(): rows = jnp.array([0, 0, 1, 1], dtype=jnp.int32) cols = jnp.array([0, 2, 1, 3], dtype=jnp.int32) vals = jnp.array([10.0, 20.0, 30.0, 40.0], dtype=jnp.float32) sp = sparse.BCOO((vals, jnp.stack([rows, cols], axis=1)), shape=(2, 4)) sub = se.subsample_coo_columns(sp, right_indices=jnp.array([1, 3], dtype=jnp.int32)) dense = np.array(sub.todense()) assert dense.shape == (2, 2) assert np.allclose(dense[0], [0.0, 0.0]) assert np.allclose(dense[1], [30.0, 40.0])
def test_make_random_sampling_scheme_shape_and_range(): indices = se.make_random_sampling_scheme(grid_size=6, m=3, seed=1) n = 6 * 6 * 6 assert indices.shape[0] == 3 assert int(indices.min()) >= 0 assert int(indices.max()) < n123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271"""Tests for recovar.data_io.staging — transparent MRC local staging."""
import osimport time
import mrcfileimport numpy as npimport pytest
from recovar.data_io.staging import _cache_key, get_cache_dir, stage_mrc
# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------
def _write_mrc(path, n: int = 8, D: int = 16, seed: int = 0) -> np.ndarray: """Write a minimal MRC stack; return the raw float32 data.""" rng = np.random.default_rng(seed) data = rng.standard_normal((n, D, D)).astype(np.float32) with mrcfile.new(str(path), overwrite=True) as mrc: mrc.set_data(data) return data
# ---------------------------------------------------------------------------# get_cache_dir# ---------------------------------------------------------------------------
class TestGetCacheDir: def test_returns_recovar_cache_dir(self, monkeypatch): monkeypatch.setenv("RECOVAR_CACHE_DIR", "/some/fast/disk") monkeypatch.delenv("TMPDIR", raising=False) assert get_cache_dir() == "/some/fast/disk"
def test_falls_back_to_tmpdir(self, monkeypatch): monkeypatch.delenv("RECOVAR_CACHE_DIR", raising=False) monkeypatch.setenv("TMPDIR", "/tmp/slurm_job123") assert get_cache_dir() == "/tmp/slurm_job123"
def test_recovar_cache_dir_takes_precedence_over_tmpdir(self, monkeypatch): monkeypatch.setenv("RECOVAR_CACHE_DIR", "/fast") monkeypatch.setenv("TMPDIR", "/tmp") assert get_cache_dir() == "/fast"
def test_empty_string_disables_even_when_tmpdir_set(self, monkeypatch): monkeypatch.setenv("RECOVAR_CACHE_DIR", "") monkeypatch.setenv("TMPDIR", "/tmp/slurm_job123") assert get_cache_dir() is None
def test_both_unset_returns_none(self, monkeypatch): monkeypatch.delenv("RECOVAR_CACHE_DIR", raising=False) monkeypatch.delenv("TMPDIR", raising=False) assert get_cache_dir() is None
# ---------------------------------------------------------------------------# _cache_key# ---------------------------------------------------------------------------
class TestCacheKey: def test_different_paths_give_different_keys(self, tmp_path): a = tmp_path / "a.mrcs" b = tmp_path / "b.mrcs" _write_mrc(a) _write_mrc(b) assert _cache_key(str(a), os.stat(a)) != _cache_key(str(b), os.stat(b))
def test_same_path_same_stat_gives_same_key(self, tmp_path): f = tmp_path / "p.mrcs" _write_mrc(f) stat = os.stat(f) assert _cache_key(str(f), stat) == _cache_key(str(f), stat)
def test_changed_mtime_gives_different_key(self, tmp_path): f = tmp_path / "p.mrcs" _write_mrc(f) stat1 = os.stat(f) os.utime(f, (stat1.st_atime + 1, stat1.st_mtime + 1)) stat2 = os.stat(f) assert _cache_key(str(f), stat1) != _cache_key(str(f), stat2)
def test_key_is_short_hex(self, tmp_path): f = tmp_path / "p.mrcs" _write_mrc(f) key = _cache_key(str(f), os.stat(f)) assert len(key) == 20 int(key, 16) # must be valid hex
# ---------------------------------------------------------------------------# stage_mrc# ---------------------------------------------------------------------------
class TestStageMrc: def test_copies_file_to_cache_subdir(self, tmp_path): src = tmp_path / "particles.mrcs" _write_mrc(src) cache_dir = tmp_path / "cache"
staged = stage_mrc(str(src), str(cache_dir))
assert staged != str(src) assert os.path.exists(staged) assert "recovar_cache" in staged assert staged.endswith(".mrcs")
def test_staged_content_matches_source(self, tmp_path): src = tmp_path / "particles.mrcs" data = _write_mrc(src) cache_dir = tmp_path / "cache"
staged = stage_mrc(str(src), str(cache_dir))
with mrcfile.open(staged, mode="r") as mrc: np.testing.assert_array_equal(mrc.data, data)
def test_idempotent_returns_same_path(self, tmp_path): src = tmp_path / "particles.mrcs" _write_mrc(src) cache_dir = tmp_path / "cache"
staged1 = stage_mrc(str(src), str(cache_dir)) staged2 = stage_mrc(str(src), str(cache_dir))
assert staged1 == staged2
def test_second_call_does_not_recopy(self, tmp_path): src = tmp_path / "particles.mrcs" _write_mrc(src) cache_dir = tmp_path / "cache"
staged = stage_mrc(str(src), str(cache_dir)) mtime_after_first = os.path.getmtime(staged) time.sleep(0.05)
stage_mrc(str(src), str(cache_dir)) mtime_after_second = os.path.getmtime(staged)
assert mtime_after_first == mtime_after_second # not re-copied
def test_source_update_triggers_new_cache_entry(self, tmp_path): src = tmp_path / "particles.mrcs" _write_mrc(src, seed=1) cache_dir = tmp_path / "cache"
staged1 = stage_mrc(str(src), str(cache_dir))
# Rewrite source with different data → different mtime time.sleep(0.01) _write_mrc(src, seed=2) os.utime(src, None) # ensure mtime changes even on coarse filesystems
staged2 = stage_mrc(str(src), str(cache_dir))
assert staged1 != staged2
def test_source_already_under_cache_dir_is_skipped(self, tmp_path): cache_dir = tmp_path / "cache" cache_dir.mkdir() src = cache_dir / "particles.mrcs" _write_mrc(src)
staged = stage_mrc(str(src), str(cache_dir))
assert staged == str(src)
def test_nonexistent_source_returns_src_path(self, tmp_path): src = str(tmp_path / "missing.mrcs") cache_dir = tmp_path / "cache"
result = stage_mrc(src, str(cache_dir))
assert result == src # graceful fallback
def test_preserves_mrc_extension(self, tmp_path): src = tmp_path / "map.mrc" _write_mrc(src) cache_dir = tmp_path / "cache"
staged = stage_mrc(str(src), str(cache_dir))
assert staged.endswith(".mrc")
def test_sentinel_file_created(self, tmp_path): src = tmp_path / "particles.mrcs" _write_mrc(src) cache_dir = tmp_path / "cache"
staged = stage_mrc(str(src), str(cache_dir))
sentinel = staged.replace(".mrcs", ".ok") assert os.path.exists(sentinel)
# ---------------------------------------------------------------------------# Integration: MRCLoader reads through staged file# ---------------------------------------------------------------------------
class TestMRCLoaderWithStaging: def test_loader_reads_from_staged_path(self, tmp_path, monkeypatch): src = tmp_path / "particles.mrcs" data = _write_mrc(src, n=8, D=16) cache_dir = tmp_path / "cache" monkeypatch.setenv("RECOVAR_CACHE_DIR", str(cache_dir))
from recovar.data_io.image_loader import MRCLoader
loader = MRCLoader(str(src))
assert "recovar_cache" in loader._filepath np.testing.assert_array_almost_equal(loader.get(), data)
def test_loader_uses_source_when_staging_disabled(self, tmp_path, monkeypatch): src = tmp_path / "particles.mrcs" _write_mrc(src) monkeypatch.setenv("RECOVAR_CACHE_DIR", "") # explicitly disabled monkeypatch.delenv("TMPDIR", raising=False)
from recovar.data_io.image_loader import MRCLoader
loader = MRCLoader(str(src))
assert loader._filepath == str(src)
def test_loader_uses_source_when_no_cache_env(self, tmp_path, monkeypatch): src = tmp_path / "particles.mrcs" _write_mrc(src) monkeypatch.delenv("RECOVAR_CACHE_DIR", raising=False) monkeypatch.delenv("TMPDIR", raising=False)
from recovar.data_io.image_loader import MRCLoader
loader = MRCLoader(str(src))
assert loader._filepath == str(src)
def test_subset_indices_read_correctly_via_staged(self, tmp_path, monkeypatch): src = tmp_path / "particles.mrcs" data = _write_mrc(src, n=20, D=16) cache_dir = tmp_path / "cache" monkeypatch.setenv("RECOVAR_CACHE_DIR", str(cache_dir))
from recovar.data_io.image_loader import MRCLoader
indices = np.array([0, 5, 12, 19]) loader = MRCLoader(str(src), indices=indices)
result = loader.get() np.testing.assert_array_almost_equal(result, data[indices])
def test_two_loaders_same_src_reuse_cache(self, tmp_path, monkeypatch): src = tmp_path / "particles.mrcs" _write_mrc(src) cache_dir = tmp_path / "cache" monkeypatch.setenv("RECOVAR_CACHE_DIR", str(cache_dir))
from recovar.data_io.image_loader import MRCLoader
loader1 = MRCLoader(str(src)) loader2 = MRCLoader(str(src))
assert loader1._filepath == loader2._filepath # Only one staged file in the cache dir staged_files = list((cache_dir / "recovar_cache").glob("*.mrcs")) assert len(staged_files) == 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289import numpy as npimport pandas as pdimport pytest
from recovar.data_io.starfile import StarFile, read_star, write_star
pytestmark = pytest.mark.unit
def test_read_star_requires_star_extension(tmp_path): bad = tmp_path / "particles.txt" bad.write_text("data_\n") with pytest.raises(ValueError, match="Expected .star file"): read_star(str(bad))
def test_write_and_read_relion30_roundtrip(tmp_path): data = pd.DataFrame( { "_rlnImageName": ["1@a.mrcs", "2@a.mrcs"], "_rlnDefocusU": ["10000", "11000"], } ) path = tmp_path / "r30.star" write_star(str(path), data)
loaded_data, loaded_optics = read_star(str(path)) assert loaded_optics is None assert loaded_data.equals(data)
def test_write_and_read_relion31_roundtrip(tmp_path): data = pd.DataFrame( { "_rlnImageName": ["1@a.mrcs", "2@a.mrcs", "3@a.mrcs"], "_rlnOpticsGroup": ["1", "2", "1"], } ) optics = pd.DataFrame( { "_rlnOpticsGroup": ["1", "2"], "_rlnImagePixelSize": ["1.5", "2.0"], "_rlnImageSize": ["128", "64"], } ) path = tmp_path / "r31.star" write_star(str(path), data, optics)
loaded_data, loaded_optics = read_star(str(path)) assert loaded_data.equals(data) assert loaded_optics.equals(optics)
sf = StarFile.load(str(path)) assert sf.has_optics np.testing.assert_allclose(sf.apix, np.array([1.5, 2.0, 1.5], dtype=np.float32)) np.testing.assert_array_equal(sf.resolution, np.array([128, 64, 128], dtype=np.int64))
def test_set_optics_values_moves_per_particle_values_to_main_table(): data = pd.DataFrame( { "_rlnImageName": ["1@a.mrcs", "2@a.mrcs", "3@a.mrcs"], "_rlnOpticsGroup": ["1", "2", "1"], } ) optics = pd.DataFrame( { "_rlnOpticsGroup": ["1", "2"], "_rlnVoltage": ["300", "200"], } ) sf = StarFile(data=data, data_optics=optics) sf.set_optics_values("_rlnVoltage", [10, 20, 30])
assert "_rlnVoltage" in sf.df.columns assert "_rlnVoltage" not in sf.data_optics.columns np.testing.assert_array_equal(sf.df["_rlnVoltage"].values, np.array([10, 20, 30]))
def test_flatten_to_relion30_includes_optics_fields(): data = pd.DataFrame( { "_rlnImageName": ["1@a.mrcs", "2@a.mrcs"], "_rlnOpticsGroup": ["1", "2"], } ) optics = pd.DataFrame( { "_rlnOpticsGroup": ["1", "2"], "_rlnImagePixelSize": ["1.1", "1.2"], } ) sf = StarFile(data=data, data_optics=optics) flattened = sf.flatten_to_relion30()
assert "_rlnImagePixelSize" in flattened.columns np.testing.assert_allclose(flattened["_rlnImagePixelSize"].astype(float).values, np.array([1.1, 1.2]))
def test_read_star_rejects_duplicate_data_blocks(tmp_path): path = tmp_path / "dup.star" path.write_text( "data_particles\n\nloop_\n_rlnImageName #1\n1@a.mrcs\n\ndata_particles\n\nloop_\n_rlnImageName #1\n2@a.mrcs\n" ) with pytest.raises(ValueError, match="Duplicate data block"): read_star(str(path))
def test_read_star_rejects_inconsistent_row_lengths(tmp_path): path = tmp_path / "bad_rows.star" path.write_text("data_particles\n\nloop_\n_rlnImageName #1\n_rlnDefocusU #2\n1@a.mrcs 10000\n2@a.mrcs\n") with pytest.raises(ValueError, match="Inconsistent row lengths"): read_star(str(path))
def test_read_star_rejects_when_no_nonempty_data_table_exists(tmp_path): path = tmp_path / "no_data.star" path.write_text("data_particles\n\nloop_\n_rlnImageName #1\n") with pytest.raises(ValueError, match="No data table found"): read_star(str(path))
def test_read_star_column_count_mismatch(tmp_path): path = tmp_path / "col_mismatch.star" path.write_text("data_\n\nloop_\n_rlnImageName\n_rlnDefocusU\n1@a.mrcs 10000 extra_col\n") with pytest.raises(ValueError, match="Column count mismatch"): read_star(str(path))
def test_read_star_ignores_comments(tmp_path): path = tmp_path / "comments.star" path.write_text("# This is a comment\ndata_\n\nloop_\n_rlnImageName\n# Another comment\n1@a.mrcs\n2@a.mrcs\n") main, optics = read_star(str(path)) assert len(main) == 2
# ---------------------------------------------------------------------------# StarFile constructor edge cases# ---------------------------------------------------------------------------
def test_starfile_from_data(): df = pd.DataFrame({"_rlnImageName": ["a", "b"], "_rlnDefocusU": ["1", "2"]}) sf = StarFile(data=df) assert len(sf) == 2 assert not sf.has_optics assert not sf.relion31
def test_starfile_no_args_raises(): with pytest.raises(ValueError, match="exactly one"): StarFile()
def test_starfile_both_args_raises(tmp_path): path = tmp_path / "test.star" path.write_text("data_\n\nloop_\n_rlnImageName\n1@a.mrcs\n") df = pd.DataFrame({"_rlnImageName": ["a"]}) with pytest.raises(ValueError, match="exactly one"): StarFile(str(path), data=df)
def test_starfile_write_alias(tmp_path): df = pd.DataFrame({"_rlnImageName": ["a"], "_rlnDefocusU": ["10000"]}) sf = StarFile(data=df) out = str(tmp_path / "alias.star") sf.write(out) sf2 = StarFile.load(out) assert len(sf2) == 1
def test_starfile_eq_same(): df = pd.DataFrame({"_rlnImageName": ["a", "b"]}) sf1 = StarFile(data=df.copy()) sf2 = StarFile(data=df.copy()) assert sf1 == sf2
def test_starfile_ne_different_data(): df1 = pd.DataFrame({"_rlnImageName": ["a"]}) df2 = pd.DataFrame({"_rlnImageName": ["b"]}) sf1 = StarFile(data=df1) sf2 = StarFile(data=df2) assert sf1 != sf2
def test_starfile_ne_optics_mismatch(): df = pd.DataFrame({"_rlnImageName": ["a"], "_rlnOpticsGroup": ["1"]}) optics = pd.DataFrame({"_rlnOpticsGroup": ["1"], "_rlnVoltage": ["300"]}) sf1 = StarFile(data=df.copy(), data_optics=optics.copy()) sf2 = StarFile(data=df.copy()) assert sf1 != sf2
# ---------------------------------------------------------------------------# get_optics_values edge cases# ---------------------------------------------------------------------------
def test_get_optics_values_missing_field(): df = pd.DataFrame({"_rlnImageName": ["a"]}) sf = StarFile(data=df) assert sf.get_optics_values("_rlnNonExistent") is None
def test_get_optics_values_dtype_cast(): df = pd.DataFrame({"_rlnDefocusU": ["15000", "16000"]}) sf = StarFile(data=df) vals = sf.get_optics_values("_rlnDefocusU", dtype=np.float64) assert vals.dtype == np.float64 np.testing.assert_allclose(vals, [15000.0, 16000.0])
# ---------------------------------------------------------------------------# set_optics_values edge cases# ---------------------------------------------------------------------------
def test_set_optics_values_scalar(): df = pd.DataFrame({"_rlnDefocusU": ["100", "200", "300"]}) sf = StarFile(data=df) sf.set_optics_values("_rlnDefocusU", 999) assert all(v == 999 for v in sf.df["_rlnDefocusU"])
def test_set_optics_values_invalid_length(): df = pd.DataFrame({"_rlnDefocusU": ["100", "200", "300"]}) sf = StarFile(data=df) with pytest.raises(ValueError, match="Values length"): sf.set_optics_values("_rlnDefocusU", [1, 2])
def test_set_optics_values_unknown_field(): df = pd.DataFrame({"_rlnImageName": ["a"]}) sf = StarFile(data=df) with pytest.raises(ValueError, match="not found"): sf.set_optics_values("_rlnFakeField", [1])
# ---------------------------------------------------------------------------# apix fallback (old RELION format)# ---------------------------------------------------------------------------
def test_apix_old_format(): """Test pixel size from _rlnDetectorPixelSize and _rlnMagnification.""" df = pd.DataFrame( { "_rlnImageName": ["a", "b"], "_rlnDetectorPixelSize": ["14.0", "14.0"], "_rlnMagnification": ["100000", "100000"], } ) sf = StarFile(data=df) apix = sf.apix assert apix is not None # 14.0 um * 1e4 / 100000 = 1.4 Å/pixel np.testing.assert_allclose(apix, 1.4, rtol=1e-5)
def test_apix_none_when_no_fields(): df = pd.DataFrame({"_rlnImageName": ["a"]}) sf = StarFile(data=df) assert sf.apix is None
def test_resolution_none_when_no_fields(): df = pd.DataFrame({"_rlnDefocusU": ["10000"]}) sf = StarFile(data=df) assert sf.resolution is None
# ---------------------------------------------------------------------------# flatten_to_relion30 passthrough# ---------------------------------------------------------------------------
def test_flatten_to_relion30_noop_on_relion30(): df = pd.DataFrame({"_rlnImageName": ["a", "b"]}) sf = StarFile(data=df) flat = sf.flatten_to_relion30() pd.testing.assert_frame_equal(flat, sf.df)
def test_to_relion30_alias(): data = pd.DataFrame({"_rlnImageName": ["a"], "_rlnOpticsGroup": ["1"]}) optics = pd.DataFrame({"_rlnOpticsGroup": ["1"], "_rlnVoltage": ["300"]}) sf = StarFile(data=data, data_optics=optics) pd.testing.assert_frame_equal(sf.flatten_to_relion30(), sf.to_relion30())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import numpy as npimport pytest
pytest.importorskip("jax")
from recovar.simulation import synthetic_dataset
pytestmark = pytest.mark.unit
def _make_hvd(): volumes = np.array( [ [1.0, 2.0, 3.0, 4.0, 0.5, 0.2, 0.1, 0.0], [2.0, 1.0, 4.0, 3.0, 0.7, 0.3, 0.0, 0.1], ], dtype=np.float32, ) image_assignments = np.array([0, 1, 1, -1], dtype=np.int32) contrasts = np.array([1.0, 1.2, 0.8, 1.1], dtype=np.float32) return synthetic_dataset.HeterogeneousVolumeDistribution( volumes=volumes, image_assignments=image_assignments, contrasts=contrasts, valid_indices=np.ones(volumes.shape[-1], dtype=np.float32), vol_batch_size=1, )
def test_hvd_probabilities_mean_and_outlier_fraction(): hvd = _make_hvd() probs = hvd.get_probs_of_state() np.testing.assert_allclose(probs, np.array([1.0 / 3.0, 2.0 / 3.0], dtype=np.float32)) assert hvd.percent_outliers == pytest.approx(0.25)
expected_mean = hvd.volumes[0] * (1.0 / 3.0) + hvd.volumes[1] * (2.0 / 3.0) np.testing.assert_allclose(hvd.get_mean(), expected_mean, atol=1e-7, rtol=1e-7)
def test_hvd_covariance_square_root_and_columns(): hvd = _make_hvd() sqrt_cov = hvd.get_covariance_square_root(contrasted=False) assert sqrt_cov.shape[0] == hvd.volumes.shape[-1] assert sqrt_cov.shape[1] == hvd.volumes.shape[0]
picked = np.array([0, 3, 7], dtype=np.int32) cols = hvd.get_covariance_columns(picked, contrasted=False) manual = sqrt_cov @ np.conj(sqrt_cov[picked, :]).T np.testing.assert_allclose(cols, manual, atol=1e-7, rtol=1e-7)
def test_hvd_variance_helpers_match_when_idft_is_identity(monkeypatch): hvd = _make_hvd() monkeypatch.setattr( synthetic_dataset.linalg, "batch_idft3", lambda vols, volume_shape, vol_batch_size: vols, ) fourier_vars = hvd.get_fourier_variances(contrasted=False) spatial_vars = hvd.get_spatial_variances(contrasted=False) np.testing.assert_allclose(spatial_vars, fourier_vars, atol=1e-7, rtol=1e-7)
def test_load_heterogeneous_reconstruction_dict_path_with_scaling(monkeypatch): simulation_info = { "volumes_path_root": "/tmp/vol_", "grid_size": 2, "trailing_zero_format_in_vol_name": True, "image_assignment": np.array([0, 1, 0], dtype=np.int32), "per_image_contrast": np.array([1.0, 1.0, 1.0], dtype=np.float32), "scale_vol": 3.0, } monkeypatch.setattr( synthetic_dataset.simulator, "load_volumes_from_folder", lambda *args, **kwargs: np.ones((2, 8), dtype=np.float32) * 2.0, )
hvd = synthetic_dataset.load_heterogeneous_reconstruction(simulation_info, load_volumes=True) assert hvd.volumes.shape == (2, 8) # Constructor applies a default radial mask; only valid frequency entries remain non-zero. assert np.max(hvd.volumes) == pytest.approx(6.0) assert np.count_nonzero(hvd.volumes) > 0
def test_get_col_covariance_matches_manual_computation(): xs = np.array( [ [1 + 1j, 2 + 0j, 3 + 0j], [2 + 0j, 1 + 1j, 4 + 0j], ], dtype=np.complex64, ) probs = np.array([0.25, 0.75], dtype=np.float32) mean = np.sum(xs * probs[:, None], axis=0) vec_indices = np.array([0, 2], dtype=np.int32)
out = synthetic_dataset.get_col_covariance(xs, mean, vec_indices, probs) expected = np.zeros((3, 2), dtype=np.complex64) for j, v in enumerate(vec_indices): expected[:, j] = np.sum( probs[:, None] * (xs - mean) * np.conj(xs[:, v : v + 1] - mean[v]), axis=0, ) np.testing.assert_allclose(np.asarray(out), expected, atol=1e-6, rtol=1e-6)1234567891011121314151617181920212223242526272829303132333435363738394041424344import numpy as npimport pytest
pytest.importorskip("jax")
import recovar.output.metrics as metricsfrom helpers.tiny_synthetic import make_tiny_hvd_from_simulation, make_tiny_simulation
pytestmark = pytest.mark.unit
def test_simulator_to_synthetic_dataset_to_metrics_tiny(): grid_size = 4 n_images = 8 volume_size = int(grid_size**3) main_image_stack, ctf_params, rots, trans, _, _, _ = make_tiny_simulation( grid_size=grid_size, n_images=n_images, seed=0 )
assert main_image_stack.shape == (n_images, grid_size, grid_size) assert ctf_params.shape[0] == n_images assert rots.shape == (n_images, 3, 3) assert trans.shape == (n_images, 2)
hvd, _, _ = make_tiny_hvd_from_simulation(grid_size=grid_size, n_images=n_images, seed=0)
mean = hvd.get_mean() assert mean.shape == (volume_size,) assert np.all(np.isfinite(mean))
picked = np.array([0, 1, 2], dtype=np.int32) cov_cols = hvd.get_covariance_columns(picked, contrasted=False) assert cov_cols.shape == (volume_size, picked.size)
u, s, _ = hvd.get_vol_svd(contrasted=False, real_space=False, random_svd_pcs=None) assert u.shape[0] == volume_size assert s.ndim == 1 assert np.all(s >= 0)
_, rel_var, norm_var = metrics.get_all_variance_scores(u, u, s) assert rel_var[-1] == pytest.approx(1.0, rel=1e-5, abs=1e-5) assert np.all(norm_var <= 1.0 + 1e-6) angles = metrics.subspace_angles(u, u, max_rank=min(5, u.shape[1])) assert np.all(angles <= 1e-5)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328import jsonimport picklefrom pathlib import Path
import numpy as npimport pandas as pdimport pytest
from recovar.data_io import image_backends as cryo_dataset, cryoem_dataset as dataset, halfsets, starfilefrom recovar.data_io._index_utils import TiltSeriesOriginalIndexMap
pytestmark = pytest.mark.unit
def _write_mrcs(path: Path, data: np.ndarray) -> None: import mrcfile
with mrcfile.new(path, overwrite=True) as m: m.set_data(np.asarray(data, dtype=np.float32))
def _make_tilt_fixture(tmp_path: Path): # 8 images, 3 particles (groups), deliberately interleaved in STAR row order. rows = [ ("gB", 10.0, -2.0), ("gA", 1.0, -1.0), ("gC", 7.0, -3.0), ("gB", 30.0, -6.0), ("gA", 20.0, -4.0), ("gC", 5.0, -5.0), ("gB", 20.0, -7.0), ("gC", 40.0, -8.0), ] n = len(rows) D = 8 stack = np.arange(n * D * D, dtype=np.float32).reshape(n, D, D) mrcs_path = tmp_path / "tilt_stack.mrcs" _write_mrcs(mrcs_path, stack)
df = pd.DataFrame( { "_rlnImageName": [f"{i + 1}@{mrcs_path.name}" for i in range(n)], "_rlnGroupName": [r[0] for r in rows], "_rlnMicrographPreExposure": [r[1] for r in rows], "_rlnCtfScalefactor": np.ones(n, dtype=np.float32), "_rlnCtfBfactor": np.array([r[2] for r in rows], dtype=np.float32), } ) star_path = tmp_path / "tilt_particles.star" starfile.write_star(str(star_path), data=df) return star_path
def _load_golden(): golden_path = Path(__file__).resolve().parents[1] / "baselines" / "tilt_index_consistency" / "v1.json" with open(golden_path, "r", encoding="utf-8") as f: return json.load(f)
def test_particle_tilt_mapping_matches_golden_reference(tmp_path): star_path = _make_tilt_fixture(tmp_path) golden = _load_golden()
particles_to_tilts, tilts_to_particles = cryo_dataset.TiltSeriesDataset.parse_particle_tilt(str(star_path)) particles_to_tilts = [arr.tolist() for arr in particles_to_tilts] tilts_to_particles = {str(k): int(v) for k, v in sorted(tilts_to_particles.items())}
assert sorted(starfile.StarFile.load(str(star_path)).df["_rlnGroupName"].unique()) == golden["canonical_groups"] assert particles_to_tilts == golden["particles_to_tilts"] assert tilts_to_particles == golden["tilts_to_particles"]
subset_particles = np.array(golden["subset_particles"], dtype=np.int32) subset_images = np.array([1, 2, 4, 7], dtype=np.int32) index_map = TiltSeriesOriginalIndexMap.from_particles_file(str(star_path)) mapped = index_map.image_indices_from_particles(subset_particles, allowed_images=subset_images) np.testing.assert_array_equal(mapped, np.array(golden["subset_image_intersection"], dtype=np.int32))
def test_tilt_series_subset_generator_preserves_subset_order_and_indices(tmp_path): star_path = _make_tilt_fixture(tmp_path) ds = cryo_dataset.TiltSeriesDataset( str(star_path), datadir=str(tmp_path), lazy=True, random_tilts=False, num_tilts=2, tilt_file_option="relion5", ) subset = np.array([2, 0], dtype=np.int32) gen = ds.get_dataset_subset_generator( batch_size=8, subset_indices=subset, mode="tilt_series", ) batches = list(gen) assert len(batches) == len(subset)
returned_particles = [] returned_tilts = [] for batch in batches: # Tilt-series iteration remains particle-at-a-time even with a large requested batch size. returned_particles.append(int(np.array(batch[1]).reshape(-1)[0])) returned_tilts.append(np.array(batch[2]).reshape(-1))
assert returned_particles == subset.tolist() for i, pidx in enumerate(subset): expected_tilts = np.array(ds[pidx][2]).reshape(-1) np.testing.assert_array_equal(returned_tilts[i], expected_tilts)
def test_image_subset_generator_returns_only_requested_tilt_indices(tmp_path): star_path = _make_tilt_fixture(tmp_path) ds = cryo_dataset.TiltSeriesDataset( str(star_path), datadir=str(tmp_path), lazy=True, random_tilts=False, tilt_file_option="relion5", ) subset_images = np.array([7, 1, 4], dtype=np.int32) gen = ds.get_image_subset_generator(batch_size=2, subset_indices=subset_images)
got = [] for batch in gen: got.extend(np.array(batch[2]).reshape(-1).tolist()) assert got == subset_images.tolist()
def test_get_split_tilt_indices_with_precomputed_particle_halfsets_is_stable(tmp_path): star_path = _make_tilt_fixture(tmp_path)
ind_file = tmp_path / "ind.pkl" tilt_ind_file = tmp_path / "tilt_ind.pkl" halfsets_file = tmp_path / "halfsets.pkl"
with open(ind_file, "wb") as f: # Keep only a strict subset of image indices. pickle.dump(np.array([1, 2, 7], dtype=np.int32), f) with open(tilt_ind_file, "wb") as f: # Keep only particles 0 and 2 in canonical order. pickle.dump(np.array([0, 2], dtype=np.int32), f) with open(halfsets_file, "wb") as f: # One half contains particle 0, other half contains particle 2. pickle.dump([np.array([0, 1], dtype=np.int32), np.array([2], dtype=np.int32)], f)
split = halfsets.get_split_tilt_indices( particles_file=str(star_path), ind_file=str(ind_file), tilt_ind_file=str(tilt_ind_file), datadir=str(tmp_path), particle_halfset_indices_file=str(halfsets_file), )
# particle 0 -> tilts [1, 4] intersect [1,2,7] => [1] # particle 2 -> tilts [2, 5, 7] intersect [1,2,7] => [2, 7] np.testing.assert_array_equal(split[0], np.array([1], dtype=np.int32)) np.testing.assert_array_equal(split[1], np.array([2, 7], dtype=np.int32))
# No overlap, complete coverage of allowed image subset. assert np.intersect1d(split[0], split[1]).size == 0 np.testing.assert_array_equal(np.sort(np.concatenate(split)), np.array([1, 2, 7], dtype=np.int32))
def test_get_split_tilt_indices_precomputed_halfsets_respected_with_image_filter(tmp_path): star_path = _make_tilt_fixture(tmp_path)
ind_file = tmp_path / "ind_subset.pkl" halfsets_file = tmp_path / "halfsets.pkl"
with open(ind_file, "wb") as f: # Keep only images from canonical particles 0 and 2. pickle.dump(np.array([1, 2, 4, 7], dtype=np.int32), f) with open(halfsets_file, "wb") as f: # Explicit split: half0 has particles 0 and 2, half1 has particle 1. pickle.dump([np.array([0, 2], dtype=np.int32), np.array([1], dtype=np.int32)], f)
split = halfsets.get_split_tilt_indices( particles_file=str(star_path), ind_file=str(ind_file), datadir=str(tmp_path), particle_halfset_indices_file=str(halfsets_file), )
# Preserve particle/tilt traversal order from halfset [0,2]: # particle 0 contributes [1,4], particle 2 contributes [2,7]. np.testing.assert_array_equal(split[0], np.array([1, 4, 2, 7], dtype=np.int32)) np.testing.assert_array_equal(split[1], np.array([], dtype=np.int32)) assert np.intersect1d(split[0], split[1]).size == 0 np.testing.assert_array_equal(np.sort(np.concatenate(split)), np.array([1, 2, 4, 7], dtype=np.int32))
@pytest.mark.parametrize( "tilt_file_option", ["relion5", "warp"],)def test_tilt_dataset_subset_images_mode_only_emits_subset_particles(tmp_path, tilt_file_option): star_path = _make_tilt_fixture(tmp_path) ds = cryo_dataset.TiltSeriesDataset( str(star_path), datadir=str(tmp_path), lazy=True, random_tilts=False, num_tilts=2, tilt_file_option=tilt_file_option, ) subset_particles = np.array([2, 0], dtype=np.int32) gen = ds.get_dataset_subset_generator( batch_size=4, subset_indices=subset_particles, mode="images", ) seen_particles = [] seen_tilts = [] for batch in gen: seen_particles.extend(np.array(batch[1]).reshape(-1).tolist()) seen_tilts.extend(np.array(batch[2]).reshape(-1).tolist())
assert set(seen_particles).issubset(set(subset_particles.tolist())) expected_tilts = np.concatenate([ds[pidx][2] for pidx in subset_particles]).astype(int) np.testing.assert_array_equal(np.sort(np.asarray(seen_tilts, dtype=int)), np.sort(expected_tilts))
def test_tilt_dataset_subset_none_matches_full_sequence(tmp_path): star_path = _make_tilt_fixture(tmp_path) ds = cryo_dataset.TiltSeriesDataset( str(star_path), datadir=str(tmp_path), lazy=True, random_tilts=False, num_tilts=2, tilt_file_option="relion5", )
full_batches = list(ds.get_dataset_generator(batch_size=16, mode="tilt_series")) subset_none_batches = list(ds.get_dataset_subset_generator(batch_size=16, subset_indices=None, mode="tilt_series"))
assert len(full_batches) == len(subset_none_batches) == len(ds) for b_full, b_subset in zip(full_batches, subset_none_batches): np.testing.assert_array_equal(np.array(b_full[1]), np.array(b_subset[1])) np.testing.assert_array_equal(np.array(b_full[2]), np.array(b_subset[2]))
def test_tilt_series_ind_filtering_preserves_original_indices(tmp_path): star_path = _make_tilt_fixture(tmp_path) # Keep rows from all groups but sparse and unordered. ind = np.array([7, 1, 3, 4], dtype=np.int32) ds = cryo_dataset.TiltSeriesDataset( str(star_path), datadir=str(tmp_path), ind=ind, lazy=True, random_tilts=False, tilt_file_option="relion5", ) # Remaining groups should be gA:[1,4], gB:[3], gC:[7] p2t, t2p = cryo_dataset.TiltSeriesDataset.parse_particle_tilt(str(star_path), indices=ind) expected = [np.array([1, 4], dtype=int), np.array([3], dtype=int), np.array([7], dtype=int)] for got, exp in zip(p2t, expected): np.testing.assert_array_equal(got, exp) assert t2p[1] == 0 and t2p[4] == 0 and t2p[3] == 1 and t2p[7] == 2 assert ds.num_particles == 3
def test_random_tilt_selection_respects_num_tilts_and_membership(tmp_path): star_path = _make_tilt_fixture(tmp_path) np.random.seed(0) ds = cryo_dataset.TiltSeriesDataset( str(star_path), datadir=str(tmp_path), lazy=True, random_tilts=True, num_tilts=1, tilt_file_option="relion5", ) for pidx in range(len(ds)): _, _, selected = ds[pidx] assert selected.size == 1 all_group_tilts = list(ds.particle_groups.values())[pidx] assert int(selected[0]) in set(all_group_tilts.tolist())
def test_get_split_tilt_indices_random_split_has_disjoint_complete_coverage(tmp_path): star_path = _make_tilt_fixture(tmp_path) ind_file = tmp_path / "ind_all.pkl" with open(ind_file, "wb") as f: pickle.dump(np.arange(8, dtype=np.int32), f)
split = halfsets.get_split_tilt_indices( particles_file=str(star_path), ind_file=str(ind_file), datadir=str(tmp_path), ) assert len(split) == 2 assert np.intersect1d(split[0], split[1]).size == 0 np.testing.assert_array_equal(np.sort(np.concatenate(split)), np.arange(8, dtype=np.int32))
def test_get_split_tilt_indices_with_ntilts_filters_per_particle(tmp_path): star_path = _make_tilt_fixture(tmp_path) # Canonical particles: # gA -> [1,4], gB -> [0,3,6], gC -> [2,5,7] # RELION5 ordering in fixture (higher dose first): # gA keeps tilt-order ranks [4,1] => with ntilts=1 keep one per particle in get_split_tilt_indices by tilt_numbers < 1. split = halfsets.get_split_tilt_indices( particles_file=str(star_path), ntilts=1, datadir=str(tmp_path), ) # exactly one tilt per particle in whichever halfset each particle is assigned. kept = np.sort(np.concatenate(split)) assert kept.size == 3 p2t, _ = cryo_dataset.TiltSeriesDataset.parse_particle_tilt(str(star_path)) for particle_tilts in p2t: assert np.intersect1d(kept, particle_tilts).size == 1
def test_particle_subset_max_tilts_matches_parent_counts(tmp_path): star_path = _make_tilt_fixture(tmp_path) ds = cryo_dataset.TiltSeriesDataset( str(star_path), datadir=str(tmp_path), num_tilts=2, random_tilts=False, tilt_file_option="relion5", ) subset = cryo_dataset._SimpleSubset(ds, np.array([1, 2], dtype=np.int32)) # both chosen particles have >=2 tilts; max should be 2 due to num_tilts cap. assert cryo_dataset._max_tilts_per_dataset_view(subset) == 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import numpy as npimport pytestfrom pathlib import Path
pytest.importorskip("jax")
from helpers import tiny_synthetic
pytestmark = pytest.mark.unit
def test_make_tiny_fourier_volumes_shape_and_dtype(): vols = tiny_synthetic.make_tiny_fourier_volumes(grid_size=4) assert vols.shape == (2, 64) assert vols.dtype == np.complex64 assert np.all(np.isfinite(vols))
def test_tiny_ctf_pose_generator_shapes(): ctf, rots, trans = tiny_synthetic.tiny_ctf_pose_generator(n_images=5, grid_size=4) assert ctf.shape == (5, 9) assert rots.shape == (5, 3, 3) assert trans.shape == (5, 2)
def test_make_tiny_simulation_and_hvd_end_to_end(): stack, ctf_params, rots, trans, sim_info, _, _ = tiny_synthetic.make_tiny_simulation( grid_size=4, n_images=6, seed=0 ) assert stack.shape == (6, 4, 4) assert ctf_params.shape[0] == 6 assert rots.shape == (6, 3, 3) assert trans.shape == (6, 2) assert "image_assignment" in sim_info assert "per_image_contrast" in sim_info
hvd, sim_info2, vols = tiny_synthetic.make_tiny_hvd_from_simulation(grid_size=4, n_images=6, seed=0) assert hvd.volumes.shape == vols.shape assert sim_info2["image_assignment"].shape[0] == 6 assert np.isfinite(hvd.get_mean()).all()
def test_make_tiny_loader_files(tmp_path): files = tiny_synthetic.make_tiny_loader_files(tmp_path, grid_size=8, n_images=6, n_particles=3) assert set(["particles_mrcs", "particles_star", "poses_pkl", "ctf_pkl"]).issubset(files.keys()) for key in ["particles_mrcs", "particles_star", "poses_pkl", "ctf_pkl"]: assert (tmp_path / Path(files[key]).name).exists()
def test_make_tiny_tilt_loader_files_from_simulator(tmp_path): files = tiny_synthetic.make_tiny_tilt_loader_files_from_simulator( tmp_path, grid_size=8, n_images=24, n_tilts=3, n_volumes=4, ) expected = [ "particles_star", "particles_mrcs", "poses_pkl", "ctf_pkl", "simulation_info_pkl", "n_images", "grid_size", "n_tilts", "sim_info", ] assert set(expected).issubset(files.keys()) for key in ["particles_star", "particles_mrcs", "poses_pkl", "ctf_pkl", "simulation_info_pkl"]: assert Path(files[key]).exists() assert files["n_images"] == 24 assert files["grid_size"] == 8 assert files["n_tilts"] == 3 assert "dose_indices" in files["sim_info"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203import numpy as npimport pytest
from recovar.heterogeneity import trajectory
pytestmark = pytest.mark.unit
def test_get_cum_curvelength_monotonic(): pts = np.array( [ [0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [2.0, 1.0], ], dtype=np.float32, ) d = trajectory.get_cum_curvelength(pts) assert np.all(d[1:] >= d[:-1]) assert np.isclose(d[0], 0.0) assert np.isclose(d[-1], 3.0)
def test_resample_at_uniform_pts_shapes(): pts = np.stack([np.linspace(0, 3, 6), np.zeros(6)], axis=1).astype(np.float32) out = trajectory.resample_at_uniform_pts(pts, n_vols_along_path=4) assert out.shape == (4, 2) assert np.isclose(out[0, 0], 0.0) assert np.isclose(out[-1, 0], 3.0)
def test_get_grid_spacing(): bounds = [(-2.0, 2.0), (0.0, 1.0), (4.0, 8.0)] density = np.zeros((8, 4, 2), dtype=np.float32) dx = trajectory.get_grid_spacing(bounds, density) assert np.allclose(dx, [0.5, 0.25, 2.0])
def test_gradient_descent_nd_stays_finite_and_moves_toward_start(monkeypatch): x_st = np.array([0.0, 0.0], dtype=np.float32) x_end = np.array([3.0, 3.0], dtype=np.float32) travel_time = np.zeros((8, 8), dtype=np.float32)
# Use a convex surrogate objective over candidate points. monkeypatch.setattr( trajectory, "evaluate_function_off_grid", lambda _tt, pts: np.sum((pts - x_st[None, :]) ** 2, axis=1), )
path = trajectory.gradient_descent_nd( travel_time=travel_time, x_st=x_st, x_end=x_end, dx=[1.0, 1.0], step_size=0.5, n_theta=5, max_steps=100, )
assert path is not None assert path.ndim == 2 and path.shape[1] == 2 assert np.all(np.isfinite(path)) # Returned path is [start ... end] by construction. assert np.linalg.norm(path[0] - x_st) < 1e-6 assert np.linalg.norm(path[-1] - x_end) < 1e-6
def test_compute_fixed_dimensional_path_runs_on_smooth_density(): n = 32 axis = np.linspace(-2.0, 2.0, n, dtype=np.float32) xx, yy = np.meshgrid(axis, axis, indexing="ij") density = np.exp(-(xx**2 + yy**2)) bounds = np.array([[-2.0, 2.0], [-2.0, 2.0]], dtype=np.float32)
z_st = np.array([-1.5, -1.0], dtype=np.float32) z_end = np.array([1.5, 1.0], dtype=np.float32) path = trajectory.compute_fixed_dimensional_path( z_st=z_st, z_end=z_end, density_low_dim=density, latent_space_bounds=bounds, density_eps=1e-4, use_log_density=False, )
assert path.ndim == 2 and path.shape[1] == 2 assert path.shape[0] > 10 assert np.all(np.isfinite(path)) # Endpoint coordinates are quantized to grid; check they land near the requested endpoints. assert np.linalg.norm(path[0] - z_st) < 0.2 assert np.linalg.norm(path[-1] - z_end) < 0.2
def test_subsample_path_returns_correct_count(): path = np.linspace(0, 10, 50).reshape(-1, 1).astype(np.float32) sub = trajectory.subsample_path(path, 5) assert sub.shape == (5, 1) # Endpoints preserved assert np.isclose(sub[0, 0], path[0, 0]) assert np.isclose(sub[-1, 0], path[-1, 0])
def test_subsample_path_preserves_multidimensional(): rng = np.random.default_rng(42) path = rng.normal(size=(20, 3)).astype(np.float32) sub = trajectory.subsample_path(path, 10) assert sub.shape == (10, 3)
def test_compute_travel_time_finite_and_zero_at_start(): n = 16 density = np.ones((n, n), dtype=np.float64) g_st = np.array([8, 8]) bounds = [(-1.0, 1.0), (-1.0, 1.0)] tt = trajectory.compute_travel_time(density, g_st, bounds) assert tt.shape == (n, n) assert np.isfinite(tt).all() assert tt[8, 8] == 0.0 # Travel time should increase with distance from start assert tt[0, 0] > tt[7, 7]
def test_find_trajectory_in_grid_finds_path(): n = 32 ax = np.linspace(-2.0, 2.0, n, dtype=np.float64) xx, yy = np.meshgrid(ax, ax, indexing="ij") density = np.exp(-(xx**2 + yy**2)) g_st = np.array([8, 8]) g_end = np.array([24.0, 24.0]) bounds = [(-2.0, 2.0), (-2.0, 2.0)] path = trajectory.find_trajectory_in_grid(density, g_st, g_end, bounds, eps=1e-4) assert path is not None assert path.ndim == 2 and path.shape[1] == 2 assert np.all(np.isfinite(path)) # Path should start near g_st and end near g_end assert np.linalg.norm(path[0] - g_st) < 2.0 assert np.linalg.norm(path[-1] - g_end) < 2.0
def test_find_trajectory_in_grid_with_log_density(): n = 32 ax = np.linspace(-2.0, 2.0, n, dtype=np.float64) xx, yy = np.meshgrid(ax, ax, indexing="ij") density = np.exp(-(xx**2 + yy**2)) g_st = np.array([10, 10]) g_end = np.array([22.0, 22.0]) bounds = [(-2.0, 2.0), (-2.0, 2.0)] path = trajectory.find_trajectory_in_grid(density, g_st, g_end, bounds, eps=1e-4, use_log_density=True) assert path is not None assert path.ndim == 2 and path.shape[1] == 2 assert np.all(np.isfinite(path))
def test_find_trajectory_in_grid_raises_on_failure(monkeypatch): """find_trajectory_in_grid should raise RuntimeError (not return None) when gradient descent fails to converge.""" density = np.ones((8, 8), dtype=np.float32) g_st = np.array([0, 0]) g_end = np.array([7, 7], dtype=np.float32) bounds = [(-1.0, 1.0), (-1.0, 1.0)]
# Force gradient_descent_nd to always return None (simulates convergence failure) monkeypatch.setattr(trajectory, "gradient_descent_nd", lambda *a, **kw: None)
with pytest.raises(RuntimeError, match="Trajectory computation failed"): trajectory.find_trajectory_in_grid(density, g_st, g_end, bounds)
def test_evaluate_function_off_grid_interpolates(): density = np.array([[0.0, 1.0], [2.0, 3.0]], dtype=np.float64) # Center of 2x2 grid should be average of all 4 corners pts = np.array([[0.5, 0.5]]) val = trajectory.evaluate_function_off_grid(density, pts) assert np.isclose(val[0], 1.5, atol=0.1)
def test_compute_high_dimensional_path_base_case_low_dim_only(): n = 32 axis = np.linspace(-2.0, 2.0, n, dtype=np.float32) xx, yy = np.meshgrid(axis, axis, indexing="ij") density_2d = np.exp(-(xx**2 + yy**2))
rng = np.random.default_rng(0) zs = rng.normal(size=(120, 3)).astype(np.float32) cov_zs = np.tile(np.eye(3, dtype=np.float32)[None], (120, 1, 1)) * 0.1
path = trajectory.compute_high_dimensional_path( zs=zs, cov_zs=cov_zs, z_st=np.array([-1.0, -1.0, 0.0], dtype=np.float32), z_end=np.array([1.0, 1.0, 0.5], dtype=np.float32), density_low_dim=density_2d, density_eps=1e-4, max_dim=2, percentile_bound=5, use_log_density=False, )
assert path.ndim == 2 and path.shape[1] == 2 assert path.shape[0] > 10 assert np.all(np.isfinite(path))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248"""Unit tests for recovar.simulation.trajectory_generation."""
import osimport tempfile
import numpy as npimport pytest
from recovar.simulation.trajectory_generation import ( CHAIN_GROUPS_5NRL, HINGE_INDEX_5NRL, compute_bfactor_scaling, generate_conformation_2D, generate_trajectory_volumes, path_asymmetric, path_symmetric, prepare_5nrl_subcomplexes, rigid_motion, split_atom_group_by_chains, stitched_path,)from recovar.simulation.pdb_utils import AtomGroup
pytestmark = pytest.mark.unit
# ---------------------------------------------------------------------------# split_atom_group_by_chains# ---------------------------------------------------------------------------
class TestSplitAtomGroupByChains: def test_basic_split(self): atoms = AtomGroup() atoms.setCoords(np.array([[1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0]], dtype=np.float64)) atoms.setElements(np.array(["C", "N", "O", "C"])) atoms.setChids(np.array(["A", "A", "B", "C"]))
groups = split_atom_group_by_chains(atoms, [["A"], ["B", "C"]]) assert len(groups) == 2 assert groups[0][0].shape == (2, 3) assert groups[1][0].shape == (2, 3) np.testing.assert_array_equal(groups[0][1], ["C", "N"]) np.testing.assert_array_equal(groups[1][1], ["O", "C"])
def test_empty_chain_group(self): atoms = AtomGroup() atoms.setCoords(np.array([[1, 0, 0]], dtype=np.float64)) atoms.setElements(np.array(["C"])) atoms.setChids(np.array(["A"]))
groups = split_atom_group_by_chains(atoms, [["A"], ["X"]]) assert groups[0][0].shape == (1, 3) assert groups[1][0].shape == (0, 3)
# ---------------------------------------------------------------------------# rigid_motion# ---------------------------------------------------------------------------
class TestRigidMotion: def test_identity_rotation(self): from scipy.spatial.transform import Rotation
coords = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float64) pivot = np.array([0, 0, 0], dtype=np.float64) result = rigid_motion(coords, pivot, Rotation.identity()) np.testing.assert_allclose(result, coords, atol=1e-14)
def test_rotation_around_pivot(self): from scipy.spatial.transform import Rotation
# 180-degree rotation around z-axis: (1,0,0) -> (-1,0,0) coords = np.array([[2, 0, 0]], dtype=np.float64) pivot = np.array([1, 0, 0], dtype=np.float64) rot = Rotation.from_euler("z", 180, degrees=True) result = rigid_motion(coords, pivot, rot) np.testing.assert_allclose(result, [[0, 0, 0]], atol=1e-14)
def test_preserves_distances(self): from scipy.spatial.transform import Rotation
rng = np.random.default_rng(42) coords = rng.standard_normal((50, 3)) pivot = rng.standard_normal(3) rot = Rotation.random(random_state=42) result = rigid_motion(coords, pivot, rot)
# Pairwise distances should be preserved from scipy.spatial.distance import pdist
np.testing.assert_allclose(pdist(result), pdist(coords), atol=1e-12)
# ---------------------------------------------------------------------------# generate_conformation_2D and path functions# ---------------------------------------------------------------------------
class TestPathFunctions: @pytest.fixture def simple_groups(self): """3 groups of 10 atoms each, plus a pivot.""" rng = np.random.default_rng(123) groups = [rng.standard_normal((10, 3)) for _ in range(3)] pivot = np.zeros(3) return groups, pivot
def test_path_symmetric_at_zero(self, simple_groups): groups, pivot = simple_groups result = path_symmetric(0, groups, pivot) # At t=0, rot_around_x gives -10 degrees, so groups[0] unchanged np.testing.assert_allclose(result[0], groups[0], atol=1e-14)
def test_path_symmetric_modifies_arms(self, simple_groups): groups, pivot = simple_groups result = path_symmetric(15, groups, pivot) # B and Db should be rotated assert not np.allclose(result[1], groups[1]) assert not np.allclose(result[2], groups[2])
def test_path_asymmetric_fixes_B(self, simple_groups): groups, pivot = simple_groups result1 = path_asymmetric(0, groups, pivot) result2 = path_asymmetric(10, groups, pivot) # B should be the same (both at t_right_fixed=40) np.testing.assert_allclose(result1[1], result2[1], atol=1e-14) # Db should differ assert not np.allclose(result1[2], result2[2])
def test_stitched_path_continuity(self, simple_groups): groups, pivot = simple_groups # At t=35, stitched should equal path_symmetric(35) result_stitch = stitched_path(35, groups, pivot) result_sym = path_symmetric(35, groups, pivot) for r1, r2 in zip(result_stitch, result_sym): np.testing.assert_allclose(r1, r2, atol=1e-14)
def test_conformation_2D_ab_unchanged(self, simple_groups): groups, pivot = simple_groups result = generate_conformation_2D(groups, 5, 10, pivot) # Ab (index 0) should not be rotated np.testing.assert_allclose(result[0], groups[0], atol=1e-14)
# ---------------------------------------------------------------------------# compute_bfactor_scaling# ---------------------------------------------------------------------------
class TestBfactorScaling: def test_shape(self): shape = (16, 16, 16) result = compute_bfactor_scaling(shape, voxel_size=4.25, Bfactor=80) assert result.shape == shape
def test_max_is_one(self): shape = (16, 16, 16) result = compute_bfactor_scaling(shape, voxel_size=4.25, Bfactor=80) # The DC component (zero frequency) should give exp(0) = 1, # which is the maximum value in the array. assert abs(np.max(result) - 1.0) < 1e-10
def test_bfactor_zero_is_all_ones(self): shape = (16, 16, 16) result = compute_bfactor_scaling(shape, voxel_size=4.25, Bfactor=0) np.testing.assert_allclose(result, 1.0, atol=1e-14)
def test_higher_bfactor_more_dampening(self): shape = (16, 16, 16) low_b = compute_bfactor_scaling(shape, voxel_size=4.25, Bfactor=20) high_b = compute_bfactor_scaling(shape, voxel_size=4.25, Bfactor=200) # Higher B should dampen more (smaller values at high freq) assert np.sum(high_b) < np.sum(low_b)
# ---------------------------------------------------------------------------# prepare_5nrl_subcomplexes (loading the shipped .npz asset)# ---------------------------------------------------------------------------
class TestPrepare5nrl: def test_loads_and_returns_correct_structure(self): group_coords, group_elements, fixed_pt = prepare_5nrl_subcomplexes() assert len(group_coords) == 3 assert len(group_elements) == 3 assert fixed_pt.shape == (3,)
# Total atoms should match 5nrl total = sum(c.shape[0] for c in group_coords) assert total > 90000 # 5nrl has ~100k atoms
# Elements should be valid all_elems = set(np.concatenate(group_elements).tolist()) assert "C" in all_elems assert "N" in all_elems
def test_centered_bounding_box(self): group_coords, _, _ = prepare_5nrl_subcomplexes() all_coords = np.concatenate(group_coords) # Centering uses bounding-box midpoint, not mean bbox_center = (all_coords.max(axis=0) + all_coords.min(axis=0)) / 2 np.testing.assert_allclose(bbox_center, 0, atol=1.0)
def test_missing_file_raises(self): with pytest.raises(FileNotFoundError): prepare_5nrl_subcomplexes("/nonexistent/path.npz")
# ---------------------------------------------------------------------------# generate_trajectory_volumes (tiny grid, fast)# ---------------------------------------------------------------------------
class TestGenerateTrajectoryVolumes: def test_generates_mrc_files(self): with tempfile.TemporaryDirectory() as tmpdir: n_vols = 3 grid_size = 16 prefix = generate_trajectory_volumes( output_dir=tmpdir, grid_size=grid_size, n_volumes=n_vols, Bfactor=80, max_rotation_degrees=5.0, ) for i in range(n_vols): path = f"{prefix}{i:04d}.mrc" assert os.path.isfile(path), f"Missing volume: {path}"
def test_volumes_differ_along_trajectory(self): with tempfile.TemporaryDirectory() as tmpdir: n_vols = 5 grid_size = 16 prefix = generate_trajectory_volumes( output_dir=tmpdir, grid_size=grid_size, n_volumes=n_vols, Bfactor=80, max_rotation_degrees=10.0, ) from recovar import utils
vol_first = utils.load_mrc(f"{prefix}0000.mrc") vol_last = utils.load_mrc(f"{prefix}{n_vols - 1:04d}.mrc") # Volumes at different trajectory points should differ assert not np.allclose(vol_first, vol_last, atol=1e-6)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388import loggingfrom types import SimpleNamespace
import numpy as npimport pytest
jax = pytest.importorskip("jax")jnp = pytest.importorskip("jax.numpy")pytest.importorskip("mrcfile")pytest.importorskip("starfile")
import recovar.core.fourier_transform_utils as fourier_transform_utilsfrom recovar import utilsfrom recovar.utils import helpers as _utils_helpers
pytestmark = pytest.mark.unit
def test_make_radial_image_matches_manual_indexing(): average = jnp.array([10.0, 20.0], dtype=jnp.float32) radial_distances = ( fourier_transform_utils.get_grid_of_radial_distances((3, 3), scaled=False).astype(int).reshape(-1) ) expected = np.asarray(average)[np.asarray(radial_distances)]
out = utils.make_radial_image(average, (3, 3), extend_last_frequency=False) np.testing.assert_allclose(np.asarray(out), expected)
def test_make_radial_image_extend_last_frequency_true(): average = jnp.array([10.0, 20.0], dtype=jnp.float32) out = utils.make_radial_image(average, (5, 5), extend_last_frequency=True) assert out.shape == (25,) # Outer ring indices should map to appended last value. assert np.max(np.asarray(out)) == pytest.approx(20.0)
def test_batch_iter_helpers(): assert [list(x) for x in utils.index_batch_iter(10, 4)] == [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]] assert [list(x) for x in utils.subset_batch_iter([5, 1, 9, 2], 2)] == [[5, 1], [9, 2]] paired = list(utils.subset_and_indices_batch_iter([5, 1, 9, 2], 2)) assert [list(x) for x, _ in paired] == [[0, 1], [2, 3]] assert [list(y) for _, y in paired] == [[5, 1], [9, 2]]
def test_batch_iter_helpers_validate_batch_size_and_counts(): with pytest.raises(ValueError, match="batch_size must be >= 1"): list(utils.index_batch_iter(10, 0)) with pytest.raises(ValueError, match="n_units must be >= 0"): list(utils.index_batch_iter(-1, 2)) with pytest.raises(ValueError, match="batch_size must be >= 1"): list(utils.subset_batch_iter([1, 2, 3], 0)) with pytest.raises(ValueError, match="batch_size must be >= 1"): list(utils.subset_and_indices_batch_iter([1, 2, 3], 0))
def test_estimate_variance(): u = np.array([[1 + 1j, 2], [3, 4 - 1j]], dtype=np.complex64) s = np.array([2.0, 3.0], dtype=np.float32) out = utils.estimate_variance(u, s) expected = np.sum(np.abs(u) ** 2 * s[..., None], axis=0) np.testing.assert_allclose(out, expected)
def test_get_gpu_memory_helpers_without_gpu(monkeypatch): monkeypatch.setattr(_utils_helpers, "GPU_MEMORY_LIMIT", None) monkeypatch.setattr(_utils_helpers, "jax_has_gpu", lambda: False) # Without GPU, returns half of available system RAM (capped at >= 1) result = utils.get_gpu_memory_total() assert result >= 1 assert utils.get_gpu_memory_used() == 0 assert utils.get_peak_gpu_memory_used() == 0
def test_get_gpu_memory_total_limit_override(monkeypatch): monkeypatch.setattr(_utils_helpers, "GPU_MEMORY_LIMIT", 12) assert utils.get_gpu_memory_total() == 12
def test_get_gpu_memory_helpers_with_mocked_stats(monkeypatch): class FakeDevice: @staticmethod def memory_stats(): return { "bytes_limit": 42 * 10**9, "bytes_in_use": 7 * 10**9, "peak_bytes_in_use": 9 * 10**9, }
monkeypatch.setattr(_utils_helpers, "GPU_MEMORY_LIMIT", None) monkeypatch.setattr(_utils_helpers, "jax_has_gpu", lambda: True) monkeypatch.setattr(_utils_helpers.jax, "local_devices", lambda: [FakeDevice()]) assert utils.get_gpu_memory_total() == 42 assert utils.get_gpu_memory_used() == 7 assert utils.get_peak_gpu_memory_used() == 9
def test_report_memory_device_with_logger(monkeypatch): captured = {"msg": None} logger = SimpleNamespace(info=lambda msg: captured.__setitem__("msg", msg)) monkeypatch.setattr(_utils_helpers, "get_gpu_memory_used", lambda device=0: 1) monkeypatch.setattr(_utils_helpers, "get_peak_gpu_memory_used", lambda device=0: 2) monkeypatch.setattr(_utils_helpers, "get_gpu_memory_total", lambda device=0: 3) monkeypatch.setattr(_utils_helpers, "get_process_memory_used", lambda: 4) _utils_helpers.report_memory_device(logger=logger) assert "GPU mem in use:1; peak:2; total available:3, process mem in use:4" == captured["msg"]
def test_report_memory_device_without_logger(monkeypatch): """When logger=None, report_memory_device falls back to the module logger.""" captured = {"msg": None} fake_logger = SimpleNamespace(info=lambda msg: captured.__setitem__("msg", msg)) monkeypatch.setattr(_utils_helpers, "_module_logger", fake_logger) monkeypatch.setattr(_utils_helpers, "get_gpu_memory_used", lambda device=0: 1) monkeypatch.setattr(_utils_helpers, "get_peak_gpu_memory_used", lambda device=0: 2) monkeypatch.setattr(_utils_helpers, "get_gpu_memory_total", lambda device=0: 3) monkeypatch.setattr(_utils_helpers, "get_process_memory_used", lambda: 4) _utils_helpers.report_memory_device(logger=None) assert "GPU mem in use:1; peak:2; total available:3, process mem in use:4" == captured["msg"]
def test_misc_size_and_shape_helpers(): arr = np.zeros((10,), dtype=np.float64) assert utils.get_size_in_gb(arr) == arr.size * arr.itemsize / 1e9 assert utils.guess_grid_size_from_vol_size(27) == 3 assert utils.guess_vol_shape_from_vol_size(27) == (3, 3, 3)
def test_write_and_load_mrc_roundtrip(tmp_path): vol = np.arange(27, dtype=np.float32).reshape(3, 3, 3) out = tmp_path / "vol.mrc" utils.write_mrc(str(out), vol, voxel_size=2.5) loaded, voxel = utils.load_mrc(str(out), return_voxel_size=True) np.testing.assert_allclose(loaded, vol) assert float(voxel.x) == pytest.approx(2.5)
def test_symmetrize_ft_volume_shape_and_dtype(): vol = jnp.ones((8,), dtype=jnp.complex64) out = utils.symmetrize_ft_volume(vol, (2, 2, 2)) assert out.shape == (8,) assert jnp.iscomplexobj(out)
def test_dataset_index_helpers(): cryos = [SimpleNamespace(dataset_indices=np.array([2, 5])), SimpleNamespace(dataset_indices=np.array([1, 3]))] all_idx = utils.get_all_dataset_indices(cryos) inv_idx = utils.get_inverse_dataset_indices(cryos) np.testing.assert_array_equal(all_idx, np.array([2, 5, 1, 3])) np.testing.assert_array_equal(all_idx[inv_idx], np.sort(all_idx))
def test_batch_size_helpers_and_validation(): assert utils.get_image_batch_size(256, 10) > 0 assert utils.get_vol_batch_size(128, 10) > 0 assert utils.get_column_batch_size(128, 10) > 0 with pytest.raises(ValueError): utils.get_image_batch_size(0, 10) with pytest.raises(ValueError): utils.get_vol_batch_size(8, 0) with pytest.raises(ValueError): utils.get_column_batch_size(-1, 10)
def test_latent_and_embedding_batch_size(caplog): test_pts = np.zeros((100, 3), dtype=np.float32) assert utils.get_latent_density_batch_size(test_pts, zdim=2, gpu_memory=4) >= 1
basis = np.zeros((2000, 2000), dtype=np.float64) image_size = 64 * 64 contrast_grid = np.zeros((16,), dtype=np.float64) with caplog.at_level("WARNING"): out = utils.get_embedding_batch_size(basis, image_size, contrast_grid, zdim=8, gpu_memory=0.001) assert out == 1 out2 = utils.get_embedding_batch_size( basis=np.zeros((10, 10), dtype=np.float64), image_size=image_size, contrast_grid=contrast_grid, zdim=2, gpu_memory=16, ) assert out2 >= 1
def test_options_and_pickle_helpers(tmp_path): args = SimpleNamespace( mask="none", zdim=8, correct_contrast=True, ignore_zero_frequency=False, keep_intermediate=True, ) opts = utils.make_algorithm_options(args) assert opts.contrast == "contrast_qr" assert opts.zs_dim_to_test == 8
path = tmp_path / "obj.pkl" obj = {"a": 1, "b": [1, 2]} utils.pickle_dump(obj, path) assert utils.pickle_load(path) == obj
def test_get_variances_and_batch_index_helpers(): cov = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) picked = np.array([2, 0, 1]) out = utils.get_variances(cov, picked_frequencies=picked) np.testing.assert_array_equal(out, np.array([31, 12, 23]))
assert utils.get_number_of_index_batch(10, 3) == 4 assert utils.get_number_of_index_batch(9, 3) == 3 assert utils.get_batch_of_indices(10, 3, 2) == (6, 9) np.testing.assert_array_equal(utils.get_batch_of_indices_arange(10, 3, 2), np.array([6, 7, 8])) assert utils.get_batch_of_indices(10, 3, 3) == (9, 10)
def test_get_number_of_index_batch_validates_inputs(): with pytest.raises(ValueError, match="batch_size must be >= 1"): utils.get_number_of_index_batch(10, 0) with pytest.raises(ValueError, match="n_images must be >= 0"): utils.get_number_of_index_batch(-1, 3)
def test_jax_has_gpu_returns_bool(): assert isinstance(utils.jax_has_gpu(), bool)
def test_dtype_to_real(): assert utils.dtype_to_real(np.dtype(np.complex64)) == np.dtype(np.float32) assert utils.dtype_to_real(np.dtype(np.complex128)) == np.dtype(np.float64)
def test_relion_rotation_roundtrip(): scipy_rot = pytest.importorskip("scipy.spatial.transform").Rotation mats = scipy_rot.random(5, random_state=0).as_matrix() euler = utils.R_to_relion(mats, degrees=True) back = utils.R_from_relion(euler, degrees=True) np.testing.assert_allclose(back, mats, atol=1e-6, rtol=1e-6)
def test_relion_rotation_input_shapes(): ident = np.eye(3) out = utils.R_to_relion(ident) assert out.shape == (1, 3) with pytest.raises(ValueError): utils.R_to_relion(np.ones((2, 2)))
def test_write_starfile_minimal(tmp_path): n = 3 ctf = np.zeros((n, 7), dtype=np.float32) ctf[:, 3] = 300.0 ctf[:, 4] = 2.7 ctf[:, 5] = 0.1 rots = np.tile(np.eye(3, dtype=np.float32), (n, 1, 1)) trans = np.zeros((n, 2), dtype=np.float32) out = tmp_path / "particles.star" utils.write_starfile( CTF_params=ctf, rotation_matrices=rots, translations=trans, voxel_size=1.5, grid_size=64, particles_file="particles.mrcs", output_filename=str(out), halfset_indices=np.array([1, 2, 1]), ) assert out.exists()
def test_downsample_vol_by_fourier_truncation(): vol = np.ones((8, 8, 8), dtype=np.float32) out = utils.downsample_vol_by_fourier_truncation(vol, target_grid_size=4) assert out.shape == (4, 4, 4) out_same = utils.downsample_vol_by_fourier_truncation(vol, target_grid_size=8) assert out_same.shape == (8, 8, 8) out_odd = utils.downsample_vol_by_fourier_truncation(vol, target_grid_size=5) assert out_odd.shape == (5, 5, 5)
def test_downsample_vol_by_fourier_truncation_validates_target(): vol = np.ones((8, 8, 8), dtype=np.float32) with pytest.raises(ValueError): utils.downsample_vol_by_fourier_truncation(vol, target_grid_size=0) with pytest.raises(ValueError): utils.downsample_vol_by_fourier_truncation(vol, target_grid_size=9)
def test_set_gpu_memory_limit(monkeypatch): monkeypatch.setattr(_utils_helpers, "GPU_MEMORY_LIMIT", None) assert _utils_helpers.GPU_MEMORY_LIMIT is None utils.set_gpu_memory_limit(24) assert _utils_helpers.GPU_MEMORY_LIMIT == 24 assert utils.get_gpu_memory_total() == 24 # Reset _utils_helpers.GPU_MEMORY_LIMIT = None
def test_safe_batch_size_edge_cases(): assert utils.safe_batch_size(0) == 1 assert utils.safe_batch_size(-5) == 1 assert utils.safe_batch_size(0.7) == 1 assert utils.safe_batch_size(3.9) == 3 assert utils.safe_batch_size(100) == 100
def test_robust_stream_handler_handles_oserror(tmp_path, monkeypatch): handler = _utils_helpers.RobustStreamHandler() record = logging.LogRecord("test", logging.INFO, "", 0, "msg", (), None) # Monkey-patch emit to raise OSError original_emit = logging.StreamHandler.emit
def bad_emit(self, record): raise OSError("stale handle")
monkeypatch.setattr(logging.StreamHandler, "emit", bad_emit) # Should not raise handler.emit(record) monkeypatch.setattr(logging.StreamHandler, "emit", original_emit)
def test_robust_file_handler_handles_oserror(tmp_path): log_file = tmp_path / "test.log" handler = _utils_helpers.RobustFileHandler(str(log_file)) record = logging.LogRecord("test", logging.INFO, "", 0, "hello", (), None) handler.emit(record) assert log_file.exists() content = log_file.read_text() assert "hello" in content handler.close()
def test_basic_config_logger_and_duplicate_filter(tmp_path): utils.basic_config_logger(str(tmp_path)) logger = utils.logging.getLogger("recovar-test") logger.info("hello") assert (tmp_path / "run.log").exists()
f = utils.DuplicateFilter() r1 = SimpleNamespace(msg="same") r2 = SimpleNamespace(msg="same") assert f.filter(r1) is True assert f.filter(r2) is False
# ---------------------------------------------------------------------------# GPU tests – verify CPU/GPU numerical equivalence# ---------------------------------------------------------------------------
@pytest.mark.gpudef test_make_radial_image_gpu(gpu_device): average = jnp.array([10.0, 20.0], dtype=jnp.float32)
cpu_out = np.asarray(utils.make_radial_image(average, (3, 3), extend_last_frequency=False))
with jax.default_device(gpu_device): average_g = jax.device_put(jnp.array(np.asarray(average)), gpu_device) gpu_out = np.asarray(utils.make_radial_image(average_g, (3, 3), extend_last_frequency=False))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_estimate_variance_gpu(gpu_device): u = np.array([[1 + 1j, 2], [3, 4 - 1j]], dtype=np.complex64) s = np.array([2.0, 3.0], dtype=np.float32)
cpu_out = np.asarray(utils.estimate_variance(u, s))
with jax.default_device(gpu_device): u_g = jax.device_put(jnp.array(u), gpu_device) s_g = jax.device_put(jnp.array(s), gpu_device) gpu_out = np.asarray(utils.estimate_variance(u_g, s_g))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)
@pytest.mark.gpudef test_symmetrize_ft_volume_gpu(gpu_device): vol = jnp.ones((8,), dtype=jnp.complex64)
cpu_out = np.asarray(utils.symmetrize_ft_volume(vol, (2, 2, 2)))
with jax.default_device(gpu_device): vol_g = jax.device_put(jnp.array(np.asarray(vol)), gpu_device) gpu_out = np.asarray(utils.symmetrize_ft_volume(vol_g, (2, 2, 2)))
np.testing.assert_allclose(cpu_out, gpu_out, atol=1e-5, rtol=1e-5)baselines/recovar/tests/unit/test_homogeneous.pyAdded+114
baselines/recovar/tests/unit/test_image_assignment.pyAdded+115
baselines/recovar/tests/unit/test_image_backends.pyAdded+1296
baselines/recovar/tests/unit/test_image_loader.pyAdded+980
baselines/recovar/tests/unit/test_job_dir.pyAdded+272
baselines/recovar/tests/unit/test_latent_density.pyAdded+172
baselines/recovar/tests/unit/test_linalg.pyAdded+349
baselines/recovar/tests/unit/test_load_utils.pyAdded+339
baselines/recovar/tests/unit/test_locres.pyAdded+351
baselines/recovar/tests/unit/test_locres_half_volume.pyAdded+265
baselines/recovar/tests/unit/test_m_step.pyAdded+193
baselines/recovar/tests/unit/test_mask.pyAdded+109
baselines/recovar/tests/unit/test_max_r_default_and_equivalence.pyAdded+560
baselines/recovar/tests/unit/test_memory_planner.pyAdded+745
baselines/recovar/tests/unit/test_metadata_readers.pyAdded+349
baselines/recovar/tests/unit/test_metrics.pyAdded+100
baselines/recovar/tests/unit/test_metrics_regression_helper.pyAdded+93
baselines/recovar/tests/unit/test_module_imports.pyAdded+36
baselines/recovar/tests/unit/test_multi_gpu_utils.pyAdded+88
baselines/recovar/tests/unit/test_noise.pyAdded+595
baselines/recovar/tests/unit/test_output.pyAdded+439
baselines/recovar/tests/unit/test_output_helpers.pyAdded+376
baselines/recovar/tests/unit/test_output_paths.pyAdded+129
baselines/recovar/tests/unit/test_packaging_metadata.pyAdded+138
baselines/recovar/tests/unit/test_padding.pyAdded+94
baselines/recovar/tests/unit/test_parse_relion5_tomo.pyAdded+1391
baselines/recovar/tests/unit/test_parse_relion5_tomo_realdata.pyAdded+123
baselines/recovar/tests/unit/test_parser_args.pyAdded+111
baselines/recovar/tests/unit/test_pdb_utils.pyAdded+89
baselines/recovar/tests/unit/test_perf_regression.pyAdded+68
baselines/recovar/tests/unit/test_pipeline_with_outliers.pyAdded+289
baselines/recovar/tests/unit/test_plot_utils.pyAdded+95
baselines/recovar/tests/unit/test_ppca.pyAdded+117
baselines/recovar/tests/unit/test_principal_components.pyAdded+679
baselines/recovar/tests/unit/test_project.pyAdded+297
baselines/recovar/tests/unit/test_regularization.pyAdded+341
baselines/recovar/tests/unit/test_relion_functions.pyAdded+679
baselines/recovar/tests/unit/test_run_test_all_metrics.pyAdded+1201
baselines/recovar/tests/unit/test_simulate_scattering_potential.pyAdded+183
baselines/recovar/tests/unit/test_simulator.pyAdded+247
baselines/recovar/tests/unit/test_small_experiment.pyAdded+47
baselines/recovar/tests/unit/test_staging.pyAdded+271
baselines/recovar/tests/unit/test_starfile.pyAdded+289
baselines/recovar/tests/unit/test_synthetic_dataset.pyAdded+105
baselines/recovar/tests/unit/test_synthetic_pipeline_integration.pyAdded+44
baselines/recovar/tests/unit/test_tilt_index_consistency.pyAdded+328
baselines/recovar/tests/unit/test_tiny_synthetic_helper.pyAdded+75
baselines/recovar/tests/unit/test_trajectory.pyAdded+203
baselines/recovar/tests/unit/test_trajectory_generation.pyAdded+248
baselines/recovar/tests/unit/test_utils.pyAdded+388