Skip to content

Commit a0c0299

Browse files
authored
Merge pull request #605 from JuliaRobotics/feat/20Q3/modul_softtype
Save/load softtype with module
2 parents 9c26e59 + 56af037 commit a0c0299

File tree

3 files changed

+47
-15
lines changed

3 files changed

+47
-15
lines changed

src/CloudGraphsDFG/services/CloudGraphsDFG.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ isFactor(dfg::CloudGraphsDFG, sym::Symbol)::Bool =
155155
function getSofttype(dfg::CloudGraphsDFG, lbl::Symbol; currentTransaction::Union{Nothing, Neo4j.Transaction}=nothing)
156156
st = _getNodeProperty(dfg.neo4jInstance, union(_getLabelsForType(dfg, DFGVariable), [String(lbl)]), "softtype", currentTransaction=currentTransaction)
157157
@debug "Trying to find softtype: $st"
158-
softType = getTypeFromSerializationModule(dfg, Symbol(st))
158+
softType = getTypeFromSerializationModule(st)
159159
return softType()
160160
end
161161

@@ -177,7 +177,7 @@ function updateVariable!(dfg::CloudGraphsDFG, variable::DFGVariable; skipAddErro
177177
# Create/update the base variable
178178
# NOTE: We are not merging the variable.tags into the labels anymore. We can index by that but not
179179
# going to pollute the graph with unnecessary (and potentially dangerous) labels.
180-
addProps = Dict("softtype" => "\"$(string(typeof(getSofttype(variable))))\"")
180+
addProps = Dict("softtype" => "\"$(DistributedFactorGraphs.typeModuleName(getSofttype(variable)))\"")
181181
query = """
182182
MATCH (session:$(join(_getLabelsForType(dfg, Session), ":")))
183183
MERGE (node:$(join(_getLabelsForInst(dfg, variable), ":")))

src/CloudGraphsDFG/services/CommonFunctions.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ function _structToNeo4jProps(inst::Union{User, Robot, Session, PVND, N, APPE, AB
146146
# Neo4j type conversion if possible - keep timestamps timestamps, etc.
147147
if field isa ZonedDateTime
148148
val = "datetime(\"$(string(field))\")"
149+
# val = "datetime(\"$(Dates.format(field, "yyyy-mm-ddTHH:MM:SS.ssszzz"))\")"
149150
end
150151
if field isa UUID
151152
val = "\"$(string(field))\""
@@ -167,7 +168,7 @@ function _structToNeo4jProps(inst::Union{User, Robot, Session, PVND, N, APPE, AB
167168
val = field.value
168169
end
169170
if fieldname == :softtype
170-
val = string(typeof(getSofttype(inst)))
171+
val = DistributedFactorGraphs.typeModuleName(getSofttype(inst))
171172
end
172173
# Factors
173174
# TODO: Consolidate with packFactor in Serialization.jl - https://github.com/JuliaRobotics/DistributedFactorGraphs.jl/issues/525

src/services/Serialization.jl

Lines changed: 43 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import JSON.Writer: StructuralContext, JSONContext, show_json
99
import JSON.Serializations: CommonSerialization, StandardSerialization
1010
JSON.show_json(io::JSONContext, serialization::CommonSerialization, uuid::UUID) = print(io.io, "\"$uuid\"")
1111

12-
1312
## Utility functions for ZonedDateTime
1413

1514
# Regex parser that converts clauses like ":59.82-" to well formatted ":59.820-"
@@ -40,6 +39,43 @@ function standardizeZDTStrings!(T, interm::Dict)
4039
nothing
4140
end
4241

42+
function string2ZonedDateTime(stringTimestamp)
43+
# ss = split(stringTimestamp, r"(T[0-9.:]*?\K(?=[-+Zz]))|[\[\]]")
44+
ss = split(stringTimestamp, r"T[\d.:]{5,12}?\K(?=[-+Zz])")
45+
length(ss) != 2 && error("Misformed zoned timestamp string $stringTimestamp")
46+
ZonedDateTime(DateTime(ss[1]), TimeZone(ss[2]))
47+
end
48+
49+
# Softtype module.type string functions
50+
function typeModuleName(softtype::InferenceVariable)
51+
io = IOBuffer()
52+
ioc = IOContext(io, :module=>DistributedFactorGraphs)
53+
show(ioc, typeof(softtype))
54+
return String(take!(io))
55+
end
56+
57+
function getTypeFromSerializationModule(softtypeString::String)
58+
try
59+
# split the type at last `.`
60+
split_st = split(softtypeString, r"\.(?!.*\.)")
61+
#if module is specified look for the module in main, otherwise use Main
62+
if length(split_st) == 2
63+
m = getfield(Main, Symbol(split_st[1]))
64+
else
65+
m = Main
66+
end
67+
return getfield(m, Symbol(split_st[end]))
68+
69+
catch ex
70+
@error "Unable to deserialize soft type $(softtypeString)"
71+
io = IOBuffer()
72+
showerror(io, ex, catch_backtrace())
73+
err = String(take!(io))
74+
@error(err)
75+
end
76+
nothing
77+
end
78+
4379
##==============================================================================
4480
## Variable Packing and unpacking
4581
##==============================================================================
@@ -53,9 +89,8 @@ function packVariable(dfg::G, v::DFGVariable)::Dict{String, Any} where G <: Abst
5389
props["solverDataDict"] = JSON2.write(Dict(keys(v.solverDataDict) .=> map(vnd -> packVariableNodeData(dfg, vnd), values(v.solverDataDict))))
5490
props["smallData"] = JSON2.write(v.smallData)
5591
props["solvable"] = v.solvable
56-
props["softtype"] = string(typeof(getSofttype(v)))
92+
props["softtype"] = typeModuleName(getSofttype(v))
5793
props["dataEntry"] = JSON2.write(Dict(keys(v.dataDict) .=> map(bde -> JSON.json(bde), values(v.dataDict))))
58-
5994
props["dataEntryType"] = JSON2.write(Dict(keys(v.dataDict) .=> map(bde -> typeof(bde), values(v.dataDict))))
6095
return props
6196
end
@@ -82,8 +117,8 @@ function unpackVariable(dfg::G,
82117
smallData = JSON2.read(packedProps["smallData"], Dict{Symbol, SmallDataTypes})
83118

84119
softtypeString = packedProps["softtype"]
85-
softtype = getTypeFromSerializationModule(dfg, Symbol(softtypeString))
86-
softtype == nothing && error("Cannot deserialize softtype '$softtypeString' in variable '$label'")
120+
softtype = getTypeFromSerializationModule(softtypeString)
121+
isnothing(softtype) && error("Cannot deserialize softtype '$softtypeString' in variable '$label'")
87122

88123
if unpackSolverData
89124
packed = JSON2.read(packedProps["solverDataDict"], Dict{String, PackedVariableNodeData})
@@ -134,7 +169,7 @@ function packVariableNodeData(dfg::G, d::VariableNodeData)::PackedVariableNodeDa
134169
d.BayesNetOutVertIDs,
135170
d.dimIDs, d.dims, d.eliminated,
136171
d.BayesNetVertID, d.separator,
137-
d.softtype != nothing ? string(d.softtype) : nothing,
172+
typeModuleName(d.softtype),
138173
d.initialized,
139174
d.inferdim,
140175
d.ismargin,
@@ -153,14 +188,10 @@ function unpackVariableNodeData(dfg::G, d::PackedVariableNodeData)::VariableNode
153188
c4 = r4 > 0 ? floor(Int,length(d.vecbw)/r4) : 0
154189
M4 = reshape(d.vecbw,r4,c4)
155190

156-
# TODO -- allow out of module type allocation (future feature, not currently in use)
157191
@debug "Dispatching conversion packed variable -> variable for type $(string(d.softtype))"
158192
# Figuring out the softtype
159-
unpackedTypeName = split(d.softtype, "(")[1]
160-
unpackedTypeName = split(unpackedTypeName, '.')[end]
161-
@debug "DECODING Softtype = $unpackedTypeName"
162-
st = getTypeFromSerializationModule(dfg, Symbol(unpackedTypeName))
163-
st == nothing && error("The variable doesn't seem to have a softtype. It needs to set up with an InferenceVariable from IIF. This will happen if you use DFG to add serialized variables directly and try use them. Please use IncrementalInference.addVariable().")
193+
st = getTypeFromSerializationModule(d.softtype)
194+
isnothing(st) && error("The variable doesn't seem to have a softtype. It needs to set up with an InferenceVariable from IIF. This will happen if you use DFG to add serialized variables directly and try use them. Please use IncrementalInference.addVariable().")
164195

165196
return VariableNodeData{st}(M3,M4, d.BayesNetOutVertIDs,
166197
d.dimIDs, d.dims, d.eliminated, d.BayesNetVertID, d.separator,

0 commit comments

Comments
 (0)