Skip to content

Commit

Permalink
Merge pull request #157 from CQCL/156-conditional-wasm-operations-inc…
Browse files Browse the repository at this point in the history
…lude-condition-bit-in-their-arguments
  • Loading branch information
qartik committed Apr 2, 2024
2 parents 1384648 + ab17133 commit 58d8cd2
Show file tree
Hide file tree
Showing 7 changed files with 198 additions and 132 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ repos:
- id: debug-statements

- repo: https://github.com/crate-ci/typos
rev: v1.19.0
rev: v1.20.1
hooks:
- id: typos

Expand All @@ -25,7 +25,7 @@ repos:
- black==23.10.1

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.4
rev: v0.3.5
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,6 @@ version_scheme = "python-simplified-semver"

[tool.refurb]
python_version = "3.10"

[tool.typos]
default.extend-words = { lst = "lst" }
23 changes: 16 additions & 7 deletions pytket/phir/phirgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,11 +230,11 @@ def convert_subcmd(op: tk.Op, cmd: tk.Command) -> JsonDict | None:
# See https://github.com/CQCL/tket/blob/0ec603986821d994caa3a0fb9c4640e5bc6c0a24/pytket/pytket/qasm/qasm.py#L419-L459
match op.data[0:5]:
case "sleep":
dur = op.data.removeprefix("sleep(").removesuffix(")")
duration = op.data.removeprefix("sleep(").removesuffix(")")
out = {
"mop": "Idle",
"args": [arg_to_bit(qbit) for qbit in cmd.qubits],
"duration": (float(dur), "s"),
"duration": (float(duration), "s"),
}
case "order" | "group":
raise NotImplementedError(op.data)
Expand Down Expand Up @@ -357,11 +357,13 @@ def extract_wasm_args_and_returns(
) -> tuple[list[str], list[str]]:
"""Extract the wasm args and return values as whole register names."""
# This slice removes the extra `_w` cregs (wires) that are not part of the
# circuit, and the output args which are appended after the input args
# circuit and the output args, which are appended after the input args
slice_index = op.num_w + sum(op.output_widths)
only_args = command.args[:-slice_index]
# Eliminate conditional bits from the front of the args
input_args = only_args[len(only_args) - op.n_inputs :]
return (
dedupe_bits_to_registers(only_args),
dedupe_bits_to_registers(input_args),
dedupe_bits_to_registers(command.bits),
)

Expand All @@ -375,9 +377,18 @@ def make_comment_text(cmd: tk.Command, op: tk.Op) -> str:
"""Converts a command + op to the PHIR comment spec."""
comment = str(cmd)
match op:
case tk.Conditional():
conditional_text = str(cmd)
cleaned = (
conditional_text[: conditional_text.find("THEN") + 5]
if isinstance(op.op, tk.WASMOp)
else ""
)
comment = f"{cleaned}{make_comment_text(cmd, op.op)}"

case tk.WASMOp():
args, returns = extract_wasm_args_and_returns(cmd, op)
comment = f"WASM function={op.func_name} args={args} returns={returns}"
comment = f"WASM_function='{op.func_name}' args={args} returns={returns};"

case tk.BarrierOp():
comment = op.data + " " + str(cmd.args[0]) + ";" if op.data else str(cmd)
Expand All @@ -395,8 +406,6 @@ def make_comment_text(cmd: tk.Command, op: tk.Op) -> str:

def get_decls(qbits: set["Qubit"], cbits: set[tkBit]) -> list[dict[str, str | int]]:
"""Format the qvar and cvar define PHIR elements."""
# TODO(kartik): this may not always be accurate
# https://github.com/CQCL/pytket-phir/issues/24
qvar_dim: dict[str, int] = {}
for qbit in qbits:
qvar_dim.setdefault(qbit.reg_name, 0)
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pydata_sphinx_theme==0.15.2
pytest==8.1.1
pytest-order==1.2.0
pytket==1.26.0
ruff==0.3.4
ruff==0.3.5
setuptools_scm==8.0.4
sphinx==7.2.6
wasmtime==19.0.0
Expand Down
24 changes: 12 additions & 12 deletions tests/test_parallelization.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,18 @@ def test_parallel_subcommand_relative_ordering() -> None:
phir = get_phir_json(QasmFile.rxrz, rebase=True)
# make sure it is ordered like the qasm file
ops = phir["ops"]
frst_sc = ops[3]
scnd_sc = ops[5]
thrd_sc = ops[7]
frth_sc = ops[9]
assert frst_sc["qop"] == "RZ"
assert frst_sc["angles"] == [[0.5], "pi"]
assert scnd_sc["qop"] == "R1XY"
assert scnd_sc["angles"] == [[3.5, 0.0], "pi"]
assert thrd_sc["qop"] == "R1XY"
assert thrd_sc["angles"] == [[0.5, 0.0], "pi"]
assert frth_sc["qop"] == "RZ"
assert frth_sc["angles"] == [[3.5], "pi"]
sc1 = ops[3]
sc2 = ops[5]
sc3 = ops[7]
sc4 = ops[9]
assert sc1["qop"] == "RZ"
assert sc1["angles"] == [[0.5], "pi"]
assert sc2["qop"] == "R1XY"
assert sc2["angles"] == [[3.5, 0.0], "pi"]
assert sc3["qop"] == "R1XY"
assert sc3["angles"] == [[0.5, 0.0], "pi"]
assert sc4["qop"] == "RZ"
assert sc4["angles"] == [[3.5], "pi"]


def test_single_qubit_circuit_with_parallel() -> None:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_phirgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,18 @@ def test_conditional_barrier() -> None:
}


def test_simple_cond_classical() -> None:
"""Ensure conditional classical operation are correctly generated."""
circ = get_qasm_as_circuit(QasmFile.simple_cond)
phir = json.loads(pytket_to_phir(circ))
assert phir["ops"][-6] == {"//": "IF ([c[0]] == 1) THEN SetBits(1) z[0];"}
assert phir["ops"][-5] == {
"block": "if",
"condition": {"cop": "==", "args": [["c", 0], 1]},
"true_branch": [{"cop": "=", "returns": [["z", 0]], "args": [1]}],
}


def test_nested_bitwise_op() -> None:
"""From https://github.com/CQCL/pytket-phir/issues/133 ."""
circ = Circuit(4)
Expand Down Expand Up @@ -183,6 +195,7 @@ def test_conditional_measure() -> None:
c.Measure(0, 0)
c.Measure(1, 1, condition_bits=[0], condition_value=1)
phir = json.loads(pytket_to_phir(c))
assert phir["ops"][-2] == {"//": "IF ([c[0]] == 1) THEN Measure q[1] --> c[1];"}
assert phir["ops"][-1] == {
"block": "if",
"condition": {"cop": "==", "args": [["c", 0], 1]},
Expand Down
Loading

0 comments on commit 58d8cd2

Please sign in to comment.