def _canonical(seq):
    """
    Rotates and flips a sequence into its minimal form.
    Useful for identifying node sequences that are identical except for starting point and direction.
    """
    def rotated(seq, i):
        return seq[i:] + seq[:i]
    def flipped(seq):
        return list(reversed(seq))
    candidates = []
    for i in range(len(seq)):
        for f in (flipped, lambda seq: seq):
            candidates.append(f(rotated(seq, i)))
    return tuple(min(candidates))