コード例 #1
0
def write_histogram(var, hname, weight, samples, sn, sampn, cuts, cuts_antiiso, outdir, channel, coupling, binning=None, plot_range=None, asymmetry=None, mtmetcut=None):
    weight_str = weight
    samp = samples[sampn]
    outfile = File(outdir + "/%s_%s.root" % (sampn,hname), "RECREATE")
    if sn=="DATA":
        weight_str = "1"
    if var == "eta_lj":
        var = "abs("+var+")"
    qcd_extra = None
    
    #This is a really ugly way of adding the QCD shape variation, but works. Restructure the whole thing in the future
    if "iso__down" in hname:
        if var == "abs(eta_lj)":
            cuts_antiiso = str(Cuts.eta_fit_antiiso_down(channel))
            qcd_extra = str(Cuts.eta_fit_antiiso(channel)) #hack for now
        else:
            for x in str(cuts_antiiso).split("&&"):
                if "mva" in x:
                    cut = x
            cut = cut.replace("(","").replace(")","")
            cuts_antiiso = str(Cuts.mva_antiiso_down(channel, mva_var=var)) + " && ("+cut+")"
            qcd_extra = str(Cuts.mva_antiiso(channel, mva_var=var)) + " && ("+cut+")" #hack for now
    elif "iso__up" in hname:
        if var == "abs(eta_lj)":
            cuts_antiiso = str(Cuts.eta_fit_antiiso_up(channel))
            qcd_extra = str(Cuts.eta_fit_antiiso(channel)) #hack for now
        else:
            for x in str(cuts_antiiso).split("&&"):
                if "mva" in x:
                    cut = x
            cut = cut.replace("(","").replace(")","")
            cuts_antiiso = str(Cuts.mva_antiiso_up(channel, mva_var=var)) + " && ("+cut+")"
            qcd_extra = str(Cuts.mva_antiiso(channel, mva_var=var)) + " && ("+cut+")" #hack for now
    hist = create_histogram_for_fit(sn, samp, weight_str, cuts, cuts_antiiso, channel, coupling, var, binning=binning, plot_range=plot_range, asymmetry=asymmetry, qcd_extra=qcd_extra, mtmetcut=mtmetcut)
    outfile.cd() #Must cd after histogram creation

    #Write histogram to file
    logging.info("Writing histogram %s to file %s" % (hist.GetName(), outfile.GetPath()))
    logging.info("%i entries, %.2f events" % (hist.GetEntries(), hist.Integral()))
    hist.SetName(hname)
    hist.SetDirectory(outfile)
    #hist.Write() #Double write?
    outfile.Write()
    outfile.Close()
