use polypus::circuit::{Param, ParameterizedCircuit};
use polypus::evaluation::{CircuitSource, EvaluationError};
use polypus::infrastructure::BoundCircuit;
fn qaoa_template() -> ParameterizedCircuit {
let edges = [(0usize, 1usize), (1, 2), (2, 3), (3, 0)];
let mut qc = ParameterizedCircuit::new(4);
for q in 0..4 {
qc = qc.h(q);
}
for &(a, b) in &edges {
qc = qc.rzz(a, b, Param(0));
}
for q in 0..4 {
qc = qc.rx(q, Param(1));
}
qc.measure_all()
}
#[test]
fn native_bind_requires_no_python_interpreter() {
let source = CircuitSource::Native(qaoa_template());
let bound = source
.bind(&[0.4, 0.8])
.expect("binding a valid native template must succeed");
match bound {
BoundCircuit::Native(circuit) => {
let qasm = circuit.try_to_qasm2().unwrap();
assert!(qasm.starts_with("OPENQASM 2.0;"));
assert!(qasm.contains("rzz(0.4) q[0],q[1];"));
assert!(qasm.contains("rx(0.8) q[3];"));
assert!(qasm.ends_with("measure q -> c;\n"));
}
BoundCircuit::Qasm2(_) | BoundCircuit::Foreign(_) => {
panic!("native template must bind to the native variant")
}
}
}
#[test]
fn native_bind_is_threadsafe_without_gil() {
let source = std::sync::Arc::new(CircuitSource::Native(qaoa_template()));
let handles: Vec<_> = (0..8)
.map(|i| {
let src = std::sync::Arc::clone(&source);
std::thread::spawn(move || {
for j in 0..100 {
let theta = [0.01 * i as f64, 0.02 * j as f64];
let bound = src.bind(&theta).expect("native binding must succeed");
let BoundCircuit::Native(circuit) = bound else {
panic!("expected native circuit");
};
assert!(circuit.try_to_qasm2().unwrap().starts_with("OPENQASM 2.0;"));
}
})
})
.collect();
for h in handles {
h.join().expect("binding thread panicked");
}
}
#[test]
fn native_num_params_known_without_python() {
let source = CircuitSource::Native(qaoa_template());
assert_eq!(source.num_params(), Some(2));
}
#[test]
fn native_bind_errors_on_wrong_param_count() {
let source = CircuitSource::Native(qaoa_template());
let result = source.bind(&[0.1]); assert!(
matches!(result, Err(EvaluationError::Binding(_))),
"expected a typed native binding error"
);
}
#[test]
fn bound_qasm_duplicate_requires_no_python() {
let original = BoundCircuit::Qasm2("OPENQASM 2.0;\n".to_string());
let copy = original.duplicate();
match (original, copy) {
(BoundCircuit::Qasm2(a), BoundCircuit::Qasm2(b)) => assert_eq!(a, b),
_ => panic!("duplicate changed the variant"),
}
}
#[test]
fn evaluation_types_are_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<ParameterizedCircuit>();
assert_send_sync::<CircuitSource>();
assert_send_sync::<BoundCircuit>();
assert_send_sync::<polypus::evaluation::VqcOracle>();
assert_send_sync::<polypus::evaluation::QmlOracle>();
}