-
Notifications
You must be signed in to change notification settings - Fork 0
/
recoveryVariability.py
3139 lines (2613 loc) · 112 KB
/
recoveryVariability.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
from run_lidarcollect import *
from run_hydrocollect import *
from funcs.create_contours import *
from funcs.lidar_check import *
from funcs.calculate_beachvol import *
from funcs.lidar_fillgaps import *
from run_makeplots import *
import pickle
import os
# DEFINE WHERE FRF DATA FILES ARE LOCATED
# local_base = 'D:/FRF_data/'
local_base = '/volumes/macDrive/FRF_data/'
# DEFINE TIME PERIOD OF INTEREST
time_beg = '2016-01-01T00:00:00' # 'YYYY-MM-DDThh:mm:ss' (string), time of interest BEGIN
time_end = '2024-10-01T00:00:00' # 'YYYY-MM-DDThh:mm:ss (string), time of interest END
tzinfo = dt.timezone(-dt.timedelta(hours=4)) # FRF = UTC-4
# DEFINE CONTOUR ELEVATIONS OF INTEREST
cont_elev = np.arange(-1.75,4.00,0.25) # <<< MUST BE POSITIVELY INCREASING
# DEFINE NUMBER OF PROFILES TO PLOT
num_profs_plot = 15
# DEFINE SUBDIR WITH LIDAR FILES
lidarfloc = local_base + 'dune_lidar/lidar_transect/'
lidarext = 'nc' # << change not recommended; defines file type to look for
# DEFINE SUBDIR WITH NOAA WATERLEVEL FILES
noaawlfloc = local_base + 'waterlevel/'
noaawlext = 'nc' # << change not recommended; defines file type to look for
# DEFINE SUBDIR WITH LIDAR HYDRO FILES
lidarhydrofloc = local_base + 'waves_lidar/lidar_hydro/'
lidarhydroext = 'nc' # << change not recommended; defines file type to look for
# -------------------- BEGIN RUN_CODE.PY --------------------
# convert period of interest to datenum
time_format = '%Y-%m-%dT%H:%M:%S'
epoch_beg = dt.datetime.strptime(time_beg,time_format).timestamp()
epoch_end = dt.datetime.strptime(time_end,time_format).timestamp()
TOI_duration = dt.datetime.fromtimestamp(epoch_end)-dt.datetime.fromtimestamp(epoch_beg)
# Save timing variables
with open('timeinfo.pickle','wb') as file:
pickle.dump([tzinfo,time_format,time_beg,time_end,epoch_beg,epoch_end,TOI_duration], file)
# run file run_lidarcollect.py
lidarelev,lidartime,lidar_xFRF,lidarelevstd,lidarmissing = run_lidarcollect(lidarfloc, lidarext)
# Remove weird data (first order filtering)
stdthresh = 0.05 # [m], e.g., 0.05 equals 5cm standard deviation in hrly reading
pmissthresh = 0.75 # [0-1]. e.g., 0.75 equals 75% time series missing
tmpii = (lidarelevstd >= stdthresh) + (lidarmissing > pmissthresh)
lidarelev[tmpii] = np.nan
# run file create_contours.py
elev_input = lidarelev
cont_ts, cmean, cstd = create_contours(elev_input,lidartime,lidar_xFRF,cont_elev)
lidarTime = lidartime
lidarProfiles = lidarelev
lidarContours = cont_ts
dts = [dt.datetime.utcfromtimestamp(ts) for ts in lidarTime]
del lidartime
del lidarelev
del cont_ts
del cmean
del cstd
import pickle
clusterPickle = 'alongshoreAverages.pickle'
with open(clusterPickle, "rb") as input_file:
inputCusps = pickle.load(input_file)
profileTimeAlongshore = inputCusps['profileTime']
alongshoreAverageTime = [dt.datetime.utcfromtimestamp(ts) for ts in profileTimeAlongshore]
# lidar_yFRFAlongshore = inputCusps['lidar_yFRF']
lidar_xFRFAlongshore = inputCusps['lidar_xFRF']
ysCAlongshore = inputCusps['ysC']
alongshoreAverage = inputCusps['alongshoreAverage']
alongshoreAverage = np.stack(alongshoreAverage,axis=0)
# alongshoreStd = inputCusps['alongshoreStd']
# cont_elev_alongshore = inputCusps['cont_elev']
# cont_ts_alongshore = inputCusps['cont_ts']
# cmean_alongshore = inputCusps['cmean']
# cstd_alongshore = inputCusps['cstd']
del profileTimeAlongshore
cuspsPickle = 'cuspTimes.pickle'
with open(cuspsPickle, "rb") as input_file:
inputTime = pickle.load(input_file)
timeCusps = inputTime['timeCusps']
cuspsTimes = [dt.datetime.utcfromtimestamp(ts) for ts in timeCusps]
del timeCusps
# s = 25000
# plt.figure()
# for hh in range(100):
# plt.plot(lidar_xFRF,lidarProfiles[s+hh])
#
def rmse(predictions, targets):
differences = predictions - targets #the DIFFERENCEs.
differences_squared = differences ** 2 #the SQUAREs of ^
mean_of_differences_squared = differences_squared.mean() #the MEAN of ^
rmse_val = np.sqrt(mean_of_differences_squared) #ROOT of ^
return rmse_val #get the ^
import numba
import numpy as np
@numba.njit()
def interpolate_with_max_gap(orig_x,
orig_y,
target_x,
max_gap=np.inf,
orig_x_is_sorted=False,
target_x_is_sorted=False):
"""
Interpolate data linearly with maximum gap. If there is
larger gap in data than `max_gap`, the gap will be filled
with np.nan.
The input values should not contain NaNs.
Parameters
---------
orig_x: np.array
The input x-data
orig_y: np.array
The input y-data
target_x: np.array
The output x-data; the data points in x-axis that
you want the interpolation results from.
max_gap: float
The maximum allowable gap in `orig_x` inside which
interpolation is still performed. Gaps larger than
this will be filled with np.nan in the output `target_y`.
orig_x_is_sorted: boolean, default: False
If True, the input data `orig_x` is assumed to be monotonically
increasing. Some performance gain if you supply sorted input data.
target_x_is_sorted: boolean, default: False
If True, the input data `target_x` is assumed to be
monotonically increasing. Some performance gain if you supply
sorted input data.
Returns
------
target_y: np.array
The interpolation results.
"""
if not orig_x_is_sorted:
# Sort to be monotonous wrt. input x-variable.
idx = orig_x.argsort()
orig_x = orig_x[idx]
orig_y = orig_y[idx]
if not target_x_is_sorted:
target_idx = target_x.argsort()
# Needed for sorting back the data.
target_idx_for_reverse = target_idx.argsort()
target_x = target_x[target_idx]
target_y = np.empty(target_x.size)
idx_orig = 0
orig_gone_through = False
for idx_target, x_new in enumerate(target_x):
# Grow idx_orig if needed.
while not orig_gone_through:
if idx_orig + 1 >= len(orig_x):
# Already consumed the orig_x; no more data
# so we would need to extrapolate
orig_gone_through = True
elif x_new > orig_x[idx_orig + 1]:
idx_orig += 1
else:
# x_new <= x2
break
if orig_gone_through:
target_y[idx_target] = np.nan
continue
x1 = orig_x[idx_orig]
y1 = orig_y[idx_orig]
x2 = orig_x[idx_orig + 1]
y2 = orig_y[idx_orig + 1]
if x_new < x1:
# would need to extrapolate to left
target_y[idx_target] = np.nan
continue
delta_x = x2 - x1
if delta_x > max_gap:
target_y[idx_target] = np.nan
continue
delta_y = y2 - y1
if delta_x == 0:
target_y[idx_target] = np.nan
continue
k = delta_y / delta_x
delta_x_new = x_new - x1
delta_y_new = k * delta_x_new
y_new = y1 + delta_y_new
target_y[idx_target] = y_new
if not target_x_is_sorted:
return target_y[target_idx_for_reverse]
return target_y
from scipy.io.matlab.mio5_params import mat_struct
import scipy.io as sio
# def ReadMatfile(p_mfile):
# 'Parse .mat file to nested python dictionaries'
#
# def RecursiveMatExplorer(mstruct_data):
# # Recursive function to extrat mat_struct nested contents
#
# if isinstance(mstruct_data, mat_struct):
# # mstruct_data is a matlab structure object, go deeper
# d_rc = {}
# for fn in mstruct_data._fieldnames:
# d_rc[fn] = RecursiveMatExplorer(getattr(mstruct_data, fn))
# return d_rc
#
# else:
# # mstruct_data is a numpy.ndarray, return value
# return mstruct_data
#
# # base matlab data will be in a dict
# mdata = sio.loadmat(p_mfile, squeeze_me=True, struct_as_record=False)
# mdata_keys = [x for x in mdata.keys() if x not in
# ['__header__','__version__','__globals__']]
#
# # use recursive function
# dout = {}
# for k in mdata_keys:
# dout[k] = RecursiveMatExplorer(mdata[k])
# return dout
#
# wls = ReadMatfile('/Users/dylananderson/Documents/data/noaaWaterLevels/duck/noaa8651370.mat')
# tide = wls['dailyData']['tide']
# wl = wls['dailyData']['wl']
# seasonal = wls['dailyData']['seasonal']
# msl = wls['dailyData']['msl']
# mmsla = wls['dailyData']['mmsla']
# dsla = wls['dailyData']['dsla']
# ss = wls['dailyData']['ss']
# timeHourly = wls['dailyData']['hourlyDateVec']
# timeMonthly = wls['dailyData']['monthDateVec']
# mmslaMonth = wls['dailyData']['mmsla_month']
import numpy as np
import pandas as pd
import requests
from datetime import datetime
def download_noaa_tides_dylanWithPred(gauge, datum, start_year, end_year):
wl = []
time = []
pred = []
matlabTimePred = []
datetimePred = []
for yr in range(start_year, end_year + 1):
print(yr)
# NOAA API URLs for water levels and predictions
website = f'https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?begin_date={yr}0101&end_date={yr}1231&station={gauge}&product=hourly_height&datum={datum}&time_zone=gmt&units=metric&format=csv'
website2 = f'https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?begin_date={yr}0101&end_date={yr}1231&station={gauge}&product=predictions&datum={datum}&time_zone=gmt&units=metric&format=csv'
try:
# Download hourly height data
response = requests.get(website, timeout=15)
with open('tempwaves.csv', 'w') as f:
f.write(response.text)
data2 = pd.read_csv('tempwaves.csv')
# Parse datetime
data2['datetime'] = pd.to_datetime(data2['Date Time'], format='%Y-%m-%d %H:%M')
wl.extend(data2[' Water Level'].values)
time.extend(data2['datetime'].apply(lambda x: x.toordinal() + x.hour / 24 + x.minute / 1440).values)
# Download predictions data
response2 = requests.get(website2, timeout=15)
with open('tempwaves2.csv', 'w') as f:
f.write(response2.text)
data = pd.read_csv('tempwaves2.csv')
# Parse datetime for predictions
data['datetime'] = pd.to_datetime(data['Date Time'], format='%Y-%m-%d %H:%M')
pred.extend(data[' Prediction'].values)
matlabTimePred.extend(data['datetime'].apply(lambda x: x.toordinal() + x.hour / 24 + x.minute / 1440).values)
datetimePred.extend(data['datetime'].values)
except Exception as e:
print(f"Error for year {yr}: {e}")
continue
# Output data as a dictionary
tideout = {
'wltime': np.array(time),
'wl': np.array(wl, dtype=float),
'predtimeMatlabTime': np.array(matlabTimePred),
'predtimeDateTime': np.array(datetimePred),
'pred': np.array(pred, dtype=float)
}
return tideout
gauge = '8651370'
datum = 'MSL'
start_year = 2016#1978
end_year = 2024
tideout = download_noaa_tides_dylanWithPred(gauge, datum, start_year, end_year)
dat = tideout['wl']
time = tideout['wltime']
time_tide_predUTC = np.asarray([(dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's') for dt64 in tideout['predtimeDateTime'][::5]])
time_tide_pred = np.asarray([datetime.utcfromtimestamp(utc) for utc in time_tide_predUTC])
tide_pred = tideout['pred'][::5]
from scipy.signal import find_peaks
peaks = find_peaks(tide_pred)
highTideTimes = time_tide_pred[peaks[0]]
highTideUTCtime = time_tide_predUTC[peaks[0]]
highTides = tide_pred[peaks[0]]
del tideout
import datetime as dt
from dateutil.relativedelta import relativedelta
st = dt.datetime(2016,1,1)
# end = dt.datetime(2021,12,31)
end = dt.datetime(2024,10,1)
step = relativedelta(days=1)
dayTime = []
while st < end:
dayTime.append(st)#.strftime('%Y-%m-%d'))
st += step
# st = dt.datetime(2016,1,1)
# # end = dt.datetime(2021,12,31)
# end = dt.datetime(2024,10,1)
# step = relativedelta(days=2)
# twoDayTime = []
# while st < end:
# twoDayTime.append(st)#.strftime('%Y-%m-%d'))
# st += step
def find_files_local(floc,ext_in):
full_path = floc
ids = []
for file in os.listdir(full_path):
if file.endswith(ext_in):
if not file.startswith('.'):
ids.append(file)
return ids
from datetime import datetime
#
# #start with NOAA water level files
# floc = noaawlfloc
# ext = noaawlext
# fname_in_range = find_files_local(floc,ext)#find_files_in_range(floc,ext,epoch_beg,epoch_end, tzinfo)
# wltime_noaa = []
# wltime_datetime = []
# wl_noaa = []
# for fname_ii in fname_in_range:
# print('reading... ' + fname_ii)
# full_path = floc + fname_ii
# waterlevel_noaa, time_noaa = getlocal_waterlevels(full_path)
# convertTime = np.asarray([datetime.utcfromtimestamp(st) for st in time_noaa])
# wltime_datetime = np.append(wltime_datetime,convertTime)
# wltime_noaa = np.append(wltime_noaa, time_noaa)
# wl_noaa = np.append(wl_noaa, waterlevel_noaa)
#
#
# from dateutil.relativedelta import relativedelta
# st = dt.datetime(2016, 1, 1,5,30,0)
# end = dt.datetime(2024,10,1)
# step = relativedelta(hours=12.41667)
# wlTimes = []
# wlDateTimes = []
# while st < end:
# wlDateTimes.append(st) #.strftime('%Y-%m-%d')
# wlTimes.append((st - datetime(1970,1,1)).total_seconds())
# st += step
#
# highTideIndices = []
# highTideTimes = []
# highTides = []
# highTideUTCtime = []
# morphTime = []
# morphUTCtime = []
# for qq in range(len(wlDateTimes)-1):
# # inder = np.where((wlTimes[qq] > wltime_noaa) & (wlTimes[qq] < wltime_noaa))
# # inder = np.where((wltime_datetime >= wlDateTimes[qq]) & (wltime_datetime <= wlDateTimes[qq+1]))
# inder = np.where((time_tide_pred >= wlDateTimes[qq]) & (time_tide_pred <= wlDateTimes[qq+1]))
#
# if len(inder[0]) == 0:
# print('gap in the record for {}'.format(wlDateTimes[qq]))
# else:
# temp = tide_pred[inder]
# temp = np.delete(temp,np.where(np.isnan(temp)))
# if len(temp) > 0:
# subsetWLind = np.nanargmax(tide_pred[inder])
# subsetTime = time_tide_pred[inder]
# subsetUTC = time_tide_predUTC[inder]#np.asarray([dt.datetime.utcfromtimestamp(ts) for ts in subsetTime])
# highTideUTCtime.append(subsetUTC[subsetWLind])
# highTideTimes.append(subsetTime[subsetWLind])
# highTides.append(np.nanmax(tide_pred[inder]))
# morphTime.append(wlDateTimes[qq])
# morphUTCtime.append(wlTimes[qq])
# dailyAverage = np.nan * np.ones((len(dayTime),len(lidar_xFRF)))
# dailyStd = np.nan * np.ones((len(dayTime),len(lidar_xFRF)))
# dailyAverageWithData = []
# dailyStdWithData = []
# dailyTimeWithData = []
# for qq in range(len(dayTime)-1):
# inder = np.where((np.asarray(dts)>=np.asarray(dayTime)[qq]) & (np.asarray(dts) <=np.asarray(dayTime)[qq+1]))
# if len(inder[0])>0:
# dailyAverage[qq,:] = np.nanmean(lidarProfiles[inder[0],:],axis=0)
# dailyStd[qq,:] = np.nanstd(lidarProfiles[inder[0],:],axis=0)
# dailyAverageWithData.append(np.nanmean(lidarProfiles[inder[0],:],axis=0))
# dailyStdWithData.append(np.nanstd(lidarProfiles[inder[0],:],axis=0))
# dailyTimeWithData.append(dayTime[qq])
# dailyTimeWithData = np.asarray(dailyTimeWithData)
# dailyAverageWithData = np.asarray(dailyAverageWithData)
# dailyStdWithData = np.asarray(dailyStdWithData)
tidalAverage = np.nan * np.ones((len(highTideTimes),len(lidar_xFRF)))
tidalStd = np.nan * np.ones((len(highTideTimes),len(lidar_xFRF)))
tidalAverageWithData = []
tidalStdWithData = []
tidalTimeWithData = []
tidalTimeUTCWithData = []
tidalTime = []
tidalTimeUTC = []
for qq in range(len(highTideTimes)-1):
# if np.remainder(qq,100):
print('done with {} of {}: {}'.format(qq,len(highTideTimes),highTideTimes[qq]))
# first step - do we have cusps present?
indexCusps = np.where((np.asarray(cuspsTimes) >= np.asarray(highTideTimes)[qq]) & (np.asarray(cuspsTimes) <= np.asarray(highTideTimes)[qq+1]))
if len(indexCusps[0]) > 0:
print('we found a cusp')
inder = np.where((np.asarray(alongshoreAverageTime) >= np.asarray(highTideTimes)[qq]) & (np.asarray(alongshoreAverageTime) <= np.asarray(highTideTimes)[qq+1]))
profsOfInterest = alongshoreAverage[inder[0],:]
m, n = np.shape(profsOfInterest)
for pp in range(m):
singleProfOfInterest = profsOfInterest[pp, :]
nanIndex = np.where(np.isnan(singleProfOfInterest))
closeNans = np.where(nanIndex[0] > 10)
profsOfInterest[pp, nanIndex[0][closeNans[0][0]]:] = np.nan * profsOfInterest[pp,
nanIndex[0][closeNans[0][0]]:]
nonNanIndices = ~np.isnan(profsOfInterest)
goodDataNumbers = np.sum(nonNanIndices, axis=0)
goodDataInds = np.where(goodDataNumbers < 1)
profileOfInterestMean = np.nanmean(alongshoreAverage[inder[0], :], axis=0)
profileOfInterestStd = np.nanstd(alongshoreAverage[inder[0], :], axis=0)
profileOfInterestMean[goodDataInds] = profileOfInterestMean[goodDataInds] * np.nan
profileOfInterestStd[goodDataInds] = profileOfInterestStd[goodDataInds] * np.nan
UNDEF = np.nan
interpAlongMean = np.interp(lidar_xFRF, lidar_xFRFAlongshore, profileOfInterestMean, left=UNDEF)
interpAlongStd = np.interp(lidar_xFRF, lidar_xFRFAlongshore, profileOfInterestStd, left=UNDEF)
tidalAverage[qq, :] = interpAlongMean
tidalStd[qq, :] = interpAlongStd
tidalAverageWithData.append(interpAlongMean)
tidalStdWithData.append(interpAlongStd)
tidalTimeWithData.append(highTideTimes[qq])
tidalTimeUTCWithData.append(highTideUTCtime[qq])
else:
inder = np.where((np.asarray(dts) >= np.asarray(highTideTimes)[qq]) & (np.asarray(dts) <= np.asarray(highTideTimes)[qq+1]))
if len(inder[0])>0:
profsOfInterest = lidarProfiles[inder[0],:]
m, n = np.shape(profsOfInterest)
for pp in range(m):
singleProfOfInterest = profsOfInterest[pp,:]
nanIndex = np.where(np.isnan(singleProfOfInterest))
closeNans = np.where(nanIndex[0]>100)
profsOfInterest[pp,nanIndex[0][closeNans[0][0]]:] = np.nan*profsOfInterest[pp,nanIndex[0][closeNans[0][0]]:]
nonNanIndices = ~np.isnan(profsOfInterest)
goodDataNumbers = np.sum(nonNanIndices, axis=0)
goodDataInds = np.where(goodDataNumbers < 2)
profileOfInterestMean = np.nanmean(lidarProfiles[inder[0],:],axis=0)
profileOfInterestStd = np.nanstd(lidarProfiles[inder[0],:],axis=0)
profileOfInterestMean[goodDataInds] = profileOfInterestMean[goodDataInds]*np.nan
profileOfInterestStd[goodDataInds] = profileOfInterestStd[goodDataInds]*np.nan
tidalAverage[qq,:] = profileOfInterestMean
tidalStd[qq,:] = profileOfInterestStd
tidalAverageWithData.append(profileOfInterestMean)
tidalStdWithData.append(profileOfInterestStd)
tidalTimeWithData.append(highTideTimes[qq])
tidalTimeUTCWithData.append(highTideUTCtime[qq])
tidalTimeWithData = np.asarray(tidalTimeWithData)
tidalAverageWithData = np.asarray(tidalAverageWithData)
tidalStdWithData = np.asarray(tidalStdWithData)
tidalTimeUTCWithData = np.asarray(tidalTimeUTCWithData)
cont_elev2 = np.arange(-1.,1.00,0.1) # <<< MUST BE POSITIVELY INCREASING
cont_Tidal, cmean_Tidal, cstd_Tidal = create_contours(tidalAverageWithData,tidalTimeUTCWithData,lidar_xFRF,cont_elev2)
#
# # # plt.figure()
# # # plt.pcolor(dayTime,lidar_xFRF,dailyAverage.T)
plt.figure()
plt.pcolor(highTideTimes,lidar_xFRF,tidalAverage.T)
plt.ylabel('xFRF (m)')
plt.title('Tidal Average Profile densities')
plt.ylim([50,170])
# plt.figure()
# plt.plot(dts,cont_ts[-2,:])
howManyObs = []
# howManyDays = []
howManyTidal= []
for qq in range(len(lidar_xFRF)):
finder = np.where(np.isnan(elev_input[:,qq]))
howManyObs.append(len(finder[0]))
# finder2 = np.where(np.isnan(dailyAverage[:,qq]))
# howManyDays.append(len(finder2[0]))
finder3 = np.where(np.isnan(tidalAverage[:,qq]))
howManyTidal.append(len(finder3[0]))
numOfObs = np.abs(np.asarray(howManyObs)-np.nanmax(np.asarray(howManyObs)))
# numOfDays = np.abs(np.asarray(howManyDays)-np.nanmax(np.asarray(howManyDays)))
numOfTidal = np.abs(np.asarray(howManyTidal)-np.nanmax(np.asarray(howManyTidal)))
# plt.figure()
# p1 = plt.subplot2grid((1,2),(0,0))
# # p2 = plt.subplot2grid((1,2),(0,1))
# p3 = plt.subplot2grid((1,2),(0,1))
# p1.plot(lidar_xFRF,numOfObs)
# # p2.plot(lidar_xFRF,numOfDays)
# p3.plot(lidar_xFRF,numOfTidal)
# p1.set_xlabel('xFRF (m)')
# # p2.set_xlabel('xFRF (m)')
# p3.set_xlabel('xFRF (m)')
# p1.set_ylabel('# of Profiles with data')
# # p2.set_ylabel('# of Days with data')
# p3.set_ylabel('# of Tidal Windows')
# p1.plot([100,100],[-10,50000],'--',color='k')
# # p2.plot([100,100],[-10,2500],'--',color='k')
# p3.plot([100,100],[-10,4200],'--',color='k')
# p1.set_ylim([0,50000])
# # p2.set_ylim([0,2300])
# p3.set_ylim([0,4200])
# p1.set_title('All Observations')
# # p2.set_title('Daily Averaged Profiles')
# p3.set_title('Tidal Averaged Windows')
# asdfg
# d1 = datetime(2017,1,1,0,0,0)
# d2 = datetime(2018,1,1,0,0,0)
# dt = 3600. #seconds has to be a float and not an integer
# profile_num = 960
# dx = 1
# t = np.arange(d1, d2, timedelta(hours=1)).astype(datetime)
# dataloc = ("https://chldata.erdc.dren.mil/thredds/dodsC/frf/geomorphology/elevationTransects/survey/surveyTransects.ncml")
# ncfile = nc.Dataset(dataloc)
# bathy_date= ncfile["date"][:]
# bathy_y = ncfile["profileNumber"][:]
# ifind = np.where((bathy_date>=[tepoch[0]-45*24*60*60*1000]) & (bathy_date<=[tepoch[-1]+45*24*60*60*1000]) & (bathy_y == profile_num))
# bathy_elevation_all= ncfile["elevation"][:]
# bathy_x_all = ncfile["xFRF"][:]
# bathy_elevation= bathy_elevation_all[ifind]
# bathy_x = bathy_x_all[ifind]
# bathy_times = bathy_date[ifind]
# bathy_dates_unique = np.unique(bathy_times)
# # INTERPOLATE BATHY DATA
# offshore_x = 900
# xinterp = np.arange(75, offshore_x + 1, 1)
# zInterpSurvey = np.zeros([len(bathy_dates_unique), len(xinterp)]) * np.nan
# for i in range(len(bathy_dates_unique)):
# ifind_data = np.where((bathy_times == bathy_dates_unique[i]))
# if np.size(ifind_data) > 1:
# z_data_temp = np.array(bathy_elevation[ifind_data])
# x_data_temp = np.array(bathy_x[ifind_data])
# isort = np.argsort(x_data_temp)
# zInterp = interpolate_with_max_gap(x_data_temp[isort], z_data_temp[isort], xinterp, max_gap=10,
# orig_x_is_sorted=False, target_x_is_sorted=False)
# zInterpSurvey[i, :] = zInterp
# zInterpAll = np.zeros([np.size(t), np.size(xinterp)]) * np.nan
#
# for ix in range(len(xinterp)):
# tempz = zInterpSurvey[:,ix]
# inonan = np.where(np.isnan(tempz) == False)
# if np.size(inonan)>2:
# zInterpTemp = np.interp(tepoch, np.array(bathy_dates_unique[inonan]), np.array(tempz[inonan]))
# zInterpAll[:,ix] = zInterpTemp
# c = 1
# for hh in range(150):
# tempProfileBefore = tidalAverage[c-1,:]
# tempProfile = tidalAverage[c,:]
# tempProfileAfter = tidalAverage[c+1,:]
# tempNanInds = np.where(np.isnan(tempProfile))
#
# plt.figure()
# plt.plot(lidar_xFRF,tempProfileBefore)
# plt.plot(lidar_xFRF,tempProfile,color='k',linewidth=2)
# plt.plot(lidar_xFRF,tempProfileAfter)
# from loess.loess_2d import loess_2d
## LETS EXTEND OUR LIDAR PROFILES WITH DATA WE HAVE FROM EITHER SIDE IN TIME
# AND ALSO CLEAN UP THE PROFILES THAT HAVE SOME WEIRD END EFFECTS
from loess.loess_1d import loess_1d
#
# xIn,yIn = np.meshgrid(np.asarray(highTideUTCtime)[35:45], lidar_xFRF[0:700])
# xOut = np.copy(xIn.flatten())
# yOut = np.copy(yIn.flatten())
# zIn = tidalAverage[35:45,0:700].T
# zIn = zIn.flatten()
# xIn = xIn.flatten()
# yIn = yIn.flatten()
# indNan = np.where(np.isnan(zIn))
# xIn = np.delete(xIn,indNan)
# yIn = np.delete(yIn,indNan)
# zIn = np.delete(zIn,indNan)
#
# zout, wout = loess_2d(xIn,yIn,zIn, xnew=xOut, ynew=yOut, degree=2, frac=0.1,npoints=None, rescale=False, sigz=None)
#
# plt.figure()
# p1 = plt.subplot2grid((2,2),(0,0))
# p1.pcolor(np.asarray(highTideTimes)[35:45],lidar_xFRF,tidalAverage[35:45].T,vmax=6,vmin=-1)
# p1.set_ylabel('xFRF (m)')
# p1.set_ylim([40,110])
# p1.set_title('tidally-averaged profiles')
# p1.tick_params(axis='x', labelrotation=45)
# p2 = plt.subplot2grid((2,2),(0,1))
# p2.pcolor(np.asarray(highTideTimes)[35:46],lidar_xFRF[0:701],zout.reshape((700,10)),vmax=6,vmin=-1)
# p2.set_ylabel('xFRF (m)')
# p2.set_ylim([40,110])
# p2.set_title('loess 2d profiles')
# p2.tick_params(axis='x', labelrotation=45)
# p3 = plt.subplot2grid((2,2),(1,0))
# p3.plot(lidar_xFRF,tidalAverage[40])
# p3.set_xlim([40,110])
# p4 = plt.subplot2grid((2,2),(1,1))
# p4.plot(lidar_xFRF[0:700],zout.reshape((700,10))[:,5])
# p4.set_xlim([40,110])
geomorphdir = '/volumes/anderson/FRF_Data/surveys/'
files = os.listdir(geomorphdir)
files.sort()
subset = files.copy()
subset = subset[1039:]
files_path = [os.path.abspath(geomorphdir) for x in os.listdir(geomorphdir)]
def getBathy(file, lower, upper):
bathy = Dataset(file)
xs_bathy = bathy.variables['xFRF'][:]
ys_bathy = bathy.variables['yFRF'][:]
zs_bathy = bathy.variables['elevation'][:]
ts_bathy = bathy.variables['time'][:]
pr_bathy = bathy.variables['profileNumber'][:]
zs_bathy = np.ma.masked_where((pr_bathy > upper), zs_bathy)
ys_bathy = np.ma.masked_where((pr_bathy > upper), ys_bathy)
xs_bathy = np.ma.masked_where((pr_bathy > upper), xs_bathy)
pr_bathy = np.ma.masked_where((pr_bathy > upper), pr_bathy)
ts_bathy = np.ma.masked_where((pr_bathy > upper), ts_bathy)
zs_bathy = np.ma.masked_where((pr_bathy < lower), zs_bathy)
ys_bathy = np.ma.masked_where((pr_bathy < lower), ys_bathy)
xs_bathy = np.ma.masked_where((pr_bathy < lower), xs_bathy)
pr_bathy = np.ma.masked_where((pr_bathy < lower), pr_bathy)
ts_bathy = np.ma.masked_where((pr_bathy < lower), ts_bathy)
output = dict()
output['x'] = xs_bathy
output['y'] = ys_bathy
output['z'] = zs_bathy
output['pr'] = pr_bathy
output['t'] = ts_bathy
return output
extendedTidalAverages = np.copy(tidalAverage)
# extendedTidalAveragesWithData = np.copy(tidalAverageWithData)
# extendedTidalAverages = np.copy(tidalAverage)
# extendedTidalAveragesWithData = np.copy(tidalAverageWithData)
# smoothedTidalAverages = []
bathyX = np.nan*np.copy(tidalAverage)
bathyZ = np.nan*np.copy(tidalAverage)
whichTransect = np.nan*np.ones((len(tidalAverage),))
for i in range(len(subset)):
file_params = subset[i].split('_')
## ### Southern Lines
data1 = getBathy(os.path.join(geomorphdir, subset[i]), lower=900, upper=920)
data2 = getBathy(os.path.join(geomorphdir, subset[i]), lower=920, upper=940)
data3 = getBathy(os.path.join(geomorphdir, subset[i]), lower=950, upper=955)
data4 = getBathy(os.path.join(geomorphdir, subset[i]), lower=956, upper=965)
data5 = getBathy(os.path.join(geomorphdir, subset[i]), lower=1000, upper=1015)
data6 = getBathy(os.path.join(geomorphdir, subset[i]), lower=860, upper=875)
temp = subset[i].split('_')
if temp[1] == 'geomorphology':
temp2 = temp[-1].split('.')
surveydate = dt.datetime.strptime(temp2[0], '%Y%m%d')
else:
surveydate = dt.datetime.strptime(temp[1], '%Y%m%d')
print('working on {}'.format(surveydate))
elevs = data1['z']
cross = data1['x']
crossind = np.argsort(data1['x'])
crossS = cross[crossind]
elevsS = elevs[crossind]
elevs2 = data2['z']
cross2 = data2['x']
crossind2 = np.argsort(data2['x'])
crossS2 = cross2[crossind2]
elevsS2 = elevs2[crossind2]
elevs3 = data3['z']
cross3 = data3['x']
crossind3 = np.argsort(data3['x'])
crossS3 = cross3[crossind3]
elevsS3 = elevs3[crossind3]
elevs4 = data4['z']
cross4 = data4['x']
crossind4 = np.argsort(data4['x'])
crossS4 = cross4[crossind4]
elevsS4 = elevs4[crossind4]
elevs5 = data5['z']
cross5 = data5['x']
crossind5 = np.argsort(data5['x'])
crossS5 = cross5[crossind5]
elevsS5 = elevs5[crossind5]
elevs6 = data6['z']
cross6 = data6['x']
crossind6 = np.argsort(data6['x'])
crossS6 = cross5[crossind6]
elevsS6 = elevs5[crossind6]
xSub = np.ma.MaskedArray.filled(crossS, np.nan)
zSub = np.ma.MaskedArray.filled(elevsS, np.nan)
xSub2 = np.ma.MaskedArray.filled(crossS2, np.nan)
zSub2 = np.ma.MaskedArray.filled(elevsS2, np.nan)
xSub3 = np.ma.MaskedArray.filled(crossS3, np.nan)
zSub3 = np.ma.MaskedArray.filled(elevsS3, np.nan)
xSub4 = np.ma.MaskedArray.filled(crossS4, np.nan)
zSub4 = np.ma.MaskedArray.filled(elevsS4, np.nan)
xSub5 = np.ma.MaskedArray.filled(crossS5, np.nan)
zSub5 = np.ma.MaskedArray.filled(elevsS5, np.nan)
xSub6 = np.ma.MaskedArray.filled(crossS6, np.nan)
zSub6 = np.ma.MaskedArray.filled(elevsS6, np.nan)
realValues = ~np.isnan(xSub)
xSubNew = xSub[~np.isnan(xSub)]
zSubNew = zSub[~np.isnan(xSub)]
realValues2 = ~np.isnan(xSub2)
xSubNew2 = xSub2[~np.isnan(xSub2)]
zSubNew2 = zSub2[~np.isnan(xSub2)]
realValues3 = ~np.isnan(xSub3)
xSubNew3 = xSub3[~np.isnan(xSub3)]
zSubNew3 = zSub3[~np.isnan(xSub3)]
realValues4 = ~np.isnan(xSub4)
xSubNew4 = xSub4[~np.isnan(xSub4)]
zSubNew4 = zSub4[~np.isnan(xSub4)]
realValues5 = ~np.isnan(xSub5)
xSubNew5 = xSub5[~np.isnan(xSub5)]
zSubNew5 = zSub5[~np.isnan(xSub5)]
realValues6 = ~np.isnan(xSub6)
xSubNew6 = xSub6[~np.isnan(xSub6)]
zSubNew6 = zSub6[~np.isnan(xSub6)]
temp = np.hstack((np.hstack((np.hstack((realValues,realValues2)),realValues3)),realValues4))
tempRealValues = np.hstack((temp,realValues5))
tempRealValues2 = np.hstack((tempRealValues,realValues6))
tempXSub = np.hstack((np.hstack((np.hstack((xSubNew,xSubNew2)),xSubNew3)),xSubNew4))
tempXSubNew = np.hstack((tempXSub,xSubNew5))
tempXSubNew2 = np.hstack((tempXSubNew,xSubNew6))
## lets find the closest lidar profile
surveydateUTC = surveydate.timestamp()
# timeInd = np.abs(np.asarray(tidalTimeUTCWithData)-surveydateUTC)
timeInd = np.abs(np.asarray(highTideUTCtime)-surveydateUTC)
profInd = np.where((np.min(timeInd) == timeInd))
lidarProf = extendedTidalAverages[profInd[0][0],:]
# lidarProf = tidalAverageWithData[profInd[0][0],:]
lidarProfCopy = np.copy(lidarProf)
lidarProfCopy = np.delete(lidarProfCopy,np.where(np.isnan(lidarProfCopy)))
if len(lidarProfCopy) == 0:
print('no profile in this tidally averaged time window')
timeInd = np.abs(np.asarray(highTideUTCtime) - surveydateUTC)
profInd = np.where((np.min(timeInd) == timeInd))
if len(zSubNew4) > 2:
UNDEF = np.nan
interpExtendedLidarZ = np.interp(lidar_xFRF, xSubNew4, zSubNew4, left=UNDEF)
extendedTidalAverages[profInd[0][0] - 1, :] = interpExtendedLidarZ
extendedTidalAverages[profInd[0][0] + 1, :] = interpExtendedLidarZ
extendedTidalAverages[profInd[0][0], :] = interpExtendedLidarZ
# extendedTidalAveragesWithData[profInd[0][0], :] = transect1Avg
# extendedTidalAverages[matchingFullTidalInd[0][0], interTidalLidarInd[0][0]:] = interpExtendedLidarZ
# extendedTidalAveragesWithData[profInd[0][0], interTidalLidarInd[0][0]:] = interpExtendedLidarZ
# bathyX.append(chosenX)
bathyZ[profInd[0][0], :] = interpExtendedLidarZ
whichTransect[qq] = 960
print('but we have added a profile up to {} at profInd = {} and time = {}'.format(np.nanmax(zSubNew4),profInd[0][0],surveydate))
else:
interTidalLidarInd = np.where((lidarProf<1.5) & (lidarProf>-1.5))
interTidalLidarZ = lidarProf[interTidalLidarInd]
interTidalLidarX = lidar_xFRF[interTidalLidarInd]
# print('we are trying to fuse to {}'.format(tidalTimeWithData[profInd]))
print('we are trying to fuse to {}'.format(highTideTimes[profInd[0][0]]))
# lidarZextrapolated
# matchingFullTidalInd = np.where(tidalTimeWithData[profInd] == highTideTimes)
matchingFullTidalInd = profInd #np.where(tidalTimeWithData[profInd] == highTideTimes)
if len(interTidalLidarZ) < 2:
print('needing to look higher on the profile to find lidar data')
interTidalLidarInd = np.where((lidarProf < 3.5) & (lidarProf > -1.5))
interTidalLidarZ = lidarProf[interTidalLidarInd]
interTidalLidarX = lidar_xFRF[interTidalLidarInd]
if len(interTidalLidarZ) < 2:
print('We should probably just skip this one....')
else:
if len(zSubNew) > 2:
zSub1Intertp = np.interp(interTidalLidarX,xSubNew,zSubNew)
r1 = np.corrcoef(interTidalLidarZ, zSub1Intertp)[0, 1]
rmse1 = rmse(interTidalLidarZ, zSub1Intertp)
else:
r1 = 0
rmse1 = 100
if len(zSubNew2) > 2:
zSub2Intertp = np.interp(interTidalLidarX,xSubNew2,zSubNew2)
r2 = np.corrcoef(interTidalLidarZ, zSub2Intertp)[0, 1]
rmse2 = rmse(interTidalLidarZ, zSub2Intertp)
else:
r2 = 0
rmse2 = 100
if len(zSubNew3) > 2:
zSub3Intertp = np.interp(interTidalLidarX,xSubNew3,zSubNew3)
r3 = np.corrcoef(interTidalLidarZ, zSub3Intertp)[0, 1]
rmse3 = rmse(interTidalLidarZ, zSub3Intertp)
else:
r3 = 0
rmse3 = 100
if len(zSubNew4) > 2:
zSub4Intertp = np.interp(interTidalLidarX,xSubNew4,zSubNew4)
r4 = np.corrcoef(interTidalLidarZ, zSub4Intertp)[0, 1]
rmse4 = rmse(interTidalLidarZ, zSub4Intertp)
else:
r4 = 0
rmse4 = 100
if len(zSubNew5) > 2:
zSub5Intertp = np.interp(interTidalLidarX,xSubNew5,zSubNew5)
r5 = np.corrcoef(interTidalLidarZ, zSub5Intertp)[0,1]
rmse5 = rmse(interTidalLidarZ, zSub5Intertp)
else:
r5 = 0
rmse5 = 100
if len(zSubNew6) > 2:
zSub6Intertp = np.interp(interTidalLidarX,xSubNew6,zSubNew6)
r6 = np.corrcoef(interTidalLidarZ, zSub6Intertp)[0,1]
rmse6 = rmse(interTidalLidarZ, zSub6Intertp)
else:
r6 = 0
rmse6 = 100
allRMSE = [rmse1,rmse2,rmse3,rmse4,rmse5,rmse6]
bestCaseInd = np.argmin([rmse1,rmse2,rmse3,rmse4,rmse5,rmse6])
interpBathyOnToX = lidar_xFRF[interTidalLidarInd[0][0]:]
if bestCaseInd == 0:
interpExtendedLidarZ = np.interp(interpBathyOnToX,xSubNew,zSubNew)
chosenX = xSubNew
chosenZ = zSubNew
lineNumber= 914
elif bestCaseInd == 1:
interpExtendedLidarZ = np.interp(interpBathyOnToX,xSubNew2,zSubNew2)
chosenX = xSubNew2
chosenZ = zSubNew2
lineNumber= 927
elif bestCaseInd == 2:
interpExtendedLidarZ = np.interp(interpBathyOnToX,xSubNew3,zSubNew3)
chosenX = xSubNew3
chosenZ = zSubNew3
lineNumber= 951
elif bestCaseInd == 3:
interpExtendedLidarZ = np.interp(interpBathyOnToX,xSubNew4,zSubNew4)