iful.util

Utility functions for numerical analysis, geometry, kinematic profile evaluation, image masking, and MCMC post-processing.

Functions

arctan_1d(A, B, r)

Evaluate 1D arctan velocity profile: A * arctan(B * r).

arctan_2d(PA, A, B, C, c0, c1, r0, r1)

Evaluate 2D arctan velocity field given major axis position angle and center.

avg_dist(beta_ra, beta_dec[, c_loc])

Compute mean Euclidean distance from points to mean position or reference location.

calculate_fwhm(amplitudes, sigmas)

Calculate the Full Width at Half Maximum (FWHM) for a sum of centered Gaussians.

check_bounds_proximity(params, lower_bounds, ...)

Check whether parameter values are close to or outside lower/upper parameter bounds.

check_list(variable)

Check if a variable is a list or NumPy ndarray.

check_near_bounds(results, lowers, uppers, ind)

Print warnings if parameter fit results lie near boundary limits (within 1e-3).

check_within_bounds(inits, lowers, uppers)

Print warnings for initial parameter values outside specified lower and upper bounds.

create_gif(image_paths, output_gif_path[, ...])

Assemble a sequence of saved PNG images into an animated GIF file.

distance_2d(x0, y0, x1, y1)

Compute 2D Euclidean distance between (x0, y0) and (x1, y1).

distance_to_line(point, line_point, ...)

Calculate perpendicular distance from a point to a line specified by a point and position angle.

find_closest_point_indices(points, target_points)

Find indices of nearest source grid points for each target coordinate within a radius threshold.

gen_gif(data_datacube, model_datacube, ...)

Generate an animated GIF showing data, model, and residual maps slice-by-slice along wavelength.

gen_obs_gif(data_datacube, mask_3d, waves, name)

Generate an animated GIF showing datacube channel slices alongside the integrated spectrum.

get_outlier_mask_iqr(data[, scale_l, scale_u])

Compute a 2D boolean mask filtering out Interquartile Range (IQR) outliers.

get_p_value(fitting_seq, kwargs_model, mask)

Calculate p-value for the reduced chi-squared fit statistic.

get_reduced_chi_sq(fitting_seq, ...)

Calculate reduced chi-squared statistic using Lenstronomy ModelPlot.

homography_loss(points_src, points_dst)

Compute minimal squared distance loss between four source and target 2D points.

is_border_all_nan(arr_2d)

Check whether all perimeter border elements of a 2D array are NaN.

least_squares_mean_loss(points_src[, return_loc])

Compute sum of distances from 2D points to their mean location.

mask_circle(x, y, rad, shape)

Create a 2D mask array with zeros inside a circle of given radius and center.

min_total_squared_distance(...)

Calculate minimal total squared assignment distance between observed and predicted image locations.

multiparam_1d(Vt, Rt, beta, xi, r)

Evaluate 1D multi-parameter rotation curve (Courteau / Catinella profile).

multiparam_2d(PA, Vt, Rt, beta, xi, C, c0, ...)

Evaluate 2D multi-parameter velocity field.

norm_dist(amp, mu, std, x)

Evaluate 1D unnormalized Gaussian distribution: amp * exp(-0.5 * ((x - mu)/std)^2).

prune_mcmc_chains(traces[, ...])

Identify and prune stagnant or outlier MCMC walker chains based on variance and median absolute deviation.

rename_repeats(strings)

Append numerical suffixes to repeated strings in a list (e.g. ['a', 'a'] -> ['a0', 'a1']).

rotate_points(points, e1, e2)

Rotate 2D coordinates according to ellipticity parameters (e1, e2).

sum_of_gaussians(x, amplitudes, sigmas)

Sum multiple centered 1D Gaussians: sum(A_i * exp(-x^2 / (2 * sig_i^2))).

tanh_1d(A, B, r)

Evaluate 1D tanh velocity profile: A * tanh(r / B).

tanh_2d(PA, A, B, C, c0, c1, r0, r1)

Evaluate 2D tanh velocity field.

iful.util.arctan_1d(A, B, r)[source]

Evaluate 1D arctan velocity profile: A * arctan(B * r).

Parameters:
  • A (float) – Asymptotic velocity scale.

  • B (float) – Turnover scale parameter.

  • r (float or numpy.ndarray) – Distance from center along major axis.

Returns:

Modeled velocity value(s).

Return type:

float or numpy.ndarray

iful.util.arctan_2d(PA, A, B, C, c0, c1, r0, r1)[source]

Evaluate 2D arctan velocity field given major axis position angle and center.

