curvelets.torch package

PyTorch implementation of Uniform Discrete Curvelet Transform (UDCT).

class curvelets.torch.MeyerWavelet(shape)

Bases: object

Multi-dimensional Meyer wavelet transform with pre-computed filters.

This class provides forward and backward Meyer wavelet transforms with filters pre-computed during initialization for improved performance. The forward transform returns all subbands in a nested list structure, and the backward transform accepts this full structure for reconstruction.

The filter computation uses the same method as UDCT’s _create_bandpass_windows() for num_scales=2, ensuring compatibility when used with UDCT in wavelet mode with num_scales=2 and high_frequency_mode=”wavelet”.

Parameters:

shape (tuple[int, ...]) – Expected shape of input signals. Used for validation and to determine the number of dimensions. All dimensions must be even (divisible by 2).

shape

Expected signal shape (all dimensions are even).

Type:

tuple[int, …]

dimension

Number of dimensions.

Type:

int

Raises:

ValueError – If any dimension in shape is odd (not divisible by 2).

Notes

This implementation requires all dimensions to be even. Odd-length signals are not supported due to the downsampling strategy used in the transform, which produces mismatched subband sizes that cannot be correctly reconstructed.

Examples

>>> import torch
>>> from curvelets.torch import MeyerWavelet
>>> wavelet = MeyerWavelet(shape=(64, 64))
>>> signal = torch.randn(64, 64)
>>> coefficients = wavelet.forward(signal)
>>> len(coefficients)  # 2 subband groups
2
>>> coefficients[0][0].shape  # Lowpass subband
torch.Size([32, 32])
>>> len(coefficients[1])  # Highpass subbands
3
>>> reconstructed = wavelet.backward(coefficients)
>>> torch.allclose(signal, reconstructed, atol=1e-10)
True
>>> # Odd dimensions raise an error
>>> try:
...     MeyerWavelet(shape=(65, 65))
... except ValueError:
...     print("Odd dimensions not supported")
Odd dimensions not supported
backward(coefficients)

Apply multi-dimensional Meyer wavelet inverse transform.

Reconstructs the original signal from the full coefficient structure returned by forward().

Parameters:

coefficients (list[list[Tensor]]) –

Full coefficient structure from forward() with 2 subband groups:

  • coefficients[0]: [lowpass] - single lowpass subband

  • coefficients[1]: [highpass_0, highpass_1, …] - all highpass subbands

Returns:

Reconstructed signal with shape matching the original input.

Return type:

Tensor

Raises:

ValueError – If coefficients structure is invalid (must have 2 subband groups).

Examples

>>> import torch
>>> from curvelets.torch import MeyerWavelet
>>> wavelet = MeyerWavelet(shape=(64, 64))
>>> signal = torch.randn(64, 64)
>>> coefficients = wavelet.forward(signal)
>>> reconstructed = wavelet.backward(coefficients)
>>> torch.allclose(signal, reconstructed, atol=1e-10)
True
forward(signal)

Apply multi-dimensional Meyer wavelet forward transform.

Decomposes the input signal into 2^dimension subbands organized into 2 subband groups. Returns all subbands in a nested list structure similar to UDCT.

Parameters:

signal (Tensor) – Input tensor (real or complex). Must match the shape specified during initialization.

Returns:

All subbands organized into 2 subband groups:

  • coefficients[0]: [lowpass] - single lowpass subband (1 subband)

  • coefficients[1]: [highpass_0, highpass_1, …] - all highpass subbands (2^dimension - 1 subbands)

Each subband has shape approximately half the input shape in each dimension.

Return type:

list[list[Tensor]]

Raises:

ValueError – If signal shape does not match expected shape.

Examples

>>> import torch
>>> from curvelets.torch import MeyerWavelet
>>> wavelet = MeyerWavelet(shape=(64, 64))
>>> signal = torch.randn(64, 64)
>>> coefficients = wavelet.forward(signal)
>>> len(coefficients)  # 2 subband groups
2
>>> coefficients[0][0].shape  # Lowpass subband
torch.Size([32, 32])
>>> len(coefficients[1])  # Highpass subbands
3
class curvelets.torch.SparseWindow(indices, values, shape, folded_indices=None, flipped_indices=None, flipped_folded_indices=None, decimation=None, out_shape=None)

Bases: object

Sparse frequency-domain window for efficient curvelet operations (PyTorch).

This class represents a sparse window as a collection of indices and values, providing efficient methods for forward and backward curvelet transforms.

Parameters:
  • indices (Tensor) – Flat indices into array where window has non-zero values.

  • values (Tensor) – Window values at those indices.

  • shape (tuple[int, ...]) – Original array shape (for to_dense conversion).

  • folded_indices (Tensor | None) – Decimated-grid flat indices attached by attach_periodized.

  • flipped_indices (Tensor | None) – FFT-axis flipped flat indices attached when with_flip=True.

  • flipped_folded_indices (Tensor | None) – Folded indices corresponding to flipped_indices.

  • decimation (Tensor | None) – Per-axis decimation ratios attached with periodized maps.

  • out_shape (tuple[int, ...] | None) – Decimated coefficient shape s // d per axis.

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> arr = torch.tensor([[0.1, 0.9], [0.2, 0.8]])
>>> window = SparseWindow.from_dense(arr, threshold=0.5)
>>> window.size
2
>>> dense = window.to_dense()
>>> dense.shape
torch.Size([2, 2])
analyze(image_frequency, scale, *, flip=False, extra_at_indices=None, decimation=None)

Forward periodized wedge: fold → small IFFT → scale.

Parameters:
  • image_frequency (Tensor) – Full-size frequency-domain tensor.

  • scale (float) – Combined normalization factor applied after the small IFFT.

  • flip (bool) – If True, use flipped indices.

  • extra_at_indices (Tensor | None) – Extra weights aligned with window indices (e.g. Riesz samples).

  • decimation (Any | None) – Fallback when periodized maps are not attached.

Returns:

Decimated coefficient tensor.

Return type:

Tensor

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.ones((8, 8)), threshold=0.5)
>>> window.attach_periodized([2, 2])
>>> image_freq = torch.fft.fftn(torch.randn(8, 8))
>>> coeff = window.analyze(image_freq, scale=1.0)
>>> coeff.shape
torch.Size([4, 4])
apply(fn)

Return a new window with fn applied to every tensor it holds.

Unlike rebuilding the window from indices and values, this keeps the precomputed periodized index maps, so the transform does not have to recompute them on every call. decimation is small integer metadata and stays where it is (normally the CPU).

Added in version 1.3.

Parameters:

fn (Callable[[Tensor], Tensor]) – Tensor function, e.g. lambda t: t.cuda() or the function torch.nn.Module._apply passes for .to() / .half().

Returns:

New window with mapped tensors.

Return type:

SparseWindow

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.ones((8, 8)), threshold=0.5)
>>> window.attach_periodized([2, 2])
>>> moved = window.apply(lambda t: t.clone())
>>> moved.folded_indices is not None
True
attach_periodized(decimation, *, with_flip=False)

Attach decimation and precomputed folded (and optional flipped) index maps.

Parameters:
  • decimation (Any) – Per-axis decimation ratios for this window.

  • with_flip (bool) – If True, also attach flipped index maps for complex mode. Default is False.

Return type:

None

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.ones((8, 8)), threshold=0.5)
>>> window.attach_periodized([2, 2], with_flip=True)
>>> window.folded_indices is not None
True
>>> window.flipped_indices is not None
True
>>> window.out_shape
(4, 4)
decimation: Tensor | None = None
property device: device

Device of the window tensors.

Returns:

Device where the window tensors are located.

Return type:

torch.device

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> arr = torch.tensor([0.1, 0.9])
>>> window = SparseWindow.from_dense(arr, threshold=0.5)
>>> window.device
device(type='cpu')
flipped_folded_indices: Tensor | None = None
flipped_indices: Tensor | None = None
fold_product(image_frequency, *, flip=False, extra_at_indices=None, decimation=None, out=None)

Fold values * image_frequency[indices] into the decimated frequency grid.

