Пример #1
0
def common_make_root_histogram_test():
  x_list = list(range(0,10000))
  w_list = []
  for i in range( len(x_list) ): 
    x_list[i] = float(x_list[i])/10000.
    w_list.append(x_list[i])
  y_list = __sine_list(2., 2.*math.pi, x_list)
  hist1 = common.make_root_histogram('hist sin(x)', y_list, 'hist of x', 100)
  hist2 = common.make_root_histogram('hist sin(x)', y_list, 'hist of x', 50, x_list, 'hist of y', 50)
  hist3 = common.make_root_histogram('hist sin(x)', y_list, 'hist of x', 10, x_list, 'hist of y', 10, w_list)
  testpass = __test_root_hist(hist3,'hist sin(x)','hist of x','hist of y',common.min_max(y_list, w_list, rg.histo_margin)[0], common.min_max(y_list, w_list, rg.histo_margin)[1], 
                                                                          common.min_max(x_list, w_list, rg.histo_margin)[0], common.min_max(x_list, w_list, rg.histo_margin)[1], 
                              rg.line_color, rg.line_style, rg.line_width, rg.fill_color, '')
  hist4 = common.make_root_histogram('hist sin(x)', y_list, 'hist of x', 10, x_list, 'hist of y', 10, w_list, xmin=y_list[7500],xmax=y_list[2500],ymin=x_list[2500],ymax=x_list[7500],
                                     line_color=1, line_style=2, line_width=3, fill_color=4, hist_title_string='title_string')
  testpass = __test_root_hist(hist4,'hist sin(x)', 'hist of x', 'hist of y', y_list[7500], y_list[2500], x_list[2500], x_list[7500], 1, 2, 3, 4, 'title_string')
  canvas1 = common.make_root_canvas('hist_test1')
  hist1.Draw()
  canvas2 = common.make_root_canvas('hist_test2')
  hist2.Draw('cont1z')
  canvas3 = common.make_root_canvas('hist_test3')
  hist3.Draw('lego')
  canvas4 = common.make_root_canvas('hist_test4')
  hist4.Draw('lego')
  if not testpass: return 'fail'
  return 'pass'
Пример #2
0
def common_make_root_canvas_test():
  testpass = True
  canvas = common.make_root_canvas('canvas_name')
  testpass &= canvas.GetName().find('canvas_name') > -1
  canvas = common.make_root_canvas('canvas_name_2', 'canvas_title', bg_color=10, highlight_color=12, border_mode=1, frame_fill_color=2)
  testpass &= __test_root_canvas(canvas, 'canvas_name_2', 'canvas_title', 10, 12, 1, 2)
  if testpass: return 'pass'
  return 'fail'
Пример #3
0
def plot_one_phi(row_data, da_key, axis1, axis2, max_n_points, variables):
    global ROOT_OBJECTS
    hit_data = row_data[da_key]
    name = "phi_" + da_key + "_" + axis1 + " vs " + axis2
    title = get_title(variables)
    name += " " + title
    canvas = None
    tune_data = []
    area_data = []
    da_row = get_da_row(hit_data, max_n_points)
    print("Plot on phi")
    cholesky_canvas = common.make_root_canvas(name + "_cholesky")
    cholesky_canvas.SetCanvasSize(1000, 1000)
    delta = (da_row + 1) * 0.4 + 1.
    hist = common.make_root_histogram("", [-100.],
                                      "u",
                                      100, [-100.],
                                      "u'",
                                      100,
                                      xmin=-delta,
                                      xmax=+delta,
                                      ymin=-delta,
                                      ymax=+delta)
    hist.Draw()
    for i, hit_list in enumerate(hit_data[:da_row + 1]):
        hit_list = [Hit.new_from_dict(hit_dict) for hit_dict in hit_list[1]]
        finder = DPhiTuneFinder()
        finder.u = [hit[axis1] for hit in hit_list[1:]]
        finder.up = [hit[axis2] for hit in hit_list[1:]]
        area_src = numpy.array([[hit[axis1], hit[axis2]] for hit in hit_list])
        try:
            finder.get_tune()
            an_area = get_area(area_src)
        except Exception:
            print("Failed to unpack data for phi da plot")
            continue
        cholesky_canvas, hist, graph = finder.plot_cholesky_space(
            cholesky_canvas, 1. + i * 0.2)
        if i < da_row:
            color = ROOT.TColor(10000 + len(ROOT_OBJECTS), 0.,
                                1. - i * 1. / da_row, 0.)
            ROOT_OBJECTS.append(color)
            graph.SetMarkerColor(ROOT.kGreen)
        ROOT_OBJECTS += [hist, graph]
        tune_data += copy.deepcopy(finder.dphi)
        area_data += [an_area for i in finder.dphi]
        print("    Area", an_area, end=' ')
        print(" tune", numpy.mean(tune_data), "+/-", numpy.std(tune_data))
    canvas = common.make_root_canvas(name)
    canvas.Draw()
    hist, graph = common.make_root_graph(name, area_data, "Amplitude [mm]",
                                         tune_data, "Fractional tune")
    ROOT_OBJECTS += [hist, graph]
    hist.SetTitle(da_key)
    hist.Draw()
    graph.SetMarkerStyle(24)
    graph.Draw("p same")
    return canvas, cholesky_canvas
def plot_alignment(data, plot_dir):
    del data[0]
    optimisation_set = set([opt_key(item) for item in data])
    for opt in optimisation_set:
        name = opt.replace("Coils", "")
        results = [item for item in data if opt_key(item) == opt]
        canvas = common.make_root_canvas("alignment - "+name)
        n_list = range(len(results))
        x_list = [item["axes"][opt]["x"]["value"] for item in results]
        y_list = [item["axes"][opt]["y"]["value"] for item in results]
        xp_list = [item["axes"][opt]["xp"]["value"]*1000. for item in results]
        yp_list = [item["axes"][opt]["yp"]["value"]*1000. for item in results]

        hist, zero_graph = common.make_root_graph("x residual",
                                                 [0, len(results)], "Iteration",
                                                 [0., 0.], "Residual [mm]")
        hist, x_graph = common.make_root_graph("x alignment", n_list, "iteration", x_list, "misalignment [mm]")
        hist, y_graph = common.make_root_graph("y alignment", n_list, "iteration", y_list, "misalignment [mm]")
        hist, all_graph = common.make_root_graph("all alignment", n_list*2, "iteration", x_list+y_list, "misalignment [mm]")
        hist.SetTitle(name+" alignment")
        hist.Draw()
        zero_graph.Draw("SAMEL")
        x_graph.Draw("SAMEP")
        x_graph.SetMarkerStyle(24)
        x_graph.SetMarkerColor(4)
        y_graph.Draw("SAMEP")
        y_graph.SetMarkerStyle(24)
        y_graph.SetMarkerColor(8)
        canvas.Update()
        for format in ["pdf", "png", "root"]:
            canvas.Print(plot_dir+"/alignment_"+name+"."+format)


        canvas = common.make_root_canvas("tilt - "+name)
        hist, zero_graph = common.make_root_graph("x residual",
                                                 [0, len(results)], "Iteration",
                                                 [0., 0.], "Residual [mm]")
        hist, xp_graph = common.make_root_graph("x alignment", n_list, "iteration", xp_list, "tilt [mrad]")
        hist, yp_graph = common.make_root_graph("y alignment", n_list, "iteration", yp_list, "tilt [mrad]")
        hist, all_graph = common.make_root_graph("all alignment", n_list*2, "iteration", xp_list+yp_list, "titl [mrad]")
        hist.SetTitle(name+" tilt")
        hist.Draw()
        zero_graph.Draw("SAMEL")
        xp_graph.Draw("SAMEP")
        xp_graph.SetMarkerStyle(24)
        xp_graph.SetMarkerColor(4)
        yp_graph.Draw("SAMEP")
        yp_graph.SetMarkerStyle(24)
        yp_graph.SetMarkerColor(8)

        canvas.Update()
        for format in ["pdf", "png", "root"]:
            canvas.Print(plot_dir+"/tilt_"+name+"."+format)
    def pdf_ratio_plot(self, suffix):
        data = self.amp.amplitudes[suffix]["ratio"]
        name = "pdf_ratio_" + suffix
        canvas = common.make_root_canvas(name)
        canvas.SetName(name)

        pdf_graph_stats = self.get_asymm_error_graph(data["corrected_pdf"],
                                                     data["pdf_stats_errors"],
                                                     style=20,
                                                     name="PDF Ratio stats")
        pdf_graph_sys = self.get_asymm_error_graph(data["corrected_pdf"],
                                                   data["pdf_sum_errors"],
                                                   fill=ROOT.kGray,
                                                   name="PDF Ratio sys")
        graph_list = [pdf_graph_stats, pdf_graph_sys]
        draw_list = ["p", "2"]

        hist = self.get_hist(graph_list,
                             self.get_suffix_label(suffix) + " Amplitude [mm]",
                             "Number Ratio")
        hist.Draw()
        for i, graph in enumerate(graph_list):
            graph.Draw("SAME " + draw_list[i])
        self.text_box(graph_list)
        print "PDF"
        print data["corrected_pdf"]
        print data["pdf_stats_errors"]
        print data["pdf_sum_errors"]

        canvas.Update()
        for a_format in ["eps", "pdf", "root", "png"]:
            canvas.Print(self.plot_dir + canvas.GetName() + "." + a_format)
        return canvas
