-
Notifications
You must be signed in to change notification settings - Fork 2
/
core.py
2900 lines (2454 loc) · 105 KB
/
core.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
from collections import deque
from astropy.io import fits
import numpy as np
import pylab as pl
from scipy.integrate import simps,cumtrapz
from scipy.optimize import fmin,fsolve,fmin_tnc,brentq
from scipy.interpolate import interp1d
from scipy.stats import chi2
from . import bary
from . import events
from . import py_exposure_p8
from importlib import reload
reload(py_exposure_p8)
dbug = dict()
# MET bounds for 8-year data set used for FL8Y and 4FGL
t0_8year = 239557007.6
t1_8year = 491999980.6
def met2mjd(times,mjdref=51910+7.428703703703703e-4):
times = np.asarray(times,dtype=np.float128)
return times*(1./86400)+mjdref
def mjd2met(times,mjdref=51910+7.428703703703703e-4):
times = (np.asarray(times,dtype=np.float128)-mjdref)*86400
return times
def infer_met(time):
if time < 100000:
return mjd2met(time)
return time
def calc_weighted_aeff(pcosines,phi,base_spectrum=None,
ltfrac=None,correct_psf=True,
use_psf_types=True,type_selector=None,emin=100,emax=1e5,
verbosity=2):
""" Compute the "effective effective area" for a set of exposure
segments, typically the ~30s intervals tabulated in an FT2 files.
Typically, this will involve averaging the effective area over the
energy range. Additionally, by default, the finite aperture size
will be taken into account by computing the fraction of the PSF
contained at each energy slice.
Parameters
----------
pcosines : the polar angle cosines, vz. cos(theta)
phi : azimuthal angle (radians); if not None, then the azimuthal
dependence of the effective area will be applied
base_spectrum : a function returning dN/dE(E) for the source; if None,
will use an E^-2 weighting
ltfrac : a livetime fraction entry for each interval. If not None,
will apply the efficiency correction to the aeff
correct_psf : scale the effective area by the fraction of the PSF
contained at the energy slice
type_selector : an instance of PSFTypeSelector, e.g., which will
give an energy-dependent event type selection. Those events
which are not selected will be omitted from the effective area
sum.
use_psf_types : event types are PSF types; otherwise, front/back
emin : minimum energy of integration (MeV)
emax : maximum energy of integration (MeV)
"""
emin = np.log10(emin)
emax = np.log10(emax)
ea = py_exposure_p8.EffectiveArea()
if correct_psf:
pc = py_exposure_p8.PSFCorrection()
else:
pc = None
if ltfrac is not None:
ec = py_exposure_p8.EfficiencyCorrection()
else:
ec = None
if use_psf_types:
event_types = [f'PSF{i}' for i in range(4)]
event_codes = range(0,4)
else:
event_types = ['FRONT','BACK']
event_codes = range(0,2)
if base_spectrum is None:
base_spectrum = lambda E: E**-2
# try to pick something like 8/decade
nbin = int(round((emax-emin)*8))+1
edom = np.logspace(emin,emax,nbin)
wts = base_spectrum(edom)
# this is the exposure as a function of energy
total_exposure = np.empty_like(edom)
rvals = np.zeros([len(edom),len(pcosines)])
for i,(en,wt) in enumerate(zip(edom,wts)):
for etype,ecode in zip(event_types,event_codes):
if type_selector is not None:
# check to see if we are using this en/ct
if not type_selector.accept(en,ecode):
if verbosity >= 2:
print(f'Skipping {en:.2f},{ecode}.')
continue
aeff = ea(en,pcosines,etype,phi=phi)
if pc is not None: # PSF correction
aeff *= pc(en,pcosines,etype)
if ec is not None: # efficiency correction
aeff *= ec(en,ltfrac,etype)
rvals[i] += aeff
total_exposure[i] = rvals[i].sum()
rvals[i] *= wt
aeff = simps(rvals,edom,axis=0)/simps(wts,edom)
return aeff,edom,total_exposure
class PSFTypeSelector():
""" Select event types as a function of energy. This is used for
selecting events and for computing the weighted effective area.
We assume there is no maximum energy for a given PSF type.
"""
def __init__(self,min_energies=10**np.asarray([2.75,2.5,2.25,2.00])):
if not len(min_energies)==4:
raise ValueError('Provide a minimum energy for each PSF type.')
self._men = np.asarray(min_energies)
if not np.all((self._men[:-1] > self._men[1:])):
raise Warning('Minimum energies should probably decrease with PSF type.')
def accept(self,en,evtype):
""" Return TRUE where the evtype satisfies the minimum for the
provided energy.
"""
en = np.atleast_1d(en)
evtype = np.atleast_1d(evtype)
ok = np.full(len(en),False,dtype=bool)
for i in range(4):
m = evtype==i
ok[m] = en[m] >= self._men[i]
return np.squeeze(ok)
class FBTypeSelector():
""" Select event types as a function of energy. This is used for
selecting events and for computing the weighted effective area.
It is assumed there is no minimum energy for front-type events, so
the only parameter is the minimum energy for BACK events.
"""
def __init__(self,min_back_energy=10**2.5):
self._mbe = min_back_energy
def accept(self,en,evtype):
""" Return TRUE where the evtype satisfies the minimum for the
provided energy.
"""
return evtype==0 | (evtype==1 & en >= self._mbe)
class Cell(object):
""" Encapsulate the concept of a Cell, specifically a start/stop
time, the exposure, and set of photons contained within."""
def __init__(self,tstart,tstop,exposure,photon_times,photon_weights,
source_to_background_ratio):
self.tstart = tstart
self.tstop = tstop
self.exp = exposure
self.ti = np.atleast_1d(photon_times)
self.we = np.atleast_1d(photon_weights)
self.SonB = source_to_background_ratio
# TMP? Try baking in a set of scales to allow re-scaling of a
# baseline set of weights. Ultimately we need this at the data
# level too...
self._alpha = 1
self._beta = 1
def sanity_check(self):
if self.exp==0:
assert(len(self.ti)==0)
assert(len(self.ti)==len(self.we))
assert(np.all(self.ti >= self.tstart))
assert(np.all(self.ti < self.tstop))
def get_tmid(self):
return 0.5*(self.tstart+self.tstop)
class PhaseCell(Cell):
def __init__(self,tstart,tstop,exposure,photon_times,photon_weights,
source_to_background_ratio):
super(PhaseCell,self).__init__(tstart,tstop,exposure,photon_times,photon_weights,source_to_background_ratio)
def copy(self,phase_offset=0):
return PhaseCell(self.tstart+phase_offset,self.tstop+phase_offset,
self.exp,self.ti,self.we,self.SonB)
def cell_from_cells(cells):
""" Return a single Cell object for multiple cells."""
cells = sorted(cells,key=lambda cell:cell.tstart)
tstart = cells[0].tstart
we = np.concatenate([c.we for c in cells])
ti = np.concatenate([c.ti for c in cells])
exp = np.asarray([c.exp for c in cells]).sum()
bexp = np.asarray([c.exp/c.SonB for c in cells]).sum()
SonB = exp/bexp
return Cell(cells[0].tstart,cells[-1].tstop,exp,ti,we,SonB)
class CellTimeSeries(object):
""" Encapsulate binned data from cells, specifically the exposure,
the cell edges, and the first three moments of the photon weights
(counts, weights, weights^2 in each cell.)
The purpose of this class/time series is a lightweight version of
the cell data for use in uniform sampling algorithms like FFTs.
It's possible that during rebinning, some small-exposure cells will
come to be. A minimum exposure cut here keeps numerical problems at
bay.
"""
def __init__(self,starts,stops,exp,sexp,bexp,
counts,weights,weights2,deadtime,
alt_starts=None,alt_stops=None,timesys='barycenter',
minimum_exposure=3e4):
self.starts = starts
self.stops = stops
self.exp = exp
self.sexp = sexp
self.bexp = bexp
self.counts = counts
self.weights = weights
self.weights2 = weights2
self.deadtime = deadtime
self.alt_starts = alt_starts
self.alt_stops = alt_stops
self.timesys = timesys
## exposure mask
self.minimum_exposure = minimum_exposure
mask = ~(exp > minimum_exposure)
self._zero_weight(mask)
def save(self,fname,compress=True):
keys = ['starts','stops','exp','sexp','bexp','counts','weights',
'weights2','deadtime']
if self.alt_starts is not None:
keys += ['alt_starts']
if self.alt_stops is not None:
keys += ['alt_stops']
d = dict()
for key in keys:
d[key] = getattr(self,key)
d['metadata'] = [str(self.minimum_exposure),self.timesys]
if compress:
np.savez_compressed(fname,**d)
else:
np.savez(fname,**d)
@staticmethod
def load(fname):
q = np.load(fname)
minimum_exposure = float(q['metadata'][0])
timesys = q['metadata'][1]
alt_starts = alt_stops = None
if 'alt_starts' in q.keys():
alt_starts = q['alt_starts']
if 'alt_stops' in q.keys():
alt_stops = q['alt_stops']
keys = ['starts','stops','exp','sexp','bexp','counts','weights',
'weights2','deadtime']
args = [q[key] for key in keys]
kwargs = dict(alt_starts=alt_starts,alt_stops=alt_stops,timesys=timesys,minimum_exposure=minimum_exposure)
q.close()
return CellTimeSeries(*args,**kwargs)
def _zero_weight(self,mask):
self.exp[mask] = 0
self.sexp[mask] = 0
self.bexp[mask] = 0
self.counts[mask] = 0
self.weights[mask] = 0
self.weights2[mask] = 0
def tsamp(self):
# TODO -- perhaps put in a contiguity check
return self.stops[0]-self.starts[0]
def ps_nbin(self):
""" Return the expected number of frequency bins in the likelihood
PSD, with no zero padding.
"""
return len(self.starts)//4 + 1
def tspan(self):
return self.stops[-1]-self.starts[0]
def get_topo_bins(self):
if self.timesys=='barycenter':
if self.alt_starts is None:
raise Exception('Do not have topocentric bins.')
return self.alt_starts,self.alt_stops
else:
return self.starts,self.stops
def get_bary_bins(self):
if self.timesys!='barycenter':
if self.alt_starts is None:
raise Exception('Do not have barycentric bins.')
return self.alt_starts,self.alt_stops
else:
return self.starts,self.stops
def zero_weight(self,tstart,tstop):
""" Zero out data between tstart and tstop.
Parameters
----------
tstart : beginning of zero interval (MET, but will infer from MJD)
ttop : end of zero interval (MET, but will infer from MJD)
"""
tstart = infer_met(tstart)
tstop = infer_met(tstop)
mask = (self.starts >= tstart) & (self.stops <= tstop)
self._zero_weight(mask)
class CellLogLikelihood(object):
def __init__(self,cell,swap=False):
"""
Parameters
----------
cell : a Cell object to form the likelihood for
swap : swap the source and the background
"""
self.cell = cell
self.ti = cell.ti
#self.we = cell.we.astype(np.float64)
a,b,w = cell._alpha,cell._beta,cell.we.astype(np.float64)
self.we = w*a / (w*a + b*(1-w))
self.iwe = 1-self.we
self.S = cell.exp*cell._alpha
self.B = cell.exp/cell.SonB*cell._beta
if swap:
self.we,self.iwe = self.iwe,self.we
self.S,self.B = self.B,self.S
self._tmp1 = np.empty_like(self.we)
self._tmp2 = np.empty_like(self.we)
self._last_beta = 0.
def log_likelihood(self,alpha):
""" Return the (positive) log likelihood for a flux multiplier
alpha. Viz, the flux in this cell is alpha*F_mean, so the
null hypothesis is alpha=1.
"""
# NB the minimum defined alpha is between -1 and 0 according to
# amin = (wmax-1)/wmax
t1,t2 = self._tmp1,self._tmp2
np.multiply(self.we,alpha,out=t1)
np.add(t1,self.iwe,out=t1)
np.log(t1,out=t2)
return np.sum(t2)-(self.S*alpha)
def log_profile_likelihood_approx(self,alpha):
""" Profile over the background level under assumption that the
background variations are small (few percent).
For this formulation, we're using zero-based parameters, i.e
flux = F0*(1+alpha)."""
alpha = alpha-1
t1,t2 = self._tmp1,self._tmp2
np.multiply(self.we,alpha,out=t1)
t1 += 1.
# t1 is now 1+alpha*we
np.divide(self.iwe,t1,out=t2)
#t2 is now 1-w/1+alpha*w
Q = np.sum(t2)
t2 *= t2
R = np.sum(t2)
# for reference
beta_hat = (Q-self.B)/R
t1 += beta_hat*(1-self.we)
np.log(t1,out=t2)
#return np.sum(t2) + 0.5*(Q-B)**2/R -alpha*self.exp
return np.sum(t2) - (1+alpha)*self.S - (1+beta_hat)*self.B
def log_profile_likelihood(self,alpha,beta_guess=1):
""" Profile over the background level with no restriction on
amplitude. Use a prescription similar to finding max on alpha.
For this formulation, we're using zero-based parameters.
"""
beta = self._last_beta = self.get_beta_max(
alpha,guess=beta_guess)-1
alpha = alpha-1
t1,t2 = self._tmp1,self._tmp2
np.multiply(self.we,alpha-beta,out=t1)
np.add(1.+beta,t1,out=t1)
# t1 is now 1+beta+we(alpha-beta)
np.log(t1,out=t1)
return np.sum(t1)-self.S*(1+alpha)-self.B*(1+beta)
def get_likelihood_grid(self,amax=2,bmax=2,res=0.01):
na = int(round(amax/res))+1
nb = int(round(bmax/res))+1
agrid = np.linspace(0,amax,na)-1
bgrid = np.linspace(0,bmax,nb)-1
rvals = np.empty((na,nb))
S,B = self.S,self.B
t1,t2 = self._tmp1,self._tmp2
iw = self.iwe
for ia,alpha in enumerate(agrid):
t2[:] = alpha*self.we+1
for ib,beta in enumerate(bgrid):
np.multiply(beta,iw,out=t1)
np.add(t2,t1,out=t1)
np.log(t1,out=t1)
rvals[ia,ib] = np.sum(t1) -B*(1+beta)
rvals[ia,:] -= S*(1+alpha)
return agrid+1,bgrid+1,rvals
def log_full_likelihood(self,p):
""" Likelihood for both source and background normalizations.
"""
alpha,beta = p
alpha -= 1
beta -= 1
t1,t2 = self._tmp1,self._tmp2
np.multiply(alpha-beta,self.we,out=t1)
np.add(1+beta,t1,out=t1)
np.log(t1,out=t1)
return np.sum(t1) - self.S*(1+alpha) -self.B*(1+beta)
def fmin_tnc_func(self,p):
alpha,beta = p
alpha = p[0] - 1
beta = p[1] -1
if (alpha==-1) and (beta==-1):
# would call log(0)
return np.inf,[np.inf,np.inf]
S,B = self.S,self.B
t1 = np.multiply(self.we,alpha-beta,out=self._tmp1)
t1 += 1+beta
if np.any(t1 <= 0):
print(alpha,beta,self.we[t1 <= 0])
# above equivalent to
# t1[:] = 1+beta*iw+alpha*self.we
t2 = np.log(t1,out=self._tmp2)
logl = np.sum(t2) - S*alpha -B*beta
np.divide(self.we,t1,out=t2)
grad_alpha = np.sum(t2)-S
np.divide(self.iwe,t1,out=t2)
grad_beta = np.sum(t2)-B
return -logl,[-grad_alpha,-grad_beta]
def fmin_fsolve(self,p):
alpha,beta = p
alpha -= 1
beta -= 1
S,B = self.S,self.B
w = self.we
iw = 1-self.we
t1,t2 = self._tmp1,self._tmp2
t1[:] = 1+beta*iw+alpha*w
grad_alpha = np.sum(w/t1)-S
grad_beta = np.sum(iw/t1)-B
print(p,grad_alpha,grad_beta)
return [-grad_alpha,-grad_beta]
def fmin_fsolve_jac(self,p):
pass
def f1(self,alpha):
w = self.we
return np.sum(w/(alpha*w+(1-w)))-self.S
def f1_profile(self,alpha):
w = self.we
a = alpha-1
S,B = self.S,self.B
t1 = self._tmp1
t2 = self._tmp2
t1[:] = (1-w)/(1+a*w)
np.multiply(t1,t1,out=t2)
t3 = w/(1+a*w)
T2 = np.sum(t2)
beta_hat = (np.sum(t1)-B)/T2
t1_prime = np.sum(t3*t1)
t2_prime = np.sum(t3*t2)
beta_hat_prime = (2*beta_hat*t2_prime-t1_prime)/T2
return np.sum((w+beta_hat_prime*(1-w))/(1+a*w+beta_hat*(1-w))) -S -beta_hat_prime*B
def f2(self,alpha):
w = self.we
t = alpha*w+(1-w)
return -np.sum((w/t)**2)
def f3(self,alpha):
w = self.we
t = alpha*w+(1-w)
return np.sum((w/t)**3)
def nr(self,guess=1,niter=6):
""" Newton-Raphson solution to max."""
# can precalculate alpha=0, alpha=1 for guess, but varies depending
# on TS, might as well just stick to 1 and use full iteration
a = guess
w = self.we
iw = 1-self.we
S = self.S
t = np.empty_like(self.we)
for i in range(niter):
t[:] = w/(a*w+iw)
f1 = np.sum(t)-S
t *= t
f2 = -np.sum(t)
a = max(0,a - f1/f2)
return a
def halley(self,guess=1,niter=5):
""" Hally's method solution to max."""
a = guess
w = self.we
iw = 1-self.we
S = self.S
t = np.empty_like(self.we)
t2 = np.empty_like(self.we)
for i in range(niter):
t[:] = w/(a*w+iw)
f1 = np.sum(t)-S
np.multiply(t,t,out=t2)
f2 = -np.sum(t2)
np.multiply(t2,t,out=t)
f3 = 2*np.sum(t)
a = max(0,a - 2*f1*f2/(2*f2*f2-f1*f3))
return a
def get_max(self,guess=1,beta=1,profile_background=False,
recursion_count=0):
""" Find value of alpha that optimizes the log likelihood.
Is now switched to the 0-based parameter convention.
Use an empirically tuned series of root finding.
"""
if profile_background:
rvals,nfeval,rc = fmin_tnc(self.fmin_tnc_func,
[float(guess),float(beta)],
bounds=[[0,None],[0,None]],disp=0,ftol=1e-3,
maxfun=200)
if not((rc < 0) or (rc > 2)):
if (guess == 0) and (rvals[0] > 5e-2):
print('Warning, possible inconsistency. Guess was 0, best fit value %.5g.'%(rvals[0]),'beta=',beta)
return rvals
# just do a second iteration to try see if it converges
guess = rvals[0]
beta = rvals[1]
guess += 1e-3 # just perturb these a bit
beta -= 1e-3
rvals,nfeval,rc = fmin_tnc(self.fmin_tnc_func,
[guess,beta],
bounds=[[0,None],[0,None]],disp=0,ftol=1e-3,
maxfun=200)
if not((rc < 0) or (rc > 2)):
if (guess == 0) and (rvals[0] > 5e-2):
print('Warning, possible inconsistency. Guess was 0, best fit value %.5g.'%(rvals[0]),'beta=',beta)
return rvals
oldguess = guess
oldbeta = beta
oldrvals = rvals
oldlogl = self.fmin_tnc_func(rvals)[0]
if rc == 3: # exceeded maximum evaluations
newguess = oldguess
newbeta = oldbeta
else:
# try a small grid to seed a search
grid = np.asarray([0,0.1,0.3,0.5,1.0,1.5,2.0,5.0,10.0])
cogrid = np.asarray(
[self.log_profile_likelihood(x) for x in grid])
idx_amax = np.argmax(cogrid)
idx_less = max(0,idx_amax-1)
idx_gret = min(idx_amax+1,len(grid)-1)
dlogl = abs(cogrid[idx_gret]-cogrid[idx_less])
if dlogl > 100:
# make a finer grid
grid = np.linspace(grid[idx_less],grid[idx_gret],20)
cogrid = np.asarray(
[self.log_profile_likelihood(x) for x in grid])
# need to cast these otherwise the TNC wrapper barfs on a
# type check...
newguess = float(grid[np.argmax(cogrid)])
newbeta = float(max(0.1,self.get_beta_max(newguess)))
rvals,nfeval,rc = fmin_tnc(self.fmin_tnc_func,
[newguess,newbeta],
bounds=[[0,None],[0,None]],disp=0,ftol=1e-3,
maxfun=200)
newrvals = rvals
newlogl = self.fmin_tnc_func(rvals)[0]
if not((rc < 0) or (rc > 2)):
if newlogl > oldlogl:
if newlogl > (oldlogl+2e-3):
print(f'Warning! Converged but log likelihood decreased; rc={rc}.')
return oldrvals
return newrvals
else:
# alpha = 0, but the log likelihoods agree, so don't emit
# a warning
if (rvals[0] == 0) and np.all((cogrid[1:]-cogrid[:-1]<0)):
pass
else:
print('Warning, never converged locating maximum with profile_background! Results for this interval may be unreliable.')
return newrvals
w = self.we
iw = self.iwe
S,B = self.S,self.B
guess = guess-1
beta = beta-1
# check that the maximum isn't at flux=0 (alpha-1) with derivative
a = -1
t1,t2 = self._tmp1,self._tmp2
t2[:] = 1+beta*iw
t1[:] = w/(t2+a*w)
if (np.sum(t1)-S) < 0:
return 0
else:
a = guess
# on first iteration, don't let it go to 0
t1[:] = w/(t2+a*w)
f1 = np.sum(t1)-S
t1 *= t1
f2 = np.sum(t1) # will include sign below
a = a + f1/f2
if a < 0-1:
a = 0.2-1
# second iteration more relaxed
t1[:] = w/(t2+a*w)
f1 = np.sum(t1)-S
t1 *= t1
f2 = np.sum(t1) # will include sign below
a = a + f1/f2
if a < 0.05-1:
a = 0.05-1
# last NR iteration allow 0
t1[:] = w/(t2+a*w)
f1 = np.sum(t1)-S
t1 *= t1
f2 = np.sum(t1) # will include sign below
alast = a = max(0-1,a + f1/f2)
# now do a last Hally iteration
t1[:] = w/(t2+a*w)
f1 = np.sum(t1)-S
t1 *= t1
f2 = np.sum(t1) # will include sign below
t1 *= w/(t2+a*w)
f3 = 2*np.sum(t1)
a = max(0-1,a + 2*f1*f2/(2*f2*f2-f1*f3))
# a quick check if we are converging slowly to try again or if
# we started very from from the guess (large value)
if (abs(a-alast)>0.05) or (abs(guess-a) > 10):
if recursion_count > 2:
return self.get_max_numerical()
#raise ValueError('Did not converge!')
return self.get_max(guess=a+1,beta=beta+1,
recursion_count=recursion_count+1)
return a+1
def get_max_numerical(self,guess=1,beta=1,profile_background=False,
recursion_count=0):
""" Find value of alpha that optimizes the log likelihood.
Is now switched to the 0-based parameter convention.
Use an empirically tuned series of root finding.
"""
if profile_background:
# TODO -- probably want to replace this with a better iterative
# method, but for now, just use good ol' fsolve!
# test TNC method
rvals,nfeval,rc = fmin_tnc(self.fmin_tnc_func,[guess,beta],
bounds=[[0,None],[0,None]],disp=0,ftol=1e-3)
if (rc < 0) or (rc > 2):
print('Warning, best guess probably wrong.')
return rvals
w = self.we
iw = self.iwe
S,B = self.S,self.B
guess = guess-1
beta = beta-1
# check that the maximum isn't at flux=0 (alpha-1) with derivative
a = -1
t1,t2 = self._tmp1,self._tmp2
t2[:] = 1+beta*iw
t1[:] = w/(t2+a*w)
if (np.sum(t1)-S) < 0:
return 0
else:
a = guess
def f(a):
t1[:] = w/(t2+a*w)
return np.sum(t1)-S
a0 = -1
amax = guess
for i in range(12):
if f(amax) < 0:
break
a0 = amax
amax = 2*amax+1
return brentq(f,a0,amax,xtol=1e-3)+1
def get_beta_max(self,alpha,guess=1,recursion_count=0):
""" Find value of beta that optimizes the likelihood, given alpha.
"""
if np.isnan(alpha):
return 1
if len(self.we)==0:
return 0 # maximum likelihood estimator
if alpha == 0:
return len(self.we)/self.B # MLE
alpha = alpha-1
guess -= 1
S,B = self.S,self.B
w = self.we
iw = self.iwe
t,t2 = self._tmp1,self._tmp2
# check that the maximum isn't at 0 (-1) with derivative
t[:] = iw/w
if np.sum(t) < B*(1+alpha):
return 0
else:
b = guess
# on first iteration, don't let it go to 0
t2[:] = 1+alpha*w
t[:] = iw/(t2+b*iw)
f1 = np.sum(t)-B
t *= t
f2 = np.sum(t) # will include sign below
b = b + f1/f2
b = max(0.2-1,b)
# second iteration more relaxed
t[:] = iw/(t2+b*iw)
f1 = np.sum(t)-B
t *= t
f2 = np.sum(t) # will include sign below
b = b + f1/f2
b = max(0.05-1,b)
# last NR iteration allow 0
# second iteration more relaxed
t[:] = iw/(t2+b*iw)
f1 = np.sum(t)-B
t *= t
f2 = np.sum(t) # will include sign below
b = b + f1/f2
b = max(0.02-1,b)
# replace last NR iteration with a Halley iteration to handle
# values close to 0 better; however, it can result in really
# huge values, so add a limiting step to it
t[:] = iw/(t2+b*iw)
f1 = np.sum(t)-B
t *= t
f2 = np.sum(t) # will include sign below
t *= iw/(t2+b*iw)
f3 = 2*np.sum(t)
newb = max(0-1,b + 2*f1*f2/(2*f2*f2-f1*f3))
if abs(newb-b) > 10:
blast = b = 2*b+1
else:
blast = b = newb
# now do a last Hally iteration
t[:] = iw/(t2+b*iw)
f1 = np.sum(t)-B
t *= t
f2 = np.sum(t) # will include sign below
t *= iw/(t2+b*iw)
f3 = 2*np.sum(t)
b = max(0-1,b + 2*f1*f2/(2*f2*f2-f1*f3))
# a quick check if we are converging slowly to try again or if
# the final value is very large
if (abs(b-blast)>0.05) or (abs(guess-b) > 10) or (b==-1):
if recursion_count > 2:
raise ValueError('Did not converge for alpha=%.5f!'%(
alpha+1))
return self.get_beta_max(alpha+1,guess=b+1,
recursion_count=recursion_count+1)
return b+1
def get_beta_max_numerical(self,alpha,guess=1):
alpha = alpha-1
S,B = self.S,self.B
w = self.we
iw = self.iwe
t,t2 = self._tmp1,self._tmp2
# check that the maximum isn't at 0 (-1) with derivative
t2[:] = 1+alpha*w
t[:] = iw/(t2-iw)
if (np.sum(t)-B) < 0:
return 0
def f(b):
t[:] = iw/(t2+b*iw)
return np.sum(t)-B
b0 = -1
bmax = guess-1
for i in range(8):
if f(bmax) < 0:
break
b0 = bmax
bmax = 2*bmax+1
return brentq(f,b0,bmax,xtol=1e-3)+1
def get_logpdf(self,aopt=None,dlogl=20,npt=100,include_zero=False,
profile_background=False):
""" Evaluate the pdf over an adaptive range that includes the
majority of the support. Try to keep it to about 100 iters.
"""
if profile_background:
return self._get_logpdf_profile(aopt=aopt,dlogl=dlogl,npt=npt,
include_zero=include_zero)
if aopt is None:
aopt = self.get_max()
we = self.we
iw = self.iwe
S,B = self.S,self.B
t = self._tmp1
amin = 0
if aopt == 0:
# find where logl has dropped, upper side
llmax = np.log(iw).sum()
# do a few NR iterations
amax = max(0,-(llmax+dlogl)/(np.sum(we/(1-we))-S))
for i in range(10):
t[:] = amax*we+iw
f0 = np.log(t).sum()-amax*S+dlogl-llmax
f1 = np.sum(we/t)-S
amax = amax - f0/f1
if abs(f0) < 0.1:
break
else:
# find where logl has dropped, upper side
t[:] = aopt*we + iw
llmax = np.sum(np.log(t))-S*aopt
# use Taylor approximation to get initial guess
f2 = np.abs(np.sum((we/t)**2))
amax = aopt + np.sqrt(2*dlogl/f2)
# do a few NR iterations
for i in range(5):
t[:] = amax*we+iw
f0 = np.log(t).sum()-amax*S+dlogl-llmax
f1 = np.sum(we/t)-S
amax = amax - f0/f1
if abs(f0) < 0.1:
break
if (not include_zero) and (aopt > 0):
# ditto, lower side; require aopt > 0 to avoid empty we
t[:] = aopt*we + iw
# use Taylor approximation to get initial guess
f2 = np.abs(np.sum((we/t)**2))
# calculate the minimum value of a which will keep the argument
# of the logarithm below positive, and enforce it, just to
# avoid numerical warnings -- 25 Apr 2024
min_a = np.max(1-1./we) + 1e-6
amin = max(min_a,aopt - np.sqrt(2*dlogl/f2))
# do a few Newton-Raphson iterations
for i in range(5):
t[:] = amin*we+iw
f0 = np.log(t).sum()-amin*S+dlogl-llmax
f1 = np.sum(we/t)-S
amin = max(min_a,amin - f0/f1)
if abs(f0) < 0.1:
break
amin = max(0,amin)
dom = np.linspace(amin,amax,npt)
cod = np.empty_like(dom)
for ia,a in enumerate(dom):
cod[ia] = self.log_likelihood(a)
# do a sanity check here
acodmax = np.argmax(cod)
codmax = cod[acodmax]
if abs(codmax - llmax) > 0.05:
aopt = dom[acodmax]
return self.get_logpdf(aopt=aopt,dlogl=dlogl,npt=npt,
include_zero=include_zero)
cod -= llmax
return dom,cod
def _get_logpdf_profile(self,aopt=None,dlogl=20,npt=100,
include_zero=False):
""" Evaluate the pdf over an adaptive range that includes the
majority of the support. Try to keep it to about 100 iters.
"""
if aopt is None:
aopt,bopt = self.get_max(profile_background=True)
else:
bopt = self.get_beta_max(aopt)
# the algebra gets pretty insane here, so I think it's easier just
# to find the range numerically
amin = 0
llmax = self.log_full_likelihood([aopt,bopt])
f = lambda a:self.log_profile_likelihood(a)-llmax+dlogl
a0 = aopt
amin = 0
amax = max(5,a0)
# make sure upper range contains root
for i in range(4):
if f(amax) > 0:
a0 = amax
amax *= amax
amax = brentq(f,a0,amax)
if aopt > 0:
if f(0) > 0:
amin = 0
else:
amin = brentq(f,0,aopt)
dom = np.linspace(amin,amax,npt)
cod = np.empty_like(dom)
self._last_beta = 0
for ia,a in enumerate(dom):
cod[ia] = self.log_profile_likelihood(a)
#beta_guess=self._last_beta+1)
cod -= llmax
return dom,cod
def get_pdf(self,aopt=None,dlogl=20,npt=100,profile_background=False):
dom,cod = self.get_logpdf(aopt=aopt,dlogl=dlogl,npt=npt,
profile_background=profile_background)
np.exp(cod,out=cod)
return dom,cod*(1./simps(cod,x=dom))
def get_ts(self,aopt=None,profile_background=False):
if self.S == 0:
return 0
if aopt is None:
aopt = self.get_max(profile_background=profile_background)
print(aopt)
if profile_background:
aopt = aopt[0] # discard beta
print(aopt)
if aopt == 0:
return 0
func = self.log_profile_likelihood if profile_background else self.log_likelihood
return 2*(func(aopt)-func(0))
def get_flux(self,conf=[0.05,0.95],profile_background=False):
aopt = self.get_max(profile_background=profile_background)
if profile_background:
aopt = aopt[0]
dom,cod = self.get_pdf(aopt=aopt,