-
Notifications
You must be signed in to change notification settings - Fork 3
/
EventAnalysis.py
2377 lines (1767 loc) · 99.2 KB
/
EventAnalysis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
------------------------------------------------------------------------
A script to replace the energy and angular resolution measurements performed by mimrec
Author: Daniel Kocevski ([email protected])
Date: September 3rd, 2016
Modified by Donggeun Tak ([email protected])
Date: April 3rd, 2020
Additional modifications by Sean Griffin ([email protected])
Data: April 10, 2020
Additional modifications by Donggeun Tak ([email protected])
Data: April 15, 2020
Usage Examples:
import EventAnalysis
# Parse the .tra file obtained from revan
events = EventAnalysis.parse('EffectiveArea_2MeV.inc1.id1.tra', sourceTheta=0.9)
# Calculate the angular resolution measurement (ARM) for Compton events
FWHM_ARM, dphi = EventAnalysis.getARMForComptonEvents(events, numberOfBins=100, phiRadius=5)
# Calculate the angular resolution measurement (ARM) for pair events
angles, openingAngles, contaimentData_68, contaimentBinned_68 = EventAnalysis.getARMForPairEvents(events, numberOfBins=100)
# Calculate the energy resolution for Compton events
mean, FWHM = EventAnalysis.getEnergyResolutionForComptonEvents(events, numberOfBins=100, energyPlotRange=[0,10000], energyFitRange=[1800,2100])
# Calculate the energy resolution for Pair events
fitMax, FWHM = EventAnalysis.getEnergyResolutionForPairEvents(events, numberOfBins=100, energyPlotRange=[0,10000], energyFitRange=[1800,2100])
# Display some diagnostic plots
EventAnalysis.plotDiagnostics(events)
# Visualize the pair events
EventAnalysis.visualizePairs(events, numberOfPlots=10)
------------------------------------------------------------------------
"""
import os
import time
import sys
import fileinput
import numpy
from itertools import product, combinations, repeat
from collections import OrderedDict
from scipy.stats import norm
from scipy.optimize import leastsq
import scipy.optimize
import math
import glob
try:
import matplotlib.pyplot as plot
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.mlab as mlab
import matplotlib.gridspec as gridspec
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from matplotlib.ticker import AutoMinorLocator
from matplotlib.colors import LogNorm
# Set the default title font dict
titleFormat = {'fontsize': 12, 'fontweight' : plot.rcParams['axes.titleweight'], 'verticalalignment': 'baseline', 'horizontalalignment': 'center'}
except:
print("\n**** Warning: matplotlib not found. Do not try to make plots or bad things will happen! ****")
try:
from IPython.display import clear_output
except:
pass
##########################################################################################
def getDetailsFromFilename(filename):
'''Function to get the energy and angle from a filename.
Really should be meta data.'''
details = {}
filepath, filename = os.path.split(filename)
info = filename.split('_')
details['MeV'] = info[1][:-3]
angle = info[2].split('.')
details['Cos'] = "{}.{}".format(angle[0][3:], angle[1])
return details
def DoubleLorentzAsymGausArm(x, par):
"""
DoubleLorentzAsymGausArm(x, par)
Fucntion Parameters:
par[0]: Offset
par[1]: Mean
par[2]: Lorentz Width 1
par[3]: Lorentz Height 1
par[4]: Lorentz Width 2
par[5]: Lorentz Height 2
par[6]: Gaus Height
par[7]: Gaus Sigma 1
par[8]: Gaus Sigma 2
"""
y = par[0];
y += numpy.abs(par[3]) * (par[2]*par[2])/(par[2]*par[2]+(x-par[1])*(x-par[1]));
y += numpy.abs(par[5]) * (par[4]*par[4])/(par[4]*par[4]+(x-par[1])*(x-par[1]));
for datum in x:
arg = 0;
if (datum - par[1] >= 0):
if (par[7] != 0):
arg = (datum - par[1])/par[7];
y += numpy.abs(par[6])*numpy.exp(-0.5*arg*arg);
else:
if (par[8] != 0):
arg = (datum - par[1])/par[8];
y += numpy.abs(par[6])*numpy.exp(-0.5*arg*arg);
return y
##########################################################################################
def DoubleLorentzian(x, offset, mean, width1, height1, width2, height2):
"""
DoubleLorentzAsymGausArm(x, par)
Fucntion Parameters:
par[0]: Offset
par[1]: Mean
par[2]: Lorentz Width 1
par[3]: Lorentz Height 1
par[4]: Lorentz Width 2
par[5]: Lorentz Height 2
"""
y = offset
y += numpy.abs(height1) * (width1*width1)/(width1*width1+(x-mean)*(x-mean));
y += numpy.abs(height2) * (width2*width2)/(width2*width2+(x-mean)*(x-mean));
return y
##########################################################################################
def Lorentzian(x, par):
x = numpy.array(range(-50,50,1))/10.
par = [0,0.5]
mean = par[0]
Gamma = par[1]
y = (1/(Gamma*math.pi)) * ( ( Gamma**2 ) / ( (x-mean)**2 + Gamma**2 ) )
plot.plot(x,y)
plot.show()
##########################################################################################
def skewedGaussian(x,h=1, e=0,w=1,a=0):
t = (x-e) / w
# return 2 / w * scipy.stats.norm.pdf(t) * scipy.stats.norm.cdf(a*t)
return h * 2 * scipy.stats.norm.pdf(t) * scipy.stats.norm.cdf(a*t)
##########################################################################################
def plotCube(shape=[80,80,60], position=[0,0,0], ax=None, color='blue'):
"""
A helper function to plot a 3D cube. Note that if no ax object is provided, a new plot will be created.
Example Usage:
EventViewer.plotCube(shape=[50*2,50*2,35.75*2], position=[0,0,35.0], color='red', ax=ax)
"""
# individual axes coordinates (clockwise around (0,0,0))
x_bottom = numpy.array([1,-1,-1,1,1]) * (shape[0]/2.) + position[0]
y_bottom = numpy.array([-1,-1,1,1,-1]) * (shape[1]/2.) + position[1]
z_bottom = numpy.array([-1,-1,-1,-1,-1]) * (shape[2]/2.) + position[2]
# individual axes coordinates (clockwise around (0,0,0))
x_top = numpy.array([1,-1,-1,1,1]) * (shape[0]/2.) + position[0]
y_top= numpy.array([-1,-1,1,1,-1]) * (shape[1]/2.) + position[1]
z_top = numpy.array([1,1,1,1,1]) * (shape[2]/2.) + position[2]
x_LeftStrut = numpy.array([1,1]) * (shape[0]/2.0) + position[0]
x_RightStrut = numpy.array([-1,-1]) * (shape[0]/2.0) + position[0]
y_FrontStrut = numpy.array([1,1]) * (shape[1]/2.0) + position[1]
y_BackStrut = numpy.array([-1,-1]) * (shape[1]/2.0) + position[1]
z_Strut = numpy.array([1,-1]) * (shape[2]/2.0) + position[2]
if ax == None:
fig = plot.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot3D(x_bottom, y_bottom, z_bottom, c=color)
ax.plot3D(x_top, y_top, z_top, c=color)
ax.plot3D(x_LeftStrut, y_FrontStrut, z_Strut, c=color)
ax.plot3D(x_LeftStrut, y_BackStrut, z_Strut, c=color)
ax.plot3D(x_RightStrut, y_FrontStrut, z_Strut, c=color)
ax.plot3D(x_RightStrut, y_BackStrut, z_Strut, c=color)
##########################################################################################
def plotSphere(radius=300, ax=None):
"""
A helper function to plot a 3D sphere. Note that if no ax object is provided, a new plot will be created.
Example Usage:
EventViewer.plotSphere(radius=300, ax=ax)
"""
#draw sphere
u, v = numpy.mgrid[0:2*numpy.pi:20j, 0:numpy.pi:10j]
x=numpy.cos(u)*numpy.sin(v)
y=numpy.sin(u)*numpy.sin(v)
z=numpy.cos(v)
if ax == None:
fig = plot.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(x*radius, y*radius, z*radius, color="gray")
##########################################################################################
def angularSeparation(vector1, vector2):
# Calculate the product of the vector magnitudes
product = numpy.linalg.norm(vector2) * numpy.linalg.norm(vector1)
# Make sure we don't devide by zero
if product != 0:
# Calculate the dot product
dotProduct = numpy.dot(vector2, vector1)
# Make sure we have sane results
value = dotProduct/product
if (value > 1.0): value = 1.0;
if (value < -1.0): value = -1.0;
# Get the reconstructed angle (in degrees)
angle = numpy.degrees(numpy.arccos(value))
else:
# Return zero in case the denominator is zero
angle = 0.0
return angle
##########################################################################################
def extractCoordinates(coordinateData):
x = []
y = []
z = []
for coordinates in coordinateData:
x.append(coordinates[0])
y.append(coordinates[1])
z.append(coordinates[2])
return x, y, z
##########################################################################################
def plotPairConversionCoordinates(events):
# Get the individual pair conversion coordinates
x, y, z = extractCoordinates(events['position_pairConversion'])
plot.figure(figsize=[10,9], color='#3e4d8b', alpha=0.9, histtype='stepfilled')
plot.hist(x, bins=50)
plot.xlabel('x')
plot.figure(figsize=[10,9], color='#3e4d8b', alpha=0.9, histtype='stepfilled')
plot.hist(y, bins=50)
plot.xlabel('y')
plot.figure(figsize=[10,9], color='#3e4d8b', alpha=0.9, histtype='stepfilled')
plot.hist(z, bins=50)
plot.xlabel('z')
##########################################################################################
def parse(filename, sourceTheta=1.0, testnum=-1):
# Create the dictionary that will contain all of the results
events = {}
# Define the lists to store energy information for Compton events
energy_ComptonEvents = []
energy_ComptonEvents_error = []
energy_TrackedComptonEvents = []
energy_UntrackedComptonEvents = []
energy_firstScatteredPhoton = []
energy_firstScatteredPhoton_error = []
energy_recoiledElectron = []
energy_recoiledElectron_error = []
# Define the lists to store energy information for pair events
energy_pairElectron = []
energy_pairElectron_error = []
energy_pairPositron = []
energy_pairPositron_error = []
energy_pairDepositedInFirstLayer = []
energy_pairDepositedInFirstLayer_error = []
# Define the lists to store position information
position_originalPhoton = []
position_firstInteraction = []
position_firstInteraction_error = []
position_secondInteraction = []
position_secondInteraction_error = []
position_pairConversion = []
position_firstInteraction = []
position_firstInteraction_error = []
# Define the lists to store the direction vectors
direction_recoilElectron = []
direction_pairElectron = []
direction_pairPositron = []
# Define other lists
phi_Tracker = []
qualityOfComptonReconstruction = []
qualityOfPairReconstruction = []
# Read the number of lines in the file
command = 'wc %s' % filename
output = os.popen(command).read()
totalNumberOfLines = float(output.split()[0])
# Start the various event and line counters
numberOfUnknownEventTypes = 0
numberOfComptonEvents = 0
numberOfPairEvents = 0
numberOfPhotoElectricEffectEvents = 0
numberOfTrackedElectronEvents = 0
numberOfUntrackedElectronEvents = 0
numberOfBadEvents = 0
lineNumber = 0
eventNumber = 0
# Create empty index lists to track event types
index_tracked = []
index_untracked = []
# track time of event and times between events
time = []
dt = []
tn=0
# Start by collecting all events
skipEvent = False
# Loop through the .tra file
print('\nParsing: %s' % filename)
for line in fileinput.input([filename]):
try:
sys.stdout.write("Progress: %d%% \r" % (lineNumber/totalNumberOfLines * 100) )
sys.stdout.flush()
except:
pass
if 'TI' in line:
lineContents = line.split()
time.append(float(lineContents[1]))
if testnum > 0:
if tn == testnum:
break
tn=tn+1
if 'ET ' in line:
# Split the line
lineContents = line.split()
eventType = lineContents[1]
# Skip the event if its of unknown type
if 'UN' in eventType:
numberOfUnknownEventTypes = numberOfUnknownEventTypes + 1
skipEvent = True
continue
else:
skipEvent = False
if 'CO' in eventType:
# Increment the Compton event counter
numberOfComptonEvents = numberOfComptonEvents + 1
if 'PA' in eventType:
# Increment the pair event counter
numberOfPairEvents = numberOfPairEvents + 1
if 'PH' in eventType:
# Increment the photo electron effect counter
numberOfPhotoElectricEffectEvents = numberOfPhotoElectricEffectEvents + 1
if 'BD' in line:
# Split the line
lineContents = line.split()
whybad = lineContents[1]
if whybad != 'None':
# Events don't get reconstructed for a number of reasons
# In pair, it's mostly 'TooManyHistInCSR'
numberOfBadEvents = numberOfBadEvents + 1
####### Compton Events #######
# Extract the Compton event energy information
if 'CE ' in line and skipEvent == False:
# Split the line
lineContents = line.split()
# Get the energy of the first scattered gamma-ray
energy_firstScatteredPhoton.append(float(lineContents[1]))
energy_firstScatteredPhoton_error.append(float(lineContents[2]))
# Get the energy of the recoiled electron
energy_recoiledElectron.append(float(lineContents[3]))
energy_recoiledElectron_error.append(float(lineContents[4]))
# Extract the Compton event hit information
if 'CD ' in line and skipEvent == False:
# Split the line
lineContents = line.split()
# Get the position of the first scattered gamma-ray
x1 = float(lineContents[1])
y1 = float(lineContents[2])
z1 = float(lineContents[3])
# Get the position uncertainty of the first scattered gamma-ray
x1_error = float(lineContents[4])
y1_error = float(lineContents[5])
z1_error = float(lineContents[6])
# Get the position of the second scattered gamma-ray
x2 = float(lineContents[7])
y2 = float(lineContents[8])
z2 = float(lineContents[9])
# Get the position uncertainty of the second scattered gamma-ray
x2_error = float(lineContents[10])
y2_error = float(lineContents[11])
z2_error = float(lineContents[12])
# Get the origin position of the original gamma-ray
x0 = x1
y0 = y1
z0 = 1000.0
# Get the position of the second scattered gamma-ray
x_electron = float(lineContents[13])
y_electron = float(lineContents[14])
z_electron = float(lineContents[15])
# Get the position uncertainty of the second scattered gamma-ray
x_electron_error = float(lineContents[16])
y_electron_error = float(lineContents[17])
z_electron_error = float(lineContents[18])
# Record the energy of the Compton event (regardless of whether it was has a tracked or untrack electron)
energy_ComptonEvents.append(energy_firstScatteredPhoton[-1] + energy_recoiledElectron[-1])
# Record the energy error of the Compton event (regardless of whether it was has a tracked or untrack electron)
energy_ComptonEvents_error.append( math.sqrt( energy_firstScatteredPhoton_error[-1]**2 + energy_recoiledElectron_error[-1]**2 ) )
# Determine if the recoil electron was tracked by the detector
if x_electron != 0:
# Record the direction of the recoil electron
direction_recoilElectron.append([x_electron, y_electron, z_electron])
# Record the energy of tracked events
energy_TrackedComptonEvents.append(energy_firstScatteredPhoton[-1] + energy_recoiledElectron[-1])
# Record the number of tracked events
numberOfTrackedElectronEvents = numberOfTrackedElectronEvents + 1
# Add this event to the index of tracked events
index_tracked.append(eventNumber)
else:
# Record the direction of the recoil electron
direction_recoilElectron.append([numpy.nan,numpy.nan,numpy.nan])
# Record the energy of tracked events
energy_UntrackedComptonEvents.append(energy_firstScatteredPhoton[-1] + energy_recoiledElectron[-1])
# Record the number of untracked events
numberOfUntrackedElectronEvents = numberOfUntrackedElectronEvents + 1
# Add this event to the index of untracked events
index_untracked.append(eventNumber)
# Store the origin coordinates of the original gamma-ray
position0 = numpy.array([x0, y0, z0])
# position0Error = numpy.array([x1_error,y1_error,z1_error])
# Get the x-axis offset based on the theta of the source. This assumes phi=0
# Note: For Compton events adjusting the theta of the source happens in the parser
# for pair events, it happens in the ARM calculation.
dx = numpy.tan(numpy.arccos(sourceTheta)) * (z1 - z0)
# Set the origin position of the original gamma-ray
position0 = numpy.array([x1-dx, y1, z0])
# Store the coordinates of the first interaction in an array
position1 = numpy.array([x1, y1, z1])
position1Error = numpy.array([x1_error, y1_error, z1_error])
# Store the coordinates of the second interaction in an array
position2 = numpy.array([x2, y2, z2])
position2Error = numpy.array([x2_error, y2_error, z2_error])
# Calculate the vector between the second and first interaction
directionVector2 = position2 - position1
# Calculate the vector between the first interaction and the origin of the original gamma-ray
directionVector1 = position1 - position0
# Calculate the product of the vector magnitudes
product = numpy.linalg.norm(directionVector1) * numpy.linalg.norm(directionVector2)
# Make sure we don't devide by zero
if product != 0:
# Calculate the dot product
dotProduct = numpy.dot(directionVector2, directionVector1)
# Make sure we have sane results
value = dotProduct/product
if (value > 1.0): value = 1.0;
if (value < -1.0): value = -1.0;
# Get the reconstructed phi angle (in radians) and add the known angle to the source
phi_Tracker.append(numpy.arccos(value))
else:
# Return zero in case the denominator is zero
phi_Tracker.append(0.0)
# Add the position information to their respective list of positions
position_originalPhoton.append(position0)
position_firstInteraction.append(position1)
position_firstInteraction_error.append(position1Error)
position_secondInteraction.append(position2)
position_secondInteraction_error.append(position2Error)
# Increment the event number
eventNumber = eventNumber + 1
####### Pair Events #######
# Extract the pair conversion hit information
if 'PC ' in line and skipEvent == False:
# Split the line
lineContents = line.split()
# Get the position of the pair conversion
x1 = float(lineContents[1])
y1 = float(lineContents[2])
z1 = float(lineContents[3])
# Save the position
position_pairConversion.append([x1,y1,z1])
# Extract the pair electron information
if 'PE ' in line and skipEvent == False:
# Split the line
lineContents = line.split()
# Get the electron information
energy_pairElectron.append(float(lineContents[1]))
energy_pairElectron_error.append(float(lineContents[2]))
# Get the direction of the pair electron
x = float(lineContents[3])
y = float(lineContents[4])
z = float(lineContents[5])
# Store the direction of the pair electron
direction_pairElectron.append([x,y,z])
# Extract the pair positron information
if 'PP ' in line and skipEvent == False:
# Split the line
lineContents = line.split()
# Get the electron information
energy_pairPositron.append(float(lineContents[1]))
energy_pairPositron_error.append(float(lineContents[2]))
# Get the direction of the pair electron
x = float(lineContents[3])
y = float(lineContents[4])
z = float(lineContents[5])
# Store the direction of the pair electron
direction_pairPositron.append([x,y,z])
if 'PI ' in line and skipEvent == False:
# Split the line
lineContents = line.split()
# Get the electron information
energy_pairDepositedInFirstLayer.append(float(lineContents[1]))
# Extract the reconstruction quality
if 'TQ ' in line and skipEvent == False:
# Split the line
lineContents = line.split()
if 'CO' in eventType:
# Get the reconstruction quality
qualityOfComptonReconstruction.append(float(lineContents[1]))
if 'PA' in eventType:
# Get the reconstruction quality
qualityOfPairReconstruction.append(float(lineContents[1]))
# Increment the line number for the progress indicator
lineNumber = lineNumber + 1
# Add all of the lists to the results dictionary
events['energy_ComptonEvents'] = numpy.array(energy_ComptonEvents).astype(float)
events['energy_ComptonEvents_error'] = numpy.array(energy_ComptonEvents_error).astype(float)
events['energy_TrackedComptonEvents'] = numpy.array(energy_TrackedComptonEvents).astype(float)
events['energy_UntrackedComptonEvents'] = numpy.array(energy_UntrackedComptonEvents).astype(float)
events['energy_firstScatteredPhoton'] = numpy.array(energy_firstScatteredPhoton).astype(float)
events['energy_firstScatteredPhoton_error'] = numpy.array(energy_firstScatteredPhoton_error).astype(float)
events['energy_recoiledElectron'] = numpy.array(energy_recoiledElectron).astype(float)
events['energy_recoiledElectron_error'] = numpy.array(energy_recoiledElectron_error).astype(float)
events['energy_pairElectron'] = numpy.array(energy_pairElectron).astype(float)
events['energy_pairElectron_error'] = numpy.array(energy_pairElectron_error).astype(float)
events['energy_pairPositron'] = numpy.array(energy_pairPositron).astype(float)
events['energy_pairPositron_error'] = numpy.array(energy_pairPositron_error).astype(float)
events['energy_pairDepositedInFirstLayer'] = numpy.array(energy_pairDepositedInFirstLayer).astype(float)
events['energy_pairDepositedInFirstLayer_error'] = numpy.array(energy_pairDepositedInFirstLayer_error).astype(float)
events['position_originalPhoton'] = numpy.array(position_originalPhoton).astype(float)
events['position_firstInteraction'] = numpy.array(position_firstInteraction).astype(float)
events['position_firstInteraction_error'] = numpy.array(position_firstInteraction_error).astype(float)
events['position_secondInteraction'] = numpy.array(position_secondInteraction).astype(float)
events['position_secondInteraction_error'] = numpy.array(position_secondInteraction_error).astype(float)
events['position_pairConversion'] = numpy.array(position_pairConversion).astype(float)
events['direction_recoilElectron'] = numpy.array(direction_recoilElectron).astype(float)
events['direction_pairElectron'] = numpy.array(direction_pairElectron).astype(float)
events['direction_pairPositron'] = numpy.array(direction_pairPositron).astype(float)
events['phi_Tracker'] = numpy.array(phi_Tracker).astype(float)
events['numberOfComptonEvents'] =numberOfComptonEvents
events['numberOfUntrackedElectronEvents'] =numberOfUntrackedElectronEvents
events['numberOfTrackedElectronEvents'] =numberOfTrackedElectronEvents
events['numberOfPairEvents'] = numberOfPairEvents
events['numberOfUnknownEventTypes'] = numberOfUnknownEventTypes
events['numberOfBadEvents'] = numberOfBadEvents
events['index_tracked'] = numpy.array(index_tracked)
events['index_untracked']= numpy.array(index_untracked)
events['qualityOfComptonReconstruction'] = numpy.array(qualityOfComptonReconstruction).astype(float)
events['qualityOfPairReconstruction'] = numpy.array(qualityOfPairReconstruction).astype(float)
events['time'] = numpy.array(time).astype(float)
events['deltime'] = numpy.append(0.,events['time'][1:]-events['time'][0:len(events['time'])-1])
# Print some event statistics
print("\n\nStatistics of Event Selection")
print("***********************************")
print("Total number of analyzed events: %s" % (numberOfComptonEvents + numberOfPairEvents))
if numberOfComptonEvents + numberOfPairEvents == 0:
print("No events pass selection")
events=False
return events
print("")
print("Number of unknown events: %s (%i%%)" % (numberOfUnknownEventTypes, 100*numberOfUnknownEventTypes/(numberOfComptonEvents + numberOfPairEvents + numberOfUnknownEventTypes)))
print("Number of pair events: %s (%i%%)" % (numberOfPairEvents, 100*numberOfPairEvents/(numberOfComptonEvents + numberOfPairEvents + numberOfUnknownEventTypes)))
print("Number of Compton events: %s (%i%%)" % (numberOfComptonEvents, 100*numberOfComptonEvents/(numberOfComptonEvents + numberOfPairEvents + numberOfUnknownEventTypes)))
if numberOfComptonEvents > 0:
print(" - Number of tracked electron events: %s (%i%%)" % (numberOfTrackedElectronEvents, 100.0*(float(numberOfTrackedElectronEvents)/numberOfComptonEvents)))
print(" - Number of untracked electron events: %s (%i%%)" % (numberOfUntrackedElectronEvents, 100*(float(numberOfUntrackedElectronEvents)/numberOfComptonEvents)))
print("")
print("")
fileinput.close()
return events
##########################################################################################
def getARMForComptonEvents(events, numberOfBins=100, phiRadius=10, onlyTrackedElectrons=False, onlyUntrackedElectrons=False, showPlots=True, filename=None, energyCutSelection=False, energyCut = [0, 0]):
# Set some constants
electron_mc2 = 511.0 # KeV
# Retrieve the event data
# energyCutSelection=False
if energyCutSelection:
energySelection = (events['energy_ComptonEvents']<(energyCut[0]+3*energyCut[1])) * (events['energy_ComptonEvents']>(energyCut[0]-3*energyCut[1]))
index_tracked = [i for i in events['index_tracked'] if energySelection[i]==True]
index_untracked = [i for i in events['index_untracked'] if energySelection[i]==True]
energy_firstScatteredPhoton = events['energy_firstScatteredPhoton'][energySelection]
energy_recoiledElectron = events['energy_recoiledElectron'][energySelection]
phi_Tracker = events['phi_Tracker'][energySelection]
if onlyTrackedElectrons == True:
energy_firstScatteredPhoton = events['energy_firstScatteredPhoton'][index_tracked]
energy_recoiledElectron = events['energy_recoiledElectron'][index_tracked]
phi_Tracker = events['phi_Tracker'][index_tracked]
if onlyUntrackedElectrons == True:
print("select either tracked or untracked compton events!!")
exit()
if onlyUntrackedElectrons == True:
energy_firstScatteredPhoton = events['energy_firstScatteredPhoton'][index_untracked]
energy_recoiledElectron = events['energy_recoiledElectron'][index_untracked]
phi_Tracker = events['phi_Tracker'][index_untracked]
if onlyTrackedElectrons == True:
print("select either tracked or untracked compton events!!")
exit()
else:
energy_firstScatteredPhoton = events['energy_firstScatteredPhoton']
energy_recoiledElectron = events['energy_recoiledElectron']
phi_Tracker = events['phi_Tracker']
index_tracked = events['index_tracked']
index_untracked=events['index_untracked']
# Determine whether to include only Tracked or Untracked electron events
if onlyTrackedElectrons == True:
energy_firstScatteredPhoton = energy_firstScatteredPhoton[index_tracked]
energy_recoiledElectron = energy_recoiledElectron[index_tracked]
phi_Tracker = phi_Tracker[index_tracked]
if onlyUntrackedElectrons == True:
print("select either tracked or untracked compton events!!")
exit()
if onlyUntrackedElectrons == True:
energy_firstScatteredPhoton = energy_firstScatteredPhoton[index_untracked]
energy_recoiledElectron = energy_recoiledElectron[index_untracked]
phi_Tracker = phi_Tracker[index_untracked]
if onlyTrackedElectrons == True:
print("select either tracked or untracked compton events!!")
exit()
# Calculate the Compton scattering angle
value = 1 - electron_mc2 * (1/energy_firstScatteredPhoton - 1/(energy_recoiledElectron + energy_firstScatteredPhoton));
# Keep only sane results
# index = numpy.where( (value > -1) | (value < 1) )
# value = value[index]
# Calculate the theoretical phi angle (in radians)
phi_Theoretical = numpy.arccos(value);
# Calculate the difference between the tracker reconstructed scattering angle and the theoretical scattering angle
dphi = numpy.degrees(phi_Tracker) - numpy.degrees(phi_Theoretical)
# Fit only a subsample of the data
selection = numpy.where( (dphi > (-1*phiRadius)) & (dphi < phiRadius) )
# Set the plot size
plot.figure(figsize=[10,9])
# plot.rcParams['figure.figsize'] = 10, 9
gs = gridspec.GridSpec(4,1)
ax1 = plot.subplot(gs[:3, :])
if len(dphi[selection]) < 10:
print("The number of events is not sufficient (<10)")
return numpy.nan, numpy.nan
elif len(dphi[selection]) < 500:
print("The number of events is not sufficient, so that 'numberOfBins' and 'phiRadius' changed.")
numberOfBins = 25
# Create the histogram
histogram_angleResults = ax1.hist(dphi[selection], numberOfBins, color='#3e4d8b', alpha=0.9, histtype='stepfilled')
ax1.set_xlim([-1*phiRadius,phiRadius])
# Extract the binned data and bin locations
dphi_binned = histogram_angleResults[0]
if max(dphi_binned) < 10:
numberOfBins = 20
histogram_angleResults = ax1.hist(dphi[selection], numberOfBins, color='#3e4d8b', alpha=0.9, histtype='stepfilled')
ax1.set_xlim([-1*phiRadius,phiRadius])
dphi_binned = histogram_angleResults[0]
bins = histogram_angleResults[1]
bincenters = 0.5*(bins[1:]+bins[:-1])
# Set the initial parameters
offset = 0
mean = 0
width1 = 1
height1 = numpy.max(dphi_binned)
width2 = 0
height2 = 0
# Fit the histogram data
try:
optimizedParameters, covariance = scipy.optimize.curve_fit(DoubleLorentzian, bincenters, dphi_binned, [offset, mean, width1, height1, width2, height2])
# Calculate the optimized curve
y_fit = DoubleLorentzian(bincenters, optimizedParameters[0], optimizedParameters[1], optimizedParameters[2], optimizedParameters[3], optimizedParameters[4], optimizedParameters[5])
# Get the fwhm of the fit
x1 = bincenters[numpy.where(y_fit >= numpy.max(y_fit)/2)[0][0]]
x2 = bincenters[numpy.where(y_fit >= numpy.max(y_fit)/2)[0][-1]]
mean = optimizedParameters[1]
FWHM = x2-x1
# Annotate the plot
ax1.text(0.03, 0.9, "Mean = %.3f deg\nFWHM = %.3f deg" % (mean, FWHM), verticalalignment='bottom', horizontalalignment='left', transform=ax1.transAxes, color='black', fontsize=12)
# Plot the data
ax1.plot(bincenters, y_fit, color='darkred', linewidth=2)
ax1.plot([x1,x2],[numpy.max(y_fit)/2.,numpy.max(y_fit)/2.], color='darkred', linestyle='--', linewidth=2)
titlestr = ''
if onlyTrackedElectrons:
titlestr = "Tracked"
if onlyUntrackedElectrons:
titlestr = "Untracked"
if not onlyTrackedElectrons and not onlyUntrackedElectrons:
titlestr = "Tracked + Untracked"
ax1.set_title(f'Angular Resolution (Compton Events)\n{titlestr}', fontdict=titleFormat)
# ax1.axes.xaxis.set_ticklabels([])
# Create a subplot for the residuals
ax2 = plot.subplot(gs[3, :])
# Plot the residuals
ax2.step(bincenters, dphi_binned-y_fit, color='#3e4d8b', alpha=0.9)
ax2.plot([bincenters[0],bincenters[-1]], [0,0], color='darkred', linewidth=2, linestyle='--')
ax2.set_xlim([-1*phiRadius,phiRadius])
ax2.set_xlabel('ARM - Compton Cone (deg)')
# Set the minor ticks
ax1.xaxis.set_minor_locator(AutoMinorLocator(4))
ax1.yaxis.set_minor_locator(AutoMinorLocator(4))
ax2.xaxis.set_minor_locator(AutoMinorLocator(4))
except:
print("**** Warning: fit failed to converge! ****")
mean = numpy.nan
FWHM = numpy.nan
# Print some statistics
print("\n\nStatistics of ARM histogram and fit (Compton Events)")
print("***********************************")
print("Compton and pair events in ARM histogram: %s (%s%%)" % ( len(dphi[selection]), 100*len(dphi[selection])/(len(dphi)) ))
print("")
print("Mean of fit: %s" % mean)
print("FWHM of fit: %s" % FWHM)
print("")
if filename is not None:
f=getDetailsFromFilename(filename)
f1,f2 = f['MeV'], f['Cos']
ft=None
if onlyTrackedElectrons == True:
ft='tracked'
else:
ft='untracked'
plot.savefig("%sMeV_Cos%s_angular_resolution_%s.png" % (f1,f2,ft))
# Show the plot
if showPlots == True:
plot.show()
else:
plot.close()
return FWHM, dphi
########################################################
def kingFunction(x, sigma, gamma):
K = (1. / (2. * numpy.pi * sigma**2.)) * (1. - (1./gamma)) * ((1 + (1/(2*gamma)) * (x**2/sigma**2))**(-1*gamma))
return K
########################################################
def fcore(N, sigma_tail, sigma_core):
value = 1 / (1 + (N * sigma_tail**2 / sigma_core**2))
return value
##########################################################################################
def latScaleFactor(energy, c0=0.153, c1=0.0057000001, beta=-0.8):
scaleFactor = numpy.sqrt( (c0 * ((energy/100)**beta) )**2 + c1**2)
return scaleFactor
##########################################################################################
def latPSF(scaledDeviation, NTAIL, STAIL, SCORE, GTAIL, GCORE):
psf = (fcore(NTAIL, STAIL, SCORE) * kingFunction(scaledDeviation, SCORE, GCORE)) + (( 1 - fcore(NTAIL, STAIL, SCORE) ) * kingFunction(scaledDeviation, STAIL, GTAIL))
return psf
##########################################################################################
def getScaledDeviation(events, sourceTheta=0):
# Get the scaled angular distribution
scaledDeviation, openingAngles, contaimentData_68, contaimentBinned_68 = getARMForPairEvents(events, sourceTheta=sourceTheta, numberOfBins=100, angleFitRange=[0,10**1.5], anglePlotRange=[0,10**1.5], openingAngleMax=180., showPlots=True, numberOfPlots=0, finishExtraction=True, qualityCut=1, energyCut=numpy.nan, weightByEnergy=True, showDiagnosticPlots=False, filename=None, log=True, getScaledDeviation=True)
# angles, openingAngles, contaimentData_68, contaimentBinned_68 = EventAnalysis.getARMForPairEvents(events, sourceTheta=sourceTheta, numberOfBins=100, angleFitRange=[0,10**1.5], anglePlotRange=[0,10**1.5], openingAngleMax=180., showPlots=True, numberOfPlots=0, finishExtraction=True, qualityCut=1, energyCut=numpy.nan, weightByEnergy=True, showDiagnosticPlots=False, filename=None, log=True, getScaledDeviation=True)
return scaledDeviation
##########################################################################################
def getARMForPairEvents(events, sourceTheta=0, numberOfBins=100, angleFitRange=[0,30], anglePlotRange=[0,30], openingAngleMax=180., showPlots=True, numberOfPlots=0, finishExtraction=True, qualityCut=1, energyCut=numpy.nan, weightByEnergy=True, showDiagnosticPlots=True, filename=None, log=False, getScaledDeviation=False, onlyangles=False):
# Define the list to contain the resulting angle measurements
angles = []
openingAngles = []
distances = []
# Start some counters
plotNumber = 0
numberOfRejectedEvents = 0
# Define a default position to the source
dz = 1000.0
dx = 0
dy = 0
# Create a list to contain an index of events passing the quality cut
index_goodQuality = []
# Loop through each event and calculate the reconstructed photon direction and it's offset to the true direction