def graph_peak_times(a_data, errors, colour, y_range, canvas=None, title=""):
    hist, graph = common.make_root_graph("Volts",
                                         a_data["time_list"],
                                         "Time [ns]",
                                         a_data["voltage_list"],
                                         "Signal Voltage [V]",
                                         ymin=y_range[0],
                                         ymax=y_range[1])
    peak_time_list = [x["x"] for x in errors]
    peak_voltage_list = [x["y"] for x in errors]
    peak_hist, peak_graph = common.make_root_graph("Peaks", peak_time_list,
                                                   "Time of peak [ns]",
                                                   peak_voltage_list,
                                                   "Peak voltage")
    if canvas == None:
        canvas = common.make_root_canvas(title + "bpm peaks")
        canvas.Draw()
        hist.Draw()
    canvas.cd()
    peak_graph.SetMarkerColor(colour)
    peak_graph.SetMarkerStyle(4)
    peak_graph.Draw("p")
    graph.SetMarkerColor(colour)
    graph.Draw("p")
    canvas.Update()
    return canvas, hist, graph, peak_hist, peak_graph
 def matrix_plot(self, matrix, title, axis_1, axis_2):
     """
     Plot the matrix entries as a TH2D
     
     * matrix: matrix data to plot; list n_bins by n_bins
     * title: the title of the hist (used in the file name also)
     * axis_1: x axis title
     * axis_2: y axis title
     """
     bin_centre_list = self.amp.amplitudes["reco"]["all_upstream"][
         "bin_centre_list"]
     xmax = max(self.amp.bin_edge_list)
     nbins = len(bin_centre_list)
     matrix_hist = ROOT.TH2D(title, title + ";" + axis_1 + ";" + axis_2,
                             nbins, 0., xmax, nbins, 0., xmax)
     for i in range(nbins):
         for j in range(nbins):
             matrix_hist.Fill(bin_centre_list[i], bin_centre_list[j],
                              matrix[i][j])
     self.root_objects.append(matrix_hist)
     canvas = common.make_root_canvas(title)
     canvas.SetFrameFillColor(utilities.utilities.get_frame_fill())
     matrix_hist.SetTitle(self.config_anal['name'])
     matrix_hist.SetStats(False)
     matrix_hist.Draw("COLZ")
     title = title.replace(" ", "_")
     for format in ["eps", "png", "root"]:
         canvas.Print(self.plot_dir + title + "." + format)
Пример #8
0
 def _draw_volumes_2d(self, x_range, z_range):
     """Make a 2D plot of position vs volume"""
     canvas = common.make_root_canvas("Volume Name vs position")
     hist, graph = common.make_root_graph("Volume Name vs position",
                                          [1e9], "z [mm]",
                                          [1e9], "x [mm]",
                                          xmin=z_range[0], xmax=z_range[1],
                                          ymin=x_range[0], ymax=x_range[1])
     hist.Draw()
     draw_list = sorted(self.volume_data.keys(), self._sort_cmp)
     n_colors = 5
     for i, vol in enumerate(draw_list):
         data = self.volume_data[vol]
         r_list = [data["r_min"], data["r_max"], data["r_max"],
                   data["r_min"], data["r_min"]]
         z_list = [data["z_min"], data["z_min"], data["z_max"],
                   data["z_max"], data["z_min"]]
         hist, graph = common.make_root_graph(vol,
                                              z_list, "z [mm]",
                                              r_list, "r [mm]", sort = False)
         color = self.color(i % n_colors, n_colors)
         graph.SetLineColor(color)
         graph.Draw('l')
         self._draw_volume_label(data["z_min"], vol, x_range, color)
     canvas.Update()
     for _format in self.formats:
         canvas.Print(self.vol_2d+"."+_format)
Пример #9
0
 def _draw_materials_2d(self, step_data, material_dict, x_range, z_range):
     """Make a 2D plot of position vs material in r, z"""
     # we plot G4_AIR first, then G4_GALACTIC?
     canvas = common.make_root_canvas("Material vs position")
     hist, graph = common.make_root_graph("Material vs position", [1e9],
                                          "z [mm]", [1e9],
                                          "r [mm]",
                                          xmin=z_range[0],
                                          xmax=z_range[1],
                                          ymin=x_range[0],
                                          ymax=x_range[1])
     hist.Draw()
     draw_list = step_data.keys()
     draw_list = self.move(draw_list, "G4_AIR", 0)
     draw_list = self.move(draw_list, "G4_Galactic", 1)
     graph_list = []
     for material in draw_list:
         x_list = [step["r"] for step in step_data[material]]
         z_list = [step["z"] for step in step_data[material]]
         hist, graph = common.make_root_graph(material, z_list, "z [mm]",
                                              x_list, "r [mm]")
         graph.SetMarkerColor(material_dict[material])
         graph.SetMarkerStyle(7)
         graph.SetLineColor(10)
         graph.Draw('p')
         graph_list.append(graph)
     common.make_root_legend(canvas, graph_list)
     canvas.Update()
     for _format in self.formats:
         canvas.Print(self.mat_2d + "." + _format)
Пример #10
0
 def make_plot(self, data_list, da_row, name, x_name, y_name):
     graph_list = []
     for x_data, y_data in data_list:
         i = len(graph_list)
         hist, graph = common.make_root_graph(name + str(i), x_data, x_name,
                                              y_data, y_name)
         graph.SetMarkerStyle(7)
         if i == da_row:
             canvas = common.make_root_canvas(name)
             hist.SetTitle(name)
             hist.Draw()
         elif i == 0 and i < da_row:
             graph.SetMarkerColor(ROOT.kBlue)
         elif i < da_row:
             graph.SetMarkerColor(ROOT.kGreen)
         else:
             graph.SetMarkerColor(ROOT.kGray)
         graph_list.append(graph)
     canvas.cd()
     canvas.Update()
     for graph in graph_list[da_row+1:]+graph_list[1:da_row]+\
                  graph_list[0:1]+graph_list[da_row:da_row+1]:
         graph.Draw("SAMEP")
     name = name.replace(":", "")
     name = name.replace(" ", "_")
     for fmt in self.formats:
         canvas.Print(self.plot_dir + "/" + name + "." + fmt)
Пример #11
0
 def _draw_materials_2d(self, step_data, material_dict, x_range, z_range):
     """Make a 2D plot of position vs material in r, z"""
     # we plot G4_AIR first, then G4_GALACTIC?
     canvas = common.make_root_canvas("Material vs position")
     hist, graph = common.make_root_graph("Material vs position",
                                          [1e9], "z [mm]",
                                          [1e9], "r [mm]",
                                          xmin=z_range[0], xmax=z_range[1],
                                          ymin=x_range[0], ymax=x_range[1])
     hist.Draw()
     draw_list = step_data.keys()
     draw_list = self.move(draw_list, "G4_AIR", 0)
     draw_list = self.move(draw_list, "G4_Galactic", 1)
     graph_list = []
     for material in draw_list:
         x_list = [step["r"] for step in step_data[material]]
         z_list = [step["z"] for step in step_data[material]]
         hist, graph = common.make_root_graph(material,
                                              z_list, "z [mm]",
                                              x_list, "r [mm]")
         graph.SetMarkerColor(material_dict[material])
         graph.SetMarkerStyle(7)
         graph.SetLineColor(10)
         graph.Draw('p')
         graph_list.append(graph)
     common.make_root_legend(canvas, graph_list)
     canvas.Update()
     for _format in self.formats:
         canvas.Print(self.mat_2d+"."+_format)
def plot_trajectory(item, line_color, canvas = None):
    z_list = [hit["z"] for hit in item["seed"]]
    x_list = [hit["x"] for hit in item["seed"]]
    y_list = [hit["y"] for hit in item["seed"]]
    r_list = [hit["r"] for hit in item["seed"]]

    x_min, x_max = common.min_max(x_list+r_list+y_list)
    title = "x: "+str(item["seed"][0]["x"])+" mm "+\
            "p_{x}: "+str(item["seed"][0]["px"])+" MeV/c"
    hist_r, graph_r = common.make_root_graph(title, z_list, "z [mm]", r_list, "Radius [mm]", ymin=0.0, ymax=250.)
    hist_x, graph_x = common.make_root_graph("x", z_list, "z [mm]", x_list, "Position [mm]")
    hist_y, graph_y = common.make_root_graph("y", z_list, "z [mm]", y_list, "Position [mm]")
    graph_r.SetLineColor(line_color)
    graph_x.SetLineColor(line_color)
    graph_x.SetLineStyle(3)
    graph_y.SetLineColor(line_color)
    graph_y.SetLineStyle(4)
    if canvas == None:
        canvas = common.make_root_canvas("trajectory")
        #hist_r.SetTitle("x = "+str(x_list[0])+" px = "+str(item["seed"][0]["px"]))
        hist_r.Draw()
    canvas.cd()
    graph_r.Draw("SAMEPL")
    #graph_x.Draw("SAMEPL")
    #graph_y.Draw("SAMEPL")
    canvas.Update()

    return canvas, graph_r
