# Quantum Counting using the Iterative Quantum Amplitude Estimation Algorithm

Quantum Counting algorithm [1] is an algorithm for efficiently estimating the number of valid solutions to a search problem, based on the amplitude estimation algorithm. It demonstrates a quadratic improvement with regards to a classical algorithm with black-box oracle access to the function $$f$$.

More precisely, the counting problem is, given a boolean function $$f :\{0, 1\}^n\rightarrow\{0,1\}$$, estimate the number of inputs $$x$$ to $$f$$ such that $$f(x)=1$$.

In this tutorial we will deomstrate how to estimate the Couting problem using a specific variant of the Amplitude Estimation algorithm - the Iterative Quantum Amplitude Estimation (IQAE) [2].

The IQAE does not rely on the Quantum Phase Estimation algoritm [3], but purely on applications of the grover operator:

$Q\equiv - A S_0 A^{\dagger} S_{\psi_1} ,$

Hence reducing the required amount of qubits and gates of the circuit, at the expense of additional multiplicative factor poly-logarithmic in the error $$\epsilon$$.

## Setting the problem

We will choose the equation:

$(a + b) <= 2$

where $$a$$, $$b$$ are 2-bit unsigned integers. This equation has 6 solutions. The goal is to estimate the number of valid solutions out of the 16 possible inputs, with precision $$0.5$$.

## Amplitude Estimation using Phase Estimation

We first show how to use Quantum Phase Estimation algorithm for the Quantum Counting [3], then move to solve it using the IQAE method.

Given a state $$|\psi\rangle$$ such that $$|\psi\rangle=\sqrt{a}|\psi_1\rangle+\sqrt{1-a}|\psi_0\rangle$$ we can measure $$a$$ up to arbitrary precision, given the following building blocks: 1) State Preperation: A unitary $$A$$ such that: $$A|0\rangle = |\psi\rangle = \sqrt{a}|\psi_1\rangle+\sqrt{1-a}|\psi_0\rangle$$

2) Oracle: A unitary $$S_{\psi_1}$$ such that $$S_{\psi_1}=I-2|\psi_1\rangle\langle\psi_1|$$, which adds a $$(-1)$$ phase to $$|\psi_1|\psi\rangle\rangle$$ and does nothing to any orthognal states to $$|\psi_1\rangle$$. This is effectively a reflection around the "good" state $$|\psi_1\rangle$$.

Given this 2 functions, we can construct the grover operator:

$Q\equiv - A S_0 A^{\dagger} S_{\psi_1} ,$

Which is exactly the same operator as the one for the grover's search algorithm.

In the subspace spanned by $$|\psi_1\rangle$$ and $$|\psi_0\rangle$$, $$Q$$ has 2 eigenvalues:

$\lambda_{\pm}=\exp\left(\pm i2\pi \theta \right), \qquad \sin^2 \left(\pi \theta\right)\equiv a.$

Therefore, if we apply a QPE on $$A|0\rangle$$ we will have these two eigenvalues encoded in the QPE register, however, both give the value of $$a$$, so there is no ambiguity here.

### Arithmetic oracle

Here we define the $$S_{\psi_1}$$ oracle:

$S_{\psi_1}|a\rangle|b\rangle= (-1)^{f(a,b)}|a\rangle|b\rangle$
from classiq import *

A_SIZE = 2
B_SIZE = 2
DOMAIN_SIZE = A_SIZE + B_SIZE

class OracleVars(QStruct):
a: QNum[A_SIZE, False, 0]
b: QNum[B_SIZE, False, 0]

@qfunc
def arith_equation(a: QNum, b: QNum, res: QBit):
res ^= a + b <= 2

# use phase kickback for turning the arith_equation to an oracle
@qfunc
def arith_oracle(state: OracleVars):
aux = QBit("aux")
within_apply(
lambda: (allocate(1, aux), X(aux), H(aux)),
lambda: arith_equation(state.a, state.b, aux),
)

### Diffuser

The diffuser consists of the reflection around the $$|0\rangle$$ state, and a state-preparation function.

The state preparation function $$A$$ reflects knowledge about the solution space, and can be used to eliminate invalid assignments. Here we assume no knowledge on the solution space, hence we use the uniform superposition state preparation.

import numpy as np

@qfunc
lsb = QBit("lsb")
msbs = QArray("msbs", QBit, x.len - 1)

apply_to_all(X, x)
bind(x, [msbs, lsb])
control(msbs, lambda: Z(lsb))
bind([msbs, lsb], x)
apply_to_all(X, x)

@qfunc
def my_diffuser(sp_operand: QCallable[QArray[QBit]], x: QArray[QBit]):
within_apply(
lambda: invert(lambda: sp_operand(x)),
)

### Complete Grover operator definition

@qfunc
def my_grover_operator(
oracle_operand: QCallable[QArray[QBit]],
sp_operand: QCallable[QArray[QBit]],
x: QArray[QBit],
):
oracle_operand(x)
my_diffuser(sp_operand, x)
U(0, 0, 0, np.pi, x[0])

### Wrap all to the Phase Estimation

We will acheive the desired precision only in the IQAE phase. Here we compute the worst-case precision for 5 phase qubits:

NUM_PHASE_QUBITS = 5

x = np.linspace(0, 1, 100)
(2**DOMAIN_SIZE) * max(
np.abs(
np.sin(np.pi * x) ** 2 - np.sin(np.pi * (x - 1 / (2**NUM_PHASE_QUBITS))) ** 2
)
)
1.5681439279637468
@qfunc
def main(
phase_reg: Output[QNum],
) -> None:
state_reg = OracleVars("state_reg")
allocate(state_reg.size, state_reg)
allocate_num(NUM_PHASE_QUBITS, False, NUM_PHASE_QUBITS, phase_reg)
sp_oracle(state_reg)
qpe(
unitary=lambda: my_grover_operator(
arith_oracle,
sp_oracle,
state_reg,
),
phase=phase_reg,
)

### Synthesize the model to a quantum program

constraints = Constraints(max_width=14)
qmod_qpe = create_model(main, constraints=constraints, out_file="quantum_counting_qpe")
qprog_qpe = synthesize(qmod_qpe)
show(qprog_qpe)
Opening: https://platform.classiq.io/circuit/d218b496-fb51-4009-ae0f-11de2970a36a?version=0.0.0

### Quantum Program execution

result = execute(qprog_qpe).result_value()

Plotting the resulting histogram we see two phase values with high probability (however, both corresponds to the same amplitude). Note that phase_reg is already coded as fixed QNum in the range [0,1].

import matplotlib.pyplot as plt

phases_counts = dict(
(sampled_state.state["phase_reg"], sampled_state.shots)
for sampled_state in result.parsed_counts
)
plt.bar(phases_counts.keys(), phases_counts.values(), width=0.1)
plt.xticks(rotation=90)
print("phase with max probability: ", max(phases_counts, key=phases_counts.get))
phase with max probability:  0.78125

From the phase we can extract the number of solutions:

solutions_ratio_qpe = np.sin(np.pi * max(phases_counts, key=phases_counts.get)) ** 2
print(
"Number of solutions: ",
(2**DOMAIN_SIZE) * solutions_ratio_qpe,
)
Number of solutions:  6.439277423870974

## Amplitude Estimation using Iterative Quantum Amplitude Estimation

Now we are ready for the iterative method!

Instead of QPE, the algorithm applies the unitary:

$(Q)^mA$

where $$m$$, the number of repetitions is changed between iterations of the algorithm.

There is one subtlety that will change the way we work with the Grover operator. The classical algorithm expects additional indicator qubit that marks the "good" states, i.e.:

$|a\rangle|b\rangle|f(a,b)\rangle$

So now, most of our logic will go into the state preparation oracle ($$A$$). It will combine both the loading of the solution space, and the setting of the indicator qubit.

