~ma5/madanalysis5/madanalysis-development

« back to all changes in this revision

Viewing changes to madanalysis/IOinterface/delphescard_checker.py

  • Committer: Benjamin Fuks
  • Date: 2018-05-04 10:44:49 UTC
  • mfrom: (115.1.81 v1.6beta)
  • Revision ID: fuks@cern.ch-20180504104449-60h8a00loxgr8zg0
Releasing v1.6

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
################################################################################
 
2
#  
 
3
#  Copyright (C) 2012-2016 Eric Conte, Benjamin Fuks
 
4
#  The MadAnalysis development team, email: <ma5team@iphc.cnrs.fr>
 
5
#  
 
6
#  This file is part of MadAnalysis 5.
 
7
#  Official website: <https://launchpad.net/madanalysis5>
 
8
#  
 
9
#  MadAnalysis 5 is free software: you can redistribute it and/or modify
 
10
#  it under the terms of the GNU General Public License as published by
 
11
#  the Free Software Foundation, either version 3 of the License, or
 
12
#  (at your option) any later version.
 
13
#  
 
14
#  MadAnalysis 5 is distributed in the hope that it will be useful,
 
15
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
16
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 
17
#  GNU General Public License for more details.
 
18
#  
 
19
#  You should have received a copy of the GNU General Public License
 
20
#  along with MadAnalysis 5. If not, see <http://www.gnu.org/licenses/>
 
21
#  
 
22
################################################################################
 
23
 
 
24
 
 
25
import logging
 
26
import os
 
27
 
 
28
class DelphesModule():
 
29
    
 
30
    def __init__(self):
 
31
        self.name=''
 
32
        self.type=''
 
33
        self.inputs=[]
 
34
        self.outputs=[]
 
35
        self.ModuleExecutionPaths=[]
 
36
        self.Modules=[]
 
37
        self.PileUps=[]
 
38
 
 
39
 
 
40
class DelphesCardChecker():
 
41
 
 
42
    def __init__(self,dirname,main):
 
43
        self.dirname = dirname
 
44
        self.main    = main
 
45
 
 
46
 
 
47
    def getNameCard(self):
 
48
        if self.main.fastsim.package=="delphes":
 
49
            cardname = self.main.fastsim.delphes.card
 
50
        elif self.main.fastsim.package=="delphesMA5tune":
 
51
            cardname = self.main.fastsim.delphesMA5tune.card
 
52
        return self.dirname+"/Input/"+cardname        
 
53
        
 
54
 
 
55
    def checkPresenceCard(self):
 
56
        logging.getLogger('MA5').debug("Check the presence of the Delphes card: "+self.getNameCard()+' ...')
 
57
        if not os.path.isfile(self.getNameCard()):
 
58
            logging.getLogger('MA5').error('DelphesCard is not found: '+self.getNameCard())
 
59
            return False
 
60
        return True
 
61
                          
 
62
 
 
63
    def editCard(self):
 
64
        logging.getLogger('MA5').debug("Invite the user to edit the Delphes card: "+self.getNameCard()+' ...')
 
65
        if self.main.forced or self.main.script:
 
66
            return True
 
67
 
 
68
        logging.getLogger('MA5').info("Would you like to edit the Delphes Card? (Y/N)")
 
69
        allowed_answers=['n','no','y','yes']
 
70
        answer=""
 
71
        while answer not in  allowed_answers:
 
72
            answer=raw_input("Answer: ")
 
73
            answer=answer.lower()
 
74
        if answer=="no" or answer=="n":
 
75
            return True
 
76
        else:
 
77
            # TO BE CODED PROPERLY AND CHECK IF THE COMMAND HAS WORKED
 
78
            os.system(self.main.session_info.editor+" "+self.getNameCard())
 
79
            return True
 
80
 
 
81
 
 
82
    def checkContentCard(self):
 
83
        logging.getLogger('MA5').debug("Check the content of the Delphes card: "+self.getNameCard()+' ...')
 
84
 
 
85
        self.extractContentCard()
 
86
        test = self.decodeContentCard()
 
87
        if test or self.main.forced or self.main.script:
 
88
            return test
 
89
        else:
 
90
            logging.getLogger('MA5').info("Are you sure to go on with this Card? (Y/N)")
 
91
            allowed_answers=['n','no','y','yes']
 
92
            answer=""
 
93
            while answer not in  allowed_answers:
 
94
                answer=raw_input("Answer: ")
 
95
                answer=answer.lower()
 
96
            if answer=="no" or answer=="n":
 
97
                return False # no, give up
 
98
            else:
 
99
                return True # go on       
 
100
    
 
101
 
 
102
    def extractContentCard(self):
 
103
        ExecutionMode=False
 
104
        self.ModuleExecutionPaths=[]
 
105
        self.Modules=[]
 
106
        self.PileUps=[]
 
107
        module=""
 
108
        input = open(self.getNameCard())
 
109
        counter=0
 
110
        for line in input:
 
111
            counter = counter+1
 
112
 
 
113
            #isolating '=' character 
 
