ANTsPy: Possible bug in deformation_gradient rotations with py_based=True

Thanks for adding the polar decomposition tests (#818) @ntustison.

The reason I was doubting it was because the tensor reorientation in antspymm appeared to be working despite using the jacobian of the warp field and not its inverse, which was puzzling me. I think the answer might be in the “py_based” part of the computation:

https://github.com/ANTsX/ANTsPy/blob/2ac0e45df5cf14f19e2667258b0ab82d9f759441/ants/registration/create_jacobian_determinant_image.py#L89-L122

This bypasses CreateJacobianDeterminantImage and computes the gradient itself.

However, it does not produce the gradient in physical space - it does the same thing that the ANTs filter was doing:

https://github.com/ANTsX/ANTsPy/blob/2ac0e45df5cf14f19e2667258b0ab82d9f759441/ants/registration/create_jacobian_determinant_image.py#L98-L100

This applies the direction matrix to the displacement vectors that are already in physical space. In the case of a diagonal direction matrix, the direction is its own inverse so this does a rebase of the vectors to index coordinates - it doesn’t change the magnitude into voxels, but that gets accounted for in the gradient calculation. If the fixed image was oblique, applying the direction matrix in this way rotates the vectors into a new coordinate system, which is one reason why CreateJacobianDeterminantImage was giving wrong answers on oblique images.

So the rotations returned by the py_based method are in index coordinates. In the antspymm tests, the direction matrix is very close to diag(-1, -1, 1), so the rotation about z in index space is (I think) equivalent to the opposite rotation in physical space, so it appears to work.

I’ll try to confirm later with further DT reorientation tests @stnava

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 17 (17 by maintainers)

Most upvoted comments

@cookpa – I was not sure where to put this but I think this vectorized implementation is both correct and much faster. also relevant to : https://github.com/ANTsX/ANTsPyMM/issues/27

def deformation_gradient( warp_image, to_rotation=False, to_inverse_rotation=False, py_based=False ):
    """
    Compute the deformation gradient from an image containing a warp (deformation).

    This function now includes a highly optimized pure Python/NumPy implementation.

    ANTsR function: `NA`

    Arguments
    ---------
    warp_image : ANTsImage (or filename if not py_based)
        image that defines the deformation field (vector pixels)

    to_rotation : boolean
        maps deformation gradient to a rotation matrix using polar decomposition.

    to_inverse_rotation : boolean
        map the deformation gradient to a rotation matrix, and return its inverse.
        This is useful for reorienting tensors and vectors after resampling.

    py_based: boolean
        If True, uses the optimized pure Python/NumPy implementation. If False,
        uses the classic C++ backend.

    Returns
    -------
    ANTsImage with dimension*dimension components indexed in order U_xyz, V_xyz, W_xyz
        where U is the x-component of deformation and xyz are spatial.

    Example
    -------
    >>> import ants
    >>> fi = ants.image_read( ants.get_ants_data('r16'))
    >>> mi = ants.image_read( ants.get_ants_data('r64'))
    >>> fi = ants.resample_image(fi,(128,128),1,0)
    >>> mi = ants.resample_image(mi,(128,128),1,0)
    >>> mytx = ants.registration(fixed=fi , moving=mi, type_of_transform = ('SyN') )
    >>> warp = ants.image_read( mytx['fwdtransforms'][0] )
    >>> # Use the fast, optimized Python implementation
    >>> dg_py = ants.deformation_gradient( warp, py_based=True )
    >>> dg_rot_py = ants.deformation_gradient( warp, to_rotation=True, py_based=True )
    """
    if not py_based:
        # --- Original C++ based implementation (unchanged) ---
        if ants.is_image(warp_image):
            txuse = mktemp(suffix='.nii.gz')
            ants.image_write(warp_image, txuse)
        else:
            txuse = warp_image
            warp_image=ants.image_read(txuse)
        if not ants.is_image(warp_image):
            raise RuntimeError("antsimage is required")
        writtenimage = mktemp(suffix='.nrrd')
        dimage = warp_image.split_channels()[0].clone('double')
        dim = dimage.dimension
        tshp = dimage.shape
        args2 = [dim, txuse, writtenimage, int(0), int(0), int(1)]
        processed_args = process_arguments(args2)
        libfn = get_lib_fn('CreateJacobianDeterminantImage')
        libfn(processed_args)
        dg = ants.image_read(writtenimage)
        if to_rotation or to_inverse_rotation:
            # This part still uses loops, but is in the C++ branch.
            newshape = tshp + (dim,dim)
            dg = np.reshape( dg.numpy(), newshape )
            it=np.ndindex(tshp)
            for i in it:
                # Assuming ants.polar_decomposition exists and works as expected
                dg[i]=ants.polar_decomposition( dg[i] )['Z']
                if to_inverse_rotation:
                    dg[i] = dg[i].T
            newshape = tshp + (dim*dim,)
            dg = np.reshape( dg, newshape )
            dg = ants.from_numpy( dg, has_components=True )
            dg = ants.copy_image_info( dimage, dg )
        import os
        os.remove( writtenimage )
        return dg

    # --- Optimized Python/NumPy Implementation ---
    if py_based:
        if not ants.is_image(warp_image):
            raise RuntimeError("antsimage is required")

        dim = warp_image.dimension
        tshp = warp_image.shape
        tdir = warp_image.direction
        spc = warp_image.spacing
        warpnp = warp_image.numpy()

        # Step 1: Compute the gradient of each warp component w.r.t. voxel coordinates.
        # The result is the Jacobian of the physical displacement w.r.t. voxel coordinates.
        # The shape will be (tshp, dim, dim), e.g., (nx, ny, nz, 3, 3)
        # Using a list comprehension and generalized `*spc` is cleaner than if/else.
        gradient_list = [np.gradient(warpnp[..., k], *spc, axis=range(dim)) for k in range(dim)]
        # Stack the gradients correctly to form the Jacobian matrices at each voxel.
        # dg[..., i, j] = d(u_i)/d(v_j) where u is displacement and v is voxel index.
        dg = np.stack([np.stack(grad_k, axis=-1) for grad_k in gradient_list], axis=-2)
        # *** THE FIX IS HERE ***
        # The original loop was equivalent to (tdir @ J.T).T
        # Since our `dg` is J.T, we need to compute (tdir @ dg).T
        # 1. Compute temp = tdir @ dg
        temp = np.einsum('ij,...jk->...ik', tdir, dg)
        # 2. Transpose the result
        axes = (*range(temp.ndim - 2), temp.ndim - 1, temp.ndim - 2)
        dg = np.transpose(temp, axes=axes)
        
        dg += np.eye(dim)
        if to_rotation or to_inverse_rotation:
            U, s, Vh = np.linalg.svd(dg)
            Z = U @ Vh
            dets = np.linalg.det(Z)
            reflection_mask = dets < 0
            Vh[reflection_mask, -1, :] *= -1
            Z[reflection_mask] = U[reflection_mask] @ Vh[reflection_mask]
            dg = Z
            if to_inverse_rotation:
                dg = np.transpose(dg, axes=(*range(dg.ndim - 2), dg.ndim - 1, dg.ndim - 2))
        new_shape = tshp + (dim * dim,)
        dg_reshaped = np.reshape(dg, new_shape)
        return ants.from_numpy(dg_reshaped, origin=warp_image.origin,
                            spacing=warp_image.spacing, direction=warp_image.direction,
                            has_components=True)