cqlib-core 0.1.0-beta.4

The high-performance core foundation for the CQLib quantum computing ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// This code is part of Cqlib.
//
// (C) Copyright China Telecom Quantum Group 2026
//
// This code is licensed under the Apache License, Version 2.0. You may
// obtain a copy of this license in the LICENSE.txt file in the root directory
// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
//
// Any modifications or derivative works of this code must retain this
// copyright notice, and modified files need to carry a notice indicating
// that they have been altered from the originals.

//! Observable trait for computing expectation values.
//!
//! This module defines the [`Observable`] trait, which provides a unified interface
//! for computing expectation values of quantum observables across different quantum
//! state representations (statevectors and density matrices).
//!
//! # Supported Observables
//!
//! - [`Hamiltonian`]: A sum of Pauli strings with complex coefficients, commonly
//!   used to represent system energies and physical observables.
//! - [`PauliString`]: A single multi-qubit Pauli operator, useful for individual
//!   measurements and stabilizer formalism.
//!
//! # Expectation Value Formulas
//!
//! For a statevector $|\psi\rangle$:
//! $$\langle O \rangle = \langle\psi|O|\psi\rangle$$
//!
//! For a density matrix $\rho$:
//! $$\langle O \rangle = \text{Tr}(\rho O)$$
//!
//! # Examples
//!
//! ```rust
//! use cqlib_core::qis::{Statevector, Hamiltonian, PauliString, Observable};
//! use num_complex::Complex64;
//!
//! // Create a state
//! let mut sv = Statevector::new(2);
//! sv.apply_h(0);
//! sv.apply_cx(0, 1);
//!
//! // Create an observable H = ZZ
//! let ps: PauliString = "ZZ".parse().unwrap();
//! let h = Hamiltonian::from_pauli(ps);
//!
//! // Compute expectation value
//! let exp = h.expectation_statevector(&sv).unwrap();
//! // For Bell state, <ZZ> = 1.0
//! ```

use crate::qis::error::QisError;
use crate::qis::hamiltonian::Hamiltonian;
use crate::qis::pauli::{PauliString, Phase};
use crate::qis::state::{DensityMatrix, Statevector};
use num_complex::Complex64;
use rayon::prelude::*;
use std::collections::HashMap;

const VARIANCE_TOLERANCE: f64 = 1e-10;

/// Trait for quantum observables that can compute expectation values.
///
/// This trait is implemented by types representing quantum observables,
/// allowing them to compute expectation values across different quantum
/// state representations.
///
/// # Type Implementations
///
/// - [`Hamiltonian`]: Implements this trait for multi-term Hamiltonians
/// - [`PauliString`]: Implements this trait for single Pauli operators
///
/// # Errors
///
/// Methods may return [`QisError::QubitMismatch`] if the observable
/// and the quantum state have incompatible qubit counts.
/// Real expectation methods return [`QisError::NotHermitian`] for non-Hermitian
/// observables; Hamiltonian coefficients must also be finite.
pub trait Observable {
    /// Computes the expectation value for a statevector: $\langle\psi|O|\psi\rangle$.
    ///
    /// # Arguments
    ///
    /// * `sv` - The statevector representing the pure quantum state.
    ///
    /// # Returns
    ///
    /// The expectation value as a real number (`f64`), or an error if the
    /// qubit counts do not match.
    fn expectation_statevector(&self, sv: &Statevector) -> Result<f64, QisError>;

    /// Computes the expectation value for a density matrix: $\text{Tr}(\rho O)$.
    ///
    /// # Arguments
    ///
    /// * `dm` - The density matrix representing the quantum state.
    ///
    /// # Returns
    ///
    /// The expectation value as a real number (`f64`), or an error if the
    /// qubit counts do not match.
    fn expectation_density_matrix(&self, dm: &DensityMatrix) -> Result<f64, QisError>;

