Beispiel #1
0
    def __init__( self, status, inputFile, parameters, databaseVersion):
        """
        Initialize output. If one of the checks failed, exit.
        
        """

        try:
            filename=os.path.join ( installation.installDirectory(),
                                    'smodels/version' )
            with open( filename, 'r') as versionFile:
                version = versionFile.readline()
            self.smodelsVersion = version.replace('\n','')
        except IOError:
            self.smodelsVersion = None

        self.inputfile = inputFile.replace("//","/")
        self.parameters = parameters
        self.filestatus = status[0]
        self.warnings = status[1]
        self.databaseVersion = databaseVersion
        self.statusStrings = {-1: "#could not run the decomposition",
                              - 3: "#no cross sections above sigmacut found",
                              - 4: "#database not found",
                              - 2: "#bad input file, did not run decomposition",
                               0: "#no matching experimental results",
                               1: "#decomposition was successful"}

        self.status = 0
        if not self.databaseVersion:
            self.status = -4
        if self.filestatus < 0:
            self.status = -2
def loadDatabase(parser, db):
    """
    Load database
    
    :parameter parser: ConfigParser with path to database
    :parameter db: binary database object. If None, then database is loaded,
                   according to databasePath. If True, then database is loaded,
                   and text mode is forced.
    :returns: database object, database version
        
    """
    try:
        databasePath = parser.get("path", "databasePath")
        if databasePath == "micromegas":
            databasePath = installDirectory() + "/smodels-database/"
        database = db
        if database in [None, True]:
            force_load = None
            if database == True: force_load = "txt"
            database = Database(databasePath, force_load=force_load)
        databaseVersion = database.databaseVersion
    except DatabaseNotFoundException:
        logger.error("Database not found in %s" %
                     os.path.realpath(databasePath))
        sys.exit()
    return database, databaseVersion
Beispiel #3
0
def main():
    import argparse
    """ Set default input and output files """
    parameterFile = "%s/smodels/etc/parameters_default.ini" % installDirectory()
    outputDir = "./results/"

    """ Get the name of input SLHA file and parameter file """
    ap = argparse.ArgumentParser( description=
            "Run SModelS over SLHA/LHE input files." )
    ap.add_argument('-f', '--filename',
            help='name of SLHA or LHE input file or a directory path (required argument). '
            'If a directory is given, loop over all files in the directory', required=True)
    ap.add_argument('-p', '--parameterFile',
            help='name of parameter file, where most options are defined (optional argument). If not set, use '
            'all parameters from smodels/etc/parameters_default.ini',
            default=parameterFile)
    ap.add_argument('-o', '--outputDir',
            help='name of output directory (optional argument). The default folder is: ' +
            outputDir, default=outputDir)
    ap.add_argument('-d', '--development', help='if set, SModelS will run in development mode and exit if any errors are found.',
            action='store_true')
    ap.add_argument('-t', '--force_txt', help='force loading the text database',
            action='store_true')
    ap.add_argument('-C', '--colors', help='colored output',
            action='store_true')
    ap.add_argument('-V', '--version', action='version', version = version() )
    ap.add_argument('-c', '--run-crashreport',
            help='parse crash report file and use its contents for a SModelS run. '
                 "Supply the crash file simply via '--filename myfile.crash'",
            action='store_true')
    ap.add_argument('-v','--verbose', help='sets the verbosity level (debug, info, warning, error). Default value is info.',
            default = "info", type = str )
    ap.add_argument('-T', '--timeout',
            help='define a limit on the running time (in secs).'
                 'If not set, run without a time limit. If a directory is given as input, '
                 'the timeout will be  applied for each individual file.',
            default = 0, type = int)


    args = ap.parse_args()
    if args.colors:
        from smodels.tools.colors import colors
        colors.on = True


    db=None
    if args.force_txt: db=True
    smodelsLogging.setLogLevel ( args.verbose )

    if args.run_crashreport:
        args.filename, args.parameterFile = crashReport.readCrashReportFile(
                args.filename)
        run(args.filename, args.parameterFile, args.outputDir,
               db, args.timeout, development=True )

    else:
        run(args.filename, args.parameterFile, args.outputDir,
              db, args.timeout, args.development)
    def createCrashReportFile(self, inputFileName, parameterFileName):
        """
        Create a new SModelS crash report file.
        
        A SModelS crash report file contains:
        
        - a timestamp
        - SModelS version
        - platform information (CPU architecture, operating system, ...)
        - Python version
        - stack trace
        - input file name
        - input file content
        - parameter file name
        - parameter file content
        
        :param inputFileName: relative location of the input file
        :param parameterFileName: relative location of the parameter file
        
        """

        with open(installDirectory() + '/smodels/version', 'r') as versionFile:
            version = versionFile.readline()

        with open(inputFileName, 'r') as inputFile:
            inputFileContent = inputFile.read()

        with open(parameterFileName, 'r') as parameterFile:
            parameterFileContent = parameterFile.read()

        with open(self.crashReportFileName, 'w') as crashReportFile:
            crashReportFile.write("=" * 80 + "\n")
            crashReportFile.write("SModelS Crash Report File\n")
            crashReportFile.write("=" * 80 + "\n")
            crashReportFile.write("Timestamp: " + self.timestampHuman + "\n\n")
            crashReportFile.write("SModelS Version: " + version + "\n")
            crashReportFile.write("Platform: " + platform.platform() + "\n")
            crashReportFile.write("Python Version: " +
                                  platform.python_version() + "\n\n")
            crashReportFile.write("=" * 80 + "\n\n")
            crashReportFile.write("-" * 80 + "\n")
            crashReportFile.write("* Output\n")
            crashReportFile.write("-" * 80 + "\n\n")
            crashReportFile.write(traceback.format_exc() + "\n\n")
            crashReportFile.write("-" * 80 + "\n")
            crashReportFile.write("* Input File\n")
            crashReportFile.write("  " + os.path.basename(inputFileName) +
                                  "\n")
            crashReportFile.write("-" * 80 + "\n\n")
            crashReportFile.write(inputFileContent + "\n")
            crashReportFile.write("-" * 80 + "\n")
            crashReportFile.write("* Parameter File\n")
            crashReportFile.write("  " + os.path.basename(parameterFileName) +
                                  "\n")
            crashReportFile.write("-" * 80 + "\n\n")
            crashReportFile.write(parameterFileContent)
Beispiel #5
0
 def createCrashReportFile(self, inputFileName, parameterFileName):
     """
     Create a new SModelS crash report file.
     
     A SModelS crash report file contains:
     
     - a timestamp
     - SModelS version
     - platform information (CPU architecture, operating system, ...)
     - Python version
     - stack trace
     - input file name
     - input file content
     - parameter file name
     - parameter file content
     
     :param inputFileName: relative location of the input file
     :param parameterFileName: relative location of the parameter file
     
     """
 
     with open ( installDirectory()+'/smodels/version', 'r') as versionFile:
         version = versionFile.readline()
 
     with open(inputFileName, 'r') as inputFile:
         inputFileContent = inputFile.read()
 
     with open(parameterFileName, 'r') as parameterFile:
         parameterFileContent = parameterFile.read()
 
     with open(self.crashReportFileName, 'w') as crashReportFile:
         crashReportFile.write("="*80+"\n")
         crashReportFile.write("SModelS Crash Report File\n")
         crashReportFile.write("="*80+"\n")
         crashReportFile.write("Timestamp: " + self.timestampHuman + "\n\n")
         crashReportFile.write("SModelS Version: " + version + "\n")
         crashReportFile.write("Platform: " + platform.platform() + "\n")
         crashReportFile.write("Python Version: " + platform.python_version() + "\n\n")
         crashReportFile.write("="*80+"\n\n")
         crashReportFile.write("-"*80+"\n")
         crashReportFile.write("* Output\n")
         crashReportFile.write("-"*80+"\n\n")
         crashReportFile.write(traceback.format_exc() + "\n\n")
         crashReportFile.write("-"*80+"\n")
         crashReportFile.write("* Input File\n")
         crashReportFile.write("  " + os.path.basename(inputFileName) + "\n")
         crashReportFile.write("-"*80+"\n\n")
         crashReportFile.write(inputFileContent + "\n")
         crashReportFile.write("-"*80+"\n")
         crashReportFile.write("* Parameter File\n")
         crashReportFile.write("  " + os.path.basename(parameterFileName) + "\n")
         crashReportFile.write("-"*80+"\n\n")
         crashReportFile.write(parameterFileContent)
Beispiel #6
0
 def absPath(self, path):
     """
     Get the absolute path of <path>, replacing <install> with the
     installation directory.
     
     """
     if path == None:
         return self.tempDirectory() + "/temp.cfg"
     installdir = installation.installDirectory()
     path = path.replace("<install>", installdir)
     # path = path.replace(".egg/smodels", ".egg/")
     path = os.path.abspath(path)
     return path
Beispiel #7
0
 def absPath(self, path):
     """
     Get the absolute path of <path>, replacing <install> with the
     installation directory.
     
     """
     if path == None:
         return self.tempDirectory() + "/temp.cfg"
     installdir = installation.installDirectory()
     path = path.replace("<install>", installdir)
     # path = path.replace(".egg/smodels", ".egg/")
     path = os.path.abspath(path)
     return path
