Indexed text attachment
verify-topology-learning.py
Source for Algebraic and Differential Topology in Machine Learning and AI: Obstructions, Invariants, and Counts
View paper · Download original file
Lines 524–623 of 1604. Source text is displayed literally.
524 525def mat_mul(A, B):526 if not A or not B:527 return [[0] * (len(B[0]) if B else 0) for _ in A]528 Bt = list(zip(*B))529 return [[sum(a * b for a, b in zip(r, c)) for c in Bt] for r in A]530 531 532def mat_eq(A, B):533 return all(list(r) == list(q) for r, q in zip(A, B)) and len(A) == len(B)534 535 536def mat_sub(A, B):537 return [[a - b for a, b in zip(r, q)] for r, q in zip(A, B)]538 539 540def trace(M):541 return sum(M[i][i] for i in range(min(len(M), len(M[0]) if M else 0)))542 543 544def nullspace(M, ncols):545 """rational basis of the kernel"""546 A = [[Fr(x) for x in r] for r in M]547 piv = []548 rk = 0549 for c in range(ncols):550 p = next((i for i in range(rk, len(A)) if A[i][c] != 0), None)551 if p is None:552 continue553 A[rk], A[p] = A[p], A[rk]554 A[rk] = [x / A[rk][c] for x in A[rk]]555 for i in range(len(A)):556 if i != rk and A[i][c] != 0:557 f = A[i][c]558 A[i] = [x - f * y for x, y in zip(A[i], A[rk])]559 piv.append(c)560 rk += 1561 free = [c for c in range(ncols) if c not in piv]562 basis = []563 for f in free:564 v = [Fr(0)] * ncols565 v[f] = Fr(1)566 for i, c in enumerate(piv):567 v[c] = -A[i][f]568 basis.append(v)569 return basis570 571 572def independent_extend(base, cands):573 """greedily pick vectors of cands independent modulo span(base); returns (reduced rows, picked)"""574 rows = []575 def reduce(v):576 v = list(v)577 for r, c in rows:578 if v[c] != 0:579 f = v[c] / r[c]580 v = [a - f * b for a, b in zip(v, r)]581 return v582 def add(v):583 v = reduce(v)584 c = next((i for i, a in enumerate(v) if a != 0), None)585 if c is None:586 return False587 rows.append((v, c))588 return True589 for b in base:590 add([Fr(x) for x in b])591 picked = []592 for v in cands:593 if add(v):594 picked.append(v)595 return picked596 597 598def solve_coords(cols, v):599 """coordinates of v in the independent family cols (exact)"""600 n = len(cols)601 m = len(v)602 A = [[Fr(cols[j][i]) for j in range(n)] + [Fr(v[i])] for i in range(m)]603 rk = 0604 piv = []605 for c in range(n):606 p = next((i for i in range(rk, m) if A[i][c] != 0), None)607 if p is None:608 return None609 A[rk], A[p] = A[p], A[rk]610 A[rk] = [x / A[rk][c] for x in A[rk]]611 for i in range(m):612 if i != rk and A[i][c] != 0:613 f = A[i][c]614 A[i] = [x - f * y for x, y in zip(A[i], A[rk])]615 piv.append(c)616 rk += 1617 if any(A[i][n] != 0 for i in range(rk, m)):618 return None619 return [A[i][n] for i in range(n)]620 621 622def homology_trace(K, vmap, d):623 """trace of the map induced on H_d(K; Q) by a simplicial self-map"""