Skip to content

psiqit.algorithms

Auto-generated documentation for the psiqit.algorithms module.

psiqit.algorithms

PSIQIT - Python Scientific Quantum Information Toolkit Algorithms Module

This module provides quantum algorithms for various computational tasks.

Submodules:

grover.py - Grover's search algorithm (quadratic speedup for search) deutsch_jozsa.py - Deutsch-Jozsa algorithm (determine if function is constant or balanced) bernstein_vazirani.py - Bernstein-Vazirani algorithm (find hidden string) simon.py - Simon's algorithm (find period of a function) qft.py - Quantum Fourier Transform (key component for many algorithms) qpe.py - Quantum Phase Estimation (estimate eigenvalues of unitary operators) shor.py - Shor's factoring algorithm (exponential speedup for factoring)

Grover's search algorithm for unstructured search

Finds a target state in an unsorted database of size N = 2^n using O(√N) queries (quadratic speedup over classical O(N)).

Parameters:

Name Type Description Default
n_qubits int

Number of qubits (database size = 2^n)

required
target int

Target state to search for (0 to 2^n - 1)

required
n_iterations Optional[int]

Number of Grover iterations (auto-calculated if None)

None
shots int

Number of measurement shots

1024
oracle_type str

'phase' or 'boolean' (phase oracle is more efficient)

'phase'
return_circuit bool

If True, return the circuit as well

False
seed Optional[int]

Random seed for reproducibility

None

Returns:

Name Type Description
Dict Dict[str, Any]

Results including the most likely state and counts

Example

Search for state |101⟩ in 3-qubit system

result = grover_search(n_qubits=3, target=5, shots=1024) print(result['most_likely']) # 5 print(result['success']) # True if probability > 0.5

Search with custom iterations

result = grover_search(n_qubits=4, target=10, n_iterations=3)

Source code in psiqit\algorithms\grover.py
def grover_search(
    n_qubits: int,
    target: int,
    n_iterations: Optional[int] = None,
    shots: int = 1024,
    oracle_type: str = 'phase',
    return_circuit: bool = False,
    seed: Optional[int] = None
) -> Dict[str, Any]:
    """
    Grover's search algorithm for unstructured search

    Finds a target state in an unsorted database of size N = 2^n
    using O(√N) queries (quadratic speedup over classical O(N)).

    Args:
        n_qubits: Number of qubits (database size = 2^n)
        target: Target state to search for (0 to 2^n - 1)
        n_iterations: Number of Grover iterations (auto-calculated if None)
        shots: Number of measurement shots
        oracle_type: 'phase' or 'boolean' (phase oracle is more efficient)
        return_circuit: If True, return the circuit as well
        seed: Random seed for reproducibility

    Returns:
        Dict: Results including the most likely state and counts

    Example:
        >>> # Search for state |101⟩ in 3-qubit system
        >>> result = grover_search(n_qubits=3, target=5, shots=1024)
        >>> print(result['most_likely'])  # 5
        >>> print(result['success'])  # True if probability > 0.5

        >>> # Search with custom iterations
        >>> result = grover_search(n_qubits=4, target=10, n_iterations=3)
    """
    if seed is not None:
        np.random.seed(seed)

    validate_qubits(n_qubits)
    dim = 2 ** n_qubits

    if target < 0 or target >= dim:
        raise ValueError(f"Target {target} out of range [0, {dim-1}]")

    # Calculate optimal number of iterations
    if n_iterations is None:
        n_iterations = int(np.floor(np.pi / 4 * np.sqrt(dim)))
        logger.info(f"Auto-calculated {n_iterations} Grover iterations")

    logger.info(f"Grover search: {n_qubits} qubits, target={target}, iterations={n_iterations}")

    # Create circuit
    circuit = QuantumCircuit(n_qubits)

    # Initialize to |+⟩⊗n (superposition of all states)
    for i in range(n_qubits):
        circuit.h(i)

    # Grover iterations
    for iteration in range(n_iterations):
        # Oracle (marks target state)
        _apply_oracle(circuit, target, oracle_type=oracle_type)

        # Diffusion operator
        _apply_diffusion(circuit)

    # Measure
    result = circuit.measure(shots=shots)

    # Find most likely state
    counts = result['counts']
    most_likely_binary = max(counts, key=counts.get) if counts else None

    # Convert binary string to int
    most_likely_int = int(most_likely_binary, 2) if most_likely_binary else -1

    # Calculate probability of target
    target_binary = format(target, f'0{n_qubits}b')
    prob_target = counts.get(target_binary, 0) / shots if shots > 0 else 0

    # Determine success
    success = prob_target > 0.5

    # Build result
    result_dict = {
        'most_likely': most_likely_int,
        'most_likely_binary': most_likely_binary,
        'counts': counts,
        'shots': shots,
        'n_qubits': n_qubits,
        'target': target,
        'target_binary': target_binary,
        'iterations': n_iterations,
        'probability_target': prob_target,
        'success': success,
        'algorithm': 'grover'
    }

    if return_circuit:
        result_dict['circuit'] = circuit

    logger.info(f"Grover search completed: target={target}, found={most_likely_int}, success={success}")

    return result_dict

grover_search_simulated(n_qubits, target, n_iterations=None)

Simulated version of Grover's algorithm using state vectors

This is faster and more accurate for testing, as it doesn't build circuits.

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required
target int

Target state to find

required
n_iterations Optional[int]

Number of iterations (auto-calculated if None)

None

Returns:

Name Type Description
Dict Dict[str, Any]

Results with probabilities

Example

result = grover_search_simulated(n_qubits=3, target=5) print(result['probability_target']) # ~0.94 print(result['most_likely']) # 5

Source code in psiqit\algorithms\grover.py
def grover_search_simulated(
    n_qubits: int,
    target: int,
    n_iterations: Optional[int] = None
) -> Dict[str, Any]:
    """
    Simulated version of Grover's algorithm using state vectors

    This is faster and more accurate for testing, as it doesn't build circuits.

    Args:
        n_qubits: Number of qubits
        target: Target state to find
        n_iterations: Number of iterations (auto-calculated if None)

    Returns:
        Dict: Results with probabilities

    Example:
        >>> result = grover_search_simulated(n_qubits=3, target=5)
        >>> print(result['probability_target'])  # ~0.94
        >>> print(result['most_likely'])  # 5
    """
    validate_qubits(n_qubits)
    dim = 2 ** n_qubits

    if target < 0 or target >= dim:
        raise ValueError(f"Target {target} out of range [0, {dim-1}]")

    # Calculate optimal iterations
    if n_iterations is None:
        n_iterations = int(np.floor(np.pi / 4 * np.sqrt(dim)))

    # Initial state: |s⟩ = (1/√N) Σ|x⟩
    s = np.ones(dim, dtype=complex) / np.sqrt(dim)

    # Target state |w⟩
    w = np.zeros(dim, dtype=complex)
    w[target] = 1.0

    # Apply Grover iterations
    state = s.copy()
    for _ in range(n_iterations):
        # Reflect about |w⟩ (oracle)
        state = state - 2 * (np.vdot(w, state) * w)

        # Reflect about |s⟩ (diffusion)
        state = 2 * np.vdot(s, state) * s - state

    # Normalize
    state = state / np.linalg.norm(state)

    # Probabilities
    probs = np.abs(state) ** 2

    # Most likely state
    most_likely = int(np.argmax(probs))
    prob_target = float(probs[target])

    logger.info(f"Grover simulated: target={target}, prob={prob_target:.4f}")

    return {
        'most_likely': most_likely,
        'probability_target': prob_target,
        'probabilities': probs.tolist(),
        'target': target,
        'n_qubits': n_qubits,
        'iterations': n_iterations,
        'state': Ket(state),
        'algorithm': 'grover_simulated',
        'success': prob_target > 0.5
    }

grover_with_custom_oracle(n_qubits, oracle, n_iterations=None, shots=1024, return_circuit=False)

Grover's search with a custom oracle function

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required
oracle Callable

Oracle function that takes a circuit and qubits

required
n_iterations Optional[int]

Number of Grover iterations

None
shots int

Number of measurement shots

1024
return_circuit bool

If True, return the circuit

False

Returns:

Name Type Description
Dict Dict[str, Any]

Results

Example

def my_oracle(circ, qubits): ... # Mark state |101⟩ ... circ.x(qubits[0]) ... circ.x(qubits[2]) ... circ.cz(qubits[0], qubits[1]) ... circ.cz(qubits[1], qubits[2]) ... circ.x(qubits[0]) ... circ.x(qubits[2]) result = grover_with_custom_oracle(3, my_oracle)

