def compare(self, card1, card2, pid, name1, name2): def error_text(info1, info2, pid, name1, name2): """get error text""" text = "%s INFORMATION:\n" % name1 text += 'total: %s \n' % info1['decay'].get((pid, )).value if info1['decay'].decay_table.has_key(pid): text += str(info1['decay'].decay_table[pid]) + '\n' text += "%s INFORMATION\n" % name2 text += 'total: %s \n' % info2['decay'].get((pid, )).value if info2['decay'].decay_table.has_key(pid): text += str(info2['decay'].decay_table[pid]) + '\n' print text return text if os.path.exists(card1): card1 = card_reader.ParamCard(card1) width1 = card1['decay'].get((pid, )).value else: width1 = 0 if os.path.exists(card2): card2 = card_reader.ParamCard(card2) width2 = card2['decay'].get((pid, )).value else: width2 = 0 print width1, width2 if width1 == width2 == 0: return 'True' if (width1 - width2) / (width1 + width2) > 1e-4: text = error_text(card1, card2, pid, name1, name2) return text + '\n%s has not the same total width: ratio of %s' % \ (pid, (width1 - width2) / (width1 + width2)) info_partial1 = {} for partial_width in card1['decay'].decay_table[pid]: lha_code = list(partial_width.lhacode) lha_code.sort() lha_code = tuple(lha_code) info_partial1[lha_code] = partial_width.value for partial_width in card2['decay'].decay_table[pid]: lha_code = list(partial_width.lhacode) lha_code.sort() lha_code = tuple(lha_code) try: value1 = info_partial1[lha_code] except: value1 = 0 value2 = partial_width.value if value1 == value2 == 0: continue elif value1 == 0 and value2 / width2 < 1e-6: continue elif abs(value1 - value2) / (value1 + value2) > 1e-3 and \ value2 / width2 > 1e-5: text = error_text(card1, card2, pid, name1, name2) return text + '\n%s has not the same partial width for %s: ratio of %s' % \ (pid, lha_code, (value1 - value2) / (value1 + value2)) return 'True'
def write_restrict_card(self, outputdir): """ propagate model restriction of the original model. """ restrict_list = [ l for l in os.listdir(self.modelpath) if l.startswith('restrict_') ] if not self.new_external: # no new entry in the card => just copy the restrict_card.dat for p in restrict_list: files.cp(pjoin(self.modelpath, p), outputdir) else: # need to add the parameter and ensure that they will not be restricted! for p in restrict_list: param_card = check_param_card.ParamCard( pjoin(self.modelpath, p)) for parameter in self.new_external: block = parameter.lhablock lhaid = parameter.lhacode value = parameter.value if value == 0: value = 1e-99 elif value == 1: value = 9.999999e-1 try: param_card.add_param(block.lower(), lhaid, value, 'from addon') except check_param_card.InvalidParamCard: logger.warning("%s will not acting for %s %s" % (p, block, lhaid)) param_card[block.lower()].get(lhaid).value = value # all added -> write it param_card.write(pjoin(outputdir, p), precision=7)
def import_model(self, args): """syntax: import model NAME CARD_PATH args didn't include import model""" bypass_check = False if '--bypass_check' in args: args.remove('--bypass_check') bypass_check = True if len(args) == 1: logger.warning( """No param_card defined for the new model. We will use the default one but this might completely wrong.""" ) elif len(args) != 2: return self.InvalidCmd, 'import model requires two arguments' model_name = args[0] self.load_model(model_name, False, False) if len(args) == 2: card = args[1] if not os.path.exists(card): raise self.InvalidCmd('%s: no such file' % card) else: card = "madspin_param_card.dat" export_v4.UFO_model_to_mg4.create_param_card_static( self.model, card, rule_card_path=None) #Check the param_card if not bypass_check: if not hasattr(self.banner, 'param_card'): self.banner.charge_card('slha') param_card = check_param_card.ParamCard(card) # checking that all parameter of the old param card are present in #the new one with the same value try: diff = self.banner.param_card.create_diff(param_card) except Exception: raise self.InvalidCmd( '''The two param_card seems very different. So we prefer not to proceed. If you are sure about what you are doing, you can use the command \'import model MODELNAME PARAM_CARD_PATH --bypass_check\'''' ) if diff: raise self.InvalidCmd( '''Original param_card differs on some parameters: %s Due to those differences, we prefer not to proceed. If you are sure about what you are doing, you can use the command \'import model MODELNAME PARAM_CARD_PATH --bypass_check\'''' % diff.replace('\n', '\n ')) #OK load the new param_card (but back up the old one) if 'slha' in self.banner: self.banner['slha_original'] = self.banner['slha'] self.banner['slha'] = open(card).read() if hasattr(self.banner, 'param_card'): del self.banner.param_card self.banner.charge_card('slha')
def charge_card(self, tag): """Build the python object associated to the card""" if tag == 'param_card': tag = 'slha' elif tag == 'run_card': tag = 'mgruncard' elif tag == 'proc_card': tag = 'mg5proccard' elif tag == 'shower_card': tag = 'mgshowercard' elif tag == 'FO_analyse_card': tag = 'foanalyse' assert tag in [ 'slha', 'mgruncard', 'mg5proccard', 'mgshowercard', 'foanalyse' ], 'invalid card %s' % tag if tag == 'slha': param_card = self[tag].split('\n') self.param_card = param_card_reader.ParamCard(param_card) return self.param_card elif tag == 'mgruncard': run_card = self[tag].split('\n') if 'parton_shower' in self[tag]: self.run_card = RunCardNLO(run_card) else: self.run_card = RunCard(run_card) return self.run_card elif tag == 'mg5proccard': proc_card = self[tag].split('\n') self.proc_card = ProcCard(proc_card) return self.proc_card elif tag == 'mgshowercard': shower_content = self[tag] if MADEVENT: import internal.shower_card as shower_card else: import madgraph.various.shower_card as shower_card self.shower_card = shower_card.ShowerCard(shower_content, True) # set testing to false (testing = true allow to init using # the card content instead of the card path" self.shower_card.testing = False return self.shower_card elif tag == 'foanalyse': analyse_content = self[tag] if MADEVENT: import internal.FO_analyse_card as FO_analyse_card else: import madgraph.various.FO_analyse_card as FO_analyse_card # set testing to false (testing = true allow to init using # the card content instead of the card path" self.FOanalyse_card = FO_analyse_card.FOAnalyseCard( analyse_content, True) self.FOanalyse_card.testing = False return self.FOanalyse_card
def import_model(self, args): """syntax: import model NAME CARD_PATH args didn't include import model""" bypass_check = False if '--bypass_check' in args: args.remove('--bypass_check') bypass_check = True if len(args) != 2: return self.InvalidCmd, 'import model requires two arguments' model_name = args[0] card = args[1] if not os.path.exists(card): raise self.InvalidCmd('%s: no such file' % card) self.load_model(model_name, False, False) #Check the param_card if not bypass_check: if not hasattr(self.banner, 'param_card'): self.banner.charge_card('slha') param_card = check_param_card.ParamCard(card) # checking that all parameter of the old param card are present in #the new one with the same value try: diff = self.banner.param_card.create_diff(param_card) except Exception: raise self.InvalidCmd( '''The two param_card seems very different. So we prefer not to proceed. If you are sure about what you are doing, you can use the command \'import model MODELNAME PARAM_CARD_PATH --bypass_check\'''' ) if diff: raise self.InvalidCmd( '''Original param_card differs on some parameters: %s Due to those preferences, we prefer not to proceed. If you are sure about what you are doing, you can use the command \'import model MODELNAME PARAM_CARD_PATH --bypass_check\'''' % diff.replace('\n', '\n ')) #OK load the new param_card self.banner['slha'] = open(card).read() if hasattr(self.banner, 'param_card'): del self.banner.param_card self.banner.charge_card('slha')
def test_complex_mass_scheme(self): """check that auto-width and Madspin works nicely with complex-mass-scheme""" mg_cmd = MGCmd.MasterCmd() mg_cmd.no_notification() mg_cmd.exec_cmd('set automatic_html_opening False --save') mg_cmd.exec_cmd('set complex_mass_scheme', precmd=True) mg_cmd.exec_cmd('generate g g > t t~', precmd=True) mg_cmd.exec_cmd('output %s' % self.run_dir, precmd=True) self.cmd_line = MECmd.MadEventCmdShell(me_dir=self.run_dir) self.cmd_line.no_notification() self.cmd_line.exec_cmd('set automatic_html_opening False') #modify run_card run_card = banner_mod.RunCard( pjoin(self.run_dir, 'Cards', 'run_card.dat')) run_card.set('nevents', 100) run_card.write(pjoin(self.run_dir, 'Cards', 'run_card.dat')) # check the auto-width self.cmd_line.exec_cmd('compute_widths 6 -f') # check value for the width import models.check_param_card as check_param_card param_card = check_param_card.ParamCard( pjoin(self.run_dir, 'Cards', 'param_card.dat')) self.assertTrue(misc.equal(1.491257, param_card['decay'].get(6).value), 3) # generate events self.cmd_line.exec_cmd('launch -f') val1 = self.cmd_line.results.current['cross'] err1 = self.cmd_line.results.current['error'] target = 440.779 self.assertTrue(misc.equal(target, val1, 4 * err1)) # run madspin fsock = open(pjoin(self.run_dir, 'Cards', 'madspin_card.dat'), 'w') fsock.write('decay t > w+ b \n launch') fsock.close() self.cmd_line.exec_cmd('decay_events run_01 -f') val1 = self.cmd_line.results.current['cross'] err1 = self.cmd_line.results.current['error'] target = 440.779 self.assertTrue(misc.equal(target, val1, 4 * err1))
def get_2body(self, particle): """use FR to get the list of particles being in the 1->2 final state""" dir_name = 'TEST_DECAY3_%s_%s' % (self.model,particle) os.system('rm -rf %s >/dev/null' % dir_name) pid = self.particles_id[particle] #make a fake output self.cmd._curr_model.write_param_card() self.cmd.exec_cmd('generate z > e+ e-') self.cmd.exec_cmd('output %s -f' % dir_name) me_cmd = me_interface.MadEventCmd(dir_name) self.cmd.define_child_cmd_interface(me_cmd, False) me_cmd.model_name = self.model me_cmd.do_compute_widths(' %s -f --body_decay=2' % particle) # now get the results: pids = set() path = pjoin(dir_name, 'Cards', 'param_card.dat') card = card_reader.ParamCard(path) if pid not in card['decay'].decay_table: return set(), {} for partial_width in card['decay'].decay_table[pid]: pids.update(list(partial_width.lhacode)[1:]) labels = set() for id in pids: part = self.cmd._curr_model.get_particle(id) #if part.get('mass').lower() == 'zero': # continue #if part.get('width').lower() == 'zero': # continue labels.add(part.get('name')) labels.add(part.get('antiname')) os.system('rm -rf %s >/dev/null' % dir_name) me_cmd.do_quit('') return labels, card['decay'].decay_table[pid]
def set_parameters_and_couplings(self, param_card = None, scale=None, complex_mass_scheme=None): """Read a param_card and calculate all parameters and couplings. Set values directly in the parameters and couplings, plus add new dictionary coupling_dict from parameter name to value.""" param_card_text = None # Extract external parameters external_parameters = self['parameters'][('external',)] # Read in param_card if param_card: # Create a dictionary from LHA block name and code to parameter name parameter_dict = {} for param in external_parameters: try: dictionary = parameter_dict[param.lhablock.lower()] except KeyError: dictionary = {} parameter_dict[param.lhablock.lower()] = dictionary dictionary[tuple(param.lhacode)] = param if isinstance(param_card, basestring): # Check that param_card exists if not os.path.isfile(param_card): raise MadGraph5Error, "No such file %s" % param_card param_card_text = param_card param_card = card_reader.ParamCard(param_card) #misc.sprint(type(param_card), card_reader.ParamCard, isinstance(param_card, card_reader.ParamCard)) #assert isinstance(param_card, card_reader.ParamCard),'%s is not a ParamCard: %s' % (type(param_card), isinstance(param_card, card_reader.ParamCard)) if complex_mass_scheme is None: if aloha.complex_mass: param_card.convert_to_complex_mass_scheme() else: if complex_mass_scheme: param_card.convert_to_complex_mass_scheme() key = [k for k in param_card.keys() if not k.startswith('qnumbers ') and not k.startswith('decay_table') and 'info' not in k] param_key = [k for k in parameter_dict.keys() if 'info' not in k] if set(key) != set(parameter_dict.keys()): # the two card are different. check if this critical fail = True missing_set = set(parameter_dict.keys()).difference(set(key)) unknow_set = set(key).difference(set(parameter_dict.keys())) missing_block = ','.join(missing_set) unknow_block = ','.join(unknow_set) msg = '''Invalid restriction card (not same block) %s != %s. Missing block: %s Unknown block : %s''' % (set(key), set(parameter_dict.keys()), missing_block, unknow_block) apply_conversion = [] if not missing_block: logger.warning("Unknow type of information in the card: %s" % unknow_block) fail = False elif self['name'].startswith('mssm-') or self['name'] == 'mssm': if not missing_set: fail = False else: apply_conversion.append('to_slha2') overwrite = False elif missing_set == set(['fralpha']) and 'alpha' in unknow_set: apply_conversion.append('alpha') elif self.need_slha2(missing_set, unknow_set): apply_conversion.append('to_slha2') overwrite = True if apply_conversion: try: if 'to_slha2' in apply_conversion: if overwrite: logger.error('Convention for the param_card seems to be wrong. Trying to automatically convert your file to SLHA2 format. \n'+\ "Please check that the conversion occurs as expected (The converter is not fully general)") import time time.sleep(5) param_card = param_card.input_path param_card = card_reader.convert_to_mg5card(param_card, writting=overwrite) key = [k for k in param_card.keys() if not k.startswith('qnumbers ') and not k.startswith('decay_table')] if not set(parameter_dict.keys()).difference(set(key)): fail = False if 'alpha' in apply_conversion: logger.info("Missing block fralpha but found a block alpha, apply automatic conversion") param_card.rename_blocks({'alpha':'fralpha'}) param_card['fralpha'].rename_keys({(): (1,)}) param_card.write(param_card.input_path) key = [k for k in param_card.keys() if not k.startswith('qnumbers ') and not k.startswith('decay_table')] if not set(parameter_dict.keys()).difference(set(key)): fail = False except Exception: raise raise MadGraph5Error, msg if fail: raise MadGraph5Error, msg for block in key: if block not in parameter_dict: continue for pid in parameter_dict[block]: try: value = param_card[block].get(pid).value except: raise MadGraph5Error, '%s %s not define' % (block, pid) else: if isinstance(value, str) and value.lower() == 'auto': value = '0.0' if scale and parameter_dict[block][pid].name == 'aS': runner = Alphas_Runner(value, nloop=2) try: value = runner(scale) except ValueError, err: if str(err) == 'math domain error' and scale < 1: value = 0.0 else: raise exec("locals()[\'%s\'] = %s" % (parameter_dict[block][pid].name, value)) parameter_dict[block][pid].value = float(value)
def compare3(self, card1, card2, pid, name1, name2, twobody_decay, log, raiseerror=False): fail = False if twobody_decay: twobody_key = [ list(p.lhacode)[1:] for p in twobody_decay if len(p.lhacode) == 3 ] [t.sort() for t in twobody_key] else: twobody_key = [] def error_text(info1, info2, pid, name1, name2): """get error text""" text = "%s INFORMATION:\n" % name1 text += 'total: %s \n' % info1['decay'].get((pid, )).value if info1['decay'].decay_table.has_key(pid): text += str(info1['decay'].decay_table[pid]) + '\n' text += "%s INFORMATION\n" % name2 text += 'total: %s \n' % info2['decay'].get((pid, )).value if info2['decay'].decay_table.has_key(pid): text += str(info2['decay'].decay_table[pid]) + '\n' if not raiseerror: print text else: raise Exception, text return text if os.path.exists(card1): card1 = card_reader.ParamCard(card1) width1 = card1['decay'].get((pid, )).value else: width1 = 0 if os.path.exists(card2): card2 = card_reader.ParamCard(card2) width2 = card2['decay'].get((pid, )).value else: width2 = 0 if width1 == width2 == 0: return 'True' orig_width1 = width1 info_partial2 = {} for partial_width in card2['decay'].decay_table[pid]: lha_code = list(partial_width.lhacode) lha_code.sort() lha_code = tuple(lha_code) info_partial2[lha_code] = partial_width.value * width2 for partial_width in card1['decay'].decay_table[pid][:]: lha_code = list(partial_width.lhacode) lha_code.sort() lha_code = tuple(lha_code) try: value2 = info_partial2[lha_code] except: value2 = 0 value1 = partial_width.value * orig_width1 if value1 == value2 == 0: continue elif value2 == 0 and len(lha_code) == 4: # check if this is a radiation ids = list(partial_width.lhacode)[1:] ids.sort() id1, id2, id3 = ids if [id1, id2] in twobody_key or \ [id1, id3] in twobody_key or \ [id2, id3] in twobody_key: card1['decay'].decay_table[pid].remove( partial_width.lhacode) card1['decay'].get((pid, )).value -= value1 width1 -= value1 continue if value2 == 0 and value1 / orig_width1 < 1e-6: continue print '\n%s has not the same partial width for %s: ratio of %s' % \ (pid, lha_code, (value1 - value2) / (value1 + value2)) fail = True elif abs(value1 - value2) / (value1 + value2) < 5e-2 or \ value1 / orig_width1 < 1e-5: continue elif abs(value1 - value2) / (value1 + value2) < 1e-3 or \ value1 / orig_width1 < 1e-3: continue else: print 'fail for %s %s %s' % (lha_code, value1, value2) fail = True if fail: text = error_text(card1, card2, pid, name1, name2) if not raiseerror: return text else: raise Exception, text if abs(width1 - width2) / width1 + width2 > 5e-2 or \ abs(width1 - width2) / orig_width1 + width2 > 3e-2: print width1, width2, abs(width1 - width2) / width1 + width2, abs( width1 - width2) / orig_width1 + width2 print 'fail for the total cross section (orig: %s)' % orig_width1 text = error_text(card1, card2, pid, name1, name2) if not raiseerror: return text + '\n%s has not the same total width: ratio of %s' % \ (pid, (width1 - width2) / (width1 + width2)) else: raise text return 'True'
def do_launch(self, line): """end of the configuration launched the code""" args = self.split_arg(line) self.check_launch(args) model_line = self.banner.get('proc_card', 'full_model_line') if not self.has_standalone_dir: self.create_standalone_directory() ff = open(pjoin(self.me_dir, 'rw_me','Cards', 'param_card.dat'), 'w') ff.write(self.banner['slha']) ff.close() ff = open(pjoin(self.me_dir, 'rw_me','Cards', 'param_card_orig.dat'), 'w') ff.write(self.banner['slha']) ff.close() cmd = common_run_interface.CommonRunCmd.ask_edit_card_static(cards=['param_card.dat'], ask=self.ask, pwd=pjoin(self.me_dir,'rw_me')) new_card = open(pjoin(self.me_dir, 'rw_me', 'Cards', 'param_card.dat')).read() # Find new tag in the banner and add information if needed if 'initrwgt' in self.banner: if 'type=\'mg_reweighting\'' in self.banner['initrwgt']: blockpat = re.compile(r'''<weightgroup type=\'mg_reweighting\'\s*>(?P<text>.*?)</weightgroup>''', re.I+re.M+re.S) before, content, after = blockpat.split(self.banner['initrwgt']) header_rwgt_other = before + after pattern = re.compile('<weight id=\'mg_reweight_(?P<id>\d+)\'>(?P<info>[^<>]*)</weight>', re.S+re.I+re.M) mg_rwgt_info = pattern.findall(content) maxid = 0 for i, diff in mg_rwgt_info: if int(i) > maxid: maxid = int(i) maxid += 1 rewgtid = maxid else: header_rwgt_other = self.banner['initrwgt'] mg_rwgt_info = [] rewgtid = 1 else: self.banner['initrwgt'] = '' header_rwgt_other = '' mg_rwgt_info = [] rewgtid = 1 # add the reweighting in the banner information: #starts by computing the difference in the cards. s_orig = self.banner['slha'] s_new = new_card old_param = check_param_card.ParamCard(s_orig.splitlines()) new_param = check_param_card.ParamCard(s_new.splitlines()) card_diff = old_param.create_diff(new_param) if card_diff == '': raise self.InvalidCmd, 'original card and new card are identical' mg_rwgt_info.append((str(rewgtid), card_diff)) # re-create the banner. self.banner['initrwgt'] = header_rwgt_other self.banner['initrwgt'] += '\n<weightgroup type=\'mg_reweighting\'>\n' for tag, diff in mg_rwgt_info: self.banner['initrwgt'] += '<weight id=\'mg_reweight_%s\'>%s</weight>\n' % \ (tag, diff) self.banner['initrwgt'] += '\n</weightgroup>\n' self.banner['initrwgt'] = self.banner['initrwgt'].replace('\n\n', '\n') output = open( self.lhe_input.name +'rw', 'w') logger.info('starts to compute weight for events with the following modification to the param_card:') logger.info(card_diff) #write the banner to the output file self.banner.write(output, close_tag=False) # prepare the output file for the weight plot if self.mother: out_path = pjoin(self.mother.me_dir, 'Events', 'reweight.lhe') output2 = open(out_path, 'w') self.banner.write(output2, close_tag=False) new_banner = banner.Banner(self.banner) if not hasattr(self, 'run_card'): self.run_card = new_banner.charge_card('run_card') self.run_card['run_tag'] = 'reweight_%s' % rewgtid new_banner['slha'] = s_new del new_banner['initrwgt'] #ensure that original banner is kept untouched assert new_banner['slha'] != self.banner['slha'] assert 'initrwgt' in self.banner ff = open(pjoin(self.mother.me_dir,'Events',self.mother.run_name, '%s_%s_banner.txt' % \ (self.mother.run_name, self.run_card['run_tag'])),'w') new_banner.write(ff) ff.close() # Loop over all events tag_name = 'mg_reweight_%s' % rewgtid start = time.time() cross = 0 os.environ['GFORTRAN_UNBUFFERED_ALL'] = 'y' if self.lhe_input.closed: self.lhe_input = lhe_parser.EventFile(self.lhe_input.name) for event_nb,event in enumerate(self.lhe_input): #control logger if (event_nb % max(int(10**int(math.log10(float(event_nb)+1))),1000)==0): running_time = misc.format_timer(time.time()-start) logger.info('Event nb %s %s' % (event_nb, running_time)) if (event_nb==10001): logger.info('reducing number of print status. Next status update in 10000 events') weight = self.calculate_weight(event) cross += weight event.reweight_data[tag_name] = weight #write this event with weight output.write(str(event)) if self.mother: event.wgt = weight event.reweight_data = {} output2.write(str(event)) running_time = misc.format_timer(time.time()-start) logger.info('All event done (nb_event: %s) %s' % (event_nb+1, running_time)) output.write('</LesHouchesEvents>\n') output.close() os.environ['GFORTRAN_UNBUFFERED_ALL'] = 'n' if self.mother: output2.write('</LesHouchesEvents>\n') output2.close() # add output information if hasattr(self.mother, 'results'): run_name = self.mother.run_name results = self.mother.results results.add_run(run_name, self.run_card, current=True) results.add_detail('nb_event', event_nb+1) results.add_detail('cross', cross) results.add_detail('error', 'nan') self.mother.create_plot(mode='reweight', event_path=output2.name, tag=self.run_card['run_tag']) #modify the html output to add the original run if 'plot' in results.current.reweight: html_dir = pjoin(self.mother.me_dir, 'HTML', run_name) td = pjoin(self.mother.options['td_path'], 'td') MA = pjoin(self.mother.options['madanalysis_path']) path1 = pjoin(html_dir, 'plots_parton') path2 = pjoin(html_dir, 'plots_%s' % self.run_card['run_tag']) outputplot = path2 combine_plots.merge_all_plots(path2, path1, outputplot, td, MA) #results.update_status(level='reweight') #results.update(status, level, makehtml=True, error=False) #old_name = self.mother.results.current['run_name'] #new_run = '%s_rw_%s' % (old_name, rewgtid) #self.mother.results.add_run( new_run, self.run_card) #self.mother.results.add_detail('nb_event', event_nb+1) #self.mother.results.add_detail('cross', cross) #self.mother.results.add_detail('error', 'nan') #self.mother.do_plot('%s -f' % new_run) #self.mother.update_status('Reweight %s done' % rewgtid, 'madspin') #self.mother.results.def_current(old_name) #self.run_card['run_tag'] = self.run_card['run_tag'][9:] #self.mother.run_name = old_name self.lhe_input.close() files.mv(output.name, self.lhe_input.name) logger.info('Event %s have now the additional weight' % self.lhe_input.name) logger.info('new cross-section is : %g pb' % cross) self.terminate_fortran_executables(new_card_only=True) #store result self.all_cross_section[rewgtid] = cross
def set_parameters_and_couplings(self, param_card = None, scale=None, complex_mass_scheme=None): """Read a param_card and calculate all parameters and couplings. Set values directly in the parameters and couplings, plus add new dictionary coupling_dict from parameter name to value.""" # Extract external parameters external_parameters = self['parameters'][('external',)] # Read in param_card if param_card: # Create a dictionary from LHA block name and code to parameter name parameter_dict = {} for param in external_parameters: try: dictionary = parameter_dict[param.lhablock.lower()] except KeyError: dictionary = {} parameter_dict[param.lhablock.lower()] = dictionary dictionary[tuple(param.lhacode)] = param if isinstance(param_card, basestring): # Check that param_card exists if not os.path.isfile(param_card): raise MadGraph5Error, "No such file %s" % param_card param_card = card_reader.ParamCard(param_card) # misc.sprint(type(param_card), card_reader.ParamCard, isinstance(param_card, card_reader.ParamCard)) # assert isinstance(param_card, card_reader.ParamCard),'%s is not a ParamCard: %s' % (type(param_card), isinstance(param_card, card_reader.ParamCard)) if complex_mass_scheme is None: if aloha.complex_mass: param_card.convert_to_complex_mass_scheme() else: if complex_mass_scheme: param_card.convert_to_complex_mass_scheme() key = [k for k in param_card.keys() if not k.startswith('qnumbers ') and not k.startswith('decay_table') and 'info' not in k] param_key = [k for k in parameter_dict.keys() if 'info' not in k] if set(key) != set(parameter_dict.keys()): # the two card are different. check if this critical fail = True missing_block = ','.join(set(parameter_dict.keys()).difference(set(key))) unknow_block = ','.join(set(key).difference(set(parameter_dict.keys()))) msg = '''Invalid restriction card (not same block) %s != %s. Missing block: %s Unknown block : %s''' % (set(key), set(parameter_dict.keys()), missing_block, unknow_block) if not missing_block: logger.warning("Unknow type of information in the card: %s" % unknow_block) fail = False elif msg =="Invalid restriction card (not same block)\n set(['yu', 'umix', 'ae', 'ad', 'decay', 'nmix', 'ye', 'sbotmix', 'msoft', 'yd', 'vmix', 'au', 'mass', 'alpha', 'modsel', 'sminputs', 'staumix', 'stopmix', 'hmix']) != set(['umix', 'msoft', 'msu2', 'fralpha', 'msd2', 'msl2', 'decay', 'tu', 'selmix', 'td', 'te', 'usqmix', 'dsqmix', 'ye', 'yd', 'sminputs', 'yu', 'mse2', 'nmix', 'vmix', 'msq2', 'mass', 'hmix']).\n Missing block: te,msl2,dsqmix,tu,selmix,msu2,msq2,usqmix,td,fralpha,mse2,msd2\n Unknown block : ae,ad,sbotmix,au,alpha,modsel,staumix,stopmix" \ or self['name'].startswith('mssm-') or self['name'] == 'mssm': if not set(parameter_dict.keys()).difference(set(key)): fail = False else: # FOR MSSM allow for automatic conversion to correct format try: param_card = param_card.input_path param_card = card_reader.convert_to_mg5card(param_card, writting=False) key = [k for k in param_card.keys() if not k.startswith('qnumbers ') and not k.startswith('decay_table')] if not set(parameter_dict.keys()).difference(set(key)): fail = False except Exception: raise MadGraph5Error, msg if fail: raise MadGraph5Error, msg for block in key: if block not in parameter_dict: continue for id in parameter_dict[block]: try: value = param_card[block].get(id).value except: raise MadGraph5Error, '%s %s not define' % (block, id) else: if isinstance(value, str) and value.lower() == 'auto': value = '0.0' if scale and parameter_dict[block][id].name == 'aS': runner = Alphas_Runner(value, nloop=2) value = runner(scale) exec("locals()[\'%s\'] = %s" % (parameter_dict[block][id].name, value)) parameter_dict[block][id].value = float(value) else: # No param_card, use default values for param in external_parameters: if scale and parameter_dict[block][id].name == 'aS': runner = Alphas_Runner(value, nloop=3) value = runner(scale) exec("locals()[\'%s\'] = %s" % (param.name, param.value)) # Define all functions used for func in self['functions']: exec("def %s(%s):\n return %s" % (func.name, ",".join(func.arguments), func.expr)) # Extract derived parameters derived_parameters = [] keys = [key for key in self['parameters'].keys() if \ key != ('external',)] keys.sort(key=len) for key in keys: derived_parameters += self['parameters'][key] # Now calculate derived parameters for param in derived_parameters: try: exec("locals()[\'%s\'] = %s" % (param.name, param.expr)) except Exception as error: msg = 'Unable to evaluate %s = %s: raise error: %s' % (param.name,param.expr, error) raise MadGraph5Error, msg param.value = complex(eval(param.name)) if not eval(param.name) and eval(param.name) != 0: logger.warning("%s has no expression: %s" % (param.name, param.expr)) # Correct width sign for Majorana particles (where the width # and mass need to have the same sign) for particle in self.get('particles'): if particle.is_fermion() and particle.get('self_antipart') and \ particle.get('width').lower() != 'zero' and \ eval(particle.get('mass')).real < 0: exec("locals()[\'%(width)s\'] = -abs(%(width)s)" % \ {'width': particle.get('width')}) # Extract couplings couplings = sum(self['couplings'].values(), []) # Now calculate all couplings for coup in couplings: #print "I execute %s = %s"%(coup.name, coup.expr) exec("locals()[\'%s\'] = %s" % (coup.name, coup.expr)) coup.value = complex(eval(coup.name)) if not eval(coup.name) and eval(coup.name) != 0: logger.warning("%s has no expression: %s" % (coup.name, coup.expr)) # Set parameter and coupling dictionaries self.set('parameter_dict', dict([(param.name, param.value) \ for param in external_parameters + \ derived_parameters])) # Add "zero" self.get('parameter_dict')['ZERO'] = complex(0.) self.set('coupling_dict', dict([(coup.name, coup.value) \ for coup in couplings])) return locals()
def set_parameters_and_couplings(self, param_card=None, scale=None, complex_mass_scheme=None): """Read a param_card and calculate all parameters and couplings. Set values directly in the parameters and couplings, plus add new dictionary coupling_dict from parameter name to value.""" param_card_text = None # Extract external parameters external_parameters = self['parameters'][('external', )] # Read in param_card if param_card: # Create a dictionary from LHA block name and code to parameter name parameter_dict = {} for param in external_parameters: try: dictionary = parameter_dict[param.lhablock.lower()] except KeyError: dictionary = {} parameter_dict[param.lhablock.lower()] = dictionary dictionary[tuple(param.lhacode)] = param if isinstance(param_card, basestring): # Check that param_card exists if not os.path.isfile(param_card): raise MadGraph5Error, "No such file %s" % param_card param_card_text = param_card param_card = card_reader.ParamCard(param_card) #misc.sprint(type(param_card), card_reader.ParamCard, isinstance(param_card, card_reader.ParamCard)) #assert isinstance(param_card, card_reader.ParamCard),'%s is not a ParamCard: %s' % (type(param_card), isinstance(param_card, card_reader.ParamCard)) if complex_mass_scheme is None: if aloha.complex_mass: param_card.convert_to_complex_mass_scheme() else: if complex_mass_scheme: param_card.convert_to_complex_mass_scheme() key = [ k for k in param_card.keys() if not k.startswith('qnumbers ') and not k.startswith('decay_table') and 'info' not in k ] param_key = [k for k in parameter_dict.keys() if 'info' not in k] if set(key) != set(parameter_dict.keys()): # the two card are different. check if this critical fail = True missing_set = set(parameter_dict.keys()).difference(set(key)) unknow_set = set(key).difference(set(parameter_dict.keys())) missing_block = ','.join(missing_set) unknow_block = ','.join(unknow_set) msg = '''Invalid restriction card (not same block) %s != %s. Missing block: %s Unknown block : %s''' % (set(key), set( parameter_dict.keys()), missing_block, unknow_block) apply_conversion = [] if not missing_block: logger.warning( "Unknow type of information in the card: %s" % unknow_block) fail = False elif self['name'].startswith( 'mssm-') or self['name'] == 'mssm': if not missing_set: fail = False else: apply_conversion.append('to_slha2') overwrite = False elif missing_set == set(['fralpha']) and 'alpha' in unknow_set: apply_conversion.append('alpha') elif self.need_slha2(missing_set, unknow_set): apply_conversion.append('to_slha2') overwrite = True if apply_conversion: try: if 'to_slha2' in apply_conversion: if overwrite: logger.error('Convention for the param_card seems to be wrong. Trying to automatically convert your file to SLHA2 format. \n'+\ "Please check that the conversion occurs as expected (The converter is not fully general)") import time time.sleep(5) param_card = param_card.input_path param_card = card_reader.convert_to_mg5card( param_card, writting=overwrite) key = [ k for k in param_card.keys() if not k.startswith('qnumbers ') and not k.startswith('decay_table') ] if not set(parameter_dict.keys()).difference( set(key)): fail = False if 'alpha' in apply_conversion: logger.info( "Missing block fralpha but found a block alpha, apply automatic conversion" ) param_card.rename_blocks({'alpha': 'fralpha'}) param_card['fralpha'].rename_keys({(): (1, )}) param_card.write(param_card.input_path) key = [ k for k in param_card.keys() if not k.startswith('qnumbers ') and not k.startswith('decay_table') ] if not set(parameter_dict.keys()).difference( set(key)): fail = False except Exception: raise raise MadGraph5Error, msg if fail: raise MadGraph5Error, msg for block in key: if block not in parameter_dict: continue for pid in parameter_dict[block]: try: value = param_card[block].get(pid).value except: raise MadGraph5Error, '%s %s not define' % (block, pid) else: if isinstance(value, str) and value.lower() == 'auto': value = '0.0' if scale and parameter_dict[block][pid].name == 'aS': runner = Alphas_Runner(value, nloop=2) value = runner(scale) exec("locals()[\'%s\'] = %s" % (parameter_dict[block][pid].name, value)) parameter_dict[block][pid].value = float(value) else: # No param_card, use default values for param in external_parameters: if scale and parameter_dict[block][id].name == 'aS': runner = Alphas_Runner(value, nloop=3) value = runner(scale) exec("locals()[\'%s\'] = %s" % (param.name, param.value)) # Define all functions used for func in self['functions']: exec("def %s(%s):\n return %s" % (func.name, ",".join(func.arguments), func.expr)) # Extract derived parameters derived_parameters = [] keys = [key for key in self['parameters'].keys() if \ key != ('external',)] keys.sort(key=len) for key in keys: derived_parameters += self['parameters'][key] # Now calculate derived parameters for param in derived_parameters: try: exec("locals()[\'%s\'] = %s" % (param.name, param.expr)) except Exception as error: msg = 'Unable to evaluate %s = %s: raise error: %s' % ( param.name, param.expr, error) raise MadGraph5Error, msg param.value = complex(eval(param.name)) if not eval(param.name) and eval(param.name) != 0: logger.warning("%s has no expression: %s" % (param.name, param.expr)) # Correct width sign for Majorana particles (where the width # and mass need to have the same sign) for particle in self.get('particles'): if particle.is_fermion() and particle.get('self_antipart') and \ particle.get('width').lower() != 'zero' and \ eval(particle.get('mass')).real < 0: exec("locals()[\'%(width)s\'] = -abs(%(width)s)" % \ {'width': particle.get('width')}) # Extract couplings couplings = sum(self['couplings'].values(), []) # Now calculate all couplings for coup in couplings: #print "I execute %s = %s"%(coup.name, coup.expr) exec("locals()[\'%s\'] = %s" % (coup.name, coup.expr)) coup.value = complex(eval(coup.name)) if not eval(coup.name) and eval(coup.name) != 0: logger.warning("%s has no expression: %s" % (coup.name, coup.expr)) # Set parameter and coupling dictionaries self.set('parameter_dict', dict([(param.name, param.value) \ for param in external_parameters + \ derived_parameters])) # Add "zero" self.get('parameter_dict')['ZERO'] = complex(0.) self.set('coupling_dict', dict([(coup.name, coup.value) \ for coup in couplings])) return locals()
def check_compilation(self): """check that the model compile return correct output""" #Check the cleaning join = lambda p: os.path.join(self.output_path, p) self.assertFalse(os.path.exists(self.give_pos('testprog'))) try: os.remove(join('../param_card.inc')) except: pass # prepare for a local compilation subprocess.call(['python', 'write_param_card.py'], cwd=os.path.join(MG5DIR, 'models', 'sm'), stdout=subprocess.PIPE) files.cp(os.path.join(MG5DIR, 'models', 'sm', 'param_card.dat'), join('param_card.dat')) text = file(join('makefile')).read().replace( '../../Cards/param_card.dat', 'param_card.dat') open(join('makefile'), 'w').write(text) #make ../param_card.inc param_card = check_param_card.ParamCard(join('param_card.dat')) param_card.write_inc_file(join('../param_card.inc'), join('ident_card.dat'), join('param_card.dat')) subprocess.call(['make', 'testprog'], cwd=self.output_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.assertTrue(os.path.exists(self.give_pos('testprog'))) os.chmod(os.path.join(self.output_path, 'testprog'), 0777) testprog = subprocess.Popen("./testprog", stdout=subprocess.PIPE, cwd=self.output_path, stderr=subprocess.STDOUT, shell=True) solutions = { 'ymtau ': [1.7769999504089355], 'I4x33 ': [0.024123685681481218, 0.0], 'MTA ': [1.7769999504089355], 'GC_81 ': [0.0, 67.544], 'GC_5 ': [0.0, 0.094836], 'MZ ': [91.18800354003906], 'GC_27 ': [0.94484, 0.0], 'I1x33 ': [0.024123685681481218, 0.0], 'I3x33 ': [0.9448443987662922, 0.0], 'GC_95 ': [0.66811, 0.0], 'GC_60 ': [-0.37035, 0.0], 'ee__exp__2 ': [0.09483552005165403], 'aEWM1 ': [132.5070037841797], 'ytau ': [0.01020661671581679], 'GC_69 ': [-0.0, -190.38], 'GC_35 ': [-0.0, -0.42671], 'cw__exp__2 ': [0.7777535472599892], 'Gf ': [1.16639e-05], 'GC_59 ': [0.0, 0.08231], 'GC_21 ': [-0.94484, -0.0], 'ee ': [0.307953762847045], 'WZ ': [2.441404104232788], 'sw2 ': [0.22224645274001076], 'WT ': [1.5083359479904175], 'GC_80 ': [-0.0, -33.772], 'GC_57 ': [-0.0, -0.35482], 'sqrt__sw2 ': [0.4714302204356555], 'GC_67 ': [13.239, 0.0], 'GC_76 ': [-29.784, 0.0], 'GC_36 ': [0.0, 0.33188], 'GC_68 ': [-0.0, -63.46], 'GC_56 ': [0.10058, 0.0], 'sw__exp__2 ': [0.22224645274001076], 'GC_3 ': [-0.0, -0.30795], 'GC_54 ': [-0.10058, 0.0], 'WW ': [2.047600030899048], 'GC_70 ': [-26.266, 0.0], 'GC_66 ': [-13.239, 0.0], 'GC_38 ': [-0.0, -0.32662], 'GC_83 ': [-0.0, -0.017058], 'GC_77 ': [-16.545, 0.0], 'gw ': [0.653232969584471], 'MH ': [125.0], 'ymb ': [4.199999809265137], 'complexi ': [0.0, 1.0], 'GC_37 ': [-0.32662, 0.0], 'conjg__CKM1x1 ': [1.0], 'GC_2 ': [0.0, 0.2053], 'GC_51 ': [0.0, 0.28804], 'GC_71 ': [-0.0, -26.266], 'GC_39 ': [0.0, 0.32662], 'GC_82 ': [-0.017058, 0.0], 'GC_55 ': [-0.0, -0.10058], 'GC_78 ': [16.545, 0.0], 'GC_98 ': [-0.0072172, 0.0], 'GC_30 ': [-0.024124, -0.0], 'GC_15 ': [0.024124, 0.0], 'cw ': [0.881903366168873], 'yt ': [0.9448443987662922], 'sqrt__aEW ': [0.08687215260631942], 'vev ': [246.2184581018163], 'GC_79 ': [29.784, 0.0], 'GC_72 ': [0.0, 52.532], 'GC_1 ': [-0.0, -0.10265], 'conjg__CKM3x3 ': [1.0], 'GC_52 ': [-0.0, -0.57609], 'GC_100 ': [0.0, 0.46191], 'GC_65 ': [0.0, 0.27432], 'GC_12 ': [0.0, 1.4828], 'I2x33 ': [0.9448443987662922, 0.0], 'GC_94 ': [-0.0, -0.66811], 'sqrt__aS ': [0.3435112817874484], 'GC_31 ': [-0.0, -0.25774], 'aS ': [0.11800000071525575], 'MW__exp__2 ': [6467.21673128622], 'MZ__exp__4 ': [69143415.65084904], 'yb ': [0.024123685681481218], 'GC_99 ': [-0.0, -0.0072172], 'WH ': [0.006382339168339968], 'GC_96 ': [-0.010207, 0.0], 'MH__exp__2 ': [15625.0], 'GC_63 ': [0.0, 0.12671], 'GC_53 ': [0.0, 0.57609], 'GC_73 ': [26.266, 0.0], 'GC_64 ': [0.0, 0.084653], 'sw ': [0.4714302204356555], 'GC_9 ': [0.053768, 0.0], 'GC_32 ': [-0.0, -0.51548], 'muH ': [88.38834764831844], 'GC_7 ': [-0.053768, 0.0], 'aEW ': [0.0075467708984556505], 'vev__exp__2 ': [60623.52911003587], 'MZ__exp__2 ': [8315.251989618177], 'GC_97 ': [0.010207, 0.0], 'GC_62 ': [0.0, 0.37035], 'GC_74 ': [-24.765, 0.0], 'g1 ': [0.34919218438279087], 'GC_10 ': [-1.2177, 0.0], 'GC_8 ': [0.0, 0.053768], 'CKM3x3 ': [1.0], 'MW ': [80.41900727617956], 'MT ': [172.0], 'GC_33 ': [-0.0, -0.77321], 'GC_6 ': [0.0, 0.18967], 'GC_4 ': [0.0, 0.30795], 'MB ': [4.699999809265137], 'GC_61 ': [0.0, -0.20573], 'ymt ': [164.5], 'GC_75 ': [24.765, 0.0], 'G__exp__2 ': [1.4828317414825511], 'lam ': [0.1288691060169027], 'GC_50 ': [-0.0, -0.28804], 'GC_34 ': [0.0, 0.21336], 'GC_11 ': [0.0, 1.2177], 'sqrt__2 ': [1.4142135623730951], 'GC_58 ': [-0.0, -0.027437] } #solutions = {'GC_5 ': [0.0, 0.094836], 'mdl_MW ': [80.41900727617956], 'mdl_yb ': [0.024123685681481218], 'mdl_sw__exp__2 ': [0.22224645274001076], 'mdl_conjg__CKM3x3 ': [1.0], 'GC_56 ': [0.10058, 0.0], 'mdl_MH ': [125.0], 'GC_95 ': [0.66811, 0.0], 'mdl_I4x33 ': [0.024123685681481218, 0.0], 'mdl_complexi ': [0.0, 1.0], 'aEWM1 ': [132.5070037841797], 'GC_69 ': [-0.0, -190.38], 'GC_35 ': [-0.0, -0.42671], 'mdl_Gf ': [1.16639e-05], 'mdl_gw ': [0.653232969584471], 'mdl_conjg__CKM1x1 ': [1.0], 'mdl_sqrt__aEW ': [0.08687215260631942], 'GC_59 ': [0.0, 0.08231], 'GC_21 ': [-0.94484, -0.0], 'GC_4 ': [0.0, 0.30795], 'mdl_cw ': [0.881903366168873], 'GC_80 ': [-0.0, -33.772], 'GC_64 ': [0.0, 0.084653], 'GC_57 ': [-0.0, -0.35482], 'GC_76 ': [-29.784, 0.0], 'GC_67 ': [13.239, 0.0], 'mdl_vev__exp__2 ': [60623.52911003587], 'mdl_I3x33 ': [0.9448443987662922, 0.0], 'GC_36 ': [0.0, 0.33188], 'mdl_I1x33 ': [0.024123685681481218, 0.0], 'GC_81 ': [0.0, 67.544], 'mdl_sw2 ': [0.22224645274001076], 'GC_68 ': [-0.0, -63.46], 'mdl_ytau ': [0.01020661671581679], 'GC_100 ': [0.0, 0.46191], 'GC_3 ': [-0.0, -0.30795], 'GC_54 ': [-0.10058, 0.0], 'GC_70 ': [-26.266, 0.0], 'GC_66 ': [-13.239, 0.0], 'GC_38 ': [-0.0, -0.32662], 'GC_83 ': [-0.0, -0.017058], 'GC_77 ': [-16.545, 0.0], 'GC_27 ': [0.94484, 0.0], 'GC_10 ': [-1.2177, 0.0], 'GC_37 ': [-0.32662, 0.0], 'GC_60 ': [-0.37035, 0.0], 'GC_2 ': [0.0, 0.2053], 'mdl_muH ': [88.38834764831844], 'mdl_MT ': [172.0], 'mdl_WH ': [0.006382339168339968], 'GC_51 ': [0.0, 0.28804], 'GC_71 ': [-0.0, -26.266], 'GC_39 ': [0.0, 0.32662], 'GC_82 ': [-0.017058, 0.0], 'mdl_sw ': [0.4714302204356555], 'GC_55 ': [-0.0, -0.10058], 'GC_61 ': [0.0, -0.20573], 'mdl_cw__exp__2 ': [0.7777535472599892], 'mdl_ymt ': [164.5], 'GC_78 ': [16.545, 0.0], 'mdl_CKM3x3 ': [1.0], 'GC_30 ': [-0.024124, -0.0], 'GC_15 ': [0.024124, 0.0], 'mdl_aEW ': [0.0075467708984556505], 'mdl_sqrt__sw2 ': [0.4714302204356555], 'mdl_I2x33 ': [0.9448443987662922, 0.0], 'GC_72 ': [0.0, 52.532], 'GC_1 ': [-0.0, -0.10265], 'GC_52 ': [-0.0, -0.57609], 'GC_65 ': [0.0, 0.27432], 'GC_12 ': [0.0, 1.4828], 'mdl_ymb ': [4.199999809265137], 'mdl_ee ': [0.307953762847045], 'GC_79 ': [29.784, 0.0], 'mdl_sqrt__2 ': [1.4142135623730951], 'GC_31 ': [-0.0, -0.25774], 'aS ': [0.11800000071525575], 'GC_99 ': [-0.0, -0.0072172], 'mdl_vev ': [246.2184581018163], 'GC_96 ': [-0.010207, 0.0], 'GC_63 ': [0.0, 0.12671], 'GC_53 ': [0.0, 0.57609], 'GC_73 ': [26.266, 0.0], 'mdl_MZ__exp__2 ': [8315.251989618177], 'mdl_WZ ': [2.441404104232788], 'GC_9 ': [0.053768, 0.0], 'mdl_g1 ': [0.34919218438279087], 'GC_32 ': [-0.0, -0.51548], 'mdl_G ': [1.2177157884673053], 'mdl_WT ': [1.5083359479904175], 'GC_7 ': [-0.053768, 0.0], 'mdl_G__exp__2 ': [1.4828317414825511], 'GC_97 ': [0.010207, 0.0], 'GC_62 ': [0.0, 0.37035], 'GC_74 ': [-24.765, 0.0], 'mdl_MZ ': [91.18800354003906], 'mdl_MZ__exp__4 ': [69143415.65084904], 'GC_8 ': [0.0, 0.053768], 'mdl_yt ': [0.9448443987662922], 'GC_98 ': [-0.0072172, 0.0], 'mdl_ee__exp__2 ': [0.09483552005165403], 'mdl_MB ': [4.699999809265137], 'GC_33 ': [-0.0, -0.77321], 'mdl_ymtau ': [1.7769999504089355], 'mdl_WW ': [2.047600030899048], 'GC_6 ': [0.0, 0.18967], 'mdl_MTA ': [1.7769999504089355], 'GC_75 ': [24.765, 0.0], 'GC_94 ': [-0.0, -0.66811], 'mdl_MW__exp__2 ': [6467.21673128622], 'mdl_MH__exp__2 ': [15625.0], 'GC_50 ': [-0.0, -0.28804], 'GC_34 ': [0.0, 0.21336], 'GC_11 ': [0.0, 1.2177], 'mdl_sqrt__aS ': [0.3435112817874484], 'GC_58 ': [-0.0, -0.027437], 'mdl_lam ': [0.1288691060169027]} nb_value = 0 for line in testprog.stdout: self.assertTrue('Warning' not in line) if '=' not in line: continue split = line.split('=') variable = split[0].lstrip() if variable.startswith('mdl_'): variable = variable[4:] if ',' in line: value = eval(split[1]) else: value = [float(numb) for numb in split[1].split()] nb_value += 1 for i, singlevalue in enumerate(value): #try: self.assertAlmostEqual(singlevalue, solutions[variable][i], places=6, msg='fail to be equal for param %s : %s != %s' % \ (variable, singlevalue, solutions[variable][i])) #except Exception as error: # print variable # if i == 0: # solutions[variable] = [singlevalue] # else: # solutions[variable].append(singlevalue) self.assertEqual(nb_value, 116)