コード例 #2
0
ファイル: ppd_file_w.py プロジェクト: ZhenghengLi/POLAR_DATA
class ppd_file_w:
    def __init__(self):
        self.__t_file_out = None
        self.__t_tree_ppd = None

    def open_file(self, filename):
        self.__t_file_out = File(filename, "recreate")
        self.__t_tree_ppd = Tree("t_ppd", "platform parameters data")
        self.__t_tree_ppd.create_branches({
            "pitch_angle"          : "D"     ,
            "yaw_angle"            : "D"     ,
            "roll_angle"           : "D"     ,
            "pitch_angle_v"        : "D"     ,
            "yaw_angle_v"          : "D"     ,
            "roll_angle_v"         : "D"     ,
            "orbit_agl_v"          : "D"     ,
            "longitude"            : "D"     ,
            "latitude"             : "D"     ,
            "geocentric_d"         : "D"     ,
            "ship_time_sec"        : "D"     ,
            "utc_time_sec"         : "D"     ,
            "utc_time_str"         : "C[32]" ,
            "flag_of_pos"          : "I"     ,
            "wgs84_x"              : "D"     ,
            "wgs84_y"              : "D"     ,
            "wgs84_z"              : "D"     ,
            "wgs84_x_v"            : "D"     ,
            "wgs84_y_v"            : "D"     ,
            "wgs84_z_v"            : "D"     ,
            "det_z_lat"            : "D"     ,
            "det_z_lon"            : "D"     ,
            "det_z_ra"             : "D"     ,
            "det_z_dec"            : "D"     ,
            "det_x_lat"            : "D"     ,
            "det_x_lon"            : "D"     ,
            "det_x_ra"             : "D"     ,
            "det_x_dec"            : "D"     ,
            "earth_lat"            : "D"     ,
            "earth_lon"            : "D"     ,
            "earth_ra"             : "D"     ,
            "earth_dec"            : "D"     ,
            "sun_ra"               : "D"     ,
            "sun_dec"              : "D"
            })

    def fill_data(self, ppd_obj):
        self.__t_tree_ppd.pitch_angle     = ppd_obj.pitch_angle
        self.__t_tree_ppd.yaw_angle       = ppd_obj.yaw_angle
        self.__t_tree_ppd.roll_angle      = ppd_obj.roll_angle
        self.__t_tree_ppd.pitch_angle_v   = ppd_obj.pitch_angle_v
        self.__t_tree_ppd.yaw_angle_v     = ppd_obj.yaw_angle_v
        self.__t_tree_ppd.roll_angle_v    = ppd_obj.roll_angle_v
        self.__t_tree_ppd.orbit_agl_v     = ppd_obj.orbit_agl_v
        self.__t_tree_ppd.longitude       = ppd_obj.longitude
        self.__t_tree_ppd.latitude        = ppd_obj.latitude
        self.__t_tree_ppd.geocentric_d    = ppd_obj.geocentric_d
        self.__t_tree_ppd.ship_time_sec   = ppd_obj.ship_time_sec
        self.__t_tree_ppd.utc_time_sec    = ppd_obj.utc_time_sec
        self.__t_tree_ppd.utc_time_str    = str(ppd_obj.utc_time_str)
        self.__t_tree_ppd.flag_of_pos     = ppd_obj.flag_of_pos
        self.__t_tree_ppd.wgs84_x         = ppd_obj.wgs84_x
        self.__t_tree_ppd.wgs84_y         = ppd_obj.wgs84_y
        self.__t_tree_ppd.wgs84_z         = ppd_obj.wgs84_z
        self.__t_tree_ppd.wgs84_x_v       = ppd_obj.wgs84_x_v
        self.__t_tree_ppd.wgs84_y_v       = ppd_obj.wgs84_y_v
        self.__t_tree_ppd.wgs84_z_v       = ppd_obj.wgs84_z_v
        self.__t_tree_ppd.det_z_lat       = ppd_obj.det_z_lat
        self.__t_tree_ppd.det_z_lon       = ppd_obj.det_z_lon
        self.__t_tree_ppd.det_z_ra        = ppd_obj.det_z_ra
        self.__t_tree_ppd.det_z_dec       = ppd_obj.det_z_dec
        self.__t_tree_ppd.det_x_lat       = ppd_obj.det_x_lat
        self.__t_tree_ppd.det_x_lon       = ppd_obj.det_x_lon
        self.__t_tree_ppd.det_x_ra        = ppd_obj.det_x_ra
        self.__t_tree_ppd.det_x_dec       = ppd_obj.det_x_dec
        self.__t_tree_ppd.earth_lat       = ppd_obj.earth_lat
        self.__t_tree_ppd.earth_lon       = ppd_obj.earth_lon
        self.__t_tree_ppd.earth_ra        = ppd_obj.earth_ra
        self.__t_tree_ppd.earth_dec       = ppd_obj.earth_dec
        self.__t_tree_ppd.sun_ra          = ppd_obj.sun_ra
        self.__t_tree_ppd.sun_dec         = ppd_obj.sun_dec
        self.__t_tree_ppd.fill()

    def write_tree(self):
        self.__t_file_out.cd()
        self.__t_tree_ppd.write()

    def write_meta(self, key, value):
        self.__t_file_out.cd()
        ROOT.TNamed(key, value).Write()

    def close_file(self):
        self.__t_file_out.close()
        self.__t_file_out = None
        self.__t_tree_ppd = None
コード例 #3
0
                max_count_mat[idx][j] = entry.cnts_ps[j]
                max_time_mat[idx][j] = entry.time_sec
                max_index_mat[idx][j] = it

for idx in xrange(25):
    for j in xrange(64):
        begin_time_mat[idx][j] = max_time_mat[idx][j]
        end_time_mat[idx][j] = max_time_mat[idx][j]
        for t in xrange(1, 15):
            if max_index_mat[idx][j] - t < 0: break
            t_rate[idx].get_entry(max_index_mat[idx][j] - t)
            begin_time_mat[idx][j] = t_rate[idx].time_sec
            if t_rate[idx].cnts_ps[j] < max_count_mat[idx][j] * 0.4: break
        for t in xrange(1, 15):
            if max_index_mat[idx][j] + t > t_rate[idx].get_entries() - 1: break
            t_rate[idx].get_entry(max_index_mat[idx][j] + t)
            if t_rate[idx].cnts_ps[j] < max_count_mat[idx][j] * 0.4: break
            end_time_mat[idx][j] = t_rate[idx].time_sec