Parameters:
  • PA (float) – Kinematic position angle in degrees.

  • A (float) – Asymptotic velocity amplitude.

  • B (float) – Spatial scaling parameter.

  • C (float) – Systemic velocity offset.

  • c0 (float) – Kinematic center coordinates (x0, y0).

  • c1 (float) – Kinematic center coordinates (x0, y0).

  • r0 (float or numpy.ndarray) – Evaluation grid coordinates (x, y).

  • r1 (float or numpy.ndarray) – Evaluation grid coordinates (x, y).

Returns:

Evaluated 2D arctan velocity model values.

Return type:

float or numpy.ndarray

iful.util.avg_dist(beta_ra, beta_dec, c_loc=None)[source]

Compute mean Euclidean distance from points to mean position or reference location.

Parameters:
  • beta_ra (array-like) – RA coordinates.

  • beta_dec (array-like) – Dec coordinates.

  • c_loc (tuple of float, optional) – Reference position (ra_0, dec_0). Defaults to mean of inputs.

Returns:

Average distance.

Return type:

float

iful.util.calculate_fwhm(amplitudes, sigmas)[source]

Calculate the Full Width at Half Maximum (FWHM) for a sum of centered Gaussians.

Parameters:
  • amplitudes (list of float) – Amplitudes of component Gaussians.

  • sigmas (list of float) – Standard deviations of component Gaussians.

Returns:

Calculated FWHM value.

Return type:

float

iful.util.check_bounds_proximity(params, lower_bounds, upper_bounds, atol=0.001, rtol=1e-05)[source]

Check whether parameter values are close to or outside lower/upper parameter bounds.

Parameters:
  • params (array-like) – Current parameter values.

  • lower_bounds (array-like) – Lower bound constraints.

  • upper_bounds (array-like) – Upper bound constraints.

  • atol (float, default=1e-3) – Absolute tolerance margin.

  • rtol (float, default=1e-5) – Relative tolerance margin.

Returns:

Dictionary containing boolean arrays for violations and is_safe flag.

Return type:

dict

iful.util.check_list(variable)[source]

Check if a variable is a list or NumPy ndarray.

Parameters:

variable (object) – Variable to inspect.

Returns:

True if variable is a list or numpy.ndarray, False otherwise.

Return type:

bool

iful.util.check_near_bounds(results, lowers, uppers, ind)[source]

Print warnings if parameter fit results lie near boundary limits (within 1e-3).

Parameters:
  • results (dict) – Fit result parameters.

  • lowers (dict) – Lower bounds dictionary.

  • uppers (dict) – Upper bounds dictionary.

  • ind (int or str) – Profile or component index identifier.

iful.util.check_within_bounds(inits, lowers, uppers)[source]

Print warnings for initial parameter values outside specified lower and upper bounds.

Parameters:
  • inits (dict) – Initial parameter dictionary.

  • lowers (dict) – Lower bounds dictionary.

  • uppers (dict) – Upper bounds dictionary.

iful.util.create_gif(image_paths, output_gif_path, duration=300, loop=0)[source]

Assemble a sequence of saved PNG images into an animated GIF file.

Parameters:
  • image_paths (list of str) – Ordered file paths to input frame images.

  • output_gif_path (str) – Output file path for generated GIF.

  • duration (int, default=300) – Display duration per frame in milliseconds.

  • loop (int, default=0) – Number of loops (0 means loop infinitely).

iful.util.distance_2d(x0, y0, x1, y1)[source]

Compute 2D Euclidean distance between (x0, y0) and (x1, y1).

Parameters:
  • x0 (float) – First point coordinates.

  • y0 (float) – First point coordinates.

  • x1 (float) – Second point coordinates.

  • y1 (float) – Second point coordinates.

Returns:

Euclidean distance.

Return type:

float

iful.util.distance_to_line(point, line_point, angle_degrees)[source]

Calculate perpendicular distance from a point to a line specified by a point and position angle.

Parameters:
  • point (tuple of float) – Target coordinate (x1, y1).

  • line_point (tuple of float) – Reference point on line (x0, y0).

  • angle_degrees (float) – Position angle of the line in degrees.

Returns:

Perpendicular distance to the line.

Return type:

float

iful.util.find_closest_point_indices(points, target_points, threshold=2)[source]

Find indices of nearest source grid points for each target coordinate within a radius threshold.

Parameters:
  • points (array-like) – Available grid point coordinates.

  • target_points (array-like) – Target point coordinates to match.

  • threshold (float, default=2) – Maximum allowed radial distance threshold. Target points beyond this return NaN.

Returns:

List of matching point indices (or NaN if outside threshold).

Return type:

list

iful.util.gen_gif(data_datacube, model_datacube, var_datacube, mask_3d, waves, name, overwrite=True, pixscale=None)[source]

Generate an animated GIF showing data, model, and residual maps slice-by-slice along wavelength.