    /// Computes the expectation value from measurement probabilities.
    ///
    /// This method allows computing expectation values from classical
    /// measurement outcomes, useful for shot-based simulators and
    /// real quantum hardware results.
    ///
    /// # Arguments
    ///
    /// * `measurements` - A slice of tuples containing the measurement basis
    ///   (as a [`PauliString`]) and a map from state strings to their observed
    ///   probabilities.
    ///
    /// # Returns
    ///
    /// The expectation value as a real number (`f64`), or an error if no
    /// compatible measurement basis is found.
    fn expectation_probs(
        &self,
        measurements: &[(PauliString, HashMap<String, f64>)],
    ) -> Result<f64, QisError>;

    /// Returns the number of qubits this observable acts on.
    ///
    /// Used for dimension validation before computing expectation values.
    fn num_qubits(&self) -> usize;

    /// Computes the variance of this observable for a statevector.
    ///
    /// Var(O) = <O^2> - <O>^2.  Returns an error when the observable is not
    /// Hermitian, the qubit counts do not match, or a numerical issue arises.
    ///
    /// # Default Implementation
    ///
    /// Returns QisError::UnsupportedOperation. Observable types that support
    /// variance calculation must override this method.
    fn variance_statevector(&self, _sv: &Statevector) -> Result<f64, QisError> {
        Err(QisError::UnsupportedOperation(
            "variance_statevector not implemented for this observable type".into(),
        ))
    }
}

fn apply_pauli_string_to_statevector(
    pauli_str: &PauliString,
    sv: &Statevector,
    coeff: Complex64,
) -> Vec<Complex64> {
    let x_mask = pauli_str.x_mask();
    let z_mask = pauli_str.z_mask();
    let y_phase = pauli_str.y_phase();
    let global_phase = pauli_str.phase.to_complex();
    let base_factor = coeff * global_phase * y_phase;
    let sv_data = sv.data();

    (0..sv_data.len())
        .into_par_iter()
        .map(|j| {
            let source_j = j ^ x_mask;
            // P = phase * i^num_y * X^x * Z^z: Z acts on the source.
            let z_parity = (source_j & z_mask).count_ones();
            let sign = if z_parity % 2 == 1 { -1.0 } else { 1.0 };
            sv_data[source_j] * base_factor * sign
        })
        .collect()
}

fn finalize_variance(variance: f64) -> Result<f64, QisError> {
    if variance < -VARIANCE_TOLERANCE {
        // The current QisError model has no dedicated numerical error variant.
        return Err(QisError::InvalidParameterValue(format!(
            "variance computation produced a negative result beyond tolerance: {}",
            variance
        )));
    }

    if variance < 0.0 {
        Ok(0.0)
    } else {
        Ok(variance)
    }
}

// Validate the operator itself, including cancellations between repeated terms.
// Do not prune small coefficients while checking a real-valued API's contract.
fn ensure_hermitian_hamiltonian(h: &Hamiltonian) -> Result<(), QisError> {
    let finite = |c: &Complex64| c.re.is_finite() && c.im.is_finite();
    if h.terms.iter().any(|(_, c)| !finite(c)) {
        return Err(QisError::InvalidParameterValue(
            "observable coefficients must be finite".into(),
        ));
    }
    let mut merged = h.clone();
    merged.simplify_with_tolerance(0.0);
    for (_, coeff) in &merged.terms {
        if !finite(coeff) {
            return Err(QisError::InvalidParameterValue(
                "merged observable coefficients must be finite".into(),
            ));
        }
        if coeff.im.abs() > VARIANCE_TOLERANCE {
            return Err(QisError::NotHermitian);
        }
    }
    Ok(())
}

