use super::{OperateOnSpins, SpinOperator};
use crate::fermions::FermionOperator;
use crate::mappings::JordanWignerSpinToFermion;
use crate::spins::DecoherenceProduct;
use crate::{
OperateOnDensityMatrix, OperateOnState, SpinIndex, 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, Deserialize, Serialize)]
#[serde(from = "DecoherenceOperatorSerialize")]
#[serde(into = "DecoherenceOperatorSerialize")]
pub struct DecoherenceOperator {
#[cfg(feature = "indexed_map_iterators")]
internal_map: IndexMap<DecoherenceProduct, CalculatorComplex>,
#[cfg(not(feature = "indexed_map_iterators"))]
internal_map: HashMap<DecoherenceProduct, CalculatorComplex>,
}
impl crate::MinSupportedVersion for DecoherenceOperator {}
#[cfg(feature = "json_schema")]
impl schemars::JsonSchema for DecoherenceOperator {
fn schema_name() -> std::borrow::Cow<'static, str> {
"DecoherenceOperator".into()
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
<DecoherenceOperatorSerialize>::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 DecoherenceOperatorSerialize {
items: Vec<(DecoherenceProduct, CalculatorFloat, CalculatorFloat)>,
_struqture_version: StruqtureVersionSerializable,
}
impl From<DecoherenceOperatorSerialize> for DecoherenceOperator {
fn from(value: DecoherenceOperatorSerialize) -> Self {
let new_noise_op: DecoherenceOperator = value
.items
.into_iter()
.map(|(key, real, imag)| (key, CalculatorComplex { re: real, im: imag }))
.collect();
new_noise_op
}
}
impl From<DecoherenceOperator> for DecoherenceOperatorSerialize {
fn from(value: DecoherenceOperator) -> Self {
let new_noise_op: Vec<(DecoherenceProduct, 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 DecoherenceOperator {
type IteratorType = Iter<'a, Self::Index, Self::Value>;
type KeyIteratorType = Keys<'a, Self::Index, Self::Value>;
type ValueIteratorType = Values<'a, Self::Index, Self::Value>;
type Value = CalculatorComplex;
type Index = DecoherenceProduct;
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 != CalculatorComplex::ZERO {
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),
}
}
}
}
impl OperateOnState<'_> for DecoherenceOperator {
fn hermitian_conjugate(&self) -> Self {
let mut new_operator = Self::with_capacity(self.len());
for (product, value) in self.iter() {
let (new_product, prefactor) = product.hermitian_conjugate();
new_operator
.add_operator_product(new_product, value.conj() * prefactor)
.expect("Internal bug in add_operator_product");
}
new_operator
}
}
impl OperateOnSpins<'_> for DecoherenceOperator {
fn current_number_spins(&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_spins() > max_mode {
max_mode = key.current_number_spins()
}
}
}
max_mode
}
fn number_spins(&self) -> usize {
self.current_number_spins()
}
}
impl Default for DecoherenceOperator {
fn default() -> Self {
Self::new()
}
}
impl DecoherenceOperator {
pub fn new() -> Self {
DecoherenceOperator {
#[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 {
DecoherenceOperator {
#[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_spins: usize,
) -> Result<(Self, Self), StruqtureError> {
let mut separated = Self::default();
let mut remainder = Self::default();
for (prod, val) in self.iter() {
if prod.len() == number_spins {
separated.add_operator_product(prod.clone(), val.clone())?;
} else {
remainder.add_operator_product(prod.clone(), val.clone())?;
}
}
Ok((separated, remainder))
}
}
impl ops::Neg for DecoherenceOperator {
type Output = DecoherenceOperator;
fn neg(self) -> Self {
#[cfg(not(feature = "indexed_map_iterators"))]
let mut internal = HashMap::with_capacity(self.len());
#[cfg(feature = "indexed_map_iterators")]
let mut internal = IndexMap::with_capacity(self.len());
for (key, val) in self {
internal.insert(key.clone(), val.neg());
}
DecoherenceOperator {
internal_map: internal,
}
}
}
impl<T, V> ops::Add<T> for DecoherenceOperator
where
T: IntoIterator<Item = (DecoherenceProduct, V)>,
V: Into<CalculatorComplex>,
{
type Output = Self;
fn add(mut self, other: T) -> Self {
for (key, value) in other.into_iter() {
self.add_operator_product(key.clone(), Into::<CalculatorComplex>::into(value))
.expect("Internal bug in add_operator_product");
}
self
}
}
impl<T, V> ops::Sub<T> for DecoherenceOperator
where
T: IntoIterator<Item = (DecoherenceProduct, V)>,
V: Into<CalculatorComplex>,
{
type Output = Self;
fn sub(mut self, other: T) -> Self {
for (key, value) in other.into_iter() {
self.add_operator_product(key.clone(), Into::<CalculatorComplex>::into(value) * -1.0)
.expect("Internal bug in add_operator_product");
}
self
}
}
impl<T> ops::Mul<T> for DecoherenceOperator
where
T: Into<CalculatorComplex>,
{
type Output = Self;
fn mul(self, other: T) -> Self {
let other_cc = Into::<CalculatorComplex>::into(other);
#[cfg(not(feature = "indexed_map_iterators"))]
let mut internal = HashMap::with_capacity(self.len());
#[cfg(feature = "indexed_map_iterators")]
let mut internal = IndexMap::with_capacity(self.len());
for (key, val) in self {
internal.insert(key, val * other_cc.clone());
}
DecoherenceOperator {
internal_map: internal,
}
}
}
impl ops::Mul<DecoherenceOperator> for DecoherenceOperator {
type Output = Self;
fn mul(self, other: DecoherenceOperator) -> Self {
let mut spin_op = DecoherenceOperator::with_capacity(self.len() * other.len());
for (pps, vals) in self {
for (ppo, valo) in other.iter() {
let (ppp, coefficient) = pps.clone() * ppo.clone();
let coefficient =
Into::<CalculatorComplex>::into(valo) * coefficient * vals.clone();
spin_op
.add_operator_product(ppp, coefficient)
.expect("Internal bug in add_operator_product");
}
}
spin_op
}
}
impl IntoIterator for DecoherenceOperator {
type Item = (DecoherenceProduct, CalculatorComplex);
#[cfg(not(feature = "indexed_map_iterators"))]
type IntoIter = std::collections::hash_map::IntoIter<DecoherenceProduct, CalculatorComplex>;
#[cfg(feature = "indexed_map_iterators")]
type IntoIter = indexmap::map::IntoIter<DecoherenceProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.internal_map.into_iter()
}
}
impl<'a> IntoIterator for &'a DecoherenceOperator {
type Item = (&'a DecoherenceProduct, &'a CalculatorComplex);
type IntoIter = Iter<'a, DecoherenceProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.internal_map.iter()
}
}
impl FromIterator<(DecoherenceProduct, CalculatorComplex)> for DecoherenceOperator {
fn from_iter<I: IntoIterator<Item = (DecoherenceProduct, CalculatorComplex)>>(iter: I) -> Self {
let mut so = DecoherenceOperator::new();
for (pp, cc) in iter {
so.add_operator_product(pp, cc)
.expect("Internal bug in add_operator_product");
}
so
}
}
impl Extend<(DecoherenceProduct, CalculatorComplex)> for DecoherenceOperator {
fn extend<I: IntoIterator<Item = (DecoherenceProduct, 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 DecoherenceOperator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut output = "DecoherenceOperator{\n".to_string();
for (key, val) in self.iter() {
writeln!(output, "{key}: {val},")?;
}
output.push('}');
write!(f, "{output}")
}
}
impl From<SpinOperator> for DecoherenceOperator {
fn from(op: SpinOperator) -> Self {
let mut out = DecoherenceOperator::new();
for prod in op.keys() {
let (new_prod, new_coeff) = DecoherenceProduct::spin_to_decoherence(prod.clone());
out.add_operator_product(new_prod, op.get(prod).clone() * new_coeff)
.expect("Internal error in add_operator_product");
}
out
}
}
impl JordanWignerSpinToFermion for DecoherenceOperator {
type Output = FermionOperator;
fn jordan_wigner(&self) -> Self::Output {
let mut out = FermionOperator::new();
for (dp, value) in self.iter() {
out = out + dp.jordan_wigner() * value;
}
out
}
}
#[cfg(test)]
mod test {
use super::*;
use serde_test::{assert_tokens, Configure, Token};
#[test]
fn so_from_sos() {
let pp: DecoherenceProduct = DecoherenceProduct::new().z(0);
let sos = DecoherenceOperatorSerialize {
items: vec![(pp.clone(), 0.5.into(), 0.0.into())],
_struqture_version: StruqtureVersionSerializable {
major_version: 1,
minor_version: 0,
},
};
let mut so = DecoherenceOperator::new();
so.set(pp, CalculatorComplex::from(0.5)).unwrap();
assert_eq!(DecoherenceOperator::from(sos.clone()), so);
assert_eq!(DecoherenceOperatorSerialize::from(so), sos);
}
#[test]
fn clone_partial_eq() {
let pp: DecoherenceProduct = DecoherenceProduct::new().z(0);
let sos = DecoherenceOperatorSerialize {
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: DecoherenceProduct = DecoherenceProduct::new().z(0);
let sos_1 = DecoherenceOperatorSerialize {
items: vec![(pp_1, 0.5.into(), 0.0.into())],
_struqture_version: StruqtureVersionSerializable {
major_version: 1,
minor_version: 0,
},
};
let pp_2: DecoherenceProduct = DecoherenceProduct::new().z(2);
let sos_2 = DecoherenceOperatorSerialize {
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: DecoherenceProduct = DecoherenceProduct::new().z(0);
let sos = DecoherenceOperatorSerialize {
items: vec![(pp, 0.5.into(), 0.0.into())],
_struqture_version: StruqtureVersionSerializable {
major_version: 1,
minor_version: 0,
},
};
assert_eq!(
format!("{sos:?}"),
"DecoherenceOperatorSerialize { items: [(DecoherenceProduct { items: [(0, Z)] }, Float(0.5), Float(0.0))], _struqture_version: StruqtureVersionSerializable { major_version: 1, minor_version: 0 } }"
);
}
#[test]
fn serde_readable() {
let pp = DecoherenceProduct::new().x(0);
let sos = DecoherenceOperatorSerialize {
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: "DecoherenceOperatorSerialize",
len: 2,
},
Token::Str("items"),
Token::Seq { len: Some(1) },
Token::Tuple { len: 3 },
Token::Str("0X"),
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 = DecoherenceProduct::new().x(0);
let sos = DecoherenceOperatorSerialize {
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: "DecoherenceOperatorSerialize",
len: 2,
},
Token::Str("items"),
Token::Seq { len: Some(1) },
Token::Tuple { len: 3 },
Token::Seq { len: Some(1) },
Token::Tuple { len: 2 },
Token::U64(0),
Token::UnitVariant {
name: "SingleDecoherenceOperator",
variant: "X",
},
Token::TupleEnd,
Token::SeqEnd,
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,
],
);
}
}