-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSB_processing.py
More file actions
2289 lines (1885 loc) · 103 KB
/
Copy pathCSB_processing.py
File metadata and controls
2289 lines (1885 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
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
# -*- coding: utf-8 -*-
"""
Created on Tue May 21 12:49:05 2024
Updated on Fri Jun 26 2025
@author: Anthony.R.Klemm
This script now supports two options for reference bathymetry:
- Automated BlueTopo download.
- User-provided local BAG or GeoTIFF file.
This script integrates multiple stages of CSB data processing:
1. Initial processing and tide correction.
2. (Optional) Post-processing analysis including histograms, offset application,
and outlier detection for individual transits.
3. (Optional) A final gridding stage to produce averaged GeoTIFFs and
filtered GeoPackages, either as a single file or tiled using a
tessellation scheme.
4. (Optional) Organization of final rasters by CRS and VRT creation.
"""
import tkinter as tk
from tkinter import filedialog, ttk
import geopandas as gpd
import pandas as pd
import numpy as np
import requests
import os
from osgeo import gdal, osr
import rasterio
from scipy.interpolate import interp1d
from rasterio.features import shapes, rasterize
from shapely.geometry import shape, LineString, Point
from shapely.validation import make_valid
from rasterio.transform import from_origin
from rasterio.warp import calculate_default_transform, reproject, Resampling
from datetime import datetime, timedelta
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import time
import threading
from rasterio.merge import merge
from rasterio.enums import Resampling as rioResampling
from shapely.ops import unary_union
from skimage.morphology import binary_dilation, binary_erosion
import shutil
import glob
import subprocess
import duckdb
import gc
import math
from fes_model import get_fes_tide
# --- IMPORTS for post-processing analysis ---
import seaborn as sns
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from scipy.ndimage import uniform_filter1d
# Global variables
title = ""
csb = ""
BAG_filepath = ""
fp_zones = ""
output_dir = ""
resolution = 20 # resolution of quick-look geotiff raster
MASTER_OFFSET_FILE = os.path.join(output_dir, "master_offsets.csv")
pd.set_option('display.max_columns', None)
def loadCSB():
print('*****Reading CSB input csv file*****')
df = pd.read_csv(csb)
# Convert 'depth' to numeric and 'time' to datetime; invalid parsing results in NaN
df['depth'] = pd.to_numeric(df['depth'], errors='coerce')
df['time'] = pd.to_datetime(df['time'], errors='coerce')
# Drop rows where 'time' or 'depth' conversion failed
df = df.dropna(subset=['time', 'depth'])
# Filter rows based on depth criteria
df = df[(df['depth'] > 0.5) & (df['depth'] < 1000)]
# Define time bounds and filter by time
lower_bound = pd.to_datetime("2014")
upper_bound = pd.to_datetime(str(datetime.now().year + 1))
df = df[(df['time'] > lower_bound) & (df['time'] < upper_bound)]
# Drop duplicate rows based on key columns
df = df.drop_duplicates(subset=['lon', 'lat', 'depth', 'time', 'unique_id'])
# Create a GeoDataFrame using lon/lat columns
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.lon, df.lat), crs="EPSG:4326")
return gdf
def insert_into_duckdb(gdf, duckdb_path):
"""
Inserts (or appends) data, automatically upgrading the table schema if necessary.
-- FINAL, ROBUST VERSION --
"""
# Ensure the directory for the DuckDB file exists.
duckdb_dir = os.path.dirname(duckdb_path)
if not os.path.exists(duckdb_dir):
os.makedirs(duckdb_dir, exist_ok=True)
df = gdf.copy()
if 'geometry' in df.columns:
df['wkb_geom'] = df['geometry'].apply(lambda geom: geom.wkb if geom is not None else None)
df = df.drop(columns='geometry')
else:
df['wkb_geom'] = None
# This master list defines the complete, final schema.
master_columns_with_types = {
"ControlStn": "VARCHAR", "Raster_Value": "DOUBLE", "Uncertainty_Value": "DOUBLE",
"accuracy_score": "DOUBLE", "date_range": "VARCHAR", "depth_new": "DOUBLE",
"depth_old": "DOUBLE", "depthfinal": "DOUBLE", "lat": "FLOAT", "lon": "FLOAT",
"offset_value": "DOUBLE", "platform_name_x": "VARCHAR", "provider": "VARCHAR",
"std_dev": "DOUBLE", "tile_name": "VARCHAR", "time": "VARCHAR", "unique_id": "VARCHAR",
"wkb_geom": "BLOB", "diff": "DOUBLE", "depth_mod": "DOUBLE", "uncertainty_vert": "DOUBLE",
"uncertainty_hori": "DOUBLE", "Outlier": "BOOLEAN", "transit_id": "VARCHAR",
"vessel_speed_smoothed": "DOUBLE"
}
master_columns = list(master_columns_with_types.keys())
# Ensure the incoming DataFrame has all columns, filling missing with None
for col in master_columns:
if col not in df.columns:
df[col] = None
df = df[master_columns] # Ensure consistent order
try:
with duckdb.connect(database=duckdb_path, read_only=False) as con:
# Check if the 'csb' table exists
table_exists = con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='csb'").fetchone()
if table_exists:
# --- SCHEMA MIGRATION LOGIC ---
# Table exists, so check and add any missing columns.
existing_columns_df = con.execute("DESCRIBE csb").fetchdf()
existing_columns = existing_columns_df['column_name'].tolist()
for col_name, col_type in master_columns_with_types.items():
if col_name not in existing_columns:
print(f"Schema mismatch detected. Adding missing column '{col_name}' to the 'csb' table.")
con.execute(f"ALTER TABLE csb ADD COLUMN {col_name} {col_type};")
else:
# Table does not exist, create it with the full schema.
columns_for_create = ", ".join([f"{name} {dtype}" for name, dtype in master_columns_with_types.items()])
con.execute(f"CREATE TABLE csb ({columns_for_create})")
# Now, the table schema is guaranteed to match our DataFrame.
# Use an explicit column list in the INSERT statement for maximum safety.
col_list_for_insert = ", ".join(master_columns)
con.register("temp_df", df)
con.execute(f"INSERT INTO csb ({col_list_for_insert}) SELECT * FROM temp_df")
print(f"Data successfully appended to DuckDB table at {duckdb_path}.")
except Exception as e:
print(f"CRITICAL ERROR inserting into DuckDB: {e}")
raise e
def draft_corr(master_offsets_df): # MODIFIED: Accept DataFrame
csb_corr = derive_draft(master_offsets_df) # MODIFIED: Pass DataFrame
# Merge the CSB data with the master offsets based on unique vessel ID
# This will now include any newly derived offsets from the step above
master_offsets_updated = read_master_offsets() # Read the potentially updated file
csb_corr1 = csb_corr.merge(master_offsets_updated, on='unique_id', how='left')
# Apply the offset correction
# Fill missing offsets with 0 so the calculation doesn't fail
csb_corr1['offset_value'] = csb_corr1['offset_value'].fillna(0)
csb_corr1['depthfinal'] = csb_corr1['depth_new'] - csb_corr1['offset_value']
csb_corr1['depthfinal'] = csb_corr1['depthfinal'] * -1
# try to drop some unneeded columns
csb_corr1 = csb_corr1.drop(columns=['s', 'f', 'q', 'DataProv', 'ControlS_2', 'ControlS_1', 'row_id', 'platform_name_y'], errors='ignore')
print('*****Processed CSB data ready*****')
# Instead of immediately exporting to geopackage, return the processed GeoDataFrame.
return csb_corr1
def rasterize_CSB(master_offsets_df): # MODIFIED: Accept DataFrame
csb_corr1 = draft_corr(master_offsets_df) # MODIFIED: Pass DataFrame
#Based on GUI options, insert processed data into DuckDB.
if duckdb_option_var.get():
duckdb_path = os.path.join(output_dir, "csb.duckdb")
insert_into_duckdb(csb_corr1, duckdb_path)
# Optionally export as geopackage if the checkbox is selected.
if export_gp_var.get():
gpkg_path = os.path.join(output_dir, 'csb_processed_'+ title +'.gpkg')
print('*****Exporting processed CSB data to geopackage*****')
csb_corr1.to_file(gpkg_path, driver='GPKG', layer='csb')
print(f"Geopackage exported to {gpkg_path}")
return csb_corr1
def reproject_tiff(input_dir, output_dir, target_epsg='EPSG:3395'):
"""
Searches the input directory for files ending in .tif or .tiff,
reprojects each to the target EPSG code, and writes the output to output_dir.
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for root, dirs, files in os.walk(input_dir):
for file in files:
if file.lower().endswith((".tif", ".tiff")):
input_path = os.path.join(root, file)
relative_path = os.path.relpath(root, input_dir)
base_filename, file_extension = os.path.splitext(file)
new_filename = f"{base_filename}_reprojected{file_extension}"
output_path = os.path.join(output_dir, relative_path, new_filename)
output_folder = os.path.dirname(output_path)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
command = [
'gdalwarp', '-t_srs', target_epsg,
input_path, output_path
]
try:
subprocess.run(command, check=True)
# print(f"Reprojected {input_path} to {output_path}")
except Exception as e:
print(f"[DEBUG] Error reprojecting {input_path}: {e}")
def mosaic_tiles(tiles_dir):
"""
Searches the given tiles directory for reprojected TIFF files (with the "_reprojected" suffix).
Then it merges the available TIFF files using rasterio.merge.merge,
writes the merged raster to a file, and returns the path of the merged raster.
"""
mosaic_raster_path = os.path.join(tiles_dir, 'merged_tiles.tif')
# Call the reproject_tiff function (make sure it also works with both .tif and .tiff files)
reproject_tiff(tiles_dir, tiles_dir)
# List to store the opened rasters
raster_list = []
print("[DEBUG] Searching for reprojected TIFF files in:", tiles_dir)
for root, dirs, files in os.walk(tiles_dir):
for file in files:
# Use lower-case for a case-insensitive check
if file.lower().endswith('_reprojected.tif') or file.lower().endswith('_reprojected.tiff'):
raster_path = os.path.join(root, file)
print(f"[DEBUG] Found reprojected file: {raster_path}")
try:
src = rasterio.open(raster_path)
raster_list.append(src)
except Exception as e:
print(f"[DEBUG] Error opening {raster_path}: {e}")
if not raster_list:
raise RuntimeError("No input dataset specified. No reprojected TIFF files were found in " + tiles_dir)
print(f"[DEBUG] Total input datasets found: {len(raster_list)}")
try:
merged_raster, out_transform = merge(raster_list)
except Exception as e:
raise RuntimeError(f"Error during merging: {e}")
# Use metadata from the last opened raster in the list
out_meta = raster_list[-1].meta.copy()
out_meta.update({
"driver": "GTiff",
"height": merged_raster.shape[1],
"width": merged_raster.shape[2],
"transform": out_transform,
"count": raster_list[-1].count
})
try:
with rasterio.open(mosaic_raster_path, "w", **out_meta) as dest:
for i in range(1, out_meta["count"] + 1):
dest.write(merged_raster[i - 1, :, :], i)
print(f"[DEBUG] Merged raster written to {mosaic_raster_path}")
except Exception as e:
raise RuntimeError(f"Error writing merged raster: {e}")
# Close all opened raster files
for src in raster_list:
src.close()
return mosaic_raster_path
def create_convex_hull_and_download_tiles(csb_data_path, output_dir, use_bluetopo=True):
"""
Loads CSB data, builds a convex hull, and writes it to a shapefile.
If use_bluetopo is True, it creates a dedicated Modeling folder,
downloads BlueTopo tiles, copies them to a separate archive folder,
and then builds a VRT from all GeoTIFF files found recursively in that folder.
If use_bluetopo is False, it returns the user‐provided BAG_filepath.
"""
# Load CSB data and create convex hull
csb_data = pd.read_csv(csb_data_path)
gdf = gpd.GeoDataFrame(csb_data, geometry=gpd.points_from_xy(csb_data.lon, csb_data.lat))
gdf = gdf.set_crs(4326, allow_override=True)
convex_hull_polygon = gdf.unary_union.convex_hull
convex_hull_gdf = gpd.GeoDataFrame(geometry=[convex_hull_polygon], crs=gdf.crs)
convex_hull_shapefile = os.path.join(output_dir, "convex_hull_polygon.shp")
convex_hull_gdf.to_file(convex_hull_shapefile)
print(f"Convex hull shapefile written to: {convex_hull_shapefile}")
if use_bluetopo:
# Create the 'Modeling' folder for downloading tiles
bluetopo_tiles_dir = os.path.join(output_dir, "Modeling")
os.makedirs(bluetopo_tiles_dir, exist_ok=True)
# Download BlueTopo tiles
from nbs.bluetopo import fetch_tiles
fetch_tiles(bluetopo_tiles_dir, convex_hull_shapefile, data_source='modeling')
# Use the CSV file's title (assumed to be stored in the global variable 'title')
bluetopo_tiles_copy = os.path.join(output_dir, f"BlueTopo_Tiles_{title}")
if os.path.exists(bluetopo_tiles_copy):
shutil.rmtree(bluetopo_tiles_copy)
shutil.copytree(bluetopo_tiles_dir, bluetopo_tiles_copy)
print(f"Copied BlueTopo tiles to {bluetopo_tiles_copy}")
# Build a VRT from the copied tiles using a unique folder name that includes the title.
vrt_dir = os.path.join(output_dir, f"BlueTopo_VRT_{title}")
os.makedirs(vrt_dir, exist_ok=True)
# Create glob patterns to find both .tif and .tiff files in the unique tiles folder.
tif_pattern = os.path.join(bluetopo_tiles_copy, '**', '*.tif')
tiff_pattern = os.path.join(bluetopo_tiles_copy, '**', '*.tiff')
print(f"[DEBUG] Glob pattern for .tif: {tif_pattern}")
print(f"[DEBUG] Glob pattern for .tiff: {tiff_pattern}")
tile_files = glob.glob(tif_pattern, recursive=True) + glob.glob(tiff_pattern, recursive=True)
print("[DEBUG] Found the following tile files for VRT building:")
for f in tile_files:
print(" ", f)
if not tile_files:
raise RuntimeError("No BlueTopo GeoTIFF files were found in " + bluetopo_tiles_copy)
# Save the VRT file with the title appended to the file name.
vrt_path = os.path.join(vrt_dir, f"merged_tiles_{title}.vrt")
vrt = gdal.BuildVRT(vrt_path, tile_files)
vrt = None # Close the VRT dataset
print(f"Created VRT at {vrt_path}")
return vrt_path
else:
# If not using automated download, assume BAG_filepath is provided by the user.
return BAG_filepath
def reproject_raster(input_raster, output_raster, dst_crs):
with rasterio.open(input_raster) as src:
transform, width, height = calculate_default_transform(
src.crs, dst_crs, src.width, src.height, *src.bounds)
kwargs = src.meta.copy()
kwargs.update({
'crs': dst_crs,
'transform': transform,
'width': width,
'height': height,
'driver': 'GTiff',
'count': 1,
'dtype': src.dtypes[0]
})
with rasterio.open(output_raster, 'w', **kwargs) as dst:
reproject(
source=rasterio.band(src, 1), # Reproject only the first band
destination=rasterio.band(dst, 1),
src_transform=src.transform,
src_crs=src.crs,
dst_transform=transform,
dst_crs=dst_crs,
resampling=Resampling.nearest)
def apply_fes_tides(gdf):
"""
Applies tides using the FES global model.
The resulting depths are referenced to MSL.
"""
print("***** Applying tides using global FES model *****")
fes_data_path = fes_path_var.get()
fes_yaml_path = fes_yaml_var.get()
if not fes_data_path or not fes_yaml_path:
raise ValueError("FES Model requires both a data path and a YAML config file.")
lons = gdf['lon'].to_numpy()
lats = gdf['lat'].to_numpy()
times = gdf['time'].to_numpy(dtype='datetime64[us]')
# Call our new function
tide_values_msl = get_fes_tide(lons, lats, times, fes_data_path, fes_yaml_path)
# Apply the correction: Depth Correction = Original Depth - Tide Height
gdf['depth_new'] = gdf['depth'] - tide_values_msl
# Clean up and prepare for next steps
gdf = gdf.rename(columns={'depth': 'depth_old'})
print("***** FES tide correction complete. Depths are referenced to MSL. *****")
return gdf
def fetch_tide_data(station_id, start_date, end_date, product, interval=None, attempt_great_lakes=False):
base_url = "https://api.tidesandcurrents.noaa.gov/api/prod/datagetter"
params = {
"begin_date": start_date,
"end_date": end_date,
"station": station_id,
"datum": "MLLW" if not attempt_great_lakes else "LWD",
"time_zone": "gmt",
"units": "metric",
"format": "json",
"product": product
}
if interval:
params["interval"] = interval
request_url = requests.Request('GET', base_url, params=params).prepare().url
print(f"Requesting URL: {request_url}")
response = requests.get(base_url, params=params)
data = response.json()
if 'predictions' in data:
df = pd.json_normalize(data['predictions'])
data_type = "predicted data"
elif 'data' in data:
df = pd.json_normalize(data['data'])
data_type = "observed data"
else:
print(f"No data returned for URL: {request_url}")
return pd.DataFrame()
df['t'] = pd.to_datetime(df['t'])
# Convert 'v' to numeric, coercing errors to NaN
df['v'] = pd.to_numeric(df['v'], errors='coerce')
if df['v'].isna().any():
print("Warning: Some tide values could not be converted to numeric and will be dropped.")
df = df.dropna(subset=['v'])
print(f"Pulled {data_type} for station {station_id} from {start_date} to {end_date}")
return df
def check_for_gaps(dataframe, max_gap_duration='1h'):
gaps = dataframe['t'].diff() > pd.Timedelta(max_gap_duration)
return gaps.any()
def cosine_interpolation(df, start_date, end_date):
df['time_num'] = (df['t'] - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')
df = df.sort_values('time_num')
interp_func = interp1d(df['time_num'], df['v'], kind='cubic')
time_num_grid = np.linspace(df['time_num'].min(), df['time_num'].max(), num=3000)
v_grid = interp_func(time_num_grid)
time_grid = pd.to_datetime(time_num_grid, unit='s')
# Trimming
trim_start = pd.to_datetime(start_date) + pd.Timedelta(hours=12)
trim_end = pd.to_datetime(end_date) - pd.Timedelta(hours=12)
trimmed_df = pd.DataFrame({'t': time_grid, 'v': v_grid})
trimmed_df = trimmed_df[(trimmed_df['t'] >= trim_start) & (trimmed_df['t'] <= trim_end)]
#print(trimmed_df)
return trimmed_df
def create_survey_outline(raster_path, output_dir, title, desired_resolution=8, dilation_iterations=3, erosion_iterations=2):
print("starting create_survey_outline() function")
with rasterio.open(raster_path) as raster:
# Resample the raster
data = raster.read(
1, # Reading only the first band
out_shape=(
raster.height // desired_resolution,
raster.width // desired_resolution
),
resampling=Resampling.bilinear
)
# Create a binary mask
nodata = raster.nodatavals[0] or 1000000
binary_mask = (data != nodata).astype(np.uint8)
# Apply dilation and erosion
for _ in range(dilation_iterations):
binary_mask = binary_dilation(binary_mask)
for _ in range(erosion_iterations):
binary_mask = binary_erosion(binary_mask)
# Ensure binary_mask is of type uint8
binary_mask = binary_mask.astype(np.uint8)
# Generate shapes from the binary mask
transform = raster.transform * raster.transform.scale(
(raster.width / data.shape[-1]),
(raster.height / data.shape[-2])
)
#polygons = [shape(geom) for geom, val in shapes(binary_mask, mask=binary_mask, transform=transform) if val == 1]
# Perform unary union
#unified_geometry = unary_union(polygons)
# Generate polygons from the binary mask and make them valid
polygons = [make_valid(shape(geom)) for geom, val in shapes(binary_mask, mask=binary_mask, transform=transform) if val == 1]
# Simplify polygons to reduce complexity
simplified_polygons = [polygon.simplify(tolerance=0.001, preserve_topology=True) for polygon in polygons]
# Perform unary union on simplified, valid polygons
unified_geometry = unary_union(simplified_polygons)
# Reproject unified geometry to WGS84 before simplification
geo_df = gpd.GeoDataFrame(geometry=[unified_geometry], crs=raster.crs)
geo_df = geo_df.to_crs(epsg=4326)
# Simplify the geometry
geo_df['geometry'] = geo_df.geometry.simplify(tolerance=0.001)
# Check and fix bad topology if necessary
geo_df['geometry'] = geo_df.geometry.apply(lambda geom: geom.buffer(0) if not geom.is_valid else geom)
# Save to a shapefile
bathy_polygon_shp = f"{output_dir}/{title}_bathy_polygon.shp"
geo_df.to_file(bathy_polygon_shp, driver='ESRI Shapefile')
print('Bathymetry polygon shapefile created.')
return bathy_polygon_shp
# def tides():
# gdf = loadCSB()
# print('CSB data from csv file loaded. Starting tide correction')
# zones = gpd.read_file(fp_zones)
# join = gpd.sjoin(gdf, zones, how='inner', predicate='within')
# join = join.astype({'time': 'datetime64[ns]'})
# join = join.sort_values('time')
# def generate_date_ranges(dates):
# dates.sort()
# date_ranges = []
# for date in dates:
# if not date_ranges or date - pd.Timedelta(days=1) > date_ranges[-1][1]:
# date_ranges.append([date, date])
# else:
# date_ranges[-1][1] = date
# date_ranges = [(start_date - pd.Timedelta(days=1), end_date + pd.Timedelta(days=1)) for start_date, end_date in date_ranges]
# return [(start_date.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')) for start_date, end_date in date_ranges]
# tdf = []
# known_subordinate_stations = set()
# known_great_lakes_stations = set()
# for station_id in join['ControlStn'].unique():
# station_dates = join[join['ControlStn'] == station_id]['time'].dt.floor('d').unique()
# date_ranges = generate_date_ranges(list(station_dates))
# for start_date, end_date in date_ranges:
# # Try to fetch observed data first
# verified_data = fetch_tide_data(station_id, start_date, end_date, product="water_level")
# if not verified_data.empty and not check_for_gaps(verified_data):
# tdf.append(verified_data)
# else:
# # If there are gaps, try fetching 6-minute predicted data
# predicted_data = fetch_tide_data(station_id, start_date, end_date, product="predictions")
# if not predicted_data.empty and not check_for_gaps(predicted_data):
# tdf.append(predicted_data)
# else:
# # If that doesn't work, fallback to predicted hilo data
# hilo_predictions = fetch_tide_data(station_id, start_date, end_date, product="predictions", interval='hilo')
# if not hilo_predictions.empty:
# interpolated_hilo = cosine_interpolation(hilo_predictions, start_date, end_date)
# tdf.append(interpolated_hilo)
# known_subordinate_stations.add(station_id)
# else:
# great_lakes_data = fetch_tide_data(station_id, start_date, end_date, product="water_level", attempt_great_lakes=True)
# if not great_lakes_data.empty:
# tdf.append(great_lakes_data)
# known_great_lakes_stations.add(station_id)
# else:
# print(f"No water level data available for station {station_id}.")
# if tdf:
# tdf = pd.concat(tdf)
# print("Concatenated tdf shape:", tdf.shape)
# tdf = tdf.sort_values('t')
# jtdf = pd.merge_asof(join, tdf, left_on='time', right_on='t')
# print("jtdf shape before column drop:", jtdf.shape)
# columns_to_drop = ['Shape__Are', 'Shape__Len', 'Input_FID', 'id', 'name', 'state', 'affil',
# 'latitude', 'longitude', 'data', 'metaapi', 'dataapi', 'Shape_Le_2']
# jtdf.drop(columns=columns_to_drop, inplace=True, errors='ignore')
# print("jtdf shape after column drop:", jtdf.shape)
# jtdf = jtdf.dropna(subset=['depth', 'time', 'geometry'])
# print("jtdf shape after dropna:", jtdf.shape)
# jtdf['t_corr'] = jtdf['t'] + pd.to_timedelta(jtdf['ATCorr'], unit='m')
# newdf = jtdf[['t_corr', 'v']].copy()
# print("newdf shape before dropna:", newdf.shape)
# newdf = newdf.rename(columns={'v': 'v_new', 't_corr': 't_new'})
# newdf = newdf.sort_values('t_new').dropna()
# print("newdf shape after dropna:", newdf.shape)
# csb_corr = pd.merge_asof(jtdf, newdf, left_on='time', right_on='t_new', direction='nearest')
# print("csb_corr shape before dropna:", csb_corr.shape)
# print("csb_corr shape after dropna:", csb_corr.shape)
# csb_corr['depth_new'] = csb_corr['depth'] - (csb_corr['RR'] * csb_corr['v_new'])
# print("csb_corr shape after applying tide corrections:", csb_corr.shape)
# csb_corr = gpd.GeoDataFrame(csb_corr, geometry='geometry', crs='EPSG:4326')
# csb_corr['time'] = csb_corr['time'].dt.strftime("%Y%m%d %H:%M:%S")
# csb_corr = csb_corr[(csb_corr['depth'] > 1.5) & (csb_corr['depth'] < 1000)]
# csb_corr = csb_corr.rename(columns={'depth': 'depth_old'}).drop(columns=['index_right', 'ATCorr', 'RR', 'ATCorr2', 'RR2', 'Shape_Leng', 'Shape_Area', 'Shape_Le_1', 't', 'v', 't_corr', 't_new', 'v_new'])
# return csb_corr
# else:
# print("No tide data available for the specified period.")
# return pd.DataFrame()
def tides():
gdf = loadCSB()
if fes_model_var.get():
# --- Route to the new FES model function ---
# This path completely bypasses the NOAA zoned tide logic
csb_corr = apply_fes_tides(gdf)
# Add columns that are expected by later functions but not created by FES
csb_corr['ControlStn'] = 'FES_Model'
csb_corr['time'] = csb_corr['time'].dt.strftime("%Y%m%d %H:%M:%S")
csb_corr = gpd.GeoDataFrame(csb_corr, geometry='geometry', crs='EPSG:4326')
else:
# --- Route to the original NOAA zoned tide logic ---
print('CSB data from csv file loaded. Starting NOAA tide correction')
zones = gpd.read_file(fp_zones)
join = gpd.sjoin(gdf, zones, how='inner', predicate='within')
join = join.astype({'time': 'datetime64[ns]'})
join = join.sort_values('time')
def generate_date_ranges(dates):
dates.sort()
date_ranges = []
for date in dates:
if not date_ranges or date - pd.Timedelta(days=1) > date_ranges[-1][1]:
date_ranges.append([date, date])
else:
date_ranges[-1][1] = date
date_ranges = [(start_date - pd.Timedelta(days=1), end_date + pd.Timedelta(days=1)) for start_date, end_date in date_ranges]
return [(start_date.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')) for start_date, end_date in date_ranges]
tdf = []
known_subordinate_stations = set()
known_great_lakes_stations = set()
for station_id in join['ControlStn'].unique():
station_dates = join[join['ControlStn'] == station_id]['time'].dt.floor('d').unique()
date_ranges = generate_date_ranges(list(station_dates))
for start_date, end_date in date_ranges:
# Try to fetch observed data first
verified_data = fetch_tide_data(station_id, start_date, end_date, product="water_level")
if not verified_data.empty and not check_for_gaps(verified_data):
tdf.append(verified_data)
else:
# If there are gaps, try fetching 6-minute predicted data
predicted_data = fetch_tide_data(station_id, start_date, end_date, product="predictions")
if not predicted_data.empty and not check_for_gaps(predicted_data):
tdf.append(predicted_data)
else:
# If that doesn't work, fallback to predicted hilo data
hilo_predictions = fetch_tide_data(station_id, start_date, end_date, product="predictions", interval='hilo')
if not hilo_predictions.empty:
interpolated_hilo = cosine_interpolation(hilo_predictions, start_date, end_date)
tdf.append(interpolated_hilo)
known_subordinate_stations.add(station_id)
else:
great_lakes_data = fetch_tide_data(station_id, start_date, end_date, product="water_level", attempt_great_lakes=True)
if not great_lakes_data.empty:
tdf.append(great_lakes_data)
known_great_lakes_stations.add(station_id)
else:
print(f"No water level data available for station {station_id}.")
if tdf:
tdf = pd.concat(tdf)
print("Concatenated tdf shape:", tdf.shape)
tdf = tdf.sort_values('t')
jtdf = pd.merge_asof(join, tdf, left_on='time', right_on='t')
print("jtdf shape before column drop:", jtdf.shape)
columns_to_drop = ['Shape__Are', 'Shape__Len', 'Input_FID', 'id', 'name', 'state', 'affil',
'latitude', 'longitude', 'data', 'metaapi', 'dataapi', 'Shape_Le_2']
jtdf.drop(columns=columns_to_drop, inplace=True, errors='ignore')
print("jtdf shape after column drop:", jtdf.shape)
jtdf = jtdf.dropna(subset=['depth', 'time', 'geometry'])
print("jtdf shape after dropna:", jtdf.shape)
jtdf['t_corr'] = jtdf['t'] + pd.to_timedelta(jtdf['ATCorr'], unit='m')
newdf = jtdf[['t_corr', 'v']].copy()
print("newdf shape before dropna:", newdf.shape)
newdf = newdf.rename(columns={'v': 'v_new', 't_corr': 't_new'})
newdf = newdf.sort_values('t_new').dropna()
print("newdf shape after dropna:", newdf.shape)
csb_corr = pd.merge_asof(jtdf, newdf, left_on='time', right_on='t_new', direction='nearest')
print("csb_corr shape before dropna:", csb_corr.shape)
print("csb_corr shape after dropna:", csb_corr.shape)
csb_corr['depth_new'] = csb_corr['depth'] - (csb_corr['RR'] * csb_corr['v_new'])
print("csb_corr shape after applying tide corrections:", csb_corr.shape)
csb_corr = gpd.GeoDataFrame(csb_corr, geometry='geometry', crs='EPSG:4326')
csb_corr['time'] = csb_corr['time'].dt.strftime("%Y%m%d %H:%M:%S")
csb_corr = csb_corr[(csb_corr['depth'] > 1.5) & (csb_corr['depth'] < 1000)]
csb_corr = csb_corr.rename(columns={'depth': 'depth_old'}).drop(columns=['index_right', 'ATCorr', 'RR', 'ATCorr2', 'RR2', 'Shape_Leng', 'Shape_Area', 'Shape_Le_1', 't', 'v', 't_corr', 't_new', 'v_new'])
else:
print("No tide data available for the specified period.")
# Return an empty DataFrame but with columns expected by later steps to avoid errors
csb_corr = pd.DataFrame(columns=gdf.columns.tolist() + ['depth_old', 'depth_new'])
return csb_corr
# def BAGextract():
# print("starting BAGextract() function")
# global BAG_filepath
# BAG_filepath = os.path.abspath(BAG_filepath) # Ensure it's an absolute path
# print("DEBUG - BAG_filepath:", BAG_filepath)
# print('*****Starting to import BAG bathy and aggregate to 8m geotiff*****')
# # Translate options and creation of multi-band GeoTIFF
# translate_options = gdal.TranslateOptions(bandList=[1, 2], creationOptions=['COMPRESS=LZW'])
# intermediate_raster_path = output_dir + '/' + title + '_intermediate.tif'
# dataset = gdal.Open(BAG_filepath, gdal.GA_ReadOnly)
# if dataset is None:
# print("Error: Unable to open the file. Check the file path.")
# return None, None
# gdal.Translate(intermediate_raster_path, dataset, options=translate_options)
# # Check the CRS
# crs = osr.SpatialReference(wkt=dataset.GetProjection())
# dataset = None # Close the dataset
# if crs.IsGeographic():
# print("Reprojecting GeoTIFF to a projected CRS...")
# reprojected_raster_path = output_dir + '/' + title + '_reprojected.tif'
# gdal.Warp(reprojected_raster_path, intermediate_raster_path, dstSRS='EPSG:3395', creationOptions=['COMPRESS=LZW'])
# intermediate_raster_path = reprojected_raster_path
# # Open the intermediate raster to check its resolution
# with rasterio.open(intermediate_raster_path) as src:
# res_x, res_y = src.res
# # Check if the resolution is coarser than 8m
# if max(res_x, res_y) > 8:
# output_raster = intermediate_raster_path
# else:
# # Resample to desired resolution
# output_raster_resampled = output_dir + '/' + title + '_5m_MLLW.tif'
# gdal.Warp(output_raster_resampled, intermediate_raster_path, xRes=8, yRes=8, creationOptions=['COMPRESS=LZW'])
# output_raster = output_raster_resampled
# # Clean up intermediate file
# os.remove(intermediate_raster_path)
# # Replace NaN values and update nodata value in the raster
# with rasterio.open(output_raster) as src:
# data = src.read()
# meta = src.meta
# data = np.where(np.isnan(data), 1000000, data)
# meta.update(nodata=1000000)
# with rasterio.open(output_raster, 'w', **meta) as dst:
# dst.write(data)
# # Reproject the raster to WGS84
# output_raster_wgs84 = output_dir + '/' + title + '_wgs84.tif'
# gdal.Warp(output_raster_wgs84, output_raster, dstSRS='EPSG:4326', creationOptions=['COMPRESS=LZW'])
# # Call create_survey_outline to generate the bathymetry polygon shapefile
# bathy_polygon_shp = create_survey_outline(output_raster_wgs84, output_dir, title)
# # Clean up intermediate files
# try:
# os.remove(intermediate_raster_path)
# os.remove(output_raster_resampled)
# os.remove(output_raster_wgs84)
# except Exception:
# pass
# return output_raster_wgs84, bathy_polygon_shp
def BAGextract():
print("starting BAGextract() function")
global BAG_filepath
BAG_filepath = os.path.abspath(BAG_filepath)
print("DEBUG - BAG_filepath:", BAG_filepath)
print('*****Starting to import reference bathy*****')
output_raster_wgs84 = os.path.join(output_dir, title + '_wgs84.tif')
temp_vrt_path = os.path.join(output_dir, 'temp_for_warp.vrt')
print("Warping input raster to standard WGS84 (EPSG:4269)...")
input_for_warp = BAG_filepath
# --- CORRECTED LOGIC for BAG Files ---
# For BAG files, we first create a VRT to select the depth and uncertainty bands
if BAG_filepath.lower().endswith('.bag'):
print("BAG file detected, creating temporary VRT to select bands 1 and 2...")
# gdal.BuildVRT is the correct place to use bandList
gdal.BuildVRT(temp_vrt_path, BAG_filepath, bandList=[1, 2])
input_for_warp = temp_vrt_path
# The gdal.Warp function no longer has the incorrect 'bandList' argument
gdal.Warp(output_raster_wgs84, input_for_warp,
dstSRS='EPSG:4326',
creationOptions=['COMPRESS=LZW'],
dstNodata=1000000)
# Clean up the temporary VRT file if it was created
if os.path.exists(temp_vrt_path):
os.remove(temp_vrt_path)
print("Reference raster prepared successfully.")
# Call create_survey_outline to generate the bathymetry polygon shapefile
bathy_polygon_shp = create_survey_outline(output_raster_wgs84, output_dir, title)
return output_raster_wgs84, bathy_polygon_shp
def read_master_offsets():
"""Reads the master offsets from a CSV file."""
MASTER_OFFSET_FILE = os.path.join(output_dir, "master_offsets.csv")
if os.path.exists(MASTER_OFFSET_FILE):
return pd.read_csv(MASTER_OFFSET_FILE)
else:
return pd.DataFrame(columns=['unique_id', 'platform_name', 'offset_value', 'std_dev', 'accuracy_score', 'date_range', 'tile_name'])
def update_master_offsets(unique_id, platform_name, new_offset, std_dev, date_range, tile_name):
global MASTER_OFFSET_FILE
MASTER_OFFSET_FILE = os.path.join(output_dir, "master_offsets.csv")
master_offsets = read_master_offsets()
accuracy_score = 1 / std_dev if std_dev != 0 else 0
#print('checking for existing offset by unique_id and platform_name')
existing_index = master_offsets[(master_offsets['unique_id'] == unique_id)].index
new_row = pd.DataFrame([{
'unique_id': unique_id,
'platform_name': platform_name,
'offset_value': new_offset,
'std_dev': std_dev,
'accuracy_score': accuracy_score,
'date_range': date_range,
'tile_name': tile_name
}])
# Exclude empty or all-NA entries before concatenation
new_row = new_row.dropna(how='all')
if existing_index.empty:
master_offsets = pd.concat([master_offsets, new_row], ignore_index=True)
else:
if master_offsets.loc[existing_index[0], 'accuracy_score'] <= accuracy_score:
master_offsets.loc[existing_index[0], list(new_row.columns)] = new_row.iloc[0]
try:
master_offsets.to_csv(MASTER_OFFSET_FILE, index=False)
#print(f"Master offsets updated successfully in {MASTER_OFFSET_FILE}.")
except Exception as e:
print(f"Failed to update master offsets: {e}")
def get_raster_values_vectorized(coords, raster_path, batch_size=100000):
"""
Given a list of (x, y) coordinate pairs and a raster file path,
returns a list of lists, each containing the pixel values from
all bands at that coordinate.
If the number of coordinates exceeds batch_size, processing is done in batches.
Pixels with nodata values are replaced with np.nan.
"""
all_samples = []
with rasterio.open(raster_path) as src:
nodata = src.nodatavals # Tuple of nodata values for each band
# Process in batches if necessary to manage memory usage
if len(coords) > batch_size:
for i in range(0, len(coords), batch_size):
batch_coords = coords[i:i+batch_size]
batch_samples = list(src.sample(batch_coords))
all_samples.extend(batch_samples)
else:
all_samples = list(src.sample(coords))
# Process the samples to replace nodata values with np.nan
processed_samples = []
for sample in all_samples:
processed = []
for i, val in enumerate(sample):
if nodata[i] is not None and val == nodata[i]:
processed.append(np.nan)
else:
processed.append(val)
processed_samples.append(processed)
return processed_samples
# def derive_draft(master_offsets_df): # MODIFIED: Accept DataFrame
# output_raster, raster_boundary_shp = BAGextract()
# csb_corr = tides()
# # --- NEW: Get a list of vessels that already have an offset ---
# vessels_with_offsets = master_offsets_df['unique_id'].unique().tolist()
# print(f"Found {len(vessels_with_offsets)} vessels with pre-existing offsets.")
# # Read and fix geometries in the raster boundary and CSB data
# raster_boundary = gpd.read_file(raster_boundary_shp)
# raster_boundary['geometry'] = raster_boundary['geometry'].apply(
# lambda geom: geom if geom.is_valid else geom.buffer(0)
# )
# csb_corr['geometry'] = csb_corr['geometry'].apply(
# lambda geom: geom if geom.is_valid else geom.buffer(0)
# )
# csb_corr['row_id'] = range(len(csb_corr))
# # Compute the unary union of the raster boundary geometries once
# boundary_union = raster_boundary.geometry.unary_union
# # Get the bounding box of the boundary_union: (minx, miny, maxx, maxy)
# bbox = boundary_union.bounds
# # Use the spatial index to find candidate points that intersect the bbox
# possible_matches_index = csb_corr.sindex.query(boundary_union, predicate="intersects")
# possible_matches = csb_corr.iloc[possible_matches_index]
# # Now apply the precise .within() filter on this subset
# csb_corr_subset = possible_matches[possible_matches.geometry.within(boundary_union)]
# # --- MODIFIED: Filter out vessels that already have an offset ---
# csb_for_offset_derivation = csb_corr_subset[~csb_corr_subset['unique_id'].isin(vessels_with_offsets)]
# if csb_for_offset_derivation.empty:
# print("All vessels within reference data already have offsets. Skipping new offset calculation.")
# # We still need to sample the raster for all points for post-processing diff calculation
# # So we continue, but the offset derivation part will be skipped.
# else:
# print(f"Found {csb_for_offset_derivation['unique_id'].nunique()} new vessels requiring offset derivation.")
# # Instead of sampling 1000 points per vessel, use all points.
# sampled_csb_corr_subset = csb_corr_subset.copy()
# # Compute date ranges for each vessel (unique_id) using all available points.
# date_ranges = {}
# for name, group in csb_corr_subset.groupby('unique_id'):
# # Ensure time is in datetime format.
# group['time'] = pd.to_datetime(group['time'])
# min_timestamp = group['time'].min()
# max_timestamp = group['time'].max()
# if pd.notnull(min_timestamp) and pd.notnull(max_timestamp):
# date_ranges[name] = (min_timestamp.strftime('%Y%m%d'), max_timestamp.strftime('%Y%m%d'))
# else:
# date_ranges[name] = ("19700101", "19700101")
# # Use the new vectorized raster sampling function over all points.
# try:
# # Extract (x, y) coordinates from the GeoDataFrame.
# coords = [(geom.x, geom.y) for geom in sampled_csb_corr_subset.geometry]
# # Get raster values (supports batching if needed).