Skip to content

Commit f060bb5

Browse files
committed
Updated the repository with the newest versions of the NDH_Tools functions
1 parent 943d3c6 commit f060bb5

17 files changed

+780
-93
lines changed

edgetrim_mask.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
2+
3+
def edgetrim_mask(edge_trim_array, debug_flag=0, start_trim=0, end_trim=0):
4+
"""
5+
% (C) Nick Holschuh - Amherst College -- 2022 ([email protected])
6+
%
7+
% This function takes in a CSARP_surf y array generated using "pick edge_mask"
8+
% and converts the output into a mask for subsetting CSARP_dem data
9+
%
10+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
11+
% The inputs are:
12+
%
13+
%
14+
%%%%%%%%%%%%%%%
15+
% The outputs are:
16+
%
17+
%
18+
%
19+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
20+
% the edge trim array is typically surf_data['surf']['y'][7]
21+
"""
22+
import numpy as np
23+
from scipy.interpolate import interp1d
24+
mask = np.zeros(edge_trim_array.shape)
25+
26+
et_row,et_col = np.where(~np.isnan(edge_trim_array))
27+
center_split = np.mean(et_row)
28+
left_ind = np.where(et_row < center_split)
29+
right_ind = np.where(et_row >= center_split)
30+
31+
32+
col_opts = np.arange(0,edge_trim_array.shape[1])
33+
34+
left_row_interpolator = interp1d(et_col[left_ind],et_row[left_ind],fill_value=np.NaN,bounds_error=0)
35+
right_row_interpolator = interp1d(et_col[right_ind],et_row[right_ind],fill_value=np.NaN,bounds_error=0)
36+
37+
left_row = left_row_interpolator(col_opts).astype(int)
38+
right_row = right_row_interpolator(col_opts).astype(int)
39+
40+
for i in col_opts:
41+
mask[left_row[i]:right_row[i]+1,i] = 1
42+
for i in range(start_trim):
43+
mask[:,i] = 0
44+
for i in range(end_trim):
45+
mask[:,-i] = 0
46+
47+
mask[mask == 0] = np.NaN
48+
49+
50+
if debug_flag:
51+
import matplotlib.pyplot as pltdd
52+
plt.imshow(mask)
53+
plt.plot(et_col,et_row,'o',c='red')
54+
plt.plot(col_opts,left_row,'-',c='black')
55+
plt.plot(col_opts,right_row,'-',c='black')
56+
plt.gca().set_aspect('auto')
57+
58+
return mask
59+

find_nearest.py

+5
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ def find_nearest(vector_2_search,value,how_many=1):
2727
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2828
"""
2929

30+
if isinstance(vector_2_search,list):
31+
vector_2_search = np.array(vector_2_search)
32+
if isinstance(value,list):
33+
value = np.array(value)
34+
3035
comp_vec = vector_2_search
3136

3237
if isinstance(vector_2_search,type(np.array([]))) == 0:

find_nearest_xy.py

+17-2
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,28 @@ def find_nearest_xy(vector_2_search,value,how_many=1):
2727
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2828
"""
2929

30+
if isinstance(vector_2_search,list):
31+
vector_2_search = np.array(vector_2_search)
32+
if isinstance(value,list):
33+
value = np.array(value)
34+
35+
3036
sd = vector_2_search.shape
31-
37+
if sd[0] == 2:
38+
vector_2_search = vector_2_search.transpose();
39+
else:
40+
vector_2_search = vector_2_search;
41+
42+
ss = value.shape
43+
if len(ss) == 1:
44+
value = np.expand_dims(value,axis=0)
45+
ss = value.shape
46+
3247
## The two column, vector search case
3348
if len(sd) == 2:
3449

3550
comp_vec = vector_2_search[:,0] + vector_2_search[:,1]*np.sqrt(np.array(-1,dtype=complex));
36-
ss = value.shape;
51+
ss = value.shape
3752
if np.all([np.min(ss) > 1,ss[0] >= ss[1]]):
3853
value2 = value.transpose();
3954
elif ss[0] == 1:

