lambeq.backend

lambeq.backend.grammar

Grammar category

Lambeq’s internal representation of the grammar category. This work is based on DisCoPy (https://discopy.org/) which is released under the BSD 3-Clause “New” or “Revised” License.

class lambeq.backend.grammar.Box(name: str, dom: Ty, cod: Ty, z: int = 0)[source]

Bases: Entity

A box in the grammar category.

Parameters:
namestr

The name of the box.

domTy

The domain of the box.

codTy

The codomain of the box.

zint, optional

The winding number of the box, by default 0.

__init__(name: str, dom: Ty, cod: Ty, z: int = 0) None
apply_functor(functor: Functor) Diagrammable[source]
category: ClassVar[Category] = Category(name='grammar', Ty=<class 'lambeq.backend.grammar.Ty'>, Box=<class 'lambeq.backend.grammar.Box'>, Layer=<class 'lambeq.backend.grammar.Layer'>, Diagram=<class 'lambeq.backend.grammar.Diagram'>)
cod: Ty
dagger() Daggered | Box[source]
dom: Ty
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property l: Self
name: str
property r: Self
rotate(z: int) Self[source]

Rotate the box, changing the winding number.

to_diagram() Diagram[source]
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self[source]
z: int = 0
class lambeq.backend.grammar.Cap(left: Ty, right: Ty, is_reversed: bool = False)[source]

Bases: Box

The unit of the adjunction for an atomic type.

Parameters:
leftTy

The type of the left output.

rightTy

The type of the right output.

is_reversedbool, default: False

Whether the cap is reversed or not. Normally, caps only allow outputs where right is the left adjoint of left. However, to facilitate operations like dagger, we pass in a flag that indicates that the inputs are the opposite way round, which initialises a reversed cap. Then, when a cap is adjointed, it turns into a reversed cap, which can be adjointed again to turn it back into a normal cap.

__init__(left: Ty, right: Ty, is_reversed: InitVar[bool] = False) None
apply_functor(functor: Functor) Diagrammable[source]
category: ClassVar[Category] = Category(name='grammar', Ty=<class 'lambeq.backend.grammar.Ty'>, Box=<class 'lambeq.backend.grammar.Box'>, Layer=<class 'lambeq.backend.grammar.Layer'>, Diagram=<class 'lambeq.backend.grammar.Diagram'>)
cod: Ty
dagger() Cup[source]
dom: Ty
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

is_reversed: InitVar[bool] = False
property l: Self
left: Ty
name: str
property r: Self
right: Ty
rotate(z: int) Self[source]

Rotate the cap.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

classmethod to_left(right: Ty, is_reversed: bool = False) Self | Diagram[source]
classmethod to_right(left: Ty, is_reversed: bool = False) Self | Diagram[source]
unwind() Self
z: int = 0
class lambeq.backend.grammar.Category(name: str)[source]

Bases: object

The base class for all categories.

Box: type[lambeq.backend.grammar.Box]
Diagram: type[lambeq.backend.grammar.Diagram]
Layer: type[lambeq.backend.grammar.Layer]
Ty: type[lambeq.backend.grammar.Ty]
__call__(name_or_entity: str) Callable[[_EntityType], _EntityType][source]
__call__(name_or_entity: _EntityType) _EntityType

Call self as a function.

__init__(name: str) None
from_json(data: _JSONDictT | str) Entity[source]

Decode a JSON object or string into an entity from this category.

Returns:
Entity

The entity generated from the JSON data. This could be a Ty, a Box subclass, or a Diagram instance.

name: str
set(name: str, entity: _EntityType) _EntityType[source]
class lambeq.backend.grammar.Cup(left: Ty, right: Ty, is_reversed: bool = False)[source]

Bases: Box

The counit of the adjunction for an atomic type.

Parameters:
leftTy

The type of the left output.

rightTy

The type of the right output.

is_reversedbool, default: False

Whether the cup is reversed or not. Normally, cups only allow inputs where right is the right adjoint of left. However, to facilitate operations like dagger, we pass in a flag that indicates that the inputs are the opposite way round, which initialises a reversed cup. Then, when a cup is adjointed, it turns into a reversed cup, which can be adjointed again to turn it back into a normal cup.

__init__(left: Ty, right: Ty, is_reversed: InitVar[bool] = False) None
apply_functor(functor: Functor) Diagrammable[source]
category: ClassVar[Category] = Category(name='grammar', Ty=<class 'lambeq.backend.grammar.Ty'>, Box=<class 'lambeq.backend.grammar.Box'>, Layer=<class 'lambeq.backend.grammar.Layer'>, Diagram=<class 'lambeq.backend.grammar.Diagram'>)
cod: Ty
dagger() Cap[source]
dom: Ty
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

is_reversed: InitVar[bool] = False
property l: Self
left: Ty
name: str
property r: Self
right: Ty
rotate(z: int) Self[source]

Rotate the cup.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

classmethod to_left(right: Ty, is_reversed: bool = False) Self | Diagram[source]
classmethod to_right(left: Ty, is_reversed: bool = False) Self | Diagram[source]
unwind() Self
z: int = 0
class lambeq.backend.grammar.Daggered(box: Box)[source]

Bases: Box

A daggered box.

Parameters:
boxBox

The box to be daggered.

__init__(box: Box) None
apply_functor(functor: Functor) Diagrammable
box: Box
category: ClassVar[Category] = Category(name='grammar', Ty=<class 'lambeq.backend.grammar.Ty'>, Box=<class 'lambeq.backend.grammar.Box'>, Layer=<class 'lambeq.backend.grammar.Layer'>, Diagram=<class 'lambeq.backend.grammar.Diagram'>)
cod: Ty
dagger() Box[source]
dom: Ty
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property l: Self
name: str
property r: Self
rotate(z: int) Self[source]

Rotate the daggered box.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.grammar.Diagram(dom: Ty, cod: Ty, layers: list[lambeq.backend.grammar.Layer])[source]

Bases: Entity

A diagram in the grammar category.

Parameters:
domTy

The type of the input wires.

codTy

The type of the output wires.

layerslist[Layer]

The layers of the diagram.

__init__(dom: Ty, cod: Ty, layers: list[lambeq.backend.grammar.Layer]) None
apply_functor(functor: Functor) Diagram[source]
classmethod ba(left, right) Self[source]
classmethod bc(left, middle, right) Self[source]
property boxes: list[lambeq.backend.grammar.Box]
classmethod bx(left, middle, right) Self[source]
classmethod caps(left: Ty, right: Ty, is_reversed=False) Diagrammable[source]
category: ClassVar[Category] = Category(name='grammar', Ty=<class 'lambeq.backend.grammar.Ty'>, Box=<class 'lambeq.backend.grammar.Box'>, Layer=<class 'lambeq.backend.grammar.Layer'>, Diagram=<class 'lambeq.backend.grammar.Diagram'>)
cod: Ty
classmethod create_pregroup_diagram(words: list[lambeq.backend.grammar.Word], morphisms: list[tuple[type, int, int]]) Self[source]

Create a Diagram from cups and swaps.

>>> n, s = Ty('n'), Ty('s')
>>> words = [Word('she', n), Word('goes', n.r @ s @ n.l),
...          Word('home', n)]
>>> morphs = [(Cup, 0, 1), (Cup, 3, 4)]
>>> diagram = Diagram.create_pregroup_diagram(words, morphs)
Parameters:
wordslist of Word

A list of Word s corresponding to the words of the sentence.

morphisms: list of tuple[type, int, int]
A list of tuples of the form:

(morphism, start_wire_idx, end_wire_idx).

Morphisms can be Cup s or Swap s, while the two numbers define the indices of the wires on which the morphism is applied.

Returns:
Diagram

The generated pregroup diagram.

Raises:
ValueError

If the provided morphism list does not type-check properly.

classmethod cups(left: Ty, right: Ty, is_reversed=False) Diagrammable[source]
curry(n: int = 1, left: bool = True) Self[source]
dagger() Self[source]
dom: Ty
draw(draw_as_pregroup=True, **kwargs: Any) None[source]

Draw the diagram.

Parameters:
draw_as_pregroupbool, optional

Whether to try drawing the diagram as a pregroup diagram, default is True.

draw_as_nodesbool, optional

Whether to draw boxes as nodes, default is False.

colorstring, optional

Color of the box or node, default is white (‘#ffffff’) for boxes and red (‘#ff0000’) for nodes.

textpadpair of floats, optional

Padding between text and wires, default is (0.1, 0.1).

draw_type_labelsbool, optional

Whether to draw type labels, default is False.

draw_box_labelsbool, optional

Whether to draw box labels, default is True.

aspectstring, optional

Aspect ratio, one of [‘auto’, ‘equal’].

marginstuple, optional

Margins, default is (0.05, 0.05).

nodesizefloat, optional

BoxNode size for spiders and controlled gates.

fontsizeint, optional

Font size for the boxes, default is 12.

fontsize_typesint, optional

Font size for the types, default is 12.

figsizetuple, optional

Figure size.

pathstr, optional

Where to save the image, if None we call plt.show().

to_tikzbool, optional

Whether to output tikz code instead of matplotlib.

asymmetryfloat, optional

Make a box and its dagger mirror images, default is .25 * any(box.is_dagger for box in diagram.boxes).

classmethod fa(left, right) Self[source]
classmethod fc(left, middle, right) Self[source]
classmethod from_discopy(diagram: discopy.monoidal.Diagram) Diagram[source]

Import discopy diagram to lambeq diagram.

Parameters:
diagramdiscopy.monoidal.Diagram
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Diagram.

Returns:
Diagram

The diagram generated from the JSON data.

classmethod fx(left, middle, right) Self[source]
classmethod id(dom: Ty | None = None) Self[source]
property is_id: bool
property is_pregroup: bool

Check if a diagram is a pregroup diagram.

Adapted from discopy.grammar.pregroup.draw.

Returns:
bool

Whether the diagram is a pregroup diagram.

property l: Self
layers: list[lambeq.backend.grammar.Layer]
classmethod lift(diagrams: Iterable[Diagrammable | Ty]) list[Self][source]

Lift diagrams to the current category.

Given a list of boxes or diagrams, call to_diagram on each, then check all of the diagrams are in the same category as the calling class.

Parameters:
diagramsiterable

The diagrams to lift and check.

Returns:
list of Diagram

The diagrams after calling to_diagram on each.

Raises:
ValueError

If any of the diagrams are not in the same category of the calling class.

normal_form(left: bool = False) Diagram[source]

Returns the normal form of a connected diagram, see arXiv:1804.07832.

Parameters:
leftbool, optional

Whether to apply left interchangers.

Raises:
NotImplementedError

Whenever normalizer yields the same rewrite steps twice.

property offsets: list[int]

The offset of a box is the length of the type on its left.

classmethod permutation(dom: Ty, permutation: Iterable[int]) Self[source]

Create a layer of Swaps that permutes the wires.

permuted(permutation: Iterable[int]) Self[source]
pregroup_normal_form()[source]

Applies normal form to a pregroup diagram of the form word @ ... @ word >> wires by normalising words and wires seperately before combining them, so it can be drawn with draw().

property r: Self
classmethod register_special_box(name: str, diagram_factory: None = None) Callable[[_DiagrammableFactoryT], _DiagrammableFactoryT][source]
classmethod register_special_box(name: str, diagram_factory: Callable[[...], Diagrammable]) None
render_as_str(**kwargs: Any) str[source]

Render the diagram as text.

Presently only implemented for pregroup diagrams.

Parameters:
word_spacingint, default: 2

The number of spaces between the words of the diagrams.

use_at_separatorbool, default: False

Whether to represent types using @ as the monoidal product. Otherwise, use the unicode dot character.

compress_layersbool, default: True

Whether to draw boxes in the same layer when they can occur simultaneously, otherwise, draw one box per layer.

use_ascii: bool, default: False

Whether to draw using ASCII characters only, for compatibility reasons.

Returns:
str

Drawing of diagram in string format.

rotate(z: int) Self[source]

Rotate the diagram.

special_boxes: ClassVar[dict[str, collections.abc.Callable[..., lambeq.backend.grammar.Diagrammable]]] = {'cap': <class 'lambeq.backend.grammar.Cap'>, 'cup': <class 'lambeq.backend.grammar.Cup'>, 'spider': <class 'lambeq.backend.grammar.Spider'>, 'swap': <class 'lambeq.backend.grammar.Swap'>}
classmethod swap(left: Ty, right: Ty) Diagrammable[source]
tensor(*diagrams: Diagrammable | Ty) Self[source]
then(*diagrams: Diagrammable) Self[source]
then_at(diagram: Diagrammable, index: int) Self[source]
to_diagram() Self[source]
to_discopy() discopy.monoidal.Diagram[source]

Export lambeq diagram to discopy diagram.

Returns:
discopy.monoidal.Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this diagram to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

transpose(left: bool = False) Self[source]

Construct the diagrammatic transpose.

The transpose of any diagram in a category with cups and caps can be constructed as follows:

(default)

Left transpose Right transpose

│╭╮ ╭╮│ │█│ │█│ ╰╯│ │╰╯

The input and output types of the transposed diagram are the adjoints of the respective types of the original diagram. This means that for diagrams with composite types, the order of the objects are reversed.

Parameters:
leftbool, default: False

Whether to transpose to the diagram to the left.

Returns:
Diagram

The transposed diagram, constructed as shown above.

class lambeq.backend.grammar.Diagrammable(*args, **kwargs)[source]

Bases: Protocol

An abstract base class describing the behavior of a diagram.

This is used by static type checkers that recognize structural sub-typing (duck-typing) and does not need to be explicitly subclassed.

__init__(*args, **kwargs)
apply_functor(functor: Functor) Diagrammable[source]

Apply a functor to the current object.

property cod: Ty

The co-domain of the diagram.

property dom: Ty

The domain of the diagram.

property is_id: bool

Whether the current diagram is an identity diagram.

rotate(z: int) Diagrammable[source]

Apply the adjoint operation z times.

If z is positive, apply the right adjoint z times. If z is negative, apply the left adjoint -z times.

to_diagram() Diagram[source]

Transform the current object into an actual Diagram object.

class lambeq.backend.grammar.Entity[source]

Bases: object

__init__() None
category: ClassVar[Category]
class lambeq.backend.grammar.Functor(target_category: Category, ob: Callable[[Functor, Ty], Ty], ar: Callable[[Functor, Box], Diagrammable] | None = None)[source]

Bases: object

A functor that maps between categories.

Parameters:
target_categoryCategory

The category to which the functor maps.

obcallable, optional

A function that maps types to types, by default None

arcallable, optional

A function that maps boxes to Diagrammables, by default None

Examples

>>> n = Ty('n')
>>> diag = Cap(n, n.l) @ Id(n) >> Id(n) @ Cup(n.l, n)
>>> diag.draw(
...     figsize=(2, 2), path='./docs/_static/images/snake.png')
docs/_static/images/snake.png
>>> F = Functor(grammar, lambda _, ty : ty @ ty)
>>> F(diag).draw(
...     figsize=(2, 2), path='./docs/_static/images/snake-2.png')
docs/_static/images/snake-2.png
__call__(entity: Ty) Ty[source]
__call__(entity: Box) Diagrammable
__call__(entity: Diagram) Diagram
__call__(entity: Diagrammable) Diagrammable

Apply the functor to a type or a diagrammable.

Parameters:
entityTy or Diagrammable

The type or diagrammable to which the functor is applied.

__init__(target_category: Category, ob: Callable[[Functor, Ty], Ty], ar: Callable[[Functor, Box], Diagrammable] | None = None) None[source]
ar(ar: Box) Diagrammable[source]

Apply the functor to a box.

ar_with_cache(ar: Diagrammable) Diagrammable[source]

Apply the functor to a diagrammable, caching the result.

ob(ob: Ty) Ty[source]

Apply the functor to a type.

ob_with_cache(ob: Ty) Ty[source]

Apply the functor to a type, caching the result.

target_category: Category
lambeq.backend.grammar.Id(dom: Ty | None = None) Self
class lambeq.backend.grammar.Layer(left: Ty, box: Box, right: Ty)[source]

Bases: Entity

A layer in a diagram.

Parameters:
boxBox

The box in the layer.

leftTy

The wire type to the left of the box.

rightTy

The wire type to the right of the box.

__init__(left: Ty, box: Box, right: Ty) None
box: Box
category: ClassVar[Category] = Category(name='grammar', Ty=<class 'lambeq.backend.grammar.Ty'>, Box=<class 'lambeq.backend.grammar.Box'>, Layer=<class 'lambeq.backend.grammar.Layer'>, Diagram=<class 'lambeq.backend.grammar.Diagram'>)
property cod: Ty
dagger() Self[source]
property dom: Ty
extend(left: Ty | None = None, right: Ty | None = None) Self[source]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Layer.

Returns:
Layer

The layer generated from the JSON data.

left: Ty
right: Ty
rotate(z: int) Self[source]

Rotate the layer.

to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this layer to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unpack() tuple[lambeq.backend.grammar.Ty, lambeq.backend.grammar.Box, lambeq.backend.grammar.Ty][source]
class lambeq.backend.grammar.Spider(type: Ty, n_legs_in: int, n_legs_out: int)[source]

Bases: Box

A spider in the grammar category.

Parameters:
typeTy

The atomic type of the spider.

n_legs_inint

The number of input legs.

n_legs_outint

The number of output legs.

__init__(type: Ty, n_legs_in: int, n_legs_out: int) None
apply_functor(functor: Functor) Diagrammable[source]
category: ClassVar[Category] = Category(name='grammar', Ty=<class 'lambeq.backend.grammar.Ty'>, Box=<class 'lambeq.backend.grammar.Box'>, Layer=<class 'lambeq.backend.grammar.Layer'>, Diagram=<class 'lambeq.backend.grammar.Diagram'>)
cod: Ty
dagger() Self[source]
dom: Ty
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property l: Self
n_legs_in: int
n_legs_out: int
name: str
property r: Self
rotate(z: int) Self[source]

Rotate the spider.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

type: Ty
unwind() Self
z: int = 0
class lambeq.backend.grammar.Swap(left: Ty, right: Ty)[source]

Bases: Box

A swap in the grammar category.

Swaps two wires.

Parameters:
leftTy

The atomic type of the left input wire.

rightTy

The atomic type of the right input wire.

__init__(left: Ty, right: Ty) None
apply_functor(functor: Functor) Diagrammable[source]
category: ClassVar[Category] = Category(name='grammar', Ty=<class 'lambeq.backend.grammar.Ty'>, Box=<class 'lambeq.backend.grammar.Box'>, Layer=<class 'lambeq.backend.grammar.Layer'>, Diagram=<class 'lambeq.backend.grammar.Diagram'>)
cod: Ty
dagger() Self[source]
dom: Ty
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property l: Self
left: Ty
name: str
property r: Self
right: Ty
rotate(z: int) Self[source]

Rotate the swap.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.grammar.Ty(name: str | None = None, objects: list[Self] = <factory>, z: int = 0)[source]

Bases: Entity

A type in the grammar category.

Every type is either atomic, complex, or empty. Complex types are tensor products of atomic types, and empty types are the identity type.

Parameters:
namestr, optional

The name of the type, by default None.

objectslist[Ty], optional

The objects defining a complex type, by default [].

zint, optional

The winding number of the type, by default 0.

__init__(name: str | None = None, objects: list[Self] = <factory>, z: int = 0) None
apply_functor(functor: Functor) Ty[source]
category: ClassVar[Category] = Category(name='grammar', Ty=<class 'lambeq.backend.grammar.Ty'>, Box=<class 'lambeq.backend.grammar.Box'>, Layer=<class 'lambeq.backend.grammar.Layer'>, Diagram=<class 'lambeq.backend.grammar.Diagram'>)
count(other: Self) int[source]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Ty.

Returns:
Ty

The type generated from the JSON data.

property is_atomic: bool
property is_complex: bool
property is_empty: bool
property l: Self
name: str | None = None
objects: list[Self]
property r: Self
repeat(times: int) Self[source]
rotate(z: int) Self[source]

Rotate the type, changing the winding number.

tensor(other: Iterable[Self]) Self[source]
tensor(other: Self, *rest: Self) Self
to_diagram() Diagram[source]
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this type to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self[source]
z: int = 0
class lambeq.backend.grammar.Word(name: str, cod: Ty, z: int = 0)[source]

Bases: Box

A word in the grammar category.

A word is a Box with an empty domain.

Parameters:
namestr

The name of the word.

codTy

The codomain of the word.

zint, optional

The winding number of the word, by default 0

__init__(name: str, cod: Ty, z: int = 0) None
apply_functor(functor: Functor) Diagrammable
category: ClassVar[Category] = Category(name='grammar', Ty=<class 'lambeq.backend.grammar.Ty'>, Box=<class 'lambeq.backend.grammar.Box'>, Layer=<class 'lambeq.backend.grammar.Layer'>, Diagram=<class 'lambeq.backend.grammar.Diagram'>)
cod: Ty
dagger() Daggered[source]
dom: Ty
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property l: Self
name: str
property r: Self
rotate(z: int) Self[source]

Rotate the Word box, changing the winding number.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0

lambeq.backend.tensor

Tensor category

Lambeq’s internal representation of the tensor category. This work is based on DisCoPy (https://discopy.org/) which is released under the BSD 3-Clause ‘New’ or ‘Revised’ License.

class lambeq.backend.tensor.Box(name: str, dom: Dim, cod: Dim, data: float | np.ndarray | None = None, z: int = 0)[source]

Bases: Box

Box (tensor) in the the tensor category.

Attributes:
datanp.array or float or None

Data used to represent the array attribute. Typically either the array itself, or a symbolic array.

arraynp.array or float

Tensor which the box represents.

free_symbolsset of sympy.Symbol

In case of a symbolic tensor, set of symbols in the box’s data.

__init__(name: str, dom: Dim, cod: Dim, data: float | np.ndarray | None = None, z: int = 0)[source]

Initialise a tensor.Box type.

Parameters:
namestr

Name for the box.

domDim

Dimension of the box’s domain.

codDim

Dimension of the box’s codomain.

datafloat or np.ndarray, optional

The concrete tensor the box represents.

zint, optional

Winding number of the box, indicating conjugation. Starts at 0 if not provided.

apply_functor(functor: Functor) Diagrammable[source]
property array
category: ClassVar[Category] = Category(name='tensor', Ty=<class 'lambeq.backend.tensor.Dim'>, Box=<class 'lambeq.backend.tensor.Box'>, Layer=<class 'lambeq.backend.tensor.Layer'>, Diagram=<class 'lambeq.backend.tensor.Diagram'>)
cod: Dim
dagger()[source]

Get the dagger (adjoint) of the box.

Returns:
Box

Dagger of the box.

data: float | np.ndarray | None
dom: Dim
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable[source]

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z: int)[source]

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

to_diagram() Diagram[source]
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self[source]
z: int = 0
class lambeq.backend.tensor.Cap(left: Ty, right: Ty, is_reversed: bool = False)[source]

Bases: Cap, Box

A Cap in the tensor category.

__init__(left: Dim, right: Dim, is_reversed: bool = False)[source]

Initialise a tensor Cap.

Parameters:
leftDim

Dimension (type) of the left leg of the cap. Must be the conjugate of right.

rightDim

Dimension (type) of the right leg of the cap. Must be the conjugate of left.

is_reversedbool, default False

Ignored parameter, since left and right conjugates are equivalent in the tensor category. Necessary to inherit from grammar.Cap appropriately.

apply_functor(functor: Functor) Diagrammable[source]
property array
category: ClassVar[Category] = Category(name='tensor', Ty=<class 'lambeq.backend.tensor.Dim'>, Box=<class 'lambeq.backend.tensor.Box'>, Layer=<class 'lambeq.backend.tensor.Layer'>, Diagram=<class 'lambeq.backend.tensor.Diagram'>)
cod: Dim
dagger() Cup[source]

Get the dagger (adjoint) of the box.

Returns:
Box

Dagger of the box.

data: float | np.ndarray | None
dom: Dim
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

is_reversed: bool = False
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

left: Dim
name: str
property r: Self
right: Dim
rotate(z: int) Self[source]

Rotate the cap.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

classmethod to_left(right: Ty, is_reversed: bool = False) Self | Diagram[source]
classmethod to_right(left: Ty, is_reversed: bool = False) Self | Diagram[source]
unwind() Self
z: int = 0
class lambeq.backend.tensor.Cup(left: Ty, right: Ty, is_reversed: bool = False)[source]

Bases: Cup, Box

A Cup in the tensor category.

__init__(left: Dim, right: Dim, is_reversed: bool = False)[source]

Initialise a tensor Cup.

Parameters:
leftDim

Dimension (type) of the left leg of the cup. Must be the conjugate of right.

rightDim

Dimension (type) of the right leg of the cup. Must be the conjugate of left.

is_reversedbool, default False

Ignored parameter, since left and right conjugates are equivalent in the tensor category. Necessary to inherit from grammar.Cup appropriately.

apply_functor(functor: Functor) Diagrammable[source]
property array
category: ClassVar[Category] = Category(name='tensor', Ty=<class 'lambeq.backend.tensor.Dim'>, Box=<class 'lambeq.backend.tensor.Box'>, Layer=<class 'lambeq.backend.tensor.Layer'>, Diagram=<class 'lambeq.backend.tensor.Diagram'>)
cod: Dim
dagger() Cap[source]

Get the dagger (adjoint) of the box.

Returns:
Box

Dagger of the box.

data: float | np.ndarray | None
dom: Dim
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

is_reversed: bool = False
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

left: Dim
name: str
property r: Self
right: Dim
rotate(z: int) Self[source]

Rotate the cup.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

classmethod to_left(right: Ty, is_reversed: bool = False) Self | Diagram[source]
classmethod to_right(left: Ty, is_reversed: bool = False) Self | Diagram[source]
unwind() Self
z: int = 0
class lambeq.backend.tensor.Daggered(box: Box)[source]

Bases: Daggered, Box

A daggered box.

Attributes:
boxBox

The box to be daggered.

__init__(box: Box) None

Initialise a tensor.Box type.

Parameters:
namestr

Name for the box.

domDim

Dimension of the box’s domain.

codDim

Dimension of the box’s codomain.

datafloat or np.ndarray, optional

The concrete tensor the box represents.

zint, optional

Winding number of the box, indicating conjugation. Starts at 0 if not provided.

apply_functor(functor: Functor) Diagrammable
property array
box: Box
category: ClassVar[Category] = Category(name='tensor', Ty=<class 'lambeq.backend.tensor.Dim'>, Box=<class 'lambeq.backend.tensor.Box'>, Layer=<class 'lambeq.backend.tensor.Layer'>, Diagram=<class 'lambeq.backend.tensor.Diagram'>)
cod: Dim
dagger() Box[source]

Get the dagger (adjoint) of the box.

Returns:
Box

Dagger of the box.

data: float | np.ndarray | None = None
dom: Dim
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z: int) Self[source]

Rotate the daggered box.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.tensor.Diagram(dom: Dim, cod: Dim, layers: list[lambeq.backend.tensor.Layer])[source]

Bases: Diagram

Diagram in the tensor category.

__init__(dom: Dim, cod: Dim, layers: list[lambeq.backend.tensor.Layer]) None
apply_functor(functor: Functor) Diagram[source]
classmethod ba(left, right) Self[source]
classmethod bc(left, middle, right) Self[source]
property boxes: list[lambeq.backend.grammar.Box]
classmethod bx(left, middle, right) Self[source]
classmethod caps(left: Ty, right: Ty, is_reversed=False) Diagrammable[source]
category: ClassVar[Category] = Category(name='tensor', Ty=<class 'lambeq.backend.tensor.Dim'>, Box=<class 'lambeq.backend.tensor.Box'>, Layer=<class 'lambeq.backend.tensor.Layer'>, Diagram=<class 'lambeq.backend.tensor.Diagram'>)
cod: Dim
classmethod create_pregroup_diagram(words: list[lambeq.backend.grammar.Word], morphisms: list[tuple[type, int, int]]) Self[source]

Create a Diagram from cups and swaps.

>>> n, s = Ty('n'), Ty('s')
>>> words = [Word('she', n), Word('goes', n.r @ s @ n.l),
...          Word('home', n)]
>>> morphs = [(Cup, 0, 1), (Cup, 3, 4)]
>>> diagram = Diagram.create_pregroup_diagram(words, morphs)
Parameters:
wordslist of Word

A list of Word s corresponding to the words of the sentence.

morphisms: list of tuple[type, int, int]
A list of tuples of the form:

(morphism, start_wire_idx, end_wire_idx).

Morphisms can be Cup s or Swap s, while the two numbers define the indices of the wires on which the morphism is applied.

Returns:
Diagram

The generated pregroup diagram.

Raises:
ValueError

If the provided morphism list does not type-check properly.

classmethod cups(left: Ty, right: Ty, is_reversed=False) Diagrammable[source]
curry(n: int = 1, left: bool = True) Self[source]
dagger() Self[source]
dom: Dim
draw(draw_as_pregroup=True, **kwargs: Any) None[source]

Draw the diagram.

Parameters:
draw_as_pregroupbool, optional

Whether to try drawing the diagram as a pregroup diagram, default is True.

draw_as_nodesbool, optional

Whether to draw boxes as nodes, default is False.

colorstring, optional

Color of the box or node, default is white (‘#ffffff’) for boxes and red (‘#ff0000’) for nodes.

textpadpair of floats, optional

Padding between text and wires, default is (0.1, 0.1).

draw_type_labelsbool, optional

Whether to draw type labels, default is False.

draw_box_labelsbool, optional

Whether to draw box labels, default is True.

aspectstring, optional

Aspect ratio, one of [‘auto’, ‘equal’].

marginstuple, optional

Margins, default is (0.05, 0.05).

nodesizefloat, optional

BoxNode size for spiders and controlled gates.

fontsizeint, optional

Font size for the boxes, default is 12.

fontsize_typesint, optional

Font size for the types, default is 12.

figsizetuple, optional

Figure size.

pathstr, optional

Where to save the image, if None we call plt.show().

to_tikzbool, optional

Whether to output tikz code instead of matplotlib.

asymmetryfloat, optional

Make a box and its dagger mirror images, default is .25 * any(box.is_dagger for box in diagram.boxes).

eval(contractor=<function auto>, dtype: type | None = None)[source]

Evaluate the tensor diagram.

Parameters:
contractortn contractor

tensornetwork contractor for chosen contraction algorithm.

dtypetype, optional

Data type of the resulting array. Defaults to np.float32.

Returns:
numpy.ndarray

n-dimension array representing the contracted tensor.

classmethod fa(left, right) Self[source]
classmethod fc(left, middle, right) Self[source]
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_discopy(diagram: discopy.monoidal.Diagram) Diagram[source]

Import discopy diagram to lambeq diagram.

Parameters:
diagramdiscopy.monoidal.Diagram
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Diagram.

Returns:
Diagram

The diagram generated from the JSON data.

classmethod fx(left, middle, right) Self[source]
classmethod id(dom: Ty | None = None) Self[source]
property is_id: bool
property is_pregroup: bool

Check if a diagram is a pregroup diagram.

Adapted from discopy.grammar.pregroup.draw.

Returns:
bool

Whether the diagram is a pregroup diagram.

property l: Self
lambdify(*symbols, **kwargs)[source]
layers: list[Layer]
classmethod lift(diagrams: Iterable[Diagrammable | Ty]) list[Self][source]

Lift diagrams to the current category.

Given a list of boxes or diagrams, call to_diagram on each, then check all of the diagrams are in the same category as the calling class.

Parameters:
diagramsiterable

The diagrams to lift and check.

Returns:
list of Diagram

The diagrams after calling to_diagram on each.

Raises:
ValueError

If any of the diagrams are not in the same category of the calling class.

normal_form(left: bool = False) Diagram[source]

Returns the normal form of a connected diagram, see arXiv:1804.07832.

Parameters:
leftbool, optional

Whether to apply left interchangers.

Raises:
NotImplementedError

Whenever normalizer yields the same rewrite steps twice.

property offsets: list[int]

The offset of a box is the length of the type on its left.

classmethod permutation(dom: Ty, permutation: Iterable[int]) Self[source]

Create a layer of Swaps that permutes the wires.

permuted(permutation: Iterable[int]) Self[source]
pregroup_normal_form()[source]

Applies normal form to a pregroup diagram of the form word @ ... @ word >> wires by normalising words and wires seperately before combining them, so it can be drawn with draw().

property r: Self
classmethod register_special_box(name: str, diagram_factory: _DiagrammableFactory | None = None) None | Callable[[_DiagrammableFactoryT], _DiagrammableFactoryT][source]
render_as_str(**kwargs: Any) str[source]

Render the diagram as text.

Presently only implemented for pregroup diagrams.

Parameters:
word_spacingint, default: 2

The number of spaces between the words of the diagrams.

use_at_separatorbool, default: False

Whether to represent types using @ as the monoidal product. Otherwise, use the unicode dot character.

compress_layersbool, default: True

Whether to draw boxes in the same layer when they can occur simultaneously, otherwise, draw one box per layer.

use_ascii: bool, default: False

Whether to draw using ASCII characters only, for compatibility reasons.

Returns:
str

Drawing of diagram in string format.

rotate(z: int) Self[source]

Rotate the diagram.

special_boxes: ClassVar[dict[str, _DiagrammableFactory]] = {'cap': <class 'lambeq.backend.tensor.Cap'>, 'cup': <class 'lambeq.backend.tensor.Cup'>, 'spider': <class 'lambeq.backend.tensor.Spider'>, 'swap': <class 'lambeq.backend.tensor.Swap'>}
classmethod swap(left: Ty, right: Ty) Diagrammable[source]
tensor(*diagrams: Diagrammable | Ty) Self[source]
then(*diagrams: Diagrammable) Self[source]
then_at(diagram: Diagrammable, index: int) Self[source]
to_diagram() Self[source]
to_discopy() discopy.monoidal.Diagram[source]

Export lambeq diagram to discopy diagram.

Returns:
discopy.monoidal.Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this diagram to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

to_tn(dtype: type | None = None)[source]

Convert the diagram to a tensornetwork TN.

Parameters:
dtypetype, optional

Data type of the resulting array. Defaults to np.float32.

Returns:
tuple[list[tn.Node], list[tn.Edge]]

tensornetwork representation of the diagram. An edge object is returned for each dangling edge in the network.

transpose(left: bool = False) Self[source]

Construct the diagrammatic transpose.

The transpose of any diagram in a category with cups and caps can be constructed as follows:

(default)

Left transpose Right transpose

│╭╮ ╭╮│ │█│ │█│ ╰╯│ │╰╯

The input and output types of the transposed diagram are the adjoints of the respective types of the original diagram. This means that for diagrams with composite types, the order of the objects are reversed.

Parameters:
leftbool, default: False

Whether to transpose to the diagram to the left.

Returns:
Diagram

The transposed diagram, constructed as shown above.

class lambeq.backend.tensor.Dim(*dim: int, objects: list[Self] | None = None)[source]

Bases: Ty

Dimension in the tensor category.

Attributes:
dimtuple of int

Tuple of dimensions represented by the object.

product: int

Product of contained dimensions.

__init__(*dim: int, objects: list[Self] | None = None) None[source]

Initialise a Dim type.

Parameters:
dimlist[int]

List of dimensions to initialise.

objects: list[Self] or None, default None

List of Dim`s, to prepare a non-atomic `Dim object.

apply_functor(functor: Functor) Ty
category: ClassVar[Category] = Category(name='tensor', Ty=<class 'lambeq.backend.tensor.Dim'>, Box=<class 'lambeq.backend.tensor.Box'>, Layer=<class 'lambeq.backend.tensor.Layer'>, Diagram=<class 'lambeq.backend.tensor.Diagram'>)
count(other: Self) int
property dim: tuple[int, ...]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Ty.

Returns:
Ty

The type generated from the JSON data.

property is_atomic: bool
property is_complex: bool
property is_empty: bool
property l: Self
name: str | None = None
objects: list[Self]
property product: int
property r: Self
repeat(times: int) Self
rotate(z: int) Self[source]

Rotate the type, changing the winding number.

tensor(other: Self | Iterable[Self], *rest: Self) Self
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this type to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.tensor.Layer(left: Dim, box: Box, right: Dim)[source]

Bases: Layer

Layer in the tensor category.

__init__(left: Dim, box: Box, right: Dim) None
box: Box
category: ClassVar[Category] = Category(name='tensor', Ty=<class 'lambeq.backend.tensor.Dim'>, Box=<class 'lambeq.backend.tensor.Box'>, Layer=<class 'lambeq.backend.tensor.Layer'>, Diagram=<class 'lambeq.backend.tensor.Diagram'>)
property cod: Ty
dagger() Self[source]
property dom: Ty
extend(left: Ty | None = None, right: Ty | None = None) Self[source]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Layer.

Returns:
Layer

The layer generated from the JSON data.

left: Dim
right: Dim
rotate(z: int) Self[source]

Rotate the layer.

to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this layer to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unpack() tuple[lambeq.backend.grammar.Ty, lambeq.backend.grammar.Box, lambeq.backend.grammar.Ty][source]
class lambeq.backend.tensor.Spider(type: Ty, n_legs_in: int, n_legs_out: int)[source]

Bases: Spider, Box

A Spider in the tensor category.

Concretely represented by a copy node.

__init__(type: Dim, n_legs_in: int, n_legs_out: int)[source]

Initialise a tensor Spider.

Parameters:
typeDim

Dimension (type) of each leg of the spider.

n_legs_inint

Number of input legs of the spider.

n_legs_outint

Number of input legs of the spider.

apply_functor(functor: Functor) Diagrammable[source]
property array
category: ClassVar[Category] = Category(name='tensor', Ty=<class 'lambeq.backend.tensor.Dim'>, Box=<class 'lambeq.backend.tensor.Box'>, Layer=<class 'lambeq.backend.tensor.Layer'>, Diagram=<class 'lambeq.backend.tensor.Diagram'>)
cod: Dim
dagger() Self[source]

Get the dagger (adjoint) of the box.

Returns:
Box

Dagger of the box.

data: float | np.ndarray | None
dom: Dim
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

n_legs_in: int
n_legs_out: int
name: str
property r: Self
rotate(z: int) Self[source]

Rotate the spider.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

type: Dim
unwind() Self
z: int = 0
class lambeq.backend.tensor.Swap(left: Ty, right: Ty)[source]

Bases: Swap, Box

A Swap in the tensor category.

__init__(left: Dim, right: Dim)[source]

Initialise a tensor Swap.

Parameters:
leftDim

Dimension (type) of the left input of the swap.

rightDim

Dimension (type) of the right input of the swap.

apply_functor(functor: Functor) Diagrammable[source]
property array
category: ClassVar[Category] = Category(name='tensor', Ty=<class 'lambeq.backend.tensor.Dim'>, Box=<class 'lambeq.backend.tensor.Box'>, Layer=<class 'lambeq.backend.tensor.Layer'>, Diagram=<class 'lambeq.backend.tensor.Diagram'>)
cod: Dim
dagger()[source]

Get the dagger (adjoint) of the box.

Returns:
Box

Dagger of the box.

data: float | np.ndarray | None
dom: Dim
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

left: Dim
name: str
property r: Self
right: Dim
rotate(z: int) Self[source]

Rotate the swap.

to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0

lambeq.backend.quantum

Quantum category

Lambeq’s internal representation of the quantum category. This work is based on DisCoPy (https://discopy.org/) which is released under the BSD 3-Clause ‘New’ or ‘Revised’ License.

Notes

In lambeq, gates are represented as the transpose of their matrix according to the standard convention in quantum computing. This makes composition of gates using the tensornetwork library easier.

class lambeq.backend.quantum.AntiConjugate(name: str, dom: Ty, cod: Ty, data: float | np.ndarray | None = None, z: int = 0, is_mixed: bool = False, self_adjoint: bool = False)[source]

Bases: Box

An anti-conjugate box is equal to the conjugate of its conjugate.

__init__(name: str, dom: Ty, cod: Ty, data: float | np.ndarray | None = None, z: int = 0, is_mixed: bool = False, self_adjoint: bool = False)

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Daggered | Box

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z)[source]

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Bit(*bitstring: int)[source]

Bases: Box

Classical state for a given bit.

__init__(bit_value: int) None[source]

Initialise a ket box.

Parameters:
bit_valueint

The state of the qubit (either 0 or 1).

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Daggered | Box

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z: int)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Box(name: str, dom: Ty, cod: Ty, data: float | np.ndarray | None = None, z: int = 0, is_mixed: bool = False, self_adjoint: bool = False)[source]

Bases: Box

A box in the quantum category.

__init__(name: str, dom: Ty, cod: Ty, data: float | np.ndarray | None = None, z: int = 0, is_mixed: bool = False, self_adjoint: bool = False)[source]

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable[source]
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Daggered | Box[source]

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable[source]

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z: int)[source]

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool
to_diagram() Diagram[source]
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self[source]
z: int = 0
class lambeq.backend.quantum.Bra(*bitstring: int)[source]