# ===============================

t_file_out.cd()
begin_time_mat.Write("begin_time_mat")
end_time_mat.Write("end_time_mat")
max_count_mat.Write("max_count_mat")
max_time_mat.Write("max_time_mat")

t_file_out.close()

t_file_in.close()
コード例 #4
0
time_win_filename = sys.argv[1]
decoded_data_filename = sys.argv[2]
merged_filename = sys.argv[3]

t_file_time_win = File(time_win_filename, "read")
begin_time_mat = t_file_time_win.get("begin_time_mat")
end_time_mat   = t_file_time_win.get("end_time_mat")
max_count_mat  = t_file_time_win.get("max_count_mat")
t_file_time_win.close()

t_file_merged_out = File(merged_filename, "recreate")
t_beam_event_tree = Tree("t_beam_event", "Beam Event Data")
t_beam_event_tree.create_branches({
    'type': 'I',
    'trig_accepted': 'B[25]',
    'time_aligned': 'B[25]',
    'pkt_count': 'I',
    'lost_count': 'I',
    'trigger_bit': 'B[1600]',
    'trigger_n': 'I',
    'multiplicity': 'I[25]',
    'energy_adc': 'F[1600]',
    'compress': 'I[25]',
    'common_noise': 'F[25]',
    'bar_beam': 'B[1600]' })

t_file_merged_out.cd()
t_beam_event_tree.write()
t_file_merged_out.close()
コード例 #5
0
def save_to_root_file(histograms, file_name):
    output = File(file_name, 'recreate')
    output.cd()
    for histogram in histograms:
        histogram.Write()
    output.close()
コード例 #6
0
        t_tree_ppd.wgs84_z            = float(row[17])
        t_tree_ppd.wgs84_x_v          = float(row[18])
        t_tree_ppd.wgs84_y_v          = float(row[19])
        t_tree_ppd.wgs84_z_v          = float(row[20])
        t_tree_ppd.fill()
        if cur_flag_of_pos != 0x55: continue
        if ship_time_is_first:
            ship_time_is_first  = False
            first_ship_time_sec = cur_ship_time_sec
        last_ship_time_sec = cur_ship_time_sec
        if utc_time_is_first:
            utc_time_is_first  = False
            first_utc_time_sec = cur_utc_time_sec
        last_utc_time_sec = cur_utc_time_sec

dattype        = ROOT.TNamed("dattype", "PLATFORM PARAMETERS DATA")
version        = ROOT.TNamed("version", "PPD_Gen1M.py v1.0.0")
gentime        = ROOT.TNamed("gentime", datetime.now().isoformat() + "+0800")
ship_time_span = ROOT.TNamed("ship_time_span", str(first_ship_time_sec) + " => " + str(last_ship_time_sec))
utc_time_span  = ROOT.TNamed("utc_time_span",  str(first_utc_time_sec) + " => " + str(last_utc_time_sec))

t_file_out.cd()
t_tree_ppd.write()
dattype.Write()
version.Write()
gentime.Write()
ship_time_span.Write()
utc_time_span.Write()
t_file_out.close()