Source code in psiqit\algorithms\grover.py
def grover_with_custom_oracle(
    n_qubits: int,
    oracle: Callable,
    n_iterations: Optional[int] = None,
    shots: int = 1024,
    return_circuit: bool = False
) -> Dict[str, Any]:
    """
    Grover's search with a custom oracle function

    Args:
        n_qubits: Number of qubits
        oracle: Oracle function that takes a circuit and qubits
        n_iterations: Number of Grover iterations
        shots: Number of measurement shots
        return_circuit: If True, return the circuit

    Returns:
        Dict: Results

    Example:
        >>> def my_oracle(circ, qubits):
        ...     # Mark state |101⟩
        ...     circ.x(qubits[0])
        ...     circ.x(qubits[2])
        ...     circ.cz(qubits[0], qubits[1])
        ...     circ.cz(qubits[1], qubits[2])
        ...     circ.x(qubits[0])
        ...     circ.x(qubits[2])
        >>> result = grover_with_custom_oracle(3, my_oracle)
    """
    validate_qubits(n_qubits)
    dim = 2 ** n_qubits

    # Calculate optimal iterations
    if n_iterations is None:
        n_iterations = int(np.floor(np.pi / 4 * np.sqrt(dim)))

    # Create circuit
    circuit = QuantumCircuit(n_qubits)

    # Initialize to |+⟩⊗n
    for i in range(n_qubits):
        circuit.h(i)

    # Grover iterations
    for _ in range(n_iterations):
        # Apply custom oracle
        oracle(circuit, list(range(n_qubits)))

        # Apply diffusion
        _apply_diffusion(circuit)

    # Measure
    result = circuit.measure(shots=shots)

    # Find most likely state
    counts = result['counts']
    most_likely_binary = max(counts, key=counts.get) if counts else None
    most_likely_int = int(most_likely_binary, 2) if most_likely_binary else -1

    result_dict = {
        'most_likely': most_likely_int,
        'most_likely_binary': most_likely_binary,
        'counts': counts,
        'shots': shots,
        'n_qubits': n_qubits,
        'iterations': n_iterations,
        'algorithm': 'grover_custom_oracle'
    }

    if return_circuit:
        result_dict['circuit'] = circuit

    return result_dict

optimal_grover_iterations(n_qubits)

Calculate the optimal number of Grover iterations

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required

Returns:

Name Type Description
int int

Optimal number of iterations

Example

optimal_grover_iterations(3) # 2 optimal_grover_iterations(4) # 3

Source code in psiqit\algorithms\grover.py
def optimal_grover_iterations(n_qubits: int) -> int:
    """
    Calculate the optimal number of Grover iterations

    Args:
        n_qubits: Number of qubits

    Returns:
        int: Optimal number of iterations

    Example:
        >>> optimal_grover_iterations(3)  # 2
        >>> optimal_grover_iterations(4)  # 3
    """
    dim = 2 ** n_qubits
    return int(np.floor(np.pi / 4 * np.sqrt(dim)))

grover_probability(n_qubits, n_iterations, target=0)

Calculate the probability of finding the target state after n_iterations

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required
n_iterations int

Number of Grover iterations

required
target int

Target state (for reference)

0

Returns:

Name Type Description
float float

Probability of target state

Example

grover_probability(3, 2) # ~0.945

Source code in psiqit\algorithms\grover.py
def grover_probability(
    n_qubits: int,
    n_iterations: int,
    target: int = 0
) -> float:
    """
    Calculate the probability of finding the target state after n_iterations

    Args:
        n_qubits: Number of qubits
        n_iterations: Number of Grover iterations
        target: Target state (for reference)

    Returns:
        float: Probability of target state

    Example:
        >>> grover_probability(3, 2)  # ~0.945
    """
    dim = 2 ** n_qubits
    theta = 2 * np.arcsin(1 / np.sqrt(dim))
    prob = np.sin((2 * n_iterations + 1) * theta / 2) ** 2
    return float(prob)

grover_amplitude(n_qubits, n_iterations, target=0)

Calculate the amplitude of the target state after n_iterations

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required
n_iterations int

Number of Grover iterations

required
target int

Target state (for reference)

0

Returns:

Name Type Description
float float

Amplitude of target state

Example

grover_amplitude(3, 2) # ~0.972

Source code in psiqit\algorithms\grover.py
def grover_amplitude(
    n_qubits: int,
    n_iterations: int,
    target: int = 0
) -> float:
    """
    Calculate the amplitude of the target state after n_iterations

    Args:
        n_qubits: Number of qubits
        n_iterations: Number of Grover iterations
        target: Target state (for reference)

    Returns:
        float: Amplitude of target state

    Example:
        >>> grover_amplitude(3, 2)  # ~0.972
    """
    return np.sqrt(grover_probability(n_qubits, n_iterations))

deutsch_algorithm(oracle_function=None, function_type=None, shots=1024, return_circuit=False, n_qubits=1)

Deutsch algorithm (1-qubit version of Deutsch-Jozsa)

Source code in psiqit\algorithms\deutsch_jozsa.py
def deutsch_algorithm(
    oracle_function: Optional[Callable] = None,
    function_type: Optional[str] = None,
    shots: int = 1024,
    return_circuit: bool = False,
    n_qubits: int = 1
) -> Dict[str, Any]:
    """
    Deutsch algorithm (1-qubit version of Deutsch-Jozsa)
    """
    if function_type == 'identity' or function_type == 'not':
        function_type = 'balanced'

    return deutsch_jozsa(
        oracle_function=oracle_function,
        n_qubits=n_qubits,
        function_type=function_type,
        shots=shots,
        return_circuit=return_circuit
    )

bernstein_vazirani_circuit(hidden_string, include_measurements=True)

Create a Bernstein-Vazirani circuit for a given hidden string

Parameters:

Name Type Description Default
hidden_string str

Hidden string s (e.g., '101')

required
include_measurements bool

Whether to include measurement gates

True

Returns:

Name Type Description
QuantumCircuit QuantumCircuit

Circuit implementing Bernstein-Vazirani

Example

circ = bernstein_vazirani_circuit('101') print(circ.draw())

Source code in psiqit\algorithms\bernstein_vazirani.py
def bernstein_vazirani_circuit(
    hidden_string: str,
    include_measurements: bool = True
) -> QuantumCircuit:
    """
    Create a Bernstein-Vazirani circuit for a given hidden string

    Args:
        hidden_string: Hidden string s (e.g., '101')
        include_measurements: Whether to include measurement gates

    Returns:
        QuantumCircuit: Circuit implementing Bernstein-Vazirani

    Example:
        >>> circ = bernstein_vazirani_circuit('101')
        >>> print(circ.draw())
    """
    n_qubits = len(hidden_string)
    hidden_bits = [int(b) for b in hidden_string]

    # Create circuit with n_qubits + 1 qubits
    circuit = QuantumCircuit(n_qubits + 1)

    # Initialize ancilla to |−⟩
    circuit.x(n_qubits)
    circuit.h(n_qubits)

    # Apply Hadamard to input qubits
    for i in range(n_qubits):
        circuit.h(i)

    # Apply oracle (CNOTs for each 1 in hidden string)
    for i, bit in enumerate(hidden_bits):
        if bit == 1:
            circuit.cx(i, n_qubits)

    # Apply Hadamard to input qubits again
    for i in range(n_qubits):
        circuit.h(i)

    # Measurements
    if include_measurements:
        # The ancilla is not measured in standard Bernstein-Vazirani
        # Only the input qubits are measured
        pass

    logger.debug(f"Bernstein-Vazirani circuit created for hidden string: {hidden_string}")

    return circuit

bernstein_vazirani_simulated(hidden_string, shots=1024)

Simulate Bernstein-Vazirani algorithm using state vector

This is a faster simulation that doesn't build a circuit.

Parameters:

Name Type Description Default
hidden_string str

Hidden string s

required
shots int

Number of measurement shots

1024

Returns:

Name Type Description
Dict Dict[str, Any]

Results

Example

result = bernstein_vazirani_simulated('101') print(result['found_string']) # '101'

Source code in psiqit\algorithms\bernstein_vazirani.py
def bernstein_vazirani_simulated(
    hidden_string: str,
    shots: int = 1024
) -> Dict[str, Any]:
    """
    Simulate Bernstein-Vazirani algorithm using state vector

    This is a faster simulation that doesn't build a circuit.

    Args:
        hidden_string: Hidden string s
        shots: Number of measurement shots

    Returns:
        Dict: Results

    Example:
        >>> result = bernstein_vazirani_simulated('101')
        >>> print(result['found_string'])  # '101'
    """
    n_qubits = len(hidden_string)
    hidden_bits = [int(b) for b in hidden_string]

    # In the ideal case, the algorithm returns the hidden string
    # with probability 1

    # Simulate measurements
    # The result is deterministic in the ideal case
    counts = {hidden_string: shots}

    return {
        'hidden_string': hidden_string,
        'found_string': hidden_string,
        'counts': counts,
        'shots': shots,
        'n_qubits': n_qubits,
        'success': True,
        'algorithm': 'berstein_vazirani_simulated'
    }

bernstein_vazirani_classical(oracle_function, n_qubits)

Classical version of Bernstein-Vazirani (requires n queries)

This is provided for comparison with the quantum algorithm.

Parameters:

Name Type Description Default
oracle_function callable

Oracle function f(x) that computes s·x (mod 2)

required
n_qubits int

Number of qubits

required

Returns:

Name Type Description
str str

Found hidden string

Example

def oracle(x): ... # s = 101 ... return (x[0] + x[2]) % 2 result = bernstein_vazirani_classical(oracle, 3) print(result) # '101'