def graph_peak_magnitude(pos_peak_with_errors, neg_peak_with_errors, title):
    peak_time_list, peak_voltage_list, peak_err_list = [], [], []
    for i, v_pos in enumerate(pos_peak_with_errors):
        di = 0
        if i >= len(neg_peak_with_errors):
            break
        while neg_peak_with_errors[i+di]["x"] < pos_peak_with_errors[i]["x"]:
            if i+di+1 >= len(neg_peak_with_errors):
                break
            di += 1
        v_neg = neg_peak_with_errors[i+di]
        v_0 = (v_pos["y"]+v_neg["y"])/2.
        v_err = abs(v_0)*(v_pos["cov(x,y)"][1][1]/v_pos["y"]**2+v_neg["cov(x,y)"][1][1]/v_neg["y"]**2)**0.5
        peak_voltage_list.append(v_0)
        peak_err_list.append(v_err*1e3)
        peak_time_list.append(v_pos["x"]*DT)
    print "    Peak voltage mean:", numpy.mean(peak_voltage_list[-20:-10]),
    print "sigma:", numpy.std(peak_voltage_list[-20:-10])
    canvas = common.make_root_canvas(title+" rf voltage")
    canvas.Draw()
    canvas.cd()
    y_range = common.min_max(peak_voltage_list+peak_err_list)
    hist, graph = common.make_root_graph("Peaks", peak_time_list, "Time of peak [ns]", peak_voltage_list, "Peak voltage [kV]", ymin = y_range[0], ymax = y_range[1])
    hist.Draw()
    graph.SetMarkerStyle(6)
    graph.Draw("p")
    hist, graph = common.make_root_graph("Errors", peak_time_list, "Time of peak [ns]", peak_err_list, "Error [V]", ymin = y_range[0], ymax = y_range[1])
    graph.SetMarkerColor(2)
    graph.SetMarkerStyle(6)
    graph.Draw("p")
    canvas.Update()    
    return canvas, hist, graph
Пример #14
0
 def _draw_volumes_1d(self, z_range):
     """Make a 1D plot of position vs volume along the z axis"""
     draw_list = sorted(self.volume_data.keys(), self._sort_cmp)
     x_list = []
     canvas = common.make_root_canvas("Volume Name vs z")
     # set up axis labels
     print "VOLUME PLOT", z_range
     hist = ROOT.TH2D("name", "Volume Name vs z", 30000,
                      z_range[0], z_range[1],
                      len(draw_list)+1, -0.5, len(draw_list)+0.5)
     common._common._hist_persistent.append(hist) #pylint: disable=W0212
     for material in draw_list:
         hist.Fill(z_range[0], material, 1.)
     hist.SetBit(ROOT.TH1.kCanRebin)
     hist.SetStats(0)
     hist.LabelsDeflate("Y")
     hist.LabelsOption("v")
     hist.Draw()
     # now draw graphs
     for i, volume in enumerate(draw_list):
         x_list = [self.volume_data[volume]["z_min"],
                     self.volume_data[volume]["z_max"]]
         y_list = [i+0.1, i+0.1]
         hist, graph = common.make_root_graph("", x_list, "z [mm]",
                                                y_list, "volume index")
         graph.SetLineColor(ROOT.TColor.GetColor(0.5, 0.5, 0.5))
         graph.Draw('l')
         if self.volume_data[volume]["r_min"] < 1e-9:
             y_list = [i, i]
             hist, graph = common.make_root_graph("", x_list, "z [mm]",
                                                    y_list, "material index")
             graph.Draw('l')
     canvas.Update()
     for _format in self.formats:
         canvas.Print(self.vol_1d+"."+_format)
Пример #15
0
    def test_binomial(self):
        """
        Check that we can generate a binomial distribution for event number
        """
        # make a dict of bunches of xboa.Hits separated by event (spill) number
        bunch_dict = Bunch.new_dict_from_read_builtin('maus_json_primary', \
                          BIN_SIM, 'spill')
        bunch_weights = []
        for bunch in bunch_dict.values():
            bunch_weights.append(bunch.bunch_weight())
        canvas = common.make_root_canvas("")
        hist = common.make_root_histogram("generated distribution", \
             bunch_weights, "bunch weights", BIN_N+1, xmin=-0.5, xmax=BIN_N+0.5)
        hist.Fill(0, 1000-hist.GetSumOfWeights()) # xboa ignores empty spills
        hist.Draw()

        test_hist = ROOT.TH1D("test_hist", "reference distribution", BIN_N+1, -0.5, BIN_N+0.5)  # pylint: disable = E1101, C0301
        for i in range(BIN_N+1):
            test_hist.SetBinContent(i, \
                    (ROOT.TMath.BinomialI(BIN_P, BIN_N, i-1)- ROOT.TMath.BinomialI(BIN_P, BIN_N, i))*N_SPILLS) # pylint: disable = E1101, C0301
            print i, test_hist.GetBinContent(i), hist.GetBinContent(i)
        test_hist.SetLineStyle(2)
        test_hist.Draw("SAME")
        ks_value = test_hist.KolmogorovTest(hist)
        canvas.Update()
        canvas.Print(PLOT_DIR+"/binomial_distribution_test.png")
        print "binomial ks_value", ks_value
        self.assertGreater(ks_value, 1e-3)
Пример #16
0
def plot_z(item, line_color, do_square, canvas=None):
    z_list = [hit["z"] for hit in item["seed"]]
    if not do_square:  #i.e. do triangle
        area_list = [
            abs(area / item["an_area_list"][0] - 1)
            for area in item["an_area_list"]
        ]
    else:
        area_list = [
            abs(sum(area_list) / sum(item["area_list_of_lists"][0]) - 1)
            for area_list in item["area_list_of_lists"]
        ]

    title = "x: "+str(item["seed"][0]["x"])+" mm "+\
            "p_{x}: "+str(item["seed"][0]["px"])+" MeV/c"
    hist, graph = common.make_root_graph(
        title,
        z_list,
        "z [mm]",
        area_list,
        "Fractional change in simplex content",
        ymin=1e-5,
        ymax=100.)
    if canvas == None:
        canvas = common.make_root_canvas("content growth vs z")
        canvas.SetLogy()
        hist.Draw()
    canvas.cd()
    graph.SetLineColor(line_color)
    graph.Draw("SAMEPL")
    canvas.Update()
    return canvas, graph
Пример #17
0
    def test_binomial(self):
        """
        Check that we can generate a binomial distribution for event number
        """
        # make a dict of bunches of xboa.Hits separated by event (spill) number
        bunch_dict = Bunch.new_dict_from_read_builtin('maus_json_primary', \
                          BIN_SIM, 'spill')
        bunch_weights = []
        for bunch in bunch_dict.values():
            bunch_weights.append(bunch.bunch_weight())
        canvas = common.make_root_canvas("")
        hist = common.make_root_histogram("generated distribution", \
             bunch_weights, "bunch weights", BIN_N+1, xmin=-0.5, xmax=BIN_N+0.5)
        hist.Fill(0,
                  1000 - hist.GetSumOfWeights())  # xboa ignores empty spills
        hist.Draw()

        test_hist = ROOT.TH1D("test_hist", "reference distribution", BIN_N + 1,
                              -0.5,
                              BIN_N + 0.5)  # pylint: disable = E1101, C0301
        for i in range(BIN_N + 1):
            test_hist.SetBinContent(i, \
                    (ROOT.TMath.BinomialI(BIN_P, BIN_N, i-1)- ROOT.TMath.BinomialI(BIN_P, BIN_N, i))*N_SPILLS) # pylint: disable = E1101, C0301
            print i, test_hist.GetBinContent(i), hist.GetBinContent(i)
        test_hist.SetLineStyle(2)
        test_hist.Draw("SAME")
        ks_value = test_hist.KolmogorovTest(hist)
        canvas.Update()
        canvas.Print(PLOT_DIR + "/binomial_distribution_test.png")
        print "binomial ks_value", ks_value
        self.assertGreater(ks_value, 1e-3)
