use crate::field::{solve, Fp};
use crate::paper::ops::{from_spectral, target_multiplier, to_spectral, OpCounter};
use crate::paper::params::Params;
use crate::paper::predictor::{apply_predictor, predictor_value};
#[derive(Debug)]
pub struct RepairOutput {
pub rows: Vec<Vec<Fp>>,
pub s: usize,
pub max_exceptions: usize,
}
pub fn paper_exception_budget(w: usize, m: usize) -> usize {
w / (2 * m * m * m)
}
pub fn required_budget(params: &Params, shifts: &[u32]) -> usize {
(0..1usize << params.m)
.map(|nu| exception_set(params, shifts, nu).len())
.max()
.unwrap_or(0)
}
fn exception_set(params: &Params, shifts: &[u32], nu: usize) -> Vec<usize> {
let z = target_multiplier(nu);
shifts
.iter()
.enumerate()
.filter(|&(_, &b)| predictor_value(params, b, nu) != z)
.map(|(i, _)| i)
.collect()
}
fn node(i: usize) -> Fp {
Fp::new(i as u64 + 1)
}
fn mix<F: Fn(usize, usize) -> Fp>(rows: &[Vec<Fp>], out: usize, coef: F) -> Vec<Vec<Fp>> {
let n = rows.first().map_or(0, |r| r.len());
(0..out)
.map(|t| {
let mut acc = vec![Fp::ZERO; n];
for (i, r) in rows.iter().enumerate() {
let c = coef(t, i);
if c != Fp::ZERO {
for k in 0..n {
acc[k] += c * r[k];
}
}
}
acc
})
.collect()
}
pub fn apply_f_repaired(
params: &Params,
xs: &[Vec<Fp>],
shifts: &[u32],
s: Option<usize>,
ctr: &OpCounter,
) -> RepairOutput {
let m = params.m;
let n = 1usize << m;
let w = xs.len();
assert_eq!(shifts.len(), w);
assert!(xs.iter().all(|r| r.len() == n));
let max_exc = required_budget(params, shifts);
let s = s.unwrap_or(max_exc);
assert!(s >= max_exc, "budget s={s} below max |J|={max_exc}");
let px: Vec<_> = (0..w).map(|i| apply_predictor(params, shifts[i], &xs[i], ctr)).collect();
let p2x: Vec<_> = (0..w).map(|i| apply_predictor(params, shifts[i], &px[i], ctr)).collect();
let p3x: Vec<_> = (0..w).map(|i| apply_predictor(params, shifts[i], &p2x[i], ctr)).collect();
let (a_rows, fa_rows) = if s == 0 {
(Vec::new(), Vec::new())
} else {
let hx = mix(xs, s, |t, i| node(i).pow(t as u64));
let hpx = mix(&px, s, |t, i| node(i).pow(t as u64));
let hx_s: Vec<_> = hx.iter().map(|r| to_spectral(r, ctr)).collect();
let hpx_s: Vec<_> = hpx.iter().map(|r| to_spectral(r, ctr)).collect();
let mut a_s = vec![vec![Fp::ZERO; n]; s];
let mut fa_s = vec![vec![Fp::ZERO; n]; s];
let half = Fp::new(2).inv();
for nu in 0..n {
let z = target_multiplier(nu);
let jset = exception_set(params, shifts, nu);
let k = jset.len();
if k == 0 {
continue;
}
let he: Vec<Fp> = (0..k).map(|t| hpx_s[t][nu] - z * hx_s[t][nu]).collect();
let vt: Vec<Vec<Fp>> = (0..k)
.map(|t| jset.iter().map(|&i| node(i).pow(t as u64)).collect())
.collect();
let e = solve(vt, he);
let rhs: Vec<Fp> = jset
.iter()
.zip(&e)
.map(|(&i, &ei)| {
let p = predictor_value(params, shifts[i], nu);
-(p + Fp::new(2) * z) * half * ei
})
.collect();
let vj: Vec<Vec<Fp>> = jset
.iter()
.map(|&i| (0..k).map(|t| node(i).pow(t as u64)).collect())
.collect();
let a = solve(vj, rhs);
for t in 0..k {
a_s[t][nu] = a[t];
fa_s[t][nu] = z * a[t];
}
}
(
a_s.iter().map(|r| from_spectral(r, ctr)).collect::<Vec<_>>(),
fa_s.iter().map(|r| from_spectral(r, ctr)).collect::<Vec<_>>(),
)
};
let zhat = if s == 0 {
vec![vec![Fp::ZERO; n]; w]
} else {
mix(&a_rows, w, |i, t| node(i).pow(t as u64))
};
let fzhat = if s == 0 {
vec![vec![Fp::ZERO; n]; w]
} else {
mix(&fa_rows, w, |i, t| node(i).pow(t as u64))
};
let half = Fp::new(2).inv();
let three = Fp::new(3);
let rows = (0..w)
.map(|i| {
let pz = if s == 0 {
vec![Fp::ZERO; n]
} else {
apply_predictor(params, shifts[i], &zhat[i], ctr)
};
(0..n)
.map(|k| (three * px[i][k] - p3x[i][k]) * half - pz[k] + fzhat[i][k])
.collect()
})
.collect();
RepairOutput {
rows,
s,
max_exceptions: max_exc,
}
}
pub fn balanced_shifts(m: usize, w: usize) -> Vec<u32> {
let n = 1usize << m;
assert!(w % n == 0, "W must be a multiple of 2^m for balanced shifts");
(0..w).map(|i| (i % n) as u32).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::paper::ops::apply_f_reference;
fn rows(m: usize, w: usize, seed: u64) -> Vec<Vec<Fp>> {
let mut st = seed;
(0..w)
.map(|_| {
(0..1usize << m)
.map(|_| {
st = st.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
Fp::new(st >> 1)
})
.collect()
})
.collect()
}
fn check(params: Params, w: usize, seed: u64) -> RepairOutput {
let ctr = OpCounter::default();
let xs = rows(params.m, w, seed);
let shifts = balanced_shifts(params.m, w);
let out = apply_f_repaired(¶ms, &xs, &shifts, None, &ctr);
for (x, y) in xs.iter().zip(&out.rows) {
assert_eq!(y, &apply_f_reference(params.m, x));
}
assert_eq!(ctr.spectral() as usize, 4 * out.s);
out
}
#[test]
fn exact_without_exceptions() {
let out = check(Params::paper(5), 32, 1);
assert_eq!(out.s, 0);
}
#[test]
fn exact_with_exceptions() {
for (m, b) in [(4, 0.5), (6, 1.0), (7, 1.0), (8, 1.5)] {
let p = Params::with_half_width(m, b);
assert!(p.window_bites());
let out = check(p, 1 << m, 42 + m as u64);
assert!(out.s > 0, "expected exceptions for m={m}");
}
}
#[test]
#[should_panic(expected = "budget")]
fn too_small_budget_rejected() {
let p = Params::with_half_width(6, 1.0);
let ctr = OpCounter::default();
let xs = rows(6, 64, 3);
apply_f_repaired(&p, &xs, &balanced_shifts(6, 64), Some(1), &ctr);
}
}