Skip to main content

tenferro_fft/
spec.rs

1use tenferro_tensor::DType;
2
3/// FFT normalization convention.
4///
5/// `Backward` matches NumPy, JAX, and PyTorch defaults: the forward transform
6/// is unscaled and the inverse transform is scaled by `1 / n`.
7///
8/// # Examples
9///
10/// ```
11/// use tenferro_fft::FftNorm;
12///
13/// assert_eq!(FftNorm::default(), FftNorm::Backward);
14/// ```
15#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
16pub enum FftNorm {
17    /// Scale inverse transforms by `1 / n`.
18    #[default]
19    Backward,
20    /// Scale forward transforms by `1 / n`.
21    Forward,
22    /// Scale both forward and inverse transforms by `1 / sqrt(n)`.
23    Ortho,
24}
25
26impl FftNorm {
27    #[cfg(feature = "autodiff")]
28    pub(crate) fn c2c_adjoint(self) -> Self {
29        match self {
30            Self::Backward => Self::Forward,
31            Self::Forward => Self::Backward,
32            Self::Ortho => Self::Ortho,
33        }
34    }
35}
36
37/// One-dimensional FFT operation requested from an [`FftBackend`](crate::FftBackend).
38///
39/// # Examples
40///
41/// ```
42/// use tenferro_fft::FftOperation;
43///
44/// assert_ne!(FftOperation::C2cForward, FftOperation::C2cInverse);
45/// assert_ne!(FftOperation::R2cFull, FftOperation::R2cOnesided);
46/// ```
47#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
48pub enum FftOperation {
49    /// Forward complex-to-complex FFT.
50    C2cForward,
51    /// Inverse complex-to-complex FFT.
52    C2cInverse,
53    /// Real-to-complex FFT returning the full complex spectrum.
54    R2cFull,
55    /// Real-to-complex FFT returning the non-negative-frequency spectrum.
56    R2cOnesided,
57    /// Complex-to-real FFT consuming a one-sided Hermitian spectrum.
58    C2r,
59}
60
61impl FftOperation {
62    #[cfg(feature = "autodiff")]
63    pub(crate) const fn is_c2c(self) -> bool {
64        matches!(self, Self::C2cForward | Self::C2cInverse)
65    }
66
67    pub(crate) const fn is_forward(self) -> bool {
68        matches!(self, Self::C2cForward | Self::R2cFull | Self::R2cOnesided)
69    }
70
71    pub(crate) const fn is_onesided(self) -> bool {
72        matches!(self, Self::R2cOnesided)
73    }
74
75    /// Return the operation of the `index`-th declared axis of a `count`-axis request.
76    ///
77    /// `count == 1` returns `self`, so a one-axis request is exactly the
78    /// historical one-dimensional transform. For the mixed real transforms the
79    /// last declared axis carries the real transform while every other axis is
80    /// complex, which is the NumPy `rfftn`/`irfftn` convention.
81    pub(crate) const fn step_operation(self, index: usize, count: usize) -> Self {
82        if index + 1 < count {
83            match self {
84                Self::R2cFull | Self::R2cOnesided => Self::C2cForward,
85                Self::C2r => Self::C2cInverse,
86                Self::C2cForward | Self::C2cInverse => self,
87            }
88        } else {
89            self
90        }
91    }
92}
93
94/// Validated, backend-neutral description of one FFT request over one or more axes.
95///
96/// Backends receive this value only after the public FFT surface has validated
97/// dtype, rank, axes, requested lengths, and inverse-spectrum shape. The layout
98/// requirement is explicit so a backend can reject unsupported storage without
99/// silently materializing or transferring the input.
100///
101/// A spec carries one or more axes. The n-dimensional executor splits a
102/// multi-axis request into one single-axis spec per axis, so every spec a
103/// backend actually executes names exactly one axis; [`Self::axes`] stays
104/// useful for tests and diagnostics. Axis order is significant only for the
105/// mixed real transforms, whose real transform is the last declared axis.
106///
107/// # Examples
108///
109/// ```
110/// use tenferro_fft::{FftOperation, FftPlanSpec};
111///
112/// fn inspect(spec: &FftPlanSpec) {
113///     let operation: FftOperation = spec.operation();
114///     assert_eq!(operation, spec.operation());
115///     assert!(spec.requires_compact_column_major());
116///     assert!(!spec.axes().is_empty());
117/// }
118/// ```
119#[derive(Clone, Debug, Eq, PartialEq)]
120pub struct FftPlanSpec {
121    operation: FftOperation,
122    axes: Vec<usize>,
123    lengths: Option<Vec<usize>>,
124    norm: FftNorm,
125    input_dtype: DType,
126    input_shape: Vec<usize>,
127    requires_compact_column_major: bool,
128}
129
130impl FftPlanSpec {
131    /// Build a spec from already-validated axes and per-axis lengths.
132    ///
133    /// `axes` must be non-empty and `lengths`, when present, must match its
134    /// length. Every public constructor validates that before reaching here.
135    pub(crate) fn new(
136        operation: FftOperation,
137        axes: Vec<usize>,
138        lengths: Option<Vec<usize>>,
139        norm: FftNorm,
140        input_dtype: DType,
141        input_shape: Vec<usize>,
142    ) -> Self {
143        debug_assert!(!axes.is_empty(), "an FFT spec names at least one axis");
144        debug_assert!(
145            lengths
146                .as_ref()
147                .is_none_or(|lengths| lengths.len() == axes.len()),
148            "one requested length per axis"
149        );
150        Self {
151            operation,
152            axes,
153            lengths,
154            norm,
155            input_dtype,
156            input_shape,
157            requires_compact_column_major: true,
158        }
159    }
160
161    /// Return the transform operation of the last declared axis.
162    pub const fn operation(&self) -> FftOperation {
163        self.operation
164    }
165
166    /// Return every validated axis of this request.
167    pub fn axes(&self) -> &[usize] {
168        &self.axes
169    }
170
171    /// Return the caller-requested transform length of every axis, if supplied.
172    pub fn lengths(&self) -> Option<&[usize]> {
173        self.lengths.as_deref()
174    }
175
176    /// Return the non-negative, validated axis executed by a backend.
177    ///
178    /// Multi-axis requests are expanded into one single-axis spec per axis
179    /// before a backend sees them, so this is the axis of the step to run now.
180    pub fn normalized_axis(&self) -> usize {
181        // INVARIANT: `new` requires a non-empty axis list.
182        self.axes[0]
183    }
184
185    /// Return the caller-requested transform length of the executed step.
186    pub fn requested_len(&self) -> Option<usize> {
187        self.lengths.as_ref().map(|lengths| lengths[0])
188    }
189
190    /// Return the requested normalization convention.
191    pub const fn norm(&self) -> FftNorm {
192        self.norm
193    }
194
195    /// Return the validated input dtype.
196    pub const fn input_dtype(&self) -> DType {
197        self.input_dtype
198    }
199
200    /// Return the validated input shape.
201    pub fn input_shape(&self) -> &[usize] {
202        &self.input_shape
203    }
204
205    /// Return whether execution requires compact column-major storage.
206    pub const fn requires_compact_column_major(&self) -> bool {
207        self.requires_compact_column_major
208    }
209}