Exemple #1
0
def plot_data_2d(data, tune_axis, plot_dir):
    x_tune = [item['x_tune'] for item in data]
    y_tune = [item['y_tune'] for item in data]
    print("X Tunes", x_tune)
    print("Y Tunes", y_tune)
    x_name = "Varying "
    axis_candidates = utilities.get_substitutions_axis(data)
    for key in axis_candidates:
        min_val = str(min(axis_candidates[key]))
        max_val = str(max(axis_candidates[key]))
        x_name += utilities.sub_to_name(
            key) + " from " + min_val + " to " + max_val
    axis_candidates = utilities.get_substitutions_axis(data)
    canvas = xboa.common.make_root_canvas('tune x vs y')
    hist, graph = xboa.common.make_root_graph('tune x vs y',
                                              x_tune,
                                              "horizontal tune",
                                              y_tune,
                                              "vertical tune",
                                              xmin=0.,
                                              xmax=1.,
                                              ymin=0.,
                                              ymax=1.)
    hist.SetTitle(x_name)
    hist.Draw()
    #utilities.tune_lines(canvas)
    graph.SetMarkerStyle(24)
    graph.Draw("P SAME")
    canvas.Update()
    for format in "eps", "png", "root":
        canvas.Print(plot_dir + "/tune_x_vs_y." + format)
Exemple #2
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
    def get_seed(self, results, subs):
        """
        Get a new seed
        - results: list of previous closed orbits
        - subs: substitutions

        * If results is an empty list, then return the configuration input seed
        * If results is of length 1, then assume this is a best guess for the
          next seed
        * If results is of length >1, then attempt a linear extrapolation of
          closest previous results to guess the next seed
        """
        if len(results) == 0:
            config_seed = self.config.find_closed_orbits["seed"].pop(0)
            print("Using config seed", config_seed)
            return config_seed, len(self.config.find_closed_orbits["seed"]) > 0
        axis_candidates = utilities.get_substitutions_axis(results)
        if len(axis_candidates) == 0:
            co_hit = results[0]["hits"][0]
            seed = [co_hit["x"], co_hit["px"]]
            print("Using last co as seed", seed)
            return seed, False
        print("Doing interpolation for seed for variables",
              list(axis_candidates.keys()))
        # [dx, dpx]
        delta_keys_new = {}
        delta_var_new = []
        seed_var = {
            "x": results[-1]["hits"][0]["x"],
            "px": results[-1]["hits"][0]["px"]
        }
        print("  base", seed_var)
        for key in list(axis_candidates.keys()):
            key2 = subs[key]
            key1 = axis_candidates[key][-1]
            key0 = axis_candidates[key][-2]
            print("    key", key, "values", key0, key1, key2)
            for var in list(seed_var.keys()):
                var1 = results[-1]["hits"][0][var]
                var0 = results[-2]["hits"][0][var]
                if abs(key1 - key0) < 1e-9:  # div0
                    seed_var[var] = var1
                    continue
                delta = (var1 - var0) / (key1 - key0) * (key2 - key1)
                print("      var", var, "values", var1, var0, "delta", delta)
                seed_var[var] += delta
        print("  seed", seed_var)
        seed = [seed_var["x"], seed_var["px"]]
        return seed, False
def plot_tune(data, tune_axis, plot_dir):
    print("Plotting tune")
    axis_candidates = utilities.get_substitutions_axis(data)
    metres = 1e-3
    for key in axis_candidates:
        sys.stdout.flush()
        x_name = utilities.sub_to_name(key)
        x_list = axis_candidates[key]
        y_list = [filtered_dphi(item[tune_axis]) for item in data]
        x_name += utilities.sub_to_units(key)
        fig_index = matplotlib_wrapper.make_graph(x_list, x_name, y_list,
                                                  tune_axis)
        for format in ["png"]:
            name = plot_dir + "/" + tune_axis + "." + format
            fig = matplotlib.pyplot.figure(fig_index)
            fig.savefig(name)
