definition example program

A -weighted graph is a Graph whose edges are labeled by elements of a Symmetric Monoidal Preorder . A -weighted graph (edges labeled by ) describes a city with one-way roads of given length/effort; a Hasse Diagram is a -weighted graph (edges weighted ; -edges are simply not drawn).

Sources: 7 Sketches §2.3.3 (Eqs. 2.56–2.60), §2.5.3, Exercises 2.58, 2.60, 2.62, 2.63, 2.105; footnote 4.

Presenting -categories

Just as a Hasse diagram presents a Preorder, a -weighted graph presents a Lawvere Metric Space on its vertex set: is the length of the shortest path from to . For the graph with edges , , , :

043
306
740

The graph matrix takes no thinking: on the diagonal, the edge weight where there is an edge, (, the “zero” of the Quantale) where there is none:

The distance matrix is obtained by repeated matrix multiplication in : records the shortest paths using edges and the powers stabilize (). In general, for any quantale , the hom-object of the presented -category is — e.g. union over paths of intersections of labels for (7S Exercise 2.62), or max over paths of min edge label for (7S Exercise 2.63).

Graph of Eq. (2.56) (, , , , ): and are computed in 7S Exercise 2.60, 7S Exercise 2.58, 7S Exercise 2.105.

Categorically this is the free -category on a -weighted graph — the -analogue of the Free Category on a graph — i.e. the left adjoint of the forgetful map from -categories to -weighted graphs.

Docs: ACSets API · Graphs

# Cost-weighted graph → distance matrix by min-plus powers
function graph_matrix(n, edges)   # edges: (src, tgt, weight)
  M = fill(Inf, n, n); for i in 1:n; M[i,i] = 0.0; end
  for (s, t, w) in edges; M[s,t] = min(M[s,t], w); end
  M
end
minplus(A, B) = [minimum(A[i,k] + B[k,j] for k in axes(A,2)) for i in axes(A,1), j in axes(B,2)]
function distances(M)
  D = M
  while true
    D2 = minplus(D, M)
    D2 == D && return D
    D = D2
  end
end
MY = graph_matrix(3, [(1,3,3.0), (1,2,4.0), (2,1,3.0), (3,2,4.0)])   # x=1, y=2, z=3
distances(MY)   # [0 4 3; 3 0 6; 7 4 0]

Catlab version (run in a fresh Julia session — Catlab exports its own compose, id, FinFunction, …):

# Catlab: weighted graphs as ACSets with an edge attribute
using Catlab
g = @acset WeightedGraph{Float64} begin
  V = 3; E = 4; src = [1,1,2,3]; tgt = [3,2,1,2]; weight = [3.0, 4.0, 3.0, 4.0]
end
-- Mathlib: `SimpleGraph` has `edist`/`dist` for unweighted graphs; weighted shortest paths
-- are the (min,+) closure; by hand:
def graphMatrix (n : ℕ) (w : Fin n → Fin n → ENNReal) : Matrix (Fin n) (Fin n) ENNReal :=
  fun i j => if i = j then 0 else w i j
-- min-plus closure of a weighted adjacency matrix (Floyd–Warshall)
type Mat = [[Double]]
minPlus :: Mat -> Mat -> Mat
minPlus a b = [ [ minimum (zipWith (+) row col) | col <- cols ] | row <- a ]
  where cols = foldr (zipWith (:)) (repeat []) b
 
distances :: Mat -> Mat
distances m = go m where go d = let d' = minPlus d m in if d' == d then d else go d'