コード例 #7
0
    def __init__(self, sNameOfSingleFile, forceReprocess=False, timeCut=True):
        # features to add
        # 1. Optimize gain fitting procedure
        # 2. Print out canvas with signal, bkg, and bkg subtraction hist
        # 3. Update pickle file to mysql

        self.lLightLevels = neriX_led_datasets.lLightLevels
        dRunFiles = neriX_led_datasets.run_files
        lRuns = neriX_led_datasets.runsInUse
        self.lHistParameters = neriX_led_datasets.lHistParameters

        sPathToData = neriX_led_datasets.sPathToData  # must append run number
        sPathToProcessedData = neriX_led_datasets.sPathToProcessedData

        self.dLightLevels = neriX_led_datasets.dLightLevels
        self.stringForNumEntries = 'num_events'

        self.sNameOfSingleFile = sNameOfSingleFile

        # append .root if not there
        if sNameOfSingleFile[-5:] != '.root':
            sNameOfSingleFile += '.root'

        dChannelsAtLightLevels = neriX_led_datasets.dChannelsAtLightLevels
        self.lChannelsToAnalyze = []

        self.dFiles = None
        for run in lRuns:
            for dCheckFiles in dRunFiles[run]:
                for lightLevel in dCheckFiles:
                    if sNameOfSingleFile == dCheckFiles[lightLevel]:
                        currentRun = run
                        self.dFiles = dCheckFiles
                    else:
                        continue

        if not self.dFiles:
            print str(sNameOfSingleFile
                      ) + ' does not appear in neriX_led_datasets.py'
            print 'Please check if the file exists and that your spelling is correct'
            sys.exit()

        self.runNumber = currentRun
        self.sPathToGraphs = neriX_led_datasets.sPathToGraphs + 'run_' + str(
            self.runNumber) + '/'
        self.sPathToHists = neriX_led_datasets.sPathToHists + 'run_' + str(
            self.runNumber) + '/'
        sPathToData += 'run_' + str(self.runNumber) + '/'
        lProcessedPreviously = [False for i in self.lLightLevels]

        self.lProcessedRootFiles = []

        for i, lightLevel in enumerate(self.dFiles):
            # see if data has been processed already
            if os.path.isfile(sPathToProcessedData + 'spe_' +
                              self.dFiles[lightLevel]) and not forceReprocess:
                print 'Found processed data for ' + self.dFiles[lightLevel]
                self.lProcessedRootFiles.append(
                    File(
                        sPathToProcessedData + 'spe_' +
                        self.dFiles[lightLevel], 'read'))

            else:
                print 'Processed data not found for ' + str(
                    self.dFiles[lightLevel]) + ', processing now...'
                if self.dFiles[lightLevel][-5:] != '.root':
                    self.dFiles[lightLevel] += '.root'

                # check if file exists on computer
                if not os.path.isfile(sPathToData + self.dFiles[lightLevel]):
                    print 'Could not find file ' + str(
                        self.dFiles[lightLevel]) + ' in ' + str(sPathToData)
                    print 'Exiting...'
                    sys.exit()

                # load root file
                try:
                    currentFile = File(sPathToData + self.dFiles[lightLevel],
                                       'r')
                except:
                    print 'Could not load ' + str(
                        currentFile) + ' - please check quality of file.'
                    sys.exit()

                T0 = currentFile.T0
                T0.SetName('T0_' + self.dFiles[lightLevel])
                T0.create_buffer()

                # all files must have same number of entries
                self.originalNumberOfEvents = T0.GetEntriesFast()

                processedFile = File(
                    sPathToProcessedData + 'spe_' + self.dFiles[lightLevel],
                    'recreate')

                lHists = [
                    Hist(self.lHistParameters[0],
                         self.lHistParameters[1],
                         self.lHistParameters[2],
                         name='spe_' + str(i + 1),
                         title='spe_' + str(i + 1),
                         drawstyle='hist') for i in xrange(17)
                ]
                for i in xrange(17):
                    xTime = ''
                    if timeCut:
                        xTime = 'SingleSample[' + str(
                            i) + '] > 157 && SingleSample[' + str(
                                i) + '] < 188'
                    T0.Draw(
                        'SingleBefore[%d][1]+SingleBefore[%d][0]+SinglePeak[%d]+SingleAfter[%d][0]+SingleAfter[%d][1]'
                        % (5 * (i, )),
                        hist=lHists[i],
                        selection=xTime)
                    lHists[i].Sumw2()
                    processedFile.cd()
                    lHists[i].Write(lHists[i].GetName())

                sNumEntries = root.TObjString(str(self.originalNumberOfEvents))
                sNumEntries.Write(self.stringForNumEntries,
                                  root.TObject.kOverwrite)

                self.lProcessedRootFiles.append(processedFile)
            self.lChannelsToAnalyze += dChannelsAtLightLevels[lightLevel]

        # fit approval by user:
        # -1: fit failed, 0: not completed yet, 1: passed!
        self.dFitApproved = {i: 0 for i in self.lChannelsToAnalyze}

        # final parameters from fits
        self.dFitParameters = {
            i: {
                'bkg_mean': -1,
                'bkg_width': -1,
                'spe_mean': -1,
                'spe_width': -1,
                'bkg_mean_err': -1,
                'bkg_width_err': -1,
                'spe_mean_err': -1,
                'spe_width_err': -1,
                'chi2': -1,
                'ndf': -1
            }
            for i in self.lChannelsToAnalyze
        }

        # check if pickle file exists
        # try to load pickle file that has saved histogram parameters
        try:
            self.dCompletedFitParameters = pickle.load(
                open('completed_spe_fits.p', 'r'))
        except:
            print 'Pickled file of old parameters does not exist yet'
            self.dCompletedFitParameters = {}

        self.numEventsBeforeCuts = int(
            str(self.lProcessedRootFiles[0].Get(self.stringForNumEntries)))
