Repository navigation
Expand file tree
/
Copy pathshared_funcs.py
More file actions
1441 lines (1251 loc) · 53 KB
/
Copy pathshared_funcs.py
File metadata and controls
1441 lines (1251 loc) · 53 KB
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 ipython
# -*- coding: utf-8 -*-
from datetime import datetime, time, timedelta
import numpy as np
import console_colors as ccl
from scipy.io.netcdf import netcdf_file
from ShiftTimes import ShiftCorrection, ShiftDts
import os, argparse
import h5py
from h5py import File as h5
from numpy import (
mean, median, nanmean, nanmedian, std, nan,
isnan, min, max, zeros, ones, size, loadtxt
)
from os.path import isfile, isdir
if 'DISPLAY' in os.environ: # to avoid crash when running remotely
from pylab import figure, savefig, close, find, pause
import matplotlib.patches as patches
import matplotlib.transforms as transforms
#from read_NewTable import tshck, tini_icme, tend_icme, tini_mc, tend_mc, n_icmes, MCsig
#from z_expansion_gulisano import z as z_exp
_ERROR_ = ccl.Rn+' ### ERROR ###: '+ccl.W
def flags2nan(VAR, FLAG):
cond = VAR < FLAG
VAR = np.array(VAR)
VAR[~cond] = np.nan
return VAR
def date_to_utc(fecha):
utc = datetime(1970, 1, 1, 0, 0, 0, 0)
sec_utc = (fecha - utc).total_seconds()
return sec_utc
def selecc_data(data, tshk):
time = data[0] #[s] utc sec
rate = data[1]
day = 86400. # [seg]
utc = datetime(1970, 1, 1, 0, 0, 0, 0)
tshk_utc = (tshk - utc).total_seconds()
ti = tshk_utc - 10.*day # [seg] utc
tf = tshk_utc + 30.*day
cond = (time > ti) & (time < tf)
time = (time[cond] - tshk_utc) / day # [days] since shock
rate = rate[cond]
return (time, rate)
def selecc_window(data, tini, tend):
time = data[0] #[s] utc sec
y = data[1]
day = 86400. # [seg]
utc = datetime(1970, 1, 1, 0, 0, 0, 0)
tini_utc = (tini - utc).total_seconds() # [s] utc sec
tend_utc = (tend - utc).total_seconds() # [s] utc sec
ti = tini_utc # [seg] utc
tf = tend_utc
cond = (time > ti) & (time < tf)
time = (time[cond] - tini_utc) / day # [days] since 'ti'
y = y[cond]
return (time, y)
def enoughdata(var, fgap):
n = len(var)
ngood = len(find(~isnan(var)))
fdata = 1.*ngood/n # fraccion de data sin gaps
if fdata>=(1.-fgap):
return True
else:
return False
def averages_and_std(n_icmes, t_shck, ti_icme, dTday, nbin, t_utc, VAR, fgap):
day = 86400.
nok=0; nbad=0
adap = []
for i in range(n_icmes):
dT = (ti_icme[i] - t_shck[i]).total_seconds()/day # [day]
if dT>dTday:
dt = dT/nbin
t, var = selecc_window(
[t_utc, VAR],
t_shck[i], ti_icme[i]
)
if enoughdata(var, fgap): # pido q haya mas del 80% NO sean gaps
adap += [adaptar(nbin, dt, t, var)]
nok +=1
else:
continue
else:
print " i:%d ---> Este evento es muy chico!, dT/day:%g" % (i, dT)
nbad +=1
VAR_adap = zeros(nbin*nok).reshape(nok, nbin)
for i in range(nok):
VAR_adap[i,:] = adap[i][1]
VAR_avrg = zeros(nbin)
VAR_std = zeros(nbin)
ndata = zeros(nbin)
for i in range(nbin):
cond = ~isnan(VAR_adap.T[i,:])
ndata[i] = len(find(cond)) # nro de datos != flag
VAR_avrg[i] = mean(VAR_adap.T[i,cond]) # promedio entre los valores q no tienen flag
VAR_std[i] = std(VAR_adap.T[i,cond]) # std del mismo conjunto de datos
tnorm = adap[0][0]
return [nok, nbad, tnorm, VAR_avrg, VAR_std, ndata]
def adaptar(n, dt, t, r):
#n = int(5./dt) # nro de puntos en todo el intervalo de ploteo
tt = zeros(n)
rr = zeros(n)
for i in range(n):
tmin = i*dt
tmax = (i+1.)*dt
cond = (t>tmin) & (t<tmax)
tt[i] = mean(t[cond])
rr[i] = mean(r[cond])
return [tt/(n*dt), rr]
def adaptar(nwndw, dT, n, dt, t, r):
#n = int(5./dt) # nro de puntos en todo el intervalo de ploteo
tt = zeros(n)
rr = zeros(n)
_nbin_ = n/(1+nwndw[0]+nwndw[1]) # nro de bins en la sheath
for i in range(n):
tmin = (i-nwndw[0]*_nbin_)*dt
tmax = tmin + dt
cond = (t>tmin) & (t<tmax)
tt[i] = mean(t[cond])#; print "tt:", t[i]; pause(1)
rr[i] = mean(r[cond])
return [tt/dT, rr] # tiempo normalizado x la duracion de la sheath
#@profile
def adaptar_ii(nwndw, dT, n, dt, t, r, fgap):
tt = zeros(n)
rr = zeros(n)
_nbin_ = n/(1+nwndw[0]+nwndw[1]) # nro de bins en la sheath/mc
cc = (t>0.) & (t<dT) # intervalo de la sheath/mc
#print " r[cc]: ", r[cc]
if len(r[cc])==0: # no hay data en esta ventana
rr = nan*ones(n)
enough = False
else:
enough = enoughdata(r[cc], fgap) # [bool] True si hay mas del 80% de data buena.
if not(enough):
rr = nan*ones(n) # si no hay suficiente data, este evento no aporta
for i in range(n):
tmin = (i-nwndw[0]*_nbin_)*dt
tmax = tmin + dt
cond = (t>=tmin) & (t<=tmax)
#tt[i] = mean(t[cond])#; print "tt:", t[i]; pause(1) # bug
tt[i] = tmin + .5*dt # bug corregido
if enough:
#cc = ~isnan(r[cond]) # no olvidemos filtrar los gaps
#rr[i] = mean(r[cond][cc])
rr[i] = nanmean(r[cond])
return enough, [tt/dT, rr] # tiempo normalizado x la duracion de la sheath/mc/etc
#@profile
def selecc_window_ii(nwndw, data, tini, tend):
time = data[0] #[s] utc sec
y = data[1]
day = 86400. # [seg]
utc = datetime(1970, 1, 1, 0, 0, 0, 0)
tini_utc = (tini - utc).total_seconds() # [s] utc sec
tend_utc = (tend - utc).total_seconds() # [s] utc sec
dt = tend_utc - tini_utc
ti = tini_utc - nwndw[0]*dt # [seg] utc
tf = tend_utc + nwndw[1]*dt
cond = (time > ti) & (time < tf)
time = (time[cond] - tini_utc) / day # [days] since 'ti'
y = y[cond]
return (time, y)
def averages_and_std_ii(nwndw,
SELECC, #MCsig, MCwant,
n_icmes, tini, tend, dTday, nbin, t_utc, VAR):
day = 86400.
nok=0; nbad=0
adap = []
for i in range(n_icmes):
dT = (tend[i] - tini[i]).total_seconds()/day # [day]
if ((dT>dTday) & SELECC[i]):# (MCsig[i]>=MCwant)):
dt = dT*(1+nwndw[0]+nwndw[1])/nbin
t, var = selecc_window_ii(
nwndw, # nro de veces hacia atras y adelante
[t_utc, VAR],
tini[i], tend[i]
)
adap += [adaptar(nwndw, dT, nbin, dt, t, var)] # rebinea usando 'dt' como el ancho de nuevo bineo
nok +=1
else:
print " i:%d ---> Filtramos este evento!, dT/day:%g" % (i, dT)
nbad +=1
VAR_adap = zeros(nbin*nok).reshape(nok, nbin)
for i in range(nok):
VAR_adap[i,:] = adap[i][1]
VAR_avrg = zeros(nbin)
VAR_medi = zeros(nbin)
VAR_std = zeros(nbin)
ndata = zeros(nbin)
for i in range(nbin):
cond = ~isnan(VAR_adap.T[i,:])
ndata[i] = len(find(cond)) # nro de datos != flag
VAR_avrg[i] = mean(VAR_adap.T[i,cond]) # promedio entre los valores q no tienen flag
VAR_medi[i] = median(VAR_adap.T[i,cond])# mediana entre los valores q no tienen flag
VAR_std[i] = std(VAR_adap.T[i,cond]) # std del mismo conjunto de datos
tnorm = adap[0][0]
return [nok, nbad, tnorm, VAR_avrg, VAR_medi, VAR_std, ndata]
def mvs_for_each_event(VAR_adap, nbin, nwndw, Enough, verbose=False):
nok = size(VAR_adap, axis=0)
mvs = zeros(nok) # valores medios por cada evento
binsPerTimeUnit = nbin/(1+nwndw[0]+nwndw[1]) # nro de bines por u. de tiempo
start = nwndw[0]*binsPerTimeUnit # en este bin empieza la estructura (MC o sheath)
for i in range(nok):
aux = VAR_adap[i, start:start+binsPerTimeUnit] # (*)
cc = ~isnan(aux) # pick good-data only
#if len(find(cc))>1:
if Enough[i]: # solo imprimo los q tienen *suficiente data*
if verbose:
print ccl.G + "id %d/%d: %r"%(i+1, nok, aux[cc]) + ccl.W
mvs[i] = mean(aux[cc])
else:
mvs[i] = nan
#(*): esta es la serie temporal (de esta variable) para el evento "i"
pause(1)
return mvs
def diff_dates(tend, tini):
n = len(tend)
diffs = np.nan*np.ones(n)
for i in range(n):
ok = type(tend[i]) == type(tini[i]) == datetime # ambos deben ser fechas!
if ok:
diffs[i] = (tend[i] - tini[i]).total_seconds()
else:
diffs[i] = np.nan
return diffs #[sec]
def write_variable(fout, varname, dims, var, datatype, comments):
dummy = fout.createVariable(varname, datatype, dims)
dummy[:] = var
dummy.units = comments
def calc_beta(Temp, Pcc, B):
# Agarramos la definicion de OMNI, de:
# http://omniweb.gsfc.nasa.gov/ftpbrowser/magnetopause/Reference.html
# http://pamela.roma2.infn.it/index.php
# Beta = [(4.16*10**-5 * Tp) + 5.34] * Np/B**2 (B in nT)
#
beta = ((4.16*10**-5 * Temp) + 5.34) * Pcc/B**2
return beta
def thetacond(ThetaThres, ThetaSh):
"""
Set a lower threshold for shock orientation, using Wang's
catalog of shocks.
NOTE: Near 180Â means very close to the nose!
"""
if ThetaThres<=0.:
print ccl.Rn + ' ----> BAD WANG FILTER!!: ThetaThres<=0.'
print ' ----> Saliendo...' + ccl.Rn
raise SystemExit
#return ones(len(ThetaSh), dtype=bool)
else:
return (ThetaSh > ThetaThres)
def wangflag(ThetaThres):
if ThetaThres<0:
return 'NaN'
else:
return str(ThetaThres)
def makefig(medVAR, avrVAR, stdVAR, nVAR, tnorm,
SUBTITLE, YLIMS, YLAB, fname_fig):
fig = figure(1, figsize=(13, 6))
ax = fig.add_subplot(111)
ax.plot(tnorm, avrVAR, 'o-', color='black', markersize=5, label='mean')
ax.plot(tnorm, medVAR, 'o-', color='red', alpha=.5, markersize=5, markeredgecolor='none', label='median')
inf = avrVAR + stdVAR/np.sqrt(nVAR)
sup = avrVAR - stdVAR/np.sqrt(nVAR)
ax.fill_between(tnorm, inf, sup, facecolor='gray', alpha=0.5)
trans = transforms.blended_transform_factory(
ax.transData, ax.transAxes)
rect1 = patches.Rectangle((0., 0.), width=1.0, height=1,
transform=trans, color='blue',
alpha=0.3)
ax.add_patch(rect1)
ax.legend(loc='upper right')
ax.grid()
ax.set_ylim(YLIMS)
TITLE = SUBTITLE
ax.set_title(TITLE)
ax.set_xlabel('time normalized to MC passage time [1]', fontsize=14)
ax.set_ylabel(YLAB, fontsize=20)
savefig(fname_fig, format='png', dpi=180, bbox_inches='tight')
close()
def makefig_ii(mc, sh, YLIMS, YLAB, **kws):
"""
- ftext{bool}:
if False, we put the text in the title. Otherwise, we put
the text inside the figure, using `TEXT_LOC`{dict} as positions
- TEXT_LOC{dict}:
coordinates for the text inside the figure. The `TEXT_LOC['sh']`{2-tuple} are
the positions for the left part, and `TEXT_LOC['mc']`{2-tuple} for the right
part.
"""
#--- kws
ftext = kws.get('ftext', False)
TEXT = kws.get('TEXT', None)
TEXT_LOC = kws.get('TEXT_LOC', None)
fname_fig = kws.get('fname_fig', None)
#-------------------------------------
fmc,fsh = 3.0, 1.0 # escaleos temporales
#--- if figure is not given, create one
if 'fig' in kws:
fig, ax = kws['fig'], kws['ax']
else:
fig = figure(1, figsize=(13, 6))
ax = fig.add_subplot(111)
# catch the name of the observable
if 'varname' in kws:
varname = kws['varname']
else:
varname = fname_fig[:-4].split('_')[-1]
if(varname == 'Temp'):
mc.med /= 1.0e4; sh.med /= 1.0e4
mc.avr /= 1.0e4; sh.avr /= 1.0e4
mc.std_err /= 1.0e4; sh.std_err /= 1.0e4
YLIMS[0] /= 1.0e4; YLIMS[1] /= 1.0e4
if ftext:
TEXT_LOC['mc'][1] /= 1.0e4
TEXT_LOC['sh'][1] /= 1.0e4
# curvas del mc
time = fsh+fmc*mc.tnorm
cc = time>=fsh
ax.plot(time[cc], mc.avr[cc], 'o-', color='black', markersize=5)
ax.plot(time[cc], mc.med[cc], 'o-', color='red', alpha=.8, markersize=5, markeredgecolor='none')
# sombra del mc
inf = mc.avr + mc.std_err/np.sqrt(mc.nValues)
sup = mc.avr - mc.std_err/np.sqrt(mc.nValues)
ax.fill_between(time[cc], inf[cc], sup[cc], facecolor='gray', alpha=0.5)
trans = transforms.blended_transform_factory(
ax.transData, ax.transAxes)
rect1 = patches.Rectangle((fsh, 0.), width=fmc, height=1,
transform=trans, color='blue',
alpha=0.3)
ax.add_patch(rect1)
# curvas del sheath
time = fsh*sh.tnorm
cc = time<=fsh
ax.plot(time[cc], sh.avr[cc], 'o-', color='black', markersize=5)
ax.plot(time[cc], sh.med[cc], 'o-', color='red', alpha=.8, markersize=5, markeredgecolor='none')
# sombra del sheath
inf = sh.avr + sh.std_err/np.sqrt(sh.nValues)
sup = sh.avr - sh.std_err/np.sqrt(sh.nValues)
ax.fill_between(time[cc], inf[cc], sup[cc], facecolor='gray', alpha=0.5)
#trans = transforms.blended_transform_factory(
# ax.transData, ax.transAxes)
rect1 = patches.Rectangle((0., 0.), width=fsh, height=1,
transform=trans, color='orange',
alpha=0.3)
ax.add_patch(rect1)
ax.tick_params(labelsize=17)
ax.grid()
ax.set_ylim(YLIMS)
if ftext:
ax.text(TEXT_LOC['mc'][0], TEXT_LOC['mc'][1], TEXT['mc'], fontsize=22)
ax.text(TEXT_LOC['sh'][0], TEXT_LOC['sh'][1], TEXT['sh'], fontsize=22)
else:
if TEXT is not None:
ax.set_title(
'left: '+TEXT['sh']+'\n'
'right: '+TEXT['mc']
)
else:
pass # no text anywhere
ax.set_ylabel(YLAB, fontsize=27)
# if `varname` has any of these strings, plot in log-scale.
if any([(nm in varname) for nm in \
('beta','Temp', 'rmsB', 'rmsBoB', 'ratio')]):
ax.set_yscale('log')
else:
ax.set_yscale('linear')
ax.legend(loc='best', fontsize=20)
if 'fig' not in kws: # if figure not given, save to disk
ax.set_xlim(-2.0, 7.0)
ax.set_xlabel('time normalized to sheath/MC passage [1]', fontsize=25)
savefig(fname_fig, format='png', dpi=100, bbox_inches='tight')
close()
return None
else:
# return changes of passed figure
return fig, ax
#--- chekea q el archivo no repita elementos de la 1ra columna
def check_redundancy(fname, name):
f = open(fname, 'r')
dummy = {}
for line in f:
ll = line.split(' ')
varname = ll[0]
dummy[varname] = 0
dummy_names = dummy.keys()
dummy_set = set(dummy_names)
redundancy = len(dummy_set)<len(dummy_names)
overwriting = name in dummy_set
if redundancy or overwriting:
return True
else:
return False
class general:
def __init__(self):
self.name = 'name'
class dummy1:
def __init__(self,):
pass
class dummy2 (object):
"""
can be used:
>>> dd = dummy2()
>>> dd['name'] = [3,4,5]
>>> dd['name2'].time = [0,1,2,3,4]
"""
def __init__(self):
self.this = {}
def __getitem__(self, idx):
if not idx in self.this.keys():
self.this[idx] = dummy1()
return self.this[idx]
def set(self, name, attname, value):
if not name in self.this.keys():
self.this[name] = dummy1()
setattr(self.this[name], attname, value)
def keys(self,):
return self.this.keys()
class boundaries:
def __init__(self):
print self.__dict__
print dict(self)
def ff(self):
self.fg = 0.2
def nans(sh):
return np.nan*np.ones(sh)
def grab_time_domain(adap, check=False):
"""
Search for a valid time domain for
this `varname` and return.
If `check`==True, it checks that all time domains
are the same (for all `varname`s) unless a difference
of 10 times the numerical epsilon.
"""
na = len(adap)
# grab all posible time domains
found = False
for i in range(na):
for name in adap[i].keys():
if not(found):
tarr = adap[i][name][0]
if tarr is not None:
found = True
if found:
# we found a valid time domain (`tarr`)
if check:
# assume time array is 'np.float32'
eps32 = np.finfo(np.float32).eps
for i in range(na):
for name in adap[i].keys():
tarr_ = adap[i][name][0]
if tarr_ is not None:
# they differ at most in its
# numerical epsilon
ok = (tarr_-tarr<=eps32)
assert ok.prod(),\
" we have more than 1 valid time domain!!:\n%r\n\n%r"%(
tarr_, tarr)
return tarr
#--- didn't find any valid time domain
try:
# hung in debug mode
import pdb; pdb.set_trace()
except ImportError:
# ok, get out!
raise SystemExit(
'shut! none are valid time domains:\n %r'%t_array
)
class events_mgr(object):
def __init__(self, gral, FILTER, CUTS, bd, nBin, fgap, tb, z_exp, structure='mc', fparam='mc_V', verbose=True):
"""
structure: can be 'sh.mc', 'sh.i', 'mc', 'i', refering to sheath-of-mc,
sheath-of-icme, mc, and icme, respectively. This is to
use the proper mean values calculated in each structure.
"""
self.fparam = fparam
self.structure = structure
self.data_name = gral.data_name
self.FILTER = FILTER
self.CUTS = CUTS
self.bd = bd
self.nBin = nBin
self.fgap = fgap
self.tb = tb
self.z_exp = z_exp
self.dir_plots = gral.dirs['dir_plots']
self.dir_ascii = gral.dirs['dir_ascii']
self.gral = gral
self._dirs_ = gral.dirs
self.verbose = verbose
#self.f_sc = netcdf_file(gral.fnames[gral.data_name], 'r')
self.f_events = netcdf_file(gral.fnames['table_richardson'], 'r')
print " -------> archivos input leidos!"
#--- put False to all possible data-flags (all CR detector-names
# must be included in 'self.CR_observs')
self.names_ok = ('Auger_BandMuons', 'Auger_BandScals', 'Auger_scals', \
'McMurdo', 'ACE', 'ACE_o7o6', 'ACE1sec')
for name in self.names_ok:
read_flag = 'read_'+name
setattr(self, read_flag, False) # True: if files are already read
#--- names of CR observatories
self.CR_observs = ( #must **include** the 'load_data_..()' methods
'Auger_scals', 'Auger_BandMuons', 'Auger_BandScals',\
'McMurdo')
#--- just a check for load_data_.. methods
for att_name in dir(events_mgr): # iterate on all methods
if att_name.startswith('load_data_'):
att_suffix = att_name.replace('load_data_', '')
assert att_suffix in self.names_ok,\
" [-] ERROR: one of the methods '%s' is NOT taken into account in 'self.CR_observs' (%s) " % (att_name, att_suffix)
self.data_name_ = str(self.data_name) # nombre de la data input inicial (*1)
self.IDs_locked = False # (*2)
"""
(*1): si despues cambia 'self.data_name', me voy a dar
cuenta en la "linea" FLAG_001.
(*2): lock in lock_IDs().
True: if the id's of the events have been
fixed/locked, so that later analysis is
resctricted only with theses locked id's.
"""
#++++++++++ CORRECTION OF BORDERS ++++++++++
# IMPORTANTE:
# Solo valido para los "63 eventos" (MCflag='2', y visibles en ACE)
# NOTA: dan saltos de shock mas marcados con True.
# TODO: make a copy/deepcopy of `tb` and `bd`, so that we don't
# bother the rest of data_names (i.e. Auger_scals, Auger_BandMuons,
# etc.)
if FILTER['CorrShift']:
ShiftCorrection(ShiftDts, tb.tshck)
ShiftCorrection(ShiftDts, tb.tini_icme)
ShiftCorrection(ShiftDts, tb.tend_icme)
ShiftCorrection(ShiftDts, tb.tini_mc)
ShiftCorrection(ShiftDts, tb.tend_mc)
ShiftCorrection(ShiftDts, bd.tini)
ShiftCorrection(ShiftDts, bd.tend)
def run_all(self, _data_handler):
#----- seleccion de eventos
self.filter_events()
print "\n ---> filtrado de eventos (n:%d): OK\n" % (self.n_SELECC)
#----- load data y los shiftimes "omni"
self.load_files_and_timeshift_ii(_data_handler)
#----- rebineo y promedios
self.rebine()
self.rebine_final()
#----- hacer ploteos
self.make_plots()
#----- archivos "stuff"
self.build_params_file()
#@profile
def rebine(self, collect_only=False):
"""
rebineo de c/evento
"""
nvars = self.nvars #len(VARS)
n_icmes = self.tb.n_icmes
bd = self.bd
VARS = self.VARS
nbin = self.nBin['total']
nwndw = [self.nBin['before'], self.nBin['after']]
day = 86400.
#---- quiero una lista de los eventos-id q van a incluirse en c/promedio :-)
IDs = {}
Enough, nEnough = {}, {}
self.__ADAP__ = ADAP = [] # conjunto de varios 'adap' (uno x c/variable)
for varname in VARS.keys():
IDs[varname] = []
Enough[varname] = []
nEnough[varname] = 0 # counter
# recorremos los eventos:
nok, nbad = 0, 0
nnn = 0 # nro de evento q pasan el filtro a-priori
self.out = {}
if collect_only:
self.out['events_data'] = {} # bag to save data from events
ok = np.zeros(n_icmes,dtype=np.bool) # all `False` by default
for i in range(n_icmes):
try: #no todos los elementos de 'tend' son fechas (algunos eventos no tienen fecha definida)
# this 'i'-event must be contained in our data-base
ok[i] = date_to_utc(bd.tini[i]) >= self.t_utc[0] #True
ok[i] &= date_to_utc(bd.tend[i]) <= self.t_utc[-1]
if self.IDs_locked:
ok[i] &= i in self.restricted_IDs
except: # e.g. if `bd.{tini,tend}[i]` is NaN
ok[i] = False
for i in range(n_icmes):
#np.set_printoptions(4) # nro de digitos a imprimir al usar numpy.arrays
if not (ok[i] & self.SELECC[i]): #---FILTRO--- (*1)
print ccl.Rn, " id:%d ---> ok, SELECC: "%i, ok[i], self.SELECC[i], ccl.W
nbad +=1
continue
dT = (bd.tend[i] - bd.tini[i]).total_seconds()/day # [day]
ADAP += [ {} ] # agrego un diccionario a la lista
nnn += 1
print ccl.Gn + " id:%d ---> dT/day:%g" % (i, dT) + ccl.W
print self.tb.tshck[i]
nok +=1
if collect_only:
# evdata is just a pointer
evdata = self.out['events_data']['id_%03d'%i] = dummy2() #{}
# recorremos las variables:
for varname in VARS.keys():
dt = dT*(1+nwndw[0]+nwndw[1])/nbin
t, var = self.grab_window(
nwndw=nwndw, #rango ploteo
data=[self.t_utc, VARS[varname]['value']],
tini=bd.tini[i],
tend=bd.tend[i],
vname=varname, # for ACE 1sec
)
if collect_only:
evdata.set(varname, 'time', t)
evdata.set(varname, 'data', var)
#--- read average CR rates before shock/disturbance
if self.data_name in self.CR_observs: # is it CR data?
rate_pre = getattr(self, 'rate_pre_'+self.data_name)
var = 100.*(var - rate_pre[i]) / rate_pre[i]
#--- rebinea usando 'dt' como el ancho de nuevo bineo
out = adaptar_ii(
nwndw = nwndw,
dT = dT,
n = nbin,
dt = dt,
t = t,
r = var,
fgap = self.fgap
)
enough = out[0] # True: data con menos de 100*'fgap'% de gap
Enough[varname] += [ enough ]
ADAP[nok-1][varname] = out[1] # out[1] = [tiempo, variable]
if enough:
#import pdb; pdb.set_trace()
IDs[varname] += [i]
nEnough[varname] += 1
#NOTE: `ADAP` points to `self.__ADAP__`
print " ----> len.ADAP: %d" % len(ADAP)
self.__nok__ = nok
self.__nbad__ = nbad
self.out['nok'] = nok
self.out['nbad'] = nbad
self.out['IDs'] = IDs
self.out['nEnough'] = nEnough
self.out['Enough'] = Enough
def lock_IDs(self):
"""
This assumes that 'IDs' has only *one* key.
That is, len(IDs)=1 !!
"""
IDs = self.out['IDs']
varname = IDs.keys()[0]
self.restricted_IDs = IDs[varname]
self.IDs_locked = True
def rebine_final(self):
"""
rebineo de c/evento ... PARTE FINAL
"""
nvars = self.nvars #len(VARS)
VARS = self.VARS
nbin = self.nBin['total']
nwndw = [self.nBin['before'], self.nBin['after']]
day = 86400.
## salidas del 'self.rebine()'
ADAP = self.__ADAP__
Enough = self.out['Enough']
nEnough = self.out['nEnough']
IDs = self.out['IDs']
nok = self.out['nok']
nbad = self.out['nbad']
stuff = {} #[]
# Hacemos un lugar para la data rebineada (posible uso post-analisis)
if self.data_name==self.data_name_:
self.rebined_data = {} # creamos el diccionario UNA sola vez
for varname in VARS.keys():
if self.verbose:
print ccl.On + " -------> procesando: %s" % VARS[varname]['label']
print " nEnough/nok/(nok+nbad): %d/%d/%d " % (nEnough[varname], nok, nok+nbad) + ccl.W
VAR_adap = zeros((nok, nbin)) # perfiles rebineados (*)
# (*): uno de estos por variable
# recorro los 'nok' eventos q pasaron el filtro de arriba:
for i in range(nok):
VAR_adap[i,:] = ADAP[i][varname][1] # valores rebineados de la variable "j" para el evento "i"
self.rebined_data[varname] = VAR_adap
# valores medios de esta variable para c/evento
avrVAR_adap = mvs_for_each_event(VAR_adap, nbin, nwndw, Enough[varname], self.verbose)
if self.verbose:
print " ---> (%s) avrVAR_adap[]: \n" % varname, avrVAR_adap
VAR_avrg = zeros(nbin)
VAR_avrgNorm = zeros(nbin)
VAR_medi = zeros(nbin)
VAR_std = zeros(nbin)
ndata = zeros(nbin)
# recorremos bin a bin, para calular media, mediana, error, etc...
for i in range(nbin):
cond = ~np.isnan(VAR_adap.T[i,:]) # filtro eventos q no aportan data en este bin
ndata[i] = len(find(cond)) # nro de datos != nan
VAR_avrg[i] = np.mean(VAR_adap.T[i,cond]) # promedio entre los valores q no tienen flag
VAR_avrgNorm[i] = np.mean(VAR_adap.T[i,cond]/avrVAR_adap[cond])
VAR_medi[i] = np.median(VAR_adap.T[i,cond])# mediana entre los valores q no tienen flag
VAR_std[i] = np.std(VAR_adap.T[i,cond]) # std del mismo conjunto de datos
stuff[varname] = [VAR_avrg, VAR_medi, VAR_std, ndata, avrVAR_adap]
# NOTA: chekar q 'ADAP[j][varname][0]' sea igual para TODOS los
# eventos 'j', y para TODOS los 'varname'.
self.out['dVARS'] = stuff
self.out['tnorm'] = grab_time_domain(ADAP, check=True)
"""def __getattr__(self, attname):
if attname[:10]=='load_data_':
return self.attname"""
def load_files_and_timeshift_ii(self, _data_handler, obs_check=None):
"""
INPUT
-----
* _data_handler:
class that handles the i/o of the database related to 'data_name'.
* obs_check:
if not None, is a list of strings related to the names of
the observables of our interest. The idea is to make
sure that we are asking for variables that are included
in our database `self.VARS`.
"""
read_flag = 'read_'+self.data_name # e.g. self.read_Auger
if not(read_flag in self.__dict__.keys()): # do i know u?
setattr(self, read_flag, False) #True: if files are already read
#--- read data and mark flag as read!
if not( getattr(self, read_flag) ):
attname = 'load_data_'+self.data_name
dh = _data_handler(
input=self.gral.fnames[self.data_name],
)
# point to the method that selects data from
# a given window
self.grab_window = dh.grab_block # {method}
# grab/point-to data from disk
#NOTE: if self.FILTER['CorrShift']==True, then `self.tb` and
# `self.bd` will be shifted!
out = dh.load(data_name=self.data_name, tb=self.tb, bd=self.bd)
# attribute data pointers to `self`
for nm, value in out.iteritems():
# set `t_utc` and `VAR` to `self`
setattr(self,nm,value)
# check that we are grabbing observables of our
# interest
if obs_check is not None:
for nm in obs_check:
nm_ = nm+'.'+self.data_name
assert nm_ in self.VARS.keys(),\
" %s is not database list: %r"%(nm_, self.VARS.keys())
self.nvars = len(self.VARS.keys())
# mark as read
self.read_flag = True # True: ya lei los archivos input
#--- check weird case
assert self.data_name in self.names_ok,\
_ERROR_+" not on my list!: %s" % self.data_name+\
"\n Must be one of these: %r" % [self.names_ok]
def make_plots(self):
"""
#---- generar figuras y asciis de los perfiles promedio/mediana
"""
nBin = self.nBin
fgap = self.fgap
MCwant = self.FILTER['MCwant']
ThetaThres = self.CUTS['ThetaThres']
if self.FILTER['vsw_filter']:
v_lo, v_hi = self.CUTS['v_lo'], self.CUTS['v_hi']
else:
v_lo, v_hi = 0.0, 0.0 #estos valores significan q no hay filtro
if self.FILTER['z_filter_on']:
z_lo, z_hi = self.CUTS['z_lo'], self.CUTS['z_hi']
else:
z_lo, z_hi = 0.0, 0.0
if self.FILTER['B_filter']:
B_lo, B_hi = self.CUTS['B_lo'], self.CUTS['B_hi']
else:
B_lo, B_hi = 0.0, 0.0 #estos valores significan q no hay filtro
if self.FILTER['filter_dR.icme']:
dR_lo, dR_hi = self.CUTS['dR_lo'], self.CUTS['dR_hi']
else:
dR_lo, dR_hi = 0.0, 0.0 #estos valores significan q no hay filtro
nbin = (1+nBin['before']+nBin['after'])*nBin['bins_per_utime'] # [1] nro de bines q quiero en mi perfil promedio
#-------------------- prefijos:
# prefijo para filtro Wang:
if self.FILTER['wang']:
WangFlag = str(ThetaThres)
else:
WangFlag = 'NaN'
# prefijo gral para los nombres de los graficos:
if self.FILTER['CorrShift']:
prexShift = 'wShiftCorr'
else:
prexShift = 'woShiftCorr'
#-------------------------------
# nombres genericos...
DIR_FIGS = '%s/MCflag%s/%s' % (self.dir_plots, MCwant['alias'], prexShift)
DIR_FIGS += '/' + self._dirs_['suffix']
DIR_ASCII = '%s/MCflag%s/%s' % (self.dir_ascii, MCwant['alias'], prexShift)
DIR_ASCII += '/' + self._dirs_['suffix']
os.system('mkdir -p %s' % DIR_FIGS) # si no existe, lo creamos
os.system('mkdir -p %s' % DIR_ASCII) # (bis)
print ccl.On + " -------> creando: %s" % DIR_FIGS + ccl.W
print ccl.On + " -------> creando: %s" % DIR_ASCII + ccl.W
FNAMEs = 'MCflag%s_%dbefore.%dafter_fgap%1.1f' % (MCwant['alias'], nBin['before'], nBin['after'], fgap)
FNAMEs += '_Wang%s' % (WangFlag)
if self.FILTER['vsw_filter']: FNAMEs += '_vlo.%03.1f.vhi.%04.1f' % (v_lo, v_hi)
if self.FILTER['z_filter_on']: FNAMEs += '_zlo.%2.2f.zhi.%2.2f' % (z_lo, z_hi)
if self.FILTER['B_filter']: FNAMEs += '_Blo.%2.2f.Bhi.%2.2f' % (B_lo, B_hi)
if self.FILTER['filter_dR.icme']: FNAMEs += '_dRlo.%2.2f.dRhi.%2.2f' % (dR_lo, dR_hi)
if not self.FILTER['vsw_filter']:
FNAMEs += '_' # flag for post-processing, indicating
# there was no splitting
FNAME_ASCII = '%s/%s' % (DIR_ASCII, FNAMEs)
FNAME_FIGS = '%s/%s' % (DIR_FIGS, FNAMEs)
fname_nro = DIR_ASCII+'/'+'n.events_'+FNAMEs+'.txt'
#'w': write mode #'a': append mode
#---FLAG_001
if self.data_name==self.data_name_:
fnro = open(fname_nro, 'w')
else:
fnro = open(fname_nro, 'a') # si uso otra data input, voy anotando el nro
# de eventos al final del archivo 'fname_nro'
#-------------------------------------------------------------------
nvars = len(self.VARS)
for varname in self.VARS.keys():
fname_fig = '%s_%s.png' % (FNAME_FIGS, varname) #self.VARS[i][1])
print ccl.Rn+ " ------> %s" % fname_fig
ylims = self.VARS[varname]['lims'] #self.VARS[i][2]
ylabel = self.VARS[varname]['label'] #self.VARS[i][3]
average = self.out['dVARS'][varname][0]
mediana = self.out['dVARS'][varname][1] #self.out['dVARS'][i][4]
std_err = self.out['dVARS'][varname][2]
nValues = self.out['dVARS'][varname][3] # number of values aporting to each data bin
N_selec = self.out['nok'] #self.out['dVARS'][varname][0]
N_final = self.out['nEnough'][varname] #nEnough[i]
SUBTITLE = '# of selected events: %d \n\
events w/80%% of data: %d \n\
bins per time unit: %d \n\
MCflag: %s \n\
WangFlag: %s' % (N_selec, N_final, nBin['bins_per_utime'], MCwant['alias'], WangFlag)
makefig(mediana, average, std_err, nValues, self.out['tnorm'],
SUBTITLE, ylims, ylabel, fname_fig)
fdataout = '%s_%s.txt' % (FNAME_ASCII, varname) #self.VARS[i][1])
dataout = np.array([self.out['tnorm'] , mediana, average, std_err, nValues])
print " ------> %s\n" % fdataout + ccl.W
np.savetxt(fdataout, dataout.T, fmt='%12.5f')
#-------- grabamos nro de eventos selecc para esta variable
line = '%s %d %d\n' % (varname, N_final, N_selec)
fnro.write(line)
print ccl.Rn + " --> nro de eventos seleccionados: " + fname_nro + ccl.W
fnro.close()
#--- salidas (a parte de los .png)
self.DIR_ASCII = DIR_ASCII
self.FNAMEs = FNAMEs
def build_params_file(self):
"""
Construye archivo q tiene cosas de los eventos seleccionados:
- valores medios de los observables (B, Vsw, Temp, beta, etc)
- los IDs de los eventos
- duracion de los MCs y las sheaths
"""
DIR_ASCII = self.DIR_ASCII
FNAMEs = self.FNAMEs
#-------------------------------------------- begin: NC_FILE
print "\n*********************************** begin: NC_FILE"