| name | discopy-nlp |
| description | DisCoPy categorical quantum NLP for string diagrams, monoidal categories, and compositional semantics in Python. Use when implementing compositional distributional semantics, building string diagram computations, working with monoidal category theory in code, creating quantum-inspired NLP models, or applying categorical semantics to natural language processing. |
DisCoPy Categorical Quantum NLP
DisCoPy provides Python implementations of string diagrams and monoidal categories for compositional NLP.
Installation
pip install discopy
Core Categorical Structures
Types and Morphisms
from discopy import Ty, Box, Id, Diagram
n = Ty('n')
s = Ty('s')
john = Box('John', Ty(), n)
sleeps = Box('sleeps', n, s)
Composition and Tensor
john_sleeps = john >> sleeps
mary = Box('Mary', Ty(), n)
john_and_mary = john @ mary
String Diagrams
diagram = john >> sleeps
diagram.draw()
diagram.draw(path="diagram.png")
Pregroup Grammar
from discopy.grammar.pregroup import Ty, Word, Cup, Id
n = Ty('n')
s = Ty('s')
n_r = n.r
n_l = n.l
john = Word('John', n)
sleeps = Word('sleeps', n.r @ s)
loves = Word('loves', n.r @ s @ n.l)
sentence = john @ sleeps >> Cup(n, n.r) @ Id(s)
Functorial Semantics
import numpy as np
from discopy.tensor import Tensor, Dim
d = Dim(2)
john_vec = Tensor(dom=Dim(1), cod=d, array=np.array([1, 0]))
sleeps_mat = Tensor(dom=d, cod=Dim(1), array=np.array([0.8, 0.2]))
result = john_vec >> sleeps_mat
Quantum Circuit Semantics
from discopy.quantum import Circuit, Ket, Bra, H, CX
john_circuit = Ket(0)
mary_circuit = Ket(1)
entangle = CX >> (H @ Circuit.id(1))
Categorical Guarantees
DisCoPy ensures:
- Monoidal Laws: Associativity and unit laws for ⊗
- Functoriality: Semantic maps preserve composition
- String Diagram Correctness: Diagrams represent valid morphisms
- Type Safety: Composition only when types match