-
Notifications
You must be signed in to change notification settings - Fork 21
/
CliqStateMachine.jl
1633 lines (1222 loc) · 52.4 KB
/
CliqStateMachine.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# clique state machine for tree based initialization and inference
# newer exports
export towardUpOrDwnSolve_StateMachine, checkIfCliqNullBlock_StateMachine, doAnyChildrenNeedDwn_StateMachine
export mustInitUpCliq_StateMachine, doCliqUpSolveInitialized_StateMachine
export rmUpLikeliSaveSubFg_StateMachine
"""
$SIGNATURES
Specialized info logger print function to show clique state machine information
in a standardized form.
"""
function infocsm(csmc::CliqStateMachineContainer, str::A) where {A <: AbstractString}
tm = string(Dates.now())
tmt = split(tm, 'T')[end]
lbl = getLabel(csmc.cliq)
lbl1 = split(lbl,',')[1]
cliqst = getCliqueStatus(csmc.cliq)
with_logger(csmc.logger) do
@info "$tmt | $(csmc.cliq.index)---$lbl1 @ $(cliqst) | "*str
end
flush(csmc.logger.stream)
nothing
end
"""
$SIGNATURES
Do cliq downward inference
Notes:
- State machine function nr. 11
"""
function doCliqDownSolve_StateMachine(csmc::CliqStateMachineContainer)
infocsm(csmc, "11, doCliqDownSolve_StateMachine")
setCliqDrawColor(csmc.cliq, "red")
opts = getSolverParams(csmc.dfg)
# get down msg from parent (assuming root clique CSM wont make it here)
# this looks like a pull model #674
prnt = getParent(csmc.tree, csmc.cliq)
dwnmsgs = fetchMsgDwnThis(prnt[1])
infocsm(csmc, "11, doCliqDownSolve_StateMachine -- dwnmsgs=$(collect(keys(dwnmsgs.belief)))")
# maybe cycle through separators (or better yet, just use values directly -- see next line)
msgfcts = addMsgFactors!(csmc.cliqSubFg, dwnmsgs, DownwardPass)
# force separator variables in cliqSubFg to adopt down message values
updateSubFgFromDownMsgs!(csmc.cliqSubFg, dwnmsgs, getCliqSeparatorVarIds(csmc.cliq))
# add required all frontal connected factors
if !opts.useMsgLikelihoods
newvars, newfcts = addDownVariableFactors!(csmc.dfg, csmc.cliqSubFg, csmc.cliq, csmc.logger, solvable=1)
end
# store the cliqSubFg for later debugging
if opts.dbg
DFG.saveDFG(csmc.cliqSubFg, joinpath(opts.logpath,"logs/cliq$(csmc.cliq.index)/fg_beforedownsolve"))
drawGraph(csmc.cliqSubFg, show=false, filepath=joinpath(opts.logpath,"logs/cliq$(csmc.cliq.index)/fg_beforedownsolve.pdf"))
end
## new way
# calculate belief on each of the frontal variables and iterate if required
solveCliqDownFrontalProducts!(csmc.cliqSubFg, csmc.cliq, opts, csmc.logger)
# compute new down messages
infocsm(csmc, "11, doCliqDownSolve_StateMachine -- going to set new down msgs.")
newDwnMsgs = getSetDownMessagesComplete!(csmc.cliqSubFg, csmc.cliq, dwnmsgs, csmc.logger)
#JT 459 putMsgDwnThis!(cliq, newDwnMsgs), DF still looks like a pull model here #674
putMsgDwnThis!(csmc.cliq.data, newDwnMsgs, from=:putMsgDwnThis!) # putCliqueMsgDown!
# update clique subgraph with new status
setCliqDrawColor(csmc.cliq, "lightblue")
csmc.dodownsolve = false
infocsm(csmc, "11, doCliqDownSolve_StateMachine -- finished with downGibbsCliqueDensity, now update csmc")
# go to 11b.
return cleanupAfterDownSolve_StateMachine
end
"""
$SIGNATURES
One of the last steps in CSM to clean up after a down solve.
Notes
- CSM function 11b.
"""
function cleanupAfterDownSolve_StateMachine(csmc::CliqStateMachineContainer)
# RECENT split from 11 (using #760 solution for deleteMsgFactors)
opts = getSolverParams(csmc.cliqSubFg)
# set PPE and solved for all frontals
for sym in getCliqFrontalVarIds(csmc.cliq)
# set PPE in cliqSubFg
setVariablePosteriorEstimates!(csmc.cliqSubFg, sym)
# set solved flag
vari = getVariable(csmc.cliqSubFg, sym)
setSolvedCount!(vari, getSolvedCount(vari, :default)+1, :default )
end
# store the cliqSubFg for later debugging
if opts.dbg
DFG.saveDFG(csmc.cliqSubFg, joinpath(opts.logpath,"logs/cliq$(csmc.cliq.index)/fg_afterdownsolve"))
drawGraph(csmc.cliqSubFg, show=false, filepath=joinpath(opts.logpath,"logs/cliq$(csmc.cliq.index)/fg_afterdownsolve.pdf"))
end
# transfer results to main factor graph
frsyms = getCliqFrontalVarIds(csmc.cliq)
infocsm(csmc, "11, finishingCliq -- going for transferUpdateSubGraph! on $frsyms")
transferUpdateSubGraph!(csmc.dfg, csmc.cliqSubFg, frsyms, csmc.logger, updatePPE=true)
infocsm(csmc, "11, doCliqDownSolve_StateMachine -- before notifyCliqDownInitStatus!")
notifyCliqDownInitStatus!(csmc.cliq, :downsolved, logger=csmc.logger)
infocsm(csmc, "11, doCliqDownSolve_StateMachine -- just notified notifyCliqDownInitStatus!")
# remove msg factors that were added to the subfg
rmFcts = lsf(csmc.cliqSubFg, tags=[:LIKELIHOODMESSAGE;]) .|> x -> getFactor(csmc.cliqSubFg, x)
infocsm(csmc, "11, doCliqDownSolve_StateMachine -- removing all up/dwn message factors, length=$(length(rmFcts))")
deleteMsgFactors!(csmc.cliqSubFg, rmFcts) # msgfcts # TODO, use tags=[:LIKELIHOODMESSAGE], see #760
infocsm(csmc, "11, doCliqDownSolve_StateMachine -- finished, exiting CSM on clique=$(csmc.cliq.index)")
# and finished
return IncrementalInference.exitStateMachine
end
"""
$SIGNATURES
Root clique upsolve and downsolve are equivalent, so skip a repeat downsolve, just set messages and just exit directly.
Notes
- State machine function nr. 10b
- Separate out during #459 dwnMsg consolidation.
DevNotes
- TODO should this consolidate some work with 11b?
"""
function specialCaseRootDownSolve_StateMachine(csmc::CliqStateMachineContainer)
# this is the root clique, so assume already downsolved -- only special case
dwnmsgs = getCliqDownMsgsAfterDownSolve(csmc.cliqSubFg, csmc.cliq)
setCliqDrawColor(csmc.cliq, "lightblue")
# this part looks like a pull model
# JT 459 putMsgDwnThis!(csmc.cliq, dwnmsgs)
putMsgDwnThis!(csmc.cliq.data, dwnmsgs, from=:putMsgDwnThis!) # putCliqueMsgDown!
setCliqueStatus!(csmc.cliq, :downsolved)
csmc.dodownsolve = false
# Update estimates and transfer back to the graph
frsyms = getCliqFrontalVarIds(csmc.cliq)
# set PPE and solved for all frontals
for sym in frsyms
# set PPE in cliqSubFg
setVariablePosteriorEstimates!(csmc.cliqSubFg, sym)
# set solved flag
vari = getVariable(csmc.cliqSubFg, sym)
setSolvedCount!(vari, getSolvedCount(vari, :default)+1, :default )
end
# Transfer to parent graph
transferUpdateSubGraph!(csmc.dfg, csmc.cliqSubFg, frsyms, updatePPE=true)
notifyCliqDownInitStatus!(csmc.cliq, :downsolved, logger=csmc.logger)
# bye
return IncrementalInference.exitStateMachine
end
"""
$SIGNATURES
Direct state machine to continue with downward solve or exit.
Notes
- State machine function nr. 10
"""
function canCliqDownSolve_StateMachine(csmc::CliqStateMachineContainer)
infocsm(csmc, "10, canCliqDownSolve_StateMachine, csmc.dodownsolve=$(csmc.dodownsolve).")
# finished and exit downsolve
if !csmc.dodownsolve
infocsm(csmc, "10, canCliqDownSolve_StateMachine -- shortcut exit since downsolve not required.")
return IncrementalInference.exitStateMachine
end
# assume separate down solve via solveCliq! call, but need a csmc.cliqSubFg
# could be dedicated downsolve that was skipped during previous upsolve only call
# e.g. federated solving case (or debug)
if length(ls(csmc.cliqSubFg)) == 0
# first need to fetch cliq sub graph
infocsm(csmc, "10, canCliqDownSolve_StateMachine, oops no cliqSubFg detected, lets go fetch a copy first.")
# go to 2b
return buildCliqSubgraphForDown_StateMachine
end
# both parent or otherwise might start by immediately doing downsolve, so likely need cliqSubFg in both cases
# e.g. federated solving case (or debug)
prnt = getParent(csmc.tree, csmc.cliq)
if 0 == length(prnt) # check if have parent
# go to 10b
return specialCaseRootDownSolve_StateMachine
end
# go to 10a
return somebodyLovesMe_StateMachine
end
"""
$SIGNATURES
Need description for this???
Notes
- State machine function nr.9
"""
function finishCliqSolveCheck_StateMachine(csmc::CliqStateMachineContainer)
cliqst = getCliqueStatus(csmc.cliq)
infocsm(csmc, "9, finishCliqSolveCheck_StateMachine")
if cliqst == :upsolved
frsyms = getCliqFrontalVarIds(csmc.cliq)
infocsm(csmc, "9, finishCliqSolveCheck_StateMachine -- going for transferUpdateSubGraph! on $frsyms")
# TODO what about down solve??
transferUpdateSubGraph!(csmc.dfg, csmc.cliqSubFg, frsyms, csmc.logger, updatePPE=false)
# remove any solvable upward cached data -- TODO will have to be changed for long down partial chains
# assuming maximally complte up solved cliq at this point
lockUpStatus!(csmc.cliq, csmc.cliq.index, true, csmc.logger, true, "9.finishCliqSolveCheck")
sdims = Dict{Symbol,Float64}()
for varid in getCliqAllVarIds(csmc.cliq)
sdims[varid] = 0.0
end
updateCliqSolvableDims!(csmc.cliq, sdims, csmc.logger)
unlockUpStatus!(csmc.cliq)
# go to 10
return canCliqDownSolve_StateMachine # IncrementalInference.exitStateMachine
elseif cliqst == :initialized
setCliqDrawColor(csmc.cliq, "sienna")
# go to 7
return determineCliqNeedDownMsg_StateMachine
else
infocsm(csmc, "9, finishCliqSolveCheck_StateMachine -- init not complete and should wait on init down message.")
setCliqDrawColor(csmc.cliq, "coral")
# TODO, potential problem with trying to downsolve
# return canCliqMargSkipUpSolve_StateMachine
end
# go to 4b (redirected here during #459 dwnMsg effort)
return trafficRedirectConsolidate459_StateMachine
# # go to 4
# return canCliqMargSkipUpSolve_StateMachine # whileCliqNotSolved_StateMachine
end
"""
$SIGNATURES
Do up initialization calculations, loosely translates to solving Chapman-Kolmogorov
transit integral in upward direction.
Notes
- State machine function nr. 8f
- Includes initialization routines.
- Adds LIKELIHOODMESSAGE factors but does not remove.
- gets msg likelihoods from cliqSubFg, see #760
DevNotes
- TODO: Make multi-core
"""
function mustInitUpCliq_StateMachine(csmc::CliqStateMachineContainer)
setCliqDrawColor(csmc.cliq, "green")
# check if init is required and possible
infocsm(csmc, "8f, mustInitUpCliq_StateMachine -- going for doCliqAutoInitUpPart1!.")
# get incoming clique up messages
upmsgs = getMsgsUpInitChildren(csmc, skip=[csmc.cliq.index;]) # FIXME, post #459 calls?
# remove all lingering upmessage likelihoods
oldTags = lsf(csmc.cliqSubFg, tags=[:LIKELIHOODMESSAGE;])
0 < length(oldTags) ? @warn("stale LIKELIHOODMESSAGE tags present in mustInitUpCliq_StateMachine") : nothing
oldFcts = oldTags .|> x->getFactor(csmc.cliqSubFg, x)
# add incoming up messages as priors to subfg
infocsm(csmc, "8f, mustInitUpCliq_StateMachine -- adding up message factors")
deleteMsgFactors!(csmc.cliqSubFg, oldFcts)
# interally adds :LIKELIHOODMESSAGE, :UPWARD_DIFFERENTIAL, :UPWARD_COMMON to each of the factors
msgfcts = addMsgFactors!(csmc.cliqSubFg, upmsgs, UpwardPass)
# store the cliqSubFg for later debugging
opts = getSolverParams(csmc.dfg)
if opts.dbg
DFG.saveDFG(csmc.cliqSubFg, joinpath(opts.logpath,"logs/cliq$(csmc.cliq.index)/fg_beforeupsolve"))
drawGraph(csmc.cliqSubFg, show=false, filepath=joinpath(opts.logpath,"logs/cliq$(csmc.cliq.index)/fg_beforeupsolve.pdf"))
end
# attempt initialize if necessary
if !areCliqVariablesAllInitialized(csmc.cliqSubFg, csmc.cliq)
# structure for all up message densities computed during this initialization procedure.
varorder = getCliqVarInitOrderUp(csmc.tree, csmc.cliq)
cycleInitByVarOrder!(csmc.cliqSubFg, varorder, logger=csmc.logger)
# is clique fully upsolved or only partially?
# print out the partial init status of all vars in clique
printCliqInitPartialInfo(csmc.cliqSubFg, csmc.cliq, csmc.logger)
end
# check again if all cliq vars have been initialized so that full inference can occur on clique
if areCliqVariablesAllInitialized(csmc.cliqSubFg, csmc.cliq)
infocsm(csmc, "8f, mustInitUpCliq_StateMachine -- all initialized")
# go to 8g.
return doCliqUpSolveInitialized_StateMachine
else
infocsm(csmc, "8f, mustInitUpCliq_StateMachine -- not able to init all")
# TODO Simplify this
status = getCliqueStatus(csmc.cliq)
status = (status == :initialized || length(getParent(csmc.tree, csmc.cliq)) == 0) ? status : :needdownmsg
# notify of results (big part of #459 consolidation effort)
prepPutCliqueStatusMsgUp!(csmc, status)
# go to 8h
return rmUpLikeliSaveSubFg_StateMachine
end
end
"""
$SIGNATURES
Find upward Chapman-Kolmogorov transit integral solution (approximation).
Notes
- State machine function nr. 8g
- Assumes LIKELIHOODMESSAGE factors are in csmc.cliqSubFg but does not remove them.
- TODO: Make multi-core
DevNotes
- NEEDS DFG v0.8.1, see IIF #760
"""
function doCliqUpSolveInitialized_StateMachine(csmc::CliqStateMachineContainer)
# check if all cliq vars have been initialized so that full inference can occur on clique
status = getCliqueStatus(csmc.cliq)
infocsm(csmc, "8g, doCliqUpSolveInitialized_StateMachine -- clique status = $(status)")
setCliqDrawColor(csmc.cliq, "red")
# get Dict{Symbol, TreeBelief} of all updated variables in csmc.cliqSubFg
retdict = approxCliqMarginalUp!(csmc, logger=csmc.logger)
# set clique color accordingly, using local memory
updateFGBT!(csmc.cliqSubFg, csmc.cliq, retdict, dbg=getSolverParams(csmc.cliqSubFg).dbg, logger=csmc.logger) # urt
setCliqDrawColor(csmc.cliq, isCliqFullDim(csmc.cliqSubFg, csmc.cliq) ? "pink" : "tomato1")
# notify of results (part of #459 consolidation effort)
getCliqueData(csmc.cliq).upsolved = true
status = :upsolved
# Send upward message, NOTE consolidation WIP #459
infocsm(csmc, "8g, doCliqUpSolveInitialized_StateMachine -- setting up messages with status = $(status)")
prepPutCliqueStatusMsgUp!(csmc, status)
# go to 8h
return rmUpLikeliSaveSubFg_StateMachine
end
"""
$SIGNATURES
Close out up solve attempt by removing any LIKELIHOODMESSAGE and save a debug cliqSubFg.
Notes
- State machine function nr. 8h
- Assumes LIKELIHOODMESSAGE factors are in csmc.cliqSubFg and also removes them.
- TODO: Make multi-core
DevNotes
- NEEDS DFG v0.8.1, see IIF #760
"""
function rmUpLikeliSaveSubFg_StateMachine(csmc::CliqStateMachineContainer)
#
status = getCliqueStatus(csmc.cliq)
# remove msg factors that were added to the subfg
tags__ = getSolverParams(csmc.cliqSubFg).useMsgLikelihoods ? [:UPWARD_COMMON;] : [:LIKELIHOODMESSAGE;]
msgfcts = lsf(csmc.cliqSubFg, tags=tags__) .|> x->getFactor(csmc.cliqSubFg, x)
infocsm(csmc, "8g, doCliqUpsSolveInit.! -- status = $(status), removing $(tags__) factors, length=$(length(msgfcts))")
deleteMsgFactors!(csmc.cliqSubFg, msgfcts)
# store the cliqSubFg for later debugging
opts = getSolverParams(csmc.dfg)
if opts.dbg
DFG.saveDFG(csmc.cliqSubFg, joinpath(opts.logpath,"logs/cliq$(csmc.cliq.index)/fg_afterupsolve"))
drawGraph(csmc.cliqSubFg, show=false, filepath=joinpath(opts.logpath,"logs/cliq$(csmc.cliq.index)/fg_afterupsolve.pdf"))
end
# go to 9
return finishCliqSolveCheck_StateMachine
end
"""
$SIGNATURES
WIP to resolve 459 dwnMsg consolidation. This is partly doing some kind of downsolve but seems out of place.
Notes
- State machine function nr. 10a
DevNotes
- FIXME, resolve/consolidate whatever is going on here
"""
function somebodyLovesMe_StateMachine(csmc::CliqStateMachineContainer)
infocsm(csmc, "10a, canCliqDownSolve_StateMachine, going to block on parent.")
prnt = getParent(csmc.tree, csmc.cliq)
# block here until parent is downsolved
setCliqDrawColor(csmc.cliq, "turquoise")
# this part is a pull model #674
while fetchMsgDwnInit(prnt[1]).status != :downsolved
wait(getSolveCondition(prnt[1]))
end
# blockMsgDwnUntilStatus(prnt[1], :downsolved)
# blockCliqUntilParentDownSolved(, logger=csmc.logger)
# yes, continue with downsolve
prntst = getCliqueStatus(prnt[1])
infocsm(csmc, "10a, somebodyLovesMe_StateMachine, parent status=$prntst.")
if prntst != :downsolved
infocsm(csmc, "10a, somebodyLovesMe_StateMachine, going around again.")
return canCliqDownSolve_StateMachine
end
infocsm(csmc, "10a, somebodyLovesMe_StateMachine, going for down solve.")
# go to 11
return doCliqDownSolve_StateMachine
end
"""
$SIGNATURES
Nedd description for this???
Notes
- State machine function nr. 8c
DevNotes
- Must consolidate as part of #459
"""
function waitChangeOnParentCondition_StateMachine(csmc::CliqStateMachineContainer)
#
setCliqDrawColor(csmc.cliq, "coral")
prnt = getParent(csmc.tree, csmc.cliq)
if length(prnt) > 0
infocsm(csmc, "8c, waitChangeOnParentCondition_StateMachine, wait on parent=$(prnt[1].index) for condition notify.")
@sync begin
@async begin
sleep(1)
notify(getSolveCondition(prnt[1]))
end
# wait but don't clear what is in the Condition (guess)
wait(getSolveCondition(prnt[1]))
end
else
infocsm(csmc, "8c, waitChangeOnParentCondition_StateMachine, cannot wait on parent for condition notify.")
@warn "no parent!"
end
# go to 4b
return trafficRedirectConsolidate459_StateMachine
# # go to 4
# return canCliqMargSkipUpSolve_StateMachine
end
"""
$SIGNATURES
WIP #459 dwnMsg consolidation towards blocking cliq that `:needdwninit` to wait on parent `:initialized` dwn message.
Notes
- State machine function nr.6e
DevNotes
- Seems really unnecessary
- Separated out during #459 dwnMsg consolidation
- Should only happen in long downinit chains below parent that needed dwninit
- TODO figure out whats different between this and 8c
"""
function slowOnPrntAsChildrNeedDwn_StateMachine(csmc::CliqStateMachineContainer)
# do actual fetch
prtmsg = fetchMsgDwnInit(getParent(csmc.tree, csmc.cliq)[1]).status
if prtmsg == :initialized
# FIXME what does this mean???
# probably that downward init should commence (not complete final solve)
allneeddwn = true
# go to 8e.ii
# return attemptDownInit_StateMachine
end
# FIXME WHY THIS???
# go to 7
return determineCliqNeedDownMsg_StateMachine
end
"""
$SIGNATURES
Decide whether to pursue and upward or downward solve with present state.
Notes
- State machine function nr. 7c
"""
function towardUpOrDwnSolve_StateMachine(csmc::CliqStateMachineContainer)
sleep(0.1) # FIXME remove after #459 resolved
# return doCliqInferAttempt_StateMachine
cliqst = getCliqueStatus(csmc.cliq)
infocsm(csmc, "7c, status=$(cliqst), before picking direction")
# d1,d2,cliqst = doCliqInitUpOrDown!(csmc.cliqSubFg, csmc.tree, csmc.cliq, isprntnddw)
if cliqst == :needdownmsg && !isCliqParentNeedDownMsg(csmc.tree, csmc.cliq, csmc.logger)
# FIXME, end 459, was collectDwnInitMsgFromParent_StateMachine but 674 requires pull model
# go to 8c
# notifyCSMCondition(csmc.cliq)
# return waitChangeOnParentCondition_StateMachine
# go to 8a
return collectDwnInitMsgFromParent_StateMachine
# HALF DUPLICATED IN STEP 4
elseif cliqst == :marginalized
# go to 1
return isCliqUpSolved_StateMachine
end
# go to 8b
return attemptCliqInitUp_StateMachine
end
"""
$SIGNATURES
Quick redirection of out-marginalized cliques to downsolve path, or wait on children cliques to get a csm status.
Notes
- State machine function nr.4
"""
function canCliqMargSkipUpSolve_StateMachine(csmc::CliqStateMachineContainer)
cliqst = getCliqueStatus(csmc.oldcliqdata)
infocsm(csmc, "4, canCliqMargSkipUpSolve_StateMachine, $cliqst, csmc.incremental=$(csmc.incremental)")
# if clique is out-marginalized, then no reason to continue with upsolve
# marginalized state is set in `testCliqCanRecycled_StateMachine`
if cliqst == :marginalized
# go to 10 -- Add case for IIF issue #474
return canCliqDownSolve_StateMachine
end
# go to 4e
return blockUntilChildrenHaveStatus_StateMachine
end
"""
$SIGNATURES
Do down solve calculations, loosely translates to solving Chapman-Kolmogorov
transit integral in downward direction.
Notes
- State machine function nr. 8e.ii.
- Follows routines in 8c.
- Pretty major repeat of functionality, FIXME
- TODO: Make multi-core
Initialization requires down message passing of more specialized down init msgs.
This function performs any possible initialization of variables and retriggers
children cliques that have not yet initialized.
Notes:
- Assumed this function is only called after status from child clique up inits completed.
- Assumes cliq has parent.
- will fetch message from parent
- Will perform down initialization if status == `:needdownmsg`.
- might be necessary to pass furhter down messges to child cliques that also `:needdownmsg`.
- Will not complete cliq solve unless all children are `:upsolved` (upward is priority).
- `dwinmsgs` assumed to come from parent initialization process.
- assume `subfg` as a subgraph that can be modified by this function (add message factors)
- should remove message prior factors from subgraph before returning.
- May modify `cliq` values.
- `putMsgUpInit!(cliq, msg)`
- `setCliqueStatus!(cliq, status)`
- `setCliqDrawColor(cliq, "sienna")`
- `notifyCliqDownInitStatus!(cliq, status)`
Algorithm:
- determine which downward messages influence initialization order
- initialize from singletons to most connected non-singletons
- revert back to needdownmsg if cycleInit does nothing
- can only ever return :initialized or :needdownmsg status
DevNotes
- TODO Lots of cleanup required, especially from calling function.
- TODO move directly into a CSM state function
"""
function attemptDownInit_StateMachine(csmc::CliqStateMachineContainer)
setCliqDrawColor(csmc.cliq, "green")
opt = getSolverParams(csmc.cliqSubFg)
dwnkeys_ = lsf(csmc.cliqSubFg, tags=[:DOWNWARD_COMMON;]) .|> x->ls(csmc.cliqSubFg, x)[1]
## TODO deal with partial inits only, either delay or continue at end...
# find intersect between downinitmsgs and local clique variables
# if only partials available, then
infocsm(csmc, "8e.ii, attemptDownInit_StateMachine, do cliq init down dwinmsgs=$(dwnkeys_)")
# get down variable initialization order
initorder = getCliqInitVarOrderDown(csmc.cliqSubFg, csmc.cliq, dwnkeys_)
infocsm(csmc, "8e.ii, attemptDownInit_StateMachine, initorder=$(initorder)")
# store the cliqSubFg for later debugging
if opt.dbg
DFG.saveDFG(csmc.cliqSubFg, joinpath(opt.logpath,"logs/cliq$(csmc.cliq.index)/fg_beforedowninit"))
end
# cycle through vars and attempt init
infocsm(csmc, "8e.ii, attemptDownInit_StateMachine, cycle through vars and attempt init")
cliqst = :needdownmsg
if cycleInitByVarOrder!(csmc.cliqSubFg, initorder)
cliqst = :initialized
end
infocsm(csmc, "8e.ii, attemptDownInit_StateMachine, current status: $cliqst")
# store the cliqSubFg for later debugging
if opt.dbg
DFG.saveDFG(csmc.cliqSubFg, joinpath(opt.logpath,"logs/cliq$(csmc.cliq.index)/fg_afterdowninit"))
end
# TODO: transfer values changed in the cliques should be transfered to the tree in proc 1 here.
# # TODO: is status of notify required here?
setCliqueStatus!(csmc.cliq, cliqst)
# go to 8l
return rmMsgLikelihoodsAfterDwn_StateMachine
end
"""
$SIGNATURES
Remove any `:LIKELIHOODMESSAGE` from `cliqSubFg`.
Notes
- State machine function nr.8l
"""
function rmMsgLikelihoodsAfterDwn_StateMachine(csmc::CliqStateMachineContainer)
## TODO only remove :DOWNWARD_COMMON messages here
#
## FIXME move this to separate state in CSM.
# remove all message factors
# remove msg factors previously added
fctstorm = ls(csmc.cliqSubFg, tags=[:LIKELIHOODMESSAGE;])
infocsm(csmc, "8e.ii., attemptDownInit_StateMachine, removing factors $fctstorm")
rmfcts = fctstorm .|> x->getFactor(csmc.cliqSubFg, x)
deleteMsgFactors!(csmc.cliqSubFg, rmfcts )
# go to 8d
return decideUpMsgOrInit_StateMachine
end
"""
$SIGNATURES
Blocking until all children of the clique's parent (i.e. siblings) have a valid status.
Notes
- State machine function nr. 5
"""
function blockUntilSiblingsStatus_StateMachine(csmc::CliqStateMachineContainer)
infocsm(csmc, "5, blocking on parent until all sibling cliques have valid status")
setCliqDrawColor(csmc.cliq, "blueviolet")
cliqst = getCliqueStatus(csmc.cliq)
infocsm(csmc, "5, block on siblings")
prnt = getParent(csmc.tree, csmc.cliq)
if length(prnt) > 0
infocsm(csmc, "5, has parent clique=$(prnt[1].index)")
ret = fetchChildrenStatusUp(csmc.tree, prnt[1], csmc.logger)
infocsm(csmc,"prnt $(prnt[1].index), fetched all, keys=$(keys(ret)).")
end
infocsm(csmc, "5, finishing")
# go to 6c
return doesParentNeedDwn_StateMachine
end
"""
$SIGNATURES
Delay loop if waiting on upsolves to complete.
Notes
- State machine 7b
- Also has "recursion", to come back to this function to make sure that child clique updates are in fact upsolved.
- Differs from 4e in that here children must be "upsolved" or equivalent to continue.
"""
function slowIfChildrenNotUpSolved_StateMachine(csmc::CliqStateMachineContainer)
# childs = getChildren(csmc.tree, csmc.cliq)
# len = length(childs)
@inbounds for chld in getChildren(csmc.tree, csmc.cliq)
chst = getCliqueStatus(chld)
if !(chst in [:upsolved;:uprecycled;:marginalized])
infocsm(csmc, "7b, slowIfChildrenNotUpSolved_StateMachine, wait condition on upsolve, cliq=$(chld.index), ch_lbl=$(getCliqFrontalVarIds(chld)[1]).")
# wait for child clique status/msg to be updated
wait(getSolveCondition(chld))
# check again and reroute if :needdownmsg
# chst = getCliqueStatus(chld)
# if chst == :needdownmsg
# return prntPrepDwnInitMsg_StateMachine
# end
end
end
# go to 4b
return trafficRedirectConsolidate459_StateMachine
end
# """
# $SIGNATURES
# New function in 459 dwnMsg init for when child clique needdowninit msg.
# Notes
# - State machine function nr. 7d
# DevNotes
# - "Parent" must do work from (pre-#459) `collectDwnInitMsgFromParent_StateMachine`.
# """
# function prntPrepDwnInitMsg_StateMachine(csmc::CliqStateMachineContainer)
# @warn("prntPrepDwnInitMsg_StateMachine -- WIP")
# infocsm(csmc, "prntPrepDwnInitMsg_StateMachine -- WIP")
# # TEMP go to 7b
# return slowIfChildrenNotUpSolved_StateMachine
# end
"""
$SIGNATURES
Block until all children have a csm status, using `fetch---Condition` model.
Notes
- State machine function nr.4e
"""
function blockUntilChildrenHaveStatus_StateMachine(csmc::CliqStateMachineContainer)
#must happen before if :null
stdict = fetchChildrenStatusUp(csmc.tree, csmc.cliq, csmc.logger)
infocsm(csmc,"fetched all, keys=$(keys(stdict)).")
# make sure forceproceed is false, not strictly needed if csmc starts false
csmc.forceproceed = false # only used in 7
# go to 4b
return trafficRedirectConsolidate459_StateMachine
end
## ============================================================================================
# start of things downinit
## ============================================================================================
"""
$SIGNATURES
Test waiting order between siblings for cascading downward tree initialization.
Notes
- State machine function 8j.
DevNotes
- FIXME, something wrong with CSM sequencing, https://github.com/JuliaRobotics/IncrementalInference.jl/issues/602#issuecomment-682114232
- This might be replaced with 4-stroke tree-init, if that algorithm turns out to work in all cases.
"""
function dwnInitSiblingWaitOrder_StateMachine(csmc::CliqStateMachineContainer)
prnt = getParent(csmc.tree, csmc.cliq)[1]
opt = getSolverParams(csmc.cliqSubFg) # csmc.dfg
# now get the newly computed message from the appropriate container
# FIXME THIS IS A PUSH MODEL, see #674 -- must make pull model first
# FIXME must be consolidated as part of #459
dwinmsgs = getfetchCliqueInitMsgDown(getCliqueData(prnt), from=:dwnInitSiblingWaitOrder_StateMachine)
# add downward belief prop msgs
msgfcts = addMsgFactors!(csmc.cliqSubFg, dwinmsgs, DownwardPass)
# determine if more info is needed for partial
sdims = getCliqVariableMoreInitDims(csmc.cliqSubFg, csmc.cliq)
updateCliqSolvableDims!(csmc.cliq, sdims, csmc.logger)
opt.dbg ? saveDFG(joinLogPath(csmc.cliqSubFg, "logs", "cliq$(csmc.cliq.index)", "fg_DWNCMN"), csmc.cliqSubFg) : nothing
dwnkeys_ = collect(keys(dwinmsgs.belief))
# NOTE, only use separators, not all parent variables
# dwnkeys_ = lsf(csmc.cliqSubFg, tags=[:DOWNWARD_COMMON;]) .|> x->ls(csmc.cliqSubFg, x)[1]
# @assert length(intersect(dwnkeys, dwnkeys_)) == length(dwnkeys) "split dwnkeys_ is not the same, $dwnkeys, and $dwnkeys_"
# priorize solve order for mustinitdown with lowest dependency first
# follow example from issue #344
mustwait = false
if length(intersect(dwnkeys_, getCliqSeparatorVarIds(csmc.cliq))) == 0
infocsm(csmc, "8j, dwnInitSiblingWaitOrder_StateMachine, no can do, must wait for siblings to update parent first.")
mustwait = true
elseif getSiblingsDelayOrder(csmc.tree, csmc.cliq, dwnkeys_, logger=csmc.logger)
infocsm(csmc, "8j, dwnInitSiblingWaitOrder_StateMachine, prioritize")
mustwait = true
elseif getCliqSiblingsPartialNeeds(csmc.tree, csmc.cliq, dwinmsgs, logger=csmc.logger)
infocsm(csmc, "8j, dwnInitSiblingWaitOrder_StateMachine, partialneedsmore")
mustwait = true
end
solord = getCliqSiblingsPriorityInitOrder( csmc.tree, prnt, csmc.logger )
noOneElse = areSiblingsRemaingNeedDownOnly(csmc.tree, csmc.cliq)
infocsm(csmc, "8j, dwnInitSiblingWaitOrder_StateMachine, $(prnt.index), $mustwait, $noOneElse, solord = $solord")
if mustwait && csmc.cliq.index != solord[1] # && !noOneElse
infocsm(csmc, "8j, dwnInitSiblingWaitOrder_StateMachine, must wait on change.")
# remove all message factors
fctstorm = ls(csmc.cliqSubFg, tags=[:DOWNWARD_COMMON;])
infocsm(csmc, "8j, dwnInitSiblingWaitOrder_StateMachine, removing factors $fctstorm")
rmfcts = fctstorm .|> x->getFactor(csmc.cliqSubFg, x)
# remove msg factors previously added
deleteMsgFactors!(csmc.cliqSubFg, rmfcts )
# go to 8c
return waitChangeOnParentCondition_StateMachine
end
# go to 8e.ii.
return attemptDownInit_StateMachine
end
"""
$SIGNATURES
Do down initialization calculations, loosely translates to solving Chapman-Kolmogorov
transit integral in downward direction.
Notes
- State machine function nr. 8a
- Includes initialization routines.
- TODO: Make multi-core
DevNotes
- FIXME major refactor of this function required.
- FIXME this function actually occur during the parent CSM, therefore not all pull model #674
"""
function collectDwnInitMsgFromParent_StateMachine(csmc::CliqStateMachineContainer)
#
# TODO consider exit early for root clique rather than avoiding this function
infocsm(csmc, "8a, needs down message -- attempt down init")
setCliqDrawColor(csmc.cliq, "gold")
# initialize clique in downward direction
# not if parent also needs downward init message
prnt = getParent(csmc.tree, csmc.cliq)[1]
opt = getSolverParams(csmc.dfg)
@assert !haskey(opt.devParams,:dontUseParentFactorsInitDown) "dbgnew is old school, 459 dwninit consolidation has removed the option for :dontUseParentFactorsInitDown"
# FIXME, offload this work to the parent's CSM
# take atomic lock OF PARENT ??? when waiting for downward information
lockUpStatus!(prnt, prnt.index, true, csmc.logger, true, "cliq$(csmc.cliq.index)") # TODO XY ????
infocsm(csmc, "8a, after up lock")
# get down message from the parent
# check if any msgs should be multiplied together for the same variable
# get the current messages ~~stored in~~ [going to] the parent (pull model #674)
# FIXME, post #459 calls?
# this guy is getting any sibling up messages by calling on the parent
prntmsgs::Dict{Int, LikelihoodMessage} = getMsgsUpInitChildren(csmc.tree, prnt, TreeBelief, skip=[csmc.cliq.index;])
# reference to default dict location
dwinmsgs = getfetchCliqueInitMsgDown(prnt.data, from=:getMsgDwnThisInit) |> deepcopy #JT 459 products = getMsgDwnThisInit(prnt)
infocsm(csmc, "prnt $(prnt.index), getMsgInitDwnParent -- msg ids::Int=$(collect(keys(prntmsgs)))")
# stack all parent incoming upward messages into dict of vector msgs
prntBelDictVec::Dict{Symbol, Vector{TreeBelief}} = convertLikelihoodToVector(prntmsgs, logger=csmc.logger)
## TODO use parent factors too
# intersect with the asking clique's separator variables
# this function populates `dwinmsgs` with the appropriate products described in `prntBelDictVec`
# FIXME, should not be using full .dfg ???
condenseDownMsgsProductPrntFactors!(csmc.dfg, dwinmsgs, prntBelDictVec, prnt, csmc.cliq, csmc.logger)
# remove msgs that have no data
rmlist = Symbol[]
for (prsym,belmsg) in dwinmsgs.belief
if belmsg.inferdim < 1e-10
# no information so remove
push!(rmlist, prsym)
end
end
infocsm(csmc, "prepCliqInitMsgsDown! -- rmlist, no inferdim, keys=$(rmlist)")
for pr in rmlist
delete!(dwinmsgs.belief, pr)
end
infocsm(csmc, "prnt $(prnt.index), prepCliqInitMsgsDown! -- product keys=$(collect(keys(dwinmsgs.belief)))")
# now put the newly computed message in the appropriate container
# FIXME THIS IS A PUSH MODEL, see #674 -- must make pull model first
# FIXME must be consolidated as part of #459
putCliqueInitMsgDown!(getCliqueData(prnt), dwinmsgs)
# unlock
unlockUpStatus!(prnt) # TODO XY ????, maybe can remove after pull model #674?
infocsm(csmc, "8a, attemptCliqInitD., unlocked")
# go to 8j.
return dwnInitSiblingWaitOrder_StateMachine
end
"""
$SIGNATURES
Redirect CSM traffic in various directions
Notes
- State machine function nr.4b
- Was refactored during #459 dwnMsg effort.
DevNotes
- Consolidate with 7?
"""
function trafficRedirectConsolidate459_StateMachine(csmc::CliqStateMachineContainer)
cliqst = getCliqueStatus(csmc.cliq)
infocsm(csmc, "4b, trafficRedirectConsolidate459_StateMachine, cliqst=$cliqst")
# if no parent or parent will not update
# for recycle computed clique values case
if csmc.incremental && cliqst == :downsolved
csmc.incremental = false