freegsnke.switch_profile module

Implements some functionality needed by the FreeGSNKE profile object to find optimised coefficients when switching between different profile parametrisations.

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

freegsnke.switch_profile.Lao_parameters_finder(pn_: ndarray, pprime_: ndarray, ffprime_: ndarray, n_alpha: int, n_beta: int, alpha_logic: bool = True, beta_logic: bool = True, Ip_logic: bool = True) → tuple[ndarray, ndarray][source]

Fit Lao85 profile coefficients to prescribed pprime and ffprime profiles.

The profiles are represented as polynomial expansions in the normalised flux coordinate pn_. The coefficients are obtained via a linear least-squares fit.

Parameters:
  • pn (ndarray) – Normalised flux coordinate values in the interval [0, 1].

  • pprime (ndarray) – Values of pprime evaluated at pn_.

  • ffprime (ndarray) – Values of ffprime evaluated at pn_.

  • n_alpha (int) – Number of free coefficients in the pprime expansion.

  • n_beta (int) – Number of free coefficients in the ffprime expansion.

  • alpha_logic (bool, optional) – If True, include the Lao85 constraint term so that the fitted pprime profile satisfies the boundary condition at pn = 1. Default is True.

  • beta_logic (bool, optional) – If True, include the Lao85 constraint term so that the fitted ffprime profile satisfies the boundary condition at pn = 1. Default is True.

  • Ip_logic (bool, optional) – If False, rescale the fitted coefficients using the original profile amplitudes. Default is True.

Returns:

  • alpha (ndarray) – Fitted coefficients for the pprime profile.

  • beta (ndarray) – Fitted coefficients for the ffprime profile.

Notes

The returned coefficients must be used with the same values of alpha_logic and beta_logic that were used during fitting.

This routine normalises pprime_ and ffprime_ by their values at pn_[0] before fitting. The normalisation is done in place, so the input arrays pprime_ and ffprime_ are modified (and must be float arrays).

freegsnke.switch_profile.Lpars(tp: ndarray, tf: ndarray, x: ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: ndarray | None = None) → float | ndarray[source]

Compute the total loss for the parameterised Topeol model.

The loss is defined as the sum of two squared-error contributions: one for tp and one for tf, using a shared profile.

