freegsnke.jtor_refinement module
Contains various functions for refining the plasma current density map.
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.jtor_refinement.Jtor_refiner(eq: object, nnx: int, nny: int)[source]
Bases:
objectRefines the toroidal plasma current (Jtor) on a structured grid.
This class implements a local sub-grid refinement strategy for Jtor, currently used primarily for Lao85-type profiles when refinement is enabled.
Refinement is applied selectively to grid cells, typically those: - intersected by the separatrix (LCFS), - exhibiting large Jtor magnitude, or - showing strong spatial gradients.
The goal is to improve resolution of sharp features without globally increasing grid resolution.
- __init__(eq: object, nnx: int, nny: int) None[source]
Initialise the Jtor refiner and precompute geometric and indexing data.
- Parameters:
eq (freegsnke.Equilibrium) – Equilibrium object defining the computational grid and limiter geometry.
nnx (int (even)) – Refinement factor in the R-direction (number of subcells per cell).
nny (int (even)) – Refinement factor in the Z-direction (number of subcells per cell).
Notes
The grid is assumed to be uniform in R and Z, and refinement is performed by subdividing each selected cell into an nnx × nny subgrid.
- build_LCFS_mask(core_mask: ndarray) ndarray[source]
Construct a refinement mask identifying grid points adjacent to the LCFS.
The mask is built by detecting interfaces between plasma and vacuum cells in the binary core_mask. Any grid cell that shares an edge with a cell of opposite classification (inside/outside plasma core) is marked for refinement.
The resulting mask is additive: cells adjacent to multiple LCFS edges may accumulate values greater than 1. This is primarily used as a selection indicator, not a strict boolean mask.
- Parameters:
core_mask (np.ndarray of shape (nx, ny)) –
Binary plasma core mask on the structured grid. Expected values:
1 (or True): inside plasma core
0 (or False): outside plasma core
- Returns:
LCFS refinement indicator array. Entries are non-zero where grid cells are adjacent to a change in core_mask across a grid edge. Higher values indicate multiple adjacent LCFS crossings.
- Return type:
np.ndarray of shape (nx, ny)
- build_bilinear_psi_interp(psi: ndarray, core_mask: ndarray, unrefined_jtor: ndarray, thresholds: tuple[float, float]) tuple[ndarray, ndarray][source]
Construct a refined representation of the poloidal flux psi on a sub-grid using bilinear interpolation in selected refinement cells.
- Cells are selected for refinement based on a combined criterion:
proximity to the LCFS (core–vacuum interface)
large values of Jtor (based on quantile thresholding)
large gradients in Jtor (based on quantile thresholding)
For each selected coarse-grid cell, a higher-resolution sub-grid is generated and psi is reconstructed via bilinear interpolation.
- Parameters:
psi (np.ndarray of shape (nx, ny)) – Poloidal flux on the coarse grid.
core_mask (np.ndarray of shape (nx, ny)) – Binary plasma core mask defining LCFS location.
unrefined_jtor (np.ndarray of shape (nx, ny)) – Toroidal current density on the coarse grid.
thresholds (tuple of float) – (jtor_threshold, gradient_threshold) Scaling factors used in refinement criteria via inter-quantile ranges.
- Returns:
format_bilinear_psi (np.ndarray of shape (n_refined, nnx, nny)) – Bilinearly interpolated psi values on refined sub-grids for each selected coarse cell.
refined_R (np.ndarray of shape (n_refined, nnx, nny)) – R-coordinate values corresponding to each refined sub-grid point.
Notes
The refinement mask is computed internally via build_mask_to_refine.
Each selected coarse cell is subdivided into an nnx × nny sub-grid.
Bilinear interpolation is performed using precomputed vertex weights
(self.xxxx, self.yyyy). - Output is structured per refined cell, not a full fine global grid.
- build_from_refined_jtor(unrefined_jtor: ndarray, refined_jtor: ndarray) ndarray[source]
Reconstruct a coarse-grid Jtor field by averaging refined sub-grid values back onto the original (nx, ny) mesh.
For each selected coarse cell, the corresponding refined sub-grid (nnx × nny) is first masked to remove points outside the limiter. The remaining values are then spatially averaged and used to replace the coarse-grid value.
- Parameters:
unrefined_jtor (np.ndarray of shape (nx, ny)) – Original coarse-grid toroidal current density.
refined_jtor (np.ndarray of shape (n_refined, nnx, nny)) – Refined Jtor values on sub-grids for each selected coarse cell.
- Returns:
Updated Jtor field where selected cells have been replaced by averaged refined values and all other cells remain unchanged.
- Return type:
np.ndarray of shape (nx, ny)
Notes
Refinement contributions are masked using self.full_masks to
exclude points outside the limiter. - Each coarse cell is updated independently; no smoothing is applied between neighboring refined regions. - The output preserves the original grid structure.
- build_jtor_gradient_mask(unrefined_jtor: ndarray, threshold: float, quantiles: tuple[float, float] = (0.5, 0.9)) ndarray[source]
Construct a refinement mask based on local finite-difference variations of Jtor.
Cells are selected when the magnitude of local Jtor differences between neighbouring grid points exceeds a threshold derived from the distribution of these differences.
The method approximates spatial variation using forward finite differences in both R and Z directions, and applies a quantile-based thresholding strategy (via build_jtor_value_mask) to identify large-gradient regions.
- Parameters:
unrefined_jtor (np.ndarray) – Coarse-grid toroidal current density field.
threshold (float) – Scaling factor applied to the inter-quantile range of gradient magnitudes used for refinement.
quantiles (tuple of float, optional) – (q_low, q_high) quantiles used to normalise gradient magnitude thresholds. Default is (0.5, 0.9).
- Returns:
Boolean mask indicating cells selected for refinement.
- Return type:
np.ndarray (bool)
- build_jtor_value_mask(unrefined_jtor: ndarray, threshold: float, quantiles: tuple[float, float] = (0.5, 0.9)) ndarray[source]
Construct a refinement mask based on the magnitude of Jtor.
Cells are selected for refinement if their Jtor value exceeds a scaled threshold defined relative to two quantiles of the Jtor distribution.
- Parameters:
unrefined_jtor (np.ndarray) – Coarse-grid toroidal current density field.
threshold (float) – Scaling factor applied to the inter-quantile range to determine refinement sensitivity.
quantiles (tuple of float, optional) – Two quantiles (q_low, q_high) used to define a reference range. Default is (0.5, 0.9).
- Returns:
Boolean mask indicating cells selected for refinement.
- Return type:
np.ndarray (bool)
- build_mask_to_refine(unrefined_jtor: ndarray, core_mask: ndarray, thresholds: tuple[float, float]) None[source]
Construct the global refinement mask combining LCFS location, Jtor magnitude, and Jtor gradient criteria.
This method aggregates multiple refinement indicators into a single cell-wise mask. A cell is marked for refinement if it satisfies any of the following conditions:
It lies adjacent to the LCFS (core–vacuum interface)
Its Jtor value exceeds a threshold based on distribution quantiles
Its Jtor gradient exceeds a threshold based on distribution quantiles
Boundary cells are excluded from refinement.
- The intermediate masks are also stored as attributes for diagnostics:
self.lcfs_mask
self.value_mask
self.gradient_mask
- Parameters:
unrefined_jtor (np.ndarray of shape (nx, ny)) – Toroidal current density on the coarse grid.
core_mask (np.ndarray of shape (nx, ny)) – Binary mask identifying plasma core cells. Typically 1 inside plasma, 0 outside.
thresholds (tuple of float) – (jtor_threshold, gradient_threshold) Scaling factors applied to inter-quantile ranges used to define refinement sensitivity.
Notes
The result is stored in
self.mask_to_refine(np.ndarray of bool).
- copy() Jtor_refiner[source]
Create a deep copy of the Jtor_refiner object.
- Returns:
A new instance with the same configuration and precomputed refinement structures.
- Return type:
Notes
Array-like attributes such as grid geometry and masks are copied using
copy_into. - Derived refinement structures are recomputed via prepare_for_refinement(). - Optional attributes (e.g. LCFS and refinement masks) are copied if present, otherwise they are ignored (strict=False).
- get_indexes_for_refinement(mask_to_refine: ndarray) tuple[ndarray, ndarray][source]
Construct index arrays for bilinear interpolation on refined cells.
For each selected coarse grid cell, this function returns the indices of the 2×2 stencil (four surrounding vertices) required to perform bilinear interpolation of ψ on the refined subgrid.
- Parameters:
mask_to_refine (np.ndarray (bool)) – Boolean mask of coarse grid cells selected for refinement, shape (nx, ny).
- Returns:
RRidxs (np.ndarray) – R-index stencil for each selected cell, shape (n_cells, 4, 2, 2): one 2×2 vertex stencil per quadrant of the cell (see quartermasks).
ZZidxs (np.ndarray) – Z-index stencil matching RRidxs structure.
Notes
Each cell contributes a structured 2×2 vertex stencil used for vectorised bilinear interpolation of ψ on the nnx × nny subgrid.
- prepare_for_refinement() None[source]
Precompute geometric, interpolation, and masking structures used in Jtor refinement.
This method builds all static quantities required for sub-grid refinement, including: - coarse-grid index maps (Ridx, Zidx), - sub-cell coordinate systems, - bilinear interpolation weights, - limiter-based inside/outside masks at refined resolution, - quadrant decomposition masks for vectorised operations.
These arrays are reused across refinement calls to avoid recomputation.
Notes
Assumes a uniform structured grid in (R, Z).
Sub-cell structure is defined by (nnx × nny) refinement per cell.
Limiter geometry is accessed via self.path.contains_points.