def run_estimate(unknown_gate, qnum, repetitions):
    """Construct the following phase estimator circuit and execute simulations.

                                     ---------
    ---H---------------------@------|         |---M--- [m4]:lowest bit
                             |      |         |
    ---H---------------@-----+------|         |---M--- [m3]
                       |     |      | QFT_inv |
    ---H---------@-----+-----+------|         |---M--- [m2]
                 |     |     |      |         |
    ---H---@-----+-----+-----+------|         |---M--- [m1]:highest bit
           |     |     |     |       ---------
    -------U-----U^2---U^4---U^8----------------------

    The measurement results M=[m1, m2,...] are translated to the estimated
    phase with the following formula:
    phi = m1*(1/2) + m2*(1/2)^2 + m3*(1/2)^3 + ...
    """

    ancilla = cirq.LineQubit(-1)
    qubits = cirq.LineQubit.range(qnum)

    oracle_raised_to_power = [
        unknown_gate.on(ancilla).controlled_by(qubits[i]) ** (2**i) for i in range(qnum)
    ]
    circuit = cirq.Circuit(
        cirq.H.on_each(*qubits),
        oracle_raised_to_power,
        cirq.qft(*qubits, without_reverse=True) ** -1,
        cirq.measure(*qubits, key='phase'),
    )

    return cirq.sample(circuit, repetitions=repetitions)
Construct the following phase estimator circuit and execute simulations.

                                     ---------
    ---H---------------------@------|         |---M--- [m4]:lowest bit
                             |      |         |
    ---H---------------@-----+------|         |---M--- [m3]
                       |     |      | QFT_inv |
    ---H---------@-----+-----+------|         |---M--- [m2]
                 |     |     |      |         |
    ---H---@-----+-----+-----+------|         |---M--- [m1]:highest bit
           |     |     |     |       ---------
    -------U-----U^2---U^4---U^8----------------------

    The measurement results M=[m1, m2,...] are translated to the estimated
    phase with the following formula:
    phi = m1*(1/2) + m2*(1/2)^2 + m3*(1/2)^3 + ...
    
examples/phase_estimator.py