""" Minimum enclosing circle of a point set """

from math import sqrt
from scipy.optimize import minimize
import matplotlib.pyplot as plt

x = [1.0, 3.0, 2.5, 4.0, 5.0, 6.0, 5.0]
y = [3.0, 1.0, 3.0, 6.0, 7.0, 7.0, 2.0]

trace = []

def dist(p, q):
    return sqrt((p[0]-q[0])**2 + (p[1]-q[1])**2)

def max_distance(c):
    trace.append(c)
    return max(dist(p, c) for p in zip(x, y))

c = minimize(max_distance, [0.0, 0.0], method="nelder-mead").x

ax = plt.gca()
ax.set_xlim((0, 8))
ax.set_ylim((0, 8))
ax.set_aspect("equal")
plt.plot(x, y, "g.")
plt.plot(*zip(*trace), "b.-")
ax.add_artist(plt.Circle(c, max_distance(c), color="r", fill=False))
plt.show()
