Skip to content

Datasets & Stream Generators

The stride.datasets subpackage provides streaming data generators, semi-synthetic stream blending tools (Shaker protocol), and external benchmark loaders.


Overview

All generators inherit from BaseDataset and implement a unified generate() interface returning pandas DataFrame feature matrices \(X\) and target series \(y\).

from stride.datasets import (
    HyperplaneDriftDataset,
    SeaDriftDataset,
    RBFDriftDataset,
    LinearWeightInversionDriftDataset,
    SemiSyntheticDriftDataset,
)

Key Components

Class / Function Description
BaseDataset Abstract base class defining the generator contract and windowing parameters.
HyperplaneDriftDataset Continuous rotating hyperplane in \(d\)-dimensional feature space simulating gradual drift.
SeaDriftDataset Abrupt threshold displacement benchmark with noise features.
RbfDriftDataset Moving Gaussian radial basis centroids simulating non-linear cluster displacement.
LinearWeightInversionDriftDataset Feature correlation inversion benchmark testing model attribution sensitivity.
SemiSyntheticDriftDataset Empirical stream splicing under the Shaker protocol (Shaker & Hüllermeier, 2015).
FeatureMatcher Statistical feature alignment via Hungarian Wasserstein mapping or PCA subspace.
DriftBlender Deterministic stream blending with abrupt, gradual, incremental, or harmonic schedules.
RiverDataset Adapter wrapping River streaming benchmark datasets.
CsvDataset Offline loader for tabular CSV streaming datasets with sliding window slicing.

API Specification

stride.datasets

BaseDataset

Bases: ABC

Abstract base class for all data streams and drift generators.

display_name abstractmethod property

display_name

Human-readable name for the dataset.

name abstractmethod property

name

Unique identifier for the dataset.

generate abstractmethod

generate(**kwargs)

Generate the data stream before and after drift.

Returns:

Type Description
tuple[DataFrame, Series]

Tuple of (X, y) where: - X: pd.DataFrame with named features of shape (n_samples, n_features). - y: pd.Series with target values of shape (n_samples,).

Source code in src/stride/datasets/base.py
@abstractmethod
def generate(self, **kwargs) -> tuple[pd.DataFrame, pd.Series]:
    """Generate the data stream before and after drift.

    Returns:
        Tuple of `(X, y)` where:
            - `X`: pd.DataFrame with named features of shape `(n_samples, n_features)`.
            - `y`: pd.Series with target values of shape `(n_samples,)`.
    """
    pass

get_available_settings

get_available_settings()

Deprecated: Return available named preset settings for this dataset.

UI presets should be managed by consumer applications (e.g. dashboard.config.dataset_schemas).

Source code in src/stride/datasets/base.py
def get_available_settings(self) -> dict[str, dict]:
    """
    Deprecated: Return available named preset settings for this dataset.

    UI presets should be managed by consumer applications (e.g. dashboard.config.dataset_schemas).
    """
    import warnings

    warnings.warn(
        "get_available_settings() on dataset classes is deprecated and will be removed in a future release. "
        "UI presets should be managed by the application layer (e.g. dashboard.config.dataset_schemas).",
        DeprecationWarning,
        stacklevel=2,
    )
    try:
        from dashboard.config.dataset_schemas import get_dataset_available_settings

        return get_dataset_available_settings(self.name)
    except ImportError:
        return {}

get_params

get_params()

Return default generation parameters for the dataset.

Source code in src/stride/datasets/base.py
def get_params(self) -> dict:
    """Return default generation parameters for the dataset."""
    return {"n_samples_before": 1000, "n_samples_after": 1000, "random_seed": 42}

get_settings_schema

get_settings_schema()

Deprecated: Return a schema describing the settings for this dataset.

UI schemas should be managed by consumer applications (e.g. dashboard.config.dataset_schemas).

Source code in src/stride/datasets/base.py
def get_settings_schema(self) -> list[dict]:
    """
    Deprecated: Return a schema describing the settings for this dataset.

    UI schemas should be managed by consumer applications (e.g. dashboard.config.dataset_schemas).
    """
    import warnings

    warnings.warn(
        "get_settings_schema() on dataset classes is deprecated and will be removed in a future release. "
        "UI configuration schemas should be managed by the application layer (e.g. dashboard.config.dataset_schemas).",
        DeprecationWarning,
        stacklevel=2,
    )
    try:
        from dashboard.config.dataset_schemas import get_dataset_schema

        return get_dataset_schema(self.name)
    except ImportError:
        return []

DatasetRegistry

DatasetRegistry(
    data_dir="data/imported_datasets",
    registry_file="registry.json",
)
Source code in src/stride/datasets/dataset_registry.py
def __init__(self, data_dir: str = "data/imported_datasets", registry_file: str = "registry.json") -> None:
    # Ensure paths are absolute or relative to the project root as needed.
    # Assuming run from project root.
    self.data_dir = data_dir
    self.registry_path = os.path.join(self.data_dir, registry_file)

    self._ensure_data_dir()
    self._load_registry()

save_dataset

save_dataset(
    name, file_obj, target_column, selected_features=None
)

Save a new imported CSV dataset. file_obj: file-like object (e.g. from st.file_uploader) or bytes

Source code in src/stride/datasets/dataset_registry.py
def save_dataset(
    self,
    name: str,
    file_obj: Any,
    target_column: str,
    selected_features: list[str] | None = None,
) -> None:
    """
    Save a new imported CSV dataset.
    file_obj: file-like object (e.g. from st.file_uploader) or bytes
    """
    safe_filename = f"{name.replace(' ', '_')}.csv"
    file_path = os.path.join(self.data_dir, safe_filename)

    # Save the file
    with open(file_path, "wb") as f:
        if hasattr(file_obj, "read"):
            # Reset pointer just in case
            file_obj.seek(0)
            f.write(file_obj.read())
        else:
            f.write(file_obj)

    # Update registry
    self.registry[name] = {
        "name": name,
        "filename": safe_filename,
        "type": "imported_csv",
        "target_column": target_column,
        "selected_features": selected_features,
    }
    self._save_registry()

save_semi_synthetic_dataset

save_semi_synthetic_dataset(
    name, df, target_column, recipe, selected_features=None
)

Save a semi-synthetic dataset synthesized from two empirical concepts.

Source code in src/stride/datasets/dataset_registry.py
def save_semi_synthetic_dataset(
    self,
    name: str,
    df: Any,
    target_column: str,
    recipe: dict,
    selected_features: list[str] | None = None,
) -> None:
    """
    Save a semi-synthetic dataset synthesized from two empirical concepts.
    """
    safe_filename = f"{name.replace(' ', '_')}.csv"
    file_path = os.path.join(self.data_dir, safe_filename)

    # Save DataFrame to CSV
    if hasattr(df, "to_csv"):
        df.to_csv(file_path, index=False)

    # Update registry
    feature_cols = (
        selected_features
        if selected_features is not None
        else [c for c in df.columns if c not in (target_column, "_concept")]
    )

    self.registry[name] = {
        "name": name,
        "filename": safe_filename,
        "type": "semi_synthetic",
        "display_name": f"{name} (Semi-Synthetic)",
        "target_column": target_column,
        "selected_features": feature_cols,
        "recipe": recipe,
    }
    self._save_registry()

DriftBlender

DriftBlender(
    schedule="gradual",
    n_samples=None,
    t_0=None,
    w=200,
    period=500,
    random_state=42,
)

Blends two concept datasets into a continuous non-stationary stream.

Supports abrupt, gradual (Shaker sigmoidal Bernoulli schedule), incremental (nearest-neighbor linear interpolation), and recurring (periodic harmonic modulation) drift schedules.