Source code in psiqit\algorithms\bernstein_vazirani.py
def bernstein_vazirani_classical(
    oracle_function: callable,
    n_qubits: int
) -> str:
    """
    Classical version of Bernstein-Vazirani (requires n queries)

    This is provided for comparison with the quantum algorithm.

    Args:
        oracle_function: Oracle function f(x) that computes s·x (mod 2)
        n_qubits: Number of qubits

    Returns:
        str: Found hidden string

    Example:
        >>> def oracle(x):
        ...     # s = 101
        ...     return (x[0] + x[2]) % 2
        >>> result = bernstein_vazirani_classical(oracle, 3)
        >>> print(result)  # '101'
    """
    hidden_bits = []

    for i in range(n_qubits):
        # Query with x = e_i (one-hot vector)
        x = [0] * n_qubits
        x[i] = 1

        # Get the result
        result = oracle_function(x)
        hidden_bits.append(result)

    return ''.join(str(b) for b in hidden_bits)

create_oracle_from_hidden_string(hidden_string)

Create an oracle function from a hidden string

Parameters:

Name Type Description Default
hidden_string str

Hidden string s

required

Returns:

Name Type Description
callable callable

Oracle function f(x) = s·x (mod 2)

Example

oracle = create_oracle_from_hidden_string('101') print(oracle([1, 0, 1])) # 0 (11 + 00 + 1*1 = 2 mod 2 = 0) print(oracle([1, 0, 0])) # 1

Source code in psiqit\algorithms\bernstein_vazirani.py
def create_oracle_from_hidden_string(hidden_string: str) -> callable:
    """
    Create an oracle function from a hidden string

    Args:
        hidden_string: Hidden string s

    Returns:
        callable: Oracle function f(x) = s·x (mod 2)

    Example:
        >>> oracle = create_oracle_from_hidden_string('101')
        >>> print(oracle([1, 0, 1]))  # 0 (1*1 + 0*0 + 1*1 = 2 mod 2 = 0)
        >>> print(oracle([1, 0, 0]))  # 1
    """
    hidden_bits = [int(b) for b in hidden_string]

    def oracle(x: List[int]) -> int:
        """Oracle function"""
        if len(x) != len(hidden_bits):
            raise ValueError(f"Input length {len(x)} does not match hidden string length {len(hidden_bits)}")

        # Compute dot product mod 2
        result = 0
        for xi, si in zip(x, hidden_bits):
            result ^= (xi & si)

        return result

    return oracle

generate_random_hidden_string(n_qubits, seed=None)

Generate a random non-zero hidden string

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required
seed Optional[int]

Random seed

None

Returns:

Name Type Description
str str

Random binary string (non-zero)

Example

s = generate_random_hidden_string(5) print(s) # e.g., '10110'

Source code in psiqit\algorithms\simon.py
def generate_random_hidden_string(n_qubits: int, seed: Optional[int] = None) -> str:
    """
    Generate a random non-zero hidden string

    Args:
        n_qubits: Number of qubits
        seed: Random seed

    Returns:
        str: Random binary string (non-zero)

    Example:
        >>> s = generate_random_hidden_string(5)
        >>> print(s)  # e.g., '10110'
    """
    if seed is not None:
        np.random.seed(seed)

    # Generate a random non-zero string
    while True:
        bits = np.random.randint(0, 2, size=n_qubits)
        if any(bits):
            return ''.join(str(b) for b in bits)

simon_algorithm(oracle_function=None, hidden_string=None, n_qubits=None, shots=1024, max_attempts=10, return_circuit=False, verbose=False)

Simon's algorithm to find the period of a function

Given a function f: {0,1}ⁿ → {0,1}ⁿ such that f(x) = f(x ⊕ s) for some hidden string s, Simon's algorithm finds s using O(n) queries (exponential speedup over classical O(2^{n/2})).

Parameters:

Name Type Description Default
oracle_function Optional[Callable]

Oracle function f(x) that returns a bitstring If provided, hidden_string is ignored.

None
hidden_string Optional[str]

Hidden string s (e.g., '101') If provided, oracle is constructed automatically.

None
n_qubits Optional[int]

Number of qubits (automatically determined if not provided)

None
shots int

Number of measurement shots

1024
max_attempts int

Maximum number of attempts to find s

10
return_circuit bool

If True, return the circuit as well

False
verbose bool

Print progress information

False

Returns:

Name Type Description
Dict Dict[str, Any]

Results including the found string

Example

Find hidden string '101'

result = simon_algorithm(hidden_string='101') print(result['hidden_string']) # '101' print(result['found_string']) # '101'

With custom oracle

def oracle(x): ... # f(x) = x if x[0] == 0, else x ⊕ s ... s = [1, 0, 1] ... if x[0] == 0: ... return x ... else: ... return [(xi ^ si) for xi, si in zip(x, s)] result = simon_algorithm(oracle_function=oracle, n_qubits=3)

Source code in psiqit\algorithms\simon.py
def simon_algorithm(
    oracle_function: Optional[Callable] = None,
    hidden_string: Optional[str] = None,
    n_qubits: Optional[int] = None,
    shots: int = 1024,
    max_attempts: int = 10,
    return_circuit: bool = False,
    verbose: bool = False
) -> Dict[str, Any]:
    """
    Simon's algorithm to find the period of a function

    Given a function f: {0,1}ⁿ → {0,1}ⁿ such that f(x) = f(x ⊕ s)
    for some hidden string s, Simon's algorithm finds s using O(n) queries
    (exponential speedup over classical O(2^{n/2})).

    Args:
        oracle_function: Oracle function f(x) that returns a bitstring
                         If provided, hidden_string is ignored.
        hidden_string: Hidden string s (e.g., '101')
                       If provided, oracle is constructed automatically.
        n_qubits: Number of qubits (automatically determined if not provided)
        shots: Number of measurement shots
        max_attempts: Maximum number of attempts to find s
        return_circuit: If True, return the circuit as well
        verbose: Print progress information

    Returns:
        Dict: Results including the found string

    Example:
        >>> # Find hidden string '101'
        >>> result = simon_algorithm(hidden_string='101')
        >>> print(result['hidden_string'])  # '101'
        >>> print(result['found_string'])   # '101'

        >>> # With custom oracle
        >>> def oracle(x):
        ...     # f(x) = x if x[0] == 0, else x ⊕ s
        ...     s = [1, 0, 1]
        ...     if x[0] == 0:
        ...         return x
        ...     else:
        ...         return [(xi ^ si) for xi, si in zip(x, s)]
        >>> result = simon_algorithm(oracle_function=oracle, n_qubits=3)
    """
    logger.info("Running Simon's algorithm")

    # Determine n_qubits
    if n_qubits is None:
        if hidden_string is not None:
            n_qubits = len(hidden_string)
        elif oracle_function is not None:
            # Try to infer from oracle (would need inspection)
            n_qubits = 3  # Default
            logger.warning("n_qubits not provided, using default 3")
        else:
            raise ValueError("Either oracle_function or hidden_string must be provided")

    validate_qubits(n_qubits)

    # Build oracle if hidden_string is provided
    if hidden_string is not None:
        if len(hidden_string) != n_qubits:
            raise ValueError(f"hidden_string length {len(hidden_string)} does not match n_qubits {n_qubits}")

        # Convert to list of ints
        hidden_bits = [int(b) for b in hidden_string]

        # Create oracle function
        def built_oracle(x: List[int]) -> List[int]:
            """Oracle that implements f(x) = x ⊕ s"""
            # f(x) = x if x[0] == 0, else x ⊕ s
            if x[0] == 0:
                return x.copy()
            else:
                return [(xi ^ si) for xi, si in zip(x, hidden_bits)]

        oracle = built_oracle
    else:
        oracle = oracle_function
        hidden_bits = None

    # Run Simon's algorithm multiple times to find s
    found_string = None
    equations = []
    attempts = 0

    while attempts < max_attempts:
        attempts += 1

        if verbose:
            logger.info(f"Attempt {attempts}/{max_attempts}")

        # Run the quantum circuit
        result = _simon_circuit(oracle, n_qubits, shots=shots)

        # Get the measured bitstring
        counts = result['counts']
        most_likely = max(counts, key=counts.get) if counts else None

        if most_likely is not None:
            # The measured bitstring y satisfies y · s = 0 (mod 2)
            # We collect these equations to solve for s
            y_bits = [int(b) for b in most_likely]

            # Skip zero vector
            if all(b == 0 for b in y_bits):
                continue

            # Add equation to the system
            equations.append(y_bits)

            if verbose:
                logger.info(f"Found equation: {most_likely} · s = 0")

            # Try to solve the system of equations
            solution = _solve_linear_system(equations, n_qubits)

            if solution is not None:
                found_string = ''.join(str(b) for b in solution)

                # Verify the solution
                if hidden_string is not None:
                    if found_string == hidden_string:
                        break
                else:
                    # Verify using the oracle
                    if _verify_solution(oracle, found_string, n_qubits):
                        break

    # Build result
    result_dict = {
        'hidden_string': hidden_string,
        'found_string': found_string,
        'equations': equations,
        'attempts': attempts,
        'shots': shots,
        'n_qubits': n_qubits,
        'success': found_string is not None and (hidden_string is None or found_string == hidden_string),
        'algorithm': 'simon'
    }

    if return_circuit:
        result_dict['circuit'] = result.get('circuit') if 'result' in locals() else None

    logger.info(f"Simon's algorithm result: found={found_string}, success={result_dict['success']}")

    return result_dict

simon_classical(oracle, n_qubits, max_attempts=20)