Bases: SelfConjugate, Box

A bra in the quantum category.

A bra is a box that measures a qubit in the computational basis and post-selects on a given state.

__init__(bit: int)[source]

Initialise a bra box.

Parameters:
bitint

The state of the qubit to post-select on (either 0 or 1).

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Self[source]

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
lambeq.backend.quantum.CRx(phi, distance=1)
lambeq.backend.quantum.CRy(phi, distance=1)
lambeq.backend.quantum.CRz(phi, distance=1)
class lambeq.backend.quantum.Controlled(controlled: Box, distance=1)[source]

Bases: Parametrized

A gate that applies a unitary controlled by a qubit’s state.

__init__(controlled: Box, distance=1)[source]

Initialise a controlled box.

Parameters:
controlledBox

The box to be controlled.

distanceint, optional

The distance between the control and the target, by default 1

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger()[source]

Return the dagger of the box.

data: float
decompose() Diagram | Box[source]

Split a box (distance >1) into distance 1 box + swaps.

dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool = False
property l: Self
lambdify(*symbols, **kwargs)[source]

Return a lambda function that evaluates the box.

property modules
name: str
property phase: float
property r: Self
rotate(z)[source]

Conjugate the box.

self_adjoint: bool = False
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Daggered(box: ~lambeq.backend.quantum.Box, __hash__: ~collections.abc.Callable[[~lambeq.backend.quantum.Box], int] = <function Box.__hash__>, __repr__: ~collections.abc.Callable[[~lambeq.backend.quantum.Box], str] = <function Box.__repr__>)[source]

