[1738] | 1 | # Reconstructing ORCHIDEE's forcing files as matrices for a gien area |
---|
| 2 | # L. Fita, CIMA. December 2017 |
---|
| 3 | # |
---|
| 4 | import numpy as np |
---|
| 5 | from netCDF4 import Dataset as NetCDFFile |
---|
| 6 | import os |
---|
| 7 | import re |
---|
| 8 | import numpy.ma as ma |
---|
| 9 | # Importing generic tools file 'generic_tools.py' |
---|
| 10 | import generic_tools as gen |
---|
[1744] | 11 | import nc_var_tools as ncvar |
---|
[1738] | 12 | import subprocess as sub |
---|
[1744] | 13 | import module_ForSci as Sci |
---|
[1749] | 14 | from optparse import OptionParser |
---|
[1738] | 15 | |
---|
[1749] | 16 | parser = OptionParser() |
---|
[1782] | 17 | parser.add_option("-F", "--filename", dest="fn", help="name of files (overwrites -f option)", \ |
---|
| 18 | metavar="VALUE") |
---|
[1750] | 19 | parser.add_option("-f", "--fileHEader", dest="fh", help="header of files", \ |
---|
| 20 | metavar="VALUE") |
---|
[1782] | 21 | parser.add_option("-i", "--indices", dest="indn", help="name of the variable indices", \ |
---|
| 22 | metavar="VALUE") |
---|
[1750] | 23 | parser.add_option("-L", "--latitude", dest="latn", help="name of the variable latitiude", \ |
---|
| 24 | metavar="VALUE") |
---|
| 25 | parser.add_option("-l", "--longitude", dest="lonn", help="name of the variable longitiude", \ |
---|
| 26 | metavar="VALUE") |
---|
[1782] | 27 | parser.add_option("-t", "--TransposeVariables", dest="tvars", help="whether variables should be trasposed", \ |
---|
| 28 | metavar="VALUE") |
---|
[1750] | 29 | parser.add_option("-v", "--Variables", dest="varns", help="',' separated list of variables", \ |
---|
| 30 | metavar="VALUE") |
---|
[1749] | 31 | parser.add_option("-y", "--year", dest="year", help="year to process", \ |
---|
| 32 | metavar="VALUE") |
---|
[1738] | 33 | |
---|
[1749] | 34 | (opts, args) = parser.parse_args() |
---|
| 35 | |
---|
| 36 | ####### ###### ##### #### ### ## # |
---|
| 37 | |
---|
[1782] | 38 | if opts.fn is None: |
---|
| 39 | filen = opts.fh + opts.year + '.nc' |
---|
| 40 | else: |
---|
| 41 | filen = opts.fn |
---|
[1749] | 42 | |
---|
[1738] | 43 | # Variable whcih provides the indices of a 1D vector from the dimy, dimx space |
---|
[1782] | 44 | indvar = opts.indn |
---|
[1738] | 45 | |
---|
| 46 | # 2D longitude, latitude matrices |
---|
[1750] | 47 | lonvar = opts.lonn |
---|
| 48 | latvar = opts.latn |
---|
[1738] | 49 | |
---|
| 50 | # Range to retrieve |
---|
[1744] | 51 | Xmin=-90.25 |
---|
[1782] | 52 | Xmin='all' |
---|
[1746] | 53 | Xmax=-33.25 |
---|
[1744] | 54 | Ymin=-67.25 |
---|
| 55 | Ymax=15.25 |
---|
[1738] | 56 | |
---|
[1744] | 57 | # Variables to reconstruct |
---|
| 58 | #variable = 'all' |
---|
[1750] | 59 | variable = opts.varns |
---|
[1740] | 60 | |
---|
[1744] | 61 | # Resolution |
---|
| 62 | resX = 0.5 |
---|
| 63 | resY = 0.5 |
---|
[1740] | 64 | |
---|
[1744] | 65 | # Minimum difference from matrix to localized point |
---|
| 66 | maxdiff = 0.05 |
---|
| 67 | |
---|
[1740] | 68 | # Projection of the matrix |
---|
| 69 | matProj = 'latlon' |
---|
| 70 | |
---|
[1738] | 71 | ####### ####### |
---|
| 72 | ## MAIN |
---|
| 73 | ####### |
---|
[1744] | 74 | main = 'ORforcing_reconstruct.py' |
---|
| 75 | fname = 'ORforcing_reconstruct.py' |
---|
| 76 | |
---|
[1738] | 77 | onc = NetCDFFile(filen, 'r') |
---|
[1740] | 78 | |
---|
| 79 | availProj = ['latlon'] |
---|
| 80 | |
---|
[1749] | 81 | ofilen = 'reconstruct_matrix_' + opts.year + '.nc' |
---|
[1738] | 82 | |
---|
[1744] | 83 | ncvars = onc.variables.keys() |
---|
[1738] | 84 | |
---|
| 85 | varstocheck = [indvar, lonvar, latvar] |
---|
[1744] | 86 | for vn in varstocheck: |
---|
| 87 | if not gen.searchInlist(ncvars, vn): |
---|
[1738] | 88 | print gen.errormsg |
---|
| 89 | print ' ' + main + ": file '" + filen + "' does not have variable '" + vn + \ |
---|
| 90 | "' !!" |
---|
[1744] | 91 | print ' available ones:', ncvars |
---|
[1738] | 92 | quit(-1) |
---|
| 93 | |
---|
| 94 | oind = onc.variables[indvar] |
---|
| 95 | olon = onc.variables[lonvar] |
---|
| 96 | olat = onc.variables[latvar] |
---|
| 97 | |
---|
[1750] | 98 | indv = oind[:] |
---|
| 99 | lonv = olon[:] |
---|
| 100 | latv = olat[:] |
---|
| 101 | |
---|
| 102 | if len(olon.dimensions) == 2: |
---|
[1782] | 103 | dimx = lonv.shape[1] |
---|
| 104 | dimy = lonv.shape[0] |
---|
| 105 | veclon = lonv.reshape(dimx*dimy) |
---|
| 106 | veclat = latv.reshape(dimx*dimy) |
---|
[1750] | 107 | Xdimn = olon.dimensions[1] |
---|
| 108 | Ydimn = olon.dimensions[0] |
---|
[1782] | 109 | else: |
---|
| 110 | veclon = lonv.copy() |
---|
| 111 | veclat = latv.copy() |
---|
| 112 | Xdimn = 'x' |
---|
| 113 | Ydimn = 'y' |
---|
[1744] | 114 | |
---|
[1782] | 115 | vecdimn = oind.dimensions[0] |
---|
[1738] | 116 | |
---|
[1740] | 117 | if not gen.searchInlist(availProj, matProj): |
---|
| 118 | print errormsg |
---|
| 119 | print ' ' + fname + ": projection '" + matProj + "' not available !!" |
---|
| 120 | print ' available ones:', availProj |
---|
[1738] | 121 | quit(-1) |
---|
[1740] | 122 | |
---|
| 123 | ncdims = onc.dimensions |
---|
| 124 | |
---|
| 125 | if variable == 'all': |
---|
| 126 | varns = ncvars |
---|
| 127 | else: |
---|
| 128 | varns = variable.split(',') |
---|
| 129 | for vn in varns: |
---|
| 130 | if not gen.searchInlist(ncvars, vn): |
---|
[1746] | 131 | print gen.errormsg |
---|
[1750] | 132 | print ' ' + fname + ": file '" + filen + "' does not have " + \ |
---|
[1740] | 133 | " variable '" + vn + "' !!" |
---|
| 134 | print ' available ones:', ncvars |
---|
| 135 | quit(-1) |
---|
| 136 | |
---|
| 137 | if gen.searchInlist(olon.ncattrs(), 'units'): |
---|
| 138 | xunits = olon.getncattr('units') |
---|
| 139 | else: |
---|
| 140 | xunits = '-' |
---|
| 141 | if gen.searchInlist(olat.ncattrs(), 'units'): |
---|
| 142 | yunits = olat.getncattr('units') |
---|
| 143 | else: |
---|
| 144 | yunits = '-' |
---|
| 145 | |
---|
| 146 | if type(Xmin) == type('2') and Xmin == 'all': |
---|
[1744] | 147 | Xmin = np.min(lonv) |
---|
| 148 | Xmax = np.max(lonv) |
---|
| 149 | Ymin = np.min(latv) |
---|
| 150 | Ymax = np.max(latv) |
---|
[1740] | 151 | |
---|
| 152 | # Matrix values |
---|
| 153 | if matProj == 'latlon': |
---|
[1744] | 154 | dimx = int((Xmax - Xmin+resX)/resX) |
---|
| 155 | dimy = int((Ymax - Ymin+resY)/resY) |
---|
[1740] | 156 | |
---|
[1782] | 157 | print 'Xmin:', Xmin, 'Xmax:', Xmax, 'Ymin:', Ymin, 'Ymax:', Ymax, 'maxdiff:', maxdiff |
---|
[1740] | 158 | |
---|
[1782] | 159 | matindt, matXt, matYt, matdifft = Sci.module_scientific.reconstruct_matrix( \ |
---|
| 160 | vectorxpos=veclon, vectorypos=veclat, dvec=veclon.shape[0], xmin=Xmin, xmax=Xmax, \ |
---|
| 161 | ymin=Ymin,ymax=Ymax, dmatx=dimx, dmaty=dimy, matproj=matProj, maxdiff=maxdiff) |
---|
| 162 | |
---|
[1740] | 163 | matind = matindt.transpose() |
---|
[1782] | 164 | Nfound = np.sum(matind != -1) |
---|
| 165 | Nstations = veclon.shape[0] |
---|
| 166 | print ' Nfound:', Nfound, ' number of stations:', Nstations |
---|
| 167 | |
---|
| 168 | if Nfound*1. / Nstations < 0.8: |
---|
| 169 | print gen.errormsg |
---|
| 170 | print ' '+main + ': only ', '{:.2f}'.format(Nfound*100./Nstations),\ |
---|
| 171 | '% of points ' + 'have been found !!' |
---|
| 172 | print ' this is not enough. Something must went wrong!' |
---|
| 173 | print ' Longitudes Latitudes _______' |
---|
| 174 | for i in range(veclon.shape[0]): |
---|
| 175 | print ' ', veclon[i], veclat[i] |
---|
| 176 | dx2 = dimx/2 |
---|
| 177 | dy2 = dimy/2 |
---|
| 178 | print ' dx2, dy2 -/+ 5 fraction of destiny longitudes _______' |
---|
| 179 | for j in range(-5,5): |
---|
| 180 | print matXt[dx2-5:dx2+5,dy2+j] |
---|
| 181 | print ' dx2, dy2 -/+ 5 fraction of destiny latitudes _______' |
---|
| 182 | for j in range(-5,5): |
---|
| 183 | print matYt[dx2-5:dx2+5,dy2+j] |
---|
| 184 | print ' dx2, dy2 -/+ 5 fraction of indices equivalency _______' |
---|
| 185 | for j in range(-5,5): |
---|
| 186 | print matindt[dx2-5:dx2+5,dy2+j] |
---|
| 187 | print ' min distance lon(dy2,dx2)=', matXt[dx2,dy2], ':', \ |
---|
| 188 | np.min(veclon - matXt[dx2,dy2]) |
---|
| 189 | print ' min distance lat(dy2,dx2)=', matYt[dx2,dy2], ':', \ |
---|
| 190 | np.min(veclat - matYt[dx2,dy2]) |
---|
| 191 | print ' longitude borders:', Xmin, Xmax, 'dX:', resX |
---|
| 192 | print ' latitude borders:', Ymin, Ymax, 'dY:', resY |
---|
| 193 | #quit(-1) |
---|
| 194 | |
---|
[1746] | 195 | # Fortran like, First 1 |
---|
| 196 | matind = np.where(matind != -1, matind - 1, matind) |
---|
[1740] | 197 | |
---|
| 198 | # Creation of file |
---|
| 199 | onewnc = NetCDFFile(ofilen, 'w') |
---|
| 200 | |
---|
| 201 | # Dimensions |
---|
| 202 | newdim = onewnc.createDimension('x', dimx) |
---|
| 203 | newdim = onewnc.createDimension('y', dimy) |
---|
| 204 | |
---|
| 205 | # Variable-dimension |
---|
[1744] | 206 | newvar = onewnc.createVariable('lon', 'f8', ('y', 'x')) |
---|
[1740] | 207 | newvar[:] = matXt.transpose() |
---|
[1744] | 208 | ncvar.basicvardef(newvar, 'lon', 'Longitude', 'degrees_east') |
---|
[1740] | 209 | |
---|
[1744] | 210 | newvar = onewnc.createVariable('lat', 'f8', ('y', 'x')) |
---|
[1740] | 211 | newvar[:] = matYt.transpose() |
---|
[1744] | 212 | ncvar.basicvardef(newvar, 'lat', 'Latitude', 'degrees_north') |
---|
[1740] | 213 | onewnc.sync() |
---|
| 214 | |
---|
[1745] | 215 | # Variable indices |
---|
[1746] | 216 | newvar = onewnc.createVariable('vec1D_matind', 'i', ('y', 'x'), fill_value=-1) |
---|
[1745] | 217 | newvar[:] = matind |
---|
[1746] | 218 | ncvar.basicvardef(newvar, 'vec1D_matind', 'matrix with the equivalencies from 1D ' + \ |
---|
| 219 | 'vector indices', '-') |
---|
| 220 | ncvar.set_attribute(newvar, 'coordinates', 'lon lat') |
---|
[1745] | 221 | |
---|
[1782] | 222 | # Variable differences |
---|
| 223 | newvar = onewnc.createVariable('vec1D_matdiff', 'i', ('y', 'x'), fill_value=-1) |
---|
| 224 | newvar[:] = matdifft.transpose() |
---|
| 225 | ncvar.basicvardef(newvar,'vec1D_matdiff', 'matrix differences respect 1D ', 'degrees') |
---|
| 226 | ncvar.set_attribute(newvar, 'coordinates', 'lon lat') |
---|
| 227 | |
---|
[1745] | 228 | # Looking for equivalencies in the 1D vector |
---|
[1746] | 229 | matlonlat = matind.copy() |
---|
[1745] | 230 | for j in range(dimy): |
---|
| 231 | for i in range(dimx): |
---|
| 232 | if matind[j,i] != -1: |
---|
[1746] | 233 | matlonlat[j,i] = indv[matind[j,i]] |
---|
[1745] | 234 | |
---|
[1746] | 235 | newvar = onewnc.createVariable('lonlat_matind', 'i', ('y', 'x'), fill_value=-1) |
---|
| 236 | newvar[:] = matlonlat |
---|
| 237 | ncvar.basicvardef(newvar, 'lonlat_matind', 'matrix with the equivalencies from ' + \ |
---|
| 238 | '2D lon, lat matrices', '-') |
---|
| 239 | ncvar.set_attribute(newvar, 'coordinates', 'lon lat') |
---|
[1745] | 240 | onewnc.sync() |
---|
| 241 | |
---|
[1740] | 242 | # Getting variables |
---|
| 243 | for vn in varns: |
---|
| 244 | if not onewnc.variables.has_key(vn): |
---|
| 245 | ovar = onc.variables[vn] |
---|
[1782] | 246 | if gen.Str_Bool(opts.tvars): |
---|
| 247 | indn0 = ovar.dimensions |
---|
| 248 | indn = list(indn0)[::-1] |
---|
| 249 | else: |
---|
| 250 | indn = ovar.dimensions |
---|
[1740] | 251 | vardims = [] |
---|
| 252 | shapevar = [] |
---|
| 253 | for dn in indn: |
---|
| 254 | if not gen.searchInlist(onewnc.dimensions, dn) and dn != Xdimn and \ |
---|
| 255 | dn != Ydimn: |
---|
| 256 | if onc.dimensions[dn].isunlimited(): |
---|
[1744] | 257 | newdim = onewnc.createDimension(dn, None) |
---|
[1740] | 258 | else: |
---|
[1744] | 259 | newdim = onewnc.createDimension(dn, len(onc.dimensions[dn])) |
---|
[1740] | 260 | |
---|
[1744] | 261 | if dn == vecdimn: |
---|
[1740] | 262 | vardims.append('y') |
---|
| 263 | vardims.append('x') |
---|
| 264 | shapevar.append(dimy) |
---|
| 265 | shapevar.append(dimx) |
---|
| 266 | else: |
---|
| 267 | vardims.append(dn) |
---|
| 268 | shapevar.append(len(onc.dimensions[dn])) |
---|
| 269 | |
---|
| 270 | if ovar.dtype == type(int(2)): |
---|
[1744] | 271 | newvar= onewnc.createVariable(vn,ncvar.nctype(ovar.dtype),tuple(vardims),\ |
---|
[1740] | 272 | fill_value=gen.fillValueI) |
---|
| 273 | varvals = np.ones(tuple(shapevar), dtype=ovar.dtype)*gen.fillValueI |
---|
[1744] | 274 | elif ovar.dtype == type(np.int32(2)): |
---|
| 275 | newvar= onewnc.createVariable(vn,ncvar.nctype(ovar.dtype),tuple(vardims),\ |
---|
| 276 | fill_value=gen.fillValueI) |
---|
| 277 | varvals = np.ones(tuple(shapevar), dtype=ovar.dtype)*gen.fillValueI |
---|
| 278 | elif ovar.dtype == type(np.int64(2)): |
---|
| 279 | newvar= onewnc.createVariable(vn,ncvar.nctype(ovar.dtype),tuple(vardims),\ |
---|
| 280 | fill_value=gen.fillValueI) |
---|
| 281 | varvals = np.ones(tuple(shapevar), dtype=ovar.dtype)*gen.fillValueI |
---|
| 282 | elif ovar.dtype == type(np.float(2.)): |
---|
| 283 | newvar= onewnc.createVariable(vn,ncvar.nctype(ovar.dtype),tuple(vardims),\ |
---|
[1740] | 284 | fill_value=gen.fillValueF) |
---|
| 285 | varvals = np.ones(tuple(shapevar), dtype=ovar.dtype)*gen.fillValueF |
---|
[1744] | 286 | elif ovar.dtype == type(np.float32(2.)): |
---|
| 287 | newvar= onewnc.createVariable(vn,ncvar.nctype(ovar.dtype),tuple(vardims),\ |
---|
| 288 | fill_value=gen.fillValueF) |
---|
| 289 | varvals = np.ones(tuple(shapevar), dtype=ovar.dtype)*gen.fillValueF |
---|
| 290 | else: |
---|
| 291 | print gen.errormsg |
---|
| 292 | print ' ' + fname + ': variable type:', ovar.dtype, ' not ready !!' |
---|
| 293 | quit(-1) |
---|
[1740] | 294 | |
---|
[1782] | 295 | print ' reconstructing:', vn, ' shape:', newvar.shape, '...' |
---|
[1740] | 296 | # Filling variable. It would be faster if we can avoid this loop... I'm feeling lazy! |
---|
[1744] | 297 | if not gen.searchInlist(vardims,'x') and not gen.searchInlist(vardims,'y'): |
---|
[1782] | 298 | if gen.Str_Bool(opts.tvars): |
---|
| 299 | newvar[:] = ovar[:].transpose() |
---|
| 300 | else: |
---|
| 301 | newvar[:] = ovar[:] |
---|
[1744] | 302 | else: |
---|
[1782] | 303 | if gen.Str_Bool(opts.tvars): |
---|
| 304 | ovart = ovar[:] |
---|
| 305 | else: |
---|
| 306 | ovart = ovar[:].transpose() |
---|
| 307 | print ' Lluis shapes ovart:', ovart.shape, 'newvar:', newvar.shape |
---|
[1748] | 308 | if newvar.dtype == type(float(2.)) or newvar.dtype == type(np.float(2.)) \ |
---|
| 309 | or newvar.dtype == type(np.float32(2)) or \ |
---|
| 310 | newvar.dtype == type(np.float64(2)): |
---|
| 311 | newvals = Sci.module_scientific.fill3dr_2dvec(matind=matindt, \ |
---|
| 312 | inmat=ovart, id1=ovart.shape[0], id2=ovart.shape[1], \ |
---|
| 313 | od1=newvar.shape[2], od2=newvar.shape[1], od3=newvar.shape[0]) |
---|
| 314 | else: |
---|
| 315 | newvals = Sci.module_scientific.fill3di_2dvec(matind=matindt, \ |
---|
| 316 | inmat=ovart, id1=ovart.shape[0], id2=ovart.shape[1], \ |
---|
| 317 | od1=newvar.shape[2], od2=newvar.shape[1], od3=newvar.shape[0]) |
---|
| 318 | newvar[:] = newvals.transpose() |
---|
[1740] | 319 | |
---|
| 320 | # Attributes |
---|
| 321 | for atn in ovar.ncattrs(): |
---|
[1748] | 322 | if atn != '_FillValue' and atn != 'units': |
---|
[1740] | 323 | atv = ovar.getncattr(atn) |
---|
[1744] | 324 | ncvar.set_attribute(newvar, atn, atv) |
---|
| 325 | ncvar.set_attribute(newvar, 'coordinates', 'lon lat') |
---|
[1740] | 326 | onewnc.sync() |
---|
| 327 | |
---|
| 328 | # Global attributes |
---|
| 329 | for atn in onc.ncattrs(): |
---|
[1782] | 330 | atv = onc.getncattr(atn) |
---|
[1744] | 331 | ncvar.set_attribute(onewnc, atn, atv) |
---|
[1740] | 332 | onewnc.sync() |
---|
[1748] | 333 | ncvar.add_global_PyNCplot(onewnc, main, fname, '0.1') |
---|
[1749] | 334 | onc.close() |
---|
[1740] | 335 | |
---|
[1749] | 336 | # Reconstructing times |
---|
[1782] | 337 | #otime = onewnc.variables['time'] |
---|
| 338 | #ncvar.set_attribute(otime, 'units', 'seconds since ' + opts.year + '-01-01 00:00:00') |
---|
[1749] | 339 | |
---|
[1740] | 340 | onewnc.sync() |
---|
| 341 | onewnc.close() |
---|
| 342 | |
---|
[1749] | 343 | print fname + ": Successful writing of file '" + ofilen + ".nc' !!" |
---|