Ejemplo n.º 1
0
def command(p, cmd, timeout=5):
    fields = cmd.split()
    if not fields:
        return None

    if fields[0] == "jtag":
        if len(fields) < 4:
            print("COMMAND has to few fields: (%s)" % cmd)
            return None

        regexp = "(.*)%s %s %s# retcode=(.*)" % tuple(fields[1:])
    else:
        regexp = "{0}\s?#((\s|E)[^\r^\n]*)".format(re.escape(cmd))

    try:
        p.sendline(cmd)
        p.expect(regexp, timeout=timeout)
        return p.match.group(0).split("\r\n")
    except pexpect.TIMEOUT:
        tail = "tail -20 %s" % p.logfile.name

        msg = printer.msg('The command "', p=False)
        msg += printer.cyan(cmd, p=False)
        msg += printer.msg(
            '"\n       produced unexpected output.  Consult the log file, e.g.',
            p=False)
        msg += printer.msg('\n       "%s" gives this:' %
                           printer.gray(tail, p=False),
                           p=False)
        printer.error(msg)
        os.system(tail)
        sys.exit()
Ejemplo n.º 2
0
def inner_vars(outer, inner, mapOptions, oMapF, oMapB, oMapBcn):
    if inner:
        chainI = raw.tchain(inner)
        iMapF, iMapB, iMapBcn = eventMaps(chainI, inner)
        if mapOptions["identityMap"]:
            iMapF = oMapF
            iMapB = oMapB
            iMapBcn = oMapBcn

        innerEvent = eventToEvent(oMapF, iMapB)
        if set(innerEvent.values()) == set([None]):
            sys.exit(
                "No common events found.  Consider passing --identity-map.")

        if mapOptions['printEventMap']:
            for oEntry, iEntry in sorted(innerEvent.iteritems()):
                printer.msg(", ".join([
                    "oEntry = %s" % str(oEntry),
                    "oEvnOrn = %s" % str(oMapF[oEntry]),
                    "iEntry = %s" % str(iEntry),
                ]))
    else:
        chainI = None
        innerEvent = iMapF = iMapB = iMapBcn = {}

    return chainI, innerEvent, iMapF, iMapB, iMapBcn
Ejemplo n.º 3
0
def go(outer={}, inner={}, outputFile="", mapOptions={}, options={}):

    raw.setup_root()
    import_plugins(outer["plugins"])
    outer.update(fileSpec(outer["fileNames"]))
    if inner:
        inner.update(fileSpec(inner["fileNames"]))
        if inner["fileNames"] == outer["fileNames"]:
            mapOptions["identityMap"] = True

    chain = raw.tchain(outer)
    oMapF, oMapB, oMapBcn = eventMaps(chain, outer, mapOptions["identityMap"])
    chainI, innerEvent, iMapF, iMapB, iMapBcn = inner_vars(
        outer, inner, mapOptions, oMapF, oMapB, oMapBcn)
    book = loop(chain=chain,
                chainI=chainI,
                outer=outer,
                inner=inner,
                innerEvent=innerEvent,
                oMapF=oMapF,
                options=options)

    utils.delete(chain)
    if chainI:
        utils.delete(chainI)

    # write results to a ROOT file
    dirName = os.path.dirname(outputFile)
    if not os.path.exists(dirName):
        print "Creating directory '%s'" % dirName
        os.mkdir(dirName)

    f = r.TFile(outputFile, "RECREATE")
    if not f.IsZombie():
        write_category_graphs(
            category_vs_time(oMap=oMapF,
                             oMapBcn=oMapBcn,
                             iMap=iMapF,
                             iMapBcn=iMapBcn,
                             innerEvent=innerEvent), outer, inner)
        for h in book.values():
            h.Write()
    f.Close()

    for h in book.values():
        utils.delete(h)

    if printEventSummary(outer, inner):
        s = "%s: %4s = %6d" % (outputFile, outer["label"], len(oMapF))
        if inner:
            nBoth = len(filter(lambda x: x is not None, innerEvent.values()))
            s += ", %4s = %6d, both = %6d" % (inner["label"], len(iMapB),
                                              nBoth)
        printer.msg(s)

    oFeds = sorted(outer.get("wargs", {}).keys())
    iFeds = sorted(inner.get("wargs", {}).keys()) if inner else []
    return not len(oMapF), oFeds, iFeds
