00001 import re
00002 from sys import stderr
00003
00004 globalNuisances = re.compile('(lumi|pdf_(qqbar|gg|qg)|QCDscale_(ggH|qqH|VH|ggH1in|ggH2in|VV)|UEPS|FakeRate|CMS_(eff|fake|trigger|scale|res)_([gemtjb]|met))')
00005
00006 def addDatacardParserOptions(parser):
00007 parser.add_option("-s", "--stat", dest="stat", default=False, action="store_true", help="keep only statistical uncertainties, no systematics")
00008 parser.add_option("-f", "--fix-pars", dest="fixpars",default=False, action="store_true", help="fix all floating parameters of the pdfs except for the POI")
00009 parser.add_option("-c", "--compiled", dest="cexpr", default=False, action="store_true", help="use compiled expressions (not suggested)")
00010 parser.add_option("-a", "--ascii", dest="bin", default=True, action="store_false", help="produce a Workspace in a rootfile in an HLF file (legacy, unsupported)")
00011 parser.add_option("-b", "--binary", dest="bin", default=True, action="store_true", help="produce a Workspace in a rootfile (default)")
00012 parser.add_option("-o", "--out", dest="out", default=None, type="string", help="output file (if none, it will print to stdout). Required for binary mode.")
00013 parser.add_option("-v", "--verbose", dest="verbose", default=0, type="int", help="Verbosity level (0 = quiet, 1 = verbose, 2+ = more)")
00014 parser.add_option("-m", "--mass", dest="mass", default=0, type="float", help="Higgs mass to use. Will also be written in the Workspace as RooRealVar 'MH'.")
00015 parser.add_option("-D", "--dataset", dest="dataname", default="data_obs", type="string", help="Name of the observed dataset")
00016 parser.add_option("-L", "--LoadLibrary", dest="libs", type="string" , action="append", help="Load these libraries")
00017 parser.add_option("--poisson", dest="poisson", default=0, type="int", help="If set to a positive number, binned datasets wih more than this number of entries will be generated using poissonians")
00018 parser.add_option("--default-morphing", dest="defMorph", type="string", default="shape2N", help="Default template morphing algorithm (to be used when the datacard has just 'shape')")
00019 parser.add_option("--X-exclude-nuisance", dest="nuisancesToExclude", type="string", action="append", default=[], help="Exclude nuisances that match these regular expressions.")
00020 parser.add_option("--X-force-simpdf", dest="forceSimPdf", default=False, action="store_true", help="FOR DEBUG ONLY: Always produce a RooSimultaneous, even for single channels.")
00021 parser.add_option("--X-no-check-norm", dest="noCheckNorm", default=False, action="store_true", help="FOR DEBUG ONLY: Turn off the consistency check between datacard norms and shape norms. Will give you nonsensical results if you have shape uncertainties.")
00022 parser.add_option("--X-no-jmax", dest="noJMax", default=False, action="store_true", help="FOR DEBUG ONLY: Turn off the consistency check between jmax and number of processes.")
00023
00024
00025 class Datacard():
00026 def __init__(self):
00027 self.bins = []
00028 self.obs = []
00029 self.processes = []; self.signals = []; self.isSignal = {}
00030 self.keyline = []
00031 self.exp = {}
00032 self.systs = []
00033
00034 self.shapeMap = {}
00035 self.hasShape = False
00036 self.flatParamNuisances = {}
00037
00038 def isVetoed(name,vetoList):
00039 for pattern in vetoList:
00040 if not pattern: continue
00041 if re.match(pattern,name): return True
00042 return False
00043
00044 def parseCard(file, options):
00045 if type(file) == type("str"):
00046 raise RuntimeError, "You should pass as argument to parseCards a file object, stream or a list of lines, not a string"
00047 ret = Datacard()
00048
00049 nbins = -1;
00050 nprocesses = -1;
00051 nuisances = -1;
00052 binline = []; processline = []; sigline = []
00053 for l in file:
00054 f = l.split();
00055 if len(f) < 1: continue
00056 if f[0] == "imax":
00057 nbins = int(f[1]) if f[1] != "*" else -1
00058 if f[0] == "jmax":
00059 nprocesses = int(f[1])+1 if f[1] != "*" else -1
00060 if f[0] == "kmax":
00061 nuisances = int(f[1]) if f[1] != "*" else -1
00062 if f[0] == "shapes":
00063 if not options.bin: raise RuntimeError, "Can use shapes only with binary output mode"
00064 if len(f) < 4: raise RuntimeError, "Malformed shapes line"
00065 if not ret.shapeMap.has_key(f[2]): ret.shapeMap[f[2]] = {}
00066 if ret.shapeMap[f[2]].has_key(f[1]): raise RuntimeError, "Duplicate definition for process '%s', channel '%s'" % (f[1], f[2])
00067 ret.shapeMap[f[2]][f[1]] = f[3:]
00068 if f[0] == "Observation" or f[0] == "observation":
00069 ret.obs = [ float(x) for x in f[1:] ]
00070 if nbins == -1: nbins = len(ret.obs)
00071 if len(ret.obs) != nbins: raise RuntimeError, "Found %d observations but %d bins have been declared" % (len(ret.obs), nbins)
00072 if binline != []:
00073 if len(binline) != len(ret.obs): raise RuntimeError, "Found %d bins (%s) but %d bins have been declared" % (len(ret.bins), ret.bins, nbins)
00074 ret.bins = binline
00075 ret.obs = dict([(b,ret.obs[i]) for i,b in enumerate(ret.bins)])
00076 binline = []
00077 if f[0] == "bin":
00078 binline = []
00079 for b in f[1:]:
00080 if re.match("[0-9]+", b): b = "bin"+b
00081 binline.append(b)
00082 if f[0] == "process":
00083 if processline == []:
00084 processline = f[1:]
00085 if len(binline) != len(processline): raise RuntimeError, "'bin' line has a different length than 'process' line."
00086 continue
00087 sigline = f[1:]
00088 if re.match("-?[0-9]+", processline[0]) and not re.match("-?[0-9]+", sigline[0]):
00089 (processline,sigline) = (sigline,processline)
00090 if len(sigline) != len(processline): raise RuntimeError, "'bin' line has a different length than 'process' line."
00091 hadBins = (len(ret.bins) > 0)
00092 for i,b in enumerate(binline):
00093 p = processline[i];
00094 s = (int(sigline[i]) <= 0)
00095 ret.keyline.append((b, processline[i], s))
00096 if hadBins:
00097 if b not in ret.bins: raise RuntimeError, "Bin %s not among the declared bins %s" % (b, ret.bins)
00098 else:
00099 if b not in ret.bins: ret.bins.append(b)
00100 if p not in ret.processes: ret.processes.append(p)
00101 if nprocesses == -1: nprocesses = len(ret.processes)
00102 if nbins == -1: nbins = len(ret.bins)
00103 if not options.noJMax:
00104 if nprocesses != len(ret.processes): raise RuntimeError, "Found %d processes (%s), declared jmax = %d" % (len(ret.processes),ret.processes,nprocesses)
00105 if nbins != len(ret.bins): raise RuntimeError, "Found %d bins (%s), declared imax = %d" % (len(ret.bins),ret.bins,nbins)
00106 ret.exp = dict([(b,{}) for b in ret.bins])
00107 ret.isSignal = dict([(p,None) for p in ret.processes])
00108 if ret.obs != [] and type(ret.obs) == list:
00109 ret.obs = dict([(b,ret.obs[i]) for i,b in enumerate(ret.bins)])
00110 for (b,p,s) in ret.keyline:
00111 if ret.isSignal[p] == None:
00112 ret.isSignal[p] = s
00113 elif ret.isSignal[p] != s:
00114 raise RuntimeError, "Process %s is declared as signal in some bin and as background in some other bin" % p
00115 ret.signals = [p for p,s in ret.isSignal.items() if s == True]
00116 if len(ret.signals) == 0: raise RuntimeError, "You must have at least one signal process (id <= 0)"
00117 if f[0] == "rate":
00118 if processline == []: raise RuntimeError, "Missing line with process names before rate line"
00119 if sigline == []: raise RuntimeError, "Missing line with process id before rate line"
00120 if len(f[1:]) != len(ret.keyline): raise RuntimeError, "Malformed rate line: length %d, while bins and process lines have length %d" % (len(f[1:]), len(ret.keyline))
00121 for (b,p,s),r in zip(ret.keyline,f[1:]):
00122 ret.exp[b][p] = float(r)
00123 break
00124
00125 for l in file:
00126 if l.startswith("--"): continue
00127 l = re.sub("\\s*#.*","",l)
00128 l = re.sub("(?<=\\s)-+(\\s|$)"," 0\\1",l);
00129 f = l.split();
00130 if len(f) <= 1: continue
00131 nofloat = False
00132 lsyst = f[0]; pdf = f[1]; args = []; numbers = f[2:];
00133 if lsyst.endswith("[nofloat]"):
00134 lsyst = lsyst.replace("[nofloat]","")
00135 nofloat = True
00136 if options.nuisancesToExclude and isVetoed(lsyst, options.nuisancesToExclude):
00137 if options.verbose > 0: stderr.write("Excluding nuisance %s selected by a veto pattern among %s\n" % (lsyst, options.nuisancesToExclude))
00138 if nuisances != -1: nuisances -= 1
00139 continue
00140 if re.match("[0-9]+",lsyst): lsyst = "theta"+lsyst
00141 if pdf == "lnN" or pdf == "lnU" or pdf == "gmM" or pdf == "trG" or pdf.startswith("shape"):
00142 pass
00143 elif pdf == "gmN":
00144 args = [int(f[2])]; numbers = f[3:];
00145 elif pdf == "unif":
00146 args = [float(f[2]), float(f[3])]; numbers = f[4:];
00147 elif pdf == "param":
00148
00149
00150 args = f[2:]
00151 if len(args) <= 1: raise RuntimeError, "Uncertainties of type 'param' must have at least two arguments (mean and sigma)"
00152 ret.systs.append([lsyst,nofloat,pdf,args,[]])
00153 continue
00154 elif pdf == "flatParam":
00155 ret.flatParamNuisances[lsyst] = True
00156
00157 continue
00158 else:
00159 raise RuntimeError, "Unsupported pdf %s" % pdf
00160 if len(numbers) < len(ret.keyline): raise RuntimeError, "Malformed systematics line %s of length %d: while bins and process lines have length %d" % (lsyst, len(numbers), len(ret.keyline))
00161 errline = dict([(b,{}) for b in ret.bins])
00162 nonNullEntries = 0
00163 for (b,p,s),r in zip(ret.keyline,numbers):
00164 if "/" in r:
00165 if (pdf not in ["lnN","lnU"]) and ("?" not in pdf): raise RuntimeError, "Asymmetric errors are allowed only for Log-normals"
00166 errline[b][p] = [ float(x) for x in r.split("/") ]
00167 else:
00168 errline[b][p] = float(r)
00169
00170 if pdf == "gmN" and ret.exp[b][p] == 0 and float(r) != 0: ret.exp[b][p] = 1e-6
00171 ret.systs.append([lsyst,nofloat,pdf,args,errline])
00172
00173 for b in ret.bins:
00174 np_bin = sum([(ret.exp[b][p] != 0) for (b1,p,s) in ret.keyline if b1 == b])
00175 ns_bin = sum([(ret.exp[b][p] != 0) for (b1,p,s) in ret.keyline if b1 == b and s == True])
00176 nb_bin = sum([(ret.exp[b][p] != 0) for (b1,p,s) in ret.keyline if b1 == b and s != True])
00177 if np_bin == 0: raise RuntimeError, "Bin %s has no processes contributing to it" % b
00178 if ns_bin == 0: raise RuntimeError, "Bin %s has no signal processes contributing to it" % b
00179 if nb_bin == 0: raise RuntimeError, "Bin %s has no background processes contributing to it" % b
00180
00181 syst2 = []
00182 for lsyst,nofloat,pdf,args,errline in ret.systs:
00183 nonNullEntries = 0
00184 if pdf == "param":
00185 syst2.append((lsyst,nofloat,pdf,args,errline))
00186 continue
00187 for (b,p,s) in ret.keyline:
00188 r = errline[b][p]
00189 nullEffect = (r == 0.0 or (pdf == "lnN" and r == 1.0))
00190 if not nullEffect and ret.exp[b][p] != 0: nonNullEntries += 1
00191 if nonNullEntries != 0: syst2.append((lsyst,nofloat,pdf,args,errline))
00192 elif nuisances != -1: nuisances -= 1
00193 ret.systs = syst2
00194
00195 if options.stat:
00196 nuisances = 0
00197 ret.systs = []
00198
00199 if nuisances == -1:
00200 nuisances = len(ret.systs)
00201 elif len(ret.systs) != nuisances:
00202 raise RuntimeError, "Found %d systematics, expected %d" % (len(ret.systs), nuisances)
00203
00204 ret.hasShapes = (len(ret.shapeMap) > 0)
00205
00206 return ret