1use crate::chirp::ChirpZ;
13use crate::field::{Fp, P};
14use crate::ntt::Ntt;
15
16const ODD_PRIMES: [u64; 5] = [3, 5, 17, 257, 65537];
17
18pub fn is_supported_len(n: usize) -> bool {
20 n > 0 && (P - 1) % n as u64 == 0
21}
22
23#[derive(Clone, Debug)]
24enum Axis {
25 Trivial,
26 Ntt(Ntt),
27 Direct(Vec<Fp>, usize),
29 Chirp(ChirpZ),
30}
31
32impl Axis {
33 fn new(len: usize, root: Fp) -> Self {
34 if len == 1 {
35 Axis::Trivial
36 } else if len.is_power_of_two() {
37 Axis::Ntt(Ntt::with_root(len, root))
38 } else if len <= 17 {
39 let mut m = Vec::with_capacity(len * len);
40 for j in 0..len {
41 let wj = root.pow(j as u64);
42 let mut w = Fp::ONE;
43 for _ in 0..len {
44 m.push(w);
45 w *= wj;
46 }
47 }
48 Axis::Direct(m, len)
49 } else {
50 Axis::Chirp(ChirpZ::new(len, len, root))
51 }
52 }
53
54 fn apply(&self, buf: &mut [Fp], tmp: &mut [Fp]) {
55 match self {
56 Axis::Trivial => {}
57 Axis::Ntt(p) => p.forward(buf),
58 Axis::Direct(m, q) => {
59 for k in 0..*q {
60 let row = &m[k * q..(k + 1) * q];
61 tmp[k] = row.iter().zip(buf.iter()).fold(Fp::ZERO, |s, (a, b)| s + *a * *b);
62 }
63 buf.copy_from_slice(&tmp[..*q]);
64 }
65 Axis::Chirp(c) => {
66 let y = c.apply(buf);
67 buf.copy_from_slice(&y);
68 }
69 }
70 }
71}
72
73fn apply_axes(data: &mut [Fp], dims: &[usize], axes: &[Axis]) {
75 let max = dims.iter().copied().max().unwrap_or(1);
76 let mut fibre = vec![Fp::ZERO; max];
77 let mut tmp = vec![Fp::ZERO; max];
78 let mut stride = 1;
79 for ax in (0..dims.len()).rev() {
80 let a = dims[ax];
81 if a > 1 {
82 let block = a * stride;
83 for base in (0..data.len()).step_by(block) {
84 for off in 0..stride {
85 let start = base + off;
86 if stride == 1 {
87 axes[ax].apply(&mut data[start..start + a], &mut tmp);
88 } else {
89 for k in 0..a {
90 fibre[k] = data[start + k * stride];
91 }
92 axes[ax].apply(&mut fibre[..a], &mut tmp);
93 for k in 0..a {
94 data[start + k * stride] = fibre[k];
95 }
96 }
97 }
98 }
99 }
100 stride *= a;
101 }
102}
103
104#[derive(Clone, Debug)]
106pub struct Dft {
107 n: usize,
108 factors: Vec<usize>,
109 axes: Vec<Axis>,
110 in_map: Vec<u32>,
112 out_map: Vec<u32>,
114 inv_n: Fp,
115}
116
117impl Dft {
118 pub fn new(n: usize) -> Self {
121 assert!(is_supported_len(n), "no primitive {n}-th root of unity in F_p (n must divide p-1)");
122 let mut factors = Vec::new();
123 let two = 1usize << n.trailing_zeros();
124 if two > 1 {
125 factors.push(two);
126 }
127 let mut rest = n / two;
128 for &q in &ODD_PRIMES {
129 if rest as u64 % q == 0 {
130 factors.push(q as usize);
131 rest /= q as usize;
132 }
133 }
134 debug_assert_eq!(rest, 1);
135 let omega = Fp::root_of_unity(n as u64);
136 let axes = factors.iter().map(|&f| Axis::new(f, omega.pow((n / f) as u64))).collect();
138
139 let coef_in: Vec<u64> = factors.iter().map(|&f| (n / f) as u64).collect();
141 let coef_out: Vec<u64> = factors
142 .iter()
143 .map(|&f| {
144 let m = (n / f) as u64;
145 m * inv_mod(m % f as u64, f as u64) % n as u64
146 })
147 .collect();
148 let mut in_map = vec![0u32; n];
149 let mut out_map = vec![0u32; n];
150 let mut digits = vec![0usize; factors.len()];
151 for pos in 0..n {
152 let (mut a, mut b) = (0u64, 0u64);
153 for (i, &d) in digits.iter().enumerate() {
154 a = (a + d as u64 * coef_in[i]) % n as u64;
155 b = (b + d as u64 * coef_out[i]) % n as u64;
156 }
157 in_map[pos] = a as u32;
158 out_map[pos] = b as u32;
159 for i in (0..factors.len()).rev() {
161 digits[i] += 1;
162 if digits[i] < factors[i] {
163 break;
164 }
165 digits[i] = 0;
166 }
167 }
168 Dft { n, factors, axes, in_map, out_map, inv_n: Fp::new(n as u64).inv() }
169 }
170
171 pub fn len(&self) -> usize {
172 self.n
173 }
174
175 pub fn is_empty(&self) -> bool {
176 self.n == 0
177 }
178
179 pub fn factors(&self) -> &[usize] {
181 &self.factors
182 }
183
184 pub fn forward(&self, x: &[Fp]) -> Vec<Fp> {
186 assert_eq!(x.len(), self.n, "input length mismatch");
187 if self.factors.len() == 1 {
188 let mut y = x.to_vec();
189 apply_axes(&mut y, &self.factors, &self.axes);
190 return y;
191 }
192 let mut grid: Vec<Fp> = self.in_map.iter().map(|&i| x[i as usize]).collect();
193 apply_axes(&mut grid, &self.factors, &self.axes);
194 let mut y = vec![Fp::ZERO; self.n];
195 for (g, &o) in grid.iter().zip(&self.out_map) {
196 y[o as usize] = *g;
197 }
198 y
199 }
200
201 pub fn inverse(&self, y: &[Fp]) -> Vec<Fp> {
203 let f = self.forward(y);
205 let n = self.n;
206 (0..n).map(|j| f[(n - j) % n] * self.inv_n).collect()
207 }
208}
209
210fn inv_mod(a: u64, m: u64) -> u64 {
211 if m == 1 {
212 return 0;
213 }
214 let (mut r0, mut r1) = (a as i128, m as i128);
216 let (mut s0, mut s1) = (1i128, 0i128);
217 while r1 != 0 {
218 let q = r0 / r1;
219 (r0, r1) = (r1, r0 - q * r1);
220 (s0, s1) = (s1, s0 - q * s1);
221 }
222 assert_eq!(r0, 1, "not coprime");
223 s0.rem_euclid(m as i128) as u64
224}
225
226#[derive(Clone, Debug)]
229pub struct GroupDft {
230 dims: Vec<usize>,
231 plans: Vec<Dft>,
232}
233
234impl GroupDft {
235 pub fn new(dims: &[usize]) -> Self {
238 GroupDft { dims: dims.to_vec(), plans: dims.iter().map(|&a| Dft::new(a)).collect() }
239 }
240
241 pub fn dims(&self) -> &[usize] {
242 &self.dims
243 }
244
245 pub fn len(&self) -> usize {
246 self.dims.iter().product()
247 }
248
249 pub fn is_empty(&self) -> bool {
250 self.len() == 0
251 }
252
253 fn run(&self, x: &[Fp], inverse: bool) -> Vec<Fp> {
254 assert_eq!(x.len(), self.len(), "input length mismatch");
255 let mut data = x.to_vec();
256 let mut stride = 1;
257 let mut fibre = Vec::new();
258 for ax in (0..self.dims.len()).rev() {
259 let a = self.dims[ax];
260 let plan = &self.plans[ax];
261 fibre.resize(a, Fp::ZERO);
262 for base in (0..data.len()).step_by(a * stride) {
263 for off in 0..stride {
264 for k in 0..a {
265 fibre[k] = data[base + off + k * stride];
266 }
267 let out = if inverse { plan.inverse(&fibre) } else { plan.forward(&fibre) };
268 for k in 0..a {
269 data[base + off + k * stride] = out[k];
270 }
271 }
272 }
273 stride *= a;
274 }
275 data
276 }
277
278 pub fn forward(&self, x: &[Fp]) -> Vec<Fp> {
279 self.run(x, false)
280 }
281
282 pub fn inverse(&self, x: &[Fp]) -> Vec<Fp> {
283 self.run(x, true)
284 }
285}