~maddevelopers/mg5amcnlo/2.7.1.3

« back to all changes in this revision

Viewing changes to models/import_ufo.py

  • Committer: olivier Mattelaer
  • Date: 2017-12-12 21:11:08 UTC
  • mfrom: (274.1.52 2.6.1)
  • Revision ID: olivier.mattelaer@uclouvain.be-20171212211108-xfh9rt0j9c9m6nxp
pass to 2.6.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
60
60
    """ a class for invalid Model """
61
61
 
62
62
last_model_path =''
63
 
def find_ufo_path(model_name):
 
63
def find_ufo_path(model_name, web_search=True):
64
64
    """ find the path to a model """
65
65
 
66
66
    global last_model_path
67
67
 
68
68
    # Check for a valid directory
69
 
    if model_name.startswith('./') and os.path.isdir(model_name):
 
69
    if model_name.startswith(('./','../')) and os.path.isdir(model_name):
70
70
        return model_name
71
71
    elif os.path.isdir(os.path.join(MG5DIR, 'models', model_name)):
72
72
        return os.path.join(MG5DIR, 'models', model_name)
80
80
    if os.path.isdir(model_name):
81
81
        logger.warning('No model %s found in default path. Did you mean \'import model ./%s\'',
82
82
                       model_name, model_name)
83
 
        raise UFOImportError("Path %s is not a valid pathname" % model_name)    
 
83
        if os.path.sep in model_name:
 
84
            raise UFOImportError("Path %s is not a valid pathname" % model_name)    
 
85
    elif web_search and '-' not in model_name:
 
86
        found = import_model_from_db(model_name)
 
87
        if found:
 
88
            return find_ufo_path(model_name, web_search=False)
 
89
        else:
 
90
            raise UFOImportError("Path %s is not a valid pathname" % model_name)    
84
91
    else:
85
92
        raise UFOImportError("Path %s is not a valid pathname" % model_name)    
86
93
    
87
 
 
 
94
    raise UFOImportError("Path %s is not a valid pathname" % model_name)
88
95
    return
89
96
 
 
97
 
 
98
def get_model_db():
 
99
    """return the file with the online model database"""
 
100
 
 
101
    data_path = ['http://madgraph.phys.ucl.ac.be/models_db.dat',
 
102
                     'http://madgraph.physics.illinois.edu/models_db.dat']
 
103
    import random
 
104
    import urllib
 
105
    r = random.randint(0,1)
 
106
    r = [r, (1-r)]
 
107
 
 
108
    for index in r:
 
109
        cluster_path = data_path[index]
 
110
        try:
 
111
            data = urllib.urlopen(cluster_path)
 
112
        except Exception:
 
113
            continue
 
114
        break
 
115
    else:
 
116
        raise MadGraph5Error, '''Model not found locally and Impossible to connect any of us servers.
 
117
        Please check your internet connection or retry later'''
 
118
    return data
 
119
 
 
120
def import_model_from_db(model_name):
 
121
    """ import the model with a given name """
 
122
 
 
123
    data =get_model_db()
 
124
    link = None
 
125
    for line in data:
 
126
        split = line.split()
 
127
        if model_name == split[0]:
 
128
            link = split[1]
 
129
            break
 
130
    else:
 
131
        logger.debug('no model with that name found online')
 
132
        return False
 
133
    
 
134
    #get target directory
 
135
    # 1. PYTHONPATH containing UFO
 
136
    # 2. models directory
 
137
    target = None 
 
138
    if 'PYTHONPATH' in os.environ:
 
139
        for directory in os.environ['PYTHONPATH'].split(':'):
 
140
            if 'UFO' in os.path.basename(directory) and os.path.exists(directory):
 
141
                target= directory 
 
142
    if target is None:
 
143
        target = pjoin(MG5DIR, 'models')    
 
144
    try:
 
145
        os.remove(pjoin(target, 'tmp.tgz'))
 
146
    except Exception:
 
147
        pass
 
148
    logger.info("download model from %s to the following directory: %s", link, target, '$MG:color:BLACK')
 
149
    if sys.platform == "darwin":
 
150
        misc.call(['curl', link, '-otmp.tgz'], cwd=target)
 
151
    else:
 
152
        misc.call(['wget', link, '--output-document=tmp.tgz'], cwd=target)
 
153
 
 
154
    #untar the file.
 
