1
2
3
4
5
6
7
8
9
10
11
12
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
41
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',
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
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
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
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
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
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
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
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
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
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
188 self.get_all_fct()
189
190
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()
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
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
279 """print the cross-section."""
280
281 norm = self.banner.get('run_card', 'event_norm', default='sum')
282
283
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 = {}
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
365 resume.write( "#\n")
366 for lhapdfid,values in pdfs.items():
367 if lhapdfid == self.orig_pdf.lhapdfID:
368 continue
369 pdfset = self.pdfsets[lhapdfid]
370 pdferr = pdfset.uncertainty(values)
371 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]))
372
373 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}' }
374 for key, curr in dyns.items():
375 if key ==-1:
376 continue
377 central, maxvalue, minvalue = curr['central'], curr['max'], curr['min']
378 if central == 0:
379 continue
380 if maxvalue == 0:
381 resume.write("# dynamical scheme # %s : %g # %s\n" %(key, central, dyn_name[key]))
382 else:
383 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]))
384
385 resume.write('\n'.join(to_report))
386
387 resume.write( '#***************************************************************************\n')
388
389 stdout.write(resume.getvalue())
390 self.log(resume.getvalue())
391
392
394 """create the new banner with the information of the weight"""
395
396 cid = self.get_id()
397 lowest_id = cid
398
399 in_scale = False
400 in_pdf = False
401 in_alps = False
402
403 text = ''
404
405 for arg in self.args[1:]:
406 mur, muf, alps, dyn, pdf = arg[:5]
407 if pdf == self.orig_pdf and alps ==1 and (mur!=1 or muf!=1 or dyn!=-1):
408 if not in_scale:
409 text += "<weightgroup name=\"Central scale variation\" combine=\"envelope\">\n"
410 in_scale=True
411 elif in_scale:
412 if (pdf == self.orig_pdf and alps ==1):
413 pass
414 else:
415 text += "</weightgroup> # scale\n"
416 in_scale = False
417
418 if pdf == self.orig_pdf and mur == muf == 1 and dyn==-1 and alps!=1:
419 if not in_alps:
420 text += "<weightgroup name=\"Emission scale variation\" combine=\"envelope\">\n"
421 in_alps=True
422 elif in_alps:
423 text += "</weightgroup> # ALPS\n"
424 in_alps=False
425
426 if pdf != self.orig_pdf and mur == muf == 1 and dyn==-1 and alps ==1:
427 if pdf.lhapdfID in self.pdfsets:
428 if in_pdf:
429 text += "</weightgroup> # PDFSET -> PDFSET\n"
430 pdfset = self.pdfsets[pdf.lhapdfID]
431 descrip = pdfset.description.replace('=>',';').replace('>','.gt.').replace('<','.lt.')
432 text +="<weightgroup name=\"%s\" combine=\"%s\"> # %s: %s\n" %\
433 (pdfset.name, pdfset.errorType,pdfset.lhapdfID, descrip)
434 in_pdf=pdf.lhapdfID
435 elif pdf.memberID == 1 and (pdf.lhapdfID - pdf.memberID) in self.pdfsets:
436 if in_pdf:
437 text += "</weightgroup> # PDFSET -> PDFSET\n"
438 pdfset = self.pdfsets[pdf.lhapdfID - 1]
439 descrip = pdfset.description.replace('=>',';').replace('>','.gt.').replace('<','.lt.')
440 text +="<weightgroup name=\"%s\" combine=\"%s\"> # %s: %s\n" %\
441 (pdfset.name, pdfset.errorType,pdfset.lhapdfID, descrip)
442 in_pdf=pdfset.lhapdfID
443 elif in_pdf and pdf.lhapdfID - pdf.memberID != in_pdf:
444 text += "</weightgroup> # PDFSET -> PDF\n"
445 in_pdf = False
446 elif in_pdf:
447 text += "</weightgroup> PDF \n"
448 in_pdf=False
449
450
451
452 tag, info = '',''
453 if mur!=1.:
454 tag += 'MUR="%s" ' % mur
455 info += 'MUR=%s ' % mur
456 else:
457 tag += 'MUR="%s" ' % mur
458 if muf!=1.:
459 tag += 'MUF="%s" ' % muf
460 info += 'MUF=%s ' % muf
461 else:
462 tag += 'MUF="%s" ' % muf
463
464 if alps!=1.:
465 tag += 'ALPSFACT="%s" ' % alps
466 info += 'alpsfact=%s ' % alps
467 if dyn!=-1.:
468 tag += 'DYN_SCALE="%s" ' % dyn
469 info += 'dyn_scale_choice=%s ' % {1:'sum pt', 2:'HT',3:'HT/2',4:'sqrts'}[dyn]
470
471 if pdf != self.orig_pdf:
472 tag += 'PDF="%s" ' % pdf.lhapdfID
473 info += 'PDF=%s MemberID=%s' % (pdf.lhapdfID-pdf.memberID, pdf.memberID)
474 else:
475 tag += 'PDF="%s" ' % pdf.lhapdfID
476
477 text +='<weight id="%s" %s> %s </weight>\n' % (cid, tag, info)
478 cid+=1
479
480 if in_scale or in_alps or in_pdf:
481 text += "</weightgroup>\n"
482
483 if 'initrwgt' in self.banner:
484 self.banner['initrwgt'] += text
485 else:
486 self.banner['initrwgt'] = text
487
488
489 self.banner.write(self.output, close_tag=False)
490
491 return lowest_id
492
493
495
496 if 'initrwgt' in self.banner:
497 pattern = re.compile('<weight id=(?:\'|\")([_\w]+)(?:\'|\")', re.S+re.I+re.M)
498 return max([int(wid) for wid in pattern.findall(self.banner['initrwgt']) if wid.isdigit()])+1
499 else:
500 return 1
501
502
503
504
506
507 all_args = []
508 default = [1.,1.,1.,-1,self.orig_pdf]
509
510 pos = {'mur':0, 'muf':1, 'alps':2, 'dyn':3, 'pdf':4}
511 done = set()
512 for one_block in self.together:
513 for name in one_block:
514 done.add(name)
515 for together in itertools.product(*[getattr(self,name) for name in one_block]):
516 new_args = list(default)
517 for name,value in zip(one_block, together):
518 new_args[pos[name]] = value
519 all_args.append(new_args)
520 for name in pos:
521 if name in done:
522 continue
523 for value in getattr(self, name):
524 new_args = list(default)
525 new_args[pos[name]] = value
526 all_args.append(new_args)
527
528 self.args = [default]+ [arg for arg in all_args if arg!= default]
529
530 self.log( "#Will Compute %s weights per event." % (len(self.args)-1))
531 return
532
534 self.alphas = {}
535 self.pdfQ2 = {}
536
537
538 - def get_pdfQ(self, pdf, pdg, x, scale):
539
540 if pdg in [-21,-22]:
541 pdg = abs(pdg)
542 elif pdg == 0:
543 return 1
544
545 f = pdf.xfxQ(pdg, x, scale)/x
546
547
548
549
550 return f
551
553
554 if pdg in [-21,-22]:
555 pdg = abs(pdg)
556 elif pdg == 0:
557 return 1
558
559 if (pdf, pdg,x,scale) in self.pdfQ2:
560 return self.pdfQ2[(pdf, pdg,x,scale)]
561 f = pdf.xfxQ2(pdg, x, scale)/x
562 self.pdfQ2[(pdf, pdg,x,scale)] = f
563 return f
564
565
566 if f == 0 and pdf.memberID ==0:
567
568
569
570 pdfset = pdf.set()
571 allnumber= [0] + [self.get_pdfQ2(p, pdg, x, scale) for p in pdfset.mkPDFs()[1:]]
572 f = pdfset.uncertainty(allnumber).central
573 self.pdfQ2[(pdf, pdg,x,scale)] = f
574 return f
575
576 - def get_lo_wgt(self,event, Dmur, Dmuf, Dalps, dyn, pdf):
577 """
578 pdf is a lhapdf object!"""
579
580 loinfo = event.parse_lo_weight()
581
582 if dyn == -1:
583 mur = loinfo['ren_scale']
584 muf1 = loinfo['pdf_q1'][-1]
585 muf2 = loinfo['pdf_q2'][-1]
586 else:
587 if dyn == 1:
588 mur = event.get_et_scale(1.)
589 elif dyn == 2:
590 mur = event.get_ht_scale(1.)
591 elif dyn == 3:
592 mur = event.get_ht_scale(0.5)
593 elif dyn == 4:
594 mur = event.get_sqrts_scale(1.)
595 muf1 = mur
596 muf2 = mur
597 loinfo['pdf_q1'][-1] = mur
598 loinfo['pdf_q2'][-1] = mur
599
600
601
602
603 if self.b1 == 0 == self.b2:
604 wgt = self.alpsrunner(Dmur*mur)**loinfo['n_qcd']
605 else:
606 wgt = pdf.alphasQ(Dmur*mur)**loinfo['n_qcd']
607
608 wgt *= self.get_pdfQ(pdf, self.b1*loinfo['pdf_pdg_code1'][-1], loinfo['pdf_x1'][-1], Dmuf*muf1)
609 wgt *= self.get_pdfQ(pdf, self.b2*loinfo['pdf_pdg_code2'][-1], loinfo['pdf_x2'][-1], Dmuf*muf2)
610
611 for scale in loinfo['asrwt']:
612 if self.b1 == 0 == self.b2:
613 wgt = self.alpsrunner(Dalps*scale)
614 else:
615 wgt *= pdf.alphasQ(Dalps*scale)
616
617
618 for i in range(loinfo['n_pdfrw1']-1):
619 scale = min(Dalps*loinfo['pdf_q1'][i], Dmuf*muf1)
620 wgt *= self.get_pdfQ(pdf, self.b1*loinfo['pdf_pdg_code1'][i], loinfo['pdf_x1'][i], scale)
621 wgt /= self.get_pdfQ(pdf, self.b1*loinfo['pdf_pdg_code1'][i], loinfo['pdf_x1'][i+1], scale)
622
623 for i in range(loinfo['n_pdfrw2']-1):
624 scale = min(Dalps*loinfo['pdf_q2'][i], Dmuf*muf2)
625 wgt *= self.get_pdfQ(pdf, self.b2*loinfo['pdf_pdg_code2'][i], loinfo['pdf_x2'][i], scale)
626 wgt /= self.get_pdfQ(pdf, self.b2*loinfo['pdf_pdg_code2'][i], loinfo['pdf_x2'][i+1], scale)
627
628 return wgt
629
630 - def get_nlo_wgt(self,event, Dmur, Dmuf, Dalps, dyn, pdf):
631 """return the new weight for NLO event --with weight information-- """
632
633 wgt = 0
634 nloinfo = event.parse_nlo_weight(real_type=(1,11,12,13))
635 for cevent in nloinfo.cevents:
636 if dyn == 1:
637 mur2 = cevent.get_et_scale(1.)**2
638 elif dyn == 2:
639 mur2 = cevent.get_ht_scale(1.)**2
640 elif dyn == 3:
641 mur2 = cevent.get_ht_scale(0.5)**2
642 elif dyn == 4:
643 mur2 = cevent.get_sqrts_scale(event,1)**2
644 else:
645 mur2 = 0
646 muf2 = mur2
647
648 for onewgt in cevent.wgts:
649 if not __debug__ and (dyn== -1 and Dmur==1 and Dmuf==1 and pdf==self.orig_pdf):
650 wgt += onewgt.ref_wgt
651
652 if dyn == -1:
653 mur2 = onewgt.scales2[1]
654 muf2 = onewgt.scales2[2]
655 Q2 = onewgt.scales2[0]
656
657 wgtpdf = self.get_pdfQ2(pdf, self.b1*onewgt.pdgs[0], onewgt.bjks[0],
658 Dmuf**2 * muf2)
659 wgtpdf *= self.get_pdfQ2(pdf, self.b2*onewgt.pdgs[1], onewgt.bjks[1],
660 Dmuf**2 * muf2)
661
662 tmp = onewgt.pwgt[0]
663 tmp += onewgt.pwgt[1] * math.log(Dmur**2 * mur2/ Q2)
664 tmp += onewgt.pwgt[2] * math.log(Dmuf**2 * muf2/ Q2)
665
666 if self.b1 == 0 == self.b2:
667 alps = self.alpsrunner(Dmur*math.sqrt(mur2))
668 else:
669 alps = pdf.alphasQ2(Dmur**2*mur2)
670
671 tmp *= math.sqrt(4*math.pi*alps)**onewgt.qcdpower
672
673 if wgtpdf == 0:
674 key = (self.b1*onewgt.pdgs[0], self.b2*onewgt.pdgs[1], onewgt.bjks[0],onewgt.bjks[1], muf2)
675 if dyn== -1 and Dmuf==1 and Dmur==1 and pdf==self.orig_pdf:
676 wgtpdf = onewgt.ref_wgt / tmp
677 self.pdfQ2[key] = wgtpdf
678 elif key in self.pdfQ2:
679 wgtpdf = self.pdfQ2[key]
680 else:
681
682 wgtpdf = 0
683
684 tmp *= wgtpdf
685 wgt += tmp
686
687 if __debug__ and dyn== -1 and Dmur==1 and Dmuf==1 and pdf==self.orig_pdf:
688 if not misc.equal(tmp, onewgt.ref_wgt, sig_fig=4):
689 misc.sprint(tmp, onewgt.ref_wgt, (tmp-onewgt.ref_wgt)/tmp)
690 misc.sprint(onewgt)
691 misc.sprint(cevent)
692 misc.sprint(mur2,muf2)
693 raise Exception, 'not enough agreement between stored value and computed one'
694
695
696 return wgt
697
698
701 """calling systematics from a list of arguments"""
702
703 input, output = args[0:2]
704 opts = {}
705 for arg in args[2:]:
706 if '=' in arg:
707 key,values= arg.split('=')
708 key = key.replace('-','')
709 values = values.strip()
710 if values[0] in ["'",'"'] and values[-1]==values[0]:
711 values = values[1:-1]
712 values = values.split(',')
713 if key == 'together':
714 if key in opts:
715 opts[key].append(tuple(values))
716 else:
717 opts[key]=[tuple(values)]
718 elif key == 'result':
719 result = open(values[0],'w')
720 elif key in ['start_event', 'stop_event']:
721 opts[key] = int(values[0])
722 elif key == 'write_banner':
723 opts[key] = banner_mod.ConfigFile.format_variable(values[0], bool, 'write_banner')
724 else:
725 if key in opts:
726 opts[key] += values
727 else:
728 opts[key] = values
729 else:
730 raise SystematicsError, "unknow argument %s" % arg
731
732
733 if 'from_card' in opts:
734 if opts['from_card'] != ['internal']:
735 card = banner.RunCard(opts['from_card'][0])
736 else:
737 for i in range(10):
738 try:
739 lhe = lhe_parser.EventFile(input)
740 break
741 except OSError,error:
742 print error
743 time.sleep(15*(i+1))
744 else:
745 raise
746
747 card = banner.RunCard(banner.Banner(lhe.banner)['mgruncard'])
748 lhe.close()
749
750 if isinstance(card, banner.RunCardLO):
751
752 opts['mur'] = [float(x) for x in card['sys_scalefact'].split()]
753 opts['muf'] = opts['mur']
754 if card['sys_alpsfact'] != 'None':
755 opts['alps'] = [float(x) for x in card['sys_alpsfact'].split()]
756 else:
757 opts['alps'] = [1.0]
758 opts['together'] = [('mur','muf','alps','dyn')]
759 pdfs = card['sys_pdf'].split('&&')
760 opts['dyn'] = [-1,1,2,3,4]
761 opts['pdf'] = []
762 for pdf in pdfs:
763 split = pdf.split()
764 if len(split)==1:
765 opts['pdf'].append('%s' %pdf)
766 else:
767 pdf,nb = split
768 for i in range(int(nb)):
769 opts['pdf'].append('%s@%s' % (pdf, i))
770 if not opts['pdf']:
771 opts['pdf'] = 'central'
772 else:
773
774 raise Exception
775 del opts['from_card']
776
777
778 obj = Systematics(input, output, log=log,**opts)
779 if running:
780 obj.run(result)
781 return obj
782
783 if __name__ == "__main__":
784 call_systematics(sys.argv[1:])
785