-
Notifications
You must be signed in to change notification settings - Fork 0
/
gauss_newton.jl
249 lines (219 loc) Β· 8.47 KB
/
gauss_newton.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# # Reconstructions using Gauss-Newton method
# Here we give an example of reconstructing the conductivity by successive
# linearization
# ## Graph setup
# Define graph and graph Laplacian
using Plots, LinearAlgebra, Test, Random
β = kron
Nx = 10; Ny = 10; # number of nodes
x = (0:(Nx-1))*ones(1,Ny)/(Nx-1)
y = ones(Nx)*((0:(Ny-1))') /(Ny-1)
D(N) = [ (i+1==j) - (i==j) for i=1:N-1,j=1:N]
## Discrete gradient
β = [ I(Ny) β D(Nx) # horizontal edges
D(Ny) β I(Nx) # vertical edges
]
π = findall( (x[:].==0) .| (x[:].==1) .| (y[:].==0) .| (y[:].==1))
π = setdiff(1:Nx*Ny,π)
xπ = abs.(β)*x[:]/2; yπ = abs.(β)*y[:]/2 # edge centers
nπ =length(π); nπ = length(π);
nπ, nπ = size(β)
Rπ = I(nπ)[π,:] # restriction to interior nodes
Rπ = I(nπ)[π,:] # restriction to boundary nodes
indisk(c,r,x) = (x[1]-c[1])^2 + (x[2]-c[2])^2 <= r^2
Ο_true =
[ 1 + indisk((0.2,0.2),0.1,(x,y)) +
-0.5indisk((0.5,0.5),0.2,(x,y)) +
2indisk((0.75,0.6),0.2,(x,y))
for (x,y) β zip(xπ,yπ) ]
Ο0 = ones(nπ)
L(Ο) = β'*diagm(Ο)*β # Laplacian
# ## Boundary conditions and data
# The Dirichlet boundary conditions we use are similar to $x + y$ and $x-y$ in
# the continuum. They are on purpose not aligned with the grid edges, so that we
# do not end up with edges where there are no currents flowing.
fs = [x[π]+y[π] x[π]-y[π]]; N = size(fs,2)
## Dirichlet problem solve
function dirsolve(Ο,f)
u = zeros(nπ)
u[π] = f
u[π] = -L(Ο)[π,π]\(L(Ο)[π,π]*f)
return u
end
function state(Ο)
us = hcat([ dirsolve(Ο,f) for f β eachcol(fs)]...)
Hs = hcat([ Ο.*abs2.(β*u) for u β eachcol(us)]...)
return us,Hs
end
us_true, Hs_true = state(Ο_true) # true data
us0, Hs0 = state(Ο0); # data for a reference conductivity (constant)
# ## Plot conductivity
function plot_edge_quantity(f;lw=6,clims=extrema(f))
p = plot()
minf, maxf = clims
for (i, r) in enumerate(eachrow(β))
i1, i2 = findall(abs.(r) .> 0)
if (maxf-minf)/(maxf+minf) < 1e-6
c = "black"
else
c = get(cgrad(:thermal),(f[i]-minf)/(maxf-minf))
end
plot!(p,[x[i1], x[i2]], [y[i1], y[i2]], linecolor=c, lw=lw)
end
plot!(p,legend=:none, aspect_ratio=:equal, axis=false, grid=false)
return p
end
h2 = scatter([0,0], [0,1], zcolor=[0,1], clims=extrema(Ο_true),
xlims=(1,1.1), label="", c=:thermal, framestyle=:none)
l = @layout [ a b{0.1w} ]
p = plot(
plot_edge_quantity(Ο_true,lw=4), h2,
layout=l, size=(400,300)
)
# ## Plot voltages
clims = extrema(us_true)
p = plot(
heatmap(reshape(us_true[:,1],Nx,Ny),clims=clims),
heatmap(reshape(us_true[:,2],Nx,Ny),clims=clims),
layout=grid(1,2)
)
# ## Plot dissipated power
Hclims = extrema(Hs_true)
dpi=400; h=1*dpi; cw = h/4;
h2 = scatter([0,0], [0,1], zcolor=[0,1], clims=Hclims,
xlims=(1,1.1), label="", c=:thermal, framestyle=:none,
size=(cw,h),dpi=dpi)
l = @layout [ a b c{0.1w} ]
p1 = plot_edge_quantity(Hs_true[:,1],lw=4,clims=Hclims)
plot!(p1,size=(h,h),dpi=dpi)
p2 = plot_edge_quantity(Hs_true[:,2],lw=4,clims=Hclims)
plot!(p2,size=(h,h),dpi=dpi)
## output
savefig(h2,"dissipated_power_cbar.png")
savefig(p1,"dissipated_power1.png")
savefig(p2,"dissipated_power2.png")
plot(p1,p2,h2,layout=l, size=(700,300))
# ## Jacobian computation
## Forward problem and Jacobian for one measurement
β(Ο,u) = [ (L(Ο)*u)[π]
u[π] ]
β³(Ο,u) = Ο .* abs2.(β*u)
Dβ(Ο,u) = [
Rπ*β'*diagm(β*u) Rπ*L(Ο)
zeros(nπ,nπ) Rπ
]
Dβ³(Ο,u) = [ diagm(abs2.(β*u)) 2diagm(Ο .* (β*u))*β ];
## Assemble forward map
fwd(Ο,us) = [ vcat([β(Ο,u) for u β eachcol(us)]...)
vcat([β³(Ο,u) for u β eachcol(us)]...) ]
## Assemble rhs
rhs(fs,Hs) = [ vec([zeros(nπ,N); fs])
Hs[:] ]
## Assemble Jacobian and injectivity matrix for all boundary conditions
function jacobian(Ο,us)
N = size(us,2) # number of Dirichlet boundary conditions
Dβs = [ Dβ(Ο,u) for u β eachcol(us) ]
Dβ³s = [ Dβ³(Ο,u) for u β eachcol(us) ]
## Assemble full Jacobian
π = zeros(N*nπ+N*nπ,nπ+N*nπ)
for j=1:N
π[ (j-1)*nπ .+ (1:nπ) , 1:nπ ] = Dβs[j][:,1:nπ]
π[ N*nπ .+ (j-1)*nπ .+ (1:nπ) , 1:nπ ] = Dβ³s[j][:,1:nπ]
π[ (j-1)*nπ .+ (1:nπ) , nπ .+ (j-1)*nπ .+ (1:nπ) ] = Dβs[j][:,nπ .+ (1:nπ)]
π[ N*nπ .+ (j-1)*nπ .+ (1:nπ), nπ .+ (j-1)*nπ .+ (1:nπ) ] = Dβ³s[j][:,nπ .+ (1:nπ)]
end
return π
end;
# ## Gauss-Newton method
# Here we solve the optimization problem
# $$
# \min_x \| R(x) \|^2,
# $$
# where $R$ is the residual of a (nonlinear) system of equations describing the
# problem. The Gauss-Newton method consists of the update:
# $$
# x^{(n+1)} = x^{(n)} - (DR(x^{(n)})DR^T(x^{(n)}) + \alpha^2 I)^{-1} DR^T(x^{(n)}) R(x^{(n)}),
# $$
# where $DF(x)$ is the Jacobian of $F$ evaluated at $x$ and $|alpha$ is a
# regularization parameter. We add Armijo backtracking to avoid taking steps
# that are too large (based on the unregularized objective function)
function gauss_newton(R,DR,x0;
maxiter=100, # max number of GN iterations
tol=1e-4, # gradient tolerance
Ξ±=1e-3, # regularization parameter
btΞ±=1e-4, # SDC for backtracking
Ξ²=1/2, # Armijo factor
btmaxiter=100 # backtracking max iter
)
x = x0
objfun = []
f(x) = norm(R(x))^2 # objective function
for n=1:maxiter
J = DR(x)
r = R(x)
βf = 2J'*r
push!(objfun,f(x))
norm(βf) < tol && return x,objfun
dx = - (J'*J + Ξ±^2*I)\(J'*r) # GN direction
## backtracking line search
t = 1; k = 1
for k=1:btmaxiter
(f(x+t*dx)-f(x) < btΞ±*t*βf'*dx) && break
t*=Ξ²
(k==btmaxiter) && println("Warning: max backtracking limit hit")
end
x = x + t*dx
end
return x,objfun
end
# ## Setup data and residual
# We check numerically whether the Jacobian we calculate satisfies
# $$
# F(x + \epsilon \delta x) = F(x) + \epsilon DF(x)\delta x + \mathcal{O}(\epsilon^2).
# $$
# More concretely, if $\epsilon$ is too large, Taylor's theorem doesn't hold, if
# it is too small then we encounter problems with machine precision, so if
# divide the purportedly $\mathcal{O}(\epsilon^2)$ terrm by $\epsilon^2$ we
# should get something approximately constant (for values of $\epsilon$ that are
# neither too big or too small)
unpack(x) = (Ο=x[1:nπ],us=reshape(x[(nπ+1):end],nπ,N)) # go from x to Ο,us
pack(Ο,us) = vcat(Ο,vec(us)) # go from (Ο,us) to x
noiselevel = 5/100
Random.seed!(17) # initialize seed
R(x) = fwd(unpack(x)...) - rhs(fs,Hs_true)
Rnoisy(x) = fwd(unpack(x)...) - rhs(fs,Hs_true + maximum(Hs_true)*noiselevel*randn(size(Hs_true)))
DR(x) = jacobian(unpack(x)...)
## test Jacobian against Taylor's theorem
Ο΅s = 10.0 .^ (2:-0.5:-16)
jacobian_test(F,DF,x0,Ξ΄x) =
[ norm(F(x0 + Ο΅*Ξ΄x) - (F(x0) + Ο΅*DF(x0)*Ξ΄x))/Ο΅^2/norm(Ξ΄x) for Ο΅ β Ο΅s ]
plot(Ο΅s, jacobian_test(R,DR,pack(Ο_true,us_true),randn(nπ+N*nπ)),
scale=:log10,xlabel="Ο΅",ylabel="Taylor error (should be const)")
# ## Reconstructions with and without noise
X,objfun1=gauss_newton(R,DR,pack(Ο0,us0);Ξ±=1e-4,tol=1e-6,maxiter=50)
Οrec1,usrec1 = unpack(X)
X,objfun2=gauss_newton(Rnoisy,DR,pack(Ο0,us0);Ξ±=5e-3,tol=1e-6,maxiter=50)
Οrec2,usrec2 = unpack(X)
p1 = plot(objfun1,yscale=:log10,label="noiseless")
plot!(objfun2,title="objective function",label="noisy",xlabel="iteration")
p2 = plot(Οrec1,label="rec"); p2=plot!(Οrec2,label="noisy"); p2=plot!(Ο_true,label="true");
plot(p1,p2,layout=grid(1,2))
# ## Plot for paper
relerr(a,b) = norm(a-b)/norm(a)
println("relative error Οrec1 = ",100*relerr(Ο_true,Οrec1)," %")
println("relative error Οrec2 = ",100*relerr(Ο_true,Οrec2)," %")
clims = extrema([Οrec1;Οrec2])
l = @layout [ grid(1,2) a{0.1w} ]; dpi=400; h=1*dpi; cw = h/4;
## Colorbar
h2 = scatter([0,0], [0,1], zcolor=[0,1], clims=clims,
xlims=(1,1.1), label="", c=:thermal, framestyle=:none,
size=(cw,h),dpi=dpi)
p1 = plot_edge_quantity(Οrec1,lw=4,clims=clims)
plot!(p1,size=(h,h),dpi=dpi)
p2 = plot_edge_quantity(Οrec2,lw=4,clims=clims)
plot!(p2,size=(h,h),dpi=dpi)
## output
savefig(p1,"sigrec_noiseless.png")
savefig(p2,"sigrec_noisy.png")
savefig(h2,"sigrec_cbar.png")
p = plot(p1,p2,h2,layout=l,size=(700,300))