Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Python] The lazy evaluation of lambda expressions causes the definition of ElementaryOperator to change unexpectedly #2426

Open
ikkoham opened this issue Nov 27, 2024 · 0 comments
Labels
python-lang Anything related to the Python CUDA Quantum language implementation

Comments

@ikkoham
Copy link
Contributor

ikkoham commented Nov 27, 2024

import cudaq
from cudaq import ElementaryOperator
import numpy as np

cudaq.set_target("dynamics")

n = 2
c_op = np.zeros((n, n), dtype=np.complex128)

ElementaryOperator.define(
    "c_op",
    expected_dimensions=[n],
    create= lambda: c_op,
)

c_op = np.array([[0, 1], [0, 0]] , dtype=np.complex128)

result = cudaq.evolve(
    hamiltonian=cudaq.operators.zero(0),
    dimensions={0: n},
    schedule=cudaq.Schedule([0, 1], "time"),
    initial_state=cudaq.State.from_data(np.identity(n, dtype=np.complex128) / n),
    collapse_operators=[ElementaryOperator("c_op", [0])]
)
print(np.array(result.final_state()))

As shown in this example, users can change the definition of an operator after it has been defined. While this behavior is correct according to Python's language specifications, it might lead to unexpected results for users.
In particular, if users use a for loop to call define, users need to be careful because the for loop may inadvertently change the operator definitions. For example,

for c_op in collapse_ops:
    cudaq.ElementaryOperator.define(
        f"c_op_{c_op}",
        expected_dimensions=[n],
        create= lambda: c_op,
    )
@schweitzpgi schweitzpgi added the python-lang Anything related to the Python CUDA Quantum language implementation label Nov 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
python-lang Anything related to the Python CUDA Quantum language implementation
Projects
None yet
Development

No branches or pull requests

2 participants