コード例 #1
0
def runMain(filename,
            timeout=0,
            suppressStdout=True,
            development=False,
            inifile="testParameters.ini"):
    """ run SModelS proper 
    :param filename: slha file
    :returns: printer output
    """
    to = None
    oldlevel = getLogLevel()
    level = 'debug'
    if suppressStdout:
        level = 'error'
        to = os.devnull
    with redirector.stdout_redirected(to=to):
        out = join(iDir(), "test/unitTestOutput")
        setLogLevel(level)
        run(filename,
            parameterFile=join(iDir(), "test/%s" % inifile),
            outputDir=out,
            db=database,
            timeout=timeout,
            development=development)
        setLogLevel(oldlevel)
        sfile = join(iDir(), "test/unitTestOutput/%s.py" % basename(filename))
        return sfile
コード例 #2
0
ファイル: unitTestHelpers.py プロジェクト: gipsyblues/smodels
def runMain( filename, timeout = 0, suppressStdout=True, development=False,
             inifile = "testParameters.ini", overridedatabase = None ):
    """ run SModelS proper
    :param filename: slha file
    :param timeout: timeout for the operation, given in seconds
    :param suppressStdout: if True, then redirect stdout and stderr to /dev/null
    :param development: development run (FIXME what does that entail?)
    :param inifile: the config file to be used
    :param overridedatabase: if not None, then use the provided database,
           else use databaseLoader.database
    :returns: printer output
    """
    to = None
    oldlevel = getLogLevel()
    level = 'debug'
    if suppressStdout:
        level = 'error'
        to = os.devnull
    database = None
    if overridedatabase != None:
        database = overridedatabase
    else:
        from databaseLoader import database ## to make sure the db exists
    with redirector.stdout_redirected ( to = to ):
        out = join( iDir(), "test/unitTestOutput" )
        setLogLevel ( level )
        run(filename, parameterFile=join ( iDir(), "test/%s" % inifile ),
             outputDir= out, db= database, timeout = timeout,
             development = development)
        setLogLevel ( oldlevel )
        sfile = join(iDir(),"test/unitTestOutput/%s.py" % basename(filename))
        return sfile
コード例 #3
0
 def __init__(self, base=None, force_load=None, verbosity=None):
     """
     :param force_load: force loading the text database ("txt"),
         or binary database ("pcl"), dont force anything if None
     """
     self.force_load = force_load
     self.pclfilename = "database.pcl"
     self.hasFastLim = False  # True if any ExpResult is from fastlim
     self._validateBase(base)
     self._verbosity = verbosity
     self._databaseVersion = None
     self.expResultList = []
     self.txt_mtime = None, None
     self.pcl_mtime = None, None
     self.pcl_db = None
     self.sw_format_version = "115"  ## what format does the software support?
     self.pcl_format_version = None  ## what format is in the binary file?
     self.binfile = os.path.join(self._base, self.pclfilename)
     setLogLevel(self._verbosity)
     if self.force_load == "txt":
         self.loadTextDatabase()
         self.printFastlimBanner()
         return
     if self.force_load == "pcl":
         self.loadBinaryFile()
         self.printFastlimBanner()
         return
     if self.force_load in [None, "none", "None"]:
         self.loadDatabase()
         self.printFastlimBanner()
         return
     logger.error ( "when initialising database: force_load=%s is not " \
                    "recognized. Valid values are: pcl, txt, None." % force_load )
     sys.exit()
コード例 #4
0
ファイル: xsecComputer.py プロジェクト: gipsyblues/smodels
def main(args):
    canonizer = ArgsStandardizer()
    setLogLevel(args.verbosity)
    if not hasattr(args, "noautocompile"):
        args.noautocompile = False
    if args.query:
        return canonizer.queryCrossSections(args.filename)
    if args.colors:
        from smodels.tools.colors import colors
        colors.on = True
    sqrtses = canonizer.getSqrtses(args)
    order = canonizer.getOrder(args)
    canonizer.checkAllowedSqrtses(order, sqrtses)
    inputFiles = canonizer.getInputFiles(args)
    ncpus = canonizer.checkNCPUs(args.ncpus, inputFiles)
    pythiaVersion = canonizer.getPythiaVersion(args)
    ssmultipliers = None
    if hasattr(args, "ssmultipliers"):
        ssmultipliers = canonizer.getSSMultipliers(args.ssmultipliers)
        if ssmultipliers != None:
            for pids, multiplier in ssmultipliers.items():
                if type(pids) != tuple:
                    logger.error(
                        "keys of ssmultipliers need to be supplied as tuples")
                    sys.exit()
                if type(multiplier) not in [int, float]:
                    logger.error(
                        "values of ssmultipliers need to be supplied as ints or floats"
                    )
                    sys.exit()

    pythiacard = None
    if hasattr(args, 'pythiacard'):
        pythiacard = args.pythiacard

    children = []
    for i in range(ncpus):
        pid = os.fork()
        chunk = inputFiles[i::ncpus]
        if pid < 0:
            logger.error("fork did not succeed! Pid=%d" % pid)
            sys.exit()
        if pid == 0:
            logger.debug("chunk #%d: pid %d (parent %d)." %
                         (i, os.getpid(), os.getppid()))
            logger.debug(" `-> %s" % " ".join(chunk))
            computer = XSecComputer( order, args.nevents, pythiaVersion, \
                                     not args.noautocompile )
            toFile = canonizer.writeToFile(args)
            computer.computeForBunch (  sqrtses, chunk, not args.keep,
                          args.LOfromSLHA, toFile, pythiacard=pythiacard, \
                        ssmultipliers = ssmultipliers )
            os._exit(0)
        if pid > 0:
            children.append(pid)
    for child in children:
        r = os.waitpid(child, 0)
        logger.debug("child %d terminated: %s" % (child, r))
    logger.debug("all children terminated.")