Parameters:
  • image_frequency (Tensor) – Full-size frequency-domain tensor.

  • flip (bool) – If True, use flipped indices.

  • extra_at_indices (Tensor | None) – Extra multiplicative weights already aligned with window indices (e.g. Riesz filter samples).

  • decimation (Any | None) – Fallback when periodized maps are not attached.

  • out (Tensor | None) – Reusable output buffer (cleared before use).

Returns:

Folded spectrum of shape out_shape.

Return type:

Tensor

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.ones((4, 4)), threshold=0.5)
>>> window.attach_periodized([2, 2])
>>> image_freq = torch.ones((4, 4), dtype=torch.complex128)
>>> folded = window.fold_product(image_freq)
>>> folded.shape
torch.Size([2, 2])
folded_indices: Tensor | None = None
classmethod from_dense(arr, threshold)

Create SparseWindow from dense tensor using threshold.

Parameters:
  • arr (Tensor) – Input dense tensor.

  • threshold (float) – Threshold for sparse storage (values above threshold are kept).

Returns:

Sparse window containing only values above threshold.

Return type:

SparseWindow

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> arr = torch.tensor([[0.1, 0.9], [0.2, 0.8]])
>>> window = SparseWindow.from_dense(arr, threshold=0.5)
>>> window.size
2
indices: Tensor
multiply_at_indices(source, filter_arr, out=None)

Multiply source values at window indices by filter values at same indices.

This method replaces the pattern: out.flatten()[idx] = source.flatten()[idx] * filter_arr.flatten()[idx]

Parameters:
  • source (Tensor) – Source tensor (typically already windowed).

  • filter_arr (Tensor) – Filter tensor to multiply with (e.g., Riesz filter).

  • out (Tensor | None) – Output tensor to write results into. If None, a new tensor is created.

Returns:

Dense tensor with multiplied values at window indices.

Return type:

Tensor

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.tensor([0.0, 0.5, 1.0]), threshold=0.3)
>>> source = torch.tensor([1.0, 2.0, 3.0])
>>> filter_arr = torch.tensor([0.5, 1.5, 2.5])
>>> result = window.multiply_at_indices(source, filter_arr)
>>> result[1]  # Only indices 1 and 2 are in window
tensor(3.)
multiply_extract(arr, out=None)

Extract values at indices, multiply by window, return dense result.

This method replaces the pattern: freq_band.flatten()[idx] = image_frequency.flatten()[idx] * val

Parameters:
  • arr (Tensor) – Input tensor to extract values from.

  • out (Tensor | None) – Output tensor to write results into. If None, a new tensor is created.

Returns:

Dense tensor with extracted and multiplied values.

Return type:

Tensor

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.tensor([0.0, 0.5, 1.0]), threshold=0.3)
>>> arr = torch.tensor([1.0, 2.0, 3.0])
>>> result = window.multiply_extract(arr)
>>> result[1]  # Only index 1 and 2 are in window
tensor(1.)
out_shape: tuple[int, ...] | None = None
resolve_indices(*, flip=False, decimation=None)

Return (indices, folded_indices), computing on the fly if needed.

Parameters:
  • flip (bool) – If True, use flipped indices (complex negative-frequency wedges).

  • decimation (Any | None) – Used only when folded maps are not yet attached.

Return type:

tuple[Tensor, Tensor]

Returns:

  • indices (torch.Tensor) – Flat indices into the full-size frequency grid.

  • folded_indices (torch.Tensor) – Flat indices into the decimated grid.

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.ones((8, 8)), threshold=0.5)
>>> window.attach_periodized([2, 2])
>>> idx, folded = window.resolve_indices()
>>> len(idx) == len(folded) == window.size
True
scatter_add(target, source)

Add source*window to target at window indices (in-place).

This method replaces the pattern: target.flatten()[idx] += source.flatten()[idx] * val

Parameters:
  • target (Tensor) – Target tensor to accumulate into (modified in-place).

  • source (Tensor) – Source tensor to extract values from.

Return type:

None

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.tensor([0.0, 0.5, 1.0]), threshold=0.3)
>>> target = torch.zeros(3)
>>> source = torch.tensor([1.0, 2.0, 3.0])
>>> window.scatter_add(target, source)
>>> target[1]  # Only indices 1 and 2 are accumulated
tensor(1.)
scatter_tiled(small_fft, target, scale, *, flip=False, decimation=None)

Scatter scale * values * tile(small_fft) into target.

Parameters:
  • small_fft (Tensor) – fftn of the coefficient tensor.

  • target (Tensor) – Full-size frequency accumulator (modified in-place).

  • scale (float) – Combined normalization / mode scale factor.

  • flip (bool) – If True, use flipped indices.

  • decimation (Any | None) – Fallback when periodized maps are not attached.

Return type:

None

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.ones((4, 4)), threshold=0.5)
>>> window.attach_periodized([2, 2])
>>> target = torch.zeros((4, 4), dtype=torch.complex128)
>>> small = torch.ones((2, 2), dtype=torch.complex128)
>>> window.scatter_tiled(small, target, scale=1.0)
>>> bool(torch.any(target != 0))
True
shape: tuple[int, ...]
property size: int

Number of non-zero elements.

Returns:

Number of non-zero elements in the sparse window.

Return type:

int

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.tensor([0.1, 0.9, 0.2]), threshold=0.5)
>>> window.size
1
synthesize(coefficient, target, scale, *, flip=False, decimation=None)

Backward periodized wedge: small FFT → tiled sparse scatter into target.

Parameters:
  • coefficient (Tensor) – Decimated coefficient tensor.

  • target (Tensor) – Full-size frequency accumulator (modified in-place).

  • scale (float) – Combined normalization / mode scale factor.

  • flip (bool) – If True, use flipped indices.

  • decimation (Any | None) – Fallback when periodized maps are not attached.

Return type:

None

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.ones((8, 8)), threshold=0.5)
>>> window.attach_periodized([2, 2])
>>> target = torch.zeros((8, 8), dtype=torch.complex128)
>>> coeff = torch.ones((4, 4), dtype=torch.complex128)
>>> window.synthesize(coeff, target, scale=1.0)
>>> bool(torch.any(target != 0))
True
to(device)

Move window to specified device.

Parameters:

device (device) – Target device to move window to.

Returns:

New SparseWindow instance on the specified device.

Return type:

SparseWindow

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.tensor([0.1, 0.9]), threshold=0.5)
>>> window_gpu = window.to(torch.device("cuda"))
>>> window_gpu.device
device(type='cuda', index=0)
to_dense(dtype=None)

Convert to dense tensor.

This method replaces the pattern: arr.flatten()[idx] = val

Parameters:

dtype (dtype | None) – Dtype for output tensor. If None, uses self.values.dtype.

Returns:

Dense tensor representation of the sparse window.

Return type:

Tensor

Examples

>>> import torch
>>> from curvelets.torch._sparse_window import SparseWindow
>>> window = SparseWindow.from_dense(torch.tensor([0.1, 0.9, 0.2]), threshold=0.5)
>>> dense = window.to_dense()
>>> dense[1]  # Only index 1 is above threshold
tensor(0.9000)
values: Tensor
class curvelets.torch.UDCT(shape, angular_wedges_config=None, num_scales=None, wedges_per_direction=None, window_overlap=None, radial_frequency_params=None, window_threshold=1e-05, high_frequency_mode='curvelet', transform_kind='real', dtype=None, cuda_graphs=False)

Bases: CudaGraphsMixin, Module

Uniform Discrete Curvelet Transform (UDCT) implementation.

Forward and backward curvelet transforms (real, complex or monogenic) as a torch.nn.Module with no learnable parameters. Calling the module (udct(x)) is forward(); forward(x, structured=False) and backward() of a flat tensor work on the vect() layout instead of nested lists, which suits networks and optimizers.

Gradients of every transform come from the adjoint transform: the UDCT is a tight frame, so the gradient of the forward transform is the backward transform and vice versa, with no autograd graph through the computation. Second derivatives, torch.func transforms and torch.compile are supported. .to(device), .cuda(), .double() and .float() move or recast the windows; they are not buffers, so state_dict() stays empty (they are rebuilt from the constructor arguments).

Changed in version 1.3: UDCT is a torch.nn.Module, and its gradients come from the adjoint transform in both layouts. It replaces the deprecated UDCTModule.

Changed in version 1.3: Every transform accepts leading batch dimensions, so torch.vmap() is no longer needed.

Changed in version 1.3: The transform has a fixed precision (dtype). Inputs and coefficients of another precision raise a TypeError instead of being cast.

Parameters:
  • shape (tuple[int, ...]) – Shape of the input data.

  • angular_wedges_config (Tensor | None) – Configuration tensor specifying the number of angular wedges per scale and dimension. Shape is (num_scales - 1, dimension), where num_scales includes the lowpass scale. If provided, cannot be used together with num_scales/wedges_per_direction. Default is None.

  • num_scales (int | None) – Total number of scales (including lowpass scale 0). Must be >= 2. Used when angular_wedges_config is not provided. Default is 3.

  • wedges_per_direction (int | None) – Number of angular wedges per direction at the coarsest scale. The number of wedges doubles at each finer scale. Must be >= 3. Used when angular_wedges_config is not provided. Default is 3.

  • window_overlap (float | None) –

    Window overlap parameter \(\alpha\) controlling the smoothness of window transitions. If None, automatically chosen as 10% of the Nguyen & Chauris (2010) upper bound, capped at \(1/16\) (0.0625). With the default radial_frequency_params, a wedge at scale \(s\) spans \(\frac{8}{9}(1 + 2\alpha)\) decimated bins along the transverse axis, so its periodized fold stays injective (aliasing-free) iff \(\alpha \le 1/16\), independent of shape, scales, and wedge count. Passing a larger value logs a warning when aliasing occurs. Default is None (auto).

    Changed in version 1.3: Auto-selected window_overlap is now capped at \(1/16\) so wedges_per_direction >= 6 reconstructs to machine precision, and explicit overlaps that alias log a warning.

  • radial_frequency_params (tuple[float, float, float, float] | None) – Radial frequency parameters defining the frequency bands. Default is (\(\pi/3\), \(2\pi/3\), \(2\pi/3\), \(4\pi/3\)).

  • window_threshold (float) – Threshold for sparse window storage (values below this are stored as sparse). Default is 1e-5.

  • high_frequency_mode (Literal['curvelet', 'wavelet']) – High frequency mode. “curvelet” uses curvelets at all scales, “wavelet” creates a single ring-shaped window (bandpass filter only, no angular components) at the highest scale with decimation=1. Default is “curvelet”.

  • transform_kind (Literal['real', 'complex', 'monogenic']) –

    Type of transform to use:

    • ”real” (default): Real transform where each band captures both positive and negative frequencies combined.

    • ”complex”: Complex transform which separates positive and negative frequency components into different bands. Each band is scaled by \(\sqrt{0.5}\).

    • ”monogenic”: Monogenic transform that extends the curvelet transform by applying Riesz transforms. Each band has ndim+2 real channels along its last axis: the complex scalar coefficient (real and imaginary parts) and one Riesz component per dimension. The backward transform returns ndim + 1 components stacked along a new first axis: \(f\), then approximations of \(-R_k f\) (see backward()). The results match curvelets.numpy.UDCT.

    Changed in version 1.3: "monogenic" is implemented (it raised NotImplementedError before).

  • dtype (dtype | None) –

    Precision of the transform: torch.float32 or torch.float64 (torch.complex64 / torch.complex128 are accepted and mean the same precision). The windows are computed in double precision and stored once in this dtype. Inputs must have this precision (or its complex counterpart for the complex transform), and coefficients come out as coefficient_dtype. Default is torch.get_default_dtype() (normally torch.float32).

    Added in version 1.3.

  • cuda_graphs (bool) –

    Replay the transforms on CUDA from CUDA graphs: one launch per call instead of a few dozen, captured on the first call for each input shape and dtype (the last cuda_graph_cache_size are kept). Covers every forward/backward entry point, filter() and gradients (through the adjoint transform). Worthwhile for small and medium inputs, where launches dominate (a 512² transform gets ~6x faster on an RTX 4090); slower for large inputs, where copying in and out of the graph buffers costs more. Default is False.

    Added in version 1.3.

