Skip to content

Comonads

A comonad is the dual of a monad: a counit extracts a value from its context, and a comultiplication duplicates the context so that computations extend over it (Mac Lane, 1998). The counit laws constrain how extraction and duplication interact (comonads). The module gives the Comonad interface, its co-Kleisli category, and CofreeComonad, the product (environment) comonad \(A \times S\).

comonads

Comonads and coKleisli categories on V-enriched FinSet.

A comonad (W, ε, δ) consists of an endofunctor W, a natural counit ε: W ⇒ Id, and a natural comultiplication δ: W ⇒ W² satisfying:

W(δ) ∘ δ = δ_W ∘ δ     (coassociativity)
ε_W ∘ δ = id             (left counit)
W(ε) ∘ δ = id            (right counit)

The coKleisli category of a comonad has the same objects but morphisms A → B are morphisms W(A) → B in the base category, composed via:

f =>> g = g ∘ W(f) ∘ δ_A

The base category here is the category of V-valued matrices, which is a category when V is a Semiring, so the comonads below require a semiring algebra.

This module provides the abstract Comonad, the CoKleisliCategory adapter, and CofreeComonad, the product (environment) comonad W(A) = A × S.

References

Uustalu, T., and Vene, V. (2008). Comonadic notions of computation. Electronic Notes in Theoretical Computer Science, 203(5), 263-284. doi:10.1016/j.entcs.2008.05.029

Comonad

Bases: ABC

Abstract comonad (W, ε, δ) on V-enriched FinSet.

Subclasses must implement endofunctor, counit, and comultiply. CoKleisli composition is derived.

endofunctor abstractmethod property

endofunctor: Functor

The underlying endofunctor W.

counit abstractmethod

counit(obj: SetObject) -> Morphism

The counit component ε_A: W(A) → A.

PARAMETER DESCRIPTION
obj

The object A.

TYPE: SetObject

RETURNS DESCRIPTION
Morphism

The counit morphism ε_A.

Source code in src/quivers/monadic/comonads.py
@abstractmethod
def counit(self, obj: SetObject) -> Morphism:
    """The counit component ε_A: W(A) → A.

    Parameters
    ----------
    obj : SetObject
        The object A.

    Returns
    -------
    Morphism
        The counit morphism ε_A.
    """
    ...

comultiply abstractmethod

comultiply(obj: SetObject) -> Morphism

The comultiplication component δ_A: W(A) → W(W(A)).

PARAMETER DESCRIPTION
obj

The object A.

TYPE: SetObject

RETURNS DESCRIPTION
Morphism

The comultiplication morphism δ_A.

Source code in src/quivers/monadic/comonads.py
@abstractmethod
def comultiply(self, obj: SetObject) -> Morphism:
    """The comultiplication component δ_A: W(A) → W(W(A)).

    Parameters
    ----------
    obj : SetObject
        The object A.

    Returns
    -------
    Morphism
        The comultiplication morphism δ_A.
    """
    ...

cokleisli_compose

cokleisli_compose(f: Morphism, g: Morphism) -> Morphism

CoKleisli composition: f =>> g = g ∘ W(f) ∘ δ_A.

For f: W(A) → B and g: W(B) → C, produces W(A) → C.

PARAMETER DESCRIPTION
f

Left coKleisli morphism W(A) → B.

TYPE: Morphism

g

Right coKleisli morphism W(B) → C.

TYPE: Morphism

RETURNS DESCRIPTION
Morphism

Composed coKleisli morphism W(A) → C.

Source code in src/quivers/monadic/comonads.py
def cokleisli_compose(self, f: Morphism, g: Morphism) -> Morphism:
    """CoKleisli composition: f =>> g = g ∘ W(f) ∘ δ_A.

    For f: W(A) → B and g: W(B) → C, produces W(A) → C.

    Parameters
    ----------
    f : Morphism
        Left coKleisli morphism W(A) → B.
    g : Morphism
        Right coKleisli morphism W(B) → C.

    Returns
    -------
    Morphism
        Composed coKleisli morphism W(A) → C.
    """
    delta = self.comultiply(self.base_of(f.domain))
    wf = self.endofunctor.map_morphism(f)
    return delta >> wf >> g

