-
Notifications
You must be signed in to change notification settings - Fork 3
/
XRayAnalysisTool.py
973 lines (924 loc) · 39.3 KB
/
XRayAnalysisTool.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
#add info here:
#import libraries here
# _ _________________ ___ ______ _____ _____ _____
#| | |_ _| ___ \ ___ \/ _ \ | ___ \_ _| ___/ ___|
#| | | | | |_/ / |_/ / /_\ \| |_/ / | | | |__ \ `--.
#| | | | | ___ \ /| _ || / | | | __| `--. \
#| |_____| |_| |_/ / |\ \| | | || |\ \ _| |_| |___/\__/ /
#\_____/\___/\____/\_| \_\_| |_/\_| \_|\___/\____/\____/
from optparse import OptionParser
parser = OptionParser()
import sys
import glob
import re
import os
import numpy as np
from array import *
from ROOT import *
#Here list the parser options
# _ __ __ _ _ __ ___ ___ _ __
#| '_ \ / _` | '__/ __|/ _ \ '__|
#| |_) | (_| | | \__ \ __/ |
#| .__/ \__,_|_| |___/\___|_|
#| |
#|_|
#
#
#
#
#
#
#
#
# Hey you. Yes you. Before you do what you would normally do, I put something new in.
# You don't have to edit this file anymore to do the fluoro scripts. You can, if you wish.
# Or, you can also run this like you would normally but when you do so add the module name and date, for example:
# python2.6 python2.6 /home/CMS_pixel/Testing/FPIXUtils/XRayAnalysisTool.py_T mi250 060116
# would be the command to run the script on module mi250 whose fluoro file has date June 1, 2016.
# Don't worry, the old way works too if you don't like this.
#
# READ THE THING RIGHT ABOVE THIS THING
myfilename1 = "fluoro_mp323_061016.root" #"pa207_071615.root" This is the Copper Cu File
myfilename2 = "prep_noxray_mp323_061016.root"; #"fluoro_122915.root" This is the Silver Ag File
myfilename3 = myfilename1; #"fluoro2_122915.root" #"pa207_071615.root" This is the Tin Sn file
myfilename4 = myfilename1; #"fluoro2_122915.root" This is the Indium In File
myfileoutname = "XRFResult_mp323"
rocs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
parser.add_option('--setup', type='string', action='store',
default='KU',
dest='setup',
help='Setup corresponding to KU or UIC?: Options KU or UIC only')
parser.add_option('--outputfile', type='string', action='store',
default=myfileoutname, #''M_',
dest='outputfile',
help='Set first part of the name of outputfile: Usually M_XX_YYY')
parser.add_option('--histoname', type='string', action='store',
default='Xray/q',
dest='histoname',
help='Histogram that is analyzed')
parser.add_option('--sigma', type='int', action='store',
default=3,
dest='sigma',
help='Value of sigma to be used to find peaks in TSpectrum')
parser.add_option('--threshold', type='float', action='store',
default=0.2,
dest='threshold',
help='Value of the threshold to be used to find peaks in TSpectrum')
parser.add_option('--XRSource', type='string', action='store',
default='Mo',
dest='XRSource',
help='Name of the XRay source, valid options: Cu or Mo ')
parser.add_option('--CuFile', type='string', action='store',
default=myfilename1, #''Fluorescence.root',
dest='CuFile',
help='Name of the Cu root file (when Mo is the XRaySource) ')
parser.add_option('--MoFile', type='string', action='store',
default='Fluorescence.root',
dest='MoFile',
help='Name of the Mo root file (when Cu is the XRaySource ')
parser.add_option('--AgFile', type='string', action='store',
default=myfilename2, #''Fluorescence.root',
dest='AgFile',
help='Name of the Ag root file ')
parser.add_option('--SnFile', type='string', action='store',
default=myfilename3, #''Fluorescence.root',
dest='SnFile',
help='Name of the Sn root file ')
parser.add_option('--InFile', type='string', action='store',
default=myfilename4, #'Fluorescence.root',
dest='InFile',
help='Name of the In root file ')
parser.add_option('--nrocs', type='int', action='store',
default=15,
dest='nrocs',
help='Number or rocs')
parser.add_option('--badrocs', type='string', action='store',
default=' ',
dest='badrocs',
help='List of bad rocs, for example [2,4,5]')
(options, args) = parser.parse_args()
argv = []
if len(sys.argv) >= 3:
modName = sys.argv[1]
testDate= sys.argv[2]
myCuFileName = "fluoro_"+modName+"_"+testDate+".root" #"pa207_071615.root"
myAgFileName = myCuFileName; #"fluoro_122915.root"
mySnFileName = myCuFileName; #"fluoro2_122915.root" #"pa207_071615.root"
myInFileName = myCuFileName; #"fluoro2_122915.root"
myfileoutname = "XRFResult_"+modName
else:
myCuFileName = myfilename1;
myAgFileName = myfilename2; #"fluoro_122915.root"
mySnFileName = myfilename3; #"fluoro2_122915.root" #"pa207_071615.root"
myInFileName = myfilename4; #"fluoro2_122915.rooot"
options.CuFile = myCuFileName
options.AgFile = myAgFileName
options.SnFile = mySnFileName
options.InFile = myInFileName
options.outputfile = myfileoutname;
#define functions here:
# _ _ _ _ _ _ _ _ _
# / \ / \ / \ / \ / \ / \ / \ / \ / \
#( f | u | n | c | t | i | o | n | s )
# \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
#Comments on get_gpeaks: To get rid of the polymarkers of the Spectrum method, use the option ='goff' in the search function
def get_gpeaks(h,lrange=[0,180],sigma=6,opt="goff",thres=0.05,niter=1000,exp=0,i=0):
s = TSpectrum(niter,1)
h.GetXaxis().SetRangeUser(lrange[0],lrange[1])
for sigma_temp in range(sigma,0,-1):
s.Search(h,sigma_temp,"",thres)
print "sigma", sigma_temp, s.GetNPeaks()
h.Draw()
c1.Update()
name = h.GetName()
c1.SaveAs(output+'Sigma_'+str(sigma_temp)+name+'.png')
if s.GetNPeaks() >= exp:
break
s.SetAverageWindow(2)
bufX, bufY = s.GetPositionX(), s.GetPositionY()
pos = []
for i in range(s.GetNPeaks()):
pos.append([bufX[i], bufY[i]])
pos.sort()
return pos
#Comments on rm_peak: Gets rid of the additional peak that KU observes
def rm_peak(histo, gaus):
bins = histo.GetNbinsX()
print 'P0',gaus.GetParameter(0),gaus.GetParameter(1),gaus.GetParameter(2)
newhisto = histo.Clone()
newhisto.Reset()
for i in range( 1 , bins) :
#val = histo.GetBinContent(i) - gaus.Eval(i)
val = gaus.Eval(i*2)
newhisto.Fill(i*2,val)
histo.Add(newhisto,-1)
return histo
#Comments on FitPeaks: It has 2 variants depending on the Xray source used. It will get the peaks and fit them and save the stats info in .txt files per Material and ROC.
def FitPeaks(rootfile,histo,material,rocs,output,XRSource,rebin):
arrayMo = false
arrayCu = false
arrayIn = false
arrayAg = false
arraySn = false
grocs = len(rocs)+1
ArrayG = TObjArray(16)
if material == 'Mo':
arrayMo = true
ArrayMo = TObjArray(16)
if XRSource == 'Mo':
exp = 2
elif material == 'Ag':
arrayAg = true
ArrayAg = TObjArray(16)
if XRSource == 'Mo':
exp = 3
elif material == 'Sn':
arraySn =true
ArraySn = TObjArray(16)
if XRSource == 'Mo':
exp = 3
elif material == 'In':
arrayIn = true
ArrayIn = TObjArray(16)
if XRSource == 'Mo':
exp = 3
elif material == 'Cu':
arrayCu = true
ArrayCu = TObjArray(16)
if XRSource == 'Mo':
exp = 2
#for i in range(0,int(nrocs)-1):
for i in range(0,16):
if i not in rocs:
print 'Skipping roc', i
continue
stats= open(output+material+'C_'+str(i)+'_stats.txt','w')
if material == 'not': #'In':
hl = len( histo )
hist = histo[0 : hl-4] + "Ag_C" + str(i) + "_V0"
else:
hist = histo +str(i)+"_V0"
directory = rootfile.Get('Xray')
keys = directory.GetListOfKeys()
allkeys = []
for key in keys:
allkeys.append(key.GetName())
print hist, hist.strip('Xray/')
if hist.strip('Xray/') in allkeys:
print 'FoilandRoc found:', hist
#if hist not in key.GetName():
#print 'Target foil not found'
#continue
else:
print 'Histogram needed not found',hist.strip('Xray/')
continue
tgt = rootfile.Get(hist)
print "Opening file:"+ hist
tgt.Rebin(rebin)
tgt.Draw()
tgt.GetXaxis().SetRangeUser(0,250)
peaks = get_gpeaks(tgt,[0,250],6,"goff",.05,1000,exp,i)
print len(peaks), "Roc: ", i, material
if len(peaks)==0:
print 'Couldnt find peaks, check here!'
continue
mid1 = peaks[0][1]
mid2 = peaks[1][1]
rebinned = false
if(len(peaks)>3):
print "Too many peaks,rebinning"
tgt.Rebin(2)
peaks = get_gpeaks(tgt,[20,300],6,"goff",.05,1000,exp)
if (len(peaks)==2):
mid1 = peaks[0][1]
mid2 = peaks[1][1]
rebinned = true
#peaks = peaks[1:3]
if (len(peaks)==2 or rebinned):
for t in range(1, int(peaks[0][0])):
if (tgt.GetBinContent(t)/mid1>0.68):
sigma1l = t
break
for j in range(int(peaks[0][0])+1,int(peaks[1][0])):
if (tgt.GetBinContent(j)/mid1<0.68):
sigma1r = j
break
for l in range(int(peaks[1][0])+1,300):
if (tgt.GetBinContent(l)/mid2<0.68):
sigma2r = l
break
for k in range(int(peaks[0][0])+(sigma1r)/2,int(peaks [1][0])):
if (tgt.GetBinContent(k)/mid2>0.68) and abs(k-peaks[1][0])<20:
sigma2l = k
break
if(len(peaks)==3):
if peaks[1][1] > peaks[2][1]:
mid3 = peaks[1][1]
right3 = int(peaks[1][0])
for t in range(1, int(peaks[0][0])):
if (tgt.GetBinContent(t)/mid1>0.68):
sigma1l = t
break
for j in range(int(peaks[0][0])+1,right3):
if (tgt.GetBinContent(j)/mid1<0.68):
sigma1r = j
break
for l in range(right3+1,300):
if (tgt.GetBinContent(l)/mid3<0.68):
sigma2r = l
break
for k in range(int(peaks[0][0])+(sigma1r)/2,right3):
if (tgt.GetBinContent(k)/mid3>0.68):
sigma2l = k
if abs(k-right3)< 20:
break
else:
mid3 = peaks[2][1]
right3 = int(peaks[2][0])
for t in range(1, int(peaks[0][0])):
if (tgt.GetBinContent(t)/mid1>0.68):
sigma1l = t
break
for j in range(int(peaks[0][0])+1,int(peaks[1][0])):
if (tgt.GetBinContent(j)/mid1<0.68):
sigma1r = j
break
for l in range(right3+1,300):
if (tgt.GetBinContent(l)/mid3<0.68):
sigma2r = l
break
for k in range(int(peaks[1][0])+(sigma1r)/2,right3):
if (tgt.GetBinContent(k)/mid3>0.68) and abs(k-right3)<20:
sigma2l = k
break
if (XRSource == 'Mo'):
print "Mo source" ,len(peaks)
if (material == 'Cu'):
gaus1 = TF1("gaus1","gaus",peaks[1][0]-15, peaks[1][0]+15)
gaus2 = TF1("gaus2","gaus",peaks[0][0]-15, peaks[0][0]+15)
elif ((material == 'Sn' or material == 'Ag' or material == 'In') and len(peaks) == 3):
gaus1 = TF1("gaus1","gaus",peaks[1][0]-15, peaks[1][0]+15)
gaus2 = TF1("gaus2","gaus",peaks[2][0]-20, peaks[2][0]+20)
gaus3 = TF1("gaus3","gaus",peaks[2][0]-20, peaks[2][0]+20)
elif ((material == 'Sn' or material == 'Ag' or material == 'In') and len(peaks) == 2):
if peaks[0][0] > 70 and peaks[0][0] < 100:
gaus1 = TF1("gaus1","gaus",peaks[0][0]-15, peaks[0][0]+15)
gaus2 = TF1("gaus2","gaus",peaks[1][0]-15, peaks[1][0]+15)
gaus3 = TF1("gaus3","gaus",peaks[1][0]-15, peaks[1][0]+15)
else:
gaus1 = TF1("gaus1","gaus",peaks[1][0]-15, peaks[1][0]+15)
gaus2 = TF1("gaus2","gaus",peaks[0][0]-15, peaks[0][0]+15)
gaus3 = TF1("gaus3","gaus",peaks[0][0]-15, peaks[0][0]+15)
tgt.Fit("gaus1","R")
tgt.Fit("gaus2","+R")
tgt.Draw()
print tgt.GetFunction("gaus2").GetParameter(1)
mu1 = tgt.GetFunction("gaus1").GetParameter(1)
mu2 = tgt.GetFunction("gaus2").GetParameter(1)
sigma1 = tgt.GetFunction("gaus1").GetParameter(2)
sigma2 = tgt.GetFunction("gaus2").GetParameter(2)
c1.SaveAs(output+'FitC_'+str(i)+material+'.png')
if material == 'Ag' or material == 'In' or material == 'Sn':
newhisto = rm_peak(tgt,tgt.GetFunction("gaus1"))
print "Got new histo"
c1.Update()
newhisto.Fit("gaus3","+R")
newhisto.Draw()
mu2 = newhisto.GetFunction("gaus3").GetParameter(1)
print "new mu2: ", mu2
sigma2 = newhisto.GetFunction("gaus3").GetParameter(2)
c1.Update()
c1.SaveAs(output+'Stripped_C'+str(i)+'_'+material+'.png')
print material, "roc: "+str(i), mu1 , sigma1, mu2, sigma2
stats.writelines(["Mean_Mo_C"+str(i)+":\t"+str(mu1)+"\n", "Sigma_Mo_C"+str(i)+":\t"+str(sigma1)+"\n","Mean_"+material+"_C"+str(i)+":\t"+str(mu2)+"\n", "Sigma_"+material+"_C"+str(i)+":\t"+str(sigma2)+"\n"])
if arrayCu:
ArrayCu.AddAt(tgt,i)
elif arrayAg:
ArrayAg.AddAt(tgt,i)
elif arraySn:
ArraySn.AddAt(tgt,i)
elif arrayIn:
ArrayIn.AddAt(tgt,i)
elif (XRSource == 'Cu'):
gaus1 = TF1("gaus1","gaus",peaks[0][0]-15, peaks[0][0]+15)
if len(peaks)==2: gaus2 = TF1("gaus2","gaus",peaks[1][0]-15,peaks[1][0]+15)
if len(peaks)==3:
if peaks[1][1]>peaks[2][1]:
gaus2 = TF1("gaus2","gaus",peaks[1][0]-20,peaks[1][0]+20)
else:
gaus2 = TF1("gaus2","gaus",peaks[2][0]-20,peaks[2][0]+20)
tgt.Fit("gaus1","R")
tgt.Fit("gaus2","+R")
tgt.Draw()
c1.Update()
mu1 = tgt.GetFunction("gaus1").GetParameter(1)
mu2 = tgt.GetFunction("gaus2").GetParameter(1)
sigma1 = tgt.GetFunction("gaus1").GetParameter(2)
sigma2 = tgt.GetFunction("gaus2").GetParameter(2)
print mu1 , sigma1, mu2, sigma2
c1.SaveAs(output+'FitC_'+str(i)+material+'.png')
stats.writelines(["Mean_Cu_C"+str(i)+":\t"+str(mu1)+"\n", "Sigma_Cu_C"+str(i)+":\t"+str(sigma1)+"\n","Mean_"+material+"_C"+str(i)+":\t"+str(mu2)+"\n", "Sigma_"+material+"_C"+str(i)+":\t"+str(sigma2)+"\n"])
if arrayMo:
ArrayMo.AddAt(tgt,i)
elif arrayAg:
ArrayAg.AddAt(tgt,i)
elif arraySn:
ArraySn.AddAt(tgt,i)
elif arrayIn:
ArrayIn.AddAt(tgt,i)
if arrayCu:
ArrayG = ArrayCu
elif arrayAg:
ArrayG = ArrayAg
elif arraySn:
ArrayG = ArraySn
elif arrayMo:
ArrayG = ArrayMo
elif arrayIn:
ArrayG = ArrayIn
print "fit Peaks Finished"
return ArrayG
#Comments on :
def PlotSameNStats(arrayfithisto1, arrayfithisto2, arrayfithisto3, arrayfithisto4, rocs, output, XRSource):
grocs = len(rocs)
for i in range(0,grocs):
if i not in rocs:
print 'Skipping roc', i
continue
c1 = TCanvas('c1',"Fluorescence test",1)
gStyle.SetOptStat(0)
c1.cd()
gStyle.SetOptTitle(0)
height=[]
if not arrayfithisto1:
height.append(0)
continue
else:
fithisto1 = arrayfithisto1[i]
fithisto1.GetXaxis().SetRange(20,300)
fithisto1.SetLineColor(kBlue)
mu1f = fithisto1.GetFunction("gaus2").GetParameter(1)
sigma1f = fithisto1.GetFunction("gaus2").GetParameter(2)
mu1 = float("{0:.2f}".format(mu1f))
sigma1 = float("{0:.2f}".format(sigma1f))
height.append( fithisto1.GetMaximum())
if not arrayfithisto2:
height.append(0)
continue
else:
fithisto2 = arrayfithisto2[i]
fithisto2.GetXaxis().SetRange(20,300)
fithisto2.SetLineColor(kMagenta)
mu2f = fithisto2.GetFunction("gaus2").GetParameter(1)
sigma2f = fithisto2.GetFunction("gaus2").GetParameter(2)
mu2 = float("{0:.2f}".format(mu2f))
sigma2 = float("{0:.2f}".format(sigma2f))
height.append(fithisto2.GetMaximum())
if not arrayfithisto3:
continue
height.append(0)
else:
fithisto3 = arrayfithisto3[i]
fithisto3.GetXaxis().SetRange(20,300)
fithisto3.SetLineColor(kGreen)
mu3f = fithisto3.GetFunction("gaus2").GetParameter(1)
sigma3f = fithisto3.GetFunction("gaus2").GetParameter(2)
mu3 = float("{0:.2f}".format(mu3f))
sigma3 = float("{0:.2f}".format(sigma3f))
height.append(fithisto3.GetMaximum())
if not arrayfithisto4:
continue
height.append(0)
else:
fithisto4 = arrayfithisto4[i]
fithisto4.GetXaxis().SetRange(20,300)
fithisto4.SetLineColor(kOrange)
mu4f = fithisto4.GetFunction("gaus2").GetParameter(1)
sigma4f = fithisto4.GetFunction("gaus2").GetParameter(2)
mu4 = float("{0:.2f}".format(mu4f))
sigma4 = float("{0:.2f}".format(sigma4f))
height.append( fithisto4.GetMaximum())
print height
maxheight = max(height)
print maxheight
if XRSource == 'Mo':
fithisto1.SetMaximum(maxheight+100)
fithisto1.Draw()
c1.Update()
textmu1 = TLatex()
textmu1.SetNDC()
textmu1.SetTextColor(kBlue)
textmu1.SetTextSize(0.03)
textmu1.DrawText(0.7,0.25,"Cu.Mean():"+ str(mu1))
textsigma1 = TLatex()
textsigma1.SetNDC()
textsigma1.SetTextColor(kBlue)
textsigma1.SetTextSize(0.03)
textsigma1.DrawText(0.7,0.15,"Cu.Sigma():"+ str(sigma1))
c1.Update()
elif XRSource == 'Cu':
fithisto1.SetMaximum(maxheight+100)
fithisto1.Draw()
c1.Update()
textmu1 = TLatex()
textmu1.SetNDC()
textmu1.SetTextColor(kBlue)
textmu1.SetTextSize(0.03)
textmu1.DrawText(0.7,0.25,"Mo.Mean():"+ str(mu1))
textsigma1 = TLatex()
textsigma1.SetNDC()
textsigma1.SetTextColor(kBlue)
textsigma1.SetTextSize(0.03)
textsigma1.DrawText(0.7,0.15,"Mo.Sigma():"+ str(sigma1))
c1.Update()
if not arrayfithisto2:
continue
else:
fithisto2.SetMaximum(maxheight+100)
fithisto2.Draw("sames")
textmu2 = TLatex()
textmu2.SetNDC()
textmu2.SetTextColor(kMagenta)
textmu2.SetTextSize(0.03)
textmu2.DrawText(0.7,0.45,"Ag.Mean():"+ str(mu2))
textsigma2 = TLatex()
textsigma2.SetNDC()
textsigma2.SetTextColor(kMagenta)
textsigma2.SetTextSize(0.03)
textsigma2.DrawText(0.7,0.35,"Ag.Sigma():"+ str(sigma2))
c1.Update()
if not arrayfithisto3:
continue
else:
fithisto3.SetMaximum(maxheight+100)
fithisto3.Draw("sames")
textmu3 = TLatex()
textmu3.SetNDC()
textmu3.SetTextColor(kGreen)
textmu3.SetTextSize(0.03)
textmu3.DrawText(0.7,0.65,"Sn.Mean():"+ str(mu3))
textsigma3 = TLatex()
textsigma3.SetNDC()
textsigma3.SetTextColor(kGreen)
textsigma3.SetTextSize(0.03)
textsigma3.DrawText(0.7,0.55,"Sn.Sigma():"+ str(sigma3))
c1.Update()
if not arrayfithisto4:
continue
else:
fithisto4.SetMaximum(maxheight+100)
fithisto4.Draw("sames")
textmu4 = TLatex()
textmu4.SetNDC()
textmu4.SetTextColor(kOrange)
textmu4.SetTextSize(0.03)
textmu4.DrawText(0.7,0.85,"In.Mean():"+ str(mu4))
textsigma4 = TLatex()
textsigma4.SetNDC()
textsigma4.SetTextColor(kOrange)
textsigma4.SetTextSize(0.03)
textsigma4.DrawText(0.7,0.75,"In.Sigma():"+ str(sigma4))
c1.Update()
text = TLatex()
text.SetNDC()
text.DrawText(0.4,0.95,"Fluorescence tests C_"+str(i))
print 'Saving to:', output
c1.SaveAs(output+"XRayFluoResultsC_"+str(i)+'.png')
c1.Close()
return
def ConversionPlot(rocs,output, XRSource):
grocs = len(rocs)
convfactcu = 8048/3.6
convfactmo = 17479/3.6
convfactag = 22163/3.6
convfactsn= 25271/3.6
convfactin = 24207/3.6
sumoutfile = "SummaryQPlots_" + output + ".txt"
sumout = open(sumoutfile, "w")
sumout.write(myfileoutname + "Summary of QPlots Slopes.\n"+ " e^{-}/Vcal: Intercept: \n" )
qplotfit = open("SummaryQplots.txt",'w')
n_oh = TH1F('n_oh','N_o', 100,0,1000)
slopeh = TH1F('Slope','Slope',100, 0,100)
qmatrix = np.zeros((16,5))
for i in rocs:
mu_cu =[]
sig_cu=[]
mu_mo = []
sig_mo = []
mu_ag =[]
sig_ag =[]
mu_sn =[]
sig_sn = []
mu_in =[]
sig_in = []
for file in glob.glob("*_"+str(i)+"_stats.txt"):
name = os.path.splitext(file)[0]
print "Opening:",name
if XRSource =='Mo':
if('CuC_' in name):
material = 'Cu'
f = open(file,'r')
line = f.readlines()
for k in range(0,len(line)):
if "_Mo" in line[k]:
if "Mean_Mo" in line[k]:
words = re.split(':\t',line[k])
meanmo = words[1].strip('\n')
mu_mo.append(meanmo)
elif "Sigma_Mo" in line[k]:
words = re.split(':\t',line[k])
sigmamo = words[1].strip('\n')
sig_mo.append(sigmamo)
else:
if "Mean_"+material in line[k]:
words = re.split(':\t',line[k])
mean = words[1].strip('\n')
mu_cu.append(mean)
elif "Sigma_"+material in line[k]:
words = re.split(':\t',line[k])
sigma = words[1].strip('\n')
sig_cu.append(sigma)
f.close()
elif('AgC_' in name):
material = 'Ag'
f = open(file,'r')
line = f.readlines()
for k in range(0,len(line)):
if "_Mo" in line[k]:
if "Mean_Mo" in line[k]:
words = re.split(':\t',line[k])
meanmo = words[1].strip('\n')
mu_mo.append(meanmo)
elif "Sigma_Mo" in line[k]:
words = re.split(':\t',line[k])
sigmamo = words[1].strip('\n')
sig_mo.append(sigmamo)
else:
if "Mean_"+material in line[k]:
words = re.split(':\t',line[k])
meanag = words[1].strip('\n')
mu_ag.append(meanag)
elif "Sigma_"+material in line[k]:
words = re.split(':\t',line[k])
sigma = words[1].strip('\n')
sig_ag.append(sigma)
f.close()
elif('SnC_' in name):
material = 'Sn'
convfact= 25271/3.6
f = open(file,'r')
line = f.readlines()
for k in range(0,len(line)):
if "_Mo" in line[k]:
if "Mean_Mo" in line[k]:
words = re.split(':\t',line[k])
meanmo = words[1].strip('\n')
mu_mo.append(meanmo)
elif "Sigma_Mo" in line[k]:
words = re.split(':\t',line[k])
sigmamo = words[1].strip('\n')
sig_mo.append(sigmamo)
else:
if "Mean_"+material in line[k]:
words = re.split(':\t',line[k])
mean = words[1].strip('\n')
mu_sn.append(mean)
elif "Sigma_"+material in line[k]:
words = re.split(':\t',line[k])
sigma = words[1].strip('\n')
sig_sn.append(sigma)
f.close()
elif('InC_' in name):
material = 'In'
convfact= 24207/3.6
f = open(file,'r')
line = f.readlines()
for k in range(0,len(line)):
if "_Mo" in line[k]:
if "Mean_Mo" in line[k]:
words = re.split(':\t',line[k])
meanmo = words[1].strip('\n')
mu_mo.append(meanmo)
elif "Sigma_Mo" in line[k]:
words = re.split(':\t',line[k])
sigmamo = words[1].strip('\n')
sig_mo.append(sigmamo)
else:
if "Mean_"+material in line[k]:
words = re.split(':\t',line[k])
mean = words[1].strip('\n')
mu_in.append(mean)
elif "Sigma_"+material in line[k]:
words = re.split(':\t',line[k])
sigma = words[1].strip('\n')
sig_in.append(sigma)
f.close()
elif XRSource == 'Cu':
if('MoC_' in name):
material = 'Mo'
f = open(file,'r')
line = f.readlines()
for k in range(0,len(line)):
if "_Cu" in line[k]:
if "Mean_Cu" in line[k]:
words = re.split(':\t',line[k])
meancu = words[1].strip('\n')
mu_cu.append(meancu)
elif "Sigma_Cu" in line[k]:
words = re.split(':\t',line[k])
sigmacu = words[1].strip('\n')
sig_cu.append(sigmacu)
else:
if "Mean_"+material in line[k]:
words = re.split(':\t',line[k])
mean = words[1].strip('\n')
mu_mo.append(mean)
elif "Sigma_"+material in line[k]:
words = re.split(':\t',line[k])
sigma = words[1].strip('\n')
sig_mo.append(sigma)
f.close()
elif('AgC_' in name):
material = 'Ag'
f = open(file,'r')
line = f.readlines()
for k in range(0,len(line)):
if "_Cu" in line[k]:
if "Mean_Cu" in line[k]:
words = re.split(':\t',line[k])
meancu = words[1].strip('\n')
mu_cu.append(meancu)
elif "Sigma_Cu" in line[k]:
words = re.split(':\t',line[k])
sigmacu = words[1].strip('\n')
sig_cu.append(sigmacu)
else:
if "Mean_"+material in line[k]:
words = re.split(':\t',line[k])
mean = words[1].strip('\n')
mu_ag.append(mean)
elif "Sigma_"+material in line[k]:
words = re.split(':\t',line[k])
sigma = words[1].strip('\n')
sig_ag.append(sigma)
f.close()
elif('SnC_' in name):
material = 'Sn'
convfact= 25271/3.6
f = open(file,'r')
line = f.readlines()
for k in range(0,len(line)):
if "_Cu" in line[k]:
if "Mean_Cu" in line[k]:
words = re.split(':\t',line[k])
meancu = words[1].strip('\n')
mu_cu.append(meancu)
elif "Sigma_Cu" in line[k]:
words = re.split(':\t',line[k])
sigmacu = words[1].strip('\n')
sig_cu.append(sigmacu)
else:
if "Mean_"+material in line[k]:
words = re.split(':\t',line[k])
mean = words[1].strip('\n')
mu_sn.append(mean)
elif "Sigma_"+material in line[k]:
words = re.split(':\t',line[k])
sigma = words[1].strip('\n')
sig_sn.append(sigma)
f.close()
elif('InC_' in name):
material = 'In'
convfact= 24207/3.6
f = open(file,'r')
line = f.readlines()
for k in range(0,len(line)):
if "_Cu" in line[k]:
if "Mean_Cu" in line[k]:
words = re.split(':\t',line[k])
meancu = words[1].strip('\n')
mu_cu.append(meancu)
elif "Sigma_Cu" in line[k]:
words = re.split(':\t',line[k])
sigmacu = words[1].strip('\n')
sig_cu.append(sigmacu)
else:
if "Mean_"+material in line[k]:
words = re.split(':\t',line[k])
mean = words[1].strip('\n')
mu_in.append(mean)
elif "Sigma_"+material in line[k]:
words = re.split(':\t',line[k])
sigma = words[1].strip('\n')
sig_in.append(sigma)
f.close()
n_cu = len(mu_cu)
n_mo = len(mu_mo)
n_ag = len(mu_ag)
n_sn = len(mu_sn)
n_in = len(mu_in)
n_all = n_cu + n_mo + n_sn + n_ag+ n_in
sigma_y = [0]*n_all
mus = mu_cu + mu_mo + mu_ag + mu_sn + mu_in
sigma_x = sig_cu + sig_mo + sig_ag+ sig_sn + sig_in
k_cu = [convfactcu]*n_cu
k_mo = [convfactmo]*n_mo
k_ag = [convfactag]*n_ag
k_sn = [convfactsn]*n_sn
k_in = [convfactin]*n_in
k = k_cu + k_mo + k_ag + k_sn+k_in
matrix = np.zeros(((len(mus)),4))
print "mus", mus, len(matrix)
a=0
for j in [0,1,2, 3, 4 ,5 ,6, 7]: #range(0,len(mus)):
a = j
matrix[a][1] = float(mus[j])
matrix[a][0] = float(k[j])
matrix[a][3] = float(sigma_x[j])
table = open('SummaryTable'+'_'+output+'_'+'C_'+str(i)+'.txt','w')
np.savetxt("SummaryTable"+'_'+output+'_'+"C_"+str(i)+".txt",matrix, delimiter="\t", fmt="%s", newline='\n' )
gStyle.SetOptFit(1)
c1 = TCanvas('c1',"Fluorescence test",1)
c1.cd()
c1.Update()
gStyle.SetOptStat(0)
gr = TGraphErrors("SummaryTable"+'_'+output+'_'+"C_"+str(i)+".txt")
gr.SetMarkerStyle(41)
fit = TF1("fit","pol1",1000,10000)
gr.Fit("fit","w","l",1000,10000)
gr.SetMarkerStyle(20)
n_o = gr.GetFunction("fit").GetParameter(0)
n_o_er = gr.GetFunction("fit").GetParError(0)
slope = gr.GetFunction("fit").GetParameter(1)
pn_o = -(n_o/slope)
pn_o_er =abs(n_o_er/slope)
pslope = 1/slope
slope_err = gr.GetFunction("fit").GetParError(1)
pslope_err = slope_err /( slope*slope)
chisquare = gr.GetFunction("fit").GetChisquare()
ndf = gr.GetFunction("fit").GetNDF()
print "no:",pn_o
print "no error:", pn_o_er
print "slope:",pslope
print "slope error:",pslope_err
sumout.write( "C_" + str(i) + " "+ '{0:.2}'.format(pslope) + " +/- " + '{0:.1}'.format(pslope_err) +" " + '{0:.2}'.format(pn_o) + " +/- " + '{0:.2}'.format(pn_o_er)+ '\n' )
gStyle.SetOptFit(0)
gr.Draw("AP")
#gr.GetYaxis().SetRange(0,300)
#gr.GetXaxis().SetRange(0,8000)
title = "Graph eV vs Vcal for ROC " + str(i) + " "
gr.SetTitle( title )
gr.GetYaxis().SetTitle("Vcal")
gr.GetXaxis().SetTitle("No.Electrons")
gStyle.SetOptStat(0)
c1.Update()
gStyle.SetOptFit(0)
gr.Draw("AP")
gStyle.SetOptFit(0)
#ps = c1.FindObject("Graph").FindObject("stats")
#ps.SetX1NDC(0.15)
#ps.SetX2NDC(0.55)
#gStyle.SetOptStat(0)
c1.SetGrid()
textslope = TLatex()
textslope.SetNDC()
textslope.SetTextColor(kBlack)
textslope.SetTextSize(0.05)
textslope.DrawLatex(0.15,0.9,title)
textslope.DrawLatex(0.15,0.8,"e^{-}/Vcal: "+ '{0:.2}'.format(pslope) + " \pm " + '{0:.1}'.format(pslope_err) +
" Intercept: " + '{0:.2}'.format(pn_o) + " \pm " + '{0:.2}'.format(pn_o_er))
textslope.DrawLatex(0.2,0.2," Cu Mo Ag In Sn")
textslope.DrawLatex(0.15,0.7,"#chi^{2}/ndf = " + '{0:.4}'.format(chisquare/ndf))
gStyle.SetOptFit(0)
c1.Update()
gStyle.SetOptFit(0)
c1.Update()
c1.SaveAs('Qplot'+'_'+output+'_C'+str(i)+'.png')
c1.Close()
c1.Update()
gStyle.SetOptStat(1)
c1.Update()
##get q value of fit and error and add them to a table then use TGraphError to make a distribution of them
n_oh.Fill(-n_o/slope)
slopeh.Fill(1/slope)
qmatrix[i][0] = 1/slope
qmatrix[i][1] = -n_o/slope
qmatrix[i][2] = chisquare
qmatrix[i][3] = ndf
qmatrix[i][4] = slope_err/pow(slope,2)
# Create SummaryQPlots txt file:
np.savetxt("SummaryDistributionTable"+'_'+output+'_'+".txt",qmatrix, delimiter="\t", fmt="%s", newline='\n' )
FormattedFile = open("FluorFormatedOutput" + output + ".txt", "w")
FormattedFile.write("Roc Number Slope (e-/Vcal) Offset (Vcal) Chi2/NDf\n")
for iroc in rocs:
FormattedFile.write("ROC "+str(iroc)+" "+str(round(qmatrix[iroc][0],2))+" +/- "+str(round(qmatrix[iroc][4],4))+" "+str(int(round(qmatrix[iroc][1])))+" "+str(round(qmatrix[iroc][2]/qmatrix[iroc][3],4))+"\n")
FormattedFile.close()
c2 = TCanvas('c2',"Distribution N_o",1)
c2.cd()
gStyle.SetOptStat(1)
n_oh.Draw()
n_oh.SetStats(1)
c2.Update()
ps2 = n_oh.GetListOfFunctions().FindObject("stats")
gStyle.SetOptStat(0)
n_oh.Draw()
c2.Update()
c2.SaveAs(output+'Distribution_NoEle.png')
c3 = TCanvas('c3',"Distribution N_o",1)
c3.cd()
gStyle.SetOptStat(1)
slopeh.Draw()
slopeh.SetStats(1)
c3.Update()
slopeh.GetXaxis().SetTitle("p1[Vcal/No.Ele]")
slopeh.GetYaxis().SetTitle("Entries")
gStyle.SetOptStat(1)
slopeh.Draw()
c3.Update()
c3.SaveAs(output+'Distribution_Slope.png')
sumout.close()
return
# _
# _ __ ___ __ _(_)_ __
#| '_ ` _ \ / _` | | '_ \
#| | | | | | (_| | | | | |
#|_| |_| |_|\__,_|_|_| |_|
if options.setup == 'UIC':
rootfile1 = TFile(options.MoFile)
rootfile1name = options.MoFile
material1 = 'Mo'
XRSource = 'Cu'
elif options.setup =='KU':
rootfile1 = TFile(options.CuFile)
rootfile1name = options.CuFile
material1 = 'Cu'
XRSource = 'Mo'
rootfile2 = TFile(options.AgFile)
rootfile2name = options.AgFile
rootfile3 = TFile(options.SnFile)
rootfile3name = options.SnFile
rootfile4 = TFile(options.InFile)
rootfile4name = options.InFile
outrootfile = TFile('histos.root')
histname = options.histoname
nrocs = options.nrocs
for item in options.badrocs.split():
if item in rocs: rocs.remove( item )
output = options.outputfile
material2 = 'Ag'
material3 = 'Sn'
material4 = 'In'
hist1 = histname+"_"+material1+"_C"
hist2 = histname+"_"+material2+"_C"
hist3 = histname+"_"+material3+"_C"
hist4 = histname+"_"+material4+"_C"
gROOT.SetBatch(kTRUE)
Arraytgt1 = FitPeaks(rootfile1,hist1,material1,rocs,output, XRSource, 2)
Arraytgt2 = FitPeaks(rootfile2,hist2,material2,rocs,output,XRSource, 2)
Arraytgt3 = FitPeaks(rootfile3,hist3,material3,rocs,output,XRSource, 2)
Arraytgt4 = FitPeaks(rootfile4,hist4,material4,rocs,output,XRSource, 2)
PlotSameNStats(Arraytgt1,Arraytgt2,Arraytgt3,Arraytgt4,rocs,output,XRSource)
ConversionPlot(rocs, output,XRSource)
outrootfile.Write()
outrootfile.Close()
print "Thats all Folks!"