"""Read the finite-stage coloring factor from visits on a single tree.""" from bisect import bisect_right from itertools import combinations from diamond import depth, distance, normalize, tree_walks from folds import decode, field_x, stars, x def forbidden_pairs(word, stage): word = normalize(word) route, tree = decode(word) if depth(route, tree) > stage: raise ValueError("Diagram omitted at this stage") visits = [[] for _ in tree] for time, v in enumerate(route): visits[v].append(time) neighbors = stars(tree) forbidden = set() for v, incident in enumerate(neighbors): if len(incident) < 3: continue for z, times in enumerate(visits): if len(times) < 2 or distance(tree, v, z) != stage: continue gaps = [] for e in incident: near, far = tree[e+1], e+1 u = near+far-v if distance(tree, u, z) == stage+1: # All visits to this neighbor fall in the same cyclic z-gap. gap = bisect_right(times, visits[u][0]) % len(times) gaps.append((e, gap)) for (e, left), (f, right) in combinations(gaps, 2): if left != right: forbidden.add((e, f)) return forbidden def coloring_factor(word, stage): if not word: return field_x.one word = normalize(word) forbidden = forbidden_pairs(word, stage) _, tree = decode(word) value = x for incident in stars(tree): for j, f in enumerate(incident[1:], 1): value *= x-sum((e, f) not in forbidden for e in incident[:j]) return value if __name__ == "__main__": total = 0 for k in (8, 10, 12, 14): for word, route, tree in tree_walks(k): if depth(route, tree) > 2: continue found = set() for incident in stars(tree): for e, f in combinations(incident, 2): merged = normalize(tuple(e if a == f else a for a in word)) times, parent = decode(merged) if depth(times, parent) > 2: found.add((e, f)) assert found == forbidden_pairs(word, 2) total += 1 example = "abccbaabddba" assert coloring_factor(example, 2) == x*(x-1)**3 print("Cyclic-gap test agrees with every elementary fold in", total, "allowed walks in degrees 8, 10, 12 and 14 at stage 2.") print(example, "has coloring factor x*(x-1)^3.")