Skip to main content

qslib_core/
operators.rs

1use crate::{BasisBit, BasisState, Complex64, SiteCount, SiteId};
2use std::fmt::{self, Display, Formatter};
3
4/// Errors raised while constructing or applying local operators.
5#[derive(Clone, Debug, PartialEq)]
6pub enum OperatorError {
7    /// A Pauli support contains the same site more than once.
8    DuplicateSupport {
9        /// Repeated site.
10        site: SiteId,
11    },
12    /// An operator support is outside the Hamiltonian's site count.
13    SiteOutOfRange {
14        /// Invalid site.
15        site: SiteId,
16        /// Declared site count.
17        site_count: usize,
18    },
19    /// A coefficient contains NaN or infinity.
20    NonFiniteCoefficient {
21        /// Invalid coefficient.
22        value: Complex64,
23    },
24    /// The state length does not match the Hamiltonian.
25    StateLength {
26        /// Required state length.
27        expected: usize,
28        /// Supplied state length.
29        actual: usize,
30    },
31    /// A Hermitian Hamiltonian received a complex coefficient.
32    NonHermitianCoefficient {
33        /// Non-real coefficient.
34        value: Complex64,
35    },
36    /// The reference wavefunction amplitude is absent or zero.
37    ZeroReferenceAmplitude,
38    /// A connected state has no supplied wavefunction amplitude.
39    MissingAmplitude {
40        /// Connected state with no supplied amplitude.
41        state: BasisState,
42    },
43}
44
45impl Display for OperatorError {
46    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
47        match self {
48            Self::DuplicateSupport { site } => {
49                write!(formatter, "operator support repeats site {}", site.get())
50            }
51            Self::SiteOutOfRange { site, site_count } => write!(
52                formatter,
53                "operator site {} is outside {site_count} sites",
54                site.get()
55            ),
56            Self::NonFiniteCoefficient { value } => {
57                write!(formatter, "operator coefficient {value:?} is non-finite")
58            }
59            Self::StateLength { expected, actual } => write!(
60                formatter,
61                "operator expects {expected} sites, received {actual}"
62            ),
63            Self::NonHermitianCoefficient { value } => write!(
64                formatter,
65                "Hermitian operator coefficient {value:?} is non-real"
66            ),
67            Self::ZeroReferenceAmplitude => {
68                formatter.write_str("local-energy reference amplitude is zero or missing")
69            }
70            Self::MissingAmplitude { state } => write!(
71                formatter,
72                "local-energy amplitude table omits a connected {}-site state",
73                state.len()
74            ),
75        }
76    }
77}
78
79impl std::error::Error for OperatorError {}
80
81/// One local Pauli factor in a simulation basis.
82#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
83pub enum Pauli {
84    /// Identity factor.
85    I,
86    /// Pauli X factor.
87    X,
88    /// Pauli Y factor.
89    Y,
90    /// Pauli Z factor.
91    Z,
92}
93
94/// A Pauli product with distinct, canonical site support.
95#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
96pub struct PauliString {
97    factors: Vec<(SiteId, Pauli)>,
98}
99
100impl PauliString {
101    /// Construct a product and reject repeated support sites.
102    pub fn new(mut factors: Vec<(SiteId, Pauli)>) -> Result<Self, OperatorError> {
103        factors.retain(|(_, pauli)| *pauli != Pauli::I);
104        factors.sort_unstable_by_key(|factor| factor.0);
105        for pair in factors.windows(2) {
106            if pair[0].0 == pair[1].0 {
107                return Err(OperatorError::DuplicateSupport { site: pair[0].0 });
108            }
109        }
110        Ok(Self { factors })
111    }
112
113    /// Reduce an ordered product, returning its canonical Pauli string and phase.
114    pub fn product(factors: Vec<(SiteId, Pauli)>) -> Result<(Self, Complex64), OperatorError> {
115        let mut reduced: Vec<(SiteId, Pauli)> = Vec::new();
116        let mut phase = Complex64::new(1.0, 0.0);
117        for (site, pauli) in factors {
118            if pauli == Pauli::I {
119                continue;
120            }
121            if let Some((_, existing)) =
122                reduced.iter_mut().find(|(candidate, _)| *candidate == site)
123            {
124                let (next, factor) = multiply_pauli(*existing, pauli);
125                *existing = next;
126                phase *= factor;
127            } else {
128                reduced.push((site, pauli));
129            }
130        }
131        Ok((Self::new(reduced)?, phase))
132    }
133
134    /// Return canonical support factors.
135    pub fn factors(&self) -> &[(SiteId, Pauli)] {
136        &self.factors
137    }
138
139    /// Apply the Pauli product to one dense binary state.
140    pub fn apply(&self, state: &BasisState) -> Result<(BasisState, Complex64), OperatorError> {
141        let mut bits = state.bits().to_vec();
142        let mut coefficient = Complex64::new(1.0, 0.0);
143        for &(site, pauli) in &self.factors {
144            let index = site.get() as usize;
145            let bit = bits.get_mut(index).ok_or(OperatorError::SiteOutOfRange {
146                site,
147                site_count: state.len(),
148            })?;
149            match (pauli, *bit) {
150                (Pauli::I, _) => {}
151                (Pauli::X, value) => *bit = flip(value),
152                (Pauli::Y, value) => {
153                    coefficient *= if value == BasisBit::Zero {
154                        Complex64::new(0.0, 1.0)
155                    } else {
156                        Complex64::new(0.0, -1.0)
157                    };
158                    *bit = flip(value);
159                }
160                (Pauli::Z, value) => {
161                    coefficient *= Complex64::new(value.pauli_eigenvalue() as f64, 0.0)
162                }
163            }
164        }
165        BasisState::from_bits(&bits)
166            .map(|result| (result, coefficient))
167            .map_err(|_| OperatorError::StateLength {
168                expected: state.len(),
169                actual: 0,
170            })
171    }
172}
173
174fn flip(bit: BasisBit) -> BasisBit {
175    match bit {
176        BasisBit::Zero => BasisBit::One,
177        BasisBit::One => BasisBit::Zero,
178    }
179}
180
181/// A deterministic Hamiltonian term list with a physical scalar constant.
182#[derive(Clone, Debug, PartialEq)]
183pub struct Hamiltonian {
184    site_count: SiteCount,
185    constant: Complex64,
186    terms: Vec<(Complex64, PauliString)>,
187}
188
189impl Hamiltonian {
190    /// Validate and sort a Hamiltonian term list.
191    pub fn new(
192        site_count: SiteCount,
193        mut constant: Complex64,
194        terms: Vec<(Complex64, PauliString)>,
195    ) -> Result<Self, OperatorError> {
196        if !constant.re.is_finite() || !constant.im.is_finite() {
197            return Err(OperatorError::NonFiniteCoefficient { value: constant });
198        }
199        for (coefficient, operator) in &terms {
200            if !coefficient.re.is_finite() || !coefficient.im.is_finite() {
201                return Err(OperatorError::NonFiniteCoefficient {
202                    value: *coefficient,
203                });
204            }
205            for &(site, _) in operator.factors() {
206                site_count
207                    .validate(site)
208                    .map_err(|_| OperatorError::SiteOutOfRange {
209                        site,
210                        site_count: site_count.get(),
211                    })?;
212            }
213        }
214        let mut constants = vec![constant];
215        let mut non_identity = Vec::new();
216        for (coefficient, operator) in terms {
217            if operator.factors().is_empty() {
218                constants.push(coefficient);
219                continue;
220            }
221            non_identity.push((coefficient, operator));
222        }
223        constants.sort_by(complex_total_cmp);
224        constant = deterministic_complex_sum(&constants);
225        non_identity.sort_by(
226            |(left_coefficient, left_operator), (right_coefficient, right_operator)| {
227                left_operator
228                    .cmp(right_operator)
229                    .then_with(|| complex_total_cmp(left_coefficient, right_coefficient))
230            },
231        );
232        let mut combined: Vec<(Complex64, PauliString)> = Vec::new();
233        let mut pending_coefficients: Vec<Complex64> = Vec::new();
234        let mut pending_operator: Option<PauliString> = None;
235        for (coefficient, operator) in non_identity {
236            if pending_operator.as_ref() != Some(&operator) {
237                if let Some(previous_operator) = pending_operator.take() {
238                    let resolved = deterministic_complex_sum(&pending_coefficients);
239                    if !resolved.re.is_finite() || !resolved.im.is_finite() {
240                        return Err(OperatorError::NonFiniteCoefficient { value: resolved });
241                    }
242                    combined.push((resolved, previous_operator));
243                    pending_coefficients.clear();
244                }
245                pending_operator = Some(operator);
246            }
247            pending_coefficients.push(coefficient);
248        }
249        if let Some(previous_operator) = pending_operator {
250            let resolved = deterministic_complex_sum(&pending_coefficients);
251            if !resolved.re.is_finite() || !resolved.im.is_finite() {
252                return Err(OperatorError::NonFiniteCoefficient { value: resolved });
253            }
254            combined.push((resolved, previous_operator));
255        }
256        combined.retain(|(coefficient, _)| !is_exact_zero(*coefficient));
257        if !constant.re.is_finite() || !constant.im.is_finite() {
258            return Err(OperatorError::NonFiniteCoefficient { value: constant });
259        }
260        combined.sort_by(|a, b| a.1.cmp(&b.1));
261        Ok(Self {
262            site_count,
263            constant,
264            terms: combined,
265        })
266    }
267
268    /// Construct a Hamiltonian and require every term coefficient to be real.
269    pub fn new_hermitian(
270        site_count: SiteCount,
271        constant: Complex64,
272        terms: Vec<(Complex64, PauliString)>,
273    ) -> Result<Self, OperatorError> {
274        let result = Self::new(site_count, constant, terms)?;
275        if result.constant.im != 0.0 {
276            return Err(OperatorError::NonHermitianCoefficient {
277                value: result.constant,
278            });
279        }
280        if let Some((coefficient, _)) = result
281            .terms
282            .iter()
283            .find(|(coefficient, _)| coefficient.im != 0.0)
284        {
285            return Err(OperatorError::NonHermitianCoefficient {
286                value: *coefficient,
287            });
288        }
289        Ok(result)
290    }
291
292    /// Number of sites represented by the Hamiltonian.
293    pub const fn site_count(&self) -> SiteCount {
294        self.site_count
295    }
296
297    /// Return the physical scalar constant.
298    pub const fn constant(&self) -> Complex64 {
299        self.constant
300    }
301
302    /// Return deterministic coefficient/operator terms.
303    pub fn terms(&self) -> &[(Complex64, PauliString)] {
304        &self.terms
305    }
306
307    /// Apply the Hamiltonian and combine duplicate connected states.
308    pub fn apply(&self, state: &BasisState) -> Result<Vec<(BasisState, Complex64)>, OperatorError> {
309        if state.len() != self.site_count.get() {
310            return Err(OperatorError::StateLength {
311                expected: self.site_count.get(),
312                actual: state.len(),
313            });
314        }
315        let mut result = vec![(state.clone(), self.constant)];
316        for &(coefficient, ref operator) in &self.terms {
317            let (connected, matrix_element) = operator.apply(state)?;
318            add_transition(&mut result, connected, coefficient * matrix_element);
319        }
320        result.retain(|(_, coefficient)| !is_exact_zero(*coefficient));
321        result.sort_by_key(|(basis, _)| basis_key(basis));
322        Ok(result)
323    }
324
325    /// Evaluate `sum_b H_ab psi_b / psi_a` from an explicit amplitude table.
326    pub fn local_energy(
327        &self,
328        state: &BasisState,
329        amplitudes: &[(BasisState, Complex64)],
330    ) -> Result<Complex64, OperatorError> {
331        let reference = amplitudes
332            .iter()
333            .find(|(candidate, _)| candidate == state)
334            .map(|(_, amplitude)| *amplitude)
335            .ok_or(OperatorError::ZeroReferenceAmplitude)?;
336        if reference == Complex64::new(0.0, 0.0) {
337            return Err(OperatorError::ZeroReferenceAmplitude);
338        }
339        let mut row = vec![(state.clone(), self.constant)];
340        for &(coefficient, ref operator) in &self.terms {
341            let (connected, matrix_element) = operator.apply(state)?;
342            // Pauli strings are Hermitian, so P_ab = conjugate(P_ba),
343            // while a general Hamiltonian coefficient remains c rather than
344            // c*. This keeps the public complex-coefficient path correct.
345            add_transition(&mut row, connected, coefficient * matrix_element.conj());
346        }
347        row.retain(|(_, coefficient)| !is_exact_zero(*coefficient));
348        let mut numerator = Complex64::new(0.0, 0.0);
349        for (connected, coefficient) in row {
350            let amplitude = if connected == *state {
351                reference
352            } else {
353                amplitudes
354                    .iter()
355                    .find(|(candidate, _)| *candidate == connected)
356                    .map(|(_, value)| *value)
357                    .ok_or_else(|| OperatorError::MissingAmplitude {
358                        state: connected.clone(),
359                    })?
360            };
361            numerator += coefficient * amplitude;
362        }
363        Ok(numerator / reference)
364    }
365}
366
367fn complex_total_cmp(left: &Complex64, right: &Complex64) -> std::cmp::Ordering {
368    left.re
369        .total_cmp(&right.re)
370        .then_with(|| left.im.total_cmp(&right.im))
371}
372
373fn deterministic_complex_sum(values: &[Complex64]) -> Complex64 {
374    let mut sum = Complex64::new(0.0, 0.0);
375    let mut correction = Complex64::new(0.0, 0.0);
376    for value in values {
377        let next = sum + *value;
378        correction.re += if sum.re.abs() >= value.re.abs() {
379            (sum.re - next.re) + value.re
380        } else {
381            (value.re - next.re) + sum.re
382        };
383        correction.im += if sum.im.abs() >= value.im.abs() {
384            (sum.im - next.im) + value.im
385        } else {
386            (value.im - next.im) + sum.im
387        };
388        sum = next;
389    }
390    sum + correction
391}
392
393fn is_exact_zero(value: Complex64) -> bool {
394    value.re == 0.0 && value.im == 0.0
395}
396
397fn add_transition(
398    result: &mut Vec<(BasisState, Complex64)>,
399    state: BasisState,
400    coefficient: Complex64,
401) {
402    if let Some((_, existing)) = result.iter_mut().find(|(candidate, _)| *candidate == state) {
403        *existing += coefficient;
404    } else {
405        result.push((state, coefficient));
406    }
407}
408
409fn basis_key(state: &BasisState) -> Vec<u8> {
410    state.bits().iter().rev().map(|bit| bit.as_u8()).collect()
411}
412
413fn multiply_pauli(left: Pauli, right: Pauli) -> (Pauli, Complex64) {
414    let i = Complex64::new(0.0, 1.0);
415    match (left, right) {
416        (Pauli::I, value) | (value, Pauli::I) => (value, Complex64::new(1.0, 0.0)),
417        (Pauli::X, Pauli::X) | (Pauli::Y, Pauli::Y) | (Pauli::Z, Pauli::Z) => {
418            (Pauli::I, Complex64::new(1.0, 0.0))
419        }
420        (Pauli::X, Pauli::Y) => (Pauli::Z, i),
421        (Pauli::Y, Pauli::X) => (Pauli::Z, -i),
422        (Pauli::Y, Pauli::Z) => (Pauli::X, i),
423        (Pauli::Z, Pauli::Y) => (Pauli::X, -i),
424        (Pauli::Z, Pauli::X) => (Pauli::Y, i),
425        (Pauli::X, Pauli::Z) => (Pauli::Y, -i),
426    }
427}