Initialize DriftBlender.

Parameters:

Name Type Description Default
schedule str

Transition schedule ("abrupt", "gradual", "incremental", or "recurring").

'gradual'
n_samples int | None

Total stream length. If None, defaults to len(X_a) + len(X_b).

None
t_0 int | None

Inflection point (midpoint) of drift. If None, defaults to n_samples // 2.

None
w int

Transition window width in samples.

200
period int

Period length T for recurring schedule.

500
random_state int | None

Random seed for deterministic stream generation.

42

Raises:

Type Description
ValueError

If schedule is not one of {"abrupt", "gradual", "incremental", "recurring"}.

Source code in src/stride/datasets/drift_blending.py
def __init__(
    self,
    schedule: str = "gradual",
    n_samples: int | None = None,
    t_0: int | None = None,
    w: int = 200,
    period: int = 500,
    random_state: int | None = 42,
) -> None:
    """Initialize DriftBlender.

    Args:
        schedule: Transition schedule ("abrupt", "gradual", "incremental",
            or "recurring").
        n_samples: Total stream length. If None, defaults to `len(X_a) + len(X_b)`.
        t_0: Inflection point (midpoint) of drift. If None, defaults to `n_samples // 2`.
        w: Transition window width in samples.
        period: Period length T for recurring schedule.
        random_state: Random seed for deterministic stream generation.

    Raises:
        ValueError: If `schedule` is not one of {"abrupt", "gradual", "incremental", "recurring"}.
    """
    valid_schedules = [s.value for s in DriftSchedule]
    if schedule not in valid_schedules:
        raise ValueError(f"Unsupported schedule '{schedule}'. Supported schedules are: {valid_schedules}")

    self.schedule = schedule
    self.n_samples = n_samples
    self.t_0 = t_0
    self.w = max(1, int(w))
    self.period = max(2, int(period))
    self.random_state = random_state

blend

blend(X_a, y_a, X_b, y_b)

Blend Concept A and Concept B according to the configured schedule.

Parameters:

Name Type Description Default
X_a DataFrame

Aligned feature matrix for Concept A.

required
y_a Series

Target series for Concept A.

required
X_b DataFrame

Aligned feature matrix for Concept B.

required
y_b Series

Target series for Concept B.

required

Returns:

Type Description
DriftBlendResult

Synthesized stream DataFrame, target Series, concept indicators,

DriftBlendResult

and ground-truth change-point metadata.

Raises:

Type Description
ValueError

If input datasets are empty or column schemas do not match.

Source code in src/stride/datasets/drift_blending.py
def blend(
    self,
    X_a: pd.DataFrame,
    y_a: pd.Series,
    X_b: pd.DataFrame,
    y_b: pd.Series,
) -> DriftBlendResult:
    """Blend Concept A and Concept B according to the configured schedule.

    Args:
        X_a: Aligned feature matrix for Concept A.
        y_a: Target series for Concept A.
        X_b: Aligned feature matrix for Concept B.
        y_b: Target series for Concept B.

    Returns:
        Synthesized stream DataFrame, target Series, concept indicators,
        and ground-truth change-point metadata.

    Raises:
        ValueError: If input datasets are empty or column schemas do not match.
    """
    if len(X_a) == 0 or len(X_b) == 0:
        raise ValueError("Input concept datasets must not be empty.")
    if list(X_a.columns) != list(X_b.columns):
        raise ValueError("Feature columns in X_a and X_b must match. Please align them first.")

    rng = np.random.RandomState(self.random_state)
    n_total = self.n_samples or (len(X_a) + len(X_b))
    t_mid = self.t_0 if self.t_0 is not None else n_total // 2

    # Permute indices for drawing instances without artificial ordering
    idx_a = rng.permutation(len(X_a))
    idx_b = rng.permutation(len(X_b))

    if self.schedule == DriftSchedule.ABRUPT.value:
        return self._blend_abrupt(X_a, y_a, X_b, y_b, n_total, t_mid, idx_a, idx_b)
    elif self.schedule == DriftSchedule.GRADUAL.value:
        return self._blend_gradual(X_a, y_a, X_b, y_b, n_total, t_mid, idx_a, idx_b, rng)
    elif self.schedule == DriftSchedule.INCREMENTAL.value:
        return self._blend_incremental(X_a, y_a, X_b, y_b, n_total, t_mid, idx_a, idx_b, rng)
    elif self.schedule == DriftSchedule.RECURRING.value:
        return self._blend_recurring(X_a, y_a, X_b, y_b, n_total, idx_a, idx_b, rng)
    else:
        raise ValueError(f"Unknown schedule: {self.schedule}")

DriftSchedule

Bases: str, Enum

Supported drift transition schedules.

FeatureAlignmentResult dataclass

FeatureAlignmentResult(
    X_a_aligned,
    X_b_aligned,
    feature_mapping,
    aligned_feature_names,
    drifting_features,
    drift_diagnostics,
)

Result of feature alignment between two datasets.

FeatureMatcher

FeatureMatcher(
    match_strategy="exact",
    manual_mapping=None,
    align_distributions=False,
    scaler_type="standard",
    scaler_mode="joint",
    subspace_components=None,
    drift_significance_level=0.05,
    random_state=42,
)

Aligns and matches feature spaces between two distinct datasets or cohorts.

Supports exact column matching, user-specified manual dictionary mapping, statistical distribution matching (Wasserstein/KS bipartite assignment), and latent subspace projection via PCA. Also provides distribution normalization (joint or per-concept) and drifting feature identification.

Initialize FeatureMatcher.

Parameters:

Name Type Description Default
match_strategy str

Strategy to align features ("exact", "manual", "statistical", or "subspace").

'exact'
manual_mapping dict[str, str] | None

Mapping dictionary {col_A: col_B} for "manual" strategy.

None
align_distributions bool

Whether to apply feature scaling/normalization after alignment.

False
scaler_type str | None

Type of scaler: "standard" (StandardScaler) or "minmax" (MinMaxScaler).

'standard'
scaler_mode str

"joint" to fit scaler across pooled [X_A; X_B], or "per_concept" to fit independently on X_A and X_B.

'joint'
subspace_components int | None

Number of latent dimensions for "subspace" strategy. If None, min(d_A, d_B).

None
drift_significance_level float

p-value threshold below which a feature is categorized as drifting under KS test.

0.05
random_state int | None

Random seed for stochastic operations.

42

Raises:

Type Description
ValueError

If an unsupported strategy, scaler type, or scaler mode is provided.

Source code in src/stride/datasets/feature_matching.py
def __init__(
    self,
    match_strategy: str = "exact",
    manual_mapping: dict[str, str] | None = None,
    align_distributions: bool = False,
    scaler_type: str | None = "standard",
    scaler_mode: str = "joint",
    subspace_components: int | None = None,
    drift_significance_level: float = 0.05,
    random_state: int | None = 42,
) -> None:
    """Initialize FeatureMatcher.

    Args:
        match_strategy: Strategy to align features ("exact", "manual",
            "statistical", or "subspace").
        manual_mapping: Mapping dictionary `{col_A: col_B}` for "manual" strategy.
        align_distributions: Whether to apply feature scaling/normalization after alignment.
        scaler_type: Type of scaler: "standard" (`StandardScaler`) or "minmax" (`MinMaxScaler`).
        scaler_mode: "joint" to fit scaler across pooled `[X_A; X_B]`, or "per_concept" to
            fit independently on `X_A` and `X_B`.
        subspace_components: Number of latent dimensions for "subspace" strategy.
            If None, `min(d_A, d_B)`.
        drift_significance_level: p-value threshold below which a feature is categorized
            as drifting under KS test.
        random_state: Random seed for stochastic operations.

    Raises:
        ValueError: If an unsupported strategy, scaler type, or scaler mode is provided.
    """
    if match_strategy not in self.SUPPORTED_STRATEGIES:
        raise ValueError(
            f"Unsupported match_strategy '{match_strategy}'. Supported strategies are: {self.SUPPORTED_STRATEGIES}"
        )
    if scaler_type not in self.SUPPORTED_SCALERS:
        raise ValueError(f"Unsupported scaler_type '{scaler_type}'. Supported scalers are: {self.SUPPORTED_SCALERS}")
    if scaler_mode not in self.SUPPORTED_SCALER_MODES:
        raise ValueError(
            f"Unsupported scaler_mode '{scaler_mode}'. Supported scaler modes are: {self.SUPPORTED_SCALER_MODES}"
        )

    self.match_strategy = match_strategy
    self.manual_mapping = manual_mapping or {}
    self.align_distributions = align_distributions
    self.scaler_type = scaler_type
    self.scaler_mode = scaler_mode
    self.subspace_components = subspace_components
    self.drift_significance_level = drift_significance_level
    self.random_state = random_state

align

align(X_a, X_b)

Align feature representations between dataset A and dataset B.

Parameters:

Name Type Description Default
X_a DataFrame

Feature matrix of Concept A (pre-drift).

required
X_b DataFrame

Feature matrix of Concept B (post-drift).

required

Returns:

Type Description
FeatureAlignmentResult

Dataclass containing aligned DataFrames, column mapping, and drift diagnostics.

Raises:

Type Description
TypeError

If either X_a or X_b is not a DataFrame.

ValueError

If input feature DataFrames are empty.

Source code in src/stride/datasets/feature_matching.py
def align(self, X_a: pd.DataFrame, X_b: pd.DataFrame) -> FeatureAlignmentResult:
    """Align feature representations between dataset A and dataset B.

    Args:
        X_a: Feature matrix of Concept A (pre-drift).
        X_b: Feature matrix of Concept B (post-drift).

    Returns:
        Dataclass containing aligned DataFrames, column mapping, and drift diagnostics.

    Raises:
        TypeError: If either `X_a` or `X_b` is not a DataFrame.
        ValueError: If input feature DataFrames are empty.
    """
    if not isinstance(X_a, pd.DataFrame) or not isinstance(X_b, pd.DataFrame):
        raise TypeError("Both X_a and X_b must be pandas DataFrames.")
    if X_a.empty or X_b.empty:
        raise ValueError("Input feature DataFrames must not be empty.")

    X_a_work = X_a.copy()
    X_b_work = X_b.copy()

    # Step 1: Feature Matching
    if self.match_strategy == "exact":
        X_a_matched, X_b_matched, mapping, aligned_names = self._match_exact(X_a_work, X_b_work)
    elif self.match_strategy == "manual":
        X_a_matched, X_b_matched, mapping, aligned_names = self._match_manual(X_a_work, X_b_work)
    elif self.match_strategy == "statistical":
        X_a_matched, X_b_matched, mapping, aligned_names = self._match_statistical(X_a_work, X_b_work)
    elif self.match_strategy == "subspace":
        X_a_matched, X_b_matched, mapping, aligned_names = self._match_subspace(X_a_work, X_b_work)
    else:
        raise ValueError(f"Unknown match strategy: {self.match_strategy}")

    # Step 2: Distribution Normalization
    if self.align_distributions and self.scaler_type is not None:
        X_a_norm, X_b_norm = self._normalize(X_a_matched, X_b_matched)
    else:
        X_a_norm, X_b_norm = X_a_matched, X_b_matched

    # Step 3: Drift Diagnostics & Identification
    diagnostics, drifting_features = self.identify_drifting_features(X_a_norm, X_b_norm)

    return FeatureAlignmentResult(
        X_a_aligned=X_a_norm,
        X_b_aligned=X_b_norm,
        feature_mapping=mapping,
        aligned_feature_names=aligned_names,
        drifting_features=drifting_features,
        drift_diagnostics=diagnostics,
    )

identify_drifting_features

identify_drifting_features(X_a, X_b)

Evaluate statistical drift between aligned feature distributions.

Parameters:

Name Type Description Default
X_a DataFrame

Pre-drift aligned feature matrix.

required
X_b DataFrame

Post-drift aligned feature matrix.

required

Returns:

Type Description
DataFrame

Tuple of (diagnostics_df, drifting_features_list) where diagnostics

list[str]

contains KS-test statistics and p-values per feature.

Source code in src/stride/datasets/feature_matching.py
def identify_drifting_features(self, X_a: pd.DataFrame, X_b: pd.DataFrame) -> tuple[pd.DataFrame, list[str]]:
    """Evaluate statistical drift between aligned feature distributions.

    Args:
        X_a: Pre-drift aligned feature matrix.
        X_b: Post-drift aligned feature matrix.

    Returns:
        Tuple of `(diagnostics_df, drifting_features_list)` where diagnostics
        contains KS-test statistics and p-values per feature.
    """
    diagnostics: list[dict[str, Any]] = []
    drifting_features: list[str] = []

    for col in X_a.columns:
        vals_a = np.asarray(X_a[col].dropna())
        vals_b = np.asarray(X_b[col].dropna())

        # KS test
        ks_res = ks_2samp(vals_a, vals_b)
        ks_stat = float(ks_res.statistic)
        p_val = float(ks_res.pvalue)

        # Wasserstein distance
        wd = float(wasserstein_distance(vals_a, vals_b))

        mean_a = float(np.mean(vals_a)) if len(vals_a) else 0.0
        mean_b = float(np.mean(vals_b)) if len(vals_b) else 0.0
        std_a = float(np.std(vals_a)) if len(vals_a) else 0.0
        std_b = float(np.std(vals_b)) if len(vals_b) else 0.0

        is_drifting = bool(p_val < self.drift_significance_level)
        if is_drifting:
            drifting_features.append(col)

        diagnostics.append(
            {
                "feature": col,
                "ks_statistic": ks_stat,
                "p_value": p_val,
                "wasserstein_distance": wd,
                "mean_a": mean_a,
                "mean_b": mean_b,
                "mean_diff": abs(mean_b - mean_a),
                "std_a": std_a,
                "std_b": std_b,
                "is_drifting": is_drifting,
            }
        )

    diag_df = (
        pd.DataFrame(diagnostics)
        .sort_values(by=["is_drifting", "wasserstein_distance"], ascending=[False, False])
        .reset_index(drop=True)
    )

    return diag_df, drifting_features

HyperplaneDriftDataset

Bases: BaseDataset

generate

generate(
    n_samples_before=1000,
    n_samples_after=1000,
    n_features=2,
    n_drift_features=2,
    noise_percentage=0.05,
    drift_noise_percentage=0.1,
    mag_change=0.2,
    drift_width=1,
    random_seed=42,
    **kwargs,
)

Generate synthetic data stream using River's Hyperplane generator.

Both concepts are generated with the same random_seed. For abrupt drift the post-drift stream therefore starts from the same feature sequence: the first n_samples_after samples after the drift have exactly the same features as the first samples of the stream and only their labels differ. This is intentional and isolates pure concept drift (identical inputs, changed decision boundary). To compare two independent feature samples, use windows of at most n_samples_before / 2 samples on each side of the drift point.

