def make_txt_hist_from_root_file(file_path_txt, rid, is_parallel, draw_string, hist_dim, cut_string="", option_string="", titles=("", "", "")): """Given a draw/cut string, take an SRK ROOT results file and create a histogram from it.""" if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str( rid) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() histogram = TH1D("tempHist", "tempHist", hist_dim[0], hist_dim[1], hist_dim[2]) total_draw_string = draw_string + " >> tempHist" hit_tree.Draw(total_draw_string, cut_string, option_string) make_txt_from_hist(file_path_txt, histogram, titles) root_file.Close() return
def calc_delta_stats_same_tracks(run_id, use_wrapping=True): """Calculates differences in orientation of fields when tracks are the same""" hit_trees = [] root_files = [] for is_parallel in [True, False]: if is_parallel: letter = 'P' else: letter = 'A' file_path = srkglobal.results_dir + "Results_RID" + str(run_id) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_files.append(TFile(file_path, "READ")) hit_trees.append(gDirectory.Get('hitTree')) gROOT.cd() delta_phi_list = [] for i in xrange(hit_trees[0].GetEntries()): hit_trees[0].GetEntry(i) hit_trees[1].GetEntry(i) delta_phi = hit_trees[0].phi - hit_trees[1].phi delta_phi_list.append(delta_phi) if use_wrapping: delta_phi_mean = srkmisc.reduce_periodics(delta_phi_list) else: delta_phi_mean = srkmisc.careful_mean(delta_phi_list) delta_phi_std = srkmisc.careful_std(delta_phi_list) root_files[0].Close() root_files[1].Close() return [delta_phi_mean, delta_phi_std]
def make_txt_hist_from_root_file(file_path_txt, rid, is_parallel, draw_string, hist_dim, cut_string="", option_string="", titles=("", "", "")): """Given a draw/cut string, take an SRK ROOT results file and create a histogram from it.""" if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str(rid) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() histogram = TH1D("tempHist", "tempHist", hist_dim[0], hist_dim[1], hist_dim[2]) total_draw_string = draw_string + " >> tempHist" hit_tree.Draw(total_draw_string, cut_string, option_string) make_txt_from_hist(file_path_txt, histogram, titles) root_file.Close() return
def make_alpha_vs_phi_plot(run_id, is_parallel): if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str(run_id) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() num_events = hit_tree.GetEntries() phi_list = [] alpha_list = [] radius = srkdata.get_data_for_rids_from_database([run_id], "ChamberRadius")[0][0] print radius for i in xrange(num_events): hit_tree.GetEntry(i) phi_list.append(hit_tree.phi) alpha = get_alpha_angle_2d(radius, hit_tree.pos0, hit_tree.vel0) alpha_list.append(alpha) root_file.Close() phi_mean = srkmisc.reduce_periodics(phi_list) delta_phi_list = map(lambda x: x - phi_mean, phi_list) plt.scatter(alpha_list, delta_phi_list)
def calc_delta_stats_same_tracks(run_id, use_wrapping=True): """Calculates differences in orientation of fields when tracks are the same""" hit_trees = [] root_files = [] for is_parallel in [True, False]: if is_parallel: letter = 'P' else: letter = 'A' file_path = srkglobal.results_dir + "Results_RID" + str( run_id) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_files.append(TFile(file_path, "READ")) hit_trees.append(gDirectory.Get('hitTree')) gROOT.cd() delta_phi_list = [] for i in xrange(hit_trees[0].GetEntries()): hit_trees[0].GetEntry(i) hit_trees[1].GetEntry(i) delta_phi = hit_trees[0].phi - hit_trees[1].phi delta_phi_list.append(delta_phi) if use_wrapping: delta_phi_mean = srkmisc.reduce_periodics(delta_phi_list) else: delta_phi_mean = srkmisc.careful_mean(delta_phi_list) delta_phi_std = srkmisc.careful_std(delta_phi_list) root_files[0].Close() root_files[1].Close() return [delta_phi_mean, delta_phi_std]
def get_result_data(leaf_names, run_id, is_parallel): """Get result data directly from root files based on leaf names""" if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str( run_id) + "_" + letter + ".root" print "Opening ", file_path if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() num_events = hit_tree.GetEntries() data = [] for leaf_name in leaf_names: temp_data = [] for i in xrange(num_events): hit_tree.GetEntry(i) temp_data.append( hit_tree.GetBranch(leaf_name).GetListOfLeaves()[0].GetValue()) data.append(temp_data) root_file.Close() return data
def get_result_data(leaf_names, run_id, is_parallel): """Get result data directly from root files based on leaf names""" if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str(run_id) + "_" + letter + ".root" print "Opening ", file_path if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() num_events = hit_tree.GetEntries() data = [] for leaf_name in leaf_names: temp_data = [] for i in xrange(num_events): hit_tree.GetEntry(i) temp_data.append(hit_tree.GetBranch(leaf_name).GetListOfLeaves()[0].GetValue()) data.append(temp_data) root_file.Close() return data
def make_root_plot_from_results_file(rid, is_parallel, draw_string, cut_string="", option_string=""): """Makes a ROOT plot from results file based on a draw and cut string.""" # gStyle.SetOptStat("iMRKS") if is_parallel: letter = 'P' else: letter = 'A' file_path = srkglobal.results_dir + "Results_RID" + str( rid) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() c1 = rootnotes.canvas("Canvas", (1200, 800)) hit_tree.Draw(draw_string, cut_string, option_string) root_file.Close() return c1
def make_alpha_vs_phi_plot(run_id, is_parallel): if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str( run_id) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() num_events = hit_tree.GetEntries() phi_list = [] alpha_list = [] radius = srkdata.get_data_for_rids_from_database([run_id], "ChamberRadius")[0][0] print radius for i in xrange(num_events): hit_tree.GetEntry(i) phi_list.append(hit_tree.phi) alpha = get_alpha_angle_2d(radius, hit_tree.pos0, hit_tree.vel0) alpha_list.append(alpha) root_file.Close() phi_mean = srkmisc.reduce_periodics(phi_list) delta_phi_list = map(lambda x: x - phi_mean, phi_list) plt.scatter(alpha_list, delta_phi_list)
def make_sz_prob_dist(run_id, is_parallel, use_wrapping=True): """Make a spin direction (after flip) detection probability histogram""" if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str( run_id) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return [] root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() num_events = hit_tree.GetEntries() phi_list = [] theta_list = [] for i in xrange(num_events): hit_tree.GetEntry(i) phi_list.append(hit_tree.phi) theta_list.append(hit_tree.theta) root_file.Close() if use_wrapping: phi_mean = srkmisc.reduce_periodics(phi_list) else: phi_mean = srkmisc.careful_mean(phi_list) phi_std = srkmisc.careful_std(phi_list) theta_std = srkmisc.careful_std(theta_list) comb_std = np.sqrt(phi_std * phi_std + theta_std * theta_std) print "Combined Standard deviation: %e" % (comb_std) x = np.linspace(-30, 30, num=60) y = [] for num_std_dev in x: sz_det_prob = 0 for phi, theta in zip(phi_list, theta_list): sz_det_prob += calc_opposite_spin_prob( phi - phi_mean + comb_std * num_std_dev, theta) sz_det_prob /= num_events y.append(1 - sz_det_prob) return x, y
def check_user_info_tree(run_id, post_fix): """Prints use info tree (contains used macro commands).""" file_path = srkdata.srkglobal.results_dir + "Results_RID" + str(run_id) + "_" + post_fix + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') u = hit_tree.GetUserInfo() u.Print() root_file.Close() return
def check_user_info_tree(run_id, post_fix): """Prints use info tree (contains used macro commands).""" file_path = srkdata.srkglobal.results_dir + "Results_RID" + str( run_id) + "_" + post_fix + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') u = hit_tree.GetUserInfo() u.Print() root_file.Close() return
def make_sz_prob_dist(run_id, is_parallel, use_wrapping=True): """Make a spin direction (after flip) detection probability histogram""" if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str(run_id) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return [] root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() num_events = hit_tree.GetEntries() phi_list = [] theta_list = [] for i in xrange(num_events): hit_tree.GetEntry(i) phi_list.append(hit_tree.phi) theta_list.append(hit_tree.theta) root_file.Close() if use_wrapping: phi_mean = srkmisc.reduce_periodics(phi_list) else: phi_mean = srkmisc.careful_mean(phi_list) phi_std = srkmisc.careful_std(phi_list) theta_std = srkmisc.careful_std(theta_list) comb_std = np.sqrt(phi_std * phi_std + theta_std * theta_std) print "Combined Standard deviation: %e" % (comb_std) x = np.linspace(-30, 30, num=60) y = [] for num_std_dev in x: sz_det_prob = 0 for phi, theta in zip(phi_list, theta_list): sz_det_prob += calc_opposite_spin_prob(phi - phi_mean + comb_std * num_std_dev, theta) sz_det_prob /= num_events y.append(1 - sz_det_prob) return x, y
def make_and_run(srk_settings, run_settings, computer="work_laptop"): """Adds run to database, makes macro, and runs it (remotely if on optima)""" prev_comp = srkglobal.computer srkglobal.set_computer(computer) rid = make_macro_and_add_to_database(srk_settings, run_settings) if computer == "optima": run_macro_optima(rid) else: run_macro_local(rid, True) results_path = srkglobal.results_dir + 'Results_RID' + str(rid) + '.root' # time.sleep(5) #To wait for SRK to finish. Maybe later somewhere else, or have return value of SRK? if not srkmisc.file_exits_and_not_zombie(results_path): print "No results file created. Check log." else: update_database({"ResultsFilePath": results_path}, "Run=" + str(rid)) srkglobal.set_computer(prev_comp)
def calc_step_tree(file_path, inp_periodic_stop_time): """Calculate time and spin detection probabilities from step tree.""" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return [] print "Calculating step tree for {}".format(file_path) root_file = TFile(file_path, "READ") step_tree = gDirectory.Get('stepTree') hit_tree = gDirectory.Get('hitTree') gROOT.cd() user_info_list = hit_tree.GetUserInfo() periodic_stop_time = inp_periodic_stop_time for i in xrange(user_info_list.GetEntries()): par = user_info_list.At(i) if par.GetName() == 'PeriodicStopTime': periodic_stop_time = float(par.GetTitle()) break num_events = hit_tree.GetEntries() num_steps_per_event = step_tree.GetEntries() / num_events time_data = np.zeros(num_steps_per_event) sx_prob_data = np.zeros(num_steps_per_event) # Set times for j in xrange(num_steps_per_event): time_data[j] = ((j + 1) * periodic_stop_time) # Add data for i in xrange(num_events): if i % 100 == 0: print "Stepping for Event {} in {}".format(i, file_path) for j in xrange(num_steps_per_event): step_tree.GetEntry(i * num_steps_per_event + j) sx_prob_data[j] += step_tree.sxProb # Normalize sx_prob_data /= float(num_events) root_file.Close() return zip(time_data, sx_prob_data)
def calc_stats_for_results_file(file_path, runtype="nedm", use_wrapping=False): """Calculates summary stats for a SRK results ROOT file.""" stats = srkdata.default_file_stats(runtype) # Check if file exists and is valid if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() stats['NumEventsRun'] = hit_tree.GetEntries() # Get arrays for phi and theta from file phi_array = np.empty(hit_tree.GetEntries()) theta_array = np.empty(hit_tree.GetEntries()) for i in xrange(stats['NumEventsRun']): hit_tree.GetEntry(i) phi_array[i] = hit_tree.phi theta_array[i] = hit_tree.theta root_file.Close() # Calculate the mean phi's and thetas. Depending on purpose, wrap around at two pi depending on mean location. if use_wrapping: stats['PhiMean'] = srkmisc.reduce_periodics(phi_array) stats['ThetaMean'] = srkmisc.reduce_periodics(theta_array) else: stats['PhiMean'] = srkmisc.careful_mean(phi_array) stats['ThetaMean'] = srkmisc.careful_mean(theta_array) if runtype != "g2": # Calculate probability of detecting the spin in the opposite direction stats['SZDetProb'] = 0. for phi, theta in zip(phi_array, theta_array): stats['SZDetProb'] += calc_opposite_spin_prob( phi - stats['PhiMean'], theta) stats['SZDetProb'] /= stats['NumEventsRun'] # Calculate other summary info stats['PhiStDev'] = srkmisc.careful_std(phi_array) stats['ThetaStDev'] = srkmisc.careful_std(theta_array) stats['PhiError'] = stats['PhiStDev'] / math.sqrt(len(phi_array)) stats['ThetaError'] = stats['ThetaStDev'] / math.sqrt(len(theta_array)) if runtype != "g2": stats['PhiKurtosis'] = kurtosis(phi_array) stats['ThetaKurtosis'] = kurtosis(theta_array) stats['PhiSkewness'] = skew(phi_array) stats['ThetaSkewness'] = skew(theta_array) print "Phi Kurtosis: %f" % stats['PhiKurtosis'] percentile_lower, percentile_upper = np.percentile( phi_array, (16.5, 83.50)) percentile_width = percentile_upper - percentile_lower stats['PhiPercentileWidth'] = percentile_width percentile_lower, percentile_upper = np.percentile( theta_array, (16.5, 83.5)) percentile_width = percentile_upper - percentile_lower stats['ThetaPercentileWidth'] = percentile_width # Fit phi to Tsallis q-Gaussian function (old form) power, error = make_tsallis_fit(phi_array, stats['PhiMean'], stats['PhiStDev']) stats['PhiTsallisPower'] = power stats['PhiTsallisPowerError'] = error # Fit theta to Tsallis q-Gaussian function (old form) power, error = make_tsallis_fit(theta_array, stats['ThetaMean'], stats['ThetaStDev']) stats['ThetaTsallisPower'] = power stats['ThetaTsallisPowerError'] = error # Fit phi to Tsallis q-Gaussian function (new form) power, error = make_qgaussian_fit(phi_array, stats['PhiMean'], stats['PhiStDev']) stats['PhiQGaussianQ'] = power stats['PhiQGaussianQError'] = error # Fit theta to Tsallis q-Gaussian function (new form) power, error = make_qgaussian_fit(theta_array, stats['ThetaMean'], stats['ThetaStDev']) stats['ThetaQGaussianQ'] = power stats['ThetaQGaussianQError'] = error return stats
def make_tree_to_array(run_id, query_list=default_params): """Makes the step_tree of result files into a numpy array""" #Currently only for one particle! # print query_list results_path = srkglobal.results_dir + "Results_RID" + str( run_id) + ".root" if not srkmisc.file_exits_and_not_zombie(results_path): print "No results file found for RunID " + str(run_id) + ". Aborting." return else: root_file = r.TFile(results_path, "READ") step_tree = r.gDirectory.Get('stepTree') # r.gROOT.cd() return_arr = np.empty((len(query_list), step_tree.GetEntries() + 2)) # tree_dict = { # "posX":step_tree.pos.x(), # "posZ":step_tree.pos.z(), # "velX":step_tree.vel.x(), # "velZ":step_tree.vel.z(), # "phi":step_tree.phi, # "theta":step_tree.theta() # } for i in range(step_tree.GetEntries()): step_tree.GetEntry(i) return_arr[0, i + 1] = step_tree.pos.x() return_arr[1, i + 1] = step_tree.pos.y() return_arr[2, i + 1] = step_tree.pos.z() return_arr[3, i + 1] = step_tree.vel.x() return_arr[4, i + 1] = step_tree.vel.y() return_arr[5, i + 1] = step_tree.vel.z() return_arr[6, i + 1] = step_tree.M.x() return_arr[7, i + 1] = step_tree.M.y() return_arr[8, i + 1] = step_tree.M.z() return_arr[9, i + 1] = step_tree.magM return_arr[10, i + 1] = step_tree.projection #return_arr[6,i+1] = step_tree.BFieldStrenth.x() #return_arr[7,i+1] = step_tree.BFieldStrenth.y() #return_arr[8,i+1] = step_tree.BFieldStrenth.z() # for j in range(len(query_list)): # return_arr[j,i]=tree_dict[query_list[j]] hit_tree = r.gDirectory.Get('hitTree') hit_tree.GetEntry(0) return_arr[0, 0] = hit_tree.pos0.x() return_arr[1, 0] = hit_tree.pos0.y() return_arr[2, 0] = hit_tree.pos0.z() return_arr[3, 0] = hit_tree.vel0.x() return_arr[4, 0] = hit_tree.vel0.y() return_arr[5, 0] = hit_tree.vel0.z() return_arr[6, 0] = hit_tree.M0.x() return_arr[7, 0] = hit_tree.M0.y() return_arr[8, 0] = hit_tree.M0.z() return_arr[9, 0] = hit_tree.magM0 return_arr[10, 0] = hit_tree.projection0 return_arr[0, -1] = hit_tree.pos.x() return_arr[1, -1] = hit_tree.pos.y() return_arr[2, -1] = hit_tree.pos.z() return_arr[3, -1] = hit_tree.vel.x() return_arr[4, -1] = hit_tree.vel.y() return_arr[5, -1] = hit_tree.vel.z() return_arr[6, -1] = hit_tree.M.x() return_arr[7, -1] = hit_tree.M.y() return_arr[8, -1] = hit_tree.M.z() return_arr[9, -1] = hit_tree.magM return_arr[10, -1] = hit_tree.projection root_file.Close() return return_arr
def calc_stats_for_results_file(file_path, use_wrapping=False): """Calculates summary stats for a SRK results ROOT file.""" stats = srkdata.default_file_stats() # Check if file exists and is valid if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() stats['NumEventsRun'] = hit_tree.GetEntries() # Get arrays for phi and theta from file phi_array = np.empty(hit_tree.GetEntries()) theta_array = np.empty(hit_tree.GetEntries()) for i in xrange(stats['NumEventsRun']): hit_tree.GetEntry(i) phi_array[i] = hit_tree.phi theta_array[i] = hit_tree.theta root_file.Close() # Calculate the mean phi's and thetas. Depending on purpose, wrap around at two pi depending on mean location. if use_wrapping: stats['PhiMean'] = srkmisc.reduce_periodics(phi_array) stats['ThetaMean'] = srkmisc.reduce_periodics(theta_array) else: stats['PhiMean'] = srkmisc.careful_mean(phi_array) stats['ThetaMean'] = srkmisc.careful_mean(theta_array) # Calculate probability of detecting the spin in the opposite direction stats['SZDetProb'] = 0. for phi, theta in zip(phi_array, theta_array): stats['SZDetProb'] += calc_opposite_spin_prob(phi - stats['PhiMean'], theta) stats['SZDetProb'] /= stats['NumEventsRun'] # Calculate other summary info stats['PhiStDev'] = srkmisc.careful_std(phi_array) stats['ThetaStDev'] = srkmisc.careful_std(theta_array) stats['PhiError'] = stats['PhiStDev'] / math.sqrt(len(phi_array)) stats['ThetaError'] = stats['ThetaStDev'] / math.sqrt(len(theta_array)) stats['PhiKurtosis'] = kurtosis(phi_array) stats['ThetaKurtosis'] = kurtosis(theta_array) stats['PhiSkewness'] = skew(phi_array) stats['ThetaSkewness'] = skew(theta_array) print "Phi Kurtosis: %f" % stats['PhiKurtosis'] percentile_lower, percentile_upper = np.percentile(phi_array, (16.5, 83.50)) percentile_width = percentile_upper - percentile_lower stats['PhiPercentileWidth'] = percentile_width percentile_lower, percentile_upper = np.percentile(theta_array, (16.5, 83.5)) percentile_width = percentile_upper - percentile_lower stats['ThetaPercentileWidth'] = percentile_width # Fit phi to Tsallis q-Gaussian function (old form) power, error = make_tsallis_fit(phi_array, stats['PhiMean'], stats['PhiStDev']) stats['PhiTsallisPower'] = power stats['PhiTsallisPowerError'] = error # Fit theta to Tsallis q-Gaussian function (old form) power, error = make_tsallis_fit(theta_array, stats['ThetaMean'], stats['ThetaStDev']) stats['ThetaTsallisPower'] = power stats['ThetaTsallisPowerError'] = error # Fit phi to Tsallis q-Gaussian function (new form) power, error = make_qgaussian_fit(phi_array, stats['PhiMean'], stats['PhiStDev']) stats['PhiQGaussianQ'] = power stats['PhiQGaussianQError'] = error # Fit theta to Tsallis q-Gaussian function (new form) power, error = make_qgaussian_fit(theta_array, stats['ThetaMean'], stats['ThetaStDev']) stats['ThetaQGaussianQ'] = power stats['ThetaQGaussianQError'] = error return stats