~chirality-flow/chiralityflow/ChiralityFlowMG

« back to all changes in this revision

Viewing changes to madgraph/madweight/MW_info.py

  • Committer: andrew.lifson at lu
  • Date: 2021-09-02 13:57:34 UTC
  • Revision ID: andrew.lifson@thep.lu.se-20210902135734-4eybgli0iljkax9b
added fresh copy of MG5_aMC_v3.2.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
##########################################################################
 
3
##                                                                      ##
 
4
##                               MadWeight                              ##
 
5
##                               ---------                              ##
 
6
##########################################################################
 
7
##                                                                      ##
 
8
##   author: Mattelaer Olivier (CP3)                                    ##
 
9
##       email:  olivier.mattelaer@uclouvain.be                         ##
 
10
##   author: Artoisenet Pierre (CP3)                                    ##
 
11
##       email:  pierre.artoisenet@uclouvain.be                         ##
 
12
##                                                                      ##
 
13
##########################################################################
 
14
##                                                                      ##
 
15
##   license: GNU                                                       ##
 
16
##   last-modif:10/06/08                                                ##
 
17
##                                                                      ##
 
18
##########################################################################
 
19
##                                                                      ##
 
20
##   Content                                                            ##
 
21
##   -------                                                            ##
 
22
##      +go_to_main_dir                                                 ##
 
23
##      +read_card                                                      ##
 
24
##      +check_for_help                                                 ##
 
25
##########################################################################
 
26
##      +Class P_info                                                   ##
 
27
##      |     +  P_listdir                                              ##
 
28
##      |     +  detectSubProcesses                                     ##
 
29
##########################################################################
 
30
##      +Class MW_info (dict,P_info)                                    ##
 
31
##      |     +  init                                                   ##
 
32
##      |     |    + init_run_opt                                       ##
 
33
##      |     +  check_info                                             ##
 
34
##      |     +  take_un_name                                           ##
 
35
##      |     +  update_nb_card                                         ##
 
36
##      |     +  number_of_P_run                                        ##
 
37
##      |     +  load_events                                            ##
 
38
##      |     +  give_block_param_info                                  ##
 
39
##      |     |    +  CardNB_to_ParameterTag                            ##
 
40
##      |     +  set_run_opt                                            ##
 
41
##      |     |    + control_opt                                        ##
 
42
##      |     +  def_actif_param                                        ##
 
43
##      |     +  find_existing_events                                   ##
 
44
##########################################################################
 
45
##      +Class move                                                     ##
 
46
##      |     +  init                                                   ##
 
47
##      |     +  to_SubProcesses                                        ##
 
48
##      |     +  to_init                                                ##
 
49
##      |     +  store                                                  ##
 
50
##      |     +  to_store                                               ##
 
51
##      |     +  to_last_pos                                            ##
 
52
##      |     +  to_main                                                ##
 
53
##                                                                      ##
 
54
##########################################################################
 
55
##
 
56
## BEGIN INCLUDE
 
57
##
 
58
from __future__ import absolute_import
 
59
from __future__ import print_function
 
60
import sys
 
61
import os
 
62
import re
 
63
import stat
 
64
from six.moves import range
 
65
try: 
 
66
    import madgraph.madweight.Cards as Cards
 
67
except ImportError as error:
 
68
    print(error)
 
69
    import internal.madweight.Cards as Cards
 
70
 
 
71
##
 
72
## END INCLUDE
 
73
## GLOBAL DEFINITION
 
74
 
 
75
num_to_tag={1:'param',2:'analyzer',3:'compilation',4:'event',5:'dir',6:'launch',7:'control',8:'collect',9:'plot',\
 
76
            -1:'relaunch',-2:'clean',-3:'refine',-4:'status'}
 
77
tag_to_num={'param':1,'analyzer':2,'compilation':3,'event':4,'dir':5,'launch':6,'control':7,'collect':8,'plot':9,\
 
78
            'relaunch':-1,'clean':-2,'refine':-3,'status':-4}
 
79
last_step=9
 
80
#1#########################################################################
 
81
##                    START CODE
 
82
#1#########################################################################
 
83
def go_to_main_dir():
 
84
    """ move to main position """
 
85
    pos=os.getcwd()
 
86
    last=pos.split(os.sep)[-1]
 
87
    if last=='bin':
 
88
        os.chdir(os.pardir)
 
