~maddevelopers/mg5amcnlo/2.5.0

« back to all changes in this revision

Viewing changes to madgraph/interface/common_run_interface.py

  • Committer: olivier Mattelaer
  • Date: 2016-08-22 20:43:28 UTC
  • mfrom: (262.13.38 plugin_mode)
  • Revision ID: olivier.mattelaer@uclouvain.be-20160822204328-898681196houupn4
merge the plugin_mode branch

Show diffs side-by-side

added added

removed removed

Lines of Context:
739
739
                    param = param_card['decay'].get((part.pdg_code,))
740
740
 
741
741
                    if  param.value != 0:
742
 
                        logger.info('''For gauge cancellation, the width of \'%s\' has been set to zero.'''
 
742
                        logger.info('''For gauge cancellation, the width of \'%s\' has been set to zero.'''\
743
743
                                    % part.name,'$MG:color:BLACK')
744
744
                        param.value = 0
745
745
 
746
746
            param_card.write_inc_file(outfile, ident_card, default)
747
747
 
 
748
    def get_model(self):
 
749
        """return the model related to this process"""
 
750
 
 
751
        if self.options['mg5_path']:
 
752
            sys.path.append(self.options['mg5_path'])
 
753
            import models.import_ufo as import_ufo
 
754
            with misc.MuteLogger(['madgraph.model'],[50]):
 
755
                out= import_ufo.import_model(pjoin(self.me_dir,'bin','internal','ufomodel'))
 
756
            return out
 
757
        elif self.mother:
 
758
            return self.mother._curr_model
 
759
        else:
 
760
            return None
748
761
 
749
762
    def ask_edit_cards(self, cards, mode='fixed', plot=True, first_cmd=None):
750
763
        """ """
1685
1698
        if self.cluster_mode == 1:
1686
1699
            opt = self.options
1687
1700
            cluster_name = opt['cluster_type']
1688
 
            self.cluster = cluster.from_name[cluster_name](**opt)
1689
 
 
1690
 
 
1691
 
    def check_param_card(self, path, run=True):
 
1701
            if cluster_name in cluster.from_name:
 
1702
                self.cluster = cluster.from_name[cluster_name](**opt)
 
1703
            else:
 
1704
                if MADEVENT and ('mg5_path' not in self.options or not self.options['mg5_path']):
 
1705
                    raise self.InvalidCmd('%s not native cluster type and not MG5aMC found to check for plugin')
 
1706
                elif MADEVENT:
 
1707
                    mg5dir = self.options['mg5_path']
 
1708
                    if mg5dir not in sys.path:
 
1709
                        sys.path.append(mg5dir)
 
1710
                else:
 
1711
                    mg5dir = MG5DIR
 
1712
                # Check if a plugin define this type of cluster
 
1713
                # check for PLUGIN format
 
1714
                for plug in os.listdir(pjoin(mg5dir, 'PLUGIN')):
 
1715
                    if os.path.exists(pjoin(mg5dir, 'PLUGIN', plug, '__init__.py')):
 
1716
                        try:
 
1717
                            __import__('PLUGIN.%s' % plug)
 
1718
                        except Exception, error:
 
1719
                            logger.critical('plugin directory %s fail to be loaded. Please check it', plug)
 
1720
                            continue
 
1721
                        plugin = sys.modules['PLUGIN.%s' % plug]  
 
1722
                        if not hasattr(plugin, 'new_cluster'):
 
1723
                            continue
 
1724
                        if not misc.is_plugin_supported(plugin):
 
1725
                            continue              
 
1726
                        if cluster_name in plugin.new_cluster:
 
1727
                            logger.info("cluster handling will be done with PLUGIN: %s" % plug,'$MG:color:BLACK')
 
1728
                            self.cluster = plugin.new_cluster[cluster_name](**opt)
 
1729
                            break
 
1730
                else:
 
1731
                    raise self.InvalidCmd, "%s is not recognized as a supported cluster format." % cluster_name
 
1732
                
 
1733
                
 
1734
    def check_param_card(self, path, run=True, dependent=False):
1692
1735
        """
1693
1736
        1) Check that no scan parameter are present
1694
1737
        2) Check that all the width are define in the param_card.
1695
1738
        - If a scan parameter is define. create the iterator and recall this fonction 
1696
1739
          on the first element.
1697
 
        - If some width are set on 'Auto', call the computation tools."""
 
1740
        - If some width are set on 'Auto', call the computation tools.
 
1741
        3) if dependent is on True check for dependent parameter (automatic for scan)"""
1698
1742
        
1699
1743
        pattern_scan = re.compile(r'''^(decay)?[\s\d]*scan''', re.I+re.M)  
1700
1744
        pattern_width = re.compile(r'''decay\s+(\+?\-?\d+)\s+auto(@NLO|)''',re.I)
1709
1753
            self.param_card_iterator = main_card
1710
1754
            first_card = main_card.next(autostart=True)
1711
1755
            first_card.write(path)
1712
 
            return self.check_param_card(path, run)
 
1756
            return self.check_param_card(path, run, dependent=True)
1713
1757
        
1714
1758
        pdg_info = pattern_width.findall(text)
1715
1759
        if pdg_info:
1720
1764
                if not has_nlo:
1721
1765
                    self.do_compute_widths('%s %s' % (' '.join(pdg), path))
1722
1766
                else:
1723
 
                    self.do_compute_widths('%s %s --nlo' % (' '.join(pdg), path))
 
1767
                    self.do_compute_widths('%s %s --nlo' % (' '.join(pdg), path)) 
1724
1768
            else:
1725
1769
                logger.info('''Some width are on Auto in the card. 
1726
1770
    Those will be computed as soon as you have finish the edition of the cards.
1727
1771
    If you want to force the computation right now and being able to re-edit
1728
1772
    the cards afterwards, you can type \"compute_wdiths\".''')
1729
 
 
 
1773
        
 
1774
        if dependent:   
 
1775
            card = check_param_card.ParamCard(path)
 
1776
            AskforEditCard.update_dependent(self, self.me_dir, card, path, timer=20)
 
1777
        
 
1778
        return
1730
1779
 
1731
1780
    def add_error_log_in_html(self, errortype=None):
1732
1781
        """If a ME run is currently running add a link in the html output"""
2138
2187
 
2139
2188
 
2140
2189
 
2141
 
    def complete_compute_widths(self, text, line, begidx, endidx):
 
2190
    def complete_compute_widths(self, text, line, begidx, endidx, formatting=True):
2142
2191
        "Complete the compute_widths command"
2143
2192
 
2144
2193
        args = self.split_arg(line[0:begidx])
2158
2207
                            ['--path=', '--output=', '--min_br=0.\$', '--nlo',
2159
2208
                             '--precision_channel=0.\$', '--body_decay='])            
2160
2209
        
2161
 
        return self.deal_multiple_categories(completion)
 
2210
        return self.deal_multiple_categories(completion, formatting)
2162
2211
        
2163
2212
 
2164
2213
    def update_make_opts(self):
2376
2425
            filename = pdf_info[filename]['filename']
2377
2426
        
2378
2427
        if os.path.exists(pjoin(pdfsets_dir, filename)):
2379
 
            logger.debug('%s is already present in %s', (filename, pdfsets_dir))
 
2428
            logger.debug('%s is already present in %s', filename, pdfsets_dir)
2380
2429
            return
2381
2430
             
2382
2431
        logger.info('Trying to download %s' % filename)
2530
2579
                        'fixed_scale': ['run_card fixed_fac_scale T', 'run_card fixed_ren_scale T', 'run_card scale %(0)s', 'run_card dsqrt_q2fact1 %(0)s' ,'run_card dsqrt_q2fact2 %(0)s'],
2531
2580
                        }
2532
2581
    
2533
 
    def __init__(self, question, cards=[], mode='auto', *args, **opt):
2534
 
 
 
2582
    def load_default(self):
 
2583
        """ define all default variable. No load of card here.
 