Пример #18
0
def plot_acceptance(da_list, eigenspace_key):
    global ERRORS_GRAPH, MIN_N_CELLS
    plot_dir = "baseline/"
    acceptance_list_0 = []
    acceptance_list_1 = []
    pphi_list = []
    mean_acceptance_list_0 = []
    mean_acceptance_list_1 = []
    mean_pphi_list = []
    means_0 = ROOT.TGraphErrors(len(da_list))
    means_0.SetMarkerStyle(21)
    means_0.SetMarkerColor(8)
    means_0.SetLineColor(8)
    means_1 = ROOT.TGraphErrors(len(da_list))
    means_1.SetMarkerStyle(21)
    means_1.SetMarkerColor(4)
    means_1.SetLineColor(4)
    ERRORS_GRAPH.append(means_0)
    ERRORS_GRAPH.append(means_1)
    for i, element in enumerate(da_list):
        ekin = get_ekin(element)
        acceptance_list = get_acceptance(element, eigenspace_key, 0)
        if len(acceptance_list) < 5:
            continue
        acceptance_list_0 += acceptance_list
        means_0.SetPoint(i, ekin, numpy.mean(acceptance_list))
        means_0.SetPointError(i, 0., 0.)  #numpy.std(acceptance_list))
        acceptance_list = get_acceptance(element, eigenspace_key, 1)
        acceptance_list_1 += acceptance_list
        means_1.SetPoint(i, ekin, numpy.mean(acceptance_list))
        means_1.SetPointError(i, 0., 0.)  #numpy.std(acceptance_list))
        pphi_list += [ekin for item in acceptance_list]
    canvas = common.make_root_canvas("acceptance " + eigenspace_key)
    canvas.Draw()
    axes, graph = common.make_root_graph('axes',
                                         pphi_list,
                                         "E_{kin} [MeV]",
                                         acceptance_list_0,
                                         "A_{2D} [mm]",
                                         ymin=-0.01,
                                         ymax=20.)
    axes.Draw()
    da_eigenspace = {'da_1': 0, 'da_2': 1, 'da_3': 2}[eigenspace_key]
    axes.SetTitle("Acceptance for eigenspace " + str(da_eigenspace) +
                  " requiring " + str(MIN_N_CELLS / CELL_STEP) + " turns")
    for acceptance_list, color in [(acceptance_list_0, 8),
                                   (acceptance_list_1, 4)]:
        dummy, graph = common.make_root_graph('axes', pphi_list,
                                              "P_{phi} [MeV/c]",
                                              acceptance_list, "A_{2D} [mm]")
        graph.SetMarkerStyle(7)
        graph.SetMarkerColor(color)
        graph.Draw('pSAME')
        means_0.Draw('PSAME')
        means_1.Draw('PSAME')
    canvas.Update()
    name = "acceptance_eigenspace_" + str(da_eigenspace)
    for format in "png", "root", "pdf":
        canvas.Print(plot_dir + name + "." + format)
Пример #19
0
    def find_peak_errors_derivative(self, data, peak_list, delta_index, draw=False):
        """
        Find the error on the peak estimation based on a linear fit to the
        derivative
        """
        derivative = self._get_derivative(data)
        # we want to fit for x = my + c
        # c is the peak
        # chi2 gives estimate of fit errors
        peak_with_errors = []
        for peak in peak_list:
            x_min = max(peak-delta_index, 0)
            x_max = min(peak+delta_index+1, len(derivative))
            x_list = range(x_min, x_max)
            y_list = derivative[x_min:x_max]
            graph = ROOT.TGraph(len(x_list))
            for i in range(5):
                self.fit.SetParameter(i, 0.)
            for i in range(2, 5):
                self.fit.FixParameter(i, 0.)
            self.fit.SetRange(min(y_list), max(y_list))
            for i, x in enumerate(x_list):
                y = y_list[i]
                graph.SetPoint(i, y, x) # note this is intentionally backwards
            graph.Fit(self.fit, "NO")
            if draw:
                canvas = common.make_root_canvas("derivatives")
                canvas.Draw()
                canvas.cd()
                hist, graph = common.make_root_graph("name", x_list, "", y_list, "")
                hist.Draw()
                graph.SetMarkerStyle(6)
                graph.Draw('p')
                canvas.Update()

                canvas = common.make_root_canvas("values")
                canvas.Draw()
                canvas.cd()
                hist, graph = common.make_root_graph("name", x_list, "", data[x_min:x_max], "")
                hist.Draw()
                graph.SetMarkerStyle(6)
                graph.Draw('p')
                canvas.Update()
            peak_with_errors.append([self.fit.GetParameter(0),
                                     self.fit.GetParError(0)])
        return peak_with_errors
def plot_data_vs_delta(data, title, filter_lambdas, x_axis_lambda, x_axis_name, canvas_square = None, canvas_tri = None, line_color=1):
    data = filter_data(data, filter_lambdas)

    if len(data) == 0:
        return canvas_square, canvas_tri
    print "plot", title
    delta_list = [x_axis_lambda(item) for item in data]
    triangle_list = [abs(item["an_area_list"][-1]/item["an_area_list"][0]-1) for item in data]
    square_list = [abs(sum(item["area_list_of_lists"][-1])/sum(item["area_list_of_lists"][0])-1) for item in data]
    print triangle_list, delta_list
    ymin=min(square_list+triangle_list)*0.1
    ymax=max(square_list+triangle_list)*1.1


    hist, graph = common.make_root_graph("step size "+str(data[0]['step_size'])+" mm",
                              delta_list, x_axis_name,
                              triangle_list, "Fractional change in simplex content",
                              xmin=min(delta_list)*0.9, ymin=ymin, ymax=ymax)
    if canvas_tri == None:
        canvas_tri = common.make_root_canvas("delta triangles - "+title)
        canvas_tri.SetLogy()
        hist.Draw()
    hist.SetTitle(title)
    canvas_tri.cd()
    graph.SetLineColor(line_color)
    graph.SetMarkerStyle(24)
    graph.Draw("SAMEPL")
    canvas_tri.Update()
    hist, graph = common.make_root_graph("step size "+str(data[0]['step_size'])+" mm",
                                         delta_list, x_axis_name,
                                         square_list, "Fractional change in hypercube content",
                                         xmin=min(delta_list)*0.9, ymin=ymin, ymax=ymax)
    hist.SetTitle(title)
    if canvas_square == None:
        canvas_square = common.make_root_canvas("delta triangles - "+title)
        canvas_square.SetLogy()
        hist.Draw()
    canvas_square.cd()
    graph.SetLineColor(line_color)
    graph.SetMarkerStyle(24)
    graph.Draw("SAMEPL")
    canvas_square.Update()

    return canvas_square, canvas_tri
Пример #21
0
def plot_fields(data, plot_dir, foil_probe, foil_var, axis_name):
    bump_fields = {}
    bump_position = get_bump_position(data, foil_probe, foil_var)
    for bump in data:
        for key in bump["bump_fields"]:
            if key not in bump_fields:
                bump_fields[key] = []
            bump_fields[key].append(bump["bump_fields"][key])
    print("bump_fields = {")
    for key in bump_fields:
        print("    \"" + key + "\" :", bump_fields[key], ",")
    print("}")
    canvas = common.make_root_canvas("fields")
    all_fields = []
    for key in bump_fields:
        all_fields += bump_fields[key]
    delta = 0.2
    max_pos = (1. + delta) * max(bump_position) - delta * min(bump_position)
    hist, graph = common.make_root_graph(
        "fields",
        bump_position * len(bump_fields) + [max_pos], axis_name,
        all_fields + [0.], "Dipole field [T]")
    hist.Draw()
    color = [
        ROOT.kBlue, ROOT.kGreen + 2, ROOT.kRed, ROOT.kYellow + 2,
        ROOT.kCyan + 1
    ]
    marker = [20, 24, 21, 25]
    leg_list = []
    index = 0
    marker_index = 0
    for key, field in sorted(bump_fields.items()):
        name = key.replace("__", "")
        name = name.replace("_", " ")
        hist, graph = common.make_root_graph(name, bump_position, axis_name,
                                             field, "Dipole field [T]")
        graph.SetMarkerStyle(marker[marker_index])
        graph.SetMarkerColor(color[index])
        graph.SetLineColor(color[index])
        graph.SetLineStyle(color[index])
        graph.Draw("lpsame")
        leg_list.append(graph)
        index += 1
        if index == len(color):
            index = 0
            marker_index += 1
    leg = common.make_root_legend(canvas, leg_list)
    leg.SetBorderSize(1)
    leg.SetX1NDC(0.75)
    leg.SetX2NDC(0.9)
    leg.SetY1NDC(0.5)
    leg.SetY2NDC(0.9)
    leg.Draw()
    canvas.Update()
    for format in ["png"]:
        canvas.Print(plot_dir + "/bump_fields." + format)
