//! The windowed table of Section 4, shared by all counts belonging to one //! radius m, with an a-posteriori certificate replacing the unspecified //! constants of Section 3 (C_0, E = C sqrt(K), the cutoff 1/(4m), ...). //! //! Notation (lambda = m, b_i = floor(lambda sigma_i), phi_i = frac): //! f_i(z) = T(b_i+z) - T(b_i) - lambda sigma_i z = z(z+1-2 phi_i)/2 >= 0. //! For any rectangle n = A+B (balanced) and depths d with debit <= W_n and //! perimeter <= U (an upper bound on L_k), with Delta = sum_i f_i(d_i-b_i): //! Delta <= Dmax(n) := Psi(lambda) + W_n - lambda (2n - U) (*) //! where Psi(mu) = sum_i max_t (mu sigma_i t - T(t)). The same holds with //! any mu > 0 in place of lambda (with b_i(mu)), and Delta >= 0, so //! min_mu Dmax_mu(n) < 0 excludes the rectangle n (Lagrangian dual bound). //! Cauchy--Schwarz gives |zeta| <= D1 + sqrt(2 D2 Delta) for //! zeta = sum sigma_i (d_i - b_i), which together with the two linear //! relations of Lemma `window` bounds the range of n rigorously. //! Every node then satisfies f_i(d_i - b_i) <= Delta* := max over feasible n //! of Dmax(n); and some optimizer occupies an upper set of nodes in the //! order (sigma desc, id asc), so a vacant-node cutoff follows from the //! sum of 1 - lambda sigma_i over nodes with b_i = 0. //! All formulas are evaluated in the "small domain" (deviations only). use crate::dp::Table; use crate::polygon; use crate::tree::{Tree, V2}; use std::time::Instant; pub const D1: f64 = 8.0; pub fn d2() -> f64 { 2.0 * (4.0 - std::f64::consts::PI) } #[inline] pub fn tri(t: i64) -> i64 { t * (t + 1) / 2 } /// Balanced rectangle with side sum n. #[inline] pub fn rect(n: i64) -> (i64, i64) { (n / 2, n - n / 2) } #[inline] pub fn count_of(n: i64) -> i64 { let (a, b) = rect(n); (a + 1) * (b + 1) } /// Smallest side sum n whose balanced rectangle has at least k points. pub fn n_min_for(k: i64) -> i64 { let mut n = ((2.0 * (k as f64).sqrt() - 3.0).floor() as i64).max(0); while count_of(n) < k { n += 1; } while n > 0 && count_of(n - 1) >= k { n -= 1; } n } /// The radius a count belongs to: nearest integer to sqrt(k/pi). pub fn radius_of(k: i64) -> i64 { ((k as f64 / std::f64::consts::PI).sqrt() + 0.5).floor().max(1.0) as i64 } /// Neumaier compensated sum. #[derive(Default, Clone, Copy)] struct KSum { s: f64, c: f64, } impl KSum { #[inline] fn add(&mut self, x: f64) { let t = self.s + x; if self.s.abs() >= x.abs() { self.c += (self.s - t) + x; } else { self.c += (x - t) + self.s; } self.s = t; } #[inline] fn get(&self) -> f64 { self.s + self.c } } #[derive(Clone)] pub struct Params { /// Half-width of the heuristic first-pass windows. pub h1: i64, /// First pass includes nodes with lambda*sigma >= theta1. pub theta1: f64, /// Store choices and reconstruct/verify polygons. pub polygons: bool, pub max_passes: usize, /// First-pass candidate side sums: estimate +- r1. pub r1: i64, /// Above this many bytes of choice tables, polygons are reconstructed /// by the memory-bounded divide and conquer instead. pub mem_limit: usize, /// Debug: add this to Delta* and widen the side sums by 2 (must not /// change any result). pub inflate: f64, } impl Default for Params { fn default() -> Self { Params { h1: 1, theta1: 0.5, polygons: true, max_passes: 4, r1: 2, mem_limit: 4_000_000_000, inflate: 0.0 } } } #[derive(Clone)] pub struct KResult { pub k: i64, pub m: i64, pub perimeter: f64, pub a: i64, pub b: i64, pub certified: bool, pub delta_star: f64, pub n_feasible: usize, pub vertices: Option>, /// vertex count (kept after `vertices` is dropped) pub nverts: usize, /// lattice points on the boundary, longest edge length and its lattice steps pub boundary: i64, pub longest_edge: f64, pub longest_steps: i64, /// Some(true) when the polygon passed all checks. pub check_ok: Option, pub check_msg: String, } #[derive(Clone, Default)] pub struct GroupStats { pub m: i64, pub ks: usize, pub passes: usize, pub tree_rebuilds: usize, pub nodes_enum: usize, pub dp_nodes: usize, pub items: usize, pub table_len: usize, pub groups: usize, pub work: u64, pub choice_bytes: usize, pub delta_star: f64, pub secs: f64, pub secs_dp: f64, pub pass_log: String, } /// Per-global-node depth windows; `inc[i]` false means the node is vacant. #[derive(Clone)] struct Windows { inc: Vec, l: Vec, u: Vec, } impl Windows { fn contains(&self, o: &Windows) -> bool { for i in 0..o.inc.len() { if o.inc[i] && o.u[i] > 0 { if !self.inc[i] || self.l[i] > o.l[i] || self.u[i] < o.u[i] { return false; } } else if o.inc[i] && o.u[i] == 0 && self.inc[i] && self.l[i] > 0 { return false; } } true } } struct Dp { table: Table, scale: f64, /// compulsory debit and saving d: i64, s: f64, nodes: usize, items: usize, /// items by weight (sorted by the table build), for reconstruction by_weight: Vec>, } fn build_dp(tree: &Tree, win: &Windows, cap_budget: i64, keep: bool) -> Dp { let n = tree.n_global(); let mut d = 0i64; let mut s = KSum::default(); let mut tot = 0.0f64; let mut maxw = 0i64; let mut nodes = 0; for i in 0..n { if !win.inc[i] { continue; } let sg = tree.sig(i); d += tri(win.l[i]); s.add(sg * win.l[i] as f64); tot += sg * (win.u[i] - win.l[i]) as f64; maxw = maxw.max(win.u[i]); nodes += 1; } let e = (tot + 1.0).log2().ceil() as i32; let scale = 2f64.powi((60 - e).clamp(20, 60)); let mut items: Vec> = vec![vec![]; (maxw + 1) as usize]; let mut nitems = 0; for i in 0..n { if !win.inc[i] { continue; } let p = (tree.sig(i) * scale).round() as i64; for j in (win.l[i] + 1)..=win.u[i] { items[j as usize].push((p, i as u32)); nitems += 1; } } let cap_len = (cap_budget.max(0) + 1) as usize; let table = Table::build(&mut items, cap_len, keep); Dp { table, scale, d, s: s.get(), nodes, items: nitems, by_weight: items } } /// Precomputed pieces of the certificate for one pass. struct Cert { /// sum sigma_i (b_i - l_i) sb: f64, /// sum T(b_i) - T(l_i) tb: i64, /// Delta_l(lambda) = sum f_i(l_i - b_i) dl_lam: f64, /// lower convex hull of (mu, Delta_l(mu)) hull: Vec<(f64, f64)>, } fn f_dev(z: i64, phi: f64) -> f64 { let zf = z as f64; zf * (zf + 1.0 - 2.0 * phi) / 2.0 } fn delta_l(tree: &Tree, win: &Windows, mu: f64) -> f64 { let mut acc = KSum::default(); for i in 0..tree.n_global() { let l = if win.inc[i] { win.l[i] } else { 0 }; let x = mu * tree.sig(i); if l == 0 && x < 1.0 { continue; } let b = x.floor(); acc.add(f_dev(l - b as i64, x - b)); } acc.get() } fn make_cert(tree: &Tree, win: &Windows, lam: f64) -> Cert { let mut sb = KSum::default(); let mut tb = 0i64; for i in 0..tree.n_global() { let l = if win.inc[i] { win.l[i] } else { 0 }; let x = lam * tree.sig(i); let b = x.floor() as i64; if b == 0 && l == 0 { continue; } sb.add(tree.sig(i) * (b - l) as f64); tb += tri(b) - tri(l); } let dl_lam = delta_l(tree, win, lam); // mu grid around lambda let tmax = (1.0 / tree.cutoff - lam).min(640.0); let tmin = -(lam - 0.01).min(640.0); let mut ts: Vec = vec![]; let mut t = 0.0f64; while t <= tmax { ts.push(t); t += step_for(t); } let mut t = 0.0f64; loop { t += step_for(t); if -t < tmin { break; } ts.push(-t); } ts.sort_by(|a, b| a.partial_cmp(b).unwrap()); let pts: Vec<(f64, f64)> = ts.iter().map(|&t| (lam + t, delta_l(tree, win, lam + t))).collect(); // lower hull (monotone chain) let mut hull: Vec<(f64, f64)> = vec![]; for p in pts { while hull.len() >= 2 { let a = hull[hull.len() - 2]; let b = hull[hull.len() - 1]; let cr = (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0); if cr <= 0.0 { hull.pop(); } else { break; } } hull.push(p); } Cert { sb: sb.get(), tb, dl_lam, hull } } fn step_for(t: f64) -> f64 { let a = t.abs(); if a < 4.0 { 1.0 / 32.0 } else if a < 32.0 { 0.25 } else if a < 128.0 { 1.0 } else { 8.0 } } /// min over hull points of y - c*mu. fn hull_min(hull: &[(f64, f64)], c: f64) -> f64 { let (mut lo, mut hi) = (0usize, hull.len() - 1); while lo < hi { let mid = (lo + hi) / 2; let slope = (hull[mid + 1].1 - hull[mid].1) / (hull[mid + 1].0 - hull[mid].0); if slope < c { lo = mid + 1; } else { hi = mid; } } let mut best = f64::INFINITY; for i in lo.saturating_sub(1)..(lo + 2).min(hull.len()) { best = best.min(hull[i].1 - c * hull[i].0); } best } struct KBest { n: i64, w: i64, fhat: f64, perim: f64, } /// Best candidate among the side sums `cand`. fn best_for(k: i64, dp: &Dp, cand: &[i64]) -> Option { let sc = dp.scale as i128; let mut best: Option<(i128, i64, i64)> = None; for &n in cand { let w = count_of(n) - k - dp.d; if w < 0 { continue; } let v = 2 * n as i128 * sc - dp.table.value(w) as i128; if best.map_or(true, |b| v < b.0) { best = Some((v, n, w)); } } best.map(|(_, n, w)| { let fhat = dp.table.value(w) as f64 / dp.scale; KBest { n, w, fhat, perim: (2 * n) as f64 - fhat - dp.s } }) } struct KCert { feasible: Vec, delta_star: f64, } fn certify_k(k: i64, lam: f64, dp: &Dp, ce: &Cert, kb: &KBest, eps: f64) -> KCert { let d2 = d2(); let u = kb.perim; let n_lo = n_min_for(k); let n_hi = (u / std::f64::consts::SQRT_2 + 1e-9).floor() as i64; let w_of = |n: i64| count_of(n) - k - dp.d; let dmax = |n: i64| ce.dl_lam + w_of(n) as f64 - lam * (2.0 * (n - kb.n) as f64 + kb.fhat); let zmin = |n: i64| 2.0 * (n - kb.n) as f64 + kb.fhat - ce.sb; let zmax = |n: i64| (w_of(n) - ce.tb) as f64 / lam; let ab = |n: i64| { let (a, b) = rect(n); (a as f64 + 1.0 - 2.0 * lam) * (b as f64 + 1.0 - 2.0 * lam) }; let sig_s = |n: i64| (n + 2) as f64 - 4.0 * lam; let g = dmax(kb.n) - ab(kb.n); let gp = g.max(0.0); let gamma = 2.0 * sig_s(kb.n) - zmin(kb.n); let c2 = zmax(kb.n) - 2.0 * sig_s(kb.n) - ab(kb.n) / lam; let slack = 1e-6 * (1.0 + lam.sqrt()); let test = |n: i64| -> Option { let dm = dmax(n); if dm < -eps { return None; } let bn = D1 + (2.0 * d2 * dm.max(0.0)).sqrt() + slack; if zmin(n) > bn || zmax(n) < -bn { return None; } let c = 2.0 * (n - kb.n) as f64 + kb.fhat; if hull_min(&ce.hull, c) + (w_of(n) as f64) < -eps { return None; } Some(dm) }; let mut feasible = vec![]; let mut ds = f64::NEG_INFINITY; // upward let mut n = kb.n; while n <= n_hi { let s = sig_s(n); if s >= 0.0 && 2.0 * s - gamma > D1 + (2.0 * d2 * (s * s / 4.0 + gp)).sqrt() + slack { break; } if let Some(dm) = test(n) { feasible.push(n); ds = ds.max(dm); } n += 1; } // downward let nu_max = 4.0 * lam - 2.0 - n_lo as f64; let monotone = nu_max < 2.1 * lam; let mut n = kb.n - 1; while n >= n_lo { let nu = -sig_s(n); if monotone && nu >= 0.0 && 2.0 * nu - nu * nu / (4.0 * lam) - c2 > D1 + (2.0 * d2 * (nu * nu / 4.0 + gp)).sqrt() + slack { break; } if let Some(dm) = test(n) { feasible.push(n); ds = ds.max(dm); } n -= 1; } feasible.sort_unstable(); KCert { feasible, delta_star: ds } } /// Windows required by Delta* (None: the tree must be enumerated deeper). fn required_windows(tree: &Tree, lam: f64, delta_star: f64, order0: &[u32]) -> Option { let n = tree.n_global(); let mut w = Windows { inc: vec![false; n], l: vec![0; n], u: vec![0; n] }; let zr = |phi: f64| -> (i64, i64) { let bq = 1.0 - 2.0 * phi; let r = (bq * bq + 8.0 * delta_star.max(0.0)).sqrt(); (((-bq - r) / 2.0 - 1e-7).ceil() as i64, ((-bq + r) / 2.0 + 1e-7).floor() as i64) }; for i in 0..n { let x = lam * tree.sig(i); if x >= 1.0 { let b = x.floor(); let (lo, hi) = zr(x - b); let b = b as i64; w.inc[i] = true; w.l[i] = (b + lo).max(0); w.u[i] = b + hi.max(0); } } // cutoff walk over nodes with b = 0 in order (sigma desc, id asc) let mut acc = 0.0; let mut exhausted = true; for &g in order0 { let g = g as usize; let x = lam * tree.sig(g); acc += 1.0 - x; if acc > delta_star { exhausted = false; break; } let (_, hi) = zr(x); if hi >= 1 { w.inc[g] = true; w.l[g] = 0; w.u[g] = hi; } } if exhausted { return None; } Some(w) } fn heuristic_windows(tree: &Tree, lam: f64, h1: i64, theta1: f64) -> Windows { let n = tree.n_global(); let mut w = Windows { inc: vec![false; n], l: vec![0; n], u: vec![0; n] }; for i in 0..n { let x = lam * tree.sig(i); if x >= theta1 { let b = x.floor() as i64; w.inc[i] = true; w.l[i] = (b - h1).max(0); w.u[i] = b + h1.max(1); } } w } /// Solve all counts `ks` (which should belong to radius m) with one table. pub fn solve_group(m: i64, ks: &[i64], par: &Params) -> (Vec, GroupStats) { let t0 = Instant::now(); let lam = m as f64; let eps = 1e-6 * (1.0 + lam / 1000.0); let mut st = GroupStats { m, ks: ks.len(), ..Default::default() }; let mut z = (1.0 / (4.0 * lam)).min(1.0 / (2.0 * lam + 16.0)); // debug hook: KGRID_Z_FACTOR > 1 starts with a too-coarse enumeration // to exercise the re-enumeration path if let Some(f) = std::env::var("KGRID_Z_FACTOR").ok().and_then(|v| v.parse::().ok()) { z *= f; } 'outer: loop { let tree = Tree::build(z); st.nodes_enum = tree.n_global(); // b = 0 nodes in cutoff order let mut order0: Vec = (0..tree.n_global() as u32).filter(|&g| lam * tree.sig(g as usize) < 1.0).collect(); order0.sort_by(|&a, &b| { tree.sig(b as usize).partial_cmp(&tree.sig(a as usize)).unwrap().then(a.cmp(&b)) }); // pass-1 candidates let mut cands: Vec> = ks .iter() .map(|&k| { let est = (4.0 * (k as f64 / std::f64::consts::PI).sqrt() - 2.0).round() as i64; let lo = n_min_for(k).max(est - par.r1); (lo..=lo.max(est) + par.r1).collect() }) .collect(); let mut win = heuristic_windows(&tree, lam, par.h1, par.theta1); let mut have_choices; let mut prev_est = 0usize; for pass in 1..=par.max_passes { st.passes = pass; let keep = par.polygons && pass > 1 && prev_est <= par.mem_limit; let dmin: i64 = (0..tree.n_global()).filter(|&i| win.inc[i]).map(|i| tri(win.l[i])).sum(); let mut cap = 0i64; for (ki, &k) in ks.iter().enumerate() { for &n in &cands[ki] { cap = cap.max(count_of(n) - k - dmin); } } let td = Instant::now(); let dp = build_dp(&tree, &win, cap, keep); st.secs_dp += td.elapsed().as_secs_f64(); st.dp_nodes = dp.nodes; st.items = dp.items; st.table_len = dp.table.f.len(); st.groups = dp.table.groups.len(); st.work += dp.table.work; st.choice_bytes = st.choice_bytes.max(dp.table.choice_bytes); have_choices = keep; st.pass_log.push_str(&format!( "[pass {} len={} groups={} items={} work={} (smawk {}, naive {}) dp={:.3}s (direct {:.3}s smawk {:.3}s)] ", pass, dp.table.f.len(), dp.table.groups.len(), dp.items, dp.table.work, dp.table.work_smawk, dp.table.work_naive, td.elapsed().as_secs_f64(), dp.table.secs_direct, dp.table.secs_smawk )); let bests: Vec> = ks.iter().enumerate().map(|(ki, &k)| best_for(k, &dp, &cands[ki])).collect(); if bests.iter().any(|b| b.is_none()) { // heuristic windows too expensive for some count: drop compulsory parts for i in 0..win.inc.len() { win.l[i] = 0; } continue; } let ce = make_cert(&tree, &win, lam); let mut ds = f64::NEG_INFINITY; let mut kc: Vec = vec![]; for (ki, &k) in ks.iter().enumerate() { let c = certify_k(k, lam, &dp, &ce, bests[ki].as_ref().unwrap(), eps); ds = ds.max(c.delta_star); kc.push(c); } let ds = ds + eps + par.inflate; st.delta_star = ds; let req = match required_windows(&tree, lam, ds, &order0) { Some(r) => r, None => { z /= 4.0; st.tree_rebuilds += 1; continue 'outer; } }; let covered = win.contains(&req) && ks.iter().enumerate().all(|(ki, &k)| { kc[ki].feasible.iter().all(|&n| cands[ki].contains(&n) || count_of(n) - k - dp.d < 0) }); let est: usize = dp .table .groups .iter() .map(|g| g.len_after * if g.owners.len() < 256 { 1 } else { 2 }) .sum(); prev_est = est; let recon = par.polygons && !have_choices && est > par.mem_limit && pass > 1; if covered && (have_choices || !par.polygons || recon) { // certified let mut out = vec![]; let mut cnt = vec![0i64; tree.n_global()]; for (ki, &k) in ks.iter().enumerate() { let kb = bests[ki].as_ref().unwrap(); let (a, b) = rect(kb.n); let mut r = KResult { k, m, perimeter: kb.perim, a, b, certified: true, delta_star: kc[ki].delta_star, n_feasible: kc[ki].feasible.len(), vertices: None, nverts: 0, boundary: 0, longest_edge: 0.0, longest_steps: 0, check_ok: None, check_msg: String::new(), }; if par.polygons { let mut touched = vec![]; if have_choices { dp.table.traceback(kb.w, |o| { cnt[o as usize] += 1; touched.push(o); }); } else { crate::dp::reconstruct(&dp.by_weight, kb.w, par.mem_limit, &mut |o| { cnt[o as usize] += 1; touched.push(o); }); } let depth = |g: usize| if win.inc[g] { win.l[g] + cnt[g] } else { 0 }; let verts = polygon::vertices(&tree, a, b, &depth); for o in touched { cnt[o as usize] = 0; } let ch = polygon::check(&verts); let tol = 1e-9 * (1.0 + kb.perim); let ok = ch.convex && ch.count == k as i128 && (ch.perimeter - kb.perim).abs() <= tol; r.boundary = ch.boundary as i64; r.longest_edge = ch.longest_edge; r.longest_steps = ch.longest_steps; r.check_msg = format!( "convex={} pick_count={} perim_vertices={:.12} perim_table={:.12}", ch.convex, ch.count, ch.perimeter, kb.perim ); r.check_ok = Some(ok); r.vertices = Some(verts); } out.push(r); } st.secs = t0.elapsed().as_secs_f64(); return (out, st); } // next pass: the required windows (plus the current ones if the // requirement is not yet satisfied by a certified pass) win = req; for (ki, _) in ks.iter().enumerate() { let f = &kc[ki].feasible; cands[ki] = if par.inflate > 0.0 && !f.is_empty() { ((f[0] - 2)..=(f[f.len() - 1] + 2)).filter(|&n| n >= 0).collect() } else { f.clone() }; } } panic!("radius {}: certification did not converge in {} passes", m, par.max_passes); } }