hugr_core/utils.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
//! General utilities.
use std::fmt::{self, Debug, Display};
use itertools::Itertools;
use crate::{ops::Value, Hugr, HugrView, IncomingPort, Node};
/// Write a comma separated list of of some types.
/// Like debug_list, but using the Display instance rather than Debug,
/// and not adding surrounding square brackets.
pub fn display_list<T>(ts: impl IntoIterator<Item = T>, f: &mut fmt::Formatter) -> fmt::Result
where
T: Display,
{
display_list_with_separator(ts, f, ", ")
}
/// Write a separated list of of some types, using a custom separator.
/// Like debug_list, but using the Display instance rather than Debug,
/// and not adding surrounding square brackets.
pub fn display_list_with_separator<T>(
ts: impl IntoIterator<Item = T>,
f: &mut fmt::Formatter,
sep: &str,
) -> fmt::Result
where
T: Display,
{
let mut first = true;
for t in ts.into_iter() {
if !first {
f.write_str(sep)?;
}
t.fmt(f)?;
if first {
first = false;
}
}
Ok(())
}
/// Collect a vector into an array.
///
/// This is useful for deconstructing a vectors content.
///
/// # Example
///
/// ```ignore
/// let iter = 0..3;
/// let [a, b, c] = crate::utils::collect_array(iter);
/// assert_eq!(b, 1);
/// ```
///
/// # Panics
///
/// If the length of the slice is not equal to `N`.
///
/// See also [`try_collect_array`] for a non-panicking version.
#[inline]
pub fn collect_array<const N: usize, T: Debug>(arr: impl IntoIterator<Item = T>) -> [T; N] {
try_collect_array(arr).unwrap_or_else(|v| panic!("Expected {} elements, got {:?}", N, v))
}
/// Collect a vector into an array.
///
/// This is useful for deconstructing a vectors content.
///
/// # Example
///
/// ```ignore
/// let iter = 0..3;
/// let [a, b, c] = crate::utils::try_collect_array(iter)
/// .unwrap_or_else(|v| panic!("Expected 3 elements, got {:?}", v));
/// assert_eq!(b, 1);
/// ```
///
/// See also [`collect_array`].
#[inline]
pub fn try_collect_array<const N: usize, T>(
arr: impl IntoIterator<Item = T>,
) -> Result<[T; N], Vec<T>> {
arr.into_iter().collect_vec().try_into()
}
/// Helper method to skip serialization of default values in serde.
///
/// ```ignore
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct MyStruct {
/// #[serde(skip_serializing_if = "crate::utils::is_default")]
/// field: i32,
/// }
/// ```
///
/// From https://github.com/serde-rs/serde/issues/818.
#[allow(dead_code)]
pub(crate) fn is_default<T: Default + PartialEq>(t: &T) -> bool {
*t == Default::default()
}
#[cfg(test)]
pub(crate) mod test_quantum_extension {
use std::sync::Arc;
use crate::ops::{OpName, OpNameRef};
use crate::std_extensions::arithmetic::float_ops;
use crate::std_extensions::logic;
use crate::types::FuncValueType;
use crate::{
extension::{
prelude::{bool_t, qb_t},
ExtensionId, ExtensionRegistry, PRELUDE,
},
ops::ExtensionOp,
std_extensions::arithmetic::float_types,
type_row,
types::{PolyFuncTypeRV, Signature},
Extension,
};
use lazy_static::lazy_static;
fn one_qb_func() -> PolyFuncTypeRV {
FuncValueType::new_endo(qb_t()).into()
}
fn two_qb_func() -> PolyFuncTypeRV {
FuncValueType::new_endo(vec![qb_t(), qb_t()]).into()
}
/// The extension identifier.
pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("test.quantum");
fn extension() -> Arc<Extension> {
Extension::new_test_arc(EXTENSION_ID, |extension, extension_ref| {
extension
.add_op(
OpName::new_inline("H"),
"Hadamard".into(),
one_qb_func(),
extension_ref,
)
.unwrap();
extension
.add_op(
OpName::new_inline("RzF64"),
"Rotation specified by float".into(),
Signature::new(vec![qb_t(), float_types::float64_type()], vec![qb_t()]),
extension_ref,
)
.unwrap();
extension
.add_op(
OpName::new_inline("CX"),
"CX".into(),
two_qb_func(),
extension_ref,
)
.unwrap();
extension
.add_op(
OpName::new_inline("Measure"),
"Measure a qubit, returning the qubit and the measurement result.".into(),
Signature::new(vec![qb_t()], vec![qb_t(), bool_t()]),
extension_ref,
)
.unwrap();
extension
.add_op(
OpName::new_inline("QAlloc"),
"Allocate a new qubit.".into(),
Signature::new(type_row![], vec![qb_t()]),
extension_ref,
)
.unwrap();
extension
.add_op(
OpName::new_inline("QDiscard"),
"Discard a qubit.".into(),
Signature::new(vec![qb_t()], type_row![]),
extension_ref,
)
.unwrap();
})
}
lazy_static! {
/// Quantum extension definition.
pub static ref EXTENSION: Arc<Extension> = extension();
/// A registry with all necessary extensions to run tests internally, including the test quantum extension.
pub static ref REG: ExtensionRegistry = ExtensionRegistry::new([
EXTENSION.clone(),
PRELUDE.clone(),
float_types::EXTENSION.clone(),
float_ops::EXTENSION.clone(),
logic::EXTENSION.clone()
]);
}
fn get_gate(gate_name: &OpNameRef) -> ExtensionOp {
EXTENSION.instantiate_extension_op(gate_name, []).unwrap()
}
pub(crate) fn h_gate() -> ExtensionOp {
get_gate("H")
}
pub(crate) fn cx_gate() -> ExtensionOp {
get_gate("CX")
}
pub(crate) fn measure() -> ExtensionOp {
get_gate("Measure")
}
pub(crate) fn rz_f64() -> ExtensionOp {
get_gate("RzF64")
}
pub(crate) fn q_alloc() -> ExtensionOp {
get_gate("QAlloc")
}
pub(crate) fn q_discard() -> ExtensionOp {
get_gate("QDiscard")
}
}
/// Sort folding inputs with [`IncomingPort`] as key
fn sort_by_in_port(consts: &[(IncomingPort, Value)]) -> Vec<&(IncomingPort, Value)> {
let mut v: Vec<_> = consts.iter().collect();
v.sort_by_key(|(i, _)| i);
v
}
/// Sort some input constants by port and just return the constants.
pub fn sorted_consts(consts: &[(IncomingPort, Value)]) -> Vec<&Value> {
sort_by_in_port(consts)
.into_iter()
.map(|(_, c)| c)
.collect()
}
/// Calculate the depth of a node in the hierarchy.
pub fn depth(h: &Hugr, n: Node) -> u32 {
match h.get_parent(n) {
Some(p) => 1 + depth(h, p),
None => 0,
}
}
#[allow(dead_code)]
// Test only utils
#[cfg(test)]
pub(crate) mod test {
#[allow(unused_imports)]
use crate::HugrView;
use crate::{
ops::{OpType, Value},
Hugr,
};
/// Check that a hugr just loads and returns a single expected constant.
pub(crate) fn assert_fully_folded(h: &Hugr, expected_value: &Value) {
assert_fully_folded_with(h, |v| v == expected_value)
}
/// Check that a hugr just loads and returns a single constant, and validate
/// that constant using `check_value`.
///
/// [CustomConst::equals_const] is not required to be implemented. Use this
/// function for Values containing such a `CustomConst`.
pub(crate) fn assert_fully_folded_with(h: &Hugr, check_value: impl Fn(&Value) -> bool) {
let mut node_count = 0;
for node in h.children(h.root()) {
let op = h.get_optype(node);
match op {
OpType::Input(_) | OpType::Output(_) | OpType::LoadConstant(_) => node_count += 1,
OpType::Const(c) if check_value(c.value()) => node_count += 1,
_ => panic!("unexpected op: {}\n{}", op, h.mermaid_string()),
}
}
assert_eq!(node_count, 4);
}
}