File size: 20,696 Bytes
3875184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
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 = "1888_rte"
SIZES = CaseSizes(n_bus=1888, n_load=1000, n_gen=290, n_branch=2531)
NUM_TRAIN = 371587
NUM_TEST = 92897
NUM_INFEASIBLE = 35516
SPLITFILES = {
    "train/SOCOPF/dual.h5.gz": ["train/SOCOPF/dual/xaa", "train/SOCOPF/dual/xab", "train/SOCOPF/dual/xac"],
}

URL = "https://huggingface.co/datasets/PGLearn/PGLearn-Medium-1888_rte"
DESCRIPTION = """\
The 1888_rte PGLearn optimal power flow dataset, part of the PGLearn-Medium 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-Medium-1888_rte/blob/script/case.json.gz
"""
USE_ML4OPF_WARNING = """
================================================================================================
  Loading PGLearn-Medium-1888_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-Medium-1888_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 PGLearnMedium1888_rteConfig(hfd.BuilderConfig):
    """BuilderConfig for PGLearn-Medium-1888_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(PGLearnMedium1888_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 PGLearnMedium1888_rte(hfd.ArrowBasedBuilder):
    """DatasetBuilder for PGLearn-Medium-1888_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-Medium-1888_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 = PGLearnMedium1888_rteConfig
    DEFAULT_CONFIG_NAME=CASENAME
    BUILDER_CONFIGS = [
        PGLearnMedium1888_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")