use super::{
FermionHamiltonian, FermionSystem, HermitianFermionProduct, ModeIndex, OperateOnFermions,
};
use crate::mappings::JordanWignerFermionToSpin;
use crate::spins::SpinHamiltonianSystem;
use crate::{OperateOnDensityMatrix, OperateOnModes, OperateOnState, StruqtureError};
#[cfg(feature = "indexed_map_iterators")]
use indexmap::map::{Iter, Keys, Values};
use qoqo_calculator::{CalculatorComplex, CalculatorFloat};
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 FermionHamiltonianSystem {
pub(crate) number_modes: Option<usize>,
pub(crate) hamiltonian: FermionHamiltonian,
}
impl crate::MinSupportedVersion for FermionHamiltonianSystem {}
impl<'a> OperateOnDensityMatrix<'a> for FermionHamiltonianSystem {
type Index = HermitianFermionProduct;
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 {
self.hamiltonian.get(key)
}
fn iter(&'a self) -> Self::IteratorType {
self.hamiltonian.iter()
}
fn keys(&'a self) -> Self::KeyIteratorType {
self.hamiltonian.keys()
}
fn values(&'a self) -> Self::ValueIteratorType {
self.hamiltonian.values()
}
fn remove(&mut self, key: &Self::Index) -> Option<CalculatorComplex> {
self.hamiltonian.remove(key)
}
fn empty_clone(&self, capacity: Option<usize>) -> Self {
match capacity {
Some(cap) => Self {
number_modes: self.number_modes,
hamiltonian: FermionHamiltonian::with_capacity(cap),
},
None => Self {
number_modes: self.number_modes,
hamiltonian: FermionHamiltonian::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.hamiltonian.set(key, value)
} else {
Err(StruqtureError::NumberModesExceeded)
}
}
None => self.hamiltonian.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.hamiltonian.add_operator_product(key, value)
} else {
Err(StruqtureError::NumberModesExceeded)
}
}
None => self.hamiltonian.add_operator_product(key, value),
}
}
}
impl OperateOnState<'_> for FermionHamiltonianSystem {
fn hermitian_conjugate(&self) -> Self {
self.clone()
}
}
impl OperateOnModes<'_> for FermionHamiltonianSystem {
fn number_modes(&self) -> usize {
match self.number_modes {
Some(fermions) => fermions,
None => self.hamiltonian.current_number_modes(),
}
}
fn current_number_modes(&self) -> usize {
self.hamiltonian.current_number_modes()
}
}
impl OperateOnFermions<'_> for FermionHamiltonianSystem {}
impl FermionHamiltonianSystem {
pub fn new(number_modes: Option<usize>) -> Self {
FermionHamiltonianSystem {
number_modes,
hamiltonian: FermionHamiltonian::new(),
}
}
pub fn with_capacity(number_modes: Option<usize>, capacity: usize) -> Self {
FermionHamiltonianSystem {
number_modes,
hamiltonian: FermionHamiltonian::with_capacity(capacity),
}
}
pub fn hamiltonian(&self) -> &FermionHamiltonian {
&self.hamiltonian
}
pub fn from_hamiltonian(
hamiltonian: FermionHamiltonian,
number_modes: Option<usize>,
) -> Result<Self, StruqtureError> {
match number_modes {
Some(x) => {
if hamiltonian.current_number_modes() <= x {
Ok(FermionHamiltonianSystem {
number_modes: Some(x),
hamiltonian,
})
} else {
Err(StruqtureError::NumberModesExceeded)
}
}
None => Ok(FermionHamiltonianSystem {
number_modes: None,
hamiltonian,
}),
}
}
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 FermionHamiltonianSystem {
type Output = Self;
fn neg(mut self) -> Self {
self.hamiltonian = self.hamiltonian.neg();
self
}
}
impl<T, V> ops::Add<T> for FermionHamiltonianSystem
where
T: IntoIterator<Item = (HermitianFermionProduct, 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 FermionHamiltonianSystem
where
T: IntoIterator<Item = (HermitianFermionProduct, 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 FermionHamiltonianSystem {
type Output = Self;
fn mul(mut self, other: CalculatorFloat) -> Self {
self.hamiltonian = self.hamiltonian * other;
self
}
}
impl ops::Mul<CalculatorComplex> for FermionHamiltonianSystem {
type Output = Result<FermionSystem, StruqtureError>;
fn mul(self, other: CalculatorComplex) -> Self::Output {
let mut system = FermionSystem::new(self.number_modes);
system.operator = (self.hamiltonian * other)?;
Ok(system)
}
}
impl ops::Mul<FermionHamiltonianSystem> for FermionHamiltonianSystem {
type Output = Result<FermionSystem, StruqtureError>;
fn mul(self, other: FermionHamiltonianSystem) -> Self::Output {
Ok(FermionSystem {
number_modes: Some(self.number_modes().max(other.number_modes())),
operator: (self.hamiltonian * other.hamiltonian)?,
})
}
}
impl IntoIterator for FermionHamiltonianSystem {
type Item = (HermitianFermionProduct, CalculatorComplex);
#[cfg(not(feature = "indexed_map_iterators"))]
type IntoIter =
std::collections::hash_map::IntoIter<HermitianFermionProduct, CalculatorComplex>;
#[cfg(feature = "indexed_map_iterators")]
type IntoIter = indexmap::map::IntoIter<HermitianFermionProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.hamiltonian.into_iter()
}
}
impl<'a> IntoIterator for &'a FermionHamiltonianSystem {
type Item = (&'a HermitianFermionProduct, &'a CalculatorComplex);
type IntoIter = Iter<'a, HermitianFermionProduct, CalculatorComplex>;
fn into_iter(self) -> Self::IntoIter {
self.hamiltonian.iter()
}
}
impl FromIterator<(HermitianFermionProduct, CalculatorComplex)> for FermionHamiltonianSystem {
fn from_iter<I: IntoIterator<Item = (HermitianFermionProduct, CalculatorComplex)>>(
iter: I,
) -> Self {
let mut bhs = FermionHamiltonianSystem::new(None);
for (bp, cc) in iter {
bhs.add_operator_product(bp.clone(), cc.clone())
.expect("Internal error in add_operator_product");
}
bhs
}
}
impl Extend<(HermitianFermionProduct, CalculatorComplex)> for FermionHamiltonianSystem {
fn extend<I: IntoIterator<Item = (HermitianFermionProduct, CalculatorComplex)>>(
&mut self,
iter: I,
) {
for (bp, cc) in iter {
self.add_operator_product(bp, cc)
.expect("Internal error in add_operator_product");
}
}
}
impl fmt::Display for FermionHamiltonianSystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut output = format!("FermionHamiltonianSystem({}){{\n", self.number_modes());
for (key, val) in self.iter() {
writeln!(output, "{key}: {val},")?;
}
output.push('}');
write!(f, "{output}")
}
}
impl JordanWignerFermionToSpin for FermionHamiltonianSystem {
type Output = SpinHamiltonianSystem;
fn jordan_wigner(&self) -> Self::Output {
SpinHamiltonianSystem::from_hamiltonian(
self.hamiltonian().jordan_wigner(),
self.number_modes,
)
.expect("Internal bug in jordan_wigner for FermionHamiltonian. The number of spins in the resulting Hamiltonian should equal the number of modes of the FermionHamiltonian.")
}
}