Utilities API¶
Utilities cover caching, sampling, target-coordinate handling, spectral helpers, sample weights, and plotting helpers.
Cache Utilities¶
cache_result ¶
cache_result(prefix: str, max_size: int = DEFAULT_MAX_CACHE_SIZE, max_age_days: float = DEFAULT_MAX_CACHE_AGE, key_gen_func: Callable | None = None) -> Callable
Decorator that caches function results based on all function and class instance parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Prefix for the cache directory (e.g., 'preprocess', 'featurize') |
required |
max_size
|
int
|
Maximum cache size in bytes for this prefix |
DEFAULT_MAX_CACHE_SIZE
|
max_age_days
|
float
|
Maximum age of cache files in days |
DEFAULT_MAX_CACHE_AGE
|
key_gen_func
|
Callable | None
|
Optional function to generate the cache key dictionary. If None, a default key generation logic is used. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
Decorated function |
Source code in xdflow/utils/cache_utils.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | |
get_pipeline_cache_key_dict ¶
get_pipeline_cache_key_dict(func: Callable, instance: Any, *args, **kwargs) -> dict[str, Any]
Generate a cache key dictionary for a pipeline.
This function creates a detailed dictionary that includes: - The function's arguments. - The configuration of the pipeline instance and all its nested transforms. - The code hashes of the modules of the pipeline and all its transforms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
The function being called (e.g., fit_transform). |
required |
instance
|
Any
|
The pipeline instance. |
required |
*args
|
Positional arguments to the function. |
()
|
|
**kwargs
|
Keyword arguments to the function. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary to be hashed for the cache key. |
Source code in xdflow/utils/cache_utils.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
clear_cache ¶
clear_cache(prefix: str | None = None) -> None
Clear the cache for a given prefix or all caches if no prefix is specified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str | None
|
Optional prefix to clear specific cache directory |
None
|
Source code in xdflow/utils/cache_utils.py
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 | |
Sampling Utilities¶
get_container_by_conditions ¶
get_container_by_conditions(container: DataContainer, conditions: dict) -> DataContainer
Get a container by conditions.
Source code in xdflow/utils/sampling.py
12 13 14 15 16 | |
get_da_by_conditions ¶
get_da_by_conditions(da: DataArray, conditions: dict[str, Any]) -> xr.DataArray
Select a DataArray subset based on flexible coordinate conditions.
Each condition can be
- single value → equality
- list → membership
- tuple of 2 → range (inclusive)
- dict with comparison operator → inequalities e.g. {'>': 5}, {'<=': 10}
Example: conditions = { "latitude": {">": 15}, # latitude > 15 "time": {"<=": 2}, # time <= 2 "depth": (10, 30), # between 10 and 30 (inclusive) "channel": [1, 3, 5], # in [1, 3, 5] "animal": 35 # equals 35 }
Source code in xdflow/utils/sampling.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
train_test_split_container ¶
train_test_split_container(container: DataContainer, target_coord: str, test_size: float = 0.2, random_state: int | None = None) -> tuple[DataContainer, DataContainer]
Split a container into train and test sets.
Source code in xdflow/utils/sampling.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
stratified_sample ¶
stratified_sample(da, coord_name, max_samples_per_class=10, random_state=None) -> xr.DataArray
Perform stratified sampling on categorical coordinates.
TODO: add support for non-categorical coordinates and balanced classes.¶
Parameters:¶
da : xr.DataArray Input data array coord_name : str Name of categorical coordinate to stratify on max_samples_per_class : int Maximum number of samples per category/class random_state : int, optional Random seed for reproducibility
Returns:¶
xr.DataArray Stratified sample with max_samples_per_class from each category
Source code in xdflow/utils/sampling.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |
sample_by_max_count ¶
sample_by_max_count(indices: ndarray, labels: ndarray, max_samples: int) -> np.ndarray
Sample up to max_samples from each class.
Source code in xdflow/utils/sampling.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
sample_by_fraction ¶
sample_by_fraction(indices: ndarray, labels: ndarray, all_labels: ndarray, sample_fraction: float) -> np.ndarray
Sample a fraction of each class based on the whole dataset.
Source code in xdflow/utils/sampling.py
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | |
get_group_dim ¶
get_group_dim(container: DataContainer, group_coord: str) -> str
Resolves the dimension that the group_coord indexes.
Source code in xdflow/utils/sampling.py
206 207 208 209 210 211 212 213 214 215 216 217 | |
discover_groups ¶
discover_groups(container: DataContainer, group_coord: str) -> list[Hashable]
Discovers unique group values from the data.
Source code in xdflow/utils/sampling.py
220 221 222 223 | |
select_group ¶
select_group(container: DataContainer, group_coord: str, group_val: Hashable) -> DataContainer
Selects data for a specific group using boolean indexing.
Source code in xdflow/utils/sampling.py
226 227 228 229 230 | |
Target Utilities¶
resolve_target_coords ¶
resolve_target_coords(target_coord: str | Sequence[str], data: DataArray) -> list[str]
Accept a single coord name, an explicit list/tuple of coord names, or a glob pattern (e.g., "*_target").
Returns a validated list of coord names present in data.
Pattern matching is only activated when the string contains a * wildcard character.
Explicit coordinate names are matched exactly.
Source code in xdflow/utils/target_utils.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | |
extract_target_array ¶
extract_target_array(target_coord: str | Sequence[str], data: DataArray, validate: bool = True) -> np.ndarray
Resolve target coordinates and return a stacked numpy array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_coord
|
str | Sequence[str]
|
String pattern/name or iterable of coord names. If |
required |
data
|
DataArray
|
DataArray containing target coords. |
required |
validate
|
bool
|
Whether to validate/resolve the target coordinates. Defaults to True. |
True
|
Source code in xdflow/utils/target_utils.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | |
Sample-Weight Utilities¶
extract_sample_weights ¶
extract_sample_weights(data: DataArray, sample_dim: str, coord_name: str | None, sample_index: Index | DataArray | None = None) -> np.ndarray | None
Extract 1D sample weights aligned to a sample dimension.
Source code in xdflow/utils/sample_weights.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | |
Spectral Utilities¶
bandpass_filter ¶
bandpass_filter(data, lowcut, highcut, order=4, fs=500, causal=False, axis=-1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
|
required | |
lowcut
|
|
required | |
highcut
|
|
required | |
order
|
(Default value = 4) |
4
|
|
fs
|
Default value = 500) |
500
|
|
causal
|
Default value = False) |
False
|
|
axis
|
Default value = -1) |
-1
|
Returns:
Source code in xdflow/utils/spectral.py
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
get_remove_freq_ranges ¶
get_remove_freq_ranges(num_bands_remove, freqs, remove_high=True)
Removes a specified number of frequency bands from the frequency ranges dictionary, starting with high or low frequency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_bands_remove
|
Number of frequency bands to remove |
required | |
freqs
|
Dictionary of frequency ranges (e.g., {'theta': (4, 8), 'beta': (13, 30)}) |
required | |
remove_high
|
Boolean indicating whether to remove high (Default value = True) |
True
|
Returns:
| Type | Description |
|---|---|
|
Modified frequency ranges dictionary with the specified number of frequency bands removed. |
Source code in xdflow/utils/spectral.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
get_freq_band_indices ¶
get_freq_band_indices(frequencies, low, high)
Returns the indices of the beginning and end of a frequency band.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequencies
|
Sorted array of frequencies |
required | |
low
|
Lower bound of the frequency band |
required | |
high
|
Upper bound of the frequency band |
required |
Returns:
| Type | Description |
|---|---|
|
List with start and end indices of the frequency band. |
Source code in xdflow/utils/spectral.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | |
Visualization Utilities¶
plot_confusion_matrix ¶
plot_confusion_matrix(confusion_matrix: ndarray, labels: Iterable[Any], want_plot: bool = False, want_confus: bool = False, save_as: str | None = None, title: str = 'Confusion Matrix', test_trues: Iterable[Any] | None = None, ylabels: Iterable[Any] | None = None, xlabels: Iterable[Any] | None = None, ax=None, show_plot: bool = True, show_annotations: bool = True, cmap: str = 'Blues')
Plot a confusion matrix heatmap with optional annotations.
Returns:
| Type | Description |
|---|---|
|
The matplotlib module if want_plot is True. |
Source code in xdflow/utils/visualizations.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
plot_combined_confusion_matrix ¶
plot_combined_confusion_matrix(confusion_matrices: Iterable[ndarray], labels: Iterable[Any], f1_scores: Iterable[float] | None = None, sample_sizes: ndarray | None = None, test_trues: Iterable[Iterable[Any]] | None = None, want_plot: bool = False, want_confus: bool = False, title: str | None = None, save_as: str | None = None, xlabels: Iterable[Any] | None = None, ylabels: Iterable[Any] | None = None, cmap: str = 'Blues')
Plot mean confusion matrix with standard error annotations across folds.
Source code in xdflow/utils/visualizations.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
plot_tune_importances ¶
plot_tune_importances(study, *, want_plot: bool = True)
Plot Optuna parameter importances for a study.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
study
|
Optuna study object. |
required | |
want_plot
|
bool
|
Whether to return the matplotlib module. |
True
|
Source code in xdflow/utils/visualizations.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | |