示例#1
0
    def transpose(self, parent, key, axes):
        """
        !tranpose
        """
        int_axes = axes.split(",")
        assert all(s.isdigit() for s in int_axes), (
            "Invalid transpose parameters. "
            "Expected comma separated integers, got {0!r}".format(axes))

        int_axes = tuple(map(int, int_axes))

        # Check for invalid
        assert not any(i >= self.order for i in int_axes), (
            "Transpose beyond available dimensions N={0}, transpose={1}. "
            "No transpose argument is allowed to be >=N."
        ).format(self.order, int_axes)

        complete_ordering = self.get_missing_ordering(int_axes)

        # Build a new indexed_contexts list with the indices re-ordered
        new_contexts = []
        for index_tuple, obj in self.indexed_contexts:
            new_index_tuple = tuple(index_tuple[i] for i in complete_ordering)
            new_contexts.append((new_index_tuple, obj))

        new_ordering = tuple(self.ordering[i] for i in complete_ordering)

        log.error("Transpose, new ordering: {0}".format(new_ordering))

        return MultipleTraverser.from_parent(parent, key, new_contexts,
                                             order=self.order, ordering=new_ordering)
示例#2
0
    def transpose(self, parent, key, axes):
        """
        !tranpose
        """
        int_axes = axes.split(",")
        assert all(s.isdigit() for s in int_axes), (
            "Invalid transpose parameters. "
            "Expected comma separated integers, got {0!r}".format(axes))

        int_axes = tuple(map(int, int_axes))

        # Check for invalid
        assert not any(i >= self.order for i in int_axes), (
            "Transpose beyond available dimensions N={0}, transpose={1}. "
            "No transpose argument is allowed to be >=N.").format(
                self.order, int_axes)

        complete_ordering = self.get_missing_ordering(int_axes)

        # Build a new indexed_contexts list with the indices re-ordered
        new_contexts = []
        for index_tuple, obj in self.indexed_contexts:
            new_index_tuple = tuple(index_tuple[i] for i in complete_ordering)
            new_contexts.append((new_index_tuple, obj))

        new_ordering = tuple(self.ordering[i] for i in complete_ordering)

        log.error("Transpose, new ordering: {0}".format(new_ordering))

        return MultipleTraverser.from_parent(parent,
                                             key,
                                             new_contexts,
                                             order=self.order,
                                             ordering=new_ordering)
示例#3
0
 def keys(self):
     log.error("{0}".format(self.object_types))
     if any(hasattr(t, "keys") for t in self.object_types):
         keys = [set(x.keys()) for n, x in self.stack if hasattr(x, "keys")]
         result = reduce(set.union, keys, set())
         log.error("--- {0}".format(result))
         return result
     return []
示例#4
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)
示例#5
0
    def compose(self, parent, key, composition_type):
        """
        !compose/composition_type
        Compose the first axis into a set of combination objects in terms of the other axes
        """

        i_to_yank = -1

        assert len(self.indexed_contexts), "Nothing to compose!"

        def yank_index(index, what):
            return what[index], what[:index] + what[index:][1:]

        to_compose = {}
        for index_tuple, o in self.indexed_contexts:
            index, new_index_tuple = yank_index(i_to_yank, index_tuple)
            to_compose.setdefault(new_index_tuple, []).append((index, o))

        cardinals = list(range(len(index_tuple)))
        _, cardinals = yank_index(i_to_yank, cardinals)

        new_contexts = []
        for index_tuple, stack in sorted(to_compose.iteritems()):
            filled = self.fill_slots(zip(cardinals, index_tuple))["!compose"]
            composed = Combination.from_parent(filled, key, stack,
                                               composition_type)
            new_contexts.append((index_tuple, composed))

        if self.order == 1:
            assert len(new_contexts) == 1
            idx, composition = new_contexts[0]
            assert idx == ()
            return composition

        _, new_ordering = yank_index(i_to_yank, self.ordering)

        log.error("New ordering after compose = {0}".format(new_ordering))

        # Otherwise build a multitraverser whose order is reduced by one.
        return MultipleTraverser.from_parent(parent,
                                             composition_type,
                                             new_contexts,
                                             order=self.order - 1,
                                             ordering=new_ordering)
