use super::{ToSparseMatrixOperator, ToSparseMatrixSuperOperator};
use crate::fermions::FermionSystem;
use crate::mappings::JordanWignerSpinToFermion;
use crate::spins::{OperateOnSpins, PauliProduct, SpinIndex, SpinOperator};
use crate::{
CooSparseMatrix, OperateOnDensityMatrix, OperateOnState, StruqtureError, SymmetricIndex,
};
#[cfg(feature = "indexed_map_iterators")]
use indexmap::map::{Iter, Keys, Values};
use num_complex::Complex64;
use qoqo_calculator::CalculatorComplex;
use serde::{Deserialize, Serialize};
#[cfg(not(feature = "indexed_map_iterators"))]
use std::collections::hash_map::{Iter, Keys, Values};
use std::iter::{FromIterator, IntoIterator};
use std::{
fmt::{self, Write},
ops,
};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "json_schema", derive(schemars::JsonSchema))]
pub struct SpinSystem {
pub(crate) number_spins: Option<usize>,
pub(crate) operator: SpinOperator,
}
impl crate::MinSupportedVersion for SpinSystem {}
impl<'a> OperateOnDensityMatrix<'a> for SpinSystem {
type Value = CalculatorComplex;
type Index = PauliProduct;
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: SpinOperator::with_capacity(cap),
},
None => Self {
number_spins: self.number_spins,
operator: SpinOperator::new(),
},
}
}
fn set(
&mut self,
key: Self::Index,
value: Self::Value,
) -> Result<Option<Self::Value>, StruqtureError> {
match self.number_spins {
Some(x) => {
if key.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.current_number_spins() <= x {
self.operator.add_operator_product(key, value)
} else {
Err(StruqtureError::NumberSpinsExceeded)
}
}
None => self.operator.add_operator_product(key, value),
}
}
}
impl OperateOnState<'_> for SpinSystem {
fn hermitian_conjugate(&self) -> Self {
let mut new_operator = Self::with_capacity(self.number_spins, self.len());
for (pauli_product, value) in self.iter() {
let (new_spin_product, prefactor) = pauli_product.hermitian_conjugate();
new_operator
.add_operator_product(new_spin_product, value.conj() * prefactor)
.expect("Internal bug in add_operator_product");
}
new_operator
}
}
impl OperateOnSpins<'_> for SpinSystem {
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 ToSparseMatrixOperator<'_> for SpinSystem {}
impl<'a> ToSparseMatrixSuperOperator<'a> for SpinSystem {
fn sparse_matrix_superoperator_entries_on_row(
&'a self,
row: usize,
number_spins: usize,
) -> Result<std::collections::HashMap<usize, Complex64>, StruqtureError> {
<Self as ToSparseMatrixOperator>::sparse_matrix_superoperator_entries_on_row(
self,
row,
number_spins,
)
}
fn unitary_sparse_matrix_coo(&'a self) -> Result<CooSparseMatrix, StruqtureError> {
self.operator.sparse_matrix_coo(self.number_spins)
}
fn sparse_lindblad_entries(
&'a self,
) -> Result<Vec<(CooSparseMatrix, CooSparseMatrix, Complex64)>, StruqtureError> {
let rate = Complex64::default();
let left: CooSparseMatrix = (vec![], (vec![], vec![]));
let right: CooSparseMatrix = (vec![], (vec![], vec![]));
Ok(vec![(left, right, rate)])
}
}
impl SpinSystem {
pub fn new(number_spins: Option<usize>) -> Self {
SpinSystem {
number_spins,
operator: SpinOperator::new(),
}
}
pub fn with_capacity(number_spins: Option<usize>, capacity: usize) -> Self {
SpinSystem {
number_spins,
operator: SpinOperator::with_capacity(capacity),
}
}
pub fn operator(&self) -> &SpinOperator {
&self.operator
}
pub fn from_operator(
operator: SpinOperator,
number_spins: Option<usize>,
) -> Result<Self, StruqtureError> {
match number_spins {
Some(x) => {
if operator.current_number_spins() <= x {
Ok(SpinSystem {
number_spins: Some(x),
operator,
})
} else {
Err(StruqtureError::NumberSpinsExceeded)
}
}
None => Ok(SpinSystem {
number_spins: None,
operator,
}),
}
}
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 SpinSystem {
type Output = Self;
fn neg(mut self) -> Self {
self.operator = self.operator.neg();
self
}
}
impl<T, V> ops::Add<T> for SpinSystem
where
T: IntoIterator<Item = (PauliProduct, 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 SpinSystem
where
T: IntoIterator<Item = (PauliProduct, 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 SpinSystem
where
T: Into<CalculatorComplex>,
{
type Output = Self;
fn mul(mut self, other: T) -> Self {
self.operator = self.operator * other;
self
}
}
impl ops::Mul<SpinSystem> for SpinSystem {
type Output = Self;
fn mul(self, other: SpinSystem) -> Self::Output {
SpinSystem {
number_spins: Some(self.number_spins().max(other.number_spins())),
operator: self.operator * other.operator,
}
}
}
impl IntoIterator for SpinSystem {
type Item = (PauliProduct, CalculatorComplex);
#[cfg(not(feature = "indexed_map_iterators"))]
type IntoIter = std::collections::hash_map::IntoIter<PauliProduct, CalculatorComplex>;
#[cfg(feature = "indexed_map_iterators")]
type IntoIter = indexmap::map::IntoIter<PauliProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.operator.into_iter()
}
}
impl<'a> IntoIterator for &'a SpinSystem {
type Item = (&'a PauliProduct, &'a CalculatorComplex);
type IntoIter = Iter<'a, PauliProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.operator.iter()
}
}
impl FromIterator<(PauliProduct, CalculatorComplex)> for SpinSystem {
fn from_iter<I: IntoIterator<Item = (PauliProduct, CalculatorComplex)>>(iter: I) -> Self {
let mut so = SpinSystem::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<(PauliProduct, CalculatorComplex)> for SpinSystem {
fn extend<I: IntoIterator<Item = (PauliProduct, 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 SpinSystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut output = format!("SpinSystem({}){{\n", self.number_spins());
for (key, val) in self.iter() {
writeln!(output, "{key}: {val},")?;
}
output.push('}');
write!(f, "{output}")
}
}
impl JordanWignerSpinToFermion for SpinSystem {
type Output = FermionSystem;
fn jordan_wigner(&self) -> Self::Output {
FermionSystem::from_operator(
self.operator().jordan_wigner(),
Some(self.number_spins()),
)
.expect("Internal bug in jordan_wigner() for SpinSystem. The number of modes in the resulting FermionSystem should equal the number of spins of the SpinSystem.")
}
}