def main(): config = ConfigLoader("config.yml") decay = config.get_amplitude().decay_group data = config.get_data("phsp") ret = [] for i in data: cached_amp = build_angle_amp_matrix(decay, i) ret.append(data_to_numpy(cached_amp)) idx = config.get_data_index("angle", "R_BC/B") ang = data_index(data[0], idx) np.savez("phsp.npz", ret) for k, v in ret[0].items(): for i, amp in enumerate(v): w = np.abs(amp)**2 w = np.sum(np.reshape(w, (amp.shape[0], -1)), axis=-1) plt.hist( np.cos(ang["beta"]), weights=w, bins=20, histtype="step", label="{}: {}".format(k, i), ) plt.savefig("angle_costheta.png")
def test_load(): with write_temp_file(resonancs_str) as f: cs = config_str.format(file_name=f) print(cs) with write_temp_file(cs) as g: config = ConfigLoader(g) config.get_amplitude()
def test_chain_phsp(): dic = yaml.full_load(config_text) config = ConfigLoader(dic) data = config.generate_toy(10) data.mass_hist("(C, F, G, H)").draw() import matplotlib.pyplot as plt plt.savefig("chain_phsp.png")
def test_cp_decay(): with open(f"{this_dir}/config_toy.yml") as f: config_data = yaml.full_load(f) config_data["decay_chain"] = {"$all": {"is_cp": True}} config = ConfigLoader(config_data) amp = config.get_amplitude() data = config.get_data("data")[0] amp(data)
def test_constrains(): with write_temp_file(resonancs_str) as f: cs = config_str.format(file_name=f) print(cs) with write_temp_file(cs) as g: config = ConfigLoader(g) amp = config.get_amplitude() config.add_free_var_constraints(amp)
def single_fit(config_dict, data, phsp, bg): config = ConfigLoader(config_dict) print("\n########### initial parameters") pprint(config.get_params()) print(config.full_decay) fit_result = config.fit(data, phsp, bg=bg) pprint(fit_result.params) # fit_result.save_as("final_params.json") return fit_result.min_nll, fit_result.ndf
def plot(params_file): config = ConfigLoader("config.yml") with open(params_file) as f: params = yaml.safe_load(f) params = params["value"] config.plot_partial_wave(params, plot_pull=True, prefix="fig/", save_pdf=True, save_root=True)
def plot_all( res="MI(1+)S", config_file="config.yml", params="final_params.json", prefix="figure/", ): """plot all figure""" config = ConfigLoader(config_file) config.set_params(params) particle = config.get_decay().get_particle(res) mi, r, phi_i, r_e, phi_e = load_params(config_file, params, res) x, y, x_e, y_e = trans_r2xy(r, phi_i, r_e, phi_e) m = np.linspace(mi[0], mi[-1], 1000) M_Kpm = 0.49368 M_Dpm = 1.86961 M_Dstar0 = 2.00685 M_Bpm = 5.27926 # x_new = interp1d(xi, x, "cubic")(m) # y_new = interp1d(xi, y, "cubic")(m) rm_new = particle.interp(m).numpy() x_new, y_new = rm_new.real, rm_new.imag pq = dalitz_weight(m * m, M_Bpm, M_Dstar0, M_Dpm, M_Kpm) pq_i = dalitz_weight(mi * mi, M_Bpm, M_Dstar0, M_Dpm, M_Kpm) phi = np.arctan2(y_new, x_new) r2 = x_new * x_new + y_new * y_new plot_phi(f"{prefix}phi.png", m, phi, mi, np.arctan2(y, x)) plot_x_y( f"{prefix}r2.png", m, r2, mi, r * r, "mass", "$|R(m)|^2$", ylim=(0, None), ) plot_x_y(f"{prefix}x_y.png", x_new, y_new, x, y, "real R(m)", "imag R(m)") plot_x_y_err(f"{prefix}x_y_err.png", x[1:-1], y[1:-1], x_e[1:-1], y_e[1:-1]) plot_x_y( f"{prefix}r2_pq.png", m, r2 * pq, mi, r * r * pq_i, "mass", "$|R(m)|^2 p \cdot q$", ylim=(0, None), ) plot3d_m_x_y(f"{prefix}m_r.gif", m, x_new, y_new)
def cal_fitfractions(params_file): config = ConfigLoader("config.yml") config.set_params(params_file) params = config.get_params() config.get_params_error(params) mcdata = ( config.get_phsp_noeff() ) # use the file of PhaseSpace MC without efficiency indicated in config.yml fit_frac, err_frac = fit_fractions( config.get_amplitude(), mcdata, config.inv_he, params ) print("########## fit fractions:") fit_frac_string = "" for i in fit_frac: if isinstance(i, tuple): name = "{}x{}".format(*i) # interference term else: name = i # fit fraction fit_frac_string += "{} {}\n".format( name, error_print(fit_frac[i], err_frac.get(i, None)) ) print(fit_frac_string) print("########## fit fractions table:") print_frac_table( fit_frac_string ) # print the fit-fractions as a 2-D table. The codes below are just to implement the print function.
def main(): config = ConfigLoader("config.yml") config.set_params("final_params.json") amp = config.get_amplitude() data = config.get_data("data_origin")[0] phsp = config.get_data("phsp_plot")[0] phsp_re = config.get_data("phsp_plot_re")[0] print("data loaded") amps = amp(phsp_re) pw = amp.partial_weight(phsp_re) re_weight = phsp_re["weight"] re_size = config.resolution_size amps = sum_resolution(amps, re_weight, re_size) pw = [sum_resolution(i, re_weight, re_size) for i in pw] m_idx = config.get_data_index("mass", "R_BC") m_phsp = data_index(phsp, m_idx).numpy() m_data = data_index(data, m_idx).numpy() m_min, m_max = np.min(m_phsp), np.max(m_phsp) scale = m_data.shape[0] / np.sum(amps) get_hist = lambda m, w: Hist1D.histogram( m, weights=w, range=(m_min, m_max), bins=100) data_hist = get_hist(m_data, None) phsp_hist = get_hist(m_phsp, scale * amps) pw_hist = [] for i in pw: pw_hist.append(get_hist(m_phsp, scale * i)) ax2 = plt.subplot2grid((4, 1), (3, 0), rowspan=1) ax = plt.subplot2grid((4, 1), (0, 0), rowspan=3, sharex=ax2) data_hist.draw_error(ax, label="data") phsp_hist.draw(ax, label="fit") for i, j in zip(pw_hist, config.get_decay()): i.draw_kde(ax, label=str(j.inner[0])) (data_hist - phsp_hist).draw_pull(ax2) ax.set_ylim((1, None)) ax.legend() ax.set_yscale("log") ax.set_ylabel("Events/{:.1f} MeV".format((m_max - m_min) * 10)) ax2.set_xlabel("M( R_BC )") ax2.set_ylabel("pull") ax2.set_xlim((1.3, 1.7)) ax2.set_ylim((-5, 5)) plt.setp(ax.get_xticklabels(), visible=False) plt.savefig("m_R_BC_fit.png")
def get_data(config_file="config.yml", init_params="init_params.json"): config = ConfigLoader(config_file) try: config.set_params(init_params) print("using {}".format(init_params)) except Exception as e: print("using RANDOM parameters") phsp = config.get_data("phsp") for i in config.full_decay: print(i) for j in i: print(j.get_ls_list()) print("\n########### initial parameters") print(json.dumps(config.get_params(), indent=2)) params = config.get_params() amp = config.get_amplitude() pw = amp.partial_weight(phsp) pw_if = amp.partial_weight_interference(phsp) weight = amp(phsp) print(weight) return config, amp, phsp, weight, pw, pw_if
def main(): config = ConfigLoader("config.yml") data = config.get_data("data")[0] phsp = config.get_data("phsp")[0] bg = config.get_data("bg")[0] config.set_params("final_params.json") mbc_idx = config.get_data_index("mass", "R_BC") # ("particle", "(D, K)", "m") mbd_idx = config.get_data_index("mass", "R_BD") # ("particle", "(D0, K, pi)", "m") data_idx = [mbc_idx, mbd_idx] data_cut = np.array([data_index(data, idx) for idx in data_idx]) adapter = AdaptiveBound(data_cut**2, [[2, 2], [3, 3], [2, 2]]) bound = adapter.get_bounds() cal_chi2_config(config, adapter, data, phsp, data_idx, bg=bg, data_cut=data_cut) draw_dalitz(data_cut, bound)
def fit(final_params_file): config = ConfigLoader( "config.yml" ) # We use ConfigLoader to read the information in the configuration file # config.set_params("gen_params.json") # If not set, we will use random initial parameters fit_result = config.fit(method="BFGS") errors = config.get_params_error( fit_result) # calculate Hesse errors of the parameters print("\n########## fit parameters:") for key, value in config.get_params().items(): print(key, error_print(value, errors.get(key, None))) fit_result.save_as(final_params_file) # save fit_result to a json file config.plot_partial_wave( fit_result ) # Plot distributions of variables indicated in the configuration file fit_frac, err_frac = config.cal_fitfractions() print("\n########## fit fractions:") for i in fit_frac: if not isinstance(i, tuple): # fit fraction name = i else: name = "{}x{}".format(*i) # interference term print(name + ": " + error_print(fit_frac[i], err_frac.get(i, None)))
def main(): sigma = 0.005 config = ConfigLoader("config.yml") decay = config.get_decay() m0 = decay.top.get_mass() m1, m2, m3 = [i.get_mass() for i in decay.outs] print("mass: ", m0, " -> ", m1, m2, m3) phsp = PhaseSpaceGenerator(m0, [m1, m2, m3]) p1, p2, p3 = phsp.generate(100000) angle = cal_angle_from_momentum({"B": p1, "C": p2, "D": p3}, decay) amp = config.get_amplitude() m_idx = config.get_data_index("mass", "R_BC") m_BC = data_index(angle, m_idx) R_BC = decay.get_particle("R_BC1") m_R, g_R = R_BC.get_mass(), R_BC.get_width() # import matplotlib.pyplot as plt # x = np.linspace(1.3, 1.7, 1000) # amp = R_BC.get_amp({"m": x}).numpy() # plt.plot(x, np.abs(amp)**2) # plt.show() print("mass: ", m_R, "width: ", g_R) amp_s2 = resolution_bw(m_BC, m_R, g_R, sigma, m1 + m2, m0 - m3) print("|A|*R: ", amp_s2) cut_data = simple_selection(angle, amp_s2) ps = [data_index(cut_data, ("particle", i, "p")).numpy() for i in "BCD"] np.savetxt("data/data_origin.dat", np.transpose(ps, (1, 0, 2)).reshape((-1, 4))) p1, p2, p3 = phsp.generate(100000) np.savetxt("data/phsp.dat", np.transpose([p1, p2, p3], (1, 0, 2)).reshape((-1, 4))) p1, p2, p3 = phsp.generate(50000) np.savetxt( "data/phsp_plot.dat", np.transpose([p1, p2, p3], (1, 0, 2)).reshape((-1, 4)), )
def test_load(): with write_temp_file(resonancs_str) as f: cs = config_str.format(file_name=f) print(cs) with write_temp_file(cs) as g: config = ConfigLoader(g) with open(g) as f: data = yaml.full_load(f) config2 = ConfigLoader(data) config.get_amplitude() config2.get_amplitude()
def main(): sym.init_printing() config = ConfigLoader("config.yml") decay_group = config.get_decay() decay_chain = list(decay_group)[0] print(decay_chain) angle = get_angle_distrubution(decay_chain) ret = [] for k, v in angle.items(): for k2, v2 in v.items(): f_theta = simplify(v2 * v2.conjugate()) print("ls: ", k) print(" lambda:", k2) print(" :", f_theta) ret.append(f_theta) # break f_theta = ret[0] plot_theta("costheta.png", f_theta, "theta1") plot_theta("costheta2.png", f_theta, "theta2") plot_theta("phi2.png", f_theta, "phi2")
def main(): sigma = 0.005 r_name = "R_BC" config = ConfigLoader("config.yml") sample_N = config.resolution_size decays = config.get_decay(False) decay_chain = decays.get_decay_chain(r_name) data = config.get_data("data_origin")[0] phsp = config.get_data("phsp_plot")[0] dat_order = config.get_dat_order() generate = lambda x: gauss_random(x, decay_chain, r_name, sigma, sample_N, dat_order) pi = generate(data) np.savetxt("data/data.dat", pi) np.savetxt("data/data_weight.dat", np.ones((pi.shape[0] // len(dat_order), ))) pi = generate(phsp) np.save("data/phsp_re.npy", pi) np.savetxt("data/phsp_re_weight.dat", np.ones((pi.shape[0] // len(dat_order), )))
def main(): Nbins = 64 config = ConfigLoader("config.yml") # config = MultiConfig(["config.yml"]).configs[0] config.set_params("final_params.json") name = "R_BC" idx = config.get_data_index("mass", "R_BC") # idx_costheta = (*config.get_data_index("angle", "DstD/D*"), "beta") datas, phsps, bgs, _ = config.get_all_data() amp = config.get_amplitude() get_data = lambda x: data_index(x, idx).numpy() # get_data = lambda x: np.cos(data_index(x, idx_costheta).numpy()) plot_mass(amp, datas, bgs, phsps, get_data, name, Nbins)
def generate_toy_from_phspMC(Ndata, mc_file, data_file): """Generate toy using PhaseSpace MC from mc_file""" config = ConfigLoader(f"{this_dir}/config_toy.yml") config.set_params(f"{this_dir}/gen_params.json") amp = config.get_amplitude() data = gen_data( amp, Ndata=Ndata, mcfile=mc_file, genfile=data_file, particles=config.get_dat_order(), ) return data
def test_constrains(gen_toy): config = ConfigLoader(f"{this_dir}/config_cfit.yml") var_name = "A->R_CD.B_g_ls_1r" config.config["constrains"]["init_params"] = {var_name: 1.0} @config.register_extra_constrains("init_params") def float_var(amp, params=None): amp.set_params(params) config.register_extra_constrains("init_params2", float_var) amp = config.get_amplitude() assert amp.get_params()[var_name] == 1.0
def cal_errors(params_file): config = ConfigLoader("config.yml") config.set_params(params_file) fcn = config.get_fcn() fcn.model.Amp.vm.rp2xy_all( ) # we can use this to transform all complex parameters to xy-coordinates, since the Hesse errors of xy are more statistically reliable params = config.get_params() errors, config.inv_he = cal_hesse_error( fcn, params, check_posi_def=True, save_npy=True ) # obtain the Hesse errors and the error matrix (inverse Hessian) print("\n########## fit parameters in XY-coordinates:") errors = dict(zip(fcn.model.Amp.vm.trainable_vars, errors)) for key, value in config.get_params().items(): print(key, error_print(value, errors.get(key, None))) print("\n########## correlation matrix:") print("Matrix index:\n", fcn.model.Amp.vm.trainable_vars) print("Correlation Coefficients:\n", corr_coef_matrix(config.inv_he) ) # obtain the correlation matrix using the inverse Hessian
def generate_toy_from_phspMC(Ndata, mc_file, data_file): """Generate toy using PhaseSpace MC from mc_file""" # We use ConfigLoader to read the information in the configuration file config = ConfigLoader("config.yml") # Set the parameters in the amplitude model config.set_params("gen_params.json") amp = config.get_amplitude() # data is saved in data_file data = gen_data( amp, Ndata=Ndata, mcfile=mc_file, # input phsase space file genfile=data_file, # saved toy data file # use the order in config, the default is ascii order. particles=config.get_dat_order(), ) return data
def main(): import argparse parser = argparse.ArgumentParser(description="calculate fit fractions") parser.add_argument("-c", "--config", default="config.yml") parser.add_argument("-i", "--init_params", default="final_params.json") parser.add_argument("-e", "--error_matrix", default="error_matrix.npy") results = parser.parse_args() # load model and parameters and error matrix config = ConfigLoader(results.config) config.set_params(results.init_params) err_matrix = np.load(results.error_matrix) amp = config.get_amplitude() phsp = config.get_phsp_noeff() # get_data("phsp")[0] cal_frac(amp, phsp, err_matrix)
def main(): sigma = 0.005 sigma_delta = 5 r_name = "R_BC" config = ConfigLoader("config.yml") sample_N = config.resolution_size decays = config.get_decay(False) decay_chain = decays.get_decay_chain(r_name) data = config.get_data("data_origin")[0] pi, total_weights = gauss_sample(data, decay_chain, "R_BC", sigma, sample_N, config.get_dat_order()) np.savetxt("data/data.dat", pi.reshape((-1, 4))) np.savetxt("data/data_weight.dat", np.reshape(total_weights, (-1, ))) data = config.get_data("phsp_plot")[0] pi, total_weights = gauss_sample(data, decay_chain, "R_BC", sigma, sample_N, config.get_dat_order()) np.save("data/phsp_re.npy", pi.reshape((-1, 4))) np.savetxt("data/phsp_re_weight.dat", np.reshape(total_weights, (-1, )))
def load_config(config_file="config.yml", total_same=False): config_files = config_file.split(",") if len(config_files) == 1: return ConfigLoader(config_files[0]) return MultiConfig(config_files, total_same=total_same)
def main(): sigma = 0.005 r_name = "DstD" config = ConfigLoader("config_data.yml") decays = config.get_decay(False) decay_chain = decays.get_decay_chain(r_name) data = config.get_data("data")[0] angle = cal_helicity_angle(data["particle"], decay_chain.standard_topology()) decay_chain.standard_topology() tp_map = decay_chain.topology_map() r_particle = tp_map[get_particle(r_name)] mass = {} for i in data["particle"]: mi = data["particle"][i]["m"] if i == r_particle: mi = mi + tf.random.normal(mi.shape, 0, sigma, dtype=mi.dtype) mass[i] = mi mask = True p4_all = {} for i in decay_chain: phi = angle[tp_map[i]][tp_map[i.outs[0]]]["ang"]["alpha"] theta = angle[tp_map[i]][tp_map[i.outs[0]]]["ang"]["beta"] m0 = mass[tp_map[i.core]] m1 = mass[tp_map[i.outs[0]]] m2 = mass[tp_map[i.outs[1]]] mask = mask & (m0 >= m1 + m2) p_square = get_relative_p2(m0, m1, m2) p = tf.sqrt(tf.where(p_square > 0, p_square, 0)) pz = p * tf.cos(theta) px = p * tf.sin(theta) * tf.cos(phi) py = p * tf.sin(theta) * tf.sin(phi) E1 = tf.sqrt(m1 * m1 + p * p) E2 = tf.sqrt(m2 * m2 + p * p) p1 = tf.stack([E1, px, py, pz], axis=-1) p2 = tf.stack([E2, -px, -py, -pz], axis=-1) p4_all[i.outs[0]] = p1 p4_all[i.outs[1]] = p2 core_boost = {} for i in decay_chain: if i.core != decay_chain.top: core_boost[i.outs[0]] = i.core core_boost[i.outs[1]] = i.core ret = {} for i in decay_chain.outs: tmp = i ret[i] = p4_all[i] while tmp in core_boost: tmp = core_boost[tmp] # print(i, tmp) ret[i] = lv.rest_vector(lv.neg(p4_all[tmp]), ret[i]) ret2 = {} mask = tf.expand_dims(mask, -1) for i in ret: ret2[i] = tf.where(mask, ret[i], data["particle"][tp_map[i]]["p"]) # print(ret) # print({i: data["particle"][tp_map[i]]["p"] for i in decay_chain.outs}) pi = np.stack([ret2[i] for i in config.get_dat_order()], axis=1) np.savetxt("data_gauss.dat", pi.reshape((-1, 4)))
def test_cfit(gen_toy): config = ConfigLoader(f"{this_dir}/config_cfit.yml") config.set_params(f"{this_dir}/gen_params.json") fcn = config.get_fcn() fcn({}) fcn.nll_grad({})
def toy_config(gen_toy): config = ConfigLoader(f"{this_dir}/config_toy.yml") config.set_params(f"{this_dir}/exp_params.json") return config
R2: { mass: 0.824, width: 0.05, J: 0, P: +1} R3: { mass: 0.824, width: 0.05, J: 0, P: +1} """ # %% # The config file can be loaded by `yaml` library. # import matplotlib.pyplot as plt import yaml from tf_pwa.config_loader import ConfigLoader from tf_pwa.histogram import Hist1D config = ConfigLoader(yaml.full_load(config_str)) # %% # We set parameters to a blance value. And we can generate some toy data and calclute the weights # input_params = { "A->R1_a.BR1_a->C.D_total_0r": 6.0, "A->R1_b.BR1_b->C.D_total_0r": 1.0, "A->R2.CR2->B.D_total_0r": 2.0, "A->R3.DR3->B.C_total_0r": 1.0, } config.set_params(input_params) data = config.generate_toy(1000) phsp = config.generate_phsp(10000)
def main(): config = ConfigLoader("config.yml") for i, dec in enumerate(config.get_decay()): draw_decay_struct(dec, filename="figure/fig_{}".format(i), format="png")