sarcasm.utils
Classes
Miscellaneous utility functions |
Module Contents
- class sarcasm.utils.Utils[source]
Miscellaneous utility functions
- static get_device(print_device=False, no_cuda_warning=False)[source]
Determines the most suitable device (CUDA, MPS, or CPU) for PyTorch operations.
Parameters: - print_device (bool): If True, prints the device being used. - no_cuda_warning (bool): If True, prints a warning if neither CUDA nor MPS is available.
Returns: - torch.device: The selected device for PyTorch operations.
- static today_date()[source]
Get today’s date in the format ‘YYYYMMDD’.
- Returns:
Today’s date in ‘YYYYMMDD’ format.
- Return type:
str
- static get_tif_files_in_folder(folder: str) List[str] [source]
Find all .tif files in a specified folder.
- Parameters:
folder (str) – Path to the folder.
- Returns:
List of file paths to the .tif files.
- Return type:
list
- static get_lois_of_file(filename_cell: str) List[Tuple[str, str]] [source]
Get the lines of interests (LOIs) of a tif-file.
- Parameters:
filename_cell (str) – Path to the file of the cell.
- Returns:
List of tuples, each containing the cell file path and LOI filename.
- Return type:
list
- static open_folder(path: str)[source]
Open a folder in the file explorer.
- Parameters:
path (str) – Path to the folder.
- static two_sample_t_test(data: numpy.ndarray, alpha: float = 0.05) Tuple[numpy.ndarray, numpy.ndarray] [source]
Pair-wise two sample t-test of multiple conditions.
- Parameters:
data (array-like) – Input data for the t-test.
alpha (float, optional) – Significance level. Default is 0.05.
- Returns:
p-values and significance levels for each pair of conditions.
- Return type:
tuple
- static nan_sav_golay(data: numpy.ndarray, window_length: int, polyorder: int, axis: int = 0) numpy.ndarray [source]
Apply a Savitzky-Golay filter to data with NaN values along the specified axis.
- Parameters:
data (array-like) – Input data.
window_length (int) – Length of the filter window, must be odd and greater than polyorder.
polyorder (int) – Order of the polynomial used for the filtering.
axis (int, optional) – The axis along which to apply the filter. The default is 0 (first axis).
- Returns:
Filtered data with NaN values preserved.
- Return type:
array-like
- static nan_low_pass(x: numpy.ndarray, N: int = 6, crit_freq: float = 0.25, min_len: int = 31) numpy.ndarray [source]
Apply a Butterworth low-pass filter to data with NaN values.
- Parameters:
x (np.ndarray) – Input data.
N (int, optional) – Filter order. The higher the order, the steeper the spectral cutoff. Default is 6.
crit_freq (float, optional) – Maximum passed frequency. Default is 0.25.
min_len (int, optional) – Minimum length of data required to apply the filter. Default is 31.
- Returns:
Filtered data with NaN values preserved.
- Return type:
np.ndarray
- static most_freq_val(array: numpy.ndarray, bins: int = 20) numpy.ndarray[Any, numpy.dtype[Any]] [source]
Calculate the most frequent value in an array.
- Parameters:
array (np.ndarray) – Input array.
bins (int, optional) – Number of bins for the histogram calculation. Default is 20.
- Returns:
Most frequent value in the array.
- Return type:
float
- static weighted_avg_and_std(x: numpy.ndarray, weights: numpy.ndarray, axis: int = 0) Tuple[numpy.ndarray, numpy.ndarray] [source]
Return the weighted average and standard deviation.
- Parameters:
x (array-like) – Values.
weights (array-like) – Weights.
axis (int, optional) – Axis along which to compute the average and standard deviation. Default is 0.
- Returns:
Weighted average and weighted standard deviation.
- Return type:
tuple
- static weighted_quantile(data: numpy.ndarray, weights: numpy.ndarray, quantile: float) float | numpy.ndarray[Any, numpy.dtype[Any]] [source]
Compute the weighted quantile of a 1D numpy array.
- Parameters:
data (np.ndarray) – Input array (one dimension array).
weights (np.ndarray) – Array with the weights of the same size of data.
quantile (float) – Desired quantile.
- Returns:
result – Weighted quantile of data.
- Return type:
np.ndarray
- static column_weighted_quantiles(data: numpy.ndarray, weights: numpy.ndarray, quantiles: list) numpy.ndarray [source]
Compute the weighted quantile for each column of a 2D numpy array.
- Parameters:
data (np.ndarray) – Input array (two dimension array).
weights (np.ndarray) – Array with the weights of the same size of data.
quantiles (list of float) – List with desired quantiles.
- Returns:
result – 2D array with weighted quantiles of each data column.
- Return type:
np.array
- static custom_diff(x: numpy.ndarray, dt: float) numpy.ndarray [source]
Compute derivative of x using central differences.
This function computes the derivative of the input time-series x using central differences. At the edges of x, forward and backward differences are used. The time-series x can be either 1D or 2D.
- Parameters:
x (ndarray) – The input time-series, must be 1D or 2D.
dt (float) – The time interval between pos_vectors in x.
- Returns:
v – The derivative of x, has the same shape as x.
- Return type:
ndarray
- static process_profile(profile: numpy.ndarray, pixelsize: float, slen_lims: tuple = (1, 3), thres: float = 0.25, min_dist: float = 1, width: float = 0.5, interp_factor: int = 4) Tuple[float, float] [source]
Find peak distance in a 1D intensity profile using interpolation and center of mass (COM).
This function detects peaks in a normalized 1D intensity profile, optionally interpolates the profile using Akima interpolation, and refines the peak positions using the center of mass within a local window.
- Parameters:
profile (np.ndarray) – 1D intensity profile.
pixelsize (float) – Physical size per pixel.
slen_lims (tuple of float, optional) – (min, max) valid peak separation range, by default (1, 3).
thres (float, optional) – Peak detection height threshold (0-1), by default 0.25.
min_dist (float, optional) – Minimum peak separation in µm, by default 1.
width (float, optional) – Half-width of COM window in µm, by default 0.5.
interp_factor (int, optional) – Interpolation upsampling factor, by default 4. If ≤ 1, no interpolation is performed.
- Returns:
slen_profile (float) – Peak separation distance in micrometer, or np.nan if invalid.
center_offsets (float) – Offset of the profile center in micrometer, or np.nan if invalid.
Notes
For interp_factor ≤ 1, no interpolation is performed and the original profile is used.
The function uses Akima1DInterpolator for smooth interpolation when requested.
Center of mass calculation is performed in a window around each detected peak for sub-pixel accuracy.
If less than two peaks are detected, or the separation is outside slen_lims, returns (np.nan, np.nan).
- static peakdetekt(x_pos, y, thres=0.2, thres_abs=False, min_dist=10, width=6, interp_factor=6)[source]
A customized peak detection algorithm using scipy with Akima interpolation.
- Parameters:
x_pos (ndarray) – An array containing the positions in µm.
y (ndarray) – The intensity profile.
thres (float, optional) – Threshold for the peak detection. Default is 0.3.
thres_abs (bool, optional) – Whether the peak detection threshold is absolute. Default is True.
min_dist (int, optional) – Minimum distance between detected peaks, in pixels. Default is 10.
width (int, optional) – Width of the region of interest around the detected peaks for the method of moments computation. Default is 6.
interp_factor (int, optional) – Factor by which to increase the resolution through interpolation. Default is 10.
- Returns:
refined_peaks – An array containing the refined peak positions in µm.
- Return type:
ndarray
- static peak_by_first_moment(x: numpy.ndarray, y: numpy.ndarray)[source]
Calculate the peak of y using the first moment method.
- Parameters:
x (numpy.ndarray) – The x-values of the data.
y (numpy.ndarray) – The y-values of the data.
- Returns:
peak – The calculated peak value.
- Return type:
float
- static analyze_orientations(orientations: numpy.ndarray)[source]
Calculate the orientational order parameter and mean vector of non-polar elements in 2D. Orientations are expected to be in the range [0, pi]. See https://physics.stackexchange.com/questions/65358/2-d-orientational-order-parameter
- Parameters:
orientations (numpy.ndarray) – Array of orientations. In radians.
- Returns:
oop (float) – The calculated orientational order parameter.
angle (float) – The calculated mean vector angle.
- static correct_phase_confocal(tif_file: str, shift_max=30)[source]
Correct phase shift for images of Leica confocal resonant scanner in bidirectional mode while conserving metadata.
- Parameters:
tif_file (str) – Path to the input .tif file.
shift_max (int, optional) – Maximum allowed shift, by default 30.
- static map_array(array: numpy.ndarray, from_values: List | numpy.ndarray, to_values: List | numpy.ndarray) numpy.ndarray [source]
Map a numpy array from one set of values to a new set of values.
- Parameters:
array (numpy.ndarray) – The input 2D numpy array.
from_values (list) – List of original values.
to_values (list) – List of target values.
- Returns:
out – The array with values mapped from ‘from_values’ to ‘to_values’.
- Return type:
numpy.ndarray
- static shuffle_labels(labels: numpy.ndarray, seed=0)[source]
Shuffle labels randomly
- Parameters:
labels (numpy.ndarray) – The labels to be shuffled.
seed (int, optional) – The seed for the random number generator, by default 0.
- Returns:
labels_shuffled – The input labels, randomly shuffled.
- Return type:
numpy.ndarray
- static get_orientation_angle_map(orientation_field: numpy.ndarray, use_median_filter: bool = True, radius: int = 3) numpy.ndarray [source]
Convert a polar vector field into a map of angles for sarcomere orientations.
The function supports both single-image and multi-image inputs. For single-image inputs, the expected shape is (2, H, W). For multi-image inputs, the expected shape is (N, 2, H, W), where N is the number of images.
- Parameters:
orientation_field (numpy.ndarray) – Polar vector field(s). For a single image, a 3D array of shape (2, H, W). For multiple images, a 4D array of shape (N, 2, H, W).
use_median_filter (bool, optional) – Whether to apply a median filter to the resulting angle map. Default is True.
radius (int, optional) – Radius of the disk-shaped footprint for the median filter. Default is 3.
- Returns:
A 2D or 3D array of angles in radians, mapped to the range [0, π]. If the input is a single image of shape (2, H, W), the output shape is (H, W). If the input contains multiple images of shape (N, 2, H, W), the output shape is (N, H, W).
- Return type:
numpy.ndarray
- static create_distance_map(sarc_obj)[source]
Creates distance map for sarcomeres from a Structure object. The distance map is 0 at Z-bands and 1 at M-bands.
- Parameters:
sarc_obj (Structure) – An object of the Structure class.
- Returns:
distance – A 2D array with normalized distances (0 to 1) along sarcomeres.
- Return type:
numpy.ndarray
- static interpolate_distance_map(image, N=50, method='linear')[source]
Interpolates NaN regions in a 2D image, filling only those regions whose size is less than or equal to a specified threshold.
- Parameters:
image (numpy.ndarray) – A 2D array representing the input image. NaN values represent gaps to be filled.
N (int) – The maximum size (in pixels) of connected NaN regions to interpolate. Regions larger than this threshold will remain unaltered.
method (str, optional) – The interpolation method to use. Options are ‘linear’, ‘nearest’, and ‘cubic’. Default is ‘linear’.
- Returns:
A 2D array with the same shape as the input image, where small NaN regions (size <= N) have been interpolated. Larger NaN regions are left unchanged.
- Return type:
numpy.ndarray
- static fast_profile_lines(image, start_points, end_points, linewidth=3, mode='constant', cval=0.0)[source]
Vectorized version of profile_line from scikit-image that processes multiple lines simultaneously.
- Parameters:
image (ndarray) – The input image from which to sample the profile lines.
start_points (array_like) – An array of shape (N, 2) containing the starting coordinates of the lines.
end_points (array_like) – An array of shape (N, 2) containing the ending coordinates of the lines.
linewidth (int, optional) – The width of the profile line, in pixels. Default is 1.
mode (str, optional) – The mode parameter for map_coordinates. Default is ‘constant’.
cval (float, optional) – The value used for points outside the boundaries of the input image. Default is 0.0.
- Returns:
result – A list containing the sampled profile values for each line.
- Return type:
list of ndarray
- static nanmedian_filter_numba(data, window_size)[source]
Applies a nanmedian filter to a 2D array using a sliding window. The function computes the median of each window ignoring NaN values.
text :param data: 2D numpy array of float
Input array with possible NaN values.
- Parameters:
window_size – int The size (assumed odd) of the square window.
- Returns:
2D numpy array of the same shape as data containing the filtered result.
- Return type:
out