Phase estimation circuit builder
================================

The :class:`~qdk_chemistry.algorithms.phase_estimation.circuit_builder.base.QpeCircuitBuilder` is an abstract base class that defines the interface for constructing phase estimation circuits.
It serves as the central component that orchestrates circuit synthesis by composing a :doc:`HamiltonianUnitaryBuilder <hamiltonian_unitary_builder>` (to construct the target unitary) with a :class:`~qdk_chemistry.algorithms.ControlledCircuitMapper` (to convert it to a controlled circuit).

The ``QpeCircuitBuilder`` is the primary algorithm reference configured in the :class:`~qdk_chemistry.algorithms.PhaseEstimation` class via the ``qpe_circuit_builder`` setting.
It encapsulates all details about circuit composition, allowing the high-level phase estimation interface to remain agnostic to the specific phase estimation variant (iterative or standard).

Overview
--------

Phase estimation circuit builders are responsible for:

1. **Composing circuits** from state preparation, controlled unitaries, and measurement/QFT operations
2. **Generating variant-specific circuits** (iterative uses adaptive feedback; standard uses QFT)

The :class:`~qdk_chemistry.algorithms.phase_estimation.circuit_builder.base.QpeCircuitBuilder` abstract class provides the common interface, while concrete implementations handle variant-specific details.
All variants delegate to the same nested algorithm interfaces, enabling flexible composition of different circuit synthesis strategies.

Use QpeCircuitBuilder
---------------------

.. note::
   This algorithm is currently available only in the Python API.


This section demonstrates how to create, configure, and run a phase estimation circuit builder.
The ``run`` method returns a list of :class:`~qdk_chemistry.data.Circuit` containing the constructed phase estimation circuits.

Input requirements
~~~~~~~~~~~~~~~~~~

The :class:`~qdk_chemistry.algorithms.phase_estimation.circuit_builder.base.QpeCircuitBuilder` requires the following inputs:

State preparation circuit
   A :class:`~qdk_chemistry.data.Circuit` that prepares the target quantum state on the system register.
   This is typically generated by the :doc:`StatePreparation <state_preparation>` algorithm from a :class:`~qdk_chemistry.data.Wavefunction`, but can also be any user-constructed circuit (e.g., a custom initial state for a :doc:`model Hamiltonian <../model_hamiltonians>`).

QubitOperator
   A :class:`~qdk_chemistry.data.QubitOperator` containing the Pauli-string representation of the Hamiltonian.
   This can be obtained from the :doc:`QubitMapper <qubit_mapper>` algorithm, constructed from a :doc:`model Hamiltonian <../model_hamiltonians>`, or built directly by the user.


The :class:`~qdk_chemistry.algorithms.phase_estimation.circuit_builder.base.QpeCircuitBuilderSettings` class defines the general configuration parameters shared by all QPE circuit builders.

.. list-table::
   :header-rows: 1
   :widths: 20 15 65

   * - Setting
     - Type
     - Description
   * - ``num_bits``
     - int
     - Number of phase bits to estimate. Must be a positive integer. Default: ``-1`` (invalid; user must set).
   * - ``measure_phase``
     - bool
     - Measure the phase register in the computational basis. Default: ``True``.
   * - ``unitary_builder``
     - :class:`~qdk_chemistry.data.AlgorithmRef`
     - Reference to the algorithm that constructs the target unitary :math:`U`. Default: :class:`~qdk_chemistry.data.AlgorithmRef` to ``"hamiltonian_unitary_builder"`` with method ``"trotter"``.
   * - ``controlled_circuit_mapper``
     - :class:`~qdk_chemistry.data.AlgorithmRef`
     - Reference to the algorithm that converts unitaries to controlled circuits. Default: :class:`~qdk_chemistry.data.AlgorithmRef` to ``"controlled_circuit_mapper"`` with method ``"pauli_sequence"``.

Once configured, the :class:`~qdk_chemistry.algorithms.phase_estimation.circuit_builder.base.QpeCircuitBuilder` can be executed with all required dependencies:

.. tab:: Python API

   .. literalinclude:: ../../../_static/examples/python/qpe_circuit_builder.py
      :language: python
      :start-after: # start-cell-run
      :end-before: # end-cell-run

Available Implementations
-------------------------

QDK/Chemistry provides two primary implementations of :class:`~qdk_chemistry.algorithms.phase_estimation.circuit_builder.base.QpeCircuitBuilder`:

Iterative Phase Estimation Circuit Builder (IQPE)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. rubric:: Class: ``QdkIterativeQpeCircuitBuilder`` (QDK native) and ``QiskitIterativeQpeCircuitBuilder`` (Qiskit implementation)

.. rubric:: Factory name: ``"qdk_iterative"`` (QDK native), ``"qiskit_iterative"`` (Qiskit implementation)