示例#6
0
    def compose(self, parent, key, composition_type):
        """
        !compose/composition_type
        Compose the first axis into a set of combination objects in terms of the other axes
        """

        i_to_yank = -1

        assert len(self.indexed_contexts), "Nothing to compose!"

        def yank_index(index, what):
            return what[index], what[:index] + what[index:][1:]

        to_compose = {}
        for index_tuple, o in self.indexed_contexts:
            index, new_index_tuple = yank_index(i_to_yank, index_tuple)
            to_compose.setdefault(new_index_tuple, []).append((index, o))

        cardinals = list(range(len(index_tuple)))
        _, cardinals = yank_index(i_to_yank, cardinals)

        new_contexts = []
        for index_tuple, stack in sorted(to_compose.iteritems()):
            filled = self.fill_slots(zip(cardinals, index_tuple))["!compose"]
            composed = Combination.from_parent(filled, key, stack, composition_type)
            new_contexts.append((index_tuple, composed))

        if self.order == 1:
            assert len(new_contexts) == 1
            idx, composition = new_contexts[0]
            assert idx == ()
            return composition

        _, new_ordering = yank_index(i_to_yank, self.ordering)

        log.error("New ordering after compose = {0}".format(new_ordering))

        # Otherwise build a multitraverser whose order is reduced by one.
        return MultipleTraverser.from_parent(parent, composition_type, new_contexts,
                                             order=self.order - 1, ordering=new_ordering)
示例#7
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)
示例#8
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.")
         
     if self.format == "parentage":
         contents = []
         from pyramid.location import lineage
         for element in lineage(self):
             contents.append(str(element))
         return Response("\n".join(contents), content_type="text/plain")
 
     print "Rendering..", 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)
             alive = []       
             self.render(canvas, alive.append)
             
             if self.format == "xml":
                 # TODO(pwaller): special case
                 raise NotImplementedError()
             
             canvas.Update()
             print "Saving to", tmpfile.name
             canvas.SaveAs(tmpfile.name)
             
         # TODO(pwaller): figure out why these two lines are preventing
         #                 blank images. (wtf?)
         # Response(pwaller): global canvas lock seems to have fixed the 
         #                    problem, but it's still a black box.
         # with open(tmpfile.name) as eps_fd: epsdata = eps_fd.read()
         
         log.error("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)
示例#9
0
    def render(self, canvas, keep_alive):
        
        params = self.request.params
        names, histograms = zip(*self.resource_to_render.stack)
        #print "Rendering stack with {0} histograms".format(len(histograms))
        
        names = [n for n in names]
        histograms = [h for h in histograms]
        objs = [h.obj for h in histograms]

        if "sum" in params:

            hsum = objs[0].Clone("sum")
            keep_alive(hsum)
            hsum.SetTitle("sum")

            for h in objs[1:]:
                hsum.Add(h)

            names.append("sum")
            objs.append(hsum)
        
        colordict = {
            "all"   :R.kBlue,
            "signal":R.kGreen,
            "fake"  :R.kRed,
        }
        
        for name, obj, col in zip(names, objs, [R.kBlue, R.kRed, R.kGreen, R.kBlack, R.kBlack, R.kBlack]):
            #obj.SetTitle(""); obj.SetStats(False)
            if name in colordict:
                obj.SetLineColor(colordict[name])
            else:
                obj.SetLineColor(col)
            obj.SetMarkerColor(col)
            obj.SetLineWidth(2)
        
        if "shape" in params:
            for obj in objs:
                if obj.Integral():
                    obj.Scale(1. / obj.Integral())
        
        max_value = max(o.GetMaximum() for o in objs) * 1.1
        
        
        obj = objs[0] #.pop(0)
        from root.histogram import build_draw_params
        dp = "hist e0x0" #build_draw_params(obj, self.request.params, True)
        
        obj.Draw(dp)
        obj.SetMaximum(max_value)
        #obj.SetMinimum(0)
        
        for obj in objs[1:]:
            obj.Draw(dp + " same")
        
        logy = canvas.GetLogy()
        canvas.SetLogy(False)
        canvas.Update()
        canvas_yrange = ymin, ymax = canvas.GetUymin(), canvas.GetUymax()
        canvas.SetLogy(logy)
        canvas.Update()
        
        def line(x, yrange):
            ymin, ymax = yrange
            args = x, ymin, x, ymax
            l = R.TLine(*args)
            l.SetLineWidth(3); l.SetLineStyle(2)
            l.Draw()
            keep_alive(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, yrange in zip(cuts[slot], zip(etabins, etabins[1:])):
                if canvas.GetUxmin() < x < canvas.GetUxmax():
                    line(x, canvas_yrange if obj.GetDimension() != 2 else yrange)
        
        
        
        
        if self.request.params.get("legend", None) is not None:
            log.error("Drawing legend: {0}".format(objs))
            for n, o in zip(names, objs):
                o.SetTitle(n)
            legend = get_legend(mc=objs)
            legend.Draw()
            keep_alive(legend)
            
        return
        
        if "unit_fixup" in params:
            h = fixup_hist_units(h)
        
        if "nostat" in params:
            h.SetStats(False)
        
        if "notitle" in params:
            h.SetTitle("")
        
        # TODO(pwaller): bring back draw options
        h.Draw()