base_of abstractmethod

base_of(wa: SetObject) -> SetObject

Recover A from an object of the form W(A).

PARAMETER DESCRIPTION
wa

An object W(A).

TYPE: SetObject

RETURNS DESCRIPTION
SetObject

The object A.

RAISES DESCRIPTION
ValueError

If wa is not of the form W(A).

Source code in src/quivers/monadic/comonads.py
@abstractmethod
def base_of(self, wa: SetObject) -> SetObject:
    """Recover ``A`` from an object of the form ``W(A)``.

    Parameters
    ----------
    wa : SetObject
        An object ``W(A)``.

    Returns
    -------
    SetObject
        The object ``A``.

    Raises
    ------
    ValueError
        If ``wa`` is not of the form ``W(A)``.
    """
    ...

CoKleisliCategory

CoKleisliCategory(comonad: Comonad)

The coKleisli category of a comonad.

Objects are the same as the base category. Morphisms A → B in the coKleisli category are morphisms W(A) → B in the base category.

PARAMETER DESCRIPTION
comonad

The underlying comonad.

TYPE: Comonad

Source code in src/quivers/monadic/comonads.py
def __init__(self, comonad: Comonad) -> None:
    self._comonad = comonad

comonad property

comonad: Comonad

The underlying comonad.

identity

identity(obj: SetObject) -> Morphism

CoKleisli identity at object A: ε_A: W(A) → A.

PARAMETER DESCRIPTION
obj

The object A.

TYPE: SetObject

RETURNS DESCRIPTION
Morphism

The coKleisli identity morphism.

Source code in src/quivers/monadic/comonads.py
def identity(self, obj: SetObject) -> Morphism:
    """CoKleisli identity at object A: ε_A: W(A) → A.

    Parameters
    ----------
    obj : SetObject
        The object A.

    Returns
    -------
    Morphism
        The coKleisli identity morphism.
    """
    return self._comonad.counit(obj)

compose

compose(f: Morphism, g: Morphism) -> Morphism

CoKleisli composition: f =>> g.

PARAMETER DESCRIPTION
f

Left morphism W(A) → B.

TYPE: Morphism

g

Right morphism W(B) → C.

TYPE: Morphism

RETURNS DESCRIPTION
Morphism

Composed morphism W(A) → C.

Source code in src/quivers/monadic/comonads.py
def compose(self, f: Morphism, g: Morphism) -> Morphism:
    """CoKleisli composition: f =>> g.

    Parameters
    ----------
    f : Morphism
        Left morphism W(A) → B.
    g : Morphism
        Right morphism W(B) → C.

    Returns
    -------
    Morphism
        Composed morphism W(A) → C.
    """
    return self._comonad.cokleisli_compose(f, g)

CofreeComonad

CofreeComonad(store: SetObject, algebra: Semiring)

Bases: Comonad

The product (environment) comonad W(A) = A × S.

This is the comonad of values in an environment S [Uustalu and Vene (2008)], and it is the cofree comonad on the constant functor at S. It is not the store (costate) comonad, which is S × (S → A).

ε_A: A × S → A is the first projection (extract the value). δ_A: A × S → (A × S) × S duplicates the environment component. W(f) = f × id_S.

Only the environment is copied, and morphisms act on it as the identity, so ε and δ are natural for every V-valued morphism, not only for functions.

PARAMETER DESCRIPTION
store

The environment object S.

TYPE: SetObject

algebra

The enrichment algebra; a semiring, so that the base category and the coKleisli category are categories.

TYPE: Semiring

RAISES DESCRIPTION
TypeError

If algebra is not a Semiring.