89
        return
 
90
    if last=='Python':
 
91
        os.chdir(os.pardir+os.sep+os.pardir+os.sep+os.pardir)
 
92
        return
 
93
    
 
94
    list_dir=os.listdir('./')
 
95
    if 'bin' in list_dir:
 
96
        return
 
97
    else:
 
98
        sys.exit('Error: script must be executed from the main, bin or Python directory')
 
99
 
 
100
#1#########################################################################
 
101
def read_card(name_card):
 
102
    """put all card information in a dictionary"""
 
103
 
 
104
    card=Cards.Card(name_card)
 
105
    return card.info
 
106
 
 
107
#1#########################################################################
 
108
def check_for_help(opt):
 
109
    """ check if the user use the -h or -help option or simply invalid option """
 
110
 
 
111
    opt_pat=re.compile(r'''-?(?P<opt>\w*)[+-]?''',re.I)
 
112
    help=0
 
113
    authorized_opt=list(tag_to_num.keys())+['version']
 
114
    for i in range(0,len(num_to_tag)):
 
115
        authorized_opt+=[str(i)]
 
116
    for i in range(1,len(opt)):
 
117
        if opt_pat.search(opt[i]):
 
118
            if opt_pat.search(opt[i]).group('opt').lower() not in authorized_opt:
 
119
                try:
 
120
                    int(opt_pat.search(opt[i]).group('opt').lower())
 
121
                except:
 
122
                    os.system('cat ./Source/MadWeight/Readme.txt')
 
123
                    sys.exit()
 
124
            if opt_pat.search(opt[i]).group('opt').lower()=='version':
 
125
                print('MadWeight Version')
 
126
                os.system('cat ./Source/MadWeight/MW_TemplateVersion.txt')
 
127
                sys.exit()
 
128
 
 
129
#1#########################################################################
 
130
class P_info:
 
131
    """ class containing option/routine for standard MG/ME run """
 
132
    
 
133
    #2#########################################################################
 
134
    def P_lisdir(self):
 
135
        try:
 
136
            return self.Plistdir
 
137
        except:
 
138
            self.Plistdir,nothing=self.detect_SubProcess()
 
139
            return self.Plistdir
 
140
 
 
141
    #2#########################################################################
 
142
    def detect_SubProcess(self,P_mode=0):
 
143
        
 
144
            
 
145
        P_SubProcess_list,MW_SubProcess_list=detect_SubProcess(P_mode)
 
146
        return P_SubProcess_list,MW_SubProcess_list 
 
147
 
 
148
 
 
149
 
 
150
#1#########################################################################
 
151
class MW_info(dict,P_info):
 
152
    """ class containing all the option/information from the run """
 
153
 
 
154
    #2#########################################################################
 
155
    def __init__(self,card_name):
 
156
        """ init all the param for the run """
 
157
 
 
158
        self.mw_card=Cards.Card(card_name)
 
159
        self.info=self.mw_card.info
 
160
        for key,value in self.info.items():
 
161
            self[key]=value
 
162
 
 
163
        dict.__init__(self.info)
 
164
        self.check_info()
 
165
        #assign special value
 
166
        self.nb_event= self.info['mw_run']['nb_exp_events']
 
167
        self.nb_card=self.number_of_P_run()
 
168
        try:
 
169
            self.name = self.info['mw_run']['name']
 
170
        except:
 
171
            self.name = self.take_run_name()
 
172
        self.P_listdir,self.MW_listdir=self.detect_SubProcess()
 
173
        self.nb_event_MW = {}
 
174
        for MW in self.MW_listdir:
 
175
            self.nb_event_MW[MW] = self.nb_event 
 
176
        self.init_run_opt()
 
177
        self.def_actif_param()
 
178
        self.Pinupdate=[]
 
179
        self.Minpudate=[]
 
180
        self.startevent=0
 
181
 
 
182
 
 
183
    #3#########################################################################
 
184
    def init_run_opt(self,value=1):
 
185
        """ init all the run scheduling paramater to value """
 
186
        self.run_opt={}
 
187
        self.run_opt['param']=value
 
188
        self.run_opt['analyzer']=value
 
189
        self.run_opt['compilation']=value
 
190
        self.run_opt['event']=value
 
191
        self.run_opt['dir']=value
 
192
        self.run_opt['launch']=value
 
193
        self.run_opt['control']=value
 
