<jupyter_start><jupyter_text>Notebook for TAFT Time alignment for tiles<jupyter_code>%cd ..
import numpy as np
import matplotlib.pyplot as plt
from melp import Detector
import melp.taft
#from melp.taft import get_median_from_hist, read_histo, select<jupyter_output>Welcome to JupyROOT 6.24/06<jupyter_text>Creating/Loading detector with misalignment<jupyter_code>mu3e_detector = Detector.initFromROOT("./run42_20000.root")
#mu3e_detector = Detector.initFromSave("calibration_iteration2_v1.det")
#mu3e_detector = Detector.initFromSave("test_det.dev")
melp.taft.select(mu3e_detector)<jupyter_output><empty_output><jupyter_text>Plotting time misalignment distribution<jupyter_code>options_g = {"sigma": 2}
mu3e_detector.TileDetector.generate_misal(**options_g)
dt = []
for tile in mu3e_detector.TileDetector.tile:
    dt.append(mu3e_detector.TileDetector.tile[tile].dt_truth)
dt = np.array(dt)
plt.hist(dt, bins=200)
plt.show()
for tile_id in mu3e_detector.TileDetector.tile:
    tile = mu3e_detector.TileDetector.tile[tile_id]
    #tile.dt_truth_abs = tile.dt_truth # + master_tile
    tile.dt_cal_abs += tile.dt_cal
for tile_id in mu3e_detector.TileDetector.tile:
    tile = mu3e_detector.TileDetector.tile[tile_id]
    tile.dt_truth -= tile.dt_cal # + master_tile
    tile.dt_cal = 0.
mu3e_detector.TileDetector.calibrated = False<jupyter_output><empty_output><jupyter_text>Generating Histograms<jupyter_code>#options_hist = {
#    "histo_options": (40000, -20, 20),  # nbins, min, max (10000, -64, 64)
#    "hist_file": "hist_test_2.root",  # histogram save file
#    "ttree_loc": "mu3e"   # alignment/
#}
#melp.taft.generate_hist("../../Downloads/mu3e_sorted_000002.root", **options_hist)
#melp.taft.generate_hist("./merged.root", **options_hist)<jupyter_output><empty_output><jupyter_text>Calibrating Tile Detector<jupyter_code>options_cal = {
    "debug_station": 2,     # 1 / 2
    "tof": "simple",  # advanced_new / advanced_graf / simple / None
    "dt_mode": "median",    # MEDIAN / mean / gaus
    "overwrite": True,      # True / False
    "hist_file": '/run/media/maximilian/Volume/merged.root',  # "/run/media/maximilian/Volume/merged.root",
    
    "cosmic_correction": False,
    "cosmic_mc_primary": True,
    "cosmic_n_modes" : 5,  # (x2 for cos and sin)
    "ttree_loc": "alignment/mu3e",
    "cosmic_threshold": 0.05,  #m
    "cosmic_file": '/home/maximilian/Github/melp/mu3e_sorted_000002_cosmic.root'#'/home/maximilian/mu3e_sorted_000334.root'
    #"cosmic_file": '/home/maximilian/mu3e_run_000779_cosmic_sorted.root'
    #'/home/maximilian/mu3e_run_000779_cosmic_sorted.root'# '/run/media/maximilian/Volume/mu3e_sorted_000002_cosmic.root' #'./cosmic_test.root'
}
resid_z, resid_phi, cal_z, cal_phi, popt_1, popt_2 = melp.taft.calibrate(**options_cal)
#mu3e_detector.save("new_det_file_2.taft")
resid_z = np.array(resid_z)
resid_phi = np.array(resid_phi)
fig, axs = plt.subplots(1, 2, figsize=(12, 4))

axs[0].hist(resid_z, bins=200)
axs[0].title.set_text("residuals z-dir")
axs[1].hist(resid_phi, bins=200)
axs[1].title.set_text("residuals phi-dir")
plt.show()<jupyter_output><empty_output><jupyter_text>small data sets results in empty histograms between some tiles -> big jumps in dt  Result for z-direction (station 1)<jupyter_code>cal1 = {}
for phi_row in range(56):
    dt_truth = [0]
    for tile in range(0, 51):
        
        tile_id = 200000 + phi_row + tile * 56

        dt_tmp = (mu3e_detector.TileDetector.tile[tile_id].dt_truth -
                   mu3e_detector.TileDetector.tile[mu3e_detector.TileDetector.getNeighbour(tile_id, "right")].dt_truth)
        dt_truth.append(dt_truth[-1] + dt_tmp)

    cal1[phi_row] = np.array(dt_truth)
fig, axs = plt.subplots(1, 3, figsize=(16, 4))

for phi in cal1:
    axs[0].plot(np.array(cal1[phi], dtype=object))

axs[0].autoscale()
axs[0].title.set_text("Before alignment")