impl Observable for Hamiltonian {
    fn expectation_statevector(&self, sv: &Statevector) -> Result<f64, QisError> {
        if sv.num_qubits != self.num_qubits {
            return Err(QisError::QubitMismatch {
                expected: self.num_qubits,
                actual: sv.num_qubits,
            });
        }

        ensure_hermitian_hamiltonian(self)?;
        let mut expected_value = 0.0;

        // Iterate over each term in the Hamiltonian
        for (pauli_str, coeff) in &self.terms {
            let x_mask = pauli_str.x_mask();
            let z_mask = pauli_str.z_mask();

            // Calculate Y phase factor and combine with PauliString's global phase
            let y_phase = pauli_str.y_phase();
            let global_phase = pauli_str.phase.to_complex();
            let base_factor = global_phase * y_phase;

            // Compute term expectation value in parallel
            let sv_data = sv.data();
            let term_expectation: Complex64 = sv_data
                .par_iter()
                .enumerate()
                .map(|(j, amp)| {
                    // Output j receives the amplitude from source_j.
                    let source_j = j ^ x_mask;
                    let source_amp = sv_data[source_j];

                    // Z acts before X, so its phase depends on the source.
                    let z_parity = (source_j & z_mask).count_ones();
                    let sign = if z_parity % 2 == 1 { -1.0 } else { 1.0 };

                    let phase_factor = base_factor * sign;

                    // Contribution: conj(amp_j) * (P * psi)_j
                    amp.conj() * source_amp * phase_factor
                })
                .sum();

            // Hamiltonian is Hermitian, so expectation value is real
            expected_value += (term_expectation * coeff).re;
        }

        Ok(expected_value)
    }

    fn expectation_density_matrix(&self, dm: &DensityMatrix) -> Result<f64, QisError> {
        if dm.num_qubits != self.num_qubits {
            return Err(QisError::QubitMismatch {
                expected: self.num_qubits,
                actual: dm.num_qubits,
            });
        }

        ensure_hermitian_hamiltonian(self)?;
        let mut expected_value = 0.0;
        let n = self.num_qubits;
        let dim = 1 << n; // 2^n

        for (pauli_str, coeff) in &self.terms {
            let x_mask = pauli_str.x_mask();
            let z_mask = pauli_str.z_mask();

            // Calculate Y phase factor and combine with PauliString's global phase
            let y_phase = pauli_str.y_phase();
            let global_phase = pauli_str.phase.to_complex();
            let base_factor = global_phase * y_phase;

            // Parallel computation: Tr(ρ * P) = Σ_j ρ[j, j^x] * phase(j, P)
            let term_expectation: Complex64 = (0..dim)
                .into_par_iter()
                .map(|j| {
                    // X operator: flip bits where x_mask is 1 to get column index
                    let col = j ^ x_mask;

                    // Flat index: (row << n) | col
                    let flat_index = (j << n) | col;
                    let rho_elem = dm.data()[flat_index];

                    // Z operator: add phase (-1)^(number of overlapping Z bits)
                    let z_parity = (j & z_mask).count_ones();
                    let sign = if z_parity % 2 == 1 { -1.0 } else { 1.0 };

                    let phase_factor = base_factor * sign;

                    // Contribution to trace
                    rho_elem * phase_factor
                })
                .sum();

            // Hamiltonian is Hermitian, so expectation value is real
            expected_value += (term_expectation * coeff).re;
        }

        Ok(expected_value)
    }