コード例 #5
0
ファイル: runSModelS.py プロジェクト: SModelS/smodels
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)
コード例 #6
0
def main(args):
    setLogLevel(args.verbosity)
    if args.query:
        return queryCrossSections(args.filename)
    sqrtses = getSqrtses(args)
    order = getOrder(args)
    checkAllowedSqrtses(order, sqrtses)
    inputFiles = getInputFiles(args)
    ncpus = args.ncpus

    if hasattr(args, 'pythiacard'):
        pythiacard = args.pythiacard
    else:
        pythiacard = None
    if ncpus < -1 or ncpus == 0:
        logger.error("Weird number of CPUs given: %d" % ncpus)
        sys.exit()
    if ncpus == -1:
        ncpus = runtime.nCPUs()
    ncpus = min(len(inputFiles), ncpus)
    if ncpus == 1:
        logger.info("We run on a single cpu")
    else:
        logger.info("We run on %d cpus" % ncpus)
    children = []
    for i in range(ncpus):
        pid = os.fork()
        chunk = inputFiles[i::ncpus]
        if pid < 0:
            logger.error("fork did not succeed! Pid=%d" % pid)
            sys.exit()
        if pid == 0:
            logger.debug("chunk #%d: pid %d (parent %d)." %
                         (i, os.getpid(), os.getppid()))
            logger.debug(" `-> %s" % " ".join(chunk))
            computeForBunch(sqrtses,
                            order,
                            args.nevents,
                            chunk,
                            not args.keep,
                            args.LOfromSLHA,
                            args.tofile,
                            pythiacard=pythiacard)
            os._exit(0)
        if pid > 0:
            children.append(pid)
    for child in children:
        r = os.waitpid(child, 0)
        logger.debug("child %d terminated: %s" % (child, r))
    logger.debug("all children terminated.")
コード例 #7
0
 def testWithDisplaced(self):
     setLogLevel('error')
     self.logger.info("test decomposition with displaced vertex tracking")
     slhafile = "./testFiles/slha/hscpTest_mid.slha"
     topos = slhaDecomposer.decompose(slhafile, .1*fb, False, False, 5.*GeV)
     self.assertEqual(len(topos),1)
     topo = topos[0]
     ellist=topo.elementList
     self.assertEqual(len(ellist), 1)
     element=ellist[0]
     self.assertEqual(str(element), "[[],[]]")
     self.assertEqual(element.getFinalStates(), ['Displaced', 'Displaced'])
     weight = element.weight.getXsecsFor(13*TeV)[0].value.asNumber(fb)
     self.assertAlmostEqual(weight,0.6963,places=3)
コード例 #8
0
def makePlots(smodelsFolder,
              slhaFolder,
              outputFolder,
              parameters,
              npoints,
              verbosity,
              indexfile="index.html"):
    """
    Main interface for the interactive-plots.

    :parameter smodelsFolder: Path to the folder containing the SModelS python output
    :parameter slhaFolder: Path to the folder containing the SLHA files corresponding to the SModelS output
    :parameter parameters: Path to the parameter file setting the options for the interactive plots
    :parameter npoints: Number of points used to produce the plot. If -1, all points will be used.
    :parameter verbosity: Verbosity of the output (debug,info,warning,error)
    :parameter indexfile: name of the starting web page (index.html)

    :return: True if the plot creation was successfull

    """

    try:
        import plotly
    except ImportError:
        raise SModelSError(
            "Plotly is not installed. To use this tool, please install plotly")

    try:
        import pandas
    except ImportError:
        raise SModelSError(
            "Pandas is not installed. To use this tool, please install pandas")

    setLogLevel(verbosity)

    #Basic checks:
    smodelsFolder = smodelsFolder
    slhaFolder = slhaFolder
    parFile = parameters

    dataHolder = DataHolder(smodelsFolder, slhaFolder, parFile, indexfile)
    loadData = dataHolder.loadData(npoints)
    if not loadData:
        raise SModelSError("Error loading data from folders:\n %s\n %s" %
                           (smodelsFolder, slhaFolder))

    dataHolder.makePlots(outputFolder)

    return outputFolder
コード例 #9
0
 def testWithDisplaced(self):
     setLogLevel('error')
     self.logger.info("test decomposition with displaced vertex tracking")
     slhafile = "./testFiles/slha/hscpTest_mid.slha"
     topos = slhaDecomposer.decompose(slhafile, .1 * fb, False, False,
                                      5. * GeV)
     self.assertEqual(len(topos), 1)
     topo = topos[0]
     ellist = topo.elementList
     self.assertEqual(len(ellist), 1)
     element = ellist[0]
     self.assertEqual(str(element), "[[],[]]")
     self.assertEqual(element.getFinalStates(), ['Displaced', 'Displaced'])
     weight = element.weight.getXsecsFor(13 * TeV)[0].value.asNumber(fb)
     self.assertAlmostEqual(weight, 0.6963, places=3)
コード例 #10
0
ファイル: xsecComputer.py プロジェクト: ismailturan/smodels
def main(args):
    canonizer = ArgsStandardizer()
    setLogLevel(args.verbosity)
    if args.query:
        return canonizer.queryCrossSections(args.filename)
    if args.colors:
        from smodels.tools.colors import colors
        colors.on = True
    sqrtses = canonizer.getSqrtses(args)
    order = canonizer.getOrder(args)
    canonizer.checkAllowedSqrtses(order, sqrtses)
    inputFiles = canonizer.getInputFiles(args)
    ncpus = canonizer.checkNCPUs(args.ncpus, inputFiles)
    pythiaVersion = canonizer.getPythiaVersion(args)

    pythiacard = None
    if hasattr(args, 'pythiacard'):
        pythiacard = args.pythiacard

    children = []
    for i in range(ncpus):
        pid = os.fork()
        chunk = inputFiles[i::ncpus]
        if pid < 0:
            logger.error("fork did not succeed! Pid=%d" % pid)
            sys.exit()
        if pid == 0:
            logger.debug("chunk #%d: pid %d (parent %d)." %
                         (i, os.getpid(), os.getppid()))
            logger.debug(" `-> %s" % " ".join(chunk))
            computer = XSecComputer(order, args.nevents, pythiaVersion)
            toFile = canonizer.writeToFile(args)
            computer.computeForBunch(sqrtses,
                                     chunk,
                                     not args.keep,
                                     args.LOfromSLHA,
                                     toFile,
                                     pythiacard=pythiacard)
            os._exit(0)
        if pid > 0:
            children.append(pid)
    for child in children:
        r = os.waitpid(child, 0)
        logger.debug("child %d terminated: %s" % (child, r))
    logger.debug("all children terminated.")
コード例 #11
0
    def testHSCPPredictions(self):
        setLogLevel('error')
        expID = ["CMS-EXO-13-006"]
        
        #Test long-lived case:
        slhafile = './testFiles/slha/hscpTest_long.slha'
        expValue = [0.0743]
        self.checkPrediction(slhafile, expID, expValue)

        #Test displaced case:
        slhafile = './testFiles/slha/hscpTest_mid.slha'
        expValue = [2.20e-7]
        self.checkPrediction(slhafile, expID, expValue)


        #Test short-lived case:
        slhafile = './testFiles/slha/hscpTest_short.slha'
        expValue = [5.98e-10]
        self.checkPrediction(slhafile, expID, expValue)
