# python setup
import matplotlib.pyplot as plt
import numpy as np
import cvxpy as cvx
%matplotlib inline
def diff(n, k=1):
""" Construct kth order difference matrix with shape (n-k, n)
"""
D = np.diag(-1*np.ones(n)) + np.diag(np.ones(n-1),1)
D = D[:-1,:]
if k > 1:
return diff(n-1,k-1).dot(D)
else:
return D
# generate and plot data
np.random.seed(101)
n = 100
t = np.linspace(0, 2*np.pi, n)
y = np.sin(t)
y = y + np.random.randn(n)*.2
plt.figure()
plt.plot(y,'o')
plt.xlabel('time')
plt.ylabel('$y$: observed data')
<matplotlib.text.Text at 0x1071ca8d0>
# get second-order difference matrix
D = diff(n, 2)
rho = 1
# construct and solve problem
x = cvx.Variable(n)
cvx.Problem(cvx.Minimize(cvx.sum_squares(x-y)
+rho*cvx.sum_squares(D*x))).solve()
x = np.array(x.value).flatten()
plt.figure()
plt.plot(y,'o')
plt.plot(x,'g-')
[<matplotlib.lines.Line2D at 0x1070fad10>]
rho = 10
x = cvx.Variable(n)
cvx.Problem(cvx.Minimize(cvx.sum_squares(x-y) + rho*cvx.sum_squares(D*x))).solve()
x = np.array(x.value).flatten()
plt.figure()
plt.plot(y,'o')
plt.plot(x,'g-')
[<matplotlib.lines.Line2D at 0x107381950>]
rho = 1000
x = cvx.Variable(n)
cvx.Problem(cvx.Minimize(cvx.sum_squares(x-y) + rho*cvx.sum_squares(D*x))).solve()
x = np.array(x.value).flatten()
plt.figure()
plt.plot(y,'o')
plt.plot(x,'g-')
[<matplotlib.lines.Line2D at 0x10782b450>]