PKZ~jMqScanLHA/EditLHA.py#!/usr/bin/env python3 """ Interactively load/edit/save/plot HDF files. """ from pandas import read_hdf, DataFrame # noqa: F401 try: from IPython import embed ipy = True except: import code ipyt = False from glob import glob import os from matplotlib import pyplot as plt # noqa: F401 from argparse import ArgumentParser __pdoc__ = {} __pdoc__['Edit'] = """ Usage: EditLHA [-h] h5file.h5 [h5file.h5 ...] Loads the hdf files and saves them into the variable DATA. An IPython session with imported matplotlib.pyplot is started. """ __all__ = ['Edit'] def Edit(): parser = ArgumentParser(description='Interactively load/edit/save/plot HDF files.') parser.add_argument('files', metavar='h5file.h5', type=str, nargs='+', help='HDF file(s) to edit.') args = parser.parse_args() HDFFILES = [ k for f in args.files for k in glob(f) ] DATA = {} header = "Your data files are stored in 'DATA'" for f in HDFFILES: print('Reading %s ...' % f) DATA[f] = read_hdf(f) if len(DATA) == 1: HDFFILE = HDFFILES[0] DATA = DATA[HDFFILE] else: header += "and accessible via DATA['path/to/filename.h5']" if len(DATA) == 0: print('No valid data files specified.\n') else: HDFDIR = os.path.dirname(os.path.abspath(HDFFILES[0])) + '/' print('Changing working directory to {}.\n'.format(HDFDIR)) os.chdir(HDFDIR) if ipy: embed(header=header) else: print(header) code.interact(local=locals()) PK{[MOEScanLHA/MergeLHA.py#!/usr/bin/env python3 """ Merges multiple HDF files into one file. """ from pandas import HDFStore, DataFrame from glob import glob import sys from os import getenv __pdoc__ = {} __pdoc__['Merge'] = """ Merges multiple HDF files into one file. Usage: MergeLHA mergedfile.h5 file1.h5 file2.h5 [...] File names may be specified using patterns compatible with python.glob (e.g. '*.h5'). Note that it is not possible to merge different `ScanLHA.config.Config` instances i.e. the `Config` instance of the first file is used. The default H5 tree is 'results' (default of `ScanLHA.scan.Scan.save`). For changing the path set the environment variable `export LHPATH='/yourpath'`. """ def Merge(): if len(sys.argv) < 3: print('No valid filenames given!') print(__pdoc__['Merge']) sys.exit(1) infiles = [glob(f) for f in sys.argv[1:-1]] outfile = sys.argv[-1] LHAPATH = getenv('LHAPATH') if getenv('LHAPATH') else 'results' print("Will concatenate into {}.".format(outfile)) store = HDFStore(outfile) df = DataFrame() store_conf = None for fs in infiles: for f in fs: print('Reading %s ...' % f) tmp_store = HDFStore(f) tmp_conf = tmp_store.get_storer(LHAPATH).attrs.config try: tmp_conf = tmp_store.get_storer(LHAPATH).attrs.config if not store_conf: store_conf = tmp_conf except AttributeError: print('No config attribute found in {}'.format(f)) if 'scatterplot' in store_conf: tmp_conf['scatterplot'] = store_conf['scatterplot'] if store_conf and store_conf != tmp_conf: print('Warning: merge file with different config {}'.format(f)) tmp_df = tmp_store['results'] try: tmp_df['scan_seed'] = tmp_store.get_storer(LHAPATH).attrs.seed tmp_df['scan_parallel'] = tmp_store.get_storer(LHAPATH).attrs.parallel except AttributeError: pass df = df.append(tmp_df, ignore_index=True) tmp_store.close() store[LHAPATH] = df store.get_storer(LHAPATH).attrs.config = store_conf store.close() PK sjM 11ScanLHA/PlotLHA.py#!/usr/bin/env python3 """ Plot ScanLHA scan results. """ from pandas import HDFStore # from IPython import embed import logging import os from .config import Config from math import * # noqa: E403 F401 F403 from collections import ChainMap from argparse import ArgumentParser import matplotlib from matplotlib.colors import LogNorm, Normalize from matplotlib.colorbar import ColorbarBase matplotlib.use('Agg') # matplotlib.use('ps') import matplotlib.pyplot as plt # noqa: E402 __all__ = ['Plot', 'PlotConf', 'axisdefault'] axisdefault = { 'boundaries' : [], 'lognorm' : False, 'vmin' : None, 'vmax' : None, 'ticks' : [], 'colorbar' : False, 'colorbar_orientation': 'horizontal', 'label' : None, 'datafile' : None } """ Default values for all axes. """ class PlotConf(ChainMap): """ Config class which allows for successively defined defaults """ def __init__(self, *args): super().__init__(*args) self.maps.append({ 'x-axis': axisdefault, 'y-axis': axisdefault, 'z-axis': axisdefault, 'colorbar_only': False, 'constraints': [], 'legend': { 'loc' : 'right', 'bbox_to_anchor' : [1.5, 0.5] }, 'hline': False, 'vline': False, 'lw': 1.0, 's': None, 'title': False, 'label': None, 'cmap': None, 'alpha' : 1.0, 'datafile': 'results.h5', 'fontsize': 28, 'rcParams': { 'font.size': 28, 'text.usetex': True, 'font.weight' : 'bold', 'text.latex.preamble': [ r'\usepackage{xcolor}', r'\usepackage{nicefrac}', r'\usepackage{amsmath}', r'\usepackage{units}', r'\usepackage{sfmath} \boldmath'] }, 'dpi': 300, 'textbox': {} }) def new_child(self, child = {}): for ax in ['x-axis','y-axis','z-axis']: if type(child.get(ax, {})) == str: child[ax] = ChainMap({ 'field': child[ax] }, self[ax]) else: child[ax] = ChainMap(child.get(ax,{}), self[ax]) return self.__class__(child, *self.maps) def Plot(): """ Basic usage: `PlotLHA --help` Requires a YAML config file that specifies at least the `'scatterplot'` dict with the list '`plots`'. * Automatically uses the `'latex'` attribute of specified LHA blocks for labels. * Fields for x/y/z axes can be specified by either `BLOCKNAME.values.LHAID` or the specified `'parameter'` attribute. * New fields to plot can be computed using existing fields * Optional constraints on the different fields may be specified * Various options can be passed to `matplotlib`s `legend`, `scatter`, `colorbar` functions. * Optional ticks can be set manually. __Example config.yml__ --- scatterplot: conf: datafile: "mssm.h5" newfields: TanBeta: "DATA['HMIX.values.2'].apply(abs).apply(tan)" constraints: - "PDATA['TREELEVELUNITARITYwTRILINEARS.values.1']<0.5" # enforces e.g. unitarity plots: - filename: "mssm_TanBetaMSUSYmH.png" # one scatterplot y-axis: {field: TanBeta, label: '$\\tan\\beta$'} x-axis: field: MSUSY label: "$m_{SUSY}$ (TeV)$" lognorm: True ticks: - [1000,2000,3000,4000] - ['$1$','$2','$3','$4$'] z-axis: field: MASS.values.25 colorbar: True label: "$m_h$ (GeV)" alpha: 0.8 textbox: {x: 0.9, y: 0.3, text: 'some info'} - filename: "mssm_mhiggs.png" # multiple lines in one plot with legend constraints: [] # ignore all global constraints x-axis: field: MSUSY, label: 'Massparameter (GeV)' y-axis: lognorm: True, label: '$m_{SUSY}$ (GeV)' plots: - y-axis: MASS.values.25 color: red label: '$m_{h_1}$' - y-axis: MASS.values.26 color: green label: '$m_{h_2}$' - y-axis: MASS.values.35 color: blue label: '$m_{A}$' """ parser = ArgumentParser(description='Plot ScanLHA results.') parser.add_argument("config", type=str, help="path to YAML file config.yml containing the plot (and optional scan) config.") parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity") args = parser.parse_args() logging.getLogger().setLevel(logging.INFO) if args.verbose: logging.getLogger().setLevel(logging.DEBUG) c = Config(args.config) DIR = os.path.dirname(os.path.abspath(args.config)) + '/' if 'scatterplot' not in c: logging.error('config file must contain "scatterplot" dict.') exit(1) if 'plots' not in c['scatterplot']: logging.error('no plots to plot') exit(1) conf = PlotConf() conf = conf.new_child(c['scatterplot'].get('conf',{})) if not os.path.isfile(conf['datafile']): logging.error('Data file {} does not exist.'.format(conf['datafile'])) exit(1) store = HDFStore(conf['datafile']) path = 'results' # TODO DATA = store[path] attrs = store.get_storer(path).attrs if hasattr(attrs, 'config') and conf.get('conf_overwrite', False): attrs.config['scatterplot'] = {} c.append(attrs.config) if not DATA.empty and 'newfields' in conf: for field,expr in conf['newfields'].items(): logging.debug("executing DATA[{}] = {}]".format(field, expr)) DATA[field] = eval(expr) logging.debug("done.") pcount = 0 for p in c['scatterplot']['plots']: lcount = 0 pconf = conf.new_child(p) plt.cla() plt.clf() plt.rcParams.update(pconf['rcParams']) if pconf['fontsize'] != conf['fontsize']: plt.rcParams.update({'font.size': pconf['fontsize']}) if pconf['colorbar_only']: plt.figure(figsize=(8, 0.25)) ax = plt.gca() norm = Normalize(vmin=pconf['z-axis']['vmin'], vmax=pconf['z-axis']['vmax']) if pconf['z-axis']['lognorm']: norm = LogNorm(vmin=pconf['z-axis']['vmin'], vmax=pconf['z-axis']['vmax']) cbar = ColorbarBase(ax,norm=norm, cmap=pconf['cmap'], orientation=pconf['z-axis']['colorbar_orientation']) if pconf['z-axis']['colorbar_orientation'] == 'horizontal': ax.xaxis.set_label_position('top') ax.xaxis.set_ticks_position('top') if pconf['z-axis']['label']: cbar.set_label(pconf['z-axis']['label']) if pconf['z-axis']['ticks']: cbar.set_ticks(pconf['z-axis']['ticks']) plt.savefig(pconf['filename'],bbox_inches='tight') plt.figure() continue if pconf['title']: plt.title(conf['title']) if 'plots' not in p: p['plots'] = [p] for l in p['plots']: lconf = pconf.new_child(l) label = lconf['label'] label = label if label else None cmap = lconf['cmap'] zorder = lconf.get('zorder', lcount) color = lconf.get('color', "C{}".format(lcount)) x = lconf.get('x-field', lconf['x-axis'].get('field', None)) y = lconf.get('y-field', lconf['y-axis'].get('field', None)) z = lconf.get('z-field', lconf['z-axis'].get('field', None)) xlabel = lconf['x-axis']['label'] ylabel = lconf['y-axis']['label'] zlabel = lconf['z-axis']['label'] if hasattr(c, 'parameters'): xlabel = c.parameters.get(x, {'latex': xlabel})['latex'] if not xlabel else xlabel ylabel = c.parameters.get(y, {'latex': ylabel})['latex'] if not ylabel else ylabel zlabel = c.parameters.get(z, {'latex': zlabel})['latex'] if not zlabel else zlabel if xlabel: plt.xlabel(xlabel) if ylabel: plt.ylabel(ylabel) if lconf['hline']: plt.axhline(y=y, color=color, linestyle='-', lw=lconf['lw'], label=label, zorder=zorder, alpha=lconf['alpha']) continue if lconf['vline']: plt.axvline(x=x, color=color, linestyle='-', lw=lconf['lw'], label=label, zorder=zorder, alpha=lconf['alpha']) continue if hasattr(c, 'parameters'): x = c.parameters.get(x,{'lha': x})['lha'] y = c.parameters.get(y,{'lha': y})['lha'] z = c.parameters.get(z,{'lha': z})['lha'] PDATA = DATA if(lconf['datafile'] and lconf['datafile'] != conf['datafile']): conf['datafile'] = lconf['datafile'] # TODO DATA = HDFStore(lconf['datafile'])['results'] # TODO PDATA = DATA if not PDATA.empty and 'newfields' in conf: for field,expr in conf['newfields'].items(): logging.debug("executing PATA[{}] = {}]".format(field, expr)) PDATA[field] = eval(expr) logging.debug("done.") for ax,field in {'x-axis':x, 'y-axis':y, 'z-axis':z}.items(): bounds = lconf[ax]['boundaries'] if len(bounds) == 2: PDATA = PDATA[(PDATA[field] >= bounds[0]) & (PDATA[field] <= bounds[1])] for constr in lconf['constraints']: PDATA = PDATA[eval(constr)] if lconf['x-axis']['lognorm']: plt.xscale('log') if lconf['y-axis']['lognorm']: plt.yscale('log') if z: color = PDATA[z] vmin = PDATA[z].min() if not lconf['z-axis']['vmin'] else lconf['z-axis']['vmin'] vmax = PDATA[z].max() if not lconf['z-axis']['vmax'] else lconf['z-axis']['vmax'] else: vmin = None vmax = None znorm = LogNorm(vmin=vmin, vmax=vmax) if lconf['z-axis']['lognorm'] else None cs = plt.scatter(PDATA[x], PDATA[y], zorder=zorder, label=label, cmap=cmap, c=color, vmin=vmin, vmax=vmax, norm=znorm, s=lconf['s'], alpha=lconf['alpha']) plt.margins(x=0.01,y=0.01) # TODO if lconf['x-axis']['ticks']: plt.xticks(lconf['x-axis']['ticks'][0],lconf['x-axis']['ticks'][1]) if lconf['y-axis']['ticks']: plt.yticks(lconf['y-axis']['ticks'][0],lconf['y-axis']['ticks'][1]) if lconf['z-axis']['colorbar']: cbar = plt.colorbar(cs, orientation=lconf['z-axis']['colorbar_orientation']) if zlabel: cbar.set_label(zlabel) if lconf['z-axis']['ticks']: cbar.set_ticks(lconf['z-axis']['ticks']) lcount += 1 if any([l.get('label', False) for l in p['plots']]): plt.legend(**pconf['legend']) if pconf['textbox'] and 'text' in pconf['textbox']: bbox = pconf['textbox'].get('bbox', dict(boxstyle='round', facecolor='white', alpha=0.2)) va = pconf['textbox'].get('va', 'top') ha = pconf['textbox'].get('ha', 'left') textsize = pconf['textbox'].get('fontsize', pconf['rcParams'].get('font.size',15)) xtext = pconf['textbox'].get('x', 0.95) ytext = pconf['textbox'].get('y', 0.85) plt.gcf().text(xtext, ytext, pconf['textbox']['text'], fontsize=textsize ,va=va, ha=ha, bbox=bbox) plotfile = DIR + p.get('filename', 'plot{}.png'.format(pcount)) logging.info("Saving {}.".format(plotfile)) plt.savefig(plotfile, bbox_inches="tight", dpi=pconf['dpi']) pcount += 1 store.close() PKsjM"wwScanLHA/ScanLHA.py#!/usr/bin/env python3 """ Perform scans from the command line using YAML config files. """ import os import sys import logging from ScanLHA import Config, Scan, RandomScan from ScanLHA import __file__ as libpath from argparse import ArgumentParser from math import * # noqa: F401 F403 __all__ = ['ScanLHA'] def cpath(yml): if os.path.isfile(yml): return yml default = os.path.join(os.path.dirname(libpath),'configs',yml) if os.path.isfile(default): return default return yml def ScanLHA(): """ Basic usage: `ScanLHA --help`. Takes at least one argument that is the path to a config YAML file. The variety of arguments may increase if parameters in the config file are specified with the `argument` attribute. This way it is possible to define the values/scan ranges of specific parameters through command line arguments while other may be defined in the config file. __Basic scan.yml__ --- runner: binaries: - ['/bin/SPhenoMSSM', '{input_file}', '{output_file}'] - ['./HiggsBounds', 'LandH', 'SLHA', '3', '0', '{output_file}'] keep_log: true timeout: 90 scantype: random numparas: 50000 constraints: # Higgs mass constraint - "result['MASS']['values']['25']<127.09" - "result['MASS']['values']['25']>123.09" blocks: - block: MINPAR lines: - parameter: 'MSUSY' latex: '$M_{SUSY}$ (GeV)' id: 1 random: [500,3500] - parameter: 'TanBeta' latex: '$\\tan\\beta$' argument: 'value' Then start the scan e.g. with: `ScanLHA scan.yml --TanBeta 10 result10.h5` Alternatively one may specify `values: [1, 2, 10]` for TanBeta instead of `argument` or even `scan: [1, 50, 50]` to scan over TanBeta and save the result into one single file. """ parser = ArgumentParser(description='Perform an (S)LHA scan.') parser.add_argument("config", type=str, metavar="config.yml", help="path to YAML file config.yml containing config for the scan. Must be the very first argument.") parser.add_argument("output", nargs='?', default="config.h5", help="optional file path to store the results, defaults to config.h5") parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity") parser.add_argument("-p", "--parallel", metavar='N', type=int, default=None, help="parallelize on N threads") parser.add_argument("-o", "--overwrite", action="store_true", help="overwrite output files without asking") if len(sys.argv) == 1: parser.parse_args(["-h"]) if not os.path.isfile(sys.argv[1]): parser.parse_args() logging.error('No valid config file "{}".'.format(sys.argv[1])) parser.parse_args(["-h"]) logging.debug('loading config {}'.format(sys.argv[1])) scanconf = Config(sys.argv[1]) defaultfile = scanconf['runner'].get('defaults', 'SPheno.yml') if defaultfile: logging.debug('loading default config {}'.format(defaultfile)) c = Config(cpath(defaultfile)) if not c.valid: logging.error('No valid default config.') sys.exit(1) c.append(scanconf) else: c = scanconf if not c.valid: logging.error('No valid scan config.') sys.exit(1) arg_paras = [ p for p,v in c.parameters.items() if v.get('argument', False) ] arg_types = { 'help': { 'values': 'List input: para="[value1, value2, ...]"', 'value': 'Single number input: para=value', 'random': 'Random number input: para=[min,max]', 'scan': 'ScanLHA.Scan range input: para="[start, stop, num]"' }, } if arg_paras: required_paras = parser.add_argument_group("Parameters to be specified for the scan") for p in arg_paras: required_paras.add_argument("--{}".format(p), help=arg_types['help'][c[p]['argument']], required=True ) args = parser.parse_args() if args.verbose: logging.getLogger().setLevel(logging.DEBUG) for p,v in args.__dict__.items(): if p not in arg_paras: continue c[p][c[p]['argument']] = eval(v) if not c.valid: logging.error('No valid scan config.') sys.exit(1) HDFSTORE = args.output if args.output else args.config.replace('.yml','.h5') if HDFSTORE == args.config: print('Scan config file must end with ".yml"') exit(1) HDFSTORE = os.path.abspath(HDFSTORE) if os.path.exists(HDFSTORE): if args.overwrite or input("File {} already exists. Overwrite/append [o/a] ?".format(HDFSTORE)) == "o": logging.info("removing {}".format(HDFSTORE)) os.remove(HDFSTORE) if c['runner'].get('scantype', 'straight') == 'random': scan = RandomScan(c) else: scan = Scan(c) scan.submit(args.parallel) scan.save(filename=HDFSTORE) PKBsM@""ScanLHA/__init__.py#!/usr/bin/env python3 """ Perform parameter scans with HEP tools that use (not only) (S)LHA in- and output. __Use Case__ Typical tool-chains in high-energy physics (HEP) are the pass-through of one SLHA-input file from spectrum generators, e.g. [SPheno](https://spheno.hepforge.org/), to further HEP tools like [HiggsBounds](https://higgsbounds.hepforge.org/) and/or [micrOmegas](https://lapth.cnrs.fr/micromegas/) which themself return SLHA-output files. To provide correct input for the various tools between the different steps as well as to enable further processing (e.g. plotting) the SLHA format needs to be parsed and stored in a storage-efficient tabular format. In a phenomenological study, most of the physical parameters as well as config flags within a considered scenario are kept constant while only a few O(1-20) parameters are varied in different ways (grid- or randomly scanned, more sophisticated scanning techniques are planned in the future). Due to the large combinatorics, the scan may be done in parallel and even be distributed over different machines (using e.g. Sun Grid Engine, the usage of [dask.distributed](https://github.com/dask/distributed) is planned for the future). The outcome is one (or multiple) HDF files (to be merged) that may undergo further editing before the results are visualized in 2D or 3D scatter plots. __Installing__ pip3 install ScanLHA __Executables__ * [ScanLHA](https://martingabelmann.github.io/ScanLHA/ScanLHA.m.html) - Perform (S)LHA scan/s and save to HDF file/s. * [PlotLHA](https://martingabelmann.github.io/ScanLHA/PlotLHA.m.html) - Plot ScanLHA results from HDF file/s. * [EditLHA](https://martingabelmann.github.io/ScanLHA/EditLHA.m.html) - Interactively load/edit/save/plot HDF file/s. * [MergeLHA](https://martingabelmann.github.io/ScanLHA/MergeLHA.m.html) - Merge multiple HDF files into one file. The executables ``ScanLHA`` and ``PlotLHA`` take a YAML input [config](https://martingabelmann.github.io/ScanLHA/config.m.html) file. __Scanning__ The [config](https://martingabelmann.github.io/ScanLHA/config.m.html) YAML file must contain two dictionaries ``runner`` and ``blocks`` controlling the type of scan/tools to be used as well as the SLHA blocks that have to be present/scanned in the input file. In order to simplify the distribution of similar scans through grid-computing software, it is possible to declare ``argument`` SLHA entries. The value/scanrange of these entries can be set from within command line arguments. A basic config.yml file to run SPheno and HiggsBounds may look like --- runner: binaries: - ['/bin/SPhenoMSSM', '{input_file}', '{output_file}'] - ['./HiggsBounds', 'LandH', 'SLHA', '3', '0', '{output_file}'] tmpfs: /dev/shm/slha keep_log: true timeout: 90 scantype: random numparas: 50000 constraints: # Higgs mass constraint - "result['MASS']['values']['25']<127.09" - "result['MASS']['values']['25']>123.09" blocks: - block: MINPAR lines: - parameter: 'MSUSY' latex: '$M_{SUSY}$ (GeV)' id: 1 random: [500,3500] - parameter: 'TanBeta' latex: '$\\tan\\beta$' argument: 'value' - parameter: 'mu' latex: '$\\mu$ (GeV)' id: 2 value: 300 Where the ``id`` is the SLHA-id of the parameter ``parameter`` in the block ``block`` which either takes the constant value ``value``, is ``random``ly chosen or ``scan``ed in a grid. The presence of the new command line argument ``TanBeta`` may be verified with ``ScanLHA config.yml --help``. A scan that runs the SPheno->HiggsBounds chain in 2 parallel threads is started with ``ScanLHA config.yml -p 2 --TanBeta 4 scantanbeta4.h5`` (by default os.cpucount() is used for ``-p``). For this purpose, 2 copies of the binaries are stored in 2 randomly named directories in ``runner['tmpfs']`` (default: ``/dev/shm/``) where the input and output files are generated. Alternatively one may specify ``values: [1, 2, 10]`` for the line ``TanBeta`` instead of ``argument`` or even ``scan: [1, 50, 50]`` to scan over ``TanBeta`` (from 1 to 50 in 50 steps for each random value of ``MSUSY``) and save the result into one single file (likewise, the ``argument`` option can be set to ``scan`` or ``random`` and according numbers may be provided from the command line). Grid scans can have a ``distribution`` attribute equaling ``linear,log,geom,arange,uniform`` or ``normal``. The executables in ``runner['binaries']`` are run subsequential for each parameter point using given arguments. For each point a randomly named ``{input_file}`` is generated and may be passed as argument to the executables. Likewise, the ``{output_file}`` is supposed to be written by the executables and eventually parsed afterwards. One may also make direct use of Python (or C-Python) implementations instead of using executables by implementing a [runner module](https://martingabelmann.github.io/ScanLHA/runner.m.html). __Plotting__ The config.yml used for the scan may also contain a ``scatterplot`` dictionary (but can also be contained in a separate file). Plotting capabilities are: * Automatically uses the ``latex`` attribute of specified LHA ``blocks`` for labels. * Fields for x/y/z axes can be specified by either ``BLOCKNAME.values.LHAID`` or the specified ``parameter`` attribute. * New fields to plot can be computed using existing fields saved in ``DATA`` * Optional constraints on the different fields may be specified using ``PDATA`` * Various options can be passed to ``matplotlib``s ``legend``, ``scatter``, ``colorbar`` functions. * Optional ticks, textboxes, legend-position, colors, etc... can be set manually. The ``scatterplot`` dict must contain a ``conf`` dict that specifies at least the HDF ``datafile`` to load. Additionaly, defaults for x/y/z axes or other plot configs may be set and need not to be repeated in the plot definitions (but can be overwritten). In addition, the ``plots`` key contains a list of dicts that specify the ``filename`` and data to plot. An example configuration may look like --- scatterplot: conf: datafile: "mssm.h5" newfields: TanBeta: "DATA['HMIX.values.2'].apply(abs).apply(tan)" # the string is passed to eval constraints: - "PDATA['TREELEVELUNITARITYwTRILINEARS.values.1']<0.5" # enforces unitarity on the sample plots: - filename: "mssm_TanBetaMSUSYmH.png" # one scatterplot y-axis: {field: TanBeta, label: '$\\tan\\beta$'} x-axis: field: MSUSY label: "$m_{SUSY}$ (TeV)$" lognorm: True ticks: - [1000,2000,3000,4000] - ['$1$','$2','$3','$4$'] z-axis: field: MASS.values.25 colorbar: True label: "$m_h$ (GeV)" alpha: 0.8 textbox: {x: 0.9, y: 0.3, text: 'some info'} - filename: "mssm_mhiggs.png" # multiple lines in one plot with legend constraints: [] # ignore all global constraints x-axis: field: MSUSY, label: 'Massparameter (GeV)' y-axis: lognorm: True, label: '$m_{SUSY}$ (GeV)' plots: - y-axis: MASS.values.25 color: red label: '$m_{h_1}$' - y-axis: MASS.values.26 color: green label: '$m_{h_2}$' - y-axis: MASS.values.35 color: blue label: '$m_{A}$' __Editing and Merging__ See ``EditLHA --help`` and ``MergeLHA --help``. __Scanning with other (non-)SLHA Tools__ See the API docs of the [runner module](https://martingabelmann.github.io/ScanLHA/runner.m.html). __Related Tools__ * [xBIT](https://github.com/fstaub/xBIT) * [SSP](https://sarah.hepforge.org/SSP.html)/[pySSP](https://github.com/fstaub/pySSP) * ask me if you wish to be listed here """ from .scan import Scan, RandomScan from .config import Config from .runner import RUNNERS from .slha import genSLHA, parseSLHA __version__ = '0.1' __all__ = [] PKtjMm66ScanLHA/config.py""" Maps (S)LHA syntax onto YAML as well as stores configs for scanning and plotting. """ from numpy import linspace, logspace, geomspace, arange from numpy.random import uniform, normal import logging import re from sys import exit import yaml # scientific notation, see # https://stackoverflow.com/questions/30458977/yaml-loads-5e-6-as-string-and-not-a-number yaml.add_implicit_resolver( u'tag:yaml.org,2002:float', re.compile(u'''^(?: [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?:[0-5]?[0-9])+\\.[0-9_]* |[-+]?\\.(?:inf|Inf|INF) |\\.(?:nan|NaN|NAN))$''', re.X), list(u'-+0123456789.')) def intersect(list1,list2): """ Returns intersection of two lists """ return list(set(list1) & set(list2)) __all__ = ['Config'] class Config(dict): """ A dict-like object that carries information about LHA file(s), programs that import/export LHA files, and plots. 1. LHA blocks are stored in the key `'blocks'`. 2. Information about the scan to perform and used programs is stored in the key `'runner'`. 3. Information about the plots is stored in the key `'scatterplot'`. Example for accessing LHA entries: In [1]: from ScanLHA import Config In [2]: c=Config('SPheno.yml') In [3]: c.parameters # contains all LHA entries using unique parameter identifiers In [4]: c['MODSEL'] # returns the whole MODSEL block In [5]: c['MODSEL.1'] # line with LHA id=1 from block MODSEL In [6]: c['MODSEL.values.1'] # value to which the LHA id=1 in the block MODSEL is set In [7]: c['TanBeta'] # return the line which is associated with the parameter TanBeta Out[7]: {'id': 4, 'latex': '$\\tan\\beta$', 'lha': 'MINPAR.values.4', 'parameter': 'TanBeta', 'values': [1,2,3,4]} Example for `'runner'` (more see `ScanLHA.runner`): --- runner: binaries: - [ '/home/user/SPheno/bin/SPhenoMSSM', '{input_file}', '{output_file}'] - [ '/home/user/HiggsBounds-4.3.1/HiggsBounds', 'LandH', 'SLHA', '3', '0', '{output_file}'] micromegas: src: '/home/user/micrOMEGAS/src' modelname: 'MSSM' main: 'CalcOmegaDD.cpp' exec: ['CalcOmegaDD', '{output_file}'] type: MicrOmegas cleanup: false keep_log: true remove_slha: true Example for `'blocks'`: --- blocks: - block: MINPAR lines: - parameter: 'MSUSY' id: 1 scan: [2e3, 2e4, 100] distribution: 'geom' - parameter: 'TanBeta' latex: '$\\tan\\beta$' id: 2 value: 4 - .. Example for `'scatterplot'` (more see `ScanLHA.PlotLHA`): --- scatterplot: conf: datafile: "results.h5" newfields: TanBeta: "DATA['HMIX.values.11'].apply(abs).apply(tan)" M1: "DATA['MASS.values.1000022'].apply(abs)" M2: "DATA['MASS.values.1000023'].apply(abs)" Mdiff: "DATA['MASS.values.1000023'].apply(abs)-DATA['MASS.values.1000022'].apply(abs)" dpi: 200 x-axis: { field: 'MSUSY', lognorm: True, label: "$m_{SUSY}$ [TeV]", ticks: [[2000, 3000, 6000, 10000, 20000], ['$2$','$3$', '$6$', '$10$', '$20$']] } plots: - filename: 'masses.png' alpha: 0.8 legend: {'loc':'right'} y-axis: {label: '$Mass$ [GeV]', lognorm: True } textbox: {x: 0.94, y: 0.35, text: 'some info text', fontsize: 12} plots: - {y-axis: 'M1', label: '$m_{\chi_1^0}$'} - {y-axis: 'M2', label: '$m_{\chi_2^0}$'} - {vline: True, x-field: 3000, lw: 2, color: 'black', alpha: 1} - {vline: True, x-field: 6000, lw: 2, color: 'black', alpha: 1} - filename: diff.png x-axis: {field: M1, label: 'm_{\chi_1^0}'} y-axis: {field: M2, label: 'm_{\chi_2^0}'} z-axis: {field: Mdiff, label: '\delta_m'} """ def __init__(self,src): self.src = src self['runner'] = {} self['blocks'] = [] self.distribution = { 'linear': linspace, 'log': logspace, 'geom': geomspace, 'arange': arange, 'uniform': uniform, 'normal': normal } self.valid = True self.parameters = {} # directly access a block item via 'parameter' self.load() def __getitem__(self, key): if key in self.keys(): return self.get(key) if self.getBlock(key): return self.getBlock(key) if key in self.parameters: return self.parameters[key] dots = key.split('.') # access line e.g. via Config["MINPAR.1"] if len(dots) == 2: return self.getLine(dots[0], dots[1]) if len(dots) == 3: # or value/scan/values via Config["MINPAR.values.1"] line = self.getLine(dots[0], int(dots[2])) if line and dots[1] in line.keys(): return line.get(dots[1]) raise KeyError('No valid config parameter: {}'.format(key)) def load(self, src = None): """Load config from source file `src`. If the `ScanLHA.config.Config` instance was already loaded, information from the old `src` file is overwritten. After successfully loading the `ScanLHA.config.Config` instance it gets validated using `ScanLHA.config.Config.validate`. """ src = self.src if not src else src try: with open(src, 'r') as c: new = yaml.safe_load(c) for i in intersect(new.keys(), self.keys()): logging.debug('Overwriting config "{}".'.format(i)) self.update(new) if not self.validate(): logging.error('Errorenous config file.') exit(1) except FileNotFoundError: logging.error('File {} not found.'.format(src)) self.valid = False return -2 except Exception as e: logging.error("failed to load config file {}".format(src)) logging.error(str(e)) self.valid = False def save(self, dest = None): """Save `ScanLHA.config.Config` instance to destination file `dest`. If `dest==None` (default), `Config.src` is used.""" dest = self.src if not dest else dest with open(dest, 'w') as f: f.write(yaml.dump(self)) def append(self, c): """ Append information from another ScanLHA.Config instance . """ for b in ['runner', 'scatterplot']: if b in c and b in self: self[b].update(c[b]) elif b in c and b not in self: self[b] = c[b] for b in c['blocks']: if not self.getBlock(b['block']): self.setBlock(b['block'], b['lines']) else: for l in b['lines']: self.setLine(b['block'], l) return self.validate() def getBlock(self, block): """ Blocks are stored in a list of dicts. This method is to access blocks by their name. Example: In [1]: from ScanLHA import Config In [2]: c=Config('SPheno.yml') In [3]: c.getBlock('MODSEL') Out[3]: {'block': 'MODSEL', 'lines': [{'id': 1, 'value': 1, 'parameter': 'MODSEL.1', 'latex': 'MODSEL.1', 'lha': 'MODSEL.values.1'}, {'id': 2, 'value': 1, 'parameter': 'MODSEL.2', 'latex': 'MODSEL.2', 'lha': 'MODSEL.values.2'}, {'id': 6, 'value': 1, 'parameter': 'MODSEL.6', 'latex': 'MODSEL.6', 'lha': 'MODSEL.values.6'}]} """ blockpos = [i for i,b in enumerate(self['blocks']) if b['block'] == block] if not blockpos: return return self['blocks'][blockpos[0]] def getLine(self, block, id): """ Returns the line with the SLHA id `id` from the block `block` Example: In [1]: from ScanLHA import Config In [2]: c=Config('SPheno.yml') In [3]: c.getLine('MODSEL', 1) Out[3]: {'id': 1, 'value': 1, 'parameter': 'MODSEL.1', 'latex': 'MODSEL.1', 'lha': 'MODSEL.values.1'} """ b = self.getBlock(block) if not b: logging.error('Block {} not present in config.'.format(block)) return lines = b['lines'] linepos = [i for i,l in enumerate(lines) if 'id' in l and l['id'] == id] if not linepos: return return lines[linepos[0]] def setBlock(self, block, lines=[]): """ Defines a SLHA block `block` with optional lines `lines` Example: In [1]: from ScanLHA import Config In [1]: c=Config('SPheno.yml') In [1]: Config.setBlock('MINPAR', lines=[{'id': 1, 'value': 1, 'parameter': 'TanBeta', 'latex': '\\tan\\beta'}, ...]) """ b = self.getBlock(block) if b: b['lines'] = lines else: self['blocks'].append({'block':block, 'lines': lines}) return self.validate() def setLine(self, block, line): """ Add the `line` to the LHA `block` If the line already exists, the given keys are updated. Example: In [1]: from ScanLHA import Config In [2]: c=Config('SPheno.yml') In [3]: # use 1-loop RGEs In [4]: c.setLine('SPhenoInput', {'id': 38, 'value': 1}) """ b = self.getBlock(block) linepos = [i for i,l in enumerate(b['lines']) if 'id' in l and l['id'] == line['id']] if not b: return if not linepos: logging.debug('Appending new line with ID %d.' % line['id']) b['lines'].append(line) else: logging.debug('Updating line with ID %d.' % line['id']) b['lines'][linepos[0]] = line return self.validate() def validate(self): """ Validates the `ScanLHA.config.Config` instance and prepares further information attributes such as latex output. This method is applied after `ScanLHA.config.Config.load`, `ScanLHA.config.Config.setBlock`, `ScanLHA.config.Config.setLine` and `ScanLHA.config.Config.append`. """ self.valid = True if 'blocks' not in self: logging.error("No 'blocks' section in config ") self.valid = False # check for double entries lines_seen = [] self.parameters = {} for block in self['blocks']: if block['block'].count('.') > 0: logging.error('Block {} contains forbiddeni character "."!'.format(block['block'])) self.valid = False for line in block['lines']: if 'id' not in line: logging.error('No ID set for line entry!') self.valid = False if [block['block'],line['id']] in lines_seen: logging.error('Parameter {} in block {} set twice! Taking the first occurence.'.format(line['id'], block['block'])) self.valid = False if 'parameter' not in line: line['parameter'] = '{}.{}'.format(block['block'],line['id']) elif line['parameter'] in self.parameters.keys(): para = line['parameter'] + '1' logging.error('Parameter {} set twice! Renaming to {}.'.format(line['parameter'], para)) line['parameter'] = para self.valid = False self.parameters[line['parameter']] = line if 'value' in line and line.get('dependent', False) and type(line['value']) != str: print(line.get('dependent', False)) logging.error("'value' with attribute 'dependent' must be string not {} ({}, {}).".format(type(line['value']), block['block'], line['id'])) self.valid = False if 'value' in line and not line.get('dependent', False): try: float(line['value']) except ValueError: logging.error("'value' must be a number not {} ({}, {}).".format(str(type(line['value'])), block['block'], line['id'])) self.valid = False if 'values' in line and type(line['values']) != list and len(line['values']) < 1: logging.error("'values' must be a nonemtpy list ({}, {}).".format(block['block'], line['id'])) self.valid = False if 'scan' in line and type(line['scan']) != list and len(line['scan']) < 2: logging.error("'scan' must be a nonemtpy list ({}, {}).".format(block['block'], line['id'])) self.valid = False if 'latex' not in line: line['latex'] = line['parameter'] if 'lha' not in line: line['lha'] = '{}.values.{}'.format(block['block'],line['id']) lines_seen.append([block['block'], line['id']]) return self.valid PK{[M%99ScanLHA/runner.py""" Control programs that need (S)LHA input. """ from collections import defaultdict import logging from subprocess import Popen, STDOUT, PIPE, DEVNULL, TimeoutExpired from .slha import parseSLHA from random import randrange,randint import os from sys import exit from math import * # noqa: F403 F401 from shutil import copy2,copytree, rmtree from tempfile import mkdtemp from pandas.io.json import json_normalize __all__ = ['RUNNERS', 'BaseRunner', 'SLHARunner', 'MicrOmegas'] RUNNERS = {} """ Contains all available runner classes. Runners that are stored in the directory `runner_plugins` and are a child of `ScanLHA.runner.BaseRunner` are automatically added to this variable. To add your own custom runner create the `runner_plugins` directory in you working directory and add e.g. the file `myrunner.py` with e.g. the content: from ScanLHA.runner import BaseRunner class MyRunner(BaseRunner): def __init__(self, conf): super().__init__(conf) def execute(self, params): # do your computation using the # parameter set stored in the dict `params` return {'param1': myresult1, ...} To use that runner, set --- runner: type: MyRunner ... in your config. The default runner for each scan is the `ScanLHA.runner.SLHARunner`. """ class Runner_Register(type): """ Add each new runner to the `RUNNERS` variable. """ def __new__(cls, clsname, bases, attrs): newcls = super(Runner_Register, cls).__new__(cls, clsname, bases, attrs) if hasattr(newcls, 'execute') and hasattr(newcls, 'run'): RUNNERS.update({clsname: newcls}) return newcls class BaseRunner(metaclass=Runner_Register): """ Every runner must be a child of this. Needs a Config instance for initialization. """ def __init__(self,conf): """ Basic initialization. For a correct behaviour use `super().__init__(conf)` in the `__init__` of your child runner. """ self.config = conf self.rundir = os.getcwd() self.binaries = [] self.tmp = False self.initialized = False def makedirs(self, tocopy=[]): """ * Create temporary directories (default: `/dev/shm/run`). * Copy all binaries listed in `self.config['binaries']` to the temporary directory """ if 'tmpfs' not in self.config: if os.path.exists('/dev/shm/'): self.config['tmpfs'] = '/dev/shm/' else: self.config['tmpfs'] = mkdtemp() self.rundir = os.path.join(self.config['tmpfs'], 'run%d' % randint(10000,99999)) if not os.path.exists(self.rundir): logging.debug('Creating temporary directory {}.'.format(self.rundir)) os.makedirs(self.rundir) tocopy = tocopy if type(tocopy) == list else [tocopy] if 'binary' in self.config: self.binaries = [os.path.join(self.rundir, os.path.basename(self.config['binary'])), '{input_file}', '{output_file}'] tocopy.append(self.config['binary']) elif 'binaries' in self.config: if type(self.config['binaries']) != list: logging.error("syntax: runner['binaries'] = [ ['executable', 'arg1', ...], ...]") exit(1) for binary in self.config['binaries']: if type(binary) != list: logging.error("syntax: runner['binaries'] = [ ['executable', 'arg1', ...], ...]") exit(1) tocopy.append(binary[0]) self.binaries.append([os.path.join(self.rundir, os.path.basename(binary[0]))] + binary[1:]) for f in tocopy: if not os.path.exists(f): logging.error('File/dir {} not found!'.format(f)) exit(1) logging.debug('Copying {} into temporary directory {}.'.format(f, self.rundir)) if os.path.isdir(f): copytree(f, os.path.join(self.rundir, os.path.basename(f))) else: copy2(f, self.rundir) logging.debug('Changing directory') os.chdir(self.rundir) self.tmp = True def cleanup(self): """ remove temporary directory """ if not self.config.get('cleanup', False) or not self.tmp: return try: logging.debug('Removing temporary directory {}'.format(self.rundir)) os.chdir(self.config['tmpfs']) rmtree(self.rundir) except FileNotFoundError: logging.error('Directory {} does not exist.'.format(self.rundir)) except: logging.error('Could not remove directory {}.'.format(self.rundir)) def __del__(self): self.cleanup() def constraints(self, result): """ Check if the data point `result` fulfills the constraints of the list `self.config['constraints']`.""" try: if not all(map(eval, self.config['constraints'])): return return True except KeyError: return True return @staticmethod def removeFile(f, err=True): """ Removes a file `f`. """ try: os.remove(f) except FileNotFoundError: if err: logging.error('file {} missing?'.format(f)) def runBinary(self, args, cwd = None): # noqa """ Execute `args` using `Popen`. Returns `(stdout, stderr)`. `stderr` is set to `'Timeout'` if `self.timeout` is exceeded. """ proc = Popen(args, cwd=cwd, stderr=STDOUT, stdout=PIPE) try: stdout, stderr = proc.communicate(timeout=self.timeout) except TimeoutExpired: stdout = '' stderr = 'Timeout' return stdout, stderr stdout = stdout.decode('utf8').strip() if stdout else '' stderr = stderr.decode('utf8').strip() if stderr else '' return stdout, stderr def execute(self, params): """ This method specifies what the runner should do with the single data pint `params`. """ pass def run(self, params): """ Normalizes the result of `ScanLHA.runner.BaseRunner.execute`. It is e.g. used by `ScanLHA.scan.Scan` and should not be overwritten by child runners. To specify the behaviour of your custom runner overwrite the `ScanLHA.runner.BaseRunner.execute` method. """ return json_normalize(self.execute(params)) class SLHARunner(BaseRunner): """ Runner that runs binaries with (S)LHA input/output. """ def __init__(self,conf): """ `self.tpl=conf['template']` should be a string containing patterns compatible with `conf['template'].format_map(params)` for a given set of parameters `params`. """ super().__init__(conf) self.timeout = conf.get('timeout', 10) """ Timeout for Popen """ self.tpl = conf['template'] self.blocks = conf.get('getblocks', []) self.makedirs() self.initialized = True def prepare(self, params): """ Generate input and output file names. Write the input file for the parameter dict `params` using the template `self.tpl`. Returns the filenames `('inputfile', 'outputfile', 'logfile')`. """ fname = str(randrange(10**10)) fin = os.path.join(self.rundir, fname + '.in') fout = os.path.join(self.rundir, fname + '.out') flog = os.path.join(self.rundir, fname + '.log') with open(fin, 'w') as inputf: try: params = defaultdict(str, { '%{}%'.format(p) : v for p,v in params.items() }) inputf.write(self.tpl.format_map(params)) except KeyError: logging.error("Could not substitute {}.".format(params)) return None, None, None return fin, fout, flog def read(self, fout): """ Reads the file `fout` using `ScanLHA.slha.parseSLHA` and checks if all constraints `self.constraints` are fulfilled. If at least one constraint is not fulfilled, an empty result (dict) is returned. """ slha = parseSLHA(fout, self.blocks) if self.config.get('constraints', False) and not self.constraints(slha): return {} return slha def execute(self, params): """ * Prepare all files for the run with the parameters `params` (dict). * iterate over the binaries in `self.binaries` * check for fulfilled constraints Example for `self.binaries` that passes results trough the different runs: config['runner']['binaries'] = [ ['./SPheno', '{input_file}', '{output_file}'], ['./HiggsBounds', '{output_file}'] ] The patterns `{input_file}`, `{output_file}` and `{log_file}` are available and are replaced by the result of `ScanLHA.runner.SLHARunner.prepare`. """ fin, fout, flog = self.prepare(params) if not all([fin, fout, flog]): return {'log': 'Error preparing files for parameters: {parameters}'.format(params)} slha_base = { 'log_stdout': '', 'log_stderr': '', 'input_parameters': params, 'input_file': fin, 'output_file': fout, 'log_file': flog } slha = True for binary in self.binaries: if not slha: continue if type(binary) == list: # insert file names into the executable command binary = [ b.format(**slha_base) for b in binary ] else: binary = [binary] logging.debug("executing {}".format(' '.join(binary))) stdout, stderr = self.runBinary(binary) slha_base['log_stderr'] += stderr slha_base['log_stdout'] += stdout slha = self.read(fout) if self.config.get('remove_slha', True): self.removeFile(fin) self.removeFile(fout, err=False) if self.config.get('keep_log', False): slha.update(slha_base) log = 'parameters: {input_parameters}\nstdout: {log_stdout}\nstderr: {log_stderr}\n\n'.format(**slha_base) if self.config.get('logfiles', False): with open(flog, 'w') as logf: logf.write(log) slha.update({ 'log_file': flog }) logging.debug(log) return slha class MicrOmegas(SLHARunner): """ Runner for MicrOmegas based on the `ScanLHA.runner.SLHARunner`. Works exactly the same as `ScanLHA.runner.SLHARunner` but builds the MicrOmegas src files in the temporary runner directory during initialization. """ def __init__(self,conf): super(SLHARunner, self).__init__(conf) """ One needs to compile MicrOmegas for each runner since it uses hard coded paths. In order to do so, put the following information in your runner config: runner: type: MicrOmegas micromegas: src: '/home/user/micrOMEGAS/src' # source directory to copy (run make clean before) modelname: 'SplitNMSSM' # model-dir to join (run make clean before) main: 'CalcOmegaDD.cpp' # cpp file to build exec: ['CalcOmegaDD', '{input_file}'] # entry for runner['binaries'] The resulting binary is appended to the list `runner['binaries']`. If you use e.g. SPheno to generate input for MicrOmegas, you may want to add `['./SPheno', '{input_file}', '{output_file}']` to `runner['binaries']` and change the `exec` option to use the `{output_file}` instead. Additional `'binaries'` may be specified as well. """ self.timeout = conf.get('timeout', 18000) self.tpl = conf['template'] self.blocks = conf.get('getblocks', []) if 'micromegas' not in self.config: logging.error('need to specify "micromegas" config') exit(1) omega = self.config['micromegas'] if 'src' not in omega or not os.path.exists(omega['src']): logging.error('need to specify micromegas "src" directory to build from') exit(1) if 'modelname' not in omega: logging.error('need to specify "modelname" name') exit(1) if 'main' not in omega: logging.error('need to specify "main" cpp file to build') exit(1) if 'exec' not in omega: logging.error('need to specify "exec"utable created by the build followed by its arguments (Popen list syntax)') exit(1) self.makedirs(tocopy = omega['src']) self.omegadir = os.path.join(self.rundir,os.path.basename(omega['src'])) self.modeldir = os.path.join(self.omegadir, omega['modelname']) logging.debug('running "make clean" on MicrOmegas installtion.') Popen('yes|make clean', shell=True, stdout=DEVNULL, stderr=DEVNULL, cwd=self.omegadir) logging.debug('running "make" on MicrOmegas installtion.') i = 0 stdout, stderr = "", "MicrOmegas was already built(?)" while not os.path.isfile(self.omegadir + '/include/microPath.h') and i < 15: stdout, stderr = self.runBinary(['make'], cwd=self.omegadir) i += 1 if i >= 5: logging.error('Build failed') logging.error(stdout) logging.error(stderr) logging.debug('running "make clean" on MicrOmegas model.') os.chdir(self.modeldir) Popen(['make', 'clean'], stdout=DEVNULL, stderr=DEVNULL, shell=True, cwd=self.modeldir) logging.debug('running "make main={}" on MicrOmegas model.'.format(omega['main'])) i = 0 stdout, stderr = "", "The model was already built(?)" while not os.path.isfile(omega['exec'][0]) and i < 15: stdout, stderr = self.runBinary(['make', 'main='+omega['main']], cwd=self.modeldir) i += 1 if i < 15 and i != 0: logging.debug('file {} was build'.format(omega['exec'][0])) self.initialized = True else: logging.error(stdout) logging.error(stderr) os.chdir(self.rundir) self.binaries.append([os.path.join(self.modeldir, omega['exec'][0])] + omega['exec'][1:]) PKsjM"T7,7,ScanLHA/scan.py# import lzma """ Control random- and grid-scans. """ import logging from collections import ChainMap import os from numpy import linspace, prod from concurrent.futures import ProcessPoolExecutor as Executor from concurrent.futures import as_completed from tqdm import tqdm from math import * # noqa: F403 F401 from itertools import product from pandas import HDFStore, concat, DataFrame from .slha import genSLHA from .runner import RUNNERS from numpy.random import seed, uniform from time import time from glob import glob import importlib if os.path.isdir('runner_plugins'): # dynamically import custom runners from the directory "./runner_plugins" for runner in glob('runner_plugins/*.py'): importlib.import_module(runner.replace('/', '.').replace('.py', '')) def substitute(param_dict): """ recusively apply format_map onto keys of using """ subst = { p : str(v).format_map(param_dict) for p,v in param_dict.items() } if param_dict == subst: return { p : eval(v) for p,v in subst.items() } else: return substitute(subst) __all__ = ['Scan', 'RandomScan'] class Scan(): """ Scan object Controls a scan over a n-dimensional parameter range using a grid. Needs a Config object (see `ScanLHA.config.Config`) for initialization. The `'runner'` config must be present as well. """ def __init__(self, c): self.config = c self.config['runner']['template'] = genSLHA(c['blocks']) self.getblocks = self.config.get('getblocks', []) self.runner = RUNNERS[self.config['runner'].get('type','SLHARunner')] self.scanset = [] scan = None for block in c['blocks']: for line in block['lines']: if 'scan' in line: self.addScanRange(block['block'], line) scan = True elif 'values' in line: self.addScanValues(block['block'], line) scan = True if not scan: logging.info("No scan parameters defined in config!") logging.info("Register a scan range with addScanRange(, {'id': , 'scan': [,,]})") logging.info("Register a list of scan values with addScanValues(,{'id': , 'values': [1,3,6,...])") def addScanRange(self, block, line): """ Register a scan range for LHA entry in the block . `'line'` must be a dict containing: 1. the LHA id 'id' within the block `block` 2. a scan range 'scan' consisting of a two-tuple 3. optional: `'distribution'` can be `'log'`, `'linear'`, `'geom'`, `'arange'`, `'uniform'` and `'normal'`. default: `'linear'` """ if 'id' not in line: logging.error("No 'id' set for parameter.") return if 'scan' not in line or len(line['scan']) < 2: logging.error("No proper 'scan' option set for parameter %d." % line['id']) return dist = self.config.distribution.get(line['distribution'], linspace) if 'distribution' in line else linspace line['scan'] = [ eval(str(s)) for s in line['scan'] ] line.update({'values': dist(*line['scan'])}) self.addScanValues(block, line) def addScanValues(self, block, line): """ Set a LHA entry to a specific list of input values in the block `block`. `line` must be a dict containing the: 1. `id` of the LHA entry within the block 2. `values` given as a list """ if 'id' not in line: logging.error("No 'id' set for parameter.") return if 'values' not in line or len(line['values']) < 1: logging.error("No proper 'values' option set for paramete %d." % line['id']) return self.config.setLine(block, line) # update the slha template with new config self.config['runner']['template'] = genSLHA(self.config['blocks']) def build(self,num_workers=4): """ Expand parameter lists and scan ranges while substituting eventual dependencies. """ if not self.config.validate(): return values = [] for parameter,line in self.config.parameters.items(): if 'values' in line: values.append([{str(parameter): num} for num in line['values']]) if 'dependent' in line and 'value' in line: values.append([{line['parameter']: line['value']}]) self.numparas = prod([len(v) for v in values]) logging.info('Build all %d parameter points.' % self.numparas) self.scanset = [ substitute(dict(ChainMap(*s))) for s in product(*values) ] if self.scanset: return self.numparas return def scan(self, dataset): """ Register an runner using the config and apply it on `dataset` """ # this is still buggy: https://github.com/tqdm/tqdm/issues/510 # res = [ runner.run(d) for d in tqdm(dataset) ] runner = self.runner(self.config['runner']) return concat([ runner.run(d) for d in dataset ], ignore_index=True) def submit(self,num_workers=None): """ Start a scan and distribute it on `num_workers` threads. If `num_workers` is omitted, the value of `os.cpu_count()` is used. Results are stored in `self.results`. """ num_workers = os.cpu_count() if not num_workers else num_workers if not self.scanset: self.build(num_workers) if num_workers == 1: runner = self.runner(self.config['runner']) self.results = concat([ runner.run(d) for d in tqdm(self.scanset) ], ignore_index=True) return chunksize = min(int(self.numparas/num_workers),1000) chunks = range(0, self.numparas, chunksize) logging.info('Running on host {}.'.format(os.getenv('HOSTNAME'))) logging.info('Splitting dataset into %d chunks.' % len(chunks)) logging.info('Will work on %d chunks in parallel.' % num_workers) with Executor(num_workers) as executor: futures = [ executor.submit(self.scan, self.scanset[i:i+chunksize]) for i in chunks ] progresser = tqdm(as_completed(futures), total=len(chunks), unit = 'chunk') self.results = [ r.result() for r in progresser ] self.results = concat(self.results, ignore_index=True) def save(self, filename='store.hdf', path='results'): """ Saves `self.results` into the HDF file `filename` in the tree `path`. """ print('Saving to {} ({})'.format(filename,path)) if path == 'config': logging.error('Cant use "config" as path, using "config2" instead.i') path = "config2" store = HDFStore(filename) store[path] = self.results store.get_storer(path).attrs.config = self.config store.close() class RandomScan(): """ Scan object Controls a scan over an n-dimensional parameter range using uniformly distributed numbers. Needs a Config object (see `ScanLHA.config.Config`) for initialization. The `'runner'` config-entry needs to specify the number `'numparas'` of randomly generated parameters. """ def __init__(self, c, seed=None): self.config = c self.numparas = eval(str(c['runner']['numparas'])) self.config['runner']['template'] = genSLHA(c['blocks']) self.getblocks = self.config.get('getblocks', []) self.runner = RUNNERS[self.config['runner'].get('type','SLHARunner')] self.parallel = os.cpu_count() self.seed = round(time()) if not seed else seed self.randoms = { p : [eval(str(k)) for k in v['random']] for p,v in c.parameters.items() if 'random' in v } self.dependent = { p : v['value'] for p,v in c.parameters.items() if v.get('dependent',False) and 'value' in v } def generate(self): """ Generate uniformly distributed numbers for specified SLHA blocks. Substitute the numbers in dependend blocks, if necessary. """ dataset = { p : v for p,v in self.dependent.items() } [ dataset.update({ p : uniform(*v)}) for p,v in self.randoms.items() ] return substitute(dataset) def scan(self, numparas, pos=0): """ Register a runner using the config and generate `numparas` data samples. Returns a `pandas.DataFrame`. """ numresults = 0 runner = self.runner(self.config['runner']) if not runner.initialized: logging.error('Could not initialize runner.') return DataFrame() results = [] seed(self.seed + pos) with tqdm(total=numparas, unit='point', position=pos) as bar: while numresults < numparas: result = runner.run(self.generate()) if not result.isnull().values.all(): results.append(result) numresults += 1 bar.update(1) return concat(results, ignore_index=True) def submit(self,num_workers=None): """ Start a scan and distribute it on `num_workers` threads. If `num_workers` is omitted, the value of `os.cpu_count()` is used. Results are stored in `self.results`. """ num_workers = os.cpu_count() if not num_workers else num_workers self.parallel = num_workers logging.info('Running on host {}.'.format(os.getenv('HOSTNAME'))) logging.info('Will work on %d threads in parallel.' % num_workers) if num_workers == 1: self.results = self.scan(self.numparas) return paras_per_thread = int(self.numparas/num_workers) remainder = self.numparas % num_workers numparas = [ paras_per_thread for p in range(num_workers) ] numparas[-1] += remainder with Executor(num_workers) as executor: futures = [ executor.submit(self.scan, j, i) for i,j in enumerate(numparas) ] self.results = [ r.result() for r in as_completed(futures) ] self.results = concat(self.results, ignore_index=True) def save(self, filename='store.hdf', path='results'): """ Saves `self.results` into the HDF file `filename` in the tree `path`. """ if self.results.empty: return print('Saving to {} ({})'.format(filename,path)) if path == 'config': logging.error('Cant use "config" as path, using "config2" instead.') path = "config2" store = HDFStore(filename) store[path] = self.results store.get_storer(path).attrs.config = self.config store.get_storer(path).attrs.seed = self.seed store.get_storer(path).attrs.parallel = self.parallel store.close() class FileScan(Scan): """ Performs a scan based on input file(s) from a previous scan. Needs a Config object (see `ScanLHA.config.Config`) for initialization. TODO: not yet functional """ def __init__(self, c): self.config = c self.getblocks = self.config.get('getblocks', []) self.runner = RUNNERS[self.config['runner'].get('type','SLHARunner')] PK{[M&,oU U ScanLHA/slha.py""" Parsing and writing of (S)LHA files. """ from collections import defaultdict import logging import pylha def genSLHA(blocks): """ Generate string in SLHA format from `'blocks'` entry of a `ScanLHA.config.Config` instance. """ out = '' for block in blocks: out += 'BLOCK {}\n'.format(block['block']) for data in block['lines']: data = defaultdict(str,data) if any(k in ['scan','values','random','dependent'] for k in data): try: para = data['parameter'] except KeyError: logging.info('Using {}.{} as template parameter.'.format(block, data['id'])) para = '{}.{}'.format(block,data['id']) data['value'] = '{%' + para + '%}' out += '{id} {value} #{parameter} {comment}\n'.format_map(data) return out def list2dict(l): """ recursively convert [1,2,3,4] to {'1':{'2':{'3':4}} """ if len(l) == 1: return l[0] return { str(l[0]) : list2dict(l[1:]) } def mergedicts(l, d): """ merge list of nested dicts """ if type(l) == list: d.update(l[0]) for dct in l[1:]: mergedicts(dct, d) return d elif type(l) == dict: for k,v in l.items(): if k in d and isinstance(d[k], dict): mergedicts(l[k], d[k]) else: d[k] = l[k] 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 PK{[MUNNNScanLHA/configs/SPheno.yml--- runner: binaries: [] tmpfs: '/dev/shm/slha/' keep_log: False logfile: False remove_slha: True blocks: - block: MODSEL lines: - {id: 1, value: 1} # input at the high scale - {id: 2, value: 1} # boundary condition to choose - {id: 6, value: 1} # generation mixing - block: SMINPUTS lines: - {id: 2, value: 1.166390E-05} # G_F - {id: 3, value: 1.172000E-01} # alpha_s(MS)^MSbar - {id: 4, value: 9.118760E+01} # z pole mass - {id: 5, value: 4.20000E+00} # bottom mass (MSbar) - {id: 6, value: 1.729000E+02} # top pole mass - {id: 7, value: 1.7770E+00} # tau pole mass - block: SPhenoInput lines: - {id: 1, value: -2} # error level - {id: 7, value: 0} # 1/0 skips/includes two loop Higgs masses - {id: 9, value: 1} # two loop corrections in gaugeless limit - {id: 11, value: 1} # calculate branching ratios - {id: 12, value: 1.0E-04} # threshold for writing branching ratios - {id: 13, value: 3} # 3-Body decays: 0/1/2/3 none/fermions/scalars/both - {id: 31, value: -1} # -1 dynamical GUT scale - {id: 38, value: 2} # 1- or 2-Loop RGEs - {id: 20, value: 1} # mass uncreatanties - {id: 51, value: 1} # Write Output in CKM basis - {id: 55, value: 1} # Calculate loop corrected masses - {id: 57, value: 1} # Calculate low energy constraints - {id: 66, value: 1} # 1/0 turn Two-Scale Matching on/off - {id: 67, value: 1} # effective Higgs mass calculation: 1/2 auto/always - {id: 75, value: 1} # Write WHIZARD files - {id: 76, value: 1} # Write HiggsBounds file - {id: 77, value: 1} # Output for MicrOmegas - {id: 78, value: 1} # Output for MadGraph - {id: 79, value: 1} # Write WCXF files - {id: 515, value: 1} # write parameters at GUT scale - {id: 520, value: 1} # Write effective Higgs couplings - {id: 530, value: 1} # Write Blocks for Vevacious - block: DECAYOPTIONS lines: - {id: 1, value: 1} # Cha - {id: 2, value: 1} # Chi - {id: 3, value: 1} # Glu PK!H/(I&ScanLHA-0.1.dist-info/entry_points.txtN+I/N.,()rM,p NNzPM-JOE X\9(|+KBi+(PKnM ~~ScanLHA-0.1.dist-info/LICENSE GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. PK!Hd BUcScanLHA-0.1.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,rzd&Y)r$[)T&UD"PK!H M "ScanLHA-0.1.dist-info/METADATAYmo_A$$/qĉ#rr=ڥ\! $XDr2V?<s)S5Pf秓Ni\ŕ*yBmU) m,NOK+*D/˭ȳditΆBf+[T6r ֱFKA#p:[ʹJReZs˟.|ٙT6˱M}/ U*u2޿\R&,uaeYu-pYe" cvz&&EQ*o.ߋ7*SLU5Ot?y)I뽹:?kөn:;4Ӂ:DgR8le<$+Q+C#zT` 1CyES%`8NXy*LB[VX=l^P27ӫXe^tS V^oEUiR9wJܜWYddbq?>E7˷ZֱD6¬4юwCØNJT*3+k!:׹0Бa^]x/^:WcRDzP%"O #$*s -EY$<3-XLImARDmɟCXPVΫDivFC)|Ɂcl"͍0ZyKH2K_ F$ cNTpl@#  V3mmB/K )K OA2*S逓&/bm,, Vq_$|Ƌ dW"Sӯ0ߒ I4 ZC"J!D%uEHRyEZʖ6 a8ӫ88` lEǭ2,&.h\~ niӨ/i5" pTNR]iX]$/N_v!z.S e"3 S:U)w{)A\m*OțGȪ0НQ$ H *tqԔ:>yTae) o ʭn:R?HئI_ z?2.=Km&W;#mV1#Sv'0wGZP3KZ}SI.qD:%[l/( o}Řj­m:i)+U},f3Ou6cofވn%L.=|8a݉FT/ԃ _f9䦕a!be<.I|#eιҡ|}38Z}[qhU8R.cTpzG1]0kK^iDDЁѩڠ`P&H12z(T:pOiٴXE~dtdX*nc.+>Sc~WrvݕRVT[x w%b:mLkt/&iMЧ=)JOǿb9XnOǚh,_; HewyӉ߽[Gcqs,n`>~SkirWro:ٰͻk&ߴ˴wcqx51zCju܌xYv;d׈H47LTѦSf f gf(aw(}fz 4;;a %vcx?B8 4+Gn^m nX%lF ]sJ@͛j6(ߺoF-Pk(׹8:z  2zС7_X,$W&*s~m7ޘMUeAebzEƜb7]G΋6jqQG+߷Eۏ7h =p ]O5@*oXvOD>6pOI!2WIQ Y$M- rm=ny2T6O%Ґ3 >ڽ#440Q2Кz| #H J"-蓐V?;xOdg\SeqD]]8E=[7|t;~7[R+{˘m'׌Ϫ -*>p_<˹$;,{2h90i@0LamFsW`nNʒ" AwܥUnJ VW#(Nՠ rwN[@MW:*o(L;g4TC=ЭA wjU*+\2,H]Bj_uГ ) RUɘG&ؖ{ƛbs>Rc^ǛSOg!QM?uv?(UOMD3Kmd0:& hnjOa0r\;99?przwgg'wZ̗S !B=:_mWuG~[ڳެZGA-M5QkmX %j,~gk >>otwcv,{({!no?0QS6.!2`S!ۋ8;{vDo/ۻ?}SɴjtN-~6LXңl-yPgiGX[nݎ})ƚ{] cW;7AHN'X&|47mu_Kl|79^&GTc6P/\|߾vY*!ƇΓYs$j$=TQ Nk_?X_Pw]C/˳a/Z&Mp?:Q6 tN%܂4\g;".|D}(mzzЏĈ7c1TyN,*`&IK!PK!H,8qScanLHA-0.1.dist-info/RECORDuɒHH&a LApC2hbdrmGUշ'x3<ıts'74eK?U 1Cw0ۛ\)>Smܑ, (7p:W7ZTZ9<)4 ~,RuV:Y zypǰ-j5;t+w.~̀7+$xi.P5q<.A[͂x3һG8%7|F*I0mYqXsSĢflR%ra{ MG:D2oXo%v)pb H(k=V3wd7[!>0rPǼ!L櫢yR2ྩo~(%>љsY`Sb}>~]𓪹Tg? rMwѲ"xs3WHӿ25WfErl=tL <0bboY `x/&`rMbi4՘ͤ}/~? D[GAiy?Z~5J_tg_ E?Q-mF3?P{ *,[ !v2UO j|7S@;\0HӵH{hY&A[ N N#> לLWRcU~aW0PKZ~jMqScanLHA/EditLHA.pyPK{[MOEMScanLHA/MergeLHA.pyPK sjM 11MScanLHA/PlotLHA.pyPKsjM"ww@ScanLHA/ScanLHA.pyPKBsM@""=UScanLHA/__init__.pyPKtjMm66wScanLHA/config.pyPK{[M%99ScanLHA/runner.pyPKsjM"T7,7,ScanLHA/scan.pyPK{[M&,oU U CScanLHA/slha.pyPK{[MUNNN ScanLHA/configs/SPheno.ymlPK!H/(I&K)ScanLHA-0.1.dist-info/entry_points.txtPKnM ~~)ScanLHA-0.1.dist-info/LICENSEPK!Hd BUcScanLHA-0.1.dist-info/WHEELPK!H M "GScanLHA-0.1.dist-info/METADATAPK!H,8qScanLHA-0.1.dist-info/RECORDPK