-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaverage_nc
executable file
·178 lines (155 loc) · 6.3 KB
/
average_nc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/usr/bin/env python
from __future__ import print_function
import gdal
import math
from gdalconst import *
import struct
from netCDF4 import Dataset
import matplotlib.pylab as mpl
import numpy as np
import sys
import glob
# fill in times.
from datetime import datetime, timedelta
from netCDF4 import num2date, date2num
from argparse import ArgumentParser
import flo_utils as fu
def cerr(*objs):
print( *objs, file=sys.stderr)
def debug(*objs):
if fu.debug:
print( *objs, file=sys.stderr)
def copy_atts(infile, outfile, varname):
var = infile.variables[varname]
atts = {x: var.getncattr(x) for x in var.ncattrs() if x not in ["_FillValue"]}
outfile.variables[varname].setncatts(atts)
def open_files(infilename, outfilename):
infile = Dataset(infilename,"r")
outfile = Dataset (outfilename, "w")
return (infile, outfile)
def copy_dimensions(infile, outfile, average_dimensions, npoints):
for dim in infile.dimensions:
in_dim_d = infile.dimensions[dim]
if dim in infile.variables:
in_dim_v = infile.variables[dim]
else:
in_dim_v = None
if infile.dimensions[dim].isunlimited():
outfile.createDimension(dim, None)
if dim in infile.variables:
out_dim_v = outfile.createVariable(dim,in_dim_v.dtype, (dim,))
out_dim_v[0:len(in_dim_d)] = in_dim_v[:]
else:
out_dim_v = outfile.createVariable(dim,'f8', (dim,))
out_dim_v[0:len(in_dim_d)] = 0.
else:
if not dim in average_dimensions:
outfile.createDimension(dim,len(in_dim_d))
if dim in infile.variables:
out_dim_v = outfile.createVariable( dim,in_dim_v.dtype, (dim,) )
out_dim_v[:] = in_dim_v[:]
else:
outfile.createDimension(dim,len(in_dim_d)/npoints)
if dim in infile.variables:
out_dim_v = outfile.createVariable( dim,in_dim_v.dtype, (dim,) )
out_dim_v[:] = 0.
for x in xrange(npoints):
out_dim_v[:] = out_dim_v[:] + in_dim_v[x:len(out_dim_v)*npoints:npoints]
out_dim_v[:] = out_dim_v[:] / npoints
if dim in infile.variables:
copy_atts(infile, outfile, dim)
def copy_leftovers(infile, outfile, average_dimensions):
for v in infile.variables.keys():
var = infile.variables[v]
debug(v)
debug(var.dtype)
dims = var.dimensions
debug(dims)
match_dims = [x for x in dims if x in average_dimensions]
if (not match_dims) and (not v in infile.dimensions):
debug(v)
outfile.createVariable(v, var.dtype, dims)
outfile.variables[v][:]= var[:]
copy_atts(infile, outfile, v)
def check_var_dims(infile, varname, average_dimensions):
dims = infile.variables[varname].dimensions
debug(varname)
if not dims:
return False
if infile.dimensions[dims[0]].isunlimited():
dims = dims[1:]
if dims[0] in average_dimensions and dims[1] in average_dimensions:
return True
return False
def convert_var(infile, outfile, varname, npoints):
var = infile.variables[varname]
if infile.dimensions[var.dimensions[0]].isunlimited():
has_time = True
start_dim = 1
else:
has_time = False
start_dim = 0
in_dims = [infile.dimensions[x] for x in var.dimensions[start_dim:]]
# out_dims = [outfile.dimensions[x] for x in var.dimensions[start_dim:]]
debug( var.dimensions)
debug( var.shape)
fill_value = -9e33
if "_FillValue" in var.ncattrs():
fill_value=var._FillValue
debug( "creating with _FillValue %f"%fill_value)
ov = outfile.createVariable(varname,var.dtype,var.dimensions, fill_value=var._FillValue)
debug(ov.shape)
out_var = np.zeros(ov.shape)
out_count = np.zeros(out_var.shape)
endx = len(in_dims[0]) - len(in_dims[0])%npoints
endy = len(in_dims[1]) - len(in_dims[1])%npoints
for i in xrange(npoints):
for j in xrange (npoints):
if has_time:
debug( "adding out_var with offset %d %d"%(i,j))
out_var[:] = out_var[:] + var[:, i:endx:npoints, j:endy:npoints] * (1-var.mask[:, i:endx:npoints, j:endy:npoints])
out_count = out_count + (1-var[:, i:endx:npoints, j:endy:npoints].mask)
else:
out_var[:] = out_var[:] + var[i:endx:npoints, j:endy:npoints] * (1-var[i:endx:npoints, j:endy:npoints].mask)
out_count = out_count + (1-var[i:endx:npoints, j:endy:npoints].mask)
ov[:] = (out_var[:] / (out_count + (out_count == 0))) * (out_count > 0 ) + (out_count == 0) * fill_value
copy_atts(infile, outfile, varname)
# print (dir(driver))
# src_ds = gdal.Open( template )
# outDataset = driver.CreateCopy(newname, src_ds, 0 )
# print outDataset
# outBand = outDataset.GetRasterBand(1)
# outBand.WriteArray(np.squeeze(var[:]), 0,0)
def parse_args():
parser = ArgumentParser()
parser.description = "block average netcdf file"
parser.add_argument("FILE", nargs=2)
parser.add_argument("-n", "--npoints",
help='''number of points to average over''', default=None, type = int)
parser.add_argument("-a", "--average_dimensions",
help='''dimensions to average over''', default="x,y")
parser.add_argument("-x", "--exclude",
help='''variables to exclude''', default="lon,lat,lon_bnds,lat_bnds")
parser.add_argument("-v", "--verbose",
help='''verbose''', action = "store_true")
options = parser.parse_args()
return options
def main(argv):
options = parse_args()
if options.verbose:
fu.debug = True
# print (dir(options))
infilename = options.FILE[0]
outfilename = options.FILE[1]
(infile, outfile ) = open_files(infilename, outfilename)
dimensions = infile.dimensions.keys()
exclude = options.exclude.split(",") + dimensions
copy_dimensions(infile, outfile, options.average_dimensions.split(","), options.npoints)
copy_leftovers(infile, outfile, options.average_dimensions)
for varname in infile.variables.keys():
if varname not in exclude and check_var_dims(infile, varname, options.average_dimensions):
convert_var(infile, outfile, varname, options.npoints)
else:
debug( "Omitting %s"%(varname))
if __name__ == "__main__":
main(sys.argv)