2584
            This allow to subclass this class and just change init and still have
 
2585
            all variables defined."""
 
2586
    
 
2587
        self.me_dir = None
 
2588
        self.param_card = None
 
2589
        self.run_card = {}
 
2590
        self.pname2block = {}
 
2591
        self.conflict = []
 
2592
        self.restricted_value = {}
 
2593
        self.mode = ''
 
2594
        self.cards = [] 
 
2595
        self.run_set = []
 
2596
        self.has_mw = False
 
2597
        self.has_ml = False   
 
2598
        self.has_shower = False
 
2599
        self.paths = {}
 
2600
    
 
2601
    def define_paths(self, **opt):
 
2602
        
2535
2603
        # Initiation
2536
2604
        if 'pwd' in opt:
2537
2605
            self.me_dir = opt['pwd']
2538
 
            del opt['pwd']
2539
 
 
2540
 
        cmd.OneLinePathCompletion.__init__(self, question, *args, **opt)
2541
 
 
 
2606
        elif 'mother_interface' in opt:
 
2607
            self.mother_interface = opt['mother_interface']     
2542
2608
        if not hasattr(self, 'me_dir') or not self.me_dir:
2543
2609
            self.me_dir = self.mother_interface.me_dir
2544
 
 
2545
 
        # read the card
 
2610
        
 
2611
        #define paths
 
2612
        self.paths['param'] = pjoin(self.me_dir,'Cards','param_card.dat')
 
2613
        self.paths['param_default'] = pjoin(self.me_dir,'Cards','param_card_default.dat')
 
2614
        self.paths['run'] = pjoin(self.me_dir,'Cards','run_card.dat')
 
2615
        self.paths['run_default'] = pjoin(self.me_dir,'Cards','run_card_default.dat')
 
2616
        self.paths['transfer'] =pjoin(self.me_dir,'Cards','transfer_card.dat')
 
2617
        self.paths['MadWeight'] =pjoin(self.me_dir,'Cards','MadWeight_card.dat')
 
2618
        self.paths['MadWeight_default'] =pjoin(self.me_dir,'Cards','MadWeight_card_default.dat')
 
2619
        self.paths['ML'] =pjoin(self.me_dir,'Cards','MadLoopParams.dat')
 
2620
        self.paths['shower'] = pjoin(self.me_dir,'Cards','shower_card.dat')
 
2621
        self.paths['shower_default'] = pjoin(self.me_dir,'Cards','shower_card_default.dat')
 
2622
        self.paths['pythia'] =pjoin(self.me_dir, 'Cards','pythia_card.dat')
 
2623
        self.paths['madspin_default'] = pjoin(self.me_dir,'Cards/madspin_card_default.dat')
 
2624
        self.paths['madspin'] = pjoin(self.me_dir,'Cards/madspin_card.dat')
 
2625
        self.paths['reweight'] = pjoin(self.me_dir,'Cards','reweight_card.dat')
 
2626
        self.paths['delphes'] = pjoin(self.me_dir,'Cards','delphes_card.dat')
 
2627
 
 
2628
    def __init__(self, question, cards=[], mode='auto', *args, **opt):
 
2629
 
 
2630
        self.load_default()        
 
2631
        self.define_paths(**opt)
 
2632
        cmd.OneLinePathCompletion.__init__(self, question, *args, **opt)
2546
2633
 
2547
2634
 
2548
2635
        try:
2549
 
            self.param_card = check_param_card.ParamCard(pjoin(self.me_dir,'Cards','param_card.dat'))
 
2636
            self.param_card = check_param_card.ParamCard(self.paths['param'])
2550
2637
        except (check_param_card.InvalidParamCard, ValueError) as e:
2551
2638
            logger.error('Current param_card is not valid. We are going to use the default one.')
2552
2639
            logger.error('problem detected: %s' % e)
2553
2640
            files.cp(pjoin(self.me_dir,'Cards','param_card_default.dat'),
2554
2641
                     pjoin(self.me_dir,'Cards','param_card.dat'))
2555
 
            self.param_card = check_param_card.ParamCard(pjoin(self.me_dir,'Cards','param_card.dat'))
2556
 
        default_param = check_param_card.ParamCard(pjoin(self.me_dir,'Cards','param_card_default.dat'))
 
2642
            self.param_card = check_param_card.ParamCard(self.paths['param'])
 
2643
        default_param = check_param_card.ParamCard(self.paths['param_default'])
2557
2644
        
2558
2645
        
2559
2646
        try:
2560
 
            self.run_card = banner_mod.RunCard(pjoin(self.me_dir,'Cards','run_card.dat'))
 
2647
            self.run_card = banner_mod.RunCard(self.paths['run'])
2561
2648
        except IOError:
2562
2649
            self.run_card = {}
2563
2650
        try:
2564
 
            run_card_def = banner_mod.RunCard(pjoin(self.me_dir,'Cards','run_card_default.dat'))
 
2651
            run_card_def = banner_mod.RunCard(self.paths['run_default'])
2565
2652
        except IOError:
2566
2653
            run_card_def = {}
2567
2654
 
2596
2683
            self.do_change_tf = self.mother_interface.do_define_transfer_fct
2597
2684
            self.complete_change_tf = self.mother_interface.complete_define_transfer_fct
2598
2685
            self.help_change_tf = self.mother_interface.help_define_transfer_fct
2599
 
            if not os.path.exists(pjoin(self.me_dir,'Cards','transfer_card.dat')):
 
2686
            if not os.path.exists(self.paths['transfer']):
2600
2687
                logger.warning('No transfer function currently define. Please use the change_tf command to define one.')
2601
2688
            
2602
2689
            
2605
2692
                import madgraph.madweight.Cards as mwcards
2606
2693
            except:
2607
2694
                import internal.madweight.Cards as mwcards
2608
 
            self.mw_card = mwcards.Card(pjoin(self.me_dir,'Cards','MadWeight_card.dat'))
 
2695
            self.mw_card = mwcards.Card(self.paths['MadWeight'])
2609
2696
            self.mw_card = self.mw_card.info
2610
2697
            self.mw_vars = []
2611
2698
            for key in self.mw_card:
2625
2712
                    
2626
2713
        #check if MadLoopParams.dat is present:
2627
2714
        self.has_ml = False
2628
 
        if os.path.isfile(pjoin(self.me_dir,'Cards','MadLoopParams.dat')):
 
2715
        if os.path.isfile(self.paths['ML']):
2629
2716
            self.has_ml = True
2630
 
            self.MLcard = banner_mod.MadLoopParam(pjoin(self.me_dir,'Cards','MadLoopParams.dat'))
 
2717
            self.MLcard = banner_mod.MadLoopParam(self.paths['ML'])
2631
2718
            self.MLcardDefault = banner_mod.MadLoopParam()
2632
2719
            
2633
2720
            self.ml_vars = [k.lower() for k in self.MLcard.keys()]
2648
2735
                import madgraph.various.shower_card as showercards
2649
2736
            except:
2650
2737
                import internal.shower_card as showercards
2651
 
            self.shower_card = showercards.ShowerCard(pjoin(self.me_dir,'Cards','shower_card.dat'))
 
2738
            self.shower_card = showercards.ShowerCard(self.paths['shower'])
2652
2739
            self.shower_vars = self.shower_card.keys()
2653
2740
            
2654
2741
            # check for conflict with run_card/param_card
2660
2747
                    self.conflict.append(var)
2661
2748
 
2662
2749
 
2663
 
    def complete_set(self, text, line, begidx, endidx):
 
2750
    def complete_set(self, text, line, begidx, endidx, formatting=True):
2664
2751
        """ Complete the set command"""
2665
2752
 
2666
2753
        prev_timer = signal.alarm(0) # avoid timer if any
2838
2925
                        possibilities['Special value'] = self.list_completion(text, opts)
2839
2926
                possibilities['MadWeight Card id' ] = self.list_completion(text, ids) 
2840
2927
 
2841
 
        return self.deal_multiple_categories(possibilities)
 
2928
        return self.deal_multiple_categories(possibilities, formatting)
2842
2929
 
2843
2930
    def do_set(self, line):
2844
2931
        """ edit the value of one parameter in the card"""
2893
2980
 
2894
2981
        # Special case for the qcut value
2895
2982
        if args[0].lower() == 'qcut':
2896
 
            pythia_path = pjoin(self.me_dir, 'Cards','pythia_card.dat')
 
2983
            pythia_path = self.paths['pythia']
2897
2984
            if os.path.exists(pythia_path):
2898
2985
                logger.info('add line QCUT = %s in pythia_card.dat' % args[1])
2899
2986
                p_card = open(pythia_path,'r').read()
2907
2994
                return
2908
2995
        # Special case for the showerkt value
2909
2996
        if args[0].lower() == 'showerkt':
2910
 
            pythia_path = pjoin(self.me_dir, 'Cards','pythia_card.dat')
 
2997
            pythia_path = self.paths['pythia']
2911
2998
            if os.path.exists(pythia_path):
2912
2999
                logger.info('add line SHOWERKT = %s in pythia_card.dat' % args[1].upper())
2913
3000
                p_card = open(pythia_path,'r').read()
2943
3030
        if args[0] in ['run_card', 'param_card', 'MadWeight_card', 'shower_card']:
2944
3031
            if args[1] == 'default':
2945
3032
                logging.info('replace %s by the default card' % args[0])
2946
 
                files.cp(pjoin(self.me_dir,'Cards','%s_default.dat' % args[0]),
2947
 
                        pjoin(self.me_dir,'Cards','%s.dat'% args[0]))
 
3033
                files.cp(self.paths['%s_default' %args[0][:-5]], self.paths[args[0][:-5]])
2948
3034
                if args[0] == 'param_card':
2949
 
                    self.param_card = check_param_card.ParamCard(pjoin(self.me_dir,'Cards','param_card.dat'))
 
3035
                    self.param_card = check_param_card.ParamCard(self.paths['param'])
2950
3036
                elif args[0] == 'run_card':
2951
 
                    self.run_card = banner_mod.RunCard(pjoin(self.me_dir,'Cards','run_card.dat'))
 
3037
                    self.run_card = banner_mod.RunCard(self.paths['run'])
2952
3038
                elif args[0] == 'shower_card':
2953
 
                    self.shower_card = shower_card_mod.ShowerCard(pjoin(self.me_dir,'Cards','shower_card.dat'))
 
3039
                    self.shower_card = shower_card_mod.ShowerCard(self.paths['shower'])
2954
3040
                return
2955
3041
            else:
2956
3042
                card = args[0]
2963
3049
            if args[1] == 'default':
2964
3050
                logging.info('replace MadLoopParams.dat by the default card')
2965
3051
                self.MLcard = banner_mod.MadLoopParam(self.MLcardDefault)
2966
 
                self.MLcard.write(pjoin(self.me_dir,'Cards','MadLoopParams.dat'),
 
3052
                self.MLcard.write(self.paths['ML'],
2967
3053
                                  commentdefault=True)
2968
3054
                return
2969
3055
            else:
2975
3061
        elif args[0] in ['madspin_card']:
2976
3062
            if args[1] == 'default':
2977
3063
                logging.info('replace madspin_card.dat by the default card')
2978
 
                files.cp(pjoin(self.me_dir,'Cards/madspin_card_default.dat'),
2979
 
                         pjoin(self.me_dir,'Cards/madspin_card.dat'))
 
3064
                files.cp(self.paths['MS_default'], self.paths['madspin'])
2980
3065
                return
2981
3066
            else:
2982
3067
                logger.warning("""Command set not allowed for modifying the madspin_card. 
