Ejemplo n.º 1
0
    # Set default histogram behavior
    import ROOT as r
    r.TH1.SetDefaultSumw2(False)
    r.gROOT.SetBatch(True)
    r.gStyle.SetOptStat(1111111)

    dacScanFile = r.TFile(args.infilename, "READ")

    if len(args.infilename.split('/')) > 1 and len(
            args.infilename.split('/')[len(args.infilename.split('/')) -
                                       2].split('.')) == 5:
        scandate = args.infilename.split('/')[len(args.infilename.split('/')) -
                                              2]
    else:
        scandate = 'noscandate'

    from gempython.gemplotting.utils.anautilities import dacAnalysis
    from gempython.gemplotting.utils.exceptions import VFATDACBiasCannotBeReached
    try:
        dacAnalysis(args,
                    dacScanFile.dacScanTree,
                    chamber_config,
                    scandate=scandate)
    except VFATDACBiasCannotBeReached as err:
        from gempython.utils.gemlogger import printRed
        printRed(err.message)
        printRed("VFATs above may *NOT* be properly biased")
    dacScanFile.Close()

    print("\nAnalysis completed. Goodbye")
                        default="current")

    args = parser.parse_args()

    # Set logging level to INFO if debug requested
    if args.debug:
        gemlogger = getGEMLogger(__name__)
        gemlogger.setLevel(logging.INFO)

    # Check to make sure (shelf,slot,key) exists in chamber_config
    from gempython.gemplotting.mapping.chamberInfo import chamber_config
    ohKey = (args.shelf, args.slot, args.link)
    import os
    if ohKey not in chamber_config:
        printRed(
            "I did not find (shelf,slot,link) = {0} in the chamber_config dictionary.\nExiting"
            .format(ohKey))
        exit(os.EX_USAGE)
    cName = chamber_config[ohKey]

    # Determine Card Name
    from gempython.vfatqc.utils.qcutilities import getCardName
    cardName = getCardName(args.shelf, args.slot)

    from gempython.tools.hw_constants import maxVfat3DACSize
    from gempython.gemplotting.utils.anautilities import getDataPath
    from gempython.vfatqc.utils.confUtils import updateVFAT3ConfFilesOnAMC
    dataPath = getDataPath()
    if args.dacSelect is None:
        # Send IREF values
        filename_iref = "{0}/{1}/NominalValues-CFG_IREF.txt".format(
    import numpy as np
    import root_numpy as rp
    print("Getting histograms and making output canvases")
    for oh in range(0, 12):
        # Skip masked OH's
        if (not ((args.ohMask >> oh) & 0x1)):
            continue

        # Make base directory
        baseDir[args.slot][oh] = "AMC13-{0}/AMC-{1}/GEB-{2}/".format(
            args.amc13, args.slot, oh)

        # Check to make sure this AMC13 & AMC exist in the file
        currentDir = infile.GetDirectory(baseDir[args.slot][oh])
        if currentDir == 0:
            printRed("Directory: {0} in file {1} does not exist".format(
                baseDir[slot][oh], args.infile))
            printRed("Skipping AMC{0} OH{1}".format(args.slot, oh))
            continue

        # Make mean & RMS lat dist
        latencyMean[args.slot][oh] = r.TH1D(
            "latencyMean_AMC{0}_OH{1}".format(args.slot, oh),
            "Latency spread across all VFATs for #left(AMC{0},OH{1}#right)".
            format(args.slot, oh), (args.scanmax - args.scanmin) * 10,
            args.scanmin - 0.5, args.scanmax - 0.5)
        latencyRMS[args.slot][oh] = r.TH1D(
            "latencyRMS_AMC{0}_OH{1}".format(args.slot, oh),
            "Latency RMS across all VFATs for #left(AMC{0},OH{1}#right)".
            format(args.slot, oh), 100, -0.5, 9.5)
        allVFATsLatency[args.slot][oh] = None
                    print('Set link {0} VFAT{1} CFG_THR_ARM_DAC to {2}'.format(
                        args.link, event.vfatN, event.vt1))
                    vfatBoard.setVFATThreshold(chip=int(event.vfatN),
                                               vt1=int(event.vt1))

        # Get all chip IDs
        dict_vfatIDvals[ohN] = vfatBoard.getAllChipIDs(args.vfatmask)

        # Get CFG_CAL_DAC calibration constants
        if args.calFileCAL:
            calDacCalFile = "{0}/{1}/calFile_calDac_{1}.txt".format(
                dataPath, chamber_config[ohKey])
            calDacCalFileExists = os.path.isfile(calDacCalFile)
            if not calDacCalFileExists:
                printRed(
                    "Missing CFG_CAL_DAC calibration file for shelf{0} slot{1} OH{2}, detector {3}:\n\t{4}"
                    .format(args.shelf, args.slot, ohN, chamber_config[ohKey],
                            calDacCalFile))
                raise Exception("Missing CFG_CAL_DAC Calibration file.")

            ohKey = (args.shelf, args.slot, ohN)
            dict_calFiles[ohKey] = calDacCalFile
            pass

    # Get initial channel registers
    if args.zeroChan:
        print(
            "zero'ing all channel registers on shelf{0} slot{1} in ohMask: 0x{2:x}"
            .format(args.shelf, args.slot, args.ohMask))
        for ohN in range(0, amcBoard.nOHs):
            # Skip masked OH's
            if (not ((args.ohMask >> ohN) & 0x1)):
def iterativeTrim(args,
                  dict_dirPaths,
                  identifier,
                  dict_chanRegData=None,
                  dict_calFiles=None):
    """
    Takes an scurve at a given set of channel registers (all 0's if not provided) and
    returns a dictionary of numpy arrays with fit results (see gempythong.gemplotting.fitting.fitScanData
    for details on the output container).

    args        - Namespace produced by ArgumentParser.parse_args
    dirPath     - Output filepath location that scurve raw data should be saved at
    identifier  - Unique string identifier to be used for each iteration
    chanRegData - structure numpy array containing channel register data, expected dtype values are:
                  [('CALPULSE_ENABLE','bool'),('MASK','bool'),('ZCC_TRIM_POLARITY','bool'),
                  ('ZCC_TRIM_AMPLITUDE','uint8'),('ARM_TRIM_POLARITY','bool'),('ARM_TRIM_AMPLITUDE','uint8')].
                  If provided these values will be written to the channel registers of all unmaksed VFATs.
    calInfo     - Tuple of numpy arrays providing CFG_CAL_DAC calibration info, idx = 0 (1) for slopw (intercept)
                  indexed by VFAT position
    """

    from ctypes import c_uint32

    import root_numpy as rp

    from gempython.vfatqc.utils.scanUtils import launchSCurve

    dictOfFiles = {}

    for ohN in range(0, amcBoard.nOHs):
        # Skip masked OH's
        if (not ((args.ohMask >> ohN) & 0x1)):
            continue

        ohKey = (args.shelf, args.slot, ohN)

        # Get Channel Register Info
        if dict_chanRegData is None:
            setChanRegs = False
            cArray_trimVal = None
            cArray_trimPol = None
        else:
            setChanRegs = True
            detName = chamber_config[ohKey]
            gemType = detName[:detName.find('-')].lower()
            cArray_trimVal = (
                c_uint32 * (vfatsPerGemVariant[gemType] * CHANNELS_PER_VFAT))(
                    *dict_chanRegData[ohN]["ARM_TRIM_AMPLITUDE"])
            cArray_trimPol = (
                c_uint32 * (vfatsPerGemVariant[gemType] * CHANNELS_PER_VFAT))(
                    *dict_chanRegData[ohN]["ARM_TRIM_POLARITY"])
            pass

        # Set filename of this scurve
        isZombie = True
        filename = "{:s}/SCurveData_{:s}.root".format(dict_dirPaths[ohN],
                                                      identifier)
        dictOfFiles[ohKey] = (filename, chamber_config[ohKey], GEBtype[ohKey])
        if os.path.isfile(filename):
            scurveRawFile = r.TFile(filename, "READ")
            isZombie = scurveRawFile.IsZombie()

        # Take the scurves in sequence (it is not possible to take scurves in parallel)
        if not isZombie:
            try:
                thisTree = scurveRawFile.scurveTree
            except AttributeError as error:
                print("Caught exception {:s}".format(error))
                print("Going to re-take scurve corresponding to: {:s}".format(
                    filename))
                launchSCurve(calSF=args.calSF,
                             cardName=getCardName(args.shelf, args.slot),
                             chMax=args.chMax,
                             chMin=args.chMin,
                             debug=args.debug,
                             filename=filename,
                             latency=args.latency,
                             link=ohN,
                             mspl=args.pulseStretch,
                             nevts=args.nevts,
                             setChanRegs=setChanRegs,
                             trimARM=cArray_trimVal,
                             trimARMPol=cArray_trimPol,
                             vfatmask=args.vfatmask,
                             voltageStepPulse=not args.currentPulse)

                print("scurve finished")
        else:
            print("File {:s} either doesn't exist or is a zombie".format(
                filename))
            print("Going to re-take scurve corresponding to: {:s}".format(
                filename))
            launchSCurve(calSF=args.calSF,
                         cardName=getCardName(args.shelf, args.slot),
                         chMax=args.chMax,
                         chMin=args.chMin,
                         debug=args.debug,
                         filename=filename,
                         latency=args.latency,
                         link=ohN,
                         mspl=args.pulseStretch,
                         nevts=args.nevts,
                         setChanRegs=setChanRegs,
                         trimARM=cArray_trimVal,
                         trimARMPol=cArray_trimPol,
                         vfatmask=args.vfatmask,
                         voltageStepPulse=not args.currentPulse)

            print("scurve finished")
            pass

    # Make the analysis output directories and set permissions
    from gempython.utils.wrappers import runCommand
    for scurveFile in dictOfFiles.values():
        runCommand(
            ["mkdir", "-p", "{0}".format(scurveFile[0].replace(".root", ""))])
        os.system("chmod -R g+rw {0} 2> /dev/null".format(
            scurveFile[0].replace(".root", "")))

    # Do the analysis in parallel
    from multiprocessing import Pool
    from gempython.gemplotting.utils.anautilities import getNumCores2Use, init_worker
    pool = Pool(getNumCores2Use(args), initializer=init_worker
                )  # Allocate number of CPU's based on getNumCores2Use()

    from gempython.gemplotting.utils.scurveAlgos import anaUltraScurveStar
    import itertools, sys, traceback

    try:
        print(
            "Launching scurve analysis processes, this may take some time, please be patient"
        )
        pool.map_async(
            anaUltraScurveStar,
            itertools.izip(
                [args for geoAddr in dictOfFiles.keys()],  # args namespace
                [scurveFile[0]
                 for scurveFile in dictOfFiles.values()],  # scurveFilename
                [dict_calFiles[geoAddr]
                 for geoAddr in dictOfFiles.keys()],  # calFile
                [scurveFile[2]
                 for scurveFile in dictOfFiles.values()],  # GEBtype
                [
                    scurveFile[0].replace(".root", "")
                    for scurveFile in dictOfFiles.values()
                ],  # outputDir
                [None for geoAddr in dictOfFiles.keys()]  # vfatList
            )).get(7200)  # wait at most 2 hours
    except KeyboardInterrupt:
        printRed("Caught KeyboardInterrupt, terminating workers")
        pool.terminate()
        raise Exception("Analysis failed.")
    except Exception as err:
        printRed("Caught {0}: {1}, terminating workers".format(
            type(err), err.message))
        pool.terminate()
        traceback.print_exc(file=sys.stdout)
        raise Exception("Analysis failed.")
    except:  # catch *all* exceptions
        e = sys.exc_info()[0]
        printRed("Caught non-Python Exception %s" % (e))
        pool.terminate()
        traceback.print_exc(file=sys.stdout)
        raise Exception("Analysis failed.")
    else:
        printGreen("Analysis Completed Successfully")
        pool.close()
        pool.join()

    scurveFitResults = {}

    for ohN in range(0, amcBoard.nOHs):
        # Skip masked OH's
        if (not ((args.ohMask >> ohN) & 0x1)):
            continue

        from gempython.gemplotting.utils.anaInfo import tree_names

        filename = "{0}/{1}".format(
            dict_dirPaths[ohN],
            tree_names["itertrimAna"][0].format(IDENTIFIER=identifier))

        # Load the file
        r.TH1.AddDirectory(False)
        scanFile = r.TFile(filename, "READ")

        if not scanFile.IsOpen():
            raise IOError(
                "iterativeTrim(): File {0} is not open or is not readable".
                format(filename))
        if scanFile.IsZombie():
            raise IOError(
                "iterativeTrim(): File {0} is a zombie".format(filename))

        # Determine vfatID
        list_bNames = ['vfatN', 'vfatID']
        array_vfatData = rp.tree2array(tree=scanFile.scurveFitTree,
                                       branches=list_bNames)
        array_vfatData = np.unique(array_vfatData)

        # Get scurve data for this arm dac value (used for boxplots)
        list_bNames = ['vfatCH', 'vfatN', 'threshold', 'noise']
        scurveFitData = rp.tree2array(tree=scanFile.scurveFitTree,
                                      branches=list_bNames)

        scurveFitResults[ohN] = scurveFitData

    return scurveFitResults
Ejemplo n.º 6
0
        help="String that defines the GEM variant, available from the list: {0}"
        .format(gemVariants.keys()),
        default="ge11")
    parser.add_argument(
        "--detType",
        type=str,
        help=
        "Detector type within gemType. If gemType is 'ge11' then this should be from list {0}; if gemType is 'ge21' then this should be from list {1}; and if type is 'me0' then this should be from the list {2}"
        .format(gemVariants['ge11'], gemVariants['ge21'], gemVariants['me0']),
        default=None)
    args = parser.parse_args()

    from gempython.utils.gemlogger import printRed
    if ((args.dacSelect not in maxVfat3DACSize.keys())
            and (args.dacSelect is not None)):
        printRed("Input DAC selection {0} not understood".format(
            args.dacSelect))
        printRed("possible options include:")
        from gempython.vfatqc.utils.qcutilities import printDACOptions
        printDACOptions()
        exit(os.EX_USAGE)

    # Open rpc connection to hw
    from gempython.vfatqc.utils.qcutilities import getCardName, inputOptionsValid
    cardName = getCardName(args.shelf, args.slot)
    from gempython.tools.vfat_user_functions_xhal import *
    vfatBoard = HwVFAT(cardName, 0, args.debug, args.gemType,
                       args.detType)  # Assign link 0; we will update later
    print 'opened connection'
    amcBoard = vfatBoard.parentOH.parentAMC
    if amcBoard.fwVersion < 3:
        printRed("DAC Scan of v2b electronics is not supported, exiting!!!")
    
    # Make output directory
    from gempython.utils.wrappers import runCommand
    filePath = args.infilename.replace('.root','')
    runCommand(["mkdir", "-p", "{0}".format(filePath)])
    runCommand(["chmod", "g+rw", "{0}".format(filePath)])

    if args.vfatList is not None:
        vfatList = [int(vfat) for vfat in args.vfatList.split(",")]
    else:
        vfatList = None

    # Run Analysis
    from gempython.utils.gemlogger import printRed
    import os, sys, traceback
    try:
        args.func(args,args.infilename,args.calFile,args.GEBtype,filePath,vfatList)
    except RuntimeError as err:
        printRed("RuntimeError: {0}".format(err.message))
        traceback.print_exc(file=sys.stdout)
        sys.exit(os.EX_SOFTWARE)
    except IOError as err:
        printRed("IOError: {0}".format(err.message))
        traceback.print_exc(file=sys.stdout)
        sys.exit(os.EX_IOERR)
    else:
        print('Analysis Completed Successfully')
    finally:
        from gempython.gemplotting.utils.anautilities import cleanup
        cleanup( [filePath] )
Ejemplo n.º 8
0
def readBackCheckV3(rootTree, dict_Names, vfatBoard, mask=0x0, vt1bump=0):
    """
    Given an input set of registers, and expected values of those registers, read from all VFATs on vfatBoard to see if there are any differences between written and read values.  Specifically for v3 electronics

    rootTree - name of a TTree that has values that should have been written
    dict_Names - dictionary where key names are the branch names in rootTree and the values are the register names they correspond too
    vfatBoard - instance of the HwVFAT class
    mask - vfatmask to use, 24 bit number, if the n^th bit is 1 the n^th VFAT is not considered
    vt1bump - value that has been added to CFG_THR_ARM_DAC
    """

    import numpy as np
    import root_numpy as rp
    import os, sys

    # Check that the requested register is supported
    list_KnownRegs = [
            "CFG_PULSE_STRETCH",
            "CFG_SYNC_LEVEL_MODE",
            "CFG_SELF_TRIGGER_MODE",
            "CFG_DDR_TRIGGER_MODE",
            "CFG_SPZS_SUMMARY_ONLY",
            "CFG_SPZS_MAX_PARTITIONS",
            "CFG_SPZS_ENABLE",
            "CFG_SZP_ENABLE",
            "CFG_SZD_ENABLE",
            "CFG_TIME_TAG",
            "CFG_EC_BYTES",
            "CFG_BC_BYTES",
            "CFG_FP_FE",
            "CFG_RES_PRE",
            "CFG_CAP_PRE",
            "CFG_PT",
            "CFG_EN_HYST",
            "CFG_SEL_POL",
            "CFG_FORCE_EN_ZCC",
            "CFG_FORCE_TH",
            "CFG_SEL_COMP_MODE",
            "CFG_VREF_ADC",
            "CFG_MON_GAIN",
            "CFG_MONITOR_SELECT",
            "CFG_IREF",
            "CFG_THR_ZCC_DAC",
            "CFG_THR_ARM_DAC",
            "CFG_HYST",
            "CFG_LATENCY",
            "CFG_CAL_SEL_POL",
            "CFG_CAL_PHI",
            "CFG_CAL_EXT",
            "CFG_CAL_DAC",
            "CFG_CAL_MODE",
            "CFG_CAL_FS",
            "CFG_CAL_DUR",
            "CFG_BIAS_CFD_DAC_2",
            "CFG_BIAS_CFD_DAC_1",
            "CFG_BIAS_PRE_I_BSF",
            "CFG_BIAS_PRE_I_BIT",
            "CFG_BIAS_PRE_I_BLCC",
            "CFG_BIAS_PRE_VREF",
            "CFG_BIAS_SH_I_BFCAS",
            "CFG_BIAS_SH_I_BDIFF",
            "CFG_BIAS_SH_I_BFAMP",
            "CFG_BIAS_SD_I_BDIFF",
            "CFG_BIAS_SD_I_BSF",
            "CFG_BIAS_SD_I_BFCAS",
            "CFG_RUN",
            "HW_CHIP_ID",
            "VFAT_CHANNELS.CHANNEL"]

    for regName in dict_Names.values():
        if regName not in list_KnownRegs:
            raise Exception("{2}readBackCheckV3() does not understand {0}; only supported for registers: {1}{3}".format(regName, list_KnownRegs,colors.RED,colors.ENDC),os.EX_USAGE)

    # Get data from tree
    list_bNames = dict_Names.keys()
    list_bNames.append('vfatN')
    if "mask" in dict_Names.keys() or "trimDAC" in dict_Names.keys() or "trimPolarity" in dict_Names.keys():
        list_bNames.append('vfatCH')
    array_writeVals = rp.tree2array(tree=rootTree, branches=list_bNames)

    # Get data from VFATs
    for bName,regName in dict_Names.iteritems():
        printBlue("Reading back (%s,%s) from all VFATs, any potential mismatches will be reported below"%(bName,regName))
        print "="*40

        regMap = []
        regValues = []
        if regName == "VFAT_CHANNELS.CHANNEL": #Channel Register
            regValues = getChannelRegisters(vfatBoard,mask)
            for vfat in range(0,24):
                if (mask >> vfat) & 0x1:
                    continue

                for chan in range(0,128):
                    writeValsPerVFAT = array_writeVals[ array_writeVals['vfatN'] == vfat]
                    writeValsPerVFAT = writeValsPerVFAT[ writeValsPerVFAT['vfatCH'] == chan]
                    writeValOfReg = np.asscalar(writeValsPerVFAT['%s'%bName])
                    if bName == "mask":
                        if writeValOfReg != regValues[128*vfat+chan]['MASK']:
                            printRed("VFAT%i Chan%i: %s mismatch, write val = %i, readback = %i"%(vfat, chan, bName, writeValOfReg, regValues[128*vfat+chan]['MASK']))
                    elif bName == "trimDAC":
                        if writeValOfReg != regValues[128*vfat+chan]['ARM_TRIM_AMPLITUDE']:
                            printRed("VFAT%i Chan%i: %s mismatch, write val = %i, readback = %i"%(vfat, chan, bName, writeValOfReg, regValues[128*vfat+chan]['ARM_TRIM_AMPLITUDE']))
                    elif bName == "trimPolarity":
                        if writeValOfReg != regValues[128*vfat+chan]['ARM_TRIM_POLARITY']:
                            printRed("VFAT%i Chan%i: %s mismatch, write val = %i, readback = %i"%(vfat, chan, bName, writeValOfReg, regValues[128*vfat+chan]['ARM_TRIM_POLARITY']))
        elif regName == "HW_CHIP_ID": #ChipID
            regValues = vfatBoard.getAllChipIDs(mask)
            for vfat,readBackVal in enumerate(regValues):
                if (mask >> vfat) & 0x1:
                    continue
                valsPerVFAT = array_writeVals[ array_writeVals['vfatN'] == vfat]
                valOfReg = int(np.asscalar(np.unique(valsPerVFAT['%s'%bName])))
                if valOfReg != readBackVal:
                    printRed("VFAT%i: %s mismatch, expected = %s, readback = %s"%(vfat, regName, hex(valOfReg), hex(readBackVal)))
        else: #VFAT Register
            regValues = vfatBoard.readAllVFATs(regName, mask)
            for vfat,readBackVal in enumerate(regValues):
                if (mask >> vfat) & 0x1:
                    continue
                writeValsPerVFAT = array_writeVals[ array_writeVals['vfatN'] == vfat]
                writeValOfReg = np.asscalar(writeValsPerVFAT['%s'%bName])
                if regName == "CFG_THR_ARM_DAC":
                    writeValOfReg+=vt1bump
                if writeValOfReg != readBackVal:
                    printRed("VFAT%i: %s mismatch, write val = %i, readback = %i"%(vfat, regName, writeValOfReg, readBackVal))

    return