find_pixelcoords.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def find_pixelcoords(im_filename,original_width,original_height,im_pick_params=0
2626
% ### ---- minimum contour size (number of points)
2727
% ### ---- the aggregation type (0: average of marker, 1: horizontal bar)
2828
% ### ---- distance threshold for pixel combination or separation
29-
% ### ---- the distance calculation method (0:true or 1:vertical)
29+
% ### ---- the distance calculation method (0:true or 1:vertical or 2:overweight horizontal)
3030
% 0 defaults to [[0,5,0,5],[2,25,1,10]] which looks for blue points and red lines
3131
%
3232
%%%%%%%%%%%%%%%
@@ -71,7 +71,7 @@ def find_pixelcoords(im_filename,original_width,original_height,im_pick_params=0
7171
im_colors = ['blue','red']
7272
im_pick_params = [[0,5,0,50,2],[2,25,1,10,1]]
7373
### This defines how the contours are treated. There should be three parameters here:
74-
### ---- which bands to look for minima in
74+
### ---- which bands to look for minima in (0: red, 1: green, 2:blue)
7575
### ---- minimum contour size (number of points)
7676
### ---- the aggregation type (0: average of marker, 1: horizontal bar)
7777
### ---- distance threshold for pixel combination or separation

flatten_list.py

+11-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import sys
22
sys.path.append('/mnt/data01/Code/')
33

4-
def flatten_list(list_of_lists,recursive=1):
4+
def flatten_list(list_of_lists,recursive_flag=1,nan_divide=0):
55
"""
66
% (C) Nick Holschuh - Amherst College - 2022 ([email protected])
77
% This will take a list of lists (or an array of arrays) and flattens
@@ -10,7 +10,7 @@ def flatten_list(list_of_lists,recursive=1):
1010
% The inputs are as follows:
1111
%
1212
% flatten_list -- The list of lists to be flattened
13-
% recursive -- This will keep flattening until the list stops changing
13+
% recursive_flag -- This will keep flattening until the list stops changing
1414
%
1515
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1616
% The outputs are as follows:
@@ -24,6 +24,14 @@ def flatten_list(list_of_lists,recursive=1):
2424
import numpy as np
2525
from NDH_Tools import compare_list
2626

27+
if nan_divide == 1:
28+
new_list_of_lists = []
29+
for i in list_of_lists:
30+
new_list_of_lists.append(i)
31+
new_list_of_lists.append([np.nan])
32+
list_of_lists = new_list_of_lists[:-1]
33+
34+
2735
flat_list = []
2836
array_flag = 0
2937
steps = 0
@@ -49,7 +57,7 @@ def flatten_list(list_of_lists,recursive=1):
4957

5058
if comb_result:
5159
recursive_flag = 0
52-
if recursive == 0:
60+
if recursive_flag == 0:
5361
recursive_flag = 0
5462

5563
############ nan's present in the ojbect break the list comparison.

generate_pickingpdf.py

+78-31
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
################################################################################################
1010

1111

12-
def generate_pickingpdf(fn,picking_root_dir,frame_spacing=25,surf_dir='CSARP_surf_ndh',crop_type='100'):
12+
def generate_pickingpdf(fn,picking_root_dir,frame_spacing=25,surf_dir='CSARP_surf_ndh',crop_type='100',clims=[], alternative_data_opt=0):
1313
"""
1414
% (C) Nick Holschuh - Amherst College -- 2022 ([email protected])
1515
%
@@ -115,60 +115,102 @@ def generate_pickingpdf(fn,picking_root_dir,frame_spacing=25,surf_dir='CSARP_sur
115115

116116
os.system('rm -r '+picking_root_dir+seg)
117117

118-
118+
####################################################################################################################
119+
####################################################################################################################
120+
####################################################################################################################
121+
####################################################################################################################
122+
####################################################################################################################
119123
#######################################################################################################
120124
####################### The alternative is a directory full of standard files
121125
str_opt, str_ind = ndh.str_compare([fn],'standard')
122126
if len(str_opt) > 0:
127+
123128
file_list = sorted(glob.glob(fn+'/Data_*.mat'))
129+
130+
if len(file_list) > 0:
131+
ki = [];
132+
for ind,i in enumerate(file_list):
133+
if i.split('/')[-1][5] != 'i':
134+
ki.append(ind)
135+
file_list = ndh.index_list(file_list,ki)
136+
else:
137+
file_list = sorted(glob.glob(fn+'/*.mat'))
124138

125-
max_num = int(file_list[-1].split('/')[-1].split('.')[0].split('_')[-1])
126-
seg = file_list[-1].split('/')[-2]
127-
froot = '_'.join(file_list[-1].split('/')[-1].split('.')[0].split('_')[0:-1])
139+
140+
try:
141+
max_num = int(file_list[-1].split('/')[-1].split('.')[0].split('_')[-1])
142+
seg = file_list[-1].split('/')[-2]
143+
froot = '_'.join(file_list[-1].split('/')[-1].split('.')[0].split('_')[0:-1])
144+
except:
145+
max_num = len(file_list)
146+
seg = file_list[-1].split('/')[-2]
147+
froot = seg
128148
num_range = np.arange(1,max_num+1,1)
129149

150+
130151

131152
################ Here we do some directory checking to make sure all folders we need exist
132153
if not os.path.isdir(picking_root_dir+'To_Pick/'+seg):
133154
os.makedirs(picking_root_dir+'To_Pick/'+seg) ### The pdf directory where pickfiles are stored
134155

135-
if not os.path.isdir(picking_root_dir+seg):
136-
os.makedirs(picking_root_dir+seg) ### The directory for the segment
137-
138156
fig = plt.figure(figsize=(15,7))
139157
ax = plt.gca()
140158

141159
for ind1,file_num in enumerate(num_range):
160+
142161
fn_frame = '%s/%s_%0.3d.mat' % (fn,froot,file_num)
162+
print(fn_frame)
163+
if os.path.isfile(fn_frame) == 0:
164+
fn_frame = file_list[ind1]
165+
143166
radar_data,depth_data = ndh.radar_load(fn_frame,plot_flag=0,elevation1_or_depth2=0)
144167

145-
bot_inds = ndh.find_nearest(radar_data['Time'],radar_data['Bottom'])['index'].astype(float)
146-
surf_inds = ndh.find_nearest(radar_data['Time'],radar_data['Surface'])['index'].astype(float)
147-
bot_inds[bot_inds == 0] = np.NaN
148-
surf_inds[surf_inds == 0] = np.NaN
149-
150-
151-
if crop_type == '100':
152-
bot_ind = np.nanmax(bot_inds)+100
153-
crop_string = 'maxbotplus100'
168+
if len(radar_data.keys()) > 0:
169+
bot_inds = ndh.find_nearest(radar_data['Time'],radar_data['Bottom'])['index'].astype(float)
170+
surf_inds = ndh.find_nearest(radar_data['Time'],radar_data['Surface'])['index'].astype(float)
171+
bot_inds[bot_inds == 0] = np.NaN
172+
surf_inds[surf_inds == 0] = np.NaN
173+
174+
175+
if crop_type == '100':
176+
bot_ind = np.nanmax(bot_inds)+100
177+
crop_string = 'maxbotplus100'
178+
else:
179+
bot_ind = len(radar_data['Time'])
180+
crop_string = 'nocrop'
181+
182+
ndh.remove_image(ax,1,verbose=0)
183+
ndh.remove_line(ax,2,verbose=0)
184+
185+
if np.isnan(bot_ind) == 1:
186+
plt.plot(0,0)
187+
else:
188+
########### This accomodates files that have more than one data type
189+
if alternative_data_opt == 1:
190+
find_data_opts = ndh.str_compare(radar_data.keys,'Data2')
191+
if len(find_data_opts[0]) > 0:
192+
radar_data['Data'] = radar_data['Data2']
193+
194+
if len(clims) > 0:
195+
imdata = plt.imshow(10*np.log10(radar_data['Data'][:int(bot_ind),:]),
196+
origin='lower',aspect='auto',cmap='gray_r',vmin=clims[0],vmax=clims[1])
197+
else:
198+
imdata = plt.imshow(10*np.log10(radar_data['Data'][:int(bot_ind),:]),
199+
origin='lower',aspect='auto',cmap='gray_r')
200+
201+
plt.plot(np.arange(0,len(radar_data['distance'])),bot_inds,ls='--',c='green',alpha=0.2)
202+
plt.plot(np.arange(0,len(radar_data['distance'])),surf_inds,ls='--',c='green',alpha=0.2)
203+
154204
else:
155-
bot_ind = len(radar_data['Time'])
156-
crop_string = 'nocrop'
205+
plt.plot(0,0)
157206

158-
ndh.remove_image(ax,1,verbose=0)
159-
ndh.remove_line(ax,2,verbose=0)
160-
161-
imdata = plt.imshow(np.log10(radar_data['Data'][:int(bot_ind),:]),
162-
origin='lower',aspect='auto',cmap='gray_r')
163-
164-
plt.plot(np.arange(0,len(radar_data['distance'])),bot_inds,ls='--',c='green',alpha=0.2)
165-
plt.plot(np.arange(0,len(radar_data['distance'])),surf_inds,ls='--',c='green',alpha=0.2)
166207

167208
ax.invert_yaxis()
168209

169210
plt.axis('off')
170-
plt.savefig('%s%s/Frame_%0.3d.png' %(picking_root_dir,seg,file_num))
171-
211+
frame_fn = '%s/To_Pick/%s/Frame_%0.3d.png' %(picking_root_dir,seg,file_num)
212+
plt.savefig(frame_fn)
213+
print(' --- Completed Image '+str(ind1)+' of '+str(len(num_range)))
172214

173215
print('Completed the image generation')
174216

@@ -180,9 +222,14 @@ def generate_pickingpdf(fn,picking_root_dir,frame_spacing=25,surf_dir='CSARP_sur
180222
pdfend = 'StandardPicks_%s_crop_%s.pdf' %(seg,crop_string)
181223
pdfname=pdfroot+pdfend
182224

183-
frames = '%s%s/*.png' % (picking_root_dir,seg)
225+
frames = '%s/To_Pick/%s/*.png' % (picking_root_dir,seg)
184226

185227
os.system("convert -adjoin "+frames+" -gravity center -scale '90<x770<' "+pdfname)
186228
###########
187229

188-
os.system('rm -r '+picking_root_dir+seg)
230+
if 0:
231+
os.system('rm -r '+picking_root_dir+'/To_Pick/'+seg)
232+
os.system('rmdir '+picking_root_dir+'/To_Pick/'+seg)
233+
else:
234+
print('rm -r '+picking_root_dir+'/To_Pick/'+seg)
235+
print('rmdir '+picking_root_dir+'/To_Pick/'+seg)

get_contour_data.py

+22-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,18 @@
1+
################ This is the import statement required to reference scripts within the package
2+
import os,sys
3+
ndh_tools_path_opts = [
4+
'/mnt/data01/Code/',
5+
'/home/common/HolschuhLab/Code/'
6+
]
7+
for i in ndh_tools_path_opts:
8+
if os.path.isfile(i): sys.path.append(i)
9+
################################################################################################
10+
111
import numpy as np
212
import matplotlib.pyplot as plt
13+
import NDH_Tools as ndh
314

4-
def get_contour_data(contour_object):
15+
def get_contour_data(contour_object,simplify_flag=0,simplify_threshold=100):
516
"""
617
% (C) Nick Holschuh - Amherst College - 2022 ([email protected])
718
%
@@ -27,5 +38,14 @@ def get_contour_data(contour_object):
2738
contour_mat = np.array(j.vertices)
2839
contour_mat = np.concatenate([contour_mat,np.ones((len(contour_mat[:,0]),1))*cvals[ind0]],axis=1)
2940
clines.append(contour_mat)
41+
42+
if simplify_flag == 1:
43+
new_clines = np.empty(shape=(0,3))
44+
for ind0,subline in enumerate(clines):
45+
if len(subline) > simplify_threshold:
46+
new_clines = np.concatenate([new_clines,np.ones([1,3])*np.NaN,np.array(subline)])
47+
else:
48+
new_clines = clines
49+
3050

31-
return clines
51+
return new_clines

0 commit comments

Comments
 (0)