Beispiel #1
0
    print 'old:', get_bin_centers(bins)
    new_centers = barycenters(h_truth_finebinned, h_truth)
    print 'centre of mass:', new_centers
    new_centers = calculate_correct_x_coordinates(h_truth_finebinned, bins)
    print 'correct:', new_centers
    data = list(h_truth.y())
    h_truth_new = Hist(new_centers)
    bin_widths = [25, 20, 25, 30, 1000]
    g_truth_new = Graph(len(new_centers))
    for i, (x, y, width) in enumerate(zip(new_centers, data, bin_widths)):
        g_truth_new.SetPoint(i, x, y / width)
        error = h_truth.GetBinError(i + 1)
        g_truth_new.SetPointError(i, 0, 0, error, error)

    for bin_i in range(len(data)):
        h_truth_new.SetBinContent(bin_i + 1, data[bin_i] / bin_widths[bin_i])
        h_truth.SetBinContent(bin_i + 1, data[bin_i] / bin_widths[bin_i])

    h_truth_finebinned.SetFillStyle(0)
    h_truth_finebinned.Smooth(500)
    x, y = list(h_truth_finebinned.x()), list(h_truth_finebinned.y())
    bin_edges = np.array(list(h_truth_finebinned.xedges()))
    bincenters = 0.5 * (bin_edges[1:] + bin_edges[:-1])
    g_truth = Graph(h_truth)
    #    g_truth_new = Graph(len(h_truth), h_truth_new)
    g_truth_new.SetLineColor('red')
    g_truth_new.SetMarkerColor('red')
    h_truth_finebinned.axis().SetRange(0, 1000)
    h_truth_finebinned.linecolor = 'orange'
    plt.figure(figsize=(16, 10), dpi=100)
    axes = plt.axes()
Beispiel #2
0
def _project(tree,
             var,
             selection='',
             weight=1.0,
             bins=None,
             includeover=False):

    h = None
    if var.count(':') == 0:
        ## Hist (1D)
        if bins:
            if isinstance(bins, tuple):
                assert len(bins) == 3
                h = Hist(*bins)
            elif isinstance(bins, list):
                h = Hist(bins)
            else:
                assert False
        else:
            assert False
    elif var.count(':') == 1:
        ## Hist2D
        ## like rootpy, we use a convention where var=x:y, unlike ROOT
        varx, vary = var.split(':')
        var = ':'.join([vary, varx])
        if bins:
            if isinstance(bins, tuple):
                assert len(bins) == 6
                h = Hist2D(*bins)
            elif isinstance(bins, list):
                ## TODO: support variable bins for Hist2D
                h = Hist2D(*bins)
                #assert False
            else:
                assert False
        else:
            assert False
    else:
        assert False

    assert h
    #            kwargs['hist'] = h

    ## add the weight to the selection via a TCut
    weighted_selection = str(selection)
    if weight and weight != 1.0:
        weighted_selection = Cut(weighted_selection)
        weighted_selection = weighted_selection * weight
        weighted_selection = str(weighted_selection)

    tree.Draw('%s>>%s' % (var, h.GetName()), weighted_selection)

    ##    print tree.GetSelectedRows() ## debuging

    #    for event in t:
    #        x = getattr(event, var)
    #        h.fill(x)

    if h:
        h.SetDirectory(0)

        #        elist = ROOT.gDirectory.Get('elist')
        #        elist.Print('all')

        if var.count(':') == 0 and includeover:
            ## include overflow for Hist (1D)
            nbins = h.GetNbinsX()
            c1 = h.GetBinContent(nbins)
            c2 = h.GetBinContent(nbins + 1)
            e1 = h.GetBinError(nbins)
            e2 = h.GetBinError(nbins + 1)
            h.SetBinContent(nbins, c1 + c2)
            h.SetBinError(
                nbins,
                math.sqrt((c1 * e1 * e1 + c2 * e2 * e2) /
                          (c1 + c2)) if c1 + c2 != 0.0 else 0.0)
            h.SetBinContent(nbins + 1, 0.0)
            h.SetBinError(nbins + 1, 0.0)

    return h
Beispiel #3
0
h_t1Shape = Hist(nBins, 0, nBins, title='t1Shape')
h_t2Shape = Hist(nBins, 0, nBins, title='t2Shape')
h_t3Shape = Hist(nBins, 0, nBins, title='t3Shape')
h_t4Shape = Hist(nBins, 0, nBins, title='t4Shape')

h_t1 = Hist(nBins, 0, nBins, title=t1Name)
h_t2 = Hist(nBins, 0, nBins, title=t2Name)
h_t3 = Hist(nBins, 0, nBins, title=t3Name)
h_t4 = Hist(nBins, 0, nBins, title=t4Name)
h_data = Hist(nBins, 0, nBins, title='data')

if useTemplatesFromFile:
    templates = getTemplatesFromFile()

    for bin in range(1, nBins + 1):
        h_t1.SetBinContent(bin, templates[0][bin - 1])
        h_t2.SetBinContent(bin, templates[1][bin - 1])
        h_t3.SetBinContent(bin, templates[2][bin - 1])
        h_t4.SetBinContent(bin, templates[3][bin - 1])
        pass

    h_t1.Scale(absolute_eta_initialValues[t1Name][whichBinFromFile][0])
    h_t2.Scale(absolute_eta_initialValues[t2Name][whichBinFromFile][0])
    h_t3.Scale(absolute_eta_initialValues[t3Name][whichBinFromFile][0])
    h_t4.Scale(absolute_eta_initialValues[t4Name][whichBinFromFile][0])
else:
    # Fill the histograms
    h_t1Shape.SetBinContent(1, 20)
    h_t1Shape.SetBinContent(2, 20)
    h_t1Shape.SetBinContent(3, 20)
    h_t1Shape.SetBinContent(4, 50)
Beispiel #4
0
def make_line_hist(bin_edges, y_value):
    l = Hist(bin_edges, type = 'D')
    for i in range(1, len(bin_edges)):
        l.SetBinContent(i, y_value)
    return l
    h_response = inputFile.unfoldingAnalyserElectronChannel.response_withoutFakes_AsymBins #response_AsymBins
    # h_measured_new = h_measured - h_fakes
    
#    h_response = inputFile.unfoldingAnalyserElectronChannel.response_AsymBins #response_AsymBins
    nEvents = inputFile.EventFilter.EventCounter.GetBinContent(1)
    lumiweight = 164.5 * 5050 / nEvents
    h_truth.Scale(lumiweight)
    h_measured.Scale(lumiweight)
    h_fakes.Scale(lumiweight)
    h_response.Scale(lumiweight)
    unfolding = Unfolding(h_truth, h_measured, h_response, method = method)
    #should be identical to
#    unfolding = Unfolding(h_truth, h_measured, h_response, h_fakes, method = method)
    
    #test values for real data input
    h_data = Hist(bins.tolist())
    h_data.SetBinContent(1, 2146)
    h_data.SetBinError(1, 145)
    h_data.SetBinContent(2, 3399)
    h_data.SetBinError(2, 254)
    h_data.SetBinContent(3, 3723)
    h_data.SetBinError(3, 69)
    h_data.SetBinContent(4, 2256)
    h_data.SetBinError(4, 53)
    h_data.SetBinContent(5, 1722)
    h_data.SetBinError(5, 91)
    
    checkOnMC(unfolding, method)
    doUnfoldingSequence(unfolding, h_data, method)
    print 'Done'