Beispiel #8
0
def getParticlesFromModule(modelFile):
    """
    Reads the python model file and retrieves the list of BSM particles (BSMList)

    :param modelFile: Name/path to the python module containing the BSM particle definitions

    :return: a list of Particle objects
    """

    from smodels.installation import installDirectory
    from importlib import import_module
    fulldir = os.path.join(installDirectory(), "smodels", "share", "models")
    sys.path.insert(0, installDirectory())
    sys.path.insert(0, os.path.join(installDirectory(), "smodels"))
    sys.path.insert(0, fulldir)
    sys.path.insert(0, ".")

    logger.debug("Trying to load model file: %s" % modelFile)

    fname = modelFile[:]
    if fname.endswith(".py"):
        fname = modelFile[:-3]
    if "/" in fname:
        import shutil
        filename = os.path.basename(fname)
        shutil.copy(fname, filename)
    else:
        filename = fname

    pM = import_module(filename, package='smodels')
    logger.debug("Found model file at %s" % pM.__file__)
    if filename != fname:
        os.remove(filename)
    BSMList = pM.BSMList

    return BSMList
Beispiel #9
0
    def getHeader ():
        from smodels.installation import installDirectory
        header = ""
        with open( installDirectory()+"smodels/share/BANNER") as f:
            lines=f.readlines()
            for line in lines: header+=line

        header += "\n"
        header += "fb, pb, GeV, TeV defined.\n"
        header +=  "\nBrowser loaded for %s \n" %( args.path_to_database )
        header += "Try 'print(browser)' for the list of available results.\n"
        header += "More examples on how to access the database can be found in the SModelS manual.\n"
        header += "\nType 'exit' to exit this session."

        return header
    def checkInstallation(self, fix=False):
        """
        Check if installation of tool is correct by looking for executable and
        running it.

        :param fix: should it try to fix the situation, if something is wrong?

        :returns: True, if everything is ok
        
        """
        if not os.path.exists(self.executablePath):
            logger.error("Executable '%s' not found. Maybe you didn't compile " \
                         "the external tools in smodels/lib?", self.executablePath)
            if fix:
                self.compile()
            return False
        if not os.access(self.executablePath, os.X_OK):
            logger.error("%s is not executable", self.executable)
            self.chmod()
            return False
        slhaFile = "/inputFiles/slha/gluino_squarks.slha"
        slhaPath = installation.installDirectory() + slhaFile
        try:
            output = self.run(slhaPath,
                              "<install>/etc/pythia_test.card",
                              do_compile=False,
                              do_check=False)
            output = output.split("\n")
            if output[-1].find("The following floating-point") > -1:
                output.pop()

            output.pop()
            val = (" ********* Fraction of events that fail fragmentation "
                   "cuts =  0.00000 *********")
            lines = {-1: val}
            for (nr, line) in lines.items():
                if output[nr].find(line) == -1:
                    logger.error("Expected >>>%s<<< found >>>%s<<<", line,
                                 output[nr])
                    return False
        except Exception as e:
            logger.error("Something is wrong with the setup: exception %s", e)
            return False
        return True
    def checkInstallation(self, fix=False ):
        """
        Check if installation of tool is correct by looking for executable and
        running it.

        :param compile: should it try to fix the situation, if something is wrong?

        :returns: True, if everything is ok
        
        """
        if not os.path.exists(self.executablePath):
            logger.error("executable '%s' not found", self.executablePath)
            if fix:
                self.compile()
            return False
        if not os.access(self.executablePath, os.X_OK):
            logger.error("%s is not executable", self.executable)
            self.chmod()
            return False
        slhaFile = "/inputFiles/slha/gluino_squarks.slha"
        slhaPath = installation.installDirectory() + slhaFile
        try:
            output = self.run(slhaPath, "<install>/etc/pythia_test.card",
                    do_compile=False, do_check=False ) 
            output = output.split("\n")
            if output[-1].find("The following floating-point") > -1:
                output.pop()

            output.pop()
            val = (" ********* Fraction of events that fail fragmentation "
                   "cuts =  0.00000 *********")
            lines = {-1 : val}
            for (nr, line) in lines.items():
                if output[nr].find(line) == -1:
                    logger.error("Expected >>>%s<<< found >>>%s<<<", line,
                                 output[nr])
                    return False
        except Exception, e:
            logger.error("Something is wrong with the setup: exception %s", e)
            return False
Beispiel #12
0
    def __init__( self, status, inputFile, parameters, databaseVersion):
        """
        Initialize output. If one of the checks failed, exit.
        
        :parameter status: status of input file
        :parameter inputFile: input file name
        :parameter parameters: input parameters
        :parameter databaseVersion: database version (string)        
        """

        try:
            filename=os.path.join ( installation.installDirectory(),
                                    'smodels/version' )
            with open( filename, 'r') as versionFile:
                version = versionFile.readline()
            self.smodelsVersion = version.replace('\n','')
        except IOError:
            self.smodelsVersion = None

        self.inputfile = inputFile.replace("//","/")
        self.parameters = parameters
        self.filestatus = status[0]
        self.warnings = status[1]
        self.databaseVersion = databaseVersion
        self.statusStrings = {-1: "#could not run the decomposition",
                              - 3: "#no cross sections above sigmacut found",
                              - 4: "#database not found",
                              - 2: "#bad input file, did not run decomposition",
                               0: "#no matching experimental results",
                               1: "#decomposition was successful"}

        self.status = 0
        if not self.databaseVersion:
            self.status = -4
        if self.filestatus < 0:
            self.status = -2
Beispiel #13
0
        if unlink:
            self.unlink( unlinkdir=True )
        else:
            f = open(self.tempDirectory() + "/log", "w")
            f.write (cmd + "\n\n\n")
            f.write (out + "\n")
            f.close()
        return out

if __name__ == "__main__":
    #from smodelsLogging import setLogLevel
    #setLogLevel ( "debug" )
    tool = Pythia6Wrapper()
    print("[Pythia6Wrapper] installed: " + str(tool.installDirectory()))
    td_exists = wrapperBase.ok(os.path.exists(tool.tempDirectory()))
    print("[Pythia6Wrapper] temporary directory: %s: %s" % (str(tool.tempDirectory()),
                                           td_exists))
    print("[Pythia6Wrapper] check: " + wrapperBase.ok(tool.checkInstallation()))
    print("[Pythia6Wrapper] seconds per event: %d" % tool.secondsPerEvent)
    tool.replaceInCfgFile({"NEVENTS": 1, "SQRTS":8000})
    tool.setParameter("MSTP(163)", "6")
    slhafile = "inputFiles/slha/simplyGluino.slha"
    slhapath = os.path.join ( installation.installDirectory(), slhafile )
    # print ( "[Pythia6Wrapper] slhapath:",slhapath )
    xsec = tool.run(slhapath, unlink=True )
    # n = len (output.split("\n"))
    # print ( "n: ",n )
    isok = abs ( xsec[0].value.asNumber ( pb ) - 2.80E-01  ) < 1e-5
    print("[Pythia6Wrapper] run: " + wrapperBase.ok (isok))
    # tool.unlink()
