1 from __future__ import division
2
3 from __future__ import absolute_import
4 from __future__ import print_function
5 import itertools
6 import xml.etree.ElementTree as ET
7 import math
8
9 import os
10 import re
11 import shutil
12 import logging
13 import random
14 import six
15 StringIO = six
16 from six.moves import range
17
18 logger = logging.getLogger('madgraph.models')
19
20 try:
21 import madgraph.iolibs.file_writers as file_writers
22 import madgraph.various.misc as misc
23 except:
24 import internal.file_writers as file_writers
25 import internal.misc as misc
26
27 pjoin = os.path.join
30 """ a class for invalid param_card """
31 pass
32
34 """A class for a param_card parameter"""
35
36 - def __init__(self, param=None, block=None, lhacode=None, value=None, comment=None):
37 """Init the parameter"""
38
39 self.format = 'float'
40 if param:
41 block = param.lhablock
42 lhacode = param.lhacode
43 value = param.value
44 comment = param.comment
45 format = param.format
46
47 self.lhablock = block
48 if lhacode:
49 self.lhacode = lhacode
50 else:
51 self.lhacode = []
52 self.value = value
53 self.comment = comment
54
56 """ set the block name """
57
58 self.lhablock = block
59
61 """ initialize the information from a str"""
62
63 if '#' in text:
64 data, self.comment = text.split('#',1)
65 else:
66 data, self.comment = text, ""
67
68
69 data = data.split()
70 if any(d.startswith('scan') for d in data):
71 position = [i for i,d in enumerate(data) if d.startswith('scan')][0]
72 data = data[:position] + [' '.join(data[position:])]
73 if not len(data):
74 return
75 try:
76 self.lhacode = tuple([int(d) for d in data[:-1]])
77 except Exception:
78 self.lhacode = tuple([int(d) for d in data[:-1] if d.isdigit()])
79 self.value= ' '.join(data[len(self.lhacode):])
80 else:
81 self.value = data[-1]
82
83
84 try:
85 self.value = float(self.value)
86 except:
87 self.format = 'str'
88 pass
89 else:
90 if self.lhablock == 'modsel':
91 self.format = 'int'
92 self.value = int(self.value)
93
95 """ initialize the decay information from a str"""
96
97 if '#' in text:
98 data, self.comment = text.split('#',1)
99 else:
100 data, self.comment = text, ""
101
102 if ']]>' in data:
103 data = data.split(']]>',1)[0]
104
105
106 data = data.split()
107 if not len(data):
108 return
109 self.lhacode = [int(d) for d in data[2:]]
110 self.lhacode.sort()
111 self.lhacode = tuple([len(self.lhacode)] + self.lhacode)
112
113 self.value = float(data[0])
114 self.format = 'decay_table'
115
117 """ return a SLAH string """
118
119
120 format = self.format
121 if self.format == 'float':
122 try:
123 value = float(self.value)
124 except:
125 format = 'str'
126 self.comment = self.comment.strip()
127 if not precision:
128 precision = 6
129
130 if format == 'float':
131 if self.lhablock == 'decay' and not isinstance(self.value,six.string_types):
132 return 'DECAY %s %.{0}e # %s'.format(precision) % (' '.join([str(d) for d in self.lhacode]), self.value, self.comment)
133 elif self.lhablock == 'decay':
134 return 'DECAY %s Auto # %s' % (' '.join([str(d) for d in self.lhacode]), self.comment)
135 elif self.lhablock and self.lhablock.startswith('qnumbers'):
136 return ' %s %i # %s' % (' '.join([str(d) for d in self.lhacode]), int(self.value), self.comment)
137 else:
138 return ' %s %.{0}e # %s'.format(precision) % (' '.join([str(d) for d in self.lhacode]), self.value, self.comment)
139 elif format == 'int':
140 return ' %s %i # %s' % (' '.join([str(d) for d in self.lhacode]), int(self.value), self.comment)
141 elif format == 'str':
142 if self.lhablock == 'decay':
143 return 'DECAY %s %s # %s' % (' '.join([str(d) for d in self.lhacode]),self.value, self.comment)
144 return ' %s %s # %s' % (' '.join([str(d) for d in self.lhacode]), self.value, self.comment)
145 elif self.format == 'decay_table':
146 return ' %e %s # %s' % ( self.value,' '.join([str(d) for d in self.lhacode]), self.comment)
147 elif self.format == 'int':
148 return ' %s %i # %s' % (' '.join([str(d) for d in self.lhacode]), int(self.value), self.comment)
149 else:
150 if self.lhablock == 'decay':
151 return 'DECAY %s %d # %s' % (' '.join([str(d) for d in self.lhacode]), self.value, self.comment)
152 else:
153 return ' %s %d # %s' % (' '.join([str(d) for d in self.lhacode]), self.value, self.comment)
154
157 """ list of parameter """
158
160 if name:
161 self.name = name.lower()
162 else:
163 self.name = name
164 self.scale = None
165 self.comment = ''
166 self.decay_table = {}
167 self.param_dict={}
168 list.__init__(self)
169
170 - def get(self, lhacode, default=None):
171 """return the parameter associate to the lhacode"""
172 if not self.param_dict:
173 self.create_param_dict()
174
175 if isinstance(lhacode, int):
176 lhacode = (lhacode,)
177
178 try:
179 return self.param_dict[tuple(lhacode)]
180 except KeyError:
181 if default is None:
182 raise KeyError('id %s is not in %s' % (tuple(lhacode), self.name))
183 else:
184 return Parameter(block=self, lhacode=lhacode, value=default,
185 comment='not define')
186
188
189
190 for old_key, new_key in change_keys.items():
191
192 assert old_key in self.param_dict
193 param = self.param_dict[old_key]
194 del self.param_dict[old_key]
195 self.param_dict[new_key] = param
196 param.lhacode = new_key
197
198
200 """ remove a parameter """
201 list.remove(self, self.get(lhacode))
202
203 return self.param_dict.pop(tuple(lhacode))
204
205 - def __eq__(self, other, prec=1e-4):
206 """ """
207
208 if isinstance(other, str) and ' ' not in other:
209 return self.name.lower() == other.lower()
210
211
212 if len(self) != len(other):
213 return False
214
215 return not any(abs(param.value-other.param_dict[key].value)> prec * abs(param.value)
216 for key, param in self.param_dict.items())
217
218 - def __ne__(self, other, prec=1e-4):
219 return not self.__eq__(other, prec)
220
222
223 assert isinstance(obj, Parameter)
224 if not hasattr(self, 'name'):
225 self.__init__(obj.lhablock)
226 assert not obj.lhablock or obj.lhablock == self.name
227
228
229
230 if not hasattr(self, 'param_dict'):
231 self.param_dict = {}
232
233 if tuple(obj.lhacode) in self.param_dict:
234 if self.param_dict[tuple(obj.lhacode)].value != obj.value:
235 raise InvalidParamCard('%s %s is already define to %s impossible to assign %s' % \
236 (self.name, obj.lhacode, self.param_dict[tuple(obj.lhacode)].value, obj.value))
237 return
238 list.append(self, obj)
239
240 self.param_dict[tuple(obj.lhacode)] = obj
241
243 """create a link between the lhacode and the Parameter"""
244 for param in self:
245 self.param_dict[tuple(param.lhacode)] = param
246
247 return self.param_dict
248
250 """ """
251 self.scale = scale
252
254 "set inforamtion from the line"
255
256 if '#' in text:
257 data, self.comment = text.split('#',1)
258 else:
259 data, self.comment = text, ""
260
261 data = data.lower()
262 data = data.split()
263 self.name = data[1]
264 if len(data) == 3:
265 if data[2].startswith('q='):
266
267 self.scale = float(data[2][2:])
268 elif self.name == 'qnumbers':
269 self.name += ' %s' % data[2]
270 elif len(data) == 4 and data[2] == 'q=':
271
272 self.scale = float(data[3])
273
274 return self
275
277 """returns the list of id define in this blocks"""
278
279 return [p.lhacode for p in self]
280
282 """ return a str in the SLAH format """
283
284 text = """###################################""" + \
285 """\n## INFORMATION FOR %s""" % self.name.upper() +\
286 """\n###################################\n"""
287
288 if self.name == 'decay':
289 for param in self:
290 pid = param.lhacode[0]
291 param.set_block('decay')
292 text += str(param)+ '\n'
293 if pid in self.decay_table:
294 text += str(self.decay_table[pid])+'\n'
295 return text
296 elif self.name.startswith('decay'):
297 text = ''
298
299 elif not self.scale:
300 text += 'BLOCK %s # %s\n' % (self.name.upper(), self.comment)
301 else:
302 text += 'BLOCK %s Q= %e # %s\n' % (self.name.upper(), self.scale, self.comment)
303
304 text += '\n'.join([param.__str__(precision) for param in self])
305 return text + '\n'
306
309 """ a param Card: list of Block """
310 mp_prefix = 'MP__'
311
312 header = \
313 """######################################################################\n""" + \
314 """## PARAM_CARD AUTOMATICALY GENERATED BY MG5 ####\n""" + \
315 """######################################################################\n"""
316
317
319 dict.__init__(self,{})
320 self.order = []
321 self.not_parsed_entry = []
322
323 if isinstance(input_path, ParamCard):
324 self.read(input_path.write())
325 self.input_path = input_path.input_path
326 else:
327 self.input_path = input_path
328 if input_path:
329 self.read(input_path)
330
331 - def read(self, input_path):
332 """ read a card and full this object with the content of the card """
333
334 if isinstance(input_path, str):
335 if '\n' in input_path:
336 input = StringIO.StringIO(input_path)
337 else:
338 input = open(input_path)
339 else:
340 input = input_path
341
342
343 cur_block = None
344 for line in input:
345 line = line.strip()
346 if not line or line[0] == '#':
347 continue
348 line = line.lower()
349 if line.startswith('block'):
350 cur_block = Block()
351 cur_block.load_str(line)
352 self.append(cur_block)
353 continue
354
355 if line.startswith('decay'):
356 if not self.has_block('decay'):
357 cur_block = Block('decay')
358 self.append(cur_block)
359 else:
360 cur_block = self['decay']
361 param = Parameter()
362 param.set_block(cur_block.name)
363 param.load_str(line[6:])
364 cur_block.append(param)
365 continue
366
367 if line.startswith('xsection') or cur_block == 'notparsed':
368 cur_block = 'notparsed'
369 self.not_parsed_entry.append(line)
370 continue
371
372
373 if cur_block is None:
374 continue
375
376 if cur_block.name == 'decay':
377
378 id = cur_block[-1].lhacode[0]
379 cur_block = Block('decay_table_%s' % id)
380 self['decay'].decay_table[id] = cur_block
381
382 if cur_block.name.startswith('decay_table'):
383 param = Parameter()
384 param.load_decay(line)
385 try:
386 cur_block.append(param)
387 except InvalidParamCard:
388 pass
389 else:
390 param = Parameter()
391 param.set_block(cur_block.name)
392 param.load_str(line)
393 cur_block.append(param)
394
395 return self
396
400
403
405 """ Analyzes the comment of the parameter in the param_card and returns
406 a dictionary with parameter names in values and the tuple (lhablock, id)
407 in value as well as a dictionary for restricted values.
408 WARNING: THIS FUNCTION RELIES ON THE FORMATTING OF THE COMMENT IN THE
409 CARD TO FETCH THE PARAMETER NAME. This is mostly ok on the *_default.dat
410 but typically dangerous on the user-defined card."""
411
412 pname2block = {}
413 restricted_value = {}
414
415 for bname, block in self.items():
416 for lha_id, param in block.param_dict.items():
417 all_var = []
418 comment = param.comment
419
420 if comment.strip().startswith('set of param :'):
421 all_var = list(re.findall(r'''[^-]1\*(\w*)\b''', comment))
422
423 elif len(comment.split()) == 1:
424 all_var = [comment.strip().lower()]
425
426 else:
427 split = comment.split()
428 if len(split) >2 and split[1] == ':':
429
430 restricted_value[(bname, lha_id)] = ' '.join(split[1:])
431 elif len(split) == 2:
432 if re.search(r'''\[[A-Z]\]eV\^''', split[1]):
433 all_var = [comment.strip().lower()]
434 elif len(split) >=2 and split[1].startswith('('):
435 all_var = [split[0].strip().lower()]
436 else:
437 if not bname.startswith('qnumbers'):
438 logger.debug("not recognize information for %s %s : %s",
439 bname, lha_id, comment)
440
441 continue
442
443 for var in all_var:
444 var = var.lower()
445 if var in pname2block:
446 pname2block[var].append((bname, lha_id))
447 else:
448 pname2block[var] = [(bname, lha_id)]
449
450 return pname2block, restricted_value
451
453 """update the parameter of the card which are not free parameter
454 (i.e mass and width)
455 loglevel can be: None
456 info
457 warning
458 crash # raise an error
459 return if the param_card was modified or not
460 """
461 modify = False
462 if isinstance(restrict_rule, str):
463 restrict_rule = ParamCardRule(restrict_rule)
464
465
466 if restrict_rule:
467 _, modify = restrict_rule.check_param_card(self, modify=True, log=loglevel)
468
469 import models.model_reader as model_reader
470 import madgraph.core.base_objects as base_objects
471 if not isinstance(model, model_reader.ModelReader):
472 model = model_reader.ModelReader(model)
473 parameters = model.set_parameters_and_couplings(self)
474 else:
475 parameters = model.set_parameters_and_couplings(self)
476
477
478 for particle in model.get('particles'):
479 if particle.get('goldstone') or particle.get('ghost'):
480 continue
481 mass = model.get_parameter(particle.get('mass'))
482 lhacode = abs(particle.get_pdg_code())
483
484 if isinstance(mass, base_objects.ModelVariable) and not isinstance(mass, base_objects.ParamCardVariable):
485 try:
486 param_value = self.get('mass').get(lhacode).value
487 except Exception:
488 param = Parameter(block='mass', lhacode=(lhacode,),value=0,comment='added')
489 param_value = -999.999
490 self.get('mass').append(param)
491 model_value = parameters[particle.get('mass')]
492 if isinstance(model_value, complex):
493 if model_value.imag > 1e-5 * model_value.real:
494 raise Exception("Mass should be real number: particle %s (%s) has mass: %s" % (lhacode, particle.get('name'), model_value))
495 model_value = model_value.real
496
497 if not misc.equal(model_value, param_value, 4):
498 modify = True
499 if loglevel == 20:
500 logger.info('For consistency, the mass of particle %s (%s) is changed to %s.' % (lhacode, particle.get('name'), model_value), '$MG:BOLD')
501 else:
502 logger.log(loglevel, 'For consistency, the mass of particle %s (%s) is changed to %s.' % (lhacode, particle.get('name'), model_value))
503
504 if model_value != param_value:
505 self.get('mass').get(abs(particle.get_pdg_code())).value = model_value
506
507 width = model.get_parameter(particle.get('width'))
508 if isinstance(width, base_objects.ModelVariable):
509 try:
510 param_value = self.get('decay').get(lhacode).value
511 except Exception:
512 param = Parameter(block='decay', lhacode=(lhacode,),value=0,comment='added')
513 param_value = -999.999
514 self.get('decay').append(param)
515 model_value = parameters[particle.get('width')]
516 if isinstance(model_value, complex):
517 if model_value.imag > 1e-5 * model_value.real:
518 raise Exception("Width should be real number: particle %s (%s) has mass: %s")
519 model_value = model_value.real
520 if not misc.equal(abs(model_value), param_value, 4):
521 modify = True
522 if loglevel == 20:
523 logger.info('For consistency, the width of particle %s (%s) is changed to %s.' % (lhacode, particle.get('name'), model_value), '$MG:BOLD')
524 else:
525 logger.log(loglevel,'For consistency, the width of particle %s (%s) is changed to %s.' % (lhacode, particle.get('name'), model_value))
526
527 if abs(model_value) != param_value:
528 self.get('decay').get(abs(particle.get_pdg_code())).value = abs(model_value)
529
530 return modify
531
532
533 - def write(self, outpath=None, precision=''):
534 """schedular for writing a card"""
535
536
537 blocks = self.order_block()
538 text = self.header
539 text += ''.join([block.__str__(precision) for block in blocks])
540 text += '\n'
541 text += '\n'.join(self.not_parsed_entry)
542 if not outpath:
543 return text
544 elif isinstance(outpath, str):
545 open(outpath,'w').write(text)
546 else:
547 outpath.write(text)
548
550 """return a text file allowing to pass from this card to the new one
551 via the set command"""
552
553 diff = ''
554 for blockname, block in self.items():
555 for param in block:
556 lhacode = param.lhacode
557 value = param.value
558 new_value = new_card[blockname].get(lhacode).value
559 if not misc.equal(value, new_value, 6, zero_limit=False):
560 lhacode = ' '.join([str(i) for i in lhacode])
561 diff += 'set param_card %s %s %s # orig: %s\n' % \
562 (blockname, lhacode , new_value, value)
563 return diff
564
565
566 - def get_value(self, blockname, lhecode, default=None):
567 try:
568 return self[blockname].get(lhecode).value
569 except KeyError:
570 if blockname == 'width':
571 blockname = 'decay'
572 return self.get_value(blockname, lhecode,default=default)
573 elif default is not None:
574 return default
575 raise
576
578 """ """
579 missing = set()
580 all_blocks = set(self.keys())
581 for line in open(identpath):
582 if line.startswith('c ') or line.startswith('ccccc'):
583 continue
584 split = line.split()
585 if len(split) < 3:
586 continue
587 block = split[0]
588 if block not in self:
589 missing.add(block)
590 elif block in all_blocks:
591 all_blocks.remove(block)
592
593 unknow = all_blocks
594 return missing, unknow
595
597
598 missing_set, unknow_set = self.get_missing_block(identpath)
599
600 apply_conversion = []
601 if missing_set == set(['fralpha']) and 'alpha' in unknow_set:
602 apply_conversion.append('alpha')
603 elif all([b in missing_set for b in ['te','msl2','dsqmix','tu','selmix','msu2','msq2','usqmix','td', 'mse2','msd2']]) and\
604 all(b in unknow_set for b in ['ae','ad','sbotmix','au','modsel','staumix','stopmix']):
605 apply_conversion.append('to_slha2')
606
607 if 'to_slha2' in apply_conversion:
608 logger.error('Convention for the param_card seems to be wrong. Trying to automatically convert your file to SLHA2 format. \n'+\
609 "Please check that the conversion occurs as expected (The converter is not fully general)")
610
611 param_card =self.input_path
612 convert_to_mg5card(param_card, writting=True)
613 self.clear()
614 self.__init__(param_card)
615
616 if 'alpha' in apply_conversion:
617 logger.info("Missing block fralpha but found a block alpha, apply automatic conversion")
618 self.rename_blocks({'alpha':'fralpha'})
619 self['fralpha'].rename_keys({(): (1,)})
620 self.write(param_card.input_path)
621
622 - def write_inc_file(self, outpath, identpath, default, need_mp=False):
623 """ write a fortran file which hardcode the param value"""
624
625 self.secure_slha2(identpath)
626
627
628 fout = file_writers.FortranWriter(outpath)
629 defaultcard = ParamCard(default)
630 for line in open(identpath):
631 if line.startswith('c ') or line.startswith('ccccc'):
632 continue
633 split = line.split()
634 if len(split) < 3:
635 continue
636 block = split[0]
637 lhaid = [int(i) for i in split[1:-1]]
638 variable = split[-1]
639 if block in self:
640 try:
641 value = self[block].get(tuple(lhaid)).value
642 except KeyError:
643 value =defaultcard[block].get(tuple(lhaid)).value
644 logger.warning('information about \"%s %s" is missing using default value: %s.' %\
645 (block, lhaid, value))
646 else:
647 value =defaultcard[block].get(tuple(lhaid)).value
648 logger.warning('information about \"%s %s" is missing (full block missing) using default value: %s.' %\
649 (block, lhaid, value))
650 value = str(value).lower()
651
652 if block == 'decay':
653 if self['mass'].get(tuple(lhaid)).value < 0:
654 value = '-%s' % value
655
656 fout.writelines(' %s = %s' % (variable, ('%e'%float(value)).replace('e','d')))
657 if need_mp:
658 fout.writelines(' mp__%s = %s_16' % (variable, value))
659
661 """ Convert this param_card to the convention used for the complex mass scheme:
662 This includes, removing the Yukawa block if present and making sure the EW input
663 scheme is (MZ, MW, aewm1). """
664
665
666 if self.has_block('yukawa'):
667
668 for lhacode in [param.lhacode for param in self['yukawa']]:
669 self.remove_param('yukawa', lhacode)
670
671
672 EW_input = {('sminputs',(1,)):None,
673 ('sminputs',(2,)):None,
674 ('mass',(23,)):None,
675 ('mass',(24,)):None}
676 for block, lhaid in EW_input.keys():
677 try:
678 EW_input[(block,lhaid)] = self[block].get(lhaid).value
679 except:
680 pass
681
682
683
684
685 internal_param = [key for key,value in EW_input.items() if value is None]
686 if len(internal_param)==0:
687
688 return
689
690 if len(internal_param)!=1:
691 raise InvalidParamCard(' The specified EW inputs has more than one'+\
692 ' unknown: [%s]'%(','.join([str(elem) for elem in internal_param])))
693
694
695 if not internal_param[0] in [('mass',(24,)), ('sminputs',(2,)),
696 ('sminputs',(1,))]:
697 raise InvalidParamCard(' The only EW input scheme currently supported'+\
698 ' are those with either the W mass or GF left internal.')
699
700
701 if internal_param[0] == ('mass',(24,)):
702 aewm1 = EW_input[('sminputs',(1,))]
703 Gf = EW_input[('sminputs',(2,))]
704 Mz = EW_input[('mass',(23,))]
705 try:
706 Mw = math.sqrt((Mz**2/2.0)+math.sqrt((Mz**4/4.0)-((
707 (1.0/aewm1)*math.pi*Mz**2)/(Gf*math.sqrt(2.0)))))
708 except:
709 InvalidParamCard, 'The EW inputs 1/a_ew=%f, Gf=%f, Mz=%f are inconsistent'%\
710 (aewm1,Gf,Mz)
711 self.remove_param('sminputs', (2,))
712 self.add_param('mass', (24,), Mw, 'MW')
713
715 """add an object to this"""
716
717 assert isinstance(obj, Block)
718 self[obj.name] = obj
719 if not obj.name.startswith('decay_table'):
720 self.order.append(obj)
721
722
723
726
728 """ reorganize the block """
729 return self.order
730
732 """ rename the blocks """
733
734 for old_name, new_name in name_dict.items():
735 self[new_name] = self.pop(old_name)
736 self[new_name].name = new_name
737 for param in self[new_name]:
738 param.lhablock = new_name
739
741 """ remove a blocks """
742 assert len(self[name])==0
743 [self.order.pop(i) for i,b in enumerate(self.order) if b.name == name]
744 self.pop(name)
745
747 """ remove a parameter """
748 if self.has_param(block, lhacode):
749 self[block].remove(lhacode)
750 if len(self[block]) == 0:
751 self.remove_block(block)
752
754 """check if param exists"""
755
756 try:
757 self[block].get(lhacode)
758 except:
759 return False
760 else:
761 return True
762
763 - def copy_param(self,old_block, old_lha, block=None, lhacode=None):
764 """ make a parameter, a symbolic link on another one """
765
766
767 old_block_obj = self[old_block]
768 parameter = old_block_obj.get(old_lha)
769 if not block:
770 block = old_block
771 if not lhacode:
772 lhacode = old_lha
773
774 self.add_param(block, lhacode, parameter.value, parameter.comment)
775
776 - def add_param(self,block, lha, value, comment=''):
777
778 parameter = Parameter(block=block, lhacode=lha, value=value,
779 comment=comment)
780 try:
781 new_block = self[block]
782 except KeyError:
783
784 new_block = Block(block)
785 self.append(new_block)
786 new_block.append(parameter)
787
788 - def do_help(self, block, lhacode, default=None):
789
790 if not lhacode:
791 logger.info("Information on block parameter %s:" % block, '$MG:color:BLUE')
792 print(str(self[block]))
793 elif default:
794 pname2block, restricted = default.analyze_param_card()
795 if (block, lhacode) in restricted:
796 logger.warning("This parameter will not be consider by MG5_aMC")
797 print( " MadGraph will use the following formula:")
798 print(restricted[(block, lhacode)])
799 print( " Note that some code (MadSpin/Pythia/...) will read directly the value")
800 else:
801 for name, values in pname2block.items():
802 if (block, lhacode) in values:
803 valid_name = name
804 break
805 logger.info("Information for parameter %s of the param_card" % valid_name, '$MG:color:BLUE')
806 print(("Part of Block \"%s\" with identification number %s" % (block, lhacode)))
807 print(("Current value: %s" % self[block].get(lhacode).value))
808 print(("Default value: %s" % default[block].get(lhacode).value))
809 print(("comment present in the cards: %s " % default[block].get(lhacode).comment))
810
811
812
813
814 - def mod_param(self, old_block, old_lha, block=None, lhacode=None,
815 value=None, comment=None):
816 """ change a parameter to a new one. This is not a duplication."""
817
818
819 old_block = self[old_block]
820 try:
821 parameter = old_block.get(old_lha)
822 except:
823 if lhacode is not None:
824 lhacode=old_lha
825 self.add_param(block, lhacode, value, comment)
826 return
827
828
829
830 if block:
831 parameter.lhablock = block
832 if lhacode:
833 parameter.lhacode = lhacode
834 if value:
835 parameter.value = value
836 if comment:
837 parameter.comment = comment
838
839
840 if block:
841 old_block.remove(old_lha)
842 if not len(old_block):
843 self.remove_block(old_block.name)
844 try:
845 new_block = self[block]
846 except KeyError:
847
848 new_block = Block(block)
849 self.append(new_block)
850 new_block.append(parameter)
851 elif lhacode:
852 old_block.param_dict[tuple(lhacode)] = \
853 old_block.param_dict.pop(tuple(old_lha))
854
855
857 """ check that the value is coherent and remove it"""
858
859 if self.has_param(block, lhacode):
860 param = self[block].get(lhacode)
861 if param.value != value:
862 error_msg = 'This card is not suitable to be convert to SLAH1\n'
863 error_msg += 'Parameter %s %s should be %s' % (block, lhacode, value)
864 raise InvalidParamCard(error_msg)
865 self.remove_param(block, lhacode)
866
869 """ a param Card: list of Block with also MP definition of variables"""
870
872 """ write a fortran file which hardcode the param value"""
873
874 fout = file_writers.FortranWriter(outpath)
875 defaultcard = ParamCard(default)
876 for line in open(identpath):
877 if line.startswith('c ') or line.startswith('ccccc'):
878 continue
879 split = line.split()
880 if len(split) < 3:
881 continue
882 block = split[0]
883 lhaid = [int(i) for i in split[1:-1]]
884 variable = split[-1]
885 if block in self:
886 try:
887 value = self[block].get(tuple(lhaid)).value
888 except KeyError:
889 value =defaultcard[block].get(tuple(lhaid)).value
890 else:
891 value =defaultcard[block].get(tuple(lhaid)).value
892
893 fout.writelines(' %s = %s' % (variable, ('%e' % value).replace('e','d')))
894 fout.writelines(' %s%s = %s_16' % (self.mp_prefix,
895 variable, ('%e' % value)))
896
901 """A class keeping track of the scan: flag in the param_card and
902 having an __iter__() function to scan over all the points of the scan.
903 """
904
905 logging = True
911
913 """generate the next param_card (in a abstract way) related to the scan.
914 Technically this generates only the generator."""
915
916 if hasattr(self, 'iterator'):
917 return self.iterator
918 self.iterator = self.iterate()
919 return self.iterator
920
921 - def next(self, autostart=False):
922 """call the next iteration value"""
923 try:
924 iterator = self.iterator
925 except:
926 if autostart:
927 iterator = self.__iter__()
928 else:
929 raise
930 try:
931 out = next(iterator)
932 except StopIteration:
933 del self.iterator
934 raise
935 return out
936
938 """create the actual generator"""
939 all_iterators = {}
940 pattern = re.compile(r'''scan\s*(?P<id>\d*)\s*:\s*(?P<value>[^#]*)''', re.I)
941 self.autowidth = []
942
943
944 for block in self.order:
945 for param in block:
946 if isinstance(param.value, str) and param.value.strip().lower().startswith('scan'):
947 try:
948 key, def_list = pattern.findall(param.value)[0]
949 except:
950 raise Exception("Fail to handle scanning tag: Please check that the syntax is valid")
951 if key == '':
952 key = -1 * len(all_iterators)
953 if key not in all_iterators:
954 all_iterators[key] = []
955 try:
956 all_iterators[key].append( (param, eval(def_list)))
957 except SyntaxError as error:
958 raise Exception("Fail to handle your scan definition. Please check your syntax:\n entry: %s \n Error reported: %s" %(def_list, error))
959 elif isinstance(param.value, str) and param.value.strip().lower().startswith('auto'):
960 self.autowidth.append(param)
961 keys = list(all_iterators.keys())
962 param_card = ParamCard(self)
963
964 for key in keys:
965 for param, values in all_iterators[key]:
966 self.param_order.append("%s#%s" % (param.lhablock, '_'.join(repr(i) for i in param.lhacode)))
967
968
969 lengths = [list(range(len(all_iterators[key][0][1]))) for key in keys]
970 for positions in itertools.product(*lengths):
971 self.itertag = []
972 if self.logging:
973 logger.info("Create the next param_card in the scan definition", '$MG:BOLD')
974 for i, pos in enumerate(positions):
975 key = keys[i]
976 for param, values in all_iterators[key]:
977
978 param_card[param.lhablock].get(param.lhacode).value = values[pos]
979 self.itertag.append(values[pos])
980 if self.logging:
981 logger.info("change parameter %s with code %s to %s", \
982 param.lhablock, param.lhacode, values[pos])
983
984
985
986 yield param_card
987
988
989 - def store_entry(self, run_name, cross, error=None, param_card_path=None):
990 """store the value of the cross-section"""
991
992 if isinstance(cross, dict):
993 info = dict(cross)
994 info.update({'bench' : self.itertag, 'run_name': run_name})
995 self.cross.append(info)
996 else:
997 if error is None:
998 self.cross.append({'bench' : self.itertag, 'run_name': run_name, 'cross(pb)':cross})
999 else:
1000 self.cross.append({'bench' : self.itertag, 'run_name': run_name, 'cross(pb)':cross, 'error(pb)':error})
1001
1002 if self.autowidth and param_card_path:
1003 paramcard = ParamCard(param_card_path)
1004 for param in self.autowidth:
1005 self.cross[-1]['width#%s' % param.lhacode[0]] = paramcard.get_value(param.lhablock, param.lhacode)
1006
1007
1008 - def write_summary(self, path, order=None, lastline=False, nbcol=20):
1009 """ """
1010
1011 if path:
1012 ff = open(path, 'w')
1013 else:
1014 ff = StringIO.StringIO()
1015 if order:
1016 keys = order
1017 else:
1018 keys = list(self.cross[0].keys())
1019 if 'bench' in keys: keys.remove('bench')
1020 if 'run_name' in keys: keys.remove('run_name')
1021 keys.sort()
1022 if 'cross(pb)' in keys:
1023 keys.remove('cross(pb)')
1024 keys.append('cross(pb)')
1025 if 'error(pb)' in keys:
1026 keys.remove('error(pb)')
1027 keys.append('error(pb)')
1028
1029 formatting = "#%s%s%s\n" %('%%-%is ' % (nbcol-1), ('%%-%is ' % (nbcol))* len(self.param_order),
1030 ('%%-%is ' % (nbcol))* len(keys))
1031
1032 if not lastline:
1033 ff.write(formatting % tuple(['run_name'] + self.param_order + keys))
1034 formatting = "%s%s%s\n" %('%%-%is ' % (nbcol), ('%%-%ie ' % (nbcol))* len(self.param_order),
1035 ('%%-%ie ' % (nbcol))* len(keys))
1036
1037
1038 if not lastline:
1039 to_print = self.cross
1040 else:
1041 to_print = self.cross[-1:]
1042
1043 for info in to_print:
1044 name = info['run_name']
1045 bench = info['bench']
1046 data = []
1047 for k in keys:
1048 if k in info:
1049 data.append(info[k])
1050 else:
1051 data.append(0.)
1052 ff.write(formatting % tuple([name] + bench + data))
1053
1054 if not path:
1055 return ff.getvalue()
1056
1057
1059 """returns a smart name for the next run"""
1060
1061 if '_' in run_name:
1062 name, value = run_name.rsplit('_',1)
1063 if value.isdigit():
1064 return '%s_%02i' % (name, float(value)+1)
1065
1066 return '%s_scan_02' % run_name
1067
1071 """ A class for storing the linked between the different parameter of
1072 the param_card.
1073 Able to write a file 'param_card_rule.dat'
1074 Able to read a file 'param_card_rule.dat'
1075 Able to check the validity of a param_card.dat
1076 """
1077
1078
1080 """initialize an object """
1081
1082
1083 self.zero = []
1084 self.one = []
1085 self.identical = []
1086 self.opposite = []
1087
1088
1089 self.rule = []
1090
1091 if inputpath:
1092 self.load_rule(inputpath)
1093
1094 - def add_zero(self, lhablock, lhacode, comment=''):
1095 """add a zero rule"""
1096 self.zero.append( (lhablock, lhacode, comment) )
1097
1098 - def add_one(self, lhablock, lhacode, comment=''):
1099 """add a one rule"""
1100 self.one.append( (lhablock, lhacode, comment) )
1101
1102 - def add_identical(self, lhablock, lhacode, lhacode2, comment=''):
1103 """add a rule for identical value"""
1104 self.identical.append( (lhablock, lhacode, lhacode2, comment) )
1105
1106 - def add_opposite(self, lhablock, lhacode, lhacode2, comment=''):
1107 """add a rule for identical value"""
1108 self.opposite.append( (lhablock, lhacode, lhacode2, comment) )
1109
1110
1111 - def add_rule(self, lhablock, lhacode, rule, comment=''):
1112 """add a rule for constraint value"""
1113 self.rule.append( (lhablock, lhacode, rule) )
1114
1116
1117 text = """<file>######################################################################
1118 ## VALIDITY RULE FOR THE PARAM_CARD ####
1119 ######################################################################\n"""
1120
1121
1122 text +='<zero>\n'
1123 for name, id, comment in self.zero:
1124 text+=' %s %s # %s\n' % (name, ' '.join([str(i) for i in id]),
1125 comment)
1126
1127 text +='</zero>\n<one>\n'
1128 for name, id, comment in self.one:
1129 text+=' %s %s # %s\n' % (name, ' '.join([str(i) for i in id]),
1130 comment)
1131
1132 text +='</one>\n<identical>\n'
1133 for name, id,id2, comment in self.identical:
1134 text+=' %s %s : %s # %s\n' % (name, ' '.join([str(i) for i in id]),
1135 ' '.join([str(i) for i in id2]), comment)
1136
1137
1138 text +='</identical>\n<opposite>\n'
1139 for name, id,id2, comment in self.opposite:
1140 text+=' %s %s : %s # %s\n' % (name, ' '.join([str(i) for i in id]),
1141 ' '.join([str(i) for i in id2]), comment)
1142
1143
1144 text += '</opposite>\n<constraint>\n'
1145 for name, id, rule, comment in self.rule:
1146 text += ' %s %s : %s # %s\n' % (name, ' '.join([str(i) for i in id]),
1147 rule, comment)
1148 text += '</constraint>\n</file>'
1149
1150 if isinstance(output, str):
1151 output = open(output,'w')
1152 if hasattr(output, 'write'):
1153 output.write(text)
1154 return text
1155
1157 """ import a validity rule file """
1158
1159
1160 try:
1161 tree = ET.parse(inputpath)
1162 except IOError:
1163 if '\n' in inputpath:
1164
1165 tree = ET.fromstring(inputpath)
1166 else:
1167 raise
1168
1169
1170 element = tree.find('zero')
1171 if element is not None:
1172 for line in element.text.split('\n'):
1173 line = line.split('#',1)[0]
1174 if not line:
1175 continue
1176 lhacode = line.split()
1177 blockname = lhacode.pop(0)
1178 lhacode = [int(code) for code in lhacode ]
1179 self.add_zero(blockname, lhacode, '')
1180
1181
1182 element = tree.find('one')
1183 if element is not None:
1184 for line in element.text.split('\n'):
1185 line = line.split('#',1)[0]
1186 if not line:
1187 continue
1188 lhacode = line.split()
1189 blockname = lhacode.pop(0)
1190 lhacode = [int(code) for code in lhacode ]
1191 self.add_one(blockname, lhacode, '')
1192
1193
1194 element = tree.find('identical')
1195 if element is not None:
1196 for line in element.text.split('\n'):
1197 line = line.split('#',1)[0]
1198 if not line:
1199 continue
1200 line, lhacode2 = line.split(':')
1201 lhacode = line.split()
1202 blockname = lhacode.pop(0)
1203 lhacode = [int(code) for code in lhacode ]
1204 lhacode2 = [int(code) for code in lhacode2.split() ]
1205 self.add_identical(blockname, lhacode, lhacode2, '')
1206
1207
1208 element = tree.find('opposite')
1209 if element is not None:
1210 for line in element.text.split('\n'):
1211 line = line.split('#',1)[0]
1212 if not line:
1213 continue
1214 line, lhacode2 = line.split(':')
1215 lhacode = line.split()
1216 blockname = lhacode.pop(0)
1217 lhacode = [int(code) for code in lhacode ]
1218 lhacode2 = [int(code) for code in lhacode2.split() ]
1219 self.add_opposite(blockname, lhacode, lhacode2, '')
1220
1221
1222 element = tree.find('rule')
1223 if element is not None:
1224 for line in element.text.split('\n'):
1225 line = line.split('#',1)[0]
1226 if not line:
1227 continue
1228 line, rule = line.split(':')
1229 lhacode = line.split()
1230 blockname = lhacode.pop(0)
1231 self.add_rule(blockname, lhacode, rule, '')
1232
1233 @staticmethod
1235 """ read a param_card and return a dictionary with the associated value."""
1236
1237 output = ParamCard(path)
1238
1239
1240
1241 return output
1242
1243 @staticmethod
1255
1256
1257 - def check_param_card(self, path, modify=False, write_missing=False, log=False):
1258 """Check that the restriction card are applied"""
1259
1260 is_modified = False
1261
1262 if isinstance(path,str):
1263 card = self.read_param_card(path)
1264 else:
1265 card = path
1266
1267
1268 for block, id, comment in self.zero:
1269 try:
1270 value = float(card[block].get(id).value)
1271 except KeyError:
1272 if modify and write_missing:
1273 new_param = Parameter(block=block,lhacode=id, value=0,
1274 comment='fixed by the model')
1275 if block in card:
1276 card[block].append(new_param)
1277 else:
1278 new_block = Block(block)
1279 card.append(new_block)
1280 new_block.append(new_param)
1281 else:
1282 if value != 0:
1283 if not modify:
1284 raise InvalidParamCard('parameter %s: %s is not at zero' % \
1285 (block, ' '.join([str(i) for i in id])))
1286 else:
1287 param = card[block].get(id)
1288 param.value = 0.0
1289 param.comment += ' fixed by the model'
1290 is_modified = True
1291 if log ==20:
1292 logger.log(log,'For model consistency, update %s with id %s to value %s',
1293 block, id, 0.0, '$MG:BOLD')
1294 elif log:
1295 logger.log(log,'For model consistency, update %s with id %s to value %s',
1296 block, id, 0.0)
1297
1298
1299 for block, id, comment in self.one:
1300 try:
1301 value = card[block].get(id).value
1302 except KeyError:
1303 if modify and write_missing:
1304 new_param = Parameter(block=block,lhacode=id, value=1,
1305 comment='fixed by the model')
1306 if block in card:
1307 card[block].append(new_param)
1308 else:
1309 new_block = Block(block)
1310 card.append(new_block)
1311 new_block.append(new_param)
1312 else:
1313 if value != 1:
1314 if not modify:
1315 raise InvalidParamCard('parameter %s: %s is not at one but at %s' % \
1316 (block, ' '.join([str(i) for i in id]), value))
1317 else:
1318 param = card[block].get(id)
1319 param.value = 1.0
1320 param.comment += ' fixed by the model'
1321 is_modified = True
1322 if log ==20:
1323 logger.log(log,'For model consistency, update %s with id %s to value %s',
1324 (block, id, 1.0), '$MG:BOLD')
1325 elif log:
1326 logger.log(log,'For model consistency, update %s with id %s to value %s',
1327 (block, id, 1.0))
1328
1329
1330
1331 for block, id1, id2, comment in self.identical:
1332 if block not in card:
1333 is_modified = True
1334 logger.warning('''Param card is not complete: Block %s is simply missing.
1335 We will use model default for all missing value! Please cross-check that
1336 this correspond to your expectation.''' % block)
1337 continue
1338 value2 = float(card[block].get(id2).value)
1339 try:
1340 param = card[block].get(id1)
1341 except KeyError:
1342 if modify and write_missing:
1343 new_param = Parameter(block=block,lhacode=id1, value=value2,
1344 comment='must be identical to %s' %id2)
1345 card[block].append(new_param)
1346 else:
1347 value1 = float(param.value)
1348
1349 if value1 != value2:
1350 if not modify:
1351 raise InvalidParamCard('parameter %s: %s is not to identical to parameter %s' % \
1352 (block, ' '.join([str(i) for i in id1]),
1353 ' '.join([str(i) for i in id2])))
1354 else:
1355 param = card[block].get(id1)
1356 param.value = value2
1357 param.comment += ' must be identical to %s' % id2
1358 is_modified = True
1359 if log ==20:
1360 logger.log(log,'For model consistency, update %s with id %s to value %s since it should be equal to parameter with id %s',
1361 block, id1, value2, id2, '$MG:BOLD')
1362 elif log:
1363 logger.log(log,'For model consistency, update %s with id %s to value %s since it should be equal to parameter with id %s',
1364 block, id1, value2, id2)
1365
1366 for block, id1, id2, comment in self.opposite:
1367 value2 = float(card[block].get(id2).value)
1368 try:
1369 param = card[block].get(id1)
1370 except KeyError:
1371 if modify and write_missing:
1372 new_param = Parameter(block=block,lhacode=id1, value=-value2,
1373 comment='must be opposite to to %s' %id2)
1374 card[block].append(new_param)
1375 else:
1376 value1 = float(param.value)
1377
1378 if value1 != -value2:
1379 if not modify:
1380 raise InvalidParamCard('parameter %s: %s is not to opposite to parameter %s' % \
1381 (block, ' '.join([str(i) for i in id1]),
1382 ' '.join([str(i) for i in id2])))
1383 else:
1384 param = card[block].get(id1)
1385 param.value = -value2
1386 param.comment += ' must be opposite to %s' % id2
1387 is_modified = True
1388 if log ==20:
1389 logger.log(log,'For model consistency, update %s with id %s to value %s since it should be equal to the opposite of the parameter with id %s',
1390 block, id1, -value2, id2, '$MG:BOLD')
1391 elif log:
1392 logger.log(log,'For model consistency, update %s with id %s to value %s since it should be equal to the opposite of the parameter with id %s',
1393 block, id1, -value2, id2)
1394
1395 return card, is_modified
1396
1399 """ """
1400
1401 if not outputpath:
1402 outputpath = path
1403 card = ParamCard(path)
1404 if not 'usqmix' in card:
1405
1406 card.write(outputpath)
1407 return
1408
1409
1410
1411 card.copy_param('mass', [6], 'sminputs', [6])
1412 card.copy_param('mass', [15], 'sminputs', [7])
1413 card.copy_param('mass', [23], 'sminputs', [4])
1414
1415
1416
1417 card.add_param('modsel',[1], value=1)
1418 card['modsel'].get([1]).format = 'int'
1419
1420
1421 scale = card['hmix'].scale
1422 if not scale:
1423 scale = 1
1424
1425
1426 if not card.has_param('sminputs', [2]):
1427 aem1 = card['sminputs'].get([1]).value
1428 mz = card['mass'].get([23]).value
1429 mw = card['mass'].get([24]).value
1430 gf = math.pi / math.sqrt(2) / aem1 * mz**2/ mw**2 /(mz**2-mw**2)
1431 card.add_param('sminputs', [2], gf, 'G_F [GeV^-2]')
1432
1433
1434 card.check_and_remove('usqmix', [1,1], 1.0)
1435 card.check_and_remove('usqmix', [2,2], 1.0)
1436 card.check_and_remove('usqmix', [4,4], 1.0)
1437 card.check_and_remove('usqmix', [5,5], 1.0)
1438 card.mod_param('usqmix', [3,3], 'stopmix', [1,1])
1439 card.mod_param('usqmix', [3,6], 'stopmix', [1,2])
1440 card.mod_param('usqmix', [6,3], 'stopmix', [2,1])
1441 card.mod_param('usqmix', [6,6], 'stopmix', [2,2])
1442
1443
1444 card.check_and_remove('dsqmix', [1,1], 1.0)
1445 card.check_and_remove('dsqmix', [2,2], 1.0)
1446 card.check_and_remove('dsqmix', [4,4], 1.0)
1447 card.check_and_remove('dsqmix', [5,5], 1.0)
1448 card.mod_param('dsqmix', [3,3], 'sbotmix', [1,1])
1449 card.mod_param('dsqmix', [3,6], 'sbotmix', [1,2])
1450 card.mod_param('dsqmix', [6,3], 'sbotmix', [2,1])
1451 card.mod_param('dsqmix', [6,6], 'sbotmix', [2,2])
1452
1453
1454
1455 card.check_and_remove('selmix', [1,1], 1.0)
1456 card.check_and_remove('selmix', [2,2], 1.0)
1457 card.check_and_remove('selmix', [4,4], 1.0)
1458 card.check_and_remove('selmix', [5,5], 1.0)
1459 card.mod_param('selmix', [3,3], 'staumix', [1,1])
1460 card.mod_param('selmix', [3,6], 'staumix', [1,2])
1461 card.mod_param('selmix', [6,3], 'staumix', [2,1])
1462 card.mod_param('selmix', [6,6], 'staumix', [2,2])
1463
1464
1465 card.mod_param('fralpha', [1], 'alpha', [' '])
1466
1467
1468 if not card.has_param('hmix', [3]):
1469 aem1 = card['sminputs'].get([1]).value
1470 tanb = card['hmix'].get([2]).value
1471 mz = card['mass'].get([23]).value
1472 mw = card['mass'].get([24]).value
1473 sw = math.sqrt(mz**2 - mw**2)/mz
1474 ee = 2 * math.sqrt(1/aem1) * math.sqrt(math.pi)
1475 vu = 2 * mw *sw /ee * math.sin(math.atan(tanb))
1476 card.add_param('hmix', [3], vu, 'higgs vev(Q) MSSM DRb')
1477 card['hmix'].scale= scale
1478
1479
1480 card.check_and_remove('vckm', [1,1], 1.0)
1481 card.check_and_remove('vckm', [2,2], 1.0)
1482 card.check_and_remove('vckm', [3,3], 1.0)
1483
1484
1485 card.check_and_remove('snumix', [1,1], 1.0)
1486 card.check_and_remove('snumix', [2,2], 1.0)
1487 card.check_and_remove('snumix', [3,3], 1.0)
1488
1489
1490 card.check_and_remove('upmns', [1,1], 1.0)
1491 card.check_and_remove('upmns', [2,2], 1.0)
1492 card.check_and_remove('upmns', [3,3], 1.0)
1493
1494
1495 ye = card['ye'].get([3, 3]).value
1496 te = card['te'].get([3, 3]).value
1497 card.mod_param('te', [3,3], 'ae', [3,3], value= te/ye, comment='A_tau(Q) DRbar')
1498 card.add_param('ae', [1,1], 0, 'A_e(Q) DRbar')
1499 card.add_param('ae', [2,2], 0, 'A_mu(Q) DRbar')
1500 card['ae'].scale = scale
1501 card['ye'].scale = scale
1502
1503
1504 yu = card['yu'].get([3, 3]).value
1505 tu = card['tu'].get([3, 3]).value
1506 card.mod_param('tu', [3,3], 'au', [3,3], value= tu/yu, comment='A_t(Q) DRbar')
1507 card.add_param('au', [1,1], 0, 'A_u(Q) DRbar')
1508 card.add_param('au', [2,2], 0, 'A_c(Q) DRbar')
1509 card['au'].scale = scale
1510 card['yu'].scale = scale
1511
1512
1513 yd = card['yd'].get([3, 3]).value
1514 td = card['td'].get([3, 3]).value
1515 if td:
1516 card.mod_param('td', [3,3], 'ad', [3,3], value= td/yd, comment='A_b(Q) DRbar')
1517 else:
1518 card.mod_param('td', [3,3], 'ad', [3,3], value= 0., comment='A_b(Q) DRbar')
1519 card.add_param('ad', [1,1], 0, 'A_d(Q) DRbar')
1520 card.add_param('ad', [2,2], 0, 'A_s(Q) DRbar')
1521 card['ad'].scale = scale
1522 card['yd'].scale = scale
1523
1524
1525 value = card['msl2'].get([1, 1]).value
1526 card.mod_param('msl2', [1,1], 'msoft', [31], math.sqrt(value))
1527 value = card['msl2'].get([2, 2]).value
1528 card.mod_param('msl2', [2,2], 'msoft', [32], math.sqrt(value))
1529 value = card['msl2'].get([3, 3]).value
1530 card.mod_param('msl2', [3,3], 'msoft', [33], math.sqrt(value))
1531 card['msoft'].scale = scale
1532
1533
1534 value = card['mse2'].get([1, 1]).value
1535 card.mod_param('mse2', [1,1], 'msoft', [34], math.sqrt(value))
1536 value = card['mse2'].get([2, 2]).value
1537 card.mod_param('mse2', [2,2], 'msoft', [35], math.sqrt(value))
1538 value = card['mse2'].get([3, 3]).value
1539 card.mod_param('mse2', [3,3], 'msoft', [36], math.sqrt(value))
1540
1541
1542 value = card['msq2'].get([1, 1]).value
1543 card.mod_param('msq2', [1,1], 'msoft', [41], math.sqrt(value))
1544 value = card['msq2'].get([2, 2]).value
1545 card.mod_param('msq2', [2,2], 'msoft', [42], math.sqrt(value))
1546 value = card['msq2'].get([3, 3]).value
1547 card.mod_param('msq2', [3,3], 'msoft', [43], math.sqrt(value))
1548
1549
1550 value = card['msu2'].get([1, 1]).value
1551 card.mod_param('msu2', [1,1], 'msoft', [44], math.sqrt(value))
1552 value = card['msu2'].get([2, 2]).value
1553 card.mod_param('msu2', [2,2], 'msoft', [45], math.sqrt(value))
1554 value = card['msu2'].get([3, 3]).value
1555 card.mod_param('msu2', [3,3], 'msoft', [46], math.sqrt(value))
1556
1557
1558 value = card['msd2'].get([1, 1]).value
1559 card.mod_param('msd2', [1,1], 'msoft', [47], math.sqrt(value))
1560 value = card['msd2'].get([2, 2]).value
1561 card.mod_param('msd2', [2,2], 'msoft', [48], math.sqrt(value))
1562 value = card['msd2'].get([3, 3]).value
1563 card.mod_param('msd2', [3,3], 'msoft', [49], math.sqrt(value))
1564
1565
1566
1567
1568
1569
1570 card.write(outputpath)
1571
1575 """
1576 """
1577
1578 if not outputpath:
1579 outputpath = path
1580 card = ParamCard(path)
1581 if 'usqmix' in card:
1582
1583 if outputpath != path and writting:
1584 card.write(outputpath)
1585 return card
1586
1587
1588
1589 card.remove_param('sminputs', [2])
1590 card.remove_param('sminputs', [4])
1591 card.remove_param('sminputs', [6])
1592 card.remove_param('sminputs', [7])
1593
1594
1595
1596 card.remove_param('modsel',[1])
1597
1598
1599
1600 card.add_param('usqmix', [1,1], 1.0)
1601 card.add_param('usqmix', [2,2], 1.0)
1602 card.add_param('usqmix', [4,4], 1.0)
1603 card.add_param('usqmix', [5,5], 1.0)
1604 card.mod_param('stopmix', [1,1], 'usqmix', [3,3])
1605 card.mod_param('stopmix', [1,2], 'usqmix', [3,6])
1606 card.mod_param('stopmix', [2,1], 'usqmix', [6,3])
1607 card.mod_param('stopmix', [2,2], 'usqmix', [6,6])
1608
1609
1610 card.add_param('dsqmix', [1,1], 1.0)
1611 card.add_param('dsqmix', [2,2], 1.0)
1612 card.add_param('dsqmix', [4,4], 1.0)
1613 card.add_param('dsqmix', [5,5], 1.0)
1614 card.mod_param('sbotmix', [1,1], 'dsqmix', [3,3])
1615 card.mod_param('sbotmix', [1,2], 'dsqmix', [3,6])
1616 card.mod_param('sbotmix', [2,1], 'dsqmix', [6,3])
1617 card.mod_param('sbotmix', [2,2], 'dsqmix', [6,6])
1618
1619
1620
1621 card.add_param('selmix', [1,1], 1.0)
1622 card.add_param('selmix', [2,2], 1.0)
1623 card.add_param('selmix', [4,4], 1.0)
1624 card.add_param('selmix', [5,5], 1.0)
1625 card.mod_param('staumix', [1,1], 'selmix', [3,3])
1626 card.mod_param('staumix', [1,2], 'selmix', [3,6])
1627 card.mod_param('staumix', [2,1], 'selmix', [6,3])
1628 card.mod_param('staumix', [2,2], 'selmix', [6,6])
1629
1630
1631 card.mod_param('alpha', [], 'fralpha', [1])
1632
1633
1634 card.remove_param('hmix', [3])
1635
1636
1637 card.add_param('vckm', [1,1], 1.0)
1638 card.add_param('vckm', [2,2], 1.0)
1639 card.add_param('vckm', [3,3], 1.0)
1640
1641
1642 card.add_param('snumix', [1,1], 1.0)
1643 card.add_param('snumix', [2,2], 1.0)
1644 card.add_param('snumix', [3,3], 1.0)
1645
1646
1647 card.add_param('upmns', [1,1], 1.0)
1648 card.add_param('upmns', [2,2], 1.0)
1649 card.add_param('upmns', [3,3], 1.0)
1650
1651
1652 ye = card['ye'].get([1, 1], default=0).value
1653 ae = card['ae'].get([1, 1], default=0).value
1654 card.mod_param('ae', [1,1], 'te', [1,1], value= ae * ye, comment='T_e(Q) DRbar')
1655 if ae * ye:
1656 raise InvalidParamCard('''This card is not suitable to be converted to MSSM UFO model
1657 Parameter ae [1, 1] times ye [1,1] should be 0''')
1658 card.remove_param('ae', [1,1])
1659
1660 ye = card['ye'].get([2, 2], default=0).value
1661
1662 ae = card['ae'].get([2, 2], default=0).value
1663 card.mod_param('ae', [2,2], 'te', [2,2], value= ae * ye, comment='T_mu(Q) DRbar')
1664 if ae * ye:
1665 raise InvalidParamCard('''This card is not suitable to be converted to MSSM UFO model
1666 Parameter ae [2, 2] times ye [2,2] should be 0''')
1667 card.remove_param('ae', [2,2])
1668
1669 ye = card['ye'].get([3, 3], default=0).value
1670 ae = card['ae'].get([3, 3], default=0).value
1671 card.mod_param('ae', [3,3], 'te', [3,3], value= ae * ye, comment='T_tau(Q) DRbar')
1672
1673
1674 yu = card['yu'].get([1, 1], default=0).value
1675 au = card['au'].get([1, 1], default=0).value
1676 card.mod_param('au', [1,1], 'tu', [1,1], value= au * yu, comment='T_u(Q) DRbar')
1677 if au * yu:
1678 raise InvalidParamCard('''This card is not suitable to be converted to MSSM UFO model
1679 Parameter au [1, 1] times yu [1,1] should be 0''')
1680 card.remove_param('au', [1,1])
1681
1682 ye = card['yu'].get([2, 2], default=0).value
1683
1684 ae = card['au'].get([2, 2], default=0).value
1685 card.mod_param('au', [2,2], 'tu', [2,2], value= au * yu, comment='T_c(Q) DRbar')
1686 if au * yu:
1687 raise InvalidParamCard('''This card is not suitable to be converted to MSSM UFO model
1688 Parameter au [2, 2] times yu [2,2] should be 0''')
1689 card.remove_param('au', [2,2])
1690
1691 yu = card['yu'].get([3, 3]).value
1692 au = card['au'].get([3, 3]).value
1693 card.mod_param('au', [3,3], 'tu', [3,3], value= au * yu, comment='T_t(Q) DRbar')
1694
1695
1696 yd = card['yd'].get([1, 1], default=0).value
1697 ad = card['ad'].get([1, 1], default=0).value
1698 card.mod_param('ad', [1,1], 'td', [1,1], value= ad * yd, comment='T_d(Q) DRbar')
1699 if ad * yd:
1700 raise InvalidParamCard('''This card is not suitable to be converted to MSSM UFO model
1701 Parameter ad [1, 1] times yd [1,1] should be 0''')
1702 card.remove_param('ad', [1,1])
1703
1704 ye = card['yd'].get([2, 2], default=0).value
1705
1706 ae = card['ad'].get([2, 2], default=0).value
1707 card.mod_param('ad', [2,2], 'td', [2,2], value= ad * yd, comment='T_s(Q) DRbar')
1708 if ad * yd:
1709 raise InvalidParamCard('''This card is not suitable to be converted to MSSM UFO model
1710 Parameter ad [2, 2] times yd [2,2] should be 0''')
1711 card.remove_param('ad', [2,2])
1712
1713 yd = card['yd'].get([3, 3]).value
1714 ad = card['ad'].get([3, 3]).value
1715 card.mod_param('ad', [3,3], 'td', [3,3], value= ad * yd, comment='T_b(Q) DRbar')
1716
1717
1718
1719 value = card['msoft'].get([31]).value
1720 card.mod_param('msoft', [31], 'msl2', [1,1], value**2)
1721 value = card['msoft'].get([32]).value
1722 card.mod_param('msoft', [32], 'msl2', [2,2], value**2)
1723 value = card['msoft'].get([33]).value
1724 card.mod_param('msoft', [33], 'msl2', [3,3], value**2)
1725
1726
1727 value = card['msoft'].get([34]).value
1728 card.mod_param('msoft', [34], 'mse2', [1,1], value**2)
1729 value = card['msoft'].get([35]).value
1730 card.mod_param('msoft', [35], 'mse2', [2,2], value**2)
1731 value = card['msoft'].get([36]).value
1732 card.mod_param('msoft', [36], 'mse2', [3,3], value**2)
1733
1734
1735 value = card['msoft'].get([41]).value
1736 card.mod_param('msoft', [41], 'msq2', [1,1], value**2)
1737 value = card['msoft'].get([42]).value
1738 card.mod_param('msoft', [42], 'msq2', [2,2], value**2)
1739 value = card['msoft'].get([43]).value
1740 card.mod_param('msoft', [43], 'msq2', [3,3], value**2)
1741
1742
1743 value = card['msoft'].get([44]).value
1744 card.mod_param('msoft', [44], 'msu2', [1,1], value**2)
1745 value = card['msoft'].get([45]).value
1746 card.mod_param('msoft', [45], 'msu2', [2,2], value**2)
1747 value = card['msoft'].get([46]).value
1748 card.mod_param('msoft', [46], 'msu2', [3,3], value**2)
1749
1750
1751 value = card['msoft'].get([47]).value
1752 card.mod_param('msoft', [47], 'msd2', [1,1], value**2)
1753 value = card['msoft'].get([48]).value
1754 card.mod_param('msoft', [48], 'msd2', [2,2], value**2)
1755 value = card['msoft'].get([49]).value
1756 card.mod_param('msoft', [49], 'msd2', [3,3], value**2)
1757
1758
1759
1760
1761 if writting:
1762 card.write(outputpath)
1763 return card
1764
1767 """ modify the current param_card such that it agrees with the restriction"""
1768
1769 if not outputpath:
1770 outputpath = path
1771
1772 cardrule = ParamCardRule()
1773 cardrule.load_rule(restrictpath)
1774 try :
1775 cardrule.check_param_card(path, modify=False)
1776 except InvalidParamCard:
1777 new_data, was_modified = cardrule.check_param_card(path, modify=True, write_missing=True)
1778 if was_modified:
1779 cardrule.write_param_card(outputpath, new_data)
1780 else:
1781 if path != outputpath:
1782 shutil.copy(path, outputpath)
1783 return cardrule
1784
1786 """ check if the current param_card agrees with the restriction"""
1787
1788 if restrictpath is None:
1789 restrictpath = os.path.dirname(path)
1790 restrictpath = os.path.join(restrictpath, os.pardir, os.pardir, 'Source',
1791 'MODEL', 'param_card_rule.dat')
1792 if not os.path.exists(restrictpath):
1793 restrictpath = os.path.dirname(path)
1794 restrictpath = os.path.join(restrictpath, os.pardir, 'Source',
1795 'MODEL', 'param_card_rule.dat')
1796 if not os.path.exists(restrictpath):
1797 return True
1798
1799 cardrule = ParamCardRule()
1800 cardrule.load_rule(restrictpath)
1801 cardrule.check_param_card(path, modify=False)
1802
1803
1804
1805 if '__main__' == __name__:
1806
1807
1808
1809
1810 import sys
1811 args = sys.argv
1812 sys.path.append(os.path.dirname(__file__))
1813 convert_to_slha1(args[1] , args[2])
1814