1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 """A File for splitting"""
16
17 from __future__ import division
18 import copy
19 import logging
20 import numbers
21 import os
22 import sys
23 import re
24 import math
25
26 pjoin = os.path.join
27
28 try:
29 import madgraph
30 except ImportError:
31 MADEVENT = True
32 from internal import MadGraph5Error, InvalidCmd
33 import internal.file_writers as file_writers
34 import internal.files as files
35 import internal.check_param_card as param_card_reader
36 import internal.misc as misc
37 MEDIR = os.path.split(os.path.dirname(os.path.realpath( __file__ )))[0]
38 MEDIR = os.path.split(MEDIR)[0]
39 else:
40 MADEVENT = False
41 import madgraph.various.misc as misc
42 import madgraph.iolibs.file_writers as file_writers
43 import madgraph.iolibs.files as files
44 import models.check_param_card as param_card_reader
45 from madgraph import MG5DIR, MadGraph5Error, InvalidCmd
46
47
48 logger = logging.getLogger('madevent.cards')
52 """ """
53
54 ordered_items = ['mgversion', 'mg5proccard', 'mgproccard', 'mgruncard',
55 'slha', 'mggenerationinfo', 'mgpythiacard', 'mgpgscard',
56 'mgdelphescard', 'mgdelphestrigger','mgshowercard','run_settings']
57
58 capitalized_items = {
59 'mgversion': 'MGVersion',
60 'mg5proccard': 'MG5ProcCard',
61 'mgproccard': 'MGProcCard',
62 'mgruncard': 'MGRunCard',
63 'mggenerationinfo': 'MGGenerationInfo',
64 'mgpythiacard': 'MGPythiaCard',
65 'mgpgscard': 'MGPGSCard',
66 'mgdelphescard': 'MGDelphesCard',
67 'mgdelphestrigger': 'MGDelphesTrigger',
68 'mgshowercard': 'MGShowerCard' }
69
71 """ """
72 if isinstance(banner_path, Banner):
73 dict.__init__(self, banner_path)
74 self.lhe_version = banner_path.lhe_version
75 return
76 else:
77 dict.__init__(self)
78
79
80 if MADEVENT:
81 self['mgversion'] = '#%s\n' % open(pjoin(MEDIR, 'MGMEVersion.txt')).read()
82 else:
83 info = misc.get_pkg_info()
84 self['mgversion'] = info['version']+'\n'
85
86 self.lhe_version = None
87
88
89 if banner_path:
90 self.read_banner(banner_path)
91
92
93
94
95 pat_begin=re.compile('<(?P<name>\w*)>')
96 pat_end=re.compile('</(?P<name>\w*)>')
97
98 tag_to_file={'slha':'param_card.dat',
99 'mgruncard':'run_card.dat',
100 'mgpythiacard':'pythia_card.dat',
101 'mgpgscard' : 'pgs_card.dat',
102 'mgdelphescard':'delphes_card.dat',
103 'mgdelphestrigger':'delphes_trigger.dat',
104 'mg5proccard':'proc_card_mg5.dat',
105 'mgproccard': 'proc_card.dat',
106 'init': '',
107 'mggenerationinfo':'',
108 'scalesfunctionalform':'',
109 'montecarlomasses':'',
110 'initrwgt':'',
111 'madspin':'madspin_card.dat',
112 'mgshowercard':'shower_card.dat',
113 'run_settings':''
114 }
115
117 """read a banner"""
118
119 if isinstance(input_path, str):
120 if input_path.find('\n') ==-1:
121 input_path = open(input_path)
122 else:
123 def split_iter(string):
124 return (x.groups(0)[0] for x in re.finditer(r"([^\n]*\n)", string, re.DOTALL))
125 input_path = split_iter(input_path)
126
127 text = ''
128 store = False
129 for line in input_path:
130 if self.pat_begin.search(line):
131 if self.pat_begin.search(line).group('name').lower() in self.tag_to_file:
132 tag = self.pat_begin.search(line).group('name').lower()
133 store = True
134 continue
135 if store and self.pat_end.search(line):
136 if tag == self.pat_end.search(line).group('name').lower():
137 self[tag] = text
138 text = ''
139 store = False
140 if store:
141 if line.endswith('\n'):
142 text += line
143 else:
144 text += '%s%s' % (line, '\n')
145
146
147 if "</init>" in line:
148 break
149 elif "<event>" in line:
150 break
151
153 """change the lhe version associate to the banner"""
154
155 version = float(version)
156 if version < 3:
157 version = 1
158 elif version > 3:
159 raise Exception, "Not Supported version"
160 self.lhe_version = version
161
163 """return the cross-section of the file"""
164
165 if "init" not in self:
166 misc.sprint(self.keys())
167 raise Exception
168
169 text = self["init"].split('\n')
170 cross = 0
171 for line in text:
172 s = line.split()
173 if len(s)==4:
174 cross += float(s[0])
175 return cross
176
177
178
180 """modify the init information with the associate cross-section"""
181
182 assert isinstance(cross, dict)
183
184 assert "init" in self
185
186 all_lines = self["init"].split('\n')
187 new_data = []
188 new_data.append(all_lines[0])
189 for i in range(1, len(all_lines)):
190 line = all_lines[i]
191 split = line.split()
192 if len(split) == 4:
193 xsec, xerr, xmax, pid = split
194 else:
195 new_data += all_lines[i:]
196 break
197 if int(pid) not in cross:
198 raise Exception
199 pid = int(pid)
200 ratio = cross[pid]/float(xsec)
201 line = " %+13.7e %+13.7e %+13.7e %i" % \
202 (float(cross[pid]), ratio* float(xerr), ratio*float(xmax), pid)
203 new_data.append(line)
204 self['init'] = '\n'.join(new_data)
205
207 """modify the init information with the associate scale"""
208
209 assert "init" in self
210
211 all_lines = self["init"].split('\n')
212 new_data = []
213 new_data.append(all_lines[0])
214 for i in range(1, len(all_lines)):
215 line = all_lines[i]
216 split = line.split()
217 if len(split) == 4:
218 xsec, xerr, xmax, pid = split
219 else:
220 new_data += all_lines[i:]
221 break
222 pid = int(pid)
223
224 line = " %+13.7e %+13.7e %+13.7e %i" % \
225 (ratio*float(xsec), ratio* float(xerr), ratio*float(xmax), pid)
226 new_data.append(line)
227 self['init'] = '\n'.join(new_data)
228
230 """ Load the proc_card /param_card and run_card """
231
232 self.add(pjoin(medir,'Cards', 'param_card.dat'))
233 self.add(pjoin(medir,'Cards', 'run_card.dat'))
234 if os.path.exists(pjoin(medir, 'SubProcesses', 'procdef_mg5.dat')):
235 self.add(pjoin(medir,'SubProcesses', 'procdef_mg5.dat'))
236 self.add(pjoin(medir,'Cards', 'proc_card_mg5.dat'))
237 else:
238 self.add(pjoin(medir,'Cards', 'proc_card.dat'))
239
240
242 """Change the seed value in the banner"""
243
244 p = re.compile(r'''^\s*\d+\s*=\s*iseed''', re.M)
245 new_seed_str = " %s = iseed" % seed
246 self['mgruncard'] = p.sub(new_seed_str, self['mgruncard'])
247
249 """add info on MGGeneration"""
250
251 text = """
252 # Number of Events : %s
253 # Integrated weight (pb) : %s
254 """ % (nb_event, cross)
255 self['MGGenerationInfo'] = text
256
257
258
259
260 - def split(self, me_dir, proc_card=True):
261 """write the banner in the Cards directory.
262 proc_card argument is present to avoid the overwrite of proc_card
263 information"""
264
265 for tag, text in self.items():
266 if tag == 'mgversion':
267 continue
268 if not proc_card and tag in ['mg5proccard','mgproccard']:
269 continue
270 if not self.tag_to_file[tag]:
271 continue
272 ff = open(pjoin(me_dir, 'Cards', self.tag_to_file[tag]), 'w')
273 ff.write(text)
274 ff.close()
275
276
277
278
279
281 """special routine removing width/mass of particles not present in the model
282 This is usefull in case of loop model card, when we want to use the non
283 loop model."""
284
285 if not hasattr(self, 'param_card'):
286 self.charge_card('slha')
287
288 for tag in ['mass', 'decay']:
289 block = self.param_card.get(tag)
290 for data in block:
291 pid = data.lhacode[0]
292 if pid not in pid2label.keys():
293 block.remove((pid,))
294
296 """get the lha_strategy: how the weight have to be handle by the shower"""
297
298 if not self["init"]:
299 raise Exception, "No init block define"
300
301 data = self["init"].split('\n')[0].split()
302 if len(data) != 10:
303 misc.sprint(len(data), self['init'])
304 raise Exception, "init block has a wrong format"
305 return int(float(data[-2]))
306
308 """set the lha_strategy: how the weight have to be handle by the shower"""
309
310 if not (-4 <= int(value) <= 4):
311 raise Exception, "wrong value for lha_strategy", value
312 if not self["init"]:
313 raise Exception, "No init block define"
314
315 all_lines = self["init"].split('\n')
316 data = all_lines[0].split()
317 if len(data) != 10:
318 misc.sprint(len(data), self['init'])
319 raise Exception, "init block has a wrong format"
320 data[-2] = '%s' % value
321 all_lines[0] = ' '.join(data)
322 self['init'] = '\n'.join(all_lines)
323
325 """modify the init information with the associate cross-section"""
326
327 assert isinstance(cross, dict)
328
329 assert "init" in self
330
331 all_lines = self["init"].split('\n')
332 new_data = []
333 new_data.append(all_lines[0])
334 for i in range(1, len(all_lines)):
335 line = all_lines[i]
336 split = line.split()
337 if len(split) == 4:
338 xsec, xerr, xmax, pid = split
339 else:
340 new_data += all_lines[i:]
341 break
342 if int(pid) not in cross:
343 raise Exception
344 pid = int(pid)
345 ratio = cross[pid]/float(xsec)
346 line = " %+13.7e %+13.7e %+13.7e %i" % \
347 (float(cross[pid]), ratio* float(xerr), ratio*float(xmax), pid)
348 new_data.append(line)
349 self['init'] = '\n'.join(new_data)
350
351
352
353
354 - def write(self, output_path, close_tag=True, exclude=[]):
355 """write the banner"""
356
357 if isinstance(output_path, str):
358 ff = open(output_path, 'w')
359 else:
360 ff = output_path
361
362 if MADEVENT:
363 header = open(pjoin(MEDIR, 'Source', 'banner_header.txt')).read()
364 else:
365 header = open(pjoin(MG5DIR,'Template', 'LO', 'Source', 'banner_header.txt')).read()
366
367 if not self.lhe_version:
368 self.lhe_version = self.get('run_card', 'lhe_version', default=1.0)
369 if float(self.lhe_version) < 3:
370 self.lhe_version = 1.0
371
372 ff.write(header % { 'version':float(self.lhe_version)})
373
374
375 for tag in [t for t in self.ordered_items if t in self.keys()]:
376 if tag in exclude:
377 continue
378 capitalized_tag = self.capitalized_items[tag] if tag in self.capitalized_items else tag
379 ff.write('<%(tag)s>\n%(text)s\n</%(tag)s>\n' % \
380 {'tag':capitalized_tag, 'text':self[tag].strip()})
381 for tag in [t for t in self.keys() if t not in self.ordered_items]:
382 if tag in ['init'] or tag in exclude:
383 continue
384 capitalized_tag = self.capitalized_items[tag] if tag in self.capitalized_items else tag
385 ff.write('<%(tag)s>\n%(text)s\n</%(tag)s>\n' % \
386 {'tag':capitalized_tag, 'text':self[tag].strip()})
387
388 if not '/header' in exclude:
389 ff.write('</header>\n')
390
391 if 'init' in self and not 'init' in exclude:
392 text = self['init']
393 ff.write('<%(tag)s>\n%(text)s\n</%(tag)s>\n' % \
394 {'tag':'init', 'text':text.strip()})
395 if close_tag:
396 ff.write('</LesHouchesEvents>\n')
397 return ff
398
399
400
401
402
403 - def add(self, path, tag=None):
404 """Add the content of the file to the banner"""
405
406 if not tag:
407 card_name = os.path.basename(path)
408 if 'param_card' in card_name:
409 tag = 'slha'
410 elif 'run_card' in card_name:
411 tag = 'MGRunCard'
412 elif 'pythia_card' in card_name:
413 tag = 'MGPythiaCard'
414 elif 'pgs_card' in card_name:
415 tag = 'MGPGSCard'
416 elif 'delphes_card' in card_name:
417 tag = 'MGDelphesCard'
418 elif 'delphes_trigger' in card_name:
419 tag = 'MGDelphesTrigger'
420 elif 'proc_card_mg5' in card_name:
421 tag = 'MG5ProcCard'
422 elif 'proc_card' in card_name:
423 tag = 'MGProcCard'
424 elif 'procdef_mg5' in card_name:
425 tag = 'MGProcCard'
426 elif 'shower_card' in card_name:
427 tag = 'MGShowerCard'
428 elif 'madspin_card' in card_name:
429 tag = 'madspin'
430 elif 'FO_analyse_card' in card_name:
431 tag = 'foanalyse'
432 elif 'reweight_card' in card_name:
433 tag='reweight_card'
434 else:
435 raise Exception, 'Impossible to know the type of the card'
436
437 self.add_text(tag.lower(), open(path).read())
438
439 - def add_text(self, tag, text):
440 """Add the content of the file to the banner"""
441
442 if tag == 'param_card':
443 tag = 'slha'
444 elif tag == 'run_card':
445 tag = 'mgruncard'
446 elif tag == 'proc_card':
447 tag = 'mg5proccard'
448 elif tag == 'shower_card':
449 tag = 'mgshowercard'
450 elif tag == 'FO_analyse_card':
451 tag = 'foanalyse'
452
453 self[tag.lower()] = text
454
455
505
506
508 """return a specific """
509
510 if tag in ['param_card', 'param']:
511 tag = 'slha'
512 attr_tag = 'param_card'
513 elif tag in ['run_card', 'run']:
514 tag = 'mgruncard'
515 attr_tag = 'run_card'
516 elif tag == 'proc_card':
517 tag = 'mg5proccard'
518 attr_tag = 'proc_card'
519 elif tag == 'model':
520 tag = 'mg5proccard'
521 attr_tag = 'proc_card'
522 arg = ('model',)
523 elif tag == 'generate':
524 tag = 'mg5proccard'
525 attr_tag = 'proc_card'
526 arg = ('generate',)
527 elif tag == 'shower_card':
528 tag = 'mgshowercard'
529 attr_tag = 'shower_card'
530 assert tag in ['slha', 'mgruncard', 'mg5proccard', 'shower_card'], '%s not recognized' % tag
531
532 if not hasattr(self, attr_tag):
533 self.charge_card(attr_tag)
534
535 card = getattr(self, attr_tag)
536 if len(arg) == 1:
537 if tag == 'mg5proccard':
538 try:
539 return card.get(arg[0])
540 except KeyError, error:
541 if 'default' in opt:
542 return opt['default']
543 else:
544 raise
545 try:
546 return card[arg[0]]
547 except KeyError:
548 if 'default' in opt:
549 return opt['default']
550 else:
551 raise
552 elif len(arg) == 2 and tag == 'slha':
553 try:
554 return card[arg[0]].get(arg[1:])
555 except KeyError:
556 if 'default' in opt:
557 return opt['default']
558 else:
559 raise
560 elif len(arg) == 0:
561 return card
562 else:
563 raise Exception, "Unknow command"
564
565
566 get = get_detail
567
568 - def set(self, card, *args):
569 """modify one of the cards"""
570
571 if tag == 'param_card':
572 tag = 'slha'
573 attr_tag = 'param_card'
574 elif tag == 'run_card':
575 tag = 'mgruncard'
576 attr_tag = 'run_card'
577 elif tag == 'proc_card':
578 tag = 'mg5proccard'
579 attr_tag = 'proc_card'
580 elif tag == 'model':
581 tag = 'mg5proccard'
582 attr_tag = 'proc_card'
583 arg = ('model',)
584 elif tag == 'generate':
585 tag = 'mg5proccard'
586 attr_tag = 'proc_card'
587 arg = ('generate',)
588 elif tag == 'shower_card':
589 tag = 'mgshowercard'
590 attr_tag = 'shower_card'
591 assert tag in ['slha', 'mgruncard', 'mg5proccard', 'shower_card'], 'not recognized'
592
593 if not hasattr(self, attr_tag):
594 self.charge_card(attr_tag)
595
596 card = getattr(self, attr_tag)
597 if len(args) ==2:
598 if tag == 'mg5proccard':
599 card.info[args[0]] = args[-1]
600 else:
601 card[args[0]] = args[1]
602 else:
603 card[args[:-1]] = args[-1]
604
605
606 @misc.multiple_try()
608 """Add the banner to a file and change the associate seed in the banner"""
609
610 if seed is not None:
611 self.set("run_card", "iseed", seed)
612
613 if not out:
614 path_out = "%s.tmp" % path
615 else:
616 path_out = out
617
618 ff = self.write(path_out, close_tag=False,
619 exclude=['MGGenerationInfo', '/header', 'init'])
620 ff.write("## END BANNER##\n")
621 if self.lhe_version >= 3:
622
623 [ff.write(line) if not line.startswith("<generator name='MadGraph5_aMC@NLO'")
624 else ff.write("<generator name='MadGraph5_aMC@NLO' version='%s'>" % self['mgversion'][:-1])
625 for line in open(path)]
626 else:
627 [ff.write(line) for line in open(path)]
628 ff.write("</LesHouchesEvents>\n")
629 ff.close()
630 if out:
631 os.remove(path)
632 else:
633 files.mv(path_out, path)
634
635
636
637 -def split_banner(banner_path, me_dir, proc_card=True):
642
644 """as input we receive a gen_crossxhtml.AllResults object.
645 This define the current banner and load it
646 """
647
648 if not run:
649 try:
650 _run = results_object.current['run_name']
651 _tag = results_object.current['tag']
652 except Exception:
653 return Banner()
654 else:
655 _run = run
656 if not tag:
657 try:
658 _tag = results_object[run].tags[-1]
659 except Exception,error:
660 return Banner()
661 else:
662 _tag = tag
663
664 path = results_object.path
665 banner_path = pjoin(path,'Events',run,'%s_%s_banner.txt' % (run, tag))
666
667 if not os.path.exists(banner_path):
668 if level != "parton" and tag != _tag:
669 return recover_banner(results_object, level, _run, results_object[_run].tags[0])
670
671 return Banner()
672 banner = Banner(banner_path)
673
674
675
676 if level == 'pythia':
677 if 'mgpythiacard' in banner:
678 del banner['mgpythiacard']
679 if level in ['pythia','pgs','delphes']:
680 for tag in ['mgpgscard', 'mgdelphescard', 'mgdelphestrigger']:
681 if tag in banner:
682 del banner[tag]
683 return banner
684
687
689 """Basic Proccard object"""
690
691 history_header = \
692 '#************************************************************\n' + \
693 '#* MadGraph5_aMC@NLO *\n' + \
694 '#* *\n' + \
695 "#* * * *\n" + \
696 "#* * * * * *\n" + \
697 "#* * * * * 5 * * * * *\n" + \
698 "#* * * * * *\n" + \
699 "#* * * *\n" + \
700 "#* *\n" + \
701 "#* *\n" + \
702 "%(info_line)s" +\
703 "#* *\n" + \
704 "#* The MadGraph5_aMC@NLO Development Team - Find us at *\n" + \
705 "#* https://server06.fynu.ucl.ac.be/projects/madgraph *\n" + \
706 '#* *\n' + \
707 '#************************************************************\n' + \
708 '#* *\n' + \
709 '#* Command File for MadGraph5_aMC@NLO *\n' + \
710 '#* *\n' + \
711 '#* run as ./bin/mg5_aMC filename *\n' + \
712 '#* *\n' + \
713 '#************************************************************\n'
714
715
716
717
719 """ initialize a basic proc_card"""
720 self.info = {'model': 'sm', 'generate':None,
721 'full_model_line':'import model sm'}
722 list.__init__(self)
723 if init:
724 self.read(init)
725
726
727 - def read(self, init):
728 """read the proc_card and save the information"""
729
730 if isinstance(init, str):
731 init = file(init, 'r')
732
733 store_line = ''
734 for line in init:
735 line = line.strip()
736 if line.endswith('\\'):
737 store_line += line[:-1]
738 else:
739 self.append(store_line + line)
740 store_line = ""
741 if store_line:
742 raise Exception, "WRONG CARD FORMAT"
744 """move an element to the last history."""
745 for line in self[:]:
746 if line.startswith(cmd):
747 self.remove(line)
748 list.append(self, line)
749
751 """"add a line in the proc_card perform automatically cleaning"""
752
753 line = line.strip()
754 cmds = line.split()
755 if len(cmds) == 0:
756 return
757
758 list.append(self, line)
759
760
761 cmd = cmds[0]
762
763 if cmd == 'output':
764
765 self.clean(allow_for_removal = ['output'], keep_switch=True,
766 remove_bef_last='output')
767 elif cmd == 'generate':
768
769 self.clean(remove_bef_last='generate', keep_switch=True,
770 allow_for_removal= ['generate', 'add process', 'output'])
771 self.info['generate'] = ' '.join(cmds[1:])
772 elif cmd == 'add' and cmds[1] == 'process' and not self.info['generate']:
773 self.info['generate'] = ' '.join(cmds[2:])
774 elif cmd == 'import':
775 if len(cmds) < 2:
776 return
777 if cmds[1].startswith('model'):
778 self.info['full_model_line'] = line
779 self.clean(remove_bef_last='import', keep_switch=True,
780 allow_for_removal=['generate', 'add process', 'add model', 'output'])
781 if cmds[1] == 'model':
782 self.info['model'] = cmds[2]
783 else:
784 self.info['model'] = None
785 elif cmds[1] == 'proc_v4':
786
787 self[:] = []
788
789
790 - def clean(self, to_keep=['set','add','load'],
791 remove_bef_last=None,
792 to_remove=['open','display','launch', 'check','history'],
793 allow_for_removal=None,
794 keep_switch=False):
795 """Remove command in arguments from history.
796 All command before the last occurrence of 'remove_bef_last'
797 (including it) will be removed (but if another options tells the opposite).
798 'to_keep' is a set of line to always keep.
799 'to_remove' is a set of line to always remove (don't care about remove_bef_
800 status but keep_switch acts.).
801 if 'allow_for_removal' is define only the command in that list can be
802 remove of the history for older command that remove_bef_lb1. all parameter
803 present in to_remove are always remove even if they are not part of this
804 list.
805 keep_switch force to keep the statement remove_bef_??? which changes starts
806 the removal mode.
807 """
808
809
810 if __debug__ and allow_for_removal:
811 for arg in to_keep:
812 assert arg not in allow_for_removal
813
814
815 nline = -1
816 removal = False
817
818 while nline > -len(self):
819 switch = False
820
821
822 if not removal and remove_bef_last:
823 if self[nline].startswith(remove_bef_last):
824 removal = True
825 switch = True
826
827
828 if switch and keep_switch:
829 nline -= 1
830 continue
831
832
833 if any([self[nline].startswith(arg) for arg in to_remove]):
834 self.pop(nline)
835 continue
836
837
838 if removal:
839 if allow_for_removal:
840
841 if any([self[nline].startswith(arg)
842 for arg in allow_for_removal]):
843 self.pop(nline)
844 continue
845 elif not any([self[nline].startswith(arg) for arg in to_keep]):
846
847 self.pop(nline)
848 continue
849
850
851 nline -= 1
852
853 - def get(self, tag, default=None):
854 if isinstance(tag, int):
855 list.__getattr__(self, tag)
856 elif tag == 'info' or tag == "__setstate__":
857 return default
858 elif tag == "multiparticles":
859 out = []
860 for line in self:
861 if line.startswith('define'):
862 name, content = line[7:].split('=',1)
863 out.append((name, content))
864 return out
865 else:
866 return self.info[tag]
867
869 """write the proc_card to a given path"""
870
871 fsock = open(path, 'w')
872 fsock.write(self.history_header)
873 for line in self:
874 while len(line) > 70:
875 sub, line = line[:70]+"\\" , line[70:]
876 fsock.write(sub+"\n")
877 else:
878 fsock.write(line+"\n")
879
882 """ a class for storing/dealing with input file.
883 """
884
886 """initialize a new instance. input can be an instance of MadLoopParam,
887 a file, a path to a file, or simply Nothing"""
888
889 if isinstance(finput, self.__class__):
890 dict.__init__(self, finput)
891 assert finput.__dict__.keys()
892 for key in finput.__dict__:
893 setattr(self, key, copy.copy(getattr(finput, key)) )
894 return
895 else:
896 dict.__init__(self)
897
898
899 self.user_set = set()
900 self.lower_to_case = {}
901 self.default_setup()
902
903
904
905
906 if isinstance(finput, (file, str)):
907 self.read(finput)
908
909
912
914 return self.__class__(self)
915
917 """define the sum"""
918 assert isinstance(other, dict)
919 base = self.__class__(self)
920
921 base.update((key.lower(),value) for key, value in other.items())
922 return base
923
925 """define the sum"""
926 new = copy.copy(other)
927 new.update((key, value) for key, value in self.items())
928 return new
929
932
936
939
943
944 - def __setitem__(self, name, value, change_userdefine=False):
945 """set the attribute and set correctly the type if the value is a string"""
946 if not len(self):
947
948 self.__init__()
949
950 name = name.strip()
951
952 if name in self:
953 lower_name = name.lower()
954 targettype = type(self[name])
955 else:
956 lower_name = name.lower()
957 logger.debug('Trying to add argument %s in %s. ' % (name, self.__class__.__name__) +\
958 'This argument is not defined by default. Please consider to add it.')
959 logger.debug("Did you mean %s", [k for k in self.keys() if k.startswith(name[0].lower())])
960 self.add_param(lower_name, self.format_variable(str(value), str, name))
961 self.lower_to_case[lower_name] = name
962 if change_userdefine:
963 self.user_set.add(lower_name)
964 return
965
966 value = self.format_variable(value, targettype, name=name)
967 dict.__setitem__(self, lower_name, value)
968 if change_userdefine:
969 self.user_set.add(lower_name)
970
972 """add a default parameter to the class"""
973
974 lower_name = name.lower()
975 if __debug__:
976 if lower_name in self:
977 raise Exception("Duplicate case for %s in %s" % (name,self.__class__))
978
979 dict.__setitem__(self, lower_name, value)
980 self.lower_to_case[lower_name] = name
981
982 @staticmethod
1051
1052
1053
1055
1056 if __debug__:
1057 if name.lower() not in self:
1058 if name.lower() in [key.lower() for key in self] :
1059 raise Exception, "Some key are not lower case %s. Invalid use of the class!"\
1060 % [key for key in self if key.lower() != key]
1061
1062 return dict.__getitem__(self, name.lower())
1063
1064
1065 - def set(self, name, value, ifnotdefault=True, user=False):
1066 """convenient way to change attribute.
1067 ifnotdefault=False means that the value is NOT change is the value is not on default.
1068 user=True, means that the value will be marked as modified by the user
1069 (potentially preventing future change to the value)
1070 """
1071
1072
1073 if not ifnotdefault:
1074 if name.lower() in self.user_set:
1075
1076 return
1077
1078 self.__setitem__(name, value, change_userdefine=user)
1079
1083 """A class to handle information which are passed from MadGraph to the madevent
1084 interface."""
1085
1087 """initialize the directory to the default value"""
1088
1089 self.add_param('loop_induced', False)
1090 self.add_param('has_isr', False)
1091 self.add_param('has_fsr', False)
1092 self.add_param('nb_channel', 0)
1093 self.add_param('nexternal', 0)
1094 self.add_param('ninitial', 0)
1095 self.add_param('grouped_matrix', True)
1096 self.add_param('has_loops', False)
1097
1098 - def read(self, finput):
1099 """Read the input file, this can be a path to a file,
1100 a file object, a str with the content of the file."""
1101
1102 if isinstance(finput, str):
1103 if "\n" in finput:
1104 finput = finput.split('\n')
1105 elif os.path.isfile(finput):
1106 finput = open(finput)
1107 else:
1108 raise Exception, "No such file %s" % finput
1109
1110 for line in finput:
1111 if '#' in line:
1112 line = line.split('#',1)[0]
1113 if not line:
1114 continue
1115
1116 if '=' in line:
1117 key, value = line.split('=',1)
1118 self[key.strip()] = value
1119
1120 - def write(self, outputpath):
1121 """write the file"""
1122
1123 template ="# Information about the process #\n"
1124 template +="#########################################\n"
1125
1126 fsock = open(outputpath, 'w')
1127 fsock.write(template)
1128
1129 for key, value in self.items():
1130 fsock.write(" %s = %s \n" % (key, value))
1131
1132 fsock.close()
1133
1138 """an object for the GridpackCard"""
1139
1141 """default value for the GridpackCard"""
1142
1143 self.add_param("GridRun", True)
1144 self.add_param("gevents", 2500)
1145 self.add_param("gseed", 1)
1146 self.add_param("ngran", -1)
1147
1148 - def read(self, finput):
1149 """Read the input file, this can be a path to a file,
1150 a file object, a str with the content of the file."""
1151
1152 if isinstance(finput, str):
1153 if "\n" in finput:
1154 finput = finput.split('\n')
1155 elif os.path.isfile(finput):
1156 finput = open(finput)
1157 else:
1158 raise Exception, "No such file %s" % finput
1159
1160 for line in finput:
1161 line = line.split('#')[0]
1162 line = line.split('!')[0]
1163 line = line.split('=',1)
1164 if len(line) != 2:
1165 continue
1166 self[line[1].strip()] = line[0].replace('\'','').strip()
1167
1168 - def write(self, output_file, template=None):
1169 """Write the run_card in output_file according to template
1170 (a path to a valid run_card)"""
1171
1172 if not template:
1173 if not MADEVENT:
1174 template = pjoin(MG5DIR, 'Template', 'LO', 'Cards',
1175 'grid_card_default.dat')
1176 else:
1177 template = pjoin(MEDIR, 'Cards', 'grid_card_default.dat')
1178
1179
1180 text = ""
1181 for line in file(template,'r'):
1182 nline = line.split('#')[0]
1183 nline = nline.split('!')[0]
1184 comment = line[len(nline):]
1185 nline = nline.split('=')
1186 if len(nline) != 2:
1187 text += line
1188 elif nline[1].strip() in self:
1189 text += ' %s\t= %s %s' % (self[nline[1].strip()],nline[1], comment)
1190 else:
1191 logger.info('Adding missing parameter %s to current run_card (with default value)' % nline[1].strip())
1192 text += line
1193
1194 fsock = open(output_file,'w')
1195 fsock.write(text)
1196 fsock.close()
1197
1199
1201 if cls is RunCard:
1202 if not finput:
1203 target_class = RunCardLO
1204 elif isinstance(finput, cls):
1205 target_class = finput.__class__
1206 elif isinstance(finput, str):
1207 if '\n' not in finput:
1208 finput = open(finput).read()
1209 if 'fixed_QES_scale' in finput:
1210 target_class = RunCardNLO
1211 else:
1212 target_class = RunCardLO
1213 else:
1214 return None
1215 return super(RunCard, cls).__new__(target_class, finput)
1216 else:
1217 return super(RunCard, cls).__new__(cls, finput)
1218
1220
1221
1222
1223
1224 self.hidden_param = []
1225
1226 self.not_in_include = []
1227
1228 self.fortran_name = {}
1229
1230 self.legacy_parameter = {}
1231
1232 self.cuts_parameter = []
1233
1234
1235 super(RunCard, self).__init__(*args, **opts)
1236
1237 - def add_param(self, name, value, fortran_name=None, include=True,
1238 hidden=False, legacy=False, cut=False):
1239 """ add a parameter to the card. value is the default value and
1240 defines the type (int/float/bool/str) of the input.
1241 fortran_name defines what is the associate name in the f77 code
1242 include defines if we have to put the value in the include file
1243 hidden defines if the parameter is expected to be define by the user.
1244 legacy:Parameter which is not used anymore (raise a warning if not default)
1245 cut: defines the list of cut parameter to allow to set them all to off.
1246 """
1247
1248 super(RunCard, self).add_param(name, value)
1249 name = name.lower()
1250 if fortran_name:
1251 self.fortran_name[name] = fortran_name
1252 if not include:
1253 self.not_in_include.append(name)
1254 if hidden:
1255 self.hidden_param.append(name)
1256 if legacy:
1257 self.legacy_parameter[name] = value
1258 if include:
1259 self.not_in_include.append(name)
1260 if cut:
1261 self.cuts_parameter.append(name)
1262
1263
1264
1265 - def read(self, finput):
1266 """Read the input file, this can be a path to a file,
1267 a file object, a str with the content of the file."""
1268
1269 if isinstance(finput, str):
1270 if "\n" in finput:
1271 finput = finput.split('\n')
1272 elif os.path.isfile(finput):
1273 finput = open(finput)
1274 else:
1275 raise Exception, "No such file %s" % finput
1276
1277 for line in finput:
1278 line = line.split('#')[0]
1279 line = line.split('!')[0]
1280 line = line.split('=',1)
1281 if len(line) != 2:
1282 continue
1283 value, name = line
1284 name = name.lower().strip()
1285 if name not in self and ('min' in name or 'max' in name):
1286
1287 self.add_param(name, float(value), hidden=True, cut=True)
1288 else:
1289 self.set( name, value, user=True)
1290
1291 - def write(self, output_file, template=None, python_template=False):
1292 """Write the run_card in output_file according to template
1293 (a path to a valid run_card)"""
1294
1295 to_write = set(self.user_set)
1296 if not template:
1297 raise Exception
1298
1299 if python_template and not to_write:
1300 text = file(template,'r').read() % self
1301 else:
1302 text = ""
1303 for line in file(template,'r'):
1304 nline = line.split('#')[0]
1305 nline = nline.split('!')[0]
1306 comment = line[len(nline):]
1307 nline = nline.split('=')
1308 if len(nline) != 2:
1309 text += line
1310 elif nline[1].strip() in self:
1311 if python_template:
1312 text += line % {nline[1].strip().lower(): self[nline[1].strip()]}
1313 else:
1314 text += ' %s\t= %s %s' % (self[nline[1].strip()],nline[1], comment)
1315 if nline[1].strip().lower() in to_write:
1316 to_write.remove(nline[1].strip().lower())
1317 else:
1318 logger.info('Adding missing parameter %s to current run_card (with default value)' % nline[1].strip())
1319 text += line
1320
1321 if to_write:
1322 text+="""#*********************************************************************
1323 # Additional parameter
1324 #*********************************************************************
1325 """
1326
1327 for key in to_write:
1328 text += ' %s\t= %s # %s\n' % (self[key], key, 'hidden parameter')
1329
1330 if isinstance(output_file, str):
1331 fsock = open(output_file,'w')
1332 fsock.write(text)
1333 fsock.close()
1334 else:
1335 output_file.write(text)
1336
1337
1338 - def get_default(self, name, default=None, log_level=None):
1339 """return self[name] if exist otherwise default. log control if we
1340 put a warning or not if we use the default value"""
1341
1342 if name not in self.user_set:
1343 if log_level is None:
1344 if name.lower() in self.hidden_param:
1345 log_level = 10
1346 else:
1347 log_level = 20
1348 if not default:
1349 default = self[name]
1350 logger.log(log_level, 'run_card missed argument %s. Takes default: %s'
1351 % (name, default))
1352 self[name] = default
1353 return default
1354 else:
1355 return self[name]
1356
1357 @staticmethod
1363
1364 @staticmethod
1406
1407
1408
1432
1433
1451
1452 def get_pdf_id(pdf):
1453 if pdf == "lhapdf":
1454 return self["lhaid"]
1455 else:
1456 return {'none': 0, 'mrs02nl':20250, 'mrs02nn':20270, 'cteq4_m': 19150,
1457 'cteq4_l':19170, 'cteq4_d':19160, 'cteq5_m':19050,
1458 'cteq5_d':19060,'cteq5_l':19070,'cteq5m1':19051,
1459 'cteq6_m':10000,'cteq6_l':10041,'cteq6l1':10042,
1460 'nn23lo':246800,'nn23lo1':247000,'nn23nlo':244600
1461 }[pdf]
1462
1463 output["idbmup1"] = get_idbmup(self['lpp1'])
1464 output["idbmup2"] = get_idbmup(self['lpp2'])
1465 output["ebmup1"] = self["ebeam1"]
1466 output["ebmup2"] = self["ebeam2"]
1467 output["pdfgup1"] = 0
1468 output["pdfgup2"] = 0
1469 output["pdfsup1"] = get_pdf_id(self["pdlabel"])
1470 output["pdfsup2"] = get_pdf_id(self["pdlabel"])
1471 return output
1472
1474 """remove all the cut"""
1475
1476 for name in self.cuts_parameter:
1477 targettype = type(self[name])
1478 if targettype == bool:
1479 self[name] = False
1480 elif 'min' in name:
1481 self[name] = 0
1482 elif 'max' in name:
1483 self[name] = -1
1484 elif 'eta' in name:
1485 self[name] = -1
1486 else:
1487 self[name] = 0
1488
1490 """an object to handle in a nice way the run_card infomration"""
1491
1493 """default value for the run_card.dat"""
1494
1495 self.add_param("run_tag", "tag_1", include=False)
1496 self.add_param("gridpack", False)
1497 self.add_param("time_of_flight", -1.0, include=False, hidden=True)
1498 self.add_param("nevents", 10000)
1499 self.add_param("iseed", 0)
1500 self.add_param("lpp1", 1, fortran_name="lpp(1)")
1501 self.add_param("lpp2", 1, fortran_name="lpp(2)")
1502 self.add_param("ebeam1", 6500.0, fortran_name="ebeam(1)")
1503 self.add_param("ebeam2", 6500.0, fortran_name="ebeam(2)")
1504 self.add_param("polbeam1", 0.0, fortran_name="pb1")
1505 self.add_param("polbeam2", 0.0, fortran_name="pb2")
1506 self.add_param("pdlabel", "nn23lo1")
1507 self.add_param("lhaid", 230000, hidden=True)
1508 self.add_param("fixed_ren_scale", False)
1509 self.add_param("fixed_fac_scale", False)
1510 self.add_param("scale", 91.1880)
1511 self.add_param("dsqrt_q2fact1", 91.1880, fortran_name="sf1")
1512 self.add_param("dsqrt_q2fact2", 91.1880, fortran_name="sf2")
1513 self.add_param("dynamical_scale_choice", -1)
1514
1515
1516 self.add_param("scalefact", 1.0)
1517 self.add_param("ickkw", 0)
1518 self.add_param("highestmult", 1, fortran_name="nhmult")
1519 self.add_param("ktscheme", 1)
1520 self.add_param("alpsfact", 1.0)
1521 self.add_param("chcluster", False)
1522 self.add_param("pdfwgt", True)
1523 self.add_param("asrwgtflavor", 5)
1524 self.add_param("clusinfo", True)
1525 self.add_param("lhe_version", 3.0)
1526
1527 self.add_param("auto_ptj_mjj", True)
1528 self.add_param("bwcutoff", 15.0)
1529 self.add_param("cut_decays", False)
1530 self.add_param("nhel", 0, include=False)
1531
1532 self.add_param("ptj", 20.0, cut=True)
1533 self.add_param("ptb", 0.0, cut=True)
1534 self.add_param("pta", 10.0, cut=True)
1535 self.add_param("ptl", 10.0, cut=True)
1536 self.add_param("misset", 0.0, cut=True)
1537 self.add_param("ptheavy", 0.0, cut=True)
1538 self.add_param("ptonium", 1.0, legacy=True)
1539 self.add_param("ptjmax", -1.0, cut=True)
1540 self.add_param("ptbmax", -1.0, cut=True)
1541 self.add_param("ptamax", -1.0, cut=True)
1542 self.add_param("ptlmax", -1.0, cut=True)
1543 self.add_param("missetmax", -1.0, cut=True)
1544
1545 self.add_param("ej", 0.0, cut=True)
1546 self.add_param("eb", 0.0, cut=True)
1547 self.add_param("ea", 0.0, cut=True)
1548 self.add_param("el", 0.0, cut=True)
1549 self.add_param("ejmax", -1.0, cut=True)
1550 self.add_param("ebmax", -1.0, cut=True)
1551 self.add_param("eamax", -1.0, cut=True)
1552 self.add_param("elmax", -1.0, cut=True)
1553
1554 self.add_param("etaj", 5.0, cut=True)
1555 self.add_param("etab", -1.0, cut=True)
1556 self.add_param("etaa", 2.5, cut=True)
1557 self.add_param("etal", 2.5, cut=True)
1558 self.add_param("etaonium", 0.6, legacy=True)
1559 self.add_param("etajmin", 0.0, cut=True)
1560 self.add_param("etabmin", 0.0, cut=True)
1561 self.add_param("etaamin", 0.0, cut=True)
1562 self.add_param("etalmin", 0.0, cut=True)
1563
1564 self.add_param("drjj", 0.4, cut=True)
1565 self.add_param("drbb", 0.0, cut=True)
1566 self.add_param("drll", 0.4, cut=True)
1567 self.add_param("draa", 0.4, cut=True)
1568 self.add_param("drbj", 0.0, cut=True)
1569 self.add_param("draj", 0.4, cut=True)
1570 self.add_param("drjl", 0.4, cut=True)
1571 self.add_param("drab", 0.0, cut=True)
1572 self.add_param("drbl", 0.0, cut=True)
1573 self.add_param("dral", 0.4, cut=True)
1574 self.add_param("drjjmax", -1.0, cut=True)
1575 self.add_param("drbbmax", -1.0, cut=True)
1576 self.add_param("drllmax", -1.0, cut=True)
1577 self.add_param("draamax", -1.0, cut=True)
1578 self.add_param("drbjmax", -1.0, cut=True)
1579 self.add_param("drajmax", -1.0, cut=True)
1580 self.add_param("drjlmax", -1.0, cut=True)
1581 self.add_param("drabmax", -1.0, cut=True)
1582 self.add_param("drblmax", -1.0, cut=True)
1583 self.add_param("dralmax", -1.0, cut=True)
1584
1585 self.add_param("mmjj", 0.0, cut=True)
1586 self.add_param("mmbb", 0.0, cut=True)
1587 self.add_param("mmaa", 0.0, cut=True)
1588 self.add_param("mmll", 0.0, cut=True)
1589 self.add_param("mmjjmax", -1.0, cut=True)
1590 self.add_param("mmbbmax", -1.0, cut=True)
1591 self.add_param("mmaamax", -1.0, cut=True)
1592 self.add_param("mmllmax", -1.0, cut=True)
1593 self.add_param("mmnl", 0.0, cut=True)
1594 self.add_param("mmnlmax", -1.0, cut=True)
1595
1596 self.add_param("ptllmin", 0.0, cut=True)
1597 self.add_param("ptllmax", -1.0, cut=True)
1598 self.add_param("xptj", 0.0, cut=True)
1599 self.add_param("xptb", 0.0, cut=True)
1600 self.add_param("xpta", 0.0, cut=True)
1601 self.add_param("xptl", 0.0, cut=True)
1602
1603 self.add_param("ptj1min", 0.0, cut=True)
1604 self.add_param("ptj1max", -1.0, cut=True)
1605 self.add_param("ptj2min", 0.0, cut=True)
1606 self.add_param("ptj2max", -1.0, cut=True)
1607 self.add_param("ptj3min", 0.0, cut=True)
1608 self.add_param("ptj3max", -1.0, cut=True)
1609 self.add_param("ptj4min", 0.0, cut=True)
1610 self.add_param("ptj4max", -1.0, cut=True)
1611 self.add_param("cutuse", 0, cut=True)
1612
1613 self.add_param("ptl1min", 0.0, cut=True)
1614 self.add_param("ptl1max", -1.0, cut=True)
1615 self.add_param("ptl2min", 0.0, cut=True)
1616 self.add_param("ptl2max", -1.0, cut=True)
1617 self.add_param("ptl3min", 0.0, cut=True)
1618 self.add_param("ptl3max", -1.0, cut=True)
1619 self.add_param("ptl4min", 0.0, cut=True)
1620 self.add_param("ptl4max", -1.0, cut=True)
1621
1622 self.add_param("htjmin", 0.0, cut=True)
1623 self.add_param("htjmax", -1.0, cut=True)
1624 self.add_param("ihtmin", 0.0, cut=True)
1625 self.add_param("ihtmax", -1.0, cut=True)
1626 self.add_param("ht2min", 0.0, cut=True)
1627 self.add_param("ht3min", 0.0, cut=True)
1628 self.add_param("ht4min", 0.0, cut=True)
1629 self.add_param("ht2max", -1.0, cut=True)
1630 self.add_param("ht3max", -1.0, cut=True)
1631 self.add_param("ht4max", -1.0, cut=True)
1632
1633 self.add_param("ptgmin", 0.0, cut=True)
1634 self.add_param("r0gamma", 0.4)
1635 self.add_param("xn", 1.0)
1636 self.add_param("epsgamma", 1.0)
1637 self.add_param("isoem", True)
1638 self.add_param("xetamin", 0.0, cut=True)
1639 self.add_param("deltaeta", 0.0, cut=True)
1640 self.add_param("ktdurham", -1.0, fortran_name="kt_durham", cut=True)
1641 self.add_param("dparameter", 0.4, fortran_name="d_parameter", cut=True)
1642 self.add_param("maxjetflavor", 4)
1643 self.add_param("xqcut", 0.0, cut=True)
1644 self.add_param("use_syst", True)
1645 self.add_param("sys_scalefact", "0.5 1 2", include=False)
1646 self.add_param("sys_alpsfact", "None", include=False)
1647 self.add_param("sys_matchscale", "30 50", include=False)
1648 self.add_param("sys_pdf", "Ct10nlo.LHgrid", include=False)
1649 self.add_param("sys_scalecorrelation", -1, include=False)
1650
1651
1652 self.add_param('gridrun', False, hidden=True)
1653 self.add_param('fixed_couplings', True, hidden=True)
1654 self.add_param('mc_grouped_subproc', True, hidden=True)
1655 self.add_param('xmtcentral', 0.0, hidden=True, fortran_name="xmtc")
1656 self.add_param('d', 1.0, hidden=True)
1657 self.add_param('gseed', 0, hidden=True, include=False)
1658 self.add_param('issgridfile', '', hidden=True)
1659
1660 self.add_param('job_strategy', 0, hidden=True, include=False)
1661 self.add_param('survey_splitting', -1, hidden=True, include=False)
1662 self.add_param('refine_evt_by_job', -1, hidden=True, include=False)
1663
1664
1665
1666
1668 """ """
1669
1670
1671
1672 if 'nhel' not in self.user_set:
1673 raise InvalidRunCard, "Parameter nhel is not defined in the run_card."
1674 if self['nhel'] not in [1,0]:
1675 raise InvalidRunCard, "Parameter nhel can only be '0' or '1', "+\
1676 "not %s." % self['nhel']
1677 if int(self['maxjetflavor']) > 6:
1678 raise InvalidRunCard, 'maxjetflavor should be lower than 5! (6 is partly supported)'
1679
1680
1681 if self['ptgmin'] > 0:
1682 if self['pta'] > 0:
1683 logger.warning('pta cut discarded since photon isolation is used')
1684 self['pta'] = 0.0
1685 if self['draj'] > 0:
1686 logger.warning('draj cut discarded since photon isolation is used')
1687 self['draj'] = 0.0
1688
1689
1690 if self['gridrun']:
1691 self['iseed'] = self['gseed']
1692
1693
1694 if self['use_syst']:
1695 if self['scalefact'] != 1.0:
1696 logger.warning('Since use_syst=T, We change the value of \'scalefact\' to 1')
1697 self['scalefact'] = 1.0
1698
1699
1700 if self['ickkw'] > 0:
1701 if self['use_syst']:
1702
1703 if self['alpsfact'] != 1.0:
1704 logger.warning('Since use_syst=T, We change the value of \'alpsfact\' to 1')
1705 self['alpsfact'] =1.0
1706 if self['maxjetflavor'] == 6:
1707 raise InvalidRunCard, 'maxjetflavor at 6 is NOT supported for matching!'
1708 if self['ickkw'] == 2:
1709
1710 self.get_default('highestmult', log_level=20)
1711 self.get_default('issgridfile', 'issudgrid.dat', log_level=20)
1712 if self['xqcut'] > 0:
1713 if self['drjj'] != 0:
1714 logger.warning('Since icckw>0, We change the value of \'drjj\' to 0')
1715 self['drjj'] = 0
1716 if self['drjl'] != 0:
1717 logger.warning('Since icckw>0, We change the value of \'drjl\' to 0')
1718 self['drjl'] = 0
1719 if not self['auto_ptj_mjj']:
1720 if self['mmjj'] > self['xqcut']:
1721 logger.warning('mmjj > xqcut (and auto_ptj_mjj = F). MMJJ set to 0')
1722 self['mmjj'] = 0.0
1723
1724
1725
1726 possible_set = ['lhapdf','mrs02nl','mrs02nn', 'mrs0119','mrs0117','mrs0121','mrs01_j', 'mrs99_1','mrs99_2','mrs99_3','mrs99_4','mrs99_5','mrs99_6', 'mrs99_7','mrs99_8','mrs99_9','mrs9910','mrs9911','mrs9912', 'mrs98z1','mrs98z2','mrs98z3','mrs98z4','mrs98z5','mrs98ht', 'mrs98l1','mrs98l2','mrs98l3','mrs98l4','mrs98l5', 'cteq3_m','cteq3_l','cteq3_d', 'cteq4_m','cteq4_d','cteq4_l','cteq4a1','cteq4a2', 'cteq4a3','cteq4a4','cteq4a5','cteq4hj','cteq4lq', 'cteq5_m','cteq5_d','cteq5_l','cteq5hj','cteq5hq', 'cteq5f3','cteq5f4','cteq5m1','ctq5hq1','cteq5l1', 'cteq6_m','cteq6_d','cteq6_l','cteq6l1', 'nn23lo','nn23lo1','nn23nlo']
1727 if self['pdlabel'] not in possible_set:
1728 raise InvalidRunCard, 'Invalid PDF set (argument of pdlabel): %s. Possible choice are:\n %s' % (self['pdlabel'], ', '.join(possible_set))
1729 if self['pdlabel'] == 'lhapdf':
1730
1731 self.get_default('lhaid', log_level=20)
1732
1733 for name in self.legacy_parameter:
1734 if self[name] != self.legacy_parameter[name]:
1735 logger.warning("The parameter %s is not supported anymore this parameter will be ignored." % name)
1736
1737
1738
1739
1741 """Rules
1742 process 1->N all cut set on off.
1743 loop_induced -> MC over helicity
1744 e+ e- beam -> lpp:0 ebeam:500
1745 p p beam -> set maxjetflavor automatically
1746 more than one multiplicity: ickkw=1 xqcut=30 use_syst=F
1747 """
1748
1749 if proc_characteristic['loop_induced']:
1750 self['nhel'] = 1
1751
1752 if proc_characteristic['ninitial'] == 1:
1753
1754 self.remove_all_cut()
1755 else:
1756
1757 beam_id = set()
1758 for proc in proc_def:
1759 for oneproc in proc:
1760 for leg in oneproc['legs']:
1761 if not leg['state']:
1762 beam_id.add(leg['id'])
1763 if any(i in beam_id for i in [1,-1,2,-2,3,-3,4,-4,5,-5,21,22]):
1764 maxjetflavor = max([4]+[abs(i) for i in beam_id if -7< i < 7])
1765 self['maxjetflavor'] = maxjetflavor
1766 self['asrwgtflavor'] = maxjetflavor
1767 pass
1768 elif 11 in beam_id or -11 in beam_id:
1769 self['lpp1'] = 0
1770 self['lpp2'] = 0
1771 self['ebeam1'] = 500
1772 self['ebeam2'] = 500
1773 else:
1774 self['lpp1'] = 0
1775 self['lpp2'] = 0
1776
1777
1778 min_particle = 99
1779 max_particle = 0
1780 for proc in proc_def:
1781 min_particle = min(len(proc[0]['legs']), min_particle)
1782 max_particle = max(len(proc[0]['legs']), max_particle)
1783 if min_particle != max_particle:
1784
1785 for procmin in proc_def:
1786 if len(procmin[0]['legs']) != min_particle:
1787 continue
1788 else:
1789 idsmin = [l['id'] for l in procmin[0]['legs']]
1790 break
1791 matching = False
1792 for procmax in proc_def:
1793 if len(procmax[0]['legs']) != max_particle:
1794 continue
1795 idsmax = [l['id'] for l in procmax[0]['legs']]
1796 for i in idsmin:
1797 if i not in idsmax:
1798 continue
1799 else:
1800 idsmax.remove(i)
1801 for j in idsmax:
1802 if j not in [1,-1,2,-2,3,-3,4,-4,5,-5,21]:
1803 break
1804 else:
1805
1806 matching=True
1807 break
1808
1809 if matching:
1810 self['ickkw'] = 1
1811 self['xqcut'] = 30
1812 self['use_syst'] = False
1813 self['drjj'] = 0
1814 self['drjl'] = 0
1815 self['sys_alpsfact'] = "0.5 1 2"
1816
1817
1818 - def write(self, output_file, template=None, python_template=False):
1819 """Write the run_card in output_file according to template
1820 (a path to a valid run_card)"""
1821
1822 if not template:
1823 if not MADEVENT:
1824 template = pjoin(MG5DIR, 'Template', 'LO', 'Cards',
1825 'run_card.dat')
1826 python_template = True
1827 else:
1828 template = pjoin(MEDIR, 'Cards', 'run_card_default.dat')
1829 python_template = False
1830
1831 super(RunCardLO, self).write(output_file, template=template,
1832 python_template=python_template)
1833
1836 """A class object for the run_card for a (aMC@)NLO pocess"""
1837
1838
1840 """define the default value"""
1841
1842 self.add_param('run_tag', 'tag_1', include=False)
1843 self.add_param('nevents', 10000)
1844 self.add_param('req_acc', -1.0, include=False)
1845 self.add_param('nevt_job', -1, include=False)
1846 self.add_param('event_norm', 'average')
1847
1848 self.add_param('req_acc_fo', 0.01, include=False)
1849 self.add_param('npoints_fo_grid', 5000, include=False)
1850 self.add_param('niters_fo_grid', 4, include=False)
1851 self.add_param('npoints_fo', 10000, include=False)
1852 self.add_param('niters_fo', 6, include=False)
1853
1854 self.add_param('iseed', 0)
1855 self.add_param('lpp1', 1, fortran_name='lpp(1)')
1856 self.add_param('lpp2', 1, fortran_name='lpp(2)')
1857 self.add_param('ebeam1', 6500.0, fortran_name='ebeam(1)')
1858 self.add_param('ebeam2', 6500.0, fortran_name='ebeam(2)')
1859 self.add_param('pdlabel', 'nn23nlo')
1860 self.add_param('lhaid', 244600)
1861
1862 self.add_param('parton_shower', 'HERWIG6', fortran_name='shower_mc')
1863 self.add_param('shower_scale_factor',1.0)
1864 self.add_param('fixed_ren_scale', False)
1865 self.add_param('fixed_fac_scale', False)
1866 self.add_param('mur_ref_fixed', 91.118)
1867 self.add_param('muf1_ref_fixed', 91.118)
1868 self.add_param('muf2_ref_fixed', 91.118)
1869 self.add_param("dynamical_scale_choice", -1)
1870 self.add_param('fixed_qes_scale', False)
1871 self.add_param('qes_ref_fixed', 91.118)
1872 self.add_param('mur_over_ref', 1.0)
1873 self.add_param('muf1_over_ref', 1.0)
1874 self.add_param('muf2_over_ref', 1.0)
1875 self.add_param('qes_over_ref', 1.0)
1876 self.add_param('reweight_scale', True, fortran_name='do_rwgt_scale')
1877 self.add_param('rw_rscale_down', 0.5)
1878 self.add_param('rw_rscale_up', 2.0)
1879 self.add_param('rw_fscale_down', 0.5)
1880 self.add_param('rw_fscale_up', 2.0)
1881 self.add_param('reweight_pdf', False, fortran_name='do_rwgt_pdf')
1882 self.add_param('pdf_set_min', 244601)
1883 self.add_param('pdf_set_max', 244700)
1884
1885 self.add_param('ickkw', 0)
1886 self.add_param('bwcutoff', 15.0)
1887
1888 self.add_param('jetalgo', 1.0)
1889 self.add_param('jetradius', 0.7, hidden=True)
1890 self.add_param('ptj', 10.0 , cut=True)
1891 self.add_param('etaj', -1.0, cut=True)
1892 self.add_param('ptl', 0.0, cut=True)
1893 self.add_param('etal', -1.0, cut=True)
1894 self.add_param('drll', 0.0, cut=True)
1895 self.add_param('drll_sf', 0.0, cut=True)
1896 self.add_param('mll', 0.0, cut=True)
1897 self.add_param('mll_sf', 30.0, cut=True)
1898 self.add_param('ptgmin', 20.0, cut=True)
1899 self.add_param('etagamma', -1.0)
1900 self.add_param('r0gamma', 0.4)
1901 self.add_param('xn', 1.0)
1902 self.add_param('epsgamma', 1.0)
1903 self.add_param('isoem', True)
1904 self.add_param('maxjetflavor', 4)
1905 self.add_param('iappl', 0)
1906
1907 self.add_param('lhe_version', 3, hidden=True, include=False)
1908
1910 """check the validity of the various input"""
1911
1912
1913 if self['ickkw'] == 3:
1914
1915 scales=['fixed_ren_scale','fixed_fac_scale','fixed_QES_scale']
1916 for scale in scales:
1917 if self[scale]:
1918 logger.warning('''For consistency in the FxFx merging, \'%s\' has been set to false'''
1919 % scale,'$MG:color:BLACK')
1920 self[scale]= False
1921
1922 if self["dynamical_scale_choice"] != -1:
1923 self["dynamical_scale_choice"] = -1
1924 logger.warning('''For consistency in the FxFx merging, dynamical_scale_choice has been set to -1 (default)'''
1925 ,'$MG:color:BLACK')
1926
1927
1928
1929 jetparams=['jetradius','jetalgo']
1930 for jetparam in jetparams:
1931 if float(self[jetparam]) != 1.0:
1932 logger.info('''For consistency in the FxFx merging, \'%s\' has been set to 1.0'''
1933 % jetparam ,'$MG:color:BLACK')
1934 self[jetparam] = 1.0
1935 elif self['ickkw'] == -1 and self["dynamical_scale_choice"] != -1:
1936 self["dynamical_scale_choice"] = -1
1937 self["dynamical_scale_choice"] = -1
1938 logger.warning('''For consistency with the jet veto, the scale which will be used is ptj. dynamical_scale_choice will be set at -1.'''
1939 ,'$MG:color:BLACK')
1940
1941
1942
1943 if self['iappl'] != 0 and self['pdlabel'].lower() != 'lhapdf':
1944 raise InvalidRunCard('APPLgrid generation only possible with the use of LHAPDF')
1945 if self['iappl'] != 0 and not self['reweight_scale']:
1946 raise InvalidRunCard('APPLgrid generation only possible with including' +\
1947 ' the reweighting to get scale dependence')
1948
1949
1950 possible_set = ['lhapdf','mrs02nl','mrs02nn', 'mrs0119','mrs0117','mrs0121','mrs01_j', 'mrs99_1','mrs99_2','mrs99_3','mrs99_4','mrs99_5','mrs99_6', 'mrs99_7','mrs99_8','mrs99_9','mrs9910','mrs9911','mrs9912', 'mrs98z1','mrs98z2','mrs98z3','mrs98z4','mrs98z5','mrs98ht', 'mrs98l1','mrs98l2','mrs98l3','mrs98l4','mrs98l5', 'cteq3_m','cteq3_l','cteq3_d', 'cteq4_m','cteq4_d','cteq4_l','cteq4a1','cteq4a2', 'cteq4a3','cteq4a4','cteq4a5','cteq4hj','cteq4lq', 'cteq5_m','cteq5_d','cteq5_l','cteq5hj','cteq5hq', 'cteq5f3','cteq5f4','cteq5m1','ctq5hq1','cteq5l1', 'cteq6_m','cteq6_d','cteq6_l','cteq6l1', 'nn23lo','nn23lo1','nn23nlo']
1951 if self['pdlabel'] not in possible_set:
1952 raise InvalidRunCard, 'Invalid PDF set (argument of pdlabel) possible choice are:\n %s' % ','.join(possible_set)
1953
1954
1955
1956 if self['reweight_pdf']:
1957
1958 if self['pdlabel'] != "lhapdf":
1959 raise InvalidRunCard, 'Reweight PDF option requires to use pdf sets associated to lhapdf. Please either change the pdlabel or set reweight_pdf to False.'
1960
1961
1962 if (self['pdf_set_max'] - self['pdf_set_min'] + 1) % 2:
1963 raise InvalidRunCard, "The number of PDF error sets must be even"
1964
1965
1966 - def write(self, output_file, template=None, python_template=False):
1967 """Write the run_card in output_file according to template
1968 (a path to a valid run_card)"""
1969
1970 if not template:
1971 if not MADEVENT:
1972 template = pjoin(MG5DIR, 'Template', 'NLO', 'Cards',
1973 'run_card.dat')
1974 python_template = True
1975 else:
1976 template = pjoin(MEDIR, 'Cards', 'run_card_default.dat')
1977 python_template = False
1978
1979 super(RunCardNLO, self).write(output_file, template=template,
1980 python_template=python_template)
1981
1982
1984 """Rules
1985 e+ e- beam -> lpp:0 ebeam:500
1986 p p beam -> set maxjetflavor automatically
1987 """
1988
1989
1990 beam_id = set()
1991 for proc in proc_def:
1992 for leg in proc[0]['legs']:
1993 if not leg['state']:
1994 beam_id.add(leg['id'])
1995 if any(i in beam_id for i in [1,-1,2,-2,3,-3,4,-4,5,-5,21,22]):
1996 maxjetflavor = max([4]+[abs(i) for i in beam_id if -7< i < 7])
1997 self['maxjetflavor'] = maxjetflavor
1998 pass
1999 elif 11 in beam_id or -11 in beam_id:
2000 self['lpp1'] = 0
2001 self['lpp2'] = 0
2002 self['ebeam1'] = 500
2003 self['ebeam2'] = 500
2004 else:
2005 self['lpp1'] = 0
2006 self['lpp2'] = 0
2007
2008 if proc_characteristic['ninitial'] == 1:
2009
2010 self.remove_all_cut()
2011
2013 """ a class for storing/dealing with the file MadLoopParam.dat
2014 contains a parser to read it, facilities to write a new file,...
2015 """
2016
2017
2018
2020 """initialize the directory to the default value"""
2021
2022 self.add_param("MLReductionLib", "1|3|2")
2023 self.add_param("IREGIMODE", 2)
2024 self.add_param("IREGIRECY", True)
2025 self.add_param("CTModeRun", -1)
2026 self.add_param("MLStabThres", 1e-3)
2027 self.add_param("NRotations_DP", 1)
2028 self.add_param("NRotations_QP", 0)
2029 self.add_param("ImprovePSPoint", 2)
2030 self.add_param("CTLoopLibrary", 2)
2031 self.add_param("CTStabThres", 1e-2)
2032 self.add_param("CTModeInit", 1)
2033 self.add_param("CheckCycle", 3)
2034 self.add_param("MaxAttempts", 10)
2035 self.add_param("ZeroThres", 1e-9)
2036 self.add_param("OSThres", 1.0e-8)
2037 self.add_param("DoubleCheckHelicityFilter", True)
2038 self.add_param("WriteOutFilters", True)
2039 self.add_param("UseLoopFilter", False)
2040 self.add_param("HelicityFilterLevel", 2)
2041 self.add_param("LoopInitStartOver", False)
2042 self.add_param("HelInitStartOver", False)
2043
2044 - def read(self, finput):
2045 """Read the input file, this can be a path to a file,
2046 a file object, a str with the content of the file."""
2047
2048 if isinstance(finput, str):
2049 if "\n" in finput:
2050 finput = finput.split('\n')
2051 elif os.path.isfile(finput):
2052 finput = open(finput)
2053 else:
2054 raise Exception, "No such file %s" % input
2055
2056 previous_line= ''
2057 for line in finput:
2058 if previous_line.startswith('#'):
2059 name = previous_line[1:].split()[0]
2060 value = line.strip()
2061 if len(value) and value[0] not in ['#', '!']:
2062 self.__setitem__(name, value, change_userdefine=True)
2063 previous_line = line
2064
2065
2066 - def write(self, outputpath, template=None,commentdefault=False):
2067
2068 if not template:
2069 if not MADEVENT:
2070 template = pjoin(MG5DIR, 'Template', 'loop_material', 'StandAlone',
2071 'Cards', 'MadLoopParams.dat')
2072 else:
2073 template = pjoin(MEDIR, 'SubProcesses', 'MadLoop5_resources',
2074 'MadLoopParams.dat' )
2075 if not os.path.exists(template):
2076 template = pjoin(MEDIR, 'Cards', 'MadLoopParams.dat')
2077 fsock = open(template, 'r')
2078 template = fsock.readlines()
2079 fsock.close()
2080
2081 if isinstance(outputpath, str):
2082 output = open(outputpath, 'w')
2083 else:
2084 output = outputpath
2085
2086 def f77format(value):
2087 if isinstance(value, bool):
2088 if value:
2089 return '.true.'
2090 else:
2091 return '.false.'
2092 elif isinstance(value, int):
2093 return value
2094 elif isinstance(value, float):
2095 tmp ='%e' % value
2096 return tmp.replace('e','d')
2097 elif isinstance(value, str):
2098 return value
2099 else:
2100 raise Exception, "Can not format input %s" % type(value)
2101
2102 name = ''
2103 done = set()
2104 for line in template:
2105 if name:
2106 done.add(name)
2107 if commentdefault and name.lower() not in self.user_set :
2108 output.write('!%s\n' % f77format(self[name]))
2109 else:
2110 output.write('%s\n' % f77format(self[name]))
2111 name=''
2112 continue
2113 elif line.startswith('#'):
2114 name = line[1:].split()[0]
2115 output.write(line)
2116