Bases: Daggered, Box

A daggered gate reverses the box’s effect on a quantum state.

Parameters:
boxBox

The box to be daggered.

__init__(box: ~lambeq.backend.quantum.Box, __hash__: ~collections.abc.Callable[[~lambeq.backend.quantum.Box], int] = <function Box.__hash__>, __repr__: ~collections.abc.Callable[[~lambeq.backend.quantum.Box], str] = <function Box.__repr__>) None

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
box: Box
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Box[source]

Return the dagger of the box.

data: float | np.ndarray | None = None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool = False
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z: int) Self[source]

Rotate the daggered box.

self_adjoint: bool = False
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Diagram(dom: ~lambeq.backend.quantum.Ty, cod: ~lambeq.backend.quantum.Ty, layers: list[lambeq.backend.quantum.Layer], __hash__: ~collections.abc.Callable[[], int] = <function Diagram.__hash__>)[source]

Bases: Diagram

A diagram in the quantum category.

Parameters:
domTy

The type of the input wires.

codTy

The type of the output wires.

layerslist[Layer]

The layers of the diagram.

__init__(dom: ~lambeq.backend.quantum.Ty, cod: ~lambeq.backend.quantum.Ty, layers: list[lambeq.backend.quantum.Layer], __hash__: ~collections.abc.Callable[[], int] = <function Diagram.__hash__>) None
apply_functor(functor: Functor) Diagram[source]
apply_gate(gate: Box, *qubits: int) Self[source]
apply_parametrized_gate(gate: Callable[[float], Parametrized], param: float, *qubits: int) Self[source]
classmethod ba(left, right) Self[source]
classmethod bc(left, middle, right) Self[source]
property boxes: list[lambeq.backend.grammar.Box]
classmethod bx(left, middle, right) Self[source]
classmethod caps(left: Ty, right: Ty, is_reversed=False) Diagrammable[source]
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
classmethod create_pregroup_diagram(words: list[lambeq.backend.grammar.Word], morphisms: list[tuple[type, int, int]]) Self[source]

