guppyalgos.utils

Classical and Guppy utility functions.

Functions

analyze_qubit_pauli_operator(ham_op, time_step)

Summarize exact and Trotterized spectra for a Pauli Hamiltonian.

apply_bitstring()

Apply bit flips to a reg according to bit_array.

apply_phase(q, theta)

Apply a phase rotation to a qubit.

binary_fraction(readout)

Convert bits into a QPE-style fraction number [0, 2).

bits_to_int(bits, *[, signed])

Interpret bits as a little-endian integer.

ccswap()

Apply a double-control swap between qubits or equal size registers.

cphase(control, target, theta)

Apply a controlled phase rotation (CU1).

cswap()

Apply a control swap between qubits or equal size registers.

discard_nested_arrays(arrays)

Discard every qubit in a nested array.

dominant_measured_phase(result_counter[, ...])

Return the dominant bitstring and its decoded phase from a histogram.

dominant_trotter_phase(analysis)

Return the dominant Trotter phase and overlap from an analysis table.

dominant_trotterized_eigenphase(ham_op, ...)

Return the Trotter eigenphase with the largest overlap to a state.

fixed_point_to_float(bits[, int_bits])

Convert an unsigned fixed-point bit string to a float.

float_to_fixed_point(value, frac_bits[, ...])

Convert a float to a fixed-point binary representation.

floor(x)

Compute the largest integer less than or equal to x.

get_bit(k, i)

Extract bit i from integer k.

int_to_bits(integer, length, *[, signed])

Convert an integer to a little-endian bit string of input length.

measurement_dataframe(result_counter[, int_bits])

Store a measurement histogram and decoded phases as a dataframe.

phase_distance_mod_2(phase_a, phase_b)

Return the shortest distance between two phases on the circle [0, 2).

phase_to_energy_qpe(phase, total_time[, ...])

Convert a QPE phase into an energy for U(t) = e^{-i \pi t H / 2}.

phase_to_energy_qubitized_qpe(phase, ...)

Convert a qubitization walk phase to its encoded operator energy.

qarray(n)

Allocate a qubit array of length n.

qsp_phase_reflection(phi_list)

QSP reflection phase convention conversion from pyqsp.

t_state(qubit)

Directly generate a T state on a qubit.

tan(x)

Compute the tangent of x.

transversal()

Apply a single or two qubit operator register-wise.

trotter_step_matrix(ham_op, time_step[, ...])

Return the one-step first-order Trotter unitary matrix.

trotterized_eigenphases(ham_op, time_step[, ...])

Return sorted one-step Trotter eigenphases and eigenvectors.

Classes

BaseCompilePhases()

Abstract class for Phase Compilers for QSPAngleFinder.

ChebyshevPolynomial(fun, degree[, rtol])

Chebyshev class.

CompilerPhasesNumba()

Compiler based on numba operations.

CompilerPhasesNumpy()

Compiler based on numpy operations.

FourierPolynomial(coeffs[, d_max, d_min, rtol])

Fourier class representing a Fourier Polynomial.

FunctionParity(*values)

Parity of function.

GQSPAngleFinder(target_polynomial)

Find GQSP angles via exact methods.

QSPAngleFinder(d_phi, target_polynomial[, ...])

Find QSP angles via optimization.

class guppyalgos.utils.BaseCompilePhases

Abstract class for Phase Compilers for QSPAngleFinder.

class guppyalgos.utils.ChebyshevPolynomial(fun, degree, rtol=0.001)

Chebyshev class.

Given an input vectorized function computes the coefficients of the Chebyshev polynomial with the desired degree that approximates it. The input function must be normalized, i.e. it’s maximum (in absolute value) in [-1, 1] has to be 1 at most. Furthermore, even (odd) parity functions require an even (odd) degree.

Parameters:
  • fun (Callable[[NDArray], NDArray]) – vectorized function to be approximated

  • degree (int) – degree of the polynomial

  • rtol (float) – tolerance for checking normalization and parity

property coeffs: NDArray[float64]

Return the coefficients.

property degree: int

Return the degree.

property error: float64

Return the maximum absolute error of the polynomial approximation.

property extrema: NDArray[float64]

Return the extrema.

property fun: Callable[[NDArray[float64]], NDArray[float64]]