Ejemplo n.º 9
0
def configure(args, vfatBoard):
    """
    Configures the front-end detector

    args - namespace returned by ArgumentParser::parse_args(), expects to contain following fields:

        applyMasks  - If True channel masks in chConfig will be applied
        chConfig    - Text file containing the channel configuration register information
        compare     - If True only compares provided config file(s) with currently loaded parameters in frontend, does not write
        debug       - Prints additional debugging information
        filename    - TFile containing the scurveFitTree, used in writing channel registers
        run         - Places front-end ASIC into run mode if true
        vt1         - For V3 (V2) electronics this is CFG_THR_ARM_DAC (VThreshold1) value to write
        vt1bump     - Adds this value to the CFG_THR_ARM_DAC or VThreshold1 value that will be written
        vt2         - For V3 (V2) electronics this is not used (VThreshold2 value to write)
        vfatConfig  - For V3 (V2) electronics contains CFG_THR_ARM_DAC (VThreshold1 & trimRange) values to write per VFAT
        vfatmask    - 24 bit number specifying which vfats to mask, a 1 in the N^th bit means ignore that vfat
        zeroChan    - Sets all bits of all channel registers to 0

    vfatBoard - An instance of HwVFAT class
    """

    shelf   = vfatBoard.parentOH.parentAMC.getShelf()
    slot    = vfatBoard.parentOH.parentAMC.getSlot()
    ohN     = vfatBoard.parentOH.link

    ohKey = (shelf,slot,ohN)

    from gempython.gemplotting.mapping.chamberInfo import chamber_vfatDACSettings
    if ohKey in chamber_vfatDACSettings.keys():
        print "Configuring VFATs on (shelf{0}, slot{1}, OH{2}) with chamber_vfatDACSettings dictionary values".format(shelf,slot,ohN)
        for key in chamber_vfatDACSettings[ohKey]:
            vfatBoard.paramsDefVals[key] = chamber_vfatDACSettings[ohKey][key]
    vfatBoard.biasAllVFATs(args.vfatmask)
    print 'biased VFATs on (shelf{0}, slot{1}, OH{2})'.format(shelf,slot,ohN)
    
    if not args.compare:
        vfatBoard.setVFATThresholdAll(args.vfatmask, args.vt1, args.vt2)
        if vfatBoard.parentOH.parentAMC.fwVersion > 2:
            print('Set CFG_THR_ARM_DAC to %i'%args.vt1)
        else:
            print('Set VThreshold1 to %i'%args.vt1)
            print('Set VThreshold2 to %i'%args.vt2)
    
    if args.run:
        vfatBoard.setRunModeAll(args.vfatmask, True)
        print 'VFATs on (shelf{0}, slot{1}, OH{2}) set to run mode'.format(shelf,slot,ohN)
    else:
        vfatBoard.setRunModeAll(args.vfatmask, False)
    
    import ROOT as r
    if args.filename:
        try:
            inF = r.TFile(args.filename)
            chTree = inF.Get("scurveFitTree")
            if not args.compare:
                print 'Configuring Channel Registers on (shelf{0}, slot{1}, OH{2}) based on {3}'.format(shelf,slot,ohN, args.filename)
                setChannelRegisters(vfatBoard, chTree, args.vfatmask, args.applyMasks)

            dict_readBack = {}
            if vfatBoard.parentOH.parentAMC.fwVersion > 2:
                dict_readBack = { "trimDAC":"VFAT_CHANNELS.CHANNEL", "trimPolarity":"VFAT_CHANNELS.CHANNEL", "vfatID":"HW_CHIP_ID" }
                if args.applyMasks:
                    dict_readBack["mask"]="VFAT_CHANNELS.CHANNEL"

                print 'Comparing Currently Stored Channel Registers with %s'%args.chConfig
                readBackCheckV3(chTree, dict_readBack, vfatBoard, args.vfatmask)
    
        except IOError as e:
            printRed( '%s does not seem to exist'%args.filename )
            printRed( e )
            exit(os.EX_IOERR)
    
    if args.chConfig:
        try:
            chTree = r.TTree('chTree','Tree holding Channel Configuration Parameters')
            chTree.ReadFile(args.chConfig)
            if not args.compare:
                print 'Configuring Channel Registers on (shelf{0}, slot{1}, OH{2}) based on {3}'.format(shelf,slot,ohN,args.chConfig)
                setChannelRegisters(vfatBoard, chTree, args.vfatmask, args.applyMasks)

            dict_readBack = {}
            if vfatBoard.parentOH.parentAMC.fwVersion > 2:
                dict_readBack = { "trimDAC":"VFAT_CHANNELS.CHANNEL", "trimPolarity":"VFAT_CHANNELS.CHANNEL", "vfatID":"HW_CHIP_ID" }
                if args.applyMasks:
                    dict_readBack["mask"]="VFAT_CHANNELS.CHANNEL"
                print 'Comparing Currently Stored Channel Registers on (shelf{0}, slot{1}, OH{2}) with {3}'.format(shelf,slot,ohN,args.chConfig)
                readBackCheckV3(chTree, dict_readBack, vfatBoard, args.vfatmask)
    
        except IOError as e:
            printRed( '%s does not seem to exist'%args.filename )
            printRed( e )
            exit(os.EX_IOERR)
    
    if args.zeroChan:    
        print("zero'ing all channel registers on (shelf{0}, slot{1}, OH{2})".format(shelf,slot,ohN))
        rpcResp = vfatBoard.setAllChannelRegisters(vfatMask=args.vfatmask)
                    
        if rpcResp != 0:
            raise Exception("{0}RPC response was non-zero, zero'ing all channel registers failed{1}".format(colors.RED,colors.ENDC))
        pass
    
    if args.vfatConfig:
        try:
            vfatTree = r.TTree('vfatTree','Tree holding VFAT Configuration Parameters')
            vfatTree.ReadFile(args.vfatConfig)
    
            if not args.compare:
                print 'Configuring VFAT Registers on (shelf{0}, slot{1}, OH{2}) based on {3}'.format(shelf,slot,ohN,args.vfatConfig)
    
                for event in vfatTree :
                    # Skip masked vfats
                    if (args.vfatmask >> int(event.vfatN)) & 0x1:
                        continue
                    
                    # Tell user whether CFG_THR_ARM_DAC or VThreshold1 is being written
                    if vfatBoard.parentOH.parentAMC.fwVersion > 2:
                        print 'Set link %d VFAT%d CFG_THR_ARM_DAC to %i'%(ohN,event.vfatN,event.vt1+args.vt1bump)
                    else:
                        print 'Set link %d VFAT%d VThreshold1 to %i'%(ohN,event.vfatN,event.vt1+args.vt1bump)
                    
                    # Write CFG_THR_ARM_DAC or VThreshold1
                    vfatBoard.setVFATThreshold(chip=int(event.vfatN), vt1=int(event.vt1+args.vt1bump))
    
                    # Write trimRange (only supported for v2b electronics right now)
                    if not (vfatBoard.parentOH.parentAMC.fwVersion > 2):
                        vfatBoard.writeVFAT(int(event.vfatN), "ContReg3", int(event.trimRange),args.debug)
            
            if vfatBoard.parentOH.parentAMC.fwVersion > 2:
                print 'Comparing Curently Stored VFAT Registers on (shelf{0}, slot{1}, OH{2}) with {3}'.format(shelf,slot,ohN,args.vfatConfig)
                #dict_readBack = { "vfatID":"HW_CHIP_ID", "vt1":"CFG_THR_ARM_DAC" } # Future refactoring of gemplotting will include this
                dict_readBack = { "vt1":"CFG_THR_ARM_DAC" }
                readBackCheckV3(vfatTree, dict_readBack, vfatBoard, args.vfatmask, args.vt1bump)
    
        except IOError as e:
            printRed( '%s does not seem to exist'%args.filename )
            printRed( e )
            exit(os.EX_IOERR)
            pass
        pass

    return
