Source code for hqs_qorrelator_app.experimental_nmr_helpers

# Copyright © 2021-2025 HQS Quantum Simulations GmbH. All Rights Reserved.
"""Experimental NMR helpers to run on simulators and hardware."""

import numpy as np
import re
import warnings

from struqture_py.spins import PauliHamiltonian  # type: ignore
from qiskit.quantum_info.operators import SparsePauliOp
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.circuit.library import PauliEvolutionGate
from qiskit.synthesis import LieTrotter
from qiskit.primitives import BackendEstimatorV2, StatevectorEstimator, PrimitiveJob
from typing import Tuple, Any, List, Generator
from itertools import combinations

from hqs_qorrelator_app.causal_fft import fft_causal


def _struqture_hamiltonian_to_qiskit_op(
    ham_struqture: PauliHamiltonian,
    n_qubits: int,
    reverse_qubit_order: bool = True,
) -> SparsePauliOp:
    """Convert struqture PauliHamiltonian keys like '0Z', '10X11X' into Qiskit labels.

    Args:
        ham_struqture (PauliHamiltonian): struqture Hamiltonian to transform to Qiskit
        n_qubits (int): number of qubits in the Hamiltonian
        reverse_qubit_order (bool): makes Qiskit's rightmost char qubit 0 (little-endian).
    """
    labels = []
    coeffs = []
    token_re = re.compile(r"(\d+)([XYZ])")

    for key, val in zip(ham_struqture.keys(), ham_struqture.values(), strict=False):
        s = str(key)  # e.g., '0Z', '0X1X', '10X11X'
        pauli = ["I"] * n_qubits
        if s != "I":
            for m in token_re.finditer(s):
                idx = int(m.group(1))  # site index (can be multi-digit)
                op = m.group(2)  # 'X', 'Y', or 'Z'
                q = (n_qubits - 1 - idx) if reverse_qubit_order else idx
                if not (0 <= q < n_qubits):
                    raise IndexError(
                        f"Site index {idx} (mapped to qubit {q}) out of range 0..{n_qubits - 1}"
                    )
                pauli[q] = op
        labels.append("".join(pauli))
        coeffs.append(complex(val))

    return SparsePauliOp(labels, coeffs)


def _xsum_eigenstate_template(n_qubits: int) -> tuple[QuantumCircuit, ParameterVector]:
    """Parameterized prep for any eigenstate of sum_i X_i.

    Set phi[i]=0 for |+>, phi[i]=pi for |-> on qubit i.
    """
    phi = ParameterVector("phi", n_qubits)
    qc = QuantumCircuit(n_qubits, name="XsumEigen")
    for q in range(n_qubits):
        qc.ry(np.pi / 2, q)
        qc.rz(phi[q], q)
    return qc, phi


def _magnetization_sign(bits: list[int]) -> int:
    """Using Pauli-sigma convention for obs_x: each qubit contributes +1 (|+>) or -1 (|->)."""
    return sum(1 if b == 0 else -1 for b in bits)


def _positive_magnetization_bitstrings(n: int) -> Generator[tuple[int, ...], None, None]:
    """Generate only positive-magnetization bitstrings.

    Yield all X-basis product states with strictly positive total sigma_x magnetization.
    - For odd n: exactly half of all bitstrings (2^(n-1)).
    - For even n: excludes the m=0 layer (k = n/2 ones), which has zero weight anyway.
    """
    max_ones = (n - 1) // 2  # <= floor((n-1)/2)
    for k in range(0, max_ones + 1):  # number of |-> entries ("1"s)
        for ones in combinations(range(n), k):
            bits = [0] * n
            for j in ones:
                bits[j] = 1
            yield tuple(bits)