Return the original function.

property norm: float64

Return the norm.

property parity: FunctionParity

Return the parity of the function.

property roots: NDArray[float64]

Return the roots.

class guppyalgos.utils.CompilerPhasesNumba

Compiler based on numba operations.

class guppyalgos.utils.CompilerPhasesNumpy

Compiler based on numpy operations.

class guppyalgos.utils.FourierPolynomial(coeffs, d_max=None, d_min=0, rtol=0.001)

Fourier class representing a Fourier Polynomial.

Given coefficients \(\{n: c_n\}\) for \(d_{\min} \leq n \leq d_{\max}\), this class represents \(f(x) = \sum_n c_n \exp(i n \pi x)\). The coefficients must define a normalized function.

Parameters:
  • coeffs (dict) – dictionary of coefficients.

  • d_max (Optional[int]) – maximum degree.

  • d_min (int) – minimum degree.

  • rtol (float) – tolerance for checking normalization.

property coeffs: dict[int, complex128]

Return dict of coefficients.

property coeffs_list: NDArray[complex128]

Return list of coefficients.

property d_max: int

Return maximum degree.

property d_min: int

Return minimum degree.

eval_mat(mat)

Given matrix mat, evaluates mat * pi.

Return type:

GenericAlias[complex128]

property norm: float

Return norm of function.

class guppyalgos.utils.FunctionParity(*values)

Parity of function.

EVEN = 0
NONE = 2
ODD = 1
class guppyalgos.utils.GQSPAngleFinder(target_polynomial)

Find GQSP angles via exact methods.

Given a target Fourier series P, this class computes the phase factors to implement the GQSP circuit for a given operator. It consists of two steps:

Although the procedure is exact, when considering large degrees numerical errors may arise.

Parameters:

target_polynomial (FourierPolynomial) – Target Fourier series.

property G_roots: NDArray[complex128]

Return roots of the Laurent poly sorted by increasing magn.

property complementary_polynomial: FourierPolynomial

Return the complementary polynomial.

property degree: int

Return the degree.

property phase_factors: NDArray[float64]

Return the phases.

property prefactor: float64

Return the prefactor of the Laurent poly, must be real.

property target_polynomial: FourierPolynomial

Return the target polynomial.

class guppyalgos.utils.QSPAngleFinder(d_phi, target_polynomial, phi_0=None, compiler=<guppyalgos.utils.python.angle_finder.CompilerPhasesNumpy object>)

Find QSP angles via optimization.

Based on https://arxiv.org/abs/2002.11649. Given a target polynomial f(x), this protocol minimizes the loss function L(phi) = dist(Re(<0|U_phi(x)|0>), f(x)). It uses phase symmetry to reduce the complexity of the problem. For degree d, there are d + 1 standard phases, but only d_hat = ceil((d + 1) / 2) independent symmetric phases. If phi_hat = (phi_hat_0, ..., phi_hat_{d_hat - 1}), the mappings are:

  • For odd d: phi = (phi_hat_0, ..., phi_hat_{d_hat - 1}, phi_hat_{d_hat - 1}, ..., phi_hat_0).

  • For even d: phi = (phi_hat_0, ..., phi_hat_{d_hat - 2}, phi_hat_{d_hat - 1}, phi_hat_{d_hat - 2}, ..., phi_hat_0).

There is also the option to use numba to accelerate the evaluation of the loss function.

Parameters:
  • d_phi (int) – Degree of the QSP.

  • target_polynomial (ChebyshevPolynomial) – Target Chebyshev polynomial.

  • phi_0 (NDArray[np.float64]) – Set of initial phases.

  • compiler (BaseCompilePhases) – Compiler used for generating the loss function. Availables: ‘numpy’ and ‘numba’. Defaults to numpy.

property compiler: BaseCompilePhases

Return the compiler.

property fun_vals: NDArray[complex128] | NDArray[float64]

Return the value of the target function.

property norm: float64

Return the value of the target function.

property opt_error: float64

Return the optimization error.

property phi: Sequence[float]

Return the phases.

property target_polynomial: ChebyshevPolynomial

Return the target polynomial.

property x_Chebyshev_roots: NDArray[float64]

Return the roots.

