-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rate_Fitter_June18.py
executable file
·1548 lines (1220 loc) · 62.2 KB
/
Rate_Fitter_June18.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
#!/software/python-2.7-2014q3-el6-x86_64/bin/python
import SNANA_Reader as simread
import REAL_Reader as dataread
#import astropy.cosmology as cosmo
import traceback
import scipy
import scipy.stats as stats
import numpy as np
#import matplotlib as mpl
import matplotlib.pyplot as plt
plt.switch_backend('Agg')
import Cosmology
#import emcee as MC
#import corner
import scipy.stats.mstats as mstats
from sys import argv
import glob
import time
import os
import gzip
import shutil
import numpy.ma as ma
import subprocess
import iminuit as iM
from iminuit import Minuit as M
from discreteChi2Func import discreteChi2Func as chi2func
class Rate_Fitter:
def __init__(self, realfilename, realName, simfilename, simName, simgenfilename, MCBeta, zmin=0.1, zmax=1.20 , simOmegaM=0.3, simOmegaL=0.7, simH0=70.0, simw=-1.0, simOb0=0.049, simSigma8=0.81, simNs=0.95, Rate_Model = 'powerlaw', cheatType = False, cheatZ = False, cheatCCSub = False, cheatCCScale = False, cuts = None, nprint = 5):
self.zmin = zmin
self.zmax = zmax
self.MCBeta = MCBeta
self.Rate_Model = Rate_Model
self.cheatType = cheatType
self.cheatZ = cheatZ
self.cheatCCSub = cheatCCSub
self.cheatCCScale = cheatCCScale
self.cuts = cuts
self.nprint = nprint
self.globalChi2Storage = []
self.globalNDataStorage = []
self.globalZPhotBinStorage = []
self.globalNDataIaPhotBinStorage = []
self.globalNDataCCPhotBinStorage = []
self.globalZTrueBinStorage = []
self.globalNDataIaTrueBinStorage = []
self.globalNDataCCTrueBinStorage = []
try:
self.simcat = simread.SNANA_Cat(simfilename, simName, simOmegaM=0.3, simOmegaL=0.7, simH0=70.0, simw=-1.0, simOb0=0.049, simSigma8=0.81, simNs=0.95)
except:
self.simcat = simread.SNANA_Cat(simfilename, simName, simOmegaM=0.3, simOmegaL=0.7, simH0=70.0, simw=-1.0, simOb0=0.049, simSigma8=0.81, simNs=0.95, skip_header = 5)
self.simName = simName
self.simgencat = simread.SNANA_Cat(simfilename, simName, simOmegaM=0.3, simOmegaL=0.7, simH0=70.0, simw=-1.0, simOb0=0.049, simSigma8=0.81, simNs=0.95)
try:
SIMGEN = np.load(simgenfilename + '.npz')['a']
except:
SIMGEN = np.genfromtxt(simgenfilename, dtype=None, names = True, skip_footer=3, invalid_raise=False)
np.savez_compressed(simgenfilename+'.npz', a = SIMGEN)
print "WHY DO YOU HATE ME WHEN I SHOW YOU NOTHING BUT LOVE"
print simgenfilename
SIMGEN = SIMGEN[SIMGEN['GENZ'] != 'GENZ']
self.simgencat.params = {'flat':True, 'H0': simH0, 'Om0':simOmegaM, 'Ob0': simOb0, 'sigma8': simSigma8, 'ns': simNs}
self.simgencat.cosmo = Cosmology.setCosmology('simCosmo', self.simcat.params)
self.simgencat.OrigCatalog = np.copy(SIMGEN)
self.simgencat.Catalog = np.copy(SIMGEN)
self.simgencat.Catalog = self.simgencat.Catalog[self.simgencat.Catalog['GENZ'] != 'GENZ']
self.simgencat.simname = simName
self.simgencat.NSN = int(len(self.simgencat.Catalog['GENZ']))
print "SIMGEN NUMBER"
print self.simgencat.NSN
print "SIMGENCAT FILE"
print simfilename
self.realName = realName
try:
self.realcat = simread.SNANA_Cat(realfilename, realName, simOmegaM=0.3, simOmegaL=0.7, simH0=70.0, simw=-1.0, simOb0=0.049, simSigma8=0.81, simNs=0.95, skip_header = 5)
except:
self.realcat = simread.SNANA_Cat(realfilename, realName, simOmegaM=0.3, simOmegaL=0.7, simH0=70.0, simw=-1.0, simOb0=0.049, simSigma8=0.81, simNs=0.95)
if self.cheatType:
print "WARNING, THE FITTER IS CHEATING AND ELIMINATED NON-IAs USING SIM INFO"
self.realcat.Catalog = self.realcat.Catalog[self.realcat.Catalog['SIM_TYPE_INDEX'].astype(int) == 1]
self.simcat.Catalog = self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'].astype(int) == 1]
for cut in cuts:
self.realcat.Catalog = self.realcat.Catalog[(self.realcat.Catalog[cut[0]].astype(type(cut[1])) > cut[1]) & (self.realcat.Catalog[cut[0]].astype(type(cut[2])) < cut[2])]
self.simcat.Catalog = self.simcat.Catalog[(self.simcat.Catalog[cut[0]].astype(type(cut[1])) > cut[1]) & (self.simcat.Catalog[cut[0]].astype(type(cut[2])) < cut[2])]
def newData(self, realfilename, realName, simIndex = 100):
self.realName = realName
try:
self.simcat = simread.SNANA_Cat(simfilename, simName, simOmegaM=0.3, simOmegaL=0.7, simH0=70.0, simw=-1.0, simOb0=0.049, simSigma8=0.81, simNs=0.95)
except:
self.realcat = simread.SNANA_Cat(realfilename, realName, simOmegaM=0.3, simOmegaL=0.7, simH0=70.0, simw=-1.0, simOb0=0.049, simSigma8=0.81, simNs=0.95, skip_header = 5 )
if self.cheatType:
print "WARNING, THE FITTER IS CHEATING AND ELIMINATED NON-IAs USING SIM INFO"
self.realcat.Catalog = self.realcat.Catalog[self.realcat.Catalog['SIM_TYPE_INDEX'].astype(int) == 1]
if simIndex < self.nprint:
print 'N precuts'
print self.realcat.Catalog['FITPROB'].shape
for cut in cuts:
self.realcat.Catalog = self.realcat.Catalog[(self.realcat.Catalog[cut[0]].astype(type(cut[1])) > cut[1]) & (self.realcat.Catalog[cut[0]].astype(type(cut[2])) < cut[2])]
if simIndex < self.nprint:
print "Minimum Fitprob"
print np.min(self.realcat.Catalog['FITPROB'])
print 'N postcuts'
print self.realcat.Catalog['FITPROB'].shape
def effCalc(self, fracContamCut = 0.0, nbins = 10, simIndex = 100):
#### Do we want SNIas or all SN for efficiency?
self.nbins = nbins
self.typeString = ''
if self.cheatZ:
ztype = 'SIM_ZCMB'
else:
ztype = 'zPHOT'
'''
if (fracContamCut > 0.000000001) & (fracContamCut < 1.0):
print " Cutting based on Frac Contam"
histTot, binsX, binsY = np.histogram2d(self.simcat.Catalog[ztype], self.simcat.Catalog['MURES'], bins = nbins)
histCC, binsX, binsY = np.histogram2d(self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'].astype(int) != 1][ztype], self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'].astype(int) != 1]['MURES'], bins = (binsX, binsY))
fracContam = histCC.astype(np.float)/histTot.astype(np.float)
for fcRow, i in zip(fracContam, xrange(binsX.shape[0])):
for fc, j in zip(fcRow, xrange(binsY.shape[0])):
if fc < fracContamCut:
continue
else:
simInBin = (self.simcat.Catalog[ztype] > binsX[i]) & (self.simcat.Catalog[ztype] < binsX[i+1]) & (self.simcat.Catalog['MURES'] > binsY[j]) & (self.simcat.Catalog['MURES'] < binsY[j+1])
realInBin = (self.realcat.Catalog[ztype] > binsX[i]) & (self.realcat.Catalog[ztype] < binsX[i+1]) & (self.realcat.Catalog['MURES'] > binsY[j]) & (self.realcat.Catalog['MURES'] < binsY[j+1])
self.simcat.Catalog = self.simcat.Catalog[np.invert(simInBin)]
self.realcat.Catalog = self.realcat.Catalog[np.invert(realInBin)]
'''
zPHOTs = self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'].astype(int) == 1][ztype].astype(float)
zTRUEs = self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'].astype(int) == 1]['SIM_ZCMB'].astype(float)
self.typeString = self.typeString + 'A1'
binList = np.linspace(self.zmin, self.zmax, nbins+1)
if simIndex < self.nprint:
print "Type Location A"
print "Choice A1"
print zPHOTs.shape
print zTRUEs.shape
print binList
self.binList = binList
counts, zPhotEdges, zTrueEdges, binnumber = scipy.stats.binned_statistic_2d(zPHOTs, zTRUEs, zTRUEs, statistic = 'count', bins = self.binList)
assert(zPhotEdges.shape[0] == (self.nbins + 1))
if simIndex < self.nprint:
print "Type Location B"
print "Choice B1"
self.typeString = self.typeString + 'B1'
zGenHist, zGenBins = np.histogram(self.simgencat.Catalog[self.simgencat.Catalog['GENTYPE'].astype(int) == 1]['GENZ'].astype(float), bins = self.binList)
zSim1Hist, zSim1Bins = np.histogram(self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'].astype(int) ==1]['SIM_ZCMB'].astype(float), bins = self.binList)
if simIndex < self.nprint:
print "counts of zTrue in each zPhot vs zTrue bin"
print counts.astype(int)
print "zGen Bins"
print zGenBins
print 'zGen Histogram'
print zGenHist
print "sum zGen events"
print np.sum(zGenHist)
print "sum zPhot events"
print np.sum(counts)
#print "DEBUG HERE"
#assert(0)
self.effmat = np.zeros((self.nbins,self.nbins))
xMax = zPhotEdges.shape[0] - 2
yMax = zTrueEdges.shape[0] - 2
if simIndex < self.nprint:
print zGenHist
print counts.astype(int)
for zPhotLedge, zPhotRedge, row, i in zip(zPhotEdges[:-1], zPhotEdges[1:], counts, xrange(xMax + 1)):
zPhotCenter = (zPhotLedge + zPhotRedge)/2.0
for zTrueLedge, zTrueRedge, count, j in zip(zTrueEdges[:-1], zTrueEdges[1:], row, xrange(yMax + 1)):
zTrueCenter = (zTrueLedge + zTrueRedge)/2.0
inCell = (zPHOTs > zPhotLedge) & (zPHOTs < zPhotRedge) & (zTRUEs > zTrueLedge)& (zTRUEs < zTrueRedge)
zPhotCell = zPHOTs[inCell];zTrueCell = zTRUEs[inCell]
self.effmat[i][j] = np.sum(inCell)
assert(np.abs(np.sum(inCell) - count < 2))
for row, i in zip(self.effmat, xrange(self.effmat.shape[0])):
for j in xrange(row.shape[0]):
self.effmat[i][j] /= zGenHist[j]
if simIndex < self.nprint:
print 'effmat'
print self.effmat
if simIndex == 0:
extent = [zPhotEdges[0], zPhotEdges[-1], zTrueEdges[0], zTrueEdges[-1]]
plt.figure()
plt.imshow(np.flipud(counts), extent = extent, cmap = 'Blues')
plt.colorbar()
plt.savefig(self.realName + 'redshiftDistro.png')
plt.clf()
plt.close()
plt.figure()
plt.imshow(np.flipud(self.effmat), extent = extent, cmap = 'Blues', norm=mpl.colors.LogNorm())
plt.colorbar()
plt.savefig(self.realName + 'efficiencyMatrixLog.png')
plt.clf()
plt.close()
plt.figure()
plt.imshow(np.flipud(self.effmat), extent = extent, cmap = 'Blues')
plt.colorbar()
plt.savefig(self.realName + 'efficiencyMatrix.png')
plt.clf()
plt.close()
def fit_rate(self, fixK = False, fixBeta = False, simIndex = 100, trueBeta = 0, CCScale = 1.0, TrueCCScale = 1.0, BetaInit = 0.0, kInit = 1.0, BetaErr = 1, kErr = 1, f_Js = None):
#import iminuit as iM
#from iminuit import Minuit as M
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
if self.cheatZ:
ztype = 'SIM_ZCMB'
else:
ztype = 'zPHOT'
plt.switch_backend('Agg')
if simIndex < self.nprint:
print "Type Location C"
print "Choice C1"
if len(self.typeString) <= 4:
self.typeString = self.typeString + 'C1'
nSim, simBins = np.histogram(self.simgencat.Catalog[self.simgencat.Catalog['GENTYPE'].astype(int) == 1]['GENZ'].astype(float), bins=self.binList)
nSim2, simBins2 = np.histogram(self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'].astype(int) ==1][ztype].astype(float), bins=self.binList)
nSim3, simBins3 = np.histogram(self.simcat.Catalog[ztype].astype(float), bins=self.binList)
NCC , _ = np.histogram(self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'] != 1][ztype].astype(float), bins=self.binList)
OrigNCC = np.copy(NCC)
if self.cheatCCSub:
if self.cheatCCScale:
print "WARNING: Only cheating on CC Subtraction not scale"
print "Setting NCC to infinity to make sure that cheating correctly"
print "Diagnostics after this point may be nonsense"
print "NCC BeforeFck"
print NCC
NCC = NCC*1E100
print "NCC AfterFck"
print NCC
elif self.cheatCCScale:
print "NCC Before1"
print NCC
print TrueCCScale
NCC = applyCCScale(NCC, TrueCCScale)
print "NCC After1"
print NCC
else:
print "NCC Before2"
print NCC
print CCScale
NCC = applyCCScale(NCC, CCScale)
print "NCC After2"
print NCC
#assert(0)
NIa , _ = np.histogram(self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'] == 1][ztype].astype(float), bins=self.binList)
DebugNIaPhot, _ = np.histogram(self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'] == 1]['zPHOT'].astype(float), bins=self.binList)
DebugNCCPhot, _ = np.histogram(self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'] != 1]['zPHOT'].astype(float), bins=self.binList)
DebugNCCPhot = applyCCScale(DebugNCCPhot, CCScale)
DebugNIaTrue, _ = np.histogram(self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'] == 1]['SIM_ZCMB'].astype(float), bins=self.binList)
DebugNCCTrue, _ = np.histogram(self.simcat.Catalog[self.simcat.Catalog['SIM_TYPE_INDEX'] != 1]['SIM_ZCMB'].astype(float), bins=self.binList)
DebugNCCTrue = applyCCScale(DebugNCCTrue, CCScale)
uselessCtr = 0
for niap, nccp, niat, ncct, zb in zip(DebugNIaPhot, DebugNCCPhot, DebugNIaTrue, DebugNCCTrue,(self.binList[1:] + self.binList[:-1])/2.0 ):
uselessCtr +=1
self.globalZTrueBinStorage.append(zb)
self.globalZPhotBinStorage.append(zb)
self.globalNDataIaPhotBinStorage.append(niap)
self.globalNDataCCPhotBinStorage.append(nccp)
self.globalNDataIaTrueBinStorage.append(niat)
self.globalNDataCCTrueBinStorage.append(ncct)
print "UselessCtr"
print uselessCtr
try:
TrueNCC, _ = np.histogram(self.realcat.Catalog[self.realcat.Catalog['SIM_TYPE_INDEX'] !=1][ztype].astype(float), bins=self.binList)
if simIndex < self.nprint:
print "True NCC Data"
print TrueNCC
except:
print "Using real data"
TrueNCC = None
nData, dataBins = np.histogram(self.realcat.Catalog[ztype].astype(float), bins=self.binList)
if not(self.cheatCCSub):
FracBad = NCC*1.0/(1.0*(NCC+NIa))
nCCData = nData*FracBad
else:
nCCData = TrueNCC*1.0
FracBad = TrueNCC*1.0/nData
print "PreScale NCC/nSim"
print OrigNCC*1.0/(OrigNCC+NIa)
print "PreScale Pred NCC Data"
print OrigNCC*1.0/(OrigNCC+NIa)*nData
print "PreScale Pred NCC Data if 2NCC"
print OrigNCC*2.0/(2.0*OrigNCC+NIa)*nData
print "PreScale PredNCCData - TrueNCCData"
print OrigNCC*2.0/(2.0*OrigNCC+NIa)*nData - TrueNCC
print "PreScale PredNCCData - TrueNCCData/ PredNCCData"
print (OrigNCC*2.0/(2.0*OrigNCC+NIa)*nData - TrueNCC)/(OrigNCC*2.0/(2.0*OrigNCC+NIa)*nData)
print "Mean of PreScale PredNCCData - TrueNCCData/ PredNCCData"
print np.mean((OrigNCC*2.0/(2.0*OrigNCC+NIa)*nData - TrueNCC)/(OrigNCC*2.0/(2.0*OrigNCC+NIa)*nData))
print "PostScale NCC/nData"
print NCC*1.0/(NCC+NIa)
if True or simIndex < self.nprint:
print "Fraction of CCs in each bin"
print FracBad
print 'NCC'
print NCC
print 'nSim2'
print nSim2
print "nData, dataBins, realcat shape pre contam correction"
print nData
print dataBins
print np.sum(self.realcat.Catalog[ztype].astype(float) > zmax)
print np.sum(self.realcat.Catalog[ztype].astype(float) < zmin)
print self.realcat.Catalog[ztype].shape
print "Ratio nData/nSim"
print 1.0*nData/(1.0*nSim)
print "Ratio nData/nSim2"
print 1.0*nData/(1.0*nSim2)
print "Ratio nSim/nData"
print 1.0*nSim2/(1.0*nData)
print "Ratio nSim2/nData"
print 1.0*nSim2/(1.0*nData)
print "FracBad"
print FracBad
print 'NCCData'
print nCCData
if simIndex < self.nprint:
print "overall Contam"
print np.sum(NCC)*1.0/(np.sum(nSim3)*1.0)
def chi2func(nData, nSim, effmat, fnorm, zCenters, k = 1.0, Beta = 0.0, zBreak = 1.0, dump = False, complexdump = False, modelError = False, nIA = None, nCC = None, Rate_Model = 'powerlaw', zbins = None, simIndex = 100, BetaPrior = (-3, 3), KPrior = (0.0, 50.0), TrueNCCData = None, f_1 = 1.0, f_2 = 1.0, f_3 = 1.0, f_4 = 1.0, f_5 = 1.0, f_6 = 1.0, f_7 = 1.0, f_8 = 1.0, f_9 = 1.0, f_10 = 1.0):
Chi2Temp = 0.0
if Rate_Model == 'powerlaw':
f_Js = k*(1+zCenters)**Beta
elif Rate_Model == 'discrete':
f_Js = np.array([f_1, f_2, f_3, f_4, f_5, f_6, f_7, f_8, f_9, f_10])
elif Rate_Model == 'brokenpowerlaw':
zCenters = (zbins[1:]+zbins[:-1])/2.0
for zC in zCenters:
if zC < zBreak:
f_Js.append(k*(1+zC)**Beta)
elif not(temp is None):
f_Js.append(temp)
else:
temp = f_Js[-1]
f_Js.append(temp)
else:
assert(0)
chi2Mat = np.zeros((self.nbins))
adjNMC = np.zeros((self.nbins))
if Rate_Model == 'discrete':
kprior = 0
betaprior = 0
else:
kprior = weakPrior(k, KPrior)
betaprior = weakPrior(Beta, BetaPrior)
if dump and (self.nprint < simInd):
print "kprior"
print kprior
print "betaprior"
print betaprior
if (nIA is None) or (nCC is None):
print "No CC Cut"
fracCCData = np.zeros(nData.shape)
elif self.cheatCCSub:
fracCCData = TrueNCC*1.0/nData
else:
if Rate_Model == 'discrete':
print 'f_J adjusted CC Cut'
fracCCData = (nCC*1.0)/((1.0*nCC + nIA*np.array(f_Js)))
print fracCCData
else:
print "Beta Adjusted CC Cut"
#BetaRatio = k*(1+zCenters)**(Beta)#/(1+zCenters)**MCBeta
BetaRatio = (1+zCenters)**(Beta)#/(1+zCenters)**MCBeta
print "BadFracCCData"
print (nCC*1.0)/((1.0*nCC + nIA*BetaRatio))
print "bad NCCData"
print (nCC*1.0)/((1.0*nCC + nIA*BetaRatio))*nData
fracCCData = (nCC*1.0)/((1.0*nCC + nIA*BetaRatio))
if dump and (self.nprint < simInd):
print "fracCCData2"
print fracCCData
print "unscaled fracCCData"
print (1.0*nCC)/(1.0*(nCC+nIA))
if self.cheatCCSub:
print "Cheating CC Sub"
assert(not(TrueNCCData is None))
nCCData = TrueNCCData
else:
print "Normal CC Sub"
nCCData = nData*fracCCData
if dump and (self.nprint < simInd):
print "nCCData2"
print nCCData
if not(TrueNCCData is None):
print "TrueNCCData"
print TrueNCCData
#print f_Js
#Check if I am scaling errors down with increasing MC size. Make MC twice as large as "Data" to test.
if dump: chi2Storage = []
if dump: scaledNSimStor = []
if dump:
print "actually used NCC"
#print nCC
print nCCData
for row, nDataI, nCCDataI, i in zip(effmat, nData, nCCData, xrange(self.nbins)):
if dump and (self.nprint < simInd):
print 'effmat row'
print row
print 'nDataI'
print nDataI
print 'nCCDataI'
print nCCDataI
scaledNSimTemp = 0.0
JSumTempNum = 0.0
JSumTempDen = 0.0
for eff, nSimJ, f_J, j in zip(row, nSim, f_Js, xrange(self.nbins)):
if dump and (i == j) and (self.nprint < simInd):
print 'NGen J'
print nSimJ
print 'JSumTempNum contr'
print nSimJ*f_J*eff*fnorm
print 'JSumTempDen contr'
print nSimJ*f_J*eff*fnorm*f_J*fnorm
if dump and (i != j) and self.cheatZ and (self.nprint < simInd):
if nSimJ*f_J*eff*fnorm > 0:
print " This should be zero but isnt "
print nSimJ*f_J*eff*fnorm
assert(0)
JSumTempNum += nSimJ*f_J*eff*fnorm
JSumTempDen += nSimJ*f_J*eff*fnorm*f_J*fnorm
dataFunc = np.maximum(nDataI ,1)
CCFunc = np.ceil(np.maximum(nCCDataI, 1))
c2t = (nDataI - nCCDataI - JSumTempNum)**2/( dataFunc + CCFunc + JSumTempDen) + kprior + betaprior
if dump and (self.nprint < simInd):
print i
print 'nDataI'
print nDataI
print 'fnCCDataI'
print nCCDataI
print 'fnorm'
print fnorm
print "JSumTempNum tot"
print JSumTempNum
print "JSumTempDen tot"
print JSumTempDen
print "Chi2Bin"
print c2t
if dump:
chi2Storage.append(c2t)
if c2t > 5:
print 'INSANITY CHECK ABOVE'
# Chi2Temp += ((nDataI - nCCDataI - JSumTempNum)**2/(JSumTempNum + JSumTempDen))#*fnorm**2
if nDataI > 1E-11 or JSumTempDen > 1E-11:
Chi2Temp += c2t
if dump:
return Chi2Temp, chi2Storage
else:
return Chi2Temp
zCenters = (simBins[1:] + simBins[:-1])/2.0
#Is this right? Everything else in the other side of the chi2 function should be Ia only
if self.cheatCCSub:
self.fracCCData = TrueNCC*1.0/nData
else:
self.fracCCData = (NCC*1.0)/(1.0*(NCC + NIa))
fnorm = float(np.sum(nData*(1-self.fracCCData)))/float(np.sum(nSim))
if self.Rate_Model == 'powerlaw':
lamChi2 = lambda k, Beta: chi2func(nData, nSim, self.effmat, fnorm, zCenters, k, Beta, nIA = NIa, nCC = NCC, simIndex = simIndex, TrueNCCData = TrueNCC)
lamChi2Dump = lambda k, Beta: chi2func(nData, nSim, self.effmat, fnorm, zCenters, k, Beta, dump = True, nIA = NIa, nCC = NCC, simIndex = simIndex, TrueNCCData = TrueNCC)
MinObj = M(lamChi2, k = kInit, error_k = kErr , Beta = BetaInit, error_Beta = BetaErr, limit_k = (0.0, None), fix_k = fixK, fix_Beta = fixBeta)
c2i, _ = lamChi2Dump(1.0, 0.0)
print "Chi2 init = {0}".format(round(c2i, 4))
elif self.Rate_Model == 'brokenpowerlaw':
lamChi2 = lambda k, Beta: chi2func(nData, nSim, self.effmat, fnorm, zCenters, k, Beta, 1.0, nCCData = NCCData, simIndex = simIndex, TrueNCCData = TrueNCC)
lamChi2Dump = lambda k, Beta: chi2func(nData, nSim, self.effmat, fnorm, zCenters, k, Beta, 1.0, dump = True, nCCData = nCCData, simIndex = simIndex, TrueNCCData = TrueNCC)
MinObj = M(lamChi2, k = kInit, error_k = kErr , Beta = BetaInit, error_Beta = BetaErr, limit_k = (0.0, None), fix_k = fixK, fix_Beta = fixBeta)
c2i, _ = lamChi2Dump(1.0, 0.0)
print "Chi2 init = {0}".format(round(c2i, 4))
elif self.Rate_Model == 'discrete':
lamChi2 = lambda f_1, f_2, f_3, f_4, f_5, f_6, f_7, f_8, f_9, f_10: chi2func(nData, nSim, self.effmat, fnorm, zCenters, 1.0, nIA = NIa, nCC = NCC, simIndex = simIndex, TrueNCCData = TrueNCC, f_1 = f_1, f_2 = f_2,f_3 = f_3, f_4 = f_4,f_5 = f_5, f_6 = f_6,f_7 = f_7, f_8 = f_8,f_9 = f_9, f_10 = f_10 )
lamChi2Dump = lambda f_1, f_2, f_3, f_4, f_5, f_6, f_7, f_8, f_9, f_10: chi2func(nData, nSim, self.effmat, fnorm, zCenters, 1.0, nIA = NIa, nCC = NCC, simIndex = simIndex, TrueNCCData = TrueNCC, f_1 = f_1, f_2 = f_2,f_3 = f_3, f_4 = f_4,f_5 = f_5, f_6 = f_6,f_7 = f_7, f_8 = f_8,f_9 = f_9, f_10 = f_10, dump = True)
c2i, _ = lamChi2Dump(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
print "Chi2 init = {0}".format(round(c2i, 4))
MinObj = M(lamChi2, f_1 = 1.0, error_f_1 = 1.0, limit_f_1 = (0.0, None), f_2 = 1.0, error_f_2 = 1.0, limit_f_2 = (0.0, None), f_3 = 1.0, error_f_3 = 1.0, limit_f_3 = (0.0, None), f_4 = 1.0, error_f_4 = 1.0, limit_f_4 = (0.0, None), f_5 = 1.0, error_f_5 = 1.0, limit_f_5 = (0.0, None), f_6 = 1.0, error_f_6 = 1.0, limit_f_6 = (0.0, None), f_7 = 1.0, error_f_7 = 1.0, limit_f_7 = (0.0, None), f_8 = 1.0, error_f_8 = 1.0, limit_f_8 = (0.0, None), f_9 = 1.0, error_f_9 = 1.0, limit_f_9 = (0.0, None), f_10 = 1.0, error_f_10 = 1.0, limit_f_10 = (0.0, None))
if self.Rate_Model == 'discrete':
c2f, c2stor = lamChi2Dump(MinObj.values['f_1'],MinObj.values['f_2'],MinObj.values['f_3'],MinObj.values['f_4'],MinObj.values['f_5'],MinObj.values['f_6'],MinObj.values['f_7'],MinObj.values['f_8'],MinObj.values['f_9'],MinObj.values['f_10'])
else:
c2f, c2stor = lamChi2Dump(MinObj.values['k'], MinObj.values['Beta'])
#MinObj = M(lamChi2, k = 1.0, fix_k = True, Beta = 0.0, error_Beta = 0.1)
MinObj.set_strategy(2)
fmin, param = MinObj.migrad(nsplit= 10)
plt.scatter(nData, c2stor)
plt.xlabel('nData')
plt.ylabel('chi2 in bin')
plt.savefig(self.realName + 'Chi2VsnData.png')
plt.clf()
print "Shapes of things"
print len(c2stor)
print nData.shape
print dataBins.shape
print self.binList.shape
print DebugNIaPhot.shape
print DebugNCCPhot.shape
print DebugNIaTrue.shape
print DebugNCCTrue.shape
for c2, nd in zip(c2stor, nData):
self.globalChi2Storage.append(c2)
self.globalNDataStorage.append(nd)
if self.Rate_Model == 'discrete':
fJList = [MinObj.values['f_1'],MinObj.values['f_2'],MinObj.values['f_3'],MinObj.values['f_4'],MinObj.values['f_5'],MinObj.values['f_6'],MinObj.values['f_7'],MinObj.values['f_8'],MinObj.values['f_9'],MinObj.values['f_10']]
fJErrList = [MinObj.errors['f_1'],MinObj.errors['f_2'],MinObj.errors['f_3'],MinObj.errors['f_4'],MinObj.errors['f_5'],MinObj.errors['f_6'],MinObj.errors['f_7'],MinObj.errors['f_8'],MinObj.errors['f_9'],MinObj.errors['f_10']]
self.fJList = fJList
self.fJErrList = fJErrList
self.Beta = None
self.k = None
self.kErr = None
self.BetaErr = None
print fJList
print fJErrList
else:
k = MinObj.values['k']
kErr = MinObj.errors['k']
Beta = MinObj.values['Beta']
BetaErr = MinObj.errors['Beta']
self.k = k
self.Beta = Beta
self.kErr = kErr
self.BetaErr = BetaErr
#/(self.nbins - 2)
self.BetaRatio = (1+zCenters)**(Beta)
self.fJList = None
self.fracCCData = (NCC*1.0)/(1.0*(1.0*NCC + NIa*self.BetaRatio))
print "Chi2 final = {0}".format(round(lamChi2Dump(self.k, self.Beta)[0], 4))
self.chi2 = fmin.fval
print "Chi2final? = {0}".format(round(fmin.fval, 4))
#fJs = np.ones(zCenters.shape)
'''
xgrid,ygrid, sigma, rawdata = MinObj.mncontour_grid('k', 'Beta', numpoints=400, sigma_res = 4, nsigma = 2.0)
plt.figure()
plt.clf()
CS = plt.contour(xgrid, ygrid + self.MCBeta, sigma, levels = [0.5, 1.0, 1.5, 2.0])
plt.clabel(CS, fontsize=7, inline=1)
plt.xlabel('k')
plt.ylabel('Beta')
plt.savefig('{0}_{1}_k_beta_contour.png'.format(self.realName, self.simName))
plt.close()
'''
#plt.axhline(y = self.MCBeta, c = 'k', label = 'True Beta')
#plt.axhline(y = Beta + self.MCBeta, c = 'g', label= 'Best Fit Beta')
#plt.axvline(x = k, label = 'Best Fit k')
def chi2V2(self, fJs, fJErrs, zCenters, k, Beta):
fitfJs = k*(1+zCenters)**Beta
Chi2Temp = 0
for fJ, fitfJ, fJErr in zip(fJs, fitfJs, fJErrs):
Chi2Temp += (fJ - fitfJ)**2/(fJ + fJErr)
return Chi2Temp
def weakPrior(value, priorTuple):
if value < priorTuple[1]:
if value > priorTuple[0]:
return 1
else:
return (value - priorTuple[0])**4
else:
return (value - priorTuple[1])**4
def getCCScale(simCat, dataCat, MURESWindow = (-1, 1), zbins = [0.0, 0.3, 0.6, 0.9, 1.2], muresBins = np.linspace(-2, -1, 4), Beta = None, binList = None, fracCCData = None, outfilePrefix = 'Test', Rate_Model = 'powerlaw', f_Js = None):
import iminuit as iM
from iminuit import Minuit as M
CCScales = []
CCScaleErrs = []
if not(f_Js is None):
f_Js = np.array(f_Js)
tempSimCC = simCat[simCat['SIM_TYPE_INDEX'].astype(int) != 1]
tempSimIa = simCat[simCat['SIM_TYPE_INDEX'].astype(int) == 1]
allSimCC = np.copy(tempSimCC)
allSimIa = np.copy(tempSimIa)
allData = np.copy(dataCat)
simHistCC, simBinsCC = np.histogram(tempSimCC['MURES'], bins = muresBins)
simHistIa, simBinsIa = np.histogram(tempSimIa['MURES'], bins = muresBins)
simZHistCC, simZBinsCC = np.histogram(tempSimCC['zPHOT'], bins = binList)
simZHistIa, simZBinsIa = np.histogram(tempSimIa['zPHOT'], bins = binList)
binCent = (simZBinsIa[1:] + simZBinsIa[:-1])/2.0
print "components of simHist"
print simZHistIa
print binCent
print simHistCC
if Rate_Model == 'discrete':
simHist = simZHistIa*np.array(f_Js) + simZHistCC
else:
simHist = (simZHistIa*(1+binCent)**Beta) + simZHistCC
print 'num and denom of fnorm2'
print float(dataCat.shape[0])
print float(np.sum(simHist))
fnorm2 = float(dataCat.shape[0])/float(np.sum(simHist))
print "precut"
print simCat.shape
print dataCat.shape
simCat = simCat[(simCat['MURES'] < MURESWindow[0]) | (simCat['MURES'] > MURESWindow[1]) ]
dataCat = dataCat[(dataCat['MURES'] < MURESWindow[0]) | (dataCat['MURES'] > MURESWindow[1]) ]
print "postcut"
print simCat.shape
print dataCat.shape
print 'post MURES Cut Ndata and Nsim'
print dataCat.shape
print simCat.shape
for zl, zh in zip(zbins[:-1], zbins[1:]):
tempSim = simCat[(simCat['zPHOT'] < zh) & (simCat['zPHOT'] > zl)]
tempData = dataCat[(dataCat['zPHOT'] < zh) & (dataCat['zPHOT'] > zl)]
allSimCCZbin = allSimCC[(allSimCC['zPHOT'] < zh) & (allSimCC['zPHOT'] > zl)]
allSimIaZbin = allSimIa[(allSimIa['zPHOT'] < zh) & (allSimIa['zPHOT'] > zl)]
print "all Sim CC Zbin/IaZbin"
print allSimCCZbin.shape[0]
print allSimIaZbin.shape[0]
allDataZbin = allData[(allData['zPHOT'] < zh) & (allData['zPHOT'] > zl)]
#binchoice = np.abs(binCent - np.mean(tempData['zPHOT']))
#fracCCCent = fracCCData[np.argmin(binchoice)]
if type(muresBins == int):
histD, muresBins = np.histogram(tempData['MURES'], bins = muresBins)
binsD = muresBins
#histDAll, muresBins = np.histogram(allDataZbin['MURES'], bins = binsD)
else:
histD, binsD = np.histogram(tempData['MURES'], bins = muresBins)
#histDAll = np.histogram(allDataZbin['MURES'], bins = muresBins)
histS, binsS = np.histogram(tempSim['MURES'], bins = muresBins)
tempSimCC = tempSim[tempSim['SIM_TYPE_INDEX'] != 1]
tempSimIa = tempSim[tempSim['SIM_TYPE_INDEX'] == 1]
histSCC, binsSCC = np.histogram(tempSimCC['MURES'], bins = muresBins)
if Rate_Model == 'discrete':
histSIa, binsSIa = np.histogram(tempSimIa['MURES'], bins = muresBins)
histSIa = histSIa*f_Js
else:
histSIa, binsSIa = np.histogram(tempSimIa['MURES'], bins = muresBins, weights = (1+tempSimIa['zPHOT'])**Beta)
#histSAllCC, binsSAllCC = np.histogram(allSimCCZbin['MURES'], bins = muresBins)
#histSAllIa, binsSAllIa = np.histogram(allSimIaZbin['MURES'], bins = muresBins)
#histSIa = histSIa*(1+np.mean(tempSim['zPHOT'])**Beta)
print " MURES tail"
print histS
print histSCC
print histSIa
print "MURES bins"
print binsS
print binsSCC
print binsSIa
print "MURES tail scaled by fnorm2"
print histS*fnorm2
print histSCC*fnorm2
print histSIa*fnorm2
print "Data tail"
print histD
print "fnorm2"
print fnorm2
print "data events outliers only and total"
print histD
print allDataZbin.shape[0]
#R = np.array(histD).astype(float)/np.array(histDAll).astype(float)
R = np.array(histD).astype(float)/float(allDataZbin.shape[0])
print "R"
print R
print "Hist CC, outlier and total"
print histSCC
#print histSAllCC
print allSimCCZbin.shape[0]
print "pre Beta Correction allSimIa"
print allSimIaZbin.shape[0]
#print "Beta Correction Factor"
#print (1+np.mean(allSimIaZbin['zPHOT']))**Beta
#print "BetaCorrected allSimIa"
#print allSimIaZbin.shape[0]*(1+np.mean(allSimIaZbin['zPHOT']))**Beta
#betaCorrAllSimIaZbin = allSimIaZbin.shape[0]*(1+np.mean(allSimIaZbin['zPHOT']))**Beta
if Rate_Model == 'discrete':
hist, bins = np.histogram(allSimIaZbin['zPHOT'], bins = 10)
print 'fJ shape'
print f_Js.shape
print f_Js
print hist
print bins
betaCorrAllSimIaZbin =np.sum(hist*f_Js)
else:
betaCorrAllSimIaZbin =np.sum((1+ allSimIaZbin['zPHOT'])**Beta)
#S = float(np.array(R*histSAllIa) - np.array(histSIa))/float(np.array(histSCC) - np.array(R*histSAllCC))
try:
S = float(np.array(R*betaCorrAllSimIaZbin) - np.array(histSIa))/float(np.array(histSCC) - np.array(R*allSimCCZbin.shape[0]))
except:
S = np.nan
print "S"
print S
print "Uncertainty Related Bullshit"
'''
print "Delta R"
dR = np.sqrt(histD + histDAll)
print dR
num1 = np.sqrt(np.sqrt((dR/R)**2 + histSAllIa) + histSIa)
num2 = np.sqrt(np.sqrt((dR/R)**2 + histSAllCC) + histSCC)
den1 = (R*histSAllIa - histSIa)
den2 = (histSCC - R*histSAllCC)
dS = np.sqrt((num1/den1)**2 + (num2/den2)**2)
'''
#ddnCC = np.sqrt(histSCC)*(histSIa - histSAllIa*R)/(histSCC - R*histSAllCC)**2
#ddNCC = np.sqrt(histSAllCC)*R*(histSAllIa*R - histSIa)/(histSCC - R*histSAllCC)**2
#ddnIa = np.sqrt(histSIa)/(histSCC - R*histSAllCC)
#ddNIa = np.sqrt(histSAllIa)*R/(histSCC - R*histSAllCC)
ddnCC = np.sqrt(histSCC)*(histSIa - allSimIaZbin.shape[0]*R)/(histSCC - R*allSimCCZbin.shape[0])**2
ddNCC = np.sqrt(allSimCCZbin.shape[0])*R*(allSimIaZbin.shape[0]*R - histSIa)/(histSCC - R*allSimCCZbin.shape[0])**2
ddnIa = np.sqrt(histSIa)/(histSCC - R*allSimCCZbin.shape[0])
ddNIa = np.sqrt(allSimIaZbin.shape[0])*R/(histSCC - R*allSimCCZbin.shape[0])
#ddR = (histSAllIa*histSCC - histSAllCC * histSIa)/(histSCC - R*histSAllCC)**2
dS = np.sqrt(ddnCC**2 + ddNCC**2 + ddnIa**2 + ddNIa**2)# + ddR**2)
print "ddnCC"
print ddnCC
print "ddNCC"
print ddNCC
print "ddnIa"
print ddnIa
print "ddNIa"
print ddNIa
#print "ddR"
#print ddR
print "Delta S"
print dS
#assert(S > 0)
if S < 0:
S = np.nan
CCScales.append(S)
CCScaleErrs.append(dS[0])
plt.step((simBinsCC[1:] + simBinsCC[:-1])/2.0, simHistCC, c = 'b', where = 'mid', label = 'prescaled Sim CC')
plt.step((simBinsCC[1:] + simBinsCC[:-1])/2.0, CCScales[0]*simHistCC*fnorm2, c = 'g', where = 'post', label = 'postscaledSimCC')
plt.step((muresBins[1:] + muresBins[:-1])/2.0, histD, c = 'r', where = 'mid', label = 'data')
plt.savefig(outfilePrefix + 'ScaledHist.png')
plt.clf()
return CCScales, CCScaleErrs
def applyCCScale(NCC, CCScales, datazbins = None, zbins = None):
NCCScaled = CCScales*NCC
return NCCScaled
if __name__ == '__main__':
from sys import argv
print "argv"
print argv
datadir = argv[1]
simdir = argv[2]
dataname = argv[3]
print "dataname"
simname = argv[4]
print simname
simgenfile = argv[5]
print simgenfile
NNCut = False
cheatType = bool(int(argv[6]))
cheatZ = bool(int(argv[7]))
trueBeta = float(argv[8])
paramFile = argv[9]
cutFiles = argv[10:]
if( ('Combine' in simdir) or ('SALT2' in simdir)) & (('Combine' in datadir) or ('SALT2' in simdir)):
NNCut = True
NNProbCut = 0.95
#if len(argv) > 6:
# NNCut = True
# NNProbCut = 0.9
# NNData = argv[6]
# NNSim = argv[7]
#default params
zmin = 0.1
zmax = 1.2
MJDMin = 0.0
MJDMax = np.inf
bins = "equalSize"
runFit = True
fracContamCuts = [-1]
fixBeta = True
fixK = False
nbins = 10
ScaleMuResCutLow = -1
ScaleMuResCutHigh = 1
muresBins = 1
muresBinsLow = 3
muresBinsHigh = 3
scaleZBins = [0.0, 1.2]
cheatCCSub = False
cheatCCScale = False
#override file
params = open(paramFile, 'r').readlines()
for p in params:
exec(p)
kmean = []
ksigma = []
kErr = []