Ejemplo n.º 1
0
def sbitRateScanAllLinks(args,
                         rateTree,
                         vfatBoard,
                         chan=128,
                         scanReg="CFG_THR_ARM_DAC"):
    """
    Measures the rate of sbits from all VFATs on all unmasked optohybrids against an arbitrary register

    args - parsed arguments from an ArgumentParser instance
    rateTree - instance of gemSbitRateTreeStructure
    vfatBoard - instance of HwVFAT
    chan - VFAT channel to be scanned, if 128 is supplied the OR of all channels will be taken
    scanReg - Name of the VFAT register to scan against
    """

    nVFATs = vfatBoard.parentOH.nVFATs

    # Check to make sure required parameters exist, if not provide a default
    if hasattr(args, 'debug') is False:  # debug
        args.debug = False
    if hasattr(args, 'ohMask') is False:  # ohMask
        args.ohMask = 0xfff
    if hasattr(args, 'perchannel') is False:  # Channel scan?
        args.perchannel = False
    if hasattr(args, 'scanmax') is False:  # scanmax
        args.scanmax = 255
    if hasattr(args, 'scanmin') is False:  # scanmin
        args.scanmin = 0
    if hasattr(args, 'stepSize') is False:  # stepSize
        args.stepSize = 0

    # Remove the leading "CFG_" since this is not expected by the RPC module
    if "CFG_" in scanReg:
        scanReg = scanReg.replace("CFG_", "")
        pass

    # Get the AMC
    amcBoard = vfatBoard.parentOH.parentAMC

    # Determine the per OH vfatmask
    ohVFATMaskArray = amcBoard.getMultiLinkVFATMask(args.ohMask)
    if args.debug:
        for ohN in range(0, amcBoard.nOHs):
            # Skip masked OH's
            if (not ((args.ohMask >> ohN) & 0x1)):
                continue

            print("vfatMask for OH{0} is 0x{1:x}".format(
                ohN, ohVFATMaskArray[ohN]))
            pass
        pass

    #print("Getting CHIP IDs of all VFATs")
    vfatIDvals = {}
    selCompVals_orig = {}
    forceEnZCCVals_orig = {}
    for ohN in range(0, amcBoard.nOHs):
        # Skip masked OH's
        if (not ((args.ohMask >> ohN) & 0x1)):
            continue

        # update the OH in question
        vfatBoard.parentOH.link = ohN

        # Get the chip ID's
        vfatIDvals[ohN] = vfatBoard.getAllChipIDs(ohVFATMaskArray[ohN])

        #Place chips into run mode
        vfatBoard.setRunModeAll(ohVFATMaskArray[ohN], True, args.debug)

        #Store original CFG_SEL_COMP_MODE
        vals = vfatBoard.readAllVFATs("CFG_SEL_COMP_MODE",
                                      ohVFATMaskArray[ohN])
        selCompVals_orig[ohN] = dict(
            map(lambda slotID: (slotID, vals[slotID] & 0xff), range(0,
                                                                    nVFATs)))

        #Store original CFG_FORCE_EN_ZCC
        vals = vfatBoard.readAllVFATs("CFG_FORCE_EN_ZCC", ohVFATMaskArray[ohN])
        forceEnZCCVals_orig[ohN] = dict(
            map(lambda slotID: (slotID, vals[slotID] & 0xff), range(0,
                                                                    nVFATs)))
        pass

    # Make the containers
    nDACValues = (args.scanmax - args.scanmin + 1) / args.stepSize
    arraySize = 12 * nDACValues
    scanDataDAC = (c_uint32 * arraySize)()
    scanDataRate = (c_uint32 * arraySize)()
    scanDataRatePerVFAT = (c_uint32 * (nVFATs * arraySize))()  # per VFAT

    # Perform SBIT Rate Scan vs. scanReg
    if chan == 128:
        strChannels = "(OR of all channels per VFAT)"
    else:
        strChannels = "(only from channel {0} for each VFAT)".format(chan)
        pass
    print("scanning {0} for all VFATs in ohMask 0x{1:x} {2}".format(
        scanReg, args.ohMask, strChannels))
    rpcResp = amcBoard.performSBITRateScanMultiLink(
        scanDataDAC,
        scanDataRate,  #this is actually a rate i.e. it has units of Hz
        scanDataRatePerVFAT,  #this is actually not a rate - it is an integrated count
        chan=chan,
        dacMin=args.scanmin,
        dacMax=args.scanmax,
        dacStep=args.stepSize,
        ohMask=args.ohMask,
        scanReg=scanReg,
        waitTime=args.waitTime)

    if rpcResp != 0:
        raise Exception('RPC response was non-zero, sbit rate scan failed')

    # place holder
    if args.debug:
        print(
            "| detName | link | vfatN | vfatID | vfatCH | nameX | dacValX | rate |"
        )
        print(
            "| :-----: | :--: | :---: | :----: | :----: | :---: | :-----: | :--: |"
        )
    for ohN in range(0, amcBoard.nOHs):
        # Skip masked OH's
        if (not ((args.ohMask >> ohN) & 0x1)):
            continue

        # Fill per VFAT rate
        for vfat in range(0, nVFATs):
            # Skip masked VFATs
            if ((ohVFATMaskArray[ohN] >> vfat) & 0x1):
                continue

            for dacVal in range(args.scanmin, args.scanmax + 1, args.stepSize):
                idxVFAT = ohN * nVFATs * nDACValues + vfat * nDACValues + (
                    dacVal - args.scanmin) / args.stepSize
                idxDAC = ohN * nDACValues + (dacVal -
                                             args.scanmin) / args.stepSize
                rateTree.fill(
                    dacValX=scanDataDAC[idxDAC],
                    detName=chamber_config[(amcBoard.getShelf(),
                                            amcBoard.getSlot(), ohN)],
                    link=ohN,
                    nameX=scanReg,
                    #as mentioned above, scanDataRatePerVFAT is actually a count, unlike scanDateRate which is already a rate
                    rate=scanDataRatePerVFAT[idxVFAT] / float(args.waitTime),
                    shelf=amcBoard.getShelf(),
                    slot=amcBoard.getSlot(),
                    vfatCH=chan,
                    vfatID=vfatIDvals[ohN][vfat],
                    vfatN=vfat)
                if args.debug:
                    print(
                        "| {0} | {1} | {2} | 0x{3:x} | {4} | {5} | {6} | {7} |"
                        .format(rateTree.detName[0], rateTree.link[0],
                                rateTree.vfatN[0], rateTree.vfatID[0],
                                rateTree.vfatCH[0], rateTree.nameX[0],
                                rateTree.dacValX[0], rateTree.rate[0]))
                    pass
                pass
            pass

        # Fill overall rate
        for dacVal in range(args.scanmin, args.scanmax + 1, args.stepSize):
            idxDAC = ohN * nDACValues + (dacVal - args.scanmin) / args.stepSize
            rateTree.fill(
                dacValX=scanDataDAC[idxDAC],
                detName=chamber_config[(amcBoard.getShelf(),
                                        amcBoard.getSlot(), ohN)],
                link=ohN,
                nameX=scanReg,
                #as mentioned above, scanDataRate is already a rate, unlike scanDataRatePerVFAT which is actually a count
                rate=scanDataRate[idxDAC],
                shelf=amcBoard.getShelf(),
                slot=amcBoard.getSlot(),
                vfatCH=chan,
                vfatID=0xdead,
                vfatN=nVFATs)
            if args.debug:
                print("| {0} | {1} | {2} | 0x{3:x} | {4} | {5} | {6} | {7} |".
                      format(rateTree.detName[0], rateTree.link[0],
                             rateTree.vfatN[0], rateTree.vfatID[0],
                             rateTree.vfatCH[0], rateTree.nameX[0],
                             rateTree.dacValX[0], rateTree.rate[0]))
                pass
            pass
        pass

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

        # update the OH in question
        vfatBoard.parentOH.link = ohN

        #Place chips into run mode
        vfatBoard.setRunModeAll(ohVFATMaskArray[ohN], False, args.debug)
        pass

    printGreen(
        "SBIT Rate scan vs. {0} for optohybrids in 0x{1:x} {2} completed".
        format(scanReg, args.ohMask, strChannels))

    return
