-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinputObjects.py
More file actions
1535 lines (1357 loc) · 64.5 KB
/
inputObjects.py
File metadata and controls
1535 lines (1357 loc) · 64.5 KB
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
#!/usr/bin/env python
"""
.. module:: inputObjects
:synopsis: Holds objects used by convert.py.
.. moduleauthor:: Michael Traub <[email protected]>
.. moduleauthor:: Wolfgang Waltenberger <[email protected]>
.. moduleauthor:: Andre Lessa <[email protected]>
"""
import sys
import os
from smodels_utils.helper.txDecays import TxDecay
from smodels_utils.dataPreparation.databaseCreation import databaseCreator,round_list
from smodels_utils.dataPreparation.dataHandlerObjects import hbar
from smodels_utils.dataPreparation.covarianceHandler import \
UPROOTCovarianceHandler, CSVCovarianceHandler, PYROOTCovarianceHandler,\
FakeCovarianceHandler
from smodels_utils.dataPreparation import covarianceHandler
from smodels.base.physicsUnits import fb, pb, TeV, GeV
from smodels_utils.dataPreparation.massPlaneObjects import MassPlane
from smodels_utils.dataPreparation.graphMassPlaneObjects import GraphMassPlane
from smodels.experiment.expSMS import ExpSMS
from smodels.experiment.expAuxiliaryFuncs import smsInStr
from typing import Dict, Union
import logging
from smodels_utils.helper import prettyDescriptions
from smodels_utils.helper.terminalcolors import *
FORMAT = '%(levelname)s in %(module)s.%(funcName)s() in %(lineno)s: %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.WARNING)
quenchNegativeMasses = False ## set to true, if you wish to
# quench the warning about negative masses
errormsgs = {}
# if on, will check for overlapping constraints
_complainAboutOverlappingConstraints = False
complainAbout = { "sympy obj": 0, "x in datamap": 0, "axesMap": 0 }
def elementsInStr(instring : str,removeQuotes : bool = True) -> list: ## from V2
"""
Parse instring and return a list of elements appearing in instring.
instring can also be a list of strings.
:param instring: string containing elements (e.g. "[[['e+']],[['e-']]]+[[['mu+']],[['mu-']]]")
:param removeQuotes: If True, it will remove the quotes from the particle labels.
Set to False, if one wants to run eval on the output.
:returns: list of elements appearing in instring in string format
"""
outstr = ""
if isinstance(instring,str):
outstr = instring
elif isinstance(instring,list):
for st in instring:
if not isinstance(st,str):
logger.error("Input must be a string or a list of strings")
raise SModelSError()
# Combine list of strings in a single string
outstr += st
else:
raise SModelSError(f"syntax error in constraint/condition: ``{instring}''."\
"Check your constraints and conditions in your database." )
elements = []
outstr = outstr.replace(" ", "")
if removeQuotes:
outstr = outstr.replace("'", "")
elStr = ""
nc = 0
# Parse the string and looks for matching ['s and ]'s, when the matching is
# complete, store element
for c in outstr:
delta = 0
if c == '[':
delta = -1
elif c == ']':
delta = 1
nc += delta
if nc != 0:
elStr += c
if nc == 0 and delta != 0:
elements.append(elStr + c)
elStr = ""
# Syntax checks
ptclist = elements[-1].replace(']', ',').replace('[', ',').\
split(',')
for ptc in ptclist:
ptc = ptc.replace("'","")
if not ptc:
continue
# Check if there are not unmatched ['s and/or ]'s in the string
if nc != 0:
raise SModelSError(f"Wrong input (incomplete elements?) {instring}")
return elements
def getSignalRegionsEMBaked ( filename, exclude : list = [] ):
""" from an emBaked file, retrieve the names of the signal regions
:param filename: name of embaked file.
if list of filenames, get SRs for all and check if equal
:param exclude: list of SR regions to exclude
"""
if type ( filename) in [ list, tuple ]:
rets = {}
lens = {}
l0,l,lf = -1,-1,""
ret=None
for f in filename:
rets[f] = getSignalRegionsEMBaked ( f, exclude )
ret = rets[f]
l = len(rets[f])
lens[f] = l
if l0 > -1 and l != l0:
print ( "[inputObjects] number of signal regions in embaked files differ: {lf}:{l0}!={f}:{l}" )
l0,lf = l,f
return ret
# ret = set()
ret = []
try:
f=open( filename,"r")
values=list(eval(f.read()).values())
f.close()
except Exception as e:
logger.error ( f"cannot read {filename}: {e}" )
sys.exit(-1)
for v in values:
for k in v:
if not k.startswith("__") and not k in exclude:
if not k in ret:
ret.append(k)
#ret.add(k)
return ret
def getStatsEMBaked ( statsfile : os.PathLike = "orig/statsEM.py" ) -> Dict:
""" retrieve the stats from an emBaked stats file """
if not os.path.exists ( statsfile ):
print ( f"ERROR: cannot find {statsfile}" )
return None
f=open( statsfile )
g=eval(f.read())
f.close()
from smodels_utils.dataPreparation import databaseCreation
databaseCreation.DatabaseCreator.tempInputFiles.append ( statsfile )
return g
class Locker(object):
"""Super-class to 'lock' a class.
Every child-class of Locker needs 2 class-attributes:
infoAttr: list of strings
interAttr: list of strings
Only attributes with names defined in one of those lists can
be added to the child
"""
def __setattr__(self, name, attr):
"""
set a attripute if defiened in self.allowedAttr
:param name: name of the attribute
:param attr: value of the attribute
:raise attrError: If name is not in self.allowedAttr
"""
if name in self.allowedAttr:
object.__setattr__(self, name, attr)
return
logger.error( f"Attribute {name} is not allowed for {type(self)}" )
@property
def allowedAttr(self):
"""
:return: list containing all entries of
infoAttr and internalAttr
"""
return self.infoAttr + self.internalAttr + self.requiredAttr
class MetaInfoInput(Locker):
"""Holds all informations related to the publication
(publication means: physic summary note or conference note)
"""
infoAttr = [ 'id','sqrts', 'lumi', 'prettyName', 'url', 'arxiv',
'publication', 'publicationDOI', 'contact', 'supersededBy','supersedes', 'comment', 'modelFile', 'datasetOrderForModel', 'mlModels',
'private', 'implementedBy','lastUpdate', 'datasetOrder', 'covariance',
'combinableWith', 'jsonFiles', 'jsonFiles_FullLikelihood', 'source',
'Leff_inner', 'Leff_outer', 'type',
'includeCRs', 'onnxFiles', 'resultType', 'signalUncertainty' ]
internalAttr = ['_sqrts', '_lumi']
requiredAttr = ['sqrts', 'lumi', 'id', 'lastUpdate']
def __new__( cls, ID : str ):
"""
checks if databaseCreator already contains
a MetaInfoInput object, writes this object to
databaseCreation if not
:param ID: name of the publication as string
:returns: instance of MetaInfoInput
:raise Error: if there is already a MetaInfoInput instance
"""
if databaseCreator.metaInfo:
logger.error('MetaInfo object for this publication already defined')
sys.exit()
metaInfo = object.__new__(cls)
databaseCreator.metaInfo = metaInfo
return metaInfo
def createCovarianceMatrix ( self, filename : str,
histoname : Union[str,None] = None, addOrder : bool =True,
max_datasets : Union[int,None] = None,
aggregate : Union[list,None] = None,
datasets : Union[list,None] = None,
matrixIsCorrelations : bool = False,
aggprefix : str ="ar", zeroIndexed : bool = False,
scaleCov : float = 1.0, blinded_regions : list = [] ):
""" create the covariance matrix from file <filename>, histo <histoname>,
allowing only a maximum of <max_datasets> datasets. If
aggregate is not None, aggregate the signal regions, given as
a list of lists of signal region names, e.g.
[ [ "sr1", "sr2" ], [ "sr3", "sr4" ] ] or as a list of lists of
signal numbers, e.g. [ [ 1, 2 ], [ 3, 4 ] ]
:param addOrder: False, True, or "overwrite". should a datasetOrder field
be defined purely from the signal regions (overwrite),
only if no datasetOrder is explicitly given (True),
or the standard "SRx" names be used (False)
:param max_datasets: if not None, restrict the number of datasets
:param aggregate: aggregate signal regions, given by indices, e.g.
[[0,1,2],[3,4]] or signal region names, e.g.[["sr0","sr1"],["sr2"]].
:param datasets: list of datasets, so we can cross-check the covariance
matrix with the errors given per signal region
:param matrixIsCorrelations: if true, then assume that we histoname
refers to a correlation matrix, not a covariance matrix, so multiply with
the SR erros, accordingly
:param aggprefix: prefix for aggregate signal region names, eg ar0, ar1, etc
:param zeroIndexed: are indices given one-indexed or zero-indexed
:param scaleCov: allows to downscale the offdiagonal elements, so that
the determinant stays firmly positive
:param blinded_regions: list of regions we omit
"""
if type(filename)==dict:
if zeroIndexed:
logger.error ( "zeroIndex not implemented for FakeCovarianceHandler" )
if abs ( scaleCov - 1. ) > 1e-20:
logger.error ( "scaleCov not implemented for FakeCovarianceHandler" )
handler = FakeCovarianceHandler ( filename, max_datasets, aggregate,
aggprefix )
elif filename.endswith ( ".csv" ):
if zeroIndexed:
logger.error ( "zeroIndex not implemented for CSVCovarianceHandler" )
if abs ( scaleCov - 1. ) > 1e-20:
logger.error ( "scaleCov not implemented for CSVCovarianceHandler" )
handler = CSVCovarianceHandler ( filename,
max_datasets, aggregate, aggprefix )
else:
"""
try:
import ROOT
handler = PYROOTCovarianceHandler ( filename, histoname, max_datasets,
aggregate, aggprefix )
except ModuleNotFoundError as e:
logger.error ( "could not import pyroot, trying uproot now" )
handler = UPROOTCovarianceHandler ( filename, histoname, max_datasets,
aggregate, aggprefix )
"""
try:
import uproot
handler = UPROOTCovarianceHandler ( filename, histoname,
max_datasets, aggregate, aggprefix, zeroIndexed,
scaleCov = scaleCov, blinded_regions = blinded_regions,
datasets = datasets )
except ModuleNotFoundError as e:
logger.error ( "could not import uproot, trying pyroot now" )
if zeroIndexed:
logger.error ( "zeroIndex not implemented for PYROOTCovarianceHandler" )
sys.exit()
if abs ( scaleCov - 1. ) > 1e-20:
logger.error ( "scaleCov not implemented for PYROOTCovarianceHandler" )
sys.exit()
if len ( blinded_regions ) > 0:
logger.error ( "blinded_regions not implemented for PYROOTCovarianceHandler" )
sys.exit()
handler = PYROOTCovarianceHandler ( filename, histoname, max_datasets,
aggregate, aggprefix )
if not hasattr ( self, "datasetOrder" ) or addOrder == "overwrite":
if addOrder:
self.datasetOrder = ", ".join ( [ f'"{x}"' for x in handler.datasetOrder ] )
else:
self.datasetOrder = ", ".join ( [ f'"SR{x+1}"' for x in range ( handler.n ) ] )
self.covariance = handler.covariance
if True: ## pretty print
self.covariance = "["
for rowctr,row in enumerate(handler.covariance):
self.covariance += "["
for colctr,x in enumerate(row):
if matrixIsCorrelations:
if datasets == None:
logger.error ( "you supplied correlations, now i need datasets" )
sys.exit()
oldx=x
x = x * datasets[colctr].bgError * datasets[rowctr].bgError
#if colctr < 2 and rowctr < 2:
# logger.error ( f">>> ctrs={colctr}, {rowctr}, bgerr={datasets[colctr].bgError}, x={oldx}, {x}" )
if rowctr==colctr:
logger.debug ( f"variance({rowctr+1},{colctr+1})={x}" )
if datasets != None:
dsSigma = (datasets[rowctr].bgError)
dsVar = (datasets[rowctr].bgError)**2
if dsVar > 1.5 * x and not matrixIsCorrelations and covarianceHandler.overrideWithConservativeErrors:
logger.error ( f"variance determined from table ({dsVar:.2g}) is more than 1.5*variance in covariance matrix ({x:.2g}) at #({rowctr+1}). replace variance in covariance matrix with more conservative estimate." )
x = dsVar
logger.debug ( f"dataset({rowctr+1})^2={dsSigma}^2={dsVar}" )
off = max ( dsVar,x ) / min ( dsVar,x)
logger.debug ( f"it is a factor of {off:.1f} off" )
err = 2.*(dsVar-x ) / (dsVar+x)
logger.debug ( f"relative error on variance {100*err:.1f} percent" )
self.covariance += f"{x:.4g}, "
self.covariance = f"{self.covariance[:-2]}], "
self.covariance = f"{self.covariance[:-2]}]"
def __init__(self, ID):
"""
:param ID: name of the publication as string
"""
self.id = ID
@property
def sqrts(self):
"""
:returns: center-of-mass energy in TeV as String
"""
return self._sqrts
@sqrts.setter
def sqrts(self, value):
"""
sets center-of-mass energy
:param value: center-of-mass energy as float, integer or string
"""
value = self.unitValue(value,'*','TeV')
if not value:
logger.error("Sqrts value not correclty defined")
sys.exit()
self._sqrts = value
@property
def lumi(self):
"""
:returns: integrated luminosity in fb-1 as string
"""
return self._lumi
@lumi.setter
def lumi(self, value):
"""
sets integrated luminosity in fb-1 as string
:param value: integrated luminosity as float, integer or string
"""
value = self.unitValue(value,'/','fb')
if not value:
logger.error("lumi value not correclty defined")
sys.exit()
self._lumi = value
def unitValue(self, value, operation,unit):
"""
checks if input conditions are met by value
formats value
:param value: float, integer or a number as string
:param operation: '/' or '*'
:param unit: unit of value as string
"""
if isinstance(value, str):
check = value.split(operation)
if len(check) == 2:
if not check[1].strip() == unit: return False
try:
check[0] = float(check[0])
except:
return False
if len(check) == 1: return f'{value}{operation}{unit}'
if len(check) == 2: return value
return False
try:
check = float(value)
return f'{value}{operation}{unit}'
except:
return False
class DataSetInput(Locker):
"""
Holds all informations related to one dataset
"""
infoAttr = ['dataId','dataType','observedN','expectedBG','bgError', 'comment',
'upperLimit', 'expectedUpperLimit', 'aggregated', 'jsonfile', 'lumi',
'originalSRs', 'thirdMoment', 'regionType' ]
internalAttr = ['_name','_txnameList']
requiredAttr = ['dataType', 'dataId']
ntoys = 200000 ## number of toys in computing limits
def __init__(self,name):
"""initialize the dataset
:param name: name of dataset (used as folder name)
"""
if name == None:
name = "data"
if type(name)!=str or len(name)<1: ## or name[0] not in string.ascii_letters:
logger.error ( f"Illegal dataset name: ``{name}''. Make sure it starts with a letter." )
sys.exit()
self._name = name
self._txnameList = []
databaseCreator.addDataset(self)
def __eq__(self,other):
"""
Check if datasets have the same name
"""
if type(self) != type(other):
return False
return self._name == other._name
def __str__(self):
return self._name
def setInfo(self,**attributes):
"""
Set the attributes given as input. The only allowed attributes
are the ones defined in infoAttr:
:param attributes: Attributes and their values (dataId = xxx,...)
"""
for key,val in attributes.items():
if type(val) == type(None):
continue
if key in [ "upperLimit", "expectedUpperLimit" ] and type(val) == type(fb):
val = f"{val.asNumber(fb)!s}*fb"
setattr(self,key,val)
def computeULs ( self ):
#First check if a luminosity has been defined for the dataset
if hasattr(self,"lumi"):
lumi = self.lumi
else:
lumi = getattr(databaseCreator.metaInfo,'lumi')
if isinstance(lumi,str):
lumi = eval(lumi,{'fb':fb,'pb': pb})
# lumi = lumi.asNumber(1./fb)
if False: ## the spey stuff
try:
import spey
except ImportError as e:
print ( f"[inputObjects] seems like you dont have spey. install it!" )
sys.exit()
from smodels.tools.speyTools import SpeyComputer, SimpleSpeyDataSet
dataset = SimpleSpeyDataSet ( float(self.observedN),
float(self.expectedBG), float(self.bgError), lumi )
computer = SpeyComputer ( dataset, 1. )
try:
ulspey = computer.poi_upper_limit ( expected = False, limit_on_xsec = True )
ulspeyE = computer.poi_upper_limit ( expected = True, limit_on_xsec = True )
except Exception as e:
ulspey = computer.poi_upper_limit ( evaluationType = observed, limit_on_xsec = True )
ulspeyE = computer.poi_upper_limit ( evaluationType = apriori, limit_on_xsec = True )
#Round numbers:
ulspey, ulspeyE = round_list(( ulspey.asNumber(fb),ulspeyE.asNumber(fb)), 4)
return ulspey, ulspeyE
alpha = .05
try:
try:
# v3.1.0
# new API
from smodels.statistics.simplifiedLikelihoods import Data, UpperLimitComputer, LikelihoodComputer
from smodels.statistics.basicStats import aposteriori
m = Data ( self.observedN, self.expectedBG, self.bgError**2, None, 1.,
lumi = lumi )
llhdComp = LikelihoodComputer ( m )
comp = UpperLimitComputer ( llhdComp, 1. - alpha )
ul = comp.getUpperLimitOnSigmaTimesEff ( ).asNumber ( fb )
try:
ulExpected = comp.getUpperLimitOnSigmaTimesEff ( expected=aposteriori ).asNumber ( fb )
except Exception as e:
ulExpected = comp.getUpperLimitOnSigmaTimesEff ( evaluationType=aposteriori ).asNumber ( fb )
if type(ul) == type(None):
ul = comp.getUpperLimitOnSigmaTimesEff ( m, )
ul, ulExpected = round_list(( ul, ulExpected ), 4)
return ul, ulExpected
except Exception as e:
print ( f"[inputObjects] Exception {e}, will try with older version" )
try:
# v3.0.0
from smodels.statistics.simplifiedLikelihoods import Data, UpperLimitComputer
# new API
m = Data ( self.observedN, self.expectedBG, self.bgError**2, None, 1.,
lumi = lumi )
comp = UpperLimitComputer ( 1. - alpha )
ul = comp.getUpperLimitOnSigmaTimesEff ( m ).asNumber ( fb )
ulExpected = comp.getUpperLimitOnSigmaTimesEff ( m, expected="posteriori" ).asNumber ( fb )
if type(ul) == type(None):
ul = comp.getUpperLimitOnSigmaTimesEff ( m, )
ul, ulExpected = round_list(( ul, ulExpected ), 4)
print ( f"[inputObjects] older version worked!" )
return ul, ulExpected
except Exception as e:
print ( "Exception", e )
except Exception as e:
print ( f"[inputObjects] Exception {e}" )
# print ( "@>>>>>", "obs", m.observed, "bg", m.backgrounds, "+-", m.covariance )
# print ( "SModelS ul", ul, "ule", ulExpected )
# print ( "spey ul", ulspey, ulspeyE )
return None, None
def computeStatistics(self):
"""Compute expected and observed limits and store them """
if not hasattr(databaseCreator, 'metaInfo'):
logger.error('MetaInfo must be defined before computing statistics')
sys.exit()
elif not hasattr(databaseCreator.metaInfo, 'lumi'):
logger.error('Luminosity must be defined in MetaInfo')
sys.exit()
elif not hasattr(self, 'observedN') or not hasattr(self, 'expectedBG') or not hasattr(self, 'bgError'):
if hasattr(self,"jsonfile"):
logger.error ( "pyhf result. for now I wont compute anything. FIXME probably should though." )
# self.upperLimit = str(ul)+'*fb'
# self.expectedUpperLimit = str(ulExpected)+'*fb'
return
logger.error('observedN, expectedBG and bgError must be defined before computing statistics')
sys.exit()
ul, ulExpected = self.computeULs ( )
self.upperLimit = f"{ul!s}*fb"
self.expectedUpperLimit = f"{ulExpected!s}*fb"
def addTxName( self,txname : str ):
"""
Adds txname to dataset. Checks if txname already exists and
raise an error if it does.
:param txname: txname (string)
:return: TxNameInput object
"""
for txobj in self._txnameList:
if txobj._name == txname:
logger.error( f"Txname {txname} already exists in dataset" )
sys.exit()
txobj = TxNameInput(txname)
self._txnameList.append(txobj)
return txobj
def checkConsistency(self):
"""
Some consistency checks which the dataset must satisfy
"""
#Check if it contains txnames:
if not self._txnameList:
logger.error( f"Dataset {self} does not contain txnames" )
return False
#Check txname data type
for tx in self._txnameList:
txDataTypes = set()
for plane in tx._planes:
if hasattr(plane,'upperLimits'):
txDataTypes.add('upperLimits')
elif hasattr(plane,'efficiencyMap'):
txDataTypes.add('efficiencyMap')
txDataTypes = list(txDataTypes)
if not txDataTypes:
logger.info( f"{self}:{tx.txName} has neither upperLimits nor efficiencyMap data. skip it!" )
# return False
if len(txDataTypes) > 1:
logger.error( f"Txname {tx.txName} has mixed data types" )
return False
if len(txDataTypes) > 0 and not self.dataType in txDataTypes[0]:
logger.error( f"Txname {tx.txName} data type ({txDataTypes[0]}) does not match dataset type ({self.dataType})" )
return False
if self.dataType != 'efficiencyMap':
return True
#Check constraints (only for EM results):
datasetElements = []
for tx in self._txnameList:
for el in smsInStr(tx.constraint):
newEl = None
fs = tx.finalState
midState = tx.intermediateState
try:
newEl = ExpSMS.from_string(el,finalState=fs,intermediateState=midState,model=tx._particles)
except Exception as e:
logger.error(str(e))
logger.error("Error building elements. Are the versions of smodels-utils and smodels compatible?")
sys.exit()
datasetElements.append(newEl)
for iel,elA in enumerate(datasetElements):
for jel,elB in enumerate(datasetElements):
if jel <= iel:
continue
if hasattr ( elA, "particlesMatch" ) and elA.particlesMatch(elB):
logger.error( f"Constraints ({elA} <-> {elB}) appearing in dataset {self} overlap (may result in double counting)" )
if not _complainAboutOverlappingConstraints: return True
return False
if elA == elB:
logger.error( f"Constraints ({elA} <-> {elB}) appearing in dataset {self} overlap (may result in double counting)" )
if not _complainAboutOverlappingConstraints: return True
return False
return True
class TxNameInput(Locker):
"""
Holds all informations related to one txName
"""
infoAttr = ['txName','constraint', 'condition','conditionDescription',
'susyProcess','checked','figureUrl','dataUrl','source',
'comment', 'validated','axes','upperLimits', 'validationTarball',
'efficiencyMap','expectedUpperLimits','xrange', 'yrange',
'axesMap', 'dataMap', 'bsmProcess' ]
internalAttr = ['_name', 'name', '_txDecay','_planes','_goodPlanes',
'_branchcondition', 'onShell', 'offShell', 'constraint',
'condition', 'conditionDescription','massConstraint',
'upperLimits','efficiencyMap','expectedUpperLimits',
'massConstraints', '_dataLabels', 'round_to',
'_databaseParticles', '_smallerThanError', '_particles',
'_node2arrayDict']
requiredAttr = [ 'constraint','condition','txName','dataUrl', 'source' ]
infoAttr.append ( 'finalState' )
infoAttr.append ( 'intermediateState' )
requiredAttr.append ( 'finalState' )
__hasWarned__ = { "omitted": 0 }
round_to = 7 ## number of digits to round to
def addValidationTarballsFromPlanes ( self ):
""" if a mass plane has a validation tarball defined,
add it to to this TxnameInput object, together with axis name """
for p in self._planes:
if hasattr ( p, "validationTarball" ):
if p.validationTarball == None:
# p.validationTarball = "skip"
continue
line = f"{str(p).replace(' ', '')}:{p.validationTarball}"
if not hasattr ( self, "validationTarball" ) or self.validationTarball in [ "", None ]:
self.validationTarball = line
else:
self.validationTarball += f";{line}"
def addXYRangesFromPlanes ( self ):
""" if a mass plane has xrange or yrange defined, add it to this
TxnameInput object, together with the axis name """
for p in self._planes:
if hasattr ( p, "xrange" ):
if type(p.xrange) == list:
p.xrange=str(p.xrange)
line = f"{str(p).replace(' ', '')}:{p.xrange}"
if not hasattr ( self, "xrange" ) or self.xrange in [ "", None ]:
self.xrange = line
else:
self.xrange += f";{line}"
if hasattr ( p, "yrange" ):
if type(p.yrange) == list:
p.yrange=str(p.yrange)
line = f"{str(p).replace(' ', '')}:{p.yrange}"
if not hasattr ( self, "yrange" ) or self.yrange in [ "", None ]:
self.yrange = line
else:
self.yrange += f";{line}"
def __init__(self,txName):
"""initialize the txName related values an objects
checks if the given txName string is valid
:param txName: name as string
:raise unknownTxNameError: if txName string is not known by module
helper.txDecays
:raise doubleDecayError: if helper.txDecays holds 2 txNames with
the same decay chain
"""
self._name = txName
self._smallerThanError = 0
self.txName = txName
self.finalState = ['MET','MET']
self.intermediateState = None
self.bsmProcess = prettyDescriptions.prettyTxname(txName,outputtype="text")
self._txDecay = TxDecay(self._name)
if not self._txDecay:
logger.error( f"Unknown txname {self._name}" )
sys.exit()
self._planes = []
self._goodPlanes = []
self._dataLabels = []
self.setDefaultParticles()
def __str__(self):
return self._name
def setDefaultParticles(self):
"""
Load the default particles contained in the smodels/experiment/defaultFinalStates.py.
"""
from smodels.experiment.defaultFinalStates import finalStates
self._particles = finalStates
def setParticlesFromFile(self,particlesFile):
"""
Load the particles contained in the particlesFile. These are stored in self._particles
and used to build the txname elements.
"""
pFile = os.path.abspath(particlesFile)
if not os.path.isfile(pFile):
logger.error( f"Could not find file {pFile}" )
sys.exit()
from importlib import import_module
sys.path.append(os.path.dirname(pFile))
pF = os.path.basename(os.path.splitext(pFile)[0])
logger.debug( f"Loading database particles from: {pFile}" )
modelFile = import_module(pF, package='smodels')
if not hasattr(modelFile,'finalStates'):
logger.error( f"Model definition (finalStates) not found in {pFile}" )
else:
#set model name to file location:
modelFile.finalStates.label = os.path.basename(pFile)
self._particles = modelFile.finalStates
def addMassPlaneV2(self, plane):
"""
add a MassPlane object with given axes to self.planes, for axes v2 format
Add new attributes to the MassPlane.
:param txDecay: object of type TxDecay
:param plane: A MassPlane object or the full mass array containing
equations which relate the physical masses and the plane
coordinates, using the pre-defined 'x','y',.. symbols.
(e.g. [[x,y],[x,y]]).
:raise missingMassError: if one mass entry is missing
:raise onlyOnePlaneError: if a second mass plane is given and the related mass space
have only 2 dimensions
:raise interMediateParticleError: if a interMasses are given and the related
mass space
have only 2 dimensions
:return: MassPlane-object
"""
if isinstance(plane,MassPlane):
self._planes.append(plane)
return plane
elif isinstance(plane,list):
massArray = plane
else:
logger.error("Input must be a MassPlane object or a mass array")
sys.exit()
try:
element = ExpSMS.from_string(smsInStr(self.constraint)[0],
intermediateState=self.intermediateState,
finalState=self.finalState,
model = self._particles)
except Exception as e:
logger.error(str(e))
logger.error("Error building elements. Are the versions of smodels-utils and smodels compatible?")
sys.exit()
for ibr,br in enumerate(element.branches):
if str(br) == '[*]': #Ignore wildcard branches
continue
if len(massArray[ibr]) != br.vertnumb+1:
logger.error( f"Mass array definition ({len(massArray[ibr])}-dim) is not consistent with the txname constraint ({br.vertnumb+1}-dim) in {self._txDecay} [{plane}]" )
sys.exit()
#Create mass plane for new input
massPlane = MassPlane(self._txDecay,massArray)
self._planes.append(massPlane)
return massPlane
def addAxesMap ( self, plane ):
""" add an axesMap entry. """
if "z" in str(plane):
return ## dont add 3d axes. we dont validate them.
if not hasattr ( self, "axesMap" ):
self.axesMap = []
if isinstance(plane,MassPlane):
import sympy
x,y,z,w=sympy.var("x y z w")
s = eval(str(plane))
if not s in self.axesMap:
self.axesMap.append ( s )
elif isinstance(plane,(list,dict)):
if not plane in self.axesMap:
self.axesMap.append ( plane )
elif isinstance(plane,str):
massArray = eval(plane)
if not massArray in self.axesMap:
self.axesMap.append ( massArray )
def addMassPlane(self, plane):
"""
add a MassPlane object with given axes to self.planes.
Add new attributes to the MassPlane.
:param txDecay: object of type TxDecay
:param plane: A MassPlane object or the full mass array containing
equations which relate the physical masses and the plane
coordinates, using the pre-defined 'x','y',.. symbols.
(e.g. [[x,y],[x,y]]).
:raise missingMassError: if one mass entry is missing
:raise onlyOnePlaneError: if a second mass plane is given and the related mass space
have only 2 dimensions
:raise interMediateParticleError: if a interMasses are given and the related
mass space
have only 2 dimensions
:return: MassPlane-object
"""
if type(plane)==list:
complainAbout["axesMap"]+=1
if complainAbout["axesMap"]<3:
logger.error ( f"skipping adding axesMap, hope it is ok, else fix in inputObjects!" )
if complainAbout["axesMap"]==3:
logger.error ( f"... " )
else:
self.addAxesMap ( plane )
if isinstance(plane,MassPlane):
self._planes.append(plane)
return plane
elif isinstance(plane,(list,dict)):
massArray = plane
elif isinstance(plane,str):
massArray = eval(plane)
else:
logger.error("Input must be a MassPlane object or a mass array")
sys.exit()
try:
element = ExpSMS.from_string(smsInStr(self.constraint)[0],
intermediateState=self.intermediateState,
finalState=self.finalState,
model = self._particles)
except Exception as e:
logger.error(str(e))
logger.error("Error building elements. Are the versions of smodels-utils and smodels compatible?")
sys.exit()
#Create mass plane for new input
if type(massArray)==dict:
massPlane = GraphMassPlane(self._txDecay,massArray)
else:
massPlane = MassPlane(self._txDecay,massArray)
self._planes.append(massPlane)
return massPlane
def nodeIndex2arrayIndex(self,nodeIndex,attr='mass'):
"""
Convert the node index to the corresponding entry (array index)
in the data grid array for the desired attribute.
:param nodeIndex: Index for the particle node in the constraint (i.e. anyBSM(nodeIndex))
:param attr: Attribute for which to convert the indices (i.e. mass or totalwidth)
"""
if not hasattr(self,'dataMap'):
logger.error("Can not convert indices if dataMap has not been defined!")
return None
# Create inverted dictionary:
if not hasattr(self,'_node2arrayDict'):
self._node2arrayDict = {}
if attr not in self._node2arrayDict:
self._node2arrayDict[attr] = {}
for iarray,(inode,nodeAttr,_) in self.dataMap.items():
if nodeAttr != attr:
continue
self._node2arrayDict[attr][inode] = iarray
if not nodeIndex in self._node2arrayDict[attr]:
logger.error(f"Node {nodeIndex} not found in dataMap for attribute {attr}!")
return False
return self._node2arrayDict[attr][nodeIndex]
def getDataFromPlanes(self,dataType):
"""
Loop over the defined planes and collects the data.
Reads the source file and stores the data.
Stores which planes have data for this txname in _goodPlanes.
:param dataType: Type of data (efficiencyMap or upperLimit)
"""
for plane in self._planes:
logger.info( f'Reading mass plane: {self}, {plane}' )
if dataType == 'upperLimit':
if not hasattr(plane,'upperLimits'):
logger.error( f'{dataType} source not defined for plane {plane}' )
sys.exit()
else:
if self.addDataFrom(plane,'upperLimits'):
self._dataLabels.append('upperLimits')
#Avoid adding the same plane twice
if not plane in self._goodPlanes:
self._goodPlanes.append(plane)
elif dataType == 'efficiencyMap':
if not hasattr(plane,'efficiencyMap'):
logger.info( f'{dataType} source not defined for plane {plane}' )
if not plane in self._goodPlanes:
self._goodPlanes.append(plane)
# sys.exit()
else:
if self.addDataFrom(plane,'efficiencyMap'):
self._dataLabels.append('efficiencyMap')
#Avoid adding the same plane twice
if not plane in self._goodPlanes:
self._goodPlanes.append(plane)
else:
logger.error( f'Unknown data type {dataType}' )
sys.exit()
#Add expected upper limits, if it exists:
if hasattr(plane,'expectedUpperLimits'):
if self.addDataFrom(plane,'expectedUpperLimits'):
self._dataLabels.append('expectedUpperLimits')
#Avoid adding the same plane twice
if not plane in self._goodPlanes:
self._goodPlanes.append(plane)
def getMetaData(self):
"""
Collects all the info attributes from its mass planes
(only for the planes which generated data and are stored
in _goodPlanes) and stores it in self.
Also defines additional information.
"""
for infoAttr in self.infoAttr:
infoList = [""]*len(self._goodPlanes)
planeHasInfo = False
for i,plane in enumerate(self._goodPlanes):
if not infoAttr in plane.infoAttr:
continue
doValidateIt=True
if infoAttr in [ "axes", "validationTarball", "xrange", "yrange" ]: