Exemple #1
0
    def content(self):
        # TODO(pwaller): Remove defunct raise/parentage
        if self.format == "raise":
            class UserThrow(RuntimeError):
                pass
            raise UserThrow("Stopping because you asked me to.")

        log.debug("Rendering {0} from {1}".format(self.format, self))
        params = self.params
        params.update(self.request.params)

        resolution = int(params.get("resolution", self.RESOLUTION_DEFAULT))
        resolution = min(resolution, self.RESOLUTION_MAX)

        rootformat = "eps"
        if self.format == "pdf":
            rootformat = "pdf"

        with NamedTemporaryFile(suffix="." + rootformat) as tmpfile:
            with self.canvas as canvas:
                self.configure_canvas(params, canvas)
                self.render(canvas)

                canvas.Update()
                try:
                    canvas.SaveAs(tmpfile.name)
                except ROOTError as err:
                    if "illegal number of points" in err.msg:
                        log.warning('problem plotting canvas "%s", error from ROOT "%s"',
                                    canvas.GetName(), err.msg)
                    else:
                        raise

            log.info("RENDERING {0} -- {1}".format(self.format, rootformat))
            if self.format == rootformat:
                # No conversion necessary, ROOT did it directly.
                # grab the file from disk
                with open(tmpfile.name) as eps_fd:
                    content = eps_fd.read()
            else:
                # convert_eps releases the GIL by doing the work off-process.
                # This is where the speed comes from.
                content = convert_eps(tmpfile.name, resolution, self.format)

            # print "Made EPS: {0:5.2f} content = {1:5.2f}".format(len(epsdata) /
            # 1024., len(content) / 1024.)

            extra_args = {}
            if "attach" in params:
                log.error("Attaching rendered image")
                # Give the file a sensible name, rather than the last fragment
                # of the URL which was visited.
                extra_args.update(content_disposition=(
                    "Content-Disposition: attachment; filename={0};"
                    .format(self.filename)))

            return Response(content,
                            content_type="image/{0}".format(self.format), **extra_args)
Exemple #2
0
    def render(self, canvas):

        params = self.request.params
        names, histograms = zip(*self.resource_to_render.stack)
        # print "Rendering stack with {0} histograms".format(len(histograms))

        objs = [h.obj for h in histograms]

        colordict = {
            "all": R.kBlue,
            "signal": R.kGreen,
            "fake": R.kRed,
        }

        from ROOT import (kAzure, kBlue, kWhite, kRed, kBlack, kGray, kGreen,
                          kYellow, kTeal, kCyan, kMagenta, kSpring)
        clrs = [
            kWhite, kGreen, kYellow, kBlue, kCyan, kMagenta, kBlack, kGray,
            kRed, kAzure
        ]

        mc = []
        signals = []
        data = []
        name_of = {}

        def is_data(h, name):
            # log.info("Got histogram: {0} - {1}".format(h.GetName(), name))
            # return h.GetTitle().lower().startswith("data")
            return "data" in name

        def is_signal(h):
            return h.GetTitle().lower().startswith("higgs")

        for name, obj in zip(names, objs):
            name_of[obj] = name
            obj.SetStats(False)
            if not obj.GetTitle():
                obj.SetTitle(name.replace(".root", ""))
            if is_data(obj, name):
                data.append(obj)
            elif is_signal(obj):
                signals.append(obj)
            else:
                mc.append(obj)

            # obj.SetFillStyle(1001)

        for h in data:
            h.SetMarkerStyle(20)
            h.SetMarkerSize(1.2)
            h.SetFillStyle(0)

        mc.sort(key=lambda h: h.GetMaximum())
        for h, col in zip(reversed(mc), clrs):
            if name_of[h] in colordict:
                col = colordict[name_of[h]]
            log.warning("Giving %s the color %s" % (name_of[h], col))
            h.SetMarkerColor(col)
            h.SetLineColor(R.kBlack)
            h.SetLineWidth(2)
            h.SetFillColor(col)
            h.SetFillStyle(1001)

        for h, col in zip(reversed(signals), (R.kRed, R.kBlue, R.kGreen)):
            h.SetLineColor(col)
            h.SetLineWidth(2)
            h.SetLineStyle(2)

        # get min/max
        ymax = sum(h.GetMaximum() for h in mc)
        ymin = sum(h.GetMinimum() for h in mc)
        if data or signals:
            ymax = max(ymax, max(h.GetMaximum() for h in data + signals))
            ymin = min(ymin, min(h.GetMinimum() for h in data + signals))
        ymax += 1
        ymax *= (1.5 if not canvas.GetLogy() else 120)
        ymin = max(5e-1, ymin)

        # Create Stack of MC
        mcstack = R.THStack()
        for h in mc:
            mcstack.Add(h)
        keepalive(canvas, mcstack)

        axis = None
        mc_sum_line, mc_sum_error = None, None
        if mc:
            axis = mcstack
            mcstack.Draw("Hist")
            mc_sum_line, mc_sum_error = create_mc_sum(mc)
            keepalive(canvas, mc_sum_line)
            keepalive(canvas, mc_sum_error)

        for signal in signals:
            if mc:
                signal.Add(mc_sum_line)
            if not axis:
                axis = signal
                signal.Draw("hist")
            else:
                signal.Draw("hist same")

        if mc:
            mc_sum_error.Draw("e2same")
            mc_sum_line.Draw("hist same")

        for d in data:
            if not axis:
                axis = d
                d.Draw("pe")
            else:
                d.Draw("pe same")

        axis.SetMaximum(ymax)
        axis.SetMinimum(ymin)
        axis.GetXaxis().SetRange(objs[0].GetXaxis().GetFirst(),
                                 objs[0].GetXaxis().GetLast())
        axis.GetXaxis().SetTitle(objs[0].GetXaxis().GetTitle())
        if not self.request.params.get("xlabel", None) is None:
            axis.GetXaxis().SetTitle(self.request.params["xlabel"])
        if not self.request.params.get("ylabel", None) is None:
            axis.GetYaxis().SetTitle(self.request.params["ylabel"])

        logy = canvas.GetLogy()
        canvas.SetLogy(False)
        canvas.Update()
        ymin, ymax = canvas.GetUymin(), canvas.GetUymax()
        canvas.SetLogy(logy)
        canvas.Update()

        def line(x):
            args = x, ymin, x, ymax
            l = R.TLine(*args)
            l.SetLineWidth(1)
            l.SetLineStyle(2)
            l.Draw()
            keepalive(canvas, l)

        # Draw cuts
        slot = self.request.params.get("slot", None)
        if not slot:
            # Determine slot from path
            for p in lineage(self):
                if p.__name__ in cuts:
                    slot = p.__name__

        if slot:
            for x in set(cuts[slot]):
                if canvas.GetUxmin() < x < canvas.GetUxmax():
                    line(x)

        if not self.request.params.get("legend", None) is None:
            legend = get_legend(mc=mc,
                                data=data,
                                signal=signals,
                                mc_sum=mc_sum_error)
            legend.Draw()

        if not self.request.params.get("lumi", None) is None:
            label = get_lumi_label(lumi=self.request.params["lumi"])
            label.Draw()

        p = preliminary()
        p.Draw("hist e0x0")
Exemple #3
0
    def content(self):
        # TODO(pwaller): Remove defunct raise/parentage
        if self.format == "raise":

            class UserThrow(RuntimeError):
                pass

            raise UserThrow("Stopping because you asked me to.")

        log.debug("Rendering {0} from {1}".format(self.format, self))
        params = self.params
        params.update(self.request.params)

        resolution = int(params.get("resolution", self.RESOLUTION_DEFAULT))
        resolution = min(resolution, self.RESOLUTION_MAX)

        rootformat = "eps"
        if self.format == "pdf":
            rootformat = "pdf"

        with NamedTemporaryFile(suffix="." + rootformat) as tmpfile:
            with self.canvas as canvas:
                self.configure_canvas(params, canvas)
                self.render(canvas)

                canvas.Update()
                try:
                    canvas.SaveAs(tmpfile.name)
                except ROOTError as err:
                    if "illegal number of points" in err.msg:
                        log.warning(
                            'problem plotting canvas "%s", error from ROOT "%s"',
                            canvas.GetName(), err.msg)
                    else:
                        raise

            log.info("RENDERING {0} -- {1}".format(self.format, rootformat))
            if self.format == rootformat:
                # No conversion necessary, ROOT did it directly.
                # grab the file from disk
                with open(tmpfile.name) as eps_fd:
                    content = eps_fd.read()
            else:
                # convert_eps releases the GIL by doing the work off-process.
                # This is where the speed comes from.
                content = convert_eps(tmpfile.name, resolution, self.format)

            # print "Made EPS: {0:5.2f} content = {1:5.2f}".format(len(epsdata) /
            # 1024., len(content) / 1024.)

            extra_args = {}
            if "attach" in params:
                log.error("Attaching rendered image")
                # Give the file a sensible name, rather than the last fragment
                # of the URL which was visited.
                extra_args.update(content_disposition=(
                    "Content-Disposition: attachment; filename={0};".format(
                        self.filename)))

            return Response(content,
                            content_type="image/{0}".format(self.format),
                            **extra_args)
Exemple #4
0
    def render(self, canvas):

        params = self.request.params
        names, histograms = zip(*self.resource_to_render.stack)
        # print "Rendering stack with {0} histograms".format(len(histograms))

        objs = [h.obj for h in histograms]

        colordict = {
            "all": R.kBlue,
            "signal": R.kGreen,
            "fake": R.kRed,
        }

        from ROOT import (kAzure, kBlue, kWhite, kRed, kBlack, kGray,
                          kGreen, kYellow, kTeal, kCyan, kMagenta, kSpring)
        clrs = [kWhite, kGreen, kYellow, kBlue, kCyan,
                kMagenta, kBlack, kGray, kRed, kAzure]

        mc = []
        signals = []
        data = []
        name_of = {}

        def is_data(h, name):
            # log.info("Got histogram: {0} - {1}".format(h.GetName(), name))
            # return h.GetTitle().lower().startswith("data")
            return "data" in name

        def is_signal(h):
            return h.GetTitle().lower().startswith("higgs")

        for name, obj in zip(names, objs):
            name_of[obj] = name
            obj.SetStats(False)
            if not obj.GetTitle():
                obj.SetTitle(name.replace(".root", ""))
            if is_data(obj, name):
                data.append(obj)
            elif is_signal(obj):
                signals.append(obj)
            else:
                mc.append(obj)

            # obj.SetFillStyle(1001)

        for h in data:
            h.SetMarkerStyle(20)
            h.SetMarkerSize(1.2)
            h.SetFillStyle(0)

        mc.sort(key=lambda h: h.GetMaximum())
        for h, col in zip(reversed(mc), clrs):
            if name_of[h] in colordict:
                col = colordict[name_of[h]]
            log.warning("Giving %s the color %s" % (name_of[h], col))
            h.SetMarkerColor(col)
            h.SetLineColor(R.kBlack)
            h.SetLineWidth(2)
            h.SetFillColor(col)
            h.SetFillStyle(1001)

        for h, col in zip(reversed(signals), (R.kRed, R.kBlue, R.kGreen)):
            h.SetLineColor(col)
            h.SetLineWidth(2)
            h.SetLineStyle(2)

        # get min/max
        ymax = sum(h.GetMaximum() for h in mc)
        ymin = sum(h.GetMinimum() for h in mc)
        if data or signals:
            ymax = max(ymax, max(h.GetMaximum() for h in data + signals))
            ymin = min(ymin, min(h.GetMinimum() for h in data + signals))
        ymax += 1
        ymax *= (1.5 if not canvas.GetLogy() else 120)
        ymin = max(5e-1, ymin)

        # Create Stack of MC
        mcstack = R.THStack()
        for h in mc:
            mcstack.Add(h)
        keepalive(canvas, mcstack)

        axis = None
        mc_sum_line, mc_sum_error = None, None
        if mc:
            axis = mcstack
            mcstack.Draw("Hist")
            mc_sum_line, mc_sum_error = create_mc_sum(mc)
            keepalive(canvas, mc_sum_line)
            keepalive(canvas, mc_sum_error)

        for signal in signals:
            if mc:
                signal.Add(mc_sum_line)
            if not axis:
                axis = signal
                signal.Draw("hist")
            else:
                signal.Draw("hist same")

        if mc:
            mc_sum_error.Draw("e2same")
            mc_sum_line.Draw("hist same")

        for d in data:
            if not axis:
                axis = d
                d.Draw("pe")
            else:
                d.Draw("pe same")

        axis.SetMaximum(ymax)
        axis.SetMinimum(ymin)
        axis.GetXaxis().SetRange(objs[0].GetXaxis().GetFirst(), objs[0].GetXaxis().GetLast())
        axis.GetXaxis().SetTitle(objs[0].GetXaxis().GetTitle())
        if not self.request.params.get("xlabel", None) is None:
            axis.GetXaxis().SetTitle(self.request.params["xlabel"])
        if not self.request.params.get("ylabel", None) is None:
            axis.GetYaxis().SetTitle(self.request.params["ylabel"])

        logy = canvas.GetLogy()
        canvas.SetLogy(False)
        canvas.Update()
        ymin, ymax = canvas.GetUymin(), canvas.GetUymax()
        canvas.SetLogy(logy)
        canvas.Update()

        def line(x):
            args = x, ymin, x, ymax
            l = R.TLine(*args)
            l.SetLineWidth(1)
            l.SetLineStyle(2)
            l.Draw()
            keepalive(canvas, l)

        # Draw cuts
        slot = self.request.params.get("slot", None)
        if not slot:
            # Determine slot from path
            for p in lineage(self):
                if p.__name__ in cuts:
                    slot = p.__name__

        if slot:
            for x in set(cuts[slot]):
                if canvas.GetUxmin() < x < canvas.GetUxmax():
                    line(x)

        if not self.request.params.get("legend", None) is None:
            legend = get_legend(mc=mc, data=data, signal=signals, mc_sum=mc_sum_error)
            legend.Draw()

        if not self.request.params.get("lumi", None) is None:
            label = get_lumi_label(lumi=self.request.params["lumi"])
            label.Draw()

        p = preliminary()
        p.Draw("hist e0x0")