cuda-quantum icon indicating copy to clipboard operation
cuda-quantum copied to clipboard

Improve custom unitary operations

Open annagrin opened this issue 6 months ago • 0 comments

Required prerequisites

  • [X] Search the issue tracker to check if your feature has already been mentioned or rejected in other issues.

Describe the feature

Improvement suggestions for custom unitary operations:

  • Allow unitary operations to be passed a qvector as a parameter
  • Support kernel mode.
  • Support lookup of custom unitary ops with parameterized strings (see #2137 for details)

Example of code where those features would be beneficial:

import cudaq
import numpy as np

@cudaq.kernel
def kernel_helper(state: list[complex]):
    qubits = cudaq.qvector(state)

def flip_qubit(matrix, i):
    j = i - 1
    idx = 1 << i
    if (j < 0):
        jdx = 0
    else:
        jdx = 1 << j
    matrix[jdx][jdx] = 0
    matrix[idx][idx] = 0
    matrix[idx][jdx] = 1
    matrix[jdx][idx] = 1
    return matrix

def test_unitary():
    def register_custom_operation(unitary_index: int, matrix: np.ndarray):
        cudaq.register_operation(f"U_{unitary_index}", matrix)

    state = np.zeros(8)
    state[0] = 1
    state = np.array(state, dtype=cudaq.complex())
    states = [state]
    for i in range(0,3):
        matrix = flip_qubit(np.identity(8), i)
        register_custom_operation(i, matrix)

        kernel, s = cudaq.make_kernel(cudaq.State)
        qubits = kernel.qalloc(s)
        kernel.__getattr__(f'U_{i}')(qubits[0], qubits[1], qubits[2])

        cudaq_state = cudaq.State.from_data(state)
        state = np.array(cudaq.get_state(kernel, cudaq_state))
        states.append(state)

    for s in states:
        counts = cudaq.sample(kernel_helper, s)
        print(counts)

test_unitary()

# Output:

# { 000:1000 }
# { 001:1000 }
# { 010:1000 }
# { 100:1000 }

annagrin avatar Aug 23 '24 23:08 annagrin