use super::{BosonOperator, OperateOnBosons};
use crate::bosons::BosonProduct;
use crate::{ModeIndex, OperateOnDensityMatrix, OperateOnModes, OperateOnState, StruqtureError};
use qoqo_calculator::CalculatorComplex;
use serde::{Deserialize, Serialize};
use std::fmt::{self, Write};
use std::iter::{FromIterator, IntoIterator};
use std::ops;
#[cfg(feature = "indexed_map_iterators")]
use indexmap::map::{Iter, Keys, Values};
#[cfg(not(feature = "indexed_map_iterators"))]
use std::collections::hash_map::{Iter, Keys, Values};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "json_schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "json_schema", schemars(deny_unknown_fields))]
pub struct BosonSystem {
pub(crate) number_modes: Option<usize>,
pub(crate) operator: BosonOperator,
}
impl crate::MinSupportedVersion for BosonSystem {}
impl<'a> OperateOnDensityMatrix<'a> for BosonSystem {
type Index = BosonProduct;
type Value = CalculatorComplex;
type IteratorType = Iter<'a, Self::Index, Self::Value>;
type KeyIteratorType = Keys<'a, Self::Index, Self::Value>;
type ValueIteratorType = Values<'a, Self::Index, Self::Value>;
fn get(&self, key: &Self::Index) -> &Self::Value {
self.operator.get(key)
}
fn iter(&'a self) -> Self::IteratorType {
self.operator.iter()
}
fn keys(&'a self) -> Self::KeyIteratorType {
self.operator.keys()
}
fn values(&'a self) -> Self::ValueIteratorType {
self.operator.values()
}
fn remove(&mut self, key: &Self::Index) -> Option<Self::Value> {
self.operator.remove(key)
}
fn empty_clone(&self, capacity: Option<usize>) -> Self {
match capacity {
Some(cap) => Self {
number_modes: self.number_modes,
operator: BosonOperator::with_capacity(cap),
},
None => Self {
number_modes: self.number_modes,
operator: BosonOperator::new(),
},
}
}
fn set(
&mut self,
key: Self::Index,
value: Self::Value,
) -> Result<Option<Self::Value>, StruqtureError> {
match self.number_modes {
Some(x) => {
if key.current_number_modes() <= x {
self.operator.set(key, value)
} else {
Err(StruqtureError::NumberModesExceeded)
}
}
None => self.operator.set(key, value),
}
}
fn add_operator_product(
&mut self,
key: Self::Index,
value: Self::Value,
) -> Result<(), StruqtureError> {
match self.number_modes {
Some(x) => {
if key.current_number_modes() <= x {
self.operator.add_operator_product(key, value)
} else {
Err(StruqtureError::NumberModesExceeded)
}
}
None => self.operator.add_operator_product(key, value),
}
}
}
impl OperateOnState<'_> for BosonSystem {}
impl<'a> OperateOnModes<'a> for BosonSystem {
fn number_modes(&'a self) -> usize {
match self.number_modes {
Some(modes) => modes,
None => self.operator.current_number_modes(),
}
}
fn current_number_modes(&'a self) -> usize {
self.operator.current_number_modes()
}
}
impl OperateOnBosons<'_> for BosonSystem {}
impl BosonSystem {
pub fn new(number_modes: Option<usize>) -> Self {
BosonSystem {
number_modes,
operator: BosonOperator::new(),
}
}
pub fn with_capacity(number_modes: Option<usize>, capacity: usize) -> Self {
BosonSystem {
number_modes,
operator: BosonOperator::with_capacity(capacity),
}
}
pub fn operator(&self) -> &BosonOperator {
&self.operator
}
pub fn from_operator(
operator: BosonOperator,
number_modes: Option<usize>,
) -> Result<Self, StruqtureError> {
match number_modes {
Some(x) => {
if operator.current_number_modes() <= x {
Ok(BosonSystem {
number_modes: Some(x),
operator,
})
} else {
Err(StruqtureError::NumberModesExceeded)
}
}
None => Ok(BosonSystem {
number_modes: None,
operator,
}),
}
}
pub fn separate_into_n_terms(
&self,
number_creators_annihilators: (usize, usize),
) -> Result<(Self, Self), StruqtureError> {
let mut separated = Self::default();
let mut remainder = Self::default();
for (prod, val) in self.iter() {
if (prod.creators().len(), prod.annihilators().len()) == number_creators_annihilators {
separated.add_operator_product(prod.clone(), val.clone())?;
} else {
remainder.add_operator_product(prod.clone(), val.clone())?;
}
}
Ok((separated, remainder))
}
}
impl ops::Neg for BosonSystem {
type Output = BosonSystem;
fn neg(mut self) -> Self {
self.operator = self.operator.neg();
self
}
}
impl<T, V> ops::Add<T> for BosonSystem
where
T: IntoIterator<Item = (BosonProduct, V)>,
V: Into<CalculatorComplex>,
{
type Output = Result<Self, StruqtureError>;
fn add(mut self, other: T) -> Self::Output {
for (key, value) in other.into_iter() {
self.add_operator_product(key.clone(), Into::<CalculatorComplex>::into(value))?;
}
Ok(self)
}
}
impl<T, V> ops::Sub<T> for BosonSystem
where
T: IntoIterator<Item = (BosonProduct, V)>,
V: Into<CalculatorComplex>,
{
type Output = Result<Self, StruqtureError>;
fn sub(mut self, other: T) -> Self::Output {
for (key, value) in other.into_iter() {
self.add_operator_product(key.clone(), Into::<CalculatorComplex>::into(value) * -1.0)?;
}
Ok(self)
}
}
impl<T> ops::Mul<T> for BosonSystem
where
T: Into<CalculatorComplex>,
{
type Output = Self;
fn mul(mut self, other: T) -> Self {
self.operator = self.operator * other;
self
}
}
impl ops::Mul<BosonSystem> for BosonSystem {
type Output = Self;
fn mul(self, other: BosonSystem) -> Self {
BosonSystem {
number_modes: Some(self.number_modes().max(other.number_modes())),
operator: self.operator * other.operator,
}
}
}
impl IntoIterator for BosonSystem {
type Item = (BosonProduct, CalculatorComplex);
#[cfg(not(feature = "indexed_map_iterators"))]
type IntoIter = std::collections::hash_map::IntoIter<BosonProduct, CalculatorComplex>;
#[cfg(feature = "indexed_map_iterators")]
type IntoIter = indexmap::map::IntoIter<BosonProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.operator.into_iter()
}
}
impl<'a> IntoIterator for &'a BosonSystem {
type Item = (&'a BosonProduct, &'a CalculatorComplex);
type IntoIter = Iter<'a, BosonProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.operator.iter()
}
}
impl FromIterator<(BosonProduct, CalculatorComplex)> for BosonSystem {
fn from_iter<I: IntoIterator<Item = (BosonProduct, CalculatorComplex)>>(iter: I) -> Self {
let mut so = BosonSystem::new(None);
for (pp, cc) in iter {
so.add_operator_product(pp.clone(), cc.clone())
.expect("Internal error in add_operator_product");
}
so
}
}
impl Extend<(BosonProduct, CalculatorComplex)> for BosonSystem {
fn extend<I: IntoIterator<Item = (BosonProduct, CalculatorComplex)>>(&mut self, iter: I) {
for (bp, cc) in iter {
self.add_operator_product(bp, cc)
.expect("Internal error in add_operator_product");
}
}
}
impl fmt::Display for BosonSystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut output = format!("BosonSystem({}){{\n", self.number_modes());
for (key, val) in self.iter() {
writeln!(output, "{key}: {val},")?;
}
output.push('}');
write!(f, "{output}")
}
}