>>> import nc
>>> a = nc.create('test.nc',nc.CLOBBER)
>>> a.def_dim('time',nc.UNLIMITED)
>>> a.def_dim('x', 10)
>>> a.def_dim('y', 5)
>>> a.def_att('Title','',nc.CHAR,'Test netCDF dataset')
>>> a.def_var('temp',nc.FLOAT,('time','x'))
>>> a.def_var('pres',nc.FLOAT,('time','y'))
>>> a.def_att('_units','temp',nc.CHAR,'degree_Fahrenheit')
>>> a.endef()
This creates the netCDF file and defines some dimensions, attributes and
variables. This generally follows the netCDF API.
>>> a.list_var()
[('temp', 5, 1, 2, [0, 1]), ('pres', 5, 0, 2, [0, 2])]
>>> a.list_att()
{'Title': 'Test netCDF dataset'}
>>> a.list_att('temp')
{'_units': 'degree_Fahrenheit'}
>>> temp = a.var('temp')
>>> temp.list_att()
{'_units': 'degree_Fahrenheit'}
>>> temp._units
'degree_Fahrenheit'
>>> temp
<netCDF variable object at 140055a00>
A netCDF variable object has attributes and values. The current indexing
scheme in python only allows 1 dimension to be addressed. This is being
fixed with the numerical extensions.
>>> temp[0] = (10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0)
>>> temp[:]
[10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0]
>>> temp[1] = range(20,30)
>>> temp[:]
[[10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0], [20.0, 21.0,
22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0]]
>>> z = temp[0]
>>> z[5] = 200
>>> temp[0] = z
>>> temp[0]
[10.0, 11.0, 12.0, 13.0, 14.0, 200.0, 16.0, 17.0, 18.0, 19.0]
>>> temp[0][5]
200.0
>>> a.close()
The variable object methods hide most of the access routines in the netCDF
API.
>>> a = nc.open('test.nc')
>>> temp = a.var('temp')
>>> temp[0]
[10.0, 11.0, 12.0, 13.0, 14.0, 200.0, 16.0, 17.0, 18.0, 19.0]
>>> a.close()
One problem is the use of scalar variables. Due to the python method of always
passing by reference, the syntax can't be the expected simple assign.
If z is a scalar netCDF variable, z = 10.0 would replace the z variable with
the value 10. I have decided to make all assignment and reference to scalar
values be of the form z[0].
>>> import nc
>>> a = nc.create('example.nc',nc.CLOBBER)
>>> a.def_dim('x',10)
>>> a.def_var('temp',nc.SHORT,('x'))
>>> a.def_att('_units','temp',nc.CHAR,'degreeF')
>>> a.endef()
>>> t = a.var('temp')
>>> t[:] = range(10,20)
>>> t[:]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> t.list_att()
{'_units': 'degreeF'}
>>> t.use_unit('degreeC')
>>> t[:]
[-12.2222222222, -11.6666666667, -11.1111111111, -10.5555555556, -10.0,
-9.44444444444, -8.88888888889, -8.33333333333, -7.77777777778, -7.22222222222]
This example shows the use of the udunits library to do unit conversions.
Note that since python is dynamically typed, conversion from SHORT to FLOAT causes no problems.