Skip to content
Construct PsiQDK Algorithms

utils

utils

ListOfBlockEncodingsCompressionGadget

ListOfBlockEncodingsCompressionGadget(list_strategies: tuple[Qubrick] | list[Qubrick], data: tuple | list)

Implementation of a CompressionGadgetStrategy for a list of block-encodings.

Parameters:

Name Type Description Default
list_strategies tuple[Qubrick] | list[Qubrick]

List of strategies to apply the block-encodings.

required
data tuple | list

List of block-encoding's data.

required

list_strategies property

list_strategies

List of strategies.

data property

data

List of data.

apply_compression_gadget_block_encoding

apply_compression_gadget_block_encoding(system_reg: Qubits, be_anc: Qubits, idx: int, ctrl: Qubits | int = 0)

Apply block-encoding strategy of kth block-encoding.

Parameters:

Name Type Description Default
system_reg Qubits

System register.

required
be_anc Qubits

Block-encoding auxiliary qubits.

required
idx int

Index of the strategy to used.

required
ctrl Qubits | int

Control register. Default to 0.

0

PowerCompressionGadgetStrategy

PowerCompressionGadgetStrategy(block_encoding_strategy: Qubrick, data)

Implementation of a CompressionGadgetStrategy to implement \(H^n\).

Parameters:

Name Type Description Default
block_encoding_strategy Qubrick

Strategy to apply the block-encoding.

required
data Any

Block-encoding's data.

required

block_encoding_strategy property

block_encoding_strategy

Block-encoding strategy.

data property

data

Block-encoding's data.

apply_compression_gadget_block_encoding

apply_compression_gadget_block_encoding(system_reg: Qubits, be_anc: Qubits, idx: int, ctrl: Qubits | int = 0)

Apply block-encoding strategy of k-th block-encoding.

Parameters:

Name Type Description Default
system_reg Qubits

System register.

required
be_anc Qubits

Block-encoding auxiliary qubits.

required
idx int

Index of the strategy to use.

required
ctrl Qubits | int

Control register. Default to 0.

0

DysonSelectStrategyNaive

DysonSelectStrategyNaive(truncation: int, fast_forward_exp: Qubrick, hamiltonian: PauliSum, block_encoding: Qubrick)

A helper class to apply an operator of the form \(\exp(-iH_0 t)V \exp(iH_0 t)\).

Parameters:

Name Type Description Default
truncation int

a value of the truncation parameter.

required
fast_forward_exp Qubrick

a fast-forwardable part \(\exp(-iH_0 t)\) of a Hamiltonian to simulate.

required
hamiltonian PauliSum

a block-encoded part \(BE(V)\) of a Hamiltonian to simulate.

required
block_encoding Qubrick

a block-encoding/LCU subroutine.

required

truncation property

truncation

Getter for the truncation parameter.

hamiltonian property

hamiltonian

Getter for the block-encoded part of a Hamiltonian to simulate.

fast_forward_exp property

fast_forward_exp

Getter for the fast-forwardable part of the Hamiltonian.

block_encoding property

block_encoding

Getter for the block encoding subroutine.

apply_compression_gadget_block_encoding

apply_compression_gadget_block_encoding(register: DysonSeriesBinaryIndex, idx: int, ctrl: Qubits | int = 0)

Apply the Hamiltonian operator to the system register.

Parameters:

Name Type Description Default
register CompositeRegister

a composite register for Dyson Series.

required
idx int

an index of the time iteration for the time discretization register.

required
ctrl (Qubits, int)

a register to control this operation on. Default to 0.

0

DysonSeriesBinaryIndex dataclass

DysonSeriesBinaryIndex(trunc_reg: Qubits, discret_reg: list[Qubits], be_anc: Qubits, system_reg: Qubits, name: str)

Bases: CompositeRegister

Dataclass for the binary Dyson Series Composite Register.

trunc_reg instance-attribute

trunc_reg: Qubits

discret_reg instance-attribute

discret_reg: list[Qubits]

be_anc instance-attribute

be_anc: Qubits

system_reg instance-attribute

system_reg: Qubits

name instance-attribute

name: str

initialize classmethod

initialize(qc, name, trunc_param: int, t_disc_param: int, syst: int | Qubits, n_be_anc: int | list)

The binary Dyson Series Expansion composite index register.

Parameters:

Name Type Description Default
qc QPU

A QPU instance.

required
name str

The name of composite register.

required
trunc_param int

Truncation parameter.

required
t_disc_param int

Time-discretization parameter.

required
syst int | Qubits

The system register an operator is applied to.

required
n_be_anc int | list

A register for the operator block encoding.

required

DysonSeriesData dataclass

DysonSeriesData(discretization: int, truncation: int, collision: bool, hamiltonian: PauliSum, t0: float)

Dataclass for the DysonSeriesLCU Qubrick.

Parameters:

Name Type Description Default
discretization int

The time discretization value.

required
truncation int

The truncation bound value.

required
collision bool

Whether to flag a (time) collision in the time register.

required
hamiltonian PauliSum

A time independent part of the Hamiltinian to simulate.

required
t0 float

A time interval to simulate a Hamiltinian.

required

discretization instance-attribute

discretization: int

truncation instance-attribute

truncation: int

collision instance-attribute

collision: bool

hamiltonian instance-attribute

hamiltonian: PauliSum

t0 instance-attribute

t0: float

probabilities

probabilities()

Return the normalized probabilities for the state preparation routine.

DysonSeriesUnaryIndex dataclass

DysonSeriesUnaryIndex(trunc_reg: Qubits, discret_reg: list[Qubits], be_anc: Qubits, system_reg: Qubits, t_disc_param: int, name: str)

Bases: CompositeRegister

Dataclass for the unary Dyson Series Composite Register.

trunc_reg instance-attribute

trunc_reg: Qubits

discret_reg instance-attribute

discret_reg: list[Qubits]

be_anc instance-attribute

be_anc: Qubits

system_reg instance-attribute

system_reg: Qubits

t_disc_param instance-attribute

t_disc_param: int

name instance-attribute

name: str

initialize classmethod

initialize(qc, name, trunc_param: int, t_disc_param: int, syst: int | Qubits, n_be_anc: int | list)

The unary Dyson Series Expansion composite index register.

Parameters:

Name Type Description Default
qc QPU

A QPU instance.

required
name str

The name of composite register.

required
trunc_param int

Truncation parameter.

required
t_disc_param int

Time-discretization parameter.

required
syst int | Qubits

The system register an operator is applied to.

required
n_be_anc int | list

A register for the operator block encoding.

required

PauliMask

PauliMask(x_mask, z_mask)

Bases: MutableSequence

A PauliMask is representation of a multi-qubit Pauli operator.

Internally, it is represented as a tuple of two ints [x_mask, z_mask] specifying the qubits on which a Pauli acts.

This matches the format for ppr and ppm input in Workbench.

Example

"Z0 I1 Y2 X3" = (0b1100, 0b0101) = (4 + 8, 1 + 4) = (12, 5)

Parameters:

Name Type Description Default
x_mask int

The X mask.

required
z_mask int

The Z mask.

required

mask instance-attribute

mask = (x_mask, z_mask)

from_pauli_string classmethod

from_pauli_string(pauli_string)

Create a PauliMask object given a Pauli string - a string-based representation of the operator.

Parameters:

Name Type Description Default
pauli_string str

A string representing the Pauli operators acting on individual qubits. The expected format includes the character representing the Pauli ('I', 'X', 'Y', 'Z') followed by the qubit index, with whitespace inbetween operators.

required

Returns:

Type Description
PauliMask

The PauliMask object representing the input Pauli string

Example

"Z0 Y2 X3" -> PauliMask(12, 5)

insert

insert(index, value)

Insert a value into the mask.

to_list

to_list()

Casts a PauliMask to a list (for printing).

get_indices

get_indices(pauli_type='full')