Source code in src/quivers/monadic/comonads.py
def __init__(self, store: SetObject, algebra: Semiring) -> None:
    if not isinstance(algebra, Semiring):
        raise TypeError(
            "CofreeComonad requires a Semiring algebra, so that its "
            f"coKleisli composition is associative; got {algebra!r}"
        )
    self._store = store
    self._algebra = algebra
    self._functor = _StoreFunctor(store)

store property

store: SetObject

The store object S.

algebra property

algebra: Algebra

The enrichment algebra.

endofunctor property

endofunctor: Functor

W(A) = A × S.

counit

counit(obj: SetObject) -> Morphism

ε_A: A × S → A is the first projection.

PARAMETER DESCRIPTION
obj

The object A.

TYPE: SetObject

RETURNS DESCRIPTION
ObservedMorphism

The extraction morphism.

Source code in src/quivers/monadic/comonads.py
def counit(self, obj: SetObject) -> Morphism:
    """ε_A: A × S → A is the first projection.

    Parameters
    ----------
    obj : SetObject
        The object A.

    Returns
    -------
    ObservedMorphism
        The extraction morphism.
    """
    source = ProductSet(components=(obj, self._store))
    data = torch.full((*source.shape, *obj.shape), self._algebra.zero)
    for a_idx in itertools.product(*(range(s) for s in obj.shape)):
        for s_idx in itertools.product(*(range(s) for s in self._store.shape)):
            data[a_idx + s_idx + a_idx] = self._algebra.unit
    return observed(source, obj, data, algebra=self._algebra)

comultiply

comultiply(obj: SetObject) -> Morphism

δ_A: A × S → (A × S) × S duplicates the store.

Maps (a, s) to ((a, s), s).

PARAMETER DESCRIPTION
obj

The object A.

TYPE: SetObject

RETURNS DESCRIPTION
ObservedMorphism

The comultiplication morphism.

Source code in src/quivers/monadic/comonads.py
def comultiply(self, obj: SetObject) -> Morphism:
    """δ_A: A × S → (A × S) × S duplicates the store.

    Maps (a, s) to ((a, s), s).

    Parameters
    ----------
    obj : SetObject
        The object A.

    Returns
    -------
    ObservedMorphism
        The comultiplication morphism.
    """
    source = ProductSet(components=(obj, self._store))
    target = ProductSet(components=(obj, self._store, self._store))
    data = torch.full((*source.shape, *target.shape), self._algebra.zero)
    for a_idx in itertools.product(*(range(s) for s in obj.shape)):
        for s_idx in itertools.product(*(range(s) for s in self._store.shape)):
            src = a_idx + s_idx
            tgt = a_idx + s_idx + s_idx
            data[src + tgt] = self._algebra.unit
    return observed(source, target, data, algebra=self._algebra)

base_of

base_of(wa: SetObject) -> SetObject

Recover A from W(A) = A × S.

PARAMETER DESCRIPTION
wa

An object A × S.

TYPE: SetObject

RETURNS DESCRIPTION
SetObject

The object A.

RAISES DESCRIPTION
ValueError

If wa is not a binary product whose second factor is the environment S.

Source code in src/quivers/monadic/comonads.py
def base_of(self, wa: SetObject) -> SetObject:
    """Recover ``A`` from ``W(A) = A × S``.

    Parameters
    ----------
    wa : SetObject
        An object ``A × S``.

    Returns
    -------
    SetObject
        The object ``A``.

    Raises
    ------
    ValueError
        If ``wa`` is not a binary product whose second factor is
        the environment ``S``.
    """
    if (
        isinstance(wa, ProductSet)
        and len(wa.components) == 2
        and wa.components[1] == self._store
    ):
        return wa.components[0]
    raise ValueError(
        f"CofreeComonad: {wa!r} is not of the form A × {self._store!r}"
    )

Cited sources

Saunders Mac Lane. Categories for the Working Mathematician. Volume 5 of Graduate Texts in Mathematics. Springer, 2 edition, 1998. URL: https://link.springer.com/book/10.1007/978-1-4757-4721-8, doi:10.1007/978-1-4757-4721-8.