python - 使用 python 在 netcdf 文件中定义单位

标签 python unit-testing netcdf units-of-measurement

我正在创建一个包含一些变量的 netcdf 文件。我的 netcdf 文件和我预期的一样有用,但我不知道如何定义变量的单位。

这就是我的代码现在的样子:

import netCDF4
import numpy as np

ncfile = netCDF4.Dataset('state.global.nc', 'r')
u = ncfile.variables['U'][:,:,:,:] # [T,Z,Y,X]
v = ncfile.variables['V'][:,:,:,:]
nx = np.shape(u)[3] - 1
ny = np.shape(v)[2] - 1
nz = np.shape(u)[1]

u_c = 0.5 * (u[:,:,:,0:nx] + u[:,:,:,1:nx+1])
v_c = 0.5 * (v[:,:,0:ny,:] + v[:,:,1:ny+1,:])

u_center = np.fliplr(u_c) # Flip upside down
v_center = np.fliplr(v_c)

# Write out u_center and v_center into a new netCDF file
ncfile_out = netCDF4.Dataset('./output.nc', 'w')
ncfile_out.createDimension('X', nx)
ncfile_out.createDimension('Y', ny)
ncfile_out.createDimension('Z', nz)

ncfile_out.createDimension('time', None)
u_out = ncfile_out.createVariable('u_center', 'f4', ('time', 'Z', 'Y', 'X'))
v_out = ncfile_out.createVariable('v_center', 'f4', ('time', 'Z', 'Y', 'X'))
time = ncfile_out.createVariable('Time', 'i4', 'time')

v_out.units = 'm/s' # Define units of variables
u_out.units = 'm/s'
time.units = 's'

u_out[:,:,:,:] = u_center[:,:,:,:]
v_out[:,:,:,:] = v_center[:,:,:,:]
ncfile_out.close()

但是我使用 ncview 阅读了最终文件,但没有看到任何单位,我也想将尺寸 (x,y,z) 单位定义为“米”。我怎样才能做到这一点?而且,如果我想将 1 步放入“X”中,例如“500 米”,该怎么办?

最佳答案

定义单位的方法是使用 netCDF 文件中的属性。

虽然您可以按照自己喜欢的方式执行此操作,但最好的想法是坚持 netCDF 约定并为变量定义一个名为“单位”的文本属性,并放入 SI 单位。

这里有一个很好的例子: http://schubert.atmos.colostate.edu/~cslocum/netcdf_example.html

单位由如下代码定义:

w_nc_var.setncatts({'long_name': u"mean Daily Air temperature",\
                'units': u"degK", 'level_desc': u'Surface',\
                'var_desc': u"Air temperature",\
                'statistic': u'Mean\nM'})

(上面的代码还定义了其他属性,但您可以看到它将“units”设置为“degK”。)

如果您需要单位之间的转换,udunits 包可以提供帮助。这也是获取用于您的单位的缩写的好地方。

Udunits 也来自 Unidata,也是 netCDF 的维护者。

http://www.unidata.ucar.edu/software/udunits/

关于python - 使用 python 在 netcdf 文件中定义单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37677175/

相关文章:

python - Pandas 日期时间格式化与时区转换

python - 断言错误 : View function mapping is overwriting an existing endpoint function

ios - OCMock单元测试错误

python - 始终使用 netCDF4 生成屏蔽数组

python - 从域 ncfile 中提取数据

python - Flask-SQLAlchemy hybrid_property 中的多对多有序关系

python - 导入wx.lib.py时为"Import Error: NumPy not found"

c# - Rhino 模拟 stub 方法不起作用

unit-testing - Angular2 RC5 如何正确配置测试模块

R - 绘制 netcdf 气候数据