Returns indices on which PauliMask acts.

Parameters:

Name Type Description Default
pauli_type str

Which indices to pull. Can either be 'X', 'Y' or 'Z', to pull indices for certain Paulis; or 'full' to pull all indices acted on by Paulis. Defaults to pauli_type='full'.

'full'

Returns:

Type Description
list

The indices acted on by Paulis specified by pauli_type.

get_pauli

get_pauli(index)

Returns the Pauli that acts on qubit labeled by index.

Parameters:

Name Type Description Default
index int

The qubit index to query.

required

Returns:

Type Description
str

The Pauli that acts on the qubit labeled by index.

get_pauli_string

get_pauli_string() -> str

Get a string representing the Pauli operators acting on sequential qubits.

Returns:

Type Description
str

The Pauli string representation of the PauliMask.

Example

PauliMask(12, 5) -> "Z0 Y2 X3"

compressed_length

compressed_length() -> int

Length of Pauli string, without the identity terms.

reverse_masks

reverse_masks(mask_length)

Reverse the qubit order of PauliMasks.

commute_check

commute_check(other)

Check for commutation between two PauliMasks.

Parameters:

Name Type Description Default
other PauliMask

The PauliMask to compare.

required

Returns:

Type Description
bool

Whether the PauliMasks commute.

commutator

commutator(other, drop_phase=True)

Returns the commutator of two PauliMasks.

Parameters:

Name Type Description Default
other PauliMask

The PauliMask to compare.

required
drop_phase bool

Whether the factor of \(2j\varepsilon_{i,j,k}\) in the commutator is retained. Defaults to drop_phase = True.

True

Returns:

Type Description
PauliMask or PauliSum

The commutator without the phase if drop_phase=True (PauliMask) or with the phase if drop_phase=False (PauliSum)

Note

If drop_phase=False, this returns a PauliSum.

Example

For the commutator \([XXY, ZYX]\), the first qubit gives a phase \((-j)\), the second \((j)\), and the third \((-j)\), which totals to 2 negative phases and 1 positive phase. The result is then \(2 \cdot (j)^{1} \cdot (-j)^{2} YZZ = -2j YZZ\).

PauliSum

PauliSum(*mask_tuples)

Bases: MutableSequence

Class for representing Pauli sums.

A PauliSum is a list of two-element lists, where the first element is a numeric coefficient and the second is a PauliMask.

Parameters:

Name Type Description Default
mask_tuples list

The two-element list [coeff, mask].

()

sum instance-attribute

sum = list()

get_mask

get_mask(index)

Returns the mask tuple at position given by index.

get_coefficient

get_coefficient(index)

Returns the real coefficient corresponding to the mask at position given by index.

get_pauli_string

get_pauli_string(index)

Returns the Pauli string corresponding to the mask at position given by index.

get_coefficients

get_coefficients()

Returns all coefficients in the PauliSum.

get_pauli_strings

get_pauli_strings()

Returns all Pauli strings in the PauliSum.

set_mask

set_mask(index, val)

Sets the mask at position index.

set_coefficient

set_coefficient(index, val)

Sets the coefficient at position index.

width

width()

Returns the width of the PauliSum.

The width is the total number of qubits on which the operator acts non-trivially.

wires

wires()

Returns the number of wires on which the PauliSum acts.

Differs from width by including Identity wires.

Example

PauliSum([1.0, PauliMask(10, 10)]) --> Width = 2, Wires = 5

insert

insert(index, term)

Insert a term in the Pauli sum.

add_to_coeff

add_to_coeff(index, addend)

Addition of a scalar to a PauliSum term coefficient.

combine_terms

combine_terms()

Combine all terms that have equivalent masks but inequivalent coefficients.

to_list

to_list()

Casts the PauliSum object to a list, for readability.

stack

stack(addend)

Addition of two PauliSums, without combining terms.

mult_term

mult_term(index, multiplicand)

Multiplication of a particular term by a scalar.

remove_below

remove_below(threshold)

If a term has a coefficient smaller than threshold in absolute value, remove it.

norm

norm()

Calculates a bound on the 1-norm of the PauliSum.

normalize

normalize()

Normalize the PauliSum by dividing all terms by the norm of the PauliSum.

Returns:

Type Description
PauliSum

Normalized PauliSum.

add_identity_offset

add_identity_offset()

Add identity offset term to the PauliSum.

Returns:

Type Description
Tuple[float, PauliMask]

Identity offset (sum of coefficients) to pull eigenvalues into positive reals and PauliSum + Identity term.

get_padded_abs_amplitudes

get_padded_abs_amplitudes()

Extract the weights of each Pauli term and place them in a list.

These will serve as the amplitudes for our auxiliary register.

Note

This function makes the coefficients positive-real valued, assuming the sign is absorbed into the Pauli operators.

Returns:

Type Description
list

List of amplitudes.

commutator

commutator(other)

Compute the commutator of a PauliSum with a PauliSum or PauliMask.

Parameters:

Name Type Description Default
other PauliSum or PauliMask

Second term

required

Returns:

Type Description
PauliSum

Returns the commutator, i.e. [self, other]

Notes

If other is a PauliMask, it assumes a coefficient 1.

SymbolicPauliMask

SymbolicPauliMask(x_weight=None, z_weight=None)

Symbolic version of a PauliMask object.

For symbolics, the only relevant info one might need to extract from a PauliMask is the number of Pauli Xs and the number of Pauli Zs.

Notes

If both x_weight and z_weight default to None, other methods in classes and functions that make use of this class will assume the worse-case scenario where we have a string of Y gates on all qubits.

Parameters:

Name Type Description Default
x_weight (Optional, Parameter)

The number of Pauli Xs. Defaults to None.

None
z_weight (Optional, Parameter)

The number of Pauli Zs. Defaults to None.

None

x_weight instance-attribute

x_weight = x_weight

z_weight instance-attribute

z_weight = z_weight

SymbolicPauliSum

SymbolicPauliSum(num_terms: int | Parameter, average_x_weight: NumberOrParam = 0, average_y_weight: NumberOrParam = 0, average_z_weight: NumberOrParam = 0)

Symbolic version of a PauliSum object.

Given that we can't model exact weights in a Pauli sum symbolically, we model it using average weight values.

Notes
  • Weights used here are non-overlapping, so X weight means "X weight not overlapping with either Y or Z".

Parameters:

Name Type Description Default
num_terms int | Parameter

The number of terms in the sum of Paulis.

required
average_x_weight NumberOrParam

The (average) number of Pauli Xs. Defaults to 0.

0
average_y_weight NumberOrParam

The (average) number of Pauli Ys. Defaults to 0.

0
average_z_weight NumberOrParam

The (average) number of Pauli Zs. Defaults to 0.

0

num_terms instance-attribute

num_terms = num_terms

average_x_weight instance-attribute

average_x_weight = average_x_weight

average_y_weight instance-attribute

average_y_weight = average_y_weight

average_z_weight instance-attribute

average_z_weight = average_z_weight

combined_data_list

combined_data_list(alias_list, threshold_list, num_alias_qubits=None)

Converts classical data specified by alias_list and threshold_list into a combined output list.

This list specifies the classical data to load with a QROM in an alias sampler.

Note

In regular alias sampling, only a single set of data is used, so we can infer the length of the combined terms directly from this data. In multiplexed alias sampling, however, all the sets of data being multiplexed over has to be loaded into the same register, so we need to include a shift not based on the current data, but on the largest set of data being loaded in total. In this case, we need to explicitly pass the number of alias qubits to this function to get the correct shift.

Parameters:

Name Type Description Default
alias_list list

List of alias values.

required
threshold_list list

List of threshold values.

required
num_alias_qubits int

Number of alias qubits. Defaults to None.

None

Returns:

Type Description
list

List of values to load onto alias and keep registers in an alias sampler.

generate_alias_table