Source code in src/stride/datasets/hyperplane_drift.py
def generate(
    self,
    n_samples_before=1000,
    n_samples_after=1000,
    n_features=2,
    n_drift_features=2,
    noise_percentage=0.05,
    drift_noise_percentage=0.1,
    mag_change=0.2,
    drift_width=1,
    random_seed=42,
    **kwargs,
):
    """
    Generate synthetic data stream using River's Hyperplane generator.

    Both concepts are generated with the same ``random_seed``. For abrupt drift
    the post-drift stream therefore starts from the same feature sequence: the
    first ``n_samples_after`` samples after the drift have exactly the same
    features as the first samples of the stream and only their labels differ.
    This is intentional and isolates pure concept drift (identical inputs,
    changed decision boundary). To compare two independent feature samples,
    use windows of at most ``n_samples_before / 2`` samples on each side of
    the drift point.
    """
    # Validation
    if n_features < 2:
        raise ValueError("n_features must be at least 2")
    if n_drift_features < 2:
        raise ValueError("n_drift_features must be at least 2")
    if n_drift_features > n_features:
        raise ValueError("n_drift_features cannot exceed n_features")

    # FIX: Avoid math range error in River's ConceptDriftStream for small width
    # The sigmoid function 1/(1+exp(-4*(i-p)/w)) overflows if w is very small.
    # If drift_width is small, we treat it as abrupt drift (chaining streams).
    SAFE_MIN_WIDTH = 50

    if drift_width < SAFE_MIN_WIDTH:
        # Manual Abrupt Drift
        stream1 = synth.Hyperplane(
            n_features=n_features, n_drift_features=n_drift_features, seed=random_seed, noise_percentage=noise_percentage
        )
        stream2 = synth.Hyperplane(
            n_features=n_features,
            n_drift_features=n_drift_features,
            seed=random_seed,
            mag_change=mag_change,
            noise_percentage=drift_noise_percentage,
        )

        # Chain the streams: First n_before from stream1, then n_after from stream2
        # Note: stream1 and stream2 are infinite generators
        stream_HP = itertools.chain(
            itertools.islice(stream1, n_samples_before), itertools.islice(stream2, n_samples_after)
        )
    else:
        stream_HP = synth.ConceptDriftStream(
            stream=synth.Hyperplane(
                n_features=n_features,
                n_drift_features=n_drift_features,
                seed=random_seed,
                noise_percentage=noise_percentage,
            ),
            drift_stream=synth.Hyperplane(
                n_features=n_features,
                n_drift_features=n_drift_features,
                seed=random_seed,
                mag_change=mag_change,
                noise_percentage=drift_noise_percentage,
            ),
            position=n_samples_before,
            width=drift_width,  # Gradual drift
            seed=random_seed,
        )
    return generate_river_data(stream_HP, n_samples_before + n_samples_after, n_features)

ImportedCSVDataset

ImportedCSVDataset(name, registry_info, registry)

Bases: BaseDataset

Source code in src/stride/datasets/imported_dataset.py
def __init__(self, name: str, registry_info: dict, registry: DatasetRegistry):
    self._name = name
    self.registry_info = registry_info
    self.registry = registry

generate

generate(**kwargs)

Load data from the stored CSV file.

Source code in src/stride/datasets/imported_dataset.py
def generate(self, **kwargs):
    """
    Load data from the stored CSV file.
    """
    file_path = self.registry.get_dataset_path(self._name)
    if not file_path:
        raise FileNotFoundError(f"File for dataset {self._name} not found.")

    df = pd.read_csv(file_path)

    target_col = self.registry_info.get("target_column", "target")
    selected_features = self.registry_info.get("selected_features")

    if target_col not in df.columns:
        raise ValueError(f"Target column '{target_col}' not found in dataset")

    y = df[target_col]

    if selected_features:
        # Filter columns, keeping only those selected (and checking existence)
        valid_features = [f for f in selected_features if f in df.columns and f != target_col]
        X = df[valid_features]
    else:
        X = df.drop(columns=[target_col])

    return X, y

LinearWeightInversionDriftDataset

Bases: BaseDataset

generate

generate(
    n_samples_before=1000,
    n_samples_after=1000,
    n_features=11,
    n_drift_features=5,
    random_seed=42,
    drift_width=1,
    **kwargs,
)

Generate synthetic data with Linear Weight Inversion Drift.

Source code in src/stride/datasets/linear_weight_inversion_drift.py
def generate(
    self,
    n_samples_before=1000,
    n_samples_after=1000,
    n_features=11,
    n_drift_features=5,
    random_seed=42,
    drift_width=1,
    **kwargs,
):
    """
    Generate synthetic data with Linear Weight Inversion Drift.
    """
    # Validation
    if n_drift_features > n_features:
        raise ValueError("n_drift_features cannot exceed n_features")
    if n_drift_features == 0:
        raise ValueError("n_drift_features must be greater than 0 to observe drift")

    np.random.seed(random_seed)
    total_samples = n_samples_before + n_samples_after
    drift_point = n_samples_before
    feature_names = [f"X{i + 1}" for i in range(n_features)]

    # --- Feature Generation (NO Data Drift) ---
    # Generate all features from a stable distribution (Uniform [0, 1])
    X = np.random.uniform(0, 1, (total_samples, n_features))

    # --- Define Weights for Equal Magnitude Concept Drift ---

    # Base weight for non-drifting features (e.g., X3, X4, ...)
    # Set to 1.0 so they have equal importance to drifting features (which are 1.0 or -1.0)
    stable_weight = 1.0
    stable_weights = np.full(n_features - n_drift_features, stable_weight)

    # Weights for the drifting features (e.g., X1, X2)
    # 1. Before Drift: All drifting features have a strong positive influence.
    drift_weight_before = 1.0
    weights_drift_before = np.full(n_drift_features, drift_weight_before)
    W_before = np.concatenate([weights_drift_before, stable_weights])

    # 2. After Drift: All drifting features have an equally strong
    # negative influence.
    drift_weight_after = -1.0
    weights_drift_after = np.full(n_drift_features, drift_weight_after)
    W_after = np.concatenate([weights_drift_after, stable_weights])

    # --- Calculate Scores and Labels ---

    # We calculate "concept 1" (Pre) labels for ALL samples
    scores_pre = X @ W_before + np.random.normal(0, 0.1, total_samples)
    threshold_pre = np.median(scores_pre)
    y_pre = (scores_pre > threshold_pre).astype(int)

    # We calculate "concept 2" (Post) labels for ALL samples
    scores_post = X @ W_after + np.random.normal(0, 0.1, total_samples)
    threshold_post = np.median(scores_post)
    y_post = (scores_post > threshold_post).astype(int)

    # --- Mix Labels Based on Drift Width (Sigmoid) ---
    y_array = apply_sigmoid_drift(y_pre, y_post, drift_point, drift_width)

    X_df = pd.DataFrame(X, columns=feature_names)
    y_series = pd.Series(y_array, name="Y")

    return X_df, y_series

MixedMultiWindowDataset

Bases: BaseDataset

generate

generate(
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    classification_function=1,
    random_seed=42,
    **kwargs,
)

Generate synthetic data stream using protree's Mixed generator.

Parameters:

Name Type Description Default
num_windows

Number of windows to generate.

100
window_length

Number of samples per window.

1000
drift_positions

List of sample positions where drifts occur, or comma-separated string.

None
drift_duration

Duration of drift transition in samples.

1
classification_function

Classification function (0 or 1).

1
random_seed

Random seed for reproducibility.

42
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description

Tuple of (X, y) data stream.

