pingmapper 5.5.6__tar.gz → 5.5.8__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {pingmapper-5.5.6 → pingmapper-5.5.8}/PKG-INFO +1 -1
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/__main__.py +7 -0
- pingmapper-5.5.8/pingmapper/batch_global_egn.py +65 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/class_portstarObj.py +30 -92
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/funcs_common.py +83 -23
- pingmapper-5.5.8/pingmapper/global_egn.py +300 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/gui_main.py +18 -1
- pingmapper-5.5.8/pingmapper/main_mosaic.py +336 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/main_readFiles.py +64 -22
- pingmapper-5.5.8/pingmapper/mosaic_quality.py +910 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/nonGUI_batch_main.py +30 -10
- pingmapper-5.5.8/pingmapper/nonGUI_mosaic.py +44 -0
- pingmapper-5.5.8/pingmapper/version.py +1 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper.egg-info/PKG-INFO +1 -1
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper.egg-info/SOURCES.txt +8 -2
- pingmapper-5.5.8/tests/test_mosaic_quality.py +219 -0
- pingmapper-5.5.6/pingmapper/version.py +0 -1
- {pingmapper-5.5.6 → pingmapper-5.5.8}/LICENSE +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/README.md +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/__init__.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/class_mapSubstrateObj.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/class_rectObj.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/class_sonObj.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/class_sonObj_nadirgaptest.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/default_params.json +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/doWork.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/funcs_model.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/funcs_rectify.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/main_mapSubstrate.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/main_rectify.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/nonGui_main.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/processing_scripts/main_batchDirectory_2024-01-18_0926.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/processing_scripts/main_batchDirectory_2024-01-18_0929.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/scratch/funcs_pyhum_correct.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/scratch/main.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/scratch/main_batchDirectory.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/self_check.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/test_PINGMapper.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/test_cli_self_check.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/test_dq_filter.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/test_time.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/DRAFT_Workflows/avg_predictions_Mussel_WBL.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/DRAFT_Workflows/gen_centerline.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/DRAFT_Workflows/gen_centerline_from_bankline.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/DRAFT_Workflows/gen_centerline_trkpnts_fitspline_DRAFT.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/DRAFT_Workflows/testEXAMPLE_mosaic_logit.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/RawEGN_avg_predictions.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/00_substrate_logits_mosaic_transects.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/00_substrate_shps_mosaic_transects.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/01_gen_centerline_from_coverage.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/02_gen_summary_stamp_shps.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/03_gen_summary_shp.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/04_combine_summary_shp_csv.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/05_gen_summary_shp_plots.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/06_compare_raw-egn_volume.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/08_raw-egn_hardReacheFreq_hist.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/09_raw-egn_PatchSize_density.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/Substrate_Summaries/summarize_project_substrate.py +0 -0
- /pingmapper-5.5.6/pingmapper/utils/main_mosaic_transects.py → /pingmapper-5.5.8/pingmapper/utils/_old_main_mosaic_transects.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/export_coverage.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/kml2mosaic.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper/utils/tile2mosaic.py +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper.egg-info/dependency_links.txt +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper.egg-info/requires.txt +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pingmapper.egg-info/top_level.txt +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/pyproject.toml +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/setup.cfg +0 -0
- {pingmapper-5.5.6 → pingmapper-5.5.8}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pingmapper
|
|
3
|
-
Version: 5.5.
|
|
3
|
+
Version: 5.5.8
|
|
4
4
|
Summary: Open-source interface for processing recreation-grade side scan sonar datasets and reproducibly mapping benthic habitat
|
|
5
5
|
Author: Cameron Bodine, Daniel Buscombe, Iury T Simoes-Sousa
|
|
6
6
|
Author-email: bodine.cs@gmail.email
|
|
@@ -49,6 +49,13 @@ def main(process):
|
|
|
49
49
|
from pingmapper.test_PINGMapper import test
|
|
50
50
|
test(2)
|
|
51
51
|
|
|
52
|
+
# Merge mosaics from many recordings (sonar-quality merge)
|
|
53
|
+
elif process == 'mosaic':
|
|
54
|
+
print('\n\nLaunching mosaic merge...\n\n')
|
|
55
|
+
from pingmapper.main_mosaic import main as mosaic_main
|
|
56
|
+
import sys
|
|
57
|
+
mosaic_main(sys.argv[2:])
|
|
58
|
+
|
|
52
59
|
elif process in ('check', 'test_unit'):
|
|
53
60
|
print('\n\nRunning PINGMapper self-check...\n\n')
|
|
54
61
|
from pingmapper.self_check import run_self_check
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Batch processing with one global EGN correction shared by all recordings.
|
|
2
|
+
|
|
3
|
+
Phase 1 read every recording without EGN or exports (nav, depth, chunks)
|
|
4
|
+
Phase 2 pool range-wise means, min/max and histograms across recordings
|
|
5
|
+
Phase 3 re-open each project (project_mode=2) with EGN from the pooled file
|
|
6
|
+
and run the requested exports/rectification
|
|
7
|
+
Phase 4 optionally merge the resulting mosaics
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
from pingmapper.batch_global_egn import process_with_global_egn
|
|
11
|
+
process_with_global_egn(in_dir, out_dir, params, sampling='moderate')
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
|
|
16
|
+
from pingmapper.doWork import doWork
|
|
17
|
+
from pingmapper import global_egn
|
|
18
|
+
|
|
19
|
+
# Output-producing steps that are deferred until the global EGN is ready.
|
|
20
|
+
_DEFERRED_OFF = {
|
|
21
|
+
'egn': False, 'wcp': False, 'wcm': False, 'wcr': False, 'wco': False,
|
|
22
|
+
'rect_wcp': False, 'rect_wcr': False, 'pred_sub': False, 'map_sub': False,
|
|
23
|
+
'export_poly': False, 'pltSubClass': False, 'banklines': False,
|
|
24
|
+
'coverage': False,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def process_with_global_egn(in_dir=None, out_dir=None, params=None, sampling='moderate',
|
|
29
|
+
in_files=None, prefix='', suffix='', preserve_subdirs=False,
|
|
30
|
+
means_file=None, merge=False, merge_kw=None, log=print, workers=None):
|
|
31
|
+
"""Process recordings with a single EGN curve pooled across all of them.
|
|
32
|
+
|
|
33
|
+
``params`` are the normal doWork parameters (egn is forced on in phase 3).
|
|
34
|
+
``sampling`` is 'low', 'moderate' or 'high' (share of chunks used to build
|
|
35
|
+
the curve). Returns {'phase1', 'phase3', 'means_file', 'mosaic'}.
|
|
36
|
+
"""
|
|
37
|
+
if not out_dir:
|
|
38
|
+
raise ValueError('out_dir is required.')
|
|
39
|
+
params = dict(params or {})
|
|
40
|
+
common = dict(in_dir=in_dir, in_files=in_files, out_dir=out_dir, batch=True,
|
|
41
|
+
prefix=prefix, suffix=suffix, preserve_subdirs=preserve_subdirs)
|
|
42
|
+
|
|
43
|
+
log('Phase 1/3: reading recordings (no EGN, no exports)')
|
|
44
|
+
p1 = dict(params, **_DEFERRED_OFF)
|
|
45
|
+
r1 = doWork(params=p1, **common)
|
|
46
|
+
ok = [r['inFile'] for r in r1 if r['success']]
|
|
47
|
+
if not ok:
|
|
48
|
+
raise RuntimeError('No recordings were read successfully.')
|
|
49
|
+
|
|
50
|
+
means_file = means_file or os.path.join(out_dir, 'global_egn.npz')
|
|
51
|
+
log('Phase 2/3: pooling EGN across %d recordings (%s sampling)' % (len(ok), sampling))
|
|
52
|
+
global_egn.build(out_dir, means_file, sampling, log=log, workers=workers)
|
|
53
|
+
|
|
54
|
+
log('Phase 3/3: applying global EGN and exporting')
|
|
55
|
+
p3 = dict(params, project_mode=2, egn=True, egn_means_file=means_file)
|
|
56
|
+
kw = dict(common, in_files=ok)
|
|
57
|
+
r3 = doWork(params=p3, **kw)
|
|
58
|
+
|
|
59
|
+
mosaic = None
|
|
60
|
+
if merge:
|
|
61
|
+
from pingmapper import main_mosaic
|
|
62
|
+
kw = dict(colormap=params.get('son_colorMap'), **(merge_kw or {}))
|
|
63
|
+
mosaic = main_mosaic.merge_mosaics(root=out_dir, **kw)
|
|
64
|
+
|
|
65
|
+
return {'phase1': r1, 'phase3': r3, 'means_file': means_file, 'mosaic': mosaic}
|
|
@@ -401,9 +401,30 @@ class portstarObj(object):
|
|
|
401
401
|
for i, pred in enumerate(predictToMosaic):
|
|
402
402
|
_ = Parallel(n_jobs=safe_n_jobs(bands, threadCnt), verbose=10)(delayed(self._mosaicVRT)([pred], overview, i, bands=[c], son=True) for c in range(1,bands+1))
|
|
403
403
|
|
|
404
|
-
|
|
405
|
-
|
|
404
|
+
#=======================================================================
|
|
405
|
+
def _transectChunkFiles(self, subdir, iter_groups, chunkField='chunk_id'):
|
|
406
|
+
'''
|
|
407
|
+
Explicit {transect_id: [chunk tifs]} for port and star combined, found
|
|
408
|
+
by transect id (not by position), so a transect with no exported
|
|
409
|
+
chunks cannot shift the others onto the wrong id.
|
|
410
|
+
'''
|
|
411
|
+
files = {}
|
|
412
|
+
for son in (self.port, self.star):
|
|
413
|
+
son._loadSonMeta()
|
|
414
|
+
sonDir = os.path.join(son.outDir, subdir)
|
|
415
|
+
for name, group in iter_groups(son.sonMetaDF):
|
|
416
|
+
try:
|
|
417
|
+
tid = int(name)
|
|
418
|
+
except (TypeError, ValueError):
|
|
419
|
+
tid = 0
|
|
420
|
+
for chunk in pd.unique(group[chunkField]):
|
|
421
|
+
zero = son._addZero(chunk)
|
|
422
|
+
imgs = glob(os.path.join(sonDir, '*_{}{}.tif'.format(zero, chunk)))
|
|
423
|
+
if len(imgs) > 0:
|
|
424
|
+
files.setdefault(tid, []).append(imgs[0])
|
|
425
|
+
return dict(sorted(files.items()))
|
|
406
426
|
|
|
427
|
+
#=======================================================================
|
|
407
428
|
def _createMosaicTransect(self,
|
|
408
429
|
mosaic=1,
|
|
409
430
|
overview=True,
|
|
@@ -457,93 +478,10 @@ class portstarObj(object):
|
|
|
457
478
|
|
|
458
479
|
if son:
|
|
459
480
|
if self.port.rect_wcp: # Moscaic wcp sonograms if previousl exported
|
|
460
|
-
self.
|
|
461
|
-
df = self.port.sonMetaDF
|
|
462
|
-
|
|
463
|
-
portPath = os.path.join(self.port.outDir, 'rect_wcp')
|
|
464
|
-
|
|
465
|
-
port = []
|
|
466
|
-
for name, group in _iter_groups(df):
|
|
467
|
-
chunks = pd.unique(group[chunkField])
|
|
468
|
-
port_transect = []
|
|
469
|
-
for chunk in chunks:
|
|
470
|
-
zero = self.port._addZero(chunk)
|
|
471
|
-
img_path = os.path.join(portPath, '*_{}{}.tif'.format(zero, chunk))
|
|
472
|
-
imgs = glob(img_path)
|
|
473
|
-
if len(imgs) == 0:
|
|
474
|
-
continue
|
|
475
|
-
port_transect.append(imgs[0])
|
|
476
|
-
if len(port_transect) > 0:
|
|
477
|
-
port.append(port_transect)
|
|
478
|
-
|
|
479
|
-
self.star._loadSonMeta()
|
|
480
|
-
df = self.star.sonMetaDF
|
|
481
|
-
|
|
482
|
-
starPath = os.path.join(self.star.outDir, 'rect_wcp')
|
|
483
|
-
|
|
484
|
-
star = []
|
|
485
|
-
for name, group in _iter_groups(df):
|
|
486
|
-
chunks = pd.unique(group[chunkField])
|
|
487
|
-
star_transect = []
|
|
488
|
-
for chunk in chunks:
|
|
489
|
-
zero = self.port._addZero(chunk)
|
|
490
|
-
img_path = os.path.join(starPath, '*_{}{}.tif'.format(zero, chunk))
|
|
491
|
-
imgs = glob(img_path)
|
|
492
|
-
if len(imgs) == 0:
|
|
493
|
-
continue
|
|
494
|
-
star_transect.append(imgs[0])
|
|
495
|
-
if len(star_transect) > 0:
|
|
496
|
-
star.append(star_transect)
|
|
497
|
-
|
|
498
|
-
wcpToMosaic = [list(itertools.chain(*i)) for i in zip(port, star)]
|
|
481
|
+
wcpToMosaic = self._transectChunkFiles('rect_wcp', _iter_groups, chunkField)
|
|
499
482
|
|
|
500
|
-
if self.port.rect_wcr: # Moscaic
|
|
501
|
-
|
|
502
|
-
self.port._loadSonMeta()
|
|
503
|
-
df = self.port.sonMetaDF
|
|
504
|
-
|
|
505
|
-
portPath = os.path.join(self.port.outDir, 'rect_wcr')
|
|
506
|
-
|
|
507
|
-
port = []
|
|
508
|
-
for name, group in _iter_groups(df):
|
|
509
|
-
chunks = pd.unique(group[chunkField])
|
|
510
|
-
port_transect = []
|
|
511
|
-
for chunk in chunks:
|
|
512
|
-
# try:
|
|
513
|
-
zero = self.port._addZero(chunk)
|
|
514
|
-
img_path = os.path.join(portPath, '*_{}{}.tif'.format(zero, chunk))
|
|
515
|
-
imgs = glob(img_path)
|
|
516
|
-
if len(imgs) == 0:
|
|
517
|
-
continue
|
|
518
|
-
port_transect.append(imgs[0])
|
|
519
|
-
# except:
|
|
520
|
-
# pass
|
|
521
|
-
if len(port_transect) > 0:
|
|
522
|
-
port.append(port_transect)
|
|
523
|
-
|
|
524
|
-
self.star._loadSonMeta()
|
|
525
|
-
df = self.star.sonMetaDF
|
|
526
|
-
|
|
527
|
-
starPath = os.path.join(self.star.outDir, 'rect_wcr')
|
|
528
|
-
|
|
529
|
-
star = []
|
|
530
|
-
for name, group in _iter_groups(df):
|
|
531
|
-
chunks = pd.unique(group[chunkField])
|
|
532
|
-
star_transect = []
|
|
533
|
-
for chunk in chunks:
|
|
534
|
-
# try:
|
|
535
|
-
zero = self.star._addZero(chunk)
|
|
536
|
-
img_path = os.path.join(starPath, '*_{}{}.tif'.format(zero, chunk))
|
|
537
|
-
imgs = glob(img_path)
|
|
538
|
-
if len(imgs) == 0:
|
|
539
|
-
continue
|
|
540
|
-
star_transect.append(imgs[0])
|
|
541
|
-
# except:
|
|
542
|
-
# pass
|
|
543
|
-
if len(star_transect) > 0:
|
|
544
|
-
star.append(star_transect)
|
|
545
|
-
|
|
546
|
-
srcToMosaic = [list(itertools.chain(*i)) for i in zip(port, star)]
|
|
483
|
+
if self.port.rect_wcr: # Moscaic wcr sonograms if previousl exported
|
|
484
|
+
srcToMosaic = self._transectChunkFiles('rect_wcr', _iter_groups, chunkField)
|
|
547
485
|
|
|
548
486
|
else:
|
|
549
487
|
if self.port.map_sub:
|
|
@@ -595,10 +533,10 @@ class portstarObj(object):
|
|
|
595
533
|
if son:
|
|
596
534
|
if self.port.rect_wcp:
|
|
597
535
|
if len(wcpToMosaic) > 0:
|
|
598
|
-
|
|
536
|
+
res = Parallel(n_jobs=safe_n_jobs(len(wcpToMosaic), threadCnt), verbose=10)(delayed(self._mosaicGtiff)([wcp], overview, i, son=son) for i, wcp in wcpToMosaic.items())
|
|
599
537
|
if self.port.rect_wcr:
|
|
600
538
|
if len(srcToMosaic) > 0:
|
|
601
|
-
|
|
539
|
+
res = Parallel(n_jobs=safe_n_jobs(len(srcToMosaic), threadCnt), verbose=10)(delayed(self._mosaicGtiff)([src], overview, i, son=son) for i, src in srcToMosaic.items())
|
|
602
540
|
else:
|
|
603
541
|
if self.port.map_sub:
|
|
604
542
|
_ = Parallel(n_jobs=safe_n_jobs(len(subToMosaic), threadCnt), verbose=10)(delayed(self._mosaicGtiff)([sub], overview=overview, i=i, son=son) for i, sub in enumerate(subToMosaic))
|
|
@@ -613,9 +551,9 @@ class portstarObj(object):
|
|
|
613
551
|
elif mosaic == 2:
|
|
614
552
|
if son:
|
|
615
553
|
if self.port.rect_wcp:
|
|
616
|
-
_ = Parallel(n_jobs=safe_n_jobs(len(wcpToMosaic), threadCnt), verbose=10)(delayed(self._mosaicVRT)([wcp], overview, i, son=son) for i, wcp in
|
|
554
|
+
_ = Parallel(n_jobs=safe_n_jobs(len(wcpToMosaic), threadCnt), verbose=10)(delayed(self._mosaicVRT)([wcp], overview, i, son=son) for i, wcp in wcpToMosaic.items())
|
|
617
555
|
if self.port.rect_wcr:
|
|
618
|
-
_ = Parallel(n_jobs=safe_n_jobs(len(srcToMosaic), threadCnt), verbose=10)(delayed(self._mosaicVRT)([src], overview, i, son=son) for i, src in
|
|
556
|
+
_ = Parallel(n_jobs=safe_n_jobs(len(srcToMosaic), threadCnt), verbose=10)(delayed(self._mosaicVRT)([src], overview, i, son=son) for i, src in srcToMosaic.items())
|
|
619
557
|
else:
|
|
620
558
|
if self.port.map_sub:
|
|
621
559
|
_ = Parallel(n_jobs=safe_n_jobs(len(subToMosaic), threadCnt), verbose=10)(delayed(self._mosaicVRT)([sub], overview, i, son=son) for i, sub in enumerate(subToMosaic))
|
|
@@ -326,42 +326,102 @@ class Logger(object):
|
|
|
326
326
|
pass
|
|
327
327
|
|
|
328
328
|
# =========================================================
|
|
329
|
-
def
|
|
329
|
+
def segmentationModelsExist(modelDir):
|
|
330
|
+
"""True only if the model folder was fully extracted (not just created)."""
|
|
331
|
+
return os.path.isdir(modelDir) and any(
|
|
332
|
+
f.endswith('.json')
|
|
333
|
+
for _, _, files in os.walk(modelDir) for f in files
|
|
334
|
+
)
|
|
330
335
|
|
|
331
|
-
# Create directories
|
|
332
|
-
if not os.path.exists(modelDir):
|
|
333
|
-
os.makedirs(modelDir)
|
|
334
336
|
|
|
335
|
-
|
|
336
|
-
url = 'https://zenodo.org/records/10093642/files/PINGMapperv2.0_SegmentationModelsv1.0.zip?download=1'
|
|
337
|
-
print('\n\nDownloading segmentation models (v1.0):\nhttps://zenodo.org/records/10092289/files/PINGMapperv2.0_SegmentationModelsv1.0.zip?download=1')
|
|
337
|
+
def downloadSegmentationModelsv1_0(modelDir, retries=4):
|
|
338
338
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
# open(filename, 'wb').write(r.content)
|
|
342
|
-
with open(filename, 'wb') as f:
|
|
343
|
-
f.write(r.content)
|
|
339
|
+
url = 'https://zenodo.org/records/10093642/files/PINGMapperv2.0_SegmentationModelsv1.0.zip?download=1'
|
|
340
|
+
print('\n\nDownloading segmentation models (v1.0):\n{}'.format(url))
|
|
344
341
|
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
342
|
+
# Start clean in case a previous attempt left a partial folder
|
|
343
|
+
if os.path.exists(modelDir):
|
|
344
|
+
shutil.rmtree(_long_path(modelDir), ignore_errors=True)
|
|
345
|
+
os.makedirs(modelDir, exist_ok=True)
|
|
348
346
|
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
347
|
+
filename = modelDir+'.zip'
|
|
348
|
+
last_err = None
|
|
349
|
+
for attempt in range(1, retries + 1):
|
|
350
|
+
try:
|
|
351
|
+
with requests.get(url, allow_redirects=True, stream=True, timeout=(30, 120)) as r:
|
|
352
|
+
r.raise_for_status()
|
|
353
|
+
with open(filename, 'wb') as f:
|
|
354
|
+
for chunk in r.iter_content(chunk_size=1024*1024):
|
|
355
|
+
f.write(chunk)
|
|
356
|
+
|
|
357
|
+
# Guard against error pages (e.g. 504) saved as the zip
|
|
358
|
+
if not zipfile.is_zipfile(filename):
|
|
359
|
+
raise RuntimeError('Downloaded file is not a valid zip archive.')
|
|
360
|
+
|
|
361
|
+
# \\?\ prefix lets extraction exceed MAX_PATH on Windows without admin rights
|
|
362
|
+
with zipfile.ZipFile(filename, 'r') as z_fp:
|
|
363
|
+
z_fp.extractall(_long_path(modelDir))
|
|
364
|
+
|
|
365
|
+
if not segmentationModelsExist(modelDir):
|
|
366
|
+
raise RuntimeError('Models were not extracted correctly.')
|
|
367
|
+
|
|
368
|
+
os.remove(filename)
|
|
369
|
+
print('Model download success!')
|
|
370
|
+
return
|
|
371
|
+
except Exception as e:
|
|
372
|
+
last_err = e
|
|
373
|
+
print('Model download attempt {} of {} failed: {}'.format(attempt, retries, e))
|
|
374
|
+
if os.path.exists(filename):
|
|
375
|
+
os.remove(filename)
|
|
376
|
+
if attempt < retries:
|
|
377
|
+
time.sleep(5 * attempt)
|
|
378
|
+
|
|
379
|
+
shutil.rmtree(_long_path(modelDir), ignore_errors=True)
|
|
380
|
+
raise RuntimeError(
|
|
381
|
+
'Unable to download segmentation models after {} attempts: {}\n'
|
|
382
|
+
'Download manually from {} and extract to {}'.format(retries, last_err, url, modelDir)
|
|
383
|
+
)
|
|
352
384
|
|
|
353
385
|
|
|
354
386
|
# =========================================================
|
|
355
387
|
def get_segmentation_model_dir():
|
|
356
388
|
"""
|
|
357
389
|
Return the default local directory for segmentation models.
|
|
358
|
-
Models are stored in
|
|
359
|
-
that can break zip extraction on Windows.
|
|
390
|
+
Models are stored in a short path outside the environment to avoid deep
|
|
391
|
+
paths that can break zip extraction on Windows. Set PINGMAPPER_MODEL_DIR to
|
|
392
|
+
override. If the home folder is synced by OneDrive (which can lock files
|
|
393
|
+
mid-extraction), a folder at the drive root is used instead.
|
|
360
394
|
"""
|
|
395
|
+
override = os.environ.get('PINGMAPPER_MODEL_DIR')
|
|
396
|
+
if override:
|
|
397
|
+
return os.path.normpath(override)
|
|
398
|
+
|
|
399
|
+
model_name = 'PINGMapperv2.0_SegmentationModelsv1.0'
|
|
361
400
|
home_dir = os.path.expanduser('~')
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
401
|
+
|
|
402
|
+
if os.name == 'nt' and 'onedrive' in home_dir.lower():
|
|
403
|
+
drive = os.path.splitdrive(home_dir)[0] or 'C:'
|
|
404
|
+
alt = os.path.join(drive + os.sep, '.pingmapper', 'models')
|
|
405
|
+
try:
|
|
406
|
+
os.makedirs(alt, exist_ok=True)
|
|
407
|
+
print('Home folder is in OneDrive; storing models in {} instead.'.format(alt))
|
|
408
|
+
return os.path.normpath(os.path.join(alt, model_name))
|
|
409
|
+
except OSError:
|
|
410
|
+
print('Warning: models will be stored in OneDrive and sync may interfere.')
|
|
411
|
+
|
|
412
|
+
return os.path.normpath(os.path.join(home_dir, '.pingmapper', 'models', model_name))
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _long_path(path):
|
|
416
|
+
"""Return a \\\\?\\ prefixed absolute path on Windows; unchanged elsewhere."""
|
|
417
|
+
if os.name != 'nt':
|
|
418
|
+
return path
|
|
419
|
+
path = os.path.abspath(path)
|
|
420
|
+
if path.startswith('\\\\?\\'):
|
|
421
|
+
return path
|
|
422
|
+
if path.startswith('\\\\'):
|
|
423
|
+
return '\\\\?\\UNC\\' + path[2:]
|
|
424
|
+
return '\\\\?\\' + path
|
|
365
425
|
|
|
366
426
|
|
|
367
427
|
# # =========================================================
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
'''
|
|
2
|
+
Global empirical gain normalization (EGN) across many recordings.
|
|
3
|
+
|
|
4
|
+
Each recording normally gets its own range-wise mean intensity curve. That
|
|
5
|
+
makes neighbouring recordings differ in tone. This module pools sampled chunk
|
|
6
|
+
means from many processed recordings into one curve per channel, saved to an
|
|
7
|
+
.npz file. Pass that file to PINGMapper as ``egn_means_file`` and every
|
|
8
|
+
recording is normalised with the same curve.
|
|
9
|
+
|
|
10
|
+
Typical use (recordings already read, i.e. a ``meta`` folder exists):
|
|
11
|
+
|
|
12
|
+
from pingmapper import global_egn
|
|
13
|
+
global_egn.build('C:/proj/out', 'C:/proj/egn_global.npz', sampling='low')
|
|
14
|
+
|
|
15
|
+
then reprocess with ``egn=True``, ``egn_means_file='C:/proj/egn_global.npz'``
|
|
16
|
+
and ``project_mode=2``.
|
|
17
|
+
'''
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
import glob
|
|
22
|
+
import argparse
|
|
23
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
# Fraction of chunks sampled per recording
|
|
28
|
+
SAMPLING = {'low': 0.25, 'moderate': 0.5, 'high': 1.0}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def select_chunks(chunks, sampling='high'):
|
|
32
|
+
'''Evenly spaced, repeatable subset of chunks (at least one).'''
|
|
33
|
+
chunks = list(chunks)
|
|
34
|
+
if isinstance(sampling, str):
|
|
35
|
+
if sampling not in SAMPLING:
|
|
36
|
+
raise ValueError("sampling must be one of %s" % list(SAMPLING))
|
|
37
|
+
frac = SAMPLING[sampling]
|
|
38
|
+
else:
|
|
39
|
+
frac = float(sampling)
|
|
40
|
+
n = len(chunks)
|
|
41
|
+
if n == 0 or frac >= 1:
|
|
42
|
+
return chunks
|
|
43
|
+
k = max(1, int(round(n*frac)))
|
|
44
|
+
idx = np.unique(np.linspace(0, n-1, k).round().astype(int))
|
|
45
|
+
return [chunks[i] for i in idx]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def stack_means(chunk_means):
|
|
49
|
+
'''Stack (bed, wc) chunk mean vectors into nan padded 2D arrays.'''
|
|
50
|
+
lv = max(c[0].shape[0] for c in chunk_means)
|
|
51
|
+
lw = max(c[1].shape[0] for c in chunk_means)
|
|
52
|
+
bed = np.full((lv, len(chunk_means)), np.nan)
|
|
53
|
+
wc = np.full((lw, len(chunk_means)), np.nan)
|
|
54
|
+
for i, c in enumerate(chunk_means):
|
|
55
|
+
bed[:c[0].shape[0], i] = c[0]
|
|
56
|
+
wc[:c[1].shape[0], i] = c[1]
|
|
57
|
+
return bed, wc
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def pool(chunk_means_by_beam):
|
|
61
|
+
'''
|
|
62
|
+
Pool chunk means for each beam name.
|
|
63
|
+
|
|
64
|
+
chunk_means_by_beam: {beam: [(bed_means, wc_means), ...]} with all
|
|
65
|
+
sampled chunks of all recordings.
|
|
66
|
+
Returns {beam: {'bed': 1D, 'wc': 1D, 'n_chunks': int}}.
|
|
67
|
+
'''
|
|
68
|
+
out = {}
|
|
69
|
+
for beam, cms in chunk_means_by_beam.items():
|
|
70
|
+
bed, wc = stack_means(cms)
|
|
71
|
+
with np.errstate(all='ignore'):
|
|
72
|
+
out[beam] = {'bed': np.nanmean(bed, axis=1),
|
|
73
|
+
'wc': np.nanmean(wc, axis=1),
|
|
74
|
+
'n_chunks': len(cms)}
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def save(path, pooled, stats=None):
|
|
79
|
+
"""Write pooled means and optional global stats (min/max, histograms)."""
|
|
80
|
+
arrs = {}
|
|
81
|
+
for beam, d in pooled.items():
|
|
82
|
+
arrs[beam + '__bed'] = d['bed']
|
|
83
|
+
arrs[beam + '__wc'] = d['wc']
|
|
84
|
+
arrs[beam + '__n'] = np.array(d['n_chunks'])
|
|
85
|
+
for k, v in (stats or {}).items():
|
|
86
|
+
arrs['stats__' + k] = np.asarray(v)
|
|
87
|
+
np.savez(path, **arrs)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def load(path, beam):
|
|
91
|
+
"""Return (bed_means, wc_means) for a beam name such as ss_port."""
|
|
92
|
+
with np.load(path) as z:
|
|
93
|
+
if beam + '__bed' not in z:
|
|
94
|
+
raise KeyError("%s has no EGN curve for %s" % (path, beam))
|
|
95
|
+
return z[beam + '__bed'].copy(), z[beam + '__wc'].copy()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def load_stats(path):
|
|
99
|
+
"""Global min/max and histograms, or None if the file has none."""
|
|
100
|
+
with np.load(path) as z:
|
|
101
|
+
out = {k[7:]: z[k].copy() for k in z.files if k.startswith('stats__')}
|
|
102
|
+
need = ('bed_min', 'bed_max', 'wc_min', 'wc_max', 'wcp_hist', 'wcr_hist')
|
|
103
|
+
return out if all(k in out for k in need) else None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def fit_length(means, n):
|
|
107
|
+
"""Trim or pad (by repeating the last value) a curve to n bins."""
|
|
108
|
+
means = np.asarray(means, dtype=float)
|
|
109
|
+
if means.shape[0] >= n:
|
|
110
|
+
return means[:n]
|
|
111
|
+
pad = np.full(n - means.shape[0], means[~np.isnan(means)][-1])
|
|
112
|
+
return np.concatenate([means, pad])
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def combine_minmax(min_max):
|
|
116
|
+
"""Global bed/wc min and max from per-chunk _egnCalcMinMax results."""
|
|
117
|
+
bmin = [m[0][0] for m in min_max]
|
|
118
|
+
bmax = [m[0][1] for m in min_max]
|
|
119
|
+
wmin = [m[1][0] for m in min_max]
|
|
120
|
+
wmax = [m[1][1] for m in min_max]
|
|
121
|
+
with np.errstate(all='ignore'):
|
|
122
|
+
return {'bed_min': np.nanmin(bmin), 'bed_max': np.nanmax(bmax),
|
|
123
|
+
'wc_min': np.nanmin(wmin), 'wc_max': np.nanmax(wmax)}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _open_son(meta_file):
|
|
127
|
+
from pingmapper.class_rectObj import rectObj
|
|
128
|
+
son = rectObj(meta_file)
|
|
129
|
+
son.egn = True
|
|
130
|
+
son.tvg = False
|
|
131
|
+
return son
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _sampled_chunks(son, sampling):
|
|
135
|
+
chunks = son._getChunkID()
|
|
136
|
+
chunks = chunks[:-1] if len(chunks) > 1 else chunks
|
|
137
|
+
return select_chunks(chunks, sampling)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _per_chunk(son, fn, chunks):
|
|
141
|
+
out = []
|
|
142
|
+
for c in chunks:
|
|
143
|
+
son._loadSonMeta() # the chunk routines free it
|
|
144
|
+
out.append(fn(c))
|
|
145
|
+
return out
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def recording_chunk_means(meta_file, sampling='high', log=print):
|
|
149
|
+
"""Sampled chunk means for one sidescan beam of a processed recording."""
|
|
150
|
+
son = _open_son(meta_file)
|
|
151
|
+
chunks = _sampled_chunks(son, sampling)
|
|
152
|
+
return son.beamName, _per_chunk(son, son._egnCalcChunkMeans, chunks)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _meta_files(root):
|
|
156
|
+
# Recurse so projects nested by preserve_subdirs are found too
|
|
157
|
+
files = []
|
|
158
|
+
for d, _, _ in sorted(os.walk(root)):
|
|
159
|
+
if os.path.basename(d) == 'meta':
|
|
160
|
+
files += [f for f in sorted(glob.glob(os.path.join(d, '*_ss_*_meta.meta')))
|
|
161
|
+
if _has_depth(f)]
|
|
162
|
+
return files
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _has_depth(meta_file):
|
|
166
|
+
# Recordings that failed reading (e.g. all pings outside the AOI) leave a
|
|
167
|
+
# meta folder without processed depth; they cannot contribute to EGN.
|
|
168
|
+
csv_file = os.path.splitext(meta_file)[0] + '.csv'
|
|
169
|
+
try:
|
|
170
|
+
with open(csv_file, 'r') as f:
|
|
171
|
+
return 'dep_m' in f.readline().strip().split(',')
|
|
172
|
+
except OSError:
|
|
173
|
+
return False
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _default_workers():
|
|
177
|
+
# Serial by default: the chunk routines already use joblib internally, and
|
|
178
|
+
# spawned processes re-import the heavy classes, which loses on small sets.
|
|
179
|
+
return 1
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _run(fn, jobs, workers):
|
|
183
|
+
'''Run fn over jobs (tuples), in order, serially or in worker processes.'''
|
|
184
|
+
if workers <= 1 or len(jobs) <= 1:
|
|
185
|
+
return [fn(*j) for j in jobs]
|
|
186
|
+
with ProcessPoolExecutor(max_workers=min(workers, len(jobs))) as ex:
|
|
187
|
+
return list(ex.map(fn, *zip(*jobs)))
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _means_job(mf, sampling):
|
|
191
|
+
return recording_chunk_means(mf, sampling)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _minmax_job(mf, pooled, sampling):
|
|
195
|
+
son = _prep(mf, pooled)
|
|
196
|
+
return _per_chunk(son, son._egnCalcMinMax, _sampled_chunks(son, sampling))
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _hist_job(mf, pooled, stats, sampling):
|
|
200
|
+
son = _prep(mf, pooled)
|
|
201
|
+
son.egn_bed_min, son.egn_bed_max = stats['bed_min'], stats['bed_max']
|
|
202
|
+
son.egn_wc_min, son.egn_wc_max = stats['wc_min'], stats['wc_max']
|
|
203
|
+
son.remShadow = getattr(son, 'remShadow', 0)
|
|
204
|
+
wcp = np.zeros(255)
|
|
205
|
+
wcr = np.zeros(255)
|
|
206
|
+
for a, b in _per_chunk(son, son._egnCalcHist, _sampled_chunks(son, sampling)):
|
|
207
|
+
wcp += a
|
|
208
|
+
wcr += b
|
|
209
|
+
return wcp, wcr
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _prep(mf, pooled):
|
|
213
|
+
son = _open_son(mf)
|
|
214
|
+
son.egn_bed_means = pooled[son.beamName]['bed']
|
|
215
|
+
son.egn_wc_means = pooled[son.beamName]['wc']
|
|
216
|
+
return son
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def build(root, out_file, sampling='high', stats=True, log=print, workers=None):
|
|
220
|
+
"""
|
|
221
|
+
Pool EGN from every recording folder under root (each holding a ``meta``
|
|
222
|
+
folder). Port and starboard are pooled separately.
|
|
223
|
+
|
|
224
|
+
Stage 1 pools the range-wise means. If stats is True, stage 2 finds the
|
|
225
|
+
global min/max after EGN and stage 3 sums the corrected histograms, so the
|
|
226
|
+
contrast stretch is also shared by all recordings. Everything is written
|
|
227
|
+
to out_file, and the pooled means dict is returned.
|
|
228
|
+
|
|
229
|
+
Within each stage the recordings/beams are independent, so they are
|
|
230
|
+
processed by ``workers`` processes (default 1 = serial; >1 helps only for many recordings).
|
|
231
|
+
The stages themselves depend on each other and run in order.
|
|
232
|
+
"""
|
|
233
|
+
workers = _default_workers() if workers is None else int(workers)
|
|
234
|
+
by_beam = {}
|
|
235
|
+
good = []
|
|
236
|
+
files = _meta_files(root)
|
|
237
|
+
try:
|
|
238
|
+
results = _run(_means_job, [(mf, sampling) for mf in files], workers)
|
|
239
|
+
except Exception as e:
|
|
240
|
+
log('parallel means failed (%r); retrying serially' % (e,))
|
|
241
|
+
results = _run(_means_job, [(mf, sampling) for mf in files], 1)
|
|
242
|
+
for mf, (beam, cms) in zip(files, results):
|
|
243
|
+
name = os.path.basename(os.path.dirname(os.path.dirname(mf)))
|
|
244
|
+
by_beam.setdefault(beam, []).extend(cms)
|
|
245
|
+
good.append(mf)
|
|
246
|
+
log('means %s %s: %d chunks' % (name, beam, len(cms)))
|
|
247
|
+
if not by_beam:
|
|
248
|
+
raise RuntimeError('No processed recordings found under %s' % root)
|
|
249
|
+
pooled = pool(by_beam)
|
|
250
|
+
|
|
251
|
+
extra = None
|
|
252
|
+
if stats:
|
|
253
|
+
extra = _pool_stats(good, pooled, sampling, log, workers)
|
|
254
|
+
save(out_file, pooled, extra)
|
|
255
|
+
log('wrote %s' % out_file)
|
|
256
|
+
return pooled
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _pool_stats(meta_files, pooled, sampling, log, workers=1):
|
|
260
|
+
mm = []
|
|
261
|
+
for chunk_mm, mf in zip(_run(_minmax_job, [(mf, pooled, sampling) for mf in meta_files], workers), meta_files):
|
|
262
|
+
mm += chunk_mm
|
|
263
|
+
log('min/max %s' % os.path.basename(mf))
|
|
264
|
+
stats = combine_minmax(mm)
|
|
265
|
+
|
|
266
|
+
wcp = np.zeros(255)
|
|
267
|
+
wcr = np.zeros(255)
|
|
268
|
+
jobs = [(mf, pooled, stats, sampling) for mf in meta_files]
|
|
269
|
+
for (a, b), mf in zip(_run(_hist_job, jobs, workers), meta_files):
|
|
270
|
+
wcp += a
|
|
271
|
+
wcr += b
|
|
272
|
+
log('histogram %s' % os.path.basename(mf))
|
|
273
|
+
stats['wcp_hist'] = wcp
|
|
274
|
+
stats['wcr_hist'] = wcr
|
|
275
|
+
return stats
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def main(argv=None):
|
|
279
|
+
ap = argparse.ArgumentParser(description='Pool EGN across recordings.')
|
|
280
|
+
ap.add_argument('root', help='Folder holding processed recording folders')
|
|
281
|
+
ap.add_argument('out', help='Output .npz file')
|
|
282
|
+
ap.add_argument('--no-stats', action='store_true',
|
|
283
|
+
help='Pool only the means (skip global min/max and stretch)')
|
|
284
|
+
ap.add_argument('--workers', type=int, default=None, help='processes across recordings (default 1)')
|
|
285
|
+
ap.add_argument('--sampling', default='high',
|
|
286
|
+
help='low, moderate, high or a fraction 0-1')
|
|
287
|
+
a = ap.parse_args(argv)
|
|
288
|
+
s = a.sampling
|
|
289
|
+
try:
|
|
290
|
+
s = float(s)
|
|
291
|
+
except ValueError:
|
|
292
|
+
pass
|
|
293
|
+
build(a.root, a.out, s, stats=not a.no_stats, workers=a.workers)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
if __name__ == '__main__':
|
|
297
|
+
here = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
|
298
|
+
if here not in sys.path:
|
|
299
|
+
sys.path.insert(0, here)
|
|
300
|
+
main()
|