use std::ops::{Deref, DerefMut};
use crate::{
GenerationShape, TensorExpression,
expressions::JittableExpression,
index::{IndexDirection, TensorIndex},
};
use super::NamedExpression;
use qudit_core::QuditSystem;
use qudit_core::Radices;
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct BraSystemExpression {
inner: NamedExpression,
radices: Radices,
num_states: usize,
}
impl BraSystemExpression {
pub fn new<T: AsRef<str>>(input: T) -> Self {
TensorExpression::new(input).try_into().unwrap()
}
pub fn num_qudits(&self) -> usize {
self.radices.num_qudits()
}
}
impl JittableExpression for BraSystemExpression {
fn generation_shape(&self) -> GenerationShape {
GenerationShape::Tensor3D(self.num_states, 1, self.radices.dimension())
}
}
impl AsRef<NamedExpression> for BraSystemExpression {
fn as_ref(&self) -> &NamedExpression {
&self.inner
}
}
impl From<BraSystemExpression> for NamedExpression {
fn from(value: BraSystemExpression) -> Self {
value.inner
}
}
impl Deref for BraSystemExpression {
type Target = NamedExpression;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for BraSystemExpression {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl From<BraSystemExpression> for TensorExpression {
fn from(value: BraSystemExpression) -> Self {
let BraSystemExpression {
inner,
radices,
num_states,
} = value;
let indices = [num_states]
.into_iter()
.map(|r| (IndexDirection::Batch, r))
.chain(
radices
.iter()
.map(|r| (IndexDirection::Input, usize::from(*r))),
)
.enumerate()
.map(|(i, (d, r))| TensorIndex::new(d, i, r))
.collect();
TensorExpression::from_raw(indices, inner)
}
}
impl TryFrom<TensorExpression> for BraSystemExpression {
type Error = String;
fn try_from(value: TensorExpression) -> Result<Self, Self::Error> {
let mut num_states = None;
let mut radices = vec![];
for idx in value.indices() {
match idx.direction() {
IndexDirection::Batch => match num_states {
Some(n) => num_states = Some(n * idx.index_size()),
None => num_states = Some(idx.index_size()),
},
IndexDirection::Input => {
radices.push(idx.index_size());
}
_ => {
if idx.index_size() > 1 {
return Err(String::from(
"Cannot convert a tensor with non-input or batch indices to a bra system.",
));
}
}
}
}
Ok(BraSystemExpression {
inner: value.into(),
radices: radices.into(),
num_states: num_states.unwrap_or(1),
})
}
}
#[cfg(feature = "python")]
mod python {
use super::*;
use crate::python::PyExpressionRegistrar;
use pyo3::prelude::*;
use pyo3_stub_gen::derive::*;
use qudit_core::Radix;
#[gen_stub_pyclass]
#[pyclass(name = "BraSystemExpression", module = "openqudit.expressions")]
pub struct PyBraSystemExpression {
expr: BraSystemExpression,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyBraSystemExpression {
#[new]
fn new(expr: String) -> Self {
Self {
expr: BraSystemExpression::new(expr),
}
}
fn num_params(&self) -> usize {
self.expr.num_params()
}
fn name(&self) -> String {
self.expr.name().to_string()
}
fn radices(&self) -> Vec<Radix> {
self.expr.radices.to_vec()
}
fn num_qudits(&self) -> usize {
self.expr.num_qudits()
}
fn num_states(&self) -> usize {
self.expr.num_states
}
fn dimension(&self) -> usize {
self.expr.radices.dimension()
}
fn __repr__(&self) -> String {
format!(
"BraSystemExpression(name='{}', radices={:?}, num_states={}, params={})",
self.expr.name(),
self.expr.radices.to_vec(),
self.expr.num_states,
self.expr.num_params()
)
}
}
impl From<BraSystemExpression> for PyBraSystemExpression {
fn from(value: BraSystemExpression) -> Self {
PyBraSystemExpression { expr: value }
}
}
impl From<PyBraSystemExpression> for BraSystemExpression {
fn from(value: PyBraSystemExpression) -> Self {
value.expr
}
}
impl<'py> IntoPyObject<'py> for BraSystemExpression {
type Target = <PyBraSystemExpression as IntoPyObject<'py>>::Target;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let py_expr = PyBraSystemExpression::from(self);
Bound::new(py, py_expr)
}
}
impl<'a, 'py> FromPyObject<'a, 'py> for BraSystemExpression {
type Error = PyErr;
fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
let py_expr: PyRef<PyBraSystemExpression> = ob.extract()?;
Ok(py_expr.expr.clone())
}
}
fn register(parent_module: &Bound<'_, PyModule>) -> PyResult<()> {
parent_module.add_class::<PyBraSystemExpression>()?;
Ok(())
}
inventory::submit!(PyExpressionRegistrar { func: register });
}