Create a Diagram from cups and swaps.

>>> n, s = Ty('n'), Ty('s')
>>> words = [Word('she', n), Word('goes', n.r @ s @ n.l),
...          Word('home', n)]
>>> morphs = [(Cup, 0, 1), (Cup, 3, 4)]
>>> diagram = Diagram.create_pregroup_diagram(words, morphs)
Parameters:
wordslist of Word

A list of Word s corresponding to the words of the sentence.

morphisms: list of tuple[type, int, int]
A list of tuples of the form:

(morphism, start_wire_idx, end_wire_idx).

Morphisms can be Cup s or Swap s, while the two numbers define the indices of the wires on which the morphism is applied.

Returns:
Diagram

The generated pregroup diagram.

Raises:
ValueError

If the provided morphism list does not type-check properly.

classmethod cups(left: Ty, right: Ty, is_reversed=False) Diagrammable[source]
curry(n: int = 1, left: bool = True) Self[source]
dagger() Self[source]
dom: Ty
draw(draw_as_pregroup=True, **kwargs: Any) None[source]

Draw the diagram.

Parameters:
draw_as_pregroupbool, optional

Whether to try drawing the diagram as a pregroup diagram, default is True.

draw_as_nodesbool, optional

Whether to draw boxes as nodes, default is False.