Source code in src/stride/datasets/mixed_multi_window.py
def generate(
    self,
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    classification_function=1,
    random_seed=42,
    **kwargs,
):
    """Generate synthetic data stream using protree's Mixed generator.

    Args:
        num_windows: Number of windows to generate.
        window_length: Number of samples per window.
        drift_positions: List of sample positions where drifts occur, or comma-separated string.
        drift_duration: Duration of drift transition in samples.
        classification_function: Classification function (0 or 1).
        random_seed: Random seed for reproducibility.
        **kwargs: Additional keyword arguments.

    Returns:
        Tuple of `(X, y)` data stream.
    """

    # Parse drift positions if string
    if isinstance(drift_positions, str):
        if drift_positions.strip():
            drift_positions = [int(x.strip()) for x in drift_positions.split(",")]
        else:
            drift_positions = []
    elif drift_positions is None:
        drift_positions = []

    # Ensure classification_function is in valid range using modulo
    classification_function = classification_function % 2

    # Create Mixed generator
    ds = Mixed(
        drift_position=drift_positions if drift_positions else 500,
        drift_duration=drift_duration,
        classification_function=classification_function,
        seed=random_seed,
    )

    # Generate all windows
    all_x = []
    all_y = []

    for i in range(num_windows):
        x_block, y_block = zip(*ds.take(window_length))
        all_x.extend(x_block)
        all_y.extend(y_block)

    # Convert to DataFrame and Series
    # The x_block items are dictionaries with feature names as keys
    X = feature_frame(all_x)
    y = pd.Series(all_y, name="target")

    return X, y

PlaneMultiWindowDataset

Bases: BaseDataset

generate

generate(
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    random_seed=42,
    **kwargs,
)

Generate synthetic data stream using protree's Plane generator.

Parameters:

Name Type Description Default
num_windows

Number of windows to generate.

100
window_length

Number of samples per window.

1000
drift_positions

List of sample positions where drifts occur, or comma-separated string.

None
drift_duration

Duration of drift transition in samples.

1
random_seed

Random seed for reproducibility.

42
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description

Tuple of (X, y) data stream.

Source code in src/stride/datasets/plane_multi_window.py
def generate(self, num_windows=100, window_length=1000, drift_positions=None, drift_duration=1, random_seed=42, **kwargs):
    """Generate synthetic data stream using protree's Plane generator.

    Args:
        num_windows: Number of windows to generate.
        window_length: Number of samples per window.
        drift_positions: List of sample positions where drifts occur, or comma-separated string.
        drift_duration: Duration of drift transition in samples.
        random_seed: Random seed for reproducibility.
        **kwargs: Additional keyword arguments.

    Returns:
        Tuple of `(X, y)` data stream.
    """

    # Parse drift positions if string
    if isinstance(drift_positions, str):
        if drift_positions.strip():
            drift_positions = [int(x.strip()) for x in drift_positions.split(",")]
        else:
            drift_positions = []
    elif drift_positions is None:
        drift_positions = []

    # Create Plane generator
    ds = Plane(drift_position=drift_positions if drift_positions else 500, drift_duration=drift_duration, seed=random_seed)

    # Generate all windows
    all_x = []
    all_y = []

    for i in range(num_windows):
        x_block, y_block = zip(*ds.take(window_length))
        all_x.extend(x_block)
        all_y.extend(y_block)

    # Convert to DataFrame and Series
    # The x_block items are dictionaries with feature names as keys
    X = feature_frame(all_x)
    y = pd.Series(all_y, name="target")

    return X, y

RBFDriftDataset

Bases: BaseDataset

RandomTreeMultiWindowDataset

Bases: BaseDataset

generate

generate(
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    n_informative=4,
    n_redundant=2,
    random_seed=42,
    **kwargs,
)

Generate synthetic data stream using protree's RandomTree generator.

Parameters:

Name Type Description Default
num_windows

Number of windows to generate.

100
window_length

Number of samples per window.

1000
drift_positions

List of sample positions where drifts occur, or comma-separated string.

None
drift_duration

Duration of drift transition in samples.

1
n_informative

Number of informative features.

4
n_redundant

Number of redundant features.

2
random_seed

Random seed for reproducibility.

42
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description

Tuple of (X, y) data stream.

Source code in src/stride/datasets/random_tree_multi_window.py
def generate(
    self,
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    n_informative=4,
    n_redundant=2,
    random_seed=42,
    **kwargs,
):
    """Generate synthetic data stream using protree's RandomTree generator.

    Args:
        num_windows: Number of windows to generate.
        window_length: Number of samples per window.
        drift_positions: List of sample positions where drifts occur, or comma-separated string.
        drift_duration: Duration of drift transition in samples.
        n_informative: Number of informative features.
        n_redundant: Number of redundant features.
        random_seed: Random seed for reproducibility.
        **kwargs: Additional keyword arguments.

    Returns:
        Tuple of `(X, y)` data stream.
    """

    # Parse drift positions if string
    if isinstance(drift_positions, str):
        if drift_positions.strip():
            drift_positions = [int(x.strip()) for x in drift_positions.split(",")]
        else:
            drift_positions = []
    elif drift_positions is None:
        drift_positions = []

    # Create RandomTree generator
    ds = RandomTree(
        drift_position=drift_positions if drift_positions else 500,
        drift_duration=drift_duration,
        seed=random_seed,
        n_informative=n_informative,
        n_redundant=n_redundant,
    )

    # Generate all windows
    all_x = []
    all_y = []

    for i in range(num_windows):
        x_block, y_block = zip(*ds.take(window_length))
        all_x.extend(x_block)
        all_y.extend(y_block)

    # Convert to DataFrame and Series
    # The x_block items are dictionaries with feature names as keys
    X = feature_frame(all_x)
    y = pd.Series(all_y, name="target")

    return X, y

RbfMultiWindowDataset

Bases: BaseDataset

generate

generate(
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    n_informative=5,
    n_centroids=11,
    random_seed=42,
    **kwargs,
)

Generate synthetic data stream using protree's Rbf generator.

Parameters:

Name Type Description Default
num_windows

Number of windows to generate.

100
window_length

Number of samples per window.

1000
drift_positions

List of sample positions where drifts occur, or comma-separated string.

None
drift_duration

Duration of drift transition in samples.

1
n_informative

Number of informative features.

5
n_centroids

Number of centroids.

11
random_seed

Random seed for reproducibility.

42
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description

Tuple of (X, y) data stream.

Source code in src/stride/datasets/rbf_multi_window.py
def generate(
    self,
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    n_informative=5,
    n_centroids=11,
    random_seed=42,
    **kwargs,
):
    """Generate synthetic data stream using protree's Rbf generator.

    Args:
        num_windows: Number of windows to generate.
        window_length: Number of samples per window.
        drift_positions: List of sample positions where drifts occur, or comma-separated string.
        drift_duration: Duration of drift transition in samples.
        n_informative: Number of informative features.
        n_centroids: Number of centroids.
        random_seed: Random seed for reproducibility.
        **kwargs: Additional keyword arguments.

    Returns:
        Tuple of `(X, y)` data stream.
    """

    # Parse drift positions if string
    if isinstance(drift_positions, str):
        if drift_positions.strip():
            drift_positions = [int(x.strip()) for x in drift_positions.split(",")]
        else:
            drift_positions = []
    elif drift_positions is None:
        drift_positions = []

    # Create Rbf generator
    ds = Rbf(
        drift_position=drift_positions if drift_positions else 500,
        drift_duration=drift_duration,
        seed=random_seed,
        n_informative=n_informative,
        n_centroids=n_centroids,
    )

    # Generate all windows
    all_x = []
    all_y = []

    for i in range(num_windows):
        x_block, y_block = zip(*ds.take(window_length))
        all_x.extend(x_block)
        all_y.extend(y_block)

    # Convert to DataFrame and Series
    # The x_block items are dictionaries with feature names as keys
    X = feature_frame(all_x)
    y = pd.Series(all_y, name="target")

    return X, y

SeaDriftDataset

Bases: BaseDataset

generate

generate(
    n_samples_before=1000,
    n_samples_after=1000,
    random_seed=42,
    n_features=3,
    drift_width=1,
    **kwargs,
)

Generate synthetic data stream using River's SEA generator. Drifts from variant 0 to variant 3 at the drift point. The SEA generator has 3 features, and we use all of them.

Both concepts are generated with the same random_seed. For abrupt drift the post-drift stream therefore starts from the same feature sequence: the first n_samples_after samples after the drift have exactly the same features as the first samples of the stream and only their labels differ. This is intentional and isolates pure concept drift (identical inputs, changed decision boundary). To compare two independent feature samples, use windows of at most n_samples_before / 2 samples on each side of the drift point.

Source code in src/stride/datasets/sea_drift.py
def generate(self, n_samples_before=1000, n_samples_after=1000, random_seed=42, n_features=3, drift_width=1, **kwargs):
    """
    Generate synthetic data stream using River's SEA generator.
    Drifts from variant 0 to variant 3 at the drift point.
    The SEA generator has 3 features, and we use all of them.

    Both concepts are generated with the same ``random_seed``. For abrupt drift
    the post-drift stream therefore starts from the same feature sequence: the
    first ``n_samples_after`` samples after the drift have exactly the same
    features as the first samples of the stream and only their labels differ.
    This is intentional and isolates pure concept drift (identical inputs,
    changed decision boundary). To compare two independent feature samples,
    use windows of at most ``n_samples_before / 2`` samples on each side of
    the drift point.
    """
    if drift_width < 5:
        # Sudden drift workaround for River overflow bug at small widths
        stream_SEA = itertools.chain(
            itertools.islice(synth.SEA(seed=random_seed, variant=0), n_samples_before),
            itertools.islice(synth.SEA(seed=random_seed, variant=3), n_samples_after),
        )
    else:
        stream_SEA = synth.ConceptDriftStream(
            stream=synth.SEA(seed=random_seed, variant=0),
            drift_stream=synth.SEA(seed=random_seed, variant=3),
            position=n_samples_before,
            width=drift_width,  # Gradual drift
            seed=random_seed,
        )
    return generate_river_data(stream_SEA, n_samples_before + n_samples_after, n_features=n_features)

SeaMultiWindowDataset

Bases: BaseDataset

generate

generate(
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    random_seed=42,
    **kwargs,
)

Generate synthetic data stream using protree's SEA generator.

Parameters:

Name Type Description Default
num_windows

Number of windows to generate.

100
window_length

Number of samples per window.

1000
drift_positions

List of sample positions where drifts occur, or comma-separated string.

None
drift_duration

Duration of drift transition in samples.

1
random_seed

Random seed for reproducibility.

42
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description

Tuple of (X, y) data stream.

Source code in src/stride/datasets/sea_multi_window.py
def generate(self, num_windows=100, window_length=1000, drift_positions=None, drift_duration=1, random_seed=42, **kwargs):
    """Generate synthetic data stream using protree's SEA generator.

    Args:
        num_windows: Number of windows to generate.
        window_length: Number of samples per window.
        drift_positions: List of sample positions where drifts occur, or comma-separated string.
        drift_duration: Duration of drift transition in samples.
        random_seed: Random seed for reproducibility.
        **kwargs: Additional keyword arguments.

    Returns:
        Tuple of `(X, y)` data stream.
    """

    # Parse drift positions if string
    if isinstance(drift_positions, str):
        if drift_positions.strip():
            drift_positions = [int(x.strip()) for x in drift_positions.split(",")]
        else:
            drift_positions = []
    elif drift_positions is None:
        drift_positions = []

    # Create SEA generator
    ds = Sea(drift_position=drift_positions if drift_positions else 500, drift_duration=drift_duration, seed=random_seed)

    # Generate all windows
    all_x = []
    all_y = []

    for i in range(num_windows):
        x_block, y_block = zip(*ds.take(window_length))
        all_x.extend(x_block)
        all_y.extend(y_block)

    # Convert to DataFrame and Series
    # The x_block items are dictionaries with feature names as keys
    X = feature_frame(all_x)
    y = pd.Series(all_y, name="target")

    return X, y

SemiSyntheticDriftDataset

SemiSyntheticDriftDataset(
    name="semi_synthetic",
    display_name=None,
    X_a=None,
    y_a=None,
    X_b=None,
    y_b=None,
    match_strategy="exact",
    manual_mapping=None,
    align_distributions=False,
    scaler_type="standard",
    scaler_mode="joint",
    schedule="gradual",
    n_samples=None,
    t_0=None,
    drift_width=200,
    period=500,
    random_seed=42,
    static_file_path=None,
    target_column="target",
)

Bases: BaseDataset

Semi-synthetic concept drift dataset generated by splicing two empirical datasets.

Adheres strictly to the Shaker Protocol (Shaker & Hüllermeier, 2015), providing feature alignment, controlled drift schedules, ground-truth change-point annotations, and drifting feature diagnostics.

Initialize SemiSyntheticDriftDataset.

Parameters:

Name Type Description Default
name str

Unique dataset identifier.

'semi_synthetic'
display_name str | None

Human-readable display name.

None
X_a DataFrame | None

Feature matrix for concept A.

None
y_a Series | None

Target series for concept A.

None
X_b DataFrame | None

Feature matrix for concept B.

None
y_b Series | None

Target series for concept B.

None
match_strategy str

Feature matching strategy ("exact", "manual", "statistical", or "subspace").

'exact'
manual_mapping dict[str, str] | None

Manual column mapping dict for "manual" strategy.

None
align_distributions bool

Whether to normalize feature distributions.

False
scaler_type str | None

Scaler type ("standard" or "minmax").

'standard'
scaler_mode str

Normalization mode ("joint" or "per_concept").

'joint'
schedule str

Drift schedule ("abrupt", "gradual", "incremental", or "recurring").

'gradual'
n_samples int | None

Total stream length in samples.

None
t_0 int | None

Drift inflection point / midpoint.

None
drift_width int

Transition window width.

200
period int

Period T for recurring drift.

500
random_seed int

Random seed for reproducibility.

42
static_file_path str | None

Path to static pre-generated CSV if loading from persistent cache.

None
target_column str

Target column name if loading from static CSV.

'target'
Source code in src/stride/datasets/semi_synthetic.py
def __init__(
    self,
    name: str = "semi_synthetic",
    display_name: str | None = None,
    X_a: pd.DataFrame | None = None,
    y_a: pd.Series | None = None,
    X_b: pd.DataFrame | None = None,
    y_b: pd.Series | None = None,
    match_strategy: str = "exact",
    manual_mapping: dict[str, str] | None = None,
    align_distributions: bool = False,
    scaler_type: str | None = "standard",
    scaler_mode: str = "joint",
    schedule: str = "gradual",
    n_samples: int | None = None,
    t_0: int | None = None,
    drift_width: int = 200,
    period: int = 500,
    random_seed: int = 42,
    static_file_path: str | None = None,
    target_column: str = "target",
) -> None:
    """Initialize SemiSyntheticDriftDataset.

    Args:
        name: Unique dataset identifier.
        display_name: Human-readable display name.
        X_a: Feature matrix for concept A.
        y_a: Target series for concept A.
        X_b: Feature matrix for concept B.
        y_b: Target series for concept B.
        match_strategy: Feature matching strategy ("exact", "manual",
            "statistical", or "subspace").
        manual_mapping: Manual column mapping dict for "manual" strategy.
        align_distributions: Whether to normalize feature distributions.
        scaler_type: Scaler type ("standard" or "minmax").
        scaler_mode: Normalization mode ("joint" or "per_concept").
        schedule: Drift schedule ("abrupt", "gradual", "incremental", or "recurring").
        n_samples: Total stream length in samples.
        t_0: Drift inflection point / midpoint.
        drift_width: Transition window width.
        period: Period T for recurring drift.
        random_seed: Random seed for reproducibility.
        static_file_path: Path to static pre-generated CSV if loading from persistent cache.
        target_column: Target column name if loading from static CSV.
    """
    self._name = name
    self._display_name = display_name or f"Semi-Synthetic: {name}"

    self.X_a = X_a
    self.y_a = y_a
    self.X_b = X_b
    self.y_b = y_b

    self.match_strategy = match_strategy
    self.manual_mapping = manual_mapping
    self.align_distributions = align_distributions
    self.scaler_type = scaler_type
    self.scaler_mode = scaler_mode
    self.schedule = schedule
    self.n_samples = n_samples
    self.t_0 = t_0
    self.drift_width = drift_width
    self.period = period
    self.random_seed = random_seed
    self.static_file_path = static_file_path
    self.target_column = target_column

    # Ground truth state
    self._ground_truth_drift_points: list[int] = []
    self._drift_intervals: list[tuple[int, int]] = []
    self._concept_stream: pd.Series = pd.Series(dtype=int)
    self._drifting_features: list[str] = []
    self._feature_mapping: dict[str, str] = {}
    self._drift_diagnostics: pd.DataFrame = pd.DataFrame()

