OB.DAAC Logo
NASA Logo
Ocean Color Science Software

ocssw V2022
dtdb.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # encoding: utf-8
3 
4 import os
5 import sys
6 import math
7 import time
8 import argparse
9 import xarray as xr
10 import numpy as np
11 import matplotlib.pyplot as plt
12 from matplotlib import cm
13 from dtocean import dtocean
14 from dbocean import dbocean
15 
16 W410 = 0
17 W445 = 1
18 W490 = 2
19 W550 = 3
20 W670 = 4
21 W865 = 5
22 W1240 = 6
23 W1610 = 7
24 W2250 = 8
25 NWL = 9
26 
27 wlstr = ["410","445","490","550","670","865","1240","1610","2250"]
28 
29 class input(object):
30 
31  def __init__(self, l1b_filepath, st, ct):
32  self.ifile = l1b_filepath
33  print ("Reading sensor data: " + self.ifile)
34  try:
35  self.rfl = np.zeros((NWL,ct[0],ct[1]))
36  self.rfl[W410] = xr.load_dataset(l1b_filepath,group='/observations')['rhot_410'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
37  self.rfl[W445] = xr.load_dataset(l1b_filepath,group='/observations')['rhot_445'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
38  self.rfl[W490] = xr.load_dataset(l1b_filepath,group='/observations')['rhot_490'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
39  self.rfl[W550] = xr.load_dataset(l1b_filepath,group='/observations')['rhot_550'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
40  self.rfl[W670] = xr.load_dataset(l1b_filepath,group='/observations')['rhot_670'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
41  self.rfl[W865] = xr.load_dataset(l1b_filepath,group='/observations')['rhot_865'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
42  self.rfl[W1240] = xr.load_dataset(l1b_filepath,group='/observations')['rhot_1240'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
43  self.rfl[W1610] = xr.load_dataset(l1b_filepath,group='/observations')['rhot_1610'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
44  self.rfl[W2250] = xr.load_dataset(l1b_filepath,group='/observations')['rhot_2250'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
45  self.sza = xr.load_dataset(l1b_filepath,group='/geolocation')['solar_zenith'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
46  self.vza = xr.load_dataset(l1b_filepath,group='/geolocation')['sensor_zenith'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
47  self.raa = xr.load_dataset(l1b_filepath,group='/geolocation')['relative_azimuth'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
48  self.lat = xr.load_dataset(l1b_filepath,group='/navigation_data')['latitude'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
49  self.lon = xr.load_dataset(l1b_filepath,group='/navigation_data')['longitude'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
50  self.cld = xr.load_dataset(l1b_filepath,group='/ancillary')['cloud_mask'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
51  self.wnd = xr.load_dataset(l1b_filepath,group='/ancillary')['wind_speed'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
52 # self.chl = xr.load_dataset(l1b_filepath,group='/ancillary')['chlorophyll'].values[st[0]:st[0]+ct[0],st[1]:st[1]+ct[1]]
53  self.rfl = np.transpose(self.rfl, (1,2,0))
54  self.shape = self.sza.shape
55  except Exception as inst:
56  print(type(inst))
57  print(inst)
58  print ("Unable to read from file ... exiting")
59  sys.exit()
60 
61 class output(object):
62 
63  def __init__(self, out_filepath, ydim, xdim):
64  self.ofile = out_filepath
65  self.ydim = ydim
66  self.xdim = xdim
67  try:
68  rfl = xr.DataArray(np.zeros((NWL,ydim,xdim)),dims=('wl','y', 'x'))
69  lat = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
70  lon = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
71  sza = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
72  vza = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
73  raa = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
74  wnd = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
75  chl = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
76  aot = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
77  fmf = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
78  sse = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
79  typ = xr.DataArray(np.zeros((ydim,xdim)),dims=('y', 'x'))
80  self.ds = xr.Dataset({'rfl': rfl, 'lat': lat, 'lon': lon,
81  'sza': sza, 'vza': vza, 'raa': raa,
82  'wnd': wnd, 'chl': chl, 'aot': aot,
83  'fmf': fmf, 'sse': sse, 'typ': typ})
84  except Exception as inst:
85  print(type(inst))
86  print(inst)
87  print ("Unable to initialize output file ... exiting")
88  sys.exit()
89 
90  def write(self):
91  print ("Writing to file: " + self.ofile)
92  self.ds.to_netcdf(self.ofile)
93 
94 def main():
95 
96  parser = argparse.ArgumentParser()
97  parser.add_argument("-af", "--alg",
98  help="algorithm name", required=True)
99  parser.add_argument("-if", "--ifile", type=argparse.FileType('r'),
100  help="input file", required=True)
101  parser.add_argument("-of", "--ofile", type=argparse.FileType('w'),
102  help="output file", required=False)
103  parser.add_argument("-lf", "--lut", type=argparse.FileType('r'),
104  help="lookup table file", required=True)
105  parser.add_argument("-pf", "--plot", type=bool, default=False,
106  help="plot pixel data", required=False)
107  parser.add_argument("-mf", "--mode", type=int, default=0,
108  help="mode option", required=False)
109  parser.add_argument("-um", "--unmask", type=bool, default=False,
110  help="ignore masks", required=False)
111  parser.add_argument("y", type=int, help="start line")
112  parser.add_argument("x", type=int, help="start pixel")
113  parser.add_argument("z", type=int, help="square side ")
114 
115  args = parser.parse_args()
116  dimx = dimy = args.z
117  if (args.z <= 0):
118  args.y = args.x = 0
119  vin = input(args.ifile.name)
120  dimy = vin.shape[0]
121  dimx = vin.shape[1]
122  else:
123  vin = input(args.ifile.name, [args.y,args.x], [dimy,dimx])
124 
125  vout = output(args.ofile.name, dimy, dimx)
126 
127  if (args.alg == "deepblue"):
128  dtdb = dbocean(args.lut.name, args.mode)
129  elif (args.alg == "darktarget"):
130  dtdb = dtocean(args.lut.name, args.mode)
131  else:
132  print ("invalid algorithm")
133  sys.exit()
134 
135  if (args.mode == 2):
136  print ("\nProcessing statistics mode {0}".format(args.mode))
137 
138  refwl = W865
139  nbins = 100
140  pca10 = np.clip(vin.rfl[:,:,refwl].flatten(), a_min=0.0001, a_max=1.0)
141  pca20 = np.log10(pca10)
142  hist = np.zeros((NWL, nbins, nbins))
143  cmap = cm.get_cmap('jet') # Get desired colormap - you can change this!
144  fig = plt.figure()
145  bticks = True
146  for wl in range(NWL):
147 
148  pca1 = np.clip(vin.rfl[:,:,wl].flatten(), a_min=0.0001, a_max=1.0)
149  pca2 = np.log10(pca1)
150 
151  try:
152  hist[wl], edges = np.histogramdd((pca20,pca2-pca20), range=[[-2.0,0.0],[-1.0,1.0]],bins=nbins, density=True)
153  except Exception as inst:
154  print(type(inst))
155  print(inst)
156  print ("Numpy.histogramdd failure ... exiting")
157  sys.exit()
158 
159 # ax2 = fig.add_subplot(121, projection='3d')
160  ax2 = fig.add_subplot(1,9,wl+1)
161  xpos0, ypos0 = np.meshgrid(edges[0][:-1]+edges[0][1:], edges[1][:-1]+edges[1][1:])
162  cp2 = ax2.contourf(xpos0/2, ypos0/2, hist[wl].T, levels=100, cmap=cmap)
163  plt.tick_params(labelleft=bticks, left=bticks)
164  plt.grid(b=True, which='major', color='#666666', linestyle='-')
165  plt.minorticks_on()
166  plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
167  ax2.set_title("RHOT_"+wlstr[wl])
168  ax2.set_xlabel("log10 (RHOT_"+wlstr[refwl]+")")
169  if bticks:
170  ax2.set_ylabel("log10(RHOT_X) - log10(RHOT_"+wlstr[refwl]+")")
171  bticks = False
172  fig.colorbar(cp2)
173  path, fname = os.path.split(args.ifile.name)
174  plt.suptitle(fname)
175  plt.show()
176 
177  elif (args.mode == 1):
178  print ("\nProcessing tensor mode {0}".format(args.mode))
179 
180  sy = [args.y,args.y+dimy]
181  sx = [args.x,args.x+dimx]
182 
183  remaining = dimy
184  count = 0
185  CHUNK = 10
186  cy = [args.y,args.y+dimy]
187  while (remaining > CHUNK):
188 
189  chnk = min(CHUNK,remaining)
190  cy[0] += CHUNK
191  cy[1] = cy[0] + chnk
192  rfl = vin.rfl[cy[0]:cy[1],sx[0]:sx[1]]
193  lat = vin.lat[cy[0]:cy[1],sx[0]:sx[1]]
194  lon = vin.lon[cy[0]:cy[1],sx[0]:sx[1]]
195  sza = vin.sza[cy[0]:cy[1],sx[0]:sx[1]]
196  vza = vin.vza[cy[0]:cy[1],sx[0]:sx[1]]
197  raa = vin.raa[cy[0]:cy[1],sx[0]:sx[1]]
198  wnd = vin.wnd[cy[0]:cy[1],sx[0]:sx[1]]
199 # chl = vin.chl[cy[0]:cy[1],sx[0]:sx[1]]
200 
201  fmf,aot,sse,typ = dtdb.proc_gran(rfl,sza,vza,raa,wnd)
202 
203  oy = [cy[0] - args.y, cy[1] - args.y]
204  vout.ds.rfl[:,oy[0]:oy[1],sx[0]:sx[1]] = rfl.transpose((2,0,1))
205  vout.ds.lat[oy[0]:oy[1],sx[0]:sx[1]] = lat
206  vout.ds.lon[oy[0]:oy[1],sx[0]:sx[1]] = lon
207  vout.ds.sza[oy[0]:oy[1],sx[0]:sx[1]] = sza
208  vout.ds.vza[oy[0]:oy[1],sx[0]:sx[1]] = vza
209  vout.ds.raa[oy[0]:oy[1],sx[0]:sx[1]] = raa
210  vout.ds.wnd[oy[0]:oy[1],sx[0]:sx[1]] = wnd
211 # vout.ds.chl[oy[0]:oy[1],sx[0]:sx[1]] = chl
212  vout.ds.aot[oy[0]:oy[1],sx[0]:sx[1]] = aot
213  vout.ds.fmf[oy[0]:oy[1],sx[0]:sx[1]] = fmf
214  vout.ds.sse[oy[0]:oy[1],sx[0]:sx[1]] = sse
215  vout.ds.typ[oy[0]:oy[1],sx[0]:sx[1]] = typ
216 
217  remaining -= CHUNK
218  count += 1
219  else:
220  print ("\nProcessing pixel mode {0}".format(args.mode))
221  for iy in range(dimy):
222  tic = time.perf_counter()
223  tip =0
224  for ix in range(dimx):
225 
226  if(vin.cld[iy,ix] and not args.unmask):
227  fmf,aot,chl,wnd,sse = -999.9, -999.9, -999.9, -999.9, -999.9
228  else:
229  try:
230  fmf,aot,wnd,sse,aero = dtdb.process(vin.rfl[iy,ix],vin.sza[iy,ix],
231  vin.vza[iy,ix],vin.raa[iy,ix],vin.wnd[iy,ix])
232  except Exception as inst:
233  print(type(inst))
234  print(inst)
235  print ("processing error at pixel", iy, ix)
236 
237  if(args.plot):
238  dtdb.plot(iy,ix)
239 # dtdb.plot_points()
240 
241  vout.ds.rfl[:,iy,ix] = vin.rfl[iy,ix]
242  vout.ds.lat[iy,ix] = vin.lat[iy,ix]
243  vout.ds.lon[iy,ix] = vin.lon[iy,ix]
244  vout.ds.sza[iy,ix] = vin.sza[iy,ix]
245  vout.ds.vza[iy,ix] = vin.vza[iy,ix]
246  vout.ds.raa[iy,ix] = vin.raa[iy,ix]
247  vout.ds.wnd[iy,ix] = wnd
248 # vout.ds.chl[iy,ix] = chl
249  vout.ds.aot[iy,ix] = aot
250  vout.ds.fmf[iy,ix] = fmf
251  vout.ds.sse[iy,ix] = sse
252 
253  toc = time.perf_counter()
254  tpp = (toc-tic)/dimx
255 # print('.', end = '', flush=True)
256  print(iy, tpp, " sec per pixel", flush=True)
257  print(' Done!')
258  vout.write()
259 
260 if __name__ == "__main__":
261 
262  main()
def write(self)
Definition: dtdb.py:68
def main()
Definition: dtdb.py:72
character(len=1000) if
Definition: names.f90:13
def __init__(self, out_filepath, ydim, xdim)
Definition: dtdb.py:42
def __init__(self, l1b_filepath)
Definition: dtdb.py:18