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,
)
BinaryEstimate, BinaryCorrection, BinaryInterval and BinaryPopulation are defined in nwqlib.evidence.binary, and EstimateValue in nwqlib.execution.
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 arguments decide how the terms are evaluated:
- Default, exact readout: the simulator computes every term from one prepared state without shot sampling, subject to numerical rounding.
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 observable in its input format and 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"prepares each occupied site with the gates H, Z, H, which equal X, in place of X, and 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 scalar work of the classical evaluation, including matrix-vector products, scaling, reductions and known state-preparation work. It also limits the comparisons used to form qubit-wise commuting groups for measured counts. -
max_admission_steps(PositiveInt) –Default
1_000_000. Upper limit on the planning work of checking eachProgramthat the method builds (NWQLib's description of a circuit as named steps). It caps the number of stored fields of aProgramand the work units of one check of it. Summing aProgram's resource counts may use up to 24 times this value. A largerProgramis refused with a ValueError that names this field, the refused stage and its count. Raising the limit 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 binary population is the set of zero and one outcomes counted
for one estimated binary mean
(BinaryPopulation). It has
n0 zero and n1 one outcomes, and n = n0 + n1. F is the number of
predeclared binary populations. Without mitigation, these are the nonzero
nonidentity Pauli labels, including labels that share a measurement
setting. With mitigation, they are the science and calibration settings.
delta is failure_probability, and each interval uses alpha = delta/F.
Hoeffding intervals give simultaneous coverage under their sampling
assumptions. Beta intervals give posterior credibility under their
likelihood assumptions.
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 F predeclared binary populations defined above. -
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.Truesupplies the independence assumptions of the chosen inference. Without mitigation, the empirical variance uses joint counts within each measurement group and this assumption between groups. With mitigation, the delta-method variance uses this assumption between the science and calibration settings. A product Beta model, which is available only without mitigation, requires independence of the binary populations, here the individual Pauli labels. Independence between groups alone does not establish independence of labels measured from the same shots. NWQLib does not infer these assumptions from the data, and the aggregate Beta variance stays unavailable when distinct labels share group shots. -
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.
EstimateValue ¶
Bases: Record
The expectation value a provider estimated for one weighted Pauli observable, with the provider's reported uncertainty.
It answers an ObservableEstimateSpec, and ExpectationAnalysis.estimates
holds the estimates of an Expectation run. The reported
standard_error is statistical uncertainty with the provider's stated
meaning. It is not total physical error or a certified bound. Settings
that the provider applied without reporting them, extra shots and
billing remain unknown.
Attributes:
-
kind(Literal['estimate']) –Fixed
"estimate". -
estimate_id(ContentID) –Content hash of the
ObservableEstimateSpec, which fixes the original coefficients and the requested precision. -
value(Real) –Finite estimate, of either sign, in the original units of the observable's coefficients.
-
standard_error(Nonnegative | None) –Nonnegative standard error that the provider reported, or
Nonewhenuncertainty_unavailablegives the reason. -
uncertainty_unavailable(Text | None) –Reason the standard error is unavailable, or
None. -
uncertainty_source(Source) –Sourcenaming where the uncertainty comes from and what it means. -
requested_options_json(Text) –JSON text of the options passed to the provider's estimator.
-
provider_metadata_json(Text) –JSON text of the settings and usage that the provider returned for the job and its input, with the raw uncertainty values it reported.
ExpectationStatistics ¶
Bases: Record
Counts, inference and variance behind a measured ExpectationAnalysis value.
A run with positive shots returns 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 measured data 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 behind the counted data.
-
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-term intervals (the corrected ones with mitigation) 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 predeclared setting (group, parity or calibration) with its preparation records, no recorded reason that rules out an interval for a setting's counts, 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 population, 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.
BinaryPopulation ¶
Bases: Record
A binary population: the counts of zeros and ones of one measured binary mean, with each source of sampled data counted once.
BinaryEstimate.population holds it. A source is one set of sampled
data. A preparation with a fixed seed reproduces its source each time it
runs, so a repeated observation of that source is listed in
reused_observation_ids and does not increase the sample size. One
hardware preparation may supply many fresh sources, and many same-seed
preparations may supply one source. Equal counts from distinct sources
remain distinct data, not proof that the samples are independent and
identically distributed.
Attributes:
-
name(Text) –Name of the setting, or
<setting>:<label>for one label of a grouped setting. -
zeros(BinaryCount) –Number n0 of zero outcomes over the distinct sources.
-
ones(BinaryCount) –Number n1 of one outcomes over the distinct sources.
-
source_ids(tuple[ContentID, ...]) –Content hashes that identify the distinct counted sources.
-
observation_ids(tuple[ContentID, ...]) –Content hash of the observation counted for each source, in the order of
source_ids. -
reused_observation_ids(tuple[ContentID, ...]) –Default
(). Further observations of the same sources, which add no sample size. -
preparation_ids(tuple[tuple[ContentID, ...], ...]) –Default
(). For each counted source, the content hashes of the preparation records that produced it, including repeated runs. Supplied data that no quantum preparation produced can leave it empty.
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 binary population.
-
zero_id(ContentID) –Content hash of the zero-state calibration binary population.
-
one_id(ContentID) –Content hash of the one-state calibration binary 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, under the corrected-mean map, of the joint rectangle of the science and the two calibration intervals, 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 binary populations, positive. Without mitigation, these are the nonzero nonidentity Pauli labels, including labels that share a measurement setting. With mitigation, they are the science and calibration settings. Each interval is evaluated at
alpha = delta/F. Hoeffding coverage and Beta posterior credibility depend on their respective sampling and likelihood assumptions.
When solve or plan receives an accuracy request in place of shots, it calls the Method's sampling_shots before planning. ExpectationMethod.sampling_shots accepts an absolute sampling tolerance, Accuracy(component="sampling", absolute_tolerance=...), and returns the shots per qubit-wise commuting group, as Choose shots for a target accuracy states. A Method without sampling_shots raises ApplicabilityError for an accuracy request. Add a Method states how a new Method supplies it, and Extending NWQLib lists the other functions of a Method.