Ejemplo n.º 10
0
            sbitSize[0] = ((word >> 11) & 0x7)
            chHitPerCluster[0] = 2*(sbitSize[0]+1)
            L1Delay[0] = ((word >> 14) & 0xFFF)
            eta = vfat_to_etaphi[vfatN[0]][0]
            phi = vfat_to_etaphi[vfatN[0]][1]
            
            # SBIT always includes doublet of adjacent channels
            vfatCH[0] = 2*(sbitAddr % 64)
            vfatCH[1] = vfatCH[0] + 1
            strip[0] = vfat_ch_strips[vfatN[0]]['Strip'][vfatCH[0]]
            strip[1] = vfat_ch_strips[vfatN[0]]['Strip'][vfatCH[1]]

            # In case of wrong mapping adjacent channels may not be adjacent strips, which is physically inconsistent
            if(np.abs(strip[0] - strip[1]) > 1):
                if args.debug:
                    printRed("WARNING: not adjacent strips")

            # filling vfat 1Dhistos
            vfat_h_strip[vfatN[0]].Fill(strip[0])
            vfat_h_strip[vfatN[0]].Fill(strip[1])
            vfat_h_ch[vfatN[0]].Fill(vfatCH[0])
            vfat_h_ch[vfatN[0]].Fill(vfatCH[1])
            vfat_h_delay[vfatN[0]].Fill(L1Delay[0])
            vfat_h_sbitSize[vfatN[0]].Fill(sbitSize[0])

            # filling ieta 1Dhistos
            ieta_h_strip[eta].Fill((phi-1)*maxChans+strip[0])
            ieta_h_strip[eta].Fill((phi-1)*maxChans+strip[1])
            ieta_h_ch[eta].Fill((phi-1)*maxChans+vfatCH[0])
            ieta_h_ch[eta].Fill((phi-1)*maxChans+vfatCH[1])
            ieta_h_delay[eta].Fill(L1Delay[0])
