data_io¶
Data loading, preprocessing, and export utilities.
Overview¶
This module handles:
- Loading PLR data from DuckDB/SQLite
- Data preprocessing and validation
- Export to various formats
- Stratification for cross-validation
Data Import¶
data_import
¶
import_PLR_data_wrapper
¶
Import and preprocess PLR data from individual CSV files.
Main import wrapper that handles the complete data loading pipeline: importing raw data, combining with metadata, preparing for imputation, granularizing outlier labels, and stratifying splits.
| PARAMETER | DESCRIPTION |
|---|---|
cfg
|
Configuration dictionary containing DATA and METADATA settings.
TYPE:
|
data_dir
|
Directory for data files, by default None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (df_train, df_test) as Polars dataframes. |
Source code in src/data_io/data_import.py
import_data
¶
Import raw PLR data from individual subject CSV files.
| PARAMETER | DESCRIPTION |
|---|---|
cfg
|
Configuration dictionary containing DATA settings.
TYPE:
|
data_dir
|
Directory for output data files, by default None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Polars dataframe containing all imported subject data. |
Source code in src/data_io/data_import.py
create_csvs_from_individual_subjects
¶
create_csvs_from_individual_subjects(
individual_subjects_dir: str,
data_dir: str,
no_of_timepoints: int = 1981,
cfg: DictConfig = None,
) -> DataFrame
Create a combined dataframe from individual subject CSV files.
| PARAMETER | DESCRIPTION |
|---|---|
individual_subjects_dir
|
Directory containing individual subject CSV files.
TYPE:
|
data_dir
|
Directory for output data files.
TYPE:
|
no_of_timepoints
|
Expected number of timepoints per subject, by default 1981.
TYPE:
|
cfg
|
Configuration dictionary, by default None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Combined pandas dataframe with all subjects. |
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If the individual subjects directory does not exist. |
Source code in src/data_io/data_import.py
convert_list_of_dfs_to_df
¶
Convert a list of subject dataframes into a single combined dataframe.
| PARAMETER | DESCRIPTION |
|---|---|
list_of_dfs
|
List of pandas dataframes, one per subject.
TYPE:
|
outliers
|
List of outlier counts per subject.
TYPE:
|
subject_codes
|
List of subject code identifiers.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Combined dataframe with subject_code and no_outliers columns added. |
Source code in src/data_io/data_import.py
export_split_dataframes
¶
Export train and validation dataframes to CSV files.
| PARAMETER | DESCRIPTION |
|---|---|
df_train
|
Training data dataframe.
TYPE:
|
df_val
|
Validation data dataframe.
TYPE:
|
data_dir
|
Directory to save the CSV files.
TYPE:
|
Source code in src/data_io/data_import.py
define_split
¶
define_split(
subject_codes: list,
csv_subsets: list,
indices: list,
split: str,
drop_raw_pupil_values: bool = False,
)
Create a combined dataframe for a specific train/test split.
| PARAMETER | DESCRIPTION |
|---|---|
subject_codes
|
List of all subject code identifiers.
TYPE:
|
csv_subsets
|
List of dataframes for all subjects.
TYPE:
|
indices
|
Indices of subjects to include in this split.
TYPE:
|
split
|
Name of the split ("train" or "test").
TYPE:
|
drop_raw_pupil_values
|
Whether to drop rows with NaN pupil values, by default False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Combined dataframe for the split. |
Source code in src/data_io/data_import.py
import_master_csv
¶
Import and preprocess a single subject's CSV file.
Performs column selection, time vector quality checks, column renaming, and linear interpolation of color channels.
| PARAMETER | DESCRIPTION |
|---|---|
i
|
Subject index (for first-subject logging).
TYPE:
|
csv_path
|
Path to the subject's CSV file.
TYPE:
|
cfg
|
Configuration dictionary with DATA settings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (no_outliers, csv_subset, subject_code). |
Source code in src/data_io/data_import.py
linear_interpolation_of_col
¶
Apply linear interpolation to fill NaN values in a pandas Series.
| PARAMETER | DESCRIPTION |
|---|---|
column
|
Series with potential NaN values.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Series
|
Series with NaN values linearly interpolated. |
Source code in src/data_io/data_import.py
import_data_from_duckdb
¶
Import PLR data from a DuckDB database file.
| PARAMETER | DESCRIPTION |
|---|---|
data_cfg
|
Data configuration dictionary with filename_DuckDB setting.
TYPE:
|
data_dir
|
Directory containing the DuckDB file.
TYPE:
|
use_demo_data
|
Whether to use demo data instead of full dataset, by default False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (df_train, df_val) as Polars dataframes. |
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If the DuckDB file does not exist. |
Source code in src/data_io/data_import.py
Data Utilities¶
data_utils
¶
convert_sec_to_date
¶
Convert seconds to datetime format in a dataframe column.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe containing the time column.
TYPE:
|
time_col
|
Name of the time column to convert, by default "ds".
TYPE:
|
seconds_offset
|
Offset in seconds to add before conversion, by default 1.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with the time column converted to datetime. |
Source code in src/data_io/data_utils.py
convert_sec_to_millisec
¶
convert_sec_to_millisec(
df: DataFrame,
time_col: str = "ds",
seconds_offset: float = 1,
) -> DataFrame
Convert seconds to milliseconds in a dataframe column.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe containing the time column.
TYPE:
|
time_col
|
Name of the time column to convert, by default "ds".
TYPE:
|
seconds_offset
|
Offset in seconds to add before conversion, by default 1.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with the time column converted to milliseconds. |
Source code in src/data_io/data_utils.py
split_df_to_samples
¶
split_df_to_samples(
df: DataFrame,
split: str = "train",
subject_col_name: str = "unique_id",
) -> dict[str, DataFrame]
Split a dataframe into a dictionary of single-subject dataframes.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe containing multiple subjects.
TYPE:
|
split
|
Name of the data split (for logging), by default "train".
TYPE:
|
subject_col_name
|
Name of the column containing subject identifiers, by default "unique_id".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary mapping subject codes to their respective dataframes. |
Source code in src/data_io/data_utils.py
get_subset_of_data
¶
Extract a time-windowed subset of data from a dataframe.
Filters data to keep only rows within the specified time range and limits to the first 3 subjects (96 rows).
| PARAMETER | DESCRIPTION |
|---|---|
df_subset
|
Input dataframe with a 'ds' time column.
TYPE:
|
t0
|
Start time for filtering, by default 18.0.
TYPE:
|
t1
|
End time for filtering, by default 19.05.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Filtered dataframe containing only data within the time window. |
Source code in src/data_io/data_utils.py
define_split_csv_paths
¶
Define file paths for train and validation CSV files.
| PARAMETER | DESCRIPTION |
|---|---|
data_dir
|
Directory containing the data files.
TYPE:
|
suffix
|
Suffix to append to filenames, by default "".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of Path
|
Tuple containing (train_path, val_path). |
Source code in src/data_io/data_utils.py
import_nonnan_data_from_csv
¶
import_nonnan_data_from_csv(
data_dir: str, suffix: str = "_nonNan"
) -> tuple[DataFrame, DataFrame]
Import PLR data from CSV files with NaN/outlier rows removed.
| PARAMETER | DESCRIPTION |
|---|---|
data_dir
|
Directory containing the CSV files.
TYPE:
|
suffix
|
Suffix for the CSV filenames, by default "_nonNan".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of pl.DataFrame
|
Tuple containing (df_train, df_val) as Polars dataframes. |
Source code in src/data_io/data_utils.py
import_PLR_data_from_CSV
¶
Import PLR data from train and validation CSV files.
| PARAMETER | DESCRIPTION |
|---|---|
data_dir
|
Directory containing the CSV files.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of pl.DataFrame
|
Tuple containing (df_train, df_val) as Polars dataframes. |
Source code in src/data_io/data_utils.py
export_dataframe_to_duckdb
¶
export_dataframe_to_duckdb(
df: DataFrame,
db_name: str,
cfg: DictConfig,
name: Optional[str] = None,
service_name: str = "duckdb",
debug_DuckDBWrite: bool = True,
copy_orig_db: bool = False,
) -> str
Export a Polars dataframe to a DuckDB database.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Polars dataframe to export.
TYPE:
|
db_name
|
Name of the output database file.
TYPE:
|
cfg
|
Configuration dictionary containing DATA settings.
TYPE:
|
name
|
Name identifier for the export, by default None.
TYPE:
|
service_name
|
Service name for artifact directory, by default "duckdb".
TYPE:
|
debug_DuckDBWrite
|
Whether to verify the write by reading back, by default True.
TYPE:
|
copy_orig_db
|
Whether to copy the original database instead of writing new, by default False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Path to the created DuckDB database file. |
Source code in src/data_io/data_utils.py
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 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | |
load_both_splits_from_duckdb
¶
Load and concatenate both train and validation splits from DuckDB.
| PARAMETER | DESCRIPTION |
|---|---|
db_path
|
Path to the DuckDB database file.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Concatenated Polars dataframe containing both splits. |
Source code in src/data_io/data_utils.py
load_from_duckdb_as_dataframe
¶
Load a data split from DuckDB as a Polars dataframe.
| PARAMETER | DESCRIPTION |
|---|---|
db_path
|
Path to the DuckDB database file.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
split
|
Name of the split to load ("train" or "test"), by default "train".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Polars dataframe containing the requested split. |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
If there is an error reading from DuckDB. |
Source code in src/data_io/data_utils.py
export_dataframes_to_duckdb
¶
export_dataframes_to_duckdb(
df_train: Union[DataFrame, DataFrame],
df_test: Union[DataFrame, DataFrame],
db_name: str = "SERI_PLR_GLAUCOMA.db",
data_dir: Optional[str] = None,
debug_DuckDBWrite: bool = True,
) -> str
Export train and test dataframes to a DuckDB database.
Creates separate tables for train and test splits in the database.
| PARAMETER | DESCRIPTION |
|---|---|
df_train
|
Training data dataframe.
TYPE:
|
df_test
|
Test data dataframe.
TYPE:
|
db_name
|
Name of the database file, by default "SERI_PLR_GLAUCOMA.db".
TYPE:
|
data_dir
|
Directory to save the database, by default None.
TYPE:
|
debug_DuckDBWrite
|
Whether to verify the write by reading back, by default True.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Path to the created DuckDB database file. |
Source code in src/data_io/data_utils.py
import_duckdb_as_dataframes
¶
Import train and test dataframes from a DuckDB database.
| PARAMETER | DESCRIPTION |
|---|---|
db_path
|
Path to the DuckDB database file.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of pl.DataFrame
|
Tuple containing (df_train, df_test) as Polars dataframes. |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
If there is an error reading from DuckDB. |
Source code in src/data_io/data_utils.py
check_data_import
¶
Validate imported data splits for data leakage and display statistics.
Checks that no subject appears in both train and validation splits, and optionally displays outlier statistics.
| PARAMETER | DESCRIPTION |
|---|---|
df_train
|
Training data dataframe.
TYPE:
|
df_val
|
Validation data dataframe.
TYPE:
|
display_outliers
|
Whether to display outlier statistics, by default True.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If data leakage is detected (same subject in both splits). |
Source code in src/data_io/data_utils.py
prepare_dataframe_for_imputation
¶
Prepare a dataframe for imputation by fixing light stimuli and setting outliers.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe containing PLR data.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Prepared dataframe ready for imputation. |
Source code in src/data_io/data_utils.py
fix_light_stimuli_vector
¶
Combine Red and Blue channels into a single light stimuli column.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe with Red and Blue columns.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
drop_colors
|
Whether to drop the original Red and Blue columns, by default False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with combined light_stimuli column. |
Source code in src/data_io/data_utils.py
interpolate_missing_light_stimuli_values
¶
interpolate_missing_light_stimuli_values(
df: DataFrame,
cfg: DictConfig,
col_name: str = "light_stimuli",
) -> DataFrame
Interpolate missing values in a light stimuli column.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
col_name
|
Name of the column to interpolate, by default "light_stimuli".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with interpolated values. |
Source code in src/data_io/data_utils.py
set_outliers_to_null
¶
Set outlier values to null in the pupil_raw column based on outlier labels.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe with pupil_raw and outlier_labels columns.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with outliers set to null in pupil_raw column. |
Source code in src/data_io/data_utils.py
set_missing_in_data
¶
set_missing_in_data(
df: DataFrame,
X: ndarray,
_missingness_cfg: DictConfig,
col_name: str = "pupil_raw",
split: str = "train",
) -> ndarray
Set missing values in numpy array based on dataframe null values.
Transfers the missingness pattern from a dataframe column to a numpy array.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe containing the column with missing values.
TYPE:
|
X
|
Numpy array to apply missingness pattern to.
TYPE:
|
col_name
|
Name of the column to get missingness from, by default "pupil_raw".
TYPE:
|
split
|
Name of the data split (for logging), by default "train".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Array with missing values set to NaN where the dataframe has nulls. |
Source code in src/data_io/data_utils.py
combine_metadata_with_df_splits
¶
combine_metadata_with_df_splits(
df_raw: DataFrame, df_metadata: DataFrame
) -> tuple[DataFrame, dict]
Combine metadata dataframe with the PLR data splits.
| PARAMETER | DESCRIPTION |
|---|---|
df_raw
|
Raw PLR data dataframe.
TYPE:
|
df_metadata
|
Metadata dataframe containing subject information.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (combined_df, code_stats) where code_stats contains information about matching, extra, and missing subject codes. |
Source code in src/data_io/data_utils.py
combine_metadata_with_df
¶
combine_metadata_with_df(
df: DataFrame, df_metadata: DataFrame, split: str
) -> tuple[DataFrame, dict]
Combine metadata with a PLR dataframe for a specific split.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
PLR data dataframe.
TYPE:
|
df_metadata
|
Metadata dataframe containing subject information.
TYPE:
|
split
|
Name of the data split.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (combined_df, code_stats). |
Source code in src/data_io/data_utils.py
get_missing_labels
¶
Identify matching, extra, and missing subject codes between PLR and metadata.
| PARAMETER | DESCRIPTION |
|---|---|
unique_PLR
|
Dataframe with unique PLR subject codes.
TYPE:
|
unique_metadata
|
Dataframe with unique metadata subject codes.
TYPE:
|
split
|
Name of the data split (for logging).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary containing lists of 'matching', 'extra_metadata', and 'missing_from_PLR' subject codes. |
Source code in src/data_io/data_utils.py
add_labels_for_matching_codes
¶
add_labels_for_matching_codes(
df: DataFrame,
df_metadata: DataFrame,
matching_codes: list[str],
) -> DataFrame
Add metadata labels to dataframe for subjects with matching codes.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
PLR data dataframe.
TYPE:
|
df_metadata
|
Metadata dataframe containing subject information.
TYPE:
|
matching_codes
|
List of subject codes that exist in both dataframes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with metadata columns added for matching subjects. |
Source code in src/data_io/data_utils.py
add_label_per_code
¶
add_label_per_code(
code: str,
df: DataFrame,
df_metadata: DataFrame,
code_col: str = "subject_code",
length_PLR: int = 1981,
) -> DataFrame
Add metadata labels for a single subject code.
| PARAMETER | DESCRIPTION |
|---|---|
code
|
Subject code to add labels for.
TYPE:
|
df
|
PLR data dataframe.
TYPE:
|
df_metadata
|
Metadata dataframe.
TYPE:
|
code_col
|
Name of the subject code column, by default "subject_code".
TYPE:
|
length_PLR
|
Expected number of timepoints per subject, by default 1981.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with metadata added for the specified subject. |
Source code in src/data_io/data_utils.py
get_unique_labels
¶
get_unique_labels(
df: DataFrame,
unique_col: str = "class_label",
value_col: str = "time",
) -> list[str]
Get list of unique non-null labels from a dataframe column.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe.
TYPE:
|
unique_col
|
Column to get unique values from, by default "class_label".
TYPE:
|
value_col
|
Column to use for selecting representative rows, by default "time".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list
|
List of unique label values. |
Source code in src/data_io/data_utils.py
pick_per_label
¶
Filter dataframe to keep only rows with a specific class label.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe with class_label column.
TYPE:
|
label
|
Class label to filter for.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Filtered dataframe containing only rows with the specified label. |
Source code in src/data_io/data_utils.py
get_outlier_count_per_code
¶
Get outlier counts per subject code, sorted by count.
| PARAMETER | DESCRIPTION |
|---|---|
unique_value
|
Array of unique subject codes.
TYPE:
|
df_pd
|
Dataframe with subject_code and no_outliers columns.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (sorted_counts, sorted_codes) for subjects with outlier counts above the median. |
Source code in src/data_io/data_utils.py
pick_random_subjects_with_outlier_no_cutoff
¶
pick_random_subjects_with_outlier_no_cutoff(
unique_value: ndarray, df_pd: DataFrame, n: int
) -> ndarray
Pick random subjects from those with above-median outlier counts.
| PARAMETER | DESCRIPTION |
|---|---|
unique_value
|
Array of unique subject codes.
TYPE:
|
df_pd
|
Dataframe with subject_code and no_outliers columns.
TYPE:
|
n
|
Number of subjects to pick.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Array of randomly selected subject codes. |
Source code in src/data_io/data_utils.py
pick_n_subjects_per_label_pandas
¶
pick_n_subjects_per_label_pandas(
df: DataFrame,
n: int,
PLR_length: int = 1981,
col_select: str = "subject_code",
pick_random: bool = False,
) -> DataFrame
Pick n subjects from a dataframe, optionally with outlier-based selection.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe.
TYPE:
|
n
|
Number of subjects to pick.
TYPE:
|
PLR_length
|
Expected number of timepoints per subject, by default 1981.
TYPE:
|
col_select
|
Column containing subject identifiers, by default "subject_code".
TYPE:
|
pick_random
|
If True, pick first n subjects; if False, pick from high-outlier subjects, by default False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe containing data for the selected n subjects. |
Source code in src/data_io/data_utils.py
pick_n_subjects_per_label
¶
pick_n_subjects_per_label(
df: DataFrame,
label: str,
n: int,
PLR_length: int = 1981,
) -> DataFrame
Pick n subjects with a specific class label from a dataframe.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe with class_label column.
TYPE:
|
label
|
Class label to filter for.
TYPE:
|
n
|
Number of subjects to pick.
TYPE:
|
PLR_length
|
Expected number of timepoints per subject, by default 1981.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe containing data for the selected n subjects with the given label. |
Source code in src/data_io/data_utils.py
get_list_of_unique_subjects
¶
Get a list of unique subject codes from a dataframe.
| PARAMETER | DESCRIPTION |
|---|---|
df_label
|
Input dataframe.
TYPE:
|
unique_col
|
Column containing subject identifiers, by default "subject_code".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list
|
List of unique subject codes. |
Source code in src/data_io/data_utils.py
get_unique_polars_rows
¶
get_unique_polars_rows(
df: DataFrame,
unique_col: str = "subject_code",
value_col: str = "time",
split: Optional[str] = None,
df_string: Optional[str] = None,
pandas_fix: bool = True,
) -> DataFrame
Get unique rows from a Polars dataframe based on a column.
Deduplicates the dataframe to get one row per unique value in the specified column.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input Polars dataframe.
TYPE:
|
unique_col
|
Column to use for identifying unique rows, by default "subject_code".
TYPE:
|
value_col
|
Column to use for selecting representative rows, by default "time".
TYPE:
|
split
|
Name of the data split (for logging), by default None.
TYPE:
|
df_string
|
Description string for logging, by default None.
TYPE:
|
pandas_fix
|
Whether to use pandas for deduplication (more reliable), by default True.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with one row per unique value in unique_col. |
Source code in src/data_io/data_utils.py
check_post_metadata_add
¶
Validate dataframe after metadata addition.
Checks that the number of rows with and without class labels are multiples of the PLR length.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Dataframe to validate.
TYPE:
|
length_PLR
|
Expected number of timepoints per subject, by default 1981.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If row counts are not multiples of PLR length. |
Source code in src/data_io/data_utils.py
pick_debug_data
¶
pick_debug_data(
df: DataFrame,
string: str,
cfg: DictConfig,
n: int = 4,
pick_random: bool = False,
) -> DataFrame
Pick a small subset of data for debugging purposes.
Selects n subjects per unique label for faster debugging runs.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe.
TYPE:
|
string
|
Description string for logging.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
n
|
Number of subjects to pick per label, by default 4.
TYPE:
|
pick_random
|
Whether to pick subjects randomly, by default False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Subset dataframe for debugging. |
Source code in src/data_io/data_utils.py
combine_split_dataframes
¶
combine_split_dataframes(
df_train: DataFrame,
df_val: DataFrame,
cfg: DictConfig,
debug_mode: bool = False,
debug_n: int = 4,
pick_random: bool = False,
demo_mode: bool = False,
) -> DataFrame
Combine train and validation dataframes with a split indicator column.
| PARAMETER | DESCRIPTION |
|---|---|
df_train
|
Training dataframe.
TYPE:
|
df_val
|
Validation dataframe.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
debug_mode
|
Whether to use debug mode (subset of data), by default False.
TYPE:
|
debug_n
|
Number of subjects per label in debug mode, by default 4.
TYPE:
|
pick_random
|
Whether to pick subjects randomly in debug mode, by default False.
TYPE:
|
demo_mode
|
Whether demo mode is enabled, by default False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Combined dataframe with 'split' column indicating train/test. |
Source code in src/data_io/data_utils.py
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 | |
define_desired_timevector
¶
Generate an ideal time vector for PLR recordings.
| PARAMETER | DESCRIPTION |
|---|---|
PLR_length
|
Number of timepoints in the recording, by default 1981.
TYPE:
|
fps
|
Frames per second of the recording, by default 30.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Time vector in seconds. |
Source code in src/data_io/data_utils.py
check_time_similarity
¶
Check if two time vectors are similar.
| PARAMETER | DESCRIPTION |
|---|---|
time_vec_in
|
Input time vector to check.
TYPE:
|
time_vec_ideal
|
Ideal/reference time vector.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary containing check results including 'allclose', 'min_same', 'max_same', and overall 'OK' status. |
Source code in src/data_io/data_utils.py
check_time_vector_quality
¶
check_time_vector_quality(
subject_code: str,
csv_subset: DataFrame,
cfg: DictConfig,
) -> tuple[ndarray, ndarray, dict[str, bool | float]]
Check the quality of a subject's time vector against the ideal.
| PARAMETER | DESCRIPTION |
|---|---|
subject_code
|
Subject identifier.
TYPE:
|
csv_subset
|
Subject's data containing a 'time' column.
TYPE:
|
cfg
|
Configuration dictionary with PLR_length setting.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (time_vec_in, time_vec_ideal, time_checks). |
Source code in src/data_io/data_utils.py
check_for_unique_timepoints
¶
check_for_unique_timepoints(
df: DataFrame,
cfg: DictConfig,
col: str = "time",
assert_on_error: bool = True,
) -> None
Check that all subjects have the same time vector.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe.
TYPE:
|
cfg
|
Configuration dictionary with PLR_length setting.
TYPE:
|
col
|
Name of the time column, by default "time".
TYPE:
|
assert_on_error
|
Whether to raise an error if check fails, by default True.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If subjects have different time vectors and assert_on_error is True. |
Source code in src/data_io/data_utils.py
fix_for_orphaned_nans
¶
fix_for_orphaned_nans(
subject_code: str,
csv_subset: DataFrame,
cfg: DictConfig,
cols: tuple = ("Red", "Blue"),
)
Fix orphaned NaN values by replacing with zeros.
Orphaned NaNs are NaN values that remain after interpolation, typically at the edges of the data.
| PARAMETER | DESCRIPTION |
|---|---|
subject_code
|
Subject identifier for logging.
TYPE:
|
csv_subset
|
Subject's data containing the columns to fix.
TYPE:
|
cfg
|
Configuration dictionary with PLR_length setting.
TYPE:
|
cols
|
Columns to check and fix, by default ("Red", "Blue").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with orphaned NaNs replaced by zeros. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If NaNs remain after the fix. |
Source code in src/data_io/data_utils.py
check_for_data_lengths
¶
Verify that all subjects have the expected PLR data length.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe.
TYPE:
|
cfg
|
Configuration dictionary with PLR_length setting.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If any subject has a different number of timepoints than expected. |
Source code in src/data_io/data_utils.py
transform_data_for_momentfm
¶
transform_data_for_momentfm(
X: ndarray,
mask: ndarray,
dataset_cfg: DictConfig,
model_name: str,
) -> tuple[ndarray, ndarray, ndarray]
Transform data arrays for MOMENT foundation model input.
Applies trimming, padding, and downsampling to prepare PLR data for the MOMENT time series foundation model.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data array of shape (n_subjects, n_timepoints).
TYPE:
|
mask
|
Outlier mask array of shape (n_subjects, n_timepoints).
TYPE:
|
dataset_cfg
|
Dataset configuration with transform parameters.
TYPE:
|
model_name
|
Name of the model (e.g., "MOMENT", "UniTS", "TimesNet").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (X_transformed, mask_transformed, input_mask). |
Source code in src/data_io/data_utils.py
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 | |
fill_na_in_array_before_windowing
¶
fill_na_in_array_before_windowing(
array: ndarray,
fill_na: Optional[str],
trim_to_size: int,
model_name: Optional[str],
) -> ndarray
Fill NaN values in array before splitting into windows.
Different models have different requirements for handling NaN values. This function applies model-specific filling strategies.
| PARAMETER | DESCRIPTION |
|---|---|
array
|
Input array of shape (batch_size, time_points).
TYPE:
|
fill_na
|
Strategy for filling NaN values ("median", "0", or None).
TYPE:
|
trim_to_size
|
Target window size after trimming.
TYPE:
|
model_name
|
Name of the model ("TimesNet", "UniTS", etc.).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Array with NaN values filled according to the strategy. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If model_name is unknown. |
NotImplementedError
|
If fill_na strategy is not implemented. |
Source code in src/data_io/data_utils.py
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 | |
transform_for_moment_fm_length
¶
transform_for_moment_fm_length(
data_array: ndarray,
trim_to_size: int = 512,
pad_ts: bool = True,
downsample_factor: int = 4,
resample_method: str = "cubic",
split_subjects_to_windows: bool = True,
_binarize_output: bool = False,
fill_na: Optional[str] = None,
model_name: Optional[str] = None,
) -> ndarray
Transform data array to required length for foundation models.
Applies padding or trimming, optional downsampling, and optional window splitting to prepare data for time series foundation models.
| PARAMETER | DESCRIPTION |
|---|---|
data_array
|
Input array of shape (n_subjects, n_timepoints).
TYPE:
|
trim_to_size
|
Target size for trimming/padding, by default 512.
TYPE:
|
pad_ts
|
Whether to pad the time series, by default True.
TYPE:
|
downsample_factor
|
Factor for downsampling, by default 4.
TYPE:
|
resample_method
|
Interpolation method for resampling, by default "cubic".
TYPE:
|
split_subjects_to_windows
|
Whether to split into fixed-size windows, by default True.
TYPE:
|
fill_na
|
Strategy for filling NaN values, by default None.
TYPE:
|
model_name
|
Name of the target model, by default None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Transformed data array. |
Source code in src/data_io/data_utils.py
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 | |
trim_to_multiple_of
¶
Trim array length to a multiple of window_size by removing edge samples.
| PARAMETER | DESCRIPTION |
|---|---|
data_array
|
Input array of shape (n_subjects, n_timepoints).
TYPE:
|
window_size
|
Target multiple size, by default 96.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Trimmed array with length as a multiple of window_size. |
Source code in src/data_io/data_utils.py
get_no_of_windows
¶
Calculate the number of windows needed to cover the PLR signal.
| PARAMETER | DESCRIPTION |
|---|---|
length_PLR
|
Length of the PLR signal, by default 1981.
TYPE:
|
window_size
|
Size of each window, by default 512.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of windows needed (rounded up). |
Source code in src/data_io/data_utils.py
split_subjects_to_windows_PLR
¶
Split subject data into fixed-size windows.
Reshapes the array so each subject's time series is split into multiple windows, creating pseudo-subjects.
| PARAMETER | DESCRIPTION |
|---|---|
array
|
Input array of shape (n_subjects, n_timepoints).
TYPE:
|
window_size
|
Size of each window, by default 512.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Reshaped array of shape (n_subjects * windows_per_subject, window_size). |
Source code in src/data_io/data_utils.py
downsample_PLR
¶
Downsample PLR signals by a given factor using interpolation.
| PARAMETER | DESCRIPTION |
|---|---|
array
|
Input array of shape (n_subjects, n_timepoints).
TYPE:
|
downsample_factor
|
Factor by which to reduce the number of samples, by default 4.
TYPE:
|
resample_method
|
Interpolation method ("cubic", "linear", etc.), by default "cubic".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Downsampled array of shape (n_subjects, n_timepoints // downsample_factor). |
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If NaN ratio increases significantly after resampling or all values are NaN. |
Source code in src/data_io/data_utils.py
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 | |
unpad_glaucoma_PLR
¶
Remove padding from PLR array to restore original length.
| PARAMETER | DESCRIPTION |
|---|---|
array
|
Padded array of shape (n_subjects, padded_length).
TYPE:
|
length_PLR
|
Original PLR signal length, by default 1981.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Unpadded array of shape (n_subjects, length_PLR). |
Source code in src/data_io/data_utils.py
get_padding_indices
¶
Calculate start and end indices for centered padding/unpadding.
| PARAMETER | DESCRIPTION |
|---|---|
length_orig
|
Original signal length, by default 1981.
TYPE:
|
length_padded
|
Padded signal length, by default 2048.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (start_idx, end_idx) for slicing. |
Source code in src/data_io/data_utils.py
pad_glaucoma_PLR
¶
Pad PLR array with NaN values to reach a multiple of trim_to_size.
Centers the original data within the padded array.
| PARAMETER | DESCRIPTION |
|---|---|
data_array
|
Input array of shape (n_subjects, n_timepoints).
TYPE:
|
trim_to_size
|
Target multiple for the padded length, by default 512.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Padded array of shape (n_subjects, ceil(n_timepoints/trim_to_size) * trim_to_size). |
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If the padded array contains only NaN values. |
Source code in src/data_io/data_utils.py
Data Wrangling¶
data_wrangler
¶
convert_datadict_to_dict_arrays
¶
convert_datadict_to_dict_arrays(
data_dict: dict[str, Any], cls_model_cfg: DictConfig
) -> dict[str, Any]
Convert hierarchical data dictionary to flat arrays structure.
Needs to be this flat structure, used with some models. See data_transform_wrapper() -> create_dmatrices_and_dict_arrays().
| PARAMETER | DESCRIPTION |
|---|---|
data_dict
|
Hierarchical data dictionary with train/test splits.
TYPE:
|
cls_model_cfg
|
Classification model configuration.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Flat dictionary with x_train, y_train, x_test, y_test, etc. |
Source code in src/data_io/data_wrangler.py
fix_pl_schema
¶
Cast object types in a Polars dataframe to appropriate types.
Handles conversion of decimal.Decimal to float and ensures string types are properly cast.
| PARAMETER | DESCRIPTION |
|---|---|
df_metadata
|
Polars dataframe with potential Object dtype columns.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with Object types cast to appropriate types. |
See Also
convert_object_type : Similar function for numpy arrays.
References
https://docs.pola.rs/user-guide/expressions/casting/#basic-example
Source code in src/data_io/data_wrangler.py
convert_subject_dict_of_arrays_to_df
¶
convert_subject_dict_of_arrays_to_df(
subject_dict: dict[str, dict[str, ndarray]],
wildcard_categories: list[str] | None = None,
) -> DataFrame
Convert a subject dictionary of arrays to a Polars dataframe.
| PARAMETER | DESCRIPTION |
|---|---|
subject_dict
|
Dictionary with category names as keys containing sub-dictionaries with array data.
TYPE:
|
wildcard_categories
|
If provided, only include categories in this list, by default None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Polars dataframe with arrays as columns. |
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If any array is not 1D. |
Source code in src/data_io/data_wrangler.py
get_subject_dict_for_featurization
¶
get_subject_dict_for_featurization(
split_dict: dict[str, dict[str, ndarray]],
i: int,
cfg: DictConfig,
return_1st_value: bool = False,
) -> dict[str, dict[str, Any]]
Extract a single subject's data from a split dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
split_dict
|
Dictionary containing data for all subjects in a split.
TYPE:
|
i
|
Subject index to extract.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
return_1st_value
|
If True, return only the first value; otherwise return the full row, by default False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary containing only the specified subject's data. |
Source code in src/data_io/data_wrangler.py
pick_correct_data_and_label_for_experiment
¶
pick_correct_data_and_label_for_experiment(
data_dict: dict[str, Any],
cfg: DictConfig,
task: str,
_task_cfg: DictConfig,
) -> None
Select appropriate data columns for a specific experiment task.
| PARAMETER | DESCRIPTION |
|---|---|
data_dict
|
Full data dictionary.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
task
|
Task name.
TYPE:
|
_task_cfg
|
Task-specific configuration (currently unused).
TYPE:
|
Notes
Currently a placeholder function.
Source code in src/data_io/data_wrangler.py
get_dict_with_wildcard
¶
Extract columns matching a wildcard pattern as a dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input Polars dataframe.
TYPE:
|
wildcard
|
Pattern to match in column names, by default "pupil".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary mapping column names to Polars Series. |
Source code in src/data_io/data_wrangler.py
get_dict_with_list_of_cols
¶
Extract specific columns as a dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input Polars dataframe.
TYPE:
|
cols
|
List of column names to extract.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary mapping column names to Polars Series. |
Source code in src/data_io/data_wrangler.py
get_dict_with_remaining_cols
¶
get_dict_with_remaining_cols(
df_split: DataFrame,
data_dict: dict[str, dict[str, Any]],
) -> dict[str, Series]
Extract columns not already present in data_dict as a dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
df_split
|
Input Polars dataframe.
TYPE:
|
data_dict
|
Existing data dictionary to check for used columns.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary mapping remaining column names to Polars Series. |
Source code in src/data_io/data_wrangler.py
convert_object_type
¶
Convert numpy object dtype arrays to appropriate types.
Handles conversion of decimal.Decimal to float and str to string dtype.
| PARAMETER | DESCRIPTION |
|---|---|
array_tmp
|
Array potentially with object dtype.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Array with appropriate dtype (float or str). |
Source code in src/data_io/data_wrangler.py
reshape_flat_series_to_2d_arrays
¶
reshape_flat_series_to_2d_arrays(
dict_series: dict[str, dict[str, Series]],
length_PLR: int = 1981,
) -> dict[str, dict[str, ndarray]]
Reshape flat Polars Series to 2D numpy arrays.
Converts a dictionary of Series to 2D arrays with shape (n_subjects, n_timepoints).
| PARAMETER | DESCRIPTION |
|---|---|
dict_series
|
Dictionary of dictionaries containing Polars Series.
TYPE:
|
length_PLR
|
Number of timepoints per subject, by default 1981.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with same structure but 2D numpy arrays. |
Source code in src/data_io/data_wrangler.py
split_df_to_dict
¶
split_df_to_dict(
df_split: DataFrame, cfg: DictConfig, split: str
) -> dict[str, dict[str, ndarray]]
Convert a split dataframe to a hierarchical dictionary of 2D arrays.
Creates a structured dictionary with categories: time, data, labels, light, and metadata. All values are reshaped to (n_subjects, n_timepoints).
| PARAMETER | DESCRIPTION |
|---|---|
df_split
|
Polars dataframe for a single split.
TYPE:
|
cfg
|
Configuration dictionary with DATA settings.
TYPE:
|
split
|
Name of the split (for logging).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Hierarchical dictionary with 2D numpy arrays. |
Source code in src/data_io/data_wrangler.py
convert_df_to_dict
¶
Convert a Polars dataframe to a hierarchical dictionary for model input.
Converts the combined dataframe into a structured dictionary that can be used with various ML frameworks: - sklearn: (X_train, X_val, y_train, y_val) - PyTorch: (dataloader, dataset)
| PARAMETER | DESCRIPTION |
|---|---|
data_df
|
Combined Polars dataframe with 'split' column.
TYPE:
|
cfg
|
Configuration dictionary with DATA settings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with 'df' key containing split dictionaries and 'preprocess' key with preprocessing parameters. |
Source code in src/data_io/data_wrangler.py
Flow Data¶
flow_data
¶
flow_import_data
¶
Import PLR data from either raw CSVs or DuckDB database.
Main data import flow that handles loading, combining splits, optional debug subsetting, and visualization of PLR pupillometry data.
| PARAMETER | DESCRIPTION |
|---|---|
cfg
|
Configuration dictionary containing DATA, DEBUG, EXPERIMENT, and PREFECT settings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Combined Polars dataframe with train and test splits indicated by the 'split' column. |
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
If debug mode is on but no subject subset is specified. |
Source code in src/data_io/flow_data.py
DuckDB Export¶
duckdb_export
¶
Memory-efficient export of features and classifier results to DuckDB.
This module creates shareable DuckDB databases that enable: 1. Reproducibility without raw clinical data access 2. Memory-efficient analysis (target: <16GB RAM) 3. Continuation from intermediate artifacts
Cross-references: - planning/share-features-and-classifier-outputs.md - planning/statistics-implementation.md (Memory Optimization section)
Output Files: - foundation_plr_features.db: Hand-crafted PLR features (shareable) - foundation_plr_results.db: All classifier outputs (shareable)
Usage: # Export from mlruns python -m src.data_io.duckdb_export export --mlruns ./mlruns
# Continue analysis from features.db
python -m src.data_io.duckdb_export analyze --from-features features.db
# Continue analysis from results.db (re-run only statistics)
python -m src.data_io.duckdb_export analyze --from-results results.db
DuckDBAnalysisPipeline
dataclass
¶
DuckDBAnalysisPipeline(
features_db: Optional[Path] = None,
results_db: Optional[Path] = None,
output_dir: Path = (lambda: Path("outputs/analysis"))(),
_features: Optional[ndarray] = None,
_labels: Optional[ndarray] = None,
_feature_names: Optional[List[str]] = None,
_predictions_df: Optional[DataFrame] = None,
_metrics_df: Optional[DataFrame] = None,
)
Pipeline for running analysis from DuckDB artifacts.
Supports continuation from: 1. features.db - re-run classification + statistics 2. results.db - re-run only statistics
Usage: # From features (re-run classification) pipeline = DuckDBAnalysisPipeline.from_features("features.db") pipeline.run_classification() pipeline.run_statistics()
# From results (re-run only statistics)
pipeline = DuckDBAnalysisPipeline.from_results("results.db")
pipeline.run_statistics()
from_features
classmethod
¶
from_features(
features_db: Union[str, Path],
output_dir: Optional[Union[str, Path]] = None,
) -> DuckDBAnalysisPipeline
Create pipeline from features database (will run classification).
Source code in src/data_io/duckdb_export.py
from_results
classmethod
¶
from_results(
results_db: Union[str, Path],
output_dir: Optional[Union[str, Path]] = None,
) -> DuckDBAnalysisPipeline
Create pipeline from results database (statistics only).
Source code in src/data_io/duckdb_export.py
can_run_classification
¶
can_run_statistics
¶
run_classification
¶
Run classification on loaded features.
| PARAMETER | DESCRIPTION |
|---|---|
classifiers
|
Classifier names to use (default: LogReg, XGBoost, CatBoost)
TYPE:
|
n_folds
|
Number of CV folds
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Classification results |
Source code in src/data_io/duckdb_export.py
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 | |
run_statistics
¶
Run statistical analysis on loaded/computed results.
| PARAMETER | DESCRIPTION |
|---|---|
output_dir
|
Override output directory
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Any]
|
Statistical results |
Source code in src/data_io/duckdb_export.py
export_for_reproduction
¶
Export current state to DuckDB for future reproduction.
Source code in src/data_io/duckdb_export.py
load_artifact_safe
¶
Context manager for safe artifact loading with cleanup.
Usage: with load_artifact_safe(path) as artifact: # Use artifact # Artifact is automatically deleted and garbage collected
Source code in src/data_io/duckdb_export.py
iter_artifacts_chunked
¶
iter_artifacts_chunked(
artifact_paths: List[Path], batch_size: int = 5
) -> Generator[List[Any], None, None]
Iterate over artifacts in batches with explicit cleanup.
Prevents memory accumulation when processing many artifacts.
Source code in src/data_io/duckdb_export.py
concat_dataframes_efficient
¶
Efficiently concatenate multiple DataFrames.
Uses pandas concat with copy=False for O(n) performance instead of O(n^2) that would occur with iterative concatenation.
| PARAMETER | DESCRIPTION |
|---|---|
dfs
|
List of DataFrames to concatenate.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Concatenated DataFrame with reset index. |
Source code in src/data_io/duckdb_export.py
export_features_to_duckdb
¶
export_features_to_duckdb(
features_data: Dict[str, DataFrame],
metadata: DataFrame,
output_path: Union[str, Path],
provenance: Optional[Dict[str, Dict]] = None,
chunk_size: int = 1000,
) -> Path
Export hand-crafted features to DuckDB.
| PARAMETER | DESCRIPTION |
|---|---|
features_data
|
Mapping from source_name to features DataFrame
TYPE:
|
metadata
|
Subject metadata (subject_id, eye, split, has_glaucoma)
TYPE:
|
output_path
|
Output .db file path
TYPE:
|
provenance
|
Mapping from source_name to provenance info
TYPE:
|
chunk_size
|
Rows per insert batch
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Path
|
Path to created database |
Source code in src/data_io/duckdb_export.py
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 | |
export_results_to_duckdb
¶
export_results_to_duckdb(
predictions_df: DataFrame,
metrics_per_fold: DataFrame,
metrics_aggregate: DataFrame,
output_path: Union[str, Path],
calibration_curves: Optional[DataFrame] = None,
dca_curves: Optional[DataFrame] = None,
mlflow_runs: Optional[DataFrame] = None,
chunk_size: int = 1000,
) -> Path
Export classifier results to DuckDB.
| PARAMETER | DESCRIPTION |
|---|---|
predictions_df
|
All predictions with columns matching schema
TYPE:
|
metrics_per_fold
|
Metrics per fold
TYPE:
|
metrics_aggregate
|
Aggregated metrics (mean, CI)
TYPE:
|
output_path
|
Output .db file path
TYPE:
|
calibration_curves
|
Calibration curve data
TYPE:
|
dca_curves
|
Decision curve analysis data
TYPE:
|
mlflow_runs
|
MLflow run metadata
TYPE:
|
chunk_size
|
Rows per insert batch
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Path
|
Path to created database |
Source code in src/data_io/duckdb_export.py
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 | |
load_features_from_duckdb
¶
load_features_from_duckdb(
db_path: Union[str, Path],
source_name: Optional[str] = None,
split: Optional[str] = None,
) -> Tuple[ndarray, ndarray, List[str]]
Load features from DuckDB for classification.
| PARAMETER | DESCRIPTION |
|---|---|
db_path
|
Path to features.db
TYPE:
|
source_name
|
Filter for specific pipeline configuration
TYPE:
|
split
|
Filter for 'train', 'val', or 'test'
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
X
|
Feature matrix (n_samples, n_features)
TYPE:
|
y
|
Labels (n_samples,)
TYPE:
|
feature_names
|
Feature column names
TYPE:
|
Source code in src/data_io/duckdb_export.py
load_results_from_duckdb
¶
load_results_from_duckdb(
db_path: Union[str, Path],
table: str = "metrics_aggregate",
) -> DataFrame
Load results from DuckDB.
| PARAMETER | DESCRIPTION |
|---|---|
db_path
|
Path to results.db
TYPE:
|
table
|
Table to load: "predictions", "metrics_per_fold", "metrics_aggregate", "calibration_curves", "dca_curves", "mlflow_runs"
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Requested data |
Source code in src/data_io/duckdb_export.py
extract_mlflow_classification_runs
¶
extract_mlflow_classification_runs(
mlruns_dir: Union[str, Path],
experiment_id: Optional[str] = None,
batch_size: int = 10,
) -> Tuple[
DataFrame, DataFrame, DataFrame, DataFrame, DataFrame
]
Extract classification results from MLflow runs.
Extracts all available metrics and computes STRATOS-required metrics: - Calibration slope, intercept, O:E ratio - Net benefit at 5%, 10%, 20% thresholds - Full DCA curves (50 threshold points from 1% to 50%)
| PARAMETER | DESCRIPTION |
|---|---|
mlruns_dir
|
Path to mlruns directory
TYPE:
|
experiment_id
|
Specific experiment ID (defaults to classification experiment)
TYPE:
|
batch_size
|
Number of runs to process per batch
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tuple[DataFrame, DataFrame, DataFrame, DataFrame, DataFrame]
|
(predictions_df, metrics_per_fold_df, metrics_aggregate_df, dca_curves_df, mlflow_runs_df) |
Source code in src/data_io/duckdb_export.py
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 | |
export_mlflow_to_duckdb
¶
export_mlflow_to_duckdb(
mlruns_dir: Union[str, Path],
output_path: Union[str, Path],
experiment_id: Optional[str] = None,
) -> Path
Export MLflow classification results to DuckDB.
| PARAMETER | DESCRIPTION |
|---|---|
mlruns_dir
|
Path to mlruns directory
TYPE:
|
output_path
|
Output .db file path
TYPE:
|
experiment_id
|
Specific experiment ID
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Path
|
Path to created database |
Source code in src/data_io/duckdb_export.py
main
¶
Command-line interface for DuckDB export/analysis.
Supports two main commands: - export: Export MLflow runs to a DuckDB database - analyze: Run analysis from existing features or results databases
| RETURNS | DESCRIPTION |
|---|---|
None
|
Executes CLI commands and writes output to files. |
Source code in src/data_io/duckdb_export.py
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 | |
Stratification¶
stratification_utils
¶
add_split_col_to_dataframe
¶
Add a 'split' column to dataframe based on subject code assignments.
| PARAMETER | DESCRIPTION |
|---|---|
df_raw
|
Raw data dataframe.
TYPE:
|
split_codes
|
Dictionary mapping split names to lists of subject codes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with added 'split' column. |
Source code in src/data_io/stratification_utils.py
multicol_stratification
¶
multicol_stratification(
df_tmp: DataFrame,
test_size: float,
stratify_columns: list,
cfg: DictConfig,
col_to_return: str = "subject_code",
) -> dict
Perform multi-column iterative stratification for train/test split.
Custom iterative train test split which 'maintains balanced representation with respect to order-th label combinations.'
| PARAMETER | DESCRIPTION |
|---|---|
df_tmp
|
Temporary dataframe with columns to stratify on.
TYPE:
|
test_size
|
Proportion of data to use for test set (0-1).
TYPE:
|
stratify_columns
|
List of column names to use for stratification.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
col_to_return
|
Column name to return for each split, by default "subject_code".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with 'train' and 'test' keys mapping to lists of values. |
References
- https://www.abzu.ai/data-science/stratified-data-splitting-part-2/
- https://madewithml.com/courses/mlops/splitting/#stratified-split
Source code in src/data_io/stratification_utils.py
create_tmp_stratification_df
¶
Create a temporary dataframe for stratification with binned features.
| PARAMETER | DESCRIPTION |
|---|---|
df_raw
|
Raw data dataframe.
TYPE:
|
stratify_columns
|
List of columns to use for stratification.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Temporary pandas dataframe with subject_code, no_outliers_bins, and class_label columns. |
Source code in src/data_io/stratification_utils.py
bin_outlier_counts
¶
Bin outlier counts into quantile-based categories.
| PARAMETER | DESCRIPTION |
|---|---|
outliers
|
List of outlier counts per subject.
TYPE:
|
no_of_bins
|
Number of bins to create, by default 5.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Array of bin labels for each subject. |
Source code in src/data_io/stratification_utils.py
create_splits_to_df
¶
Create stratified splits and add split column to dataframe.
| PARAMETER | DESCRIPTION |
|---|---|
df_raw
|
Raw data dataframe.
TYPE:
|
cfg
|
Configuration with STRATIFICATION settings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Dataframe with added 'split' column. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If any data points have missing split assignments. |
Source code in src/data_io/stratification_utils.py
stratify_splits
¶
Main function to stratify data into train and test splits.
Performs multi-column stratification based on class labels and outlier counts, ensuring balanced representation in both splits.
| PARAMETER | DESCRIPTION |
|---|---|
df_raw
|
Raw data dataframe with all subjects.
TYPE:
|
cfg
|
Configuration with STRATIFICATION settings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (df_train, df_test) as Polars dataframes. |
Source code in src/data_io/stratification_utils.py
Source Definitions¶
define_sources_for_flow
¶
get_best_mlflow_col_for_imputation
¶
Get the MLflow column name for the best imputation metric.
| PARAMETER | DESCRIPTION |
|---|---|
cfg
|
Configuration dictionary containing IMPUTATION_METRICS settings.
TYPE:
|
string
|
Metric identifier (e.g., "MAE"), by default "MAE".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
MLflow column name for the specified metric. |
Source code in src/data_io/define_sources_for_flow.py
get_best_string_for_imputation
¶
Get the best metric configuration dictionary for imputation.
| PARAMETER | DESCRIPTION |
|---|---|
cfg
|
Configuration dictionary containing IMPUTATION_METRICS settings.
TYPE:
|
split
|
Data split name, by default "test".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Best metric configuration dictionary. |
Source code in src/data_io/define_sources_for_flow.py
get_best_string_for_outlier_detection
¶
Get the best metric configuration for outlier detection.
| PARAMETER | DESCRIPTION |
|---|---|
cfg
|
Configuration dictionary containing OUTLIER_DETECTION settings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Best metric configuration for outlier detection. |
Source code in src/data_io/define_sources_for_flow.py
get_best_string_for_classification
¶
Get the best metric configuration for classification.
| PARAMETER | DESCRIPTION |
|---|---|
cfg
|
Configuration dictionary containing CLASSIFICATION_SETTINGS.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Best metric configuration for classification. |
Source code in src/data_io/define_sources_for_flow.py
get_best_dict
¶
Get the best metric dictionary for a given task.
| PARAMETER | DESCRIPTION |
|---|---|
task
|
Task name ("outlier_detection", "imputation", "featurization", or "classification").
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict or None
|
Best metric configuration dictionary, or None for featurization. |
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
If the task is unknown. |
Source code in src/data_io/define_sources_for_flow.py
get_best_run_dict
¶
Sort MLflow runs by the best metric and return the sorted dataframe.
| PARAMETER | DESCRIPTION |
|---|---|
run_df
|
DataFrame of MLflow runs.
TYPE:
|
best_dict
|
Configuration specifying the metric column and sort direction.
TYPE:
|
task
|
Task name for metric column selection.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Sorted DataFrame with best runs first. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If task is unknown or metric column not found. |
Source code in src/data_io/define_sources_for_flow.py
drop_ensemble_runs
¶
Remove ensemble runs from a MLflow runs dataframe.
| PARAMETER | DESCRIPTION |
|---|---|
runs_model
|
DataFrame of MLflow runs.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with ensemble runs removed. |
Source code in src/data_io/define_sources_for_flow.py
foundation_model_filter
¶
foundation_model_filter(
mlflow_runs: DataFrame,
best_dict: dict,
model_name: str,
task: str,
) -> Optional[DataFrame]
Filter foundation model runs to get best zeroshot and finetuned variants.
The idea is to get both the zeroshot and finetuned model with the foundation models (if available) whereas with the more traditional models, the zeroshot option is not there typically (or does not perform so well at all).
| PARAMETER | DESCRIPTION |
|---|---|
mlflow_runs
|
DataFrame of all MLflow runs.
TYPE:
|
best_dict
|
Configuration specifying the best metric and direction.
TYPE:
|
model_name
|
Name of the foundation model to filter for.
TYPE:
|
task
|
Task name for metric selection.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame or None
|
DataFrame with filtered runs, or None if no runs found. |
Source code in src/data_io/define_sources_for_flow.py
get_best_imputation_runs
¶
Get the best run for each unique imputer+outlier combination.
Unlike best outlier_runs, we now have added 3 new fields to the mlflow_runs: 1. imputer_model 2. outlier_source 3. unique_combo
And the unique_combo defines how many imputer+outlier_source combos we have for featurization.
| PARAMETER | DESCRIPTION |
|---|---|
mlflow_runs
|
DataFrame of MLflow runs with unique_combo column.
TYPE:
|
task
|
Task name for metric selection.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with one best run per unique combination. |
Source code in src/data_io/define_sources_for_flow.py
drop_foundational_models
¶
Remove foundation model runs from MLflow runs dataframe.
| PARAMETER | DESCRIPTION |
|---|---|
mlflow_runs
|
DataFrame of MLflow runs.
TYPE:
|
foundation_model_names
|
List of foundation model name strings to filter out.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with foundation model runs removed. |
Source code in src/data_io/define_sources_for_flow.py
get_best_model_runs
¶
Get the best runs for each model type (foundation and traditional).
Manual definition of what you want to compare. You could also simply use all MLflow runs as source, and put the return_subset to False. This artisanal selection is here just to reduce the number of combos to return.
| PARAMETER | DESCRIPTION |
|---|---|
mlflow_runs
|
DataFrame of all MLflow runs.
TYPE:
|
task
|
Task name for metric selection.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with best runs for each model type. |
Source code in src/data_io/define_sources_for_flow.py
get_unique_outlier_runs
¶
Get one best run per unique run name from MLflow runs.
| PARAMETER | DESCRIPTION |
|---|---|
mlflow_runs
|
DataFrame of MLflow runs.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
task
|
Task name for metric selection.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with one best run per unique run name. |
Source code in src/data_io/define_sources_for_flow.py
parse_run_name_for_two_model_names
¶
Parse a run name to extract imputer model and outlier source names.
| PARAMETER | DESCRIPTION |
|---|---|
run_name
|
MLflow run name in format "imputer__outlier_source".
TYPE:
|
delimiter
|
Delimiter separating model names, by default "__".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (imputer_model, outlier_source) as simplified names. |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
If the run name cannot be parsed. |
Source code in src/data_io/define_sources_for_flow.py
simplify_model_name
¶
Simplify a model name by extracting the core identifier.
Handles special cases for ensemble and MOMENT model naming conventions.
| PARAMETER | DESCRIPTION |
|---|---|
model_name
|
Full model name from MLflow run.
TYPE:
|
delimiter
|
Delimiter in the model name, by default "_".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Simplified model name. |
Source code in src/data_io/define_sources_for_flow.py
get_unique_combo_runs
¶
get_unique_combo_runs(
mlflow_runs_in: DataFrame,
cfg: DictConfig,
task: str,
delimiter: str = "__",
) -> DataFrame
Add unique combo columns to MLflow runs for imputer+outlier tracking.
Parses run names to extract imputer_model and outlier_source, creating a unique_combo identifier for each combination.
| PARAMETER | DESCRIPTION |
|---|---|
mlflow_runs_in
|
Input MLflow runs DataFrame.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
task
|
Task name.
TYPE:
|
delimiter
|
Delimiter separating model names, by default "__".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with added imputer_model, outlier_source, and unique_combo columns. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If any run has a NaN run_id. |
Source code in src/data_io/define_sources_for_flow.py
get_previous_best_mlflow_runs
¶
get_previous_best_mlflow_runs(
experiment_name: str,
cfg: DictConfig,
task: str = "outlier_detection",
return_subset: bool = True,
) -> Optional[DataFrame]
Get the best MLflow runs from a previous experiment for use as data sources.
| PARAMETER | DESCRIPTION |
|---|---|
experiment_name
|
Name of the MLflow experiment.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
task
|
Task name to determine filtering strategy, by default "outlier_detection".
TYPE:
|
return_subset
|
Whether to return a curated subset or all runs, by default True.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame or None
|
DataFrame of best MLflow runs, or None if no runs found. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the task is unknown. |
NotImplementedError
|
If featurization task is requested. |
Source code in src/data_io/define_sources_for_flow.py
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 | |
get_arrays_for_splits_from_imputer_artifacts
¶
get_arrays_for_splits_from_imputer_artifacts(
artifacts: dict, run_name: str
) -> dict[str, dict[str, ndarray]]
Extract imputation arrays from MLflow imputer artifacts.
| PARAMETER | DESCRIPTION |
|---|---|
artifacts
|
MLflow artifacts containing imputation results.
TYPE:
|
run_name
|
MLflow run name for logging.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with train/test splits containing X, CI_pos, CI_neg, and mask arrays. |
Source code in src/data_io/define_sources_for_flow.py
check_arrays
¶
Validate that X and mask arrays have matching shapes.
| PARAMETER | DESCRIPTION |
|---|---|
splits_dicts
|
Dictionary of split dictionaries containing X and mask arrays.
TYPE:
|
task
|
Task name for error messages.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If X and mask arrays have different shapes. |
Source code in src/data_io/define_sources_for_flow.py
get_best_epoch
¶
Extract the best epoch results from outlier detection artifacts.
Handles multiple artifact formats from different outlier detection methods.
| PARAMETER | DESCRIPTION |
|---|---|
outlier_artifacts
|
Dictionary of outlier detection artifacts from MLflow.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (results_best, simple_format) where simple_format indicates the artifact structure type. |
Source code in src/data_io/define_sources_for_flow.py
if_pick_the_split
¶
Determine if a given split should be processed based on run name.
| PARAMETER | DESCRIPTION |
|---|---|
run_name
|
MLflow run name.
TYPE:
|
split
|
Split name to check.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the split should be picked, False otherwise. |
Source code in src/data_io/define_sources_for_flow.py
get_arrays_for_splits_from_outlier_artifacts
¶
get_arrays_for_splits_from_outlier_artifacts(
outlier_artifacts: dict, run_name: str
) -> dict[str, dict[str, ndarray]]
Extract reconstruction and mask arrays from outlier detection artifacts.
Handles multiple artifact formats from different outlier detection methods (MOMENT, TimesNet, LOF, Prophet, etc.).
| PARAMETER | DESCRIPTION |
|---|---|
outlier_artifacts
|
Dictionary of outlier detection artifacts from MLflow.
TYPE:
|
run_name
|
MLflow run name for logging and method detection.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with train/test splits containing X (reconstruction) and mask arrays. Format: {split: {'X': np.array, 'mask': np.array}} |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If arrays cannot be extracted from the artifacts. |
AssertionError
|
If no splits were selected for analysis. |
Source code in src/data_io/define_sources_for_flow.py
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 | |
get_ensembled_anomaly_masks
¶
Create ensembled anomaly masks from individual detector masks.
| PARAMETER | DESCRIPTION |
|---|---|
artifacts
|
Dictionary mapping splits to 3D arrays of individual detector masks.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with ensembled masks for each split. |
Source code in src/data_io/define_sources_for_flow.py
get_source_data
¶
Load source data arrays from MLflow artifacts for each run.
| PARAMETER | DESCRIPTION |
|---|---|
mlflow_runs
|
DataFrame of MLflow runs to process.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
task
|
Task name ("outlier_detection" or "imputation").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (dicts_out, mlflow_dict) where dicts_out contains the data arrays and mlflow_dict maps source names to MLflow run info. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the task is unknown. |
Source code in src/data_io/define_sources_for_flow.py
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 | |
add_array_to_dict
¶
Validate and optionally cast a numpy array before adding to a dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
array_to_add
|
Array to validate and add.
TYPE:
|
key
|
Dictionary key name for error messages.
TYPE:
|
astype
|
Data type to cast the array to, by default None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Validated (and optionally cast) array. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the input is not a numpy array. |
Source code in src/data_io/define_sources_for_flow.py
get_dict_per_col_name
¶
get_dict_per_col_name(
col_names: list[str],
data_dict: dict,
col_name: str,
mask_col: str,
) -> dict
Create data dictionary structure for a specific column name.
| PARAMETER | DESCRIPTION |
|---|---|
col_names
|
List of column names to process (typically pupil signal columns).
TYPE:
|
data_dict
|
Source data dictionary with df and preprocess keys.
TYPE:
|
col_name
|
Target column name for the data.
TYPE:
|
mask_col
|
Column name for the mask data.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Structured data dictionary with X, X_GT, and mask arrays. |
Source code in src/data_io/define_sources_for_flow.py
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 | |
print_mask_stats
¶
Log statistics about the mask coverage for each split.
| PARAMETER | DESCRIPTION |
|---|---|
data_dict
|
Data dictionary containing df with mask arrays.
TYPE:
|
mask_col
|
Name of the mask column for logging.
TYPE:
|
Source code in src/data_io/define_sources_for_flow.py
import_data_for_flow
¶
Import data from DuckDB and prepare it for the processing flow.
| PARAMETER | DESCRIPTION |
|---|---|
cfg
|
Configuration dictionary.
TYPE:
|
task
|
Task name ("outlier_detection" or "imputation").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
Tuple containing (data_dicts, input_signal, data_dict) where data_dicts is the structured source data, input_signal is the column name for input data, and data_dict is the raw imported data. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the task is unknown. |
Source code in src/data_io/define_sources_for_flow.py
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 | |
check_combination
¶
Validate that X, mask, and time arrays have consistent dimensions.
| PARAMETER | DESCRIPTION |
|---|---|
source_data
|
Dictionary of source data.
TYPE:
|
source_name
|
Name of the source to check.
TYPE:
|
split
|
Split name to check.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If array dimensions are inconsistent. |
Source code in src/data_io/define_sources_for_flow.py
check_gt_and_X
¶
Check if X and X_GT arrays are identical and warn if so.
| PARAMETER | DESCRIPTION |
|---|---|
source_data
|
Dictionary of source data.
TYPE:
|
source_name
|
Name of the source to check.
TYPE:
|
split
|
Split name for logging.
TYPE:
|
Source code in src/data_io/define_sources_for_flow.py
add_CI_to_data_dicts
¶
Add placeholder confidence interval arrays to data dictionaries.
The featurization script assumes CI arrays exist, so this adds NaN-filled arrays where they are missing.
| PARAMETER | DESCRIPTION |
|---|---|
data_dicts
|
Data dictionaries to add CI arrays to.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Updated data dictionaries with CI_pos and CI_neg arrays. |
Source code in src/data_io/define_sources_for_flow.py
add_mlflow_dict_to_sources
¶
Add MLflow run information to each source dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
sources
|
Dictionary of source data.
TYPE:
|
mlflow_dict
|
Dictionary mapping source names to MLflow run info.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Updated sources dictionary with mlflow key added to each source. |
Source code in src/data_io/define_sources_for_flow.py
check_sources
¶
Quality check all source data for NaN values.
| PARAMETER | DESCRIPTION |
|---|---|
sources
|
Dictionary of source data to check.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If any source contains NaN values in its data arrays. |
Source code in src/data_io/define_sources_for_flow.py
combine_source_with_data_dicts
¶
combine_source_with_data_dicts(
source_data: Optional[dict],
data_dicts_for_source: dict,
mlflow_dict: Optional[dict],
cfg: DictConfig,
task: str,
input_signal: str,
data_dict: dict,
) -> dict
Combine MLflow source data with the base data dictionary template.
Merges reconstruction/mask arrays from MLflow runs with the full data structure (time, metadata, etc.) from the DuckDB import.
| PARAMETER | DESCRIPTION |
|---|---|
source_data
|
Dictionary of source data from MLflow runs.
TYPE:
|
data_dicts_for_source
|
Base data dictionary template from DuckDB import.
TYPE:
|
mlflow_dict
|
Dictionary mapping source names to MLflow run info.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
task
|
Task name ("outlier_detection" or "imputation").
TYPE:
|
input_signal
|
Column name for input data when no reconstruction available.
TYPE:
|
data_dict
|
Raw imported data dictionary for fallback values.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Combined sources dictionary with full data structure for each source. |
Notes
Expected data_dict_template structure: df: dict train: dict time: dict data: dict labels: dict light: dict metadata: dict test: dict same as train preprocess: dict standardization: dict
Source code in src/data_io/define_sources_for_flow.py
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 | |
define_sources_for_flow
¶
define_sources_for_flow(
prev_experiment_name: str,
cfg: DictConfig,
task: str = "outlier_detection",
) -> dict
Define all data sources for a processing flow from previous MLflow experiments.
Main entry point for loading source data. Combines: 1. Best runs from the previous MLflow experiment 2. Original ground truth data from DuckDB
| PARAMETER | DESCRIPTION |
|---|---|
prev_experiment_name
|
Name of the previous MLflow experiment to get runs from.
TYPE:
|
cfg
|
Configuration dictionary.
TYPE:
|
task
|
Task name for determining data source type, by default "outlier_detection".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary of all source data, including both MLflow and ground truth sources. |
Source code in src/data_io/define_sources_for_flow.py
PyTorch Data¶
torch_data
¶
trim_data
¶
Trim PLR data to remove edge artifacts.
Removes the first 3 and last 2 timepoints from PLR recordings to get a clean 1976-sample signal.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Input array with shape (n_subjects, n_timepoints).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Trimmed array with shape (n_subjects, 1976). |
Source code in src/data_io/torch_data.py
nan_padding
¶
Pad trimmed data back to original length with NaN values.
Inverse operation of trim_data, fills edge positions with NaN.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Trimmed input array with shape (n_subjects, 1976).
TYPE:
|
n
|
Target output length, by default 1981.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Padded array with shape (n_subjects, n) with NaN at edges. |
Source code in src/data_io/torch_data.py
get_outlier_data
¶
Extract outlier detection data and masks from data dictionary.
Retrieves the imputed original pupil data and corresponding outlier mask for evaluating outlier detection algorithms.
| PARAMETER | DESCRIPTION |
|---|---|
data_dict
|
Hierarchical data dictionary with split keys.
TYPE:
|
split
|
Data split to extract ("train" or "test").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of np.ndarray
|
X: pupil data array (n_subjects, n_timepoints) mask: outlier mask array where 1=outlier, 0=normal |
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If no outliers are labeled in the mask. |
Source code in src/data_io/torch_data.py
pick_pupil_data_col
¶
Select appropriate pupil data column based on training configuration.
Retrieves the correct data column (ground truth, raw imputed, or original imputed) and corresponding mask based on the train_on parameter.
| PARAMETER | DESCRIPTION |
|---|---|
train_on
|
Data column to use: "pupil_gt", "pupil_raw_imputed", or "pupil_orig_imputed".
TYPE:
|
data_dict
|
Hierarchical data dictionary with split keys.
TYPE:
|
split
|
Data split to extract ("train" or "test").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of np.ndarray
|
X: pupil data array (n_subjects, n_timepoints) mask: corresponding mask array (zeros for gt/raw, outlier_mask for orig) |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If train_on parameter is not recognized. |
Source code in src/data_io/torch_data.py
dataset_outlier_detection_selector
¶
dataset_outlier_detection_selector(
detection_type: str,
train_on: str,
split: str,
split_data: str,
data_dict: dict,
)
Select data for outlier detection based on detection type and split.
Routes data selection based on whether fine-tuning or zero-shot detection is used, and whether outlier-specific splits are requested.
| PARAMETER | DESCRIPTION |
|---|---|
detection_type
|
Detection approach: "fine-tune" or "zero-shot".
TYPE:
|
train_on
|
Data column to use for training.
TYPE:
|
split
|
Data split ("train" or "test").
TYPE:
|
split_data
|
Specific split type (e.g., "outlier_train", "outlier_test").
TYPE:
|
data_dict
|
Hierarchical data dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of np.ndarray
|
X: data array and mask: outlier mask array. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If detection_type is not recognized. |
AssertionError
|
If outlier split requested but mask has no outliers. |
Source code in src/data_io/torch_data.py
dataset_ts_cls_selector
¶
Select data for time series classification task.
Extracts features and class labels for binary classification, encoding string labels to integers.
| PARAMETER | DESCRIPTION |
|---|---|
detection_type
|
Detection approach: "fine-tune" or "full-finetune".
TYPE:
|
train_on
|
Data column to use (not used directly, for interface consistency).
TYPE:
|
split
|
Data split ("train" or "test").
TYPE:
|
data_dict
|
Hierarchical data dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
X: feature array (n_subjects, n_features) labels: integer class labels (n_subjects,) |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If detection_type is not recognized. |
AssertionError
|
If number of unique classes is not 2, or if label count mismatches X. |
Source code in src/data_io/torch_data.py
dataset_imputation_selector
¶
Select data for imputation task.
Extracts data and missingness mask for training imputation models to reconstruct missing values.
| PARAMETER | DESCRIPTION |
|---|---|
detection_type
|
Detection approach: "fine-tune" or "zero-shot".
TYPE:
|
train_on
|
Data column: "pupil_gt" or "pupil_raw_imputed".
TYPE:
|
split
|
Data split ("train" or "test").
TYPE:
|
data_dict
|
Hierarchical data dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of np.ndarray
|
X: data array and mask: missingness mask. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If detection_type or train_on is not recognized. |
NotImplementedError
|
If train_on is "pupil_raw_imputed" (not yet implemented). |
AssertionError
|
If mask has no missing points. |
Source code in src/data_io/torch_data.py
dataset_data_array_selector
¶
dataset_data_array_selector(
split_data,
task,
data_dict,
detection_type: str = "zero-shot",
train_on: str = "gt",
)
Main dispatcher for selecting data arrays based on task and split.
Routes data extraction to appropriate task-specific selector based on the task type (outlier detection, imputation, or classification).
| PARAMETER | DESCRIPTION |
|---|---|
split_data
|
Split specification: "train", "test", "outlier_train", "outlier_test".
TYPE:
|
task
|
Task type: "outlier_detection", "imputation", or "ts_cls".
TYPE:
|
data_dict
|
Hierarchical data dictionary.
TYPE:
|
detection_type
|
Detection approach, by default "zero-shot".
TYPE:
|
train_on
|
Data column to use, by default "gt".
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of np.ndarray
|
X: data array and mask/label array depending on task. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If split_data or task is not recognized. |
AssertionError
|
If X contains NaN values or shape mismatch with mask. |
Source code in src/data_io/torch_data.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | |
pick_splits_from_data_dict_to_ts
¶
Extract train/test splits from data dictionary for time series export.
Organizes data into split-specific dictionaries with X (data), y (outlier mask), and time arrays for downstream processing.
| PARAMETER | DESCRIPTION |
|---|---|
data_dict_df
|
Hierarchical data dictionary with split keys containing data arrays.
TYPE:
|
model_cfg
|
Model configuration (not currently used but kept for interface).
TYPE:
|
train_on
|
Data column to extract (e.g., "pupil_orig_imputed").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with "train" and "test" keys, each containing: - X: data array - y: outlier mask - time: time vector |
References
- https://github.com/eBay/RANSynCoders/blob/main/example.ipynb
Source code in src/data_io/torch_data.py
create_dataset_from_numpy
¶
create_dataset_from_numpy(
data_dict_df: dict,
dataset_cfg: DictConfig,
model_cfg: DictConfig,
split: str,
task: str = "imputation",
model_name: str = None,
)
Create a PyTorch TensorDataset from numpy arrays.
Converts data dictionary arrays to PyTorch tensors and optionally applies trimming for foundation model compatibility.
| PARAMETER | DESCRIPTION |
|---|---|
data_dict_df
|
Hierarchical data dictionary containing numpy arrays.
TYPE:
|
dataset_cfg
|
Dataset configuration with trim_to_size and other settings.
TYPE:
|
model_cfg
|
Model configuration with MODEL settings (detection_type, train_on).
TYPE:
|
split
|
Data split to use ("train", "test", "outlier_train", "outlier_test").
TYPE:
|
task
|
Task type for data selection, by default "imputation".
TYPE:
|
model_name
|
Model name for trim configuration, by default None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TensorDataset
|
PyTorch dataset with (X, mask, input_mask) tensors. |