obpg-orm 1.1.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. obpg_orm-1.1.5.data/data/data/aph_bricaud_1998.txt +163 -0
  2. obpg_orm-1.1.5.data/data/data/f.dat +491 -0
  3. obpg_orm-1.1.5.data/data/data/f0_tsis_1nm_v2.nc +0 -0
  4. obpg_orm-1.1.5.data/data/data/fp.dat +491 -0
  5. obpg_orm-1.1.5.data/data/data/mm01_kbio.nc +0 -0
  6. obpg_orm-1.1.5.data/data/data/mm01_kbio.txt +72 -0
  7. obpg_orm-1.1.5.data/data/data/morel_fq.nc +0 -0
  8. obpg_orm-1.1.5.data/data/data/morel_fq_appb.dat +34 -0
  9. obpg_orm-1.1.5.data/data/data/morel_fq_appb.nc +0 -0
  10. obpg_orm-1.1.5.data/data/data/morel_fq_hyperspectral.nc +0 -0
  11. obpg_orm-1.1.5.data/data/data/morel_mud_f_fp.nc +0 -0
  12. obpg_orm-1.1.5.data/data/data/mud.dat +491 -0
  13. obpg_orm-1.1.5.data/data/data/thuillier.dat +730 -0
  14. obpg_orm-1.1.5.data/data/data/thuillier2003_f0.nc +0 -0
  15. obpg_orm-1.1.5.data/data/data/water_spectra.nc +0 -0
  16. obpg_orm-1.1.5.data/data/docs/get_brdf.md +49 -0
  17. obpg_orm-1.1.5.data/data/docs/get_f0.md +31 -0
  18. obpg_orm-1.1.5.data/data/docs/morel_read.md +34 -0
  19. obpg_orm-1.1.5.data/data/docs/utils.md +30 -0
  20. obpg_orm-1.1.5.dist-info/METADATA +105 -0
  21. obpg_orm-1.1.5.dist-info/RECORD +49 -0
  22. obpg_orm-1.1.5.dist-info/WHEEL +5 -0
  23. obpg_orm-1.1.5.dist-info/entry_points.txt +5 -0
  24. obpg_orm-1.1.5.dist-info/top_level.txt +1 -0
  25. orm/__init__.py +0 -0
  26. orm/data/aph_bricaud_1998.txt +163 -0
  27. orm/data/f.dat +491 -0
  28. orm/data/f0_tsis_1nm_v2.nc +0 -0
  29. orm/data/fp.dat +491 -0
  30. orm/data/mm01_kbio.nc +0 -0
  31. orm/data/mm01_kbio.txt +72 -0
  32. orm/data/morel_fq.nc +0 -0
  33. orm/data/morel_fq_appb.dat +34 -0
  34. orm/data/morel_fq_appb.nc +0 -0
  35. orm/data/morel_fq_hyperspectral.nc +0 -0
  36. orm/data/morel_mud_f_fp.nc +0 -0
  37. orm/data/mud.dat +491 -0
  38. orm/data/thuillier.dat +730 -0
  39. orm/data/thuillier2003_f0.nc +0 -0
  40. orm/data/water_spectra.nc +0 -0
  41. orm/get_brdf.py +185 -0
  42. orm/get_f0.py +150 -0
  43. orm/kbio-netCDF.py +41 -0
  44. orm/model.py +419 -0
  45. orm/morel_fq_appb-netCDF.py +78 -0
  46. orm/morel_read.py +143 -0
  47. orm/mud_f_fp-netCDF.py +77 -0
  48. orm/orm.py +181 -0
  49. orm/utils.py +217 -0