Constructs circuits for Kitaev's iterative phase estimation algorithm, which extracts phase bits one at a time using single-ancilla feedback corrections.

**Additional settings:**

.. list-table::
   :header-rows: 1
   :widths: 20 15 65

   * - Setting
     - Type
     - Description
   * - ``phase_correction``
     - float
     - Accumulated phase feedback from prior iterations. Default: ``0.0``.
   * - ``num_iteration``
     - int
     - Specific iteration to build (0-based). If negative, builds all iterations. Default: ``-1``.

**Usage example:**

.. literalinclude:: ../../../_static/examples/python/qpe_circuit_builder.py
   :language: python
   :start-after: start-cell-configure-iqpe
   :end-before: end-cell-configure-iqpe

Standard QFT-based Phase Estimation Circuit Builder
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. rubric:: Class: ``QdkStandardQpeCircuitBuilder`` (QDK native) and ``QiskitStandardQpeCircuitBuilder`` (Qiskit implementation)

.. rubric:: Factory name: ``"qdk_standard"`` (QDK native), ``"qiskit_standard"`` (Qiskit implementation)

Constructs the textbook multi-ancilla QPE circuit with inverse Quantum Fourier Transform. Extracts all phase bits simultaneously using ``num_bits`` ancilla qubits, applying controlled-:math:`U^{2^k}` for each ancilla and finishing with the inverse QFT.

**Additional settings (Qiskit implementation):**

.. list-table::
   :header-rows: 1
   :widths: 20 15 65

   * - Setting
     - Type
     - Description
   * - ``qft_do_swaps``
     - bool
     - Whether to include swap gates in the inverse QFT decomposition. Default: ``True``.

**Usage example:**

.. literalinclude:: ../../../_static/examples/python/qpe_circuit_builder.py
   :language: python
   :start-after: start-cell-configure-standard
   :end-before: end-cell-configure-standard

Circuit Composition Details
----------------------------

The phase estimation circuit is built by composing:

1. **State Preparation** — Prepares the initial quantum state on the system register
2. **Controlled Unitaries** — Applies controlled powers of the unitary operator :math:`C\text{-}U^{2^k}` to extract phase information
3. **Phase Feedback (IQPE only)** — Applies adaptive phase corrections between iterations
4. **Measurement/QFT** — For standard QPE, applies the inverse QFT before measurement

To accomplish this, the :class:`~qdk_chemistry.algorithms.phase_estimation.circuit_builder.base.QpeCircuitBuilder` maintains two key nested algorithm references:

**Nested Algorithm 1: Unitary Builder**
   Reference setting: ``"unitary_builder"``

   Default: :class:`~qdk_chemistry.data.AlgorithmRef` to ``"hamiltonian_unitary_builder"`` with method ``"trotter"``

   The unitary builder (typically :doc:`HamiltonianUnitaryBuilder <hamiltonian_unitary_builder>`) produces a :class:`~qdk_chemistry.data.UnitaryRepresentation` of the target operator from a :class:`~qdk_chemistry.data.QubitOperator`.
   The builder is configured with the desired time-evolution strategy and time parameter (``time`` setting).

**Nested Algorithm 2: Controlled Circuit Mapper**
   Reference setting: ``"controlled_circuit_mapper"``

   Default: :class:`~qdk_chemistry.data.AlgorithmRef` to ``"controlled_circuit_mapper"`` with method ``"pauli_sequence"``

   The controlled circuit mapper (see :class:`~qdk_chemistry.algorithms.ControlledCircuitMapper`) converts the :class:`~qdk_chemistry.data.UnitaryRepresentation` into a controlled circuit, i.e., it synthesizes :math:`C\text{-}U` as an executable :class:`~qdk_chemistry.data.Circuit`.

Related Classes
---------------

- :class:`~qdk_chemistry.algorithms.phase_estimation.circuit_builder.base.QpeCircuitBuilderSettings`: Settings for circuit builders
- :class:`~qdk_chemistry.data.Circuit`: Quantum circuit representation
- :class:`~qdk_chemistry.data.UnitaryRepresentation`: Output of unitary builders
- :class:`~qdk_chemistry.data.AlgorithmRef`: Nested algorithm references
- :class:`~qdk_chemistry.algorithms.PhaseEstimation`: High-level phase estimation interface that uses circuit builders internally

Further Reading
---------------

- :doc:`phase_estimation`: Run phase estimation algorithm
- :doc:`hamiltonian_unitary_builder`: Constructs unitary operators for Hamiltonian time evolution
- :doc:`circuit_executor`: Executes quantum circuits
- :doc:`../design/index`: QDK/Chemistry algorithm design principles
- :doc:`settings`: Configuration and settings management
- :doc:`factory_pattern`: Understanding algorithm creation and composition
