//! The four Stern--Brocot trees of cut directions (Section 2 of the paper). //! //! We generate the first-quadrant tree (generators (1,0),(0,1)) down to a //! cutoff on the unit saving sigma, and obtain the other three quadrants by //! rotating by 90 degrees. A *global* node id is `quad * nq + local`. pub type V2 = (i64, i64); /// Rotate by 90 degrees counterclockwise `r` times. pub fn rot(v: V2, r: usize) -> V2 { let mut v = v; for _ in 0..(r % 4) { v = (-v.1, v.0); } v } fn norm(v: V2) -> f64 { ((v.0 as f64) * (v.0 as f64) + (v.1 as f64) * (v.1 as f64)).sqrt() } /// Unit saving |p| + |q| - |p+q| computed by the rationalized formula /// 2 / ((|p||q| + p.q)(|p| + |q| + |p+q|)), which has no cancellation. pub fn unit_saving(p: V2, q: V2) -> f64 { let a = norm(p); let b = norm(q); let s = norm((p.0 + q.0, p.1 + q.1)); let d = (p.0 * q.0 + p.1 * q.1) as f64; 2.0 / ((a * b + d) * (a + b + s)) } pub const NONE: u32 = u32::MAX; /// First-quadrant tree, nodes in pre-order (parents before children). /// Generator references: 0 = p0 axis, 1 = q0 axis, 2 + i = node i. pub struct Tree { pub cutoff: f64, pub vecs: Vec, pub sigma: Vec, pub parent: Vec, pub left: Vec, pub right: Vec, pub gen_p: Vec, pub gen_q: Vec, } impl Tree { /// All nodes with sigma >= z (closed under ancestors since sigma /// strictly decreases down the tree). pub fn build(z: f64) -> Tree { let mut t = Tree { cutoff: z, vecs: vec![], sigma: vec![], parent: vec![], left: vec![], right: vec![], gen_p: vec![], gen_q: vec![], }; // stack entries: (p, q, gen_p, gen_q, parent, is_left) let mut stack: Vec<(V2, V2, u32, u32, u32, bool)> = vec![((1, 0), (0, 1), 0, 1, NONE, false)]; while let Some((p, q, gp, gq, par, is_left)) = stack.pop() { let s = unit_saving(p, q); if s < z { continue; } let id = t.vecs.len() as u32; let v = (p.0 + q.0, p.1 + q.1); t.vecs.push(v); t.sigma.push(s); t.parent.push(par); t.left.push(NONE); t.right.push(NONE); t.gen_p.push(gp); t.gen_q.push(gq); if par != NONE { if is_left { t.left[par as usize] = id; } else { t.right[par as usize] = id; } } // push right first so left is processed first (pre-order) stack.push((v, q, id + 2, gq, id, false)); stack.push((p, v, gp, id + 2, id, true)); } t } pub fn nq(&self) -> usize { self.vecs.len() } pub fn n_global(&self) -> usize { 4 * self.vecs.len() } #[inline] pub fn sig(&self, g: usize) -> f64 { self.sigma[g % self.nq()] } }