freegsnke.control_loop.virtual_circuits_category module

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/>.

class freegsnke.control_loop.virtual_circuits_category.VirtualCircuitsController(data: dict[str, Any], ctrl_coils: list[str], ctrl_targets: list[str], plasma_target: list[str], vc_generator: object | None = None)[source]

Bases: object

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.

interpolant_derivatives

Derivatives of the coil-reference spline interpolants, rebuilt whenever update_interpolants is called and reused during control steps.

Type:

dict

__init__(data: dict[str, Any], ctrl_coils: list[str], ctrl_targets: list[str], plasma_target: list[str], vc_generator: object | None = None) → None[source]

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.

ctrl_coils

Stored copy of ctrl_coils.

Type:

list of str

vc_coil_order

Coil ordering used by the virtual circuit matrices, taken from data[“coil_order”].

Type:

list of str

vc_coil_order_index

Mapping from coil name to its index in vc_coil_order.

Type:

dict

ctrl_targets

Stored copy of ctrl_targets.

Type:

list of str

plasma_target

Stored copy of plasma_target.

Type:

list of str

keys_to_spline

Data keys that will be spline-interpolated: one “<coil>_ref” entry per coil in ctrl_coils.

Type:

list of str

keys_to_step

Data keys that will be step-interpolated: ctrl_targets + plasma_target.

Type:

list of str

data

Internal reference to the input data.

Type:

dict

vc_generator

Stored copy of vc_generator.

Type:

object or None

latest_vc_time

Only set if vc_generator is provided. Placeholder for the timestamp of the most recently computed virtual circuit.

Type:

None

latest_vc

Only set if vc_generator is provided. Placeholder for the most recently computed virtual circuit.

Type:

None

jacobian_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.

Type:

list

vc_list

Only set if vc_generator is provided. Accumulated virtual circuits.

Type:

list

vc_times

Only set if vc_generator is provided. Timestamps corresponding to vc_list and jacobian_list.

Type:

list

full_vc_matrix

Only set if vc_generator is provided. Accumulated full virtual circuit matrix.

Type:

list

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.

extract_values(t: float, targets: list[str], deriv: bool = False) → ndarray[source]

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:

Array of interpolated values (or derivatives) for each target at time t.

Return type:

np.ndarray

Notes

  • Assumes that self.interpolants[target] is a valid scipy.interpolate object.

  • Spline derivatives are constructed by update_interpolants and reused here.

plot_data_FF_currents(tmin: float = -1.0, tmax: float = 1.0, nt: int = 1001) → None[source]

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.

plot_data_VCs(tmin: float = -1.0, tmax: float = 1.0, nt: int = 1001) → None[source]

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).

run_control(t: float, dt: float, dip_dt: float, dT_dt: ndarray, I_approved_prev: ndarray, vcg_inputs: ndarray | None = None, tikhonov_lambda: ndarray | None = None, verbose: bool = False) → Tuple[ndarray, ndarray][source]

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].

update_interpolants() → None[source]

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.