Classical version of Simon's algorithm (for comparison)

This is the classical algorithm for finding the period, which requires O(2^{n/2}) queries.

Parameters:

Name Type Description Default
oracle Callable

Oracle function f(x)

required
n_qubits int

Number of qubits

required
max_attempts int

Maximum number of attempts

20

Returns:

Type Description
Optional[str]

Optional[str]: Found period or None if not found

Example

def oracle(x): ... s = [1, 0, 1] ... if x[0] == 0: ... return x ... else: ... return [(xi ^ si) for xi, si in zip(x, s)] result = simon_classical(oracle, 3) print(result) # '101'

Source code in psiqit\algorithms\simon.py
def simon_classical(
    oracle: Callable,
    n_qubits: int,
    max_attempts: int = 20
) -> Optional[str]:
    """
    Classical version of Simon's algorithm (for comparison)

    This is the classical algorithm for finding the period,
    which requires O(2^{n/2}) queries.

    Args:
        oracle: Oracle function f(x)
        n_qubits: Number of qubits
        max_attempts: Maximum number of attempts

    Returns:
        Optional[str]: Found period or None if not found

    Example:
        >>> def oracle(x):
        ...     s = [1, 0, 1]
        ...     if x[0] == 0:
        ...         return x
        ...     else:
        ...         return [(xi ^ si) for xi, si in zip(x, s)]
        >>> result = simon_classical(oracle, 3)
        >>> print(result)  # '101'
    """
    # Find pairs (x, y) such that f(x) = f(y)
    # Then y = x ⊕ s, so s = x ⊕ y

    pairs = {}

    for attempt in range(max_attempts):
        # Generate random x
        x_int = np.random.randint(0, 2 ** n_qubits)
        x = [int(b) for b in format(x_int, f'0{n_qubits}b')]

        # Compute f(x)
        fx = oracle(x)
        fx_tuple = tuple(fx)

        # Check if we've seen this value before
        if fx_tuple in pairs:
            y = pairs[fx_tuple]

            # Compute s = x ⊕ y
            s = [(xi ^ yi) for xi, yi in zip(x, y)]

            # Verify the solution
            if _verify_solution(oracle, ''.join(str(b) for b in s), n_qubits):
                return ''.join(str(b) for b in s)
        else:
            pairs[fx_tuple] = x

    return None

create_simon_oracle(hidden_string)

Create an oracle for Simon's algorithm

The oracle implements f(x) = x if x[0] == 0, else x ⊕ s

Parameters:

Name Type Description Default
hidden_string str

Hidden string s

required

Returns:

Name Type Description
Callable Callable

Oracle function

Example

oracle = create_simon_oracle('101') print(oracle([0, 0, 0])) # [0, 0, 0] print(oracle([1, 0, 0])) # [1, 0, 1]

Source code in psiqit\algorithms\simon.py
def create_simon_oracle(hidden_string: str) -> Callable:
    """
    Create an oracle for Simon's algorithm

    The oracle implements f(x) = x if x[0] == 0, else x ⊕ s

    Args:
        hidden_string: Hidden string s

    Returns:
        Callable: Oracle function

    Example:
        >>> oracle = create_simon_oracle('101')
        >>> print(oracle([0, 0, 0]))  # [0, 0, 0]
        >>> print(oracle([1, 0, 0]))  # [1, 0, 1]
    """
    s = [int(b) for b in hidden_string]

    def oracle(x: List[int]) -> List[int]:
        """Oracle for Simon's algorithm"""
        if len(x) != len(s):
            raise ValueError(f"Input length {len(x)} does not match hidden string length {len(s)}")

        # f(x) = x if first bit is 0, else x ⊕ s
        if x[0] == 0:
            return x.copy()
        else:
            return [(xi ^ si) for xi, si in zip(x, s)]

    return oracle

is_periodic(oracle, s, n_qubits)

Check if s is a period of the oracle function

Parameters:

Name Type Description Default
oracle Callable

Oracle function

required
s List[int]

Candidate period

required
n_qubits int

Number of qubits

required

Returns:

Name Type Description
bool bool

True if s is a period, False otherwise

Source code in psiqit\algorithms\simon.py
def is_periodic(oracle: Callable, s: List[int], n_qubits: int) -> bool:
    """
    Check if s is a period of the oracle function

    Args:
        oracle: Oracle function
        s: Candidate period
        n_qubits: Number of qubits

    Returns:
        bool: True if s is a period, False otherwise
    """
    return _verify_solution(oracle, ''.join(str(b) for b in s), n_qubits)

qft_circuit(n_qubits, inverse=False, with_measurements=False)

Create a Quantum Fourier Transform circuit

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required
inverse bool

If True, create inverse QFT (IQFT)

False
with_measurements bool

If True, include measurement gates

False

Returns:

Name Type Description
QuantumCircuit QuantumCircuit

QFT circuit

Example

circ = qft_circuit(3) print(circ.draw())

Source code in psiqit\algorithms\qft.py
def qft_circuit(n_qubits: int, inverse: bool = False, with_measurements: bool = False) -> QuantumCircuit:
    """
    Create a Quantum Fourier Transform circuit

    Args:
        n_qubits: Number of qubits
        inverse: If True, create inverse QFT (IQFT)
        with_measurements: If True, include measurement gates

    Returns:
        QuantumCircuit: QFT circuit

    Example:
        >>> circ = qft_circuit(3)
        >>> print(circ.draw())
    """
    validate_qubits(n_qubits)

    if inverse:
        circuit = _iqft_circuit(n_qubits)
    else:
        circuit = _qft_circuit(n_qubits)

    if with_measurements:
        for i in range(n_qubits):
            # We don't add measurements here to keep the circuit clean
            # Measurements can be added separately
            pass

    logger.info(f"{'Inverse ' if inverse else ''}QFT circuit created with {n_qubits} qubits")

    return circuit

qft_matrix(n_qubits)

Generate the QFT matrix for n qubits

The QFT matrix is a unitary matrix of size 2^n × 2^n: (QFT)_{j,k} = (1/√N) ω^{j*k} where ω = e^{2πi/N} and N = 2^n

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required

Returns:

Type Description
ndarray

np.ndarray: QFT matrix (2^n × 2^n)

Example

Q = qft_matrix(2) print(Q) # 4×4 QFT matrix

Source code in psiqit\algorithms\qft.py
def qft_matrix(n_qubits: int) -> np.ndarray:
    """
    Generate the QFT matrix for n qubits

    The QFT matrix is a unitary matrix of size 2^n × 2^n:
    (QFT)_{j,k} = (1/√N) ω^{j*k}
    where ω = e^{2πi/N} and N = 2^n

    Args:
        n_qubits: Number of qubits

    Returns:
        np.ndarray: QFT matrix (2^n × 2^n)

    Example:
        >>> Q = qft_matrix(2)
        >>> print(Q)  # 4×4 QFT matrix
    """
    validate_qubits(n_qubits)
    N = 2 ** n_qubits

    QFT = np.zeros((N, N), dtype=complex)

    for j in range(N):
        for k in range(N):
            QFT[j, k] = np.exp(2j * np.pi * j * k / N) / np.sqrt(N)

    return QFT

iqft_matrix(n_qubits)

Generate the inverse QFT matrix

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required

Returns:

Type Description
ndarray

np.ndarray: Inverse QFT matrix

Example

Q_inv = iqft_matrix(2) Q = qft_matrix(2) print(np.allclose(Q @ Q_inv, np.eye(4))) # True

Source code in psiqit\algorithms\qft.py
def iqft_matrix(n_qubits: int) -> np.ndarray:
    """
    Generate the inverse QFT matrix

    Args:
        n_qubits: Number of qubits

    Returns:
        np.ndarray: Inverse QFT matrix

    Example:
        >>> Q_inv = iqft_matrix(2)
        >>> Q = qft_matrix(2)
        >>> print(np.allclose(Q @ Q_inv, np.eye(4)))  # True
    """
    QFT = qft_matrix(n_qubits)
    return QFT.conj().T

iqft(state, n_qubits=None)

Apply inverse Quantum Fourier Transform to a state

Parameters:

Name Type Description Default
state Union[Ket, ndarray, List]

Input state (Ket, list, or numpy array)

required
n_qubits Optional[int]

Number of qubits (auto-detected if not provided)

None

Returns:

Name Type Description
Ket Ket

Inverse QFT-transformed state

Example

from psiqit.quantum import Ket state = Ket([1, 0, 0, 0]) qft_state = qft(state) original = iqft(qft_state) print(np.allclose(original.data, state.data)) # True

Source code in psiqit\algorithms\qft.py
def iqft(state: Union[Ket, np.ndarray, List], n_qubits: Optional[int] = None) -> Ket:
    """
    Apply inverse Quantum Fourier Transform to a state

    Args:
        state: Input state (Ket, list, or numpy array)
        n_qubits: Number of qubits (auto-detected if not provided)

    Returns:
        Ket: Inverse QFT-transformed state

    Example:
        >>> from psiqit.quantum import Ket
        >>> state = Ket([1, 0, 0, 0])
        >>> qft_state = qft(state)
        >>> original = iqft(qft_state)
        >>> print(np.allclose(original.data, state.data))  # True
    """
    if isinstance(state, Ket):
        data = state.data
        if n_qubits is None:
            n_qubits = int(np.log2(len(data)))
    else:
        data = np.array(state, dtype=complex)
        if n_qubits is None:
            n_qubits = int(np.log2(len(data)))

    validate_qubits(n_qubits)
    dim = 2 ** n_qubits

    if len(data) != dim:
        raise ValueError(f"State dimension {len(data)} does not match 2^{n_qubits} = {dim}")

    # Build inverse QFT matrix
    IQFT_matrix = iqft_matrix(n_qubits)

    # Apply to state
    result = IQFT_matrix @ data

    logger.info(f"Inverse QFT applied to {n_qubits}-qubit state")

    return Ket(result)

