2019-02-28 Jeff Fessler, University of Michigan
using LinearAlgebra: Diagonal, svd
using Random: seed!
using Plots
include(ENV["HOME"] * "/l/g/teach/w19-598-opt/hw/auto/test/ncg_inv.jl")
using Distributions
s = (t) -> atan(4*(t-0.5)); # nonlinear function
seed!(1) # seed rng
M = 15
tm = sort(rand(M)) # M random sample locations
y = s.(tm) + 0.1 * randn(M); # noisy samples
t0 = LinRange(0, 1, 101) # fine sampling for showing curve
scatter(tm, y, color=:blue,
label="y", xlabel="t", ylabel="y", ylim=[-1.3, 1.3])
plot!(t0, s.(t0), color=:blue, label="s(t)", legend=:topleft)
deg = 3 # polynomial degree
Afun = (tt) -> [t.^i for t in tt, i in 0:deg] # matrix of monomials
A = Afun(tm) # M × 4 matrix
xh = A \ y # ordinary LS solution
plot!(t0, Afun(t0)*xh, line=:red, label="ordinary LS cubic fit")
yc = copy(y)
yc[12] = -0.5
#seed!(8)
#yc = s.(tm) + 0.2 * rand(Laplace(0,1), M)
xc = A \ yc # ordinary LS solution
scatter(tm, yc, color=:blue,
label="y", xlabel="t", ylabel="y", ylim=[-1.3, 1.3])
plot!(t0, s.(t0), color=:blue, label="s(t)", legend=:topleft)
plot!(t0, Afun(t0)*xc, line=:red, label="ordinary LS cubic fit")
delta = 0.01
dpot = (z,delta) -> z / (1 + abs(z)/delta) # Fair potential
xr,_ = ncg_inv([A], [v -> dpot.(v - yc,delta)], [1.], xc, niter=100)
plot!(t0, Afun(t0)*xr, line=:magenta, label="robust cubic fit")
#savefig("tmp.pdf")