Ejemplo n.º 2
0
def dacScanAllLinks(args, calTree, vfatBoard):
    """
    Performs a DAC scan on all VFATs on all unmasked OH's on amcBoard

    args - parsed arguments from an ArgumentParser instance
    calTree - instance of gemDacCalTreeStructure
    vfatBoard - instance of HwVFAT
    """

    # Get the AMC
    amcBoard = vfatBoard.parentOH.parentAMC
    nVFATs = vfatBoard.parentOH.nVFATs

    # Get DAC value
    dacSelect = args.dacSelect
    dacMax = maxVfat3DACSize[dacSelect][0]
    dacMin = 0
    calTree.nameX[0] = maxVfat3DACSize[dacSelect][1]
    calTree.dacSelect[0] = dacSelect

    # Get VFAT register values
    from gempython.utils.nesteddict import nesteddict as ndict
    ohVFATMaskArray = amcBoard.getMultiLinkVFATMask(args.ohMask)
    print("Getting CHIP IDs of all VFATs")
    vfatIDvals = ndict()
    irefVals = ndict()
    calSelPolVals = ndict()
    for ohN in range(0, amcBoard.nOHs):
        # Skip masked OH's
        if (not ((args.ohMask >> ohN) & 0x1)):
            calSelPolVals[ohN] = [0 for vfat in range(0, nVFATs)]
            irefVals[ohN] = [0 for vfat in range(0, nVFATs)]
            vfatIDvals[ohN] = [0 for vfat in range(0, nVFATs)]
        else:
            # update the OH in question
            vfatBoard.parentOH.link = ohN

            # Get the cal sel polarity
            calSelPolVals[ohN] = vfatBoard.readAllVFATs(
                "CFG_CAL_SEL_POL", ohVFATMaskArray[ohN])

            # Get the IREF values
            irefVals[ohN] = vfatBoard.readAllVFATs("CFG_IREF",
                                                   ohVFATMaskArray[ohN])

            # Get the chip ID's
            vfatIDvals[ohN] = vfatBoard.getAllChipIDs(ohVFATMaskArray[ohN])

    # Perform DAC Scan
    arraySize = amcBoard.nOHs * (dacMax - dacMin + 1) * nVFATs / args.stepSize
    scanData = (c_uint32 * arraySize)()
    print("Scanning DAC: {0} on all links".format(
        maxVfat3DACSize[dacSelect][1]))
    rpcResp = amcBoard.performDacScanMultiLink(scanData, dacSelect,
                                               args.stepSize, args.ohMask,
                                               args.extRefADC)
    if rpcResp != 0:
        raise Exception(
            'RPC response was non-zero, this inidcates an RPC exception occurred. DAC Scan of all links failed'
        )

    #try:
    if args.debug:
        print(
            "| detName | link | vfatN | vfatID | dacSelect | nameX | dacValX | dacValX_Err | nameY | dacValY | dacValY_Err |"
        )
        print(
            "| :-----: | :--: | :---: | :----: | :-------: |:-----: | :-----: | :---------: | :--: | :-----: | :---------: |"
        )
    for dacWord in scanData:
        # Get OH and skip if not in args.ohMask
        ohN = ((dacWord >> 23) & 0xf)
        if (not ((args.ohMask >> ohN) & 0x1)):
            continue

        # Get VFAT and skip if in ohVFATMaskArray[ohN]
        vfat = ((dacWord >> 18) & 0x1f)
        if ((ohVFATMaskArray[ohN] >> vfat) & 0x1):
            continue

        calTree.fill(
            calSelPol=calSelPolVals[ohN][vfat],
            dacValX=(dacWord & 0xff),
            dacValY=((dacWord >> 8) & 0x3ff),
            dacValY_Err=
            1,  # convert to physical units in analysis, LSB is the error on Y
            iref=irefVals[ohN][vfat],
            detName=chamber_config[(amcBoard.getShelf(), amcBoard.getSlot(),
                                    ohN)],
            link=ohN,
            shelf=amcBoard.getShelf(),
            slot=amcBoard.getSlot(),
            vfatID=vfatIDvals[ohN][vfat],
            vfatN=vfat)
        if args.debug:
            print(
                "| {0} | {1} | {2} | 0x{3:x} | {4} | {5} | {6} | {7} | {8} | {9} | {10} |"
                .format(calTree.detName[0], calTree.link[0], calTree.vfatN[0],
                        calTree.vfatID[0], calTree.dacSelect[0],
                        calTree.nameX[0], calTree.dacValX[0],
                        calTree.dacValX_Err[0], calTree.nameY[0],
                        calTree.dacValY[0], calTree.dacValY_Err[0]))
        pass

    printGreen("DAC scans for optohybrids in 0x{0:x} completed".format(
        args.ohMask))

    return