2995
3080
                logger.warning(text)
2996
3081
 
2997
3082
            if args[start+1] == 'default':
2998
 
                default = banner_mod.RunCard(pjoin(self.me_dir,'Cards','run_card_default.dat'))
 
3083
                default = banner_mod.RunCard(self.paths['run_default'])
2999
3084
                if args[start] in default.keys():
3000
3085
                    self.setR(args[start],default[args[start]])
3001
3086
                else:
3011
3096
                    except NameError:
3012
3097
                        val = args[start+1]
3013
3098
                self.setR(args[start], val)
3014
 
            self.run_card.write(pjoin(self.me_dir,'Cards','run_card.dat'),
3015
 
                                pjoin(self.me_dir,'Cards','run_card_default.dat'))
 
3099
            self.run_card.write(self.paths['run'], self.paths['run_default'])
3016
3100
            
3017
3101
        ### PARAM_CARD WITH BLOCK NAME -----------------------------------------
3018
3102
        elif (args[start] in self.param_card or args[start] == 'width') \
3052
3136
                                continue
3053
3137
                            else:
3054
3138
                                self.setP(args[start], key, args[-1])
3055
 
                        self.param_card.write(pjoin(self.me_dir,'Cards','param_card.dat'))
 
3139
                        self.param_card.write(self.paths['param'])