from config.variable_binning import bin_edges_vis
from ROOT import RooUnfoldResponse, RooUnfoldSvd, RooUnfoldBayes
from rootpy import asrootpy
from copy import copy
from math import sqrt
from random import gauss

#
# Use your own test input
#

bins = [0, 10, 15, 30, 60]

# Truth histogram
h_truth = Hist(bins)
h_truth.SetBinContent(1, 400)
h_truth.SetBinContent(2, 400)
h_truth.SetBinContent(3, 100)
h_truth.SetBinContent(4, 5)

# Measured histogram
# If identical to truth (before adding fakes), then there is no inefficiency in your measurement
h_measured = Hist(bins)
h_measured.SetBinContent(1, 400)
h_measured.SetBinContent(2, 400)
h_measured.SetBinContent(3, 100)
h_measured.SetBinContent(4, 5)

# Set data equal to measured for this test
h_data = Hist(bins)
h_data.SetBinContent(1, 400)
            ensure_dir(args.output_folder)
            out_file_path = os.path.join(args.output_folder,
                                         os.path.basename(f) + ".hists")
        if (args.doNotOverwrite and os.path.isfile(out_file_path)): continue
        out_file = root_open(out_file_path, "RECREATE")
        tree = in_file.get(args.treename)
        if (args.hists != None and len(args.hists) > 0):
            out_file.cd()
            for hist in args.hists:
                in_file.Get(hist).Write()
        if args.copy_mbj_cutflow:
            cf = in_file.Get('cut_flow')
            cf2 = Hist(1, 0, 1, name='cutflow')
            cf2.Sumw2()
            cf2.SetEntries(cf.GetBinContent(1))
            cf2.SetBinContent(1, cf.GetBinContent(2))
            cf2.SetBinError(
                1,
                np.sqrt(cf.GetBinContent(1)) * cf.GetBinContent(2) /
                cf.GetBinContent(1))
            allDir = os.path.join(args.outdir, 'all')
            out_file.mkdir(allDir, recurse=True)
            try:
                out_file.cd(allDir)
            except:
                pass
            cf2.Write()

    else:
        out_file = root_open(f, "UPDATE")
        tree = out_file.get(args.treename)