[docs] def hamiltonian_to_trotter_circuits( hamiltonian: PauliHamiltonian, number_of_trottersteps: int = 100, trotter_timestep: float = 0.01, ) -> Tuple[List[QuantumCircuit], ParameterVector]: """Create Trotter circuit for a given struqture Hamiltonian. Args: hamiltonian (PauliHamiltonian): Hamiltonian to create Trotter circuits for number_of_trottersteps (int): Number of Trotter steps to apply trotter_timestep (float): Time step for the Trotter steps Returns: List[QuantumCircuit]: A list of Trotter circuits for the given Hamiltonian """ number_spins = hamiltonian.current_number_spins() hamiltonian_qiskit = _struqture_hamiltonian_to_qiskit_op(hamiltonian, number_spins) trotter_step_first_order = PauliEvolutionGate( hamiltonian_qiskit, trotter_timestep, synthesis=LieTrotter() ) circuit = QuantumCircuit(hamiltonian_qiskit.num_qubits) circuit.append(trotter_step_first_order, range(hamiltonian_qiskit.num_qubits)) circuit = circuit.decompose(reps=1) qc_init_template, phi = _xsum_eigenstate_template(number_spins) circuits_per_step = [] c = QuantumCircuit(number_spins) c = c.compose(qc_init_template) circuits_per_step.append(c) for _ in range(1, number_of_trottersteps): c = c.compose(circuit) circuits_per_step.append(c) return circuits_per_step, phi
[docs] def run_trotter_circuits( circuits: List[QuantumCircuit], phi: ParameterVector, backend: Any = None, ) -> Tuple[np.ndarray, Any]: """Run Trotter circuits with estimator and return expectation values. A qiskit EstimatorBackendV2 is used here. The argument backend should be an instance of qiskit BackendV2 or a qoqo_for_braket BraketBackend or None. If backend is None, a StatevectorEstimator will be used. If backend is an instance of BraketBackend, the AWS device and session will be extracted and used to create a BraketAwsBackend. Otherwise, the provided backend will be used. Args: circuits (List[QuantumCircuit]): List of Trotter circuits phi (ParameterVector): Parameter vector for the X-sum eigenstate template backend (Backend): backend to run the circuits on. Please note that the number of shots is converted to a precision, where precision = 1 / sqrt(number_shots). Returns: Tuple[np.ndarray, np.ndarray]: A tuple containing the X and Y expectation values for the given circuits and parameters """ number_spins = circuits[0].num_qubits bits_list = list(_positive_magnetization_bitstrings(number_spins)) param_maps = [] for bits in bits_list: vals = [np.pi if b else 0.0 for b in bits] # 0->|+>, pi->|-> bind = {phi[i]: vals[i] for i in range(number_spins)} param_maps.append(bind) obs_x = SparsePauliOp.from_sparse_list( [("X", [i], 1.0) for i in range(number_spins)], num_qubits=number_spins ) obs_y = SparsePauliOp.from_sparse_list( [("Y", [i], 1.0) for i in range(number_spins)], num_qubits=number_spins ) precision: float | None = None if backend is None: estimator = StatevectorEstimator() else: try: from qoqo_for_braket import BraketBackend # noqa: PLC0415 from qiskit_braket_provider.providers import ( # noqa: PLC0415 BraketAwsBackend, BraketLocalBackend, ) if isinstance(backend, BraketBackend): precision = 1 / np.sqrt(backend.max_shots) if backend.device in ["braket_sv", "braket_dm", "braket_ahs"]: backend = BraketLocalBackend(backend.device) else: from braket.aws import AwsDevice # noqa: PLC0415 device = AwsDevice(backend.device, aws_session=backend.aws_session) backend = BraketAwsBackend(device=device) else: estimator = BackendEstimatorV2(backend=backend) except ImportError: print( "Can't find the Braket packages. If you are using a BraketBackend, please ensure " + "you have both qoqo-for-braket and qiskit-braket-provider installed. If you are" + " not using a BraketBackend, disregard this message." ) estimator = BackendEstimatorV2(backend=backend) number_of_initializations = len(bits_list) number_of_trottersteps = len(circuits) exp_x = np.zeros((number_of_initializations, number_of_trottersteps)) exp_y = np.zeros((number_of_initializations, number_of_trottersteps)) for k, circ in enumerate(circuits): pubs = [] for m in range(number_of_initializations): pubs.append((circ, [obs_x, obs_y], param_maps[m])) # pass parameter_values per pub job = estimator.run(pubs, precision=precision) results = _retry_failed_jobs(estimator, job, pubs, precision) for m, res in enumerate(results): try: evs = res.data.evs # [⟨obs_x⟩, ⟨obs_y⟩] exp_x[m, k] = evs[0] exp_y[m, k] = evs[1] except AttributeError: warnings.warn( f"Run number {m} was unsuccessful: its expectation value has been set to 0.", stacklevel=1, ) return exp_x, exp_y
[docs] def correlators_to_spectrum( m_avg_x: list[float], m_avg_y: list[float], n_max: int, trotter_timestep: float, b_field: float, chem_shift_hz: float, noise_strength: float, gyromagnetic_ratio: float = 267522128.0, ) -> tuple[Any, Any]: """Calculate the full spectrum from the computed correlators, and the corresponding ppm array. Note: The correlators are computed via a Fourier Transform. Please note that this experimental function defines the external magnetic field to be in the z-direction, meaning that the full spectrum is represented by x.real + y.imag. If you have defined the external magnetic field to be in the x-direction, this function will not work, as you will need to use x.real - y.imag. Args: m_avg_x: The first correlator, e.g. the ZZ correlator if the field is in the x-direction. m_avg_y: The second correlator, e.g. the YZ correlator if the field is in the x-direction. n_max: The total number of data points, which is greater than or equal to the number of trotter steps. trotter_timestep: The trotter timestep. b_field: strength of the constant magnetic field in the z-direction in Tesla. chem_shift_hz: The chemical shift of the input Hamiltonian. noise_strength: strength of the noise (gamma) used to decay the correlators. gyromagnetic_ratio: The gyromagnetic ratio of the isotope in rad/(s*T). If None is specified, will default to the one for 1H (267522128.0) Returns: spectrum_full: The calculated spectrum. ppm: The ppm array to plot the full spectrum against. """ time = np.linspace(0, n_max * trotter_timestep, n_max) gamma = noise_strength yt_x = m_avg_x * np.exp((-gamma / (1.0)) * time) yt_y = m_avg_y * np.exp((-gamma / (1.0)) * time) yf_x = fft_causal(yt_x) yf_y = fft_causal(yt_y) times = np.array(time) xf = np.fft.fftshift(np.fft.fftfreq(times.shape[-1], d=(times[1] - times[0]))) frequencies = xf spectrum_full = yf_x.real + yf_y.imag # And now we have the frequency axis in ppm: # we need to shift the frequencies by twice the chemical input shift and then by the reference # energy, i.e. the energy of the homoisotope (H) times the magnetic field. reference_energy = gyromagnetic_ratio * b_field / (2 * np.pi) hz_to_ppm_conversion = 2.0 * np.pi / (gyromagnetic_ratio * b_field) * 1e6 # Have confirmed the `- reference_energy` term is correct: ppm = (frequencies - 2 * chem_shift_hz - reference_energy) * hz_to_ppm_conversion spectrum_full /= np.max(spectrum_full) return spectrum_full, ppm
def _retry_failed_jobs( estimator: Any, job: PrimitiveJob, pubs: list[Any], precision: float | None, max_retries: int = 3, ) -> list[Any]: """Iterate over jobs and re-run any failed ones up to three times, fetching the result. Args: estimator (Any): the estimator on which the jobs have run. job (PrimitiveJob): the job which ran, with information about which circuits succeeded. pubs (list[Any]): the list of PUBs which have run. precision (float): the precision to pass to the estimator run. max_retries (int): the number of times to retry a failed job. Returns: list[Any]: list of results from the jobs. """ results = [None] * len(pubs) pending = list(range(len(pubs))) retries = 0 while pending: try: batch = list(job.result()) failed = [] for i, res in zip(pending, batch, strict=False): try: valid = len(res.data.evs) >= 2 except (AttributeError, TypeError): valid = False if valid: results[i] = res else: failed.append(i) pending = failed except Exception as e: # Complete job failure: keep the entire current batch pending. print(f"Whole job failed, retrying whole job: {e}") if not pending or retries >= max_retries: break # Retry submission failures without losing previously collected results. while retries < max_retries: retries += 1 try: job = estimator.run( [pubs[i] for i in pending], precision=precision, ) break except Exception: if retries == max_retries: print("All retries attempted, there ") return results return results