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