コード例 #12
0
ファイル: unitTestHelpers.py プロジェクト: SModelS/smodels
def runMain( filename, timeout = 0, suppressStdout=True, development=False,
             inifile = "testParameters.ini" ):
    """ run SModelS proper 
    :param filename: slha file
    :returns: printer output
    """
    to = None
    oldlevel = getLogLevel()
    level = 'debug'
    if suppressStdout:
        level = 'error'
        to = os.devnull
    with redirector.stdout_redirected ( to = to ):
        out = join( iDir(), "test/unitTestOutput" )
        setLogLevel ( level )
        run(filename, parameterFile=join ( iDir(), "test/%s" % inifile ),
             outputDir= out, db= database, timeout = timeout,
             development = development)
        setLogLevel ( oldlevel )
        sfile = join(iDir(),"test/unitTestOutput/%s.py" % basename(filename))
        return sfile
コード例 #13
0
ファイル: interactivePlots.py プロジェクト: SModelS/smodels
def makePlots(smodelsFolder,slhaFolder,outputFolder,
         parameters,npoints,verbosity):
    """
    Main interface for the interactive-plots. 
    
    :parameter smodelsFolder: Path to the folder containing the SModelS python output
    :parameter slhaFolder: Path to the folder containing the SLHA files corresponding to the SModelS output
    :parameter parameters: Path to the parameter file setting the options for the interactive plots
    :parameter npoints: Number of points used to produce the plot. If -1, all points will be used.
    :parameter verbosity: Verbosity of the output (debug,info,warning,error)
    
    :return: True if the plot creation was successfull
    
    """

    try:
        import plotly
    except ImportError as e:
        raise SModelSError("Plotly is not installed. To use this tool, please install plotly")

    try:
        import pandas
    except ImportError as e:
        raise SModelSError("Pandas is not installed. To use this tool, please install pandas")

    setLogLevel(verbosity)

    #Basic checks:
    smodelsFolder = smodelsFolder
    slhaFolder = slhaFolder
    parFile = parameters
    
    dataHolder = DataHolder(smodelsFolder,slhaFolder,parFile)
    loadData = dataHolder.loadData(npoints)
    if not loadData:
        raise SModelSError("Error loading data from folders:\n %s\n %s" %(smodelsFolder,slhaFolder))
    
    dataHolder.makePlots(outputFolder)
    
    return outputFolder