generate_alias_table(input_list, bit_precision)

Generates a table of alias and threshold values.

These values come from a distribution specified as a list of relative probabilties.

The cutoff threshold is calculated as being a uniform distribution, i.e. the bar height is \(1/L\) for \(L\) the length of input_list. The number of "boxes" in the discretization (see Fig. 13 in "Encoding Electronic Spectra in Quantum Circuits with Linear T Complexity" (arXiv:1805.03662 ⧉) for details) is given by len(input_list) * 2 ** bit_precision. The values that are returned correspond to:

  • alias_list: The value of the index at the top of the final histogram after the discretization and transformation.
  • threshold_list: The height of the cutoff where one index changes to another.

As a worked example, take the coefficients [1/4, 2/4, 0, 1/4]. There are 4 values, so the height of the uniform distribution is 1/4. The first element is exactly 1/4, so nothing needs to change here: the index corresponding to the top of the bar is 0 and there is only one value in it, so the threshold value is also 0.

The second element is overfull: we take the additional 1/4 and move it into column 2 (using Python indexing). The index corresponding to the top of the bar is 1 and there is only one value in the final column, so the threshold value is 0.

The third element in the prior distribution is 0, but we took 1/4 from the second column and put it in here: the value at the top of the bar thus corresponds to index 1, and there is only one value in the final column, so the threshold value is 0.

Finally, we don't need to change the final value: the alias index is 3 and the threshold value is 0.

Putting it all together, we map:

    [1/4, 2/4, 0, 1/4] -> ([0, 1, 1, 3], [0, 0, 0, 0])
For another example, we have:
    [1/4, 3/8, 1/8, 1/4] -> ([0, 1, 1, 3], [0, 0, 2, 0])

Parameters:

Name Type Description Default
input_list list

List of the relative probabilities of the target distibution.

required
bit_precision int

Number of bits specifying the threshold values.

required

Returns:

Type Description
tuple[list, list]

List of alias values and list of threshold values.

Note

One can pass any list of values, but this function first normalizes the list so that it corresponds to a probability distribution (that is, sum(normalized_input_list) == 1).

calculate_fixed_point_amp_amp_angles

calculate_fixed_point_amp_amp_angles(p_succ, eps_targ)

Compute the optimal number of iterations and reflection angles for fixed-point amplitude amplification.

Parameters:

Name Type Description Default
p_succ float

Initial probability of obtaining the good state.

required
eps_targ float

Target error \(\epsilon\).

required

Returns:

Type Description
Tuple[List[float], List[float]]

The first list (alphas) contains angles for reflections about the initial state, while the second list (betas) contains angles for reflections about the final state.

calculate_vanilla_amp_amp_angles

calculate_vanilla_amp_amp_angles(p_succ)

Compute the optimal number of iterations and reflection angles for fixed-point amplitude amplification.

Reference

Section 2.1 of "Quantum Amplitude Amplification and Estimation" (arXiv:quant-ph/0005055 ⧉).

Note
  • All angles are set to \(\pi\) except for the last, which is adjusted for exact final overlap.
  • The target state is obtained exactly (up to numerical precision).

Parameters:

Name Type Description Default
p_succ float

Initial probability of obtaining the good state.

required

Returns:

Type Description
Tuple[List[float], List[float]]

Angles for amplitude amplification reflections.

get_final_reflection_angle

get_final_reflection_angle(optimal_full_refls, p_succ)

Compute the optimal final angles for vanilla amplitude amplification.

Notes
  • The equation is complex, so optimization is used to determine the best angles.
  • Optimal angles minimize the difference in Eq. (12) from "Quantum Amplitude Amplification and Estimation" (arXiv:quant-ph/0005055 ⧉).

Parameters:

Name Type Description Default
optimal_full_refls int

Number of full reflections needed.

required
p_succ float

Initial probability of obtaining the good state.

required

Returns:

Type Description
Tuple[List[float], List[float]]

Tuple of angles (in degrees) for the final AA reflection. The first value is for reflection around the initial state, and the second for reflection around the good state.

num_comps_lower_bound

num_comps_lower_bound(num_regs)

Lower bound on the number of comparators used in a bitonic sort.

The expression can be found in the Wikipedia article on bitonic sorter ⧉.

Parameters:

Name Type Description Default
num_regs int

Number of registers we are sorting.

required

Returns:

Type Description
int

Lower bound of number of comparators used.

num_comps_upper_bound

num_comps_upper_bound(num_regs)

Upper bound on the number of comparators used in a bitonic sort.

The expression can be found in the Wikipedia article on bitonic sorter ⧉.

Parameters:

Name Type Description Default
num_regs int

Number of registers we are sorting.

required

Returns:

Type Description
int

Upper bound of number of comparators used.

permutation_parity

permutation_parity(permutation)

Determine the parity of the given permutation.

Parameters:

Name Type Description Default
permutation List[int]

List of integers with no collisions.

required

Returns:

Type Description
bool

True if even parity, False if odd parity.

prob_no_collision

prob_no_collision(num_regs, prob_knob)

Probability of finding no collisions in measured seed register.

We can calculate the probability of observing no collisions, and thus, the probability of continuing the antisymmetrization procedure after measuring all of the seed registers as a function of the number of registers we sort, and a user-input value, which one can tune to the probability.

In "Improved Techniques for Preparing Eigenstates of Fermionic Hamiltonians" (arXiv:1711.10460 ⧉), the probability of observing a collision is upperbounded by the expression shown in Eqn. (A5):

\[\eta (\eta - 1) / 2f\]

Here \(\eta\) is the number of registers we are sorting, and \(f\) is a tunable knob. The probability of not observing a collision is simply 1 minus this quantity. This upper bound is valid only for values of \(f >= \eta\).

Ensuring a probability of success of at least 1/2 for all \(\eta\) requires \(f = \eta^2\).

Parameters:

Name Type Description Default
num_regs int

Number of registers we are sorting.

required
prob_knob int

A tunable knob to determine the probability of success.

required

Returns:

Type Description
float

The probability of not observing a collision.

seed_reg_size

seed_reg_size(prob_knob)

Compute the size of each seed register.

The size per seed register is determined by the tunable knob value chosen to parametrize the probability of success of the seed reg sort.

Parameters:

Name Type Description Default
prob_knob int

A tunable knob to determine the probability of success.

required

Returns:

Type Description
int

Size of each seed register.

total_sort_num_comps

total_sort_num_comps(num_regs, low=0, cnt=None, acc=0)

Numerically determine the number of comparators in a bitonic sort.

In addition to upper and lower bounds on the number of necessary comparators, we can determine the exact number used numerically by accumulating a counter and recursively calling this function in the same call-path structure used by the sorting methods in the bitonic sort Qubrick.

Parameters:

Name Type Description Default
num_regs int

Number of registers we are sorting.

required
low (int, Optional)

Index at which the sequence to be sorted starts. Defaults to (and starts at) 0.

0
cnt (Optional, int)

Number of elements to be sorted. Defaults to (and starts at) None, in which case we calculate the first number of elements.

None
acc (int, Optional)

An accumulator we simply increment to keep track of the number of comparators. Defaults to (and starts at) 0.

0

Returns:

Type Description
int

The exact number of comparators used in a bitonic sort.

build_zoo

build_zoo()

Build the qubrick zoo.

find_all_qubricks

find_all_qubricks(packages)

Returns all functions in all subpackages of all supplied packages.

find_all_subpackages

find_all_subpackages(package)

Import all submodules of a module, recursively, including subpackages.

get_all_notebooks

get_all_notebooks()

Scan the tutorials directory and return a list of jupyter notebooks.

get_tutorial_notebooks_for_qubricks

get_tutorial_notebooks_for_qubricks(qubrick)

Loop through the list of notebooks and pull out any that mention the qubrick provided.

elbow_count_unoptimized

elbow_count_unoptimized(num_elements, is_controlled=False)

Helper to calculate subtractive constant in SELECT cost.

Parameters:

Name Type Description Default
num_elements int or Integer

Number of elements in list to load.

required
is_controlled bool

Whether the SELECT is controlled or not. Defaults to False.

False

Returns:

Type Description
int

A constant for the cost expression of SELECT.

elbow_subtractive_const

elbow_subtractive_const(num_elements, is_controlled=False)

Helper to calculate subtractive constant in SELECT cost.

Parameters:

Name Type Description Default
num_elements int or Integer

Number of elements in list to load.

required
is_controlled bool

Whether the SELECT is controlled or not. Defaults to False.

False

Returns:

Type Description
int

A constant for the cost expression of SELECT.

gate_efficient_lambda

gate_efficient_lambda(num_elements, b)

Helper to handle choice of lambda value.

Parameters:

Name Type Description Default
num_elements int

Number of elements in list to load.

required
b int

b-bit precision for elements in list.

required

Returns:

Type Description
int

lambda value that yields minimal Toff count for QROM.

Notes
  • This computes the gate-optimal lambda assuming doing one Select-SwapUp pair.
  • If you are using dirty QROMs, you should double-check against the case of doing a naive QROM (i.e. not using SwapUp at all).

get_fixup_addresses

get_fixup_addresses(mmt_result, restacked_list, b_of_p, num_regs, num_addresses)

Get list of QROM addresses requiring a phase fixup.

The measurement of the output/data register during the uncomputation of a data lookup circuit probabilistically flips the sign of some of the addresses encoded by the index register. To complete the routine, we must determine which addresses have had their sign flipped, and then perform a phase fixup for each one.

An address requires a phase fixup if its corresponding entry in the lookup table toggles an odd number of qubits that have also returned an "ON" measurement result.

Appendix C in "Qubitization of Arbitrary Basis Quantum Chemistry Leveraging Sparsity and Low Rank Factorization" (arXiv:1902.02134 ⧉).

Parameters:

Name Type Description Default
mmt_result int

The measurement result returned after reading the output register in a QROM (including "clean" and "junk" qubits).

required
restacked_list list

That same data after it has been restacked.

required
b_of_p int

Number of bits used to represent each item in the original unscrambled list.

required
num_regs int

Number of copies of the output reg; a tunable knob used to trade off between gates and qubits in QROMs.

required
num_addresses int

The number of addresses that may possibly need a fixup. Typically equal to the length of the original input data.

required

Returns:

Type Description
list[int]

A list of each address (int) that requires a phase fixup.

load_all_at_once

load_all_at_once(target_reg, data, ctrl=0)

Load all values at the same time.

This simply corresponds to the case where the number of output registers you have equals the number of items to load. In this case, we are not actually "multiplexing", in the sense that we apply the data on the target register without quantum conditioning.

Parameters:

Name Type Description Default
target_reg Qubits

Register where we load the data.

required
data list

The data to load. It's actually a single item to be applied across all target qubits.

required
ctrl (Qubits, int)

A register to control on. Defaults to zero, meaning no control.

0

make_fixup_table

make_fixup_table(fixup_addresses, loaded_data)

Construct the fixup table for unloading data via QROM.

Each element is either a one or a zero, corresponding to whether a particular address requires or does not require an X gate to be applied by a smaller QROM to fix up the phase.

Parameters:

Name Type Description Default
fixup_addresses list

List of addresses that require phase fixups.

required
loaded_data list

Data loaded by a QROM.

required

Returns:

Type Description
list

List of zeros and ones where each value at a particular index corresponds to applying or not applying an X gate.

partition_index_register

partition_index_register(index_reg, data, lambda_val)

Determine the SELECT and SwapUp subregisters of the index register.

Parameters:

Name Type Description Default
index_reg Qubits

Index register for QROM.

required
data list

List of data to load.

required
lambda_val int

Power-of-two knob to trade off between gates and qubits.

required

Returns:

Type Description
tuple

A tuple of qubits objects corresponding to slices of the index register iterated over by SELECT and SwapUp. Depending on the if/else branches, one or the other (but never both) may evaluate to None.

restack_bitlist

restack_bitlist(data, num_regs, b_of_p)

Given a list of different bitstring values, restack the bits into groups of OR'd bits.

The b_of_p and lambda values will affect the grouping. As an example, suppose I have a list of 4 values, each represented by 2 bits (in big endian), and I use a lambda value of 2 to restack items:

bit_list = [2, 3, 3, 0] --> in binary --> [10, 11, 11, 00]

We then restack the list so that we now have:

new_list = [1011, 1100] --> in decimal --> [9, 12]

Parameters:

Name Type Description Default
data list

List of values indexed by the index register.

required
num_regs int

Number of copies of output registers.

required
b_of_p int

Number of bits in per datum.

required

Returns:

Type Description
list

Restacked data.

symbolic_elbow_count_unoptimized

symbolic_elbow_count_unoptimized(num_elements, is_controlled=False)

Helper to calculate subtractive constant in SELECT cost.

Parameters:

Name Type Description Default
num_elements int

Number of elements in list to load.

required
is_controlled bool

Whether the SELECT is controlled or not. Defaults to False.

False

Returns:

Type Description
Function

Callable to allow for calculating the subtractive constant symbolically.

symbolic_elbow_subtractive_const

symbolic_elbow_subtractive_const(num_elements, is_controlled=False)

Helper to calculate subtractive constant in SELECT cost.

Parameters:

Name Type Description Default
num_elements int

Number of elements in list to load.

required
is_controlled bool

Whether the SELECT is controlled or not. Defaults to False.

False

Returns:

Type Description
Function

Callable to allow for calculating the subtractive constant symbolically.

symbolic_gate_efficient_lambda

symbolic_gate_efficient_lambda(num_elements, b)

Symbolic mimic of the above function.

Parameters:

Name Type Description Default
num_elements Parameter

Number of elements in list to load.

required
b Parameter

b-bit precision for elements in list.

required

Returns:

Type Description
Function

Callable to allow for calculating the gate efficient lambda symbolically.

validate_qrom_input_params

validate_qrom_input_params(data, b, lambda_val=None)

Checks that the supplied input parameters are valid for use in QROM.

There are several checks that can be done on the inputs to QROM (of all flavors) to ensure that sensible outputs are computed. The checks vary from warnings (for possibly unintentional but still valid operations such as insufficient precision bits resulting in integer overflow) to exceptions (for invalid operations such as non-power-of-2 lambda values).

Parameters:

Name Type Description Default
data (PauliSum, List[int])

Hamiltonian terms expressed as a PauliSum or a list of bitvalues to load.

required
b int

Number of bits to represent item in list.

required
lambda_val int

Power-of-two knob to trade off between gates and qubits. If None (default), then optimal lambda is calculated.

None

Returns:

Type Description
int

The processed lambda value.

deprecate_location

deprecate_location(new_path: str, until: str | None = None, warn_msg: str | None = None) -> Callable

Can be used as a wrapper when moving a function to indicate that the current location will be deprecated.

Parameters:

Name Type Description Default
new_path str

import-path to the new function. Example: 'package.module.function'

required
until optional

At what version is the old function location deprecated? Example: '3.0.0'

None
warn_msg optional

A specific warning message to use.

None

Returns:

Type Description
callable

The wrapped function.

Example
@deprecate_location('new_module.some_func')
def some_func(*args, **kwargs):
    pass

get_deprecations_from

get_deprecations_from(version: str | None = None) -> Iterable[str]

Returns the deprecation decorators remaining after the specified version.

Note

Deprecations are only included if the module they live in is loaded.

Parameters:

Name Type Description Default
version str | None

include deprecations at and before this version. Example: '3.0.0' Default: include all deprecations.

None

Yields:

Type Description
str

The path to the deprecated function.

dyson_series_numpy

