use std::collections::HashSet;
use polypus_circuit::ParameterizedCircuit;
use pyo3::exceptions::{PyException, PyTypeError, PyValueError};
use pyo3::intern;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
use crate::exceptions::{
backend_error_to_pyerr, describe_python_error, qiskit_error_to_pyerr, BackendError,
};
use crate::infrastructure::{to_py_object, BoundCircuit, NativeStatevectorBackend};
const CONTROL_FLOW: [&str; 4] = ["if_else", "while_loop", "for_loop", "switch_case"];
#[pyfunction]
#[pyo3(signature = (circuit, *, resources = false))]
pub(crate) fn backend_compatibility<'py>(
circuit: &Bound<'py, PyAny>,
resources: bool,
) -> PyResult<Bound<'py, PyDict>> {
let py = circuit.py();
let report = reasons(circuit, resources).map_err(qiskit_error_to_pyerr)?;
let dict = PyDict::new(py);
dict.set_item("aer", PyList::new(py, report.aer)?)?;
dict.set_item("polypus", PyList::new(py, report.native)?)?;
dict.set_item("cunqa", PyList::new(py, report.cunqa)?)?;
dict.set_item("qmio", PyList::new(py, report.qmio)?)?;
Ok(dict)
}
struct Report {
aer: Vec<String>,
native: Vec<String>,
cunqa: Vec<String>,
qmio: Vec<String>,
}
fn reasons(circuit: &Bound<'_, PyAny>, resources: bool) -> PyResult<Report> {
let py = circuit.py();
let bound = match super::extract_bound_circuit(circuit) {
Ok(bound) => bound,
Err(err) if err.is_instance_of::<PyValueError>(py) => {
let reason = message(py, &err);
let foreign = quantum_circuit(circuit).ok();
let mut native = vec![reason.clone()];
let mut qmio = vec![reason.clone()];
qmio.extend(qmio_not_compiled());
if let Some(qc) = foreign {
native.push(super::NATIVE_REJECTS_QISKIT.to_string());
native.extend(dynamic_features(qc)?);
qmio.push(super::QMIO_REJECTS_QISKIT.to_string());
}
let mut cunqa = vec![reason.clone()];
cunqa.extend(cunqa_missing(py));
return Ok(Report {
aer: vec![reason],
native,
cunqa,
qmio,
});
}
Err(err) => return Err(err),
};
if bound.is_foreign() {
let qc = quantum_circuit(circuit)?;
let mut native = vec![super::NATIVE_REJECTS_QISKIT.to_string()];
native.extend(dynamic_features(qc)?);
let mut qmio = qmio_not_compiled();
qmio.push(super::QMIO_REJECTS_QISKIT.to_string());
return Ok(Report {
aer: aer_quantum_circuit_rejections(qc)?,
native,
cunqa: cunqa_rejections(qc)?,
qmio,
});
}
let mut native = match NativeStatevectorBackend::check_circuit(&bound) {
Ok(()) => Vec::new(),
Err(err) => vec![message(py, &backend_error_to_pyerr(err))],
};
if resources && native.is_empty() {
if let Err(err) = NativeStatevectorBackend::check_resources(&bound) {
native.push(message(py, &backend_error_to_pyerr(err)));
}
}
let qasm = to_py_object(&bound, py).map_err(backend_error_to_pyerr)?;
let mut qmio = qmio_not_compiled();
qmio.extend(qmio_program_rejection(&bound));
Ok(Report {
aer: aer_qasm_rejections(py, &bound)?,
native,
cunqa: cunqa_rejections(qasm.bind(py))?,
qmio,
})
}
fn message(py: Python<'_>, err: &PyErr) -> String {
err.value(py)
.str()
.map_or_else(|_| err.to_string(), |m| m.to_string())
}
fn quantum_circuit<'a, 'py>(circuit: &'a Bound<'py, PyAny>) -> PyResult<&'a Bound<'py, PyAny>> {
let py = circuit.py();
let is_circuit = PyModule::import(py, "qiskit")
.and_then(|qiskit| qiskit.getattr("QuantumCircuit"))
.and_then(|class| circuit.is_instance(&class))
.unwrap_or(false);
if is_circuit {
Ok(circuit)
} else {
Err(PyTypeError::new_err(format!(
"backend_compatibility expects a polypus.Circuit, an OpenQASM 2.0 str or a \
qiskit QuantumCircuit, got {}",
circuit.get_type().name()?
)))
}
}
fn aer_qasm_rejections(py: Python<'_>, bound: &BoundCircuit) -> PyResult<Vec<String>> {
let Some(from_qasm_str) = aer_parser(py) else {
return Ok(vec![aer_missing(py)]);
};
let qasm = to_py_object(bound, py).map_err(backend_error_to_pyerr)?;
match from_qasm_str.call1((qasm,)) {
Ok(_) => Ok(Vec::new()),
Err(err) => Ok(vec![describe_python_error(py, &err)]),
}
}
fn aer_parser(py: Python<'_>) -> Option<Bound<'_, PyAny>> {
PyModule::import(py, "qiskit_aer").ok()?;
PyModule::import(py, "qiskit")
.and_then(|qiskit| qiskit.getattr("QuantumCircuit"))
.and_then(|class| class.getattr("from_qasm_str"))
.ok()
}
fn aer_missing(py: Python<'_>) -> String {
match PyModule::import(py, "qiskit_aer").and(PyModule::import(py, "qiskit")) {
Ok(_) => "Qiskit Aer is not available".to_string(),
Err(err) => format!(
"Qiskit Aer is not installed ({}), so backend=\"aer\" cannot run",
describe_python_error(py, &err)
),
}
}
fn aer_quantum_circuit_rejections(qc: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
let py = qc.py();
let Some(aer_simulator) = aer_simulator_class(py) else {
return Ok(vec![aer_missing(py)]);
};
let basis = aer_simulator
.call0()?
.getattr(intern!(py, "target"))?
.getattr(intern!(py, "operation_names"))?;
let supported = names(&basis)?;
let control_flow = names(
&PyModule::import(py, "qiskit.circuit")?.getattr(intern!(py, "CONTROL_FLOW_OP_NAMES"))?,
)?;
if !outside_basis(qc, &supported, &control_flow)? {
return Ok(Vec::new());
}
let rewrite = PyModule::import(py, "polypus_python.local")?
.getattr(intern!(py, "_rewrite_into_aer_basis"))?;
match rewrite.call1((qc, basis)) {
Ok(_) => Ok(Vec::new()),
Err(err) => {
let raised = qiskit_error_to_pyerr(err);
if raised.is_instance_of::<BackendError>(py) {
Ok(vec![message(py, &raised)])
} else {
Err(raised)
}
}
}
}
fn cunqa_rejections(circuit: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
let py = circuit.py();
let seal = match cunqa_seal(py) {
Ok(seal) => seal,
Err(reason) => return Ok(vec![reason]),
};
match seal.call_method1(intern!(py, "_convert"), (circuit,)) {
Ok(_) => Ok(Vec::new()),
Err(err) if err.is_instance_of::<PyException>(py) => {
Ok(vec![message(py, &qiskit_error_to_pyerr(err))])
}
Err(err) => Err(err),
}
}
fn cunqa_missing(py: Python<'_>) -> Vec<String> {
cunqa_seal(py).err().into_iter().collect()
}
fn cunqa_seal(py: Python<'_>) -> Result<Bound<'_, PyModule>, String> {
PyModule::import(py, "polypus_python.cunqa").map_err(|err| {
format!(
"CUNQA is not available ({}), so infrastructure=\"cunqa\" cannot run",
describe_python_error(py, &err)
)
})
}
fn qmio_not_compiled() -> Vec<String> {
#[cfg(not(feature = "qmio"))]
{
vec![super::QMIO_NOT_COMPILED.to_string()]
}
#[cfg(feature = "qmio")]
{
Vec::new()
}
}
fn qmio_program_rejection(circuit: &BoundCircuit) -> Option<String> {
let built = match circuit {
BoundCircuit::Native(cc) => cc.try_to_qasm2().map(drop),
BoundCircuit::Qasm2(qasm) => ParameterizedCircuit::from_qasm2(qasm)
.and_then(|pc| pc.assign_parameters(&[]))
.map(drop),
BoundCircuit::Foreign(_) => return None,
};
built
.err()
.map(|e| format!("could not build a circuit for QMIO: {e}"))
}
fn aer_simulator_class(py: Python<'_>) -> Option<Bound<'_, PyAny>> {
PyModule::import(py, "qiskit").ok()?;
PyModule::import(py, "qiskit_aer")
.and_then(|aer| aer.getattr("AerSimulator"))
.ok()
}
fn names(iterable: &Bound<'_, PyAny>) -> PyResult<HashSet<String>> {
iterable
.try_iter()?
.map(|name| name?.extract::<String>())
.collect()
}
fn outside_basis(
qc: &Bound<'_, PyAny>,
supported: &HashSet<String>,
control_flow: &HashSet<String>,
) -> PyResult<bool> {
let py = qc.py();
let used = names(&qc.call_method0(intern!(py, "count_ops"))?)?;
if used
.iter()
.any(|name| name != "barrier" && !supported.contains(name))
{
return Ok(true);
}
if used.is_disjoint(control_flow) {
return Ok(false);
}
for instruction in qc.getattr(intern!(py, "data"))?.try_iter()? {
let operation = instruction?.getattr(intern!(py, "operation"))?;
let name: String = operation.getattr(intern!(py, "name"))?.extract()?;
if !control_flow.contains(&name) {
continue;
}
for block in operation.getattr(intern!(py, "blocks"))?.try_iter()? {
if outside_basis(&block?, supported, control_flow)? {
return Ok(true);
}
}
}
Ok(false)
}
fn dynamic_features(qc: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
let py = qc.py();
let mut measured = HashSet::new();
let mut reasons: Vec<String> = Vec::new();
let mut report = |reason: String| {
if !reasons.contains(&reason) {
reasons.push(reason);
}
};
for instruction in qc.getattr(intern!(py, "data"))?.try_iter()? {
let instruction = instruction?;
let operation = instruction.getattr(intern!(py, "operation"))?;
let name: String = operation.getattr(intern!(py, "name"))?.extract()?;
if CONTROL_FLOW.contains(&name.as_str()) {
report(format!(
"instruction '{name}' is classical control flow, which makes a dynamic \
circuit; Polypus circuits use terminal measurement (contract C-4, \
docs/adr/0001-terminal-measurements.md)"
));
continue;
}
if operation
.getattr(intern!(py, "condition"))
.is_ok_and(|condition| !condition.is_none())
{
report(format!(
"instruction '{name}' is classically conditioned, which makes a dynamic \
circuit; Polypus circuits use terminal measurement (contract C-4, \
docs/adr/0001-terminal-measurements.md)"
));
}
for qubit in instruction.getattr(intern!(py, "qubits"))?.try_iter()? {
let index: usize = qc
.call_method1(intern!(py, "find_bit"), (qubit?,))?
.getattr(intern!(py, "index"))?
.extract()?;
match name.as_str() {
"measure" => {
measured.insert(index);
}
"barrier" => {}
"reset" => report(format!(
"'reset' on qubit {index} is not supported: Polypus circuits use terminal \
measurement and no other non-unitary operation (contract C-4, \
docs/adr/0001-terminal-measurements.md)"
)),
_ if measured.contains(&index) => report(format!(
"'{name}' acts on qubit {index} after it was measured; Polypus circuits \
use terminal measurement (contract C-4)"
)),
_ => {}
}
}
}
Ok(reasons)
}