| Trees | Indices | Help |
|---|
|
|
1 ################################################################################
2 #
3 # Copyright (c) 2009 The MadGraph5_aMC@NLO Development team and Contributors
4 #
5 # This file is a part of the MadGraph5_aMC@NLO project, an application which
6 # automatically generates Feynman diagrams and matrix elements for arbitrary
7 # high-energy processes in the Standard Model and beyond.
8 #
9 # It is subject to the MadGraph5_aMC@NLO license which should accompany this
10 # distribution.
11 #
12 # For more information, visit madgraph.phys.ucl.ac.be and amcatnlo.web.cern.ch
13 #
14 ################################################################################
15 """A user friendly command line interface to access all MadGraph5_aMC@NLO features.
16 Uses the cmd package for command interpretation and tab completion.
17 """
18
19
20 import atexit
21 import logging
22 import optparse
23 import os
24 import pydoc
25 import re
26 import subprocess
27 import sys
28 import traceback
29 import time
30
31 root_path = os.path.split(os.path.dirname(os.path.realpath( __file__ )))[0]
32 root_path = os.path.split(root_path)[0]
33 sys.path.insert(0, root_path)
34
35 #usefull shortcut
36 pjoin = os.path.join
37
38 import madgraph
39 import madgraph.core.diagram_generation as diagram_generation
40 import madgraph.core.helas_objects as helas_objects
41 import madgraph.loop.loop_base_objects as loop_base_objects
42 import madgraph.interface.extended_cmd as cmd
43 import madgraph.interface.madgraph_interface as MGcmd
44 import madgraph.interface.loop_interface as LoopCmd
45 import madgraph.interface.amcatnlo_interface as amcatnloCmd
46 import madgraph.fks.fks_base as fks_base
47 import madgraph.iolibs.files as files
48 import madgraph.various.misc as misc
49
50 from madgraph import MG4DIR, MG5DIR, MadGraph5Error
51
52 logger = logging.getLogger('cmdprint') # -> stdout
56 """ Helping class containing all the switching routine """
57
59
60 # define the interface
61 self.change_principal_cmd(main)
62 self.cmd.__init__(self, *args, **opt)
63
64 interface_names= {'MadGraph':('MG5_aMC',MGcmd.MadGraphCmd),
65 'MadLoop':('MG5_aMC',LoopCmd.LoopInterface),
66 'aMC@NLO':('MG5_aMC',amcatnloCmd.aMCatNLOInterface)}
67
68 _switch_opts = interface_names.keys()
69 current_interface = None
70
71 # Helper functions
72
74 """ Function to initialize the interface when switched to it. It is not
75 the same as __init__ as this latter functions would call its mother
76 from madgraph_interface and this is only desirable for the first
77 initialization when launching MG5 """
78 return self.cmd.setup(self, *args, **opts)
79
81 """redefine all the command to call directly the appropriate child"""
82
83 correct = True
84 # function which should be self.cmd dependent but which doesn't start
85 # by do_xxxx, help_xxx, check_xxxx or complete_xxx
86 overwritable = []
87 # list of item overwritten by the MasterClass
88 self.to_preserve = [key for key,method in Switcher.__dict__.items() if
89 hasattr(method, '__call__') ]
90 self.to_preserve += ['do_shell', 'help_shell', 'complete_shell']
91
92 ff = open(pjoin(os.getcwd(), 'additional_command'), 'w')
93
94 for key in dir(self):
95 # by pass all not over-writable command
96 if key in self.to_preserve:
97 continue
98 if not (key.startswith('do_') or key.startswith('complete_') or \
99 key.startswith('help_') or key.startswith('check_') or \
100 key in overwritable):
101 continue
102 text = """\
103 def %(key)s(self, *args, **opts):
104 return self.cmd.%(key)s(self, *args, **opts)
105
106 """ % {'key': key}
107 logger.warning("""Command %s not define in the Master.
108 The line to add to the master_interface.py are written in 'additional_command' file""" % key)
109 ff.write(text)
110 correct = False
111
112
113 # Check that all function define in more than one subclass is define
114 # in the Switcher or in one of the MasterClass
115 define = {}
116 for mother in MasterCmd.__mro__:
117 if mother.__name__ in ['Cmd', 'BasicCmd', 'ExtendedCmd']:
118 continue
119
120
121 for data in mother.__dict__:
122 #check if define in Switcher
123 if data in Switcher.__dict__ or data.startswith('__'):
124 continue
125 if data in MasterCmd.__dict__:
126 #always overwritten in the main class
127 continue
128 if data not in define:
129 define[data] = mother.__name__
130 else:
131 logger.warning('%s define in %s and in %s but not in Switcher.' % (data, define[data], mother.__name__))
132 correct = False
133
134 # Do the same for the WEb MasterClass
135 define = {}
136 for mother in MasterCmdWeb.__mro__:
137 if mother.__name__ in ['Cmd', 'BasicCmd', 'ExtendedCmd']:
138 continue
139
140 for data in mother.__dict__:
141 #check if define in Switcher
142 if data in Switcher.__dict__ or data.startswith('__'):
143 continue
144 if data in MasterCmdWeb.__dict__:
145 #always overwritten in the main class
146 continue
147 if data not in define:
148 define[data] = mother.__name__
149 else:
150 logger.warning('%s define in %s and in %s but not in Switcher.' % (data, define[data], mother.__name__))
151 correct = False
152
153 if not correct:
154 raise Exception, 'The Cmd interface has dangerous features. Please see previous warnings and correct those.'
155
156
157
158 @staticmethod
160 """Extract from a string what is the type of the computation. This
161 returns a tuple (mode, option, pert_orders) where mode can be either 'NLO' or 'tree'
162 and option 'all', 'real' or 'virt'."""
163
164 # Perform sanity modifications on the lines:
165 # Add a space before and after any > , $ / | [ ]
166 space_before = re.compile(r"(?P<carac>\S)(?P<tag>[\\[\\]/\,\\$\\>|])(?P<carac2>\S)")
167 line2 = space_before.sub(r'\g<carac> \g<tag> \g<carac2>', line)
168
169 # Use regular expressions to extract the loop mode (if present) and its
170 # option, specified in the line with format [ option = loop_orders ] or
171 # [ loop_orders ] which implicitly select the 'all' option.
172 loopRE = re.compile(r"^(.*)(?P<loop>\[(\s*(?P<option>\w+)\s*=)?(?P<orders>.+)?\])(.*)$")
173 res=loopRE.search(line)
174 if res:
175 orders=res.group('orders').split() if res.group('orders') else []
176 if res.group('option') and len(res.group('option').split())==1:
177 if res.group('option').split()[0]=='tree':
178 return ('tree',res.group('option').split()[0],orders)
179 else:
180 return ('NLO',res.group('option').split()[0],orders)
181 else:
182 # If not option is set the convention is that the mode is 'all'
183 # unless no perturbation orders is defined.
184 if len(orders)>0:
185 return ('NLO','all',orders)
186 else:
187 return ('tree',None,[])
188 else:
189 return ('tree',None,[])
190
191 # Wrapping functions possibly switching to new interfaces
192
194
195 argss = cmd.Cmd.split_arg(line)
196 if len(argss)>=1 and argss[0] in ['process','timing','profile']:
197 proc_line = ' '.join(argss[1:])
198 (type,nlo_mode,orders)=self.extract_process_type(proc_line)
199 if type=='NLO':
200 if not nlo_mode in self._valid_nlo_modes: raise self.InvalidCMD( \
201 'The NLO mode %s is not valid. Please choose one among: %s' \
202 % (nlo_mode, ' '.join(self._valid_nlo_modes)))
203 elif nlo_mode in ['all', 'real', 'LOonly']:
204 self.change_principal_cmd('aMC@NLO')
205 elif nlo_mode in ['virt', 'sqrvirt']:
206 self.change_principal_cmd('MadLoop')
207 elif nlo_mode == 'noborn':
208 self.change_principal_cmd('MadLoop')
209 self.cmd.validate_model(self, loop_type=nlo_mode,
210 coupling_type=orders)
211 self.change_principal_cmd('MadGraph')
212 return self.cmd.create_loop_induced(self, line, *args, **opts)
213 try:
214 return self.cmd.do_add(self, line, *args, **opts)
215 except fks_base.NoBornException:
216 logger.info("------------------------------------------------------------------------", '$MG:color:BLACK')
217 logger.info(" No Born diagrams found. Now switching to the loop-induced mode. ", '$MG:color:BLACK')
218 logger.info(" Please cite ref. 'arXiv:1507.00020' when using results from this mode. ", '$MG:color:BLACK')
219 logger.info("------------------------------------------------------------------------", '$MG:color:BLACK')
220 self.change_principal_cmd('MadGraph')
221 return self.cmd.create_loop_induced(self, line, *args, **opts)
222
223
225
226 argss = self.split_arg(line)
227 proc_line = " ".join(argss[1:])
228 (type,nlo_mode,orders)=self.extract_process_type(proc_line)
229 if type=='NLO':
230 if not nlo_mode in self._valid_nlo_modes: raise self.InvalidCMD(\
231 'The NLO mode %s is not valid. Please chose one among: %s' \
232 % (nlo_mode, ' '.join(self._valid_nlo_modes)))
233 elif nlo_mode == 'all':
234 self.change_principal_cmd('MadLoop')
235 elif nlo_mode == 'real':
236 raise self.InvalidCMD('Mode [real=...] not valid for checking processes.')
237 self.change_principal_cmd('aMC@NLO')
238 elif nlo_mode == 'virt' or nlo_mode == 'sqrvirt':
239 self.change_principal_cmd('MadLoop')
240 else:
241 self.change_principal_cmd('MadGraph')
242
243 return self.cmd.do_check(self, line, *args, **opts)
244
246
247 argss = cmd.Cmd.split_arg(line)
248 # Make sure to switch to the right interface.
249 if len(argss)>=1:
250 proc_line = ' '.join(argss[1:])
251 (type,nlo_mode,orders)=self.extract_process_type(proc_line)
252 if type=='NLO':
253 if not nlo_mode in self._valid_nlo_modes: raise self.InvalidCmd( \
254 'The NLO mode %s is not valid. Please chose one among: %s' \
255 % (nlo_mode, ' '.join(self._valid_nlo_modes)))
256 elif nlo_mode in ['all', 'real', 'LOonly']:
257 self._fks_multi_proc = fks_base.FKSMultiProcess()
258 self.change_principal_cmd('aMC@NLO')
259 elif nlo_mode == 'virt' or nlo_mode == 'virtsqr':
260 self.change_principal_cmd('MadLoop')
261 else:
262 self.change_principal_cmd('MadGraph')
263 return self.cmd.do_generate(self, line, *args, **opts)
264
266 self.cmd.do_import(self, *args, **opts)
267 if self._curr_model:
268 if isinstance(self._curr_model, loop_base_objects.LoopModel) and \
269 self._curr_model['perturbation_couplings']!=[] and \
270 self.current_interface not in ['aMC@NLO','MadLoop']:
271 self.change_principal_cmd('aMC@NLO')
272 if (not isinstance(self._curr_model, loop_base_objects.LoopModel) or \
273 self._curr_model['perturbation_couplings']==[]) and \
274 self.current_interface in ['MadLoop']:
275 self.change_principal_cmd('MadGraph')
276 import madgraph.various.misc as misc
277 return
278
280 """ treat output aloha in order to use always the one in MG5 """
281 if line.strip().startswith('aloha'):
282 MGcmd.MadGraphCmd.do_output(self, line, *args, **opts)
283 else:
284 self.cmd.do_output(self, line, *args, **opts)
285
287 if arg and arg[0] == 'aloha':
288 MGcmd.MadGraphCmd.check_output(self, arg, *args, **opts)
289 else:
290 self.cmd.check_output(self, arg, *args, **opts)
291
292
293
294
295 # Dummy functions, not triggering any switch of interfaces
296
299
302
305
308
311
314
317
320
323
326
329
332
335
338
341
344
347
350
353
356
359
362
365
368
371
374
377
380
383
386
389
392
395
398
401
404
407
410
413
416
419
422
425
428
431
434
438
441
444
447
450
453
456
459
461 args = cmd.Cmd.split_arg(line)
462 # check if a path is given
463 if len(args) >=1:
464 if os.path.isdir(args[0]):
465 path = os.path.realpath(args[0])
466 elif os.path.isdir(pjoin(MG5DIR,args[0])):
467 path = pjoin(MG5DIR,args[0])
468 elif MG4DIR and os.path.isdir(pjoin(MG4DIR,args[0])):
469 path = pjoin(MG4DIR,args[0])
470 else:
471 path=None
472 # if there is a path, find what output has been done
473 if path:
474 type = self.cmd.find_output_type(self, path)
475 if type in ['standalone', 'standalone_cpp', 'pythia8', 'madevent']:
476 self.change_principal_cmd('MadGraph')
477 elif type == 'aMC@NLO':
478 self.change_principal_cmd('aMC@NLO')
479 elif type == 'MadLoop':
480 self.change_principal_cmd('MadLoop')
481
482 return self.cmd.do_launch(self, line, *argss, **opts)
483
486
489
492
495
498
501
504
507
510
513
516
519
522
525
528
531
534
537
540
543
546
549
552
555
558
561
564
567
570
573
575
577
578 # define the interface
579 if main in self.interface_names.keys():
580 self.prompt= self.interface_names[main][0]+'>'
581 self.cmd= self.interface_names[main][1]
582 self.current_interface=main
583 else:
584 raise MadGraph5Error, 'Type of interface not valid: %s' % main
585 self.cmd.__init__(self, *args, **opt)
586 self.current_interface = main
587
591
593 """Not in help: Allow to switch to any given interface from command line """
594
595 args = cmd.Cmd.split_arg(line)
596 if len(args)==1 and args[0] in self.interface_names.keys():
597 self.change_principal_cmd(args[0])
598 else:
599 raise self.InvalidCmd("Invalid switch command or non existing interface %s."\
600 %args[0]+" Valid interfaces are %s"\
601 %','.join(interface_quick_name.keys()))
602
604 old_cmd=self.current_interface
605 if name in self.interface_names.keys():
606 self.prompt= self.interface_names[name][0]+'>'
607 self.cmd= self.interface_names[name][1]
608 self.current_interface=name
609 else:
610 raise MadGraph5Error, 'Type of interface not valid: %s' % name
611
612 if self.interface_names[old_cmd][0]!=self.interface_names[name][0]:
613 logger.info("Switching from interface %s to %s"\
614 %(self.interface_names[old_cmd][0],\
615 self.interface_names[name][0]))
616 # Setup the interface
617 self.cmd.setup(self)
618
619 if __debug__:
620 self.debug_link_to_command()
621
624
626
627 if os.environ.has_key('_CONDOR_SCRATCH_DIR'):
628 self.writing_dir = pjoin(os.environ['_CONDOR_SCRATCH_DIR'], \
629 os.path.pardir)
630 else:
631 self.writing_dir = pjoin(os.environ['MADGRAPH_DATA'],
632 os.environ['REMOTE_USER'])
633
634
635 #standard initialization
636 Switcher.__init__(self, mgme_dir = '', *arg, **opt)
637
638 self.options['timeout'] = 1 # time authorize to answer question [0 is no time limit]
639
641 if name == 'MadGraph':
642 self.cmd = MGcmd.MadGraphCmdWeb
643 elif name == 'Loop':
644 self.cmd = LoopCmd.LoopInterfaceWeb
645 else:
646 raise MadGraph5Error, 'Type of interface not valid'
647
648 if __debug__:
649 self.debug_link_to_command()
650
653
655 """Finalize web generation"""
656
657 if flaglist != []:
658 raise Exception
659 self.cmd.finalize(self, nojpeg, online = True)
660
662 """Finalize web generation"""
663
664 opts['online'] = True
665 self.cmd.finalize(self, nojpeg, opts)
666
667 # Generate a new amplitude
669 """Generate an amplitude for a given process"""
670
671 try:
672 Switcher.do_generate(self, line)
673 except:
674 # put the stop logo on the web
675 files.cp(self._export_dir+'/HTML/stop.jpg',self._export_dir+'/HTML/card.jpg')
676 raise
677
678 # Add a process to the existing multiprocess definition
680 """Generate an amplitude for a given process and add to
681 existing amplitudes
682 syntax:
683 """
684 try:
685 Switcher.do_add(self, line)
686 except:
687 # put the stop logo on the web
688 files.cp(self._export_dir+'/HTML/stop.jpg',self._export_dir+'/HTML/card.jpg')
689 raise
690
691 # Use the cluster file for the configuration
693
694 """Force to use the web configuration file only"""
695 config_path = pjoin(os.environ['MADGRAPH_BASE'], 'mg5_configuration.txt')
696 return Switcher.set_configuration(self, config_path=config_path, final=final)
697
699 """Save information to file"""
700
701 if check:
702 self.check_save([])
703 raise #useless but full security
704
705 args = self.split_arg(line)
706 if args[0] != 'options':
707 Switcher.do_save(self, line,check, opt)
708 else:
709 # put default options since
710 # in the web the local file is not used
711 # in download the default file is more usefull
712 files.cp(pjoin(MG5DIR,'input','mg5_configuration.txt'), args[1])
713
717
| Trees | Indices | Help |
|---|
| Generated by Epydoc 3.0.1 on Mon Aug 1 11:09:53 2016 | http://epydoc.sourceforge.net |