Beispiel #14
0
def main():
    import argparse
    parser = argparse.ArgumentParser(description="SModelS-tools command line tool.")

    parser.add_argument('-v','--verbose', help='verbosity level. '
                        'accepted values are: debug, info, warning, error.',
                                    default = "info", type = str )

    subparsers = parser.add_subparsers(dest='subparser_name')

    installation = subparsers.add_parser('installation', description="Print installation setup and exit.")
    fixpermissions = subparsers.add_parser('fixpermissions', description="Fix file permissions for xseccomputer.")
    xseccomputer = subparsers.add_parser('xseccomputer', description="Compute MSSM cross sections for a SLHA file.")
    xseccomputer.add_argument('-s', '--sqrts', nargs='+', action='append',
        help="sqrt(s) TeV. Can supply more than one value (as a space separated list). Default is both 8 and 13.",
        type=int, default=[])
    xseccomputer.add_argument('-e', '--nevents', type=int, default=10000,
        help="number of events to be simulated.")
    xseccomputer.add_argument('-v', '--verbosity', type=str, default="info",
        help="Verbosity (debug, info, warning, error)")
    xseccomputer.add_argument('-c', '--ncpus', type=int, default=-1,
        help="number of cores to be used simultaneously. -1 means 'all'. ")
    xseccomputer.add_argument('-p', '--tofile', action='store_true',
        help="write cross sections to file (only highest order)")
    xseccomputer.add_argument('-P', '--alltofile', action='store_true',
        help="write all cross sections to file, including lower orders")
    xseccomputer.add_argument('-q', '--query', action='store_true',
        help="only query if there are cross sections in the file")
    xseccomputer.add_argument('-C', '--colors', action='store_true',
        help="colored terminal output" )
    xseccomputer.add_argument('-k', '--keep', action='store_true',
        help="do not unlink temporary directory")
    xseccomputer.add_argument('-6', '--pythia6', action='store_true',
        help="use pythia6 for LO cross sections")
    xseccomputer.add_argument('-8', '--pythia8', action='store_true',
        help="use pythia8 for LO cross sections (default)")
    xseccomputer.add_argument('-n', '--NLO', action='store_true',
        help="compute at the NLO level (default is LO)")
    xseccomputer.add_argument('-N', '--NLL', help="compute at the NLO+NLL level (takes precedence over NLO, default is LO)", action='store_true')
    xseccomputer.add_argument('-O', '--LOfromSLHA', help="use LO cross sections from file to compute the NLO or NLL cross sections", action='store_true')
    xseccomputer.add_argument('-f', '--filename', required=True,
            help="SLHA file to compute cross sections for. "
            "If a directory is given, compute cross sections for all files in directory." )

    slhachecker = subparsers.add_parser('slhachecker', description="Perform several checks on a SLHA file.")
    slhachecker.add_argument('-xS', '--xsec', help='turn off the check for xsection blocks', action='store_false')
    slhachecker.add_argument('-s', '--sigmacut', help='give sigmacut in fb', default=.03, type=float)
    slhachecker.add_argument('-illegal', '--illegal', help='turn on check for kinematically forbidden decays', action='store_true')
    slhachecker.add_argument('-dB', '--decayBlocks', help='turn off the check for missing decay blocks', action='store_false')
    slhachecker.add_argument('-f', '--filename', help='name of input SLHA file', required=True)

    lhechecker = subparsers.add_parser('lhechecker', description="Check if the input file has LHE format.")
    lhechecker.add_argument('-f', '--filename', help='name of input LHE file', required=True)

    dbBrowser = subparsers.add_parser('database-browser', description="Interface for browsing the Database.")
    dbBrowser.add_argument('-p', '--path_to_database', help='path to SModelS database', required=True)
    dbBrowser.add_argument('-t', '--text', help='load text database, dont even search for binary database file', action='store_true')
    
    iPlots = subparsers.add_parser('interactive-plots', description="Produces a set of interactive plots for visualizing results from a scan.")
    iPlots.add_argument('-p', '--parameters', help='path to the parameters file [./iplots_parameters.py]', default = './iplots_parameters.py')
    iPlots.add_argument('-f', '--smodelsFolder', help='path to the smodels folder with the SModelS python output files.', 
                            required=True)
    iPlots.add_argument('-s', '--slhaFolder', help='path to the SLHA folder with the SLHA input files.', 
                            required=True)
    iPlots.add_argument('-o', '--outputFolder', 
                  help='path to the output folder, where the plots will be stored. [./iplots]', 
                  default = "./iplots" )
    
    iPlots.add_argument('-N', '--npoints', type=int, default=-1,
        help="How many (randomly selected) points will be included in the plot. If -1 all points will be read and included (default = -1).")
    
    iPlots.add_argument('-v', '--verbosity', type=str, default="info",
        help="Verbosity (debug, info, warning, error)")


    toolbox = subparsers.add_parser( 'toolbox', description=
								                     "Facility to control external dependencies")
    toolbox.add_argument('-c', '--colors', help='turn on terminal colors',
                           action='store_true')
    toolbox.add_argument('-l', '--long', help='long output lines',
                           action='store_true')
    toolbox.add_argument('-m', '--make', help='compile packages if needed',
                           action='store_true')
    args = parser.parse_args()

    from smodels.tools import smodelsLogging
    smodelsLogging.setLogLevel(args.verbose)

    if args.subparser_name == 'fixpermissions':
        from smodels import installation
        installation.fixpermissions()

    if args.subparser_name == 'installation':
        from smodels import installation
        import sys, os
        print ( installation.banner() )
        print ( "SModelS version:", installation.version() )
        print ( "Installation directory:",installation.installDirectory() )
        path = os.path.abspath(os.path.realpath(__file__))
        print ( "This binary:",path )
        sys.exit()
    if args.subparser_name == 'toolbox':
        from smodels.tools import toolBox
        toolBox.main ( args )
    if args.subparser_name == 'xseccomputer':
        from smodels.tools import xsecComputer
        xsecComputer.main(args)
    if args.subparser_name == 'slhachecker':
        from smodels.tools import slhaChecks
        slhaChecks.main(args)
    if args.subparser_name == 'lhechecker':
        from smodels.tools import lheChecks
        lheChecks.main(args)
    if args.subparser_name == 'database-browser':
        from smodels.tools import databaseBrowser
        databaseBrowser.main(args)
    if args.subparser_name == 'interactive-plots':
        from smodels.tools import interactivePlots
        interactivePlots.main(args)
            val = (" ********* Fraction of events that fail fragmentation "
                   "cuts =  0.00000 *********")
            lines = {-1: val}
            for (nr, line) in lines.items():
                if output[nr].find(line) == -1:
                    logger.error("Expected >>>%s<<< found >>>%s<<<", line,
                                 output[nr])
                    return False
        except Exception as e:
            logger.error("Something is wrong with the setup: exception %s", e)
            return False
        return True


if __name__ == "__main__":
    tool = ExternalPythia6()
    print("installed: " + str(tool.installDirectory()))
    td_exists = externalTool.ok(os.path.exists(tool.tempDirectory()))
    print("temporary directory: %s: %s" %
          (str(tool.tempDirectory()), td_exists))
    print("check: " + externalTool.ok(tool.checkInstallation()))
    print("seconds per event: %d" % tool.secondsPerEvent)
    tool.replaceInCfgFile({"NEVENTS": 1, "SQRTS": 8000})
    tool.setParameter("MSTP(163)", "6")
    slhafile = "/inputFiles/slha/andrePT4.slha"
    slhapath = installation.installDirectory() + slhafile
    output = tool.run(slhafile)
    isok = (len(output.split("\n")) > 570)
    print("run: " + externalTool.ok(isok))
    tool.unlink()
            val = (" ********* Fraction of events that fail fragmentation "
                   "cuts =  0.00000 *********")
            lines = {-1 : val}
            for (nr, line) in lines.items():
                if output[nr].find(line) == -1:
                    logger.error("Expected >>>%s<<< found >>>%s<<<", line,
                                 output[nr])
                    return False
        except Exception, e:
            logger.error("Something is wrong with the setup: exception %s", e)
            return False
        return True


if __name__ == "__main__":
    tool = ExternalPythia6()
    print("installed: " + str(tool.installDirectory()))
    td_exists = externalTool.ok(os.path.exists(tool.tempDirectory()))
    print("temporary directory: %s: %s" % (str(tool.tempDirectory()),
                                           td_exists))
    print("check: " + externalTool.ok(tool.checkInstallation()))
    print("seconds per event: %d" % tool.secondsPerEvent)
    tool.replaceInCfgFile({"NEVENTS": 1, "SQRTS":8000})
    tool.setParameter("MSTP(163)", "6")
    slhafile = "/inputFiles/slha/andrePT4.slha"
    slhapath = installation.installDirectory() + slhafile
    output = tool.run(slhafile)
    isok = (len (output.split("\n")) > 570)
    print("run: " + externalTool.ok (isok))
    tool.unlink()
# In[3]:

# define where the database resides
smsHelpers.base=os.path.join(os.getenv("HOME"),"smodels-database/")


# In[4]:

# load list of analyses from database
listOfAnalyses = smsAnalysisFactory.load()


# In[5]:

# Define the SLHA file name
filename = "%s/inputFiles/slha/gluino_squarks.slha" % installDirectory()


# In[6]:

# Perform the decomposition:
listOfTopologies = slhaDecomposer.decompose (filename, sigcut=0.5*fb, doCompress=True, doInvisible=True, minmassgap=5*GeV)


# In[7]:

# Initiate missing Topologies for 8 TeV
missingtopos = missingTopologies.MissingTopoList(8*TeV)


# In[8]:
Beispiel #18
0
#!/usr/bin/env python

"""
.. module:: runSModelS
   :synopsis: Main code for running SModelS.
   
"""

import sys, os, logging
from smodels.installation import installDirectory
sys.path.append(installDirectory()+"/Unum-4.1.3-py2.7.egg/")
import argparse
from ConfigParser import SafeConfigParser
from smodels.tools.physicsUnits import GeV, fb
from smodels.tools import slhaPrinter
log = logging.getLogger(__name__)


