use alloc::collections::BTreeMap;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use crate::qubo::ordered;
use crate::{Coefficient, Qubo};
#[derive(Debug, Clone, PartialEq)]
pub struct Ising<T> {
offset: T,
field: Vec<T>,
coupling: BTreeMap<(usize, usize), T>,
scale: T,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InexactScale;
impl fmt::Display for InexactScale {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a QUBO coefficient is not an exact multiple of the Ising scale")
}
}
impl core::error::Error for InexactScale {}
impl<T: Coefficient> Ising<T> {
#[must_use]
pub fn new(spins: usize, scale: T) -> Self {
assert!(scale != T::ZERO, "the Ising scale must not be zero");
Self {
offset: T::ZERO,
field: vec![T::ZERO; spins],
coupling: BTreeMap::new(),
scale,
}
}
#[must_use]
pub fn num_spins(&self) -> usize {
self.field.len()
}
#[must_use]
pub fn offset(&self) -> T {
self.offset
}
#[must_use]
pub fn scale(&self) -> T {
self.scale
}
#[must_use]
pub fn field(&self, i: usize) -> T {
self.field[i]
}
#[must_use]
pub fn coupling(&self, i: usize, j: usize) -> T {
self.coupling
.get(&ordered(i, j))
.copied()
.unwrap_or(T::ZERO)
}
pub fn couplings(&self) -> impl Iterator<Item = (usize, usize, T)> + '_ {
self.coupling.iter().map(|(&(i, j), &c)| (i, j, c))
}
pub fn add_offset(&mut self, value: T) {
self.offset = self.offset.plus(value);
}
pub fn add_field(&mut self, i: usize, value: T) {
let h = &mut self.field[i];
*h = h.plus(value);
}
pub fn add_coupling(&mut self, i: usize, j: usize, value: T) {
assert!(
i.max(j) < self.num_spins(),
"the pair ({i}, {j}) refers to a spin outside the model"
);
if i == j {
self.add_offset(value);
return;
}
let c = self.coupling.entry(ordered(i, j)).or_insert(T::ZERO);
*c = c.plus(value);
}
#[must_use]
pub fn energy(&self, s: &[bool]) -> T {
assert_eq!(
s.len(),
self.num_spins(),
"the spin configuration length must equal the number of spins"
);
let field = self
.field
.iter()
.zip(s)
.fold(self.offset, |sum, (&h, &si)| signed_add(sum, h, si));
self.couplings()
.fold(field, |sum, (i, j, c)| signed_add(sum, c, s[i] == s[j]))
}
pub fn to_qubo(&self) -> Result<Qubo<T>, InexactScale> {
let mut scaled = Qubo::new(self.num_spins());
scaled.add_offset(self.offset);
for (i, &h) in self.field.iter().enumerate() {
add_field_to_qubo(&mut scaled, i, h);
}
for (i, j, c) in self.couplings() {
add_coupling_to_qubo(&mut scaled, i, j, c);
}
scaled.try_map_coefficients(|v| v.exact_div(self.scale).ok_or(InexactScale))
}
pub(crate) fn map_coefficients(mut self, f: impl Fn(T) -> T) -> Self {
self.offset = f(self.offset);
self.field.iter_mut().for_each(|h| *h = f(*h));
self.coupling.values_mut().for_each(|c| *c = f(*c));
self
}
}
fn signed_add<T: Coefficient>(sum: T, value: T, positive: bool) -> T {
if positive {
sum.plus(value)
} else {
sum.minus(value)
}
}
fn add_field_to_qubo<T: Coefficient>(qubo: &mut Qubo<T>, i: usize, h: T) {
qubo.add_linear(i, h.plus(h));
qubo.add_offset(T::ZERO.minus(h));
}
fn add_coupling_to_qubo<T: Coefficient>(qubo: &mut Qubo<T>, i: usize, j: usize, c: T) {
let twice = c.plus(c);
qubo.add_quadratic(i, j, twice.plus(twice));
qubo.add_linear(i, T::ZERO.minus(twice));
qubo.add_linear(j, T::ZERO.minus(twice));
qubo.add_offset(c);
}
#[cfg(test)]
mod tests {
use super::{InexactScale, Ising};
use crate::Qubo;
#[test]
fn energy_uses_signed_spins() {
let mut ising = Ising::<i64>::new(2, 1);
ising.add_offset(1);
ising.add_field(0, 2);
ising.add_coupling(0, 1, 3);
assert_eq!(ising.energy(&[true, true]), 1 + 2 + 3);
assert_eq!(ising.energy(&[true, false]), 1 + 2 - 3);
assert_eq!(ising.energy(&[false, false]), 1 - 2 + 3);
}
#[test]
fn i64_round_trip_is_exact() {
let mut qubo = Qubo::<i64>::new(2);
qubo.add_offset(1);
qubo.add_linear(0, 1);
qubo.add_quadratic(0, 1, 1);
let ising = qubo.to_ising();
assert_eq!(ising.scale(), 4);
assert_eq!(ising.to_qubo(), Ok(qubo));
}
#[test]
fn inexact_scale_is_an_error() {
let mut ising = Ising::<i64>::new(1, 4);
ising.add_field(0, 1);
assert_eq!(ising.to_qubo(), Err(InexactScale));
}
}