colorstring, optional

Color of the box or node, default is white (‘#ffffff’) for boxes and red (‘#ff0000’) for nodes.

textpadpair of floats, optional

Padding between text and wires, default is (0.1, 0.1).

draw_type_labelsbool, optional

Whether to draw type labels, default is False.

draw_box_labelsbool, optional

Whether to draw box labels, default is True.

aspectstring, optional

Aspect ratio, one of [‘auto’, ‘equal’].

marginstuple, optional

Margins, default is (0.05, 0.05).

nodesizefloat, optional

BoxNode size for spiders and controlled gates.

fontsizeint, optional

Font size for the boxes, default is 12.

fontsize_typesint, optional

Font size for the types, default is 12.

figsizetuple, optional

Figure size.

pathstr, optional

Where to save the image, if None we call plt.show().

to_tikzbool, optional

Whether to output tikz code instead of matplotlib.

asymmetryfloat, optional

Make a box and its dagger mirror images, default is .25 * any(box.is_dagger for box in diagram.boxes).

eval(*others, backend=None, mixed=False, contractor=<function auto>, **params)[source]

Evaluate the circuit represented by the diagram.

Be aware that this method is only suitable for small circuits with a small number of qubits (depending on hardware resources).

Parameters:
otherslambeq.backend.quantum.Diagram

Other circuits to process in batch if backend is set to tket.

backendpytket.Backend, optional

Backend on which to run the circuit, if none then we apply tensor contraction.

mixedbool, optional

Whether the circuit is mixed, by default False

contractorCallable, optional

The contractor to use, by default tn.contractors.auto

Returns:
np.ndarray or list of np.ndarray

The result of the circuit simulation.

classmethod fa(left, right) Self[source]
classmethod fc(left, middle, right) Self[source]
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_discopy(diagram: discopy.monoidal.Diagram) Diagram[source]

Import discopy diagram to lambeq diagram.

Parameters:
diagramdiscopy.monoidal.Diagram
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Diagram.

Returns:
Diagram

The diagram generated from the JSON data.

classmethod fx(left, middle, right) Self[source]
classmethod id(dom: Ty | None = None) Self[source]
init_and_discard()[source]

Return circuit with empty domain and only bits as codomain.

property is_id: bool
property is_mixed: bool

Whether the diagram is mixed.

A diagram is mixed if it contains a mixed box or if it has both classical and quantum wires.

property is_pregroup: bool

Check if a diagram is a pregroup diagram.

Adapted from discopy.grammar.pregroup.draw.

Returns:
bool

Whether the diagram is a pregroup diagram.

property l: Self
lambdify(*symbols, **kwargs)[source]
layers: list[Layer]
classmethod lift(diagrams: Iterable[Diagrammable | Ty]) list[Self][source]

Lift diagrams to the current category.

Given a list of boxes or diagrams, call to_diagram on each, then check all of the diagrams are in the same category as the calling class.

Parameters:
diagramsiterable

The diagrams to lift and check.

Returns:
list of Diagram

The diagrams after calling to_diagram on each.

Raises:
ValueError

If any of the diagrams are not in the same category of the calling class.

normal_form(left: bool = False) Diagram[source]

Returns the normal form of a connected diagram, see arXiv:1804.07832.

Parameters:
leftbool, optional

Whether to apply left interchangers.

Raises:
NotImplementedError

Whenever normalizer yields the same rewrite steps twice.

property offsets: list[int]

The offset of a box is the length of the type on its left.

classmethod permutation(dom: Ty, permutation: Iterable[int]) Self[source]

Create a layer of Swaps that permutes the wires.

permuted(permutation: Iterable[int]) Self[source]
pregroup_normal_form()[source]

Applies normal form to a pregroup diagram of the form word @ ... @ word >> wires by normalising words and wires seperately before combining them, so it can be drawn with draw().

property r: Self
classmethod register_special_box(name: str, diagram_factory: _DiagrammableFactory | None = None) None | Callable[[_DiagrammableFactoryT], _DiagrammableFactoryT][source]
render_as_str(**kwargs: Any) str[source]

Render the diagram as text.

Presently only implemented for pregroup diagrams.

Parameters:
word_spacingint, default: 2

The number of spaces between the words of the diagrams.

use_at_separatorbool, default: False

Whether to represent types using @ as the monoidal product. Otherwise, use the unicode dot character.

compress_layersbool, default: True

Whether to draw boxes in the same layer when they can occur simultaneously, otherwise, draw one box per layer.

use_ascii: bool, default: False

Whether to draw using ASCII characters only, for compatibility reasons.

Returns:
str

Drawing of diagram in string format.

rotate(z: int) Self[source]

Rotate the diagram.

special_boxes: ClassVar[dict[str, _DiagrammableFactory]] = {'cap': <function generate_cap>, 'cup': <function generate_cup>, 'spider': <function generate_spider>, 'swap': <class 'lambeq.backend.quantum.Swap'>}
classmethod swap(left: Ty, right: Ty) Diagrammable[source]
tensor(*diagrams: Diagrammable | Ty) Self[source]
then(*diagrams: Diagrammable) Self[source]
then_at(diagram: Diagrammable, index: int) Self[source]
to_diagram() Self[source]
to_discopy() discopy.monoidal.Diagram[source]

Export lambeq diagram to discopy diagram.

Returns:
discopy.monoidal.Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this diagram to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

to_pennylane(probabilities=False, backend_config=None, diff_method='best')[source]

Export lambeq circuit to PennylaneCircuit.

Parameters:
probabiltiesbool, default: False

If True, the PennylaneCircuit will return the normalized probabilties of measuring the computational basis states when run. If False, it returns the unnormalized quantum states in the computational basis.

backend_configdict, default: None

A dictionary of PennyLane backend configration options, including the provider (e.g. IBM or Honeywell), the device, the number of shots, etc. See the PennyLane plugin documentation for more details.

diff_methodstr, default: “best”

The differentiation method to use to obtain gradients for the PennyLane circuit. Some gradient methods are only compatible with simulated circuits. See the PennyLane documentation for more details.

Returns:
lambeq.backend.pennylane.PennylaneCircuit
to_tk()[source]

Export to t|ket>.

Returns:
tk_circuitlambeq.backend.converters.tk.Circuit

A lambeq.backend.converters.tk.Circuit.

Examples

>>> from lambeq.backend.quantum import *
>>> bell_test = H @ Id(qubit) >> CX >> Measure() @ Measure()
>>> bell_test.to_tk()
tk.Circuit(2, 2).H(0).CX(0, 1).Measure(0, 0).Measure(1, 1)
>>> circuit0 = (Sqrt(2) @ H @ Rx(0.5) >> CX >>
...             Measure() @ Discard())
>>> circuit0.to_tk()
tk.Circuit(2, 1).H(0).Rx(1.0, 1).CX(0, 1).Measure(0, 0).scale(2)
>>> circuit1 = Ket(1, 0) >> CX >> Id(qubit) @ Ket(0) @ Id(qubit)
>>> circuit1.to_tk()
tk.Circuit(3).X(0).CX(0, 2)
>>> circuit2 = X @ Id(qubit ** 2) \
...     >> Id(qubit) @ SWAP >> CX @ Id(qubit) >> Id(qubit) @ SWAP
>>> circuit2.to_tk()
tk.Circuit(3).X(0).CX(0, 2)
>>> circuit3 = Ket(0, 0)\
...     >> H @ Id(qubit)\
...     >> CX\
...     >> Id(qubit) @ Bra(0)
>>> print(repr(circuit3.to_tk()))
tk.Circuit(2, 1).H(0).CX(0, 1).Measure(1, 0).post_select({0: 0})
to_tn(mixed=False)[source]

Send a diagram to a mixed tensornetwork.

Parameters:
mixedbool, default: False

Whether to perform mixed (also known as density matrix) evaluation of the circuit.

Returns:
nodestensornetwork.Node

Nodes of the network.

output_edge_orderlist of tensornetwork.Edge

Output edges of the network.

transpose(left: bool = False) Self[source]

Construct the diagrammatic transpose.

The transpose of any diagram in a category with cups and caps can be constructed as follows:

(default)

Left transpose Right transpose

│╭╮ ╭╮│ │█│ │█│ ╰╯│ │╰╯

The input and output types of the transposed diagram are the adjoints of the respective types of the original diagram. This means that for diagrams with composite types, the order of the objects are reversed.

Parameters:
leftbool, default: False

Whether to transpose to the diagram to the left.

Returns:
Diagram

The transposed diagram, constructed as shown above.

class lambeq.backend.quantum.Discard[source]

Bases: SelfConjugate

Discard a qubit. This is a measurement without post-selection.

__init__()[source]

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger()[source]

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Encode[source]

Bases: SelfConjugate

Encode a classical information bit into a qubit.

__init__()[source]

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger()[source]

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
lambeq.backend.quantum.Id(ty: Ty | int | None = None) Diagram[source]
class lambeq.backend.quantum.Ket(*bitstring: int)[source]

Bases: SelfConjugate, Box

A ket in the quantum category.

A ket is a box that initializes a qubit to a given state.

__init__(bit: int) None[source]

Initialise a ket box.

Parameters:
bitint

The state of the qubit (either 0 or 1).

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Self[source]

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Layer(left: Ty, box: Box, right: Ty)[source]

Bases: Layer

A Layer in a quantum Diagram.

Parameters:
boxBox

The box of the layer.

leftTy

The wire type to the left of the box.

rightTy

The wire type to the right of the box.

__init__(left: Ty, box: Box, right: Ty) None
box: Box
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
property cod: Ty
dagger() Self[source]
property dom: Ty
extend(left: Ty | None = None, right: Ty | None = None) Self[source]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Layer.

Returns:
Layer

The layer generated from the JSON data.

left: Ty
right: Ty
rotate(z: int) Self[source]

Rotate the layer.

to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this layer to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unpack() tuple[lambeq.backend.grammar.Ty, lambeq.backend.grammar.Box, lambeq.backend.grammar.Ty][source]
class lambeq.backend.quantum.Measure[source]

Bases: SelfConjugate

Measure a qubit and return a classical information bit.

__init__()[source]

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger()[source]

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.MixedState[source]

Bases: SelfConjugate

A mixed state is a state with a density matrix proportional to the identity matrix.

__init__()[source]

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger()[source]

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Parametrized(name: str, dom: Ty, cod: Ty, data: float | np.ndarray | None = None, z: int = 0, is_mixed: bool = False, self_adjoint: bool = False)[source]

Bases: Box

A parametrized box in the quantum category.

A parametrized box is a unitary gate that can be parametrized by a real number.

Parameters:
namestr

The name of the box.

domTy

The domain of the box.

codTy

The codomain of the box.

datafloat

The parameterised unitary of the box.

is_mixedbool, default: False

Whether the box is mixed

self_adjointbool, default: False

Whether the box is self-adjoint

__init__(name: str, dom: Ty, cod: Ty, data: float | np.ndarray | None = None, z: int = 0, is_mixed: bool = False, self_adjoint: bool = False)

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Daggered | Box

Return the dagger of the box.

data: float
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool = False
property l: Self
lambdify(*symbols, **kwargs)[source]

Return a lambda function that evaluates the box.

property modules
name: str
property r: Self
rotate(z: int)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool = False
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Rotation(phase)[source]

Bases: Parametrized

Single qubit gate defining a rotation around the bloch sphere.

__init__(phase)[source]

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Self[source]

Return the dagger of the box.

data: float
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool = False
property l: Self
lambdify(*symbols, **kwargs)

Return a lambda function that evaluates the box.

property modules
name: str
property phase: float
property r: Self
rotate(z: int)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool = False
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Rx(phase)[source]

Bases: AntiConjugate, Rotation

Single qubit gate defining a rotation aound the x-axis.

__init__(phase)

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Self

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool = False
property l: Self
lambdify(*symbols, **kwargs)

Return a lambda function that evaluates the box.

property modules
name: str
property phase: float
property r: Self
rotate(z)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool = False
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Ry(phase)[source]

Bases: SelfConjugate, Rotation

Single qubit gate defining a rotation aound the y-axis.

__init__(phase)

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Self

Return the dagger of the box.

data: float
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool = False
property l: Self
lambdify(*symbols, **kwargs)

Return a lambda function that evaluates the box.

property modules
name: str
property phase: float
property r: Self
rotate(z)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool = False
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Rz(phase)[source]

Bases: AntiConjugate, Rotation

Single qubit gate defining a rotation aound the z-axis.

__init__(phase)

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Self

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool = False
property l: Self
lambdify(*symbols, **kwargs)

Return a lambda function that evaluates the box.

property modules
name: str
property phase: float
property r: Self
rotate(z)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool = False
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Scalar(data: float | np.ndarray, __hash__: Callable[[Box], int] = <function Box.__hash__>)[source]

Bases: Box

A scalar amplifies a quantum state by a given factor.

__init__(data: float | np.ndarray, __hash__: Callable[[Box], int] = <function Box.__hash__>) None

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty = Ty()
dagger()[source]

Return the dagger of the box.

data: float | np.ndarray
dom: Ty = Ty()
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool = False
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z: int)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool = False
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.SelfConjugate(name: str, dom: Ty, cod: Ty, data: float | np.ndarray | None = None, z: int = 0, is_mixed: bool = False, self_adjoint: bool = False)[source]

