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