use numpy::{IntoPyArray, PyArray1};
use polypus_circuit::draw::TextOptions;
use polypus_circuit::{
CircuitError, ConcreteCircuit, GateInstruction, GateParam, ParameterizedCircuit,
};
use polypus_sim::{SimError, Simulator, Statevector, StatevectorSimulator};
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use super::expr::{self, Operand, ParamExpr};
use crate::infrastructure::{attach_or, check_statevector_fits, InterpreterUnavailable};
fn to_py_err(e: CircuitError) -> PyErr {
PyValueError::new_err(e.to_string())
}
#[pyclass(module = "polypus", frozen, skip_from_py_object)]
#[derive(Clone, Copy)]
pub struct Param {
#[pyo3(get)]
pub index: usize,
}
#[pymethods]
impl Param {
#[new]
fn new(index: usize) -> Self {
Param { index }
}
fn __repr__(&self) -> String {
format!("Param({})", self.index)
}
fn __eq__(&self, other: &Self) -> bool {
self.index == other.index
}
fn __add__(&self, rhs: Operand) -> ParamExpr {
(self.expr() + rhs.0).into()
}
fn __radd__(&self, lhs: Operand) -> ParamExpr {
(lhs.0 + self.expr()).into()
}
fn __sub__(&self, rhs: Operand) -> ParamExpr {
(self.expr() - rhs.0).into()
}
fn __rsub__(&self, lhs: Operand) -> ParamExpr {
(lhs.0 - self.expr()).into()
}
fn __mul__(&self, rhs: Operand) -> ParamExpr {
(self.expr() * rhs.0).into()
}
fn __rmul__(&self, lhs: Operand) -> ParamExpr {
(lhs.0 * self.expr()).into()
}
fn __truediv__(&self, rhs: Operand) -> ParamExpr {
(self.expr() / rhs.0).into()
}
fn __rtruediv__(&self, lhs: Operand) -> ParamExpr {
(lhs.0 / self.expr()).into()
}
fn __pow__(&self, exponent: Operand, modulo: Option<&Bound<'_, PyAny>>) -> PyResult<ParamExpr> {
expr::pow(self.expr(), exponent.0, modulo)
}
fn __rpow__(&self, base: Operand, modulo: Option<&Bound<'_, PyAny>>) -> PyResult<ParamExpr> {
expr::pow(base.0, self.expr(), modulo)
}
fn __neg__(&self) -> ParamExpr {
(-self.expr()).into()
}
}
impl Param {
fn expr(&self) -> polypus_circuit::ParamExpr {
polypus_circuit::ParamExpr::param(self.index)
}
}
pub(crate) enum AngleArg {
Fixed(f64),
Param(usize),
Expr(polypus_circuit::ParamExpr),
}
impl<'a, 'py> FromPyObject<'a, 'py> for AngleArg {
type Error = PyErr;
fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
if let Ok(p) = ob.extract::<PyRef<'_, Param>>() {
return Ok(AngleArg::Param(p.index));
}
if let Ok(e) = ob.extract::<PyRef<'_, ParamExpr>>() {
return Ok(AngleArg::Expr(e.inner.clone()));
}
if let Ok(v) = ob.extract::<f64>() {
return Ok(AngleArg::Fixed(v));
}
Err(PyTypeError::new_err(
"angle must be a number, polypus.Param or polypus.ParamExpr",
))
}
}
#[pyclass(module = "polypus")]
pub struct Circuit {
pub(crate) inner: ParameterizedCircuit,
}
impl Circuit {
pub(crate) fn native(&self) -> &ParameterizedCircuit {
&self.inner
}
fn angle(&mut self, arg: AngleArg) -> PyResult<GateParam> {
Ok(match arg {
AngleArg::Fixed(v) => GateParam::Fixed(v),
AngleArg::Param(i) => GateParam::Param(i),
AngleArg::Expr(e) => self.inner.add_expr(e).map_err(to_py_err)?,
})
}
}
fn push(mut slf: PyRefMut<'_, Circuit>, gate: GateInstruction) -> PyResult<PyRefMut<'_, Circuit>> {
slf.inner.try_push(gate).map_err(to_py_err)?;
Ok(slf)
}
#[pyfunction(signature = (qc, params = None, fusion = true))]
pub fn statevector<'py>(
qc: PyRef<'py, Circuit>,
params: Option<Vec<f64>>,
fusion: bool,
) -> PyResult<Bound<'py, PyArray1<polypus_sim::C64>>> {
let params = params.unwrap_or_default();
super::calibration::prepare_native_threshold(qc.py())?;
let concrete = qc.native().assign_parameters(¶ms).map_err(to_py_err)?;
if concrete.num_qubits() <= polypus_sim::MAX_QUBITS {
check_statevector_fits(concrete.num_qubits())
.map_err(|e| crate::exceptions::insufficient_memory_to_pyerr(&e))?;
}
let mut pending: Option<PyErr> = None;
let outcome = qc
.py()
.detach(|| simulate_cancellable(&concrete, fusion, &mut pending));
let sv = match outcome {
Ok(sv) => sv,
Err(SimError::Cancelled) => return Err(cancellation_error(pending)),
Err(e) => return Err(PyValueError::new_err(e.to_string())),
};
qc.py().check_signals()?;
Ok(sv.into_amplitudes().into_pyarray(qc.py()))
}
pub(super) fn simulate_cancellable(
circuit: &ConcreteCircuit,
fusion: bool,
pending: &mut Option<PyErr>,
) -> Result<Statevector, SimError> {
let mut cancelled = || poll_for_cancellation(pending);
StatevectorSimulator {
fusion,
..StatevectorSimulator::new()
}
.run_cancellable(circuit, Some(&mut cancelled))
}
pub(super) fn cancellation_error(pending: Option<PyErr>) -> PyErr {
pending.unwrap_or_else(|| {
crate::exceptions::interpreter_unavailable_to_pyerr(InterpreterUnavailable)
})
}
pub(super) fn poll_for_cancellation(pending: &mut Option<PyErr>) -> bool {
attach_or(
|| true,
|py| match py.check_signals() {
Ok(()) => false,
Err(err) => {
*pending = Some(err);
true
}
},
)
}
#[pymethods]
impl Circuit {
#[new]
fn new(num_qubits: usize) -> Self {
Circuit {
inner: ParameterizedCircuit::new(num_qubits),
}
}
#[staticmethod]
fn from_qasm2(source: &str) -> PyResult<Self> {
Ok(Circuit {
inner: ParameterizedCircuit::from_qasm2(source).map_err(to_py_err)?,
})
}
#[staticmethod]
fn from_qasm3(py: Python<'_>, source: &str) -> PyResult<Self> {
let inner = py
.detach(|| ParameterizedCircuit::from_qasm3(source))
.map_err(to_py_err)?;
Ok(Circuit { inner })
}
#[getter]
fn param_names(&self) -> Vec<String> {
self.inner.param_names()
}
#[getter]
fn num_qubits(&self) -> usize {
self.inner.num_qubits()
}
#[getter]
fn num_params(&self) -> usize {
self.inner.num_params()
}
#[getter]
fn num_clbits(&self) -> usize {
self.inner.num_clbits()
}
#[getter]
fn clbits_width(&self) -> usize {
self.inner.clbits_width()
}
fn h(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::H(qubit))
}
fn x(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::X(qubit))
}
fn y(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Y(qubit))
}
fn z(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Z(qubit))
}
fn s(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::S(qubit))
}
fn t(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::T(qubit))
}
fn sdg(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Sdg(qubit))
}
fn tdg(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Tdg(qubit))
}
fn id(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Id(qubit))
}
fn rx(
mut slf: PyRefMut<'_, Self>,
qubit: usize,
theta: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
push(slf, GateInstruction::Rx { qubit, theta })
}
fn ry(
mut slf: PyRefMut<'_, Self>,
qubit: usize,
theta: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
push(slf, GateInstruction::Ry { qubit, theta })
}
fn rz(
mut slf: PyRefMut<'_, Self>,
qubit: usize,
theta: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
push(slf, GateInstruction::Rz { qubit, theta })
}
fn u(
mut slf: PyRefMut<'_, Self>,
qubit: usize,
theta: AngleArg,
phi: AngleArg,
lam: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
let phi = slf.angle(phi)?;
let lam = slf.angle(lam)?;
push(
slf,
GateInstruction::U {
qubit,
theta,
phi,
lam,
},
)
}
fn cx(slf: PyRefMut<'_, Self>, control: usize, target: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Cx(control, target))
}
fn cz(slf: PyRefMut<'_, Self>, control: usize, target: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Cz(control, target))
}
fn swap(slf: PyRefMut<'_, Self>, q0: usize, q1: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Swap(q0, q1))
}
fn rzz(
mut slf: PyRefMut<'_, Self>,
q0: usize,
q1: usize,
theta: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
push(slf, GateInstruction::Rzz { q0, q1, theta })
}
fn rxx(
mut slf: PyRefMut<'_, Self>,
q0: usize,
q1: usize,
theta: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
push(slf, GateInstruction::Rxx { q0, q1, theta })
}
fn cp(
mut slf: PyRefMut<'_, Self>,
q0: usize,
q1: usize,
theta: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
push(slf, GateInstruction::Cp { q0, q1, theta })
}
fn sx(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Sx(qubit))
}
fn sxdg(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Sxdg(qubit))
}
fn cy(slf: PyRefMut<'_, Self>, control: usize, target: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Cy(control, target))
}
fn ch(slf: PyRefMut<'_, Self>, control: usize, target: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Ch(control, target))
}
fn csx(slf: PyRefMut<'_, Self>, control: usize, target: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Csx(control, target))
}
fn ccx(
slf: PyRefMut<'_, Self>,
control0: usize,
control1: usize,
target: usize,
) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Ccx(control0, control1, target))
}
fn cswap(
slf: PyRefMut<'_, Self>,
control: usize,
target0: usize,
target1: usize,
) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Cswap(control, target0, target1))
}
fn crx(
mut slf: PyRefMut<'_, Self>,
control: usize,
target: usize,
theta: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
push(
slf,
GateInstruction::Crx {
control,
target,
theta,
},
)
}
fn cry(
mut slf: PyRefMut<'_, Self>,
control: usize,
target: usize,
theta: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
push(
slf,
GateInstruction::Cry {
control,
target,
theta,
},
)
}
fn crz(
mut slf: PyRefMut<'_, Self>,
control: usize,
target: usize,
theta: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
push(
slf,
GateInstruction::Crz {
control,
target,
theta,
},
)
}
fn cu1(
mut slf: PyRefMut<'_, Self>,
q0: usize,
q1: usize,
theta: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
push(slf, GateInstruction::Cu1 { q0, q1, theta })
}
fn cu3(
mut slf: PyRefMut<'_, Self>,
control: usize,
target: usize,
theta: AngleArg,
phi: AngleArg,
lam: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
let phi = slf.angle(phi)?;
let lam = slf.angle(lam)?;
push(
slf,
GateInstruction::Cu3 {
control,
target,
theta,
phi,
lam,
},
)
}
fn cu(
mut slf: PyRefMut<'_, Self>,
control: usize,
target: usize,
theta: AngleArg,
phi: AngleArg,
lam: AngleArg,
gamma: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let theta = slf.angle(theta)?;
let phi = slf.angle(phi)?;
let lam = slf.angle(lam)?;
let gamma = slf.angle(gamma)?;
push(
slf,
GateInstruction::Cu {
control,
target,
theta,
phi,
lam,
gamma,
},
)
}
fn p(mut slf: PyRefMut<'_, Self>, qubit: usize, lam: AngleArg) -> PyResult<PyRefMut<'_, Self>> {
let lam = slf.angle(lam)?;
push(slf, GateInstruction::P { qubit, lam })
}
fn u1(
mut slf: PyRefMut<'_, Self>,
qubit: usize,
lam: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let lam = slf.angle(lam)?;
push(slf, GateInstruction::U1 { qubit, lam })
}
fn u2(
mut slf: PyRefMut<'_, Self>,
qubit: usize,
phi: AngleArg,
lam: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let phi = slf.angle(phi)?;
let lam = slf.angle(lam)?;
push(slf, GateInstruction::U2 { qubit, phi, lam })
}
fn u0(
mut slf: PyRefMut<'_, Self>,
qubit: usize,
gamma: AngleArg,
) -> PyResult<PyRefMut<'_, Self>> {
let gamma = slf.angle(gamma)?;
push(slf, GateInstruction::U0 { qubit, gamma })
}
fn rccx(
slf: PyRefMut<'_, Self>,
control0: usize,
control1: usize,
target: usize,
) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Rccx(control0, control1, target))
}
fn rc3x(
slf: PyRefMut<'_, Self>,
c0: usize,
c1: usize,
c2: usize,
target: usize,
) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Rc3x(c0, c1, c2, target))
}
fn c3x(
slf: PyRefMut<'_, Self>,
c0: usize,
c1: usize,
c2: usize,
target: usize,
) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::C3x(c0, c1, c2, target))
}
fn c3sqrtx(
slf: PyRefMut<'_, Self>,
c0: usize,
c1: usize,
c2: usize,
target: usize,
) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::C3sqrtx(c0, c1, c2, target))
}
fn c4x(
slf: PyRefMut<'_, Self>,
c0: usize,
c1: usize,
c2: usize,
c3: usize,
target: usize,
) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::C4x(c0, c1, c2, c3, target))
}
#[pyo3(signature = (qubits=None))]
fn barrier(
slf: PyRefMut<'_, Self>,
qubits: Option<Vec<usize>>,
) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Barrier(qubits.unwrap_or_default()))
}
fn measure(slf: PyRefMut<'_, Self>, qubit: usize, cbit: usize) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::Measure { qubit, cbit })
}
fn measure_all(slf: PyRefMut<'_, Self>) -> PyResult<PyRefMut<'_, Self>> {
push(slf, GateInstruction::MeasureAll)
}
#[pyo3(signature = (other, qubits = None))]
fn compose<'py>(
slf: &Bound<'py, Self>,
other: &Bound<'py, Circuit>,
qubits: Option<Vec<usize>>,
) -> PyResult<Bound<'py, Self>> {
let copy;
let borrowed;
let other = if other.is(slf) {
copy = other.try_borrow()?.inner.clone();
©
} else {
borrowed = other.try_borrow()?;
&borrowed.inner
};
let qubits = qubits.unwrap_or_else(|| (0..other.num_qubits()).collect());
let mut this = slf.try_borrow_mut()?;
let target = &mut this.inner;
slf.py()
.detach(|| target.try_compose(other, &qubits))
.map_err(to_py_err)?;
drop(this);
Ok(slf.clone())
}
#[pyo3(signature = (params=None))]
fn to_qasm2(&self, params: Option<Vec<f64>>) -> PyResult<String> {
self.inner
.to_qasm2_with_params(¶ms.unwrap_or_default())
.map_err(to_py_err)
}
#[pyo3(signature = (params=None))]
fn to_qasm3(&self, py: Python<'_>, params: Option<Vec<f64>>) -> PyResult<String> {
let circuit = &self.inner;
py.detach(|| match ¶ms {
None => circuit.to_qasm3(),
Some(values) => circuit.to_qasm3_with_params(values),
})
.map_err(to_py_err)
}
#[pyo3(signature = (params=None))]
fn to_qir(&self, params: Option<Vec<f64>>) -> PyResult<String> {
self.inner
.to_qir_with_params(¶ms.unwrap_or_default())
.map_err(to_py_err)
}
#[pyo3(signature = (params=None))]
fn to_qir_bitcode<'py>(
&self,
py: Python<'py>,
params: Option<Vec<f64>>,
) -> PyResult<Bound<'py, PyBytes>> {
let bitcode = self
.inner
.to_qir_bitcode_with_params(¶ms.unwrap_or_default())
.map_err(to_py_err)?;
Ok(PyBytes::new(py, &bitcode))
}
#[pyo3(
signature = (output="text", *, ascii=false, fold=Some(80)),
text_signature = "($self, output='text', *, ascii=False, fold=80)"
)]
fn draw(&self, output: &str, ascii: bool, fold: Option<usize>) -> PyResult<String> {
match output {
"text" => Ok(self.inner.draw_text(TextOptions { ascii, fold })),
"svg" => Ok(self.inner.draw_svg()),
other => Err(PyValueError::new_err(format!(
"output must be \"text\" or \"svg\", got {other:?}"
))),
}
}
fn __str__(&self) -> String {
self.inner.draw_text(TextOptions::default())
}
fn _repr_svg_(&self) -> String {
self.inner.draw_svg()
}
fn __len__(&self) -> usize {
self.inner.gates().len()
}
fn __repr__(&self) -> String {
format!(
"Circuit(num_qubits={}, num_params={}, gates={})",
self.inner.num_qubits(),
self.inner.num_params(),
self.inner.gates().len()
)
}
}
#[pyfunction]
#[pyo3(signature = (num_qubits, inverse = false, swaps = true))]
pub fn qft(py: Python<'_>, num_qubits: usize, inverse: bool, swaps: bool) -> PyResult<Circuit> {
let inner = py
.detach(|| polypus_circuit::templates::qft_with_options(num_qubits, inverse, swaps))
.map_err(to_py_err)?;
Ok(Circuit { inner })
}
#[pyfunction]
#[pyo3(signature = (a, modulus, counting_qubits = None))]
pub fn shor_order_finding(
py: Python<'_>,
a: u64,
modulus: u64,
counting_qubits: Option<usize>,
) -> PyResult<Circuit> {
let inner = py
.detach(|| polypus_circuit::templates::shor_order_finding(a, modulus, counting_qubits))
.map_err(to_py_err)?;
Ok(Circuit { inner })
}