| from __future__ import annotations |
| from dataclasses import dataclass |
| from pathlib import Path |
| import json |
| import gzip |
|
|
| import datasets as hfd |
| import h5py |
| import pyarrow as pa |
|
|
| |
| |
| |
|
|
| @dataclass |
| class CaseSizes: |
| n_bus: int |
| n_load: int |
| n_gen: int |
| n_branch: int |
|
|
| CASENAME = "89_pegase" |
| SIZES = CaseSizes(n_bus=89, n_load=35, n_gen=12, n_branch=210) |
| NUM_TRAIN = 704792 |
| NUM_TEST = 176198 |
| NUM_INFEASIBLE = 119010 |
|
|
| URL = "https://huggingface.co/datasets/PGLearn/PGLearn-Small-89_pegase" |
| DESCRIPTION = """\ |
| The 89_pegase PGLearn optimal power flow dataset, part of the PGLearn-Small collection. \ |
| """ |
| VERSION = hfd.Version("1.0.0") |
| DEFAULT_CONFIG_DESCRIPTION="""\ |
| This configuration contains feasible input, metadata, primal solution, and dual solution data \ |
| for the ACOPF, DCOPF, and SOCOPF formulations on the {case} system. |
| """ |
| USE_ML4OPF_WARNING = """ |
| ================================================================================================ |
| Loading PGLearn-Small-89_pegase 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-Small-89_pegase#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 |
|
|
| |
| |
| |
|
|
| 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, |
| } |
|
|
| |
| |
| |
|
|
| class PGLearnSmall89_pegaseConfig(hfd.BuilderConfig): |
| """BuilderConfig for PGLearn-Small-89_pegase. |
| 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(PGLearnSmall89_pegaseConfig, 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 |
|
|
| 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: urls[split].append(f"{split}/{formulation}/primal.h5" + self.gz_ext) |
| if self.dual: urls[split].append(f"{split}/{formulation}/dual.h5" + self.gz_ext) |
| if self.meta: urls[split].append(f"{split}/{formulation}/meta.h5" + self.gz_ext) |
| return urls |
|
|
| |
| |
| |
|
|
| class PGLearnSmall89_pegase(hfd.ArrowBasedBuilder): |
| """DatasetBuilder for PGLearn-Small-89_pegase. |
| 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-Small-89_pegase", 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 = PGLearnSmall89_pegaseConfig |
| DEFAULT_CONFIG_NAME=CASENAME |
| BUILDER_CONFIGS = [ |
| PGLearnSmall89_pegaseConfig( |
| name=CASENAME, description=DEFAULT_CONFIG_DESCRIPTION.format(case=CASENAME), |
| formulations=list(FORMULATIONS_TO_FEATURES.keys()), |
| primal=True, dual=True, meta=True, input=True, casejson=True, |
| 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["case"], 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["case"], 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["case"], 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], n_samples: int): |
| case_data: str | None = json.dumps(json.load(open_maybe_gzip(case_file))) if case_file is not None else None |
|
|
| opened_files = [open_maybe_gzip(file) for file in data_files] |
| data = {'/'.join(Path(df.get_origin()).parts[-2:]).split('.')[0]: h5py.File(of) for of, df in zip(opened_files, data_files)} |
| 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 opened_files: |
| f.close() |
|
|
| |
| |
| |
|
|
| FLOAT_TYPE = "float32" |
| INT_TYPE = "int64" |
| BOOL_TYPE = "bool" |
| STRING_TYPE = "string" |
|
|
| def case_features(): |
| |
| 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)), |
| } |
|
|
| |
| |
| |
|
|
| def open_maybe_gzip(path): |
| return gzip.open(path, "rb") if path.endswith(".gz") else open(path, "rb") |
|
|