#!/usr/bin/env python3
"""Generate integer directions for the 5-dimensional kissing problem.
Run: python search.py [--output DIRECTORY]
Requires Python 3, NumPy, and SciPy. Output is a candidate, not an optimality proof.
"""
import os
for key in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"):
    os.environ[key] = "1"

import argparse
import itertools
import json
import math
import platform
import time
from pathlib import Path

import numpy as np
import scipy
from scipy.optimize import minimize
from scipy.special import logsumexp

DIMENSION = 5
COUNT = 41
SCALE = 100_000_000
SEED = 574
EXTRA_STARTS = 48
ROWS, COLS = np.triu_indices(COUNT, 1)


def roots():
    result = []
    for i, j in itertools.combinations(range(DIMENSION), 2):
        for sign_i, sign_j in itertools.product((-1, 1), repeat=2):
            vector = [0] * DIMENSION
            vector[i], vector[j] = sign_i, sign_j
            result.append(vector)
    return np.array(result, dtype=float) / math.sqrt(2)


def normalize(vectors):
    return vectors / np.linalg.norm(vectors, axis=1, keepdims=True)


def smooth_search(points, schedule):
    """Minimize a smooth approximation to the largest inter-point dot product."""
    for beta, maxiter in schedule:
        def objective(flat):
            vectors = flat.reshape(COUNT, DIMENSION)
            lengths = np.linalg.norm(vectors, axis=1, keepdims=True)
            unit = vectors / lengths
            dots = (unit @ unit.T)[ROWS, COLS]
            normalizer = logsumexp(beta * dots)
            probs = np.exp(beta * dots - normalizer)
            weights = np.zeros((COUNT, COUNT))
            weights[ROWS, COLS] = probs
            weights[COLS, ROWS] = probs
            gradient = weights @ unit
            gradient -= (gradient * unit).sum(1, keepdims=True) * unit
            return normalizer / beta, (gradient / lengths).ravel()
        opt = minimize(objective, points.ravel(), jac=True, method="L-BFGS-B",
                       options={"maxiter": maxiter, "ftol": 1e-13})
        points = normalize(opt.x.reshape(COUNT, DIMENSION))
    return points


def measurements(points):
    rays = np.rint(points * SCALE).astype(np.int64).tolist()
    units = normalize(np.array(rays, dtype=float))
    dots = (units @ units.T)[ROWS, COLS]
    worst = int(np.argmax(dots))
    overlaps = 0
    for a, b in itertools.combinations(rays, 2):
        dot = sum(x * y for x, y in zip(a, b))
        norm_product = sum(x * x for x in a) * sum(y * y for y in b)
        if dot > 0 and 4 * dot * dot > norm_product:
            overlaps += 1
    return rays, {
        "minimum_angle_deg": math.degrees(math.acos(float(dots[worst]))),
        "overlapping_pairs": overlaps,
        "checked_pairs": len(dots),
        "worst_pair_one_based": [int(ROWS[worst]) + 1, int(COLS[worst]) + 1],
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=Path("."))
    directory = parser.parse_args().output
    directory.mkdir(parents=True, exist_ok=True)
    rng = np.random.default_rng(SEED)
    d5 = roots()
    baseline = [(40, 170), (160, 170), (700, 170)]
    deep = [(40, 200), (160, 220), (700, 270), (2400, 350), (9000, 450)]
    starts = []
    elite = []
    begin = time.perf_counter()
    for trial in range(6 + EXTRA_STARTS):
        if trial < 6:
            x = rng.normal(size=(COUNT, DIMENSION))
            source = "random normal"
            if trial % 2 == 0:
                x[:40] = d5 + rng.normal(scale=.09, size=(40, DIMENSION))
                source = "perturbed D5 plus one random point"
        elif trial % 4 == 0:
            x = rng.normal(size=(COUNT, DIMENSION))
            x[:40] = d5 + rng.normal(scale=.12, size=(40, DIMENSION))
            source = "perturbed D5 plus one random point"
        elif trial % 4 == 1:
            x = rng.normal(size=(COUNT, DIMENSION))
            source = "random normal"
        else:
            rank = int(rng.integers(len(elite)))
            angle, base_trial, base = elite[rank]
            x = base + rng.normal(scale=rng.choice([.02, .04, .075, .11]), size=base.shape)
            source = "perturbed trial " + str(base_trial)
        points = smooth_search(x, baseline if trial < 6 else deep)
        rays, stats = measurements(points)
        starts.append({"trial": trial, "start": source, **stats})
        elite.append((stats["minimum_angle_deg"], trial, points.copy()))
        elite.sort(key=lambda item: item[0], reverse=True)
        elite = elite[:5]
        if trial == 5 or trial == 53:
            print(f'Completed {trial+1} starts; best {elite[0][0]:.9f} degrees.', flush=True)
    winning_angle, winner, points = elite[0]
    directions, best = measurements(points)
    summary = {
        "seed": SEED, "starts": len(starts), "winning_trial": winner,
        "baseline_six_best_angle_deg": max(s["minimum_angle_deg"] for s in starts[:6]),
        **best, "runtime_seconds": round(time.perf_counter() - begin, 3),
        "python": platform.python_version(), "numpy": np.__version__, "scipy": scipy.__version__,
        "direction_scale": SCALE, "trials": starts
    }
    candidate = {"dimension": DIMENSION, "directions": directions,
                 "description": "Best of 54 starts in this search. Normalize each integer direction independently."}
    (directory / "candidate.json").write_text(json.dumps(candidate, separators=(",", ":")) + "\n")
    (directory / "search-summary.json").write_text(json.dumps(summary, indent=2) + "\n")


if __name__ == "__main__":
    main()