dyson_series_numpy(trunc_param, t_disc_param, t, H0, V, flag_collision)

Compute the matrix representation of the (K, M)-Dyson series.

Computes the matrix representation of the K-truncated & M-discretized Dyson series:

\[\sum_{k = 0}^{K} (\frac{- i t}{k! M})^k (k! B_k + C_k)\]

Here

\[B_k = \sum_{0 \le m_1 < m_2 < ... < m_k < M} \prod_{j=1}^{k} \exp{(i H_0 t m_i/ M)} V \exp{(- iH_0 t m_i/ M)}\]

and \(C_k = 0\) if one desires to exclude the collisions. To keep the collisions, \(C_k\) captures terms simuilar to \(B_k\) but where at least one pair of indices \(m_j = m_d\) collide for \(j \neq d\). See eq.16 in "Hamiltonian Simulation in the Interaction Picture" (arXiv:1805.00675 ⧉).

Parameters:

Name Type Description Default
trunc_param int

Truncation.

required
t_disc_param int

Discretization.

required
t float

Time.

required
H0 ndarray

Hermitian operator (diagonal operator, time dependent).

required
V ndarray

Hermitian operator (offdiagonal operator, time independent).

required
flag_collision bool

If flag_collision == True, the collisions will be flagged and the flag being in the 0 states excludes the collisions (\(C_k = 0\)). If flag_collision == False, the collisions will not be flagged and thus, will be included (\(C_k \neq 0\)).

required

Returns:

Type Description
ndarray

the matrix representation of the (trunc_param, t_disc_param)-Dyson series.

dyson_target_prob

dyson_target_prob(t0, cutoff)

Compute the normalized probabilities for the state preparation routine (Dyson Series).

Parameters:

Name Type Description Default
t0 float

Time step.

required
cutoff int

Cutoff of the Dyson series.

required

evaluate_ham

evaluate_ham(t, H0, V)

Evaluate the operator of the form \(V(t)=\exp(iH_0t)V\exp(-iH_0t)\).

Parameters:

Name Type Description Default
t float

Evolution time.

required
H0 array

Matrix representation of the fast-forwardable part of the Hamiltonian.

required
V array

Matrix representation of the perturbation part of the Hamiltonian.

required

Returns:

Type Description
array

The result of evaluating the operator \(V(t)\).

norm_beta

norm_beta(t0, cutoff)

Compute normalization beta (Dyson series).

Parameters:

Name Type Description Default
t0 float

Time step.

required
cutoff int

Cutoff of the Dyson series.

required

num_qubits_DysonSeriesExpansionIndex

num_qubits_DysonSeriesExpansionIndex(trunc_param, t_disc_param, syst, n_be_anc, reg_type='unary') -> int

Calculate the total size of the Dyson register.

Parameters:

Name Type Description Default
trunc_param int

Truncation parameter.

required
t_disc_param int

Time-discretization parameter

required
n_be_anc int

Size of the register for block-encoding ancilla qubits.

required
syst int | Qubits

The system register an operator is applied to.

required
reg_type str

Type of the truncation register of the Dyson Series (unary or binary).

'unary'

Returns:

Type Description
int

The total number of qubits required for the Dyson Series expansion.

fetch_h2_gs_data

fetch_h2_gs_data(bond_length)

Returns ground state energy and wavefunction for checking.

Parameters:

Name Type Description Default
bond_length float

H-H bond length, in Angstroms.

required

Returns:

