Source code for freegsnke.control_loop.virtual_circuits_category

"""
Module to implement virtual circuits 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/>.
"""

import logging
from typing import Any, Optional, Tuple

import matplotlib.pyplot as plt
import numpy as np

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

logger = logging.getLogger(__name__)


[docs] class VirtualCircuitsController: """ A controller class for managing virtual circuit control matrices and coil current reference waveforms. This class supports both spline-based (linear) and step-based interpolation of control signals for coils and plasma shaping parameters. It optionally integrates with a virtual circuit provider for enhanced control capabilities. Parameters ---------- data : dict A nested dictionary containing control waveforms for each shape parameter to be controlled. Each shape parameter's dictionary must include keys for both spline-based and step-based parameters: - Spline keys: typically of the form '<coil>_ref' - Step keys: typically shape target and plasma target names Each key should map to a dictionary suitable for interpolation, with keys: - 'times': 1D array of time points - 'vals': 1D array of values at those time points (same length). ctrl_coils : list of str The list of active coils being controlled. ctrl_targets : list of str The list of shape parameters being managed. plasma_target : list of str The list of plasma parameters being managed. vc_generator : object, optional An optional class object for updating virtual circuits during simulation. If not provided, deafult waveform-defined VCs will be used. Its `vc_update_rate` attribute (set when the generator was initialised) controls how often, in seconds, new VCs are computed. Attributes ---------- interpolant_derivatives : dict Derivatives of the coil-reference spline interpolants, rebuilt whenever `update_interpolants` is called and reused during control steps. """
[docs] def __init__( self, # heterogeneous: per-coil/target `Waveform` entries, plus a "coil_order" list[str] data: dict[str, Any], ctrl_coils: list[str], ctrl_targets: list[str], plasma_target: list[str], vc_generator: object | None = None, ) -> None: """ Initialise the virtual circuits controller. Reads the coil ordering used by the virtual circuit matrices, validates that the required per-coil reference data and per-target (shape and plasma) data are present in `data`, stores a reference to the data, and builds the spline/step interpolants used to evaluate them at arbitrary times. Optionally sets up state for a virtual circuit generator. Parameters ---------- data : dict Dictionary of time-series entries, plus a "coil_order" entry. Must contain: - "coil_order" : list of str giving the ordering of `ctrl_coils` used in the virtual circuit matrices. Not validated via `check_data_entry` (not a time-series entry). - "<coil>_ref" for each coil in `ctrl_coils` : reference signal for that coil. - one entry per name in `ctrl_targets` and `plasma_target` : target values, each in the format expected by `check_data_entry` (i.e. containing 'times' and 'vals' arrays of matching length). ctrl_coils : list of str Names of the coils used for shape control. Determines which "<coil>_ref" keys are required in `data`. ctrl_targets : list of str Names of the shape parameters to be controlled. Determines which additional keys are required in `data`. plasma_target : list of str Names of the plasma parameter(s) to be controlled. Determines which additional keys are required in `data`. vc_generator : object, optional Virtual circuit generator. If provided, enables automatic VC updating (see Attributes). If None, this controller uses existing VC schedule. Its `vc_update_rate` attribute controls how often VCs are updated, in seconds. Attributes ---------- ctrl_coils : list of str Stored copy of `ctrl_coils`. vc_coil_order : list of str Coil ordering used by the virtual circuit matrices, taken from `data["coil_order"]`. vc_coil_order_index : dict Mapping from coil name to its index in `vc_coil_order`. ctrl_targets : list of str Stored copy of `ctrl_targets`. plasma_target : list of str Stored copy of `plasma_target`. keys_to_spline : list of str Data keys that will be spline-interpolated: one "<coil>_ref" entry per coil in `ctrl_coils`. keys_to_step : list of str Data keys that will be step-interpolated: `ctrl_targets` + `plasma_target`. data : dict Internal reference to the input `data`. vc_generator : object or None Stored copy of `vc_generator`. latest_vc_time : None Only set if `vc_generator` is provided. Placeholder for the timestamp of the most recently computed virtual circuit. latest_vc : None Only set if `vc_generator` is provided. Placeholder for the most recently computed virtual circuit. jacobian_list : list Only set if `vc_generator` is provided. Accumulated shape (Jacobian) matrices used to generate each virtual circuit in `vc_list` (same order/indexing), read from `vc_generator.latest_shape_matrix` after each recomputation. `None` for entries where `vc_generator` does not expose this attribute. vc_list : list Only set if `vc_generator` is provided. Accumulated virtual circuits. vc_times : list Only set if `vc_generator` is provided. Timestamps corresponding to `vc_list` and `jacobian_list`. full_vc_matrix : list Only set if `vc_generator` is provided. Accumulated full virtual circuit matrix. Raises ------ ValueError If a required key is missing from `data` or is not in the expected format, as enforced by `check_data_entry`. Also raised if `data["coil_order"]` and `ctrl_coils` do not contain the same set of coils. KeyError If `data` does not contain a "coil_order" entry. Notes ----- Calls `update_interpolants` after validating `data`, before the VC state is set up. """ # active coils list (used for shape control) self.ctrl_coils = ctrl_coils # ordering of the ctrl coils in the virtual circuit matrices self.vc_coil_order = data["coil_order"] self.vc_coil_order_index = { coil: i for i, coil in enumerate(self.vc_coil_order) } # VC matrix columns (from `data`) are ordered per `vc_coil_order`, but # everywhere else (e.g. `dI_dt_ref` below) coil-indexed arrays are # ordered per `ctrl_coils`. Precompute the permutation that reorders # VC matrix columns from `vc_coil_order` into `ctrl_coils` order. if set(self.vc_coil_order) != set(ctrl_coils): raise ValueError( "VirtualCircuitsController: `data['coil_order']` must contain " "exactly the same coils as `ctrl_coils` (order may differ). " f"Got coil_order={self.vc_coil_order}, ctrl_coils={ctrl_coils}." ) self._coil_permutation = np.array( [self.vc_coil_order_index[coil] for coil in ctrl_coils] ) # shape parameter list to be controlled self.ctrl_targets = ctrl_targets # name of plasma parameter to be controlled self.plasma_target = plasma_target # check correct data is input and in correct format self.keys_to_spline = [coil + "_ref" for coil in self.ctrl_coils] self.keys_to_step = self.ctrl_targets + self.plasma_target for key in self.keys_to_spline + self.keys_to_step: check_data_entry( data=data, key=key, controller_name="VirtualCircuitsController" ) # create an internal copy of the data self.data = data # interpolate the input data self.update_interpolants() # storage self.full_vc_matrix = [] # use if VCs class if present self.vc_generator = vc_generator if self.vc_generator: # set placeholders for most recent VCs self.latest_vc_time = None self.latest_vc = None # store VCs that were used self.jacobian_list = [] self.vc_list = [] self.vc_times = []
[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 key in self.keys_to_spline: self.interpolants[key] = interpolate_spline(self.data[key]) self.interpolant_derivatives[key] = self.interpolants[key].derivative(n=1) for key in self.keys_to_step: self.interpolants[key] = interpolate_step(self.data[key])
[docs] def run_control( self, t: float, dt: float, dip_dt: float, dT_dt: np.ndarray, I_approved_prev: np.ndarray, vcg_inputs: Optional[np.ndarray] = None, tikhonov_lambda: Optional[np.ndarray] = None, verbose: bool = False, ) -> Tuple[np.ndarray, np.ndarray]: """ Computes the unapproved coil currents and their rates of change based on feedforward coil current references and virtual circuit transformations. This method extracts coil current reference derivatives, applies virtual circuit matrices, and computes the unapproved coil current updates using Euler integration. There is also the option to provide VCs from a class object. Parameters ---------- t : float Current time at which control values are evaluated [s]. dt : float Time step for Euler integration [s]. dip_dt : float Time derivative of the requested plasma current [A/s]. dT_dt : np.ndarray Time derivative of the shape target requests [m/s]. I_approved_prev : numpy.ndarray Previously approved coil currents [A]. vcg_inputs : np.ndarray , optional Array of input values for calculating new VCs on the fly. tikhonov_lambda : numpy.ndarray , optional Array of regularisation values for Tikhonov regularisation in VC matrix inversion. Must be same length as coils_calc. verbose : bool Print some output if True. Returns ------- I_unapproved : numpy.ndarray Coil currents (not yet approved), computed via Euler integration [A]. dI_dt_unapproved : numpy.ndarray Rate of change of coil currents (not yet approved) [A/s]. """ # extract (feedforward) current references dI_dt_ref = self.extract_values( t=t, targets=[coil + "_ref" for coil in self.ctrl_coils], deriv=True ) # extract shape target VCs from waveform data (targets x coils, in # vc_coil_order), then reorder columns into ctrl_coils order VC_shape = self.extract_values(t=t, targets=self.ctrl_targets) VC_shape = VC_shape[:, self._coil_permutation] log_level = logging.INFO if verbose else logging.DEBUG logger.log(log_level, "VC's from file: %s", VC_shape) # extract plasma target VC from waveform data (targets x coils), # reordered into ctrl_coils order as above VC_plasma = self.extract_values(t=t, targets=self.plasma_target) VC_plasma = VC_plasma[:, self._coil_permutation] # if self-updating VCs to be used, extract the data and overwrite relevant VC # matrix columns if self.vc_generator is not None: if self.latest_vc is None: # compute first new VC logger.log(log_level, " calculating new VCs...") VC_shape_new = self.vc_generator.get_vc( targets=self.vc_generator.targets_ctrl, targets_calc=self.vc_generator.targets_calc, coils=self.ctrl_coils, coils_calc=self.vc_generator.coils_calc, input_data=vcg_inputs, tikhonov_lambda=tikhonov_lambda, ) # update latest vcs/times self.latest_vc_time = 1.0 * t self.latest_vc = VC_shape_new # calculate time since last VC update delta_t_vc = t - self.latest_vc_time # update with new VCs if required if delta_t_vc >= self.vc_generator.vc_update_rate: logger.log(log_level, " calculating new VCs...") VC_shape_new = self.vc_generator.get_vc( targets=self.vc_generator.targets_ctrl, targets_calc=self.vc_generator.targets_calc, coils=self.ctrl_coils, coils_calc=self.vc_generator.coils_calc, input_data=vcg_inputs, tikhonov_lambda=tikhonov_lambda, ) # update latest VCs and times self.latest_vc_time = 1.0 * t self.latest_vc = VC_shape_new # store sensitivity matrix (Jacobian) and the VC computed from it self.jacobian_list.append( getattr(self.vc_generator, "latest_shape_matrix", None) ) self.vc_list.append(self.latest_vc) self.vc_times.append(t) else: # use the existing VC VC_shape_new = self.latest_vc # fill appropriate columns from new VCs ctrl_target_order = { target: i for i, target in enumerate(self.ctrl_targets) } for j, targ in enumerate(self.vc_generator.targets_ctrl): # expand array as apropriate VC_shape[ctrl_target_order[targ], :] = 1.0 * VC_shape_new[:, j] # unapproved coil currents rates of change dI_dt_unapproved = dI_dt_ref + (dT_dt @ VC_shape) + (dip_dt * VC_plasma) self.full_vc_matrix.append(np.concatenate((VC_shape, VC_plasma), axis=0)) # unapproved coil currents (by simple Euler integration) I_unapproved = I_approved_prev + (dI_dt_unapproved * dt) return I_unapproved.squeeze(), dI_dt_unapproved.squeeze()
[docs] def extract_values( self, t: float, targets: list[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 keys. Each must correspond to a key in `self.interpolants`. 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]` 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](t) for target in targets] ) else: return np.array([self.interpolants[target](t) for target in targets])
[docs] def plot_data_FF_currents( self, tmin: float = -1.0, tmax: float = 1.0, nt: int = 1001 ) -> None: """ Visualizes interpolated control waveforms and corresponding raw inputs. This method generates subplots for each control waveform (spline types), showing the interpolated time series alongside the original data points. It helps verify the quality and behavior of the interpolation. Parameters ---------- 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 1001). Notes ----- - Each subplot corresponds to a control waveform (e.g., '<coil>_ref'). - 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) # number of plots # 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): # find out which control is ON and when FF_reference = self.interpolants[key](t) FF_mask = np.abs(FF_reference) > 0 # 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[key]["times"], self.data[key]["vals"], s=10, marker="x", color="tab:orange", alpha=0.9, label=f"raw data", ) # interpolated data ax.plot( t, self.interpolants[key](t), color="navy", linewidth=1.2, label="interpolated", ) ax.grid(True, linestyle="--", alpha=0.6) if key[-3:] == "ref": ax.set_ylabel(rf"{key} [$A$]") else: ax.set_ylabel(key) # y-scaling inside the window times = np.array(self.data[key]["times"]) mask = (times >= tmin) & (times <= tmax) if np.any(mask): ydata = np.concatenate( [self.interpolants[key](t), np.array(self.data[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) 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()
[docs] def plot_data_VCs( self, tmin: float = -1.0, tmax: float = 1.0, nt: int = 1001 ) -> None: """ Visualizes virtual circuits times and corresponding raw inputs. Parameters ---------- 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 1001). """ # times to plot at t = np.linspace(tmin, tmax, nt) nplots = len(self.keys_to_step) # number of plots # 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_step): # Assign a unique ID to each unique array state_ids = [] next_id = 1 for arr in self.data[key]["vals"]: if np.all(np.abs(arr) < 1e-12): state_ids.append(0) else: state_ids.append(next_id) next_id += 1 state_ids = np.array(state_ids) # plot different VC times ax.step( self.data[key]["times"], state_ids, where="post", color="navy", label=key, ) ax.set_yticks(sorted(set(state_ids))) ax.grid(True, linestyle="--", alpha=0.6) ax.set_ylabel(f"Unique VC ID") ax.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()