如何替换Oceananigans中FieldDataset的时间轴为自定义数组?
替换Oceananigans中FieldTimeSeries的时间轴
问题背景
使用Julia的Oceananigans海洋模型完成模拟后,通过JLD2OutputWriter将结果输出为jld2格式HDF5文件,文件包含多个随时间演化的3D变量。通过以下代码读取数据:
using Oceananigans d4 = FieldDataset("./test4_lang.jld2") d4.fields["u"].times
读取后d4.fields包含5个FieldTimeSeries对象:
julia> d4.fields Dict{String, FieldTimeSeries} with 5 entries: "v" => 32×32×32×103 FieldTimeSeries{InMemory} located at (Center, Face, Center) on CPU… "w" => 32×32×33×103 FieldTimeSeries{InMemory} located at (Center, Center, Face) on CPU… "b" => 32×32×32×103 FieldTimeSeries{InMemory} located at (Center, Center, Center) on CPU… "u" => 32×32×32×103 FieldTimeSeries{InMemory} located at (Face, Center, Center) on CPU… "νₑ" => 32×32×32×103 FieldTimeSeries{InMemory} located at (Center, Center, Center) on CPU…
需要将这些FieldTimeSeries的时间轴替换为自定义数组(如1:103,长度103)。
解决方案
FieldTimeSeries是可变结构体,可直接遍历修改其times字段:
代码实现
# 定义自定义时间数组,示例为1到103的序列 custom_times = 1:103 # 遍历所有FieldTimeSeries对象,替换时间轴 for (_, fts) in d4.fields # 先校验长度一致性,避免错误 @assert length(custom_times) == length(fts.times) "自定义时间数组长度与原时间轴不匹配" fts.times = custom_times end # 验证修改结果 println(d4.fields["u"].times) # 输出应为1:103
替代写法(使用setproperty!)
如果偏好显式调用结构体属性修改函数,也可以用setproperty!:
for (_, fts) in d4.fields @assert length(custom_times) == length(fts.times) "自定义时间数组长度与原时间轴不匹配" setproperty!(fts, :times, custom_times) end
内容的提问来源于stack exchange,提问作者Kenneth Lee
相关产品推荐
相关产品推荐

