-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
1685 lines (1204 loc) · 50.8 KB
/
utils.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
# rotarySpectrum - Gonela, Emery & Thompson methods to get rotary spectrum
def rotarySpectrum(x, y, NFFT, Fs, noverlap=0):
from matplotlib.mlab import window_hanning
import numpy as np
from scipy.signal import detrend
if len(x)<=NFFT:
NFFT = int(2**np.ceil(np.log2(len(x))))
n = len(x)
x = np.resize(x, (NFFT,))
x[n:] = 0
y = np.resize(y, (NFFT,))
y[n:] = 0
windowVals = window_hanning(np.ones((NFFT,),x.dtype))
step = NFFT - noverlap
ind = range(0,len(x)-NFFT+1,step)
n = len(ind)
numFreqs = int(NFFT//2 +1)
Pxx = np.zeros((numFreqs,n), float)
Pyy = np.zeros((numFreqs,n), float)
Pxy = np.zeros((numFreqs,n), complex)
Qxy = np.zeros((numFreqs,n), complex)
Cxy = np.zeros((numFreqs,n), complex)
for i in range(n):
thisX = x[ind[i]:ind[i]+NFFT]
#thisX = windowVals*detrend(thisX)
thisX = detrend(thisX)
fx = np.absolute(np.fft.fft(thisX))**2 # density spectrum
fxx = np.fft.fft(thisX) # amplitude spectrum
Pxx[:,i] = fx[:numFreqs]
thisY = y[ind[i]:ind[i]+NFFT]
#thisY = windowVals*detrend(thisY)
thisY = detrend(thisY)
fy = np.absolute(np.fft.fft(thisY))**2
fyy = np.fft.fft(thisY)
Pyy[:,i] = fy[:numFreqs]
Pxy[:,i] = fyy[:numFreqs]*np.conjugate(fxx[:numFreqs]) # the cross-spectrum is the product between the amplitude spectra
Qxy[:,i] = -np.imag(Pxy[:,i])
Cxy[:,i] = np.real(Pxy[:,i])
if n>1:
Pxx = np.nanmean(Pxx,1)
Pyy = np.nanmean(Pyy,1)
Pxy = np.nanmean(Pxy,1)
Qxy = np.nanmean(Qxy,1)
Cxy = np.nanmean(Cxy,1)
Pxx = np.divide(Pxx, np.linalg.norm(windowVals)**2) #,dtype='float')
Pyy = np.divide(Pyy, np.linalg.norm(windowVals)**2) #,dtype='float')
Pxy = np.divide(Pxy, np.linalg.norm(windowVals)**2) #,dtype='float')
Qxy = np.divide(Qxy, np.linalg.norm(windowVals)**2) #,dtype='float')
Cxy = np.divide(Cxy, np.linalg.norm(windowVals)**2) #,dtype='float')
# rotary spectra (clockwise - counterclockwise)
Rcw = (Pxx + Pyy - 2 * Qxy) / 8.
Rccw = (Pxx + Pyy + 2 * Qxy) / 8.
Rtot = (Pxx + Pyy) / 4.
# rotary coefficient
Cr = (Rcw - Rccw) / Rtot # - Gonella cw < 0 & ccw > 0 & unidirectional flow=0
#Cr = (Rcw - Rccw) / (Rcw + Rccw) # - Emery & Thomson: cw > 0 & ccw < 0 & unidirectional flow=0
# orientation of major axis
R2 = (1 / 64.)*((Pxx + Pyy)**2 - 4*(Pxx*Pyy - Pxy**2))
# mean orientation and stability
E = R2 / (Rcw*Rccw) # stability
Phi = 0.5*np.arctan((np.pi / 180.)*(2*Pxy / (Pxx - Pyy)))
# coherence
Coh = (Pxy - 1j*Qxy) / np.sqrt(Pxx*Pyy)
freqs = np.divide(Fs,NFFT,dtype=float)*np.arange(0,numFreqs)
freqs = freqs.reshape( freqs.shape + (1,) ) # adding 2nd dimension
return Pxx, Pyy, Pxy, Qxy, Cxy, Rcw, Rccw, Rtot, Cr, R2, E, Phi, Coh, freqs
# calcTurb - Shaw & Trawbridge method to split wave-induced velocities
def calcTurb(u1,v1,w1,u2,v2,w2,Tp,Fs):
import numpy as np
M = len(u1)
N = np.round( ( Tp )*Fs )
if not np.mod(N,2):
N = N + 1
A = np.empty( ( int(M) , int(3*N) ) )
U1 = np.array((u1,v1,w1)).T
fac = (N - 1) / 2
for row in np.arange(0,M):
col = np.linspace( row - fac, row + fac, N ).astype(int)
col[col<1] = 1
col[col>=M] = M - 1
U = np.concatenate((u2[col], v2[col], w2[col]))
A[row, : ] = U
h_hat = np.dot( np.dot( np.linalg.inv( np.dot( A.T,A ) ), A.T ), U1 )
U1_hat = np.dot(A, h_hat)
dU1_hat = U1 - U1_hat
#uwCov = np.cov( dU1_hat[:,0], w1 )
#vwCov = np.cov( dU1_hat[:,1], w1 )
uwCov = np.cov( dU1_hat[:,0], w1 )
vwCov = np.cov( dU1_hat[:,1], w1 )
return U1_hat, dU1_hat, uwCov, vwCov, h_hat
def shearVelMadsen(ubr,omegar,ucr,zr,phiwc,zin):
'''
code for wave friction factor based on Madsen (1994)
INPUTS:
ubr: wave orbital velocity
omegar: angular wave frequency
ucr: current velocity at heigth zr
zr: reference heigth for current velocity
phiwc: angle between currents and waves at zr
zin: bottom roughness height
OUTPUTS:
ustarc: current friction velocity
ustarw: wave maximum friction velocity
ustarr: wave-current combined friction velocity
fwc: wave friction factor
zoa: apparent bottom roughness
Author: Rafael
Python version by: Saulo Meirelles
'''
import numpy as np
MAXIT = 20
vkappa = 0.41
fwc = 0.4
ustarc = np.empty((1,1))
ustarw = np.empty((1,1))
ustarr = np.empty((1,1))
if np.abs(ubr) <= 0.01 and np.abs(ucr) <= 0.01:
ustarc = 0.000001
ustarw = 0.000001
ustarr = 0.000001
elif np.abs(ubr) <= 0.01:
ustarc = ucr*vkappa/np.log(zr/zin)
ustarw = 0.000001
ustarr = ustarc
cosphiwc = np.abs(np.cos(phiwc))
kN = 30*zin
rmu = np.empty((MAXIT,1))
Cmu = np.empty((MAXIT,1))
fwci = np.empty((MAXIT,1))
ustarw2 = np.empty((MAXIT,1))
ustarr2 = np.empty((MAXIT,1))
ustarci = np.empty((MAXIT,1))
dwc = np.empty((MAXIT,1))
rmu[0], Cmu[0] = 0., 1.
cukom = Cmu[0]*ubr/kN/omegar
if 0.2 < cukom <= 100.:
fwci[0] = Cmu[0]*np.exp(7.02*cukom**(-0.078)-8.82)
elif 100. < cukom <= 10000.:
fwci[0] = Cmu[0]*np.exp(5.61*cukom**(-0.109)-7.3)
elif cukom > 10000.:
fwci[0] = Cmu[0]*np.exp(5.61*10000**(-0.109)-7.3)
else:
fwci[0] = Cmu[0]*0.43
ustarw2[0] = 0.5*fwci[0]*ubr**2
ustarr2[0] = Cmu[0]*ustarw2[0]
ustarr = np.sqrt( ustarr2[0] )
if cukom >= 8.0:
dwc[0] = 2.0*vkappa*ustarr/omegar
else:
dwc[0] = kN
lnzr = np.log( zr / dwc[0] )
lndw = np.log( dwc[0] / zin )
lnln = lnzr / lndw
bigsqr = (-1.0) + np.sqrt( 1.0 + ( ( 4.0*vkappa*lndw ) / ( lnzr**2) )*(ucr / ustarr) )
ustarci[0] = 0.5*ustarr*lnln*bigsqr
i = 0
diff = 1
while i < MAXIT & diff > 0.000005:
i += 1
rmu[i] = ustarci[i-1]**2 / ustarw2[i-1]
Cmu[i] = np.sqrt( 1+2*rmu[i]*cosphiwc+rmu[i]**2 )
cukom = Cmu[i]*ubr / ( kN*omegar )
if 0.2 < cukom <= 100:
fwci[i] = Cmu[i]*np.exp(7.02*cukom**(-0.078)-8.82)
elif 100 < cukom <= 10000:
fwci[i] = Cmu[i]*np.exp(5.61*cukom**(-0.109)-7.3)
elif cukom > 10000:
fwci[i] = Cmu[i]*np.exp(5.61*10000**(-0.109)-7.3)
else:
fwci[i] = Cmu[i]*0.43
ustarw2[i] = 0.5*fwci[i]*ubr**2
ustarr2[i] = Cmu[i]*ustarw2[i]
ustarr = np.sqrt( ustarr2[i] )
if cukom >= 8.0:
dwc[i] = 2.0*vkappa*ustarr/omegar
else:
dwc[i] = kN
lnzr = np.log( zr / dwc[i] )
lndw = np.log( dwc[i] / zin )
lnln = lnzr / lndw
bigsqr = (-1.0) + np.sqrt( 1.0+ ( ( 4.0*vkappa*lndw ) / ( lnzr**2) )*ucr / ustarr )
ustarci[i] = 0.5*ustarr*lnln*bigsqr
diff = np.abs( ( fwci[i]-fwci[i-1] ) / fwci[i] )
ustarw = np.sqrt( ustarw2[i] )
ustarc = ustarci[i]
ustarr = np.sqrt( ustarr2[i] )
zoa = np.exp( np.log( dwc[i] )-( ustarc / ustarr )*np.log(dwc[i] / zin ) )
if 'zoa' not in locals():
zoa = np.nan
elif np.isinf(zoa) == True:
zoa = np.nan
fwc = fwci[i]
#print ustarc, ustarw, ustarr, fwc, zoa
return ustarc, ustarw, ustarr, fwc, zoa
def read_ascii_adcp_FromVisea(fname):
import datetime
from pandas import DataFrame, concat
from collections import OrderedDict
import numpy as np
#fname = 'MP14_ADCP_141017028t.000'
f = open(fname, 'r')
fd = f.read().split('\n')
main_header = dict()
ens_header = dict()
ens = dict()
ens_data = DataFrame()
kw = dict(columns=('depth',
'vel_mag',
'vel_dir',
'east_vel','north_vel','up_vel',
'error_vel',
'abs1','abs2','abs3','abs4',
'perc_good','discharge','longitude','latitude'))
main_header['transect_ID'] = fname[-8:-4]
try:
# main header
main_header['comment1'] = fd.pop(0)
# main main_header
main_header['comment2'] = fd.pop(0)
# main main_header
l = fd.pop(0).rstrip('\n').split()
main_header['bin_size_cm'] = int(l[0])
main_header['blank_cm'] = int(l[1])
main_header['first_bin_cm'] = int(l[2])
main_header['cells_number'] = int(l[3])
main_header['ping_per_ens'] = int(l[4])
main_header['time_per_ens'] = int(l[5])
main_header['mode'] = int(l[6])
cc = 0
while True:
# ensemble header line 01
l = fd.pop(0).rstrip('\n').split()
time = [int(i) for i in l[0:7]]
time[0] += 2000 # in the source, they start counting in year 2000
time[6] *= 10000 # 1/100 seconds to microseconds
ens_header.setdefault('ens_time',[]).append(datetime.datetime(time[0], time[1], time[2], time[3], time[4], time[5], time[6]))
ens_header.setdefault('ens_number',[]).append(int(l[7]))
ens_header.setdefault('ens_per_segment',[]).append(l[8])
ens_header.setdefault('pitch',[]).append(l[9])
ens_header.setdefault('roll',[]).append(l[10])
ens_header.setdefault('heading_corrected',[]).append(l[11])
ens_header.setdefault('temp_adcp',[]).append(l[12])
# ensemble header line 02
l = fd.pop(0).rstrip('\n').split()
ens_header.setdefault('east_vel_bt',[]).append(float(l[0])/100)
ens_header.setdefault('north_vel_bt',[]).append(float(l[1])/100)
ens_header.setdefault('up_vel_bt',[]).append(float(l[2])/100)
ens_header.setdefault('error_vel_bt',[]).append(float(l[3])/100)
ens_header.setdefault('east_vel_gga',[]).append(float(l[4])/100)
ens_header.setdefault('north_vel_gga',[]).append(float(l[5])/100)
ens_header.setdefault('up_vel_gga',[]).append(float(l[6])/100)
ens_header.setdefault('error_vel_gga',[]).append(float(l[7])/100)
depth = [float(i) for i in l[8:12]]
ens_header.setdefault('depth_beam1',[]).append(depth[0])
ens_header.setdefault('depth_beam2',[]).append(depth[1])
ens_header.setdefault('depth_beam3',[]).append(depth[2])
ens_header.setdefault('depth_beam4',[]).append(depth[3])
ens_header.setdefault('depth_mean',[]).append(np.mean(depth))
# ensemble header line 03
l = fd.pop(0).rstrip('\n').split()
ens_header.setdefault('elapsed_distance',[]).append(float(l[0]))
ens_header.setdefault('elapsed_time',[]).append(float(l[1]))
ens_header.setdefault('distance_north',[]).append(float(l[2]))
ens_header.setdefault('distance_south',[]).append(float(l[3]))
ens_header.setdefault('distance_good',[]).append(float(l[4]))
# ensemble header line 04
l = fd.pop(0).rstrip('\n').split()
ens_header.setdefault('latitude',[]).append(float(l[0]))
ens_header.setdefault('longitude',[]).append(float(l[1]))
ens_header.setdefault('doNot_know1',[]).append(float(l[2]))
ens_header.setdefault('doNot_know2',[]).append(float(l[3]))
ens_header.setdefault('doNot_know3',[]).append(float(l[4]))
# ensemble header line 05
l = fd.pop(0).rstrip('\n').split()
ens_header.setdefault('discharge_middle',[]).append(float(l[0]))
ens_header.setdefault('discharge_top',[]).append(float(l[1]))
ens_header.setdefault('discharge_bottom',[]).append(float(l[2]))
ens_header.setdefault('discharge_middle',[]).append(float(l[0]))
# ensemble header line 06
l = fd.pop(0).rstrip('\n').split()
ens_header.setdefault('number_beams_follow',[]).append(int(l[0]))
ens_header.setdefault('unit_meas',[]).append(str(l[1]))
ens_header.setdefault('vel_reference',[]).append(str(l[2]))
ens_header.setdefault('unit_abs',[]).append((l[3]))
data = []
geopos = [str(ens_header['longitude'][cc]),str(ens_header['latitude'][cc])]
for k in range(main_header['cells_number']):
l = fd.pop(0).rstrip('\n').split()
depth = l[0]
l.extend(geopos)
if len(l) == 15:
#if l[-3] == '2147483647':
#l = transpose(['-99999' for i in l])
l[0] = depth
data.append(map(float,l))
else:
l = np.transpose(['-32768' for i in range(15)])
l[0] = depth
data.append(map(float,l))
#data = data[0:-1] # workaround - somehow data is duplicating the last row
ens_dict = {ens_header['ens_number'][cc]: DataFrame(data,**kw)}
ens.update(ens_dict)
cc += 1
if len(fd) <= 1:
break
finally:
f.close()
OrderedDict(sorted(ens.items(), key=lambda t: t[0]))
#ens_data = concat(ens.values(),keys = ens.keys())
return ens, ens_header, main_header
def ReadVertsFM_MapFile_oldvr(NetNode_x, NetNode_y, NetElemNode, m='none'):
import numpy as np
cor_x = NetNode_x
cor_y = NetNode_y
poly = NetElemNode - 1 # 0-based Python indexes
idx = ~np.any(poly < 0., axis=1) # separetes trianges from quadangles
if m=='none':
verts1 = zip(cor_x[poly[idx,:]],
cor_y[poly[idx,:]]) # quadangles include all the 4 columns
verts2 = zip(cor_x[poly[~idx,:3]],
cor_y[poly[~idx,:3]]) # triangles get the first 3 columns, the last one is just a flag (large negative number)
else:
x1, y1 = m(cor_x[poly[idx,:]], cor_y[poly[idx,:]])
x2, y2 = m(cor_x[poly[~idx,:3]],cor_y[poly[~idx,:3]])
verts1 = zip(x1,y1)
verts2 = zip(x2,y2)
verts1 = np.swapaxes(verts1, 1, 2)
verts2 = np.swapaxes(verts2, 1, 2)
verts = list(verts1)+list(verts2)
return verts, idx
def ReadVertsFM_MapFile_newvr(ds, m='none'):
import numpy as np
cor_x = ds.NetNode_x.values
cor_y = ds.NetNode_y.values
idx = ~np.any( ds.NetElemNode.values.astype(int) < 0, axis=1 )
idxqua = (ds
.NetElemNode
.dropna('nNetElem')).values.astype(int) - 1 #~np.any(poly < 0., axis=1) # separetes trianges from quadangles
idxtri =(ds
.NetElemNode
.where(np.isnan(ds.NetElemNode.isel(nNetElemMaxNode=3))==True)
.dropna('nNetElem',how='all')
.dropna('nNetElemMaxNode',how='all')).values.astype(int) - 1
if m=='none':
verts1 = zip(cor_x[idxqua],
cor_y[idxqua]) # quadangles include all the 4 columns
verts2 = zip(cor_x[idxtri],
cor_y[idxtri]) # triangles get the first 3 columns, the last one is just a flag (large negative number)
else:
x1, y1 = m(cor_x[idxqua], cor_y[idxqua])
x2, y2 = m(cor_x[idxtri],cor_y[idxtri])
verts1 = zip(x1,y1)
verts2 = zip(x2,y2)
verts1 = np.swapaxes(verts1, 1, 2)
verts2 = np.swapaxes(verts2, 1, 2)
verts = list(verts1)+list(verts2)
return verts, idx
def rotation2D_velocities(u,v,angleDeg=42):
import numpy as np
RotAngle = np.deg2rad(angleDeg)
RotMatrix = np.array( [[ np.cos(RotAngle), -np.sin(RotAngle)] ,
[ np.sin(RotAngle), np.cos(RotAngle)]] )
u_vec = np.reshape(u, (1, np.size(u) ) )
v_vec = np.reshape(v, (1, np.size(v) ) )
VelMatrix = np.array( [u_vec[0][:] , v_vec[0][:]] )
VelRot = np.dot(RotMatrix,VelMatrix)
u_rot = VelRot[0,:]
v_rot = VelRot[1,:]
u_rot = np.reshape(u_rot, ( np.shape(u) ) )
v_rot = np.reshape(v_rot, ( np.shape(v) ) )
return u_rot, v_rot
def reject_outliers(data, m = 2.):
import numpy as np
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d/mdev if mdev else 0.
return s<m #data[s<m]
def swirl_strength(u,w,x,z, v=None):
'''
By Max Rademacher (Matlab)
'''
import numpy as np
from scipy import signal
convmatx = np.array([[0., 0., 0.],[1., 0., -1.],[0., 0., 0.]])
convmatz = np.array([[0., 1., 0.],[0., 0., 0.], [0., -1., 0.]])
dudz = signal.convolve2d(u,convmatz,mode='valid') / signal.convolve2d(z,convmatz,mode='valid')
if v:
dvdz = signal.convolve2d(v,convmatz,mode='valid') / signal.convolve2d(z,convmatz,mode='valid')
dudx = signal.convolve2d(u,convmatx,mode='valid') / signal.convolve2d(x,convmatx,mode='valid')
dwdz = signal.convolve2d(w,convmatz,mode='valid') / signal.convolve2d(z,convmatz,mode='valid')
dwdx = signal.convolve2d(w,convmatx,mode='valid') / signal.convolve2d(x,convmatx,mode='valid')
#curly = (dudz - dwdx)
curly = (dudz) # ignoring vertical vels
SW = np.empty(np.shape(dudx))
for i in range(np.shape(dudx)[0]):
for j in range(np.shape(dudx)[1]):
A = np.array( [ [dudx[i,j], dudz[i,j] ], [dwdx[i,j], dwdz[i,j] ] ] )
A[np.isnan(A)] = 0.
A[np.isinf(A)] = 0.
SR = (A + A.T)/2 #Strain rate tensor
OR = (A - A.T)/2 #Vorticity tensor
eigenvalues,_ = np.linalg.eig(A)
SW[i,j] = np.max(np.unique(np.abs(np.imag(eigenvalues))))
if v:
return SW, dudz, dudx, curly, SR, OR, dvdz
else:
return SW, dudz, dudx, curly, SR, OR
def get_radar_times(datadir):
'''
By Max Rademacher
'''
import gdal
import pyproj
import glob
import os
import numpy as np
import re
import datetime
from scipy import ndimage
imlist = glob.glob(os.path.join(datadir,'*.tif'))
datvec = []
for im in imlist:
path, filename = os.path.split(im)
tstr = re.findall('[0-9]{4}.*(?=UTC)', filename)[0]
datvec.append(datetime.datetime.strptime(tstr,'%Y-%m-%d %H.%M.%S'))
return datvec
def get_radar_tiff(datadir,t):
'''
By Max Rademacher
'''
import gdal
import pyproj
import glob
import os
import numpy as np
import re
import datetime
from scipy import ndimage
ds = gdal.Open(os.path.join(datadir,datetime.datetime.strftime(t,'%Y-%m-%d %H.%M.%S') + 'UTC.tif'))
band = ds.GetRasterBand(1)
img = band.ReadAsArray()
nrows, ncols = img.shape
x0, dx, dxdy, y0, dydx, dy = ds.GetGeoTransform()
x = np.arange(x0+dx/2,x0-dx/2+ncols*dx,dx)
y = np.arange(y0,y0+nrows*dy,dy)
X,Y = np.meshgrid(x,y)
v,u = img.shape
v = np.arange(v)
u = np.arange(u)
[u,v] = np.meshgrid(u,v)
uc = 511.5
vc = 511.5
r = 503
dst = np.sqrt((u-uc)**2+(v-vc)**2)
ind = dst > r
img[ind] = 255
img = img[9:1015,9:1015]
X = X[9:1015,9:1015]
Y = Y[9:1015,9:1015]
coorin=pyproj.Proj("+init=EPSG:32631")
coorout=pyproj.Proj("+init=EPSG:28992")
Xc,Yc = pyproj.transform(coorin,coorout,X,Y)
WGS84 = pyproj.Proj("+init=EPSG:4326")
RD = pyproj.Proj("+init=EPSG:28992")
loni, lati = pyproj.transform(RD, WGS84, Xc, Yc)
return loni, lati, Xc,Yc,img
def deg_to_dist(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
http://stackoverflow.com/questions/15736995/how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude-points
"""
from math import radians, cos, sin, asin, sqrt
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2.)**2 + cos(lat1) * cos(lat2) * sin(dlon/2.)**2
c = 2. * asin(sqrt(a))
km = 6367. * c
return km
def nearestDate(dates, pivot):
return min(dates, key=lambda x: abs(x - pivot))
#http://stackoverflow.com/questions/8776414/python-datetime-to-matlab-datenum
def datetime2matlabdn(date):
import datetime as dt
mdn = date + dt.timedelta(days = 366)
frac_seconds = (date - dt.datetime(date.year,date.month,date.day,0,0,0)).seconds / (24.0 * 60.0 * 60.0)
frac_microseconds = date.microsecond / (24.0 * 60.0 * 60.0 * 1000000.0)
return mdn.toordinal() + frac_seconds + frac_microseconds
def matlabDatenum2Datetime(datenum):
import datetime as dt
pydate = [dt.datetime.fromordinal(int(i)) + dt.timedelta(days = i %1) - dt.timedelta(days = 366) for i in datenum]
yearday = [(yd - dt.datetime(yd.year, 1, 1)).total_seconds()/(60.*60.*24) + 1 for yd in pydate] # datetime does that already
return pydate, yearday
def lon_lat_to_cartesian(lon, lat, R = 1):
"""
calculates lon, lat coordinates of a point on a sphere with
radius R
http://earthpy.org/interpolation_between_grids_with_ckdtree.html
"""
import numpy as np
lon_r = np.radians(lon)
lat_r = np.radians(lat)
x = R * np.cos(lat_r) * np.cos(lon_r)
y = R * np.cos(lat_r) * np.sin(lon_r)
z = R * np.sin(lat_r)
return x,y,z
# http://web.mit.edu/bgolder/www/11.521/idw/
# http://stackoverflow.com/questions/3104781/inverse-distance-weighted-idw-interpolation-with-python
def inverse_distance_weighting(x,y,z,x_grid,y_grid,neighbor_limit=10):
from scipy.spatial import cKDTree
import numpy as np
tree = cKDTree(zip(x,y),leafsize=50)
d, inds = tree.query(zip(x_grid,y_grid), k= neighbor_limit, p=2)
w = 1.0 / d**2
z_idw = np.sum(w * z[inds], axis=1) / np.sum(w, axis=1)
return z_idw
def cart2pol(x, y):
import numpy as np
rho = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)
return(rho, phi)
def pol2cart(rho, phi):
import numpy as np
x = rho * np.cos(phi)
y = rho * np.sin(phi)
return(x, y)
############################################################
############################################################
def plotSandMotor(ax, fill=0, angle=0, fillcolor='white', zorder=10):
import scipy.io as spio
import numpy as np
import cartopy.crs as ccrs
def loadmat(filename):
'''
this function should be called instead of direct spio.loadmat
as it cures the problem of not properly recovering python dictionaries
from mat files. It calls the function check keys to cure all entries
which are still mat-objects
'''
data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)
return _check_keys(data)
def _check_keys(dict):
'''
checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries
'''
for key in dict:
if isinstance(dict[key], spio.matlab.mio5_params.mat_struct):
dict[key] = _todict(dict[key])
return dict
def _todict(matobj):
'''
A recursive function which constructs from matobjects nested dictionaries
'''
dict = {}
for strg in matobj._fieldnames:
elem = matobj.__dict__[strg]
if isinstance(elem, spio.matlab.mio5_params.mat_struct):
dict[strg] = _todict(elem)
else:
dict[strg] = elem
return dict
import pyproj
import platform
if platform.system()=='Windows':
z = loadmat(r"d:\00_PhD\Dataset\MP14\01_ADCP_13hour\ADCP20141017_proc26Nov\Zandmotor_XYZ_RDNAP_2014_09.mat")
if platform.system()=='Linux':
z = loadmat(r"/media/saulo/SAULO5TB/00_PhD/Dataset/MP14/01_ADCP_13hour/ADCP20141017_proc26Nov/Zandmotor_XYZ_RDNAP_2014_09.mat")
depth = z['XYZ']['Z']
x = z['XYZ']['X']
y = z['XYZ']['Y']
WGS84 = pyproj.Proj(init='EPSG:4326')
RD = pyproj.Proj(init='EPSG:28992')
zlon, zlat = pyproj.transform(RD, WGS84, x, y)
from matplotlib.mlab import griddata
def grid(x, y, z, resX=50, resY=50):
"Convert 3 column data to matplotlib grid"
xi = np.linspace(min(x), max(x), resX)
yi = np.linspace(min(y), max(y), resY)
Z = griddata(x, y, z, xi, yi, interp='linear')
X, Y = np.meshgrid(xi, yi)
return X, Y, Z
if angle!=0:
RotAngle = np.deg2rad(angle)
RotMatrix = np.array( [[ np.cos(RotAngle), -np.sin(RotAngle)] ,
[ np.sin(RotAngle), np.cos(RotAngle)]] )
original_Matrix = np.array( [zlon, zlat] )
rotated_Matrix = np.dot( RotMatrix, original_Matrix )
zlon = rotated_Matrix[0,:]
zlat = rotated_Matrix[1,:]
xx, yy, zz = grid(zlon[::30],zlat[::30],depth[::30])
if fill==0:
ax.contour(xx,yy,zz,levels=[1, 2],colors='grey', linewidths=3)
CS = ax.contour(xx,yy,zz,levels=[-10, -8, 0],colors='black')
ax.clabel(CS, fontsize=22, inline=1, fmt='%d')
elif fill==1:
ax.contourf(xx,yy,zz, levels=np.arange(0,10,1), colors=fillcolor, zorder=zorder )
ax.contour(xx,yy,zz,levels=[0, 1, 2],colors='black', linewidths=3, zorder=zorder+1 )
CS = ax.contour(xx,yy,zz,levels=[-10, -8],colors='black')
ax.clabel(CS, fontsize=18, inline=1, fmt='%d')
return zlon, zlat, depth
def compass(u, v, ax, arrowprops=None):
import matplotlib.pyplot as plt
import cart2pol
"""
Compass draws a graph that displays the vectors with
components `u` and `v` as arrows from the origin.
Examples
--------
>>> import numpy as np
>>> u = [+0, +0.5, -0.50, -0.90]
>>> v = [+1, +0.5, -0.45, +0.85]
>>> compass(u, v)
https://ocefpaf.github.io/python4oceanographers/blog/2015/02/09/compass/
"""
angles, radii = cart2pol(u, v)
fig, ax = plt.subplots(subplot_kw=dict(polar=True))
kw = dict(arrowstyle="->", color='k')
if arrowprops:
kw.update(arrowprops)
[ax.annotate("", xy=(angle, radius), xytext=(0, 0),
arrowprops=kw) for
angle, radius in zip(angles, radii)]
ax.set_ylim(0, np.max(radii))
return fig, ax
def plotOgives(wavenumb, ogives_UW_VW, outfile):
import matplotlib.pyplot as plt
fs = 16
lw = 2
filename = str(outfile)
fig, ax = plt.subplots(1, 2, figsize=(5,3), sharey=True )
for k in range(2):
ax[k].semilogx(wavenumb[1:], ogives_UW_VW[:,k], '-k', lw=lw)
ax[k].set_xlim(1e-1,1e1)
ax[k].set_ylim(-0.6,1.6)
ax[k].set_xlabel('$2\pi fz / V$', fontsize=fs)
if k == 0:
ax[k].set_ylabel( '$Og_{u^{\prime} w^{\prime}} (f)$', fontsize=fs )
else:
ax[k].set_ylabel( '$Og_{v^{\prime} w^{\prime}} (f)$', fontsize=fs )
ax[k].grid(True,which="both")
ax[k].tick_params(axis='both', which='major', labelsize=fs)
fig.tight_layout()
fig.savefig( filename + '.png' )
plt.close()
return
def plotFilterWeight(Tp, h_hat, outfile):
import matplotlib.pyplot as plt
import numpy as np
from pandas import rolling_mean
filename = str(outfile)
lag = np.linspace( -Tp/2/2, Tp/2/2, len(h_hat)/3 )
wdw = len(lag)/5
fs = 16
huu = h_hat[0:len(h_hat)/3, 0]
huv = h_hat[0:len(h_hat)/3, 1]
huw = h_hat[0:len(h_hat)/3, 2]
huu_avg = rolling_mean( huu, wdw, min_periods=0 )
huv_avg = rolling_mean( huv, wdw, min_periods=0 )
huw_avg = rolling_mean( huw, wdw, min_periods=0 )
hVars = np.array([ huu, huv, huw ])
haVars = np.array([ huu_avg, huv_avg, huw_avg ])
ylabel = np.array(['$\hat{h}_{uu}$','$\hat{h}_{uv}$','$\hat{h}_{uw}$'])
fig, ax = plt.subplots(1,3, figsize = (20,6), sharey=True)
for k in range(3):
ax[k].plot(lag,hVars[k], '-k')
ax[k].plot(lag,haVars[k],'-r')
ax[k].plot(lag,haVars[k]*0,'--k')
ax[k].set_ylabel(ylabel[k], fontsize = 20)
ax[k].tick_params(axis='both', which='major', labelsize=fs)
ax[k].grid()
fig.tight_layout()
fig.savefig( filename + '.png' )
plt.close()
return
"""
Python translation of Zhigang Xu's tidal_ellipse MATLAB tools, available at
http://woodshole.er.usgs.gov/operations/sea-mat/tidal_ellipse-html/ap2ep.html