qft_controlled(n_qubits)

Create a controlled QFT circuit

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required

Returns:

Name Type Description
QuantumCircuit QuantumCircuit

Controlled QFT circuit

Note

This is a placeholder for future implementation

Source code in psiqit\algorithms\qft.py
def qft_controlled(n_qubits: int) -> QuantumCircuit:
    """
    Create a controlled QFT circuit

    Args:
        n_qubits: Number of qubits

    Returns:
        QuantumCircuit: Controlled QFT circuit

    Note:
        This is a placeholder for future implementation
    """
    # This would require additional qubits for control
    # For now, we return the standard QFT circuit
    logger.warning("Controlled QFT is not fully implemented")
    return qft_circuit(n_qubits)

qft_basis_state(n_qubits, state_index)

Apply QFT to a basis state |j⟩ without constructing the full state

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required
state_index int

Index of the basis state (0 to 2^n - 1)

required

Returns:

Name Type Description
Ket Ket

QFT-transformed basis state

Example

result = qft_basis_state(2, 1) # QFT(|01⟩) print(result) # Fourier basis state

Source code in psiqit\algorithms\qft.py
def qft_basis_state(n_qubits: int, state_index: int) -> Ket:
    """
    Apply QFT to a basis state |j⟩ without constructing the full state

    Args:
        n_qubits: Number of qubits
        state_index: Index of the basis state (0 to 2^n - 1)

    Returns:
        Ket: QFT-transformed basis state

    Example:
        >>> result = qft_basis_state(2, 1)  # QFT(|01⟩)
        >>> print(result)  # Fourier basis state
    """
    validate_qubits(n_qubits)
    N = 2 ** n_qubits

    if state_index < 0 or state_index >= N:
        raise ValueError(f"state_index {state_index} out of range [0, {N-1}]")

    # Create basis state
    state = basis(N, state_index)

    # Apply QFT
    return qft(state)

qft_product_state(n_qubits, amplitudes)

Apply QFT to a product state (tensor product of single-qubit states)

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required
amplitudes List[complex]

List of amplitudes for the product state

required

Returns:

Name Type Description
Ket Ket

QFT-transformed state

Example

amplitudes = [1/np.sqrt(2), 1/np.sqrt(2)] # |+⟩ result = qft_product_state(2, amplitudes)

Source code in psiqit\algorithms\qft.py
def qft_product_state(n_qubits: int, amplitudes: List[complex]) -> Ket:
    """
    Apply QFT to a product state (tensor product of single-qubit states)

    Args:
        n_qubits: Number of qubits
        amplitudes: List of amplitudes for the product state

    Returns:
        Ket: QFT-transformed state

    Example:
        >>> amplitudes = [1/np.sqrt(2), 1/np.sqrt(2)]  # |+⟩
        >>> result = qft_product_state(2, amplitudes)
    """
    validate_qubits(n_qubits)

    # Build the product state
    state_data = np.array([1.0], dtype=complex)
    for amp in amplitudes[:n_qubits]:
        amp_array = np.array(amp, dtype=complex)
        if len(amp_array.shape) == 0:
            amp_array = np.array([amp_array], dtype=complex)
        state_data = np.kron(state_data, amp_array)

    # Normalize
    norm = np.linalg.norm(state_data)
    if norm > 0:
        state_data = state_data / norm

    return qft(Ket(state_data))

compare_qft_to_fft(n_qubits, state_index=0)

Compare QFT to classical FFT on a basis state

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required
state_index int

Index of the basis state

0

Returns:

Name Type Description
Dict Dict[str, Any]

Comparison results

Example

result = compare_qft_to_fft(3, 2) print(result['max_difference']) # Numerical difference

Source code in psiqit\algorithms\qft.py
def compare_qft_to_fft(n_qubits: int, state_index: int = 0) -> Dict[str, Any]:
    """
    Compare QFT to classical FFT on a basis state

    Args:
        n_qubits: Number of qubits
        state_index: Index of the basis state

    Returns:
        Dict: Comparison results

    Example:
        >>> result = compare_qft_to_fft(3, 2)
        >>> print(result['max_difference'])  # Numerical difference
    """
    from scipy.fft import fft

    N = 2 ** n_qubits

    # Create basis state
    state = np.zeros(N, dtype=complex)
    state[state_index] = 1.0

    # Apply QFT (quantum)
    qft_state = qft(Ket(state))
    qft_result = qft_state.data

    # Apply FFT (classical)
    fft_result = fft(state) / np.sqrt(N)

    # Compare
    max_diff = np.max(np.abs(qft_result - fft_result))

    return {
        'n_qubits': n_qubits,
        'state_index': state_index,
        'max_difference': float(max_diff),
        'qft_result': qft_result.tolist(),
        'fft_result': fft_result.tolist(),
        'is_close': max_diff < 1e-10
    }

qft_circuit_comparison(n_qubits)

Compare QFT circuit complexity

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required

Returns:

Name Type Description
Dict Dict[str, int]

Circuit statistics

Example

stats = qft_circuit_comparison(3) print(stats['gates']) # Number of gates in QFT circuit

Source code in psiqit\algorithms\qft.py
def qft_circuit_comparison(n_qubits: int) -> Dict[str, int]:
    """
    Compare QFT circuit complexity

    Args:
        n_qubits: Number of qubits

    Returns:
        Dict: Circuit statistics

    Example:
        >>> stats = qft_circuit_comparison(3)
        >>> print(stats['gates'])  # Number of gates in QFT circuit
    """
    circ = qft_circuit(n_qubits)

    return {
        'n_qubits': n_qubits,
        'depth': circ.depth,
        'gates': len(circ.get_gates()),
        'classical_ops': 2 ** n_qubits * n_qubits,  # Classical FFT complexity
        'quantum_ops': n_qubits * (n_qubits + 1) // 2  # QFT complexity
    }

qft_phase_estimation_prep(n_qubits)

Create a circuit for QFT-based phase estimation (initialization part)

Parameters:

Name Type Description Default
n_qubits int

Number of qubits for phase estimation

required

Returns:

Name Type Description
QuantumCircuit QuantumCircuit

Phase estimation preparation circuit

Source code in psiqit\algorithms\qft.py
def qft_phase_estimation_prep(n_qubits: int) -> QuantumCircuit:
    """
    Create a circuit for QFT-based phase estimation (initialization part)

    Args:
        n_qubits: Number of qubits for phase estimation

    Returns:
        QuantumCircuit: Phase estimation preparation circuit
    """
    circuit = QuantumCircuit(n_qubits)

    # Initialize to |+⟩⊗n
    for i in range(n_qubits):
        circuit.h(i)

    return circuit

qft_phase_estimation_measure(n_qubits)

Create a circuit for QFT-based phase estimation (measurement part)

Parameters:

Name Type Description Default
n_qubits int

Number of qubits

required

Returns:

Name Type Description
QuantumCircuit QuantumCircuit

Phase estimation measurement circuit

Source code in psiqit\algorithms\qft.py
def qft_phase_estimation_measure(n_qubits: int) -> QuantumCircuit:
    """
    Create a circuit for QFT-based phase estimation (measurement part)

    Args:
        n_qubits: Number of qubits

    Returns:
        QuantumCircuit: Phase estimation measurement circuit
    """
    # This is essentially the inverse QFT
    return _iqft_circuit(n_qubits)

quantum_phase_estimation(unitary, n_qubits, state=None, shots=1024, return_circuit=False, return_all=False)

Quantum Phase Estimation algorithm

Estimates the phase φ such that U|ψ⟩ = e^{2πiφ}|ψ⟩ where U is a unitary operator and |ψ⟩ is an eigenstate.

Parameters:

Name Type Description Default
unitary Union[Operator, Callable]

Unitary operator (Operator or callable that applies U)

required
n_qubits int

Number of qubits for phase estimation (precision)

required
state Optional[Ket]

Eigenstate of U (if None, uses |0...0⟩)

None
shots int

Number of measurement shots

1024
return_circuit bool

If True, return the circuit

False
return_all bool

If True, return all details

False

Returns:

Name Type Description
Dict Dict[str, Any]

Results including estimated phase

Example

from psiqit.quantum import pauli_z, zero

Estimate phase of Z gate on |0⟩ (eigenvalue = 1, phase = 0)

result = quantum_phase_estimation(pauli_z(), n_qubits=3, state=zero()) print(result['phase']) # 0.0 print(result['phase_angle']) # 0.0

Estimate phase of Z gate on |1⟩ (eigenvalue = -1, phase = 0.5)

from psiqit.quantum import one result = quantum_phase_estimation(pauli_z(), n_qubits=3, state=one()) print(result['phase']) # 0.5 print(result['phase_angle']) # π

