import numpy as np
import cvxpy as cp


def compute_optimal_polynomial(eig_list,
                               deg,
                               ):
    """
    Compute the coefficients of the extremal polynomial

    Args:
        eig_list: (list of float) a discretization of \Lambda
        deg: (int) the degree of the polynomial we search

    Returns: (ndarray of floats) the coefficients of the extremal polynomial of degree deg: np.array([p_0, p_1, \cdots, p_{deg}])

    """

    # Define P a CVXPY variable corresponding to the ndarray of coefficients of the polynomial we search
    P = cp.Variable((deg+1))

    # Define the Vandermonde matrix to evaluate the polynomial of coefficient P on eig_list
    eigen_array = np.array(eig_list)
    V = np.array([eigen_array ** k for k in range(deg + 1)]).T

    # Maximize P(0) subject to supremum constraint over \Lambda
    prob = cp.Problem(objective=cp.Maximize(P[0]), constraints=[V@P <= 1, V@P >= -1])
    prob.solve(solver='SCS')

    # Return the list of all the coefficients of the over extremal polynomial
    return P.value