Bases: Box

A self-conjugate box is equal to its own conjugate.

__init__(name: str, dom: Ty, cod: Ty, data: float | np.ndarray | None = None, z: int = 0, is_mixed: bool = False, self_adjoint: bool = False)

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger() Daggered | Box

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z)[source]

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Sqrt(data: float | np.ndarray, __hash__: Callable[[], int] = <function Box.__hash__>)[source]

Bases: Scalar

A Square root.

__init__(data: float | np.ndarray, __hash__: Callable[[], int] = <function Box.__hash__>) None

Initialise a box in the quantum category.

Parameters:
namestr

Name of the box.

domTy

Domain of the box.

codTy

Codomain of the box.

datafloat | np.ndarray, optional

Array defining the tensor of the box, by default None

zint, optional

The winding number, by default 0

is_mixedbool, optional

Whether the box is mixed, by default False

self_adjointbool, optional

Whether the box is self-adjoint, by default False

apply_functor(functor: Functor) Diagrammable
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty = Ty()
dagger()[source]

Return the dagger of the box.

data: float | np.ndarray
dom: Ty = Ty()
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool = False
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

name: str
property r: Self
rotate(z: int)

Get the result of conjugating the box z times.

Parameters:
zint

Winding count. The number of conjugations to apply to the box.