Source code in psiqit\algorithms\qpe.py
def quantum_phase_estimation(
    unitary: Union[Operator, Callable],
    n_qubits: int,
    state: Optional[Ket] = None,
    shots: int = 1024,
    return_circuit: bool = False,
    return_all: bool = False
) -> Dict[str, Any]:
    """
    Quantum Phase Estimation algorithm

    Estimates the phase φ such that U|ψ⟩ = e^{2πiφ}|ψ⟩
    where U is a unitary operator and |ψ⟩ is an eigenstate.

    Args:
        unitary: Unitary operator (Operator or callable that applies U)
        n_qubits: Number of qubits for phase estimation (precision)
        state: Eigenstate of U (if None, uses |0...0⟩)
        shots: Number of measurement shots
        return_circuit: If True, return the circuit
        return_all: If True, return all details

    Returns:
        Dict: Results including estimated phase

    Example:
        >>> from psiqit.quantum import pauli_z, zero
        >>> # Estimate phase of Z gate on |0⟩ (eigenvalue = 1, phase = 0)
        >>> result = quantum_phase_estimation(pauli_z(), n_qubits=3, state=zero())
        >>> print(result['phase'])  # 0.0
        >>> print(result['phase_angle'])  # 0.0

        >>> # Estimate phase of Z gate on |1⟩ (eigenvalue = -1, phase = 0.5)
        >>> from psiqit.quantum import one
        >>> result = quantum_phase_estimation(pauli_z(), n_qubits=3, state=one())
        >>> print(result['phase'])  # 0.5
        >>> print(result['phase_angle'])  # π
    """
    logger.info(f"Quantum Phase Estimation: {n_qubits} qubits")

    # Determine the dimension of the unitary
    if isinstance(unitary, Operator):
        dim = unitary.dim
        # Check if state is provided
        if state is not None and state.dim != dim:
            raise ValueError(f"State dimension {state.dim} does not match unitary dimension {dim}")
    else:
        # Callable unitary - we need to infer dimension
        # Use a test state
        test_state = Ket(np.array([1.0] + [0.0] * (2 ** n_qubits - 1)))
        dim = len(test_state.data)

    # If state is not provided, use |0...0⟩
    if state is None:
        state = basis(dim, 0)

    # Create circuit with n_qubits + m qubits (m = log2(dim) for the unitary)
    # For simplicity, we assume the unitary acts on a single qubit or system
    # The number of qubits for the unitary is log2(dim)
    m = int(np.log2(dim))
    total_qubits = n_qubits + m

    circuit = QuantumCircuit(total_qubits)

    # Prepare eigenstate |ψ⟩ on the last m qubits
    for i in range(m):
        if state.data[i] != 0:
            # This is a simplified version - for general states, we'd need more gates
            circuit.x(n_qubits + i)

    # Apply Hadamard to all phase estimation qubits
    for i in range(n_qubits):
        circuit.h(i)

    # Apply controlled-U operations
    for i in range(n_qubits):
        power = 2 ** i
        # Apply U^(2^i) controlled by qubit i
        _apply_controlled_unitary(circuit, unitary, i, list(range(n_qubits, total_qubits)), power)

    # Apply inverse QFT on the phase estimation qubits
    iqft_circ = _iqft_circuit(n_qubits)
    # Add IQFT gates to the circuit
    for gate in iqft_circ.get_gates():
        # Extract gate info and apply to the first n_qubits
        if gate['name'] == 'H':
            q = gate['qubits'][0]
            circuit.h(q)
        elif gate['name'] == 'SWAP':
            q1, q2 = gate['qubits'][0], gate['qubits'][1]
            circuit.swap(q1, q2)
        elif gate['name'] == 'CU1':
            # Controlled phase gate
            q_control, q_target = gate['qubits'][0], gate['qubits'][1]
            angle = gate['params'][0] if gate['params'] else 0
            circuit.cu1(angle, q_control, q_target)

    # Measure the phase estimation qubits
    result = circuit.measure(shots=shots)
    counts = result['counts']

    # Find most likely phase
    most_likely_binary = max(counts, key=counts.get) if counts else None

    # Convert binary to phase
    if most_likely_binary is not None:
        # Take only the first n_qubits bits
        phase_bits = most_likely_binary[:n_qubits]
        phase_value = int(phase_bits, 2) / (2 ** n_qubits)
        phase_angle = 2 * np.pi * phase_value
    else:
        phase_value = 0.0
        phase_angle = 0.0

    # Build result
    result_dict = {
        'phase': phase_value,
        'phase_angle': phase_angle,
        'phase_bits': most_likely_binary[:n_qubits] if most_likely_binary else None,
        'counts': counts,
        'shots': shots,
        'n_qubits': n_qubits,
        'algorithm': 'quantum_phase_estimation'
    }

    if return_circuit:
        result_dict['circuit'] = circuit

    if return_all:
        result_dict['all_counts'] = counts
        result_dict['most_likely_binary'] = most_likely_binary

    logger.info(f"QPE result: phase={phase_value:.6f}, angle={phase_angle:.6f}")

    return result_dict

qpe_circuit(n_qubits, m_qubits=1, with_measurements=True)

Create a Quantum Phase Estimation circuit

Parameters:

Name Type Description Default
n_qubits int

Number of qubits for phase estimation (precision)

required
m_qubits int

Number of qubits for the unitary (default: 1)

1
with_measurements bool

Include measurement gates

True

Returns:

Name Type Description
QuantumCircuit QuantumCircuit

QPE circuit

Example

circ = qpe_circuit(n_qubits=3, m_qubits=1) print(circ.draw())

Source code in psiqit\algorithms\qpe.py
def qpe_circuit(
    n_qubits: int,
    m_qubits: int = 1,
    with_measurements: bool = True
) -> QuantumCircuit:
    """
    Create a Quantum Phase Estimation circuit

    Args:
        n_qubits: Number of qubits for phase estimation (precision)
        m_qubits: Number of qubits for the unitary (default: 1)
        with_measurements: Include measurement gates

    Returns:
        QuantumCircuit: QPE circuit

    Example:
        >>> circ = qpe_circuit(n_qubits=3, m_qubits=1)
        >>> print(circ.draw())
    """
    total_qubits = n_qubits + m_qubits
    circuit = QuantumCircuit(total_qubits)

    # Apply Hadamard to phase estimation qubits
    for i in range(n_qubits):
        circuit.h(i)

    # Controlled-U operations (placeholder)
    # In a real circuit, these would be implemented for a specific U

    # Inverse QFT
    iqft_circ = _iqft_circuit(n_qubits)
    for gate in iqft_circ.get_gates():
        if gate['name'] == 'H':
            q = gate['qubits'][0]
            circuit.h(q)
        elif gate['name'] == 'SWAP':
            q1, q2 = gate['qubits'][0], gate['qubits'][1]
            circuit.swap(q1, q2)
        elif gate['name'] == 'CU1':
            q_control, q_target = gate['qubits'][0], gate['qubits'][1]
            angle = gate['params'][0] if gate['params'] else 0
            circuit.cu1(angle, q_control, q_target)

    # Measurements
    if with_measurements:
        for i in range(n_qubits):
            # Measurements are not added here to keep the circuit clean
            pass

    logger.info(f"QPE circuit created: {n_qubits} phase qubits, {m_qubits} system qubits")

    return circuit

qpe_pauli_z(n_qubits, state, shots=1024)

Run QPE on Pauli-Z gate

Parameters:

Name Type Description Default
n_qubits int

Number of qubits for phase estimation

required
state Ket

Eigenstate of Z (|0⟩ or |1⟩)

required
shots int

Number of measurement shots

1024

Returns:

Name Type Description
Dict Dict[str, Any]

Results

Example

from psiqit.quantum import zero, one result = qpe_pauli_z(3, zero()) # phase = 0 print(result['phase']) # 0.0 result = qpe_pauli_z(3, one()) # phase = 0.5 print(result['phase']) # 0.5

Source code in psiqit\algorithms\qpe.py
def qpe_pauli_z(n_qubits: int, state: Ket, shots: int = 1024) -> Dict[str, Any]:
    """
    Run QPE on Pauli-Z gate

    Args:
        n_qubits: Number of qubits for phase estimation
        state: Eigenstate of Z (|0⟩ or |1⟩)
        shots: Number of measurement shots

    Returns:
        Dict: Results

    Example:
        >>> from psiqit.quantum import zero, one
        >>> result = qpe_pauli_z(3, zero())  # phase = 0
        >>> print(result['phase'])  # 0.0
        >>> result = qpe_pauli_z(3, one())   # phase = 0.5
        >>> print(result['phase'])  # 0.5
    """
    from ..quantum.operator import pauli_z

    # Check if state is eigenstate of Z
    if not (np.allclose(state.data, zero().data) or np.allclose(state.data, one().data)):
        logger.warning("State is not an eigenstate of Z, results may be mixed")

    return quantum_phase_estimation(
        unitary=pauli_z(),
        n_qubits=n_qubits,
        state=state,
        shots=shots
    )

qpe_rotation_gate(n_qubits, angle, state, shots=1024)

Run QPE on a rotation gate (RZ)

Parameters:

Name Type Description Default
n_qubits int

Number of qubits for phase estimation