3056
3140
                        return
3057
3141
                    logger.warning('invalid set command %s (failed to identify LHA information)' % line)
3058
3142
                    return
3078
3162
            else:
3079
3163
                logger.warning('invalid set command %s' % line)
3080
3164
                return
3081
 
            self.param_card.write(pjoin(self.me_dir,'Cards','param_card.dat'))
 
3165
            self.param_card.write(self.paths['param'])
3082
3166
        
3083
3167
        # PARAM_CARD NO BLOCK NAME ---------------------------------------------
3084
3168
        elif args[start] in self.pname2block and card != 'run_card':
3113
3197
            name = args[start+1]
3114
3198
            value = args[start+2:]
3115
3199
            self.setM(block, name, value)
3116
 
            self.mw_card.write(pjoin(self.me_dir,'Cards','MadWeight_card.dat'))        
 
3200
            self.mw_card.write(self.paths['MadWeight'])        
3117
3201
        
3118
3202
        # MadWeight_card NO Block name -----------------------------------------
3119
3203
        elif self.has_mw and args[start] in self.mw_vars \
3135
3219
            name = args[start]
3136
3220
            value = args[start+1:]
3137
3221
            self.setM(block, name, value)
3138
 
            self.mw_card.write(pjoin(self.me_dir,'Cards','MadWeight_card.dat'))
 
