Source code for freegsnke.control_loop.shape_category

"""
Module to implement shape control in FreeGSNKE control loops.

Copyright 2025 UKAEA, UKRI-STFC, and The Authors, as per the COPYRIGHT and README files.

This file is part of FreeGSNKE.

FreeGSNKE is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FreeGSNKE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with FreeGSNKE. If not, see <http://www.gnu.org/licenses/>.
"""

from typing import Callable, Optional, Tuple

import matplotlib.pyplot as plt
import numpy as np

from freegsnke.control_loop.useful_functions import (
    PID,
    Waveform,
    check_data_entry,
    interpolate_spline,
    interpolate_step,
)


[docs] class ShapeController: """ A controller class for managing shape control waveforms. Parameters ---------- data : dict A nested dictionary containing waveforms for each target to be controlled. Each target's dictionary must include keys for both spline-based and step-based parameters: - Spline keys: "ff", "ref", "blend" - Step keys: "k_prop", "k_int", "damping" Each key should map to a waveform dictionary suitable for interpolation with keys: - 'times': 1D array of time points - 'vals': 1D array of values at those time points (same length). ctrl_targets : list of str A list of shape target names (keys in `data`) that the controller will manage. mode : str Choose the type of controller to use, here the default is an "PI_with_P_damping" controller, see "run_control" method for more information. Attributes ---------- ctrl_targets : list of str The list of shape targets being managed. keys_to_spline : list of str Keys corresponding to waveforms that will be interpolated using splines. keys_to_step : list of str Keys corresponding to waveforms that will be interpolated using step functions. data : dict Internal copy of the input control waveforms. interpolants : dict A nested dictionary storing interpolation functions of each input waveform for each shape target. Structure: {target: {spline/step key: interpolant_function}} interpolant_derivatives : dict A nested dictionary storing derivatives of the spline interpolants. These are constructed with `interpolants` so control steps only evaluate them. """
[docs] def __init__( self, data: dict[str, dict[str, Waveform]], ctrl_targets: list[str], mode: Optional[str] = None, ) -> None: """ Initialise the shape controller. Selects a control algorithm based on `mode`, determines which data keys that algorithm requires, validates that `data` contains those keys (per control target) in the expected format, and builds the spline/step interpolants used to evaluate them at arbitrary times. Parameters ---------- data : dict Dictionary keyed by control target (each entry of `ctrl_targets` must be a key). Each value is itself a dictionary of time-series entries, containing whichever of "ff", "ref", "blend", "k_prop", "k_int", "k_deriv", and "damping" are required by the selected `mode` (see below), each in the format expected by `check_data_entry`. ctrl_targets : list of str Names of the shape control targets. Each must be a top-level key in `data`. mode : str, optional Control algorithm to use. One of: - "PI_with_P_damping" (default): PI control with proportional damping. Requires spline keys "ff", "ref", "blend" and step keys "k_prop", "k_int", "k_deriv", "damping". - "PID_with_scaled_out_damping": PID control with damping scaled out. Requires spline keys "ff", "ref", "blend" and step keys "k_prop", "damping". - "PID": standard PID control. Requires spline keys "ff", "ref", "blend" and step keys "k_prop", "k_int", "k_deriv". If None, defaults to "PI_with_P_damping". Attributes ---------- ctrl_targets : list of str Stored copy of `ctrl_targets`. data : dict Internal reference to the input `data`. run_control : callable Bound method implementing the selected control algorithm (`run_control_PI_with_P_damping`, `run_control_PID_with_scaled_out_damping`, or `run_control_PID`). keys_to_spline : list of str Data keys (per target) that will be spline-interpolated, as determined by `mode`. keys_to_step : list of str Data keys (per target) that will be step-interpolated, as determined by `mode`. Raises ------ ValueError If a required key is missing from `data[targ]` for any target in `ctrl_targets`, or is not in the expected format, as enforced by `check_data_entry`. Notes ----- Calls `update_interpolants` at the end of initialisation to build the interpolating functions from `data`. """ # targets list self.ctrl_targets = ctrl_targets # create an internal copy of the data self.data = data # choose controller to use (more can be added) if mode is None: mode = "PI_with_P_damping" if mode == "PI_with_P_damping": # select control algorithm self.run_control: Callable[ [float, float, np.ndarray, np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray, np.ndarray], ] = self.run_control_PI_with_P_damping # inputs required for this algorithm self.keys_to_spline = ["ff", "ref", "blend"] self.keys_to_step = ["k_prop", "k_int", "k_deriv", "damping"] elif mode == "PID_with_scaled_out_damping": # select control algorithm self.run_control = self.run_control_PID_with_scaled_out_damping # inputs required for this algorithm self.keys_to_spline = ["ff", "ref", "blend"] self.keys_to_step = ["k_prop", "damping"] elif mode == "PID": # select control algorithm self.run_control = self.run_control_PID # inputs required for this algorithm self.keys_to_spline = ["ff", "ref", "blend"] self.keys_to_step = ["k_prop", "k_int", "k_deriv"] # check correct data is input and in correct format for targ in self.ctrl_targets: for key in self.keys_to_spline + self.keys_to_step: check_data_entry( data=data[targ], key=key, controller_name="ShapeController" ) # interpolate the input data self.update_interpolants()
[docs] def update_interpolants(self) -> None: """ Recompute all interpolant functions from the current `self.data`. This method rebuilds `self.interpolants` by applying either `interpolate_spline` or `interpolate_step`, and rebuilds the cached derivatives of every spline interpolant. """ # create dictionaries to store the interpolants and spline derivatives self.interpolants = {} self.interpolant_derivatives = {} # interpolate the input data for targ in self.ctrl_targets: self.interpolants[targ] = {} self.interpolant_derivatives[targ] = {} for key in self.keys_to_spline: self.interpolants[targ][key] = interpolate_spline(self.data[targ][key]) self.interpolant_derivatives[targ][key] = self.interpolants[targ][ key ].derivative() for key in self.keys_to_step: self.interpolants[targ][key] = interpolate_step(self.data[targ][key])
[docs] def run_control_PI_with_P_damping( self, t: float, dt: float, T_meas: np.ndarray, T_err_prev: np.ndarray, T_hist_prev: np.ndarray, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Computes the time derivative of shape target requests based on measured values, reference trajectories, and control gains. It blends feedforward and feedback contributions using a time-varying blend factor, and applies damping to the error signal. Parameters ---------- t : float Current time [s]. dt : float Time step [s]. T_meas : np.ndarray Measured values of the shape targets at the current time [m]. T_err_prev : np.ndarray Previously filtered error signal (used for damping) [m]. T_hist_prev : np.ndarray Previous integral term (used for PI control) [m.s]. Returns ------- dT_dt : np.ndarray Time derivative of the shape target requests [m/s]. T_err : np.ndarray Filtered error signal at the current time [m]. T_hist : np.ndarray Updated integral term for use in the next control step [m.s]. Notes ----- - The error signal is filtered using a damping factor to smooth transitions. - The integral term is updated using trapezoidal integration. - The final output blends feedforward and feedback derivatives based on a dynamic blend factor. """ # extract data T_ref = self.extract_values(t=t, targets=self.ctrl_targets, key="ref") T_ff_deriv = self.extract_values( t=t, targets=self.ctrl_targets, key="ff", deriv=True ) T_blend = self.extract_values(t=t, targets=self.ctrl_targets, key="blend") k_prop = self.extract_values(t=t, targets=self.ctrl_targets, key="k_prop") k_int = self.extract_values(t=t, targets=self.ctrl_targets, key="k_int") k_deriv = self.extract_values(t=t, targets=self.ctrl_targets, key="k_deriv") alpha_inv = 1.0 / self.extract_values( t=t, targets=self.ctrl_targets, key="damping" ) # proportional term T_err = ((1 - alpha_inv) * T_err_prev) + (alpha_inv * (T_ref - T_meas)) # integral term T_int = T_hist_prev + (0.5 * T_err * dt) # derivative term T_deriv = (T_err - T_err_prev) / dt # update hist T_hist = T_hist_prev + (T_err * dt) # FB term T_fb_deriv = PID( error_prop=T_err, error_int=T_int, error_deriv=T_deriv, k_prop=k_prop, k_int=k_int, k_deriv=k_deriv, ) # time deriv of shape target requests dT_dt = ((T_blend * T_fb_deriv) + ((1.0 - T_blend) * T_ff_deriv)).squeeze() return ( np.atleast_1d(dT_dt), np.atleast_1d(T_err.squeeze()), np.atleast_1d(T_hist.squeeze()), )
[docs] def run_control_PID_with_scaled_out_damping( self, t: float, dt: float, T_meas: np.ndarray, T_err_prev: np.ndarray, T_hist_prev: np.ndarray, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Computes the time derivative of shape target requests based on measured values, reference trajectories, and control gains. It blends feedforward and feedback contributions using a time-varying blend factor, and applies damping to the error signal. This function re-formulates "run_control_PI_with_scaled_out_damping" to not include a damping term. Parameters ---------- t : float Current time [s]. dt : float Time step [s]. T_meas : np.ndarray Measured values of the shape targets at the current time [m]. T_err_prev : np.ndarray Previously filtered error signal [m]. T_hist_prev : np.ndarray Previous integral term (used for PI control) [m.s]. Returns ------- dT_dt : np.ndarray Time derivative of the shape target requests [m/s]. T_err : np.ndarray Filtered error signal at the current time [m]. T_hist : np.ndarray Updated integral term for use in the next control step [m.s]. """ # extract data T_ref = self.extract_values(t=t, targets=self.ctrl_targets, key="ref") T_ff_deriv = self.extract_values( t=t, targets=self.ctrl_targets, key="ff", deriv=True ) T_blend = self.extract_values(t=t, targets=self.ctrl_targets, key="blend") k_prop = self.extract_values(t=t, targets=self.ctrl_targets, key="k_prop") alpha_inv = 1.0 / self.extract_values( t=t, targets=self.ctrl_targets, key="damping" ) # build PID gains to match damping beta = 1 - alpha_inv abs_beta = np.abs(beta) k_int = alpha_inv * (1 + beta) / (1e-4) k_deriv = (abs_beta * k_int * dt - beta) * dt k_prop_new = 1 - k_int * dt / 2 - k_deriv / dt # rescale k_int *= k_prop * alpha_inv k_deriv *= k_prop * alpha_inv k_prop = k_prop_new * k_prop * alpha_inv # proportional term T_err = T_ref - T_meas # integral term T_int = abs_beta ** (dt / 1e-4) * T_hist_prev + (0.5 * T_err * dt) # derivative term T_deriv = (T_err - T_err_prev) / dt # FB term T_fb_deriv = PID( error_prop=T_err, error_int=T_int, error_deriv=T_deriv, k_prop=k_prop, k_int=k_int, k_deriv=k_deriv, ) # time deriv of shape target requests dT_dt = ((T_blend * T_fb_deriv) + ((1.0 - T_blend) * T_ff_deriv)).squeeze() # update hist T_hist = T_int + (0.5 * T_err * dt) return ( np.atleast_1d(dT_dt), np.atleast_1d(T_err.squeeze()), np.atleast_1d(T_hist.squeeze()), )
[docs] def run_control_PID( self, t: float, dt: float, T_meas: np.ndarray, T_err_prev: np.ndarray, T_hist_prev: np.ndarray, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Computes the time derivative of shape target requests based on measured values, reference trajectories, and control gains. It blends feedforward and feedback contributions using a time-varying blend factor. Parameters ---------- t : float Current time [s]. dt : float Time step [s]. T_meas : np.ndarray Measured values of the shape targets at the current time [m]. T_err_prev : np.ndarray Previously filtered error signal [m]. T_hist_prev : np.ndarray Previous integral term (used for PI control) [m.s]. Returns ------- dT_dt : np.ndarray Time derivative of the shape target requests [m/s]. T_err : np.ndarray Filtered error signal at the current time [m]. T_hist : np.ndarray Updated integral term for use in the next control step [m.s]. Notes ----- - The integral term is updated using trapezoidal integration. - The final output blends feedforward and feedback derivatives based on a dynamic blend factor. """ # extract data T_ref = self.extract_values(t=t, targets=self.ctrl_targets, key="ref") T_ff_deriv = self.extract_values( t=t, targets=self.ctrl_targets, key="ff", deriv=True ) T_blend = self.extract_values(t=t, targets=self.ctrl_targets, key="blend") k_prop = self.extract_values(t=t, targets=self.ctrl_targets, key="k_prop") k_int = self.extract_values(t=t, targets=self.ctrl_targets, key="k_int") k_deriv = self.extract_values(t=t, targets=self.ctrl_targets, key="k_deriv") # proportional term T_err = T_ref - T_meas # integral term T_int = T_hist_prev + (0.5 * T_err * dt) # derivative term T_deriv = (T_err - T_err_prev) / dt # FB term T_fb_deriv = PID( error_prop=T_err, error_int=T_int, error_deriv=T_deriv, k_prop=k_prop, k_int=k_int, k_deriv=k_deriv, ) # time deriv of shape target requests dT_dt = ((T_blend * T_fb_deriv) + ((1.0 - T_blend) * T_ff_deriv)).squeeze() # update hist T_hist = T_hist_prev + (T_err * dt) return ( np.atleast_1d(dT_dt), np.atleast_1d(T_err.squeeze()), np.atleast_1d(T_hist.squeeze()), )
[docs] def extract_values( self, t: float, targets: list[str], key: str, deriv: bool = False, ) -> np.ndarray: """ Extracts interpolated values or their derivatives for specified shape targets at a given time. This method queries the stored interpolation functions for each target and key, returning either the interpolated value or its first derivative depending on the `deriv` flag. Parameters ---------- t : float Time at which to evaluate the interpolants [s]. targets : list of str List of shape target names. Each must correspond to a key in `self.interpolants`. key : str The waveform name (e.g., 'ff', 'ref', 'blend', 'k_prop', etc.) used to select the interpolant. deriv : bool, optional If True, returns the first derivative of the interpolant at time `t`. Default is False. Returns ------- np.ndarray Array of interpolated values (or derivatives) for each target at time `t`. Notes ----- - Assumes that `self.interpolants[target][key]` is a valid `scipy.interpolate` object. - Spline derivatives are constructed by `update_interpolants` and reused here. """ if deriv: return np.array( [self.interpolant_derivatives[target][key](t) for target in targets] ) else: return np.array([self.interpolants[target][key](t) for target in targets])
[docs] def plot_data( self, targ: str, tmin: float = -1.0, tmax: float = 1.0, nt: int = 1001 ) -> None: """ Visualizes interpolated control waveforms and corresponding raw inputs for a specified shape target. This method generates subplots for each control waveform (both spline and step types), showing the interpolated time series alongside the original data points. It helps verify the quality and behavior of the interpolation. Parameters ---------- targ : str The name of the shape target waveforms to plot. Must be a key in `self.interpolants` and `self.data`. tmin : float, optional Start time for the evaluation grid (default is -1.0 seconds). tmax : float, optional End time for the evaluation grid (default is 1.0 seconds). nt : int, optional Number of time points to evaluate the interpolants over the interval [tmin, tmax] (default is 10001). Notes ----- - Each subplot corresponds to a control parameter (e.g., 'ff', 'ref', 'blend', 'k_prop', etc.). - Interpolated curves are plotted in navy; raw data points are shown in red. - Axis labels include units where applicable. - Useful for debugging or validating the interpolation quality. """ # times to plot at t = np.linspace(tmin, tmax, nt) nplots = len(self.keys_to_spline + self.keys_to_step) # number of plots # find out which control is ON and when FF_reference = self.interpolants[targ]["ff"](t) FF_mask = (self.interpolants[targ]["blend"](t) < 1) * ( np.abs(self.interpolant_derivatives[targ]["ff"](t)) > 0 ) FB_reference = self.interpolants[targ]["ref"](t) FB_mask = (self.interpolants[targ]["blend"](t) > 0) * ( np.abs(self.interpolants[targ]["ref"](t)) > 0 ) # start plotting fig, axes = plt.subplots(nplots, 1, figsize=(6, 2.5 * nplots), sharex=True) if nplots == 1: axes = [axes] for ax, key in zip(axes, self.keys_to_spline + self.keys_to_step): # shade region of FB control on_regions = np.where(np.diff(FB_mask.astype(int)) != 0)[0] + 1 segments = np.split(t, on_regions) states = np.split(FB_mask, on_regions) for seg_t, seg_state in zip(segments, states): if np.all(seg_state): # region fully "on" ax.axvspan(seg_t[0], seg_t[-1], color="green", alpha=0.25) # shade region of FF control on_regions = np.where(np.diff(FF_mask.astype(int)) != 0)[0] + 1 segments = np.split(t, on_regions) states = np.split(FF_mask, on_regions) for seg_t, seg_state in zip(segments, states): if np.all(seg_state): # region fully "on" ax.axvspan(seg_t[0], seg_t[-1], color="yellow", alpha=0.25) # raw data ax.scatter( self.data[targ][key]["times"], self.data[targ][key]["vals"], s=10, marker="x", color="tab:orange", label=f"raw data", ) # interpolated data ax.plot( t, self.interpolants[targ][key](t), color="navy", linewidth=1.2, label="interpolated", ) ax.grid(True, linestyle="--", alpha=0.6) if key in ["ref", "ff"]: ax.set_ylabel(rf"{key} [$m$]") elif key == "k_prop": ax.set_ylabel(rf"{key} [$1/s$]") elif key == "k_int": ax.set_ylabel(rf"{key} [$1/s^2$]") elif key == "k_deriv": ax.set_ylabel(rf"{key} [No units]") else: ax.set_ylabel(key) # y-scaling inside the window times = np.array(self.data[targ][key]["times"]) mask = (times >= tmin) & (times <= tmax) if np.any(mask): ydata = np.concatenate( [ self.interpolants[targ][key](t), np.array(self.data[targ][key]["vals"])[mask], ] ) ymin, ymax = np.min(ydata), np.max(ydata) yrange = ymax - ymin if yrange == 0: yrange = 1.0 ax.set_ylim(ymin - 0.02 * yrange, ymax + 0.02 * yrange) fig.suptitle(targ) axes[0].legend(loc="best") axes[-1].set_xlabel(r"Time [$s$]") axes[-1].set_xlim([tmin, tmax]) plt.tight_layout(rect=[0, 0, 1, 0.97]) plt.show()