Parameters:
  • data_datacube (numpy.ndarray) – Observed 3D datacube (N_wave, N_x, N_y).

  • model_datacube (numpy.ndarray) – Model 3D datacube matching data shape.

  • var_datacube (numpy.ndarray) – Variance 3D datacube.

  • mask_3d (numpy.ndarray) – 3D binary mask cube.

  • waves (numpy.ndarray) – 1D wavelength array.

  • name (str) – Output GIF filename.

  • overwrite (bool, default=True) – Whether to overwrite existing file.

  • pixscale (float, optional) – Pixel scale for spatial extent labeling (arcsec or degrees).

iful.util.gen_obs_gif(data_datacube, mask_3d, waves, name, overwrite=True, spectrum=None, vmin=None, vmax=None, pixscale=None)[source]

Generate an animated GIF showing datacube channel slices alongside the integrated spectrum.

Parameters:
  • data_datacube (numpy.ndarray) – 3D observed datacube.

  • mask_3d (numpy.ndarray) – 3D binary mask.

  • waves (numpy.ndarray) – 1D wavelength array.

  • name (str) – Output GIF filename.

  • overwrite (bool, default=True) – Whether to overwrite existing GIF file.

  • spectrum (numpy.ndarray, optional) – Custom 1D spectrum to display in side panel. Defaults to integrated flux spectrum.

  • vmin (float, optional) – Display intensity range bounds.

  • vmax (float, optional) – Display intensity range bounds.

  • pixscale (float, optional) – Pixel scale for spatial extent labeling.

iful.util.get_outlier_mask_iqr(data, scale_l=5, scale_u=30)[source]

Compute a 2D boolean mask filtering out Interquartile Range (IQR) outliers.

Parameters:
  • data (numpy.ndarray) – 2D input array.

  • scale_l (float, default=5) – Lower IQR multiplier.

  • scale_u (float, default=30) – Upper IQR multiplier.

Returns:

2D boolean array (True for in-range pixels, False for outliers).

Return type:

numpy.ndarray

iful.util.get_p_value(fitting_seq, kwargs_model, mask)[source]

Calculate p-value for the reduced chi-squared fit statistic.

Parameters:
  • fitting_seq (Lenstronomy FittingSequence) – Fitting sequence.

  • kwargs_model (dict) – Model dictionary.

  • mask (numpy.ndarray) – 2D binary mask.

Returns:

Survival function p-value.

Return type:

float

iful.util.get_reduced_chi_sq(fitting_seq, kwargs_model, mask)[source]

Calculate reduced chi-squared statistic using Lenstronomy ModelPlot.

Parameters:
  • fitting_seq (Lenstronomy FittingSequence) – Fitted sequence containing band list and best-fit parameters.

  • kwargs_model (dict) – Model configuration dictionary.

  • mask (numpy.ndarray) – 2D likelihood mask array.

Returns:

Reduced chi-squared statistic.

Return type:

float

iful.util.homography_loss(points_src, points_dst)[source]

Compute minimal squared distance loss between four source and target 2D points.

Parameters:
  • points_src (list or array-like) – 4 source 2D coordinates.

  • points_dst (list or array-like) – 4 destination 2D coordinates.

Returns:

Total minimum squared assignment loss.

Return type:

float

iful.util.is_border_all_nan(arr_2d)[source]

Check whether all perimeter border elements of a 2D array are NaN.

Parameters:

arr_2d (numpy.ndarray) – 2D array to inspect.

Returns:

True if all border elements are NaN, False otherwise.

Return type:

bool

iful.util.least_squares_mean_loss(points_src, return_loc=False)[source]

Compute sum of distances from 2D points to their mean location.

Parameters:
  • points_src (array-like) – Collection of 2D points.

  • return_loc (bool, default=False) – If True, return mean location vector instead of loss value.

Returns:

Distance loss value or mean location array.

Return type:

float or numpy.ndarray

iful.util.mask_circle(x, y, rad, shape)[source]

Create a 2D mask array with zeros inside a circle of given radius and center.

Parameters:
  • x (float) – Center pixel coordinates of circular region.

  • y (float) – Center pixel coordinates of circular region.

  • rad (float) – Radius of circular region (in pixels).

  • shape (tuple of int) – Output 2D array shape (N_row, N_col).

Returns:

2D mask array with 0.0 inside circle and 1.0 outside.

Return type:

numpy.ndarray

iful.util.min_total_squared_distance(observed_locations, predicted_locations)[source]

Calculate minimal total squared assignment distance between observed and predicted image locations.

Parameters:
  • observed_locations (array-like) – Observed image coordinates.

  • predicted_locations (array-like) – Model-predicted image coordinates.

Returns:

Minimum total squared distance.

Return type:

float

iful.util.multiparam_1d(Vt, Rt, beta, xi, r)[source]

Evaluate 1D multi-parameter rotation curve (Courteau / Catinella profile).

Parameters:
  • Vt (float) – Turnover velocity amplitude.

  • Rt (float) – Turnover radius.

  • beta (float) – Outer slope parameter.

  • xi (float) – Inner sharpness parameter.

  • r (float or numpy.ndarray) – Distance along major axis.

Returns:

Evaluated velocity.

Return type:

float or numpy.ndarray

iful.util.multiparam_2d(PA, Vt, Rt, beta, xi, C, c0, c1, r0, r1)[source]

Evaluate 2D multi-parameter velocity field.

Parameters:
  • PA (float) – Kinematic position angle in degrees.

  • Vt (float) – Turnover velocity.

  • Rt (float) – Turnover radius.

  • beta (float) – Outer slope index.

  • xi (float) – Inner transition sharpness.

  • C (float) – Systemic velocity offset.

  • c0 (float) – Center coordinates (x0, y0).

  • c1 (float) – Center coordinates (x0, y0).

  • r0 (float or numpy.ndarray) – Evaluation grid coordinates.

  • r1 (float or numpy.ndarray) – Evaluation grid coordinates.

Returns:

Evaluated velocity field.

Return type:

float or numpy.ndarray

iful.util.norm_dist(amp, mu, std, x)[source]

Evaluate 1D unnormalized Gaussian distribution: amp * exp(-0.5 * ((x - mu)/std)^2).

Parameters:
  • amp (float) – Peak amplitude.

  • mu (float) – Mean / center position.

  • std (float) – Standard deviation (width).

  • x (float or numpy.ndarray) – Evaluation coordinate(s).

Returns:

Evaluated Gaussian profile value(s).

Return type:

float or numpy.ndarray

iful.util.prune_mcmc_chains(traces, deviation_threshold=3.5, stagnancy_threshold=0.01, split=False)[source]

Identify and prune stagnant or outlier MCMC walker chains based on variance and median absolute deviation.

Parameters:
  • traces (numpy.ndarray) – MCMC walker chain array of shape (nwalkers, nsteps, nparams).

  • deviation_threshold (float, default=3.5) – Modified Z-score threshold for identifying outlier walker means.

  • stagnancy_threshold (float, default=0.01) – Relative variance threshold below which a walker is classified as stagnant.

  • split (bool, default=False) – If True, return two flattened chain subsets (first third and last third of steps).

Returns:

Pruned walker chain array (or pair of split chain arrays if split=True).

Return type:

numpy.ndarray or tuple of numpy.ndarray

iful.util.rename_repeats(strings)[source]

Append numerical suffixes to repeated strings in a list (e.g. [‘a’, ‘a’] -> [‘a0’, ‘a1’]).

Parameters:

strings (list of str) – Input list of string identifiers.

Returns:

List with repeated items indexed by numerical suffix.

Return type:

list of str

iful.util.rotate_points(points, e1, e2)[source]

Rotate 2D coordinates according to ellipticity parameters (e1, e2).

Parameters:
  • points (array-like) – Array of (x, y) coordinates.

  • e1 (float) – Ellipticity components.

  • e2 (float) – Ellipticity components.

Returns:

Rotated (x, y) coordinates array.

Return type:

numpy.ndarray

iful.util.sum_of_gaussians(x, amplitudes, sigmas)[source]

Sum multiple centered 1D Gaussians: sum(A_i * exp(-x^2 / (2 * sig_i^2))).

Parameters:
  • x (float or numpy.ndarray) – Evaluation coordinate.

  • amplitudes (list of float) – Gaussian peak amplitudes.

  • sigmas (list of float) – Gaussian widths.

Returns:

Summed Gaussian profile value.

Return type:

float or numpy.ndarray

iful.util.tanh_1d(A, B, r)[source]

Evaluate 1D tanh velocity profile: A * tanh(r / B).

Parameters:
  • A (float) – Asymptotic velocity scale.

  • B (float) – Scale radius.

  • r (float or numpy.ndarray) – Distance along major axis.

Returns:

Modeled velocity profile.

Return type:

float or numpy.ndarray

iful.util.tanh_2d(PA, A, B, C, c0, c1, r0, r1)[source]

Evaluate 2D tanh velocity field.

Parameters:
  • PA (float) – Kinematic position angle in degrees.

  • A (float) – Asymptotic velocity amplitude.

  • B (float) – Scale radius parameter.

  • C (float) – Systemic velocity offset.

  • c0 (float) – Kinematic center (x0, y0).

  • c1 (float) – Kinematic center (x0, y0).

  • r0 (float or numpy.ndarray) – Evaluation position(s).

  • r1 (float or numpy.ndarray) – Evaluation position(s).

Returns:

Evaluated 2D tanh velocity field values.

Return type:

float or numpy.ndarray