155
    # .tgz
 
156
    if link.endswith(('.tgz','.tar.gz')):
 
157
        try:
 
158
            proc = misc.call('tar -xzpvf tmp.tgz', shell=True, cwd=target)#, stdout=devnull, stderr=devnull)
 
159
            if proc: raise Exception
 
160
        except:
 
161
            proc = misc.call('tar -xpvf tmp.tgz', shell=True, cwd=target)#, stdout=devnull, stderr=devnull)
 
162
    # .zip
 
163
    if link.endswith(('.zip')):
 
164
        try:
 
165
            proc = misc.call('unzip tmp.tgz', shell=True, cwd=target)#, stdout=devnull, stderr=devnull)
 
166
            if proc: raise Exception
 
167
        except:
 
168
            proc = misc.call('tar -xzpvf tmp.tgz', shell=True, cwd=target)#, stdout=devnull, stderr=devnull)
 
169
    if proc:
 
170
        raise Exception, "Impossible to unpack the model. Please install it manually"
 
171
    return True
 
172
 
90
173
def import_model(model_name, decay=False, restrict=True, prefix='mdl_',
91
174
                                                    complex_mass_scheme = None):
92
175
    """ a practical and efficient way to import a model"""
96
179
        model_path = find_ufo_path(model_name)
97
180
    except UFOImportError:
98
181
        if '-' not in model_name:
 
182
            if model_name == "mssm":
 
183
                logger.error("mssm model has been replaced by MSSM_SLHA2 model.\n The new model require SLHA2 format. You can use the \"update to_slha2\" command to convert your slha1 param_card.\n That option is available at the time of the edition of the cards.")
99
184
            raise
100
185
        split = model_name.split('-')
101
186
        model_name = '-'.join([text for text in split[:-1]])
102
 
        model_path = find_ufo_path(model_name)
 
187
        try:
 
188
            model_path = find_ufo_path(model_name)
 
189
        except UFOImportError:
 
190
            if model_name == "mssm":
 
191
                logger.error("mssm model has been replaced by MSSM_SLHA2 model.\n The new model require SLHA2 format. You can use the \"update to_slha2\" command to convert your slha1 param_card.\n That option is available at the time of the edition of the cards.")
 
192
            raise
103
193
        restrict_name = split[-1]
104
194
         
105
195
        restrict_file = os.path.join(model_path, 'restrict_%s.dat'% restrict_name)
327
417
    def __init__(self, model, auto=False):
328
418
        """ initialize empty list for particles/interactions """
329
419
       
 
420
        if hasattr(model, '__arxiv__'):
 
421
            logger.info('Please cite %s when using this model', model.__arxiv__, '$MG:color:BLACK')
 
422
       
330
423
        self.particles = base_objects.ParticleList()
331
424
        self.interactions = base_objects.InteractionList()
332
425
        self.wavefunction_CT_couplings = []
1646
1739
        self.coupling_pos = {}
1647
1740
        for vertex in self['interactions']:
1648
1741
            for key, coupling in vertex['couplings'].items():
 
1742
                if coupling.startswith('-'):
 
1743
                    coupling = coupling[1:]
1649
1744
                if coupling in self.coupling_pos:
1650
1745
                    if vertex not in self.coupling_pos[coupling]:
1651
1746
                        self.coupling_pos[coupling].append(vertex)
1819
1914
        
1820
1915
        main = couplings[0]
1821
1916
        self.del_coup += couplings[1:] # add the other coupl to the suppress list
1822
 
        
1823
1917
        for coupling in couplings[1:]:
1824
1918
            # check if param is linked to an interaction
1825
1919
            if coupling not in self.coupling_pos:
1831
1925
                for key, value in vertex['couplings'].items():
1832
1926
                    if value == coupling:
1833
1927
                        vertex['couplings'][key] = main
1834
 
 
 
1928
                    elif value == '-%s' % coupling:
 
1929
                        if main.startswith('-'):
 
1930
                            vertex['couplings'][key] = main[1:]
 
1931
                        else:
 
1932
                            vertex['couplings'][key] = '-%s' % main
 
1933
                        
1835
1934
            # replace the coupling appearing in the particle counterterm
1836
1935
            particles_ct = [ pct for pct in self.coupling_pos[coupling] if 
1837
1936
                         isinstance(pct, tuple)]