use super::{BosonOperator, BosonProduct, HermitianBosonProduct, ModeIndex, OperateOnBosons};
use crate::{
GetValue, OperateOnDensityMatrix, OperateOnModes, OperateOnState, StruqtureError,
StruqtureVersionSerializable, SymmetricIndex, MINIMUM_STRUQTURE_VERSION,
};
use qoqo_calculator::{CalculatorComplex, CalculatorFloat};
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::{Entry, Iter, Keys, Values};
#[cfg(feature = "indexed_map_iterators")]
use indexmap::IndexMap;
#[cfg(not(feature = "indexed_map_iterators"))]
use std::collections::hash_map::{Entry, Iter, Keys, Values};
#[cfg(not(feature = "indexed_map_iterators"))]
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(from = "BosonHamiltonianSerialize")]
#[serde(into = "BosonHamiltonianSerialize")]
pub struct BosonHamiltonian {
#[cfg(feature = "indexed_map_iterators")]
internal_map: IndexMap<HermitianBosonProduct, CalculatorComplex>,
#[cfg(not(feature = "indexed_map_iterators"))]
internal_map: HashMap<HermitianBosonProduct, CalculatorComplex>,
}
impl crate::MinSupportedVersion for BosonHamiltonian {}
#[cfg(feature = "json_schema")]
impl schemars::JsonSchema for BosonHamiltonian {
fn schema_name() -> std::borrow::Cow<'static, str> {
"BosonHamiltonian".into()
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
<BosonHamiltonianSerialize>::json_schema(generator)
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[cfg_attr(feature = "json_schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "json_schema", schemars(deny_unknown_fields))]
struct BosonHamiltonianSerialize {
items: Vec<(HermitianBosonProduct, CalculatorFloat, CalculatorFloat)>,
_struqture_version: StruqtureVersionSerializable,
}
impl From<BosonHamiltonianSerialize> for BosonHamiltonian {
fn from(value: BosonHamiltonianSerialize) -> Self {
let new_noise_op: BosonHamiltonian = value
.items
.into_iter()
.map(|(key, real, imag)| (key, CalculatorComplex { re: real, im: imag }))
.collect();
new_noise_op
}
}
impl From<BosonHamiltonian> for BosonHamiltonianSerialize {
fn from(value: BosonHamiltonian) -> Self {
let new_noise_op: Vec<(HermitianBosonProduct, CalculatorFloat, CalculatorFloat)> = value
.into_iter()
.map(|(key, val)| (key, val.re, val.im))
.collect();
let current_version = StruqtureVersionSerializable {
major_version: MINIMUM_STRUQTURE_VERSION.0,
minor_version: MINIMUM_STRUQTURE_VERSION.1,
};
Self {
items: new_noise_op,
_struqture_version: current_version,
}
}
}
impl<'a> OperateOnDensityMatrix<'a> for BosonHamiltonian {
type Index = HermitianBosonProduct;
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 {
match self.internal_map.get(key) {
Some(value) => value,
None => &CalculatorComplex::ZERO,
}
}
fn iter(&'a self) -> Self::IteratorType {
self.internal_map.iter()
}
fn keys(&'a self) -> Self::KeyIteratorType {
self.internal_map.keys()
}
fn values(&'a self) -> Self::ValueIteratorType {
self.internal_map.values()
}
#[cfg(feature = "indexed_map_iterators")]
fn remove(&mut self, key: &Self::Index) -> Option<Self::Value> {
self.internal_map.shift_remove(key)
}
#[cfg(not(feature = "indexed_map_iterators"))]
fn remove(&mut self, key: &Self::Index) -> Option<Self::Value> {
self.internal_map.remove(key)
}
fn empty_clone(&self, capacity: Option<usize>) -> Self {
match capacity {
Some(cap) => Self::with_capacity(cap),
None => Self::new(),
}
}
fn set(
&mut self,
key: Self::Index,
value: Self::Value,
) -> Result<Option<Self::Value>, StruqtureError> {
if value.re != CalculatorFloat::ZERO || value.im != CalculatorFloat::ZERO {
if key.is_natural_hermitian() && value.im != CalculatorFloat::ZERO {
Err(StruqtureError::NonHermitianOperator)
} else {
Ok(self.internal_map.insert(key, value))
}
} else {
match self.internal_map.entry(key) {
#[cfg(feature = "indexed_map_iterators")]
Entry::Occupied(val) => Ok(Some(val.shift_remove())),
#[cfg(not(feature = "indexed_map_iterators"))]
Entry::Occupied(val) => Ok(Some(val.remove())),
Entry::Vacant(_) => Ok(None),
}
}
}
fn add_operator_product(
&mut self,
key: Self::Index,
value: Self::Value,
) -> Result<(), StruqtureError> {
let old = self.get(&key).clone();
let new_val = value + old;
if key.is_natural_hermitian() && new_val.im != CalculatorFloat::ZERO {
Err(StruqtureError::NonHermitianOperator)
} else {
self.set(key, new_val)?;
Ok(())
}
}
}
impl OperateOnState<'_> for BosonHamiltonian {
fn hermitian_conjugate(&self) -> Self {
self.clone()
}
}
impl OperateOnModes<'_> for BosonHamiltonian {
fn current_number_modes(&self) -> usize {
let mut max_mode: usize = 0;
if !self.internal_map.is_empty() {
for key in self.internal_map.keys() {
if key.current_number_modes() > max_mode {
max_mode = key.current_number_modes()
}
}
}
max_mode
}
fn number_modes(&self) -> usize {
self.current_number_modes()
}
}
impl OperateOnBosons<'_> for BosonHamiltonian {}
impl Default for BosonHamiltonian {
fn default() -> Self {
Self::new()
}
}
impl BosonHamiltonian {
pub fn new() -> Self {
BosonHamiltonian {
#[cfg(not(feature = "indexed_map_iterators"))]
internal_map: HashMap::new(),
#[cfg(feature = "indexed_map_iterators")]
internal_map: IndexMap::new(),
}
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
#[cfg(not(feature = "indexed_map_iterators"))]
internal_map: HashMap::with_capacity(capacity),
#[cfg(feature = "indexed_map_iterators")]
internal_map: IndexMap::with_capacity(capacity),
}
}
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 TryFrom<BosonOperator> for BosonHamiltonian {
type Error = StruqtureError;
fn try_from(hamiltonian: BosonOperator) -> Result<Self, StruqtureError> {
let mut internal = BosonHamiltonian::new();
for (key, value) in hamiltonian.into_iter() {
if key.creators().min() > key.annihilators().min() {
return Err(StruqtureError::CreatorsAnnihilatorsMinimumIndex {
creators_min: key.creators().min().cloned(),
annihilators_min: key.annihilators().min().cloned(),
});
} else {
let bp = HermitianBosonProduct::get_key(&key);
internal.add_operator_product(bp, value)?;
}
}
Ok(internal)
}
}
impl ops::Neg for BosonHamiltonian {
type Output = BosonHamiltonian;
fn neg(self) -> Self {
let mut internal = self.internal_map.clone();
for key in self.keys() {
internal.insert(key.clone(), internal[key].clone() * -1.0);
}
BosonHamiltonian {
internal_map: internal,
}
}
}
impl<T, V> ops::Add<T> for BosonHamiltonian
where
T: IntoIterator<Item = (HermitianBosonProduct, 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 BosonHamiltonian
where
T: IntoIterator<Item = (HermitianBosonProduct, 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 ops::Mul<CalculatorFloat> for BosonHamiltonian {
type Output = Self;
fn mul(self, other: CalculatorFloat) -> Self {
let mut internal = self.internal_map.clone();
for key in self.keys() {
internal.insert(key.clone(), internal[key].clone() * other.clone());
}
BosonHamiltonian {
internal_map: internal,
}
}
}
impl ops::Mul<CalculatorComplex> for BosonHamiltonian {
type Output = BosonOperator;
fn mul(self, other: CalculatorComplex) -> BosonOperator {
let mut new_out = BosonOperator::with_capacity(self.len());
for (key, val) in self {
if key.is_natural_hermitian() {
let new_key =
BosonProduct::new(key.creators().copied(), key.annihilators().copied())
.expect("Internal bug in BosonProduct::new");
new_out
.add_operator_product(new_key, other.clone() * val)
.expect("Internal bug in add_operator_product");
} else {
let new_key =
BosonProduct::new(key.creators().copied(), key.annihilators().copied())
.expect("Internal bug in BosonProduct::new");
new_out
.add_operator_product(new_key, other.clone() * val.clone())
.expect("Internal bug in add_operator_product");
let (key_tmp, prefactor) = key.hermitian_conjugate();
let new_key =
BosonProduct::new(key_tmp.annihilators().copied(), key_tmp.creators().copied())
.expect("Internal bug in BosonProduct::new");
new_out
.add_operator_product(new_key, other.clone() * val * prefactor)
.expect("Internal bug in add_operator_product");
}
}
new_out
}
}
impl ops::Mul<BosonHamiltonian> for BosonHamiltonian {
type Output = BosonOperator;
fn mul(self, other: BosonHamiltonian) -> BosonOperator {
let mut op = BosonOperator::with_capacity(self.len() * other.len());
for (bps, vals) in self {
for (bpo, valo) in other.iter() {
let boson_products = bps.clone() * bpo.clone();
let coefficient = Into::<CalculatorComplex>::into(valo) * vals.clone();
for b in boson_products {
op.add_operator_product(b, coefficient.clone())
.expect("Internal bug in add_operator_product");
}
}
}
op
}
}
impl IntoIterator for BosonHamiltonian {
type Item = (HermitianBosonProduct, CalculatorComplex);
#[cfg(not(feature = "indexed_map_iterators"))]
type IntoIter = std::collections::hash_map::IntoIter<HermitianBosonProduct, CalculatorComplex>;
#[cfg(feature = "indexed_map_iterators")]
type IntoIter = indexmap::map::IntoIter<HermitianBosonProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.internal_map.into_iter()
}
}
impl<'a> IntoIterator for &'a BosonHamiltonian {
type Item = (&'a HermitianBosonProduct, &'a CalculatorComplex);
type IntoIter = Iter<'a, HermitianBosonProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.internal_map.iter()
}
}
impl FromIterator<(HermitianBosonProduct, CalculatorComplex)> for BosonHamiltonian {
fn from_iter<I: IntoIterator<Item = (HermitianBosonProduct, CalculatorComplex)>>(
iter: I,
) -> Self {
let mut so = BosonHamiltonian::new();
for (pp, cc) in iter {
so.add_operator_product(pp, cc)
.expect("Internal error in add_operator_product");
}
so
}
}
impl Extend<(HermitianBosonProduct, CalculatorComplex)> for BosonHamiltonian {
fn extend<I: IntoIterator<Item = (HermitianBosonProduct, CalculatorComplex)>>(
&mut self,
iter: I,
) {
for (pp, cc) in iter {
self.add_operator_product(pp, cc)
.expect("Internal bug in add_operator_product");
}
}
}
impl fmt::Display for BosonHamiltonian {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut output = "BosonHamiltonian{\n".to_string();
for (key, val) in self.iter() {
writeln!(output, "{key}: {val},")?;
}
output.push('}');
write!(f, "{output}")
}
}
#[cfg(test)]
mod test {
use super::*;
use serde_test::{assert_tokens, Configure, Token};
#[test]
fn so_from_sos() {
let pp: HermitianBosonProduct = HermitianBosonProduct::new([0], [0]).unwrap();
let sos = BosonHamiltonianSerialize {
items: vec![(pp.clone(), 0.5.into(), 0.0.into())],
_struqture_version: StruqtureVersionSerializable {
major_version: 1,
minor_version: 0,
},
};
let mut so = BosonHamiltonian::new();
so.set(pp, CalculatorComplex::from(0.5)).unwrap();
assert_eq!(BosonHamiltonian::from(sos.clone()), so);
assert_eq!(BosonHamiltonianSerialize::from(so), sos);
}
#[test]
fn clone_partial_eq() {
let pp: HermitianBosonProduct = HermitianBosonProduct::new([0], [0]).unwrap();
let sos = BosonHamiltonianSerialize {
items: vec![(pp, 0.5.into(), 0.0.into())],
_struqture_version: StruqtureVersionSerializable {
major_version: 1,
minor_version: 0,
},
};
assert_eq!(sos.clone(), sos);
let pp_1: HermitianBosonProduct = HermitianBosonProduct::new([0], [0]).unwrap();
let sos_1 = BosonHamiltonianSerialize {
items: vec![(pp_1, 0.5.into(), 0.0.into())],
_struqture_version: StruqtureVersionSerializable {
major_version: 1,
minor_version: 0,
},
};
let pp_2: HermitianBosonProduct = HermitianBosonProduct::new([0], [1]).unwrap();
let sos_2 = BosonHamiltonianSerialize {
items: vec![(pp_2, 0.5.into(), 0.0.into())],
_struqture_version: StruqtureVersionSerializable {
major_version: 1,
minor_version: 0,
},
};
assert!(sos_1 == sos);
assert!(sos == sos_1);
assert!(sos_2 != sos);
assert!(sos != sos_2);
}
#[test]
fn debug() {
let pp: HermitianBosonProduct = HermitianBosonProduct::new([0], [0]).unwrap();
let sos = BosonHamiltonianSerialize {
items: vec![(pp, 0.5.into(), 0.0.into())],
_struqture_version: StruqtureVersionSerializable {
major_version: 1,
minor_version: 0,
},
};
assert_eq!(
format!("{sos:?}"),
"BosonHamiltonianSerialize { items: [(HermitianBosonProduct { creators: [0], annihilators: [0] }, Float(0.5), Float(0.0))], _struqture_version: StruqtureVersionSerializable { major_version: 1, minor_version: 0 } }"
);
}
#[test]
fn serde_readable() {
let pp: HermitianBosonProduct = HermitianBosonProduct::new([0], [0]).unwrap();
let sos = BosonHamiltonianSerialize {
items: vec![(pp, 0.5.into(), 0.0.into())],
_struqture_version: StruqtureVersionSerializable {
major_version: 1,
minor_version: 0,
},
};
assert_tokens(
&sos.readable(),
&[
Token::Struct {
name: "BosonHamiltonianSerialize",
len: 2,
},
Token::Str("items"),
Token::Seq { len: Some(1) },
Token::Tuple { len: 3 },
Token::Str("c0a0"),
Token::F64(0.5),
Token::F64(0.0),
Token::TupleEnd,
Token::SeqEnd,
Token::Str("_struqture_version"),
Token::Struct {
name: "StruqtureVersionSerializable",
len: 2,
},
Token::Str("major_version"),
Token::U32(1),
Token::Str("minor_version"),
Token::U32(0),
Token::StructEnd,
Token::StructEnd,
],
);
}
#[test]
fn serde_compact() {
let pp: HermitianBosonProduct = HermitianBosonProduct::new([0], [0]).unwrap();
let sos = BosonHamiltonianSerialize {
items: vec![(pp, 0.5.into(), 0.0.into())],
_struqture_version: StruqtureVersionSerializable {
major_version: 1,
minor_version: 0,
},
};
assert_tokens(
&sos.compact(),
&[
Token::Struct {
name: "BosonHamiltonianSerialize",
len: 2,
},
Token::Str("items"),
Token::Seq { len: Some(1) },
Token::Tuple { len: 3 },
Token::Tuple { len: 2 },
Token::Seq { len: Some(1) },
Token::U64(0),
Token::SeqEnd,
Token::Seq { len: Some(1) },
Token::U64(0),
Token::SeqEnd,
Token::TupleEnd,
Token::NewtypeVariant {
name: "CalculatorFloat",
variant: "Float",
},
Token::F64(0.5),
Token::NewtypeVariant {
name: "CalculatorFloat",
variant: "Float",
},
Token::F64(0.0),
Token::TupleEnd,
Token::SeqEnd,
Token::Str("_struqture_version"),
Token::Struct {
name: "StruqtureVersionSerializable",
len: 2,
},
Token::Str("major_version"),
Token::U32(1),
Token::Str("minor_version"),
Token::U32(0),
Token::StructEnd,
Token::StructEnd,
],
);
}
}