Parameters:
  • tp (ndarray) – First target dataset (e.g. pressure-like contribution), same length as x.

  • tf (ndarray) – Second target dataset (e.g. flux-function-like contribution), same length as x.

  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter controlling the split between the two datasets.

  • Tstd (float or ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

Scalar total loss value.

Return type:

float

Notes

The loss is

L = sum( (tp - beta_0 * T(x))^2 + (tf - (1 - beta_0) * T(x))^2 )

where

T(x) = (1 - x^alpha_m)^alpha_n.

The summation is performed over the input grid in x.

freegsnke.switch_profile.Topeol_opt(tp: ndarray, tf: ndarray, x: ndarray, max_it: int, tol: float) → ndarray[source]

Optimise Topeol model parameters using an iterative stepper.

This function performs a fixed-point style optimisation of the parameters [alpha_m, alpha_n, beta_0] using repeated calls to the Topeol_opt_stepper until convergence or a maximum number of iterations is reached.

Parameters:
  • tp (ndarray) – First target dataset (e.g. pressure-like contribution).

  • tf (ndarray) – Second target dataset (e.g. flux-function-like contribution).

  • x (ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • max_it (int) – Maximum number of optimisation iterations.

  • tol (float) – Convergence tolerance. Iteration stops when all parameter updates satisfy |Δpars| ≤ tol.

Returns:

Optimised parameters [alpha_m, alpha_n, beta_0].

Return type:

ndarray, shape (3,)

Notes

The optimisation procedure is:

  1. Initialise parameters using Topeol_opt_init:

    tpn, tfn, b0 = Topeol_opt_init(tp, tf)

  2. Set initial guess:

    pars = [2, 1, b0]

  3. Iterate:

    pars_{k+1} = Topeol_opt_stepper(tpn, tfn, x, pars_k)

  4. Stop when:

    max|pars_{k+1} - pars_k| ≤ tol

    or when max_it is reached.

Warning

  • Convergence is not guaranteed.

  • The algorithm depends strongly on the quality of the initial guess.

  • If max_it is reached, a message is printed and the returned parameters may not be optimal.

freegsnke.switch_profile.Topeol_opt_init(tp: ndarray, tf: ndarray) → tuple[ndarray, ndarray, float][source]

Compute an initial guess for Topeol model scaling and amplitude split.

This routine provides a heuristic initialisation for optimisation by normalising the input profiles and estimating a mixing parameter b0 that balances contributions between tp and tf.

Parameters:
  • tp (ndarray) – First input profile (e.g. pressure-like quantity).

  • tf (ndarray) – Second input profile (e.g. flux-function-like quantity).

Returns:

  • tpn (ndarray) – Normalised and rescaled version of tp using the estimated split.

  • tfn (ndarray) – Normalised and rescaled version of tf using the estimated split.

  • b0 (float) – Estimated initial amplitude split parameter in [0, 1].

Notes

The initial estimate is computed as follows:

  1. A shared normalisation scale is defined using the larger of the initial values of tp and tf.

  2. A mask is applied where tf is positive to form a stable ratio.

  3. The mean ratio tp/tf over this region is used to estimate:

    rr = mean(tp/tf) b0 = rr / (1 + rr)

  4. The profiles are then rescaled consistently using b0 and their initial values.

Warning

This heuristic assumes: - tp[0] and tf[0] are non-zero - There exists a region where tf > 0 - Ratios are numerically stable in the masked region

Results may be unstable if these assumptions are violated.

freegsnke.switch_profile.Topeol_opt_stepper(tp: ndarray, tf: ndarray, x: ndarray, pars: ndarray) → ndarray[source]

Perform one optimisation step for the Topeol parameter fit.

This routine computes a parameter update using either a Newton-like step (based on the Hessian) or a fallback gradient-scaled step when the Hessian is not sufficiently well-conditioned.

Parameters:
  • tp (ndarray) – First target dataset (e.g. pressure-like contribution).

  • tf (ndarray) – Second target dataset (e.g. flux-function-like contribution).

  • x (ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • pars (ndarray, shape (3,)) – Current parameter vector [alpha_m, alpha_n, beta_0].

Returns:

Updated parameter vector after one optimisation step.

Return type:

ndarray, shape (3,)

Notes

The update proceeds as follows:

  1. Compute the current profile:

    T(x) = Topeol_std(x, alpha_m, alpha_n, beta_0)

  2. Compute gradient and Hessian:

    grad = dLdpars(…) H = d2Ldpars2(…)

  3. Check Hessian conditioning via eigenvalues: - If sufficiently many positive eigenvalues are present,

    solve Newton step:

    dpars = -H^{-1} grad

    • Otherwise, fall back to a scaled gradient step:

      dpars = -L * grad / ||grad||

  4. Apply step limiting: Prevent excessively large updates by clipping relative changes in parameters.

Warning

This is a heuristic optimizer: - It is not guaranteed to converge globally. - Hessian inversion may be unstable if ill-conditioned. - Step limiting is ad hoc and may bias convergence.

freegsnke.switch_profile.Topeol_std(x: float | ndarray, alpha_m: float, alpha_n: float, beta_0: float) → float | ndarray[source]

Evaluate the standard Topeol profile.

The profile is defined as

T(x) = (1 - x^{alpha_m})^{alpha_n}.

Parameters:
  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent controlling the profile shape.

  • alpha_n (float) – Outer exponent controlling the profile peaking and edge behaviour.

  • beta_0 (float) – Unused parameter. Included for consistency with related Topeol profile functions and fitting routines.

Returns:

Value of the standard Topeol profile evaluated at x.

Return type:

float or ndarray

Notes

This function does not currently depend on beta_0.

freegsnke.switch_profile.d2Ldb2(t: float | ndarray, x: float | ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: float | ndarray | None = None) → float | ndarray[source]

Evaluate the second derivative of the loss function with respect to beta_0.

Parameters:
  • t (float or ndarray) – Target values used in the loss function.

  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (float or ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

Second derivative of the loss function with respect to beta_0.

Return type:

float or ndarray

Notes

This function returns

d²L/dβ₀² = 2 Tstd²,

where Tstd is the standard Topeol profile. Providing Tstd avoids recomputing the profile when multiple derivatives are evaluated at the same point.

freegsnke.switch_profile.d2Ldbdm(t: float | ndarray, x: float | ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: float | ndarray | None = None) → float | ndarray[source]

Evaluate the mixed second derivative of the loss function with respect to beta_0 and alpha_m.

Parameters:
  • t (float or ndarray) – Target values used in the loss function.

  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (float or ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

Mixed second derivative of the loss function with respect to beta_0 and alpha_m.

Return type:

float or ndarray

Notes

This function evaluates the mixed derivative

d²L / (d beta_0 d alpha_m),

using the standard Topeol profile

T(x) = (1 - x^alpha_m)^alpha_n.

The expression includes logarithmic and power-law sensitivity terms arising from differentiation with respect to alpha_m.

Warning

The term log(x) becomes singular at x = 0, so the expression is undefined at that point.

freegsnke.switch_profile.d2Ldbdn(t: float | ndarray, x: float | ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: float | ndarray | None = None) → float | ndarray[source]

Evaluate the mixed second derivative of the loss function with respect to beta_0 and alpha_n.

Parameters:
  • t (float or ndarray) – Target values used in the loss function.

  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (float or ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

Mixed second derivative of the loss function with respect to beta_0 and alpha_n.

Return type:

float or ndarray

Notes

This function evaluates

d²L / (d beta_0 d alpha_n) = (2 * beta_0 * Tstd - t) * (2 * Tstd * log(1 - x^alpha_m)),

where

Tstd = (1 - x^alpha_m)^alpha_n.

The logarithm term comes from differentiating the profile with respect to alpha_n.

Warning

This expression becomes singular when x = 1, since log(0) is undefined.

freegsnke.switch_profile.d2Ldm2(t: float | ndarray, x: float | ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: float | ndarray | None = None) → float | ndarray[source]

Evaluate the second derivative of the loss function with respect to alpha_m.

Parameters:
  • t (float or ndarray) – Target values used in the loss function.

  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (float or ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

Second derivative of the loss function with respect to alpha_m.

Return type:

float or ndarray

Notes

This function evaluates

d²L / d alpha_m²,

using the standard Topeol profile

T(x) = (1 - x^alpha_m)^alpha_n.

The expression contains logarithmic terms (log(x)) and power-law factors arising from repeated differentiation with respect to alpha_m.

Warning

The function is undefined at x = 0 due to log(x), and may suffer numerical instability near x = 0 or x = 1.

freegsnke.switch_profile.d2Ldmdn(t: float | ndarray, x: float | ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: float | ndarray | None = None) → float | ndarray[source]

Evaluate the mixed second derivative of the loss function with respect to alpha_m and alpha_n.

Parameters:
  • t (float or ndarray) – Target values used in the loss function.

  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (float or ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

Mixed second derivative of the loss function with respect to alpha_m and alpha_n.

Return type:

float or ndarray

Notes

This function evaluates the mixed derivative

d²L / (d alpha_m d alpha_n),

for the standard Topeol profile

T(x) = (1 - x^alpha_m)^alpha_n.

The expression contains coupled logarithmic sensitivities in both alpha_m and alpha_n arising from differentiation of the power-law structure of the profile.

Warning

The expression is undefined at x = 0 (log(x)) and may become singular at x = 1 due to log(1 - x^alpha_m).

freegsnke.switch_profile.d2Ldn2(t: float | ndarray, x: float | ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: float | ndarray | None = None) → float | ndarray[source]

Evaluate the second derivative of the loss function with respect to alpha_n.

Parameters:
  • t (float or ndarray) – Target values used in the loss function.

  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (float or ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

Second derivative of the loss function with respect to alpha_n.

Return type:

float or ndarray

Notes

This function evaluates

d²L / d alpha_n²,

using the standard Topeol profile

T(x) = (1 - x^alpha_m)^alpha_n.

The dependence on alpha_n enters through logarithmic terms of the form log(1 - x^alpha_m), which are squared in this second derivative.

Warning

The expression becomes singular when x = 1 since log(0) is undefined.

freegsnke.switch_profile.d2Ldpars2(tp: ndarray, tf: ndarray, x: ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: ndarray | None = None) → ndarray[source]

Compute the Hessian matrix of the total loss with respect to the model parameters.

The total loss is assumed to be the sum of two contributions: one associated with tp and one associated with tf, each depending on the same Topeol profile but with different amplitude structure.

Parameters:
  • tp (ndarray) – First target dataset (e.g. pressure-like contribution), same length as x.

  • tf (ndarray) – Second target dataset (e.g. flux-function-like contribution), same length as x.

  • x (ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

Hessian matrix of the total loss with respect to: [alpha_m, alpha_n, beta_0].

Return type:

ndarray, shape (3, 3)

Notes

The Hessian is constructed as the sum of two contributions:

  1. tp contribution: - uses second derivatives of the loss with respect to all parameter pairs - evaluated using d2Ldm2, d2Ldn2, d2Ldb2, d2Ldmdn, d2Ldbdm, d2Ldbdn

  2. tf contribution: - uses modified amplitude (1 - beta_0) - includes sign flips in mixed derivatives involving beta_0 due to chain rule

The final Hessian is:

H = H(tp) + H(tf)

freegsnke.switch_profile.dLdb(t: float | ndarray, x: float | ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: float | ndarray | None = None) → float | ndarray[source]

Evaluate the first derivative of the loss function with respect to beta_0.

Parameters:
  • t (float or ndarray) – Target values used in the loss function.

  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (float or ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

First derivative of the loss function with respect to beta_0.

Return type:

float or ndarray

Notes

This function evaluates

dL / d beta_0,

using the standard Topeol profile

T(x) = (1 - x^alpha_m)^alpha_n.

The derivative reflects a simple quadratic residual structure in beta_0.

freegsnke.switch_profile.dLdm(t: float | ndarray, x: float | ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: float | ndarray | None = None) → float | ndarray[source]

Evaluate the first derivative of the loss function with respect to alpha_m.

Parameters:
  • t (float or ndarray) – Target values used in the loss function.

  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (float or ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

First derivative of the loss function with respect to alpha_m.

Return type:

float or ndarray

Notes

This function evaluates

dL / d alpha_m,

using the standard Topeol profile

T(x) = (1 - x^alpha_m)^alpha_n.

The dependence on alpha_m enters through logarithmic and power-law terms involving log(x).

Warning

The expression is undefined at x = 0 due to log(x), and may become numerically unstable near x = 0 or x = 1.

freegsnke.switch_profile.dLdn(t: float | ndarray, x: float | ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: float | ndarray | None = None) → float | ndarray[source]

Evaluate the first derivative of the loss function with respect to alpha_n.

Parameters:
  • t (float or ndarray) – Target values used in the loss function.

  • x (float or ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (float or ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

First derivative of the loss function with respect to alpha_n.

Return type:

float or ndarray

Notes

This function evaluates

dL / d alpha_n,

using the standard Topeol profile

T(x) = (1 - x^alpha_m)^alpha_n.

The dependence on alpha_n enters through a logarithmic term of the form log(1 - x^alpha_m).

Warning

The expression becomes singular when x = 1 since log(0) is undefined.

freegsnke.switch_profile.dLdpars(tp: ndarray, tf: ndarray, x: ndarray, alpha_m: float, alpha_n: float, beta_0: float, Tstd: ndarray | None = None) → ndarray[source]

Compute the gradient of the total loss with respect to the model parameters.

The total loss is assumed to be the sum of two contributions: one associated with tp and one associated with tf, each depending on the same Topeol profile but with different amplitude structure.

Parameters:
  • tp (ndarray) – First target dataset (e.g. pressure-like contribution), same length as x.

  • tf (ndarray) – Second target dataset (e.g. flux-function-like contribution), same length as x.

  • x (ndarray) – Independent variable, typically a normalised coordinate in the interval [0, 1].

  • alpha_m (float) – Inner exponent of the standard Topeol profile.

  • alpha_n (float) – Outer exponent of the standard Topeol profile.

  • beta_0 (float) – Amplitude parameter of the fitted profile.

  • Tstd (ndarray, optional) – Precomputed value of Topeol_std(x, alpha_m, alpha_n, beta_0). If not provided, it is evaluated internally.

Returns:

Gradient of the total loss with respect to: [alpha_m, alpha_n, beta_0].

Return type:

ndarray, shape (3,)

Notes

The gradient is constructed as the sum of two contributions:

  1. tp contribution: - uses standard derivatives dLdm, dLdn, dLdb

  2. tf contribution: - uses modified amplitude (1 - beta_0) - flips sign of beta_0 derivative term

The final result is:

grad L = grad L(tp) + grad L(tf)