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

Source Code for Module madgraph.various.banner

   1  ################################################################################ 
   2  # 
   3  # Copyright (c) 2011 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  """A File for splitting""" 
  16   
  17  from __future__ import division 
  18  import copy 
  19  import logging 
  20  import numbers 
  21  import os 
  22  import sys 
  23  import re 
  24  import math 
  25   
  26  pjoin = os.path.join 
  27   
  28  try: 
  29      import madgraph 
  30  except ImportError: 
  31      MADEVENT = True 
  32      from internal import MadGraph5Error, InvalidCmd 
  33      import internal.file_writers as file_writers 
  34      import internal.files as files 
  35      import internal.check_param_card as param_card_reader 
  36      import internal.misc as misc 
  37      MEDIR = os.path.split(os.path.dirname(os.path.realpath( __file__ )))[0] 
  38      MEDIR = os.path.split(MEDIR)[0] 
  39  else: 
  40      MADEVENT = False 
  41      import madgraph.various.misc as misc 
  42      import madgraph.iolibs.file_writers as file_writers 
  43      import madgraph.iolibs.files as files  
  44      import models.check_param_card as param_card_reader 
  45      from madgraph import MG5DIR, MadGraph5Error, InvalidCmd 
  46   
  47   
  48  logger = logging.getLogger('madevent.cards') 
 151       