114
            line = line.replace('=',' = ')
 
115
            line = line.replace('{',' { ')
 
116
            line = line.replace('}',' } ')
 
117
            
 
118
            #cleaning the line
 
119
            line = line.lstrip()
 
120
 
 
121
            #rejecting comment line
 
122
            if line.startswith('#'):
 
123
                continue
 
124
 
 
125
            #rejecting comment part of a line
 
126
            if '#' in line:
 
127
                line = line.split('#')[0]
 
128
            line = line.rstrip()
 
129
 
 
130
            #splitting line
 
131
            split = line.split()
 
132
            if len(split)==0:
 
133
                continue
 
134
            if ExecutionMode:
 
135
                if split[0]=='}':
 
136
                    ExecutionMode=False
 
137
                elif len(split)==1:
 
138
                    self.ModuleExecutionPaths.append(split[0])
 
139
                else:
 
140
                    logging.getLogger("MA5").warning('Problem with Delphes card: incorrect syntax @ line '+str(counter))
 
141
                continue
 
142
            if len(split)>=3 and split[0]=='module':
 
143
                MyModule=DelphesModule()
 
144
                MyModule.name = split[2]
 
145
                MyModule.type = split[1]
 
146
                module=MyModule.type
 
147
                self.Modules.append(MyModule)
 
148
            if len(split)>=3 and split[0] in ['set','add'] and split[1].endswith('InputArray'):
 
149
                if len(self.Modules)==0:
 
150
                    logging.getLogger("MA5").warning('Problem with Delphes card: InputArray before module definition @ line '+str(counter))
 
151
                else:          
 
152
                    self.Modules[-1].inputs.append(split[2])
 
153
                    if len(split)==4:
 
154
                        self.Modules[-1].outputs.append(split[3])
 
155
                    
 
156
            if len(split)>=3 and split[0]=='set' and split[1].endswith('OutputArray'):
 
157
                if len(self.Modules)==0:
 
158
                    logging.getLogger("MA5").warning('Problem with Delphes card OutputArray before module definition @ line '+str(counter))
 
159
                else:          
 
160
                    self.Modules[-1].outputs.append(split[2])
 
161
            if len(split)>=3 and split[0]=='set' and split[1]=='PileUpFile' and module=='PileUpMerger':
 
162
                self.PileUps.append(split[2])
 
163
            if len(split)>=2 and split[0]=='set' and split[1]=='ExecutionPath':
 
164
                ExecutionMode=True
 
165
            
 
166
        input.close()
 
167
 
 
168
    def decodeContentCard(self):
 
169
        # check that modules are declared
 
170
        logging.getLogger("MA5").debug("- Check that the modules to execute are declared (#modules="+str(len(self.ModuleExecutionPaths))+")...")
 
171
        test = True
 
172
        for i in self.ModuleExecutionPaths:
 
173
            ok=False
 
174
            for j in self.Modules: 
 
175
                if i==j.name:
 
176
                    ok=True
 
177
                    break
 
178
            if not ok:
 
179
                logging.getLogger("MA5").warning("Problem with Delphes card: module "+item+" is not declared.")
 
180
                test=False
 
181
 
 
182
        # check pileup path
 
183
        logging.getLogger("MA5").debug("- Check the pile-up files (#files="+str(len(self.PileUps))+")...")
 
184
        for item in self.PileUps:
 
185
            if not os.path.isfile(item):
 
186
                logging.getLogger("MA5").warning("Problem with Delphes card: the pile-up file "+item+" is not found.")
 
187
                test=False
 
188
 
 
189
        # check inputs and output
 
190
        logging.getLogger("MA5").debug("- Check the input of modules...")
 
191
        for module in self.Modules:
 
192
            for input in module.inputs:
 
193
                words=input.split('/')
 
194
                if len(words)!=2:
 
195
                    logging.getLogger("MA5").warning("Problem with Delphes card: the module "+module.name+" has a bad syntax for the input collection: "+input)
 
196
                    test=False
 
197
                else:
 
198
                    theModule=words[0]
 
199
                    theCollection=words[1]
 
200
 
 
201
                    ok=False
 
202
                    outputModule=0
 
203
                    for i in self.Modules:
 
204
                       if theModule==i.name:
 
205
                           outputModule=i
 
206
                           ok=True
 
207
                           break
 
208
                    if not ok and theModule!='Delphes':
 
209
                        logging.getLogger("MA5").warning("Problem with Delphes card: the module "+module.name+" has unknown InputArray module called: "+theModule)
 
210
                        test=False
 
211
                    elif theModule!='Delphes':
 
212
                        ok=False
 
213
                        for j in outputModule.outputs:
 
214
                            if j==theCollection:
 
215
                                ok=True
 
216
                                break
 
217
                        if not ok:
 
218
                            logging.getLogger("MA5").warning("Problem with Delphes card: the module "+module.name+" has unknown InputArray label called: "+theCollection)
 
219
                            test=False
 
220
 
 
221
 
 
222
        return test 
 
223
 
 
224