コード例 #8
0
def save_to_root_file(histograms, file_name):
    output = File(file_name, "recreate")
    output.cd()
    for histogram in histograms:
        histogram.Write()
    output.close()
コード例 #9
0
ファイル: raw-ratios.py プロジェクト: suvayu/Bs2DsKTools
            for nbin in range(1, ratio_histograms[idx].GetNbinsX() + 1):
                ratio_histograms[idx].SetBinContent(
                    nbin, ratio_histograms[idx].GetBinContent(nbin) + 80.0)
            ratio_histograms[idx].Draw('e3 same')
            legend = TLegend(0.75, 0.3, 0.85, 0.5)
            legend.SetLineColor(0)
            legend.SetFillStyle(0)
            legend.AddEntry(histograms[0][idx], 'DsK', 'l')
            legend.AddEntry(histograms[1][idx], 'Ds#pi', 'l')
            legend.AddEntry(ratio_histograms[idx], 'ratio', 'l')
            legend.Draw()
            gPad.Update()
        else:
            ratio_histograms[idx].Draw('e1')
        if doPrint and (idx == 0 or idx > 6):
            canvas0.Print('plots/DsK_ratio_' + str(idx) + '_' + str(zoom) +
                          '.png')
            canvas0.Print('plots/DsK_ratio_' + str(idx) + '_' + str(zoom) +
                          '.pdf')
    canvas.Update()
    if not zoom:
        dfile = File('data/raw_ratios.root', 'recreate')
        dfile.cd()
        for hist in ratio_histograms:
            dfile.WriteTObject(hist)
        dfile.Close()

    if doPrint:
        canvas.Print('plots/DsK_ratio_grid_' + str(zoom) + '.png')
        canvas.Print('plots/DsK_ratio_grid_' + str(zoom) + '.pdf')
コード例 #10
0
            for lumi in range(lumiRange[0], lumiRange[1] + 1):
                fullRunLumi.append([int(run), lumi])
    return fullRunLumi


inputFile = File(
    '/hdfs/TopQuarkGroup/run2/ntuples/v22/SingleMuonFullDCS/SingleMuon.root')
treeName = 'nTupleTree/tree'
tree = inputFile.Get(treeName)

jsonForFiltering = '/users/ec6821/lumiScripts/lcr2/lcr2/good_list.txt'
json = readJson(jsonForFiltering)

newFile = File('SingleMuonFiltered.root', 'RECREATE')
newFile.mkdir('nTupleTree')
newFile.cd('nTupleTree')
newTree = tree.CloneTree(0)

print 'Number of events in tree : ', tree.GetEntries()

for event in tree:
    run = event.__getattr__('Event.Run')
    lumi = event.__getattr__('Event.LumiSection')

    if [run, lumi] in json:
        newTree.Fill()
    else:
        pass
newFile.Close()

