freegsnke.virtual_circuits module

Defines class that represents the virtual circuits.

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.virtual_circuits.VirtualCircuit(name: str, eq: object, profiles: object, shape_matrix: ndarray, VCs_matrix: ndarray, target_names: list[str], coils: list[str], target_calculator: Callable[[object], ndarray])[source]

Bases: object

The class for storing/recording virtual circuits that have been built using the VirtualCircuitHandling class.

__init__(name: str, eq: object, profiles: object, shape_matrix: ndarray, VCs_matrix: ndarray, target_names: list[str], coils: list[str], target_calculator: Callable[[object], ndarray]) → None[source]

Store the key quantities from the VirtualCircuitHandling calculations.

Parameters:
  • name (str) – Name to call the VCs (e.g. super-X VCs).

  • eq (object) – The equilibrium object used to build the VCs.

  • profiles (object) – The profiles object used to build the VCs.

  • shape_matrix (np.array) – The array storing the Jacobians between the targets and coils given in ‘targets’ and ‘coils’.

  • VCs_matrix (np.array) – The array storing the VCs between the targets and coils given in ‘targets’ and ‘coils’.

  • target_names (list) – A list of the target names, e.g [Rin, Rout, Rx, Zx, …] (must be same length as array from target_calculator).

  • coils (list) – The list of coils used to calculate the shape_matrix and VCs_matrix.

  • target_calculator (function) – Function returning an array of the shape targets (VC will be calculated for ALL of these targets).

class freegsnke.virtual_circuits.VirtualCircuitHandling[source]

Bases: object

The virtual circuits handling class.

__init__() → None[source]

Initialises the virtual circuits.

apply_VC(eq: object, profiles: object, VC_object: VirtualCircuit, requested_target_shifts: list[float], verbose: bool = False) → tuple[object, object, ndarray, ndarray][source]

Here we apply the VC matrix V to requested shifts in the target quantities (dT), obtaining the shift in the currents (in coils, dI) required to achieve this:

dI = V * dT.

Applying the current shifts to the existing currents, we re-solve the equilibrium and return to user.

Parameters:
  • eq (object) – The equilibrium object upon which to apply the VCs.

  • profiles (object) – The profiles object upon which to apply the VCs.

  • VC_object (an instance of the VirtualCircuit class) – Specifies the virtual circuit matrix and properties.

  • requested_target_shifts (list) – List of floats containing the shifts in all of the relevant targets. Same order as VC_object.target_names.

  • verbose (bool) – Display output (or not).

Returns:

  • object – Returns the equilibrium object after applying the shifted currents.

  • object – Returns the profiles object after applying the shifted currents.

  • np.array – Array of new target values.

  • np.array – Array of old target values.

Raises:
  • ValueError – If the length of requested_target_shifts does not match the targets of VC_object.

  • AttributeError – If the solver has not been defined (see define_solver).

assign_currents(currents_vec: ndarray, coils: list[str], eq: object) → None[source]

For the given equilibrium, this function assigns the coil currents (for those listed in ‘coils’) in the class object.

Parameters:
  • currents_vec (np.array) – Vector of coil currents to be assigned to the eq object using the coil names in ‘coils.

  • coils (list) – List of strings containing the names of the coil currents to be assigned.

  • eq (object) – The equilibrium object, modified in place.

assign_currents_solve_GS(currents_vec: ndarray, coils: list[str], target_relative_tolerance: float) → None[source]

Assigns the coil currents in ‘currents_vec’ to a private equilibrium object and then solve using the static GS solver.

Parameters:
  • currents_vec (np.array) – Input current values to be assigned. Format as in self.assign_currents.

  • coils (list) – List of strings containing the names of the coil currents to be assigned.

  • target_relative_tolerance (float) – Target relative tolerance to be met by the solver.

Raises:

AttributeError – If the solver has not been defined (see define_solver).

build_current_vec(eq: object, coils: list[str]) → None[source]

For the given equilibrium, this function stores the coil currents (for those listed in ‘coils’) in the class object.

Parameters:
  • eq (object) – The equilibrium object.

  • coils (list) – List of strings containing the names of the coil currents to be stored. Modifies the class object in place.

build_dIydI_j(j: int, coils: list[str], verbose: bool = False) → ndarray[source]

Computes the term d(Iy)/dI_j of the Jacobian as a finite difference derivative, using the value of delta(I_j) inferred earlier by self.prepare_build_dIydI_j.

Here:
  • Iy is the flattened vector of plasma currents (on the computational grid).

  • I_j is the current in the jth coil.

Parameters:
  • j (int) – Index identifying the current to be varied. Indexes as in self.currents_vec.

  • coils (list) – List of strings containing the names of the coil currents to be assigned.

  • verbose (bool) – Display output (or not).