required
angle float

Rotation angle

required
state Ket

Eigenstate of RZ (|0⟩ or |1⟩)

required
shots int

Number of measurement shots

1024

Returns:

Name Type Description
Dict Dict[str, Any]

Results

Example

from psiqit.quantum import zero result = qpe_rotation_gate(3, np.pi/4, zero()) print(result['phase']) # 0.125 (for |0⟩, phase = 0) result = qpe_rotation_gate(3, np.pi/4, one()) print(result['phase']) # 0.375 (for |1⟩, phase = angle/(2π))

Source code in psiqit\algorithms\qpe.py
def qpe_rotation_gate(n_qubits: int, angle: float, state: Ket, shots: int = 1024) -> Dict[str, Any]:
    """
    Run QPE on a rotation gate (RZ)

    Args:
        n_qubits: Number of qubits for phase estimation
        angle: Rotation angle
        state: Eigenstate of RZ (|0⟩ or |1⟩)
        shots: Number of measurement shots

    Returns:
        Dict: Results

    Example:
        >>> from psiqit.quantum import zero
        >>> result = qpe_rotation_gate(3, np.pi/4, zero())
        >>> print(result['phase'])  # 0.125 (for |0⟩, phase = 0)
        >>> result = qpe_rotation_gate(3, np.pi/4, one())
        >>> print(result['phase'])  # 0.375 (for |1⟩, phase = angle/(2π))
    """
    from ..quantum.operator import rz

    # Check if state is eigenstate of RZ
    if not (np.allclose(state.data, zero().data) or np.allclose(state.data, one().data)):
        logger.warning("State is not an eigenstate of RZ, results may be mixed")

    # For |0⟩, eigenvalue = 1 (phase = 0)
    # For |1⟩, eigenvalue = e^{-iθ} (phase = -θ/(2π))

    U = rz(angle)

    return quantum_phase_estimation(
        unitary=U,
        n_qubits=n_qubits,
        state=state,
        shots=shots
    )

phase_to_angle(phase)

Convert phase to angle (in radians)

Parameters:

Name Type Description Default
phase float

Phase value (0 to 1)

required

Returns:

Name Type Description
float float

Angle in radians

Example

phase_to_angle(0.5) # np.pi

Source code in psiqit\algorithms\qpe.py
def phase_to_angle(phase: float) -> float:
    """
    Convert phase to angle (in radians)

    Args:
        phase: Phase value (0 to 1)

    Returns:
        float: Angle in radians

    Example:
        >>> phase_to_angle(0.5)  # np.pi
    """
    return 2 * np.pi * phase

angle_to_phase(angle)

Convert angle to phase (0 to 1)

Parameters:

Name Type Description Default
angle float

Angle in radians

required

Returns:

Name Type Description
float float

Phase value (0 to 1)

Example

angle_to_phase(np.pi) # 0.5

Source code in psiqit\algorithms\qpe.py
def angle_to_phase(angle: float) -> float:
    """
    Convert angle to phase (0 to 1)

    Args:
        angle: Angle in radians

    Returns:
        float: Phase value (0 to 1)

    Example:
        >>> angle_to_phase(np.pi)  # 0.5
    """
    return angle / (2 * np.pi)

phase_to_eigenvalue(phase)

Convert phase to eigenvalue

Parameters:

Name Type Description Default
phase float

Phase value (0 to 1)

required

Returns:

Name Type Description
complex complex

Eigenvalue e^{2πiφ}

Example

phase_to_eigenvalue(0.5) # -1

Source code in psiqit\algorithms\qpe.py
def phase_to_eigenvalue(phase: float) -> complex:
    """
    Convert phase to eigenvalue

    Args:
        phase: Phase value (0 to 1)

    Returns:
        complex: Eigenvalue e^{2πiφ}

    Example:
        >>> phase_to_eigenvalue(0.5)  # -1
    """
    return np.exp(2j * np.pi * phase)

eigenvalue_to_phase(eigenvalue)

Convert eigenvalue to phase

Parameters:

Name Type Description Default
eigenvalue complex

Complex eigenvalue

required

Returns:

Name Type Description
float float

Phase value (0 to 1)

Example

eigenvalue_to_phase(-1) # 0.5

Source code in psiqit\algorithms\qpe.py
def eigenvalue_to_phase(eigenvalue: complex) -> float:
    """
    Convert eigenvalue to phase

    Args:
        eigenvalue: Complex eigenvalue

    Returns:
        float: Phase value (0 to 1)

    Example:
        >>> eigenvalue_to_phase(-1)  # 0.5
    """
    return np.angle(eigenvalue) / (2 * np.pi)

qpe_accuracy(n_qubits, true_phase)

Calculate the theoretical accuracy of QPE

Parameters:

Name Type Description Default
n_qubits int

Number of qubits for phase estimation

required
true_phase float

True phase value

required

Returns:

Name Type Description
Dict Dict[str, Any]

Accuracy statistics

Example

result = qpe_accuracy(3, 0.5) print(result['max_error']) # 1/2^3 = 0.125

Source code in psiqit\algorithms\qpe.py
def qpe_accuracy(n_qubits: int, true_phase: float) -> Dict[str, Any]:
    """
    Calculate the theoretical accuracy of QPE

    Args:
        n_qubits: Number of qubits for phase estimation
        true_phase: True phase value

    Returns:
        Dict: Accuracy statistics

    Example:
        >>> result = qpe_accuracy(3, 0.5)
        >>> print(result['max_error'])  # 1/2^3 = 0.125
    """
    N = 2 ** n_qubits
    resolution = 1 / N

    # Best approximation
    best_approx = round(true_phase * N) / N
    error = abs(true_phase - best_approx)

    return {
        'n_qubits': n_qubits,
        'resolution': resolution,
        'true_phase': true_phase,
        'best_approximation': best_approx,
        'error': error,
        'success_probability': np.sin(np.pi * N * error / 2) ** 2 if error > 0 else 1.0
    }

shor_factor(N, max_attempts=10, use_quantum=True, verbose=False)

Factor an integer N using Shor's algorithm

Parameters:

Name Type Description Default
N int

Integer to factor

required
max_attempts int

Maximum number of attempts

10
use_quantum bool

Use quantum algorithm (if False, use classical simulation)

True
verbose bool

Print progress information

False

Returns:

Type Description
Tuple[int, int]

Tuple[int, int]: Factors (p, q) such that p * q = N

Example

factors = shor_factor(15) print(factors) # (3, 5) factors = shor_factor(21) print(factors) # (3, 7) factors = shor_factor(35) print(factors) # (5, 7)

