ProjectQ-Framework / ProjectQ

ProjectQ: An open source software framework for quantum computing
https://projectq.ch
Apache License 2.0
893 stars 276 forks source link

Context Manager: with flushing(MainEngine()) as eng: #449

Closed cclauss closed 2 years ago

cclauss commented 2 years ago

Simplify the creation, use, and flushing of any Engine using a Python context manager.

When exiting the with block, the engine is automatically flushed.

Just like auto-closing of files:

with open("my_file.txt") as in_file:
    print(in_file.read())

Modeled after https://docs.python.org/3/library/contextlib.html#contextlib.closing


from projectq import MainEngine, flushing  # import the main compiler engine
from projectq.ops import (
    H,
    Measure,
)  # import the operations we want to perform (Hadamard and measurement)

with flushing(MainEngine()) as eng:  # create a default compiler (the back-end is a simulator)
    qubit = eng.allocate_qubit()  # allocate a quantum register with 1 qubit

    H | qubit  # apply a Hadamard gate
    Measure | qubit  # measure the qubit

    # This line is no longer required... eng.flush()

print(f"Measured {int(qubit)}")  # converting a qubit to int or bool gives access to the measurement result
coveralls commented 2 years ago

Pull Request Test Coverage Report for Build 3310727324


Totals Coverage Status
Change from base Build 3279663869: 0.0%
Covered Lines: 7301
Relevant Lines: 7301

💛 - Coveralls
Takishima commented 2 years ago

Also, if you have not done so already, please send an email to info@projectq.ch to request the ProjectQ license agreement that you'll have to sign before we can merge this PR.

cclauss commented 2 years ago

% pytest

...
projectq/cengines/_withflushing_test.py ..                               [ 58%]
...
Takishima commented 2 years ago

Looks good to me. Now before I can merge this, I do need to have you sign the ProjectQ CLA.

EDIT: I just saw your email in the ProjectQ mailbox and the person responsible for it will contact you shortly.

Takishima commented 2 years ago

Thanks for the contribution!