Beispiel #8
0
    def plot(self):

        if self._ratio_plot:
            gs = gridspec.GridSpec(nrows=2, ncols=1, height_ratios=[3, 1], wspace=1.08, hspace=0., bottom=0.12, left=0.18) 
            # gs.update(wspace=0.1, hspace=0.1, left=0.1, right=0.4, bottom=0.1, top=0.9) 
            # gs.update(hspace=0.05) # set the spacing between axes. 
            # gs.update(left=0.05, right=0.48, wspace=0.05)
            # self._plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)

            
            ax0 = self._plt.subplot(gs[0])
            ax1 = self._plt.subplot(gs[1])
        else:
            ax0 = self._plt.gca()

        # Set the logo.lin
        ax0.add_artist(self.logo_box())

        # Set basic plot element formattings. lin
        self.set_formatting()

        # Normalize all the histograms.
        self.normalize_hists()


        z_indices = range(len(self._hists), 0, -1)
        
        if "error" in self._plot_types:
            z_indices[self._plot_types.index("error")] *= 10

        if "theory" in self._plot_types:
            z_indices[self._plot_types.index("theory")] *= 5

        # First, draw the regular "non-ratio" plot.


        legend_handles = []
        for i in range(len(self._hists)):

            plot_type = self._plot_types[i]

            if plot_type == 'hist':

                #print("this is hist")
            
                #self._hists[i].hist().SetLineStyle(self._line_styles[i])

                plot = self._rplt.hist(self._hists[i].hist(), axes=ax0, zorder=z_indices[i], emptybins=False)
                plot[1].set_dashes(self._line_styles[i])
                legend_handles.append( plot )

                # print legend_handles[i][1].get_dashes()
            
            elif plot_type == 'error':
            
                plot = self._rplt.errorbar(self._hists[i].hist(), axes=ax0, zorder=z_indices[i], emptybins=False, xerr=1, yerr=1, ls='None', marker='o', markersize=10, pickradius=8, capthick=5, capsize=8, elinewidth=5, alpha=1.0)
                legend_handles.append( plot )
            
            elif plot_type == "theory":

                if self._x_scale == "log":
                    x_s = np.exp( self._hists[i][0] )
                else:
                    
                    x_s = self._hists[i][0]

                # There are two portions of x. 
                # Find the index where we need to switch.
                np_correction_index = 0
                for ab in range(len(x_s)):
                    if x_s[ab] > self.get_np_correction_boundary():
                        np_correction_index = ab
                        break


                # print np_correction_index, self.get_np_correction_boundary()
                # print x_s
                
                y_line_s = self._hists[i][2]
                y_min_s = self._hists[i][1]
                y_max_s = self._hists[i][3]

                # print x_s[ : np_correction_index]
                # Distribution.
                ax0.plot(x_s[ : np_correction_index + 1], y_line_s[ : np_correction_index + 1], lw=12, zorder=z_indices[i], color=self._plot_colors[i], ls="dotted")


                

                if "Track" not in self._x_label: 
                    ax0.plot(x_s[np_correction_index : ], y_line_s[np_correction_index : ], lw=8, zorder=z_indices[i], color=self._plot_colors[i])
                    ax0.fill_between(x_s[np_correction_index : ], y_max_s[np_correction_index : ], y_min_s[np_correction_index : ], zorder=z_indices[i], where=np.less_equal(y_min_s[np_correction_index : ], y_max_s[np_correction_index : ]), facecolor=self._plot_colors[i], color=self._plot_colors[i], interpolate=True, alpha=0.2, linewidth=0.)
                else:
                    ax0.plot(x_s[np_correction_index : ], y_line_s[np_correction_index : ], ls="dotted", lw=12, zorder=z_indices[i], color=self._plot_colors[i])


                theory_min_interpolate_function = self.extrap1d(interpolate.interp1d(x_s, y_min_s))
                theory_line_interpolate_function = self.extrap1d(interpolate.interp1d(x_s, y_line_s))
                theory_max_interpolate_function = self.extrap1d(interpolate.interp1d(x_s, y_max_s))

                if self._hists[0].x_range() != (0, -1):
                    
                    # This is important for log plots because we don't want to consider the bins that's not visibile while figuring out how many bins to use for theory.



                    # x_s_to_use = filter( lambda x: x >= self._hists[0].x_range()[0], self._plot_points_x_s[self._plot_types.index("error")] )
                    x_s_to_use = self._plot_points_x_s[self._plot_types.index("error")]
                
                else:
                    x_s_to_use = self._plot_points_x_s[self._plot_types.index("error")]


                theory_extrapolated_min = theory_min_interpolate_function(x_s_to_use)
                theory_extrapolated_line = theory_line_interpolate_function(x_s_to_use)
                theory_extrapolated_max = theory_max_interpolate_function(x_s_to_use)

                # print "the data x points were", (x_s_to_use)
                
            if plot_type == "theory":
                self._plot_points_x_s.append( x_s )
                self._plot_points_y_s.append( [] )
            elif plot_type == "error":
                data_points_x = plot[0].get_xdata()
                data_points_y = plot[0].get_ydata()


                data_plot_points_x = []
                data_plot_points_y = []

                for i in range(0, len(data_points_x)):
                    if float(data_points_x[i]) > 0.0:   # This is just to ignore the points at the 0th bin.
                        data_plot_points_x.append(data_points_x[i])
                        data_plot_points_y.append(data_points_y[i])

                data_x_errors, data_y_errors = [], []
                for x_segment in plot[2][0].get_segments():
                    data_x_errors.append((x_segment[1][0] - x_segment[0][0]) / 2.)
                for y_segment in plot[2][1].get_segments():
                    data_y_errors.append((y_segment[1][1] - y_segment[0][1]) / 2.)

                self._plot_points_x_s.append( data_plot_points_x )
                self._plot_points_y_s.append( data_plot_points_y )

            elif plot_type == "hist":

                
                bin_width = (self._hists[i].hist().upperbound() - self._hists[i].hist().lowerbound()) / self._hists[i].hist().nbins()

                if self._x_scale != "log":
                    data_points_x = [x + bin_width / 2 for x in plot[1].get_xdata()][:-1]
                else:
                    data_points_x = plot[1].get_xdata()[:-1]
                
                data_points_y = plot[1].get_ydata()

                data_plot_points_x = []
                data_plot_points_y = []

                for i in range(0, len(data_points_x)):
                    if float(data_points_x[i]) > 0.0:   # This is just to ignore the points at the 0th bin.
                        data_plot_points_x.append(data_points_x[i])
                        data_plot_points_y.append(data_points_y[i])

                self._plot_points_x_s.append( data_plot_points_x )
                self._plot_points_y_s.append( data_plot_points_y )
                


        if self._y_scale == 'log':
            ax0.set_yscale('log')
            pass


        # Ratio plot.

        if self._ratio_plot:

            if (type(self._ratio_to_index) == dict) or (type(self._ratio_to_index) == int and self._plot_types[self._ratio_to_index] == "hist" or self._plot_types[self._ratio_to_index] == "error"):
                # print "ratio to something else"

                
                for i in range(len(self._hists)):
                    
                    if type(self._ratio_to_index) == int:
                        denominator_hist = self._hists[self._ratio_to_index].hist()
                    elif type(self._ratio_to_index) == dict:
                        denominator_hist = self._hists[self._ratio_to_index[i]].hist()

                    plot_type = self._plot_types[i]

                    ratio_hist = copy.deepcopy( self._hists[i].hist() )

                    #print(ratio_hist.lowerbound())
                    divided_hist = Hist(len(ratio_hist), ratio_hist.lowerbound(), ratio_hist.upperbound())
                    for k in range(len(ratio_hist)):
                        num_val = ratio_hist.GetBinContent(k)
                        denom_val = denominator_hist.GetBinContent(k)
                        #print(i, num_val, denom_val)
                        num_err = ratio_hist.GetBinError(k)
                        denom_err = denominator_hist.GetBinError(k)
                        if denom_val != 0.0:
                            divided_hist.SetBinContent(k+1, num_val*1.0/denom_val)
                            print(i, num_val*1.0/denom_val)
                        if denom_err != 0.0:
                            divided_hist.SetBinError(k+1, num_err*1.0/denom_val)
                            print(i, num_err*1.0/denom_val)


                    divided_hist.SetColor(self._plot_colors[i])
                    #ratio_hist.Divide(denominator_hist)
                    
                    if plot_type == 'hist':
                        plot = self._rplt.hist(divided_hist, axes=ax1, zorder=z_indices[i], emptybins=False, lw=8)
                        print("i", i)
                        plot[1].set_dashes(self._line_styles[i])


                    elif plot_type == 'error':
                        self._rplt.errorbar(divided_hist, axes=ax1, zorder=z_indices[i], emptybins=False, ls='None', marker='o', markersize=10, pickradius=8, capthick=5, capsize=8, elinewidth=5, alpha=1.0)
                        
                        
        # Ratio plot ends.


        handles, labels = legend_handles, self._plot_labels

        handler_map = {}
        if "theory" in self._plot_types:
            
            

            if "Track" not in self._x_label: 
                th_line, = ax0.plot(range(1), linewidth=8, color='red')
                th_patch = mpatches.Patch(facecolor='red', alpha=0.2, linewidth=0., edgecolor='red')

                handles.insert( self._plot_types.index("theory"), (th_patch, th_line))
            else:
                th_line, = ax0.plot(range(1), linewidth=12, ls="dotted", color='red')
                handles.insert( self._plot_types.index("theory"), (th_line, ))
            
            # labels.insert( self._plot_types.index("theory"), self._plot_labels[self._plot_types.index("theory")])

            handler_map[th_line ] = HandlerLine2D(marker_pad=0)

        for i in range(len(handles)):
            if self._plot_types[i] == "hist":
                line, = ax0.plot(range(1), linewidth=8, color=self._plot_colors[i], dashes=self._line_styles[i])
                handles[i] = line

                handler_map[line] = HandlerLine2D(marker_pad=0)
        



        legend = ax0.legend(handles, labels, frameon=0, fontsize=50, handler_map=handler_map, bbox_to_anchor=self._legend_location[1], loc=self._legend_location[0] )
        # legend = ax0.legend(handles, labels, frameon=0, fontsize=60, handler_map=handler_map, bbox_to_anchor=self._legend_location, loc="upper left" )
        ax0.add_artist(legend)

        # Any additional texts.
        extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)
        # ax0.legend([extra]*len(labels), labels, loc=7, frameon=0, borderpad=0.1, fontsize=60, bbox_to_anchor=[1.00, 0.53])


        # get the width of your widest label, since every label will need 
        #to shift by this amount after we align to the right
        shift = max([t.get_window_extent(plt.gcf().canvas.get_renderer()).width for t in legend.get_texts()])


        if self._text_outside_the_frame:
            outside_text = ax0.legend( [extra], ["CMS 2011 Open Data"], frameon=0, borderpad=0, fontsize=50, bbox_to_anchor=(1.0, 1.005), loc='lower right')
            ax0.add_artist(outside_text)

        
        if "Soft Drop" in self._plot_labels[0]:
            additional_text =  self._hists[1].additional_text()
        else:
            additional_text = self._hists[0].additional_text()

        for position, anchor_location, text in additional_text:
            texts = text.split("\n")
            additional_info = ax0.legend( [extra] * len(texts), texts, frameon=0, borderpad=0, fontsize=50, bbox_to_anchor=position, loc=anchor_location)

            if position[0] > 0.30:
                for t in additional_info.get_texts():
                    t.set_ha('right') # ha is alias for horizontalalignment
                    t.set_position((shift,0))
                
            
        # if len()

        

        # Axes labels.

        # ax0.set_xlabel(self._x_label, fontsize=60)

        # if "$" in self._y_label:
        if self._y_label[0] == "$":
            ax0.set_ylabel(self._y_label, fontsize=105, y=0.5, rotation=0, labelpad=120)
        else:
            ax0.set_ylabel(self._y_label, fontsize=65, y=0.5, labelpad=50)

        if self._ratio_plot:
            ax1.set_xlabel(self._x_label, fontsize=70, labelpad=35)
            ax1.set_ylabel(self._ratio_label, fontsize=55, labelpad=25)
        else:
            ax0.set_xlabel(self._x_label, fontsize=70, labelpad=35)

        # Axes labels end.


        self._plt.sca(ax0)

        self._plt.tick_params(which='major', width=5, length=25, labelsize=70)
        self._plt.tick_params(which='minor', width=3, length=15)

        if self._ratio_plot:
            self._plt.sca(ax1)
            
            self._plt.tick_params(which='major', axis='x', width=5, length=25, labelsize=70)
            self._plt.tick_params(which='major', axis='y', width=5, length=25, labelsize=45)

            self._plt.tick_params(which='minor', width=3, length=15)



        if self._ratio_plot:
            self._plt.gcf().set_size_inches(30, 24, forward=1)
        else:
            self._plt.gcf().set_size_inches(30, 24, forward=1)

        
        
        
        self._plt.sca(ax0)
        self._plt.autoscale()
        self._plt.xscale(self._x_scale)
        self._plt.gca().xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())


        if self._ratio_plot:
            self._plt.sca(ax1)
            self._plt.autoscale()
            self._plt.xscale(self._x_scale)
            self._plt.gca().xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())

            self._plt.sca(ax0)
            self._plt.gca().get_xaxis().set_ticklabels([])

            

        if self._x_lims[1] == -1:
            ax0.set_xlim( self._x_lims[0], ax0.get_xlim()[1] )
        else:
            ax0.set_xlim( self._x_lims[0], self._x_lims[1] )

        if self._y_lims[1] == -1:
            ax0.set_ylim( self._y_lims[0], ax0.get_ylim()[1] * 1.125 )
        else:
            # print self._y_lims[0], self._y_lims[1]
            ax0.set_ylim( self._y_lims[0], self._y_lims[1] )

        if self._ratio_plot:
            ax1.set_xlim( ax0.get_xlim()[0], ax0.get_xlim()[1] )
            ax1.set_ylim(0., 2.5)

        if self._hists[0].axes_label_pi():
            plt.sca(ax0)
            plt.gca().set_xticks( [0, round(0.5*np.pi, 3), round(np.pi, 3), round(1.5*np.pi, 3), round(2*np.pi, 3)] )
            plt.gca().set_xticklabels( ["0", "$\pi / 2$", "$\pi$", "$3 \pi / 2$", "$2 \pi$"] )

            if self._ratio_plot:
                plt.sca(ax1)
                plt.gca().set_xticks( [0, round(0.5*np.pi, 3), round(np.pi, 3), round(1.5*np.pi, 3), round(2*np.pi, 3)] )
                plt.gca().set_xticklabels( ["0", "$\pi / 2$", "$\pi$", "$3 \pi / 2$", "$2 \pi$"] )          

                plt.sca(ax0)
                plt.gca().set_xticklabels( [] )


        if self._x_scale == "log":
            if self._ratio_plot:
                self._plt.sca(ax1)
                # ax1.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.0e'))
                ax1.xaxis.set_major_formatter(mpl.ticker.ScalarFormatter(useMathText=False))

            self._plt.sca(ax0)

            # print self._plt.gca().get_xlim()

            

            upper_lim = self._plt.gca().get_xlim()[1]
            lower_lim = self._plt.gca().get_xlim()[0]

            # print lower_lim

            if lower_lim < 0.01:
                denominations = [9] # 1 + 9 = 10.
            else:
                denominations = [1, 3, 5] # 1 + 1 = 2; 2 + 3 = 5; 5 + 5 = 10. 

            multiplier = lower_lim

            count = 0
            x_ticks = [lower_lim]
            
            # print abs(x_ticks[-1] - upper_lim) > 1e-6
    

            if float(upper_lim) <= 5.:

                while abs(x_ticks[-1] - upper_lim) > 1e-6:
                    
            
                    x_ticks.append( x_ticks[-1] + denominations[count] * multiplier )

                    # print x_ticks[-1] + denominations[count] * multiplier
                    
                    if count == (len(denominations) - 1):
                        count = 0
                        multiplier = x_ticks[-1]
                    else:
                        count += 1

                    # print x_ticks[-1]
            else:
                # print abs(x_ticks[-1] - upper_lim)
                # while abs(x_ticks[-1] - upper_lim) > 20:
                    
                #   x_ticks.append( x_ticks[-1] + denominations[count] * multiplier )

                #   # print x_ticks[-1] + denominations[count] * multiplier
                    
                #   if count == 2:
                #       count = 0
                #       multiplier = x_ticks[-1]
                #   else:
                #       count += 1
                pass

                x_ticks = [100, 200, 500, 1000, 2000]



            # print x_ticks
            self._plt.xticks(x_ticks)

            if self._ratio_plot:
                self._plt.sca(ax1)
                self._plt.xticks(x_ticks)


        if self._ratio_plot:
            self._plt.sca(ax1)
            self._plt.gca().get_yaxis().set_ticks( [ x for x in self._plt.gca().get_yaxis().get_majorticklocs() if x < 2.5 and x > 0.] )
        
        # Minor ticks.
        if not self._x_scale == "log":
            if len(ax0.get_xaxis().get_majorticklocs()) >= 2:
                factor = abs(ax0.get_xaxis().get_majorticklocs()[1] - ax0.get_xaxis().get_majorticklocs()[0]) / 10
                
                ax0.xaxis.set_minor_locator(MultipleLocator(factor))

                if self._ratio_plot:
                    ax1.xaxis.set_minor_locator(MultipleLocator(factor))

        if not self._y_scale == "log":
            if len(ax0.get_yaxis().get_majorticklocs()) >= 2:
                factor = abs(ax0.get_yaxis().get_majorticklocs()[1] - ax0.get_yaxis().get_majorticklocs()[0]) / 5

                ax0.yaxis.set_minor_locator(MultipleLocator(factor))
        
        if self._ratio_plot:
            ax1.yaxis.set_minor_locator(MultipleLocator(0.1))


        def convert_to_axes_coordinates(x, y):
            x_bounds, y_bounds = ax0.get_xlim(), ax0.get_ylim()
            return (x - x_bounds[0]) / (x_bounds[1] - x_bounds[0]), (y - y_bounds[0]) / (y_bounds[1] - y_bounds[0])




        # Any possible markers.
        for marker in self._mark_regions:

            #print marker

            if "Area" in self._x_label:
                ax0.plot([marker[0], marker[0]], [2, marker[1] ], zorder=9999, color='red', linewidth=8, linestyle="dashed")
            else:
                #print([marker[0], marker[0]])
                #print( [ax0.get_ylim()[0], marker[1] ])
                ax0.plot([marker[0], marker[0]], [ax0.get_ylim()[0], marker[1]], zorder=9999, color='red', linewidth=8, linestyle="dashed")

            unit_x_minor_tick_length = abs(ax0.get_xaxis().get_majorticklocs()[1] - ax0.get_xaxis().get_majorticklocs()[0]) /  10
            unit_y_minor_tick_length = abs(ax0.get_yaxis().get_majorticklocs()[1] - ax0.get_yaxis().get_majorticklocs()[0]) /  5

            # print ax0.get_yaxis().get_majorticklocs()[1], ax0.get_yaxis().get_majorticklocs()[0]

            if marker[2] != None:
                # Arrows.
                if marker[2] == "right":


                    if self._y_scale == 'log':
                        #ax0.arrow(marker[0], fy(marker[3]), marker[4], 0., head_width=unit_y_minor_tick_length, head_length=unit_x_minor_tick_length, fc='red', ec='red', transform=ax0.transAxes)
                        #ax0.arrow(marker[0], fy(marker[3]), marker[4], 0., fc='red', ec='red', transform=ax0.transAxes)
                        #ax0.arrow(marker[0], marker[3], marker[4], 0., head_width=unit_y_minor_tick_length, head_length=unit_x_minor_tick_length, fc='red', ec='red')
                        
                        x_o, y_o = convert_to_axes_coordinates(marker[0], marker[3])
                        delta_x, delta_y = convert_to_axes_coordinates(marker[4], 0)

                        print(x_o, y_o, delta_x, delta_y)

                        ax0.arrow(x_o, y_o, delta_x, delta_y, fc='red', ec='red', head_length=0.02, head_width=0.03, transform=ax0.transAxes)
                    
                    else:
                        ax0.arrow(marker[0], marker[3], marker[4], 0., head_width=unit_y_minor_tick_length, head_length=unit_x_minor_tick_length, fc='red', ec='red')
                elif marker[2] == "left":
                    
                    if self._y_scale == 'log':
                        x_o, y_o = convert_to_axes_coordinates(marker[0], marker[3])
                        delta_x, delta_y = convert_to_axes_coordinates(marker[4], 0)
                        
                        ax0.arrow(marker[0], marker[3], marker[4], 0., head_width=unit_y_minor_tick_length, head_length=unit_x_minor_tick_length, fc='red', ec='red', transform=ax0.transAxes)
                    else:
                        ax0.arrow(marker[0], marker[3], marker[4], 0., head_width=unit_y_minor_tick_length, head_length=unit_x_minor_tick_length, fc='red', ec='red')
            

            if "Area" in self._x_label:
                ax0.text(marker[0], 1., "$\pi \mathrm{R}^2$", color='red', fontsize=75, horizontalalignment='center')
          

        self._plt.gcf().set_snap(True)