guppyalgos.utils.analyze_qubit_pauli_operator(ham_op, time_step, prepared_state=None, little_endian=True)

Summarize exact and Trotterized spectra for a Pauli Hamiltonian.

The returned single-row dataframe keeps the dense matrices, spectra, and overlap diagnostics together so the notebook can display them compactly.

This routine constructs dense 2**n matrices and diagonalizes them, so the cost is exponential in the number of qubits.

Return type:

DataFrame

guppyalgos.utils.apply_bitstring()

Apply bit flips to a reg according to bit_array.

guppyalgos.utils.apply_phase(q, theta)

Apply a phase rotation to a qubit.

guppyalgos.utils.binary_fraction(readout)

Convert bits into a QPE-style fraction number [0, 2).

Return type:

float

guppyalgos.utils.bits_to_int(bits, *, signed=False)

Interpret bits as a little-endian integer.

Parameters:
  • bits (list[bool]) – Little-endian bit string. When signed is true, the final bit is interpreted as the sign bit of a two’s-complement integer.

  • signed (bool) – Whether to decode a signed two’s-complement integer.

Return type:

int

Returns:

The integer represented by bits.

guppyalgos.utils.ccswap()

Apply a double-control swap between qubits or equal size registers.

Either:

ccswap(control_bit_0, control_bit_1, qubit_a, qubit_b)

Or:

ccswap(control_bit_0, control_bit_1, a_reg, b_reg)

guppyalgos.utils.cphase(control, target, theta)

Apply a controlled phase rotation (CU1).

Parameters:
  • control – Control qubit.

  • target – Target qubit.

  • theta – Angle of rotation.

Returns:

None

guppyalgos.utils.cswap()

Apply a control swap between qubits or equal size registers.

Either:

cswap(control_bit, qubit_a, qubit_b)

Or:

cswap(control_bit, a_reg, b_reg)

guppyalgos.utils.discard_nested_arrays(arrays)

Discard every qubit in a nested array.

Parameters:

arrays – Owned, equally sized qubit arrays to discard.

guppyalgos.utils.dominant_measured_phase(result_counter, int_bits=1)

Return the dominant bitstring and its decoded phase from a histogram.

Return type:

tuple[str, int, float]

guppyalgos.utils.dominant_trotter_phase(analysis)

Return the dominant Trotter phase and overlap from an analysis table.

Return type:

tuple[float, float]

guppyalgos.utils.dominant_trotterized_eigenphase(ham_op, time_step, prepared_state, little_endian=True)

Return the Trotter eigenphase with the largest overlap to a state.

This performs trotterized_eigenphases, so it is exponentially expensive in the number of qubits.

Parameters:
  • ham_op (RealTermSum) – Pauli Hamiltonian whose Trotter step is analyzed.

  • time_step (float) – Dimensionless Trotter time step.

  • prepared_state (GenericAlias[complex128]) – State vector to project onto the Trotter eigenbasis.

  • little_endian (bool) – Whether the underlying matrix convention is little-endian.

Return type:

tuple[float, float]

Returns:

The dominant eigenphase and the corresponding overlap probability.

guppyalgos.utils.fixed_point_to_float(bits, int_bits=0)

Convert an unsigned fixed-point bit string to a float.

Parameters:
  • bits (Sequence[bool]) – Fixed-point bit string.

  • int_bits (int) – Number of bits above the radix point.

Return type:

float

Returns:

The decoded unsigned fixed-point value.

Examples

>>> fixed_point_to_float([True, False, False], int_bits=1)
0.25
>>> fixed_point_to_float([True, True, False, True], int_bits=1)
1.375
guppyalgos.utils.float_to_fixed_point(value, frac_bits, int_bits=0)

Convert a float to a fixed-point binary representation.

Parameters:
  • value (float) – Unsigned value to encode.

  • frac_bits (int) – Number of bits below the radix point.

  • int_bits (int) – Number of bits above the radix point.

Return type:

list[bool]

Returns:

Little-endian fixed-point bit string.

Examples

>>> float_to_fixed_point(0.25, 2)
[True, False]
>>> float_to_fixed_point(1.375, 3, int_bits=1)
[True, True, False, True]
guppyalgos.utils.floor(x)

Compute the largest integer less than or equal to x.