Пример #22
0
 def make_global_plot(self, min_n_points, plot_dir):
     axis_candidates = utilities.get_substitutions_axis(
         self.data, "substitutions")
     my_axes_x = dict([(key, []) for key in axis_candidates])
     da = {'y_da': [], 'x_da': []}
     for item in self.data:
         for da_key in da:
             if da_key not in list(item.keys()):
                 print("Did not find", da_key, "in keys", list(item.keys()),
                       "... skipping")
                 continue
             da[da_key].append(
                 self.calculate_da(item, da_key, min_n_points) * 1e3)
             print(da_key, da[da_key][-1])
         for ax_key in my_axes_x:
             my_axes_x[ax_key].append(item['substitutions'][ax_key])
     for ax_key in my_axes_x:
         ordinate = my_axes_x[ax_key]
         x_name = utilities.sub_to_name(ax_key)
         canvas_name = x_name + ' vs da'
         canvas = common.make_root_canvas(canvas_name)
         canvas.SetLogy()
         x_range = [min(ordinate), max(ordinate)]
         y_range = [
             min(da['x_da'] + da['y_da']),
             max(da['x_da'] + da['y_da'])
         ]
         y_range[0] = max(y_range[0] / 2, 0.01)
         hist, graph = common.make_root_graph('axes',
                                              x_range,
                                              x_name,
                                              y_range,
                                              "DA [#pi #mum]",
                                              ymin=y_range[0],
                                              ymax=y_range[1] * 3)
         hist.Draw()
         if len(da['x_da']) == len(ordinate):
             hist_x, graph_x = common.make_root_graph(
                 'horizontal da', ordinate, "", da['x_da'], "")
             graph_x.SetMarkerStyle(24)
             graph_x.SetMarkerColor(2)
             graph_x.Draw("SAME P")
         if len(da['y_da']) == len(ordinate):
             hist_y, graph_y = common.make_root_graph(
                 'vertical da', ordinate, "", da['y_da'], "")
             graph_y.SetMarkerStyle(26)
             graph_y.SetMarkerColor(4)
             graph_y.Draw("SAME P")
         #legend = common.make_root_legend(canvas, [graph_x, graph_y])
         #legend.Draw()
         canvas.Update()
         canvas_name = canvas_name.replace(" ", "_")
         for format in "eps", "png", "root":
             canvas.Print(plot_dir + "/" + canvas_name + "." + format)
     return
Пример #23
0
 def plot_gauss(self, x_list, gauss_list):
     canvas = common.make_root_canvas("gauss")
     canvas.Draw()
     canvas.SetLogy()
     hist, graph = common.make_root_graph("gauss", x_list, "position", gauss_list, "Gauss")
     hist.Draw()
     graph.Draw('l')
     fit_function = ROOT.TF1("fit", "gaus")
     graph.Fit(fit_function)
     canvas.Update()
     return fit_function        
Пример #24
0
    def plot_one_da(self, row_data, da_key, axis1, axis2, max_n_points,
                    variables, acceptance):
        hit_data = row_data[da_key]
        name = da_key + "_" + axis1 + " vs " + axis2
        title = self.get_title(variables)
        name += " " + title
        canvas = None
        da_row = self.get_da_row(hit_data, max_n_points)
        graph_list = []
        acceptance_graph = None
        units = {
            'x': 'mm',
            'y': 'mm',
            'px': 'MeV/c',
            'py': 'MeV/c',
            "x'": 'rad',
            "y'": 'rad'
        }
        for i, hit_list in enumerate(hit_data):
            hit_list = [
                Hit.new_from_dict(hit_dict) for hit_dict in hit_list[1]
            ]
            x_data = [hit[axis1] for hit in hit_list]
            y_data = [hit[axis2] for hit in hit_list]
            axis1_label = axis1 + " [" + units[axis1] + "]"
            axis2_label = axis2 + " [" + units[axis2] + "]"
            hist, graph = common.make_root_graph(name + " " + str(i), x_data,
                                                 axis1_label, y_data,
                                                 axis2_label)
            graph.SetMarkerStyle(7)
            if i == da_row:
                canvas = common.make_root_canvas(name)
                hist.SetTitle(title)
                hist.Draw()
            elif i < da_row:
                graph.SetMarkerColor(ROOT.kGreen)
            else:
                graph.SetMarkerColor(ROOT.kGray)
            graph_list.append(graph)
            pz = hit_list[0]['pz']
            mass = common.pdg_pid_to_mass[2212]
            if axis2 == "px" or axis2 == "py":
                geom_acceptance = acceptance * mass  #mm mrad normalised -> MeV/c
            elif axis2 == "x'" or axis2 == "y'":
                geom_acceptance = acceptance * mass / pz
            #if i == 3:
            #    acceptance_graph = self.plot_acceptance(geom_acceptance, x_data, y_data, axis2)

        for graph in graph_list:
            graph.Draw("SAMEP")
        if acceptance_graph != None:
            acceptance_graph.Draw("SAME C")
        canvas.Update()
        return canvas
Пример #25
0
    def test_apply_weights_bound(self):
        test_bunch = Bunch()
        for i in range(1000):
            x = random.gauss(0., 10.**0.5)
            y = random.gauss(0., 20.**0.5)
            test_hit = Hit.new_from_dict({'x':x, 'y':y})
            test_bunch.append(test_hit)
        limit_ellipse = numpy.zeros([2, 2])
        for i in range(2):
            limit_ellipse[i, i] = 200.
        bound = BoundingEllipse(limit_ellipse, numpy.zeros([2]), 50)

        my_weights = VoronoiWeighting(['x', 'y'],
                                      numpy.array([[20., 0.],[0., 20.]]),
                                      voronoi_bound = bound)
        print("Plotting weights", datetime.datetime.now())
        canvas, hist = test_bunch.root_histogram('x', 'mm', 'y', 'mm')
        hist.Draw("COLZ")
        canvas.Update()
        print('Covariances ["x", "y"] before\n', test_bunch.covariance_matrix(['x', 'y']))
        print("Applying weights", datetime.datetime.now())
        my_weights.apply_weights(test_bunch, False)
        print("Plotting tesselation", datetime.datetime.now())
        #my_weights.plot_two_d_projection(['x', 'y'], 'weight')
        my_weights.plot_two_d_projection(['x', 'y'], 'weight')
        my_weights.plot_two_d_projection(['x', 'y'], 'content')
        print("Plotting weights", datetime.datetime.now())
        canvas, hist = test_bunch.root_histogram('x', 'mm', 'y', 'mm')
        hist.Draw("COLZ")
        canvas.Update()
        test_bunch.root_histogram('local_weight', nx_bins=100)
        canvas = common.make_root_canvas('local_weight')
        hist = common.make_root_histogram('local_weight', test_bunch.list_get_hit_variable(['local_weight'])[0], 'local_weight', 100)
        hist.Draw()
        canvas.Update()
        canvas = common.make_root_canvas('content')
        hist = common.make_root_histogram('content', my_weights.tile_content_list, 'content', 100)
        hist.Draw()
        canvas.Update()
        print('Covariances ["x", "y"] after\n', test_bunch.covariance_matrix(['x', 'y']))
def plot_heat(data, plane = None, canvas = None):
    if plane != None:
        print "Doing plane", plane
    data = filter_data(data, [lambda item: item["an_area_list"][-1] != None],)
    data = filter_data(data, [lambda item: item["seed"][-1]["r"] < 1e3],)
 
    triangle_list = []
    for item in data:
        if plane == None:
            triangle_list.append(abs(item["an_area_list"][-1]/item["an_area_list"][0]-1))
        else:
            if plane < len(item["an_area_list"]):
                triangle_list.append(abs(item["an_area_list"][plane]/item["an_area_list"][0]-1))
            else:
                triangle_list.append(1e9)
    x_list = [item["seed"][0]["x"] for item in data]
    px_list = [item["seed"][0]["px"] for item in data]
    
    x_min, x_max, n_x_bins = get_axis(x_list)
    px_min, px_max, n_px_bins = get_axis(px_list)
    if canvas == None:
        canvas = common.make_root_canvas("heating map")
        if plane != None:
            canvas.SetCanvasSize(700, 1000)
            canvas.Divide(1, 2)
    if plane != None:       
        canvas.cd(2)
        get_b_field(canvas.GetPad(2), z = item["seed"][plane]["z"])
        canvas.cd(1)
        canvas.GetPad(1).SetLogz()
    hist = ROOT.TH2D("heating map", ";x [mm];p_{x} [MeV/c]", n_x_bins, x_min, x_max, n_px_bins, px_min, px_max)
    hist.SetStats(False)
    z_min, z_max = 1e-4, 100.
    hist.GetZaxis().SetRangeUser(z_min, z_max)
    canvas.Draw()
    for i, content in enumerate(triangle_list):
        bin = hist.FindBin(x_list[i], px_list[i])
        if content < z_min:
            content = z_min*1.00001
        if content > z_max:
            content = z_max*0.99999
        hist.SetBinContent(bin, content)
    hist.Draw("COLZ")
    root_list.append(hist)
    canvas.SetLogz()
    canvas.Update()
    if plane == None:
        canvas.Print("plots/heat_map.png")
    else:
        name = str(plane).rjust(4, '0')
        canvas.Print("plots/heat_map_"+name+".gif")
    return canvas
    def cdf_plot(self, suffix):
        us_data = self.amp.amplitudes[suffix]["all_upstream"]
        ds_data = self.amp.amplitudes[suffix]["all_downstream"]
        name = "amplitude_cdf_" + suffix
        canvas = common.make_root_canvas(name)
        canvas.SetName(name)

        upstream_graph = self.get_asymm_error_graph(
            us_data["corrected_cdf"],
            us_data["cdf_stats_errors"],
            style=24,
            color=self.us_color,
            name="Upstream CDF stats",
            centred=False)
        downstream_graph = self.get_asymm_error_graph(
            ds_data["corrected_cdf"],
            ds_data["cdf_stats_errors"],
            style=26,
            color=self.ds_color,
            name="Downstream CDF stats",
            centred=False)
        upstream_graph_sys = self.get_asymm_error_graph(
            us_data["corrected_cdf"],
            us_data["cdf_sum_errors"],
            fill=self.us_color,
            name="Upstream CDF sys",
            centred=False)
        downstream_graph_sys = self.get_asymm_error_graph(
            ds_data["corrected_cdf"],
            ds_data["cdf_sum_errors"],
            fill=self.ds_color,
            name="Downstream CDF sys",
            centred=False)
        graph_list = [
            upstream_graph, downstream_graph, upstream_graph_sys,
            downstream_graph_sys
        ]
        draw_list = ["p", "p", "2", "2"]

        hist = self.get_hist(graph_list,
                             self.get_suffix_label(suffix) + " Amplitude [mm]",
                             "Cumulative Number")
        hist.Draw()
        for i, graph in enumerate(graph_list):
            graph.Draw("SAME " + draw_list[i])
        self.text_box(graph_list)

        canvas.Update()
        for a_format in ["eps", "pdf", "root", "png"]:
            canvas.Print(self.plot_dir + "amplitude_cdf_" + suffix + "." +
                         a_format)
        return canvas
