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