concept_stream property

concept_stream

Stream array tracking the true generative source concept (0 for A, 1 for B).

drift_diagnostics property

drift_diagnostics

Full statistical diagnostics table for all aligned features.

drift_intervals property

drift_intervals

Interval ranges [start, end] of concept transition regions.

drifting_features property

drifting_features

Features with significant distribution drift between concepts.

feature_mapping property

feature_mapping

Mapping dictionary between Concept A and Concept B features.

ground_truth_drift_points property

ground_truth_drift_points

Timestamps of ground-truth drift midpoints / inflection points.

from_registry_info classmethod

from_registry_info(name, registry_info, registry)

Instantiate SemiSyntheticDriftDataset from DatasetRegistry configuration.

Parameters:

Name Type Description Default
name str

Dataset name.

required
registry_info dict

Registry metadata dictionary.

required
registry Any

DatasetRegistry instance.

required

Returns:

Type Description
SemiSyntheticDriftDataset

Configured dataset instance.

Source code in src/stride/datasets/semi_synthetic.py
@classmethod
def from_registry_info(cls, name: str, registry_info: dict, registry: Any) -> "SemiSyntheticDriftDataset":
    """Instantiate SemiSyntheticDriftDataset from DatasetRegistry configuration.

    Args:
        name: Dataset name.
        registry_info: Registry metadata dictionary.
        registry: DatasetRegistry instance.

    Returns:
        Configured dataset instance.
    """
    recipe = registry_info.get("recipe", {})
    csv_path = registry.get_dataset_path(name)

    ds = cls(
        name=name,
        display_name=registry_info.get("display_name", f"{name} (Semi-Synthetic)"),
        match_strategy=recipe.get("match_strategy", "exact"),
        manual_mapping=recipe.get("manual_mapping"),
        align_distributions=recipe.get("align_distributions", False),
        scaler_type=recipe.get("scaler_type", "standard"),
        scaler_mode=recipe.get("scaler_mode", "joint"),
        schedule=recipe.get("schedule", "gradual"),
        n_samples=recipe.get("n_samples"),
        t_0=recipe.get("t_0"),
        drift_width=recipe.get("drift_width", 200),
        period=recipe.get("period", 500),
        random_seed=recipe.get("random_seed", 42),
        static_file_path=csv_path,
        target_column=registry_info.get("target_column", "target"),
    )

    # Restore stored ground-truth metadata
    ds._ground_truth_drift_points = recipe.get("ground_truth_drift_points", [])
    raw_intervals = recipe.get("drift_intervals", [])
    ds._drift_intervals = [tuple(inv) for inv in raw_intervals]
    ds._drifting_features = recipe.get("drifting_features", [])
    ds._feature_mapping = recipe.get("feature_mapping", {})

    return ds

generate

generate(**kwargs)

Generate or load the semi-synthetic concept drift stream.

Returns:

Type Description
tuple[DataFrame, Series]

Tuple of (X, y) data stream.

Raises:

Type Description
ValueError

If source concepts are not provided and static file is missing.

Source code in src/stride/datasets/semi_synthetic.py
def generate(self, **kwargs) -> tuple[pd.DataFrame, pd.Series]:
    """Generate or load the semi-synthetic concept drift stream.

    Returns:
        Tuple of `(X, y)` data stream.

    Raises:
        ValueError: If source concepts are not provided and static file is missing.
    """
    # If pre-saved static CSV file is available and concepts are not supplied directly
    if self.static_file_path is not None and (self.X_a is None or self.X_b is None):
        df = pd.read_csv(self.static_file_path)
        target_col = kwargs.get("target_column", self.target_column)

        if target_col in df.columns:
            y = df[target_col]
            drop_cols = [target_col]
        else:
            y = df.iloc[:, -1]
            drop_cols = [df.columns[-1]]

        if "_concept" in df.columns:
            self._concept_stream = df["_concept"]
            drop_cols.append("_concept")

        X = df.drop(columns=[c for c in drop_cols if c in df.columns])
        return X, y

    if self.X_a is None or self.y_a is None or self.X_b is None or self.y_b is None:
        raise ValueError("Source concepts (X_a, y_a, X_b, y_b) must be provided to generate stream.")

    # Merge runtime overrides
    match_strat = kwargs.get("match_strategy", self.match_strategy)
    manual_map = kwargs.get("manual_mapping", self.manual_mapping)
    align_dist = kwargs.get("align_distributions", self.align_distributions)
    scaler_t = kwargs.get("scaler_type", self.scaler_type)
    scaler_m = kwargs.get("scaler_mode", self.scaler_mode)
    sched = kwargs.get("schedule", self.schedule)
    n_samp = kwargs.get("n_samples", self.n_samples)
    t_zero = kwargs.get("t_0", self.t_0)
    width = kwargs.get("drift_width", self.drift_width)
    per = kwargs.get("period", self.period)
    seed = kwargs.get("random_seed", self.random_seed)

    # 1. Feature Alignment
    matcher = FeatureMatcher(
        match_strategy=match_strat,
        manual_mapping=manual_map,
        align_distributions=align_dist,
        scaler_type=scaler_t,
        scaler_mode=scaler_m,
        random_state=seed,
    )
    alignment_result = matcher.align(self.X_a, self.X_b)

    self._feature_mapping = alignment_result.feature_mapping
    self._drifting_features = alignment_result.drifting_features
    self._drift_diagnostics = alignment_result.drift_diagnostics

    # 2. Stream Blending
    blender = DriftBlender(
        schedule=sched,
        n_samples=n_samp,
        t_0=t_zero,
        w=width,
        period=per,
        random_state=seed,
    )
    blend_result = blender.blend(
        alignment_result.X_a_aligned,
        self.y_a,
        alignment_result.X_b_aligned,
        self.y_b,
    )

    self._ground_truth_drift_points = blend_result.ground_truth_drift_points
    self._drift_intervals = blend_result.drift_intervals
    self._concept_stream = blend_result.concept_stream

    return blend_result.X, blend_result.y

get_params

get_params()

Return parameters for the semi-synthetic dataset.

