Ejemplo n.º 1
0
    def test_group_subprocess(self):
        """check that both u u > u u gives the same result"""
        

        mg_cmd = MGCmd.MasterCmd()
        mg_cmd.exec_cmd('set automatic_html_opening False --no_save')
        mg_cmd.exec_cmd(' generate u u > u u')
        mg_cmd.exec_cmd('output %s/'% self.run_dir)
        self.cmd_line = MECmd.MadEventCmdShell(me_dir= self.run_dir)
        self.cmd_line.exec_cmd('set automatic_html_opening False')
        
        self.do('generate_events -f')
        val1 = self.cmd_line.results.current['cross']
        err1 = self.cmd_line.results.current['error']
        
        self.run_dir = pjoin(self.path, 'MGPROC2')
        mg_cmd.exec_cmd('set group_subprocesses False')
        mg_cmd.exec_cmd('generate u u > u u')
        mg_cmd.exec_cmd('output %s' % self.run_dir)
        self.cmd_line = MECmd.MadEventCmdShell(me_dir= self.run_dir)
        self.cmd_line.exec_cmd('set automatic_html_opening False')

        
        self.do('generate_events -f')        
        
        val2 = self.cmd_line.results.current['cross']
        err2 = self.cmd_line.results.current['error']        
        
        self.assertTrue(abs(val2 - val1) / (err1 + err2) < 5)
        target = 1310200.0
        self.assertTrue(abs(val2 - target) / (err2) < 5)
        #check precision
        self.assertTrue(err2 / val2 < 0.005)
        self.assertTrue(err1 / val1 < 0.005)
Ejemplo n.º 2
0
    def test_e_e_collision(self):
        """check that e+ e- > t t~ gives the correct result"""

        mg_cmd = MGCmd.MasterCmd()
        mg_cmd.no_notification()
        mg_cmd.exec_cmd('set automatic_html_opening False --save')
        mg_cmd.exec_cmd(' generate e+ e-  > e+ e-')
        mg_cmd.exec_cmd('output %s/' % self.run_dir)
        self.cmd_line = MECmd.MadEventCmdShell(me_dir=self.run_dir)
        self.cmd_line.no_notification()

        # couple of test checking that default run_card is as expected
        run_card = banner.RunCardLO(
            pjoin(self.run_dir, 'Cards', 'run_card.dat'))
        self.assertFalse('ptj' in run_card.user_set)
        self.assertFalse('drjj' in run_card.user_set)
        self.assertFalse('ptj2min' in run_card.user_set)
        self.assertFalse('ptj3min' in run_card.user_set)
        self.assertFalse('mmjj' in run_card.user_set)
        self.assertFalse('ptheavy' in run_card.user_set)
        self.assertTrue('el' in run_card.user_set)
        self.assertTrue('polbeam1' in run_card.user_set)
        self.assertTrue('ptl' in run_card.user_set)

        shutil.copy(os.path.join(_file_path, 'input_files', 'run_card_ee.dat'),
                    '%s/Cards/run_card.dat' % self.run_dir)

        self.do('generate_events -f')
        val1 = self.cmd_line.results.current['cross']
        err1 = self.cmd_line.results.current['error']

        target = 155.9
        self.assertTrue(abs(val1 - target) / err1 < 2.)