Beispiel #9
0
        xrange(sci_trigger_r_obj.begin_entry, sci_trigger_r_obj.end_entry)):
    sci_trigger_r_obj.t_trigger.get_entry(i)
    if not sci_trigger_r_obj.t_trigger.abs_gps_valid: continue
    trigger_hist.fill((sci_trigger_r_obj.t_trigger.abs_gps_week -
                       sci_trigger_r_obj.start_week) * 604800 +
                      (sci_trigger_r_obj.t_trigger.abs_gps_second -
                       sci_trigger_r_obj.start_second))
    for j in xrange(25):
        if sci_trigger_r_obj.t_trigger.trig_accepted[j]:
            modules_hist[j].fill((sci_trigger_r_obj.t_trigger.abs_gps_week -
                                  sci_trigger_r_obj.start_week) * 604800 +
                                 (sci_trigger_r_obj.t_trigger.abs_gps_second -
                                  sci_trigger_r_obj.start_second))

for i in xrange(1, nbins + 1):
    trigger_hist.SetBinContent(i, trigger_hist.GetBinContent(i) / args.bw)
    trigger_hist.SetBinError(i, trigger_hist.GetBinError(i) / args.bw)
    for j in xrange(25):
        modules_hist[j].SetBinContent(
            i, modules_hist[j].GetBinContent(i) / args.bw)
        modules_hist[j].SetBinError(i,
                                    modules_hist[j].GetBinError(i) / args.bw)