# print run, lumi
コード例 #11
0
def add_histos(outdir, var, channel, mva, mtmetcut):
    from os import listdir
    from os.path import isfile, join
    
    
    onlyfiles = [ f for f in listdir(outdir) if isfile(join(outdir,f)) ]
    hists = dict()
    hists_data = []
    hists_qcd = []
    for fname in onlyfiles:
        f = File(outdir+"/"+fname)
        for root, dirs, items in f.walk():
            for name in items:
                h = f.Get(join(root, name))
                if fname.endswith("DATA.root"):
                    hists_data.append(h)
                    continue
                elif fname.startswith("Single"):
                    hists_qcd.append(h)
                    continue
                if not name in hists:
                    hists[name] = []
                if h.GetEntries()>0:
                    print fname, "factor", h.Integral()/math.sqrt(h.GetEntries())
                for bin in range(1, h.GetNbinsX()+1):
                    print bin, h.GetBinContent(bin), h.GetBinError(bin)
                hists[name].append(h)
                #hists[name].SetTitle(name)
    
    hist_data = hists_data[0]
    for i in range(1, len(hists_data)):
        hist_data.Add(hists_data[i])
    hist_qcd = hists_qcd[0]
    print "data", "factor", hist_data.Integral()/math.sqrt(hist_data.GetEntries())
    for i in range(1, len(hists_qcd)):
        print "add", i
        hist_qcd.Add(hists_qcd[i])
    print "QCD", "factor", hist_qcd.Integral()/math.sqrt(hist_qcd.GetEntries())
                
    for bin in range(1, hist_data.GetNbinsX()+1):
        hist_data.SetBinError(bin, math.sqrt(hist_data.GetBinContent(bin)))
        hist_qcd.SetBinError(bin, math.sqrt(hist_qcd.GetBinContent(bin)))

        print bin, hist_qcd.GetBinContent(bin), hist_qcd.GetBinError(bin)
    hist_qcd.Scale(get_qcd_scale_factor(var, channel, mva, mtmetcut))
    for bin in range(1, hist_data.GetNbinsX()+1):
        print bin, hist_qcd.GetBinContent(bin), hist_qcd.GetBinError(bin)
    hists[hist_data.GetName()] = [hist_data]
    print hist_qcd.GetName()
    hists[hist_qcd.GetName()].append(hist_qcd)
    outfile = File(outdir+"/"+generate_file_name(False), "recreate")

    
    for category in hists:
        factor = 1.0    
        total_hist=hists[category][0].Clone()
        total_hist.Reset("ICE")
        #total_hist.Sumw2()
        total_hist.SetNameTitle(category,category)
        outfile.cd()
        print category
        for bin in range(1, total_hist.GetNbinsX()+1):
            zero_error = 0.
            zero_integral = 0.
            nonzero_error = 0.
            bin_sum = 0.
            #max_zero_error = 0.
            for hist in hists[category]:
                print "hist", hist.GetBinContent(bin), hist.GetBinError(bin)**2
                if hist.GetEntries()>0:
                    #factor = hist.Integral()/math.sqrt(hist.GetEntries())
                    #print "fact", factor,hist.Integral(), hist.GetEntries()
                    min_nonzero_error = sys.float_info.max
                    for bin1 in range(1, hist.GetNbinsX()+1):
                        if hist.GetBinContent(bin1) > 0 and hist.GetBinError(bin1) < min_nonzero_error:
                            min_nonzero_error = hist.GetBinError(bin1)
                    print "error", min_nonzero_error
                else:
                    min_nonzero_error = 0.
                if hist.GetBinContent(bin) < 0.00001:
                    #zero_error += factor**2 * hist.Integral()
                    zero_error += min_nonzero_error**2
                    zero_integral += hist.Integral()
                else:
                    bin_sum += hist.GetBinContent(bin)
                    nonzero_error += hist.GetBinError(bin)**2
                #print "...hist", hist.GetBinContent(bin), hist.GetBinError(bin)**2
            total_hist.SetBinContent(bin, bin_sum)
            if zero_integral > 0:
                #total_error = math.sqrt(nonzero_error + zero_error / zero_integral)
                total_error = math.sqrt(nonzero_error + zero_error)
            else:
                total_error = math.sqrt(nonzero_error)
            total_hist.SetBinError(bin, total_error)
            print category, "bin", bin, "content", bin_sum, "error", total_error
            print category, "bin", bin, "weight", total_error**2/bin_sum
        total_hist.Write()
    """for category in hists:       #Imitate hadd
        #factor = 1.0    
        total_hist=hists[category][0].Clone()
        total_hist.Reset("ICE")
        print "cat", category
        total_hist.SetNameTitle(category,category)
        total_hist.Sumw2()
        outfile.cd()
        for hist in hists[category]:
            print "hist", hist, hist.GetName()
            factor = 1.0
            if hist.GetEntries()>0:
                factor = hist.Integral()/hist.GetEntries()

            for bin in range(1, total_hist.GetNbinsX()+1):
                if hist.GetBinError(bin) < factor:
                    hist.SetBinError(bin, factor)
                #total_hist.SetBinContent(bin, total_hist.GetBinContent(bin) + hist.GetBinContent(bin))
                #total_hist.SetBinError(bin, total_hist.GetBinError(bin) + hist.GetBinError(bin))
            total_hist.Add(hist)
        total_hist.Write()"""
    outfile.Write()
    outfile.Close()