def main(inputFile, parameterFile, outputFile, slhaOutputFile, particlePath):
    """
    Provides a command line interface to basic SModelS functionalities.
    
    :param inputFile: input file name (either a SLHA or LHE file)
    :param parameterFile: File containing the input parameters (default = /etc/parameters_default.ini)
    :param outputFile: Output file to write a summary of results
    :param slhaOutputFile: Output file to write SLHA type summary of results
    :param particlePath: Path to directory where particles.py is stored
    
    """

    """
    return kFacs


def getDecoupledKfactors(nllpath, process, energy, pdf, mass):
    """
    Compute k-factors in the decoupled (squark or gluino) regime for the process.
    If a decoupled grid does not exist for the process, return None
    """

    if process != 'sb' and process != 'gg': return None
    elif process == 'sb': process_dcpl = 'sdcpl'
    elif process == 'gg': process_dcpl = 'gdcpl'
    nll_run = "./nllfast_" + energy + " %s %s %s" % \
                      (process_dcpl, pdf, mass)
    nll_output = runNLLfast(nll_run, nllpath)
    if "K_NLO" in nll_output:
        return getKfactorsFrom(nll_output)
    else:
        return None


if __name__ == "__main__":
    """
    Calculate k factors for a pid pair.
    
    """
    slhaF = installation.installDirectory() + "inputFiles/slha/T1.slha"
    kNLO, kNLL = getKfactorsFor((1000021, 1000021), 13. * TeV, slhaF)
    print("nlo, nll = " + str(kNLO) + ", " + str(kNLL))
Beispiel #20
0
def main():
    parser = argparse.ArgumentParser(description="SModelS command line tool.")
    subparsers = parser.add_subparsers(dest='subparser_name')

    xseccomputer = subparsers.add_parser(
        'xseccomputer',
        description="Compute MSSM cross sections for a SLHA file.")
    xseccomputer.add_argument(
        '-s',
        '--sqrts',
        nargs='+',
        action='append',
        help="sqrt(s) TeV. Can supply more than one value.",
        type=int,
        default=[])
    xseccomputer.add_argument('-e',
                              '--nevents',
                              type=int,
                              default=10000,
                              help="number of events to be simulated.")
    xseccomputer.add_argument('-p',
                              '--tofile',
                              action='store_true',
                              help="write cross sections to file")
    xseccomputer.add_argument('-k',
                              '--keep',
                              action='store_true',
                              help="do not unlink temporary directory")
    xseccomputer.add_argument('-n',
                              '--NLO',
                              action='store_true',
                              help="compute at the NLO level (default is LO)")
    xseccomputer.add_argument(
        '-N',
        '--NLL',
        help=
        "compute at the NLO+NLL level (takes precedence over NLO, default is LO)",
        action='store_true')
    xseccomputer.add_argument(
        '-O',
        '--LOfromSLHA',
        help=
        "use LO cross-sections from file to compute the NLO or NLL cross-sections",
        action='store_true')
    xseccomputer.add_argument('-f',
                              '--filename',
                              help="SLHA file to compute cross sections for",
                              required=True)
    xseccomputer.add_argument(
        '-particles',
        '--particlePath',
        help='path to directory where particles.py is located',
        default=installDirectory() + "/smodels")

    slhachecker = subparsers.add_parser(
        'slhachecker', description="Perform several checks on a SLHA file.")
    slhachecker.add_argument('-xS',
                             '--xsec',
                             help='turn off the check for xsection blocks',
                             action='store_false')
    slhachecker.add_argument('-lsp',
                             '--lsp',
                             help='turn off the check for charged lsp',
                             action='store_false')
    slhachecker.add_argument(
        '-longlived',
        '--longlived',
        help=
        'turn off the check for stable charged particles and visible displaced vertices',
        action='store_false')
    slhachecker.add_argument(
        '-m',
        '--displacement',
        help='give maximum displacement of secondary vertex in m',
        default=.001,
        type=float)
    slhachecker.add_argument('-s',
                             '--sigmacut',
                             help='give sigmacut in fb',
                             default=.01,
                             type=float)
    slhachecker.add_argument(
        '-illegal',
        '--illegal',
        help='turn on check for kinematically forbidden decays',
        action='store_true')
    slhachecker.add_argument(
        '-dB',
        '--decayBlocks',
        help='turn off the check for missing decay blocks',
        action='store_false')
    slhachecker.add_argument('-f',
                             '--filename',
                             help='name of input SLHA file',
                             required=True)
    slhachecker.add_argument(
        '-particles',
        '--particlePath',
        help='path to directory where particles.py is located',
        default=installDirectory() + "/smodels")

    lhechecker = subparsers.add_parser(
        'lhechecker', description="Check if the input file has LHE format.")
    lhechecker.add_argument('-f',
                            '--filename',
                            help='name of input LHE file',
                            required=True)
    lhechecker.add_argument(
        '-particles',
        '--particlePath',
        help='path to directory where particles.py is located',
        default=installDirectory() + "/smodels")

    args = parser.parse_args()
    """
    check if particles.py exists in specified path, and add to sys.path
    """
    if not os.path.isfile(os.path.join(args.particlePath, "particles.py")):
        log.error("particle.py not found in %s" % args.particlePath)
        return
    else:
        sys.path.insert(1, args.particlePath)
        from smodels.tools import xsecComputer
        from smodels.tools import slhaChecks, lheChecks

    if args.subparser_name == 'xseccomputer':
        xsecComputer.main(args)
    if args.subparser_name == 'slhachecker':
        slhaChecks.main(args)
    if args.subparser_name == 'lhechecker':
        lheChecks.main(args)
Beispiel #21
0
def main():
    import argparse
    parser = argparse.ArgumentParser(
        description="SModelS-tools command line tool.")

    parser.add_argument('-v',
                        '--verbose',
                        help='verbosity level. '
                        'accepted values are: debug, info, warning, error.',
                        default="info",
                        type=str)

    subparsers = parser.add_subparsers(dest='subparser_name')

    subparsers.add_parser('installation',
                          description="Print installation setup and exit.")
    subparsers.add_parser('fixpermissions',
                          description="Fix file permissions for xseccomputer.")
    xseccomputer = subparsers.add_parser(
        'xseccomputer',
        description="Compute MSSM cross sections for a SLHA file.")
    xseccomputer.add_argument(
        '-s',
        '--sqrts',
        nargs='+',
        action='append',
        help=
        "sqrt(s) TeV. Can supply more than one value (as a space separated list). Default is both 8 and 13.",
        type=int,
        default=[])
    xseccomputer.add_argument('-e',
                              '--nevents',
                              type=int,
                              default=10000,
                              help="number of events to be simulated [10000].")
    xseccomputer.add_argument('-v',
                              '--verbosity',
                              type=str,
                              default="info",
                              help="Verbosity (debug, info, warning, error)")
    xseccomputer.add_argument(
        '-c',
        '--ncpus',
        type=int,
        default=-1,
        help="number of cores to be used simultaneously. -1 means 'all'. ")
    xseccomputer.add_argument(
        '-p',
        '--tofile',
        action='store_true',
        help="write cross sections to file (only highest order)")
    xseccomputer.add_argument(
        '-P',
        '--alltofile',
        action='store_true',
        help="write all cross sections to file, including lower orders")
    xseccomputer.add_argument(
        '-q',
        '--query',
        action='store_true',
        help="only query if there are cross sections in the file")
    xseccomputer.add_argument('-C',
                              '--colors',
                              action='store_true',
                              help="colored terminal output")
    xseccomputer.add_argument('--noautocompile',
                              action='store_true',
                              help="turn off automatic compilation")
    xseccomputer.add_argument('-k',
                              '--keep',
                              action='store_true',
                              help="do not unlink temporary directory")
    xseccomputer.add_argument('-6',
                              '--pythia6',
                              action='store_true',
                              help="use pythia6 for LO cross sections")
    xseccomputer.add_argument(
        '-8',
        '--pythia8',
        action='store_true',
        help="use pythia8 for LO cross sections (default)")
    xseccomputer.add_argument('-n',
                              '--NLO',
                              action='store_true',
                              help="compute at the NLO level (default is LO)")
    xseccomputer.add_argument(
        '-N',
        '--NLL',
        help=
        "compute at the NLO+NLL level (takes precedence over NLO, default is LO)",
        action='store_true')
    xseccomputer.add_argument(
        '-O',
        '--LOfromSLHA',
        help=
        "use LO cross sections from file to compute the NLO or NLL cross sections",
        action='store_true')
    xseccomputer.add_argument(
        '-S',
        '--ssmultipliers',
        type=str,
        default=None,
        help="Signal strength multipliers, provided as dictionary of pids")
    xseccomputer.add_argument(
        '-f',
        '--filename',
        required=True,
        help="SLHA file to compute cross sections for. "
        "If a directory is given, compute cross sections for all files in directory."
    )

    slhachecker = subparsers.add_parser(
        'slhachecker', description="Perform several checks on a SLHA file.")
    slhachecker.add_argument('-xS',
                             '--xsec',
                             help='turn off the check for xsection blocks',
                             action='store_false')
    slhachecker.add_argument(
        '-illegal',
        '--illegal',
        help='turn on check for kinematically forbidden decays',
        action='store_true')
    slhachecker.add_argument(
        '-dB',
        '--decayBlocks',
        help='turn off the check for missing decay blocks',
        action='store_false')
    slhachecker.add_argument('-f',
                             '--filename',
                             help='name of input SLHA file',
                             required=True)

    lhechecker = subparsers.add_parser(
        'lhechecker', description="Check if the input file has LHE format.")
    lhechecker.add_argument('-f',
                            '--filename',
                            help='name of input LHE file',
                            required=True)

    dbBrowser = subparsers.add_parser(
        'database-browser', description="Interface for browsing the Database.")
    dbBrowser.add_argument('-p',
                           '--path_to_database',
                           help='path to SModelS database',
                           required=True)
    dbBrowser.add_argument(
        '-t',
        '--text',
        help='load text database, dont even search for binary database file',
        action='store_true')

    iPlots = subparsers.add_parser(
        'interactive-plots',
        description=
        "Produces a set of interactive plots for visualizing results from a scan."
    )
    iPlots.add_argument(
        '-p',
        '--parameters',
        help='path to the parameters file [./iplots_parameters.py]',
        default='./iplots_parameters.py')
    iPlots.add_argument(
        '-f',
        '--smodelsFolder',
        help='path to the smodels folder with the SModelS python output files.',
        required=True)
    iPlots.add_argument(
        '-s',
        '--slhaFolder',
        help='path to the SLHA folder with the SLHA input files.',
        required=True)
    iPlots.add_argument(
        '-o',
        '--outputFolder',
        help=
        'path to the output folder, where the plots will be stored. [./iplots]',
        default="./iplots")

    iPlots.add_argument(
        '-N',
        '--npoints',
        type=int,
        default=-1,
        help=
        "How many (randomly selected) points will be included in the plot. If -1 all points will be read and included (default = -1)."
    )

    iPlots.add_argument('-v',
                        '--verbosity',
                        type=str,
                        default="info",
                        help="Verbosity (debug, info, warning, error)")

    proxydb = subparsers.add_parser(
        'proxydb', description="create proxy databases for network use")
    proxydb.add_argument('-i',
                         '--inputfile',
                         help='input database file [db31.pcl]',
                         type=str,
                         default="db31.pcl")
    proxydb.add_argument('-s',
                         '--servername',
                         help='the server name [None]',
                         type=str,
                         default=None)
    proxydb.add_argument('-v',
                         '--verbose',
                         help='verbosity, for server and client [info]',
                         type=str,
                         default="info")
    proxydb.add_argument('-R',
                         '--rundir',
                         help='the rundir [./]',
                         type=str,
                         default="./")
    proxydb.add_argument('-p',
                         '--serverport',
                         help='the server port [31770]',
                         type=int,
                         default=None)
    proxydb.add_argument('-l',
                         '--symlink',
                         help='set a symlink from outputfile to default.pcl',
                         action='store_true')
    proxydb.add_argument('-o',
                         '--outputfile',
                         help='input database file [proxy31.pcl]',
                         type=str,
                         default="proxy31.pcl")
    proxydb.add_argument('-r',
                         '--run',
                         help='start the server upon creation',
                         action='store_true')

    toolbox = subparsers.add_parser(
        'toolbox', description="Facility to control external dependencies")
    toolbox.add_argument('-c',
                         '--colors',
                         help='turn on terminal colors',
                         action='store_true')
    toolbox.add_argument('-l',
                         '--long',
                         help='long output lines',
                         action='store_true')
    toolbox.add_argument('-m',
                         '--make',
                         help='compile packages if needed',
                         action='store_true')
    args = parser.parse_args()

    from smodels.tools import smodelsLogging
    smodelsLogging.setLogLevel(args.verbose)

    from smodels import installation
    if args.subparser_name == 'fixpermissions':
        installation.fixpermissions()

    if args.subparser_name == 'installation':
        import sys, os
        print(installation.banner())
        print("SModelS version:", installation.version())
        print("Installation directory:", installation.installDirectory())
        path = os.path.abspath(os.path.realpath(__file__))
        print("This binary:", path)
        sys.exit()
    if args.subparser_name == 'toolbox':
        from smodels.tools import toolBox
        toolBox.main(args)
    if args.subparser_name == 'proxydb':
        from smodels.tools import proxyDBCreator
        proxyDBCreator.main(args)
    if args.subparser_name == 'xseccomputer':
        from smodels.tools import xsecComputer
        xsecComputer.main(args)
    if args.subparser_name == 'slhachecker':
        from smodels.tools import slhaChecks
        slhaChecks.main(args)
    if args.subparser_name == 'lhechecker':
        from smodels.tools import lheChecks
        lheChecks.main(args)
    if args.subparser_name == 'database-browser':
        from smodels.tools import databaseBrowser
        databaseBrowser.main(args)
    if args.subparser_name == 'interactive-plots':
        from smodels.tools import interactivePlots
        interactivePlots.main(args)
Beispiel #22
0
#!/usr/bin/env python
"""
.. module:: runSModelS
   :synopsis: Main code for running SModelS.
   
"""

import sys, os, logging
from smodels.installation import installDirectory
sys.path.append(installDirectory() + "/Unum-4.1.3-py2.7.egg/")
import argparse
from ConfigParser import SafeConfigParser
from smodels.tools.physicsUnits import GeV, fb
from smodels.tools import slhaPrinter
log = logging.getLogger(__name__)


def main(inputFile, parameterFile, outputFile, slhaOutputFile, particlePath):
    """
    Provides a command line interface to basic SModelS functionalities.
    
    :param inputFile: input file name (either a SLHA or LHE file)
    :param parameterFile: File containing the input parameters (default = /etc/parameters_default.ini)
    :param outputFile: Output file to write a summary of results
    :param slhaOutputFile: Output file to write SLHA type summary of results
    :param particlePath: Path to directory where particles.py is stored
    
    """
    """
    Read and check input file
    =========================
Beispiel #23
0
    argparser.add_argument('-T',
                           nargs='?',
                           help="Tx name, will look up lhe file in "
                           "../regression/Tx_1.lhe. Will be overriden by the "
                           "'--lhe' argument",
                           type=types.StringType,
                           default='T1')
    argparser.add_argument('-l',
                           '--lhe',
                           nargs='?',
                           help="LHE file name, supplied directly. Takes "
                           "precedence over '-T' argument.",
                           type=types.StringType,
                           default='')
    argparser.add_argument('-b',
                           '--border',
                           action='store_true',
                           help="draw a border around the graph")
    args = argparser.parse_args()

    path = os.path.join(installation.installDirectory(), "inputFiles/lhe/")
    filename = os.path.join(path, args.T + "_1.lhe")
    if args.lhe != "":
        filename = args.lhe

    reader = lheReader.LheReader(filename)
    event = reader.next()
    element = lheDecomposer.elementFromEvent(event,
                                             crossSection.XSectionList())
    print(asciidraw(element, border=args.border))
import sys,os
sys.path.append(os.path.join(os.getenv("HOME"),"smodels/"))


# In[2]:

#Import those parts of smodels that are needed for this exercise
from smodels.theory import lheReader, lheDecomposer, crossSection
from smodels.installation import installDirectory
from smodels.tools import asciiGraph


# In[3]:

#Load an input file containing LHE events and start the LHE reader
filename="%s/inputFiles/lhe/gluino_squarks.lhe" % installDirectory()
reader = lheReader.LheReader ( filename )


# In[4]:

#Read the next event and generate the corresponding element
event=reader.next()
element=lheDecomposer.elementFromEvent (event)


# In[5]:

#Print the corresponding ASCII graph
print asciiGraph.asciidraw ( element )
Beispiel #25
0
import sys,os
sys.path.append(os.path.join(os.getenv("HOME"),"smodels/"))


# In[2]:

#Import those parts of smodels that are needed for this exercise
from smodels.theory import lheReader, lheDecomposer, crossSection
from smodels.installation import installDirectory
from smodels.tools import asciiGraph


# In[3]:

#Load an input file containing LHE events and start the LHE reader
filename="%s/inputFiles/lhe/gluino_squarks.lhe" % installDirectory()
reader = lheReader.LheReader ( filename )


# In[4]:

#Read the next event and generate the corresponding element
event=reader.next()
element=lheDecomposer.elementFromEvent (event)


# In[5]:

#Print the corresponding ASCII graph
print asciiGraph.asciidraw ( element )
Beispiel #26
0
def getParticlesFromSLHA(slhafile):
    """
    Defines BSM particles from the QNUMBERS blocks in the slhafile.
    OBS: If the QNUMBERS block does not include a 5-th entry, the particle
    will be assumed to be Z2-odd

    :param slhafile: Path to the SLHA file

    :return: List with Particle objects
    """

    from smodels.theory.particle import Particle
    from smodels.installation import installDirectory

    checkDirs = [
        os.path.join(installDirectory(), "smodels", "share", "models"),
        installDirectory(),
        os.path.join(installDirectory(), "smodels")
    ]

    filename = slhafile
    #If file does not exist, check if it is in any of the default folders:
    if not os.path.isfile(slhafile):
        for dirPath in checkDirs:
            if os.path.isfile(os.path.join(dirPath, slhafile)):
                filename = os.path.join(dirPath, slhafile)
                break

    if not os.path.isfile(filename):
        logger.error("Model file %s not found." % slhafile)
        raise SModelSError()

    logger.debug("Trying to define BSM particles from SLHA input file %s" %
                 filename)

    #Read file and extract blocks:
    with open(filename, 'r') as f:
        data = f.read()
    data = data.lower()
    data = data[:data.find('\ndecay')]
    data = data[:data.find('\nxsection')]
    blocks = [b.splitlines() for b in data.split('\nblock')]

    #Extract qnumber blocks
    qnumberBlocks = [b for b in blocks if 'qnumbers' in b[0]]
    if not qnumberBlocks:
        logger.error("No QNUMBERS blocks were found in %s" % slhafile)
        raise SModelSError()

    #Build list of BSM particles:
    BSMList = []
    for b in qnumberBlocks:
        headerInfo = [
            x for x in b[0].replace('qnumbers', '').split() if x != '#'
        ]
        if headerInfo[0].replace('-', '').replace('+', '').isdigit():
            pdg = eval(headerInfo[0])
        else:
            logger.error(
                "Error obtaining PDG number from QNUMBERS block:\n %s \n" % b)

        if any(p.pdg == pdg for p in BSMList):
            logger.warning(
                "Particle with pdg %i appears multiple times in QNUMBERS blocks"
            )
            continue

        if len(headerInfo) > 1:
            label = headerInfo[1].strip()
        else:
            label = str(pdg)
            logger.debug(
                "Could not find label for particle %i, will use its PDG number"
                % pdg)
        try:
            numbers = [l[:l.find('#')].lstrip().split() for l in b[1:]]
            numbers = dict([x for x in numbers if x])
            numbers = dict([[eval(x), eval(y)] for x, y in numbers.items()])
        except:
            logger.error("Error reading quantum numbers from block: \n %s \n" %
                         b)
            continue
        if any(not x in numbers for x in [1, 2, 3]):
            logger.error("Missing quantum numbers in block:\n %s\n" % b)
            continue
        newParticle = Particle(Z2parity=-1,
                               label=label,
                               pdg=pdg,
                               eCharge=numbers[1] / 3.,
                               colordim=numbers[3],
                               spin=(numbers[2] - 1.) / 2.)

        #Allows an additional quantum number defining the Z2-parity:
        if 11 in numbers:
            newParticle.Z2parity = int((-1)**int(numbers[11]))
        BSMList.append(newParticle)
        if numbers[4]:  #Particle is not its own anti-particle
            newParticleC = newParticle.chargeConjugate()
            if any(p.pdg == newParticleC.pdg for p in BSMList):
                continue
            BSMList.append(newParticleC)

    return BSMList