Exemple #5
0
    def do_plots_by_sub(self):
        subs_axes = utilities.get_substitutions_axis(self.data, self.subs_key)
        print(subs_axes)
        for axis in subs_axes:
            axis_name = utilities.sub_to_name(axis).lower().replace(" ", "_")
            for name in "x", "x'", "y", "y'":
                canvas, mgraph = self.plot_item(
                    name,
                    lambda item: Hit.new_from_dict(item["seed_hit"])[name],
                    axis, None, None)
                mgraph.Draw("AP")
                name = name.replace("'", "p")
                canvas.Print(self.output_dir+"/"+axis_name+"_vs_"+name+".png")

            canvas, mgraph = None, None
            for self.phase_advance_axis in 0, 1:
                self.tm_lambda = self.tm_phase_advance
                name = "Phase Advance "+str(self.phase_advance_axis)
                canvas, mgraph = self.plot_item(name, self.get_tm, axis, canvas, mgraph)
            mgraph.Draw("AP")
            canvas.Print(self.output_dir+"/"+axis_name+"_vs_phase_advance.png")
            
            for self.phase_advance_axis in 0, 1:
                canvas, mgraph = None, None
                self.tm_lambda = self.tm_phase_advance
                name = "phase advance "+str(self.phase_advance_axis)
                canvas, mgraph = self.plot_item(name, self.get_tm, axis, canvas, mgraph)
                mgraph.Draw("AP")
                name = name.replace(" ", "_")
                canvas.Print(self.output_dir+"/"+axis_name+"_vs_"+name+".png")

            self.tm_lambda = self.tm_det
            name = "Determinant"
            canvas, mgraph = self.plot_item(name, self.get_tm, axis, None, None)
            mgraph.Draw("AP")
            canvas.Print(self.output_dir+"/"+axis_name+"_vs_determinant.png")

            name = "delta"
            canvas, mgraph = self.plot_item(name, self.get_co, axis, None, None)
            mgraph.Draw("AP")
            #canvas.SetLogy()
            canvas.Print(self.output_dir+"/"+axis_name+"_vs_delta.png")
Exemple #6
0
def plot_da(data, max_n_points, plot_dir, acceptance):
    variables = utilities.get_substitutions_axis(data)
    plot_dir = os.path.join(plot_dir, "plot_da2")
    utilities.clear_dir(plot_dir)
    for index, item in enumerate(data):
        for key in variables:
            variables[key] = item['substitutions'][key]
        for da_key in 'y_da', 'x_da':
            if da_key not in list(item.keys()):
                print("Did not find", da_key, "in keys", list(item.keys()),
                      "... skipping")
                continue
            for axis1, axis2 in ('x', "x'"), ('y', "y'"):
                canvas = plot_one_da(item, da_key, axis1, axis2, max_n_points,
                                     variables, acceptance)
                plot_name = "da_" + str(
                    index) + "_" + da_key + "_" + axis1 + "_" + axis2
                for format in ["eps", "png", "root"]:
                    canvas.Print(plot_dir + "/" + plot_name + "." + format)
                if axis1[0] not in da_key:
                    continue
Exemple #7
0
def get_seed(config, results, subs):
    if len(results) == 0:
        config_seed = config.find_closed_orbits["seed"].pop(0)
        print("Using config seed", config_seed)
        return config_seed, len(config.find_closed_orbits["seed"]) > 0
    axis_candidates = utilities.get_substitutions_axis(results)
    if len(axis_candidates) == 0:
        co_hit = results[0]["hits"][0]
        seed = [co_hit["x"], co_hit["px"]]
        print("Using last co as seed", seed)
        return seed, False
    print("Doing interpolation for seed for variables",
          list(axis_candidates.keys()))
    # [dx, dpx]
    delta_keys_new = {}
    delta_var_new = []
    seed_var = {
        "x": results[-1]["hits"][0]["x"],
        "px": results[-1]["hits"][0]["px"]
    }
    print("  base", seed_var)
    for key in list(axis_candidates.keys()):
        key2 = subs[key]
        key1 = axis_candidates[key][-1]
        key0 = axis_candidates[key][-2]
        print("    key", key, "values", key0, key1, key2)
        for var in list(seed_var.keys()):
            var1 = results[-1]["hits"][0][var]
            var0 = results[-2]["hits"][0][var]
            if abs(key1 - key0) < 1e-9:  # div0
                seed_var[var] = var1
                continue
            delta = (var1 - var0) / (key1 - key0) * (key2 - key1)
            print("      var", var, "values", var1, var0, "delta", delta)
            seed_var[var] += delta
    print("  seed", seed_var)
    seed = [seed_var["x"], seed_var["px"]]
    return seed, False
Exemple #8
0
    def plot_da(self, max_n_points, plot_dir, acceptance):
        variables = utilities.get_substitutions_axis(self.data,
                                                     "substitutions")
        plot_dir = os.path.join(plot_dir, "plot_da")
        utilities.clear_dir(plot_dir)
        self.plot_dir = plot_dir
        for index, item in enumerate(self.data):
            for key in variables:
                variables[key] = item['substitutions'][key]
            for da_key in 'y_da', 'x_da':
                if da_key not in list(item.keys()):
                    print("Did not find", da_key, "in keys", list(item.keys()),
                          "... skipping")
                    continue
                for axis1, axis2 in ('x', "px"), ('y', "py"):
                    canvas = self.plot_one_da(item, da_key, axis1, axis2,
                                              max_n_points, variables,
                                              acceptance)
                    plot_name = "da_" + str(
                        index) + "_" + da_key + "_" + axis1 + "_" + axis2
                    for format in ["eps", "png", "root"]:
                        canvas.Print(plot_dir + "/" + plot_name + "." + format)

                    continue
                    if axis1[0] not in da_key:
                        continue
                    canvas, chol_canvas = plot_one_phi(item, da_key, axis1,
                                                       axis2, max_n_points,
                                                       variables)
                    plot_name = "phi_" + str(
                        index) + "_" + da_key + "_" + axis1 + "_" + axis2
                    for format in ["eps", "png", "root"]:
                        canvas.Print(plot_dir + "/" + plot_name + "." + format)
                        chol_canvas.Print(plot_dir + "/" + plot_name +
                                          "_cholesky." + format)

                self.plot_decoupled_da(item, da_key, index, axis1, axis2,
                                       max_n_points, variables, acceptance)