Source code in src/stride/datasets/semi_synthetic.py
def get_params(self) -> dict[str, Any]:
    """Return parameters for the semi-synthetic dataset."""
    return {
        "match_strategy": self.match_strategy,
        "align_distributions": self.align_distributions,
        "scaler_type": self.scaler_type,
        "scaler_mode": self.scaler_mode,
        "schedule": self.schedule,
        "n_samples": self.n_samples,
        "t_0": self.t_0,
        "drift_width": self.drift_width,
        "period": self.period,
        "random_seed": self.random_seed,
    }

SineMultiWindowDataset

Bases: BaseDataset

generate

generate(
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    informative_attr_0=3,
    informative_attr_1=2,
    random_seed=42,
    **kwargs,
)

Generate synthetic data stream using protree's Sine generator.

Parameters:

Name Type Description Default
num_windows

Number of windows to generate.

100
window_length

Number of samples per window.

1000
drift_positions

List of sample positions where drifts occur, or comma-separated string.

None
drift_duration

Duration of drift transition in samples.

1
informative_attr_0

First informative attribute.

3
informative_attr_1

Second informative attribute.

2
random_seed

Random seed for reproducibility.

42
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description

Tuple of (X, y) data stream.

Source code in src/stride/datasets/sine_multi_window.py
def generate(
    self,
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    informative_attr_0=3,
    informative_attr_1=2,
    random_seed=42,
    **kwargs,
):
    """Generate synthetic data stream using protree's Sine generator.

    Args:
        num_windows: Number of windows to generate.
        window_length: Number of samples per window.
        drift_positions: List of sample positions where drifts occur, or comma-separated string.
        drift_duration: Duration of drift transition in samples.
        informative_attr_0: First informative attribute.
        informative_attr_1: Second informative attribute.
        random_seed: Random seed for reproducibility.
        **kwargs: Additional keyword arguments.

    Returns:
        Tuple of `(X, y)` data stream.
    """

    # Parse drift positions if string
    if isinstance(drift_positions, str):
        if drift_positions.strip():
            drift_positions = [int(x.strip()) for x in drift_positions.split(",")]
        else:
            drift_positions = []
    elif drift_positions is None:
        drift_positions = []

    # Create Sine generator
    ds = Sine(
        drift_position=drift_positions if drift_positions else 500,
        drift_duration=drift_duration,
        seed=random_seed,
        informative_attrs=(informative_attr_0, informative_attr_1),
    )

    # Generate all windows
    all_x = []
    all_y = []

    for i in range(num_windows):
        x_block, y_block = zip(*ds.take(window_length))
        all_x.extend(x_block)
        all_y.extend(y_block)

    # Convert to DataFrame and Series
    # The x_block items are dictionaries with feature names as keys
    X = feature_frame(all_x)
    y = pd.Series(all_y, name="target")

    return X, y

StaggerMultiWindowDataset

Bases: BaseDataset

generate

generate(
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    classification_function=0,
    random_seed=42,
    **kwargs,
)

Generate synthetic data stream using protree's Stagger generator.

Parameters:

Name Type Description Default
num_windows

Number of windows to generate.

100
window_length

Number of samples per window.

1000
drift_positions

List of sample positions where drifts occur, or comma-separated string.

None
drift_duration

Duration of drift transition in samples.

1
classification_function

Classification function (0, 1, or 2).

0
random_seed

Random seed for reproducibility.

42
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description

Tuple of (X, y) data stream.

Source code in src/stride/datasets/stagger_multi_window.py
def generate(
    self,
    num_windows=100,
    window_length=1000,
    drift_positions=None,
    drift_duration=1,
    classification_function=0,
    random_seed=42,
    **kwargs,
):
    """Generate synthetic data stream using protree's Stagger generator.

    Args:
        num_windows: Number of windows to generate.
        window_length: Number of samples per window.
        drift_positions: List of sample positions where drifts occur, or comma-separated string.
        drift_duration: Duration of drift transition in samples.
        classification_function: Classification function (0, 1, or 2).
        random_seed: Random seed for reproducibility.
        **kwargs: Additional keyword arguments.

    Returns:
        Tuple of `(X, y)` data stream.
    """

    # Parse drift positions if string
    if isinstance(drift_positions, str):
        if drift_positions.strip():
            drift_positions = [int(x.strip()) for x in drift_positions.split(",")]
        else:
            drift_positions = []
    elif drift_positions is None:
        drift_positions = []

    # Ensure classification_function is in valid range using modulo
    classification_function = classification_function % 3

    # Create Stagger generator
    ds = Stagger(
        drift_position=drift_positions if drift_positions else 500,
        drift_duration=drift_duration,
        classification_function=classification_function,
        seed=random_seed,
    )

    # Generate all windows
    all_x = []
    all_y = []

    for i in range(num_windows):
        x_block, y_block = zip(*ds.take(window_length))
        all_x.extend(x_block)
        all_y.extend(y_block)

    # Convert to DataFrame and Series
    # The x_block items are dictionaries with feature names as keys
    X = feature_frame(all_x)
    y = pd.Series(all_y, name="target")

    return X, y

get_sample_wine_quality_data

get_sample_wine_quality_data(
    n_samples=150, random_state=42
)

Generate sample empirical subsets of Red and White wine quality data.

Preserves authentic empirical means and standard deviations, reproducing the canonical Shaker & Hüllermeier (2015) non-stationary benchmark with significant physicochemical drift in total sulfur dioxide, volatile acidity, and chlorides.

Parameters:

Name Type Description Default
n_samples int

Number of samples per wine concept.

150
random_state int

Seed for reproducibility.

42

Returns:

Type Description
tuple[tuple[DataFrame, Series], tuple[DataFrame, Series]]

Tuple of ((X_red, y_red), (X_white, y_white)).

Source code in src/stride/datasets/benchmarks.py
def get_sample_wine_quality_data(
    n_samples: int = 150, random_state: int = 42
) -> tuple[tuple[pd.DataFrame, pd.Series], tuple[pd.DataFrame, pd.Series]]:
    """Generate sample empirical subsets of Red and White wine quality data.

    Preserves authentic empirical means and standard deviations, reproducing
    the canonical Shaker & Hüllermeier (2015) non-stationary benchmark with
    significant physicochemical drift in total sulfur dioxide, volatile acidity,
    and chlorides.

    Args:
        n_samples: Number of samples per wine concept.
        random_state: Seed for reproducibility.

    Returns:
        Tuple of `((X_red, y_red), (X_white, y_white))`.
    """
    rng = np.random.RandomState(random_state)

    # Red Wine Generation
    raw_red = rng.normal(loc=RED_WINE_MEANS, scale=RED_WINE_STDS, size=(n_samples, len(WINE_FEATURES)))
    raw_red = np.maximum(raw_red, 0.001)  # Physical constraints: non-negative
    X_red = pd.DataFrame(raw_red, columns=WINE_FEATURES)
    y_red_score = 5.0 + 0.3 * (X_red["alcohol"] - 10.0) - 1.5 * (X_red["volatile acidity"] - 0.5)
    y_red = (y_red_score + rng.normal(0, 0.5, size=n_samples) >= 5.5).astype(int)
    y_red.name = "quality"

    # White Wine Generation
    raw_white = rng.normal(loc=WHITE_WINE_MEANS, scale=WHITE_WINE_STDS, size=(n_samples, len(WINE_FEATURES)))
    raw_white = np.maximum(raw_white, 0.001)
    X_white = pd.DataFrame(raw_white, columns=WINE_FEATURES)
    y_white_score = 5.2 + 0.25 * (X_white["alcohol"] - 10.0) - 1.2 * (X_white["volatile acidity"] - 0.3)
    y_white = (y_white_score + rng.normal(0, 0.5, size=n_samples) >= 5.5).astype(int)
    y_white.name = "quality"

    return (X_red, y_red), (X_white, y_white)