orm/model.py ADDED
@@ -0,0 +1,419 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Ocean Reflectance Model
4
+
5
+ Generates hyperspectral (1nm) or sensor-specific Rrs (or Lwn) spectra using the
6
+ ocean reflectance model described in:
7
+ P. Jeremy Werdell, Sean W. Bailey, Bryan A. Franz, André Morel, and
8
+ Charles R. McClain, "On-orbit vicarious calibration of ocean color sensors
9
+ using an ocean surface reflectance model" Appl. Opt. 46, 5649-5666 (2007),
10
+ https://doi.org/10.1364/AO.46.005649
11
+ """
12
+
13
+
14
+ import math
15
+ from netCDF4 import Dataset
16
+ import numpy as np
17
+ from scipy.interpolate import CubicSpline as spline
18
+ from scipy.interpolate import interp1d
19
+ import scipy.ndimage.filters as filters
20
+
21
+ from orm.get_brdf import get_fq
22
+ import orm.morel_read as morel_read
23
+ from orm.utils import get_data_path, rrs_to_lwn, bandpass_avg_rrs, get_wavelength_array
24
+
25
+ __version__ = '1.1.0'
26
+ verbose = False
27
+
28
+ # Global variables
29
+ wl = get_wavelength_array()
30
+ interp_func_q = None
31
+ bricdat = None
32
+
33
+ verbose = False
34
+
35
+ def rrs_below_to_above(rrs_s, q=3.141529, gordon=False):
36
+ """
37
+ Compute above-water Rrs from sub-surface rrs.
38
+
39
+ Uses Lee et al 2002 or Gordon 1988.
40
+
41
+ Inputs:
42
+ subsurface remote-sensing reflectance
43
+ Q parameter (for Gordon - defaults to PI)
44
+ Output:
45
+ above-water remote-sensing reflectance
46
+ """
47
+ if gordon:
48
+ rho = 0.021
49
+ rho_bar = 0.043
50
+ r_eu = 0.48
51
+ m = 1.34
52
+
53
+ t = ((1. - rho) * (1. - rho_bar)) / (np.power(m,2) * (1. - r_eu * rrs_s))
54
+ rrs_a = t * rrs_s / q
55
+
56
+ else:
57
+ rrs_a = (0.52 * rrs_s) / (1.0 - 1.7 * rrs_s)
58
+
59
+ return rrs_a
60
+
61
+
62
+ def get_mm01_bb(chl):
63
+ """
64
+ Retrieve backscattering coefficient for a given chlorophyll concentration.
65
+
66
+ Based on Loisel and Morel 1998, Ciotti et al 1999, and
67
+ Morel and Maritorena 2001.
68
+ """
69
+ global wl
70
+
71
+ # Backscattering coefficient for seawater
72
+ bbw = 0.0038 * np.power(400./wl, 4.32)
73
+
74
+ # Loisel and Morel 1998 bbp function
75
+ bp550 = 0.416 * np.power(chl, 0.766)
76
+
77
+ # Morel and Maritorena 2001 bbp with v from Ciotti et al. 1999
78
+ v = 0.768 * np.log10(chl) - 1.
79
+
80
+ bbp = (0.002 + 0.01 * (0.5 - 0.25 * np.log10(chl))) * np.power(wl[:,np.newaxis] / 550.,v) * bp550
81
+ bb = bbp + bbw[:, np.newaxis]
82
+
83
+ return np.squeeze(bb)
84
+
85
+
86
+ def get_mm01_kd(chl):
87
+ """
88
+ Compute diffuse attenuation coefficient from chlorophyll concentration.
89
+
90
+ Based on Morel and Maritorena 2001
91
+ Kd = Kw + X chl^e
92
+ """
93
+ global wl
94
+ kbiofile = get_data_path() / 'mm01_kbio.nc'
95
+ data = Dataset(kbiofile, 'r')
96
+ X = data['X'][:]
97
+ e = data['e'][:]
98
+ kw = data['kw'][:]
99
+ wavelength = data['wavelength'][:]
100
+
101
+ k0 = X[:, np.newaxis] * np.power(chl, e[:, np.newaxis]) + kw[:, np.newaxis]
102
+
103
+ cs = spline(wavelength, k0)
104
+ kd = cs(wl)
105
+
106
+ return np.squeeze(kd)
107
+
108
+
109
+ def get_morel_mud(chl, solz):
110
+ """
111
+ Compute mean cosine for downward flux.
112
+
113
+ A. Morel, personal communication, Summer 2006
114
+ """
115
+ mud = morel_read.morel_read(chl, solz, mud=True)
116
+
117
+ return mud
118
+
119
+
120
+ def get_morel_fq(chl, solz):
121
+ """
122
+ Retrieve f and Q given chlorophyll and solar zenith angle.
123
+
124
+ Morel et al. 2002, Appendix B for use with in-water data
125
+ (senz = 0 and relaz = 0)
126
+ """
127
+ global wl
128
+ global interp_func_q
129
+
130
+ if interp_func_q is None:
131
+ print("Initializing q table interpolation")
132
+ interp_func_q = morel_read.morel_q_interp()
133
+
134
+ interp_arr = np.meshgrid(solz, chl, wl)
135
+ flat = np.array([m.flatten() for m in interp_arr])
136
+ out_array = interp_func_q(flat.T)
137
+ q = np.moveaxis(out_array.reshape(*interp_arr[0].shape), -1, 0)
138
+ if solz.size > 1:
139
+ q = np.diagonal(q, axis1=1, axis2=2)
140
+
141
+ f = morel_read.morel_read(chl, solz, fp=True)
142
+
143
+ f = np.squeeze(f)
144
+ q = np.squeeze(q)
145
+ return (f, q)
146
+
147
+
148
+ def get_aw():
149
+ """Get pure water absorption and interpolate to sensor wavelength."""
150
+ specFile = get_data_path() / "water_spectra.nc"
151
+ spec = Dataset(specFile, 'r')
152
+ wvl = spec['wavelength'][:]
153
+ idx = np.where(np.logical_and(wvl >= 300, wvl <= 900))
154
+ aw = spec['aw'][:]
155
+ bw = spec['bw'][:]
156
+ spec.close()
157
+
158
+ return aw[idx], bw[idx]/2.
159
+
160
+
161
+ def get_bricaud_aph(chl, normalize=False):
162
+ """
163
+ Get the bricaud phytoplankton absorption shape.
164
+
165
+ Bricaud et al., JGR 103, 31033-31044, 1998
166
+ Inputs:
167
+ chl: chlorophyll-a pigment concentration
168
+ norm: logic flag to normalise aph* to 0.055 as per GIOP method
169
+
170
+ Ouputs:
171
+ ap: particulate absorption coefficient (Ap Chl^Ep)
172
+ aps: normalised particle absorption coefficient (Ap Chl^(Ep-1))
173
+ aph: phytoplankton absorption coefficient (Aph Chl^Eph)
174
+ aphs: normalised phytoplankton absorption coefficient (Aph Chl^(Eph-1))
175
+ """
176
+ global wl
177
+ global bricdat
178
+
179
+ # Load files once
180
+ if bricdat is None:
181
+ # bricaud_1998_aph.txt order of columns: wl,Ap,Ep,Aph,Eph
182
+ bricFile = get_data_path() / "aph_bricaud_1998.txt"
183
+ print("Loading {}".format(str(bricFile)))
184
+ bricdat = np.genfromtxt(bricFile, delimiter=',', skip_header=12)
185
+ chl = np.atleast_1d(chl)
186
+ ap0 = bricdat[:, 1] * np.power(chl[:, np.newaxis], bricdat[:, 2])
187
+ aps0 = bricdat[:, 1] * np.power(chl[:, np.newaxis], (bricdat[:, 2] - 1))
188
+ aph0 = bricdat[:, 3] * np.power(chl[:, np.newaxis], bricdat[:, 4])
189
+ aphs0 = bricdat[:, 3] * np.power(chl[:, np.newaxis], (bricdat[:, 4] - 1))
190
+
191
+ # Normalize aph
192
+ if normalize:
193
+ idx442 = np.where(bricdat[:, 0] == 442)[0][0]
194
+ aphs442 = aphs0[:, idx442]
195
+ aphs0 = aphs0 * 0.055 / aphs442[:, np.newaxis]
196
+
197
+ # Interpolate to sensor wavelength
198
+ ap = interp1d(bricdat[:, 0], ap0, bounds_error=False,
199
+ kind='cubic', fill_value=0.0)
200
+ aps = interp1d(bricdat[:, 0], aps0, bounds_error=False,
201
+ kind='cubic', fill_value=0.0)
202
+ aph = interp1d(bricdat[:, 0], aph0, bounds_error=False,
203
+ kind='cubic', fill_value=0.0)
204
+ aphs = interp1d(bricdat[:, 0], aphs0,
205
+ bounds_error=False, kind='cubic', fill_value=0.0)
206
+
207
+ return ap(wl), aps(wl), aph(wl), aphs(wl)
208
+
209
+
210
+ def extrap_aph(chl, normalize=False):
211
+ """
212
+ Extrapolate aphStar into the UV and NIR.
213
+
214
+ Inputs:
215
+ chl: chlorophyll-a pigment concentration (float)
216
+
217
+ Ouputs:
218
+ aphStar: extrapolated normalised phytoplankton absorption shape
219
+ """
220
+ global wl
221
+ ap, aps, aph, aphs = get_bricaud_aph(chl, normalize=normalize)
222
+
223
+ # very, very ad-hoc extrapolation from 400 down to 350 nm, then spectrally
224
+ # flat from from 350 nm to shorter wavelengths
225
+ i350 = np.where(wl == 350)[0].item()
226
+ i400 = np.where(wl == 400)[0].item()
227
+ i405 = np.where(wl == 405)[0].item()
228
+ i410 = np.where(wl == 410)[0].item()
229
+ i443 = np.where(wl == 443)[0].item()
230
+ i700 = np.where(wl == 700)[0].item()
231
+
232
+ # The 0.5 factor here is arbitrary to stop extrapolations going negative
233
+ aph_slope = 0.5*(aphs[:, i443] - aphs[:, i410]) / (443 - 410)
234
+ aph_int = aphs[:, i443] - aph_slope*443
235
+ lamUV = wl[i350:i405]
236
+ aphUV = aph_slope*lamUV[:, np.newaxis] + aph_int
237
+ delta_aphs = aphUV[-1] - aphs[:, i405]
238
+ aphUV = aphUV - delta_aphs
239
+
240
+ aphs[:, i350:i405] = np.transpose(aphUV)
241
+ aphs[:, 0:i350] = (aphs[:, i350])[:, np.newaxis]
242
+
243
+ # Wavelengths longer than 700 nm extrapolated using a smooth exponential
244
+ # decay curve. Curve shape derived from selection of SeaBASS measurements
245
+ p = np.array((-0.0789811, 55.12363434))
246
+ aph700Nir = np.exp(p[1])*np.exp(wl[i700:]*p[0])
247
+
248
+ aphs[:, i700:] = aph700Nir*(aphs[:, i700])[:, np.newaxis]
249
+
250
+ aphUV = np.array([0.8168912, 0.81677942, 0.81650336, 0.81598752,
251
+ 0.81518127, 0.81410382, 0.81286164, 0.81162225,
252
+ 0.81055652, 0.80978012, 0.80932177, 0.80912699,
253
+ 0.80909137, 0.80910478, 0.8091019, 0.80910205,
254
+ 0.80921815, 0.80962099, 0.8104629, 0.81180237,
255
+ 0.81357246, 0.815613, 0.81774113, 0.81981493,
256
+ 0.82175759, 0.82354585, 0.8251863, 0.82670197,
257
+ 0.82812943, 0.82951537, 0.83089821, 0.8322774,
258
+ 0.8335878, 0.8346934, 0.83540505, 0.83551171,
259
+ 0.83480672, 0.83310557, 0.83026425, 0.82620653,
260
+ 0.82095056, 0.81461136, 0.80736381, 0.79937762,
261
+ 0.79076349, 0.78156979, 0.77183674, 0.76168252,
262
+ 0.75136854, 0.74130173, 0.73196185, 0.72378628,
263
+ 0.71706382, 0.711885, 0.70816165, 0.70569461,
264
+ 0.70425134, 0.70362551, 0.70367264, 0.70432556,
265
+ 0.70559371, 0.70753984, 0.71023409, 0.71370017,
266
+ 0.71788149, 0.72265037, 0.72785336, 0.7333654,
267
+ 0.73912123, 0.74511257, 0.75136361, 0.75790804,
268
+ 0.76477631, 0.7719909, 0.77955978, 0.78746745,
269
+ 0.7956687, 0.80409496, 0.81267063, 0.82132997,
270
+ 0.83002155, 0.83869668, 0.84729066, 0.85571288,
271
+ 0.86385694, 0.87162939, 0.87898592, 0.88595694,
272
+ 0.89265189, 0.8992391, 0.90590968, 0.91283903,
273
+ 0.9201604, 0.92795851, 0.93628156, 0.9451633,
274
+ 0.9546435, 0.96478, 0.9756518, 0.98735552, 1.])
275
+
276
+ lamAphUV = np.linspace(300, 400., 101)
277
+
278
+ aphUVI = interp1d(lamAphUV, aphUV, bounds_error=False,
279
+ kind='cubic', fill_value=0.0)
280
+ aphUV_temp = aphUVI(wl[0:i400+1])
281
+
282
+ aphUV = aphUV_temp*(aphs[:, i400])[:, np.newaxis]
283
+
284
+ aphs[:, 0:i400+1] = aphUV
285
+
286
+ # smooth a little using a gaussain convolution filter
287
+ # For this excercise, we are simulating Rrs for testing processing
288
+ # capabilities and not algorithm skill
289
+ aphs = filters.gaussian_filter1d(aphs, sigma=2)
290
+
291
+ # normalise to 1 at 443 nm
292
+ aphStar = aphs/(aphs[:, i443])[:, np.newaxis]
293
+
294
+ return aphStar.T
295
+
296
+
297
+ def morel_rrs(chl, solz=None, wvl=None, bandpass=11,
298
+ lwn=False, mm01iter=True, use_fq=False, tsis=False):
299
+ """
300
+ Calculate Rrs given chlorophyll and solar zenith angle.
301
+
302
+ Based mostly on Morel and Maritorena 2001
303
+ Rrs = trans * (f / Q) * {bb / (a + bb)}, where (a + bb) ~ mud * Kd
304
+ """
305
+ global wl
306
+ global verbose
307
+
308
+ # Default solar zenith angle is 30-degrees
309
+ if solz is None:
310
+ solz = np.atleast_1d(30.)
311
+ else:
312
+ solz = np.atleast_1d(solz)
313
+
314
+ chl = np.atleast_1d(chl)
315
+
316
+ # Backscattering coefficient
317
+ bb = get_mm01_bb(chl)
318
+
319
+ # Diffuse attenuation coefficient
320
+ kd = get_mm01_kd(chl)
321
+
322
+ # Mean cosine for downward flux
323
+ mud = get_morel_mud(chl, solz)
324
+
325
+ # f and Q
326
+ (f, q) = get_morel_fq(chl, solz)
327
+ if use_fq:
328
+ fq = get_fq(solz, 0., 0., chl, wvl=wvl)
329
+ f = fq * q
330
+
331
+ # Morel and Maritorena 2001, Morel et al. 2007 iteration
332
+ u2 = mud
333
+ r0 = f * bb / (u2 * kd + bb)
334
+
335
+ if mm01iter:
336
+ # Iterate 3 times
337
+ for i in range(3):
338
+ u2 = mud * (1. - r0) / (1. + mud * r0 / 0.4)
339
+ atot = 0.962 * kd * mud * (1. - r0 / f)
340
+ r0 = f * bb / (atot + bb)
341
+ else:
342
+ # Iterate until convergence
343
+ last_r0 = r0 + 2.
344
+ iterations = 0
345
+ close_enough = False
346
+ while close_enough is False:
347
+ iterations += 1
348
+ u2 = mud * (1. - r0) / (1. + mud * r0 / 0.4)
349
+ atot = 0.962 * kd * mud * (1. - r0 / f)
350
+ r0 = f * bb / (atot + bb)
351
+ close_enough = True
352
+ for i in range(len(r0)):
353
+ if not math.isclose(r0[i], last_r0[i], rel_tol=1e-07):
354
+ last_r0[i] = r0[i]
355
+ close_enough = False
356
+ continue
357
+ if close_enough:
358
+ break
359
+
360
+ if verbose:
361
+ print("MM01 iterations: %d" % iterations)
362
+
363
+ # Transmission across the air-sea interface
364
+ rrs = rrs_below_to_above(r0, q, gordon=True)
365
+
366
+ # lwn instead of rrs
367
+ if lwn:
368
+ rrs = rrs_to_lwn(rrs, tsis=tsis)
369
+
370
+ # Bandpass averages centered on discrete lambda
371
+ if wvl is not None:
372
+ rrs = bandpass_avg_rrs(rrs, wvl, bandpass=bandpass)
373
+
374
+ return rrs
375
+
376
+
377
+ def gordon_rrs(adg, aph, bbp, bbp_s, chl, lwn=False, wvl=None, bandpass=11, tsis=False):
378
+ """
379
+ Calculate Rrs given chlorophyll and IOPs.
380
+
381
+ Uses the Gordon quadratic formulation.
382
+ """
383
+ global wl
384
+ aw, bbw = get_aw()
385
+ g0 = 0.0949
386
+ g1 = 0.0794
387
+
388
+ # Model adgStar spectra
389
+ madgStar = np.exp(-0.018 * (wl[:, np.newaxis]-443.))
390
+
391
+ # Get extrapolated aphStar spectra
392
+ maphStar = extrap_aph(chl, normalize=False)
393
+
394
+ # Get bbpStar spectra
395
+ mbbpStar = np.power((443./wl[:, np.newaxis]), bbp_s)
396
+
397
+ # Compute total backscattering
398
+ bbtot = np.squeeze(bbp * mbbpStar + bbw[:, np.newaxis])
399
+ # bbtot = get_mm01_bb(chl)
400
+
401
+ # Compute total absorption
402
+ atot = np.squeeze(aw[:, np.newaxis] + adg * madgStar + aph * maphStar)
403
+
404
+ kappa = atot + bbtot
405
+ u = bbtot / kappa
406
+ rrs = np.squeeze((g0 + g1 * u) * u)
407
+
408
+ # Transmission across the air-sea interface
409
+ Rrs = rrs_below_to_above(rrs)
410
+
411
+ # lwn instead of rrs
412
+ if lwn:
413
+ Rrs = rrs_to_lwn(Rrs, tsis=tsis)
414
+
415
+ # Bandpass averages centered on discrete lambda
416
+ if wvl is not None:
417
+ Rrs = bandpass_avg_rrs(Rrs, wvl, bandpass=bandpass)
418
+
419
+ return Rrs
@@ -0,0 +1,78 @@
1
+ """
2
+ Script that generates the Morel f/Q tables as a NetCDF.
3
+
4
+ Tables 1 and 2 from appendix b of morel et al. (2002)
5
+ wl (columns): 412.5, 442.5, 490, 510, 560, 620, 660
6
+ chl (rows): 0.03, 0.1, 0.3, 1, 3, 10
7
+
8
+ """
9
+ import numpy as np
10
+ from netCDF4 import Dataset
11
+ from datetime import datetime
12
+ import time
13
+
14
+ f0 = [[0.297892, 0.311742, 0.347280, 0.359728, 0.375008, 0.370053, 0.372716],
15
+ [0.324018, 0.328848, 0.345755, 0.350503, 0.358735, 0.350497, 0.349206],
16
+ [0.340239, 0.341657, 0.350980, 0.349334, 0.349570, 0.334437, 0.330755],
17
+ [0.351673, 0.352505, 0.362207, 0.359773, 0.357388, 0.327275, 0.320913],
18
+ [0.359587, 0.360429, 0.374357, 0.376513, 0.383433, 0.335178, 0.323731],
19
+ [0.370570, 0.370782, 0.389128, 0.397841, 0.424316, 0.362306, 0.340204]]
20
+
21
+ sf = [[0.065801, 0.076526, 0.095435, 0.103901, 0.121165, 0.134426, 0.143912],
22
+ [0.095786, 0.111534, 0.138252, 0.147280, 0.169210, 0.183429, 0.195362],
23
+ [0.131988, 0.154209, 0.191203, 0.201694, 0.225606, 0.227381, 0.236441],
24
+ [0.183170, 0.213187, 0.261757, 0.276009, 0.305781, 0.284162, 0.285455],
25
+ [0.239626, 0.273898, 0.330935, 0.349059, 0.386471, 0.352961, 0.343078],
26
+ [0.316124, 0.351720, 0.415626, 0.438584, 0.482277, 0.457638, 0.433943]]
27
+
28
+ q0 = [[3.318220, 3.291250, 3.245640, 3.176500, 3.138020, 3.116680, 3.126530],
29
+ [3.375400, 3.385700, 3.408430, 3.359680, 3.336890, 3.309970, 3.332380],
30
+ [3.484950, 3.529680, 3.613410, 3.601660, 3.606950, 3.542300, 3.560200],
31
+ [3.675060, 3.746830, 3.868930, 3.894090, 3.942030, 3.815240, 3.801910],
32
+ [3.913530, 3.991380, 4.110030, 4.141140, 4.188650, 4.104160, 4.053610],
33
+ [4.252700, 4.313260, 4.393950, 4.405460, 4.368130, 4.427190, 4.371050]]
34
+
35
+ sq = [[0.863223, 0.976278, 1.129290, 1.203100, 1.296770, 1.413010, 1.479420],
36
+ [1.055510, 1.190090, 1.382130, 1.482910, 1.625960, 1.775070, 1.866290],
37
+ [1.302830, 1.469930, 1.700680, 1.827460, 2.036100, 2.175700, 2.269360],
38
+ [1.671180, 1.877700, 2.115910, 2.239960, 2.479820, 2.711180, 2.789710],
39
+ [2.083950, 2.303690, 2.506640, 2.580090, 2.707700, 3.141310, 3.229040],
40
+ [2.625950, 2.843750, 2.978790, 2.986960, 2.898750, 3.527960, 3.717540]]
41
+
42
+ # Create the netCDF file and add dimensions
43
+ dataset = Dataset('morel_fq_appb.nc', 'w', format='NETCDF4')
44
+ dataset.createDimension('nchl', 6)
45
+ dataset.createDimension('nwavelengths', 7)
46
+
47
+ # Set global attributes
48
+ dataset.title = "Morel f/Q table"
49
+ dataset.date_created = (datetime.fromtimestamp(
50
+ time.time()).strftime('%Y-%m-%dT%H:%M:%SZ')).encode('ascii')
51
+ dataset.creator_name = "Sean Bailey, NASA/GSFC/OBPG"
52
+ dataset.creator_email = "data@oceancolor.gsfc.nasa.gov"
53
+ dataset.creator_url = "https://oceancolor.gsfc.nasa.gov"
54
+ dataset.product_name = "morel_fq_appb.nc'"
55
+
56
+ # Create the table data sets
57
+ f0SDS = dataset.createVariable('f0', np.float32, ('nchl', 'nwavelengths'))
58
+ sfSDS = dataset.createVariable('sf', np.float32, ('nchl', 'nwavelengths'))
59
+ q0SDS = dataset.createVariable('q0', np.float32, ('nchl', 'nwavelengths'))
60
+ sqSDS = dataset.createVariable('sq', np.float32, ('nchl', 'nwavelengths'))
61
+ wavelength = dataset.createVariable(
62
+ 'wavelength', np.float32, ('nwavelengths',))
63
+ chlorophyll = dataset.createVariable('chlorophyll', np.float32, ('nchl',))
64
+
65
+ # Write the data
66
+ f0SDS[:] = f0
67
+ sfSDS[:] = sf
68
+ q0SDS[:] = q0
69
+ sqSDS[:] = sq
70
+ wavelength[:] = np.array([412.5, 442.5, 490, 510, 560, 620, 660])
71
+ chlorophyll[:] = np.array([0.03, 0.1, 0.3, 1, 3, 10])
72
+
73
+ # Add some variable attributes
74
+ wavelength.units = 'nm'
75
+ chlorophyll.units = 'mg/m3'
76
+
77
+ # Close the file
78
+ dataset.close()
orm/morel_read.py ADDED
@@ -0,0 +1,143 @@
1
+ """Modules that read in Morel Tables."""
2
+ import argparse
3
+ import sys
4
+ import numpy as np
5
+ from netCDF4 import Dataset
6
+ from scipy.interpolate import RegularGridInterpolator as rgi
7
+ import os
8
+
9
+ wl = np.linspace(300, 900., 601)
10
+ interp_func_mud = None
11
+ interp_func_fn = None
12
+ interp_func_fp = None
13
+
14
+ def get_script_path():
15
+ """Return path to orm_morel table."""
16
+ return os.path.join(os.path.dirname(__file__),'data')
17
+
18
+ def morel_table_interp(mud=False, fn=False, fp=False):
19
+ """Read Morel f, fp, and mud tables and interpolate."""
20
+ mudfile = os.path.join(get_script_path(), 'morel_mud_f_fp.nc')
21
+ ncfile = Dataset(mudfile, 'r')
22
+ data = None
23
+ if mud:
24
+ data = ncfile['mud'][:, :, :]
25
+ elif fn:
26
+ data = ncfile['f'][:, :, :]
27
+ elif fp:
28
+ data = ncfile['fp'][:, :, :]
29
+
30
+ if data is None:
31
+ print, ''
32
+ print, 'Error: please indicate mud, f, or fp'
33
+ print, ''
34
+ sys.exit(-1)
35
+
36
+ grdwvl = ncfile['wavelength'][:]
37
+ grdchl = ncfile['chlorophyll'][:]
38
+ grdsolz = ncfile['solz'][:]
39
+
40
+ interp_func = rgi((grdsolz, grdwvl, grdchl), data,
41
+ fill_value=None, bounds_error=False)
42
+
43
+ return interp_func
44
+
45
+ def morel_q_interp():
46
+ """Read Morel f/Q table and interpolate."""
47
+ fqfile = os.path.join(get_script_path(), 'morel_fq_appb.nc')
48
+
49
+ morel_fq_appb = Dataset(fqfile, 'r')
50
+
51
+ grdwvl = morel_fq_appb['wavelength'][:]
52
+ grdchl = morel_fq_appb['chlorophyll'][:]
53
+ q0 = morel_fq_appb['q0'][:]
54
+ sq = morel_fq_appb['sq'][:]
55
+ grdsolz = np.linspace(0., 60., num=30)
56
+
57
+ z = 1. - np.cos(np.deg2rad(grdsolz))
58
+ q1 = np.empty([grdsolz.size, grdchl.size, grdwvl.size])
59
+ for i, solz in enumerate(grdsolz):
60
+ q1[i, :, :] = q0 + sq * z[i]
61
+
62
+ return rgi((grdsolz, grdchl, grdwvl), q1,
63
+ fill_value=None, bounds_error=False)
64
+
65
+
66
+ def morel_read(chl, solz, mud=False, fn=False, fp=False):
67
+ """Standalone version, reads Morel tables and interpolates."""
68
+ global interp_func_mud
69
+ global interp_func_fn
70
+ global interp_func_fp
71
+ global wl
72
+ solz = np.atleast_1d(solz)
73
+ chl = np.atleast_1d(chl)
74
+
75
+ if mud:
76
+ if interp_func_mud is None:
77
+ interp_func_mud = morel_table_interp(mud=True)
78
+ print("Initializing mean cosine of downwelling irradiance "
79
+ "interpolation function")
80
+ interp_func = interp_func_mud
81
+ elif fn:
82
+ if interp_func_fn is None:
83
+ interp_func_fn = morel_table_interp(fn=True)
84
+ print("Initializing f interpolation function")
85
+ interp_func = interp_func_fn
86
+ elif fp:
87
+ if interp_func_fp is None:
88
+ interp_func_fp = morel_table_interp(fp=True)
89
+ print("Initializing f-prime interpolation function")
90
+ interp_func = interp_func_fp
91
+ else:
92
+ print, ''
93
+ print, 'Error: please indicate mud, f, or fp'
94
+ print, ''
95
+ sys.exit(-1)
96
+
97
+ interp_arr = np.meshgrid(solz, wl, chl)
98
+ flat = np.array([m.flatten() for m in interp_arr])
99
+ out_array = interp_func(flat.T)
100
+ result = np.squeeze(out_array.reshape(*interp_arr[0].shape))
101
+
102
+ if solz.size > 1:
103
+ result = np.diagonal(result, axis1=1, axis2=2)
104
+
105
+ return result
106
+
107
+ def main():
108
+ """Primary driver for stand-alone version."""
109
+ __version__ = '1.0.0'
110
+
111
+ parser = argparse.ArgumentParser(description='Read Morel tables')
112
+
113
+ parser.add_argument('--version', action='version',
114
+ version='%(prog)s ' + __version__)
115
+ parser.add_argument('chl', type=float, default=None,
116
+ help='input chlorophyll')
117
+ parser.add_argument('solz', type=float, default=None,
118
+ help='input solar zenith angle')
119
+ parser.add_argument('--table','-t', type=str,
120
+ choices=['mud',
121
+ 'fn',
122
+ 'fp'],
123
+ default=None, help='Morel table to interpolate')
124
+ args = parser.parse_args()
125
+
126
+ global wl
127
+
128
+ tables = {'mud':False,
129
+ 'fp':False,
130
+ 'fn':False}
131
+ for table in tables.keys():
132
+ if table == args.table:
133
+ tables[table]=True
134
+
135
+ spectrum = morel_read(args.chl, args.solz, mud=tables['mud'], fp=tables['fp'], fn=tables['fn'])
136
+ outarray = np.column_stack((np.asarray(wl), np.asarray(spectrum)))
137
+ print('\n'.join([' '.join(['{:.6f}'.format(value)
138
+ for value in row])
139
+ for row in outarray]))
140
+
141
+ # The following allows the file to be imported without immediately executing.
142
+ if __name__ == '__main__':
143
+ sys.exit(main())