File size: 19,901 Bytes
48ba1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
"""
Unit tests for recovar.adaptive_kernel_discretization.

Tests are organised in three tiers:

1. Pure-Python / numpy utility functions – no JAX tracing needed.
2. JAX-traced functions exercised on tiny synthetic inputs.
3. Dataset-level functions run against make_tiny_cryo_dataset_with_images
   (grid_size=4, n_images=8) so every batch in the real code is exercised
   without GPU memory pressure.
"""

import numpy as np
import pytest

pytest.importorskip("jax")

import jax
import jax.numpy as jnp

import recovar.heterogeneity.adaptive_kernel_discretization as akd

from recovar.core.configs import ForwardModelConfig
from recovar.reconstruction import relion_functions
from helpers.tiny_synthetic import make_tiny_cryo_dataset_with_images

pytestmark = pytest.mark.unit

# ---------------------------------------------------------------------------
# Tier 1 – pure-Python / numpy utilities
# ---------------------------------------------------------------------------


def test_get_feature_size_known_degrees():
    assert akd.get_feature_size(0) == 1
    assert akd.get_feature_size(1) == 4
    assert akd.get_feature_size(2) == 10


def test_small_gram_matrix_size():
    # For degree-0 the Gram matrix is scalar (1x1): upper-tri storage = 1
    assert akd.small_gram_matrix_size(0) == 1
    # For degree-1: feature_size=4, 4*5//2 = 10
    assert akd.small_gram_matrix_size(1) == 10


def test_big_gram_matrix_size():
    assert akd.big_gram_matrix_size(0) == 1
    assert akd.big_gram_matrix_size(1) == 16  # 4**2


def test_volume_shape_to_half_volume_shape_even():
    vs = (8, 8, 8)
    hvs = akd.volume_shape_to_half_volume_shape(vs)
    assert hvs == (8, 8, 5)  # canonical: last axis truncated


def test_volume_shape_to_half_volume_shape_four():
    vs = (4, 4, 4)
    hvs = akd.volume_shape_to_half_volume_shape(vs)
    assert hvs == (4, 4, 3)  # canonical: last axis truncated


def test_get_default_discretization_params_small_grid():
    params = akd.get_default_discretization_params(grid_size=32)
    assert len(params) > 0
    for pol_degree, h, flag in params:
        assert pol_degree in (0, 1)
        assert isinstance(h, int)
        assert isinstance(flag, bool)


def test_keep_upper_triangular_roundtrip():
    """keep_upper_triangular extracts upper-tri; undo should recover it."""
    n = 3
    mat = np.arange(n * n, dtype=np.float32).reshape(n, n)
    mat = mat + mat.T  # make symmetric
    mat = mat[np.newaxis]  # (1, n, n)
    flat = akd.keep_upper_triangular(mat)  # (1, m) where m = n(n+1)/2
    assert flat.shape == (1, n * (n + 1) // 2)
    recovered = akd.undo_keep_upper_triangular(flat)  # (1, n, n)
    np.testing.assert_allclose(np.asarray(recovered[0]), mat[0], atol=1e-6)


def test_find_smaller_pol_indices_degree0_inside_degree1():
    """Degree-0 indices must be a strict subset of degree-1 indices."""
    idx = akd.find_smaller_pol_indices(max_pol_degree=1, target_pol_degree=0)
    # degree-0 has 1 parameter; result should be of length 1
    assert idx.shape[0] == 1
    # All indices must be valid for the degree-1 upper-triangular layout
    n_max = akd.small_gram_matrix_size(1)
    assert int(idx[0]) < n_max


def test_find_diagonal_pol_indices_degree0():
    idx = akd.find_diagonal_pol_indices(max_pol_degree=0)
    assert idx.shape[0] == 1
    assert idx[0] == 0


def test_find_diagonal_pol_indices_degree1():
    # Degree-1 has 4 features; diagonal entries of 4x4 are 4 elements.
    # Upper-tri storage of a 4x4 matrix has 10 entries.
    idx = akd.find_diagonal_pol_indices(max_pol_degree=1)
    assert idx.shape[0] == 4
    # All indices must be within the valid upper-tri range
    n_flat = akd.small_gram_matrix_size(1)
    assert np.all(idx < n_flat)


def test_pad_noise_variance_for_fixed_batch_marks_padded_rows_infinite():
    noise = np.array([[1.0, 2.0, 3.0]], dtype=np.float32)
    padded = akd._pad_noise_variance_for_fixed_batch(
        noise,
        current_batch_size=2,
        target_batch_size=4,
    )

    assert padded.shape == (4, 3)
    np.testing.assert_array_equal(
        padded[:2],
        np.array([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]], dtype=np.float32),
    )
    assert np.isinf(padded[2:]).all()


