diff --git a/pxiii_bec/macros/calibrate_bpm.py b/pxiii_bec/macros/calibrate_bpm.py new file mode 100644 index 0000000..7fe89dd --- /dev/null +++ b/pxiii_bec/macros/calibrate_bpm.py @@ -0,0 +1,553 @@ +""" +BPM calibration. +""" + +import time +from datetime import datetime +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt + +from pxiii_bec.scripts import beamline_context as bl +# from pxiii_bec.macros.beamline_planner import BeamlineState +def bpm_errors(ch1, ch2, ch3, ch4): + total = ch1 + ch2 + ch3 + ch4 + + if total <= 0: + raise ValueError("BPM total intensity is zero or negative") + + x_error = ((ch1 - ch3) + (ch2 - ch4)) / total + y_error = ((ch1 - ch2) + (ch3 - ch4)) / total + + return x_error, y_error + + +def find_bpm_centre(positions, errors): + """Fit the BPM difference signal and return its zero crossing.""" + + slope, intercept = np.polyfit(positions, errors, 1) + + if abs(slope) < 1e-6: + raise ValueError("BPM signal is too flat to determine centre") + + centre = -intercept / slope + + return centre, slope, intercept + + +def centre_bcu_bpm_x(): + positions = [] + errors = [] + startx = dev.bcu_bpm_x.position + starty = dev.bcu_bpm_y.position + scanpoints_x = np.linspace(startx - 0.15, startx + 0.15, 20) + for x in scanpoints_x: + umv(dev.bcu_bpm_x, x) + ch1 = get_value(dev.bcu_bpm1) + ch2 = get_value(dev.bcu_bpm2) + ch3 = get_value(dev.bcu_bpm3) + ch4 = get_value(dev.bcu_bpm4) + + x_error, _ = bpm_errors(ch1, ch2, ch3, ch4) + + print(f"BPM_X = {float(x)}, Xerror = {x_error}") + + positions.append(x) + errors.append(x_error) + + centre, slope, intercept = find_bpm_centre(positions, errors) + print(f"BPM centre in X is at {centre} mm") + umv(dev.bcu_bpm_x, centre) + return centre + + +def centre_bcu_bpm_y(): + positions = [] + errors = [] + starty = dev.bcu_bpm_y.position + scanpoints_y = np.linspace(starty - 0.15, starty + 0.15, 20) + for y in scanpoints_y: + umv(dev.bcu_bpm_y, y) + ch1 = get_value(dev.bcu_bpm1) + ch2 = get_value(dev.bcu_bpm2) + ch3 = get_value(dev.bcu_bpm3) + ch4 = get_value(dev.bcu_bpm4) + _, y_error = bpm_errors(ch1, ch2, ch3, ch4) + + print(f"BPM_Y = {float(y)}, Yerror = {y_error}") + + positions.append(y) + errors.append(y_error) + + centre, slope, intercept = find_bpm_centre(positions, errors) + print(f"BPM centre in Y is at {centre} mm") + umv(dev.bcu_bpm_y, centre) + return centre + +def centre_ss_bpm_x(): + positions = [] + errors = [] + startx = dev.ss_bpm_x.position + starty = dev.ss_bpm_y.position + scanpoints_x = np.linspace(startx - 0.15, startx + 0.15, 20) + for x in scanpoints_x: + umv(dev.ss_bpm_x, x) + ch1 = get_value(dev.ss_bpm1) + ch2 = get_value(dev.ss_bpm2) + ch3 = get_value(dev.ss_bpm3) + ch4 = get_value(dev.ss_bpm4) + + x_error, _ = bpm_errors(ch1, ch2, ch3, ch4) + + print(f"BPM_X = {float(x)}, Xerror = {x_error}") + + positions.append(x) + errors.append(x_error) + + centre, slope, intercept = find_bpm_centre(positions, errors) + print(f"BPM centre in X is at {centre} mm") + umv(dev.ss_bpm_x, centre) + return centre + + +def centre_ss_bpm_y(): + positions = [] + errors = [] + starty = dev.ss_bpm_y.position + scanpoints_y = np.linspace(starty - 0.15, starty + 0.15, 20) + for y in scanpoints_y: + umv(dev.ss_bpm_y, y) + ch1 = get_value(dev.ss_bpm1) + ch2 = get_value(dev.ss_bpm2) + ch3 = get_value(dev.ss_bpm3) + ch4 = get_value(dev.ss_bpm4) + _, y_error = bpm_errors(ch1, ch2, ch3, ch4) + + print(f"BPM_Y = {float(y)}, Yerror = {y_error}") + + positions.append(y) + errors.append(y_error) + + centre, slope, intercept = find_bpm_centre(positions, errors) + print(f"BPM centre in Y is at {centre} mm") + umv(dev.ss_bpm_y, centre) + return centre + +def compute_norm_ss(n_readings=5): + """Average normalized BPM X/Y from repeated sets of four channels.""" + + xn_values = [] + yn_values = [] + + for _ in range(n_readings): + bpm1 = dev.ss_bpm1.read()["ss_bpm1"]["value"] + bpm2 = dev.ss_bpm2.read()["ss_bpm2"]["value"] + bpm3 = dev.ss_bpm3.read()["ss_bpm3"]["value"] + bpm4 = dev.ss_bpm4.read()["ss_bpm4"]["value"] + + total = bpm1 + bpm2 + bpm3 + bpm4 + + if total == 0: + continue + + xn = ((bpm1 + bpm2) - (bpm3 + bpm4)) / total + yn = ((bpm1 + bpm3) - (bpm2 + bpm4)) / total + + xn_values.append(xn) + yn_values.append(yn) + + time.sleep(0.1) + + return { + "ss_Xnorm": float(np.mean(xn_values)), + "ss_Ynorm": float(np.mean(yn_values)), + } + +def compute_norm_bcu(n_readings=5): + """Average normalized BPM X/Y from repeated sets of four channels.""" + + xn_values = [] + yn_values = [] + + for _ in range(n_readings): + bpm1 = dev.bcu_bpm1.read()["bcu_bpm1"]["value"] + bpm2 = dev.bcu_bpm2.read()["bcu_bpm2"]["value"] + bpm3 = dev.bcu_bpm3.read()["bcu_bpm3"]["value"] + bpm4 = dev.bcu_bpm4.read()["bcu_bpm4"]["value"] + + total = bpm1 + bpm2 + bpm3 + bpm4 + + if total == 0: + continue + + xn = ((bpm1 + bpm2) - (bpm3 + bpm4)) / total + yn = ((bpm1 + bpm3) - (bpm2 + bpm4)) / total + + xn_values.append(xn) + yn_values.append(yn) + + time.sleep(0.1) + + return { + "bcu_Xnorm": float(np.mean(xn_values)), + "bcu_Ynorm": float(np.mean(yn_values)), + } + +def compute_norm_lu(n_readings=5): + """Average normalized BPM X/Y from repeated sets of four channels.""" + + xn_values = [] + yn_values = [] + + for _ in range(n_readings): + bpm1 = dev.lu_bpm1.read()["lu_bpm1"]["value"] + bpm2 = dev.lu_bpm2.read()["lu_bpm2"]["value"] + bpm3 = dev.lu_bpm3.read()["lu_bpm3"]["value"] + bpm4 = dev.lu_bpm4.read()["lu_bpm4"]["value"] + + total = bpm1 + bpm2 + bpm3 + bpm4 + + if total == 0: + continue + + xn = ((bpm1 + bpm2) - (bpm3 + bpm4)) / total + yn = ((bpm1 + bpm3) - (bpm2 + bpm4)) / total + + xn_values.append(xn) + yn_values.append(yn) + + time.sleep(0.1) + + return { + "lu_Xnorm": float(np.mean(xn_values)), + "lu_Ynorm": float(np.mean(yn_values)), + } + + + +def run_calibration_ss(): + """Scan bpm in x and y and record normalised x and y positions""" + centred_x = 2.8625 + centred_y = -1.3874 + now = datetime.now() + fnow = filenow() + print(f"moving bpm to {centred_x}, {centred_y}") + umv(dev.ss_bpm_y, centred_y) + umv(dev.ss_bpm_x, centred_x) + + # # # Calibrate in X + umv(dev.bsf_sl_xsize, 0.3) + umv(dev.bsf_sl_xsize, 0.4) + filename = bl.env.lut_dir / "bpm_calib" / f"ss_bpm_x_{fnow}.csv" + xn_data = [] + x_positions = np.linspace(centred_x - 0.3, centred_x + 0.3, 51) + with open(filename, "w", encoding="utf-8") as f: + f.write(f"Xpos,Xnorm\n") + for x in x_positions: + umv(dev.ss_bpm_x, x) + print(f"Moving BPM X to {x} mm") + time.sleep(0.2) + result = compute_norm_ss() + xn = result["ss_Xnorm"] + xn_data.append(xn) + with open(filename, "a", encoding="utf-8") as f: + f.write(f"{x},{xn}\n") + + # # Calibrate in Y + umv(dev.ss_bpm_x, centred_x) + umv(dev.bsf_sl_xsize, 0.3) + umv(dev.bsf_sl_ysize, 0.4) + filename = bl.env.lut_dir / "bpm_calib" / f"ss_bpm_y_{fnow}.csv" + y_positions = np.linspace(centred_y - 0.04, centred_y + 0.04, 41) + yn_data = [] + with open(filename, "w", encoding="utf-8") as f: + f.write(f"Ypos,Ynorm\n") + for y in y_positions: + umv(dev.ss_bpm_y, y) + print(f"Moving BPM Y to {y} mm") + time.sleep(0.2) + result = compute_norm_ss() + yn = result["ss_Ynorm"] + yn_data.append(yn) + with open(filename, "a", encoding="utf-8") as f: + f.write(f"{y},{yn}\n") + + umv(dev.ss_bpm_x, centred_x) + umv(dev.ss_bpm_y, centred_y) + umv(dev.bsf_sl_ysize, 3.0) + umv(dev.bsf_sl_xsize, 3.0) + +def run_calibration_lu(): + """Scan bpm in x and y and record normalised x and y positions""" + centred_x = 2.1816 + centred_y = 3.0175 + now = datetime.now() + fnow = filenow() + print(f"moving bpm to {centred_x}, {centred_y}") + umv(dev.lu_bpm_y, centred_y) + umv(dev.lu_bpm_x, centred_x) + + # # Calibrate in X + umv(dev.bsf_sl_xsize, 0.3) + umv(dev.bsf_sl_xsize, 0.4) + filename = bl.env.lut_dir / "bpm_calib" / f"lu_bpm_x_{fnow}.csv" + xn_data = [] + x_positions = np.linspace(centred_x - 0.3, centred_x + 0.3, 51) + with open(filename, "w", encoding="utf-8") as f: + f.write(f"Xpos,Xnorm\n") + for x in x_positions: + umv(dev.lu_bpm_x, x) + print(f"Moving BPM X to {x} mm") + time.sleep(0.2) + result = compute_norm_lu() + xn = result["lu_Xnorm"] + xn_data.append(xn) + with open(filename, "a", encoding="utf-8") as f: + f.write(f"{x},{xn}\n") + + # # Calibrate in Y + umv(dev.lu_bpm_x, centred_x) + umv(dev.bsf_sl_xsize, 0.3) + umv(dev.bsf_sl_ysize, 0.4) + filename = bl.env.lut_dir / "bpm_calib" / f"lu_bpm_y_{fnow}.csv" + y_positions = np.linspace(centred_y - 0.04, centred_y + 0.04, 41) + yn_data = [] + with open(filename, "w", encoding="utf-8") as f: + f.write(f"Ypos,Ynorm\n") + for y in y_positions: + umv(dev.lu_bpm_y, y) + print(f"Moving BPM Y to {y} mm") + time.sleep(0.2) + result = compute_norm_lu() + yn = result["lu_Ynorm"] + yn_data.append(yn) + with open(filename, "a", encoding="utf-8") as f: + f.write(f"{y},{yn}\n") + + umv(dev.lu_bpm_x, centred_x) + umv(dev.lu_bpm_y, centred_y) + umv(dev.bsf_sl_ysize, 3.0) + umv(dev.bsf_sl_xsize, 3.0) + + +def run_calibration(env): + """Scan bpm in x and y and record normalised x and y positions""" + centred_x = 0.444 + centred_y = -1.5404 + now = datetime.now() + fnow = filenow() + print(f"moving bpm to {centred_x}, {centred_y}") + umv(dev.bcu_bpm_y, centred_y) + umv(dev.bcu_bpm_x, centred_x) + + # # Calibrate in X + umv(dev.ss_sl_xsize, 0.02) + umv(dev.ss_sl_xsize, 3.0) + filename = env.lut_dir / "bpm_calib" / f"bcu_bpm_x_{fnow}.csv" + xn_data = [] + x_positions = np.linspace(centred_x - 0.4, centred_x + 0.4, 101) + with open(filename, "w", encoding="utf-8") as f: + f.write(f"Xpos,Xnorm\n") + for x in x_positions: + umv(dev.bcu_bpm_x, x) + print(f"Moving BPM X to {x} mm") + time.sleep(0.2) + xn, yn = compute_norm() + xn_data.append(xn) + with open(filename, "a", encoding="utf-8") as f: + f.write(f"{x},{xn}\n") + + # # Calibrate in Y + umv(dev.bcu_bpm_x, centred_x) + umv(dev.ss_sl_xsize, 3.0) + umv(dev.ss_sl_ysize, 0.03) + filename = env.lut_dir / "bpm_calib" / f"bcu_bpm_y_{fnow}.csv" + y_positions = np.linspace(centred_y - 0.05, centred_y + 0.05, 101) + yn_data = [] + with open(filename, "w", encoding="utf-8") as f: + f.write(f"Ypos,Ynorm\n") + for y in y_positions: + umv(dev.bcu_bpm_y, y) + print(f"Moving BPM Y to {y} mm") + time.sleep(0.2) + xn, yn = compute_norm() + yn_data.append(yn) + with open(filename, "a", encoding="utf-8") as f: + f.write(f"{y},{yn}\n") + + umv(dev.bcu_bpm_x, centred_x) + umv(dev.bcu_bpm_y, centred_y) + umv(dev.ss_sl_ysize, 3.0) + + +def read_bpm_calibration_data(env, x_y, rundate, bpm_name="bcu_bpm"): + """Read BPM calibration data from CSV.""" + + filename = env.lut_dir / f"bpm_calib/{bpm_name}_{x_y}_{rundate}.csv" + + data = np.loadtxt(filename, delimiter=",", skiprows=1) + + position = data[:, 0] + bpm_norm = data[:, 1] + + return position, bpm_norm + + +# def fit_bpm_linear(env, filename, x_y, plot=True): +# """ +# Fit the linear region of a BPM calibration scan. + +# The fit is: + +# normalised_signal = slope * bpm_motor_position + intercept +# """ + +# file = env.lut_dir / "bpm_calib" / filename + +# bpm_centre = { +# "x": 0.441, +# "y": -1.5405, +# } + +# linear_limit = { +# "x": 0.59, +# "y": 0.5, +# } +# data = pd.read_csv(file) + +# if x_y == "x": +# pos = data["Xpos"].to_numpy() +# signal = data["Xnorm"].to_numpy() +# elif x_y == "y": +# pos = data["Ypos"].to_numpy() +# signal = data["Ynorm"].to_numpy() +# else: +# raise ValueError("x_y must be 'x' or 'y'") + +# limit = linear_limit[x_y] + +# mask = np.abs(signal) < limit + +# pos_fit = pos[mask] +# signal_fit = signal[mask] + +# slope, intercept = np.polyfit(pos_fit, signal_fit, 1) + +# fitted = slope * pos_fit + intercept + +# ss_res = np.sum((signal_fit - fitted) ** 2) +# ss_tot = np.sum((signal_fit - np.mean(signal_fit)) ** 2) + +# r_squared = 1 - ss_res / ss_tot + +# zero_position = -intercept / slope + +# result = { +# "axis": x_y, +# "slope": float(slope), +# "intercept": float(intercept), +# "linear_limit": limit, +# "r_squared": float(r_squared), +# "zero_position": float(zero_position), +# "centred_bpm_position": bpm_centre[x_y], +# } +# print(result) +# print(f"class BPM_{x_y.upper()}_Calibration:") +# print(f" slope = {slope:.6f}") +# print(f" intercept = {intercept:.6f}") +# print(f" linear_limit = {limit:.2f}") +# print(f" centred_position = {bpm_centre[x_y]:.3f}") +# print(f" crosshair_signal = None") +# print(f" crosshair_bpm_position = None") + +# if plot: +# xline = np.linspace(pos_fit.min(), pos_fit.max(), 200) + +# plt.figure(figsize=(7, 5)) +# plt.scatter(pos, signal, alpha=0.4, label="all data") +# plt.scatter(pos_fit, signal_fit, label="linear region") +# plt.plot( +# xline, +# slope * xline + intercept, +# label="linear fit", +# ) + +# plt.axvline( +# bpm_centre[x_y], +# linestyle="--", +# label="centred BPM position", +# ) + +# plt.xlabel(f"BPM {x_y} position (mm)") +# plt.ylabel(f"BPM {x_y} normalised signal") +# plt.title(f"BPM {x_y.upper()} calibration") +# plt.grid(True) +# plt.legend() +# plt.tight_layout() +# plt.show() + +# return result + + +def polynomial_calibration( + env, x_y, rundate, bpm_name="bcu_bpm", degree=5, signal_limit=0.9, plot=True +): + + # BPM centre during calibration run + bpm_centre = {"x": 0.441, "y": -1.5405} + + xdata, ydata = read_bpm_calibration_data(env, x_y, rundate=rundate, bpm_name=bpm_name) + + # Keep useful BPM range + mask = np.abs(ydata) < signal_limit + + position = xdata[mask] + signal = ydata[mask] + + # Fit position as a function of BPM signal + coeffs = np.polyfit(signal, position, degree) + + fitted_position = np.polyval(coeffs, signal) + + residual_um = (position - fitted_position) * 1000 + + rms_error_um = np.sqrt(np.mean(residual_um**2)) + max_error_um = np.max(np.abs(residual_um)) + + ss_res = np.sum((position - fitted_position) ** 2) + ss_tot = np.sum((position - np.mean(position)) ** 2) + r_squared = 1 - ss_res / ss_tot + + print(f"{x_y.upper()} calibration") + print(f"Polynomial degree: {degree}") + print(f"Signal range: ±{signal_limit}") + print(f"R²: {r_squared:.6f}") + print(f"RMS error: {rms_error_um:.2f} µm") + print(f"Max error: {max_error_um:.2f} µm") + print(f"Coefficients: {coeffs}") + + print(f"class BPM_{x_y.upper()}_Calibration:") + print(f" coeffs = {coeffs}") + print(f" signal_limit = {signal_limit:.2f}") + print(f" centred_position = {bpm_centre[x_y]:.3f}") + print(f" crosshair_signal = None") + print(f" crosshair_bpm_position = None") + + if plot: + signal_fit = np.linspace(signal.min(), signal.max(), 500) + + position_fit = np.polyval(coeffs, signal_fit) + + plt.figure(figsize=(7, 5)) + plt.scatter(ydata, xdata, alpha=0.4, label="Calibration data") + plt.plot(signal_fit, position_fit, label=f"{degree}th-order polynomial") + + plt.xlabel(f"BPM {x_y} normalized signal") + plt.ylabel(f"BPM {x_y} position (mm)") + plt.title(f"BPM {x_y.upper()} calibration") + plt.grid(True) + plt.legend() + plt.tight_layout() + plt.show() + + return coeffs