Package models :: Module check_param_card
[hide private]
[frames] | no frames]

Source Code for Module models.check_param_card

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