-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathclass_sonObj.py
2144 lines (1661 loc) · 68.7 KB
/
class_sonObj.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Part of PING-Mapper software
#
# GitHub: https://github.com/CameronBodine/PINGMapper
# Website: https://cameronbodine.github.io/PINGMapper/
#
# Co-Developed by Cameron S. Bodine and Dr. Daniel Buscombe
#
# Inspired by PyHum: https://github.com/dbuscombe-usgs/PyHum
#
# MIT License
#
# Copyright (c) 2025 Cameron S. Bodine
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os, sys
# Add 'pingmapper' to the path, may not need after pypi package...
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PACKAGE_DIR = os.path.dirname(SCRIPT_DIR)
sys.path.append(PACKAGE_DIR)
from pingmapper.funcs_common import *
class sonObj(object):
'''
Python class to store everything related to reading and exporting data from
Humminbird sonar recordings.
----------------
Class Attributes
----------------
* Alphabetical order *
self.beam : str
DESCRIPTION - Beam number B***
self.beamName : str
DESCRIPTION - Name of sonar beam.
self.datLen : int
DESCRIPTION - Number of bytes in DAT file.
self.datMetaFile : str
DESCRIPTION - Path to .DAT metadata file (.csv).
self.headBytes : int
DESCRIPTION - Number of header bytes for a ping.
self.headIdx : list
DESCRIPTION - List to hold byte index (offset) of each ping.
self.headStruct : dict
DESCRIPTION - Dictionary to store ping header structure.
self.headValid : bool
DESCRIPTION - Flag indicating if SON header structure is correct.
self.humDat : dict
DESCRIPTION - Dictionary to store .DAT file contents.
self.humDatStruct : dict
DESCRIPTION - Dictionary to store .DAT file structure.
self.humFile : str
DESCRIPTION - Path to .DAT file.
self.isOnix : bool
DESCRIPTION - Flag indicating if sonar recording from ONIX.
self.metaDir : str
DESCRIPTION - Path to metadata directory.
self.nchunk : int
DESCRIPTION - Number of pings/sonar records per chunk.
self.outDir : str
DESCRIPTION - Path where outputs are saved.
self.pingCnt : int
DESCRIPTION - Number of ping returns for each ping.
self.pingMax : int
DESCRIPTION - Stores largest pingCnt value (max range) for a currently
loaded sonar chunk.
self.projDir : str
DESCRIPTION - Path (top level) to output directory.
self.sonDat : arr
DESCRIPTION - Array to hold ping ping returns for currently
loaded chunk.
self.sonFile : str
DESCRIPTION - Path to .SON file.
self.sonIdxFile : str
DESCRIPTION - Path to .IDX file.
self.sonMetaDF : DataFrame
DESCRIPTION - Pandas dataframe to store .SON metadata.
self.sonMetaFile : str
DESCRIPTION - Path to .SON metadata file (.csv).
self.sonMetaPickle : str
DESCRIPTION - Path to .SON metadata pickle file (.meta).
self.wcr : bool
DESCRIPTION - Flag to export non-rectified sonar tiles w/ water column
removed (wcr) & slant range corrected.
self.tempC : float
DESCRIPTION - Water temperature (Celcius) during survey divided by 10.
self.trans : non-class function
DESCRIPTION - Function to convert utm to lat/lon.
self.wcp : bool
DESCRIPTION - Flag to export non-rectified sonar tiles w/ water column
present (wcp).
'''
#===========================================================================
def __init__(self,
sonFile,
humFile,
projDir,
tempC=0.1,
nchunk=500,
pH=8.0):
'''
Initialize a sonObj instance.
----------
Parameters
----------
sonFile : str
DESCRIPTION - Path to .SON file.
EXAMPLE - sonFile = 'C:/PINGMapper/SonarRecordings/R00001/B002.SON'
humFile : str
DESCRIPTION - Path to .DAT file associated w/ .SON directory.
EXAMPLE - humFile = 'C:/PINGMapper/SonarRecordings/R00001.DAT'
projDir : str
DESCRIPTION - Path to output directory.
EXAMPLE - projDir = 'C:/PINGMapper/procData/R00001'
tempC : float : [Default=0.1]
DESCRIPTION - Water temperature (Celcius) during survey divided by 10.
EXAMPLE - tempC = (20/10)
nchunk : int : [Default=500]
DESCRIPTION - Number of pings per chunk. Chunk size dictates size of
sonar tiles (sonograms). Most testing has been on chunk
sizes of 500 (recommended).
EXAMPLE - nchunk = 500
pH : float : [Default=8.0]
DESCRIPTION - pH of the water during sonar survey. Used in the phase
preserving filtering of high dynamic range images.
EXAMPLE - pH = 8
-------
Returns
-------
sonObj instance.
'''
# Create necessary attributes
self.sonFile = sonFile # SON file path
self.projDir = projDir # Project directory
self.humFile = humFile # DAT file path
self.tempC = tempC # Water temperature
self.nchunk = nchunk # Number of sonar records per chunk
self.pH = pH # Water pH during survey
return
############################################################################
# Decode DAT file (varies by model) #
############################################################################
# ======================================================================
def _fread(self,
infile,
num,
typ):
'''
Helper function that reads binary data in a file.
----------------------------
Required Pre-processing step
----------------------------
Called from self._getHumDat(), self._cntHead(), self._decodeHeadStruct(),
self._getSonMeta(), self._loadSonChunk()
----------
Parameters
----------
infile : file
DESCRIPTION - A binary file opened in read mode at a pre-specified
location.
num : int
DESCRIPTION - Number of bytes to read.
typ : type
DESCRIPTION - Byte type
-------
Returns
-------
List of decoded binary data
--------------------
Next Processing Step
--------------------
Returns list to function it was called from.
'''
dat = arr(typ)
dat.fromfile(infile, num)
return(list(dat))
#=======================================================================
def _saveSonMetaCSV(self, sonMetaAll):
# Write metadata to csv
if not hasattr(self, 'sonMetaFile'):
outCSV = os.path.join(self.metaDir, self.beam+"_"+self.beamName+"_meta.csv")
sonMetaAll.to_csv(outCSV, index=False, float_format='%.14f')
self.sonMetaFile = outCSV
else:
sonMetaAll.to_csv(self.sonMetaFile, index=False, float_format='%.14f')
############################################################################
# Filter sonar recording from user params #
############################################################################
# ======================================================================
def _doSonarFiltering(self,
max_heading_dev,
distance,
min_speed,
max_speed,
aoi,
time_table,
):
'''
'''
#################
# Get metadata df
self._loadSonMeta()
sonDF = self.sonMetaDF
# print('len', len(sonDF))
# print(sonDF)
#############################
# Do Heading Deviation Filter
if max_heading_dev > 0:
sonDF = self._filterHeading(sonDF, max_heading_dev, distance)
#################
# Do Speed Filter
if min_speed > 0 or max_speed > 0:
sonDF = self._filterSpeed(sonDF, min_speed, max_speed)
###############
# Do AOI Filter
if aoi:
sonDF = self._filterAOI(sonDF, aoi)
#############
# Time Filter
if time_table:
sonDF = self._filterTime(sonDF, time_table)
return sonDF
# ======================================================================
def _filterHeading(self,
df,
dev,
d,
):
'''
'''
#######
# Setup
# convert dev to radians
dev = np.deg2rad(dev)
# Set Fields for Filtering
trk_dist = 'trk_dist' # Along track distance
head = 'instr_heading' # Heading reported by instrument
filtCol = 'filter'
# Get max distance
max_dist = df[trk_dist].max()
# Set counters
win = 1 # stride of moving window
dist_start = 0 # Counter for beginning of current window
dist_end = dist_start + d # Counbter for end of current window
df[filtCol] = False
##############################
# Iterator through each window
# Compare heading deviation from first and last ping for current window
while dist_end < max_dist:
# Filter df by window
dfFilt = df[(df[trk_dist] >= dist_start) & (df[trk_dist] < dist_end)]
dfFilt[head] = np.deg2rad(dfFilt[head])
# Unwrap the heading because heading is circular
dfFilt[head] = np.unwrap(dfFilt[head])
if len(dfFilt) > 0:
# Get difference between start and end heading
start = dfFilt[head].iloc[0]
end = dfFilt[head].iloc[-1]
vessel_dev = np.abs(start - end)
# Compare vessel deviation to threshold deviation
if vessel_dev < dev:
# Keep these pings
df[filtCol].loc[dfFilt.index] = True
# dist_start += win
# dist_start = dist_end
else:
# dist_start = dist_end
# df[filtCol].loc[dfFilt.index] = False
# dist_start += win
pass
dist_start = dist_end
dist_end = dist_start + d
try:
return df
except:
sys.exit('\n\n\nERROR:\nMax heading standard deviation too small.\nPlease specify a larger value.')
# ======================================================================
def _filterTime(self,
sonDF,
time_table):
'''
'''
time_col = 'time_s'
filtTimeCol = 'filter_time'
filtCol = 'filter'
sonDF[filtTimeCol] = False
if not filtCol in sonDF.columns:
sonDF[filtCol] = True
time_table = pd.read_csv(time_table)
for i, row in time_table.iterrows():
start = row['start_seconds']
end = row['end_seconds']
# dfFilt = sonDF[(sonDF['time_s'] >= start) & (sonDF['time_s'] <= end)]
sonDF.loc[(sonDF[time_col] >= start) & (sonDF[time_col] <= end) & (sonDF[filtCol] == True), filtTimeCol] = True
sonDF[filtCol] *= sonDF[filtTimeCol]
return sonDF
# ======================================================================
def _filterSpeed(self,
sonDF,
min_speed,
max_speed):
'''
'''
speed_col = 'speed_ms'
filtCol = 'filter'
if not filtCol in sonDF.columns:
sonDF[filtCol] = True
# Filter min_speed
if min_speed > 0:
# sonDF = sonDF[sonDF['speed_ms'] >= min_speed]
sonDF.loc[sonDF[speed_col] < min_speed, filtCol] = False
# Filter max_speed
if max_speed > 0:
# sonDF = sonDF[sonDF['speed_ms'] <= max_speed]
sonDF.loc[sonDF[speed_col] > max_speed, filtCol] = False
return sonDF
# ======================================================================
def _filterAOI(self,
sonDF,
aoi):
filtCol = 'filter'
if not filtCol in sonDF.columns:
sonDF[filtCol] = True
# If .plan file (from Hydronaulix)
if os.path.basename(aoi.split('.')[-1]) == 'plan':
with open(aoi, 'r', encoding='utf-8') as f:
f = json.load(f)
# Find 'polygon' coords in nested json
# polys = []
# poly_coords = getPolyCoords(f, 'polygon')
# print(poly_coords)
f = f['mission']
f = f['items']
poly_coords = []
for i in f:
for k, v in i.items():
if k == 'polygon':
poly_coords.append(v)
aoi_poly_all = gpd.GeoDataFrame()
for poly in poly_coords:
# Extract coordinates
lat_coords = [i[0] for i in poly]
lon_coords = [i[1] for i in poly]
polygon_geom = Polygon(zip(lon_coords, lat_coords))
aoi_poly = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[polygon_geom])
aoi_poly_all = pd.concat([aoi_poly_all, aoi_poly], ignore_index=True)
# If shapefile
elif os.path.basename(aoi.split('.')[-1]) == 'shp':
aoi_poly_all = gpd.read_file(aoi)
else:
print(os.path.basename, ' is not a valid aoi file type.')
sys.exit()
# Reproject to utm
epsg = int(self.humDat['epsg'].split(':')[-1])
aoi_poly = aoi_poly_all.to_crs(crs=epsg)
aoi_poly = aoi_poly.dissolve()
# Buffer aoi
if os.path.basename(aoi.split('.')[-1]) == 'plan':
buf_dist = 0.5
aoi_poly['geometry'] = aoi_poly.geometry.buffer(buf_dist)
# Save aoi
aoi_dir = os.path.join(self.projDir, 'aoi')
aoiOut = os.path.basename(self.projDir) + '_aoi.shp'
if not os.path.exists(aoi_dir):
os.makedirs(aoi_dir)
aoiOut = os.path.join(aoi_dir, aoiOut)
aoi_poly.to_file(aoiOut)
# Convert to geodataframe
epsg = int(self.humDat['epsg'].split(':')[-1])
sonDF = gpd.GeoDataFrame(sonDF, geometry=gpd.points_from_xy(sonDF.e, sonDF.n), crs=epsg)
# Get polygon
aoi_poly = aoi_poly.geometry[0]
# Subset
mask = sonDF.within(aoi_poly)
sonDF[filtCol] *= mask
return sonDF
# ======================================================================
def _reassignChunks(self,
sonDF):
#################
# Reassign Chunks
nchunk = self.nchunk
# Make transects from consective pings using dataframe index
idx = sonDF.index.values
transect_groups = np.split(idx, np.where(np.diff(idx) != 1)[0]+1)
# print(transect_groups)
# Assign transect
transect = 0
for t in transect_groups:
sonDF.loc[sonDF.index>=t[0], 'transect'] = transect
transect += 1
# Set chunks
lastChunk = 0
newChunk = []
for name, group in sonDF.groupby('transect'):
if (len(group)%nchunk) != 0:
rdr = nchunk-(len(group)%nchunk)
chunkCnt = int(len(group)/nchunk)
chunkCnt += 1
else:
rdr = False
chunkCnt = int(len(group)/nchunk)
chunks = np.arange(chunkCnt) + lastChunk
chunks = np.repeat(chunks, nchunk)
if rdr:
chunks = chunks[:-rdr]
newChunk += list(chunks)
lastChunk = chunks[-1] + 1
del chunkCnt
sonDF['chunk_id'] = newChunk
# self._saveSonMetaCSV(sonDF)
# self._cleanup()
return sonDF
############################################################################
# Fix corrupt recording w/ missing pings #
############################################################################
# ======================================================================
def _fixNoDat(self, dfA, beams):
# Empty dataframe to store final results
df = pd.DataFrame(columns = dfA.columns)
# For tracking beam presence
b = defaultdict()
bCnt = 0
for i in beams:
b[i] = np.nan
bCnt+=1
del i
c = 0 # Current row index
while ((c) < len(dfA)):
cRow = dfA.loc[[c]]
# Check if b['beam'] is > 0, if it is, we found end of 'ping packet':
## add unfound beams as NoData to ping packet
if ~np.isnan(b[cRow['beam'].values[0]]):
# Add valid data to df
noDat = []
for k, v in b.items():
# Store valid data in df
if ~np.isnan(v):
df = pd.concat([df,dfA.loc[[v]]], ignore_index=True)
# Add beam to noDat list
else:
noDat.append(k)
# Duplicate valid data for missing rows. Remove unneccessary values.
for beam in noDat:
df = pd.concat([df, df.iloc[[-1]]], ignore_index=True)
# df.iloc[-1, df.columns.get_loc('record_num')] = np.nan
df.iloc[-1, df.columns.get_loc('index')] = np.nan
df.iloc[-1, df.columns.get_loc('volt_scale')] = np.nan
df.iloc[-1, df.columns.get_loc('f')] = np.nan
# df.iloc[-1, df.columns.get_loc('ping_cnt')] = np.nan
df.iloc[-1, df.columns.get_loc('beam')] = beam
del beam
del noDat
# reset b
for k, v in b.items():
b.update({k:np.nan})
del k, v
else:
# Add c idx to b and keep searching for beams in current packet
b[cRow['beam'].values[0]] = c
c+=1
del beams, dfA, cRow, bCnt, c, b
return df
############################################################################
# Export un-rectified sonar tiles #
############################################################################
# ==========================================================================
def _exportTiles(self,
chunk,
tileFile):
'''
Main function to read sonar record ping return values. Stores the
number of pings per chunk, chunk id, and byte index location in son file,
then calls self._loadSonChunk() to read the data into memory, then calls
self._writeTiles to save an unrectified image.
----------------------------
Required Pre-processing step
----------------------------
self._getSonMeta()
-------
Returns
-------
*.PNG un-rectified sonar tiles (sonograms)
--------------------
Next Processing Step
--------------------
NA
'''
filterIntensity = False
# Make sonar imagery directory for each beam if it doesn't exist
try:
os.mkdir(self.outDir)
except:
pass
# Filter sonMetaDF by chunk
isChunk = self.sonMetaDF['chunk_id']==chunk
sonMeta = self.sonMetaDF[isChunk].copy().reset_index()
# Update class attributes based on current chunk
self.pingMax = np.nanmax(sonMeta['ping_cnt']) # store to determine max range per chunk
# self.headIdx = sonMeta['index'] # store byte offset per ping
# self.pingCnt = sonMeta['ping_cnt'] # store ping count per ping
if ~np.isnan(self.pingMax):
# Load chunk's sonar data into memory
# self._loadSonChunk()
self._getScanChunkSingle(chunk)
# Remove shadows
if self.remShadow:
# Get mask
self._SHW_mask(chunk)
# Mask out shadows
self.sonDat = self.sonDat*self.shadowMask
# Export water column present (wcp) image
if self.wcp:
son_copy = self.sonDat.copy()
# self._doPPDRC()
# egn
if self.egn:
self._egn_wcp(chunk, sonMeta)
if self.egn_stretch > 0:
self._egnDoStretch()
self._writeTiles(chunk, imgOutPrefix='wcp', tileFile=tileFile) # Save image
self.sonDat = son_copy
del son_copy
# Export slant range corrected (water column removed) imagery
if self.wcr_src:
self._WCR_SRC(sonMeta) # Remove water column and redistribute ping returns based on FlatBottom assumption
# self._doPPDRC()
# Empirical gain normalization
if self.egn:
self._egn()
self.sonDat = np.nan_to_num(self.sonDat, nan=0)
if self.egn_stretch > 0:
self._egnDoStretch()
self._writeTiles(chunk, imgOutPrefix='wcr', tileFile=tileFile) # Save image
gc.collect()
return #self
# ==========================================================================
def _loadSonChunk(self):
'''
Reads ping returns into memory based on byte index location in son file
and number of pings to return.
----------------------------
Required Pre-processing step
----------------------------
Called from self._getScanChunkALL() or self._getScanChunkSingle()
-------
Returns
-------
2-D numpy array containing sonar intensity
--------------------
Next Processing Step
--------------------
Return numpy array to self._getScanChunkALL() or self._getScanChunkSingle()
'''
sonDat = np.zeros((int(self.pingMax), len(self.pingCnt))).astype(int) # Initialize array to hold sonar returns
file = open(self.sonFile, 'rb') # Open .SON file
for i in range(len(self.headIdx)):
if ~np.isnan(self.headIdx[i]):
ping_len = min(self.pingCnt[i].astype(int), self.pingMax)
headIDX = self.headIdx[i].astype(int)
son_offset = self.son_offset[i].astype(int)
# pingIdx = headIDX + self.headBytes # Determine byte offset to sonar returns
pingIdx = headIDX + son_offset
file.seek(pingIdx) # Move to that location
# Get the ping
buffer = file.read(ping_len)
if self.flip_port:
buffer = buffer[::-1]
# Read the data
dat = np.frombuffer(buffer, dtype='>u1')
try:
sonDat[:ping_len, i] = dat
except:
ping_len = len(dat)
sonDat[:ping_len, i] = dat
file.close()
self.sonDat = sonDat
return
# ======================================================================
def _WC_mask(self, i, son=True):
'''
'''
# Get sonMeta
if not hasattr(self, 'sonMetaDF'):
self._loadSonMeta()
if son:
# self._loadSonMeta()
self._getScanChunkSingle(i)
# Filter sonMetaDF by chunk
isChunk = self.sonMetaDF['chunk_id']==i
sonMeta = self.sonMetaDF[isChunk].copy().reset_index()
# Load depth (in real units) and convert to pixels
# bedPick = round(sonMeta['dep_m'] / sonMeta['pix_m'], 0).astype(int)
bedPick = round(sonMeta['dep_m'] / self.pixM, 0).astype(int)
minDep = min(bedPick)
del sonMeta, self.sonMetaDF
# Make zero mask
wc_mask = np.zeros((self.sonDat.shape))
# Fill non-wc pixels with 1
for p, s in enumerate(bedPick):
wc_mask[s:, p] = 1
self.wcMask = wc_mask
self.minDep = minDep
self.bedPick = bedPick
return
# ======================================================================
def _WCR_SRC(self, sonMeta, son=True):
'''
Slant range correction is the process of relocating sonar returns after
water column removal by converting slant range distances to the bed into
horizontal distances based off the depth at nadir. As SSS does not
measure depth across the track, we must assume depth is constant across
the track (Flat bottom assumption). The pathagorean theorem is used
to calculate horizontal distance from slant range distance and depth at
nadir.
----------
Parameters
----------
sonMeta : DataFrame
DESCRIPTION - Dataframe containing ping metadata.
----------------------------
Required Pre-processing step
----------------------------
Called from self._getScanChunkALL() or self._getScanChunkSingle()
-------
Returns
-------
Self w/ array of relocated intensities stored in self.sonDat.
--------------------
Next Processing Step
--------------------
Returns relocated bed intensities to self._getScanChunkALL() or
self._getScanChunkSingle()
'''
# Load depth (in real units) and convert to pixels
# bedPick = round(sonMeta['dep_m'] / sonMeta['pix_m'], 0).astype(int)
bedPick = round(sonMeta['dep_m'] / self.pixM, 0).astype(int)
# Initialize 2d array to store relocated sonar records
srcDat = np.zeros((self.sonDat.shape[0], self.sonDat.shape[1])).astype(np.float32)#.astype(int)
#Iterate each ping
for j in range(self.sonDat.shape[1]):
depth = bedPick[j] # Get depth (in pixels) at nadir
dd = depth**2
# Create 1d array to store relocated bed pixels. Set to nan so we
## can later interpolate over gaps.
pingDat = (np.ones((self.sonDat.shape[0])).astype(np.float32)) * np.nan
dataExtent = 0
#Iterate each sonar/ping return
for i in range(self.sonDat.shape[0]):
if i >= depth:
intensity = self.sonDat[i,j] # Get the intensity value
srcIndex = int(round(math.sqrt(i**2 - dd),0)) #Calculate horizontal range (in pixels) using pathagorean theorem
pingDat[srcIndex] = intensity # Store intensity at appropriate horizontal range
dataExtent = srcIndex # Store range extent (max range) of ping
else:
pass
pingDat[dataExtent:]=0 # Zero out values past range extent so we don't interpolate past this
# Process of relocating bed pixels will introduce across track gaps
## in the array so we will interpolate over gaps to fill them.
nans, x = np.isnan(pingDat), lambda z: z.nonzero()[0]
pingDat[nans] = np.interp(x(nans), x(~nans), pingDat[~nans])
# Store relocated ping in output array
if son:
srcDat[:,j] = np.around(pingDat, 0)
else:
srcDat[:,j] = pingDat
del pingDat
if son:
self.sonDat = srcDat.astype(int) # Store in class attribute for later use
else:
self.sonDat = srcDat
del srcDat
return #self
# ======================================================================
def _WCR_crop(self,
sonMeta,
crop=True):
# Load depth (in real units) and convert to pixels
bedPick = round(sonMeta['dep_m'] / self.pixM, 0).astype(int)
minDep = min(bedPick)
sonDat = self.sonDat
# Zero out water column
for j, d in enumerate(bedPick):
sonDat[:d, j] = 0
# Crop to min depth
if crop:
sonDat = sonDat[minDep:,]
self.sonDat = sonDat
return minDep
# ======================================================================
def _WCO(self,
sonMeta):
# Load depth (in real units) and convert to pixels
bedPick = round(sonMeta['dep_m'] / self.pixM, 0).astype(int)
maxDep = max(bedPick)
sonDat = self.sonDat
# Zero out water column
for j, d in enumerate(bedPick):
sonDat[d:, j] = 0
# Crop to min depth
sonDat = sonDat[:maxDep,]
self.sonDat = sonDat
return maxDep
# ======================================================================
def _SHW_mask(self, i, son=True):
'''
'''
# Get sonar data and shadow pix coordinates
if son:
self._getScanChunkSingle(i)
sonDat = self.sonDat
shw_pix = self.shadow[i]
# Create a mask and work on that first, then mask sonDat
mask = np.ones(sonDat.shape)
for k, val in shw_pix.items():
for v in val:
try:
mask[v[0]:v[1], k] = 0
except:
pass
self.shadowMask = mask
return #self
# ======================================================================
def _SHW_crop(self, i, maxCrop=True, croprange=True):
'''
maxCrop: True: ping-wise crop; False: crop tile to max range
'''
buf=50 # Add buf if maxCrop is false
# Get sonar data
sonDat = self.sonDat
# Get sonar data and shadow pix coordinates
self._SHW_mask(i)
mask = self.shadowMask
# Remove non-contiguous regions
reg = label(mask)
# Find region w/ min row value/highest up on sonogram
highReg = -1
minRow = mask.shape[0]
for region in regionprops(reg):
minr, minc, maxr, maxc = region.bbox
if (minr < minRow) and (highReg != 0):
highReg = region.label
minRow = minr
# Keep only region matching highReg, update mask with reg
mask = np.where(reg==highReg, 1, 0)
# Find max range of valid son returns
max_r = []
mask[mask.shape[0]-1, :] = 0 # Zero-out last row
R = mask.shape[0] # max range
P = mask.shape[1] # number of pings
for c in range(P):
bed = np.where(mask[:,c]==1)[0]
try:
bed = np.split(bed, np.where(np.diff(bed) != 1)[0]+1)[-1][-1]
except:
bed = np.nan
max_r.append(bed)