Skip to main content

hekate_core/poly/
variant.rs

1// SPDX-FileCopyrightText: 2026 Andrei Kochergin <andrei@oumuamua.dev>
2// SPDX-FileCopyrightText: 2026 Oumuamua Labs <info@oumuamua.dev>
3// SPDX-License-Identifier: AGPL-3.0-only
4
5use crate::errors;
6use crate::tensor::TensorProduct;
7use crate::trace::TraceCompatibleField;
8use alloc::vec;
9use alloc::vec::Vec;
10use core::fmt;
11use hekate_math::{Bit, Block8, Block16, Block32, Block64, Block128, Flat};
12use zeroize::Zeroize;
13
14/// Failures raised by `PolyVariant` operations.
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16pub enum Error {
17    /// `1 << num_vars` overflowed `usize`.
18    DomainTooLarge { num_vars: usize },
19
20    /// Polynomial length disagrees with `2^num_vars`.
21    DomainSizeMismatch { expected_len: usize, got_len: usize },
22
23    /// Evaluation point has the
24    /// wrong number of coordinates.
25    PointDimensionMismatch { expected_len: usize, got_len: usize },
26
27    /// Variant is read-only at fold time.
28    UnsupportedFold { kind: &'static str },
29}
30
31impl fmt::Display for Error {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        match self {
34            Self::DomainTooLarge { num_vars } => {
35                write!(
36                    f,
37                    "Virtual polynomial domain too large: num_vars={num_vars}"
38                )
39            }
40            Self::DomainSizeMismatch {
41                expected_len,
42                got_len,
43            } => write!(
44                f,
45                "Virtual polynomial domain size mismatch: expected {expected_len}, got {got_len}",
46            ),
47            Self::PointDimensionMismatch {
48                expected_len,
49                got_len,
50            } => write!(
51                f,
52                "Virtual polynomial point dimension mismatch: expected {expected_len}, got {got_len}",
53            ),
54            Self::UnsupportedFold { kind } => {
55                write!(
56                    f,
57                    "Virtual polynomial cannot be folded lazily for kind: {kind}"
58                )
59            }
60        }
61    }
62}
63
64/// Zero-copy MLE view over a physical trace column.
65/// Every variant must deliver `get_at(i)` without
66/// heap allocation, the hot path inside Sumcheck.
67#[derive(Clone, Debug, Zeroize)]
68pub enum PolyVariant<'a, F>
69where
70    F: TraceCompatibleField,
71{
72    /// Fully materialized hypercube.
73    #[zeroize(skip)]
74    Dense(&'a [Flat<F>]),
75
76    #[zeroize(skip)]
77    Shifted(&'a [Flat<F>]),
78
79    /// `Eq(x, r)` held lazily as a `TensorProduct`:
80    /// `O(num_vars)` memory, `O(1)` fold.
81    Eq(TensorProduct<F>),
82
83    /// `(data[i] >> bit_idx) & 1` on a `B8` column.
84    #[zeroize(skip)]
85    PackedBitB8 {
86        data: &'a [Flat<Block8>],
87        bit_idx: usize,
88    },
89
90    /// `(data[i] >> bit_idx) & 1` on a `B16` column.
91    #[zeroize(skip)]
92    PackedBitB16 {
93        data: &'a [Flat<Block16>],
94        bit_idx: usize,
95    },
96
97    /// `(data[i] >> bit_idx) & 1` on a `B32` column.
98    #[zeroize(skip)]
99    PackedBitB32 {
100        data: &'a [Flat<Block32>],
101        bit_idx: usize,
102    },
103
104    /// `(data[i] >> bit_idx) & 1` on a `B64` column.
105    #[zeroize(skip)]
106    PackedBitB64 {
107        data: &'a [Flat<Block64>],
108        bit_idx: usize,
109    },
110
111    /// `S(i) = Σ_k cols[k][i]` over boolean
112    /// columns (one-hot selector groups).
113    #[zeroize(skip)]
114    CompositeSelector(Vec<&'a [Bit]>),
115
116    /// Mask that is `1` everywhere and
117    /// `1 - product_of_challenges` at
118    /// index `2^N - 1`. Used to kill
119    /// cross-row wrap in Sumcheck.
120    #[zeroize(skip)]
121    TransitionMask {
122        num_vars: usize,
123        product_of_challenges: F,
124    },
125
126    // ==============================================================
127    // Indirect:
128    // P(x) = data[indices[x]].
129    // Zero-copy permutations and arbitrary wiring.
130    // ==============================================================
131    #[zeroize(skip)]
132    IndirectBit {
133        data: &'a [Bit],
134        indices: &'a [usize],
135    },
136    #[zeroize(skip)]
137    IndirectB8 {
138        data: &'a [Flat<Block8>],
139        indices: &'a [usize],
140    },
141    #[zeroize(skip)]
142    IndirectB16 {
143        data: &'a [Flat<Block16>],
144        indices: &'a [usize],
145    },
146    #[zeroize(skip)]
147    IndirectB32 {
148        data: &'a [Flat<Block32>],
149        indices: &'a [usize],
150    },
151    #[zeroize(skip)]
152    IndirectB64 {
153        data: &'a [Flat<Block64>],
154        indices: &'a [usize],
155    },
156    #[zeroize(skip)]
157    IndirectB128 {
158        data: &'a [Flat<Block128>],
159        indices: &'a [usize],
160    },
161
162    // ====================================================
163    // Stride Access:
164    // P(i) = data[start + i * step].
165    // ====================================================
166    #[zeroize(skip)]
167    StrideBit {
168        data: &'a [Bit],
169        start: usize,
170        step: usize,
171        len: usize,
172    },
173    #[zeroize(skip)]
174    StrideB8 {
175        data: &'a [Flat<Block8>],
176        start: usize,
177        step: usize,
178        len: usize,
179    },
180    #[zeroize(skip)]
181    StrideB16 {
182        data: &'a [Flat<Block16>],
183        start: usize,
184        step: usize,
185        len: usize,
186    },
187    #[zeroize(skip)]
188    StrideB32 {
189        data: &'a [Flat<Block32>],
190        start: usize,
191        step: usize,
192        len: usize,
193    },
194    #[zeroize(skip)]
195    StrideB64 {
196        data: &'a [Flat<Block64>],
197        start: usize,
198        step: usize,
199        len: usize,
200    },
201    #[zeroize(skip)]
202    StrideB128 {
203        data: &'a [Flat<Block128>],
204        start: usize,
205        step: usize,
206        len: usize,
207    },
208
209    // ====================================================
210    // Cyclic Rotation:
211    // P(i) = data[(i + rotation) % len].
212    // Uses bitwise masking for modulo (len must be power of 2).
213    // ====================================================
214    #[zeroize(skip)]
215    RotationBit { data: &'a [Bit], rotation: usize },
216    #[zeroize(skip)]
217    RotationB8 {
218        data: &'a [Flat<Block8>],
219        rotation: usize,
220    },
221    #[zeroize(skip)]
222    RotationB16 {
223        data: &'a [Flat<Block16>],
224        rotation: usize,
225    },
226    #[zeroize(skip)]
227    RotationB32 {
228        data: &'a [Flat<Block32>],
229        rotation: usize,
230    },
231    #[zeroize(skip)]
232    RotationB64 {
233        data: &'a [Flat<Block64>],
234        rotation: usize,
235    },
236    #[zeroize(skip)]
237    RotationB128 {
238        data: &'a [Flat<Block128>],
239        rotation: usize,
240    },
241
242    // ====================================================
243    // Compressed slice views (JIT-promoted to F)
244    // ====================================================
245    #[zeroize(skip)]
246    BitSlice(&'a [Bit]),
247    #[zeroize(skip)]
248    B8Slice(&'a [Flat<Block8>]),
249    #[zeroize(skip)]
250    B16Slice(&'a [Flat<Block16>]),
251    #[zeroize(skip)]
252    B32Slice(&'a [Flat<Block32>]),
253    #[zeroize(skip)]
254    B64Slice(&'a [Flat<Block64>]),
255    #[zeroize(skip)]
256    B128Slice(&'a [Flat<Block128>]),
257
258    // ====================================================
259    // Same-width views shifted by one row (cyclic)
260    // ====================================================
261    #[zeroize(skip)]
262    ShiftedBitSlice(&'a [Bit]),
263    #[zeroize(skip)]
264    ShiftedB8Slice(&'a [Flat<Block8>]),
265    #[zeroize(skip)]
266    ShiftedB16Slice(&'a [Flat<Block16>]),
267    #[zeroize(skip)]
268    ShiftedB32Slice(&'a [Flat<Block32>]),
269    #[zeroize(skip)]
270    ShiftedB64Slice(&'a [Flat<Block64>]),
271    #[zeroize(skip)]
272    ShiftedB128Slice(&'a [Flat<Block128>]),
273
274    #[zeroize(skip)]
275    ShiftedPackedBitB8 {
276        data: &'a [Flat<Block8>],
277        bit_idx: usize,
278    },
279    #[zeroize(skip)]
280    ShiftedPackedBitB16 {
281        data: &'a [Flat<Block16>],
282        bit_idx: usize,
283    },
284    #[zeroize(skip)]
285    ShiftedPackedBitB32 {
286        data: &'a [Flat<Block32>],
287        bit_idx: usize,
288    },
289    #[zeroize(skip)]
290    ShiftedPackedBitB64 {
291        data: &'a [Flat<Block64>],
292        bit_idx: usize,
293    },
294}
295
296impl<'a, F> PolyVariant<'a, F>
297where
298    F: TraceCompatibleField,
299{
300    /// Number of hypercube points (polynomial length).
301    pub fn len(&self) -> usize {
302        match self {
303            Self::Dense(h) => h.len(),
304            Self::Shifted(h) => h.len(),
305            Self::Eq(t) => 1 << t.num_vars(),
306            Self::PackedBitB8 { data, .. } => data.len(),
307            Self::PackedBitB16 { data, .. } => data.len(),
308            Self::PackedBitB32 { data, .. } => data.len(),
309            Self::PackedBitB64 { data, .. } => data.len(),
310            Self::TransitionMask { num_vars, .. } => 1 << num_vars,
311            Self::CompositeSelector(cols) => {
312                if cols.is_empty() {
313                    0
314                } else {
315                    cols[0].len()
316                }
317            }
318            Self::IndirectBit { indices, .. } => indices.len(),
319            Self::IndirectB8 { indices, .. } => indices.len(),
320            Self::IndirectB16 { indices, .. } => indices.len(),
321            Self::IndirectB32 { indices, .. } => indices.len(),
322            Self::IndirectB64 { indices, .. } => indices.len(),
323            Self::IndirectB128 { indices, .. } => indices.len(),
324            Self::StrideBit { len, .. } => *len,
325            Self::StrideB8 { len, .. } => *len,
326            Self::StrideB16 { len, .. } => *len,
327            Self::StrideB32 { len, .. } => *len,
328            Self::StrideB64 { len, .. } => *len,
329            Self::StrideB128 { len, .. } => *len,
330            Self::RotationBit { data, .. } => data.len(),
331            Self::RotationB8 { data, .. } => data.len(),
332            Self::RotationB16 { data, .. } => data.len(),
333            Self::RotationB32 { data, .. } => data.len(),
334            Self::RotationB64 { data, .. } => data.len(),
335            Self::RotationB128 { data, .. } => data.len(),
336            Self::BitSlice(h) => h.len(),
337            Self::B8Slice(h) => h.len(),
338            Self::B16Slice(h) => h.len(),
339            Self::B32Slice(h) => h.len(),
340            Self::B64Slice(h) => h.len(),
341            Self::B128Slice(h) => h.len(),
342            Self::ShiftedBitSlice(h) => h.len(),
343            Self::ShiftedB8Slice(h) => h.len(),
344            Self::ShiftedB16Slice(h) => h.len(),
345            Self::ShiftedB32Slice(h) => h.len(),
346            Self::ShiftedB64Slice(h) => h.len(),
347            Self::ShiftedB128Slice(h) => h.len(),
348            Self::ShiftedPackedBitB8 { data, .. } => data.len(),
349            Self::ShiftedPackedBitB16 { data, .. } => data.len(),
350            Self::ShiftedPackedBitB32 { data, .. } => data.len(),
351            Self::ShiftedPackedBitB64 { data, .. } => data.len(),
352        }
353    }
354
355    pub fn is_empty(&self) -> bool {
356        self.len() == 0
357    }
358
359    /// Read the hypercube value at `index`,
360    /// lifted into `Flat<F>`. `O(1)` for
361    /// slice variants, `O(num_vars)` for `Eq`.
362    #[inline(always)]
363    pub fn get_at(&self, index: usize) -> Flat<F> {
364        match self {
365            Self::Dense(h) => h[index],
366            Self::Shifted(h) => {
367                let len = h.len();
368                let next_idx = if index + 1 == len { 0 } else { index + 1 };
369
370                h[next_idx]
371            }
372            Self::Eq(t) => t.evaluate_at_index(index),
373            Self::PackedBitB8 { data, bit_idx } => {
374                Flat::from_raw(F::from(Bit::new(data[index].tower_bit(*bit_idx))))
375            }
376            Self::PackedBitB16 { data, bit_idx } => {
377                Flat::from_raw(F::from(Bit::new(data[index].tower_bit(*bit_idx))))
378            }
379            Self::PackedBitB32 { data, bit_idx } => {
380                Flat::from_raw(F::from(Bit::new(data[index].tower_bit(*bit_idx))))
381            }
382            Self::PackedBitB64 { data, bit_idx } => {
383                Flat::from_raw(F::from(Bit::new(data[index].tower_bit(*bit_idx))))
384            }
385            Self::TransitionMask {
386                num_vars,
387                product_of_challenges,
388            } => {
389                let last_idx: usize = (1 << num_vars) - 1;
390                if index == last_idx {
391                    Flat::from_raw(F::ONE - *product_of_challenges)
392                } else {
393                    Flat::from_raw(F::ONE)
394                }
395            }
396            Self::CompositeSelector(cols) => {
397                let parity = cols.iter().fold(0, |acc, col| acc ^ col[index].get());
398
399                Flat::from_raw(F::from(Bit::new(parity)))
400            }
401
402            Self::IndirectBit { data, indices } => Flat::from_raw(F::from(data[indices[index]])),
403            Self::IndirectB8 { data, indices } => F::promote_flat(data[indices[index]]),
404            Self::IndirectB16 { data, indices } => F::promote_flat(data[indices[index]]),
405            Self::IndirectB32 { data, indices } => F::promote_flat(data[indices[index]]),
406            Self::IndirectB64 { data, indices } => F::promote_flat(data[indices[index]]),
407            Self::IndirectB128 { data, indices } => F::promote_flat(data[indices[index]]),
408
409            Self::StrideBit {
410                data, start, step, ..
411            } => Flat::from_raw(F::from(data[start + index * step])),
412            Self::StrideB8 {
413                data, start, step, ..
414            } => F::promote_flat(data[start + index * step]),
415            Self::StrideB16 {
416                data, start, step, ..
417            } => F::promote_flat(data[start + index * step]),
418            Self::StrideB32 {
419                data, start, step, ..
420            } => F::promote_flat(data[start + index * step]),
421            Self::StrideB64 {
422                data, start, step, ..
423            } => F::promote_flat(data[start + index * step]),
424            Self::StrideB128 {
425                data, start, step, ..
426            } => F::promote_flat(data[start + index * step]),
427
428            Self::RotationBit { data, rotation } => {
429                Flat::from_raw(F::from(data[(index + rotation) & (data.len() - 1)]))
430            }
431            Self::RotationB8 { data, rotation } => {
432                F::promote_flat(data[(index + rotation) & (data.len() - 1)])
433            }
434            Self::RotationB16 { data, rotation } => {
435                F::promote_flat(data[(index + rotation) & (data.len() - 1)])
436            }
437            Self::RotationB32 { data, rotation } => {
438                F::promote_flat(data[(index + rotation) & (data.len() - 1)])
439            }
440            Self::RotationB64 { data, rotation } => {
441                F::promote_flat(data[(index + rotation) & (data.len() - 1)])
442            }
443            Self::RotationB128 { data, rotation } => {
444                F::promote_flat(data[(index + rotation) & (data.len() - 1)])
445            }
446
447            Self::BitSlice(s) => Flat::from_raw(F::from(s[index])),
448            Self::B8Slice(s) => F::promote_flat(s[index]),
449            Self::B16Slice(s) => F::promote_flat(s[index]),
450            Self::B32Slice(s) => F::promote_flat(s[index]),
451            Self::B64Slice(s) => F::promote_flat(s[index]),
452            Self::B128Slice(s) => F::promote_flat(s[index]),
453
454            Self::ShiftedBitSlice(s) => {
455                let len = s.len();
456                let next_idx = if index + 1 == len { 0 } else { index + 1 };
457
458                Flat::from_raw(F::from(s[next_idx]))
459            }
460            Self::ShiftedB8Slice(s) => {
461                let len = s.len();
462                let next_idx = if index + 1 == len { 0 } else { index + 1 };
463
464                F::promote_flat(s[next_idx])
465            }
466            Self::ShiftedB16Slice(s) => {
467                let len = s.len();
468                let next_idx = if index + 1 == len { 0 } else { index + 1 };
469
470                F::promote_flat(s[next_idx])
471            }
472            Self::ShiftedB32Slice(s) => {
473                let len = s.len();
474                let next_idx = if index + 1 == len { 0 } else { index + 1 };
475
476                F::promote_flat(s[next_idx])
477            }
478            Self::ShiftedB64Slice(s) => {
479                let len = s.len();
480                let next_idx = if index + 1 == len { 0 } else { index + 1 };
481
482                F::promote_flat(s[next_idx])
483            }
484            Self::ShiftedB128Slice(s) => {
485                let len = s.len();
486                let next_idx = if index + 1 == len { 0 } else { index + 1 };
487
488                F::promote_flat(s[next_idx])
489            }
490            Self::ShiftedPackedBitB8 { data, bit_idx } => {
491                let len = data.len();
492                let next_idx = if index + 1 == len { 0 } else { index + 1 };
493
494                Flat::from_raw(F::from(Bit::new(data[next_idx].tower_bit(*bit_idx))))
495            }
496            Self::ShiftedPackedBitB16 { data, bit_idx } => {
497                let len = data.len();
498                let next_idx = if index + 1 == len { 0 } else { index + 1 };
499
500                Flat::from_raw(F::from(Bit::new(data[next_idx].tower_bit(*bit_idx))))
501            }
502            Self::ShiftedPackedBitB32 { data, bit_idx } => {
503                let len = data.len();
504                let next_idx = if index + 1 == len { 0 } else { index + 1 };
505
506                Flat::from_raw(F::from(Bit::new(data[next_idx].tower_bit(*bit_idx))))
507            }
508            Self::ShiftedPackedBitB64 { data, bit_idx } => {
509                let len = data.len();
510                let next_idx = if index + 1 == len { 0 } else { index + 1 };
511
512                Flat::from_raw(F::from(Bit::new(data[next_idx].tower_bit(*bit_idx))))
513            }
514        }
515    }
516
517    /// Evaluate the MLE at an arbitrary point.
518    /// `Eq` delegates to `TensorProduct`;
519    /// every other variant expands MLE weights
520    /// once and does a single `get_at` sweep.
521    #[inline(always)]
522    pub fn evaluate(&self, point: &[Flat<F>]) -> errors::Result<Flat<F>> {
523        match self {
524            Self::Eq(t) => Ok(t.evaluate_extension(point)?),
525            _ => {
526                let num_vars = point.len();
527                let got_len = self.len();
528
529                let Some(expected_len) = 1usize.checked_shl(num_vars as u32) else {
530                    return Err(Error::DomainTooLarge { num_vars }.into());
531                };
532
533                if got_len != expected_len {
534                    return Err(Error::DomainSizeMismatch {
535                        expected_len,
536                        got_len,
537                    }
538                    .into());
539                }
540
541                if num_vars == 0 {
542                    return Ok(self.get_at(0));
543                }
544
545                let weights = Self::expand_mle_weights(point);
546                let mut total = Flat::from_raw(F::ZERO);
547
548                for (i, w) in weights.iter().enumerate() {
549                    total += self.get_at(i) * *w;
550                }
551
552                Ok(total)
553            }
554        }
555    }
556
557    pub fn expand_mle_weights(r: &[Flat<F>]) -> Vec<Flat<F>> {
558        let num_vars = r.len();
559        let size = 1 << num_vars;
560
561        let mut weights = vec![Flat::from_raw(F::ZERO); size];
562        weights[0] = Flat::from_raw(F::ONE);
563
564        for (i, &rk) in r.iter().enumerate() {
565            let one_minus_rk = Flat::from_raw(F::ONE) - rk;
566            let current_len = 1 << i;
567
568            for i in 0..current_len {
569                let w = weights[i];
570                weights[i] = w * one_minus_rk;
571                weights[current_len + i] = w * rk;
572            }
573        }
574
575        weights
576    }
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582    use hekate_math::{Bit, Block8, Block128, FlatPromote, HardwareField, TowerField};
583
584    type F = Block128;
585
586    #[test]
587    fn get_at_dense_returns_correct_values() {
588        let data: Vec<Flat<F>> = (0..4u128).map(|i| F::from(i * 10).to_hardware()).collect();
589        let v = PolyVariant::<F>::Dense(&data);
590
591        assert_eq!(v.get_at(0), F::from(0u128).to_hardware());
592        assert_eq!(v.get_at(1), F::from(10u128).to_hardware());
593        assert_eq!(v.get_at(2), F::from(20u128).to_hardware());
594        assert_eq!(v.get_at(3), F::from(30u128).to_hardware());
595    }
596
597    #[test]
598    fn get_at_bit_slice_promotes_to_field() {
599        let bits = vec![
600            Bit::from(0u32),
601            Bit::from(1u32),
602            Bit::from(1u32),
603            Bit::from(0u32),
604        ];
605        let v = PolyVariant::<F>::BitSlice(&bits);
606
607        assert_eq!(v.get_at(0), Flat::from_raw(F::ZERO));
608        assert_eq!(v.get_at(1), Flat::from_raw(F::ONE));
609        assert_eq!(v.get_at(2), Flat::from_raw(F::ONE));
610        assert_eq!(v.get_at(3), Flat::from_raw(F::ZERO));
611    }
612
613    #[test]
614    fn get_at_b8_slice_promotes() {
615        let data = vec![
616            Block8::from(0u8).to_hardware(),
617            Block8::from(0xFFu8).to_hardware(),
618        ];
619        let v = PolyVariant::<F>::B8Slice(&data);
620
621        assert_eq!(
622            v.get_at(0),
623            F::promote_flat(Block8::from(0u8).to_hardware())
624        );
625        assert_eq!(
626            v.get_at(1),
627            F::promote_flat(Block8::from(0xFFu8).to_hardware())
628        );
629    }
630
631    #[test]
632    fn len_matches_data_size() {
633        let data = vec![Flat::from_raw(F::ZERO); 16];
634        assert_eq!(PolyVariant::<F>::Dense(&data).len(), 16);
635
636        let bits = vec![Bit::from(0u32); 8];
637        assert_eq!(PolyVariant::<F>::BitSlice(&bits).len(), 8);
638
639        let eq = TensorProduct::new(vec![Flat::from_raw(F::ONE); 5]);
640        assert_eq!(PolyVariant::<F>::Eq(eq).len(), 32);
641
642        let empty: Vec<Flat<F>> = vec![];
643        assert!(PolyVariant::<F>::Dense(&empty).is_empty());
644    }
645
646    #[test]
647    fn evaluate_constant_polynomial() {
648        let num_vars = 3;
649        let data = vec![F::from(42u128).to_hardware(); 1 << num_vars];
650        let v = PolyVariant::<F>::Dense(&data);
651
652        let point: Vec<Flat<F>> = vec![
653            Flat::from_raw(F::from(1u128).to_hardware().into_raw()),
654            Flat::from_raw(F::from(2u128).to_hardware().into_raw()),
655            Flat::from_raw(F::from(3u128).to_hardware().into_raw()),
656        ];
657
658        let val = v.evaluate(&point).unwrap();
659        assert_eq!(val.into_raw(), F::from(42u128).to_hardware().into_raw());
660    }
661
662    #[test]
663    fn evaluate_linear_polynomial() {
664        let data = vec![F::ZERO.to_hardware(), F::from(10u128).to_hardware()];
665        let v = PolyVariant::<F>::Dense(&data);
666
667        let point = vec![Flat::from_raw(F::from(2u128).to_hardware().into_raw())];
668        let val = v.evaluate(&point).unwrap();
669        assert_eq!(val.into_raw(), F::from(20u128).to_hardware().into_raw());
670    }
671
672    #[test]
673    fn evaluate_single_row() {
674        let data = vec![F::from(99u128).to_hardware()];
675        let v = PolyVariant::<F>::Dense(&data);
676
677        let val = v.evaluate(&[]).unwrap();
678        assert_eq!(val.into_raw(), F::from(99u128).to_hardware().into_raw());
679    }
680
681    #[test]
682    fn evaluate_domain_mismatch_rejected() {
683        let data = vec![F::ZERO.to_hardware(); 4];
684        let v = PolyVariant::<F>::Dense(&data);
685
686        let point = vec![Flat::from_raw(F::ONE); 3];
687        assert!(v.evaluate(&point).is_err());
688    }
689
690    #[test]
691    fn evaluate_eq_polynomial() {
692        let r = vec![Flat::from_raw(F::ONE), Flat::from_raw(F::ZERO)];
693        let eq = PolyVariant::<F>::Eq(TensorProduct::new(r.clone()));
694
695        let val = eq.evaluate(&r).unwrap();
696        assert_eq!(val.into_raw(), F::ONE.to_hardware().into_raw());
697    }
698
699    #[test]
700    fn expand_mle_weights_single_var() {
701        let r = vec![Flat::from_raw(F::from(7u128).to_hardware().into_raw())];
702        let w = PolyVariant::<F>::expand_mle_weights(&r);
703
704        assert_eq!(w.len(), 2);
705        let r0 = r[0];
706        let one = Flat::from_raw(F::ONE);
707        assert_eq!(w[0], one - r0);
708        assert_eq!(w[1], r0);
709    }
710
711    #[test]
712    fn expand_mle_weights_zero_vars() {
713        let w = PolyVariant::<F>::expand_mle_weights(&[]);
714        assert_eq!(w.len(), 1);
715        assert_eq!(w[0], Flat::from_raw(F::ONE));
716    }
717
718    #[test]
719    fn shifted_get_at_wraps_cyclically() {
720        let data: Vec<Flat<F>> = (1..=4u128).map(|i| F::from(i).to_hardware()).collect();
721        let v = PolyVariant::<F>::Shifted(&data);
722
723        assert_eq!(v.get_at(0), F::from(2u128).to_hardware());
724        assert_eq!(v.get_at(1), F::from(3u128).to_hardware());
725        assert_eq!(v.get_at(2), F::from(4u128).to_hardware());
726        assert_eq!(v.get_at(3), F::from(1u128).to_hardware());
727    }
728
729    #[test]
730    fn composite_selector_sums_columns() {
731        let a = vec![
732            Bit::from(1u32),
733            Bit::from(0u32),
734            Bit::from(1u32),
735            Bit::from(0u32),
736        ];
737        let b = vec![
738            Bit::from(0u32),
739            Bit::from(1u32),
740            Bit::from(1u32),
741            Bit::from(0u32),
742        ];
743        let v = PolyVariant::<F>::CompositeSelector(vec![&a, &b]);
744
745        assert_eq!(v.get_at(0), Flat::from_raw(F::ONE));
746        assert_eq!(v.get_at(1), Flat::from_raw(F::ONE));
747
748        let two = F::ONE + F::ONE;
749        assert_eq!(v.get_at(2), Flat::from_raw(two));
750        assert_eq!(v.get_at(3), Flat::from_raw(F::ZERO));
751    }
752}