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
Example #2
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)
Example #3
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 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
Example #5
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)
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
Example #7
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)
Example #8
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)
Example #9
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)
Example #10
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
Example #11
0
def get_b_field(canvas, z=None):
    global bfield_hist, bfield_graph
    if not maus_globals.has_instance():
        configuration = Configuration.Configuration().\
                                          getConfigJSON(command_line_args=True)

        maus_globals.birth(configuration)
        z_list = []
        bz_list = []
        for z_pos in range(-8000, 8001, 50):
            z_pos = float(z_pos)
            (bx_field, by_field, bz_field, ex_field, ey_field, ez_field) = \
                                            field.get_field_value(0., 0., z_pos, 0.)
            z_list.append(z_pos)  # z in mm
            bz_list.append(bz_field * 1e3)  # bz in T
        bfield_hist, bfield_graph = common.make_root_graph(
            "bz vs z", z_list, "z [m]", bz_list, "B_{z} [T]")
    canvas.cd()
    bfield_hist.Draw()
    bfield_graph.Draw('l')
    if z != None:
        print "Plotting z", z
        marker_graph = ROOT.TGraph(2)
        marker_graph.SetPoint(0, z, -1000)
        marker_graph.SetPoint(1, z, +1000)
        marker_graph.Draw('l')
        root_list.append(marker_graph)
def get_b_field(canvas, z = None):
    global bfield_hist, bfield_graph
    if not maus_globals.has_instance():
        configuration = Configuration.Configuration().\
                                          getConfigJSON(command_line_args=True)

        maus_globals.birth(configuration)
        z_list = []
        bz_list = []
        for z_pos in range(-8000, 8001, 50):
            z_pos = float(z_pos)
            (bx_field, by_field, bz_field, ex_field, ey_field, ez_field) = \
                                            field.get_field_value(0., 0., z_pos, 0.)
            z_list.append(z_pos)  # z in mm
            bz_list.append(bz_field*1e3)  # bz in T
        bfield_hist, bfield_graph = common.make_root_graph("bz vs z", z_list, "z [m]",
                                                             bz_list, "B_{z} [T]")
    canvas.cd()
    bfield_hist.Draw()
    bfield_graph.Draw('l')
    if z != None:
        print "Plotting z", z
        marker_graph = ROOT.TGraph(2)
        marker_graph.SetPoint(0, z, -1000)
        marker_graph.SetPoint(1, z, +1000)
        marker_graph.Draw('l')
        root_list.append(marker_graph)
Example #13
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
Example #14
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)
Example #15
0
def plot_acceptance(acceptance, x_data, y_data, axis2):
    area_src = numpy.transpose(numpy.array([x_data, y_data]))
    area = get_area(area_src)
    scale = (acceptance / area)**0.5
    #covariance *= scale
    x_mean, y_mean = numpy.mean(x_data), numpy.mean(y_data)
    x_values = [(x - x_mean) * scale for x in x_data]
    y_values = [(y - y_mean) * scale for y in y_data]
    print("Acceptance bounding box (relative to mean) x:", min(x_values),
          max(x_values), "x':", min(y_values), max(y_values))
    values = list(zip(x_values, y_values))
    values = sorted(values, key=lambda x: math.atan2(x[0], x[1]))
    x_values, y_values = list(zip(*values))
    x_values = [x + x_mean for x in x_values]
    y_values = [y + y_mean for y in y_values]
    x_values.append(x_values[0])
    y_values.append(y_values[0])
    hist, graph = common.make_root_graph("",
                                         x_values,
                                         "",
                                         y_values,
                                         "",
                                         sort=False)
    graph.SetLineColor(ROOT.kOrange)
    return graph
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
Example #17
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
Example #18
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
Example #19
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_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
Example #21
0
def plot_fields(data, plot_dir, foil_probe):
    print("\nfield", end=' ')
    bump_fields = [[], [], [], []]
    bump_position = []
    for bump_run in data:
        bump_position += [
            bump["tracking"][foil_probe][1] for bump in bump_run["bumps"]
        ]
        for bump in bump_run["bumps"]:
            for i in range(4):
                bump_fields[i].append(bump["bump_fields"][i])
    canvas = common.make_root_canvas("fields")
    all_fields = bump_fields[0] + bump_fields[1] + bump_fields[
        2] + bump_fields[3]
    delta = 0.2
    max_pos = (1. + delta) * max(bump_position) - delta * min(bump_position)
    hist, graph = common.make_root_graph("fields",
                                         bump_position * 4 + [max_pos],
                                         "Radial position [mm]",
                                         all_fields + [0.], "Dipole field [T]")
    hist.Draw()
    color = [ROOT.kBlue, ROOT.kGreen + 2, ROOT.kRed, ROOT.kYellow + 2]
    leg_list = []
    for i, field in enumerate(bump_fields):
        hist, graph = common.make_root_graph("Bump " + str(i + 1),
                                             bump_position,
                                             "Radial position [mm]", field,
                                             "Dipole field [T]")
        graph.SetMarkerStyle(20)
        graph.SetMarkerColor(color[i])
        graph.SetLineColor(color[i])
        graph.Draw("lpsame")
        leg_list.append(graph)
    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 "eps", "png", "root":
        canvas.Print(plot_dir + "/bump_fields." + format)
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)
Example #23
0
def plot_score(data, plot_dir, foil_probe):
    """
    data - the data
    co_axis - "x" or "y"
    plot_dir - directory to which files are written
    foil_probe - element in the "tracking output" list which contains the foil probe
    """
    print("\nclosed orbit with foil probe", foil_probe)
    metres = 1e-3
    bump_position = []
    bump_score = []
    bump_n_iterations = []
    for bump_run in data:
        bump_position += [
            bump["tracking"][foil_probe][1] for bump in bump_run["bumps"]
        ]
        bump_score += [bump["score"] for bump in bump_run["bumps"]]
        bump_n_iterations += [
            bump["n_iterations"] for bump in bump_run["bumps"]
        ]
    canvas = common.make_root_canvas("score")
    hist, graph = common.make_root_graph("score", bump_position * 2,
                                         "Radial position [mm]",
                                         bump_score + bump_n_iterations,
                                         "Score (red)   Iterations (blue)")
    hist.Draw()
    hist, graph = common.make_root_graph("score", bump_position,
                                         "Radial position [mm]", bump_score,
                                         "Score")
    graph.SetMarkerStyle(20)
    graph.SetMarkerColor(ROOT.kRed)
    graph.Draw("lpsame")
    hist, graph = common.make_root_graph("score", bump_position,
                                         "Radial position [mm]",
                                         bump_n_iterations, "n_iterations")
    graph.SetMarkerColor(ROOT.kBlue)
    graph.SetMarkerStyle(24)
    graph.Draw("lpsame")
    canvas.SetLogy()
    canvas.Update()
    for format in "eps", "png", "root":
        canvas.Print(plot_dir + "/score." + format)
Example #24
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)
Example #25
0
def common_make_root_graph_test():
  testpass = True
  canvas = common.make_root_canvas('graph_test')
  x_list = list(range(0,100))
  for i in range( len(x_list) ): x_list[i] = float(x_list[i])/100.
  y_list = __sine_list(2., 2.*math.pi, x_list)
  mm = common.min_max(x_list) + common.min_max(y_list)
  (hist,graph) = common.make_root_graph('test', x_list, 'x [2#pi rad]', y_list, 'a*sin(b*x)')
  if not __test_root_hist(hist, '', 'x [2#pi rad]', 'a*sin(b*x)', mm[0], mm[1], mm[2], mm[3], rg.line_color, rg.line_style, rg.line_width, rg.fill_color, ''): return 'fail'
  (hist,graph) = common.make_root_graph('test', x_list, 'x [2#pi rad]', y_list, 'a*sin(b*x)', xmin=-1001., xmax=+1001, ymin=-1002., ymax=+1002.,line_color=201, line_style=202, line_width=203, fill_color=204, hist_title_string='mr title')
  testpass &= __test_root_hist(hist, 'namey', 'x [2#pi rad]', 'a*sin(b*x)', -1001., +1001., -1002., +1002., rg.line_color, rg.line_style, rg.line_width, rg.fill_color, 'mr title') 
  testpass &= __test_root_graph(graph, 'namey', x_list, y_list, 201, 202, 203, 204)
  (x_list, y_list) = ([3,2,1], [3,2,1]) #check that x_list and y_list are not changed by sort
  (hist,graph) = common.make_root_graph('test', x_list, 'x', y_list, 'y')
  testpass &=   (x_list, y_list) == ([3,2,1], [3,2,1])
  hist.Draw()
  graph.Draw()
  common.clear_root()
  if testpass: return 'pass'
  else:        return 'fail'
Example #26
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
 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        
