Formula reference: utils

This page is generated from the docstrings of vaft/formula/utils.py: 9 public functions. The category overview and notation come from the module docstring; every entry below is what vaft.formula.describe("utils.<name>") prints. Back to the formula reference index.

Overview

This module provides common utility functions and fitting utilities used throughout the formula module.

Functions

calculate_peaking_factor

calculate_peaking_factor(central, volume_avg)

Peaking factor, central value over volume average.

\[\mathrm{PF} = \frac{X(0)}{\langle X\rangle}\]
ParameterTypeUnitDescription
centralfloatany

Value on the magnetic axis.

volume_avgfloatany

Volume average of the same quantity, same unit.

ReturnsTypeUnitDescription
float-

Peaking factor.

Limitations.

No guard against a zero volume average. Tracked in #357.

calculate_poloidal_flux

calculate_poloidal_flux(R, B_theta, l, psi_axis=0.0)

Convention-sensitive.

Poloidal flux per radian from a line integral of $RB_\theta$.

\[\psi(l) = \int_0^{l} R\,B_\theta\,dl' + \psi_a\]
ParameterTypeUnitDescription
Rnp.ndarraym

Major radius along the path.

B_thetanp.ndarrayT

Poloidal field normal to the path.

lnp.ndarraym

Path coordinate, monotonic.

psi_axisfloat, optionalWb/rad

Offset added to the integral; default 0.

ReturnsTypeUnitDescription
floatWb/rad

Flux at the end of the path.

Convention.

Flux per radian (COCOS 1-8 storage); multiply by $2\pi$ for the IMAS full-weber flux. Sign follows B_theta and the direction of l. The physics wrapper is vaft.formula.equilibrium.psi_from_RBtheta.

Numerical notes.

Trapezoidal rule over the whole path; returns the end value only.

calculate_toroidal_flux

calculate_toroidal_flux(B_phi, dA)

Convention-sensitive.

Toroidal flux as a sum of $B_\varphi$ over area elements.

\[\Phi = \sum_i B_{\varphi,i}\,\Delta A_i\]
ParameterTypeUnitDescription
B_phinp.ndarrayT

Toroidal field on the area elements.

dAnp.ndarraym^2

Area of each element, same shape.

ReturnsTypeUnitDescription
floatWb

Toroidal flux.

Convention.

Full weber (toroidal flux has no per-radian form); sign of $B_\varphi$. The physics wrapper is vaft.formula.equilibrium.phi_from_Bphi.

Numerical notes.

A Riemann sum with caller-supplied areas, not a quadrature rule; first order in the cell size. Tracked in #358.

calculate_volume_weighted_average

calculate_volume_weighted_average(x, V)

Volume-weighted average of a sampled profile.

\[\langle X\rangle = \frac{\sum_i X_i\,V_i}{\sum_i V_i}\]
ParameterTypeUnitDescription
xnp.ndarrayany

Profile values at each cell.

Vnp.ndarraym^3

Volume of each cell, same shape.

ReturnsTypeUnitDescription
floatany

Volume-weighted average in the unit of x.

Limitations.

No guard against a zero total volume. Tracked in #357.

fit_profile

fit_profile(x, y, y_std, x_eval, order=3, uncertainty_option=1, fitting_function='polynomial', gp_kernel=None, gp_anchor=None, n_restarts_optimizer=5)

Fit a 1-D profile with a selectable model and evaluate it on a grid.

Least-squares (scipy.optimize.curve_fit) for the parametric modes, Gaussian-process regression (sklearn) for 'gp', linear interpolation for 'linear', a core-polynomial/edge-exponential blend with a $\tanh$ transition for 'core_poly_edge_exp', and square-root modes that fit $y^2$ and return $\sqrt{f}$.

ParameterTypeUnitDescription
xarray-likeany

Data abscissae, 1-D.

yarray-likeany

Data values.

y_stdarray-like or Noneany

Per-point uncertainty, same unit as y; None for unweighted.

x_evalarray-likeany

Evaluation grid.

orderint, optional-

Number of polynomial coefficients (degree order - 1); default 3.

uncertainty_optionint, optional-

1 (default) weights by y_std when given; 0 ignores it.

fitting_functionstr, optionalstr

Model name, default 'polynomial'. One of 'gp', 'polynomial', 'free_polynomial', 'exponential', 'free_exponential', 'linear', 'core_poly_edge_exp', 'sqrt', 'sqrt_exponential'.

gp_kernelsklearn kernel or None, optionaln/a

Kernel for the GP mode; default constant times RBF.

gp_anchortuple or None, optionaln/a

(x_anchor, y_anchor, y_std_anchor) extra points for the GP.

n_restarts_optimizerint, optional-

GP hyperparameter restarts; default 5.

ReturnsTypeUnitDescription
y_evalnp.ndarrayany

Fitted values on x_eval.

y_std_evalnp.ndarrayany

Fitted uncertainty; non-zero for the GP mode only.

fit_functioncallablen/a

f(x) evaluating the fit at arbitrary x.

coeffsnp.ndarray or Noneany

Fitted coefficients; None for the GP and linear modes.

Raises.

ValueError Fewer than two valid points after masking, or an unknown mode. RuntimeError When curve_fit does not converge.

Assumptions.

x is a normalised radius on $[0, 1]$ for the constrained modes (they force zero at $x = 1$); uncertainties are one-sigma and independent.

Limitations.

Non-finite points and non-positive y_std are dropped with a warning. The 'linear' mode uses numpy.interp, which holds the end values constant outside the data range (silent constant extrapolation; tracked in #359). The square-root modes clip negative data to zero before squaring, biasing the fit where the data cross zero, and report zero uncertainty. A fit that returns its initial guess unchanged is reported by a warning, not an exception.

Numerical notes.

The initial guess is scaled to max|y| so raw densities in m^-3 do not stall the optimiser; maxfev=20000.

Examples.

fit_profile(x, y, y_std, x_eval, fitting_function=’gp’) fit_profile(x, y, y_std, x_eval, order=3, fitting_function=’polynomial’) fit_profile(x, y, y_std, x_eval, fitting_function=’linear’) fit_profile(x, y, y_std, x_eval, order=3, fitting_function=’core_poly_edge_exp’)

gradient

gradient(x, y)

Derivative $dy/dx$ on a sampled 1-D profile.

\[\frac{dy}{dx}\Big|_i \approx \frac{y_{i+1} - y_{i-1}}{x_{i+1} - x_{i-1}}\]

(second-order central difference on a possibly non-uniform grid).

ParameterTypeUnitDescription
xnp.ndarrayany

Independent variable, monotonic.

ynp.ndarrayany

Dependent variable, same length as x.

ReturnsTypeUnitDescription
np.ndarrayany

$dy/dx$ at every sample, in units of y per unit x.

Numerical notes.

Wraps numpy.gradient(y, x): second-order accurate in the interior, first-order one-sided at the two end points, and noise-amplifying (a relative noise $\delta$ on y becomes $\delta/\Delta x$ on the derivative). Needs at least two samples; only the first axis of a 2-D y is differentiated.

make_fit_function

make_fit_function(mode)

Build a 1-D parametric model $f(x; c_0, c_1, \dots)$ for profile fitting.

\[\begin{aligned} \text{polynomial:}\ & (1-x)\,\textstyle\sum_k c_kx^k & \text{free\_polynomial:}\ & \textstyle\sum_k c_kx^k \\ \text{exponential:}\ & (1-x)\exp\big(\textstyle\sum_k c_kx^k\big) & \text{free\_exponential:}\ & \exp\big(\textstyle\sum_k c_kx^k\big) \end{aligned}\]
ParameterTypeUnitDescription
modestrstr

Model name, case-insensitive. One of 'polynomial', 'free_polynomial', 'exponential', 'free_exponential' (a few aliases are accepted).

ReturnsTypeUnitDescription
callableany

f(x, *coeffs) evaluating the model, in the unit of the data.

Raises.

ValueError For an unknown mode.

Assumptions.

x is a normalised radius on $[0, 1]$: the $(1 - x)$ factor forces the constrained modes to zero at $x = 1$; the exponential modes are strictly positive and decay monotonically when the polynomial is decreasing.

normalize_profile

normalize_profile(x, x_axis, x_boundary)

Linear normalisation of a profile between its axis and boundary values.

\[x_N = \frac{x - x_{\mathrm{axis}}}{x_{\mathrm{boundary}} - x_{\mathrm{axis}}}\]
ParameterTypeUnitDescription
xfloat or np.ndarrayany

Values to normalise.

x_axisfloatany

Value mapped to 0.

x_boundaryfloatany

Value mapped to 1.

ReturnsTypeUnitDescription
float or np.ndarray-

Normalised values, 0 at the axis value and 1 at the boundary value.

Limitations.

No guard against x_boundary == x_axis: a degenerate equilibrium with equal axis and boundary flux, which packaged VEST samples do contain, returns inf/nan. Tracked in #357.

trapz_integral

trapz_integral(x, y)

vaft.formula.trapz_integral resolves to the green copy; reach this one as vaft.formula.utils.trapz_integral.

Definite integral $\int y\,dx$ by the trapezoidal rule.

\[\int y\,dx \approx \sum_i \frac{y_i + y_{i+1}}{2}\,(x_{i+1} - x_i)\]
ParameterTypeUnitDescription
xnp.ndarrayany

Sample abscissae, monotonic.

ynp.ndarrayany

Integrand at the samples.

ReturnsTypeUnitDescription
floatany

Integral over the sampled range, in units of y times x.

Numerical notes.

numpy.trapezoid through vaft.compat.trapz_compat; second-order accurate in the spacing, exact for piecewise-linear integrands, and sign-reversed for a decreasing x. A same-named helper in vaft.formula.green shadows this one on the package namespace (vaft.formula.trapz_integral is the Green’s-function copy).

Refreshing this snapshot

From a checkout of the develop branch, run:

python -m vaft.formula.catalog --output /path/to/vaft-gh/_data/formula_catalog.yml

The snapshot records the SHA-256 of every vaft/formula/*.py source file; documentation validation compares them when VAFT_REGISTRY_SOURCE points to the corresponding source checkout. The same text is available offline as vaft.formula.describe("<name>"), vaft.formula.search("<text>") and vaft.formula.list_formulas(category="<category>").

results matching ""

    No results matching ""