chore: cleanup junk and backup files
This commit was merged in pull request #23.
This commit is contained in:
1 parent
e33538b5ea
commit
b77ba7b73e
5 files changed
-1639
No files matched your search
Binary file not shown.
@@ -1,144 +0,0 @@
|
||||
"""Initialise sample environment devices and beamline states"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
# from devices_manager import DeviceManager
|
||||
# from beamline_state_manager import DefineStatesManager
|
||||
# from dependencies import planner_deps
|
||||
# from beamline_planner import StateChangePlanner
|
||||
|
||||
|
||||
@dataclass
|
||||
class Environment:
|
||||
"""Define the device and state yaml files for each beamline"""
|
||||
|
||||
device_mocks: dict[str, bool] = None
|
||||
beamline: str = None
|
||||
|
||||
beamline_configs = {
|
||||
# "x06sa" : {
|
||||
# "devdir": "/sls/x10sa/config/bec/production/pxi_bec/pxi_bec/device_configs/",
|
||||
# "state": "pxi-state-devices.yaml",
|
||||
# "rest": "pxi-rest-devices.yaml",
|
||||
# "states": "pxi-beamline-states.yaml",
|
||||
# },
|
||||
"x10sa": {
|
||||
"devdir": "/sls/x10sa/config/bec/production/pxii_bec/pxii_bec/device_configs/",
|
||||
"devices": "pxii-devices.yaml",
|
||||
"states": "pxii-beamline-states.yaml",
|
||||
},
|
||||
"x06da": {
|
||||
"devdir": "/sls/x06da/config/bec/production/pxiii_bec/pxiii_bec/device_configs/",
|
||||
"state": "pxiii-devices.yaml",
|
||||
"states": "pxiii-beamline-states.yaml",
|
||||
},
|
||||
}
|
||||
|
||||
def __post_init__(self):
|
||||
|
||||
if self.device_mocks is None:
|
||||
self.device_mocks = {
|
||||
"aerotech_x": "real",
|
||||
"aerotech_y": "real",
|
||||
"aerotech_z": "real",
|
||||
"aerotech_u": "real",
|
||||
"bl_bright": "real",
|
||||
"bl_pos": "real",
|
||||
"bs_pos": "real",
|
||||
"bs_z": "real",
|
||||
"coll_y": "real",
|
||||
"cryo_pos": "real",
|
||||
"det_cov": "real",
|
||||
"diag_y": "real",
|
||||
"fl_bright": "real",
|
||||
"smargon_x": "real",
|
||||
"smargon_y": "real",
|
||||
"smargon_z": "real",
|
||||
"smargon_chi": "real",
|
||||
"smargon_phi": "real",
|
||||
"xrf_pos": "mock",
|
||||
}
|
||||
|
||||
mocks = sorted(name for name, backend in self.device_mocks.items() if backend == "mock")
|
||||
|
||||
reals = sorted(name for name, backend in self.device_mocks.items() if backend == "real")
|
||||
|
||||
# print(f"Mock devices ({len(mocks)}): {mocks}")
|
||||
# print(f"Real devices ({len(reals)}): {reals}")
|
||||
|
||||
try:
|
||||
cfg = self.beamline_configs[self.beamline]
|
||||
except KeyError:
|
||||
raise ValueError(f"Unknown beamline '{self.beamline}'")
|
||||
|
||||
devdir = cfg["devdir"]
|
||||
|
||||
self.devices_file = devdir + cfg["devices"]
|
||||
self.states_file = devdir + cfg["states"]
|
||||
|
||||
mock_start_positions = {
|
||||
"aerotech_x": "in",
|
||||
"aerotech_y": "mount",
|
||||
"aerotech_z": "mount",
|
||||
"aerotech_u": "mount",
|
||||
"bl_bright": "off",
|
||||
"bl_pos": "out",
|
||||
"bs_pos": "in",
|
||||
"bs_z": "safe",
|
||||
"coll_y": "park",
|
||||
"cryo_pos": "in",
|
||||
"det_cov": "close",
|
||||
"diag_y": "park",
|
||||
"fl_bright": "off",
|
||||
"smargon_x": "mount",
|
||||
"smargon_y": "mount",
|
||||
"smargon_z": "mount",
|
||||
"smargon_chi": "mount",
|
||||
"smargon_phi": "mount",
|
||||
"xrf_pos": "out",
|
||||
}
|
||||
|
||||
@property
|
||||
def mock_devices(self):
|
||||
mock_names = set()
|
||||
for name, device in self.device_mocks.items():
|
||||
if device == "mock":
|
||||
mock_names.add(name)
|
||||
return mock_names
|
||||
|
||||
|
||||
def init_beamline_environment():
|
||||
"""
|
||||
Initializes the beamline with real or mock devices.
|
||||
"""
|
||||
|
||||
beamline = os.environ["BEAMLINE"]
|
||||
|
||||
env = Environment(beamline=beamline)
|
||||
|
||||
# Initialize devices
|
||||
device_manager = DeviceManager()
|
||||
devices = device_manager.initialize_devices(env.devices_file, env.mock_devices)
|
||||
|
||||
# Initialize states
|
||||
state_manager = DefineStatesManager()
|
||||
states, allow_modifiers = state_manager.initialize_states(env.states_file)
|
||||
|
||||
# Setup dependencies
|
||||
deps = planner_deps()
|
||||
|
||||
# Setup planner
|
||||
planner = StateChangePlanner(devices, states, allow_modifiers, deps)
|
||||
print("Initializing beamline state planner and devices")
|
||||
|
||||
# Set mock motor starting positions
|
||||
|
||||
for mock_dev, pos in env.mock_start_positions.items():
|
||||
if mock_dev in env.mock_devices:
|
||||
try:
|
||||
devices[mock_dev].set_position(pos)
|
||||
except Exception as e:
|
||||
print(f"{e} error when setting {mock_dev}")
|
||||
|
||||
return devices, planner
|
||||
@@ -1,313 +0,0 @@
|
||||
"""Get data from an h5 file or BEC history and perform fitting."""
|
||||
|
||||
import numpy as np
|
||||
from lmfit.models import (
|
||||
GaussianModel,
|
||||
LorentzianModel,
|
||||
VoigtModel,
|
||||
ConstantModel,
|
||||
LinearModel,
|
||||
)
|
||||
from scipy.ndimage import gaussian_filter1d
|
||||
import h5py
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def create_fit_parameters(
|
||||
deriv: bool = False,
|
||||
negative: bool = False,
|
||||
model: str = "Voigt",
|
||||
baseline: str = "Linear",
|
||||
smoothing: None = None,
|
||||
):
|
||||
"""Store the fit parameters in a dictionary."""
|
||||
# map input model to lmfit model name
|
||||
model_mappings = {
|
||||
"Gaussian": GaussianModel,
|
||||
"Lorentzian": LorentzianModel,
|
||||
"Voigt": VoigtModel,
|
||||
"Constant": ConstantModel,
|
||||
"Linear": LinearModel,
|
||||
}
|
||||
return {
|
||||
"deriv": deriv,
|
||||
"negative": negative,
|
||||
"model": model_mappings[model],
|
||||
"baseline": model_mappings[baseline],
|
||||
"smoothing": smoothing,
|
||||
}
|
||||
|
||||
|
||||
def get_data_from_h5(signal_name: str = "lu_bpmsum"):
|
||||
"""Get data from an h5 file."""
|
||||
root, name = get_signal_values(signal_name)
|
||||
with h5py.File("scan_676.h5", "r") as f:
|
||||
entry = f["entry"]["collection"]
|
||||
y_data = entry["devices"][root][name]["value"][:]
|
||||
motor_data = entry["metadata"]["bec"]
|
||||
motor_name = motor_data["scan_motors"][0].decode()
|
||||
scan_number = motor_data["scan_number"][()]
|
||||
x_data = entry["devices"][motor_name][motor_name]["value"][:]
|
||||
return {
|
||||
"x_data": x_data,
|
||||
"y_data": y_data,
|
||||
"signal_name": signal_name,
|
||||
"motor_name": motor_name,
|
||||
"scan_number": str(scan_number),
|
||||
}
|
||||
|
||||
def get_history(scan):
|
||||
if isinstance(scan, int):
|
||||
if scan < 0:
|
||||
return bec.history[scan]
|
||||
return bec.history.get_by_scan_number(scan)
|
||||
# return bec.history.get_by_dataset_number(scan)
|
||||
return scan
|
||||
|
||||
|
||||
def get_signal_values(signal_name):
|
||||
|
||||
try:
|
||||
mot = getattr(dev,signal_name)
|
||||
root_name = signal_name
|
||||
except:
|
||||
root_name = signal_name.split("_", maxsplit=1)[0]
|
||||
|
||||
return root_name, signal_name
|
||||
|
||||
|
||||
def get_data_from_history(
|
||||
scan: int,
|
||||
signal_name: str = "lu_bpmsum",
|
||||
):
|
||||
"""Read data from the BEC history and return the X and Y data as arrays."""
|
||||
|
||||
data = get_history(scan)
|
||||
md = data.metadata["bec"]
|
||||
motor_name = md["scan_report_devices"][0].decode()
|
||||
mot_name = motor_name.replace(".","_")
|
||||
print(data.devices)
|
||||
if "." in motor_name:
|
||||
root_name = motor_name.split(".")[0]
|
||||
x_data = data.devices[root_name][mot_name].read()["value"]
|
||||
else:
|
||||
x_data = data.devices[mot_name][mot_name].read()["value"]
|
||||
|
||||
scan_number = md["scan_number"]
|
||||
|
||||
# y_data = data.devices[signal_name][signal_name].read()["value"]
|
||||
root, name = get_signal_values(signal_name)
|
||||
y_data = data.devices[root][name].read()["value"]
|
||||
return {
|
||||
"signal_name": signal_name,
|
||||
"x_data": x_data,
|
||||
"y_data": y_data,
|
||||
"motor_name": mot_name,
|
||||
"scan_number": float(scan_number),
|
||||
}
|
||||
|
||||
|
||||
def process_data(data, fit_params):
|
||||
"""
|
||||
Process the signal data for fitting based on derivative or smoothing.
|
||||
"""
|
||||
smoothing = fit_params["smoothing"]
|
||||
deriv = fit_params["deriv"]
|
||||
negative = fit_params["negative"]
|
||||
|
||||
signal_name = data["signal_name"]
|
||||
y_data = data["y_data"]
|
||||
|
||||
if smoothing and smoothing > 0.01:
|
||||
fitting_data = gaussian_filter1d(y_data, smoothing)
|
||||
signal_name = f"Smoothed {signal_name}"
|
||||
else:
|
||||
fitting_data = y_data.copy()
|
||||
|
||||
if deriv:
|
||||
fitting_data = np.gradient(fitting_data)
|
||||
signal_name = f"Derivative of {signal_name}"
|
||||
|
||||
if negative:
|
||||
fitting_data = -fitting_data
|
||||
signal_name = f"Negative {signal_name}"
|
||||
|
||||
data.update(
|
||||
{
|
||||
"y_to_fit": fitting_data,
|
||||
"signal_name": signal_name,
|
||||
}
|
||||
)
|
||||
return data
|
||||
|
||||
# if deriv:
|
||||
# if smoothing:
|
||||
# y_smooth = gaussian_filter1d(y_data, smoothing)
|
||||
# fitting_data = np.gradient(y_smooth)
|
||||
# signal_name = f"Derivative of smoothed {signal_name}"
|
||||
# else:
|
||||
# fitting_data = np.gradient(y_data)
|
||||
# signal_name = f"Derivative of {signal_name}"
|
||||
# elif smoothing and smoothing > 0.01:
|
||||
# fitting_data = gaussian_filter1d(y_data, smoothing)
|
||||
# signal_name = f"Smoothed {signal_name}"
|
||||
# else:
|
||||
# fitting_data = y_data
|
||||
|
||||
# updated_data = {
|
||||
# "y_to_fit": fitting_data,
|
||||
# "signal_name": signal_name,
|
||||
# }
|
||||
# data.update(updated_data)
|
||||
# return data
|
||||
|
||||
|
||||
def fit(data, fit_params):
|
||||
"""Fit a signal to a model and return the fitting results."""
|
||||
# Create the model
|
||||
peak_model = fit_params["model"](prefix="peak_")
|
||||
baseline_model = fit_params["baseline"](prefix="base_")
|
||||
full_model = peak_model + baseline_model
|
||||
|
||||
# Prepare data
|
||||
processed_data = process_data(data, fit_params)
|
||||
params = full_model.make_params()
|
||||
y_min = np.min(processed_data["y_to_fit"])
|
||||
|
||||
# Configure baseline parameters
|
||||
if fit_params["baseline"] == ConstantModel:
|
||||
params["base_c"].set(value=y_min)
|
||||
elif fit_params["baseline"] == LinearModel:
|
||||
params["base_intercept"].set(value=y_min)
|
||||
params["base_slope"].set(value=0)
|
||||
|
||||
# Add peak-specific parameters
|
||||
params.update(
|
||||
peak_model.guess(processed_data["y_to_fit"], x=processed_data["x_data"])
|
||||
)
|
||||
|
||||
# Perform the fitting
|
||||
lmfit_result = full_model.fit(
|
||||
processed_data["y_to_fit"], params, x=processed_data["x_data"]
|
||||
)
|
||||
|
||||
# Find the X that gives the max Y
|
||||
max_index = np.argmax(processed_data["y_to_fit"])
|
||||
x_max = processed_data["x_data"][max_index]
|
||||
|
||||
# Generate data for a smoothed fit curve
|
||||
fit_xdata = np.linspace(np.min(data["x_data"]), np.max(data["x_data"]), 500)
|
||||
fit_ydata = lmfit_result.eval(x=fit_xdata, params=lmfit_result.params)
|
||||
|
||||
# Collect results
|
||||
return {
|
||||
"model": fit_params["model"].__name__,
|
||||
"fwhm": lmfit_result.params["peak_fwhm"].value,
|
||||
"centre": lmfit_result.best_values["peak_center"],
|
||||
"height": lmfit_result.params["peak_height"].value,
|
||||
"chi_sq": lmfit_result.chisqr,
|
||||
"lmfit_result": lmfit_result,
|
||||
"x_max": x_max,
|
||||
"fit_xdata": fit_xdata,
|
||||
"fit_ydata": fit_ydata,
|
||||
}
|
||||
|
||||
|
||||
def plot_fitted_data(data, fit_result):
|
||||
"""Plot the original data and the fitted model."""
|
||||
plt.plot(data["x_data"], data["y_to_fit"], label="Data")
|
||||
plt.plot(fit_result['fit_xdata'], fit_result['fit_ydata'], label="Fit")
|
||||
plt.xlabel(data["motor_name"])
|
||||
plt.ylabel(data["signal_name"])
|
||||
plt.title(f"Scan {data['scan_number']}, fitted with {fit_result['model']}")
|
||||
plt.grid(True)
|
||||
plt.legend()
|
||||
plt.show()
|
||||
|
||||
|
||||
def select_bec_window(dock_area_name="Fitting"):
|
||||
"""Check to see if the fitting results dock is already open and re-create it if not"""
|
||||
open_docks = bec.gui.windows
|
||||
if open_docks.get(dock_area_name) is None:
|
||||
dock_area = bec.gui.new(dock_area_name)
|
||||
# wf = dock_area.new("Plot").new(bec.gui.available_widgets.Waveform)
|
||||
wf = dock_area.new(widget='Waveform', object_name='Plot')
|
||||
text_box = dock_area.new(widget='TextBox', object_name="Results", where="bottom")
|
||||
else:
|
||||
wf = bec.gui.Fitting.Plot
|
||||
text_box = bec.gui.Fitting.Results
|
||||
return wf, text_box
|
||||
|
||||
|
||||
def plot_live_data_bec(
|
||||
motor_name,
|
||||
signal_name,
|
||||
window_name="Fitting"
|
||||
):
|
||||
"""
|
||||
Plotting live data for motor and signal using BEC.
|
||||
|
||||
This function plots live data from a specified motor and signal.
|
||||
It clears the current plot window, sets its title, labels the axes
|
||||
with the provided motor and signal names, and initializes live plotting
|
||||
on the given signal against the motor.
|
||||
|
||||
Args:
|
||||
motor_name (str): The name of the motor to be used as the x-axis.
|
||||
signal_name (str): The name of the signal to be used as the y-axis.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
root, name = get_signal_values(signal_name)
|
||||
wf, text_box = select_bec_window(window_name)
|
||||
text_box.set_plain_text("Plotting live data")
|
||||
wf.clear_all()
|
||||
wf.title = "Scan: Live scan"
|
||||
wf.x_label = motor_name
|
||||
wf.y_label = signal_name
|
||||
wf.plot(device_x=motor_name, device_y=root)
|
||||
|
||||
|
||||
|
||||
|
||||
def plot_fitted_data_bec(
|
||||
data,
|
||||
fit_result,
|
||||
):
|
||||
"""
|
||||
Plot fitted data and display fitting parameters in the specified window.
|
||||
|
||||
This function selects a BEC window and plots the original data along with the
|
||||
fitted function. Additionally, it displays the fitting results in a text
|
||||
box within the same window for better visualization of the fit results.
|
||||
|
||||
Parameters:
|
||||
data : dict
|
||||
Dictionary containing the original dataset, where 'x_data' and 'y_to_fit'
|
||||
hold the independent variable and the dependent variable, respectively,
|
||||
'scan_number' represents the scan number, 'motor_name' and 'signal_name'
|
||||
provide axis labels.
|
||||
fit_result : dict
|
||||
Dictionary containing the results of the fit, including parameters such
|
||||
as 'centre', 'fwhm', 'height', and the fitted model stored under
|
||||
'lmfit_result', with its 'best_fit' attribute representing the fitted data.
|
||||
"""
|
||||
wf, text_box = select_bec_window()
|
||||
fit_text = (
|
||||
f"Fit parameters: Centre = {fit_result['centre']:.5g}, "
|
||||
f"FWHM = {fit_result['fwhm']:.5f}, "
|
||||
f"Height = {fit_result['height']:.4g}\n"
|
||||
f"Model = {fit_result['model']}\n"
|
||||
f"Chi sq = {fit_result['chi_sq']:.3g}"
|
||||
)
|
||||
text_box.set_plain_text(fit_text)
|
||||
wf.clear_all()
|
||||
wf.title = f"Scan: {data['scan_number']}"
|
||||
wf.x_label = data["motor_name"]
|
||||
wf.y_label = data["signal_name"]
|
||||
wf.plot(x=data["x_data"], y=data["y_to_fit"], label="Data")
|
||||
wf.plot(x=fit_result["fit_xdata"], y=fit_result["fit_ydata"], label="Fit")
|
||||
# wf.Fit.set(symbol_size = 0)
|
||||
wf.get_curve('Fit').set(symbol_size=0)
|
||||
|
||||
@@ -1,516 +0,0 @@
|
||||
"""Get data from an h5 file or BEC history and perform fitting."""
|
||||
import re
|
||||
import numpy as np
|
||||
from lmfit.models import (
|
||||
GaussianModel,
|
||||
LorentzianModel,
|
||||
VoigtModel,
|
||||
ConstantModel,
|
||||
LinearModel,
|
||||
)
|
||||
from scipy.ndimage import gaussian_filter1d
|
||||
import h5py
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def create_fit_parameters(
|
||||
deriv: bool = False,
|
||||
negative: bool = False,
|
||||
model: str = "Voigt",
|
||||
baseline: str = "Linear",
|
||||
smoothing: None = None,
|
||||
):
|
||||
"""Store the fit parameters in a dictionary."""
|
||||
# map input model to lmfit model name
|
||||
model_mappings = {
|
||||
"Gaussian": GaussianModel,
|
||||
"Lorentzian": LorentzianModel,
|
||||
"Voigt": VoigtModel,
|
||||
"Constant": ConstantModel,
|
||||
"Linear": LinearModel,
|
||||
}
|
||||
return {
|
||||
"deriv": deriv,
|
||||
"negative": negative,
|
||||
"model": model_mappings[model],
|
||||
"baseline": model_mappings[baseline],
|
||||
"smoothing": smoothing,
|
||||
}
|
||||
|
||||
|
||||
# def get_data_from_h5(signal_name: str = "lu_bpmsum"):
|
||||
# """Get data from an h5 file."""
|
||||
# root, name = get_signal_values(signal_name)
|
||||
# with h5py.File("scan_676.h5", "r") as f:
|
||||
# entry = f["entry"]["collection"]
|
||||
# y_data = entry["devices"][root][name]["value"][:]
|
||||
# motor_data = entry["metadata"]["bec"]
|
||||
# motor_name = motor_data["scan_motors"][0].decode()
|
||||
# scan_number = motor_data["scan_number"][()]
|
||||
# x_data = entry["devices"][motor_name][motor_name]["value"][:]
|
||||
# return {
|
||||
# "x_data": x_data,
|
||||
# "y_data": y_data,
|
||||
# "signal_name": signal_name,
|
||||
# "motor_name": motor_name,
|
||||
# "scan_number": str(scan_number),
|
||||
# }
|
||||
|
||||
def get_history(scan):
|
||||
if isinstance(scan, int):
|
||||
if scan < 0:
|
||||
return bec.history[scan]
|
||||
return bec.history.get_by_scan_number(scan)
|
||||
# return bec.history.get_by_dataset_number(scan)
|
||||
return scan
|
||||
|
||||
|
||||
def get_value(dev_name, all=False):
|
||||
if dev_name == dev.scam:
|
||||
root = 'scam'
|
||||
live_root = 'scam'
|
||||
name = 'scam_contrast'
|
||||
value = dev_name.read()[name]['value']
|
||||
else:
|
||||
try:
|
||||
name = live_root = root = dev_name.name
|
||||
value = dev_name.read()[name]['value']
|
||||
except:
|
||||
print("non-standard device")
|
||||
root = dev_name.dotted_name
|
||||
name = dev_name.full_name
|
||||
live_root = dev_name.parent.name
|
||||
value = dev_name.read()[name]['value']
|
||||
|
||||
|
||||
if all:
|
||||
return {"value": value, "root": root, "name": name, "live_root": live_root}
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def get_data_from_history(
|
||||
scan: int,
|
||||
signal_dev,
|
||||
):
|
||||
"""Read data from the BEC history and return the X and Y data as arrays."""
|
||||
|
||||
data = get_history(scan)
|
||||
md = data.metadata["bec"]
|
||||
motor_name = md["scan_report_devices"][0].decode()
|
||||
if '.' in motor_name:
|
||||
root = motor_name.split(".")[0]
|
||||
name = motor_name.replace(".","_")
|
||||
else:
|
||||
root = motor_name
|
||||
name = motor_name
|
||||
|
||||
|
||||
x_data = data.devices[root][name].read()["value"]
|
||||
y_res = get_value(signal_dev, True)
|
||||
y_data = data.devices[y_res['root']][y_res['name']].read()["value"]
|
||||
signal_name = y_res['name']
|
||||
|
||||
scan_number = md["scan_number"]
|
||||
|
||||
return {
|
||||
"signal_name": signal_name,
|
||||
"x_data": x_data,
|
||||
"y_data": y_data,
|
||||
"motor_name": motor_name,
|
||||
"scan_number": float(scan_number),
|
||||
}
|
||||
|
||||
|
||||
def process_data(data, fit_params):
|
||||
"""
|
||||
Process the signal data for fitting based on derivative or smoothing.
|
||||
"""
|
||||
smoothing = fit_params["smoothing"]
|
||||
deriv = fit_params["deriv"]
|
||||
negative = fit_params["negative"]
|
||||
|
||||
signal_name = data["signal_name"]
|
||||
y_data = data["y_data"]
|
||||
|
||||
if smoothing and smoothing > 0.01:
|
||||
fitting_data = gaussian_filter1d(y_data, smoothing)
|
||||
signal_name = f"Smoothed {signal_name}"
|
||||
else:
|
||||
fitting_data = y_data.copy()
|
||||
|
||||
if deriv:
|
||||
fitting_data = np.gradient(fitting_data)
|
||||
signal_name = f"Derivative of {signal_name}"
|
||||
|
||||
if negative:
|
||||
fitting_data = -fitting_data
|
||||
signal_name = f"Negative {signal_name}"
|
||||
|
||||
data.update(
|
||||
{
|
||||
"y_to_fit": fitting_data,
|
||||
"signal_name": signal_name,
|
||||
}
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
def fit(data, fit_params):
|
||||
"""Fit a signal to a model and return the fitting results."""
|
||||
# Create the model
|
||||
peak_model = fit_params["model"](prefix="peak_")
|
||||
baseline_model = fit_params["baseline"](prefix="base_")
|
||||
full_model = peak_model + baseline_model
|
||||
|
||||
# Prepare data
|
||||
processed_data = process_data(data, fit_params)
|
||||
params = full_model.make_params()
|
||||
y_min = np.min(processed_data["y_to_fit"])
|
||||
|
||||
# Configure baseline parameters
|
||||
if fit_params["baseline"] == ConstantModel:
|
||||
params["base_c"].set(value=y_min)
|
||||
elif fit_params["baseline"] == LinearModel:
|
||||
params["base_intercept"].set(value=y_min)
|
||||
params["base_slope"].set(value=0)
|
||||
|
||||
# Add peak-specific parameters
|
||||
params.update(
|
||||
peak_model.guess(processed_data["y_to_fit"], x=processed_data["x_data"])
|
||||
)
|
||||
|
||||
# Perform the fitting
|
||||
lmfit_result = full_model.fit(
|
||||
processed_data["y_to_fit"], params, x=processed_data["x_data"]
|
||||
)
|
||||
|
||||
# Find the X that gives the max Y
|
||||
max_index = np.argmax(processed_data["y_to_fit"])
|
||||
x_max = processed_data["x_data"][max_index]
|
||||
|
||||
# Generate data for a smoothed fit curve
|
||||
fit_xdata = np.linspace(np.min(data["x_data"]), np.max(data["x_data"]), 500)
|
||||
fit_ydata = lmfit_result.eval(x=fit_xdata, params=lmfit_result.params)
|
||||
|
||||
def fit(data, fit_params):
|
||||
"""Fit a signal to a model and return the fitting results."""
|
||||
# Create the model
|
||||
peak_model = fit_params["model"](prefix="peak_")
|
||||
baseline_model = fit_params["baseline"](prefix="base_")
|
||||
full_model = peak_model + baseline_model
|
||||
|
||||
# Prepare data
|
||||
processed_data = process_data(data, fit_params)
|
||||
params = full_model.make_params()
|
||||
y_min = np.min(processed_data["y_to_fit"])
|
||||
|
||||
# Configure baseline parameters
|
||||
if fit_params["baseline"] == ConstantModel:
|
||||
params["base_c"].set(value=y_min)
|
||||
elif fit_params["baseline"] == LinearModel:
|
||||
params["base_intercept"].set(value=y_min)
|
||||
params["base_slope"].set(value=0)
|
||||
|
||||
# Add peak-specific parameters
|
||||
params.update(
|
||||
peak_model.guess(processed_data["y_to_fit"], x=processed_data["x_data"])
|
||||
)
|
||||
|
||||
# Perform the fitting
|
||||
lmfit_result = full_model.fit(
|
||||
processed_data["y_to_fit"], params, x=processed_data["x_data"]
|
||||
)
|
||||
|
||||
# Find the X that gives the max Y
|
||||
max_index = np.argmax(processed_data["y_to_fit"])
|
||||
x_max = processed_data["x_data"][max_index]
|
||||
|
||||
# Generate data for a smoothed fit curve
|
||||
fit_xdata = np.linspace(np.min(data["x_data"]), np.max(data["x_data"]), 500)
|
||||
fit_ydata = lmfit_result.eval(x=fit_xdata, params=lmfit_result.params)
|
||||
|
||||
# Fit diagnostics
|
||||
residuals = lmfit_result.residual
|
||||
noise = np.std(residuals)
|
||||
|
||||
height = lmfit_result.params["peak_height"].value
|
||||
centre = lmfit_result.best_values["peak_center"]
|
||||
fwhm = lmfit_result.params["peak_fwhm"].value
|
||||
|
||||
centre_stderr = lmfit_result.params["peak_center"].stderr
|
||||
height_stderr = lmfit_result.params["peak_height"].stderr
|
||||
|
||||
snr = height / noise if noise > 0 else np.inf
|
||||
|
||||
|
||||
# Collect results
|
||||
return {
|
||||
"model": fit_params["model"].__name__,
|
||||
"fwhm": fwhm,
|
||||
"centre": centre,
|
||||
"height": height,
|
||||
|
||||
# Fit quality
|
||||
"chi_sq": lmfit_result.chisqr,
|
||||
"redchi": lmfit_result.redchi,
|
||||
"aic": lmfit_result.aic,
|
||||
"bic": lmfit_result.bic,
|
||||
"noise": noise,
|
||||
"snr": snr,
|
||||
"centre_stderr": centre_stderr,
|
||||
"height_stderr": height_stderr,
|
||||
|
||||
# Existing information
|
||||
"lmfit_result": lmfit_result,
|
||||
"x_max": x_max,
|
||||
"fit_xdata": fit_xdata,
|
||||
"fit_ydata": fit_ydata,
|
||||
}
|
||||
|
||||
def check_peak_fit(x_data, result):
|
||||
"""Check whether a fitted peak is reliable."""
|
||||
|
||||
x_data = np.asarray(x_data)
|
||||
|
||||
x_min = np.min(x_data)
|
||||
x_max = np.max(x_data)
|
||||
scan_range = x_max - x_min
|
||||
step = np.median(np.diff(np.sort(x_data)))
|
||||
|
||||
centre = result["centre"]
|
||||
fwhm = result["fwhm"]
|
||||
|
||||
problems = []
|
||||
|
||||
if not (
|
||||
x_min + 0.1 * scan_range
|
||||
< centre
|
||||
< x_max - 0.1 * scan_range
|
||||
):
|
||||
problems.append("peak centre is too close to scan edge")
|
||||
|
||||
if fwhm < 3 * step:
|
||||
problems.append("peak is narrower than 3 scan steps")
|
||||
|
||||
if fwhm > 0.7 * scan_range:
|
||||
problems.append("peak is too broad for scan range")
|
||||
|
||||
if result["snr"] < 5:
|
||||
problems.append(f"low SNR ({result['snr']:.1f})")
|
||||
|
||||
centre_stderr = result["centre_stderr"]
|
||||
|
||||
if centre_stderr is None:
|
||||
problems.append("centre uncertainty could not be estimated")
|
||||
elif centre_stderr > 0.2 * fwhm:
|
||||
problems.append(
|
||||
f"centre uncertainty is large "
|
||||
f"({centre_stderr:.3g})"
|
||||
)
|
||||
|
||||
return {
|
||||
"success": not problems,
|
||||
"problems": problems,
|
||||
}
|
||||
|
||||
|
||||
def plot_fitted_data(data, fit_result):
|
||||
"""Plot the original data and display fitting parameters."""
|
||||
|
||||
plt.plot(data["x_data"], data["y_to_fit"], label="Data")
|
||||
plt.plot(fit_result['fit_xdata'], fit_result['fit_ydata'], label="Fit")
|
||||
plt.xlabel(data["motor_name"])
|
||||
plt.ylabel(data["signal_name"])
|
||||
plt.title(f"Scan {data['scan_number']}, fitted with {fit_result['model']}")
|
||||
plt.grid(True)
|
||||
plt.legend()
|
||||
plt.show()
|
||||
|
||||
|
||||
def select_bec_window(dock_area_name="Fitting"):
|
||||
"""Check to see if the fitting results dock is already open and re-create it if not"""
|
||||
|
||||
open_docks = bec.gui.windows
|
||||
|
||||
if open_docks.get(dock_area_name) is None:
|
||||
dock_area = bec.gui.new(dock_area_name)
|
||||
|
||||
wf = dock_area.new(widget='Waveform', object_name='Plot')
|
||||
|
||||
text_box = dock_area.new(widget='TextBox', object_name="Results", where="bottom")
|
||||
|
||||
else:
|
||||
dock_area = open_docks[dock_area_name]
|
||||
wf = dock_area.Plot
|
||||
text_box = dock_area.Results
|
||||
|
||||
return wf, text_box
|
||||
|
||||
|
||||
def plot_live_data_bec(
|
||||
motor_name,
|
||||
signal_name,
|
||||
window_name="Fitting"
|
||||
):
|
||||
"""
|
||||
Plotting live data for motor and signal using BEC.
|
||||
|
||||
This function plots live data from a specified motor and signal.
|
||||
It clears the current plot window, sets its title, labels the axes
|
||||
with the provided motor and signal names, and initializes live plotting
|
||||
on the given signal against the motor.
|
||||
|
||||
Args:
|
||||
motor_name (str): The name of the motor to be used as the x-axis.
|
||||
signal_name (str): The name of the signal to be used as the y-axis.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
wf, text_box = select_bec_window(window_name)
|
||||
text_box.set_plain_text("Plotting live data")
|
||||
wf.clear_all()
|
||||
wf.title = "Scan: Live scan"
|
||||
wf.x_label = motor_name
|
||||
wf.y_label = signal_name
|
||||
wf.plot(device_x=motor_name, device_y=signal_name)
|
||||
|
||||
def plot_live_data(
|
||||
wf,
|
||||
motor_name,
|
||||
signal_name,
|
||||
title="Live scan",
|
||||
):
|
||||
wf.clear_all()
|
||||
wf.title = title
|
||||
wf.x_label = motor_name
|
||||
wf.y_label = signal_name
|
||||
|
||||
wf.plot(
|
||||
device_x=motor_name,
|
||||
device_y=signal_name,
|
||||
)
|
||||
|
||||
|
||||
def plot_fitted_data_bec(
|
||||
data,
|
||||
fit_result,
|
||||
window_name="Fitting",
|
||||
plot_widget=None
|
||||
):
|
||||
"""
|
||||
Plot fitted data and display fitting parameters in the specified window.
|
||||
|
||||
This function selects a BEC window and plots the original data along with the
|
||||
fitted function. Additionally, it displays the fitting results in a text
|
||||
box within the same window for better visualization of the fit results.
|
||||
|
||||
Parameters:
|
||||
data : dict
|
||||
Dictionary containing the original dataset, where 'x_data' and 'y_to_fit'
|
||||
hold the independent variable and the dependent variable, respectively,
|
||||
'scan_number' represents the scan number, 'motor_name' and 'signal_name'
|
||||
provide axis labels.
|
||||
fit_result : dict
|
||||
Dictionary containing the results of the fit, including parameters such
|
||||
as 'centre', 'fwhm', 'height', and the fitted model stored under
|
||||
'lmfit_result', with its 'best_fit' attribute representing the fitted data.
|
||||
"""
|
||||
if plot_widget is not None:
|
||||
wf = plot_widget
|
||||
else:
|
||||
wf, text_box = select_bec_window(window_name)
|
||||
|
||||
fit_text = (
|
||||
f"Fit parameters: Centre = {fit_result['centre']:.5g}, "
|
||||
f"FWHM = {fit_result['fwhm']:.5f}, "
|
||||
f"Height = {fit_result['height']:.4g}\n"
|
||||
f"Model = {fit_result['model']}\n"
|
||||
f"Chi sq = {fit_result['chi_sq']:.3g}\n"
|
||||
f"SNR = {fit_result['snr']:.3g}"
|
||||
)
|
||||
if plot_widget is None:
|
||||
text_box.set_plain_text(fit_text)
|
||||
|
||||
wf.clear_all()
|
||||
wf.title = f"Scan: {data['scan_number']}"
|
||||
wf.x_label = data["motor_name"]
|
||||
wf.y_label = data["signal_name"]
|
||||
wf.plot(x=data["x_data"], y=data["y_to_fit"], label="Data")
|
||||
wf.plot(x=fit_result["fit_xdata"], y=fit_result["fit_ydata"], label="Fit")
|
||||
# wf.Fit.set(symbol_size = 0)
|
||||
wf.get_curve('Fit').set(symbol_size=0)
|
||||
|
||||
# def plot_feature_bec(
|
||||
# data,
|
||||
# result,
|
||||
# window_name="Feature",
|
||||
# ):
|
||||
# """
|
||||
# Plot feature data and indicate the detected edges and centre.
|
||||
# """
|
||||
|
||||
# wf, text_box = select_bec_window(window_name)
|
||||
|
||||
# feature_text = (
|
||||
# f"Feature centre = {result['centre']:.5g}\n"
|
||||
# f"Left edge = {result['left_edge']:.5g}\n"
|
||||
# f"Right edge = {result['right_edge']:.5g}\n"
|
||||
# f"Width = {result['width']:.5g}\n"
|
||||
# f"Threshold = {result['threshold']:.4g}"
|
||||
# )
|
||||
|
||||
# text_box.set_plain_text(feature_text)
|
||||
|
||||
# wf.clear_all()
|
||||
# # wf.title = f"Scan: {data['scan_number']}"
|
||||
# wf.title = "What now??"
|
||||
# wf.x_label = data["motor_name"]
|
||||
# wf.y_label = data["signal_name"]
|
||||
|
||||
# x = data["x_data"]
|
||||
# y = data["y_data"]
|
||||
|
||||
# wf.plot(
|
||||
# x=x,
|
||||
# y=y,
|
||||
# label="Data",
|
||||
# )
|
||||
|
||||
# ymin = np.min(y)
|
||||
# ymax = np.max(y)
|
||||
|
||||
# # Horizontal threshold
|
||||
# wf.plot(
|
||||
# x=[np.min(x), np.max(x)],
|
||||
# y=[result["threshold"], result["threshold"]],
|
||||
# label="Threshold",
|
||||
# )
|
||||
|
||||
# # Left edge
|
||||
# wf.plot(
|
||||
# x=[result["left_edge"], result["left_edge"]],
|
||||
# y=[ymin, ymax],
|
||||
# label="Left edge",
|
||||
# )
|
||||
|
||||
# # Right edge
|
||||
# wf.plot(
|
||||
# x=[result["right_edge"], result["right_edge"]],
|
||||
# y=[ymin, ymax],
|
||||
# label="Right edge",
|
||||
# )
|
||||
|
||||
# # Centre
|
||||
# wf.plot(
|
||||
# x=[result["centre"], result["centre"]],
|
||||
# y=[ymin, ymax],
|
||||
# label="Centre",
|
||||
# )
|
||||
|
||||
# # Remove symbols from guide lines
|
||||
# wf.get_curve("Threshold").set(symbol_size=0)
|
||||
# wf.get_curve("Left edge").set(symbol_size=0)
|
||||
# wf.get_curve("Right edge").set(symbol_size=0)
|
||||
# wf.get_curve("Centre").set(symbol_size=0)
|
||||
@@ -1,666 +0,0 @@
|
||||
"""Use the methods in mx_basics to perform:
|
||||
1) a go_to_peak scan, that scans a motor, finds the peak position and moves to peak
|
||||
2) fits data from a bec history file
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
import numpy as np
|
||||
|
||||
# from pxiii_parameters import FitDefaults, BPMScans, MirrorConfig
|
||||
|
||||
# from mx_basics import (
|
||||
# create_fit_parameters,
|
||||
# get_data_from_history,
|
||||
# fit,
|
||||
# plot_fitted_data_bec,
|
||||
# plot_live_data_bec,
|
||||
# )
|
||||
|
||||
|
||||
# Method functions
|
||||
def calculate_step_size(start: float, stop: float, steps: int) -> float:
|
||||
"""
|
||||
Provides the function to calculate the step size for dividing a specified range
|
||||
into a given number of steps.
|
||||
|
||||
Args:
|
||||
start: The starting value of the range.
|
||||
stop: The stopping value of the range.
|
||||
steps: The number of steps to divide the range into. Must be at least 1.
|
||||
|
||||
Raises:
|
||||
ValueError: If the steps value is less than 1.
|
||||
|
||||
Returns:
|
||||
The calculated step size as a float, rounded to three decimal places.
|
||||
"""
|
||||
if steps < 1:
|
||||
raise ValueError("Number of steps must be at least 1.")
|
||||
return round((stop - start) / (steps - 1), 5)
|
||||
|
||||
|
||||
def move_to_position(motor_device, motor_name: str, position: float, data: dict):
|
||||
"""
|
||||
Function to move a specified motor device to a given position.
|
||||
|
||||
The function verifies if the requested position is within the scan range of the
|
||||
motor device provided. If the position is outside the range, the motor is
|
||||
moved to the center of its scan range, an error message is raised, and the
|
||||
operation is halted. If the position is valid, the motor is moved to the
|
||||
specified position.
|
||||
|
||||
Parameters:
|
||||
motor_device: The motor device to be moved.
|
||||
motor_name: str
|
||||
The name of the motor as a string
|
||||
position: float
|
||||
The desired position to move the motor to. Position should be within
|
||||
the scan range of the motor determined by the provided data.
|
||||
data: dict
|
||||
A dictionary containing "x_data", which is used to determine the
|
||||
scan range of the motor.
|
||||
|
||||
Raises:
|
||||
ValueError: Raised if the specified position is outside the valid scan
|
||||
range determined by "x_data" in the data dictionary. The motor will
|
||||
return to the center of its scan range in this case.
|
||||
"""
|
||||
|
||||
motor_min = np.min(data["x_data"])
|
||||
motor_max = np.max(data["x_data"])
|
||||
motor_centre = (motor_max + motor_min) / 2
|
||||
|
||||
if not motor_min <= position <= motor_max:
|
||||
scans.umv(motor_device, motor_centre, relative=False)
|
||||
msg = (
|
||||
f"Position {position: .2f} is outside the scan range of "
|
||||
f"{motor_min: .2f} to {motor_max: .2f}. "
|
||||
f"Returning to centre of scan range {motor_centre: .3f}."
|
||||
)
|
||||
raise ValueError(msg)
|
||||
motor_position = round(position, 4)
|
||||
scans.umv(motor_device, motor_position, relative=False)
|
||||
print(f"\n Moving {motor_name} to position {motor_position: .3f}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FitDefaults:
|
||||
"""Default values for fitting routines"""
|
||||
|
||||
# Constants for default models, baselines, and parameters
|
||||
MODEL = "Voigt"
|
||||
BASELINE = "Linear"
|
||||
SETTLE_TIME = 0.1
|
||||
RELATIVE_MODE = True
|
||||
|
||||
|
||||
def go_to_peak(
|
||||
motor_device,
|
||||
signal_device,
|
||||
start: float,
|
||||
stop: float,
|
||||
steps: int,
|
||||
relative: bool = FitDefaults.RELATIVE_MODE,
|
||||
plot: bool = True,
|
||||
settle: float = FitDefaults.SETTLE_TIME,
|
||||
confirm: bool = True,
|
||||
gomax: bool = False,
|
||||
negative: bool = False,
|
||||
gap: bool = False,
|
||||
window_name: str = "Fitting",
|
||||
plot_widget = None,
|
||||
):
|
||||
"""
|
||||
Go to the peak of a signal by scanning a motor within a specified range and
|
||||
identifying the optimal position based on signal peak data.
|
||||
|
||||
Parameters:
|
||||
motor_device: The motor device to be scanned.
|
||||
signal_device: The signal device to monitor during the scan.
|
||||
start (float): The starting position of the scan. Ignored if `relative` is True.
|
||||
stop (float): The ending position of the scan. Ignored if `relative` is True.
|
||||
steps (int): The number of steps to divide the scan range into.
|
||||
relative (bool, optional): If True, interpret `start` and `stop` as relative to
|
||||
the current motor position. Defaults to RELATIVE_MODE constant.
|
||||
plot (bool, optional): If True, plot the scan data and the fitted results.
|
||||
Defaults to True.
|
||||
settle (float, optional): The time in seconds to wait after each step for the
|
||||
signal to stabilize. Defaults to DEFAULT_SETTLE_TIME constant.
|
||||
confirm (bool, optional): If True, ask for user confirmation before starting
|
||||
the scan. Defaults to True.
|
||||
|
||||
Raises:
|
||||
Exception: Raises exceptions potentially raised by dependent functions or
|
||||
operations such as plotting, fitting, or motor movement.
|
||||
|
||||
Returns:
|
||||
fit parameters
|
||||
"""
|
||||
# Get motor and signal names
|
||||
mres = get_value(motor_device, True)
|
||||
motor_name = mres['root']
|
||||
sres = get_value(signal_device, True)
|
||||
signal_name = sres['root']
|
||||
print(f"Signal name is {signal_name}")
|
||||
# wf.plot(x_name=motor_name, y_name=signal_name)
|
||||
if plot:
|
||||
if plot_widget is not None:
|
||||
plot_live_data(
|
||||
plot_widget,
|
||||
motor_name,
|
||||
signal_name,
|
||||
title=f"{motor_name} scan"
|
||||
)
|
||||
else:
|
||||
plot_live_data_bec(motor_name, signal_name, window_name=window_name)
|
||||
|
||||
# Validate and calculate step size
|
||||
step_size = calculate_step_size(start, stop, steps)
|
||||
|
||||
# Confirm the scan range
|
||||
current_motor_position = mres['value']
|
||||
print(f"Starting motor position = {current_motor_position}")
|
||||
|
||||
if confirm:
|
||||
if relative:
|
||||
scan_start = current_motor_position + start
|
||||
scan_end = current_motor_position + stop
|
||||
print(
|
||||
f"\nScanning from {scan_start: .6g} to {scan_end: .6g} in "
|
||||
f"{steps} steps of size {step_size}"
|
||||
)
|
||||
print(f"Relative mode = {relative}")
|
||||
else:
|
||||
print(
|
||||
f"\nScanning from {start: .5g} to {stop: .5g} in {steps} steps of size {step_size}"
|
||||
)
|
||||
print(f"Relative mode = {relative}")
|
||||
input("Press Enter to continue...")
|
||||
|
||||
# Perform the scan
|
||||
scan_result = scans.line_scan(
|
||||
motor_device, start, stop, steps=steps, relative=relative, settling_time=settle
|
||||
)
|
||||
motor_data = scan_result.scan.live_data[mres['live_root']][mres['name']].val
|
||||
# # motor_data = scan_result.scan.live_data[motor_name][motor_name].val
|
||||
# sres = get_value(signal_name, True)
|
||||
signal_data = scan_result.scan.live_data[sres['root']][sres['name']].val
|
||||
scan_number = "Current"
|
||||
|
||||
data = {
|
||||
"x_data": np.array(motor_data),
|
||||
"y_data": np.array(signal_data),
|
||||
"motor_name": motor_name,
|
||||
"signal_name": signal_name,
|
||||
"motor_device": motor_device,
|
||||
"scan_number": scan_number,
|
||||
}
|
||||
|
||||
# Define and fit model to scan data
|
||||
fit_params = create_fit_parameters(deriv = False,
|
||||
negative = False,
|
||||
model = FitDefaults.MODEL,
|
||||
baseline = FitDefaults.BASELINE)
|
||||
fit_result = fit(data, fit_params)
|
||||
|
||||
check = check_peak_fit(data["x_data"], fit_result)
|
||||
|
||||
if not check["success"]:
|
||||
print("Peak fit rejected:")
|
||||
for problem in check["problems"]:
|
||||
print(f" - {problem}")
|
||||
return
|
||||
|
||||
# Plot the fitted data if plot = True
|
||||
if plot:
|
||||
plot_fitted_data_bec(data, fit_result, window_name=window_name, plot_widget = plot_widget)
|
||||
|
||||
# If gomax is set then move to the maximum value, rather than the fit centre
|
||||
if gomax:
|
||||
value = fit_result["x_max"]
|
||||
print(f"Max position is at {value}")
|
||||
move_to_position(data["motor_device"], data["motor_name"], fit_result["x_max"], data)
|
||||
else:
|
||||
if gap:
|
||||
if fit_result["centre"] < 4.5:
|
||||
umv(dev.id_gap, 4.5)
|
||||
else:
|
||||
move_to_position(data["motor_device"], data["motor_name"], fit_result["centre"], data)
|
||||
else:
|
||||
# Safely move the motor to the peak position
|
||||
move_to_position(data["motor_device"], data["motor_name"], fit_result["centre"], data)
|
||||
|
||||
return {
|
||||
"centre": fit_result["centre"],
|
||||
"fwhm": float(fit_result["fwhm"]),
|
||||
"height": float(fit_result["height"]),
|
||||
"chi_sq": float(fit_result["chi_sq"]),
|
||||
"snr": float(fit_result["snr"]),
|
||||
}
|
||||
|
||||
|
||||
def fit_history(
|
||||
history_index: int,
|
||||
signal_name: str,
|
||||
deriv: bool = False,
|
||||
negative: bool = False,
|
||||
smoothing: bool = False,
|
||||
model: str = FitDefaults.MODEL,
|
||||
move_to_peak: bool = False,
|
||||
):
|
||||
"""
|
||||
Retrieve and analyze historical data by fitting a model, optionally moving to
|
||||
a peak position.
|
||||
|
||||
Parameters:
|
||||
history_index (int): Index of the historical data set to retrieve.
|
||||
signal_name (str): Name of the signal to fit.
|
||||
deriv (bool, optional): Whether to include the derivative in the fitting
|
||||
procedure. Defaults to False.
|
||||
model (str, optional): Name of the model to use for fitting. Defaults to
|
||||
DEFAULT_MODEL.
|
||||
move_to_peak (bool, optional): Whether to move the motor to the peak position
|
||||
after fitting. Defaults to False.
|
||||
|
||||
Raises:
|
||||
KeyError: If required keys are not found in the retrieved data dictionary.
|
||||
ValueError: If the fitting process fails or produces invalid results.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
# Retrieve historical data
|
||||
data = get_data_from_history(history_index, signal_name)
|
||||
|
||||
# Define fitting parameters
|
||||
fit_params = create_fit_parameters(deriv, negative, model, FitDefaults.BASELINE)
|
||||
|
||||
# Perform fit and plot the data
|
||||
fit_result = fit(data, fit_params)
|
||||
plot_fitted_data_bec(data, fit_result)
|
||||
|
||||
|
||||
# Optionally move the motor to the peak position
|
||||
if move_to_peak:
|
||||
move_to_position(data["motor_device"], data["motor_name"], fit_result["centre"], data)
|
||||
return fit_result
|
||||
|
||||
|
||||
def scan_bpm(bpmname):
|
||||
"""
|
||||
Runs a grid scan of a BPM in x and y, and plots each channel
|
||||
as a heatmap.
|
||||
|
||||
Parameters:
|
||||
bpmname: the name of the bpm to be scanned e.g. "fe"
|
||||
|
||||
"""
|
||||
|
||||
# Open a dock area and set up the heatmaps
|
||||
dock_area = bec.gui.new("XBPM_Scan")
|
||||
wf5 = dock_area.new("Sum").new(bec.gui.available_widgets.Heatmap)
|
||||
wf1 = dock_area.new("Ch1", relative_to="Sum", position="bottom").new(
|
||||
bec.gui.available_widgets.Heatmap
|
||||
)
|
||||
wf3 = dock_area.new("Ch3", relative_to="Ch1", position="right").new(
|
||||
bec.gui.available_widgets.Heatmap
|
||||
)
|
||||
wf4 = dock_area.new("Ch4", relative_to="Ch3", position="bottom").new(
|
||||
bec.gui.available_widgets.Heatmap
|
||||
)
|
||||
wf2 = dock_area.new("Ch2", relative_to="Ch1", position="bottom").new(
|
||||
bec.gui.available_widgets.Heatmap
|
||||
)
|
||||
wfscan = dock_area.new("ScanControl").new(bec.gui.available_widgets.ScanControl)
|
||||
|
||||
cfg = getattr(BPMScans, bpmname)
|
||||
|
||||
wf1.x_label = cfg["x_name"]
|
||||
wf1.y_label = cfg["y_name"]
|
||||
wf1.plot(x_name=cfg["x_name"], y_name=cfg["y_name"], z_name=cfg["z1_name"], color_map="plasma")
|
||||
|
||||
wf2.x_label = cfg["x_name"]
|
||||
wf2.y_label = cfg["y_name"]
|
||||
wf2.plot(x_name=cfg["x_name"], y_name=cfg["y_name"], z_name=cfg["z2_name"], color_map="plasma")
|
||||
|
||||
wf3.x_label = cfg["x_name"]
|
||||
wf3.y_label = cfg["y_name"]
|
||||
wf3.plot(x_name=cfg["x_name"], y_name=cfg["y_name"], z_name=cfg["z3_name"], color_map="plasma")
|
||||
|
||||
wf4.x_label = cfg["x_name"]
|
||||
wf4.y_label = cfg["y_name"]
|
||||
wf4.plot(x_name=cfg["x_name"], y_name=cfg["y_name"], z_name=cfg["z4_name"], color_map="plasma")
|
||||
|
||||
wf5.x_label = cfg["x_name"]
|
||||
wf5.y_label = cfg["y_name"]
|
||||
wf5.plot(x_name=cfg["x_name"], y_name=cfg["y_name"], z_name=cfg["z5_name"], color_map="plasma")
|
||||
# Run the scan
|
||||
x_mot = cfg["x_device"]
|
||||
y_mot = cfg["y_device"]
|
||||
# scans.grid_scan(x_mot, -0.5, 0.5, 20, y_mot, -0.5, 0.5, 20,
|
||||
# exp_time=0.5, relative=False, snaked=True)
|
||||
|
||||
|
||||
def optimise_kb(mirror):
|
||||
"""
|
||||
Runs a grid scan of a the upstream and downstream benders,
|
||||
and plots a heatmap of the sample camera x or y sigma.
|
||||
|
||||
Parameters:
|
||||
mirror: either "hfm" or :vfm"
|
||||
|
||||
"""
|
||||
|
||||
# Open a dock area and set up the heatmaps
|
||||
dock_area = bec.gui.new(mirror)
|
||||
wf1 = dock_area.new("Heatmap").new(bec.gui.available_widgets.Heatmap)
|
||||
|
||||
wfscan = dock_area.new("ScanControl").new(bec.gui.available_widgets.ScanControl)
|
||||
|
||||
cfg = getattr(MirrorConfig, mirror)
|
||||
|
||||
wf1.x_label = cfg["bu_name"]
|
||||
wf1.y_label = cfg["bd_name"]
|
||||
wf1.plot(x_name=cfg["bu_name"], y_name=cfg["bd_name"], z_name=cfg["z_name"], color_map="plasma")
|
||||
|
||||
# Run the scan
|
||||
x_mot = cfg["x_device"]
|
||||
y_mot = cfg["y_device"]
|
||||
# scans.grid_scan(x_mot, -0.02, 0.02, 11, y_mot, -0.02, 0.02, 11,
|
||||
# exp_time=0.5, relative=True, snaked=True)
|
||||
|
||||
|
||||
def find_feature(
|
||||
motor_device,
|
||||
signal_device,
|
||||
start: float,
|
||||
stop: float,
|
||||
steps: int,
|
||||
feature: str = "peak",
|
||||
offset=None,
|
||||
fraction: float = 0.5,
|
||||
relative: bool = FitDefaults.RELATIVE_MODE,
|
||||
plot: bool = True,
|
||||
settle: float = FitDefaults.SETTLE_TIME,
|
||||
confirm: bool = True,
|
||||
window_name: str = "Fitting",
|
||||
plot_widget=None,
|
||||
):
|
||||
"""
|
||||
Scan a motor, determine the centre of a high- or low-signal region,
|
||||
and move the motor to that position.
|
||||
"""
|
||||
|
||||
# Get motor and signal names
|
||||
mres = get_value(motor_device, True)
|
||||
motor_name = mres["root"]
|
||||
|
||||
sres = get_value(signal_device, True)
|
||||
signal_name = sres["root"]
|
||||
|
||||
print(f"Signal name is {signal_name}")
|
||||
|
||||
# Calculate step size
|
||||
step_size = calculate_step_size(start, stop, steps)
|
||||
|
||||
current_motor_position = mres["value"]
|
||||
print(f"Starting motor position = {current_motor_position}")
|
||||
|
||||
# Confirm scan range
|
||||
if confirm:
|
||||
if relative:
|
||||
scan_start = current_motor_position + start
|
||||
scan_end = current_motor_position + stop
|
||||
else:
|
||||
scan_start = start
|
||||
scan_end = stop
|
||||
|
||||
print(
|
||||
f"\nScanning from {scan_start:.6g} to {scan_end:.6g} "
|
||||
f"in {steps} steps of size {step_size}"
|
||||
)
|
||||
print(f"Relative mode = {relative}")
|
||||
print(f"Looking for a {feature} feature")
|
||||
|
||||
input("Press Enter to continue...")
|
||||
|
||||
# -------------------------------------------------
|
||||
# Set up live plot BEFORE starting the scan
|
||||
# -------------------------------------------------
|
||||
if plot:
|
||||
if plot_widget is not None:
|
||||
plot_live_data(
|
||||
plot_widget,
|
||||
motor_name,
|
||||
signal_name,
|
||||
title=f"{motor_name} scan",
|
||||
)
|
||||
else:
|
||||
plot_live_data_bec(
|
||||
motor_name,
|
||||
signal_name,
|
||||
window_name=window_name,
|
||||
)
|
||||
|
||||
# Perform scan
|
||||
scan_result = scans.line_scan(
|
||||
motor_device,
|
||||
start,
|
||||
stop,
|
||||
steps=steps,
|
||||
relative=relative,
|
||||
settling_time=settle,
|
||||
)
|
||||
|
||||
# Retrieve data
|
||||
motor_data = (
|
||||
scan_result.scan.live_data[mres["live_root"]][mres["name"]].val
|
||||
)
|
||||
|
||||
signal_data = (
|
||||
scan_result.scan.live_data[sres["root"]][sres["name"]].val
|
||||
)
|
||||
|
||||
data = {
|
||||
"x_data": np.array(motor_data),
|
||||
"y_data": np.array(signal_data),
|
||||
"motor_name": motor_name,
|
||||
"signal_name": signal_name,
|
||||
"motor_device": motor_device,
|
||||
"scan_number": "Current",
|
||||
}
|
||||
|
||||
# Find feature centre
|
||||
if feature in ("peak", "dip"):
|
||||
result = find_feature_centre(
|
||||
data["x_data"],
|
||||
data["y_data"],
|
||||
feature=feature,
|
||||
fraction=fraction,
|
||||
)
|
||||
elif feature == "edge_offset":
|
||||
result = find_edge_offset(
|
||||
data["x_data"],
|
||||
data["y_data"],
|
||||
feature=feature,
|
||||
offset=offset,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Unknown feature type {feature}")
|
||||
if feature in ("peak", "dip"):
|
||||
print(f"\nLeft edge = {result['left_edge']:.4f}")
|
||||
print(f"Right edge = {result['right_edge']:.4f}")
|
||||
print(f"Width = {result['width']:.4f}")
|
||||
print(f"Centre = {result['centre']:.4f}")
|
||||
elif feature == "edge_offset":
|
||||
print(f"Edge = {result['edge']:.4f}")
|
||||
print(f"Centre = {result['centre']:.4f}")
|
||||
|
||||
# Move safely to centre
|
||||
move_to_position(
|
||||
data["motor_device"],
|
||||
data["motor_name"],
|
||||
result["centre"],
|
||||
data,
|
||||
)
|
||||
|
||||
if plot and plot_widget is not None:
|
||||
# Replace the live subscription with static completed scan data
|
||||
plot_widget.clear_all()
|
||||
|
||||
plot_widget.plot(
|
||||
x=data["x_data"],
|
||||
y=data["y_data"],
|
||||
label="Scan data",
|
||||
)
|
||||
# Mark centre
|
||||
|
||||
plot_widget.plot(
|
||||
x=[result["centre"], result["centre"]],
|
||||
y=[
|
||||
np.min(data["y_data"]),
|
||||
np.max(data["y_data"]),
|
||||
],
|
||||
label="Centre",
|
||||
)
|
||||
|
||||
|
||||
plot_widget.title = f"{motor_name} scan"
|
||||
plot_widget.x_label = motor_name
|
||||
plot_widget.y_label = signal_name
|
||||
|
||||
return result
|
||||
|
||||
def find_edge_offset(x, y, fraction=0.5, feature="edge_offset", offset=0.0):
|
||||
"""
|
||||
Find a single signal edge and calculate a target position
|
||||
at a known offset from that edge.
|
||||
"""
|
||||
|
||||
x = np.asarray(x)
|
||||
y = np.asarray(y)
|
||||
|
||||
y_min = np.min(y)
|
||||
y_max = np.max(y)
|
||||
|
||||
threshold = y_min + fraction * (y_max - y_min)
|
||||
|
||||
# Find threshold crossings
|
||||
crossings = np.where(np.diff(np.sign(y - threshold)) != 0)[0]
|
||||
|
||||
if len(crossings) == 0:
|
||||
raise RuntimeError("No edge found in scan")
|
||||
|
||||
# If we expect only one useful edge, use the strongest/first one
|
||||
i = crossings[0]
|
||||
|
||||
# Linear interpolation for more accurate edge position
|
||||
x1, x2 = x[i], x[i + 1]
|
||||
y1, y2 = y[i], y[i + 1]
|
||||
|
||||
edge = x1 + (threshold - y1) * (x2 - x1) / (y2 - y1)
|
||||
|
||||
centre = edge + offset
|
||||
|
||||
return {
|
||||
"edge": edge,
|
||||
"centre": centre,
|
||||
"threshold": threshold,
|
||||
}
|
||||
|
||||
def find_feature_centre(x, y, feature="peak", fraction=0.5):
|
||||
"""
|
||||
Find the centre of a peak-like or dip-like region from its two edges.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
x, y : array-like
|
||||
Scan positions and measured signal.
|
||||
|
||||
mode : {"peak", "dip"}
|
||||
"peak":
|
||||
Feature is the high-signal region, e.g. collimator scan.
|
||||
|
||||
"dip":
|
||||
Feature is the low-signal region, e.g. beamstop scan.
|
||||
|
||||
fraction : float
|
||||
Fraction of the signal range used for the edge threshold.
|
||||
0.5 means the 50% crossing points.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
centre
|
||||
left_edge
|
||||
right_edge
|
||||
width
|
||||
threshold
|
||||
"""
|
||||
|
||||
x = np.asarray(x, dtype=float)
|
||||
y = np.asarray(y, dtype=float)
|
||||
|
||||
y_low = np.min(y)
|
||||
y_high = np.max(y)
|
||||
|
||||
threshold = y_low + fraction * (y_high - y_low)
|
||||
|
||||
if feature == "peak":
|
||||
inside = y >= threshold
|
||||
|
||||
elif feature == "dip":
|
||||
inside = y <= threshold
|
||||
|
||||
else:
|
||||
raise ValueError("mode must be 'peak' or 'dip'")
|
||||
|
||||
# Find transitions into and out of the feature
|
||||
transitions = np.diff(inside.astype(int))
|
||||
|
||||
entering = np.where(transitions == 1)[0]
|
||||
leaving = np.where(transitions == -1)[0]
|
||||
|
||||
if len(entering) == 0 or len(leaving) == 0:
|
||||
raise ValueError("Could not find both feature edges")
|
||||
|
||||
# Use first entrance and last exit
|
||||
left_idx = entering[0]
|
||||
right_idx = leaving[-1]
|
||||
|
||||
left_edge = interpolate_crossing(
|
||||
x[left_idx],
|
||||
y[left_idx],
|
||||
x[left_idx + 1],
|
||||
y[left_idx + 1],
|
||||
threshold,
|
||||
)
|
||||
|
||||
right_edge = interpolate_crossing(
|
||||
x[right_idx],
|
||||
y[right_idx],
|
||||
x[right_idx + 1],
|
||||
y[right_idx + 1],
|
||||
threshold,
|
||||
)
|
||||
|
||||
centre = 0.5 * (left_edge + right_edge)
|
||||
width = right_edge - left_edge
|
||||
|
||||
return {
|
||||
"centre": centre,
|
||||
"left_edge": left_edge,
|
||||
"right_edge": right_edge,
|
||||
"width": width,
|
||||
"threshold": threshold,
|
||||
}
|
||||
|
||||
|
||||
def interpolate_crossing(x1, y1, x2, y2, threshold):
|
||||
"""Linearly interpolate the x position where y crosses threshold."""
|
||||
|
||||
if y2 == y1:
|
||||
return 0.5 * (x1 + x2)
|
||||
|
||||
return x1 + (threshold - y1) * (x2 - x1) / (y2 - y1)
|
||||
|
||||
Reference in new issue
Block a user