rockmapper 1.0.0a1__py3-none-any.whl

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.
rockmapper/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .version import __version__
rockmapper/__main__.py ADDED
@@ -0,0 +1,46 @@
1
+ '''
2
+ Copyright (c) 2025 Cameron S. Bodine
3
+ '''
4
+
5
+ #########
6
+ # Imports
7
+ import os, sys
8
+
9
+ # Add 'rockmapper' to the path, may not need after pypi package...
10
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
11
+ PACKAGE_DIR = os.path.dirname(SCRIPT_DIR)
12
+ sys.path.append(PACKAGE_DIR)
13
+
14
+ # Set GHOSTVISION utils dir
15
+ USER_DIR = os.path.expanduser('~')
16
+ GV_UTILS_DIR = os.path.join(USER_DIR, '.rockmapper')
17
+ if not os.path.exists(GV_UTILS_DIR):
18
+ os.makedirs(GV_UTILS_DIR)
19
+
20
+ # Default function to run
21
+ if len(sys.argv) == 1:
22
+ to_do = 'gui'
23
+ else:
24
+ to_do = sys.argv[1]
25
+
26
+ #=======================================================================
27
+ def main(process):
28
+ '''
29
+ '''
30
+
31
+ from rockmapper.version import __version__
32
+ print("\n\nRockMapper v{}".format(__version__))
33
+
34
+ # Launch GUI
35
+ if process == 'gui':
36
+ print('\n\nLaunching RockMapper gui...\n\n')
37
+
38
+ from rockmapper.gui_main import gui
39
+ gui()
40
+
41
+ return
42
+
43
+ #=======================================================================
44
+ if __name__ == "__main__":
45
+ main(to_do)
46
+
rockmapper/gui_main.py ADDED
@@ -0,0 +1,88 @@
1
+
2
+ '''
3
+ Copyright (c) 2025 Cameron S. Bodine
4
+ '''
5
+
6
+ #########
7
+ # Imports
8
+ import os, sys
9
+ import time, datetime
10
+
11
+ start_time = time.time()
12
+
13
+ # Set ROCKMAPPER utils dir
14
+ USER_DIR = os.path.expanduser('~')
15
+ GV_UTILS_DIR = os.path.join(USER_DIR, '.rockmapper')
16
+ if not os.path.exists(GV_UTILS_DIR):
17
+ os.makedirs(GV_UTILS_DIR)
18
+
19
+ def gui():
20
+ '''
21
+ '''
22
+
23
+ #################
24
+ # NEED TO ADD GUI
25
+
26
+
27
+ # FOR DEVELOPMENT
28
+ #############################
29
+ # Hard coding for development
30
+ seg_model = 'RockMapper_20250628_v1'
31
+ inDir = r'Z:\scratch\202506_BrushyDeepKiamichi_Substrate\mosaics'
32
+ # modelDir = r'Z:\scratch\202506_BrushyDeepKiamichi_Substrate\seg_gym\20250628_test\fold_0\RockMapper'
33
+ # inDir = r'Z:\scratch\USGS-CERC_2025\00_carp_group_targets\Mosaics'
34
+ # modelDir = r'D:\redbo_science\projects\USGS-CERC_2025\seg_gym\20250710_v01\fold_0'
35
+ mosaicFileType = '.tif'
36
+ outDirTop = r'Z:\scratch'
37
+ projName = 'RockMapperTest'
38
+ mapRast = False
39
+ mapShp = True
40
+
41
+ epsg = 32616
42
+
43
+ windowSize_m = (18, 18)
44
+ window_stride = 9
45
+ minArea_percent = 0.75
46
+ threadCnt = 0.25
47
+
48
+ predBatchSize = 30
49
+
50
+ deleteIntData = True
51
+
52
+
53
+ ################
54
+ # Run HabiMapper
55
+
56
+ modelDir = os.path.join(GV_UTILS_DIR, 'models')
57
+
58
+ # RockMapper
59
+ if seg_model == 'RockMapper_20250628_v1':
60
+ from rockmapper.rock_mapper import do_work
61
+
62
+ modelDir = os.path.join(modelDir, seg_model)
63
+
64
+
65
+ print('\n\nMapping habitat with ROCKMAPPER model...\n\n')
66
+ do_work(
67
+ inDir = inDir,
68
+ outDirTop = outDirTop,
69
+ projName = projName,
70
+ mapRast = mapRast,
71
+ mapShp = mapShp,
72
+ epsg = epsg,
73
+ windowSize_m = windowSize_m,
74
+ window_stride = window_stride,
75
+ minArea_percent = minArea_percent,
76
+ threadCnt = threadCnt,
77
+ mosaicFileType=mosaicFileType,
78
+ modelDir=modelDir,
79
+ predBatchSize=predBatchSize,
80
+ deleteIntData=deleteIntData
81
+ )
82
+
83
+
84
+
85
+
86
+
87
+ print("\n\nGrand Total Processing Time: ", datetime.timedelta(seconds = round(time.time() - start_time, ndigits=0)))
88
+ return
@@ -0,0 +1,442 @@
1
+ '''
2
+ Copyright (c) 2025 Cameron S. Bodine
3
+ '''
4
+
5
+ #########
6
+ # Imports
7
+ import os, sys, time
8
+ from os import cpu_count
9
+ from glob import glob
10
+ import pandas as pd
11
+ import geopandas as gpd
12
+ import json
13
+ import shutil
14
+ import requests, zipfile
15
+
16
+ from rockmapper.utils import printUsage#, avg_npz_files, map_npzs
17
+
18
+ # # Debug
19
+ # pingTilePath = os.path.normpath('../PINGTile')
20
+ # pingTilePath = os.path.abspath(pingTilePath)
21
+ # sys.path.insert(0, pingTilePath)
22
+ # sys.path.insert(0, 'src')
23
+
24
+ # pingSegPath = os.path.normpath('../PINGSeg')
25
+ # pingSegPath = os.path.abspath(pingSegPath)
26
+ # sys.path.insert(0, pingSegPath)
27
+ # sys.path.insert(0, 'src')
28
+
29
+ from pingtile.mosaic2tile import doMosaic2tile
30
+ from pingtile.utils import avg_npz_files, map_npzs, mosaic_maps, maps2Shp
31
+ from pingseg.seg_gym import seg_gym_folder, seg_gym_folder_noDL
32
+
33
+ # Set ROCKMAPPER utils dir
34
+ USER_DIR = os.path.expanduser('~')
35
+ GV_UTILS_DIR = os.path.join(USER_DIR, '.rockmapper')
36
+ if not os.path.exists(GV_UTILS_DIR):
37
+ os.makedirs(GV_UTILS_DIR)
38
+
39
+ #=======================================================================
40
+ def do_work(
41
+ inDir: str,
42
+ outDirTop: str,
43
+ modelDir: str,
44
+ projName: str,
45
+ mapRast: bool,
46
+ mapShp: bool,
47
+ epsg: int,
48
+ windowSize_m: tuple,
49
+ window_stride: int,
50
+ minArea_percent: float,
51
+ threadCnt: float,
52
+ mosaicFileType: str,
53
+ predBatchSize: int,
54
+ deleteIntData: bool=True
55
+ ):
56
+ '''
57
+ '''
58
+
59
+ start_time = time.time()
60
+
61
+ outDir = os.path.join(outDirTop, projName)
62
+
63
+ if os.path.exists(outDir):
64
+ shutil.rmtree(outDir)
65
+
66
+ if not os.path.exists(outDir):
67
+ os.makedirs(outDir)
68
+
69
+ ###########
70
+ # Get model
71
+
72
+ seg_model = os.path.basename(modelDir)
73
+
74
+ if not os.path.exists(modelDir) or len(os.listdir(modelDir)) == 0:
75
+ os.makedirs(modelDir, exist_ok=True)
76
+
77
+ url = f'https://github.com/PINGEcosystem/RockMapper/releases/download/models/{seg_model}.zip'
78
+ print(f'\n\nDownloading segmentation models (v1.0): {url}')
79
+
80
+ filename = modelDir + '.zip'
81
+ try:
82
+ # stream download to avoid memory spikes
83
+ with requests.get(url, stream=True, timeout=60) as r:
84
+ r.raise_for_status()
85
+ with open(filename, 'wb') as f:
86
+ for chunk in r.iter_content(chunk_size=8192):
87
+ if chunk:
88
+ f.write(chunk)
89
+
90
+ # quick validation
91
+ if not zipfile.is_zipfile(filename):
92
+ # read beginning of file to help debug (text/html error pages)
93
+ with open(filename, 'rb') as fh:
94
+ head = fh.read(512).decode('utf-8', errors='replace')
95
+ os.remove(filename)
96
+ raise RuntimeError(f"Downloaded file is not a zip file. Server response starts with: {head!r}")
97
+
98
+ # extract safely
99
+ with zipfile.ZipFile(filename, 'r') as z_fp:
100
+ z_fp.extractall(modelDir)
101
+
102
+ os.remove(filename)
103
+ print('Model download and extraction success!')
104
+
105
+ except requests.RequestException as e:
106
+ # network/HTTP problem
107
+ if os.path.exists(filename):
108
+ os.remove(filename)
109
+ raise RuntimeError(f"Failed to download model from {url}: {e}") from e
110
+ except zipfile.BadZipFile as e:
111
+ if os.path.exists(filename):
112
+ os.remove(filename)
113
+ raise RuntimeError("Downloaded model archive is corrupted or not a zip file.") from e
114
+
115
+
116
+ ###############################################
117
+ # Specify multithreaded processing thread count
118
+ if threadCnt==0: # Use all threads
119
+ threadCnt=cpu_count()
120
+ elif threadCnt<0: # Use all threads except threadCnt; i.e., (cpu_count + (-threadCnt))
121
+ threadCnt=cpu_count()+threadCnt
122
+ if threadCnt<0: # Make sure not negative
123
+ threadCnt=1
124
+ elif threadCnt<1: # Use proportion of available threads
125
+ threadCnt = int(cpu_count()*threadCnt)
126
+ # Make even number
127
+ if threadCnt % 2 == 1:
128
+ threadCnt -= 1
129
+ else: # Use specified threadCnt if positive
130
+ pass
131
+
132
+ if threadCnt>cpu_count(): # If more than total avail. threads, make cpu_count()
133
+ threadCnt=cpu_count();
134
+ print("\nWARNING: Specified more process threads then available, \nusing {} threads instead.".format(threadCnt))
135
+
136
+ # Set Stride
137
+ windowStride_m = windowSize_m
138
+ minArea = minArea_percent * windowSize_m[0]*windowSize_m[1]
139
+
140
+ # Delete intermediate data
141
+ to_delete = []
142
+
143
+ # Make output image dir
144
+ dirName = projName
145
+ outDir = os.path.join(outDirTop, dirName)
146
+ outSonDir = os.path.join(outDir, 'images')
147
+
148
+ if not os.path.exists(outSonDir):
149
+ os.makedirs(outSonDir)
150
+
151
+ # Get the sonar images
152
+ mosaics = glob(os.path.join(inDir, '**', '*{}'.format(mosaicFileType)), recursive=True)
153
+
154
+ # Get the model config file and load it
155
+ configFile = glob(os.path.join(modelDir, 'config', '*.json'))[0]
156
+
157
+ with open(configFile) as f:
158
+ config = json.load(f)
159
+
160
+
161
+
162
+
163
+
164
+
165
+
166
+
167
+
168
+
169
+ # For debug
170
+ mosaics = mosaics[:1]
171
+
172
+
173
+
174
+
175
+
176
+
177
+ ###############################
178
+ # Generate moving window images
179
+
180
+ print('\n\nTiling Mosaics...\n\n')
181
+
182
+ imagesAll = []
183
+
184
+ for mosaic in mosaics:
185
+ r = doMosaic2tile(
186
+ inFile = mosaic,
187
+ outDir = outSonDir,
188
+ windowSize = windowSize_m,
189
+ windowStride_m = window_stride,
190
+ outName = projName,
191
+ epsg_out = epsg,
192
+ threadCnt = threadCnt,
193
+ target_size = config['TARGET_SIZE'],
194
+ minArea_percent = minArea_percent,
195
+ )
196
+
197
+ imagesAll.append(r)
198
+
199
+ imagesDF = pd.concat(imagesAll, axis=0, ignore_index=True)
200
+
201
+ # For debug
202
+ outDF = os.path.join(outDir, f'{projName}_{windowSize_m[0]}_{windowSize_m[1]}_tiles.csv')
203
+ imagesDF.to_csv(outDF, index=False)
204
+
205
+ # Delete intermediate data
206
+ if deleteIntData:
207
+ to_delete.append(outSonDir)
208
+
209
+ print('Image Tiles Generated: {}'.format(len(imagesDF)))
210
+
211
+ print("\nDone!")
212
+ print("Time (s):", round(time.time() - start_time, ndigits=1))
213
+ printUsage()
214
+
215
+
216
+ # For Debug
217
+ imagesDF = pd.read_csv(outDF)
218
+ print(len(imagesDF))
219
+
220
+
221
+ ################################
222
+ # Perform segmentation on images
223
+
224
+ print('\n\nPredicting substrate from sonar tiles...\n\n')
225
+ start_time = time.time()
226
+
227
+ out_npz = os.path.join(outDir, 'preds_npz')
228
+
229
+ imagesDF = seg_gym_folder(imgDF=imagesDF, modelDir=modelDir, out_dir=out_npz, batch_size=predBatchSize, threadCnt=threadCnt)
230
+
231
+ outDF = os.path.join(outDir, f'{projName}_{windowSize_m[0]}_{windowSize_m[1]}_tileseg.csv')
232
+ imagesDF.to_csv(outDF, index=False)
233
+
234
+ # Delete intermediate data
235
+ if deleteIntData:
236
+ to_delete.append(out_npz)
237
+
238
+ print("\nPrediction Complete!")
239
+ print("Time (s):", round(time.time() - start_time, ndigits=1))
240
+ printUsage()
241
+
242
+
243
+ # # For Debug #
244
+ # #######################
245
+ # # Map average npz files
246
+ # print('\n\nMapping predicted substrate...\n\n')
247
+ # start_time = time.time()
248
+
249
+ # out_maps = os.path.join(outDir, 'preds_mapped_ind_npz')
250
+
251
+ # if not os.path.exists(out_maps):
252
+ # os.makedirs(out_maps)
253
+
254
+ # from shapely.geometry import box
255
+ # # Create per-row geometry safely from bounds (xmin, ymin, xmax, ymax).
256
+ # # Passing pandas.Series directly to shapely.box raises TypeError because
257
+ # # shapely expects scalar floats for each bound. Build a geometry per row,
258
+ # # coerce to float, and ignore degenerate or invalid rows.
259
+ # def _make_geom_from_bounds(row):
260
+ # try:
261
+ # xmin = float(row['x_min'])
262
+ # ymin = float(row['y_min'])
263
+ # xmax = float(row['x_max'])
264
+ # ymax = float(row['y_max'])
265
+ # # ignore degenerate boxes or NaNs
266
+ # if any(pd.isna([xmin, ymin, xmax, ymax])):
267
+ # return None
268
+ # if xmin >= xmax or ymin >= ymax:
269
+ # return None
270
+ # return box(xmin, ymin, xmax, ymax)
271
+ # except Exception:
272
+ # return None
273
+
274
+ # imagesDF['geometry'] = imagesDF.apply(_make_geom_from_bounds, axis=1)
275
+ # # Drop rows without valid geometry
276
+ # imagesDF = imagesDF[~imagesDF['geometry'].isnull()].reset_index(drop=True)
277
+ # # Convert to GeoDataFrame with the provided CRS
278
+ # imagesDF = gpd.GeoDataFrame(imagesDF, geometry='geometry', crs=f"EPSG:{epsg}")
279
+
280
+ # # Make npz column with basename in imagesDF['mosaic'] and out_npz directory
281
+ # # imagesDF['mosaic'] contains the source image path used for prediction.
282
+ # # Build the corresponding npz filename (basename + .npz) located in out_npz.
283
+ # def _npz_path_from_mosaic(p):
284
+ # try:
285
+ # if pd.isna(p):
286
+ # return None
287
+ # base = os.path.splitext(os.path.basename(p))[0]
288
+ # return os.path.join(out_npz, f"{base}.npz")
289
+ # except Exception:
290
+ # return None
291
+
292
+ # imagesDF['npz'] = imagesDF['mosaic'].apply(_npz_path_from_mosaic)
293
+
294
+ # gdf = map_npzs(df=imagesDF, in_dir=out_npz, out_dir=out_maps, outName=projName, windowSize_m=windowSize_m, epsg=epsg)
295
+
296
+ # # Delete intermediate data
297
+ # if deleteIntData:
298
+ # to_delete.append(out_maps)
299
+
300
+ # print("\nDone!")
301
+ # print("Time (s):", round(time.time() - start_time, ndigits=1))
302
+ # printUsage()
303
+ # # For Debug #
304
+
305
+
306
+
307
+
308
+
309
+
310
+ # For debug
311
+ out_npz = os.path.join(outDir, 'preds_npz')
312
+ outDF = os.path.join(outDir, f'{projName}_{windowSize_m[0]}_{windowSize_m[1]}_tileseg.csv')
313
+ imagesDF = pd.read_csv(outDF)
314
+
315
+ ###############################
316
+ # Average overlapping npz files
317
+ print('\n\nAveraging overlapping substrate predictions...\n\n')
318
+ start_time = time.time()
319
+
320
+ out_avg_npz = os.path.join(outDir, 'preds_avg_npz')
321
+
322
+ if not os.path.exists(out_avg_npz):
323
+ os.makedirs(out_avg_npz)
324
+
325
+ gdf = avg_npz_files(df=imagesDF, in_dir=out_npz, out_dir=out_avg_npz, outName=projName, windowSize_m=windowSize_m, stride=windowSize_m[0], epsg=epsg, threadCnt=threadCnt)
326
+
327
+ outDF = os.path.join(outDir, f'{projName}_{windowSize_m[0]}_{windowSize_m[1]}_avgnpz.csv')
328
+ gdf.to_csv(outDF, index=False)
329
+
330
+ # Delete intermediate data
331
+ if deleteIntData:
332
+ to_delete.append(out_avg_npz)
333
+
334
+ print("\nDone!")
335
+ print("Time (s):", round(time.time() - start_time, ndigits=1))
336
+ printUsage()
337
+
338
+
339
+ # For debug
340
+ out_avg_npz = os.path.join(outDir, 'preds_avg_npz')
341
+ outDF = os.path.join(outDir, f'{projName}_{windowSize_m[0]}_{windowSize_m[1]}_avgnpz.csv')
342
+ gdf = pd.read_csv(outDF)
343
+
344
+
345
+
346
+ #######################
347
+ # Map average npz files
348
+ print('\n\nMapping predicted substrate...\n\n')
349
+ start_time = time.time()
350
+
351
+ out_maps = os.path.join(outDir, 'preds_mapped')
352
+
353
+ if not os.path.exists(out_maps):
354
+ os.makedirs(out_maps)
355
+
356
+ gdf = map_npzs(df=gdf, in_dir=out_avg_npz, out_dir=out_maps, outName=projName, windowSize_m=windowSize_m, epsg=epsg, threadCnt=threadCnt)
357
+
358
+ # Delete intermediate data
359
+ if deleteIntData:
360
+ to_delete.append(out_maps)
361
+
362
+ print("\nDone!")
363
+ print("Time (s):", round(time.time() - start_time, ndigits=1))
364
+ printUsage()
365
+
366
+
367
+ # Save df
368
+ outDF = os.path.join(outDir, f'{projName}_{windowSize_m[0]}_{windowSize_m[1]}_mapped_npzs.csv')
369
+ gdf.to_csv(outDF, index=False)
370
+
371
+ #############
372
+ # Mosaic maps
373
+
374
+ if mapRast:
375
+
376
+ print('\n\nExport map as raster mosaic...\n\n')
377
+ start_time = time.time()
378
+
379
+ map_files = glob(os.path.join(out_maps, '*.tif'))
380
+
381
+ out_mosaic = os.path.join(outDir, 'mosaic')
382
+
383
+ if not os.path.exists(out_mosaic):
384
+ os.makedirs(out_mosaic)
385
+
386
+ mosaic_maps(map_files, out_mosaic, projName)
387
+
388
+ print("\nDone!")
389
+ print("Time (s):", round(time.time() - start_time, ndigits=1))
390
+ printUsage()
391
+
392
+ ###################
393
+ # Maps to Shapefile
394
+
395
+ if mapShp:
396
+
397
+ print('\n\nExport map as shapefile...\n\n')
398
+ start_time = time.time()
399
+
400
+ map_files = glob(os.path.join(out_maps, '*.tif'))
401
+
402
+ out_shp = os.path.join(outDir, 'map_shp')
403
+
404
+ if not os.path.exists(out_shp):
405
+ os.makedirs(out_shp)
406
+
407
+ maps2Shp(map_files, out_shp, projName, configFile)
408
+
409
+ print("\nDone!")
410
+ print("Time (s):", round(time.time() - start_time, ndigits=1))
411
+ printUsage()
412
+
413
+ # #################
414
+ # # Mask the mosaic
415
+
416
+ # print('\n\nMasking final map...\n\n')
417
+ # start_time = time.time()
418
+
419
+ # out_mosaic = os.path.join(out_mosaic, f'{projName}.tif')
420
+ # out_mask = os.path.join(outDir, 'mask')
421
+
422
+ # if not os.path.exists(out_mask):
423
+ # os.makedirs(out_mask)
424
+
425
+ # mask_mosaic_map()
426
+
427
+
428
+ ##########################
429
+ # Delete intermediate data
430
+
431
+ if deleteIntData:
432
+ print('\n\nDeleting intermediate data...\n\n')
433
+ start_time = time.time()
434
+
435
+ for d in to_delete:
436
+ shutil.rmtree(d, ignore_errors=True)
437
+
438
+ print("\nDone!")
439
+ print("Time (s):", round(time.time() - start_time, ndigits=1))
440
+ printUsage()
441
+
442
+ return
rockmapper/utils.py ADDED
@@ -0,0 +1,276 @@
1
+ '''
2
+ Copyright (c) 2025 Cameron S. Bodine
3
+ '''
4
+
5
+ #########
6
+ # Imports
7
+ import os, sys
8
+ import psutil
9
+ import pandas as pd
10
+ import numpy as np
11
+ from joblib import Parallel, delayed
12
+ from tqdm import tqdm
13
+ import rasterio as rio
14
+ from rasterio.features import shapes
15
+ import geopandas as gpd
16
+ from shapely.geometry import box, shape
17
+
18
+ # Debug
19
+ pingTilePath = os.path.normpath('../PINGTile')
20
+ pingTilePath = os.path.abspath(pingTilePath)
21
+ sys.path.insert(0, pingTilePath)
22
+ sys.path.insert(0, 'src')
23
+ from pingtile.utils import getMovingWindow
24
+
25
+ #=======================================================================
26
+ def printUsage():
27
+ '''
28
+ Show computing resources used
29
+ '''
30
+ cpuPercent = round(psutil.cpu_percent(0.5), 1)
31
+ ramPercent = round(psutil.virtual_memory()[2], 1)
32
+ ramUsed = round(psutil.virtual_memory()[3]/1000000000, 1)
33
+
34
+ print('\n\nCurrent CPU/RAM Usage:')
35
+ print('________________________')
36
+ print('{:<5s} | {:<5s} | {:<5s}'.format('CPU %', 'RAM %', 'RAM [GB]'))
37
+ print('________________________')
38
+
39
+ print('{:<5s} | {:<5s} | {:<5s}'.format(str(cpuPercent), str(ramPercent), str(ramUsed)))
40
+ print('________________________\n\n')
41
+
42
+
43
+ return
44
+
45
+ # #=======================================================================
46
+ # def avg_npz_files_batch(df: pd.DataFrame,
47
+ # win: pd.Series,
48
+ # arr_shape: tuple,
49
+ # in_dir: str,
50
+ # out_dir: str,
51
+ # outName: str,
52
+ # windowSize_m: tuple,
53
+ # epsg: int,
54
+ # ):
55
+
56
+ # '''
57
+ # '''
58
+
59
+ # win_minx, win_miny, win_maxx, win_maxy = win.geometry.bounds
60
+
61
+ # # Calculate pixel size for the window array
62
+ # win_height, win_width = arr_shape[1], arr_shape[2] # (bands, height, width)
63
+ # win_pixel_size_x = (win_maxx - win_minx) / win_width
64
+ # win_pixel_size_y = (win_maxy - win_miny) / win_height
65
+
66
+
67
+ # win_coords = ''
68
+ # for b in win.geometry.bounds:
69
+ # b = int(round(b, 0))
70
+
71
+ # win_coords += str(b)+'_'
72
+
73
+ # win_coords = win_coords[:-1]
74
+
75
+ # # Find overlapping npz files
76
+ # overlaps = df[
77
+ # (df['x_min'] < win_maxx) & (df['x_max'] > win_minx) &
78
+ # (df['y_min'] < win_maxy) & (df['y_max'] > win_miny)
79
+ # ]
80
+
81
+ # if overlaps.empty:
82
+ # return
83
+
84
+ # # Determine output array shape for this window
85
+ # sum_arr = np.zeros(arr_shape, dtype=np.float64)
86
+ # count_arr = np.zeros((arr_shape[1], arr_shape[2]), dtype=np.int32)
87
+
88
+ # for _, row in overlaps.iterrows():
89
+ # base = os.path.splitext(os.path.basename(row['mosaic']))[0]
90
+ # npz_path = os.path.join(in_dir, f"{base}.npz")
91
+ # npz = np.load(npz_path)
92
+ # arr = npz['softmax']
93
+ # arr_minx, arr_miny, arr_maxx, arr_maxy = row[['x_min', 'y_min', 'x_max', 'y_max']]
94
+ # arr_shape = arr.shape # (bands, height, width)
95
+ # arr_pixel_size_x = (arr_maxx - arr_minx) / arr_shape[2]
96
+ # arr_pixel_size_y = (arr_maxy - arr_miny) / arr_shape[1]
97
+
98
+
99
+ # # Calculate overlap in world coordinates
100
+ # overlap_minx = max(win_minx, arr_minx)
101
+ # overlap_maxx = min(win_maxx, arr_maxx)
102
+ # overlap_miny = max(win_miny, arr_miny)
103
+ # overlap_maxy = min(win_maxy, arr_maxy)
104
+
105
+ # # Convert world coordinates to array indices
106
+ # win_x0 = int(np.floor((overlap_minx - win_minx) / win_pixel_size_x))
107
+ # win_x1 = int(np.ceil((overlap_maxx - win_minx) / win_pixel_size_x))
108
+ # win_y0 = int(np.floor((overlap_miny - win_miny) / win_pixel_size_y))
109
+ # win_y1 = int(np.ceil((overlap_maxy - win_miny) / win_pixel_size_y))
110
+
111
+ # arr_x0 = int(np.floor((overlap_minx - arr_minx) / arr_pixel_size_x))
112
+ # arr_x1 = int(np.ceil((overlap_maxx - arr_minx) / arr_pixel_size_x))
113
+ # arr_y0 = int(np.floor((overlap_miny - arr_miny) / arr_pixel_size_y))
114
+ # arr_y1 = int(np.ceil((overlap_maxy - arr_miny) / arr_pixel_size_y))
115
+
116
+ # # Check for valid overlap and matching shapes
117
+ # win_slice_shape = (win_y1 - win_y0, win_x1 - win_x0)
118
+ # arr_slice_shape = (arr_y1 - arr_y0, arr_x1 - arr_x0)
119
+ # if (win_slice_shape[0] > 0 and win_slice_shape[1] > 0 and
120
+ # arr_slice_shape[0] > 0 and arr_slice_shape[1] > 0 and
121
+ # win_slice_shape == arr_slice_shape):
122
+ # sum_arr[:, win_y0:win_y1, win_x0:win_x1] += arr[:, arr_y0:arr_y1, arr_x0:arr_x1]
123
+ # count_arr[win_y0:win_y1, win_x0:win_x1] += 1
124
+
125
+
126
+ # # print('\n\n', win_x0, win_x1, win_y0, win_y1, sum_arr.shape)
127
+ # # print(arr_x0, arr_x1, arr_y0, arr_y1, arr.shape)
128
+ # # print('Overlap:', overlap_minx, overlap_miny, overlap_maxx, overlap_maxy)
129
+ # # print(arr_pixel_size_x, arr_pixel_size_y)
130
+
131
+ # # Avoid division by zero
132
+ # avg_arr = np.divide(sum_arr, count_arr, out=np.zeros_like(sum_arr), where=count_arr != 0)
133
+
134
+ # # print('\n\n', avg_arr)
135
+
136
+ # # Save to npz
137
+ # # Save the clipped raster and shapefile
138
+ # if outName:
139
+ # fileName = f"{outName}_{windowSize_m[0]}m_{win_coords}"
140
+ # else:
141
+ # fileName = f"{windowSize_m[0]}m_{win_coords}"
142
+ # out_npz = os.path.join(out_dir, f"{fileName}.npz")
143
+
144
+ # df['npz'] = out_npz
145
+
146
+ # np.savez_compressed(out_npz, softmax=avg_arr)
147
+
148
+ # # Convert to GeoDataFrame
149
+ # geometry = box(win_minx, win_miny, win_maxx, win_maxy)
150
+ # # df['geometry'] = gpd.GeoSeries.from_bounds(win_minx, win_miny, win_maxx, win_maxy, crs=f"EPSG:{epsg}").geometry
151
+ # df['geometry'] = gpd.GeoSeries([geometry], crs=f"EPSG:{epsg}")
152
+
153
+ # return df
154
+
155
+
156
+
157
+ # #=======================================================================
158
+ # def avg_npz_files(df: pd.DataFrame,
159
+ # in_dir: str,
160
+ # out_dir: str,
161
+ # outName: str,
162
+ # windowSize_m: tuple,
163
+ # stride: int,
164
+ # epsg: int):
165
+ # '''
166
+ # Average overlapping npz files
167
+ # '''
168
+
169
+ # # Get non-overlapping moving window geodataframe
170
+ # movWin = getMovingWindow(df=df, windowSize=windowSize_m, windowStride_m=stride, epsg=epsg)
171
+
172
+ # # Save moving window to shapefile
173
+ # out_file = os.path.join(out_dir, 'Map_Tiles.shp')
174
+ # movWin.to_file(out_file, driver='ESRI Shapefile')
175
+
176
+ # # Assume all arrays have the same shape and resolution
177
+ # # Load one sample to get array shape and pixel size
178
+ # base = os.path.splitext(os.path.basename(df.iloc[0]['mosaic']))[0]
179
+ # base = base.split('.png')[0]
180
+ # npz_path = os.path.join(in_dir, f"{base}.npz")
181
+ # sample_npz = np.load(npz_path)
182
+ # arr_shape = sample_npz['softmax'].shape
183
+
184
+ # # Use joblib to parallelize the averaging process
185
+ # results = Parallel(n_jobs=-1, verbose=10)(
186
+ # delayed(avg_npz_files_batch)(df, win, arr_shape, in_dir, out_dir, outName, windowSize_m, epsg)
187
+ # for idx, win in tqdm(movWin.iterrows(), total=len(movWin), desc="Processing windows")
188
+ # )
189
+
190
+ # results = [res for res in results if res is not None]
191
+ # results = pd.concat(results, ignore_index=True)
192
+
193
+ # results = gpd.GeoDataFrame(results, geometry='geometry', crs=movWin.crs)
194
+
195
+ # return results
196
+
197
+
198
+ # # def label_array_to_shapefile(df, in_dir, out_dir, outName, windowSize_m, epsg):
199
+ # # """
200
+ # # Convert a label array to polygons and save as a shapefile.
201
+
202
+ # # label: 2D numpy array of class labels
203
+ # # transform: affine transform for the array (e.g., from rasterio)
204
+ # # out_shp: output shapefile path
205
+ # # """
206
+
207
+ # # # Load npz
208
+ # # # base = os.path.splitext(os.path.basename(df.iloc[0]['mosaic']))[0]
209
+ # # # npz_path = os.path.join(in_dir, f"{base}.npz")
210
+ # # npz = np.load(df['npz'].values[0])
211
+
212
+ # # softmax = npz['softmax']
213
+ # # label = np.argmax(softmax, axis=0).astype(np.uint8) # Assuming softmax shape is (classes, height, width)
214
+
215
+ # # # x_min, y_min, x_max, y_max = df[['x_min', 'y_min', 'x_max', 'y_max']].values[0]
216
+
217
+ # # # transform = rio.transform.from_bounds(x_min, y_min, x_max, y_max, label.shape[1], label.shape[0])
218
+
219
+ # # geometry = df['geometry'].values[0]
220
+ # # transform = rio.transform.from_bounds(*geometry.bounds, label.shape[1], label.shape[0])
221
+
222
+ # # # Generate polygons from the label array
223
+ # # mask = label != 0 # Optional: mask out background if label 0 is background
224
+ # # results = (
225
+ # # {'properties': {'class': int(v)}, 'geometry': s}
226
+ # # for s, v in shapes(label, mask=mask, transform=transform)
227
+ # # )
228
+
229
+ # # # Convert to GeoDataFrame
230
+ # # geoms = []
231
+ # # classes = []
232
+ # # for result in results:
233
+ # # geoms.append(shape(result['geometry']))
234
+ # # classes.append(result['properties']['class'])
235
+ # # gdf = gpd.GeoDataFrame({'class': classes, 'geometry': geoms}, crs=f"EPSG:{epsg}")
236
+
237
+ # # # # Save to shapefile
238
+ # # # gdf.to_file(out_shp)
239
+
240
+ # # if len(gdf) == 0:
241
+ # # return None
242
+
243
+ # # return gdf
244
+
245
+ # #=======================================================================
246
+ # def map_npzs(df: pd.DataFrame, in_dir: str, out_dir: str, outName: str, windowSize_m: tuple, epsg: int):
247
+
248
+ # '''
249
+ # '''
250
+
251
+ # # Iterate each row
252
+ # # for idx, row in tqdm(df.iterrows(), total=len(df), desc="Mapping npz files"):
253
+
254
+ # # r = Parallel(n_jobs=-1, verbose=10)(
255
+ # # delayed(label_array_to_shapefile)(df, in_dir, out_dir, outName, windowSize_m, epsg)
256
+ # # for idx, win in tqdm(df.iterrows(), total=len(df), desc="Processing windows")
257
+ # # )
258
+
259
+ # # Concatenate results
260
+ # if not os.path.exists(out_dir):
261
+ # os.makedirs(out_dir)
262
+
263
+ # if len(r) == 0:
264
+ # print("No valid polygons found in any npz files.")
265
+ # return None
266
+ # r = pd.concat(r, ignore_index=True)
267
+
268
+ # if outName:
269
+ # out_shp = os.path.join(out_dir, f"{outName}.shp")
270
+ # else:
271
+ # out_shp = os.path.join(out_dir, 'mapped_polygons.shp')
272
+
273
+ # # r.to_file(out_shp, driver='ESRI Shapefile')
274
+
275
+
276
+
rockmapper/version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = '1.0.0-alpha1'
@@ -0,0 +1,188 @@
1
+ Metadata-Version: 2.4
2
+ Name: rockmapper
3
+ Version: 1.0.0a1
4
+ Summary: Interface for predicting and mapping benthic habitat (substrates) from any side-scan sonar mosaic.
5
+ Author: Cameron Bodine, Wyatt Wolfenkoehler
6
+ Author-email: bodine.cs@gmail.email
7
+ Project-URL: Issues, https://github.com/PINGEcosystem/RockMapper/issues
8
+ Project-URL: GitHub, https://github.com/PINGEcosystem/RockMapper
9
+ Keywords: pingmapper,sonar,ecology,remotesensing,sidescan,sidescan-sonar,aquatic,humminbird,lowrance,gis,oceanography,limnology
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Classifier: Topic :: Scientific/Engineering :: Visualization
16
+ Classifier: Topic :: Scientific/Engineering :: Oceanography
17
+ Classifier: Topic :: Scientific/Engineering :: GIS
18
+ Classifier: Topic :: Scientific/Engineering :: Hydrology
19
+ Requires-Python: <3.13
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: pinginstaller
22
+ Requires-Dist: pingwizard
23
+ Dynamic: author
24
+ Dynamic: author-email
25
+ Dynamic: classifier
26
+ Dynamic: description
27
+ Dynamic: description-content-type
28
+ Dynamic: keywords
29
+ Dynamic: project-url
30
+ Dynamic: requires-dist
31
+ Dynamic: requires-python
32
+ Dynamic: summary
33
+
34
+ # RockMapper
35
+
36
+ # 🚧**UNDER CONSTRUCTION**🚧
37
+
38
+ [![PyPI - Version](https://img.shields.io/pypi/v/rockmapper?style=flat-square&label=Latest%20Version%20(PyPi))](https://pypi.org/project/rockmapper/)
39
+ [![GitHub last commit](https://img.shields.io/github/last-commit/PINGEcosystem/GhostVision)](https://github.com/PINGEcosystem/GhostVision/commits)
40
+ [![GitHub commit activity](https://img.shields.io/github/commit-activity/m/PINGEcosystem/GhostVision)](https://github.com/PINGEcosystem/GhostVision/commits)
41
+ [![GitHub](https://img.shields.io/github/license/PINGEcosystem/GhostVision)](https://github.com/PINGEcosystem/GhostVision/blob/main/LICENSE)
42
+
43
+
44
+ Interface for predicting and mapping benthic habitat (substrates) from any side-scan sonar mosaic.
45
+
46
+ ## Overview
47
+
48
+ `RockMapper` is an open-source Python interface for automatically predicting and mapping substrate types from and side-scan sonar mosaic(s). `RockMapper` leverages SegFormer pre-trained models fine-tuned with [Segmentation Gym](https://github.com/Doodleverse/segmentation_gym) to automatically predict Paddlefish spawning habitat (manuscript forthcoming).
49
+
50
+ ## Published Documentation
51
+
52
+ ### Journal Article
53
+
54
+ Wolfenkoehler, Bodine, Long (*forthcoming...*)
55
+
56
+ ## Installation
57
+
58
+ 1. Install [`Miniforge`](https://conda-forge.org/download/).
59
+ 2. Open the [`Miniforge`](https://conda-forge.org/download/) prompt.
60
+ 3. Install `PINGInstaller`:
61
+ ```
62
+ pip install pinginstaller
63
+ ```
64
+ 4. Install `RockMapper`.
65
+ ```
66
+ python -m pinginstaller rockmapper
67
+ ```
68
+
69
+ ## Usage
70
+
71
+ 1. Copy the following script to some location on your computer:
72
+
73
+ ```python
74
+
75
+
76
+ '''
77
+ Copyright (c) 2025 Cameron S. Bodine
78
+ '''
79
+
80
+ #########
81
+ # Imports
82
+ import os, sys
83
+ import time, datetime
84
+
85
+ start_time = time.time()
86
+
87
+ # Set ROCKMAPPER utils dir
88
+ USER_DIR = os.path.expanduser('~')
89
+ GV_UTILS_DIR = os.path.join(USER_DIR, '.rockmapper')
90
+ if not os.path.exists(GV_UTILS_DIR):
91
+ os.makedirs(GV_UTILS_DIR)
92
+
93
+ def gui():
94
+ '''
95
+ '''
96
+
97
+ #################
98
+ # NEED TO ADD GUI
99
+
100
+
101
+ # FOR DEVELOPMENT
102
+ #############################
103
+ # Update Parameters
104
+ seg_model = 'RockMapper_20250628_v1' # Don't update
105
+ inDir = r'Z:\scratch\202506_BrushyDeepKiamichi_Substrate\mosaics'
106
+ mosaicFileType = '.tif'
107
+ outDirTop = r'Z:\scratch'
108
+ projName = 'RockMapperTest'
109
+ mapRast = False
110
+ mapShp = True
111
+
112
+ epsg = 32616
113
+
114
+ windowSize_m = (18, 18)
115
+ window_stride = 9
116
+ minArea_percent = 0.75
117
+ threadCnt = 0.25
118
+
119
+ predBatchSize = 30
120
+
121
+ deleteIntData = True
122
+
123
+
124
+ ################
125
+ # Run HabiMapper
126
+
127
+ modelDir = os.path.join(GV_UTILS_DIR, 'models')
128
+
129
+ # RockMapper
130
+ if seg_model == 'RockMapper_20250628_v1':
131
+ from rockmapper.rock_mapper import do_work
132
+
133
+ modelDir = os.path.join(modelDir, seg_model)
134
+
135
+
136
+ print('\n\nMapping habitat with ROCKMAPPER model...\n\n')
137
+ do_work(
138
+ inDir = inDir,
139
+ outDirTop = outDirTop,
140
+ projName = projName,
141
+ mapRast = mapRast,
142
+ mapShp = mapShp,
143
+ epsg = epsg,
144
+ windowSize_m = windowSize_m,
145
+ window_stride = window_stride,
146
+ minArea_percent = minArea_percent,
147
+ threadCnt = threadCnt,
148
+ mosaicFileType=mosaicFileType,
149
+ modelDir=modelDir,
150
+ predBatchSize=predBatchSize,
151
+ deleteIntData=deleteIntData
152
+ )
153
+
154
+
155
+
156
+
157
+
158
+ print("\n\nGrand Total Processing Time: ", datetime.timedelta(seconds = round(time.time() - start_time, ndigits=0)))
159
+ return
160
+ ```
161
+
162
+ 2. Open the file with [Visual Studio Code](https://code.visualstudio.com/).
163
+ 3. Update the Parameters as necessary:
164
+
165
+ ```python
166
+ # Update Parameters
167
+ seg_model = 'RockMapper_20250628_v1' # Don't update
168
+ inDir = r'Z:\scratch\202506_BrushyDeepKiamichi_Substrate\mosaics'
169
+ mosaicFileType = '.tif'
170
+ outDirTop = r'Z:\scratch'
171
+ projName = 'RockMapperTest'
172
+ mapRast = False
173
+ mapShp = True
174
+
175
+ epsg = 32616
176
+
177
+ windowSize_m = (18, 18)
178
+ window_stride = 9
179
+ minArea_percent = 0.75
180
+ threadCnt = 0.25
181
+
182
+ predBatchSize = 30
183
+
184
+ deleteIntData = True
185
+ ```
186
+
187
+ 4. Ensure the `rockmapper` environment is selected as the Interpreter [see this](https://stackoverflow.com/a/76289404).
188
+ 5. Run the script in debug mode by pressing `F5`.
@@ -0,0 +1,10 @@
1
+ rockmapper/__init__.py,sha256=8zLGg-DfQhnDl2Ky0n-zXpN-8e-g7iR0AcaI4l4Vvpk,32
2
+ rockmapper/__main__.py,sha256=TkjRXO1Y8jbMLVXmw4P6P1r1G-vSyZpofmDQhx2AUx0,1098
3
+ rockmapper/gui_main.py,sha256=AA7fdsLp_dn6rF8OsKJEHQRHFX4UixKCz-Q0jK5SlN0,2241
4
+ rockmapper/rock_mapper.py,sha256=ZYUX3e9KB3X4YmY65U3KQVCwgnBXCKmBPnuz_ytioY8,13615
5
+ rockmapper/utils.py,sha256=0VmSVhksPV452M54Jbmih0LNOxY2L3FjdF9chOteiBY,10273
6
+ rockmapper/version.py,sha256=XJbD6mq_zm-FX4sZEgO3FNnhJYbjNe1BEeWSDtCc1xA,28
7
+ rockmapper-1.0.0a1.dist-info/METADATA,sha256=0p5lROKiSWDLDXmdbWEcFzr8hG_Pa8b7aPz98U9kuxA,5689
8
+ rockmapper-1.0.0a1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ rockmapper-1.0.0a1.dist-info/top_level.txt,sha256=4opApW-nmXCDNrM4odb9EvAlT5p64wEivbTB_vdNz3Y,11
10
+ rockmapper-1.0.0a1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ rockmapper