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 """allow auto-build for the run_card/param_card/... """
154 try:
155 return super(Banner, self).__getattribute__(attr)
156 except:
157 if attr not in ['run_card', 'param_card', 'slha', 'mgruncard', 'mg5proccard', 'mgshowercard', 'foanalyse']:
158 raise
159 return self.charge_card(attr)
160
161
162
164 """change the lhe version associate to the banner"""
165
166 version = float(version)
167 if version < 3:
168 version = 1
169 elif version > 3:
170 raise Exception, "Not Supported version"
171 self.lhe_version = version
172
174 """return the cross-section of the file"""
175
176 if "init" not in self:
177 misc.sprint(self.keys())
178 raise Exception
179
180 text = self["init"].split('\n')
181 cross = 0
182 error = 0
183 for line in text:
184 s = line.split()
185 if len(s)==4:
186 cross += float(s[0])
187 if witherror:
188 error += float(s[1])**2
189 if not witherror:
190 return cross
191 else:
192 return cross, math.sqrt(error)
193
194
195
197 """modify the init information with the associate cross-section"""
198
199 assert isinstance(cross, dict)
200
201 assert "init" in self
202
203 all_lines = self["init"].split('\n')
204 new_data = []
205 new_data.append(all_lines[0])
206 for i in range(1, len(all_lines)):
207 line = all_lines[i]
208 split = line.split()
209 if len(split) == 4:
210 xsec, xerr, xmax, pid = split
211 else:
212 new_data += all_lines[i:]
213 break
214 if int(pid) not in cross:
215 raise Exception
216 pid = int(pid)
217 ratio = cross[pid]/float(xsec)
218 line = " %+13.7e %+13.7e %+13.7e %i" % \
219 (float(cross[pid]), ratio* float(xerr), ratio*float(xmax), pid)
220 new_data.append(line)
221 self['init'] = '\n'.join(new_data)
222
224 """modify the init information with the associate scale"""
225
226 assert "init" in self
227
228 all_lines = self["init"].split('\n')
229 new_data = []
230 new_data.append(all_lines[0])
231 for i in range(1, len(all_lines)):
232 line = all_lines[i]
233 split = line.split()
234 if len(split) == 4:
235 xsec, xerr, xmax, pid = split
236 else:
237 new_data += all_lines[i:]
238 break
239 pid = int(pid)
240
241 line = " %+13.7e %+13.7e %+13.7e %i" % \
242 (ratio*float(xsec), ratio* float(xerr), ratio*float(xmax), pid)
243 new_data.append(line)
244 self['init'] = '\n'.join(new_data)
245
247 """ Load the proc_card /param_card and run_card """
248
249 self.add(pjoin(medir,'Cards', 'param_card.dat'))
250 self.add(pjoin(medir,'Cards', 'run_card.dat'))
251 if os.path.exists(pjoin(medir, 'SubProcesses', 'procdef_mg5.dat')):
252 self.add(pjoin(medir,'SubProcesses', 'procdef_mg5.dat'))
253 self.add(pjoin(medir,'Cards', 'proc_card_mg5.dat'))
254 else:
255 self.add(pjoin(medir,'Cards', 'proc_card.dat'))
256
257
259 """Change the seed value in the banner"""
260
261 p = re.compile(r'''^\s*\d+\s*=\s*iseed''', re.M)
262 new_seed_str = " %s = iseed" % seed
263 self['mgruncard'] = p.sub(new_seed_str, self['mgruncard'])
264
266 """add info on MGGeneration"""
267
268 text = """
269 # Number of Events : %s
270 # Integrated weight (pb) : %s
271 """ % (nb_event, cross)
272 self['MGGenerationInfo'] = text
273
274
275
276
277 - def split(self, me_dir, proc_card=True):
278 """write the banner in the Cards directory.
279 proc_card argument is present to avoid the overwrite of proc_card
280 information"""
281
282 for tag, text in self.items():
283 if tag == 'mgversion':
284 continue
285 if not proc_card and tag in ['mg5proccard','mgproccard']:
286 continue
287 if not self.tag_to_file[tag]:
288 continue
289 ff = open(pjoin(me_dir, 'Cards', self.tag_to_file[tag]), 'w')
290 ff.write(text)
291 ff.close()
292
293
294
295
296
298 """special routine removing width/mass of particles not present in the model
299 This is usefull in case of loop model card, when we want to use the non
300 loop model."""
301
302 if not hasattr(self, 'param_card'):
303 self.charge_card('slha')
304
305 for tag in ['mass', 'decay']:
306 block = self.param_card.get(tag)
307 for data in block:
308 pid = data.lhacode[0]
309 if pid not in pid2label.keys():
310 block.remove((pid,))
311
313 """get the lha_strategy: how the weight have to be handle by the shower"""
314
315 if not self["init"]:
316 raise Exception, "No init block define"
317
318 data = self["init"].split('\n')[0].split()
319 if len(data) != 10:
320 misc.sprint(len(data), self['init'])
321 raise Exception, "init block has a wrong format"
322 return int(float(data[-2]))
323
325 """set the lha_strategy: how the weight have to be handle by the shower"""
326
327 if not (-4 <= int(value) <= 4):
328 raise Exception, "wrong value for lha_strategy", value
329 if not self["init"]:
330 raise Exception, "No init block define"
331
332 all_lines = self["init"].split('\n')
333 data = all_lines[0].split()
334 if len(data) != 10:
335 misc.sprint(len(data), self['init'])
336 raise Exception, "init block has a wrong format"
337 data[-2] = '%s' % value
338 all_lines[0] = ' '.join(data)
339 self['init'] = '\n'.join(all_lines)
340
342 """modify the init information with the associate cross-section"""
343
344 assert isinstance(cross, dict)
345
346 assert "init" in self
347
348 all_lines = self["init"].split('\n')
349 new_data = []
350 new_data.append(all_lines[0])
351 for i in range(1, len(all_lines)):
352 line = all_lines[i]
353 split = line.split()
354 if len(split) == 4:
355 xsec, xerr, xmax, pid = split
356 else:
357 new_data += all_lines[i:]
358 break
359 if int(pid) not in cross:
360 raise Exception
361 pid = int(pid)
362 ratio = cross[pid]/float(xsec)
363 line = " %+13.7e %+13.7e %+13.7e %i" % \
364 (float(cross[pid]), ratio* float(xerr), ratio*float(xmax), pid)
365 new_data.append(line)
366 self['init'] = '\n'.join(new_data)
367
368
369
370
371 - def write(self, output_path, close_tag=True, exclude=[]):
372 """write the banner"""
373
374 if isinstance(output_path, str):
375 ff = open(output_path, 'w')
376 else:
377 ff = output_path
378
379 if MADEVENT:
380 header = open(pjoin(MEDIR, 'Source', 'banner_header.txt')).read()
381 else:
382 header = open(pjoin(MG5DIR,'Template', 'LO', 'Source', 'banner_header.txt')).read()
383
384 if not self.lhe_version:
385 self.lhe_version = self.get('run_card', 'lhe_version', default=1.0)
386 if float(self.lhe_version) < 3:
387 self.lhe_version = 1.0
388
389 ff.write(header % { 'version':float(self.lhe_version)})
390
391
392 for tag in [t for t in self.ordered_items if t in self.keys()]:
393 if tag in exclude:
394 continue
395 capitalized_tag = self.capitalized_items[tag] if tag in self.capitalized_items else tag
396 ff.write('<%(tag)s>\n%(text)s\n</%(tag)s>\n' % \
397 {'tag':capitalized_tag, 'text':self[tag].strip()})
398 for tag in [t for t in self.keys() if t not in self.ordered_items]:
399 if tag in ['init'] or tag in exclude:
400 continue
401 capitalized_tag = self.capitalized_items[tag] if tag in self.capitalized_items else tag
402 ff.write('<%(tag)s>\n%(text)s\n</%(tag)s>\n' % \
403 {'tag':capitalized_tag, 'text':self[tag].strip()})
404
405 if not '/header' in exclude:
406 ff.write('</header>\n')
407
408 if 'init' in self and not 'init' in exclude:
409 text = self['init']
410 ff.write('<%(tag)s>\n%(text)s\n</%(tag)s>\n' % \
411 {'tag':'init', 'text':text.strip()})
412 if close_tag:
413 ff.write('</LesHouchesEvents>\n')
414 return ff
415
416
417
418
419
420 - def add(self, path, tag=None):
421 """Add the content of the file to the banner"""
422
423 if not tag:
424 card_name = os.path.basename(path)
425 if 'param_card' in card_name:
426 tag = 'slha'
427 elif 'run_card' in card_name:
428 tag = 'MGRunCard'
429 elif 'pythia_card' in card_name:
430 tag = 'MGPythiaCard'
431 elif 'pgs_card' in card_name:
432 tag = 'MGPGSCard'
433 elif 'delphes_card' in card_name:
434 tag = 'MGDelphesCard'
435 elif 'delphes_trigger' in card_name:
436 tag = 'MGDelphesTrigger'
437 elif 'proc_card_mg5' in card_name:
438 tag = 'MG5ProcCard'
439 elif 'proc_card' in card_name:
440 tag = 'MGProcCard'
441 elif 'procdef_mg5' in card_name:
442 tag = 'MGProcCard'
443 elif 'shower_card' in card_name:
444 tag = 'MGShowerCard'
445 elif 'madspin_card' in card_name:
446 tag = 'madspin'
447 elif 'FO_analyse_card' in card_name:
448 tag = 'foanalyse'
449 elif 'reweight_card' in card_name:
450 tag='reweight_card'
451 else:
452 raise Exception, 'Impossible to know the type of the card'
453
454 self.add_text(tag.lower(), open(path).read())
455
456 - def add_text(self, tag, text):
457 """Add the content of the file to the banner"""
458
459 if tag == 'param_card':
460 tag = 'slha'
461 elif tag == 'run_card':
462 tag = 'mgruncard'
463 elif tag == 'proc_card':
464 tag = 'mg5proccard'
465 elif tag == 'shower_card':
466 tag = 'mgshowercard'
467 elif tag == 'FO_analyse_card':
468 tag = 'foanalyse'
469
470 self[tag.lower()] = text
471
472
522
523
525 """return a specific """
526
527 if tag in ['param_card', 'param']:
528 tag = 'slha'
529 attr_tag = 'param_card'
530 elif tag in ['run_card', 'run']:
531 tag = 'mgruncard'
532 attr_tag = 'run_card'
533 elif tag == 'proc_card':
534 tag = 'mg5proccard'
535 attr_tag = 'proc_card'
536 elif tag == 'model':
537 tag = 'mg5proccard'
538 attr_tag = 'proc_card'
539 arg = ('model',)
540 elif tag == 'generate':
541 tag = 'mg5proccard'
542 attr_tag = 'proc_card'
543 arg = ('generate',)
544 elif tag == 'shower_card':
545 tag = 'mgshowercard'
546 attr_tag = 'shower_card'
547 assert tag in ['slha', 'mgruncard', 'mg5proccard', 'shower_card'], '%s not recognized' % tag
548
549 if not hasattr(self, attr_tag):
550 self.charge_card(attr_tag)
551
552 card = getattr(self, attr_tag)
553 if len(arg) == 1:
554 if tag == 'mg5proccard':
555 try:
556 return card.get(arg[0])
557 except KeyError, error:
558 if 'default' in opt:
559 return opt['default']
560 else:
561 raise
562 try:
563 return card[arg[0]]
564 except KeyError:
565 if 'default' in opt:
566 return opt['default']
567 else:
568 raise
569 elif len(arg) == 2 and tag == 'slha':
570 try:
571 return card[arg[0]].get(arg[1:])
572 except KeyError:
573 if 'default' in opt:
574 return opt['default']
575 else:
576 raise
577 elif len(arg) == 0:
578 return card
579 else:
580 raise Exception, "Unknow command"
581
582
583 get = get_detail
584
585 - def set(self, card, *args):
586 """modify one of the cards"""
587
588 if tag == 'param_card':
589 tag = 'slha'
590 attr_tag = 'param_card'
591 elif tag == 'run_card':
592 tag = 'mgruncard'
593 attr_tag = 'run_card'
594 elif tag == 'proc_card':
595 tag = 'mg5proccard'
596 attr_tag = 'proc_card'
597 elif tag == 'model':
598 tag = 'mg5proccard'
599 attr_tag = 'proc_card'
600 arg = ('model',)
601 elif tag == 'generate':
602 tag = 'mg5proccard'
603 attr_tag = 'proc_card'
604 arg = ('generate',)
605 elif tag == 'shower_card':
606 tag = 'mgshowercard'
607 attr_tag = 'shower_card'
608 assert tag in ['slha', 'mgruncard', 'mg5proccard', 'shower_card'], 'not recognized'
609
610 if not hasattr(self, attr_tag):
611 self.charge_card(attr_tag)
612
613 card = getattr(self, attr_tag)
614 if len(args) ==2:
615 if tag == 'mg5proccard':
616 card.info[args[0]] = args[-1]
617 else:
618 card[args[0]] = args[1]
619 else:
620 card[args[:-1]] = args[-1]
621
622
623 @misc.multiple_try()
625 """Add the banner to a file and change the associate seed in the banner"""
626
627 if seed is not None:
628 self.set("run_card", "iseed", seed)
629
630 if not out:
631 path_out = "%s.tmp" % path
632 else:
633 path_out = out
634
635 ff = self.write(path_out, close_tag=False,
636 exclude=['MGGenerationInfo', '/header', 'init'])
637 ff.write("## END BANNER##\n")
638 if self.lhe_version >= 3:
639
640 [ff.write(line) if not line.startswith("<generator name='MadGraph5_aMC@NLO'")
641 else ff.write("<generator name='MadGraph5_aMC@NLO' version='%s'>" % self['mgversion'][:-1])
642 for line in open(path)]
643 else:
644 [ff.write(line) for line in open(path)]
645 ff.write("</LesHouchesEvents>\n")
646 ff.close()
647 if out:
648 os.remove(path)
649 else:
650 files.mv(path_out, path)
651
652
653
654 -def split_banner(banner_path, me_dir, proc_card=True):
659
661 """as input we receive a gen_crossxhtml.AllResults object.
662 This define the current banner and load it
663 """
664
665 if not run:
666 try:
667 _run = results_object.current['run_name']
668 _tag = results_object.current['tag']
669 except Exception:
670 return Banner()
671 else:
672 _run = run
673 if not tag:
674 try:
675 _tag = results_object[run].tags[-1]
676 except Exception,error:
677 return Banner()
678 else:
679 _tag = tag
680
681 path = results_object.path
682 banner_path = pjoin(path,'Events',run,'%s_%s_banner.txt' % (run, tag))
683
684 if not os.path.exists(banner_path):
685 if level != "parton" and tag != _tag:
686 return recover_banner(results_object, level, _run, results_object[_run].tags[0])
687
688 return Banner()
689 banner = Banner(banner_path)
690
691
692
693 if level == 'pythia':
694 if 'mgpythiacard' in banner:
695 del banner['mgpythiacard']
696 if level in ['pythia','pgs','delphes']:
697 for tag in ['mgpgscard', 'mgdelphescard', 'mgdelphestrigger']:
698 if tag in banner:
699 del banner[tag]
700 return banner
701
704
706 """Basic Proccard object"""
707
708 history_header = \
709 '#************************************************************\n' + \
710 '#* MadGraph5_aMC@NLO *\n' + \
711 '#* *\n' + \
712 "#* * * *\n" + \
713 "#* * * * * *\n" + \
714 "#* * * * * 5 * * * * *\n" + \
715 "#* * * * * *\n" + \
716 "#* * * *\n" + \
717 "#* *\n" + \
718 "#* *\n" + \
719 "%(info_line)s" +\
720 "#* *\n" + \
721 "#* The MadGraph5_aMC@NLO Development Team - Find us at *\n" + \
722 "#* https://server06.fynu.ucl.ac.be/projects/madgraph *\n" + \
723 '#* *\n' + \
724 '#************************************************************\n' + \
725 '#* *\n' + \
726 '#* Command File for MadGraph5_aMC@NLO *\n' + \
727 '#* *\n' + \
728 '#* run as ./bin/mg5_aMC filename *\n' + \
729 '#* *\n' + \
730 '#************************************************************\n'
731
732
733
734
736 """ initialize a basic proc_card"""
737 self.info = {'model': 'sm', 'generate':None,
738 'full_model_line':'import model sm'}
739 list.__init__(self)
740 if init:
741 self.read(init)
742
743
744 - def read(self, init):
745 """read the proc_card and save the information"""
746
747 if isinstance(init, str):
748 init = file(init, 'r')
749
750 store_line = ''
751 for line in init:
752 line = line.rstrip()
753 if line.endswith('\\'):
754 store_line += line[:-1]
755 else:
756 tmp = store_line + line
757 self.append(tmp.strip())
758 store_line = ""
759 if store_line:
760 raise Exception, "WRONG CARD FORMAT"
761
762
764 """move an element to the last history."""
765 for line in self[:]:
766 if line.startswith(cmd):
767 self.remove(line)
768 list.append(self, line)
769
771 """"add a line in the proc_card perform automatically cleaning"""
772
773 line = line.strip()
774 cmds = line.split()
775 if len(cmds) == 0:
776 return
777
778 list.append(self, line)
779
780
781 cmd = cmds[0]
782
783 if cmd == 'output':
784
785 self.clean(allow_for_removal = ['output'], keep_switch=True,
786 remove_bef_last='output')
787 elif cmd == 'generate':
788
789 self.clean(remove_bef_last='generate', keep_switch=True,
790 allow_for_removal= ['generate', 'add process', 'output'])
791 self.info['generate'] = ' '.join(cmds[1:])
792 elif cmd == 'add' and cmds[1] == 'process' and not self.info['generate']:
793 self.info['generate'] = ' '.join(cmds[2:])
794 elif cmd == 'import':
795 if len(cmds) < 2:
796 return
797 if cmds[1].startswith('model'):
798 self.info['full_model_line'] = line
799 self.clean(remove_bef_last='import', keep_switch=True,
800 allow_for_removal=['generate', 'add process', 'add model', 'output'])
801 if cmds[1] == 'model':
802 self.info['model'] = cmds[2]
803 else:
804 self.info['model'] = None
805 elif cmds[1] == 'proc_v4':
806
807 self[:] = []
808
809
810 - def clean(self, to_keep=['set','add','load'],
811 remove_bef_last=None,
812 to_remove=['open','display','launch', 'check','history'],
813 allow_for_removal=None,
814 keep_switch=False):
815 """Remove command in arguments from history.
816 All command before the last occurrence of 'remove_bef_last'
817 (including it) will be removed (but if another options tells the opposite).
818 'to_keep' is a set of line to always keep.
819 'to_remove' is a set of line to always remove (don't care about remove_bef_
820 status but keep_switch acts.).
821 if 'allow_for_removal' is define only the command in that list can be
822 remove of the history for older command that remove_bef_lb1. all parameter
823 present in to_remove are always remove even if they are not part of this
824 list.
825 keep_switch force to keep the statement remove_bef_??? which changes starts
826 the removal mode.
827 """
828
829
830 if __debug__ and allow_for_removal:
831 for arg in to_keep:
832 assert arg not in allow_for_removal
833
834
835 nline = -1
836 removal = False
837
838 while nline > -len(self):
839 switch = False
840
841
842 if not removal and remove_bef_last:
843 if self[nline].startswith(remove_bef_last):
844 removal = True
845 switch = True
846
847
848 if switch and keep_switch:
849 nline -= 1
850 continue
851
852
853 if any([self[nline].startswith(arg) for arg in to_remove]):
854 self.pop(nline)
855 continue
856
857
858 if removal:
859 if allow_for_removal:
860
861 if any([self[nline].startswith(arg)
862 for arg in allow_for_removal]):
863 self.pop(nline)
864 continue
865 elif not any([self[nline].startswith(arg) for arg in to_keep]):
866
867 self.pop(nline)
868 continue
869
870
871 nline -= 1
872
873 - def get(self, tag, default=None):
874 if isinstance(tag, int):
875 list.__getattr__(self, tag)
876 elif tag == 'info' or tag == "__setstate__":
877 return default
878 elif tag == "multiparticles":
879 out = []
880 for line in self:
881 if line.startswith('define'):
882 name, content = line[7:].split('=',1)
883 out.append((name, content))
884 return out
885 else:
886 return self.info[tag]
887
889 """write the proc_card to a given path"""
890
891 fsock = open(path, 'w')
892 fsock.write(self.history_header)
893 for line in self:
894 while len(line) > 70:
895 sub, line = line[:70]+"\\" , line[70:]
896 fsock.write(sub+"\n")
897 else:
898 fsock.write(line+"\n")
899
902 """ a class for storing/dealing with input file.
903 """
904
906 """initialize a new instance. input can be an instance of MadLoopParam,
907 a file, a path to a file, or simply Nothing"""
908
909 if isinstance(finput, self.__class__):
910 dict.__init__(self, finput)
911 assert finput.__dict__.keys()
912 for key in finput.__dict__:
913 setattr(self, key, copy.copy(getattr(finput, key)) )
914 return
915 else:
916 dict.__init__(self)
917
918
919 self.user_set = set()
920 self.system_only = set()
921 self.lower_to_case = {}
922 self.list_parameter = set()
923 self.default_setup()
924
925
926
927
928 if isinstance(finput, (file, str)):
929 self.read(finput)
930
931
934
936 return self.__class__(self)
937
939 """define the sum"""
940 assert isinstance(other, dict)
941 base = self.__class__(self)
942
943 base.update((key.lower(),value) for key, value in other.items())
944 return base
945
947 """define the sum"""
948 new = copy.copy(other)
949 new.update((key, value) for key, value in self.items())
950 return new
951
954
958
961
965
966 - def __setitem__(self, name, value, change_userdefine=False):
967 """set the attribute and set correctly the type if the value is a string"""
968 if not len(self):
969
970 self.__init__()
971
972
973 name = name.strip()
974 lower_name = name.lower()
975
976 if change_userdefine and lower_name in self.system_only:
977 logger.critical('%s is a private entry which can not be modify by the user. Keep value at %s' % (name,self[name]))
978
979
980 if name in self.list_parameter:
981 if isinstance(self[name], list):
982 targettype = type(self[name][0])
983 else:
984 targettype = type(self[name])
985
986 if isinstance(value, str):
987
988 value = value.strip()
989 if value.startswith('[') and value.endswith(']'):
990 value = value[1:-1]
991 value = filter(None, re.split(r'(?:(?<!\\)\s)|,', value, re.VERBOSE))
992 elif not hasattr(value, '__iter__'):
993 value = [value]
994 elif isinstance(value, dict):
995 raise Exception, "not being able to handle dictionary in card entry"
996
997 values =[self.format_variable(v, targettype, name=name)
998 for v in value]
999 dict.__setitem__(self, lower_name, values)
1000 if change_userdefine:
1001 self.user_set.add(lower_name)
1002 return
1003 elif name in self:
1004 targettype = type(self[name])
1005 else:
1006 logger.debug('Trying to add argument %s in %s. ' % (name, self.__class__.__name__) +\
1007 'This argument is not defined by default. Please consider to add it.')
1008 logger.debug("Did you mean %s", [k for k in self.keys() if k.startswith(name[0].lower())])
1009 self.add_param(lower_name, self.format_variable(str(value), str, name))
1010 self.lower_to_case[lower_name] = name
1011 if change_userdefine:
1012 self.user_set.add(lower_name)
1013 return
1014
1015 value = self.format_variable(value, targettype, name=name)
1016 dict.__setitem__(self, lower_name, value)
1017 if change_userdefine:
1018 self.user_set.add(lower_name)
1019
1020 - def add_param(self, name, value, system=False):
1021 """add a default parameter to the class"""
1022
1023 lower_name = name.lower()
1024 if __debug__:
1025 if lower_name in self:
1026 raise Exception("Duplicate case for %s in %s" % (name,self.__class__))
1027
1028 dict.__setitem__(self, lower_name, value)
1029 self.lower_to_case[lower_name] = name
1030 if isinstance(value, list):
1031 if any([type(value[0]) != type(v) for v in value]):
1032 raise Exception, "All entry should have the same type"
1033 self.list_parameter.add(lower_name)
1034 if system:
1035 self.system_only.add(lower_name)
1036
1037 @staticmethod
1106
1107
1108
1110
1111 if __debug__:
1112 if name.lower() not in self:
1113 if name.lower() in [key.lower() for key in self] :
1114 raise Exception, "Some key are not lower case %s. Invalid use of the class!"\
1115 % [key for key in self if key.lower() != key]
1116
1117 return dict.__getitem__(self, name.lower())
1118
1119
1120 - def set(self, name, value, ifnotdefault=True, user=False):
1121 """convenient way to change attribute.
1122 ifnotdefault=False means that the value is NOT change is the value is not on default.
1123 user=True, means that the value will be marked as modified by the user
1124 (potentially preventing future change to the value)
1125 """
1126
1127
1128 if not ifnotdefault:
1129 if name.lower() in self.user_set:
1130
1131 return
1132
1133 self.__setitem__(name, value, change_userdefine=user)
1134
1138 """A class to handle information which are passed from MadGraph to the madevent
1139 interface."""
1140
1142 """initialize the directory to the default value"""
1143
1144 self.add_param('loop_induced', False)
1145 self.add_param('has_isr', False)
1146 self.add_param('has_fsr', False)
1147 self.add_param('nb_channel', 0)
1148 self.add_param('nexternal', 0)
1149 self.add_param('ninitial', 0)
1150 self.add_param('grouped_matrix', True)
1151 self.add_param('has_loops', False)
1152
1153 - def read(self, finput):
1154 """Read the input file, this can be a path to a file,
1155 a file object, a str with the content of the file."""
1156
1157 if isinstance(finput, str):
1158 if "\n" in finput:
1159 finput = finput.split('\n')
1160 elif os.path.isfile(finput):
1161 finput = open(finput)
1162 else:
1163 raise Exception, "No such file %s" % finput
1164
1165 for line in finput:
1166 if '#' in line:
1167 line = line.split('#',1)[0]
1168 if not line:
1169 continue
1170
1171 if '=' in line:
1172 key, value = line.split('=',1)
1173 self[key.strip()] = value
1174
1175 - def write(self, outputpath):
1176 """write the file"""
1177
1178 template ="# Information about the process #\n"
1179 template +="#########################################\n"
1180
1181 fsock = open(outputpath, 'w')
1182 fsock.write(template)
1183
1184 for key, value in self.items():
1185 fsock.write(" %s = %s \n" % (key, value))
1186
1187 fsock.close()
1188
1193 """an object for the GridpackCard"""
1194
1196 """default value for the GridpackCard"""
1197
1198 self.add_param("GridRun", True)
1199 self.add_param("gevents", 2500)
1200 self.add_param("gseed", 1)
1201 self.add_param("ngran", -1)
1202
1203 - def read(self, finput):
1204 """Read the input file, this can be a path to a file,
1205 a file object, a str with the content of the file."""
1206
1207 if isinstance(finput, str):
1208 if "\n" in finput:
1209 finput = finput.split('\n')
1210 elif os.path.isfile(finput):
1211 finput = open(finput)
1212 else:
1213 raise Exception, "No such file %s" % finput
1214
1215 for line in finput:
1216 line = line.split('#')[0]
1217 line = line.split('!')[0]
1218 line = line.split('=',1)
1219 if len(line) != 2:
1220 continue
1221 self[line[1].strip()] = line[0].replace('\'','').strip()
1222
1223 - def write(self, output_file, template=None):
1224 """Write the run_card in output_file according to template
1225 (a path to a valid run_card)"""
1226
1227 if not template:
1228 if not MADEVENT:
1229 template = pjoin(MG5DIR, 'Template', 'LO', 'Cards',
1230 'grid_card_default.dat')
1231 else:
1232 template = pjoin(MEDIR, 'Cards', 'grid_card_default.dat')
1233
1234
1235 text = ""
1236 for line in file(template,'r'):
1237 nline = line.split('#')[0]
1238 nline = nline.split('!')[0]
1239 comment = line[len(nline):]
1240 nline = nline.split('=')
1241 if len(nline) != 2:
1242 text += line
1243 elif nline[1].strip() in self:
1244 text += ' %s\t= %s %s' % (self[nline[1].strip()],nline[1], comment)
1245 else:
1246 logger.info('Adding missing parameter %s to current run_card (with default value)' % nline[1].strip())
1247 text += line
1248
1249 fsock = open(output_file,'w')
1250 fsock.write(text)
1251 fsock.close()
1252
1254
1256 if cls is RunCard:
1257 if not finput:
1258 target_class = RunCardLO
1259 elif isinstance(finput, cls):
1260 target_class = finput.__class__
1261 elif isinstance(finput, str):
1262 if '\n' not in finput:
1263 finput = open(finput).read()
1264 if 'req_acc_FO' in finput:
1265 target_class = RunCardNLO
1266 else:
1267 target_class = RunCardLO
1268 else:
1269 return None
1270 return super(RunCard, cls).__new__(target_class, finput)
1271 else:
1272 return super(RunCard, cls).__new__(cls, finput)
1273
1275
1276
1277
1278
1279 self.hidden_param = []
1280
1281 self.not_in_include = []
1282
1283 self.fortran_name = {}
1284
1285 self.legacy_parameter = {}
1286
1287 self.cuts_parameter = []
1288
1289
1290 super(RunCard, self).__init__(*args, **opts)
1291
1292 - def add_param(self, name, value, fortran_name=None, include=True,
1293 hidden=False, legacy=False, cut=False, system=False, **opts):
1294 """ add a parameter to the card. value is the default value and
1295 defines the type (int/float/bool/str) of the input.
1296 fortran_name defines what is the associate name in the f77 code
1297 include defines if we have to put the value in the include file
1298 hidden defines if the parameter is expected to be define by the user.
1299 legacy:Parameter which is not used anymore (raise a warning if not default)
1300 cut: defines the list of cut parameter to allow to set them all to off.
1301 """
1302
1303 super(RunCard, self).add_param(name, value, system=system,**opts)
1304 name = name.lower()
1305 if fortran_name:
1306 self.fortran_name[name] = fortran_name
1307 if not include:
1308 self.not_in_include.append(name)
1309 if hidden or system:
1310 self.hidden_param.append(name)
1311 if legacy:
1312 self.legacy_parameter[name] = value
1313 if include:
1314 self.not_in_include.append(name)
1315 if cut:
1316 self.cuts_parameter.append(name)
1317
1318
1319
1320 - def read(self, finput):
1321 """Read the input file, this can be a path to a file,
1322 a file object, a str with the content of the file."""
1323
1324 if isinstance(finput, str):
1325 if "\n" in finput:
1326 finput = finput.split('\n')
1327 elif os.path.isfile(finput):
1328 finput = open(finput)
1329 else:
1330 raise Exception, "No such file %s" % finput
1331
1332 for line in finput:
1333 line = line.split('#')[0]
1334 line = line.split('!')[0]
1335 line = line.split('=',1)
1336 if len(line) != 2:
1337 continue
1338 value, name = line
1339 name = name.lower().strip()
1340 if name not in self and ('min' in name or 'max' in name):
1341
1342 self.add_param(name, float(value), hidden=True, cut=True)
1343 else:
1344 self.set( name, value, user=True)
1345
1346 - def write(self, output_file, template=None, python_template=False):
1347 """Write the run_card in output_file according to template
1348 (a path to a valid run_card)"""
1349
1350 to_write = set(self.user_set)
1351 if not template:
1352 raise Exception
1353
1354 if python_template and not to_write:
1355 if not self.list_parameter:
1356 text = file(template,'r').read() % self
1357 else:
1358 data = dict(self)
1359 for name in self.list_parameter:
1360 data[name] = ', '.join(str(v) for v in data[name])
1361 text = file(template,'r').read() % data
1362 else:
1363 text = ""
1364 for line in file(template,'r'):
1365 nline = line.split('#')[0]
1366 nline = nline.split('!')[0]
1367 comment = line[len(nline):]
1368 nline = nline.split('=')
1369 if len(nline) != 2:
1370 text += line
1371 elif nline[1].strip() in self:
1372 name = nline[1].strip().lower()
1373 value = self[name]
1374 if name in self.list_parameter:
1375 value = ', '.join([str(v) for v in value])
1376 if python_template:
1377 text += line % {name:value}
1378 else:
1379 if not comment or comment[-1]!='\n':
1380 endline = '\n'
1381 else:
1382 endline = ''
1383 text += ' %s\t= %s %s%s' % (value, name, comment, endline)
1384
1385 if name.lower() in to_write:
1386 to_write.remove(nline[1].strip().lower())
1387 else:
1388 logger.info('Adding missing parameter %s to current run_card (with default value)' % name)
1389 text += line
1390
1391 if to_write:
1392 text+="""#*********************************************************************
1393 # Additional parameter
1394 #*********************************************************************
1395 """
1396
1397 for key in to_write:
1398 text += ' %s\t= %s # %s\n' % (self[key], key, 'hidden parameter')
1399
1400 if isinstance(output_file, str):
1401 fsock = open(output_file,'w')
1402 fsock.write(text)
1403 fsock.close()
1404 else:
1405 output_file.write(text)
1406
1407
1408 - def get_default(self, name, default=None, log_level=None):
1409 """return self[name] if exist otherwise default. log control if we
1410 put a warning or not if we use the default value"""
1411
1412 if name not in self.user_set:
1413 if log_level is None:
1414 if name.lower() in self.hidden_param:
1415 log_level = 10
1416 else:
1417 log_level = 20
1418 if not default:
1419 default = self[name]
1420 logger.log(log_level, 'run_card missed argument %s. Takes default: %s'
1421 % (name, default))
1422 self[name] = default
1423 return default
1424 else:
1425 return self[name]
1426
1427 @staticmethod
1433
1434 @staticmethod
1476
1477
1478
1480 """ """
1481
1482
1483 self.check_validity()
1484
1485 fsock = file_writers.FortranWriter(output_file)
1486 for key in self:
1487 if key in self.not_in_include:
1488 continue
1489
1490
1491 if key in self.fortran_name:
1492 fortran_name = self.fortran_name[key]
1493 else:
1494 fortran_name = key
1495
1496
1497 value = self.get_default(key)
1498
1499
1500 if isinstance(value, list):
1501
1502
1503
1504 if isinstance(value[0], bool):
1505 pass
1506 elif isinstance(value[0], int):
1507 line = '%s(%s) = %s \n' % (fortran_name, 0, self.f77_formatting(len(value)))
1508 fsock.writelines(line)
1509 elif isinstance(value[0], float):
1510 line = '%s(%s) = %s \n' % (fortran_name, 0, self.f77_formatting(float(len(value))))
1511 fsock.writelines(line)
1512
1513 for i,v in enumerate(value):
1514 line = '%s(%s) = %s \n' % (fortran_name, i+1, self.f77_formatting(v))
1515 fsock.writelines(line)
1516 else:
1517 line = '%s = %s \n' % (fortran_name, self.f77_formatting(value))
1518 fsock.writelines(line)
1519 fsock.close()
1520
1521
1539
1540
1541 output["idbmup1"] = get_idbmup(self['lpp1'])
1542 output["idbmup2"] = get_idbmup(self['lpp2'])
1543 output["ebmup1"] = self["ebeam1"]
1544 output["ebmup2"] = self["ebeam2"]
1545 output["pdfgup1"] = 0
1546 output["pdfgup2"] = 0
1547 output["pdfsup1"] = self.get_pdf_id(self["pdlabel"])
1548 output["pdfsup2"] = self.get_pdf_id(self["pdlabel"])
1549 return output
1550
1552 if pdf == "lhapdf":
1553 lhaid = self["lhaid"]
1554 if isinstance(lhaid, list):
1555 return lhaid[0]
1556 else:
1557 return lhaid
1558 else:
1559 return {'none': 0, 'mrs02nl':20250, 'mrs02nn':20270, 'cteq4_m': 19150,
1560 'cteq4_l':19170, 'cteq4_d':19160, 'cteq5_m':19050,
1561 'cteq5_d':19060,'cteq5_l':19070,'cteq5m1':19051,
1562 'cteq6_m':10000,'cteq6_l':10041,'cteq6l1':10042,
1563 'nn23lo':246800,'nn23lo1':247000,'nn23nlo':244800
1564 }[pdf]
1565
1568
1570 """remove all the cut"""
1571
1572 for name in self.cuts_parameter:
1573 targettype = type(self[name])
1574 if targettype == bool:
1575 self[name] = False
1576 elif 'min' in name:
1577 self[name] = 0
1578 elif 'max' in name:
1579 self[name] = -1
1580 elif 'eta' in name:
1581 self[name] = -1
1582 else:
1583 self[name] = 0
1584
1586 """an object to handle in a nice way the run_card infomration"""
1587
1589 """default value for the run_card.dat"""
1590
1591 self.add_param("run_tag", "tag_1", include=False)
1592 self.add_param("gridpack", False)
1593 self.add_param("time_of_flight", -1.0, include=False, hidden=True)
1594 self.add_param("nevents", 10000)
1595 self.add_param("iseed", 0)
1596 self.add_param("lpp1", 1, fortran_name="lpp(1)")
1597 self.add_param("lpp2", 1, fortran_name="lpp(2)")
1598 self.add_param("ebeam1", 6500.0, fortran_name="ebeam(1)")
1599 self.add_param("ebeam2", 6500.0, fortran_name="ebeam(2)")
1600 self.add_param("polbeam1", 0.0, fortran_name="pb1")
1601 self.add_param("polbeam2", 0.0, fortran_name="pb2")
1602 self.add_param("pdlabel", "nn23lo1")
1603 self.add_param("lhaid", 230000, hidden=True)
1604 self.add_param("fixed_ren_scale", False)
1605 self.add_param("fixed_fac_scale", False)
1606 self.add_param("scale", 91.1880)
1607 self.add_param("dsqrt_q2fact1", 91.1880, fortran_name="sf1")
1608 self.add_param("dsqrt_q2fact2", 91.1880, fortran_name="sf2")
1609 self.add_param("dynamical_scale_choice", -1)
1610
1611
1612 self.add_param("scalefact", 1.0)
1613 self.add_param("ickkw", 0)
1614 self.add_param("highestmult", 1, fortran_name="nhmult")
1615 self.add_param("ktscheme", 1)
1616 self.add_param("alpsfact", 1.0)
1617 self.add_param("chcluster", False)
1618 self.add_param("pdfwgt", True)
1619 self.add_param("asrwgtflavor", 5)
1620 self.add_param("clusinfo", True)
1621 self.add_param("lhe_version", 3.0)
1622
1623 self.add_param("auto_ptj_mjj", True)
1624 self.add_param("bwcutoff", 15.0)
1625 self.add_param("cut_decays", False)
1626 self.add_param("nhel", 0, include=False)
1627
1628 self.add_param("ptj", 20.0, cut=True)
1629 self.add_param("ptb", 0.0, cut=True)
1630 self.add_param("pta", 10.0, cut=True)
1631 self.add_param("ptl", 10.0, cut=True)
1632 self.add_param("misset", 0.0, cut=True)
1633 self.add_param("ptheavy", 0.0, cut=True)
1634 self.add_param("ptonium", 1.0, legacy=True)
1635 self.add_param("ptjmax", -1.0, cut=True)
1636 self.add_param("ptbmax", -1.0, cut=True)
1637 self.add_param("ptamax", -1.0, cut=True)
1638 self.add_param("ptlmax", -1.0, cut=True)
1639 self.add_param("missetmax", -1.0, cut=True)
1640
1641 self.add_param("ej", 0.0, cut=True)
1642 self.add_param("eb", 0.0, cut=True)
1643 self.add_param("ea", 0.0, cut=True)
1644 self.add_param("el", 0.0, cut=True)
1645 self.add_param("ejmax", -1.0, cut=True)
1646 self.add_param("ebmax", -1.0, cut=True)
1647 self.add_param("eamax", -1.0, cut=True)
1648 self.add_param("elmax", -1.0, cut=True)
1649
1650 self.add_param("etaj", 5.0, cut=True)
1651 self.add_param("etab", -1.0, cut=True)
1652 self.add_param("etaa", 2.5, cut=True)
1653 self.add_param("etal", 2.5, cut=True)
1654 self.add_param("etaonium", 0.6, legacy=True)
1655 self.add_param("etajmin", 0.0, cut=True)
1656 self.add_param("etabmin", 0.0, cut=True)
1657 self.add_param("etaamin", 0.0, cut=True)
1658 self.add_param("etalmin", 0.0, cut=True)
1659
1660 self.add_param("drjj", 0.4, cut=True)
1661 self.add_param("drbb", 0.0, cut=True)
1662 self.add_param("drll", 0.4, cut=True)
1663 self.add_param("draa", 0.4, cut=True)
1664 self.add_param("drbj", 0.0, cut=True)
1665 self.add_param("draj", 0.4, cut=True)
1666 self.add_param("drjl", 0.4, cut=True)
1667 self.add_param("drab", 0.0, cut=True)
1668 self.add_param("drbl", 0.0, cut=True)
1669 self.add_param("dral", 0.4, cut=True)
1670 self.add_param("drjjmax", -1.0, cut=True)
1671 self.add_param("drbbmax", -1.0, cut=True)
1672 self.add_param("drllmax", -1.0, cut=True)
1673 self.add_param("draamax", -1.0, cut=True)
1674 self.add_param("drbjmax", -1.0, cut=True)
1675 self.add_param("drajmax", -1.0, cut=True)
1676 self.add_param("drjlmax", -1.0, cut=True)
1677 self.add_param("drabmax", -1.0, cut=True)
1678 self.add_param("drblmax", -1.0, cut=True)
1679 self.add_param("dralmax", -1.0, cut=True)
1680
1681 self.add_param("mmjj", 0.0, cut=True)
1682 self.add_param("mmbb", 0.0, cut=True)
1683 self.add_param("mmaa", 0.0, cut=True)
1684 self.add_param("mmll", 0.0, cut=True)
1685 self.add_param("mmjjmax", -1.0, cut=True)
1686 self.add_param("mmbbmax", -1.0, cut=True)
1687 self.add_param("mmaamax", -1.0, cut=True)
1688 self.add_param("mmllmax", -1.0, cut=True)
1689 self.add_param("mmnl", 0.0, cut=True)
1690 self.add_param("mmnlmax", -1.0, cut=True)
1691
1692 self.add_param("ptllmin", 0.0, cut=True)
1693 self.add_param("ptllmax", -1.0, cut=True)
1694 self.add_param("xptj", 0.0, cut=True)
1695 self.add_param("xptb", 0.0, cut=True)
1696 self.add_param("xpta", 0.0, cut=True)
1697 self.add_param("xptl", 0.0, cut=True)
1698
1699 self.add_param("ptj1min", 0.0, cut=True)
1700 self.add_param("ptj1max", -1.0, cut=True)
1701 self.add_param("ptj2min", 0.0, cut=True)
1702 self.add_param("ptj2max", -1.0, cut=True)
1703 self.add_param("ptj3min", 0.0, cut=True)
1704 self.add_param("ptj3max", -1.0, cut=True)
1705 self.add_param("ptj4min", 0.0, cut=True)
1706 self.add_param("ptj4max", -1.0, cut=True)
1707 self.add_param("cutuse", 0, cut=True)
1708
1709 self.add_param("ptl1min", 0.0, cut=True)
1710 self.add_param("ptl1max", -1.0, cut=True)
1711 self.add_param("ptl2min", 0.0, cut=True)
1712 self.add_param("ptl2max", -1.0, cut=True)
1713 self.add_param("ptl3min", 0.0, cut=True)
1714 self.add_param("ptl3max", -1.0, cut=True)
1715 self.add_param("ptl4min", 0.0, cut=True)
1716 self.add_param("ptl4max", -1.0, cut=True)
1717
1718 self.add_param("htjmin", 0.0, cut=True)
1719 self.add_param("htjmax", -1.0, cut=True)
1720 self.add_param("ihtmin", 0.0, cut=True)
1721 self.add_param("ihtmax", -1.0, cut=True)
1722 self.add_param("ht2min", 0.0, cut=True)
1723 self.add_param("ht3min", 0.0, cut=True)
1724 self.add_param("ht4min", 0.0, cut=True)
1725 self.add_param("ht2max", -1.0, cut=True)
1726 self.add_param("ht3max", -1.0, cut=True)
1727 self.add_param("ht4max", -1.0, cut=True)
1728
1729 self.add_param("ptgmin", 0.0, cut=True)
1730 self.add_param("r0gamma", 0.4)
1731 self.add_param("xn", 1.0)
1732 self.add_param("epsgamma", 1.0)
1733 self.add_param("isoem", True)
1734 self.add_param("xetamin", 0.0, cut=True)
1735 self.add_param("deltaeta", 0.0, cut=True)
1736 self.add_param("ktdurham", -1.0, fortran_name="kt_durham", cut=True)
1737 self.add_param("dparameter", 0.4, fortran_name="d_parameter", cut=True)
1738 self.add_param("maxjetflavor", 4)
1739 self.add_param("xqcut", 0.0, cut=True)
1740 self.add_param("use_syst", True)
1741 self.add_param("sys_scalefact", "0.5 1 2", include=False)
1742 self.add_param("sys_alpsfact", "None", include=False)
1743 self.add_param("sys_matchscale", "30 50", include=False)
1744 self.add_param("sys_pdf", "NNPDF23_lo_as_0130_qed", include=False)
1745 self.add_param("sys_scalecorrelation", -1, include=False)
1746
1747
1748 self.add_param('gridrun', False, hidden=True)
1749 self.add_param('fixed_couplings', True, hidden=True)
1750 self.add_param('mc_grouped_subproc', True, hidden=True)
1751 self.add_param('xmtcentral', 0.0, hidden=True, fortran_name="xmtc")
1752 self.add_param('d', 1.0, hidden=True)
1753 self.add_param('gseed', 0, hidden=True, include=False)
1754 self.add_param('issgridfile', '', hidden=True)
1755
1756 self.add_param('job_strategy', 0, hidden=True, include=False)
1757 self.add_param('survey_splitting', -1, hidden=True, include=False)
1758 self.add_param('refine_evt_by_job', -1, hidden=True, include=False)
1759
1760
1761
1762
1764 """ """
1765
1766
1767
1768 if 'nhel' not in self.user_set:
1769 raise InvalidRunCard, "Parameter nhel is not defined in the run_card."
1770 if self['nhel'] not in [1,0]:
1771 raise InvalidRunCard, "Parameter nhel can only be '0' or '1', "+\
1772 "not %s." % self['nhel']
1773 if int(self['maxjetflavor']) > 6:
1774 raise InvalidRunCard, 'maxjetflavor should be lower than 5! (6 is partly supported)'
1775
1776
1777 if self['ptgmin'] > 0:
1778 if self['pta'] > 0:
1779 logger.warning('pta cut discarded since photon isolation is used')
1780 self['pta'] = 0.0
1781 if self['draj'] > 0:
1782 logger.warning('draj cut discarded since photon isolation is used')
1783 self['draj'] = 0.0
1784
1785
1786 if self['gridrun']:
1787 self['iseed'] = self['gseed']
1788
1789
1790 if self['use_syst']:
1791 if self['scalefact'] != 1.0:
1792 logger.warning('Since use_syst=T, We change the value of \'scalefact\' to 1')
1793 self['scalefact'] = 1.0
1794
1795
1796 if self['ickkw'] > 0:
1797 if self['use_syst']:
1798
1799 if self['alpsfact'] != 1.0:
1800 logger.warning('Since use_syst=T, We change the value of \'alpsfact\' to 1')
1801 self['alpsfact'] =1.0
1802 if self['maxjetflavor'] == 6:
1803 raise InvalidRunCard, 'maxjetflavor at 6 is NOT supported for matching!'
1804 if self['ickkw'] == 2:
1805
1806 self.get_default('highestmult', log_level=20)
1807 self.get_default('issgridfile', 'issudgrid.dat', log_level=20)
1808 if self['xqcut'] > 0:
1809 if self['drjj'] != 0:
1810 logger.warning('Since icckw>0, We change the value of \'drjj\' to 0')
1811 self['drjj'] = 0
1812 if self['drjl'] != 0:
1813 logger.warning('Since icckw>0, We change the value of \'drjl\' to 0')
1814 self['drjl'] = 0
1815 if not self['auto_ptj_mjj']:
1816 if self['mmjj'] > self['xqcut']:
1817 logger.warning('mmjj > xqcut (and auto_ptj_mjj = F). MMJJ set to 0')
1818 self['mmjj'] = 0.0
1819
1820
1821
1822 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']
1823 if self['pdlabel'] not in possible_set:
1824 raise InvalidRunCard, 'Invalid PDF set (argument of pdlabel): %s. Possible choice are:\n %s' % (self['pdlabel'], ', '.join(possible_set))
1825 if self['pdlabel'] == 'lhapdf':
1826
1827 self.get_default('lhaid', log_level=20)
1828
1829 for name in self.legacy_parameter:
1830 if self[name] != self.legacy_parameter[name]:
1831 logger.warning("The parameter %s is not supported anymore this parameter will be ignored." % name)
1832
1833
1834
1835
1837 """Rules
1838 process 1->N all cut set on off.
1839 loop_induced -> MC over helicity
1840 e+ e- beam -> lpp:0 ebeam:500
1841 p p beam -> set maxjetflavor automatically
1842 more than one multiplicity: ickkw=1 xqcut=30 use_syst=F
1843 """
1844
1845 if proc_characteristic['loop_induced']:
1846 self['nhel'] = 1
1847
1848 if proc_characteristic['ninitial'] == 1:
1849
1850 self.remove_all_cut()
1851 self['use_syst'] = False
1852 else:
1853
1854 beam_id = set()
1855 for proc in proc_def:
1856 for oneproc in proc:
1857 for leg in oneproc['legs']:
1858 if not leg['state']:
1859 beam_id.add(leg['id'])
1860 if any(i in beam_id for i in [1,-1,2,-2,3,-3,4,-4,5,-5,21,22]):
1861 maxjetflavor = max([4]+[abs(i) for i in beam_id if -7< i < 7])
1862 self['maxjetflavor'] = maxjetflavor
1863 self['asrwgtflavor'] = maxjetflavor
1864 pass
1865 elif 11 in beam_id or -11 in beam_id:
1866 self['lpp1'] = 0
1867 self['lpp2'] = 0
1868 self['ebeam1'] = 500
1869 self['ebeam2'] = 500
1870 else:
1871 self['lpp1'] = 0
1872 self['lpp2'] = 0
1873
1874
1875 min_particle = 99
1876 max_particle = 0
1877 for proc in proc_def:
1878 min_particle = min(len(proc[0]['legs']), min_particle)
1879 max_particle = max(len(proc[0]['legs']), max_particle)
1880 if min_particle != max_particle:
1881
1882 for procmin in proc_def:
1883 if len(procmin[0]['legs']) != min_particle:
1884 continue
1885 else:
1886 idsmin = [l['id'] for l in procmin[0]['legs']]
1887 break
1888 matching = False
1889 for procmax in proc_def:
1890 if len(procmax[0]['legs']) != max_particle:
1891 continue
1892 idsmax = [l['id'] for l in procmax[0]['legs']]
1893 for i in idsmin:
1894 if i not in idsmax:
1895 continue
1896 else:
1897 idsmax.remove(i)
1898 for j in idsmax:
1899 if j not in [1,-1,2,-2,3,-3,4,-4,5,-5,21]:
1900 break
1901 else:
1902
1903 matching=True
1904 break
1905
1906 if matching:
1907 self['ickkw'] = 1
1908 self['xqcut'] = 30
1909 self['use_syst'] = False
1910 self['drjj'] = 0
1911 self['drjl'] = 0
1912 self['sys_alpsfact'] = "0.5 1 2"
1913
1914
1915 - def write(self, output_file, template=None, python_template=False):
1916 """Write the run_card in output_file according to template
1917 (a path to a valid run_card)"""
1918
1919 if not template:
1920 if not MADEVENT:
1921 template = pjoin(MG5DIR, 'Template', 'LO', 'Cards',
1922 'run_card.dat')
1923 python_template = True
1924 else:
1925 template = pjoin(MEDIR, 'Cards', 'run_card_default.dat')
1926 python_template = False
1927
1928 super(RunCardLO, self).write(output_file, template=template,
1929 python_template=python_template)
1930
1933 """A class object for the run_card for a (aMC@)NLO pocess"""
1934
1935
1937 """define the default value"""
1938
1939 self.add_param('run_tag', 'tag_1', include=False)
1940 self.add_param('nevents', 10000)
1941 self.add_param('req_acc', -1.0, include=False)
1942 self.add_param('nevt_job', -1, include=False)
1943 self.add_param('event_norm', 'average')
1944
1945 self.add_param('req_acc_fo', 0.01, include=False)
1946 self.add_param('npoints_fo_grid', 5000, include=False)
1947 self.add_param('niters_fo_grid', 4, include=False)
1948 self.add_param('npoints_fo', 10000, include=False)
1949 self.add_param('niters_fo', 6, include=False)
1950
1951 self.add_param('iseed', 0)
1952 self.add_param('lpp1', 1, fortran_name='lpp(1)')
1953 self.add_param('lpp2', 1, fortran_name='lpp(2)')
1954 self.add_param('ebeam1', 6500.0, fortran_name='ebeam(1)')
1955 self.add_param('ebeam2', 6500.0, fortran_name='ebeam(2)')
1956 self.add_param('pdlabel', 'nn23nlo')
1957 self.add_param('lhaid', [244600],fortran_name='lhaPDFid')
1958 self.add_param('lhapdfsetname', ['internal_use_only'], system=True)
1959
1960 self.add_param('parton_shower', 'HERWIG6', fortran_name='shower_mc')
1961 self.add_param('shower_scale_factor',1.0)
1962 self.add_param('fixed_ren_scale', False)
1963 self.add_param('fixed_fac_scale', False)
1964 self.add_param('mur_ref_fixed', 91.118)
1965 self.add_param('muf1_ref_fixed', -1.0, hidden=True)
1966 self.add_param('muf_ref_fixed', 91.118)
1967 self.add_param('muf2_ref_fixed', -1.0, hidden=True)
1968 self.add_param("dynamical_scale_choice", [-1],fortran_name='dyn_scale')
1969 self.add_param('fixed_qes_scale', False, hidden=True)
1970 self.add_param('qes_ref_fixed', -1.0, hidden=True)
1971 self.add_param('mur_over_ref', 1.0)
1972 self.add_param('muf_over_ref', 1.0)
1973 self.add_param('muf1_over_ref', -1.0, hidden=True)
1974 self.add_param('muf2_over_ref', -1.0, hidden=True)
1975 self.add_param('qes_over_ref', -1.0, hidden=True)
1976 self.add_param('reweight_scale', [True], fortran_name='lscalevar')
1977 self.add_param('rw_rscale_down', -1.0, hidden=True)
1978 self.add_param('rw_rscale_up', -1.0, hidden=True)
1979 self.add_param('rw_fscale_down', -1.0, hidden=True)
1980 self.add_param('rw_fscale_up', -1.0, hidden=True)
1981 self.add_param('rw_rscale', [1.0,2.0,0.5], fortran_name='scalevarR')
1982 self.add_param('rw_fscale', [1.0,2.0,0.5], fortran_name='scalevarF')
1983 self.add_param('reweight_pdf', [False], fortran_name='lpdfvar')
1984 self.add_param('pdf_set_min', 244601, hidden=True)
1985 self.add_param('pdf_set_max', 244700, hidden=True)
1986 self.add_param('store_rwgt_info', False)
1987
1988 self.add_param('ickkw', 0)
1989 self.add_param('bwcutoff', 15.0)
1990
1991 self.add_param('jetalgo', 1.0)
1992 self.add_param('jetradius', 0.7)
1993 self.add_param('ptj', 10.0 , cut=True)
1994 self.add_param('etaj', -1.0, cut=True)
1995 self.add_param('ptl', 0.0, cut=True)
1996 self.add_param('etal', -1.0, cut=True)
1997 self.add_param('drll', 0.0, cut=True)
1998 self.add_param('drll_sf', 0.0, cut=True)
1999 self.add_param('mll', 0.0, cut=True)
2000 self.add_param('mll_sf', 30.0, cut=True)
2001 self.add_param('ptgmin', 20.0, cut=True)
2002 self.add_param('etagamma', -1.0)
2003 self.add_param('r0gamma', 0.4)
2004 self.add_param('xn', 1.0)
2005 self.add_param('epsgamma', 1.0)
2006 self.add_param('isoem', True)
2007 self.add_param('maxjetflavor', 4, hidden=True)
2008 self.add_param('iappl', 0)
2009 self.add_param('lhe_version', 3, hidden=True, include=False)
2010
2012 """check the validity of the various input"""
2013
2014
2015 if self['ickkw'] == 3:
2016
2017 scales=['fixed_ren_scale','fixed_fac_scale','fixed_QES_scale']
2018 for scale in scales:
2019 if self[scale]:
2020 logger.warning('''For consistency in the FxFx merging, \'%s\' has been set to false'''
2021 % scale,'$MG:color:BLACK')
2022 self[scale]= False
2023
2024 if len(self["dynamical_scale_choice"]) > 1 or self["dynamical_scale_choice"][0] != -1:
2025 self["dynamical_scale_choice"] = [-1]
2026 self["reweight_scale"]=[self["reweight_scale"][0]]
2027 logger.warning('''For consistency in the FxFx merging, dynamical_scale_choice has been set to -1 (default)'''
2028 ,'$MG:color:BLACK')
2029
2030
2031 jetparams=['jetradius','jetalgo']
2032 for jetparam in jetparams:
2033 if float(self[jetparam]) != 1.0:
2034 logger.info('''For consistency in the FxFx merging, \'%s\' has been set to 1.0'''
2035 % jetparam ,'$MG:color:BLACK')
2036 self[jetparam] = 1.0
2037 elif self['ickkw'] == -1 and (self["dynamical_scale_choice"][0] != -1 or
2038 len(self["dynamical_scale_choice"]) > 1):
2039 self["dynamical_scale_choice"] = [-1]
2040 self["reweight_scale"]=[self["reweight_scale"][0]]
2041 logger.warning('''For consistency with the jet veto, the scale which will be used is ptj. dynamical_scale_choice will be set at -1.'''
2042 ,'$MG:color:BLACK')
2043
2044
2045 if self['iappl'] != 0 and self['pdlabel'].lower() != 'lhapdf':
2046 raise InvalidRunCard('APPLgrid generation only possible with the use of LHAPDF')
2047 if self['iappl'] != 0 and not self['reweight_scale']:
2048 raise InvalidRunCard('APPLgrid generation only possible with including' +\
2049 ' the reweighting to get scale dependence')
2050
2051
2052 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']
2053 if self['pdlabel'] not in possible_set:
2054 raise InvalidRunCard, 'Invalid PDF set (argument of pdlabel) possible choice are:\n %s' % ','.join(possible_set)
2055
2056
2057 if self['qes_ref_fixed'] == -1.0:
2058 self['qes_ref_fixed']=self['mur_ref_fixed']
2059 if self['qes_over_ref'] == -1.0:
2060 self['qes_over_ref']=self['mur_over_ref']
2061 if self['muf1_over_ref'] != -1.0 and self['muf1_over_ref'] == self['muf2_over_ref']:
2062 self['muf_over_ref']=self['muf1_over_ref']
2063 if self['muf1_over_ref'] == -1.0:
2064 self['muf1_over_ref']=self['muf_over_ref']
2065 if self['muf2_over_ref'] == -1.0:
2066 self['muf2_over_ref']=self['muf_over_ref']
2067 if self['muf1_ref_fixed'] != -1.0 and self['muf1_ref_fixed'] == self['muf2_ref_fixed']:
2068 self['muf_ref_fixed']=self['muf1_ref_fixed']
2069 if self['muf1_ref_fixed'] == -1.0:
2070 self['muf1_ref_fixed']=self['muf_ref_fixed']
2071 if self['muf2_ref_fixed'] == -1.0:
2072 self['muf2_ref_fixed']=self['muf_ref_fixed']
2073
2074 if (self['rw_rscale_down'] != -1.0 and ['rw_rscale_down'] not in self['rw_rscale']) or\
2075 (self['rw_rscale_up'] != -1.0 and ['rw_rscale_up'] not in self['rw_rscale']):
2076 self['rw_rscale']=[1.0,self['rw_rscale_up'],self['rw_rscale_down']]
2077 if (self['rw_fscale_down'] != -1.0 and ['rw_fscale_down'] not in self['rw_fscale']) or\
2078 (self['rw_fscale_up'] != -1.0 and ['rw_fscale_up'] not in self['rw_fscale']):
2079 self['rw_fscale']=[1.0,self['rw_fscale_up'],self['rw_fscale_down']]
2080
2081
2082 if any(self['reweight_pdf']):
2083
2084 if self['pdlabel'] != "lhapdf":
2085 raise InvalidRunCard, 'Reweight PDF option requires to use pdf sets associated to lhapdf. Please either change the pdlabel to use LHAPDF or set reweight_pdf to False.'
2086
2087
2088 if self['pdlabel'] != "lhapdf":
2089 self['reweight_pdf']=[self['reweight_pdf'][0]]
2090 self['lhaid']=[self['lhaid'][0]]
2091
2092
2093 if self['fixed_ren_scale'] and self['fixed_fac_scale']:
2094 self['reweight_scale']=[self['reweight_scale'][0]]
2095 self['dynamical_scale_choice']=[0]
2096
2097
2098
2099
2100 if len(self['reweight_pdf']) == 1 and len(self['lhaid']) != 1:
2101 self['reweight_pdf']=self['reweight_pdf']*len(self['lhaid'])
2102 logger.warning("Setting 'reweight_pdf' for all 'lhaid' to %s" % self['reweight_pdf'][0])
2103 if len(self['reweight_scale']) == 1 and len(self['dynamical_scale_choice']) != 1:
2104 self['reweight_scale']=self['reweight_scale']*len(self['dynamical_scale_choice'])
2105 logger.warning("Setting 'reweight_scale' for all 'dynamical_scale_choice' to %s" % self['reweight_pdf'][0])
2106
2107
2108
2109 if len(self['lhaid']) != len(set(self['lhaid'])):
2110 raise InvalidRunCard, "'lhaid' has two or more identical entries. They have to be all different for the code to work correctly."
2111 if len(self['dynamical_scale_choice']) != len(set(self['dynamical_scale_choice'])):
2112 raise InvalidRunCard, "'dynamical_scale_choice' has two or more identical entries. They have to be all different for the code to work correctly."
2113
2114
2115 if len(self['reweight_pdf']) != len(self['lhaid']):
2116 raise InvalidRunCard, "'reweight_pdf' and 'lhaid' lists should have the same length"
2117 if len(self['reweight_scale']) != len(self['dynamical_scale_choice']):
2118 raise InvalidRunCard, "'reweight_scale' and 'dynamical_scale_choice' lists should have the same length"
2119 if len(self['dynamical_scale_choice']) > 10 :
2120 raise InvalidRunCard, "Length of list for 'dynamical_scale_choice' too long: max is 10."
2121 if len(self['lhaid']) > 25 :
2122 raise InvalidRunCard, "Length of list for 'lhaid' too long: max is 25."
2123 if len(self['rw_rscale']) > 9 :
2124 raise InvalidRunCard, "Length of list for 'rw_rscale' too long: max is 9."
2125 if len(self['rw_fscale']) > 9 :
2126 raise InvalidRunCard, "Length of list for 'rw_fscale' too long: max is 9."
2127
2128 if 1.0 not in self['rw_rscale']:
2129 logger.warning("'1.0' has to be part of 'rw_rscale', adding it")
2130 self['rw_rscale'].insert(0,1.0)
2131 if 1.0 not in self['rw_fscale']:
2132 logger.warning("'1.0' has to be part of 'rw_fscale', adding it")
2133 self['rw_fscale'].insert(0,1.0)
2134 if self['rw_rscale'][0] != 1.0 and 1.0 in self['rw_rscale']:
2135 a=self['rw_rscale'].index(1.0)
2136 self['rw_rscale'][0],self['rw_rscale'][a]=self['rw_rscale'][a],self['rw_rscale'][0]
2137 if self['rw_fscale'][0] != 1.0 and 1.0 in self['rw_fscale']:
2138 a=self['rw_fscale'].index(1.0)
2139 self['rw_fscale'][0],self['rw_fscale'][a]=self['rw_fscale'][a],self['rw_fscale'][0]
2140
2141 if len(self['rw_rscale']) != len(set(self['rw_rscale'])):
2142 raise InvalidRunCard, "'rw_rscale' has two or more identical entries. They have to be all different for the code to work correctly."
2143 if len(self['rw_fscale']) != len(set(self['rw_fscale'])):
2144 raise InvalidRunCard, "'rw_fscale' has two or more identical entries. They have to be all different for the code to work correctly."
2145
2146
2147 - def write(self, output_file, template=None, python_template=False):
2148 """Write the run_card in output_file according to template
2149 (a path to a valid run_card)"""
2150
2151 if not template:
2152 if not MADEVENT:
2153 template = pjoin(MG5DIR, 'Template', 'NLO', 'Cards',
2154 'run_card.dat')
2155 python_template = True
2156 else:
2157 template = pjoin(MEDIR, 'Cards', 'run_card_default.dat')
2158 python_template = False
2159
2160 super(RunCardNLO, self).write(output_file, template=template,
2161 python_template=python_template)
2162
2163
2165 """Rules
2166 e+ e- beam -> lpp:0 ebeam:500
2167 p p beam -> set maxjetflavor automatically
2168 """
2169
2170
2171 beam_id = set()
2172 for proc in proc_def:
2173 for leg in proc['legs']:
2174 if not leg['state']:
2175 beam_id.add(leg['id'])
2176 if any(i in beam_id for i in [1,-1,2,-2,3,-3,4,-4,5,-5,21,22]):
2177 maxjetflavor = max([4]+[abs(i) for i in beam_id if -7< i < 7])
2178 self['maxjetflavor'] = maxjetflavor
2179 pass
2180 elif 11 in beam_id or -11 in beam_id:
2181 self['lpp1'] = 0
2182 self['lpp2'] = 0
2183 self['ebeam1'] = 500
2184 self['ebeam2'] = 500
2185 else:
2186 self['lpp1'] = 0
2187 self['lpp2'] = 0
2188
2189 if proc_characteristic['ninitial'] == 1:
2190
2191 self.remove_all_cut()
2192
2194 """ a class for storing/dealing with the file MadLoopParam.dat
2195 contains a parser to read it, facilities to write a new file,...
2196 """
2197
2198
2199
2201 """initialize the directory to the default value"""
2202
2203 self.add_param("MLReductionLib", "6|1|2")
2204 self.add_param("IREGIMODE", 2)
2205 self.add_param("IREGIRECY", True)
2206 self.add_param("CTModeRun", -1)
2207 self.add_param("MLStabThres", 1e-3)
2208 self.add_param("NRotations_DP", 1)
2209 self.add_param("NRotations_QP", 0)
2210 self.add_param("ImprovePSPoint", 2)
2211 self.add_param("CTLoopLibrary", 2)
2212 self.add_param("CTStabThres", 1e-2)
2213 self.add_param("CTModeInit", 1)
2214 self.add_param("CheckCycle", 3)
2215 self.add_param("MaxAttempts", 10)
2216 self.add_param("ZeroThres", 1e-9)
2217 self.add_param("OSThres", 1.0e-8)
2218 self.add_param("DoubleCheckHelicityFilter", True)
2219 self.add_param("WriteOutFilters", True)
2220 self.add_param("UseLoopFilter", False)
2221 self.add_param("HelicityFilterLevel", 2)
2222 self.add_param("LoopInitStartOver", False)
2223 self.add_param("HelInitStartOver", False)
2224 self.add_param("UseQPIntegrandForNinja", False)
2225 self.add_param("UseQPIntegrandForCutTools", True)
2226
2227 - def read(self, finput):
2228 """Read the input file, this can be a path to a file,
2229 a file object, a str with the content of the file."""
2230
2231 if isinstance(finput, str):
2232 if "\n" in finput:
2233 finput = finput.split('\n')
2234 elif os.path.isfile(finput):
2235 finput = open(finput)
2236 else:
2237 raise Exception, "No such file %s" % input
2238
2239 previous_line= ''
2240 for line in finput:
2241 if previous_line.startswith('#'):
2242 name = previous_line[1:].split()[0]
2243 value = line.strip()
2244 if len(value) and value[0] not in ['#', '!']:
2245 self.__setitem__(name, value, change_userdefine=True)
2246 previous_line = line
2247
2248
2249 - def write(self, outputpath, template=None,commentdefault=False):
2250
2251 if not template:
2252 if not MADEVENT:
2253 template = pjoin(MG5DIR, 'Template', 'loop_material', 'StandAlone',
2254 'Cards', 'MadLoopParams.dat')
2255 else:
2256 template = pjoin(MEDIR, 'Cards', 'MadLoopParams_default.dat')
2257 fsock = open(template, 'r')
2258 template = fsock.readlines()
2259 fsock.close()
2260
2261 if isinstance(outputpath, str):
2262 output = open(outputpath, 'w')
2263 else:
2264 output = outputpath
2265
2266 def f77format(value):
2267 if isinstance(value, bool):
2268 if value:
2269 return '.true.'
2270 else:
2271 return '.false.'
2272 elif isinstance(value, int):
2273 return value
2274 elif isinstance(value, float):
2275 tmp ='%e' % value
2276 return tmp.replace('e','d')
2277 elif isinstance(value, str):
2278 return value
2279 else:
2280 raise Exception, "Can not format input %s" % type(value)
2281
2282 name = ''
2283 done = set()
2284 for line in template:
2285 if name:
2286 done.add(name)
2287 if commentdefault and name.lower() not in self.user_set :
2288 output.write('!%s\n' % f77format(self[name]))
2289 else:
2290 output.write('%s\n' % f77format(self[name]))
2291 name=''
2292 continue
2293 elif line.startswith('#'):
2294 name = line[1:].split()[0]
2295 output.write(line)
2296