Returns:

The column of the shape (Jacobian) matrix corresponding to coil j, i.e. d(targets)/dI_j.

Return type:

np.array

calculate_VC(eq: object, profiles: object, coils: list[str], target_names: list[str], target_calculator: Callable[[object], ndarray], target_dIy: float = 0.001, starting_dI: ndarray | None = None, min_starting_dI: float = 50, verbose: bool = False, tikhonov_lambda: ndarray | None = None, name: str | None = None, n_vc_workers: int = 1) → None[source]

Calculate the “virtual circuits” matrix:

V = (S^T S)^(-1) S^T,

which is the Moore-Penrose pseudo-inverse of the shape (Jacobian) matrix S:

S_ij = dT_i / dI_j.

This represents the sensitivity of target parameters T_i to changes in coil currents I_j.

Parameters:
  • eq (object) – The equilibrium object.

  • profiles (object) – The profiles object.

  • coils (list) – List of strings containing the names of the coil currents to be assigned.

  • target_names (list) – A list of the target names, e.g [Rin, Rout, Rx, Zx, …] (must be same length as array from target_calculator).

  • target_calculator (function) – Function returning an array of the shape targets (VC will be calculated for ALL of these targets).

  • target_dIy (float) – Target value for the norm of delta(I_y), from which the finite difference derivative is calculated.

  • starting_dI (array) – Initial current perturbations [Amps] to be used as delta(I_j) to infer the slope of norm(delta(I_y))/delta(I_j).

  • min_starting_dI (float) – Minimum starting_dI value to be used as delta(I_j): to infer the slope of norm(delta(I_y))/delta(I_j).

  • verbose (bool) – Display output (or not).

  • tikhonov_lambda (np.ndarray, optional) – Tikhonov regularisation coefficients to use when inverting the shape matrix. See calculate_matrix_inverse for details. If None (default), the Moore-Penrose pseudo-inverse is used instead.

  • name (str) – Name to store the VC under (in the ‘VirtualCircuit’ class).

  • n_vc_workers (int, default=1) – Number of worker processes used to build independent shape-matrix columns. A value of 1 retains the serial calculation.

Raises:
  • ValueError – If target_calculator or target_names is missing or inconsistent, or n_vc_workers is not a positive integer.

  • AttributeError – If the solver has not been defined (see define_solver).

static calculate_matrix_inverse(matrix: ndarray, tikhonov_lambda: ndarray | None = None, verbose: bool = False) → ndarray[source]

Compute inverse of a generically non-square matrix By default Moore Penrose inverse is used (np.pinv). If Tikhonov_lambda is provided then Tikhonov regularisation is applied and inv = [M^T M + diag(lambda)]^-1 M^T

Parameters:
  • matrix (np.ndarray) – matrix to be inverted

  • tikhonov_lambda (np.ndarray, optional) – 1d array of tikhonov coefficients, or 2d diagonal matrix of coefficients. Must have size/shape consistent with matrix.shape[1].

  • verbose (bool, optional) – Display output (or not).

Returns:

inverse – inverse of matrix

Return type:

np.ndarray

Raises:

ValueError – If tikhonov_lambda is not 1d or a 2d diagonal matrix, or its size is inconsistent with the number of columns of matrix.

define_solver(solver: object, target_relative_tolerance: float = 1e-07) → None[source]

Sets the solver in the VC class.

Parameters:
  • solver (object) – The static Grad-Shafranov solver object.

  • target_relative_tolerance (float) – Target relative tolerance to be met by the solver. Modifies the class object in place.

prepare_build_dIydI_j(j: int, coils: list[str], target_dIy: float, starting_dI: float, min_curr: float = 0.0001, max_curr: float = 300) → None[source]

Prepares to compute the term d(Iy)/dI_j of the Jacobian by inferring the value of delta(I_j) corresponding to a change delta(I_y) with norm(delta(I_y)) = target_dIy.

Here:
  • Iy is the flattened vector of plasma currents (on the computational grid).

  • I_j is the current in the jth coil.

Parameters:
  • j (int) – Index identifying the current to be varied. Indexes as in self.currents_vec.

  • coils (list) – List of strings containing the names of the coil currents to be assigned.

  • target_dIy (float) – Target value for the norm of delta(I_y), from which the finite difference derivative is calculated.

  • starting_dI (float) – Initial value to be used as delta(I_j) to infer the slope of norm(delta(I_y))/delta(I_j).

  • min_curr (float, optional, by default 1e-4) – If inferred current value is below min_curr, clip to min_curr.

  • max_curr (float, optional, by default 300) – If inferred current value is above max_curr, clip to max_curr.

Raises:

ZeroDivisionError – If the plasma current change from the initial perturbation is near zero, so no finite-difference slope can be inferred.