Ejemplo n.º 3
0
    def generate(self, process, model):
        """Create a process"""

        try:
            shutil.rmtree(self.run_dir)
        except Exception as error:
            pass
        interface = MGCmd.MasterCmd()
        interface.no_notification()
        interface.run_cmd('import model %s' % model)
        if isinstance(process, str):
            interface.run_cmd('generate %s' % process)
        else:
            for p in process:
                interface.run_cmd('add process %s' % p)

        if logging.getLogger('madgraph').level <= 20:
            stdout = None
            stderr = None
        else:
            devnull = open(os.devnull, 'w')
            stdout = devnull
            stderr = devnull

        if not os.path.exists(pjoin(MG5DIR, 'pythia-pgs')):
            print("install pythia-pgs")
            p = subprocess.Popen([pjoin(MG5DIR, 'bin', 'mg5')],
                                 stdin=subprocess.PIPE,
                                 stdout=stdout,
                                 stderr=stderr)
            out = p.communicate('install pythia-pgs'.encode())
        misc.compile(cwd=pjoin(MG5DIR, 'pythia-pgs'))
        if not os.path.exists(pjoin(MG5DIR, 'MadAnalysis')):
            print("install MadAnalysis")
            p = subprocess.Popen([pjoin(MG5DIR, 'bin', 'mg5')],
                                 stdin=subprocess.PIPE,
                                 stdout=stdout,
                                 stderr=stderr)
            out = p.communicate('install MadAnalysis4'.encode())
        misc.compile(cwd=pjoin(MG5DIR, 'MadAnalysis'))

        if not misc.which('root'):
            raise Exception('root is require for this test')
        interface.exec_cmd('set pythia-pgs_path %s --no_save' %
                           pjoin(MG5DIR, 'pythia-pgs'))
        interface.exec_cmd('set madanalysis_path %s --no_save' %
                           pjoin(MG5DIR, 'MadAnalysis'))
        interface.onecmd('output madevent %s -f' % self.run_dir)

        if os.path.exists(pjoin(interface.options['syscalc_path'],
                                'sys_calc')):
            shutil.rmtree(interface.options['syscalc_path'])
            #print "install SysCalc"
            #interface.onecmd('install SysCalc')

        self.cmd_line = MECmd.MadEventCmdShell(me_dir=self.run_dir)
        self.cmd_line.no_notification()
        self.cmd_line.options['syscalc_path'] = pjoin(MG5DIR, 'SysCalc')
Ejemplo n.º 4
0
    def test_complex_mass_scheme(self):
        """check that auto-width and Madspin works nicely with complex-mass-scheme"""
        mg_cmd = MGCmd.MasterCmd()
        mg_cmd.no_notification()
        mg_cmd.exec_cmd('set automatic_html_opening False --save')
        mg_cmd.exec_cmd('set complex_mass_scheme', precmd=True)
        mg_cmd.exec_cmd('generate g g  > t t~', precmd=True)
        mg_cmd.exec_cmd('output %s' % self.run_dir, precmd=True)

        self.cmd_line = MECmd.MadEventCmdShell(me_dir=self.run_dir)
        self.cmd_line.no_notification()
        self.cmd_line.exec_cmd('set automatic_html_opening False')

        #modify run_card
        run_card = banner_mod.RunCard(
            pjoin(self.run_dir, 'Cards', 'run_card.dat'))
        run_card.set('nevents', 100)
        run_card.write(pjoin(self.run_dir, 'Cards', 'run_card.dat'))

        # check the auto-width
        self.cmd_line.exec_cmd('compute_widths 6 -f')

        # check value for the width
        import models.check_param_card as check_param_card
        param_card = check_param_card.ParamCard(
            pjoin(self.run_dir, 'Cards', 'param_card.dat'))
        self.assertTrue(misc.equal(1.491257, param_card['decay'].get(6).value),
                        3)

        # generate events
        self.cmd_line.exec_cmd('launch -f')
        val1 = self.cmd_line.results.current['cross']
        err1 = self.cmd_line.results.current['error']
        target = 440.779
        self.assertTrue(misc.equal(target, val1, 4 * err1))

        # run madspin
        fsock = open(pjoin(self.run_dir, 'Cards', 'madspin_card.dat'), 'w')
        fsock.write('decay t > w+ b \n launch')
        fsock.close()

        self.cmd_line.exec_cmd('decay_events run_01 -f')
        val1 = self.cmd_line.results.current['cross']
        err1 = self.cmd_line.results.current['error']
        target = 440.779
        self.assertTrue(misc.equal(target, val1, 4 * err1))
Ejemplo n.º 5
0
    def test_e_e_collision(self):
        """check that e+ e- > t t~ gives the correct result"""

        mg_cmd = MGCmd.MasterCmd()
        mg_cmd.exec_cmd('set automatic_html_opening False --save')
        mg_cmd.exec_cmd(' generate e+ e-  > e+ e-')
        mg_cmd.exec_cmd('output %s/' % self.run_dir)
        self.cmd_line = MECmd.MadEventCmdShell(me_dir=self.run_dir)
        self.cmd_line.exec_cmd('set automatic_html_opening False')
        shutil.copy(os.path.join(_file_path, 'input_files', 'run_card_ee.dat'),
                    '%s/Cards/run_card.dat' % self.run_dir)

        self.do('generate_events -f')
        val1 = self.cmd_line.results.current['cross']
        err1 = self.cmd_line.results.current['error']

        target = 155.9
        self.assertTrue(abs(val1 - target) / err1 < 1.)