Beispiel #27
0
def main(inputFile, parameterFile, outputFile, slhaOutputFile, particlePath):
    """
    Provides a command line interface to basic SModelS functionalities.
    
    :param inputFile: input file name (either a SLHA or LHE file)
    :param parameterFile: File containing the input parameters (default = /etc/parameters_default.ini)
    :param outputFile: Output file to write a summary of results
    :param slhaOutputFile: Output file to write SLHA type summary of results
    :param particlePath: Path to directory where particles.py is stored
    
    """

    """
    Read and check input file
    =========================
    """
    parser = SafeConfigParser()
    parser.read(parameterFile)

    """ Minimum value of cross-section for an element to be considered eligible for decomposition.
        Too small sigmacut leads to too large decomposition time. """
    sigmacut = parser.getfloat("parameters", "sigmacut") * fb

    """ Minimum value for considering two states non-degenerate (only used for mass compression) """
    minmassgap = parser.getfloat("parameters", "minmassgap") * GeV

    if os.path.exists(outputFile):
        log.warning("Removing old output file in " + outputFile)
    outfile = open(outputFile, 'w')
    outfile.close()

    databaseVersion = "unknown" # set default database version that is printed in case of errors

    """ Set doCompress flag, only used for slha type output """
    if parser.getboolean("options", "doCompress") or parser.getboolean("options", "doInvisible"): docompress = 1
    else: docompress = 0

    """
    check if particles.py exists in specified path, and add to sys.path
    """
    if not os.path.isfile(os.path.join(particlePath,"particles.py")):
        log.error("particle.py not found in %s" %particlePath )
        return slhaPrinter.writeSLHA(None, parser.getfloat("parameters", "maxcond"), minmassgap, sigmacut, None, databaseVersion, docompress, slhaOutputFile)
    else:
        sys.path.insert(1, particlePath)
        from smodels.tools import ioObjects, missingTopologies
        from smodels.experiment import smsHelpers, smsAnalysisFactory
        from smodels.theory import slhaDecomposer, lheDecomposer
        from smodels.theory.theoryPrediction import theoryPredictionFor


    inputType = parser.get("options", "inputType").lower()
    if inputType != 'slha' and inputType != 'lhe':
        log.error("Unknown input type (must be SLHA or LHE): %s" % inputType)
        return slhaPrinter.writeSLHA(None, parser.getfloat("parameters", "maxcond"), minmassgap, sigmacut, None, databaseVersion, docompress, slhaOutputFile)

    """ Check input file for errors """
    inputStatus = ioObjects.FileStatus()
    if parser.getboolean("options", "checkInput"):
        inputStatus.checkFile(inputType, inputFile, sigmacut)

    """ Check database location """
    try:
        smsHelpers.base = parser.get("path", "databasePath")
        if smsHelpers.base == "./smodels-database" or smsHelpers.base == "./smodels-database/": smsHelpers.base = installDirectory()+"/smodels-database/"
        databaseVersion = smsHelpers.databaseVersion()
    except:
        log.error("Database not found in %s" % os.path.realpath(smsHelpers.base))
        return slhaPrinter.writeSLHA(None, parser.getfloat("parameters", "maxcond"), minmassgap, sigmacut, None, databaseVersion, docompress, slhaOutputFile)

    """ Initialize output status and exit if there were errors in the input """
    outputStatus = ioObjects.OutputStatus(inputStatus.status, inputFile, dict(parser.items("parameters")), databaseVersion, outputFile)
    if outputStatus.status < 0:
        return slhaPrinter.writeSLHA(None, parser.getfloat("parameters", "maxcond"), minmassgap, sigmacut, None, databaseVersion, docompress, slhaOutputFile)

    """
    Decompose input file
    ====================
    """
    try:
        """ Decompose input SLHA file, store the output elements in smstoplist """
        if inputType == 'slha':
            smstoplist = slhaDecomposer.decompose(inputFile, sigmacut, doCompress=parser.getboolean("options", "doCompress"),
                         doInvisible=parser.getboolean("options", "doInvisible"), minmassgap=minmassgap)
        else:
            smstoplist = lheDecomposer.decompose(inputFile, doCompress=parser.getboolean("options", "doCompress"),
                         doInvisible=parser.getboolean("options", "doInvisible"), minmassgap=minmassgap)
    except:
        """ Update status to fail, print error message and exit """
        outputStatus.updateStatus(-1)
        return slhaPrinter.writeSLHA(None, parser.getfloat("parameters", "maxcond"), minmassgap, sigmacut, None, databaseVersion, docompress, slhaOutputFile)

    """ Print Decomposition output.
        If no topologies with sigma > sigmacut are found, update status, write output file, stop running """
    if not smstoplist:
        outputStatus.updateStatus(-3)
        return slhaPrinter.writeSLHA(None, parser.getfloat("parameters", "maxcond"), minmassgap, sigmacut, None, databaseVersion, docompress, slhaOutputFile)

    outLevel = 0
    if parser.getboolean("stdout", "printDecomp"):
        outLevel = 1
        outLevel += parser.getboolean("stdout", "addElmentInfo")
    smstoplist.printout(outputLevel=outLevel)


    """
    Load analysis database
    ======================
    """
    
    """ In case that a list of analyses or txnames are given, retrieve list """
    analyses = parser.get("database", "analyses")
    if "," in analyses:
        analyses = analyses.split(",")
    txnames = parser.get("database", "txnames")
    if "," in txnames:
        txnames = txnames.split(",")
    
    """ Load analyses """
    listofanalyses = smsAnalysisFactory.load(analyses, txnames)

    """ Print list of analyses loaded """
    if parser.getboolean("stdout", "printAnalyses"):
        outLevel = 1
        outLevel += parser.getboolean("stdout", "addAnaInfo")
        print("=======================\n == List of Analyses   ====\n ================")
        for analysis in listofanalyses:
            analysis.printout(outputLevel=outLevel)


    """
    Compute theory predictions and anlalyses constraints
    ====================================================
    """

    """ Define result list that collects all theoryPrediction objects.
        Variables set to define printing options. """
    results = ioObjects.ResultList(bestresultonly=not parser.getboolean("file", "expandedSummary"),
                                   describeTopo=parser.getboolean("file", "addConstraintInfo"))

    """ Get theory prediction for each analysis and print basic output """
    for analysis in listofanalyses:
        theorypredictions = theoryPredictionFor(analysis, smstoplist)
        if not theorypredictions:
            continue
        if parser.getboolean("stdout", "printResults"):
            print "================================================================================"
            theorypredictions.printout()
        print "................................................................................"

        """ Create a list of results, to determine the best result """
        for theoryprediction in theorypredictions:
            results.addResult(theoryprediction, maxcond=parser.getfloat("parameters", "maxcond"))

    """ If there is no best result, this means that there are no matching experimental results for the point """
    if results.isEmpty():
        """ no experimental constraints found """
        outputStatus.updateStatus(0)
    else:
        outputStatus.updateStatus(1)

    """ Write output file """
    outputStatus.printout("file", outputFile)
    """ Add experimental constraints if found """
    if outputStatus.status == 1:
        results.printout("file", outputFile)

    sqrts = max([xsec.info.sqrts for xsec in smstoplist.getTotalWeight()])
    if parser.getboolean("options", "findMissingTopos"):
        """ Look for missing topologies, add them to the output file """
        missingtopos = missingTopologies.MissingTopoList(sqrts)
        missingtopos.findMissingTopos(smstoplist, listofanalyses, minmassgap, parser.getboolean("options", "doCompress"),
                         doInvisible=parser.getboolean("options", "doInvisible"))
        missingtopos.printout("file", outputFile)
    slhaPrinter.writeSLHA(results, parser.getfloat("parameters", "maxcond"), minmassgap, sigmacut, missingtopos, databaseVersion, docompress, slhaOutputFile)
