Skip to content

QPE

Use Eigenproblem(A=...) with QCELS(initial_state=...) or with SPE, RFE or RWPE, which take initial_state too. A SpectralEstimation instead supplies its own Hamiltonian or unitary and state. Each method estimates an eigenvalue or eigenphase from the Hadamard-test signals z_p = <psi|U^p|psi> of the prepared state psi, with U = exp(-i*tau*H) for a Hamiltonian H. Each estimate concerns the eigenvalues present in the prepared state and does not identify the ground state.

from nwqlib import Eigenproblem, SpectralEstimation, solve
from nwqlib.algorithms import QCELS, RFE, RWPE, SPE
from nwqlib.algorithms import QPEAnalysis, QPEVerification
Method Paper Estimate result.interval
QCELS Ding and Lin, arXiv:2211.11973v2 Single-mode complex least-squares fit None
SPE Wan, Berta and Campbell, arXiv:2110.12071v2 First crossing of a Fourier-filtered CDF, the lowest value in the prepared spectrum None
RFE Kshirsagar, Katabarwa and Johnson, arXiv:2209.11322v3 Largest sampled Fourier coefficient None
RWPE Granade and Wiebe, arXiv:2208.04526v1 Mean of a Gaussian random walk, one bit per step Nominal 95-percent Gaussian model interval

The QPE guide explains the meaning and units of the result, the choice of estimator and the cost of each.

Estimators

QCELS

QCELS method for an eigenvalue or eigenphase, by a single-mode complex least-squares fit.

Build it with keyword arguments and pass it as method=, for example solve(Eigenproblem(A=H), method=QCELS(initial_state=psi)). An Eigenproblem needs initial_state, and a SpectralEstimation supplies its own state. The other arguments are optional, and the shared settings apply too. The result is a QPEAnalysis whose value comes from the single mode a*exp(-i*p*theta), with theta = E*tau, that best fits the signals z_p = <psi|U^p|psi> of a schedule of integer powers p.

The fit minimizes the QCELS objective of Ding and Lin, arXiv:2211.11973v2, Eq. (2). Their accuracy theorems, Theorems 1 and 2 (p. 14), assume p0 > 0.71 for the squared overlap p0 = |<psi|psi_0>|**2 of the prepared state psi with the target eigenvector psi_0, and NWQLib does not check p0. Smaller overlaps need the Fourier-filtered variant of their Sec. IV (p. 15). Neither that variant nor the multi-level schedule of their Algorithm 1 (p. 13) is implemented. The finite grid search and bracket refinement have no global-optimum or uncertainty guarantee, and interval is None. result.analyze(grid_size=...) fits the same signals on another grid. The QPE guide describes the search and its aliasing limits.

Attributes:

  • num_times (PositiveInt) –

    Default 16. Upper bound on the number of positive sampling times. The zero-power quadratures are added separately. For maximum power P (set by max_time), num_times >= P gives the consecutive powers 0 through P, the form of the data set of Ding and Lin, arXiv:2211.11973v2, Eq. (6). Otherwise power 0 is kept and num_times integer powers are spread over 1 through P, a schedule their Theorems 1 and 2 do not describe and whose fit can land on a replica of the energy (QPE guide).

  • max_time (Real | None) –

    Default None, which selects maximum integer power 10, independent of units. Otherwise the positive maximum physical sampling time, which selects maximum power floor(max_time/tau), or floor(max_time) for a unitary.

  • grid_size (PositiveInt) –

    Default 4096, at least 8. Requested minimum number of phase-grid points. The effective grid is max(grid_size, 8*(max(p) - min(p)) + 1), so it also resolves the span of powers.

Examples:

H = diag(-0.5, 0.5) has eigenvalue -0.5 for the eigenvector |0>:

>>> from nwqlib import Eigenproblem, solve
>>> from nwqlib.algorithms import QCELS
>>> problem = Eigenproblem(A=[[-0.5, 0], [0, 0.5]])
>>> result = solve(problem, method=QCELS(initial_state=[1, 0]), seed=7)
>>> print(round(result.eigenvalue, 10))
-0.5

