# -*- coding: utf-8 -*-
"""
The free rigid category, i.e. diagrams with cups and caps.
Summary
-------
.. autosummary::
:template: class.rst
:nosignatures:
:toctree:
Wire
Ty
Nat
Diagram
Box
Cup
Cap
Sum
Functor
Axioms
------
>>> unit, s, n = Ty(), Ty('s'), Ty('n')
>>> t = n.r @ s @ n.l
>>> assert t @ unit == t == unit @ t
>>> assert t.l.r == t == t.r.l
>>> left_snake, right_snake = Id(n.r).transpose(left=True), Id(n.l).transpose()
>>> assert left_snake.normal_form() == Id(n) == right_snake.normal_form()
>>> Equation(left_snake, Id(n), right_snake).draw(
... figsize=(4, 1), doctest='docs/_static/rigid/typed-snake-equation.svg')
.. image:: /_static/rigid/typed-snake-equation.svg
:align: center
Objects may be coloured on both sides, i.e. an object ``F : a -> b`` is a
wire separating a region ``a`` on its left from a region ``b`` on its
right. Taking an adjoint reverses the direction of the wire, hence it
swaps the two regions: ``G = F.r : b -> a``. The unit and counit of the
adjunction, i.e. ``eta = Cap(G, F)`` and ``epsilon = Cup(F, G)``, then
satisfy the snake equations, one for ``F`` and one for ``G``, for any
colours ``a`` and ``b``:
>>> from discopy.monoidal import Colour
>>> a = Colour('cornflowerblue', label='Function')
>>> b = Colour('palegreen', label='Morphism')
>>> F = Ty(Wire('F', dom=a, cod=b))
>>> G = F.r
>>> eta, epsilon = Cap(G, F), Cup(F, G)
>>> left_snake = Id(F) @ eta >> epsilon @ Id(F)
>>> right_snake = eta @ Id(G) >> Id(G) @ epsilon
>>> assert left_snake.normal_form() == Id(F)
>>> assert right_snake.normal_form() == Id(G)
>>> from discopy.monoidal import Equation
>>> Equation(left_snake, Id(F)).draw(
... figsize=(3, 2), legend=True,
... doctest='docs/_static/rigid/coloured-snake-equation.svg')
>>> Equation(right_snake, Id(G)).draw(
... figsize=(3, 2), legend=True,
... doctest='docs/_static/rigid/coloured-snake-equation-G.svg')
.. image:: /_static/rigid/coloured-snake-equation.svg
:align: center
.. image:: /_static/rigid/coloured-snake-equation-G.svg
:align: center
This is an instance of the free-forgetful adjunction between sets and
monoids, with ``F`` the free monoid functor, sending a set of generators to
the monoid of words over it, and ``G`` the forgetful functor, sending a
monoid to its underlying set. The unit ``eta`` sends a generator to the
length-one word on it, while the counit ``epsilon`` evaluates a word of
elements of a monoid as their product:
>>> from functools import lru_cache
>>> from discopy.abc import ColouredMonoid
>>> from discopy.python.function import Function
>>> from discopy.cat import Ob as CatOb, Functor, Transformation
>>> class Z3(ColouredMonoid):
... ''' The monoid of integers modulo three, with addition. '''
... ob, dom, cod = type(None), None, None
... def __init__(self, n):
... self.n = n % 3
... def __eq__(self, other):
... return isinstance(other, Z3) and self.n == other.n
... def __repr__(self):
... return f"Z3({self.n})"
... @classmethod
... def id(cls, dom=None):
... return cls(0)
... def tensor(self, *others):
... return Z3(self.n + sum(other.n for other in others))
>>> @lru_cache
... def Free(X):
... ''' The free monoid on a set ``X``, i.e. words over ``X``. '''
... class Word(ColouredMonoid):
... ob, dom, cod = type(None), None, None
... def __init__(self, xs=()):
... self.xs = list(xs)
... def __eq__(self, other):
... return isinstance(other, Word) and self.xs == other.xs
... def __repr__(self):
... return f"Word({self.xs})"
... @classmethod
... def id(cls, dom=None):
... return cls()
... def tensor(self, *others):
... return Word(self.xs + sum((other.xs for other in others), []))
... return Word
>>> class Morphism(Function):
... ''' A morphism of monoids; homomorphism not enforced. '''
The forgetful functor ``G`` does nothing to objects, it just views a monoid
as a set, while the free functor ``F`` sends a set to its words. We spell
out the two objects needed below as ``cat.Ob`` instances so that
``Transformation`` can validate the domains and codomains of its components:
>>> X_, M_ = CatOb('X'), CatOb('M')
>>> Id_set = Functor({X_: str, M_: Z3}, {}, cod=Function)
>>> GF = Functor({X_: Free(str), M_: Free(Z3)}, {}, cod=Function)
>>> Id_monoid = Functor({M_: Z3}, {}, cod=Morphism)
>>> FG = Functor({M_: Free(Z3)}, {}, cod=Morphism)
>>> eta = Transformation(
... lambda obj: Function(
... lambda x: Free(Id_set(obj).inside[0])([x]), Id_set(obj), GF(obj)),
... Id_set, GF)
>>> epsilon = Transformation(
... lambda obj: Morphism(
... lambda w: Id_monoid(obj).inside[0].id().tensor(*w.xs),
... FG(obj), Id_monoid(obj)),
... FG, Id_monoid)
>>> X, M = str, Z3
>>> assert all(eta(X_)(x) == Free(X)([x]) for x in ('a', 'b'))
>>> assert epsilon(M_)(Free(M)([Z3(1), Z3(1), Z3(2)])) == Z3(1 + 1 + 2)
>>> assert all(epsilon(M_)(eta(M_)(x)) == x for x in (Z3(0), Z3(1), Z3(2)))
"""
from __future__ import annotations
import copy
from collections.abc import Callable
from typing import Iterator
from discopy import cat, monoidal, biclosed, messages
from discopy.abc import Pregroup, RigidCategory
from discopy.cat import factory
from discopy.utils import (
assert_isatomic,
assert_isinstance,
AxiomError,
BinaryBoxConstructor,
deprecated_alias,
factory_name,
)
[docs]
class Wire(monoidal.Wire):
"""
A rigid object has adjoints :meth:`Wire.l` and :meth:`Wire.r`.
Parameters:
name : The name of the object.
z : The winding number.
dom : The domain colour.
cod : The codomain colour.
Note
----
Taking an adjoint reverses the direction of the wire, hence it
swaps the domain and codomain colours.
Example
-------
>>> a = Wire('a')
>>> assert a.l.r == a.r.l == a and a != a.l.l != a.r.r
"""
def __setstate__(self, state):
if '_z' in state: # Backward compatibility
self.z = state['_z']
del state['_z']
super().__setstate__(state)
def __init__(self, name: str, z: int = 0,
dom: monoidal.Colour | None = None,
cod: monoidal.Colour | None = None):
assert_isinstance(z, int)
self.z = z
super().__init__(name, dom, cod)
def dagger(self) -> Wire:
raise AxiomError("Rigid types have no dagger, use pivotal instead.")
@property
def l(self) -> Wire:
""" The left adjoint of the object. """
return type(self)(self.name, self.z - 1, dom=self.cod, cod=self.dom)
@property
def r(self) -> Wire:
""" The right adjoint of the object. """
return type(self)(self.name, self.z + 1, dom=self.cod, cod=self.dom)
[docs]
def unwind(self) -> Wire:
""" The object with winding number zero and the same colours. """
result = copy.copy(self)
result.z = 0
return result
def __eq__(self, other):
return monoidal.Wire.__eq__(self, other)\
and isinstance(other, Wire) and self.z == other.z
def __hash__(self):
return hash(repr(self))
def __repr__(self):
cls_name = factory_name(type(self))
z_repr = ', z=' + repr(self.z) if self.z else ''
if self.dom is None and self.cod is None:
return f"{cls_name}({self.name!r}{z_repr})"
return f"{cls_name}({self.name!r}{z_repr}, " \
f"dom={self.dom!r}, cod={self.cod!r})"
def __str__(self):
return str(self.name) + (
- self.z * '.l' if self.z < 0 else self.z * '.r')
def to_tree(self):
tree = super().to_tree()
if self.z:
tree['z'] = self.z
return tree
@classmethod
def from_tree(cls, tree):
base = monoidal.Wire.from_tree(tree) # Parses the dom/cod colours.
return cls(base.name, tree.get('z', 0), dom=base.dom, cod=base.cod)
[docs]
@factory
class Ty(Pregroup, biclosed.Ty):
"""
A rigid type is a biclosed type with rigid objects inside.
Parameters:
inside (tuple[Wire, ...]) : The objects inside the type.
Example
-------
>>> s, n = Ty('s'), Ty('n')
>>> assert n.l.r == n == n.r.l
>>> assert (s @ n).l == n.l @ s.l and (s @ n).r == n.r @ s.r
"""
generator_factory = Wire
def __setstate__(self, state):
if '_z' in state: # Backward compatibility
del state['_z']
super().__setstate__(state)
[docs]
def assert_isadjoint(self, other):
"""
Raise ``AxiomError`` if two rigid types are not adjoints.
Parameters:
other : The alleged right adjoint.
"""
if self.r != other and self != other.r:
raise AxiomError(messages.NOT_ADJOINT.format(self, other))
if self.r != other:
raise AxiomError(messages.NOT_RIGID_ADJOINT.format(self, other))
@property
def l(self) -> Ty:
""" The left adjoint of the type. """
return self.ar(*[x.l for x in self.inside[::-1]])
@property
def r(self) -> Ty:
""" The right adjoint of the type. """
return self.ar(*[x.r for x in self.inside[::-1]])
@property
def z(self) -> int:
""" The winding number is only defined for types of length 1. """
assert_isatomic(self)
return self.inside[0].z
[docs]
def unwind(self) -> Ty:
"""
The atomic type with winding number zero, see :meth:`Wire.unwind`.
This method is only defined for atomic types.
The previous normalisation applied ``.r`` once, which is only an
involution for pivotal types: it sent rigid ``n.r`` to ``n.r.r``.
Example
-------
>>> n = Ty('n')
>>> assert n.r.r.unwind() == n.l.unwind() == n
"""
assert_isatomic(self)
return self.ar(self.inside[0].unwind())
[docs]
@factory
class Nat(monoidal.Nat, Ty):
"""
A rigid ``Nat`` is a natural number ``n`` seen as a rigid type of
length ``n``.
Parameters
----------
n : int
The natural number.
"""
l = r = property(lambda self: self)
[docs]
def unwind(self) -> Nat:
"""
A natural number is self-dual, so it is its own unwinding.
>>> assert Nat(1).unwind() == Nat(1)
"""
return self
class Layer(monoidal.Layer):
"""
A rigid layer is a monoidal layer that can be rotated.
Parameters:
inside : Boxes and non-empty types, with at least one box.
"""
def rotate(self, left=False):
return type(self)(
*(x.l if left else x.r for x in list(self)[::-1]), normalise=False)
l = property(lambda self: self.rotate(left=True))
r = property(lambda self: self.rotate(left=False))
[docs]
@factory
class Diagram(biclosed.Diagram, RigidCategory):
"""
A rigid diagram is a biclosed diagram
with :class:`Cup` and :class:`Cap` boxes.
Parameters:
inside (tuple[Layer, ...]) : The layers of the diagram.
dom (Ty) : The domain of the diagram, i.e. its input.
cod (Ty) : The codomain of the diagram, i.e. its output.
Example
-------
>>> I, n, s = Ty(), Ty('n'), Ty('s')
>>> Alice, jokes = Box('Alice', I, n), Box('jokes', I, n.r @ s)
>>> d = Alice >> Id(n) @ jokes >> Cup(n, n.r) @ Id(s)
>>> d.draw(figsize=(3, 2),
... doctest='docs/_static/rigid/diagram-example.svg')
.. image:: /_static/rigid/diagram-example.svg
:align: center
Currying and evaluation come from cups and caps:
>>> from discopy.monoidal import Equation
>>> x = Ty('x')
>>> g = Box('g', x @ x, x)
>>> assert g.curry().uncurry().normal_form() == g
>>> assert g.curry(left=False).uncurry(left=False).normal_form() == g
>>> Equation(g.curry(left=False), g, g.curry(),
... symbols=("$\\\\mapsfrom$", "$\\\\mapsto$")).draw(
... doctest="docs/_static/rigid/curry.svg")
.. image:: /_static/rigid/curry.svg
:align: center
"""
ob = Ty
layer_factory = Layer
to_drawing = monoidal.Diagram.to_drawing
ev = classmethod(RigidCategory.ev.__func__)
curry = RigidCategory.curry
[docs]
@classmethod
def cups(cls, left: Ty, right: Ty) -> Diagram:
"""
Construct a diagram of nested cups for types ``left`` and ``right``.
Parameters:
left : The type left of the cup.
right : Its right adjoint.
Example
-------
>>> a, b = Ty('a'), Ty('b')
>>> Diagram.cups(a.l @ b, b.r @ a).draw(figsize=(3, 1),\\
... margins=(0.3, 0.05), doctest='docs/_static/rigid/cups.svg')
.. image:: /_static/rigid/cups.svg
:align: center
"""
return nesting(cls, cls.cup_factory)(left, right)
[docs]
@classmethod
def caps(cls, left: Ty, right: Ty) -> Diagram:
"""
Construct a diagram of nested caps for types ``left`` and ``right``.
Parameters:
left : The type left of the cap.
right : Its left adjoint.
Example
-------
>>> a, b = Ty('a'), Ty('b')
>>> Diagram.caps(a.r @ b, b.l @ a).draw(figsize=(3, 1),\\
... margins=(0.3, 0.05), doctest='docs/_static/rigid/caps.svg')
.. image:: /_static/rigid/caps.svg
:align: center
"""
return nesting(cls, cls.cap_factory)(left, right)
[docs]
def rotate(self, left=False):
"""
The half-turn rotation of a diagram, called with ``.l`` and ``.r``.
Example
-------
>>> x, y = map(Ty, "xy")
>>> f = Box('f', Ty(), x)
>>> g = Box('g', Ty(), x.r @ y)
>>> diagram = f @ g >> Cup(x, x.r) @ y
>>> Equation(diagram.l, diagram, diagram.r,
... symbols=("$\\\\mapsfrom$", "$\\\\mapsto$")).draw(
... figsize=(8, 3), doctest='docs/_static/rigid/rotate.svg')
.. image:: /_static/rigid/rotate.svg
:align: center
"""
dom, cod = (x.l if left else x.r for x in (self.cod, self.dom))
inside = tuple(
layer.l if left else layer.r for layer in self.inside[::-1])
return self.ar(inside, dom, cod, _scan=False)
l = property(lambda self: self.rotate(left=True))
r = property(lambda self: self.rotate(left=False))
[docs]
def transpose_box(self, i, j=0, left=False):
"""
Transpose the box at index ``i``.
Parameters:
i : The vertical index of the box to transpose.
j : The horizontal index of the box to transpose, only needed if
the layer ``i`` has more than one box.
left : Whether to transpose left or right.
Example
-------
>>> x, y, z = Ty(*"xyz")
>>> f, g = Box('f', x, y), Box('g', y, z)
>>> d = (f @ g).foliation()
>>> transpose_l = d.transpose_box(0, 0, left=True)
>>> transpose_r = d.transpose_box(0, 1, left=False)
>>> Equation(
... transpose_l, d, transpose_r,
... symbols=("$\\\\mapsfrom$", "$\\\\mapsto$")).draw(
... figsize=(8, 3),
... doctest="docs/_static/rigid/transpose_box.svg")
.. image:: /_static/rigid/transpose_box.svg
"""
box = self.inside[i].boxes_and_types[2 * j + 1]
transposed_box = (box.r if left else box.l).transpose(left)
top, bottom = self[:i], self[i + 1:]
boxes_and_types = list(self.inside[i].boxes_and_types)
left_boxes_and_types = boxes_and_types[:2 * j + 1]
right_boxes_and_types = boxes_and_types[2 * j + 2:]
left_layer, right_layer = [
self.id().tensor(
*(x if k % 2 else self.id(x) for k, x in enumerate(xs)))
for xs in [left_boxes_and_types, right_boxes_and_types]]
return top >> left_layer @ transposed_box @ right_layer >> bottom
[docs]
def snake_removal(self, left=False) -> Iterator[Diagram]:
"""
Return a generator which yields normalization steps.
Parameters:
left : Passed to :meth:`discopy.monoidal.Diagram.normalize`.
Example
-------
>>> from discopy.rigid import *
>>> n, s = Ty('n'), Ty('s')
>>> cup, cap = Cup(n, n.r), Cap(n.r, n)
>>> f, g, h = Box('f', n, n), Box('g', s @ n, n), Box('h', n, n @ s)
>>> diagram = g @ cap >> f[::-1] @ Id(n.r) @ f >> cup @ h
>>> for d in diagram.normalize(): print(d)
g >> f[::-1] >> n @ Cap(n.r, n) >> n @ n.r @ f >> Cup(n, n.r) @ n >> h
g >> f[::-1] >> n @ Cap(n.r, n) >> Cup(n, n.r) @ n >> f >> h
g >> f[::-1] >> f >> h
"""
from discopy import monoidal
from discopy.rigid import Cup, Cap
if getattr(self, "has_nonidentity_permutation", False):
raise NotImplementedError(messages.PERMUTATION_HAS_NO_OFFSET)
def follow_wire(diagram, i, j):
"""
Given a diagram, the index of a box i and the offset j of an output
wire, returns (i, j, obstructions) where:
- i is the index of the box which takes this wire as input, or
len(diagram) if it is connected to the bottom boundary.
- j is the offset of the wire at its bottom end.
- obstructions is a pair of lists of indices for the boxes on
the left and right of the wire we followed.
"""
left_obstruction, right_obstruction = [], []
while i < len(diagram) - 1:
i += 1
box, off = diagram.boxes[i], diagram.offsets[i]
if off <= j < off + len(box.dom):
return i, j, (left_obstruction, right_obstruction)
if off <= j:
j += len(box.cod) - len(box.dom)
left_obstruction.append(i)
else:
right_obstruction.append(i)
return len(diagram), j, (left_obstruction, right_obstruction)
def find_snake(diagram):
"""
Given a diagram, returns (cup, cap, obstructions, left_snake)
if there is a yankable pair, otherwise returns None.
"""
for cap in range(len(diagram)):
if not isinstance(diagram.boxes[cap], Cap):
continue
for left_snake, wire in [(True, diagram.offsets[cap]),
(False, diagram.offsets[cap] + 1)]:
cup, wire, obstructions =\
follow_wire(diagram, cap, wire)
not_yankable =\
cup == len(diagram)\
or not isinstance(diagram.boxes[cup], Cup)\
or left_snake and diagram.offsets[cup] + 1 != wire\
or not left_snake and diagram.offsets[cup] != wire
if not_yankable:
continue
return cup, cap, obstructions, left_snake
return None
def unsnake(diagram, cup, cap, obstructions, left_snake=False):
"""
Given a diagram and the indices for a cup and cap pair
and a pair of lists of obstructions on the left and right,
returns a new diagram with the snake removed.
A left snake is one of the form Id @ Cap >> Cup @ Id.
A right snake is one of the form Cap @ Id >> Id @ Cup.
"""
left_obstruction, right_obstruction = obstructions
if left_snake:
for box in left_obstruction:
diagram = diagram.interchange(box, cap)
yield diagram
for i, right_box in enumerate(right_obstruction):
if right_box < box:
right_obstruction[i] += 1
cap += 1
for box in right_obstruction[::-1]:
diagram = diagram.interchange(box, cup)
yield diagram
cup -= 1
else:
for box in left_obstruction[::-1]:
diagram = diagram.interchange(box, cup)
yield diagram
for i, right_box in enumerate(right_obstruction):
if right_box > box:
right_obstruction[i] -= 1
cup -= 1
for box in right_obstruction:
diagram = diagram.interchange(box, cap)
yield diagram
cap += 1
inside = diagram.inside[:cap] + diagram.inside[cup + 1:]
yield diagram.ar(
inside, diagram.dom, diagram.cod, _scan=False)
diagram = self
while True:
yankable = find_snake(diagram)
if yankable is None:
break
for _diagram in unsnake(diagram, *yankable):
yield _diagram
diagram = _diagram
for _diagram in monoidal.Diagram.normalize(diagram, left=left):
yield _diagram
normalize = snake_removal
[docs]
class Box(biclosed.Box, Diagram):
"""
A rigid box is a biclosed box in a rigid diagram.
Parameters:
name : The name of the box.
dom : The domain of the box, i.e. its input.
cod : The codomain of the box, i.e. its output.
z : The winding number of the box,
i.e. the number of half-turn rotations.
Example
-------
>>> a, b = Ty('a'), Ty('b')
>>> f = Box('f', a, b.l @ b)
>>> assert f.l.z == -1 and f.z == 0 and f.r.z == 1
>>> assert f.r.l == f == f.l.r
>>> assert f.l.l != f != f.r.r
"""
def __setstate__(self, state):
if '_z' in state: # Backward compatibility
self.z = state['_z']
del state['_z']
super().__setstate__(state)
def __init__(self, name: str, dom: Ty, cod: Ty, data=None, z=0, **params):
self.z = z
biclosed.Box.__init__(self, name, dom, cod, data=data, **params)
def __str__(self):
return cat.Box.__str__(self) if not self.z\
else str(self.r) + '.l' if self.z < 0 else str(self.l) + '.r'
def __repr__(self):
if self.is_dagger:
return biclosed.Box.__repr__(self)
return biclosed.Box.__repr__(self)[:-1] + (
f', z={self.z})' if self.z else ')')
[docs]
def setoid(self):
"""
Rigid boxes are equal when they are equal as :class:`cat.Box` and their
winding numbers `z` are also equal.
"""
return super().setoid() + (self.z, )
def rotate(self, left=False):
dom, cod = (
getattr(x, 'l' if left else 'r') for x in (self.cod, self.dom))
z = self.z + (-1 if left else 1)
return type(self)(self.name, dom=dom, cod=cod,
data=self.data, is_dagger=self.is_dagger, z=z)
@property
def is_transpose(self):
""" Whether the box is an odd rotation of a generator. """
return not self.is_dagger and self.z and bool(self.z % 2)
def to_drawing(self):
result = super().to_drawing()
result.is_transpose = self.is_transpose
return result
[docs]
class Sum(biclosed.Sum, Box):
"""
A rigid sum is a biclosed sum that can be transposed.
Parameters:
terms (tuple[Diagram, ...]) : The terms of the formal sum.
dom (Ty) : The domain of the formal sum.
cod (Ty) : The codomain of the formal sum.
"""
def rotate(self, left=False) -> Sum:
if left:
return self.sum_factory(
tuple(term.l for term in self.terms), self.cod.l, self.dom.l)
return self.sum_factory(
tuple(term.r for term in self.terms), self.cod.r, self.dom.r)
[docs]
class Cup(BinaryBoxConstructor, Box):
"""
The counit of the adjunction for an atomic type.
Parameters:
left : The atomic type.
right : Its right adjoint.
Example
-------
>>> n = Ty('n')
>>> Cup(n, n.r).draw(figsize=(2,1), margins=(0.5, 0.05),\\
... doctest='docs/_static/rigid/cup.svg')
.. image:: /_static/rigid/cup.svg
:align: center
"""
def __init__(self, left: Ty, right: Ty):
assert_isatomic(left, Ty)
assert_isatomic(right, Ty)
left.assert_isadjoint(right)
name = f"Cup({left}, {right})"
dom, cod = left @ right, self.ob(dom=left.dom, cod=left.dom)
BinaryBoxConstructor.__init__(self, left, right)
Box.__init__(self, name, dom, cod, draw_as_cup=True)
def rotate(self, left=False):
return self.cap_factory(self.right.l, self.left.l) if left\
else self.cap_factory(self.right.r, self.left.r)
[docs]
def dagger(self):
"""
The dagger of a rigid cup is ill-defined,
use a :class:`pivotal.Cup` instead.
"""
raise AxiomError("Rigid cups have no dagger, use pivotal instead.")
[docs]
class Cap(BinaryBoxConstructor, Box):
"""
The unit of the adjunction for an atomic type.
Parameters:
left : The atomic type.
right : Its left adjoint.
Example
-------
>>> n = Ty('n')
>>> Cap(n, n.l).draw(figsize=(2,1), margins=(0.5, 0.05),\\
... doctest='docs/_static/rigid/cap.svg')
.. image:: /_static/rigid/cap.svg
:align: center
"""
def __init__(self, left: Ty, right: Ty):
assert_isatomic(left, Ty)
assert_isatomic(right, Ty)
right.assert_isadjoint(left)
name = f"Cap({left}, {right})"
dom, cod = self.ob(dom=left.dom, cod=left.dom), left @ right
BinaryBoxConstructor.__init__(self, left, right)
Box.__init__(self, name, dom, cod, draw_as_cap=True)
def rotate(self, left=False):
return self.cup_factory(self.right.l, self.left.l) if left\
else self.cup_factory(self.right.r, self.left.r)
[docs]
def dagger(self):
"""
The dagger of a rigid cap is ill-defined,
use a :class:`pivotal.Cap` instead.
"""
raise AxiomError("Rigid caps have no dagger, use pivotal instead.")
[docs]
class Functor(biclosed.Functor):
"""
A rigid functor is a biclosed functor that preserves cups and caps.
Parameters:
ob_map (Mapping[Ty, Ty]) :
Map from atomic :class:`Ty` to :code:`cod.ob`.
ar_map (Mapping[Box, Diagram]) : Map from :class:`Box` to :code:`cod`.
cod (Category) : The codomain of the functor.
Example
-------
>>> s, n = Ty('s'), Ty('n')
>>> Alice, Bob = Box("Alice", Ty(), n), Box("Bob", Ty(), n)
>>> loves = Box('loves', Ty(), n.r @ s @ n.l)
>>> love_box = Box('loves', n @ n, s)
>>> ob = {s: s, n: n}
>>> ar = {Alice: Alice, Bob: Bob}
>>> ar.update({loves: Cap(n.r, n) @ Cap(n, n.l) >> n.r @ love_box @ n.l})
>>> F = Functor(ob, ar)
>>> sentence = Alice @ loves @ Bob >> Cup(n, n.r) @ s @ Cup(n.l, n)
>>> assert F(sentence).normal_form() == Alice >> Id(n) @ Bob >> love_box
>>> Equation(sentence, F(sentence), symbol='$\\\\mapsto$').draw(
... figsize=(5, 2), doctest='docs/_static/rigid/functor-example.svg')
.. image:: /_static/rigid/functor-example.svg
:align: center
"""
dom = cod = Diagram
def __call__(self, other):
if isinstance(other, Ty) or isinstance(other, Wire) and other.z == 0:
return super().__call__(other)
if isinstance(other, Wire):
return self(other.r).l if other.z < 0 else self(other.l).r
if isinstance(other, Cup):
return self.cod.cups(self(other.dom[:1]), self(other.dom[1:]))
if isinstance(other, Cap):
return self.cod.caps(self(other.cod[:1]), self(other.cod[1:]))
if isinstance(other, Box):
if not hasattr(other, "z") or not other.z:
return super().__call__(other)
z = other.z
for _ in range(abs(z)):
other = other.l if z > 0 else other.r
result = super().__call__(other)
for _ in range(abs(z)):
result = result.l if z < 0 else result.r
return result
return super().__call__(other)
def nesting(cls: type, factory: Callable) -> Callable[[Ty, Ty], Diagram]:
"""
Take a :code:`factory` for cups or caps of atomic types
and extends it recursively.
Parameters:
cls : A diagram factory, e.g. :class:`Diagram`.
factory :
A factory for cups (or caps) of atomic types, e.g. :class:`Cup`.
"""
def method(left: Ty, right: Ty) -> Diagram:
if len(left) == 0:
return cls.id(left[:0])
head, tail = factory(left[0], right[-1]), method(left[1:], right[:-1])
if head.dom: # We are nesting cups.
return left[0] @ tail @ right[-1] >> head
return head >> left[0] @ tail @ right[-1]
return method
def to_rigid(self):
return biclosed.Functor(
ob_map=lambda x: Ty(x.inside[0].name),
ar_map=lambda f: Box(f.name, to_rigid(f.dom), to_rigid(f.cod)),
cod=Diagram)(self)
biclosed.Diagram.to_rigid = to_rigid
Diagram.cup_factory, Diagram.cap_factory, Diagram.sum_factory = Cup, Cap, Sum
Diagram.functor_factory = Functor
Id = Diagram.id
class Equation(biclosed.Equation):
""" The :class:`biclosed.Equation` of rigid diagrams. """
__getattr__ = deprecated_alias(__name__, {"Ob": "Wire", "PRO": "Nat"})