hep-olll 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: hep-olll
3
+ Version: 0.1.0
4
+ Summary: Neural network adapter for LHC likelihood interpretation
5
+ Home-page: https://github.com/OpenML-LHClikelihoods/
6
+ Author: OLLL collaboration
7
+ Author-email:
8
+ License: GPLv3
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Topic :: Scientific/Engineering :: Physics
11
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: onnx>=1.10.0
15
+ Requires-Dist: onnxruntime>=1.20.0
16
+ Requires-Dist: numpy>=2.0.0
17
+ Requires-Dist: pyyaml
18
+ Dynamic: author
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: license
24
+ Dynamic: requires-dist
25
+ Dynamic: requires-python
26
+ Dynamic: summary
27
+
28
+ # Open library of learned likelihoods from LHC experiments
29
+
30
+ The release of full statistical models from LHC analyses is a major milestone in the
31
+ LHC’s legacy. They encapsulate the full information of an analysis, including the likeli-
32
+ hood given data. Thus, full releases enable collider phenomenology to be performed at full
33
+ statistical precision. However, this comes with a significant enlargement of computational
34
+ costs. For most reinterpretation processes, we are interested in the profiled likelihood,
35
+ which is slow to extract from the statistical model, particularly for analyses with mul-
36
+ tiple signal regions. To mitigate this, we present OLLL, an Open Library of Learned
37
+ Likelihoods from LHC experiments. OLLL is composed of profiled likelihood functions
38
+ modelled with Neural Networks (NNs). We show, through five examples of increasing
39
+ complexity, that such functions can be well described with simple NNs, published in the
40
+ ONNX format, and easily used by different reinterpretation tools without compromising
41
+ statistical precision.
42
+
43
+ ## Example usage (taken from ATLAS-SUSY-2018-04):
44
+
45
+ ```python
46
+ from nnAdapter import NNAdapter
47
+ onnxFile = "atlas-susy-2018-04.onnx"
48
+
49
+ adapter = NNAdapter ( onnxFile, session_options = {} )
50
+
51
+ bkg_yields = adapter.onnxMeta["bkg_yields"]
52
+ ret = adapter.predict ( bkg_yields, yields_are_signal_yields = False )
53
+ print ( "predicting for total yields:" )
54
+ print ( "\n".join( f"{key:10s}: {value:.1f}" for key,value in ret.items()) )
55
+
56
+ sig_yields = { k: 0. for k in bkg_yields }
57
+ ret = adapter.predict ( sig_yields, yields_are_signal_yields = True )
58
+
59
+ print ( )
60
+ print ( f"predicting for signal yields:" )
61
+ print ( "\n".join( f"{key:10s}: {value:.1f}" for key,value in ret.items()) )
62
+ print ( )
63
+ ```
64
+
65
+ This produces as output:
66
+
67
+ ```
68
+ predicting for total yields:
69
+ nll_exp_0 : 99.0
70
+ nll_exp_1 : 99.0
71
+ nll_obs_0 : 99.6
72
+ nll_obs_1 : 99.6
73
+ nllA_exp_0: 99.0
74
+ nllA_exp_1: 99.0
75
+ nllA_obs_0: 99.1
76
+ nllA_obs_1: 99.1
77
+ nll_obs_max: 99.3
78
+ sigma_exp : 0.0
79
+ sigma_obs : 0.0
80
+ sigma_expA: 0.0
81
+ sigma_obsA: 0.0
82
+
83
+ predicting for signal yields:
84
+ nll_exp_0 : 99.0
85
+ nll_exp_1 : 99.0
86
+ nll_obs_0 : 99.6
87
+ nll_obs_1 : 99.6
88
+ nllA_exp_0: 99.0
89
+ nllA_exp_1: 99.0
90
+ nllA_obs_0: 99.1
91
+ nllA_obs_1: 99.1
92
+ nll_obs_max: 99.3
93
+ sigma_exp : 0.0
94
+ sigma_obs : 0.0
95
+ sigma_expA: 0.0
96
+ sigma_obsA: 0.0
97
+ ```
98
+
99
+ The NNAdapter can also be installed via
100
+
101
+ ```
102
+ pip install hep_olll
103
+ ```
@@ -0,0 +1,76 @@
1
+ # Open library of learned likelihoods from LHC experiments
2
+
3
+ The release of full statistical models from LHC analyses is a major milestone in the
4
+ LHC’s legacy. They encapsulate the full information of an analysis, including the likeli-
5
+ hood given data. Thus, full releases enable collider phenomenology to be performed at full
6
+ statistical precision. However, this comes with a significant enlargement of computational
7
+ costs. For most reinterpretation processes, we are interested in the profiled likelihood,
8
+ which is slow to extract from the statistical model, particularly for analyses with mul-
9
+ tiple signal regions. To mitigate this, we present OLLL, an Open Library of Learned
10
+ Likelihoods from LHC experiments. OLLL is composed of profiled likelihood functions
11
+ modelled with Neural Networks (NNs). We show, through five examples of increasing
12
+ complexity, that such functions can be well described with simple NNs, published in the
13
+ ONNX format, and easily used by different reinterpretation tools without compromising
14
+ statistical precision.
15
+
16
+ ## Example usage (taken from ATLAS-SUSY-2018-04):
17
+
18
+ ```python
19
+ from nnAdapter import NNAdapter
20
+ onnxFile = "atlas-susy-2018-04.onnx"
21
+
22
+ adapter = NNAdapter ( onnxFile, session_options = {} )
23
+
24
+ bkg_yields = adapter.onnxMeta["bkg_yields"]
25
+ ret = adapter.predict ( bkg_yields, yields_are_signal_yields = False )
26
+ print ( "predicting for total yields:" )
27
+ print ( "\n".join( f"{key:10s}: {value:.1f}" for key,value in ret.items()) )
28
+
29
+ sig_yields = { k: 0. for k in bkg_yields }
30
+ ret = adapter.predict ( sig_yields, yields_are_signal_yields = True )
31
+
32
+ print ( )
33
+ print ( f"predicting for signal yields:" )
34
+ print ( "\n".join( f"{key:10s}: {value:.1f}" for key,value in ret.items()) )
35
+ print ( )
36
+ ```
37
+
38
+ This produces as output:
39
+
40
+ ```
41
+ predicting for total yields:
42
+ nll_exp_0 : 99.0
43
+ nll_exp_1 : 99.0
44
+ nll_obs_0 : 99.6
45
+ nll_obs_1 : 99.6
46
+ nllA_exp_0: 99.0
47
+ nllA_exp_1: 99.0
48
+ nllA_obs_0: 99.1
49
+ nllA_obs_1: 99.1
50
+ nll_obs_max: 99.3
51
+ sigma_exp : 0.0
52
+ sigma_obs : 0.0
53
+ sigma_expA: 0.0
54
+ sigma_obsA: 0.0
55
+
56
+ predicting for signal yields:
57
+ nll_exp_0 : 99.0
58
+ nll_exp_1 : 99.0
59
+ nll_obs_0 : 99.6
60
+ nll_obs_1 : 99.6
61
+ nllA_exp_0: 99.0
62
+ nllA_exp_1: 99.0
63
+ nllA_obs_0: 99.1
64
+ nllA_obs_1: 99.1
65
+ nll_obs_max: 99.3
66
+ sigma_exp : 0.0
67
+ sigma_obs : 0.0
68
+ sigma_expA: 0.0
69
+ sigma_obsA: 0.0
70
+ ```
71
+
72
+ The NNAdapter can also be installed via
73
+
74
+ ```
75
+ pip install hep_olll
76
+ ```
@@ -0,0 +1,80 @@
1
+ """
2
+ .. module:: metadataValidator
3
+ :synopsis: A simple facility to check if the meta data of the onnx
4
+ file is looking correctly
5
+
6
+ .. moduleauthor:: OLLL Collaboration
7
+
8
+ """
9
+
10
+ __all__ = [ "validateMetaData" ]
11
+
12
+ import json
13
+ from jsonschema import validate, ValidationError
14
+
15
+ def metadata_to_dict(metadata_props : "metadata" ) -> dict:
16
+ """ convert onnx meta data to a dictionary """
17
+ return {entry.key: entry.value for entry in metadata_props}
18
+
19
+ # Define a JSON Schema for the metadata
20
+ METADATA_SCHEMA = {
21
+ "type": "object",
22
+ "required": ["preprocessing", "channels", "obs_yields", "bkg_yields",
23
+ "run_config" ],
24
+ "properties": {
25
+ "preprocessing": {
26
+ "type": "object", # after JSON parsing
27
+ "required": ["features_pipeline"],
28
+ "properties": {
29
+ "features_pipeline": {"type": "array", "items": {"type": "string"}}
30
+ }
31
+ },
32
+ "channels": {
33
+ "oneOf": [
34
+ {
35
+ "type": "array",
36
+ "items": {"type": "object"}
37
+ },
38
+ {
39
+ "type": "object"
40
+ }
41
+ ]
42
+ },
43
+ "obs_yields": {
44
+ "type": "array",
45
+ "items": {"type": "array"}
46
+ },
47
+ "bkg_yields": {
48
+ "type": "array",
49
+ "items": {"type": "array"}
50
+ },
51
+ "run_config": {
52
+ "type": "string",
53
+ },
54
+ }
55
+ }
56
+
57
+ def validateMetaData(metadata_props : "onnx metadata" ) -> dict:
58
+ """ validate the onnx metadata, check that all ingredients are there
59
+
60
+ :raises ValueError: If something goes wrong
61
+ :returns: python dictionary with content
62
+ """
63
+ # Convert to dict
64
+ raw = metadata_to_dict(metadata_props)
65
+
66
+ # Parse JSON string values into Python objects
67
+ parsed = {}
68
+ for key, value in raw.items():
69
+ try:
70
+ parsed[key] = json.loads(value)
71
+ except (json.JSONDecodeError, TypeError):
72
+ parsed[key] = value # keep as string if not JSON
73
+
74
+ # Validate against schema
75
+ try:
76
+ validate(instance=parsed, schema=METADATA_SCHEMA)
77
+ except ValidationError as e:
78
+ raise ValueError(f"Metadata validation failed: {str(e.message)[:200]} in {e.path}") from e
79
+
80
+ return parsed
@@ -0,0 +1,374 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ .. module:: nnAdapter
5
+ :synopsis: An Adapter class that wraps around the neural networks
6
+ published in arXiv:XXXX, handling all the pre- and post-processing.
7
+
8
+ .. moduleauthor:: OLLL Collaboration
9
+
10
+ """
11
+
12
+ __all__ = [ "NNAdapter" ]
13
+
14
+ import os
15
+ import onnx
16
+ import json
17
+ import math
18
+ import onnxruntime
19
+ import sys
20
+ import numpy as np
21
+ from typing import Union
22
+
23
+ class NNAdapter:
24
+ """
25
+ Adapter that wraps around a neural network
26
+ """
27
+ __slots__ = [ "mlModel", "modelType", "onnxMeta", "srOrder", "regressor",
28
+ "session_options", "onnxfilename", "crRegions" ]
29
+
30
+ def __init__( self, mlModel : Union[bytes,str,onnx.ModelProto,os.PathLike],
31
+ onnxfilename : None|str = None, session_options : dict = {},
32
+ validate_metadata : bool = True ):
33
+ """
34
+ :param mlModel: the model, as a ModelProto, as a bytes stream,
35
+ or as a path to an onnx file (needing to end with .onnx)
36
+ :param onnxfilename: filename of onnxfile, for debugging only
37
+ if None, then assume it is the same as mlModel
38
+ :param session_options: options for the onnxruntime inference session,
39
+ e.g. { "inter_op_num_threads": 1 }
40
+ :param validate_metadata: if true, then validate metadata in onnx file,
41
+ before usage
42
+ """
43
+ if onnxfilename == None:
44
+ onnxfilename = str(mlModel)
45
+ assert type(mlModel) in [ bytes, str, onnx.ModelProto,os.PathLike],\
46
+ "mlModel needs to be one of: bytes, str, onnx.ModelProto, PathType"
47
+ if type(mlModel) == str and mlModel.endswith ( "onnx") and \
48
+ os.path.exists ( mlModel ):
49
+ self.mlModel = onnx.load ( mlModel )
50
+ elif type(mlModel) in [ bytes, str ]:
51
+ try:
52
+ self.mlModel = onnx.load_model_from_string ( mlModel )
53
+ except Exception:
54
+ print( f"[nnAdapter] could not load model {onnxfilename}" )
55
+ sys.exit(-1)
56
+ self.onnxfilename = onnxfilename
57
+ self.session_options = session_options
58
+ if validate_metadata:
59
+ from hep_olll.metadataValidator import validateMetaData
60
+ validateMetaData ( self.mlModel.metadata_props )
61
+ self._parseMetaData ()
62
+ self._getSROrder()
63
+ self._cleanCRs()
64
+ self._instantiateRegressor()
65
+
66
+ def predict ( self, yields : Union[dict,list],
67
+ yields_are_signal_yields : bool = True,
68
+ obs_as_bg : list|None|str = [] ) -> dict:
69
+ """ proposal for a slightly different API
70
+
71
+ :param yields: e.g. { "SR1": 3, "SR2": 5 }, or [3,5]
72
+ (in which case the order must match the one in the json)
73
+
74
+ :param yields_are_signal_yields: if True, then yields are
75
+ interpreted as signal yields, and the backgrounds get added.
76
+ if False, yields are assumed to be total yields
77
+
78
+ :param obs_as_bg: a list of signal regions for which we use
79
+ observations as background_yields ("postfit"), given
80
+ yields_are_signal_yields is True. If None or "default", then
81
+ use self.onnxMeta["crRegions"] as defined in the onnx file
82
+
83
+ :returns: the negative log likelihoods (nlls) as a dictionary:
84
+ { 'nll_exp_0': ..., 'nll_exp_1': ..., 'nll_obs_0': ...,
85
+ 'nll_obs_1': ..., 'nllA_exp_0': ..., 'nllA_exp_1': ...,
86
+ 'nllA_obs_0': ..., 'nllA_obs_1': ... }
87
+ where 0, 1 means mu=0, 1, respectively. exp refers to a priori
88
+ expectation, obs are the observed values. nllA means the
89
+ nll is evaluated for the Asimov dataset with mu' = 0.
90
+ """
91
+ if obs_as_bg in [ None, "default", "postfit" ]:
92
+ obs_as_bg = self.onnxMeta["crRegions"]
93
+ if yields_are_signal_yields:
94
+ yields = self._totalYieldsFromSignals ( yields, obs_as_bg )
95
+ scaled_yields = self._preprocess ( yields )
96
+ out = self._predictFromScaledYields ( scaled_yields )
97
+ ret = self._postprocess ( out )
98
+ return ret
99
+
100
+ def _getCRs( self, channels : list|dict ) -> list:
101
+ """ get a list of every signal region marked as a control region
102
+ """
103
+ crRegions = []
104
+ def appendDict ( ch, crRegions ):
105
+ for regionName, regionType in ch.items():
106
+ if regionType == "CR":
107
+ crRegions.append ( regionName )
108
+
109
+ if type(channels)==list:
110
+ for ch in channels:
111
+ appendDict ( ch, crRegions )
112
+ else:
113
+ appendDict ( channels, crRegions )
114
+ return crRegions
115
+
116
+ def _cleanCRs ( self ):
117
+ """ the meta information has all regions of all models,
118
+ so we clean the list of control regions here,
119
+ possibly also adding the "-o" postfix to regio names
120
+ """
121
+ newCRs = []
122
+ for r in self.onnxMeta["crRegions"]:
123
+ if r in self.srOrder:
124
+ newCRs.append ( r )
125
+ if r+"-0" in self.srOrder:
126
+ newCRs.append ( f"{r}-0" )
127
+ self.onnxMeta["crRegions"] = newCRs
128
+
129
+ def _instantiateRegressor ( self ):
130
+ """ create the actual inference session object """
131
+ so = onnxruntime.SessionOptions()
132
+ for k,v in self.session_options.items():
133
+ setattr ( so, k, v )
134
+ sess = onnxruntime.InferenceSession ( self.mlModel.SerializeToString(),
135
+ so )
136
+ self.regressor={ "session": sess,
137
+ "dim": sess.get_inputs()[0].shape[1] }
138
+
139
+ def _fillValues ( self, container : str, values : str ) -> list:
140
+ """ given <values> fill in <container>, if values are sensible
141
+ :param container: the container to fill, e.g. nLL_obs_max
142
+ :param values: the container values to copy from, e.g. [2,0]
143
+ :returns: the values, but cast to proper type
144
+ """
145
+ tmp = json.loads(values)
146
+ if type(tmp) in [ list, tuple ] and len(tmp)==2:
147
+ if math.isfinite(tmp[1]):
148
+ container = tmp
149
+ if container[0]==None:
150
+ container[0]=tmp[0]
151
+
152
+ return container
153
+
154
+ def _getSROrder ( self ):
155
+ """ get the order of the signal regions as specified in the
156
+ onnx meta information. We rely on bkg_yields in the meta information
157
+ to define the canonical order.
158
+ """
159
+ self.srOrder = []
160
+ for srname in self.onnxMeta["bkg_yields"]:
161
+ self.srOrder.append ( srname )
162
+
163
+ def _removeSignalRegions ( self, channels : list, dictionary : dict ) -> dict:
164
+ """ remove a list of signal regions called "channels"
165
+ from the dictionary of values.
166
+ :returns: pruned dictionary
167
+ """
168
+ newDict = {}
169
+ for SRname,value in dictionary.items():
170
+ if SRname in channels:
171
+ continue
172
+ p1 = SRname.rfind("-")
173
+ if p1 > 0 and SRname[:p1] in channels:
174
+ continue
175
+ newDict[SRname]=value
176
+ return newDict
177
+
178
+ def _parseMetaData ( self ):
179
+ """ parse the model's meta data """
180
+ data = { "inputMeans": [], "inputErrors": [],
181
+ "nLL_exp_mu0": [ None ]*2, "nLL_obs_mu0": [ None ]*2,
182
+ "nLLA_exp_mu0": [ None ]*2, "nLLA_obs_mu0": [ None ]*2 }
183
+ data [ "bkg_yields" ] = {}
184
+ data [ "obs_yields" ] = {}
185
+ data["nLL_obs_max"]= [ None ] * 2
186
+ data["nLL_exp_max"]= [ None ] * 2
187
+ data["nLLA_obs_max"]= [ None ] * 2
188
+ data["nLLA_exp_max"]= [ None ] * 2
189
+ data["featureMeans"]= []
190
+ data["featureErrors"]= []
191
+ data["nllMeans"]= []
192
+ data["nllErrors"]= []
193
+ remove_channels=[]
194
+ import json
195
+ for em in self.mlModel.metadata_props:
196
+ if em.key == "channels":
197
+ data["crRegions"] = self._getCRs ( eval ( em.value ) )
198
+ if em.key == "remove_channels":
199
+ # remove these channels at the end, so that order does not matter
200
+ remove_channels = eval(em.value)
201
+ data["remove_channels"] = remove_channels
202
+ elif em.key == "obs_yields":
203
+ st = eval(em.value)
204
+ for l in st: ## the sm yields are tuple of (name,value)
205
+ data["obs_yields"][ l[0] ]= int ( l[1] )
206
+ elif em.key == "bkg_yields":
207
+ st = eval(em.value)
208
+ for l in st: ## the sm yields are tuple of (name,value)
209
+ data["bkg_yields"][ l[0] ] = l[1]
210
+ elif em.key == "standardization_mean":
211
+ data["inputMeans"] = eval(em.value)
212
+ elif em.key == "standardization_std":
213
+ data["inputErrors"] = eval(em.value)
214
+ elif em.key in [ 'nLL_exp_mu0', 'nLL_obs_mu0', 'nLLA_exp_mu0', \
215
+ 'nLLA_obs_mu0' ]:
216
+ data[em.key] = json.loads(em.value)
217
+ elif em.key in [ 'nLL_exp_max', 'nLL_obs_max', 'nLLA_exp_max', \
218
+ 'nLLA_obs_max', 'nLL_exp_mu0', ]:
219
+ data[em.key] = self._fillValues ( em.key, em.value )
220
+ elif em.key == "standardization":
221
+ values = eval(em.value)
222
+ data["featureMeans"] = values["features_mean"][0]*3
223
+ data["featureErrors"] = values["features_std"][0]*3
224
+ data["nllMeans"] = values["nLLs_mean"][0]
225
+ data["nllErrors"] = values["nLLs_std"][0]
226
+ elif em.key == "run_config":
227
+ import yaml
228
+ content = yaml.safe_load ( em.value )
229
+ data["run_config"] = content
230
+
231
+ if len(remove_channels)>0:
232
+ data["bkg_yields"]=self._removeSignalRegions ( remove_channels,
233
+ data["bkg_yields"] )
234
+ data["obs_yields"]=self._removeSignalRegions ( remove_channels,
235
+ data["obs_yields"] )
236
+ self.onnxMeta = data
237
+
238
+ def _predictFromScaledYields ( self, scaled_yields : np.array ) -> np.array:
239
+ """ get the prediction from the NN
240
+
241
+ :param scaled_yields: the input of the neural network
242
+ :returns: arr, the unscaled unshifted output of the neural network
243
+ """
244
+ if len(scaled_yields[0])!=self.regressor["dim"]:
245
+ dim_nn = self.regressor["dim"]
246
+ dim_input = len(scaled_yields[0])
247
+ line=f"the network of {self.onnxfilename} wants {dim_nn} input dimensions, but we supply {dim_input}. fix it!"
248
+ print ( f"[nnAdapter] {line}" )
249
+ print ( f"[nnAdapter] srOrder: {self.srOrder}" )
250
+ sys.exit()
251
+ dct = { "features": scaled_yields }
252
+ arr = self.regressor["session"].run(None, dct )
253
+ arr = arr[0][0]
254
+ return arr
255
+
256
+ def _postprocess( self, arr : np.ndarray,
257
+ add_errors : bool = True ) -> dict:
258
+ """ given the networks predictions, compute the NLLs
259
+
260
+ :param arr: the neural network output
261
+ :param add_errors: if true, then add errors also FIXME describe
262
+ more
263
+ :returns: { "nll_exp_0": ..., "nll_exp_1": ...,
264
+ "nll_obs_0": ..., "nll_obs_1": ...,
265
+ "nllA_exp_0": ..., "nllA_exp_1": ...,
266
+ "nllA_obs_0": ..., "nllA_obs_1": ... }
267
+ """
268
+ from hep_olll.nnPreprocessing import postprocess_nLLs
269
+ deltas_prepd = np.array(arr, dtype=np.float64)
270
+ trafos = self.onnxMeta["run_config"]["data"]["nLL_trafos"]
271
+ nll_means = self.onnxMeta["nllMeans"]
272
+ nll_errors = self.onnxMeta["nllErrors"]
273
+ deltas = postprocess_nLLs ( deltas_prepd[:4],
274
+ mean = nll_means, std = nll_errors, trafos = trafos )
275
+ deltas = list ( map ( float, deltas ) )
276
+ nll0exp = self.onnxMeta["nLL_exp_mu0"]
277
+ nll0obs = self.onnxMeta["nLL_obs_mu0"]
278
+ nllA0exp = self.onnxMeta["nLLA_exp_mu0"]
279
+ nllA0obs = self.onnxMeta["nLLA_obs_mu0"]
280
+
281
+ nll1exp = nll0exp + deltas[0]
282
+ nll1obs = nll0obs + deltas[1]
283
+ nllA1exp = nllA0exp + deltas[2]
284
+ nllA1obs = nllA0obs + deltas[3]
285
+
286
+ ret = { "nll_exp_0": nll0exp, "nll_exp_1": nll1exp,
287
+ "nll_obs_0": nll0obs, "nll_obs_1": nll1obs,
288
+ "nllA_exp_0": nllA0exp, "nllA_exp_1": nllA1exp,
289
+ "nllA_obs_0": nllA0obs, "nllA_obs_1": nllA1obs }
290
+ if self.onnxMeta["nLL_obs_max"][1] is not None:
291
+ ret["nll_obs_max"] = self.onnxMeta["nLL_obs_max"][1]
292
+ if add_errors:
293
+ from hep_olll.nnPreprocessing import postprocess_nLLs_errors
294
+ errs = postprocess_nLLs_errors ( deltas_prepd[4:],
295
+ deltas_prepd[:4],
296
+ mean = nll_means,
297
+ std = nll_errors, trafos = trafos,
298
+ eps = 1e-5 )
299
+ errs = list ( map ( float, errs ) )
300
+ ret["sigma_exp"] = errs[0]
301
+ ret["sigma_obs"] = errs[1]
302
+ ret["sigma_expA"] = errs[2]
303
+ ret["sigma_obsA"] = errs[3]
304
+ return ret
305
+
306
+ def _totalYieldsFromSignals ( self, signal_yields : dict,
307
+ obs_as_bg : list = [] ) -> dict:
308
+ """ given the signal yields, return the total
309
+ yields, signal + background
310
+
311
+ :param signal_yields: the signal yields, as a (srname, yield) dictionary
312
+ :param obs_abs_bg: a list of signal regions for which we use
313
+ observations as background_yields ("postfit")
314
+
315
+ :returns: the total yields, as a dictionary
316
+ """
317
+ new_yields = {}
318
+ account_for_crs = obs_as_bg[:]
319
+
320
+ for srname,smyield in self.onnxMeta["bkg_yields"].items():
321
+ assert srname in signal_yields, \
322
+ f"nnInterface: cannot find sr name {srname} in '{ signal_yields }'"
323
+ signal = signal_yields[srname]
324
+ if srname in obs_as_bg:
325
+ account_for_crs.remove ( srname )
326
+ smyield = self.onnxMeta["obs_yields"][srname]
327
+ signal = 0.
328
+ tot = smyield + signal
329
+ new_yields[srname] = tot
330
+ if len(account_for_crs)>0:
331
+ raise Exception ( f"signal region(s) {account_for_crs} unknown" )
332
+
333
+ return new_yields
334
+
335
+
336
+ def _preprocess ( self, yields : Union[dict,list] ) -> dict:
337
+ if type(yields)==dict:
338
+ yields = self._inputDictToList ( yields )
339
+ inp_list = np.array ( yields )
340
+ from hep_olll.nnPreprocessing import preprocess_features
341
+ trafos = self.onnxMeta["run_config"]["data"]["trafos"]
342
+ nYields = len(yields)
343
+ re = preprocess_features ( inp_list,
344
+ trafos = trafos,
345
+ mean = np.array ( self.onnxMeta["featureMeans"][:nYields] ),
346
+ std = np.array ( self.onnxMeta["featureErrors"][:nYields] ) )
347
+ ret = [ re[0] ]
348
+ return ret
349
+
350
+ def _inputDictToList ( self, in_dict : dict ) -> list:
351
+ """ translate a dictionary of input yields to a list
352
+ of said yields in the canonical order specified in the onnx
353
+ :raises: exception if input SR is missing or one too many
354
+ :returns: list of yields
355
+ """
356
+ ret = []
357
+ account_for_srs = list(in_dict.keys())
358
+ if len(in_dict) != len ( self.srOrder ):
359
+ raise Exception ( f"length of dict ({len(in_dict)} does not match srOrder ({len(self.srOrder)})" )
360
+ for sr in self.srOrder:
361
+ dsr = sr
362
+ #if dsr.endswith ( "-0" ):
363
+ # dsr = sr[:-2]
364
+ if sr in in_dict:
365
+ ret.append ( in_dict[sr] )
366
+ account_for_srs.remove ( sr )
367
+ continue
368
+ #if dsr in in_dict:
369
+ # ret.append ( in_dict[dsr] )
370
+ # continue
371
+ raise Exception ( f"signal region {sr} not in input_dict" )
372
+ if len(account_for_srs)>0:
373
+ raise Exception ( f"signal region(s) {account_for_srs} unknown" )
374
+ return ret
@@ -0,0 +1,196 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ .. module:: preprocessing_nnAdapter
5
+ :synopsis: Preprocessing and inverse-preprocessing functions for the
6
+ NNAdapter. Handles feature standardisation and nLL postprocessing,
7
+ including uncertainty propagation through arbitrary transformation chains.
8
+
9
+ """
10
+
11
+ __all__ = [
12
+ "preprocess_features",
13
+ "postprocess_nLLs",
14
+ "postprocess_nLLs_errors",
15
+ ]
16
+
17
+ import numpy as np
18
+ from typing import Optional, Callable
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Elementary transforms (forward and inverse)
23
+ # ---------------------------------------------------------------------------
24
+
25
+ def _log_with_negatives(x: np.ndarray) -> np.ndarray:
26
+ """Signed log1p transform, works for negative values, exactly invertible."""
27
+ return np.sign(x) * np.log1p(np.abs(x))
28
+
29
+
30
+ def _undo_log_with_negatives(x: np.ndarray) -> np.ndarray:
31
+ """Exact inverse of _log_with_negatives."""
32
+ return np.sign(x) * np.expm1(np.abs(x))
33
+
34
+
35
+ def _standardize(
36
+ x: np.ndarray,
37
+ mean: np.ndarray,
38
+ std: np.ndarray,
39
+ ) -> np.ndarray:
40
+ """Apply standardisation using pre-computed mean and std."""
41
+ return (x - mean) / std
42
+
43
+
44
+ def _undo_standardize(
45
+ x: np.ndarray,
46
+ mean: np.ndarray,
47
+ std: np.ndarray,
48
+ ) -> np.ndarray:
49
+ """Invert standardisation."""
50
+ return x * std + mean
51
+
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # Feature preprocessing (forward, used at inference time)
55
+ # ---------------------------------------------------------------------------
56
+
57
+ def _get_fn(fn_str: str) -> Callable:
58
+ """Return a named scalar transform."""
59
+ match fn_str:
60
+ case "log":
61
+ return np.log
62
+ case "exp":
63
+ return np.exp
64
+ case "sqrt":
65
+ return np.sqrt
66
+ case "inverse":
67
+ return lambda x: 1.0 / x
68
+ case "log_w_negatives":
69
+ return _log_with_negatives
70
+ case _:
71
+ raise ValueError(f"Unknown transform '{fn_str}'.")
72
+
73
+
74
+ def preprocess_features(
75
+ features_raw: np.ndarray,
76
+ trafos: Optional[dict] = None,
77
+ mean: Optional[np.ndarray] = None,
78
+ std: Optional[np.ndarray] = None,
79
+ ) -> tuple[np.ndarray, Optional[np.ndarray], Optional[np.ndarray]]:
80
+ """Apply feature preprocessing using saved mean/std from training.
81
+
82
+ :param features_raw: raw input features, shape (batch, n_features)
83
+ :param trafos: dict mapping set-name to list of transform strings,
84
+ e.g. ``{"fvs_standardized": ["log_w_negatives", "standardization"]}``
85
+ :param mean: per-feature mean saved at training time (required when
86
+ "standardization" is in trafos)
87
+ :param std: per-feature std saved at training time (required when
88
+ "standardization" is in trafos)
89
+ :returns: (scaled_features, mean, std)
90
+ """
91
+ assert np.isfinite(features_raw).all(), "Non-finite values in features_raw"
92
+
93
+ feature_sets = {}
94
+ if trafos:
95
+ for set_name, fn_list in trafos.items():
96
+ transformed = features_raw.copy()
97
+ for fn_str in fn_list:
98
+ if fn_str == "standardization":
99
+ assert mean is not None and std is not None, \
100
+ "mean and std must be provided for standardization at inference time"
101
+ transformed = _standardize(transformed, mean, std)
102
+ else:
103
+ transformed = _get_fn(fn_str)(transformed)
104
+ feature_sets[set_name] = transformed
105
+
106
+ scaled = list ( map ( float, feature_sets["fvs_standardized"] ) )
107
+ # scaled = np.concatenate(list(feature_sets.values()), axis=1) if feature_sets else features_raw
108
+ return scaled, mean, std
109
+
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # nLL postprocessing (inverse transforms)
113
+ # ---------------------------------------------------------------------------
114
+
115
+ def _get_inv_fn(fn_str: str) -> Callable:
116
+ """Return the inverse of a named scalar transform."""
117
+ match fn_str:
118
+ case "log":
119
+ return np.exp
120
+ case "exp":
121
+ return np.log
122
+ case "sqrt":
123
+ return lambda x: x ** 2
124
+ case "inverse":
125
+ return lambda x: 1.0 / x
126
+ case "log_w_negatives":
127
+ return _undo_log_with_negatives
128
+ case _:
129
+ raise ValueError(f"No known inverse for transform '{fn_str}'.")
130
+
131
+
132
+ def postprocess_nLLs(
133
+ nLLs: np.ndarray,
134
+ mean: np.ndarray,
135
+ std: np.ndarray,
136
+ trafos: Optional[list] = None,
137
+ ) -> np.ndarray:
138
+ """Undo nLL preprocessing in reverse order.
139
+
140
+ :param nLLs: preprocessed nLL deltas output by the NN, shape (4,)
141
+ :param mean: per-output mean saved at training time
142
+ :param std: per-output std saved at training time
143
+ :param trafos: list of transform strings applied during training,
144
+ e.g. ``["log_w_negatives", "standardization"]``
145
+ :returns: unpreprocessed nLL deltas, same shape as nLLs
146
+ """
147
+ if trafos and "per_output" in trafos:
148
+ scale = float(trafos.get("asinh_scale", 1.0))
149
+ nLLs = np.array(nLLs, dtype=np.float64)
150
+ for c, fn_list in enumerate(trafos["per_output"]):
151
+ for fn_str in reversed(fn_list):
152
+ if fn_str == "standardization":
153
+ nLLs[c] = nLLs[c] * std[c] + mean[c]
154
+ elif fn_str == "asinh":
155
+ nLLs[c] = scale * np.sinh(nLLs[c])
156
+ else:
157
+ nLLs[c] = _get_inv_fn(fn_str)(nLLs[c])
158
+ assert np.isfinite(nLLs).all(), "Non-finite values after postprocess_nLLs"
159
+ return nLLs
160
+ if trafos:
161
+ for fn_str in reversed(trafos):
162
+ if fn_str == "standardization":
163
+ nLLs = _undo_standardize(nLLs, mean, std)
164
+ else:
165
+ nLLs = _get_inv_fn(fn_str)(nLLs)
166
+ assert np.isfinite(nLLs).all(), "Non-finite values after postprocess_nLLs"
167
+ return nLLs
168
+
169
+
170
+ def postprocess_nLLs_errors(
171
+ errors: np.ndarray,
172
+ nLLs_prepd: np.ndarray,
173
+ mean: np.ndarray,
174
+ std: np.ndarray,
175
+ trafos: Optional[list] = None,
176
+ eps: float = 1e-5,
177
+ ) -> np.ndarray:
178
+ """Propagate heteroskedastic errors through the inverse nLL preprocessing.
179
+
180
+ Uses central-difference numerical differentiation to compute
181
+ ``|d(postprocess)/d(nLL)| * sigma`` for each output independently.
182
+
183
+ :param errors: NN-predicted uncertainties on the preprocessed deltas,
184
+ shape (4,), these are the errors on nLLs_prepd
185
+ :param nLLs_prepd: the central (mean) preprocessed nLL deltas, shape (4,)
186
+ :param mean: per-output mean saved at training time
187
+ :param std: per-output std saved at training time
188
+ :param trafos: same transform list used in postprocess_nLLs
189
+ :param eps: step size for numerical differentiation
190
+ :returns: propagated uncertainties on the unpreprocessed nLL deltas,
191
+ shape (4,)
192
+ """
193
+ f_plus = postprocess_nLLs(nLLs_prepd + eps, mean, std, trafos)
194
+ f_minus = postprocess_nLLs(nLLs_prepd - eps, mean, std, trafos)
195
+ deriv = np.abs(f_plus - f_minus) / (2.0 * eps)
196
+ return deriv * errors
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: hep-olll
3
+ Version: 0.1.0
4
+ Summary: Neural network adapter for LHC likelihood interpretation
5
+ Home-page: https://github.com/OpenML-LHClikelihoods/
6
+ Author: OLLL collaboration
7
+ Author-email:
8
+ License: GPLv3
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Topic :: Scientific/Engineering :: Physics
11
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: onnx>=1.10.0
15
+ Requires-Dist: onnxruntime>=1.20.0
16
+ Requires-Dist: numpy>=2.0.0
17
+ Requires-Dist: pyyaml
18
+ Dynamic: author
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: license
24
+ Dynamic: requires-dist
25
+ Dynamic: requires-python
26
+ Dynamic: summary
27
+
28
+ # Open library of learned likelihoods from LHC experiments
29
+
30
+ The release of full statistical models from LHC analyses is a major milestone in the
31
+ LHC’s legacy. They encapsulate the full information of an analysis, including the likeli-
32
+ hood given data. Thus, full releases enable collider phenomenology to be performed at full
33
+ statistical precision. However, this comes with a significant enlargement of computational
34
+ costs. For most reinterpretation processes, we are interested in the profiled likelihood,
35
+ which is slow to extract from the statistical model, particularly for analyses with mul-
36
+ tiple signal regions. To mitigate this, we present OLLL, an Open Library of Learned
37
+ Likelihoods from LHC experiments. OLLL is composed of profiled likelihood functions
38
+ modelled with Neural Networks (NNs). We show, through five examples of increasing
39
+ complexity, that such functions can be well described with simple NNs, published in the
40
+ ONNX format, and easily used by different reinterpretation tools without compromising
41
+ statistical precision.
42
+
43
+ ## Example usage (taken from ATLAS-SUSY-2018-04):
44
+
45
+ ```python
46
+ from nnAdapter import NNAdapter
47
+ onnxFile = "atlas-susy-2018-04.onnx"
48
+
49
+ adapter = NNAdapter ( onnxFile, session_options = {} )
50
+
51
+ bkg_yields = adapter.onnxMeta["bkg_yields"]
52
+ ret = adapter.predict ( bkg_yields, yields_are_signal_yields = False )
53
+ print ( "predicting for total yields:" )
54
+ print ( "\n".join( f"{key:10s}: {value:.1f}" for key,value in ret.items()) )
55
+
56
+ sig_yields = { k: 0. for k in bkg_yields }
57
+ ret = adapter.predict ( sig_yields, yields_are_signal_yields = True )
58
+
59
+ print ( )
60
+ print ( f"predicting for signal yields:" )
61
+ print ( "\n".join( f"{key:10s}: {value:.1f}" for key,value in ret.items()) )
62
+ print ( )
63
+ ```
64
+
65
+ This produces as output:
66
+
67
+ ```
68
+ predicting for total yields:
69
+ nll_exp_0 : 99.0
70
+ nll_exp_1 : 99.0
71
+ nll_obs_0 : 99.6
72
+ nll_obs_1 : 99.6
73
+ nllA_exp_0: 99.0
74
+ nllA_exp_1: 99.0
75
+ nllA_obs_0: 99.1
76
+ nllA_obs_1: 99.1
77
+ nll_obs_max: 99.3
78
+ sigma_exp : 0.0
79
+ sigma_obs : 0.0
80
+ sigma_expA: 0.0
81
+ sigma_obsA: 0.0
82
+
83
+ predicting for signal yields:
84
+ nll_exp_0 : 99.0
85
+ nll_exp_1 : 99.0
86
+ nll_obs_0 : 99.6
87
+ nll_obs_1 : 99.6
88
+ nllA_exp_0: 99.0
89
+ nllA_exp_1: 99.0
90
+ nllA_obs_0: 99.1
91
+ nllA_obs_1: 99.1
92
+ nll_obs_max: 99.3
93
+ sigma_exp : 0.0
94
+ sigma_obs : 0.0
95
+ sigma_expA: 0.0
96
+ sigma_obsA: 0.0
97
+ ```
98
+
99
+ The NNAdapter can also be installed via
100
+
101
+ ```
102
+ pip install hep_olll
103
+ ```
@@ -0,0 +1,10 @@
1
+ README.md
2
+ setup.py
3
+ hep_olll/metadataValidator.py
4
+ hep_olll/nnAdapter.py
5
+ hep_olll/nnPreprocessing.py
6
+ hep_olll.egg-info/PKG-INFO
7
+ hep_olll.egg-info/SOURCES.txt
8
+ hep_olll.egg-info/dependency_links.txt
9
+ hep_olll.egg-info/requires.txt
10
+ hep_olll.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ onnx>=1.10.0
2
+ onnxruntime>=1.20.0
3
+ numpy>=2.0.0
4
+ pyyaml
@@ -0,0 +1 @@
1
+ hep_olll
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import os
4
+ from setuptools import setup
5
+
6
+ def read(fname):
7
+ return open(os.path.join(os.path.dirname(__file__), fname)).read()
8
+
9
+ setup(
10
+ name = "hep-olll",
11
+ version = "0.1.0",
12
+ author = "OLLL collaboration",
13
+ author_email="",
14
+ python_requires='>=3.10',
15
+ install_requires=["onnx>=1.10.0", "onnxruntime>=1.20.0", "numpy>=2.0.0", "pyyaml"],
16
+ description="Neural network adapter for LHC likelihood interpretation",
17
+ license="GPLv3",
18
+ url="https://github.com/OpenML-LHClikelihoods/",
19
+ packages=["hep_olll" ],
20
+ # py_modules=["nnAdapter", "nnPreprocessing", "metadataValidator" ],
21
+ long_description=read("README.md"),
22
+ long_description_content_type="text/markdown",
23
+ classifiers=[
24
+ "Development Status :: 4 - Beta",
25
+ "Topic :: Scientific/Engineering :: Physics",
26
+ "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
27
+ ]
28
+ )