3222
            self.mw_card.write(self.paths['MadWeight'])
3139
3223
             
3140
3224
        # MadWeight_card New Block ---------------------------------------------
3141
3225
        elif self.has_mw and args[start].startswith('mw_') and len(args[start:]) == 3\
3144
3228
            name = args[start+1]
3145
3229
            value = args[start+2]
3146
3230
            self.setM(block, name, value)
3147
 
            self.mw_card.write(pjoin(self.me_dir,'Cards','MadWeight_card.dat'))    
 
3231
            self.mw_card.write(self.paths['MadWeight'])    
3148
3232
 
3149
3233
        #### SHOWER CARD
3150
3234
        elif self.has_shower and args[start].lower() in [l.lower() for l in \
3159
3243
                return
3160
3244
 
3161
3245
            if args[start+1].lower() == 'default':
3162
 
                default = shower_card_mod.ShowerCard(pjoin(self.me_dir,'Cards','shower_card_default.dat'))
 
3246
                default = shower_card_mod.ShowerCard(self.paths['shower_default'])
3163
3247
                if args[start] in default.keys():
3164
 
                    self.shower_card.set_param(args[start],default[args[start]],pjoin(self.me_dir,'Cards','shower_card.dat'))
 
3248
                    self.shower_card.set_param(args[start],default[args[start]], self.paths['shower'])
3165
3249
                else:
3166
3250
                    logger.info('remove information %s from the shower_card' % args[start])
3167
3251
                    del self.shower_card[args[start]]
3168
3252
            elif args[start+1].lower() in ['t','.true.','true']:
3169
 
                self.shower_card.set_param(args[start],'.true.',pjoin(self.me_dir,'Cards','shower_card.dat'))
 
3253
                self.shower_card.set_param(args[start],'.true.',self.paths['shower'])
3170
3254
            elif args[start+1].lower() in ['f','.false.','false']:
3171
 
                self.shower_card.set_param(args[start],'.false.',pjoin(self.me_dir,'Cards','shower_card.dat'))
 
3255
                self.shower_card.set_param(args[start],'.false.',self.paths['shower'])
3172
3256
            else:
3173
3257
                args_str = ' '.join(str(a) for a in args[start+1:len(args)])
3174
 
                self.shower_card.set_param(args[start],args_str,pjoin(self.me_dir,'Cards','shower_card.dat'))
 
3258
                self.shower_card.set_param(args[start],args_str,self.paths['shower'])
3175
3259
     
3176
3260
        # MadLoop Parameter  ---------------------------------------------------
3177
3261
        elif self.has_ml and args[start] in self.ml_vars \
3189
3273
                value = args[start+1]
3190
3274
                default = False
3191
3275
            self.setML(args[start], value, default=default)
3192
 
            self.MLcard.write(pjoin(self.me_dir,'Cards','MadLoopParams.dat'),
 
3276
            self.MLcard.write(self.paths['ML'],
3193
3277
                              commentdefault=True)
3194
3278
                
3195
3279
        #INVALID --------------------------------------------------------------
3209
3293
            logger.info('name %s was not present in the block %s for the current MadWeight card. We are adding it' % (name,block),'$MG:color:BLACK')
3210
3294
        if value == 'default':
3211
3295
            import madgraph.madweight.Cards as mwcards
3212
 
            mw_default = mwcards.Card(pjoin(self.me_dir,'Cards','MadWeight_card_default.dat'))
 
3296
            mw_default = mwcards.Card(self.paths['MadWeight_default'])
3213
3297
            try:
3214
3298
                value = mw_default[block][name]
3215
3299
            except KeyError:
3227
3311
        self.mw_card[block][name] = value
3228
3312
    
3229
3313
    def setR(self, name, value):
3230
 
        logger.info('modify parameter %s of the run_card.dat to %s' % (name, value))
 
3314
        logger.info('modify parameter %s of the run_card.dat to %s' % (name, value),'$MG:color:BLACK')
3231
3315
        self.run_card.set(name, value, user=True)
3232
3316
 
3233
3317
    def setML(self, name, value, default=False):
3237
3321
        except Exception, error:
3238
3322
            logger.warning("Fail to change parameter. Please Retry. Reason: %s." % error)
3239
3323
            return
3240
 
        logger.info('modify parameter %s of the MadLoopParam.dat to %s' % (name, value))
 
3324
        logger.info('modify parameter %s of the MadLoopParam.dat to %s' % (name, value),'$MG:color:BLACK')
3241
3325
        if default and name.lower() in self.MLcard.user_set:
3242
3326
            self.MLcard.user_set.remove(name.lower())
3243
3327
 
3245
3329
        if isinstance(value, str):
3246
3330
            value = value.lower()
3247
3331
            if value == 'default':
3248
 
                default = check_param_card.ParamCard(pjoin(self.me_dir,'Cards','param_card_default.dat'))
 
3332
                default = check_param_card.ParamCard(self.paths['param_default'])
3249
3333
                value = default[block].param_dict[lhaid].value
3250
3334
 
3251
3335
            elif value in ['auto', 'auto@nlo']:
3288
3372
            not self.run_card['store_rwgt_info']:
3289
3373
            #check if a NLO reweighting is required
3290
3374
                re_pattern = re.compile(r'''^\s*change\s*mode\s* (LO\+NLO|LO|NLO)\s*(?:#|$)''', re.M+re.I)
3291
 
                text = open(pjoin(self.me_dir,'Cards','reweight_card.dat')).read()
 
3375
                text = open(self.paths['reweight']).read()
3292
3376
                options = re_pattern.findall(text)
3293
3377
                if any(o in ['NLO', 'LO+NLO'] for o in options):
3294
3378
                    logger.info('NLO reweighting is on ON. Automatically set store_rwgt_info to True', '$MG:color:BLACK' )
3302
3386
            logger.warning('No transfer function currently define. Please use the change_tf command to define one.')
3303
3387
    
3304
3388
    def postcmd(self, stop, line):
3305
 
        
3306
3389
        ending_question = cmd.OneLinePathCompletion.postcmd(self,stop,line)
 
3390
 
3307
3391
        if ending_question:
3308
3392
            self.check_card_consistency()
 
3393
            self.do_update_dependent('', timer=20)
3309
3394
            return ending_question
3310
3395
    
 
3396
    def do_update_dependent(self, line, timer=0):
 
3397
        """Change the mass/width of particles which are not free parameter for the 
 
3398
        model."""
 
3399
        if not self.mother_interface:
 
3400
            logger.warning('Failed to update dependent parameter. This might create trouble for external program (like MadSpin/shower/...)')
 
3401
        
 
3402
        pattern_width = re.compile(r'''decay\s+(\+?\-?\d+)\s+auto(@NLO|)''',re.I)
 
3403
        pattern_scan = re.compile(r'''^(decay)?[\s\d]*scan''', re.I+re.M)
 
3404
        param_text= open(self.paths['param']).read()
 
3405
        
 
3406
        if pattern_scan.search(param_text):
 
3407
            #for block, key in self.restricted_value:
 
3408
            #    self.param_card[block].get(key).value = -9.999e-99
 
3409
            #    self.param_card.write(self.paths['param'])
 
3410
            return
 
3411
        elif pattern_width.search(param_text):
 
3412
            self.do_compute_widths('')
 
3413
            self.param_card = check_param_card.ParamCard(self.paths['param'])
 
3414
    
 
3415
        # calling the routine doing the work    
 
3416
        self.update_dependent(self.mother_interface, self.me_dir, self.param_card,
 
3417
                               self.paths['param'], timer)
 
3418
    
 
3419
    @staticmethod
 
3420
    def update_dependent(mecmd, me_dir, param_card, path ,timer=0):
 
3421
        """static method which can also be called from outside the class
 
3422
           usefull in presence of scan.
 
3423
           return if the param_card was updated or not
 
3424
        """
 
3425
        modify = True
 
3426
        class TimeOutError(Exception): 
 
3427
            pass
 
3428
        def handle_alarm(signum, frame): 
 
3429
            raise TimeOutError
 
3430
        signal.signal(signal.SIGALRM, handle_alarm)
 
3431
        if timer:
 
3432
            signal.alarm(timer)
 
3433
            log_level=30
 
3434
        else:
 
3435
            log_level=20
 
3436
        # Try to load the model in the limited amount of time allowed
 
3437
        try:
 
3438
            model = mecmd.get_model()
 
3439
            signal.alarm(0)
 
3440
        except TimeOutError:
 
3441
            logger.warning('The model takes too long to load so we bypass the updating of dependent parameter.\n'+\
 
3442
                           'This might create trouble for external program (like MadSpin/shower/...)\n'+\
 
3443
                           'The update can be forced without timer by typing \'update_dependent\' at the time of the card edition')
 
3444
            modify =False
 
3445
        except Exception:
 
3446
            logger.warning('Failed to update dependent parameter. This might create trouble for external program (like MadSpin/shower/...)')
 
3447
            signal.alarm(0)
 
3448
        else:
 
3449
            restrict_card = pjoin(me_dir,'Source','MODEL','param_card_rule.dat')
 
3450
            if not os.path.exists(restrict_card):
 
3451
                restrict_card = None
 
3452
            #restrict_card = None
 
3453
            if model:
 
3454
                modify = param_card.update_dependent(model, restrict_card, log_level)
 
3455
                if modify and path:
 
3456
                    param_card.write(path)
 
3457
            else:
 
3458
                logger.warning('missing MG5aMC code. Fail to update dependent parameter. This might create trouble for program like MadSpin/shower/...')
 
3459
            
 
3460
        if log_level==20:
 
3461
            logger.info('param_card up to date.')
 
3462
            
 
3463
        return modify
 
3464
    
 
3465
    
 
3466
    
 
3467
    
3311
3468
    def check_answer_consistency(self):
3312
3469
        """function called if the code reads a file"""
3313
 
        self.check_card_consistency() 
 
3470
        self.check_card_consistency()
 
3471
        self.do_update_dependent('', timer=20) 
3314
3472
      
3315
3473
    def help_set(self):
3316
3474
        '''help message for set'''
3354
3512
        elif os.path.isfile(line):
3355
3513
            self.copy_file(line)
3356
3514
            self.value = 'repeat'
3357
 
        elif os.path.exists(pjoin(self.me_dir, line)):
 
3515
        elif self.me_dir and os.path.exists(pjoin(self.me_dir, line)):
3358
3516
            self.copy_file(pjoin(self.me_dir,line))
3359
3517
            self.value = 'repeat'            
3360
3518
        elif line.strip() != '0' and line.strip() != 'done' and \
3361
 
            str(line) != 'EOF' and line.strip() in self.allow_arg:
 
3519
            str(line) != 'EOF' and line.strip() in self.allow_arg:            
3362
3520
            self.open_file(line)
3363
3521
            self.value = 'repeat'
3364
3522
        else:
3369
3527
    def do_decay(self, line):
3370
3528
        """edit the madspin_card to define the decay of the associate particle"""
3371
3529
        signal.alarm(0) # avoid timer if any
3372
 
        path = pjoin(self.me_dir,'Cards','madspin_card.dat')
 
3530
        path = self.paths['madspin']
3373
3531
        
3374
3532
        if 'madspin_card.dat' not in self.cards or not os.path.exists(path):
3375
3533
            logger.warning("Command decay not valid. Since MadSpin is not available.")
3405
3563
 
3406
3564
    def do_compute_widths(self, line):
3407
3565
        signal.alarm(0) # avoid timer if any
3408
 
        path = pjoin(self.me_dir,'Cards','param_card.dat')
 
3566
        path = self.paths['param']
3409
3567
        pattern = re.compile(r'''decay\s+(\+?\-?\d+)\s+auto(@NLO|)''',re.I)
3410
3568
        text = open(path).read()
3411
3569
        pdg_info = pattern.findall(text)
3454
3612
        print '   If you specify some names after the command (i.e. asperge m1 m2) then ASperGe will only'
3455
3613
        print '   diagonalize the associate mass matrices (here m1 and m2).'
3456
3614
 
3457
 
    def complete_asperge(self, text, line, begidx, endidx):
 
3615
    def complete_asperge(self, text, line, begidx, endidx, formatting=True):
3458
3616
        signal.alarm(0) # avoid timer if any
3459
3617
 
3460
3618
        blockname = self.pname2block.keys()
3465
3623
        output = {'Mixing matrices': self.list_completion(text, valid, line),
3466
3624
                  'Other potential valid input': self.list_completion(text, potential, line)}
3467
3625
 
3468
 
        return self.deal_multiple_categories(output)
 
3626
        return self.deal_multiple_categories(output, formatting)
3469
3627
 
3470
3628
 
3471
3629
    def do_asperge(self, line):
3489
3647
                return
3490
3648
 
3491
3649
        opts = line.split()
3492
 
        card = pjoin(self.me_dir,'Cards', 'param_card.dat')
 
3650
        card = self.paths['param']
3493
3651
        logger.info('running ASperGE')
3494
3652
        returncode = misc.call([pjoin(path,'ASperGe'), card, '%s.new' % card] + opts)
3495
3653
        if returncode:
3521
3679
            logger.warning('Fail to determine the type of the file. Not copied')
3522
3680
        if card_name != 'banner':
3523
3681
            logger.info('copy %s as %s' % (path, card_name))
3524
 
            files.cp(path, pjoin(self.me_dir, 'Cards', card_name))
 
3682
            files.cp(path, self.paths[card_name.split('_',1)[0]])
3525
3683
        elif card_name == 'banner':
3526
3684
            banner_mod.split_banner(path, self.mother_interface.me_dir, proc_card=False)
3527
3685
            logger.info('Splitting the banner in it\'s component')
3530
3688
 
3531
3689
    def open_file(self, answer):
3532
3690
        """open the file"""
3533
 
        me_dir = self.mother_interface.me_dir
 
3691
        try:
 
3692
            me_dir = self.mother_interface.me_dir
 
3693
        except:
 
3694
            me_dir = None
 
3695
            
3534
3696
        if answer.isdigit():
3535
3697
            if answer == '9':
3536
3698
                answer = 'plot'
3540
3702
            answer = answer.replace('madweight', 'MadWeight')
3541
3703
        
3542
3704
        if 'MadLoopParams' in answer:
3543
 
            answer = pjoin(me_dir,'Cards','MadLoopParams.dat')
 
3705
            answer = self.paths['ML']
3544
3706
        if not '.dat' in answer and not '.lhco' in answer:
3545
3707
            if answer != 'trigger':
3546
 
                path = pjoin(me_dir,'Cards','%s_card.dat' % answer)
 
3708
                path = self.paths[answer]
3547
3709
            else:
3548
 
                path = pjoin(me_dir,'Cards','delphes_trigger.dat')
 
3710
                path = self.paths['delphes']
3549
3711
        elif not '.lhco' in answer:
3550
 
            path = pjoin(me_dir, 'Cards', answer)
 
3712
            if '_' in answer:
 
3713
                path = self.paths[answer.split('_')[0]]
 
3714
            else:
 
3715
                path = pjoin(me_dir, 'Cards', answer)
3551
3716
        else:
3552
3717
            path = pjoin(me_dir, self.mw_card['mw_run']['inputfile'])
3553
3718
            if not os.path.exists(path):
3574
3739
                raise
3575
3740
            
3576
3741
        # reload object to have it in sync
3577
 
        if path == pjoin(self.me_dir,'Cards','param_card.dat'):
 
3742
        if path == self.paths['param']:
3578
3743
            try:
3579
3744
                self.param_card = check_param_card.ParamCard(path) 
3580
3745
            except (check_param_card.InvalidParamCard, ValueError) as e:
3582
3747
                logger.error('problem detected: %s' % e)
3583
3748
                logger.error('Please re-open the file and fix the problem.')
3584
3749
                logger.warning('using the \'set\' command without opening the file will discard all your manual change')
3585
 
        elif path == pjoin(self.me_dir,'Cards','run_card.dat'):
3586
 
            self.run_card = banner_mod.RunCard(pjoin(self.me_dir,'Cards','run_card.dat'))
3587
 
        elif path == pjoin(self.me_dir,'Cards','MadLoopParams.dat'):
3588
 
            self.MLcard = banner_mod.MadLoopParam(pjoin(self.me_dir,'Cards','MadLoopParams.dat'))
3589
 
        elif path == pjoin(self.me_dir,'Cards','MadWeight_card.dat'):
 
3750
        elif path == self.paths['run']:
 
3751
            self.run_card = banner_mod.RunCard(path)
 
3752
        elif path == self.paths['ML']:
 
3753
            self.MLcard = banner_mod.MadLoopParam(path)
 
3754
        elif path == self.paths['MadWeight']:
3590
3755
            try:
3591
3756
                import madgraph.madweight.Cards as mwcards
3592
3757
            except:
3593
3758
                import internal.madweight.Cards as mwcards
3594
 
            self.mw_card = mwcards.Card(pjoin(self.me_dir,'Cards','MadWeight_card.dat'))
3595
 
 
 
3759
            self.mw_card = mwcards.Card(path)
 
3760
        return path
 
3761
 
 
3762
class EditParamCard(AskforEditCard):
 
3763
    """a dedicated module for the param"""
 
3764
    
 
3765
    special_shortcut ={}
 
3766
    
 
3767
    def __init__(self, question, card=[], mode='auto', *args, **opt):
 
3768
                 
 
3769
        self.load_default()
 
3770
        cmd.OneLinePathCompletion.__init__(self, question, *args, **opt)
 
3771
        if os.path.isfile(card[0]):
 
3772
            self.param_card = check_param_card.ParamCard(card[0])
 
3773
            self.paths['param'] = card[0]
 
3774
            if os.path.isfile(card[0].replace('.dat', '_default.dat')):
 
3775
                self.paths['param_default'] = card[0].replace('.dat', '_default.dat')
 
3776
            else:
 
3777
                self.paths['param_default'] = card[0]
 
3778
        else:
 
3779
            raise Exception, 'path %s do not exists' % card[0]
 
3780
        
 
3781
        self.pname2block, self.restricted_value = self.param_card.analyze_param_card()
 
3782
        self.cards=['param']
 
3783
        
 
3784
    def do_asperge(self, *args, **opts):
 
3785
        "Not available"
 
3786
        logger.warning("asperge not available in this mode")
 
3787