def main():
    parser = argparse.ArgumentParser(
        description="SModelS-tools command line tool.")

    parser.add_argument('-particles',
                        '--particlePath',
                        help='path to directory where particles.py is located',
                        default=installDirectory() + "/smodels")
    parser.add_argument('-v',
                        '--verbose',
                        help='verbosity level. '
                        'accepted values are: debug, info, warning, error.',
                        default="info",
                        type=str)

    subparsers = parser.add_subparsers(dest='subparser_name')

    installation = subparsers.add_parser(
        'installation', description="Print installation setup and exit.")
    xseccomputer = subparsers.add_parser(
        'xseccomputer',
        description="Compute MSSM cross sections for a SLHA file.")
    xseccomputer.add_argument(
        '-s',
        '--sqrts',
        nargs='+',
        action='append',
        help=
        "sqrt(s) TeV. Can supply more than one value. Default is both 8 and 13.",
        type=int,
        default=[])
    xseccomputer.add_argument('-e',
                              '--nevents',
                              type=int,
                              default=10000,
                              help="number of events to be simulated.")
    xseccomputer.add_argument('-v',
                              '--verbosity',
                              type=str,
                              default="info",
                              help="Verbosity (debug, info, warning, error)")
    xseccomputer.add_argument(
        '-c',
        '--ncpus',
        type=int,
        default=-1,
        help="number of cores to be used simultaneously. -1 means 'all'. ")
    xseccomputer.add_argument('-p',
                              '--tofile',
                              action='store_true',
                              help="write cross sections to file")
    xseccomputer.add_argument(
        '-q',
        '--query',
        action='store_true',
        help="only query if there are cross sections in the file")
    xseccomputer.add_argument('-k',
                              '--keep',
                              action='store_true',
                              help="do not unlink temporary directory")
    xseccomputer.add_argument('-n',
                              '--NLO',
                              action='store_true',
                              help="compute at the NLO level (default is LO)")
    xseccomputer.add_argument(
        '-N',
        '--NLL',
        help=
        "compute at the NLO+NLL level (takes precedence over NLO, default is LO)",
        action='store_true')
    xseccomputer.add_argument(
        '-O',
        '--LOfromSLHA',
        help=
        "use LO cross sections from file to compute the NLO or NLL cross sections",
        action='store_true')
    xseccomputer.add_argument(
        '-f',
        '--filename',
        required=True,
        help="SLHA file to compute cross sections for. "
        "If a directory is given, compute cross sections for all files in directory."
    )

    slhachecker = subparsers.add_parser(
        'slhachecker', description="Perform several checks on a SLHA file.")
    slhachecker.add_argument('-xS',
                             '--xsec',
                             help='turn off the check for xsection blocks',
                             action='store_false')
    slhachecker.add_argument('-lsp',
                             '--lsp',
                             help='turn off the check for charged lsp',
                             action='store_false')
    slhachecker.add_argument(
        '-longlived',
        '--longlived',
        help=
        'turn off the check for stable charged particles and visible displaced vertices',
        action='store_false')
    slhachecker.add_argument(
        '-m',
        '--displacement',
        help='give maximum displacement of secondary vertex in m',
        default=.001,
        type=float)
    slhachecker.add_argument('-s',
                             '--sigmacut',
                             help='give sigmacut in fb',
                             default=.03,
                             type=float)
    slhachecker.add_argument(
        '-illegal',
        '--illegal',
        help='turn on check for kinematically forbidden decays',
        action='store_true')
    slhachecker.add_argument(
        '-dB',
        '--decayBlocks',
        help='turn off the check for missing decay blocks',
        action='store_false')
    slhachecker.add_argument('-f',
                             '--filename',
                             help='name of input SLHA file',
                             required=True)

    lhechecker = subparsers.add_parser(
        'lhechecker', description="Check if the input file has LHE format.")
    lhechecker.add_argument('-f',
                            '--filename',
                            help='name of input LHE file',
                            required=True)

    dbBrowser = subparsers.add_parser(
        'database-browser', description="Interface for browsing the Database.")
    dbBrowser.add_argument('-p',
                           '--path_to_database',
                           help='path to SModelS database',
                           required=True)
    dbBrowser.add_argument(
        '-t',
        '--text',
        help='load text database, dont even search for binary database file',
        action='store_true')

    args = parser.parse_args()
    """
    check if particles.py exists in specified path, and add to sys.path
    """
    if not os.path.isfile(os.path.join(args.particlePath, "particles.py")):
        log.error("particle.py not found in %s" % args.particlePath)
        return
    else:
        sys.path.insert(1, args.particlePath)
        from smodels.tools import xsecComputer
        from smodels.tools import slhaChecks, lheChecks

    smodelsLogging.setLogLevel(args.verbose)

    if args.subparser_name == 'installation':
        from smodels import installation
        print(installation.banner())
        print("SModelS version:", installation.version())
        print("Installation directory:", installation.installDirectory())
        path = os.path.abspath(os.path.realpath(__file__))
        print("This binary:", path)
        sys.exit()

    if args.subparser_name == 'xseccomputer':
        xsecComputer.main(args)
    if args.subparser_name == 'slhachecker':
        slhaChecks.main(args)
    if args.subparser_name == 'lhechecker':
        lheChecks.main(args)
    if args.subparser_name == 'database-browser':
        databaseBrowser.main(args)
Beispiel #29
0
#!/usr/bin/env python
"""
.. module:: smodels
   :synopsis: Command line program for SModelS tasks.

.. moduleauthor:: Wolfgang Magerl <*****@*****.**>

"""

import argparse, sys, os, logging
from smodels.installation import installDirectory
sys.path.append(installDirectory() + "/Unum-4.1.3-py2.7.egg/")
import logging.config
logging.config.fileConfig('%s/etc/logging.conf' % installDirectory(),
                          disable_existing_loggers=False)
log = logging.getLogger(__name__)