コード例 #12
0
def write_histos_to_file(hists, outdir, syst=""):
    filename = outdir+"/"+generate_file_name(False, syst)
    if len(syst)>0:
        filename = filename.replace("/lqeta","")
    #filename += ".root"
    outfile = File(filename, "recreate")
    #rint "writing to file", filename
    for category in hists:
        factor = 1.0    
        total_hist=hists[category][0].Clone()
        total_hist.Reset("ICE")
        #total_hist.Sumw2()
        total_hist.SetNameTitle(category,category)
        outfile.cd()
        #print "CAT",category
        for bin in range(1, total_hist.GetNbinsX()+1):
            zero_error = 0.
            zero_integral = 0.
            nonzero_error = 0.
            bin_sum = 0.
            max_zero_error = 0.            
            zero_errors = {}
            zero_errors[category] = []
            for hist in hists[category]:
                #print "hist", hist.GetBinContent(bin), hist.GetBinError(bin)**2
                zero_errors[category].append(sys.float_info.max)
                if hist.Integral()>0:
                    #factor = hist.Integral()/(math.sqrt(hist.GetEntries()) * total_hist.GetNbinsX()) 
                    #print "fact", factor,hist.Integral(), hist.GetEntries()
                    for bin1 in range(1, hist.GetNbinsX()+1):
                        if hist.GetBinContent(bin1) > 0 and hist.GetBinError(bin1) < zero_errors[category][-1]:
                            zero_errors[category][-1] = hist.GetBinError(bin1)**2
                    #print "error", min_nonzero_error
                else:
                    zero_errors[category][-1] = 0.
                if zero_errors[category][-1] > 10000:
                    #rint "ZERO error NOT ASSIGNED"
                    #or bin1 in range(1, hist.GetNbinsX()+1):
                    #   print bin1, hist.GetBinContent(bin1), hist.GetBinError(bin1)
                    zero_errors[category][-1] = 0.
                if hist.GetBinContent(bin) < 0.00001:
                    #zero_error += factor**2 * hist.Integral()
                    #zero_error += min_nonzero_error**2
                    zero_integral += hist.Integral()
                else:
                    bin_sum += hist.GetBinContent(bin)
                    nonzero_error += hist.GetBinError(bin)**2
                    zero_errors[category][-1] = 0.

                #for bin1 in range(1, hist.GetNbinsX()+1):
                #        print hist.GetBinContent(bin1), math.sqrt(hist.GetBinError(bin1))
                #rint bin, hist.GetName(), hist.GetBinContent(bin), hist.GetBinError(bin), zero_errors[category][-1]
                    
                #print "...hist", hist.GetBinContent(bin), hist.GetBinError(bin)**2
            total_hist.SetBinContent(bin, bin_sum)
            zero_error = 0.
            for err in zero_errors[category]:
                if err > zero_error:
                    zero_error = err
            #rint "ZERO error:", bin, math.sqrt(zero_error)
            
            total_error = math.sqrt(nonzero_error + zero_error)
            #rint math.sqrt(nonzero_error), math.sqrt(zero_error), total_error
            total_hist.SetBinError(bin, total_error)
            #print category, "bin", bin, "content", bin_sum, "error", total_error
            #print category, "bin", bin, "weight", total_error**2/bin_sum
        total_hist.Write()
    """for category in hists:       #Imitate hadd
        #factor = 1.0    
        total_hist=hists[category][0].Clone()
        total_hist.Reset("ICE")
        print "cat", category
        total_hist.SetNameTitle(category,category)
        total_hist.Sumw2()
        outfile.cd()
        for hist in hists[category]:
            print "hist", hist, hist.GetName()
            factor = 1.0
            if hist.GetEntries()>0:
                factor = hist.Integral()/hist.GetEntries()

            for bin in range(1, total_hist.GetNbinsX()+1):
                if hist.GetBinError(bin) < factor:
                    hist.SetBinError(bin, factor)
                #total_hist.SetBinContent(bin, total_hist.GetBinContent(bin) + hist.GetBinContent(bin))
                #total_hist.SetBinError(bin, total_hist.GetBinError(bin) + hist.GetBinError(bin))
            total_hist.Add(hist)
        total_hist.Write()"""
    outfile.Write()
    outfile.Close()
コード例 #13
0
'''
Created on 11 Mar 2015

@author: kreczko
'''

from rootpy.io import File
from rootpy.plotting import Hist
from rootpy import asrootpy

rootpy_hist = Hist(100, 0, 100, type='F')

rootpy_hist.SetName('hist')
test_file = File('test.root', 'RECREATE')
test_file.mkdir("test")
test_file.cd('test')
rootpy_hist.Write()
test_file.Write()
test_file.Close()

