use super::{DecoherenceProduct, ToSparseMatrixSuperOperator};
use crate::fermions::FermionLindbladNoiseSystem;
use crate::mappings::JordanWignerSpinToFermion;
use crate::spins::{OperateOnSpins, SpinIndex, SpinLindbladNoiseOperator};
use crate::{CooSparseMatrix, OperateOnDensityMatrix, StruqtureError};
use num_complex::Complex64;
use qoqo_calculator::CalculatorComplex;
use serde::{Deserialize, Serialize};
use std::iter::{FromIterator, IntoIterator};
use std::{
fmt::{self, Write},
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 SpinLindbladNoiseSystem {
pub(crate) number_spins: Option<usize>,
pub(crate) operator: SpinLindbladNoiseOperator,
}
impl crate::MinSupportedVersion for SpinLindbladNoiseSystem {}
impl<'a> OperateOnDensityMatrix<'a> for SpinLindbladNoiseSystem {
type Value = CalculatorComplex;
type Index = (DecoherenceProduct, DecoherenceProduct);
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_spins: self.number_spins,
operator: SpinLindbladNoiseOperator::with_capacity(cap),
},
None => Self {
number_spins: self.number_spins,
operator: SpinLindbladNoiseOperator::new(),
},
}
}
fn set(
&mut self,
key: Self::Index,
value: Self::Value,
) -> Result<Option<Self::Value>, StruqtureError> {
match self.number_spins {
Some(x) => {
if key.0.current_number_spins() <= x && key.1.current_number_spins() <= x {
self.operator.set(key, value)
} else {
Err(StruqtureError::NumberSpinsExceeded)
}
}
None => self.operator.set(key, value),
}
}
fn add_operator_product(
&mut self,
key: Self::Index,
value: Self::Value,
) -> Result<(), StruqtureError> {
match self.number_spins {
Some(x) => {
if key.0.current_number_spins() <= x && key.1.current_number_spins() <= x {
self.operator.add_operator_product(key, value)
} else {
Err(StruqtureError::NumberSpinsExceeded)
}
}
None => self.operator.add_operator_product(key, value),
}
}
}
impl OperateOnSpins<'_> for SpinLindbladNoiseSystem {
fn number_spins(&self) -> usize {
match self.number_spins {
Some(spins) => spins,
None => self.operator.current_number_spins(),
}
}
fn current_number_spins(&self) -> usize {
self.operator.current_number_spins()
}
}
impl<'a> ToSparseMatrixSuperOperator<'a> for SpinLindbladNoiseSystem {
fn sparse_matrix_superoperator_entries_on_row(
&'a self,
row: usize,
number_spins: usize,
) -> Result<std::collections::HashMap<usize, Complex64>, StruqtureError> {
self.operator
.sparse_matrix_superoperator_entries_on_row(row, number_spins)
}
fn unitary_sparse_matrix_coo(&'a self) -> Result<CooSparseMatrix, StruqtureError> {
Ok((vec![], (vec![], vec![])) as CooSparseMatrix)
}
fn sparse_lindblad_entries(
&'a self,
) -> Result<Vec<(CooSparseMatrix, CooSparseMatrix, Complex64)>, StruqtureError> {
let mut coo_matrices =
Vec::<(CooSparseMatrix, CooSparseMatrix, Complex64)>::with_capacity(self.len());
for ((left, right), val) in self.iter() {
coo_matrices.push((
left.to_coo(self.number_spins()).unwrap(),
right.to_coo(self.number_spins()).unwrap(),
Complex64 {
re: *val.re.float()?,
im: *val.im.float()?,
},
))
}
Ok(coo_matrices)
}
}
impl SpinLindbladNoiseSystem {
pub fn new(number_spins: Option<usize>) -> Self {
SpinLindbladNoiseSystem {
number_spins,
operator: SpinLindbladNoiseOperator::new(),
}
}
pub fn with_capacity(number_spins: Option<usize>, capacity: usize) -> Self {
SpinLindbladNoiseSystem {
number_spins,
operator: SpinLindbladNoiseOperator::with_capacity(capacity),
}
}
pub fn operator(&self) -> &SpinLindbladNoiseOperator {
&self.operator
}
pub fn from_operator(
operator: SpinLindbladNoiseOperator,
number_spins: Option<usize>,
) -> Result<Self, StruqtureError> {
match number_spins {
Some(x) => {
if operator.current_number_spins() <= x {
Ok(SpinLindbladNoiseSystem {
number_spins: Some(x),
operator,
})
} else {
Err(StruqtureError::NumberSpinsExceeded)
}
}
None => Ok(SpinLindbladNoiseSystem {
number_spins: None,
operator,
}),
}
}
pub fn separate_into_n_terms(
&self,
number_spins_left: usize,
number_spins_right: usize,
) -> Result<(Self, Self), StruqtureError> {
let mut separated = Self::default();
let mut remainder = Self::default();
for ((prod_l, prod_r), val) in self.iter() {
if prod_l.iter().len() == number_spins_left && prod_r.iter().len() == number_spins_right
{
separated.add_operator_product((prod_l.clone(), prod_r.clone()), val.clone())?;
} else {
remainder.add_operator_product((prod_l.clone(), prod_r.clone()), val.clone())?;
}
}
Ok((separated, remainder))
}
}
impl ops::Neg for SpinLindbladNoiseSystem {
type Output = Self;
fn neg(mut self) -> Self {
self.operator = self.operator.neg();
self
}
}
impl<T, V> ops::Add<T> for SpinLindbladNoiseSystem
where
T: IntoIterator<Item = ((DecoherenceProduct, DecoherenceProduct), 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 SpinLindbladNoiseSystem
where
T: IntoIterator<Item = ((DecoherenceProduct, DecoherenceProduct), 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 SpinLindbladNoiseSystem
where
T: Into<CalculatorComplex>,
{
type Output = Self;
fn mul(mut self, other: T) -> Self {
self.operator = self.operator * other;
self
}
}
impl IntoIterator for SpinLindbladNoiseSystem {
type Item = ((DecoherenceProduct, DecoherenceProduct), CalculatorComplex);
#[cfg(not(feature = "indexed_map_iterators"))]
type IntoIter = std::collections::hash_map::IntoIter<
(DecoherenceProduct, DecoherenceProduct),
CalculatorComplex,
>;
#[cfg(feature = "indexed_map_iterators")]
type IntoIter =
indexmap::map::IntoIter<(DecoherenceProduct, DecoherenceProduct), CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.operator.into_iter()
}
}
impl<'a> IntoIterator for &'a SpinLindbladNoiseSystem {
type Item = (
&'a (DecoherenceProduct, DecoherenceProduct),
&'a CalculatorComplex,
);
type IntoIter = Iter<'a, (DecoherenceProduct, DecoherenceProduct), CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.operator.iter()
}
}
impl FromIterator<((DecoherenceProduct, DecoherenceProduct), CalculatorComplex)>
for SpinLindbladNoiseSystem
{
fn from_iter<
I: IntoIterator<Item = ((DecoherenceProduct, DecoherenceProduct), CalculatorComplex)>,
>(
iter: I,
) -> Self {
let mut so = SpinLindbladNoiseSystem::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<((DecoherenceProduct, DecoherenceProduct), CalculatorComplex)>
for SpinLindbladNoiseSystem
{
fn extend<
I: IntoIterator<Item = ((DecoherenceProduct, DecoherenceProduct), CalculatorComplex)>,
>(
&mut self,
iter: I,
) {
for (pp, cc) in iter {
self.add_operator_product(pp, cc)
.expect("Internal error in add_operator_product");
}
}
}
impl fmt::Display for SpinLindbladNoiseSystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut output = format!("SpinLindbladNoiseSystem({}){{\n", self.number_spins());
for (key, val) in self.iter() {
writeln!(output, "({}, {}): {},", key.0, key.1, val)?;
}
output.push('}');
write!(f, "{output}")
}
}
impl JordanWignerSpinToFermion for SpinLindbladNoiseSystem {
type Output = FermionLindbladNoiseSystem;
fn jordan_wigner(&self) -> Self::Output {
FermionLindbladNoiseSystem::from_operator(
self.operator().jordan_wigner(),
self.number_spins,
)
.expect("Internal bug in jordan_wigner() for SpinLindbladNoiseOperator. The number of modes in the resulting fermionic noise operator should equal the number of spins of the spin noise operator.")
}
}