SPE

SPE method for the lowest eigenvalue or eigenphase in the spectrum of the prepared state.

Build it with keyword arguments and pass it as method=, for example solve(Eigenproblem(A=H), method=SPE(initial_state=psi, overlap_lower_bound=0.5)). overlap_lower_bound is required, and an Eigenproblem also needs initial_state. The other arguments are optional, and the shared settings apply too. The result is a QPEAnalysis whose value is the lowest value in the prepared spectral support. For a Hamiltonian that is the lowest energy. For a unitary it is the lowest principal eigenphase angle theta, with U v = exp(i*theta) v and theta scanned on [-pi/2, pi/2). When tau*|E| < pi/2 for every prepared energy E of U = exp(-i*tau*H), theta = -tau*E, so on such a unitary SPE returns the phase of the highest energy of the prepared support. Supplying H, or U^dagger = exp(i*tau*H), targets the lowest energy instead.

Statistical phase estimation locates the first crossing of eta/2 by a Fourier-filtered approximate cumulative distribution function (CDF) of the prepared state's spectrum, scanned on a finite grid. The filter and the eta/2 threshold come from Wan, Berta and Campbell, arXiv:2110.12071v2, PDF Eqs. (A1)-(A2) (HTML Eqs. (16)-(17)) and Algorithm 1. Positive odd frequencies are drawn by their PDF Eq. (A2) Fourier weights, numbered Eq. (17) in the HTML version. Both quadratures of the controlled evolution are measured for each draw, and conjugation supplies the negative-frequency contribution. Repeated draws of one frequency share one setting per quadrature, which with counts receives shots times the number of draws in fresh shots. The finite filter and sample defaults do not enforce the paper's precision theorem. A scan over grid_size thresholds replaces its O(log(1/delta)) binary-search decisions, and the sample count is not derived from its Eq. (11), so its Theorem 1 does not apply. The chosen controlled-evolution construction sets its own approximation, independently of the paper's randomized compiler. interval is None, and result.analyze(grid_size=...) scans the same signals on another grid. The QPE guide lists each departure from the paper.

Attributes:

  • overlap_lower_bound (Real) –

    Required, in (0, 1]. Caller-declared lower bound eta on the probability of the target component in the prepared state. NWQLib does not verify it.

  • num_samples (PositiveInt) –

    Default 32. Independent positive-frequency draws, each with two quadratures.

  • fourier_degree (PositiveInt) –

    Default 11. Filter parameter d, with maximum frequency 2*d + 1.

  • filter_beta (Real) –

    Default 6.0, positive. Error-function smoothing parameter beta.

  • grid_size (PositiveInt) –

    Default 4096, at least 8. Number of threshold points of the approximate CDF in [-pi/2, pi/2).

Examples:

H = diag(-0.5, 0.5) has eigenvalue -0.5 for the eigenvector |0>. SPE returns the first threshold crossing on its finite grid, from 32 random frequency draws:

>>> from nwqlib import Eigenproblem, solve
>>> from nwqlib.algorithms import SPE
>>> problem = Eigenproblem(A=[[-0.5, 0], [0, 0.5]])
>>> method = SPE(initial_state=[1, 0], overlap_lower_bound=1.0)
>>> result = solve(problem, method=method, seed=7)
>>> print(round(result.eigenvalue, 6))
-0.499674

RFE

RFE method for an eigenvalue or eigenphase, from the largest sampled Fourier coefficient.

Build it with keyword arguments and pass it as method=, for example solve(Eigenproblem(A=H), method=RFE(initial_state=psi)). An Eigenproblem needs initial_state. The other arguments are optional, and the shared settings apply too. The result is a QPEAnalysis whose phase is 2*pi*j/K for the frequency j of the largest of the K sampled Fourier coefficients, on the principal branch, and whose energy is -phase/tau.