    fn expectation_probs(
        &self,
        measurements: &[(PauliString, HashMap<String, f64>)],
    ) -> Result<f64, QisError> {
        ensure_hermitian_hamiltonian(self)?;
        let mut expected_value = 0.0;

        for (term_pauli, coeff) in &self.terms {
            let term_x_mask = term_pauli.x_mask();
            let term_z_mask = term_pauli.z_mask();
            let p_active = term_x_mask | term_z_mask;

            // Identity term contributes its coefficient * global_phase directly
            if p_active == 0 {
                let term_contrib = (term_pauli.phase.to_complex() * coeff).re;
                expected_value += term_contrib;
                continue;
            }

            // Find a compatible measurement basis.
            // A measurement M is compatible with P if P_i == M_i for all non-Identity P_i.
            let mut compatible_measurement = None;
            for (m_pauli, probs) in measurements {
                let m_x_mask = m_pauli.x_mask();
                let m_z_mask = m_pauli.z_mask();

                if (m_x_mask & p_active) == term_x_mask && (m_z_mask & p_active) == term_z_mask {
                    compatible_measurement = Some(probs);
                    break;
                }
            }

            if let Some(probs) = compatible_measurement {
                let mut exp_val = 0.0;

                for (state_str, prob) in probs {
                    if state_str.len() != self.num_qubits {
                        return Err(QisError::DimensionMismatch {
                            expected: self.num_qubits,
                            actual: state_str.len(),
                        });
                    }

                    let mut state_idx = 0usize;
                    for (i, c) in state_str.chars().rev().enumerate() {
                        match c {
                            '1' => state_idx |= 1 << i,
                            '0' => {}
                            _ => {
                                return Err(QisError::PauliStringParseError(
                                    crate::qis::error::PauliStringParseError::InvalidCharacter(c),
                                ));
                            }
                        }
                    }

                    let parity = (state_idx & p_active).count_ones();
                    let eigenvalue = if parity % 2 == 1 { -1.0 } else { 1.0 };
                    exp_val += prob * eigenvalue;
                }

                // Ignore y_phase, only apply global phase and coefficient
                let term_contrib = (exp_val * term_pauli.phase.to_complex() * coeff).re;
                expected_value += term_contrib;
            } else {
                return Err(QisError::UnsupportedOperation(format!(
                    "No compatible measurement basis found for term {}",
                    term_pauli
                )));
            }
        }

        Ok(expected_value)
    }

    fn num_qubits(&self) -> usize {
        self.num_qubits
    }

    fn variance_statevector(&self, sv: &Statevector) -> Result<f64, QisError> {
        if sv.num_qubits != self.num_qubits {
            return Err(QisError::QubitMismatch {
                expected: self.num_qubits,
                actual: sv.num_qubits,
            });
        }

        ensure_hermitian_hamiltonian(self)?;
        let mut simplified = self.clone();
        simplified.simplify_with_tolerance(0.0);

        for (_, coeff) in &mut simplified.terms {
            if coeff.im.abs() > VARIANCE_TOLERANCE {
                return Err(QisError::NotHermitian);
            }
            coeff.im = 0.0;
        }

        let expectation = simplified.expectation_statevector(sv)?;
        let mut applied = vec![Complex64::new(0.0, 0.0); sv.data().len()];
        for (pauli_str, coeff) in &simplified.terms {
            let term_state = apply_pauli_string_to_statevector(pauli_str, sv, *coeff);
            for (acc, term_amp) in applied.iter_mut().zip(term_state) {
                *acc += term_amp;
            }
        }

        let second_moment: f64 = applied.iter().map(|amp| amp.norm_sqr()).sum();
        finalize_variance(second_moment - expectation * expectation)
    }
}

impl Observable for PauliString {
    fn expectation_statevector(&self, sv: &Statevector) -> Result<f64, QisError> {
        if sv.num_qubits != self.num_qubits {
            return Err(QisError::QubitMismatch {
                expected: self.num_qubits,
                actual: sv.num_qubits,
            });
        }

        self.ensure_hermitian()?;
        let x_mask = self.x_mask();
        let z_mask = self.z_mask();
        let y_phase = self.y_phase();
        let global_phase = self.phase.to_complex();
        let base_factor = global_phase * y_phase;

        let sv_data = sv.data();
        let term_expectation: Complex64 = sv_data
            .par_iter()
            .enumerate()
            .map(|(j, amp)| {
                let source_j = j ^ x_mask;
                let source_amp = sv_data[source_j];
                // Z acts on the source before X moves it to output j.
                let z_parity = (source_j & z_mask).count_ones();
                let sign = if z_parity % 2 == 1 { -1.0 } else { 1.0 };
                let phase_factor = base_factor * sign;
                amp.conj() * source_amp * phase_factor
            })
            .sum();

        Ok(term_expectation.re)
    }

