-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreatment_ML.py
365 lines (292 loc) · 14.2 KB
/
treatment_ML.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
''' this script bases on a script provided by S.LeCoz to filter, mimic digitization and add noise after applying an antenna response
It can be only applied for complete array or single antenna positions having array.dat and antpos.dat as file
hand over path to folder containing somulations and antenna files as argument: python treatment_ML.py folder_sim
-> out_*.txt as output from computevoltage.py
-> antpos.dat containing all antenna position with ID of all antennas which where included in the simulations
-> array.dat containing the antenna position of the whole field
=> output: fake_*.dat with the antenna ID following the lines in array.dat : time in s, EW/nuV, NS/muV (to be checked)
if antenna position in array.dat was not icnluded in the simulations, this script creates an empty trace and does the filtering, Digitization and the noise adding with it
-> all fake traces start and end at the same time. the time window can be adjusted to include the whole array by multiplying a factor to 3mus
=> prepare input for NEURAL NETWORK
'''
import numpy as np
from scipy.fftpack import rfft, irfft, rfftfreq
from random import *
import matplotlib.pyplot as plt
import sys
import os
def Filtering(v,tstep,FREQMIN,FREQMAX):
F=rfftfreq(len(v))/tstep #len(v) points between 0 and 1/2tstep
V=rfft(v)
V[F<FREQMIN]=0
V[F>FREQMAX]=0
return irfft(V)
def Digitization(v,t,tstep,TSAMPLING,SAMPLESIZE):
vf=np.zeros(SAMPLESIZE)
tf=np.zeros(SAMPLESIZE)
ratio=int(round(TSAMPLING/tstep))
ind=np.arange(0,int(np.floor(len(v)/ratio)))*ratio
#ind=np.arange(0,int(np.int(len(v)/ratio)))*ratio
if len(ind)>SAMPLESIZE:
ind=ind[0:TSAMPLING]
vf[0:len(ind)]=v[ind]
tf[0:len(ind)]=t[ind]
for k in range(len(ind),SAMPLESIZE):
tf[k]=tf[k-1]+TSAMPLING
return vf,tf
def Addnoise(vrms,v):
for i in range(len(v)):
v[i]=v[i]+gauss(0,vrms)
return v
DISPLAY=0 # show plots if wanted
path=str(sys.argv[1]) # path to folder conating all the simulated traces and antenna positions
# array.dat: containing all antennas of an array = 10 000
# antpos.dat: containing just the antenna positions which were actually simulated after cone approximation
# -> find antenna position from array.dat in antpos.dat -> get the index ID from antpos.dat -> get out_ID.txt
# -> if antenna position from array.daz not fournd in antpos.dat -> create zero array with time trace starting at 0ns, 2ns,....
#units:
TSAMPLING=2e-9 #sec, eq to 500 MHz, sampling of system
FREQMIN=50e6 #Hz # frequencies which will be used in the later analysis: 50-200MHz
FREQMAX=200e6 #Hz, 250MHz
#tstep=t[1]-t[0]#1e-9, sec, time bins in simulations
#print " time binning sims ", tstep
print 'original sampling per antenna', int(3e-6/TSAMPLING)
times=60 # multiply time window to cover times of complete array
SAMPLESIZE=int(times* 3e-6/TSAMPLING) #=times* 1500, times* 3e-6sec length # traces lenth of system# assuming ~times*1km extent of footprint along showeraxis
print 'new one ', SAMPLESIZE
vrms=15 #uvolts, noise level
### read in all time traces of the simulated antennas and try to find min(time) -> start_time for all antenna traces.
### produce zero-array to fill in the gap between start_time and minimum time of each antenna
### NOTE: dont forget to adjust the beginning of the time trace to the start_time for the non-simulated antenna position later
if len(sys.argv)<3: # grep all antennas from the antenna file
#positions=np.genfromtxt(path+'/antpos.dat')
#start=0
#end=len(positions)
#print end
positions=np.genfromtxt(path+'/MLtoy_antenna.list') # full list of antennas
#print positions.T[0]
for file in os.listdir(path):
if file.endswith(".inp"):
print(os.path.join(path, file))
filename=os.path.join(path, file)
infile = open(filename, 'r')
firstLine = infile.readline()
#print firstLine
core_y= (firstLine.split(' ',-1)[-1])
core_y= float(core_y.split(')',-1)[0])
#core_y=float("{0:.2f}".format(float(core_y)))
off_x=(firstLine.split(' ',-1)[11])
off_x=float(off_x.split(',',-1)[0])
#off_x=float("{0:.2f}".format(float(off_x)))
print off_x, core_y
positions.T[0]=positions.T[0]+off_x
positions.T[1]=positions.T[1]+core_y
start=0
end=len(positions.T[0])
pos=[]
for i in range(start,end):
entry="{0:.2f} {1:.2f} {2:.2f}".format(positions[i,0], positions[i,1], positions[i,2] )
entry=[float("{0:.2f}".format(positions[i,0] )),float("{0:.2f}".format(positions[i,1] )), float("{0:.2f}".format(positions[i,2] )) ]
pos.append( entry )
#end=len(positions.T[0])
#pos=positions.tolist()
#start=0
#stop
print "number of antennas in array ", end
positions_sim=np.genfromtxt(path+'/antpos.dat') # list of simulated antenns positions
pos_sim=positions_sim.tolist()
start_time=1.
end_time=0.
ant=0
ant2=0
##### find minimum and maximum time in whole array
for j in range(start,len(pos_sim)):
try:
#antenna_ID=pos_sim.index(pos[l]) # ID of simulated antenna
### field in muV and time in s
voltage_trace=path+"/out_"+str(j)+".txt"
#voltage_trace=path+"/a"+str(l)+".trace"#"/out_"+str(antenna_ID)+".txt"
try:
text=np.loadtxt(voltage_trace)#'
## if first time in simulated signal wanted
if start_time>min(text.T[0]):
start_time=min(text.T[0])
ant=l
#### if trigger time wanted
## find trigger time
#Vrms=15 # muV
#trigger = abs(text.T[1]+text.T[2]) > 3.*Vrms
#sel = np.where(trigger)[0][0] # first bin when value exceeded
#triggertime=text[sel,0]
##print sel, triggertime
#if start_time>triggertime:
#start_time=triggertime
#ant=j
if end_time<max(text.T[0]):
end_time=max(text.T[0])
ant2=l
except IndexError, ValueError:
continue
except:# ValueError, IndexError:
continue
print "starttime ", start_time, ant, "endtime ", end_time, ant2, "diff in s ", (end_time-start_time) , "compare to ", times* 3e-6, start_time+times* 3e-6
#print pos_sim
#print "\n"
#print pos
###### loop over l over all antennas in the full array list
for l in range(start,end):
print 'nr ', str(l)
## find the corresponding traces if antenna psoition was included in simulations
try:
# compare array position with actual antenna positions, if position simulated read in the out_ID.txt file
antenna_ID=pos_sim.index(pos[l]) # ID of simulated antenna
print " found ", antenna_ID
#NOTE: hand over path to file and antenna idea
voltage_trace=path+"/out_"+str(antenna_ID)+".txt"
print "try reading in ", voltage_trace
try:
text=np.loadtxt(voltage_trace)#'out_128.txt')
except IOError:
print "IOError ..."
continue
#### if trigger time wanted
#print "min(t) ", min(text[:,0]), "start_time ", start_time
#if (min(text[:,0]) < start_time): # get rid of the time bins before the signal starts
## NOTE Add here how to treat time traces which has to get shorten
## find time bin of same value
#a= np.where(text.T[0]==start_time)
#print a
#t=text[a:-1,0] # in s
#vx=text[a:-1,1] #EW axis antenna
#vy=text[a:-1,2] #NS axis antenna
#vz=text[a:-1,3] #vertical axis antenna
#else:
#t=text[:,0] # in s
#vx=text[:,1] #EW axis antenna
#vy=text[:,2] #NS axis antenna
#vz=text[:,3] #vertical axis antenna
t=text[:,0] # in s
vx=text[:,1] #EW axis antenna
vy=text[:,2] #NS axis antenna
vz=text[:,3] #vertical axis antenna
#DISPLAY=1
if DISPLAY==1:
plt.plot(t*1e9,vx) # s*1e9 = ns
#plt.plot(t*1e9,vy)
#plt.plot(t*1e9,vz)
#plt.xlabel('Time [ns]')
#plt.ylabel('Voltage [uV]')
#plt.title('raw voltage trace')
#plt.show()
tstep=t[5]-t[4]#1e-9, sec, time bins in simulations
#print "antenna ", str(l)," time binning sims ", tstep, 'total trace length :', t[-1]-t[0], len(t)
#### find offset between min(t) and start_time, add zeros to voltage traces and binned time array to t
if (min(t) >= start_time): # add the additional time
nb=int(round((min(t)-start_time)/tstep))
v_off=np.zeros(nb)
vx=np.concatenate((v_off,vx))
vy=np.concatenate((v_off,vy))
vz=np.concatenate((v_off,vz))
t_off=np.fromfunction(lambda i: i*tstep+start_time, (nb,), dtype=float)
t=np.concatenate((t_off,t))
if l==0:
print t_off*100000000.
print t*100000000.
#print np.concatenate((t_off,t))*100000000.
#if min(t) < start_time): # get rid of the time bins before the signal starts
if DISPLAY==1:
#plt.plot(t*1e9,vx) # s*1e9 = ns
plt.plot(t*1e9,vy)
#plt.plot(t*1e9,vz)
#plt.xlabel('Time [ns]')
#plt.ylabel('Voltage [uV]')
#plt.title('raw voltage trace, extended')
#plt.show()
#Filtering in frequency band
vx=Filtering(vx,tstep,FREQMIN,FREQMAX)
vy=Filtering(vy,tstep,FREQMIN,FREQMAX)
vz=Filtering(vz,tstep,FREQMIN,FREQMAX)
if DISPLAY==1:
#plt.plot(t*1e9,vx)
plt.plot(t*1e9,vy)
#plt.plot(t*1e9,vz)
#plt.xlabel('Time [ns]')
#plt.ylabel('Voltage [uV]')
#plt.title('filtered voltage trace')
plt.show()
## fill up antenna which were not included in the sim
except ValueError:
print " antenna position not simulated" # empty time traces have to be created and just handed over to the rest
tstep=1e-9# sec, time bins in simulations
nbins=1024 # bin number from simulations
vx=np.zeros(nbins)
vy=np.zeros(nbins)
vz=np.zeros(nbins)
t=np.fromfunction(lambda i: i*tstep+start_time, (nbins,), dtype=float)
#Filtering in frequency band
vx=Filtering(vx,tstep,FREQMIN,FREQMAX)
vy=Filtering(vy,tstep,FREQMIN,FREQMAX)
vz=Filtering(vz,tstep,FREQMIN,FREQMAX)
if DISPLAY==1:
plt.plot(t*1e9,vx)
plt.plot(t*1e9,vy)
plt.plot(t*1e9,vz)
plt.xlabel('Time [ns]')
plt.ylabel('Voltage [uV]')
plt.title('filtered voltage trace -empty')
plt.show()
## create the fake traces
##Filtering in frequency band
#vx=Filtering(vx,tstep,FREQMIN,FREQMAX)
#vy=Filtering(vy,tstep,FREQMIN,FREQMAX)
#vz=Filtering(vz,tstep,FREQMIN,FREQMAX)
#if DISPLAY==1:
#plt.plot(t*1e9,vx)
#plt.plot(t*1e9,vy)
#plt.plot(t*1e9,vz)
#plt.xlabel('Time [ns]')
#plt.ylabel('Voltage [uV]')
#plt.show()
vx,tx=Digitization(vx,t,tstep,TSAMPLING,SAMPLESIZE)
vy,ty=Digitization(vy,t,tstep,TSAMPLING,SAMPLESIZE)
vz,tz=Digitization(vz,t,tstep,TSAMPLING,SAMPLESIZE)
if DISPLAY==1:
plt.plot(vx)
plt.plot(vy)
plt.xlabel('Time [2 ns bins]')
plt.ylabel('Voltage [uV]')
plt.title('digitised voltage trace')
plt.show()
vx=Addnoise(vrms,vx)
vy=Addnoise(vrms,vy)
vz=Addnoise(vrms,vz)
if DISPLAY==1:
plt.plot(vx)
plt.plot(vy)
plt.plot(vz)
plt.xlabel('Time [2 ns bins]')
plt.ylabel('noise Voltage [uV]')
plt.title('noise voltage trace')
plt.show()
#vx,tx=Digitization(vx,t,tstep,TSAMPLING,SAMPLESIZE)
#vy,ty=Digitization(vy,t,tstep,TSAMPLING,SAMPLESIZE)
#vz,tz=Digitization(vz,t,tstep,TSAMPLING,SAMPLESIZE)
#if DISPLAY==1:
#plt.plot(vx)
#plt.plot(vy)
#plt.xlabel('Time [2 ns bins]')
#plt.ylabel('Voltage [uV]')
#plt.show()
#f = file(path_out+'/out_'+str(l)+'.txt',"w")
#outfile=os.path.join(path, "/fake_",str(l),".txt")
#outfile=path+"/fake_"+str(l)+".txt"
#print "saved as ", outfile
#fileout = file("./fake.txt","w")
#for i in np.arange(len(tx)):
#print >>fileout ,"%e %1.3e %1.3e %1.3e" % (tx[i], vx[i], vy[i], vz[i] ) # time in s
#fileout .close()
#print "saved as ", outfile
filename = path+"fake_"+str(l)+".txt"
alld = np.transpose([tx,vx,vy,vz])
np.savetxt(filename,alld,fmt='%.4e')
#print "saved as ", filename