def graph_peak_errors(error_list, colour, canvas = None, title=""):
    peak_time_list = [x["x"]*DT for x in error_list] # 0.2 ns per count
    peak_error_list = [(x["cov(x,y)"][0][0]**0.5)*DT for x in error_list]
    hist, graph = common.make_root_graph("Peaks", peak_time_list, "Time of peak [ns]", peak_error_list, "Estimated error on peak [ns]")
    if canvas == None:
        canvas = common.make_root_canvas(title+" errors")
        canvas.Draw()
        hist.Draw()
    canvas.cd()
    graph.SetMarkerStyle(6)
    graph.SetMarkerColor(colour)
    graph.Draw("p")
    canvas.Update()    
    return canvas, hist, graph
Пример #29
0
def common_make_root_ellipse_function_test():
    testpass = True
    # worth checking by eye - the ellipse should be tilted forwards (i.e. +ve
    # correlation); and should roughly fill the canvas. If one sets correlation
    # to 0., y-intercept at x=0., 200. and x-intercept at y=0., 2.
    ell_cov = numpy.array([[10000., 0.], [0., 1.]])
    ell_mean = [100., 1.]
    canv = common.make_root_canvas("ellipse_function_test_0")
    func = common.make_root_ellipse_function(ell_mean, ell_cov, contours=[1.], xmin=-10., xmax=210., ymin=-0.1, ymax=2.1)
    func.Draw()
    canv.Update()
    for value in [(0., 1.), (200., 1.), (100., 0.), (100., 2.)]:
        testpass = testpass and (func.Eval(*value)-1.) < common.float_tolerance
        if not testpass:
            print('FAILED ON ', value, func.Eval(*value))

    ell_cov = numpy.array([[3, 1], [1, 2]])
    ell_mean = [1, 1]
    canv = common.make_root_canvas("ellipse_function_test_1")
    func = common.make_root_ellipse_function(ell_mean, ell_cov)
    func.Draw()
    canv.Update()

    ell_cov = numpy.array([[1, 0.99], [0.99, 1]])
    ell_mean = [1, 1]
    canv = common.make_root_canvas("ellipse_function_test_2")
    func = common.make_root_ellipse_function(ell_mean, ell_cov, [1., 0.08], 1-3, 1+3, 1-2, 1+2)
    func.SetLineColor(4)
    func.Draw()
    canv.Update()

    # note this looks grotty - blame ROOT
    testpass = testpass and (func.GetContourLevel(1)-0.08) < common.float_tolerance \
                        and (func.GetContourLevel(0)-1.) < common.float_tolerance
    if testpass:
        return 'pass'
    return 'fail'
def graph_delta_times(error_list, colour, canvas = None, title=""):
    peak_time_list = [x["x"]*DT for x in error_list] # 0.2 ns per count
    peak_delta_list = [t1-peak_time_list[i] for i, t1 in enumerate(peak_time_list[1:])]
    hist, graph = common.make_root_graph("Peaks", peak_time_list[0:-1], "Time of peak [ns]", peak_delta_list, "Time between peaks [ns]")
    mean_sigma_cut(peak_delta_list)
    if canvas == None:
        canvas = common.make_root_canvas(title+"bpm signal")
        canvas.Draw()
        hist.Draw()
    canvas.cd()
    graph.SetMarkerStyle(6)
    graph.SetMarkerColor(colour)
    graph.Draw("p")
    canvas.Update()    
    return canvas, hist, graph
Пример #31
0
 def plot_signal(self, title):
     """
     Plot the FFT frequency spectrum
     - title, string used as a title in FFT plots
     Returns tuple of TCanvas, TH2, TGraph
     """
     canvas = common.make_root_canvas(title)
     x_list = range(len(self.u))
     hist, graph = common.make_root_graph(title, x_list, 'count', self.u,
                                          'signal')
     hist.SetTitle(title)
     hist.Draw()
     graph.Draw('l')
     canvas.Update()
     return canvas, hist, graph
Пример #32
0
 def test_sft_accuracy(self):
     # test slow fourier transform
     canvas = common.make_root_canvas("SFT Residuals")
     hist = common.make_root_histogram('', [],
                                       'Residuals',
                                       1000, [],
                                       '',
                                       1000,
                                       xmin=1.,
                                       xmax=1000.0,
                                       ymin=0.0,
                                       ymax=1.0)
     hist.Draw()
     for i in range(3, 4):
         truth_list, sft_list, fft_list, n_list = [], [], [], []
         tune = i * 0.1
         for n in [5, 10, 20, 50, 100, 200, 500, 1000]:
             co, tracking = matrix(tune * 2. * math.pi, n)
             fft = FFTTuneFinder()
             fft.run_tracking('x', 10.0, co, tracking)
             tune_sft, tune_fft, tune_sft_hanning = 0., 0., 0.
             try:
                 tune_fft, tune_sft, tune_sft_hanning = self._ft_test(fft)
             except ValueError:
                 # statistics are low enough that no primary peaks can be
                 # found
                 sys.excepthook(*sys.exc_info())
             if tune > 0.5:
                 tune_sft = 1 - tune_sft
                 tune_fft = 1 - tune_fft
             #print "truth", tune, "sft", tune_sft,
             #print "fft", tune_fft, "hanning", tune_sft_hanning
             truth_list.append(tune)
             sft_list.append(tune_sft)
             fft_list.append(tune_fft)
             n_list.append(n)
         residual_list = []
         for i, n in enumerate(n_list):
             if fft_list[i] - truth_list[i] != 0.:
                 residual_list.append(abs(sft_list[i]-truth_list[i])\
                                     /abs(fft_list[i]-truth_list[i]))
         hist, graph = common.make_root_graph("SFT residuals", n_list,
                                              "Number of points",
                                              residual_list, "Residuals")
         graph.Draw('L')
     canvas.SetLogx()
     canvas.Update()
def peak_hist(peak_list):
    canvas = common.make_root_canvas("projected peaks")
    hist = common.make_root_histogram("projected peaks",
                                      peak_list,
                                      "#deltat [ns]",
                                      200,
                                      xmin=0,
                                      xmax=630.)
    bins = []
    for bin_index in range(1, hist.GetNbinsX() + 1):
        bins.append(hist.GetBinContent(bin_index))
    smoothing = xboa.algorithms.smoothing.GaussianSmoothing(2., 3, True)
    smoothed = smoothing.smooth(bins)
    finder = xboa.algorithms.peak_finder.WindowPeakFinder(10, -1, 1)
    peak_graph_indices, peak_x, peak_y = [], [], []
    peaks = []
    for peak in finder.find_peaks(smoothed):
        a_peak = {
            "peak": hist.GetBinCenter(peak + 1),
            "magnitude": bins[peak],
            "err": 0.
        }
        if a_peak["magnitude"] < 0.5 * max(smoothed):
            continue
        peak_graph_indices.append(peak)
        for bin in range(peak, 0, -1) + range(len(bins) - 1, peak, -1):
            if smoothed[bin] < smoothed[peak] / 2.:
                peak_graph_indices.append(bin)
                a_peak["lower_bound"] = hist.GetBinCenter(bin + 1)
                break
        for bin in range(peak, len(bins), +1) + range(0, peak, 1):
            if smoothed[bin] < smoothed[peak] / 2.:
                peak_graph_indices.append(bin)
                a_peak["upper_bound"] = hist.GetBinCenter(bin + 1)
                break
        peaks.append(a_peak)
    for peak_graph_index in peak_graph_indices:
        peak_x.append(hist.GetBinCenter(peak_graph_index + 1))
        peak_y.append(smoothed[peak_graph_index])
    dummy, graph = xboa.common.make_root_graph("peaks", peak_x, "", peak_y, "")
    graph.SetMarkerStyle(24)
    graph.SetMarkerColor(2)
    canvas.Draw()
    hist.Draw()
    graph.Draw('p')
    canvas.Update()
    return peaks, canvas
