-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[core] Fix spatial derivatives when using mode='bspline' or mode='gau…
…ssian'
- Loading branch information
Showing
2 changed files
with
236 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,205 @@ | ||
r"""Interactive test and visualization of vector flow derivatives.""" | ||
|
||
# %% | ||
# Imports | ||
from typing import Dict, Optional, Sequence | ||
|
||
import matplotlib.pyplot as plt | ||
|
||
import torch | ||
from torch import Tensor | ||
from torch.random import Generator | ||
|
||
from deepali.core import Axes, Grid | ||
import deepali.core.bspline as B | ||
import deepali.core.functional as U | ||
|
||
|
||
# %% | ||
# Auxiliary functions | ||
def change_axes(flow: Tensor, grid: Grid, axes: Axes, to_axes: Axes) -> Tensor: | ||
if axes != to_axes: | ||
flow = U.move_dim(flow, 1, -1) | ||
flow = grid.transform_vectors(flow, axes=axes, to_axes=to_axes) | ||
flow = U.move_dim(flow, -1, 1) | ||
return flow | ||
|
||
|
||
def flow_derivatives( | ||
flow: Tensor, grid: Grid, axes: Axes, to_axes: Optional[Axes] = None, **kwargs | ||
) -> Dict[str, Tensor]: | ||
if to_axes is None: | ||
to_axes = axes | ||
flow = change_axes(flow, grid, axes, to_axes) | ||
axes = to_axes | ||
if "spacing" not in kwargs: | ||
if axes == Axes.CUBE: | ||
spacing = tuple(2 / n for n in grid.size()) | ||
elif axes == Axes.CUBE_CORNERS: | ||
spacing = tuple(2 / (n - 1) for n in grid.size()) | ||
elif axes == Axes.GRID: | ||
spacing = 1 | ||
elif axes == Axes.WORLD: | ||
spacing = grid.spacing() | ||
else: | ||
spacing = None | ||
kwargs["spacing"] = spacing | ||
return U.flow_derivatives(flow, **kwargs) | ||
|
||
|
||
def random_svf( | ||
size: Sequence[int], | ||
stride: int = 1, | ||
generator: Optional[Generator] = None, | ||
) -> Tensor: | ||
cp_grid_size = B.cubic_bspline_control_point_grid_size(size, stride=stride) | ||
cp_grid_size = tuple(reversed(cp_grid_size)) | ||
data = torch.randn((1, 3) + cp_grid_size, generator=generator) | ||
data = U.fill_border(data, margin=3, value=0, inplace=True) | ||
return B.evaluate_cubic_bspline(data, size=size, stride=stride) | ||
|
||
|
||
def visualize_flow( | ||
ax: plt.Axes, | ||
flow: Tensor, | ||
grid: Optional[Grid] = None, | ||
axes: Optional[Axes] = None, | ||
label: Optional[str] = None, | ||
) -> None: | ||
if grid is None: | ||
grid = Grid(shape=flow.shape[2:]) | ||
if axes is None: | ||
axes = grid.axes() | ||
flow = change_axes(flow, grid, axes, grid.axes()) | ||
x = grid.coords(channels_last=False, dtype=flow.dtype, device=flow.device) | ||
x = U.move_dim(x.unsqueeze_(0).add_(flow), 1, -1) | ||
target_grid = U.grid_image(shape=flow.shape[2:], inverted=True, stride=(5, 5)) | ||
warped_grid = U.warp_image(target_grid, x, align_corners=grid.align_corners()) | ||
ax.imshow(warped_grid[0, 0, flow.shape[2] // 2], cmap="gray") | ||
if label: | ||
ax.set_title(label, fontsize=24) | ||
|
||
|
||
# %% | ||
# Random velocity fields | ||
generator = torch.Generator().manual_seed(42) | ||
grid = Grid(size=(128, 128, 64), spacing=(0.5, 0.5, 1.0)) | ||
flow = random_svf(grid.size(), stride=8, generator=generator).mul_(0.1) | ||
|
||
fig, axes = plt.subplots(1, 1, figsize=(4, 4)) | ||
|
||
ax = axes | ||
ax.set_title("v", fontsize=24, pad=20) | ||
visualize_flow(ax, flow, grid=grid, axes=grid.axes()) | ||
|
||
|
||
# %% | ||
# Visualise first order derivatives for different modes | ||
configs = [ | ||
dict(mode="forward_central_backward"), | ||
dict(mode="bspline"), | ||
dict(mode="gaussian", sigma=0.7355), | ||
] | ||
|
||
fig, axes = plt.subplots(len(configs), 4, figsize=(16, 4 * len(configs))) | ||
|
||
for i, config in enumerate(configs): | ||
derivs = flow_derivatives( | ||
flow, | ||
grid=grid, | ||
axes=grid.axes(), | ||
to_axes=Axes.GRID, | ||
which=["du/dx", "du/dy", "dv/dx", "dv/dy"], | ||
**config, | ||
) | ||
for ax, (key, deriv) in zip(axes[i], derivs.items()): | ||
if i == 0: | ||
ax.set_title(key, fontsize=24, pad=20) | ||
ax.imshow(deriv[0, 0, deriv.shape[2] // 2], vmin=-1, vmax=1) | ||
|
||
|
||
# %% | ||
# Compare magnitudes of first order derivatives for different modes | ||
flow_axes = [Axes.GRID, Axes.WORLD, Axes.CUBE_CORNERS] | ||
|
||
sigma = 0.7355 | ||
|
||
configs = [ | ||
dict(mode="bspline"), | ||
dict(mode="gaussian", sigma=sigma), | ||
dict(mode="forward_central_backward", sigma=sigma), | ||
dict(mode="forward_central_backward"), | ||
] | ||
|
||
for to_axes in flow_axes: | ||
for config in configs: | ||
print(f"axes={to_axes}, " + ", ".join(f"{k}={v!r}" for k, v in config.items())) | ||
derivs = flow_derivatives( | ||
flow, | ||
grid=grid, | ||
axes=grid.axes(), | ||
to_axes=to_axes, | ||
which=["du/dx", "du/dy", "dv/dx", "dv/dy"], | ||
**config, | ||
) | ||
for key, deriv in derivs.items(): | ||
print(f"- max(abs({key})): {deriv.abs().max().item():.5f}") | ||
print() | ||
print("\n") | ||
|
||
|
||
# %% | ||
# Visualise second order derivatives for different modes | ||
configs = [ | ||
dict(mode="forward_central_backward"), | ||
dict(mode="bspline"), | ||
dict(mode="gaussian", sigma=0.7355), | ||
] | ||
|
||
fig, axes = plt.subplots(len(configs), 4, figsize=(16, 4 * len(configs))) | ||
|
||
for i, config in enumerate(configs): | ||
derivs = flow_derivatives( | ||
flow, | ||
grid=grid, | ||
axes=grid.axes(), | ||
to_axes=Axes.GRID, | ||
which=["du/dxx", "du/dxy", "dv/dxy", "dv/dyy"], | ||
**config, | ||
) | ||
for ax, (key, deriv) in zip(axes[i], derivs.items()): | ||
if i == 0: | ||
ax.set_title(key, fontsize=24, pad=20) | ||
ax.imshow(deriv[0, 0, deriv.shape[2] // 2], vmin=-0.4, vmax=0.4) | ||
|
||
|
||
# %% | ||
# Compare magnitudes of second order derivatives for different modes | ||
flow_axes = [Axes.GRID, Axes.WORLD, Axes.CUBE_CORNERS] | ||
|
||
sigma = 0.7355 | ||
|
||
configs = [ | ||
dict(mode="bspline"), | ||
dict(mode="gaussian", sigma=sigma), | ||
dict(mode="forward_central_backward", sigma=sigma), | ||
dict(mode="forward_central_backward"), | ||
] | ||
|
||
for to_axes in flow_axes: | ||
for config in configs: | ||
print(f"axes={to_axes}, " + ", ".join(f"{k}={v!r}" for k, v in config.items())) | ||
derivs = flow_derivatives( | ||
flow, | ||
grid=grid, | ||
axes=grid.axes(), | ||
to_axes=to_axes, | ||
which=["du/dxx", "du/dxy", "dv/dxy", "dv/dyy"], | ||
**config, | ||
) | ||
for key, deriv in derivs.items(): | ||
print(f"- max(abs({key})): {deriv.abs().max().item():.5f}") | ||
print() | ||
print("\n") | ||
|
||
# %% |