From a1c7386ecec90a531c2009557406c80036aaa0f5 Mon Sep 17 00:00:00 2001 From: Kin Ian Lo Date: Tue, 24 Sep 2024 00:13:23 +0100 Subject: [PATCH] ensure circuit ansatze are dagger functors --- lambeq/ansatz/circuit.py | 5 ++++- tests/test_circuit.py | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/lambeq/ansatz/circuit.py b/lambeq/ansatz/circuit.py index bd1f9eb5..a0ed9d70 100644 --- a/lambeq/ansatz/circuit.py +++ b/lambeq/ansatz/circuit.py @@ -38,7 +38,7 @@ from sympy import Symbol, symbols from lambeq.ansatz import BaseAnsatz -from lambeq.backend.grammar import Box, Diagram, Functor, Ty +from lambeq.backend.grammar import Box, Diagram, Functor, Ty, Daggered from lambeq.backend.quantum import ( Bra, CRz, @@ -125,6 +125,9 @@ def _ob(self, _: Functor, ty: Ty) -> Ty: return self.ob_map[ty] def _ar(self, _: Functor, box: Box) -> Circuit: + if isinstance(box, Daggered): + return self._ar(_, box.dagger()).dagger() + label = self._summarise_box(box) dom, cod = self.ob_size(box.dom), self.ob_size(box.cod) diff --git a/tests/test_circuit.py b/tests/test_circuit.py index 29aa80d2..2f2bd54e 100644 --- a/tests/test_circuit.py +++ b/tests/test_circuit.py @@ -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