194
        self.run_opt['collect']=value
 
195
        self.run_opt['plot']=value 
 
196
        self.run_opt['madweight_main']=value
 
197
        self.run_opt['relaunch']=0           #only for bugging case... -> desactivate
 
198
        self.run_opt['refine']=0             #only for bugging case... -> desactivate
 
199
        self.run_opt['clean']=0              #dangerous... -> desactivate
 
200
        self.run_opt['status']=0             # not in the mean stream
 
201
        self.control_opt()
 
202
 
 
203
    #2#########################################################################
 
204
    def check_info(self):
 
205
        """ assign default value if not defined already and check the input type
 
206
            those default value and the type are defined in MW_param_default.inc
 
207
            structure of this file:
 
208
            block tag type value #comment
 
209
            additionaly check if the mw_parameter['?3'] is a list
 
210
        """
 
211
        
 
212
        #define convertissor
 
213
        def pass_in_integer(value):
 
214
            return int(value)
 
215
 
 
216
        def pass_in_logical(value):
 
217
            if value in ['1','t','T','.true.',1,True]:
 
218
                return 1
 
219
            else:
 
220
                return 0
 
221
 
 
222
        def pass_in_float(value):
 
223
            return float(value)
 
224
 
 
225
        for line in open('./Source/MadWeight/Python/MW_param_default.inc'):
 
226
            line=line.split('#')[0] #remove comment
 
227
            splitline=line.split()  #split the data
 
228
            if len(splitline)!=4:
 
229
                continue
 
230
            #assign element
 
231
            block=splitline[0].lower()
 
232
            tag=splitline[1].lower()
 
233
            type=splitline[2].lower()
 
234
            value=splitline[3]
 
235
            #check if exist -> default
 
236
            try:
 
237
                self[block][tag]
 
238
            except:
 
239
                if value.count('@@'):
 
240
                    value=value.split('@@')
 
241
                    value_2=self[value[0]][value[1]]
 
242
                    value=value_2
 
243
                try:
 
244
                    self[block][tag]=value
 
245
                except:
 
246
                    self[block]={tag:value}
 
247
            #change type
 
248
            if type in ['integer','logical','float']:
 
249
                self[block][tag]=eval('pass_in_'+type+'(self[block][tag])')
 
250
        self.check_mw_parameter_list_type()
 
251
        
 
252
    #2#########################################################################
 
253
    def check_mw_parameter_list_type(self):
 
254
        """ check that self['mw_parameter']['?3'] is a list """
 
255
        nb_param=1
 
256
 
 
257
        while str(nb_param*10+3) in self['mw_parameter']:
 
258
            if not isinstance(self['mw_parameter'][str(nb_param*10+3)], list):
 
259
                self['mw_parameter'][str(nb_param*10+3)]=[self['mw_parameter'][str(nb_param*10+3)]]
 
260
            nb_param+=1
 
261
                
 
262
 
 
263
    #2#########################################################################
 
264
    def take_run_name(self):
 
265
        """take the run name in run_card"""
 
266
        name="run"
 
267
        Pattern=re.compile(r'''\'(\S*)\'\s*=\s*run_tag''',re.I)
 
268
        card=open("./Cards/run_card.dat")
 
269
 
 
270
        while 1:
 
271
            line=card.readline()
 
272
            if line=='':
 
273
                break
 
274
            
 
275
            if Pattern.search(line):
 
276
                name=Pattern.search(line).groups()[0]
 
277
                break
 
278
        return name
 
279
 
 
280
    #2##########################################################################
 
281
    def update_nb_card(self):
 
282
        "take the info from MW_runcard.dat"
 
283
        self.nb_card=self.number_of_P_run()
 
284
        self.def_actif_param()
 
285
        
 
286
    #2##########################################################################
 
287
    def number_of_P_run(self):
 
288
        "take the info from the existing card in Cards"
 
289
 
 
290
        #check if we use different param_card.dat
 
291
#        if self.info["mw_parameter"]["1"]=="1":
 
292
        j=1
 
293
        while 1:
 
294
            if os.path.isfile('Cards/param_card_'+str(j)+'.dat'): j+=1
 
295
            elif(j==1): return j
 
296
            else: return j-1
 
297
            
 
298
 
 
299
 
 
300
    #2##########################################################################
 
301
    def load_events(self):
 
302
        "detect the number of events for P and MW run"
 
