1use std::collections::HashMap;
4
5#[derive(Clone, Debug, PartialEq)]
7pub enum QShotValType {
8 Bool(bool),
10 Int(i64),
12 Float(f64),
14}
15
16#[derive(Clone, Debug, PartialEq)]
18pub enum QsysShotItemValue {
19 Scalar(QShotValType),
21 List(Vec<QShotValType>),
23 Invalid,
25}
26
27impl QShotValType {
28 fn text(&self) -> String {
29 match self {
30 Self::Bool(value) => if *value { "True" } else { "False" }.to_owned(),
31 Self::Int(value) => value.to_string(),
32 Self::Float(value) if value.is_nan() => "nan".to_owned(),
33 Self::Float(value) if value.is_finite() && value.fract() == 0.0 => format!("{value}.0"),
34 Self::Float(value) => value.to_string(),
35 }
36 }
37}
38
39pub type QsysShotItem = (String, QsysShotItemValue);
41pub type QsysShot = Vec<QsysShotItem>;
43pub type QsysShots = Vec<QsysShot>;
45pub type QirMetadata = HashMap<String, String>;
47
48#[derive(Default)]
50pub struct QirOutput {
51 pub text: String,
53 pub malformed: usize,
55}
56
57pub enum FormattedValue {
59 Original,
61 Text(String),
63 Invalid,
65}
66
67#[derive(Default)]
69pub struct QirLabeledFormatter;
70
71impl QirLabeledFormatter {
72 pub const fn new() -> Self {
74 Self
75 }
76
77 pub fn _val_null(&self, tag: Option<&str>, val: &QsysShotItemValue) -> bool {
79 tag.is_some() && !matches!(val, QsysShotItemValue::Invalid)
80 }
81
82 pub fn _val_tag_type(&self, tag: Option<&str>, _val: &QsysShotItemValue) -> bool {
84 tag.is_some()
85 }
86
87 pub fn validate_tag_and_value(&self, tag: Option<&str>, val: &QsysShotItemValue) -> bool {
89 self._val_tag_type(tag, val) && self._val_null(tag, val)
90 }
91
92 pub fn results_header(&self, qo: &mut QirOutput) {
94 qo.text.push_str("HEADER\tschema_id\tlabeled\n");
95 qo.text.push_str("HEADER\tschema_version\t2.1\n");
96 }
97
98 pub fn first_shot_header(&self, qo: &mut QirOutput, attributes: &QirMetadata) {
100 qo.text.push_str("START\n");
101 qo.text.push_str("METADATA\tentry_point\n");
102 for (key, default) in [
103 ("qir_profiles", "base_profile"),
104 ("required_num_qubits", "0"),
105 ("required_num_results", "0"),
106 ] {
107 let value = attributes.get(key).map(String::as_str).unwrap_or(default);
108 qo.text.push_str(&format!("METADATA\t{key}\t{value}\n"));
109 }
110 }
111
112 pub fn shot_footer(&self, qo: &mut QirOutput) {
114 qo.text.push_str("END\t0\n");
115 }
116
117 pub fn format_value(&self, type_str: &str, val: &QsysShotItemValue) -> FormattedValue {
119 use QShotValType::{Bool, Float, Int};
120 use QsysShotItemValue::{Invalid, List, Scalar};
121 match type_str {
122 "RESULT_ARRAY" => {
123 let List(values) = val else {
124 return FormattedValue::Invalid;
125 };
126 let bits: Option<String> = values
127 .iter()
128 .map(|value| match value {
129 Bool(false) | Int(0) => Some('0'),
130 Bool(true) | Int(1) => Some('1'),
131 _ => None,
132 })
133 .collect();
134 bits.map(FormattedValue::Text)
135 .unwrap_or(FormattedValue::Invalid)
136 }
137 "BOOL" => {
138 let truthy = match val {
140 Scalar(Bool(value)) => *value,
141 Scalar(Int(value)) => *value != 0,
142 Scalar(Float(value)) => *value != 0.0,
143 List(values) => !values.is_empty(),
144 Invalid => false,
145 };
146 FormattedValue::Text(truthy.to_string())
147 }
148 _ => FormattedValue::Original,
149 }
150 }
151
152 pub fn emit(
154 &self,
155 qo: &mut QirOutput,
156 ftype: &str,
157 tag: Option<&str>,
158 val: &QsysShotItemValue,
159 ) {
160 let qir_type = match ftype {
162 "INT" | "UINT" => "INT",
163 "FLOAT" => "DOUBLE",
164 "BOOL" | "RESULT" | "RESULT_ARRAY" => ftype,
165 "QIRARRAY" => "ARRAY",
166 "QIRTUPLE" => "TUPLE",
167 _ => return,
168 };
169 let text = match self.format_value(qir_type, val) {
170 FormattedValue::Text(text) => Some(text),
171 FormattedValue::Original => match val {
172 QsysShotItemValue::Scalar(value) => Some(value.text()),
173 QsysShotItemValue::List(values) => Some(format!(
174 "[{}]",
175 values
176 .iter()
177 .map(QShotValType::text)
178 .collect::<Vec<_>>()
179 .join(", ")
180 )),
181 QsysShotItemValue::Invalid => None,
182 },
183 FormattedValue::Invalid => None,
184 };
185 let Some(text) = text else {
186 log::warn!(
187 "Skipping malformed QIR output value: raw_type={ftype:?}, qir_type={qir_type:?}, tag={tag:?}, value={val:?}"
188 );
189 qo.malformed += 1;
190 return;
191 };
192 if self.validate_tag_and_value(tag, val) {
193 qo.text
194 .push_str(&format!("OUTPUT\t{qir_type}\t{text}\t{}\n", tag.unwrap()));
195 }
196 }
197
198 pub fn emit_values_in_shot(&self, qo: &mut QirOutput, shot: &QsysShot) {
200 for (name, value) in shot {
201 if let Some((ftype, tag)) = name
202 .strip_prefix("USER:")
203 .and_then(|name| name.split_once(':'))
204 {
205 self.emit(qo, ftype, Some(tag), value);
206 }
207 }
208 }
209
210 pub fn write_shot(&self, qo: &mut QirOutput, shot: &QsysShot) {
212 qo.text.push_str("START\n");
213 self.emit_values_in_shot(qo, shot);
214 self.shot_footer(qo);
215 }
216
217 pub fn write_first_shot(&self, qo: &mut QirOutput, shot: &QsysShot, attributes: &QirMetadata) {
219 self.first_shot_header(qo, attributes);
220 self.emit_values_in_shot(qo, shot);
221 self.shot_footer(qo);
222 }
223
224 pub fn write_results(
226 &self,
227 qo: &mut QirOutput,
228 results: &[QsysShot],
229 attributes: &QirMetadata,
230 ) {
231 if let Some((first, remaining)) = results.split_first() {
232 self.results_header(qo);
233 self.write_first_shot(qo, first, attributes);
234 for shot in remaining {
235 self.write_shot(qo, shot);
236 }
237 }
238 }
239
240 pub fn qir_labeled_output(&self, results: &[QsysShot], attributes: &QirMetadata) -> String {
243 let mut output = QirOutput::default();
244 self.write_results(&mut output, results, attributes);
245 output.text
246 }
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
254 use QShotValType::{Bool, Float, Int};
255 use QsysShotItemValue::{Invalid, List, Scalar};
256
257 fn shot(items: impl IntoIterator<Item = (&'static str, QsysShotItemValue)>) -> QsysShot {
258 items
259 .into_iter()
260 .map(|(tag, value)| (tag.into(), value))
261 .collect()
262 }
263
264 #[test]
266 #[allow(clippy::approx_constant)] fn test_formatting() {
268 for (ftype, tag, value, expected) in [
269 ("INT", "i0", Scalar(Int(42)), "OUTPUT\tINT\t42\ti0\n"),
270 ("UINT", "ui0", Scalar(Int(99)), "OUTPUT\tINT\t99\tui0\n"),
271 (
272 "FLOAT",
273 "f0",
274 Scalar(Float(3.1415926)),
275 "OUTPUT\tDOUBLE\t3.1415926\tf0\n",
276 ),
277 ("BOOL", "b0", Scalar(Int(0)), "OUTPUT\tBOOL\tfalse\tb0\n"),
278 ("RESULT", "r0", Scalar(Int(0)), "OUTPUT\tRESULT\t0\tr0\n"),
279 (
280 "RESULT_ARRAY",
281 "ra0",
282 List(vec![Int(1), Int(0), Int(1)]),
283 "OUTPUT\tRESULT_ARRAY\t101\tra0\n",
284 ),
285 ("QIRARRAY", "a0", Scalar(Int(4)), "OUTPUT\tARRAY\t4\ta0\n"),
286 ("QIRTUPLE", "t0", Scalar(Int(13)), "OUTPUT\tTUPLE\t13\tt0\n"),
287 ] {
288 let mut output = QirOutput::default();
289 QirLabeledFormatter::new().emit(&mut output, ftype, Some(tag), &value);
290 assert_eq!(output.text, expected, "{ftype}");
291 }
292 }
293
294 #[test]
296 fn test_result_list() {
297 let results = vec![
299 shot([
300 ("USER:INT:i1", Scalar(Int(42))),
301 ("USER:BOOL:b1", Scalar(Int(1))),
302 ]),
303 shot([
304 ("USER:RESULT:r1", Scalar(Int(99))),
305 ("USER:INT:i2", Scalar(Int(-54321))),
306 ("USER:FLOAT:f1", Scalar(Float(std::f64::consts::E))),
307 ]),
308 shot([
309 ("USER:FLOAT:φ", Scalar(Float(std::f64::consts::PI))),
310 ("USER:INT:large", Scalar(Int(i64::MAX))),
311 ("USER:INT:neg", Scalar(Int(i64::MIN))),
312 ]),
313 shot([(
314 "USER:RESULT_ARRAY:results",
315 List(vec![Int(1), Int(0), Int(1), Int(1)]),
316 )]),
317 shot([
318 ("USER:QIRARRAY:0_a", Scalar(Int(2))),
319 ("USER:QIRTUPLE:1_a0t", Scalar(Int(2))),
320 ("USER:INT:2_a0t0i", Scalar(Int(42))),
321 ("USER:RESULT:3_a0t1r", Scalar(Int(0))),
322 ("USER:QIRTUPLE:4_a1t", Scalar(Int(2))),
323 ("USER:INT:5_a1t0i", Scalar(Int(33))),
324 ("USER:RESULT:6_a1t1r", Scalar(Int(1))),
325 ]),
326 ];
327 let attributes = QirMetadata::from([
328 ("qir_profiles".into(), "base_profile".into()),
329 ("required_num_qubits".into(), "9".into()),
330 ("required_num_results".into(), "9".into()),
331 ]);
332 assert_eq!(
333 QirLabeledFormatter::new().qir_labeled_output(&results, &attributes),
334 include_str!("tests/data/good1.output")
335 );
336 }
337
338 #[test]
341 fn test_full_raw_result_list() {
342 let results = vec![
343 shot([
344 ("MEAS:BOOL:", Scalar(Int(1))),
345 ("MEAS:BOOL:", Scalar(Int(1))),
346 ("MEAS:BOOL:", Scalar(Int(0))),
347 ("USER:INT:reg1", Scalar(Int(3))),
348 ("USER:FLOAT:reg2", Scalar(Float(1.43))),
349 ("USER:INT:reg:3", Scalar(Int(1))),
350 ("METRICS:INT:SQ", Scalar(Int(12))),
351 ("METRICS:INT:TQ", Scalar(Int(15))),
352 ("METRICS:INT:SPAM", Scalar(Int(8))),
353 ("METRICS:INT:NumQubits", Scalar(Int(4))),
354 ("METRICS:FLOAT:ShotTime", Scalar(Float(0.0194))),
355 ]),
356 shot([
357 ("MEAS:BOOL:", Scalar(Int(0))),
358 ("MEAS:BOOL:", Scalar(Int(1))),
359 ("MEAS:BOOL:", Scalar(Int(0))),
360 ("MEAS:BOOL:", Scalar(Int(1))),
361 ("USER:INT:reg1", Scalar(Int(9))),
362 ("MEAS:BOOL:", Scalar(Int(1))),
363 ("MEAS:BOOL:", Scalar(Int(0))),
364 ("USER:INTARR:reg3", List(vec![Int(5), Int(12)])),
365 ("METRICS:INT:SQ", Scalar(Int(15))),
366 ("METRICS:INT:TQ", Scalar(Int(19))),
367 ("METRICS:INT:SPAM", Scalar(Int(12))),
368 ("METRICS:FLOAT:ShotTime", Scalar(Float(0.0394))),
369 ]),
370 shot([
371 ("MEAS:BOOL:", Scalar(Int(1))),
372 ("MEAS:BOOL:", Scalar(Int(1))),
373 ("MEAS:BOOL:", Scalar(Int(1))),
374 ("MEAS:BOOL:", Scalar(Int(1))),
375 ("USER:INT:reg1", Scalar(Int(-2))),
376 (
377 "EXIT:INT:Unexpected results indicating deep flaw/exit",
378 Scalar(Int(1000)),
379 ),
380 ("METRICS:INT:SQ", Scalar(Int(12))),
381 ("METRICS:INT:TQ", Scalar(Int(15))),
382 ("METRICS:INT:SPAM", Scalar(Int(8))),
383 ("METRICS:FLOAT:ShotTime", Scalar(Float(0.0194))),
384 ]),
385 ];
386 let attributes = QirMetadata::from([
387 ("qir_profiles".into(), "base_profile".into()),
388 ("required_num_qubits".into(), "9".into()),
389 ("required_num_results".into(), "3".into()),
390 ]);
391 for (attributes, expected) in [
392 (attributes, include_str!("tests/data/full1.output")),
393 (
394 QirMetadata::new(),
395 include_str!("tests/data/missing_attributes.output"),
396 ),
397 ] {
398 assert_eq!(
399 QirLabeledFormatter::new().qir_labeled_output(&results, &attributes),
400 expected
401 );
402 }
403 }
404
405 #[test]
407 fn test_ignored_types() {
408 for ftype in ["BOOLARR", "INTARR", "UINTARR", "FLOATARR"] {
409 let mut output = QirOutput::default();
410 QirLabeledFormatter::new().emit(
411 &mut output,
412 ftype,
413 Some("aggr"),
414 &List(vec![Int(1), Int(1), Int(0)]),
415 );
416 assert!(output.text.is_empty(), "{ftype}");
417 assert_eq!(output.malformed, 0);
418 }
419 }
420
421 #[test]
423 fn test_undefined_type() {
424 let mut output = QirOutput::default();
425 QirLabeledFormatter::new().emit(
426 &mut output,
427 "UINT32",
428 Some("aggr"),
429 &List(vec![Int(1), Int(1), Int(0)]),
430 );
431 assert!(output.text.is_empty());
432 }
433
434 #[test]
436 fn test_malformed() {
437 for (ftype, tag, value) in [
439 ("INT", None, Scalar(Int(0))),
440 ("INT", Some("syndrome0"), Invalid),
441 ("BOOL", None, Invalid),
442 ("FLOAT", None, Scalar(Int(99))),
443 ("", None, Invalid),
444 ] {
445 let mut output = QirOutput::default();
446 QirLabeledFormatter::new().emit(&mut output, ftype, tag, &value);
447 assert!(output.text.is_empty(), "{ftype}");
448 }
449 }
450
451 #[test]
454 fn test_malformed_raw_result_list() {
455 let results = vec![shot([
457 ("USER:INT:reg1", Scalar(Int(3))),
458 ("USER::reg3", Scalar(Float(1.414))),
459 ("USER:RESULT:r1", Invalid),
460 ("USER:FLOAT:reg2", Scalar(Float(1.43))),
461 (":INT:i0", Scalar(Int(1))),
462 ("::i0", Scalar(Int(1))),
463 (":::", Scalar(Int(1))),
464 ("::", Scalar(Int(0))),
465 (":", Scalar(Int(0))),
466 (":", Invalid),
467 (":", Invalid),
468 ("f", Invalid),
469 ("f", Invalid),
470 ("USER:BOOL:", Scalar(Int(1))),
471 ])];
472 let attributes = QirMetadata::from([
473 ("qir_profiles".into(), "base_profile".into()),
474 ("required_num_qubits".into(), "9".into()),
475 ("required_num_results".into(), "9".into()),
476 ]);
477 assert_eq!(
478 QirLabeledFormatter::new().qir_labeled_output(&results, &attributes),
479 include_str!("tests/data/malformed1.output")
480 );
481 }
482
483 #[test]
485 fn test_empty_tag_submission() {
486 let results = vec![shot([
487 ("USER:QIRARRAY:", Scalar(Int(2))),
488 ("USER:QIRTUPLE:", Scalar(Int(2))),
489 ])];
490 let output = QirLabeledFormatter::new().qir_labeled_output(&results, &QirMetadata::new());
491 assert!(output.contains("OUTPUT\tARRAY\t2\t\n"));
493 assert!(output.contains("OUTPUT\tTUPLE\t2\t\n"));
494 }
495
496 #[test]
498 fn test_result_array_formatting() {
499 for (value, expected) in [
500 (vec![], ""),
501 (vec![Bool(false), Bool(true), Bool(false)], "010"),
502 ] {
503 let mut output = QirOutput::default();
504 QirLabeledFormatter::new().emit(
505 &mut output,
506 "RESULT_ARRAY",
507 Some("results"),
508 &List(value),
509 );
510 assert_eq!(
511 output.text,
512 format!("OUTPUT\tRESULT_ARRAY\t{expected}\tresults\n")
513 );
514 }
515 }
516
517 #[test]
519 fn test_malformed_result_array_is_ignored() {
520 use std::sync::atomic::{AtomicUsize, Ordering};
521
522 struct Logger(AtomicUsize);
523 impl log::Log for Logger {
524 fn enabled(&self, _: &log::Metadata<'_>) -> bool {
525 true
526 }
527 fn log(&self, record: &log::Record<'_>) {
528 let message = record.args().to_string();
529 if message.contains("tag=Some(\"results\")") {
531 assert_eq!(record.level(), log::Level::Warn);
532 assert!(message.starts_with("Skipping malformed QIR output value"));
533 self.0.fetch_add(1, Ordering::Relaxed);
534 }
535 }
536 fn flush(&self) {}
537 }
538 static LOGGER: Logger = Logger(AtomicUsize::new(0));
539 log::set_logger(&LOGGER).unwrap();
540 log::set_max_level(log::LevelFilter::Warn);
541
542 for value in [
544 Invalid,
545 Scalar(Int(1)),
546 Invalid,
547 List(vec![Int(2)]),
548 Invalid,
549 Invalid,
550 ] {
551 let mut output = QirOutput::default();
552 QirLabeledFormatter::new().emit(&mut output, "RESULT_ARRAY", Some("results"), &value);
553 assert!(output.text.is_empty());
554 assert_eq!(output.malformed, 1);
555 }
556 assert_eq!(LOGGER.0.load(Ordering::Relaxed), 6);
557 }
558
559 #[test]
560 fn formats_scalar_types_and_empty_tags() {
561 let formatter = QirLabeledFormatter::new();
562 for (raw, value, expected) in [
563 ("INT", Int(42), "INT\t42"),
564 ("UINT", Int(99), "INT\t99"),
565 ("FLOAT", Float(1.5), "DOUBLE\t1.5"),
566 ("BOOL", Int(0), "BOOL\tfalse"),
567 ("RESULT", Int(1), "RESULT\t1"),
568 ("QIRARRAY", Int(4), "ARRAY\t4"),
569 ("QIRTUPLE", Int(2), "TUPLE\t2"),
570 ] {
571 let mut output = QirOutput::default();
572 formatter.emit(&mut output, raw, Some(""), &Scalar(value));
573 assert_eq!(output.text, format!("OUTPUT\t{expected}\t\n"));
574 assert_eq!(output.malformed, 0);
575 }
576 }
577
578 #[test]
579 fn result_arrays_and_malformed_inputs() {
580 let formatter = QirLabeledFormatter::new();
581 let mut output = QirOutput::default();
582 formatter.emit(
583 &mut output,
584 "RESULT_ARRAY",
585 Some("bits"),
586 &List(vec![Bool(true), Int(0), Int(1)]),
587 );
588 assert_eq!(output.text, "OUTPUT\tRESULT_ARRAY\t101\tbits\n");
589 for value in [
590 Invalid,
591 Scalar(Int(1)),
592 List(vec![Int(2)]),
593 List(vec![Float(1.0)]),
594 ] {
595 formatter.emit(&mut output, "RESULT_ARRAY", Some("bits"), &value);
596 }
597 assert_eq!(output.malformed, 4);
598 formatter.emit(&mut output, "unknown", Some("tag"), &Invalid);
599 formatter.emit(&mut output, "INT", None, &Scalar(Int(1)));
600 assert_eq!(output.malformed, 4);
601 assert!(!formatter.validate_tag_and_value(Some("tag"), &Invalid));
602 }
603
604 #[test]
605 fn shot_methods_compose() {
606 let formatter = QirLabeledFormatter::new();
607 let shots = vec![vec![("USER:INT:a".into(), Scalar(Int(42)))], vec![]];
608 let attributes = QirMetadata::new();
609 let mut output = QirOutput::default();
610 formatter.results_header(&mut output);
611 formatter.write_first_shot(&mut output, &shots[0], &attributes);
612 formatter.write_shot(&mut output, &shots[1]);
613 assert_eq!(
614 formatter.qir_labeled_output(&shots, &attributes),
615 output.text
616 );
617 assert_eq!(formatter.qir_labeled_output(&[], &attributes), "");
618 assert!(output.text.ends_with("END\t0\nSTART\nEND\t0\n"));
619 }
620
621 #[test]
622 fn matches_shared_malformed_fixture() {
623 let shots = vec![vec![
624 ("USER:INT:reg1".into(), Scalar(Int(3))),
625 ("USER::reg3".into(), Scalar(Float(1.414))),
626 ("USER:RESULT:r1".into(), Invalid),
627 ("USER:FLOAT:reg2".into(), Scalar(Float(1.43))),
628 (":INT:i0".into(), Scalar(Int(1))),
629 ("USER:BOOL:".into(), Scalar(Int(1))),
630 ]];
631 let attributes = QirMetadata::from([
632 ("required_num_qubits".into(), "9".into()),
633 ("required_num_results".into(), "9".into()),
634 ]);
635 assert_eq!(
636 QirLabeledFormatter::new().qir_labeled_output(&shots, &attributes),
637 include_str!("tests/data/malformed1.output")
638 );
639 }
640}