def test_pad_heterogeneity_kernel_batch_preserves_valid_rows_and_zero_weights_padding():
    images = np.arange(2 * 4 * 4, dtype=np.float32).reshape(2, 4, 4)
    rotation_matrices = np.tile(np.eye(3, dtype=np.float32), (2, 1, 1))
    translations = np.arange(4, dtype=np.float32).reshape(2, 2)
    ctf_params = np.arange(18, dtype=np.float32).reshape(2, 9)
    noise_variance = np.array([[5.0, 6.0, 7.0, 8.0]], dtype=np.float32)

    padded = akd._pad_heterogeneity_kernel_batch(
        images,
        rotation_matrices,
        translations,
        ctf_params,
        noise_variance,
        target_batch_size=4,
    )
    padded_images, padded_rots, padded_trans, padded_ctf, padded_noise = padded

    assert padded_images.shape == (4, 4, 4)
    assert padded_rots.shape == (4, 3, 3)
    assert padded_trans.shape == (4, 2)
    assert padded_ctf.shape == (4, 9)
    assert padded_noise.shape == (4, 4)

    np.testing.assert_array_equal(padded_images[:2], images)
    np.testing.assert_array_equal(padded_rots[:2], rotation_matrices)
    np.testing.assert_array_equal(padded_trans[:2], translations)
    np.testing.assert_array_equal(padded_ctf[:2], ctf_params)
    np.testing.assert_array_equal(
        padded_noise[:2],
        np.array([[5.0, 6.0, 7.0, 8.0], [5.0, 6.0, 7.0, 8.0]], dtype=np.float32),
    )
    np.testing.assert_array_equal(
        padded_images[2:],
        np.zeros((2, 4, 4), dtype=np.float32),
    )
    assert np.isinf(padded_noise[2:]).all()


# ---------------------------------------------------------------------------
# Tier 2 – JAX-traced functions on tiny synthetic inputs
# ---------------------------------------------------------------------------


def test_full_volume_to_half_volume_to_full_roundtrip():
    """full→half→full should preserve values in the 'negative-frequency' half."""
    vol_shape = (4, 4, 4)
    vol_size = int(np.prod(vol_shape))
    vol = jnp.array(np.random.randn(vol_size).astype(np.complex64) + 1j * np.random.randn(vol_size).astype(np.float32))
    half = akd.full_volume_to_half_volume(vol, vol_shape)
    half_size = int(np.prod(akd.volume_shape_to_half_volume_shape(vol_shape)))
    assert half.shape == (half_size,)
    # Reconstructed volume must be finite
    full_back = akd.half_volume_to_full_volume(half, vol_shape)
    assert np.all(np.isfinite(np.asarray(full_back)))


def test_vec_index_to_half_vec_index_shape():
    vol_shape = (4, 4, 4)
    vol_size = int(np.prod(vol_shape))
    indices = jnp.arange(vol_size, dtype=jnp.int32)
    half_indices, neg_freq = akd.vec_index_to_half_vec_index(indices, vol_shape, flip_positive=False)
    assert half_indices.shape == (vol_size,)
    assert neg_freq.shape == (vol_size,)
    # neg_freq must be boolean-like (0/1)
    vals = np.asarray(neg_freq)
    assert np.all((vals == 0) | (vals == 1))


