"""The Mona Lisa TSP: Nagata's record tour, drawn as the continuous line it is. Data: tour.txt.gz is the 100,000 cities of mona-lisa100K.tsp (https://www.math.uwaterloo.ca/tsp/data/ml/mona-lisa100K.tsp) in the order of Nagata's tour (https://www.math.uwaterloo.ca/tsp/data/ml/tour/monalisa_5757191.tour), both from the Waterloo TSP pages the README cites. First line: the first city's coordinates; every later line: the step to the next city. The whole tour is kept; the figure checks it (100,000 distinct cities, rounded EUC_2D length 5,757,191) and then draws every STEP-th city in tour order, so the line is the tour seen at card resolution. """ import gzip import math from pathlib import Path import kit HERE = Path(__file__).resolve().parent STEP = 8 # every 8th city: 12,500 vertices, enough for the face at card size Q = 2 # path coordinates in half pixels, drawn at scale(1/Q), so the steps are small integers x = y = None pts = [] for line in gzip.open(HERE / 'tour.txt.gz', 'rt'): a, b = map(int, line.split()) x, y = (a, b) if x is None else (x + a, y + b) pts.append((x, y)) assert len(pts) == len(set(pts)) == 100_000 length = sum(int(math.hypot(p[0] - q[0], p[1] - q[1]) + 0.5) for p, q in zip(pts, pts[1:] + pts[:1])) assert length == 5_757_191, length xs, ys = [p[0] for p in pts], [p[1] for p in pts] x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys) h = 252 # canvas px for the picture's height s = h / (y1 - y0) ox = kit.W / 2 - (x1 - x0) * s / 2 # TSPLIB y grows upwards P = lambda p: (ox + (p[0] - x0) * s, 8 + (y1 - p[1]) * s) line = pts[::STEP] + pts[:1] q = [(round(a * Q), round(b * Q)) for a, b in map(P, line)] d = f'M{q[0][0]} {q[0][1]}l' + ' '.join(f'{b[0] - a[0]} {b[1] - a[1]}' for a, b in zip(q, q[1:])).replace(' -', '-') # ponytail: stroke 1 px, under the kit's 2, because the picture is line density; at 2 the portrait goes solid body = kit.path(d, 'ink2-s', 1 * Q, f' transform="scale({1 / Q:g})"') label = f'best tour, length {length:,} ยท every {STEP}th city drawn' kit.write(__file__, 'computer-science', body, label, f"Nagata's tour of the 100,000 Mona Lisa cities, length {length:,}, drawn through every {STEP}th city") print(label, len(line), 'vertices')