Ejemplo n.º 3
0
def dacScanSingleLink(args, calTree, vfatBoard):
    """
    Performs a DAC scan for the VFATs on the OH that vfatBoard.parentOH corresponds too

    args - parsed arguments from an ArgumentParser instance
    calTree - instance of gemDacCalTreeStructure
    vfatBoard - instace of HwVFAT
    """

    # Get the AMC
    amcBoard = vfatBoard.parentOH.parentAMC

    nVFATs = vfatBoard.parentOH.nVFATs

    # Get DAC value
    dacSelect = args.dacSelect
    dacMax = maxVfat3DACSize[dacSelect][0]
    dacMin = 0
    calTree.nameX[0] = maxVfat3DACSize[dacSelect][1]
    calTree.dacSelect[0] = dacSelect,

    # Determine VFAT mask
    if args.vfatmask is None:
        args.vfatmask = vfatBoard.parentOH.getVFATMask()
        if args.debug:
            print("Automatically determined vfatmask to be: {0}".format(
                str(hex(args.vfatmask)).strip('L')))

    # Get the cal sel polarity
    print("Getting Calibration Select Polarity of all VFATs")
    calSelPolVals = vfatBoard.readAllVFATs("CFG_CAL_SEL_POL", args.vfatmask)

    # Get the IREF values
    print("Getting IREF of all VFATs")
    irefVals = vfatBoard.readAllVFATs("CFG_IREF", args.vfatmask)

    # Determine Chip ID
    print("Getting CHIP IDs of all VFATs")
    vfatIDvals = vfatBoard.getAllChipIDs(args.vfatmask)

    # Perform DAC Scan
    arraySize = (dacMax - dacMin + 1) * nVFATs / args.stepSize
    scanData = (c_uint32 * arraySize)()
    print("Scanning DAC {0} on Optohybrid {1}".format(
        maxVfat3DACSize[dacSelect][1], vfatBoard.parentOH.link))
    rpcResp = vfatBoard.parentOH.performDacScan(scanData, dacSelect,
                                                args.stepSize, args.vfatmask,
                                                args.extRefADC)
    if rpcResp != 0:
        raise Exception(
            'RPC response was non-zero, this inidcates an RPC exception occurred.  DAC Scan of OH{0} Failed'
            .format(vfatBoard.parentOH.link))

    # Store Data
    calTree.shelf[0] = amcBoard.getShelf()
    calTree.slot[0] = amcBoard.getSlot()
    calTree.link[0] = vfatBoard.parentOH.link

    #try:
    if args.debug:
        print(
            "| detName | link | vfatN | vfatID | dacSelect | nameX | dacValX | dacValX_Err | nameY | dacValY | dacValY_Err |"
        )
        print(
            "| :-----: | :--: | :---: | :----: | :-------: | :-----: | :-----: | :---------: | :--: | :-----: | :---------: |"
        )
    for dacWord in scanData:
        vfat = (dacWord >> 18) & 0x1f
        calTree.fill(
            calSelPol=calSelPolVals[vfat],
            dacValX=(dacWord & 0xff),
            dacValY=((dacWord >> 8) & 0x3ff),
            dacValY_Err=
            1,  # convert to physical units in analysis, LSB is the error on Y
            iref=irefVals[vfat],
            vfatID=vfatIDvals[vfat],
            vfatN=vfat)
        if args.debug:
            print(
                "| {0} | {1} | {2} | 0x{3:x} | {4} | {5} | {6} | {7} | {8} | {9} |"
                .format(calTree.detName[0], calTree.link[0], calTree.vfatN[0],
                        calTree.vfatID[0], calTree.dacSelect[0],
                        calTree.nameX[0], calTree.dacValX[0],
                        calTree.dacValX_Err[0], calTree.nameY[0],
                        calTree.dacValY[0], calTree.dacValY_Err[0]))
        pass

    printGreen("DAC scan for optohybrid {0} completed".format(
        vfatBoard.parentOH.link))

    return