303
 
 
304
        self.P_nevents=self.info['mw_run']['5']
 
305
        self.MW_nevents=self.info['mw_run']['6']
 
306
 
 
307
        
 
308
    #2##########################################################################
 
309
    def give_block_param_info(self):
 
310
        """ return the number of modified parameter and the number of different value for each"""
 
311
 
 
312
        nb_block=0
 
313
        nb_values=[]
 
314
        k=0
 
315
        while 1:
 
316
            k+=1
 
317
            try:
 
318
                self.info['mw_parameter'][str(10*k+1)]
 
319
            except:
 
320
                break
 
321
            nb_block+=1
 
322
            if type(self.info['mw_parameter'][str(10*k+3)])==list:
 
323
                nb_values.append(len(self.info['mw_parameter'][str(10*k+3)]))
 
324
            else:
 
325
                nb_values.append(1)
 
326
 
 
327
        return nb_block,nb_values
 
328
 
 
329
    #3########################################################################
 
330
    def CardNb_to_ParameterTag(self,num_card):
 
331
        """ find from th card number, to which value for each block this card belong
 
332
            num_card is the number of the card in the last generation. 
 
333
            card in previous generation are not accessible by this routine
 
334
            (and are not related to this MadWeight card anyway)
 
335
         """
 
336
 
 
337
        nb_block,nb_data_by_block=self.give_block_param_info()
 
338
 
 
339
        if self['mw_parameter']['1']==2:
 
340
            return [num_card-1]*len(nb_data_by_block)
 
341
 
 
342
        tag=[]
 
343
        for k in range(-1,-nb_block-1,-1):
 
344
            tag.append((num_card-1)%nb_data_by_block[k])
 
345
            num_card=1+(num_card-(num_card-1)%nb_data_by_block[k])//nb_data_by_block[k]
 
346
        tag.reverse()
 
347
        return tag
 
348
 
 
349
    #2##########################################################################
 
350
    def set_run_opt(self,option):
 
351
        """analyze option for the run"""
 
352
 
 
353
        if len(option)>1:
 
354
            self.init_run_opt(0)#put everything to false
 
355
        else:
 
356
            return
 
357
        for i in range(1,len(option)):
 
358
            if option[i][0]=='-' and option[i][-1]=='+':
 
359
                num=int(option[i][1:-1])
 
360
                for j in range(num,last_step+1):
 
361
                    self.run_opt[num_to_tag[j]]=1
 
362
            elif option[i][0]=='-' and option[i][-1]=='-':
 
363
                num=int(option[i][1:-1])+1
 
364
                for j in range(1,num):
 
365
                    self.run_opt[num_to_tag[j]]=1
 
366
            elif option[i][0]=='-':
 
367
                num=int(option[i][1:])
 
368
                for i in option[i][1:]:
 
369
                    self.run_opt[num_to_tag[int(i)]]=1
 
370
            elif option[i][-1]=='+':
 
371
                num=tag_to_num[option[i][:-1]]
 
372
                for j in range(num,last_step+1):
 
373
                    self.run_opt[num_to_tag[j]]=1
 
374
            elif option[i][-1]=='-':
 
375
                num=tag_to_num[option[i][:-1]]+1
 
376
                for j in range(1,num):
 
377
                    self.run_opt[num_to_tag[j]]=1
 
378
            elif '=' in option[i]:
 
379
                obj=option[i].split('=')
 
380
                tag=obj[0]
 
381
                value=obj[1]
 
382
                self.run_opt[tag]=value
 
383
            else:
 
384
                self.run_opt[option[i]]=1
 
385
                                                
 
386
        self.control_opt()
 
387
 
 
388
    #3##########################################################################
 
389
    def control_opt(self):
 
390
        """analyze option for the run to have coherent input"""
 
391
 
 
392
 
 
393
        if self.run_opt['refine']:
 
394
            self.run_opt['relaunch']=1
 
395
        
 
396
        #check value for 'madweight_main'
 
397
        for i in list(range(3,9))+[-1,-3,-4]:
 
398
            if self.run_opt[num_to_tag[i]]==1:
 
399
                self.run_opt['madweight_main']=1
 
400
                break
 
401
 
 
402
        if self.run_opt['relaunch']==1:
 
403
            self.run_opt['control']=1
 
404
 
 
405
    #3##########################################################################
 
406
    def def_actif_param(self):
 