Пример #34
0
def graph_peak_times(a_data, errors, colour, y_range, canvas = None, title=""):
    hist, graph = common.make_root_graph("Volts", a_data["time_list"], "Time [ns]", a_data["voltage_list"], "Signal Voltage [V]", ymin=y_range[0], ymax=y_range[1])
    peak_time_list = [x["x"] for x in errors]
    peak_voltage_list = [x["y"] for x in errors]
    peak_hist, peak_graph = common.make_root_graph("Peaks", peak_time_list, "Time of peak [ns]", peak_voltage_list, "Peak voltage")
    if canvas == None:
        canvas = common.make_root_canvas(title+"bpm peaks")
        canvas.Draw()
        hist.Draw()
    canvas.cd()
    peak_graph.SetMarkerColor(colour)
    peak_graph.SetMarkerStyle(4)
    peak_graph.Draw("p")
    graph.SetMarkerColor(colour)
    graph.Draw("p")
    canvas.Update()
    return canvas, hist, graph, peak_hist, peak_graph
Пример #35
0
 def plot_phase_space(self, title):
     """
     Plot the phase space for the fourier transform
     - title, string used as a title in FFT plots
     Returns tuple of TCanvas, TH2, TGraph
     """
     # NEEDS TEST
     canvas = common.make_root_canvas(title)
     print(len(self.u), len(self.up))
     hist, graph = common.make_root_graph(title, self.u, 'displacement',
                                          self.up, 'divergence')
     hist.SetTitle(title)
     hist.Draw()
     graph.SetMarkerStyle(26)
     graph.Draw('p')
     canvas.Update()
     return canvas, hist, graph
Пример #36
0
    def _draw_materials_1d(self, step_data, z_range):
        """Make a 1D plot of position vs material along the z axis"""
        # we plot G4_AIR first, then G4_GALACTIC?
        draw_list = step_data.keys()
        draw_list = self.move(draw_list, "G4_AIR", 0)
        draw_list = self.move(draw_list, "G4_Galactic", 1)
        black_x_list, black_y_list = [], []
        grey_x_list, grey_y_list = [], []
        canvas = common.make_root_canvas("Material vs z")
        hist = ROOT.TH2D("name", "Material vs z", 30000, z_range[0],
                         z_range[1],
                         len(draw_list) + 1, -0.5,
                         len(draw_list) + 0.5)
        common._common._hist_persistent.append(hist)  #pylint: disable=W0212
        for material in draw_list:
            hist.Fill(z_range[0], material, 1.)
        hist.SetBit(ROOT.TH1.kCanRebin)
        hist.SetStats(0)
        hist.LabelsDeflate("Y")
        hist.LabelsOption("v")
        hist.Draw()
        for i, material in enumerate(draw_list):
            grey_x_list += [i + 0.1 for step in step_data[material]]
            grey_y_list += [step["z"] for step in step_data[material]]
            black_x_list += [i for step in step_data[material] \
                                                        if step["r"] < 1e-9]
            black_y_list += [step["z"] for step in step_data[material] \
                                                        if step["r"] < 1e-9]

        if len(grey_x_list) == 0:
            return
        hist, graph = common.make_root_graph("", grey_y_list, "z [mm]",
                                             grey_x_list, "material index")
        graph.SetMarkerColor(ROOT.TColor.GetColor(0.5, 0.5, 0.5))
        graph.SetMarkerStyle(7)
        graph.Draw('p')
        if len(black_x_list) != 0:
            hist, graph = common.make_root_graph("", black_y_list, "z [mm]",
                                                 black_x_list,
                                                 "material index")
            graph.SetMarkerStyle(7)
            graph.Draw('p')
        canvas.Update()
        for _format in self.formats:
            canvas.Print(self.mat_1d + "." + _format)
Пример #37
0
def common_make_root_multigraph_test():
  canvas = common.make_root_canvas('multigraph_test')
  x_list_of_lists = []
  y_list_of_lists = []
  for i in range(2):
    x_list_of_lists.append(list(range(0,50)))
    for i in range( len(x_list_of_lists[-1]) ):
      x_list_of_lists[-1][i] /= 10.
    x_list_of_lists.append(list(range(0,100)))
    for i in range( len(x_list_of_lists[-1]) ):
      x_list_of_lists[-1][i] /= 20.
  for i in range( len(x_list_of_lists) ):
     y_list_of_lists.append(__sine_list(i+1, i+1, x_list_of_lists[i]))
  (hist,list_of_graphs) = common.make_root_multigraph('test', x_list_of_lists, 'x [rad]', y_list_of_lists, 'a*sin(b*x)')
  hist.Draw()
  for graph in list_of_graphs:
    graph.Draw()
  return 'pass' # a test that can't fail - excellent!
def get_period(data):
    rf_peak_indices = data["RF"]["peak_indices"]
    rf_peak_list = [data["RF"]["time_list"][i] / 1e-9 for i in rf_peak_indices]
    rf_peak_deltas_list = [None] * (len(rf_peak_list) - 1)

    for i, rf_time in enumerate(rf_peak_list[0:-1]):
        rf_next_time = rf_peak_list[i + 1]
        rf_peak_deltas_list[i] = rf_next_time - rf_time
    canvas = common.make_root_canvas("rf_period")
    canvas.Draw()
    hist = common.make_root_histogram("times", rf_peak_deltas_list,
                                      "RF period [ns]", 100)
    hist.Draw()
    hist.SetStats(True)
    canvas.Update()
    canvas.Draw()

    return numpy.mean(rf_peak_deltas_list), rf_peak_list[0], canvas
Пример #39
0
    def _draw_materials_1d(self, step_data, z_range):
        """Make a 1D plot of position vs material along the z axis"""
        # we plot G4_AIR first, then G4_GALACTIC?
        draw_list = step_data.keys()
        draw_list = self.move(draw_list, "G4_AIR", 0)
        draw_list = self.move(draw_list, "G4_Galactic", 1)
        black_x_list, black_y_list = [], []
        grey_x_list, grey_y_list = [], []
        canvas = common.make_root_canvas("Material vs z")
        hist = ROOT.TH2D("name", "Material vs z", 30000, z_range[0], z_range[1],
                         len(draw_list)+1, -0.5, len(draw_list)+0.5)
        common._common._hist_persistent.append(hist) #pylint: disable=W0212
        for material in draw_list:
            hist.Fill(z_range[0], material, 1.)
        hist.SetBit(ROOT.TH1.kCanRebin)
        hist.SetStats(0)
        hist.LabelsDeflate("Y")
        hist.LabelsOption("v")
        hist.Draw()
        for i, material in enumerate(draw_list):
            grey_x_list += [i+0.1 for step in step_data[material]]
            grey_y_list += [step["z"] for step in step_data[material]]
            black_x_list += [i for step in step_data[material] \
                                                        if step["r"] < 1e-9]
            black_y_list += [step["z"] for step in step_data[material] \
                                                        if step["r"] < 1e-9]

        if len(grey_x_list) == 0:
            return
        hist, graph = common.make_root_graph("", grey_y_list, "z [mm]",
                                               grey_x_list, "material index")
        graph.SetMarkerColor(ROOT.TColor.GetColor(0.5, 0.5, 0.5))
        graph.SetMarkerStyle(7)
        graph.Draw('p')
        if len(black_x_list) != 0:
            hist, graph = common.make_root_graph("", black_y_list, "z [mm]",
                                                 black_x_list, "material index")
            graph.SetMarkerStyle(7)
            graph.Draw('p')
        canvas.Update()
        for _format in self.formats:
            canvas.Print(self.mat_1d+"."+_format)
def plot_z(item, line_color, do_square, canvas = None):
    z_list = [hit["z"] for hit in item["seed"]]
    if not do_square: #i.e. do triangle
        area_list = [abs(area/item["an_area_list"][0]-1) for area in item["an_area_list"]]
    else:
        area_list = [abs(sum(area_list)/sum(item["area_list_of_lists"][0])-1) for area_list in item["area_list_of_lists"]]

    title = "x: "+str(item["seed"][0]["x"])+" mm "+\
            "p_{x}: "+str(item["seed"][0]["px"])+" MeV/c"
    hist, graph = common.make_root_graph(title,
                              z_list, "z [mm]",
                              area_list, "Fractional change in simplex content",
                              ymin = 1e-5, ymax=100.
                  )
    if canvas == None:
        canvas = common.make_root_canvas("content growth vs z")
        canvas.SetLogy()
        hist.Draw()
    canvas.cd()
    graph.SetLineColor(line_color)
    graph.Draw("SAMEPL")
    canvas.Update()
    return canvas, graph
    def plot_areas(self, areas_us, areas_ds):
        assert(len(areas_us) == len(areas_ds))
        # remove None items from the list (failed to calculate area)
        areas = zip(areas_us, areas_ds)
        areas = [item for item in areas if item[0] != None and item[1] != None]
        areas_us = [item[0] for item in areas]
        areas_ds = [item[1] for item in areas]
        # remove residuals
        areas_res = [item[1]-item[0] for item in areas]
        for i in range(3):#len(areas_us)):
            print i, str(round(areas_us[i])).ljust(10), str(round(areas_ds[i])).ljust(10), areas_res[i]
        # plots
        canvas = common.make_root_canvas("content")
        n_bins = 100# max(int((len(bunch_us)/10)**0.5), 10)

        hist_us = common.make_root_histogram("Upstream", areas_us, "cell content [mm MeV/c]", n_bins, xmin=-5000.0, xmax=5000.0)
        hist_us.SetLineColor(2)
        hist_us.Draw()
        hist_ds = common.make_root_histogram("Downstream", areas_ds, "cell content [mm MeV/c]", n_bins, xmin=-5000.0, xmax=5000.0)
        hist_ds.SetLineColor(4)
        hist_ds.Draw("SAME")
        hist_res = common.make_root_histogram("Residuals", areas_res, "cell content [mm MeV/c]", n_bins)
        hist_res.Draw("SAME")