def test_solve_for_m_simple_identity_system():
    """solve_for_m_simple on a well-conditioned system returns correct answer."""
    n = 4
    A = jnp.eye(n, dtype=jnp.float32) * 5.0
    b = jnp.array([1.0 + 0j, 2.0 + 0j, 3.0 + 0j, 4.0 + 0j], dtype=jnp.complex64)
    reg = jnp.eye(n, dtype=jnp.float32) * 1e-6
    v, good_v, problem = akd.solve_for_m_simple(A, b, reg)
    expected = jnp.array([0.2, 0.4, 0.6, 0.8], dtype=jnp.complex64)
    np.testing.assert_allclose(np.asarray(v).real, np.asarray(expected).real, atol=1e-4)
    assert bool(good_v)


def test_make_X_mat_pol_degree_0_shape():
    """For pol_degree=0 the feature matrix has shape (n_images, n_pixels, 1)."""
    n_images = 4
    grid_size = 4
    vol_shape = (grid_size, grid_size, grid_size)
    img_shape = (grid_size, grid_size)
    rots = np.tile(np.eye(3, dtype=np.float32), (n_images, 1, 1))
    X, grid_pt_indices = akd.make_X_mat(rots, vol_shape, img_shape, pol_degree=0)
    n_pixels = grid_size * grid_size
    assert X.shape == (n_images, n_pixels, 1)
    assert grid_pt_indices.shape == (n_images, n_pixels)


def test_make_X_mat_pol_degree_1_shape():
    """For pol_degree=1 the feature matrix has 4 features per pixel (1+3)."""
    n_images = 4
    grid_size = 4
    vol_shape = (grid_size, grid_size, grid_size)
    img_shape = (grid_size, grid_size)
    rots = np.tile(np.eye(3, dtype=np.float32), (n_images, 1, 1))
    X, _ = akd.make_X_mat(rots, vol_shape, img_shape, pol_degree=1)
    n_pixels = grid_size * grid_size
    assert X.shape == (n_images, n_pixels, akd.get_feature_size(1))


# ---------------------------------------------------------------------------
# Tier 3 – Dataset-level: precompute + reconstruct with a tiny dataset
# ---------------------------------------------------------------------------