In randomized Fourier estimation, each of M independent draws picks a uniform integer power in [0, K) and measures the real and imaginary Hadamard tests of Kshirsagar, Katabarwa and Johnson, arXiv:2209.11322v3 (Eqs. (1)-(6), p. 4). Algorithm 1 and Eq. (7), p. 5, define the sampled Fourier coefficients. The default exact readout reads the same quadratures as the ancilla X and Y expectations at each power of one controlled trajectory, and sampled readout keeps the paired tests. Repeated draws of one power share one setting per quadrature, which with counts receives shots times the number of draws in fresh shots. The precision theorem, Theorem 2.1 (p. 6), assumes an eigenstate and enough draws, and the default M is far below the count it requires. interval is None. Changing K needs a new Plan. The QPE guide gives the sign convention and the sample bound.

Attributes:

  • num_samples (PositiveInt) –

    Default 97. Number M of independent power draws, each with two quadratures.

  • num_frequencies (PositiveInt) –

    Default 49, at least 2. Fourier size K, one greater than the largest sampled power.

Examples:

H = diag(-0.5, 0.5) has eigenvalue -0.5 for the eigenvector |0>. RFE returns a phase on the grid 2*pi*j/49:

>>> from nwqlib import Eigenproblem, solve
>>> from nwqlib.algorithms import RFE
>>> problem = Eigenproblem(A=[[-0.5, 0], [0, 0.5]])
>>> result = solve(problem, method=RFE(initial_state=[1, 0]), seed=7)
>>> print(round(result.eigenvalue, 6))
-0.498866

RWPE

RWPE method for an eigenvalue, by a Gaussian random walk with one measured bit per step.

Build it with keyword arguments and pass it as method=, for example solve(Eigenproblem(A=H), method=RWPE(initial_state=psi)). An Eigenproblem needs initial_state. The other arguments are optional, and the shared settings apply too. The result is a QPEAnalysis whose energy is -mean/tau for the posterior mean of the phase phi = -tau*E, with the nominal 95-percent interval of the Gaussian model in interval and the posterior moments in gaussian. The input must be a Hamiltonian, because the method needs continuous evolution times, which the integer powers of a bare unitary do not supply. It uses exactly one shot per step. Because each feedback angle depends on the outcomes before it, prepare(plan, settings="all") is refused, and prepare(plan) prepares the next query.

The random-walk phase estimation update is the basic walk of Granade and Wiebe, arXiv:2208.04526v1, Eq. (7) and Algorithm 1: one bit at time 1/sigma, a mean shift of +/-sigma/sqrt(e) and a width shrink by sqrt((e-1)/e). The likelihood is Eq. (2) of Granade and Wiebe, arXiv:2208.04526v1 (p. 2). The feedback sign follows that likelihood and the positive outcome-zero update in Eq. (7a), correcting the opposite sign printed in Algorithm 1. The consistency checks and unwinding of their Algorithm 2 are not implemented. The Gaussian interval is a model output, not a coverage guarantee. The QPE guide describes the finite range that the walk can explore.

Attributes:

  • max_steps (Count) –

    Default 14, nonnegative. Largest number of feedback steps, which a run uses exactly unless it is cancelled or fails. Zero returns the prior without measurement.

  • prior_mean (Real) –

    Default 0.0. Prior mean of the unwrapped phase -tau*E, in radians.

  • prior_std (Real) –

    Default pi, positive. Prior standard deviation of the phase, in radians.

Examples:

H = diag(-0.5, 0.5) has eigenvalue -0.5 for the eigenvector |0>. After 14 one-bit updates the estimate and its nominal 95-percent interval are:

>>> from nwqlib import Eigenproblem, solve
>>> from nwqlib.algorithms import RWPE
>>> problem = Eigenproblem(A=[[-0.5, 0], [0, 0.5]])
>>> result = solve(problem, method=RWPE(initial_state=[1, 0]), seed=7)
>>> low, high = result.interval.low, result.interval.high
>>> print(round(result.eigenvalue, 4), round(low, 4), round(high, 4))
-0.4784 -0.5223 -0.4345

