-
Notifications
You must be signed in to change notification settings - Fork 6
/
mcmc_limit_calculation.nim
5679 lines (5158 loc) · 240 KB
/
mcmc_limit_calculation.nim
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
import std / [os, math, random, strformat, times, stats, osproc, logging, monotimes, sets]
import pkg / [nimhdf5, unchained, seqmath, chroma, cligen, shell]
import nimhdf5 / serialize_tables
import sequtils except repeat
from strutils import repeat, endsWith, strip, parseFloat, removeSuffix, parseBool
import pkg / [sorted_seq]
import ingrid / [tos_helpers, ingrid_types]
import ingrid / private / limit_utils
# the interpolation code
import ingrid / background_interpolation
import numericalnim except linspace, cumSum
import arraymancer except read_csv, cumSum
# get serialization support for DataFrame and Tensor
import datamancer / serialize
# and serialization to binary (also needed for `procpool` `forked`!)
import flatBuffers
import flatBuffers / flatBuffers_tensor
# cligen `procpool` `forked` sugar!
import forked
defUnit(keV⁻¹•cm⁻²)
# for multiprocessing
import cligen / [procpool, mslice, osUt]
# Plot width
let Width* = getEnv("WIDTH", "600").parseFloat
type
ChipCoord = range[0.0 .. 14.0]
Candidate = object
energy: keV
pos: tuple[x, y: ChipCoord]
## TODO: split the different fields based on the method we want to use?
## SamplingKind represents the different types of candidate from background sampling we can do
SamplingKind = enum
skConstBackground, ## uses the constant background over the gold region. Only allows sampling in the gold region.
skInterpBackground ## uses the interpolated background over the whole chip.
UncertaintyKind = enum
ukCertain, # no uncertainties
ukUncertainSig, # uncertainty only on signal (integrated analytically)
ukUncertainBack, # uncertainty only on background (integrated numerically)
ukUncertain # uncertainty on both. Analytical result of ukUncertainSig integrated numerically
PositionUncertaintyKind = enum
puCertain # no uncertainty
puUncertain # use uncertainty on position
## Stores the relevant context variables for the interpolation method
Interpolation = object
kd: KDTree[float] ## we use a KDTree to store the data & compute interpolation on top of
backCache: Table[Candidate, keV⁻¹•cm⁻²] ## cache for the background values of a set of candidates. Used to avoid
## having to recompute the values in a single MC iteration (within limit computation).
## Only the signal values change when changing the coupling constants after all.
radius: float ## radius of background interpolation (σ is usually radius / 3.0)
sigma: float ## σ of the weight for, usually radius / 3.0 as mentioned above
energyRange: keV ## energy range of the background interpolation
nxy: int ## number of points at which to sample the background interpolation in x/y
nE: int ## number of points at which to sample the background interpolation in E
xyOffset: float ## Offset in x/y coordinates (to not sample edges). Is `coords[1] - coords[0] / 2`
eOffset: float ## Offset in E coordinates (to not sample edges). Is `energies[1] - energies[0] / 2`
coords: seq[float] ## the coordinates at which the background interpolation was evaluated to
## compute the the expected counts tensor
energies: seq[float] ## the energy values at which the background interpolation was evaluated
## to compute the expected counts tensor
expCounts: Tensor[float] ## the tensor containing the expected counts at different (x, y, E) pairs
backgroundTime: Hour ## time of background data (same value as in `Context`)
trackingTime: Hour ## time of solar tracking (same value as in `Context`)
# these are always valid for a single `computeLimit` call!
zeroSig: int ## counts the number of times the expected signal was 0
zeroBack: int ## counts the number of times the background was 0
zeroSigBack: int ## counts the number of times the signal & background was zero
## Stores the current state of the systematics. Allows to easier replace the kind &
## value of systematics at RT without having to change the kind of the `Context`.
## Note: for backward compat there are templates to access `ctx.systematics.X`.
Systematics = object
case uncertainty: UncertaintyKind
of ukUncertainSig:
σs_sig: float # Uncertainty on signal in relative terms, percentage
of ukUncertainBack:
σb_back: float # Uncertainty on background in relative terms, percentage
of ukUncertain: ## annoying....
σsb_sig: float
σsb_back: float
else: discard
# uncertainty on the center position of the signal
case uncertaintyPosition: PositionUncertaintyKind
of puUncertain:
σ_p: float # relative uncertainty away from the center of the chip, in units of
# ???
ϑ_x: float
ϑ_y: float
of puCertain: discard # no uncertainty
# helper object about the data we read from an input H5 file
ReadData = object
df: DataFrame
vetoCfg: VetoSettings # veto settings containing efficiencies of FADC, lnL cut, NN cut, ...
flags: set[LogLFlagKind]
totalTime: Hour # total time (background or tracking, depending on file) in Hours
Efficiency = object
totalEff: float # total efficiency multiplier based on signal efficiency of lnL cut, FADC & veto random coinc rate
signalEff: float # the lnL cut signal efficiency used in the inputs
nnSignalEff: float # target signal efficiency of MLP
nnEffectiveEff: float # effective efficiency based on
nnEffectiveEffStd: float
eccLineVetoCut: float # the eccentricity cutoff for the line veto (affects random coinc.)
vetoPercentile: float # if FADC veto used, the percentile used to generate the cuts
septemVetoRandomCoinc: float # random coincidence rate of septem veto
lineVetoRandomCoinc: float # random coincidence rate of line veto
septemLineVetoRandomCoinc: float # random coincidence rate of septem + line veto
Context = ref object ## XXX: make ref object
mcIdx: int # monte carlo index, just for reference
# input file related information
logLFlags: set[LogLFlagKind]
eff: Efficiency
switchAxes: bool # If true will exchange X and Y positions of clusters, to view as detector installed at CAST
# (see sec. `sec:limit:candidates:septemboard_layout_transformations` in thesis)
# time information
totalBackgroundClusters: int # total number of background clusters in non-tracking time
totalBackgroundTime: Hour # total time of background data taking
totalTrackingTime: Hour # total time of solar tracking
# tracking related
trackingDf: DataFrame
# energy information
energyMin, energyMax: keV
# axion signal info
axionModelFile: string # The filename we read for the differential solar axion flux
axionImageFile: string # The filename we read for the axion image (raytracing result)
axionModel: DataFrame
integralBase: float # integral of axion flux using base coupling constants
# detector related
windowRotation: Degree # rotation of the window during data taking
# efficiency
combinedEfficiencyFile: string # file storing detector efficiency including LLNL effective area
# interpolators
axionSpl: InterpolatorType[float]
efficiencySpl: InterpolatorType[float]
raytraceSpl: Interpolator2DType[float]
backgroundSpl: InterpolatorType[float]
# background candidate sampling
backgroundDf: DataFrame # the DataFrame containing all background cluster data
backgroundCDF: seq[float] # CDF of the background
energyForBCDF: seq[float] # energies to draw from for background CDF
case samplingKind: SamplingKind # the type of candidate sampling we do
of skInterpBackground:
interp: Interpolation ## A helper object to store all interpolation fields
else: discard # skConstant doesn't need
# limit related
g_aγ²: float # the ``reference`` g_aγ (squared)
g_ae²: float # the ``reference`` g_ae value (squared)
β²: float # the ``reference`` β value (squared) for the chameleon coupling XXX: not in use yet
coupling: float # the ``current`` coupling constant in use. Can be a value of
# `g_ae²`, `g_aγ⁴`, `g_ae²·g_aγ²`, `β⁴` depending on use case!
# Corresponds to first entry of MCMC chain vector!
m_a: eV = -1.eV # Axion mass for which we compute a limit. Default negative value implies we use
# low mass approximation for converison probability
couplingKind: CouplingKind # decides which coupling to modify
couplingReference: float # the full reference coupling. `g_ae²·g_aγ²` if `ck_g_ae²·g_aγ²`
mcmcCouplingTarget: float # The target value used as reference for the MCMC
# For `g_ae²` searches: `1e-21 * 1e-12^2`
# Should be larger than the typical expected coupling constant. Provides
# the range of interest in which MCMC will effectively sample.
# systematics and noise
systematics: Systematics
noiseFilter: NoiseFilter
# additional fields for computation & input data storage
rombergIntegrationDepth: int ## only for case of logLFullUncertain integration!
filePath: string ## The path to the data files
files: seq[string] ## The data files we read
tracking: seq[string] ## The H5 files containing the real tracking candidates
# the following are old parameters that are not in use anymore (lkSimple, lkScan etc)
#couplingStep: float # a step we take in the couplings during a scan
#logLVals: Tensor[float] # the logL values corresponding to `couplings`
#maxIdx: int # index of the maximum of the logL curve
CouplingKind = enum
ck_g_ae² ## We vary the `g_ae²` and leave `g_aγ²` fully fixed
ck_g_aγ⁴ ## We vary the `g_aγ⁴` and leave `g_ae²` fully fixed (and effectively 'disabled'); for axion-photon searches
ck_g_ae²·g_aγ² ## We vary the *product* of `g_ae²·g_aγ²`, i.e. direct `g⁴` proportional search.
## Note that this is equivalent in terms of the limit!
ck_g_ae·g_aγ ## We vary the *product* of `g_ae·g_aγ`, but in `g²` form. This is *NOT* equivalent and gives the ``WRONG``
## limit. Only for illustration!
ck_β⁴ ## We vary `β`, the chameleon coupling. For chameleon searches.
## For now a noise filter only defines a single set of pixels that are applied to
## all files in `fnames`. In the future we could generalize to specific sets of pixels
## for individual files.
NoiseFilter = object
pixels: seq[(int, int)] # the pixels to filter
fnames: seq[string] # the filenames this filter should be applied to
## The different ways we can compute a limit. `lkMCMC` is considered the best. `lkBayesScan`
## gives the ~same results but in cases with systematics becomes impractically slow.
## The others are somewhat outdated.
LimitKind = enum
lkSimple, ## purely physical region going down to 95% equivalent
lkScan, ## proper scan for maximum using a binary approach
lkLinearScan, ## limit based on linear scan in pre defined range
lkBayesScan, ## limit based on integrating bayes theorem (posterior prob.)
lkMCMC ## limit based on Metropolis-Hastings Markov Chain Monte Carlo
## A wrapper object for easier serialization
LimitOutput = object
ctx: Context ## The context storing most information
nmc: int
limits: seq[float]
candsInSens: seq[int] ## how many candidates in sens region for each toy set (or for observed cands)
limitKind: LimitKind
isObservedLimit: bool ## Whether the file is for expected limits or observed limits
limitNoSignal: float ## Limit without any candidates (expected only)
expectedLimit: float ## expected limit as `g_ae · g_aγ` with `g_aγ = 1e-12 GeV⁻¹` (expected only)
observedLimit: float ## observed limit (observed only)
chainDf: DataFrame ## DF of the observed limit data (observed only)
obsLimitStats: tuple[mean, median, std: float] ## Statistics of observed limits variation due to statistical fluc.
## (based on `nmc` used for observed limits)
nChainsObserved: int ## Number of chains used for observed limit
burnIn: int ## Burn in used
LimitData = object
m_a: eV
bins: int
upper: float # upper cut value (99.9 percentile of prebinned data)
gs: seq[float] # coupling constants
histo: seq[int]
MassScanLimitOutput = object
ctx: Context
burnIn: int
nChains: int # number of chains built for each mass
limitKind: LimitKind
massLow: eV
massHigh: eV
massSteps: int
dfL: DataFrame # DF of the likelihood space, narrow format `[m_a, gs, L]` columns
lData: Table[eV, LimitData]
dfLimit: DataFrame # DF of the computed limits for each mass, columns `[limit, masses]`
LogProc = proc(x: seq[float]): float
Chain = object
links: seq[seq[float]]
acceptanceRate: float
logVals: seq[float]
numChains: int # number of chains part of this combined chain
## A `RawChain` is a chain as produced by the algorithm with no elements removed due to burn in.
RawChain {.borrow: `.`.} = distinct Chain
## Mini helper to avoid `pow` calls and the issues with `^` precedence
template square[T](x: T): T = x * x
proc toH5(h5f: H5File, x: InterpolatorType[float], name = "", path = "/") =
## Serialize the interpolators we use. They all take energies in a fixed range,
## namely `(0.071, 9.999)` (based on the inputs, one of which is only defined
## in this range unfortunately).
let energies = linspace(x.X.min, x.X.max, 10000) # cut to range valid in interpolation
echo "Serializing Interpolator by evaluating ", energies.min, " to ", energies.max, " of name: ", name
let ys = energies.mapIt(x.eval(it))
let dset = h5f.create_dataset(path / name,
energies.len,
float,
filter = H5Filter(kind: fkZLib, zlibLevel: 4),
overwrite = true)
dset[dset.all] = ys
proc toH5(h5f: H5File, interp: Interpolator2DType[float], name = "", path = "/") =
## Serialize the 2D interpolator we use. Interpolator of the raytracing image
## as a 2D grid defined for each pixel (in theory higher, but practically not
## relevant).
var zs = zeros[float]([256, 256])
for x in 0 ..< 256:
for y in 0 ..< 256:
# Note: we don't center to `+ 0.5` in each pixel, because the input data is
# not centered either
zs[x, y] = interp.eval(x.float, y.float)
let dset = h5f.create_dataset(path / name,
(256, 256),
float,
filter = H5Filter(kind: fkZLib, zlibLevel: 4),
overwrite = true)
dset.unsafeWrite(zs.toUnsafeView, zs.size.int)
proc toH5(h5f: H5File, kd: KDTree[float], name = "", path = "/") =
## Serialize the 2D interpolator we use. Interpolator of the raytracing image
## as a 2D grid defined for each pixel (in theory higher, but practically not
## relevant).
let size = kd.data.size.int
let dset = h5f.create_dataset(path / name,
kd.data.shape.toSeq,
float,
filter = H5Filter(kind: fkZLib, zlibLevel: 4),
overwrite = true)
dset.unsafeWrite(kd.data.toUnsafeView, size)
proc pretty(s: Systematics): string =
result = "("
case s.uncertainty
of ukCertain: result.add "sigBack: (σ_s = σ_b = 0)"
of ukUncertainSig: result.add &"sigBack: (σ_s = {s.σs_sig}, σ_b = 0)"
of ukUncertainBack: result.add &"sigBack: (σ_s = 0, σ_b = {s.σb_back})"
of ukUncertain: result.add &"sigBack: (σ_s = {s.σsb_sig}, σ_b = {s.σsb_back})"
result.add ", "
case s.uncertaintyPosition
of puCertain: result.add "(pos: σ_p = 0)"
of puUncertain: result.add &"(pos: σ_p = {s.σ_p})"
result.add ")"
template uncertainty(ctx: Context): UncertaintyKind =
ctx.systematics.uncertainty
template uncertaintyPosition(ctx: Context): PositionUncertaintyKind =
ctx.systematics.uncertaintyPosition
template σs_sig(ctx: Context): float =
doAssert ctx.uncertainty == ukUncertainSig
ctx.systematics.σs_sig
template `σs_sig=`(ctx: Context, val: float) {.used.} =
doAssert ctx.uncertainty == ukUncertainSig
ctx.systematics.σs_sig = val
template σb_back(ctx: Context): float =
doAssert ctx.uncertainty == ukUncertainBack
ctx.systematics.σb_back
template `σs_back=`(ctx: Context, val: float) {.used.} =
doAssert ctx.uncertainty == ukUncertainBack
ctx.systematics.σs_sig = val
template σsb_sig(ctx: Context): float =
doAssert ctx.uncertainty == ukUncertain
ctx.systematics.σsb_sig
template `σsb_sig=`(ctx: Context, val: float) =
doAssert ctx.uncertainty == ukUncertain
ctx.systematics.σsb_sig = val
template σsb_back(ctx: Context): float =
doAssert ctx.uncertainty == ukUncertain
ctx.systematics.σsb_back
template `σsb_back=`(ctx: Context, val: float) =
doAssert ctx.uncertainty == ukUncertain
ctx.systematics.σsb_back = val
template σ_p(ctx: Context): float =
doAssert ctx.uncertaintyPosition == puUncertain
ctx.systematics.σ_p
template ϑ_x(ctx: Context): float =
doAssert ctx.uncertaintyPosition == puUncertain
ctx.systematics.ϑ_x
template `ϑ_x=`(ctx: Context, val: float) =
ctx.systematics.ϑ_x = val
template ϑ_y(ctx: Context): float =
doAssert ctx.uncertaintyPosition == puUncertain
ctx.systematics.ϑ_y
template `ϑ_y=`(ctx: Context, val: float) =
ctx.systematics.ϑ_y = val
## Logging helpers
proc info(logger: Logger, msgs: varargs[string, `$`]) =
logger.log(lvlInfo, msgs)
import macros, std/genasts
proc toHeader(h, sep: string): string =
result = repeat(sep, 15) & " " & h & " " & repeat(sep, 15)
proc infosImpl(log, header, prefix, sep, args: NimNode): NimNode =
result = newStmtList()
if header.kind == nnkStrLit and header.strVal.len > 0 or
header.kind != nnkStrLit:
let h = genAst(log, header, prefix, sep):
log.info(prefix & toHeader(header, sep))
result.add h
for arg in args:
let x = genAst(log, prefix, arg):
log.info prefix & "\t" & arg
result.add x
macro infos(log: Logger, header: string, args: untyped): untyped =
result = infosImpl(log, header, newLit "", newLit "=", args)
proc infoHeader(log: Logger, line: string, prefix = "", sep = "=") =
log.info(prefix & toHeader(line, sep))
macro infosNoHeader(log: Logger, args: untyped): untyped =
result = infosImpl(log, newLit "", newLit "", newLit "=", args)
macro infosP(log: Logger, header, prefix, sep: string, args: untyped): untyped =
result = infosImpl(log, header, prefix, sep, args)
## Clone
proc clone(t: Table[Candidate, keV⁻¹•cm⁻²]): Table[Candidate, keV⁻¹•cm⁻²] =
result = initTable[Candidate, keV⁻¹•cm⁻²]()
for key, val in t:
result[key] = val
proc clone(it: Interpolation): Interpolation =
for field, v1, v2 in fieldPairs(result, it):
when typeof(v1) is KDTree[float] | Table[Candidate, keV⁻¹•cm⁻²] | Tensor[float]:
v1 = v2.clone()
else:
v1 = v2
proc replace(n: NimNode, repl, by: NimNode): NimNode =
## Replace `repl` by `by` in `n`.
if n == repl:
result = by
else:
result = n.copyNimTree()
for i in 0 ..< result.len:
result[i] = result[i].replace(repl, by)
macro cloneNoCase(res, toClone: typed, body: untyped): untyped =
## Ultra simple clone helper to provide access to all fields that are not case
## fields (those would be possible to add, but I don't have the patience atm)
##
## Inject the variables `v1` and `v2` which are replaced by the fields of `res`
## and `toClone` respectively.
##
## Note: this could do all the checks needed on the types that we manually place
## in the body below, but at that point it becomes a specific to this type cloning
## tool.
let typ = toClone.getTypeImpl[0].getTypeImpl
result = newStmtList()
for field in typ[2]:
if field.kind != nnkIdentDefs: continue # skip `case` fields and their children
let fname = ident(field[0].strVal)
let rv = nnkDotExpr.newTree(res, fname)
let cv = nnkDotExpr.newTree(toClone, fname)
let bodyRepl = body.replace(ident"v1", rv).replace(ident"v2", cv)
result.add bodyRepl
proc clone(ctx: Context): Context =
result = Context(samplingKind: ctx.samplingKind)
result.cloneNoCase(ctx):
when typeof(v1) is DataFrame | InterpolatorType[float] | Interpolator2DType[float] | Interpolation:
v1 = v2.clone()
else:
v1 = v2
case ctx.samplingKind
of skInterpBackground:
result.interp = ctx.interp.clone()
else: discard
converter toChipCoords(pos: tuple[x, y: float]): tuple[x, y: ChipCoord] =
result = (x: ChipCoord(pos.x), y: ChipCoord(pos.y))
converter toChipCoords(pos: Option[tuple[x, y: float]]): Option[tuple[x, y: ChipCoord]] =
if pos.isSome:
let p = pos.get
result = some((x: ChipCoord(p.x), y: ChipCoord(p.y)))
proc cdf(x: float, μ = 0.0, σ = 1.0): float = 0.5 * (1.0 + erf((x - μ) / (σ * sqrt(2.0))))
proc calcSigma95(): float =
let res = block:
var x = 0.0
while cdf(x) < 0.95:
x += 0.0001
x
result = res * res / 2.0
proc flatten(dfs: seq[DataFrame]): DataFrame =
## flatten a seq of DFs, which are identical by stacking them
for df in dfs:
result.add df.clone
proc filterNoisyPixels(df: DataFrame, noiseFilter: NoiseFilter): DataFrame =
var pixSet = initHashSet[(int, int)]()
for p in noiseFilter.pixels:
pixSet.incl p
doAssert "centerX" in df and "centerY" in df, "centerX / centerY not found in input df. " & $df.getKeys()
result = df.filter(f{float -> bool: (toIdx(`centerX`), toIdx(`centerY`)) notin pixSet})
proc readFileData(h5f: H5File):
tuple[totalTime: Hour, vetoCfg: VetoSettings, flags: set[LogLFlagKind]] =
let logLGrp = h5f[likelihoodGroupGrpStr]
var totalTime: Hour
if "totalDuration" in logLGrp.attrs:
totalTime = logLGrp.attrs["totalDuration", float].Second.to(Hour)
## XXX: understand why using `fromH5` as a name breaks the code
let ctx = deserializeH5[LikelihoodContext](h5f, "logLCtx", logLGrp.name,
exclude = @["refSetTuple", "refDf", "refDfEnergy"])
result = (totalTime: totalTime, vetoCfg: ctx.vetoCfg, flags: ctx.flags)
proc compareVetoCfg(c1, c2: VetoSettings): bool =
result = true
for field, v1, v2 in fieldPairs(c1, c2):
if field notin ["fadcVetoes", "calibFile", "nnEffectiveEff", "nnEffectiveEffStd"]:
when typeof(v1) is float:
result = result and value.almostEqual(v1, v2)
else:
result = result and v1 == v2
if not result:
echo "Comparison failed in field: ", field, " is ", v1, " and ", v2
return
import measuremancer
proc readFiles(path: string, s: seq[string], noiseFilter: NoiseFilter,
energyMin, energyMax: keV,
switchAxes: bool): ReadData =
var h5fs = newSeq[datatypes.H5File]()
echo path
echo s
for fs in s:
h5fs.add H5open(path / fs, "r")
var df = h5fs.mapIt(
it.readDsets(likelihoodBase(), some((chip: 3, dsets: @["energyFromCharge", "centerX", "centerY"])))
.rename(f{"Energy" <- "energyFromCharge"})
.filterNoisyPixels(noiseFilter)
).flatten
doAssert not df.isNil, "Our input data is nil. This should not happen!"
if switchAxes: # rename x ↦ y and y ↦ x columns
df = df.rename(f{"tmp" <- "centerX"}, # rename to temp name to not collide with y ↦ x
f{"centerX" <- "centerY"},
f{"centerY" <- "tmp"})
echo "[INFO]: Read a total of ", df.len, " input clusters."
## NOTE: the energy cutoff used here does not matter much, because the background interpolation
## is of course energy dependent and only happens in an `EnergyRange` around the desired point.
## The candidates are drawn in a range defined by `EnergyCutoff`. The kd tree just has to be
## able to provide points for the interpolation up to the `EnergyCutoff`. That's why the
## `t.sum()` does not change if we change the energy filter here.
df = df.filter(f{float -> bool: `Energy`.keV <= energyMax and `Energy`.keV >= energyMin})
var
first = true
lastFlags: set[LogLFlagKind]
totalTime: Hour
lastCfg: VetoSettings
nnEff: Measurement[float] # for mean efficiency of NN classifier
for i, h in h5fs:
let (time, vetoCfg, flags) = readFileData(h)
# compute the mean efficiency for NN based on time of each file & its efficiency + σ
let nnEffLoc = time.float * (vetoCfg.nnEffectiveEff ± vetoCfg.nnEffectiveEffStd)
if i == 0:
nnEff = nnEffLoc
else:
nnEff = nnEff + nnEffLoc
if not first and flags != lastFlags:
raise newException(IOError, "Input files do not all match in the vetoes used! Current file " &
h.name & " has vetoes: " & $flags & ", but last file: " & $lastFlags)
if not first and not compareVetoCfg(vetoCfg, lastCfg):
raise newException(IOError, "Input files do not all match in the veto parameters. " &
h.name & " has settings: " & $vetoCfg & ", but last file: " & $lastCfg)
totalTime += time
lastCfg = vetoCfg
echo "Veto settings of input file: ", h.name, " are: ", vetoCfg, " and flags: ", flags
lastFlags = flags
first = false
discard h.close()
nnEff = nnEff / totalTime.float # normalize to total time for real efficiency
doAssert nnEff.value <= 1.0, "Something went wrong, NN efficiency is larger 1: " & $nnEff
lastCfg.nnEffectiveEff = nnEff.value
lastCfg.nnEffectiveEffStd = nnEff.error
result = ReadData(df: df, flags: lastFlags, vetoCfg: lastCfg, totalTime: totalTime)
defUnit(keV⁻¹•cm⁻²•s⁻¹)
defUnit(keV⁻¹•m⁻²•yr⁻¹)
defUnit(cm⁻²)
defUnit(keV⁻¹•cm⁻²)
# The data file `chameleon-spectrum.dat` contains the spectrum in units of
# `keV⁻¹•16mm⁻²•h⁻¹` at β_m = β_m^sun = 6.457e10 or 10^10.81, however
# it *already includes* the conversion probability, using 9T, 9.26m. Hence
# conversion prob below, which we invert.
# See fig. 11.2 in Christoph's thesis
defUnit(keV⁻¹•mm⁻²•h⁻¹)
defUnit(keV⁻¹•cm⁻²•s⁻¹)
func conversionProbabilityChameleon(B: Tesla, L: Meter): float =
const M_pl = sqrt(((hp_bar * c) / G_Newton).toDef(kg²)).toNaturalUnit.to(GeV) / sqrt(8 * π) # reduced Planck mass in natural units
const βγsun = pow(10, 10.81)
let M_γ = M_pl / βγsun
result = (B.toNaturalUnit * L.toNaturalUnit / (2 * M_γ))^2
proc readAxModel(f: string, isChameleon = false): DataFrame =
proc convert(x: float): float =
result = x.keV⁻¹•m⁻²•yr⁻¹.to(keV⁻¹•cm⁻²•s⁻¹).float
proc convertChameleon(x: float): float =
# divide by 16 to get from /16mm² to /1mm². Input f
# idiotic flux has already taken conversion probability into account.
let P = conversionProbabilityChameleon(9.0.T, 9.26.m) # used values by Christop!
result = (x.keV⁻¹•mm⁻²•h⁻¹ / 16.0 / P).to(keV⁻¹•cm⁻²•s⁻¹).float
if not isChameleon: # axion data
result = readCsv(f)
if "type" in result:
result = result.filter(f{`type` == "Total flux"}) # only use the total flux part of the CSV!
if "Energy / eV" in result:
result = result
.mutate(f{"Energy [keV]" ~ c"Energy / eV" / 1000.0})
elif "Energy" in result:
result = result.rename(f{"Energy [keV]" <- "Energy"}) # without name is keV
if "diffFlux" in result:
result = result.mutate(f{"Flux [keV⁻¹•cm⁻²•s⁻¹]" ~ convert(idx("diffFlux"))})
elif "Flux / keV⁻¹ m⁻² yr⁻¹" in result:
result = result.mutate(f{"Flux [keV⁻¹•cm⁻²•s⁻¹]" ~ convert(idx("Flux / keV⁻¹ m⁻² yr⁻¹"))})
if "Energy / eV" in result:
result = result.drop(["Energy / eV"])
if "Flux / keV⁻¹ m⁻² yr⁻¹" in result:
result = result.drop(["Flux / keV⁻¹ m⁻² yr⁻¹"])
else:
# chameleon data
result = readCsv(f, sep = '\t', header = "#")
.mutate(f{"Flux [keV⁻¹•cm⁻²•s⁻¹]" ~ convertChameleon(idx("I[/16mm2/hour/keV]"))},
f{"Energy [keV]" ~ `energy` / 1000.0})
proc detectionEff(ctx: Context, energy: keV): UnitLess {.gcsafe.}
func conversionProbability(ctx: Context, energy: keV = -1.keV, m_a: eV = -1.eV): UnitLess
template toCDF(data: seq[float], isCumSum = false): untyped =
## Computes the CDF of binned data
## XXX: fix me!!
var dataCdf = data
if not isCumSum:
seqmath.cumsum(dataCdf)
let integral = dataCdf[^1]
## XXX: must not subtract baseline!
let baseline = 0.0 # dataCdf[0]
dataCdf.mapIt((it - baseline) / (integral - baseline))
proc unbinnedCdf[T: Tensor[float] | seq[float]](x: T): (Tensor[float], seq[float]) =
## Computes the CDF of unbinned data
var cdf = newSeq[float](x.len)
for i in 0 ..< x.len:
cdf[i] = i.float / x.len.float
result = (x.sorted, cdf)
proc setupBackgroundInterpolation(kd: KDTree[float],
radius, sigma: float,
energyRange: keV,
backgroundTime, trackingTime: Hour,
nxy, nE: int): Interpolation =
## Make sure to set the global variables (*ughhh!!!*)
# set globals of interpolation, to make sure they really *do* have the same values
Radius = radius # 33.3
Sigma = sigma # 11.1
EnergyRange = energyRange # 0.3.keV
doAssert backgroundTime > 0.0.Hour
doAssert trackingTime > 0.0.Hour
## Need an offset to not start on edge, but rather within
## and stop half a step before
let xyOffset = 14.0/(nxy).float / 2.0 ## XXX: fix this for real number ``within`` the chip
## XXX: should this be 10? Or 12? or what?
## Should not matter too much of course, as we lookup background rate *locally* also
## within energy!
let Cutoff = 10.0
let eOffset = Cutoff/(nE).float / 2.0
let dist = (xyOffset * 2.0).mm
let area = dist * dist # area of considered area
echo area
let ΔE = (eOffset * 2.0).keV
echo ΔE
let volume = area * ΔE
echo volume
var t = newTensor[float]([nxy, nxy, nE])
let coords = linspace(0.0 + xyOffset, 14.0 - xyOffset, nxy)
let energies = linspace(0.0 + eOffset, Cutoff - eOffset, nE)
## TODO: fully verify the sum of the tensor here. It seems like the sum is off a bit.
## Also: `correctEdgeCutoff` has a significant effect on the sum (which partially makes sense
## of course!), but the question is do we handle the "result" of having more candidates therefore
## correctly?
## In addition though: it seems to me like changing the energy cutoff of the input data
## (i.e. changing the total number of clusters) does not translate into a change of the
## `t.sum()`. But I think this is precisely due to our normalization here? As it uses
## its own `EnergyCutoff`. However: it should clearly increase the value `val` after
## `normalizeValue`!
for yIdx in 0 ..< nxy:
for xIdx in 0 ..< nxy:
for iE, E in energies:
let y = coords[yIdx]
let x = coords[xIdx]
let tup = kd.query_ball_point([x.toIdx.float, y.toIdx.float, E].toTensor, Radius, metric = CustomMetric)
let val = compValue(tup)
.correctEdgeCutoff(Radius, x.toIdx, y.toIdx)
.normalizeValue(Radius, EnergyRange, backgroundTime)
let valCount = val * volume * trackingTime.to(Second)
#echo val, " as counts: ", valCount, " at ", x, " / ", y, " E = ", E
t[yIdx, xIdx, iE] = valCount
echo "[INFO] Sum of background interpolation tensor: ", t.sum()
result = Interpolation(kd: kd, # kd storing clusters
nxy: nxy, nE: nE, # grid definiton variables for sampling
radius: radius, sigma: sigma, energyRange: energyRange, # parameters for weighing / search range
backgroundTime: backgroundTime,
trackingTime: trackingTime,
coords: coords,
energies: energies,
xyOffset: xyOffset, eOffset: eOffset,
expCounts: t)
proc setupAxionImageInterpolation(axionImage: string): Interpolator2DType[float] =
let hmap = readCsv(axionImage)
# Some files may still use `z`, default now is `photon flux`
let zCol = if "z" in hmap: "z" else: "photon flux"
block Plot:
ggplot(hmap, aes("x", "y", fill = zCol)) +
geom_raster() + ggsave("/tmp/raster_what_old.pdf")
## XXX: Real size is 1.41 cm no? Does it even matter? Real size is 14111μm
## Well technically a larger chip improves the background rate. (but for S/B it shouldn't matter)
const area = 1.4.cm * 1.4.cm
const pixels = 256 * 256
const pixPerArea = pixels / area
var t = zeros[float]([256, 256])
let zSum = hmap[zCol, float].sum
for idx in 0 ..< hmap.len:
let x = hmap["x", int][idx]
let y = hmap["y", int][idx]
#echo "X ", x, " and ", y
let z = hmap[zCol, float][idx]
t[x, y] = (z / zSum * pixPerArea).float #zMax / 784.597 # / zSum # TODO: add telescope efficiency abs. * 0.98
result = newBilinearSpline(t, (0.0, 255.0), (0.0, 255.0)) # bicubic produces negative values!
proc initSystematics(
σ_sig = 0.0, σ_back = 0.0, σ_p = 0.0,
eff: Efficiency = Efficiency(),
uncertainty = none[UncertaintyKind](),
uncertaintyPos = none[PositionUncertaintyKind](),
): Systematics =
## Constructs the correct `Systematics` given the desired values.
## Update the signal uncertainty using the given `Efficiency`, i.e. add
## the impact of the uncertainty on the software efficiency either from
## LnL or MLP
# Note: `eff` must be given as fraction of 1
proc calcNewSig(x: float, ε: float): float = sqrt( x^2 + ε^2 )
let softEff = if eff.nnEffectiveEffStd > 0.0: eff.nnEffectiveEffStd
else: 0.01727 # else use default for LnL
# this value recovers: `σ_sig = 0.04582795952309026`
# previously we used 0.02 to get `σ_sig = 0.04692492913207222`
let σ_sig = if σ_sig > 0.0: calcNewSig(σ_sig, softEff)
else: 0.0
let uncertain = if uncertainty.isSome: uncertainty.get
elif σ_sig == 0.0 and σ_back == 0.0: ukCertain
elif σ_sig == 0.0: ukUncertainBack
elif σ_back == 0.0: ukUncertainSig
else: ukUncertain
let uncertainPos = if uncertaintyPos.isSome: uncertaintyPos.get
elif σ_p == 0.0: puCertain
else: puUncertain
result = Systematics(uncertainty: uncertain,
uncertaintyPosition: uncertainPos)
## Set fields for uncertainties
case uncertain
of ukUncertainSig:
result.σs_sig = σ_sig
of ukUncertainBack:
result.σb_back = σ_back
of ukUncertain:
result.σsb_sig = σ_sig
result.σsb_back = σ_back
else: discard # nothing to do
case uncertainPos
of puUncertain:
result.σ_p = σ_p
else: discard # nothing to do
proc initNoiseFilter(yearFiles: seq[(int, string)]): NoiseFilter =
## Argument contains the year (0) of the data file (1). The years for which
## the filter will apply are hardcoded here for the time being.
## XXX: only apply these to 2017 files & correct sensitive area!
const noisyPixels = [
(2017, [
# "Main" noise cluster in Run-2
(64, 109),
(64, 110),
(67, 112),
(65, 108),
(66, 108),
(67, 108),
(65, 109),
(66, 109),
(67, 109),
(68, 109),
(65, 110),
(66, 110),
(67, 110),
(65, 111),
(66, 111),
(67, 111),
(68, 110),
(68, 109),
(68, 111),
(68, 108),
(66, 107),
(67, 107),
(66, 111),
(69, 110),
# Secondary cluster in Run-2
(75, 197),
(76, 197),
(74, 196),
(75, 196),
(76, 196),
(76, 195),
(77, 196),
# Deich bottom left
(1 , 83),
(2 , 83),
(3 , 83),
(4 , 83),
(5 , 83),
(6 , 83),
# Deich middle left
(1 , 166),
(2 , 166),
(3 , 166),
(4 , 166),
(5 , 166),
# Deich middle right
(251 , 166),
(252 , 166),
(253 , 166),
(254 , 166),
(255 , 166)] ) ]
# [
# (64, 109),
# (64, 110),
# (67, 112),
# (65, 108),
# (66, 108),
# (67, 108),
# (65, 109),
# (66, 109),
# (67, 109),
# (68, 109),
# (65, 110),
# (66, 110),
# (67, 110),
# (65, 111),
# (66, 111),
# (67, 111),
# (68, 110),
# (68, 109),
# (68, 111),
# (68, 108),
# (67, 107),
# (66, 111),
# (69, 110)
# ])
# ]
doAssert noisyPixels.len == 1, "For now only single set of noisy pixels implemented."
for (year, pixels) in noisyPixels:
result = NoiseFilter(pixels: @pixels,
fnames: yearFiles.filterIt(it[0] == year).mapIt(it[1]))
proc calcVetoEfficiency(readData: ReadData,
septemVetoRandomCoinc,
lineVetoRandomCoinc,
septemLineVetoRandomCoinc: float): float =
## Calculates the combined efficiency of the detector given the used vetoes, the
## random coincidence rates of each and the FADC veto percentile used to compute
## the veto cut.
result = 1.0 # starting efficiency
if fkFadc in readData.flags:
doAssert readData.vetoCfg.vetoPercentile > 0.5, "Veto percentile was below 0.5: " &
$readData.vetoCfg.vetoPercentile # 0.5 would imply nothing left & have upper percentile
# input is e.g. `0.99` so: invert, multiply (both sided percentile cut), invert again
result = 1.0 - (1.0 - readData.vetoCfg.vetoPercentile) * 2.0
if {fkSeptem, fkLineVeto} - readData.flags == {}: # both septem & line veto
result *= septemLineVetoRandomCoinc
elif fkSeptem in readData.flags:
result *= septemVetoRandomCoinc
elif fkLineVeto in readData.flags:
result *= lineVetoRandomCoinc
# now multiply by lnL or MLP cut efficiency. LnL efficiency is likely always defined, but NN
# only if NN veto was used
if readData.vetoCfg.nnEffectiveEff > 0.0:
result *= readData.vetoCfg.nnEffectiveEff
elif readData.vetoCfg.signalEfficiency > 0.0:
result *= readData.vetoCfg.signalEfficiency
else:
raise newException(ValueError, "Input has neither a well defined NN signal efficiency nor a regular likelihood " &
"signal efficiency. Stopping.")
proc overwriteRandomCoinc(readData: ReadData,
lineVetoRandomCoinc, septemLineVetoRandomCoinc: float): (float, float) =
## Potentially overwrite the random coincidence values if the input file uses an
## eccenrticity cutoff other than 1.
var
lineVetoRandomCoinc = lineVetoRandomCoinc
septemLineVetoRandomCoinc = septemLineVetoRandomCoinc
if readData.vetoCfg.eccLineVetoCut > 1.0:
## in this case need to overwrite the info from `lineVetoRandomCoinc` and `septemLineVetoRandomCoinc`
## with the values from our resources file
let df = readCsv("/home/basti/org/resources/septem_line_random_coincidences_ecc_cut.csv")
let lvDf = df.filter(f{`Type` == "LinelvRegularFake"},
f{float -> bool: abs(`ε_cut` - readData.vetoCfg.eccLineVetoCut) < 1e-3})
doAssert lvDf.len == 1, "No, was : " & $lvDf
lineVetoRandomCoinc = lvDf["FractionPass", float][0]
let slDf = df.filter(f{`Type` == "SeptemLinelvRegularNoHLCFake"},
f{float -> bool: abs(`ε_cut` - readData.vetoCfg.eccLineVetoCut) < 1e-3})
doAssert slDf.len == 1, "No, was : " & $slDf
septemLineVetoRandomCoinc = slDf["FractionPass", float][0]
echo "Updated line and septem line veto random coincidence numbers : ", lineVetoRandomCoinc, " and ", septemLineVetoRandomCoinc
result = (lineVetoRandomCoinc, septemLineVetoRandomCoinc)
proc initCouplingReference(ctx: Context) =
## Sets the reference coupling values that are used to compute thresholds,
## rescaling parameters and starting values for the MCMC.
case ctx.couplingKind
of ck_g_ae²: ctx.couplingReference = ctx.g_ae²
of ck_g_aγ⁴: ctx.couplingReference = ctx.g_aγ² * ctx.g_aγ²
of ck_g_ae²·g_aγ²: ctx.couplingReference = ctx.g_ae² * ctx.g_aγ²
of ck_g_ae·g_aγ: ctx.couplingReference = ctx.g_ae² * ctx.g_aγ²
of ck_β⁴: ctx.couplingReference = ctx.β² * ctx.β²
proc setMcmcCouplingTarget(couplingKind: CouplingKind, target: float): float =
if classify(target) != fcInf:
result = target
else:
case couplingKind
of ck_g_ae²: result = 1e-21 * 1e-12^2
of ck_g_ae²·g_aγ²: result = 8e-11^2 * 1e-12^2
of ck_g_ae·g_aγ: result = 8e-11^2 * 1e-12^2
of ck_g_aγ⁴: result = 5e-9^2 * 1e-12^2 ## Nature limit 6.6e-11^4. 1e-12 because that's reference for input files
of ck_β⁴: result = 1e10^2 * pow(10, 10.81) * pow(10, 10.81) ## (10^10.81)² due to reference in input files
#else:
# doAssert false, "Not implemented yet, coupling target for " & $couplingKind
proc computeIntegralBase(ctx: Context, m_a: eV = -1.eV): float =
# Note: evaluating `detectionEff` at > 10 keV is fine, just returns 0. Not fully correct, because our
# eff. there would be > 0, but flux is effectively 0 there anyway and irrelevant for limit
var axModel = ctx.axionModel
if m_a > 0.eV:
axModel = axModel
.mutate(f{"Flux" ~ idx("Flux [keV⁻¹•cm⁻²•s⁻¹]") * detectionEff(ctx, idx("Energy [keV]").keV) *
ctx.conversionProbability(idx("Energy [keV]").keV, m_a) })
else:
axModel = axModel
.mutate(f{"Flux" ~ idx("Flux [keV⁻¹•cm⁻²•s⁻¹]") * detectionEff(ctx, idx("Energy [keV]").keV) })
echo "[INFO]: Axion model: ", axModel
result = simpson(axModel["Flux", float].toSeq1D,
axModel["Energy [keV]", float].toSeq1D)
echo "Integral:: ", result
proc initContext(path: string,
yearFiles: seq[(int, string)],
trackingYearFiles: seq[(int, string)],
useConstantBackground: bool, # decides whether to use background interpolation or not
radius, sigma: float, energyRange: keV, nxy, nE: int,
backgroundTime, trackingTime: Hour, ## Can be used to ``*overwrite*`` time from input files!
axionModel: string, # differential solar axion flux
isChameleon: bool, # whether file given for `axionModel` is actually chameleon
axionImage, # axion image (raytracing)
combinedEfficiencyFile: string, # file containing combined detector efficiency including LLNL effective area
windowRotation = 30.°,
σ_sig = 0.0, σ_back = 0.0, # depending on which `σ` is given as > 0, determines uncertainty
σ_p = 0.0,
rombergIntegrationDepth = 5,
septemVetoRandomCoinc = 1.0, # random coincidence rate of the septem veto
lineVetoRandomCoinc = 1.0, # random coincidence rate of the line veto
septemLineVetoRandomCoinc = 1.0, # random coincidence rate of the septem + line veto
energyMin = 0.0.keV,
energyMax = 12.0.keV,
couplingKind = ck_g_ae²,
m_a = -1.eV,
mcmcCouplingTarget = Inf,
switchAxes: bool
): Context =
let samplingKind = if useConstantBackground: skConstBackground else: skInterpBackground
let files = yearFiles.mapIt(it[1])
let tracking = trackingYearFiles.mapIt(it[1])
let noiseFilter = initNoiseFilter(yearFiles)
# read data including vetoes & FADC percentile
let readData = readFiles(path, files, noiseFilter, energyMin, energyMax, switchAxes)
var readDataTracking: ReadData
if tracking.len > 0:
readDataTracking = readFiles(path, tracking, noiseFilter, energyMin, energyMax, switchAxes)
let kdeSpl = block:
let dfLoc = readData.df.toKDE(energyMin, energyMax, true)
newCubicSpline(dfLoc["Energy", float].toSeq1D, dfLoc["KDE", float].toSeq1D)