pdmlabs.utils.dataset#
Dataset preparation and management for predictive maintenance tasks.
This module provides the Dataset class for handling time-series data preparation, episode management, train/validation/test splitting, and generation of labeled datasets for various learning paradigms (supervised, unsupervised, semi-supervised).
- Key Features:
Automatic episode extraction from time-series data
Intelligent train/val/test splitting with failure-aware strategy
Support for multiple dataset formats (RUL, survival analysis, classification)
Event data integration and wildcard-based event preference handling
Configurable predictive horizon and sliding window parameters
Example
>>> import pandas as pd
>>> from pdmlabs.utils.dataset import Dataset
>>> data = pd.read_csv('sensor_data.csv')
>>> dataset = Dataset(
... data=data,
... datetime_column='timestamp',
... failure_column='is_failure',
... source_column='equipment_id'
... )
>>> train_data, test_data = dataset.get_rul_dataset()
Module Attributes
Separator inserted between an original source name and its episode index. |
|
Minimum number of episodes needed to populate train, validation and test. |
Functions
|
Split one source into episodes delimited by its failure/maintenance events. |
|
Split data into episodes and mark which of them end with a failure. |
Classes
|
A class to handle dataset preparation and processing for predictive maintenance tasks. |
- class pdmlabs.utils.dataset.Dataset(data, datetime_column, event_indicator=None, maintenance_column=None, failure_column=None, event_df=None, source_column='source', beta=1, slide=None, lead='0 seconds', predictive_horizon=None, train_sources=0.6, val_sources=0.2, test_sources=0.2, max_wait_time=None, in_source_split=False, keep_censored_tail=True, random_state=None, DIVIDER=3600)#
Bases:
objectA class to handle dataset preparation and processing for predictive maintenance tasks. This includes splitting data into episodes, calculating sliding windows, and preparing training, validation, and testing datasets.
- Parameters:
data (pd.DataFrame) – The input data containing time-series information. If event_df is not provided but maintenance_column and/or failure_column are provided, they are expected to be binary indicator columns of data and are used to derive the episodes. If neither event_df, event_indicator, maintenance_column nor failure_column is provided, every source is assumed to be a single run-to-failure episode.
datetime_column (str) – The name of the column representing datetime values.
event_indicator (str, default=None) – The name of the column indicating event occurrence (binary), constant per source. If provided, it is used to mark the end of the single episode of each source (0: maintenance/reset or censored, 1: failure).
maintenance_column (str or list, default=None) – Without event_df: the name of the binary column of data that flags maintenance/reset events. With event_df: the list of values of the code column of event_df that are considered maintenance (resetting) events.
failure_column (str or list, default=None) – Without event_df: the name of the binary column of data that flags failure events. With event_df: the list of values of the code column of event_df that are considered failure events.
event_df (pd.DataFrame, optional) – A DataFrame containing event data. When provided it must contain the columns datetime_column, source_column and code, and failure_column (and optionally maintenance_column) must be given as lists of code values. Codes that appear in both lists are treated as failures.
source_column (str, default='source') – The name of the column representing the source of the data.
beta (int, default=1) – A parameter used for objective calculations.
slide (int, optional) – The sliding window size. If None, it is calculated automatically.
lead (str, default="0 seconds") – The lead time for predictions.
predictive_horizon (str, optional) – The predictive horizon for the dataset. If None, it is calculated automatically.
train_sources (float or list, default=0.6) – The ratio (float) or list of source/episode names used for training. If a float, it represents the proportion of sources used for training.
val_sources (float or list, default=0.2) – The ratio (float) or list of source/episode names used for validation.
test_sources (float or list, default=0.2) – The ratio (float) or list of source/episode names used for testing.
max_wait_time (int, optional) – Controls the maximum length of the profile parameter in OnlineFlavor and Sliding Window flavor (i.e. the maximum length of the data used to fit anomaly detectors). This is the time the user is willing to wait before detectors produce alarms. If None, it is set to 2/3 of the minimum episode length.
in_source_split (bool, default=False) – Whether to select train/val/test episodes from within each source (True) or to split at the source level (False). Splitting at the source level is the only way to guarantee that no source contributes to more than one split.
keep_censored_tail (bool, default=True) – When episodes are derived from events, whether to keep the data recorded after the last event of a source as an extra censored (non run-to-failure) episode. Setting this to False discards that data, which is the behaviour of releases up to 0.0.2.
random_state (int, optional) – When provided, sources/episodes are shuffled with this seed before being split. When None (the default) the split follows the order in which sources appear in data, which keeps the split reproducible without shuffling.
DIVIDER (int, default=3600) – Number of seconds a single RUL unit corresponds to (3600 => RUL expressed in hours). Ignored when data already carries a
RULcolumn and episodes are whole sources (the event_indicator strategy and the implicit run-to-failure fallback): that column is taken as given. When episodes are cut out of a source by events, a per-episode RUL is always recomputed, because a source-wide RUL would not restart at each episode.
- sources#
Episode names, in episode order.
- Type:
list[str]
- episode_to_source#
Maps an episode name to the original source it was extracted from.
- Type:
dict[str, str]
- rtf_dict#
Maps an episode name to 1 when the episode ends with a failure, 0 otherwise.
- Type:
dict[str, int]
- sources_for_train, sources_for_val, sources_for_test
Episode names of each split, in the same order as train_dfs, val_dfs and test_dfs.
- Type:
list[str]
- train_dfs, val_dfs, test_dfs
Episodes of each split.
- Type:
list[pd.DataFrame]
- df_to_x_y_surv(df, indicator=None, event_column='event')#
Convert dataframe to survival analysis format (time, event) tuples.
- Parameters:
df (pd.DataFrame) – Dataframe containing RUL and event columns.
indicator (int, optional) – Event indicator value (0 or 1). If None, uses event_column from df.
event_column (str, default="event") – Name of the column holding the event indicator.
- Returns:
List of (rul, event) tuples for survival analysis models.
- Return type:
list[tuple]
- generate_binary_labels(sources, list_dfs)#
Generate binary anomaly labels based on predictive horizon and lead time.
Creates binary labels (0=normal, 1=anomaly) by identifying samples within the predictive horizon before failure events and considering lead time.
- Parameters:
sources (list[str]) – Source identifiers corresponding to dataframes, in the same order as list_dfs.
list_dfs (list[pd.DataFrame]) – List of episode dataframes to label.
- Returns:
(final_ranges, leadranges) - Lists of binary label arrays and lead time flags.
- Return type:
tuple[list, list]
Notes
Uses predictive_horizon and lead time from Dataset initialization
Any sample within lead range (before failure) is marked as 1
Helper uses _data_formulation and extract_anomaly_ranges from evaluation module
- get_Classification_dataset(keep_sources=None)#
Generate a binary classification dataset.
From train episodes without failures, the last predictive_horizon period is ignored to ensure healthy operation, based on the objective the user wants to optimize. Then binary labels are generated for all training data, labeling every record as 0, except those that lie within the predictive horizon before a failure event, which are labeled as 1.
- Parameters:
keep_sources (str, optional) – If provided, preserves this column for source tracking.
- Returns:
(dataset, test_dataset) for validation and testing respectively.
- Return type:
tuple[dict, dict]
- get_SA_dataset(keep_sources=None)#
Generate Survival Analysis dataset with reliability labels.
Creates datasets for survival regression tasks where the goal is to predict survival probabilities or remaining time until events. Combines all training episodes and marks event indicators (failure/maintenance).
- Parameters:
keep_sources (str, optional) – If provided, preserves this column for source tracking.
- Returns:
(dataset, test_dataset) - Dictionaries containing: - ‘target_labels’: Tuples of (RUL, event_indicator) for each sample - ‘anomaly_labels’: Tuples of (RUL, event_flag) for training - Other fields same as get_rul_dataset()
- Return type:
tuple[dict, dict]
Notes
Survival analysis labels are tuples (time, event) used by survival methods
Event indicator: 1 for failure, 0 for maintenance/reset
Combines event information from the rtf_dict (run-to-failure mapping)
- get_events_from_df(df_list)#
Build
[date, type, source, description]rows for the end of each episode.
- get_rul_dataset(keep_sources=None)#
Generate RUL (Remaining Useful Life) prediction dataset.
Creates training, validation, and testing datasets optimized for RUL regression tasks. Uses only run-to-failure episodes for training and generates RUL labels indicating time remaining until failure.
- Parameters:
keep_sources (str, optional) – If provided, preserves this column (e.g., ‘source’) in the dataset for source tracking. Otherwise, removes source and RUL columns.
- Returns:
(dataset, test_dataset) - Two dictionaries containing: - ‘match_sources’: Source mapping for transfer learning - ‘target_sources’: Sources used for validation/testing - ‘target_data’: Feature data for val/test - ‘target_labels’: RUL values (time to failure) for val/test - ‘is_failure’: Whether each source had failures - ‘historic_data’: Training data (run-to-failure episodes only) - ‘historic_sources’: Source names for training data - ‘anomaly_labels’: RUL labels for training data - ‘predictive_horizon’: Time window before failure - ‘slide’: Sliding window step size - ‘lead’: Lead time for predictions - ‘beta’: Objective weighting parameter
- Return type:
tuple[dict, dict]
Examples
>>> dataset_obj = Dataset(data, 'timestamp', failure_column='is_failure') >>> train_set, test_set = dataset_obj.get_rul_dataset() >>> # Access training RUL data >>> rul_labels = train_set['anomaly_labels'][0]
- get_semi_dataset()#
Generate a semi-supervised dataset.
From the train episodes the last predictive_horizon period is removed so that only healthy operation remains, based on the objective the user wants to optimize. The result is used as unlabeled historical data to fit a semi-supervised anomaly detector.
- Returns:
(dataset, test_dataset) for validation and testing respectively.
- Return type:
tuple[dict, dict]
- get_unsupervised_dataset()#
Generate an unsupervised dataset.
No historical data is produced: the train and validation episodes are exposed as targets of the validation dictionary and the test episodes as targets of the test dictionary, so that an unsupervised detector is scored directly on the data it consumes.
- Returns:
(dataset, test_dataset) for validation and testing respectively.
- Return type:
tuple[dict, dict]
- safe_splitting(source_units, at_least_one_failure_in_train=False)#
Split a list of source/episode names into train, validation and test.
Kept for backwards compatibility; the splitting logic now lives in _allocate_groups and _repair_split, which also guarantee failure coverage across the three splits.
- Parameters:
source_units (list[str]) – Source or episode names to split.
at_least_one_failure_in_train (bool, default=False) – When True, a failing unit is guaranteed to end up in the training split.
- Returns:
The train, validation and test name lists.
- Return type:
tuple[list, list, list]
- slide_calculation(episodes, run_to_failure)#
Calculate optimal sliding window step size for dataset generation.
Ensures that slide + predictive_horizon equals approximately 1/3 of the smallest failure episode. This balances training data size with prediction lead time.
- Parameters:
episodes (list[pd.DataFrame]) – List of episode dataframes, each representing one run-to-failure sequence.
run_to_failure (list[int]) – List indicating which episodes contain failures (1) or are healthy runs (0).
- Returns:
Optimal sliding window step size. Minimum value is 1.
- Return type:
int
Notes
The sliding window step determines how many samples between consecutive windows. Larger steps = fewer training samples but faster processing. Smaller steps = more training samples but more computation.
Formula: slide = (episode_length / 3) - predictive_horizon_length
- split_sources_to_train_test_val(episodes, run_to_failure)#
Splits the sources into training, validation, and testing datasets.
- Parameters:
episodes (list) – A list of dataframes, where each dataframe corresponds to an episode.
run_to_failure (list) – A list of integers indicating whether each episode is a run-to-failure (1) or not (0).
- Returns:
The method updates the following attributes of the class: - self.train_dfs: Dataframes for training. - self.val_dfs: Dataframes for validation. - self.test_dfs: Dataframes for testing. - self.sources_for_train: Episodes used for training. - self.sources_for_val: Episodes used for validation. - self.sources_for_test: Episodes used for testing. - self.matches: A dictionary mapping validation/testing episodes to the training set.
- Return type:
None
Notes
sources_for_* is always kept in the same order as the corresponding *_dfs list, so the two can safely be zipped together.
- pdmlabs.utils.dataset.EPISODE_SEPARATOR = '_ep'#
Separator inserted between an original source name and its episode index.
- pdmlabs.utils.dataset.MIN_EPISODES_FOR_SPLIT = 3#
Minimum number of episodes needed to populate train, validation and test.
- pdmlabs.utils.dataset.data_split_by_event(df_source, event_source, datetime_column, failure_column, maintenance_column, source_column='source', DIVIDER=3600, keep_censored_tail=True)#
Split one source into episodes delimited by its failure/maintenance events.
Every episode spans the interval
(previous recognised event, current event]and is marked run-to-failure (1) when it ends on a failure event and reset (0) when it ends on a maintenance event. The first episode also includes the very first observation of the source, and the data recorded after the last event is emitted as a censored episode when keep_censored_tail is True.- Returns:
(episodes, run_to_failure, episode_names)
- Return type:
tuple
- pdmlabs.utils.dataset.episodes_formulation(data, datetime_column, event_indicator=None, maintenance_list=None, failure_list=None, event_df=None, source_column='source', DIVIDER=3600, keep_censored_tail=True)#
Split data into episodes and mark which of them end with a failure.
Four mutually exclusive strategies are supported, in this order of precedence:
event_df is given: episodes are delimited by the events of event_df whose code belongs to failure_list (run-to-failure) or maintenance_list (reset).
event_indicator is given: every source forms a single episode whose outcome is read from that (constant per source) binary column.
maintenance_list/failure_list name binary indicator columns of data: episodes are delimited by the rows where those columns equal 1.
Nothing is given: every source is assumed to be a single run-to-failure episode.
- Returns:
(episodes, run_to_failure, episode_sources, original_s_has_f, episode_to_source)
- Return type:
tuple