Exemple #9
0
def get_groups(data, group_axis):
    axis_candidates = utilities.get_substitutions_axis(data)
    if group_axis != None and group_axis not in axis_candidates:
        raise RuntimeError("Did not recognise group axis " + str(group_axis))
    if group_axis == None:
        group_list = [item for item in data]
        return {"": {"item_list": [i for i in range(len(data))]}}
    else:
        # group_list is lists the possible groups
        # e.g. list of all possible values of "__bump_field_1__"
        group_list = [item['substitutions'][group_axis] for item in data]
        group_list = list(set(group_list))  # unique list
        # tmp_group_dict is mapping from group value to the items having that value
        tmp_group_dict = dict([(group, []) for group in group_list])
        for key in tmp_group_dict:
            tmp_group_dict[key] = [i for i, item in enumerate(data) \
                                        if item['substitutions'][group_axis] == key]
    group_dict = {}
    for key in tmp_group_dict:
        new_key = utilities.sub_to_name(group_axis) + " " + format(key, "3.3g")
        group_dict[new_key] = {'item_list': tmp_group_dict[key]}
        print(new_key, ":", group_dict[new_key])
    return group_dict
Exemple #10
0
def plot_data_1d(data,
                 tune_axis,
                 plot_dir,
                 group_axis=None,
                 cell_conversion=1,
                 skip_length_one=True):
    """
    Plot x and y tune against a given parameter, grouping by "group_axis"
      - data: the tune data
      - tune_axis: string ... ring tune or cell tune
      - plot_dir: directory to place the plot
      - group_axis: set to None to ignore; set to a substitution variable to
                    place tune items in the same graph if the group_axis is the
                    same
      - cell_conversion: scale the tunes by the "cell_conversion" factor
      - skip_length_one: ignore a graph if there is only one element
    """
    axis_candidates = utilities.get_substitutions_axis(data)
    if group_axis in axis_candidates:
        del axis_candidates[group_axis]
    group_dict = get_groups(data, group_axis)
    group_key_list = list(group_dict.keys())
    for group_key in group_key_list:
        my_axes = dict([(key, []) for key in axis_candidates])
        x_signal, y_signal = [], []
        x_tune, y_tune = [], []
        x_tune_err, y_tune_err = [], []
        item_list = group_dict[group_key]['item_list']
        for i in item_list:
            item = data[i]
            verbose = False
            x_dphi = clean_tune_data(item['x_dphi'], verbose)
            y_dphi = clean_tune_data(item['y_dphi'], verbose)
            if verbose:
                print("X DPHI", sorted(x_dphi))
                print("Y DPHI", sorted(y_dphi))
            x_tune.append(numpy.mean(x_dphi))
            y_tune.append(numpy.mean(y_dphi))
            x_signal.append(item['x_signal'])
            y_signal.append(item['y_signal'])

            if len(x_dphi) > 1:
                x_tune_err.append(numpy.std(x_dphi))
            else:
                x_tune_err.append(1.)
            if len(y_dphi) > 1:
                y_tune_err.append(numpy.std(y_dphi))
            else:
                y_tune_err.append(1.)

            for key in my_axes:
                my_axes[key].append(item['substitutions'][key])
            if cell_conversion != 1:
                x_tune = [
                    nu * cell_conversion - math.floor(nu * cell_conversion)
                    for nu in x_tune
                ]
                y_tune = [
                    nu * cell_conversion - math.floor(nu * cell_conversion)
                    for nu in y_tune
                ]
        if len(x_tune) == 1 and skip_length_one:
            del group_dict[group_key]
            print("Removed", group_key, "because length was 1")
            continue

        group_dict[group_key]['x_tune'] = x_tune
        group_dict[group_key]['x_tune_err'] = x_tune_err
        group_dict[group_key]['y_tune'] = y_tune
        group_dict[group_key]['y_tune_err'] = y_tune_err
        group_dict[group_key]['axes'] = my_axes
        group_dict[group_key]['x_signal'] = x_signal
        group_dict[group_key]['y_signal'] = y_signal

    for key in axis_candidates:
        do_one_1d_plot(key, group_dict, plot_dir, tune_axis)
        do_ellipse_plot(key, group_dict, plot_dir, tune_axis)
    return