Skip to content

Commit

Permalink
Add get_qir_str() method to qsharp.compile() result (#887)
Browse files Browse the repository at this point in the history
This is to support the scenario where the user wants to generate an
input file to be submitted with the `az quantum` cli.
  • Loading branch information
minestarks authored Dec 7, 2023
1 parent 2b224bb commit 616dd71
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pip/qsharp/_qsharp.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,22 @@ def compile(entry_expr):
:param entry_expr: The Q# expression that will be used as the entrypoint
for the program.
:returns QirInputData: The compiled program.
To get the QIR string from the compiled program, use `str()`.
Example:
.. code-block:: python
program = qsharp.compile("...")
with open('myfile.ll', 'w') as file:
file.write(str(program))
"""
ll_str = get_interpreter().qir(entry_expr)
return QirInputData("main", ll_str)


def estimate(entry_expr, params: Union[dict, List, EstimatorParams] = None) -> EstimatorResult:
"""
Estimates resources for Q# source code.
Expand All @@ -112,6 +124,7 @@ def estimate(entry_expr, params: Union[dict, List, EstimatorParams] = None) -> E
json.loads(get_interpreter().estimate(entry_expr, json.dumps(params)))
)


def dump_machine() -> StateDump:
"""
Returns the sparse state vector of the simulator as a StateDump object.
Expand Down Expand Up @@ -140,3 +153,6 @@ def __init__(self, name: str, ll_str: str):
# by the protocol and must remain unchanged.
def _repr_qir_(self, **kwargs) -> bytes:
return self._ll_str.encode("utf-8")

def __str__(self) -> str:
return self._ll_str
9 changes: 9 additions & 0 deletions pip/tests/test_qsharp.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def test_stdout_multiple_lines() -> None:

assert f.getvalue() == "STATE:\n|0⟩: 1.0000+0.0000𝑖\nHello!\n"


def test_dump_machine() -> None:
qsharp.init(target_profile=qsharp.TargetProfile.Full)
qsharp.eval(
Expand All @@ -58,3 +59,11 @@ def test_compile_qir_input_data() -> None:
operation = qsharp.compile("Program()")
qir = operation._repr_qir_()
assert isinstance(qir, bytes)


def test_compile_qir_str() -> None:
qsharp.init(target_profile=qsharp.TargetProfile.Base)
qsharp.eval("operation Program() : Result { use q = Qubit(); return M(q) }")
operation = qsharp.compile("Program()")
qir = str(operation)
assert "define void @ENTRYPOINT__main()" in qir

0 comments on commit 616dd71

Please sign in to comment.