read_file = File('test.root')
folder = read_file.Get('test')
hist = folder.hist
print hist.TYPE
read_file.Close()

hist = None

read_file = File('test.root')
hist = read_file.Get('test/hist')
hist1 = hist.empty_clone(type='D')
コード例 #14
0
        t_beam_event.trig_accepted[i] = t_trigger.trig_accepted[i]
        t_beam_event.time_aligned[i] = False
        t_beam_event.multiplicity[i] = 0
        t_beam_event.compress[i] = -1
        t_beam_event.common_noise[i] = 0
        for j in xrange(64):
            t_beam_event.trigger_bit[64 * i + j] = False
            t_beam_event.energy_adc[64 * i + j] = 0
            t_beam_event.bar_beam[64 * i + j] = False
    for q in xrange(t_trigger.pkt_start,
                    t_trigger.pkt_start + t_trigger.pkt_count):
        t_modules.get_entry(q)
        idx = t_modules.ct_num - 1
        t_beam_event.time_aligned[idx] = True
        t_beam_event.multiplicity[idx] = t_modules.multiplicity
        t_beam_event.compress[idx] = t_modules.compress
        t_beam_event.common_noise[idx] = t_modules.common_noise
        for j in xrange(64):
            t_beam_event.trigger_bit[64 * idx + j] = t_modules.trigger_bit[j]
            t_beam_event.energy_adc[64 * idx + j] = t_modules.energy_adc[j]
            if t_modules.time_second >= begin_time_mat(
                    idx, j) and t_modules.time_second <= end_time_mat(
                        idx, j) and max_count_mat(idx, j) > 200:
                t_beam_event.trigger_bit[64 * idx + j] = True
    t_beam_event.fill()

t_file_merged_out.cd()
t_beam_event.write()
t_file_merged_out.close()
t_file_decoded_data.close()
コード例 #15
0
ファイル: raw-ratios.py プロジェクト: lbel/Bs2DsKTools
            histograms[1][idx].Draw('hist same')
            ratio_histograms[idx].SetFillColor(kBlack)
            ratio_histograms[idx].Scale(1000.0/ratio_histograms[idx].Integral())
            for nbin in range(1, ratio_histograms[idx].GetNbinsX() + 1):
                ratio_histograms[idx].SetBinContent(nbin, ratio_histograms[idx].GetBinContent(nbin) + 80.0)
            ratio_histograms[idx].Draw('e3 same')
            legend = TLegend(0.75, 0.3, 0.85, 0.5)
            legend.SetLineColor(0)
            legend.SetFillStyle(0)
            legend.AddEntry(histograms[0][idx], 'DsK', 'l')
            legend.AddEntry(histograms[1][idx], 'Ds#pi', 'l')
            legend.AddEntry(ratio_histograms[idx], 'ratio', 'l')
            legend.Draw()
            gPad.Update()
        else:
            ratio_histograms[idx].Draw('e1')
        if doPrint and (idx == 0 or idx > 6):
            canvas0.Print('plots/DsK_ratio_'+str(idx)+'_'+str(zoom)+'.png')
            canvas0.Print('plots/DsK_ratio_'+str(idx)+'_'+str(zoom)+'.pdf')
    canvas.Update()
    if not zoom:
        dfile = File('data/raw_ratios.root', 'recreate')
        dfile.cd()
        for hist in ratio_histograms:
            dfile.WriteTObject(hist)
        dfile.Close()

    if doPrint:
        canvas.Print('plots/DsK_ratio_grid_'+str(zoom)+'.png')
        canvas.Print('plots/DsK_ratio_grid_'+str(zoom)+'.pdf')
コード例 #16
0
Created on 11 Mar 2015

@author: kreczko
'''

from rootpy.io import File
from rootpy.plotting import Hist
from rootpy import asrootpy

rootpy_hist = Hist( 100, 0, 100, type = 'F' )


rootpy_hist.SetName('hist')
test_file = File('test.root', 'RECREATE')
test_file.mkdir("test")
test_file.cd('test')
rootpy_hist.Write()
test_file.Write()
test_file.Close()

read_file = File('test.root')
folder = read_file.Get('test')
hist = folder.hist
print hist.TYPE
read_file.Close()

hist = None

read_file = File('test.root')
hist = read_file.Get('test/hist')
hist1 = hist.empty_clone(type='D')