Download Terra/dataset.py from MaxKJC/TSDBench: direct link, hf CLI and curl.
- Browser
- Download file 21 kB
-
https://huggingface.co/datasets/MaxKJC/TSDBench/resolve/main/Terra/dataset.py
- Command line
-
hf download hf://datasets/MaxKJC/TSDBench/Terra/dataset.py
-
curl -L -o dataset.py https://huggingface.co/datasets/MaxKJC/TSDBench/resolve/main/Terra/dataset.py
21 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 | |
| # 记录必要的字段信息是否提供 | |
| 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]: | |
| """ | |
| 从dataset.yaml开始,读取所有相关配置文件 | |
| Args: | |
| dataset_yaml_path: dataset.yaml文件路径 | |
| Returns: | |
| 整合所有配置的字典 | |
| """ | |
| # 获取协议目录路径 | |
| protocol_dir = Path(dataset_yaml_path).parent | |
| # 1. 读取dataset.yaml | |
| dataset_config = read_yaml(Path(dataset_yaml_path)) | |
| print(f"已读取 dataset.yaml: {dataset_config['dataset_name']}") | |
| # 2. 读取图配置 | |
| 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. 读取时序配置 | |
| 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. 整合所有配置 | |
| 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: # 从多个可能路径里面,返回其中的一个存在的路径 | |
| 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]: # 生成了所有潜在可能的存储路径 | |
| 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]: | |
| # 对meta_df进行解析, 解析df中的每一列表头信息,转化为字典形式 | |
| 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]: | |
| ''' | |
| graph字典中必要的字段信息包括: | |
| - 稀疏的邻接表 | |
| - 每一条边的权重 | |
| - 边上的特征 (可选) | |
| ''' | |
| 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: # 如果图中有特征,则将特征添加到字典中 | |
| 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 # 可以通过mode确定是单特征还是多特征 | |
| if variables_mode == "single": # 如果是单一特征,index就是timestamp,col_name就是sample_id, 特征名就是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: | |
| # 如果是多特征,表头会是 sample_id, timestamp, feature_name1, feature_name2, ... | |
| # 需要提取timestamp, 并根据timestamp的顺序,提取对应的特征value,结构应该是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 | |
| # 会将所有的yaml读成一个config | |
| class MultiModalDataset(LoadedDataset): | |
| """ | |
| 使用 ``read_all_configs`` 返回的整合配置,在 ``dataset_dir`` 下按协议解析数据路径并加载表格。 | |
| ``dataset_dir`` 通常为协议根目录(含 ``input_multimodal/`` 与 ``dataset.yaml`` 的父目录), | |
| 或等价的数据根目录;路径解析会依次尝试 ``dataset_dir/<file>`` 与 | |
| ``dataset_dir/input_multimodal/...`` 等候选位置。 | |
| """ | |
| 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 = {} | |
| # 读取meta_features数据 | |
| 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) # 对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: | |
| # 如果id_col_graph和id_col_time_series都存在,则需要构建一个id_col_graph和id_col_time_series的映射关系,将两种模态进行对齐 | |
| # 默认是将时序的id_col_time_series映射到图的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])} | |
| # 读取graphs数据 | |
| 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") # 图的级别,例如:node_level_task_graph, graph_level_task_graph | |
| graph_directed = gcfg.get("directed") # 图的类型,例如: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 # 图中的特征,例如: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) | |
| # 继续解析图中的具体特征 | |
| 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 # 将图数据加载到字典中, | |
| 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() | |
| # 在断点中检查是不是该有的信息都被加载了 | |
| # 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 "spatial_grid_graph" in dataset.graphs, ( | |
| # "dataset.graphs should include spatial_grid_graph" | |
| # ) | |
| # assert isinstance(dataset.graphs["spatial_grid_graph"], dict), ( | |
| # "spatial_grid_graph should be a parsed dict" | |
| # ) | |
| # assert isinstance(dataset.time_series, dict), "dataset.time_series should be a dict" | |
| # assert "longwave_radiation" in dataset.time_series, ( | |
| # "dataset.time_series should include longwave_radiation" | |
| # ) | |
| # longwave_radiation = dataset.time_series["longwave_radiation"] | |
| # assert isinstance(longwave_radiation, dict), ( | |
| # "longwave_radiation should be a parsed dict" | |
| # ) | |
| # for field in ("variables_mode", "timestamp", "value", "frequency"): | |
| # assert field in longwave_radiation, f"longwave_radiation should include {field}" | |
| # assert isinstance(dataset.time_series, dict), "dataset.time_series should be a dict" | |
| # assert "precipitation" in dataset.time_series, ( | |
| # "dataset.time_series should include precipitation" | |
| # ) | |
| # precipitation = dataset.time_series["precipitation"] | |
| # assert isinstance(precipitation, dict), ( | |
| # "precipitation should be a parsed dict" | |
| # ) | |
| # for field in ("variables_mode", "timestamp", "value", "frequency"): | |
| # assert field in precipitation, f"precipitation should include {field}" | |
| # assert isinstance(dataset.time_series, dict), "dataset.time_series should be a dict" | |
| # assert "pressure" in dataset.time_series, ( | |
| # "dataset.time_series should include pressure" | |
| # ) | |
| # pressure = dataset.time_series["pressure"] | |
| # assert isinstance(pressure, dict), ( | |
| # "pressure should be a parsed dict" | |
| # ) | |
| # for field in ("variables_mode", "timestamp", "value", "frequency"): | |
| # assert field in pressure, f"pressure should include {field}" | |
| # assert isinstance(dataset.time_series, dict), "dataset.time_series should be a dict" | |
| # assert "relative_humidity" in dataset.time_series, ( | |
| # "dataset.time_series should include relative_humidity" | |
| # ) | |
| # relative_humidity = dataset.time_series["relative_humidity"] | |
| # assert isinstance(relative_humidity, dict), ( | |
| # "relative_humidity should be a parsed dict" | |
| # ) | |
| # for field in ("variables_mode", "timestamp", "value", "frequency"): | |
| # assert field in relative_humidity, f"relative_humidity should include {field}" | |
| # assert isinstance(dataset.time_series, dict), "dataset.time_series should be a dict" | |
| # assert "shortwave_radiation" in dataset.time_series, ( | |
| # "dataset.time_series should include shortwave_radiation" | |
| # ) | |
| # shortwave_radiation = dataset.time_series["shortwave_radiation"] | |
| # assert isinstance(shortwave_radiation, dict), ( | |
| # "shortwave_radiation should be a parsed dict" | |
| # ) | |
| # for field in ("variables_mode", "timestamp", "value", "frequency"): | |
| # assert field in shortwave_radiation, f"shortwave_radiation should include {field}" | |
| # assert isinstance(dataset.time_series, dict), "dataset.time_series should be a dict" | |
| # assert "specific_humidity" in dataset.time_series, ( | |
| # "dataset.time_series should include specific_humidity" | |
| # ) | |
| # specific_humidity = dataset.time_series["specific_humidity"] | |
| # assert isinstance(specific_humidity, dict), ( | |
| # "specific_humidity should be a parsed dict" | |
| # ) | |
| # for field in ("variables_mode", "timestamp", "value", "frequency"): | |
| # assert field in specific_humidity, f"specific_humidity should include {field}" | |
| # assert isinstance(dataset.time_series, dict), "dataset.time_series should be a dict" | |
| # assert "temperature" in dataset.time_series, ( | |
| # "dataset.time_series should include temperature" | |
| # ) | |
| # temperature = dataset.time_series["temperature"] | |
| # assert isinstance(temperature, dict), ( | |
| # "temperature should be a parsed dict" | |
| # ) | |
| # for field in ("variables_mode", "timestamp", "value", "frequency"): | |
| # assert field in temperature, f"temperature should include {field}" | |
| # assert isinstance(dataset.time_series, dict), "dataset.time_series should be a dict" | |
| # assert "wind_speed" in dataset.time_series, ( | |
| # "dataset.time_series should include wind_speed" | |
| # ) | |
| # wind_speed = dataset.time_series["wind_speed"] | |
| # assert isinstance(wind_speed, dict), ( | |
| # "wind_speed should be a parsed dict" | |
| # ) | |
| # for field in ("variables_mode", "timestamp", "value", "frequency"): | |
| # assert field in wind_speed, f"wind_speed 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}") | |