Ejemplo n.º 11
0
def readBackCheck(rootTree, dict_Names, device, gtx, vt1bump=0):
    """
    Given an input set of registers, and expected values of those registers, read from all VFATs on device.gtx to see if there are any differences between written and read values.

    rootTree - name of a TTree that has values that should have been written
    dict_Names - dictionary where key names are the branch names in rootTree and the values are the register names they correspond too
    device - optohybrid the vfats belong to that you want to check
    gtx - link of this optohybrid
    """
    
    import numpy as np
    import root_numpy as rp
    import sys
    
    # Check that the requested register is supported
    list_KnownRegs = parameters.defaultValues.keys()
    list_KnownRegs.append("VThreshold1")
    list_KnownRegs.append("VFATChannels.ChanReg")
    list_KnownRegs.append("ChipID")
    for regName in dict_Names.values():
        if regName not in list_KnownRegs:
            raise Exception("{2}readBackCheck() does not understand {0}; only supported for registers: {1}{3}".format(regName, list_KnownRegs,colors.RED,colors.ENDC),os.EX_USAGE)

    # Get data from tree
    list_bNames = dict_Names.keys()
    list_bNames.append('vfatN')
    list_bNames.append('vfatID')
    if "trimDAC" in dict_Names.keys() or "mask" in dict_Names.keys():
        list_bNames.append('vfatCH')
    array_writeVals = rp.tree2array(tree=rootTree, branches=list_bNames)

    # Get data from VFATs
    perreg   = "0x%02x"
    for bName,regName in dict_Names.iteritems():
        printBlue("Reading back (%s,%s) from all VFATs, any potential mismatches will be reported below"%(bName,regName))
        print "="*40
        
        regMap = []
        regValues = []
        if regName == "VFATChannels.ChanReg": #Channel Register, use 0x1f
            for chan in range(0,128):
                regValues = readAllVFATs(device, gtx, regName+"%d"%(chan), 0x0)
                #regMap = map(lambda chip: chip&0x1f, regValues)
                
                for vfat,readBackVal in enumerate(regValues):
                    writeValsPerVFAT = array_writeVals[ array_writeVals['vfatN'] == vfat]
                    writeValsPerVFAT = writeValsPerVFAT[ writeValsPerVFAT['vfatCH'] == chan]
                    writeValOfReg = np.asscalar(writeValsPerVFAT['%s'%bName]) 
                    if bName == "mask":
                        if writeValOfReg != ((readBackVal&0x20)%31): #trimDAC goes from 0 -> 31, leftover is mask
                            printRed("VFAT%i Chan%i: %s mismatch, write val = %i, readback = %i"%(vfat, chan, bName, writeValOfReg, (readBackVal&0x20)%31))
                    else:
                        if writeValOfReg != (readBackVal&0x1f):
                            printRed("VFAT%i Chan%i: %s mismatch, write val = %i, readback = %i"%(vfat, chan, bName, writeValOfReg, readBackVal&0x1f))
        elif regName == "ChipID": #ChipID
            regValues = getAllChipIDs(device, gtx, 0x0) # dict of { vfatN:chipID }
            for vfat in regValues:
                valsPerVFAT = array_writeVals[ array_writeVals['vfatN'] == vfat]
                valOfReg = int(np.asscalar(np.unique(valsPerVFAT['%s'%bName])))
                if valOfReg != regValues[vfat]:
                    printRed("VFAT%i: %s mismatch, expected = %s, readback = %s"%(vfat, regName, hex(valOfReg), hex(regValues[vfat])))
        else: #VFAT Register, use 0xff
            regValues = readAllVFATs(device, gtx, regName, 0x0)
            regMap = map(lambda chip: chip&0xff, regValues)

            for vfat,readBackVal in enumerate(regMap):
                writeValsPerVFAT = array_writeVals[ array_writeVals['vfatN'] == vfat]
                writeValOfReg = np.asscalar(writeValsPerVFAT['%s'%bName])
                if regName == "VThreshold1":
                    writeValOfReg+=vt1bump
                if writeValOfReg != readBackVal:
                    printRed("VFAT%i: %s mismatch, write val = %i, readback = %i"%(vfat, regName, writeValOfReg, readBackVal))

    return
