[英]Saving a array of composite type Julia
對於我正在運行的實驗,定義自己的類型很方便。 問題是計算量確實很大,因此我需要在服務器上運行它,然后訪問數據以繪制結果。
因此,第一種類型具有我定義的某些字段,然后其他類型沒有固定數量的字段。 基本上我有這種交織的類型:
type TestType1
value::Int
end
type TestType2
testvec::Any
TestType2()=new(Test2[])
end
type TestType3
testtype2::Any
TestType3()=new(TestType2[])
end
type TestType4
testtype3::Any
TestType4()=new(TestType3[])
end
因為TestType1從不改變,但在TestType2內,我想存儲不同數量的testtype1值,等等。
因此,鏈創建工作如下:
test1=Test2(2);
test2=TestType2();
test3=TestType3();
test4=TestType4();
push!(test2.testvec,test1)
push!(test3.testtype2,test2)
push!(test4.testtype3,test3)
這樣效果很好,我可以輕松訪問實驗中需要的所有內容。
盡管問題出在我在服務器上運行時,但我需要能夠在運行結束時存儲test4
,然后在另一台服務器上再次打開它以使用數據並進行漂亮的繪制。
我嘗試使用JLD,但我認為它是用於字典的,它不允許我檢索信息。
我希望能夠以與我不變的方式調用存儲在某個地方的test4文件中的所有字段,而無需更改服務器。
我在朱莉婭(Julia)和OOP中很陌生,總的來說,我不知道如何做自己想做的事。
有人可以幫忙嗎?
謝謝!
JLD.load
返回一個字典,里面是您的對象。 例如:
# test_types.jl
__precompile__()
module TestTypes
using JLD: save
import Base: push!
export TestType1, TestType2, TestType3, TestType4
struct TestType1
value::Int
end
struct TestType2
data::Vector{TestType1}
TestType2() = new(TestType1[])
end
struct TestType3
data::Vector{TestType2}
TestType3() = new(TestType2[])
end
struct TestType4
data::Vector{TestType3}
TestType4() = new(TestType3[])
end
for n in 2:4
@eval function Base.push!(test_type::$(Symbol(:TestType, n)), test_arg::$(Symbol(:TestType, n-1)))
push!(test_type.data, test_arg)
end
end
function main()
test1 = TestType1(2)
test2 = TestType2()
test3 = TestType3()
test4 = TestType4()
push!(test2, test1)
push!(test3, test2)
push!(test4, test3)
file = "test_resutls.jld"
save(file, "test4", test4)
info("Test results saved in: $file")
return @show test4
end
end
交互如下所示:
julia> include("test_types.jl")
Main.TestTypes
julia> using Main.TestTypes: main
julia> original_test4 = main();
INFO: Test results saved in: test_resutls.jld
test4 = Main.TestTypes.TestType4(Main.TestTypes.TestType3[Main.TestTypes.TestType3(Main.TestTypes.TestType2[Main.TestTypes.TestType2(
Main.TestTypes.TestType1[Main.TestTypes.TestType1(2)])])])
julia> using JLD: load
julia> results = load("test_resutls.jld")
Dict{String,Any} with 1 entry:
"test4" => Main.TestTypes.TestType4(Main.TestTypes.TestType3[Main.TestTypes.TestType3(Main.TestTypes.TestType2[Main.TestTypes.Test…
julia> copy_test4 = results["test4"] # your data is inside this dict!
Main.TestTypes.TestType4(Main.TestTypes.TestType3[Main.TestTypes.TestType3(Main.TestTypes.TestType2[Main.TestTypes.TestType2(Main.Tes
tTypes.TestType1[Main.TestTypes.TestType1(2)])])])
julia> original_test4.data[1].data[1].data[1].value == copy_test4.data[1].data[1].data[1].value
true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.