stringforge 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stringforge/__init__.py +307 -0
- stringforge/cy_io.py +1787 -0
- stringforge/kklt_database.py +2889 -0
- stringforge/lcs_database.py +1223 -0
- stringforge/vacua_writer.py +3079 -0
- stringforge/vacuavault/__init__.py +60 -0
- stringforge/vacuavault/__main__.py +104 -0
- stringforge/vacuavault/catalog.py +222 -0
- stringforge/vacuavault/ci.py +188 -0
- stringforge/vacuavault/curate.py +119 -0
- stringforge/vacuavault/schema.py +459 -0
- stringforge/vulcan/__init__.py +634 -0
- stringforge/vulcan/__main__.py +139 -0
- stringforge/vulcan/certify.py +543 -0
- stringforge/vulcan/community.py +261 -0
- stringforge/vulcan/hf_io.py +296 -0
- stringforge/vulcan/ml_view.py +386 -0
- stringforge/vulcan/ratelimit.py +285 -0
- stringforge/vulcan/reader.py +624 -0
- stringforge/vulcan/runid.py +248 -0
- stringforge/vulcan/schema.py +525 -0
- stringforge/vulcan/snapshot.py +436 -0
- stringforge/vulcan/sync.py +263 -0
- stringforge/vulcan/verifier.py +322 -0
- stringforge/vulcan/writer.py +434 -0
- stringforge-0.1.0.dist-info/METADATA +286 -0
- stringforge-0.1.0.dist-info/RECORD +30 -0
- stringforge-0.1.0.dist-info/WHEEL +5 -0
- stringforge-0.1.0.dist-info/licenses/LICENSE +674 -0
- stringforge-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
# Copyright 2026 Andreas Schachner
|
|
2
|
+
#
|
|
3
|
+
# This file is part of StringForge.
|
|
4
|
+
#
|
|
5
|
+
# StringForge is free software: you can redistribute it and/or modify
|
|
6
|
+
# it under the terms of the GNU General Public License as published by
|
|
7
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
8
|
+
# (at your option) any later version.
|
|
9
|
+
|
|
10
|
+
r"""
|
|
11
|
+
Read path for Vulcan: catalogue scan, lazy shard fetch, and query.
|
|
12
|
+
|
|
13
|
+
The reader builds a lightweight catalogue from parquet kv-metadata
|
|
14
|
+
(see :data:`stringforge.vulcan.writer.PROVENANCE_METADATA_KEY`) and
|
|
15
|
+
caches loaded shards in a small LRU. Two backends are supported:
|
|
16
|
+
|
|
17
|
+
* **Local** -- the staging directory's ``synced/`` subtree on the
|
|
18
|
+
current host. No network calls, no authentication. Used by the
|
|
19
|
+
same workflow that produced the shards.
|
|
20
|
+
* **HuggingFace** -- the production repo published by
|
|
21
|
+
:meth:`stringforge.vulcan.Vulcan.sync`. Shard manifests are
|
|
22
|
+
fetched on-demand via :func:`huggingface_hub.HfApi.list_repo_files`
|
|
23
|
+
and individual parquet files via :func:`huggingface_hub.hf_hub_download`.
|
|
24
|
+
|
|
25
|
+
The reader complements :mod:`~stringforge.vulcan.writer` /
|
|
26
|
+
:mod:`~stringforge.vulcan.sync` -- it is the inverse traversal across
|
|
27
|
+
the same on-disk layout.
|
|
28
|
+
"""
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import json
|
|
32
|
+
import os
|
|
33
|
+
import threading
|
|
34
|
+
import warnings
|
|
35
|
+
from collections import OrderedDict
|
|
36
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
37
|
+
from dataclasses import dataclass
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
from typing import Any, Iterable, List, Mapping, Optional, Tuple, Union
|
|
40
|
+
|
|
41
|
+
import pandas as pd
|
|
42
|
+
import pyarrow as pa
|
|
43
|
+
import pyarrow.parquet as pq
|
|
44
|
+
|
|
45
|
+
from .schema import GEOMETRY_KEYS, GEOMETRY_KEY_SENTINEL, SCHEMA_VERSION, geometry_id as _compute_geometry_id
|
|
46
|
+
from .writer import (
|
|
47
|
+
PROVENANCE_METADATA_KEY,
|
|
48
|
+
SCHEMA_VERSION_METADATA_KEY,
|
|
49
|
+
SYNCED_DIRNAME,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
#: Columns produced by :meth:`VulcanReader.catalog` (one row per
|
|
53
|
+
#: shard). This is the read-side catalogue contract; downstream code
|
|
54
|
+
#: can rely on these columns being present whenever the catalogue
|
|
55
|
+
#: scan succeeds.
|
|
56
|
+
CATALOG_COLUMNS: Tuple[str, ...] = (
|
|
57
|
+
"path_in_repo",
|
|
58
|
+
"run_id",
|
|
59
|
+
"geometry_id",
|
|
60
|
+
"h11", "h12", "ks_id", "triang_id", "conifold_id", "cicy_id",
|
|
61
|
+
"n_rows",
|
|
62
|
+
"schema_version",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
#: Default LRU cache size, in shards.
|
|
66
|
+
DEFAULT_CACHE_SIZE: int = 32
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ── catalogue scan helpers ────────────────────────────────────────────────
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _read_parquet_metadata(path: Path) -> dict[str, Any]:
|
|
73
|
+
r"""
|
|
74
|
+
Extract Vulcan kv-metadata from a parquet file without loading
|
|
75
|
+
any row groups.
|
|
76
|
+
|
|
77
|
+
Returns a dict combining the provenance blob (parsed JSON) and
|
|
78
|
+
the schema-version integer; an empty dict when the parquet has no
|
|
79
|
+
Vulcan kv-metadata.
|
|
80
|
+
"""
|
|
81
|
+
pf = pq.ParquetFile(path)
|
|
82
|
+
raw = pf.schema_arrow.metadata or {}
|
|
83
|
+
out: dict[str, Any] = {}
|
|
84
|
+
blob = raw.get(PROVENANCE_METADATA_KEY)
|
|
85
|
+
if blob is not None:
|
|
86
|
+
try:
|
|
87
|
+
out.update(json.loads(blob.decode("utf-8")))
|
|
88
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
89
|
+
pass
|
|
90
|
+
ver = raw.get(SCHEMA_VERSION_METADATA_KEY)
|
|
91
|
+
if ver is not None:
|
|
92
|
+
try:
|
|
93
|
+
out["schema_version"] = int(ver.decode("ascii"))
|
|
94
|
+
except (UnicodeDecodeError, ValueError):
|
|
95
|
+
pass
|
|
96
|
+
out["n_rows"] = pf.metadata.num_rows
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _row_from_metadata(path_in_repo: str, meta: Mapping[str, Any]) -> dict[str, Any]:
|
|
101
|
+
r"""Project a parquet-metadata blob into a catalogue row."""
|
|
102
|
+
geometry = dict(meta.get("geometry", {}))
|
|
103
|
+
row: dict[str, Any] = {
|
|
104
|
+
"path_in_repo": path_in_repo,
|
|
105
|
+
"run_id": meta.get("run_id"),
|
|
106
|
+
"geometry_id": _compute_geometry_id(geometry) if geometry else None,
|
|
107
|
+
"n_rows": int(meta.get("n_rows", 0)),
|
|
108
|
+
"schema_version": int(meta.get("schema_version", 0)),
|
|
109
|
+
}
|
|
110
|
+
for key in GEOMETRY_KEYS:
|
|
111
|
+
row[key] = int(geometry.get(key, GEOMETRY_KEY_SENTINEL))
|
|
112
|
+
return row
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ── LRU shard cache ──────────────────────────────────────────────────────
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class _LRUShardCache:
|
|
119
|
+
r"""
|
|
120
|
+
**Description:**
|
|
121
|
+
Thread-safe in-memory LRU cache for loaded parquet shards.
|
|
122
|
+
|
|
123
|
+
Modelled on :class:`stringforge.cy_io._LRUShardCache`. Used by the
|
|
124
|
+
Vulcan reader to keep repeated queries against the same shards
|
|
125
|
+
fast without growing memory unbounded.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
capacity: Maximum number of shards retained.
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
def __init__(self, capacity: int = DEFAULT_CACHE_SIZE) -> None:
|
|
132
|
+
if capacity < 1:
|
|
133
|
+
raise ValueError("LRU capacity must be >= 1")
|
|
134
|
+
self.capacity = int(capacity)
|
|
135
|
+
self._store: OrderedDict[str, pd.DataFrame] = OrderedDict()
|
|
136
|
+
self._lock = threading.Lock()
|
|
137
|
+
|
|
138
|
+
def get(self, key: str) -> Optional[pd.DataFrame]:
|
|
139
|
+
r"""
|
|
140
|
+
**Description:**
|
|
141
|
+
Look up a shard in the cache.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
key: Cache key (typically the repo-relative path).
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
Optional[pd.DataFrame]: The cached DataFrame, or ``None``
|
|
148
|
+
on miss. A hit moves the entry to the front of the LRU.
|
|
149
|
+
"""
|
|
150
|
+
with self._lock:
|
|
151
|
+
if key not in self._store:
|
|
152
|
+
return None
|
|
153
|
+
self._store.move_to_end(key)
|
|
154
|
+
return self._store[key]
|
|
155
|
+
|
|
156
|
+
def put(self, key: str, df: pd.DataFrame) -> None:
|
|
157
|
+
r"""
|
|
158
|
+
**Description:**
|
|
159
|
+
Insert a shard into the cache, evicting the oldest entry if
|
|
160
|
+
the capacity would be exceeded.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
key: Cache key.
|
|
164
|
+
df: DataFrame to cache.
|
|
165
|
+
"""
|
|
166
|
+
with self._lock:
|
|
167
|
+
if key in self._store:
|
|
168
|
+
self._store.move_to_end(key)
|
|
169
|
+
self._store[key] = df
|
|
170
|
+
return
|
|
171
|
+
self._store[key] = df
|
|
172
|
+
if len(self._store) > self.capacity:
|
|
173
|
+
self._store.popitem(last=False)
|
|
174
|
+
|
|
175
|
+
def __len__(self) -> int:
|
|
176
|
+
with self._lock:
|
|
177
|
+
return len(self._store)
|
|
178
|
+
|
|
179
|
+
def clear(self) -> None:
|
|
180
|
+
r"""**Description:** Remove every cached entry."""
|
|
181
|
+
with self._lock:
|
|
182
|
+
self._store.clear()
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# ── reader ───────────────────────────────────────────────────────────────
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@dataclass
|
|
189
|
+
class _Source:
|
|
190
|
+
r"""Internal: tagged-union view of the reader's data source."""
|
|
191
|
+
local_root: Optional[Path] = None
|
|
192
|
+
hf_repo: Optional[str] = None
|
|
193
|
+
#: HuggingFace revision (branch, tag, or commit SHA) to pin reads
|
|
194
|
+
#: to. ``None`` reads the repo's default branch (the rolling
|
|
195
|
+
#: ``main``). A frozen snapshot tag (see
|
|
196
|
+
#: :func:`stringforge.vulcan.snapshot.freeze_snapshot`) is passed
|
|
197
|
+
#: here so a paper can read an immutable, citeable revision.
|
|
198
|
+
revision: Optional[str] = None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class VulcanReader:
|
|
202
|
+
r"""
|
|
203
|
+
**Description:**
|
|
204
|
+
Read-side counterpart to :class:`stringforge.vulcan.Vulcan`.
|
|
205
|
+
|
|
206
|
+
Builds a Vulcan-shard catalogue by scanning either a local
|
|
207
|
+
``synced/`` tree or a HuggingFace dataset repo. Loaded shards
|
|
208
|
+
are cached in a small in-memory LRU.
|
|
209
|
+
|
|
210
|
+
A typical local usage pattern:
|
|
211
|
+
|
|
212
|
+
.. code-block:: python
|
|
213
|
+
|
|
214
|
+
reader = VulcanReader.from_local(forge.staging_dir)
|
|
215
|
+
cat = reader.catalog()
|
|
216
|
+
susy = reader.query(h12=2, solver_name="newton")
|
|
217
|
+
|
|
218
|
+
A HuggingFace usage pattern:
|
|
219
|
+
|
|
220
|
+
.. code-block:: python
|
|
221
|
+
|
|
222
|
+
reader = VulcanReader.from_hf("user/vacua_forge")
|
|
223
|
+
run = reader.fetch_run("2026-06-01-120000_fluxscan_...")
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
source: Internal source tag (use the factories instead).
|
|
227
|
+
cache_size: LRU capacity in shards.
|
|
228
|
+
token: HuggingFace read token; falls back to ``HF_TOKEN``.
|
|
229
|
+
Ignored for local sources.
|
|
230
|
+
"""
|
|
231
|
+
|
|
232
|
+
def __init__(
|
|
233
|
+
self,
|
|
234
|
+
*,
|
|
235
|
+
source: _Source,
|
|
236
|
+
cache_size: int = DEFAULT_CACHE_SIZE,
|
|
237
|
+
token: Optional[str] = None,
|
|
238
|
+
) -> None:
|
|
239
|
+
self._source = source
|
|
240
|
+
self._cache = _LRUShardCache(capacity=cache_size)
|
|
241
|
+
self._catalog: Optional[pd.DataFrame] = None
|
|
242
|
+
self._catalog_lock = threading.Lock()
|
|
243
|
+
self._token = token
|
|
244
|
+
|
|
245
|
+
# ── factories ─────────────────────────────────────────────────
|
|
246
|
+
|
|
247
|
+
@classmethod
|
|
248
|
+
def from_local(
|
|
249
|
+
cls,
|
|
250
|
+
staging_dir: Union[str, Path],
|
|
251
|
+
*,
|
|
252
|
+
cache_size: int = DEFAULT_CACHE_SIZE,
|
|
253
|
+
) -> "VulcanReader":
|
|
254
|
+
r"""
|
|
255
|
+
**Description:**
|
|
256
|
+
Construct a reader that scans ``staging_dir/synced/`` for
|
|
257
|
+
already-committed shards.
|
|
258
|
+
|
|
259
|
+
Args:
|
|
260
|
+
staging_dir: Vulcan staging root.
|
|
261
|
+
cache_size: LRU capacity.
|
|
262
|
+
|
|
263
|
+
Returns:
|
|
264
|
+
VulcanReader: A reader bound to the local synced tree.
|
|
265
|
+
"""
|
|
266
|
+
root = Path(staging_dir).resolve() / SYNCED_DIRNAME
|
|
267
|
+
return cls(source=_Source(local_root=root), cache_size=cache_size)
|
|
268
|
+
|
|
269
|
+
@classmethod
|
|
270
|
+
def from_hf(
|
|
271
|
+
cls,
|
|
272
|
+
repo: str,
|
|
273
|
+
*,
|
|
274
|
+
revision: Optional[str] = None,
|
|
275
|
+
cache_size: int = DEFAULT_CACHE_SIZE,
|
|
276
|
+
token: Optional[str] = None,
|
|
277
|
+
) -> "VulcanReader":
|
|
278
|
+
r"""
|
|
279
|
+
**Description:**
|
|
280
|
+
Construct a reader that streams shards from a HuggingFace
|
|
281
|
+
dataset repo on demand.
|
|
282
|
+
|
|
283
|
+
Args:
|
|
284
|
+
repo: ``"user/repo"`` on the Hub.
|
|
285
|
+
revision: Optional branch, tag, or commit SHA to pin reads
|
|
286
|
+
to. Pass a frozen-snapshot tag (e.g. ``"v2026.06"``,
|
|
287
|
+
produced by
|
|
288
|
+
:func:`stringforge.vulcan.snapshot.freeze_snapshot`) to
|
|
289
|
+
read an immutable, citeable revision; ``None`` reads the
|
|
290
|
+
rolling default branch.
|
|
291
|
+
cache_size: LRU capacity.
|
|
292
|
+
token: HuggingFace read token; falls back to ``HF_TOKEN``.
|
|
293
|
+
|
|
294
|
+
Returns:
|
|
295
|
+
VulcanReader: A reader bound to the remote repo (and revision).
|
|
296
|
+
"""
|
|
297
|
+
return cls(
|
|
298
|
+
source=_Source(hf_repo=repo, revision=revision),
|
|
299
|
+
cache_size=cache_size,
|
|
300
|
+
token=token,
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
@property
|
|
304
|
+
def revision(self) -> Optional[str]:
|
|
305
|
+
r"""The pinned HuggingFace revision, or ``None`` for local / default-branch reads."""
|
|
306
|
+
return self._source.revision
|
|
307
|
+
|
|
308
|
+
# ── catalogue ─────────────────────────────────────────────────
|
|
309
|
+
|
|
310
|
+
def catalog(self, *, refresh: bool = False, strict: bool = False) -> pd.DataFrame:
|
|
311
|
+
r"""
|
|
312
|
+
**Description:**
|
|
313
|
+
Return a one-row-per-shard catalogue of the configured source.
|
|
314
|
+
|
|
315
|
+
The first call scans every shard's kv-metadata and caches the
|
|
316
|
+
result; subsequent calls return the cached view. Pass
|
|
317
|
+
``refresh=True`` to force a rescan -- useful after a
|
|
318
|
+
:meth:`~stringforge.vulcan.Vulcan.sync` adds new shards
|
|
319
|
+
upstream.
|
|
320
|
+
|
|
321
|
+
Shard metadata is read in parallel via a thread pool because the
|
|
322
|
+
per-shard cost is dominated by I/O (opening the parquet file and
|
|
323
|
+
reading its footer); ordering is irrelevant because the final
|
|
324
|
+
DataFrame is sorted by ``path_in_repo``.
|
|
325
|
+
|
|
326
|
+
Unreadable shards (corrupt file, missing footer, etc.) are
|
|
327
|
+
skipped with a :class:`RuntimeWarning`; the number of skipped
|
|
328
|
+
shards is exposed on ``result.attrs["n_skipped"]``.
|
|
329
|
+
|
|
330
|
+
Shards whose embedded ``schema_version`` differs from the
|
|
331
|
+
current :data:`stringforge.vulcan.schema.SCHEMA_VERSION` emit a
|
|
332
|
+
:class:`RuntimeWarning` per shard. When ``strict=True`` such a
|
|
333
|
+
mismatch is promoted to :class:`ValueError`.
|
|
334
|
+
|
|
335
|
+
Args:
|
|
336
|
+
refresh: Force a fresh scan even if a cached catalogue
|
|
337
|
+
exists.
|
|
338
|
+
strict: When ``True``, raise :class:`ValueError` on any
|
|
339
|
+
shard whose ``schema_version`` differs from
|
|
340
|
+
:data:`stringforge.vulcan.schema.SCHEMA_VERSION`.
|
|
341
|
+
|
|
342
|
+
Returns:
|
|
343
|
+
pd.DataFrame: One row per shard with columns from
|
|
344
|
+
:data:`CATALOG_COLUMNS`.
|
|
345
|
+
|
|
346
|
+
Raises:
|
|
347
|
+
ValueError: When ``strict=True`` and a shard's
|
|
348
|
+
``schema_version`` does not match
|
|
349
|
+
:data:`stringforge.vulcan.schema.SCHEMA_VERSION`.
|
|
350
|
+
"""
|
|
351
|
+
with self._catalog_lock:
|
|
352
|
+
if self._catalog is not None and not refresh:
|
|
353
|
+
return self._catalog
|
|
354
|
+
rows: list[dict[str, Any]] = []
|
|
355
|
+
n_skipped = 0
|
|
356
|
+
shards = list(self._iter_shards())
|
|
357
|
+
max_workers = min(32, (os.cpu_count() or 1) * 4)
|
|
358
|
+
with ThreadPoolExecutor(max_workers=max_workers) as pool:
|
|
359
|
+
future_to_path = {
|
|
360
|
+
pool.submit(_read_parquet_metadata, local_path): path_in_repo
|
|
361
|
+
for path_in_repo, local_path in shards
|
|
362
|
+
}
|
|
363
|
+
for future in as_completed(future_to_path):
|
|
364
|
+
path_in_repo = future_to_path[future]
|
|
365
|
+
try:
|
|
366
|
+
meta = future.result()
|
|
367
|
+
except (OSError, pa.ArrowInvalid) as exc:
|
|
368
|
+
warnings.warn(
|
|
369
|
+
f"VulcanReader.catalog: skipping unreadable shard "
|
|
370
|
+
f"{path_in_repo!r}: {type(exc).__name__}: {exc}",
|
|
371
|
+
RuntimeWarning,
|
|
372
|
+
stacklevel=2,
|
|
373
|
+
)
|
|
374
|
+
n_skipped += 1
|
|
375
|
+
continue
|
|
376
|
+
row = _row_from_metadata(path_in_repo, meta)
|
|
377
|
+
rows.append(row)
|
|
378
|
+
df = pd.DataFrame(rows, columns=list(CATALOG_COLUMNS))
|
|
379
|
+
if len(df) > 0:
|
|
380
|
+
df = df.sort_values("path_in_repo").reset_index(drop=True)
|
|
381
|
+
df.attrs["n_skipped"] = n_skipped
|
|
382
|
+
# Surface forward-incompatible shards.
|
|
383
|
+
mismatched = [
|
|
384
|
+
(row["path_in_repo"], row["schema_version"])
|
|
385
|
+
for row in rows
|
|
386
|
+
if row.get("schema_version") != SCHEMA_VERSION
|
|
387
|
+
]
|
|
388
|
+
if mismatched and strict:
|
|
389
|
+
raise ValueError(
|
|
390
|
+
"VulcanReader.catalog: schema_version mismatch in shards "
|
|
391
|
+
f"(expected {SCHEMA_VERSION}): {mismatched}"
|
|
392
|
+
)
|
|
393
|
+
for path_in_repo, ver in mismatched:
|
|
394
|
+
warnings.warn(
|
|
395
|
+
f"VulcanReader.catalog: shard {path_in_repo!r} has "
|
|
396
|
+
f"schema_version={ver}, expected {SCHEMA_VERSION}",
|
|
397
|
+
RuntimeWarning,
|
|
398
|
+
stacklevel=2,
|
|
399
|
+
)
|
|
400
|
+
self._catalog = df
|
|
401
|
+
return self._catalog
|
|
402
|
+
|
|
403
|
+
# ── query / fetch ─────────────────────────────────────────────
|
|
404
|
+
|
|
405
|
+
def query(
|
|
406
|
+
self,
|
|
407
|
+
*,
|
|
408
|
+
run_id: Optional[str] = None,
|
|
409
|
+
geometry_id: Optional[str] = None,
|
|
410
|
+
h11: Optional[int] = None,
|
|
411
|
+
h12: Optional[int] = None,
|
|
412
|
+
ks_id: Optional[int] = None,
|
|
413
|
+
triang_id: Optional[int] = None,
|
|
414
|
+
solver_name: Optional[str] = None,
|
|
415
|
+
is_susy: Optional[bool] = None,
|
|
416
|
+
is_isd: Optional[bool] = None,
|
|
417
|
+
columns: Optional[Iterable[str]] = None,
|
|
418
|
+
) -> pd.DataFrame:
|
|
419
|
+
r"""
|
|
420
|
+
**Description:**
|
|
421
|
+
Filter Vulcan rows by catalogue + row-level predicates.
|
|
422
|
+
|
|
423
|
+
Catalogue predicates (``h11``, ``h12``, ``ks_id``,
|
|
424
|
+
``triang_id``, ``run_id``, ``geometry_id``) narrow the set of
|
|
425
|
+
shards that need to be read. Row-level predicates
|
|
426
|
+
(``solver_name``, ``is_susy``, ``is_isd``) apply post-load.
|
|
427
|
+
``columns`` projects the result down to a subset of columns
|
|
428
|
+
before returning.
|
|
429
|
+
|
|
430
|
+
``h11``, ``h12`` are interpreted in mirror (jaxvacua /
|
|
431
|
+
``lcs_tree``) convention, matching
|
|
432
|
+
:class:`stringforge.lcs.LCSDatabase`.
|
|
433
|
+
|
|
434
|
+
Args:
|
|
435
|
+
run_id: Exact match.
|
|
436
|
+
geometry_id: Exact match.
|
|
437
|
+
h11, h12, ks_id, triang_id: Exact match per geometry key.
|
|
438
|
+
solver_name: Row-level filter on the ``solver_name``
|
|
439
|
+
column.
|
|
440
|
+
is_susy: Row-level filter on the ``is_susy`` column.
|
|
441
|
+
is_isd: Row-level filter on the ``is_isd`` column.
|
|
442
|
+
columns: Optional column projection.
|
|
443
|
+
|
|
444
|
+
Returns:
|
|
445
|
+
pd.DataFrame: Concatenated rows from matching shards.
|
|
446
|
+
Empty when no shard satisfies the catalogue predicates.
|
|
447
|
+
"""
|
|
448
|
+
cat = self.catalog()
|
|
449
|
+
for col, val in (("run_id", run_id), ("geometry_id", geometry_id),
|
|
450
|
+
("h11", h11), ("h12", h12),
|
|
451
|
+
("ks_id", ks_id), ("triang_id", triang_id)):
|
|
452
|
+
if val is None:
|
|
453
|
+
continue
|
|
454
|
+
cat = cat[cat[col] == val]
|
|
455
|
+
|
|
456
|
+
if len(cat) == 0:
|
|
457
|
+
return pd.DataFrame(columns=list(columns) if columns else [])
|
|
458
|
+
|
|
459
|
+
frames: list[pd.DataFrame] = []
|
|
460
|
+
for path in cat["path_in_repo"]:
|
|
461
|
+
df = self.fetch_shard(path)
|
|
462
|
+
if solver_name is not None and "solver_name" in df.columns:
|
|
463
|
+
df = df[df["solver_name"] == solver_name]
|
|
464
|
+
if is_susy is not None and "is_susy" in df.columns:
|
|
465
|
+
df = df[df["is_susy"] == is_susy]
|
|
466
|
+
if is_isd is not None and "is_isd" in df.columns:
|
|
467
|
+
df = df[df["is_isd"] == is_isd]
|
|
468
|
+
if columns:
|
|
469
|
+
missing = [c for c in columns if c not in df.columns]
|
|
470
|
+
if missing:
|
|
471
|
+
raise KeyError(
|
|
472
|
+
f"requested columns not in shard {path!r}: {missing}"
|
|
473
|
+
)
|
|
474
|
+
df = df[list(columns)]
|
|
475
|
+
frames.append(df)
|
|
476
|
+
|
|
477
|
+
if not frames:
|
|
478
|
+
return pd.DataFrame(columns=list(columns) if columns else [])
|
|
479
|
+
return pd.concat(frames, ignore_index=True)
|
|
480
|
+
|
|
481
|
+
def fetch_run(self, run_id: str) -> pd.DataFrame:
|
|
482
|
+
r"""
|
|
483
|
+
**Description:**
|
|
484
|
+
Load every row produced by a specific ``run_id``.
|
|
485
|
+
|
|
486
|
+
Args:
|
|
487
|
+
run_id: The identifier carried on each row of the target
|
|
488
|
+
shards.
|
|
489
|
+
|
|
490
|
+
Returns:
|
|
491
|
+
pd.DataFrame: Concatenated rows. Empty when no shard
|
|
492
|
+
matches.
|
|
493
|
+
"""
|
|
494
|
+
return self.query(run_id=run_id)
|
|
495
|
+
|
|
496
|
+
def fetch_shard(self, path_in_repo: str) -> pd.DataFrame:
|
|
497
|
+
r"""
|
|
498
|
+
**Description:**
|
|
499
|
+
Load (and cache) a single shard by its HF-repo-relative path.
|
|
500
|
+
|
|
501
|
+
Args:
|
|
502
|
+
path_in_repo: The path produced by
|
|
503
|
+
:func:`stringforge.vulcan.schema.shard_relpath`.
|
|
504
|
+
|
|
505
|
+
Returns:
|
|
506
|
+
pd.DataFrame: The shard's rows.
|
|
507
|
+
|
|
508
|
+
Raises:
|
|
509
|
+
FileNotFoundError: When the shard is absent both locally
|
|
510
|
+
and (where applicable) on the Hub.
|
|
511
|
+
"""
|
|
512
|
+
hit = self._cache.get(path_in_repo)
|
|
513
|
+
if hit is not None:
|
|
514
|
+
return hit
|
|
515
|
+
local = self._resolve_local_path(path_in_repo)
|
|
516
|
+
df = pd.read_parquet(local)
|
|
517
|
+
self._cache.put(path_in_repo, df)
|
|
518
|
+
return df
|
|
519
|
+
|
|
520
|
+
def read_columns(self, path_in_repo: str, columns: Iterable[str]) -> pd.DataFrame:
|
|
521
|
+
r"""
|
|
522
|
+
**Description:**
|
|
523
|
+
Read only the named columns from one shard, skipping any that
|
|
524
|
+
the shard does not carry.
|
|
525
|
+
|
|
526
|
+
A columnar read used by snapshot manifest generation: tallying
|
|
527
|
+
``verifier_id`` / ``cert_status`` over a large dataset must not
|
|
528
|
+
pay the cost of materialising every column. Does **not**
|
|
529
|
+
populate the LRU (it returns a column projection, not the full
|
|
530
|
+
shard).
|
|
531
|
+
|
|
532
|
+
Args:
|
|
533
|
+
path_in_repo: The shard's repo-relative path.
|
|
534
|
+
columns: Column names to read; missing ones are skipped.
|
|
535
|
+
|
|
536
|
+
Returns:
|
|
537
|
+
pd.DataFrame: The projection (empty-column frame if none of
|
|
538
|
+
the requested columns are present).
|
|
539
|
+
"""
|
|
540
|
+
local = self._resolve_local_path(path_in_repo)
|
|
541
|
+
present = set(pq.ParquetFile(local).schema_arrow.names)
|
|
542
|
+
wanted = [c for c in columns if c in present]
|
|
543
|
+
if not wanted:
|
|
544
|
+
n = pq.ParquetFile(local).metadata.num_rows
|
|
545
|
+
return pd.DataFrame(index=range(n))
|
|
546
|
+
return pq.read_table(local, columns=wanted).to_pandas()
|
|
547
|
+
|
|
548
|
+
def clear_cache(self) -> None:
|
|
549
|
+
r"""**Description:** Drop every cached shard from the in-memory LRU."""
|
|
550
|
+
self._cache.clear()
|
|
551
|
+
|
|
552
|
+
# ── private: backend dispatch ─────────────────────────────────
|
|
553
|
+
|
|
554
|
+
def _iter_shards(self) -> Iterable[Tuple[str, Path]]:
|
|
555
|
+
r"""
|
|
556
|
+
Yield ``(path_in_repo, local_path)`` for every shard in the
|
|
557
|
+
configured source. ``local_path`` is downloaded if needed.
|
|
558
|
+
"""
|
|
559
|
+
if self._source.local_root is not None:
|
|
560
|
+
root = self._source.local_root
|
|
561
|
+
if not root.is_dir():
|
|
562
|
+
return
|
|
563
|
+
for parquet in sorted(root.rglob("*.parquet")):
|
|
564
|
+
# ``path_in_repo`` is reconstructed from the local
|
|
565
|
+
# filename (writer.py replaces "/" with "__").
|
|
566
|
+
path_in_repo = parquet.name.replace("__", "/")
|
|
567
|
+
yield path_in_repo, parquet
|
|
568
|
+
return
|
|
569
|
+
|
|
570
|
+
# HF source -- list, download lazily.
|
|
571
|
+
if self._source.hf_repo is None:
|
|
572
|
+
return
|
|
573
|
+
from huggingface_hub import HfApi, hf_hub_download # type: ignore
|
|
574
|
+
|
|
575
|
+
api = HfApi(token=self._token or os.environ.get("HF_TOKEN"))
|
|
576
|
+
files = api.list_repo_files(
|
|
577
|
+
repo_id=self._source.hf_repo, repo_type="dataset",
|
|
578
|
+
revision=self._source.revision,
|
|
579
|
+
)
|
|
580
|
+
for path_in_repo in files:
|
|
581
|
+
if not path_in_repo.endswith(".parquet"):
|
|
582
|
+
continue
|
|
583
|
+
local = Path(hf_hub_download(
|
|
584
|
+
repo_id=self._source.hf_repo,
|
|
585
|
+
filename=path_in_repo,
|
|
586
|
+
repo_type="dataset",
|
|
587
|
+
revision=self._source.revision,
|
|
588
|
+
token=self._token or os.environ.get("HF_TOKEN"),
|
|
589
|
+
))
|
|
590
|
+
yield path_in_repo, local
|
|
591
|
+
|
|
592
|
+
def _resolve_local_path(self, path_in_repo: str) -> Path:
|
|
593
|
+
r"""
|
|
594
|
+
Map a repo-relative path back to a concrete on-disk file,
|
|
595
|
+
downloading from HF if necessary.
|
|
596
|
+
"""
|
|
597
|
+
if self._source.local_root is not None:
|
|
598
|
+
local = self._source.local_root / path_in_repo.replace("/", "__")
|
|
599
|
+
if not local.is_file():
|
|
600
|
+
raise FileNotFoundError(
|
|
601
|
+
f"Vulcan shard not found locally: {local}"
|
|
602
|
+
)
|
|
603
|
+
return local
|
|
604
|
+
|
|
605
|
+
if self._source.hf_repo is None:
|
|
606
|
+
raise FileNotFoundError(
|
|
607
|
+
"Vulcan reader has no configured source for shard "
|
|
608
|
+
f"{path_in_repo!r}"
|
|
609
|
+
)
|
|
610
|
+
from huggingface_hub import hf_hub_download # type: ignore
|
|
611
|
+
return Path(hf_hub_download(
|
|
612
|
+
repo_id=self._source.hf_repo,
|
|
613
|
+
filename=path_in_repo,
|
|
614
|
+
repo_type="dataset",
|
|
615
|
+
revision=self._source.revision,
|
|
616
|
+
token=self._token or os.environ.get("HF_TOKEN"),
|
|
617
|
+
))
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
__all__ = (
|
|
621
|
+
"VulcanReader",
|
|
622
|
+
"CATALOG_COLUMNS",
|
|
623
|
+
"DEFAULT_CACHE_SIZE",
|
|
624
|
+
)
|