407
        """ find which card are still actif """
 
408
 
 
409
        self.param_is_actif={}
 
410
        try:
 
411
            ff=open('Cards/mapping_card.dat')
 
412
        except:
 
413
            print('no mapping card found')
 
414
            for i in range(1,self.nb_card+1):
 
415
                self.param_is_actif[i]=1 #if no file defined all card are supose to be used
 
416
            self.actif_param=list(range(1,self.nb_card+1))
 
417
            return
 
418
 
 
419
        self.actif_param=[]
 
420
        for line in ff:
 
421
            split=line.split()
 
422
            if len(split)<2:
 
423
                continue
 
424
            nb=int(split[0])
 
425
            actif=int(split[-1])
 
426
            self.param_is_actif[nb]=actif
 
427
            if actif:
 
428
                self.actif_param.append(nb)
 
429
 
 
430
        if self.nb_card!=len(self.actif_param):
 
431
            print('wrong mapping file or some card are desactivated')
 
432
 
 
433
 
 
434
    #3##########################################################################
 
435
    def find_existing_events(self,directory='',card_nb=''):
 
436
        """ find how much event are already defined """
 
437
 
 
438
        if directory=='':
 
439
            directory='./SubProcesses/'+self.MW_listdir[0]+'/'+self.name+'/'
 
440
        if card_nb=='':
 
441
            card_nb=self.actif_param[0]
 
442
        if os.path.isdir(directory+'/card_'+str(card_nb)+'/'):
 
443
            number=[int(eventdir.split('_')[-1]) for eventdir in os.listdir(directory+'/card_'+str(card_nb)+'/')]
 
444
        else:
 
445
            return 0
 
446
        
 
447
        if len(number):
 
448
            return max(number)+1
 
449
        else:
 
450
            return 0
 
451
        
 
452
#1 #################################################################################
 
453
class move:
 
454
    def __init__(self):
 
455
        self.initpos=os.getcwd()
 
456
        self.old=self.initpos
 
457
 
 
458
    def to_SubProcesses(self):
 
459
        
 
460
        old_pos=os.getcwd()+'/'
 
461
        self.old=old_pos
 
462
        if old_pos.count('/SubProcesses/')>1:
 
463
            new_pos=pos.split('/SubProcesses/')[0]+'/SubProcesses/'
 
464
        elif old_pos.count('/SubProcesses/')==0:
 
465
            new_pos=old_pos+'/SubProcesses/'
 
466
        else:
 
467
            new_pos='/SubProcesses/'.join(old_pos.split('/SubProcesses/')[:-1])+'/SubProcesses/'
 
468
            
 
469
        if new_pos!=old_pos:
 
470
            self.old=old_pos
 
471
            os.chdir(new_pos)
 
472
            
 
473
    def to_init(self):
 
474
        self.old=os.getcwd()
 
475
        os.chdir(self.initpos)
 
476
 
 
477
    def store(self):
 
478
        self.store=os.getcwd()
 
479
 
 
480
    def to_store(self):
 
481
        self.old=os.getcwd()
 
482
        os.chdir(self.store)
 
483
 
 
484
    def to_last_pos(self):
 
485
        pos,self.old=self.old,os.getcwd()
 
486
        os.chdir(pos)
 
487
 
 
488
    def to_main(self):
 
489
        old=os.getcwd()
 
490
        try:
 
491
            go_to_main_dir()
 
492
        except:
 
493
            self.to_SubProcesses()
 
494
            os.chdir('..')
 
495
        self.old=old
 
496
 
 
497
 
 
498
def detect_SubProcess(P_mode=0):
 
499
        MW_SubProcess_list=[]
 
500
        if P_mode == 1:
 
501
            print('WARNING: automatic renormalization is not supported anymore')
 
502
 
 
503
        list_dir=os.listdir("./SubProcesses/")
 
504
        for name in list_dir:
 
505
            try:           
 
506
                st = os.lstat(os.path.join("./SubProcesses/", name))
 
507
            except os.error:
 
508
                continue
 
509
            if stat.S_ISDIR(st.st_mode):
 
510
                if name[0]=='P':
 
511
                    MW_SubProcess_list.append(name)                
 
512
 
 
513
# Pierre: set MW_SubProcess_list to SubProcess_list, set SubProcess_list to []
 
514
        return [],MW_SubProcess_list
 
515