Test resampling equivalences.
(from_shape, from_affine, to_shape, to_affine, order, seed)
| 1110 | @pytest.mark.parametrize("order", [0, 1]) |
| 1111 | @pytest.mark.parametrize("seed", [0, 1]) |
| 1112 | def test_resample_equiv(from_shape, from_affine, to_shape, to_affine, order, seed): |
| 1113 | """Test resampling equivalences.""" |
| 1114 | pytest.importorskip("nibabel") |
| 1115 | pytest.importorskip("dipy") |
| 1116 | rng = np.random.RandomState(seed) |
| 1117 | from_data = rng.randn(*from_shape) |
| 1118 | is_rand = False |
| 1119 | if isinstance(to_affine, str): |
| 1120 | assert to_affine == "rand" |
| 1121 | to_affine = _rand_affine(rng) |
| 1122 | is_rand = True |
| 1123 | if isinstance(from_affine, str): |
| 1124 | assert from_affine == "rand" |
| 1125 | from_affine = _rand_affine(rng) |
| 1126 | is_rand = True |
| 1127 | to_affine = np.array(to_affine, float) |
| 1128 | assert to_affine.shape == (4, 4) |
| 1129 | from_affine = np.array(from_affine, float) |
| 1130 | assert from_affine.shape == (4, 4) |
| 1131 | # |
| 1132 | # 1. nibabel.processing.resample_from_to |
| 1133 | # |
| 1134 | # for a 1mm iso / 256 -> 5mm / 51 one sample takes ~486 ms |
| 1135 | from nibabel.processing import resample_from_to |
| 1136 | from nibabel.spatialimages import SpatialImage |
| 1137 | |
| 1138 | start = np.linalg.norm(from_data) |
| 1139 | got_nibabel = resample_from_to( |
| 1140 | SpatialImage(from_data, from_affine), (to_shape, to_affine), order=order |
| 1141 | ).get_fdata() |
| 1142 | end = np.linalg.norm(got_nibabel) |
| 1143 | assert end > 0.05 * start # not too much power lost |
| 1144 | # |
| 1145 | # 2. dipy.align.imaffine |
| 1146 | # |
| 1147 | # ~366 ms |
| 1148 | import dipy.align.imaffine |
| 1149 | |
| 1150 | interp = "linear" if order == 1 else "nearest" |
| 1151 | got_dipy = dipy.align.imaffine.AffineMap( |
| 1152 | None, |
| 1153 | domain_grid_shape=to_shape, |
| 1154 | domain_grid2world=to_affine, |
| 1155 | codomain_grid_shape=from_shape, |
| 1156 | codomain_grid2world=from_affine, |
| 1157 | ).transform(from_data, interpolation=interp, resample_only=True) |
| 1158 | # XXX possibly some error in dipy or nibabel (/SciPy), or some boundary |
| 1159 | # condition? |
| 1160 | nib_different = (is_rand and order == 1) or ( |
| 1161 | from_affine[0, 0] == 2.0 and not np.allclose(from_affine, to_affine) |
| 1162 | ) |
| 1163 | nib_different = nib_different and not ( |
| 1164 | is_rand and from_affine[0, 0] == 2 and order == 0 |
| 1165 | ) |
| 1166 | if nib_different: |
| 1167 | assert not np.allclose(got_dipy, got_nibabel), "nibabel fixed" |
| 1168 | else: |
| 1169 | assert_allclose(got_dipy, got_nibabel, err_msg="dipy<->nibabel") |
nothing calls this directly
no test coverage detected