Skip to content

Commit

Permalink
Circuit ansatze should be dagger functors (#155)
Browse files Browse the repository at this point in the history
  • Loading branch information
kinianlo authored Sep 30, 2024
1 parent 8b80d2c commit 88d93f8
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lambeq/backend/grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,9 @@ def rotate(self, z: int) -> Diagrammable:
"""

def dagger(self) -> Diagrammable:
"""Implements conjugation of diagrams."""

def __matmul__(self, rhs: Diagrammable | Ty) -> Diagrammable:
"""Implements the tensor operator `@` with another diagram."""

Expand Down Expand Up @@ -1572,6 +1575,9 @@ def rotate(self, z: int) -> Self:
def dagger(self) -> Box:
return self.box

def apply_functor(self, functor: Functor) -> Diagrammable:
return functor(self.dagger()).dagger()

@classmethod
def from_json(cls, data: _JSONDictT | str) -> Self:
data_dict = json.loads(data) if isinstance(data, str) else data
Expand Down
1 change: 1 addition & 0 deletions tests/backend/test_grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ def ar(func, box):
assert func(g.r) == func(g).r == g_z.r
assert func(f >> g) == f_z >> g_z
assert func(f @ g) == f_z @ g_z
assert func(f.dagger()) == func(f).dagger()

def bad_ar(func, box):
return Box("BOX", a, c) if box.cod == b else box
Expand Down
17 changes: 17 additions & 0 deletions tests/test_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,3 +320,20 @@ def test_lambeq_tket_conversion():
def test_special_characters(box, expected_sym_count):
ansatz = Sim15Ansatz({n_ty: 2, comma_ty: 2, space_ty: 2}, n_layers=1)
assert(len(ansatz(box).free_symbols) == expected_sym_count)


def test_ansatz_is_dagger_functor():
ansatz = IQPAnsatz({N: 1, S: 1}, n_layers=1)
diagram = Word('John', N)
circuit1 = ansatz(diagram).dagger()
circuit2 = ansatz(diagram.dagger())
assert circuit1 == circuit2

def test_ansatz_is_dagger_functor_sentence():
ansatz = IQPAnsatz({N: 1, S: 1}, n_layers=1)
diagram = (Word('Alice', N) @ Word('runs', N >> S) >>
Cup(N, N.r) @ S)

circuit1 = ansatz(diagram).dagger().normal_form()
circuit2 = ansatz(diagram.dagger()).normal_form()
assert circuit1 == circuit2

0 comments on commit 88d93f8

Please sign in to comment.