    fn expectation_density_matrix(&self, dm: &DensityMatrix) -> Result<f64, QisError> {
        if dm.num_qubits != self.num_qubits {
            return Err(QisError::QubitMismatch {
                expected: self.num_qubits,
                actual: dm.num_qubits,
            });
        }

        self.ensure_hermitian()?;
        let n = self.num_qubits;
        let dim = 1 << n;
        let x_mask = self.x_mask();
        let z_mask = self.z_mask();
        let y_phase = self.y_phase();
        let global_phase = self.phase.to_complex();
        let base_factor = global_phase * y_phase;

        let term_expectation: Complex64 = (0..dim)
            .into_par_iter()
            .map(|j| {
                let col = j ^ x_mask;
                let flat_index = (j << n) | col;
                let rho_elem = dm.data()[flat_index];
                let z_parity = (j & z_mask).count_ones();
                let sign = if z_parity % 2 == 1 { -1.0 } else { 1.0 };
                let phase_factor = base_factor * sign;
                rho_elem * phase_factor
            })
            .sum();

        Ok(term_expectation.re)
    }

    fn expectation_probs(
        &self,
        measurements: &[(PauliString, HashMap<String, f64>)],
    ) -> Result<f64, QisError> {
        self.ensure_hermitian()?;
        let term_x_mask = self.x_mask();
        let term_z_mask = self.z_mask();
        let p_active = term_x_mask | term_z_mask;

        if p_active == 0 {
            return Ok(self.phase.to_complex().re);
        }

        let mut compatible_measurement = None;
        for (m_pauli, probs) in measurements {
            let m_x_mask = m_pauli.x_mask();
            let m_z_mask = m_pauli.z_mask();

            if (m_x_mask & p_active) == term_x_mask && (m_z_mask & p_active) == term_z_mask {
                compatible_measurement = Some(probs);
                break;
            }
        }

        if let Some(probs) = compatible_measurement {
            let mut exp_val = 0.0;

            for (state_str, prob) in probs {
                if state_str.len() != self.num_qubits {
                    return Err(QisError::QubitMismatch {
                        expected: self.num_qubits,
                        actual: state_str.len(),
                    });
                }

                let mut state_idx = 0usize;
                for (i, c) in state_str.chars().rev().enumerate() {
                    match c {
                        '1' => state_idx |= 1 << i,
                        '0' => {}
                        _ => {
                            return Err(QisError::UnsupportedOperation(format!(
                                "Invalid character '{}' in state string",
                                c
                            )));
                        }
                    }
                }

                let parity = (state_idx & p_active).count_ones();
                let eigenvalue = if parity % 2 == 1 { -1.0 } else { 1.0 };
                exp_val += prob * eigenvalue;
            }

            Ok((exp_val * self.phase.to_complex()).re)
        } else {
            Err(QisError::UnsupportedOperation(format!(
                "No compatible measurement basis found for term {}",
                self
            )))
        }
    }

    fn num_qubits(&self) -> usize {
        self.num_qubits
    }

    fn variance_statevector(&self, sv: &Statevector) -> Result<f64, QisError> {
        if sv.num_qubits != self.num_qubits {
            return Err(QisError::QubitMismatch {
                expected: self.num_qubits,
                actual: sv.num_qubits,
            });
        }

        match self.phase {
            Phase::Plus | Phase::Minus => {}
            Phase::I | Phase::MinusI => return Err(QisError::NotHermitian),
        }

        let expectation = self.expectation_statevector(sv)?;
        let second_moment: f64 =
            apply_pauli_string_to_statevector(self, sv, Complex64::new(1.0, 0.0))
                .iter()
                .map(|amp| amp.norm_sqr())
                .sum();
        finalize_variance(second_moment - expectation * expectation)
    }
}

#[cfg(test)]
#[path = "./observable_test.rs"]
mod observable_test;