def test_write(self): # read s = pkgutil.get_data('pylha', 'tests/data/SPheno.spc') d = pylha.load(s.decode('utf-8')) # export json s = pylha.dump(d, 'json') self.assertIsInstance(s, str) d = json.loads(s) self.assertIsInstance(d, dict) f = tempfile.TemporaryFile(mode='w+') pylha.dump(d, 'json', f) # export yaml s = pylha.dump(d, 'yaml') self.assertIsInstance(s, str) d = yaml.load(s) self.assertIsInstance(d, dict) f = tempfile.TemporaryFile(mode='w+') pylha.dump(d, 'yaml', f) # export lha s = pylha.dump(d, 'lha') self.assertIsInstance(s, str) d = pylha.load(s) self.assertIsInstance(d, dict) f = tempfile.TemporaryFile(mode='w+') pylha.dump(d, 'lha', f) pylha.load(f)
def test_load(self): sm = pkgutil.get_data('smeftrunner', 'tests/data/SMInput-CPV.dat').decode('utf-8') wc = pkgutil.get_data( 'smeftrunner', 'tests/data/WCsInput-CPV-SMEFT.dat').decode('utf-8') wcout = pkgutil.get_data( 'smeftrunner', 'tests/data/Output_SMEFTrunner.dat').decode('utf-8') io.sm_lha2dict(pylha.load(sm)) io.wc_lha2dict(pylha.load(wc)) CSM = io.sm_lha2dict(pylha.load(wcout)) C = io.wc_lha2dict(pylha.load(wcout)) C2 = io.wc_lha2dict(io.wc_dict2lha(C)) for k in C: npt.assert_array_equal(C[k], C2[k]) smeft = SMEFT() smeft.load_initial((wcout, )) for k in C: npt.assert_array_equal(definitions.symmetrize(C)[k], smeft.C_in[k], err_msg="Failed for {}".format(k)) for k in CSM: npt.assert_array_equal(definitions.symmetrize(CSM)[k], smeft.C_in[k], err_msg="Failed for {}".format(k)) CSM2 = io.sm_lha2dict(io.sm_dict2lha(CSM)) for k in CSM: npt.assert_array_equal(CSM[k], CSM2[k], err_msg="Failed for {}".format(k))
def test_read(self): for test_file in test_in: s = pkgutil.get_data('pylha', 'tests/data/{}'.format(test_file)) d = pylha.load(s.decode('utf-8')) self.assertTrue(d) # not empty for k in d: self.assertIn(k, ['BLOCK', 'DECAY']) # no unknown blocks
def BLOCKdict(streams): d = {} for stream in streams: s = pylha.load(stream) if 'BLOCK' not in s: raise ValueError("No BLOCK found") d.update(s['BLOCK']) return d
def load(stream, fmt='lha'): """Load a parameter file in DSixTools SLHA-like format or its JSON or YAML representation.""" if fmt == 'lha': return pylha.load(stream) elif fmt == 'json': if isinstance(stream, str): return json.loads(stream) else: return json.load(stream) elif fmt == 'yaml': return yaml.safe_load(stream)
def parseSLHA(slhafile, blocks=[]): """ Turn the content of an SLHA file into a dictionary `slhafile` : path tp file `blocks` : list of BLOCKs (strings) to read, if empty all blocks are read Uses [pylha](https://github.com/DavidMStraub/pylha pylha) but gives a more meaningful output the result is stored in a nested dictionary. """ try: with open(slhafile,'r') as f: slha = pylha.load(f) except FileNotFoundError: logging.error('File %s not found.' % slhafile) return {} except: logging.error('Could not parse %s !' % slhafile) return {} try: slha_blocks = slha['BLOCK'] except KeyError: slha_blocks = {} if blocks: slha_blocks = { b : v for b,v in slha_blocks.items() if b in blocks } try: # TODO convert into valid slha instead of dropping slha_blocks.pop('HiggsBoundsInputHiggsCouplingsBosons') slha_blocks.pop('HiggsBoundsInputHiggsCouplingsFermions') except KeyError: pass for b,v in slha_blocks.items(): try: v['values'] = mergedicts([list2dict(l) for l in v['values']],{}) v['info'] = ''.join(str(i) for i in v['info']) except: pass if 'DECAY' not in slha: return slha_blocks decayblock = 'DECAYS' if 'DECAY' in slha_blocks else 'DECAY' slha_blocks[decayblock] = slha['DECAY'] for d,v in slha_blocks[decayblock].items(): try: v['values'] = mergedicts([list2dict(list(reversed(l))) for l in v['values']],{}) v['info'] = ''.join(str(i) for i in v['info']) if len(v['info']) > 1 else v['info'][0] except: pass return slha_blocks
def test_wcxf2smeftsim(self): tmpdir = mkdtemp() # use default settings res = subprocess.run(['wcxf2smeftsim', os.path.join(data_path, 'test.Warsaw_mass.yml')], cwd=tmpdir) # check return code self.assertEqual(res.returncode, 0, msg="Command failed") # check if file is present outf = os.path.join(tmpdir, 'wcxf2smeftsim_param_card.dat') self.assertTrue(os.path.isfile, outf) # check if can be imported as LHA with open(outf, 'r') as f: out = pylha.load(f) # check string is not empty self.assertTrue(out) # remove tmpdir rmtree(tmpdir)
def test_symm_fac(self): wc = wcxf.WC('SMEFT', 'Warsaw mass', 120, {'ll_1111': 1e-6, 'll_1221': 4e-6}) tmpdir = mkdtemp() with open(os.path.join(tmpdir, 'my_wcxf.yaml'), 'w') as f: wc.dump(f, fmt='yaml') res = subprocess.run(['wcxf2smeftsim', 'my_wcxf.yaml'], cwd=tmpdir) # check if file is present outf = os.path.join(tmpdir, 'wcxf2smeftsim_param_card.dat') self.assertTrue(os.path.isfile, outf) with open(outf) as f: card = pylha.load(f) self.assertEqual(dict(card['BLOCK']['FRBlock']['values'])[691], 1e6 * 4e-6 / 2, # symmetry factor of 1 / 2! msg="Wrong value for ll_1221") self.assertEqual(dict(card['BLOCK']['FRBlock']['values'])[689], 1e6 * 1e-6, # no symmetry factor! msg="Wrong value for ll_1111")
def test_exc(self): # this should work d = pylha.load(r"""BLOCK name 1 2.0 """) self.assertDictEqual(d, {'BLOCK': {'name': {'values': [[1, 2.0]]}}}) # missing block name with self.assertRaises(pylha.parse.ParseError): pylha.load("""BLOCK 1 2.0 """) # missing block name but comment with self.assertRaises(pylha.parse.ParseError): pylha.load("""BLOCK # bla 1 2.0 """) # no block with self.assertRaises(pylha.parse.ParseError): pylha.load(""" 1 2.0 """)
def test_format_comments(self): # various checks with differently formatted numbers and spaces self.assertDictEqual( pylha.load("BLOCK name\n1\t2.0 #comment", comments=True), {'BLOCK': { 'name': { 'values': [[1, 2.0, '#comment']] } }}) self.assertDictEqual(pylha.load("BLOCK name\n \t 1 2."), {'BLOCK': { 'name': { 'values': [[1, 2.]] } }}) self.assertDictEqual( pylha.load("BLOCK name\n \t 1 2.#comment", comments=True), {'BLOCK': { 'name': { 'values': [[1, 2.0, '#comment']] } }}) self.assertDictEqual( pylha.load("BLOCK name\n \t 11325325 .2#comment", comments=True), {'BLOCK': { 'name': { 'values': [[11325325, 0.2, '#comment']] } }}) self.assertDictEqual( pylha.load("BLOCK name\n1\t2.#2.0comment", comments=True), {'BLOCK': { 'name': { 'values': [[1, 2.0, '#2.0comment']] } }}) self.assertDictEqual( pylha.load("BLOCK name\n \t 1 .#2.0comment", comments=True), {'BLOCK': { 'name': { 'values': [[1, '.', '#2.0comment']] } }})
def parseSLHA(slhafile, blocks=[]): """ Turn the content of an SLHA file into a dictionary `slhafile` : path tp file `blocks` : list of BLOCKs (strings) to read, if empty all blocks are read Uses [pylha](https://github.com/DavidMStraub/pylha pylha) but gives a more meaningful output the result is stored in a nested dictionary. Converts (i.e. reverses) non-standard SLHA entrys (such as HiggsBounds). """ reversed_blocks = [ 'HiggsBoundsInputHiggsCouplingsBosons', 'HiggsBoundsInputHiggsCouplingsFermions', 'HiggsCouplingsFermions', 'HiggsCouplingsBosons' ] # blocks which have more than one numerical value are joined into a "|"-separated string list_blocks = { 'HiggsCouplingsFermions': 2, 'HiggsBoundsInputHiggsCouplingsFermions': 2, } try: with open(slhafile, 'r') as f: slha = pylha.load(f) except FileNotFoundError: logging.error('File %s not found.' % slhafile) return {} except: logging.error('Could not parse %s !' % slhafile) return {} try: slha_blocks = slha['BLOCK'] except KeyError: slha_blocks = {} if blocks: slha_blocks = {b: v for b, v in slha_blocks.items() if b in blocks} for b, v in slha_blocks.items(): try: if b in list_blocks: v['values'] = [['|'.join(str(y) for y in x[:list_blocks[b]])] + x[list_blocks[b]:] for x in v['values']] if b in reversed_blocks: [x.reverse() for x in v['values']] v['values'] = mergedicts([list2dict(l) for l in v['values']], {}) v['info'] = ''.join(str(i) for i in v['info']) except: pass if 'DECAY' not in slha: return slha_blocks decayblock = 'DECAYS' if 'DECAY' in slha_blocks else 'DECAY' slha_blocks[decayblock] = slha['DECAY'] for d, v in slha_blocks[decayblock].items(): try: v['values'] = mergedicts( [list2dict(list(reversed(l))) for l in v['values']], {}) v['info'] = ''.join( str(i) for i in v['info']) if len(v['info']) > 1 else v['info'][0] except: pass return slha_blocks