def test_precompute_triangular_kernel_shapes():
    """precompute_triangular_kernel returns XWX and F with expected shapes."""
    cryo = make_tiny_cryo_dataset_with_images(grid_size=4, n_images=8)
    noise_variance = np.ones(cryo.grid_size // 2 - 1, dtype=np.float32) * 0.1

    XWX, F = akd.precompute_triangular_kernel(cryo, noise_variance, pol_degree=0)

    half_vol_size = int(np.prod(akd.volume_shape_to_half_volume_shape(cryo.volume_shape)))
    gram_size = akd.small_gram_matrix_size(0)
    feat_size = akd.get_feature_size(0)

    assert XWX.shape == (half_vol_size, gram_size, 1)
    assert F.shape == (half_vol_size, feat_size, 1)
    # XWX (CTF^2/noise) must be finite; F (CTF*image/noise) may have NaN for
    # zero-coverage voxels, which is acceptable - the solver ignores them.
    assert np.isfinite(XWX).all()


def test_precompute_kernel_shapes():
    """precompute_kernel (original codepath) returns same shapes as triangular version."""
    cryo = make_tiny_cryo_dataset_with_images(grid_size=4, n_images=8)
    noise_variance = np.ones(cryo.grid_size // 2 - 1, dtype=np.float32) * 0.1

    XWX, F = akd.precompute_kernel(cryo, noise_variance, pol_degree=0)

    half_vol_size = int(np.prod(akd.volume_shape_to_half_volume_shape(cryo.volume_shape)))
    gram_size = akd.small_gram_matrix_size(0)
    feat_size = akd.get_feature_size(0)

    assert XWX.shape == (half_vol_size, gram_size, 1)
    assert F.shape == (half_vol_size, feat_size, 1)


def test_precompute_kernel_with_heterogeneity_bins():
    """Passing heterogeneity_bins expands the trailing dimension of XWX and F."""
    cryo = make_tiny_cryo_dataset_with_images(grid_size=4, n_images=8)
    noise_variance = np.ones(cryo.grid_size // 2 - 1, dtype=np.float32) * 0.1
    n_bins = 3
    het_dists = np.random.rand(cryo.n_images).astype(np.float32)
    het_bins = np.array([0.3, 0.6, 1.0], dtype=np.float32)

    XWX, F = akd.precompute_triangular_kernel(
        cryo,
        noise_variance,
        pol_degree=0,
        heterogeneity_distances=het_dists,
        heterogeneity_bins=het_bins,
    )

    half_vol_size = int(np.prod(akd.volume_shape_to_half_volume_shape(cryo.volume_shape)))
    assert XWX.shape == (half_vol_size, akd.small_gram_matrix_size(0), n_bins)
    assert F.shape == (half_vol_size, akd.get_feature_size(0), n_bins)


def test_estimate_multiple_disc_relion_style_returns_finite_volume():
    """Full end-to-end pipeline with tiny dataset must return finite reconstructions."""
    cryo = make_tiny_cryo_dataset_with_images(grid_size=4, n_images=8)
    noise_variance = np.ones(cryo.grid_size // 2 - 1, dtype=np.float32) * 0.1
    disc_params = [(0, 0, True)]  # minimal single param set
    n_bins = 2
    het_bins = np.array([0.5, 1.0], dtype=np.float32)
    # Two half-datasets each with n_images=8 random heterogeneity distances
    het_dists = [
        np.random.rand(cryo.n_images).astype(np.float32),
        np.random.rand(cryo.n_images).astype(np.float32),
    ]

    # estimate_multiple_disc_relion_style returns (first_estimates, opt_halfmaps,
    # disc_choices, residuals_averaged) – unpack all four.
    first_estimates, opt_halfmaps, disc_choices, residuals = akd.estimate_multiple_disc_relion_style(
        experiment_datasets=[cryo, cryo],
        noise_variance=noise_variance,
        discretization_params=disc_params,
        heterogeneity_distances=het_dists,
        heterogeneity_bins=het_bins,
    )

    assert first_estimates is not None
    assert opt_halfmaps is not None


@pytest.mark.gpu
def test_even_less_naive_matches_reference_bin_loop(gpu_device):
    """even_less_naive bin accumulation should match explicit per-bin reference."""
    cryo = make_tiny_cryo_dataset_with_images(grid_size=4, n_images=8, seed=11)
    het_dists = np.array([0.1, 0.2, 0.35, 0.7, 0.75, 1.1, 1.2, 1.8], dtype=np.float32)
    bins = np.array([0.25, 0.8, 1.3], dtype=np.float32)
    batch_size = 4

    with jax.default_device(gpu_device):
        est_new, lhs_new, rhs_new = akd.even_less_naive_heterogeneity_scheme_relion_style(
            cryo,
            None,
            het_dists,
            bins,
            batch_size=batch_size,
            tau=None,
            grid_correct=False,
            use_spherical_mask=False,
            return_lhs_rhs=True,
            heterogeneity_kernel="square",
            upsampling_factor=1,
        )

        inds = np.digitize(het_dists, bins, right=True).astype(np.int32)
        n_bins = bins.size
        upsampled_shape = (cryo.grid_size, cryo.grid_size, cryo.grid_size)
        half_vol_size = int(np.prod(akd.volume_shape_to_half_volume_shape(upsampled_shape)))

        rhs_ref = np.zeros((n_bins, half_vol_size), dtype=np.complex64)
        lhs_ref = np.zeros((n_bins, half_vol_size), dtype=np.float32)

        cfg = ForwardModelConfig.from_dataset(cryo, disc_type="linear_interp", upsampling_factor=1)
        for bin_idx in range(n_bins):
            image_inds = np.sort(np.where(inds == bin_idx)[0])
            Ft_y_acc = jnp.zeros(half_vol_size, dtype=cryo.dtype)
            Ft_ctf_acc = jnp.zeros(half_vol_size, dtype=cryo.dtype_real)
            for (
                images,
                rotation_matrices,
                translations,
                ctf_params,
                noise_variance,
                _particle_indices,
                _image_indices,
            ) in cryo.iter_batches(
                batch_size,
                noise_model=cryo.noise,
                noise_half=False,
                indices=image_inds,
            ):
                images = cryo.process_images_half(images)
                Ft_y_acc, Ft_ctf_acc = akd._heterogeneity_kernel_batch_from_fft(
                    cfg,
                    images,
                    ctf_params,
                    rotation_matrices,
                    translations,
                    noise_variance,
                    Ft_y=Ft_y_acc,
                    Ft_ctf=Ft_ctf_acc,
                )
            rhs_ref[bin_idx] = np.asarray(Ft_y_acc)
            lhs_ref[bin_idx] = np.asarray(Ft_ctf_acc)

        rhs_ref = np.cumsum(rhs_ref, axis=0)
        lhs_ref = np.cumsum(lhs_ref, axis=0)

        est_ref = []
        for idx in range(n_bins):
            est = relion_functions.post_process_from_filter_v2(
                lhs_ref[idx],
                rhs_ref[idx],
                cryo.volume_shape,
                1,
                tau=None,
                kernel="triangular",
                use_spherical_mask=False,
                grid_correct=False,
                input_half_volume=True,
            )
            est_ref.append(np.asarray(est).reshape(-1))
        est_ref = np.asarray(est_ref)

    np.testing.assert_allclose(lhs_new, lhs_ref, atol=1e-5, rtol=1e-5)
    np.testing.assert_allclose(rhs_new, rhs_ref, atol=1e-5, rtol=1e-5)
    np.testing.assert_allclose(est_new, est_ref, atol=1e-4, rtol=1e-4)


# ---------------------------------------------------------------------------
# GPU tests – verify CPU/GPU numerical equivalence
# ---------------------------------------------------------------------------


@pytest.mark.gpu
def test_full_volume_to_half_volume_roundtrip_gpu(gpu_device):
    vol_shape = (4, 4, 4)
    vol_size = int(np.prod(vol_shape))
    vol = jnp.array(
        np.random.randn(vol_size).astype(np.float32) + 1j * np.random.randn(vol_size).astype(np.float32),
        dtype=jnp.complex64,
    )

    cpu_half = np.asarray(akd.full_volume_to_half_volume(vol, vol_shape))
    cpu_full = np.asarray(akd.half_volume_to_full_volume(jnp.array(cpu_half), vol_shape))

    with jax.default_device(gpu_device):
        vol_g = jax.device_put(vol, gpu_device)
        gpu_half = np.asarray(akd.full_volume_to_half_volume(vol_g, vol_shape))
        gpu_full = np.asarray(
            akd.half_volume_to_full_volume(jax.device_put(jnp.array(cpu_half), gpu_device), vol_shape)
        )

    np.testing.assert_allclose(cpu_half, gpu_half, atol=1e-5, rtol=1e-5)
    np.testing.assert_allclose(cpu_full, gpu_full, atol=1e-5, rtol=1e-5)


@pytest.mark.gpu
def test_vec_index_to_half_vec_index_gpu(gpu_device):
    vol_shape = (4, 4, 4)
    vol_size = int(np.prod(vol_shape))
    indices = jnp.arange(vol_size, dtype=jnp.int32)

    cpu_half, cpu_neg = akd.vec_index_to_half_vec_index(indices, vol_shape, flip_positive=False)
    cpu_half, cpu_neg = np.asarray(cpu_half), np.asarray(cpu_neg)

    with jax.default_device(gpu_device):
        indices_g = jax.device_put(indices, gpu_device)
        gpu_half, gpu_neg = akd.vec_index_to_half_vec_index(indices_g, vol_shape, flip_positive=False)
        gpu_half, gpu_neg = np.asarray(gpu_half), np.asarray(gpu_neg)

    np.testing.assert_array_equal(cpu_half, gpu_half)
    np.testing.assert_array_equal(cpu_neg, gpu_neg)


@pytest.mark.gpu
def test_solve_for_m_simple_gpu(gpu_device):
    n = 4
    A = jnp.eye(n, dtype=jnp.float32) * 5.0
    b = jnp.array([1.0 + 0j, 2.0 + 0j, 3.0 + 0j, 4.0 + 0j], dtype=jnp.complex64)
    reg = jnp.eye(n, dtype=jnp.float32) * 1e-6

    cpu_v, cpu_good, cpu_prob = akd.solve_for_m_simple(A, b, reg)
    cpu_v = np.asarray(cpu_v)

    with jax.default_device(gpu_device):
        A_g = jax.device_put(A, gpu_device)
        b_g = jax.device_put(b, gpu_device)
        reg_g = jax.device_put(reg, gpu_device)
        gpu_v, gpu_good, gpu_prob = akd.solve_for_m_simple(A_g, b_g, reg_g)
        gpu_v = np.asarray(gpu_v)

    np.testing.assert_allclose(cpu_v, gpu_v, atol=1e-4, rtol=1e-4)
    assert bool(cpu_good) == bool(gpu_good)


@pytest.mark.gpu
def test_make_X_mat_gpu(gpu_device):
    n_images = 4
    grid_size = 4
    vol_shape = (grid_size, grid_size, grid_size)
    img_shape = (grid_size, grid_size)
    rots = np.tile(np.eye(3, dtype=np.float32), (n_images, 1, 1))

    cpu_X, cpu_idx = akd.make_X_mat(rots, vol_shape, img_shape, pol_degree=1)
    cpu_X, cpu_idx = np.asarray(cpu_X), np.asarray(cpu_idx)

    with jax.default_device(gpu_device):
        rots_g = jax.device_put(jnp.array(rots), gpu_device)
        gpu_X, gpu_idx = akd.make_X_mat(rots_g, vol_shape, img_shape, pol_degree=1)
        gpu_X, gpu_idx = np.asarray(gpu_X), np.asarray(gpu_idx)

    np.testing.assert_allclose(cpu_X, gpu_X, atol=1e-5, rtol=1e-5)
    np.testing.assert_array_equal(cpu_idx, gpu_idx)


@pytest.mark.gpu
def test_keep_upper_triangular_roundtrip_gpu(gpu_device):
    n = 3
    mat = np.arange(n * n, dtype=np.float32).reshape(n, n)
    mat = mat + mat.T
    mat_j = jnp.array(mat[np.newaxis])

    cpu_flat = np.asarray(akd.keep_upper_triangular(mat_j))
    cpu_recovered = np.asarray(akd.undo_keep_upper_triangular(jnp.array(cpu_flat)))

    with jax.default_device(gpu_device):
        mat_g = jax.device_put(mat_j, gpu_device)
        gpu_flat = np.asarray(akd.keep_upper_triangular(mat_g))
        gpu_recovered = np.asarray(akd.undo_keep_upper_triangular(jax.device_put(jnp.array(cpu_flat), gpu_device)))

    np.testing.assert_allclose(cpu_flat, gpu_flat, atol=1e-6)
    np.testing.assert_allclose(cpu_recovered, gpu_recovered, atol=1e-6)