Example #28
0
def plot_score(data, plot_dir, foil_probe, foil_var, axis_name):
    """
    data - the data
    co_axis - "x" or "y"
    plot_dir - directory to which files are written
    foil_probe - element in the "tracking output" list which contains the foil probe
    """
    print("\nclosed orbit with foil probe", foil_probe)
    metres = 1e-3
    bump_score = []
    bump_n_iterations = []
    bump_position = get_bump_position(data, foil_probe, foil_var)
    for bump in data:
        bump_score.append(bump["score"])
        bump_n_iterations.append(bump["n_iterations"])
    canvas = common.make_root_canvas("score")
    mgraph = ROOT.TMultiGraph()
    root_objects.append(mgraph)
    hist, graph = common.make_root_graph("score", bump_position * 2, axis_name,
                                         bump_score + bump_n_iterations,
                                         "Score (red)   Iterations (blue)")
    hist, graph = common.make_root_graph("score", bump_position,
                                         "Position [mm]", bump_score, "Score")
    graph.SetMarkerStyle(20)
    graph.SetMarkerColor(ROOT.kRed)
    mgraph.Add(graph)
    mgraph.GetXaxis().SetTitle(axis_name)
    hist, graph = common.make_root_graph("Number of iterations", bump_position,
                                         axis_name, bump_n_iterations,
                                         "n_iterations")
    graph.SetMarkerColor(ROOT.kBlue)
    graph.SetMarkerStyle(24)
    mgraph.Add(graph)
    mgraph.Draw("alp")
    #canvas.BuildLegend()
    canvas.SetLogy()
    canvas.Update()
    for format in ["png"]:
        canvas.Print(plot_dir + "/score." + format)
Example #29
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)
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
Example #31
0
def plot_closed_orbit(data, co_axis, plot_dir, foil_probe):
    """
    data - the data
    co_axis - "x" or "y"
    plot_dir - directory to which files are written
    foil_probe - element in the "tracking output" list which contains the foil probe
    """
    print("\nclosed orbit with foil probe", foil_probe)
    if co_axis == "x":
        ip = 1  # position index
        im = 2  # momentum index
    elif co_axis == "y":
        ip = 3
        im = 4
    pos, mom = [], []
    for bump_run in data:
        pos += [bump["tracking"][foil_probe][ip] for bump in bump_run["bumps"]]
        mom += [bump["tracking"][foil_probe][im] for bump in bump_run["bumps"]]
        canvas = common.make_root_canvas("closed orbit")
        hist, graph = common.make_root_graph("closed orbit", pos,
                                             "Radial position [mm]", mom,
                                             "Radial momentum [MeV/c]")
        hist.Draw()
    marker_styles = [20, 24, 21, 25, 26, 22, 27]
    for i, bump_run in enumerate(data):
        pos = [bump["tracking"][foil_probe][ip] for bump in bump_run["bumps"]]
        mom = [bump["tracking"][foil_probe][im] for bump in bump_run["bumps"]]
        hist, graph = common.make_root_graph("closed orbit", pos,
                                             "Radial position [mm]", mom,
                                             "Radial momentum [MeV/c]")
        style = marker_styles[i % len(marker_styles)]
        graph.SetMarkerStyle(style)
        graph.Draw("lpsame")
    canvas.Update()
    for format in "eps", "png", "root":
        canvas.Print(plot_dir + "/" + co_axis + "_closed_orbit_probe_" +
                     str(foil_probe) + "." + format)
Example #32
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
Example #33
0
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
Example #34
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)
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
Example #36
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()
Example #37
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
    def systematics_plot(self, target):
        """
        Plot systematic corrections:
        * Momentum correction matrix
        * Crossing probability due to reconstruction
        * Inefficiency/impurity
        """
        if "upstream" in target:
            label = "US"
        elif "downstream" in target:
            label = "DS"
        matrix = self.amp.amplitudes["crossing_probability"][target][
            "migration_matrix"]
        title = ("crossing_probability_" + target).replace("_all", "").replace(
            "_", " ")
        self.matrix_plot(
            matrix, title,
            label + " " + self.get_suffix_label("reco") + " amplitude [mm]",
            label + " " + self.get_suffix_label("reco_mc") + " amplitude [mm]")

        inefficiency = self.amp.amplitudes["inefficiency"][target]["pdf_ratio"]
        canvas = common.make_root_canvas("inefficiency_" + target)

        hist, graph = common.make_root_graph(
            "inefficiency", self.amp.get_bin_centre_list(),
            label + " MC Truth Amplitude [mm]", inefficiency[:-1],
            label + " " + self.get_suffix_label("all_mc") + " number/" +
            self.get_suffix_label("reco_mc") + " number")
        hist.GetYaxis().SetRangeUser(0., 2.0)
        hist.SetTitle(self.config_anal['name'])
        hist.Draw()
        graph.SetMarkerStyle(24)
        graph.Draw("p")
        for format in "eps", "root", "png":
            canvas.Print(self.plot_dir + "amplitude_inefficiency_" + target +
                         "." + format)
        hist.GetYaxis().SetRangeUser(0.9, 1.1)
        hist.Draw()
        graph.SetMarkerStyle(24)
        graph.Draw("p")
        for format in "eps", "root", "png":
            canvas.Print(self.plot_dir + "amplitude_inefficiency_zoom_" +
                         target + "." + 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(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)