Beispiel #1
0
    def test_short_generate_events_name(self):
        """test if the generate_events and successively the shower script in 
        the bin directory works fine"""

        self.generate_production()
        # to check that the cleaning of files work well
        os.system('touch %s/SubProcesses/P0_udx_epve/GF1' % self.path)
        self.do('quit')
        misc.call([pjoin('.', 'bin', 'generate_events'), '-fp', '-n myrun'],
                  cwd='%s' % self.path,
                  stdout=open(os.devnull, 'w'))
        # test the lhe event file exists
        self.assertTrue(
            os.path.exists('%s/Events/myrun/events.lhe.gz' % self.path))
        self.assertTrue(
            os.path.exists('%s/Events/myrun/summary.txt' % self.path))
        self.assertTrue(
            os.path.exists('%s/Events/myrun/myrun_tag_1_banner.txt' %
                           self.path))
        self.assertTrue(os.path.exists('%s/Events/myrun/res_0.txt' %
                                       self.path))
        self.assertTrue(os.path.exists('%s/Events/myrun/res_1.txt' %
                                       self.path))
        self.assertTrue(
            os.path.exists('%s/Events/myrun/alllogs_0.html' % self.path))
        self.assertTrue(
            os.path.exists('%s/Events/myrun/alllogs_1.html' % self.path))
        self.assertTrue(
            os.path.exists('%s/Events/myrun/alllogs_2.html' % self.path))
Beispiel #2
0
    def test_short_calculate_xsect_script(self):
        """test if the calculate_xsect script in the bin directory
        works fine"""

        self.generate_production()
        misc.call([pjoin('.', 'bin', 'calculate_xsect'), '-f'],
                  cwd='%s' % self.path,
                  stdout=open(os.devnull, 'w'))

        # test the plot file exists
        self.assertTrue(
            os.path.exists('%s/Events/run_01/MADatNLO.HwU' % self.path))
        self.assertTrue(
            os.path.exists('%s/Events/run_01/summary.txt' % self.path))
        self.assertTrue(
            os.path.exists('%s/Events/run_01/run_01_tag_1_banner.txt' %
                           self.path))
        self.assertTrue(
            os.path.exists('%s/Events/run_01/alllogs_0.html' % self.path))
        self.assertTrue(
            os.path.exists('%s/Events/run_01/alllogs_1.html' % self.path))
        self.assertTrue(
            os.path.exists('%s/Events/run_01/res_0.txt' % self.path))
        self.assertTrue(
            os.path.exists('%s/Events/run_01/res_1.txt' % self.path))
Beispiel #3
0
    def test_amcantlo_script(self):
        """test that ./bin/aMCatNLO can be launched with some scripts.
        Check also that two runs run without border effects"""
        self.generate_production()
        script = "set notification_center False --no_save\n"
        script += "set automatic_html_opening False --no_save\n"
        script += "launch -p\n"
        script += "launch -p\n"
        open(pjoin(self.path, 'script.txt'), 'w').write(script)

        misc.call([pjoin('.','bin','aMCatNLO'), 'script.txt'], cwd='%s' % self.path,
                stdout = open(os.devnull, 'w'))

        # test the lhe event file exists
        self.assertTrue(os.path.exists('%s/Events/run_01/events.lhe.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/summary.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/run_01_tag_1_banner.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/res_0.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/res_1.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_0.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_1.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_2.html' % self.path))

        # test the lhe event file exists
        self.assertTrue(os.path.exists('%s/Events/run_02/events.lhe.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/summary.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/run_02_tag_1_banner.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/res_0.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/res_1.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/alllogs_0.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/alllogs_1.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/alllogs_2.html' % self.path))
    def test_amcantlo_script(self):
        """test that ./bin/aMCatNLO can be launched with some scripts.
        Check also that two runs run without border effects"""
        self.generate_production()
        script = "set notification_center False --no_save\n"
        script += "set automatic_html_opening False --no_save\n"
        script += "launch -p\n"
        script += "launch -p\n"
        open(pjoin(self.path, 'script.txt'), 'w').write(script)

        misc.call([pjoin('.','bin','aMCatNLO'), 'script.txt'], cwd='%s' % self.path,
                stdout = open(os.devnull, 'w'))

        # test the lhe event file exists
        self.assertTrue(os.path.exists('%s/Events/run_01/events.lhe.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/summary.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/run_01_tag_1_banner.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/res_0.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/res_1.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_0.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_1.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_2.html' % self.path))

        # test the lhe event file exists
        self.assertTrue(os.path.exists('%s/Events/run_02/events.lhe.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/summary.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/run_02_tag_1_banner.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/res_0.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/res_1.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/alllogs_0.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/alllogs_1.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_02/alllogs_2.html' % self.path))
Beispiel #5
0
    def do_import(self, inputfile):
        """import the event file"""
        
        # change directory where to write the output
        self.options['curr_dir'] = os.path.realpath(os.path.dirname(inputfile))
        if os.path.basename(os.path.dirname(os.path.dirname(inputfile))) == 'Events':
            self.options['curr_dir'] = pjoin(self.options['curr_dir'], 
                                                      os.path.pardir, os.pardir)
            
        
        if not os.path.exists(inputfile):
            if inputfile.endswith('.gz'):
                if not os.path.exists(inputfile[:-3]):
                    raise self.InvalidCmd('No such file or directory : %s' % inputfile)
                else: 
                    inputfile = inputfile[:-3]
            elif os.path.exists(inputfile + '.gz'):
                inputfile = inputfile + '.gz'
            else: 
                raise self.InvalidCmd('No such file or directory : %s' % inputfile)
        
        if inputfile.endswith('.gz'):
            misc.call(['gunzip', inputfile])
            inputfile = inputfile[:-3]

        # Read the banner of the inputfile
        self.lhe_input = lhe_parser.EventFile(os.path.realpath(inputfile))
        if not self.lhe_input.banner:
            value = self.ask("What is the path to banner", 0, [0], "please enter a path", timeout=0)
            self.lhe_input.banner = open(value).read()
        self.banner = self.lhe_input.get_banner()
        
        # Check the validity of the banner:
        if 'slha' not in self.banner:
            self.events_file = None
            raise self.InvalidCmd('Event file does not contain model information')
        elif 'mg5proccard' not in self.banner:
            self.events_file = None
            raise self.InvalidCmd('Event file does not contain generation information')

        if 'madspin' in self.banner:
            raise self.InvalidCmd('Reweight should be done before running MadSpin')
                
                
        # load information
        process = self.banner.get_detail('proc_card', 'generate')
        if '[' in process:
            msg = 'Reweighting options is valid only for LO events'
            raise Exception, msg            
        if not process:
            msg = 'Invalid proc_card information in the file (no generate line):\n %s' % self.banner['mg5proccard']
            raise Exception, msg
        process, option = mg_interface.MadGraphCmd.split_process_line(process)
        self.proc_option = option
        
        logger.info("process: %s" % process)
        logger.info("options: %s" % option)
