-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAbstractDFG.jl
More file actions
1434 lines (1236 loc) · 42 KB
/
AbstractDFG.jl
File metadata and controls
1434 lines (1236 loc) · 42 KB
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
##==============================================================================
## AbstractDFG
##==============================================================================
##------------------------------------------------------------------------------
## Broadcasting
##------------------------------------------------------------------------------
# to allow stuff like `getFactorType.(dfg, [:x1x2f1;:x10l3f2])`
# https://docs.julialang.org/en/v1/manual/interfaces/#
Base.Broadcast.broadcastable(dfg::AbstractDFG) = Ref(dfg)
##==============================================================================
## Interface for an AbstractDFG
##==============================================================================
# TODO update to include graph and agent extras.
# Standard recommended fields to implement for AbstractDFG
# - `description::String`
# - `solverParams::T<:AbstractDFGParams`
# - `addHistory::Vector{Symbol}`
# - `blobStores::Dict{Symbol, AbstractBlobstore}`
# AbstractDFG Accessors
##------------------------------------------------------------------------------
## Getters
##------------------------------------------------------------------------------
"""
$(SIGNATURES)
Get the id of the node.
"""
getId(node) = node.id
"""
$(SIGNATURES)
Get the label of the node.
"""
getLabel(node) = node.label
"""
$SIGNATURES
Get the metadata of the node.
"""
getMetadata(node) = node.metadata
"""
$(SIGNATURES)
"""
function getAgent end
"""
$(SIGNATURES)
"""
function getGraph end
"""
$(SIGNATURES)
"""
getDescription(dfg::AbstractDFG) = dfg.description
"""
$(SIGNATURES)
"""
getAgentLabel(dfg::AbstractDFG) = getLabel(getAgent(dfg))
"""
$(SIGNATURES)
"""
getGraphLabel(dfg::AbstractDFG) = getLabel(dfg)
"""
$(SIGNATURES)
"""
getAddHistory(dfg::AbstractDFG) = dfg.addHistory
"""
$(SIGNATURES)
"""
getSolverParams(dfg::AbstractDFG) = dfg.solverParams
"""
$(SIGNATURES)
Method must be overloaded by the user for Serialization to work.
"""
function rebuildFactorCache!(dfg::AbstractDFG, factor::AbstractGraphFactor, neighbors = [])
@warn(
"FactorCache not build, rebuildFactorCache! is not implemented for $(typeof(dfg)). Make sure to load IncrementalInference.",
maxlog = 1
)
return nothing
end
"""
$(SIGNATURES)
Function to get the type of the variables in the DFG.
"""
function getTypeDFGVariables end
"""
$(SIGNATURES)
Function to get the type of the factors in the DFG.
"""
function getTypeDFGFactors end
##------------------------------------------------------------------------------
## Setters
##------------------------------------------------------------------------------
"""
$SIGNATURES
Set the metadata of the node.
"""
function setMetadata!(node, metadata::Dict{Symbol, MetadataTypes})
# with set old data should be removed, but care is taken to make sure its not the same object
node.metadata !== metadata && empty!(node.metadata)
return merge!(node.metadata, metadata)
end
"""
$(SIGNATURES)
"""
setDescription!(dfg::AbstractDFG, description::String) = dfg.description = description
"""
$(SIGNATURES)
"""
#NOTE a MethodError will be thrown if solverParams type does not mach the one in dfg
# TODO Is it ok or do we want any abstract solver paramters
function setSolverParams!(dfg::AbstractDFG, solverParams::AbstractDFGParams)
return dfg.solverParams = solverParams
end
# Accessors and CRUD for user/robot/session Data
"""
$SIGNATURES
Get the metadata from the agent in the AbstractDFG.
"""
getAgentMetadata(dfg::AbstractDFG) = getMetadata(getAgent(dfg))
"""
$SIGNATURES
Set the metadata of the agent in the AbstractDFG.
"""
function setAgentMetadata!(dfg::AbstractDFG, data::Dict{Symbol, MetadataTypes})
agent = getAgent(dfg)
return setMetadata!(agent, data)
end
"""
$SIGNATURES
Get the metadata from the factorgraph in the AbstractDFG.
"""
getGraphMetadata(dfg::AbstractDFG) = getMetadata(dfg)
"""
$SIGNATURES
Set the metadata of the factorgraph in the AbstractDFG.
"""
function setGraphMetadata!(dfg::AbstractDFG, data::Dict{Symbol, MetadataTypes})
return setMetadata!(dfg, data)
end
##==============================================================================
## Agent/Graph Data CRUD
##==============================================================================
#TODO maybe only support get and set?
#NOTE with API standardization this should become something like:
getAgentMetadata(dfg::AbstractDFG, key::Symbol) = getAgentMetadata(dfg)[key]
getGraphMetadata(dfg::AbstractDFG, key::Symbol) = getGraphMetadata(dfg)[key]
function updateAgentMetadata!(dfg::AbstractDFG, pair::Pair{Symbol, String})
return push!(dfg.agent.metadata, pair)
end
function updateGraphMetadata!(dfg::AbstractDFG, pair::Pair{Symbol, String})
return push!(dfg.graph.metadata, pair)
end
function deleteAgentMetadata!(dfg::AbstractDFG, key::Symbol)
pop!(dfg.agent.metadata, key)
return 1
end
function deleteGraphMetadata!(dfg::AbstractDFG, key::Symbol)
pop!(dfg.graph.metadata, key)
return 1
end
emptyAgentMetadata!(dfg::AbstractDFG) = empty!(dfg.agent.metadata)
emptyGraphMetadata!(dfg::AbstractDFG) = empty!(dfg.graph.metadata)
#TODO add__Data!?
##==============================================================================
## Agent/Graph/Model Blob Entries CRUD
##==============================================================================
function getGraphBlobentry end
function getGraphBlobentries end
function addGraphBlobentry! end
function addGraphBlobentries! end
function mergeGraphBlobentry! end
function mergeGraphBlobentries! end
function deleteGraphBlobentry! end
function getAgentBlobentry end
function getAgentBlobentries end
function addAgentBlobentry! end
function addAgentBlobentries! end
function mergeAgentBlobentry! end
function mergeAgentBlobentries! end
function deleteAgentBlobentry! end
function getModelBlobentry end
function getModelBlobentries end
function addModelBlobentry! end
function addModelBlobentries! end
function updateModelBlobentry! end
function deleteModelBlobentry! end
function listGraphBlobentries end
function listAgentBlobentries end
function listModelBlobentries end
function hasGraphBlobentry end
function hasAgentBlobentry end
function hasModelBlobentry end
##==============================================================================
## AbstractBlobstore CRUD
##==============================================================================
# AbstractBlobstore should have label or overwrite getLabel
getBlobstores(dfg::AbstractDFG) = dfg.blobStores
function getBlobstore(dfg::AbstractDFG, storeLabel::Symbol)
store = get(dfg.blobStores, storeLabel, nothing)
if isnothing(store)
throw(
LabelNotFoundError("Blobstore", storeLabel, collect(keys(getBlobstores(dfg)))),
)
end
return store
end
function addBlobstore!(dfg::AbstractDFG, bs::AbstractBlobstore)
return push!(dfg.blobStores, getLabel(bs) => bs)
end
function updateBlobstore!(dfg::AbstractDFG, bs::AbstractBlobstore)
return push!(dfg.blobStores, getLabel(bs) => bs)
end
function deleteBlobstore!(dfg::AbstractDFG, key::Symbol)
pop!(dfg.blobStores, key)
return 1
end
emptyBlobstore!(dfg::AbstractDFG) = empty!(dfg.blobStores)
listBlobstores(dfg::AbstractDFG) = collect(keys(dfg.blobStores))
##==============================================================================
## CRUD Interfaces
##==============================================================================
##------------------------------------------------------------------------------
## Variable And Factor CRUD
##------------------------------------------------------------------------------
"""
$(SIGNATURES)
True if the variable exists in the graph.
Implement `hasVariable(dfg::AbstractDFG, label::Symbol)`
"""
function hasVariable end
"""
$(SIGNATURES)
True if the factor exists in the graph.
Implement `hasFactor(dfg::AbstractDFG, label::Symbol)`
"""
function hasFactor end
"""
$(SIGNATURES)
Add a VariableCompute to a DFG.
Implement `addVariable!(dfg::AbstractDFG, variable::AbstractGraphVariable)`
"""
function addVariable! end
"""
$(SIGNATURES)
Add a Vector{VariableCompute} to a DFG.
Implement `addVariables!(dfg::AbstractDFG, variables::Vector{<:AbstractGraphVariable})`
"""
function addVariables!(dfg::AbstractDFG, variables::Vector{<:AbstractGraphVariable})
return asyncmap(variables) do v
return addVariable!(dfg, v)
end
end
"""
$(SIGNATURES)
Add a FactorCompute to a DFG.
Implement `addFactor!(dfg::AbstractDFG, factor::AbstractGraphFactor)`
"""
function addFactor! end
"""
$(SIGNATURES)
Add a Vector{FactorCompute} to a DFG.
"""
function addFactors!(dfg::AbstractDFG, factors::Vector{<:AbstractGraphFactor})
return asyncmap(factors) do f
return addFactor!(dfg, f)
end
end
"""
$(SIGNATURES)
Get a VariableCompute from a DFG using its label.
Implement `getVariable(dfg::AbstractDFG, label::Symbol)`
"""
function getVariable end
"""
$(SIGNATURES)
Get a VariableSummary from a DFG.
"""
function getVariableSummary end
"""
$(SIGNATURES)
Get the variables from a DFG as a Vector{VariableSummary}.
"""
function getVariablesSummary end
"""
$(SIGNATURES)
Get a VariableSkeleton from a DFG.
"""
function getVariableSkeleton end
"""
$(SIGNATURES)
Get the variables from a DFG as a Vector{VariableSkeleton}.
"""
function getVariablesSkeleton end
"""
$(SIGNATURES)
Get a FactorCompute from a DFG using its label.
Implement `getFactor(dfg::AbstractDFG, label::Symbol)`
"""
function getFactor end
"""
$(SIGNATURES)
Get the skeleton factors from a DFG as a Vector{FactorSkeleton}.
"""
function getFactorsSkeleton end
function Base.getindex(dfg::AbstractDFG, lbl::Symbol)
if isVariable(dfg, lbl)
getVariable(dfg, lbl)
elseif isFactor(dfg, lbl)
getFactor(dfg, lbl)
else
throw(LabelNotFoundError("GraphNode", lbl))
end
end
"""
$(SIGNATURES)
Merge a variable into the DFG. If a variable with the same label exists, it will be overwritten;
otherwise, the variable will be added to the graph.
Implement `mergeVariable!(dfg::AbstractDFG, variable::AbstractGraphVariable)`
"""
function mergeVariable! end
function mergeVariables! end
"""
$(SIGNATURES)
Merge a factor into the DFG. If a factor with the same label exists, it will be overwritten;
otherwise, the factor will be added to the graph.
Implement `mergeFactor!(dfg::AbstractDFG, factor::AbstractGraphFactor)`
"""
function mergeFactor! end
function mergeFactors! end
"""
$(SIGNATURES)
Delete a VariableCompute from the DFG.
Implement `deleteVariable!(dfg::AbstractDFG, label::Symbol)`
"""
function deleteVariable! end
"""
$(SIGNATURES)
Delete a FactorCompute from the DFG using its label.
Implement `deleteFactor!(dfg::AbstractDFG, label::Symbol)`
"""
function deleteFactor! end
"""
$(SIGNATURES)
Get the variables in the DFG as a Vector, supporting various filters.
Arguments
- `regexFilt`: Optional Regex to filter variable labels (deprecated, use `labelFilter` instead).
Keyword arguments
- `tags`: Vector of tags; only variables with at least one matching tag are returned.
- `solvable`: Optional Int; only variables with `solvable >= solvable` are returned.
- `solvableFilter`: Optional function to filter on the `solvable` property, eg `>=(1)`.
- `labelFilter`: Optional function to filter on label e.g., `contains(r"x1")`.
- `tagsFilter`: Optional function to filter on tags, eg. `⊇([:x1])`.
- `typeFilter`: Optional function to filter on the variable type.
Returns
- `Vector{<:AbstractGraphVariable}` matching the filters.
See also: [`listVariables`](@ref), [`ls`](@ref)
"""
function getVariables end
function getVariables(dfg::AbstractDFG, labels::Vector{Symbol})
return map(label -> getVariable(dfg, label), labels)
end
"""
$(SIGNATURES)
List the DFGFactors in the DFG.
Optionally specify a label regular expression to retrieves a subset of the factors.
"""
function getFactors end
function getFactors(dfg::AbstractDFG, labels::Vector{Symbol})
return map(label -> getFactor(dfg, label), labels)
end
##------------------------------------------------------------------------------
## Checking Types
##------------------------------------------------------------------------------
"""
$SIGNATURES
Return whether `sym::Symbol` represents a variable vertex in the graph DFG.
Checks whether it both exists in the graph and is a variable.
(If you rather want a quick for type, just do node isa VariableCompute)
Implement `isVariable(dfg::AbstractDFG, label::Symbol)`
"""
function isVariable end
"""
$SIGNATURES
Return whether `sym::Symbol` represents a factor vertex in the graph DFG.
Checks whether it both exists in the graph and is a factor.
(If you rather want a quicker for type, just do node isa FactorCompute)
Implement `isFactor(dfg::AbstractDFG, label::Symbol)`
"""
function isFactor end
##------------------------------------------------------------------------------
## Neighbors
##------------------------------------------------------------------------------
"""
$(SIGNATURES)
Checks if the graph is fully connected, returns true if so.
Implement `isConnected(dfg::AbstractDFG)`
"""
function isConnected end
"""
$(SIGNATURES)
Retrieve a list of labels of the immediate neighbors around a given variable or factor specified by its label.
Implement `listNeighbors(dfg::AbstractDFG, label::Symbol; solvable::Int = 0)`
"""
function listNeighbors end
##------------------------------------------------------------------------------
## copy and duplication
##------------------------------------------------------------------------------
#TODO use copy functions currently in attic
"""
$(SIGNATURES)
Gets an empty and unique DFG derived from an existing DFG.
Implement `_getDuplicatedEmptyDFG(dfg::AbstractDFG)`
"""
function _getDuplicatedEmptyDFG end
##------------------------------------------------------------------------------
## CRUD Aliases
##------------------------------------------------------------------------------
#TODO should this signiture be standardized or removed?
"""
$(SIGNATURES)
Get a VariableCompute with a specific solver key.
In memory types still return a reference, other types returns a variable with only solveKey.
"""
function getVariable(dfg::AbstractDFG, label::Symbol, solveKey::Symbol)
# TODO maybe change solveKey param to stateLabelFilter
# function getVariable(dfg::AbstractDFG, label::Symbol; stateLabelFilter::Union{Nothing, ...} = nothing)
var = getVariable(dfg, label)
if isa(var, VariableCompute) && !haskey(var.solverDataDict, solveKey)
throw(LabelNotFoundError("VariableNode", solveKey))
elseif !isa(var, VariableCompute)
@warn "getVariable(dfg, label, solveKey) only supported for type VariableCompute."
end
return var
end
function deleteVariable!(dfg::AbstractDFG, variable::AbstractGraphVariable)
return deleteVariable!(dfg, variable.label)
end
"""
$(SIGNATURES)
Delete the referenced Factor from the DFG.
"""
function deleteFactor!(dfg::AbstractDFG, factor::AbstractGraphFactor)
return deleteFactor!(dfg, factor.label)
end
# rather use isa in code, but ok, here it is
isVariable(dfg::AbstractDFG, node::AbstractGraphVariable) = true
isFactor(dfg::AbstractDFG, node::AbstractGraphFactor) = true
##------------------------------------------------------------------------------
## Connectivity Alias
##------------------------------------------------------------------------------
function listNeighbors(
dfg::AbstractDFG,
node::AbstractGraphNode;
solvable::Union{Nothing, Int} = nothing,
)
return listNeighbors(dfg, node.label; solvable)
end
##==============================================================================
## Listing and listing aliases
##==============================================================================
##------------------------------------------------------------------------------
## Overwrite in driver for performance
##------------------------------------------------------------------------------
"""
$(SIGNATURES)
Get a list of labels of the DFGVariables in the graph.
Optionally specify a label regular expression to retrieves a subset of the variables.
Tags is a list of any tags that a node must have (at least one match).
Notes
- Returns `::Vector{Symbol}`
Example
```julia
listVariables(dfg, r"l", tags=[:APRILTAG;])
```
See also: [`ls`](@ref)
"""
function listVariables(dfg::AbstractDFG, args...; kwargs...)
return map(getLabel, getVariables(dfg, args...; kwargs...))::Vector{Symbol}
end
"""
$(SIGNATURES)
Get a list of the labels of the DFGFactors in the DFG.
Optionally specify a label regular expression to retrieves a subset of the factors.
"""
function listFactors(dfg::AbstractDFG, args...; kwargs...)
return map(getLabel, getFactors(dfg, args...; kwargs...))::Vector{Symbol}
end
##------------------------------------------------------------------------------
## Aliases and Other filtered lists
##------------------------------------------------------------------------------
## ls Shorthands
##--------
"""
$(SIGNATURES)
List the DFGVariables in the DFG.
Optionally specify a label regular expression to retrieves a subset of the variables.
Tags is a list of any tags that a node must have (at least one match).
Notes:
- Returns `Vector{Symbol}`
"""
function ls(
dfg::AbstractDFG,
regexFilter::Union{Nothing, Regex} = nothing;
tags::Vector{Symbol} = Symbol[],
solvable::Union{Nothing, Int} = nothing,
solvableFilter::Union{Nothing, Function} = nothing,
tagsFilter::Union{Nothing, Function} = nothing,
typeFilter::Union{Nothing, Function} = nothing,
labelFilter::Union{Nothing, Function} = nothing,
)
return listVariables(
dfg,
regexFilter;
tags,
solvable,
solvableFilter,
tagsFilter,
typeFilter,
labelFilter,
)
end
#TODO tags kwarg
"""
$(SIGNATURES)
List the DFGFactors in the DFG.
Optionally specify a label regular expression to retrieves a subset of the factors.
Notes
- Return `Vector{Symbol}`
"""
function lsf(
dfg::AbstractDFG,
regexFilter::Union{Nothing, Regex} = nothing;
tags::Vector{Symbol} = Symbol[],
solvable::Union{Nothing, Int} = nothing,
solvableFilter::Union{Nothing, Function} = nothing,
tagsFilter::Union{Nothing, Function} = nothing,
typeFilter::Union{Nothing, Function} = nothing,
labelFilter::Union{Nothing, Function} = nothing,
)
return listFactors(
dfg,
regexFilter;
tags,
solvable,
solvableFilter,
tagsFilter,
typeFilter,
labelFilter,
)
end
"""
$(SIGNATURES)
Retrieve a list of labels of the immediate neighbors around a given variable or factor.
"""
function ls(
dfg::AbstractDFG,
node::AbstractGraphNode;
solvable::Union{Nothing, Int} = nothing,
)
return listNeighbors(dfg, node; solvable = solvable)
end
function ls(dfg::AbstractDFG, label::Symbol; solvable::Union{Nothing, Int} = nothing)
return listNeighbors(dfg, label; solvable = solvable)
end
function lsf(dfg::AbstractDFG, label::Symbol; solvable::Union{Nothing, Int} = nothing)
return listNeighbors(dfg, label; solvable = solvable)
end
## list by types
##--------------
function ls(dfg::AbstractDFG, ::Type{T}) where {T <: StateType}
return listVariables(dfg; typeFilter = ==(T()))
end
"""
$(SIGNATURES)
Lists the factors of a specific type in the factor graph.
Example, list all the Point2Point2 factors in the factor graph `dfg`:
lsf(dfg, Point2Point2)
Notes
- Return `Vector{Symbol}`
"""
function lsf(dfg::AbstractDFG, ::Type{T}) where {T <: AbstractObservation}
typeFilter = isconcretetype(T) ? x -> x == T : x -> x <: T
return listFactors(dfg; typeFilter)
end
function ls(dfg::AbstractDFG, ::Type{T}) where {T <: AbstractObservation}
return lsf(dfg, T)
end
"""
$(SIGNATURES)
Helper to return neighbors at distance 2 around a given node.
"""
function ls2(dfg::AbstractDFG, label::Symbol)
l2 = listNeighborhood(dfg, label, 2)
l1 = listNeighborhood(dfg, label, 1)
return setdiff(l2, l1)
end
ls2(dfg::AbstractDFG, v::AbstractGraphNode) = ls2(dfg, getLabel(v))
"""
$SIGNATURES
Return vector of prior factor symbol labels in factor graph `dfg`.
Notes:
- Returns `Vector{Symbol}`
"""
function lsfPriors(dfg::AbstractDFG)
return listFactors(dfg; typeFilter = isPrior)
end
## Listing DataTypes in a DFG
"""
$SIGNATURES
Return `Vector{DataType}` of all unique variable types in factor graph.
"""
function lsTypes(dfg::AbstractDFG)
vars = getVariables(dfg)
alltypes = Set{DataType}()
for v in vars
varType = typeof(getVariableType(v))
push!(alltypes, varType)
end
return collect(alltypes)
end
"""
$SIGNATURES
Return `::Dict{DataType, Vector{Symbol}}` of all unique variable types with labels in a factor graph.
"""
function lsTypesDict(dfg::AbstractDFG)
vars = getVariables(dfg)
alltypes = Dict{DataType, Vector{Symbol}}()
for v in vars
varType = typeof(getVariableType(v))
d = get!(alltypes, varType, Symbol[])
push!(d, v.label)
end
return alltypes
end
"""
$SIGNATURES
Return `Vector{Symbol}` of all unique factor types in factor graph.
"""
function lsfTypes(dfg::AbstractDFG)
facs = getFactors(dfg)
alltypes = Set{DataType}()
for f in facs
facType = typeof(getFactorType(f))
push!(alltypes, facType)
end
return collect(alltypes)
end
"""
$SIGNATURES
Return `::Dict{DataType, Vector{Symbol}}` of all unique factors types with labels in a factor graph.
"""
function lsfTypesDict(dfg::AbstractDFG)
facs = getFactors(dfg)
alltypes = Dict{DataType, Vector{Symbol}}()
for f in facs
facType = typeof(getFactorType(f))
d = get!(alltypes, facType, Symbol[])
push!(d, f.label)
end
return alltypes
end
##------------------------------------------------------------------------------
## tags
##------------------------------------------------------------------------------
"""
$SIGNATURES
Determine if the variable or factor neighbors have the `tags:;Vector{Symbol}`, and `matchAll::Bool`.
"""
function hasTags(dfg::AbstractDFG, sym::Symbol, tags::Vector{Symbol}; matchAll::Bool = true)
#
alltags = listTags(dfg, sym)
return length(filter(x -> x in alltags, tags)) >= (matchAll ? length(tags) : 1)
end
"""
$SIGNATURES
Determine if the variable or factor neighbors have the `tags:;Vector{Symbol}`, and `matchAll::Bool`.
"""
function hasTagsNeighbors(
dfg::AbstractDFG,
sym::Symbol,
tags::Vector{Symbol};
matchAll::Bool = true,
)
#
# assume only variables or factors are neighbors
getNeiFnc = isVariable(dfg, sym) ? getFactor : getVariable
alltags = union((ls(dfg, sym) .|> x -> getTags(getNeiFnc(dfg, x)))...)
return length(filter(x -> x in alltags, tags)) >= (matchAll ? length(tags) : 1)
end
##==============================================================================
## Finding
##==============================================================================
# function findClosestTimestamp(setA::Vector{Tuple{DateTime,T}},
# setB::Vector{Tuple{DateTime,S}}) where {S,T}
"""
$SIGNATURES
Find and return the closest timestamp from two sets of Tuples. Also return the minimum delta-time (`::Millisecond`) and how many elements match from the two sets are separated by the minimum delta-time.
"""
function findClosestTimestamp(
setA::Vector{Tuple{ZonedDateTime, T}},
setB::Vector{Tuple{ZonedDateTime, S}},
) where {S, T}
#
# build matrix of delta times, ranges on rows x vars on columns
DT = Array{Millisecond, 2}(undef, length(setA), length(setB))
for i = 1:length(setA), j = 1:length(setB)
DT[i, j] = setB[j][1] - setA[i][1]
end
DT .= abs.(DT)
# absolute time differences
# DTi = (x->x.value).(DT) .|> abs
# find the smallest element
mdt = minimum(DT)
corrs = findall(x -> x == mdt, DT)
# return the closest timestamp, deltaT, number of correspondences
return corrs[1].I, mdt, length(corrs)
end
"""
$SIGNATURES
Find and return nearest variable labels per delta time. Function will filter on `regexFilter`, `tags`, and `solvable`.
Notes
- Returns `Vector{Tuple{Vector{Symbol}, Millisecond}}`
DevNotes:
- TODO `number` should allow returning more than one for k-nearest matches.
- Future versions likely will require some optimization around the internal `getVariable` call.
- Perhaps a dedicated/efficient `getVariableTimestamp` for all DFG flavors.
Related
ls, listVariables, findClosestTimestamp
"""
function findVariableNearTimestamp(
dfg::AbstractDFG,
timest::ZonedDateTime,
regexFilter::Union{Nothing, Regex} = nothing;
tags::Vector{Symbol} = Symbol[],
solvable::Int = 0,
warnDuplicate::Bool = true,
number::Int = 1,
)
#
# get the variable labels based on filters
# syms = listVariables(dfg, regexFilter, tags=tags, solvable=solvable)
syms = listVariables(dfg, regexFilter; tags = tags, solvable = solvable)
# compile timestamps with label
# vars = map( x->getVariable(dfg, x), syms )
timeset = map(x -> (getTimestamp(getVariable(dfg, x)), x), syms)
mask = BitArray{1}(undef, length(syms))
fill!(mask, true)
RET = Vector{Tuple{Vector{Symbol}, Millisecond}}()
SYMS = Symbol[]
CORRS = 1
NUMBER = number
while 0 < CORRS + NUMBER
# get closest
link, mdt, corrs = findClosestTimestamp([(timest, 0)], timeset[mask])
newsym = syms[link[2]]
union!(SYMS, !isa(newsym, Vector) ? [newsym] : newsym)
mask[link[2]] = false
CORRS = corrs - 1
# last match, done with this delta time
if corrs == 1
NUMBER -= 1
push!(RET, (deepcopy(SYMS), mdt))
SYMS = Symbol[]
end
end
# warn if duplicates found
# warnDuplicate && 1 < corrs ? @warn("getVariableNearTimestamp found more than one variable at $timestamp") : nothing
return RET
end
function findVariableNearTimestamp(
dfg::AbstractDFG,
timest::DateTime,
regexFilter::Union{Nothing, Regex} = nothing;
timezone = tz"UTC",
kwargs...,
)
return findVariableNearTimestamp(
dfg,
ZonedDateTime(timest, timezone),
regexFilter;
kwargs...,
)
end
##==============================================================================
## exists - alias for hasVariable || hasFactor
##==============================================================================
# exists alone is ambiguous and only for variables and factors where there rest of the nouns use has,
# TODO therefore, keep as internal or deprecate?
# additionally - variables and factors can possibly have the same label in other drivers such as NvaSDK
"""
$(SIGNATURES)
True if a variable or factor with `label` exists in the graph.
"""
function exists(dfg::AbstractDFG, label::Symbol)
return hasVariable(dfg, label) || hasFactor(dfg, label)
end
function exists(dfg::AbstractDFG, node::AbstractGraphNode)
return exists(dfg, node.label)
end
##==============================================================================
## Copy Functions
##==============================================================================
"""
$(SIGNATURES)
Common function for copying nodes from one graph into another graph.
This is overridden in specialized implementations for performance.
Orphaned factors are not added, with a warning if verbose.
Set `overwriteDest` to overwrite existing variables and factors in the destination DFG.
NOTE: copyGraphMetadata not supported yet.
Related:
- [`deepcopyGraph`](@ref)
- [`deepcopyGraph!`](@ref)
- [`buildSubgraph`](@ref)
- [`listNeighborhood`](@ref)
- [`mergeGraph!`](@ref)
"""
function copyGraph!(
destDFG::AbstractDFG,
sourceDFG::AbstractDFG,
variableLabels::AbstractVector{Symbol} = listVariables(sourceDFG),
factorLabels::AbstractVector{Symbol} = listFactors(sourceDFG);
copyGraphMetadata::Bool = false,
overwriteDest::Bool = false,
deepcopyNodes::Bool = false,
verbose::Bool = false,
showprogress::Bool = verbose,
)
# Split into variables and factors
sourceVariables = getVariables(sourceDFG, variableLabels)
sourceFactors = getFactors(sourceDFG, factorLabels)
# Now we have to add all variables first,
@showprogress desc = "copy variables" enabled = showprogress for variable in
sourceVariables
variableCopy = deepcopyNodes ? deepcopy(variable) : variable
if !hasVariable(destDFG, variable.label)
addVariable!(destDFG, variableCopy)
elseif overwriteDest
mergeVariable!(destDFG, variableCopy)
else
throw(LabelExistsError("Variable", variable.label))
end
end
# And then all factors to the destDFG.
@showprogress desc = "copy factors" enabled = showprogress for factor in sourceFactors
# Get the original factor variables (we need them to create it)
sourceFactorVariableIds = collect(factor._variableOrderSymbols)
# Find the labels and associated variables in our new subgraph
factVariableIds = Symbol[]
for variable in sourceFactorVariableIds
if hasVariable(destDFG, variable)
push!(factVariableIds, variable)
end
end
# Only if we have all of them should we add it (otherwise strange things may happen on evaluation)
if length(factVariableIds) == length(sourceFactorVariableIds)
factorCopy = deepcopyNodes ? deepcopy(factor) : factor
if !hasFactor(destDFG, factor.label)
addFactor!(destDFG, factorCopy)
elseif overwriteDest
mergeFactor!(destDFG, factorCopy)
else