Subversion Repositories lagranto.arpege

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3 michaesp 1
# coding:utf-8
2
 
3
"""
4
Module to read and write netcdf file.
5
 
6
Interface to netCDF4
7
 
8
"""
9
 
10
import sys
11
import netCDF4
12
import numpy as np
13
 
14
 
15
def read_var(filename, variables, index=slice(None)):
16
    """ Extract variables from a netCDF
17
 
18
        return a list of netCDF4 array
19
        with time as a datetime object if possible
20
        index should be a slice object like np.s_[0, :, 10]
21
    """
22
    if type(variables) is not list:
23
        variables = [variables]
24
 
25
    vararray = []
26
 
27
    def check_var(nvariables, variables):
28
        nv = set(nvariables)
29
        v = set(variables)
30
        ok = set(nv).issuperset(v)
31
        if not ok:
32
            diffvar = set(v).difference(nv)
33
            err = '{} not found in {}\n. Available :{}'.format(
34
                ",".join(diffvar), filename, ",".join(nvariables))
35
            raise Exception(err)
36
 
37
    with netCDF4.MFDataset(filename) as ncfile:
38
        check_var(list(ncfile.variables.keys()), variables)
39
        for var in variables:
40
            if var == 'time':
41
                time = ncfile.variables[var]
42
                try:
43
                    vardata = netCDF4.num2date(time[:], units=time.units)
44
                except AttributeError:
45
                    vardata = np.array(time)
46
            else:
47
                vardata = ncfile.variables[var][index]
48
            vararray.append(vardata.squeeze())
49
 
50
    return vararray
51
 
52
 
53
def read_gattributes(filename):
54
    """ Read global attributes from a netCDF"""
55
    gattributes = netCDF4.Dataset(filename).__dict__
56
    return gattributes
57
 
58
 
59
def read_dimensions(filename):
60
    """ Read dimensions"""
61
    dimensions = netCDF4.Dataset(filename).dimensions
62
    return dimensions
63
 
64
 
65
def read_variables(filename):
66
    """ Read variables"""
67
    variables = list(netCDF4.Dataset(filename).variables.keys())
68
    return variables
69
 
70
 
71
def create(outname, dimensions, gattributes):
72
    """ create a netCDF """
73
    ncfile = netCDF4.Dataset(outname, 'w', format='NETCDF3_CLASSIC')
74
    for dim in dimensions:
75
        ncfile.createDimension(dim[0], dim[1])
76
    ncfile.setncatts(gattributes)
77
    return ncfile
78
 
79
 
80
def addvar(ncfile, varname, vardata, dimensions):
81
    """ Add a variable to a netcdf"""
82
    var = ncfile.createVariable(varname, vardata.dtype, dimensions)
83
    try:
84
        var[:] = vardata
85
    except Exception as e:
86
        sys.stderr.write('{0} in addvar()\n'.format(e))
87
        sys.exit(1)