Package madgraph :: Package various :: Module systematics
[hide private]
[frames] | no frames]

Source Code for Module madgraph.various.systematics

  1  ################################################################################ 
  2  # 
  3  # Copyright (c) 2016 The MadGraph5_aMC@NLO Development team and Contributors 
  4  # 
  5  # This file is a part of the MadGraph5_aMC@NLO project, an application which  
  6  # automatically generates Feynman diagrams and matrix elements for arbitrary 
  7  # high-energy processes in the Standard Model and beyond. 
  8  # 
  9  # It is subject to the MadGraph5_aMC@NLO license which should accompany this  
 10  # distribution. 
 11  # 
 12  # For more information, visit madgraph.phys.ucl.ac.be and amcatnlo.web.cern.ch 
 13  # 
 14  ################################################################################ 
 15  from __future__ import division 
 16  if __name__ == "__main__": 
 17      import sys 
 18      import os 
 19      root = os.path.dirname(__file__) 
 20      if os.path.basename(root) == 'internal': 
 21          sys.path.append(os.path.dirname(root)) 
 22      else: 
 23          sys.path.append(os.path.dirname(os.path.dirname(root))) 
 24           
 25  import lhe_parser 
 26  import banner 
 27  import banner as banner_mod 
 28  import itertools 
 29  import misc 
 30  import math 
 31  import os  
 32  import re 
 33  import sys 
 34  import time 
 35  import StringIO 
 36   
 37  pjoin = os.path.join 
 38   