class IQAEVars(QStruct):
state: OracleVars
ind: QBit

@qfunc
def iqae_state_preparation(vars: IQAEVars):
arith_equation(vars.state.a, vars.state.b, vars.ind)

Now, as we use the indicator qubit, the oracle is very simple - it is just a $$Z$$ gate on the indicator qubit!

@qfunc
def iqae_oracle(vars: IQAEVars):
Z(vars.ind)

### Wrapping all to the Iterative Quantum Amplitude Estimation Algorithm

The circuit starts with the state $$A|0\rangle$$, then applies iterations of the Grover operator.

Notice that the algorithm applies varied number of grover iterations on each execution. The number of iterations is chosen dynamically based on previous execution results, using statistical inference methods.

@qfunc
def my_iqae_algorithm(
k: CInt,
oracle_operand: QCallable[QArray[QBit]],
sp_operand: QCallable[QArray[QBit]],
x: IQAEVars,
):
sp_operand(x)
power(k, lambda: my_grover_operator(oracle_operand, sp_operand, x))

We use the built-in iqae classical execution code. It assumes only one output to the circuit, which is the indicator qubit. We set $$\epsilon = 1/{2^4} \cdot 0.5 = 1/32$$. alpha is the tail probability of esimtating the result with accuracy $$\epsilon$$.

DOMAIN_SIZE_QCONST = QConstant("DOMAIN_SIZE_QCONST", int, DOMAIN_SIZE)

@cfunc
def cmain():
iqae_res = iqae(epsilon=1 / ((2**DOMAIN_SIZE_QCONST) * 2), alpha=0.01)
save({"iqae_res": iqae_res})

@qfunc
def main(
k: CInt,
ind_reg: Output[QBit],
) -> None:
full_reg = IQAEVars("full_reg")
allocate(full_reg.size, full_reg)
my_iqae_algorithm(
k,
iqae_oracle,
iqae_state_preparation,
full_reg,
)
state_reg = OracleVars("state_reg")
bind(full_reg, [state_reg, ind_reg])

### Synthesize the model to a quantum program

constraints = Constraints(optimization_parameter="width")
qmod_iqae = create_model(
main,
constraints=constraints,
classical_execution_function=cmain,
out_file="quantum_counting_iqae",
)
qprog_iqae = synthesize(qmod_iqae)
show(qprog_iqae)
Opening: https://platform.classiq.io/circuit/b1c231ed-0a47-413f-8305-fa6416ef9f42?version=0.0.0

### Quantum Program execution

iqae_result = execute(qprog_iqae).result_value()
print(
f"IQAE result: {iqae_result.estimation}, confidence interval: {iqae_result.confidence_interval}"
)
IQAE result: 0.37335803667582856, confidence interval: (0.3454915028125263, 0.40122457053913085)
print(
f"Number of solutions: {(2**DOMAIN_SIZE) * iqae_result.estimation}, accuracy: "
f"{(2**DOMAIN_SIZE)*(iqae_result.confidence_interval[1]-iqae_result.confidence_interval[0])}"
)
Number of solutions: 5.973728586813257, accuracy: 0.8917290836256733
assert np.isclose(
iqae_result.estimation, solutions_ratio_qpe, 1 / ((2**DOMAIN_SIZE) * 0.5)
)
assert np.isclose(
iqae_result.estimation, 6 / (2**DOMAIN_SIZE), 1 / ((2**DOMAIN_SIZE) * 0.5)
)

We can also see the statistics of the IQAE execution:

for i, iteration in enumerate(iqae_result.iterations_data):
print(
f"iteration_id: {i}, num grover iterations: {iteration.grover_iterations}, counts: {iteration.sample_results.counts}"
)
iteration_id: 0, num grover iterations: 0, counts: {'0': 581, '1': 419}
iteration_id: 1, num grover iterations: 2, counts: {'0': 977, '1': 23}