Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 22 additions & 10 deletions mitiq/zne/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def mitiq_polyfit(
weights: npt.ArrayLike | None = None,
) -> tuple[list[float], npt.NDArray[np.float64] | None]:
"""Fits the ansatz to the (scale factor, expectation value) data using
``numpy.polyfit``, returning the optimal parameters and covariance matrix
polynomial fitting, returning the optimal parameters and covariance matrix
of the parameters.

Args:
Expand All @@ -167,13 +167,23 @@ def mitiq_polyfit(
w = None if weights is None else np.asarray(weights, dtype=float)

with warnings.catch_warnings(record=True) as warn_list:
try:
opt_params, params_cov = np.polyfit(
scale_factors, exp_values, deg, w=w, cov=True
)
except (ValueError, np.linalg.LinAlgError):
opt_params = np.polyfit(scale_factors, exp_values, deg, w=w)
params_cov = None
opt_params, [_res, rank, *_] = np.polynomial.polynomial.polyfit(
scale_factors, exp_values, deg, w=w, full=True
)
residuals = cast(npt.NDArray[np.float64], _res)
if rank < deg + 1:
warnings.warn(_EXTR_WARN, ExtrapolationWarning)

params_cov = None
if len(residuals) > 0:
n = len(scale_factors)
fac = residuals[0] / (n - deg - 1)
V = np.vander(
np.asarray(scale_factors, dtype=float), N=deg + 1, increasing=True
)
if w is not None:
V = np.diag(w) @ V
params_cov = fac * np.linalg.inv(V.T @ V)

for warn in warn_list:
# replace RankWarning with ExtrapolationWarning
Expand All @@ -184,7 +194,9 @@ def mitiq_polyfit(
warnings.warn_explicit(
warn.message, warn.category, warn.filename, warn.lineno
)
return list(opt_params), params_cov
return list(opt_params)[::-1], (
params_cov[::-1, ::-1] if params_cov is not None else None
)


class Factory(ABC):
Expand Down Expand Up @@ -1443,7 +1455,7 @@ def zne_curve(scale_factor: float) -> float:
zstack = list(np.log(shifted_y)) # type: ignore

# Get coefficients {z_j} of z(x)= z_0 + z_1*x + z_2*x**2...
# Note: coefficients are ordered from high powers to powers of x
# Note: coefficients are ordered from high powers to low powers of x
# Weights "w" are used to compensate for error propagation
# after the log transformation y --> z
z_coefficients, params_cov = mitiq_polyfit(
Expand Down