152 - def __getattribute__(self, attr):
153 """allow auto-build for the run_card/param_card/... """ 154 try: 155 return super(Banner, self).__getattribute__(attr) 156 except: 157 if attr not in ['run_card', 'param_card', 'slha', 'mgruncard', 'mg5proccard', 'mgshowercard', 'foanalyse']: 158 raise 159 return self.charge_card(attr)
160 161 162
163 - def change_lhe_version(self, version):
164 """change the lhe version associate to the banner""" 165 166 version = float(version) 167 if version < 3: 168 version = 1 169 elif version > 3: 170 raise Exception, "Not Supported version" 171 self.lhe_version = version
172
173 - def get_cross(self):
174 """return the cross-section of the file""" 175 176 if "init" not in self: 177 misc.sprint(self.keys()) 178 raise Exception 179 180 text = self["init"].split('\n') 181 cross = 0 182 for line in text: 183 s = line.split() 184 if len(s)==4: 185 cross += float(s[0]) 186 return cross
187 188 189
190 - def modify_init_cross(self, cross):
191 """modify the init information with the associate cross-section""" 192 193 assert isinstance(cross, dict) 194 # assert "all" in cross 195 assert "init" in self 196 197 all_lines = self["init"].split('\n') 198 new_data = [] 199 new_data.append(all_lines[0]) 200 for i in range(1, len(all_lines)): 201 line = all_lines[i] 202 split = line.split() 203 if len(split) == 4: 204 xsec, xerr, xmax, pid = split 205 else: 206 new_data += all_lines[i:] 207 break 208 if int(pid) not in cross: 209 raise Exception 210 pid = int(pid) 211 ratio = cross[pid]/float(xsec) 212 line = " %+13.7e %+13.7e %+13.7e %i" % \ 213 (float(cross[pid]), ratio* float(xerr), ratio*float(xmax), pid) 214 new_data.append(line) 215 self['init'] = '\n'.join(new_data)
216
217 - def scale_init_cross(self, ratio):
218 """modify the init information with the associate scale""" 219 220 assert "init" in self 221 222 all_lines = self["init"].split('\n') 223 new_data = [] 224 new_data.append(all_lines[0]) 225 for i in range(1, len(all_lines)): 226 line = all_lines[i] 227 split = line.split() 228 if len(split) == 4: 229 xsec, xerr, xmax, pid = split 230 else: 231 new_data += all_lines[i:] 232 break 233 pid = int(pid) 234 235 line = " %+13.7e %+13.7e %+13.7e %i" % \ 236 (ratio*float(xsec), ratio* float(xerr), ratio*float(xmax), pid) 237 new_data.append(line) 238 self['init'] = '\n'.join(new_data)
239
240 - def load_basic(self, medir):
241 """ Load the proc_card /param_card and run_card """ 242 243 self.add(pjoin(medir,'Cards', 'param_card.dat')) 244 self.add(pjoin(medir,'Cards', 'run_card.dat')) 245 if os.path.exists(pjoin(medir, 'SubProcesses', 'procdef_mg5.dat')): 246 self.add(pjoin(medir,'SubProcesses', 'procdef_mg5.dat')) 247 self.add(pjoin(medir,'Cards', 'proc_card_mg5.dat')) 248 else: 249 self.add(pjoin(medir,'Cards', 'proc_card.dat'))
250 251
252 - def change_seed(self, seed):
253 """Change the seed value in the banner""" 254 # 0 = iseed 255 p = re.compile(r'''^\s*\d+\s*=\s*iseed''', re.M) 256 new_seed_str = " %s = iseed" % seed 257 self['mgruncard'] = p.sub(new_seed_str, self['mgruncard'])
258
259 - def add_generation_info(self, cross, nb_event):
260 """add info on MGGeneration""" 261 262 text = """ 263 # Number of Events : %s 264 # Integrated weight (pb) : %s 265 """ % (nb_event, cross) 266 self['MGGenerationInfo'] = text
267 268 ############################################################################ 269 # SPLIT BANNER 270 ############################################################################
271 - def split(self, me_dir, proc_card=True):
272 """write the banner in the Cards directory. 273 proc_card argument is present to avoid the overwrite of proc_card 274 information""" 275 276 for tag, text in self.items(): 277 if tag == 'mgversion': 278 continue 279 if not proc_card and tag in ['mg5proccard','mgproccard']: 280 continue 281 if not self.tag_to_file[tag]: 282 continue 283 ff = open(pjoin(me_dir, 'Cards', self.tag_to_file[tag]), 'w') 284 ff.write(text) 285 ff.close()
286 287 288 ############################################################################ 289 # WRITE BANNER 290 ############################################################################
291 - def check_pid(self, pid2label):
292 """special routine removing width/mass of particles not present in the model 293 This is usefull in case of loop model card, when we want to use the non 294 loop model.""" 295 296 if not hasattr(self, 'param_card'): 297 self.charge_card('slha') 298 299 for tag in ['mass', 'decay']: 300 block = self.param_card.get(tag) 301 for data in block: 302 pid = data.lhacode[0] 303 if pid not in pid2label.keys(): 304 block.remove((pid,))
305
306 - def get_lha_strategy(self):
307 """get the lha_strategy: how the weight have to be handle by the shower""" 308 309 if not self["init"]: 310 raise Exception, "No init block define" 311 312 data = self["init"].split('\n')[0].split() 313 if len(data) != 10: 314 misc.sprint(len(data), self['init']) 315 raise Exception, "init block has a wrong format" 316 return int(float(data[-2]))
317
318 - def set_lha_strategy(self, value):
319 """set the lha_strategy: how the weight have to be handle by the shower""" 320 321 if not (-4 <= int(value) <= 4): 322 raise Exception, "wrong value for lha_strategy", value 323 if not self["init"]: 324 raise Exception, "No init block define" 325 326 all_lines = self["init"].split('\n') 327 data = all_lines[0].split() 328 if len(data) != 10: 329 misc.sprint(len(data), self['init']) 330 raise Exception, "init block has a wrong format" 331 data[-2] = '%s' % value 332 all_lines[0] = ' '.join(data) 333 self['init'] = '\n'.join(all_lines)
334
335 - def modify_init_cross(self, cross):
336 """modify the init information with the associate cross-section""" 337 338 assert isinstance(cross, dict) 339 # assert "all" in cross 340 assert "init" in self 341 342 all_lines = self["init"].split('\n') 343 new_data = [] 344 new_data.append(all_lines[0]) 345 for i in range(1, len(all_lines)): 346 line = all_lines[i] 347 split = line.split() 348 if len(split) == 4: 349 xsec, xerr, xmax, pid = split 350 else: 351 new_data += all_lines[i:] 352 break 353 if int(pid) not in cross: 354 raise Exception 355 pid = int(pid) 356 ratio = cross[pid]/float(xsec) 357 line = " %+13.7e %+13.7e %+13.7e %i" % \ 358 (float(cross[pid]), ratio* float(xerr), ratio*float(xmax), pid) 359 new_data.append(line) 360 self['init'] = '\n'.join(new_data)
361 362 ############################################################################ 363 # WRITE BANNER 364 ############################################################################
365 - def write(self, output_path, close_tag=True, exclude=[]):
366 """write the banner""" 367 368 if isinstance(output_path, str): 369 ff = open(output_path, 'w') 370 else: 371 ff = output_path 372 373 if MADEVENT: 374 header = open(pjoin(MEDIR, 'Source', 'banner_header.txt')).read() 375 else: 376 header = open(pjoin(MG5DIR,'Template', 'LO', 'Source', 'banner_header.txt')).read() 377 378 if not self.lhe_version: 379 self.lhe_version = self.get('run_card', 'lhe_version', default=1.0) 380 if float(self.lhe_version) < 3: 381 self.lhe_version = 1.0 382 383 ff.write(header % { 'version':float(self.lhe_version)}) 384 385 386 for tag in [t for t in self.ordered_items if t in self.keys()]: 387 if tag in exclude: 388 continue 389 capitalized_tag = self.capitalized_items[tag] if tag in self.capitalized_items else tag 390 ff.write('<%(tag)s>\n%(text)s\n</%(tag)s>\n' % \ 391 {'tag':capitalized_tag, 'text':self[tag].strip()}) 392 for tag in [t for t in self.keys() if t not in self.ordered_items]: 393 if tag in ['init'] or tag in exclude: 394 continue 395 capitalized_tag = self.capitalized_items[tag] if tag in self.capitalized_items else tag 396 ff.write('<%(tag)s>\n%(text)s\n</%(tag)s>\n' % \ 397 {'tag':capitalized_tag, 'text':self[tag].strip()}) 398 399 if not '/header' in exclude: 400 ff.write('</header>\n') 401 402 if 'init' in self and not 'init' in exclude: 403 text = self['init'] 404 ff.write('<%(tag)s>\n%(text)s\n</%(tag)s>\n' % \ 405 {'tag':'init', 'text':text.strip()}) 406 if close_tag: 407 ff.write('</LesHouchesEvents>\n') 408 return ff
409 410 411 ############################################################################ 412 # BANNER 413 ############################################################################
414 - def add(self, path, tag=None):
415 """Add the content of the file to the banner""" 416 417 if not tag: 418 card_name = os.path.basename(path) 419 if 'param_card' in card_name: 420 tag = 'slha' 421 elif 'run_card' in card_name: 422 tag = 'MGRunCard' 423 elif 'pythia_card' in card_name: 424 tag = 'MGPythiaCard' 425 elif 'pgs_card' in card_name: 426 tag = 'MGPGSCard' 427 elif 'delphes_card' in card_name: 428 tag = 'MGDelphesCard' 429 elif 'delphes_trigger' in card_name: 430 tag = 'MGDelphesTrigger' 431 elif 'proc_card_mg5' in card_name: 432 tag = 'MG5ProcCard' 433 elif 'proc_card' in card_name: 434 tag = 'MGProcCard' 435 elif 'procdef_mg5' in card_name: 436 tag = 'MGProcCard' 437 elif 'shower_card' in card_name: 438 tag = 'MGShowerCard' 439 elif 'madspin_card' in card_name: 440 tag = 'madspin' 441 elif 'FO_analyse_card' in card_name: 442 tag = 'foanalyse' 443 elif 'reweight_card' in card_name: 444 tag='reweight_card' 445 else: 446 raise Exception, 'Impossible to know the type of the card' 447 448 self.add_text(tag.lower(), open(path).read())
449
450 - def add_text(self, tag, text):
451 """Add the content of the file to the banner""" 452 453 if tag == 'param_card': 454 tag = 'slha' 455 elif tag == 'run_card': 456 tag = 'mgruncard' 457 elif tag == 'proc_card': 458 tag = 'mg5proccard' 459 elif tag == 'shower_card': 460 tag = 'mgshowercard' 461 elif tag == 'FO_analyse_card': 462 tag = 'foanalyse' 463 464 self[tag.lower()] = text
465 466
467 - def charge_card(self, tag):
468 """Build the python object associated to the card""" 469 470 if tag == 'param_card': 471 tag = 'slha' 472 elif tag == 'run_card': 473 tag = 'mgruncard' 474 elif tag == 'proc_card': 475 tag = 'mg5proccard' 476 elif tag == 'shower_card': 477 tag = 'mgshowercard' 478 elif tag == 'FO_analyse_card': 479 tag = 'foanalyse' 480 481 assert tag in ['slha', 'mgruncard', 'mg5proccard', 'mgshowercard', 'foanalyse'], 'invalid card %s' % tag 482 483 if tag == 'slha': 484 param_card = self[tag].split('\n') 485 self.param_card = param_card_reader.ParamCard(param_card) 486 return self.param_card 487 elif tag == 'mgruncard': 488 self.run_card = RunCard(self[tag]) 489 return self.run_card 490 elif tag == 'mg5proccard': 491 proc_card = self[tag].split('\n') 492 self.proc_card = ProcCard(proc_card) 493 return self.proc_card 494 elif tag =='mgshowercard': 495 shower_content = self[tag] 496 if MADEVENT: 497 import internal.shower_card as shower_card 498 else: 499 import madgraph.various.shower_card as shower_card 500 self.shower_card = shower_card.ShowerCard(shower_content, True) 501 # set testing to false (testing = true allow to init using 502 # the card content instead of the card path" 503 self.shower_card.testing = False 504 return self.shower_card 505 elif tag =='foanalyse': 506 analyse_content = self[tag] 507 if MADEVENT: 508 import internal.FO_analyse_card as FO_analyse_card 509 else: 510 import madgraph.various.FO_analyse_card as FO_analyse_card 511 # set testing to false (testing = true allow to init using 512 # the card content instead of the card path" 513 self.FOanalyse_card = FO_analyse_card.FOAnalyseCard(analyse_content, True) 514 self.FOanalyse_card.testing = False 515 return self.FOanalyse_card
516 517
518 - def get_detail(self, tag, *arg, **opt):
519 """return a specific """ 520 521 if tag in ['param_card', 'param']: 522 tag = 'slha' 523 attr_tag = 'param_card' 524 elif tag in ['run_card', 'run']: 525 tag = 'mgruncard' 526 attr_tag = 'run_card' 527 elif tag == 'proc_card': 528 tag = 'mg5proccard' 529 attr_tag = 'proc_card' 530 elif tag == 'model': 531 tag = 'mg5proccard' 532 attr_tag = 'proc_card' 533 arg = ('model',) 534 elif tag == 'generate': 535 tag = 'mg5proccard' 536 attr_tag = 'proc_card' 537 arg = ('generate',) 538 elif tag == 'shower_card': 539 tag = 'mgshowercard' 540 attr_tag = 'shower_card' 541 assert tag in ['slha', 'mgruncard', 'mg5proccard', 'shower_card'], '%s not recognized' % tag 542 543 if not hasattr(self, attr_tag): 544 self.charge_card(attr_tag) 545 546 card = getattr(self, attr_tag) 547 if len(arg) == 1: 548 if tag == 'mg5proccard': 549 try: 550 return card.get(arg[0]) 551 except KeyError, error: 552 if 'default' in opt: 553 return opt['default'] 554 else: 555 raise 556 try: 557 return card[arg[0]] 558 except KeyError: 559 if 'default' in opt: 560 return opt['default'] 561 else: 562 raise 563 elif len(arg) == 2 and tag == 'slha': 564 try: 565 return card[arg[0]].get(arg[1:]) 566 except KeyError: 567 if 'default' in opt: 568 return opt['default'] 569 else: 570 raise 571 elif len(arg) == 0: 572 return card 573 else: 574 raise Exception, "Unknow command"
575 576 #convenient alias 577 get = get_detail 578
579 - def set(self, card, *args):
580 """modify one of the cards""" 581 582 if tag == 'param_card': 583 tag = 'slha' 584 attr_tag = 'param_card' 585 elif tag == 'run_card': 586 tag = 'mgruncard' 587 attr_tag = 'run_card' 588 elif tag == 'proc_card': 589 tag = 'mg5proccard' 590 attr_tag = 'proc_card' 591 elif tag == 'model': 592 tag = 'mg5proccard' 593 attr_tag = 'proc_card' 594 arg = ('model',) 595 elif tag == 'generate': 596 tag = 'mg5proccard' 597 attr_tag = 'proc_card' 598 arg = ('generate',) 599 elif tag == 'shower_card': 600 tag = 'mgshowercard' 601 attr_tag = 'shower_card' 602 assert tag in ['slha', 'mgruncard', 'mg5proccard', 'shower_card'], 'not recognized' 603 604 if not hasattr(self, attr_tag): 605 self.charge_card(attr_tag) 606 607 card = getattr(self, attr_tag) 608 if len(args) ==2: 609 if tag == 'mg5proccard': 610 card.info[args[0]] = args[-1] 611 else: 612 card[args[0]] = args[1] 613 else: 614 card[args[:-1]] = args[-1]
615 616 617 @misc.multiple_try()
618 - def add_to_file(self, path, seed=None, out=None):
619 """Add the banner to a file and change the associate seed in the banner""" 620 621 if seed is not None: 622 self.set("run_card", "iseed", seed) 623 624 if not out: 625 path_out = "%s.tmp" % path 626 else: 627 path_out = out 628 629 ff = self.write(path_out, close_tag=False, 630 exclude=['MGGenerationInfo', '/header', 'init']) 631 ff.write("## END BANNER##\n") 632 if self.lhe_version >= 3: 633 #add the original content 634 [ff.write(line) if not line.startswith("<generator name='MadGraph5_aMC@NLO'") 635 else ff.write("<generator name='MadGraph5_aMC@NLO' version='%s'>" % self['mgversion'][:-1]) 636 for line in open(path)] 637 else: 638 [ff.write(line) for line in open(path)] 639 ff.write("</LesHouchesEvents>\n") 640 ff.close() 641 if out: 642 os.remove(path) 643 else: 644 files.mv(path_out, path)
645
646 647 648 -def split_banner(banner_path, me_dir, proc_card=True):
649 """a simple way to split a banner""" 650 651 banner = Banner(banner_path) 652 banner.split(me_dir, proc_card)
653
654 -def recover_banner(results_object, level, run=None, tag=None):
655 """as input we receive a gen_crossxhtml.AllResults object. 656 This define the current banner and load it 657 """ 658 659 if not run: 660 try: 661 _run = results_object.current['run_name'] 662 _tag = results_object.current['tag'] 663 except Exception: 664 return Banner() 665 else: 666 _run = run 667 if not tag: 668 try: 669 _tag = results_object[run].tags[-1] 670 except Exception,error: 671 return Banner() 672 else: 673 _tag = tag 674 675 path = results_object.path 676 banner_path = pjoin(path,'Events',run,'%s_%s_banner.txt' % (run, tag)) 677 678 if not os.path.exists(banner_path): 679 if level != "parton" and tag != _tag: 680 return recover_banner(results_object, level, _run, results_object[_run].tags[0]) 681 # security if the banner was remove (or program canceled before created it) 682 return Banner() 683 banner = Banner(banner_path) 684 685 686 687 if level == 'pythia': 688 if 'mgpythiacard' in banner: 689 del banner['mgpythiacard'] 690 if level in ['pythia','pgs','delphes']: 691 for tag in ['mgpgscard', 'mgdelphescard', 'mgdelphestrigger']: 692 if tag in banner: 693 del banner[tag] 694 return banner
695
696 -class InvalidRunCard(InvalidCmd):
697 pass
698
699 -class ProcCard(list):
700 """Basic Proccard object""" 701 702 history_header = \ 703 '#************************************************************\n' + \ 704 '#* MadGraph5_aMC@NLO *\n' + \ 705 '#* *\n' + \ 706 "#* * * *\n" + \ 707 "#* * * * * *\n" + \ 708 "#* * * * * 5 * * * * *\n" + \ 709 "#* * * * * *\n" + \ 710 "#* * * *\n" + \ 711 "#* *\n" + \ 712 "#* *\n" + \ 713 "%(info_line)s" +\ 714 "#* *\n" + \ 715 "#* The MadGraph5_aMC@NLO Development Team - Find us at *\n" + \ 716 "#* https://server06.fynu.ucl.ac.be/projects/madgraph *\n" + \ 717 '#* *\n' + \ 718 '#************************************************************\n' + \ 719 '#* *\n' + \ 720 '#* Command File for MadGraph5_aMC@NLO *\n' + \ 721 '#* *\n' + \ 722 '#* run as ./bin/mg5_aMC filename *\n' + \ 723 '#* *\n' + \ 724 '#************************************************************\n' 725 726 727 728
729 - def __init__(self, init=None):
730 """ initialize a basic proc_card""" 731 self.info = {'model': 'sm', 'generate':None, 732 'full_model_line':'import model sm'} 733 list.__init__(self) 734 if init: 735 self.read(init)
736 737
738 - def read(self, init):
739 """read the proc_card and save the information""" 740 741 if isinstance(init, str): #path to file 742 init = file(init, 'r') 743 744 store_line = '' 745 for line in init: 746 line = line.rstrip() 747 if line.endswith('\\'): 748 store_line += line[:-1] 749 else: 750 tmp = store_line + line 751 self.append(tmp.strip()) 752 store_line = "" 753 if store_line: 754 raise Exception, "WRONG CARD FORMAT"
755 756
757 - def move_to_last(self, cmd):
758 """move an element to the last history.""" 759 for line in self[:]: 760 if line.startswith(cmd): 761 self.remove(line) 762 list.append(self, line)
763
764 - def append(self, line):
765 """"add a line in the proc_card perform automatically cleaning""" 766 767 line = line.strip() 768 cmds = line.split() 769 if len(cmds) == 0: 770 return 771 772 list.append(self, line) 773 774 # command type: 775 cmd = cmds[0] 776 777 if cmd == 'output': 778 # Remove previous outputs from history 779 self.clean(allow_for_removal = ['output'], keep_switch=True, 780 remove_bef_last='output') 781 elif cmd == 'generate': 782 # Remove previous generations from history 783 self.clean(remove_bef_last='generate', keep_switch=True, 784 allow_for_removal= ['generate', 'add process', 'output']) 785 self.info['generate'] = ' '.join(cmds[1:]) 786 elif cmd == 'add' and cmds[1] == 'process' and not self.info['generate']: 787 self.info['generate'] = ' '.join(cmds[2:]) 788 elif cmd == 'import': 789 if len(cmds) < 2: 790 return 791 if cmds[1].startswith('model'): 792 self.info['full_model_line'] = line 793 self.clean(remove_bef_last='import', keep_switch=True, 794 allow_for_removal=['generate', 'add process', 'add model', 'output']) 795 if cmds[1] == 'model': 796 self.info['model'] = cmds[2] 797 else: 798 self.info['model'] = None # not UFO model 799 elif cmds[1] == 'proc_v4': 800 #full cleaning 801 self[:] = []
802 803
804 - def clean(self, to_keep=['set','add','load'], 805 remove_bef_last=None, 806 to_remove=['open','display','launch', 'check','history'], 807 allow_for_removal=None, 808 keep_switch=False):
809 """Remove command in arguments from history. 810 All command before the last occurrence of 'remove_bef_last' 811 (including it) will be removed (but if another options tells the opposite). 812 'to_keep' is a set of line to always keep. 813 'to_remove' is a set of line to always remove (don't care about remove_bef_ 814 status but keep_switch acts.). 815 if 'allow_for_removal' is define only the command in that list can be 816 remove of the history for older command that remove_bef_lb1. all parameter 817 present in to_remove are always remove even if they are not part of this 818 list. 819 keep_switch force to keep the statement remove_bef_??? which changes starts 820 the removal mode. 821 """ 822 823 #check consistency 824 if __debug__ and allow_for_removal: 825 for arg in to_keep: 826 assert arg not in allow_for_removal 827 828 829 nline = -1 830 removal = False 831 #looping backward 832 while nline > -len(self): 833 switch = False # set in True when removal pass in True 834 835 #check if we need to pass in removal mode 836 if not removal and remove_bef_last: 837 if self[nline].startswith(remove_bef_last): 838 removal = True 839 switch = True 840 841 # if this is the switch and is protected pass to the next element 842 if switch and keep_switch: 843 nline -= 1 844 continue 845 846 # remove command in to_remove (whatever the status of removal) 847 if any([self[nline].startswith(arg) for arg in to_remove]): 848 self.pop(nline) 849 continue 850 851 # Only if removal mode is active! 852 if removal: 853 if allow_for_removal: 854 # Only a subset of command can be removed 855 if any([self[nline].startswith(arg) 856 for arg in allow_for_removal]): 857 self.pop(nline) 858 continue 859 elif not any([self[nline].startswith(arg) for arg in to_keep]): 860 # All command have to be remove but protected 861 self.pop(nline) 862 continue 863 864 # update the counter to pass to the next element 865 nline -= 1
866
867 - def get(self, tag, default=None):
868 if isinstance(tag, int): 869 list.__getattr__(self, tag) 870 elif tag == 'info' or tag == "__setstate__": 871 return default #for pickle 872 elif tag == "multiparticles": 873 out = [] 874 for line in self: 875 if line.startswith('define'): 876 name, content = line[7:].split('=',1) 877 out.append((name, content)) 878 return out 879 else: 880 return self.info[tag]
881
882 - def write(self, path):
883 """write the proc_card to a given path""" 884 885 fsock = open(path, 'w') 886 fsock.write(self.history_header) 887 for line in self: 888 while len(line) > 70: 889 sub, line = line[:70]+"\\" , line[70:] 890 fsock.write(sub+"\n") 891 else: 892 fsock.write(line+"\n")
893
894 895 -class ConfigFile(dict):
896 """ a class for storing/dealing with input file. 897 """ 898
899 - def __init__(self, finput=None):
900 """initialize a new instance. input can be an instance of MadLoopParam, 901 a file, a path to a file, or simply Nothing""" 902 903 if isinstance(finput, self.__class__): 904 dict.__init__(self, finput) 905 assert finput.__dict__.keys() 906 for key in finput.__dict__: 907 setattr(self, key, copy.copy(getattr(finput, key)) ) 908 return 909 else: 910 dict.__init__(self) 911 912 # Initialize it with all the default value 913 self.user_set = set() 914 self.system_only = set() 915 self.lower_to_case = {} 916 self.list_parameter = set() 917 self.default_setup() 918 919 920 921 # if input is define read that input 922 if isinstance(finput, (file, str)): 923 self.read(finput)
924 925
926 - def default_setup(self):
927 pass
928
929 - def __copy__(self):
930 return self.__class__(self)
931
932 - def __add__(self, other):
933 """define the sum""" 934 assert isinstance(other, dict) 935 base = self.__class__(self) 936 #base = copy.copy(self) 937 base.update((key.lower(),value) for key, value in other.items()) 938 return base
939
940 - def __radd__(self, other):
941 """define the sum""" 942 new = copy.copy(other) 943 new.update((key, value) for key, value in self.items()) 944 return new
945
946 - def __contains__(self, key):
947 return dict.__contains__(self, key.lower())
948
949 - def __iter__(self):
950 iter = super(ConfigFile, self).__iter__() 951 return (self.lower_to_case[name] for name in iter)
952
953 - def keys(self):
954 return [name for name in self]
955
956 - def items(self):
957 return [(self.lower_to_case[name], value) for name,value in \ 958 super(ConfigFile, self).items()]
959
960 - def __setitem__(self, name, value, change_userdefine=False):
961 """set the attribute and set correctly the type if the value is a string""" 962 if not len(self): 963 #Should never happen but when deepcopy/pickle 964 self.__init__() 965 966 967 name = name.strip() 968 lower_name = name.lower() 969 # 0. check if this parameter is a system only one 970 if change_userdefine and lower_name in self.system_only: 971 logger.critical('%s is a private entry which can not be modify by the user. Keep value at %s' % (name,self[name])) 972 973 # 1. Find the type of the attribute that we want 974 if name in self.list_parameter: 975 if isinstance(self[name], list): 976 targettype = type(self[name][0]) 977 else: 978 targettype = type(self[name]) #should not happen but ok 979 980 if isinstance(value, str): 981 # split for each comma/space 982 value = value.strip() 983 if value.startswith('[') and value.endswith(']'): 984 value = value[1:-1] 985 value = filter(None, re.split(r'(?:(?<!\\)\s)|,', value, re.VERBOSE)) 986 elif not hasattr(value, '__iter__'): 987 value = [value] 988 elif isinstance(value, dict): 989 raise Exception, "not being able to handle dictionary in card entry" 990 #format each entry 991 values =[self.format_variable(v, targettype, name=name) 992 for v in value] 993 dict.__setitem__(self, lower_name, values) 994 if change_userdefine: 995 self.user_set.add(lower_name) 996 return 997 elif name in self: 998 targettype = type(self[name]) 999 else: 1000 logger.debug('Trying to add argument %s in %s. ' % (name, self.__class__.__name__) +\ 1001 'This argument is not defined by default. Please consider to add it.') 1002 logger.debug("Did you mean %s", [k for k in self.keys() if k.startswith(name[0].lower())]) 1003 self.add_param(lower_name, self.format_variable(str(value), str, name)) 1004 self.lower_to_case[lower_name] = name 1005 if change_userdefine: 1006 self.user_set.add(lower_name) 1007 return 1008 1009 value = self.format_variable(value, targettype, name=name) 1010 dict.__setitem__(self, lower_name, value) 1011 if change_userdefine: 1012 self.user_set.add(lower_name)
1013
1014 - def add_param(self, name, value, system=False):
1015 """add a default parameter to the class""" 1016 1017 lower_name = name.lower() 1018 if __debug__: 1019 if lower_name in self: 1020 raise Exception("Duplicate case for %s in %s" % (name,self.__class__)) 1021 1022 dict.__setitem__(self, lower_name, value) 1023 self.lower_to_case[lower_name] = name 1024 if isinstance(value, list): 1025 if any([type(value[0]) != type(v) for v in value]): 1026 raise Exception, "All entry should have the same type" 1027 self.list_parameter.add(lower_name) 1028 if system: 1029 self.system_only.add(lower_name)
1030 1031 @staticmethod
1032 - def format_variable(value, targettype, name="unknown"):
1033 """assign the value to the attribute for the given format""" 1034 1035 if not isinstance(value, str): 1036 # just have to check that we have the correct format 1037 if isinstance(value, targettype): 1038 pass # assignement at the end 1039 elif isinstance(value, numbers.Number) and issubclass(targettype, numbers.Number): 1040 try: 1041 new_value = targettype(value) 1042 except TypeError: 1043 if value.imag/value.real<1e-12: 1044 new_value = targettype(value.real) 1045 else: 1046 raise 1047 if new_value == value: 1048 value = new_value 1049 else: 1050 raise Exception, "Wrong input type for %s found %s and expecting %s for value %s" %\ 1051 (name, type(value), targettype, value) 1052 else: 1053 raise Exception, "Wrong input type for %s found %s and expecting %s for value %s" %\ 1054 (name, type(value), targettype, value) 1055 else: 1056 # We have a string we have to format the attribute from the string 1057 if targettype == bool: 1058 value = value.strip() 1059 if value.lower() in ['0', '.false.', 'f', 'false']: 1060 value = False 1061 elif value.lower() in ['1', '.true.', 't', 'true']: 1062 value = True 1063 else: 1064 raise Exception, "%s can not be mapped to True/False for %s" % (repr(value),name) 1065 elif targettype == str: 1066 value = value.strip() 1067 if value.startswith('\'') and value.endswith('\''): 1068 value = value[1:-1] 1069 elif value.startswith('"') and value.endswith('"'): 1070 value = value[1:-1] 1071 elif targettype == int: 1072 if value.isdigit(): 1073 value = int(value) 1074 elif value[1:].isdigit() and value[0] == '-': 1075 value = int(value) 1076 else: 1077 try: 1078 value = float(value.replace('d','e')) 1079 except ValueError: 1080 raise Exception, "%s can not be mapped to an integer" % value 1081 try: 1082 new_value = int(value) 1083 except ValueError: 1084 raise Exception, "%s can not be mapped to an integer" % value 1085 else: 1086 if value == new_value: 1087 value = new_value 1088 else: 1089 raise Exception, "incorect input: %s need an integer for %s" % (value,name) 1090 elif targettype == float: 1091 value = value.replace('d','e') # pass from Fortran formatting 1092 try: 1093 value = float(value) 1094 except ValueError: 1095 raise Exception, "%s can not be mapped to a float" % value 1096 else: 1097 raise Exception, "type %s is not handle by MadLoopParam" % targettype 1098 1099 return value
1100 1101 1102
1103 - def __getitem__(self, name):
1104 1105 if __debug__: 1106 if name.lower() not in self: 1107 if name.lower() in [key.lower() for key in self] : 1108 raise Exception, "Some key are not lower case %s. Invalid use of the class!"\ 1109 % [key for key in self if key.lower() != key] 1110 1111 return dict.__getitem__(self, name.lower())
1112 1113
1114 - def set(self, name, value, ifnotdefault=True, user=False):
1115 """convenient way to change attribute. 1116 ifnotdefault=False means that the value is NOT change is the value is not on default. 1117 user=True, means that the value will be marked as modified by the user 1118 (potentially preventing future change to the value) 1119 """ 1120 1121 # ifnotdefault=False -> we need to check if the user force a value. 1122 if not ifnotdefault: 1123 if name.lower() in self.user_set: 1124 #value modified by the user -> do nothing 1125 return 1126 1127 self.__setitem__(name, value, change_userdefine=user)
1128
1129 1130 1131 -class ProcCharacteristic(ConfigFile):
1132 """A class to handle information which are passed from MadGraph to the madevent 1133 interface.""" 1134
1135 - def default_setup(self):
1136 """initialize the directory to the default value""" 1137 1138 self.add_param('loop_induced', False) 1139 self.add_param('has_isr', False) 1140 self.add_param('has_fsr', False) 1141 self.add_param('nb_channel', 0) 1142 self.add_param('nexternal', 0) 1143 self.add_param('ninitial', 0) 1144 self.add_param('grouped_matrix', True) 1145 self.add_param('has_loops', False)
1146
1147 - def read(self, finput):
1148 """Read the input file, this can be a path to a file, 1149 a file object, a str with the content of the file.""" 1150 1151 if isinstance(finput, str): 1152 if "\n" in finput: 1153 finput = finput.split('\n') 1154 elif os.path.isfile(finput): 1155 finput = open(finput) 1156 else: 1157 raise Exception, "No such file %s" % finput 1158 1159 for line in finput: 1160 if '#' in line: 1161 line = line.split('#',1)[0] 1162 if not line: 1163 continue 1164 1165 if '=' in line: 1166 key, value = line.split('=',1) 1167 self[key.strip()] = value
1168
1169 - def write(self, outputpath):
1170 """write the file""" 1171 1172 template ="# Information about the process #\n" 1173 template +="#########################################\n" 1174 1175 fsock = open(outputpath, 'w') 1176 fsock.write(template) 1177 1178 for key, value in self.items(): 1179 fsock.write(" %s = %s \n" % (key, value)) 1180 1181 fsock.close()
1182
1183 1184 1185 1186 -class GridpackCard(ConfigFile):
1187 """an object for the GridpackCard""" 1188
1189 - def default_setup(self):
1190 """default value for the GridpackCard""" 1191 1192 self.add_param("GridRun", True) 1193 self.add_param("gevents", 2500) 1194 self.add_param("gseed", 1) 1195 self.add_param("ngran", -1)
1196
1197 - def read(self, finput):
1198 """Read the input file, this can be a path to a file, 1199 a file object, a str with the content of the file.""" 1200 1201 if isinstance(finput, str): 1202 if "\n" in finput: 1203 finput = finput.split('\n') 1204 elif os.path.isfile(finput): 1205 finput = open(finput) 1206 else: 1207 raise Exception, "No such file %s" % finput 1208 1209 for line in finput: 1210 line = line.split('#')[0] 1211 line = line.split('!')[0] 1212 line = line.split('=',1) 1213 if len(line) != 2: 1214 continue 1215 self[line[1].strip()] = line[0].replace('\'','').strip()
1216
1217 - def write(self, output_file, template=None):
1218 """Write the run_card in output_file according to template 1219 (a path to a valid run_card)""" 1220 1221 if not template: 1222 if not MADEVENT: 1223 template = pjoin(MG5DIR, 'Template', 'LO', 'Cards', 1224 'grid_card_default.dat') 1225 else: 1226 template = pjoin(MEDIR, 'Cards', 'grid_card_default.dat') 1227 1228 1229 text = "" 1230 for line in file(template,'r'): 1231 nline = line.split('#')[0] 1232 nline = nline.split('!')[0] 1233 comment = line[len(nline):] 1234 nline = nline.split('=') 1235 if len(nline) != 2: 1236 text += line 1237 elif nline[1].strip() in self: 1238 text += ' %s\t= %s %s' % (self[nline[1].strip()],nline[1], comment) 1239 else: 1240 logger.info('Adding missing parameter %s to current run_card (with default value)' % nline[1].strip()) 1241 text += line 1242 1243 fsock = open(output_file,'w') 1244 fsock.write(text) 1245 fsock.close()
1246
1247 -class RunCard(ConfigFile):
1248
1249 - def __new__(cls, finput=None):
1250 if cls is RunCard: 1251 if not finput: 1252 target_class = RunCardLO 1253 elif isinstance(finput, cls): 1254 target_class = finput.__class__ 1255 elif isinstance(finput, str): 1256 if '\n' not in finput: 1257 finput = open(finput).read() 1258 if 'req_acc_FO' in finput: 1259 target_class = RunCardNLO 1260 else: 1261 target_class = RunCardLO 1262 else: 1263 return None 1264 return super(RunCard, cls).__new__(target_class, finput) 1265 else: 1266 return super(RunCard, cls).__new__(cls, finput)
1267
1268 - def __init__(self, *args, **opts):
1269 1270 # The following parameter are updated in the defaultsetup stage. 1271 1272 #parameter for which no warning should be raised if not define 1273 self.hidden_param = [] 1274 # parameter which should not be hardcoded in the config file 1275 self.not_in_include = [] 1276 #some parameter have different name in fortran code 1277 self.fortran_name = {} 1278 #parameter which are not supported anymore. (no action on the code) 1279 self.legacy_parameter = {} 1280 #a list with all the cuts variable 1281 self.cuts_parameter = [] 1282 1283 1284 super(RunCard, self).__init__(*args, **opts)
1285
1286 - def add_param(self, name, value, fortran_name=None, include=True, 1287 hidden=False, legacy=False, cut=False, system=False, **opts):
1288 """ add a parameter to the card. value is the default value and 1289 defines the type (int/float/bool/str) of the input. 1290 fortran_name defines what is the associate name in the f77 code 1291 include defines if we have to put the value in the include file 1292 hidden defines if the parameter is expected to be define by the user. 1293 legacy:Parameter which is not used anymore (raise a warning if not default) 1294 cut: defines the list of cut parameter to allow to set them all to off. 1295 """ 1296 1297 super(RunCard, self).add_param(name, value, system=system,**opts) 1298 name = name.lower() 1299 if fortran_name: 1300 self.fortran_name[name] = fortran_name 1301 if not include: 1302 self.not_in_include.append(name) 1303 if hidden or system: 1304 self.hidden_param.append(name) 1305 if legacy: 1306 self.legacy_parameter[name] = value 1307 if include: 1308 self.not_in_include.append(name) 1309 if cut: 1310 self.cuts_parameter.append(name)
1311 1312 1313
1314 - def read(self, finput):
1315 """Read the input file, this can be a path to a file, 1316 a file object, a str with the content of the file.""" 1317 1318 if isinstance(finput, str): 1319 if "\n" in finput: 1320 finput = finput.split('\n') 1321 elif os.path.isfile(finput): 1322 finput = open(finput) 1323 else: 1324 raise Exception, "No such file %s" % finput 1325 1326 for line in finput: 1327 line = line.split('#')[0] 1328 line = line.split('!')[0] 1329 line = line.split('=',1) 1330 if len(line) != 2: 1331 continue 1332 value, name = line 1333 name = name.lower().strip() 1334 if name not in self and ('min' in name or 'max' in name): 1335 #looks like an entry added by one user -> add it nicely 1336 self.add_param(name, float(value), hidden=True, cut=True) 1337 else: 1338 self.set( name, value, user=True)
1339
1340 - def write(self, output_file, template=None, python_template=False):
1341 """Write the run_card in output_file according to template 1342 (a path to a valid run_card)""" 1343 1344 to_write = set(self.user_set) 1345 if not template: 1346 raise Exception 1347 1348 if python_template and not to_write: 1349 if not self.list_parameter: 1350 text = file(template,'r').read() % self 1351 else: 1352 data = dict(self) 1353 for name in self.list_parameter: 1354 data[name] = ', '.join(str(v) for v in data[name]) 1355 text = file(template,'r').read() % data 1356 else: 1357 text = "" 1358 for line in file(template,'r'): 1359 nline = line.split('#')[0] 1360 nline = nline.split('!')[0] 1361 comment = line[len(nline):] 1362 nline = nline.split('=') 1363 if len(nline) != 2: 1364 text += line 1365 elif nline[1].strip() in self: 1366 name = nline[1].strip().lower() 1367 value = self[name] 1368 if name in self.list_parameter: 1369 value = ', '.join([str(v) for v in value]) 1370 if python_template: 1371 text += line % {name:value} 1372 else: 1373 if not comment or comment[-1]!='\n': 1374 endline = '\n' 1375 else: 1376 endline = '' 1377 text += ' %s\t= %s %s%s' % (value, name, comment, endline) 1378 1379 if name.lower() in to_write: 1380 to_write.remove(nline[1].strip().lower()) 1381 else: 1382 logger.info('Adding missing parameter %s to current run_card (with default value)' % name) 1383 text += line 1384 1385 if to_write: 1386 text+="""#********************************************************************* 1387 # Additional parameter 1388 #********************************************************************* 1389 """ 1390 1391 for key in to_write: 1392 text += ' %s\t= %s # %s\n' % (self[key], key, 'hidden parameter') 1393 1394 if isinstance(output_file, str): 1395 fsock = open(output_file,'w') 1396 fsock.write(text) 1397 fsock.close() 1398 else: 1399 output_file.write(text)
1400 1401
1402 - def get_default(self, name, default=None, log_level=None):
1403 """return self[name] if exist otherwise default. log control if we 1404 put a warning or not if we use the default value""" 1405 1406 if name not in self.user_set: 1407 if log_level is None: 1408 if name.lower() in self.hidden_param: 1409 log_level = 10 1410 else: 1411 log_level = 20 1412 if not default: 1413 default = self[name] 1414 logger.log(log_level, 'run_card missed argument %s. Takes default: %s' 1415 % (name, default)) 1416 self[name] = default 1417 return default 1418 else: 1419 return self[name]
1420 1421 @staticmethod
1422 - def format(formatv, value):
1423 """for retro compatibility""" 1424 1425 logger.debug("please use f77_formatting instead of format") 1426 return self.f77_formatting(value, formatv=formatv)
1427 1428 @staticmethod
1429 - def f77_formatting(value, formatv=None):
1430 """format the variable into fortran. The type is detected by default""" 1431 1432 if not formatv: 1433 if isinstance(value, bool): 1434 formatv = 'bool' 1435 elif isinstance(value, int): 1436 formatv = 'int' 1437 elif isinstance(value, float): 1438 formatv = 'float' 1439 elif isinstance(value, str): 1440 formatv = 'str' 1441 else: 1442 logger.debug("unknow format for f77_formatting: %s" , value) 1443 formatv = 'str' 1444 else: 1445 assert formatv 1446 1447 if formatv == 'bool': 1448 if str(value) in ['1','T','.true.','True']: 1449 return '.true.' 1450 else: 1451 return '.false.' 1452 1453 elif formatv == 'int': 1454 try: 1455 return str(int(value)) 1456 except ValueError: 1457 fl = float(value) 1458 if int(fl) == fl: 1459 return str(int(fl)) 1460 else: 1461 raise 1462 1463 elif formatv == 'float': 1464 if isinstance(value, str): 1465 value = value.replace('d','e') 1466 return ('%.10e' % float(value)).replace('e','d') 1467 1468 elif formatv == 'str': 1469 return "'%s'" % value
1470 1471 1472
1473 - def write_include_file(self, output_file):
1474 """ """ 1475 1476 # ensure that all parameter are coherent and fix those if needed 1477 self.check_validity() 1478 1479 fsock = file_writers.FortranWriter(output_file) 1480 for key in self: 1481 if key in self.not_in_include: 1482 continue 1483 1484 #define the fortran name 1485 if key in self.fortran_name: 1486 fortran_name = self.fortran_name[key] 1487 else: 1488 fortran_name = key 1489 1490 #get the value with warning if the user didn't set it 1491 value = self.get_default(key) 1492 # Special treatment for strings containing a list of 1493 # strings. Convert it to a list of strings 1494 if isinstance(value, list): 1495 # in case of a list, add the length of the list as 0th 1496 # element in fortran. Only in case of integer or float 1497 # list (not for bool nor string) 1498 if isinstance(value[0], bool): 1499 pass 1500 elif isinstance(value[0], int): 1501 line = '%s(%s) = %s \n' % (fortran_name, 0, self.f77_formatting(len(value))) 1502 fsock.writelines(line) 1503 elif isinstance(value[0], float): 1504 line = '%s(%s) = %s \n' % (fortran_name, 0, self.f77_formatting(float(len(value)))) 1505 fsock.writelines(line) 1506 # output the rest of the list in fortran 1507 for i,v in enumerate(value): 1508 line = '%s(%s) = %s \n' % (fortran_name, i+1, self.f77_formatting(v)) 1509 fsock.writelines(line) 1510 else: 1511 line = '%s = %s \n' % (fortran_name, self.f77_formatting(value)) 1512 fsock.writelines(line) 1513 fsock.close()
1514 1515
1517 """return a dictionary with the information needed to write 1518 the first line of the <init> block of the lhe file.""" 1519 1520 output = {} 1521 1522 def get_idbmup(lpp): 1523 """return the particle colliding pdg code""" 1524 if lpp in (1,2, -1,-2): 1525 return math.copysign(2212, lpp) 1526 elif lpp in (3,-3): 1527 return math.copysign(11, lpp) 1528 elif lpp == 0: 1529 logger.critical("Fail to write correct idbmup in the lhe file. Please correct those by hand") 1530 return 0 1531 else: 1532 return lpp
1533 1534 1535 output["idbmup1"] = get_idbmup(self['lpp1']) 1536 output["idbmup2"] = get_idbmup(self['lpp2']) 1537 output["ebmup1"] = self["ebeam1"] 1538 output["ebmup2"] = self["ebeam2"] 1539 output["pdfgup1"] = 0 1540 output["pdfgup2"] = 0 1541 output["pdfsup1"] = self.get_pdf_id(self["pdlabel"]) 1542 output["pdfsup2"] = self.get_pdf_id(self["pdlabel"]) 1543 return output
1544
1545 - def get_pdf_id(self, pdf):
1546 if pdf == "lhapdf": 1547 lhaid = self["lhaid"] 1548 if isinstance(lhaid, list): 1549 return lhaid[0] 1550 else: 1551 return lhaid 1552 else: 1553 return {'none': 0, 'mrs02nl':20250, 'mrs02nn':20270, 'cteq4_m': 19150, 1554 'cteq4_l':19170, 'cteq4_d':19160, 'cteq5_m':19050, 1555 'cteq5_d':19060,'cteq5_l':19070,'cteq5m1':19051, 1556 'cteq6_m':10000,'cteq6_l':10041,'cteq6l1':10042, 1557 'nn23lo':246800,'nn23lo1':247000,'nn23nlo':244800 1558 }[pdf]
1559
1560 - def get_lhapdf_id(self):
1561 return self.get_pdf_id(self['pdlabel'])
1562
1563 - def remove_all_cut(self):
1564 """remove all the cut""" 1565 1566 for name in self.cuts_parameter: 1567 targettype = type(self[name]) 1568 if targettype == bool: 1569 self[name] = False 1570 elif 'min' in name: 1571 self[name] = 0 1572 elif 'max' in name: 1573 self[name] = -1 1574 elif 'eta' in name: 1575 self[name] = -1 1576 else: 1577 self[name] = 0 1578
1579 -class RunCardLO(RunCard):
1580 """an object to handle in a nice way the run_card infomration""" 1581
1582 - def default_setup(self):
1583 """default value for the run_card.dat""" 1584 1585 self.add_param("run_tag", "tag_1", include=False) 1586 self.add_param("gridpack", False) 1587 self.add_param("time_of_flight", -1.0, include=False, hidden=True) 1588 self.add_param("nevents", 10000) 1589 self.add_param("iseed", 0) 1590 self.add_param("lpp1", 1, fortran_name="lpp(1)") 1591 self.add_param("lpp2", 1, fortran_name="lpp(2)") 1592 self.add_param("ebeam1", 6500.0, fortran_name="ebeam(1)") 1593 self.add_param("ebeam2", 6500.0, fortran_name="ebeam(2)") 1594 self.add_param("polbeam1", 0.0, fortran_name="pb1") 1595 self.add_param("polbeam2", 0.0, fortran_name="pb2") 1596 self.add_param("pdlabel", "nn23lo1") 1597 self.add_param("lhaid", 230000, hidden=True) 1598 self.add_param("fixed_ren_scale", False) 1599 self.add_param("fixed_fac_scale", False) 1600 self.add_param("scale", 91.1880) 1601 self.add_param("dsqrt_q2fact1", 91.1880, fortran_name="sf1") 1602 self.add_param("dsqrt_q2fact2", 91.1880, fortran_name="sf2") 1603 self.add_param("dynamical_scale_choice", -1) 1604 1605 #matching 1606 self.add_param("scalefact", 1.0) 1607 self.add_param("ickkw", 0) 1608 self.add_param("highestmult", 1, fortran_name="nhmult") 1609 self.add_param("ktscheme", 1) 1610 self.add_param("alpsfact", 1.0) 1611 self.add_param("chcluster", False) 1612 self.add_param("pdfwgt", True) 1613 self.add_param("asrwgtflavor", 5) 1614 self.add_param("clusinfo", True) 1615 self.add_param("lhe_version", 3.0) 1616 #cut 1617 self.add_param("auto_ptj_mjj", True) 1618 self.add_param("bwcutoff", 15.0) 1619 self.add_param("cut_decays", False) 1620 self.add_param("nhel", 0, include=False) 1621 #pt cut 1622 self.add_param("ptj", 20.0, cut=True) 1623 self.add_param("ptb", 0.0, cut=True) 1624 self.add_param("pta", 10.0, cut=True) 1625 self.add_param("ptl", 10.0, cut=True) 1626 self.add_param("misset", 0.0, cut=True) 1627 self.add_param("ptheavy", 0.0, cut=True) 1628 self.add_param("ptonium", 1.0, legacy=True) 1629 self.add_param("ptjmax", -1.0, cut=True) 1630 self.add_param("ptbmax", -1.0, cut=True) 1631 self.add_param("ptamax", -1.0, cut=True) 1632 self.add_param("ptlmax", -1.0, cut=True) 1633 self.add_param("missetmax", -1.0, cut=True) 1634 # E cut 1635 self.add_param("ej", 0.0, cut=True) 1636 self.add_param("eb", 0.0, cut=True) 1637 self.add_param("ea", 0.0, cut=True) 1638 self.add_param("el", 0.0, cut=True) 1639 self.add_param("ejmax", -1.0, cut=True) 1640 self.add_param("ebmax", -1.0, cut=True) 1641 self.add_param("eamax", -1.0, cut=True) 1642 self.add_param("elmax", -1.0, cut=True) 1643 # Eta cut 1644 self.add_param("etaj", 5.0, cut=True) 1645 self.add_param("etab", -1.0, cut=True) 1646 self.add_param("etaa", 2.5, cut=True) 1647 self.add_param("etal", 2.5, cut=True) 1648 self.add_param("etaonium", 0.6, legacy=True) 1649 self.add_param("etajmin", 0.0, cut=True) 1650 self.add_param("etabmin", 0.0, cut=True) 1651 self.add_param("etaamin", 0.0, cut=True) 1652 self.add_param("etalmin", 0.0, cut=True) 1653 # DRJJ 1654 self.add_param("drjj", 0.4, cut=True) 1655 self.add_param("drbb", 0.0, cut=True) 1656 self.add_param("drll", 0.4, cut=True) 1657 self.add_param("draa", 0.4, cut=True) 1658 self.add_param("drbj", 0.0, cut=True) 1659 self.add_param("draj", 0.4, cut=True) 1660 self.add_param("drjl", 0.4, cut=True) 1661 self.add_param("drab", 0.0, cut=True) 1662 self.add_param("drbl", 0.0, cut=True) 1663 self.add_param("dral", 0.4, cut=True) 1664 self.add_param("drjjmax", -1.0, cut=True) 1665 self.add_param("drbbmax", -1.0, cut=True) 1666 self.add_param("drllmax", -1.0, cut=True) 1667 self.add_param("draamax", -1.0, cut=True) 1668 self.add_param("drbjmax", -1.0, cut=True) 1669 self.add_param("drajmax", -1.0, cut=True) 1670 self.add_param("drjlmax", -1.0, cut=True) 1671 self.add_param("drabmax", -1.0, cut=True) 1672 self.add_param("drblmax", -1.0, cut=True) 1673 self.add_param("dralmax", -1.0, cut=True) 1674 # invariant mass 1675 self.add_param("mmjj", 0.0, cut=True) 1676 self.add_param("mmbb", 0.0, cut=True) 1677 self.add_param("mmaa", 0.0, cut=True) 1678 self.add_param("mmll", 0.0, cut=True) 1679 self.add_param("mmjjmax", -1.0, cut=True) 1680 self.add_param("mmbbmax", -1.0, cut=True) 1681 self.add_param("mmaamax", -1.0, cut=True) 1682 self.add_param("mmllmax", -1.0, cut=True) 1683 self.add_param("mmnl", 0.0, cut=True) 1684 self.add_param("mmnlmax", -1.0, cut=True) 1685 #minimum/max pt for sum of leptons 1686 self.add_param("ptllmin", 0.0, cut=True) 1687 self.add_param("ptllmax", -1.0, cut=True) 1688 self.add_param("xptj", 0.0, cut=True) 1689 self.add_param("xptb", 0.0, cut=True) 1690 self.add_param("xpta", 0.0, cut=True) 1691 self.add_param("xptl", 0.0, cut=True) 1692 # ordered pt jet 1693 self.add_param("ptj1min", 0.0, cut=True) 1694 self.add_param("ptj1max", -1.0, cut=True) 1695 self.add_param("ptj2min", 0.0, cut=True) 1696 self.add_param("ptj2max", -1.0, cut=True) 1697 self.add_param("ptj3min", 0.0, cut=True) 1698 self.add_param("ptj3max", -1.0, cut=True) 1699 self.add_param("ptj4min", 0.0, cut=True) 1700 self.add_param("ptj4max", -1.0, cut=True) 1701 self.add_param("cutuse", 0, cut=True) 1702 # ordered pt lepton 1703 self.add_param("ptl1min", 0.0, cut=True) 1704 self.add_param("ptl1max", -1.0, cut=True) 1705 self.add_param("ptl2min", 0.0, cut=True) 1706 self.add_param("ptl2max", -1.0, cut=True) 1707 self.add_param("ptl3min", 0.0, cut=True) 1708 self.add_param("ptl3max", -1.0, cut=True) 1709 self.add_param("ptl4min", 0.0, cut=True) 1710 self.add_param("ptl4max", -1.0, cut=True) 1711 # Ht sum of jets 1712 self.add_param("htjmin", 0.0, cut=True) 1713 self.add_param("htjmax", -1.0, cut=True) 1714 self.add_param("ihtmin", 0.0, cut=True) 1715 self.add_param("ihtmax", -1.0, cut=True) 1716 self.add_param("ht2min", 0.0, cut=True) 1717 self.add_param("ht3min", 0.0, cut=True) 1718 self.add_param("ht4min", 0.0, cut=True) 1719 self.add_param("ht2max", -1.0, cut=True) 1720 self.add_param("ht3max", -1.0, cut=True) 1721 self.add_param("ht4max", -1.0, cut=True) 1722 # photon isolation 1723 self.add_param("ptgmin", 0.0, cut=True) 1724 self.add_param("r0gamma", 0.4) 1725 self.add_param("xn", 1.0) 1726 self.add_param("epsgamma", 1.0) 1727 self.add_param("isoem", True) 1728 self.add_param("xetamin", 0.0, cut=True) 1729 self.add_param("deltaeta", 0.0, cut=True) 1730 self.add_param("ktdurham", -1.0, fortran_name="kt_durham", cut=True) 1731 self.add_param("dparameter", 0.4, fortran_name="d_parameter", cut=True) 1732 self.add_param("maxjetflavor", 4) 1733 self.add_param("xqcut", 0.0, cut=True) 1734 self.add_param("use_syst", True) 1735 self.add_param("sys_scalefact", "0.5 1 2", include=False) 1736 self.add_param("sys_alpsfact", "None", include=False) 1737 self.add_param("sys_matchscale", "30 50", include=False) 1738 self.add_param("sys_pdf", "NNPDF23_lo_as_0130_qed", include=False) 1739 self.add_param("sys_scalecorrelation", -1, include=False) 1740 1741 #parameter not in the run_card by default 1742 self.add_param('gridrun', False, hidden=True) 1743 self.add_param('fixed_couplings', True, hidden=True) 1744 self.add_param('mc_grouped_subproc', True, hidden=True) 1745 self.add_param('xmtcentral', 0.0, hidden=True, fortran_name="xmtc") 1746 self.add_param('d', 1.0, hidden=True) 1747 self.add_param('gseed', 0, hidden=True, include=False) 1748 self.add_param('issgridfile', '', hidden=True) 1749 #job handling of the survey/ refine 1750 self.add_param('job_strategy', 0, hidden=True, include=False) 1751 self.add_param('survey_splitting', -1, hidden=True, include=False) 1752 self.add_param('refine_evt_by_job', -1, hidden=True, include=False)
1753 1754 1755 1756
1757 - def check_validity(self):
1758 """ """ 1759 #Make sure that nhel is only either 0 (i.e. no MC over hel) or 1760 #1 (MC over hel with importance sampling). In particular, it can 1761 #no longer be > 1. 1762 if 'nhel' not in self.user_set: 1763 raise InvalidRunCard, "Parameter nhel is not defined in the run_card." 1764 if self['nhel'] not in [1,0]: 1765 raise InvalidRunCard, "Parameter nhel can only be '0' or '1', "+\ 1766 "not %s." % self['nhel'] 1767 if int(self['maxjetflavor']) > 6: 1768 raise InvalidRunCard, 'maxjetflavor should be lower than 5! (6 is partly supported)' 1769 1770 # some cut need to be deactivated in presence of isolation 1771 if self['ptgmin'] > 0: 1772 if self['pta'] > 0: 1773 logger.warning('pta cut discarded since photon isolation is used') 1774 self['pta'] = 0.0 1775 if self['draj'] > 0: 1776 logger.warning('draj cut discarded since photon isolation is used') 1777 self['draj'] = 0.0 1778 1779 # special treatment for gridpack use the gseed instead of the iseed 1780 if self['gridrun']: 1781 self['iseed'] = self['gseed'] 1782 1783 #Some parameter need to be fixed when using syscalc 1784 if self['use_syst']: 1785 if self['scalefact'] != 1.0: 1786 logger.warning('Since use_syst=T, We change the value of \'scalefact\' to 1') 1787 self['scalefact'] = 1.0 1788 1789 # CKKW Treatment 1790 if self['ickkw'] > 0: 1791 if self['use_syst']: 1792 # some additional parameter need to be fixed for Syscalc + matching 1793 if self['alpsfact'] != 1.0: 1794 logger.warning('Since use_syst=T, We change the value of \'alpsfact\' to 1') 1795 self['alpsfact'] =1.0 1796 if self['maxjetflavor'] == 6: 1797 raise InvalidRunCard, 'maxjetflavor at 6 is NOT supported for matching!' 1798 if self['ickkw'] == 2: 1799 # add warning if ckkw selected but the associate parameter are empty 1800 self.get_default('highestmult', log_level=20) 1801 self.get_default('issgridfile', 'issudgrid.dat', log_level=20) 1802 if self['xqcut'] > 0: 1803 if self['drjj'] != 0: 1804 logger.warning('Since icckw>0, We change the value of \'drjj\' to 0') 1805 self['drjj'] = 0 1806 if self['drjl'] != 0: 1807 logger.warning('Since icckw>0, We change the value of \'drjl\' to 0') 1808 self['drjl'] = 0 1809 if not self['auto_ptj_mjj']: 1810 if self['mmjj'] > self['xqcut']: 1811 logger.warning('mmjj > xqcut (and auto_ptj_mjj = F). MMJJ set to 0') 1812 self['mmjj'] = 0.0 1813 1814 1815 # check validity of the pdf set 1816 possible_set = ['lhapdf','mrs02nl','mrs02nn', 'mrs0119','mrs0117','mrs0121','mrs01_j', 'mrs99_1','mrs99_2','mrs99_3','mrs99_4','mrs99_5','mrs99_6', 'mrs99_7','mrs99_8','mrs99_9','mrs9910','mrs9911','mrs9912', 'mrs98z1','mrs98z2','mrs98z3','mrs98z4','mrs98z5','mrs98ht', 'mrs98l1','mrs98l2','mrs98l3','mrs98l4','mrs98l5', 'cteq3_m','cteq3_l','cteq3_d', 'cteq4_m','cteq4_d','cteq4_l','cteq4a1','cteq4a2', 'cteq4a3','cteq4a4','cteq4a5','cteq4hj','cteq4lq', 'cteq5_m','cteq5_d','cteq5_l','cteq5hj','cteq5hq', 'cteq5f3','cteq5f4','cteq5m1','ctq5hq1','cteq5l1', 'cteq6_m','cteq6_d','cteq6_l','cteq6l1', 'nn23lo','nn23lo1','nn23nlo'] 1817 if self['pdlabel'] not in possible_set: 1818 raise InvalidRunCard, 'Invalid PDF set (argument of pdlabel): %s. Possible choice are:\n %s' % (self['pdlabel'], ', '.join(possible_set)) 1819 if self['pdlabel'] == 'lhapdf': 1820 #add warning if lhaid not define 1821 self.get_default('lhaid', log_level=20) 1822 1823 for name in self.legacy_parameter: 1824 if self[name] != self.legacy_parameter[name]: 1825 logger.warning("The parameter %s is not supported anymore this parameter will be ignored." % name)
1826 1827 1828 1829
1830 - def create_default_for_process(self, proc_characteristic, history, proc_def):
1831 """Rules 1832 process 1->N all cut set on off. 1833 loop_induced -> MC over helicity 1834 e+ e- beam -> lpp:0 ebeam:500 1835 p p beam -> set maxjetflavor automatically 1836 more than one multiplicity: ickkw=1 xqcut=30 use_syst=F 1837 """ 1838 1839 if proc_characteristic['loop_induced']: 1840 self['nhel'] = 1 1841 1842 if proc_characteristic['ninitial'] == 1: 1843 #remove all cut 1844 self.remove_all_cut() 1845 self['use_syst'] = False 1846 else: 1847 # check for beam_id 1848 beam_id = set() 1849 for proc in proc_def: 1850 for oneproc in proc: 1851 for leg in oneproc['legs']: 1852 if not leg['state']: 1853 beam_id.add(leg['id']) 1854 if any(i in beam_id for i in [1,-1,2,-2,3,-3,4,-4,5,-5,21,22]): 1855 maxjetflavor = max([4]+[abs(i) for i in beam_id if -7< i < 7]) 1856 self['maxjetflavor'] = maxjetflavor 1857 self['asrwgtflavor'] = maxjetflavor 1858 pass 1859 elif 11 in beam_id or -11 in beam_id: 1860 self['lpp1'] = 0 1861 self['lpp2'] = 0 1862 self['ebeam1'] = 500 1863 self['ebeam2'] = 500 1864 else: 1865 self['lpp1'] = 0 1866 self['lpp2'] = 0 1867 1868 # Check if need matching 1869 min_particle = 99 1870 max_particle = 0 1871 for proc in proc_def: 1872 min_particle = min(len(proc[0]['legs']), min_particle) 1873 max_particle = max(len(proc[0]['legs']), max_particle) 1874 if min_particle != max_particle: 1875 #take one of the process with min_particle 1876 for procmin in proc_def: 1877 if len(procmin[0]['legs']) != min_particle: 1878 continue 1879 else: 1880 idsmin = [l['id'] for l in procmin[0]['legs']] 1881 break 1882 matching = False 1883 for procmax in proc_def: 1884 if len(procmax[0]['legs']) != max_particle: 1885 continue 1886 idsmax = [l['id'] for l in procmax[0]['legs']] 1887 for i in idsmin: 1888 if i not in idsmax: 1889 continue 1890 else: 1891 idsmax.remove(i) 1892 for j in idsmax: 1893 if j not in [1,-1,2,-2,3,-3,4,-4,5,-5,21]: 1894 break 1895 else: 1896 # all are jet => matching is ON 1897 matching=True 1898 break 1899 1900 if matching: 1901 self['ickkw'] = 1 1902 self['xqcut'] = 30 1903 self['use_syst'] = False 1904 self['drjj'] = 0 1905 self['drjl'] = 0 1906 self['sys_alpsfact'] = "0.5 1 2"
1907 1908
1909 - def write(self, output_file, template=None, python_template=False):
1910 """Write the run_card in output_file according to template 1911 (a path to a valid run_card)""" 1912 1913 if not template: 1914 if not MADEVENT: 1915 template = pjoin(MG5DIR, 'Template', 'LO', 'Cards', 1916 'run_card.dat') 1917 python_template = True 1918 else: 1919 template = pjoin(MEDIR, 'Cards', 'run_card_default.dat') 1920 python_template = False 1921 1922 super(RunCardLO, self).write(output_file, template=template, 1923 python_template=python_template)
1924
1925 1926 -class RunCardNLO(RunCard):
1927 """A class object for the run_card for a (aMC@)NLO pocess""" 1928 1929
1930 - def default_setup(self):
1931 """define the default value""" 1932 1933 self.add_param('run_tag', 'tag_1', include=False) 1934 self.add_param('nevents', 10000) 1935 self.add_param('req_acc', -1.0, include=False) 1936 self.add_param('nevt_job', -1, include=False) 1937 self.add_param('event_norm', 'average') 1938 #FO parameter 1939 self.add_param('req_acc_fo', 0.01, include=False) 1940 self.add_param('npoints_fo_grid', 5000, include=False) 1941 self.add_param('niters_fo_grid', 4, include=False) 1942 self.add_param('npoints_fo', 10000, include=False) 1943 self.add_param('niters_fo', 6, include=False) 1944 #seed and collider 1945 self.add_param('iseed', 0) 1946 self.add_param('lpp1', 1, fortran_name='lpp(1)') 1947 self.add_param('lpp2', 1, fortran_name='lpp(2)') 1948 self.add_param('ebeam1', 6500.0, fortran_name='ebeam(1)') 1949 self.add_param('ebeam2', 6500.0, fortran_name='ebeam(2)') 1950 self.add_param('pdlabel', 'nn23nlo') 1951 self.add_param('lhaid', [244600],fortran_name='lhaPDFid') 1952 self.add_param('lhapdfsetname', ['internal_use_only'], system=True) 1953 #shower and scale 1954 self.add_param('parton_shower', 'HERWIG6', fortran_name='shower_mc') 1955 self.add_param('shower_scale_factor',1.0) 1956 self.add_param('fixed_ren_scale', False) 1957 self.add_param('fixed_fac_scale', False) 1958 self.add_param('mur_ref_fixed', 91.118) 1959 self.add_param('muf1_ref_fixed', -1.0, hidden=True) 1960 self.add_param('muf_ref_fixed', 91.118) 1961 self.add_param('muf2_ref_fixed', -1.0, hidden=True) 1962 self.add_param("dynamical_scale_choice", [-1],fortran_name='dyn_scale') 1963 self.add_param('fixed_qes_scale', False, hidden=True) 1964 self.add_param('qes_ref_fixed', -1.0, hidden=True) 1965 self.add_param('mur_over_ref', 1.0) 1966 self.add_param('muf_over_ref', 1.0) 1967 self.add_param('muf1_over_ref', -1.0, hidden=True) 1968 self.add_param('muf2_over_ref', -1.0, hidden=True) 1969 self.add_param('qes_over_ref', -1.0, hidden=True) 1970 self.add_param('reweight_scale', [True], fortran_name='lscalevar') 1971 self.add_param('rw_rscale_down', -1.0, hidden=True) 1972 self.add_param('rw_rscale_up', -1.0, hidden=True) 1973 self.add_param('rw_fscale_down', -1.0, hidden=True) 1974 self.add_param('rw_fscale_up', -1.0, hidden=True) 1975 self.add_param('rw_rscale', [1.0,2.0,0.5], fortran_name='scalevarR') 1976 self.add_param('rw_fscale', [1.0,2.0,0.5], fortran_name='scalevarF') 1977 self.add_param('reweight_pdf', [False], fortran_name='lpdfvar') 1978 self.add_param('pdf_set_min', 244601, hidden=True) 1979 self.add_param('pdf_set_max', 244700, hidden=True) 1980 self.add_param('store_rwgt_info', False) 1981 #merging 1982 self.add_param('ickkw', 0) 1983 self.add_param('bwcutoff', 15.0) 1984 #cuts 1985 self.add_param('jetalgo', 1.0) 1986 self.add_param('jetradius', 0.7) 1987 self.add_param('ptj', 10.0 , cut=True) 1988 self.add_param('etaj', -1.0, cut=True) 1989 self.add_param('ptl', 0.0, cut=True) 1990 self.add_param('etal', -1.0, cut=True) 1991 self.add_param('drll', 0.0, cut=True) 1992 self.add_param('drll_sf', 0.0, cut=True) 1993 self.add_param('mll', 0.0, cut=True) 1994 self.add_param('mll_sf', 30.0, cut=True) 1995 self.add_param('ptgmin', 20.0, cut=True) 1996 self.add_param('etagamma', -1.0) 1997 self.add_param('r0gamma', 0.4) 1998 self.add_param('xn', 1.0) 1999 self.add_param('epsgamma', 1.0) 2000 self.add_param('isoem', True) 2001 self.add_param('maxjetflavor', 4, hidden=True) 2002 self.add_param('iappl', 0) 2003 self.add_param('lhe_version', 3, hidden=True, include=False)
2004
2005 - def check_validity(self):
2006 """check the validity of the various input""" 2007 2008 # For FxFx merging, make sure that the following parameters are set correctly: 2009 if self['ickkw'] == 3: 2010 # 1. Renormalization and factorization (and ellis-sexton scales) are not fixed 2011 scales=['fixed_ren_scale','fixed_fac_scale','fixed_QES_scale'] 2012 for scale in scales: 2013 if self[scale]: 2014 logger.warning('''For consistency in the FxFx merging, \'%s\' has been set to false''' 2015 % scale,'$MG:color:BLACK') 2016 self[scale]= False 2017 #and left to default dynamical scale 2018 if len(self["dynamical_scale_choice"]) > 1 or self["dynamical_scale_choice"][0] != -1: 2019 self["dynamical_scale_choice"] = [-1] 2020 self["reweight_scale"]=[self["reweight_scale"][0]] 2021 logger.warning('''For consistency in the FxFx merging, dynamical_scale_choice has been set to -1 (default)''' 2022 ,'$MG:color:BLACK') 2023 2024 # 2. Use kT algorithm for jets with pseudo-code size R=1.0 2025 jetparams=['jetradius','jetalgo'] 2026 for jetparam in jetparams: 2027 if float(self[jetparam]) != 1.0: 2028 logger.info('''For consistency in the FxFx merging, \'%s\' has been set to 1.0''' 2029 % jetparam ,'$MG:color:BLACK') 2030 self[jetparam] = 1.0 2031 elif self['ickkw'] == -1 and (self["dynamical_scale_choice"][0] != -1 or 2032 len(self["dynamical_scale_choice"]) > 1): 2033 self["dynamical_scale_choice"] = [-1] 2034 self["reweight_scale"]=[self["reweight_scale"][0]] 2035 logger.warning('''For consistency with the jet veto, the scale which will be used is ptj. dynamical_scale_choice will be set at -1.''' 2036 ,'$MG:color:BLACK') 2037 2038 # For interface to APPLGRID, need to use LHAPDF and reweighting to get scale uncertainties 2039 if self['iappl'] != 0 and self['pdlabel'].lower() != 'lhapdf': 2040 raise InvalidRunCard('APPLgrid generation only possible with the use of LHAPDF') 2041 if self['iappl'] != 0 and not self['reweight_scale']: 2042 raise InvalidRunCard('APPLgrid generation only possible with including' +\ 2043 ' the reweighting to get scale dependence') 2044 2045 # check that the pdf is set correctly 2046 possible_set = ['lhapdf','mrs02nl','mrs02nn', 'mrs0119','mrs0117','mrs0121','mrs01_j', 'mrs99_1','mrs99_2','mrs99_3','mrs99_4','mrs99_5','mrs99_6', 'mrs99_7','mrs99_8','mrs99_9','mrs9910','mrs9911','mrs9912', 'mrs98z1','mrs98z2','mrs98z3','mrs98z4','mrs98z5','mrs98ht', 'mrs98l1','mrs98l2','mrs98l3','mrs98l4','mrs98l5', 'cteq3_m','cteq3_l','cteq3_d', 'cteq4_m','cteq4_d','cteq4_l','cteq4a1','cteq4a2', 'cteq4a3','cteq4a4','cteq4a5','cteq4hj','cteq4lq', 'cteq5_m','cteq5_d','cteq5_l','cteq5hj','cteq5hq', 'cteq5f3','cteq5f4','cteq5m1','ctq5hq1','cteq5l1', 'cteq6_m','cteq6_d','cteq6_l','cteq6l1', 'nn23lo','nn23lo1','nn23nlo'] 2047 if self['pdlabel'] not in possible_set: 2048 raise InvalidRunCard, 'Invalid PDF set (argument of pdlabel) possible choice are:\n %s' % ','.join(possible_set) 2049 2050 # Hidden values check 2051 if self['qes_ref_fixed'] == -1.0: 2052 self['qes_ref_fixed']=self['mur_ref_fixed'] 2053 if self['qes_over_ref'] == -1.0: 2054 self['qes_over_ref']=self['mur_over_ref'] 2055 if self['muf1_over_ref'] != -1.0 and self['muf1_over_ref'] == self['muf2_over_ref']: 2056 self['muf_over_ref']=self['muf1_over_ref'] 2057 if self['muf1_over_ref'] == -1.0: 2058 self['muf1_over_ref']=self['muf_over_ref'] 2059 if self['muf2_over_ref'] == -1.0: 2060 self['muf2_over_ref']=self['muf_over_ref'] 2061 if self['muf1_ref_fixed'] != -1.0 and self['muf1_ref_fixed'] == self['muf2_ref_fixed']: 2062 self['muf_ref_fixed']=self['muf1_ref_fixed'] 2063 if self['muf1_ref_fixed'] == -1.0: 2064 self['muf1_ref_fixed']=self['muf_ref_fixed'] 2065 if self['muf2_ref_fixed'] == -1.0: 2066 self['muf2_ref_fixed']=self['muf_ref_fixed'] 2067 # overwrite rw_rscale and rw_fscale when rw_(r/f)scale_(down/up) are explicitly given in the run_card for backward compatibility. 2068 if (self['rw_rscale_down'] != -1.0 and ['rw_rscale_down'] not in self['rw_rscale']) or\ 2069 (self['rw_rscale_up'] != -1.0 and ['rw_rscale_up'] not in self['rw_rscale']): 2070 self['rw_rscale']=[1.0,self['rw_rscale_up'],self['rw_rscale_down']] 2071 if (self['rw_fscale_down'] != -1.0 and ['rw_fscale_down'] not in self['rw_fscale']) or\ 2072 (self['rw_fscale_up'] != -1.0 and ['rw_fscale_up'] not in self['rw_fscale']): 2073 self['rw_fscale']=[1.0,self['rw_fscale_up'],self['rw_fscale_down']] 2074 2075 # PDF reweighting check 2076 if any(self['reweight_pdf']): 2077 # check that we use lhapdf if reweighting is ON 2078 if self['pdlabel'] != "lhapdf": 2079 raise InvalidRunCard, 'Reweight PDF option requires to use pdf sets associated to lhapdf. Please either change the pdlabel to use LHAPDF or set reweight_pdf to False.' 2080 2081 # make sure set have reweight_pdf and lhaid of length 1 when not including lhapdf 2082 if self['pdlabel'] != "lhapdf": 2083 self['reweight_pdf']=[self['reweight_pdf'][0]] 2084 self['lhaid']=[self['lhaid'][0]] 2085 2086 # make sure set have reweight_scale and dyn_scale_choice of length 1 when fixed scales: 2087 if self['fixed_ren_scale'] and self['fixed_fac_scale']: 2088 self['reweight_scale']=[self['reweight_scale'][0]] 2089 self['dynamical_scale_choice']=[0] 2090 2091 # If there is only one reweight_pdf/reweight_scale, but 2092 # lhaid/dynamical_scale_choice are longer, expand the 2093 # reweight_pdf/reweight_scale list to have the same length 2094 if len(self['reweight_pdf']) == 1 and len(self['lhaid']) != 1: 2095 self['reweight_pdf']=self['reweight_pdf']*len(self['lhaid']) 2096 logger.warning("Setting 'reweight_pdf' for all 'lhaid' to %s" % self['reweight_pdf'][0]) 2097 if len(self['reweight_scale']) == 1 and len(self['dynamical_scale_choice']) != 1: 2098 self['reweight_scale']=self['reweight_scale']*len(self['dynamical_scale_choice']) 2099 logger.warning("Setting 'reweight_scale' for all 'dynamical_scale_choice' to %s" % self['reweight_pdf'][0]) 2100 2101 2102 # Check that there are no identical elements in lhaid or dynamical_scale_choice 2103 if len(self['lhaid']) != len(set(self['lhaid'])): 2104 raise InvalidRunCard, "'lhaid' has two or more identical entries. They have to be all different for the code to work correctly." 2105 if len(self['dynamical_scale_choice']) != len(set(self['dynamical_scale_choice'])): 2106 raise InvalidRunCard, "'dynamical_scale_choice' has two or more identical entries. They have to be all different for the code to work correctly." 2107 2108 # Check that lenght of lists are consistent 2109 if len(self['reweight_pdf']) != len(self['lhaid']): 2110 raise InvalidRunCard, "'reweight_pdf' and 'lhaid' lists should have the same length" 2111 if len(self['reweight_scale']) != len(self['dynamical_scale_choice']): 2112 raise InvalidRunCard, "'reweight_scale' and 'dynamical_scale_choice' lists should have the same length" 2113 if len(self['dynamical_scale_choice']) > 10 : 2114 raise InvalidRunCard, "Length of list for 'dynamical_scale_choice' too long: max is 10." 2115 if len(self['lhaid']) > 10 : 2116 raise InvalidRunCard, "Length of list for 'lhaid' too long: max is 10." 2117 if len(self['rw_rscale']) > 9 : 2118 raise InvalidRunCard, "Length of list for 'rw_rscale' too long: max is 9." 2119 if len(self['rw_fscale']) > 9 : 2120 raise InvalidRunCard, "Length of list for 'rw_fscale' too long: max is 9." 2121 # make sure that the first element of rw_rscale and rw_fscale is the 1.0 2122 if 1.0 not in self['rw_rscale']: 2123 logger.warning("'1.0' has to be part of 'rw_rscale', adding it") 2124 self['rw_rscale'].insert(0,1.0) 2125 if 1.0 not in self['rw_fscale']: 2126 logger.warning("'1.0' has to be part of 'rw_fscale', adding it") 2127 self['rw_fscale'].insert(0,1.0) 2128 if self['rw_rscale'][0] != 1.0 and 1.0 in self['rw_rscale']: 2129 a=self['rw_rscale'].index(1.0) 2130 self['rw_rscale'][0],self['rw_rscale'][a]=self['rw_rscale'][a],self['rw_rscale'][0] 2131 if self['rw_fscale'][0] != 1.0 and 1.0 in self['rw_fscale']: 2132 a=self['rw_fscale'].index(1.0) 2133 self['rw_fscale'][0],self['rw_fscale'][a]=self['rw_fscale'][a],self['rw_fscale'][0] 2134 # check that all elements of rw_rscale and rw_fscale are diffent. 2135 if len(self['rw_rscale']) != len(set(self['rw_rscale'])): 2136 raise InvalidRunCard, "'rw_rscale' has two or more identical entries. They have to be all different for the code to work correctly." 2137 if len(self['rw_fscale']) != len(set(self['rw_fscale'])): 2138 raise InvalidRunCard, "'rw_fscale' has two or more identical entries. They have to be all different for the code to work correctly."
2139 2140
2141 - def write(self, output_file, template=None, python_template=False):
2142 """Write the run_card in output_file according to template 2143 (a path to a valid run_card)""" 2144 2145 if not template: 2146 if not MADEVENT: 2147 template = pjoin(MG5DIR, 'Template', 'NLO', 'Cards', 2148 'run_card.dat') 2149 python_template = True 2150 else: 2151 template = pjoin(MEDIR, 'Cards', 'run_card_default.dat') 2152 python_template = False 2153 2154 super(RunCardNLO, self).write(output_file, template=template, 2155 python_template=python_template)
2156 2157
2158 - def create_default_for_process(self, proc_characteristic, history, proc_def):
2159 """Rules 2160 e+ e- beam -> lpp:0 ebeam:500 2161 p p beam -> set maxjetflavor automatically 2162 """ 2163 2164 # check for beam_id 2165 beam_id = set() 2166 for proc in proc_def: 2167 for leg in proc['legs']: 2168 if not leg['state']: 2169 beam_id.add(leg['id']) 2170 if any(i in beam_id for i in [1,-1,2,-2,3,-3,4,-4,5,-5,21,22]): 2171 maxjetflavor = max([4]+[abs(i) for i in beam_id if -7< i < 7]) 2172 self['maxjetflavor'] = maxjetflavor 2173 pass 2174 elif 11 in beam_id or -11 in beam_id: 2175 self['lpp1'] = 0 2176 self['lpp2'] = 0 2177 self['ebeam1'] = 500 2178 self['ebeam2'] = 500 2179 else: 2180 self['lpp1'] = 0 2181 self['lpp2'] = 0 2182 2183 if proc_characteristic['ninitial'] == 1: 2184 #remove all cut 2185 self.remove_all_cut()
2186
2187 -class MadLoopParam(ConfigFile):
2188 """ a class for storing/dealing with the file MadLoopParam.dat 2189 contains a parser to read it, facilities to write a new file,... 2190 """ 2191 2192 2193
2194 - def default_setup(self):
2195 """initialize the directory to the default value""" 2196 2197 self.add_param("MLReductionLib", "6|1|2") 2198 self.add_param("IREGIMODE", 2) 2199 self.add_param("IREGIRECY", True) 2200 self.add_param("CTModeRun", -1) 2201 self.add_param("MLStabThres", 1e-3) 2202 self.add_param("NRotations_DP", 1) 2203 self.add_param("NRotations_QP", 0) 2204 self.add_param("ImprovePSPoint", 2) 2205 self.add_param("CTLoopLibrary", 2) 2206 self.add_param("CTStabThres", 1e-2) 2207 self.add_param("CTModeInit", 1) 2208 self.add_param("CheckCycle", 3) 2209 self.add_param("MaxAttempts", 10) 2210 self.add_param("ZeroThres", 1e-9) 2211 self.add_param("OSThres", 1.0e-8) 2212 self.add_param("DoubleCheckHelicityFilter", True) 2213 self.add_param("WriteOutFilters", True) 2214 self.add_param("UseLoopFilter", False) 2215 self.add_param("HelicityFilterLevel", 2) 2216 self.add_param("LoopInitStartOver", False) 2217 self.add_param("HelInitStartOver", False) 2218 self.add_param("UseQPIntegrandForNinja", False) 2219 self.add_param("UseQPIntegrandForCutTools", True)
2220
2221 - def read(self, finput):
2222 """Read the input file, this can be a path to a file, 2223 a file object, a str with the content of the file.""" 2224 2225 if isinstance(finput, str): 2226 if "\n" in finput: 2227 finput = finput.split('\n') 2228 elif os.path.isfile(finput): 2229 finput = open(finput) 2230 else: 2231 raise Exception, "No such file %s" % input 2232 2233 previous_line= '' 2234 for line in finput: 2235 if previous_line.startswith('#'): 2236 name = previous_line[1:].split()[0] 2237 value = line.strip() 2238 if len(value) and value[0] not in ['#', '!']: 2239 self.__setitem__(name, value, change_userdefine=True) 2240 previous_line = line
2241 2242
2243 - def write(self, outputpath, template=None,commentdefault=False):
2244 2245 if not template: 2246 if not MADEVENT: 2247 template = pjoin(MG5DIR, 'Template', 'loop_material', 'StandAlone', 2248 'Cards', 'MadLoopParams.dat') 2249 else: 2250 template = pjoin(MEDIR, 'Cards', 'MadLoopParams_default.dat') 2251 fsock = open(template, 'r') 2252 template = fsock.readlines() 2253 fsock.close() 2254 2255 if isinstance(outputpath, str): 2256 output = open(outputpath, 'w') 2257 else: 2258 output = outputpath 2259 2260 def f77format(value): 2261 if isinstance(value, bool): 2262 if value: 2263 return '.true.' 2264 else: 2265 return '.false.' 2266 elif isinstance(value, int): 2267 return value 2268 elif isinstance(value, float): 2269 tmp ='%e' % value 2270 return tmp.replace('e','d') 2271 elif isinstance(value, str): 2272 return value 2273 else: 2274 raise Exception, "Can not format input %s" % type(value)
2275 2276 name = '' 2277 done = set() 2278 for line in template: 2279 if name: 2280 done.add(name) 2281 if commentdefault and name.lower() not in self.user_set : 2282 output.write('!%s\n' % f77format(self[name])) 2283 else: 2284 output.write('%s\n' % f77format(self[name])) 2285 name='' 2286 continue 2287 elif line.startswith('#'): 2288 name = line[1:].split()[0] 2289 output.write(line)
2290