Settings shared by the four estimators

Settings that QCELS, SPE, RFE and RWPE all accept, with the same defaults.

Each estimator observes the signal z_p = <psi|U^p|psi> through one ancilla qubit, with U = exp(-i*tau*H) for a Hamiltonian H, or the polar factor of a supplied unitary. An Eigenproblem takes its prepared state from initial_state, and a SpectralEstimation supplies its own. A peak, fit or credible interval does not establish the requested ground state or accuracy on a mixed spectrum.

Attributes:

  • initial_state (StateData | None) –

    Default None. Reference state |psi>, required for an Eigenproblem. A SpectralEstimation supplies its own state, and this must then be None.

  • tau (Real | None) –

    Default None, which chooses 0.9*phase_radius/R from a spectral-radius bound R, the dense row-sum bound or the L1 norm of the Pauli coefficients with the identity included. The phase radius is pi, and smaller for SPE, as the QPE guide explains. Positive time step of U = exp(-i*tau*H), in inverse operator units. Unitary input takes None.

  • controlled_power_backend (Literal['auto', 'dense_exact', 'trotter_error_budgeted']) –

    Default "auto", which picks "trotter_error_budgeted" for Pauli input and "dense_exact" otherwise. Construction of the controlled powers U^p: "dense_exact", the exact power of explicit dense input, or "trotter_error_budgeted", a second-order product formula, which needs a Hamiltonian.

  • controlled_power_error_budget (Real) –

    Default 1e-3, positive. Operator-norm allowance for each power, covering Pauli pruning plus product-formula error. It does not bound the estimator error.

  • pauli_pruning_rtol (Nonnegative) –

    Default 1e-12, nonnegative. Non-identity Pauli terms with abs(c) <= pauli_pruning_rtol*max abs(c) are dropped, and their L1 mass is counted against each power's error allowance.

  • max_bytes (PositiveInt) –

    Default 10 GB (decimal, 10_000_000_000 bytes). Limit on the known bytes of input and analysis arrays.

  • max_work (PositiveInt) –

    Default 1_000_000_000. Limit on the counted work of the likelihood, the grid and the evolution choice.

  • max_power (PositiveInt) –

    Default 100_000. Largest absolute evolution time in units of tau, including the non-integer times of RWPE.

  • max_trotter_steps (PositiveInt) –

    Default 1_000_000. Largest number of product-formula steps per controlled power.

Read the result

QPEAnalysis

Bases: Result

Eigenvalue or eigenphase estimate from a QPE method, with the samples behind it.

solve returns it for QCELS, SPE, RFE and RWPE, and load_result reopens a saved one. The answer is value: the eigenvalue in the operator's unit for an Eigenvalue output, or the eigenphase in turns, in [0, 1), for an Eigenphase output. The phase is defined by U v = exp(2*pi*i*phase) v, and for a Hamiltonian U = exp(-i*tau*H), so the eigenvalue includes the minus sign of that conversion. estimator_value is None, and complete is False, when no estimate was identified. Only RWPE reports an interval, the nominal 95-percent interval of its Gaussian model. The estimate concerns the eigenvalues present in the prepared state and does not identify the ground state. print(result) shows the estimate with these limits, and result.analyze(grid_size=...) reanalyzes QCELS or SPE from the same samples. The fields below are read-only. The fields of Result are present too. Its construction and uncertainty refer to the original Plan, and the preparation records of the contributing observations record the points actually run.