dtype

Real precision of the transform.

Type:

torch.dtype

cuda_graphs

Whether CUDA calls replay CUDA graphs (can be switched at any time).

Type:

bool

cuda_graph_cache_size

Number of captured graphs kept (least recently used dropped first).

Type:

int

coefficient_dtype

Dtype of the coefficients (complex for the real and complex transforms, real for the monogenic transform).

Type:

torch.dtype

high_frequency_mode

High frequency mode.

Type:

str

transform_kind

Type of transform being used (“real”, “complex”, or “monogenic”).

Type:

str

Examples

>>> import torch
>>> from curvelets.torch import UDCT
>>> # Create a 2D transform using num_scales (simplified interface)
>>> transform = UDCT(shape=(64, 64), num_scales=3, wedges_per_direction=3)
>>> data = torch.randn(64, 64)
>>> coeffs = transform.forward(data)
>>> recon = transform.backward(coeffs)
>>> torch.allclose(data, recon, atol=1e-4)
True
>>> # Create using angular_wedges_config (advanced interface)
>>> cfg = torch.tensor([[3, 3], [6, 6]], dtype=torch.int64)
>>> transform2 = UDCT(shape=(64, 64), angular_wedges_config=cfg)
>>> coeffs2 = transform2.forward(data)
>>> recon2 = transform2.backward(coeffs2)
>>> torch.allclose(data, recon2, atol=1e-4)
True
>>> # Flat coefficients and gradients, e.g. inside a network
>>> x = torch.randn(4, 64, 64, requires_grad=True)
>>> features = transform.forward(x, structured=False)  # shape (4, ncoef)
>>> features.abs().pow(2).sum().backward()
>>> x.grad.shape
torch.Size([4, 64, 64])
apply_to_tensors(fn)

Apply a function to all internal tensors.

Called by .to(), .cuda(), .double() and the like (prefer those). It applies the given function to all internal tensor attributes including windows and decimation ratios. If fn changes the floating-point dtype of the windows, dtype follows it; a complex target dtype (e.g. udct.to(torch.complex64)) sets the matching real precision.

Changed in version 1.3: Dtype changes set the transform’s precision, and the periodized index maps are kept instead of recomputed.

Parameters:

fn (Callable[[Tensor], Tensor]) – Function to apply to each tensor. Typically this is a function like lambda t: t.cuda() or lambda t: t.to(device).

Return type:

None

Examples

>>> import torch
>>> from curvelets.torch import UDCT
>>> transform = UDCT(shape=(64, 64), num_scales=3, wedges_per_direction=3)
>>> # Move all internal tensors to GPU (if available)
>>> if torch.cuda.is_available():
...     transform.apply_to_tensors(lambda t: t.cuda())
backward(coefficients)

Apply backward (inverse) curvelet transform.

Changed in version 1.3: Leading batch dimensions are supported, and the flat tensor of forward(x, structured=False) is accepted.

Parameters:

coefficients (list[list[list[Tensor]]] | Tensor) – Curvelet coefficients from forward transform, each of shape (*batch, *wedge_shape), or the flat tensor of shape (*batch, ncoef) from forward(x, structured=False) or vect().

Returns:

Reconstruction of shape (*batch, *self.shape). For the monogenic transform, a real tensor of shape (ndim + 1, *batch, *self.shape): the components that curvelets.numpy.UDCT returns as a tuple, stacked along a new first axis (so f, *riesz = udct.backward(coeffs) works as in numpy). The first is the reconstruction of \(f\); the others are the synthesis of each Riesz channel, which approximates \(-R_k f\) (see monogenic() for the exact values). As in numpy, each Riesz channel only keeps the real part of its coefficients, so these components are not exact.

Return type:

Tensor

backward_vect(vector)

Deprecated alias of backward(vector).

Deprecated since version 1.3: backward() accepts the flat tensor directly.

Parameters:

vector (Tensor)

Return type:

Tensor

property coefficient_dtype: dtype

