Download src/binaryforecast/core/utils/datasets.py from SPARK-LAB/ST-DTKD: direct link, hf CLI and curl.
- Browser
- Download file 8.72 kB
-
https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/src/binaryforecast/core/utils/datasets.py
- Command line
-
hf download hf://SPARK-LAB/ST-DTKD/src/binaryforecast/core/utils/datasets.py
-
curl -L -o datasets.py https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/src/binaryforecast/core/utils/datasets.py
8.72 kB
| """Data loading, label alignment, preprocessing, splitting, and reproducibility.""" | |
| import json | |
| import os | |
| import random | |
| from pathlib import Path | |
| from typing import Dict, List, Sequence, Tuple | |
| import h5py | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| from torch.utils.data import Dataset | |
| from tqdm import tqdm | |
| CLASS_NAMES = ['<C', 'C', 'M', 'X'] | |
| def set_seed(seed: int=42, deterministic: bool=True) -> None: | |
| random.seed(seed) | |
| os.environ['PYTHONHASHSEED'] = str(seed) | |
| np.random.seed(seed) | |
| torch.manual_seed(seed) | |
| torch.cuda.manual_seed(seed) | |
| torch.cuda.manual_seed_all(seed) | |
| if deterministic: | |
| torch.backends.cudnn.deterministic = True | |
| torch.backends.cudnn.benchmark = False | |
| def split_dataframe_by_time(df: pd.DataFrame, train_start: str, train_end: str, val_start: str, val_end: str, test_start: str, test_end: str) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]: | |
| data = df.copy() | |
| data['timestamp'] = pd.to_datetime(data['timestamp'], errors='raise') | |
| train = data[(data.timestamp >= train_start) & (data.timestamp < train_end)].copy() | |
| val = data[(data.timestamp >= val_start) & (data.timestamp < val_end)].copy() | |
| test = data[(data.timestamp >= test_start) & (data.timestamp < test_end)].copy() | |
| return (train.reset_index(drop=True), val.reset_index(drop=True), test.reset_index(drop=True)) | |
| def _normalize_timestamp(series: pd.Series) -> pd.Series: | |
| return pd.to_datetime(series, errors='raise', utc=True).dt.tz_convert(None) | |
| def merge_primary_data_with_labels(index_csv: str, label_csv: str, label_col: str, join_cols: Sequence[str], audit_dir: Path, allow_drop_unlabeled: bool=False) -> pd.DataFrame: | |
| """Left-join four-class labels onto the primary index and write an audit.""" | |
| audit_dir.mkdir(parents=True, exist_ok=True) | |
| primary = pd.read_csv(index_csv) | |
| labels = pd.read_csv(label_csv) | |
| required_primary = {'timestamp', 'aia_idx', 'hmi_idx', 'aia_h5', 'hmi_h5'} | |
| missing_primary_columns = sorted(required_primary - set(primary.columns)) | |
| if missing_primary_columns: | |
| raise ValueError(f'Primary index is missing columns: {missing_primary_columns}') | |
| missing_label_columns = sorted((set(join_cols) | {label_col}) - set(labels.columns)) | |
| if missing_label_columns: | |
| raise ValueError(f'Label CSV is missing columns: {missing_label_columns}') | |
| missing_join_columns = sorted(set(join_cols) - set(primary.columns)) | |
| if missing_join_columns: | |
| raise ValueError(f'Primary index is missing join columns: {missing_join_columns}') | |
| if 'timestamp' in join_cols: | |
| primary['timestamp'] = _normalize_timestamp(primary['timestamp']) | |
| labels['timestamp'] = _normalize_timestamp(labels['timestamp']) | |
| primary_duplicates = primary[primary.duplicated(list(join_cols), keep=False)] | |
| label_duplicates = labels[labels.duplicated(list(join_cols), keep=False)] | |
| if not primary_duplicates.empty: | |
| primary_duplicates.to_csv(audit_dir / 'duplicate_primary_keys.csv', index=False) | |
| if not label_duplicates.empty: | |
| label_duplicates.to_csv(audit_dir / 'duplicate_label_keys.csv', index=False) | |
| if not primary_duplicates.empty or not label_duplicates.empty: | |
| raise ValueError('Join keys are not unique. Inspect duplicate_*_keys.csv and pass a more specific --join_cols.') | |
| labels = labels[list(join_cols) + [label_col]].copy() | |
| if label_col in primary.columns: | |
| primary = primary.rename(columns={label_col: f'{label_col}_primary'}) | |
| merged = primary.merge(labels, on=list(join_cols), how='left', validate='one_to_one', indicator=True) | |
| unmatched_primary = merged[merged['_merge'] == 'left_only'].copy() | |
| unmatched_labels = labels.merge(primary[list(join_cols)], on=list(join_cols), how='left', indicator=True) | |
| unmatched_labels = unmatched_labels[unmatched_labels['_merge'] == 'left_only'].copy() | |
| unmatched_primary.to_csv(audit_dir / 'unmatched_primary_rows.csv', index=False) | |
| unmatched_labels.to_csv(audit_dir / 'unmatched_label_rows.csv', index=False) | |
| summary = {'primary_rows': int(len(primary)), 'label_rows': int(len(labels)), 'matched_primary_rows': int((merged['_merge'] == 'both').sum()), 'unmatched_primary_rows': int(len(unmatched_primary)), 'unmatched_label_rows': int(len(unmatched_labels)), 'join_cols': list(join_cols), 'allow_drop_unlabeled': bool(allow_drop_unlabeled)} | |
| with open(audit_dir / 'merge_summary.json', 'w', encoding='utf-8') as handle: | |
| json.dump(summary, handle, ensure_ascii=False, indent=2) | |
| if not unmatched_primary.empty and (not allow_drop_unlabeled): | |
| raise RuntimeError(f"{len(unmatched_primary)} primary rows have no four-class label. Inspect {audit_dir / 'unmatched_primary_rows.csv'}. Regenerate labels or explicitly pass --allow_drop_unlabeled.") | |
| merged = merged[merged['_merge'] == 'both'].drop(columns='_merge').copy() | |
| numeric_labels = pd.to_numeric(merged[label_col], errors='raise') | |
| if not np.allclose(numeric_labels, np.round(numeric_labels)): | |
| raise ValueError(f'{label_col} contains non-integer values') | |
| merged[label_col] = numeric_labels.astype(np.int64) | |
| invalid = ~merged[label_col].isin(range(4)) | |
| if invalid.any(): | |
| bad = sorted(merged.loc[invalid, label_col].unique().tolist()) | |
| raise ValueError(f'{label_col} contains values outside 0/1/2/3: {bad}') | |
| return merged.reset_index(drop=True) | |
| def split_class_summary(name: str, df: pd.DataFrame, label_col: str) -> List[Dict]: | |
| counts = np.bincount(df[label_col].to_numpy(dtype=np.int64), minlength=4) | |
| rows = [] | |
| for (class_id, class_name) in enumerate(CLASS_NAMES): | |
| rows.append({'split': name, 'class_id': class_id, 'class_name': class_name, 'count': int(counts[class_id]), 'percentage': float(100.0 * counts[class_id] / max(1, len(df)))}) | |
| return rows | |
| def _preprocess_aia(image: np.ndarray) -> np.ndarray: | |
| return np.log1p(np.clip(image, 0, None)).astype(np.float32) | |
| def _preprocess_hmi(image: np.ndarray) -> np.ndarray: | |
| return (image / 3000.0).astype(np.float32) | |
| class SolarMultiSourceRAMDataset(Dataset): | |
| """Load only the requested modality into RAM using the original preprocessing.""" | |
| def __init__(self, dataframe: pd.DataFrame, cache_mode: str, label_col: str): | |
| self.index_df = dataframe.reset_index(drop=True).copy() | |
| self.cache_mode = cache_mode.upper() | |
| self.labels = self.index_df[label_col].astype(np.int64).to_numpy() | |
| if self.cache_mode not in {'AIA', 'HMI', 'BOTH'}: | |
| raise ValueError('cache_mode must be AIA, HMI, or BOTH') | |
| if self.index_df.empty: | |
| raise ValueError('Cannot construct a RAM dataset from an empty dataframe') | |
| self.aia_images = None | |
| self.hmi_images = None | |
| if self.cache_mode in {'AIA', 'BOTH'}: | |
| self.aia_images = self._load('aia_h5', 'aia_idx', _preprocess_aia, 'AIA') | |
| if self.cache_mode in {'HMI', 'BOTH'}: | |
| self.hmi_images = self._load('hmi_h5', 'hmi_idx', _preprocess_hmi, 'HMI') | |
| def _load(self, h5_col: str, idx_col: str, preprocess_fn, name: str) -> np.ndarray: | |
| first_path = str(self.index_df[h5_col].iloc[0]) | |
| first_idx = int(self.index_df[idx_col].iloc[0]) | |
| with h5py.File(first_path, 'r') as handle: | |
| sample = preprocess_fn(handle['images'][first_idx]) | |
| images = np.empty((len(self.index_df), *sample.shape), dtype=sample.dtype) | |
| grouped = self.index_df.groupby(h5_col, sort=False).groups | |
| for (h5_path, row_positions) in grouped.items(): | |
| positions = np.asarray(list(row_positions), dtype=np.int64) | |
| h5_indices = self.index_df.iloc[positions][idx_col].astype(int).to_numpy() | |
| with h5py.File(str(h5_path), 'r') as handle: | |
| dataset = handle['images'] | |
| iterator = zip(positions, h5_indices) | |
| for (position, h5_index) in tqdm(iterator, total=len(positions), desc=f'Load {name}: {Path(str(h5_path)).name}', dynamic_ncols=True): | |
| images[position] = preprocess_fn(dataset[int(h5_index)]) | |
| return images | |
| def __len__(self) -> int: | |
| return len(self.labels) | |
| def __getitem__(self, index: int): | |
| label = torch.tensor(int(self.labels[index]), dtype=torch.long) | |
| if self.cache_mode == 'AIA': | |
| return (torch.from_numpy(self.aia_images[index]), label) | |
| if self.cache_mode == 'HMI': | |
| return (torch.from_numpy(self.hmi_images[index]), label) | |
| return (torch.from_numpy(self.aia_images[index]), torch.from_numpy(self.hmi_images[index]), label) | |
| from binaryforecast.core.utils.data_protocol.temporal_dataset import SolarTemporalMultiSourceRAMDataset | |