Attributes:

  • estimator (Literal['qcels', 'spe', 'rfe', 'rwpe']) –

    "qcels", "spe", "rfe" or "rwpe".

  • estimator_value (Real | None) –

    Estimator output: energy in operator units for a Hamiltonian, or principal eigenphase in radians for a unitary. None when no estimate was identified.

  • phase_turns (Real | None) –

    Eigenphase of U in turns, in [0, 1).

  • interval (QPEInterval | None) –

    Nominal model interval, RWPE only.

  • samples (tuple[QPESample, ...]) –

    Reduced ancilla means, one per measured value.

  • missing (tuple[Text, ...]) –

    Names of planned queries without data.

  • complete (StrictBool) –

    True when all planned data are present and an estimate exists. For RWPE, every planned step has been processed.

  • gaussian (RWPEGaussian | None) –

    RWPE posterior moments, None for the other estimators.

  • processed_steps (Count) –

    RWPE updates applied.

  • controller_work (Count) –

    RWPE work units counted against max_work.

  • stop_reason (Text | None) –

    Why the measurement stopped, why no estimate is identified, or, for QCELS, that the fit is aliased.

  • analysis_settings (tuple[Binding, ...]) –

    Reanalysis settings, such as a changed grid_size.

  • fit (QCELSFit | None) –

    QCELS search record, None for the other estimators.

  • exposure (tuple[QPEExposure, ...]) –

    Requested and received shots of every SPE or RFE query measured with counts, empty otherwise.

  • requested_exposure_complete (StrictBool | None) –

    Whether every count query returned its requested shots, computed from all queries and separate from complete. None without count-mode Fourier queries.

  • minimum_effective_shots_per_draw (tuple[PositiveInt, PositiveInt] | None) –

    The exact rational min_q n_q/m_q of received shots n_q over draw multiplicity m_q, as (numerator, denominator), an effective number of shots per draw rather than a fractional physical shot count. None without count queries.

  • rfe_coordinate_variance_upper (Nonnegative | None) –

    The exact received-count proxy A = sum_u (m_u/M)**2 max(1/n_uR, 1/n_uI), rounded up to binary64, an upper bound on each real and imaginary coordinate proxy of the sampled Fourier coefficients in units of squared ancilla expectation. For SPE, 4*S**2*A bounds the CDF proxy with its weight sum S. It concerns the conditional shot contribution under independent stationary shots, not the random-draw term, and gives no energy confidence interval.

value

value

The answer: phase for an Eigenphase output, otherwise eigenvalue.

eigenvalue

eigenvalue

Energy estimate estimator_value in the operator's unit.

Raises:

  • AttributeError –

    For unitary-only input, which has no Hamiltonian eigenvalue.

phase

phase

Eigenphase of U in turns, in [0, 1), the same as phase_turns.

QPESample

Bases: Record

One measured ancilla mean with the power, phase and observations it came from.

mean is the ancilla <Z> in [-1, 1]. For counts it equals (zeros - ones)/(zeros + ones). raw_mean keeps an exact non-count mean whose magnitude exceeded one within its roundoff window, and mean is then the corresponding endpoint. The guide section Read the result states this convention.

Attributes:

  • experiment (Text) –

    Query name.

  • power (StrictInt | Real) –

    Power p, or RWPE relative time, of that query.

  • phase_shift (Real | None) –

    Ancilla phase in radians actually applied, the bound feedback for RWPE, or the logical quadrature that the classical host kernel evaluated. None for a trajectory point, which reads its quadrature from the ancilla X or Y expectation without an executed phase.

  • mean (Real) –

    Re(exp(i*s)*z_p) as measured, in [-1, 1].

  • raw_mean (Real | None) –

    Original exact mean when it lay just outside [-1, 1].

  • zeros (Count | None) –

    Returned shots with outcome 0, None for exact readout.

  • ones (Count | None) –

    Returned shots with outcome 1, None for exact readout.

  • contributions (tuple[ContentID, ...]) –

    Content IDs of the observation chunks used. The two quadratures of one trajectory point name the same point chunk, which is one acquisition, not two.

  • point (Text | None) –

    Trajectory point ID of the value, or None.

QPEInterval

Bases: Record

Nominal model interval of one estimator, not a composed uncertainty or coverage bound.

Only RWPE produces one, from its Gaussian model.

