"""Continue the three inverse branches of w**3 - 3*w = z along based loops.

Run with Python 3. Each Newton correction starts on the branch at the
previous sample. Halving the path step tests whether a sheet was skipped.
"""

from cmath import exp
from math import pi, sqrt


def loop(center, steps):
    """Travel from zero, circle one branch value counterclockwise, return."""
    start = center - (0.3 if center > 0 else -0.3)
    stem = [start * j / steps for j in range(steps + 1)]
    circle = [center + (start - center) * exp(2j*pi*j/steps)
              for j in range(1, steps + 1)]
    return stem + circle + stem[-2::-1]


def continue_sheets(centers, steps):
    base = [-sqrt(3), 0.0, sqrt(3)]
    roots = [complex(root) for root in base]
    for center in centers:
        for z in loop(center, steps):
            for index, w in enumerate(roots):
                for _ in range(12):
                    correction = (w**3 - 3*w - z) / (3*w*w - 3)
                    w -= correction
                    if abs(correction) < 2e-14:
                        break
                assert abs(w**3 - 3*w - z) < 1e-12
                roots[index] = w
            assert min(abs(roots[i] - roots[j])
                       for i, j in ((0, 1), (0, 2), (1, 2))) > 0.4
    labels = [min(range(3), key=lambda j: abs(w - base[j])) for w in roots]
    assert all(abs(w - base[j]) < 1e-12 for w, j in zip(roots, labels))
    return [j + 1 for j in labels]


if __name__ == "__main__":
    controls = [((2,), [2, 1, 3]), ((-2,), [1, 3, 2]),
                ((2, -2), [3, 1, 2]), ((-2, 2), [2, 3, 1])]
    for centers, expected in controls:
        for steps in (64, 128, 256):
            assert continue_sheets(centers, steps) == expected
        print(f"Branch values in traversal order {centers}: "
              f"initial labels 1, 2, 3 end at {expected}")