Ejemplo n.º 4
0
def go(outer={}, inner={}, outputFile="",
       mapOptions={}, options={}):

    raw.setup_root()
    import_plugins(outer["plugins"])
    outer.update(fileSpec(outer["fileNames"]))
    if inner:
        inner.update(fileSpec(inner["fileNames"]))
        if inner["fileNames"] == outer["fileNames"]:
            mapOptions["identityMap"] = True

    chain = raw.tchain(outer)
    oMapF, oMapB, oMapBcn = eventMaps(chain, outer, mapOptions["identityMap"])
    chainI, innerEvent, iMapF, iMapB, iMapBcn = inner_vars(outer, inner, mapOptions,
                                                           oMapF, oMapB, oMapBcn)
    book = loop(chain=chain, chainI=chainI,
                outer=outer, inner=inner,
                innerEvent=innerEvent, oMapF=oMapF,
                options=options)

    utils.delete(chain)
    if chainI:
        utils.delete(chainI)

    # write results to a ROOT file
    dirName = os.path.dirname(outputFile)
    if not os.path.exists(dirName):
        print("Creating directory '%s'" % dirName)
        os.mkdir(dirName)

    f = r.TFile(outputFile, "RECREATE")
    if not f.IsZombie():
        write_category_graphs(category_vs_time(oMap=oMapF, oMapBcn=oMapBcn,
                                               iMap=iMapF, iMapBcn=iMapBcn,
                                               innerEvent=innerEvent),
                              outer,
                              inner)
        for h in book.values():
            h.Write()
    f.Close()

    for h in book.values():
        utils.delete(h)

    if printEventSummary(outer, inner):
        s = "%s: %4s = %6d" % (outputFile, outer["label"], len(oMapF))
        if inner:
            nBoth = len([x for x in list(innerEvent.values()) if x is not None])
            s += ", %4s = %6d, both = %6d" % (inner["label"], len(iMapB), nBoth)
        printer.msg(s)

    oFeds = sorted(outer.get("wargs", {}).keys())
    iFeds = sorted(inner.get("wargs", {}).keys()) if inner else []
    return not len(oMapF), oFeds, iFeds
Ejemplo n.º 5
0
    def command(self,
                cmd,
                timeout=5,
                bail_on_timeout=False,
                only_first_line=True):
        fields = cmd.split()
        if not fields:
            return None

        if fields[0] == "jtag":
            if len(fields) < 4:
                print("COMMAND has to few fields: (%s)" % cmd)
                return None

            regexp = "(.*)%s %s %s# retcode=(.*)" % tuple(fields[1:])
        else:
            regexp = "{0}\s?#((\s|E)[^\r^\n]*)".format(re.escape(cmd))

        try:
            self.server.sendline(cmd)
            self.server.expect(regexp, timeout=timeout)
            out = self.server.match.group(0).split("\r\n")
        except pexpect.TIMEOUT:
            if not bail_on_timeout:
                out = [cmd + " # ERROR: timed out after %d seconds" % timeout]
            else:
                lines = [
                    printer.msg('The command "', p=False),
                    printer.cyan(cmd, p=False),
                    printer.msg(
                        '"\n       produced unexpected output.  Consult the log file, e.g.',
                        p=False),
                    printer.msg('\n       "%s" gives this:' %
                                printer.gray(tail, p=False),
                                p=False),
                    printer.error(msg)
                ]
                self.bail(lines, tail=True)

        if "ERROR" in out[0]:
            printer.red(out[0])
        return out[0] if only_first_line else out
Ejemplo n.º 6
0
def ROOT():
    moduleNames = ["ROOT"]
    if not cmssw():
        moduleNames.insert(0, "CppyyROOT")

    for moduleName in moduleNames:
        try:
            exec("import %s as r" % moduleName)
            if moduleName != "ROOT":
                printer.msg("Using "+moduleName)
            r.PyConfig.IgnoreCommandLineOptions = True
            return r
        except ImportError:
            continue

    findROOT()
    try:
        import ROOT as r
        r.PyConfig.IgnoreCommandLineOptions = True
        return r
    except ImportError:
        bail()
Ejemplo n.º 7
0
def ROOT():
    moduleNames = ["ROOT"]
    if not cmssw():
        moduleNames.insert(0, "CppyyROOT")

    for moduleName in moduleNames:
        try:
            exec("import %s as r" % moduleName)
            if moduleName != "ROOT":
                printer.msg("Using " + moduleName)
            r.PyConfig.IgnoreCommandLineOptions = True
            return r
        except ImportError:
            continue

    findROOT()
    try:
        import ROOT as r
        r.PyConfig.IgnoreCommandLineOptions = True
        return r
    except ImportError:
        bail()
Ejemplo n.º 8
0
def inner_vars(outer, inner, mapOptions, oMapF, oMapB, oMapBcn):
    if inner:
        chainI = raw.tchain(inner)
        iMapF, iMapB, iMapBcn = eventMaps(chainI, inner)
        if mapOptions["identityMap"]:
            iMapF = oMapF
            iMapB = oMapB
            iMapBcn = oMapBcn

        innerEvent = eventToEvent(oMapF, iMapB)
        if set(innerEvent.values()) == set([None]):
            sys.exit("No common events found.  Consider passing --identity-map.")

        if mapOptions['printEventMap']:
            for oEntry, iEntry in sorted(innerEvent.items()):
                printer.msg(", ".join(["oEntry = %s" % str(oEntry),
                                       "oEvnOrn = %s" % str(oMapF[oEntry]),
                                       "iEntry = %s" % str(iEntry),
                                       ]))
    else:
        chainI = None
        innerEvent = iMapF = iMapB = iMapBcn = {}

    return chainI, innerEvent, iMapF, iMapB, iMapBcn
Ejemplo n.º 9
0
def oneHtr(p={},
           printColumnHeaders=None,
           dump=None,
           crateslots=[],
           utca=None,
           nonMatchedQie=[],
           nonMatchedTp=[]):
    zs = p.get("ZS")

    if "nWord16Qie" in p:
        col = "nWord16Qie"
    elif utca:
        col = "DataLength16"
    elif p["IsTTP"]:
        col = "          "

    out = []
    if printColumnHeaders:
        columns = [
            "iWord16",
            "    EvN",
            "  OrN5",
            " BcN",
            "Cr",
            "Sl",
            " Fl",
            "FrmtV",
            "nPre",
            #"nWordTP",
            col,
            "nSamp",
            "EvN8",
            "  CRC" + ("32" if utca else ""),
        ]
        if zs:
            columns += [" ", "ZSMask:  Thr1, Thr24, ThrTP"]
        out.append("  ".join(columns))

    strings = [
        " %05d" % p["0Word16"],
        " 0x%07x" % p["EvN"],
        "0x%02x" % p["OrN5"],
        "%4d" % p["BcN"],
        "%2d" % p["Crate"],
        "%2d%1s" % (p["Slot"], p["Top"]),
        "%2d" % p.get("FWFlavor", -1),  # absent in uHTR
        " 0x%01x" % p["FormatVer"],
        "  %2d" % p["nPreSamples"],
        #"  %3d  " % p["nWord16Tp"],
    ]
    if utca:
        s = "  %4d/%4d" % (p.get(col, -1), p.get(col + "T", -1))
        strings.append(s)
    else:
        strings.append("     %3d " % p.get(col, -1))

    strings += [
        "   %2d" % p.get("nSamples", -1),  # absent in uHTR
        "  0x%02x" % p["EvN8"],
    ]
    if utca:
        strings.append("0x%08x" % p["CRC"])
    elif "Qie" in col:
        strings.append("0x%04x" % p["CRC"])
    else:
        strings.append("  TTP ")

    if zs:
        strings += [
            "",
            "0x%04x" % zs["Mask"],
            "  %3d" % zs["Threshold1"],
            "  %3d" % zs["Threshold24"],
            "  %3d" % zs["ThresholdTP"],
        ]

    out.append("  ".join(strings))
    printer.green("\n".join(out))

    anyHtrDataPrinted = False
    if 4 <= dump:
        kargs = {
            "skipFibChs": [0, 2, 3, 4, 5, 6, 7] if (4 <= dump <= 6) else [],
            "nonMatched": nonMatchedQie,
            "latency": p.get("Latency"),
            "zs": p.get("ZS"),
            "skipErrF": [3],
        }
        if dump == 6 or 8 <= dump:
            kargs["skipErrF"] = []
        if p["IsTTP"]:
            cd = ttpData(p["ttpInput"], p["ttpOutput"], p["ttpAlgoDep"])
        else:
            if crateslots and (100 * p["Crate"] + p["Slot"]) not in crateslots:
                return
            cd = htrChannelData(p["channelData"].values(),
                                crate=p["Crate"],
                                slot=p["Slot"],
                                top=p["Top"],
                                **kargs)
        if len(cd) >= 2:
            printer.yellow(cd[0])
            printer.msg("\n".join(cd[1:]))
            anyHtrDataPrinted = True

        if 5 <= dump:
            kargs = {
                "skipZeroTps": dump <= 7,
                "crate": p["Crate"],
                "slot": p["Slot"],
                "top": p["Top"],
                "nonMatched": nonMatchedTp,
            }
            if utca:
                td = uhtrTriggerData(p["triggerData"], **kargs)
            else:
                td = htrTriggerData(p["triggerData"], zs=zs, **kargs)

            if len(td) >= 2:
                printer.yellow(td[0])
                printer.msg("\n".join(td[1:]))
                anyHtrDataPrinted = True

    return anyHtrDataPrinted
Ejemplo n.º 10
0
def go(outer={},
       inner={},
       outputFile="",
       mapOptions={},
       loopOptions={},
       printEventSummary=None):

    innerEvent = {}
    deltaOrn = {}

    chain = tchain(outer)

    # by default:
    nMapMin = 0  # start from beginning
    nMapMax = None  # look at all entries

    nEv = outer["nEventsMax"] + outer["nEventsSkip"]
    if nEv:
        if mapOptions["identityMap"]:
            nMapMin = outer["nEventsSkip"]
            nMapMax = nEv
        else:
            nMapMax = nEv * 2  # a guess for how far to look not to miss out-of-order events

    oMapF, oMapB, oMapBcn = eventMaps(chain,
                                      outer,
                                      nMapMin=nMapMin,
                                      nMapMax=nMapMax)
    iMapF = iMapB = iMapBcn = {}

    if inner.get("fileNames") == outer["fileNames"]:
        chainI = chain
        innerEvent = {}
    elif inner:
        chainI = tchain(inner)
        if mapOptions["identityMap"]:
            iMapF = oMapF
            iMapB = oMapB
            iMapBcn = oMapBcn
        else:
            iMapF, iMapB, iMapBcn = eventMaps(chainI, inner)

        innerEvent = eventToEvent(oMapF, iMapB)
        if set(innerEvent.values()) == set([None]):
            sys.exit(
                "No common events found.  Consider passing --identity-map.")

        if mapOptions['printEventMap']:
            for oEntry, iEntry in sorted(innerEvent.iteritems()):
                printer.msg(", ".join([
                    "oEntry = %s" % str(oEntry),
                    "oEvnOrn = %s" % str(oMapF[oEntry]),
                    "iEntry = %s" % str(iEntry),
                ]))
    else:
        chainI = None

    book = loop(chain=chain,
                chainI=chainI,
                outer=outer,
                inner=inner,
                innerEvent=innerEvent,
                options=loopOptions)

    utils.delete(chain)
    if chainI:
        utils.delete(chainI)

    # write results to a ROOT file
    dirName = os.path.dirname(outputFile)
    if not os.path.exists(dirName):
        print "Creating directory '%s'" % dirName
        os.mkdir(dirName)

    f = r.TFile(outputFile, "RECREATE")

    d = category_vs_time(oMap=oMapF,
                         oMapBcn=oMapBcn,
                         iMap=iMapF,
                         iMapBcn=iMapBcn,
                         innerEvent=innerEvent)

    if outer["fedIds"]:
        iFeds = inner.get("fedIds", [])
        if not iFeds:
            iFeds = [None]
        for iGraph, gr in enumerate(
                graphs(d, oFed=outer["fedIds"][0], iFed=iFeds[0])):
            if iGraph == 0:
                gr.SetTitle("_".join([
                    "only %s" % inner.get("label", ""),
                    "only %s" % outer.get("label", ""), "both"
                ]))
            if iGraph == 1:
                gr.SetTitle(",".join(outer["fileNames"]))
            gr.Write()

    for h in book.values():
        h.Write()
    f.Close()

    for h in book.values():
        utils.delete(h)

    if printEventSummary:
        s = "%s: %4s = %6d" % (outputFile, outer["label"], len(oMapF))
        if inner:
            nBoth = len(filter(lambda x: x is not None, innerEvent.values()))
            s += ", %4s = %6d, both = %6d" % (inner["label"], len(iMapB),
                                              nBoth)
        printer.msg(s)

    return not len(oMapF)
Ejemplo n.º 11
0
def oneHtr(p={}, printColumnHeaders=None, dump=None, crateslots=[], utca=None,
           nonMatchedQie=[], nonMatchedTp=[]):
    zs = p.get("ZS")

    if "nWord16Qie" in p:
        col = "nWord16Qie"
    elif utca:
        col = "DataLength16"
    elif p["IsTTP"]:
        col = "          "

    out = []
    if printColumnHeaders:
        columns = ["iWord16",
                   "   EvN",
                   "  OrN5",
                   " BcN",
                   "Cr",
                   "Sl",
                   " Fl",
                   "FrmtV",
                   "nPre",
                   #"nWordTP",
                   col,
                   "nSamp",
                   "EvN8",
                   "  CRC" + ("32" if utca else ""),
        ]
        if zs:
            columns += [" ", "ZSMask:  Thr1, Thr24, ThrTP"]
        out.append("  ".join(columns))

    strings = [" %04d" % p["0Word16"],
               " 0x%07x" % p["EvN"],
               "0x%02x" % p["OrN5"],
               "%4d" % p["BcN"],
               "%2d" % p["Crate"],
               "%2d%1s" % (p["Slot"], p["Top"]),
               "%2d" % p.get("FWFlavor", -1),  # absent in uHTR
               " 0x%01x" % p["FormatVer"],
               "  %2d" % p["nPreSamples"],
               #"  %3d  " % p["nWord16Tp"],
               ]
    if utca:
        s = "    %3d/%3d" % (p.get(col, -1), p.get(col+"T", -1))
        strings.append(s)
    else:
        strings.append("     %3d " % p.get(col, -1))

    strings += ["   %2d" % p.get("nSamples", -1),  # absent in uHTR
                "  0x%02x" % p["EvN8"],
                ]
    if utca:
        strings.append("0x%08x" % p["CRC"])
    elif "Qie" in col:
        strings.append("0x%04x" % p["CRC"])
    else:
        strings.append("  TTP ")

    if zs:
        strings += ["",
                    "0x%04x" % zs["Mask"],
                    "  %3d" % zs["Threshold1"],
                    "  %3d" % zs["Threshold24"],
                    "  %3d" % zs["ThresholdTP"],
        ]

    out.append("  ".join(strings))
    printer.green("\n".join(out))

    anyHtrDataPrinted = False
    if 4 <= dump:
        kargs = {"skipFibChs": [0, 2, 3, 4, 5, 6, 7] if (4 <= dump <= 6) else [],
                 "nonMatched": nonMatchedQie,
                 "latency": p.get("Latency"),
                 "zs": p.get("ZS"),
                 "skipErrF": [3],
                 }
        if dump == 6 or 8 <= dump:
            kargs["skipErrF"] = []
        if p["IsTTP"]:
            cd = ttpData(p["ttpInput"], p["ttpOutput"], p["ttpAlgoDep"])
        else:
            if crateslots and (100*p["Crate"] + p["Slot"]) not in crateslots:
                return
            cd = htrChannelData(p["channelData"].values(),
                                crate=p["Crate"],
                                slot=p["Slot"],
                                top=p["Top"],
                                **kargs)
        if len(cd) >= 2:
            printer.yellow(cd[0])
            printer.msg("\n".join(cd[1:]))
            anyHtrDataPrinted = True

        if 5 <= dump:
            kargs = {"skipZeroTps": dump <= 7,
                     "crate": p["Crate"],
                     "slot": p["Slot"],
                     "top": p["Top"],
                     "nonMatched": nonMatchedTp,
                     }
            if utca:
                td = uhtrTriggerData(p["triggerData"], **kargs)
            else:
                td = htrTriggerData(p["triggerData"], zs=zs, **kargs)

            if len(td) >= 2:
                printer.yellow(td[0])
                printer.msg("\n".join(td[1:]))
                anyHtrDataPrinted = True

    return anyHtrDataPrinted