Beispiel #6
0
 def run_from_pickle(self):
     import madgraph.iolibs.save_load_object as save_load_object
     
     generate_all = save_load_object.load_from_file(pjoin(self.options['ms_dir'], 'madspin.pkl'))
     # Re-create information which are not save in the pickle.
     generate_all.evtfile = self.events_file
     generate_all.curr_event = madspin.Event(self.events_file) 
     generate_all.mgcmd = self.mg5cmd
     generate_all.mscmd = self 
     generate_all.pid2width = lambda pid: generate_all.banner.get('param_card', 'decay', abs(pid)).value
     generate_all.pid2mass = lambda pid: generate_all.banner.get('param_card', 'mass', abs(pid)).value
     if generate_all.path_me != self.options['ms_dir']:
         for decay in generate_all.all_ME.values():
             decay['path'] = decay['path'].replace(generate_all.path_me, self.options['ms_dir'])
             for decay2 in decay['decays']:
                 decay2['path'] = decay2['path'].replace(generate_all.path_me, self.options['ms_dir'])
         generate_all.path_me = self.options['ms_dir'] # directory can have been move
         generate_all.ms_dir = generate_all.path_me
     
     if not hasattr(self.banner, 'param_card'):
         self.banner.charge_card('slha')
     for name, block in self.banner.param_card.items():
         if name.startswith('decay'):
             continue
         orig_block = generate_all.banner.param_card[name]
         if block != orig_block:
             raise Exception, """The directory %s is specific to a mass spectrum. 
             Your event file is not compatible with this one. (Different param_card: %s different)
             orig block:
             %s
             new block:
             %s""" \
             % (self.options['ms_dir'], name, orig_block, block)
     
     # NOW we have all the information available for RUNNING
     
     if self.seed:
         #seed is specified need to use that one:
         open(pjoin(self.options['ms_dir'],'seeds.dat'),'w').write('%s\n'%self.seed)
         #remove all ranmar_state
         for name in glob.glob(pjoin(self.options['ms_dir'], '*', 'SubProcesses','*','ranmar_state.dat')):
             os.remove(name)    
     
     generate_all.ending_run()
     self.branching_ratio = generate_all.branching_ratio
     evt_path = self.events_file.name
     try:
         self.events_file.close()
     except:
         pass
     misc.call(['gzip -f %s' % evt_path], shell=True)
     decayed_evt_file=evt_path.replace('.lhe', '_decayed.lhe')
     shutil.move(pjoin(self.options['curr_dir'],'decayed_events.lhe'), decayed_evt_file)
     misc.call(['gzip -f %s' % decayed_evt_file], shell=True)
     if not self.mother:
         logger.info("Decayed events have been written in %s.gz" % decayed_evt_file)    
    def test_generate_events_shower_scripts(self):
        """test if the generate_events and successively the shower script in 
        the bin directory works fine.
        Also check the splitting of the shower for bot hep and top output"""

        self.generate_production()
        # to check that the cleaning of files work well
        os.system('touch %s/SubProcesses/P0_udx_epve/GF1' % self.path)
        self.do('quit')
        self.cmd_line.run_cmd('generate_events -f')
        # test the lhe event file exists
        self.assertTrue(os.path.exists('%s/Events/run_01/events.lhe.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/summary.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/run_01_tag_1_banner.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/res_0.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/res_1.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_0.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_1.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_2.html' % self.path))
        # test the hep event file exists
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_0.hep.gz' % self.path))
        misc.call([pjoin('.','bin','shower'), 'run_01', '-f'], cwd='%s' % self.path,
                stdout = open(os.devnull, 'w'))
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_1.hep.gz' % self.path))
        # sanity check on the size
        self.assertTrue(os.path.getsize('%s/Events/run_01/events_HERWIG6_0.hep.gz' % self.path) > \
                        os.path.getsize('%s/Events/run_01/events.lhe.gz' % self.path))
        self.assertTrue(os.path.getsize('%s/Events/run_01/events_HERWIG6_1.hep.gz' % self.path) > \
                        os.path.getsize('%s/Events/run_01/events.lhe.gz' % self.path))

        #splitting of the shower
        # 1) hep output
        shower_card = open('%s/Cards/shower_card.dat' % self.path).read()
        shower_card = shower_card.replace('nsplit_jobs  = 1', 'nsplit_jobs  = 4')
        open('%s/Cards/shower_card.dat' % self.path, 'w').write(shower_card)
        self.cmd_line.run_cmd('shower run_01 -f')
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_2__1.hep.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_2__2.hep.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_2__3.hep.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_2__4.hep.gz' % self.path))

        # 2) top output
        shower_card = shower_card.replace('EXTRALIBS    = stdhep Fmcfio', 'EXTRALIBS    =')  
        shower_card = shower_card.replace('ANALYSE      =', 'ANALYSE      = mcatnlo_hwan_pp_lvl.o mcatnlo_hbook_gfortran8.o')  
        open('%s/Cards/shower_card.dat' % self.path, 'w').write(shower_card)
        self.cmd_line.run_cmd('shower run_01 -f')
        self.assertTrue(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0.tar.gz' % self.path))
        self.assertFalse(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0__1.top' % self.path))
        misc.call(['tar', '-xzpvf', '%s/Events/run_01/plot_HERWIG6_1_0.tar.gz' % self.path],
                  cwd='%s/Events/run_01/'% self.path,
                  stdout = open(os.devnull, 'w'))
        self.assertTrue(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0__1.top' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0__2.top' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0__3.top' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0__4.top' % self.path))
    def test_generate_events_shower_scripts(self):
        """test if the generate_events and successively the shower script in 
        the bin directory works fine.
        Also check the splitting of the shower for bot hep and top output"""

        self.generate_production()
        # to check that the cleaning of files work well
        os.system('touch %s/SubProcesses/P0_udx_epve/GF1' % self.path)
        self.do('quit')
        self.cmd_line.run_cmd('generate_events -f')
        # test the lhe event file exists
        self.assertTrue(os.path.exists('%s/Events/run_01/events.lhe.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/summary.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/run_01_tag_1_banner.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/res_0.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/res_1.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_0.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_1.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_2.html' % self.path))
        # test the hep event file exists
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_0.hep.gz' % self.path))
        misc.call([pjoin('.','bin','shower'), 'run_01', '-f'], cwd='%s' % self.path,
                stdout = open(os.devnull, 'w'))
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_1.hep.gz' % self.path))
        # sanity check on the size
        self.assertTrue(os.path.getsize('%s/Events/run_01/events_HERWIG6_0.hep.gz' % self.path) > \
                        os.path.getsize('%s/Events/run_01/events.lhe.gz' % self.path))
        self.assertTrue(os.path.getsize('%s/Events/run_01/events_HERWIG6_1.hep.gz' % self.path) > \
                        os.path.getsize('%s/Events/run_01/events.lhe.gz' % self.path))

        #splitting of the shower
        # 1) hep output
        shower_card = open('%s/Cards/shower_card.dat' % self.path).read()
        shower_card = shower_card.replace('nsplit_jobs  = 1', 'nsplit_jobs  = 4')
        open('%s/Cards/shower_card.dat' % self.path, 'w').write(shower_card)
        self.cmd_line.run_cmd('shower run_01 -f')
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_2__1.hep.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_2__2.hep.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_2__3.hep.gz' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/events_HERWIG6_2__4.hep.gz' % self.path))

        # 2) top output
        shower_card = shower_card.replace('EXTRALIBS    = stdhep Fmcfio', 'EXTRALIBS    =')  
        shower_card = shower_card.replace('ANALYSE      =', 'ANALYSE      = mcatnlo_hwan_pp_lvl.o mcatnlo_hbook_gfortran8.o')  
        open('%s/Cards/shower_card.dat' % self.path, 'w').write(shower_card)
        self.cmd_line.run_cmd('shower run_01 -f')
        self.assertTrue(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0.tar.gz' % self.path))
        self.assertFalse(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0__1.top' % self.path))
        misc.call(['tar', '-xzpvf', '%s/Events/run_01/plot_HERWIG6_1_0.tar.gz' % self.path],
                  cwd='%s/Events/run_01/'% self.path,
                  stdout = open(os.devnull, 'w'))
        self.assertTrue(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0__1.top' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0__2.top' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0__3.top' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/plot_HERWIG6_1_0__4.top' % self.path))
Beispiel #9
0
    def do_import(self, inputfile):
        """import the event file"""

        # change directory where to write the output
        self.options["curr_dir"] = os.path.realpath(os.path.dirname(inputfile))
        if os.path.basename(os.path.dirname(os.path.dirname(inputfile))) == "Events":
            self.options["curr_dir"] = pjoin(self.options["curr_dir"], os.path.pardir, os.pardir)

        if not os.path.exists(inputfile):
            if inputfile.endswith(".gz"):
                if not os.path.exists(inputfile[:-3]):
                    raise self.InvalidCmd("No such file or directory : %s" % inputfile)
                else:
                    inputfile = inputfile[:-3]
            elif os.path.exists(inputfile + ".gz"):
                inputfile = inputfile + ".gz"
            else:
                raise self.InvalidCmd("No such file or directory : %s" % inputfile)

        if inputfile.endswith(".gz"):
            misc.call(["gunzip", inputfile])
            inputfile = inputfile[:-3]

        # Read the banner of the inputfile
        self.lhe_input = lhe_parser.EventFile(os.path.realpath(inputfile))
        if not self.lhe_input.banner:
            value = self.ask("What is the path to banner", 0, [0], "please enter a path", timeout=0)
            self.lhe_input.banner = open(value).read()
        self.banner = self.lhe_input.get_banner()

        # Check the validity of the banner:
        if "slha" not in self.banner:
            self.events_file = None
            raise self.InvalidCmd("Event file does not contain model information")
        elif "mg5proccard" not in self.banner:
            self.events_file = None
            raise self.InvalidCmd("Event file does not contain generation information")

        if "madspin" in self.banner:
            raise self.InvalidCmd("Reweight should be done before running MadSpin")

        # load information
        process = self.banner.get_detail("proc_card", "generate")
        if "[" in process:
            msg = "Reweighting options is valid only for LO events"
            raise Exception, msg
        if not process:
            msg = "Invalid proc_card information in the file (no generate line):\n %s" % self.banner["mg5proccard"]
            raise Exception, msg
        process, option = mg_interface.MadGraphCmd.split_process_line(process)
        self.proc_option = option

        logger.info("process: %s" % process)
        logger.info("options: %s" % option)
    def test_calculate_xsect_script(self):
        """test if the calculate_xsect script in the bin directory
        works fine"""
        
        self.generate_production()
        misc.call([pjoin('.','bin','calculate_xsect'), '-f'], cwd='%s' % self.path,
                stdout = open(os.devnull, 'w'))

        # test the plot file exists
        self.assertTrue(os.path.exists('%s/Events/run_01/MADatNLO.top' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/summary.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/run_01_tag_1_banner.txt' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_0.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/alllogs_1.html' % self.path))
        self.assertTrue(os.path.exists('%s/Events/run_01/res.txt' % self.path))
 def test_generate_events_name(self):
     """test if the generate_events and successively the shower script in 
     the bin directory works fine"""
     
     self.generate_production()
     # to check that the cleaning of files work well
     os.system('touch %s/SubProcesses/P0_udx_epve/GF1' % self.path)
     self.do('quit')
     misc.call([pjoin('.','bin','generate_events'), '-fp', '-n myrun'], cwd='%s' % self.path,
             stdout = open(os.devnull, 'w'))
     # test the lhe event file exists
     self.assertTrue(os.path.exists('%s/Events/myrun/events.lhe.gz' % self.path))
     self.assertTrue(os.path.exists('%s/Events/myrun/summary.txt' % self.path))
     self.assertTrue(os.path.exists('%s/Events/myrun/myrun_tag_1_banner.txt' % self.path))
     self.assertTrue(os.path.exists('%s/Events/myrun/res_0.txt' % self.path))
     self.assertTrue(os.path.exists('%s/Events/myrun/res_1.txt' % self.path))
     self.assertTrue(os.path.exists('%s/Events/myrun/alllogs_0.html' % self.path))
     self.assertTrue(os.path.exists('%s/Events/myrun/alllogs_1.html' % self.path))
     self.assertTrue(os.path.exists('%s/Events/myrun/alllogs_2.html' % self.path))
Beispiel #12
0
    for style in styles:
        f_code += "\nwrite(*,*) ''\nwrite(*,*) 'Style %s in red.'\n"%style
        f_code += MadLoopBannerStyles.get_MadLoop_Banner(style=style, color='red')

    for style in styles:
        f_code += "\nwrite(*,*) ''\nwrite(*,*) 'Style %s in green.'\n"%style
        f_code += MadLoopBannerStyles.get_MadLoop_Banner(style=style, color='green')

    for style in styles:
        f_code += "\nwrite(*,*) ''\nwrite(*,*) 'Style %s without frame.'\n"%style
        f_code += MadLoopBannerStyles.get_MadLoop_Banner(style=style, print_frame=False)
    
    for style in styles:
        f_code += "\nwrite(*,*) ''\nwrite(*,*) 'Style %s with a different frame.'\n"%style
        f_code += MadLoopBannerStyles.get_MadLoop_Banner(
            side_margin=10, up_margin=3,
            top_frame_char = '-',
            bottom_frame_char = '-',
            left_frame_char = '*',
            right_frame_char = '*',
            style=style)
    
    writer.writelines("program testMLBanner\n%s\nend\n"%f_code)
    writer.close()
    # Now compile and run the code
    if os.path.isfile(pjoin(os.getcwd(),'test_ML_banner')):
        os.remove(pjoin(os.getcwd(),'test_ML_banner'))
    misc.call('gfortran -o test_ML_banner test_ML_banner.f',
                                                     cwd=os.getcwd(),shell=True)
    misc.call('./test_ML_banner',cwd=os.getcwd(),shell=True)
Beispiel #13
0
    def do_import(self, inputfile):
        """import the event file"""

        args = self.split_arg(inputfile)
        if not args:
            return self.InvalidCmd, 'import requires arguments'
        elif args[0] == 'model':
            return self.import_model(args[1:])

        # change directory where to write the output
        self.options['curr_dir'] = os.path.realpath(os.path.dirname(inputfile))
        if os.path.basename(os.path.dirname(
                os.path.dirname(inputfile))) == 'Events':
            self.options['curr_dir'] = pjoin(self.options['curr_dir'],
                                             os.path.pardir, os.pardir)

        if not os.path.exists(inputfile):
            if inputfile.endswith('.gz'):
                if not os.path.exists(inputfile[:-3]):
                    raise self.InvalidCmd('No such file or directory : %s' %
                                          inputfile)
                else:
                    inputfile = inputfile[:-3]
            elif os.path.exists(inputfile + '.gz'):
                inputfile = inputfile + '.gz'
            else:
                raise self.InvalidCmd('No such file or directory : %s' %
                                      inputfile)

        if inputfile.endswith('.gz'):
            misc.call(['gunzip', inputfile])
            inputfile = inputfile[:-3]

        # Read the banner of the inputfile
        self.events_file = open(os.path.realpath(inputfile))
        self.banner = banner.Banner(self.events_file)

        # Check the validity of the banner:
        if 'slha' not in self.banner:
            self.events_file = None
            raise self.InvalidCmd(
                'Event file does not contain model information')
        elif 'mg5proccard' not in self.banner:
            self.events_file = None
            raise self.InvalidCmd(
                'Event file does not contain generation information')

        if 'madspin' in self.banner:
            raise self.InvalidCmd(
                'This event file was already decayed by MS. This is not possible to add to it a second decay'
            )

        if 'mgruncard' in self.banner:
            if not self.options['Nevents_for_max_weigth']:
                nevents = int(self.banner.get_detail('run_card', 'nevents'))
                N_weight = max([75, int(3 * nevents**(1 / 3))])
                self.options['Nevents_for_max_weigth'] = N_weight
                N_sigma = max(4.5, math.log(nevents, 7.7))
                self.options['nb_sigma'] = N_sigma
            if self.options['BW_cut'] == -1:
                self.options['BW_cut'] = float(
                    self.banner.get_detail('run_card', 'bwcutoff'))

        else:
            if not self.options['Nevents_for_max_weigth']:
                self.options['Nevents_for_max_weigth'] = 75
                self.options['nb_sigma'] = 4.5
            if self.options['BW_cut'] == -1:
                self.options['BW_cut'] = 15.0

        # load information
        process = self.banner.get_detail('proc_card', 'generate')
        if not process:
            msg = 'Invalid proc_card information in the file (no generate line):\n %s' % self.banner[
                'mg5proccard']
            raise Exception, msg
        process, option = mg_interface.MadGraphCmd.split_process_line(process)
        self.proc_option = option

        logger.info("process: %s" % process)
        logger.info("options: %s" % option)

        # Read the final state of the production process:
        #     "_full" means with the complete decay chain syntax
        #     "_compact" means without the decay chain syntax
        self.final_state_full = process[process.find(">") + 1:]
        self.final_state_compact, self.prod_branches=\
                 self.decay.get_final_state_compact(self.final_state_full)

        # Load the model
        complex_mass = False
        has_cms = re.compile(
            r'''set\s+complex_mass_scheme\s*(True|T|1|true|$|;)''')
        for line in self.banner.proc_card:
            if line.startswith('set'):
                self.mg5cmd.exec_cmd(line,
                                     printcmd=False,
                                     precmd=False,
                                     postcmd=False)
                if has_cms.search(line):
                    complex_mass = True

        info = self.banner.get('proc_card', 'full_model_line')
        if '-modelname' in info:
            mg_names = False
        else:
            mg_names = True
        model_name = self.banner.get('proc_card', 'model')
        if model_name:
            self.load_model(model_name, mg_names, complex_mass)
        else:
            raise self.InvalidCmd('Only UFO model can be loaded in MadSpin.')

        # check particle which can be decayed:
        self.final_state = set()
        for line in self.banner.proc_card:
            line = ' '.join(line.strip().split())
            if line.startswith('generate'):
                self.final_state.update(self.mg5cmd.get_final_part(line[8:]))
            elif line.startswith('add process'):
                self.final_state.update(self.mg5cmd.get_final_part(line[11:]))
            elif line.startswith('define'):
                self.mg5cmd.exec_cmd(line,
                                     printcmd=False,
                                     precmd=False,
                                     postcmd=False)
            elif line.startswith('set'):
                self.mg5cmd.exec_cmd(line,
                                     printcmd=False,
                                     precmd=False,
                                     postcmd=False)
Beispiel #14
0
    def run_from_pickle(self):
        import madgraph.iolibs.save_load_object as save_load_object

        generate_all = save_load_object.load_from_file(
            pjoin(self.options['ms_dir'], 'madspin.pkl'))
        # Re-create information which are not save in the pickle.
        generate_all.evtfile = self.events_file
        generate_all.curr_event = madspin.Event(self.events_file)
        generate_all.mgcmd = self.mg5cmd
        generate_all.mscmd = self
        generate_all.pid2width = lambda pid: generate_all.banner.get(
            'param_card', 'decay', abs(pid)).value
        generate_all.pid2mass = lambda pid: generate_all.banner.get(
            'param_card', 'mass', abs(pid)).value
        if generate_all.path_me != self.options['ms_dir']:
            for decay in generate_all.all_ME.values():
                decay['path'] = decay['path'].replace(generate_all.path_me,
                                                      self.options['ms_dir'])
                for decay2 in decay['decays']:
                    decay2['path'] = decay2['path'].replace(
                        generate_all.path_me, self.options['ms_dir'])
            generate_all.path_me = self.options[
                'ms_dir']  # directory can have been move
            generate_all.ms_dir = generate_all.path_me

        if not hasattr(self.banner, 'param_card'):
            self.banner.charge_card('slha')
        for name, block in self.banner.param_card.items():
            if name.startswith('decay'):
                continue
            orig_block = generate_all.banner.param_card[name]
            if block != orig_block:
                raise Exception, """The directory %s is specific to a mass spectrum. 
                Your event file is not compatible with this one. (Different param_card: %s different)
                orig block:
                %s
                new block:
                %s""" \
                % (self.options['ms_dir'], name, orig_block, block)

        # NOW we have all the information available for RUNNING

        if self.seed:
            #seed is specified need to use that one:
            open(pjoin(self.options['ms_dir'], 'seeds.dat'),
                 'w').write('%s\n' % self.seed)
            #remove all ranmar_state
            for name in glob.glob(
                    pjoin(self.options['ms_dir'], '*', 'SubProcesses', '*',
                          'ranmar_state.dat')):
                os.remove(name)

        generate_all.ending_run()
        self.branching_ratio = generate_all.branching_ratio
        evt_path = self.events_file.name
        try:
            self.events_file.close()
        except:
            pass
        misc.call(['gzip -f %s' % evt_path], shell=True)
        decayed_evt_file = evt_path.replace('.lhe', '_decayed.lhe')
        shutil.move(pjoin(self.options['curr_dir'], 'decayed_events.lhe'),
                    decayed_evt_file)
        misc.call(['gzip -f %s' % decayed_evt_file], shell=True)
        if not self.mother:
            logger.info("Decayed events have been written in %s.gz" %
                        decayed_evt_file)
Beispiel #15
0
    def do_launch(self, line):
        """end of the configuration launched the code"""

        if self.options['ms_dir'] and os.path.exists(
                pjoin(self.options['ms_dir'], 'madspin.pkl')):
            return self.run_from_pickle()

        args = self.split_arg(line)
        self.check_launch(args)
        for part in self.list_branches.keys():
            if part in self.mg5cmd._multiparticles:
                if any(pid in self.final_state
                       for pid in self.mg5cmd._multiparticles[part]):
                    break
            pid = self.mg5cmd._curr_model.get('name2pdg')[part]
            if pid in self.final_state:
                break
        else:
            logger.info("Nothing to decay ...")
            return

        model_line = self.banner.get('proc_card', 'full_model_line')

        if not self.seed:
            import random
            self.seed = random.randint(0, int(30081 * 30081))
            self.do_set('seed %s' % self.seed)
            logger.info('Will use seed %s' % self.seed)
            self.history.insert(0, 'set seed %s' % self.seed)

        if self.seed > 30081 * 30081:  # can't use too big random number
            msg = 'Random seed too large ' + str(self.seed) + ' > 30081*30081'
            raise Exception, msg

        self.options['seed'] = self.seed
        text = '%s\n' % '\n'.join([line for line in self.history if line])
        self.banner.add_text('madspin', text)

        self.update_status('generating Madspin matrix element')
        generate_all = madspin.decay_all_events(self, self.banner,
                                                self.events_file, self.options)

        self.update_status('running MadSpin')
        generate_all.run()

        self.branching_ratio = generate_all.branching_ratio
        evt_path = self.events_file.name
        try:
            self.events_file.close()
        except:
            pass
        misc.call(['gzip -f %s' % evt_path], shell=True)
        decayed_evt_file = evt_path.replace('.lhe', '_decayed.lhe')
        shutil.move(pjoin(self.options['curr_dir'], 'decayed_events.lhe'),
                    decayed_evt_file)
        misc.call(['gzip -f %s' % decayed_evt_file], shell=True)
        if not self.mother:
            logger.info("Decayed events have been written in %s.gz" %
                        decayed_evt_file)

        # Now arxiv the shower card used if RunMaterial is present
        ms_card_path = pjoin(self.options['curr_dir'], 'Cards',
                             'madspin_card.dat')
        run_dir = os.path.realpath(os.path.dirname(decayed_evt_file))
        if os.path.exists(ms_card_path):
            if os.path.exists(pjoin(run_dir, 'RunMaterial.tar.gz')):
                misc.call(['tar', '-xzpf', 'RunMaterial.tar.gz'], cwd=run_dir)
                base_path = pjoin(run_dir, 'RunMaterial')
            else:
                base_path = pjoin(run_dir)

            evt_name = os.path.basename(decayed_evt_file).replace('.lhe', '')
            ms_card_to_copy = pjoin(base_path,
                                    'madspin_card_for_%s.dat' % evt_name)
            count = 0
            while os.path.exists(ms_card_to_copy):
                count += 1
                ms_card_to_copy = pjoin(base_path,'madspin_card_for_%s_%d.dat'%\
                                                               (evt_name,count))
            files.cp(str(ms_card_path), str(ms_card_to_copy))

            if os.path.exists(pjoin(run_dir, 'RunMaterial.tar.gz')):
                misc.call(
                    ['tar', '-czpf', 'RunMaterial.tar.gz', 'RunMaterial'],
                    cwd=run_dir)
                shutil.rmtree(pjoin(run_dir, 'RunMaterial'))
Beispiel #16
0
        def generate_events(pdg,
                            nb_event,
                            mg5,
                            restrict_file=None,
                            cumul=False):
            """generate new events for this particle
               restrict_file allow to only generate a subset of the definition
               cumul allow to merge all the definition in one run (add process)
                     to generate events according to cross-section
            """

            part = self.model.get_particle(pdg)
            name = part.get_name()
            out = {}
            logger.info("generate %s decay event for particle %s" %
                        (nb_event, name))
            if name not in self.list_branches:
                return out
            for i, proc in enumerate(self.list_branches[name]):
                if restrict_file and i not in restrict_file:
                    continue
                decay_dir = pjoin(
                    self.path_me,
                    "decay_%s_%s" % (str(pdg).replace("-", "x"), i))
                if not os.path.exists(decay_dir):
                    if cumul:
                        mg5.exec_cmd("generate %s" % proc)
                        for j, proc2 in enumerate(
                                self.list_branches[name][1:]):
                            if restrict_file and j not in restrict_file:
                                raise Exception  # Do not see how this can happen
                            mg5.exec_cmd("add process %s" % proc2)
                        mg5.exec_cmd("output %s -f" % decay_dir)
                    else:
                        mg5.exec_cmd("generate %s" % proc)
                        mg5.exec_cmd("output %s -f" % decay_dir)

                    options = dict(mg5.options)
                    if self.options['ms_dir']:
                        misc.sprint("start gridpack!")
                        # we are in gridpack mode -> create it
                        me5_cmd = madevent_interface.MadEventCmdShell(me_dir=os.path.realpath(\
                                                decay_dir), options=options)
                        me5_cmd.options["automatic_html_opening"] = False
                        if self.options["run_card"]:
                            run_card = self.options["run_card"]
                        else:
                            run_card = banner.RunCard(
                                pjoin(decay_dir, "Cards", "run_card.dat"))

                        run_card["iseed"] = self.seed
                        run_card['gridpack'] = True
                        run_card.write(
                            pjoin(decay_dir, "Cards", "run_card.dat"))
                        param_card = self.banner['slha']
                        open(pjoin(decay_dir, "Cards", "param_card.dat"),
                             "w").write(param_card)
                        self.seed += 1
                        # actually creation
                        me5_cmd.exec_cmd("generate_events run_01 -f")
                        me5_cmd.exec_cmd("exit")
                        #remove pointless informat
                        misc.call(
                            ["rm", "Cards", "bin", 'Source', 'SubProcesses'],
                            cwd=decay_dir)
                        misc.call(['tar', '-xzpvf', 'run_01_gridpack.tar.gz'],
                                  cwd=decay_dir)

                # Now generate the events

                if not self.options['ms_dir']:
                    me5_cmd = madevent_interface.MadEventCmdShell(me_dir=os.path.realpath(\
                                                    decay_dir), options=mg5.options)
                    me5_cmd.options["automatic_html_opening"] = False
                    if self.options["run_card"]:
                        run_card = self.options["run_card"]
                    else:
                        run_card = banner.RunCard(
                            pjoin(decay_dir, "Cards", "run_card.dat"))
                    run_card["nevents"] = int(1.2 * nb_event)
                    run_card["iseed"] = self.seed
                    run_card.write(pjoin(decay_dir, "Cards", "run_card.dat"))
                    param_card = self.banner['slha']
                    open(pjoin(decay_dir, "Cards", "param_card.dat"),
                         "w").write(param_card)
                    self.seed += 1
                    me5_cmd.exec_cmd("generate_events run_01 -f")
                    me5_cmd.exec_cmd("exit")
                    out[i] = lhe_parser.EventFile(
                        pjoin(decay_dir, "Events", 'run_01',
                              'unweighted_events.lhe.gz'))
                else:
                    misc.call(
                        ['run.sh',
                         str(int(1.2 * nb_event)),
                         str(self.seed)],
                        cwd=decay_dir)
                    out[i] = lhe_parser.EventFile(
                        pjoin(decay_dir, 'events.lhe.gz'))
                if cumul:
                    break

            return out
    for style in styles:
        f_code += "\nwrite(*,*) ''\nwrite(*,*) 'Style %s in red.'\n"%style
        f_code += MadLoopBannerStyles.get_MadLoop_Banner(style=style, color='red')

    for style in styles:
        f_code += "\nwrite(*,*) ''\nwrite(*,*) 'Style %s in green.'\n"%style
        f_code += MadLoopBannerStyles.get_MadLoop_Banner(style=style, color='green')

    for style in styles:
        f_code += "\nwrite(*,*) ''\nwrite(*,*) 'Style %s without frame.'\n"%style
        f_code += MadLoopBannerStyles.get_MadLoop_Banner(style=style, print_frame=False)
    
    for style in styles:
        f_code += "\nwrite(*,*) ''\nwrite(*,*) 'Style %s with a different frame.'\n"%style
        f_code += MadLoopBannerStyles.get_MadLoop_Banner(
            side_margin=10, up_margin=3,
            top_frame_char = '-',
            bottom_frame_char = '-',
            left_frame_char = '*',
            right_frame_char = '*',
            style=style)
    
    writer.writelines("program testMLBanner\n%s\nend\n"%f_code)
    writer.close()
    # Now compile and run the code
    if os.path.isfile(pjoin(os.getcwd(),'test_ML_banner')):
        os.remove(pjoin(os.getcwd(),'test_ML_banner'))
    misc.call('gfortran -o test_ML_banner test_ML_banner.f',
                                                     cwd=os.getcwd(),shell=True)
    misc.call('./test_ML_banner',cwd=os.getcwd(),shell=True)
Beispiel #18
0
    def do_import(self, inputfile):
        """import the event file"""
        
        args = self.split_arg(inputfile)
        if not args:
            return self.InvalidCmd, 'import requires arguments'
        elif args[0] == 'model':
            return self.import_model(args[1:])
        
        # change directory where to write the output
        self.options['curr_dir'] = os.path.realpath(os.path.dirname(inputfile))
        if os.path.basename(os.path.dirname(os.path.dirname(inputfile))) == 'Events':
            self.options['curr_dir'] = pjoin(self.options['curr_dir'], 
                                                      os.path.pardir, os.pardir)
        
        if not os.path.exists(inputfile):
            if inputfile.endswith('.gz'):
                if not os.path.exists(inputfile[:-3]):
                    raise self.InvalidCmd('No such file or directory : %s' % inputfile)
                else: 
                    inputfile = inputfile[:-3]
            elif os.path.exists(inputfile + '.gz'):
                inputfile = inputfile + '.gz'
            else: 
                raise self.InvalidCmd('No such file or directory : %s' % inputfile)
        
        if inputfile.endswith('.gz'):
            misc.call(['gunzip', inputfile])
            inputfile = inputfile[:-3]

        # Read the banner of the inputfile
        self.events_file = open(os.path.realpath(inputfile))
        self.banner = banner.Banner(self.events_file)
        
        # Check the validity of the banner:
        if 'slha' not in self.banner:
            self.events_file = None
            raise self.InvalidCmd('Event file does not contain model information')
        elif 'mg5proccard' not in self.banner:
            self.events_file = None
            raise self.InvalidCmd('Event file does not contain generation information')

        
        if 'madspin' in self.banner:
            raise self.InvalidCmd('This event file was already decayed by MS. This is not possible to add to it a second decay')
        
        if 'mgruncard' in self.banner:
            if not self.options['Nevents_for_max_weigth']:
                nevents = int(self.banner.get_detail('run_card', 'nevents'))
                N_weight = max([75, int(3*nevents**(1/3))])
                self.options['Nevents_for_max_weigth'] = N_weight
                N_sigma = max(4.5, math.log(nevents,7.7))
                self.options['nb_sigma'] = N_sigma
            if self.options['BW_cut'] == -1:
                self.options['BW_cut'] = float(self.banner.get_detail('run_card', 'bwcutoff'))

        else:
            if not self.options['Nevents_for_max_weigth']:
                self.options['Nevents_for_max_weigth'] = 75
                self.options['nb_sigma'] = 4.5
            if self.options['BW_cut'] == -1:
                self.options['BW_cut'] = 15.0
                
                
        # load information
        process = self.banner.get_detail('proc_card', 'generate')
        if not process:
            msg = 'Invalid proc_card information in the file (no generate line):\n %s' % self.banner['mg5proccard']
            raise Exception, msg
        process, option = mg_interface.MadGraphCmd.split_process_line(process)
        self.proc_option = option
        
        logger.info("process: %s" % process)
        logger.info("options: %s" % option)


        # Read the final state of the production process:
        #     "_full" means with the complete decay chain syntax 
        #     "_compact" means without the decay chain syntax 
        self.final_state_full = process[process.find(">")+1:]
        self.final_state_compact, self.prod_branches=\
                 self.decay.get_final_state_compact(self.final_state_full)
                
        # Load the model
        complex_mass = False   
        has_cms = re.compile(r'''set\s+complex_mass_scheme\s*(True|T|1|true|$|;)''')
        for line in self.banner.proc_card:
            if line.startswith('set'):
                self.mg5cmd.exec_cmd(line, printcmd=False, precmd=False, postcmd=False)
                if has_cms.search(line):
                    complex_mass = True
        
          
        info = self.banner.get('proc_card', 'full_model_line')
        if '-modelname' in info:
            mg_names = False
        else:
            mg_names = True
        model_name = self.banner.get('proc_card', 'model')
        if model_name:
            self.load_model(model_name, mg_names, complex_mass)
        else:
            raise self.InvalidCmd('Only UFO model can be loaded in MadSpin.')
        
        # check particle which can be decayed:
        self.final_state = set()
        for line in self.banner.proc_card:
            line = ' '.join(line.strip().split())
            if line.startswith('generate'):
                self.final_state.update(self.mg5cmd.get_final_part(line[8:]))
            elif line.startswith('add process'):
                self.final_state.update(self.mg5cmd.get_final_part(line[11:]))
            elif line.startswith('define'):
                self.mg5cmd.exec_cmd(line, printcmd=False, precmd=False, postcmd=False)            
            elif line.startswith('set'):
                self.mg5cmd.exec_cmd(line, printcmd=False, precmd=False, postcmd=False)
Beispiel #19
0
        def generate_events(pdg, nb_event, mg5, restrict_file=None, cumul=False):
            """generate new events for this particle
               restrict_file allow to only generate a subset of the definition
               cumul allow to merge all the definition in one run (add process)
                     to generate events according to cross-section
            """
                        
            part = self.model.get_particle(pdg)
            name = part.get_name()
            out = {}
            logger.info("generate %s decay event for particle %s" % (nb_event, name))
            if name not in self.list_branches:
                return out
            for i,proc in enumerate(self.list_branches[name]):
                if restrict_file and i not in restrict_file:
                    continue
                decay_dir = pjoin(self.path_me, "decay_%s_%s" %(str(pdg).replace("-","x"),i))
                if not os.path.exists(decay_dir):
                    if cumul:
                        mg5.exec_cmd("generate %s" % proc)
                        for j,proc2 in enumerate(self.list_branches[name][1:]):
                            if restrict_file and j not in restrict_file:
                                raise Exception # Do not see how this can happen
                            mg5.exec_cmd("add process %s" % proc2)
                        mg5.exec_cmd("output %s -f" % decay_dir)
                    else:
                        mg5.exec_cmd("generate %s" % proc)
                        mg5.exec_cmd("output %s -f" % decay_dir)
                    
                    options = dict(mg5.options)
                    if self.options['ms_dir']:
                        misc.sprint("start gridpack!")
                        # we are in gridpack mode -> create it
                        me5_cmd = madevent_interface.MadEventCmdShell(me_dir=os.path.realpath(\
                                                decay_dir), options=options)
                        me5_cmd.options["automatic_html_opening"] = False
                        if self.options["run_card"]:
                            run_card = self.options["run_card"]
                        else:
                            run_card = banner.RunCard(pjoin(decay_dir, "Cards", "run_card.dat"))                        
                        
                        run_card["iseed"] = self.seed
                        run_card['gridpack'] = True
                        run_card.write(pjoin(decay_dir, "Cards", "run_card.dat"))
                        param_card = self.banner['slha']
                        open(pjoin(decay_dir, "Cards", "param_card.dat"),"w").write(param_card)
                        self.seed += 1
                        # actually creation
                        me5_cmd.exec_cmd("generate_events run_01 -f")
                        me5_cmd.exec_cmd("exit")                        
                        #remove pointless informat
                        misc.call(["rm", "Cards", "bin", 'Source', 'SubProcesses'], cwd=decay_dir)
                        misc.call(['tar', '-xzpvf', 'run_01_gridpack.tar.gz'], cwd=decay_dir)
                
                # Now generate the events

                if not self.options['ms_dir']:
                    me5_cmd = madevent_interface.MadEventCmdShell(me_dir=os.path.realpath(\
                                                    decay_dir), options=mg5.options)
                    me5_cmd.options["automatic_html_opening"] = False
                    if self.options["run_card"]:
                        run_card = self.options["run_card"]
                    else:
                        run_card = banner.RunCard(pjoin(decay_dir, "Cards", "run_card.dat"))
                    run_card["nevents"] = int(1.2*nb_event)
                    run_card["iseed"] = self.seed
                    run_card.write(pjoin(decay_dir, "Cards", "run_card.dat"))
                    param_card = self.banner['slha']
                    open(pjoin(decay_dir, "Cards", "param_card.dat"),"w").write(param_card)
                    self.seed += 1
                    me5_cmd.exec_cmd("generate_events run_01 -f")
                    me5_cmd.exec_cmd("exit")
                    out[i] = lhe_parser.EventFile(pjoin(decay_dir, "Events", 'run_01', 'unweighted_events.lhe.gz'))            
                else:
                    misc.call(['run.sh', str(int(1.2*nb_event)), str(self.seed)], cwd=decay_dir)     
                    out[i] = lhe_parser.EventFile(pjoin(decay_dir, 'events.lhe.gz'))            
                if cumul:
                    break
            
            return out
Beispiel #20
0
    def do_launch(self, line):
        """end of the configuration launched the code"""
        
        if self.options["spinmode"] in ["none"]:
            return self.run_bridge(line)
        elif self.options["spinmode"] == "bridge":
            raise Exception, "Bridge mode not yet available due to lack of validation."
        
        if self.options['ms_dir'] and os.path.exists(pjoin(self.options['ms_dir'], 'madspin.pkl')):
            return self.run_from_pickle()
        
    
        args = self.split_arg(line)
        self.check_launch(args)
        for part in self.list_branches.keys():
            if part in self.mg5cmd._multiparticles:
                if any(pid in self.final_state for pid in self.mg5cmd._multiparticles[part]):
                    break
            pid = self.mg5cmd._curr_model.get('name2pdg')[part]
            if pid in self.final_state:
                break
#        else:
#            logger.info("Nothing to decay ...")
#            return
        

        model_line = self.banner.get('proc_card', 'full_model_line')

        if not self.seed:
            self.seed = random.randint(0, int(30081*30081))
            self.do_set('seed %s' % self.seed)
            logger.info('Will use seed %s' % self.seed)
            self.history.insert(0, 'set seed %s' % self.seed)

        if self.seed > 30081*30081: # can't use too big random number
            msg = 'Random seed too large ' + str(self.seed) + ' > 30081*30081'
            raise Exception, msg

        self.options['seed'] = self.seed
        text = '%s\n' % '\n'.join([ line for line in self.history if line])
        self.banner.add_text('madspin' , text)
        
        
        self.update_status('generating Madspin matrix element')
        generate_all = madspin.decay_all_events(self, self.banner, self.events_file, 
                                                    self.options)
        
        self.update_status('running MadSpin')
        generate_all.run()
                        
        self.branching_ratio = generate_all.branching_ratio
        try:
            self.err_branching_ratio = generate_all.err_branching_ratio
        except Exception:
            self.err_branching_ratio = 0
            
        evt_path = self.events_file.name
        try:
            self.events_file.close()
        except:
            pass
        misc.gzip(evt_path)
        decayed_evt_file=evt_path.replace('.lhe', '_decayed.lhe')
        misc.gzip(pjoin(self.options['curr_dir'],'decayed_events.lhe'),
                  stdout=decayed_evt_file)
        if not self.mother:
            logger.info("Decayed events have been written in %s.gz" % decayed_evt_file)

        # Now arxiv the shower card used if RunMaterial is present
        ms_card_path = pjoin(self.options['curr_dir'],'Cards','madspin_card.dat')
        run_dir = os.path.realpath(os.path.dirname(decayed_evt_file))
        if os.path.exists(ms_card_path):
            if os.path.exists(pjoin(run_dir,'RunMaterial.tar.gz')):
                misc.call(['tar','-xzpf','RunMaterial.tar.gz'], cwd=run_dir)
                base_path = pjoin(run_dir,'RunMaterial')
            else:
                base_path = pjoin(run_dir)

            evt_name = os.path.basename(decayed_evt_file).replace('.lhe', '')
            ms_card_to_copy = pjoin(base_path,'madspin_card_for_%s.dat'%evt_name)
            count = 0    
            while os.path.exists(ms_card_to_copy):
                count += 1
                ms_card_to_copy = pjoin(base_path,'madspin_card_for_%s_%d.dat'%\
                                                               (evt_name,count))
            files.cp(str(ms_card_path),str(ms_card_to_copy))
            
            if os.path.exists(pjoin(run_dir,'RunMaterial.tar.gz')):
                misc.call(['tar','-czpf','RunMaterial.tar.gz','RunMaterial'], 
                                                                    cwd=run_dir)
                shutil.rmtree(pjoin(run_dir,'RunMaterial'))