source: lmdz_wrf/trunk/tools/compute_accum.py @ 1333

Last change on this file since 1333 was 653, checked in by lfita, 9 years ago

Script to accumulate precipitation from a `stations-map' series of observations

File size: 4.6 KB
Line 
1import numpy as np
2from netCDF4 import Dataset as NetCDFFile
3import os
4import re
5from optparse import OptionParser
6import numpy.ma as ma
7
8# version
9version=1.1
10
11# Filling values for floats, integer and string
12fillValueF = 1.e20
13fillValueI = -99999
14fillValueS = '---'
15
16# Length of the string variables
17StringLength = 200
18
19# Size of the map for the complementary variables/maps
20Ndim2D = 100
21
22main = 'create_OBSnetcdf.py'
23errormsg = 'ERROR -- error -- ERROR -- error'
24warnmsg = 'WARNING -- warning -- WARNING -- warning'
25
26fillValue = 1.e20
27
28def searchInlist(listname, nameFind):
29    """ Function to search a value within a list
30    listname = list
31    nameFind = value to find
32    >>> searInlist(['1', '2', '3', '5'], '5')
33    True
34    """
35    for x in listname:
36      if x == nameFind:
37        return True
38    return False
39
40
41def set_attribute(ncvar, attrname, attrvalue):
42    """ Sets a value of an attribute of a netCDF variable. Removes previous attribute value if exists
43    ncvar = object netcdf variable
44    attrname = name of the attribute
45    attrvalue = value of the attribute
46    """
47    import numpy as np
48    from netCDF4 import Dataset as NetCDFFile
49
50    attvar = ncvar.ncattrs()
51    if searchInlist(attvar, attrname):
52        attr = ncvar.delncattr(attrname)
53
54    attr = ncvar.setncattr(attrname, attrvalue)
55
56    return ncvar
57
58def basicvardef(varobj, vstname, vlname, vunits):
59    """ Function to give the basic attributes to a variable
60    varobj= netCDF variable object
61    vstname= standard name of the variable
62    vlname= long name of the variable
63    vunits= units of the variable
64    """
65    attr = varobj.setncattr('standard_name', vstname)
66    attr = varobj.setncattr('long_name', vlname)
67    attr = varobj.setncattr('units', vunits)
68
69    return
70
71####### ###### ##### #### ### ## #
72
73fold='/media/ExtDiskD/DATA/obs/HyMeX/IOP15/HyMeX_rainfal/V2'
74
75lonvals = []
76latvals = []
77
78for day in range(19,23):
79    if day == 22:
80        Nhour = 1
81    else:
82        Nhour = 24
83    for hour in range(0,Nhour):
84        print day, hour
85        filen = fold + '/geo_v2_201210' + str(day) + '{:02d}'.format(hour) + '_RR1.nc'
86        onc = NetCDFFile(filen, 'r')
87        opr = onc.variables['pracc']
88        olon = onc.variables['lon']
89        olat = onc.variables['lat']
90
91        lonv = olon[:]
92        latv = olat[:]
93       
94        Npts = len(lonv)
95        if day == 19 and hour == 0:
96            Nptsorig = Npts
97            lonvals = list(lonv)
98            latvals = list(latv)
99            heights = onc.variables['height'][:]
100            praccsum = np.zeros((Npts), dtype=np.float)
101            NOTfound = np.zeros((Npts), dtype=bool)
102            nNOTfound = 0
103
104        found = np.zeros((Nptsorig), dtype=bool)
105
106        nNotfounddate = 0
107        for ip in range(Npts):
108            if searchInlist(lonvals, lonv[ip]) and searchInlist(latvals, latv[ip]):
109                il = lonvals.index(lonv[ip])
110                if lonvals[il] == lonv[ip] and latvals[il] == latv[ip]:
111                    praccsum[il] = praccsum[il] + opr[ip]
112                    found[il] = True
113#                    print lonv[ip], latv[ip], ':', lonvals[il], latvals[il]
114            else:
115#                print 'Not in the first file!'
116                nNotfounddate = nNotfounddate + 1
117                   
118        print 'On',day,'at',hour,'not found;',nNotfounddate,'stations from',Npts
119        for ip in range(Nptsorig):
120            if not found[ip] and not NOTfound[ip]: 
121                NOTfound[ip] = True
122                nNOTfound = nNOTfound + 1
123
124        onc.close()
125
126print 'From originally',Nptsorig,'there are not continuosly records from:',nNOTfound
127#finalaccum = ma.masked_array(praccsum)
128for ip in range(Nptsorig):
129    if NOTfound[ip]:
130        praccsum[ip] = fillValueF
131
132# File creation
133newnc = NetCDFFile('accum.nc', 'w')
134
135# Dimensions definition
136newdim = newnc.createDimension('Npts',Nptsorig)
137
138# Variable creation
139newvar = newnc.createVariable('lon','f8',('Npts'))
140basicvardef(newvar, 'lon', 'Longitudes', 'degrees_East')
141newvar[:] = lonvals
142set_attribute(newvar,'axis','X')
143
144newvar = newnc.createVariable('lat','f8',('Npts'))
145basicvardef(newvar, 'lat', 'Latitudes', 'degrees_North')
146newvar[:] = latvals
147set_attribute(newvar,'axis','Y')
148
149# Total accumulation
150newvar = newnc.createVariable('pracc','f',('Npts'),fill_value=fillValueF)
151basicvardef(newvar, 'pracc', 'accumulated precipitation', 'kgm-2')
152newvar[:] = praccsum
153set_attribute(newvar,'coordinates','lon lat')
154
155# Global attributes
156##
157filen = fold + '/geo_v2_2012101900_RR1.nc'
158onc = NetCDFFile(filen, 'r')
159
160attrs = onc.ncattrs()
161
162for attr in attrs:
163    attrv = onc.getncattr(attr)
164    set_attribute(newnc, attr, attrv)
165
166onc.close()
167
168newnc.sync()
169newnc.close()
Note: See TracBrowser for help on using the repository browser.