use super::{FermionOperator, OperateOnFermions};
use crate::fermions::FermionProduct;
use crate::mappings::JordanWignerFermionToSpin;
use crate::spins::SpinSystem;
use crate::{ModeIndex, OperateOnDensityMatrix, OperateOnModes, OperateOnState, StruqtureError};
#[cfg(feature = "indexed_map_iterators")]
use indexmap::map::{Iter, Keys, Values};
use qoqo_calculator::CalculatorComplex;
use serde::{Deserialize, Serialize};
#[cfg(not(feature = "indexed_map_iterators"))]
use std::collections::hash_map::{Iter, Keys, Values};
use std::fmt::{self, Write};
use std::iter::{FromIterator, IntoIterator};
use std::ops;
#[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 FermionSystem {
pub(crate) number_modes: Option<usize>,
pub(crate) operator: FermionOperator,
}
impl crate::MinSupportedVersion for FermionSystem {}
impl<'a> OperateOnDensityMatrix<'a> for FermionSystem {
type Index = FermionProduct;
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: &FermionProduct) -> &CalculatorComplex {
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: FermionOperator::with_capacity(cap),
},
None => Self {
number_modes: self.number_modes,
operator: FermionOperator::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 FermionSystem {}
impl<'a> OperateOnModes<'a> for FermionSystem {
fn number_modes(&'a self) -> usize {
match self.number_modes {
Some(spins) => spins,
None => self.operator.current_number_modes(),
}
}
fn current_number_modes(&'a self) -> usize {
self.operator.current_number_modes()
}
}
impl OperateOnFermions<'_> for FermionSystem {}
impl FermionSystem {
pub fn new(number_modes: Option<usize>) -> Self {
FermionSystem {
number_modes,
operator: FermionOperator::new(),
}
}
pub fn with_capacity(number_modes: Option<usize>, capacity: usize) -> Self {
FermionSystem {
number_modes,
operator: FermionOperator::with_capacity(capacity),
}
}
pub fn operator(&self) -> &FermionOperator {
&self.operator
}
pub fn from_operator(
operator: FermionOperator,
number_modes: Option<usize>,
) -> Result<Self, StruqtureError> {
match number_modes {
Some(x) => {
if operator.current_number_modes() <= x {
Ok(FermionSystem {
number_modes: Some(x),
operator,
})
} else {
Err(StruqtureError::NumberModesExceeded)
}
}
None => Ok(FermionSystem {
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 FermionSystem {
type Output = FermionSystem;
fn neg(mut self) -> Self {
self.operator = self.operator.neg();
self
}
}
impl<T, V> ops::Add<T> for FermionSystem
where
T: IntoIterator<Item = (FermionProduct, 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 FermionSystem
where
T: IntoIterator<Item = (FermionProduct, 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 FermionSystem
where
T: Into<CalculatorComplex>,
{
type Output = Self;
fn mul(mut self, other: T) -> Self {
self.operator = self.operator * other;
self
}
}
impl ops::Mul<FermionSystem> for FermionSystem {
type Output = Self;
fn mul(self, other: FermionSystem) -> Self {
FermionSystem {
number_modes: Some(self.number_modes().max(other.number_modes())),
operator: self.operator * other.operator,
}
}
}
impl IntoIterator for FermionSystem {
type Item = (FermionProduct, CalculatorComplex);
#[cfg(not(feature = "indexed_map_iterators"))]
type IntoIter = std::collections::hash_map::IntoIter<FermionProduct, CalculatorComplex>;
#[cfg(feature = "indexed_map_iterators")]
type IntoIter = indexmap::map::IntoIter<FermionProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.operator.into_iter()
}
}
impl<'a> IntoIterator for &'a FermionSystem {
type Item = (&'a FermionProduct, &'a CalculatorComplex);
type IntoIter = Iter<'a, FermionProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.operator.iter()
}
}
impl FromIterator<(FermionProduct, CalculatorComplex)> for FermionSystem {
fn from_iter<I: IntoIterator<Item = (FermionProduct, CalculatorComplex)>>(iter: I) -> Self {
let mut so = FermionSystem::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<(FermionProduct, CalculatorComplex)> for FermionSystem {
fn extend<I: IntoIterator<Item = (FermionProduct, CalculatorComplex)>>(&mut self, iter: I) {
for (fp, cc) in iter {
self.add_operator_product(fp, cc)
.expect("Internal error in add_operator_product");
}
}
}
impl fmt::Display for FermionSystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut output = format!("FermionSystem({}){{\n", self.number_modes());
for (key, val) in self.iter() {
writeln!(output, "{key}: {val},")?;
}
output.push('}');
write!(f, "{output}")
}
}
impl JordanWignerFermionToSpin for FermionSystem {
type Output = SpinSystem;
fn jordan_wigner(&self) -> Self::Output {
SpinSystem::from_operator(
self.operator().jordan_wigner(),
Some(self.number_modes()),
)
.expect("Internal bug in jordan_wigner for FermionSystem. The number of spins in the resulting SpinSystem should equal the number of modes of the FermionSystem.")
}
}