Ejemplo n.º 12
0
    if args.zeroChan:
        configType |= 0x8
        pass

    # consider only the shelf of interest
    from gempython.gemplotting.mapping.chamberInfo import chamber_config
    chambers2Configure = {}
    for ohKey, cName in chamber_config.iteritems():
        if args.shelf == ohKey[0]:
            chambers2Configure[ohKey] = cName
            pass
        pass

    from gempython.utils.gemlogger import printRed
    if (len(chambers2Configure) == 0):
        printRed("No chambers for shelf{0} exist".format(args.shelf))
        printRed("Nothing to do, exiting")
        exit(os.EX_USAGE)

    import itertools
    if args.debug:
        print list(
            itertools.izip([ohKey[0] for ohKey in chambers2Configure],
                           [ohKey[1] for ohKey in chambers2Configure],
                           [ohKey[2] for ohKey in chambers2Configure],
                           [args.run for ohKey in chambers2Configure],
                           [args.armDAC for ohKey in chambers2Configure],
                           [args.armDACBump for ohKey in chambers2Configure],
                           [configType for ohKey in chambers2Configure], [
                               chambers2Configure[ohKey]
                               for ohKey in chambers2Configure.keys()
Ejemplo n.º 13
0
    from gempython.gemplotting.utils.threshAlgos import calibrateThrDAC
    from gempython.utils.gemlogger import printGreen, printRed
    from gempython.utils.wrappers import runCommand
    from gempython.gemplotting.utils.namespace import Namespace
    import os, sys, traceback
    ns = Namespace(inputFile=args.inputFile,
                   fitRange=args.fitRange,
                   listOfVFATs=args.listOfVFATs,
                   maxEffPedPercent=args.maxEffPedPercent,
                   highNoiseCut=args.highNoiseCut,
                   deadChanCutLow=args.deadChanCutLow,
                   deadChanCutHigh=args.deadChanCutHigh,
                   noLeg=args.noLeg,
                   outputDir=outputDir,
                   savePlots=args.savePlots,
                   debug=args.debug)

    try:
        retCode = calibrateThrDAC(ns)
    except IOError as err:
        printRed("IOError: {0}".format(err.message))
        printRed("Analysis failed with error code {0}".format(retCode))
        traceback.print_exc(file=sys.stdout)
        sys.exit(os.EX_IOERR)
    else:
        printGreen("Analysis completed successfully")
    finally:
        from gempython.gemplotting.utils.anautilities import cleanup
        cleanup([outputDir])
Ejemplo n.º 14
0
    args = parser.parse_args()

    from gempython.gemplotting.utils.anautilities import getDataPath
    dataPath = getDataPath()

    import logging
    from gempython.utils.gemlogger import getGEMLogger
    gemlogger = getGEMLogger(__name__)
    gemlogger.setLevel(logging.ERROR)

    import os, sys
    from gempython.gemplotting.mapping.chamberInfo import chamber_config
    from gempython.utils.wrappers import runCommand
    if args.chConfigScandate is None and args.vfatConfigScandate is None:
        printRed(
            "No scandates provided for either chConfig or vfatConfig. Nothing to do, exiting"
        )
        sys.exit(os.EX_USAGE)
    if args.chConfigScandate is not None:
        chConfigDict = getChConfigFileDict(chamber_config,
                                           args.chConfigScandate, args.debug,
                                           not args.updatedChConfig,
                                           args.trimChConfig)
        for cName, chConfig in chConfigDict.iteritems():
            cmd = [
                "ln", "-sf", chConfig,
                "{}/configs/chConfig_{}.txt".format(dataPath, cName)
            ]
            runCommand(cmd)
            pass
        pass
    # Make output directory
    from gempython.utils.wrappers import runCommand
    filePath = args.infilename.replace('.root', '')
    runCommand(["mkdir", "-p", "{0}".format(filePath)])
    runCommand(["chmod", "g+rw", "{0}".format(filePath)])

    # Run Analysis
    from gempython.utils.gemlogger import printRed
    import os, sys, traceback
    try:
        args.func(infilename=args.infilename,
                  debug=args.debug,
                  latSigMaskRange=args.latSigMaskRange,
                  latSigRange=args.latSigRange,
                  outputDir=filePath,
                  outfilename=args.outfilename,
                  performFit=args.performFit)
    except IndexError as err:
        printRed("IndexError: {0}".format(err.message))
        traceback.print_exc(file=sys.stdout)
        sys.exit(os.EX_SOFTWARE)
    except IOError as err:
        printRed("IOError: {0}".format(err.message))
        traceback.print_exc(file=sys.stdout)
        sys.exit(os.EX_IOERR)
    else:
        print('Analysis Completed Successfully')
    finally:
        from gempython.gemplotting.utils.anautilities import cleanup
        cleanup([filePath])
Ejemplo n.º 16
0
    args = parser.parse_args()

    # Load the input file
    import ROOT as r
    inF = r.TFile(args.inputfile,"READ")

    # Set default histogram behavior
    r.TH1.SetDefaultSumw2(False)
    r.gROOT.SetBatch(True)
    r.gStyle.SetOptStat(1111111)

    # Check if file loaded okay
    from gempython.utils.gemlogger import colors, printGreen, printRed, printYellow
    import os
    if not inF.IsOpen() or inF.IsZombie():
        printRed("File {0} did not load properly, exiting".format(args.inputfile))
        exit(os.EX_IOERR)
        pass

    # Determine layer
    if args.allLayers:
        plotTimeSeriesHV(args,"Top")
        args.update=True
        plotTimeSeriesHV(args,"Bot")
    elif args.bot:
        plotTimeSeriesHV(args,"Bot")
    elif args.top:
        plotTimeSeriesHV(args,"Top")
        pass

    print("Goodbye")