コード例 #14
0
def draw( strategy, databasepath, trianglePlot, miscol,
          diagcol, experiment, S, drawtimestamp, outputfile, nofastlim ):
    """
    :param trianglePlot: if True, then only plot the upper triangle of this
                         symmetrical matrix
    :param miscol: color to use when likelihood is missing
    :param diagcol: color to use for diagonal
    :param experiment: draw only for specific experiment ("CMS", "ATLAS", "all" )
    :param S: draw only for specific sqrts ( "8", "13", "all" )
    :param drawtimestamp: if true, put a timestamp on plot
    :param outputfile: file name of output file (matrix.png)
    :param nofastlim: if True, discard fastlim results
    """
    ROOT.gStyle.SetOptStat(0000)

    ROOT.gROOT.SetBatch()
    cols = [ ROOT.kRed+1, ROOT.kWhite, ROOT.kGreen+1, miscol, diagcol ]
    ROOT.gStyle.SetPalette(len(cols), (ctypes.c_int * len(cols))(*cols) )
    ROOT.gStyle.SetNumberContours(len(cols))

    ROOT.gStyle.SetPadLeftMargin(.25)

    sqrtses = [ 8, 13 ]
    if S not in [ "all" ]:
        sqrtses = [ int(S) ]

    colors.on = True
    setLogLevel ( "debug" )

    # dir = "/home/walten/git/smodels-database/"
    dir = databasepath
    d=Database( dir, discard_zeroes = True )
    print(d)
    analysisIds = [ "all" ]
    exps = [ "CMS", "ATLAS" ]
    if experiment in [ "CMS", "ATLAS" ]:
        analysisIds = [ experiment+"*" ]
        exps = [ experiment ]
    results = d.getExpResults( analysisIDs = analysisIds )
    if nofastlim:
        results = noFastlim ( results )
    results = sortOutDupes ( results )
    if S in [ "8", "13" ]:
        results = sortBySqrts ( results, int(S) )

    #results.sort()
    nres = len ( results )

    ROOT.c1=ROOT.TCanvas("c1","c1",1770,1540)
    ROOT.c1.SetLeftMargin(0.18)
    ROOT.c1.SetBottomMargin(0.21)
    ROOT.c1.SetTopMargin(0.06)
    ROOT.c1.SetRightMargin(0.01)
    if nres > 60:
        ROOT.c1.SetLeftMargin(0.12) ## seemed to work for 96 results
        ROOT.c1.SetBottomMargin(0.15)
        ROOT.c1.SetTopMargin(0.09)
        ROOT.c1.SetRightMargin(0.015)

    h=ROOT.TH2F ( "Correlations", "",
                  nres, 0., nres, nres, 0., nres )
    xaxis = h.GetXaxis()
    yaxis = h.GetYaxis()

    sze = 0.13 / math.sqrt ( nres )
    xaxis.SetLabelSize( 1.3*sze )
    yaxis.SetLabelSize( 1.3*sze )

    bins= { "CMS": { 8: [999,0], 13:[999,0] },
            "ATLAS": { 8: [999,0], 13: [999,0] } }

    n = len(results )
    for x,e in enumerate(results):
        label = e.globalInfo.id
        hasLikelihood = hasLLHD ( e )
        ana = analysisCombiner.getExperimentName ( e.globalInfo )
        #if not hasLikelihood:
        #    print ( "no likelihood: %s" % label )
        sqrts = int(e.globalInfo.sqrts.asNumber(TeV))
        color = ROOT.kCyan+2
        ymax=0
        if ana == "ATLAS":
            color = ROOT.kBlue+1
        if sqrts > 10.:
            color += 2
        if x < bins[ana][sqrts][0]:
            bins[ana][sqrts][0]=x
        if x > bins[ana][sqrts][1]:
            bins[ana][sqrts][1]=x
            ymax=x
        color = ROOT.kGray+2
        if len(exps)==1 and len(sqrtses)==1:
            label = label.replace("CMS-","").replace("ATLAS-","").replace("-agg","")
        label = "#color[%d]{%s}" % (color, label )
        xaxis.SetBinLabel(n-x, label )
        yaxis.SetBinLabel(x+1, label )
        for y,f in enumerate(results):
            if trianglePlot and y>x:
                continue
            isUn = analysisCombiner.canCombine ( e.globalInfo, f.globalInfo, strategy )
            # isUn = e.isUncorrelatedWith ( f )
            if isUn:
                h.SetBinContent ( n-x, y+1, 1. )
            else:
                h.SetBinContent ( n-x, y+1, -1. )
            if not hasLikelihood or not hasLLHD ( f ): ## has no llhd? cannot be combined
                h.SetBinContent ( n-x, y+1, 2. )
            if y==x:
                h.SetBinContent ( n-x, y+1, 3. )

    h.Draw("col")
    ROOT.bins, ROOT.xbins, ROOT.lines = {}, {}, []
    if len(exps)==1 and len(sqrtses)==1:
        ROOT.t1 = ROOT.TLatex()
        ROOT.t1.SetNDC()
        ROOT.t1.DrawLatex ( .45, .95, "%s, %d TeV" % ( exps[0], sqrtses[0] ) )
        
    for ana in exps:
        for sqrts in sqrtses:
            name= "%s%d" % ( ana, sqrts )
            ROOT.bins[name] = ROOT.TLatex()
            ROOT.bins[name].SetTextColorAlpha(ROOT.kBlack,.7)
            ROOT.bins[name].SetTextSize(.025)
            ROOT.bins[name].SetTextAngle(90.)
            ROOT.xbins[name] = ROOT.TLatex()
            ROOT.xbins[name].SetTextColorAlpha(ROOT.kBlack,.7)
            ROOT.xbins[name].SetTextSize(.025)
            xcoord = .5 * ( bins[ana][sqrts][0] + bins[ana][sqrts][1] )
            ycoord = n- .5 * ( bins[ana][sqrts][0] + bins[ana][sqrts][1] ) -3
            if len(sqrtses)>1 or len(exps)>1:
                ROOT.bins[name].DrawLatex(-4,xcoord-3,"#splitline{%s}{%d TeV}" % ( ana, sqrts ) )
                ROOT.xbins[name].DrawLatex(ycoord,-5,"#splitline{%s}{%d TeV}" % ( ana, sqrts ) )
            yt = bins[ana][sqrts][1] +1
            extrudes = 3 # how far does the line extrude into tick labels?
            xmax = n
            if trianglePlot:
                xmax = n-yt
            line = ROOT.TLine ( -extrudes, yt, xmax, yt )
            line.SetLineWidth(2)
            line.Draw()
            ymax = n
            if trianglePlot:
                ymax = yt
            xline = ROOT.TLine ( n-yt, ymax, n-yt, -extrudes )
            xline.SetLineWidth(2)
            xline.Draw()
            ROOT.lines.append ( line )
            ROOT.lines.append ( xline )
    line = ROOT.TLine ( -extrudes, 0, xmax, 0 )
    line.SetLineWidth(2)
    line.Draw()
    xline = ROOT.TLine ( n, ymax, n, -extrudes )
    xline.SetLineWidth(2)
    xline.Draw()
    ROOT.lines.append ( line )
    ROOT.lines.append ( xline )
    h.LabelsOption("v","X")
    if trianglePlot:
        for i in range(n+1):
            wline = ROOT.TLine ( n, i, n-i, i )
            wline.SetLineColor ( ROOT.kWhite )
            wline.Draw ()
            ROOT.lines.append ( wline )
            vline = ROOT.TLine ( i, n-i, i, n )
            vline.SetLineColor ( ROOT.kWhite )
            vline.Draw ()
        ROOT.lines.append ( vline )
        ROOT.title = ROOT.TLatex()
        ROOT.title.SetNDC()
        ROOT.title.SetTextSize(.025 )
        ROOT.title.DrawLatex(.28,.89, "#font[132]{Correlations between analyses, combination strategy: ,,%s''}" % strategy )
    ROOT.boxes = []
    if trianglePlot:
        for i,b in enumerate ( [ "pair is uncorrelated", "pair is correlated", "likelihood is missing" ] ):
            bx = 51
            by = 68 - 3*i
            box = ROOT.TBox(bx,by,bx+1,by+1)
            c = cols[i]
            if i > 0:
                c = cols[i+1]
            box.SetFillColor ( c )
            box.Draw()
            ROOT.boxes.append ( box )
            l = ROOT.TLatex()
            l.SetTextSize(.022)
            #if i == 2:
            #    c = 16
            l.SetTextColor ( c )
            b="#font[132]{%s}" % b ## add font
            l.DrawLatex ( bx+2, by, b )
            ROOT.boxes.append ( l )
    l = ROOT.TLatex()
    l.SetNDC()
    l.SetTextColor(ROOT.kGray+1)
    l.SetTextSize(.015)
    if drawtimestamp:
        l.DrawLatex ( .01, .01, "plot produced %s from database v%s" % \
                      ( time.strftime("%h %d %Y" ), d.databaseVersion ) )
    ROOT.gPad.SetGrid()
    if "@M" in outputfile:
        modifiers = ""
        if len(exps)==1:
            modifiers += exps[0]
        if len(sqrtses)==1:
            modifiers += str(sqrtses[0])
        outputfile = outputfile.replace("@M",modifiers)
    print ( "Plotting to %s" % outputfile )
    ROOT.c1.Print( outputfile )
コード例 #15
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)
コード例 #16
0
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from ptools.sparticleNames import SParticleNames
# sns.set() #Set style
# sns.set_style('ticks')
sns.set_style('ticks', {
    'font.family': 'Times New Roman',
    'font.serif': 'Times New Roman'
})
sns.set_context('paper', font_scale=2.0)
# sns.set_palette(sns.color_palette("Paired"))
sns.set_palette(sns.color_palette("deep"))
from smodels.tools import smodelsLogging
smodelsLogging.setLogLevel('error')

argparser = argparse.ArgumentParser(
    description="high score comparison plotter")
argparser.add_argument('-s',
                       '--signalfiles',
                       help='the run files [kinky]',
                       type=str,
                       default='kinky')
argparser.add_argument('-r',
                       '--realfiles',
                       help='the real files [real]',
                       type=str,
                       default='real')
args = argparser.parse_args()
コード例 #17
0
ファイル: testCombined.py プロジェクト: SModelS/smodels
            output_module = imp.load_module("output",fp,outputfile, 
                                            ('.py', 'rb', imp.PY_SOURCE) )
        smodelsOutput = output_module.smodelsOutput
        f=open("gluino_squarks_default_agg.py","w")
        f.write ( "smodelsOutputDefault = %s\n" % smodelsOutput )
        f.close()

    def testCombinedResult(self):
        filename = "./testFiles/slha/gluino_squarks.slha"
        outputfile = runMain(filename,inifile="testParameters_agg.ini", suppressStdout=True )
        with open( outputfile, 'rb') as fp: ## imports file with dots in name
            output_module = imp.load_module("output",fp,outputfile, 
                                            ('.py', 'rb', imp.PY_SOURCE) )
            smodelsOutput = output_module.smodelsOutput
            from gluino_squarks_default_agg import smodelsOutputDefault
            ignoreFields = ['input file','smodels version', 'ncpus', 'database version']
            smodelsOutputDefault['ExptRes'] = sorted(smodelsOutputDefault['ExptRes'],
                        key=lambda res: res['r'], reverse=True)
            equals = equalObjs(smodelsOutput,smodelsOutputDefault,allowedDiff=0.02,
                               ignore=ignoreFields)
            if equals != True:
                logger.error ( "%s differs from %s!" % ( "gluino_squarks_default_agg.py", outputfile) ) 
            self.assertTrue(equals)
        for i in [ outputfile, outputfile.replace(".py",".pyc") ]:
            if os.path.exists ( i ):
                os.remove ( i )
 