Source code in psiqit\algorithms\shor.py
def shor_factor(
    N: int,
    max_attempts: int = 10,
    use_quantum: bool = True,
    verbose: bool = False
) -> Tuple[int, int]:
    """
    Factor an integer N using Shor's algorithm

    Args:
        N: Integer to factor
        max_attempts: Maximum number of attempts
        use_quantum: Use quantum algorithm (if False, use classical simulation)
        verbose: Print progress information

    Returns:
        Tuple[int, int]: Factors (p, q) such that p * q = N

    Example:
        >>> factors = shor_factor(15)
        >>> print(factors)  # (3, 5)
        >>> factors = shor_factor(21)
        >>> print(factors)  # (3, 7)
        >>> factors = shor_factor(35)
        >>> print(factors)  # (5, 7)
    """
    if N < 2:
        raise ValueError(f"N must be >= 2, got {N}")

    # Check if N is even
    if N % 2 == 0:
        logger.info(f"N={N} is even: {N} = 2 × {N//2}")
        return 2, N // 2

    # Check if N is a perfect power
    root = _is_perfect_power(N)
    if root is not None:
        logger.info(f"N={N} is a perfect power: {root} × {root}")
        return root, N // root

    for attempt in range(max_attempts):
        if verbose:
            logger.info(f"Attempt {attempt + 1}/{max_attempts}")

        # Choose random a such that 1 < a < N
        a = random.randint(2, N - 1)

        # Check gcd(a, N)
        g = math.gcd(a, N)
        if g > 1:
            logger.info(f"Found factor via gcd: {g}")
            return g, N // g

        if verbose:
            logger.info(f"a = {a}, gcd(a, N) = 1")

        # Find period r of f(x) = a^x mod N
        if use_quantum:
            r = _quantum_period_finding(a, N, verbose=verbose)
        else:
            r = _classical_period_finding(a, N)

        if verbose:
            logger.info(f"Period r = {r}")

        # Check if r is even and a^{r/2} ≠ -1 mod N
        if r % 2 == 0:
            x = pow(a, r // 2, N)
            if x != N - 1:
                # Found factors
                p = math.gcd(x - 1, N)
                q = math.gcd(x + 1, N)

                if p > 1 and q > 1 and p * q == N:
                    logger.info(f"Found factors: {p} × {q} = {N}")
                    return p, q

    raise RuntimeError(f"Failed to factor {N} after {max_attempts} attempts")

shor_classical(N, max_attempts=10)

Classical version of Shor's algorithm (for comparison)

Parameters:

Name Type Description Default
N int

Integer to factor

required
max_attempts int

Maximum number of attempts

10

Returns:

Type Description
Tuple[int, int]

Tuple[int, int]: Factors

Example

factors = shor_classical(15) print(factors) # (3, 5)

Source code in psiqit\algorithms\shor.py
def shor_classical(
    N: int,
    max_attempts: int = 10
) -> Tuple[int, int]:
    """
    Classical version of Shor's algorithm (for comparison)

    Args:
        N: Integer to factor
        max_attempts: Maximum number of attempts

    Returns:
        Tuple[int, int]: Factors

    Example:
        >>> factors = shor_classical(15)
        >>> print(factors)  # (3, 5)
    """
    logger.info(f"Classical Shor's algorithm for N={N}")

    for attempt in range(max_attempts):
        # Choose random a
        a = random.randint(2, N - 1)

        # Check gcd
        g = math.gcd(a, N)
        if g > 1:
            return g, N // g

        # Find period
        r = _classical_period_finding(a, N)

        # Check if r is even
        if r % 2 == 0:
            x = pow(a, r // 2, N)
            if x != N - 1:
                p = math.gcd(x - 1, N)
                q = math.gcd(x + 1, N)
                if p > 1 and q > 1 and p * q == N:
                    return p, q

    raise RuntimeError(f"Failed to factor {N}")

shor_algorithm(N, use_quantum=True, verbose=True, max_attempts=10)

Run Shor's algorithm and return detailed results

Parameters:

Name Type Description Default
N int

Integer to factor

required
use_quantum bool

Use quantum algorithm (if False, use classical simulation)

True
verbose bool

Print progress

True
max_attempts int

Maximum number of attempts

10

Returns:

Name Type Description
Dict Dict[str, Any]

Detailed results

Example

result = shor_algorithm(15) print(result['factors']) # (3, 5) print(result['attempts']) # Number of attempts used print(result['method']) # 'quantum' or 'classical'

Source code in psiqit\algorithms\shor.py
def shor_algorithm(
    N: int,
    use_quantum: bool = True,
    verbose: bool = True,
    max_attempts: int = 10
) -> Dict[str, Any]:
    """
    Run Shor's algorithm and return detailed results

    Args:
        N: Integer to factor
        use_quantum: Use quantum algorithm (if False, use classical simulation)
        verbose: Print progress
        max_attempts: Maximum number of attempts

    Returns:
        Dict: Detailed results

    Example:
        >>> result = shor_algorithm(15)
        >>> print(result['factors'])  # (3, 5)
        >>> print(result['attempts'])  # Number of attempts used
        >>> print(result['method'])  # 'quantum' or 'classical'
    """
    logger.info(f"Shor's algorithm for N={N}")

    attempts = 0
    factor_pairs = []

    # Check small factors first
    if N % 2 == 0:
        factor_pairs = [(2, N // 2)]
        attempts = 1

    # Check perfect powers
    root = _is_perfect_power(N)
    if root is not None and not factor_pairs:
        factor_pairs = [(root, N // root)]
        attempts = 1

    # Main algorithm
    if not factor_pairs:
        for attempt in range(max_attempts):
            attempts += 1
            a = random.randint(2, N - 1)
            g = math.gcd(a, N)

            if g > 1:
                factor_pairs.append((g, N // g))
                break

            if use_quantum:
                r = _quantum_period_finding(a, N, verbose=verbose)
            else:
                r = _classical_period_finding(a, N)

            if r % 2 == 0:
                x = pow(a, r // 2, N)
                if x != N - 1:
                    p = math.gcd(x - 1, N)
                    q = math.gcd(x + 1, N)
                    if p > 1 and q > 1 and p * q == N:
                        factor_pairs.append((p, q))
                        break

    if not factor_pairs:
        raise RuntimeError(f"Failed to factor {N} after {max_attempts} attempts")

    # Sort factors
    factors = tuple(sorted(factor_pairs[0]))

    return {
        'N': N,
        'factors': factors,
        'attempts': attempts,
        'method': 'quantum' if use_quantum else 'classical',
        'success': True,
        'algorithm': 'shor'
    }

shor_steps(N, a, r)

Show the steps of Shor's algorithm for a given a and period

Parameters:

Name Type Description Default
N int

Integer to factor

required
a int

Random base

required
r int

Period of a^x mod N

required

Returns:

Name Type Description
Dict Dict[str, Any]

Step-by-step results

Example

result = shor_steps(15, 7, 4) print(result['step1']) # "Choose a = 7, gcd(7, 15) = 1" print(result['step2']) # "Find period r = 4" print(result['step3']) # "r is even" print(result['step4']) # "x = 7^2 mod 15 = 4" print(result['step5']) # "Factors: gcd(3, 15) = 3, gcd(5, 15) = 5"

Source code in psiqit\algorithms\shor.py
def shor_steps(N: int, a: int, r: int) -> Dict[str, Any]:
    """
    Show the steps of Shor's algorithm for a given a and period

    Args:
        N: Integer to factor
        a: Random base
        r: Period of a^x mod N

    Returns:
        Dict: Step-by-step results

    Example:
        >>> result = shor_steps(15, 7, 4)
        >>> print(result['step1'])  # "Choose a = 7, gcd(7, 15) = 1"
        >>> print(result['step2'])  # "Find period r = 4"
        >>> print(result['step3'])  # "r is even"
        >>> print(result['step4'])  # "x = 7^2 mod 15 = 4"
        >>> print(result['step5'])  # "Factors: gcd(3, 15) = 3, gcd(5, 15) = 5"
    """
    steps = {}

    steps['step1'] = f"Choose a = {a}, gcd({a}, {N}) = {math.gcd(a, N)}"

    if math.gcd(a, N) > 1:
        steps['step2'] = f"Found factor via gcd: {math.gcd(a, N)}"
        return steps

    steps['step2'] = f"Find period r of f(x) = {a}^x mod {N}: r = {r}"

    if r % 2 != 0:
        steps['step3'] = f"r = {r} is odd, try another a"
        return steps

    steps['step3'] = f"r = {r} is even"

    x = pow(a, r // 2, N)
    steps['step4'] = f"x = {a}^{r//2} mod {N} = {x}"

    if x == N - 1:
        steps['step5'] = f"x = {N-1} = -1 mod {N}, try another a"
        return steps

    p = math.gcd(x - 1, N)
    q = math.gcd(x + 1, N)

    steps['step5'] = f"Factors: gcd({x-1}, {N}) = {p}, gcd({x+1}, {N}) = {q}"

    if p * q == N:
        steps['step6'] = f"Success! {N} = {p} × {q}"
    else:
        steps['step6'] = f"Failed: {p} × {q} = {p*q} ≠ {N}"

    return steps

info()

Get information about the algorithms module

Returns:

Name Type Description
dict dict

Module information

Source code in psiqit\algorithms\__init__.py
def info() -> dict:
    """
    Get information about the algorithms module

    Returns:
        dict: Module information
    """
    return {
        'module': 'psiqit.algorithms',
        'version': __version__,
        'submodules': [
            'grover',
            'deutsch_jozsa',
            'bernstein_vazirani',
            'simon',
            'qft',
            'qpe',
            'shor'
        ],
        'exports': len(__all__),
    }

test()

Run basic tests for the algorithms module

Returns:

Name Type Description
dict dict

Test results

Source code in psiqit\algorithms\__init__.py
def test() -> dict:
    """
    Run basic tests for the algorithms module

    Returns:
        dict: Test results
    """
    results = {}

    # Test grover
    try:
        from .grover import grover_search
        result = grover_search(n_qubits=3, target=5, shots=100)
        results['grover'] = 'most_likely' in result
    except Exception as e:
        results['grover'] = str(e)

    # Test deutsch_jozsa
    try:
        from .deutsch_jozsa import deutsch_jozsa
        result = deutsch_jozsa(function_type='constant_zero', n_qubits=3, shots=100)
        results['deutsch_jozsa'] = result['result'] == 'constant'
    except Exception as e:
        results['deutsch_jozsa'] = str(e)

    # Test bernstein_vazirani
    try:
        from .bernstein_vazirani import bernstein_vazirani
        result = bernstein_vazirani(hidden_string='101', shots=100)
        results['bernstein_vazirani'] = result['found_string'] == '101'
    except Exception as e:
        results['bernstein_vazirani'] = str(e)

    # Test simon
    try:
        from .simon import simon_algorithm, create_simon_oracle
        oracle = create_simon_oracle('101')
        result = simon_algorithm(oracle_function=oracle, n_qubits=3, shots=100, max_attempts=5)
        results['simon'] = result['found_string'] == '101'
    except Exception as e:
        results['simon'] = str(e)

    # Test qft
    try:
        from .qft import qft
        from ..quantum.state import Ket
        state = Ket([1, 0, 0, 0])
        result = qft(state)
        results['qft'] = result.dim == 4
    except Exception as e:
        results['qft'] = str(e)

    # Test qpe
    try:
        from .qpe import quantum_phase_estimation
        from ..quantum.operator import pauli_z
        from ..quantum.state import zero
        result = quantum_phase_estimation(pauli_z(), n_qubits=3, state=zero(), shots=100)
        results['qpe'] = 'phase' in result
    except Exception as e:
        results['qpe'] = str(e)

    # Test shor
    try:
        from .shor import shor_factor
        p, q = shor_factor(15, use_quantum=False, max_attempts=5)
        results['shor'] = p * q == 15
    except Exception as e:
        results['shor'] = str(e)

    return results