def listofdicts_to_table(lod): colnames = list(set(sum([thing.keys() for thing in lod], []))) # key is col name and value is maximum length of any entry in that column d_colsize = {} for thing in lod: for colname in colnames: val = str(thing.get(colname, "")) if colname not in d_colsize: d_colsize[colname] = len(colname) + 1 d_colsize[colname] = max(len(val) + 1, d_colsize[colname]) # sort colnames from longest string lengths to shortest colnames = sorted(colnames, key=d_colsize.get, reverse=True) try: from pytable import Table if not sys.stdout.isatty(): raise Exception tab = Table() tab.set_column_names(colnames) for row in lod: tab.add_row([row.get(colname) for colname in colnames]) tab.sort(column=colnames[0], descending=False) return "".join(tab.get_table_string()) except: buff = "" header = "" for icol, colname in enumerate(colnames): header += ( "%%%s%is" % ("-" if icol == 0 else "", d_colsize[colname])) % colname buff += header + "\n" for thing in lod: line = "" for icol, colname in enumerate(colnames): tmp = "%%%s%is" % ("-" if icol == 0 else "", d_colsize[colname]) tmp = tmp % str(thing.get(colname, "")) line += tmp buff += line + "\n" return buff
def get_table(vals, do_unicode=True, width=80): d = dict(Counter(vals)) maxval = max([d[k] for k in d.keys()]) def shorten(label): return label[:50] maxstrlen = max([len(shorten(k)) for k in d.keys()]) scaleto=width-maxstrlen fillchar = "*" if do_unicode: fillchar = unichr(0x2589).encode('utf-8') tab = Table() for w in sorted(d, key=d.get, reverse=True): nfill = d[w] if maxval < scaleto else max(1,int(float(scaleto)*d[w]/maxval)) strbuff = "{0} ({1})".format(fillchar*nfill,d[w]) shortw = shorten(w) tab.add_row([shortw,strbuff]) return tab
def listofdicts_to_table(lod): colnames = list(set(sum([thing.keys() for thing in lod],[]))) # key is col name and value is maximum length of any entry in that column d_colsize = {} for thing in lod: for colname in colnames: val = str(thing.get(colname,"")) if colname not in d_colsize: d_colsize[colname] = len(colname)+1 d_colsize[colname] = max(len(val)+1, d_colsize[colname]) # sort colnames from longest string lengths to shortest colnames = sorted(colnames, key=d_colsize.get, reverse=True) try: from pytable import Table if not sys.stdout.isatty(): raise Exception tab = Table() tab.set_column_names(colnames) for row in lod: tab.add_row([row.get(colname) for colname in colnames]) tab.sort(column=colnames[0], descending=False) return "".join(tab.get_table_string()) except: buff = "" header = "" for icol,colname in enumerate(colnames): header += ("%%%s%is" % ("-" if icol==0 else "", d_colsize[colname])) % colname buff += header + "\n" for thing in lod: line = "" for icol,colname in enumerate(colnames): tmp = "%%%s%is" % ("-" if icol==0 else "", d_colsize[colname]) tmp = tmp % str(thing.get(colname,"")) line += tmp buff += line + "\n" return buff
def get_table(vals, do_unicode=True, width=80): d = dict(Counter(vals)) maxval = max([d[k] for k in d.keys()]) def shorten(label): return label[:50] maxstrlen = max([len(shorten(k)) for k in d.keys()]) scaleto = width - maxstrlen fillchar = "*" if do_unicode: fillchar = unichr(0x2589).encode('utf-8') tab = Table() for w in sorted(d, key=d.get, reverse=True): nfill = d[w] if maxval < scaleto else max( 1, int(float(scaleto) * d[w] / maxval)) strbuff = "{0} ({1})".format(fillchar * nfill, d[w]) shortw = shorten(w) tab.add_row([shortw, strbuff]) return tab
if __name__ == '__main__': f1 = r.TFile('../StopLooper/output/temp14/allBkg_25ns.root') f2 = r.TFile('../StopLooper/output/temp14/Signal_T2tt.root') f3 = r.TFile('../StopLooper/output/newbin0/allBkg_25ns.root') f4 = r.TFile('../StopLooper/output/newbin0/SMS_T2tt.root') srNames = ['srA', 'srB', 'srC', 'srD', 'srE', 'srF', 'srG', 'srH', 'srI',] bkgs = ['2lep', '1lepW', '1lepTop', 'Znunu'] tab = Table() tab.set_column_names(['srName']+srNames) for bg in bkgs: ylds, errs = getYieldAndErrsFromTopoSRs(f1, srNames, '_'+bg) tab.add_row([bg] + [E(y,e).round(2) for y, e in zip(ylds, errs)]) tab.add_line() bgylds, bgerrs = getYieldAndErrsFromTopoSRs(f1, srNames) bylds_org = [E(y,e).round(2) for y, e in zip(bgylds, bgerrs)] tab.add_row(['Total background'] + bylds_org) tab.add_line() sigylds, sigerrs = getYieldAndErrsFromTopoSRs(f2, srNames, '_1200_50') tab.add_row(['T2tt_1200_50'] + [E(y,e).round(2) for y, e in zip(sigylds, sigerrs)]) # tab.print_table() srNames = ['srA', 'srB', 'srC', 'srD', 'srE', 'srF', 'srG', 'srH'] ntcNames = ['srA1', 'srB1', 'srC1', 'srD1', 'srE1', 'srF1', 'srG1', 'srH1',] wdtNames = ['srA2', 'srB2', 'srC2', 'srD2', 'srE2', 'srF2', 'srG2', 'srH2',] wrtNames = ['srA3', 'srB3', 'srC3', 'srD3', 'srE3', 'srF3', 'srG3', 'srH3',]
def write_table(data, bgs, outname=None, signal=None, extra_hists=[], precision=2, sep=u"\u00B1".encode("utf-8"), binedge_fmt="{}-{}", fix_negative=True, binlabels=[], show_errors=True, cell_callback=None): tab = Table() sumbgs = sum(bgs) databg = data / sumbgs if signal is not None: procs = bgs + [sumbgs, data, databg, signal] cnames = [bg.get_attr("label") for bg in bgs] + ["Total bkg", "Data", "Data/bkg", "tttt"] else: procs = bgs + [sumbgs, data, databg] cnames = [bg.get_attr("label") for bg in bgs] + ["Total bkg", "Data", "Data/bkg"] for eh in extra_hists: procs.append(eh) cnames.append(eh.get_attr("label")) tab.set_column_names(["bin"] + cnames) if outname: sep = "+-" binpairs = zip(data.edges[:-1], data.edges[1:]) #tab.set_theme_basic() tab.set_theme_latex() for ibin, binrow in enumerate(binpairs): row = [("[%s]" % binedge_fmt).format(binrow[0], binrow[1])] if ibin < len(binlabels): row = [binlabels[ibin]] for iproc, proc in enumerate(procs): if fix_negative: cent = max(proc.counts[ibin], 0.) else: cent = proc.counts[ibin] err = proc.errors[ibin] if show_errors: tmp = ("{0:5.%if} {1}{2:%i.%if}" % (precision, precision + 3, precision)).format( cent, sep, err) else: tmp = ("{0:5.%if}" % (precision)).format(cent) if cell_callback: tmp = cell_callback(tmp) row.append(tmp) tab.add_row(row) tab.add_line() row = ["total"] for iproc, proc in enumerate(procs): if iproc == len(procs) - (1 + (signal is not None) + len(extra_hists)): totbg = E(sum(sumbgs.counts), np.sum(sumbgs.errors**2.)**0.5) totdata = E(sum(data.counts)) ratio = totdata / totbg cent, err = ratio[0], ratio[1] precision = max(precision, 2) if precision != 0 else 0 else: cent = sum(proc.counts) err = np.sum(proc.errors**2.)**0.5 if show_errors: tmp = ("{0:5.%if} {1}{2:%i.%if}" % (precision, precision + 3, precision)).format( cent, sep, err) else: tmp = ("{0:5.%if}" % (precision)).format(cent) if cell_callback: tmp = cell_callback(tmp) row.append(tmp) tab.add_row(row) if outname: with open(outname, "w") as fhout: # towrite = "".join(tab.get_table_string(show_row_separators=False,show_alternating=False)) towrite = "".join( tab.get_table_strings(show_row_separators=False, show_alternating=False)) fhout.write(towrite) parts = towrite.split("\n") header = parts[:3] binparts = parts[3:-4] total = parts[-4:-1] table_info = { "header": "<br>".join(header), "bins": binparts, "total": "<br>".join(total) } return table_info return tab