if __name__ == "__main__":
    setLogLevel ( "debug" )
    unittest.main()
コード例 #18
0
ファイル: Example.py プロジェクト: SModelS/smodels
from __future__ import print_function
"""
.. module:: Example
   :synopsis: Basic main file example for using SModelS.   
   This file must be run under the installation folder.
"""
""" Import basic functions (this file must be executed in the installation folder) """

from smodels import particlesLoader
from smodels.theory import slhaDecomposer,lheDecomposer
from smodels.tools.physicsUnits import fb, GeV, TeV
from smodels.theory.theoryPrediction import theoryPredictionsFor
from smodels.experiment.databaseObj import Database
from smodels.tools import coverage
from smodels.tools.smodelsLogging import setLogLevel
setLogLevel("info")


# Set the path to the database
database = Database("official")

def main():
    """
    Main program. Displays basic use case.
    """
    
    #Define your model (list of rEven and rOdd particles)
    particlesLoader.load( 'smodels.share.models.mssm' ) #Make sure all the model particles are up-to-date
    
    # Path to input file (either a SLHA or LHE file)
    slhafile = 'inputFiles/slha/lightEWinos.slha'
コード例 #19
0
ファイル: testServer.py プロジェクト: gipsyblues/smodels
sys.path.insert(0, "../")
import unittest
import glob
from smodels.tools import crashReport
from smodels.tools.timeOut import NoTime
from smodels.experiment.databaseObj import Database
from unitTestHelpers import equalObjs, runMain, importModule
import time, random
import subprocess

from smodels.tools.smodelsLogging import logger, setLogLevel
from smodels.tools.databaseClient import DatabaseClient
from smodels.tools.databaseServer import DatabaseServer
import warnings

setLogLevel("warn")


class ServerTest(unittest.TestCase):
    def testCompare(self):
        warnings.simplefilter("ignore", ResourceWarning)
        from simplyGluino_default import smodelsOutputDefault
        filename = "./testFiles/slha/simplyGluino.slha"
        port = random.choice(range(31700, 42000))
        # port = 31744
        dbfile = "database/db30.pcl"
        dbfile = "unittest"

        startserver = f"../smodels/tools/smodelsTools.py proxydb -p {port} -i {dbfile} -o ./proxy.pcl -r -v error"
        cmd = startserver.split(" ")
        # print ( "starting server %s" % startserver )
コード例 #20
0
   :synopsis: Tests QNUMBERS

.. moduleauthor:: Andre Lessa <*****@*****.**>

"""

import sys
sys.path.insert(0,"../")
import unittest
from smodels.tools.smodelsLogging import setLogLevel
from smodels.tools import runtime
from smodels.theory.model import Model
from smodels import particlesLoader
from smodels.share.models.SMparticles import SMList
from imp import reload
setLogLevel('error')


class ModelsTest(unittest.TestCase):
    #Check if models loaded through python module or through SLHA QNUMBERS give the same model
    def testRuntimeImport(self):
        filename = "./testFiles/slha/gluino_squarks.slha"
        runtime.modelFile = 'mssm'
        reload(particlesLoader)
        from smodels.particlesLoader import BSMList
        model = Model(BSMparticles=BSMList, SMparticles=SMList)
        model.updateParticles(filename)

        runtime.modelFile = 'mssmQNumbers.slha'
        reload(particlesLoader)
        from smodels.particlesLoader import BSMList
コード例 #21
0
ファイル: testModels.py プロジェクト: gipsyblues/smodels
.. moduleauthor:: Ursula Laa <*****@*****.**>
.. moduleauthor:: Andre Lessa <*****@*****.**>

"""

import sys,os
sys.path.insert(0,"../")
import unittest
from unitTestHelpers import equalObjs, runMain, importModule
from smodels.tools.smodelsLogging import setLogLevel
from smodels.tools import runtime
from smodels import particlesLoader
from imp import reload
import subprocess
from smodels.tools.smodelsLogging import logger
setLogLevel('debug')


class ModelsTest(unittest.TestCase):
    definingRun = False ## meant only to adapt to changes in output format
    ## use with super great care!!

    def testRuntimeImport(self):
        filename = "./testFiles/slha/idm_example.slha"
        runtime.modelFile = 'idm'
        reload(particlesLoader)
        outputfile = runMain(filename,inifile='testParameters_noModel.ini',suppressStdout=True)
        if self.definingRun:
            logger.error ( "This is a definition run! Know what youre doing!" )
            default = "idm_example_defaultB.py"
            cmd = "cat %s | sed -e 's/smodelsOutput/smodelsOutputDefault/' > %s" % ( outputfile, default )
コード例 #22
0
        '--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)
    ap.add_argument('-particles',
                    '--particlePath',
                    help='path to directory where particles.py is located',
                    default=installDirectory() + "/smodels")

    args = ap.parse_args()

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

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

    else:
        main(args.filename, args.parameterFile, args.outputDir, db,
             args.timeout, args.development, args.particlePath)
コード例 #23
0
ファイル: databaseObj.py プロジェクト: gipsyblues/smodels
 argparser.add_argument('-u',
                        '--update',
                        help='update binary db file, if necessary',
                        action='store_true')
 argparser.add_argument('-d',
                        '--debug',
                        help='debug mode',
                        action='store_true')
 argparser.add_argument('-D',
                        '--database',
                        help='directory name of database',
                        default="../../../smodels-database/")
 args = argparser.parse_args()
 logger.setLevel(level=logging.INFO)
 if args.debug:
     setLogLevel(level=logging.DEBUG)
 if args.write:
     db = Database(args.database, force_load="txt")
     db.createBinaryFile()
     sys.exit()
 db = Database(args.database)
 if args.update:
     db.updateBinaryFile()
 if args.check:
     db.checkBinaryFile()
 if args.time:
     t0 = time.time()
     expResult = db.loadBinaryFile(lastm_only=False)
     t1 = time.time()
     print("Time it took reading binary db file: %.1f s." % (t1 - t0))
     txtdb = db.loadTextDatabase()