Ejemplo n.º 6
0
    def test_e_p_collision(self):
        """check that e p > e j gives the correct result"""
        

        mg_cmd = MGCmd.MasterCmd()
        mg_cmd.exec_cmd('set automatic_html_opening False --save')
        mg_cmd.exec_cmd(' generate e- p  > e- j')
        mg_cmd.exec_cmd('output %s/'% self.run_dir)
        self.cmd_line = MECmd.MadEventCmdShell(me_dir=  self.run_dir)
        self.cmd_line.exec_cmd('set automatic_html_opening False')
        shutil.copy(os.path.join(_file_path, 'input_files', 'run_card_ep.dat'),
                    '%s/Cards/run_card.dat' % self.run_dir) 
        
        self.do('generate_events -f')
        val1 = self.cmd_line.results.current['cross']
        err1 = self.cmd_line.results.current['error']
        
        target = 3864.0
        self.assertTrue(abs(val1 - target) / err1 < 1., 'large diference between %s and %s +- %s'%
                        (target, val1, err1))
Ejemplo n.º 7
0
    def test_e_p_collision(self):
        """check that e p > e j gives the correct result"""

        mg_cmd = MGCmd.MasterCmd()
        mg_cmd.no_notification()
        mg_cmd.exec_cmd('set automatic_html_opening False --save')
        mg_cmd.exec_cmd(' generate e- p  > e- j')
        mg_cmd.exec_cmd('output %s/' % self.run_dir)
        self.cmd_line = MECmd.MadEventCmdShell(me_dir=self.run_dir)
        self.cmd_line.no_notification()
        self.cmd_line.exec_cmd('set automatic_html_opening False')

        #check validity of the default run_card
        run_card = banner.RunCardLO(
            pjoin(self.run_dir, 'Cards', 'run_card.dat'))
        self.assertTrue('ptj' in run_card.user_set)
        self.assertFalse('drjj' in run_card.user_set)
        self.assertFalse('ptj2min' in run_card.user_set)
        self.assertFalse('ptj3min' in run_card.user_set)
        self.assertFalse('mmjj' in run_card.user_set)
        self.assertFalse('ptheavy' in run_card.user_set)
        self.assertFalse('el' in run_card.user_set)
        self.assertFalse('ej' in run_card.user_set)
        self.assertTrue('polbeam1' in run_card.user_set)
        self.assertTrue('ptl' in run_card.user_set)

        shutil.copy(os.path.join(_file_path, 'input_files', 'run_card_ep.dat'),
                    '%s/Cards/run_card.dat' % self.run_dir)

        self.do('generate_events -f')
        val1 = self.cmd_line.results.current['cross']
        err1 = self.cmd_line.results.current['error']

        target = 3932.0
        self.assertTrue(
            abs(val1 - target) / err1 < 1.,
            'large diference between %s and %s +- %s' % (target, val1, err1))
Ejemplo n.º 8
0
class TestMECmdShell(unittest.TestCase):
    """this treats all the command not related to MG_ME"""
    def setUp(self):

        self.debugging = False
        if self.debugging:
            self.path = pjoin(MG5DIR, "tmp_test")
            if os.path.exists(self.path):
                shutil.rmtree(self.path)
            os.mkdir(pjoin(MG5DIR, "tmp_test"))
        else:
            self.path = tempfile.mkdtemp(prefix='acc_test_mg5')
        self.run_dir = pjoin(self.path, 'MGPROC')

    def tearDown(self):

        if self.path != pjoin(MG5DIR, "tmp_test"):
            shutil.rmtree(self.path)

    def generate(self, process, model):
        """Create a process"""

        try:
            shutil.rmtree(self.run_dir)
        except Exception, error:
            pass
        interface = MGCmd.MasterCmd()
        interface.no_notification()
        interface.run_cmd('import model %s' % model)
        if isinstance(process, str):
            interface.run_cmd('generate %s' % process)
        else:
            for p in process:
                interface.run_cmd('add process %s' % p)

        if logging.getLogger('madgraph').level <= 20:
            stdout = None
            stderr = None
        else:
            devnull = open(os.devnull, 'w')
            stdout = devnull
            stderr = devnull

        if not os.path.exists(pjoin(MG5DIR, 'pythia-pgs')):
            print "install pythia-pgs"
            p = subprocess.Popen([pjoin(MG5DIR, 'bin', 'mg5')],
                                 stdin=subprocess.PIPE,
                                 stdout=stdout,
                                 stderr=stderr)
            out = p.communicate('install pythia-pgs')
        misc.compile(cwd=pjoin(MG5DIR, 'pythia-pgs'))
        if not os.path.exists(pjoin(MG5DIR, 'MadAnalysis')):
            print "install MadAnalysis"
            p = subprocess.Popen([pjoin(MG5DIR, 'bin', 'mg5')],
                                 stdin=subprocess.PIPE,
                                 stdout=stdout,
                                 stderr=stderr)
            out = p.communicate('install MadAnalysis4')
        misc.compile(cwd=pjoin(MG5DIR, 'MadAnalysis'))

        if not misc.which('root'):
            raise Exception, 'root is require for this test'
        interface.exec_cmd('set pythia-pgs_path %s --no_save' %
                           pjoin(MG5DIR, 'pythia-pgs'))
        interface.exec_cmd('set madanalysis_path %s --no_save' %
                           pjoin(MG5DIR, 'MadAnalysis'))
        interface.onecmd('output madevent %s -f' % self.run_dir)

        if os.path.exists(pjoin(interface.options['syscalc_path'],
                                'sys_calc')):
            shutil.rmtree(interface.options['syscalc_path'])
            #print "install SysCalc"
            #interface.onecmd('install SysCalc')

        self.cmd_line = MECmd.MadEventCmdShell(me_dir=self.run_dir)
        self.cmd_line.no_notification()
        self.cmd_line.options['syscalc_path'] = pjoin(MG5DIR, 'SysCalc')
