Download Store_Sales/dataset.py from stable-ai/TSDBench: direct link, hf CLI and curl.
- Browser
- Download file 17.1 kB
-
https://huggingface.co/datasets/stable-ai/TSDBench/resolve/main/Store_Sales/dataset.py
- Command line
-
hf download hf://datasets/stable-ai/TSDBench/Store_Sales/dataset.py
-
curl -L -o dataset.py https://huggingface.co/datasets/stable-ai/TSDBench/resolve/main/Store_Sales/dataset.py
17.1 kB
| from __future__ import annotations | |
| import argparse | |
| import tempfile | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any, Dict, Iterable | |
| from torch.utils.data import Dataset, DataLoader | |
| import pandas as pd | |
| import yaml | |
| import ipdb | |
| # Record whether the required fields are provided. | |
| field_dict = { | |
| 'dataset': {'modalities': ['meta_features', 'node_level_task_graphs', 'time_series']}, | |
| 'graphs': ['', '', '', ''], | |
| 'time_series': ['', '', '', ' ', ''] | |
| } | |
| def read_yaml(path: Path) -> dict[str, Any]: | |
| with path.open("r", encoding="utf-8") as f: | |
| return yaml.safe_load(f) | |
| def read_all_configs(dataset_yaml_path: str) -> Dict[str, Any]: | |
| """ | |
| Read all related configuration files, starting from dataset.yaml. | |
| Args: | |
| dataset_yaml_path: Path to dataset.yaml. | |
| Returns: | |
| A dictionary containing all configurations. | |
| """ | |
| # Get the protocol directory path. | |
| protocol_dir = Path(dataset_yaml_path).parent | |
| # 1. Read dataset.yaml. | |
| dataset_config = read_yaml(Path(dataset_yaml_path)) | |
| print(f"已读取 dataset.yaml: {dataset_config['dataset_name']}") | |
| # 2. Read graph configurations. | |
| graph_configs = {} | |
| if 'node_level_task_graphs' in dataset_config['modalities']: | |
| graph_ids = dataset_config['modalities']['node_level_task_graphs'].get('graph_ids', []) | |
| for graph_id in graph_ids: | |
| graph_yaml_path = protocol_dir / f"input_multimodal/node_level_task_graphs/{graph_id}/graph.yaml" | |
| if graph_yaml_path.exists(): | |
| graph_config = read_yaml(Path(graph_yaml_path)) | |
| graph_configs[graph_id] = graph_config | |
| print(f"已读取 graph.yaml: {graph_id}") | |
| else: | |
| print(f"警告: 未找到 graph.yaml: {graph_yaml_path}") | |
| # 3. Read time series configurations. | |
| ts_configs = {} | |
| if 'time_series' in dataset_config['modalities']: | |
| ts_ids = dataset_config['modalities']['time_series'].get('time_series_ids', []) | |
| for ts_id in ts_ids: | |
| ts_yaml_path = protocol_dir / f"input_multimodal/time_series/{ts_id}/series.yaml" | |
| if ts_yaml_path.exists(): | |
| ts_config = read_yaml(Path(ts_yaml_path)) | |
| ts_configs[ts_id] = ts_config | |
| print(f"已读取 series.yaml: {ts_id}") | |
| else: | |
| print(f"警告: 未找到 series.yaml: {ts_yaml_path}") | |
| # 4. Combine all configurations. | |
| all_configs = { | |
| 'dataset': dataset_config, | |
| 'graphs': graph_configs, | |
| 'time_series': ts_configs | |
| } | |
| return all_configs | |
| def _first_existing(candidates: Iterable[Path]) -> Path: | |
| candidate_list = [Path(p).expanduser() for p in candidates] | |
| for p in candidate_list: # Return an existing path from the candidate paths. | |
| if p.is_file(): | |
| return p.resolve() | |
| shown = ", ".join(str(c) for c in candidate_list) | |
| raise FileNotFoundError(f"None of the candidate paths exist: {shown}") | |
| def _load_frame(path: Path) -> pd.DataFrame: | |
| """Load a single-table file as used in protocol YAMLs (csv / parquet / h5).""" | |
| path = Path(path).expanduser().resolve() | |
| suf = path.suffix.lower() | |
| if suf == ".csv": | |
| return pd.read_csv(path) | |
| if suf in (".tsv", ".txt"): | |
| return pd.read_csv(path, sep="\t") | |
| if suf in (".parquet", ".pq"): | |
| return pd.read_parquet(path) | |
| if suf in (".h5", ".hdf5", ".hdf"): | |
| return pd.read_hdf(path) | |
| raise ValueError(f"Unsupported data file extension for {path}") | |
| def _meta_candidates(dataset_dir: Path, file_name: str) -> list[Path]: | |
| p = Path(file_name).expanduser() | |
| if p.is_absolute(): | |
| return [p] | |
| return [ | |
| dataset_dir / "input_multimodal" / file_name, | |
| ] | |
| def _graph_file_candidates(dataset_dir: Path, graph_level: str, graph_id: str, file_name: str) -> list[Path]: | |
| p = Path(file_name).expanduser() | |
| if p.is_absolute(): | |
| return [p] | |
| base = [ | |
| dataset_dir | |
| / "input_multimodal" | |
| / graph_level | |
| / graph_id | |
| / file_name, | |
| ] | |
| return base | |
| def _series_file_candidates(dataset_dir: Path, series_id: str, file_name: str) -> list[Path]: # Generate all candidate storage paths. | |
| p = Path(file_name).expanduser() | |
| if p.is_absolute(): | |
| return [p] | |
| return [ | |
| dataset_dir / "input_multimodal" / "time_series" / series_id / file_name, | |
| dataset_dir / file_name, | |
| dataset_dir / "input_multimodal" / file_name, | |
| ] | |
| def _parse_meta(meta: pd.DataFrame) -> Dict[str, Any]: | |
| # Parse each column in meta_df and convert the data to a dictionary. | |
| meta_dict = {} | |
| for col in meta.columns: | |
| meta_dict[col] = list(meta[col]) | |
| return meta_dict | |
| def _parse_graph(graph: pd.DataFrame, graph_features: list[str] | None) -> Dict[str, Any]: | |
| ''' | |
| Required information in the graph dictionary includes: | |
| - A sparse adjacency list | |
| - The weight of each edge | |
| - Edge features (optional) | |
| ''' | |
| graph_dict = {} | |
| required_fields = ['src_id', 'dst_id', 'weight'] | |
| for field in required_fields: | |
| if field not in graph.columns: | |
| raise ValueError(f"Missing required column: {field}") | |
| graph_dict['edge'] = list(zip(graph['src_id'], graph['dst_id'])) | |
| graph_dict['weight'] = graph['weight'].tolist() | |
| if all(x == 1.0 for x in list(graph_dict['weight'])): | |
| graph_dict['weighted'] = False | |
| else: | |
| graph_dict['weighted'] = True | |
| if graph_features is not None: # Add graph features to the dictionary if they are available. | |
| for feature in graph_features: | |
| graph_dict[feature] = list(graph[feature]) | |
| return graph_dict | |
| def _parse_time_series(time_series: pd.DataFrame, scfg: dict[str, Any], time2graph_map: Dict[str, Any]|None) -> Dict[str, Any]: | |
| time_series_dict = {} | |
| variables_mode = scfg.get("variables_mode") | |
| time_series_dict['variables_mode'] = variables_mode # Use mode to distinguish single-variable and multivariable data. | |
| if variables_mode == "single": # For a single variable, the index is timestamp, column names are sample_id values, and the feature name is series_id. | |
| time_type = str(time_series.index.dtype) | |
| time_series_dict['time_type'] = time_type | |
| time_series_dict['timestamp'] = time_series.index.tolist() | |
| time_series_dict['value'] = {} | |
| if time2graph_map: # | |
| for col in time_series.columns: | |
| time_series_dict['value'][time2graph_map.get(int(col), col)] = list(time_series[col]) | |
| else: | |
| for col in time_series.columns: | |
| time_series_dict['value'][col] = list(time_series[col]) | |
| else: | |
| # For multiple variables, the columns are sample_id, timestamp, feature_name1, feature_name2, ... | |
| # Extract timestamps and feature values in timestamp order, using the structure feature_name*: {sample_id: [values]}. | |
| index_cfg = scfg.get("index") or {} | |
| id_col = index_cfg.get("id_colunm") or index_cfg.get("id_column") | |
| time_col = index_cfg.get("time_column") | |
| if not id_col: | |
| raise ValueError("time_series.index must configure id_colunm or id_column") | |
| if not time_col: | |
| raise ValueError("time_series.index must configure time_column") | |
| required_columns = [id_col, time_col] | |
| missing_columns = [col for col in required_columns if col not in time_series.columns] | |
| if missing_columns: | |
| raise ValueError(f"Missing required time series column(s): {missing_columns}") | |
| series_features = index_cfg.get("feature_column") | |
| if not series_features: | |
| series_features = [col for col in time_series.columns if col not in required_columns] | |
| elif isinstance(series_features, str): | |
| series_features = [series_features] | |
| else: | |
| series_features = list(series_features) | |
| if not series_features: | |
| raise ValueError("No feature columns configured or inferred for time series") | |
| missing_features = [col for col in series_features if col not in time_series.columns] | |
| if missing_features: | |
| raise ValueError(f"Missing configured feature column(s): {missing_features}") | |
| sorted_time_series = time_series.sort_values([id_col, time_col]) | |
| time_series_dict['feature_names'] = series_features | |
| time_series_dict['time_type'] = str(time_series[time_col].dtype) | |
| time_series_dict['timestamp'] = sorted(time_series[time_col].drop_duplicates().tolist()) | |
| timestamp_by_sample = {} | |
| time_series_dict['value'] = {feature: {} for feature in series_features} | |
| for sample_id, sample_df in sorted_time_series.groupby(id_col, sort=False): | |
| output_sample_id = time2graph_map.get(sample_id, sample_id) if time2graph_map else sample_id | |
| timestamp_by_sample[output_sample_id] = sample_df[time_col].tolist() | |
| for feature in series_features: | |
| time_series_dict['value'][feature][output_sample_id] = sample_df[feature].tolist() | |
| if any(timestamps != time_series_dict['timestamp'] for timestamps in timestamp_by_sample.values()): | |
| time_series_dict['timestamp_by_sample'] = timestamp_by_sample | |
| return time_series_dict | |
| class LoadedDataset: | |
| dataset_dir: Path | |
| config: dict[str, Any] | |
| meta_features: Dict[str, Any] | |
| graphs: Dict[str, Any] | |
| time_series: Dict[str, Any] | |
| # def _check_graphs(graph_config: dict[str, Any]) -> None: | |
| # check | |
| # Read all YAML files into one configuration. | |
| class MultiModalDataset(LoadedDataset): | |
| """ | |
| Use the configuration returned by ``read_all_configs`` to resolve protocol paths under ``dataset_dir`` and load tables. | |
| ``dataset_dir`` is usually the protocol root containing ``input_multimodal/`` and ``dataset.yaml``, | |
| or an equivalent data root. Path resolution tries ``dataset_dir/<file>`` and | |
| ``dataset_dir/input_multimodal/...``, among other candidate locations, in order. | |
| """ | |
| def __init__(self, config: dict[str, Any], dataset_dir: Path | str) -> None: | |
| root = Path(dataset_dir).expanduser().resolve() | |
| dataset_cfg = config["dataset"] | |
| modalities = dataset_cfg.get("modalities") or {} | |
| time2graph_map = {} | |
| # Read meta_features data. | |
| meta_block: Dict[str, Any] = {} | |
| if isinstance(modalities.get("meta_features"), dict): | |
| mf = modalities["meta_features"] | |
| meta_file = mf.get("file_name") | |
| if mf.get("required") and not meta_file: | |
| raise ValueError("meta_features is required but file_name is not configured") | |
| if meta_file: | |
| meta_path = _first_existing(_meta_candidates(root, str(meta_file))) | |
| meta_tmp = _load_frame(meta_path) | |
| meta_features = _parse_meta(meta_tmp) # Parse meta_df. | |
| sample_def = dataset_cfg.get("sample_defination") or dataset_cfg.get( | |
| "sample_definition" | |
| ) | |
| id_col_graph = None | |
| id_col_time_series = None | |
| if isinstance(sample_def, dict): | |
| id_col_graph = sample_def.get("sample_id_graph") | |
| id_col_time_series = sample_def.get("sample_id_time_series") | |
| meta_block = { | |
| "path": str(meta_path), | |
| "features": meta_features, | |
| "sample_id_graph": id_col_graph, | |
| "sample_id_time_series": id_col_time_series, | |
| } | |
| if id_col_graph is not None and id_col_time_series is not None: | |
| # If both id_col_graph and id_col_time_series exist, build a mapping between them to align the two modalities. | |
| # By default, map time series IDs from id_col_time_series to graph IDs in id_col_graph. | |
| time2graph_map = {time_id: graph_id for time_id, graph_id in zip(meta_tmp[id_col_time_series], meta_tmp[id_col_graph])} | |
| # Read graph data. | |
| graphs: Dict[str, Any] = {} | |
| for gid, gcfg in (config.get("graphs") or {}).items(): | |
| if not isinstance(gcfg, dict): | |
| continue | |
| fname = gcfg.get("file_name") | |
| graph_level = gcfg.get("graph_level") # Graph level, for example: node_level_task_graph, graph_level_task_graph. | |
| graph_directed = gcfg.get("directed") # Graph type, for example: directed, undirected. | |
| edge_features_cfg = gcfg.get("edge_features") or {} | |
| graph_features = edge_features_cfg.get("feature_name") if edge_features_cfg.get("available") else None # Graph features, for example: edge_features. | |
| if not fname: | |
| continue | |
| gpath = _first_existing(_graph_file_candidates(root, str(graph_level), str(gid), str(fname))) | |
| tmp_graph = _load_frame(gpath) | |
| # Continue parsing individual graph features. | |
| tmp_graph_dict = _parse_graph(tmp_graph, graph_features) | |
| tmp_graph_dict['directed'] = graph_directed | |
| tmp_graph_dict['edge_features'] = graph_features | |
| graphs[str(gid)] = tmp_graph_dict # Load graph data into the dictionary. | |
| time_series: Dict[str, Any] = {} | |
| for sid, scfg in (config.get("time_series") or {}).items(): | |
| if not isinstance(scfg, dict): | |
| continue | |
| fname = scfg.get("file_name") | |
| if not fname: | |
| continue | |
| spath = _first_existing(_series_file_candidates(root, str(sid), str(fname))) | |
| tmp_time_series = _load_frame(spath) | |
| frequency = scfg.get("temporal_granularity") | |
| tmp_time_series_dict = _parse_time_series(tmp_time_series, scfg, time2graph_map) | |
| tmp_time_series_dict['frequency'] = frequency | |
| time_series[str(sid)] = tmp_time_series_dict | |
| super().__init__( | |
| dataset_dir=root, | |
| config=config, | |
| meta_features=meta_block, | |
| graphs=graphs, | |
| time_series=time_series, | |
| ) | |
| if __name__ == '__main__': | |
| protocol_dir = Path(__file__).resolve().parent | |
| dataset_yaml_path = protocol_dir / "dataset.yaml" | |
| configs = read_all_configs(str(dataset_yaml_path)) | |
| dataset = MultiModalDataset(configs, protocol_dir) | |
| ipdb.set_trace() | |
| # At the breakpoint, check whether all required information has been loaded. | |
| assert isinstance(dataset.config, dict), "dataset.config should be a dict" | |
| assert "dataset" in dataset.config, "dataset.config should include dataset config" | |
| assert isinstance(dataset.meta_features, dict), "dataset.meta_features should be a dict" | |
| assert "features" in dataset.meta_features, "dataset.meta_features should include parsed features" | |
| assert isinstance(dataset.meta_features["features"], dict), ( | |
| "dataset.meta_features['features'] should be a dict" | |
| ) | |
| assert isinstance(dataset.graphs, dict), "dataset.graphs should be a dict" | |
| assert "store_family_relation_graph" in dataset.graphs, ( | |
| "dataset.graphs should include store_family_relation_graph" | |
| ) | |
| assert isinstance(dataset.graphs["store_family_relation_graph"], dict), ( | |
| "store_family_relation_graph should be a parsed dict" | |
| ) | |
| assert isinstance(dataset.time_series, dict), "dataset.time_series should be a dict" | |
| assert "sales" in dataset.time_series, ( | |
| "dataset.time_series should include sales" | |
| ) | |
| traffic_flow = dataset.time_series["sales"] | |
| assert isinstance(traffic_flow, dict), ( | |
| "traffic_flow should be a parsed dict" | |
| ) | |
| for field in ("variables_mode", "timestamp", "value", "frequency"): | |
| assert field in traffic_flow, f"traffic_flow should include {field}" | |
| print(f"Dataset: {dataset.config['dataset'].get('dataset_name')}") | |
| print(f"Protocol dir: {dataset.dataset_dir}") | |
| print(f"Meta features: columns={len(dataset.meta_features.get('features', {}))}") | |
| for graph_id, graph_dict in dataset.graphs.items(): | |
| print( | |
| f"Graph[{graph_id}]: edges={len(graph_dict.get('edge', []))}, " | |
| f"directed={graph_dict.get('directed')}" | |
| ) | |
| for series_id, series_data in dataset.time_series.items(): | |
| if isinstance(series_data, dict): | |
| value = series_data.get("value", {}) | |
| if series_data.get("variables_mode") == "single": | |
| feature_count = 1 | |
| sample_count = len(value) | |
| else: | |
| feature_count = len(value) | |
| sample_count = len(next(iter(value.values()), {})) | |
| print( | |
| f"TimeSeries[{series_id}]: mode={series_data.get('variables_mode')}, " | |
| f"features={feature_count}, timestamps={len(series_data.get('timestamp', []))}, " | |
| f"samples={sample_count}" | |
| ) | |
| else: | |
| print(f"TimeSeries[{series_id}]: shape={series_data.shape}") | |