complex, or real for the monogenic transform.

Added in version 1.3.

Type:

Dtype of the coefficients

coefficient_shapes()

Calculate shapes of all curvelet-domain coefficient arrays.

Computes the expected shape of every coefficient wedge across all scales, directions, and angular wedges without executing a forward transform.

Returns:

Nested list containing the shape of each coefficient wedge. Structure is shapes[scale_idx][direction_idx][wedge_idx]. For monogenic transforms, each shape includes the channel dimension as the last axis (*wedge_shape, ndim + 2).

Return type:

list[list[list[tuple[int, ...]]]]

Examples

>>> from curvelets.torch import UDCT
>>> transform = UDCT(shape=(64, 64), num_scales=3)
>>> shapes = transform.coefficient_shapes()
>>> len(shapes) == transform.num_scales
True
>>> shapes[0][0][0]  # Low-frequency band shape (decimated by 2)
(32, 32)
property decimation_ratios: list[Tensor]

Decimation ratios for each scale.

property dtype: dtype

Real precision of the transform (follows .to(dtype)).

Added in version 1.3.

filter(image, fn)

Forward transform, apply fn to the coefficients, backward transform.

The coefficients reach fn as one tensor of shape (*batch, ncoef) in vect() order (use struct() inside fn for per-wedge access), and never go through the nested list representation.

Added in version 1.3.

Parameters:
  • image (Tensor) – Input of shape (*batch, *self.shape).

  • fn (Callable[[Tensor], Tensor]) – Map from flattened coefficients to flattened coefficients of the same shape, e.g. a thresholding function.

Returns:

Filtered result of shape (*batch, *self.shape); for the monogenic transform, (ndim + 1, *batch, *self.shape) (see backward()).

Return type:

Tensor

Examples

>>> import torch
>>> from curvelets.torch import UDCT
>>> transform = UDCT(shape=(32, 32), num_scales=3, wedges_per_direction=3)
>>> noisy = torch.randn(4, 32, 32)
>>> def hard_threshold(c):
...     return c * (c.abs() > 0.5)
>>> transform.filter(noisy, hard_threshold).shape
torch.Size([4, 32, 32])
forward(image, structured=True)

Apply forward curvelet transform.

Overloads:

Changed in version 1.3: Leading batch dimensions are supported, and structured=False returns the flat vect() layout directly.

Parameters:
  • image (Tensor) –

    Input of shape (*batch, *self.shape): any number of leading batch dimensions (none for a single image) followed by the transform shape.

    • For transform_kind=”real” or “monogenic”: must be real-valued

    • For transform_kind=”complex”: can be real-valued or complex-valued

  • structured (bool) –

    If True, return the nested coefficients. If False, return the flat tensor that vect() would produce, without building the nested list (forward(x, structured=False) equals vect(forward(x))); backward() accepts it as is.

    Added in version 1.3.

Returns:

With structured=False, a tensor of shape (*batch, ncoef). Otherwise curvelet coefficients organized by scale, direction, and wedge, each of shape (*batch, *wedge_shape). For monogenic transforms, each coefficient tensor is real with shape (*batch, *wedge_shape, ndim+2), channels [scalar.real, scalar.imag, riesz_1, ..., riesz_ndim] along the last axis.

Return type:

UDCTCoefficients | torch.Tensor

Examples

>>> import torch
>>> from curvelets.torch import UDCT
>>> transform = UDCT(shape=(32, 32), num_scales=3, wedges_per_direction=3)
>>> batch = torch.randn(8, 32, 32)
>>> coeffs = transform.forward(batch)
>>> coeffs[0][0][0].shape[0]
8
>>> transform.backward(coeffs).shape
torch.Size([8, 32, 32])
>>> flat = transform.forward(batch, structured=False)
>>> torch.allclose(flat, transform.vect(coeffs))
True
forward_vect(image)

Deprecated alias of forward(image, structured=False).

Deprecated since version 1.3: Use forward(image, structured=False).

Parameters:

image (Tensor)

Return type:

Tensor

monogenic(image)

Compute the monogenic signal directly, without the curvelet transform.

