import numpy as np
import cvxpy
import matplotlib.pyplot as plt
import code





if __name__=='__main__':
    d = 10

    # seed the RNG
    np.random.seed(1)

    # set a and y
    a = np.ones(d)
    y = 2*np.linspace(-1, 0, d)

    z = y/a

    # define the dual and derivative of dual
    L = lambda l: -0.5*np.sum(np.maximum(0, y-l*a)**2) - 0.5*np.sum(y*y) - l
    dL = lambda l: np.sum(a*np.maximum(0, y - l*a)) -1

    # calculate the x and y values for plot
    delta = 0.1
    lam = np.linspace(np.min(z) - delta, np.max(z)+delta, 1000)
    Lval = np.array([L(l) for l in lam])
    dLval = np.array([dL(l) for l in lam])
    Lzval = np.array([L(l) for l in z])

    #code.interact(local={**locals(), **globals()})

    # plot the graph
    f, axarr = plt.subplots(2, sharex=True)
    axarr[0].plot(lam, Lval)
    axarr[0].scatter(z, Lzval)
    axarr[0].set_ylabel(r'$L(\lambda)$')

    axarr[1].plot(lam, dLval)
    axarr[1].set_xlabel(r'$\lambda$')
    axarr[1].axhline(color='k')
    axarr[1].set_xlim(np.min(lam), np.max(lam))

    plt.savefig('daulexample.png')
    plt.show()






