-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiuvdata.py
358 lines (299 loc) · 12.6 KB
/
iuvdata.py
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
"""
IUVS l2b data module
author: K. Masunaga (kei.masunaga@lasp.colorado.edu)
"""
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
import warnings
import os
import spiceypy as spice
from common.tools import quaternion_rotation
from PyUVS.graphics import angle_meshgrid, H_colormap, NO_colormap
from PyUVS.variables import slit_width_deg
from PyUVS.data import get_apoapse_files as get_swath_info
from PyUVS.variables import data_directory as dataloc
from chaffin.paths import anc_dir
class ApoapseInfo:
def __init__(self, orbit_number, level='l2b', channel='fuv'):
self.segment = 'apoapse'
self.orbit_number = orbit_number
self.level = level
self.channel = channel
swath_info = get_swath_info(self.orbit_number, directory=dataloc, level=self.level, channel=channel)
self.files = swath_info['files']
self.n_files = int(len(self.files))
self.n_swaths = swath_info['n_swaths']
self.swath_number = swath_info['swath_number']
self.dayside = swath_info['dayside']
self.beta_flip = swath_info['beta_flip']
self.sDt = swath_info['sDt']
self.eDt = swath_info['eDt']
self.file_version = self._get_file_version()
def _get_file_version(self):
# get files and extract data versions; if no files version is
# 'missing'
try:
version_str = self.files[0].split('_')[-2:]
data_version = '%s_%s' % (version_str[0], version_str[1][0:3])
except IndexError:
data_version = 'missing'
# return data version string
return data_version
def get_hdul(self, idx_swath_number):
hdul = fits.open(self.files[idx_swath_number])
return hdul
class ApoapseSwath:
def __init__(self, hdul, linename='Lya', swath_number=0):
self.hdul = hdul
self.swath_number = swath_number
self.linename = linename
def get_img(self, flatfield_correct=True):
data = self.hdul['primary'].data
if self.linename == 'Lya':
self.img = data[:,:,0]
if self.linename == 'OI1304':
self.img = data[:,:,1]
if self.linename == 'OI1356':
self.img = data[:,:,2]
if self.linename == 'CII1336':
self.img = data[:,:,3]
if self.linename == 'Solar':
self.img = data[:,:,4]
if flatfield_correct:
self.apply_flatfield()
return self.img
def apply_flatfield(self):
spatial_binning = np.concatenate([self.hdul['Binning'].data['SPAPIXLO'][0],
[self.hdul['Binning'].data['SPAPIXHI'][0][-1]+1]])
if self.linename == 'Lya':
#slit_flatfield = np.load(os.path.join(anc_dir, 'kei_flatfield_polynomial_25Nov2020.npy'))
slit_flatfield = np.load(os.path.join(anc_dir, 'bad_flatfield_23Sep2020.npy'))
else:
warnings.warn('Binning is not periapsis--- using a very rough FUV flatfield.')
slit_flatfield = np.load(os.path.join(anc_dir, 'bad_flatfield_23Sep2020.npy'))
flatfield = np.array([np.mean(slit_flatfield[p0:p1]) for p0,p1 in zip(spatial_binning[:-1], spatial_binning[1:])])
nint = self.img.shape[0]
for iint in range(nint):
self.img[iint, :] /= flatfield
def get_xygrids(self):
x, y = angle_meshgrid(self.hdul)
x += slit_width_deg * self.swath_number
y = (120 - y) + 60
return x, y
def get_cmap(self):
if self.linename == 'Lya':
cmap = H_colormap()
if self.linename == 'OI1304':
cmap = NO_colormap()
if self.linename == 'OI1356':
pass
if self.linename == 'CII1336':
pass
if self.linename == 'Solar':
pass
return cmap
def plot(self, ax=None, flatfield_correct=True, **kwargs):
img = self.get_img(flatfield_correct=flatfield_correct)
x, y = self.get_xygrids()
if ax is None:
mesh = plt.pcolormesh(x, y, img, **kwargs)
else:
mesh = ax.pcolormesh(x, y, img, **kwargs)
return mesh
def get_apoapseinfo(orbit_number, level='l2b', channel='fuv'):
"""
Returns an apoapse info object created by the ApoapseInfo class.
Parameters
----------
orbit_numer : int
The orbit number for which to obtain the infomation.
level : str
Data level. Default is l2b.
(l2b is only tested for the moment. Have to check later if l1b also works.)
channel : str
MUV and/or FUV channel.
(fuv is only tested for the moment. Have to check later if muv also works.)
Returns
-------
apoinfo : ApoapseInfo object
An apoapse information object.
"""
apoinfo = ApoapseInfo(orbit_number, channel=channel)
return apoinfo
def plot_apoapse_image(orbit_number, linename, ax=None, **kwargs):
"""
Plots an apoapse image for a given orbit number.
Parameters
----------
orbit_numer : int
The orbit number for which to plot the image.
linename : str
Emission line name for which to plot the image.
ax : matplotlib Artist
The axis object in which to draw the image.
Returns
-------
mesh : matplotlib.collections.QuadMesh
A mesh object that pcolormesh returns.
"""
# Get apopase information object and filenames
apoinfo = get_apoapseinfo(orbit_number)
fnames = apoinfo.files
for iswath, ifname in enumerate(fnames):
hdul = apoinfo.get_hdul(iswath)
aposwath = ApoapseSwath(hdul, linename, iswath)
mesh = aposwath.plot(**kwargs)
ax = plt.gca()
ax.set_title('Orbit ' + str(orbit_number) + ' Apoapse ' + linename)
ax.set_xlabel('Spatial angle [deg]')
ax.set_ylabel('Integrations')
return mesh
class SzaGeo:
def __init__(self, hdul, swath_number=0):
self.hdul = hdul
self.swath_number = swath_number
self.data = hdul['PixelGeometry'].data['PIXEL_SOLAR_ZENITH_ANGLE']
self.mrh_alt = hdul['PixelGeometry'].data['PIXEL_CORNER_MRH_ALT']
def get_xygrids(self):
x, y = angle_meshgrid(self.hdul)
x += slit_width_deg * self.swath_number
y = (120 - y) + 60
return x, y
def plot(self, ax=None, **kwargs):
img = np.where(self.mrh_alt[:,:,4] == 0, self.data, np.nan)
x, y = self.get_xygrids()
if ax is None:
mesh = plt.pcolormesh(x, y, img, vmin=0, vmax=180, **kwargs)
else:
mesh = ax.pcolormesh(x, y, img, vmin=0, vmax=180, **kwargs)
return mesh
def plot_apoapse_sza_geo(orbit_number, ax=None, **kwargs):
apoinfo = get_apoapseinfo(orbit_number)
fnames = apoinfo.files
for iswath, ifname in enumerate(fnames):
hdul = apoinfo.get_hdul(iswath)
szageo = SzaGeo(hdul, iswath)
mesh = szageo.plot(cmap=plt.get_cmap('magma_r', 18))
ax = plt.gca()
ax.set_title('Orbit ' + str(orbit_number) + ' SZA')
ax.set_xlabel('Spatial angle [deg]')
ax.set_ylabel('Integrations')
return mesh
class LocalTimeGeo:
def __init__(self, hdul, swath_number=0):
self.hdul = hdul
self.swath_number = swath_number
self.data = hdul['PixelGeometry'].data['PIXEL_LOCAL_TIME']
self.mrh_alt = hdul['PixelGeometry'].data['PIXEL_CORNER_MRH_ALT']
def get_xygrids(self):
x, y = angle_meshgrid(self.hdul)
x += slit_width_deg * self.swath_number
y = (120 - y) + 60
return x, y
def plot(self, ax=None, **kwargs):
# Check what the third dimension of mrh_alt!!
img = np.where(self.mrh_alt[:,:,4] == 0, self.data, np.nan)
x, y = self.get_xygrids()
if ax is None:
mesh = plt.pcolormesh(x, y, img, vmin=0, vmax=24, **kwargs)
else:
mesh = ax.pcolormesh(x, y, img, vmin=0, vmax=24, **kwargs)
return mesh
def plot_apoapse_lt_geo(orbit_number, ax=None, **kwargs):
apoinfo = get_apoapseinfo(orbit_number)
fnames = apoinfo.files
for iswath, ifname in enumerate(fnames):
hdul = apoinfo.get_hdul(iswath)
ltgeo = LocalTimeGeo(hdul, iswath)
mesh = ltgeo.plot(cmap=plt.get_cmap('twilight_shifted', 24))
ax = plt.gca()
ax.set_title('Orbit ' + str(orbit_number) + ' Local Time')
ax.set_xlabel('Spatial angle [deg]')
ax.set_ylabel('Integrations')
return mesh
class LatLonGeo:
def __init__(self, hdul, swath_number=0):
self.hdul = hdul
self.swath_number = swath_number
self.lat = hdul['PixelGeometry'].data['PIXEL_CORNER_LAT']
self.lon = hdul['PixelGeometry'].data['PIXEL_CORNER_LON']
self.mrh_alt = hdul['PixelGeometry'].data['PIXEL_CORNER_MRH_ALT']
def get_xygrids(self):
x, y = angle_meshgrid(self.hdul)
x += slit_width_deg * self.swath_number
y = (120 - y) + 60
return x, y
def plot_lat(self, ax=None, **kwargs):
# Check what the third dimension of mrh_alt!!
img = np.where(self.mrh_alt[:,:,4] == 0, self.lat[:,:,4], np.nan)
x, y = self.get_xygrids()
if ax is None:
mesh = plt.pcolormesh(x, y, img, vmin=-90, vmax=90, **kwargs)
else:
mesh = ax.pcolormesh(x, y, img, vmin=-90, vmax=90, **kwargs)
return mesh
def plot_lon(self, ax=None, **kwargs):
# Check what the third dimension of mrh_alt!!
img = np.where(self.mrh_alt[:,:,4] == 0, self.lon[:,:,4], np.nan)
x, y = self.get_xygrids()
if ax is None:
mesh = plt.pcolormesh(x, y, img, vmin=0, vmax=360, **kwargs)
else:
mesh = ax.pcolormesh(x, y, img, vmin=0, vmax=360, **kwargs)
return mesh
class FieldAngleGeo:
def __init__(self, hdul, swath_number=0):
# Read hdul and variables
self.hdul = hdul
self.swath_number = swath_number
self.et = hdul['Integration'].data['et']
self.pixel_uvec_from_sc = hdul['PixelGeometry'].data['PIXEL_VEC'] ## pixel unit vector from sc
self.los_length = hdul['PixelGeometry'].data['PIXEL_CORNER_LOS']
self.sc_pos_iau = hdul['SpacecraftGeometry'].data['V_SPACECRAFT']
self.mrh_alt = hdul['PixelGeometry'].data['PIXEL_CORNER_MRH_ALT']
# Calc pixel vector
self.pixel_vec_from_sc_iau = self.pixel_uvec_from_sc * self.los_length[:, None, :, :]
self.pixel_vec_from_pla_iau = self.sc_pos_iau[:, :, None, None] + self.pixel_vec_from_sc_iau
self._to_mso(self.pixel_vec_from_pla_iau)
self.data = None
def _to_mso(self, pixel_vec_from_pla_iau):
mats = [spice.pxform('IAU_MARS', 'MAVEN_MSO', iet) for iet in self.et]
q = [spice.m2q(imats) for imats in mats]
self.pixel_vec_from_pla_mso = np.array([[quaternion_rotation(q[it], pixel_vec_from_pla_iau[it, :, ibin, 4]) for ibin in range(pixel_vec_from_pla_iau.shape[2])] for it in range(pixel_vec_from_pla_iau.shape[0])])
length_pixel_vec_from_pla_mso = np.sqrt(self.pixel_vec_from_pla_mso[:,:,0]**2 + self.pixel_vec_from_pla_mso[:,:,1]**2 + self.pixel_vec_from_pla_mso[:,:,2]**2)
self.pixel_uvec_from_pla_mso = self.pixel_vec_from_pla_mso/length_pixel_vec_from_pla_mso[:,:, None]
def calc_cone_angle(self, field_mso):
if field_mso is not None:
self.field_mso = field_mso
if np.size(self.field_mso) == 3:
self.data = np.degrees(np.arccos(np.dot(self.pixel_uvec_from_pla_mso, self.field_mso)/np.sqrt(np.dot(self.field_mso, self.field_mso))))
else:
self.data = np.array([np.degrees(np.arccos(np.dot(self.pixel_uvec_from_pla_mso[it], self.field_mso[it])/np.sqrt(np.dot(self.field_mso[it], self.field_mso[it])))) for it in range(self.pixel_uvec_from_pla_mso.shape[0])])
else:
self.field_mso = None
def get_xygrids(self):
x, y = angle_meshgrid(self.hdul)
x += slit_width_deg * self.swath_number
y = (120 - y) + 60
return x, y
def plot(self, ax=None, **kwargs):
img = np.where(self.mrh_alt[:,:,4] == 0, self.data, np.nan)
x, y = self.get_xygrids()
if ax is None:
mesh = plt.pcolormesh(x, y, img, vmin=0, vmax=180, **kwargs)
else:
mesh = ax.pcolormesh(x, y, img, vmin=0, vmax=180, **kwargs)
return mesh
def test():
plt.close('all')
fig = plt.figure(figsize=(24,6))
ax1 = fig.add_subplot(121)
mesh1 = plot_apoapse_image(3780, 'Lya', ax1, vmin=0, vmax=10)
cb1 = plt.colorbar(mesh1)
cb1.set_label('Brightness [kR]')
ax2 = fig.add_subplot(122)
mesh2 = plot_apoapse_image(3780, 'OI1304', ax2, vmin=0, vmax=1.5)
cb2 = plt.colorbar(mesh2)
cb2.set_label('Brightness [kR]')
plt.show()