Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/research/atemporal/at1/evaluator/src/case.rs # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / research / atemporal / at1 / evaluator / src / case.rs` 665 lines ยท 24718 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Independent AT1_CASE_V1 codec: byte rules, fixed line grammar, canonical 17 //! encodings and the six validity rules in contract order (section 4), with 18 //! arbitrary-precision exact arithmetic for rules 3 and 4 (no implementation 19 //! refusal, no wrap-around). Charter readings c, d, e are applied. 20 21 use crate::rat::{parse_crat, parse_int, parse_rat, parse_scaled, Cq, Scaled, Tok, Q}; 22 use crate::sha256::{sha256_hex, tagged_hex}; 23 use crate::text::{is_code, is_digest, is_label, is_name, join_lf, lines_checked, FAILURE_CODES}; 24 25 pub const CASE_DOMAIN: &str = "omega.at1.case.v1"; 26 pub const ACC_DOMAIN: &str = "omega.at1.acceptance.v1"; 27 28 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 29 pub enum Refusal { 30 ParseError, 31 NonCanonical, 32 UnsupportedVersion, 33 InvalidParameter, 34 IrrationalSpectrum, 35 IdMismatch, 36 } 37 38 impl Refusal { 39 pub fn code(self) -> &'static str { 40 match self { 41 Refusal::ParseError => "CASE_PARSE_ERROR", 42 Refusal::NonCanonical => "CASE_NONCANONICAL", 43 Refusal::UnsupportedVersion => "CASE_UNSUPPORTED_VERSION", 44 Refusal::InvalidParameter => "CASE_INVALID_PARAMETER", 45 Refusal::IrrationalSpectrum => "CASE_IRRATIONAL_SPECTRUM", 46 Refusal::IdMismatch => "CASE_ID_MISMATCH", 47 } 48 } 49 } 50 51 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] 52 pub enum BoundKind { 53 None = 0, 54 Estimated = 1, 55 Rigorous = 2, 56 } 57 impl BoundKind { 58 pub fn parse(s: &str) -> Option { 59 match s { 60 "NONE" => Some(BoundKind::None), 61 "ESTIMATED" => Some(BoundKind::Estimated), 62 "RIGOROUS" => Some(BoundKind::Rigorous), 63 _ => None, 64 } 65 } 66 pub fn text(self) -> &'static str { 67 match self { 68 BoundKind::None => "NONE", 69 BoundKind::Estimated => "ESTIMATED", 70 BoundKind::Rigorous => "RIGOROUS", 71 } 72 } 73 } 74 75 #[derive(Clone, Debug)] 76 pub struct Case { 77 pub name: String, 78 pub n: usize, 79 pub e: Vec, 80 pub h0: Q, 81 pub h: [Q; 3], 82 pub v: Vec<[Q; 3]>, 83 pub ref_label: String, 84 pub ref_index: usize, 85 pub psi: [Cq; 2], 86 pub tau: Q, 87 pub w: Q, 88 pub m: usize, 89 pub labels: Vec, 90 pub control_positive: bool, 91 pub target_ideal: bool, 92 pub expected_pass: bool, 93 pub expected_codes: Vec, 94 pub min_bound_kind: BoundKind, 95 pub tol_constraint: Scaled, 96 pub tol_povm: Scaled, 97 pub tol_prob: Scaled, 98 pub tol_zero: Scaled, 99 pub tol_schro: Scaled, 100 pub case_id: String, 101 pub acceptance_id: String, 102 /// lines from case_name through acceptance_id (what a result copies) 103 pub body_lines: Vec, 104 pub sem_lines: Vec, 105 pub acc_lines: Vec, 106 pub file_sha256: String, 107 /// exact level norms |h + v_j| (rule 4 guarantees rational) 108 pub level_r: Vec, 109 } 110 111 struct P<'a> { 112 lines: &'a [String], 113 i: usize, 114 noncanon: Option, 115 bad_param: Option, 116 bad_version: Option, 117 } 118 119 type R = Result; 120 121 fn perr(msg: String) -> R { 122 Err((Refusal::ParseError, msg)) 123 } 124 125 impl<'a> P<'a> { 126 fn next(&mut self) -> R<&'a str> { 127 if self.i >= self.lines.len() { 128 return perr("unexpected end of file".into()); 129 } 130 let l = &self.lines[self.i]; 131 self.i += 1; 132 Ok(l) 133 } 134 /// A `key value...` line with exactly `ntok` tokens after the key. 135 fn key(&mut self, key: &str, ntok: usize) -> R> { 136 let ln = self.i + 1; 137 let l = self.next()?; 138 let t: Vec<&str> = l.split(' ').collect(); 139 if t[0] != key { 140 return perr(format!("line {}: expected key {}, found {}", ln, key, t[0])); 141 } 142 if t.len() != ntok + 1 { 143 return perr(format!("line {}: {} takes {} token(s)", ln, key, ntok)); 144 } 145 Ok(t[1..].to_vec()) 146 } 147 fn exact(&mut self, text: &str) -> R<()> { 148 let ln = self.i + 1; 149 let l = self.next()?; 150 if l != text { 151 return perr(format!("line {}: expected `{}`", ln, text)); 152 } 153 Ok(()) 154 } 155 fn tok(&mut self, t: Tok, what: &str) { 156 if t == Tok::NonCanonical && self.noncanon.is_none() { 157 self.noncanon = Some(format!("line {}: non-canonical {}", self.i, what)); 158 } 159 } 160 fn param(&mut self, msg: String) { 161 if self.bad_param.is_none() { 162 self.bad_param = Some(msg); 163 } 164 } 165 fn rat(&mut self, s: &str, what: &str) -> R { 166 match parse_rat(s) { 167 None => perr(format!("line {}: {} `{}` is not a rational", self.i, what, s)), 168 Some((q, t)) => { 169 self.tok(t, what); 170 if !q.within_limits() { 171 self.param(format!("line {}: {} outside the token limits", self.i, what)); 172 } 173 Ok(q) 174 } 175 } 176 } 177 fn list(&self, s: &str) -> R> { 178 // AT1_CASE_V1 section 2: "the empty list is `none`" 179 if s == "none" { 180 return Ok(Vec::new()); 181 } 182 let v: Vec = s.split(',').map(|x| x.to_string()).collect(); 183 if v.iter().any(|x| x.is_empty()) { 184 return perr(format!("line {}: empty list item", self.i)); 185 } 186 Ok(v) 187 } 188 fn count(&mut self, s: &str, what: &str) -> R { 189 match parse_int(s) { 190 None => perr(format!("line {}: {} is not an integer", self.i, what)), 191 Some((v, t)) => { 192 self.tok(t, what); 193 if v.is_neg() || v.bits() > 40 { 194 return perr(format!("line {}: {} cannot be a count", self.i, what)); 195 } 196 Ok(v.low_u64() as i64) 197 } 198 } 199 } 200 fn index(&mut self, s: &str, pos: usize, what: &str) -> R<()> { 201 // reading (e): parsed value compared with the position; canonicality after the shape pass 202 match parse_int(s) { 203 None => perr(format!("line {}: {} index `{}` is not an integer", self.i, what, s)), 204 Some((v, t)) => { 205 if v.is_neg() || v.bits() > 40 || v.low_u64() as usize != pos { 206 return perr(format!("line {}: {} index {} is not its position {}", self.i, what, s, pos)); 207 } 208 self.tok(t, what); 209 Ok(()) 210 } 211 } 212 } 213 fn scaled(&mut self, key: &str) -> R { 214 let t = self.key(key, 1)?; 215 match parse_scaled(t[0]) { 216 None => perr(format!("line {}: {} is not a scaled decimal", self.i, key)), 217 Some((s, tk)) => { 218 self.tok(tk, key); 219 Ok(s) 220 } 221 } 222 } 223 } 224 225 /// Parses the lines from `case_name` through `acceptance_id` (shape pass plus token 226 /// canonicality and range flags). Used for standalone files and inside results. 227 fn parse_body(p: &mut P) -> R { 228 let body_start = p.i; 229 let name = p.key("case_name", 1)?[0]; 230 if !is_name(name) { 231 return perr("case_name grammar".into()); 232 } 233 let sem_start = p.i; 234 p.exact("begin semantic")?; 235 p.exact("model_family PAGE_WOOTTERS_FINITE_CLOCKDIAG")?; 236 p.exact("energy_unit DIMENSIONLESS_HBAR_1")?; 237 let t = p.key("clock_dim", 1)?[0]; 238 let n = p.count(t, "clock_dim")?; 239 let et = p.key("clock_energies", 1)?; 240 let items = p.list(et[0])?; 241 if items.len() as i64 != n { 242 return perr(format!("clock_energies has {} entries, clock_dim {}", items.len(), n)); 243 } 244 let mut e = Vec::new(); 245 for it in &items { 246 e.push(p.rat(it, "clock energy")?); 247 } 248 p.exact("system_dim 2")?; 249 let ht = p.key("system_hamiltonian_pauli", 1)?; 250 let hi = p.list(ht[0])?; 251 if hi.len() != 4 { 252 return perr("system_hamiltonian_pauli needs 4 rationals".into()); 253 } 254 let mut hv = Vec::new(); 255 for it in &hi { 256 hv.push(p.rat(it, "system_hamiltonian_pauli component")?); 257 } 258 p.exact("interaction CLOCK_DIAGONAL_PAULI")?; 259 let mut v = Vec::new(); 260 for j in 0..n as usize { 261 let t = p.key("interaction_pauli", 2)?; 262 p.index(t[0], j, "interaction_pauli")?; 263 let comps = p.list(t[1])?; 264 if comps.len() != 3 { 265 return perr("interaction_pauli needs 3 rationals".into()); 266 } 267 let a = p.rat(&comps[0], "coupling component")?; 268 let b = p.rat(&comps[1], "coupling component")?; 269 let c = p.rat(&comps[2], "coupling component")?; 270 v.push([a, b, c]); 271 } 272 p.exact("constraint SUM_HC_HS_V")?; 273 p.exact("physical_state NULLSPACE_PROJECTION")?; 274 let rl = p.key("reference_clock_label", 1)?[0]; 275 if !is_label(rl) { 276 return perr("reference_clock_label grammar".into()); 277 } 278 let st = p.key("reference_system_state", 1)?; 279 let sv = p.list(st[0])?; 280 if sv.len() != 2 { 281 return perr("reference_system_state needs 2 complex rationals".into()); 282 } 283 let mut psi = Vec::new(); 284 for it in &sv { 285 match parse_crat(it) { 286 None => return perr("reference_system_state component is not a complex rational".into()), 287 Some((z, t)) => { 288 p.tok(t, "reference_system_state"); 289 if !z.re.within_limits() || !z.im.within_limits() { 290 p.param("reference_system_state outside the token limits".into()); 291 } 292 psi.push(z); 293 } 294 } 295 } 296 p.exact("clock_povm COVARIANT_DISCRETE")?; 297 let tau = { 298 let t = p.key("povm_tau_turns", 1)?; 299 p.rat(t[0], "povm_tau_turns")? 300 }; 301 let w = { 302 let t = p.key("povm_weight", 1)?; 303 p.rat(t[0], "povm_weight")? 304 }; 305 let t = p.key("clock_label_count", 1)?[0]; 306 let m = p.count(t, "clock_label_count")?; 307 let mut labels = Vec::new(); 308 for k in 0..m as usize { 309 let t = p.key("clock_label", 2)?; 310 p.index(t[0], k, "clock_label")?; 311 if !is_label(t[1]) { 312 return perr(format!("clock_label {} grammar", k)); 313 } 314 labels.push(t[1].to_string()); 315 } 316 p.exact("observables PAULI_X,PAULI_Y,PAULI_Z")?; 317 p.exact("end semantic")?; 318 let sem_end = p.i; 319 p.exact("begin acceptance")?; 320 let control_positive = match p.key("control_kind", 1)?[0] { 321 "POSITIVE" => true, 322 "NEGATIVE" => false, 323 _ => return perr("control_kind outside its set".into()), 324 }; 325 let target_ideal = match p.key("prediction_target", 1)?[0] { 326 "IDEAL" => true, 327 "INTERACTING" => false, 328 _ => return perr("prediction_target outside its set".into()), 329 }; 330 let expected_pass = match p.key("expected_outcome", 1)?[0] { 331 "PASS" => true, 332 "FAIL" => false, 333 _ => return perr("expected_outcome outside its set".into()), 334 }; 335 let ct = p.key("expected_failure_codes", 1)?[0]; 336 let expected_codes: Vec = if ct == "none" { 337 Vec::new() 338 } else { 339 let l = p.list(ct)?; 340 if l.iter().any(|c| !is_code(c)) { 341 return perr("expected_failure_codes token grammar".into()); 342 } 343 l 344 }; 345 let min_bound_kind = match BoundKind::parse(p.key("min_bound_kind", 1)?[0]) { 346 Some(b) => b, 347 None => return perr("min_bound_kind outside its set".into()), 348 }; 349 let tol_constraint = p.scaled("tol_constraint_residual")?; 350 let tol_povm = p.scaled("tol_povm_residual")?; 351 let tol_prob = p.scaled("tol_probability")?; 352 let tol_zero = p.scaled("tol_zero_probability")?; 353 let tol_schro = p.scaled("tol_schrodinger")?; 354 p.exact("end acceptance")?; 355 let acc_end = p.i; 356 let cid = p.key("case_id", 1)?[0]; 357 if !is_digest(cid) { 358 return perr("case_id is not a digest".into()); 359 } 360 let aid = p.key("acceptance_id", 1)?[0]; 361 if !is_digest(aid) { 362 return perr("acceptance_id is not a digest".into()); 363 } 364 let lines = p.lines; 365 Ok(Case { 366 name: name.to_string(), 367 n: n as usize, 368 e, 369 h0: hv[0].clone(), 370 h: [hv[1].clone(), hv[2].clone(), hv[3].clone()], 371 v, 372 ref_label: rl.to_string(), 373 ref_index: 0, 374 psi: [psi[0].clone(), psi[1].clone()], 375 tau, 376 w, 377 m: m as usize, 378 labels, 379 control_positive, 380 target_ideal, 381 expected_pass, 382 expected_codes, 383 min_bound_kind, 384 tol_constraint, 385 tol_povm, 386 tol_prob, 387 tol_zero, 388 tol_schro, 389 case_id: cid.to_string(), 390 acceptance_id: aid.to_string(), 391 body_lines: lines[body_start..p.i].to_vec(), 392 sem_lines: lines[sem_start..sem_end].to_vec(), 393 acc_lines: lines[sem_end..acc_end].to_vec(), 394 file_sha256: String::new(), 395 level_r: Vec::new(), 396 }) 397 } 398 399 /// Rules 3 to 6 on a shape-valid, canonical, version-valid case. 400 fn rules_3_to_6(c: &mut Case, bad_param: Option) -> R<()> { 401 let ip = |m: String| Err((Refusal::InvalidParameter, m)); 402 if let Some(m) = bad_param { 403 return ip(m); 404 } 405 if c.n < 2 || c.n > 64 { 406 return ip(format!("clock_dim {} outside 2..64", c.n)); 407 } 408 for j in 1..c.n { 409 if c.e[j].cmp(&c.e[j - 1]) != std::cmp::Ordering::Greater { 410 return ip("clock_energies not strictly increasing".into()); 411 } 412 } 413 if c.psi[0].is_zero() && c.psi[1].is_zero() { 414 return ip("reference_system_state is zero".into()); 415 } 416 if c.w.signum() <= 0 { 417 return ip("povm_weight <= 0".into()); 418 } 419 if c.tau.signum() <= 0 { 420 return ip("povm_tau_turns <= 0".into()); 421 } 422 if c.m < 1 || c.m > 256 { 423 return ip(format!("clock_label_count {} outside 1..256", c.m)); 424 } 425 let mut ref_index = None; 426 for k in 0..c.m { 427 if c.labels[..k].contains(&c.labels[k]) { 428 return ip("duplicate clock label".into()); 429 } 430 if c.labels[k] == c.ref_label { 431 ref_index = Some(k); 432 } 433 } 434 match ref_index { 435 None => return ip("reference_clock_label not among the clock labels".into()), 436 Some(r) => c.ref_index = r, 437 } 438 // rule 4, per level, exact 439 let mut rs = Vec::new(); 440 for j in 0..c.n { 441 let nx = c.h[0].add(&c.v[j][0]); 442 let ny = c.h[1].add(&c.v[j][1]); 443 let nz = c.h[2].add(&c.v[j][2]); 444 let r2 = nx.mul(&nx).add(&ny.mul(&ny)).add(&nz.mul(&nz)); 445 match r2.sqrt_exact() { 446 Some(r) => rs.push(r), 447 None => return Err((Refusal::IrrationalSpectrum, format!("level {}: |h + v_j|^2 = {} is not a rational square", j, r2.text()))), 448 } 449 } 450 c.level_r = rs; 451 // rule 5 452 let cid = tagged_hex(CASE_DOMAIN, &join_lf(&c.sem_lines)); 453 let aid = tagged_hex(ACC_DOMAIN, &join_lf(&c.acc_lines)); 454 if cid != c.case_id { 455 return Err((Refusal::IdMismatch, format!("case_id recomputes to {}", cid))); 456 } 457 if aid != c.acceptance_id { 458 return Err((Refusal::IdMismatch, format!("acceptance_id recomputes to {}", aid))); 459 } 460 // rule 6 461 if c.expected_pass { 462 if !c.expected_codes.is_empty() { 463 return ip("expected_failure_codes must be none when expected_outcome PASS".into()); 464 } 465 } else { 466 if c.expected_codes.is_empty() { 467 return ip("expected_failure_codes empty with expected_outcome FAIL".into()); 468 } 469 for i in 1..c.expected_codes.len() { 470 if c.expected_codes[i - 1].as_bytes() >= c.expected_codes[i].as_bytes() { 471 return ip("expected_failure_codes not sorted or not unique".into()); 472 } 473 } 474 for code in &c.expected_codes { 475 if !FAILURE_CODES.contains(&code.as_str()) { 476 return ip(format!("{} is not an AT1_RESULT_V1 failure code", code)); 477 } 478 } 479 } 480 Ok(()) 481 } 482 483 /// Parses and validates the lines of a body (case_name .. acceptance_id) that 484 /// sit after the three version lines (already checked by the caller). 485 pub fn validate_lines(lines: &[String], start: usize, bad_version: Option) -> R<(Case, usize)> { 486 let mut p = P { lines, i: start, noncanon: None, bad_param: None, bad_version }; 487 let mut c = parse_body(&mut p)?; 488 let end = p.i; 489 if let Some(m) = p.noncanon.take() { 490 return Err((Refusal::NonCanonical, m)); 491 } 492 if let Some(m) = p.bad_version.take() { 493 return Err((Refusal::UnsupportedVersion, m)); 494 } 495 rules_3_to_6(&mut c, p.bad_param.take())?; 496 Ok((c, end)) 497 } 498 499 /// Full case file validation in contract order. 500 pub fn validate_bytes(bytes: &[u8]) -> R { 501 let lines = lines_checked(bytes).map_err(|m| (Refusal::ParseError, m))?; 502 let mut bad_version = None; 503 // reading (d): first token is the key (shape, step 1); the rest is the value (step 2) 504 let ver = [("OMEGA-AT1-CASE", "v1"), ("domain", CASE_DOMAIN), ("contract", "AT1_CASE_V1")]; 505 for (i, (k, val)) in ver.iter().enumerate() { 506 let l = lines.get(i).ok_or((Refusal::ParseError, "file too short".to_string()))?; 507 let t: Vec<&str> = l.split(' ').collect(); 508 if t[0] != *k || t.len() != 2 { 509 return Err((Refusal::ParseError, format!("line {}: expected version line with key {}", i + 1, k))); 510 } 511 if t[1] != *val && bad_version.is_none() { 512 bad_version = Some(format!("line {}: {} {} is not {}", i + 1, k, t[1], val)); 513 } 514 } 515 // shape of the remainder must be checked before the version value is reported 516 let mut p = P { lines: &lines, i: 3, noncanon: None, bad_param: None, bad_version }; 517 let mut c = parse_body(&mut p)?; 518 p.exact("end")?; 519 if p.i != lines.len() { 520 return perr(format!("line {}: content after `end`", p.i + 1)); 521 } 522 if let Some(m) = p.noncanon.take() { 523 return Err((Refusal::NonCanonical, m)); 524 } 525 if let Some(m) = p.bad_version.take() { 526 return Err((Refusal::UnsupportedVersion, m)); 527 } 528 rules_3_to_6(&mut c, p.bad_param.take())?; 529 c.file_sha256 = sha256_hex(bytes); 530 Ok(c) 531 } 532 533 /// Rebuilds the exact bytes of the case file a result was made from (the result 534 /// copies every line except the three version lines and `end`). 535 pub fn case_bytes_from_body(body: &[String]) -> Vec { 536 let mut lines = vec!["OMEGA-AT1-CASE v1".to_string(), format!("domain {}", CASE_DOMAIN), "contract AT1_CASE_V1".to_string()]; 537 lines.extend_from_slice(body); 538 lines.push("end".into()); 539 join_lf(&lines) 540 } 541 542 /// Case generator: canonical text with both identities computed. 543 #[derive(Clone, Debug)] 544 pub struct Spec { 545 pub name: String, 546 pub e: Vec, 547 pub h: [Q; 4], 548 pub v: Vec<[Q; 3]>, 549 pub ref_label: String, 550 pub psi: [Cq; 2], 551 pub tau: Q, 552 pub w: Q, 553 pub labels: Vec, 554 pub control_positive: bool, 555 pub target_ideal: bool, 556 pub expected_pass: bool, 557 pub codes: Vec, 558 pub min_bk: String, 559 pub tols: [String; 5], 560 } 561 562 impl Spec { 563 /// The base clock B of AT1_SPEC section 13 with zero coupling. 564 pub fn base(name: &str) -> Spec { 565 let z = Q::zero; 566 Spec { 567 name: name.into(), 568 e: vec![Q::frac(-3, 2), Q::frac(-1, 2), Q::frac(1, 2), Q::frac(3, 2)], 569 h: [z(), z(), z(), Q::frac(1, 2)], 570 v: vec![[z(), z(), z()], [z(), z(), z()], [z(), z(), z()], [z(), z(), z()]], 571 ref_label: "t0".into(), 572 psi: [Cq::real(Q::one()), Cq::real(Q::one())], 573 tau: Q::frac(1, 4), 574 w: Q::one(), 575 labels: (0..4).map(|k| format!("t{}", k)).collect(), 576 control_positive: true, 577 target_ideal: false, 578 expected_pass: true, 579 codes: Vec::new(), 580 min_bk: "ESTIMATED".into(), 581 tols: ["1@12".into(), "1@12".into(), "1@12".into(), "1@9".into(), "1@12".into()], 582 } 583 } 584 pub fn negative(mut self, codes: &[&str]) -> Spec { 585 self.control_positive = false; 586 self.expected_pass = false; 587 self.codes = codes.iter().map(|s| s.to_string()).collect(); 588 self 589 } 590 pub fn lines(&self) -> Vec { 591 // the empty list is written `none` (AT1_CASE_V1 section 2) 592 let qs = |v: &[Q]| if v.is_empty() { "none".to_string() } else { v.iter().map(|q| q.text()).collect::>().join(",") }; 593 let cs = |z: &Cq| format!("({};{})", z.re.text(), z.im.text()); 594 let mut sem = vec!["begin semantic".to_string(), "model_family PAGE_WOOTTERS_FINITE_CLOCKDIAG".into(), "energy_unit DIMENSIONLESS_HBAR_1".into()]; 595 sem.push(format!("clock_dim {}", self.e.len())); 596 sem.push(format!("clock_energies {}", qs(&self.e))); 597 sem.push("system_dim 2".into()); 598 sem.push(format!("system_hamiltonian_pauli {}", qs(&self.h))); 599 sem.push("interaction CLOCK_DIAGONAL_PAULI".into()); 600 for (j, v) in self.v.iter().enumerate() { 601 sem.push(format!("interaction_pauli {} {}", j, qs(v))); 602 } 603 sem.push("constraint SUM_HC_HS_V".into()); 604 sem.push("physical_state NULLSPACE_PROJECTION".into()); 605 sem.push(format!("reference_clock_label {}", self.ref_label)); 606 sem.push(format!("reference_system_state {},{}", cs(&self.psi[0]), cs(&self.psi[1]))); 607 sem.push("clock_povm COVARIANT_DISCRETE".into()); 608 sem.push(format!("povm_tau_turns {}", self.tau.text())); 609 sem.push(format!("povm_weight {}", self.w.text())); 610 sem.push(format!("clock_label_count {}", self.labels.len())); 611 for (k, l) in self.labels.iter().enumerate() { 612 sem.push(format!("clock_label {} {}", k, l)); 613 } 614 sem.push("observables PAULI_X,PAULI_Y,PAULI_Z".into()); 615 sem.push("end semantic".into()); 616 let acc = vec![ 617 "begin acceptance".to_string(), 618 format!("control_kind {}", if self.control_positive { "POSITIVE" } else { "NEGATIVE" }), 619 format!("prediction_target {}", if self.target_ideal { "IDEAL" } else { "INTERACTING" }), 620 format!("expected_outcome {}", if self.expected_pass { "PASS" } else { "FAIL" }), 621 format!("expected_failure_codes {}", if self.codes.is_empty() { "none".to_string() } else { self.codes.join(",") }), 622 format!("min_bound_kind {}", self.min_bk), 623 format!("tol_constraint_residual {}", self.tols[0]), 624 format!("tol_povm_residual {}", self.tols[1]), 625 format!("tol_probability {}", self.tols[2]), 626 format!("tol_zero_probability {}", self.tols[3]), 627 format!("tol_schrodinger {}", self.tols[4]), 628 "end acceptance".to_string(), 629 ]; 630 let mut out = vec!["OMEGA-AT1-CASE v1".to_string(), format!("domain {}", CASE_DOMAIN), "contract AT1_CASE_V1".into(), format!("case_name {}", self.name)]; 631 out.extend(sem); 632 out.extend(acc); 633 out.push("case_id 0".into()); 634 out.push("acceptance_id 0".into()); 635 out.push("end".into()); 636 recompute_ids(&mut out); 637 out 638 } 639 pub fn bytes(&self) -> Vec { 640 join_lf(&self.lines()) 641 } 642 } 643 644 /// Rewrites the case_id and acceptance_id lines of a (possibly defective) case 645 /// text from its current semantic and acceptance blocks, when they can be found. 646 pub fn recompute_ids(lines: &mut [String]) { 647 let find = |s: &str| lines.iter().position(|l| l == s); 648 if let (Some(a), Some(b)) = (find("begin semantic"), find("end semantic")) { 649 if a < b { 650 let cid = tagged_hex(CASE_DOMAIN, &join_lf(&lines[a..=b])); 651 if let Some(i) = lines.iter().position(|l| l.starts_with("case_id ")) { 652 lines[i] = format!("case_id {}", cid); 653 } 654 } 655 } 656 let find = |s: &str| lines.iter().position(|l| l == s); 657 if let (Some(a), Some(b)) = (find("begin acceptance"), find("end acceptance")) { 658 if a < b { 659 let aid = tagged_hex(ACC_DOMAIN, &join_lf(&lines[a..=b])); 660 if let Some(i) = lines.iter().position(|l| l.starts_with("acceptance_id ")) { 661 lines[i] = format!("acceptance_id {}", aid); 662 } 663 } 664 } 665 }