コード例 #24
0
ファイル: testCombined.py プロジェクト: ismailturan/smodels
                             inifile="testParameters_agg.ini",
                             suppressStdout=True)
        with open(outputfile, 'rb') as fp:  ## imports file with dots in name
            output_module = imp.load_module("output", fp, outputfile,
                                            ('.py', 'rb', imp.PY_SOURCE))
            smodelsOutput = output_module.smodelsOutput
            from gluino_squarks_default_agg import smodelsOutputDefault
            ignoreFields = [
                'input file', 'smodels version', 'ncpus', 'database version'
            ]
            smodelsOutputDefault['ExptRes'] = sorted(
                smodelsOutputDefault['ExptRes'],
                key=lambda res: res['r'],
                reverse=True)
            equals = equalObjs(smodelsOutput,
                               smodelsOutputDefault,
                               allowedDiff=0.02,
                               ignore=ignoreFields)
            if equals != True:
                logger.error("%s differs from %s!" %
                             ("gluino_squarks_default_agg.py", outputfile))
            self.assertTrue(equals)
        for i in [outputfile, outputfile.replace(".py", ".pyc")]:
            if os.path.exists(i):
                os.remove(i)


if __name__ == "__main__":
    setLogLevel("debug")
    unittest.main()
コード例 #25
0
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)
コード例 #26
0
ファイル: runSModelS.py プロジェクト: gipsyblues/smodels
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)
コード例 #27
0
class XSecTest(unittest.TestCase):
    # use different logging config for the unit tests.
    logging.config.fileConfig( "./logging.conf" )
    from smodels.tools.smodelsLogging import setLogLevel,logger
    
    setLogLevel ( "warn" )

    toolBox.ToolBox().compile() ## make sure the tools are compiled

    def testLOGlu(self):
        """ test the computation of LO cross section, pythia6 """
        self.logger.info ( "test LO xsecs @ 8 TeV" )
        slhafile= "./testFiles/slha/simplyGluino.slha"
        computer = xsecComputer.XSecComputer ( LO, 100, 6 )
        w = computer.compute(8*TeV, slhafile ).getDictionary()
        # print ( w )
        w8lo= w[(1000021, 1000021)]['8 TeV (LO)'].asNumber( fb )
        self.assertAlmostEqual(w8lo, 268.2255 ) 

    def testNLLGlu(self):
        """ test the computation of NLL cross section """
        self.logger.info ( "test NLL xsecs @ 8 TeV" )
        slhafile="./testFiles/slha/simplyGluino.slha"
        computer = xsecComputer.XSecComputer ( NLL, 100, 6 )
        w = computer.compute( 8*TeV, slhafile ).getDictionary()
        w8nll= w[(1000021, 1000021)]['8 TeV (NLO+NLL)'].asNumber( fb )
        self.assertAlmostEqual(w8nll, 582.61261, 4 )

    def testLOGlu13(self):
        """ test the computation of LO cross section, pythia6 """
        self.logger.info ( "test LO xsecs @ 13 TeV" )
        slhafile="./testFiles/slha/simplyGluino.slha"
        computer = xsecComputer.XSecComputer ( LO, 100, 6 )
        w = computer.compute( 13*TeV, slhafile ).getDictionary()
        w13lo= w[(1000021, 1000021)]['13 TeV (LO)'].asNumber( fb )
        self.assertAlmostEqual(w13lo, 2240.7303 )

    def testNLLGlu13(self):
        """ test the computation of NLL cross section with pythia6 """
        self.logger.info ( "test NLL xsecs @ 13 TeV" )
        slhafile="./testFiles/slha/simplyGluino.slha"
        computer = xsecComputer.XSecComputer ( NLL, 100, 6 )
        w = computer.compute( 13*TeV, slhafile ).getDictionary()
        w13nll= w[(1000021, 1000021)]['13 TeV (NLO+NLL)'].asNumber( fb )
        self.assertAlmostEqual(w13nll, 4329.091, 3 )
        
    def testXSecMain(self):
        """ test the main routine for computation of LO and NLL cross section for several sqrts"""
        
        slhafile="./testFiles/slha/simplyGluino.slha"
        f = open(slhafile,'r')
        fdata = f.read()
        fdata = fdata[:fdata.find('XSECTION')]
        f.close()
        fnew = tempfile.mkstemp()
        os.close(fnew[0])
        tmpfile = fnew[1]
        fnew = open(tmpfile,'w')
        fnew.write(fdata)
        fnew.close()        
        self.logger.info ("test NLL xsecs @ 8 and 13 TeV" )
        #Set overall options:
        #Options for cross section calculation:
        xargs = argparse.Namespace()
        xargs.sqrts = [[8.,13.]]
        xargs.ncpus = 1
        xargs.nevents = 100
        #Compute LO xsecs:
        xargs.query = False
        xargs.NLL = False
        xargs.NLO = False
        xargs.LOfromSLHA = False
        xargs.keep = False
        xargs.tofile = True
        xargs.alltofile = False
        xargs.pythia6 = True
        xargs.filename = tmpfile
        xargs.colors = False
        xargs.verbosity = "warning"
        #Compute LO cross sections
        xsecComputer.main(xargs)
        #Compute NLL cross sections
        xargs.NLL = True
        xargs.LOfromSLHA = True
        xsecComputer.main(xargs)
        #Read xsecs:
        xsecsInfile = crossSection.getXsecFromSLHAFile(tmpfile)
        os.remove(tmpfile)
        
        #Check 8 TeV xsecs:
        lo = xsecsInfile.getXsecsFor('8 TeV (LO)')[0].value.asNumber(fb)
        nll = xsecsInfile.getXsecsFor('8 TeV (NLL)')[0].value.asNumber(fb)
        self.assertAlmostEqual(lo,268.2255,3)
        self.assertAlmostEqual(nll,582.612609,3)
        #Check 13 TeV xsecs:
        lo = xsecsInfile.getXsecsFor('13 TeV (LO)')[0].value.asNumber(fb)
        nll = xsecsInfile.getXsecsFor('13 TeV (NLL)')[0].value.asNumber(fb)
        self.assertAlmostEqual(lo,2240.7303,2 )
        self.assertAlmostEqual(nll,4329.09094,2)
コード例 #28
0
ファイル: smodelsTools.py プロジェクト: SModelS/smodels
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)
コード例 #29
0
from smodels.tools import runtime
#Define your model (list of BSM particles)
runtime.modelFile = 'smodels.share.models.mssm'
#runtime.modelFile = 'mssmQNumbers.slha'

