/
sphere.py
1423 lines (1084 loc) · 46.6 KB
/
sphere.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############
import numpy as np
import math
from netCDF4 import Dataset
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from matplotlib import gridspec
from matplotlib import cm
from config_pl import generate_polvar_metadata
from conversion import Conversion
import scipy.optimize as opt
from scipy.interpolate import griddata
import warnings
##############
"""
Module to create plots and perform gaussian fits on the sphere calibration data
Created on Wed Oct 19 14:13:15 2016
@author: fvanden
Revision history: 19.10.2016 - created
"""
#filename = '/ltedata/Payerne_balloon_2016/Radar/Proc_data/2016/08/24/MXPol-polar-20160824-123033-WINDOW-011_6.nc'
## -------------------------------------------------------------------------- ##
class GaussSphere():
"""
A class for fitting 1 and 2D gaussian functions to
the raw sphere calibration data
Parameters
----------
filename, str : name of the sphere calibration file
i.e. '/ltedata/Payerne_balloon_2016/Radar/Proc_data/2016/08/24/
MXPol-polar-20160824-123033-WINDOW-011_6.nc'
cutdB, float : dB value at which to cut off data
doa, float : offset from the centre from which to use the data
in degrees azimuth, if None default of 2.5 degrees is used
doe, float : offset from the centre from which to use the data
in degrees elevation, if None default of 2.5 degrees is used
gate, int : gate for which to extract data. If None, gate will be
selected based on the resolution of the scan (see the find_gate
function)
var, str : type of radar variable to use. If None, the horizontal
signal is used (SignalH)
azim, float : azimuth at which to take middle of the sphere; if None, the
highest measured value will be considered the middle
elev, float : elevation at which to take middle of the sphere; if None, the
highest measured value will be considered the middle
Attributes
----------
azimuth, list : list of all azimuths from file
elevation, list : all elevations from file
data, list : all data values from file
info_fit, dict : contains estimated optimum and one standard deviation on
error of the estimated optimum for the 1d and 2d gaussian fits.
res_azim_interp, float : the azimuth resolution to interpolate data to a
regular grid
res_elev_interp, float : the elevation resolution to interpolate data to a
regular grid
theta, float : initial value for clockwise rotation of the gaussian
function.
sigx, float : initial value for spread of gaussian function in x direction
sigy, float : initial value for spread of gaussian function in y direction
resolution, int : measurement resolution (15,30 or 75)
"""
## ------------------------------------------------------------------ ##
## Constructors/Destructors ##
## ------------------------------------------------------------------ ##
def __init__(self, filename, cutdB = None, doa = None, doe = None, gate = None, var = None,
azim = None, elev = None):
# --- input parameters --- #
self.filename = filename
if cutdB is None:
self.cutdB = 10.
else:
self.cutdB = cutdB
if doa is None:
self.doa = 1.5
else:
self.doa = doa
if doe is None:
self.doe = 1.5
else:
self.doe = doe
if var is None:
self.var = 'SignalH'
else:
self.var = var
self.load_data()
if gate is None:
self.gate = self.find_gate()
else:
self.gate = gate
self.azim = azim
self.elev = elev
# --- fitting output --- #
self.info_fit = {}
# --- interpolation parameters --- #
self.res_azim_interp = 0.16
self.res_elev_interp = 0.12
# --- fitting parameters --- #
self.theta = 0.
self.sigx = 1.
self.sigy = 0.5
def __del__(self):
pass
## ------------------------------------------------------------------ ##
## Methods ##
## ------------------------------------------------------------------ ##
# public:
## -------------------------Plot functions--------------------------- ##
## ------------------------------------------------------------------ ##
def plot_all(self, plot = None):
"""
Plots 1d and 2d plots of data in one figure
Parameters
----------
plot, str : "scatter" to plot data in scatter plot, "gauss" to plot
data in 2D gaussian plot. If None, plots scatter plot by default
NOTE: this is the 'new' plotting function which uses plot_gauss,
gaus_data_rad and data_2drad functions; data is selected within a
spherical area of radius self.doa around the center, and filtered to
take only values higher then self.cutdB. This data is used for the
2D gaussian fit, then interpolated to a spherical grid using linear
interpolation.
Returns
-------
None
See Also
--------
plot_all2
"""
fig = plt.figure(figsize = [9.45, 5.8] )
gs = gridspec.GridSpec(3,4)
# elevation axis
ax1 = plt.subplot(gs[:2,0])
self.plot_elev(ax = ax1)
# azimuth axis
ax2 = plt.subplot(gs[2,1:3])
self.plot_azim(ax = ax2)
# create 2D axis
ax3 = plt.subplot(gs[:2, 1:3])
ax3.axes.get_xaxis().set_visible(False)
ax3.axes.get_yaxis().set_visible(False)
# create gauss info panel
ax4 = plt.subplot(gs[-1,-1], frameon = False)
ax4.axes.get_yaxis().set_visible(False)
ax4.axes.get_xaxis().set_visible(False)
# create and plot 2D plot
if plot == 'scatter' or plot is None:
self.plot_scatter(ax = ax3)
else:
self.plot_gauss(ax = ax3)
# create and plot gauss info panel text
if plot == 'scatter' or plot is None:
axtext = self.create_fit_text(ttype = '1d')
else:
axtext = self.create_fit_text(ttype = '2d')
ax4.text(0.5,-0.4, axtext, fontsize = 7)
def plot_all2(self, plot = None):
"""
Plots 1d and 2d plots of data in one figure
Parameters
----------
plot, str : "scatter" to plot data in scatter plot, "gauss" to plot
data in 2D gaussian plot. If None, plots scatter plot by default
NOTE: this is the 'old' plotting function which uses the plot_gauss2
function and the interp functions; data is first interpolated to a
regular grid using nearest neighbour interpolation, then the sphere is
selected within a square frame based on self.doe and self.doa, then
fitted with a 2D gaussian function.
Returns
-------
None
See Also
--------
plot_all
"""
fig = plt.figure(figsize = [9.45, 5.8] )
gs = gridspec.GridSpec(3,4)
# elevation axis
ax1 = plt.subplot(gs[:2,0])
self.plot_elev(ax = ax1)
# azimuth axis
ax2 = plt.subplot(gs[2,1:3])
self.plot_azim(ax = ax2)
# create 2D axis
ax3 = plt.subplot(gs[:2, 1:3])
ax3.axes.get_xaxis().set_visible(False)
ax3.axes.get_yaxis().set_visible(False)
# create gauss info panel
ax4 = plt.subplot(gs[-1,-1], frameon = False)
ax4.axes.get_yaxis().set_visible(False)
ax4.axes.get_xaxis().set_visible(False)
# create and plot 2D plot
if plot == 'scatter' or plot is None:
self.plot_scatter(ax = ax3)
else:
self.plot_gauss2(ax = ax3)
# create and plot gauss info panel text
if plot == 'scatter' or plot is None:
axtext = self.create_fit_text(ttype = '1d')
else:
axtext = self.create_fit_text(ttype = '2d')
ax4.text(0.5,-0.4, axtext, fontsize = 7)
def plot_selection(self, polvar = None, title = None):
"""
plots a figure indicating the data which was selected to perform the
2D gaussian fit (only valid for plot_all function)
Parameters
----------
polvar, str : polarimetric variable, if set to None, the self.var
will be used
Returns
-------
None
"""
ind, select = self.data_2drad(polvar = polvar)
if polvar is None:
pldata = self.data[self.gate]
else:
pldata = self.file_handle.variables[polvar][self.gate]
# find max min values
if polvar is not None:
metadata = generate_polvar_metadata(polvar)
vmin = metadata['valid_min']
vmax = metadata['valid_max']
cbartitle = metadata['long_name']
elif self.var == 'SignalH':
vmin = min(self.data[self.gate])
vmax = max(self.data[self.gate])
elif self.var == 'Zh':
vmin = -10.
vmax = 40.
cbartitle = 'Reflectivity [dBZ]'
else:
metadata = generate_polvar_metadata(self.var)
vmin = metadata['valid_min']
vmax = metadata['valid_max']
cbartitle = metadata['long_name']
fig = plt.figure()
plt.hold(True)
plt.scatter(self.azimuth, self.elevation, c=pldata, marker = 's', cmap = plt.cm.jet,
vmin = vmin, vmax = vmax)
cbar = plt.colorbar()
cbar.set_label(cbartitle)
plt.scatter(np.take(self.azimuth, ind), np.take(self.elevation,ind), marker = 'o',
facecolors='none', edgecolors='w')
plt.plot(self.azim_sphere, self.elev_sphere, color = 'k')
plt.xlabel('Azimuth')
plt.ticklabel_format(useOffset=False)
plt.ylabel('Elevation')
if title is None:
plt.title( ("selected data for radius sphere: %f and maxval: %f")%(self.doa, self.cutdB) )
else:
plt.title(title)
def plot_gauss(self, ax = None):
"""
Plots a 2D gaussian plot from data, selecting first the data in a
radius of self.doa around the estimated center of the sphere
(self.data_2drad), then fitting the data to a 2D gaussian function and
finally interpolating the data to a speherical grid using linear
interpolation (for plotting purposes).
Parameters
----------
ax, axis handle : if None, creates a new figure
Returns
-------
None
See Also
--------
plot_gauss2
"""
# fit data to original data (selected with a radius of self.doa round
# the estimated middle of the sphere)
best_vals, covar = self.gauss_data_rad()
# get azimuth and elevation data and create gaussian fitted data
ind, select = self.data_2drad()
newazim = np.take(self.azimuth, ind)
newelev = np.take(self.elevation, ind)
z = (newazim, newelev)
data_fitted = self.gaussian_2d(z, *best_vals)
# interpolate data for plotting purposes
aziminterp, elevinterp, datainterp = self.interp3(newazim, newelev, np.asarray(select))
_,_,data_fit_interp = self.interp3(newazim, newelev, data_fitted)
# get metadata
if self.var == 'SignalH':
units = 'mW'
else:
metadata = generate_polvar_metadata(self.var)
units = metadata['units']
# plot
if ax is None:
fig = plt.figure()
ax = plt.subplot(1,1,1)
ax.hold(True)
c = ax.imshow(datainterp, cmap=plt.cm.jet, origin='bottom',
extent=(aziminterp.min(), aziminterp.max(), elevinterp.min(), elevinterp.max()))
CS = ax.contour(aziminterp, elevinterp, data_fit_interp, 6, colors='w')
plt.clabel(CS, fontsize = 10, inline = 1)
cbar = plt.colorbar(c)
cbar.set_label(self.var + ' ' + units)
plt.title('range' + str(self.range_r[self.gate]))
plt.xlabel('Azimuth')
plt.ylabel('Elevation')
ax.ticklabel_format(useOffset=False)
else:
ax.hold(True)
c = ax.imshow(datainterp, cmap=plt.cm.jet, origin='bottom',
extent=(aziminterp.min(), aziminterp.max(), elevinterp.min(), elevinterp.max()))
box = ax.get_position()
axc = plt.axes([box.x0*1.05 + box.width * 1.05, box.y0, 0.01, box.height])
cbar = plt.colorbar(c, cax = axc)
cbar.set_label(self.var + ' ' + units)
CS = ax.contour(aziminterp, elevinterp, data_fit_interp, 6, colors='w')
plt.clabel(CS, fontsize = 10, inline = 1)
def plot_gauss2(self, ax = None):
"""
Plots a 2D gaussian plot from the data, interpolating the data first
(self.interp), and selecting a square area around the sphere with
azimuth extending self.doa degrees from the estimated centre of the
sphere and elevation extending self.doe from the estimated centre of
the sphere (self.data_2d). The data is then fitted to a 2D gaussian
function (self.gauss_data).
Parameters
----------
ax, axis handle : if None creates a new figure
Returns
-------
None
See Also
--------
plot_gauss
"""
# interpolate and cut off data
newazim, newelev, newdata = self.interp()
best_vals, covar = self.gauss_data()
xn, yn = np.meshgrid(newazim, newelev)
z = (xn,yn)
data_fitted = self.gaussian_2d(z, *best_vals)
# get metadata
if self.var == 'SignalH':
units = 'mW'
else:
metadata = generate_polvar_metadata(self.var)
units = metadata['units']
if ax is None:
fig = plt.figure()
ax = plt.subplot(1,1,1)
ax.hold(True)
c = ax.imshow(newdata, cmap=plt.cm.jet, origin='bottom',
extent=(xn.min(), xn.max(), yn.min(), yn.max()))
CS = ax.contour(xn, yn, data_fitted.reshape(len(newelev), len(newazim)), 6, colors='w')
plt.clabel(CS, fontsize = 10, inline = 1)
cbar = plt.colorbar(c)
cbar.set_label(self.var + ' ' + units)
plt.title('range' + str(self.range_r[self.gate]))
plt.xlabel('Azimuth')
plt.ylabel('Elevation')
ax.ticklabel_format(useOffset=False)
else:
ax.hold(True)
c = ax.imshow(newdata, cmap=plt.cm.jet, origin='bottom',
extent=(xn.min(), xn.max(), yn.min(), yn.max()))
box = ax.get_position()
axc = plt.axes([box.x0*1.05 + box.width * 1.05, box.y0, 0.01, box.height])
cbar = plt.colorbar(c, cax = axc)
cbar.set_label(self.var + ' ' + units)
CS = ax.contour(xn, yn, data_fitted.reshape(len(newelev), len(newazim)), 6, colors='w')
plt.clabel(CS, fontsize = 10, inline = 1)
def plot_scatter(self, ax = None):
"""
Plots a scatter plot from the data
Parameters
----------
ax, axis handle : if None creates a new figure
Returns
-------
None
"""
ind, select = self.data_2d()
azim = self.azimuth[ind]
elev = self.elevation[ind]
max_i = np.nanargmax(select)
if self.var == 'SignalH':
vmin = min(select)
vmax = max(select)
units = 'PowerH'
elif self.var == 'Zh':
units = 'dBZ'
vmin = -10.
vmax = 40.
else:
metadata = generate_polvar_metadata(self.var)
vmin = metadata['valid_min']
vmax = metadata['valid_max']
units = metadata['units']
if ax is None:
fig = plt.figure()
ax = plt.subplot(1,1,1)
ax.scatter(azim,elev,c=select, marker = 's', cmap = cm.jet,
vmin = vmin, vmax =vmax)
cbar = plt.colorbar()
cbar.set_label(self.var + ' ' + units)
plt.title('range' + str(self.range_r[self.gate]))
plt.xlabel('Azimuth')
plt.ylabel('Elevation')
ax.ticklabel_format(useOffset=False)
else:
c = ax.scatter(azim,elev,c=select, marker = 's', cmap = cm.jet,
vmin = vmin, vmax =vmax)
box = ax.get_position()
axc = plt.axes([box.x0*1.05 + box.width * 1.05, box.y0, 0.01, box.height])
cbar = plt.colorbar(c, cax = axc)
cbar.set_label(self.var + ' ' + units)
ax.plot([azim[max_i], azim[max_i]],[min(elev), max(elev)],'-k')
ax.plot([min(azim), max(azim)],[elev[max_i], elev[max_i]], '-k')
def plot_elev(self, ax = None):
"""
Plots data from the elevation transect with a gaussian fitted curve
Parameters
----------
ax, axis handle : if None creates a new figure
Returns
-------
None
"""
ind, select = self.data_elev()
best_vals, covar = self.gauss_elev()
x = self.elevation[ind]
x_r = np.arange(x[0],x[-1],0.05)
y_r = self.gaussian_1d(x_r, best_vals[0], best_vals[1], best_vals[2])
if ax is None:
fig = plt.figure()
ax = plt.subplot(1,1,1)
ax.scatter(x,select,marker = 'o', label = 'observations')
ax.plot(x_r, y_r, '-r', label = 'gauss_fit')
ax.legend()
plt.xlabel('Elevation')
plt.ylabel(self.var)
else:
ax.scatter(select,x,marker = 'o', label = 'observations')
ax.plot(y_r,x_r, '-r', label = 'gauss_fit')
plt.xlabel(self.var)
plt.ylabel('Elevation')
plt.gca().invert_xaxis()
def plot_azim(self, ax = None):
"""
Plots data from the azimuth transect with a gaussian fitted curve
Parameters
----------
ax, axis handle : if None creates a new figure
Returns
-------
None
"""
ind, select = self.data_azim()
best_vals, covar = self.gauss_azim()
x = self.azimuth[ind][::-1]
select = select[::-1]
x_r = np.arange(x[0],x[-1],0.05)
y_r = self.gaussian_1d(x_r, best_vals[0], best_vals[1], best_vals[2])
if ax is None:
fig = plt.figure()
ax = plt.subplot(1,1,1)
ax.scatter(x,select,marker = 'o', label = 'observations')
ax.plot(x_r, y_r, '-r', label = 'gauss_fit')
ax.legend()
plt.xlabel('Azimuth')
plt.ylabel(self.var)
else:
ax.scatter(x,select,marker = 'o', label = 'observations')
ax.plot(x_r, y_r, '-r', label = 'gauss_fit')
plt.xlabel('Azimuth')
plt.ylabel(self.var)
plt.gca().invert_yaxis()
plt.axis('tight')
# private:
## -----------------------Fitting functions-------------------------- ##
## ------------------------------------------------------------------ ##
def gauss_data_rad(self):
"""
Fits data with 2D gaussian function and finds the best values and the
covariance matrix. Fit is also stored in self.info_fit.
Parameters
----------
None
Returns
-------
best_vals, numpy array : best amp, cen and wid values for the gaussian
function
covar, numpy array : the estimated covariance of the optimal values for
the parameters best_vals; use perr = np.sqrt(np.diag(pcov)) to
compute one standard deviation errors on the parameters
See Also
--------
gauss_data
"""
# select data for gaussian fitting using a circle with radius = self.doa
# eliminating nan values and requiring data points to have higher values
# then self.cutdB
ind, select = self.data_2drad()
newazim = np.take(self.azimuth, ind)
newelev = np.take(self.elevation, ind)
z = (newazim, newelev)
# determine initial values
amplitude = np.nanmax(select)
#offset = np.min(select)
max_i = np.nanargmax(select)
xo = newazim[max_i]
yo = newelev[max_i]
# fit data with 2d gaussian function
init_vals = (amplitude,xo,yo,self.sigx,self.sigy,self.theta)
best_vals, covar = opt.curve_fit(self.gaussian_2d, z, select, p0=init_vals)
perr = np.sqrt(np.diag(covar))
"""
self.info_fit['data'] = {'values': {'amp': best_vals[0], 'cenx': best_vals[1], 'ceny':best_vals[2],
'sigx': best_vals[3], 'sigy':best_vals[4], 'thet':best_vals[5], 'off':best_vals[6]},
'errors': {'amp': perr[0], 'cenx':perr[1], 'ceny':perr[2], 'sigx':perr[3],'sigy':perr[4],
'thet':perr[5],'off':perr[6]}}"""
self.info_fit['data'] = {'values': {'amp': best_vals[0], 'cenx': best_vals[1], 'ceny':best_vals[2],
'sigx': best_vals[3], 'sigy':best_vals[4], 'thet':best_vals[5]},
'errors': {'amp': perr[0], 'cenx':perr[1], 'ceny':perr[2], 'sigx':perr[3],'sigy':perr[4],
'thet':perr[5]}}
return best_vals, covar
def gauss_data(self):
"""
Interpolates data to a regular grid first (self.interp) then fits data
with 2d gaussian function and finds the best values and the
covariance matrix. Fit info is also stored in self.info_fit.
Parameters
----------
None
Returns
-------
best_vals, numpy array : best amp, cen and wid values for the gaussian
function
covar, numpy array : the estimated covariance of the optimal values for
the parameters best_vals; use perr = np.sqrt(np.diag(pcov)) to
compute one standard deviation errors on the parameters
See Also
--------
gauss_data_rad
"""
# interpolate and cut-off data for selected part if the scan
newazim, newelev, newdata = self.interp()
xn, yn = np.meshgrid(newazim, newelev)
z = (xn,yn)
# determine initial values
amplitude = np.nanmax(self.data[self.gate,:])
#offset = np.nanmin(self.data[self.gate,:])
max_i = np.nanargmax(self.data[self.gate,:])
yo = newelev[np.abs(newelev - self.elevation[max_i]).argmin()]
xo = newazim[np.abs(newazim - self.azimuth[max_i]).argmin()]
# fit data with 2d gaussian function
init_vals = (amplitude,xo,yo,self.sigx,self.sigy,self.theta)
best_vals, covar = opt.curve_fit(self.gaussian_2d, z, newdata.ravel(), p0=init_vals)
perr = np.sqrt(np.diag(covar))
"""
self.info_fit['data'] = {'values': {'amp': best_vals[0], 'cenx': best_vals[1], 'ceny':best_vals[2],
'sigx': best_vals[3], 'sigy':best_vals[4], 'thet':best_vals[5], 'off':best_vals[6]},
'errors': {'amp': perr[0], 'cenx':perr[1], 'ceny':perr[2], 'sigx':perr[3],'sigy':perr[4],
'thet':perr[5],'off':perr[6]}}"""
self.info_fit['data'] = {'values': {'amp': best_vals[0], 'cenx': best_vals[1], 'ceny':best_vals[2],
'sigx': best_vals[3], 'sigy':best_vals[4], 'thet':best_vals[5]},
'errors': {'amp': perr[0], 'cenx':perr[1], 'ceny':perr[2], 'sigx':perr[3],'sigy':perr[4],
'thet':perr[5]}}
return best_vals, covar
def gauss_elev(self):
"""
Fits elevation data with 1d gaussian function and finds the best values
and covariance matrix. Fit info is also stored in self.info_fit.
Parameters
----------
None
Returns
-------
best_vals, numpy array : best amp, cen and wid values for the gaussian
function
covar, numpy array : the estimated covariance of the optimal values for
the parameters best_vals; use perr = np.sqrt(np.diag(pcov)) to
compute one standard deviation errors on the parameters
"""
# find and reorganise data for selected part of the scan
ind, select = self.data_elev()
x = self.elevation[ind][::-1]
select = select[::-1]
# determine initial values
data_s = self.data[self.gate,:]
# convert data to linear values
max_i = np.nanargmax(data_s)
amplitude = data_s[max_i]
elevmid = self.elevation[max_i]
# fit data with id gaussian function
init_vals = [amplitude, elevmid, 2]
best_vals, covar = curve_fit(self.gaussian_1d, x, select, p0=init_vals)
perr = np.sqrt(np.diag(covar))
self.info_fit['elev'] = {'values': {'amp': best_vals[0], 'cen':best_vals[1], 'mid':best_vals[2]},
'errors': {'amp':perr[0], 'cen':perr[1], 'mid':perr[2]}}
return best_vals, covar
def gauss_azim(self):
"""
Fits azimuth data with 1d gaussian function and finds the best values
and covariance matrix
Parameters
----------
None
Returns
-------
best_vals, numpy array : best amp, cen and wid values for the gaussian
function
covar, numpy array : the estimated covariance of the optimal values for
the parameters best_vals; use perr = np.sqrt(np.diag(pcov)) to
compute one standard deviation errors on the parameters
"""
# find and reorganise data for selected part of the scan
ind, select = self.data_azim()
x = self.azimuth[ind][::-1]
select = select[::-1]
# determine initial values
data_s = self.data[self.gate,:]
max_i = np.nanargmax(data_s)
amplitude = data_s[max_i]
azimmid = self.azimuth[max_i]
# fit data with id gaussian function
init_vals = [amplitude, azimmid, 2]
best_vals, covar = curve_fit(self.gaussian_1d, x, select, p0=init_vals)
perr = np.sqrt(np.diag(covar))
self.info_fit['azim'] = {'values': {'amp': best_vals[0], 'cen':best_vals[1], 'mid':best_vals[2]},
'errors': {'amp':perr[0], 'cen':perr[1], 'mid':perr[2]}}
return best_vals, covar
def gaussian_1d(self, x, amp, cen, wid):
"""
1D gaussian function to which to fit the data
"""
return amp * np.exp(-(x-cen)**2 /wid)
def gaussian_2d(self, xy, amplitude, xo, yo, sigma_x, sigma_y, theta):
"""
2D gaussian function to which to fit the data
"""
xo = float(xo)
yo = float(yo)
x = xy[0]
y = xy[1]
a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)
b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)
c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)
#g = offset + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo)
#+ c*((y-yo)**2)))
g = amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo)
+ c*((y-yo)**2)))
return g.ravel()
## ------------------------get data functions------------------------ ##
## ------------------------------------------------------------------ ##
def data_2d(self):
"""
finds the optimum value and data around it in the both the azimuth and
elevation direction, which can then serve as input for a 2d gaussian
fit
Parameters
----------
None
Returns
-------
ind, list : indices of data around the optimum value
select, list : data around the optimum value
"""
# select data
data_s = self.data[self.gate,:]
# find location max value
max_i = np.nanargmax(data_s)
if self.azim is None:
azimmid = self.azimuth[max_i]
else:
azimmid = self.azim
if self.elev is None:
elevmid = self.elevation[max_i]
else:
elevmid = self.elev
azimmax = azimmid + self.doa
azimmin = azimmid - self.doa
elevmax = elevmid + self.doe
elevmin = elevmid - self.doe
# find indices and data
select = []
ind = []
for i in range(0,len(data_s)):
if self.azimuth[i] > azimmin and self.azimuth[i] < azimmax and self.elevation[i] > elevmin and self.elevation[i] < elevmax:
if np.isnan(data_s[i]):
pass
else:
ind.append(i)
select.append(data_s[i])
return ind, select
def data_2drad(self, polvar = None):
"""
finds the optimum value and data around it according to circle of
radius self.doa and stops at minval < self.cutdB which can then
serve as input dor a 2d gaussian fit
Parameters
----------
polvar, str : if given, extracts data for polvar instead of for the
polvar given in self.polvar
Returns
-------
ind, list : indices of data around optimum value
select, list : data around the optimum value
"""
# select data
if polvar is None:
data_e = self.data[self.gate,:]
data_s = self.data[self.gate,:]
maxval = self.cutdB
else:
data_e = self.data[self.gate,:]
data_s = self.file_handle.variables[polvar][self.gate, :]
maxval = -9999.
# find location max value
max_i = np.nanargmax(data_e)
if self.azim is None:
azimmid = self.azimuth[max_i]
else:
azimmid = self.azim
if self.elev is None:
elevmid = self.elevation[max_i]
else:
elevmid = self.elev
# find sphere indices for graphing
self.azim_sphere, self.elev_sphere = self.calc_sphere_coord(azimmid, elevmid, self.doa)
# find indices and data inside circle
select = []
ind = []
for i in range(0,len(data_s)):
x = self.azimuth[i]
y = self.elevation[i]
if np.sqrt((x - azimmid)**2 + (y-elevmid)**2) <= self.doa:
if np.isnan(data_s[i]):
pass
elif data_s[i] < maxval:
pass
else:
ind.append(i)
select.append(data_s[i])
return ind, select
def data_elev(self):
"""
finds the optimum value and data around it in the elevation direction,
which can then serve as input for a 1d gaussian fit
Parameters
----------
None
Returns
-------
ind, list : indices of data around the optimum value in the elevation
direction
select, list : data around the optimum value in the elevation direction
"""
# select data
data_s = self.data[self.gate,:]
# find location max value
max_i = np.nanargmax(data_s)
if self.azim is None:
azimmid = self.azimuth[max_i]
else:
azimmid = self.azim
azimmin = azimmid - 0.125
azimmax = azimmid + 0.125
#azimmin = azimmid - 0.2
#azimmax = azimmid + 0.2
if self.elev is None:
elevmid = self.elevation[max_i]
else:
elevmid = self.elev