Returns \((f, -R_1 f, \ldots, -R_n f)\), where \(R_k\) are the Riesz transforms, computed exactly in the Fourier domain. Available for every transform_kind.

Added in version 1.3.

Parameters:

image (Tensor) – Real input of shape (*batch, *self.shape) and precision dtype.

Returns:

Real tensor of shape (ndim + 1, *batch, *self.shape): image, then \(-R_k f\) for each dimension (the tuple that curvelets.numpy.UDCT.monogenic() returns, stacked along a new first axis).

Return type:

Tensor

Examples

>>> import torch
>>> from curvelets.torch import UDCT
>>> transform = UDCT(shape=(64, 64), transform_kind="monogenic")
>>> data = torch.randn(64, 64)
>>> scalar, riesz1, riesz2 = transform.monogenic(data)  # shape (3, 64, 64)
>>> torch.equal(scalar, data)
True
>>> recon = transform.backward(transform.forward(data))
>>> torch.allclose(recon[0], data, atol=1e-4)
True
property ndim: int

Number of dimensions.

property num_scales: int

Number of scales.

save_plan(path)

Save this transform’s execution plan for Python-free C++ libtorch.

The saved .pt file can be loaded directly with curvelets::UDCT in C++ without requiring Python.

Added in version 1.4.

Parameters:

path (str | Path) – Destination path for the serialized plan (.pt).

Returns:

Resolved path to the written plan file.

Return type:

Path

property shape: tuple[int, ...]

Shape of the transform.

struct(vector)

Restructure vectorized coefficients to nested list format.

Changed in version 1.3: Leading batch dimensions are supported, and the wedges are views into vector in its dtype (previously the dtype of the last forward call).

Parameters:

vector (Tensor) – Coefficients of shape (*batch, ncoef).

Returns:

Restructured coefficients, each of shape (*batch, *wedge_shape) ((*batch, *wedge_shape, ndim + 2) for the monogenic transform), as views into vector (same dtype).

Return type:

list[list[list[Tensor]]]

Examples

>>> import torch
>>> from curvelets.torch import UDCT
>>> transform = UDCT(shape=(64, 64), angular_wedges_config=torch.tensor([[3, 3]]))
>>> data = torch.randn(64, 64)
>>> coeffs = transform.forward(data)
>>> vec = transform.vect(coeffs)
>>> coeffs_recon = transform.struct(vec)
>>> len(coeffs_recon) == len(coeffs)
True
vect(coefficients)

Vectorize curvelet coefficients.

Changed in version 1.3: Coefficients with leading batch dimensions are supported.

Parameters:

coefficients (list[list[list[Tensor]]]) – Curvelet coefficients.

Returns:

Tensor of shape (*batch, ncoef) containing all coefficients, where batch are the leading dimensions of the coefficients (1D for unbatched coefficients).

Return type:

Tensor

property windows: list[list[list[Any]]]

Curvelet windows in sparse format.

class curvelets.torch.UDCTModule(*args, transform_type='real', **kwargs)

Bases: UDCT

Deprecated: use UDCT, which is a torch.nn.Module.

Deprecated since version 1.3: UDCT now is an nn.Module with adjoint gradients. UDCTModule(shape, ..., transform_type=kind) returned flat coefficients from __call__; the replacement is UDCT(shape, ..., transform_kind=kind).forward(x, structured=False) (or udct(x) for nested coefficients). UDCTModule will be removed in a future release.

Parameters are those of UDCT, with transform_type ("real" or "complex") in place of transform_kind. Calling the module returns flattened coefficients of shape (*batch, ncoef).

Parameters:
  • args (Any)

  • transform_type (Literal['real', 'complex'])

  • kwargs (Any)

forward(image)

Flattened coefficients of shape (*batch, ncoef).

Parameters:

image (Tensor)

Return type:

Tensor

Submodules

curvelets.torch.typing module

Type definitions for PyTorch UDCT implementation.

This module provides type aliases for UDCT coefficients and windows.

Public Types

UDCTCoefficients

Type alias for UDCT coefficient structure.

UDCTWindows

Type alias for UDCT window structure.