from __future__ import annotations from dataclasses import dataclass from pathlib import Path import json import shutil import datasets as hfd import h5py import pgzip as gzip import pyarrow as pa # ┌──────────────┐ # │ Metadata │ # └──────────────┘ @dataclass class CaseSizes: n_bus: int n_load: int n_gen: int n_branch: int CASENAME = "6470_rte" SIZES = CaseSizes(n_bus=6470, n_load=3670, n_gen=761, n_branch=9005) NUM_TRAIN = 73912 NUM_TEST = 18478 NUM_INFEASIBLE = 7628 SPLITFILES = { "train/SOCOPF/dual.h5.gz": ["train/SOCOPF/dual/xaa", "train/SOCOPF/dual/xab"], } URL = "https://huggingface.co/datasets/PGLearn/PGLearn-Large-6470_rte" DESCRIPTION = """\ The 6470_rte PGLearn optimal power flow dataset, part of the PGLearn-Large collection. \ """ VERSION = hfd.Version("1.0.0") DEFAULT_CONFIG_DESCRIPTION="""\ This configuration contains feasible input, primal solution, and dual solution data \ for the ACOPF, DCOPF, and SOCOPF formulations on the {case} system. For case data, \ download the case.json.gz file from the `script` branch of the repository. \ https://huggingface.co/datasets/PGLearn/PGLearn-Large-6470_rte/blob/script/case.json.gz """ USE_ML4OPF_WARNING = """ ================================================================================================ Loading PGLearn-Large-6470_rte through the `datasets.load_dataset` function may be slow. Consider using ML4OPF to directly convert to `torch.Tensor`; for more info see: https://github.com/AI4OPT/ML4OPF?tab=readme-ov-file#manually-loading-data Or, use `huggingface_hub.snapshot_download` and an HDF5 reader; for more info see: https://huggingface.co/datasets/PGLearn/PGLearn-Large-6470_rte#downloading-individual-files ================================================================================================ """ CITATION = """\ @article{klamkinpglearn, title={{PGLearn - An Open-Source Learning Toolkit for Optimal Power Flow}}, author={Klamkin, Michael and Tanneau, Mathieu and Van Hentenryck, Pascal}, year={2025}, }\ """ IS_COMPRESSED = True # ┌──────────────────┐ # │ Formulations │ # └──────────────────┘ def acopf_features(sizes: CaseSizes, primal: bool, dual: bool, meta: bool): features = {} if primal: features.update(acopf_primal_features(sizes)) if dual: features.update(acopf_dual_features(sizes)) if meta: features.update({f"ACOPF/{k}": v for k, v in META_FEATURES.items()}) return features def dcopf_features(sizes: CaseSizes, primal: bool, dual: bool, meta: bool): features = {} if primal: features.update(dcopf_primal_features(sizes)) if dual: features.update(dcopf_dual_features(sizes)) if meta: features.update({f"DCOPF/{k}": v for k, v in META_FEATURES.items()}) return features def socopf_features(sizes: CaseSizes, primal: bool, dual: bool, meta: bool): features = {} if primal: features.update(socopf_primal_features(sizes)) if dual: features.update(socopf_dual_features(sizes)) if meta: features.update({f"SOCOPF/{k}": v for k, v in META_FEATURES.items()}) return features FORMULATIONS_TO_FEATURES = { "ACOPF": acopf_features, "DCOPF": dcopf_features, "SOCOPF": socopf_features, } # ┌───────────────────┐ # │ BuilderConfig │ # └───────────────────┘ class PGLearnLarge6470_rteConfig(hfd.BuilderConfig): """BuilderConfig for PGLearn-Large-6470_rte. By default, primal solution data, metadata, input, casejson, are included for the train and test splits. To modify the default configuration, pass attributes of this class to `datasets.load_dataset`: Attributes: formulations (list[str]): The formulation(s) to include, e.g. ["ACOPF", "DCOPF"] primal (bool, optional): Include primal solution data. Defaults to True. dual (bool, optional): Include dual solution data. Defaults to False. meta (bool, optional): Include metadata. Defaults to True. input (bool, optional): Include input data. Defaults to True. casejson (bool, optional): Include case.json data. Defaults to True. train (bool, optional): Include training samples. Defaults to True. test (bool, optional): Include testing samples. Defaults to True. infeasible (bool, optional): Include infeasible samples. Defaults to False. """ def __init__(self, formulations: list[str], primal: bool=True, dual: bool=False, meta: bool=True, input: bool = True, casejson: bool=True, train: bool=True, test: bool=True, infeasible: bool=False, compressed: bool=IS_COMPRESSED, **kwargs ): super(PGLearnLarge6470_rteConfig, self).__init__(version=VERSION, **kwargs) self.case = CASENAME self.formulations = formulations self.primal = primal self.dual = dual self.meta = meta self.input = input self.casejson = casejson self.train = train self.test = test self.infeasible = infeasible self.gz_ext = ".gz" if compressed else "" @property def size(self): return SIZES @property def features(self): features = {} if self.casejson: features.update(case_features()) if self.input: features.update(input_features(SIZES)) for formulation in self.formulations: features.update(FORMULATIONS_TO_FEATURES[formulation](SIZES, self.primal, self.dual, self.meta)) return hfd.Features(features) @property def splits(self): splits: dict[hfd.Split, dict[str, str | int]] = {} if self.train: splits[hfd.Split.TRAIN] = { "name": "train", "num_examples": NUM_TRAIN } if self.test: splits[hfd.Split.TEST] = { "name": "test", "num_examples": NUM_TEST } if self.infeasible: splits[hfd.Split("infeasible")] = { "name": "infeasible", "num_examples": NUM_INFEASIBLE } return splits @property def urls(self): urls: dict[str, None | str | list] = { "case": None, "train": [], "test": [], "infeasible": [], } if self.casejson: urls["case"] = f"case.json" + self.gz_ext else: urls.pop("case") split_names = [] if self.train: split_names.append("train") if self.test: split_names.append("test") if self.infeasible: split_names.append("infeasible") for split in split_names: if self.input: urls[split].append(f"{split}/input.h5" + self.gz_ext) for formulation in self.formulations: if self.primal: filename = f"{split}/{formulation}/primal.h5" + self.gz_ext if filename in SPLITFILES: urls[split].append(SPLITFILES[filename]) else: urls[split].append(filename) if self.dual: filename = f"{split}/{formulation}/dual.h5" + self.gz_ext if filename in SPLITFILES: urls[split].append(SPLITFILES[filename]) else: urls[split].append(filename) if self.meta: filename = f"{split}/{formulation}/meta.h5" + self.gz_ext if filename in SPLITFILES: urls[split].append(SPLITFILES[filename]) else: urls[split].append(filename) return urls # ┌────────────────────┐ # │ DatasetBuilder │ # └────────────────────┘ class PGLearnLarge6470_rte(hfd.ArrowBasedBuilder): """DatasetBuilder for PGLearn-Large-6470_rte. The main interface is `datasets.load_dataset` with `trust_remote_code=True`, e.g. ```python from datasets import load_dataset ds = load_dataset("PGLearn/PGLearn-Large-6470_rte", trust_remote_code=True, # modify the default configuration by passing kwargs formulations=["DCOPF"], dual=False, meta=False, ) ``` """ DEFAULT_WRITER_BATCH_SIZE = 10000 BUILDER_CONFIG_CLASS = PGLearnLarge6470_rteConfig DEFAULT_CONFIG_NAME=CASENAME BUILDER_CONFIGS = [ PGLearnLarge6470_rteConfig( name=CASENAME, description=DEFAULT_CONFIG_DESCRIPTION.format(case=CASENAME), formulations=list(FORMULATIONS_TO_FEATURES.keys()), primal=True, dual=True, meta=True, input=True, casejson=False, train=True, test=True, infeasible=False, ) ] def _info(self): return hfd.DatasetInfo( features=self.config.features, splits=self.config.splits, description=DESCRIPTION + self.config.description, homepage=URL, citation=CITATION, ) def _split_generators(self, dl_manager: hfd.DownloadManager): hfd.logging.get_logger().warning(USE_ML4OPF_WARNING) filepaths = dl_manager.download_and_extract(self.config.urls) splits: list[hfd.SplitGenerator] = [] if self.config.train: splits.append(hfd.SplitGenerator( name=hfd.Split.TRAIN, gen_kwargs=dict(case_file=filepaths.get("case", None), data_files=tuple(filepaths["train"]), n_samples=NUM_TRAIN), )) if self.config.test: splits.append(hfd.SplitGenerator( name=hfd.Split.TEST, gen_kwargs=dict(case_file=filepaths.get("case", None), data_files=tuple(filepaths["test"]), n_samples=NUM_TEST), )) if self.config.infeasible: splits.append(hfd.SplitGenerator( name=hfd.Split("infeasible"), gen_kwargs=dict(case_file=filepaths.get("case", None), data_files=tuple(filepaths["infeasible"]), n_samples=NUM_INFEASIBLE), )) return splits def _generate_tables(self, case_file: str | None, data_files: tuple[hfd.utils.track.tracked_str | list[hfd.utils.track.tracked_str]], n_samples: int): case_data: str | None = json.dumps(json.load(open_maybe_gzip_cat(case_file))) if case_file is not None else None data: dict[str, h5py.File] = {} for file in data_files: v = h5py.File(open_maybe_gzip_cat(file), "r") if isinstance(file, list): k = "/".join(Path(file[0].get_origin()).parts[-3:-1]).split(".")[0] else: k = "/".join(Path(file.get_origin()).parts[-2:]).split(".")[0] data[k] = v for k in list(data.keys()): if "/input" in k: data[k.split("/", 1)[1]] = data.pop(k) batch_size = self._writer_batch_size or self.DEFAULT_WRITER_BATCH_SIZE for i in range(0, n_samples, batch_size): effective_batch_size = min(batch_size, n_samples - i) sample_data = { f"{dk}/{k}": hfd.features.features.numpy_to_pyarrow_listarray(v[i:i + effective_batch_size, ...]) for dk, d in data.items() for k, v in d.items() if f"{dk}/{k}" in self.config.features } if case_data is not None: sample_data["case/json"] = pa.array([case_data] * effective_batch_size) yield i, pa.Table.from_pydict(sample_data) for f in data.values(): f.close() # ┌──────────────┐ # │ Features │ # └──────────────┘ FLOAT_TYPE = "float32" INT_TYPE = "int64" BOOL_TYPE = "bool" STRING_TYPE = "string" def case_features(): # FIXME: better way to share schema of case data -- need to treat jagged arrays return { "case/json": hfd.Value(STRING_TYPE), } META_FEATURES = { "meta/seed": hfd.Value(dtype=INT_TYPE), "meta/formulation": hfd.Value(dtype=STRING_TYPE), "meta/primal_objective_value": hfd.Value(dtype=FLOAT_TYPE), "meta/dual_objective_value": hfd.Value(dtype=FLOAT_TYPE), "meta/primal_status": hfd.Value(dtype=STRING_TYPE), "meta/dual_status": hfd.Value(dtype=STRING_TYPE), "meta/termination_status": hfd.Value(dtype=STRING_TYPE), "meta/build_time": hfd.Value(dtype=FLOAT_TYPE), "meta/extract_time": hfd.Value(dtype=FLOAT_TYPE), "meta/solve_time": hfd.Value(dtype=FLOAT_TYPE), } def input_features(sizes: CaseSizes): return { "input/pd": hfd.Sequence(length=sizes.n_load, feature=hfd.Value(dtype=FLOAT_TYPE)), "input/qd": hfd.Sequence(length=sizes.n_load, feature=hfd.Value(dtype=FLOAT_TYPE)), "input/gen_status": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=BOOL_TYPE)), "input/branch_status": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=BOOL_TYPE)), "input/seed": hfd.Value(dtype=INT_TYPE), } def acopf_primal_features(sizes: CaseSizes): return { "ACOPF/primal/vm": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/primal/va": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/primal/pg": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/primal/qg": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/primal/pf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/primal/pt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/primal/qf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/primal/qt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), } def acopf_dual_features(sizes: CaseSizes): return { "ACOPF/dual/kcl_p": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/kcl_q": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/vm": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/pg": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/qg": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/ohm_pf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/ohm_pt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/ohm_qf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/ohm_qt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/pf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/pt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/qf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/qt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/va_diff": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/sm_fr": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/sm_to": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "ACOPF/dual/slack_bus": hfd.Value(dtype=FLOAT_TYPE), } def dcopf_primal_features(sizes: CaseSizes): return { "DCOPF/primal/va": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "DCOPF/primal/pg": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=FLOAT_TYPE)), "DCOPF/primal/pf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), } def dcopf_dual_features(sizes: CaseSizes): return { "DCOPF/dual/kcl_p": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "DCOPF/dual/pg": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=FLOAT_TYPE)), "DCOPF/dual/ohm_pf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "DCOPF/dual/pf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "DCOPF/dual/va_diff": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "DCOPF/dual/slack_bus": hfd.Value(dtype=FLOAT_TYPE), } def socopf_primal_features(sizes: CaseSizes): return { "SOCOPF/primal/w": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/primal/pg": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/primal/qg": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/primal/pf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/primal/pt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/primal/qf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/primal/qt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/primal/wr": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/primal/wi": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), } def socopf_dual_features(sizes: CaseSizes): return { "SOCOPF/dual/kcl_p": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/kcl_q": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/w": hfd.Sequence(length=sizes.n_bus, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/pg": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/qg": hfd.Sequence(length=sizes.n_gen, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/ohm_pf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/ohm_pt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/ohm_qf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/ohm_qt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/jabr": hfd.Array2D(shape=(sizes.n_branch, 4), dtype=FLOAT_TYPE), "SOCOPF/dual/sm_fr": hfd.Array2D(shape=(sizes.n_branch, 3), dtype=FLOAT_TYPE), "SOCOPF/dual/sm_to": hfd.Array2D(shape=(sizes.n_branch, 3), dtype=FLOAT_TYPE), "SOCOPF/dual/va_diff": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/wr": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/wi": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/pf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/pt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/qf": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), "SOCOPF/dual/qt": hfd.Sequence(length=sizes.n_branch, feature=hfd.Value(dtype=FLOAT_TYPE)), } # ┌───────────────┐ # │ Utilities │ # └───────────────┘ def open_maybe_gzip_cat(path: str | list): if isinstance(path, list): dest = Path(path[0]).parent.with_suffix(".h5") if not dest.exists(): with open(dest, "wb") as dest_f: for piece in path: with open(piece, "rb") as piece_f: shutil.copyfileobj(piece_f, dest_f) shutil.rmtree(Path(piece).parent) path = dest.as_posix() return gzip.open(path, "rb") if path.endswith(".gz") else open(path, "rb")