-
Notifications
You must be signed in to change notification settings - Fork 21
/
ParametricUtils.jl
409 lines (319 loc) · 11.1 KB
/
ParametricUtils.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
struct FlatVariables{T<:Real}
X::Vector{T}
idx::Dict{Symbol, UnitRange{Int}}
end
function FlatVariables(fg::AbstractDFG, varIds::Vector{Symbol})
index = 1
idx = Dict{Symbol, UnitRange{Int}}()
for vid = varIds
v = getVariable(fg, vid)
dims = getDimension(v)
idx[vid] = index:(index+dims-1)
index += dims
end
return FlatVariables(Vector{Float64}(undef, index-1), idx)
end
function Base.setindex!(flatVar::FlatVariables{T}, val::Vector{T}, vId::Symbol) where T<:Real
if length(val) == length(flatVar.idx[vId])
flatVar.X[flatVar.idx[vId]] .= val
else
error("array could not be broadcast to match destination")
end
end
function Base.getindex(flatVar::FlatVariables{T}, vId::Symbol) where T<:Real
return flatVar.X[flatVar.idx[vId]]
end
function _getParametricCov(Z::FunctorInferenceType)
error("$Z not supported, please use non-parametric or open an issue if it should be")
end
function _getParametricCov(Z::Normal)
meas = mean(Z)
σ = 1/std(Z)^2
return (Float64[meas;], reshape(Float64[σ;],1,1))
end
function _getParametricCov(Z::MvNormal)
meas = mean(Z)
iΣ = invcov(Z)
return (meas, iΣ)
end
"""
$SIGNATURES
Which field of a user factor type should be used for parametric inference (assumign Gaussian).
Notes
- Users should overload this method should their factor not default to `.Z<:ParametricType`
"""
function getParametricField(s::FunctorInferenceType)
# flat out assumption
s.Z
end
function _getParametricMeasurement(s::FunctorInferenceType)
Z = getParametricField(s)
return _getParametricCov(Z)
end
"""
$TYPEDEF
Internal parametric extension to [`CalcFactor`](@ref)
"""
struct _CalcFactorParametric{CF}
calcfactor!::CF
meanVal::Vector{Float64}
informationMat::Matrix{Float64}
end
# pass in residual for consolidation with nonparametric
# userdata is now at `cfp.cf.cachedata`
function (cfp::_CalcFactorParametric)(variables...)
# call the user function (be careful to call the new CalcFactor version only!!!)
res = zeros(length(cfp.meanVal))
cfp.calcfactor!(res, cfp.meanVal, variables...)
# 1/2*log(1/( sqrt(det(Σ)*(2pi)^k) )) ## k = dim(μ)
return 0.5 * (res' * cfp.informationMat * res)
end
# build the cost function
function _totalCost(fg::AbstractDFG,
flatvar,
X )
#
obj = 0
for fct in getFactors(fg)
cf = getFactorType(fct)
varOrder = getVariableOrder(fct)
Xparams = [view(X, flatvar.idx[varId]) for varId in varOrder]
meanval, covariance = _getParametricMeasurement(cf)
calcf_ = CalcFactor(cf, _getFMdThread(fct), 0,
1, (meanval,), Xparams)
#
# NOTE the inverse to informationMat
cfp! = _CalcFactorParametric(calcf_, meanval, covariance )
# call the user function
# retval = cfp!(Xparams...) # WHY DOES THIS NOT WORK WITH TwiceDifferentiable??
retval = cf(Xparams...) # DOES WORK
# 1/2*log(1/( sqrt(det(Σ)*(2pi)^k) )) ## k = dim(μ)
obj += 1/2*retval
end
return obj
end
"""
$SIGNATURES
Solve a Gaussian factor graph.
"""
function solveFactorGraphParametric(fg::AbstractDFG;
solvekey::Symbol=:parametric,
autodiff = :forward,
algorithm=BFGS,
algorithmkwargs=(), # add manifold to overwrite computed one
options = Optim.Options(allow_f_increases=true,
time_limit = 100,
# show_trace = true,
# show_every = 1,
))
#Other options
# options = Optim.Options(time_limit = 100,
# iterations = 1000,
# show_trace = true,
# show_every = 1,
# allow_f_increases=true,
# g_tol = 1e-6,
# )
varIds = listVariables(fg)
#TODO mabye remove sorting, just for convenience
sort!(varIds, lt=natural_lt)
flatvar = FlatVariables(fg, varIds)
for vId in varIds
flatvar[vId] = getVariableSolverData(fg, vId, solvekey).val[:,1]
end
initValues = flatvar.X
mc_mani = IIF.MixedCircular(fg, varIds)
alg = algorithm(;manifold=mc_mani, algorithmkwargs...)
# alg = algorithm(; algorithmkwargs...)
tdtotalCost = TwiceDifferentiable((x)->_totalCost(fg, flatvar, x), initValues, autodiff = autodiff)
result = optimize(tdtotalCost, initValues, alg, options)
rv = Optim.minimizer(result)
H = hessian!(tdtotalCost, rv)
Σ = pinv(H)
d = Dict{Symbol,NamedTuple{(:val, :cov),Tuple{Vector{Float64},Matrix{Float64}}}}()
for key in varIds
r = flatvar.idx[key]
push!(d,key=>(val=rv[r],cov=Σ[r,r]))
end
return d, result, flatvar.idx, Σ
end
#TODO maybe consolidate with solveFactorGraphParametric
#TODO WIP
```
$SIGNATURES
Solve for frontal values only with values in seprarators fixed
```
function solveConditionalsParametric(fg::AbstractDFG,
frontals::Vector{Symbol};
solvekey::Symbol=:parametric,
autodiff = :forward,
algorithm=BFGS,
algorithmkwargs=(), # add manifold to overwrite computed one
options = Optim.Options(allow_f_increases=true,
time_limit = 100,
# show_trace = true,
# show_every = 1,
))
varIds = listVariables(fg)
#TODO mabye remove sorting, just for convenience
sort!(varIds, lt=natural_lt)
separators = setdiff(varIds, frontals)
varIds = [frontals; separators]
flatvar = FlatVariables(fg, varIds)
for vId in varIds
flatvar[vId] = getVariableSolverData(fg, vId, solvekey).val[:,1]
end
initValues = flatvar.X
frontalsLength = sum(map(v->getDimension(getVariable(fg, v)), frontals))
# build variables for frontals and seperators
# fX = view(initValues, 1:frontalsLength)
fX = initValues[1:frontalsLength]
# sX = view(initValues, (frontalsLength+1):length(initValues))
sX = initValues[frontalsLength+1:end]
mc_mani = MixedCircular(fg, varIds)
alg = algorithm(;manifold=mc_mani, algorithmkwargs...)
tdtotalCost = TwiceDifferentiable((x)->_totalCost(fg, flatvar,x), initValues, autodiff = autodiff)
result = optimize((x)->_totalCost(fg, flatvar, [x;sX]), fX, alg, options)
# result = optimize(x->totalCost([x;sX]), fX, alg, options)
rv = Optim.minimizer(result)
H = hessian!(tdtotalCost, [rv; sX])
Σ = pinv(H)
d = Dict{Symbol,NamedTuple{(:val, :cov),Tuple{Vector{Float64},Matrix{Float64}}}}()
for key in frontals
r = flatvar.idx[key]
push!(d,key=>(val=rv[r],cov=Σ[r,r]))
end
return d, result, flatvar.idx, Σ
end
"""
$SIGNATURES
Get the indexes for labels in FlatVariables
"""
function collectIdx(varinds, labels)
idx = Int[]
for lbl in labels
append!(idx, varinds[lbl])
end
return idx
end
"""
$SIGNATURES
Calculate the marginal distribution for a clique over subsetVarIds.
"""
function calculateMarginalCliqueLikelihood(vardict, Σ, varindxs, subsetVarIds)
μₘ = Float64[]
for lbl in subsetVarIds
append!(μₘ, vardict[lbl].val)
end
Aidx = collectIdx(varindxs, subsetVarIds)
Σₘ = Σ[Aidx, Aidx]
return createMvNormal(μₘ, Σₘ)
end
"""
$SIGNATURES
"""
function calculateCoBeliefMessage(soldict, Σ, flatvars, separators, frontals)
Aidx = IIF.collectIdx(flatvars,separators)
Cidx = IIF.collectIdx(flatvars,frontals)
#marginalize separators
A = Σ[Aidx, Aidx]
#marginalize frontals
C = Σ[Cidx, Cidx]
# cross
B = Σ[Aidx, Cidx]
Σₘ = deepcopy(A)
if length(separators) == 0
return (varlbl=Symbol[], μ=Float64[], Σ=Matrix{Float64}(undef,0,0))
elseif length(separators) == 1
# create messages
return (varlbl = deepcopy(separators), μ = soldict[separators[1]].val, Σ = A)
elseif length(separators) == 2
A = Σₘ[1, 1]
C = Σₘ[2, 2]
B = Σₘ[1, 2]
#calculate covariance between separators
ΣA_B = A - B*inv(C)*B'
# create messages
m2lbl = deepcopy(separators)
m2cov = isa(ΣA_B, Matrix) ? ΣA_B : fill(ΣA_B,1,1)
m2val = soldict[m2lbl[2]].val - soldict[m2lbl[1]].val
return (varlbl = m2lbl, μ = m2val, Σ = m2cov)
else
error("Messages with more than 2 seperators are not supported yet")
end
end
"""
$SIGNATURES
Initialize the parametric solver data from a different solution in `fromkey`.
"""
function initParametricFrom(fg::AbstractDFG, fromkey::Symbol = :default; parkey::Symbol = :parametric)
for var in getVariables(fg)
#TODO only supports Normal now
# expand to MvNormal
fromvnd = getSolverData(var, fromkey)
if fromvnd.dims == 1
nf = fit(Normal, fromvnd.val)
getSolverData(var, parkey).val[1,1] = nf.μ
getSolverData(var, parkey).bw[1,1] = nf.σ
# @show nf
# m = var.estimateDict[:default].mean
else
#FIXME circular will not work correctly with MvNormal
nf = fit(MvNormal, fromvnd.val)
getSolverData(var, parkey).val[1:fromvnd.dims] .= mean(nf)[1:fromvnd.dims]
getSolverData(var, parkey).bw = cov(nf)
end
end
end
function updateVariablesFromParametricSolution!(fg::AbstractDFG, vardict)
for (v,val) in vardict
vnd = getVariableSolverData(fg, v, :parametric)
vnd.val .= val.val
if size(vnd.bw) != size(val.cov)
vnd.bw = val.cov
else
vnd.bw .= val.cov
end
end
end
"""
MixedCircular
Mixed Circular Manifold. Simple manifold for circular and cartesian mixed for use in optim
"""
struct MixedCircular <: Optim.Manifold
isCircular::BitArray
end
function MixedCircular(fg::AbstractDFG, varIds::Vector{Symbol})
circMask = Bool[]
for k = varIds
append!(circMask, getVariableType(fg, k) |> getManifolds .== :Circular)
end
MixedCircular(circMask)
end
function Optim.retract!(c::MixedCircular, x)
for (i,v) = enumerate(x)
c.isCircular[i] && (x[i] = rem2pi(v, RoundNearest))
end
return x
end
Optim.project_tangent!(S::MixedCircular,g,x) = g
function createMvNormal(val,cov)
#TODO do something better for properly formed covariance, but for now just a hack...FIXME
if all(diag(cov) .> 0.001) && isapprox(cov, transpose(cov), rtol=1e-4)
return MvNormal(val,Symmetric(cov))
else
@error("Covariance matrix error", cov)
# return nothing # FIXME, blanking nothing during #459 consolidation
return MvNormal(val, ones(length(val)))
end
end
function createMvNormal(v::DFGVariable, key=:parametric)
if key == :parametric
vnd = getSolverData(v, :parametric)
dims = vnd.dims
return createMvNormal(vnd.val[1:dims,1], vnd.bw[1:dims, 1:dims])
else
@warn "Trying MvNormal Fit, replace with PPE fits in future"
return fit(MvNormal,getSolverData(v, key).val)
end
end