Ejemplo n.º 9
0
    def launch_program(self):
        """launch the main program"""

        # Check for number of cores if multicore mode
        mode = str(self.cluster)
        nb_node = 1
        if mode == "2":
            import multiprocessing
            max_node = multiprocessing.cpu_count()
            if max_node == 1:
                logger.warning(
                    'Only one core is detected on your computer! Pass in single machine'
                )
                self.cluster = 0
                self.launch_program()
                return
            elif max_node == 2:
                nb_node = 2
            elif not self.force:
                nb_node = self.ask('How many cores do you want to use?',
                                   max_node, range(2, max_node + 1))
            else:
                nb_node = max_node

        import madgraph.interface.madevent_interface as ME

        stdout_level = self.cmd_int.options['stdout_level']
        if self.shell:
            usecmd = ME.MadEventCmdShell(me_dir=self.running_dir,
                                         options=self.options)
        else:
            usecmd = ME.MadEventCmd(me_dir=self.running_dir,
                                    options=self.options)
            usecmd.pass_in_web_mode()
        #Check if some configuration were overwritten by a command. If so use it
        set_cmd = [
            l for l in self.cmd_int.history if l.strip().startswith('set')
        ]
        all_options = usecmd.options_configuration.keys(
        ) + usecmd.options_madgraph.keys() + usecmd.options_madevent.keys()
        for line in set_cmd:
            arg = line.split()
            if arg[1] not in all_options:
                continue
            try:
                usecmd.do_set(line[3:], log=False)
            except usecmd.InvalidCmd:
                pass
        usecmd.do_set('stdout_level %s' % stdout_level, log=False)
        #ensure that the logger level
        launch = self.cmd_int.define_child_cmd_interface(usecmd,
                                                         interface=False)
        #launch.me_dir = self.running_dir
        if self.unit == 'pb':
            command = 'generate_events %s' % self.name
        else:
            warning_text = '''\
This command will create a new param_card with the computed width. 
This param_card makes sense only if you include all processes for
the computation of the width.'''
            logger.warning(warning_text)

            command = 'calculate_decay_widths %s' % self.name
        if mode == "1":
            command += " --cluster"
        elif mode == "2":
            command += " --nb_core=%s" % nb_node

        if self.force:
            command += " -f"

        if self.laststep:
            command += ' --laststep=%s' % self.laststep

        try:
            os.remove('ME5_debug')
        except:
            pass

        launch.run_cmd(command)
        launch.run_cmd('quit')

        if os.path.exists('ME5_debug'):
            return True

        # Display the cross-section to the screen
        path = os.path.join(self.running_dir, 'SubProcesses', 'results.dat')
        if not os.path.exists(path):
            logger.error('Generation failed (no results.dat file found)')
            return
        fsock = open(path)
        line = fsock.readline()
        cross, error = line.split()[0:2]

        logger.info('more information in %s' %
                    os.path.join(self.running_dir, 'index.html'))
Ejemplo n.º 10
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
Ejemplo n.º 11
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)
                import madgraph.interface.madevent_interface as madevent_interface
                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["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'))
                if cumul:
                    break

            return out