from smodels.theory import decomposer
from smodels.tools.physicsUnits import fb, GeV, TeV
from smodels.theory.theoryPrediction import theoryPredictionsFor
from smodels.experiment.databaseObj import Database
from smodels.tools import coverage
from smodels.tools.smodelsLogging import setLogLevel
from smodels.particlesLoader import BSMList
from smodels.share.models.SMparticles import SMList
from smodels.theory.model import Model
setLogLevel("info")

# Set the path to the database
database = Database("official")


def main():
    """
    Main program. Displays basic use case.
    """
    model = Model(BSMparticles=BSMList, SMparticles=SMList)
    # Path to input file (either a SLHA or LHE file)
    #     lhefile = 'inputFiles/lhe/gluino_squarks.lhe'
    slhafile = 'inputFiles/slha/lightEWinos.slha'
    #     model.updateParticles(inputFile=lhefile)
    model.updateParticles(inputFile=slhafile)
コード例 #30
0
class XSecTest(unittest.TestCase):
    # use different logging config for the unit tests.
    logging.config.fileConfig( "./logging.conf" )
    from smodels.tools.smodelsLogging import setLogLevel,logger
    
    setLogLevel ( "warn" )

    toolBox.ToolBox().compile() ## make sure the tools are compiled

    def testLOGlu(self):
        """ test the computation of LO cross section, pythia6 """
        self.logger.info ( "test LO xsecs @ 8 TeV" )
        slhafile= "./testFiles/slha/simplyGluino.slha"
        computer = xsecComputer.XSecComputer ( LO, 2000, 6 )
        w = computer.compute(8*TeV, slhafile ).getDictionary()
        # print ( w )
        w8lo= w[(1000021, 1000021)]['8 TeV (LO)'].asNumber( fb )
        self.assertAlmostEqual(w8lo/264., 1., 2 ) 

    def testNLLGlu(self):
        """ test the computation of NLL cross section """
        self.logger.info ( "test NLL xsecs @ 8 TeV" )
        slhafile="./testFiles/slha/simplyGluino.slha"
        computer = xsecComputer.XSecComputer ( NLL, 2000, 6 )
        w = computer.compute( 8*TeV, slhafile ).getDictionary()
        w8nll= w[(1000021, 1000021)]['8 TeV (NLO+NLL)'].asNumber( fb )
        self.assertAlmostEqual(w8nll / 573., 1., 2 )

    def testLOGlu13(self):
        """ test the computation of LO cross section, pythia6 """
        self.logger.info ( "test LO xsecs @ 13 TeV" )
        slhafile="./testFiles/slha/simplyGluino.slha"
        computer = xsecComputer.XSecComputer ( LO, 3000, 6 )
        w = computer.compute( 13*TeV, slhafile ).getDictionary()
        w13lo= w[(1000021, 1000021)]['13 TeV (LO)'].asNumber( fb )
        self.assertAlmostEqual(w13lo / 2237., 1., 1 )

    def testNLLGlu13(self):
        """ test the computation of NLL cross section with pythia6 """
        self.logger.info ( "test NLL xsecs @ 13 TeV" )
        slhafile="./testFiles/slha/simplyGluino.slha"
        computer = xsecComputer.XSecComputer ( NLL, 3000, 6 )
        w = computer.compute( 13*TeV, slhafile ).getDictionary()
        w13nll= w[(1000021, 1000021)]['13 TeV (NLO+NLL)'].asNumber( fb )
        self.assertAlmostEqual(w13nll / 4320. , 1., 2 )
        
    def testXSecMain(self):
        """ test the main routine for computation of LO and NLL cross section for several sqrts"""
        
        slhafile="./testFiles/slha/simplyGluino.slha"
        f = open(slhafile,'r')
        fdata = f.read()
        fdata = fdata[:fdata.find('XSECTION')]
        f.close()
        fnew = tempfile.mkstemp()
        os.close(fnew[0])
        tmpfile = fnew[1]
        fnew = open(tmpfile,'w')
        fnew.write(fdata)
        fnew.close()        
        self.logger.info ("test NLL xsecs @ 8 and 13 TeV" )
        #Set overall options:
        #Options for cross section calculation:
        xargs = argparse.Namespace()
        xargs.sqrts = [[8.,13.]]
        xargs.ncpus = 1
        xargs.noautocompile = True
        xargs.nevents = 2000
        #Compute LO xsecs:
        xargs.query = False
        xargs.NLL = False
        xargs.NLO = False
        xargs.LOfromSLHA = False
        xargs.keep = False
        xargs.tofile = True
        xargs.alltofile = False
        xargs.pythia6 = True
        xargs.filename = tmpfile
        xargs.colors = False
        xargs.ssmultipliers = None
        xargs.verbosity = "warning"
        #Compute LO cross sections
        xsecComputer.main(xargs)
        #Compute NLL cross sections
        xargs.NLL = True
        xargs.LOfromSLHA = True
        xsecComputer.main(xargs)
        #Read xsecs:
        xsecsInfile = crossSection.getXsecFromSLHAFile(tmpfile)
        os.remove(tmpfile)
        
        #Check 8 TeV xsecs:
        lo = xsecsInfile.getXsecsFor('8 TeV (LO)')[0].value.asNumber(fb)
        nll = xsecsInfile.getXsecsFor('8 TeV (NLL)')[0].value.asNumber(fb)
        self.assertAlmostEqual(lo/264.,1.,2)
        self.assertAlmostEqual(nll/573.6,1.,2)
        #Check 13 TeV xsecs:
        lo = xsecsInfile.getXsecsFor('13 TeV (LO)')[0].value.asNumber(fb)
        nll = xsecsInfile.getXsecsFor('13 TeV (NLL)')[0].value.asNumber(fb)
        self.assertAlmostEqual(lo / 2230., 1., 1 )
        self.assertAlmostEqual(nll / 4308., 1., 1 )

    def testSSMultipliers(self):
        """ test the signal strength multipliers """
        
        slhafile="./testFiles/slha/simplyGluino.slha"
        f = open(slhafile,'r')
        fdata = f.read()
        fdata = fdata[:fdata.find('XSECTION')]
        f.close()
        fnew = tempfile.mkstemp()
        os.close(fnew[0])
        tmpfile = fnew[1]
        fnew = open(tmpfile,'w')
        fnew.write(fdata)
        fnew.close()        
        self.logger.info ("test NLL xsecs @ 8 and 13 TeV" )
        #Set overall options:
        #Options for cross section calculation:
        xargs = argparse.Namespace()
        xargs.sqrts = [[8.,13.]]
        xargs.ncpus = 1
        xargs.noautocompile = True
        xargs.nevents = 5000
        #Compute LO xsecs:
        xargs.query = False
        xargs.NLL = False
        xargs.NLO = False
        xargs.LOfromSLHA = False
        xargs.keep = False
        xargs.tofile = True
        xargs.alltofile = False
        xargs.pythia6 = True
        xargs.filename = tmpfile
        xargs.colors = False
        xargs.ssmultipliers = { (1000021,1000021): 4. }
        # xargs.ssmultipliers = { 1000021: 2. }
        xargs.verbosity = "warning"
        #Compute LO cross sections
        xsecComputer.main(xargs)
        #Compute NLL cross sections
        xargs.NLL = True
        xargs.LOfromSLHA = True
        xsecComputer.main(xargs)
        #Read xsecs:
        xsecsInfile = crossSection.getXsecFromSLHAFile(tmpfile)
        os.remove(tmpfile)
        
        #Check 8 TeV xsecs:
        lo = xsecsInfile.getXsecsFor('8 TeV (LO)')[0].value.asNumber(fb)
        nll = xsecsInfile.getXsecsFor('8 TeV (NLL)')[0].value.asNumber(fb)
        self.assertAlmostEqual(lo/1058.444,1.,1)
        self.assertAlmostEqual(nll/2299.046,1.,1)
        #Check 13 TeV xsecs:
        lo = xsecsInfile.getXsecsFor('13 TeV (LO)')[0].value.asNumber(fb)
        nll = xsecsInfile.getXsecsFor('13 TeV (NLL)')[0].value.asNumber(fb)
        self.assertAlmostEqual(lo/8910.76,1.,1 )
        self.assertAlmostEqual(nll/17215.5906, 1.,1)
        
    def testSSJokers(self):
        """ test the signal strength multipliers, with jokers """
        
        slhafile="./testFiles/slha/simplyGluino.slha"
        f = open(slhafile,'r')
        fdata = f.read()
        fdata = fdata[:fdata.find('XSECTION')]
        f.close()
        fnew = tempfile.mkstemp()
        os.close(fnew[0])
        tmpfile = fnew[1]
        fnew = open(tmpfile,'w')
        fnew.write(fdata)
        fnew.close()        
        self.logger.info ("test NLL xsecs @ 8 and 13 TeV" )
        #Set overall options:
        #Options for cross section calculation:
        xargs = argparse.Namespace()
        xargs.sqrts = [[8.,13.]]
        xargs.noautocompile = True
        xargs.ncpus = 1
        xargs.nevents = 5000
        #Compute LO xsecs:
        xargs.query = False
        xargs.NLL = False
        xargs.NLO = False
        xargs.LOfromSLHA = False
        xargs.keep = False
        xargs.tofile = True
        xargs.alltofile = False
        xargs.pythia6 = True
        xargs.filename = tmpfile
        xargs.colors = False
        xargs.ssmultipliers = { ('*100002?','*1000021'): 4. }
        # xargs.ssmultipliers = { 1000021: 2. }
        xargs.verbosity = "warning"
        #Compute LO cross sections
        xsecComputer.main(xargs)
        #Compute NLL cross sections
        xargs.NLL = True
        xargs.LOfromSLHA = True
        xsecComputer.main(xargs)
        #Read xsecs:
        xsecsInfile = crossSection.getXsecFromSLHAFile(tmpfile)
        os.remove(tmpfile)
        
        #Check 8 TeV xsecs:
        lo = xsecsInfile.getXsecsFor('8 TeV (LO)')[0].value.asNumber(fb)
        nll = xsecsInfile.getXsecsFor('8 TeV (NLL)')[0].value.asNumber(fb)
        self.assertAlmostEqual(lo/1056.,1.,2)
        self.assertAlmostEqual(nll/2294.,1.,2)
        #Check 13 TeV xsecs:
        lo = xsecsInfile.getXsecsFor('13 TeV (LO)')[0].value.asNumber(fb)
        nll = xsecsInfile.getXsecsFor('13 TeV (NLL)')[0].value.asNumber(fb)
        self.assertAlmostEqual(lo/8910.76,1.,2 )
        self.assertAlmostEqual(nll/17215.5906, 1.,1)
