Pauli expectation¶
Use Expectation(state=..., observable=...) with ExpectationMethod to compute the expectation value of a Hermitian observable O in a state psi: the normalized expectation <psi|O|psi>/<psi|psi> by default, or the quadratic form <psi|O|psi> with output=QuadraticForm(observable=O).
from nwqlib import Expectation, NormalizedExpectation, QuadraticForm, solve
from nwqlib.algorithms import ExpectationAnalysis, ExpectationMethod
from nwqlib.algorithms.expectation import ExpectationStatistics
from nwqlib.evidence.binary import (
BinaryInferenceOptions,
BinaryReadoutMitigation,
)
The shot count for an absolute sampling tolerance follows Hoeffding (1963), doi:10.1080/01621459.1963.10500830, Theorem 2, with a union bound over the measured terms, and Proposition 1 derives it. The fixed-time interval of BinaryInferenceOptions(method="hoeffding") follows Theorem 1, Eq. (2.3), p. 15, of the same paper. The Expectation guide states the assumptions of each inference and of the readout calibration model, and its source and code map links each step to its source and implementing function.
Configure the method¶
ExpectationMethod ¶
Bases: Method
Pauli expectation method for the expectation value of an observable in a state.
Build it with keyword arguments and pass it as method=, for example
solve(Expectation(state=psi, observable=O), method=ExpectationMethod()).
Every argument is optional. The result is an
ExpectationAnalysis
whose value is the normalized expectation <psi|O|psi>/<psi|psi>, or
with output=QuadraticForm(observable=O) the quadratic form
<psi|O|psi>. For O = c_0 I + sum_j c_j P_j it measures the
expectations <P_j> of the nonzero non-identity Pauli terms and adds the
identity coefficient exactly, so an identity-only observable needs no
measurement on any path.
The call chooses how the terms are measured:
- Default, exact readout: one prepared state supplies every term.
shots=n: one circuit per qubit-wise commuting group, n shots each, withinferenceapplied to each term's parity. The uncertainty includes the covariance of terms in one group.shots=nwithmitigation: one parity circuit per non-identity term, plus calibration circuits for each pivot qubit.estimate_precision: one provider estimate of the whole weighted sum.execution="classical": a matrix-vector product with the stored observable in its original dimension.
Instead of shots, accuracy=Accuracy(component="sampling",
absolute_tolerance=epsilon) lets sampling_shots choose the shots per
group from Hoeffding's inequality (Hoeffding (1963),
doi:10.1080/01621459.1963.10500830, Theorem 2) with a union bound over
the measured terms. That bound covers sampling only, under its
assumptions. Proposition 1 derives the count,
and the Expectation guide states the
statistical quantities and their assumptions.
Attributes:
-
preparation_choice(Literal['native', 'hzh']) –Default
"native", the state's own preparation circuit."hzh"selects an equivalent wiring that is accepted only for occupation-number states. -
inference(BinaryInferenceOptions) –Default
BinaryInferenceOptions(), empirical points without an interval. How measured counts become estimates and intervals. Any other choice needs positive shots. -
mitigation(BinaryReadoutMitigation | None) –Default
None, no calibration. ABinaryReadoutMitigationmeasures one parity circuit per non-identity term instead of one circuit per commuting group and adds its calibration circuits. It needs positive shots and excludes Beta inference. -
estimate_precision(Real | None) –Default
None. Positive precision requested from a provider Estimator for the whole weighted sum, in the units of the observable's coefficients. It excludes positive shots, a non-defaultinferenceandmitigation, and it does not set a shot count. -
max_bytes(PositiveInt) –Default 10 GB (decimal,
10_000_000_000bytes). Limit on the known bytes of the operator, the state and the classical workspace. -
max_classical_products(PositiveInt) –Default
100_000_000. Limit on the counted classical operator applications, and on the comparisons that sort the terms of sampled readout into qubit-wise commuting groups. -
max_admission_steps(PositiveInt) –Default
1_000_000. Limit on the planning work of checking each circuit description that the method builds. It caps both the number of stored fields of a description and the work units of one structural check of it. Summing a description's resource counts may use up to 24 times this value. The default equals that ofQLSand is ten times the shared default of100_000. Raising it permits a larger check and changes no quantum operation (planning work limit).
Raises:
-
ValueError–If
estimate_precisionis combined with a non-defaultinferenceor withmitigation, or ifmitigationis combined with Beta inference.
Examples:
For the state psi = (3, 4) and O = Z, the quadratic form is
9 - 16 = -7 and the normalized expectation is -7/25 = -0.28. The
default quantum path runs on Aer with exact readout:
>>> from nwqlib import Expectation, QuadraticForm, solve
>>> from nwqlib.algorithms import ExpectationMethod
>>> problem = Expectation(state=[3, 4], observable=[[1, 0], [0, -1]])
>>> result = solve(problem, method=ExpectationMethod())
>>> print(round(result.value, 10))
-0.28
>>> quadratic = QuadraticForm(observable=problem.observable)
>>> result = solve(problem, method=ExpectationMethod(), output=quadratic)
>>> print(round(result.value, 10))
-7.0
BinaryInferenceOptions ¶
Bases: Record
Statistical model that turns measured binary counts into estimates and intervals.
Build it with keyword arguments, for example
BinaryInferenceOptions(method="hoeffding", sampling_model="iid_bernoulli"),
and pass it as ExpectationMethod(inference=...) or to
result.analyze(inference=...). Every argument is optional, and the
default returns empirical points without an interval. It applies to
measured counts, so any other choice needs positive shots. It changes
neither what is measured nor the physical accuracy, and its intervals
describe sampling under the stated model only.
Below, a population has n0 zero and n1 one outcomes, n = n0 + n1,
delta is failure_probability, and alpha = delta/F is its share for
each of the F predeclared settings, so that all F intervals hold jointly
with probability at least 1 - delta.
Attributes:
-
method(Literal['point', 'hoeffding', 'anytime_hoeffding', 'beta']) –Default
"point", the empirical mean and variance without an interval."hoeffding"gives a fixed-time interval of radiussqrt(2*log(2/alpha)/n)(Hoeffding (1963), doi:10.1080/01621459.1963.10500830, Theorem 1, Eq. (2.3), p. 15, rescaled to outcomes in [-1, 1] and made two-sided as in Eq. (1.4), p. 13)."anytime_hoeffding"gives the same radius atalpha_n = alpha/(n*(n + 1))for every n, a union bound over n."beta"gives the posteriorBeta(prior_alpha + n0, prior_beta + n1)ofp = P(bit = 0), mapped to2*p - 1, with an equal-tail interval whose credibility is not frequentist coverage. That interval is unavailable when the shape total exceeds5e11, and the posterior mean and variance remain (Engineering constants). -
failure_probability(Real) –Default
0.05, strictly between 0 and 1. Family failure probability delta, divided equally across the predeclared science and calibration settings. -
sampling_model(Literal['unknown', 'iid_bernoulli', 'constant_conditional_mean']) –Default
"unknown". Assumed model of the shots, which NWQLib does not verify:"iid_bernoulli","constant_conditional_mean"or"unknown"."unknown"keeps the empirical values and gives no interval."constant_conditional_mean"does not supply the Beta likelihood. -
independent_populations(StrictBool) –Default
False.Truedeclares the measured groups, or with mitigation the science and calibration settings, statistically independent. The variance sum across settings and a product Beta model need this assumption, which NWQLib does not deduce from the data. -
prior_alpha(Real) –Default
1.0, positive. Beta prior shape forp = P(bit = 0), added to the zero count n0. -
prior_beta(Real) –Default
1.0, positive. Beta prior shape added to the one count n1.
Raises:
-
ValueError–If
method="beta"is combined withsampling_model="constant_conditional_mean", or if a method other than"point"has afailure_probabilitywhose complement1 - failure_probabilityis not representable strictly between 0 and 1.
BinaryReadoutMitigation ¶
Bases: Record
Readout calibration that corrects each measured parity with a fitted single-bit channel.
Build it with keyword arguments, for example
BinaryReadoutMitigation(calibration_shots=512), and pass it as
ExpectationMethod(mitigation=...) together with positive shots.
calibration_shots is the only required argument. Each non-identity
term is then measured by its own parity circuit, which collects the
term's parity on its pivot, the highest-index qubit on which the term
acts. Each pivot gets two calibration circuits, which prepare 0 and 1.
For K terms and P distinct pivots, a complete run uses K + 2*P
circuits and K*shots + 2*P*calibration_shots shots.
The model z = a*mu + b maps the parity mean mu to the observed pivot
mean z. The calibration means z0 and z1 give a = (z0 - z1)/2 and
b = (z0 + z1)/2, and the corrected mean is mu = (z - b)/a. The model
assumes a stationary readout channel, transfer of the calibration to the
science circuits and correct calibration preparation, which NWQLib does
not verify. Mitigation excludes Beta inference.
Attributes:
-
calibration_shots(BinaryCount) –Required. Positive number of shots, at most
2**53 - 1, of each zero and each one calibration circuit. -
minimum_contrast(Real) –Default
0.05, in (0, 1]. Lower limit onabs(a) = abs(z0 - z1)/2. Below it the correction, and therefore the result'svalue, is unavailable. A negative contrast of larger magnitude is accepted. The default is an adjustable conditioning threshold (Engineering constants).
Read the result¶
ExpectationAnalysis ¶
Bases: Result
Expectation value from an ExpectationMethod run, with its measurement statistics.
solve returns it for an ExpectationMethod,
and load_result reopens a saved one. The answer is value, in the unit
of the Expectation problem: the normalized expectation
<psi|O|psi>/<psi|psi> for a NormalizedExpectation output, or the
quadratic form <psi|O|psi> for a QuadraticForm output. With
s = ||psi||**2, the quadratic form multiplies the normalized point and
interval by s and the estimator variance by s**2. value is None when
a term has no data or the value is unavailable, and missing and
unavailable then say why. print(result) shows the value and its
scope, and result.analyze(inference=...) applies other
BinaryInferenceOptions to the same counts without new measurement. The
fields below are read-only. The fields of
Result are present too.
Reading the Result
gives the meaning and scaling of each field, including the BinaryEstimate
and BinaryCorrection records inside statistics.
Attributes:
-
value(Real | None) –c_0 + sum_j c_j*estimate_jforO = c_0 I + sum_j c_j P_j, times s for a quadratic form.estimate_jis the exact Pauli mean, the chosen binary estimate, or the corrected point with mitigation. A provider estimate or a classical matrix-vector product gives the whole sum instead. None exactly whenmissingis nonempty orunavailableis set. -
physical_scale(PhysicalScale) –||psi||as a mantissa and binary exponent, the source of s. -
missing(tuple[Text, ...]) –Non-identity Pauli terms without data.
-
statistics(ExpectationStatistics | None) –The
ExpectationStatisticsof measured counts, otherwise None. -
estimates(tuple[EstimateValue, ...]) –Original provider estimates of the normalized expectation, on the provider path only.
-
unavailable(Text | None) –Reason
valueis None when no term is missing. -
inference(BinaryInferenceOptions | None) –BinaryInferenceOptionsused by a measured analysis, otherwise None.
provider_output_estimates ¶
provider_output_estimates
Provider estimates converted to the requested output, times s for a quadratic form.
One dict per entry of estimates, with the keys source_id, value,
standard_error and uncertainty_unavailable. They are computed when
read and are not saved, and estimates keeps the original provider
values. The standard error keeps the provider's meaning, and several
estimates carry no covariance or combined standard error.
ExpectationStatistics ¶
Bases: Record
Counts, inference and variance behind a measured ExpectationAnalysis value.
A run with positive shots stores it as result.statistics. variance
is an empirical or delta-method estimate under its recorded covariance
assumptions, not the total physical variance. interval has the
statistical meaning of the chosen inference and no physical-model
guarantee. The fields below are read-only.
Attributes:
-
inference_options_id(ContentID) –Content hash of the
BinaryInferenceOptionsthis analysis used. -
populations(tuple[BinaryEstimate, ...]) –Without mitigation, one
BinaryEstimateper nonzero non-identity term, named<group setting>:<label>, in group and member order. Its counts are the term's marginal parities in its group's histogram, and the terms of one group share that group's sources, observations and preparation records, which count as one measurement. With mitigation, oneBinaryEstimateper predeclared science and calibration setting, in setting order. Each keeps its raw counts and any posterior. -
corrections(tuple[BinaryCorrection, ...]) –With mitigation, one affine
BinaryCorrectionper science term, with its signed corrected point. Empty otherwise. -
receipt_ids(tuple[ContentID, ...]) –Content hashes of the preparation records of the counted sources.
-
raw_value(Real | None) –The same weighted sum over the uncorrected raw means, for the requested output.
-
variance_kind(Literal['empirical', 'delta_method', 'posterior']) –"empirical","delta_method"for fitted calibration, or"posterior"for Beta inference. -
variance(VarianceAssessment | None) –Variance of the requested output under the recorded covariance assumptions, or None. Without mitigation it has one contribution per group, the empirical variance of the group's weighted score mean, so the covariance between terms of one group is included.
-
variance_unavailable(Text | None) –Reason
varianceis None. -
interval(BinaryInterval | None) –Linear image of the simultaneous per-population intervals for the requested output, or None for point inference.
-
fixed_time(StrictBool) –Whether the data qualify for a fixed-time interval: exactly one complete original measurement per setting (group, parity or calibration) with its preparation records, no reason blocking a population, and no cancellation or early stop.
-
fixed_time_reason(Text) –Why
fixed_timeholds or fails. -
applicability_reason(Text | None) –Why missing preparation records leave the target, compiler or layout unverified, or None.
-
independence_reason(Text | None) –Why independence across settings is unverified because they share one fixed sampling stream, or None. The terms of one qubit-wise commuting group share their group's shots by design, so independence concerns distinct groups.
-
source(Source) –Name and version of the binary-inference implementation.
BinaryEstimate ¶
Bases: Record
Quantities derived from the counts of one binary setting, with the empirical and posterior roles kept apart.
ExpectationStatistics.populations holds one per measured label or
setting, as the Expectation
guide describes. The fields below are
read-only.
Attributes:
-
population(BinaryPopulation) –The counted data:
zeros(n0) andones(n1) of the distinct counted sources, with their identifiers. -
options_id(ContentID) –Content hash of the
BinaryInferenceOptionsused. -
source(Source) –The
Sourceof the binary inference. -
raw_mean(Real | None) –Sample mean
z = (n0 - n1)/nin [-1, 1],Nonewhenn = 0. -
empirical_variance(Rational | None) –Exact rational sample-mean variance
4*n0*n1/(n**2*(n - 1)),Noneforn <= 1. -
point(Real | None) –The Beta posterior mean of
2p - 1forbetainference,Nonewhen its assumptions fail, andraw_meanotherwise. -
posterior_variance(Nonnegative | None) –Beta posterior variance of
2p - 1, which is not a sampling variance. -
interval(BinaryInterval | None) –The
BinaryIntervalof the selected inference,Nonefor point inference. A missing interval keeps its kind and the reason. -
unavailable(tuple[Text, ...]) –Reasons for quantities that could not be formed.
BinaryCorrection ¶
Bases: Record
Readout-corrected mean of one science term from the affine calibration model, with its local derivatives.
ExpectationStatistics.corrections holds one per science term when
readout mitigation is used. The model is z = a*mu + b with
a = (z0 - z1)/2 and b = (z0 + z1)/2, where z0 and z1 are the
calibration means (Expectation guide).
The fields below are read-only.
Attributes:
-
science_id(ContentID) –Content hash of the science setting's counted population.
-
zero_id(ContentID) –Content hash of the zero-state calibration population.
-
one_id(ContentID) –Content hash of the one-state calibration population.
-
options_id(ContentID) –Content hash of the options used.
-
contrast(Real | None) –The contrast a, in [-1, 1], or
None. -
offset(Real | None) –The offset b, in [-1, 1], or
None. -
point(Real | None) –The corrected mean mu, a signed finite-sample estimator, not a physical probability or a bounded Pauli mean. It can lie outside [-1, 1].
-
derivatives(tuple[Real, Real, Real] | None) –The Jacobian of
pointin(z, z0, z1). Its use in a variance is a delta-method approximation. -
interval_image(tuple[Real, Real] | None) –Image of the calibration box before intersection with the physical mean domain [-1, 1].
-
interval(BinaryInterval | None) –That intersection, a
BinaryInterval. -
unavailable(tuple[Text, ...]) –Reasons for quantities that could not be formed.
-
assumptions(tuple[Text, ...]) –The assumptions of the correction.
BinaryInterval ¶
Bases: Record
Interval for one binary mean, separate from its empirical variance and its point estimate.
BinaryEstimate.interval and BinaryCorrection.interval hold it.
Binary64 evaluation is not a certified numerical enclosure. The fields
below are read-only.
Attributes:
-
kind(Literal['fixed_time', 'time_uniform', 'bayesian']) –"fixed_time"(Hoeffding endpoint coverage),"time_uniform"(anytime Hoeffding coverage) or"bayesian"(Beta posterior credibility), from the inference method. -
probability(Real) –Family probability
1 - delta, withdeltathe options'failure_probability, strictly between 0 and 1. -
status(Literal['conditional', 'unavailable', 'empty']) –"conditional"with both endpoints,"unavailable", or"empty"after a justified intersection with the physical parameter set, which is not missing data. -
lower(Real | None) –Lower endpoint,
Noneunlessstatusis"conditional". -
upper(Real | None) –Upper endpoint,
Noneunlessstatusis"conditional". -
reason(Text) –Text recorded with the interval, including why it is unavailable or empty.
-
assumptions(tuple[Text, ...]) –The assumptions the interval depends on.
-
family_size(Count) –Number F of predeclared settings, positive. Each interval is evaluated at
alpha = delta/F, so all F hold jointly with probability at least1 - delta.
solve calls sampling_shots and the other hooks of a Method. Choose shots for a target accuracy states the shot count that sampling_shots returns, and Extending NWQLib describes the hooks.