/
fit_rise_times_of_data_using_pulser_fit_inputs.py
881 lines (687 loc) · 33 KB
/
fit_rise_times_of_data_using_pulser_fit_inputs.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
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime,timedelta
import scipy.integrate as integrate
from scipy.optimize import curve_fit,leastsq
import parameters
from cogent_utilities import *
from fitting_utilities import *
from lichen.plotting_utilities import *
import lichen.pdfs as pdfs
import lichen.iminuit_fitting_utilities as fitutils
import lichen.lichen as lch
import iminuit as minuit
import argparse
import math
pi = np.pi
first_event = 2750361.2
start_date = datetime(2009, 12, 3, 0, 0, 0, 0) #
np.random.seed(200)
yearly_mod = 2*pi/365.0
# The entries for the narrow peak parameters.
# Using rt 0-6
#fast_mean0_k = [2.843792,2.265467,-1.096411]
#fast_sigma0_k = [3.350738,1.905592,0.224210]
#fast_num0_k = [6.540050,7926.775305,226.999254]
# The entries for the relationship between the broad and narrow peak.
# Using rt 0-6
#fast_mean_rel_k = [0.649640,-1.655929,-0.069965]
#fast_sigma_rel_k = [-3.667547,0.000256,-0.364826]
#fast_num_rel_k = [-2.831665,0.023649,1.144240]
# The entries for the narrow peak parameters.
# Using rt 0-8
#fast_mean0_k = [2.886805,2.402053,-1.095967]
#fast_sigma0_k = [3.250484,1.843179,0.222638]
#fast_num0_k = [6.140687,6587.374388,226.528560]
#fast_mean_rel_k = [0.792906,-1.628538,-0.201567]
#fast_sigma_rel_k = [-3.391094,0.000431,-0.369056]
#fast_num_rel_k = [-3.158560,0.014129,1.229496]
# Using Nicole's simulated data
# Using rt 0-8
#fast_mean0_k = [0.474833,0.660031,-1.518465]
#fast_sigma0_k = [0.496104,0.437982,0.143220]
#fast_num0_k = [1.203499,-1346.267581,1060.346657]
#
#fast_mean_rel_k = [0.431998,-1.525604,-0.024960]
#fast_sigma_rel_k = [-0.014644,5.745791,-6.168695]
#fast_num_rel_k = [-0.261322,5.553102,-5.9144]
#emid = 1.0 # Make this global for ease of fitting.
# Will use this later when trying to figure out the energy dependence of
# the log-normal parameters.
# define our (line) fitting function
expfunc = lambda p, x: p[1]*np.exp(-p[0]*x) + p[2]
errfunc = lambda p, x, y, err: (y - expfunc(p, x)) / err
expfunc1 = lambda p, x: p[1]*x + p[0]
errfunc1 = lambda p, x, y, err: (y - expfunc1(p, x)) / err
#fast_sigma0_optimal = 1.0
#fast_sigma0_uncert = 1.0
################################################################################
# Rise time fit
################################################################################
def fitfunc(data,p,parnames,params_dict):
pn = parnames
flag = p[pn.index('flag')]
pdf = None
x = data
xlo = params_dict['var_rt']['limits'][0]
xhi = params_dict['var_rt']['limits'][1]
tot_pdf = np.zeros(len(x))
#print "HERE"
#print data[data<0]
#print data[data>5.0]
############################################################################
# Log-norm structures
############################################################################
means = []
sigmas = []
nums = []
emid = p[pn.index('emid')]
num_tot = 0.0
num_tot += p[parnames.index("fast_num")]
num_tot += p[parnames.index("slow_num")]
fast_mean_rel_k = [p[pn.index('fast_mean_rel_k_0')],
p[pn.index('fast_mean_rel_k_1')],
p[pn.index('fast_mean_rel_k_2')]]
fast_sigma_rel_k = [p[pn.index('fast_sigma_rel_k_0')],
p[pn.index('fast_sigma_rel_k_1')],
p[pn.index('fast_sigma_rel_k_2')]]
fast_num_rel_k = [p[pn.index('fast_num_rel_k_0')],
p[pn.index('fast_num_rel_k_1')],
p[pn.index('fast_num_rel_k_2')]]
fast_logn_mean0 = p[pn.index('fast_logn_mean0')]
fast_logn_sigma0 = p[pn.index('fast_logn_sigma0')]
fast_logn_frac0 = p[pn.index('fast_logn_frac0')]
#print "fast_logn_frac0: ", fast_logn_frac0
slow_logn_mean = p[pn.index('slow_logn_mean')]
slow_logn_sigma = p[pn.index('slow_logn_sigma')]
fast_num = p[pn.index('fast_num')]/num_tot
slow_num = p[pn.index('slow_num')]/num_tot
#print means,sigmas,nums
# The entries for the relationship between the broad and narrow peak.
#print "emid: ",emid
fast_logn_mean_rel = expfunc(fast_mean_rel_k,emid)
fast_logn_sigma_rel = expfunc(fast_sigma_rel_k,emid)
fast_logn_num_rel = expfunc(fast_num_rel_k,emid)
fast_logn_mean1 = fast_logn_mean0 - fast_logn_mean_rel
fast_logn_sigma1 = fast_logn_sigma0 - fast_logn_sigma_rel
#fast_num1 = fast_num0 / fast_num_rel
#fast_logn_frac0 = fast_logn_num0/(fast_num0+fast_num1)
#print "IN FITFUNC: ",fast_logn_mean0,fast_logn_sigma0,fast_logn_mean1,fast_logn_sigma1
pdffast0 = pdfs.lognormal(x,fast_logn_mean0,fast_logn_sigma0,xlo,xhi)
pdffast1 = None
if emid<=1.9:
pdffast1 = pdfs.lognormal(x,fast_logn_mean1,fast_logn_sigma1,xlo,xhi)
else:
fast_logn_frac0 = 1.0
pdffast1 = np.zeros(len(x))
pdfslow = pdfs.lognormal(x,slow_logn_mean, slow_logn_sigma, xlo,xhi)
tot_pdf = fast_num*(fast_logn_frac0*pdffast0 + (1.0-fast_logn_frac0)*pdffast1) + slow_num*pdfslow
'''
for n,m,s in zip(nums,means,sigmas):
pdf = pdfs.lognormal(x,m,s,xlo,xhi)
pdf *= n
tot_pdf += pdf
'''
return tot_pdf
################################################################################
# Extended maximum likelihood function for minuit, normalized already.
################################################################################
def emlf(data,p,parnames,params_dict):
#print data[0]
ndata = len(data[0])
flag = p[parnames.index('flag')]
# Constrain this.
num_tot = 0.0
num_tot += p[parnames.index("fast_num")]
num_tot += p[parnames.index("slow_num")]
tot_pdf = fitfunc(data[0],p,parnames,params_dict)
likelihood_func = (-np.log(tot_pdf)).sum()
#print num_tot,ndata
ret = likelihood_func - fitutils.pois(num_tot,ndata)
# GAUSSIAN CONSTRAINT
for parm in ['mean','sigma']:
mu = p[parnames.index("fast_logn_"+parm+"0")]
mu0 = p[parnames.index("fast_logn_"+parm+"0_optimal")]
sig = p[parnames.index("fast_logn_"+parm+"0_uncert")]
# We are taking the log of the likelihood, so the exponential in the Gaussian function
# goes away.
gc = ((mu-mu0)**2)/(2.0*sig*sig)
#print "Gaussian constraint: ",gc,mu,mu0,sig
ret += gc
return ret
################################################################################
################################################################################
# Read in the CoGeNT data
################################################################################
def main():
############################################################################
# Parse the command lines.
############################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--fit', dest='fit', type=int,\
default=0, help='Which fit to perform (0,1,2)')
parser.add_argument('--verbose', dest='verbose', action='store_true',\
default=False, help='Verbose output')
parser.add_argument('--rt-parameters', dest='rt_parameters', type=str,\
default='risetime_parameters_risetime_determination_nicole.py', help='File of rise-time parameters determined from wavelet or pulser data.')
parser.add_argument('--batch', dest='batch', action='store_true',\
default=False, help='Run in batch mode (exit on completion).')
args = parser.parse_args()
#tag = 'data_constrained_with_pulser_mean20_sigma20_slowsigfloat'
#tag = 'data_constrained_with_pulser'
#tag = 'data_constrained_with_simulated_Nicole'
############################################################################
'''
if args.help:
parser.print_help()
exit(-1)
'''
# Read in the parameters from the file passed in on the commandline
rt_parameters_filename = args.rt_parameters.rstrip('.py')
tag = rt_parameters_filename
print(("Rise-time parameters_filename: %s" % (rt_parameters_filename)))
rt_parameters_file = __import__(rt_parameters_filename)
risetime_parameters = getattr(rt_parameters_file,'risetime_parameters')
fast_mean_rel_k,fast_sigma_rel_k,fast_num_rel_k,fast_mean0_k,fast_sigma0_k,fast_num0_k = risetime_parameters()
############################################################################
# Read in the data
############################################################################
infile_name = 'data/LE.txt'
#infile_name = 'data/HE.txt'
#infile_name = 'data/pulser_data.dat'
tdays,energies,rise_times = get_3yr_cogent_data(infile_name,first_event=first_event,calibration=0)
print (tdays)
print (energies)
print (rise_times)
print (energies)
if args.verbose:
print_data(energies,tdays,rise_times)
#data = [energies.copy(),tdays.copy()]
#print "data before range cuts: ",len(data[0]),len(data[1])
# 3yr data
data = [energies.copy(),tdays.copy(),rise_times.copy()]
print(("data before range cuts: ",len(data[0]),len(data[1]),len(data[2])))
#exit()
############################################################################
# Declare the ranges.
############################################################################
ranges,subranges,nbins = parameters.fitting_parameters(args.fit)
bin_widths = np.ones(len(ranges))
for i,n,r in zip(list(range(len(nbins))),nbins,ranges):
bin_widths[i] = (r[1]-r[0])/n
# Cut events out that fall outside the range.
data = cut_events_outside_range(data,ranges)
data = cut_events_outside_subrange(data,subranges[1],data_index=1)
if args.verbose:
print_data(energies,tdays)
print(("data after range cuts: ",len(data[0]),len(data[1])))
nevents = float(len(data[0]))
plt.figure()
plt.plot(energies,rise_times,'o',markersize=1.5)
plt.yscale('log')
plt.ylim(0.1,10)
plt.figure()
plt.plot(tdays,rise_times,'o',markersize=1.5)
plt.yscale('log')
plt.ylim(0.1,10)
############################################################################
# Plot the data
############################################################################
############################################################################
# Look at the rise-time information.
############################################################################
# For the data (two lognormals)
#starting_params = [-0.6,0.6,0.2*nevents, 0.1,0.8,0.8*nevents]
# For the pulser fast rise times (two lognormals)
starting_params = [-0.6,0.5,0.6*nevents, 0.5,0.8,0.4*nevents]
fit_parameters = []
fit_errors = []
fit_mnerrors = []
nevs = []
axrt = []
elo = 0.0
ehi = 1.0
eoffset = 0.5
ewidth = 0.100
estep = 0.100
#ewidth = 0.150
#estep = 0.150
#ewidth = 0.200
#estep = 0.050
expts = []
figcount = 0
maxrange = int((ranges[0][1]-ranges[0][0])/ewidth)
#for i in range(48,-1,-1):
for i in range(0,maxrange):
#j = 48-i
j = i
if j%6==0:
figrt = plt.figure(figsize=(12,6),dpi=100)
axrt.append(figrt.add_subplot(2,3, i%6 + 1))
#figrt = plt.figure(figsize=(6,4),dpi=100)
#axrt.append(figrt.add_subplot(1,1,1))
data_to_fit = []
#h,xpts,ypts,xpts_err,ypts_err = lch.hist_err(data[1],bins=nbins[1],range=ranges[1],axes=ax1)
if i>=0:
elo = i*estep + eoffset
ehi = elo + ewidth
index0 = data[0]>=elo
index1 = data[0]< ehi
print((elo,ehi))
index = index0*index1
data_to_fit = data[2][index]
if len(data_to_fit)>0:
lch.hist_err(data_to_fit,bins=nbins[2],range=ranges[2],axes=axrt[j])
plt.ylim(0)
plt.xlim(ranges[2][0],ranges[2][1])
name = "%0.2f-%0.2f" % (elo,ehi)
plt.text(0.75,0.75,name,transform=axrt[j].transAxes)
print ("=======-------- E BIN ----------===========")
print (name)
emid = (elo+ehi)/2.0
#print "HERE ------------------------------- emid: ",emid
# The entries for the narrow peak parameters.
fast_mean0 = expfunc(fast_mean0_k,emid)
fast_sigma0 = expfunc(fast_sigma0_k,emid)
fast_num0 = expfunc(fast_num0_k,emid)
# USE THIS FOR THE GAUSSIAN CONSTRAINT
fast_mean0_optimal = fast_mean0
fast_mean0_uncert = 0.30*fast_mean0
fast_sigma0_optimal = fast_sigma0
fast_sigma0_uncert = 0.30*fast_sigma0
# The entries for the relationship between the broad and narrow peak.
fast_mean_rel = expfunc(fast_mean_rel_k,emid)
fast_sigma_rel = expfunc(fast_sigma_rel_k,emid)
fast_logn_num_rel = expfunc(fast_num_rel_k,emid)
fast_mean1 = fast_mean0 - fast_mean_rel
fast_sigma1 = fast_sigma0 - fast_sigma_rel
fast_num1 = fast_num0 / fast_logn_num_rel
fast_logn_frac0 = fast_num0/(fast_num0+fast_num1)
nevents = len(data_to_fit)
print(("Nevents for this fit: ",nevents))
#starting_params = [-0.1,0.8,0.2*nevents, 0.6,0.52,0.8*nevents]
print((starting_params[4]))
#exit()
############################################################################
# Declare the fit parameters
############################################################################
params_dict = {}
params_dict['flag'] = {'fix':True,'start_val':args.fit}
params_dict['var_rt'] = {'fix':True,'start_val':0,'limits':(ranges[2][0],ranges[2][1])}
params_dict['emid'] = {'fix':True,'start_val':emid,'limits':(ranges[0][0],ranges[0][1])}
params_dict['fast_logn_mean0'] = {'fix':False,'start_val':fast_mean0,'limits':(-2,2),'error':0.01}
params_dict['fast_logn_sigma0'] = {'fix':False,'start_val':fast_sigma0,'limits':(0.05,30),'error':0.01}
params_dict['fast_logn_frac0'] = {'fix':True,'start_val':fast_logn_frac0,'limits':(0.0001,1.0),'error':0.01}
#params_dict['fast_num'] = {'fix':False,'start_val':0.5*nevents,'limits':(0.0,1.5*nevents),'error':0.01}
params_dict['fast_num'] = {'fix':False,'start_val':starting_params[2],'limits':(0.0,1.5*nevents),'error':0.01}
params_dict['fast_logn_sigma0_optimal'] = {'fix':True,'start_val':fast_sigma0_optimal}
params_dict['fast_logn_sigma0_uncert'] = {'fix':True,'start_val':fast_sigma0_uncert}
params_dict['fast_logn_mean0_optimal'] = {'fix':True,'start_val':fast_mean0_optimal}
params_dict['fast_logn_mean0_uncert'] = {'fix':True,'start_val':fast_mean0_uncert}
#params_dict['fast_logn_mean1'] = {'fix':False,'start_val':starting_params[0],'limits':(-2,2),'error':0.01}
#params_dict['fast_logn_sigma1'] = {'fix':False,'start_val':starting_params[1],'limits':(0.05,30),'error':0.01}
#params_dict['fast_num1'] = {'fix':False,'start_val':nevents,'limits':(0.0,1.5*nevents),'error':0.01}
# float them
params_dict['slow_logn_mean'] = {'fix':False,'start_val':starting_params[3],'limits':(-2,2),'error':0.01}
params_dict['slow_logn_sigma'] = {'fix':False,'start_val':starting_params[4],'limits':(0.05,30),'error':0.01}
params_dict['slow_num'] = {'fix':False,'start_val':starting_params[5],'limits':(0.0,1.5*nevents),'error':0.01}
# Fixed values
params_dict['fast_mean_rel_k_0'] = {'fix':True,'start_val':fast_mean_rel_k[0],'limits':(-1e6,1e6),'error':0.01}
params_dict['fast_mean_rel_k_1'] = {'fix':True,'start_val':fast_mean_rel_k[1],'limits':(-1e6,1e6),'error':0.01}
params_dict['fast_mean_rel_k_2'] = {'fix':True,'start_val':fast_mean_rel_k[2],'limits':(-1e6,1e6),'error':0.01}
params_dict['fast_sigma_rel_k_0'] = {'fix':True,'start_val':fast_sigma_rel_k[0],'limits':(-1e6,1e6),'error':0.01}
params_dict['fast_sigma_rel_k_1'] = {'fix':True,'start_val':fast_sigma_rel_k[1],'limits':(-1e6,1e6),'error':0.01}
params_dict['fast_sigma_rel_k_2'] = {'fix':True,'start_val':fast_sigma_rel_k[2],'limits':(-1e6,1e6),'error':0.01}
params_dict['fast_num_rel_k_0'] = {'fix':True,'start_val':fast_num_rel_k[0],'limits':(-1e6,1e6),'error':0.01}
params_dict['fast_num_rel_k_1'] = {'fix':True,'start_val':fast_num_rel_k[1],'limits':(-1e6,1e6),'error':0.01}
params_dict['fast_num_rel_k_2'] = {'fix':True,'start_val':fast_num_rel_k[2],'limits':(-1e6,1e6),'error':0.01}
'''
if i==7:
params_dict['slow_logn_mean'] = {'fix':True,'start_val':0.57,'limits':(-2,2),'error':0.01}
elif i==8:
params_dict['slow_logn_mean'] = {'fix':True,'start_val':0.55,'limits':(-2,2),'error':0.01}
'''
# Above some value, lock this down.
'''
if elo>=2.2:
params_dict['slow_logn_mean'] = {'fix':True,'start_val':0.0,'limits':(-2,2),'error':0.01}
params_dict['slow_logn_sigma'] = {'fix':True,'start_val':1.0,'limits':(0.05,30),'error':0.01}
params_dict['slow_num'] = {'fix':True,'start_val':1,'limits':(0.0,1.5*nevents),'error':0.01}
'''
'''
if i==0:
None
# From Nicole's simulation.
#params_dict['fast_logn_mean'] = {'fix':True,'start_val':-0.10,'limits':(-2,2),'error':0.01}
# From Juan
#params_dict['fast_logn_mean'] = {'fix':True,'start_val':-0.60,'limits':(-2,2),'error':0.01}
#params_dict['slow_logn_sigma'] = {'fix':True,'start_val':0.50,'limits':(0.05,30),'error':0.01}
'''
# Try fixing the slow sigma
#params_dict['slow_logn_sigma'] = {'fix':True,'start_val':0.60,'limits':(-2,2),'error':0.01}
#figrt.subplots_adjust(left=0.07, bottom=0.15, right=0.95, wspace=0.2, hspace=None,top=0.85)
#figrt.subplots_adjust(left=0.05, right=0.98)
#figrt.subplots_adjust(left=0.15, right=0.98,bottom=0.15)
figrt.subplots_adjust(left=0.07, right=0.98,bottom=0.10)
#plt.show()
#exit()
############################################################################
# Fit
############################################################################
if i>=0 and len(data_to_fit)>0:
params_names,kwd = fitutils.dict2kwd(params_dict)
#print data_to_fit
f = fitutils.Minuit_FCN([[data_to_fit]],params_dict,emlf)
# For maximum likelihood method.
kwd['errordef'] = 0.5
kwd['print_level'] = 0
#print kwd
m = minuit.Minuit(f,**kwd)
m.print_param()
m.migrad()
#m.hesse()
m.minos()
print ("Finished fit!!\n")
values = m.values # Dictionary
errors = m.errors # Dictionary
mnerrors = m.get_merrors()
print ("MNERRORS: ")
print (mnerrors)
fit_parameters.append(values)
fit_errors.append(errors)
fit_mnerrors.append(mnerrors)
nevs.append(len(data_to_fit))
xpts = np.linspace(ranges[2][0],ranges[2][1],1000)
tot_ypts = np.zeros(len(xpts))
# The entries for the relationship between the broad and narrow peak.
fast_logn_mean_rel = expfunc(fast_mean_rel_k,values['emid'])
fast_logn_sigma_rel = expfunc(fast_sigma_rel_k,values['emid'])
fast_logn_num_rel = expfunc(fast_num_rel_k,values['emid'])
fast_logn_mean1 = values['fast_logn_mean0'] - fast_logn_mean_rel
fast_logn_sigma1 = values['fast_logn_sigma0'] - fast_logn_sigma_rel
tot_ypts_fast = np.zeros(len(xpts))
ypts = pdfs.lognormal(xpts,values['fast_logn_mean0'],values['fast_logn_sigma0'],ranges[2][0],ranges[2][1])
y,plot = plot_pdf(xpts,ypts,bin_width=bin_widths[2],scale=values['fast_logn_frac0']*values['fast_num'],fmt='r--',linewidth=2,axes=axrt[j])
tot_ypts += y
tot_ypts_fast += y
# Only plot the second narrow bump above some value.
if emid<=3.9:
ypts = pdfs.lognormal(xpts,fast_logn_mean1,fast_logn_sigma1,ranges[2][0],ranges[2][1])
y,plot = plot_pdf(xpts,ypts,bin_width=bin_widths[2],scale=(1.0-values['fast_logn_frac0'])*values['fast_num'],fmt='r--',linewidth=2,axes=axrt[j])
tot_ypts += y
tot_ypts_fast += y
ypts = pdfs.lognormal(xpts,values['slow_logn_mean'],values['slow_logn_sigma'],ranges[2][0],ranges[2][1])
y,plot = plot_pdf(xpts,ypts,bin_width=bin_widths[2],scale=values['slow_num'],fmt='b-',linewidth=2,axes=axrt[j])
tot_ypts += y
axrt[j].plot(xpts,tot_ypts_fast,'r-',linewidth=2)
axrt[j].plot(xpts,tot_ypts,'m',linewidth=2)
axrt[j].set_ylabel(r'Events')
axrt[j].set_xlabel(r'Rise time ($\mu$s)')
axrt[j].set_xlim(0,5.0)
if j%6==5:
name = "Plots/rt_slice_%s_%d.png" % (tag,figcount)
plt.savefig(name)
figcount += 1
#'''
if math.isnan(values['fast_logn_mean0']) == False:
starting_params = [ \
values['fast_logn_mean0'], \
values['fast_logn_sigma0'], \
values['fast_num'], \
values['slow_logn_mean'], \
values['slow_logn_sigma'],
values['slow_num'] \
]
#'''
expts.append((ehi+elo)/2.0)
#plt.show()
#exit()
print (fit_parameters)
print (nevs)
ypts = [[],[],[],[],[],[]]
yerr = [[],[],[],[],[],[]]
yerrlo = [[],[],[],[],[],[]]
yerrhi = [[],[],[],[],[],[]]
npts = []
if len(expts)>0:
#for i,fp,fe,n in zip(xrange(len(nevs)),fit_parameters,fit_errors,nevs):
for i,fp,fe,n in zip(list(range(len(nevs))),fit_parameters,fit_mnerrors,nevs):
print ("----------")
#ypts[0].append(fp['fast_logn_mean'])
#ypts[1].append(fp['fast_logn_sigma'])
#ypts[2].append(fp['fast_num'])
#ypts[3].append(fp['slow_logn_mean'])
#ypts[4].append(fp['slow_logn_sigma'])
#ypts[5].append(fp['slow_num'])
pars = ['fast_logn_mean0','fast_logn_sigma0','fast_num',\
'slow_logn_mean','slow_logn_sigma','slow_num']
for i,p in enumerate(pars):
#print "key ",p
#if fe.has_key(p):
if p in fe:
ypts[i].append(fp[p])
#print "val: ",fp[p]
yerrlo[i].append(abs(fe[p]['lower']))
yerrhi[i].append(abs(fe[p]['upper']))
elif p=='slow_logn_sigma':
ypts[i].append(starting_params[4])
yerrlo[i].append(0.0)
yerrhi[i].append(0.0)
else:
ypts[i].append(0.0)
yerrlo[i].append(0.0)
yerrhi[i].append(0.0)
npts.append(n)
for i in range(len(ypts)):
ypts[i] = np.array(ypts[i])
yerrlo[i] = np.array(yerrlo[i])
yerrhi[i] = np.array(yerrhi[i])
colors = ['r','b']
labels = ['fast','slow']
# Use all or some of the points
nfitpts = len(expts)
#xp = np.linspace(min(expts),max(expts),100)
print ("herherherkehre")
print (nfitpts)
print (expts)
xp = np.linspace(min(expts),expts[nfitpts-1],100)
expts = np.array(expts)
yfitpts = []
'''
fvals2 = plt.figure(figsize=(13,6),dpi=100)
for k in range(0,3):
# Some of the broad rise times are set to 0.
#index0s = ypts[3+k]!=0
index0s = np.ones(len(ypts[3+k])).astype(bool)
#index0s = np.ones(nfitpts).astype(bool)
fvals2.add_subplot(2,3,k+1)
tempypts = ypts[0+k]-ypts[3+k]
# Fractional error
tempyerrlo = np.sqrt((yerrlo[0+k])**2 + (yerrlo[3+k])**2)
tempyerrhi = np.sqrt((yerrhi[0+k])**2 + (yerrhi[3+k])**2)
if k>1:
tempypts = ypts[0+k][index0s]/ypts[3+k][index0s]
tempyerrlo = np.sqrt((yerrlo[0+k][index0s]/ypts[3+k][index0s])**2 + (yerrlo[3+k][index0s]*(ypts[0+k][index0s]/(ypts[3+k][index0s]**2)))**2)
tempyerrhi = np.sqrt((yerrhi[0+k][index0s]/ypts[3+k][index0s])**2 + (yerrhi[3+k][index0s]*(ypts[0+k][index0s]/(ypts[3+k][index0s]**2)))**2)
print expts
print index0s
print expts[index0s]
print tempypts[index0s]
print tempyerrlo[index0s]
print tempyerrhi[index0s]
plt.errorbar(expts[index0s],tempypts[index0s],xerr=0.01,yerr=[tempyerrlo[index0s],tempyerrhi[index0s]],\
fmt='o',ecolor='k',mec='k',mfc='m',label='Ratio')
plt.xlim(0.5,3.5)
########################################################################
# Fit to exponentials.
########################################################################
pinit = [1,1,1]
if k==0:
pinit = [1.0, 1.0, -1.2]
elif k==1:
pinit = [1.0, -1.0, -0.5]
elif k==2:
pinit = [-2.0, 1.0, 2.0]
index = np.arange(0,len(tempypts))
print "WHHHHYYYYYY"
print expts
print index
print expts[index]
print tempypts[index]
print tempyerrlo[index]
print tempyerrhi[index]
if sum(tempypts[index]) > 0:
out = leastsq(errfunc, pinit, args=(expts[index], tempypts[index], (tempyerrlo[index]+tempyerrhi[index])/2.0), full_output=1)
z = out[0]
zcov = out[1]
print "Differences and ratios: %d [%f,%f,%f]" % (k,z[0],z[1],z[2])
#print "zcov: ",zcov
if zcov is not None:
print "Differences and ratios: %d [%f,%f,%f]" % (k,np.sqrt(zcov[0][0]),np.sqrt(zcov[1][1]),np.sqrt(zcov[2][2]))
yfitpts = expfunc(z,xp)
#print zcov
plt.plot(xp,yfitpts,'-',color='m')
'''
########################################################################
# Try to fit the individual distributions.
########################################################################
# To hold the means and widths for the fast and slow rise-time distributions.
means = []
sigmas = []
yfitpts = []
for i in range(0,6):
yfitpts.append(np.zeros(len(xp)))
fvals = plt.figure(figsize=(13,4),dpi=100)
for k in range(0,3):
fvals.add_subplot(1,3,k+1)
for ik in range(0,2):
nindex = k+3*ik
plt.errorbar(expts,ypts[nindex],xerr=0.01,yerr=[yerrlo[nindex],yerrhi[nindex]],\
fmt='o',ecolor='k',mec='k',mfc=colors[ik],label=labels[ik])
#'''
# Use part of the data
#index0 = np.arange(0,3)
#index1 = np.arange(7,len(expts))
#index = np.append(index0,index1)
# Use all or some of the points
index = np.arange(0,len(expts))
#index = np.arange(0,20)
if ik>0:
index = np.arange(0,len(expts))
#print index
index = index[index!=7]
index = index[index!=8]
index = index[index!=17]
index = index[index!=18]
index = index[index!=19]
########################################################################
# Fit to exponentials.
########################################################################
pinit = [1,1,1]
if ik==0 and k==0:
pinit = [1.0, 1.0, -1.2]
elif ik==0 and k==1:
pinit = [4.0, 2.0, 0.0]
elif ik==0 and k==2:
pinit = [2.0, 2000.0, 300.0]
elif ik==1 and k==0:
pinit = [3.0, 1.5, 0.5]
elif ik==1 and k==1:
pinit = [0.5, -0.1] # For linear ft
#pinit = [0.0001, 0.0001, starting_params[4]] # For exponential
#print "before fit: ",ypts[nindex][index],yerrlo[nindex][index],yerrhi[nindex][index]
print(("Fitting data!!!!!! --------------- %d %d" % (k,ik)))
#print "before fit: ",ypts[nindex][index]
if abs(sum(ypts[nindex][index])) > 0 and k<2:
print ("FITTING -----------")
#print expts[index]
#print ypts[nindex][index]
if k==1 and ik==1: ########## FIT WITH LINEAR TERM FOR SLOW SIGMA
out = leastsq(errfunc1, pinit, args=(expts[index], ypts[nindex][index], (yerrlo[nindex][index]+yerrhi[nindex][index])/2.0), full_output=1)
z = out[0]
zcov = out[1]
print(("Data points: %d %d [%f,%f]" % (k,ik,z[0],z[1])))
sigmas.append([z[0],z[1]])
'''
if zcov is not None:
print "Data points: %d %d [%f,%f]" % (k,ik,np.sqrt(zcov[0][0]),np.sqrt(zcov[1][1]))
'''
yfitpts[nindex] = expfunc1(z,xp)
#print zcov
#print plt.gca()
plt.plot(xp,yfitpts[nindex],'-',color=colors[ik])
else:
out = leastsq(errfunc, pinit, args=(expts[index], ypts[nindex][index], (yerrlo[nindex][index]+yerrhi[nindex][index])/2.0), full_output=1)
z = out[0]
zcov = out[1]
print(("Data points: %d %d [%f,%f,%f]" % (k,ik,z[0],z[1],z[2])))
if k==1 and ik==0:
sigmas.append([z[0],z[1],z[2]])
elif k==0:
means.append([z[0],z[1],z[2]])
'''
if zcov is not None:
print "Data points: %d %d [%f,%f,%f]" % (k,ik,np.sqrt(zcov[0][0]),np.sqrt(zcov[1][1]),np.sqrt(zcov[2][2]))
'''
yfitpts[nindex] = expfunc(z,xp)
#print zcov
#print plt.gca()
plt.plot(xp,yfitpts[nindex],'-',color=colors[ik])
if k==0:
plt.ylim(-1.5,1.5)
elif k==1:
plt.ylim(0.0,1.5)
plt.xlabel('Energy (keVee)')
if k==0:
plt.ylabel(r'Lognormal $\mu$')
elif k==1:
plt.ylabel(r'Lognormal $\sigma$')
elif k==2:
plt.ylabel(r'Number of events')
plt.legend()
#fval
'''
fvals.add_subplot(2,3,4)
plt.plot(xp,yfitpts[3]-yfitpts[0],'-',color='m')
fvals.add_subplot(2,3,5)
plt.plot(xp,yfitpts[4]-yfitpts[1],'-',color='m')
fvals.add_subplot(2,3,6)
plt.plot(xp,yfitpts[5]/yfitpts[2],'-',color='m')
'''
fvals.subplots_adjust(left=0.10, right=0.98,bottom=0.15,wspace=0.25,hspace=0.25)
name = 'Plots/rt_summary_%s_0.png' % (tag)
plt.savefig(name)
np.savetxt('rt_parameters.txt',[expts,ypts[0],ypts[1],ypts[2],ypts[3],ypts[4],ypts[5],npts])
#'''
#print "Sum ypts[5]: ",sum(ypts[5])
print (means)
print (sigmas)
print((fast_mean_rel_k,fast_sigma_rel_k,fast_num_rel_k))
outfilename = "risetime_parameters_from_data_%s.py" % (tag)
outfile = open(outfilename,'w')
outfile.write("def risetime_parameters():\n\n")
output = "\n\t%s = [%f,%f,%f]\n" % ("fast_mean_rel_k",fast_mean_rel_k[0],fast_mean_rel_k[1],fast_mean_rel_k[2])
outfile.write(output)
output = "\t%s = [%f,%f,%f]\n" % ("fast_sigma_rel_k",fast_sigma_rel_k[0],fast_sigma_rel_k[1],fast_sigma_rel_k[2])
outfile.write(output)
output = "\t%s = [%f,%f,%f]\n" % ("fast_num_rel_k",fast_num_rel_k[0],fast_num_rel_k[1],fast_num_rel_k[2])
outfile.write(output)
output = "\n\t%s = [%f,%f,%f]\n" % ("mu0",means[0][0],means[0][1],means[0][2])
outfile.write(output)
output = "\t%s = [%f,%f,%f]\n" % ("sigma0",sigmas[0][0],sigmas[0][1],sigmas[0][2])
outfile.write(output)
output = "\n\t%s = [%f,%f,%f]\n" % ("mu1",means[1][0],means[1][1],means[1][2])
outfile.write(output)
output = "\t%s = [%f,%f] # This has only two parameters.\n" % ("sigma1",sigmas[1][0],sigmas[1][1])
outfile.write(output)
output = "\n\treturn fast_mean_rel_k,fast_sigma_rel_k,fast_num_rel_k,mu0,sigma0,mu1,sigma1\n"
outfile.write(output)
if not args.batch:
plt.show()
#exit()
################################################################################
################################################################################
if __name__=="__main__":
main()