omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / evidence / AT1 / replication-macbook / 20261010T051932Z-ff81466-mac / hidden-set-reveal / cases / at1h.rs
| 1 | // at1h.rs: AT-1 Agent 7 hidden-set generator and exact checker. |
| 2 | // Rust std only. No crates, no Cargo, no Python. Built with: rustc -O at1h.rs |
| 3 | // All quantities are exact rationals or Gaussian rationals (own bignum below). |
| 4 | // Modes: |
| 5 | // at1h selftest <worked_example_file> digest self-test + spec table self-tests |
| 6 | // at1h gen <seed_hex> <out_dir> deterministic hidden set from a 64-bit seed |
| 7 | use std::cmp::Ordering; |
| 8 | use std::io::Write; |
| 9 | use std::process::{Command, Stdio}; |
| 10 | |
| 11 | // ---------------------------------------------------------------- bignum |
| 12 | #[derive(Clone, PartialEq, Eq, Debug)] |
| 13 | struct Nat(Vec<u32>); |
| 14 | |
| 15 | impl Nat { |
| 16 | fn zero() -> Nat { Nat(Vec::new()) } |
| 17 | fn from_u64(x: u64) -> Nat { let mut n = Nat(vec![x as u32, (x >> 32) as u32]); n.trim(); n } |
| 18 | fn trim(&mut self) { while let Some(&0) = self.0.last() { self.0.pop(); } } |
| 19 | fn is_zero(&self) -> bool { self.0.is_empty() } |
| 20 | fn cmpn(&self, o: &Nat) -> Ordering { |
| 21 | if self.0.len() != o.0.len() { return self.0.len().cmp(&o.0.len()); } |
| 22 | for i in (0..self.0.len()).rev() { |
| 23 | if self.0[i] != o.0[i] { return self.0[i].cmp(&o.0[i]); } |
| 24 | } |
| 25 | Ordering::Equal |
| 26 | } |
| 27 | fn add(&self, o: &Nat) -> Nat { |
| 28 | let n = self.0.len().max(o.0.len()); |
| 29 | let mut r = Vec::with_capacity(n + 1); |
| 30 | let mut c = 0u64; |
| 31 | for i in 0..n { |
| 32 | let s = *self.0.get(i).unwrap_or(&0) as u64 + *o.0.get(i).unwrap_or(&0) as u64 + c; |
| 33 | r.push(s as u32); |
| 34 | c = s >> 32; |
| 35 | } |
| 36 | if c > 0 { r.push(c as u32); } |
| 37 | let mut x = Nat(r); x.trim(); x |
| 38 | } |
| 39 | fn sub(&self, o: &Nat) -> Nat { |
| 40 | assert!(self.cmpn(o) != Ordering::Less, "Nat::sub underflow"); |
| 41 | let mut r = Vec::with_capacity(self.0.len()); |
| 42 | let mut b = 0i64; |
| 43 | for i in 0..self.0.len() { |
| 44 | let mut d = self.0[i] as i64 - *o.0.get(i).unwrap_or(&0) as i64 - b; |
| 45 | if d < 0 { d += 1i64 << 32; b = 1; } else { b = 0; } |
| 46 | r.push(d as u32); |
| 47 | } |
| 48 | assert!(b == 0); |
| 49 | let mut x = Nat(r); x.trim(); x |
| 50 | } |
| 51 | fn mul(&self, o: &Nat) -> Nat { |
| 52 | if self.is_zero() || o.is_zero() { return Nat::zero(); } |
| 53 | let (n, m) = (self.0.len(), o.0.len()); |
| 54 | let mut r = vec![0u32; n + m + 1]; |
| 55 | for i in 0..n { |
| 56 | let a = self.0[i] as u64; |
| 57 | let mut carry = 0u64; |
| 58 | for j in 0..m { |
| 59 | let t = a * (o.0[j] as u64) + r[i + j] as u64 + carry; |
| 60 | r[i + j] = t as u32; |
| 61 | carry = t >> 32; |
| 62 | } |
| 63 | let mut k = i + m; |
| 64 | while carry > 0 { |
| 65 | let t = r[k] as u64 + carry; |
| 66 | r[k] = t as u32; |
| 67 | carry = t >> 32; |
| 68 | k += 1; |
| 69 | } |
| 70 | } |
| 71 | let mut x = Nat(r); x.trim(); x |
| 72 | } |
| 73 | fn bits(&self) -> usize { |
| 74 | if self.is_zero() { 0 } else { self.0.len() * 32 - self.0.last().unwrap().leading_zeros() as usize } |
| 75 | } |
| 76 | fn bit(&self, i: usize) -> bool { let w = i / 32; w < self.0.len() && (self.0[w] >> (i % 32)) & 1 == 1 } |
| 77 | fn shl1_or(&self, b: bool) -> Nat { |
| 78 | let mut r = Vec::with_capacity(self.0.len() + 1); |
| 79 | let mut c = b as u32; |
| 80 | for &x in &self.0 { r.push((x << 1) | c); c = x >> 31; } |
| 81 | if c != 0 { r.push(c); } |
| 82 | let mut n = Nat(r); n.trim(); n |
| 83 | } |
| 84 | fn divrem(&self, d: &Nat) -> (Nat, Nat) { |
| 85 | assert!(!d.is_zero(), "division by zero"); |
| 86 | if self.cmpn(d) == Ordering::Less { return (Nat::zero(), self.clone()); } |
| 87 | let nb = self.bits(); |
| 88 | let mut q = vec![0u32; self.0.len()]; |
| 89 | let mut r = Nat::zero(); |
| 90 | for i in (0..nb).rev() { |
| 91 | r = r.shl1_or(self.bit(i)); |
| 92 | if r.cmpn(d) != Ordering::Less { r = r.sub(d); q[i / 32] |= 1 << (i % 32); } |
| 93 | } |
| 94 | let mut qn = Nat(q); qn.trim(); |
| 95 | (qn, r) |
| 96 | } |
| 97 | fn gcd(a: &Nat, b: &Nat) -> Nat { |
| 98 | let (mut x, mut y) = (a.clone(), b.clone()); |
| 99 | while !y.is_zero() { let (_, r) = x.divrem(&y); x = y; y = r; } |
| 100 | x |
| 101 | } |
| 102 | fn pow2(k: usize) -> Nat { let mut v = vec![0u32; k / 32 + 1]; v[k / 32] = 1 << (k % 32); Nat(v) } |
| 103 | fn isqrt(&self) -> Nat { |
| 104 | if self.is_zero() { return Nat::zero(); } |
| 105 | let mut x = Nat::pow2(self.bits() / 2 + 1); |
| 106 | let two = Nat::from_u64(2); |
| 107 | loop { |
| 108 | let (q, _) = self.divrem(&x); |
| 109 | let (y, _) = x.add(&q).divrem(&two); |
| 110 | if y.cmpn(&x) != Ordering::Less { return x; } |
| 111 | x = y; |
| 112 | } |
| 113 | } |
| 114 | fn to_dec(&self) -> String { |
| 115 | if self.is_zero() { return "0".to_string(); } |
| 116 | let base = Nat::from_u64(1_000_000_000); |
| 117 | let mut parts = Vec::new(); |
| 118 | let mut x = self.clone(); |
| 119 | while !x.is_zero() { |
| 120 | let (q, r) = x.divrem(&base); |
| 121 | parts.push(if r.is_zero() { 0 } else { r.0[0] }); |
| 122 | x = q; |
| 123 | } |
| 124 | let mut s = format!("{}", parts.last().unwrap()); |
| 125 | for p in parts.iter().rev().skip(1) { s.push_str(&format!("{:09}", p)); } |
| 126 | s |
| 127 | } |
| 128 | fn to_f64(&self) -> f64 { self.0.iter().rev().fold(0.0, |acc, &l| acc * 4294967296.0 + l as f64) } |
| 129 | } |
| 130 | |
| 131 | #[derive(Clone, PartialEq, Eq, Debug)] |
| 132 | struct Int { neg: bool, mag: Nat } |
| 133 | |
| 134 | impl Int { |
| 135 | fn mk(neg: bool, mag: Nat) -> Int { let neg = neg && !mag.is_zero(); Int { neg, mag } } |
| 136 | fn from_i64(x: i64) -> Int { Int::mk(x < 0, Nat::from_u64(x.unsigned_abs())) } |
| 137 | fn pos(m: &Nat) -> Int { Int::mk(false, m.clone()) } |
| 138 | fn is_zero(&self) -> bool { self.mag.is_zero() } |
| 139 | fn negate(&self) -> Int { Int::mk(!self.neg, self.mag.clone()) } |
| 140 | fn add(&self, o: &Int) -> Int { |
| 141 | if self.neg == o.neg { return Int::mk(self.neg, self.mag.add(&o.mag)); } |
| 142 | match self.mag.cmpn(&o.mag) { |
| 143 | Ordering::Less => Int::mk(o.neg, o.mag.sub(&self.mag)), |
| 144 | _ => Int::mk(self.neg, self.mag.sub(&o.mag)), |
| 145 | } |
| 146 | } |
| 147 | fn mul(&self, o: &Int) -> Int { Int::mk(self.neg != o.neg, self.mag.mul(&o.mag)) } |
| 148 | fn cmpi(&self, o: &Int) -> Ordering { |
| 149 | match (self.neg, o.neg) { |
| 150 | (false, true) => Ordering::Greater, |
| 151 | (true, false) => Ordering::Less, |
| 152 | (false, false) => self.mag.cmpn(&o.mag), |
| 153 | (true, true) => o.mag.cmpn(&self.mag), |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | #[derive(Clone, PartialEq, Eq, Debug)] |
| 159 | struct Q { n: Int, d: Nat } |
| 160 | |
| 161 | impl Q { |
| 162 | fn new(n: Int, d: Nat) -> Q { |
| 163 | assert!(!d.is_zero()); |
| 164 | if n.is_zero() { return Q { n: Int::from_i64(0), d: Nat::from_u64(1) }; } |
| 165 | let g = Nat::gcd(&n.mag, &d); |
| 166 | let (nm, _) = n.mag.divrem(&g); |
| 167 | let (dm, _) = d.divrem(&g); |
| 168 | Q { n: Int::mk(n.neg, nm), d: dm } |
| 169 | } |
| 170 | fn r(a: i64, b: i64) -> Q { |
| 171 | assert!(b != 0); |
| 172 | Q::new(Int::mk((a < 0) != (b < 0), Nat::from_u64(a.unsigned_abs())), Nat::from_u64(b.unsigned_abs())) |
| 173 | } |
| 174 | fn i(a: i64) -> Q { Q::r(a, 1) } |
| 175 | fn zero() -> Q { Q::i(0) } |
| 176 | fn is_zero(&self) -> bool { self.n.is_zero() } |
| 177 | fn add(&self, o: &Q) -> Q { Q::new(self.n.mul(&Int::pos(&o.d)).add(&o.n.mul(&Int::pos(&self.d))), self.d.mul(&o.d)) } |
| 178 | fn neg(&self) -> Q { Q { n: self.n.negate(), d: self.d.clone() } } |
| 179 | fn sub(&self, o: &Q) -> Q { self.add(&o.neg()) } |
| 180 | fn mul(&self, o: &Q) -> Q { Q::new(self.n.mul(&o.n), self.d.mul(&o.d)) } |
| 181 | fn div(&self, o: &Q) -> Q { |
| 182 | assert!(!o.is_zero(), "Q div by zero"); |
| 183 | Q::new(Int::mk(self.n.neg != o.n.neg, self.n.mag.mul(&o.d)), self.d.mul(&o.n.mag)) |
| 184 | } |
| 185 | fn abs(&self) -> Q { Q { n: Int::pos(&self.n.mag), d: self.d.clone() } } |
| 186 | fn cmpq(&self, o: &Q) -> Ordering { self.n.mul(&Int::pos(&o.d)).cmpi(&o.n.mul(&Int::pos(&self.d))) } |
| 187 | fn is_neg(&self) -> bool { self.n.neg } |
| 188 | // |self| >= num/den |
| 189 | fn abs_ge(&self, num: u64, den: u64) -> bool { |
| 190 | self.n.mag.mul(&Nat::from_u64(den)).cmpn(&Nat::from_u64(num).mul(&self.d)) != Ordering::Less |
| 191 | } |
| 192 | fn to_s(&self) -> String { format!("{}{}/{}", if self.n.neg { "-" } else { "" }, self.n.mag.to_dec(), self.d.to_dec()) } |
| 193 | fn to_f64(&self) -> f64 { let v = self.n.mag.to_f64() / self.d.to_f64(); if self.n.neg { -v } else { v } } |
| 194 | fn in_token_limit(&self) -> bool { |
| 195 | let lim = Nat::from_u64(1048576); |
| 196 | self.n.mag.cmpn(&lim) != Ordering::Greater && self.d.cmpn(&lim) != Ordering::Greater |
| 197 | } |
| 198 | fn sqrt_exact(&self) -> Option<Q> { |
| 199 | if self.is_neg() { return None; } |
| 200 | let a = self.n.mag.isqrt(); |
| 201 | let b = self.d.isqrt(); |
| 202 | if a.mul(&a) != self.n.mag || b.mul(&b) != self.d { return None; } |
| 203 | Some(Q::new(Int::pos(&a), b)) |
| 204 | } |
| 205 | // exact integer value if this rational is an integer |
| 206 | fn as_int(&self) -> Option<i64> { |
| 207 | if self.d != Nat::from_u64(1) { return None; } |
| 208 | let m = self.n.mag.to_f64(); |
| 209 | if m > 1e15 { return None; } |
| 210 | let v = m as i64; |
| 211 | Some(if self.n.neg { -v } else { v }) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | #[derive(Clone, PartialEq, Eq, Debug)] |
| 216 | struct G { re: Q, im: Q } |
| 217 | |
| 218 | impl G { |
| 219 | fn new(re: Q, im: Q) -> G { G { re, im } } |
| 220 | fn re(q: Q) -> G { G { re: q, im: Q::zero() } } |
| 221 | fn zero() -> G { G::re(Q::zero()) } |
| 222 | fn is_zero(&self) -> bool { self.re.is_zero() && self.im.is_zero() } |
| 223 | fn add(&self, o: &G) -> G { G::new(self.re.add(&o.re), self.im.add(&o.im)) } |
| 224 | fn sub(&self, o: &G) -> G { G::new(self.re.sub(&o.re), self.im.sub(&o.im)) } |
| 225 | fn mul(&self, o: &G) -> G { |
| 226 | G::new(self.re.mul(&o.re).sub(&self.im.mul(&o.im)), self.re.mul(&o.im).add(&self.im.mul(&o.re))) |
| 227 | } |
| 228 | fn conj(&self) -> G { G::new(self.re.clone(), self.im.neg()) } |
| 229 | fn norm2(&self) -> Q { self.re.mul(&self.re).add(&self.im.mul(&self.im)) } |
| 230 | fn scale(&self, q: &Q) -> G { G::new(self.re.mul(q), self.im.mul(q)) } |
| 231 | fn ipow(m: i64) -> G { |
| 232 | match m.rem_euclid(4) { |
| 233 | 0 => G::re(Q::i(1)), |
| 234 | 1 => G::new(Q::zero(), Q::i(1)), |
| 235 | 2 => G::re(Q::i(-1)), |
| 236 | _ => G::new(Q::zero(), Q::i(-1)), |
| 237 | } |
| 238 | } |
| 239 | fn to_s(&self) -> String { format!("({};{})", self.re.to_s(), self.im.to_s()) } |
| 240 | } |
| 241 | |
| 242 | type V2 = [G; 2]; |
| 243 | fn v2_add(a: &V2, b: &V2) -> V2 { [a[0].add(&b[0]), a[1].add(&b[1])] } |
| 244 | fn v2_scale_g(a: &V2, g: &G) -> V2 { [a[0].mul(g), a[1].mul(g)] } |
| 245 | fn v2_norm2(a: &V2) -> Q { a[0].norm2().add(&a[1].norm2()) } |
| 246 | fn v2_inner(a: &V2, b: &V2) -> G { a[0].conj().mul(&b[0]).add(&a[1].conj().mul(&b[1])) } // <a|b> |
| 247 | fn v2_zero() -> V2 { [G::zero(), G::zero()] } |
| 248 | fn v2_is_zero(a: &V2) -> bool { a[0].is_zero() && a[1].is_zero() } |
| 249 | |
| 250 | // ---------------------------------------------------------------- sha256 via shasum |
| 251 | fn sha256_hex(bytes: &[u8]) -> String { |
| 252 | let mut child = Command::new("/usr/bin/shasum").args(["-a", "256"]) |
| 253 | .stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().expect("spawn shasum"); |
| 254 | child.stdin.take().unwrap().write_all(bytes).unwrap(); |
| 255 | let out = child.wait_with_output().expect("shasum"); |
| 256 | let s = String::from_utf8(out.stdout).unwrap(); |
| 257 | let h = s[..64].to_string(); |
| 258 | assert!(h.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())); |
| 259 | h |
| 260 | } |
| 261 | |
| 262 | fn block(lines: &[String], begin: &str, end: &str) -> Vec<u8> { |
| 263 | let b = lines.iter().position(|l| l == begin).expect("begin"); |
| 264 | let e = lines.iter().position(|l| l == end).expect("end"); |
| 265 | let mut v = Vec::new(); |
| 266 | for l in &lines[b..=e] { v.extend_from_slice(l.as_bytes()); v.push(b'\n'); } |
| 267 | v |
| 268 | } |
| 269 | |
| 270 | fn tagged(tag: &str, body: &[u8]) -> String { |
| 271 | let mut v = tag.as_bytes().to_vec(); |
| 272 | v.push(0); |
| 273 | v.extend_from_slice(body); |
| 274 | sha256_hex(&v) |
| 275 | } |
| 276 | |
| 277 | // recompute case_id and acceptance_id lines from the blocks (AT1_CASE_V1 section 5) |
| 278 | fn fix_ids(text: &str) -> String { |
| 279 | let mut lines: Vec<String> = text.split_terminator('\n').map(|s| s.to_string()).collect(); |
| 280 | let cid = tagged("omega.at1.case.v1", &block(&lines, "begin semantic", "end semantic")); |
| 281 | let aid = tagged("omega.at1.acceptance.v1", &block(&lines, "begin acceptance", "end acceptance")); |
| 282 | for l in lines.iter_mut() { |
| 283 | if l.starts_with("case_id ") { *l = format!("case_id {}", cid); } |
| 284 | if l.starts_with("acceptance_id ") { *l = format!("acceptance_id {}", aid); } |
| 285 | } |
| 286 | let mut s = lines.join("\n"); |
| 287 | s.push('\n'); |
| 288 | s |
| 289 | } |
| 290 | |
| 291 | // ---------------------------------------------------------------- case model |
| 292 | #[derive(Clone, Debug)] |
| 293 | struct Case { |
| 294 | name: String, |
| 295 | e: Vec<Q>, |
| 296 | h0: Q, |
| 297 | h: [Q; 3], |
| 298 | v: Vec<[Q; 3]>, |
| 299 | r: usize, |
| 300 | psi: V2, |
| 301 | tau: Q, |
| 302 | w: Q, |
| 303 | m: usize, |
| 304 | control: String, |
| 305 | target: String, |
| 306 | outcome: String, |
| 307 | codes: Vec<String>, |
| 308 | } |
| 309 | |
| 310 | fn render(c: &Case) -> String { |
| 311 | let mut s = String::new(); |
| 312 | let mut p = |l: String| { s.push_str(&l); s.push('\n'); }; |
| 313 | p("OMEGA-AT1-CASE v1".into()); |
| 314 | p("domain omega.at1.case.v1".into()); |
| 315 | p("contract AT1_CASE_V1".into()); |
| 316 | p(format!("case_name {}", c.name)); |
| 317 | p("begin semantic".into()); |
| 318 | p("model_family PAGE_WOOTTERS_FINITE_CLOCKDIAG".into()); |
| 319 | p("energy_unit DIMENSIONLESS_HBAR_1".into()); |
| 320 | p(format!("clock_dim {}", c.e.len())); |
| 321 | p(format!("clock_energies {}", c.e.iter().map(|q| q.to_s()).collect::<Vec<_>>().join(","))); |
| 322 | p("system_dim 2".into()); |
| 323 | p(format!("system_hamiltonian_pauli {},{},{},{}", c.h0.to_s(), c.h[0].to_s(), c.h[1].to_s(), c.h[2].to_s())); |
| 324 | p("interaction CLOCK_DIAGONAL_PAULI".into()); |
| 325 | for (j, v) in c.v.iter().enumerate() { |
| 326 | p(format!("interaction_pauli {} {},{},{}", j, v[0].to_s(), v[1].to_s(), v[2].to_s())); |
| 327 | } |
| 328 | p("constraint SUM_HC_HS_V".into()); |
| 329 | p("physical_state NULLSPACE_PROJECTION".into()); |
| 330 | p(format!("reference_clock_label t{}", c.r)); |
| 331 | p(format!("reference_system_state {},{}", c.psi[0].to_s(), c.psi[1].to_s())); |
| 332 | p("clock_povm COVARIANT_DISCRETE".into()); |
| 333 | p(format!("povm_tau_turns {}", c.tau.to_s())); |
| 334 | p(format!("povm_weight {}", c.w.to_s())); |
| 335 | p(format!("clock_label_count {}", c.m)); |
| 336 | for k in 0..c.m { p(format!("clock_label {} t{}", k, k)); } |
| 337 | p("observables PAULI_X,PAULI_Y,PAULI_Z".into()); |
| 338 | p("end semantic".into()); |
| 339 | p("begin acceptance".into()); |
| 340 | p(format!("control_kind {}", c.control)); |
| 341 | p(format!("prediction_target {}", c.target)); |
| 342 | p(format!("expected_outcome {}", c.outcome)); |
| 343 | p(format!("expected_failure_codes {}", if c.codes.is_empty() { "none".to_string() } else { c.codes.join(",") })); |
| 344 | p("min_bound_kind ESTIMATED".into()); |
| 345 | p("tol_constraint_residual 1@12".into()); |
| 346 | p("tol_povm_residual 1@12".into()); |
| 347 | p("tol_probability 1@12".into()); |
| 348 | p("tol_zero_probability 1@9".into()); |
| 349 | p("tol_schrodinger 1@12".into()); |
| 350 | p("end acceptance".into()); |
| 351 | p("case_id X".into()); |
| 352 | p("acceptance_id X".into()); |
| 353 | p("end".into()); |
| 354 | fix_ids(&s) |
| 355 | } |
| 356 | |
| 357 | fn parse_q(t: &str) -> Result<Q, String> { |
| 358 | let (a, b) = t.split_once('/').ok_or(format!("not rational: {}", t))?; |
| 359 | let a: i64 = a.parse().map_err(|_| format!("bad num {}", t))?; |
| 360 | let b: i64 = b.parse().map_err(|_| format!("bad den {}", t))?; |
| 361 | let q = Q::r(a, b); |
| 362 | if q.to_s() != t { return Err(format!("noncanonical {}", t)); } |
| 363 | Ok(q) |
| 364 | } |
| 365 | fn parse_g(t: &str) -> Result<G, String> { |
| 366 | let inner = t.strip_prefix('(').and_then(|x| x.strip_suffix(')')).ok_or("bad complex")?; |
| 367 | let (a, b) = inner.split_once(';').ok_or("bad complex")?; |
| 368 | Ok(G::new(parse_q(a)?, parse_q(b)?)) |
| 369 | } |
| 370 | |
| 371 | // strict reader for files of the AT1_CASE_V1 shape written by this tool (and the worked example) |
| 372 | fn parse_case(text: &str) -> Result<Case, String> { |
| 373 | if !text.ends_with('\n') || text.contains('\r') { return Err("bad line endings".into()); } |
| 374 | let lines: Vec<&str> = text.split_terminator('\n').collect(); |
| 375 | let mut i = 0usize; |
| 376 | let mut take = |key: &str| -> Result<String, String> { |
| 377 | let l = *lines.get(i).ok_or("short file")?; |
| 378 | i += 1; |
| 379 | if key.ends_with(' ') { |
| 380 | l.strip_prefix(key).map(|s| s.to_string()).ok_or(format!("line {}: expected {}", i, key)) |
| 381 | } else if l == key { Ok(String::new()) } else { Err(format!("line {}: expected {}", i, key)) } |
| 382 | }; |
| 383 | take("OMEGA-AT1-CASE v1")?; take("domain omega.at1.case.v1")?; take("contract AT1_CASE_V1")?; |
| 384 | let name = take("case_name ")?; |
| 385 | take("begin semantic")?; take("model_family PAGE_WOOTTERS_FINITE_CLOCKDIAG")?; take("energy_unit DIMENSIONLESS_HBAR_1")?; |
| 386 | let n: usize = take("clock_dim ")?.parse().map_err(|_| "clock_dim")?; |
| 387 | let e: Vec<Q> = take("clock_energies ")?.split(',').map(parse_q).collect::<Result<_, _>>()?; |
| 388 | if e.len() != n { return Err("energies count".into()); } |
| 389 | take("system_dim 2")?; |
| 390 | let hs: Vec<Q> = take("system_hamiltonian_pauli ")?.split(',').map(parse_q).collect::<Result<_, _>>()?; |
| 391 | if hs.len() != 4 { return Err("hs".into()); } |
| 392 | take("interaction CLOCK_DIAGONAL_PAULI")?; |
| 393 | let mut v = Vec::new(); |
| 394 | for j in 0..n { |
| 395 | let rest = take(&format!("interaction_pauli {} ", j))?; |
| 396 | let c: Vec<Q> = rest.split(',').map(parse_q).collect::<Result<_, _>>()?; |
| 397 | if c.len() != 3 { return Err("v".into()); } |
| 398 | v.push([c[0].clone(), c[1].clone(), c[2].clone()]); |
| 399 | } |
| 400 | take("constraint SUM_HC_HS_V")?; take("physical_state NULLSPACE_PROJECTION")?; |
| 401 | let rl = take("reference_clock_label ")?; |
| 402 | let ps: Vec<G> = take("reference_system_state ")?.split(',').map(parse_g).collect::<Result<_, _>>()?; |
| 403 | if ps.len() != 2 { return Err("psi".into()); } |
| 404 | take("clock_povm COVARIANT_DISCRETE")?; |
| 405 | let tau = parse_q(&take("povm_tau_turns ")?)?; |
| 406 | let w = parse_q(&take("povm_weight ")?)?; |
| 407 | let m: usize = take("clock_label_count ")?.parse().map_err(|_| "m")?; |
| 408 | let mut labels = Vec::new(); |
| 409 | for k in 0..m { labels.push(take(&format!("clock_label {} ", k))?); } |
| 410 | take("observables PAULI_X,PAULI_Y,PAULI_Z")?; take("end semantic")?; take("begin acceptance")?; |
| 411 | let control = take("control_kind ")?; |
| 412 | let target = take("prediction_target ")?; |
| 413 | let outcome = take("expected_outcome ")?; |
| 414 | let codes_s = take("expected_failure_codes ")?; |
| 415 | let codes: Vec<String> = if codes_s == "none" { vec![] } else { codes_s.split(',').map(|s| s.to_string()).collect() }; |
| 416 | take("min_bound_kind ESTIMATED")?; |
| 417 | take("tol_constraint_residual 1@12")?; take("tol_povm_residual 1@12")?; take("tol_probability 1@12")?; |
| 418 | take("tol_zero_probability 1@9")?; take("tol_schrodinger 1@12")?; take("end acceptance")?; |
| 419 | take("case_id ")?; take("acceptance_id ")?; take("end")?; |
| 420 | if i != lines.len() { return Err("trailing lines".into()); } |
| 421 | let r = labels.iter().position(|l| *l == rl).ok_or("reference label missing")?; |
| 422 | Ok(Case { name, e, h0: hs[0].clone(), h: [hs[1].clone(), hs[2].clone(), hs[3].clone()], v, r, |
| 423 | psi: [ps[0].clone(), ps[1].clone()], tau, w, m, control, target, outcome, codes }) |
| 424 | } |
| 425 | |
| 426 | // ---------------------------------------------------------------- exact physics (AT1_CASE_V1 s3, AT1_SPEC 13.1) |
| 427 | struct Exact { |
| 428 | dim: usize, |
| 429 | psi_zero: bool, |
| 430 | p: Vec<Q>, // empty when trivial |
| 431 | pauli: Vec<Option<[Q; 3]>>, // plus-outcome X,Y,Z per label; None when p(k) = 0 |
| 432 | ideal: Vec<[Q; 3]>, |
| 433 | povm_res2: Q, |
| 434 | } |
| 435 | |
| 436 | fn eigvec(n: &[Q; 3], s: i64, rr: &Q) -> V2 { |
| 437 | let sr = rr.mul(&Q::i(s)); |
| 438 | let a = [G::re(sr.add(&n[2])), G::new(n[0].clone(), n[1].clone())]; |
| 439 | if !v2_is_zero(&a) { return a; } |
| 440 | [G::new(n[0].clone(), n[1].neg()), G::re(sr.sub(&n[2]))] |
| 441 | } |
| 442 | |
| 443 | fn pauli_plus(c: &V2) -> [Q; 3] { |
| 444 | let nrm = v2_norm2(c); |
| 445 | let x = c[0].conj().mul(&c[1]); |
| 446 | let half = Q::r(1, 2); |
| 447 | [half.add(&x.re.div(&nrm)), half.add(&x.im.div(&nrm)), c[0].norm2().div(&nrm)] |
| 448 | } |
| 449 | |
| 450 | // quarter-turn phase exp(2 pi i * turns) as i^(4*turns); error if 4*turns is not an integer |
| 451 | fn qphase(turns: &Q) -> Result<G, String> { |
| 452 | let m = turns.mul(&Q::i(4)).as_int().ok_or(format!("phase turn count {} not a quarter multiple", turns.to_s()))?; |
| 453 | Ok(G::ipow(m)) |
| 454 | } |
| 455 | |
| 456 | fn level_norm(h: &[Q; 3], v: &[Q; 3]) -> ([Q; 3], Q) { |
| 457 | let n = [h[0].add(&v[0]), h[1].add(&v[1]), h[2].add(&v[2])]; |
| 458 | let r2 = n[0].mul(&n[0]).add(&n[1].mul(&n[1])).add(&n[2].mul(&n[2])); |
| 459 | (n, r2) |
| 460 | } |
| 461 | |
| 462 | fn eval(c: &Case) -> Result<Exact, String> { |
| 463 | let nn = c.e.len(); |
| 464 | if nn < 2 || nn > 64 || c.v.len() != nn { return Err("clock_dim".into()); } |
| 465 | for j in 1..nn { if c.e[j].cmpq(&c.e[j - 1]) != Ordering::Greater { return Err("energies not increasing".into()); } } |
| 466 | if c.m < 1 || c.m > 256 || c.r >= c.m { return Err("labels".into()); } |
| 467 | if c.tau.is_neg() || c.tau.is_zero() || c.w.is_neg() || c.w.is_zero() { return Err("tau/w".into()); } |
| 468 | if v2_is_zero(&c.psi) { return Err("psi zero".into()); } |
| 469 | let mut dim = 0usize; |
| 470 | let mut u: Vec<V2> = vec![v2_zero(); nn]; |
| 471 | let mut any_nonzero = false; |
| 472 | for j in 0..nn { |
| 473 | let (n, r2) = level_norm(&c.h, &c.v[j]); |
| 474 | let rr = r2.sqrt_exact().ok_or(format!("level {} irrational spectrum", j))?; |
| 475 | let ej = c.e[j].add(&c.h0); |
| 476 | if rr.is_zero() { |
| 477 | if ej.is_zero() { dim += 2; u[j] = c.psi.clone(); any_nonzero = true; } |
| 478 | } else { |
| 479 | for s in [1i64, -1] { |
| 480 | if ej.add(&rr.mul(&Q::i(s))).is_zero() { |
| 481 | dim += 1; |
| 482 | let f = eigvec(&n, s, &rr); |
| 483 | let amp = v2_inner(&f, &c.psi); |
| 484 | if !amp.is_zero() { any_nonzero = true; } |
| 485 | u[j] = v2_add(&u[j], &v2_scale_g(&f, &).map(|g| g.scale(&Q::i(1).div(&v2_norm2(&f))))); |
| 486 | } |
| 487 | } |
| 488 | } |
| 489 | } |
| 490 | let psi_zero = dim > 0 && !any_nonzero; |
| 491 | let trivial = dim == 0 || psi_zero; |
| 492 | let mut p = Vec::new(); |
| 493 | let mut pauli = Vec::new(); |
| 494 | if !trivial { |
| 495 | let s_tot = u.iter().fold(Q::zero(), |a, x| a.add(&v2_norm2(x))); |
| 496 | let a = (0..nn).find(|&j| !v2_is_zero(&u[j])).unwrap(); |
| 497 | for k in 0..c.m { |
| 498 | let mut chi = v2_zero(); |
| 499 | let kr = Q::i(k as i64 - c.r as i64); |
| 500 | for j in 0..nn { |
| 501 | if v2_is_zero(&u[j]) { continue; } |
| 502 | let ph = qphase(&c.e[j].sub(&c.e[a]).mul(&kr).mul(&c.tau))?; |
| 503 | chi = v2_add(&chi, &v2_scale_g(&u[j], &ph)); |
| 504 | } |
| 505 | let pk = c.w.mul(&v2_norm2(&chi)).div(&Q::i(nn as i64).mul(&s_tot)); |
| 506 | pauli.push(if pk.is_zero() { None } else { Some(pauli_plus(&chi)) }); |
| 507 | p.push(pk); |
| 508 | } |
| 509 | } |
| 510 | // ideal reference: exp(-i H_S (t_k - t_r)) psi_0, H_S alone |
| 511 | let (_, h2) = level_norm(&c.h, &[Q::zero(), Q::zero(), Q::zero()]); |
| 512 | let hn = h2.sqrt_exact().ok_or("|h| irrational (not used by this generator)")?; |
| 513 | let mut ideal = Vec::new(); |
| 514 | for k in 0..c.m { |
| 515 | let st = if hn.is_zero() { c.psi.clone() } else { |
| 516 | let gp = eigvec(&c.h, 1, &hn); |
| 517 | let gm = eigvec(&c.h, -1, &hn); |
| 518 | let pp = v2_scale_g(&gp, &v2_inner(&gp, &c.psi)).map(|g| g.scale(&Q::i(1).div(&v2_norm2(&gp)))); |
| 519 | let pm = v2_scale_g(&gm, &v2_inner(&gm, &c.psi)).map(|g| g.scale(&Q::i(1).div(&v2_norm2(&gm)))); |
| 520 | let turns = hn.mul(&Q::i(-2)).mul(&Q::i(k as i64 - c.r as i64)).mul(&c.tau); |
| 521 | v2_add(&pm, &v2_scale_g(&pp, &qphase(&turns)?)) |
| 522 | }; |
| 523 | ideal.push(pauli_plus(&st)); |
| 524 | } |
| 525 | // POVM residual squared: || sum_k F_k - I ||_F^2 |
| 526 | let mut res2 = Q::zero(); |
| 527 | let wn = c.w.div(&Q::i(nn as i64)); |
| 528 | for i in 0..nn { |
| 529 | for j in 0..nn { |
| 530 | let mut s = G::zero(); |
| 531 | for k in 0..c.m { |
| 532 | s = s.add(&qphase(&c.e[i].sub(&c.e[j]).mul(&Q::i(-(k as i64))).mul(&c.tau))?); |
| 533 | } |
| 534 | let mut d = s.scale(&wn); |
| 535 | if i == j { d = d.sub(&G::re(Q::i(1))); } |
| 536 | res2 = res2.add(&d.norm2()); |
| 537 | } |
| 538 | } |
| 539 | Ok(Exact { dim, psi_zero, p, pauli, ideal, povm_res2: res2 }) |
| 540 | } |
| 541 | |
| 542 | // ---------------------------------------------------------------- judge (AT1_RESULT_V1 s4, s5) with the margin rule of AT1_SPEC 8.3 |
| 543 | #[allow(dead_code)] |
| 544 | const CHECKS: [&str; 12] = ["bound_kind_sufficient", "values_finite", "physical_state_nontrivial", "constraint_residual", |
| 545 | "povm_normalization", "clock_probability_sum", "probability_range", "pauli_pair_sum", "conditional_defined", |
| 546 | "target_agreement", "oracle_cross_check", "label_status_agreement"]; |
| 547 | |
| 548 | struct Verdict { checks: Vec<&'static str>, outcome: &'static str, codes: Vec<String> } |
| 549 | |
| 550 | // deviation d against tolerance 1e-12: Ok(false) if exactly 0, Ok(true) if >= 1e-9, Err otherwise |
| 551 | fn dev(d: &Q, what: &str) -> Result<bool, String> { |
| 552 | if d.is_zero() { return Ok(false); } |
| 553 | if d.abs_ge(1, 1_000_000_000) { return Ok(true); } |
| 554 | Err(format!("margin rule violated: {} deviation {:e}", what, d.to_f64())) |
| 555 | } |
| 556 | |
| 557 | fn judge(c: &Case, x: &Exact) -> Result<Verdict, String> { |
| 558 | let mut ch: Vec<&'static str> = vec!["PASS"; 12]; |
| 559 | let mut codes: Vec<&str> = Vec::new(); |
| 560 | // 1 bound kind: min ESTIMATED is met by an ESTIMATED or RIGOROUS engine; 2 finite |
| 561 | // 5 povm (evaluated even for a trivial kernel) |
| 562 | let povm_fail = if x.povm_res2.is_zero() { false } else if x.povm_res2.abs_ge(1, 1_000_000_000_000_000_000) { true } |
| 563 | else { return Err("margin rule violated: povm residual".into()); }; |
| 564 | if povm_fail { ch[4] = "FAIL"; codes.push("POVM_NORMALIZATION_EXCEEDED"); } |
| 565 | let trivial = x.dim == 0 || x.psi_zero; |
| 566 | if trivial { |
| 567 | ch[2] = "FAIL"; codes.push("TRIVIAL_PHYSICAL_STATE"); |
| 568 | for i in [3usize, 5, 6, 7, 8, 9, 10, 11] { ch[i] = "NOT_EVALUATED"; } |
| 569 | } else { |
| 570 | for pk in &x.p { if !pk.is_zero() && !pk.abs_ge(1, 1000) { return Err(format!("margin rule violated: p(k) = {:e}", pk.to_f64())); } } |
| 571 | let sum = x.p.iter().fold(Q::zero(), |a, b| a.add(b)); |
| 572 | if dev(&sum.sub(&Q::i(1)), "sum p")? { ch[5] = "FAIL"; codes.push("PROBABILITY_SUM_EXCEEDED"); } |
| 573 | // 7 range: signed distance outside [0,1] |
| 574 | let mut range_fail = false; |
| 575 | let mut vals: Vec<Q> = x.p.clone(); |
| 576 | for pl in x.pauli.iter().flatten() { for q in pl { vals.push(q.clone()); vals.push(Q::i(1).sub(q)); } } |
| 577 | for q in &vals { |
| 578 | let out = if q.is_neg() { q.neg() } else if q.cmpq(&Q::i(1)) == Ordering::Greater { q.sub(&Q::i(1)) } else { Q::zero() }; |
| 579 | if dev(&out, "range")? { range_fail = true; } |
| 580 | } |
| 581 | if range_fail { ch[6] = "FAIL"; codes.push("PROBABILITY_OUT_OF_RANGE"); } |
| 582 | // 8 pair sums: PLUS + MINUS = 1 exactly |
| 583 | // 9 defined |
| 584 | let defined: Vec<usize> = (0..c.m).filter(|&k| x.pauli[k].is_some()).collect(); |
| 585 | if defined.len() < c.m { ch[8] = "FAIL"; codes.push("CONDITIONAL_UNDEFINED"); } |
| 586 | if defined.is_empty() { ch[7] = "NOT_EVALUATED"; } |
| 587 | // 10 target agreement; 11 oracle cross-check (engine equals oracle exactly for a correct engine) |
| 588 | if defined.is_empty() { ch[9] = "NOT_EVALUATED"; ch[10] = "NOT_EVALUATED"; } |
| 589 | else if c.target == "IDEAL" { |
| 590 | let wn = c.w.div(&Q::i(c.e.len() as i64)); |
| 591 | let mut f = false; |
| 592 | for &k in &defined { |
| 593 | let pl = x.pauli[k].as_ref().unwrap(); |
| 594 | for a in 0..3 { if dev(&pl[a].sub(&x.ideal[k][a]), "pauli vs ideal")? { f = true; } } |
| 595 | if dev(&x.p[k].sub(&wn), "p vs w/N")? { f = true; } |
| 596 | } |
| 597 | if f { ch[9] = "FAIL"; codes.push("SCHRODINGER_DEVIATION_EXCEEDED"); } |
| 598 | } else { |
| 599 | ch[10] = "NOT_EVALUATED"; |
| 600 | } |
| 601 | if c.target == "INTERACTING" { ch[10] = "NOT_EVALUATED"; } |
| 602 | // 12 statuses agree (both sides apply the rule to the same exact p(k), margins keep them determinate) |
| 603 | } |
| 604 | codes.sort(); |
| 605 | codes.dedup(); |
| 606 | let outcome = if ch.iter().any(|s| *s == "FAIL") { "FAIL" } else { "PASS" }; |
| 607 | Ok(Verdict { checks: ch, outcome, codes: codes.iter().map(|s| s.to_string()).collect() }) |
| 608 | } |
| 609 | |
| 610 | // ---------------------------------------------------------------- self-tests against the frozen worked example and AT1_SPEC section 13 |
| 611 | fn qv(v: &[(i64, i64)]) -> Vec<Q> { v.iter().map(|&(a, b)| Q::r(a, b)).collect() } |
| 612 | fn gq(a: Q, b: Q) -> G { G::new(a, b) } |
| 613 | |
| 614 | fn spec_case(e: &[(i64, i64)], h0: (i64, i64), h: [(i64, i64); 3], v: &[[(i64, i64); 3]], psi: [(Q, Q); 2], |
| 615 | r: usize, tau: (i64, i64), w: (i64, i64), m: usize, target: &str) -> Case { |
| 616 | Case { name: "spec".into(), e: qv(e), h0: Q::r(h0.0, h0.1), h: [Q::r(h[0].0, h[0].1), Q::r(h[1].0, h[1].1), Q::r(h[2].0, h[2].1)], |
| 617 | v: v.iter().map(|x| [Q::r(x[0].0, x[0].1), Q::r(x[1].0, x[1].1), Q::r(x[2].0, x[2].1)]).collect(), r, |
| 618 | psi: [gq(psi[0].0.clone(), psi[0].1.clone()), gq(psi[1].0.clone(), psi[1].1.clone())], |
| 619 | tau: Q::r(tau.0, tau.1), w: Q::r(w.0, w.1), m, control: "POSITIVE".into(), target: target.into(), |
| 620 | outcome: "PASS".into(), codes: vec![] } |
| 621 | } |
| 622 | |
| 623 | fn expect_table(label: &str, x: &Exact, p: &[(i64, i64)], xs: &[(i64, i64)], ys: &[(i64, i64)], zs: &[(i64, i64)]) -> usize { |
| 624 | let mut bad = 0; |
| 625 | for k in 0..p.len() { |
| 626 | if x.p[k] != Q::r(p[k].0, p[k].1) { println!("FAIL {} p({}) = {} want {}/{}", label, k, x.p[k].to_s(), p[k].0, p[k].1); bad += 1; } |
| 627 | if xs.is_empty() { continue; } |
| 628 | let pl = x.pauli[k].as_ref().unwrap(); |
| 629 | let want = [Q::r(xs[k].0, xs[k].1), Q::r(ys[k].0, ys[k].1), Q::r(zs[k].0, zs[k].1)]; |
| 630 | for a in 0..3 { if pl[a] != want[a] { println!("FAIL {} k={} axis {} = {} want {}", label, k, a, pl[a].to_s(), want[a].to_s()); bad += 1; } } |
| 631 | } |
| 632 | bad |
| 633 | } |
| 634 | fn expect_ideal(label: &str, x: &Exact, rows: &[[(i64, i64); 3]]) -> usize { |
| 635 | let mut bad = 0; |
| 636 | for (k, row) in rows.iter().enumerate() { |
| 637 | for a in 0..3 { if x.ideal[k][a] != Q::r(row[a].0, row[a].1) { println!("FAIL {} ideal k={} axis {} = {}", label, k, a, x.ideal[k][a].to_s()); bad += 1; } } |
| 638 | } |
| 639 | bad |
| 640 | } |
| 641 | fn expect_verdict(label: &str, c: &Case, x: &Exact, outcome: &str, codes: &[&str], checks: &str) -> usize { |
| 642 | match judge(c, x) { |
| 643 | Err(e) => { println!("FAIL {} judge error {}", label, e); 1 } |
| 644 | Ok(v) => { |
| 645 | let cv = v.checks.iter().map(|s| match *s { "PASS" => "P", "FAIL" => "F", "NOT_EVALUATED" => "N", _ => "I" }).collect::<String>(); |
| 646 | if v.outcome != outcome || v.codes != codes.iter().map(|s| s.to_string()).collect::<Vec<_>>() || cv != checks { |
| 647 | println!("FAIL {} verdict {} {:?} {} (want {} {:?} {})", label, v.outcome, v.codes, cv, outcome, codes, checks); 1 |
| 648 | } else { println!("ok {} verdict {} {:?} {}", label, outcome, codes, cv); 0 } |
| 649 | } |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | fn selftest(worked: &str) -> usize { |
| 654 | let text = std::fs::read_to_string(worked).expect("read worked example"); |
| 655 | let mut bad = 0; |
| 656 | let lines: Vec<String> = text.split_terminator('\n').map(|s| s.to_string()).collect(); |
| 657 | let cid = tagged("omega.at1.case.v1", &block(&lines, "begin semantic", "end semantic")); |
| 658 | let aid = tagged("omega.at1.acceptance.v1", &block(&lines, "begin acceptance", "end acceptance")); |
| 659 | let fsha = sha256_hex(text.as_bytes()); |
| 660 | println!("worked example: lines {} case_id {} acceptance_id {} file {}", lines.len(), cid, aid, fsha); |
| 661 | if cid != "890980a43bd189494c2c922d2bf0049cbffb07f1090f578e04e1142aee7525f1" { println!("FAIL case_id"); bad += 1; } |
| 662 | if aid != "d63246c391296c6cd381f1b654cc625be9f453c77c27c68d9eac240efd5b4d8f" { println!("FAIL acceptance_id"); bad += 1; } |
| 663 | if fsha != "76e282fecf21025c9dd675378244e90ff192822a4c49d6cb812c9fe84b3f9ba4" { println!("FAIL file sha"); bad += 1; } |
| 664 | let c = parse_case(&text).expect("parse worked"); |
| 665 | let re = render(&c); |
| 666 | if re != text { println!("FAIL render(parse(worked)) is not byte-identical"); bad += 1; } else { println!("ok render(parse(worked)) byte-identical"); } |
| 667 | let x = eval(&c).unwrap(); |
| 668 | if x.dim != 2 { println!("FAIL P2 dim"); bad += 1; } |
| 669 | bad += expect_table("P2", &x, &[(5, 28), (1, 4), (9, 28), (1, 4)], &[(49, 50), (29, 70), (1, 10), (29, 70)], |
| 670 | &[(1, 2), (13, 14), (1, 2), (1, 14)], &[(16, 25), (26, 35), (4, 5), (26, 35)]); |
| 671 | bad += expect_ideal("P2", &x, &[[(1, 1), (1, 2), (1, 2)], [(1, 2), (1, 1), (1, 2)], [(0, 1), (1, 2), (1, 2)], [(1, 2), (0, 1), (1, 2)]]); |
| 672 | bad += expect_verdict("P2", &c, &x, "PASS", &[], "PPPPPPPPPPNP"); |
| 673 | let mut c1 = c.clone(); c1.target = "IDEAL".into(); |
| 674 | bad += expect_verdict("N1 (P2 target IDEAL)", &c1, &x, "FAIL", &["SCHRODINGER_DEVIATION_EXCEEDED"], "PPPPPPPPPFPP"); |
| 675 | |
| 676 | let one = |a: i64, b: i64| (Q::r(a, b), Q::zero()); |
| 677 | let z = (0i64, 1i64); |
| 678 | let b_e = [(-3, 2), (-1, 2), (1, 2), (3, 2)]; |
| 679 | let rho = [(3, 10), z, (-1, 10)]; |
| 680 | // P1 |
| 681 | let p1 = spec_case(&b_e, z, [z, z, (1, 2)], &[[z, z, z]; 4], [one(1, 1), one(1, 1)], 0, (1, 4), (1, 1), 4, "IDEAL"); |
| 682 | let x = eval(&p1).unwrap(); |
| 683 | bad += expect_table("P1", &x, &[(1, 4); 4], &[(1, 1), (1, 2), (0, 1), (1, 2)], &[(1, 2), (1, 1), (1, 2), (0, 1)], &[(1, 2); 4]); |
| 684 | bad += expect_verdict("P1b IDEAL", &p1, &x, "PASS", &[], "PPPPPPPPPPPP"); |
| 685 | // P1c |
| 686 | let p1c = spec_case(&b_e, z, [z, z, (1, 2)], &[[z, z, (1, 2)], [z, z, z], [z, z, z], rho], [one(1, 1), one(1, 1)], 0, (1, 4), (1, 1), 4, "IDEAL"); |
| 687 | let x = eval(&p1c).unwrap(); |
| 688 | bad += expect_verdict("P1c IDEAL", &p1c, &x, "PASS", &[], "PPPPPPPPPPPP"); |
| 689 | // P3 |
| 690 | let p3 = spec_case(&[(-1, 2), (1, 2), (3, 2)], z, [z, z, (1, 2)], &[rho, [z, (3, 10), (-1, 10)], [(6, 5), z, (2, 5)]], |
| 691 | [one(1, 1), one(1, 1)], 0, (1, 4), (3, 4), 4, "INTERACTING"); |
| 692 | let x = eval(&p3).unwrap(); |
| 693 | if x.dim != 3 { println!("FAIL P3 dim"); bad += 1; } |
| 694 | bad += expect_table("P3", &x, &[(107, 280), (53, 280), (5, 56), (19, 56)], &[(98, 107), (37, 53), (8, 25), (37, 95)], |
| 695 | &[(65, 214), (101, 106), (37, 50), (17, 190)], &[(65, 214), (61, 106), (9, 10), (29, 38)]); |
| 696 | bad += expect_verdict("P3", &p3, &x, "PASS", &[], "PPPPPPPPPPNP"); |
| 697 | let mut p3i = p3.clone(); p3i.target = "IDEAL".into(); |
| 698 | bad += expect_verdict("N1b (P3 IDEAL)", &p3i, &x, "FAIL", &["SCHRODINGER_DEVIATION_EXCEEDED"], "PPPPPPPPPFPP"); |
| 699 | // P3b |
| 700 | let p3b = spec_case(&[(-1, 2), z, (1, 2)], z, [z, z, (1, 2)], &[[z, z, z], [z, z, (-1, 2)], rho], |
| 701 | [one(1, 1), (Q::zero(), Q::i(1))], 0, (1, 2), (3, 4), 4, "INTERACTING"); |
| 702 | let x = eval(&p3b).unwrap(); |
| 703 | if x.dim != 4 { println!("FAIL P3b dim"); bad += 1; } |
| 704 | bad += expect_table("P3b", &x, &[(41, 80), (19, 80), (1, 80), (19, 80)], &[(29, 82), (1, 38), (1, 2), (37, 38)], |
| 705 | &[(40, 41), (10, 19), (0, 1), (10, 19)], &[(45, 82), (25, 38), (1, 2), (13, 38)]); |
| 706 | bad += expect_ideal("P3b", &x, &[[(1, 2), (1, 1), (1, 2)], [(1, 2), (0, 1), (1, 2)], [(1, 2), (1, 1), (1, 2)], [(1, 2), (0, 1), (1, 2)]]); |
| 707 | // P4 |
| 708 | let p4 = spec_case(&b_e, z, [z, z, (1, 2)], &[[z, z, z], [z, z, z], rho, [z, z, z]], |
| 709 | [one(1, 1), (Q::r(3, 5), Q::r(4, 5))], 1, (1, 4), (1, 1), 4, "INTERACTING"); |
| 710 | let x = eval(&p4).unwrap(); |
| 711 | bad += expect_table("P4", &x, &[(29, 164), (37, 164), (53, 164), (45, 164)], &[(277, 290), (197, 370), (37, 530), (13, 50)], |
| 712 | &[(17, 58), (73, 74), (65, 106), (1, 10)], &[(73, 145), (113, 185), (193, 265), (17, 25)]); |
| 713 | bad += expect_ideal("P4", &x, &[[(9, 10), (1, 5), (1, 2)], [(4, 5), (9, 10), (1, 2)], [(1, 10), (4, 5), (1, 2)], [(1, 5), (1, 10), (1, 2)]]); |
| 714 | // P5 |
| 715 | let p5 = spec_case(&[(-524289, 1048574), (524285, 1048574)], (1, 524287), [z, z, (1, 2)], |
| 716 | &[[z, z, z], [(524175, 1048354), (724, 524177), (-1, 2)]], [one(1, 1), one(1, 1)], 0, (1, 4), (1, 2), 4, "INTERACTING"); |
| 717 | let x = eval(&p5).unwrap(); |
| 718 | bad += expect_table("P5", &x, &[(524181, 2096716), (522731, 2096716), (524177, 2096716), (525627, 2096716)], |
| 719 | &[(274763624041, 549527248074), (274761527333, 548007134774), (274759430625, 549523054658), (274761527333, 551043167958)], |
| 720 | &[(274004612845, 549527248074), (274004612845, 548007134774), (275520532729, 549523054658), (275520532729, 551043167958)], |
| 721 | &[(524180, 524181), (522730, 522731), (524176, 524177), (525626, 525627)]); |
| 722 | bad += expect_verdict("P5", &p5, &x, "PASS", &[], "PPPPPPPPPPNP"); |
| 723 | let mut p5i = p5.clone(); p5i.target = "IDEAL".into(); |
| 724 | bad += expect_verdict("N1e (P5 IDEAL)", &p5i, &x, "FAIL", &["SCHRODINGER_DEVIATION_EXCEEDED"], "PPPPPPPPPFPP"); |
| 725 | // P6 |
| 726 | let p6 = spec_case(&b_e, z, [z, z, (1, 2)], &[[z, z, (1, 1)], [z, z, (1, 1048576)], rho, [z, z, z]], |
| 727 | [one(1, 1), one(1, 1)], 0, (1, 4), (1, 1), 4, "INTERACTING"); |
| 728 | let x = eval(&p6).unwrap(); |
| 729 | if x.dim != 2 { println!("FAIL P6 dim {}", x.dim); bad += 1; } |
| 730 | bad += expect_table("P6", &x, &[(5, 28), (9, 28), (5, 28), (9, 28)], &[(49, 50), (1, 10), (49, 50), (1, 10)], |
| 731 | &[(1, 2); 4], &[(16, 25), (4, 5), (16, 25), (4, 5)]); |
| 732 | // N2 |
| 733 | let n2 = spec_case(&b_e, z, [z, z, (1, 2)], &[[z, z, z], [z, z, (1, 2)], [z, z, (1, 2)], [z, z, z]], [one(1, 1), one(1, 1)], 0, (1, 4), (1, 1), 4, "INTERACTING"); |
| 734 | let x = eval(&n2).unwrap(); |
| 735 | bad += expect_verdict("N2", &n2, &x, "FAIL", &["TRIVIAL_PHYSICAL_STATE"], "PPFNPNNNNNNN"); |
| 736 | // N3 |
| 737 | let n3 = spec_case(&b_e, z, [z, z, (1, 2)], &[[z, z, z], [z, z, z], [z, z, (-1, 1)], [z, z, z]], [one(1, 1), one(1, 1)], 0, (1, 4), (1, 1), 4, "INTERACTING"); |
| 738 | let x = eval(&n3).unwrap(); |
| 739 | bad += expect_table("N3", &x, &[(1, 2), (1, 4), (0, 1), (1, 4)], &[], &[], &[]); |
| 740 | bad += expect_verdict("N3", &n3, &x, "FAIL", &["CONDITIONAL_UNDEFINED"], "PPPPPPPPFPNP"); |
| 741 | // N4a |
| 742 | let mut n4a = c.clone(); n4a.w = Q::r(1, 2); |
| 743 | let x = eval(&n4a).unwrap(); |
| 744 | bad += expect_table("N4a", &x, &[(5, 56), (1, 8), (9, 56), (1, 8)], &[], &[], &[]); |
| 745 | if x.povm_res2 != Q::i(1) { println!("FAIL N4a povm_res2 {}", x.povm_res2.to_s()); bad += 1; } |
| 746 | bad += expect_verdict("N4a", &n4a, &x, "FAIL", &["POVM_NORMALIZATION_EXCEEDED", "PROBABILITY_SUM_EXCEEDED"], "PPPPFFPPPPNP"); |
| 747 | // N6 |
| 748 | let n6 = spec_case(&b_e, z, [z, z, (1, 2)], &[[z, z, z], [z, z, (1, 2)], rho, [z, z, z]], [one(3, 1), one(1, 1)], 0, (1, 4), (1, 1), 4, "INTERACTING"); |
| 749 | let x = eval(&n6).unwrap(); |
| 750 | if !(x.dim == 1 && x.psi_zero) { println!("FAIL N6 dim/psi_zero"); bad += 1; } |
| 751 | bad += expect_ideal("N6", &x, &[[(4, 5), (1, 2), (9, 10)], [(1, 2), (4, 5), (9, 10)], [(1, 5), (1, 2), (9, 10)], [(1, 2), (1, 5), (9, 10)]]); |
| 752 | bad += expect_verdict("N6", &n6, &x, "FAIL", &["TRIVIAL_PHYSICAL_STATE"], "PPFNPNNNNNNN"); |
| 753 | // R4: per-level irrational spectrum is detected |
| 754 | let mut r4 = c.clone(); r4.v[2] = [Q::r(1, 2), Q::zero(), Q::r(-1, 10)]; |
| 755 | match eval(&r4) { Err(e) if e.contains("irrational") => println!("ok R4 irrational level detected"), _ => { println!("FAIL R4"); bad += 1; } } |
| 756 | println!("selftest: {} failure(s)", bad); |
| 757 | bad |
| 758 | } |
| 759 | |
| 760 | // ---------------------------------------------------------------- deterministic generator |
| 761 | struct Rng(u64); |
| 762 | impl Rng { |
| 763 | fn next(&mut self) -> u64 { // splitmix64 |
| 764 | self.0 = self.0.wrapping_add(0x9E3779B97F4A7C15); |
| 765 | let mut z = self.0; |
| 766 | z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9); |
| 767 | z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB); |
| 768 | z ^ (z >> 31) |
| 769 | } |
| 770 | fn pick(&mut self, n: usize) -> usize { (self.next() % n as u64) as usize } |
| 771 | fn coin(&mut self, num: u64, den: u64) -> bool { self.next() % den < num } |
| 772 | } |
| 773 | |
| 774 | const TAUS: [(i64, i64); 5] = [(1, 4), (1, 8), (3, 4), (1, 2), (3, 8)]; |
| 775 | const OFFS: [(i64, i64); 4] = [(0, 1), (1, 2), (-1, 3), (1, 5)]; |
| 776 | const H0S: [(i64, i64); 4] = [(0, 1), (1, 3), (-1, 2), (2, 7)]; |
| 777 | const DELTAS: [(i64, i64); 4] = [(1, 2), (1, 1), (1, 3), (3, 2)]; |
| 778 | // rational unit axes (a, b, c)/d with a^2 + b^2 + c^2 = d^2 |
| 779 | const QUADS: [(i64, i64, i64, i64); 14] = [(1, 2, 2, 3), (2, 3, 6, 7), (1, 4, 8, 9), (4, 4, 7, 9), (2, 6, 9, 11), (6, 6, 7, 11), |
| 780 | (3, 4, 12, 13), (2, 10, 11, 15), (3, 0, 4, 5), (0, 5, 12, 13), (8, 0, 15, 17), (0, 0, 1, 1), (1, 0, 0, 1), (0, 1, 0, 1)]; |
| 781 | const PERMS: [[usize; 3]; 6] = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]; |
| 782 | |
| 783 | fn psi_pool(i: usize) -> V2 { |
| 784 | let g = |a: i64, b: i64, c: i64, d: i64| G::new(Q::r(a, b), Q::r(c, d)); |
| 785 | match i { |
| 786 | 0 => [g(1, 1, 0, 1), g(1, 1, 0, 1)], |
| 787 | 1 => [g(1, 1, 0, 1), g(0, 1, 1, 1)], |
| 788 | 2 => [g(2, 1, 0, 1), g(1, 1, -1, 1)], |
| 789 | 3 => [g(1, 1, 0, 1), g(3, 5, 4, 5)], |
| 790 | 4 => [g(3, 1, 0, 1), g(-1, 1, 0, 1)], |
| 791 | 5 => [g(1, 1, 1, 1), g(2, 1, 0, 1)], |
| 792 | 6 => [g(1, 1, 0, 1), g(0, 1, -2, 1)], |
| 793 | _ => [g(5, 1, 0, 1), g(2, 1, 1, 1)], |
| 794 | } |
| 795 | } |
| 796 | const PSI_COMPLEX: [usize; 6] = [1, 2, 3, 5, 6, 7]; |
| 797 | |
| 798 | fn axis(rng: &mut Rng, allow_z: bool) -> [Q; 3] { |
| 799 | loop { |
| 800 | let (a, b, c, d) = QUADS[rng.pick(QUADS.len())]; |
| 801 | let comps = [a, b, c]; |
| 802 | let p = PERMS[rng.pick(6)]; |
| 803 | let mut out = [Q::zero(), Q::zero(), Q::zero()]; |
| 804 | for k in 0..3 { let s = if rng.coin(1, 2) { -1 } else { 1 }; out[k] = Q::r(s * comps[p[k]], d); } |
| 805 | let is_z = out[0].is_zero() && out[1].is_zero(); |
| 806 | if allow_z || !is_z { return out; } |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | #[derive(Clone, Copy, PartialEq, Debug)] |
| 811 | enum Role { Zero, Rot, Mz, Spec, Deg, Near, Swap } |
| 812 | |
| 813 | struct Clock { tau: Q, e: Vec<Q>, m: usize, w: Q } |
| 814 | |
| 815 | fn clock(rng: &mut Rng, n: usize, broken: bool, taus: &[(i64, i64)], offs: &[(i64, i64)], m8: bool) -> Option<Clock> { |
| 816 | let (tn, td) = taus[rng.pick(taus.len())]; |
| 817 | let tau = Q::r(tn, td); |
| 818 | let u = Q::i(1).div(&tau.mul(&Q::i(4))); |
| 819 | let mut res = vec![0i64, 1, 2, 3]; |
| 820 | for i in (1..4).rev() { let j = rng.pick(i + 1); res.swap(i, j); } |
| 821 | let mut rs: Vec<i64> = res[..n].to_vec(); |
| 822 | if broken { rs[n - 1] = rs[0]; } |
| 823 | let mut q: Vec<i64> = rs.iter().map(|&x| x + 4 * (rng.pick(3) as i64 - 1)).collect(); |
| 824 | q.sort(); |
| 825 | for i in 1..n { if q[i] == q[i - 1] { return None; } } |
| 826 | let (on, od) = offs[rng.pick(offs.len())]; |
| 827 | let off = Q::r(on, od); |
| 828 | let e: Vec<Q> = q.iter().map(|&x| u.mul(&Q::i(x)).add(&off)).collect(); |
| 829 | let m = if m8 { 8 } else if rng.coin(1, 2) { 4 } else { 8 }; |
| 830 | let w = Q::r(n as i64, m as i64); |
| 831 | Some(Clock { tau, e, m, w }) |
| 832 | } |
| 833 | |
| 834 | // |h| = mh / (8 tau), so 2 |h| (k - r) tau is a quarter-turn multiple and the ideal reference is exact |
| 835 | fn pick_h(rng: &mut Rng, tau: &Q, z_only: bool) -> (Q, [Q; 3]) { |
| 836 | let mh = 1 + rng.pick(3) as i64; |
| 837 | let hn = Q::i(mh).div(&tau.mul(&Q::i(8))); |
| 838 | let ax = if z_only { [Q::zero(), Q::zero(), Q::i(if rng.coin(1, 2) { 1 } else { -1 })] } else { axis(rng, true) }; |
| 839 | (hn.clone(), [ax[0].mul(&hn), ax[1].mul(&hn), ax[2].mul(&hn)]) |
| 840 | } |
| 841 | |
| 842 | fn level_v(rng: &mut Rng, role: Role, ej: &Q, h0: &Q, h: &[Q; 3]) -> Option<[Q; 3]> { |
| 843 | let a = ej.add(h0).abs(); |
| 844 | let sub_h = |n: [Q; 3]| [n[0].sub(&h[0]), n[1].sub(&h[1]), n[2].sub(&h[2])]; |
| 845 | match role { |
| 846 | Role::Zero => Some([Q::zero(), Q::zero(), Q::zero()]), |
| 847 | Role::Swap => Some([h[0].mul(&Q::i(-2)), h[1].mul(&Q::i(-2)), h[2].mul(&Q::i(-2))]), |
| 848 | Role::Deg => if ej.add(h0).is_zero() { Some([h[0].neg(), h[1].neg(), h[2].neg()]) } else { None }, |
| 849 | Role::Rot => { |
| 850 | if a.is_zero() { return None; } |
| 851 | let ax = axis(rng, false); |
| 852 | Some(sub_h([ax[0].mul(&a), ax[1].mul(&a), ax[2].mul(&a)])) |
| 853 | } |
| 854 | Role::Mz => { |
| 855 | if a.is_zero() { return None; } |
| 856 | let s = if rng.coin(1, 2) { a.clone() } else { a.neg() }; |
| 857 | Some(sub_h([Q::zero(), Q::zero(), s])) |
| 858 | } |
| 859 | Role::Spec => { |
| 860 | let (dn, dd) = DELTAS[rng.pick(DELTAS.len())]; |
| 861 | let rr = a.add(&Q::r(dn, dd)); |
| 862 | let ax = axis(rng, true); |
| 863 | Some(sub_h([ax[0].mul(&rr), ax[1].mul(&rr), ax[2].mul(&rr)])) |
| 864 | } |
| 865 | Role::Near => { |
| 866 | if a.is_zero() { return None; } |
| 867 | let eps = Q::r(1, 1048576); |
| 868 | let rr = if rng.coin(1, 2) { a.add(&eps) } else { a.sub(&eps) }; |
| 869 | if rr.is_neg() || rr.is_zero() { return None; } |
| 870 | let s = if rng.coin(1, 2) { rr } else { rr.neg() }; |
| 871 | Some(sub_h([Q::zero(), Q::zero(), s])) |
| 872 | } |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | fn tokens_ok(c: &Case) -> bool { |
| 877 | let mut all: Vec<&Q> = c.e.iter().collect(); |
| 878 | all.push(&c.h0); all.push(&c.tau); all.push(&c.w); |
| 879 | for q in c.h.iter() { all.push(q); } |
| 880 | for v in &c.v { for q in v.iter() { all.push(q); } } |
| 881 | for g in c.psi.iter() { all.push(&g.re); all.push(&g.im); } |
| 882 | all.iter().all(|q| q.in_token_limit()) |
| 883 | } |
| 884 | |
| 885 | fn uniform(x: &Exact) -> bool { x.p.windows(2).all(|w| w[0] == w[1]) } |
| 886 | |
| 887 | struct Built { c: Case, x: Exact, v: Verdict } |
| 888 | |
| 889 | fn finish(mut c: Case, control: &str) -> Option<Built> { |
| 890 | if !tokens_ok(&c) { return None; } |
| 891 | let x = eval(&c).ok()?; |
| 892 | let v = judge(&c, &x).ok()?; |
| 893 | c.control = control.into(); |
| 894 | c.outcome = v.outcome.into(); |
| 895 | c.codes = v.codes.clone(); |
| 896 | Some(Built { c, x, v }) |
| 897 | } |
| 898 | |
| 899 | #[derive(Clone, Copy, PartialEq, Debug)] |
| 900 | enum Class { P1, P1c, P2, P3, P3b, P4, P6, N2, N3, N4a, N4b, N6 } |
| 901 | |
| 902 | fn attempt(rng: &mut Rng, cls: Class) -> Option<Built> { |
| 903 | use Class::*; |
| 904 | let n = match cls { P1 | N2 => 2 + rng.pick(3), _ => 3 + rng.pick(2) }; |
| 905 | let (taus, offs): (&[(i64, i64)], &[(i64, i64)]) = if cls == P6 { (&TAUS[..2], &OFFS[..2]) } else { (&TAUS, &OFFS) }; |
| 906 | let ck = clock(rng, n, cls == N4b, if cls == P6 { &[(1, 4), (1, 8), (1, 2)] } else { taus }, offs, cls == P4)?; |
| 907 | let (hn, h) = pick_h(rng, &ck.tau, cls == P6); |
| 908 | let mut roles = vec![Role::Zero; n]; |
| 909 | let a = rng.pick(n); |
| 910 | let s: i64 = if rng.coin(1, 2) { 1 } else { -1 }; |
| 911 | let h0i = rng.pick(4); let mut h0 = Q::r(H0S[h0i].0, H0S[h0i].1); |
| 912 | let others: Vec<usize> = (0..n).filter(|&j| j != a).collect(); |
| 913 | let b = others[rng.pick(others.len())]; |
| 914 | match cls { |
| 915 | P1 => { h0 = ck.e[a].neg().sub(&hn.mul(&Q::i(s))); } |
| 916 | P1c => { h0 = ck.e[a].neg().sub(&hn.mul(&Q::i(s))); |
| 917 | for &j in &others { roles[j] = if rng.coin(1, 2) { Role::Spec } else { Role::Zero }; } roles[b] = Role::Spec; } |
| 918 | P2 | N4a | N4b => { h0 = ck.e[a].neg().sub(&hn.mul(&Q::i(s))); roles[b] = Role::Rot; } |
| 919 | P3 => { for j in 0..n { roles[j] = if rng.coin(3, 4) { Role::Rot } else { Role::Spec }; } } |
| 920 | P3b => { h0 = ck.e[a].neg(); roles[a] = Role::Deg; roles[b] = Role::Rot; |
| 921 | for &j in &others { if j != b { roles[j] = if rng.coin(1, 2) { Role::Spec } else { Role::Zero }; } } } |
| 922 | P4 => { roles[a] = Role::Rot; for &j in &others { roles[j] = [Role::Rot, Role::Zero, Role::Spec][rng.pick(3)]; } } |
| 923 | P6 => { h0 = Q::zero(); roles[a] = Role::Near; roles[b] = Role::Rot; |
| 924 | for &j in &others { if j != b { roles[j] = if rng.coin(1, 2) { Role::Mz } else { Role::Zero }; } } } |
| 925 | N2 => { for j in 0..n { roles[j] = Role::Spec; } } |
| 926 | N3 => { h0 = ck.e[a].neg().sub(&hn.mul(&Q::i(s))); |
| 927 | for &j in &others { roles[j] = [Role::Swap, Role::Zero, Role::Spec][rng.pick(3)]; } roles[b] = Role::Swap; } |
| 928 | N6 => { roles[b] = Role::Rot; for &j in &others { if j != b { roles[j] = Role::Spec; } } roles[a] = Role::Spec; } |
| 929 | } |
| 930 | let mut v = Vec::new(); |
| 931 | for j in 0..n { v.push(level_v(rng, roles[j], &ck.e[j], &h0, &h)?); } |
| 932 | let psi_i = if cls == P4 { PSI_COMPLEX[rng.pick(PSI_COMPLEX.len())] } else { rng.pick(8) }; |
| 933 | let mut psi = psi_pool(psi_i); |
| 934 | let r = if cls == P4 { 1 + rng.pick(ck.m - 1) } else { rng.pick(ck.m) }; |
| 935 | let target = match cls { P1 | P1c => "IDEAL", _ => "INTERACTING" }; |
| 936 | let w = if cls == N4a { ck.w.mul(&Q::r(1, 2)) } else { ck.w.clone() }; |
| 937 | if cls == N6 { |
| 938 | // psi_0 orthogonal to the single kernel vector of level b |
| 939 | let (nb, r2) = level_norm(&h, &v[b]); |
| 940 | let rr = r2.sqrt_exact()?; |
| 941 | let eb = ck.e[b].add(&h0); |
| 942 | let sb = if eb.add(&rr).is_zero() { 1 } else if eb.sub(&rr).is_zero() { -1 } else { return None }; |
| 943 | let f = eigvec(&nb, sb, &rr); |
| 944 | psi = [f[1].conj().scale(&Q::i(-1)), f[0].conj()]; |
| 945 | } |
| 946 | let c = Case { name: String::new(), e: ck.e.clone(), h0, h, v, r, psi, tau: ck.tau.clone(), w, m: ck.m, |
| 947 | control: String::new(), target: target.into(), outcome: String::new(), codes: vec![] }; |
| 948 | let positive = matches!(cls, P1 | P1c | P2 | P3 | P3b | P4 | P6); |
| 949 | let bt = finish(c, if positive { "POSITIVE" } else { "NEGATIVE" })?; |
| 950 | let (x, vd) = (&bt.x, &bt.v); |
| 951 | let codes: Vec<&str> = vd.codes.iter().map(|s| s.as_str()).collect(); |
| 952 | let ideal_twin_ok = |c: &Case| -> bool { |
| 953 | let mut ci = c.clone(); ci.target = "IDEAL".into(); |
| 954 | match judge(&ci, x) { Ok(v2) => v2.outcome == "FAIL" && v2.codes == vec!["SCHRODINGER_DEVIATION_EXCEEDED".to_string()] |
| 955 | && v2.checks[9] == "FAIL" && v2.checks[10] == "PASS", Err(_) => false } |
| 956 | }; |
| 957 | let ok = match cls { |
| 958 | P1 => vd.outcome == "PASS" && x.dim >= 2, |
| 959 | P1c => vd.outcome == "PASS" && x.dim >= 2 && bt.c.v.iter().any(|q| q.iter().any(|t| !t.is_zero())), |
| 960 | P2 => vd.outcome == "PASS" && x.dim >= 2 && !uniform(x) && ideal_twin_ok(&bt.c), |
| 961 | P3 => vd.outcome == "PASS" && x.dim >= 3 && !uniform(x) && bt.c.v.iter().all(|q| q.iter().any(|t| !t.is_zero())), |
| 962 | P3b => vd.outcome == "PASS" && x.dim >= 3 && !uniform(x), |
| 963 | P4 => vd.outcome == "PASS" && x.dim >= 2 && !uniform(x) && ideal_twin_ok(&bt.c), |
| 964 | P6 => vd.outcome == "PASS" && x.dim >= 2 && ideal_twin_ok(&bt.c), |
| 965 | N2 => codes == ["TRIVIAL_PHYSICAL_STATE"] && x.dim == 0, |
| 966 | N3 => codes == ["CONDITIONAL_UNDEFINED"], |
| 967 | N4a => codes == ["POVM_NORMALIZATION_EXCEEDED", "PROBABILITY_SUM_EXCEEDED"], |
| 968 | N4b => codes.contains(&"POVM_NORMALIZATION_EXCEEDED") && codes.iter().all(|c| *c == "POVM_NORMALIZATION_EXCEEDED" || *c == "PROBABILITY_SUM_EXCEEDED"), |
| 969 | N6 => codes == ["TRIVIAL_PHYSICAL_STATE"] && x.dim >= 1 && x.psi_zero, |
| 970 | }; |
| 971 | if ok { Some(bt) } else { None } |
| 972 | } |
| 973 | |
| 974 | fn draw(rng: &mut Rng, cls: Class) -> (Built, u32) { |
| 975 | for t in 1..=2_000_000u32 { if let Some(b) = attempt(rng, cls) { return (b, t); } } |
| 976 | panic!("class {:?}: no accepted draw", cls); |
| 977 | } |
| 978 | |
| 979 | fn chk_str(v: &Verdict) -> String { v.checks.iter().map(|s| match *s { "PASS" => "P", "FAIL" => "F", "NOT_EVALUATED" => "N", _ => "I" }).collect() } |
| 980 | |
| 981 | fn details(name: &str, b: &Built) -> String { |
| 982 | let x = &b.x; |
| 983 | let mut s = format!("== {}\nkernel_dim {} psi_zero {} povm_residual_squared {}\n", name, x.dim, x.psi_zero, x.povm_res2.to_s()); |
| 984 | for k in 0..b.c.m { |
| 985 | let p = if x.p.is_empty() { "undefined".to_string() } else { x.p[k].to_s() }; |
| 986 | let pl = match x.pauli.get(k) { Some(Some(a)) => format!("{} {} {}", a[0].to_s(), a[1].to_s(), a[2].to_s()), _ => "undefined".into() }; |
| 987 | let id = &x.ideal[k]; |
| 988 | s.push_str(&format!("k {} p {} plusXYZ {} idealXYZ {} {} {}\n", k, p, pl, id[0].to_s(), id[1].to_s(), id[2].to_s())); |
| 989 | } |
| 990 | s |
| 991 | } |
| 992 | |
| 993 | fn replace_line(text: &str, from_prefix: &str, to: &str) -> String { |
| 994 | let mut done = false; |
| 995 | let out: Vec<String> = text.split_terminator('\n').map(|l| { |
| 996 | if !done && l.starts_with(from_prefix) { done = true; to.to_string() } else { l.to_string() } |
| 997 | }).collect(); |
| 998 | assert!(done, "line not found: {}", from_prefix); |
| 999 | let mut s = out.join("\n"); s.push('\n'); s |
| 1000 | } |
| 1001 | fn remove_line(text: &str, prefix: &str) -> String { |
| 1002 | let lines: Vec<&str> = text.split_terminator('\n').collect(); |
| 1003 | let i = lines.iter().position(|l| l.starts_with(prefix)).expect("line"); |
| 1004 | let mut out: Vec<&str> = lines.clone(); out.remove(i); |
| 1005 | let mut s = out.join("\n"); s.push('\n'); s |
| 1006 | } |
| 1007 | |
| 1008 | fn generate(seed: u64, dir: &str) { |
| 1009 | let mut rng = Rng(seed); |
| 1010 | std::fs::create_dir_all(dir).unwrap(); |
| 1011 | let mut expected = String::from("# file\tclass\tkind\texpected_outcome\texpected_codes\tchecks_1_to_12(P=PASS,F=FAIL,N=NOT_EVALUATED)\tcase_id\tacceptance_id\tattempts\n"); |
| 1012 | let mut det = String::new(); |
| 1013 | let mut files: Vec<(String, String)> = Vec::new(); |
| 1014 | let mut built: Vec<(Class, Built)> = Vec::new(); |
| 1015 | use Class::*; |
| 1016 | let order = [P1, P1c, P2, P3, P3b, P4, P6, N2, N3, N4a, N4b, N6]; |
| 1017 | let mut attempts = Vec::new(); |
| 1018 | for &cls in &order { let (b, t) = draw(&mut rng, cls); attempts.push(t); built.push((cls, b)); } |
| 1019 | let tag = |cls: Class| -> &'static str { match cls { P1 => "p1-zero-coupling-ideal", P1c => "p1c-spectator-ideal", P2 => "p2-one-rotated-level", |
| 1020 | P3 => "p3-every-level-coupled", P3b => "p3b-degenerate-level", P4 => "p4-complex-psi-ref-nonzero", P6 => "p6-near-miss-level", |
| 1021 | N2 => "n2-trivial-kernel", N3 => "n3-zero-label", N4a => "n4a-wrong-weight", N4b => "n4b-broken-clock", N6 => "n6-zero-projection" } }; |
| 1022 | let mut idx = 0; |
| 1023 | let push_result = |name: String, cls: &str, c: &Case, x: &Exact, v: &Verdict, att: u32, files: &mut Vec<(String, String)>, expected: &mut String, det: &mut String| { |
| 1024 | let mut c = c.clone(); c.name = name.clone(); |
| 1025 | let text = render(&c); |
| 1026 | let back = parse_case(&text).expect("reparse"); |
| 1027 | let x2 = eval(&back).expect("re-eval"); |
| 1028 | let v2 = judge(&back, &x2).expect("re-judge"); |
| 1029 | assert!(v2.outcome == v.outcome && v2.codes == v.codes && chk_str(&v2) == chk_str(v)); |
| 1030 | assert!(back.outcome == v.outcome && back.codes == v.codes); |
| 1031 | let lines: Vec<String> = text.split_terminator('\n').map(|s| s.to_string()).collect(); |
| 1032 | let cid = lines.iter().find(|l| l.starts_with("case_id ")).unwrap()[8..].to_string(); |
| 1033 | let aid = lines.iter().find(|l| l.starts_with("acceptance_id ")).unwrap()[14..].to_string(); |
| 1034 | let fname = format!("{}.case", name); |
| 1035 | expected.push_str(&format!("{}\t{}\tRESULT\t{}\t{}\t{}\t{}\t{}\t{}\n", fname, cls, v.outcome, |
| 1036 | if v.codes.is_empty() { "none".to_string() } else { v.codes.join(",") }, chk_str(v), cid, aid, att)); |
| 1037 | det.push_str(&details(&fname, &Built { c: c.clone(), x: Exact { dim: x.dim, psi_zero: x.psi_zero, p: x.p.clone(), pauli: x.pauli.clone(), ideal: x.ideal.clone(), povm_res2: x.povm_res2.clone() }, v: Verdict { checks: v.checks.clone(), outcome: v.outcome, codes: v.codes.clone() } })); |
| 1038 | files.push((fname, text)); |
| 1039 | }; |
| 1040 | for (i, (cls, b)) in built.iter().enumerate() { |
| 1041 | idx += 1; |
| 1042 | let name = format!("a7h-{:02}-{}", idx, tag(*cls)); |
| 1043 | push_result(name, &format!("{:?}", cls), &b.c, &b.x, &b.v, attempts[i], &mut files, &mut expected, &mut det); |
| 1044 | } |
| 1045 | // N1 family: the same semantic block as P2, P4, P6 with prediction_target IDEAL |
| 1046 | for (src, label) in [(P2, "n1a-p2-question-ideal-target"), (P4, "n1b-p4-question-ideal-target"), (P6, "n1c-p6-question-ideal-target")] { |
| 1047 | let b = &built.iter().find(|(c, _)| *c == src).unwrap().1; |
| 1048 | let mut c = b.c.clone(); |
| 1049 | c.target = "IDEAL".into(); c.control = "NEGATIVE".into(); |
| 1050 | let v = judge(&c, &b.x).unwrap(); |
| 1051 | assert!(v.outcome == "FAIL" && v.codes == vec!["SCHRODINGER_DEVIATION_EXCEEDED".to_string()]); |
| 1052 | c.outcome = v.outcome.into(); c.codes = v.codes.clone(); |
| 1053 | idx += 1; |
| 1054 | let name = format!("a7h-{:02}-{}", idx, label); |
| 1055 | push_result(name, "N1", &c, &b.x, &v, 0, &mut files, &mut expected, &mut det); |
| 1056 | } |
| 1057 | // refusal files: one defect each on an accepted case (first failure in AT1_CASE_V1 section 4 order) |
| 1058 | let base = |cls: Class| -> Case { built.iter().find(|(c, _)| *c == cls).unwrap().1.c.clone() }; |
| 1059 | let mut refusals: Vec<(String, String, &str)> = Vec::new(); |
| 1060 | { |
| 1061 | // R-a: per-level irrational spectrum on one level while |h| stays rational |
| 1062 | let mut c = base(P4); |
| 1063 | let mut found = false; |
| 1064 | 'outer: for j in 0..c.v.len() { |
| 1065 | for (dn, dd) in [(1i64, 5i64), (1, 3), (1, 7), (2, 5), (3, 5)] { |
| 1066 | let mut c2 = c.clone(); |
| 1067 | c2.v[j][0] = c2.v[j][0].add(&Q::r(dn, dd)); |
| 1068 | let (_, r2) = level_norm(&c2.h, &c2.v[j]); |
| 1069 | if r2.sqrt_exact().is_none() && tokens_ok(&c2) { c = c2; found = true; break 'outer; } |
| 1070 | } |
| 1071 | } |
| 1072 | assert!(found); |
| 1073 | c.name = "a7h-R-irrational-level".into(); |
| 1074 | refusals.push(("r1-per-level-irrational".into(), render(&c), "CASE_IRRATIONAL_SPECTRUM")); |
| 1075 | // R-b: non-canonical coupling index token 01 at position 1 (charter reading e) |
| 1076 | let mut c = base(P3); c.name = "a7h-R-index-01".into(); |
| 1077 | let t = fix_ids(&replace_line(&render(&c), "interaction_pauli 1 ", &render(&c).lines().find(|l| l.starts_with("interaction_pauli 1 ")).unwrap().replacen("interaction_pauli 1 ", "interaction_pauli 01 ", 1))); |
| 1078 | refusals.push(("r2-coupling-index-01".into(), t, "CASE_NONCANONICAL")); |
| 1079 | // R-c: AT0 header on line 1 (charter reading d) |
| 1080 | let mut c = base(P1); c.name = "a7h-R-at0-header".into(); |
| 1081 | refusals.push(("r3-at0-header".into(), replace_line(&render(&c), "OMEGA-AT1-CASE v1", "OMEGA-AT0-CASE v1"), "CASE_PARSE_ERROR")); |
| 1082 | // R-d: foreign domain value (charter reading d) |
| 1083 | let mut c = base(P3b); c.name = "a7h-R-domain-at0".into(); |
| 1084 | refusals.push(("r4-domain-at0".into(), replace_line(&render(&c), "domain omega.at1.case.v1", "domain omega.at0.case.v1"), "CASE_UNSUPPORTED_VERSION")); |
| 1085 | // R-e: coupling line count not N (last interaction_pauli line removed) |
| 1086 | let mut c = base(P2); c.name = "a7h-R-coupling-count".into(); |
| 1087 | let last = format!("interaction_pauli {} ", c.v.len() - 1); |
| 1088 | refusals.push(("r5-coupling-count".into(), fix_ids(&remove_line(&render(&c), &last)), "CASE_PARSE_ERROR")); |
| 1089 | // R-f: canonical clock_label index with the wrong value (2 at position 1) |
| 1090 | let mut c = base(P6); c.name = "a7h-R-label-index-value".into(); |
| 1091 | refusals.push(("r6-label-index-value".into(), fix_ids(&replace_line(&render(&c), "clock_label 1 t1", "clock_label 2 t1")), "CASE_PARSE_ERROR")); |
| 1092 | } |
| 1093 | for (tag, text, code) in refusals { |
| 1094 | idx += 1; |
| 1095 | let fname = format!("a7h-{:02}-{}.case", idx, tag); |
| 1096 | let lines: Vec<String> = text.split_terminator('\n').map(|s| s.to_string()).collect(); |
| 1097 | let cid = lines.iter().find(|l| l.starts_with("case_id ")).map(|l| l[8..].to_string()).unwrap_or("-".into()); |
| 1098 | let aid = lines.iter().find(|l| l.starts_with("acceptance_id ")).map(|l| l[14..].to_string()).unwrap_or("-".into()); |
| 1099 | expected.push_str(&format!("{}\tR\tREFUSED\t{}\t-\t-\t{}\t{}\t0\n", fname, code, cid, aid)); |
| 1100 | files.push((fname, text)); |
| 1101 | } |
| 1102 | for (f, t) in &files { std::fs::write(format!("{}/{}", dir, f), t).unwrap(); } |
| 1103 | std::fs::write(format!("{}/EXPECTED.tsv", dir), &expected).unwrap(); |
| 1104 | std::fs::write(format!("{}/DETAILS.txt", dir), &det).unwrap(); |
| 1105 | println!("wrote {} case files", files.len()); |
| 1106 | } |
| 1107 | |
| 1108 | fn main() { |
| 1109 | let a: Vec<String> = std::env::args().collect(); |
| 1110 | match a.get(1).map(|s| s.as_str()) { |
| 1111 | Some("selftest") => { let bad = selftest(&a[2]); std::process::exit(if bad == 0 { 0 } else { 1 }); } |
| 1112 | Some("gen") => { |
| 1113 | let seed = u64::from_str_radix(a[2].trim(), 16).expect("seed hex"); |
| 1114 | generate(seed, &a[3]); |
| 1115 | } |
| 1116 | _ => { eprintln!("usage: at1h selftest <worked> | gen <seed_hex> <dir>"); std::process::exit(2); } |
| 1117 | } |
| 1118 | } |