Package madgraph :: Package interface :: Module launch_ext_program
[hide private]
[frames] | no frames]

Source Code for Module madgraph.interface.launch_ext_program

  1  ################################################################################ 
  2  # 
  3  # Copyright (c) 2009 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   
 16   
 17  import logging 
 18  import os 
 19  import pydoc 
 20  import subprocess 
 21  import time 
 22  start=time.time() 
 23  import madgraph.iolibs.files as files 
 24  import madgraph.interface.madevent_interface as me_cmd 
 25  import madgraph.various.misc as misc 
 26  import madgraph.various.process_checks as process_checks 
 27  import madgraph.various.banner as banner_mod 
 28   
 29  #from madgraph import MG4DIR, MG5DIR, MadGraph5Error 
 30  #from madgraph.iolibs.files import cp 
 31  pjoin = os.path.join 
 32   
 33   
 34  logger = logging.getLogger('cmdprint.ext_program') 
 35   
 36   
 37   
38 -class ExtLauncher(object):
39 """ Generic Class for executing external program """ 40 41 program_dir = '' 42 executable = '' # path from program_dir 43 44 force = False 45
46 - def __init__(self, cmd, running_dir, card_dir='', **options):
47 """ initialize an object """ 48 49 self.running_dir = running_dir 50 self.card_dir = os.path.join(self.running_dir, card_dir) 51 self.cmd_int = cmd 52 if 'force' in options: 53 self.force = options['force'] 54 55 #include/overwrite options 56 for key,value in options.items(): 57 setattr(self, key, value) 58 59 self.cards = [] # files can be modified (path from self.card_dir)
60
61 - def run(self):
62 """ execute the main code """ 63 64 self.prepare_run() 65 66 import madgraph.interface.common_run_interface as common_run_interface 67 68 self.cmd_int.me_dir = self.running_dir 69 if self.cards: 70 common_run_interface.CommonRunCmd.ask_edit_card_static(self.cards, 71 mode='fixed', plot=False, 72 timeout=0, ask=self.cmd_int.ask, force=self.force) 73 74 #for card in self.cards: 75 # self.treat_input_file(card, default = 'n') 76 77 self.launch_program()
78 79
80 - def prepare_run(self):
81 """ aditional way to prepare the run""" 82 pass
83
84 - def launch_program(self):
85 """launch the main program""" 86 subprocess.call([self.executable], cwd=self.running_dir)
87
88 - def edit_file(self, path):
89 """edit a file""" 90 91 path = os.path.realpath(path) 92 open_file(path)
93 94 95 # Treat Nicely the timeout
96 - def timeout_fct(self,timeout):
97 if timeout: 98 # avoid to always wait a given time for the next answer 99 self.force = True
100
101 - def ask(self, question, default, choices=[], path_msg=None):
102 """nice handling of question""" 103 104 if not self.force: 105 return self.cmd_int.ask(question, default, choices=choices, 106 path_msg=path_msg, fct_timeout=self.timeout_fct) 107 else: 108 return str(default)
109 110
111 - def treat_input_file(self, filename, default=None, msg=''):
112 """ask to edit a file""" 113 114 if msg == '' and filename == 'param_card.dat': 115 msg = \ 116 "WARNING: If you edit this file don\'t forget to consistently "+\ 117 "modify the different parameters,\n especially the width of all "+\ 118 "particles." 119 120 if not self.force: 121 if msg: print msg 122 question = 'Do you want to edit file: %(card)s?' % {'card':filename} 123 choices = ['y', 'n'] 124 path_info = 'path of the new %(card)s' % {'card':os.path.basename(filename)} 125 ans = self.ask(question, default, choices, path_info) 126 else: 127 ans = default 128 129 if ans == 'y': 130 path = os.path.join(self.card_dir, filename) 131 self.edit_file(path) 132 elif ans == 'n': 133 return 134 else: 135 path = os.path.join(self.card_dir, filename) 136 files.cp(ans, path)
137
138 -class MadLoopLauncher(ExtLauncher):
139 """ A class to launch a simple Standalone test """ 140
141 - def __init__(self, cmd_int, running_dir, **options):
142 """ initialize the StandAlone Version """ 143 144 ExtLauncher.__init__(self, cmd_int, running_dir, './Cards', **options) 145 self.cards = ['param_card.dat','MadLoopParams.dat']
146
147 - def prepare_run(self):
148 """ Possible preparatory actions to take.""" 149 pass
150
151 - def treat_input_file(self, filename, default=None, msg='', dir_path=None):
152 """ask to edit a file""" 153 154 if filename == 'PS.input': 155 if not self.force: 156 if msg!='': print msg 157 question = 'Do you want to specify the Phase-Space point: %(card)s?' % {'card':filename} 158 choices = ['y', 'n'] 159 path_info = 'path of the PS.input file' 160 ans = self.ask(question, default, choices, path_info) 161 else: 162 ans = default 163 if ans == 'y': 164 if not os.path.isfile(os.path.join(dir_path,'PS.input')): 165 PSfile = open(os.path.join(dir_path,'PS.input'), 'w') 166 if not os.path.isfile(os.path.join(dir_path,'result.dat')): 167 PSfile.write('\n'.join([' '.join(['%.16E'%0.0 for \ 168 pi in range(4)]) for pmom in range(1)])) 169 else: 170 default_ps = process_checks.LoopMatrixElementEvaluator.\ 171 parse_check_output(file(os.path.join(dir_path,\ 172 'result.dat')),format='dict')['res_p'] 173 PSfile.write('\n'.join([' '.join(['%.16E'%pi for pi \ 174 in pmom]) for pmom in default_ps])) 175 PSfile.write("\n\nEach line number 'i' like the above one sets"+\ 176 " the momentum of particle number i, \nordered like in"+\ 177 " the process definition. The format is (E,px,py,pz).") 178 PSfile.close() 179 self.edit_file(os.path.join(dir_path,'PS.input')) 180 else: 181 super(MadLoopLauncher,self).treat_input_file(filename,default,msg) 182 if filename == 'MadLoopParams.dat': 183 # Make sure to update the changes 184 MadLoopparam = banner_mod.MadLoopParam( 185 os.path.join(self.card_dir, 'MadLoopParams.dat')) 186 # Unless user asked for it, don't doublecheck the helicity filter. 187 MadLoopparam.set('DoubleCheckHelicityFilter', False, 188 changeifuserset=False) 189 MadLoopparam.write(os.path.join(self.card_dir,os.path.pardir, 190 'SubProcesses', 'MadLoopParams.dat'))
191
192 - def launch_program(self):
193 """launch the main program""" 194 evaluator = process_checks.LoopMatrixElementTimer 195 sub_path = os.path.join(self.running_dir, 'SubProcesses') 196 for path in os.listdir(sub_path): 197 if path.startswith('P') and \ 198 os.path.isdir(os.path.join(sub_path, path)): 199 shell_name = path.split('_')[1]+' > '+path.split('_')[2] 200 curr_path = os.path.join(sub_path, path) 201 infos = {} 202 logger.info("Initializing process %s."%shell_name) 203 nps = me_cmd.MadLoopInitializer.run_initialization( 204 curr_path, sub_path, infos, 205 req_files = ['HelFilter.dat','LoopFilter.dat']) 206 if nps == None: 207 raise MadGraph5Error,"MadLoop could not initialize the process %s"\ 208 %shell_name 209 logger.debug(("MadLoop initialization performed for %s"+\ 210 " using %d PS points (%s)")\ 211 %(shell_name,abs(nps),\ 212 'double precision' if nps>0 else 'quadruple precision')) 213 # Ask if the user wants to edit the PS point. 214 self.treat_input_file('PS.input', default='n', 215 msg='Phase-space point for process %s.'%shell_name,\ 216 dir_path=curr_path) 217 # We use mu_r=-1.0 to use the one defined by the user in the 218 # param_car.dat 219 me_cmd.MadLoopInitializer.fix_PSPoint_in_check(sub_path, 220 read_ps = os.path.isfile(os.path.join(curr_path, 'PS.input')), 221 npoints = 1, mu_r=-1.0) 222 # check 223 t1, t2, ram_usage = me_cmd.MadLoopInitializer.make_and_run(curr_path) 224 if t1==None or t2==None: 225 raise MadGraph5Error,"Error while running process %s."\ 226 %shell_name 227 try: 228 rFile=open(os.path.join(curr_path,'result.dat'), 'r') 229 except IOError: 230 raise MadGraph5Error,"Could not find result file %s."%\ 231 str(os.path.join(curr_path,'result.dat')) 232 # The result are returned as a dictionary. 233 result = evaluator.parse_check_output(rFile,format='dict') 234 for line in self.format_res_string(result, shell_name): 235 if isinstance(line, str): 236 logger.info(line) 237 elif isinstance(line,tuple): 238 logger.info(line[0],line[1])
239
240 - def format_res_string(self, res, shell_name):
241 """ Returns a good-looking string presenting the results. 242 The argument the tuple ((fin,born,spole,dpole,me_pow), p_out).""" 243 244 main_color='$MG:color:BLUE' 245 246 def special_float_format(float): 247 return '%s%.16e'%('' if float<0.0 else ' ',float)
248 249 so_order_names = res['Split_Orders_Names'] 250 251 def format_so_orders(so_orders): 252 return ' '.join(['%s=%d'%(so_order_names[i],so_orders[i]) for i in 253 range(len(so_orders))])
254 255 ASCII_bar = ('|'+''.join(['='*96]),main_color) 256 257 ret_code_h = res['return_code']//100 258 ret_code_t = (res['return_code']-100*ret_code_h)//10 259 ret_code_u = res['return_code']%10 260 StabilityOutput=[] 261 if ret_code_h==1: 262 if ret_code_t==3 or ret_code_t==4: 263 StabilityOutput.append('| Unknown numerical stability because '+\ 264 'MadLoop is in the initialization stage.') 265 else: 266 StabilityOutput.append('| Unknown numerical stability, check '+\ 267 'CTRunMode value in MadLoopParams.dat.') 268 elif ret_code_h==2: 269 StabilityOutput.append('| Stable kinematic configuration (SPS).') 270 elif ret_code_h==3: 271 StabilityOutput.append('| Unstable kinematic configuration (UPS).') 272 StabilityOutput.append('| Quadruple precision rescue successful.') 273 elif ret_code_h==4: 274 StabilityOutput.append('| Exceptional kinematic configuration (EPS).') 275 StabilityOutput.append('| Both double and quadruple precision'+\ 276 ' computations are unstable.') 277 278 if ret_code_t==2 or ret_code_t==4: 279 StabilityOutput.append('| Quadruple precision was used for this'+\ 280 'computation.') 281 if ret_code_h!=1: 282 if res['accuracy']>0.0: 283 StabilityOutput.append('| Estimated relative accuracy = %.1e'\ 284 %res['accuracy']) 285 elif res['accuracy']==0.0: 286 StabilityOutput.append('| Estimated relative accuracy = %.1e'\ 287 %res['accuracy']+' (i.e. beyond double precision)') 288 else: 289 StabilityOutput.append('| Estimated accuracy could not be '+\ 290 'computed for an unknown reason.') 291 292 PS_point_spec = ['|| Phase-Space point specification (E,px,py,pz)','|'] 293 PS_point_spec.append('\n'.join(['| '+' '.join(['%s'%\ 294 special_float_format(pi) for pi in pmom]) for pmom in res['res_p']])) 295 PS_point_spec.append('|') 296 297 str_lines=[] 298 299 notZeroBorn=True 300 if res['export_format']!='LoopInduced' and len(so_order_names) and \ 301 len([1 for k in res['Born_kept'] if k])==0: 302 notZeroBorn = False 303 str_lines.append( 304 ("| /!\\ There is no Born contribution for the squared orders specified in "+ 305 "the process definition/!\\",'$MG:color:RED')) 306 307 if res['export_format']=='Default' and notZeroBorn: 308 str_lines.extend(['\n',ASCII_bar, 309 ('|| Results for process %s'%shell_name,main_color), 310 ASCII_bar]+PS_point_spec+StabilityOutput+[ 311 '|', 312 ('|| Total(*) Born contribution (GeV^%d):'%res['gev_pow'],main_color), 313 ('| Born = %s'%special_float_format(res['born']),main_color), 314 ('|| Total(*) virtual contribution normalized with born*alpha_S/(2*pi):',main_color), 315 ('| Finite = %s'%special_float_format(res['finite']),main_color), 316 ('| Single pole = %s'%special_float_format(res['1eps']),main_color), 317 ('| Double pole = %s'%special_float_format(res['2eps']),main_color)]) 318 elif res['export_format']=='LoopInduced' and notZeroBorn: 319 str_lines.extend(['\n',ASCII_bar, 320 ('|| Results for process %s (Loop-induced)'%shell_name,main_color), 321 ASCII_bar]+PS_point_spec+StabilityOutput+[ 322 '|', 323 ('|| Loop amplitude squared, must be finite:',main_color), 324 ('| Finite = %s'%special_float_format(res['finite']),main_color), 325 '|(| Pole residues, indicated only for checking purposes: )', 326 '|( Single pole = %s )'%special_float_format(res['1eps']), 327 '|( Double pole = %s )'%special_float_format(res['2eps'])]) 328 329 if (len(res['Born_SO_Results'])+len(res['Born_SO_Results']))>0: 330 if notZeroBorn: 331 str_lines.append( 332 ("| (*) The results above sum all starred contributions below",main_color)) 333 334 str_lines.append('|') 335 if not notZeroBorn: 336 str_lines.append( 337 ("| The Born contributions below are computed but do not match these squared "+ 338 "orders constraints",main_color)) 339 340 if len(res['Born_SO_Results'])==1: 341 str_lines.append('|| All Born contributions are of split orders *(%s)'\ 342 %format_so_orders(res['Born_SO_Results'][0][0])) 343 elif len(res['Born_SO_Results'])>1: 344 for i, bso_contrib in enumerate(res['Born_SO_Results']): 345 str_lines.append('|| Born contribution of split orders %s(%s) = %s'\ 346 %('*' if res['Born_kept'][i] else ' ', 347 format_so_orders(bso_contrib[0]), 348 special_float_format(bso_contrib[1]['BORN']))) 349 350 if len(so_order_names): 351 str_lines.append('|') 352 353 if len(res['Loop_SO_Results'])==1: 354 str_lines.append('|| All virtual contributions are of split orders *(%s)'\ 355 %format_so_orders(res['Loop_SO_Results'][0][0])) 356 elif len(res['Loop_SO_Results'])>1: 357 if not notZeroBorn: 358 str_lines.append( 359 ("| The coupling order combinations matching the squared order"+ 360 " constraints are marked with a star",main_color)) 361 for i, lso_contrib in enumerate(res['Loop_SO_Results']): 362 str_lines.append('|| Virtual contribution of split orders %s(%s):'\ 363 %('*' if res['Loop_kept'][i] else ' ', 364 format_so_orders(lso_contrib[0]))) 365 str_lines.append('| Accuracy = %.1e'%\ 366 lso_contrib[1]['ACC']), 367 str_lines.append('| Finite = %s'%\ 368 special_float_format(lso_contrib[1]['FIN'])), 369 if res['export_format']=='LoopInduced': 370 str_lines.append('|( Single pole = %s )'%\ 371 special_float_format(lso_contrib[1]['1EPS'])) 372 str_lines.append('|( Double pole = %s )'%\ 373 special_float_format(lso_contrib[1]['2EPS'])) 374 else: 375 str_lines.append('| Single pole = %s'%\ 376 special_float_format(lso_contrib[1]['1EPS'])) 377 str_lines.append('| Double pole = %s'%\ 378 special_float_format(lso_contrib[1]['2EPS'])) 379 str_lines.extend([ASCII_bar,'\n']) 380 381 return str_lines 382
383 -class SALauncher(ExtLauncher):
384 """ A class to launch a simple Standalone test """ 385
386 - def __init__(self, cmd_int, running_dir, **options):
387 """ initialize the StandAlone Version""" 388 389 ExtLauncher.__init__(self, cmd_int, running_dir, './Cards', **options) 390 self.cards = ['param_card.dat']
391 392
393 - def launch_program(self):
394 """launch the main program""" 395 sub_path = os.path.join(self.running_dir, 'SubProcesses') 396 for path in os.listdir(sub_path): 397 if path.startswith('P') and \ 398 os.path.isdir(os.path.join(sub_path, path)): 399 cur_path = os.path.join(sub_path, path) 400 # make 401 misc.compile(cwd=cur_path, mode='unknown') 402 # check 403 subprocess.call(['./check'], cwd=cur_path)
404
405 -class MWLauncher(ExtLauncher):
406 """ A class to launch a simple Standalone test """ 407 408
409 - def __init__(self, cmd_int, running_dir, **options):
410 """ initialize the StandAlone Version""" 411 ExtLauncher.__init__(self, cmd_int, running_dir, './Cards', **options) 412 self.options = cmd_int.options
413
414 - def launch_program(self):
415 """launch the main program""" 416 417 import madgraph.interface.madweight_interface as MW 418 # Check for number of cores if multicore mode 419 mode = str(self.cluster) 420 nb_node = 1 421 if mode == "2": 422 import multiprocessing 423 max_node = multiprocessing.cpu_count() 424 if max_node == 1: 425 logger.warning('Only one core is detected on your computer! Pass in single machine') 426 self.cluster = 0 427 self.launch_program() 428 return 429 elif max_node == 2: 430 nb_node = 2 431 elif not self.force: 432 nb_node = self.ask('How many core do you want to use?', max_node, range(2,max_node+1)) 433 else: 434 nb_node=max_node 435 436 import madgraph.interface.madevent_interface as ME 437 438 stdout_level = self.cmd_int.options['stdout_level'] 439 if self.shell: 440 usecmd = MW.MadWeightCmdShell(me_dir=self.running_dir, options=self.options) 441 else: 442 usecmd = MW.MadWeightCmd(me_dir=self.running_dir, options=self.options) 443 usecmd.pass_in_web_mode() 444 #Check if some configuration were overwritten by a command. If so use it 445 set_cmd = [l for l in self.cmd_int.history if l.strip().startswith('set')] 446 for line in set_cmd: 447 try: 448 usecmd.do_set(line[3:], log=False) 449 except Exception: 450 pass 451 452 usecmd.do_set('stdout_level %s' % stdout_level,log=False) 453 #ensure that the logger level 454 launch = self.cmd_int.define_child_cmd_interface( 455 usecmd, interface=False) 456 457 command = 'launch' 458 if mode == "1": 459 command += " --cluster" 460 elif mode == "2": 461 command += " --nb_core=%s" % nb_node 462 463 if self.force: 464 command+= " -f" 465 if self.laststep: 466 command += ' --laststep=%s' % self.laststep 467 468 try: 469 os.remove('ME5_debug') 470 except: 471 pass 472 launch.run_cmd(command) 473 launch.run_cmd('quit') 474 475 if os.path.exists('ME5_debug'): 476 return True
477 478 479
480 -class aMCatNLOLauncher(ExtLauncher):
481 """A class to launch MadEvent run""" 482
483 - def __init__(self, running_dir, cmd_int, run_mode='', unit='pb', **option):
484 """ initialize the StandAlone Version""" 485 486 ExtLauncher.__init__(self, cmd_int, running_dir, './Cards', **option) 487 #self.executable = os.path.join('.', 'bin','generate_events') 488 489 self.options = option 490 assert hasattr(self, 'cluster') 491 assert hasattr(self, 'multicore') 492 assert hasattr(self, 'name') 493 assert hasattr(self, 'shell') 494 495 self.unit = unit 496 self.run_mode = run_mode 497 498 if self.cluster or option['cluster']: 499 self.cluster = 1 500 if self.multicore or option['multicore']: 501 self.cluster = 2 502 503 self.cards = [] 504 505 # Assign a valid run name if not put in options 506 if self.name == '': 507 self.name = me_cmd.MadEventCmd.find_available_run_name(self.running_dir)
508
509 - def launch_program(self):
510 """launch the main program""" 511 512 # Check for number of cores if multicore mode 513 mode = str(self.cluster) 514 nb_node = 1 515 if mode == "2": 516 import multiprocessing 517 max_node = multiprocessing.cpu_count() 518 if max_node == 1: 519 logger.warning('Only one core is detected on your computer! Pass in single machine') 520 self.cluster = 0 521 self.launch_program() 522 return 523 elif max_node == 2: 524 nb_node = 2 525 elif not self.force: 526 nb_node = self.ask('How many cores do you want to use?', max_node, range(2,max_node+1)) 527 else: 528 nb_node=max_node 529 530 import madgraph.interface.amcatnlo_run_interface as run_int 531 532 if hasattr(self, 'shell') and self.shell: 533 usecmd = run_int.aMCatNLOCmdShell(me_dir=self.running_dir, options = self.cmd_int.options) 534 else: 535 usecmd = run_int.aMCatNLOCmd(me_dir=self.running_dir, options = self.cmd_int.options) 536 537 #Check if some configuration were overwritten by a command. If so use it 538 set_cmd = [l for l in self.cmd_int.history if l.strip().startswith('set')] 539 all_options = usecmd.options_configuration.keys() + usecmd.options_madgraph.keys() + usecmd.options_madevent.keys() 540 for line in set_cmd: 541 arg = line.split() 542 if arg[1] not in all_options: 543 continue 544 try: 545 usecmd.exec_cmd(line) 546 except Exception, error: 547 misc.sprint('Command %s fails with msg: %s'%(str(line), \ 548 str(error))) 549 pass 550 launch = self.cmd_int.define_child_cmd_interface( 551 usecmd, interface=False) 552 #launch.me_dir = self.running_dir 553 option_line = ' '.join([' --%s' % opt for opt in self.options.keys() \ 554 if self.options[opt] and not opt in ['cluster', 'multicore', 'name', 'appl_start_grid','shell']]) 555 if self.options['name']: 556 option_line += ' --name %s' % self.options['name'] 557 if 'appl_start_grid' in self.options and self.options['appl_start_grid']: 558 option_line += ' --appl_start_grid %s' % self.options['appl_start_grid'] 559 command = 'launch ' + self.run_mode + ' ' + option_line 560 561 if mode == "1": 562 command += " -c" 563 elif mode == "2": 564 command += " -m" 565 usecmd.nb_core = int(nb_node) 566 try: 567 os.remove('ME5_debug') 568 except: 569 pass 570 launch.run_cmd(command) 571 launch.run_cmd('quit')
572 573 574 575 576
577 -class MELauncher(ExtLauncher):
578 """A class to launch MadEvent run""" 579
580 - def __init__(self, running_dir, cmd_int , unit='pb', **option):
581 """ initialize the StandAlone Version""" 582 583 ExtLauncher.__init__(self, cmd_int, running_dir, './Cards', **option) 584 #self.executable = os.path.join('.', 'bin','generate_events') 585 self.pythia = cmd_int.options['pythia-pgs_path'] 586 self.delphes = cmd_int.options['delphes_path'], 587 self.options = cmd_int.options 588 589 assert hasattr(self, 'cluster') 590 assert hasattr(self, 'multicore') 591 assert hasattr(self, 'name') 592 assert hasattr(self, 'shell') 593 594 self.unit = unit 595 596 if self.cluster: 597 self.cluster = 1 598 if self.multicore: 599 self.cluster = 2 600 601 self.cards = [] 602 603 # Assign a valid run name if not put in options 604 if self.name == '': 605 self.name = me_cmd.MadEventCmd.find_available_run_name(self.running_dir)
606
607 - def launch_program(self):
608 """launch the main program""" 609 610 # Check for number of cores if multicore mode 611 mode = str(self.cluster) 612 nb_node = 1 613 if mode == "2": 614 import multiprocessing 615 max_node = multiprocessing.cpu_count() 616 if max_node == 1: 617 logger.warning('Only one core is detected on your computer! Pass in single machine') 618 self.cluster = 0 619 self.launch_program() 620 return 621 elif max_node == 2: 622 nb_node = 2 623 elif not self.force: 624 nb_node = self.ask('How many cores do you want to use?', max_node, range(2,max_node+1)) 625 else: 626 nb_node=max_node 627 628 import madgraph.interface.madevent_interface as ME 629 630 stdout_level = self.cmd_int.options['stdout_level'] 631 632 with ME.MadEventCmd.RunWebHandling(self.running_dir): 633 if self.shell: 634 usecmd = ME.MadEventCmdShell(me_dir=self.running_dir, options=self.options, force_run=True) 635 else: 636 usecmd = ME.MadEventCmd(me_dir=self.running_dir, options=self.options, force_run=True) 637 usecmd.pass_in_web_mode() 638 #Check if some configuration were overwritten by a command. If so use it 639 set_cmd = [l for l in self.cmd_int.history if l.strip().startswith('set')] 640 all_options = usecmd.options_configuration.keys() + usecmd.options_madgraph.keys() + usecmd.options_madevent.keys() 641 for line in set_cmd: 642 arg = line.split() 643 if arg[1] not in all_options: 644 continue 645 try: 646 usecmd.do_set(line[3:], log=False) 647 except usecmd.InvalidCmd: 648 pass 649 usecmd.do_set('stdout_level %s' % stdout_level,log=False) 650 #ensure that the logger level 651 launch = self.cmd_int.define_child_cmd_interface( 652 usecmd, interface=False) 653 #launch.me_dir = self.running_dir 654 if self.unit == 'pb': 655 command = 'generate_events %s' % self.name 656 else: 657 warning_text = '''\ 658 Note that since 2.3. The launch for 1>N pass in event generation 659 For efficient width computation see arXiv:1402.1178.''' 660 logger.warning(warning_text) 661 command = 'generate_events %s' % self.name 662 if mode == "1": 663 command += " --cluster" 664 elif mode == "2": 665 command += " --nb_core=%s" % nb_node 666 667 if self.force: 668 command+= " -f" 669 670 if self.laststep: 671 command += ' --laststep=%s' % self.laststep 672 if self.reweight: 673 command += ' -R ' 674 if self.madspin: 675 command += ' -M ' 676 677 678 try: 679 os.remove('ME5_debug') 680 except: 681 pass 682 683 launch.run_cmd(command) 684 launch.run_cmd('quit') 685 686 if os.path.exists('ME5_debug'): 687 return True 688 689 # Display the cross-section to the screen 690 path = os.path.join(self.running_dir, 'SubProcesses', 'results.dat') 691 if not os.path.exists(path): 692 logger.error('Generation failed (no results.dat file found)') 693 return 694 fsock = open(path) 695 line = fsock.readline() 696 cross, error = line.split()[0:2] 697 698 logger.info('more information in %s' 699 % os.path.join(self.running_dir, 'index.html'))
700 701
702 -class Pythia8Launcher(ExtLauncher):
703 """A class to launch Pythia8 run""" 704
705 - def __init__(self, running_dir, cmd_int, **option):
706 """ initialize launching Pythia 8""" 707 708 running_dir = os.path.join(running_dir, 'examples') 709 ExtLauncher.__init__(self, cmd_int, running_dir, '.', **option) 710 self.cards = []
711
712 - def prepare_run(self):
713 """ ask for pythia-pgs/delphes run """ 714 715 # Find all main_model_process.cc files 716 date_file_list = [] 717 for file in misc.glob('main_*_*.cc', self.running_dir): 718 # retrieves the stats for the current file as a tuple 719 # (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) 720 # the tuple element mtime at index 8 is the last-modified-date 721 stats = os.stat(file) 722 # create tuple (year yyyy, month(1-12), day(1-31), hour(0-23), minute(0-59), second(0-59), 723 # weekday(0-6, 0 is monday), Julian day(1-366), daylight flag(-1,0 or 1)) from seconds since epoch 724 # note: this tuple can be sorted properly by date and time 725 lastmod_date = time.localtime(stats[8]) 726 date_file_list.append((lastmod_date, os.path.split(file)[-1])) 727 728 if not date_file_list: 729 raise MadGraph5Error, 'No Pythia output found' 730 # Sort files according to date with newest first 731 date_file_list.sort() 732 date_file_list.reverse() 733 files = [d[1] for d in date_file_list] 734 735 answer = '' 736 answer = self.ask('Select a main file to run:', files[0], files) 737 738 self.cards.append(answer) 739 740 self.executable = self.cards[-1].replace(".cc","") 741 742 # Assign a valid run name if not put in options 743 if self.name == '': 744 for i in range(1000): 745 path = os.path.join(self.running_dir, '', 746 '%s_%02i.log' % (self.executable, i)) 747 if not os.path.exists(path): 748 self.name = '%s_%02i.log' % (self.executable, i) 749 break 750 751 if self.name == '': 752 raise MadGraph5Error, 'too many runs in this directory' 753 754 # Find all exported models 755 models = misc.glob("Processes_*", pjoin(self.running_dir,os.path.pardir)) 756 models = [os.path.split(m)[-1].replace("Processes_","") for m in models] 757 # Extract model name from executable 758 models.sort(key=len) 759 models.reverse() 760 model_dir = "" 761 for model in models: 762 if self.executable.replace("main_", "").startswith(model): 763 model_dir = "Processes_%s" % model 764 break 765 if model_dir: 766 self.model = model 767 self.model_dir = os.path.realpath(os.path.join(self.running_dir, 768 os.path.pardir, 769 model_dir)) 770 self.cards.append(os.path.join(self.model_dir, 771 "param_card_%s.dat" % model))
772
773 - def launch_program(self):
774 """launch the main program""" 775 776 # Make pythia8 777 print "Running make for pythia8 directory" 778 if self.model_dir: 779 print "Running make in %s" % self.model_dir 780 misc.compile(cwd=self.model_dir, mode='cpp') 781 # Finally run make for executable 782 makefile = self.executable.replace("main_","Makefile_") 783 print "Running make with %s" % makefile 784 misc.compile(arg=['-f', makefile], cwd=self.running_dir, mode='cpp') 785 786 print "Running " + self.executable 787 788 output = open(os.path.join(self.running_dir, self.name), 'w') 789 if not self.executable.startswith('./'): 790 self.executable = os.path.join(".", self.executable) 791 subprocess.call([self.executable], stdout = output, stderr = output, 792 cwd=self.running_dir) 793 794 # Display the cross-section to the screen 795 path = os.path.join(self.running_dir, self.name) 796 pydoc.pager(open(path).read()) 797 798 print "Output of the run is found at " + \ 799 os.path.realpath(os.path.join(self.running_dir, self.name))
800 801 # old compatibility shortcut 802 open_file = misc.open_file 803