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

Spider tn #157

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# lambeq

[![lambeq logo](https://cqcl.github.io/lambeq-docs/_static/lambeq_logo.png)](//cqcl.github.io/lambeq-docs)
# λambeq

![Build status](https://github.com/CQCL/lambeq/actions/workflows/build_test.yml/badge.svg)
[![License](https://img.shields.io/github/license/CQCL/lambeq)](LICENSE)
Expand Down
3 changes: 2 additions & 1 deletion lambeq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
'bag_of_words_reader',
'cups_reader',
'spiders_reader',
'spider_chain_reader',
'stairs_reader',
'word_sequence_reader',

Expand Down Expand Up @@ -124,7 +125,7 @@
WebParseError, WebParser,
Reader, LinearReader, TreeReader, TreeReaderMode,
bag_of_words_reader, cups_reader, spiders_reader,
stairs_reader, word_sequence_reader)
spider_chain_reader, stairs_reader, word_sequence_reader)
from lambeq.tokeniser import Tokeniser, SpacyTokeniser
from lambeq.training import (Checkpoint, Dataset, Optimizer,
NelderMeadOptimizer, RotosolveOptimizer,
Expand Down
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
38 changes: 32 additions & 6 deletions lambeq/backend/tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,21 +385,47 @@ def to_tn(self, dtype: type | None = None):
del scan[len(l): len(l) + 2]
else:
if isinstance(box, Spider):
node = tn.CopyNode(box.n_legs_in + box.n_legs_out,
box.type.product, dtype=dtype,
backend=backend)
rank = box.n_legs_in + box.n_legs_out
dim = box.type.product
if rank <= 3:
node = tn.CopyNode(rank, dim, dtype=dtype,
backend=backend)
nodes.append(node)
legs = node.edges
else:
# Decompose the spider into a chain of
# three-legged spiders of length rank - 2
# For example, a 5-legged spider will be
# decomposed into:
# 2 2 2
# | | |
# ---1-[N0]-0----1-[N1]-0----1-[N2]-0---
# where the numbers indicate the leg indices of
# the spiders.
spiders = [tn.CopyNode(3, dim, dtype=dtype,
backend=backend)
for _ in range(rank-2)]
nodes.extend(spiders)

for i in range(len(spiders)-1):
tn.connect(spiders[i][0], spiders[i+1][1])

legs = ([spiders[0][1]]
+ [n[2] for n in spiders]
+ [spiders[-1][0]])
else:
node = tn.Node(box.array,
str(box.name),
backend=backend)

nodes.append(node)
nodes.append(node)
legs = node.edges

for i in range(len(box.dom)):
tn.connect(scan[len(l) + i], node[i])
tn.connect(scan[len(l) + i], legs[i])

scan = (scan[:len(l)]
+ node[len(box.dom):]
+ legs[len(box.dom):]
+ scan[len(l) + len(box.dom):])

# nodes, input_edge_order, output_edge_order
Expand Down
4 changes: 3 additions & 1 deletion lambeq/text2diagram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
'bag_of_words_reader',
'cups_reader',
'spiders_reader',
'spider_chain_reader',
'stairs_reader',
'word_sequence_reader']

Expand All @@ -53,5 +54,6 @@
stairs_reader,
word_sequence_reader)
from lambeq.text2diagram.spiders_reader import (bag_of_words_reader,
spiders_reader)
spiders_reader,
spider_chain_reader)
from lambeq.text2diagram.tree_reader import TreeReader, TreeReaderMode
5 changes: 4 additions & 1 deletion lambeq/text2diagram/spiders_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.

__all__ = ['SpidersReader', 'bag_of_words_reader', 'spiders_reader']
__all__ = ['SpidersReader', 'bag_of_words_reader',
'spiders_reader', 'spider_chain_reader']

from lambeq.backend.grammar import Diagram, Id, Spider, Word
from lambeq.core.types import AtomicType
from lambeq.core.utils import SentenceType, tokenised_sentence_type_check
from lambeq.text2diagram.base import Reader
from lambeq.text2diagram.linear_reader import LinearReader

S = AtomicType.SENTENCE

Expand Down Expand Up @@ -46,3 +48,4 @@ def sentence2diagram(self,

spiders_reader = SpidersReader()
bag_of_words_reader = spiders_reader
spider_chain_reader = LinearReader(Spider(AtomicType.SENTENCE, 2, 1))
Copy link
Contributor Author

@kinianlo kinianlo Oct 11, 2024

Choose a reason for hiding this comment

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

LinearReader requires a Diagram type but Spider is a Box. Should LinearReader be modified to also accept Box or we should convert the Spider into a diagram, e.g. using .to_diagram()?

Copy link
Contributor

Choose a reason for hiding this comment

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

Just use .to_diagram() for now. Please also note that your branch requires some cleaning.

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
22 changes: 22 additions & 0 deletions tests/backend/test_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import lambeq.backend.grammar as grammar
from lambeq.backend.tensor import *

@pytest.fixture
def spider():
return Spider(Dim(3), 5, 3)

def test_Ty():
assert Dim(1,1,1,1,1) == Dim(1) == Dim()
Expand Down Expand Up @@ -85,3 +88,22 @@ def test_lambdify():

assert bx1.lambdify(a,b,c,d)(1,2,3,4) == bx1_concrete
assert (bx1 >> bx2).lambdify(a,b,c,d)(1,2,3,4) == bx1_concrete >> bx2_concrete

def test_to_tn_spider_unfuse(spider):
nodes, edges = spider.to_tn()

assert len(edges) == spider.n_legs_in + spider.n_legs_out
assert all(node.rank <= 3 for node in nodes)

def test_spider_eval(spider):
n_legs = 8
dim = 3

expected = np.zeros(tuple(dim for _ in range(n_legs)))
for i in range(dim):
expected[tuple(i for _ in range(n_legs))] = 1

result = spider.eval()

assert result.shape == tuple(dim for _ in range(n_legs))
assert np.allclose(result, expected)
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
Loading