-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathradar_load.py
More file actions
executable file
·327 lines (278 loc) · 15.6 KB
/
radar_load.py
File metadata and controls
executable file
·327 lines (278 loc) · 15.6 KB
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
import matplotlib.pyplot as plt
import numpy as np
###########################################################
################## NDH Tools self imports
from .elevation_shift import elevation_shift
from .distance_vector import distance_vector
from .depth_shift import depth_shift
from .find_nearest_xy import find_nearest_xy
from .loadmat import loadmat
from .polarstereo_fwd import polarstereo_fwd
from .str_compare import str_compare
from .struct_to_dict import struct_to_dict
############################################################
def radar_load(fn,plot_flag=0,elevation1_or_depth2=1,alternative_data_opt=0,trace_spacing=1):
"""
% (C) Nick Holschuh - Amherst College -- 2022 ([email protected])
%
% This function does the standard load, transformation, and plotting
% that is common in the CReSIS radar analysis workflow
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The inputs are:
%
% fn -- the input filename or list of filenames to be read
% plot_flag -- 0 or 1, for whether or not you want a plot included, or 2 for the plotting code to be printed
% elevation1_or_depth2 -- there is a depth conversion that is built in, 1 if you want true elevation, 2 for depth in ice
% 0 will give you an empty object
% alternative_data_opt -- Some files (generated by Nick) contain more than one data type. This lets you switch them.
%
%%%%%%%%%%%%%%%
% The outputs are:
%
% radar_data -- the simple product of loading the mat file (+ x and y coordinates and distance added)
% depth_data -- the depth or elevation product
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
"""
if isinstance(fn,list) == 0:
fn = [fn]
concat_list = ['Elevation','GPS_time','Latitude','Longitude','Surface','Bottom']
############## Here we loop through the radar data and concatenate the files
for fn_ind,fn_temp in enumerate(fn):
if fn_ind == 0:
radar_data = loadmat(fn_temp);
if len(radar_data['Elevation'].shape) == 2:
for key_opt in concat_list:
radar_data[key_opt] = np.squeeze(radar_data[key_opt])
if len(radar_data['Time'].shape) == 2:
radar_data['Time'] = np.squeeze(radar_data['Time'])
############################################################################################
############### A set of helper function to clean up the parameter sections of spreadsheets
############################################################################################
keylist = radar_data.keys()
param_cleanup = 0
for key in keylist:
if 'param' in key:
if isinstance(radar_data[key],dict) == 0:
radar_data[key] = struct_to_dict(radar_data[key])
param_cleanup = 1
try:
system_center_f = radar_data['param_sar']
try:
system_center_f = system_center_f['radar']['wfs'][0]['fc']
except:
raise ValueError("The parameter structure you've provided didn't have the center frequency in the expected location.")
except:
try:
system_center_f = radar_data['param_qlook']
try:
system_center_f = system_center_f['radar']['wfs'][0]['fc']
except:
raise ValueError("The parameter structure you've provided didn't have the center frequency in the expected location.")
except:
try:
system_center_f = radar_data['param_array']
try:
system_center_f = system_center_f['radar']['wfs'][0]['fc']
except:
raise ValueError("The parameter structure you've provided didn't have the center frequency in the expected location.")
except:
system_center_f = np.nan
radar_data['fc'] = system_center_f
if param_cleanup == 1:
#print('Fixed parameter structure')
pass
if 'Bottom' not in radar_data.keys():
radar_data['Bottom'] = np.zeros(radar_data['Surface'].shape)*np.nan
############# Here we exit if the file didn't load properly
if len(radar_data.keys()) == 0:
depth_data = radar_data
return radar_data,depth_data
data2_exist = str_compare(radar_data.keys(),'Data2')
if len(data2_exist[0]) > 0:
alternative_data_exist = 1
else:
alternative_data_exist = 0
if trace_spacing > 1:
for key in concat_list:
radar_data[key] = radar_data[key][::trace_spacing]
radar_data['Data'] = radar_data['Data'][:,::trace_spacing]
if alternative_data_exist == 1:
radar_data['Data2'] = radar_data['Data2'][:,::trace_spacing]
xy = polarstereo_fwd(radar_data['Latitude'],radar_data['Longitude'])
distance = distance_vector(xy['x'],xy['y'])
radar_data['x'] = xy['x']
radar_data['y'] = xy['y']
radar_data['distance'] = distance
radar_data['im_end'] = [0,len(distance)]
radar_data['orig_ind'] = np.arange(0,len(distance))
radar_data['filename'] = [fn_temp.split('/')[-1]]
if fn_ind > 0:
radar_data_temp = loadmat(fn_temp)
if 'Bottom' not in radar_data_temp.keys():
radar_data_temp['Bottom'] = np.zeros(radar_data_temp['Surface'].shape)*np.nan
if trace_spacing > 1:
for key in concat_list:
radar_data_temp[key] = radar_data_temp[key][::trace_spacing]
radar_data_temp['Data'] = radar_data_temp['Data'][:,::trace_spacing]
if alternative_data_exist == 1:
radar_data_temp['Data2'] = radar_data_temp['Data2'][:,::trace_spacing]
xy_temp = polarstereo_fwd(radar_data_temp['Latitude'],radar_data_temp['Longitude'])
########## Here we deal with potentially overlapping frames
comp_dists = find_nearest_xy([xy_temp['x'],xy_temp['y']],[radar_data['x'][-1],radar_data['y'][-1]])
if comp_dists['index'] != 0:
for cut_key in concat_list:
radar_data_temp[cut_key] = radar_data_temp[cut_key][comp_dists['index'][0]:]
radar_data_temp['Data'] = radar_data_temp['Data'][:,comp_dists['index'][0]:]
xy_temp['x'] = xy_temp['x'][comp_dists['index'][0]:]
xy_temp['y'] = xy_temp['y'][comp_dists['index'][0]:]
inc_dist = comp_dists['distance'][0]
distance = distance_vector(xy_temp['x'],xy_temp['y'])
if inc_dist < 0.01:
inc_dist = 0.01
########## Here we do the data concatenation
radar_data['x'] = np.concatenate([radar_data['x'],xy_temp['x']])
radar_data['y'] = np.concatenate([radar_data['y'],xy_temp['y']])
radar_data['distance'] = np.concatenate([radar_data['distance'],distance+np.max(radar_data['distance'])+inc_dist])
radar_data['im_end'].append(len(radar_data['distance']))
radar_data['orig_ind'] = np.concatenate([radar_data['orig_ind'],np.arange(comp_dists['index'][0],len(distance))])
radar_data['filename'].append(fn_temp.split('/')[-1])
radar_data['Data'] = np.concatenate([radar_data['Data'],radar_data_temp['Data']],axis=1)
############# Here we handle files with potentially alternative datatytpes:
if alternative_data_exist == 1:
radar_data['Data2'] = np.concatenate([radar_data['Data2'],radar_data_temp['Data2']],axis=1)
for concat_keys in concat_list:
radar_data[concat_keys] = np.concatenate([radar_data[concat_keys],radar_data_temp[concat_keys]])
############# Here we do the depth or elevation shift
if elevation1_or_depth2 == 0:
depth_data = 'No depth data requested'
elif elevation1_or_depth2 == 1:
if np.all([alternative_data_exist == 1, alternative_data_opt == 1]):
print('Loading Alternative Data Set')
depth_data = elevation_shift(radar_data['Data2'],radar_data['Time'],radar_data['Surface'],radar_data['Elevation'],radar_data['Bottom'])
else:
depth_data = elevation_shift(radar_data['Data'],radar_data['Time'],radar_data['Surface'],radar_data['Elevation'],radar_data['Bottom'])
elif elevation1_or_depth2 == 2:
if np.all([alternative_data_exist == 1, alternative_data_opt == 1]):
print('Loading Alternative Data Set')
depth_data = depth_shift(radar_data['Data2'],radar_data['Time'],radar_data['Surface'],radar_data['Elevation'],radar_data['Bottom'])
else:
depth_data = depth_shift(radar_data['Data'],radar_data['Time'],radar_data['Surface'],radar_data['Elevation'],radar_data['Bottom'])
else:
depth_data = 'No depth data requested'
##############################################################################################################
############# Here we either plot the data or deliver a plot string for future use
##############################################################################################################
if plot_flag == 1:
############## Here, we accomodate complex valued data:
if np.any(np.iscomplex(radar_data['Data'])):
if elevation1_or_depth2 == -1:
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(np.real(radar_data['Data'])**2),
origin='lower',aspect='auto',cmap='gray_r')
ax = plt.gca()
ax.invert_yaxis()
elif elevation1_or_depth2 == 0:
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(np.real(radar_data['Data'])**2),
extent=[radar_data['distance'][0]/1000,radar_data['distance'][-1]/1000,
radar_data['Time'][0],radar_data['Time'][-1]],
origin='lower',aspect='auto',cmap='gray_r')
ax = plt.gca()
else:
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(np.real(depth_data['new_data'])**2),
extent=[radar_data['distance'][0]/1000,radar_data['distance'][-1]/1000,
depth_data['depth_axis'][0],depth_data['depth_axis'][-1]],
origin='lower',aspect='auto',cmap='gray_r')
else:
if elevation1_or_depth2 == -1:
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(radar_data['Data']),
origin='lower',aspect='auto',cmap='gray_r')
ax = plt.gca()
ax.invert_yaxis()
elif elevation1_or_depth2 == 0:
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(radar_data['Data']),
extent=[radar_data['distance'][0]/1000,radar_data['distance'][-1]/1000,
radar_data['Time'][0],radar_data['Time'][-1]],
origin='lower',aspect='auto',cmap='gray_r')
ax = plt.gca()
else:
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(depth_data['new_data']),
extent=[radar_data['distance'][0]/1000,radar_data['distance'][-1]/1000,
depth_data['depth_axis'][0],depth_data['depth_axis'][-1]],
origin='lower',aspect='auto',cmap='gray_r')
if elevation1_or_depth2 == 2:
plt.ylabel('Depth (m)')
elif elevation1_or_depth2 == 1:
plt.ylabel('Elevation w.r.t WGS84 (m)')
plt.xlabel('Distance (km)')
cbar = plt.colorbar(imdata)
ax = plt.gca()
ax.invert_yaxis()
############## This delivers the plot string of interest
elif plot_flag == 2:
############## Here, we accomodate complex valued data:
if np.any(np.iscomplex(radar_data['Data'])):
if elevation1_or_depth2 == -1:
print('''
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(np.real(radar_data['Data'])**2),
origin='lower',aspect='auto',cmap='gray_r')
''')
elif elevation1_or_depth2 == 0:
print('''
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(np.real(radar_data['Data'])**2),
extent=[radar_data['distance'][0]/1000,radar_data['distance'][-1]/1000,
radar_data['Time'][0],radar_data['Time'][-1]],
origin='lower',aspect='auto',cmap='gray_r')
''')
else:
print('''
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(np.real(depth_data['new_data'])**2),
extent=[radar_data['distance'][0]/1000,radar_data['distance'][-1]/1000,
depth_data['depth_axis'][0],depth_data['depth_axis'][-1]],
origin='lower',aspect='auto',cmap='gray_r')
''')
else:
if elevation1_or_depth2 == -1:
print('''
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(radar_data['Data']),
origin='lower',aspect='auto',cmap='gray_r')
''')
elif elevation1_or_depth2 == 0:
print('''
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(radar_data['Data']),
extent=[radar_data['distance'][0]/1000,radar_data['distance'][-1]/1000,
radar_data['Time'][0],radar_data['Time'][-1]],
origin='lower',aspect='auto',cmap='gray_r')
''')
else:
print('''
fig = plt.figure(figsize=(15,7))
imdata = plt.imshow(10*np.log10(depth_data['new_data']),
extent=[radar_data['distance'][0]/1000,radar_data['distance'][-1]/1000,
depth_data['depth_axis'][0],depth_data['depth_axis'][-1]],
origin='lower',aspect='auto',cmap='gray_r')
''')
print('''
cbar = plt.colorbar(imdata)
ax = plt.gca()
ax.invert_yaxis()
plt.xlabel('Distance (km)')
''')
if elevation1_or_depth2 == 2:
print('''
plt.ylabel('Depth (m)')''')
elif elevation1_or_depth2 == 1:
print('''
plt.ylabel('Elevation w.r.t WGS84 (m)')''')
return radar_data,depth_data