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

时间:2016-06-07 10:44:21

标签: 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)单位定义为'米'太。我怎样才能做到这一点?而且,如果我想把这一步放在' X'有点像500米'?

1 个答案:

答案 0 :(得分:2)

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

虽然您可以按照自己喜欢的方式执行此操作,但最好的方法是坚持使用netCDF约定并为变量定义一个名为“units”的文本属性,并将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/