for phi in cal_z:
    axs[1].plot(cal_z[phi])

axs[1].set_ylim(axs[0].get_ylim())
axs[1].title.set_text("after alignment")

for phi in cal_z:
    axs[2].plot(cal_z[phi])

axs[2].title.set_text("after alignment (zoomed in)")
plt.show()<jupyter_output><empty_output><jupyter_text>Result for phi-direction<jupyter_code>cal2 = {}
for z_column in range(52):
    dt_truth = [0]
    for tile in range(0, 56):
        
        tile_id = (200000 + z_column*56 + tile)

        dt_tmp = (mu3e_detector.TileDetector.tile[tile_id].dt_truth -
                   mu3e_detector.TileDetector.tile[mu3e_detector.TileDetector.getNeighbour(tile_id, "up")].dt_truth)
        dt_truth.append(dt_truth[-1] + dt_tmp)

    cal2[z_column] = np.array(dt_truth)
fig, axs = plt.subplots(1, 3, figsize=(16, 4))

for phi in cal2:
    axs[0].plot(cal2[phi])

axs[0].autoscale()
axs[0].title.set_text("Before alignment")

for phi in cal_phi:
    axs[1].plot(cal_phi[phi])

axs[1].set_ylim(axs[0].get_ylim())
axs[1].title.set_text("after alignment")

for phi in cal_phi:
    axs[2].plot(cal_phi[phi])

axs[2].title.set_text("after alignment (zoomed in)")
plt.show()<jupyter_output><empty_output><jupyter_text>Calibrated station<jupyter_code>melp.taft.plot_station_calibration(mu3e_detector, 2)
#mu3e_detector.save("test_det.dev")
melp.taft.plot_calibration(mu3e_detector)
melp.taft.plot_correction_function(melp.taft.corrections.calibration_correction_z, popt_1, popt_2)
melp.taft.plot_error_dist(mu3e_detector)<jupyter_output><empty_output><jupyter_text>Testing section<jupyter_code>hist = []

master_time = mu3e_detector.TileDetector.tile[200000].dt_truth
for tileid in mu3e_detector.TileDetector.tile:
    if tileid >= 300000:
        continue
    tile = mu3e_detector.TileDetector.tile[tileid]
    time_t = tile.dt_truth - master_time
    time_c = tile.dt_cal
    hist.append(time_t - time_c)
def gauss_function(x, a, x0, sigma):
    return a*np.exp(-(x-x0)**2/(2*sigma**2))

import scipy.optimize as opt

hist_1, bin_edges = np.histogram(hist, bins=150, range=(-0.004,0.004),  density=False)

bin_center = (bin_edges[1:] + bin_edges[:-1])/2
print(len(bin_center), "  |  ", len(bin_edges))

popt, cov = opt.curve_fit(gauss_function, bin_center, hist_1)

print('Mu: {0:.10f}'.format(popt[1]))
print('Sigma: {0:.10f}'.format(popt[2]))
plt.plot(bin_center, gauss_function(bin_center, *popt))
plt.hist(hist, bins=150, range=(-0.004,0.004), density = False)
plt.show()
#hist, _ = melp.taft.get_cosmic_data_from_file('/run/media/maximilian/Volume/mu3e_sorted_000002_cosmic.root', mu3e_detector, 1, **options_cal)
#hist, _ = melp.taft.get_cosmic_data_from_file('/home/maximilian/mu3e_run_000779_cosmic_sorted.root', mu3e_detector, 1, **options_cal)
#import matplotlib.pyplot as plt
#plt.hist(hist, bins=200, range=(-1,1))
#plt.show()
#plt.hist(hist, bins=200, range=(-1,1))
#plt.show()
result = 0
for i in range(1,52):
    result += (53-i)
print(result)
#popt = (-0.0424028  , 0.00848795 , 0.012342   , 0.01152916)
popt = (-0.11725448 ,-1.15888243 , 0.11309043 , 0.13314496, -1.85933635 , 0.15629317,
  0.50977926 ,-0.04436698)
melp.taft.plot_correction_function(melp.taft.corrections.calibration_correction_z, popt, popt)
melp.taft.plot_calibration_Abs(mu3e_detector)
mu3e_detector.TileDetector.row_ids(0,200000)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14772409941357162, 'fraction_numerical': 0.05640882435074002, 'mean_word_length': 5.2449869224062775, 'pattern_counts': {'":': 15, '<': 36, '<?xml version=': 0, '>': 38, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '634237', 'license': 'MIT', 'n_tokens_mistral': 3252, 'n_tokens_neox': 2969, 'n_words': 427, 'path': 'jupyter-notbooks/taft_v2-global_correction_z-Copy1.ipynb', 'repo_name': 'maximilianKoeper/melp', 'size': '7162'}