-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgenerate_pickingpdf.py
More file actions
executable file
·375 lines (294 loc) · 17.4 KB
/
generate_pickingpdf.py
File metadata and controls
executable file
·375 lines (294 loc) · 17.4 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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import matplotlib.pyplot as plt
import numpy as np
import os
import glob
################## NDH Tools self imports
###########################################################
from .distance_vector import distance_vector
from .find_nearest import find_nearest
from .index_list import index_list
from .loadmat import loadmat
from .polarstereo_fwd import polarstereo_fwd
from .radar_load import radar_load
from .remove_image import remove_image
from .remove_line import remove_line
from .str_compare import str_compare
###########################################################
def generate_pickingpdf(fn,picking_root_dir='./',frame_spacing=25,surf_dir='CSARP_surf_ndh',crop_type='100',clims=[], alternative_data_opt=0):
"""
% (C) Nick Holschuh - Amherst College -- 2022 ([email protected])
%
% This function takes either a music file or a directory of
% standard files and generates a pdf with slices (or frames) that
% can be annotated by hand using GoodNotes6 on the iPad, and parsed
% using the process_XXXXX_pickedpdf.py scripts.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The inputs are:
%
% fn - This should be one of two things:
% 1: The filename (with complete path) to a music image to be picked
% 2: The directory name (with complete path and no trailing /) to
% a standard folder with radar images to be picked.
%
% picking_root_dir - In this directory, a folder called "to_pick" will get
% generated that stores the new picking pdfs.
%
% frame_spacing - default=25, for use in Music picking. This defines the
% slice interval for picking
%
% surf_dir - default='CSARP_surf_ndh', for use in Music picking, this puts
% the current surf values onto the image.
%
% crop_type - default='100', this is currently not widely implemented, but
% it allows you to ether crop the standard images to the max
% bottom pick plus 100 or the full time interval. By default
% the music images provide the max bottom pick +100 as the bottom.
%
% clims - default=[], only implemented for standard images. Allows you to change
% the vmin and vmax for the image. Supply a two value list if desired.
%
% alternative_data_opt - default=0. Some radar files generated by BAS or UTIG
% have two different waveforms. Setting this flag to 1
% will use the non-default waveform.
%
%%%%%%%%%%%%%%%
% The outputs are:
%
% This will write a picking pdf to the To_Pick folder of your choice.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
"""
import NDH_Tools as ndh
######### Set-up the directory where picks are placed
if not os.path.isdir(picking_root_dir+'To_Pick'):
os.makedirs(picking_root_dir+'To_Pick')
#######################################################################################################
####################### We need to determine if this is a 2D file or a MUSIC File
str_opt, str_ind = str_compare([fn],'music')
#######################################################################################################
######### For MUSIC files
if len(str_opt) > 0:
seg = fn.split('/')[-2]
frame = fn.split('/')[-1].split('.')[0]
if picking_root_dir[-1] != '/':
picking_root_dir = picking_root_dir+'/'
################ Here we do some directory checking to make sure all folders we need exist
if not os.path.isdir(picking_root_dir+'To_Pick/'+seg):
os.makedirs(picking_root_dir+'To_Pick/'+seg) ### The pdf directory where pickfiles are stored
if not os.path.isdir(picking_root_dir+seg):
os.makedirs(picking_root_dir+seg) ### The directory for the segment
if not os.path.isdir(picking_root_dir+seg+'/'+frame):
os.makedirs(picking_root_dir+seg+'/'+frame) ### The subdirectory for the frame
########### Now the data anlysis begins
data = loadmat(fn)
xy = polarstereo_fwd(data['Latitude'],data['Longitude'])
distance = distance_vector(xy['x'],xy['y'])
fig = plt.figure(figsize=(5,10))
ax = plt.gca()
#### Here we test to see if there are existing surface picks
fn_list = fn.split('/')
fn_list[-3] = surf_dir
fn2 = '/'.join(fn_list)
#try:
surfdata = loadmat(fn2)
surf_dims = surfdata['surf']['y'][1].shape
bot_ind = find_nearest(data['Time'],np.array([np.max(surfdata['surf']['y'][1])]))
bot_ind['index'] = [np.min([bot_ind['index'][0]+100,len(data['Time'])])]
#### Accounts for reduced size images for massive music files
if data['Tomo']['img'].dtype == 'uint8':
bot_ind['index'] = np.array([len(data['Tomo']['img'][:,0,0])]).astype(int)
data['Time'] = data['Time'][::2]
#except:
# print(fn2+' could not be found')
# fn2 = 0
# bot_ind = {'index':[len(data['Time'])]}
#### Now we loop through the frames we want to plot and generate an image for
frame_print = np.arange(0,len(xy['x']),frame_spacing)
for ind1,i in enumerate(frame_print):
remove_image(ax,1,verbose=0)
####### Accounting for int images (for massive swath files)
if data['Tomo']['img'].dtype == 'uint8':
ax.imshow(np.squeeze(data['Tomo']['img'][:bot_ind['index'][0],:,i]),cmap='bone_r')
else:
ax.imshow(np.squeeze(np.log10(data['Tomo']['img'][:bot_ind['index'][0],:,i])),cmap='bone_r')
ax.set_aspect('auto')
if fn2 != 0:
remove_line(ax,1,verbose=0)
#### Here we identify the indecies associated with the bottom picks and add them to the image
bot_inds = find_nearest(data['Time'],surfdata['surf']['y'][1][:,i])
plt.plot(np.arange(0,surf_dims[0],4),bot_inds['index'][::4],ls='none',marker='^',c='green',ms=4,alpha=0.1)
else:
pass
plt.axis('off')
plt.savefig('%s%s/%s/Frame_%0.4d_fs_%0.2d_crop_%0.4d.png' %(picking_root_dir,seg,frame,i,frame_spacing,bot_ind['index'][0]))
print('Completed the image generation')
########## Website used to do the following:
# https://stackoverflow.com/questions/9710118/convert-multipage-pdf-to-png-and-back-linux
########## This converts all the images to a single pdf
pdfroot = picking_root_dir+'To_Pick/'+seg+'/'
pdfend = '%s_fs_%0.2d_crop_%0.4d.pdf' %(frame,frame_spacing,bot_ind['index'][0])
pdfname=pdfroot+pdfend
frames = '%s%s/%s/*.png' % (picking_root_dir,seg,frame)
os.system("convert -adjoin "+frames+" -gravity center -scale '90<x770<' "+pdfname)
###########
os.system('rm -r '+picking_root_dir+seg)
####################################################################################################################
####################################################################################################################
####################################################################################################################
####################################################################################################################
####################################################################################################################
#######################################################################################################
####################### The alternative is a directory full of standard files
str_opt, str_ind = str_compare([fn],'standard')
if len(str_opt) > 0:
str_opt2, str_ind2 = str_compare([fn.split('/')[-2]],'standard')
if len(str_opt2) == 1:
file_dirs = sorted(glob.glob(fn+'/*'))
season_name = fn.split('/')[-3]
if not os.path.isdir(picking_root_dir+'To_Pick/'+season_name):
os.makedirs(picking_root_dir+'To_Pick/'+season_name) ### The pdf directory where pickfiles are stored
fig = plt.figure(figsize=(15,10))
ax = plt.gca()
num_to_remove = 0
for ind1,file_dir in enumerate(file_dirs):
dayseg = file_dir.split('/')[-1]
file_list = sorted(glob.glob(file_dir+'/Data_*.mat'))
if len(file_list) > 0:
ki = [];
for ind,i in enumerate(file_list):
if i.split('/')[-1][5] != 'i':
ki.append(ind)
file_list = index_list(file_list,ki)
else:
file_list = sorted(glob.glob(fn+'/*.mat'))
try:
radar_data,depth_data = radar_load(file_list,plot_flag=0,elevation1_or_depth2=0,trace_spacing=frame_spacing)
except:
radar_data,depth_data = radar_load('')
if len(radar_data.keys()) > 0:
bot_inds = find_nearest(radar_data['Time'],radar_data['Bottom'])['index'].astype(float)
surf_inds = find_nearest(radar_data['Time'],radar_data['Surface'])['index'].astype(float)
bot_inds[bot_inds == 0] = np.nan
surf_inds[surf_inds == 0] = np.nan
if crop_type == '100' and np.min(np.isnan(bot_inds)) == 0:
bot_ind = np.nanmax(bot_inds)+100
crop_string = 'maxbotplus100'
elif crop_type == '500' and np.min(np.isnan(bot_inds)) == 0:
bot_ind = np.nanmax(bot_inds)+100
crop_string = 'remove_bot'
else:
bot_ind = len(radar_data['Time'])
crop_string = 'nocrop'
remove_image(ax,1,verbose=0)
remove_line(ax,num_to_remove,verbose=0)
if np.isnan(bot_ind) == 1:
plt.plot(0,0)
else:
########### This accomodates files that have more than one data type
if alternative_data_opt == 1:
find_data_opts = str_compare(radar_data.keys,'Data2')
if len(find_data_opts[0]) > 0:
radar_data['Data'] = radar_data['Data2']
if len(clims) > 0:
imdata = plt.imshow(10*np.log10(radar_data['Data'][:int(bot_ind),:]),
origin='lower',aspect='auto',cmap='gray_r',vmin=clims[0],vmax=clims[1])
else:
imdata = plt.imshow(10*np.log10(radar_data['Data'][:int(bot_ind),:]),
origin='lower',aspect='auto',cmap='gray_r')
#plt.plot(np.arange(0,len(radar_data['distance'])),bot_inds,ls='--',c='green',alpha=0.2)
#plt.plot(np.arange(0,len(radar_data['distance'])),surf_inds,ls='--',c='green',alpha=0.2)
for hbar in radar_data['im_end'][1:]:
plt.axvline(hbar,c='green',lw=1)
num_to_remove = len(radar_data['im_end'][1:])
ax.set_xlim([0,hbar])
else:
remove_image(ax,1,verbose=0)
remove_line(ax,num_to_remove,verbose=0)
plt.imshow([[1]],cmap='gray_r',vmin=0,vmax=5)
num_to_remove = 0
ax.set_xlim([-0.5,0.5])
ax.set_aspect('auto')
ax.invert_yaxis()
plt.axis('off')
frame_fn = '%s/To_Pick/%s/%s.png' %(picking_root_dir,season_name,dayseg)
plt.savefig(frame_fn)
print(' --- Completed Image '+str(ind1)+' of '+str(len(file_dirs)))
else:
file_list = sorted(glob.glob(fn+'/Data_*.mat'))
if len(file_list) > 0:
ki = [];
for ind,i in enumerate(file_list):
if i.split('/')[-1][5] != 'i':
ki.append(ind)
file_list = index_list(file_list,ki)
else:
file_list = sorted(glob.glob(fn+'/*.mat'))
try:
max_num = int(file_list[-1].split('/')[-1].split('.')[0].split('_')[-1])
seg = file_list[-1].split('/')[-2]
froot = '_'.join(file_list[-1].split('/')[-1].split('.')[0].split('_')[0:-1])
except:
max_num = len(file_list)
seg = file_list[-1].split('/')[-2]
froot = seg
num_range = np.arange(1,max_num+1,1)
################ Here we do some directory checking to make sure all folders we need exist
if not os.path.isdir(picking_root_dir+'To_Pick/'+seg):
os.makedirs(picking_root_dir+'To_Pick/'+seg) ### The pdf directory where pickfiles are stored
fig = plt.figure(figsize=(15,7))
ax = plt.gca()
for ind1,file_num in enumerate(num_range):
fn_frame = '%s/%s_%0.3d.mat' % (fn,froot,file_num)
print(fn_frame)
if os.path.isfile(fn_frame) == 0:
fn_frame = file_list[ind1]
radar_data,depth_data = radar_load(fn_frame,plot_flag=0,elevation1_or_depth2=0)
if len(radar_data.keys()) > 0:
bot_inds = find_nearest(radar_data['Time'],radar_data['Bottom'])['index'].astype(float)
surf_inds = find_nearest(radar_data['Time'],radar_data['Surface'])['index'].astype(float)
bot_inds[bot_inds == 0] = np.nan
surf_inds[surf_inds == 0] = np.nan
if crop_type == '100' and np.min(np.isnan(bot_inds)) == 0:
bot_ind = np.nanmax(bot_inds)+100
crop_string = 'maxbotplus100'
else:
bot_ind = len(radar_data['Time'])
crop_string = 'nocrop'
remove_image(ax,1,verbose=0)
remove_line(ax,2,verbose=0)
if np.isnan(bot_ind) == 1:
plt.plot(0,0)
else:
########### This accomodates files that have more than one data type
if alternative_data_opt == 1:
find_data_opts = str_compare(radar_data.keys,'Data2')
if len(find_data_opts[0]) > 0:
radar_data['Data'] = radar_data['Data2']
if len(clims) > 0:
imdata = plt.imshow(10*np.log10(radar_data['Data'][:int(bot_ind),:]),
origin='lower',aspect='auto',cmap='gray_r',vmin=clims[0],vmax=clims[1])
else:
imdata = plt.imshow(10*np.log10(radar_data['Data'][:int(bot_ind),:]),
origin='lower',aspect='auto',cmap='gray_r')
plt.plot(np.arange(0,len(radar_data['distance'])),bot_inds,ls='--',c='green',alpha=0.2)
plt.plot(np.arange(0,len(radar_data['distance'])),surf_inds,ls='--',c='green',alpha=0.2)
else:
plt.plot(0,0)
ax.invert_yaxis()
plt.axis('off')
frame_fn = '%s/To_Pick/%s/Frame_%0.3d.png' %(picking_root_dir,seg,file_num)
plt.savefig(frame_fn)
print(' --- Completed Image '+str(ind1)+' of '+str(len(num_range)))
print('Completed the image generation')
########## Website used to do the following:
# https://stackoverflow.com/questions/9710118/convert-multipage-pdf-to-png-and-back-linux
if 'season_name' in locals():
seg = season_name
########## This converts all the images to a single pdf
pdfroot = picking_root_dir+'To_Pick/'
pdfend = 'StandardPicks_%s_crop_%s.pdf' %(seg,crop_string)
pdfname=pdfroot+pdfend
frames = '%s/To_Pick/%s/*.png' % (picking_root_dir,seg)
os.system("convert -adjoin "+frames+" -gravity center -scale '90<x770<' "+pdfname)
###########