Attributes:

  • low (Real) –

    Lower endpoint in frame.

  • high (Real) –

    Upper endpoint in frame.

  • level (Literal[0.95]) –

    Nominal model level, 0.95.

  • method (Text) –

    Interval construction, rwpe_gaussian_credible.

  • frame (Literal['unwrapped turns around reported phase', 'energy in requested operator units']) –

    Unwrapped phase turns centered on the reported phase, or energy in the requested operator units.

  • interpretation (Text) –

    Scope text, prefixed by any identification_note.

QCELSFit

Bases: Record

Outcome of the QCELS finite search. There is no statistical uncertainty model.

Attributes:

  • objective (Literal['complex_least_squares']) –

    Always the amplitude-eliminated complex least squares.

  • effective_grid (PositiveInt) –

    Grid size G = max(grid_size, 8*span + 1) on [-pi, pi), with grid_size the requested setting and span the largest minus the smallest power.

  • evaluations (PositiveInt) –

    Objective evaluations performed, at most 65*G: the grid points and 64 golden-section evaluations for each local minimum of the grid.

  • residual (Nonnegative) –

    Smallest objective value found, mean |z_p - a*exp(-i*p*theta)|**2.

  • interval_method (Literal['unavailable']) –

    Always unavailable.

RWPEGaussian

Bases: Record

Moment-matched Gaussian posterior N(mean, standard_deviation*2) for phi = -tauE.

Attributes:

  • mean (Real) –

    Posterior mean of the unwrapped phase in radians.

  • standard_deviation (Real) –

    Posterior width in radians, prior_std*((e-1)/e)**(k/2) after k processed steps (Granade and Wiebe, arXiv:2208.04526v1, Eq. (7b)).

QPEExposure

Bases: Record

Requested and received population of one count-mode SPE or RFE query.

Attributes:

  • experiment (Text) –

    Query name; its power and quadrature are the Plan's query and its contributing count identities are its samples'.

  • multiplicity (PositiveInt) –

    Original random-draw multiplicity m.

  • requested (PositiveInt) –

    Requested shots plan.shots * m.

  • received (PositiveInt) –

    Shots actually returned, 1 <= received <= requested.

QPEVerification

Bases: Record

Options for checking a QPE estimate against a dense reference spectrum.

Build it with keyword arguments, for example QPEVerification(tolerance=1e-3), and pass it to result.verify(checks=...). tolerance is the only required argument. The check computes a nominal reference spectrum of the estimator's target, H or U, and a QR projector. SPE compares the lowest spectral cluster, and the other estimators compare the largest prepared cluster. It returns (receipt, facts), a record of the check and the facts that compare component_error with tolerance and overlap_deficit = max(0, minimum_overlap - weight) with zero. Numerical grouping does not prove degeneracy. The check runs on explicit dense data only, with no automatic Pauli expansion.

Attributes:

  • tolerance (Nonnegative) –

    Required, nonnegative. Accepted component discrepancy in the requested output unit: the Problem's energy unit for an Eigenvalue output, and turns of circular distance for an Eigenphase output.

  • group_atol (Nonnegative) –

    Default 1e-8, nonnegative. Absolute tolerance for numerical spectral clustering, in the unit of the compared eigenvalues. For a Hamiltonian target it is in the Problem's energy unit and compares eigenvalues of H. For a unitary target it is in radians and compares the principal differences of eigenphase angles. It does not follow the output unit, so an Eigenphase output of a Hamiltonian still groups by energy.

  • minimum_overlap (Real | None) –

    Default None, which uses SPE's declared eta, or 0.9 for the other estimators. Required projector weight, in [0, 1].

  • materialize_preparation (StrictBool) –

    Default False. True allows simulating a supplied preparation circuit to obtain its reference state.

  • reuse_only (StrictBool) –

    Default False. True requires existing spectral and reference data whose target and preparation match, instead of computing them.

  • max_bytes (PositiveInt) –

    Default 10 GB (decimal, 10_000_000_000 bytes). Limit on the known bytes of reference arrays.

  • max_work (PositiveInt) –

    Default 1_000_000_000. Limit on the declared reference work.

solve calls plan, analyze and the other hooks of a Method. Extending NWQLib describes them.