39 -class SystematicsError(Exception):
40 pass
41
42 -class Systematics(object):
43
44 - def __init__(self, input_file, output_file, 45 start_event=0, stop_event=sys.maxint, write_banner=False, 46 mur=[0.5,1,2], 47 muf=[0.5,1,2], 48 alps=[1], 49 pdf='errorset', #[(id, subset)] 50 dyn=[-1,1,2,3,4], 51 together=[('mur', 'muf', 'dyn')], 52 lhapdf_config=misc.which('lhapdf-config'), 53 log=lambda x: sys.stdout.write(str(x)+'\n') 54 ):
55 56 # INPUT/OUTPUT FILE 57 if isinstance(input_file, str): 58 self.input = lhe_parser.EventFile(input_file) 59 else: 60 self.input = input_file 61 self.output_path = output_file 62 if output_file != None: 63 if isinstance(output_file, str): 64 if output_file == input_file: 65 directory,name = os.path.split(output_file) 66 new_name = pjoin(directory, '.tmp_'+name) 67 self.output = lhe_parser.EventFile(new_name, 'w') 68 else: 69 self.output = lhe_parser.EventFile(output_file, 'w') 70 else: 71 self.output = output_file 72 self.log = log 73 74 #get some information from the run_card. 75 self.banner = banner_mod.Banner(self.input.banner) 76 self.force_write_banner = bool(write_banner) 77 self.orig_dyn = self.banner.get('run_card', 'dynamical_scale_choice') 78 self.orig_pdf = self.banner.run_card.get_lhapdf_id() 79 80 #check for beam 81 beam1, beam2 = self.banner.get_pdg_beam() 82 if abs(beam1) != 2212 and abs(beam2) != 2212: 83 self.b1 = 0 84 self.b2 = 0 85 pdf = 'central' 86 #raise SystematicsError, 'can only reweight proton beam' 87 elif abs(beam1) != 2212: 88 self.b1 = 0 89 self.b2 = beam2//2212 90 elif abs(beam2) != 2212: 91 self.b1 = beam1//2212 92 self.b2 = 0 93 else: 94 self.b1 = beam1//2212 95 self.b2 = beam2//2212 96 97 if isinstance(self.banner.run_card, banner_mod.RunCardLO): 98 self.is_lo = True 99 if not self.banner.run_card['use_syst']: 100 raise SystematicsError, 'The events have not been generated with use_syst=True. Cannot evaluate systematics error on these events.' 101 else: 102 self.is_lo = False 103 if not self.banner.run_card['store_rwgt_info']: 104 raise SystematicsError, 'The events have not been generated with store_rwgt_info=True. Cannot evaluate systematics error on these events.' 105 106 # MUR/MUF/ALPS PARSING 107 if isinstance(mur, str): 108 mur = mur.split(',') 109 self.mur=[float(i) for i in mur] 110 if isinstance(muf, str): 111 muf = muf.split(',') 112 self.muf=[float(i) for i in muf] 113 114 if isinstance(alps, str): 115 alps = alps.split(',') 116 self.alps=[float(i) for i in alps] 117 118 # DYNAMICAL SCALE PARSING + together 119 if isinstance(dyn, str): 120 dyn = dyn.split(',') 121 self.dyn=[int(i) for i in dyn] 122 123 if isinstance(together, str): 124 self.together = together.split(',') 125 else: 126 self.together = together 127 128 # START/STOP EVENT 129 self.start_event=int(start_event) 130 self.stop_event=int(stop_event) 131 if start_event != 0: 132 self.log( "#starting from event #%s" % start_event) 133 if stop_event != sys.maxint: 134 self.log( "#stopping at event #%s" % stop_event) 135 136 # LHAPDF set 137 if isinstance(lhapdf_config, list): 138 lhapdf_config = lhapdf_config[0] 139 lhapdf = misc.import_python_lhapdf(lhapdf_config) 140 if not lhapdf: 141 return 142 lhapdf.setVerbosity(0) 143 self.pdfsets = {} 144 if isinstance(pdf, str): 145 pdf = pdf.split(',') 146 147 if isinstance(pdf,list) and isinstance(pdf[0],(str,int)): 148 self.pdf = [] 149 for data in pdf: 150 if data == 'errorset': 151 data = '%s' % self.orig_pdf 152 if data == 'central': 153 data = '%s@0' % self.orig_pdf 154 if '@' in data: 155 #one particular dataset 156 name, arg = data.rsplit('@',1) 157 if int(arg) == 0: 158 if name.isdigit(): 159 self.pdf.append(lhapdf.mkPDF(int(name))) 160 else: 161 self.pdf.append(lhapdf.mkPDF(name)) 162 elif name.isdigit(): 163 try: 164 self.pdf.append(lhapdf.mkPDF(int(name)+int(arg))) 165 except: 166 raise Exception, 'Individual error sets need to be called with LHAPDF NAME not with LHAGLUE NUMBER' 167 else: 168 self.pdf.append(lhapdf.mkPDF(name, int(arg))) 169 else: 170 if data.isdigit(): 171 pdfset = lhapdf.mkPDF(int(data)).set() 172 else: 173 pdfset = lhapdf.mkPDF(data).set() 174 self.pdfsets[pdfset.lhapdfID] = pdfset 175 self.pdf += pdfset.mkPDFs() 176 else: 177 self.pdf = pdf 178 179 for p in self.pdf: 180 if p.lhapdfID == self.orig_pdf: 181 self.orig_pdf = p 182 break 183 else: 184 self.orig_pdf = lhapdf.mkPDF(self.orig_pdf) 185 if not self.b1 == 0 == self.b2: 186 self.log( "# events generated with PDF: %s (%s)" %(self.orig_pdf.set().name,self.orig_pdf.lhapdfID )) 187 # create all the function that need to be called 188 self.get_all_fct() # define self.fcts and self.args 189 190 # For e+/e- type of collision initialise the running of alps 191 if self.b1 == 0 == self.b2: 192 try: 193 from models.model_reader import Alphas_Runner 194 except ImportError: 195 root_path = pjoin(root, os.pardir, os.pardir) 196 try: 197 import internal.madevent_interface as me_int 198 cmd = me_int.MadEventCmd(root_path,force_run=True) 199 except ImportError: 200 import internal.amcnlo_run_interface as me_int 201 cmd = me_int.Cmd(root_path,force_run=True) 202 if 'mg5_path' in cmd.options and cmd.options['mg5_path']: 203 sys.path.append(cmd.options['mg5_path']) 204 from models.model_reader import Alphas_Runner 205 206 if not hasattr(self.banner, 'param_card'): 207 param_card = self.banner.charge_card('param_card') 208 else: 209 param_card = self.banner.param_card 210 211 asmz = param_card.get_value('sminputs', 3, 0.13) 212 nloop =2 213 zmass = param_card.get_value('mass', 23, 91.188) 214 cmass = param_card.get_value('mass', 4, 1.4) 215 if cmass == 0: 216 cmass = 1.4 217 bmass = param_card.get_value('mass', 5, 4.7) 218 if bmass == 0: 219 bmass = 4.7 220 self.alpsrunner = Alphas_Runner(asmz, nloop, zmass, cmass, bmass)
221 222
223 - def run(self, stdout=sys.stdout):
224 """ """ 225 start_time = time.time() 226 if self.start_event == 0 or self.force_write_banner: 227 lowest_id = self.write_banner(self.output) 228 else: 229 lowest_id = self.get_id() 230 231 ids = [lowest_id+i for i in range(len(self.args)-1)] 232 all_cross = [0 for i in range(len(self.args))] 233 234 for nb_event,event in enumerate(self.input): 235 if nb_event < self.start_event: 236 continue 237 elif nb_event >= self.stop_event: 238 if self.force_write_banner: 239 self.output.write('</LesHouchesEvents>\n') 240 break 241 if self.is_lo: 242 if (nb_event-self.start_event)>=0 and (nb_event-self.start_event) % 2500 ==0: 243 self.log( '# currently at event %s [elapsed time: %.2g s]' % (nb_event, time.time()-start_time)) 244 else: 245 if (nb_event-self.start_event)>=0 and (nb_event-self.start_event) % 1000 ==0: 246 self.log( '# currently at event %i [elapsed time: %.2g s]' % (nb_event, time.time()-start_time)) 247 248 self.new_event() #re-init the caching of alphas/pdf 249 if self.is_lo: 250 wgts = [self.get_lo_wgt(event, *arg) for arg in self.args] 251 else: 252 wgts = [self.get_nlo_wgt(event, *arg) for arg in self.args] 253 254 if wgts[0] == 0: 255 print wgts 256 print event 257 raise Exception 258 259 wgt = [event.wgt*wgts[i]/wgts[0] for i in range(1,len(wgts))] 260 all_cross = [(all_cross[j] + event.wgt*wgts[j]/wgts[0]) for j in range(len(wgts))] 261 262 rwgt_data = event.parse_reweight() 263 rwgt_data.update(zip(ids, wgt)) 264 event.reweight_order += ids 265 # order the 266 self.output.write(str(event)) 267 else: 268 self.output.write('</LesHouchesEvents>\n') 269 self.output.close() 270 self.print_cross_sections(all_cross, min(nb_event,self.stop_event)-self.start_event+1, stdout) 271 272 if self.output.name != self.output_path: 273 import shutil 274 shutil.move(self.output.name, self.output_path) 275 276 return all_cross
277
278 - def print_cross_sections(self, all_cross, nb_event, stdout):
279 """print the cross-section.""" 280 281 norm = self.banner.get('run_card', 'event_norm', default='sum') 282 #print "normalisation is ", norm 283 #print "nb_event is ", nb_event 284 285 max_scale, min_scale = 0,sys.maxint 286 max_alps, min_alps = 0, sys.maxint 287 max_dyn, min_dyn = 0,sys.maxint 288 pdfs = {} 289 dyns = {} # dyn : {'max': , 'min':} 290 291 if norm == 'sum': 292 norm = 1 293 elif norm == 'average': 294 norm = 1./nb_event 295 elif norm == 'unity': 296 norm = 1 297 298 all_cross = [c*norm for c in all_cross] 299 stdout.write("# mur\t\tmuf\t\talpsfact\tdynamical_scale\tpdf\t\tcross-section\n") 300 for i,arg in enumerate(self.args): 301 302 to_print = list(arg) 303 to_print[4] = to_print[4].lhapdfID 304 to_print.append(all_cross[i]) 305 to_report = [] 306 stdout.write('%s\t\t%s\t\t%s\t\t%s\t\t%s\t\t%s\n' % tuple(to_print)) 307 308 mur, muf, alps, dyn, pdf = arg[:5] 309 if pdf == self.orig_pdf and (dyn==self.orig_dyn or dyn==-1)\ 310 and (mur!=1 or muf!=1 or alps!=1): 311 max_scale = max(max_scale,all_cross[i]) 312 min_scale = min(min_scale,all_cross[i]) 313 if pdf == self.orig_pdf and mur==1 and muf==1 and \ 314 (dyn==self.orig_dyn or dyn==-1) and alps!=1: 315 max_alps = max(max_alps,all_cross[i]) 316 min_alps = min(min_alps,all_cross[i]) 317 318 if pdf == self.orig_pdf and mur==1 and muf==1 and alps==1: 319 max_dyn = max(max_dyn,all_cross[i]) 320 min_dyn = min(min_dyn,all_cross[i]) 321 322 if pdf == self.orig_pdf and (alps!=1 or mur!=1 or muf!=1) and \ 323 (dyn!=self.orig_dyn or dyn!=-1): 324 if dyn not in dyns: 325 dyns[dyn] = {'max':0, 'min':sys.maxint,'central':0} 326 curr = dyns[dyn] 327 curr['max'] = max(curr['max'],all_cross[i]) 328 curr['min'] = min(curr['min'],all_cross[i]) 329 if pdf == self.orig_pdf and (alps==1 and mur==1 and muf==1) and \ 330 (dyn!=self.orig_dyn or dyn!=-1): 331 if dyn not in dyns: 332 dyns[dyn] = {'max':0, 'min':sys.maxint,'central':all_cross[i]} 333 else: 334 dyns[dyn]['central'] = all_cross[i] 335 336 if alps==1 and mur==1 and muf==1 and (dyn==self.orig_dyn or dyn==-1): 337 pdfset = pdf.set() 338 if pdfset.lhapdfID in self.pdfsets: 339 if pdfset.lhapdfID not in pdfs : 340 pdfs[pdfset.lhapdfID] = [0] * pdfset.size 341 pdfs[pdfset.lhapdfID][pdf.memberID] = all_cross[i] 342 else: 343 to_report.append('# PDF %s : %s\n' % (pdf.lhapdfID, all_cross[i])) 344 345 stdout.write('\n') 346 347 resume = StringIO.StringIO() 348 349 resume.write( '#***************************************************************************\n') 350 resume.write( "#\n") 351 resume.write( '# original cross-section: %s\n' % all_cross[0]) 352 if max_scale: 353 resume.write( '# scale variation: +%2.3g%% -%2.3g%%\n' % ((max_scale-all_cross[0])/all_cross[0]*100,(all_cross[0]-min_scale)/all_cross[0]*100)) 354 if max_alps: 355 resume.write( '# emission scale variation: +%2.3g%% -%2.3g%%\n' % ((max_alps-all_cross[0])/all_cross[0]*100,(max_alps-min_scale)/all_cross[0]*100)) 356 if max_dyn and (max_dyn!= all_cross[0] or min_dyn != all_cross[0]): 357 resume.write( '# central scheme variation: +%2.3g%% -%2.3g%%\n' % ((max_dyn-all_cross[0])/all_cross[0]*100,(all_cross[0]-min_dyn)/all_cross[0]*100)) 358 if self.orig_pdf.lhapdfID in pdfs: 359 lhapdfid = self.orig_pdf.lhapdfID 360 values = pdfs[lhapdfid] 361 pdfset = self.pdfsets[lhapdfid] 362 pdferr = pdfset.uncertainty(values) 363 resume.write( '# PDF variation: +%2.3g%% -%2.3g%%\n' % (pdferr.errplus*100/all_cross[0], pdferr.errminus*100/all_cross[0])) 364 # report error/central not directly linked to the central 365 resume.write( "#\n") 366 for lhapdfid,values in pdfs.items(): 367 if lhapdfid == self.orig_pdf.lhapdfID: 368 continue 369 if len(values) == 1 : 370 continue 371 pdfset = self.pdfsets[lhapdfid] 372 373 if pdfset.errorType == 'unknown' : 374 # Don't know how to determine uncertainty for 'unknown' errorType : 375 # File "lhapdf.pyx", line 329, in lhapdf.PDFSet.uncertainty (lhapdf.cpp:6621) 376 # RuntimeError: "ErrorType: unknown" not supported by LHAPDF::PDFSet::uncertainty. 377 continue 378 pdferr = pdfset.uncertainty(values) 379 resume.write( '#PDF %s: %g +%2.3g%% -%2.3g%%\n' % (pdfset.name, pdferr.central,pdferr.errplus*100/all_cross[0], pdferr.errminus*100/all_cross[0])) 380 381 dyn_name = {1: '\sum ET', 2:'\sum\sqrt{m^2+pt^2}', 3:'0.5 \sum\sqrt{m^2+pt^2}',4:'\sqrt{\hat s}' } 382 for key, curr in dyns.items(): 383 if key ==-1: 384 continue 385 central, maxvalue, minvalue = curr['central'], curr['max'], curr['min'] 386 if central == 0: 387 continue 388 if maxvalue == 0: 389 resume.write("# dynamical scheme # %s : %g # %s\n" %(key, central, dyn_name[key])) 390 else: 391 resume.write("# dynamical scheme # %s : %g +%2.3g%% -%2.3g%% # %s\n" %(key, central, (maxvalue-central)/central*100,(central-minvalue)/central*100, dyn_name[key])) 392 393 resume.write('\n'.join(to_report)) 394 395 resume.write( '#***************************************************************************\n') 396 397 stdout.write(resume.getvalue()) 398 self.log(resume.getvalue())
399 400
401 - def write_banner(self, fsock):
402 """create the new banner with the information of the weight""" 403 404 cid = self.get_id() 405 lowest_id = cid 406 407 in_scale = False 408 in_pdf = False 409 in_alps = False 410 411 text = '' 412 413 default = self.args[0] 414 for arg in self.args[1:]: 415 mur, muf, alps, dyn, pdf = arg[:5] 416 if pdf == self.orig_pdf and alps ==1 and (mur!=1 or muf!=1 or dyn!=-1): 417 if not in_scale: 418 text += "<weightgroup name=\"Central scale variation\" combine=\"envelope\">\n" 419 in_scale=True 420 elif in_scale: 421 if (pdf == self.orig_pdf and alps ==1) and arg != default: 422 pass 423 else: 424 text += "</weightgroup> # scale\n" 425 in_scale = False 426 427 if pdf == self.orig_pdf and mur == muf == 1 and dyn==-1 and alps!=1: 428 if not in_alps: 429 text += "<weightgroup name=\"Emission scale variation\" combine=\"envelope\">\n" 430 in_alps=True 431 elif in_alps: 432 text += "</weightgroup> # ALPS\n" 433 in_alps=False 434 435 if mur == muf == 1 and dyn==-1 and alps ==1: 436 if pdf.lhapdfID < 0: 437 for central,sets in self.pdfsets.items(): 438 if pdf in sets.set(): 439 misc.sprint(central) 440 441 if pdf.lhapdfID in self.pdfsets: 442 if in_pdf: 443 text += "</weightgroup> # PDFSET -> PDFSET\n" 444 pdfset = self.pdfsets[pdf.lhapdfID] 445 descrip = pdfset.description.replace('=>',';').replace('>','.gt.').replace('<','.lt.') 446 text +="<weightgroup name=\"%s\" combine=\"%s\"> # %s: %s\n" %\ 447 (pdfset.name, pdfset.errorType,pdfset.lhapdfID, descrip) 448 in_pdf=pdf.lhapdfID 449 elif pdf.memberID == 0 and (pdf.lhapdfID - pdf.memberID) in self.pdfsets: 450 if in_pdf: 451 text += "</weightgroup> # PDFSET -> PDFSET\n" 452 pdfset = self.pdfsets[pdf.lhapdfID - 1] 453 descrip = pdfset.description.replace('=>',';').replace('>','.gt.').replace('<','.lt.') 454 text +="<weightgroup name=\"%s\" combine=\"%s\"> # %s: %s\n" %\ 455 (pdfset.name, pdfset.errorType,pdfset.lhapdfID, descrip) 456 in_pdf=pdfset.lhapdfID 457 elif in_pdf and pdf.lhapdfID - pdf.memberID != in_pdf: 458 misc.sprint(pdf.lhapdfID) 459 text += "</weightgroup> # PDFSET -> PDF\n" 460 in_pdf = False 461 elif in_pdf: 462 text += "</weightgroup> PDF \n" 463 in_pdf=False 464 465 466 467 tag, info = '','' 468 if mur!=1.: 469 tag += 'MUR="%s" ' % mur 470 info += 'MUR=%s ' % mur 471 else: 472 tag += 'MUR="%s" ' % mur 473 if muf!=1.: 474 tag += 'MUF="%s" ' % muf 475 info += 'MUF=%s ' % muf 476 else: 477 tag += 'MUF="%s" ' % muf 478 479 if alps!=1.: 480 tag += 'ALPSFACT="%s" ' % alps 481 info += 'alpsfact=%s ' % alps 482 if dyn!=-1.: 483 tag += 'DYN_SCALE="%s" ' % dyn 484 info += 'dyn_scale_choice=%s ' % {1:'sum pt', 2:'HT',3:'HT/2',4:'sqrts'}[dyn] 485 486 if pdf != self.orig_pdf: 487 tag += 'PDF="%s" ' % pdf.lhapdfID 488 info += 'PDF=%s MemberID=%s' % (pdf.lhapdfID-pdf.memberID, pdf.memberID) 489 else: 490 tag += 'PDF="%s" ' % pdf.lhapdfID 491 492 text +='<weight id="%s" %s> %s </weight>\n' % (cid, tag, info) 493 cid+=1 494 495 if in_scale or in_alps or in_pdf: 496 text += "</weightgroup>\n" 497 498 if 'initrwgt' in self.banner: 499 self.banner['initrwgt'] += text 500 else: 501 self.banner['initrwgt'] = text 502 503 504 self.banner.write(self.output, close_tag=False) 505 506 return lowest_id
507 508
509 - def get_id(self):
510 511 if 'initrwgt' in self.banner: 512 pattern = re.compile('<weight id=(?:\'|\")([_\w]+)(?:\'|\")', re.S+re.I+re.M) 513 return max([int(wid) for wid in pattern.findall(self.banner['initrwgt']) if wid.isdigit()])+1 514 else: 515 return 1
516 517 518 519
520 - def get_all_fct(self):
521 522 all_args = [] 523 default = [1.,1.,1.,-1,self.orig_pdf] 524 #all_args.append(default) 525 pos = {'mur':0, 'muf':1, 'alps':2, 'dyn':3, 'pdf':4} 526 done = set() 527 for one_block in self.together: 528 for name in one_block: 529 done.add(name) 530 for together in itertools.product(*[getattr(self,name) for name in one_block]): 531 new_args = list(default) 532 for name,value in zip(one_block, together): 533 new_args[pos[name]] = value 534 all_args.append(new_args) 535 for name in pos: 536 if name in done: 537 continue 538 for value in getattr(self, name): 539 new_args = list(default) 540 new_args[pos[name]] = value 541 all_args.append(new_args) 542 543 self.args = [default] + [arg for arg in all_args if arg!= default] 544 545 # add the default before the pdf scan to have a full grouping 546 pdfplusone = [pdf for pdf in self.pdf if pdf.lhapdfID == self.orig_pdf.lhapdfID+1] 547 if pdfplusone: 548 pdfplusone = default[:-1] + [pdfplusone[0]] 549 index = self.args.index(pdfplusone) 550 self.args.insert(index, default) 551 552 self.log( "#Will Compute %s weights per event." % (len(self.args)-1)) 553 return
554
555 - def new_event(self):
556 self.alphas = {} 557 self.pdfQ2 = {}
558 559
560 - def get_pdfQ(self, pdf, pdg, x, scale):
561 562 if pdg in [-21,-22]: 563 pdg = abs(pdg) 564 elif pdg == 0: 565 return 1 566 567 f = pdf.xfxQ(pdg, x, scale)/x 568 # if f == 0 and pdf.memberID ==0: 569 # pdfset = pdf.set() 570 # allnumber= [p.xfxQ(pdg, x, scale) for p in pdfset.mkPDFs()] 571 # f = pdfset.uncertainty(allnumber).central /x 572 return f
573
574 - def get_pdfQ2(self, pdf, pdg, x, scale):
575 576 if pdg in [-21,-22]: 577 pdg = abs(pdg) 578 elif pdg == 0: 579 return 1 580 581 if (pdf, pdg,x,scale) in self.pdfQ2: 582 return self.pdfQ2[(pdf, pdg,x,scale)] 583 f = pdf.xfxQ2(pdg, x, scale)/x 584 self.pdfQ2[(pdf, pdg,x,scale)] = f 585 return f 586 587 #one method to handle the nnpd2.3 problem -> now just move to central 588 if f == 0 and pdf.memberID ==0: 589 # to avoid problem with nnpdf2.3 in lhapdf6.1.6 590 #print 'central pdf returns 0', pdg, x, scale 591 #print self.pdfsets 592 pdfset = pdf.set() 593 allnumber= [0] + [self.get_pdfQ2(p, pdg, x, scale) for p in pdfset.mkPDFs()[1:]] 594 f = pdfset.uncertainty(allnumber).central 595 self.pdfQ2[(pdf, pdg,x,scale)] = f 596 return f
597
598 - def get_lo_wgt(self,event, Dmur, Dmuf, Dalps, dyn, pdf):
599 """ 600 pdf is a lhapdf object!""" 601 602 loinfo = event.parse_lo_weight() 603 604 if dyn == -1: 605 mur = loinfo['ren_scale'] 606 muf1 = loinfo['pdf_q1'][-1] 607 muf2 = loinfo['pdf_q2'][-1] 608 else: 609 if dyn == 1: 610 mur = event.get_et_scale(1.) 611 elif dyn == 2: 612 mur = event.get_ht_scale(1.) 613 elif dyn == 3: 614 mur = event.get_ht_scale(0.5) 615 elif dyn == 4: 616 mur = event.get_sqrts_scale(1.) 617 muf1 = mur 618 muf2 = mur 619 loinfo = dict(loinfo) 620 loinfo['pdf_q1'] = loinfo['pdf_q1'] [:-1] + [mur] 621 loinfo['pdf_q2'] = loinfo['pdf_q2'] [:-1] + [mur] 622 623 624 625 # MUR part 626 if self.b1 == 0 == self.b2: 627 if loinfo['n_qcd'] != 0: 628 wgt = self.alpsrunner(Dmur*mur)**loinfo['n_qcd'] 629 else: 630 wgt = 1.0 631 else: 632 wgt = pdf.alphasQ(Dmur*mur)**loinfo['n_qcd'] 633 # MUF/PDF part 634 wgt *= self.get_pdfQ(pdf, self.b1*loinfo['pdf_pdg_code1'][-1], loinfo['pdf_x1'][-1], Dmuf*muf1) 635 wgt *= self.get_pdfQ(pdf, self.b2*loinfo['pdf_pdg_code2'][-1], loinfo['pdf_x2'][-1], Dmuf*muf2) 636 637 for scale in loinfo['asrwt']: 638 if self.b1 == 0 == self.b2: 639 wgt = self.alpsrunner(Dalps*scale) 640 else: 641 wgt *= pdf.alphasQ(Dalps*scale) 642 643 # ALS part 644 for i in range(loinfo['n_pdfrw1']-1): 645 scale = min(Dalps*loinfo['pdf_q1'][i], Dmuf*muf1) 646 wgt *= self.get_pdfQ(pdf, self.b1*loinfo['pdf_pdg_code1'][i], loinfo['pdf_x1'][i], scale) 647 wgt /= self.get_pdfQ(pdf, self.b1*loinfo['pdf_pdg_code1'][i], loinfo['pdf_x1'][i+1], scale) 648 649 for i in range(loinfo['n_pdfrw2']-1): 650 scale = min(Dalps*loinfo['pdf_q2'][i], Dmuf*muf2) 651 wgt *= self.get_pdfQ(pdf, self.b2*loinfo['pdf_pdg_code2'][i], loinfo['pdf_x2'][i], scale) 652 wgt /= self.get_pdfQ(pdf, self.b2*loinfo['pdf_pdg_code2'][i], loinfo['pdf_x2'][i+1], scale) 653 654 return wgt
655
656 - def get_nlo_wgt(self,event, Dmur, Dmuf, Dalps, dyn, pdf):
657 """return the new weight for NLO event --with weight information-- """ 658 659 wgt = 0 660 nloinfo = event.parse_nlo_weight(real_type=(1,11,12,13)) 661 for cevent in nloinfo.cevents: 662 if dyn == 1: 663 mur2 = cevent.get_et_scale(1.)**2 664 elif dyn == 2: 665 mur2 = cevent.get_ht_scale(1.)**2 666 elif dyn == 3: 667 mur2 = cevent.get_ht_scale(0.5)**2 668 elif dyn == 4: 669 mur2 = cevent.get_sqrts_scale(event,1)**2 670 else: 671 mur2 = 0 672 muf2 = mur2 673 674 for onewgt in cevent.wgts: 675 if not __debug__ and (dyn== -1 and Dmur==1 and Dmuf==1 and pdf==self.orig_pdf): 676 wgt += onewgt.ref_wgt 677 678 if dyn == -1: 679 mur2 = onewgt.scales2[1] 680 muf2 = onewgt.scales2[2] 681 Q2 = onewgt.scales2[0] # Ellis-Sexton scale 682 683 wgtpdf = self.get_pdfQ2(pdf, self.b1*onewgt.pdgs[0], onewgt.bjks[0], 684 Dmuf**2 * muf2) 685 wgtpdf *= self.get_pdfQ2(pdf, self.b2*onewgt.pdgs[1], onewgt.bjks[1], 686 Dmuf**2 * muf2) 687 688 tmp = onewgt.pwgt[0] 689 tmp += onewgt.pwgt[1] * math.log(Dmur**2 * mur2/ Q2) 690 tmp += onewgt.pwgt[2] * math.log(Dmuf**2 * muf2/ Q2) 691 692 if self.b1 == 0 == self.b2: 693 alps = self.alpsrunner(Dmur*math.sqrt(mur2)) 694 else: 695 alps = pdf.alphasQ2(Dmur**2*mur2) 696 697 tmp *= math.sqrt(4*math.pi*alps)**onewgt.qcdpower 698 699 if wgtpdf == 0: #happens for nn23pdf due to wrong set in lhapdf 700 key = (self.b1*onewgt.pdgs[0], self.b2*onewgt.pdgs[1], onewgt.bjks[0],onewgt.bjks[1], muf2) 701 if dyn== -1 and Dmuf==1 and Dmur==1 and pdf==self.orig_pdf: 702 wgtpdf = onewgt.ref_wgt / tmp 703 self.pdfQ2[key] = wgtpdf 704 elif key in self.pdfQ2: 705 wgtpdf = self.pdfQ2[key] 706 else: 707 # real zero! 708 wgtpdf = 0 709 710 tmp *= wgtpdf 711 wgt += tmp 712 713 if __debug__ and dyn== -1 and Dmur==1 and Dmuf==1 and pdf==self.orig_pdf: 714 if not misc.equal(tmp, onewgt.ref_wgt, sig_fig=2): 715 misc.sprint(tmp, onewgt.ref_wgt, (tmp-onewgt.ref_wgt)/tmp) 716 misc.sprint(onewgt) 717 misc.sprint(cevent) 718 misc.sprint(mur2,muf2) 719 raise Exception, 'not enough agreement between stored value and computed one' 720 721 722 return wgt
723 724
725 -def call_systematics(args, result=sys.stdout, running=True, 726 log=lambda x:sys.stdout.write(str(x)+'\n')):
727 """calling systematics from a list of arguments""" 728 729 input, output = args[0:2] 730 opts = {} 731 for arg in args[2:]: 732 if '=' in arg: 733 key,values= arg.split('=') 734 key = key.replace('-','') 735 values = values.strip() 736 if values[0] in ["'",'"'] and values[-1]==values[0]: 737 values = values[1:-1] 738 values = values.split(',') 739 if key == 'together': 740 if key in opts: 741 opts[key].append(tuple(values)) 742 else: 743 opts[key]=[tuple(values)] 744 elif key == 'result': 745 result = open(values[0],'w') 746 elif key in ['start_event', 'stop_event']: 747 opts[key] = int(values[0]) 748 elif key == 'write_banner': 749 opts[key] = banner_mod.ConfigFile.format_variable(values[0], bool, 'write_banner') 750 else: 751 if key in opts: 752 opts[key] += values 753 else: 754 opts[key] = values 755 else: 756 raise SystematicsError, "unknow argument %s" % arg 757 758 #load run_card and extract parameter if needed. 759 if 'from_card' in opts: 760 if opts['from_card'] != ['internal']: 761 card = banner.RunCard(opts['from_card'][0]) 762 else: 763 for i in range(10): 764 try: 765 lhe = lhe_parser.EventFile(input) 766 break 767 except OSError,error: 768 print error 769 time.sleep(15*(i+1)) 770 else: 771 raise 772 773 card = banner.RunCard(banner.Banner(lhe.banner)['mgruncard']) 774 lhe.close() 775 776 if isinstance(card, banner.RunCardLO): 777 # LO case 778 opts['mur'] = [float(x) for x in card['sys_scalefact'].split()] 779 opts['muf'] = opts['mur'] 780 if card['sys_alpsfact'] != 'None': 781 opts['alps'] = [float(x) for x in card['sys_alpsfact'].split()] 782 else: 783 opts['alps'] = [1.0] 784 opts['together'] = [('mur','muf','alps','dyn')] 785 if '&&' in card['sys_pdf']: 786 pdfs = card['sys_pdf'].split('&&') 787 else: 788 data = card['sys_pdf'].split() 789 pdfs = [] 790 for d in data: 791 if not d.isdigit(): 792 pdfs.append(d) 793 elif int(d) > 500: 794 pdfs.append(d) 795 else: 796 pdfs[-1] = '%s %s' % (pdfs[-1], d) 797 798 opts['dyn'] = [-1,1,2,3,4] 799 opts['pdf'] = [] 800 for pdf in pdfs: 801 split = pdf.split() 802 if len(split)==1: 803 opts['pdf'].append('%s' %pdf) 804 else: 805 pdf,nb = split 806 for i in range(int(nb)): 807 opts['pdf'].append('%s@%s' % (pdf, i)) 808 if not opts['pdf']: 809 opts['pdf'] = 'central' 810 else: 811 #NLO case 812 raise Exception 813 del opts['from_card'] 814 815 816 obj = Systematics(input, output, log=log,**opts) 817 if running: 818 obj.run(result) 819 return obj
820 821 if __name__ == "__main__": 822 sys_args = sys.argv[1:] 823 for i, arg in enumerate(sys_args) : 824 if arg.startswith('--lhapdf_config=') : 825 lhapdf = misc.import_python_lhapdf(arg[len('--lhapdf_config='):]) 826 del sys_args[i] 827 break 828 829 if 'lhapdf' not in globals(): 830 lhapdf = misc.import_python_lhapdf('lhapdf-config') 831 832 if not lhapdf: 833 sys.exit('Can not run systematics since can not link python to lhapdf, specify --lhapdf-config=') 834 call_systematics(sys_args) 835