print ' - drawing ... '
y_max = 0
for i in xrange(25):
    if modules_hist[i].GetMaximum() > y_max:
        y_max = modules_hist[i].GetMaximum()
for i in xrange(25):
    modules_hist[i].SetMaximum(y_max * 1.1)

canvas_trigger = Canvas(1000,
Beispiel #10
0
def main():
    print("Number of arguments: ", len(sys.argv), "arguments.")
    filename = sys.argv[1]
    print("Input file: {}".format(filename))

    jetBinBorders = [5, 10, 20, 30, 40, 60, 80, 100, 150, 500]
    jetPtBins = [(a, b) for a, b in zip(jetBinBorders, jetBinBorders[1:])]
    JetPtCenter = [7.5, 15, 25, 35, 50, 70, 90, 125, 325]
    JetPtError = [2.5, 5, 5, 5, 10, 10, 10, 25, 175]
    Njets = len(jetBinBorders) - 1
    Njets = 9
    f = root_open(filename, "read")
    if len(sys.argv) > 2:
        filename_test = sys.argv[2]
        f_test = root_open(filename_test)
        print("Open {} for test data".format(filename_test))
    else:
        f_test = root_open(filename)
    if len(sys.argv) < 4:
        f_data = None
    else:
        filename_data = sys.argv[3]
        f_data = root_open(filename_data)
        if len(sys.argv) > 4:
            if sys.argv[4] == "MB":
                do_mb = True
                do_triggered = False
            elif sys.argv[4] == "Triggered":
                do_mb = False
                do_triggered = True
            else:
                do_mb = False
                do_triggered = False

    nR = 3
    iFinder = 0
    iMCFinder = iFinder + nR * 2

    base_folder = "AliJJetJtTask/AliJJetJtHistManager"
    base_folder_trig = "AliJJetJtTask_kEMCEJE/AliJJetJtHistManager"
    base_folder_MC = "AliJJetJtTask/AliJJetJtMCHistManager"

    if f_data:
        numberJetsDataMB = get_numbers(f_data, base_folder, "JetPtBin",
                                       iFinder, Njets)

        numberJetsDataTriggered = get_numbers(f_data, base_folder_trig,
                                              "JetPtBin", iFinder, Njets)

        hTrackJtDataMB = get_hists(f_data, base_folder, "JetConeJtWeightBin",
                                   iFinder, Njets)
        hTrackJtDataTriggered = get_hists(f_data, base_folder_trig,
                                          "JetConeJtWeightBin", iFinder, Njets)

        hTrackJt2DDataMB = get_hists(f_data, base_folder, "JtWeight2D",
                                     iFinder)
        hTrackJt2DDataTriggered = get_hists(f_data, base_folder_trig,
                                            "JtWeight2D", iFinder)

        hJetPtDataMBCoarse = Hist(jetBinBorders)
        for n, i in zip(numberJetsDataMB, range(1, Njets + 1)):
            hJetPtDataMBCoarse.SetBinContent(i, n)

        hJetPtDataTriggeredCoarse = Hist(jetBinBorders)
        for n, i in zip(numberJetsDataTriggered, range(1, Njets + 1)):
            hJetPtDataTriggeredCoarse.SetBinContent(i, n)

        hJetPtDataMB = get_hists(f_data, base_folder, "JetPt", iFinder)
        hJetPtDataTriggered = get_hists(f_data, base_folder_trig, "JetPt",
                                        iFinder)

        # Get Background distributions
        hBgJtDataMB = get_hists(f_data, base_folder, "BgJtWeightBin", iFinder,
                                Njets)
        hBgJtDataTriggered = get_hists(f_data, base_folder_trig,
                                       "BgJtWeightBin", iFinder, Njets)

        # Get number of background jets
        hBgNumbersDataMB = get_numbers(f_data, base_folder, "BgTrkNumberBin",
                                       iFinder, Njets)

        hBgNumbersDataTriggered = get_numbers(f_data, base_folder_trig,
                                              "BgTrkNumberBin", iFinder, Njets)

    numberJetsMeas = get_numbers(f_test, base_folder, "JetPtBin", iFinder,
                                 Njets)

    numberJetsTrue = get_numbers(f_test, base_folder, "JetPtBin", iMCFinder,
                                 Njets)

    hTrackJtMeas = get_hists(f_test, base_folder, "JetConeJtWeightBin",
                             iFinder, Njets)
    hTrackJtTrue = get_hists(f_test, base_folder, "JetConeJtWeightBin",
                             iMCFinder, Njets)

    numberJetsMeasTrain = get_numbers(f, base_folder, "JetPtBin", iFinder,
                                      Njets)

    hTrackJtCorr2D = get_hists(f, base_folder_MC, "TrackJtCorr2D", iFinder,
                               Njets)
    hTrackJtMeas2D = get_hists(f_test, base_folder, "JtWeight2D", iFinder)
    hTrackJtTrue2D = get_hists(f_test, base_folder, "JtWeight2D", iMCFinder)
    hTrackJtMisses2D = get_hists(f, base_folder_MC, "TrackJtMisses2D", iFinder)
    hTrackJtFakes2D = get_hists(f, base_folder, "JetConeJtUnfBg2D", iFinder)
    hTrackJtBg = get_hists(f, base_folder, "BgJtWeightBin", iFinder, Njets)

    hTrackJtBgNumber = get_numbers(f, base_folder, "BgTrkNumberBin", iFinder,
                                   Njets)
    # Get number of background jets

    hTrackMatchSuccess = get_hists(f, base_folder_MC, "TrackMatchSuccess",
                                   iFinder, Njets)

    LogBinsJt = [
        hTrackJtMeas2D.GetXaxis().GetBinLowEdge(iBin)
        for iBin in range(1,
                          hTrackJtMeas2D.GetNbinsX() + 2)
    ]

    for h in hTrackJtCorr2D:
        print("{}".format(h.GetTitle()))
    hJetPtMeas = get_hists(f_test, base_folder, "JetPt", iFinder)
    hJetPtMeasCoarse = Hist(jetBinBorders)
    for n, i in zip(numberJetsMeas, range(1, Njets + 1)):
        hJetPtMeasCoarse.SetBinContent(i, n)

    hJetPtTrue = get_hists(f_test, base_folder, "JetPt", iMCFinder)
    hJetPtTrueCoarse = Hist(jetBinBorders)
    for n, i in zip(numberJetsTrue, range(1, Njets + 1)):
        hJetPtTrueCoarse.SetBinContent(i, n)
    LogBinsPt = [
        hJetPtTrue.GetXaxis().GetBinLowEdge(iBin)
        for iBin in range(1,
                          hJetPtTrue.GetNbinsX() + 2)
    ]
    hJetPtResponse = get_hists(f, base_folder_MC, "JetPtCorr", iFinder)
    hJetPtResponseCoarse = get_hists(f, base_folder_MC, "JetPtCorrCoarse",
                                     iFinder)

    if False:
        TrackJtUnfolder = JtUnfolder.JtUnfolder(
            "TrackJtUnfolder",
            jetBinBorders=jetBinBorders,
            Njets=Njets,
            Iterations=5,
            Data=True,
        )
        TrackJtUnfolder.setTrackMatch(hTrackMatchSuccess)
        # TrackJtUnfolder.drawTrackMatch("TrackMatch",'single')
        TrackJtUnfolder.setPtBins(LogBinsPt)
        TrackJtUnfolder.setJtBins(LogBinsJt)
        TrackJtUnfolder.setJtMeas2D(hTrackJtMeas2D)
        TrackJtUnfolder.setJtTestMeas2D(hTrackJtMeas2D)
        TrackJtUnfolder.setJtTrue2D(hTrackJtTrue2D)
        TrackJtUnfolder.setJtTestTrue2D(hTrackJtTrue2D)
        TrackJtUnfolder.setMisses2D(hTrackJtMisses2D)
        TrackJtUnfolder.setFakes2D(hTrackJtFakes2D)
        TrackJtUnfolder.setJetPtMeas(hJetPtMeas)
        TrackJtUnfolder.setJetPtTrue(hJetPtTrue)
        TrackJtUnfolder.setJetPtMeasCoarse(hJetPtMeasCoarse)
        TrackJtUnfolder.setJetPtTrueCoarse(hJetPtTrueCoarse)
        TrackJtUnfolder.setJetPtResponse(
            createResponseInverse(hJetPtMeas, hJetPtResponse))
        TrackJtUnfolder.setJetPtResponseCoarse(
            createResponseInverse(hJetPtMeasCoarse, hJetPtResponseCoarse))
        TrackJtUnfolder.setNumberJetsMeas(numberJetsMeas)
        TrackJtUnfolder.setNumberJetsTrue(numberJetsTrue)
        TrackJtUnfolder.setNumberJetsTestMeas(numberJetsMeas)
        TrackJtUnfolder.setNumberJetsTestTrue(numberJetsTrue)
        TrackJtUnfolder.setNumberJetsMeasTrain(sum(numberJetsMeasTrain))
        TrackJtUnfolder.set2Dresponse(hTrackJtCorr2D)
        TrackJtUnfolder.setJtBackground(hTrackJtBg)
        TrackJtUnfolder.setJtBackgroundNumbers(hTrackJtBgNumber)
        TrackJtUnfolder.unfold()
        TrackJtUnfolder.write_files("dataUnfolded.root")
        # TrackJtUnfolder.plotResponse()
        # TrackJtUnfolder.plotJetPt()
        # TrackJtUnfolder.plotJt("PythiaTest", Rebin=4)
        return

    if f_data:
        split_file = splitext(split(filename_data)[1])
        suffix = "_unfolded"
        if do_mb:
            suffix += "_MB"
        if do_triggered:
            suffix += "_triggered"
        output_file = "output/" + split_file[0] + suffix + split_file[1]

        if not os.path.exists('output'):
            os.makedirs('output')

        if do_mb:
            MBDataJtUnfolder = JtUnfolder.JtUnfolder(
                "MBDataUnfolder",
                jetBinBorders=jetBinBorders,
                Njets=Njets,
                Data=True,
                Iterations=5,
            )
            MBDataJtUnfolder.setPtBins(LogBinsPt)
            MBDataJtUnfolder.setJtBins(LogBinsJt)
            MBDataJtUnfolder.setJtMeas2D(hTrackJt2DDataMB)
            MBDataJtUnfolder.setJetPtMeas(hJetPtDataMB)
            MBDataJtUnfolder.setJetPtMeasCoarse(hJetPtDataMBCoarse)
            MBDataJtUnfolder.setNumberJetsMeas(numberJetsDataMB)
            MBDataJtUnfolder.setJtBackground(hBgJtDataMB)
            MBDataJtUnfolder.setJtBackgroundNumbers(hBgNumbersDataMB)

            MBDataJtUnfolder.setJtTrue2D(hTrackJtTrue2D)
            MBDataJtUnfolder.setJtTestTrue2D(hTrackJtTrue2D)
            MBDataJtUnfolder.setFakes2D(hTrackJtFakes2D)
            MBDataJtUnfolder.setMisses2D(hTrackJtMisses2D)
            MBDataJtUnfolder.setJetPtResponse(
                createResponseInverse(hJetPtMeas, hJetPtResponse))
            MBDataJtUnfolder.setJetPtResponseCoarse(
                createResponseInverse(hJetPtMeasCoarse, hJetPtResponseCoarse))
            MBDataJtUnfolder.setNumberJetsMeasTrain(sum(numberJetsMeasTrain))
            MBDataJtUnfolder.set2Dresponse(hTrackJtCorr2D)
            MBDataJtUnfolder.unfold()
            MBDataJtUnfolder.write_files(output_file)
            # MBDataJtUnfolder.plotJt("MBDataUnfolded", Rebin=4)

        if do_triggered:
            TriggeredDataJtUnfolder = JtUnfolder.JtUnfolder(
                "TriggeredDataUnfolder",
                jetBinBorders=jetBinBorders,
                Njets=Njets,
                Data=True,
                Iterations=5,
            )
            TriggeredDataJtUnfolder.setPtBins(LogBinsPt)
            TriggeredDataJtUnfolder.setJtBins(LogBinsJt)
            TriggeredDataJtUnfolder.setJtMeas2D(hTrackJt2DDataTriggered)
            TriggeredDataJtUnfolder.setJetPtMeas(hJetPtDataTriggered)
            TriggeredDataJtUnfolder.setJetPtMeasCoarse(
                hJetPtDataTriggeredCoarse)
            TriggeredDataJtUnfolder.setNumberJetsMeas(numberJetsDataTriggered)
            TriggeredDataJtUnfolder.setJtBackground(hBgJtDataTriggered)
            TriggeredDataJtUnfolder.setJtBackgroundNumbers(
                hBgNumbersDataTriggered)

            TriggeredDataJtUnfolder.setJtTrue2D(hTrackJtTrue2D)
            TriggeredDataJtUnfolder.setJtTestTrue2D(hTrackJtTrue2D)
            TriggeredDataJtUnfolder.setFakes2D(hTrackJtFakes2D)
            TriggeredDataJtUnfolder.setMisses2D(hTrackJtMisses2D)
            TriggeredDataJtUnfolder.setJetPtResponse(
                createResponseInverse(hJetPtMeas, hJetPtResponse))
            TriggeredDataJtUnfolder.setJetPtResponseCoarse(
                createResponseInverse(hJetPtMeasCoarse, hJetPtResponseCoarse))
            TriggeredDataJtUnfolder.setNumberJetsMeasTrain(
                sum(numberJetsMeasTrain))
            TriggeredDataJtUnfolder.set2Dresponse(hTrackJtCorr2D)
            TriggeredDataJtUnfolder.unfold()
            TriggeredDataJtUnfolder.write_files(output_file)
    def __return_histogram(self,
                           d_hist_info,
                           ignoreUnderflow=True,
                           useQCDControl=False,
                           useQCDSystematicControl=False):
        '''
        Takes basic histogram info and returns histo.
        Maybe this can move to ROOT_utilities?
        '''
        from rootpy.io.file import File
        from rootpy.plotting import Hist
        from dps.utils.hist_utilities import fix_overflow

        f = d_hist_info['input_file']
        tree = d_hist_info['tree']
        qcd_tree = d_hist_info["qcd_control_region"]
        qcd_tree_for_normalisation = d_hist_info["qcd_normalisation_region"]
        var = d_hist_info['branch']
        bins = d_hist_info['bin_edges']
        lumi_scale = d_hist_info['lumi_scale']
        scale = d_hist_info['scale']
        weights = d_hist_info['weight_branches']
        selection = d_hist_info['selection']

        if useQCDControl:
            # replace SR tree with CR tree
            if useQCDSystematicControl:
                tree = qcd_tree_for_normalisation
            else:
                tree = qcd_tree
            # Remove the Lepton reweighting for the datadriven qcd (SF not derived for unisolated leptons)
            for weight in weights:
                if 'Electron' in weight: weights.remove(weight)
                elif 'Muon' in weight: weights.remove(weight)

        weights = "*".join(weights)
        # Selection will return a weight 0 or 1 depending on whether event passes selection
        weights_and_selection = '( {0} ) * ( {1} )'.format(weights, selection)

        scale *= lumi_scale

        root_file = File(f)
        root_tree = root_file.Get(tree)

        root_histogram = Hist(bins)
        # Draw histogram of var for selection into root_histogram
        root_tree.Draw(var,
                       selection=weights_and_selection,
                       hist=root_histogram)
        root_histogram.Scale(scale)

        # When a tree is filled with a dummy variable, it will end up in the underflow, so ignore it
        if ignoreUnderflow:
            root_histogram.SetBinContent(0, 0)
            root_histogram.SetBinError(0, 0)

        # Fix overflow (Moves entries from overflow bin into last bin i.e. last bin not |..| but |--> )
        root_histogram = fix_overflow(root_histogram)

        root_file.Close()
        return root_histogram
def main(parameters):
  input_files = parameters.input_files
  tree_name = parameters.input_tree
  means = Hist(4*len(input_files), 0, 4*len(input_files), name='mean values')
  rmss = Hist(4*len(input_files), 0, 4*len(input_files), name='rms values')
  cov_means = Hist(2*len(input_files), 0, 2*len(input_files), name='covariance mean values')
  cov_rmss = Hist(2*len(input_files), 0, 2*len(input_files), name='covariance rms values')
  means.SetYTitle('Variance mean [cm^{2}]')
  rmss.SetYTitle('Variance RMS [cm^{2}]')
  cov_means.SetYTitle('Covariance mean [cm^{2}]')
  cov_rmss.SetYTitle('Covariance RMS [cm^{2}]')
  with root_open(parameters.output_file, 'recreate') as output_file:
    for i, (name, input_file_name) in enumerate(input_files):
      means.GetXaxis().SetBinLabel(i*4+1, name+' x')
      means.GetXaxis().SetBinLabel(i*4+2, name+' y')
      means.GetXaxis().SetBinLabel(i*4+3, name+' u')
      means.GetXaxis().SetBinLabel(i*4+4, name+' v')
      rmss.GetXaxis().SetBinLabel(i*4+1, name+' x')
      rmss.GetXaxis().SetBinLabel(i*4+2, name+' y')
      rmss.GetXaxis().SetBinLabel(i*4+3, name+' u')
      rmss.GetXaxis().SetBinLabel(i*4+4, name+' v')
      cov_means.GetXaxis().SetBinLabel(i*2+1, name+' x/y')
      cov_rmss.GetXaxis().SetBinLabel(i*2+1, name+' x/y')
      cov_means.GetXaxis().SetBinLabel(i*2+2, name+' u/v')
      cov_rmss.GetXaxis().SetBinLabel(i*2+2, name+' u/v')
      with root_open(input_file_name) as input_file:
        tree = input_file.Get(tree_name)
        moment_2nd_x, moment_2nd_y, moment_2nd_xy, moment_2nd_u, moment_2nd_v, moment_2nd_uv = shape_distribution(tree, parameters.log_weights)
        print name
        print 'x variance Mu =', moment_2nd_x.GetMean(), '+/-', moment_2nd_x.GetMeanError(), 'RMS =', moment_2nd_x.GetRMS(), '+/-', moment_2nd_x.GetRMSError()
        print 'y variance Mu =', moment_2nd_y.GetMean(), '+/-', moment_2nd_y.GetMeanError(), 'RMS =', moment_2nd_y.GetRMS(), '+/-', moment_2nd_y.GetRMSError()
        print 'u variance Mu =', moment_2nd_u.GetMean(), '+/-', moment_2nd_u.GetMeanError(), 'RMS =', moment_2nd_u.GetRMS(), '+/-', moment_2nd_u.GetRMSError()
        print 'v variance Mu =', moment_2nd_v.GetMean(), '+/-', moment_2nd_v.GetMeanError(), 'RMS =', moment_2nd_v.GetRMS(), '+/-', moment_2nd_v.GetRMSError()
        print 'x-y covariance Mu =', moment_2nd_xy.GetMean(), '+/-', moment_2nd_xy.GetMeanError(), 'RMS =', moment_2nd_xy.GetRMS(), '+/-', moment_2nd_xy.GetRMSError()
        print 'u-v covariance Mu =', moment_2nd_uv.GetMean(), '+/-', moment_2nd_uv.GetMeanError(), 'RMS =', moment_2nd_uv.GetRMS(), '+/-', moment_2nd_uv.GetRMSError()
        # fill mean values of variances
        means.SetBinContent(i*4+1, moment_2nd_x.GetMean())
        means.SetBinError(i*4+1, moment_2nd_x.GetMeanError())
        means.SetBinContent(i*4+2, moment_2nd_y.GetMean())
        means.SetBinError(i*4+2, moment_2nd_y.GetMeanError())
        means.SetBinContent(i*4+3, moment_2nd_u.GetMean())
        means.SetBinError(i*4+3, moment_2nd_u.GetMeanError())
        means.SetBinContent(i*4+4, moment_2nd_v.GetMean())
        means.SetBinError(i*4+4, moment_2nd_v.GetMeanError())
        # fill rms values of variances
        rmss.SetBinContent(i*4+1, moment_2nd_x.GetRMS())
        rmss.SetBinError(i*4+1, moment_2nd_x.GetRMSError())
        rmss.SetBinContent(i*4+2, moment_2nd_y.GetRMS())
        rmss.SetBinError(i*4+2, moment_2nd_y.GetRMSError())
        rmss.SetBinContent(i*4+3, moment_2nd_u.GetRMS())
        rmss.SetBinError(i*4+3, moment_2nd_u.GetRMSError())
        rmss.SetBinContent(i*4+4, moment_2nd_v.GetRMS())
        rmss.SetBinError(i*4+4, moment_2nd_v.GetRMSError())
        # fill mean values of covariances
        cov_means.SetBinContent(i*2+1, moment_2nd_xy.GetMean())
        cov_means.SetBinError(i*2+1, moment_2nd_xy.GetMeanError())
        cov_means.SetBinContent(i*2+2, moment_2nd_uv.GetMean())
        cov_means.SetBinError(i*2+2, moment_2nd_uv.GetMeanError())
        # fill rms values of covariances
        cov_rmss.SetBinContent(i*2+1, moment_2nd_xy.GetRMS())
        cov_rmss.SetBinError(i*2+1, moment_2nd_xy.GetRMSError())
        cov_rmss.SetBinContent(i*2+2, moment_2nd_uv.GetRMS())
        cov_rmss.SetBinError(i*2+2, moment_2nd_uv.GetRMSError())
        # write variance distributions
        moment_2nd_x.SetName(moment_2nd_x.GetName()+'_'+name)
        moment_2nd_y.SetName(moment_2nd_y.GetName()+'_'+name)
        moment_2nd_xy.SetName(moment_2nd_xy.GetName()+'_'+name)
        moment_2nd_u.SetName(moment_2nd_u.GetName()+'_'+name)
        moment_2nd_v.SetName(moment_2nd_v.GetName()+'_'+name)
        output_file.cd()
        moment_2nd_x.Write()   
        moment_2nd_y.Write()
        moment_2nd_xy.Write()
        moment_2nd_u.Write()
        moment_2nd_v.Write()
    means.Write()
    rmss.Write()
    cov_means.Write()
    cov_rmss.Write()
Beispiel #13
0
def get_fit_histogram(chi2,typ,tbin,wave1, wave2 = None, mmin = .5, mmax = 2.5, nbin = 500,component = -1, parameters = None):
	"""
	Gets a single histogram from a chi2 object
	@param chi2: Chi2 from where the histogrm is built
	@type chi2: chi2
	@param typ: type of the histogram:
		intensity: Intensity for wave1
		amp_re: Real part of wave1
		amp_im: Imag part of wave1
		amp_phase: Phase of wave1
		real: Real part of the interference of wave1 and wave2
		imag: Imag part of the interference of wave1 and wave2
		phase: Phase of the interference of wave1 and wave2
	@type param: str
	@param wave1: Number of the first wave
	@type wave1: int
	@param wave2: Number of the first wave (only for interferences, ignored otherwise)
	@type wave2: int
	@param mmin: Minimum mass for the histogram
	@type mmin: float
	@param mmax: Maximum mass for the histogram
	@type mmax: float
	@param nbin: Number of bins for the histogram
	@type nbin: int
	@param component: Number of active component, all active if component == -1 (default)
	@type component: int
	@return Specified histogram
	@rtyp Hist
	"""
	nWaves = chi2.nWaves()
	nTbin= chi2.nTbin()
	perT = chi2.nBrCpl()
	nCpl = perT*nTbin


	hist = Hist(nbin,mmin,mmax)
	if typ.startswith("all_waves"):
		if not component == -1:
			raise ValueError # Not possible with specified component
		hist = []
		for i in range(nWaves):
			histLine = []
			for j in range(nWaves):
				histLine.append(Hist(nbin,mmin,mmax))
			hist.append(histLine)

	step = (mmax - mmin)/nbin
	if not parameters:
		parameters = chi2.fullParameters()
	print '-----------------------------------------------------'
	print '-----------------------------------------------------'
	print tbin,wave1,component
	print '-----------------------------------------------------'
	print parameters[:2*nTbin*perT]
	if not component == -1:
		params_to_keep = chi2.getFuncParameters(component)
		for i in range(2*nCpl):
			if not i in params_to_keep:
				parameters[i] = 0.
	print parameters[:2*nTbin*perT]
	for i in range(nTbin):
		if not i == tbin:
			for j in range(perT):
				parameters[2*(j+i*perT)  ] = 0. # Set eveything in the wrong tbin to zero, just to be shure
				parameters[2*(j+i*perT)+1] = 0.
	print '-----------------------------------------------------'
	print parameters[:2*nTbin*perT]

	for i in range(1,nbin+1):
		m = mmin+(i-.5)*step
		amps = chi2.Amplitudes(m,tbin, parameters)

		if typ == "intensity":
			hist.SetBinContent(i,abs(amps[wave1])**2)
		elif typ == "ampl_real":
			hist.SetBinContent(i,amps[wave1].real)
		elif typ == "ampl_imag":
			hist.SetBinContent(i,amps[wave1].imag)
		elif typ == "ampl_phase":
			hist.SetBinContent(i,math.atan2(amps[wave1].imag,amps[wave1].real)*180./math.pi)
		elif typ.startswith("all_waves"):
			for k in range(nWaves):
				for l in range(nWaves):
					interference = amps[k]*amps[l].conjugate()
					if typ.endswith("real"):
						hist[k][l].SetBinContent(i,interference.real)
					if typ.endswith("imag"):
						hist[k][l].SetBinContent(i,interference.imag)
					if typ.endswith("phase"):
						hist[k][l].SetBinConetnt(i,math.atan2(interference.imag,interference.real)*180./math.pi)
		else:
			interference = amps[wave1]*amps[wave2].conjugate()
			if typ =="real":
				hist.SetBinContent(i,interference.real)
			elif typ == "imag":
				hist.SetBinContent(i,interference.imag)
			elif typ == "phase":
				phase=math.atan2(interference.imag,interference.real)*180./math.pi
				hist.SetBinContent(i,phase)
	if component == -1:
		name = "mass-dependent"
	else:
		name = chi2.get_component_name(component)
	if not typ.startswith("all_waves"):
		hist.SetTitle(name)
		hist.SetName(name)	
	else:
		for i in range(nWaves):
			for j in range(nWaves):
				hist[i][j].SetTitle(name)
				hist[i][j].SetName(name)	
	return hist