-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreport_utils.py
1972 lines (1746 loc) · 80.3 KB
/
report_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
import report_configuration as c
import numpy as np
import requests
import time
import matplotlib.pyplot as plt
import matplotlib.dates as md
import matplotlib as mp
import logging
import os
import pytz
from textwrap import wrap
from datetime import datetime
from pylatex import Figure, NoEscape, Table, Tabular, MultiColumn, MultiRow
from mpl_toolkits.basemap import Basemap
from scipy import signal, fft, interpolate
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.patches import Ellipse
import calendar
from oct2py import octave
from matplotlib import ticker
from windrose import WindroseAxes
from adjustText import adjust_text
from okean import gshhs
# Command does not really work currently, but let's keep it if we use a similar approach later
# mp.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})
logger = logging.getLogger(__name__)
handler = logging.FileHandler(c.settings.logging_path)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s p%(process)s {%(pathname)s:%(lineno)d} - %(name)s -'
' %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
def get_years_and_months_ranges(start_year, end_year, start_month, end_month):
year_difference = end_year - start_year
month_difference = end_month - start_month
counter_difference = year_difference * 12 + month_difference
cur_year = start_year
out_years = []
out_months = []
for x in range(0, counter_difference + 1):
cur_month = (start_month + x - 1) % 12 + 1
if ((start_month + x) % 12) == 1:
cur_year += 1
out_years.append(cur_year)
out_months.append(cur_month)
return out_years, out_months
def calc_distance(lat1, lon1, lat2, lon2):
# Using haversine formula to calculate the spherical distance
radius = 6370.
dlat = np.deg2rad(lat2) - np.deg2rad(lat1)
dlon = np.deg2rad(lon2) - np.deg2rad(lon1)
a = np.power(np.sin(dlat/2.), 2) + np.cos(np.deg2rad(lat1)) * np.cos(np.deg2rad(lat2)) * np.power(np.sin(dlon/2.), 2)
dist = 2. * radius * np.arcsin(np.sqrt(a))
return dist
def t_tide_harmonic_analysis(doc, u_data, v_data, cur_time, year, month, latitude_array, longitude_array, qc_u, qc_v,
wdir, wspe, np_longrid, np_latgrid):
general_shape = u_data.shape
desired_constituents = ['K1 ', 'M2 ', 'S2 ']
mp.rcParams['ytick.labelsize'] = 10
mp.rcParams['xtick.labelsize'] = 10
mp.rcParams.update({'font.size': 10})
fig, axes = plt.subplots(3, 1, figsize=(7, 11), sharey=True)
axes[0].set_title(desired_constituents[0])
axes[1].set_title(desired_constituents[1])
axes[2].set_title(desired_constituents[2])
x, y = gshhs.get_coastline(xlim=[0.55, 1.45], ylim=[38.35, 39.05], res='f')
for a in axes:
a.plot(x, y, 'k')
a.set_xlim([0.55, 1.45])
a.set_ylim([38.35, 39.05])
a.set(adjustable='box-forced', aspect='equal')
a.set_ylabel('$^{\circ}$N', rotation=0, horizontalalignment='right')
a.set_xlabel('$^{\circ}$E')
for m in range(0, general_shape[1]):
cur_latitude = latitude_array[m]
for n in range(0, general_shape[2]):
cur_longitude = longitude_array[n]
cur_u = u_data[:, m, n]
cur_v = v_data[:, m, n]
cur_qc_u = qc_u[:, m, n]
cur_qc_u_idx = cur_qc_u == 1
cur_u[~cur_qc_u_idx] = np.nan
cur_qc_v = qc_v[:, m, n]
cur_qc_v_idx = cur_qc_v == 1
cur_v[~cur_qc_v_idx] = np.nan
cur_u, cur_v = compute_u_v_components(wdir[:, m, n], wspe[:, m, n])
u_percent_nan = len(np.where(np.isnan(cur_u))[0])/float(len(cur_u)) * 100
v_percent_nan = len(np.where(np.isnan(cur_v))[0])/float(len(cur_v)) * 100
if (u_percent_nan > 99) or (v_percent_nan > 99):
logger.info('>60% NaNs found (index {0}, {1})'
' - U NaNs: {2:.2g}%, V NaNs: {3:.2f}%'.format(m, n, u_percent_nan, v_percent_nan))
continue
cur_u_interpolated = linear_fill(cur_time, cur_u)
cur_v_interpolated = linear_fill(cur_time, cur_v)
complex_u_v = cur_u_interpolated + 1j * cur_v_interpolated
# list of constituents used, frequency of tidal constituents (cycles/hr), tidal constituents with confidence
# intervals
logger.info('Processing {0}, {1} ({2}, {3})'.format(cur_latitude, cur_longitude, m, n))
try:
logger.info('Calling octave t_tide...')
octave.addpath(c.settings.octave_modified_t_tide_path)
const_names, const_freqs, tide_const, prediction = octave.t_tide(
complex_u_v, 'interval', 1, 'start_time',
get_md_datenum(cur_time)[0], 'latitude', cur_latitude,
'output', 'none')
# In case the python t_tide implementation should be used:
# const_names, const_freqs, tide_const, prediction = t_tide(complex_u_v, dt=1,
# stime=get_md_datenum(cur_time)[0],
# lat=cur_latitude, output=False)
except TypeError:
logger.warning('Type error at tidal analysis.')
continue
cur_counter = 0
for constituent in desired_constituents:
cur_axis = axes[cur_counter]
# cur_axis.set_title(constituent)
idx = np.where(const_names == constituent)[0]
ell_params = tide_const[idx][0]
cur_ellipse = Ellipse(xy=(np_longrid[m, n], np_latgrid[m, n]), width=ell_params[0], height=ell_params[2],
angle=ell_params[4])
cur_axis.add_artist(cur_ellipse)
cur_ellipse.set_clip_box(cur_axis.bbox)
cur_ellipse.set_facecolor('white')
cur_counter += 1
fig.tight_layout()
fig.subplots_adjust(hspace=0.25)
with doc.create(Figure(position='!htbp')) as plot:
plot.add_plot(width=NoEscape(r'1\textwidth, height=0.8\textheight, keepaspectratio'))
plot.add_caption('Tidal Ellipses for the main tidal constituents (K1, M2 and S2) in {0} {1}.'.format(
calendar.month_name[month], str(year)))
plt.clf()
plt.close('all')
mp.rcParams.update(mp.rcParamsDefault)
def clean_direction_and_speed(direction, var):
"""
Remove nan and var=0 values in the two arrays
if a var (wind speed) is nan or equal to 0, this data is
removed from var array but also from dir array
:param var:
:param direction:
"""
dirmask = np.isfinite(direction)
varmask = (var != 0 & np.isfinite(var))
ind = dirmask*varmask
return direction[ind], var[ind]
def wind_rose_hist(direction, var, nsector, normed=False):
if len(var) != len(direction):
raise(ValueError("var and direction must have same length"))
angle = 360. / nsector
dir_bins = np.arange(-angle / 2, 360. + angle, angle, dtype=np.float)
dir_edges = dir_bins.tolist()
dir_edges.pop(-1)
dir_edges[0] = dir_edges.pop(-1)
dir_bins[0] = 0.
bins = np.arange(10, 70, 10)
var_bins = np.asarray(bins).tolist()
var_bins.append(np.inf)
table = np.lib.twodim_base.histogram2d(x=var, y=direction, bins=[var_bins, dir_bins], normed=False)[0]
# add the last value to the first to have the table of North winds
table[:, 0] = table[:, 0] + table[:, -1]
# and remove the last col
table = table[:, :-1]
if normed:
table = table * 100 / table.sum()
wd_freq = np.sum(table, axis=0)
return wd_freq
def plot_wind_rose(doc, speed, direction, cur_title, month_str, year, cur_y_lim=None):
clean_wdir, clean_wspe = clean_direction_and_speed(direction, speed)
if np.all(clean_wspe <= 10):
logger.warning('Wind rose creation skipped. All speed values are below 10 cm/s.')
return None
with doc.create(Figure(position='htbp')) as plot:
ax = WindroseAxes.from_ax()
ax.bar(clean_wdir, clean_wspe, nsector=32, normed=True, opening=0.8, edgecolor='white',
bins=np.arange(10, 70, 10))
ax.set_legend()
ax.set_title("\n".join(wrap(cur_title, 50)), y=1.05)
table = ax._info['table']
wd_freq = np.sum(table, axis=0)
# In case a defined limit for the distributions is wanted to be set
if cur_y_lim is not None:
ax.set_ylim(cur_y_lim)
ax.yaxis.set_major_locator(ticker.AutoLocator())
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plot.add_plot(width=NoEscape(r'0.6\textwidth'))
plot.add_caption(cur_title + ' in ' + month_str + ' ' + str(year))
plt.clf()
plt.close('all')
return wd_freq
def plot_wind_bars_distribution(doc, wd_freq, cur_title, month_str, year, cur_y_lim=None):
# care, I assume 32 bins here!
if wd_freq is None:
logger.info('Wind bar distribution skipped.')
return
with doc.create(Figure(position='htbp')) as plot:
plt.bar(np.arange(32), wd_freq, align='center', color='gray')
xlabels = ('N', '', '', '', 'N-E', '', '', '', 'E', '', '', '', 'S-E', '', '', '',
'S', '', '', '', 'S-W', '', '', '', 'W', '', '', '', 'N-W', '', '', '')
xticks = np.arange(32)
plt.gca().set_xticks(xticks)
plt.ylabel('%')
plt.xlabel('Direction')
plt.draw()
plt.gca().set_xticklabels(xlabels)
plt.title(cur_title)
if cur_y_lim is not None:
plt.ylim(cur_y_lim)
plt.draw()
plot.add_plot(width=NoEscape(r'0.6\textwidth'))
plot.add_caption(cur_title + ' in ' + month_str + ' ' + str(year) + '.')
plt.clf()
plt.close('all')
def average_spatially(data):
out_data = np.nanmean(data[0::, :, :], axis=(1, 2))
return out_data
def filter_components(doc, data, cur_time, y_label):
y_label = transform_y_label(y_label)
conv_time = get_md_datenum(cur_time)
x_limits = [conv_time[0], conv_time[-1]]
desired_filters = np.asarray([33, 24, 12, 19]) # in hours
desired_filters = 1.0/desired_filters # in Hz
variance_storage = [np.nanvar(data)]
variance_strings = ['unfiltered Spatially Averaged', 'low-pass 33h', 'low-pass 24h', 'low-pass 12h', 'low-pass 19h']
for band in desired_filters:
filtered_data, _ = apply_low_pass_filter(band, data, cur_time)
variance_storage.append(np.nanvar(filtered_data)*100.)
for i in range(0, 4):
doc.append(NoEscape('Variance of {0}: {1:.5f}{2}.\n'.format(variance_strings[i], variance_storage[i],
'$(cm\, s^{-1})^2$')))
for band in desired_filters:
filtered_data, interpolated_data = apply_low_pass_filter(band, data, cur_time)
nan_idx = np.isnan(data)
# nan insertion
filtered_data[nan_idx] = np.nan
interpolated_data[nan_idx] = np.nan
with doc.create(Figure(position='htbp')) as plot:
plt.figure()
plt.gcf().set_size_inches(11, 3)
plt.plot(conv_time, filtered_data, '-k')
data_axis = plt.gca()
data_axis.xaxis.set_major_formatter(c.settings.xfmt)
data_axis.set_ylabel(y_label, rotation=0, horizontalalignment='right')
data_axis.grid(b=False, which='major', color='k', linestyle='--', linewidth=0.25)
plt.plot(conv_time, interpolated_data, '-b')
plt.title('Low-Pass {0:.3f}Hz / {1}h and input data.'.format(band, 1./band))
data_axis.set_xlim(x_limits)
data_axis.get_yaxis().get_major_formatter().set_useOffset(False)
plt.gcf().autofmt_xdate()
data_axis.set_xticks(np.arange(x_limits[0], x_limits[1]+1, 5.0))
data_axis.locator_params(axis='y', nbins=6)
plt.tight_layout()
plot.add_plot(width=NoEscape(r'1\textwidth'))
plot.add_caption('The blue line is the WSPE time serie. The black line indicates the 4th order'
' low-pass Butterworth filter ({0})h. Gaps show NaN values for these'
' dates.'.format(1./band))
plt.clf()
plt.close('all')
def apply_low_pass_filter(cutoff_frequency, data, cur_time):
if np.any(np.isnan(data)):
logger.info('Interpolating data. Check to use the data as output.')
data = linear_fill(cur_time, data)
order = 4
b, a = signal.butter(order, cutoff_frequency, 'low', output='ba')
filtered = signal.filtfilt(b, a, data)
return filtered, data
def compare_u_v_components(doc, hf_dir, hf_spe, buoy_dir, buoy_spe, hf_u, hf_v, hf_converted_time,
same_y_limits=False):
"""
Computes the u v components from two speed and direction variables.
:param same_y_limits:
:param doc:
:param hf_dir:
:param hf_spe:
:param buoy_dir:
:param buoy_spe:
:param hf_u:
:param hf_v:
:param hf_converted_time:
:return:
"""
x_limits = [hf_converted_time[0], hf_converted_time[-1]]
hf_computed_u, hf_computed_v = compute_u_v_components(hf_dir, hf_spe)
buoy_computed_u, buoy_computed_v = compute_u_v_components(buoy_dir, buoy_spe)
u_y_lim = [np.nanmin([hf_u, buoy_computed_u]), np.nanmax([hf_u, buoy_computed_u])]
v_y_lim = [np.nanmin([hf_v, buoy_computed_v]), np.nanmax([hf_v, buoy_computed_v])]
combined_y_lim = [np.nanmin([u_y_lim[0], v_y_lim[0]]), np.nanmax([u_y_lim[1], v_y_lim[1]])]
with doc.create(Figure(position='htbp')) as plot:
f, axarr = plt.subplots(2, sharex=True)
axarr[0].plot(hf_converted_time, hf_computed_u, '-r', label='hf computed')
axarr[0].plot(hf_converted_time, hf_u, '--k', label='hf read-in')
axarr[0].plot(hf_converted_time, buoy_computed_u, '--b', label='buoy computed')
axarr[0].set_title('U component')
axarr[0].set_xlim(x_limits)
axarr[0].set_ylim(combined_y_lim)
axarr[0].set_xticks(np.arange(x_limits[0], x_limits[1]+1, 5.0))
axarr[0].set_ylabel(r'$ms^{-1}$', rotation=0, horizontalalignment='right')
axarr[1].plot(hf_converted_time, hf_computed_v, '-r', label='hf computed')
axarr[1].plot(hf_converted_time, hf_v, '--k', label='hf read-in')
axarr[1].plot(hf_converted_time, buoy_computed_v, '--b', label='buoy computed')
axarr[1].xaxis.set_major_formatter(c.settings.xfmt)
axarr[1].set_ylabel(r'$ms^{-1}$', rotation=0, horizontalalignment='right')
axarr[1].set_title('V component')
axarr[1].set_ylim(combined_y_lim)
if same_y_limits:
for cur_axis in axarr:
cur_limits = cur_axis.get_ylim()
new_limit = np.max(np.abs(cur_limits)) + 0.02
cur_axis.set_ylim([-new_limit, new_limit])
# cur_axis.locator_params(axis='y', nbins=6)
axarr[0].yaxis.set_major_locator(mp.ticker.MaxNLocator(nbins=6, symmetric=True, trim=False))
# axarr[0].yaxis.set_major_formatter(mp.ticker.ScalarFormatter())
axarr[1].yaxis.set_major_locator(mp.ticker.MaxNLocator(nbins=6, symmetric=True, trim=False))
# axarr[1].yaxis.set_major_formatter(mp.ticker.ScalarFormatter())
f.autofmt_xdate()
f.suptitle('continuous red line = HFR computed U and V' + "\n" + 'discontinuous black line = HFR output U'
' and V' + "\n" + 'discontinuous blue line = BUOY output U and V')
f.set_size_inches(11, 5)
plt.tight_layout()
plt.subplots_adjust(top=0.8)
plot.add_plot(width=NoEscape(r'1\textwidth'))
plot.add_caption('U and V comparisons. The red lines indicates the computed HFR U and V components. The'
' discontinous black lines are the HFR output U and V components. The discontinous blue lines'
' are the Buoy output U and V components. The red and black lines should overlap. This means'
' that the U and V calculation provides the same result.')
plt.clf()
plt.close('all')
def compute_u_v_components(direction, spe=None):
if spe is None:
spe = np.ones((1, len(direction)))[0]
u = spe * np.sin(np.deg2rad(direction))
v = spe * np.cos(np.deg2rad(direction))
return u, v
def get_title_name(variable):
"""
Get the variable name
:param variable:
:bug when using concatenated files with MFDataset
:mf = MFDataset(files); var_mf = mf.variables['time']
:ds = Dataset(Files); var_ds = ds.variables['time']
:dir(var_mf) [..............'_name']
:dir(var_ds) [...'name'..., '_name']
"""
try:
title_name = variable.long_name + ' (' + variable._name + ')'
except AttributeError:
logger.info(variable._name + ' has no long name.')
try:
title_name = variable.standard_name + ' (' + variable._name + ')'
except AttributeError:
logger.info(variable._name + ' has no standard name.')
title_name = variable._name
return title_name
def transform_to_full_time(time1, time2):
if len(time1) > len(time2):
return time1
else:
return time2
def transform_to_full_data(data1, data2, idx):
if len(data1) > len(data2):
data1_filled = np.empty((1, len(data1)))[0]
data1_filled.fill(np.nan)
data2_filled = np.empty((1, len(data1)))[0]
data2_filled.fill(np.nan)
data1_filled = data1
data2_filled[idx] = data2
else:
data1_filled = np.empty((1, len(data2)))[0]
data1_filled.fill(np.nan)
data2_filled = np.empty((1, len(data2)))[0]
data2_filled.fill(np.nan)
data1_filled[idx] = data1
data2_filled = data2
return data1_filled, data2_filled
def get_same_idx(arr1, arr2):
if len(arr1) > len(arr2):
return np.in1d(arr1, arr2)
else:
return np.in1d(arr2, arr1)
def get_md_datenum(obs_time):
dates = [datetime.fromtimestamp(ts, tz=pytz.utc) for ts in obs_time]
return md.date2num(dates)
def plot_tidal_ellipses():
"""
Here we prepare the tidal ellipses representation...
:return:
"""
pass
def get_tidal_ellipse_coordinates(smaj, smin, inc):
"""
Might be replaced with plot_ellipse (https://casper.berkeley.edu/astrobaki/index.php/Plotting_Ellipses_in_Python)
Or http://matplotlib.org/api/patches_api.html#matplotlib.patches.Ellipse:
Ellipse(xy, width, height, angle=0.0, **kwargs)
xy: center of ellipse
width: total length (diameter) of horizontal axis
height: total length (diameter) of vertical axis
angle: rotation in degrees (anti-clockwise)
:param smaj: semi major axis width
:param smin: semi minor axis width
:param inc: angle in degrees (anti-clockwise)
:return: arrays with x and y coordinates of the ellipse (density is 100 points)
"""
th = np.arange(0, 2.*np.pi+0.0001, 2.*np.pi/100)
inc = inc / 180 * np.pi
x = smaj * np.cos(th)
y = smin * np.sin(th)
(th, r) = cart2pol(x, y)
(x, y) = pol2cart(th + inc, r)
return x, y
def cart2pol(x, y):
rho = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)
return rho, phi
def pol2cart(rho, phi):
x = rho * np.cos(phi)
y = rho * np.sin(phi)
return x, y
def spec_rot(u, v):
"""
Taken from https://github.com/pyoceans/python-oceans/blob/master/oceans/ff_tools/ocfis.py
Compute the rotary spectra from u,v velocity components
Parameters
----------
u : array_like
zonal wind velocity [m s :sup:`-1`]
v : array_like
meridional wind velocity [m s :sup:`-1`]
Returns
-------
cw : array_like
Clockwise spectrum [TODO]
ccw : array_like
Counter-clockwise spectrum [TODO]
puv : array_like
Cross spectra [TODO]
quv : array_like
Quadrature spectra [ TODO]
Notes
-----
The spectral energy at some frequency can be decomposed into two circularly
polarized constituents, one rotating clockwise and other anti-clockwise.
Examples
--------
TODO: puv, quv, cw, ccw = spec_rot(u, v)
References
----------
.. [1] J. Gonella Deep Sea Res., 833-846, 1972.
"""
# Individual components Fourier series.
fu, fv = list(map(np.fft.fft, (u, v)))
# Auto-spectra of the scalar components.
pu = fu * np.conj(fu)
pv = fv * np.conj(fv)
# Cross spectra.
puv = fu.real * fv.real + fu.imag * fv.imag
# Quadrature spectra.
quv = -fu.real * fv.imag + fv.real * fu.imag
# Rotatory components
# TODO: Check the division, 4 or 8?
cw = (pu + pv - 2 * quv) / 8.
ccw = (pu + pv + 2 * quv) / 8.
n = len(u)
f = np.arange(0, n) / n
return puv, quv, cw, ccw, f
def get_inertial_band_hours(latitude):
return 12. / np.sin(np.deg2rad(latitude))
def selection_main_frequencies(latitude=None):
freqs = dict()
freqs['NO1'] = 0.0402686
freqs['K1'] = 0.0417807
freqs['J1'] = 0.0432929
freqs['OO1'] = 0.0448308
freqs['UPS1'] = 0.0463430
freqs['EPS2'] = 0.0761773
freqs['MU2'] = 0.0776895
freqs['N2'] = 0.0789992
freqs['M2'] = 0.0805114
freqs['L2'] = 0.0820236
freqs['S2'] = 0.0833333
freqs['ETA2'] = 0.0850736
freqs['MO3'] = 0.1192421
freqs['M3'] = 0.1207671
freqs['MK3'] = 0.1222921
freqs['SK3'] = 0.1251141
freqs['MN4'] = 0.1595106
freqs['M4'] = 0.1610228
freqs['SN4'] = 0.1623326
freqs['MS4'] = 0.1638447
if latitude is not None:
freqs['inertial'] = 1./get_inertial_band_hours(latitude)
return freqs
def check_freq_in_range(cur_freq, latitude=None):
defined_freqs = selection_main_frequencies(latitude)
cur_identifier = ''
if defined_freqs['NO1'] < cur_freq < defined_freqs['J1']:
cur_identifier = 'K1'
if defined_freqs['K1'] < cur_freq < defined_freqs['OO1']:
cur_identifier = 'J1'
if defined_freqs['OO1'] < cur_freq < 0.0468:
cur_identifier = 'UPS1'
if 0.075 < cur_freq < defined_freqs['MU2']:
cur_identifier = 'EPS2'
if defined_freqs['EPS2'] < cur_freq < defined_freqs['J1']:
cur_identifier = 'MU2'
if defined_freqs['MU2'] < cur_freq < defined_freqs['M2']:
cur_identifier = 'N2'
if defined_freqs['N2'] < cur_freq < defined_freqs['L2']:
cur_identifier = 'M2'
if defined_freqs['M2'] < cur_freq < defined_freqs['S2']:
cur_identifier = 'L2'
if defined_freqs['L2'] < cur_freq < defined_freqs['ETA2']:
cur_identifier = 'S2'
if defined_freqs['S2'] < cur_freq < 0.086:
cur_identifier = 'ETA2'
if 0.118 < cur_freq < defined_freqs['M3']:
cur_identifier = 'MO3'
if 'inertial' in defined_freqs:
if (defined_freqs['inertial'] - 0.002) < cur_freq < (defined_freqs['inertial'] + 0.002):
cur_identifier = 'inertial'
return cur_identifier
def get_important_peaks_in_freq_range(freq, power, latitude=None):
# propably also possible as a one-liner but sorry i am stupid so KISS... keep it simple and stupid
identifier_storage = []
main_frequencies_points = []
remainder_frequencies = []
remainder_power = []
# MAX POWER!
max_power = np.nanmax(power)
for i in range(0, len(freq)):
cur_freq = freq[i]
identifier = check_freq_in_range(cur_freq, latitude)
if len(identifier_storage) > 0:
if (identifier != '') & (identifier_storage[-1] != identifier):
logger.info('freq found: ' + identifier)
identifier_storage.append(identifier)
main_frequencies_points.append([cur_freq, power[i]])
else:
remainder_frequencies.append(cur_freq)
remainder_power.append(power[i])
else:
if identifier != '':
logger.info('freq found: ' + identifier)
identifier_storage.append(identifier)
main_frequencies_points.append([cur_freq, power[i]])
else:
remainder_frequencies.append(cur_freq)
remainder_power.append(power[i])
return identifier_storage, main_frequencies_points, np.asarray(remainder_frequencies), np.asarray(remainder_power)
def _datacheck_peakdetect(x_axis, y_axis):
if x_axis is None:
x_axis = range(len(y_axis))
if len(y_axis) != len(x_axis):
raise ValueError(
"Input vectors y_axis and x_axis must have same length")
# needs to be a numpy array
y_axis = np.array(y_axis)
x_axis = np.array(x_axis)
return x_axis, y_axis
def peakdet(v, delta, x=None):
maxtab = []
mintab = []
if x is None:
x = np.arange(len(v))
v = np.asarray(v)
if len(v) != len(x):
logger.warning('Input vectors v and x must have same length')
if not np.isscalar(delta):
logger.warning('Input argument delta must be a scalar')
if delta <= 0:
logger.warning('Input argument delta must be positive')
mn, mx = np.Inf, -np.Inf
mnpos, mxpos = np.NaN, np.NaN
lookformax = True
for i in np.arange(len(v)):
this = v[i]
if this > mx:
mx = this
mxpos = x[i]
if this < mn:
mn = this
mnpos = x[i]
if lookformax:
if this < mx-delta:
maxtab.append((mxpos, mx))
mn = this
mnpos = x[i]
lookformax = False
else:
if this > mn+delta:
mintab.append((mnpos, mn))
mx = this
mxpos = x[i]
lookformax = True
return np.array(maxtab), np.array(mintab)
def peakdetect(y_axis, x_axis=None, lookahead=200, delta=0):
max_peaks = []
min_peaks = []
dump = [] # Used to pop the first hit which almost always is false
# check input data
x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
# store data length for later use
length = len(y_axis)
# perform some checks
if lookahead < 1:
raise ValueError("Lookahead must be '1' or above in value")
if not (np.isscalar(delta) and delta >= 0):
raise ValueError("delta must be a positive number")
# maxima and minima candidates are temporarily stored in
# mx and mn respectively
mn, mx = np.Inf, -np.Inf
# Only detect peak if there is 'lookahead' amount of points after it
for index, (x, y) in enumerate(zip(x_axis[:-lookahead], y_axis[:-lookahead])):
if y > mx:
mx = y
mxpos = x
if y < mn:
mn = y
mnpos = x
# look for max
if y < mx-delta and mx != np.Inf:
# Maxima peak candidate found
# look ahead in signal to ensure that this is a peak and not jitter
if y_axis[index:index+lookahead].max() < mx:
max_peaks.append([mxpos, mx])
dump.append(True)
# set algorithm to only find minima now
mx = np.Inf
mn = np.Inf
if index+lookahead >= length:
# end is within lookahead no more peaks can be found
break
continue
# else: #slows shit down this does
# mx = ahead
# mxpos = x_axis[np.where(y_axis[index:index+lookahead]==mx)]
# look for min
if y > mn+delta and mn != -np.Inf:
# Minima peak candidate found
# look ahead in signal to ensure that this is a peak and not jitter
if y_axis[index:index+lookahead].min() > mn:
min_peaks.append([mnpos, mn])
dump.append(False)
# set algorithm to only find maxima now
mn = -np.Inf
mx = -np.Inf
if index+lookahead >= length:
# end is within lookahead no more peaks can be found
break
# else: #slows shit down this does
# mn = ahead
# mnpos = x_axis[np.where(y_axis[index:index+lookahead]==mn)]
# Remove the false hit on the first value of the y_axis
try:
if dump[0]:
max_peaks.pop(0)
else:
min_peaks.pop(0)
del dump
except IndexError:
# no peaks were found, should the function return empty lists?
pass
return [max_peaks, min_peaks]
def frequency_plotter(doc, freq, power, significant_freq_names, significant_freq_points, cur_title, month_str, year,
other_freqs_x=None, other_freqs_y=None, zoom=False):
cur_x_lim = [0.025, 0.1]
if other_freqs_x is not None:
idx = (other_freqs_x >= 0.04) & (other_freqs_x <= 0.07)
other_freqs_x = other_freqs_x[idx]
other_freqs_y = other_freqs_y[idx]
if zoom:
cur_title += ' section of interest'
with doc.create(Figure(position='htbp')) as plot:
f = plt.figure()
plt.plot(freq, power, 'k-', lw=0.5)
ax = plt.gca()
line_holder = []
y_lims = ax.get_ylim()
if zoom:
texts = []
for i in range(0, len(significant_freq_points)):
act_freq = significant_freq_points[i][0]
act_power = significant_freq_points[i][1]
plt.plot(act_freq, act_power, 'ro')
texts.append(plt.text(act_freq, act_power, significant_freq_names[i]))
cs, = plt.plot([act_freq, act_freq], [y_lims[0], y_lims[1]], '--')
line_holder.append(cs)
# cur_line = significant_freq_points[i]
# cs, = plt.plot(cur_line[0], cur_line[1], '--')
# line_holder.append(cs)
for i in range(0, len(other_freqs_x)):
plt.plot(other_freqs_x[i], other_freqs_y[i], 'ro')
texts.append(plt.text(other_freqs_x[i], other_freqs_y[i], '{:0.2f}'.format(1./other_freqs_x[i])))
plt.legend(line_holder, significant_freq_names, numpoints=1, fontsize=10)
plt.title(cur_title)
ax.set_ylabel('${|dft|}^{2}$', rotation=0, horizontalalignment='right')
ax.set_xlabel('cycles/hour')
f.set_size_inches(11, 3)
if zoom:
y_min = 0
selection_idx = np.logical_and(freq >= 0.004, freq <= 0.1)
y_max = np.nanmax(power[selection_idx])
plt.ylim([y_min, y_max])
plt.xlim(cur_x_lim)
adjust_text(texts, arrowprops=dict(arrowstyle="-", color='k', lw=0.5), force_points=0.9,
expand_points=(1.2, 1.3))
plt.tight_layout()
plot.add_plot(width=NoEscape(r'1\textwidth'))
plot.add_caption(NoEscape(cur_title + ' in ' + month_str + ' ' + str(year)))
plt.clf()
plt.close('all')
if not zoom:
frequency_plotter(doc, freq, power, significant_freq_names, significant_freq_points, cur_title, month_str, year,
other_freqs_x=other_freqs_x, other_freqs_y=other_freqs_y, zoom=True)
def compute_dft_spectrum(obs_time, component_data):
filled_component_data = linear_fill(obs_time, component_data)
x = filled_component_data
fs = 1./3600.
t = np.arange(0, 0.25, fs/2.)
n = len(t)
y = fft(x, n)
power = np.power(abs(y[0:(n/2)]), 2)
nyquist = 1/2.
freq = np.arange(0, n/2)/(n/2.)*nyquist
# max_peaks, min_peaks = peakdetect(power, lookahead=3)
max_peaks, min_peaks = peakdet(power, 5)
x_p, y_p = zip(*max_peaks)
peak_freqs = freq[list(map(int, x_p))]
peak_power = power[list(map(int, x_p))]
return freq, power, peak_freqs, peak_power
def plot_energy_spectrum(doc, obs_time, u, v, month_str, year, latitude=None):
cur_title = r'U component ${|dft|}^{2}$'
freq, power, peak_freqs, peak_power = compute_dft_spectrum(obs_time, u)
significant_freq_names, significant_freq_points, remainder_freqs, remainder_power = \
get_important_peaks_in_freq_range(peak_freqs, peak_power, latitude)
frequency_plotter(doc, freq, power, significant_freq_names, significant_freq_points, cur_title, month_str, year,
other_freqs_x=remainder_freqs, other_freqs_y=remainder_power, zoom=True)
found_freqs = []
for stored_freq in significant_freq_points:
found_freqs.append(stored_freq[0])
write_frequencies_table(doc, 'U component', significant_freq_names, found_freqs)
cur_title = r'V component ${|dft|}^{2}$'
freq, power, peak_freqs, peak_power = compute_dft_spectrum(obs_time, v)
significant_freq_names, significant_freq_points, remainder_freqs, remainder_power = \
get_important_peaks_in_freq_range(peak_freqs, peak_power, latitude)
frequency_plotter(doc, freq, power, significant_freq_names, significant_freq_points, cur_title, month_str, year,
other_freqs_x=remainder_freqs, other_freqs_y=remainder_power, zoom=True)
found_freqs = []
for stored_freq in significant_freq_points:
found_freqs.append(stored_freq[0])
write_frequencies_table(doc, 'V component', significant_freq_names, found_freqs)
def write_frequencies_table(doc, cur_title, identifiers, frequencies):
with doc.create(Table(position='htb')) as t:
doc.append(NoEscape(r'\begin{center}'))
with doc.create(Tabular('|c|c|c|', pos='htb')) as table:
table.add_hline()
table.add_row(((MultiColumn(3, align='|c|', data=cur_title)),))
table.add_row(('Identifier', 'cycles/hour', 'hour'))
table.add_hline()
for i in range(0, len(identifiers)):
table.add_row((identifiers[i], np.round(frequencies[i], 4), np.round(1./frequencies[i], 2)))
table.add_hline()
t.add_caption('Identified frequencies for ' + cur_title)
doc.append(NoEscape(r'\end{center}'))
def linear_fill(x, y, kind=None):
"""
Fill the gap in a time serie using linear interpolation.
Taken from https://github.com/ctroupin/SOCIB_plots/blob/master/HFradar/energy_spectrum_radar.ipynb all credit goes
to Charles Troupin, Socib.
:param x: 1-D time array
:param y: 1-D data array
:param kind: str
:return: filled gaps (NaN values) using one-dimensional linear interpolation (numpy.interp)
"""
if kind is None:
kind = 'linear'
good_values = np.where(~np.isnan(y))
missing_values = np.where(np.isnan(y))
y_interp = np.copy(y)
if kind == 'linear':
y_interp[missing_values] = np.interp(x[missing_values], x[good_values], y[good_values])
# elif kind == 'spline':
# f = interpolate.interp1d(x, y)
# y_interp[missing_values] = np.interp(x[missing_values], x[good_values], y[good_values])
return y_interp
def plot_quiver_direction_overlapping(doc, cur_time, lower_direction, plot_title, upper_direction, upper_amplifier=None,
s_name=None, x_limits=None, input_month_title=None, lower_amplifier=None,
shared_qc_idx_upper=None, shared_qc_idx_lower=None):
# TODO: jajaja i c, very dirty. but had to be done quick, so remove duplicate code bases when there is some time
if x_limits is None:
x_limits = [np.nanmin(cur_time) - 1, np.nanmax(cur_time) + 1]
else:
x_limits = [x_limits[0] - 1, x_limits[1] + 1]
plt.rcParams.update({'font.size': 13})
try:
month_title = c.settings.month_str + ' ' + str(c.settings.year)
except AttributeError:
if input_month_title is None:
logger.warning('Trying to access non-set setting variable.', exc_info=True)
month_title = ''
else:
month_title = input_month_title
if s_name is None:
my_title = 'Evolution of ' + plot_title + ' in ' + month_title + '.'
else:
my_title = 'Evolution of ' + plot_title + ' at ' + s_name + ' in ' + month_title + '.'
if np.all(np.isnan(lower_direction)) or np.all(np.isnan(upper_direction)):
print ('Only NaNs found at ' + plot_title)
doc.append('Only NaNs encountered at one of the plots from ' + plot_title)
return
if upper_amplifier is not None:
upper_amplifier = normalize_data(upper_amplifier, 'mean')
if lower_amplifier is not None:
lower_amplifier = normalize_data(lower_amplifier, 'mean')
u, v = compute_u_v_components(lower_direction, lower_amplifier)
upper_u, upper_v = compute_u_v_components(upper_direction, upper_amplifier)
# u_raw = np.cos(np.deg2rad(lower_direction))
# v_raw = np.sin(np.deg2rad(lower_direction))
# u_raw_lower = np.cos(np.deg2rad(upper_direction))
# v_raw_lower = np.sin(np.deg2rad(upper_direction))
if (upper_amplifier is not None) or (lower_amplifier is not None):
plot_title += ' normalized and scaled with speed'
if lower_amplifier is None:
vector_length = np.sqrt((u * u) + (v * v))
u = u / vector_length
v = v / vector_length
# else:
# upper_amplifier = normalize_data(upper_amplifier, 'mean')
# u = -upper_amplifier * u_raw
# v = -upper_amplifier * v_raw
if upper_amplifier is None:
upper_vector_length = np.sqrt((upper_u * upper_u) + (upper_v * upper_v))
upper_u = upper_u / upper_vector_length
upper_v = upper_u / upper_vector_length
# else:
# lower_amplifier = normalize_data(lower_amplifier, 'mean')
# lower_u = -lower_amplifier * u_raw_lower
# lower_v = -lower_amplifier * v_raw_lower
with doc.create(Figure(position='htbp')) as plot:
f, axarr = plt.subplots(2, sharex=True)
axarr[0].set_title("\n".join(wrap(plot_title, 70)))
try:
if shared_qc_idx_upper is not None:
upper_u[~shared_qc_idx_upper] = np.nan
upper_v[~shared_qc_idx_upper] = np.nan
axarr[0].quiver(cur_time, 0, upper_u, upper_v, color='r', alpha=0.5,
width=0.004, units='width', scale=1, scale_units='y', headlength=0, headwidth=1)
else:
axarr[0].quiver(cur_time, 0, upper_u, upper_v, color='r', alpha=0.5, width=0.004, units='width',
scale=1, scale_units='y', headlength=0, headwidth=1)
axarr[0].set_xlim(x_limits)
axarr[0].set_ylim(-1, 1)
axarr[0].xaxis.set_major_formatter(c.settings.xfmt)
axarr[0].set_xticks(np.arange(x_limits[0]+1, x_limits[1], 5.0))
if shared_qc_idx_lower is not None:
u[~shared_qc_idx_lower] = np.nan
v[~shared_qc_idx_lower] = np.nan
axarr[1].quiver(cur_time, 0, u, v, color='r', alpha=0.5, width=0.004,
units='width', scale=1, scale_units='y', headlength=0, headwidth=1)
else:
axarr[1].quiver(cur_time, 0, u, v, color='r', alpha=0.5, width=0.004, units='width', scale=1,
scale_units='y', headlength=0, headwidth=1)
axarr[1].set_xlim(x_limits)
axarr[1].set_ylim(-1, 1)
#axarr[1].set_xticks([])
f.autofmt_xdate()
f.set_size_inches(11, 5)
plt.tight_layout()
except RuntimeWarning:
logger.debug('Problem at plotting quiver.', exc_info=True)
plt.subplots_adjust(top=0.8)
plot.add_plot(width=NoEscape(r'1\textwidth'))
plot.add_caption(my_title)
plt.clf()
plt.close('all')
def write_header_tabular(table, variable, spec_len):
table.add_hline()
table.add_row(((MultiColumn(spec_len, align='|c|',
data=get_standard_name(variable) + ' (' + variable.name + ')')),))
def write_data_only_tabular(table, variable, cur_mean, cur_min, cur_max, cur_min_time, cur_max_time):
cur_units = variable.units
table.add_row((MultiColumn(2, align='|c|', data=''), MultiColumn(3, align='c|', data='Data Statistics')))
table.add_row((MultiColumn(1, align='|c', data=''), '', 'Mean (' + cur_units + ')',
'Min (' + cur_units + ')', 'Max (' + cur_units + ')'))
table.add_hline()
table.add_row((MultiRow(2, data=''), 'Value', "%.2f" % cur_mean, "%.2f" % cur_min, "%.2f" % cur_max))
table.add_row(('', 'Time', '-', cur_min_time, cur_max_time))
def write_qc_only_tabular(table, sum_good, sum_prob_good, sum_prob_bad, sum_bad, sum_spike, sum_nan, percent_good,
percent_rest, percent_nan):
table.add_row((MultiColumn(2, align='|c|', data=''), MultiColumn(6, align='c|', data='QC Flags')))
table.add_row((MultiColumn(1, align='|c', data=''), '', 1, 2, 3, 4, 6, 9))
table.add_hline()