Parameters:

x – Floating-point value.

Returns:

Largest integer less than or equal to x.

Return type:

int

guppyalgos.utils.get_bit(k, i)

Extract bit i from integer k.

Parameters:
  • k – Integer value.

  • i – Bit position, where 0 is the rightmost (least significant) bit.

Returns:

True if bit i is 1, False otherwise.

Return type:

bool

guppyalgos.utils.int_to_bits(integer, length, *, signed=False)

Convert an integer to a little-endian bit string of input length.

Parameters:
  • integer (int) – The integer to convert.

  • length (int) – The length of the resulting bit string.

  • signed (bool) – Flag to represent signed vs unsigned ints.

Returns:

A list of boolean values representing the bit string. When signed gives the twos-complement, where bits[-1] is the sign bit.

Return type:

list[bool]

guppyalgos.utils.measurement_dataframe(result_counter, int_bits=1)

Store a measurement histogram and decoded phases as a dataframe.

The measurement bitstrings are interpreted as little-endian by default, which matches the current QPE readout convention.

Return type:

DataFrame

guppyalgos.utils.phase_distance_mod_2(phase_a, phase_b)

Return the shortest distance between two phases on the circle [0, 2).

This is useful when comparing QPE phases modulo 2, where values that differ by an integer multiple of 2 represent the same point on the phase circle.

Return type:

float

guppyalgos.utils.phase_to_energy_qpe(phase, total_time, phase_wraps=0)

Convert a QPE phase into an energy for U(t) = e^{-i \pi t H / 2}.

Uses E = -2 * (phase + 2 * phase_wraps) / total_time. The default phase_wraps=0 selects the principal branch.

Return type:

float

guppyalgos.utils.phase_to_energy_qubitized_qpe(phase, normalization)

Convert a qubitization walk phase to its encoded operator energy.

Return type:

float

guppyalgos.utils.qarray(n)

Allocate a qubit array of length n.

guppyalgos.utils.qsp_phase_reflection(phi_list)

QSP reflection phase convention conversion from pyqsp.

Converts a list of qsp phases to radians for use in guppy in the convention used in Appendix A2 of https://journals.aps.org/prxquantum/pdf/10.1103/PRXQuantum.2.040203

Parameters:

phi_list (list[float]) – The list of phases to be converted

Returns:

The converted phases

Return type:

np.array

guppyalgos.utils.t_state(qubit)

Directly generate a T state on a qubit.

guppyalgos.utils.tan(x)

Compute the tangent of x.

Based on https://go.dev/src/math/tan.go.

Parameters:

x – Angle in radians.

Returns:

Tangent of x.

Return type:

float

guppyalgos.utils.transversal()

Apply a single or two qubit operator register-wise.

To apply x to all the qubits in the register: transversal(x, register)

To apply cx to all the qubits in the register: transversal(cx, reg1, reg2)

To apply cx to specific qubits in the register: transversal(cx, reg1, reg2, array([1, 3])) or transversal2(cx, controls, targets, array(comptime(n_qubits - 1)))

guppyalgos.utils.trotter_step_matrix(ham_op, time_step, little_endian=True)

Return the one-step first-order Trotter unitary matrix.

Parameters:
  • ham_op (RealTermSum) – Pauli Hamiltonian to exponentiate term-by-term.

  • time_step (float) – Dimensionless Trotter time step.

  • little_endian (bool) – Whether the underlying matrix convention is little-endian.

Return type:

GenericAlias[complex128]

Returns:

The dense unitary matrix for one first-order Trotter step.

guppyalgos.utils.trotterized_eigenphases(ham_op, time_step, little_endian=True)

Return sorted one-step Trotter eigenphases and eigenvectors.

This diagonalizes the dense Trotter step matrix, so the cost is exponential in the number of qubits.

Parameters:
  • ham_op (RealTermSum) – Pauli Hamiltonian to diagonalize through the Trotter step.

  • time_step (float) – Dimensionless Trotter time step.

  • little_endian (bool) – Whether the underlying matrix convention is little-endian.

Return type:

tuple[GenericAlias[float64], GenericAlias[complex128]]

Returns:

A tuple of the sorted eigenphases in [0, 2) and the corresponding eigenvectors as columns.