def main():
    parser = argparse.ArgumentParser(description="SModelS command line tool.")
    subparsers = parser.add_subparsers(dest='subparser_name')

    xseccomputer = subparsers.add_parser(
        'xseccomputer',
        description="Compute MSSM cross sections for a SLHA file.")
    xseccomputer.add_argument(
        '-s',
        '--sqrts',
        nargs='+',
        action='append',
        help="sqrt(s) TeV. Can supply more than one value.",
Beispiel #30
0
def main():
    import argparse
    """ Set default input and output files """
    parameterFile = "%s/smodels/etc/parameters_default.ini" % installDirectory(
    )
    outputDir = "./results/"
    """ Get the name of input SLHA file and parameter file """
    ap = argparse.ArgumentParser(
        description="Run SModelS over SLHA/LHE input files.")
    ap.add_argument(
        '-f',
        '--filename',
        help=
        'name of SLHA or LHE input file or a directory path (required argument). '
        'If a directory is given, loop over all files in the directory',
        required=True)
    ap.add_argument(
        '-p',
        '--parameterFile',
        help=
        'name of parameter file, where most options are defined (optional argument). If not set, use '
        'all parameters from smodels/etc/parameters_default.ini',
        default=parameterFile)
    ap.add_argument(
        '-o',
        '--outputDir',
        help=
        'name of output directory (optional argument). The default folder is: '
        + outputDir,
        default=outputDir)
    ap.add_argument(
        '-d',
        '--development',
        help=
        'if set, SModelS will run in development mode and exit if any errors are found.',
        action='store_true')
    ap.add_argument('-t',
                    '--force_txt',
                    help='force loading the text database',
                    action='store_true')
    ap.add_argument('-C',
                    '--colors',
                    help='colored output',
                    action='store_true')
    ap.add_argument('-V', '--version', action='version', version=version())
    ap.add_argument(
        '-c',
        '--run-crashreport',
        help='parse crash report file and use its contents for a SModelS run. '
        "Supply the crash file simply via '--filename myfile.crash'",
        action='store_true')
    ap.add_argument(
        '-v',
        '--verbose',
        help=
        'sets the verbosity level (debug, info, warning, error). Default value is info.',
        default="info",
        type=str)
    ap.add_argument(
        '-T',
        '--timeout',
        help='define a limit on the running time (in secs).'
        'If not set, run without a time limit. If a directory is given as input, '
        'the timeout will be  applied for each individual file.',
        default=0,
        type=int)

    args = ap.parse_args()
    if args.colors:
        from smodels.tools.colors import colors
        colors.on = True

    db = None
    if args.force_txt: db = True
    smodelsLogging.setLogLevel(args.verbose)

    if args.run_crashreport:
        args.filename, args.parameterFile = crashReport.readCrashReportFile(
            args.filename)
        run(args.filename,
            args.parameterFile,
            args.outputDir,
            db,
            args.timeout,
            development=True)

    else:
        run(args.filename, args.parameterFile, args.outputDir, db,
            args.timeout, args.development)
Beispiel #31
0
        kFacs.append(kfac)

    return kFacs

def getDecoupledKfactors(nllpath,process,energy,pdf,mass):
    """
    Compute k-factors in the decoupled (squark or gluino) regime for the process.
    If a decoupled grid does not exist for the process, return None
    """
        
    if process != 'sb' and process != 'gg': return None
    elif process == 'sb': process_dcpl = 'sdcpl'
    elif process == 'gg': process_dcpl = 'gdcpl'    
    nll_run = "./nllfast_" + energy + " %s %s %s" % \
                      (process_dcpl, pdf, mass)
    nll_output = runNLLfast(nll_run, nllpath)
    if "K_NLO" in nll_output:
        return getKfactorsFrom(nll_output)
    else: return None



if __name__ == "__main__":
    """
    Calculate k factors for a pid pair.
    
    """
    slhaF = installation.installDirectory() + "inputFiles/slha/T1.slha"
    kNLO, kNLL = getKfactorsFor((1000021, 1000021), 13.*TeV, slhaF)
    print("nlo, nll = " + str(kNLO) + ", " + str(kNLL))
Beispiel #32
0
def main(inputFile, parameterFile, outputFile, slhaOutputFile, particlePath):
    """
    Provides a command line interface to basic SModelS functionalities.
    
    :param inputFile: input file name (either a SLHA or LHE file)
    :param parameterFile: File containing the input parameters (default = /etc/parameters_default.ini)
    :param outputFile: Output file to write a summary of results
    :param slhaOutputFile: Output file to write SLHA type summary of results
    :param particlePath: Path to directory where particles.py is stored
    
    """
    """
    Read and check input file
    =========================
    """
    parser = SafeConfigParser()
    parser.read(parameterFile)
    """ Minimum value of cross-section for an element to be considered eligible for decomposition.
        Too small sigmacut leads to too large decomposition time. """
    sigmacut = parser.getfloat("parameters", "sigmacut") * fb
    """ Minimum value for considering two states non-degenerate (only used for mass compression) """
    minmassgap = parser.getfloat("parameters", "minmassgap") * GeV

    if os.path.exists(outputFile):
        log.warning("Removing old output file in " + outputFile)
    outfile = open(outputFile, 'w')
    outfile.close()

    databaseVersion = "unknown"  # set default database version that is printed in case of errors
    """ Set doCompress flag, only used for slha type output """
    if parser.getboolean("options", "doCompress") or parser.getboolean(
            "options", "doInvisible"):
        docompress = 1
    else:
        docompress = 0
    """
    check if particles.py exists in specified path, and add to sys.path
    """
    if not os.path.isfile(os.path.join(particlePath, "particles.py")):
        log.error("particle.py not found in %s" % particlePath)
        return slhaPrinter.writeSLHA(None,
                                     parser.getfloat("parameters",
                                                     "maxcond"), minmassgap,
                                     sigmacut, None, databaseVersion,
                                     docompress, slhaOutputFile)
    else:
        sys.path.insert(1, particlePath)
        from smodels.tools import ioObjects, missingTopologies
        from smodels.experiment import smsHelpers, smsAnalysisFactory
        from smodels.theory import slhaDecomposer, lheDecomposer
        from smodels.theory.theoryPrediction import theoryPredictionFor

    inputType = parser.get("options", "inputType").lower()
    if inputType != 'slha' and inputType != 'lhe':
        log.error("Unknown input type (must be SLHA or LHE): %s" % inputType)
        return slhaPrinter.writeSLHA(None,
                                     parser.getfloat("parameters",
                                                     "maxcond"), minmassgap,
                                     sigmacut, None, databaseVersion,
                                     docompress, slhaOutputFile)
    """ Check input file for errors """
    inputStatus = ioObjects.FileStatus()
    if parser.getboolean("options", "checkInput"):
        inputStatus.checkFile(inputType, inputFile, sigmacut)
    """ Check database location """
    try:
        smsHelpers.base = parser.get("path", "databasePath")
        if smsHelpers.base == "./smodels-database" or smsHelpers.base == "./smodels-database/":
            smsHelpers.base = installDirectory() + "/smodels-database/"
        databaseVersion = smsHelpers.databaseVersion()
    except:
        log.error("Database not found in %s" %
                  os.path.realpath(smsHelpers.base))
        return slhaPrinter.writeSLHA(None,
                                     parser.getfloat("parameters",
                                                     "maxcond"), minmassgap,
                                     sigmacut, None, databaseVersion,
                                     docompress, slhaOutputFile)
    """ Initialize output status and exit if there were errors in the input """
    outputStatus = ioObjects.OutputStatus(inputStatus.status, inputFile,
                                          dict(parser.items("parameters")),
                                          databaseVersion, outputFile)
    if outputStatus.status < 0:
        return slhaPrinter.writeSLHA(None,
                                     parser.getfloat("parameters",
                                                     "maxcond"), minmassgap,
                                     sigmacut, None, databaseVersion,
                                     docompress, slhaOutputFile)
    """
    Decompose input file
    ====================
    """
    try:
        """ Decompose input SLHA file, store the output elements in smstoplist """
        if inputType == 'slha':
            smstoplist = slhaDecomposer.decompose(
                inputFile,
                sigmacut,
                doCompress=parser.getboolean("options", "doCompress"),
                doInvisible=parser.getboolean("options", "doInvisible"),
                minmassgap=minmassgap)
        else:
            smstoplist = lheDecomposer.decompose(
                inputFile,
                doCompress=parser.getboolean("options", "doCompress"),
                doInvisible=parser.getboolean("options", "doInvisible"),
                minmassgap=minmassgap)
    except:
        """ Update status to fail, print error message and exit """
        outputStatus.updateStatus(-1)
        return slhaPrinter.writeSLHA(None,
                                     parser.getfloat("parameters",
                                                     "maxcond"), minmassgap,
                                     sigmacut, None, databaseVersion,
                                     docompress, slhaOutputFile)
    """ Print Decomposition output.
        If no topologies with sigma > sigmacut are found, update status, write output file, stop running """
    if not smstoplist:
        outputStatus.updateStatus(-3)
        return slhaPrinter.writeSLHA(None,
                                     parser.getfloat("parameters",
                                                     "maxcond"), minmassgap,
                                     sigmacut, None, databaseVersion,
                                     docompress, slhaOutputFile)

    outLevel = 0
    if parser.getboolean("stdout", "printDecomp"):
        outLevel = 1
        outLevel += parser.getboolean("stdout", "addElmentInfo")
    smstoplist.printout(outputLevel=outLevel)
    """
    Load analysis database
    ======================
    """
    """ In case that a list of analyses or txnames are given, retrieve list """
    analyses = parser.get("database", "analyses")
    if "," in analyses:
        analyses = analyses.split(",")
    txnames = parser.get("database", "txnames")
    if "," in txnames:
        txnames = txnames.split(",")
    """ Load analyses """
    listofanalyses = smsAnalysisFactory.load(analyses, txnames)
    """ Print list of analyses loaded """
    if parser.getboolean("stdout", "printAnalyses"):
        outLevel = 1
        outLevel += parser.getboolean("stdout", "addAnaInfo")
        print(
            "=======================\n == List of Analyses   ====\n ================"
        )
        for analysis in listofanalyses:
            analysis.printout(outputLevel=outLevel)
    """
    Compute theory predictions and anlalyses constraints
    ====================================================
    """
    """ Define result list that collects all theoryPrediction objects.
        Variables set to define printing options. """
    results = ioObjects.ResultList(
        bestresultonly=not parser.getboolean("file", "expandedSummary"),
        describeTopo=parser.getboolean("file", "addConstraintInfo"))
    """ Get theory prediction for each analysis and print basic output """
    for analysis in listofanalyses:
        theorypredictions = theoryPredictionFor(analysis, smstoplist)
        if not theorypredictions:
            continue
        if parser.getboolean("stdout", "printResults"):
            print "================================================================================"
            theorypredictions.printout()
        print "................................................................................"
        """ Create a list of results, to determine the best result """
        for theoryprediction in theorypredictions:
            results.addResult(theoryprediction,
                              maxcond=parser.getfloat("parameters", "maxcond"))
    """ If there is no best result, this means that there are no matching experimental results for the point """
    if results.isEmpty():
        """ no experimental constraints found """
        outputStatus.updateStatus(0)
    else:
        outputStatus.updateStatus(1)
    """ Write output file """
    outputStatus.printout("file", outputFile)
    """ Add experimental constraints if found """
    if outputStatus.status == 1:
        results.printout("file", outputFile)

    sqrts = max([xsec.info.sqrts for xsec in smstoplist.getTotalWeight()])
    if parser.getboolean("options", "findMissingTopos"):
        """ Look for missing topologies, add them to the output file """
        missingtopos = missingTopologies.MissingTopoList(sqrts)
        missingtopos.findMissingTopos(
            smstoplist,
            listofanalyses,
            minmassgap,
            parser.getboolean("options", "doCompress"),
            doInvisible=parser.getboolean("options", "doInvisible"))
        missingtopos.printout("file", outputFile)
    slhaPrinter.writeSLHA(results, parser.getfloat("parameters", "maxcond"),
                          minmassgap, sigmacut, missingtopos, databaseVersion,
                          docompress, slhaOutputFile)
#Set up the path to SModelS installation folder if running on a different folder
import sys, os
sys.path.append(os.path.join(os.getenv("HOME"), "smodels/"))

# In[2]:

#Import those parts of smodels that are needed for this exercise
from smodels.tools import xsecComputer
from smodels.tools.physicsUnits import TeV, fb
from smodels.installation import installDirectory
from smodels.tools.xsecComputer import LO, NLL

# In[5]:

#Define the SLHA file name
filename = "%s/inputFiles/slha/gluino_squarks.slha" % installDirectory()

# In[7]:

#Now lets compute the leading order (LO) cross sections for 8 TeV, simulating 1000
# events with pythia.
LO = 0
xsecs = xsecComputer.computeXSec(sqrts=8 * TeV,
                                 maxOrder=LO,
                                 nevts=1000,
                                 slhafile=filename)

# In[8]:

# the output is a XSectionList ...
type(xsecs)
#!/usr/bin/env python
"""
.. module:: smodelsTools
   :synopsis: Command line program for SModelS tools.

.. moduleauthor:: Wolfgang Magerl <*****@*****.**>
.. moduleauthor:: Wolfgang Waltenberger <*****@*****.**>

"""

from __future__ import print_function
import argparse, os, sys
from smodels.installation import installDirectory
sys.path.append(installDirectory() + "/Unum-4.1.3-py2.7.egg/")
from smodels.tools import smodelsLogging


def main():
    parser = argparse.ArgumentParser(
        description="SModelS-tools command line tool.")

    parser.add_argument('-particles',
                        '--particlePath',
                        help='path to directory where particles.py is located',
                        default=installDirectory() + "/smodels")
    parser.add_argument('-v',
                        '--verbose',
                        help='verbosity level. '
                        'accepted values are: debug, info, warning, error.',
                        default="info",
                        type=str)