Returns:
Box

The box conjugated z times.

self_adjoint: bool = False
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self
z: int = 0
class lambeq.backend.quantum.Swap(left: Ty, right: Ty)[source]

Bases: Swap, SelfConjugate, Box

A swap box in the quantum category.

__init__(left: Ty, right: Ty)[source]

Initialise a swap box.

Parameters:
leftTy

The left type of the swap.

rightTy

The right type of the swap.

apply_functor(functor: Functor) Diagrammable[source]
property array
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
cod: Ty
dagger()[source]

Return the dagger of the box.

data: float | np.ndarray | None
dom: Ty
property free_symbols: set[sympy.core.symbol.Symbol]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Box.

Returns:
Box

The box generated from the JSON data.

property is_classical: bool
is_mixed: bool
property l: Self
lambdify(*symbols: Symbol, **kwargs) Callable

Get a lambdified version of a symbolic box.

Returns a function which when provided appropriate parameters, initialises a concrete box.

Parameters:
symbolslist of sympy.Symbols

List of symbols in the box in the order in which their assigned values will appear in the concretisation call.

kwargs:

Additional parameters to pass to sympy.lambdify.

Returns:
Callable[…, Box]:

A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.

left: Dim
n_legs_in: int
n_legs_out: int
name: str
property r: Self
right: Dim
rotate(z: int) Self[source]