Пример #42
0
def plot(plot_dir, data_list_pairs):
    tmp_data = []
    for i, data in enumerate(data_list_pairs):
        pos_peak = numpy.mean([x["y"] for x in data["RF"]["pos_peak_with_errors"]])
        neg_peak = numpy.mean([-x["y"] for x in data["RF"]["neg_peak_with_errors"]])
        voltage = (pos_peak-neg_peak)
        data["rf_peak_to_peak_voltage"] = voltage
        rf_list = ["0.2", "0.32", "0.46", "0.62", "0.81", "3.01", "7.18"]
        if True or str(round(voltage, 2)) in rf_list:
            print "Using", voltage
            tmp_data.append(data)
        else:
            print "Not using", voltage
    data_list_pairs = tmp_data
    peak_delta_canvas = common.make_root_canvas("delta rf vs bpm")
    peak_delta_canvas.Draw()
    peak_delta_hist_canvas = common.make_root_canvas("delta rf vs bpm - hist")
    peak_delta_hist_canvas.Draw()
    graph_list = []
    hist_list = []
    dt_mean_list = []
    dt_err_list = []
    measured_voltage_list = []
    max_y = -1e9
    min_y = 1e9
    delta_hist_min = 1e9
    delta_hist_max = -1e9
    for i, data in enumerate(data_list_pairs):
        """
        voltage_str = "V="+str(round(data["rf_peak_to_peak_voltage"], 2))
        print "Plotting measured "+voltage_str
        formats = ["png", "root"]
        times = data["RF"]["time_list"]

        rf_voltage_list = data["RF"]["voltage_list"]
        rf_peak_error_list = data["RF"]["pos_peak_with_errors"]
        rf_peak_list = [x["x"] for x in rf_peak_error_list]
        rf_period = sum([rf_peak_list[j+1] - rf_peak_list[j] for j, index in enumerate(rf_peak_list[:-1])])  
        rf_period = DT*rf_period/float(len(rf_peak_list))
        rf_frequency = 1./rf_period
        print "  RF Period", rf_period, "Frequency", rf_frequency

        print "  Plotting RF magnitude and error"
        canvas_rf_v, hist_rf_v, graph_rf_v = graph_peak_magnitude(data["RF"]["pos_peak_with_errors"], data["RF"]["neg_peak_with_errors"], title=voltage_str)
        for format in formats:
            canvas_rf_v.Print(plot_dir+voltage_str+"_rf_voltage."+format)

        print "  Plotting peak finding errors"
        canvas_err, hist_err, graph_err = graph_peak_errors(data["signal"]["peak_with_errors"], 4, title=voltage_str)
        graph_peak_errors(data["RF"]["pos_peak_with_errors"], 2, canvas_err)
        for format in formats:
            canvas_err.Print(plot_dir+voltage_str+"_peak_errors."+format)

        print "  Plotting peak to peak distance"
        print "    signal",
        canvas_pp, hist_pp, graph_pp = graph_delta_times(data["signal"]["peak_with_errors"], 4, title=voltage_str)
        print "    RF",
        graph_delta_times(data["RF"]["pos_peak_with_errors"], 2, canvas_pp)
        for format in formats:
            canvas_pp.Print(plot_dir+voltage_str+"_peak_deltas."+format)

        print "  Plotting data"
        y_range = common.min_max(data["RF"]["voltage_list"]+data["signal"]["voltage_list"]+data["dc_signal"]["voltage_list"])
        canvas, hist, graph, peak_hist, peak_graph = graph_peak_times(data["RF"], data["RF"]["pos_peak_with_errors"], 2, y_range, title=voltage_str)
        bpm_peak_indices = data["signal"]["peak_indices"]
        bpm_voltage_list = data["signal"]["voltage_list"]
        bpm_peak_list = [index for index in bpm_peak_indices]
        graph_peak_times(data["signal"], data["signal"]["peak_with_errors"], 4, y_range, canvas)
        graph_peak_times(data["dc_signal"], [{"x":0, "y":0}], 6, y_range, canvas)
        canvas.Update()
        for format in formats:
            canvas.Print(plot_dir+voltage_str+"_signals."+format)
        """

        print "  Plotting distance between bpm and rf peaks"
        peak_delta_canvas.cd()
        peak_time_list = data["peak_time_list"]
        peak_delta_list = data["peak_delta_list"]

        hist, graph = common.make_root_graph(voltage_str, peak_time_list, "time [ns]", peak_delta_list, "dt [ns]")
        min_y = min([hist.GetYaxis().GetXmin(), min_y])
        max_y = max([hist.GetYaxis().GetXmax(), max_y])
        if len(data_list_pairs) > 1:
            hist.Draw()
            color_fraction = float(i)/float(len(data_list_pairs)-1)
        else:
            color_fraction = 1
        color = ROOT.TColor.GetColor(color_fraction, 1.-color_fraction, 0)
        graph.SetMarkerColor(color)
        graph.SetLineColor(color)
        graph.SetMarkerStyle(6)
        graph_list.append(graph)

        peak_delta_hist_canvas.cd()
        filtered_list = []
        for j, peak in enumerate(peak_delta_list):
            if peak_time_list[j] > 30.e3 and \
               peak_time_list[j] < 40.e3:
                filtered_list.append(peak)
        if len(filtered_list) > 0:
            dt_mean_list.append(max(filtered_list))
            #dt_err_list.append(numpy.std(filtered_list)/len(filtered_list)**0.5)
            measured_voltage_list.append(data["rf_peak_to_peak_voltage"])
        hist = common.make_root_histogram(voltage_str, filtered_list, "dt [ns]", 4)
        delta_hist_min = min([hist.GetXaxis().GetXmin(), delta_hist_min])
        delta_hist_max = max([hist.GetXaxis().GetXmax(), delta_hist_max])
        hist.SetLineColor(color)
        hist_list.append(hist)

    peak_delta_canvas.cd()
    hist, graph = common.make_root_graph(voltage_str, peak_time_list, "t [ns]", peak_delta_list, "dt [ns]", ymin=0., ymax=700.)
    hist.Draw() # redraw hist to get axes right
    for graph in graph_list:
        graph.Draw("p")
    legend = common.make_root_legend(peak_delta_canvas, graph_list)
    legend.Draw()
    peak_delta_canvas.Update() 
    for format in formats:
        peak_delta_canvas.Print(plot_dir+"bpm_to_rf_deltas."+format)

    peak_delta_hist_canvas.cd()
    print delta_hist_min, delta_hist_max
    hist = common.make_root_histogram(voltage_str, [-1], "dt [ns]", 1000, [-1], "Counts", 1000, xmin=delta_hist_min, xmax=delta_hist_max, ymin=1e-2, ymax=20.)
    hist.Draw() # redraw hist to get axes right
    for a_hist in hist_list:
        a_hist.Draw("same")
    legend = common.make_root_legend(peak_delta_hist_canvas, hist_list)
    legend.Draw()
    peak_delta_hist_canvas.Update()
    for format in formats:
        peak_delta_hist_canvas.Print(plot_dir+"bpm_to_rf_deltas_hist."+format)

    if len(dt_mean_list) < 2:
        return
    phase_mean_list = [2.*math.pi*dt/rf_period for dt in dt_mean_list[1:]]
    measured_voltage_list = measured_voltage_list[1:]
    for popper in []:
        phase_mean_list.pop(popper)
        phase_err_list.pop(popper)
        measured_voltage_list.pop(popper)
    synchronous_phase_canvas = common.make_root_canvas("Synchronous phase vs voltage")
    hist, graph = common.make_root_graph("Synchronous phase vs voltage", phase_mean_list, "#phi [rad]", measured_voltage_list, "V [au]")
    graph = ROOT.TGraph(len(phase_mean_list))
    graph.SetMarkerStyle(4)
    for i in range(len(phase_mean_list)):
        graph.SetPoint(i, phase_mean_list[i], measured_voltage_list[i])

    print phase_mean_list 
    print measured_voltage_list
    hist.Draw()
    graph.Draw('p')
    print "Doing unweighted fit"
    fit_unweighted = ROOT.TF1("fit", "[0]/sin([1]+x)")
    fit_unweighted.SetParameter(0, 0.1)
    fit_unweighted.SetParameter(1, 0.)
    fit_unweighted.SetLineColor(4)
    graph.Fit(fit_unweighted, "EX0")
    fit_unweighted.Draw("SAME")
    synchronous_phase_canvas.Update()    
    for format in formats:
        synchronous_phase_canvas.Print(plot_dir+"synchronous_phase_vs_voltage_unweighted."+format)