-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflux_fitter.py
639 lines (531 loc) · 25.5 KB
/
flux_fitter.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
from __future__ import print_function
from utils import *
from fluxes import *
from xSec import *
from oscProbs import *
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
class flux_fitter:
def __init__(self, beamMode, FDfromFlavor, FDtoFlavor, NDflavor, oscParam = None, Erebin = 1, OArebin = 1, useHC = True):
"""
flux_fitter object which holds fluxes, settings, and solutions to
DUNE-PRISM style flux matching problems
"""
# initial binning. This is determined by the binning of the flux sim
self.initNEbins = Ebins.size
self.initNOAbins = OAbins.size
self.Ebins = Ebins
self.OAbins = OAbins
self.EbinEdges = EbinEdges
self.OAbinEdges = OAbinEdges
self.EbinWidths = EbinWidths
self.OAbinWidths = OAbinWidths
# if we're using alternative horn currents, establish another set of bins for those
if useHC:
# currents is defined in fluxes.py each value should have an accompanying flux object
self.HCbins = currents
self.maxHC = np.max(currents)
else:
self.HCbins = []
self.maxHC = 293. # 293 kA is the nominal horn current setting
# initial maximum off-axis distance. Determined by flux sim, usually 40m
self.maxOA = np.max(self.OAbins)
# Are we rebinning in energy?
# if so, redefine the energy bins
self.Erebin = Erebin
if type(self.Erebin) == np.ndarray:
self.Ebins = average_by_bin_edge(self.Ebins, Ebins, self.Erebin)
self.EbinEdges = self.Erebin
self.EbinWidths = self.EbinEdges[1:] - self.EbinEdges[:-1]
elif type(self.Erebin) == int:
self.Ebins = average(self.Ebins, self.Erebin)
self.EbinEdges = self.EbinEdges[::self.Erebin]
self.EbinWidths = self.EbinEdges[1:] - self.EbinEdges[:-1]
# likewise with off-axis position
self.OArebin = OArebin
if type(self.OArebin) == np.ndarray:
self.OAbins = average_by_bin_edge(self.OAbins, OAbins, self.OArebin)
self.OAbinEdges = self.OArebin
self.OAbinWidths = self.OAbinEdges[1:] - self.OAbinEdges[:-1]
elif type(self.OArebin) == int:
self.OAbins = average(self.OAbins, self.OArebin)
self.OAbinEdges = self.OAbinEdges[::self.OArebin]
self.OAbinWidths = self.OAbinEdges[1:] - self.OAbinEdges[:-1]
# set flavor information
self.beamMode = beamMode
self.FDfromFlavor = FDfromFlavor
self.FDtoFlavor = FDtoFlavor
self.NDflavor = NDflavor
# if not specified, load the default oscillation profile
if not oscParam:
self.oscParam = oscProb(FDfromFlavor, FDtoFlavor)
else:
self.oscParam = oscParam
self.Posc = self.oscParam.load(self.Ebins)
self.ND_OA_loaded = False
self.ND_HC_loaded = False
# load cross sections
self.load_xSec()
# load nominal fluxes
self.load_nom()
# set default bounds for the fit
self.Ebounds = (0, np.max(self.Ebins))
self.OutOfRegionFactors = (0, 0)
# Don't load systematics by default
self.ppfx_systs_loaded = False
self.ND_OA_ppfx_systs_loaded = False
self.ND_HC_ppfx_systs_loaded = False
self.other_systs_loaded = False
self.ND_OA_other_systs_loaded = False
self.ND_HC_other_systs_loaded = False
def load_xSec(self):
"""
Load cross sections for the set flavors
"""
self.NDxSec = xSec[self.NDflavor]["CCInc"].load(binEdges = [self.EbinEdges])
self.FDxSec = xSec[self.FDtoFlavor]["CCInc"].load(binEdges = [self.EbinEdges])
def load_FD_nom(self):
"""
Load the nominal far detector flux and update the FD_oscillated and target
"""
flux = FD_nominal[self.beamMode][self.FDfromFlavor]
self.FD_unoscillated = flux.load(binEdges = [self.EbinEdges])
self.FD_oscillated = self.FD_unoscillated*self.Posc
self.target = self.FD_oscillated
self.FD_rate = FDscale*self.FD_oscillated*self.FDxSec#/self.EbinWidths
self.FD_rate_statErr = np.sqrt(self.FD_rate)
def load_ND_OA_nom(self):
"""
Load the nominal near detector flux for off-axis positions at 293 kA
"""
flux = ND_nominal[self.beamMode][self.NDflavor]
self.ND_OA = flux.load(binEdges = [self.EbinEdges, self.OAbinEdges])
print (NDOAruntimeSplit.shape, OAbinEdges.shape, self.OAbinEdges.shape)
self.OAruntimeSplit = rebin_by_bin_edge(NDOAruntimeSplit, OAbins, self.OAbinEdges)
# self.ND_OA_rate = NDscale*self.OAruntimeSplit*(self.ND_OA.T*self.NDxSec/self.EbinWidths).T
self.ND_OA_rate = NDscale*self.OAruntimeSplit*(self.ND_OA.T*self.NDxSec).T
self.ND_OA_rate_statErr = np.sqrt(self.ND_OA_rate)
self.ND_OA_loaded = True
if self.ND_HC_loaded:
self.runtimeSplit = np.concatenate((self.OAruntimeSplit, self.HCruntimeSplit))
self.ND = np.concatenate((self.ND_OA, self.ND_HC), axis = 1)
self.ND_rate = np.concatenate((self.ND_OA_rate, self.ND_HC_rate), axis = 1)
self.ND_rate_statErr = np.concatenate((self.ND_OA_rate_statErr, self.ND_HC_rate_statErr), axis = 1)
def load_ND_HC_nom(self):
"""
Load the nominal near detector flux for all alternative horn currents
"""
if list(self.HCbins):
self.ND_HC = 12*np.array([ND_HC_shifts[self.beamMode][self.NDflavor][current].load(binEdges = [self.EbinEdges])
for current in self.HCbins]).T
self.HCruntimeSplit = NDHCruntimeSplit
else:
self.ND_HC = np.ndarray((len(self.Ebins), 0))
self.HCruntimeSplit = np.array([])
# self.ND_HC_rate = NDscale*self.HCruntimeSplit*(self.ND_HC.T*self.NDxSec/self.EbinWidths).T
self.ND_HC_rate = NDscale*self.HCruntimeSplit*(self.ND_HC.T*self.NDxSec).T
self.ND_HC_rate_statErr = np.sqrt(self.ND_HC_rate)
self.ND_HC_loaded = True
if self.ND_OA_loaded:
self.runtimeSplit = np.concatenate((self.OAruntimeSplit, self.HCruntimeSplit))
self.ND = np.concatenate((self.ND_OA, self.ND_HC), axis = 1)
self.ND_rate = np.concatenate((self.ND_OA_rate, self.ND_HC_rate), axis = 1)
self.ND_rate_statErr = np.concatenate((self.ND_OA_rate_statErr, self.ND_HC_rate_statErr), axis = 1)
def load_nom(self):
"""
Load all nominal fluxes
"""
self.load_FD_nom()
self.ND_OA_loaded = False
self.ND_HC_loaded = False
self.load_ND_OA_nom()
self.load_ND_HC_nom()
def load_FD_ppfx_systs(self):
"""
Load the hadron production throws for the far detector flux
"""
nUniv = self.nPpfxUniv
flux = FD_ppfx_CV[self.beamMode][self.FDfromFlavor]
FD_CV = flux.load(binEdges = [self.EbinEdges])
FD = np.array([shift.load(binEdges = [self.EbinEdges]) for shift
in FD_ppfx_shifts[self.beamMode][self.FDfromFlavor][:nUniv]])
FD /= FD_CV
FD *= self.FD_unoscillated
self.FD_unosc_ppfx_univs = FD
def load_ND_OA_ppfx_systs(self):
"""
Load the hadron production throws for the near detector flux for off-axis positions
"""
nUniv = self.nPpfxUniv
ND_OA_CV = ND_ppfx_CV[self.beamMode][self.FDfromFlavor].load(binEdges = [self.EbinEdges, self.OAbinEdges])
ND_OA = np.array([shift.load(binEdges = [self.EbinEdges, self.OAbinEdges]) for shift
in ND_ppfx_shifts[self.beamMode][self.NDflavor][:nUniv]])
ND_OA /= ND_OA_CV
ND_OA *= self.ND_OA
self.ND_OA_ppfx_shifts_loaded = True
self.ND_OA_ppfx_univs = ND_OA
if self.ND_HC_ppfx_shifts_loaded:
self.ND_ppfx_univs = np.concatenate((self.ND_OA_ppfx_univs,
self.ND_HC_ppfx_univs),
axis = 2)
def load_ND_HC_ppfx_systs(self):
"""
Load the hadron production throws for the near detector flux for alternative horn currents
"""
nUniv = self.nPpfxUniv
ND_HC_CV = np.array([ND_HC_ppfx_CV[self.beamMode][self.FDfromFlavor][current].load(binEdges = [self.EbinEdges])
for current in self.HCbins]).T
if np.any(self.HCbins):
ND_HC = np.array([np.array([ND_HC_ppfx_shifts[self.beamMode][self.NDflavor][current][univ].load(binEdges = [self.EbinEdges])
for univ in range(nUniv)]).T
for current in self.HCbins]).T
else:
ND_HC = np.ndarray((nUniv, self.initNEbins, len(self.HCbins)))
ND_HC /= ND_HC_CV
ND_HC *= self.ND_HC
self.ND_HC_ppfx_shifts_loaded = True
self.ND_HC_ppfx_univs = ND_HC
if self.ND_OA_ppfx_shifts_loaded:
self.ND_ppfx_univs = np.concatenate((self.ND_OA_ppfx_univs,
self.ND_HC_ppfx_univs),
axis = 2)
def load_ppfx_systs(self, nUniv = 100):
"""
Load all hadron production throws
"""
self.nPpfxUniv = nUniv
self.load_FD_ppfx_systs()
self.ND_OA_ppfx_shifts_loaded = False
self.ND_HC_ppfx_shifts_loaded = False
self.load_ND_OA_ppfx_systs()
self.load_ND_HC_ppfx_systs()
self.ppfx_systs_loaded = True
def load_FD_other_systs(self):
"""
Load systematic throw fluxes for specific beam parameters for far detector
"""
FD = {key: shift.load(binEdges = [self.EbinEdges])
for key, shift in FD_other_shifts[self.beamMode][self.FDfromFlavor].items()}
self.FD_unosc_other_univs = FD
def load_ND_OA_other_systs(self):
"""
Load systematic throw fluxes for specific beam parameters for near detector off-axis positions
"""
ND_OA = {key: shift.load(binEdges = [self.EbinEdges])
for key, shift in ND_other_shifts[self.beamMode][self.NDflavor].items()}
self.ND_OA_other_univs = ND_OA
self.ND_OA_other_shifts_loaded = True
if self.ND_HC_other_shifts_loaded:
self.ND_other_univs = {key: np.concatenate((self.ND_OA_other_univs[key],
self.ND_HC_other_univs[key]),
axis = 1)
for key in systKeys}
def load_ND_HC_other_systs(self):
"""
Load systematic throw fluxes for specific beam parameters for near detector alternative horn currents
"""
# Don't have HC beam systs yet, so fake them by assuming
# the same fractional error as seen in 293 kA
if np.any(self.HCbins):
ND_HC = {}
for key in HCsystKeys:
currentList = []
for current in self.HCbins:
flux = ND_HC_other_shifts[self.beamMode][self.NDflavor][current][key]
currentList.append(12*flux.load(binEdges=[self.EbinEdges]))
arr = np.array(currentList).T
ND_HC.update({key: arr})
else:
ND_HC = {key: np.ndarray((self.Ebins.size, len(self.HCbins)))
for key in HCsystKeys}
self.ND_HC_other_univs = ND_HC
self.ND_HC_other_shifts_loaded = True
if self.ND_OA_other_shifts_loaded:
self.ND_other_univs = {key: np.concatenate((self.ND_OA_other_univs[key],
self.ND_HC_other_univs[HCkey]),
axis = 1)
for key, HCkey in zip(systKeys, HCsystKeys)}
def load_other_systs(self):
"""
Load all systematic throw fluxes for specific beam parameters
"""
self.load_FD_other_systs()
self.ND_OA_other_shifts_loaded = False
self.ND_HC_other_shifts_loaded = False
self.load_ND_OA_other_systs()
self.load_ND_HC_other_systs()
self.other_systs_loaded = True
def set_fit_region(self, energies = None, peaks = None):
"""
Specify the energy region in which to fit the ND and target fluxes. The region can be specified by the keyword argument 'energies', or 'peaks', which are counted from high to low energy. The arguments should be specified as an iterable of length 2
"""
if energies:
if not len(energies) == 2:
print("Energy bounds must be an iterable of length 2!")
return
self.Ebounds = energies
elif peaks:
# WARNING: this is very touchy and tuned specifically for FD numu -> numu fluxes
if not len(peaks) == 2:
print("Peak indices must be an iterable of length 2!")
return
else:
# this should be an odd integer
# otherwise I have to think harder about how to do this...
window_size = 7
fringe_size = window_size/2
smoothed = np.convolve(self.target,
(1/float(window_size))*np.ones(window_size))[:-window_size+1]
threshold = 0.05*np.max(smoothed)
foundPeaks = self.Ebins[(np.diff(smoothed, n = 1, prepend = 0) > 0) &
(np.diff(smoothed, n = 1, append = 0) < 0) &
(smoothed > threshold)]
# peaks should be specified from the right,
# i.e (1, 3) fits between the first and third-highest energy peaks
if peaks[0] == 0:
self.Ebounds = (foundPeaks[-peaks[1]], max(self.Ebins))
else:
self.Ebounds = (foundPeaks[-peaks[1]], foundPeaks[-peaks[0]])
print("found peaks at ", self.Ebounds)
def set_rebin(self, Erebin = None, OArebin = None):
"""
Set the rebin variables and redefine axes and reload fluxes
"""
if Erebin:
self.Erebin = Erebin
if type(self.Erebin) == np.ndarray:
self.Ebins = average_by_bin_edge(self.Ebins, Ebins, self.Erebin)
self.EbinEdges = self.Erebin
elif type(self.Erebin) == int:
self.Ebins = average(self.Ebins, self.Erebin)
self.EbinEdges = self.EbinEdges[::self.Erebin]
if OArebin:
self.OArebin = OArebin
if type(self.OArebin) == np.ndarray:
self.OAbins = average_by_bin_edge(self.OAbins, OAbins, self.OArebin)
self.OAbinEdges = self.OArebin
elif type(self.OArebin) == int:
self.OAbins = average(self.OAbins, self.OArebin)
self.OAbinEdges = self.OAbinEdges[::self.OArebin]
self.Posc = self.oscParam.load(self.Ebins)
# load cross sections
self.load_xSec()
# load nominal fluxes
self.load_nom()
def set_OOR(self, weights):
"""
Specify the relative weight of the regions outside of the "fit region" when contributing to the residual. The weights should be specified as an iterable of length 2
"""
self.OutOfRegionFactors = weights
def set_oscHypothesis(self, Posc):
"""
"""
self.Posc = Posc.load(self.Ebins)
self.FD_oscillated = self.FD_unoscillated*self.Posc
self.target = self.FD_oscillated
def set_maxOA(self, maxOA):
self.maxOA = maxOA
self.OAbins = self.OAbins[self.OAbins <= maxOA]
self.OAbinEdges = self.OAbinEdges[:len(self.OAbins)+1]
self.load_ND_OA_nom()
if self.ppfx_systs_loaded:
self.load_ND_OA_ppfx_systs()
if self.other_systs_loaded:
self.load_ND_OA_other_systs()
def set_maxHC(self, maxHC):
self.maxHC = maxHC
self.HCbins = self.HCbins[self.HCbins <= maxHC]
self.load_ND_HC_nom()
if self.ppfx_systs_loaded:
self.load_ND_HC_ppfx_systs()
if self.other_systs_loaded:
self.load_ND_HC_other_systs()
def use_currents(self, theseCurrents):
self.maxHC = max(list(theseCurrents) + [293])
self.HCbins = np.array(theseCurrents)
self.load_ND_HC_nom()
if self.ppfx_systs_loaded:
self.load_ND_HC_ppfx_systs()
if self.other_systs_loaded:
self.load_ND_HC_other_systs()
def calc_coeffs(self, OAreg, HCreg, A = [None], ND = [None], target = [None], fluxTimesE = False, NDtoFD = NDtoFD, **kwargs):
if not np.any(ND):
ND = self.ND
if not np.any(target):
target = self.target
if fluxTimesE:
ND = ND*self.Ebins.reshape(ND.shape[0], 1)
target = target*self.Ebins
# penalty matrix for coefficients
nBinsOA = np.sum(self.OAbins <= self.maxOA)
nBinsHC = self.ND_HC.shape[1]
# OA penalty term is a difference matrix
# OA_penalty = np.diag(nBinsOA*[1]) - np.diag((nBinsOA - 1)*[1], k = 1)
# # OA penalty term is the L1 norm
OA_penalty = np.eye(nBinsOA)
HC_penalty = np.eye(nBinsHC)
if not np.any(A):
self.A = block_diag(OA_penalty, HC_penalty)
else:
self.A = A
# Gamma = block_diag(OAreg*OA_penalty, HCreg*HC_penalty)
Gamma = OAreg*self.A
self.Gamma = Gamma
# weighting matrix for target flux
P = np.diag(np.where(self.Ebins > self.Ebounds[1],
self.OutOfRegionFactors[1],
np.where(self.Ebins < self.Ebounds[0],
self.OutOfRegionFactors[0],
1)))
self.P = P
# ND matrix
NDmatr = np.matrix(ND)
if OAreg == 0 and HCreg == 0:
LHS = NDmatr.T
RHS = target
else:
LHS = np.matmul(NDmatr.T, np.matmul(P, NDmatr)) + np.matmul(Gamma.T, Gamma)
RHS = np.dot(np.matmul(NDmatr.T, P), target)
self.c = np.array(np.dot(RHS, LHS.I)).squeeze()
self.cOA = self.c[:nBinsOA]
self.cHC = self.c[nBinsOA:]
self.fluxPred = np.dot(self.ND, self.c)
self.ratePred = NDtoFD*np.dot(self.ND_rate, self.c/self.runtimeSplit)
self.ratePred_statErr = NDtoFD*np.sqrt(np.dot(self.ND_rate, np.power((self.c/self.runtimeSplit), 2)))
def calc_coeffs_DFT(self, OAreg, HCreg, filt, ND = [None], target = [None], fluxTimesE = False):
if not np.any(ND):
ND = self.ND
if not np.any(target):
target = self.target
if fluxTimesE:
ND = ND*self.Ebins.reshape(ND.shape[0], 1)
target = target*self.Ebins
# if not np.any(filt):
# filt = np.ones_like(self.OAbins <= self.maxOA, dtype = float)
# penalty matrix for coefficients
nBinsOA = np.sum(self.OAbins <= self.maxOA)
nBinsHC = self.ND_HC.shape[1]
# # OA penalty term is a difference matrix
# OA_penalty = np.diag(nBinsOA*[1]) - np.diag((nBinsOA - 1)*[1], k = 1)
# # OA penalty term is the L1 norm
# OA_penalty = np.eye(nBinsOA)
# OA penalty is a frequency filter based on the DFT
from scipy.linalg import dft
# OA_penalty = np.diag(filt)*dft(nBinsOA) + OAreg*(np.diag(nBinsOA*[1]) - np.diag((nBinsOA - 1)*[1], k = 1))
OA_penalty = np.diag(filt)*dft(nBinsOA) + OAreg*(np.diag(nBinsOA*[1]) - np.diag((nBinsOA - 1)*[1], k = 1))
HC_penalty = np.eye(nBinsHC)
self.A = block_diag(OA_penalty, HC_penalty)
# Gamma = block_diag(OAreg*OA_penalty, HCreg*HC_penalty)
Gamma = block_diag(OA_penalty, HCreg*HC_penalty)
self.Gamma = Gamma
# weighting matrix for target flux
P = np.diag(np.where(self.Ebins > self.Ebounds[1],
self.OutOfRegionFactors[1],
np.where(self.Ebins < self.Ebounds[0],
self.OutOfRegionFactors[0],
1)))
self.P = P
# ND matrix
NDmatr = np.matrix(ND)
LHS = np.matmul(NDmatr.T, np.matmul(P, NDmatr)) + np.matmul(Gamma.T.conj(), Gamma)
RHS = np.dot(np.matmul(NDmatr.T, P), target)
self.c = np.array(np.dot(RHS, LHS.I)).squeeze()
self.c = np.linalg.solve(LHS, RHS)
self.cOA = self.c[:nBinsOA]
self.cHC = self.c[nBinsOA:]
self.fluxPred = np.dot(self.ND, self.c)
self.ratePred = np.dot(self.ND_rate, self.c)
self.ratePred_statErr = np.sqrt(np.dot(self.ND_rate, np.power(self.c, 2)))
def calc_var_coeff_correction(self, reg, fluxTimesE = False):
"""
Calculate a correction to the nominal coefficients to minimize the variance of the residual
over different systematic universes
"""
ND = np.concatenate((self.ND,) + tuple(ND for ND in self.ND_ppfx_univs))
target = np.concatenate((self.target,) + tuple(FD*self.Posc for FD in self.FD_unosc_ppfx_univs))
target -= np.dot(ND, self.c)
# if fluxTimesE:
# ND = ND*self.Ebins.reshape(ND.shape[0], 1)
# target = target*self.Ebins
# penalty matrix for coefficients
nBinsOA = np.sum(self.OAbins <= self.maxOA)
nBinsHC = self.ND_HC.shape[1]
# # OA penalty term is a difference matrix
# OA_penalty = np.diag(nBinsOA*[1]) - np.diag((nBinsOA - 1)*[1], k = 1)
# OA penalty term is the L1 norm
OA_penalty = np.eye(nBinsOA)
HC_penalty = np.eye(nBinsHC)
OAreg = reg
HCreg = reg
Gamma = block_diag(OAreg*OA_penalty, HCreg*HC_penalty)
# weighting matrix for target flux
P = np.diag(np.where(self.Ebins > self.Ebounds[1],
self.OutOfRegionFactors[1],
np.where(self.Ebins < self.Ebounds[0],
self.OutOfRegionFactors[0],
1)))
P = block_diag(*(101*(P,)))
# ND matrix
NDmatr = np.matrix(ND)
LHS = np.matmul(NDmatr.T, np.matmul(P, NDmatr)) + np.matmul(Gamma.T, Gamma)
RHS = np.dot(np.matmul(NDmatr.T, P), target)
deltac = np.array(np.dot(RHS, LHS.I)).squeeze()
# self.c = np.linalg.solve(LHS, RHS)
self.c += deltac
self.cOA = self.c[:nBinsOA]
self.cHC = self.c[nBinsOA:]
self.fluxPred = np.dot(self.ND, self.c)
self.ratePred = np.dot(self.ND_rate, self.c)
self.ratePred_statErr = np.sqrt(np.dot(self.ND_rate, np.power(self.c, 2)))
def compressed_sensing(self, diag = [None], reg = 1.e-9, ND = None, target = None):
if not ND:
ND = self.ND
if not target:
target = self.target
# penalty matrix for coefficients
nBinsOA = np.sum(self.OAbins <= self.maxOA)
# A = np.diag(nBinsOA*[1]) - np.diag((nBinsOA - 1)*[1], k = 1)
if any(diag):
Gamma = np.diag(diag)
else:
A = np.eye(nBinsOA)
Gamma = reg*A
# weighting matrix for target flux
P = np.diag(np.where(self.Ebins > self.Ebounds[1],
self.OutOfRegionFactors[1],
np.where(Ebins < self.Ebounds[0],
self.OutOfRegionFactors[0],
1)))
# ND matrix
NDmatr = np.matrix(ND)
LHS = np.matmul(NDmatr.T, np.matmul(P, NDmatr)) + np.matmul(Gamma.T, Gamma)
RHS = np.dot(np.matmul(NDmatr.T, P), target)
self.c = np.array(np.dot(RHS, LHS.I)).squeeze()
self.fluxPred = np.dot(self.ND, self.c)
self.ratePred = np.dot(self.ND_rate, self.c)
self.ratePred_statErr = np.sqrt(np.dot(self.ND_rate, np.power(self.c, 2)))
def residual_norm(self, P = None, ND = None, target = None, **kwargs):
if not np.any(P):
P = self.P
if not np.any(ND):
ND = self.ND
if not np.any(target):
target = self.target
# return np.sqrt(np.sum(np.power(np.matmul(P, self.fluxPred - target), 2)))
return np.sqrt(np.sum(np.power(np.matmul(P, self.ratePred - self.FD_rate), 2)))
def solution_norm(self, A = None, **kwargs):
if not np.any(A): # user specified an alternative penalty matrix
A = self.A
# NOTE: solution norm uses the UNWEIGHTED penalty matrix
return np.sqrt(np.sum(np.power(np.dot(A, self.c), 2)))
def variance_norm(self):
if self.ppfx_systs_loaded:
return np.sqrt(np.sum(np.sum(np.power(np.matmul(self.P,
np.dot(self.ND_ppfx_univs,
self.c) - self.target),
2))))
def statvar_norm(self):
return np.sqrt(np.sum(np.power(np.matmul(self.P, self.ratePred_statErr), 2)))
def set_coeffs(self, other):
self.coeffs = other.coeff