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

fix: Emit nested binary expressions for classical ops #224

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ name = "pytket-phir"
description = "A circuit analyzer and translator from pytket to PHIR"
readme = "README.md"
requires-python = ">=3.10, <3.13"
license = {file = "LICENSE"}
authors = [{name = "Quantinuum"}]
license = { file = "LICENSE" }
authors = [{ name = "Quantinuum" }]
maintainers = [
{ name = "Kartik Singhal", email = "Kartik.Singhal@quantinuum.com" },
]

classifiers = [
"Environment :: Console",
Expand Down Expand Up @@ -50,9 +53,7 @@ where = ["."]

[tool.pytest.ini_options]
addopts = "-s -vv"
pythonpath = [
"."
]
pythonpath = ["."]
log_cli = true
log_cli_level = "INFO"
log_level = "DEBUG"
Expand Down
33 changes: 24 additions & 9 deletions pytket/phir/phirgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import json
import logging
import sys
from collections import deque
from copy import deepcopy
from importlib.metadata import version
from typing import TYPE_CHECKING, Any, TypeAlias
Expand Down Expand Up @@ -356,15 +357,29 @@ def convert_classicalevalop(op: tk.ClassicalEvalOp, cmd: tk.Command) -> JsonDict

def multi_bit_condition(args: "list[UnitID]", value: int) -> JsonDict:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a feeling this will error out if len(args) is 0 or 1. While these may be rare edge cases it would be good to handle them or at least raise an informative exception.

Copy link

@PabloAndresCQ PabloAndresCQ Sep 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would make sense, but PECOS does not seem to be able to deal with "cop": "&" with fewer than two arguments.

ValueError: not enough values to unpack (expected 2, got 1)

Is there a way to add a "True" constant to an expression in PHIR? The AND with a single element args == [x] could be implemented as (x == val) & (x == val), but in the case of args == [] you'd need to be able to output True somehow.

Not sure if we'd want to do this, though. Is it OK for pytket-phir to create valid PHIR when the conditions the user inputted would not be accepted by PECOS if done directly? It's true that in this case, the action of AND on 1 and 0 arguments is not ambiguous, but it still makes me uneasy. I'd just throw an exception with informative message.

Copy link
Member Author

@qartik qartik Sep 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function is only called at one place when len(args) is not 1, but for generality (and reusability), it's certainly worth doing an edge case check. Implemented and pushed.

"""Construct bitwise condition."""
return {
"cop": "&",
"args": [
{"cop": "==", "args": [arg_to_bit(arg), bval]}
for (arg, bval) in zip(
args[::-1], map(int, f"{value:0{len(args)}b}"), strict=True
)
],
}
min_args = 2
if len(args) < min_args:
msg = f"multi_bit_condition requires at least {min_args} arguments"
raise TypeError(msg)

def nested_cop(cop: str, args: "deque[UnitID]", val_bits: deque[int]) -> JsonDict:
if len(args) == min_args:
return {
"cop": cop,
"args": [
{"cop": "==", "args": [arg_to_bit(args.popleft()), val_bits.pop()]},
{"cop": "==", "args": [arg_to_bit(args.popleft()), val_bits.pop()]},
],
}
return {
"cop": cop,
"args": [
{"cop": "==", "args": [arg_to_bit(args.popleft()), val_bits.pop()]},
nested_cop(cop, args, val_bits),
],
}

return nested_cop("&", deque(args), deque(map(int, f"{value:0{len(args)}b}")))


def convert_subcmd(op: tk.Op, cmd: tk.Command) -> JsonDict | None: # noqa: PLR0912
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ networkx<3
phir==0.3.3
pre-commit==3.8.0
pydata_sphinx_theme==0.15.4
pytest==8.3.2
pytest==8.3.3
pytket==1.32.0
ruff==0.6.4
setuptools_scm==8.1.0
Expand Down
27 changes: 25 additions & 2 deletions tests/test_phirgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ def test_pytket_classical_only() -> None:
"condition": {
"cop": "&",
"args": [
{"cop": "==", "args": [["b", 2], 1]},
{"cop": "==", "args": [["b", 1], 0]},
{"cop": "==", "args": [["b", 2], 1]},
],
},
"true_branch": [
Expand Down Expand Up @@ -177,8 +177,8 @@ def test_conditional_barrier() -> None:
"condition": {
"cop": "&",
"args": [
{"cop": "==", "args": [["m", 1], 0]},
{"cop": "==", "args": [["m", 0], 0]},
{"cop": "==", "args": [["m", 1], 0]},
],
},
"true_branch": [{"meta": "barrier", "args": [["q", 0], ["q", 1]]}],
Expand Down Expand Up @@ -463,3 +463,26 @@ def test_nullary_ops() -> None:
"cop": "==",
"args": [["tk_SCRATCH_BIT", 1], 1], # evals to False
}


def test_condition_multiple_bits() -> None:
"""From https://github.com/CQCL/pytket-phir/issues/215 ."""
n_bits = 3
c = Circuit(1, n_bits)
c.Rz(0.5, 0, condition_bits=list(range(n_bits)), condition_value=6)
phir = json.loads(pytket_to_phir(c))

assert phir["ops"][2] == {"//": "IF ([c[0], c[1], c[2]] == 6) THEN Rz(0.5) q[0];"}
assert phir["ops"][3]["condition"] == {
"cop": "&",
"args": [
{"cop": "==", "args": [["c", 0], 0]},
{
"cop": "&",
"args": [
{"cop": "==", "args": [["c", 1], 1]},
{"cop": "==", "args": [["c", 2], 1]},
Comment on lines +475 to +484
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note endianness of pytket: #162 (comment)

Need to be careful of endianness here. The conditional value in pytket is little-endian, e.g. a value of 2 on the bits [a[0], a[1]] means a[0] == 0 && a[1] == 1.

],
},
],
}