-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataHandlerObjects.py
More file actions
1792 lines (1584 loc) · 69.2 KB
/
dataHandlerObjects.py
File metadata and controls
1792 lines (1584 loc) · 69.2 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 python3
"""
.. module:: dataHandlerObjects
:synopsis: Holds objects for reading and processing the data in different formats
.. moduleauthor:: Michael Traub <michael.traub@gmx.at>
.. moduleauthor:: Andre Lessa <lessa.a.p@gmail.com>
"""
__all__ = [ "ExclusionHandler", "DataHandler" ]
import ctypes
import sys
import os
import logging
import math
import numpy as np
from typing import List, Generator
FORMAT = '%(levelname)s in %(module)s.%(funcName)s() in %(lineno)s: %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger(__name__)
from sympy import var
x,y,z = var('x y z')
# h = 4.135667662e-15 # in GeV * ns
hbar = 6.582119514e-16 # in GeV * ns
## for debugging, if set to true, allow for the acceptance files
## to have multiple entries for the same mass point. that is obviously a bug,
## so use this feature with great care
allowMultipleAcceptances = False
errorcounts = { "pathtupleerror": False, "smallerthanzero": False,
"wildcards": False, "trimyaxis": False, "trimxaxis": False,
"trimzaxis": False, "zerovalue": False }
suppressWarnings = { "objectname": False }
def _Hash ( lst ): ## simple hash function for our masses
ret=0.
for l in lst:
ret=100000*ret+l
return ret
# maximum number of entries before we trim
# (given that allowTrimming is true, see below)
max_nbins = 12000
allowTrimming=True ## allow big grids to be trimmed down
trimmingFactor = [ None ] ## the factor by which to trim, if none then determine automatically
fileCache = {} ## a file cache for input files, to speed things up
pointsCache = {}
class DataHandler(object):
"""
Iterable class
Super class used by other dataHandlerObjects.
Holds attributes for describing original data types and
methods to set the data source and preprocessing the data
"""
hasWarned = {}
def __init__(self,dataLabel,coordinateMap,xvars, txName = None ):
"""
initialize data-source attributes with None
and allowNegativeValues with False
:param name: name as string
:param dimensions: Dimensions of the data (e.g., for x,y,value, dimensions=2).
:param coordinateMap: A dictionary mapping the index of the variables
in the data and the corresponding x,y,.. coordinates used to define the
plane axes. (e.g. {x : 0, y : 1, 'ul value' : 2} for a 3-column data,
where x,y,.. are the sympy symbols and the value key can be anything)
:param xvars: List with x,y,.. variables (sympy symbols).
:param txName: the txname, for debugging only
"""
self.txName = txName
self.name = dataLabel
varsUsed = set()
for expr in xvars:
for i in [ "x", "y", "z" ]:
if i in str(expr):
varsUsed.add ( i )
self.dimensions = len(varsUsed)
self.coordinateMap = coordinateMap
self.xvars = xvars
# so we dont need to parse them so often
self.path = None
self.files = []
self.fileType = None
self.objectName = None
self.dataUrl = None
self.index = None
self.allowNegativeValues = False
self.dataset=None
self._massUnit = 'GeV'
self._unit = None #Default unit
self._rescaleFactors = None
if self.name == 'upperLimits' or self.name == 'expectedUpperLimits':
self._unit = 'pb'
newCoordinateMap = {} # take out entries with 'None'
for k,v in coordinateMap.items():
if v != None:
newCoordinateMap[k]=v
if len(coordinateMap) != self.dimensions+1 and \
len(newCoordinateMap) == self.dimensions+1:
coordinateMap = newCoordinateMap
nCoordinateMap = 0 ## determine length of coordinate map
for k,v in coordinateMap.items():
if k!="constraint":
nCoordinateMap+=1
#Consistency checks:
if nCoordinateMap != self.dimensions+1:
logger.error( f"Coordinate map {coordinateMap} (dim {nCoordinateMap}) is not consistent with number of dimensions ({self.dimensions+1}) in {dataLabel}" )
# sys.exit()
for xy in { "x": x, "y": y, "z": z }.items(): # allow also strings
if xy[0] in coordinateMap:
coordinateMap[xy[1]] = coordinateMap[xy[0]]
coordinateMap.pop ( xy[0] )
for xv in self.xvars:
if not xv in coordinateMap:
try:
fl = float(str(xv)) ## if we can cast, its all good
except ValueError as e:
if xv in [ x, y, z ]:
logger.error( f"Coordinate {xv}, {type(xv)} has not been defined in coordinateMap" )
logger.error ( f"Maybe you wrote '{xv}' instead of {xv} (i.e. a string instead of a sympy Symbol?)" )
# sys.exit()
@property
def unit(self):
"""
:return: unit as string
"""
return self._unit
@unit.setter
def unit(self, unitString):
"""
Set unit. For upper limits the default is 'pb'.
For efficiency map the default is None.
For exclusion lines it defines the units on the x and y axes.
:param unitString: 'fb','pb' or '', None
"""
if not unitString:
return
if "fficienc" in self.name:
if self.unit not in [ "%s", None, "perc", "percent", "percentage" ]:
logger.error("Units should not be defined for efficiency maps" )
sys.exit()
if unitString in [ "perc", "percent", "percentage" ]:
unitString = "%"
if unitString:
units = ['/10000','%','fb','pb',('GeV','GeV'),('GeV','ns'),('ns','GeV'),('GeV','X:60'), ( 'GeV','X:60','fb'), ( 'GeV','X:60','pb' ), ( 'GeV', 'ns', '/1' ), ( 'GeV', 'ns', '%' ), ( 'GeV', 'ns', '/10000' ) ]
if type(unitString) == str and unitString.startswith("/"):
self._unit = unitString
return
if type(unitString) == str and unitString.startswith("*"):
self._unit = unitString
return
if not unitString in units:
logger.error(f"Units must be in {str(units)}, not {unitString}" )
sys.exit()
self._unit = unitString
def loadData(self):
"""
Loads the data and stores it in the data attribute
"""
if not self.fileType:
logger.error( f"File type for {self.path} has not been defined" )
sys.exit()
if self.fileType == "csv" and type(self.path) == tuple:
if errorcounts["pathtupleerror"] == False:
print ( f"[dataHandlerObjects] warning: {self.path} is a tuple. will switch from csv to mcsv as your dataformat." )
errorcounts["pathtupleerror"] = True
self.fileType = "mcsv"
if self.fileType == "direct":
return
#Load data
self.data = []
strictlyPositive = False
if self._unit in [ "fb", "pb" ]:
strictlyPositive = True
if not hasattr ( self, self.fileType ):
logger.error ( f"Format type '{self.fileType}' is not defined. Try either one of 'root', 'csv', 'txt', 'embaked', 'mscv', 'effi', 'cMacro', 'canvas', 'svg', 'pdf', 'direct' instead. " )
sys.exit(-1)
for point in getattr(self,self.fileType)():
ptDict = self.mapPoint(point) #Convert point to dictionary
if self.allowNegativeValues:
self.data.append(ptDict)
#Check if the upper limit value is positive:
else:
#Just check floats in the point elements which are not variables
values = [value for xv,value in ptDict.items() if not xv in self.xvars]
if self._positiveValues(values, strictlyPositive = strictlyPositive ):
self.data.append(ptDict)
def __nonzero__(self):
"""
:returns: True if contains data
"""
if hasattr(self,'data') and len(self.data):
return True
return False
def __iter__(self):
"""
gives the entries of the original upper limit histograms
:yield: [x-value in GeV, y-value in GeV,..., value]
"""
for point in self.data:
yield point
def __getitem_(self,i):
"""
Returns the point located at i=x.
:param i: Integer specifying the point index.
:return: Point in dictionary format.
"""
return self.data[i]
def __len_(self):
"""
Returns the data length.
:return: Integer (length)
"""
return len(self.data)
def getX(self):
"""
Iterates over the x,y,.. values for the data
:yield: {x : x-value, y: y-value,...}
"""
for point in self.data:
xDict = {}
for key,val in point.items():
if not key in self.xvars:
continue
xDict[str(key)] = val
yield xDict
def getValues(self):
"""
Iterates over the values for the data (e.g. upper limit for upperLimits,
efficiency for efficiencyMap,...)
:yield: {'value-keyword' : value}
"""
for point in self.data:
vDict = {}
for key,val in point.items():
if key in self.xvars:
continue
vDict[str(key)] = val
yield vDict
def getPointsWith(self,**xvals):
"""
Returns point(s) with the properties defined by input.
(e.g. x=200., y=100., will return all points with these values)
:param xvals: Values for the variables (e.g. x=x-float, y=y-float,...)
:return: list of points which satisfy the requirements given by xvals.
"""
points = []
#Convert xvals from dictionary to sympy vars:
varDict = dict([[str(v),v] for v in self.xvars])
xv = dict([[eval(k,varDict),v] for k,v in xvals.items()])
for point in self.data:
addPoint = True
for key,val in xv.items():
if not key in point:
logger.error(f"Key {key} not allowed for data")
sys.exit()
if point[key] != val:
addPoint = False
break
if addPoint:
points.append(point)
return points
def reweightBy(self,data):
"""
Reweight the values in self by the values in data.
If data is a float, apply the same rescaling for all points.
If data is a DataHandler object, multiply the value for the points in self
by the values for the same points in data. Mainly intended to be
used to rescale efficiencies by acceptances or to rescale the whole data.
:param data: float or DataHandler object
"""
if isinstance(data,float):
for i,value in enumerate(self.getValues()):
factor = data
newvalue = dict([[key,val*factor] for key,val in value.items()])
self.data[i].update(newvalue)
elif isinstance(data,DataHandler):
for i,xvals in enumerate(self.getX()):
#Get the point in the data which matches the one in self
pts = data.getPointsWith(**xvals)
if pts and len(pts)>1 and allowMultipleAcceptances:
logger.error(f"More than one point in reweighting data matches point {xvals}")
logger.error("But allowMultipleAcceptances is set to true, so will choose first value!" )
pts = [ pts[0] ]
if not pts:
continue
elif len(pts) > 1:
logger.error(f"More than one point in reweighting data matches point {xvals}")
logger.error("(If you want to allow for this happen, then set dataHandlerObjects.allowMultipleAcceptances = True)" )
sys.exit()
else:
pt = pts[0]
oldpt = self.data[i] #Old point
for key,val in oldpt.items():
if str(key) in xvals.keys() or not key in pt:
continue
factor = pt[key]
oldpt[key] = oldpt[key]*factor #Rescale values which do not appear in xvals
self.data[i] = oldpt #Store rescaled point
def mapPoint(self,point):
"""
Convert a point in list format (e.g. [float,float,float])
to a dictionary using the definitions in self.coordinateMap
:param point: list with floats
:return: dictionary with coordinates and value
(e.g. {x : x-float, y : y-float, 'ul' : ul-float})
"""
if len(point) < self.dimensions: # +1:
logger.error(f"{self.name} should have at least {self.dimensions+1} dimensions ({len(point)} dimensions found)" )
sys.exit()
ptDict = {}
#Return a dictionary with the values:
for xvar,i in self.coordinateMap.items():
#Skip variables without indices (relevant for exclusion curves)
if i is None:
continue
if i >= len(point):
logger.error( f"asking for {i}th element of {point} in {self.path}")
logger.error( f"coordinate map is {self.coordinateMap}" )
ptDict[xvar] = point[i]
return ptDict
def setSource(self, path, fileType, objectName = None,
index = None, unit = None, scale = None, **args ):
"""set path and type of data source
:param path: path to data file as string
:param fileType: string describing type of file
name of every public method of child-class can be used
:param objectName: name of object stored in root-file or cMacro, or string
appearing in title of csv table in a multi-table csv file.
If it is a list, then the elements of the list get aggregated.
:param index: index of object in listOfPrimitives of ROOT.TCanvas
:param unit: string defining unit. If None, it will use the default values.
:param scale: float to re-scale the data.
"""
self.args = args
self.path = path
self.fileType = fileType
self.objectName = objectName
self.index = index
if fileType == "direct":
if type(path) in [ float, int ]: ## 1d exclusions can be given directly
self.data = [ [ path ] ]
elif type(path) in [ list ]:
self.data = [ path ]
else:
logger.error ( f"direct data source but cannot recognize data {path}" )
sys.exit()
elif type(path) not in [ tuple, list ] and not os.path.isfile(path):
logger.error( f"File {path} not found" )
if type(self.dataUrl ) == str and os.path.basename(path) == os.path.basename ( self.dataUrl ):
logger.info( "But you supplied a dataUrl with same basename, so I try to fetch it" )
import requests
r = requests.get ( self.dataUrl )
if not r.status_code == 200:
logger.error ( f"retrieval failed: {r.status_code}" )
sys.exit()
with open ( path, "wb" ) as f:
f.write ( r.content )
f.close()
else:
sys.exit()
if unit:
self.unit = unit
self.loadData()
if scale:
self.reweightBy(scale)
@property
def massUnit(self):
"""
:return: unit as string
"""
return self._massUnit
@massUnit.setter
def massUnit(self, unitString):
"""
Set unit for masses, default: 'GeV'.
If unitString is null, it will not set the property
:param unitString: 'GeV','TeV' or '', None
"""
if unitString:
units = ['GeV','TeV']
if not unitString in units:
logger.error(f'Mass units must be in {str(units)}')
sys.exit()
self._massUnit = unitString
def _positiveValues(self, values, strictlyPositive = False ):
"""checks if values greater then zero
:param value: float or integer
:param strictlyPositive: if true, then dont allow zeroes either
:return: True if value greater (or equals) 0 or allowNegativeValues == True
"""
if self.allowNegativeValues:
return True
for value in values:
if not isinstance ( value, ( np.floating, float, int, np.integer) ):
# if type(value) not in [ float, np.float64, int, np.int32, np.int64, np.int16, np.float32, np.float16 ]:
# print ( f"[dataHandlerObjects] value {value}, {type(value)} cannot be cast to float." )
if type(value) == str and "{" in value:
print ( "[dataHandlerObjects] did you try to parse an embaked file as a csv file maybe?" )
sys.exit(-1)
if type(value) in [ float ] and value < 0.0:
logger.warning(f"Negative value {value} in {self.path} will be ignored")
return False
if value == 0.0 and strictlyPositive:
if not errorcounts["zerovalue"]:
logger.warning(f"Zero value {value} in {self.path} will be ignored")
errorcounts["zerovalue"]=True
return False
return True
def txt(self):
"""
iterable method
preprocessing txt-files containing only columns with
floats
:yield: list with values as float, one float for every column
"""
txtFile = open(self.path,'r')
content = txtFile.readlines()
txtFile.close
lines = []
for line in content:
#print(line)
if line.find("#")>-1:
line=line[:line.find("#")]
if line=="":
continue
try:
values = line.split()
if values==[]:
continue
except:
logger.error(f"Error reading file {self.path}")
sys.exit()
values = [value.strip() for value in values]
try:
values = [float(value) for value in values]
except:
logger.error(f"Error evaluating values {values} in file {self.path}")
sys.exit()
lines.append ( values )
x,y = var('x y')
xcoord, ycoord = self.coordinateMap[x], self.coordinateMap[y]
## FIXME should we ever sort here?
# lines.sort( key= lambda x: x[xcoord]*1e6+x[ycoord] )
if len(lines) > max_nbins and trimmingFactor[0] == None:
trimmingFactor[0] = int ( round ( math.sqrt ( len(lines) / 6000. ) ) )
trimmingFactor[0] = trimmingFactor[0]**2
newyields = []
for cty,y in enumerate ( lines ):
if cty % trimmingFactor[0] == 0:
newyields.append ( y )
logger.warn ( f"trimmed down csv file '{self.name}' from {len(lines)} to {len(newyields)}" )
lines = newlines
for line in lines:
yield line
def pdf(self):
"""
iterable method
preprocessing pdf-files
floats
:yield: list with values as float, one float for every column
"""
from .PDFLimitReader import PDFLimitReader
if self.index == None or type(self.index) != str:
print ( "[dataHandlerObjects] index is None. For pdf files, use index to specify axis ranges, e.g. index='x[100,260];y[8,50];z[.1,100,true]'" )
sys.exit(-1)
tokens = self.index.split(";")
## boundaries in the plot!
lim = { "x": ( 150, 1200 ), "y": ( 0, 600 ), "z": ( 10**-3, 10**2 ) }
logz = True ## are the colors in log scale?
yIsDelta = False
for cttoken,token in enumerate(tokens):
axis = token[0]
lims = token[1:].replace("[","").replace("]","")
lims = lims.split(",")
hasMatched = False
if len(lims)>2:
if "delta" in lims[2].lower() and cttoken == 1:
yIsDelta = True
hasMatched = True
if lims[2].lower() in [ "log", "true" ]:
logz = True
hasMatched = True
elif lims[2].lower() in [ "false", "nolog" ]:
logz = False
hasMatched = True
if not hasMatched:
print ( f"Error: do not understand {lims[2]}. I expected log or nolog or delta (though I accept delta only in y coord)" )
lims = tuple ( map ( float, lims[:2] ) )
lim[axis]=lims
print(f"[dataHandlerObjects] limits {lim}" )
data = {
'name': self.path.replace(".pdf",""),
'x':{'limits': lim["x"]},
'y':{'limits': lim["y"]},
'z':{'limits': lim["z"], 'log':logz },
}
r = PDFLimitReader( data )
logger.warn ( "This is just a prototype of a PDF reader!" )
logger.warn ( f"{len(r.main_shapes)} shapes in pdf file." )
import numpy
data = []
lastz = float("inf")
dx = r.deltax
while dx < 15.:
dx = 2*dx
dy = r.deltay
while dy < 15.:
dy = 2*dy
for xi in numpy.arange ( lim["x"][0]+.5*r.deltax, lim["x"][1]+1e-6, dx ):
for yi in numpy.arange ( lim["y"][0]+.5*r.deltay, lim["y"][1]+1e-6, dy ):
if yi > xi:
continue
z = r.get_limit ( xi, yi )
if z == None:
continue
#if z == lastz:
# continue
# print ( "xyz", xi, yi, z )
if yIsDelta:
data.append ( ( xi, xi-yi, z ) )
else:
data.append ( ( xi, yi, z ) )
lastz = z
for d in data:
yield d
def extendDataToZero ( self, yields ):
""" if self.args['extended_to_massless_lsp'],
then extend the data to massless lsps """
# print ( "extend!", self.args )
if not "extend_to_massless_lsp" in self.args or \
self.args["extend_to_massless_lsp"] != True:
return
if self.name not in [ "expectedUpperLimits", "upperLimits" ]:
return
arr = np.array ( yields )[::,-2]
minLSP = min ( arr )
if minLSP > 25.:
# only do it when its not big
logger.warn ( f"will not extend to mlsp = 0 since minlsp = {minLSP}" )
return
add = []
for y in yields:
if abs(y[-2]-minLSP)<1e-6:
tmp = y[:-2]+[0]+y[-1:]
add.append ( tmp )
logger.info ( f"adding {len(add)} points to extend to mlsp=0" )
for a in add:
yields.append ( a )
yields.sort()
return
def direct(self):
""" value was given directly """
for d in self.data:
yield d
# return
def csv(self):
"""
iterable method
preprocessing csv-files
floats
:yield: list with values as float, one float for every column
"""
import csv
waitFor = None
if hasattr ( self, "objectName" ) and self.objectName is not None:
if not suppressWarnings["objectname"]:
print ( f"[dataHandlerObjects] warning, object name {self.objectName} supplied for an exclusion line. This is used to wait for a key word, not to give the object a name." )
waitFor = self.objectName
has_waited = False
if waitFor == None:
has_waited = True
yields = []
with open(self.path,'r', encoding = 'utf-8', errors='ignore' ) as csvfile:
reader = csv.reader(filter(lambda row: row[0]!='#', csvfile))
for r in reader:
if "@@EOF@@" in r:
break
if len(r)<1:
continue
hasLatexStuff=False
for _ in r:
if "\\tilde" in _: # sometimes its a latex line
hasLatexStuff = True
if "[GeV]" in _:
hasLatexStuff = True
if hasLatexStuff:
continue
if not has_waited:
for i in r:
if waitFor in i:
has_waited=True
continue
if r[0].startswith("'M(") or r[0].startswith("M("):
if waitFor !=None and not waitFor in r[0]:
#print ( "set back." )
has_waited = False
continue
fr = []
for i in r:
try:
fr.append ( float(i) )
except:
fr.append ( i )
if type ( self.unit) == tuple:
if self.unit[1]=="X:60":
frx = fr[0]*fr[1]+60.*( 1.-fr[1] )
fr[1]=frx
yields.append ( fr )
csvfile.close()
if len(yields) > max_nbins and trimmingFactor[0] == None:
trimmingFactor[0] = int ( round ( math.sqrt ( len(yields) / 6000. ) ) )
trimmingFactor[0] = trimmingFactor[0]**2
newyields = []
for cty,y in enumerate ( yields ):
if cty % trimmingFactor[0] == 0:
newyields.append ( y )
logger.warn ( f"trimmed down csv file '{self.name}' from {len(yields)} to {len(newyields)}" )
yields = newyields
# sort upper limits and efficiencies but not points in exclusion lines.
if "xclusion" in self.name:
xs,ys=[],[]
for yr in yields:
xs.append ( yr[0] )
if len(yr)>1:
ys.append ( yr[1] )
else:
try:
yields.sort()
except TypeError as e:
logger.error ( f"type error when sorting: {e}." )
culprits = ""
for lno,y in enumerate(yields):
for x in y:
if type(x) not in ( float, int ):
culprits += f"''{x}'' "
logger.error ( f"the culprits might be {culprits} in {self.path}" )
sys.exit()
values = [] # compute the final return values from these containers
for y in yields:
tmp = self.createEntryFromYield ( y )
if tmp != None:
values.append ( tmp )
self.extendDataToZero ( values )
for v in values:
## print ( "returning v", v, "coord map is", self.coordinateMap )
# print ( "name", self.index )
yield v
def createEntryFromYield ( self, yld : list ) -> list:
""" create a return line from a yield line """
ret = yld
if type ( self.index ) in [ list, tuple ]:
ret = []
for i in self.index:
ret.append ( yld[i] )
if type ( self.index ) in [ int ]:
if self.index >= len(yld):
print ( f"[dataHandlerObjects] too high index {self.index} for {yr} in {self.path}" )
sys.exit()
ret = yld[:self.dimensions] + [ yld[self.index] ]
if type ( self.index ) in [ str ]:
if "constraint" in self.coordinateMap:
if yld[self.coordinateMap["constraint"]] != self.index:
ret = None
return ret
def mcsv(self):
"""
iterable method
preprocessing multiple csv-files, and multiplying the last values
floats
:yield: list with values as float, one float for every column
"""
ret = 1.
npaths = []
keys = set()
for ctr,p in enumerate(self.path):
path = {}
ret = list( self.csvForPath( p ) )
for point in ret:
key = tuple(point[:-1])
hasLatexStuff = False
for k in key:
if type(k) == str and "\\tilde" in k:
hasLatexStuff = True
if type(k) == str and "$" in k:
hasLatexStuff = True
if hasLatexStuff:
continue
keys.add ( key )
path[key] = point[-1]
npaths.append ( path )
for k in keys:
ret = 1.
for p in npaths:
if not k in p.keys():
logger.error ( "it seems that point %s is not in all paths? in %s" % \
(str(k), self.path ) )
break
if type(p[k]) in [ str ]:
logger.warning ( f"skipping value {p[k]} as it is a string" )
continue
ret = ret * p[k]
y = list(k)+[ret]
if ret < 0.:
ret = 0.
if errorcounts["smallerthanzero"] == False:
errorcounts["smallerthanzero"] = True
logger.warning ( f"found value of {ret} in {self.path} -- you sure you want that?" )
#if ret > 0.:
yield y
def csvForPath ( self, path ):
""" a csv file but giving the path """
import csv
waitFor = None
if hasattr ( self, "objectName" ) and self.objectName is not None:
print ( f"[dataHandlerObjects] warning, object name {self.objectName} supplied for an exclusion line. This is used to wait for a key word, not to give the object a name." )
waitFor = self.objectName
has_waited = False
if waitFor == None:
has_waited = True
if "*" in path or "?" in path:
import glob
tmp = glob.glob ( path )
if len(tmp)==1:
if not errorcounts["wildcards"]:
print ( f"[dataHandlerObjects] wildcards in filename: {path}. they are unique. use them." )
errorcounts["wildcards"]=True
path = tmp[0]
else:
print ( f"[dataHandlerObjects] wildcards in filename. they are not unique, found {len(tmp)} matches for {path}. fix it!" )
sys.exit(-1)
with open( path,'r') as csvfile:
reader = csv.reader(filter(lambda row: row[0]!='#', csvfile))
for r in reader:
if len(r)<2:
continue
#print ( "line >>%s<< hw=%s, waitFor=>>%s<<" % ( r, has_waited, waitFor ) )
if not has_waited:
for i in r:
if waitFor in i:
has_waited=True
continue
if r[0].startswith("'M(") or r[0].startswith("M("):
if waitFor !=None and not waitFor in r[0]:
#print ( "set back." )
has_waited = False
continue
fr = []
for i in r:
try:
fr.append ( float(i) )
except:
fr.append ( i )
if type ( self.unit) == tuple:
if self.unit[1]=="X:60":
frx = fr[0]*fr[1]+60.*( 1.-fr[1] )
fr[1]=frx
yield fr
csvfile.close()
def embaked(self) -> List:
"""
iterable method
preprocessing python dictionaries as defined by the em bakery
floats
:yield: list with values as float, one float for every column
"""
SR = self.objectName
D = None
if self.path in fileCache:
D = fileCache[self.path]
else:
try:
with open(self.path) as f:
print ( f"[dataHandler] reading {self.path} searching for {SR}" )
D=eval(f.read())
fileCache[self.path]=D
except Exception as e:
logger.error ( f"could not read {self.path}: {e}" )
sys.exit(-1)
keys = list(D.keys() )
keys.sort()
for pt in keys:
values = D[pt]
vkeys = values.keys()
newentries = {}
for vkey in vkeys:
## awkward hack to make sure we allow for e.g. "SR1" and "SR1_MET...."
if vkey.startswith ( "SR" ) and vkey.find("_")>1:
sr = vkey [ : vkey.find("_") ]
newentries[sr] = values [ vkey ]
values.update ( newentries )
ret = list(pt)
eff = 0.
if type(SR) in [ list, tuple ]:
for sr in SR:
if sr in values.keys():
eff += values[sr]
elif SR in values.keys():
eff = values[SR]
ret += [ eff ]
yield ret
def effi(self):
"""
iterable method
preprocessing txt-files containing fastlim efficiency maps
(only columns with floats)
:yield: list with values as float, one float for every column
"""
txtFile = open(self.path,'r')
content = txtFile.readlines()
txtFile.close
for line in content:
#Ignore lines which start with a letter
if line.strip()[:1].isalpha():
continue
#print(line)
if line.find("#")>-1:
line=line[:line.find("#")]
if line=="":
continue
try:
values = line.split()
if values==[]:
continue
except:
logger.error(f"Error reading file {self.path}")
sys.exit()
values = [value.strip() for value in values]
try:
values = [float(value) for value in values]
except:
logger.error(f"Error evaluating values {values} in file {self.path}")
sys.exit()
if values[-2]<4*values[-1]:
logger.debug(f"Small efficiency value {values[-2]} +- {values[-1]}. Setting to zero.")
values[-2]= 0.0
print ( "value", values )
yield values
def root(self):
"""
preprocessing root-files containing root-objects
:return: ROOT-object
"""
if isinstance(self.objectName, (list,tuple) ):
# we can write tuples, list or <name>+<name>
name = "+".join ( self.objectName )
return self.rootByName ( name )
if isinstance(self.objectName, str):
return self.rootByName ( self.objectName )
logger.error ( "objectName must be a string or a list" )
sys.exit()
def uprootByName(self, name : str ) -> List:
""" generator of entries for UL and EM maps,
retrieving from root files using uproot. we know the objects name
in the root file
:param name: the name of the object in the root file. if a "+" is in
this name, we assume it's two objects and we concatenate.
"""
import uproot
if "+" in name:
names = name.split("+")
for name in names:
ret = self.uprootByName ( name )
for i in ret:
yield i
# print ( "[dataHandlerObjects] using uproot on", self.path )
rootFile = uproot.open(self.path)
obj = rootFile.get(name)
# self.interact()
if not obj:
logger.error( f"Object {name} not found in {self.path}" )
sys.exit()
points = list ( self._getUpRootPoints(obj) )
self.extendDataToZero ( points )
for point in points:
yield point
rootFile.close()
def rootByName ( self, name ):
try:
import uproot
return self.uprootByName ( name )
except Exception as e: