Esempio n. 1
0
def one(target, options):
    out = []
    for i in range(options.nIterations):
        try:
            jtag.programmer(options, target)
            out.append(None)
        except RuntimeError as e:
            printer.red(e[1])
            out.append(e)
    return out
Esempio n. 2
0
def main(options, filenames):
    for filename in filenames:
        try:
            if 2 <= len(filenames):
                print("\n", filename)
            lst = list_of_pairs(filename)
            if len(lst) == 1 and options.plots:
                one(lst[0], options.nBitsMax)
            else:
                multi(lst, options.nBitsMax)
        except EOFError:
            printer.red("EOFError")
Esempio n. 3
0
def uhtrTriggerData(d={}, dump=None, crate=None, slot=None, top="", nonMatched=[]):
    out = []
    out.append("  ".join([" TPid",
                          "Fl",
                          "  SofI",
                          "   OK",
                          "  TP(hex)",
                          "    ".join([str(i) for i in range(4)])
                          ])
               )
    for channelId, data in sorted(d.iteritems()):
        if (dump <= 8) and not any(data["TP"]):
            continue
        soi = ""
        ok = ""
        tp = ""
        for j in range(len(data["SOI"])):
            soi += str(data["SOI"][j])
            ok += str(data["OK"][j])
            tp_s = "%5x" % data["TP"][j]
            if data["SOI"][j]:
                tp_s = printer.gray(tp_s, False)
            if not data["OK"][j]:
                tp_s = printer.red(tp_s, False)
            tp += tp_s

        if dump != 10 or not all(data["OK"]):
            out.append("   ".join([" 0x%02x" % channelId,
                                   "%1d" % data["Flavor"],
                                   "%5s" % soi,
                                   "%5s" % ok,
                                   " "*2,
                                   tp]))
    return out
Esempio n. 4
0
def uhtrTriggerData(d={}, dump=None, crate=None, slot=None, top="", nonMatched=[]):
    out = []
    out.append("  ".join([" TPid",
                          "Fl",
                          "  SofI",
                          "   OK",
                          "  TP(hex)",
                          "    ".join([str(i) for i in range(4)])
                          ])
               )
    for channelId, data in sorted(d.items()):
        if (dump <= 8) and not any(data["TP"]):
            continue
        soi = ""
        ok = ""
        tp = ""
        for j in range(len(data["SOI"])):
            soi += str(data["SOI"][j])
            ok += str(data["OK"][j])
            tp_s = "%5x" % data["TP"][j]
            if data["SOI"][j]:
                tp_s = printer.gray(tp_s, False)
            if not data["OK"][j]:
                tp_s = printer.red(tp_s, False)
            tp += tp_s

        if dump != 10 or not all(data["OK"]):
            out.append("   ".join([" 0x%02x" % channelId,
                                   "%1d" % data["Flavor"],
                                   "%5s" % soi,
                                   "%5s" % ok,
                                   " "*2,
                                   tp]))
    return out
def main():
    correct_required = _get_correct_required(sys.argv[1:])
    random.seed(datetime.now())
    total_correct = 0

    while total_correct < correct_required:
        # Choosing a random game
        game = _choose_game()

        # Output the game
        starting_game = lang['starting_game'].format(game.name, total_correct,
                                                     correct_required)
        seperator = '*' * len(starting_game)
        printer.blue(seperator + os.linesep + starting_game + os.linesep +
                     seperator)

        # Get a question and validator function for the game
        question, validator = game.play_game()

        # Ask it
        printer.cyan(question)

        # Loop until an answer is correct
        is_correct = False
        total_incorrect = 0

        while is_correct == False and total_incorrect < retry_limit:
            user_input = _ask_question(lang['submit_answer'])
            is_correct = validator(user_input)

            # If that's not correct, provide a message before looping
            if is_correct == False:
                total_incorrect += 1
                remaining = retry_limit - total_incorrect
                printer.red(lang['incorrect'].format(remaining))

        if is_correct == False:
            print(lang['limit_reached'])
            return  # Must break out, probable infinite loop reached

        printer.green(lang['correct'])
        total_correct += 1
Esempio n. 6
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
Esempio n. 7
0
def qieString(qies=[], sois=[], red=False, nMax=10):
    l = []

    for i in range(nMax):
        if i < len(qies):
            s = "%2x" % qies[i]
            if i < len(sois) and sois[i] and not red:
                s = printer.gray(s, False)
            l.append(s)
        else:
            l.append("  ")

    out = " ".join(l)
    if red:
        out = printer.red(out, False)

    if nMax < len(qies):
        out += printer.red("..", False)
    else:
        out += "  "
    return out
Esempio n. 8
0
def qieString(qies=[], sois=[], red=False, nMax=10):
    l = []

    for i in range(nMax):
        if i < len(qies):
            s = "%2x" % qies[i]
            if i < len(sois) and sois[i] and not red:
                s = printer.gray(s, False)
            l.append(s)
        else:
            l.append("  ")

    out = " ".join(l)
    if red:
        out = printer.red(out, False)

    if nMax < len(qies):
        out += printer.red("..", False)
    else:
        out += "  "
    return out
Esempio n. 9
0
    def compare(self, res, expected, msg=""):
        fields = res.split("#")

        try:
            result = int(fields[1],
                         16 if fields[1].strip().startswith("0x") else 10)
        except ValueError:
            result = None
            if "ERROR" not in res:
                fields[1] = printer.red(fields[1], p=False)
                print("#".join(fields))
            self.bail()

        if result != expected and expected is not None:
            if "ERROR" not in res:
                fields[1] = printer.red(fields[1], p=False)
                print(
                    "%s   %s" %
                    ("#".join(fields),
                     printer.purple("(expected %s)" % str(expected), p=False)))
            self.bail([msg] if msg else [])
        else:
            print(res)
Esempio n. 10
0
    def compare_with_threshold(self, res, expected, threshold, msg=""):
        fields = res.split("#")

        if " " in fields[1]:
            res1 = fields[1].split()
        elif type(fields[1]) is not list:
            res1 = [fields[1]]

        try:
            if res1[0].strip().startswith("0x"):
                results = [int(x, 16) for x in res1]
            else:
                results = [float(x) for x in res1]
        except ValueError:
            results = []
            if "ERROR" not in res:
                fields[1] = printer.red(fields[1], p=False)
                print("#".join(fields))
            self.bail()

        fail = []
        for iResult, result in enumerate(results):
            if threshold < abs(result - expected):
                fail.append(iResult)
                res1[iResult] = printer.red(res1[iResult], p=False)

        if fail:
            print("%s# %s   %s" %
                  (fields[0], " ".join(res1),
                   printer.purple("(expected %s +- %s)" %
                                  (str(expected), str(threshold)),
                                  p=False)))
            self.bail([msg] if msg else [])
        else:
            if "ERROR" not in res:
                print(res)
Esempio n. 11
0
def capIdString(caps, sois, nTsMax):
    l = []

    for i in range(nTsMax):
        if i < len(caps) and i < len(sois):
            value = caps[i]
            s = "%1x" % value
            if sois[i]:
                s = printer.gray(s, False)
            l.append(s)
        else:
            l.append(" ")

    out = "".join(l)

    if nTsMax < len(caps):
        out += printer.red("..", False)
    else:
        out += "  "
    return out
Esempio n. 12
0
def capIdString(caps, sois, nTsMax):
    l = []

    for i in range(nTsMax):
        if i < len(caps) and i < len(sois):
            value = caps[i]
            s = "%1x" % value
            if sois[i]:
                s = printer.gray(s, False)
            l.append(s)
        else:
            l.append(" ")

    out = "".join(l)

    if nTsMax < len(caps):
        out += printer.red("..", False)
    else:
        out += "  "
    return out
Esempio n. 13
0
    def uhtr_compare(self,
                     slot,
                     ppod,
                     first,
                     lst,
                     expected,
                     threshold=None,
                     doubled=False,
                     dec=False):
        iStart, iEnd, items = self.uhtr_range_and_items(slot, ppod, lst, first)
        n = int((len(lst) - 19) / 12)
        if doubled:
            iStart *= 2
            iEnd *= 2
            n = int(n / 2)

        msg = lst[:19]
        for i, x in enumerate(items):
            try:
                result = int(x, 10 if dec else 16)
            except ValueError:
                try:
                    result = float(x)
                except ValueError:
                    result = None

            if doubled:
                space = " " * (n - len(x) - 1)
            else:
                space = " " * (n - len(x) - 1)

            if i < iStart or iEnd <= i or result is None:
                msg += space + printer.gray(x, p=False) + " "
            elif threshold is not None and threshold < abs(result - expected):
                msg += space + printer.red(x, p=False) + " "
            else:
                msg += space + printer.green(x, p=False) + " "

        print(msg)
Esempio n. 14
0
 def bail(self, lines=None, minimal=False, note=""):
     if lines:
         printer.red("\n".join(lines))
     if not self.options.keepgoing:
         self.disconnect()
         sys.exit(" " if lines else "")
Esempio n. 15
0
 def bail(self, lines=None):
     if lines:
         printer.red("\n".join(lines))
     self.enable()
     self.disconnect()
     sys.exit()
Esempio n. 16
0
def histogram_fit_results(lst,
                          mins,
                          factors,
                          options,
                          target,
                          h_npoints,
                          h_mins,
                          h_factors,
                          h_pvalues,
                          h_pvalues2,
                          h_delta_chi2,
                          h_delta_chi2_cut_vs_ch,
                          h_offsets,
                          h_offsets_unc,
                          h_slopes,
                          h_slopes_unc_rel,
                          h_curvatures,
                          h_curvatures_unc,
                          warn=True,
                          offset2=False,
                          slope2=False):

    for iRes, (res, res2) in enumerate(lst):
        ch = 1 + iRes
        s = "WARNING: %s MB ch %2d" % (target, ch)

        npoints = res[-3]
        h_npoints.Fill(npoints)
        if warn and npoints < options.threshold_npoints_warn:
            printer.red("%s has %d points" % (s, npoints))

        h_mins.Fill(mins[iRes])
        h_factors.Fill(factors[iRes])

        pvalue = res[-1]
        h_pvalues.Fill(pvalue)

        pvalue2 = res2[-1]
        h_pvalues2.Fill(pvalue2)

        delta_chi2 = res[-2] - res2[-2]
        h_delta_chi2.Fill(delta_chi2)
        if options.threshold_delta_chi2_warn < delta_chi2:
            h_delta_chi2_cut_vs_ch.Fill(ch)
            if warn:
                printer.dark_blue("%s has delta chi2 %e" % (s, delta_chi2))

        offset = (res2 if offset2 else res)[0][0]
        h_offsets.Fill(offset)
        h_offsets_unc.Fill((res2 if offset2 else res)[0][1])

        slope = (res2 if slope2 else res)[1][0]
        h_slopes.Fill(slope)

        h_curvatures.Fill(res2[2][0])
        h_curvatures_unc.Fill(res2[2][1])

        if options.print_fit_results and slope < 0.80:  # requirement on slope hackily filters V fits
            print("%s %2d %6.3f %6.3f" %
                  (target.split("/")[-1], ch, offset, slope))

        if warn and not (options.threshold_slope_lo_warn < slope <
                         options.threshold_slope_hi_warn):
            printer.purple("%s has fit slope  %g" % (s, slope))

        if slope:
            rel_unc = res[1][1] / slope
            h_slopes_unc_rel.Fill(rel_unc)
            if warn and options.threshold_slope_rel_unc_warn < rel_unc:
                printer.cyan("%s has fit rel unc %g" % (s, rel_unc))
Esempio n. 17
0
def htrChannelData(lst=[], crate=0, slot=0, top="",
                   skipFibers=[], skipFibChs=[], skipErrF=[],
                   nonMatched=[], latency={}, zs={},
                   te_tdc=False, nTsMax=None, perTs=None):
    out = []
    columns = ["  Cr", "Sl", "Fi", "Ch", "Fl", "LE", "CE"]
    if perTs:
        columns += ["C/0" + "".join(["%1x" % i for i in range(1, nTsMax)]),
                    "K/0" + "".join(["%1x" % i for i in range(1, nTsMax)])]
    else:
        columns.append("C0")

    columns += ["0xA0 " + " ".join(["A%1d" % i for i in range(1, nTsMax)]),
                "0xL0 " + " ".join(["L%1d" % i for i in range(1, nTsMax)])]

    if te_tdc:
        columns += ["0xT0 " + " ".join(["T%1d" % i for i in range(1, nTsMax)])]
    if latency:
        columns += [" EF", "Cnt", "IDLE"]
    if zs:
        columns += [" ", "ZS?"]
    out.append(" ".join(columns))

    for data in sorted(lst, key=lambda x: (x["Fiber"], x["FibCh"])):
        if data["Fiber"] in skipFibers:
            continue
        if data["FibCh"] in skipFibChs:
            continue
        if data["ErrF"] in skipErrF:
            continue
        red = (crate, slot, top, data["Fiber"], data["FibCh"]) in nonMatched

        fields = ["  %2d" % crate,
                  "%2d%1s%2d" % (slot, top, data["Fiber"]),
                  " %1d" % data["FibCh"],
                  " %1d" % data["Flavor"],
                  ]

        for bit in ["LE", "CE"]:
            if data.get(bit) is None:
                fields.append("  ")
                continue
            v = " %1d" % data[bit]
            if data[bit]:
                v = printer.red(v, False)
            fields.append(v)

        if perTs:
            fields += ["  " + capIdString(data["CapId"], data["SOI"], nTsMax),
                       capIdString(data.get("OK", []), data["SOI"], nTsMax)]
        else:
            fields.append(" %1d  " % data["CapId"][0])

        fields += [qieString(data["QIE"], data["SOI"], red=red, nMax=nTsMax),
                   qieString(data.get("TDC", []), data["SOI"], nMax=nTsMax)]

        if te_tdc:
            fields += [qieString(data.get("TDC_TE", []), data["SOI"], nMax=nTsMax)]
        out.append(" ".join(fields))

        if latency:
            dct = latency.get("Fiber%d" % data["Fiber"])
            if dct and data["FibCh"] == 1:
                lat = ["%s%s" % (dct["Empty"], dct["Full"]),
                       "%2d " % dct["Cnt"],
                       "%4d" % dct["IdleBCN"],
                ]
                out[-1] += " ".join(lat)
        if zs:
            iChannel = 3*(data["Fiber"] - 1) + data["FibCh"]
            marks = zs["DigiMarks"]
            if iChannel < len(marks):
                m = "y" if marks[iChannel] else "n"
            else:
                m = " "
            out[-1] += "%7s" % m

    return out
Esempio n. 18
0
def htrChannelData(lst=[], crate=0, slot=0, top="",
                   skipFibers=[], skipFibChs=[], errorsReq=None,
                   nonMatched=[], latency={}, zs={},
                   nTsMax=None, perTs=None):
    out = []
    columns = ["  Cr", "Sl", "Fi", "Ch", "Fl", "LE", "CE"]
    if perTs:
        columns += ["C/0" + "".join(["%1x" % i for i in range(1, nTsMax)]),
                    "K/0" + "".join(["%1x" % i for i in range(1, nTsMax)])]
    else:
        columns.append("C0")

    columns += ["0xA0 " + " ".join(["A%1d" % i for i in range(1, nTsMax)]),
                "0xL0 " + " ".join(["L%1d" % i for i in range(1, nTsMax)])]

    te_tdc = lst and lst[0].get("Flavor") == 2

    if te_tdc:
        columns += ["0xT0 " + " ".join(["T%1d" % i for i in range(1, nTsMax)])]
    if latency:
        columns += [" EF", "Cnt", "IDLE"]
    if zs:
        columns += [" ", "ZS?"]
    out.append(" ".join(columns))

    for data in sorted(lst, key=lambda x: (x["Fiber"], x["FibCh"])):
        if data["Fiber"] in skipFibers:
            continue
        if data["FibCh"] in skipFibChs:
            continue
        if errorsReq is not None:
            anything_wrong = data.get("LE", False) or data.get("CE", False) or not all(data.get("OK", []))
            if errorsReq ^ anything_wrong:
                continue

        red = (crate, slot, top, data["Fiber"], data["FibCh"]) in nonMatched

        fields = ["  %2d" % crate,
                  "%2d%1s%2d" % (slot, top, data["Fiber"]),
                  " %1d" % data["FibCh"],
                  " %1d" % data["Flavor"],
                  ]

        for bit in ["LE", "CE"]:
            if data.get(bit) is None:
                fields.append("  ")
                continue
            v = " %1d" % data[bit]
            if data[bit]:
                v = printer.red(v, False)
            fields.append(v)

        if perTs:
            fields += ["  " + capIdString(data["CapId"], data["SOI"], nTsMax),
                       capIdString(data.get("OK", []), data["SOI"], nTsMax)]
        else:
            if data["CapId"]:
                fields.append(" %1d  " % data["CapId"][0])
            else:
                fields.append("    ")

        fields += [qieString(data["QIE"], data["SOI"], red=red, nMax=nTsMax),
                   qieString(data.get("TDC", []), data["SOI"], nMax=nTsMax)]

        if te_tdc:
            fields += [qieString(data.get("TDC_TE", []), data["SOI"], nMax=nTsMax)]
        out.append(" ".join(fields))

        if latency:
            dct = latency.get("Fiber%d" % data["Fiber"])
            if dct and data["FibCh"] == 1:
                lat = ["%s%s" % (dct["Empty"], dct["Full"]),
                       "%2d " % dct["Cnt"],
                       "%4d" % dct["IdleBCN"],
                ]
                out[-1] += " ".join(lat)
        if zs:
            iChannel = 3*(data["Fiber"] - 1) + data["FibCh"]
            marks = zs["DigiMarks"]
            if iChannel < len(marks):
                m = "y" if marks[iChannel] else "n"
            else:
                m = " "
            out[-1] += "%3s" % m

    return out
Esempio n. 19
0
def main():
    try:
        driver(fake_options(), "target")
    except RuntimeError as e:
        printer.red(e[1])
        sys.exit(" ")
Esempio n. 20
0
    def errors(self,
               store=True,
               letter="",
               fec=True,
               ccm=True,
               sleep=True,
               old=False):
        msg = "Reading link error counters ("
        if letter:
            msg += letter + ","
        if fec:
            msg += "fec,"
        if ccm:
            msg += "ccm,"
        if store:
            msg += "store,"
            if sleep:
                msg += "integrating for %d seconds" % self.options.nSeconds
        msg += ")"

        if hasattr(self, "target0"):
            target0 = self.target0
        else:
            target0 = self.rbx + letter

        print(msg)
        if old:
            fec_cmd = "get %s-fec_dv_down_cnt_rr" % target0
        else:
            fec_cmd = "get %s-fec_[rx_rs_err,dv_down]_cnt_rr" % target0
        ccm_cmd = "get %s-mezz_rx_[prbs,rsdec]_error_cnt_rr" % target0

        if self.hb or self.he:
            b2b_cmd = "get %s-[,s]b2b_rx_[prbs,rsdec]_error_cnt_rr" % target0
        else:
            b2b_cmd = ccm_cmd  # HF has no b2b

        if store:
            if fec:
                self.fec1 = self.command(fec_cmd)
            if ccm:
                self.ccm1 = self.command(ccm_cmd)
                self.b2b1 = self.command(b2b_cmd)
            if sleep:
                time.sleep(self.options.nSeconds)

        if fec:
            fec2 = self.command(fec_cmd)
        if ccm:
            ccm2 = self.command(ccm_cmd)
            b2b2 = self.command(b2b_cmd)
        minimal = not store

        if fec and "ERROR" in self.fec1:
            self.bail([""], minimal=minimal, note="fec_err")
        elif ccm and "ERROR" in self.ccm1:
            self.bail([""], minimal=minimal, note="ccm_err")
        elif ccm and "ERROR" in self.b2b1:
            self.bail([""], minimal=minimal, note="ccm_err")
        elif fec and self.fec1 != fec2:
            self.bail(
                ["Link errors detected via FEC counters:", self.fec1, fec2],
                minimal=minimal,
                note="fec_ber")
        elif ccm and self.ccm1 != ccm2:
            self.bail(
                ["Link errors detected via CCM counters:", self.ccm1, ccm2],
                minimal=minimal,
                note="ccm_ber")
        elif ccm and self.b2b1 != b2b2:
            lines = ["Link errors detected via CCM counters:", self.b2b1, b2b2]
            if store or (not self.target.endswith("neigh")):
                self.bail(lines, minimal=minimal, note="b2b_ber")
            else:  # don't exit due to b2b errors generated by using jtag/neigh
                printer.red("\n".join(lines))
Esempio n. 21
0
def main():
    try:
        programmer(*opts())
    except RuntimeError as e:
        printer.red(e[1])
        sys.exit(" ")