-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodERec.py
executable file
·1838 lines (1477 loc) · 60.1 KB
/
modERec.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
##
#@mainpage
# PROTOTYPE Code for energy reconstruction \n
# Ready to read simulations from CORSIKA/Coreas \n
# This implementation is object oriented \n
# Date: September 16, 2019 \n \n
#
# A module to reconstruc the energy of events simulated using the Corsika/Coreas. \n\n
#
# The class EnergyRec is the main energy reconstruction class. \n \n
# It has the following inner classes: \n
# --> EnergyRec.Antenna which holds the antenna specific methods and variables.\n
# --> EnergyRec.AERA with AERA specific methods.\n
# --> EnergyRec.Shower that stores shower specific variables.\n
# --> EnergyRec.SymFit implements the symmetric signal fit.\n \n
# *** Updates on November 13, 2019:
# Eval_geo_ce_fluences implemented; \n
# EnergyRec.SymFit implemented.\n \n \n
# *** Updates on April 05, 2020:
# grand software fully integrated; \n
# Written by Bruno L. Lago
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import glob
import ctypes
from copy import deepcopy
from scipy.fftpack import fft, ifft
from scipy.signal import hilbert
from scipy import stats
from pathlib import Path
import math
from grand.simulation import ShowerEvent, ZhairesShower
import astropy.units as u
from astropy.coordinates import CartesianRepresentation
from grand import Rotation
class Antenna:
"""
A class for the antenna signal processing.
It has tools for the FFT, trace_recover and fluence evaluation.
Attributes
----------
ID:
An id for the antenna
fluence:
he total fluence.
sigma_f:
An estimate of the uncertainty of the fluence.
fluence_geo:
The geomagnetic component of the fluence
fluence_ce:
The charge ecess component of the fluence
fluence_evB:
The fluence on the evB direction
fluence_evvB:
The fluence on the evvB direction
wEarlyLate:
A weight to be used for the early-late correction
r_proj:
The position of the antenna in the shower plane
"""
## An id for the antenna
ID = None
## The total fluence.
fluence = None
## An estimate of the uncertainty of the fluence.
sigma_f = None
## The geomagnetic component of the fluence
fluence_geo = None
## The charge ecess component of the fluence
fluence_ce = None
## The fluence on the evB direction
fluence_evB = None
## The fluence on the evvB direction
fluence_evvB = None
## A wight to be used for the early-late correction
wEarlyLate = None
## The position of the antenna in the shower plane
r_proj = None
def __init__(self,ID):
"""
The default init function for the class Antenna.
"""
self.ID = ID
@staticmethod
def fft_filter(traces, nu_low = 50, nu_high = 200, bool_plot = False):
"""
Evaluates the FFT of the signal.
A filter is applied with width given by instance.antenna.nu_high and instance.antenna.nu_low.
Parameters
----------
traces:
The traces to be filtered
nu_low:
lower bound of the frequency band;
nu_high:
upper bound of the frequency band;
bool_plot: bool
toggles plots on and off;
Returns
-------
traces_fft: list
The Fourier transform of the traces.
"""
time_arr = traces[:,0]
trace1 = traces[:,1]
trace2 = traces[:,2]
trace3 = traces[:,3]
# Number of sample points
N = time_arr.size
# sample spacing
sampling_rate = 1/((time_arr[1]-time_arr[0])*1.e-9) # uniform sampling rate (convert time from ns to seconds)
T = 1/sampling_rate
yf1 = fft(trace1)
yf2 = fft(trace2)
yf3 = fft(trace3)
xf = np.linspace(0.0, 1.0/(2.0*T), N//2)
nu_low = nu_low * 10**6 # from MHz to Hz
nu_high = nu_high * 10**6 # from MHz to Hz
for i in range(xf.size):
if(xf[i]<nu_low or xf[i]>nu_high):
yf1[i]=0
yf1[-i]=0 # negative frequencies are backordered (0 1 2 3 4 -4 -3 -2 -1)
yf2[i]=0
yf2[-i]=0
yf3[i]=0
yf3[-i]=0
if(bool_plot):
fig = plt.figure(figsize=(15,3))
fig.suptitle('Fourier transform of the traces', fontsize=16,y=1)
plt.subplot(131)
plt.plot(xf, 2/N * np.abs(yf1[0:N//2]),'r')
#plt.xlabel("frequency in Hz")
plt.ylabel("signal in a.u.")
plt.xlabel("frequency in Hz")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.subplot(132)
plt.plot(xf, 2/N * np.abs(yf2[0:N//2]),'b')
plt.xlabel("frequency in Hz")
#plt.ylabel("signal in a.u.")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.subplot(133)
plt.plot(xf, 2/N * np.abs(yf3[0:N//2]),'k')
#plt.xlabel("frequency in Hz")
#plt.ylabel("signal in a.u.")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.show()
return np.c_[yf1, yf2, yf3]
@staticmethod
def trace_recover(t,traces_fft,bool_plot = False):
"""
Reconstructs the trace after the FFT and filter.
Parameters
----------
t:
The time array for the traces;
traces_fft:
The Fourier transform of the traces.
bool_plot: bool
toggles plots on and off;
Returns
-------
traces_rc: list
The reconstructed traces.
"""
yy1 = ifft(traces_fft[:,0]).real
yy2 = ifft(traces_fft[:,1]).real
yy3 = ifft(traces_fft[:,2]).real
xx = t-np.min(t)
if(bool_plot):
fig = plt.figure(figsize=(15,3))
fig.suptitle('Reconstructed traces in shower plane', fontsize=16,y=1)
plt.subplot(131)
plt.plot(xx, yy1.real,'r')
#plt.xlabel("time in ns")
plt.ylabel("signal in V/m")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.subplot(132)
plt.plot(xx, yy2.real,'b')
plt.xlabel("time in ns")
#plt.ylabel("signal in V/m")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.subplot(133)
plt.plot(xx, yy3.real,'k')
#plt.xlabel("time in ns")
#plt.ylabel("signal in V/m")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.show()
return np.c_[t,yy1, yy2, yy3]
@staticmethod
def hilbert_envelope(traces_rec, bool_plot = False):
r"""
Evaluates the hilbert envelope of the recunstructed traces.
.. math::
\mathcal{H}\{f(x)\}:=H(x)=\frac{1}{\pi}{\rm p.v.}\int_{-\infty}^\infty \frac{f(u)}{u-x}{\rm d}u
Parameters
----------
traces_rec:
The reconstructed traces.
bool_plot:
toggles plots on and off;
Returns
-------
hilbert: list
The hilbert envelopes [total, in evB direction, in evvB direction, in ev direction].
"""
tt = traces_rec[:,0]-np.min(traces_rec[:,0])
envelope1 = hilbert(traces_rec[:,1].real)
envelope2 = hilbert(traces_rec[:,2].real)
envelope3 = hilbert(traces_rec[:,3].real)
if(bool_plot):
fig = plt.figure(figsize=(15,3))
fig.suptitle('Hilbert Envelopes in the shower plane', fontsize=16,y=1)
plt.subplot(131)
plt.plot(tt,traces_rec[:,1].real, 'r', label='signal')
plt.plot(tt, np.abs(envelope1), label='envelope')
#plt.xlabel("time in ns")
plt.ylabel("signal in V/m")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.subplot(132)
plt.plot(tt,traces_rec[:,2].real, 'b', label='signal')
plt.plot(tt, np.abs(envelope2), label='envelope')
plt.xlabel("time in ns")
#plt.ylabel("signal in V/m")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.subplot(133)
plt.plot(tt,traces_rec[:,3].real, 'k', label='signal')
plt.plot(tt, np.abs(envelope3), label='envelope')
#plt.xlabel("time in ns")
#plt.ylabel("signal in V/m")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.show()
hilbert_env = np.sqrt(envelope1**2 + envelope2**2 + envelope3**2)
return np.c_[hilbert_env,envelope1,envelope2,envelope3]
def compute_fluence(self,t,hilbert_env, SNR_thres = 10, bool_plot = False):
r"""
Computes the fluence for a given antenna.
.. math::
f = \epsilon_0 c\left(\Delta t \sum_{t_1}^{t_2} \left| \vec{E}(t_i)\right|^2 - \Delta t \frac{t_2-t_1}{t_4-t_3} \sum_{t_3}^{t_4} \left| \vec{E}(t_i)\right|^2 \right)
It has a threshold for the SNR set by instance.SNR_thres.
Parameters
----------
self: modERec.EnergyRec.Antenna
A class instance.
t:
The time array for the traces;
hilbert_env:
The hilbert envelopes;
SNR_thres:
The signal to noise ratio threshold;
bool_plot: bool
toggles plots on and off;
Notes
-----
Fills self.fluence, self.fluence_geo, self.fluence_ce, self.fluence_evB and self.luence_evvB.
"""
tt = t-np.min(t)
delta_tt = (tt[1]-tt[0])*1e-9 # convert from ns to seconds
envelope2 = hilbert_env[:,0]**2.
tmean_index = np.where(envelope2==np.max(envelope2))[0][0] # Index of the hilbert envelope maximum
if(bool_plot):
plt.plot(tt,np.abs(envelope2))
plt.xlabel("time in nanoseconds")
plt.ylabel(r"E$^2$ in V$^2$/m$^2$")
plt.show()
if(tt[-1]-tt[tmean_index] < 150):
#print("Peak too close to the end of the signal. Skipping")
self.fluence = -2e-5
self.fluence_geo = -2e-5
self.fluence_ce = -2e-5
self.fluence_evB = -2e-5
self.fluence_evvB = -2e-5
return
time_100ns_index = np.where(tt<=100)[0][-1] # Index of 100 ns bin
if(tmean_index<time_100ns_index):
#tmean_index = time_100ns_index
#print("Peak too close to the beginning of the signal. Skipping")
self.fluence = -1e-5
self.fluence_geo = -1e-5
self.fluence_ce = -1e-5
self.fluence_evB = -1e-5
self.fluence_evvB = -1e-5
return
t1 = tt[tmean_index-time_100ns_index]
t2 = tt[tmean_index+time_100ns_index]
if(tmean_index < tt.size//2):
# background from the end of the trace
t3 = tt[-1-2*time_100ns_index]
t4 = tt[-1]
else:
# background from the beginning of the trace
t3 = tt[0]
t4 = tt[2*time_100ns_index]
signal = np.sum(np.abs(envelope2)[(tt>=t1) & (tt<=t2)])*delta_tt # N^2 * Coulomb^-2 * s
bkg = np.sum(np.abs(envelope2)[(tt>=t3) & (tt<t4)])*delta_tt*(t2-t1)/(t4-t3)
epsilon0 = 8.8541878128e-12 # Coulomb^2 * N^-1 * m^-2
c = 299792458 # m * s^-1
Joule_to_eV = 1/1.602176565e-19
SNR = np.sqrt(signal/bkg)
if(SNR>SNR_thres):
my_fluence = epsilon0*c* (signal - bkg)*Joule_to_eV # eV * m^-2
self.fluence = my_fluence
signal_evB = np.sum(np.abs(hilbert_env[:,1]**2.)[(tt>=t1) & (tt<=t2)])*delta_tt
bkg_evB = np.sum(np.abs(hilbert_env[:,1]**2.)[(tt>=t3) & (tt<t4)])*delta_tt*(t2-t1)/(t4-t3)
self.fluence_evB = (signal_evB - bkg_evB)*epsilon0*c*Joule_to_eV
signal_evvB = np.sum(np.abs(hilbert_env[:,2]**2.)[(tt>=t1) & (tt<=t2)])*delta_tt
bkg_evvB = np.sum(np.abs(hilbert_env[:,2]**2.)[(tt>=t3) & (tt<t4)])*delta_tt*(t2-t1)/(t4-t3)
self.fluence_evvB = (signal_evvB-bkg_evvB)*epsilon0*c*Joule_to_eV
else:
self.fluence = -1
self.fluence_evB = -1
self.fluence_evB = -1
@staticmethod
def offset_and_cut(traces, bool_cut = True):
"""
Performs cuts and offsets the traces.
The offset prevents problems due to traces too close to the time origin.
The cut, reduces the time window to speed up the code.
Parameters
----------
traces:
The traces to be cut;
bool_cut:
Toggles the bandwith cut;
Returns
-------
traces_cut: list
The cut traces.
"""
traces0 = traces[:,0]
deltat = traces0[1]-traces0[0]
min_time = traces0[0]
offset = int(100/deltat)
extra_time = np.linspace(min_time-offset*deltat,min_time-1,offset)
traces0 = np.insert(traces[:,0],0,extra_time)
traces1 = np.insert(traces[:,1],0,np.zeros(offset))
traces2 = np.insert(traces[:,2],0,np.zeros(offset))
traces3 = np.insert(traces[:,3],0,np.zeros(offset))
my_traces = np.c_[traces0,traces1,traces2,traces3]
if(bool_cut):
global_peak = np.max(np.abs(my_traces[:,1:4]))
peak_index = np.where(np.abs(my_traces[:,1:4])==global_peak)[0][0]
peak_time = my_traces[:,0][peak_index]
sel = ((my_traces[:,0]>peak_time-1000) & (my_traces[:,0]<peak_time+1000))
return my_traces[sel,0:4]
class Shower:
r"""
A class for the shower parameters.
Attributes
----------
ev:
Unitary along :math:`\vec{v}`.
eB:
Unitary along :math:`\vec{B}`.
evB:
Unitary along :math:`\vec{v}\times\vec{B}`.
evvB:
Unitary along :math:`\vec{v}\times\vec{v}\times\vec{B}`.
thetaCR:
The shower zenith in deg.
phitCR:
The shower azimuth in deg.
ECR:
The cosmic ray energy
r_Core_proj:
The position of the core projected into the shower plane.
bool_plot: bool
Toggles the plots on and off.
d_Xmax:
Distance to Xmax from the simultaion.
"""
## Unitary along \f$\vec{v}\f$.
ev = None
## Unitary along \f$\vec{B}\f$.
eB = None
## Unitary along \f$\vec{v}\times\vec{B}\f$.
evB = None
## Unitary along \f$\vec{v}\times\vec{v}\times\vec{B}\f$.
evvB = None
## The shower inclination.
thetaCR = None
## The shower azimuthal angle.
phiCR = None
## The energy of the shower.
ECR = None
## The position of the core projected into the shower plane.
r_Core_proj = None
## Toggles the plots on and off.
bool_plot = False
## Distance to Xmax.
d_Xmax = None
def __init__(self):
"""
The default init function for the class Shower.
Parameters
----------
self: modERec.EnergyRec.Shower
A class instance.
"""
class EnergyRec:
"""
A class for the energy reconstruction.
It has the inner classes: AERA, Antenna and Shower.
Attributes
----------
bool_plot: bool
Toggles the plots on and off (default: false).
bool_EarlyLate: bool
Toggles the early-late correction on and off (default: true).
nu_low:
The lower frequency of the signal filter in MHz (default: 50).
nu_high:
The upper frequency of the signal filter in MHz (default: 200).
SNR_thres:
The signal to noise ratio threshold (default: 10).
thres_low:
A initial lower threshold for selecting antennas in V/m (default: 0.1e-6).
thres_high:
A initial upper threshold for selecting antennas in V/m (default: 1).
f_thres:
A final lower threshold for selecting antennas in eV/m^2 (default: 0.01).
simulation: path, file
The path to the simulation directory or file (default: None).
antenna: modERec.EnergyRec.Antenna
An array of type modERec.EnergyRec.Antenna.
shower: modERec.EnergyRec.Shower
An instance of the class modERec.EnergyRec.Shower.
bestfit:
The bestfit values of the parameters (default: None).
GRANDshower:
The shower imported using the standard grand package(default: None).
printLevel: int
A print level variable (default: 0).
"""
## Toggles the plots on and off.
bool_plot = False
## Toggles the early-late correction on and off.
bool_EarlyLate = True
## The lower frequency of the signal filter in MHz.
nu_low = 50
## The upper frequency of the signal filter in MHz.
nu_high = 200
## The signal to noise ratio threshold.
SNR_thres = 10
## A initial lower threshold for selecting antennas in V/m.
thres_low = 0.1e-6
## A initial upper threshold for selecting antennas in V/m.
thres_high = 1
## A final lower threshold for selecting antennas in eV/m^2.
f_thres = 0.01
## The path to the simulation.
simulation = None
## An instance of the class Antenna
antenna = None
## An instance of the class Shower
shower = None
## The bestfit values of the parameters
bestfit = None
## The shower imported using the standard grand package
GRANDshower = None
## A print level variable
printLevel = 0
def __init__(self,simulation):
"""
The default init function for the class EnergyRec.
Parameters
----------
self: modERec.EnergyRec
A class instance.
simulation:
The path to the simulation directory or file.
"""
self.simulation = simulation
self.shower = Shower()
if Path(self.simulation).is_dir() or self.simulation.endswith('hdf5'):
if not self.simulation.startswith('Stshp_XmaxLibrary'):
self.GRANDshower = ShowerEvent.load(self.simulation)
else:
self.GRANDshower = ZhairesShower._from_datafile(self.simulation)
# Fixing Aires to GRAND conventions
for ant in range(len(self.GRANDshower.fields)):
self.GRANDshower.fields[ant].electric.E=self.GRANDshower.fields[ant].electric.E[0]
from astropy.coordinates.matrix_utilities import rotation_matrix
rotation = rotation_matrix(-90 * u.deg, axis='z')
self.GRANDshower.fields[ant].electric.E = self.GRANDshower.fields[ant].electric.E.transform(rotation)
self.GRANDshower.fields[ant].electric.r = self.GRANDshower.fields[ant].electric.r.transform(rotation)
self.GRANDshower.localize(latitude=45.5 * u.deg, longitude=90.5 * u.deg)
if Path(self.simulation).is_dir():
self.GRANDshower.localize(latitude=45.5 * u.deg, longitude=90.5 * u.deg)
n_ant = len(self.GRANDshower.fields)
self.antenna = [Antenna(ant) for ant in range(n_ant)]
self.shower_projection()
self.Eval_fluences()
#self.plot_antpos()
ev = self.GRANDshower.core - self.GRANDshower.maximum
ev /= ev.norm()
self.shower.ev = ev.xyz.value
evB = ev.cross(self.GRANDshower.geomagnet)
evB /= evB.norm()
self.shower.evB = evB.xyz.value
evvB = ev.cross(evB)
self.shower.evvB = evvB.xyz.value
eB = self.GRANDshower.geomagnet.xyz.value
eB /= np.linalg.norm(eB)
self.shower.eB = eB
self.early_late()
if(self.printLevel>0):
print("* EnergyRec instance starting values summary:")
print("--> bool_plot = ",self.bool_plot)
print("--> bool_EarlyLate = ",self.bool_EarlyLate)
print("--> nu_low = ",self.nu_low)
print("--> nu_high = ",self.nu_high)
print("--> SNR_thres = ",self.SNR_thres)
print("--> thres_low = ",self.thres_low)
print("--> thres_high = ",self.thres_high)
print("--> f_thres = ",self.f_thres)
print("\n")
elif Path(self.simulation).is_file():
self.model_fit(simulation)
else:
print("ERROR: ",self.simulation," not found!")
raise SystemExit("Stop right there!")
def simulation_inspect(self):
"""
Outputs theta, phi, Energy and the core position.
Parameters
----------
self: modERec.EnergyRec
A class instance.
"""
thetaCR = self.GRANDshower.zenith
phiCR = self.GRANDshower.azimuth
E = self.GRANDshower.energy
Core = self.GRANDshower.core
B = self.GRANDshower.geomagnet
print("* Simulation summary:")
print("--> thetaCR = ",thetaCR)
print("--> phiCR = ",phiCR)
print("--> E = ",E)
print("--> Core position = ", Core)
print("--> Geomagnetic field = ", B)
def inspect_antenna(self,id):
"""
Plots the traces for a given antenna.
Parameters
----------
self: modERec.EnergyRec
A class instance.
id: int
The antenna id.
"""
if(id<len(self.GRANDshower.fields)):
Ex = self.GRANDshower.fields[id].electric.E.x.to("V/m")
Ey = self.GRANDshower.fields[id].electric.E.y.to("V/m")
Ez = self.GRANDshower.fields[id].electric.E.z.to("V/m")
EvB = self.shower.traces_proj[id].x.to("V/m").value
EvvB = self.shower.traces_proj[id].y.to("V/m").value
Ev = self.shower.traces_proj[id].z.to("V/m").value
time = self.GRANDshower.fields[id].electric.t.to("ns")
global_peak = np.max(np.abs([Ex,Ey,Ez]))
peak_index = np.where(np.abs([Ex,Ey,Ez])==global_peak)[0][0]
peak_time = time[peak_index]
if(self.bool_plot):
fig = plt.figure(figsize=(15,3))
fig.suptitle('Traces', fontsize=16,y=1)
plt.subplot(131)
plt.plot(time,Ex,'r')
plt.ylabel("signal in V/m")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.subplot(132)
plt.plot(time,Ey,'b')
plt.xlabel("time in ns")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.subplot(133)
plt.plot(time,Ez,'k')
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
fig = plt.figure(figsize=(15,3))
fig.suptitle('Traces in shower plane', fontsize=16,y=1)
plt.subplot(131)
plt.plot(time,EvB,'r')
plt.ylabel("signal in V/m")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.subplot(132)
plt.plot(time,EvB,'b')
plt.xlabel("time in ns")
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.subplot(133)
plt.plot(time,Ev,'k')
ax = plt.gca()
ax.ticklabel_format(axis='y',style='sci',scilimits=(0,0))
plt.show()
def process_antenna(self, id):
"""
Process a given antenna for inspection.
For a given initialized antenna, performs offset and cut, fft, trace recover, hilbert envelope and computes the fluence.
Calls EnergyRec.Antenna.compute_fluence;
Parameters
----------
self: modERec.EnergyRec
A class instance.
"""
if(id<len(self.GRANDshower.fields)):
time = self.GRANDshower.fields[id].electric.t.to("ns").value
# Ex = self.GRANDshower.fields[id].electric.E.x.to("V/m").value
# Ey = self.GRANDshower.fields[id].electric.E.y.to("V/m").value
# Ez = self.GRANDshower.fields[id].electric.E.z.to("V/m").value
# traces = np.c_[time,Ex,Ey,Ez]
EvB = self.shower.traces_proj[id].x.to("V/m").value
EvvB = self.shower.traces_proj[id].y.to("V/m").value
Ev = self.shower.traces_proj[id].z.to("V/m").value
traces = np.c_[time,EvB,EvvB,Ev]
else:
print("ERROR: id = ",id," is out of the antenna array bounds!")
exit()
# Check if peak is within the threshold range
peak = np.max(np.abs(traces[:,1:4]))
if(peak < self.thres_low or peak > self.thres_high):
self.antenna[id].fluence = -1
return
traces_cut = Antenna.offset_and_cut(traces)
traces_fft = Antenna.fft_filter(traces_cut, self.nu_low, self.nu_high, self.bool_plot)
traces_rec = Antenna.trace_recover(traces_cut[:,0],traces_fft,self.bool_plot)
# Check if peak is within the threshold range after offset, cut and trace recover.
if(np.max(np.abs(traces_rec[:,1:4]))<self.thres_low):
self.antenna[id].fluence = -1
self.antenna[id].fluence_geo = -1
self.antenna[id].fluence_ce = -1
self.antenna[id].fluence_evB = -1
self.antenna[id].fluence_evvB = -1
return
else:
hilbert_env = Antenna.hilbert_envelope(traces_rec, self.bool_plot)
self.antenna[id].compute_fluence(traces_rec[:,0],hilbert_env,self.SNR_thres,self.bool_plot)
def Eval_fluences(self):
"""
Evaluates the geomagnetic and charge excess fluences for a set os antennas.
It has a lower threshold for the fluence f_thres.
Parameters
----------
self: modERec.EnergyRec
A class instance.
Notes
-----
Fills self.antenna.fluence, self.antenna.fluence_evB, self.antenna.fluence_evvB, self.antenna.fluence geo and self.antenna.fluence_ce for all antennas.
"""
n_ant = len(self.GRANDshower.fields)
step = int(n_ant/10)
counter = 0
if(self.printLevel>0):
print("* Evaluating the fluences:")
print("--> 0 % complete;")
for ant in self.antenna:
#Read traces or voltages
if ((ant.ID+1)%step == 0 and self.printLevel > 0):
print("-->",int((ant.ID+1)/(10*step)*100),"% complete;")
self.process_antenna(ant.ID)
if ant.fluence > 0:
ant.sigma_f = np.sqrt(ant.fluence)
if(ant.fluence > self.f_thres):
r_plane =ant.r_proj[0:2]
cosPhi = np.dot(r_plane,np.array([1,0]))/np.linalg.norm(r_plane)
sinPhi = np.sqrt(1-cosPhi*cosPhi)
my_fluence_geo = np.sqrt(ant.fluence_evB)-(cosPhi/sinPhi)*np.sqrt(ant.fluence_evvB)
ant.fluence_geo = my_fluence_geo*my_fluence_geo
ant.fluence_ce = ant.fluence_evvB/(sinPhi*sinPhi)
else:
ant.fluence_geo = -1
ant.fluence_ce = -1
if(self.printLevel>0):
print("\n")
def Eval_par_fluences(self,par):
"""
Evaluates the fluence par for a give set of parameters.
Uses bool_EarlyLate to toggle early-late correction.
Parameters
----------
self: modERec.EnergyRec
A class instance.
par: array
The parameters of the :math:`a_{ratio}` parametrization.
Returns
-------
fluence_par: array
Parametrized fluence array.
"""
fluence_arr = np.array([ant.fluence for ant in self.antenna])
n_ant = len(self.GRANDshower.fields)
fluence_par = np.zeros(n_ant)
eB = self.shower.eB
alpha = np.arccos(np.dot(self.shower.ev,eB))
d_Xmax = np.linalg.norm((self.GRANDshower.core - self.GRANDshower.maximum).xyz.value)
rho_Xmax = SymFit.rho(d_Xmax,-self.shower.ev)
for ant in self.antenna:
if(self.bool_EarlyLate and ant.wEarlyLate is not None):
weight = ant.wEarlyLate
else:
weight = 1
r_plane = ant.r_proj[0:2]*weight
fluence = ant.fluence_evB/(weight**2)
phi = np.arccos(np.dot(r_plane,np.array([1,0]))/np.linalg.norm(r_plane))
dist = np.linalg.norm((ant.r_proj - self.shower.r_Core_proj)[0:2])*weight
fluence_par[ant.ID] = SymFit.f_par_geo(fluence,phi,alpha,dist,d_Xmax,par,rho_Xmax)
return fluence_par
@staticmethod
def eval_mean_fluences(antpos_fluences):
r"""
Evaluates the fluence mean and sigma (stdev) for a given set of simulated fluences
Parameters
----------
antpos_fluences: list
An input with columns: id, x_proj, y_proj, fluence
Returns
-------
x: array
Antenna x positions in the shower plane.
y: array
Antenna y positions in the shower plane.
mean fluence: array
The mean fluence fluence in a given (x,y) position.
sigma_f: array
The unncertainty in the fluence (standard deviation).
"""
ID = antpos_fluences[:,0]
x_proj = antpos_fluences[:,1]
y_proj = antpos_fluences[:,2]
fluence_arr = antpos_fluences[:,3]
fluence_mean = {}
fluence_mean2 = {}
counter = {}
pos = {}
for i in range(len(fluence_arr)):
#label = str(x_proj[i]) + str(y_proj[i])
label = ID[i]
if label in counter:
counter[label] = counter[label] + 1
else:
counter[label] = 1
pos[label] = [x_proj[i],y_proj[i]]
if label in fluence_mean:
fluence_mean[label] += fluence_arr[i]
fluence_mean2[label] += fluence_arr[i]**2
else:
fluence_mean[label] = fluence_arr[i]
fluence_mean2[label] = fluence_arr[i]**2
f_mean = np.zeros(len(pos))
f_mean2 = np.zeros(len(pos))
r = np.zeros((len(pos),2))
trim_counter = {}
for key, value in counter.items():
if value < 2:
pos.pop(key)
index = 0
for key, value in pos.items():
label = key
f_mean[index] = fluence_mean[label]/counter[label]
f_mean2[index] = fluence_mean2[label]/counter[label]
r[index] = value
index += 1
return r[:,0], r[:,1], f_mean, np.sqrt(f_mean2-f_mean**2)
def plot_antpos(self):
"""
Plots the fluence and antenna positions in the site plane.
Parameters
----------
self: modERec.EnergyRec
A class instance.
"""
n_ant = len(self.GRANDshower.fields)
r_ant = np.zeros((n_ant,3))
for key, value in self.GRANDshower.fields.items():
r_ant[key]=value.electric.r.xyz.value
fluence_arr = np.array([ant.fluence for ant in self.antenna])
sel = np.where(fluence_arr>0)
fig= plt.figure(figsize=(10,7))
ax = plt.gca()
plt.scatter(r_ant[:,0][sel], r_ant[:,1][sel], c=fluence_arr[sel], cmap='viridis')
plt.xlabel("x (in m)")
plt.ylabel("y (in m)")
plt.colorbar().ax.set_ylabel(r"Energy fluence (eV/m$^2$)")
plt.show()
def signal_output(self):
"""
Prints the antena positions (in the shower plane) and fluences to a file.
The filename has the structure ``fluence_ShowerPlane_THETACR.out`` and is open with append option.
Parameters
----------
self: modERec.EnergyRec
A class instance.
"""
fluence_arr = np.array([ant.fluence for ant in self.antenna])
sel = np.where(fluence_arr>0)
signal = np.c_[self.shower.r_proj[sel],fluence_arr[sel]]