| 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 if hasattr(self, 'plugin') and self.plugin:
84 return True
85
86 correct = True
87 # function which should be self.cmd dependent but which doesn't start
88 # by do_xxxx, help_xxx, check_xxxx or complete_xxx
89 overwritable = []
90 # list of item overwritten by the MasterClass
91 self.to_preserve = [key for key,method in Switcher.__dict__.items() if
92 hasattr(method, '__call__') ]
93 self.to_preserve += ['do_shell', 'help_shell', 'complete_shell']
94
95 ff = open(pjoin(os.getcwd(), 'additional_command'), 'w')
96
97 for key in dir(self):
98 # by pass all not over-writable command
99 if key in self.to_preserve:
100 continue
101 if not (key.startswith('do_') or key.startswith('complete_') or \
102 key.startswith('help_') or key.startswith('check_') or \
103 key in overwritable):
104 continue
105 text = """\
106 def %(key)s(self, *args, **opts):
107 return self.cmd.%(key)s(self, *args, **opts)
108
109 """ % {'key': key}
110 logger.warning("""Command %s not define in the Master.
111 The line to add to the master_interface.py are written in 'additional_command' file""" % key)
112 ff.write(text)
113 correct = False
114
115
116 # Check that all function define in more than one subclass is define
117 # in the Switcher or in one of the MasterClass
118 define = {}
119 for mother in MasterCmd.__mro__:
120 if mother.__name__ in ['OriginalCmd', 'BasicCmd', 'CmdExtended', 'Cmd']:
121 continue
122
123
124 for data in mother.__dict__:
125 #check if define in Switcher
126 if data in Switcher.__dict__ or data.startswith('__'):
127 continue
128 if data in MasterCmd.__dict__:
129 #always overwritten in the main class
130 continue
131 if data not in define:
132 define[data] = mother.__name__
133 else:
134 logger.warning('%s define in %s and in %s but not in Switcher.' % (data, define[data], mother.__name__))
135 correct = False
136
137 # Do the same for the WEb MasterClass
138 define = {}
139 for mother in MasterCmdWeb.__mro__:
140 if mother.__name__ in ['OriginalCmd', 'BasicCmd', 'CmdExtended', 'Cmd']:
141 continue
142 for data in mother.__dict__:
143 #check if define in Switcher
144 if data in Switcher.__dict__ or data.startswith('__'):
145 continue
146 if data in MasterCmdWeb.__dict__:
147 #always overwritten in the main class
148 continue
149 if data not in define:
150 define[data] = mother.__name__
151 else:
152 logger.warning('%s define in %s and in %s but not in Switcher.' % (data, define[data], mother.__name__))
153 correct = False
154
155 if not correct:
156 raise Exception, 'The Cmd interface has dangerous features. Please see previous warnings and correct those.'
157
158
159
160 @staticmethod
162 """Extract from a string what is the type of the computation. This
163 returns a tuple (mode, option, pert_orders) where mode can be either 'NLO' or 'tree'
164 and option 'all', 'real' or 'virt'."""
165
166 # Perform sanity modifications on the lines:
167 # Add a space before and after any > , $ / | [ ]
168 space_before = re.compile(r"(?P<carac>\S)(?P<tag>[\\[\\]/\,\\$\\>|])(?P<carac2>\S)")
169 line2 = space_before.sub(r'\g<carac> \g<tag> \g<carac2>', line)
170
171 # Use regular expressions to extract the loop mode (if present) and its
172 # option, specified in the line with format [ option = loop_orders ] or
173 # [ loop_orders ] which implicitly select the 'all' option.
174 loopRE = re.compile(r"^(.*)(?P<loop>\[(\s*(?P<option>\w+)\s*=)?(?P<orders>.+)?\])(.*)$")
175 # Make sure that the content of options following '--' are not considered.
176 res=loopRE.search(line.split('--')[0])
177 if res:
178 orders=res.group('orders').split() if res.group('orders') else []
179 if res.group('option') and len(res.group('option').split())==1:
180 if res.group('option').split()[0]=='tree':
181 return ('tree',res.group('option').split()[0],orders)
182 else:
183 return ('NLO',res.group('option').split()[0],orders)
184 else:
185 # If not option is set the convention is that the mode is 'all'
186 # unless no perturbation orders is defined.
187 if len(orders)>0:
188 return ('NLO','all',orders)
189 else:
190 return ('tree',None,[])
191 else:
192 return ('tree',None,[])
193
194 # Wrapping functions possibly switching to new interfaces
195
197
198 argss = cmd.Cmd.split_arg(line)
199 if len(argss)>=1 and argss[0] in ['process','timing','profile']:
200 proc_line = ' '.join(argss[1:])
201 (type,nlo_mode,orders)=self.extract_process_type(proc_line)
202 if type=='NLO':
203 if not nlo_mode in self._valid_nlo_modes: raise self.InvalidCMD( \
204 'The NLO mode %s is not valid. Please choose one among: %s' \
205 % (nlo_mode, ' '.join(self._valid_nlo_modes)))
206 elif nlo_mode in ['all', 'real', 'LOonly']:
207 self.change_principal_cmd('aMC@NLO')
208 elif nlo_mode in ['virt', 'sqrvirt']:
209 self.change_principal_cmd('MadLoop')
210 elif nlo_mode == 'noborn':
211 self.change_principal_cmd('MadLoop')
212 self.cmd.validate_model(self, loop_type=nlo_mode,
213 coupling_type=orders)
214 self.change_principal_cmd('MadGraph')
215 return self.cmd.create_loop_induced(self, line, *args, **opts)
216 try:
217 return self.cmd.do_add(self, line, *args, **opts)
218 except fks_base.NoBornException:
219 logger.info("------------------------------------------------------------------------", '$MG:color:BLACK')
220 logger.info(" No Born diagrams found. Now switching to the loop-induced mode. ", '$MG:color:BLACK')
221 logger.info(" Please cite ref. 'arXiv:1507.00020' when using results from this mode. ", '$MG:color:BLACK')
222 logger.info("------------------------------------------------------------------------", '$MG:color:BLACK')
223 self.change_principal_cmd('MadGraph')
224 return self.cmd.create_loop_induced(self, line, *args, **opts)
225
226
228
229 argss = self.split_arg(line)
230 proc_line = " ".join(argss[1:])
231 (type,nlo_mode,orders)=self.extract_process_type(proc_line)
232 if type=='NLO':
233 if not nlo_mode in self._valid_nlo_modes: raise self.InvalidCMD(\
234 'The NLO mode %s is not valid. Please chose one among: %s' \
235 % (nlo_mode, ' '.join(self._valid_nlo_modes)))
236 elif nlo_mode == 'all':
237 self.change_principal_cmd('MadLoop')
238 elif nlo_mode == 'real':
239 raise self.InvalidCMD('Mode [real=...] not valid for checking processes.')
240 self.change_principal_cmd('aMC@NLO')
241 elif nlo_mode == 'virt' or nlo_mode == 'sqrvirt':
242 self.change_principal_cmd('MadLoop')
243 else:
244 self.change_principal_cmd('MadGraph')
245
246 return self.cmd.do_check(self, line, *args, **opts)
247
249
250 argss = cmd.Cmd.split_arg(line)
251 # Make sure to switch to the right interface.
252 if len(argss)>=1:
253 proc_line = ' '.join(argss[1:])
254 (type,nlo_mode,orders)=self.extract_process_type(proc_line)
255 if type=='NLO':
256 if not nlo_mode in self._valid_nlo_modes: raise self.InvalidCmd( \
257 'The NLO mode %s is not valid. Please chose one among: %s' \
258 % (nlo_mode, ' '.join(self._valid_nlo_modes)))
259 elif nlo_mode in ['all', 'real', 'LOonly']:
260 self._fks_multi_proc = fks_base.FKSMultiProcess()
261 self.change_principal_cmd('aMC@NLO')
262 elif nlo_mode == 'virt' or nlo_mode == 'virtsqr':
263 self.change_principal_cmd('MadLoop')
264 else:
265 self.change_principal_cmd('MadGraph')
266 return self.cmd.do_generate(self, line, *args, **opts)
267
269 self.cmd.do_import(self, *args, **opts)
270 if self._curr_model:
271 if isinstance(self._curr_model, loop_base_objects.LoopModel) and \
272 self._curr_model['perturbation_couplings']!=[] and \
273 self.current_interface not in ['aMC@NLO','MadLoop']:
274 self.change_principal_cmd('aMC@NLO')
275 if (not isinstance(self._curr_model, loop_base_objects.LoopModel) or \
276 self._curr_model['perturbation_couplings']==[]) and \
277 self.current_interface in ['MadLoop']:
278 self.change_principal_cmd('MadGraph')
279 import madgraph.various.misc as misc
280 return
281
283 """ treat output aloha in order to use always the one in MG5 """
284 if line.strip().startswith('aloha'):
285 MGcmd.MadGraphCmd.do_output(self, line, *args, **opts)
286 else:
287 self.cmd.do_output(self, line, *args, **opts)
288
290 if arg and arg[0] == 'aloha':
291 MGcmd.MadGraphCmd.check_output(self, arg, *args, **opts)
292 else:
293 self.cmd.check_output(self, arg, *args, **opts)
294
295
296
297
298 # Dummy functions, not triggering any switch of interfaces
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
437
441
444
447
450
453
456
459
462
464 args = cmd.Cmd.split_arg(line)
465 # check if a path is given
466 if len(args) >=1:
467 if os.path.isdir(args[0]):
468 path = os.path.realpath(args[0])
469 elif os.path.isdir(pjoin(MG5DIR,args[0])):
470 path = pjoin(MG5DIR,args[0])
471 elif MG4DIR and os.path.isdir(pjoin(MG4DIR,args[0])):
472 path = pjoin(MG4DIR,args[0])
473 else:
474 path=None
475 # if there is a path, find what output has been done
476 if path:
477 type = self.cmd.find_output_type(self, path)
478 if type in ['standalone', 'standalone_cpp', 'pythia8', 'madevent']:
479 self.change_principal_cmd('MadGraph')
480 elif type == 'aMC@NLO':
481 self.change_principal_cmd('aMC@NLO')
482 elif type == 'MadLoop':
483 self.change_principal_cmd('MadLoop')
484
485 return self.cmd.do_launch(self, line, *argss, **opts)
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
576
578
580
581 # define the interface
582 if main in self.interface_names.keys():
583 self.prompt= self.interface_names[main][0]+'>'
584 self.cmd= self.interface_names[main][1]
585 self.current_interface=main
586 else:
587 raise MadGraph5Error, 'Type of interface not valid: %s' % main
588 self.cmd.__init__(self, *args, **opt)
589 self.current_interface = main
590
594
596 """Not in help: Allow to switch to any given interface from command line """
597
598 args = cmd.Cmd.split_arg(line)
599 if len(args)==1 and args[0] in self.interface_names.keys():
600 self.change_principal_cmd(args[0])
601 else:
602 raise self.InvalidCmd("Invalid switch command or non existing interface %s."\
603 %args[0]+" Valid interfaces are %s"\
604 %','.join(interface_quick_name.keys()))
605
607 old_cmd=self.current_interface
608 if name in self.interface_names.keys():
609 self.prompt= self.interface_names[name][0]+'>'
610 self.cmd= self.interface_names[name][1]
611 self.current_interface=name
612 else:
613 raise MadGraph5Error, 'Type of interface not valid: %s' % name
614
615 if self.interface_names[old_cmd][0]!=self.interface_names[name][0]:
616 logger.info("Switching from interface %s to %s"\
617 %(self.interface_names[old_cmd][0],\
618 self.interface_names[name][0]))
619 # Setup the interface
620 self.cmd.setup(self)
621
622 if __debug__:
623 self.debug_link_to_command()
624
627
629
630 if os.environ.has_key('_CONDOR_SCRATCH_DIR'):
631 self.writing_dir = pjoin(os.environ['_CONDOR_SCRATCH_DIR'], \
632 os.path.pardir)
633 else:
634 self.writing_dir = pjoin(os.environ['MADGRAPH_DATA'],
635 os.environ['REMOTE_USER'])
636
637
638 #standard initialization
639 Switcher.__init__(self, mgme_dir = '', *arg, **opt)
640
641 self.options['timeout'] = 1 # time authorize to answer question [0 is no time limit]
642
644 if name == 'MadGraph':
645 self.cmd = MGcmd.MadGraphCmdWeb
646 elif name == 'Loop':
647 self.cmd = LoopCmd.LoopInterfaceWeb
648 else:
649 raise MadGraph5Error, 'Type of interface not valid'
650
651 if __debug__:
652 self.debug_link_to_command()
653
656
658 """Finalize web generation"""
659
660 if flaglist != []:
661 raise Exception
662 self.cmd.finalize(self, nojpeg, online = True)
663
665 """Finalize web generation"""
666
667 opts['online'] = True
668 self.cmd.finalize(self, nojpeg, opts)
669
670 # Generate a new amplitude
672 """Generate an amplitude for a given process"""
673
674 try:
675 Switcher.do_generate(self, line)
676 except:
677 # put the stop logo on the web
678 files.cp(self._export_dir+'/HTML/stop.jpg',self._export_dir+'/HTML/card.jpg')
679 raise
680
681 # Add a process to the existing multiprocess definition
683 """Generate an amplitude for a given process and add to
684 existing amplitudes
685 syntax:
686 """
687 try:
688 Switcher.do_add(self, line)
689 except:
690 # put the stop logo on the web
691 files.cp(self._export_dir+'/HTML/stop.jpg',self._export_dir+'/HTML/card.jpg')
692 raise
693
694 # Use the cluster file for the configuration
696
697 """Force to use the web configuration file only"""
698 config_path = pjoin(os.environ['MADGRAPH_BASE'], 'mg5_configuration.txt')
699 return Switcher.set_configuration(self, config_path=config_path, final=final)
700
702 """Save information to file"""
703
704 if check:
705 self.check_save([])
706 raise #useless but full security
707
708 args = self.split_arg(line)
709 if args[0] != 'options':
710 Switcher.do_save(self, line,check, opt)
711 else:
712 # put default options since
713 # in the web the local file is not used
714 # in download the default file is more usefull
715 files.cp(pjoin(MG5DIR,'input','mg5_configuration.txt'), args[1])
716
720
| Trees | Indices | Help |
|---|
| Generated by Epydoc 3.0.1 on Thu Aug 17 00:27:37 2017 | http://epydoc.sourceforge.net |