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.
- 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'>)¶
- classmethod from_json(data: Dict[str, Any] | 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¶
- 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.
- 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.
- 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'>)¶
- classmethod from_json(data: Dict[str, Any] | str) Self [source]¶
Decode a JSON object or string into a
Box
.- Returns:
Box
The box generated from the JSON data.
- is_reversed: dataclasses.InitVar[bool] = False¶
- property l: Self¶
- name: str¶
- property r: Self¶
- 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.Category(name: str)[source]¶
Bases:
object
The base class for all categories.
- __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: Dict[str, Any] | 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
, aBox
subclass, or aDiagram
instance.
- name: str¶
- 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.
- 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'>)¶
- classmethod from_json(data: Dict[str, Any] | str) Self [source]¶
Decode a JSON object or string into a
Box
.- Returns:
Box
The box generated from the JSON data.
- is_reversed: dataclasses.InitVar[bool] = False¶
- property l: Self¶
- name: str¶
- property r: Self¶
- 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.Daggered(box: Box)[source]¶
Bases:
Box
A daggered box.
- Parameters:
- boxBox
The box to be daggered.
- 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'>)¶
- classmethod from_json(data: Dict[str, Any] | 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¶
- 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.DaggeredFrame(frame: Frame)[source]¶
Bases:
Frame
A daggered frame.
- Parameters:
- frameFrame
The frame to be daggered.
- 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'>)¶
- components: list[Diagrammable]¶
- property frame_order¶
The level of nesting in the frame increasing from the inside going outward.
- property frame_type¶
The number of holes in the frame.
- classmethod from_json(data: Dict[str, Any] | str) DaggeredFrame [source]¶
Decode a JSON object or string into a
Frame
.- Returns:
Frame
The frame generated from the JSON data.
- property l: Self¶
- name: str¶
- property r: Self¶
- to_json(is_top_level: bool = True) Dict[str, Any] [source]¶
Encode this frame 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[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.
- 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'>)¶
- classmethod create_pregroup_diagram(words: list[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 orSwap
s, while the two numbers define the indices of the wires on which the morphism is applied.
- wordslist of
- 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]¶
- 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 from_discopy(diagram: discopy.monoidal.Diagram) Diagram [source]¶
Import discopy diagram to lambeq diagram.
- Parameters:
- diagram
discopy.monoidal.Diagram
- diagram
- classmethod from_json(data: Dict[str, Any] | str) Self [source]¶
Decode a JSON object or string into a
Diagram
.- Returns:
Diagram
The diagram generated from the JSON data.
- property has_frames: bool¶
- 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¶
- 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.
- 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 withdraw()
.
- 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
- remove_snakes(left: bool = False) Diagram [source]¶
Simplifies the diagram by removing all snakes using the snake equation. A snake is a pair of a Cup and a Cap in the form
Id @ Cap >> Cup @ Id
orCap @ Id >> Id @ Cup
, which can be straightened into anId
.- Parameters:
- leftbool, optional
If True, applies left interchangers during the process.
- 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.
- rigid_normal_form(left: bool = False) Diagram ¶
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.
- special_boxes: ClassVar[dict[str, Callable[[...], Diagrammable]]] = {'cap': <class 'lambeq.backend.grammar.Cap'>, 'cup': <class 'lambeq.backend.grammar.Cup'>, 'frame': <class 'lambeq.backend.grammar.Frame'>, '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_discopy() discopy.monoidal.Diagram [source]¶
Export lambeq diagram to discopy diagram.
- Returns:
- 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_pregroup_tree(**kwargs) PregroupTreeNode [source]¶
Convert this diagram into a pregroup tree. Parameters ———- **kwargs : dict
Keyword arguments to be passed to the diagram2tree call.
- 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.
- dagger() Diagrammable [source]¶
Apply the dagger operation.
- classmethod from_json(data: Dict[str, Any] | str) Diagrammable [source]¶
Create diagrammable from JSON data.
- 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.
- class lambeq.backend.grammar.Frame(name: str, dom: ~lambeq.backend.grammar.Ty, cod: ~lambeq.backend.grammar.Ty, z: int = 0, components: list[~lambeq.backend.grammar.Diagrammable] = <factory>)[source]¶
Bases:
Box
A frame in the grammar category.
It can contain other diagrams as its components. Frame is an abstract container, which means that the relationship between its domain/codomain with those of the individual nested diagrams remains undefined at this level, and is left to be implemented by the application of purpose-specific ansatze and rewriters.
Frames can be nested to an arbitrary depth.
- Parameters:
- namestr
The name of the frame.
- domTy
The domain of the frame.
- codTy
The codomain of the frame.
- zint, optional
The winding number of the frame, by default 0.
- componentslist of Diagrammable
The components inside this frame.
- __init__(name: str, dom: ~lambeq.backend.grammar.Ty, cod: ~lambeq.backend.grammar.Ty, z: int = 0, components: list[~lambeq.backend.grammar.Diagrammable] = <factory>) 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'>)¶
- components: list[Diagrammable]¶
- dagger() DaggeredFrame | Frame [source]¶
- property frame_order¶
The level of nesting in the frame increasing from the inside going outward.
- property frame_type¶
The number of holes in the frame.
- classmethod from_json(data: Dict[str, Any] | str) Self [source]¶
Decode a JSON object or string into a
Frame
.- Returns:
Frame
The frame generated from the JSON data.
- property l: Self¶
- name: str¶
- property r: Self¶
- to_json(is_top_level: bool = True) Dict[str, Any] [source]¶
Encode this frame 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.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='./snake.png')
>>> F = Functor(grammar, lambda _, ty : ty @ ty) >>> F(diag).draw( ... figsize=(2, 2), path='./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.
- 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.
- 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'>)¶
- classmethod from_json(data: Dict[str, Any] | str) Self [source]¶
Decode a JSON object or string into a
Layer
.- Returns:
Layer
The layer generated from the JSON data.
- to_json(is_top_level: bool = True) Dict[str, Any] [source]¶
Encode this layer to a JSON object.
- Parameters:
- is_top_levelbool, optional (default=True)
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.
- 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.
- 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'>)¶
- classmethod from_json(data: Dict[str, Any] | 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¶
- 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.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.
- 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'>)¶
- classmethod from_json(data: Dict[str, Any] | 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¶
- 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[~typing.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[~typing.Self] = <factory>, z: int = 0) None ¶
- 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'>)¶
- classmethod from_json(data: Dict[str, Any] | str) Self [source]¶
Decode a JSON object or string into a
Ty
.- Returns:
Ty
The type generated from the JSON data.
- insert(other: Self, index: int) Self [source]¶
Insert a type at the specified index in the complex type list.
- Parameters:
- otherTy
The type to insert. Can be atomic or complex.
- indexint
The position where the type should be inserted.
- 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¶
- replace(other: Self, index: int) Self [source]¶
Replace a type at the specified index in the complex type list.
- Parameters:
- otherTy
The type to insert. Can be atomic or complex.
- indexint
The position where the type should be inserted.
- 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.
- 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
- 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'>)¶
- classmethod from_json(data: Dict[str, Any] | 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¶
- 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 | 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 lambeq.backend.symbol.Symbol
In case of a symbolic tensor, set of symbols in the box’s data.
- __init__(name: str, dom: Dim, cod: Dim, data: float | 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.
- 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'>)¶
- data: float | np.ndarray | None¶
- property free_symbols: set[Symbol]¶
- 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 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 lambdify.
- Returns:
- Callable[…, Box]:
A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.
- name: str¶
- class lambeq.backend.tensor.Cap(left: Ty, right: Ty, is_reversed: bool = False)[source]¶
-
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.
- is_reversed: bool = False¶
- z: int = 0¶
- class lambeq.backend.tensor.Cup(left: Ty, right: Ty, is_reversed: bool = False)[source]¶
-
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.
- is_reversed: bool = False¶
- name: str¶
- z: int = 0¶
- class lambeq.backend.tensor.Daggered(box: Box)[source]¶
-
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.
- property array¶
- data: float | np.ndarray | None = None¶
- 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 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 lambdify.
- Returns:
- Callable[…, Box]:
A lambda function which when invoked with appropriate parameters, returns a concrete version of the box.
- name: str¶
- class lambeq.backend.tensor.Diagram(dom: Dim, cod: Dim, layers: list[Layer])[source]¶
Bases:
Diagram
Diagram in the tensor category.
- 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'>)¶
- 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.
- property free_symbols: set[Symbol]¶
- 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'>}¶
- 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.
- 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.
- 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 dim: tuple[int, ...]¶
- objects: list[Self]¶
- property product: int¶
- class lambeq.backend.tensor.Layer(left: Dim, box: Box, right: Dim)[source]¶
Bases:
Layer
Layer in the tensor category.
- class lambeq.backend.tensor.Spider(type: Ty, n_legs_in: int, n_legs_out: int)[source]¶
-
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.
- n_legs_in: int¶
- n_legs_out: int¶
- name: str¶
- z: int = 0¶
- class lambeq.backend.tensor.Swap(left: Ty, right: Ty)[source]¶
-
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.
- name: str¶
- 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 | 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.
- class lambeq.backend.quantum.Bit(*bitstring: int)[source]¶
Bases:
Box
Classical state for a given bit.
- class lambeq.backend.quantum.Box(name: str, dom: Ty, cod: Ty, data: float | 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 | 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
- 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'>)¶
- data: float | np.ndarray | None¶
- property is_classical: bool¶
- is_mixed: bool¶
- name: str¶
- self_adjoint: bool¶
- 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.
- class lambeq.backend.quantum.CircuitInfo(total_qubits: int, gates: list[Gate], bitmap: dict[int, int], postmap: dict[int, int], discards: list[int])[source]¶
Bases:
object
Info for constructing circuits with backends.
- Parameters:
- total_qubitsint
Total number of qubits in the circuit.
- gateslist[
Gate
] List containing gates, in topological ordering.
- bitmap: dict[int, int]
Dictionary mapping qubit index to bit index for measurements, postselection, etc.
- postmap: dict[int, int]
Dictionary mapping qubit index to post selection value.
- discards: list[int]
List of discarded qubit indeces.
- __init__(total_qubits: int, gates: list[Gate], bitmap: dict[int, int], postmap: dict[int, int], discards: list[int]) None ¶
- bitmap: dict[int, int]¶
- discards: list[int]¶
- postmap: dict[int, int]¶
- total_qubits: int¶
- 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
- property array¶
- property phase: float¶
- 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]¶
-
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
- data: float | np.ndarray | None = None¶
- is_mixed: bool = False¶
- name: str¶
- self_adjoint: bool = False¶
- 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_parametrized_gate(gate: Callable[[float], Parametrized], param: float, *qubits: int) Self [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'>)¶
- 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:
- others
lambeq.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
- others
- Returns:
- np.ndarray or list of np.ndarray
The result of the circuit simulation.
- property is_circuital: bool¶
Checks if this diagram is a ‘circuital’ quantum diagram.
- Circuital means:
All initial layers are qubits
All post selections are at the end
Allows for mixed_circuit measurements.
- Returns:
- bool
Whether this diagram is a circuital diagram.
- 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.
- special_boxes: ClassVar[dict[str, _DiagrammableFactory]] = {'cap': <function generate_cap>, 'cup': <function generate_cup>, 'spider': <function generate_spider>, 'swap': <class 'lambeq.backend.quantum.Swap'>}¶
- 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
Notes
No measurements are performed.
SWAP gates are treated as logical swaps.
If the circuit contains scalars or a
Bra
, thentk_circuit
will hold attributespost_selection
andscalar
.
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).SWAP(1, 2).CX(0, 1).SWAP(1, 2)
>>> circuit3 = Ket(0, 0)\ ... >> H @ Id(qubit)\ ... >> CX\ ... >> Id(qubit) @ Bra(0) >>> circuit3.to_tk() tk.Circuit(2, 1).H(0).CX(0, 1).Measure(1, 0).post_select({1: 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:
- nodes
tensornetwork.Node
Nodes of the network.
- output_edge_orderlist of
tensornetwork.Edge
Output edges of the network.
- nodes
- 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
- 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
- class lambeq.backend.quantum.Gate(name: str, gtype: str, qubits: list[int], phase: float | Symbol | None = 0, dagger: bool = False, control: list[int] | None = None, gate_q: int | None = None)[source]¶
Bases:
object
Gate information for backend circuit construction.
- Parameters:
- namestr
Arbitrary name / id
- gtypestr
Type for backend conversion, e.g., ‘Rx’, ‘X’, etc.
- qubitslist[int]
List of qubits the gate acts on.
- phaseUnion[float, Symbol, None] = 0
Phase parameter for gate.
- daggerbool = False
Whether to dagger the gate.
- controlOptional[list[int]] = None
For control gates, list of all the control qubits.
- gate_qOptional[int] = None
For control gates, the gates being controlled.
- __init__(name: str, gtype: str, qubits: list[int], phase: float | Symbol | None = 0, dagger: bool = False, control: list[int] | None = None, gate_q: int | None = None) None ¶
- control: list[int] | None = None¶
- dagger: bool = False¶
- classmethod from_box(box: Box, offset: int, use_sympy: bool = False) Gate [source]¶
Constructs Gate for backend circuit construction from a Box.
- Parameters:
- boxBox
Box to convert to a Gate.
- offsetint
Qubit index on the leftmost part of the Gate.
- use_sympybool
Use sympy.Symbol for the gate params, otherwise use lambeq.backend.Symbol.
- gate_q: int | None = None¶
- gtype: str¶
- name: str¶
- phase: float | Symbol | None = 0¶
- qubits: list[int]¶
- 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.
- 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.
- 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
- 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
- class lambeq.backend.quantum.Parametrized(name: str, dom: Ty, cod: Ty, data: float | 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
- data: float¶
- is_mixed: bool = False¶
- property modules¶
- name: str¶
- self_adjoint: bool = False¶
- 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
- property phase: float¶
- class lambeq.backend.quantum.Rx(phase)[source]¶
Bases:
AntiConjugate
,Rotation
Single qubit gate defining a rotation aound the x-axis.
- property array¶
- class lambeq.backend.quantum.Ry(phase)[source]¶
Bases:
SelfConjugate
,Rotation
Single qubit gate defining a rotation aound the y-axis.
- property array¶
- class lambeq.backend.quantum.Rz(phase)[source]¶
Bases:
AntiConjugate
,Rotation
Single qubit gate defining a rotation aound the z-axis.
- property array¶
- class lambeq.backend.quantum.Scalar(data: float | ~numpy.ndarray, __hash__: ~collections.abc.Callable[[~lambeq.backend.quantum.Box], int] = <function Box.__hash__>)[source]¶
Bases:
Box
A scalar amplifies a quantum state by a given factor.
- __init__(data: float | ~numpy.ndarray, __hash__: ~collections.abc.Callable[[~lambeq.backend.quantum.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
- property array¶
- data: float | np.ndarray¶
- is_mixed: bool = False¶
- name: str¶
- self_adjoint: bool = False¶
- z: int = 0¶
- class lambeq.backend.quantum.SelfConjugate(name: str, dom: Ty, cod: Ty, data: float | 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.
- class lambeq.backend.quantum.Sqrt(data: float | ~numpy.ndarray, __hash__: ~collections.abc.Callable[[], int] = <function Box.__hash__>)[source]¶
Bases:
Scalar
A Square root.
- __init__(data: float | ~numpy.ndarray, __hash__: ~collections.abc.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
- property array¶
- data: float | np.ndarray¶
- is_mixed: bool = False¶
- name: str¶
- self_adjoint: bool = False¶
- 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.
- n_legs_in: int¶
- n_legs_out: int¶
- name: str¶
- 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.
- 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.readoff_circuital(diagram: Diagram, use_sympy: bool = False) CircuitInfo [source]¶
Takes a circuital
lambeq.quantum.Diagram
, returns aCircuitInfo
which is used by quantum backends to construct circuits. This checks if the diagram is circuital before converting.- Parameters:
- Returns:
- lambeq.backend.quantum.to_circuital(diagram: Diagram) Diagram [source]¶
Takes a
lambeq.quantum.Diagram
, returns a modifiedlambeq.quantum.Diagram
which is easier to convert to tket and other circuit simulators- Parameters:
- Returns:
lambeq.quantum.Diagram
Circuital diagram compatible with circuital_to_dict.
lambeq.backend.pregroup_tree¶
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.
- property name¶
- class lambeq.backend.numerical_backend.PyTorch[source]¶
Bases:
Backend
PyTorch backend.
- property name¶
- class lambeq.backend.numerical_backend.TensorFlow[source]¶
Bases:
Backend
TensorFlow backend.
- property name¶
lambeq.backend.converters.discopy¶
Interface with discopy¶
Module containing the functions to convert from and to discopy. This work is based on DisCoPy (https://discopy.org/) which is released under the BSD 3-Clause “New” or “Revised” License.
- lambeq.backend.converters.discopy.box_d2l(box: Box, target: type[_LAMBEQ_BOX_VAR]) _LAMBEQ_BOX_VAR [source]¶
- lambeq.backend.converters.discopy.box_l2d(box: Box, target: type[_DISCOPY_BOX_VAR]) _DISCOPY_BOX_VAR [source]¶
- lambeq.backend.converters.discopy.from_discopy(diagram: Diagram | Circuit | Diagram) Diagram | Diagram | Diagram [source]¶
Takes a
discopy.grammar.pregroup.Diagram
,discopy.quantum.Diagram
, ordiscopy.tensor.Diagram
, and converts it to alambeq.backend.grammar.Diagram
,lambeq.backend.quantum.Diagram
, orlambeq.backend.tensor.Diagram
, respectively.- Parameters:
- diagram
discopy.grammar.pregroup.Diagram
| discopy.quantum.Diagram
|discopy.tensor.Diagram
The diagram to convert.
- diagram
- Returns:
lambeq.backend.grammar.Diagram
|lambeq.backend.quantum.Diagram
|lambeq.backend.tensor.Diagram
The converted diagram.
- lambeq.backend.converters.discopy.to_discopy(diagram: Diagram | Diagram | Diagram) Diagram | Circuit | Diagram [source]¶
Takes a
lambeq.backend.grammar.Diagram
,lambeq.backend.quantum.Diagram
, orlambeq.backend.tensor.Diagram
, and converts it to adiscopy.grammar.pregroup.Diagram
,discopy.quantum.Diagram
, ordiscopy.tensor.Diagram
, respectively.- Parameters:
- diagramlambeq.backend.grammar.Diagram |
lambeq.backend.quantum.Diagram
|lambeq.backend.tensor.Diagram
The diagram to convert.
- Returns:
- :class:
discopy.grammar.pregroup.Diagram
| discopy.quantum.Diagram
|discopy.tensor.Diagram
The converted diagram.
- :class:
lambeq.backend.converters.tk¶
Interface with tket¶
Module containing the functions to convert from and to tket. This work is based on DisCoPy (https://discopy.org/) which is released under the BSD 3-Clause “New” or “Revised” License.
- class lambeq.backend.converters.tk.Circuit(n_qubits: int = 0, n_bits: int = 0, post_selection: dict[int, int] | None = None, scalar: float | None = None, post_processing: Diagram | None = None)[source]¶
Bases:
Circuit
Extend pytket.Circuit with counts post-processing.
- __init__(*args, **kwargs)[source]¶
Overloaded function.
__init__(self: pytket._tket.circuit.Circuit) -> None
Constructs a circuit with a completely empty DAG.
__init__(self: pytket._tket.circuit.Circuit, name: str) -> None
Constructs a named circuit with a completely empty DAG.
- Parameters:
name – name for the circuit
__init__(self: pytket._tket.circuit.Circuit, n_qubits: int, name: Optional[str] = None) -> None
Constructs a circuit with a given number of qubits/blank wires.
>>> c = Circuit() >>> c.add_blank_wires(3)
is equivalent to
>>> c = Circuit(3)
- Parameters:
n_qubits – The number of qubits in the circuit
name – Optional name for the circuit.
__init__(self: pytket._tket.circuit.Circuit, n_qubits: int, n_bits: int, name: Optional[str] = None) -> None
Constructs a circuit with a given number of quantum and classical bits
- Parameters:
n_qubits – The number of qubits in the circuit
n_bits – The number of classical bits in the circuit
name – Optional name for the circuit.
- get_counts(*others: Circuit, backend=None, **params) list[ndarray] [source]¶
Runs a circuit on a backend and returns the counts.
- property n_bits: int¶
Number of bits in a circuit.
- lambeq.backend.converters.tk.from_tk(tk_circuit: Circuit) Diagram [source]¶
Translates from tket to a lambeq Diagram.
- lambeq.backend.converters.tk.to_tk(diagram: Diagram) Circuit [source]¶
Takes a
lambeq.quantum.Diagram
, returns alambeq.backend.converters.tk.Circuit
for t|ket>.- Parameters:
- Returns:
- tk_circuitlambeq.backend.quantum
Notes
Converts to circuital.
Copies the diagram to avoid modifying the original.
lambeq.backend.pennylane¶
PennyLane interface¶
Lambeq’s interface with Pennylane circuits. This work is based on DisCoPy (https://discopy.org/) which is released under the BSD 3-Clause ‘New’ or ‘Revised’ License.
Notes¶
If probabilities is set to False, the output states of the PennyLane circuit will be exactly equivalent to those of the lambeq circuit (for the same parameters).
If probabilities is set to True, the output states of the PennyLane
circuit will be the probabilities of the output states, equivalent
to appending lambeq.backend.quantum.Measure
to all the
open wires in the lambeq circuit.
Once a PennyLaneCircuit
has been constructed, it
can be evaluated with eval()
. If the circuit contains only
concrete parameters (i.e. no symbolic parameters), no arguments
should be passed to eval(). If the circuit contains symbolic
parameters, a list of the symbolic parameters and a list of their
associated weights should be passed to eval() as symbols= and
weights=.
- class lambeq.backend.pennylane.PennyLaneCircuit(ops, symbols, params, wires, probabilities, post_selection, mixed, scale, n_qubits, backend_config, diff_method)[source]¶
Bases:
object
Implement a pennylane circuit with post-selection.
- __init__(ops, symbols, params, wires, probabilities, post_selection, mixed, scale, n_qubits, backend_config, diff_method)[source]¶
- contains_symbols()[source]¶
Determine if the circuit parameters are concrete or contain SymPy symbols.
- Returns:
- bool
Whether the circuit parameters contain SymPy symbols.
- draw()[source]¶
Print a string representation of the circuit similar to qml.draw, but including post-selection.
- Parameters:
- symbolslist of
lambeq.Symbol
, default: None The symbols from the original lambeq circuit.
- weightslist of
torch.FloatTensor
, default: None The weights to substitute for the symbols.
- symbolslist of
- eval()[source]¶
Evaluate the circuit. The symbols should be those from the original lambeq diagram, which will be substituted for the concrete parameters in weights.
- Parameters:
- symbolslist of
lambeq.Symbol
, default: None The symbols from the original lambeq circuit.
- weightslist of
torch.FloatTensor
, default: None The weights to substitute for the symbols.
- symbolslist of
- Returns:
torch.Tensor
The post-selected output of the circuit.
- get_device(backend_config)[source]¶
Return a PennyLane device with the specified backend configuration.
- get_valid_states()[source]¶
Determine which of the output states of the circuit are compatible with the post-selections.
- Returns:
- list of int
The indices of the circuit output that are compatible with the post-selections.
- initialise_concrete_params(symbol_weight_map)[source]¶
Given concrete values for each of the SymPy symbols, substitute the symbols for the values to obtain concrete parameters, via the param_substitution method.
- initialise_device_and_circuit()[source]¶
Initialise the PennyLane device and circuit when instantiating the PennyLaneCirucit, or loading from disk.
- make_circuit()[source]¶
Construct the
qml.Qnode
, a circuit that can be used with autograd to construct hybrid models.- Returns:
qml.Qnode
A Pennylane circuit without post-selection.
- lambeq.backend.pennylane.extract_ops_from_circuital(gates: List[Gate]) Tuple[List[Operation], List[List[Tensor | Symbol | Never]], Set[Symbol], List[List[int]]] [source]¶
Extract the operation, parameters and wires from a circuital diagram dictionary, and return the corresponding PennyLane operation.
- Parameters:
- circuit_dict
Dict
The circuital dictionary to convert.
- circuit_dict
- Returns:
- list of
qml.operation.Operation
The PennyLane operation equivalent to the input pytket Op.
- list of (
torch.FloatTensor
or lambeq.backend.symbol.Symbol
)The parameters of the operation.
- list of
lambeq.backend.symbol.Symbol
The free symbols in the parameters of the operation.
- list of lists of int
The wires/qubits to apply the operation to.
- list of
- lambeq.backend.pennylane.to_pennylane(diagram: Diagram, probabilities=False, backend_config=None, diff_method='best') PennyLaneCircuit [source]¶
Return a PennyLaneCircuit equivalent to the input lambeq circuit. probabilities determines whether the PennyLaneCircuit returns states (as in lambeq), or probabilities (to be more compatible with automatic differentiation in PennyLane).
- Parameters:
- diagram
lambeq.backend.quantum.Diagram
The lambeq circuit to convert to PennyLane.
- probabilitiesbool, default: False
Determines whether the PennyLane circuit outputs states or un-normalized probabilities. Probabilities can be used with more PennyLane backpropagation methods.
- 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.
- diagram
- Returns:
PennyLaneCircuit
The PennyLane circuit equivalent to the input lambeq circuit.
lambeq.backend.drawing¶
lambeq’s drawing module.
- class lambeq.backend.drawing.DrawableDiagram(boxes: list[~lambeq.backend.drawing.drawable.BoxNode] = <factory>, wire_endpoints: list[~lambeq.backend.drawing.drawable.WireEndpoint] = <factory>, wires: list[tuple[int, int]] = <factory>)[source]¶
Bases:
object
Representation of a lambeq diagram carrying all information necessary to render it.
- Attributes:
- boxes: list of BoxNode
Boxes in the diagram.
- wire_endpoints: list of WireEndpoint
Endpoints for all wires in the diagram.
- wires: list of tuple of the form (int, int)
The wires in a diagram, each represented by the indices of its 2 endpoints in wire_endpoints.
- __init__(boxes: list[~lambeq.backend.drawing.drawable.BoxNode] = <factory>, wire_endpoints: list[~lambeq.backend.drawing.drawable.WireEndpoint] = <factory>, wires: list[tuple[int, int]] = <factory>) None ¶
- boxes: list[BoxNode]¶
- classmethod from_diagram(diagram: Diagram, foliated: bool = False) Self [source]¶
Builds a graph representation of the diagram, calculating coordinates for each box and wire.
- Parameters:
- diagramgrammar Diagram
A lambeq diagram.
- foliatedbool, default: False
If true, each box of the diagram is drawn in a separate layer. By default boxes are compressed upwards into available space.
- Returns:
- drawableDrawableDiagram
Representation of diagram including all coordinates necessary to draw it.
- scale_and_pad(scale: tuple[float, float], pad: tuple[float, float])[source]¶
Scales and pads the diagram as specified.
- Parameters:
- scaletuple of 2 floats
Scaling factors for x and y axes respectively.
- padtuple of 2 floats
Padding values for x and y axes respectively.
- wire_endpoints: list[WireEndpoint]¶
- wires: list[tuple[int, int]]¶
- lambeq.backend.drawing.draw(diagram: Diagram, **params) None [source]¶
Draw a grammar diagram.
- Parameters:
- diagram: Diagram
Diagram to draw.
- 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 True.
- draw_box_labelsbool, optional
Whether to draw box labels, default is True.
- color_boxesbool, optional
Whether to color boxes when drawable has frames. 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).
- foliatedbool, default: False
If true, each box of the diagram is drawn in a separate layer. By default boxes are compressed upwards into available space.
- lambeq.backend.drawing.draw_equation(*terms: Diagram, symbol: str = '=', space: float = 1, path: str | None = None, **params) None [source]¶
Draw an equation with multiple diagrams.
- Parameters:
- terms: list of Diagrams
Diagrams in equation.
- symbol: str
Symbol separating equations. ‘=’ by default.
- space: float
Amount of space between adjacent diagrams.
- pathstr, optional
Where to save the image, if None we call plt.show().
- **params:
Additional drawing parameters, passed to
draw()
.
- lambeq.backend.drawing.draw_pregroup(diagram: Diagram, **params) None [source]¶
Draw a pregroup grammar diagram.
- A pregroup diagram is structured as:
(State @ State … State) >> (Cups and Swaps)
- Parameters:
- diagram: Diagram
Diagram to draw.
- 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).
- aspectstring, optional
Aspect ratio, one of [‘auto’, ‘equal’].
- marginstuple, optional
Margins, default is (0.05, 0.05).
- 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.
- lambeq.backend.drawing.render_as_str(diagram: Diagram, word_spacing: int = 2, use_at_separator: bool = False, compress_layers: bool = True, use_ascii: bool = False) str [source]¶
Render a grammar diagram as text.
Presently only implemented for pregroup diagrams.
- Parameters:
- diagram: Diagram
Diagram to draw.
- 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.
- lambeq.backend.drawing.to_gif(diagrams: list[Diagram], path: str | None = None, timestep: int = 500, loop: bool = False, **params) str | HTML_ty [source]¶
Build a GIF stepping through the given diagrams.
- Parameters:
- diagrams: list of Diagrams
Sequence of diagrams to draw.
- pathstr
Where to save the image, if None a gif gets created.
- timestepint, optional
Time step in milliseconds, default is 500.
- loopbool, optional
Whether to loop, default is False
- paramsany, optional
Passed to Diagram.draw.
- Returns:
- IPython.display.HTML or str
HTML to display the generated GIF
lambeq.backend.snake_removal¶
Snake removal¶
This module contains a function for removing snakes from diagrams. This work is based on DisCoPy (https://discopy.org/) which is released under the BSD 3-Clause “New” or “Revised” License.
- exception lambeq.backend.snake_removal.InterchangerError(box0: Box, box1: Box)[source]¶
Bases:
Exception
This is raised when we try to interchange conected boxes.
- add_note()¶
Exception.add_note(note) – add a note to the exception
- args¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- lambeq.backend.snake_removal.interchange(diagram: Diagram, i: int, j: int, left: bool = False) Diagram [source]¶
Returns a new diagram with boxes i and j interchanged.
Gets called recursively whenever
i < j + 1 or j < i - 1
.- Parameters:
- diagram
Diagram
The diagram to interchange boxes in.
- iint
Index of the box to interchange.
- jint
Index of the new position for the box.
- leftbool, optional
Whether to apply left interchangers.
- diagram
Notes
By default, we apply only right exchange moves:
top >> Id(left @ box1.dom @ mid) @ box0 @ Id(right) >> Id(left) @ box1 @ Id(mid @ box0.cod @ right) >> bottom
gets rewritten to:
top >> Id(left) @ box1 @ Id(mid @ box0.dom @ right) >> Id(left @ box1.cod @ mid) @ box0 @ Id(right) >> bottom
- lambeq.backend.snake_removal.normalize(diagram: Diagram, left: bool = False) Iterator[Diagram] [source]¶
Implements normalization of diagrams, see arXiv:1804.07832.
- Parameters:
- diagram
Diagram
The diagram to normalize.
- leftbool, optional
Passed to
interchange()
.
- diagram
- Yields:
- diagram
Diagram
Rewrite steps.
- diagram
Examples
>>> from lambeq.backend.grammar import Ty, Box >>> s0, s1 = Box('s0', Ty(), Ty()), Box('s1', Ty(), Ty()) >>> gen = normalize(s0 @ s1) >>> for _ in range(3): print(next(gen)) |Ty() @ [s1; Ty() -> Ty()] @ Ty()| >> |Ty() @ [s0; Ty() -> Ty()] @ Ty()| |Ty() @ [s0; Ty() -> Ty()] @ Ty()| >> |Ty() @ [s1; Ty() -> Ty()] @ Ty()| |Ty() @ [s1; Ty() -> Ty()] @ Ty()| >> |Ty() @ [s0; Ty() -> Ty()] @ Ty()|
- lambeq.backend.snake_removal.snake_removal(diagram: Diagram, left: bool = False) Iterator[Diagram] [source]¶
Returns a generator which yields normalization steps.
- Parameters:
- leftbool, optional
Whether to apply left interchangers.
- Yields:
- diagram
Diagram
Rewrite steps.
- diagram
Examples
>>> from lambeq.backend.grammar import Ty, Box, Cup, Cap, Id >>> n, s = Ty('n'), Ty('s') >>> cup, cap = Cup(n, n.r), Cap(n.r, n) >>> f = Box('f', n, n) >>> g = Box('g', s @ n, n) >>> h = Box('h', n, n @ s) >>> diagram = g @ cap >> f.dagger() @ Id(n.r) @ f >> cup @ h >>> for d in snake_removal(diagram): ... print(d) |Ty... >> |Ty() @ [CUP; Ty(n) @ Ty(n).r -> Ty()] @ Ty(n)| >>... |Ty... >> |Ty(n) @ [CAP; Ty() -> Ty(n).r @ Ty(n)] @ Ty()| >> |Ty() @ [CUP; Ty(n) @ Ty(n).r -> Ty()] @ Ty(n)| >>... |Ty() @ [g; Ty(s) @ Ty(n) -> Ty(n)] @ Ty()| >> |Ty() @ [f†; Ty(n) -> Ty(n)] @ Ty()| >> |Ty() @ [f; Ty(n) -> Ty(n)] @ Ty()| >> |Ty() @ [h; Ty(n) -> Ty(n) @ Ty(s)] @ Ty()|