Type Description
g_energy (float

Ground state energy.

g_state (list

Ground state wavefunction.

fetch_h2_gs_prep_angle

fetch_h2_gs_prep_angle(bond_length)

Returns ground state preparation circuit parameter.

Parameters:

Name Type Description Default
bond_length float

H-H bond length, in Angstroms.

required

Returns:

Type Description
angle (float

Ground state preparation circuit parameter.

generate_h2_hamiltonian

generate_h2_hamiltonian(bond_length)

Generate the hydrogen Haimltonian given a bond length.

Parameters:

Name Type Description Default
bond_length float

One of [0.2, 0.5, 0.7, 1.0, 2.0].

required

Returns:

Type Description
PauliSum

H2 Hamiltonian.

get_exactly_representable_qubitized_hamiltonian

get_exactly_representable_qubitized_hamiltonian(alpha, bits_of_precision)

Returns a Hamiltonian where \(\arccos(\lambda)\) is exactly representable with bits_of_precision bits.

Note

Only the first excited state of this hamiltonian is guaranteed to be an energy that corresponds to a phase that is exactly representable using the input bits_of_precision.

Parameters:

Name Type Description Default
alpha float

Arbitrary coefficient which determines the specific type of Hamiltonian.

required
bits_of_precision int

Number of bits the phase is to be measured to. Must be greater than 2.

required

Returns:

Type Description
Tuple[PauliSum, float]

The Hamiltonian and the eigenvalue.

h2_ground_state_prep

h2_ground_state_prep(qc, sys_reg, ansatz_param)

Circuit for ground state preparation for H2.

Parameters:

Name Type Description Default
qc QPU

QPU

required
sys_reg Qubits

System register to implement state preparation.

required
ansatz_param float

Ground state prep circuit parameter (in Radians).

required
Notes

See Fig. 1 of "Scalable Quantum Simulation of Molecular Energies" (arXiv:1512.06860 ⧉).

cheb_t

cheb_t(L, x)

Generalized Chebyshev polynomial definition.

Chebyshev polynomials are defined as

\[T_L(\theta) = \cos(L\theta)\]

where \(L\) is an integer defining the Chebyshev polynomial (we say "the \(L\) th Chebyshev polynomial). If we replace \(x\) with \(\cos(\theta)\), we get

\[T_L(x) = \cos(L\arccos(x))\]

We can generalize this expression in two different ways: first, we can allow for values of \(x\) that lie outside of \([-1, 1]\) by making use of hyperbolic trig functions; and second, we can allow for non-integer values of \(L\), simply by plugging them in.

See the Wikipedia page for Chebyshev polynomials ⧉ for a derivation of the trig expressions and "Fixed-point quantum search with an optimal number of queries" (arXiv:1409.3305 ⧉) for an example of where these generalized Chebyshev functions can be used.

This function implements the most general form of Chebyshev polynomial as described above.

Parameters:

Name Type Description Default
L float

Multiplier inside the trig functions. For a standard Chebyshev polynomial, this is an integer corresponding to the degree of the polynomial, but for this function L can be any real number.

required
x float

Point at which to evaluate the Chebyshev function. For a standard Chebyshev polynomial, this should satisfy abs(x) <= 1, but for this function x can be any real number.

required

Returns:

Type Description
float

The output of the generalized Chebyshev polynomial.

closest_octant

closest_octant(phase)

Finds the closest octant.

Given a phase on the unit circle, returns the nearest value on that circle in the set {0/8, 1/8, 2/8, 3/8, 4/8, 5/8, 6/8, 7/8}.

Parameters:

Name Type Description Default
phase float

A phase in the interval [0, 1].

required

Returns:

Type Description
int

The closest octant on the unit circle.

Example

If phase = 0.49, the closest octant is 4/8 and the functions returns 4.

discretized_prob_distribution

discretized_prob_distribution(input_list, bit_precision)

Discretized a probability distrubution.

Given a list of n probabilities, return a list of integers corresponding to the number of "boxes" of weights value_per_block.

Parameters:

Name Type Description Default
input_list List[float]

Probability distribution.

required
bit_precision int

Number of bits used to represent items in probability distribution.

required

Returns:

Type Description
List(int)

Discretized probability distribution.

Note

Might have smarter way of doing this. The idea is to ensure that the final discretized probability distribution is still normalized by adjusting the total number of boxes. This adjustment is done by adding or removing one box to the histogram where the rounding error was the worst. This means that the adjustment is going to increase the error on that specific probability. The error from rounding is usually \(\pm\frac{2^{-b}}{n}\) (where \(b\) is the number of bits of precision and \(n\) is the number of boxes), but on that probability it's going to be:

Rounding error for all but one probability: \(-\frac{2^{-b}}{2n}\) < (val - rounded) < \(\frac{2^{-b}}{2n}\)

Rounding error for the adjusted one: \(-\frac{2^{-b}}{n}\) < (val - rounded) < \(-\frac{2^{-b}}{2n}\) OR \(\frac{2^{-b}}{2n}\) < (val - rounded) < \(\frac{2^{-b}}{n}\)

pauli_sum_to_numpy

pauli_sum_to_numpy(ham: PauliSum)

Takes a PauliSum Hamiltonian and converts it to a NumPy array representation for easier numerics.

Notes
  • Follows a big-endian bit ordering, where the most significant bit is stored first (on the left) and the least significant bit last (on the right).
  • May need reordering using the Workbench reverse_numpy_op utility function for compatibility with vectors directly extracted from Workbench.
  • Depending on your use case, it might be faster to use pauli_sum_to_sparse(ham).toarray() to get a the numpy representation that would be in the same ordering as Workbench than using reverse_numpy_op(pauli_sum_to_numpy(ham)).

Parameters:

Name Type Description Default
ham PauliSum

PauliSum representation of the operator to be turned into a NumPy representation.

required

Returns:

Type Description
ndarray

Representation of the operator described by ham.

Examples:

ham = PauliSum([0.5, PauliMask(1, 0)], [0.5, PauliMask(1, 1)])
pauli_sum_to_numpy(ham)

>>> np.array([[0., 0.5-0.5j],
            [0.5+0.5j, 0.]])
ham2 = PauliSum([1.0, PauliMask(1, 2)])
# Note the qubit ordering -- this yields XZ not ZX (opposite to Workbench ordering)
pauli_sum_to_numpy(ham2)

>>> np.array([[ 0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
            [ 0.+0.j,  0.+0.j,  0.+0.j, -1.+0.j],
            [ 1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j],
            [ 0.+0.j, -1.+0.j,  0.+0.j,  0.+0.j]])

Example of Workbench ordering (little-endian):

qc = QPU(num_qubits=2)
qc[0].x()
qc.pull_state()

>>> np.array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j])

pauli_sum_to_sparse

pauli_sum_to_sparse(ham: PauliSum)

Takes a PauliSum Hamiltonian and converts it to a Scipy sparse (csr) representation for easier numerics.

Note

Depending on your use case, it might be faster to use pauli_sum_to_sparse(ham).toarray() to get a the numpy representation that would be in the same ordering as Workbench than using reverse_numpy_op(pauli_sum_to_numpy(ham)).

Parameters:

Name Type Description Default
ham PauliSum

PauliSum representation of the operator to be turned into a sparse matrix representation.

required

Returns:

Type Description
csr_matrix

Representation of the operator described by ham.

Example
ham = PauliSum([0.5, PauliMask(1, 0)], [0.5, PauliMask(1, 1)])
pauli_sum_to_sparse(ham).toarray()

>>> np.array([[0., 0.5-0.5j],
            [0.5+0.5j, 0.]])
ham2 = PauliSum([1.0, PauliMask(1, 2)])
pauli_sum_to_sparse(ham2).toarray()

>>> np.array([[ 0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
            [ 0.+0.j,  0.+0.j,  0.+0.j, -1.+0.j],
            [ 1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j],
            [ 0.+0.j, -1.+0.j,  0.+0.j,  0.+0.j]])

random_pauli_sum

random_pauli_sum(wires: int, num_terms: int, low: float = 0.1, high: float = 180.0, group_like: bool = False, include_identity: bool = True, random_number_generator: Generator | None = None)

Generate a random PauliSum.

Parameters:

Name Type Description Default
wires int

Number of qubits acted on. Must be greater than zero.

required
num_terms int

Number of terms in PauliSum.

required
low float

Smallest coefficient to use. Defaults to 0.1.

0.1
high float

Largest coefficient to use. Defaults to 180.

180.0
group_like bool

Whether or not to group two PauliSum terms if they share the same x_mask and z_mask. Defaults to False.

False
include_identity bool

Whether to allow for identity terms to be included in the PauliSum. Defaults to True.

True
random_number_generator Generator | None

Generator for the random coefficients. Defaults to None.

None

Returns:

Type Description
PauliSum

A random PauliSum instance with num_terms number of terms acting on wires many qubits.

Notes
  • It is possible (but unlikely) to generate a trivial PauliSum where all terms have x_mask == z_mask == 0. In this case, the return of wires() will equal 0, and will not match the input wires arg. To avoid this, we run a while loop until we generate a non-trivial PauliSum.

  • Setting group_like = True means terms with the same masks are grouped into a single term with the sum of those terms' coefficients. This can result in the following (potentially unexpected) behavior:

    • len(psum) <= num_terms.
    • The smallest coefficient may be smaller than low.
    • The largest coefficient may be larger than high.

calculate_holevo_variance

calculate_holevo_variance(phases, probabilities)

Calculate the Holevo variance given a set of phases and their associated probabilities.

Parameters:

Name Type Description Default
phases List[float]

List of phases obtained from QPE, each between [0, \(2\pi\)].

required
probabilities List[float]

List of probabilities associated with each phase.

required
Note

The phases from running QPE calculation are in the range [0, 1] and should be multiplied by \(2\pi\) to be scaled to [0, \(2\pi\)] before being passed to this function.

clopper_pearson_lower

clopper_pearson_lower(num_successes, num_trials, fail_prob)

Evaulates the estimated lower bound to the Binomial confidence interval, via a Clopper-Pearson test.

Parameters:

Name Type Description Default
num_successes int

The number of successful trials.

required
num_trials int

The total number of trials.

required
fail_prob float

The tolerable probability of failure (i.e. that the true value lies outside the confidence interval).

required

Returns:

Type Description
float

The Clopper-Pearson lower bound to the confidence interval.

clopper_pearson_max_error

clopper_pearson_max_error(num_successes, num_trials, fail_prob)

Calculates the maximum error using Clopper-Pearson.

Returns the value furthest from the point estimate that still lies within the Clopper-Pearson confidence interval.

Parameters:

Name Type Description Default
num_successes int

The number of successful trials.

required
num_trials int

The total number of trials.

required
fail_prob float

The tolerable probability of failure (i.e. that the true value lies outside the confidence interval).

required

Returns:

Type Description
float

The value furthest from the point estimate that still lies in the confidence inteval.

clopper_pearson_upper

clopper_pearson_upper(num_successes, num_trials, fail_prob)

Evaluates the estimated upper bound to the Binomial confidence interval, via a Clopper-Pearson test.

Parameters:

Name Type Description Default
num_successes int

The number of successful trials.

required
num_trials int

The total number of trials.

required
fail_prob float

The tolerable probability of failure (i.e. that the true value lies outside the confidence interval).

required

Returns:

Type Description
float

The Clopper-Pearson upper bound to the confidence interval.

energy_to_phase_qubitization

energy_to_phase_qubitization(energy, norm)

Convert an eigenvalue to a phase.

Parameters:

Name Type Description Default
energy float

Energy eigenvalue of Hamiltonian.

required
norm float

Norm of Hamiltonian.

required

Returns:

Type Description
float

Exact phase corresponding to the energy eigenvalue

get_most_probable_phase

get_most_probable_phase(phase_qubits)

Get the most probable phase from a qubit register typically output after running phase estimation.

Note

This function is only designed for a qubit register of type QUFixed.

Parameters:

Name Type Description Default
phase_qubits QUFixed

A register of qubits, typically representing phase qubits after phase estimation.

required

Returns:

Type Description
float

The most probable phase to read.

hartree_to_ev

hartree_to_ev(energy)

Converts Hartree to electronVolts.

Parameters:

Name Type Description Default
energy float

The energy in Hartree.

required

Returns:

Type Description
float

The energy in eV.

num_trials_chernoff

num_trials_chernoff(precision, fail_prob)

Calculate the number of trials using the Chernoff bound.

Returns the number of trials needed for an estimate to be returned within a desired precision with a given fail probability, from the vanilla Chernoff bound.

Note
  • Deprecated in favour of the Clopper-Pearson tests, below.

optimal_holevo_variance

optimal_holevo_variance(n_precision_qubits)

Calculate the optimal Holevo variance for a given number of bits of precision m as per Eq. 10 in "Optimum phase estimation with two control qubits" (arXiv:2303.12503 ⧉).

Parameters:

Name Type Description Default
n_precision_qubits int

Number of bits of precision.

required

peek_ipea_phase

peek_ipea_phase(qc, ancilla, phase_sign_fixed=False)

Extracts the exact phase given to an eigenstate.

Parameters:

Name Type Description Default
qc QPU

The QPU instance.

required
ancilla Qubits

The output ancilla for IPEA.

required
phase_sign_fixed bool

Whether the sign of the kicked-back phase is known in advance, or whether it needs to be determined. The former is useful for qubitization, and the latter for Trotterization.

False

Returns:

Type Description
phase (float

The exact phase given to an eigenstate.

phase_from_cs

phase_from_cs(sine, cosine)

Calculates a phase from the sine and cosine.

Extracts an estimate of the phase, \(\phi\), given an estimate of \(\cos(2 \pi \phi)\) and \(\sin(2 \pi \phi)\).

Parameters:

Name Type Description Default
sine float

An estimate of \(\sin(2 \pi \phi)\).

required
cosine float

An estimate of \(\cos(2 \pi \phi)\).

required

Returns:

Type Description
float

An estimate of the phase, \(\phi\).

Note

The output phase is in \([0,1]\) (not \([0, 2\pi]\), or \([-\pi, \pi]\)).

phase_to_energy_qubitization

phase_to_energy_qubitization(phase, norm)

Convert a phase to an eigenvalue.

Parameters:

Name Type Description Default
phase float

Phase found using IPEA.

required
norm float

Norm of Hamiltonian.

required

Returns:

Type Description
float

Energy eigenvalue of Hamiltonian.

phase_to_energy_time_evolution

phase_to_energy_time_evolution(output, bits_precision, offset=0, rescaling_factor=1)

Converts a measured phase to an eigenenergy, when estimating the phase of \(\exp(iHt)\).

Parameters:

Name Type Description Default
output int

The bits of output from phase estimation.

required
bits_precision int

The number of bits of precision.

required
offset float

A constant factor to add to the eigenenergy (for example, if the Hamiltonian had an identity term that has been skimmed off).

0
rescaling_factor float

A factor to account for rescaling of the Hamiltonian before simulation.

1

Returns:

Type Description
float

The estimated eigenphase.

apply_controlled_pauli_term

apply_controlled_pauli_term(data, system, ctrl)

We see this subroutine everywhere we deal with Hamiltonians.

Basically, we inspect the data term to see if we should apply some controlled \(X\), \(Y\), or \(Z\) surrounded by Cliffords indexed by some register to be applied to another.

Parameters:

Name Type Description Default
data list or int

A single term of a PauliSum (int), or a list of two elements: a coefficient (float) and a PauliMask.

required
system Qubits

System qubits that Paulis apply on.

required
ctrl (int, Qubits)

Control qubits for the Pauli term to be applied. Defaults to zero.

required

get_default_used_indices

get_default_used_indices(data, non_zero_only=True)

Given a PauliSum or a list of integers, return a list of indices where ops are applied.

Parameters:

Name Type Description Default
data list or PauliSum

Data to be multiplexed over.

required
non_zero_only (Optional, bool)

Whether to only return indices corresponding to non-zero data elements. Defaults to True.

True

Returns:

Type Description
list

List of integers corresponding to the indices where data terms occur.

get_pauli_weights_symbolic

get_pauli_weights_symbolic(num_tgt: Parameter, data: SymbolicArray | SymbolicPauliSum) -> tuple[Parameter, Parameter, Parameter]

Average weight of terms in a symbolic PauliSum.

This function is meant to facilitate retrieving the X and Z weights for data meant to be loaded by SELECT Qubricks. This function is called inside of estimate methods, and thus is inaccessible to the user, precluding them from inputting any weight information. Any and all information about X and Z weights should be set as attributes of the passed data.

Parameters:

Name Type Description Default
num_tgt Parameter

Number of qubits the data acts/is loaded on.

required
data SymbolicArray | SymbolicPauliSum

Symbolic representation of Hamiltonian terms or bitvalues to load.

required

Returns:

Type Description
tuple[Parameter, Parameter, Parameter]

Average Pauli X, Y and Z weights of input data.

Notes
  • SELECT Qubricks in Workbench Algorithms can take as input both PauliSum objects and lists of bitstrings; correspondingly, symbolic estimators for SELECT Qubricks take both SymbolicPauliSum objects and SymbolicArrays.
  • Loading a b-bit number corresponds to applying a Pauli X gate on each target qubit where the bit value is 1. Since SymbolicArray corresponds to loading a list, we set the Y & Z weights to zero.
  • Like lists, SymbolicArray has no Hamming weight attribute. If loading a SymbolicArray, this function treats it as arbitrary data and sets X weight to the average Hamming weight. If the user wants to put more knowledge about the average Hamming weight of the loaded values, one can instead pass a SymbolicPauliSum with zero Z weight and a chosen X weight.

get_all_grays

get_all_grays(angles)

Apply get_gray_angles to a list of lists of angles.

Parameters:

Name Type Description Default
angles list

List of list of angles

required

Returns:

Type Description
list

List of list of single qubit gray angles

get_angles

get_angles(amps, num_qubits=None)

Equations 5 and 8 in "Transformation of quantum states using uniformly controlled rotations" (arXiv:quant-ph/0407010 ⧉).

Parameters:

Name Type Description Default
amps list

List of amplitudes.

required
num_qubits (Optional, int)

Number of qubits the amplitudes will be loaded to. Defaults to None.

None

Returns:

Type Description
(list, list)

List of list of angles for \(Z\) rotations and list of list of angles for \(Y\) rotations.

get_gray_angles

get_gray_angles(angles)

Given list of angles for uniform rotations, return angles for single qubit rotations.

Follows equation 3 in "Transformation of quantum states using uniformly controlled rotations" (arXiv:quant-ph/0407010 ⧉).

Parameters:

Name Type Description Default
angles list

List of angles.

required

Returns:

Type Description
list

List of single qubit rotation angles.

Note

The "dot" in the equation is a bitwise dot product.

get_usp_angle

get_usp_angle(d)

Calculates the rotation angle needed for USP.

Parameters:

Name Type Description Default
d int

The number of elements in the uniform superposition.

required

Returns:

Type Description
float

The rotation angle for USP, in degrees.

big_reg_to_list

big_reg_to_list(big_reg, size)

Converts a big input Qubits register into a list of smaller Qubits.

Parameters:

Name Type Description Default
big_reg Qubits

Big register given as input.

required
size int

Number of qubits on sub-registers.

required

Returns:

Type Description
list

List of qubit registers of size size each.

bit_swap

bit_swap(bitstring, p1, p2, num_bits)

Swap the p1'th and the p2'th bits of an input bitstring.

Parameters:

Name Type Description Default
bitstring int

Bitstring given as an integer.

required
p1 int

Position of the first bit sequence.

required
p2 int

Position of the second bit sequence.

required
num_bits int

How may bits to swap.

required

Returns:

Type Description
int

A new bitstring with bits swapped.

reg_swap

reg_swap(bitstring, p1, p2, num_bits)

Swap the p1'th and the p2'th registers of an input bitstring.

This function performs the same bitwise logic as bit_swap, but here we interpret the position arguments as indexes for an entire register made up of some number of bits rather than as indexes to the position of particular bits. It's really just a convenience to not have to constantly consider shifting indices by num_bits amount.

Parameters:

Name Type Description Default
bitstring int

Bitstring given as an integer.

required
p1 int

Position of the first register.

required
p2 int

Position of the second register.

required
num_bits int

Number of bits per register.

required

Returns:

Type Description
int

A new bitstring with bits swapped.

reshuffled_bitmask

reshuffled_bitmask(index_val, bitmask, num_regs, reg_size)

Calculate the reshuffled bitmask resulting from permuting bits.

This function serves as a bookeeping tool to keep track of the resulting reshuffled bitmask on the entirety of a register that has undergone a swap network. Given an index value as input, the swap network assumed by this function moves the indexed register to the topmost (least significant in little endian notation) position in the reshuffled bitmask.

The resulting bitmask on the rest of the input bits is generally ignored and not made use of. In fact, there are arbitrarily many permutations one could opt for. This function assumes a particular reshuffling permutation. The reshuffling done here follows the same pattern performed by our SwapUp Qubricks. Using this function, you can now uniquely associate an input index with an output value written on all the qubits in the target register rather than only the top reg_size many qubits.

Parameters:

Name Type Description Default
index_val int

Address value we input which then results in a reshuffling of the input bitmask.

required
bitmask int

Integer value encoded on some bits prior to reshuffling.

required
num_regs int

Number of registers we are permuting.

required
reg_size int

The number of bits per register.

required

Returns:

Type Description
int

The reshuffled bitmask, given as an integer.

cmnrs_analytic_bound

cmnrs_analytic_bound(hamiltonian, trotter_error, trotter_order=2)

Analytic bound for the Trotter error.

Implementation of the "analytic" Trotter error bound in "Toward the first quantum simulation with quantum speedup" arXiv:1711.10980 ⧉ (Eqs. 61, 70), with the modification that \(L*\Lambda\) is replaced with the sum of the coefficients of the Hamiltonian.

Parameters:

Name Type Description Default
hamiltonian PauliSum

The Hamiltonian for which the number of Trotter steps is to be estimated.

required
trotter_error float

The allowable Trotter error.

required
trotter_order int

The order of the Trotterization.

2

Returns:

Type Description
int

An upper bound on the number of Trotter steps required to reach precision given by trotter_error.

cmnrs_commutator_1

cmnrs_commutator_1(hamiltonian, trotter_error, max_exponent=100, verbose=False, mc=False, num_trials=100)

Commutator bound for first order Trotterization.

Returns the first order commutator bound in "Toward the first quantum simulation with quantum speedup" arXiv:1711.10980 ⧉, by performing binary search over the number of trotter_steps in _cmnrs_commutator_func.

Parameters:

Name Type Description Default
hamiltonian PauliSum

The Hamiltonian for which the number of Trotter steps is to be estimated.

required
trotter_error float

The allowable Trotter error.

required
max_exponent int

The maximum exponent over which binary search is to be performed; i.e. the maximum number of Trotter steps that is returned is bounded by 2^max_exponent. Defaults to max_exponent = 100.

100
verbose bool

Whether to output possibly useful debugging and timing data.

False
mc bool

If False, evaluates the bound explicitly; if True, attempts a Monte Carlo estimate. Defaults to mc = False.

False
num_trials int

The number of trials to run if mc = True. Defaults to num_trials = 100.

100

Returns:

Type Description
int

An upper bound on the number of Trotter steps required to reach precision given by trotter_error.

Note

This bound is only applicable to first order Trotterization.

cmnrs_minimized_bound

cmnrs_minimized_bound(hamiltonian, trotter_error, trotter_order=2, max_exponent=100)

Calculate the minimized Trotter error commutator bound.

Implementation of the "minimized" Trotter error bound in "Toward the first quantum simulation with quantum speedup" arXiv:1711.10980 ⧉ (Eqs. 73, 74), by performing binary search over the number of trotter_steps in _cmnrs_min_func_log.

Parameters:

Name Type Description Default
hamiltonian PauliSum

The Hamiltonian for which the number of Trotter steps is to be estimated.

required
trotter_error float

The allowable Trotter error.

required
trotter_order int

The order of the Trotterization. Defaults to trotter_order = 2.

2
max_exponent int

The maximum exponent over which binary search is to be performed; i.e. the maximum number of Trotter steps that is returned is bounded by 2^max_exponent. Defaults to max_exponent = 100.

100

Returns:

Type Description
int

An upper bound on the number of Trotter steps required to reach precision given by trotter_error.

get_ppr_args_from_ham

get_ppr_args_from_ham(ham_term)

Convenience to set up PPR arguments from a term in a PauliSum.

Parameters:

Name Type Description Default
ham_term tuple

A single term in a PauliSum, where the tuple is (coefficient, PauliMask).

required

Returns:

Type Description
list

The arguments we need to pass: angle (float), x_mask (int), z_mask (int).

google_trotter_steps

google_trotter_steps(*args, **kwargs)

Stub for backwards compatibility.

compute_amplitudes_cosine_window

compute_amplitudes_cosine_window(n_qubits: int) -> np.ndarray

Compute amplitudes for cosine window.

Parameters:

Name Type Description Default
n_qubits int

Size of phase register

required
Note

Ref: "Effects of Cosine Tapering Window on Quantum Phase Estimation" (arXiv:2110.09590 ⧉).

Returns:

Type Description
ndarray

Representation of the taper state amplitudes.

compute_amplitudes_dolph_cheby_window

compute_amplitudes_dolph_cheby_window(n_qubits: int, alpha: float) -> np.ndarray

Compute amplitudes for Dolph-Chebyshev window.

Parameters:

Name Type Description Default
n_qubits int

Size of phase register

required
alpha float

Parameter for width of Dolph-Chebyshev window

required
Note

Returns:

Type Description
ndarray

Representation of the taper state amplitudes.

compute_amplitudes_hann_window

compute_amplitudes_hann_window(n_qubits: int) -> np.ndarray

Compute amplitudes for Hann window.

Parameters:

Name Type Description Default
n_qubits int

Size of phase register

required
Note

Returns:

Type Description
ndarray

Representation of the taper state amplitudes.

compute_amplitudes_kaiser_window

compute_amplitudes_kaiser_window(n_qubits: int, alpha: float) -> np.ndarray

Compute amplitudes for Kaiser window.

Parameters:

Name Type Description Default
n_qubits int

Size of phase register

required
alpha float

Parameter for width of Kaiser window

required
Note

Ref: Eq. C1 in "Analyzing Prospects for Quantum Advantage in Topological Data Analysis" (arXiv:2209.13581 ⧉).

Returns:

Type Description
ndarray

Representation of the taper state amplitudes.

compute_amplitudes_rect_window

compute_amplitudes_rect_window(n_qubits: int) -> np.ndarray

Compute amplitudes for rect window.

Parameters:

Name Type Description Default
n_qubits int

Size of phase register

required

Returns:

Type Description
ndarray

Representation of the taper state amplitudes.

compute_amplitudes_sine_window

compute_amplitudes_sine_window(n_qubits: int) -> np.ndarray

Compute amplitudes for sine window.

Parameters:

Name Type Description Default
n_qubits int

Size of phase register

required
Note

Ref: Eq. 20 in "Encoding Electronic Spectra in Quantum Circuits with Linear T Complexity" (arXiv:1805.03662 ⧉).

Returns:

Type Description
ndarray

Representation of the taper state amplitudes.

compute_amplitudes_welch_window

compute_amplitudes_welch_window(n_qubits: int) -> np.ndarray

Compute amplitudes for Welch window.

Parameters:

Name Type Description Default
n_qubits int

Size of phase register

required
Note

Returns:

Type Description
ndarray

Representation of the taper state amplitudes.