-
Notifications
You must be signed in to change notification settings - Fork 0
/
stormrecon2.py
4523 lines (3555 loc) · 181 KB
/
stormrecon2.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 sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
#import os
#from matplotlib.dates import DateFormatter, MinuteLocator
#from matplotlib import dates
import datetime as DT
from . import tools as MT
from . import spherical_geometry as M_geo
from . import general as M
import imp
import matplotlib.dates as dates
import os
import warnings
import copy
class ID_tracker(object):
import datetime as datetime
def __init__(self, s, date=None):
self.string=s
#return self.string
def add_front(self, s, date=None):
if date:
now = self.datetime.datetime.now().strftime("%Y-%m-%dT%H:%M")
self.string=s+'.'+self.string+'_'+now
else:
self.string=s+'.'+self.string
self.string
def add_back(self, s, date=None):
if date:
now = self.datetime.datetime.now().strftime("%Y-%m-%dT%H:%M")
self.string=s+'.'+self.string+'_'+now
else:
self.string=self.string+'.'+s
self.string
def add(self, s, date=None):
self.add_front(s,date=date)
class plot_time_chunks_python2(object):
def __init__(self, time, f, data, pos, ax=None, fig=None, **kwargs):
#pos=[ 30, 60, 90]
self.f=f
self.data=data
self.time=time
self.pos=pos
#if isinstance(time[0], int):
# self.time_sec=time
#elif isinstance(time[0], np.datetime64):
# self.time_sec=MT.datetime64_to_sec(time)
# #start_date=str(np.datetime64(t).astype('M8[s]'))
#else:
# raise ValueError("unknown pos type")
#if isinstance(pos[0], int):
# self.pos=pos
#elif isinstance(pos[0], np.datetime64):
# print('print convert timeto sec')
# self.pos=MT.datetime64_to_sec(pos)
# #dates.date2num(time.astype(DT.datetime))
# #start_date=str(np.datetime64(t).astype('M8[s]'))
#else:
# raise ValueError("unknown pos type")
#print(self.time )
#print(self.data.shape)
#print('pos',self.pos)
if type(self.pos[0]) is tuple:
self.time_chu=data_chunks(self.time,self.pos, 0 )
self.data_chu=data_chunks(self.data,self.pos, 0 )
else:
self.time_chu=data_chunks_split(self.time,self.pos, 0 )
self.data_chu=data_chunks_split(self.data,self.pos, 0 )
#print(len(self.time_chu))
#print(len(self.data_chu))
#print(len(self.pos), self.pos[0])
self.Drawer=self.draw_next(**kwargs)
#ax=self.Drawer.next()
#contourfdata=plt.contourf(time_chu.next(),f,data_chu.next().T )
if ax is None:
self.ax=plt.gca()
else:
self.ax=ax
if fig is None:
self.fig=plt.gcf()
else:
self.fig=fig
#plt.show()
plt.ion()
self.cbarflag=True
def draw_next(self, **kwargs):
for i in range(len(self.pos)):
print(i)
#plt.show()
yield self.draw_fig(self.time_chu.next(), self.f, self.data_chu.next(), **kwargs)
#plt.close()
def draw_fig(self, time, f, data,clevs,ylim=None ,cmap=None, **kwargs):
import matplotlib.colors as colors
self.ax.clear()
time_local=time#time_chu.next()
data_local=data#data_chu.next()
print('time', time_local.shape)
print('data', data_local.shape)
#Figure=M.plot_periodogram(time_local,f[:],data_local[:,:], **kwargs)
#fig=plt.gcf()
#M.clevels(data_local[:,:], )
#Figure.imshow(shading=True, downscale_fac=None, anomalie=False,ax=(self.ax,self.fig), cbar=self.cbarflag)
#Figure.set_xaxis_to_days(int1=1, int2=2)
#Figure.ax.set_yscale("linear", nonposy='clip')
self.clevs=clevs
cmap=plt.cm.PuBuGn if cmap is None else cmap
shading='gouraud'
norm = colors.BoundaryNorm(boundaries=self.clevs, ncolors=256)
#self.cs=plt.contourf(time_local,f,data_local.T,self.clevs, **kwargs)
self.cs=plt.pcolormesh(time_local,f,data_local.T,cmap=cmap , norm=norm, shading=shading)
#self.ax.set_yscale("log", nonposy='clip')
if self.cbarflag is True:
self.cbar= plt.colorbar(self.cs,pad=0.01)#, Location='right')#
self.cbar.ax.aspect=100
self.cbar.outline.set_linewidth(0)
#self.cbar.set_label('Power db(' + self.data_unit + '^2/f ')
if ylim is not None:
self.ax.set_ylim(ylim[0], ylim[1])
#self.ax.set_xticklabels(time_local.astype('M8[D]')[trange][::6], minor=False)
#drawnow(draw_fig)
#draw_fig()# The drawnow(makeFig) command can be replaced
plt.draw()
self.cbarflag=False
#self.ax=Figure.ax
return self.ax
class plot_time_chunks(object):
def __init__(self, time, f, data, pos, ax=None, fig=None, **kwargs):
#pos=[ 30, 60, 90]
self.f=f
self.data=data
self.time=time
self.pos=pos
#if isinstance(time[0], int):
# self.time_sec=time
#elif isinstance(time[0], np.datetime64):
# self.time_sec=MT.datetime64_to_sec(time)
# #start_date=str(np.datetime64(t).astype('M8[s]'))
#else:
# raise ValueError("unknown pos type")
#if isinstance(pos[0], int):
# self.pos=pos
#elif isinstance(pos[0], np.datetime64):
# print('print convert timeto sec')
# self.pos=MT.datetime64_to_sec(pos)
# #dates.date2num(time.astype(DT.datetime))
# #start_date=str(np.datetime64(t).astype('M8[s]'))
#else:
# raise ValueError("unknown pos type")
#print(self.time )
#print(self.data.shape)
#print('pos',self.pos)
if type(self.pos[0]) is tuple:
self.time_chu=data_chunks(self.time,self.pos, 0 )
self.data_chu=data_chunks(self.data,self.pos, 0 )
else:
self.time_chu=data_chunks_split(self.time,self.pos, 0 )
self.data_chu=data_chunks_split(self.data,self.pos, 0 )
#print(len(self.time_chu))
#print(len(self.data_chu))
#print(len(self.pos), self.pos[0])
self.Drawer=self.draw_next(**kwargs)
#ax=self.Drawer.next()
#contourfdata=plt.contourf(time_chu.next(),f,data_chu.next().T )
if ax is None:
self.ax=plt.gca()
else:
self.ax=ax
if fig is None:
self.fig=plt.gcf()
else:
self.fig=fig
#plt.show()
plt.ion()
self.cbarflag=True
def draw_next(self, **kwargs):
for i in range(len(self.pos)):
print(i)
#plt.show()
yield self.draw_fig(self.time_chu.__next__(), self.f, self.data_chu.__next__(), **kwargs)
#plt.close()
def draw_fig(self, time, f, data,clevs,ylim=None ,cmap=None, **kwargs):
import matplotlib.colors as colors
self.ax.clear()
time_local=time#time_chu.next()
data_local=data#data_chu.next()
print('time', time_local.shape)
print('data', data_local.shape)
#Figure=M.plot_periodogram(time_local,f[:],data_local[:,:], **kwargs)
#fig=plt.gcf()
#M.clevels(data_local[:,:], )
#Figure.imshow(shading=True, downscale_fac=None, anomalie=False,ax=(self.ax,self.fig), cbar=self.cbarflag)
#Figure.set_xaxis_to_days(int1=1, int2=2)
#Figure.ax.set_yscale("linear", nonposy='clip')
self.clevs=clevs
cmap=plt.cm.PuBuGn if cmap is None else cmap
shading='gouraud'
norm = colors.BoundaryNorm(boundaries=self.clevs, ncolors=256)
#self.cs=plt.contourf(time_local,f,data_local.T,self.clevs, **kwargs)
self.cs=plt.pcolormesh(time_local,f,data_local.T,cmap=cmap , norm=norm,
shading=shading)
#self.ax.set_yscale("log", nonposy='clip')
if self.cbarflag is True:
self.cbar= plt.colorbar(self.cs,pad=0.01)#, Location='right')#
self.cbar.ax.aspect=100
self.cbar.outline.set_linewidth(0)
#self.cbar.set_label('Power db(' + self.data_unit + '^2/f ')
if ylim is not None:
self.ax.set_ylim(ylim[0], ylim[1])
#self.ax.set_xticklabels(time_local.astype('M8[D]')[trange][::6], minor=False)
#drawnow(draw_fig)
#draw_fig()# The drawnow(makeFig) command can be replaced
plt.draw()
self.cbarflag=False
#self.ax=Figure.ax
return self.ax
def data_chunks_split(data, pos, dim):
if type(data) is np.ndarray:
datalist=np.split(data,pos, 0)
for D in datalist:
yield D
elif type(data) is list:
raise ValueError("not porgrammed get")
print('list')
datalist=[]
for L in data:
print(L.shape)
#np.split(L,pos, 0)
datalist.append(np.split(L,pos, 0))
for k in range(len(datalist[:][1])):
print(k)
yield datalist[k][:]
def data_chunks(data, pos, dim):
if type(data) is np.ndarray:
datalist=list()
if dim == 0:
for pp in pos:
datalist.append(data[pp[0]:pp[1]])
elif dim ==1:
for pp in pos:
datalist.append(data[:,pp[0]:pp[1]])
for D in datalist:
yield D
elif type(data) is list:
raise ValueError("not porgrammed get")
print('list')
datalist=[]
for L in data:
print(L.shape)
#np.split(L,pos, 0)
datalist.append(np.split(L,pos, 0))
for k in range(len(datalist[:][1])):
print(k)
yield datalist[k][:]
class PointCollectorv3:
def __init__(self, ax, Drawer=None):
self.pointcount=0
line, = ax.plot([np.nan], [np.nan], marker="o", markersize=4, color="red")
lineD, = ax.plot([np.nan], [np.nan], marker="o", markersize=8, color="green")
self.line = line
self.lineD = lineD
self.xs = list(line.get_xdata())
self.ys = list(line.get_ydata())
self.D=[np.nan, np.nan]#line.get_xdata(), line.get_ydata())
self.slopes=list()
self.P1=[]
self.P2=[]
self.D=[]
#self.ax=ax
self.cid = line.figure.canvas.mpl_connect('button_press_event', self)
#self.cid =line.figure.canvas.mpl_connect('key_press_event', self)
self.Drawer=Drawer
def __call__(self, event):
print('click', event)
if (event.inaxes!=self.line.axes) & (self.Drawer is not None):
print('next chunk')
#self.fig.canvas.mpl_disconnect(self.cid)
newax=self.Drawer.next()
#newax=self.line.axes
#print(newax)
line, = newax.plot([np.nan], [np.nan], marker="o", markersize=4, color="red")
lineD, = newax.plot([np.nan], [np.nan], marker="o", markersize=8, color="green")
self.line=line
self.lineD = lineD
self.cid =newax.figure.canvas.mpl_connect('button_press_event', self)
self.pointcount=4
#return
if self.pointcount == 0:
self.pointcount+=1
self.xs.append(event.xdata)
self.ys.append(event.ydata)
self.P1=(event.xdata, event.ydata)
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw()
elif self.pointcount == 1:
self.pointcount+=1
self.xs.append(event.xdata)
self.ys.append(event.ydata)
self.P2=(event.xdata, event.ydata)
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw()
elif self.pointcount >= 2:
print('its 3')
self.pointcount=0
self.D1=(event.xdata,event.ydata)
self.slopes.append([self.P1, self.P2, self.D1])
self.D.append(self.D1)
self.D.append((np.nan,np.nan) )
self.xs.append(np.nan)
self.ys.append(np.nan)
#P1=[]
#P2=[]
#D=[]
self.lineD.set_data(event.xdata, event.ydata)
self.lineD.figure.canvas.draw()
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw()
class PointCollectorv4:
def __init__(self, ax, Drawer=None):
self.pointcount=0
line, = ax.plot([np.nan], [np.nan], marker="o", markersize=4, color="red")
lineD, = ax.plot([np.nan], [np.nan], marker="o", markersize=8, color="green")
self.line = line
self.lineD = lineD
self.xs = list(line.get_xdata())
self.ys = list(line.get_ydata())
self.D=[np.nan, np.nan]#line.get_xdata(), line.get_ydata())
self.slopes=list()
self.P1=[]
self.P2=[]
self.D=[]
#self.ax=ax
self.cid = line.figure.canvas.mpl_connect('button_press_event', self)
#self.cid =line.figure.canvas.mpl_connect('key_press_event', self)
self.Drawer=Drawer
def __call__(self, event):
print('click', event)
if (event.inaxes!=self.line.axes) & (self.Drawer is not None):
print('next chunk')
#self.fig.canvas.mpl_disconnect(self.cid)
newax=self.Drawer.next()
line, = newax.plot([np.nan], [np.nan], marker="o", markersize=4, color="red")
lineD, = newax.plot([np.nan], [np.nan], marker="o", markersize=8, color="green")
self.line=line
self.lineD = lineD
self.cid =newax.figure.canvas.mpl_connect('button_press_event', self)
self.pointcount=4
#newax.figure.canvas.draw()
#return
if self.pointcount == 0:
self.pointcount+=1
self.xs.append(event.xdata)
self.ys.append(event.ydata)
self.P1=(event.xdata, event.ydata)
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw()
elif self.pointcount == 1:
self.pointcount+=1
self.xs.append(event.xdata)
self.ys.append(event.ydata)
self.P2=(event.xdata, event.ydata)
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw()
elif self.pointcount >= 2:
print('its 3')
self.pointcount=0
self.D1=(event.xdata,event.ydata)
self.slopes.append([self.P1, self.P2, self.D1])
self.D.append(self.D1)
self.D.append((np.nan,np.nan) )
self.xs.append(np.nan)
self.ys.append(np.nan)
#P1=[]
#P2=[]
#D=[]
self.lineD.set_data(event.xdata, event.ydata)
self.lineD.figure.canvas.draw()
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw()
def create_listofstorms(slopes, hist=None):
storm=dict()
list_of_storms=dict()
list_of_storms['P1']=[]
list_of_storms['P2']=[]
list_of_storms['D']=[]
hist='list of storms' if hist is None else MT.write_log(hist, 'list of storms')
for s in slopes:
#print(s, len(np.array(s)))
if (sum([None in ss for ss in s]) != 0) or (np.isnan(np.array(s)).any()):
print('None or NAN values, line Skipped:')
print(s)
hist=MT.write_log(hist, 'None or NAN values, line Skipped:'+str(s))
warnings.warn("Some Point are Nan or None")
else:
if s[0][1] > s[1][1]: #pente descendante
P1, P2 = s[1] , s[0]
else:
P2, P1 = s[1] , s[0] #P1:premiere arrivee P2: derniere arrivee
D=s[2] #liste des points verts
list_of_storms['P1'].append(P1)
list_of_storms['P2'].append(P2)
list_of_storms['D'].append(D)
list_of_storms['hist']=hist
return list_of_storms
#def ID_builder(Station, Pol, )
def convert_slope_intersect_to_MS1957(slope, intersect, realtime, verbose=False, as_Dataframe=True):
"""
this function converts the nondimentional slope and intersect to
a radial distance in meters and a inital time as datetime64
"""
Tmin1= realtime[-1]
T0 = realtime[0]
Dt = (Tmin1-T0)
if intersect.size > 1:
import pandas as pd
t0 = pd.to_datetime(realtime[0]) + pd.to_timedelta(intersect *Dt)
else:
t0 = Dt * intersect + T0
if verbose:
print(T0)
print(Dt)
# intersect_adjusted=Storm.cal_intersect_adjust(params) ## add adjustedintersect here!! estiamted line goes now thourgh maximumo fthe model
# t0_peak = Dt * intersect_adjusted + T0
Dt_sec=Dt.astype('m8[s]').astype(float)
dfdt= slope / Dt_sec
g=9.8196
r0= g /(4*np.pi*dfdt )
if as_Dataframe:
import pandas as pd
return pd.DataFrame(data={'r0':r0 , 't0':t0 })
else:
return r0, t0
def convert_geo_time_to_dt64(geo):
import copy
S=copy.deepcopy(geo)
for k,I in S.iteritems():
if type(I) is list:
S[k][0]=MT.sec_to_dt64(np.array(I[0]))
elif isinstance(I, np.ndarray):
S[k]=MT.sec_to_dt64(I)
S['t0']=MT.sec_to_dt64(np.array(S['t0']))
S['t0R']=MT.sec_to_dt64(np.array(S['t0R']))
S['t0L']= MT.sec_to_dt64(np.array(S['t0L']))
return S
def convert_geo_time_to_float_plot(geo):
import copy
S=copy.deepcopy(geo)
converter=MT.sec_to_float_plot_single
for k,I in S.iteritems():
if type(I) is list:
S[k][0]=converter(I[0])
elif isinstance(I, np.ndarray):
S[k]=MT.sec_to_float_plot(I)
S['t0']=converter(np.array(S['t0']))
S['t0R']=converter(np.array(S['t0R']))
S['t0L']= converter(np.array(S['t0L']))
#elif type(I) is float:
# S[k]=MT.sec_to_dt64(np.array(I))
return S
class Storm(object):
def __init__(self, ID):
self.ID=ID
self.hist='------ | '+ self.ID
self.write_log('initialized')
self.fit_dict=False
self.SM_dict_pandas=None
#if S is None:
#date,
def create_storm_geo(self, P1, P2, D, f, **karg):
self.f=f
self.geo=self.geometry(P1, P2, D, **karg)
self.write_log('created geometry')
def geometry(self, P1, P2, D, f_margins=0.001):
#print(P1, P2, D)
f=self.f
mf=(P2[0]-P1[0])/(P2[1]-P1[1])
t0=P1[0]- mf * P1[1]
t0R=D[0]- mf * D[1]
delta_t=abs(t0R-t0)
if t0R > t0:
t0L=t0-delta_t
else:
t0L=t0R
t0R=t0+delta_t
f_low=P1[1]-f_margins
f_high=P2[1]+f_margins
bound_r=mf*f + t0R
bound_l=mf*f + t0L
cline=mf*f+t0
t0_75l=t0-delta_t*.5
line75left=mf*f+t0-delta_t*.5
return {'P1': P1, 'P2': P2, 'D': D,
'mf': mf, 't0': t0, 't0R':t0R,'t0L':t0L,'t0_75l':t0_75l,
'delta_t':delta_t, 'bound_r':bound_r, 'bound_l':bound_l,
'f_low':f_low, 'f_high':f_high,
'cline':cline, 'line75left':line75left, 'f_margins':f_margins}
def plot_stormgeometry(self, time_flag='sec'):
self.write_log('plotted geometry')
f=self.f
if time_flag == 'sec':
S=self.geo
elif time_flag == 'dt64':
S=convert_geo_time_to_dt64(self.geo)
elif time_flag == 'float_plot':
S=convert_geo_time_to_float_plot(self.geo)
else:
raise ValueError("unknown time_flag")
print(S['D'][0],S['D'][1])
plt.plot(S['D'][0],S['D'][1],'.',color='g', markersize=20)
plt.plot(S['P1'][0],S['P1'][1],'.', c='r', markersize=20)
plt.plot(S['P2'][0],S['P2'][1],'.', c='r', markersize=20)
plt.plot(S['t0'],0,'.', c='orange', markersize=20)
plt.plot(S['t0R'],0,'.', c='orange', markersize=20)
plt.plot(S['t0L'],0,'.', c='orange', markersize=20)
plt.plot(S['cline'],f, c='k')
plt.plot(S['bound_r'],f, c='grey')
plt.plot(S['bound_l'],f, c='green')
plt.plot(S['line75left'],f, c='red')
if time_flag == 'sec':
plt.plot(np.linspace(S['t0L'],S['bound_r'].max(), 10),np.ones(10)*S['f_low'], c='grey')
plt.plot(np.linspace(S['t0L'],S['bound_r'].max(), 10),np.ones(10)*S['f_high'], c='grey')
elif time_flag == 'dt64':
tx=np.arange(S['t0L'],S['bound_r'].max(), np.timedelta64(1, 'D'))
plt.plot(tx,np.ones(tx.size)*S['f_low'], c='grey')
plt.plot(tx,np.ones(tx.size)*S['f_high'], c='grey')
elif time_flag == 'float_plot':
tx=np.arange(S['t0L'],S['bound_r'].max(),1)
plt.plot(tx,np.ones(tx.size)*S['f_low'], c='grey')
plt.plot(tx,np.ones(tx.size)*S['f_high'], c='grey')
def plot_cutted_data(self, time_flag='float_plot', **karg ):
self.write_log('plotted cutted data')
from decimal import Decimal
mmin=np.nanmin(self.masked_data)
mmax=np.nanmax(self.masked_data)
self.clevs=np.linspace(mmin, mmax, 31)
#self.clevs=np.arange(0,1+.1,.1)*1e-5
self.cbarstr=['%.1e' % Decimal(p) for p in self.clevs]
Figure=M.plot_spectrogram(self.time_dict[time_flag],self.f,self.masked_data,
#clevs=clevs,
sample_unit='1/'+self.dt_unit,
ylim=[self.geo['f_low'], self.geo['f_high']], cmap=plt.cm.PuBuGn, clevs=self.clevs, **karg)#(0, .1))
Figure.imshow(shading=True, downscale_fac=None,anomalie=False, fig_size=[5, 2])
Figure.set_xaxis_to_days()
Figure.ax.set_yscale("linear", nonposy='clip')
Figure.ax.set_title(self.ID)
Figure.ax.set_ylim(-.001,max([.1, self.f.max()]))
Figure.cbar.set_ticks(self.clevs)
Figure.cbar.set_ticklabels(self.cbarstr)
Figure.F.make_clear_weak()
return Figure
def create_mask(self, time):
self.write_log('masked created')
f, S = self.f, self.geo
ll=np.vstack((S['bound_l'], S['bound_r']))
maskarray=np.logical_and(np.zeros(time.size), True)
#print(time)
dt=int(np.diff(time).mean())
for fi in range(f.size):
mask=M.cut_nparray(time,ll[:,fi][0]-dt, ll[:,fi][1]+dt)
maskarray=np.vstack((maskarray, mask))
maskarray=np.delete(maskarray, 0,0)
fmask=M.cut_nparray(f, S['f_low'], S['f_high'])
_, fmaskmesh=np.meshgrid(time, fmask)
self.mask_full=(fmaskmesh & maskarray).T
def cut_full_data(self, data):
self.data=np.copy(data)
self.data[self.mask_full == False]=np.nan
#return mdata
def cut_data(self, time_in, f_data, data, dt_unit, clevs):
import numpy.ma as ma
self.dt_unit=dt_unit
self.clevs=clevs
if type(time_in) is dict:
time=np.copy(time_in['sec'])
self.dt_sec=np.diff(time).mean()
else:
time=np.copy(time_in)
self.dt_sec=np.diff(time).mean()
self.create_mask(time)
fmask=M.cut_nparray(f_data, self.geo['f_low'], self.geo['f_high'])#np.logical_and(np.zeros(f_data.size)+1, True)
#adjsut geometry
#print(len(fmask))
self.f=self.f[fmask]
self.geo['cline']=self.geo['cline'][fmask]
self.geo['bound_r']=self.geo['bound_r'][fmask]
self.geo['bound_l']=self.geo['bound_l'][fmask]
self.geo['line75left']=self.geo['line75left'][fmask]
# test data shape with time shape
timemask=M.cut_nparray(time, self.geo['t0L'],self.geo['bound_r'].max())
#self.xlim=(self.geo['t0L'],self.geo['bound_r'].max())
#print(timemask)
#return time[timemask], S['masked_data'][:, timemask]
if type(time_in) is dict:
self.time=time[timemask]
self.time_dict=dict()
for k,I in time_in.iteritems():
self.time_dict[k]=I[timemask]
else:
self.time=time[timemask]
#print(fmask.shape)
#print(data.shape)
self.data=np.copy(data[timemask,:][:,fmask])
#print(self.data.shape)
self.mask=self.mask_full[timemask,:][:,fmask]
#print('mask full', self.mask_full.shape)
#print(self.mask.shape)
self.masked_data=np.copy(self.data)
#print(self.masked_data.shape, self.mask.shape)
self.masked_data[self.mask ==False]=np.nan
self.data_masked_array= ma.array(self.data, mask=self.mask)
self.write_log('cutted & assigned data of oroginal shape' + str(data.shape))
self.write_log('data cutted')
def load(self, path, verbose=False):
#load data and attibutes
D= MT.pickle_load(self.ID,path, verbose)
for k, v in D.items():
setattr(self, k, v)
self.hist= MT.json_load(self.ID,path, verbose)[0]
#if os.path.isfile(path+self.ID+'.h5'):
# with pd.HDFStore(path+self.ID+'.h5') as store2:
# #store2 = pd.HDFStore(path+self.ID+'x.h5')
# for k,I in store2.iteritems():
# setattr(self, k, I)
#store2.close()
#return A, B
def save(self, save_path, verbose=False):
import warnings
from pandas import HDFStore
from pandas.io.pytables import PerformanceWarning
self.write_log('data saved')
#save as an npy file with cPickle flag False
#+ Jason for meta data and par numbers.
if not isinstance(self.SM_dict_pandas, type(None)):
#SM_dic=self.SM_dict_pandas
#SM_dic.to_hdf(save_path+self.ID+'.h5','w' )
warnings.filterwarnings('ignore',category=PerformanceWarning)
with HDFStore(save_path+self.ID+'.h5') as store:
store['SM_dict']=self.SM_dict_pandas
#store['fit_dict']=self.S.fit_dict
#store['time_dict']=self.S.time_dict
#del self.SM_dict_pandas
#savedict=self.__dict__
#print(savedict)
savekeys=self.__dict__.keys()
savekyes_less= list(set(savekeys) - set(['weight_data1d', 'weight','weight1d', 'data1d', 'mask_full', 'minmodel']))
savedict=dict()
for k in savekyes_less:
savedict[k]=self.__dict__[k]
#deletelist=['weight_data1d', 'weight','weight1d', 'data1d', 'mask_full', 'minmodel']
#for key in deletelist:
# if key in savedict:
# del savedict[key]
MT.pickle_save(self.ID,save_path, savedict, verbose=verbose)
save_list=[self.hist]
if self.fit_dict:
from lmfit import Parameters
params=Parameters()
#print('fit dict!!')
for k,I in self.fit_dict.iteritems():
if type(I) is bool:
I=str(I)
save_list.append(self.fit_dict)
#MT.json_save(self.ID,save_path, [self.hist, self.fit_dict], verbose=verbose)
self.fitter.params.dump(open(save_path+self.ID+'.fittedparrms.json', 'w'))
MT.json_save(self.ID,save_path,save_list, verbose=verbose)
MT.save_log_txt(self.ID,save_path, self.hist, verbose=verbose)
def normalize_time(self):
time=np.copy(self.time_dict['sec'])
dt=np.diff(self.time_dict['sec']).mean()#G.dt_periodogram
time=(time-time[0])/dt#np.arange(0,time.size, 1)
self.time_dict['normalized']=(time)/(time[-1])
self.dt_sec=dt
def normalize_time_unit(self, t):
tp=np.copy(t)
#dt=np.diff(self.time_dict['sec']).mean()#G.dt_periodogram
return (tp-self.time_dict['sec'][0])/(self.time_dict['sec'][-1]-self.time_dict['sec'][0])
#return tp/self.time_dict['sec'][-1]
def denormalize_time_unit(self, t):
TN=np.copy(t)
#dt=np.diff(self.time_dict['sec']).mean()#G.dt_periodogram
return TN * (self.time_dict['sec'][-1]-self.time_dict['sec'][0]) + self.time_dict['sec'][0]
#return tp/self.time_dict['sec'][-1]
def slope_to_dfdt_normalized(self):
self.geo['slope_dfdt_norm']=self.dt_sec*self.time.size/self.geo['mf']
return self.geo['slope_dfdt_norm']
#def slope_dfdt_normalized_to_dt_normalize_df(self):
#self.geo['slope_dfdt_norm']=self.dt_sec*self.time.size/self.geo['mf']
#return self.geo['slope_dfdt_norm']
def intersect_sec_to_dfdt_normalized(self, t0_in_sec):
#return self.normalize_time_unit(t0_in_sec* self.geo['mf']/(self.geo['mf']-1) )
return self.intersect_norm_to_dfdt_normalized(self.normalize_time_unit(t0_in_sec))
def intersect_norm_to_dfdt_normalized(self, t0_in_norm):
local_slope=self.slope_to_dfdt_normalized()
return t0_in_norm* local_slope/(local_slope-1)
#def dfdt_intersect_to_intersect_norm(self, intersect):
# local_slope=self.slope_to_dfdt_normalized()
# return t0_in_norm* local_slope/(local_slope-1)
def substract_plain_simple(self, datasub=None, verbose=False):
import brewer2mpl
self.write_log('substract Plain use freq end points:')
if datasub is None:
datasub=self.data
self.write_log('used data')
else:
datasub=datasub
self.write_log('used prescribed data')
time=self.time_dict['normalized']
f=self.f
yu=datasub.T.mean(1)[-4:-1].mean()
yl=datasub.T.mean(1)[0:3].mean()
#yu=datasub.T.mean(1)[-1].mean()
#yl=datasub.T.mean(1)[0].mean()
m=(yu-yl)/(f[-1]-f[0])
yi =-m*f[0]+datasub.T.mean(1)[0]
y= m*f+yi
tt, yy=np.meshgrid(time, y)
resid= (datasub.T - yy).T
minpoint=0*abs(np.nanmin(resid))
resid=resid+minpoint
self.yy=yy+minpoint
self.masked_data=np.copy(resid)
#print(sum(np.isnan(self.masked_data)))
self.write_log('saved line as self.subtracted_plain')
self.masked_data[self.mask == False]=np.nan
self.write_log('updated self.masked_data')
if verbose:
F=M.figure_axis_xy(6,5, view_scale=.6)
plt.subplot(2,2, 1)
mmax=max(datasub.max(),-datasub.min())
cval=np.linspace(-mmax, mmax, 21)
cmap = brewer2mpl.get_map('Paired', 'qualitative', 6, reverse=False).mpl_colormap
plt.contourf(time, f, datasub.T, cval ,cmap=cmap)
plt.colorbar()
xlabelstr=(' ( time)')
#plt.ylabel(('|X|^2/f (' + data_unit + '^2/' + sample_unit+ ')'))
plt.xlabel(xlabelstr)
#plt.ylim(0.04,0.08)
plt.grid()
plt.subplot(2,2, 2)
plt.plot(f, datasub.T,c='r', alpha=.2)
plt.plot(f,y, c='k')
plt.plot(f, datasub.T.mean(1), c='r')
xlabelstr=('(Freq)')
#plt.ylabel(('|X|^2/f (' + data_unit + '^2/' + sample_unit+ ')'))
plt.xlabel(xlabelstr)
#plt.ylim(0.04,0.08)
plt.grid()
plt.subplot(2,2, 3)
#plt.contourf(time,f,, cval, cmap=cmap)
#plt.contourf(time,f, datasub.T - model_result_corse.reshape(time.size, f.size).T, cmap=cmap)
#plt.contourf(time,f, resid,cval, cmap=cmap)
plt.contourf(time,f, resid.T,cval, cmap=cmap)
plt.colorbar()
#plt.plot(time, fitter.params['tslope'].value*time+fitter.params['amp'])
xlabelstr=('(Time)')
#plt.ylabel(('|X|^2/f (' + data_unit + '^2/' + sample_unit+ ')'))
plt.xlabel(xlabelstr)
#plt.yticks(None)
#plt.ylim(0.04,0.08)
plt.grid()
plt.subplot(2,2, 4)
#plt.plot(f,(datasub.T - model_result_corse.reshape(time.size, f.size).T).mean(1), c='k', alpha=0.5)
#print(np.nanmean(resid.T, 1))
plt.plot(f, resid.T, c='b', alpha=0.2)
plt.plot(f, np.nanmean(resid.T, 1), c='b')
plt.plot(f, f*0, c='k')
xlabelstr=('(Freq)')
#plt.ylabel(('|X|^2/f (' + data_unit + '^2/' + sample_unit+ ')'))
plt.xlabel(xlabelstr)
#plt.ylim(0.04,0.08)
plt.grid()
plt.show
return resid
def substract_plain(self, datasub=None, wflag='ellipse', model='least_squares', fonly=False, verbose=False):
self.write_log('substract Plain:')
from lmfit import minimize, Parameters,Minimizer
import model_plain2d as minmodel
time=self.time_dict['normalized']
imp.reload(minmodel)
minmodel_flag='surface'
if minmodel_flag is 'plain':
model_residual_func=minmodel.residual_plain
elif minmodel_flag is 'surface':
model_residual_func=minmodel.residual_surface
f=self.f
params=Parameters()
if fonly:
vary=False
self.write_log('time slope prohbited')
else:
vary=True
self.write_log('time slope allowed')
if minmodel_flag is 'plain':
params.add('amp', value= 0, min=0, max=1)
params.add('tslope', value= 0, vary=vary)#, min=0, max=.002)
params.add('fslope', value= 0)#, min=0., max=1)
elif minmodel_flag is 'surface':
params.add('amp', value= 0, vary=False)
params.add('fslope', value= 200., min=100, max=1000.)
params.add('fp_par', value= 0., min=0., max=1000.)
if datasub is None:
datasub=self.data
self.write_log('used data')
else:
datasub=datasub
self.write_log('used prescribed data')
# Init model
model_init=model_residual_func(params, self.time_dict['normalized'], f, data=None, eps=None)
# reshape variables
data1d=datasub.reshape(datasub.shape[0]*datasub.shape[1])
# tracking Nans in 2d array
nan_track=np.isnan(data1d)
if wflag == 'data':