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/get_brdf.py ADDED
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Estimate f/Q for a given suite of observations.
4
+
5
+ Refs:
6
+ Morel and Gentilli, Applied Optics, 35(24), 1996
7
+ Morel et al., Applied Optics, 41(3), 2002
8
+
9
+ Input:
10
+ wavelength float [w]
11
+ solar zenith angle float [s]
12
+ chl concentration float [chl_in]
13
+ nadir zenith angle float [n]
14
+ azimuth angle float [a]
15
+ f/Q table array fltarr [foq_data]
16
+
17
+ Output:
18
+ f/Q correction term float [fq]
19
+
20
+ 8.20.2003 - translated from get_foq.c by PJW
21
+ """
22
+
23
+ import argparse
24
+ import sys
25
+ import numpy as np
26
+ from netCDF4 import Dataset
27
+ from scipy.interpolate import RegularGridInterpolator as rgi
28
+ from scipy.interpolate import CubicSpline as spline
29
+ import os
30
+
31
+ wl = np.linspace(300, 900., 601)
32
+ interp_func = None
33
+ def get_script_path():
34
+ return os.path.join(os.path.dirname(__file__),'data')
35
+
36
+ def fq_table_interp(use_hyperspectral=False):
37
+ """Load the f/Q datatable for interpolation."""
38
+ fq_filename = 'morel_fq.nc'
39
+ if use_hyperspectral:
40
+ fq_filename = 'morel_fq_hyperspectral.nc'
41
+
42
+ ncfile = Dataset(os.path.join(get_script_path(),fq_filename), 'r')
43
+ data = ncfile['foq'][:, :, :, :, :]
44
+
45
+ grdwvl = ncfile['wave'][:]
46
+ grdchl = np.log(ncfile['chl'][:])
47
+ grdsolz = ncfile['solz'][:]
48
+ grdviewz = ncfile['senz'][:]
49
+ grdrelaz = ncfile['phi'][:]
50
+
51
+ interp_func = rgi((grdwvl, grdsolz, grdchl, grdviewz, grdrelaz), data,
52
+ fill_value=None, bounds_error=False)
53
+
54
+ return interp_func
55
+
56
+
57
+ def get_fq(solz, viewz, relaz, chl, wvl=None, use_hyperspectral=False):
58
+ """Interpolate inputs for f/Q."""
59
+ global wl
60
+
61
+ global interp_func
62
+
63
+ if interp_func is None:
64
+ interp_func = fq_table_interp(use_hyperspectral=use_hyperspectral)
65
+ print("Initializing f/Q interpolation function")
66
+
67
+ runspline = True
68
+ if wvl is None:
69
+ wvl = wl
70
+ runspline = False
71
+
72
+ interp_arr = np.meshgrid(wvl, solz, np.log(chl),
73
+ viewz, relaz, indexing='ij')
74
+ flat = np.array([m.flatten() for m in interp_arr])
75
+ out_array = interp_func(flat.T)
76
+ result = np.squeeze(out_array.reshape(*interp_arr[0].shape))
77
+
78
+ while len(result.shape) > 2:
79
+ result = np.diagonal(result, axis1=1, axis2=2)
80
+
81
+ if runspline:
82
+ cs = spline(wvl, result)
83
+ result = cs(wl)
84
+
85
+ return result
86
+
87
+
88
+ def morel_brdf(chl, solz, viewz, relaz, wvl=None, corr=False, use_hyperspectral=False):
89
+ """
90
+ Calculate the Morel brdf correction.
91
+
92
+ Inputs:
93
+ Chlorophyll concentration
94
+ Solar zenith angle
95
+ Viewing zenith angle
96
+ Relative azimuth angle (solar - sensor)
97
+ Wavelength (default none)
98
+ use_hyperspectral flag (hyperspectral "morel fq" table, default False)
99
+
100
+ Output:
101
+ f/Q correction (unitless)
102
+ """
103
+ h2o = 1.34
104
+ thetap = np.degrees(np.arcsin(np.sin(np.radians(viewz)) / h2o))
105
+
106
+ fqA = np.array(get_fq(solz, thetap, relaz, chl, wvl=wvl, use_hyperspectral=use_hyperspectral))
107
+ fq0 = np.array(get_fq(0.0, 0.0, 0.0, chl, wvl=wvl, use_hyperspectral=use_hyperspectral))
108
+
109
+ if corr:
110
+ fq = fq0 / fqA
111
+ else:
112
+ fq = fqA
113
+
114
+ return fq
115
+
116
+
117
+ def main():
118
+ """Primary driver for stand-alone version."""
119
+ __version__ = '1.0.2'
120
+
121
+ parser = argparse.ArgumentParser(
122
+ description='calculate Morel brdf correction')
123
+
124
+ parser.add_argument('--version', action='version',
125
+ version='%(prog)s ' + __version__)
126
+
127
+ parser.add_argument('chl', nargs='+', type=float,
128
+ default=None, help='input chlorophyll')
129
+ parser.add_argument('--solz', type=float, default=30.,
130
+ help='input solar zenith angle')
131
+ parser.add_argument('--viewz', type=float, default=0.,
132
+ help='input view zenith angle')
133
+ parser.add_argument('--relaz', type=float, default=0.,
134
+ help='input relative azimuth angle')
135
+ parser.add_argument('--output_file', type=str, default=None,
136
+ help="optional output filename; default: STDOUT")
137
+ parser.add_argument('--use_hyperspectral', action='store_true',
138
+ help="use the hyperspectral morel fq table")
139
+
140
+ args = parser.parse_args()
141
+
142
+ global wl
143
+ wvl = [300., 350., 412.5, 442.5, 490., 510., 560., 620., 660., 700.]
144
+
145
+ chl = np.atleast_1d(args.chl)
146
+ solz = np.atleast_1d(args.solz)
147
+ viewz = np.atleast_1d(args.viewz)
148
+ relaz = np.atleast_1d(args.relaz)
149
+
150
+ # chl = np.array([0.01, 0.01, 0.01])
151
+ # solz = np.array([30, 35, 40])
152
+ # viewz = np.array([25, 27, 30])
153
+ # relaz = np.array([95, 110, 115])
154
+ brdf = morel_brdf(chl, solz, viewz, relaz, wvl=wvl, corr=True, use_hyperspectral=args.use_hyperspectral)
155
+
156
+ outarray = np.column_stack((np.asarray(wl), np.asarray(brdf)))
157
+
158
+ if args.output_file:
159
+ ofile = open(args.output_file, 'w')
160
+ ofile.write("/begin_header\n")
161
+ ofile.write("! Output of Model BRDF function\n")
162
+ ofile.write("! chlorophyll: %f\n" % args.chl[0])
163
+ ofile.write("! solar zenith angle: %f\n" % args.solz)
164
+ ofile.write("! view zenith angle: %f\n" % args.viewz)
165
+ ofile.write("! relative azinuth angle: %f\n" % args.relaz)
166
+ ofile.write("/missing=-999\n")
167
+ ofile.write("/delimiter=space\n")
168
+ ofile.write("/fields=wavelength,brdf\n")
169
+ ofile.write("/units=nm,dimensionless\n")
170
+ ofile.write('\n'.join([' '.join(['{:.6f}'.format(value)
171
+ for value in row])
172
+ for row in outarray]))
173
+ # for i in range(len(brdf)):
174
+ # ofile.write('%7.2f %12.9f\n' % (wl[i],brdf[i]))
175
+ ofile.close()
176
+ else:
177
+ # for i in range(len(brdf)):
178
+ # print('%7.2f %12.9f' % (wl[i],brdf[i]))
179
+ print('\n'.join([' '.join(['{:.6f}'.format(value)
180
+ for value in row]) for row in outarray]))
181
+
182
+
183
+ # The following allows the file to be imported without immediately executing.
184
+ if __name__ == '__main__':
185
+ sys.exit(main())
orm/get_f0.py ADDED
@@ -0,0 +1,150 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Return F0 from the Thuillier 2003 lookup table.
4
+
5
+ Based on the function get_f0.pro
6
+
7
+ [structure of f0 and lambda] = get_f0(avg_wl=[array of wl])
8
+ and avg_wl=[array of wl] calculated 10 nm average for each wl
9
+ """
10
+
11
+ import numpy as np
12
+ import argparse
13
+ import sys
14
+ import os
15
+ from netCDF4 import Dataset
16
+ import datetime
17
+
18
+
19
+ def get_f0(wvls=None, obstime=None, tsis=False):
20
+ """
21
+ Load Thuillier2003 or TSIS netcdf and return f0.
22
+
23
+ Defaults to returning the full table. Input obstime to correct for the
24
+ Earth-Sun distance.
25
+ """
26
+
27
+ f0filename='thuillier2003_f0.nc'
28
+ if tsis:
29
+ f0filename='f0_tsis_1nm_v2.nc'
30
+ f0file = os.path.join(
31
+ os.path.dirname(__file__), 'data', f0filename)
32
+ ncfile = Dataset(f0file, 'r')
33
+
34
+ wl = ncfile['wavelength'][:]
35
+ f0 = ncfile['irradiance'][:]
36
+
37
+ wl_save = wl
38
+ f0_save = f0
39
+
40
+ if wvls:
41
+ avg_f0 = np.empty(len(wvls))
42
+ avg_f0[:] = np.nan
43
+
44
+ for i in range(len(wvls)):
45
+ idx = np.where((wl >= wvls[i]-5.) & (wl <= wvls[i]+5.))
46
+ if idx:
47
+ avg_f0[i] = np.mean(f0[idx])
48
+
49
+ f0_save = avg_f0
50
+ wl_save = wvls
51
+
52
+ if obstime:
53
+ f0_save *= correct_esdist(obstime)
54
+
55
+ result = (f0_save, wl_save)
56
+
57
+ return result
58
+
59
+
60
+ def correct_esdist(obstime):
61
+ """Calculate the Earth-Sun distance correction factor to apply to F0."""
62
+ pi2 = 2 * np.pi
63
+ rjd = obstime.timetuple().tm_yday + obstime.timetuple().tm_hour/24.0
64
+ return np.square(1.0 / (1.00014 - 0.01671*np.cos(1.0*pi2*(0.9856002831*rjd-3.4532868)/360.0)
65
+ - 0.00014*np.cos(2.0*pi2*(0.9856002831*rjd-3.4532868)/360.0)))
66
+
67
+
68
+ def main():
69
+ """Primary driver for stand-alone version."""
70
+ __version__ = '1.0.1'
71
+
72
+ parser = argparse.ArgumentParser(description=(
73
+ 'Generates hyperspectral (1nm) or 10nm bandpass averaged '
74
+ 'extraterrestrial irradiance spectrum using Thuillier (2002): '))
75
+
76
+ parser.add_argument('--version', action='version',
77
+ version='%(prog)s ' + __version__)
78
+ parser.add_argument('--output_file', type=str,
79
+ help='output filename; default is STDOUT')
80
+ parser.add_argument('--wvl', type=float, nargs='+',
81
+ default=None, help='wavelength(s) to generate')
82
+ parser.add_argument('--datetime', type=str, default=None,
83
+ help=('ISO8601 date used to correct for '
84
+ 'Earth-Sun distance'))
85
+ parser.add_argument('--tsis', '-t', action='store_true', help='use TSIS extraterrestrial irradiance (default: Thuillier)')
86
+ parser.add_argument('--verbose', '-v', action='store_true')
87
+
88
+ args = parser.parse_args()
89
+
90
+ obstime = None
91
+ esdistcorr = 1.0
92
+ if args.datetime:
93
+ obstime = datetime.datetime.fromisoformat(args.datetime)
94
+ esdistcorr = correct_esdist(obstime)
95
+
96
+ verbose = args.verbose
97
+ tsis = args.tsis
98
+
99
+ if verbose and args.output_file:
100
+ print("Generating extraterrestrial irradiance spectrum ...")
101
+
102
+ (spectrum, wvl) = get_f0(wvls=args.wvl, obstime=obstime, tsis=tsis)
103
+ outarray = np.column_stack((np.asarray(wvl), np.asarray(spectrum)))
104
+
105
+ if args.output_file:
106
+ ofile = open(args.output_file, 'w')
107
+ ofile.write("/begin_header\n")
108
+ if tsis:
109
+ ofile.write("! Extraterrestrial irradiance spectrum from TSIS\n")
110
+ ofile.write("! Coddington, O. M., Richard, E. C., Harber, D., Pilewskie,\n"
111
+ "! P., Woods, T. N., Chance, K., et al. (2021). The !TSIS-1 hybrid\n"
112
+ "! solar reference spectrum. Geophysical Research Letters, 48, e2020GL091709.\n")
113
+ ofile.write("! https://doi.org/10.1029/2020GL091709\n\n")
114
+ else:
115
+ ofile.write("! Extraterrestrial irradiance spectrum from Thuillier\n")
116
+ ofile.write("! Thuillier, G., Hersé, M., Labs, D. et al.\n")
117
+ ofile.write("! The Solar Spectral Irradiance from 200 to 2400 nm "
118
+ "as Measured by the SOLSPEC Spectrometer\n")
119
+ ofile.write("! from the Atlas and Eureca Missions. Solar Physics "
120
+ "214, 1–22 (2003).\n")
121
+ ofile.write("! https://doi.org/10.1023/A:1024048429145\n\n")
122
+ if obstime:
123
+ ofile.write("! Observation time: {}\n".format(args.datetime))
124
+ ofile.write("! Earth-Sun distance correction factor: "
125
+ "{:.7f}\n".format(esdistcorr))
126
+ else:
127
+ ofile.write("! Mean Earth-Sun distance\n")
128
+
129
+ if args.wvl:
130
+ ofile.write("! 11nm width bands\n")
131
+ # if args.sensor:
132
+ # ofile.write("! convolved with the spectral response function "
133
+ # "for %s\n" % sensors[args.sensor]['name'])
134
+ ofile.write("/missing=-999\n")
135
+ ofile.write("/delimiter=space\n")
136
+ ofile.write("/fields=wavelength,F0\n")
137
+ ofile.write("/units=nm,W m^-2 nm^-1\n")
138
+ ofile.write('\n'.join([' '.join(['{:.5f}'.format(value)
139
+ for value in row])
140
+ for row in outarray]))
141
+ ofile.close()
142
+ else:
143
+ print('\n'.join([' '.join(['{:.5f}'.format(value)
144
+ for value in row]) for row in outarray]))
145
+
146
+
147
+
148
+ # The following allows the file to be imported without immediately executing.
149
+ if __name__ == '__main__':
150
+ sys.exit(main())
orm/kbio-netCDF.py ADDED
@@ -0,0 +1,41 @@
1
+ """Script that takes the mm01_kbio.txt file and converts it to a netcdf."""
2
+ import numpy as np
3
+ from netCDF4 import Dataset
4
+ from datetime import datetime
5
+ import time
6
+ import pandas as pd
7
+
8
+ kbio = pd.read_csv('mm01_kbio.txt', sep=' ', header=0)
9
+
10
+ # Create the netCDF file and add dimensions
11
+ dataset = Dataset('mm01_kbio.nc', 'w', format='NETCDF4')
12
+ dataset.createDimension('nwavelengths', len(kbio.wl))
13
+
14
+ # Set global attributes
15
+ dataset.title = "Morel and Maritorena kbio table"
16
+ dataset.date_created = (
17
+ datetime.fromtimestamp(time.time())
18
+ .strftime('%Y-%m-%dT%H:%M:%SZ')).encode('ascii')
19
+ dataset.creator_name = "Sean Bailey, NASA/GSFC/OBPG"
20
+ dataset.creator_email = "data@oceancolor.gsfc.nasa.gov"
21
+ dataset.creator_url = "https://oceancolor.gsfc.nasa.gov"
22
+ dataset.product_name = "mm01_kbuio.nc"
23
+
24
+ # Create the table data sets
25
+ wavelength = dataset.createVariable('wavelength', np.float32,
26
+ ('nwavelengths',))
27
+ kw = dataset.createVariable('kw', np.float32, ('nwavelengths',))
28
+ e = dataset.createVariable('e', np.float32, ('nwavelengths',))
29
+ X = dataset.createVariable('X', np.float32, ('nwavelengths',))
30
+
31
+ # Write the data
32
+ kw[:] = np.array(kbio.kw)
33
+ e[:] = np.array(kbio.e)
34
+ X[:] = np.array(kbio.X)
35
+ wavelength[:] = np.array(kbio.wl)
36
+
37
+ # Add some variable attributes
38
+ wavelength.units = 'nm'
39
+
40
+ # Close the file
41
+ dataset.close()