Rotate the swap.

self_adjoint: bool
to_diagram() Diagram
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this box to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

type: Ty
unwind() Self
z: int = 0
class lambeq.backend.quantum.Ty(name: str | None = None, objects: list[Self] | None = None)[source]

Bases: Dim

A type in the quantum category.

__init__(name: str | None = None, objects: list[Self] | None = None)[source]

Initialise a type in the quantum category.

Parameters:
namestr, optional

The name of the type, by default None

objectslist[Ty], optional

The objects defining a complex type, by default None

apply_functor(functor: Functor) Ty[source]
category: ClassVar[Category] = Category(name='quantum', Ty=<class 'lambeq.backend.quantum.Ty'>, Box=<class 'lambeq.backend.quantum.Box'>, Layer=<class 'lambeq.backend.quantum.Layer'>, Diagram=<class 'lambeq.backend.quantum.Diagram'>)
count(other: Self) int[source]
property dim: tuple[int, ...]
classmethod from_json(data: _JSONDictT | str) Self[source]

Decode a JSON object or string into a Ty.

Returns:
Ty

The type generated from the JSON data.

property is_atomic: bool
property is_complex: bool
property is_empty: bool
property l: Self
name: str | None = None
objects: list[Self]
property product: int
property r: Self
repeat(times: int) Self[source]
rotate(z: int) Self

Rotate the type, changing the winding number.

tensor(other: Self | Iterable[Self], *rest: Self) Self[source]
to_diagram() Diagram[source]
to_json(is_top_level: bool = True) Dict[str, Any][source]

Encode this type to a JSON object.

Parameters:
is_top_levelbool, optional

This flag indicates that this object is the top-most object and should have the global metadata (e.g. category). This should be set to False when calling to_json on attribute instances to avoid duplication of said global metadata.

unwind() Self[source]
z: int = 0
lambeq.backend.quantum.generate_cap(left: Ty, right: Ty, is_reversed=False) Diagram[source]

Generate a cap diagram.

Parameters:
leftTy

The left type of the cap.

rightTy

The right type of the cap.

is_reversedbool, optional

Unused, by default False

Returns:
Diagram

The cap diagram.

lambeq.backend.quantum.generate_cup(left: Ty, right: Ty, is_reversed=False) Diagram[source]

Generate a cup diagram.

Parameters:
leftTy

The left type of the cup.

rightTy

The right type of the cup.

is_reversedbool, optional

Unused, by default False

Returns:
Diagram

The cup diagram.

lambeq.backend.quantum.generate_spider(type: Ty, n_legs_in: int, n_legs_out: int) Diagram[source]

lambeq.backend.numerical_backend

Numerical Backend

Module unifying the use of numerical backends for lambeq. This module is used to provide a common interface to different numerical backends, such as NumPy, JAX, PyTorch, and TensorFlow.

class lambeq.backend.numerical_backend.Backend(module: ModuleType, array: Callable | None = None)[source]

Bases: object

A matrix backend.

Parameters:

module : The main module of the backend. array : The array class of the backend.

__init__(module: ModuleType, array: Callable | None = None)[source]
property name
class lambeq.backend.numerical_backend.JAX[source]

Bases: Backend

JAX backend.

__init__()[source]
property name
class lambeq.backend.numerical_backend.NumPy[source]

Bases: Backend

NumPy backend.

__init__()[source]
property name
class lambeq.backend.numerical_backend.PyTorch[source]