使用 julia 将字符数组写入 NetCDF 文件

Writing char array to NetCDF file with julia

如何使用 julia 在 NetCDF 文件中添加字符数组?下面是一个代码示例。首先,它已经给出了写入字符串数组的错误,因此可能有问题。但实际上,我需要 "country" 是 Char 类型。如何将字符串数组更改为 Char 以便在 NetCDF 中使用?这似乎与此问题 (https://github.com/JuliaLang/julia/issues/17694) 有关,但我不知道如何解决它。

示例:

using NetCDF
filename="test_netcdf_string.nc"
# Define some attributes
varatts = Dict("longname" => "number of citizens","units" => "million")
timeatts = Dict("longname" => "Time","units"    => "year")
nameatts = Dict("longname" => "Country name")

#Add some random data
time_data=collect(2014:2017)
countries=["Italy ","Germany", "France "]
cit_numbers=rand(5:100,size(countries,1),size(time_data,1))

#Create variable in netcdf
nccreate(filename, "citizens", "country", countries, nameatts,
"time", time_data, timeatts, atts=varatts)

ERROR: MethodError: no method matching nc_put_vara_x(::NetCDF.NcVar{Float64,1,6}, ::Array{UInt64,1}, ::Array{UInt64,1}, ::Array{String,1})

我不确定如何使用包 NetCDF.jl 执行此操作,但这里有一种使用 julia 包 NCDatasets.jl.

执行此操作的方法
using NCDatasets

filename="test_netcdf_string.nc"

time_data=collect(2014:2017)
countries=["Italy ","Germany", "France "]
cit_numbers=rand(5:100,size(countries,1),size(time_data,1))

ds = Dataset(filename,"c")
# define the dimensions
defDim(ds,"countries",length(countries))
defDim(ds,"time",length(time_data))

# define the variables
nccit_numbers = defVar(ds,"cit_numbers",Float64,("countries","time"))
nccountries = defVar(ds,"countries",String,("countries",))
nctime = defVar(ds,"time",Float64,("time",))

# define the attributes
nccountries.attrib["longname"] = "Country name"
# add more attributes...

nccountries[:] = countries
nccit_numbers[:] = cit_numbers
nctime[:] = time_data

# closing the file to make sure the data is saved
close(ds)

运行 julia 命令 Dataset(filename) returns:

Dataset: test_netcdf_string.nc
Group: /

Dimensions
   countries = 3
   time = 4

Variables
  cit_numbers   (3 × 4)
    Datatype:    Float64
    Dimensions:  countries × time

  countries   (3)
    Datatype:    String
    Dimensions:  countries
    Attributes:
     longname             = Country name

  time   (4)
    Datatype:    Float64
    Dimensions:  time

如果有人可以为包 NetCDF.jl 添加答案,这将很有帮助。

请注意,从版本 4 开始,将字符串列表(或数组)写入 NetCDF 文件已添加到 NetCDF 库中。您会发现很多关于 NetCDF 库 3 的文档,其中您只能编写向量(或数组)的单个字符。在这种情况下,您需要使所有国家/地区名称的长度相等(例如,通过用空格或空字符填充它们)并将所有这些名称 assemble 放入一个矩阵中。幸运的是,NetCDF 4 不再需要这样做。