コード例 #31
0
ファイル: databaseObj.py プロジェクト: SModelS/smodels
 argparser.add_argument('-t', '--time', help='time reading db',
                        action='store_true')
 argparser.add_argument('-r', '--read', help='read binary db file',
                        action='store_true')
 argparser.add_argument('-w', '--write', help='force writing binary db file',
                        action='store_true')
 argparser.add_argument('-u', '--update', help='update binary db file, if necessary',
                        action='store_true')
 argparser.add_argument('-d', '--debug', help='debug mode',
                        action='store_true')
 argparser.add_argument('-D', '--database', help='directory name of database',
                         default="../../../smodels-database/" )
 args = argparser.parse_args()
 logger.setLevel(level=logging.INFO )
 if args.debug:
     setLogLevel(level=logging.DEBUG )
 if args.write:
     db = Database ( args.database, force_load="txt" )
     db.createBinaryFile()
     sys.exit()
 db = Database ( args.database )
 if args.update:
     db.updateBinaryFile()
 if args.check:
     db.checkBinaryFile()
 if args.time:
     t0=time.time()
     expResult = db.loadBinaryFile ( lastm_only = False )
     t1=time.time()
     print ( "Time it took reading binary db file: %.1f s." % (t1-t0) )
     txtdb = db.loadTextDatabase()
コード例 #32
0
ファイル: testCpp.py プロジェクト: SModelS/smodels
#!/usr/bin/env python3

"""
.. module:: testCpp
   :synopsis: Tests the C++ interface

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

"""

import sys
sys.path.insert(0,"../")
from smodels.tools.smodelsLogging import setLogLevel
setLogLevel ( "error" )

import unittest
if sys.version[0]=="2":
    import commands as CMD
else:
    import subprocess as CMD

class CppTest(unittest.TestCase):
    def compile(self):
        """ compile the C++ interface """
        cmd = "cd ../cpp; make"
        a = CMD.getoutput ( cmd ).split("\n" )
        ## now check if "done" appears in the last line
        self.assertTrue ( "done" in a[-1] )

    def writeOutput(self):
        """ write the default output. will *define* the unit test. """
コード例 #33
0
ファイル: testCpp.py プロジェクト: ismailturan/smodels
#!/usr/bin/env python3
"""
.. module:: testCpp
   :synopsis: Tests the C++ interface

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

"""

import sys

sys.path.insert(0, "../")
from smodels.tools.smodelsLogging import setLogLevel

setLogLevel("error")

import unittest
if sys.version[0] == "2":
    import commands as CMD
else:
    import subprocess as CMD


class CppTest(unittest.TestCase):
    def compile(self):
        """ compile the C++ interface """
        cmd = "cd ../cpp; make"
        a = CMD.getoutput(cmd).split("\n")
        ## now check if "done" appears in the last line
        self.assertTrue("done" in a[-1])