Ejemplo n.º 4
0
==========

.. moduleauthor:: Brian Dorney <*****@*****.**>
"""

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(
        description="Arguments to supply to dump2csv.py")

    parser.add_argument("infilename",
                        type=str,
                        help="Input ROOT file to be dumped to CSV")
    args = parser.parse_args()

    import root_numpy as rp
    import pandas as pd

    # Get the data
    dataArray = rp.root2array(filenames=args.infilename)
    dfData = pd.DataFrame(dataArray)

    # write to csv file
    outFileName = args.infilename.replace(".root", ".csv")
    print("Writing data contained in {:s} to CSV Format".format(
        args.infilename))
    dfData.to_csv(path_or_buf=outFileName, index=False, mode='w')

    from gempython.utils.gemlogger import printGreen
    printGreen("Your data is available at:\n\t{:s}".format(outFileName))
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
                                           dtype=np.uint8)

                if args.debug:
                    pd.options.display.max_rows = 128
                    dfTrimCalculation = pd.DataFrame()
                    dfTrimCalculation['vfatCH'] = [x for x in range(128)]
                    dfTrimCalculation['threshold'] = scurveFitResults[ohN][0][
                        vfat]
                    dfTrimCalculation['lastTrimDACs'] = lastTrimDACs
                    dfTrimCalculation['lastTrimPols'] = lastTrimPols
                    dfTrimCalculation['trimDeltas'] = trimDeltas
                    dfTrimCalculation['currentTrimDACs'] = currentTrimDACs
                    dfTrimCalculation['currentTrimPols'] = currentTrimPols

                    printGreen(
                        "=" * 50 +
                        "VFAT{:d}: Iteration {:d}".format(vfat, iterNum) +
                        "=" * 50)
                    print("avgScurveMean = {}".format(avgScurveMean))
                    print("cal_dacm = {}".format(tuple_calInfo[0][vfat]))
                    print("cal_dacb = {}".format(tuple_calInfo[1][vfat]))
                    print("n_trimmed = {}".format(n_trimmed))
                    print(dfTrimCalculation)
                    pass

                # Ensure no |trimDAC| is greater than 63
                currentTrimDACs = np.abs(currentTrimDACs)
                currentTrimDACs[currentTrimDACs > 63] = 63

                # Store this updated info
                dict_chanRegArray[iterNum][ohN]["ARM_TRIM_POLARITY"][
                    vfat * 128:(vfat + 1) * 128] = currentTrimPols
Ejemplo n.º 7
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])