Ejemplo n.º 12
0
def oneHtr(iBlock=None, p={}, dump=None, utca=None,
           nonMatchedQie=[], nonMatchedTp=[],
           nTsMax=None, perTs=None):

    try:
        zs = p.get("ZS")
    except TypeError as e:
        print "iBlock='%s':" % str(iBlock), e
        return

    if "nWord16Qie" in p:
        col = "nWord16Qie"
    elif utca:
        col = "DataLength16"
    elif p.get("IsTTP"):
        col = "          "
    else:
        coords = "crate %2d slot %2d%1s" % (p.get("Crate", -1), p.get("Slot", -1), p.get("Top", "x"))
        printer.warning("unpacking did not succeed enough to print more about %s" % coords)
        return

    columns = ["iWord16",
               "    EvN",
               "  OrN5",
               " BcN",
               "Cr",
               "Sl",
               " Fl",
               "FrmtV",
               "nPre",
               col,
              ]
    if zs:
        columns += [" ", "ZSMask:  Thr1, Thr24, ThrTP"]

    strings = [" %05d" % p["0Word16"],
               " 0x%07x" % p["EvN"],
               "0x%02x" % p["OrN5"],
               "%4d" % p["BcN"],
               "%2d" % p["Crate"],
               "%2d%1s" % (p["Slot"], p["Top"]),
               "%2d" % p.get("FWFlavor", -1),  # absent in uHTR
               " 0x%01x" % p["FormatVer"],
               "  %2d" % p["nPreSamples"],
               ]
    if utca:
        s = "  %4d/%4d" % (p.get(col, -1), p.get(col+"T", -1))
        strings.append(s)
    else:
        strings.append("     %3d " % p.get(col, -1))

    if utca or ("Qie" in col):
        strings.append("      ")
    else:
        strings.append("  TTP ")

    if zs:
        strings += ["",
                    "0x%04x" % zs["Mask"],
                    "  %3d" % zs["Threshold1"],
                    "  %3d" % zs["Threshold24"],
                    "  %3d" % zs["ThresholdTP"],
        ]

    out = []
    if (not iBlock) or 4 <= dump:
        out.append("  ".join(columns))

    if dump != 4 and dump != 10:
        out.append("  ".join(strings))
        printer.green("\n".join(out))

    if dump <= 3:
        return

    kargs = {"skipFibers": [0, 1] + range(3, 14) + range(15, 24) if (dump == 4) else [],
             "skipFibChs": [0, 2, 3, 4, 5, 6, 7] if (4 <= dump <= 7) else [],
             "skipErrF": [],
             "nonMatched": nonMatchedQie,
             "latency": p.get("Latency"),
             "zs": p.get("ZS"),
             "nTsMax": nTsMax,
             "perTs": perTs,
            }
    if dump in [5, 6, 8]:
        kargs["skipErrF"] = [3]
    if dump == 10:
        kargs["skipErrF"] = [0]

    if p["IsTTP"]:
        cd = ttpData(p["ttpInput"], p["ttpOutput"], p["ttpAlgoDep"])
    else:
        cd = htrChannelData(p["channelData"].values(),
                            crate=p["Crate"],
                            slot=p["Slot"],
                            top=p["Top"],
                            **kargs)

    if len(cd) >= 2:
        printer.yellow(cd[0])
        printer.msg("\n".join(cd[1:]))

    if 6 <= dump:
        kargs = {"crate": p["Crate"],
                 "slot": p["Slot"],
                 "top": p["Top"],
                 "nonMatched": nonMatchedTp,
                 "dump": dump,
                 }
        if utca:
            td = uhtrTriggerData(p["triggerData"], **kargs)
        else:
            td = htrTriggerData(p["triggerData"], zs=zs, **kargs)

        if len(td) >= 2:
            printer.yellow(td[0])
            printer.msg("\n".join(td[1:]))
Ejemplo n.º 13
0
def oneHtr(iBlock=None, p={}, dump=None, utca=None,
           nonMatchedQie=[], nonMatchedTp=[],
           nTsMax=None, perTs=None):

    try:
        zs = p.get("ZS")
    except TypeError as e:
        print("iBlock='%s':" % str(iBlock), e)
        return

    if "nWord16Qie" in p:
        col = "nWord16Qie"
    elif utca:
        col = "DataLength16"
    elif p.get("IsTTP"):
        col = "          "
    else:
        coords = "crate %2d slot %2d%1s" % (p.get("Crate", -1), p.get("Slot", -1), p.get("Top", "x"))
        printer.warning("unpacking did not succeed enough to print more about %s" % coords)
        return

    columns = ["iWord16",
               "    EvN",
               "  OrN5",
               " BcN",
               "Cr",
               "Sl",
               " Fl",
               "FrmtV",
               "nPre",
               col,
              ]
    if zs:
        columns += ["ZSMask:  Thr1, Thr24, ThrTP"]

    strings = [" %05d" % p["0Word16"],
               " 0x%07x" % p["EvN"],
               "0x%02x" % p["OrN5"],
               "%4d" % p["BcN"],
               "%2d" % p["Crate"],
               "%2d%1s" % (p["Slot"], p["Top"]),
               "%2d" % p.get("FWFlavor", -1),  # absent in uHTR
               " 0x%01x" % p["PayloadFormat"],
               "  %2d" % p["nPreSamples"],
               ]
    if utca:
        s = "  %4d/%4d" % (p.get(col, -1), p.get(col+"T", -1))
        strings.append(s)
    else:
        strings.append("     %3d " % p.get(col, -1))

    if p["IsTTP"]:
        strings.append("  TTP ")
    elif p["IsIO"]:
        strings.append(" uMNio ")

    if zs:
        strings += ["  0x%04x" % zs["Mask"],
                    "  %3d" % zs["Threshold1"],
                    "  %3d" % zs["Threshold24"],
                    "  %3d" % zs["ThresholdTP"],
        ]

    out = []
    if (not iBlock) or 4 <= dump:
        out.append("  ".join(columns))

    if dump != 4 and dump != 10:
        out.append("  ".join(strings))
        printer.green("\n".join(out))

    if dump <= 3:
        return

    kargs = {"skipFibers": [0, 1] + list(range(3, 14)) + list(range(15, 24)) if (dump == 4) else [],
             "skipFibChs": [0, 2, 3, 4, 5, 6, 7] if (4 <= dump <= 7) else [],
             "nonMatched": nonMatchedQie,
             "latency": p.get("Latency"),
             "zs": p.get("ZS"),
             "nTsMax": nTsMax,
             "perTs": perTs,
            }
    if dump in [5, 6, 8]:
        kargs["errorsReq"] = False
    if dump == 10:
        kargs["errorsReq"] = True

    if p["IsTTP"]:
        cd = ttpData(p["ttpInput"], p["ttpOutput"], p["ttpAlgoDep"])
    if p["IsIO"]:
        cd = ioData(p)
    else:
        cd = htrChannelData(p["channelData"].values(),
                            crate=p["Crate"],
                            slot=p["Slot"],
                            top=p["Top"],
                            **kargs)

    if len(cd) >= 2:
        printer.yellow(cd[0])
        printer.msg("\n".join(cd[1:]))

    if 6 <= dump:
        kargs = {"crate": p["Crate"],
                 "slot": p["Slot"],
                 "top": p["Top"],
                 "nonMatched": nonMatchedTp,
                 "dump": dump,
                 }
        if utca:
            td = uhtrTriggerData(p["triggerData"], **kargs)
        else:
            td = htrTriggerData(p["triggerData"], zs=zs, **kargs)

        if len(td) >= 2:
            printer.yellow(td[0])
            printer.msg("\n".join(td[1:]))
Ejemplo n.º 14
0
def go(outer={}, inner={}, outputFile="",
       mapOptions={}, loopOptions={},
       printEventSummary=None):

    innerEvent = {}
    deltaOrn = {}

    chain = tchain(outer)

    # by default:
    nMapMin = 0     # start from beginning
    nMapMax = None  # look at all entries

    nEv = outer["nEventsMax"] + outer["nEventsSkip"]
    if nEv:
        if mapOptions["identityMap"]:
            nMapMin = outer["nEventsSkip"]
            nMapMax = nEv
        else:
            nMapMax = nEv * 2  # a guess for how far to look not to miss out-of-order events

    oMapF, oMapB, oMapBcn = eventMaps(chain, outer, nMapMin=nMapMin, nMapMax=nMapMax)
    iMapF = iMapB = iMapBcn = {}

    if inner.get("fileNames") == outer["fileNames"]:
        chainI = chain
        innerEvent = {}
    elif inner:
        chainI = tchain(inner)
        if mapOptions["identityMap"]:
            iMapF = oMapF
            iMapB = oMapB
            iMapBcn = oMapBcn
        else:
            iMapF, iMapB, iMapBcn = eventMaps(chainI, inner)

        innerEvent = eventToEvent(oMapF, iMapB)
        if set(innerEvent.values()) == set([None]):
            sys.exit("No common events found.  Consider passing --identity-map.")

        if mapOptions['printEventMap']:
            for oEntry, iEntry in sorted(innerEvent.iteritems()):
                printer.msg(", ".join(["oEntry = %s" % str(oEntry),
                                       "oEvnOrn = %s" % str(oMapF[oEntry]),
                                       "iEntry = %s" % str(iEntry),
                                       ]))
    else:
        chainI = None

    book = loop(chain=chain, chainI=chainI,
                outer=outer, inner=inner,
                innerEvent=innerEvent,
                options=loopOptions)

    utils.delete(chain)
    if chainI:
        utils.delete(chainI)

    # write results to a ROOT file
    dirName = os.path.dirname(outputFile)
    if not os.path.exists(dirName):
        print "Creating directory '%s'" % dirName
        os.mkdir(dirName)

    f = r.TFile(outputFile, "RECREATE")

    d = category_vs_time(oMap=oMapF, oMapBcn=oMapBcn,
                         iMap=iMapF, iMapBcn=iMapBcn,
                         innerEvent=innerEvent)

    if outer["fedIds"]:
        iFeds = inner.get("fedIds", [])
        if not iFeds:
            iFeds = [None]
        for iGraph, gr in enumerate(graphs(d, oFed=outer["fedIds"][0], iFed=iFeds[0])):
            if iGraph == 0:
                gr.SetTitle("_".join(["only %s" % inner.get("label", ""), "only %s" % outer.get("label", ""), "both"]))
            if iGraph == 1:
                gr.SetTitle(",".join(outer["fileNames"]))
            gr.Write()


    for h in book.values():
        h.Write()
    f.Close()

    for h in book.values():
        utils.delete(h)

    if printEventSummary:
        s = "%s: %4s = %6d" % (outputFile, outer["label"], len(oMapF))
        if inner:
            nBoth = len(filter(lambda x: x is not None, innerEvent.values()))
            s += ", %4s = %6d, both = %6d" % (inner["label"], len(iMapB), nBoth)
        printer.msg(s)

    return not len(oMapF)