Q3D-Calibration/calibration.py

101 lines
2.8 KiB
Python

import csv
import numpy as np
from qdx import Bind
from qdx.utils import readBlockData, get_hist
from tqdm import tqdm
from matplotlib import pyplot as plt
# Initialization
n, m = 5, 8
bias = 12.97
deltaE = 4
binds = [[Bind(i, j) for j in range(m)] for i in range(n)]
# Read Data
file_list = csv.reader(open("./config1.csv", "r"))
pbar = tqdm(desc="Read Data E1", total=len(open("./config1.csv", "r").readlines()))
for row in file_list:
pn = int(row[1])
ldata, rdata = readBlockData(row[0], pn, m)
for i in range(m):
bind = binds[pn][i]
bind.add_data(0, ldata[i], rdata[i], 585 - float(row[2]))
pbar.update(1)
pbar.close()
file_list = csv.reader(open("./config2.csv", "r"))
pbar = tqdm(desc="Read Data E2", total=len(open("./config2.csv", "r").readlines()))
for row in file_list:
pn = int(row[1])
ldata, rdata = readBlockData(row[0], pn, m)
for i in range(m):
bind = binds[pn][i]
bind.add_data(1, ldata[i], rdata[i], 585 - float(row[2]))
pbar.update(1)
pbar.close()
# Data preprocessing
pbar = tqdm(desc="Bind Process", total=n * m)
for i in range(n):
for j in range(m):
bind: Bind = binds[i][j]
bind.slash()
bind.get_line()
bind.get_kb(bias, deltaE)
bind.draw_fit_line("result/FIT-LINE/" + bind.name + ".png")
bind.draw_cluster("result/GMM/" + bind.name + ".png")
bind.draw_peak("result/PEAK/" + bind.name + ".png")
pbar.update(1)
pbar.close()
# Fit
pbar = tqdm(desc="Bind Fit", total=n * m)
for i in range(n):
for j in range(m):
bind: Bind = binds[i][j]
bind.get_peak_center()
bind.fit_px()
pbar.update(1)
pbar.close()
# Draw check figure
pbar = tqdm(desc="Figure Check", total=n * m)
fig = plt.figure(figsize=(16, 10), dpi=200)
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)
peaks = np.array([])
for i in range(n):
for j in range(m):
bind = binds[i][j]
peaks = np.hstack((np.unique(bind.px[0]), peaks))
eng = bind.predict_energy(bind.x[0], bind.y[0])
pX = bind.predict_px(bind.x[0], bind.y[0])
count, center = get_hist(pX, delta=0.5)
ax1.scatter(pX, eng, s=0.1, color="k")
ax2.scatter(center, count + 2500 * (7 - j), s=0.5, color="k")
pbar.update(1)
peaks = np.unique(peaks)
for x in peaks:
ax2.vlines(x, 0, 20000, color="gray", linestyles="dashed")
for j in range(m):
ax2.hlines(2500 * j, -50, 600, color="r", linestyles="dashdot")
fig.savefig("./result/Check.png", facecolor="w", transparent=False)
plt.close()
pbar.close()
# Save coefficient to file
f = open("./coef.csv", "w")
for i in range(n):
for j in range(m):
bind = binds[i][j]
f.writelines(
"{:d},{:d},{:.9f},{:.9f},{:.9f},{:.9f},{:.9f}\n".format(
i, j, bind.k1, bind.k2, bind.b, bind.L, bind.C
)
)