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.
@@ -0,0 +1,2889 @@
1
+ # ==============================================================================
2
+ # stringforge / kklt_database
3
+ #
4
+ # KKLTDatabase — a curated subset of the TDF dataset, indexed by conifold
5
+ # class. Does not duplicate Calabi-Yau geometry data: every row links back
6
+ # to the full TDF database via the logical key
7
+ # ``(ks_id, triang_id, tdf_conifold_id)`` and the wrapped
8
+ # :class:`~stringforge.lcs_database.LCSDatabase` (``dataset="tdf"``)
9
+ # resolves physical shard coordinates on the fly.
10
+ #
11
+ # Three local catalogs (under ``<cache_dir>/kklt/``):
12
+ #
13
+ # - ``catalog.parquet`` (polytope-grain;
14
+ # one row per ks_id;
15
+ # columns include n_rigids_dual, Q,
16
+ # n_coni_classes)
17
+ # - ``conifold_class_catalog.parquet`` (one row per (ks_id, coni_class_id);
18
+ # carries one_face_divisor)
19
+ # - ``conifold_catalog.parquet`` (one row per
20
+ # (ks_id, coni_class_id, coni_id);
21
+ # carries (triang_id, tdf_conifold_id))
22
+ #
23
+ # Optional local run logs and solution-stage fragments are run artefacts. Public
24
+ # designated vacua belong in the shared ``vacua_vault/kklt_vacua`` namespace,
25
+ # not in the static ``cy-database/kklt`` index.
26
+ #
27
+ # Subset criterion (applied at build time): ``n_rigids_dual > h12``.
28
+ # ``Q := h11 + h12 + 2`` is a column on ``catalog.parquet`` but not a
29
+ # build-time filter; the historically well-studied ``Q >= 100`` subset is
30
+ # recovered by ``db.query_polytopes(Q_min=100)``.
31
+ # ==============================================================================
32
+
33
+ from __future__ import annotations
34
+
35
+ import datetime as _dt
36
+ import json
37
+ import socket
38
+ import uuid
39
+ import warnings
40
+ from contextlib import contextmanager
41
+ from pathlib import Path
42
+ from typing import Any, Dict, Iterator, List, Optional, Union
43
+
44
+ import numpy as np
45
+
46
+ from .cy_io import (
47
+ HF_REPO_ID,
48
+ _DATASET_CONFIGS,
49
+ _require_pandas,
50
+ )
51
+ from .lcs_database import LCSDatabase, _swap_h_columns
52
+
53
+
54
+ _RUN_STATUS_VALUES = {"running", "done", "failed", "cancelled"}
55
+ _RUN_SCOPES = {"class", "conifold"}
56
+
57
+
58
+ # KKLT solution-stage registry: stage name → tuple of valid "kind"
59
+ # sub-directories under that stage, or ``None`` if the stage has no
60
+ # sub-kind. Used by :meth:`KKLTDatabase._kklt_stage_dir` and friends.
61
+ _KKLT_STAGES: Dict[str, Optional[tuple]] = {
62
+ "pfv": ("harvested", "promoted"),
63
+ "precursor": ("derived", "proxy"),
64
+ "vacua": None,
65
+ }
66
+
67
+
68
+ def _kklt_polytope_dirname(h11: int, h12: int, ks_id: int) -> str:
69
+ r"""Return ``h11_<n>_h12_<m>_ksid_<id>`` — the polytope-level
70
+ directory name under a KKLT stage. ``(h11, h12)`` is required to
71
+ fully disambiguate ``ks_id``."""
72
+ return f"h11_{int(h11)}_h12_{int(h12)}_ksid_{int(ks_id)}"
73
+
74
+
75
+ def _kklt_conifold_dirname(coni_class_id: int, coni_id: int) -> str:
76
+ r"""Return ``coniclass_<c>_coni_<k>`` — the conifold-level
77
+ directory name under a KKLT polytope directory."""
78
+ return f"coniclass_{int(coni_class_id)}_coni_{int(coni_id)}"
79
+
80
+
81
+ def _utcnow() -> _dt.datetime:
82
+ r"""Return the current UTC time as a ``datetime``."""
83
+ return _dt.datetime.now(_dt.timezone.utc)
84
+
85
+
86
+ def _normalise_tags_arg(tags: Optional[Union[str, List[str]]]) -> set:
87
+ r"""Normalise a tag filter argument to a set of strings."""
88
+ if tags is None:
89
+ return set()
90
+ if isinstance(tags, str):
91
+ return {tags}
92
+ return {str(tag) for tag in tags}
93
+
94
+
95
+ def _tags_from_cell(value: Any) -> set:
96
+ r"""Return a set of tag labels from a scalar or list-like parquet cell."""
97
+ if value is None:
98
+ return set()
99
+ if hasattr(value, "tolist") and not isinstance(value, (str, bytes)):
100
+ value = value.tolist()
101
+ if isinstance(value, str):
102
+ raw = value.replace(";", ",").replace("|", ",").split(",")
103
+ return {item.strip() for item in raw if item.strip()}
104
+ if isinstance(value, (list, tuple, set)):
105
+ return {
106
+ str(item).strip()
107
+ for item in value
108
+ if item is not None and str(item).strip()
109
+ }
110
+ try:
111
+ if bool(np.isnan(value)):
112
+ return set()
113
+ except (TypeError, ValueError):
114
+ pass
115
+ return {str(value).strip()} if str(value).strip() else set()
116
+
117
+
118
+ def _apply_tag_filters(
119
+ frame: Any,
120
+ mask: Any,
121
+ *,
122
+ tags_include: Optional[Union[str, List[str]]] = None,
123
+ tags_exclude: Optional[Union[str, List[str]]] = None,
124
+ tag_column: str = "tags",
125
+ tag_mode: str = "all",
126
+ ) -> Any:
127
+ r"""Apply include/exclude tag filters to a boolean pandas/numpy mask."""
128
+ include = _normalise_tags_arg(tags_include)
129
+ exclude = _normalise_tags_arg(tags_exclude)
130
+ if not include and not exclude:
131
+ return mask
132
+ if tag_mode not in {"all", "any"}:
133
+ raise ValueError("tag_mode must be 'all' or 'any'.")
134
+ if tag_column not in frame.columns:
135
+ message = (
136
+ f"Tag column '{tag_column}' not found in KKLT catalog; "
137
+ "include-tag filter matched no rows."
138
+ if include
139
+ else
140
+ f"Tag column '{tag_column}' not found in KKLT catalog; "
141
+ "tag filter ignored."
142
+ )
143
+ warnings.warn(message, stacklevel=3)
144
+ if include:
145
+ return mask & np.zeros(len(frame), dtype=bool)
146
+ return mask
147
+
148
+ row_tags = frame[tag_column].map(_tags_from_cell)
149
+ if include:
150
+ if tag_mode == "all":
151
+ mask &= row_tags.map(lambda tags: include.issubset(tags)).values
152
+ else:
153
+ mask &= row_tags.map(lambda tags: bool(include & tags)).values
154
+ if exclude:
155
+ mask &= row_tags.map(lambda tags: exclude.isdisjoint(tags)).values
156
+ return mask
157
+
158
+
159
+ @contextmanager
160
+ def _file_lock(path: Path):
161
+ r"""Advisory exclusive flock on a sibling lockfile.
162
+
163
+ Used to serialise concurrent appends to ``run_log.parquet`` from
164
+ parallel cluster workers writing into a shared local cache. Falls
165
+ back to a no-op on platforms without :mod:`fcntl` (Windows).
166
+ """
167
+ try:
168
+ import fcntl
169
+ except ImportError:
170
+ yield
171
+ return
172
+ lock_path = path.with_suffix(path.suffix + ".lock")
173
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
174
+ fh = open(lock_path, "a+")
175
+ try:
176
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
177
+ yield
178
+ finally:
179
+ try:
180
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
181
+ finally:
182
+ fh.close()
183
+
184
+
185
+ # Column schema for the append-only run log (``run_log.parquet``).
186
+ _RUN_LOG_COLUMNS = [
187
+ "run_id", "scope", "ks_id", "coni_class_id",
188
+ "coni_id", "attempt_index", "status",
189
+ "started_at", "finished_at",
190
+ "job_id", "host", "worker", "task",
191
+ "n_solutions", "n_attempted",
192
+ "payload_uri", "payload_hash",
193
+ "error_summary", "notes",
194
+ ]
195
+
196
+
197
+ # ----------------------------------------------------------------------------
198
+ # Module-level constants and env-var helpers
199
+ # ----------------------------------------------------------------------------
200
+
201
+ DEFAULT_KKLT_HF_REPO: str = HF_REPO_ID
202
+
203
+
204
+ def _resolve_kklt_hf_repo() -> str:
205
+ r"""
206
+ **Description:**
207
+ Return the HuggingFace dataset repo ID for the ``kklt`` sub-dataset.
208
+
209
+ KKLT index data now live inside the general-purpose
210
+ ``aschachner/cy-database`` repository. This helper is kept for
211
+ compatibility with older code paths and therefore resolves to the
212
+ normal ``STRINGFORGE_HF_REPO`` value, not to a separate KKLT
213
+ repository.
214
+
215
+ Returns:
216
+ str: ``"user/repo"`` HF Hub identifier.
217
+ """
218
+ return DEFAULT_KKLT_HF_REPO
219
+
220
+
221
+ # ----------------------------------------------------------------------------
222
+ # KKLTDatabase
223
+ # ----------------------------------------------------------------------------
224
+
225
+
226
+ class KKLTDatabase(LCSDatabase):
227
+ r"""
228
+ **Description:**
229
+ Advanced KKLT index interface: a curated subset of
230
+ :class:`~stringforge.lcs_database.LCSDatabase` (``dataset="tdf"``).
231
+
232
+ This is specialised infrastructure for curated KKLT-style searches, not the default user entry point.
233
+ The KKLT database does **not** duplicate Calabi-Yau geometry data.
234
+ Every row in the local catalogs carries a *logical* link
235
+ ``(ks_id, triang_id, tdf_conifold_id)`` into the full TDF dataset;
236
+ physical shard coordinates are resolved on demand by the wrapped TDF
237
+ database held on :attr:`tdf`.
238
+
239
+ Models are indexed by ``(ks_id, coni_class_id, coni_id)``. Conifolds
240
+ sharing the same *one-face divisor* on a given polytope form a single
241
+ ``coni_class``; this grouping cuts across triangulations of the same
242
+ polytope.
243
+
244
+ Three local catalogs live under ``<cache_dir>/kklt/``:
245
+
246
+ - ``catalog.parquet`` (polytope-grain): one row per ``ks_id`` with
247
+ ``h11``, ``h12``, ``chi``, ``n_rigids_dual``, ``Q``,
248
+ ``n_coni_classes``. All KKLT polytopes satisfy
249
+ ``n_rigids_dual > h12``; the historically well-studied subset
250
+ ``Q >= 100`` is a downstream DataFrame filter, not a build-time cut.
251
+ - ``conifold_class_catalog.parquet``: one row per
252
+ ``(ks_id, coni_class_id)``.
253
+ - ``conifold_catalog.parquet``: one row per
254
+ ``(ks_id, coni_class_id, coni_id)``, carrying the logical TDF link.
255
+
256
+ Optional local ``run_log.parquet`` records cluster runs
257
+ (``scope="class"`` or ``scope="conifold"``) for private/local
258
+ run-tracking. Public designated vacuum records belong in the
259
+ shared ``vacua_vault/kklt_vacua`` area.
260
+
261
+ A *TDF-compat fingerprint* (``tdf_schema_version``,
262
+ ``tdf_catalog_sha256``) is stored in ``schema.json`` at build time
263
+ and re-checked on every instantiation. A mismatch raises a
264
+ :class:`UserWarning` pointing the user at :meth:`rebuild_links`.
265
+
266
+ Example usage::
267
+
268
+ from stringforge.kklt_database import KKLTDatabase
269
+ db = KKLTDatabase()
270
+ polys = db.query_polytopes(Q_min=100)
271
+ classes = db.query_classes(ks_id=int(polys.iloc[0]["ks_id"]))
272
+ cfs = db.query_conifolds(
273
+ ks_id=int(polys.iloc[0]["ks_id"]),
274
+ coni_class_id=int(classes.iloc[0]["coni_class_id"]),
275
+ )
276
+ """
277
+
278
+ # Consumed by :meth:`CYDatabase.from_local` so that
279
+ # ``KKLTDatabase.from_local(path)`` infers ``dataset="kklt"``.
280
+ _DATASET: str = "kklt"
281
+
282
+ @classmethod
283
+ def from_local( # type: ignore[override]
284
+ cls,
285
+ path: Union[str, Path],
286
+ dataset: Optional[str] = None,
287
+ shard_cache_size: int = 32,
288
+ *,
289
+ tdf_db: Optional[LCSDatabase] = None,
290
+ tdf_cache_dir: Optional[str] = None,
291
+ ) -> "KKLTDatabase":
292
+ r"""
293
+ **Description:**
294
+ Create an offline :class:`KKLTDatabase` from a local build,
295
+ allowing the wrapped TDF database to be supplied explicitly.
296
+
297
+ Args:
298
+ path (str | Path): KKLT cache root (the directory
299
+ *containing* ``kklt/``, or the ``kklt/`` directory
300
+ itself).
301
+ dataset (str | None): Sub-dataset id; must be
302
+ ``"kklt"`` if supplied. Defaults to ``cls._DATASET``.
303
+ shard_cache_size (int): LRU shard cache size for KKLT
304
+ (does not affect the wrapped TDF).
305
+ tdf_db (LCSDatabase | None): Pre-built TDF database.
306
+ Recommended when your TDF cache is not a sibling of
307
+ the KKLT cache.
308
+ tdf_cache_dir (str | None): If ``tdf_db`` is not supplied
309
+ but the TDF cache is in a non-default location, set
310
+ ``tdf_cache_dir`` and a fresh offline
311
+ ``LCSDatabase(dataset="tdf", cache_dir=tdf_cache_dir,
312
+ offline=True)`` is built and wrapped.
313
+
314
+ Returns:
315
+ KKLTDatabase: Offline instance with the right wrapped TDF.
316
+
317
+ Example::
318
+
319
+ db = KKLTDatabase.from_local(".", tdf_cache_dir="./cy-database/")
320
+ # or
321
+ tdf = LCSDatabase(dataset="tdf", cache_dir="./cy-database/", offline=True)
322
+ db = KKLTDatabase.from_local(".", tdf_db=tdf)
323
+ """
324
+ if dataset is None:
325
+ dataset = cls._DATASET
326
+ if dataset != cls._DATASET:
327
+ raise ValueError(
328
+ f"KKLTDatabase.from_local requires dataset={cls._DATASET!r}; "
329
+ f"got {dataset!r}."
330
+ )
331
+ path = Path(path)
332
+ if path.name == dataset and (path / "catalog.parquet").exists():
333
+ path = path.parent
334
+ if tdf_db is None and tdf_cache_dir is not None:
335
+ tdf_db = LCSDatabase(
336
+ dataset = "tdf",
337
+ cache_dir = str(tdf_cache_dir),
338
+ offline = True,
339
+ )
340
+ return cls(
341
+ tdf_db = tdf_db,
342
+ cache_dir = str(path),
343
+ offline = True,
344
+ shard_cache_size = shard_cache_size,
345
+ )
346
+
347
+ def __init__(
348
+ self,
349
+ tdf_db: Optional[LCSDatabase] = None,
350
+ hf_repo: Optional[str] = None,
351
+ cache_dir: Optional[str] = None,
352
+ offline: bool = False,
353
+ cache_mode: str = "persistent",
354
+ shard_cache_size: int = 32,
355
+ dataset: Optional[str] = None,
356
+ ) -> None:
357
+ r"""Initialise a :class:`KKLTDatabase` instance.
358
+
359
+ Args:
360
+ tdf_db (LCSDatabase | None): Pre-built TDF
361
+ :class:`~stringforge.lcs_database.LCSDatabase` to delegate
362
+ shard fetches and model loads to. If ``None``, a fresh
363
+ ``LCSDatabase(dataset="tdf", ...)`` is constructed lazily
364
+ on first use with matching ``offline`` / ``cache_mode`` /
365
+ ``shard_cache_size`` settings and the same parent
366
+ ``cache_dir``.
367
+ hf_repo (str | None): HuggingFace repository ID for the
368
+ ``kklt`` parquet shards. Defaults to the general
369
+ cy-database repository.
370
+ cache_dir (str | None): Local cache directory. Defaults to
371
+ the global ``stringforge.data_dir``.
372
+ offline (bool): If ``True``, no network access is attempted.
373
+ The wrapped TDF database inherits this setting.
374
+ cache_mode (str): Shard cache mode. See
375
+ :class:`~stringforge.cy_io.CYDatabase`.
376
+ shard_cache_size (int): LRU shard cache size. See
377
+ :class:`~stringforge.cy_io.CYDatabase`.
378
+ dataset (str | None): Accepted for compatibility with
379
+ :meth:`~stringforge.cy_io.CYDatabase.from_local`; must
380
+ equal ``"kklt"`` if supplied.
381
+
382
+ Raises:
383
+ ValueError: If ``dataset`` is supplied and is not
384
+ ``"kklt"``.
385
+ """
386
+ if dataset is not None and dataset != self._DATASET:
387
+ raise ValueError(
388
+ f"KKLTDatabase requires dataset={self._DATASET!r}; "
389
+ f"got {dataset!r}"
390
+ )
391
+
392
+ super().__init__(
393
+ dataset=self._DATASET,
394
+ hf_repo=hf_repo or _resolve_kklt_hf_repo(),
395
+ cache_dir=cache_dir,
396
+ offline=offline,
397
+ shard_cache_size=shard_cache_size,
398
+ cache_mode=cache_mode,
399
+ )
400
+
401
+ # Wrapped TDF database — owns the raw geometry shards. Built
402
+ # lazily on first access via :attr:`tdf` so a user can construct
403
+ # a KKLTDatabase pointing at a local build without paying the
404
+ # TDF-init cost upfront.
405
+ self._tdf_seed: Optional[LCSDatabase] = tdf_db
406
+ self._tdf_built: Optional[LCSDatabase] = None
407
+
408
+ # KKLT-specific catalogs (loaded lazily by Phase-B _ensure_*).
409
+ self._class_catalog: Any = None
410
+ self._run_log: Any = None
411
+
412
+ # Fingerprint check (no-op when schema.json carries no TDF
413
+ # fingerprint, e.g. for a freshly bootstrapped local build).
414
+ self._check_tdf_compat()
415
+
416
+ # ------------------------------------------------------------------
417
+ # Wrapped TDF database (lazy)
418
+ # ------------------------------------------------------------------
419
+
420
+ @property
421
+ def tdf(self) -> LCSDatabase:
422
+ r"""
423
+ **Description:**
424
+ The wrapped TDF :class:`~stringforge.lcs_database.LCSDatabase`
425
+ instance. Built lazily on first access from the seed passed to
426
+ ``__init__`` (if any), or freshly with matching cache / offline
427
+ settings, using the parent of ``self.cache_dir`` as the TDF cache
428
+ root.
429
+ """
430
+ if self._tdf_built is not None:
431
+ return self._tdf_built
432
+ if self._tdf_seed is not None:
433
+ self._tdf_built = self._tdf_seed
434
+ return self._tdf_built
435
+ tdf_cache = str(self.cache_dir.parent)
436
+ warnings.warn(
437
+ "KKLTDatabase: no `tdf_db` or `tdf_cache_dir` was provided; "
438
+ f"defaulting the wrapped TDF database to cache_dir={tdf_cache!r} "
439
+ "(the parent of this KKLT cache). Pass `tdf_cache_dir=` to "
440
+ "`from_local` to make this explicit.",
441
+ UserWarning,
442
+ stacklevel=2,
443
+ )
444
+ self._tdf_built = LCSDatabase(
445
+ dataset="tdf",
446
+ cache_dir=tdf_cache,
447
+ offline=self.offline,
448
+ cache_mode=self.cache_mode,
449
+ )
450
+ return self._tdf_built
451
+
452
+ # ------------------------------------------------------------------
453
+ # TDF-compat fingerprint check
454
+ # ------------------------------------------------------------------
455
+
456
+ def _check_tdf_compat(self) -> None:
457
+ r"""
458
+ **Description:**
459
+ Verify that the local KKLT cache was built against the same TDF
460
+ version that the wrapped :attr:`tdf` instance is currently
461
+ serving.
462
+
463
+ Reads two optional fields from ``<cache_dir>/schema.json``:
464
+
465
+ - ``tdf_schema_version`` (int) — TDF schema version at KKLT build
466
+ time;
467
+ - ``tdf_catalog_sha256`` (hex string) — sha256 over the TDF
468
+ catalog columns KKLT depends on.
469
+
470
+ If either field is absent the check is silently skipped (so a
471
+ freshly bootstrapped local build does not trip the warning). On
472
+ mismatch a :class:`UserWarning` is emitted pointing the user at
473
+ :meth:`rebuild_links`.
474
+
475
+ This method is called from :meth:`__init__` and is also exposed
476
+ so callers can re-run the check after replacing :attr:`tdf`.
477
+ """
478
+ import json
479
+
480
+ path = self.cache_dir / "schema.json"
481
+ if not path.exists():
482
+ # No local schema.json — the cache has not been populated yet.
483
+ return
484
+ try:
485
+ with open(path) as f:
486
+ stored = json.load(f)
487
+ except (OSError, ValueError):
488
+ return
489
+
490
+ expected_version = stored.get("tdf_schema_version")
491
+ expected_hash = stored.get("tdf_catalog_sha256")
492
+ if expected_version is None and expected_hash is None:
493
+ # No fingerprint recorded — pre-fingerprint local build.
494
+ return
495
+
496
+ # Avoid forcing a TDF catalog download just to run the check; if
497
+ # the wrapped TDF cannot be inspected cheaply, skip silently.
498
+ try:
499
+ current_version = _read_tdf_schema_version(self.tdf)
500
+ current_hash = _compute_tdf_fingerprint(self.tdf)
501
+ except Exception:
502
+ return
503
+
504
+ if (expected_version is not None and current_version != expected_version) \
505
+ or (expected_hash is not None and current_hash != expected_hash):
506
+ warnings.warn(
507
+ "KKLTDatabase: TDF fingerprint mismatch.\n"
508
+ f" Built against: schema v{expected_version!s}, "
509
+ f"sha256={(expected_hash or '')[:12]}...\n"
510
+ f" Current TDF: schema v{current_version!s}, "
511
+ f"sha256={(current_hash or '')[:12]}...\n"
512
+ "Logical TDF keys may no longer resolve. "
513
+ "Run db.rebuild_links() to refresh.",
514
+ stacklevel=2,
515
+ )
516
+
517
+ # ------------------------------------------------------------------
518
+
519
+ def __repr__(self) -> str:
520
+ r"""String representation."""
521
+ status = "catalog loaded" if self._catalog is not None else "catalog not yet loaded"
522
+ return (
523
+ f"KKLTDatabase(dataset='{self.dataset}', "
524
+ f"hf_repo='{self.hf_repo}', {status})"
525
+ )
526
+
527
+ # ------------------------------------------------------------------
528
+ # Catalog ensure-loaders
529
+ # ------------------------------------------------------------------
530
+
531
+ def _ensure_class_catalog(self) -> None:
532
+ r"""
533
+ **Description:**
534
+ Download ``conifold_class_catalog.parquet`` if not already cached,
535
+ then load it into :attr:`_class_catalog`.
536
+
537
+ One row per ``(ks_id, coni_class_id)`` with columns
538
+ ``ks_id``, ``coni_class_id``, ``h11``, ``h12``, ``one_face_divisor``,
539
+ ``n_conifolds_in_class``.
540
+
541
+ Raises:
542
+ FileNotFoundError: If ``offline=True`` and the file is not in
543
+ the local cache.
544
+ """
545
+ if self._class_catalog is not None:
546
+ return
547
+
548
+ pd = _require_pandas()
549
+ path = self.cache_dir / "conifold_class_catalog.parquet"
550
+
551
+ if not path.exists():
552
+ if self.offline:
553
+ raise FileNotFoundError(
554
+ f"Conifold-class catalog not found in cache ({path}) and "
555
+ "offline=True. Run with offline=False first to download "
556
+ "it, or rebuild the database to generate "
557
+ "conifold_class_catalog.parquet."
558
+ )
559
+ self._download_file(
560
+ f"{self.dataset}/conifold_class_catalog.parquet", path
561
+ )
562
+
563
+ self._class_catalog = pd.read_parquet(path)
564
+
565
+ def _ensure_run_log(self) -> None:
566
+ r"""
567
+ **Description:**
568
+ Load ``run_log.parquet`` into :attr:`_run_log`.
569
+
570
+ The run log is append-only and stores one row per
571
+ :meth:`start_run` / :meth:`finish_run` / :meth:`cancel_run`
572
+ invocation; see :data:`_RUN_LOG_COLUMNS` for the schema.
573
+
574
+ If the file is missing the log is initialised in memory as an
575
+ empty DataFrame. This is the standard state for a freshly-built
576
+ database (the build script writes an empty parquet, but the file
577
+ may be absent if the user has never invoked run-tracking).
578
+ """
579
+ if self._run_log is not None:
580
+ return
581
+
582
+ pd = _require_pandas()
583
+ path = self.cache_dir / "run_log.parquet"
584
+
585
+ if path.exists():
586
+ self._run_log = pd.read_parquet(path)
587
+ return
588
+
589
+ if not self.offline:
590
+ # Try a best-effort download; the run log may not exist on
591
+ # the Hub yet for a freshly-published dataset.
592
+ try:
593
+ self._download_file(f"{self.dataset}/run_log.parquet", path)
594
+ self._run_log = pd.read_parquet(path)
595
+ return
596
+ except RuntimeError:
597
+ pass
598
+
599
+ # Fall back to an empty in-memory log.
600
+ self._run_log = pd.DataFrame(columns=_RUN_LOG_COLUMNS)
601
+
602
+ # ------------------------------------------------------------------
603
+ # Query helpers
604
+ # ------------------------------------------------------------------
605
+
606
+ def info(self) -> None: # type: ignore[override]
607
+ r"""Print a summary of the KKLT database.
608
+
609
+ Includes the number of polytopes, conifold classes, and
610
+ individual conifolds, plus the Hodge-number ranges (in mirror
611
+ convention) and tadpole range.
612
+ """
613
+ self._ensure_catalog()
614
+ self._ensure_class_catalog()
615
+ self._ensure_conifold_catalog()
616
+ cat = self._catalog
617
+ class_cat = self._class_catalog
618
+ cf = self._conifold_catalog
619
+
620
+ n_polys = len(cat)
621
+ n_classes = len(class_cat)
622
+ n_cfs = len(cf)
623
+
624
+ h11_min, h11_max = int(cat["h11"].min()), int(cat["h11"].max())
625
+ h12_min, h12_max = int(cat["h12"].min()), int(cat["h12"].max())
626
+ Q_min, Q_max = (
627
+ (int(cat["Q"].min()), int(cat["Q"].max()))
628
+ if "Q" in cat.columns and len(cat)
629
+ else (None, None)
630
+ )
631
+
632
+ print(f"KKLTDatabase — sub-dataset: '{self.dataset}' (mirror convention)")
633
+ print(f" Polytopes : {n_polys:,}")
634
+ print(f" Conifold classes : {n_classes:,}")
635
+ print(f" Conifolds : {n_cfs:,}")
636
+ # Mirror convention: catalog h12 reported as h11, and vice versa.
637
+ print(f" h11 range (mirror) : {h12_min} - {h12_max}")
638
+ print(f" h12 range (mirror) : {h11_min} - {h11_max}")
639
+ if Q_min is not None:
640
+ print(f" Q range : {Q_min} - {Q_max}")
641
+ print(f" Cache dir : {self.cache_dir}")
642
+ print(f" Wrapped TDF hf_repo : {self.tdf.hf_repo}")
643
+
644
+ def query_polytopes(
645
+ self,
646
+ h11: Optional[int] = None,
647
+ h12: Optional[int] = None,
648
+ Q_min: Optional[int] = None,
649
+ Q_max: Optional[int] = None,
650
+ n_rigids_dual_min: Optional[int] = None,
651
+ n_coni_classes_min: Optional[int] = None,
652
+ n_coni_classes_max: Optional[int] = None,
653
+ tags_include: Optional[Union[str, List[str]]] = None,
654
+ tags_exclude: Optional[Union[str, List[str]]] = None,
655
+ tag_mode: str = "all",
656
+ **filters: Any,
657
+ ) -> Any:
658
+ r"""
659
+ **Description:**
660
+ Filter the polytope-grain :attr:`_catalog` and return matching
661
+ rows as a ``pandas.DataFrame``. Operates entirely on the
662
+ in-memory catalog; no geometry data is fetched.
663
+
664
+ Hodge-number arguments are interpreted in *mirror convention*
665
+ (i.e. ``h12`` here = catalog ``h11``), matching the rest of the
666
+ :class:`~stringforge.lcs_database.LCSDatabase` surface.
667
+
668
+ Args:
669
+ h11 (int | None): Mirror :math:`h^{1,1}` (= catalog
670
+ :math:`h^{1,2}`).
671
+ h12 (int | None): Mirror :math:`h^{1,2}` (= catalog
672
+ :math:`h^{1,1}`).
673
+ Q_min (int | None): Lower bound on the D3 tadpole
674
+ :math:`Q = h^{1,1} + h^{1,2} + 2`.
675
+ Q_max (int | None): Upper bound on the D3 tadpole.
676
+ n_rigids_dual_min (int | None): Minimum number of rigid
677
+ divisors on the dual side. (All KKLT polytopes already
678
+ satisfy ``n_rigids_dual > h12``.)
679
+ n_coni_classes_min (int | None): Minimum number of conifold
680
+ classes on the polytope.
681
+ n_coni_classes_max (int | None): Maximum number of conifold
682
+ classes on the polytope.
683
+ tags_include (str | list[str] | None): Require rows to carry
684
+ these tag labels. Tags are read from the ``tags`` column.
685
+ tags_exclude (str | list[str] | None): Reject rows carrying
686
+ any of these tag labels.
687
+ tag_mode (str): ``"all"`` requires every include tag;
688
+ ``"any"`` requires at least one include tag.
689
+ **filters: Additional exact-match filters on catalog columns.
690
+
691
+ Returns:
692
+ pandas.DataFrame: Matching polytope rows, with ``h11`` and
693
+ ``h12`` columns relabelled to mirror convention. The
694
+ catalog ``chi = 2(h11_cat - h12_cat)`` column is dropped
695
+ because its sign is inverted under the mirror swap;
696
+ recompute as ``chi = 2 * (h11 - h12)`` from the mirrored
697
+ columns if needed.
698
+ """
699
+ self._ensure_catalog()
700
+ cat = self._catalog
701
+ mask = np.ones(len(cat), dtype=bool)
702
+
703
+ # Mirror swap at the boundary.
704
+ if h11 is not None:
705
+ mask &= (cat["h12"] == h11).values
706
+ if h12 is not None:
707
+ mask &= (cat["h11"] == h12).values
708
+ if Q_min is not None and "Q" in cat.columns:
709
+ mask &= (cat["Q"] >= Q_min).values
710
+ if Q_max is not None and "Q" in cat.columns:
711
+ mask &= (cat["Q"] <= Q_max).values
712
+ if n_rigids_dual_min is not None and "n_rigids_dual" in cat.columns:
713
+ mask &= (cat["n_rigids_dual"] >= n_rigids_dual_min).values
714
+ if n_coni_classes_min is not None and "n_coni_classes" in cat.columns:
715
+ mask &= (cat["n_coni_classes"] >= n_coni_classes_min).values
716
+ if n_coni_classes_max is not None and "n_coni_classes" in cat.columns:
717
+ mask &= (cat["n_coni_classes"] <= n_coni_classes_max).values
718
+ for col, val in filters.items():
719
+ if col in cat.columns:
720
+ mask &= (cat[col] == val).values
721
+ else:
722
+ warnings.warn(
723
+ f"Column '{col}' not found in KKLT polytope catalog; "
724
+ "filter ignored."
725
+ )
726
+
727
+ mask = _apply_tag_filters(
728
+ cat,
729
+ mask,
730
+ tags_include=tags_include,
731
+ tags_exclude=tags_exclude,
732
+ tag_mode=tag_mode,
733
+ )
734
+ out = _swap_h_columns(cat[mask].reset_index(drop=True))
735
+ return out.drop(columns=["chi"], errors="ignore")
736
+
737
+ def query( # type: ignore[override]
738
+ self,
739
+ h11: Optional[int] = None,
740
+ h12: Optional[int] = None,
741
+ **filters: Any,
742
+ ) -> Any:
743
+ r"""Alias for :meth:`query_polytopes`.
744
+
745
+ Inherited :class:`~stringforge.lcs_database.LCSDatabase` filters
746
+ (``has_conifolds``, ``has_gv``, ``D3_tadpole_max``,
747
+ ``n_conifolds_min``, ``n_conifolds_max``) are silently dropped:
748
+ the KKLT polytope-grain catalog does not carry the columns those
749
+ filters rely on. Use :meth:`query_conifolds` or
750
+ :meth:`query_classes` for per-conifold / per-class views.
751
+ """
752
+ drop_keys = {
753
+ "has_conifolds", "n_conifolds_min", "n_conifolds_max",
754
+ "has_gv", "D3_tadpole_max",
755
+ }
756
+ forwarded = {k: v for k, v in filters.items() if k not in drop_keys}
757
+ return self.query_polytopes(h11=h11, h12=h12, **forwarded)
758
+
759
+ def query_classes(
760
+ self,
761
+ ks_id: Optional[int] = None,
762
+ coni_class_id: Optional[int] = None,
763
+ h11: Optional[int] = None,
764
+ h12: Optional[int] = None,
765
+ n_conifolds_in_class_min: Optional[int] = None,
766
+ n_conifolds_in_class_max: Optional[int] = None,
767
+ tags_include: Optional[Union[str, List[str]]] = None,
768
+ tags_exclude: Optional[Union[str, List[str]]] = None,
769
+ tag_mode: str = "all",
770
+ **filters: Any,
771
+ ) -> Any:
772
+ r"""
773
+ **Description:**
774
+ Filter the per-class catalog and return matching rows.
775
+
776
+ One row per ``(ks_id, coni_class_id)`` — i.e. per conifold class
777
+ on a given polytope. Hodge numbers are in mirror convention.
778
+
779
+ Args:
780
+ ks_id (int | None): Filter by polytope ID.
781
+ coni_class_id (int | None): Filter by conifold-class ID.
782
+ h11 (int | None): Mirror :math:`h^{1,1}` filter.
783
+ h12 (int | None): Mirror :math:`h^{1,2}` filter.
784
+ n_conifolds_in_class_min (int | None): Minimum number of
785
+ individual conifolds in the class.
786
+ n_conifolds_in_class_max (int | None): Maximum number.
787
+ tags_include (str | list[str] | None): Require rows to carry
788
+ these tag labels. Tags are read from the ``tags`` column.
789
+ tags_exclude (str | list[str] | None): Reject rows carrying
790
+ any of these tag labels.
791
+ tag_mode (str): ``"all"`` requires every include tag;
792
+ ``"any"`` requires at least one include tag.
793
+ **filters: Additional exact-match filters.
794
+
795
+ Returns:
796
+ pandas.DataFrame: Matching class rows.
797
+ """
798
+ self._ensure_class_catalog()
799
+ cat = self._class_catalog
800
+ mask = np.ones(len(cat), dtype=bool)
801
+
802
+ if ks_id is not None:
803
+ mask &= (cat["ks_id"] == ks_id).values
804
+ if coni_class_id is not None:
805
+ mask &= (cat["coni_class_id"] == coni_class_id).values
806
+ if h11 is not None and "h12" in cat.columns:
807
+ mask &= (cat["h12"] == h11).values
808
+ if h12 is not None and "h11" in cat.columns:
809
+ mask &= (cat["h11"] == h12).values
810
+ if n_conifolds_in_class_min is not None \
811
+ and "n_conifolds_in_class" in cat.columns:
812
+ mask &= (cat["n_conifolds_in_class"] >= n_conifolds_in_class_min).values
813
+ if n_conifolds_in_class_max is not None \
814
+ and "n_conifolds_in_class" in cat.columns:
815
+ mask &= (cat["n_conifolds_in_class"] <= n_conifolds_in_class_max).values
816
+ for col, val in filters.items():
817
+ if col in cat.columns:
818
+ mask &= (cat[col] == val).values
819
+ else:
820
+ warnings.warn(
821
+ f"Column '{col}' not found in KKLT class catalog; "
822
+ "filter ignored."
823
+ )
824
+
825
+ mask = _apply_tag_filters(
826
+ cat,
827
+ mask,
828
+ tags_include=tags_include,
829
+ tags_exclude=tags_exclude,
830
+ tag_mode=tag_mode,
831
+ )
832
+ df = cat[mask].reset_index(drop=True)
833
+ if "h11" in df.columns and "h12" in df.columns:
834
+ df = _swap_h_columns(df)
835
+ return df.drop(columns=["chi"], errors="ignore")
836
+
837
+ def query_conifolds( # type: ignore[override]
838
+ self,
839
+ ks_id: Optional[int] = None,
840
+ coni_class_id: Optional[int] = None,
841
+ coni_id: Optional[int] = None,
842
+ triang_id: Optional[int] = None,
843
+ h11: Optional[int] = None,
844
+ h12: Optional[int] = None,
845
+ tdf_status: Optional[str] = None,
846
+ tags_include: Optional[Union[str, List[str]]] = None,
847
+ tags_exclude: Optional[Union[str, List[str]]] = None,
848
+ tag_mode: str = "all",
849
+ **filters: Any,
850
+ ) -> Any:
851
+ r"""
852
+ **Description:**
853
+ Filter the per-conifold catalog (one row per
854
+ ``(ks_id, coni_class_id, coni_id)``) and return matching rows.
855
+
856
+ Each row carries the *logical* TDF link
857
+ ``(ks_id, triang_id, tdf_conifold_id)`` — pass that triple to
858
+ :attr:`tdf` to fetch the underlying geometry.
859
+
860
+ Args:
861
+ ks_id (int | None): Filter by polytope ID.
862
+ coni_class_id (int | None): Filter by conifold-class ID.
863
+ coni_id (int | None): Filter by conifold ID within the class.
864
+ triang_id (int | None): Filter by linked TDF triangulation ID.
865
+ h11 (int | None): Mirror :math:`h^{1,1}` filter.
866
+ h12 (int | None): Mirror :math:`h^{1,2}` filter.
867
+ tdf_status (str | None): Filter by TDF-link status
868
+ (``"ok"`` or ``"orphaned"``). Populated by
869
+ :meth:`rebuild_links` after a TDF rebuild.
870
+ tags_include (str | list[str] | None): Require rows to carry
871
+ these tag labels. Tags are read from the ``tags`` column.
872
+ tags_exclude (str | list[str] | None): Reject rows carrying
873
+ any of these tag labels.
874
+ tag_mode (str): ``"all"`` requires every include tag;
875
+ ``"any"`` requires at least one include tag.
876
+ **filters: Additional exact-match filters.
877
+
878
+ Returns:
879
+ pandas.DataFrame: Matching conifold rows, with h-columns
880
+ relabelled to mirror convention when present.
881
+ """
882
+ self._ensure_conifold_catalog()
883
+ cat = self._conifold_catalog
884
+ mask = np.ones(len(cat), dtype=bool)
885
+
886
+ if ks_id is not None:
887
+ mask &= (cat["ks_id"] == ks_id).values
888
+ if coni_class_id is not None and "coni_class_id" in cat.columns:
889
+ mask &= (cat["coni_class_id"] == coni_class_id).values
890
+ if coni_id is not None and "coni_id" in cat.columns:
891
+ mask &= (cat["coni_id"] == coni_id).values
892
+ if triang_id is not None and "triang_id" in cat.columns:
893
+ mask &= (cat["triang_id"] == triang_id).values
894
+ if h11 is not None and "h12" in cat.columns:
895
+ mask &= (cat["h12"] == h11).values
896
+ if h12 is not None and "h11" in cat.columns:
897
+ mask &= (cat["h11"] == h12).values
898
+ if tdf_status is not None and "tdf_status" in cat.columns:
899
+ mask &= (cat["tdf_status"] == tdf_status).values
900
+ for col, val in filters.items():
901
+ if col in cat.columns:
902
+ mask &= (cat[col] == val).values
903
+ else:
904
+ warnings.warn(
905
+ f"Column '{col}' not found in KKLT conifold catalog; "
906
+ "filter ignored."
907
+ )
908
+
909
+ mask = _apply_tag_filters(
910
+ cat,
911
+ mask,
912
+ tags_include=tags_include,
913
+ tags_exclude=tags_exclude,
914
+ tag_mode=tag_mode,
915
+ )
916
+ df = cat[mask].reset_index(drop=True)
917
+ if "h11" in df.columns and "h12" in df.columns:
918
+ df = _swap_h_columns(df)
919
+ return df.drop(columns=["chi"], errors="ignore")
920
+
921
+ # ------------------------------------------------------------------
922
+ # load / load_model — delegation to the wrapped TDF database
923
+ # ------------------------------------------------------------------
924
+
925
+ def _resolve_kklt_row(
926
+ self,
927
+ h11: int,
928
+ ks_id: int,
929
+ coni_class_id: int,
930
+ coni_id: int,
931
+ *,
932
+ h12: Optional[int] = None,
933
+ ) -> Any:
934
+ r"""Filter the conifold catalog by the KKLT primary key and
935
+ return the (unique) matching row as a :class:`pandas.Series`.
936
+
937
+ **All h11/h12 args are in MIRROR convention** (jaxvacua /
938
+ :class:`LCSDatabase` convention), matching the rest of the
939
+ ``KKLTDatabase`` public API. Internally the on-disk catalog
940
+ stores h11/h12 in catalog convention; this method swaps at the
941
+ boundary (``mirror h11 == catalog h12``, ``mirror h12 ==
942
+ catalog h11``) before filtering.
943
+
944
+ ``ks_id`` is only unique within a fixed ``(h11, h12)``, so
945
+ ``h11`` is required and ``h12`` is recommended for full
946
+ disambiguation. When ``h12`` is omitted, the filter uses
947
+ ``(h11, ks_id, coni_class_id, coni_id)`` alone and raises
948
+ :class:`ValueError` if more than one row matches.
949
+
950
+ Raises:
951
+ KeyError: No matching row.
952
+ ValueError: Multiple matches when ``h12`` was not supplied,
953
+ or zero/multiple matches even with ``h12`` given.
954
+ """
955
+ self._ensure_conifold_catalog()
956
+ cf = self._conifold_catalog
957
+ # Mirror → catalog swap. cf columns are catalog convention
958
+ # (cf["h11"] is small; cf["h12"] is large) but the user passes
959
+ # mirror values (h11 large, h12 small).
960
+ mask = (
961
+ (cf["h12"] == h11) # mirror h11 ↔ catalog h12
962
+ & (cf["ks_id"] == ks_id)
963
+ & (cf["coni_class_id"] == coni_class_id)
964
+ & (cf["coni_id"] == coni_id)
965
+ )
966
+ if h12 is not None:
967
+ mask = mask & (cf["h11"] == h12) # mirror h12 ↔ catalog h11
968
+ match = cf[mask]
969
+ if len(match) == 0:
970
+ key_repr = (
971
+ f"(h11={h11}, h12={h12}, ks_id={ks_id}, "
972
+ f"coni_class_id={coni_class_id}, coni_id={coni_id})"
973
+ )
974
+ raise KeyError(f"No KKLT conifold for {key_repr}.")
975
+ if len(match) > 1:
976
+ if h12 is None:
977
+ # ``match["h11"]`` is catalog h11 == mirror h12; show
978
+ # the user the mirror values they care about.
979
+ seen_mirror_h12 = sorted(set(int(x) for x in match["h11"]))
980
+ raise ValueError(
981
+ f"Ambiguous KKLT lookup: {len(match)} rows match "
982
+ f"(h11={h11}, ks_id={ks_id}, "
983
+ f"coni_class_id={coni_class_id}, coni_id={coni_id}) "
984
+ f"across mirror h12 ∈ {seen_mirror_h12}. "
985
+ "Pass h12= to disambiguate."
986
+ )
987
+ raise ValueError(
988
+ f"Ambiguous KKLT lookup: {len(match)} rows match "
989
+ f"(h11={h11}, h12={h12}, ks_id={ks_id}, "
990
+ f"coni_class_id={coni_class_id}, coni_id={coni_id}) "
991
+ "— the catalog has duplicate rows for this key."
992
+ )
993
+ return match.iloc[0]
994
+
995
+ def _resolve_kklt_to_tdf(
996
+ self,
997
+ h11: int,
998
+ ks_id: int,
999
+ coni_class_id: int,
1000
+ coni_id: int,
1001
+ *,
1002
+ h12: Optional[int] = None,
1003
+ ) -> Dict[str, int]:
1004
+ r"""Resolve a KKLT key to its logical TDF coordinates.
1005
+
1006
+ Args:
1007
+ h11 (int): :math:`h^{1,1}` in **mirror convention**
1008
+ (matches :class:`LCSDatabase` and the rest of the KKLT
1009
+ public API). Required — ``ks_id`` is only unique
1010
+ within a fixed ``(h11, h12)``.
1011
+ ks_id (int): Polytope ID.
1012
+ coni_class_id (int): Conifold-class ID.
1013
+ coni_id (int): Conifold ID within the class.
1014
+ h12 (int | None): Optional :math:`h^{1,2}` (mirror).
1015
+ Required only when the
1016
+ ``(h11, ks_id, coni_class_id, coni_id)`` quad alone is
1017
+ ambiguous; in that case :meth:`_resolve_kklt_row` raises
1018
+ a ``ValueError`` advising you to pass it.
1019
+
1020
+ Returns:
1021
+ Dict[str, int]: ``{"ks_id", "triang_id", "tdf_conifold_id",
1022
+ "h11_mirror", "h12_mirror", "h11_cat", "h12_cat"}`` — the
1023
+ row from the local ``conifold_catalog.parquet`` reduced to
1024
+ the columns relevant for a TDF lookup. Both mirror and
1025
+ catalog Hodge numbers are returned so callers can pick the
1026
+ convention they need.
1027
+
1028
+ Raises:
1029
+ KeyError: No matching row in the conifold catalog.
1030
+ ValueError: Row exists but ``tdf_status="orphaned"`` (the TDF
1031
+ model it pointed at is gone — see :meth:`rebuild_links`),
1032
+ or the key is ambiguous and ``h12`` was not supplied.
1033
+ """
1034
+ row = self._resolve_kklt_row(
1035
+ h11, ks_id, coni_class_id, coni_id, h12=h12,
1036
+ )
1037
+ # cf row stores catalog convention. Compute the mirror values
1038
+ # by swapping so callers have both available.
1039
+ cat_h11 = int(row["h11"])
1040
+ cat_h12 = int(row["h12"])
1041
+ mir_h11 = cat_h12
1042
+ mir_h12 = cat_h11
1043
+ if str(row.get("tdf_status", "ok")) == "orphaned":
1044
+ raise ValueError(
1045
+ f"KKLT row (h11={mir_h11}, h12={mir_h12} [mirror], "
1046
+ f"ks_id={ks_id}, coni_class_id={coni_class_id}, "
1047
+ f"coni_id={coni_id}) references a TDF model that no "
1048
+ "longer exists. Run db.rebuild_links() or pick a "
1049
+ "different row."
1050
+ )
1051
+ return {
1052
+ "ks_id": int(row["ks_id"]),
1053
+ "triang_id": int(row["triang_id"]),
1054
+ "tdf_conifold_id": int(row["tdf_conifold_id"]),
1055
+ "h11_mirror": mir_h11,
1056
+ "h12_mirror": mir_h12,
1057
+ "h11_cat": cat_h11,
1058
+ "h12_cat": cat_h12,
1059
+ }
1060
+
1061
+ def _has_kklt_gv(
1062
+ self,
1063
+ h11: int,
1064
+ ks_id: int,
1065
+ coni_class_id: int,
1066
+ coni_id: int,
1067
+ *,
1068
+ h12: Optional[int] = None,
1069
+ ) -> bool:
1070
+ r"""Return ``True`` iff the KKLT conifold-catalog row has populated
1071
+ ``gv_kklt_shard_id`` / ``gv_kklt_row_index`` pointers (i.e.
1072
+ KKLT-native GVs are available for this conifold).
1073
+
1074
+ ``h11`` is required for disambiguation; ``h12`` is optional and
1075
+ only needed when ``(h11, ks_id, coni_class_id, coni_id)`` alone
1076
+ is ambiguous (which raises ``ValueError`` via
1077
+ :meth:`_resolve_kklt_row`). Returns ``False`` rather than
1078
+ raising when the key simply doesn't exist."""
1079
+ pd = _require_pandas()
1080
+ self._ensure_conifold_catalog()
1081
+ if ("gv_kklt_shard_id" not in self._conifold_catalog.columns
1082
+ or "gv_kklt_row_index" not in self._conifold_catalog.columns):
1083
+ return False
1084
+ try:
1085
+ row = self._resolve_kklt_row(
1086
+ h11, ks_id, coni_class_id, coni_id, h12=h12,
1087
+ )
1088
+ except KeyError:
1089
+ return False
1090
+ sh = row["gv_kklt_shard_id"]
1091
+ rw = row["gv_kklt_row_index"]
1092
+ return not (pd.isna(sh) or pd.isna(rw))
1093
+
1094
+ def _fetch_kklt_gv(
1095
+ self,
1096
+ h11: int,
1097
+ ks_id: int,
1098
+ coni_class_id: int,
1099
+ coni_id: int,
1100
+ *,
1101
+ h12: Optional[int] = None,
1102
+ maximum_degree: Optional[int] = None,
1103
+ ) -> Optional[Dict[str, Any]]:
1104
+ r"""
1105
+ **Description:**
1106
+ Fetch the KKLT-native GV row for a given conifold and return it
1107
+ in the same dict shape as :func:`stringforge.cy_io._parse_gv_row`
1108
+ (so it's plug-compatible with TDF's GV loader).
1109
+
1110
+ Args:
1111
+ h11 (int): Hodge number :math:`h^{1,1}` in mirror
1112
+ convention. Required.
1113
+ ks_id (int): Polytope ID.
1114
+ coni_class_id (int): Conifold-class ID.
1115
+ coni_id (int): Conifold ID within the class.
1116
+ h12 (int | None): Optional :math:`h^{1,2}`. Required only
1117
+ when the ``(h11, ks_id, coni_class_id, coni_id)`` quad
1118
+ is ambiguous.
1119
+ maximum_degree (int | None): If supplied, truncate the
1120
+ returned GVs/GWs to entries whose grading-vector
1121
+ dot-product is at most this degree.
1122
+
1123
+ Returns:
1124
+ dict | None: ``{"GVs": {...}, "GWs": {...}, "grading_vector":
1125
+ ndarray}`` matching :func:`_parse_gv_row`; ``None`` if no
1126
+ KKLT GV pointer is populated for this conifold.
1127
+
1128
+ Raises:
1129
+ KeyError: No matching row in the conifold catalog.
1130
+ ValueError: Ambiguous key without ``h12``.
1131
+ """
1132
+ from .cy_io import _parse_gv_row
1133
+
1134
+ pd = _require_pandas()
1135
+ row = self._resolve_kklt_row(
1136
+ h11, ks_id, coni_class_id, coni_id, h12=h12,
1137
+ )
1138
+ sh_id = row.get("gv_kklt_shard_id")
1139
+ rw_idx = row.get("gv_kklt_row_index")
1140
+ if sh_id is None or rw_idx is None or pd.isna(sh_id) or pd.isna(rw_idx):
1141
+ return None
1142
+
1143
+ cat_h11 = int(row["h11"])
1144
+ split = f"gv/h11_{cat_h11}"
1145
+
1146
+ if self.cache_mode == "persistent":
1147
+ shard = self._fetch_shard(split, int(sh_id))
1148
+ gv_row = shard.iloc[int(rw_idx)]
1149
+ else:
1150
+ gv_row = self._fetch_row(split, int(sh_id), int(rw_idx))
1151
+
1152
+ gv_data = _parse_gv_row(gv_row)
1153
+
1154
+ if maximum_degree is not None and gv_data.get("grading_vector") is not None:
1155
+ gvs, gws = self._truncate_gv(
1156
+ gv_data["GVs"], gv_data["GWs"],
1157
+ gv_data["grading_vector"], maximum_degree,
1158
+ )
1159
+ gv_data["GVs"], gv_data["GWs"] = gvs, gws
1160
+
1161
+ return gv_data
1162
+
1163
+ def _effective_gv_source(
1164
+ self,
1165
+ h11: int,
1166
+ ks_id: int,
1167
+ coni_class_id: int,
1168
+ coni_id: int,
1169
+ requested: Optional[str],
1170
+ *,
1171
+ h12: Optional[int] = None,
1172
+ ) -> str:
1173
+ r"""Resolve ``gv_source`` to a concrete ``"kklt"`` or ``"tdf"``.
1174
+
1175
+ - If *requested* is ``"kklt"`` or ``"tdf"``, return it.
1176
+ - If *requested* is ``None``, return ``"kklt"`` whenever
1177
+ :meth:`_has_kklt_gv` is true, else ``"tdf"``.
1178
+
1179
+ Args:
1180
+ h11, ks_id, coni_class_id, coni_id, h12: KKLT key (see
1181
+ :meth:`_resolve_kklt_row`).
1182
+ requested: Explicit ``gv_source`` argument from the public
1183
+ API, or ``None`` for auto-select.
1184
+ """
1185
+ if requested in ("kklt", "tdf"):
1186
+ return requested
1187
+ if requested is not None:
1188
+ raise ValueError(
1189
+ f"gv_source must be 'kklt', 'tdf', or None; "
1190
+ f"got {requested!r}."
1191
+ )
1192
+ return (
1193
+ "kklt"
1194
+ if self._has_kklt_gv(h11, ks_id, coni_class_id, coni_id, h12=h12)
1195
+ else "tdf"
1196
+ )
1197
+
1198
+ def load( # type: ignore[override]
1199
+ self,
1200
+ h11: Optional[int] = None,
1201
+ ks_id: Optional[int] = None,
1202
+ coni_class_id: Optional[int] = None,
1203
+ coni_id: Optional[int] = None,
1204
+ *,
1205
+ h12: Optional[int] = None,
1206
+ include_gv: bool = False,
1207
+ gv_source: Optional[str] = None,
1208
+ conifold_basis: bool = True,
1209
+ include_extra_data: bool = True,
1210
+ include_polytope: bool = False,
1211
+ extra_fields: Optional[List[str]] = None,
1212
+ maximum_degree: Optional[int] = None,
1213
+ ) -> Any:
1214
+ r"""
1215
+ **Description:**
1216
+ Load a KKLT model as an :class:`~jaxvacua.lcs.lcs_tree`,
1217
+ resolving the logical TDF link from this database's
1218
+ ``conifold_catalog.parquet`` and delegating to the wrapped
1219
+ :attr:`tdf` database for the underlying geometry.
1220
+
1221
+ GV invariants can come from either the KKLT-native ``gv/`` split
1222
+ (typically computed at higher truncation degrees and/or in a
1223
+ class-adapted basis) or from the wrapped TDF database's ``gv/``
1224
+ split. See ``gv_source``.
1225
+
1226
+ Args:
1227
+ h11 (int): Hodge number :math:`h^{1,1}` in **mirror
1228
+ convention** (matches :class:`LCSDatabase` and the rest
1229
+ of the KKLT public API). Required — ``ks_id`` is only
1230
+ unique within a fixed ``(h11, h12)``.
1231
+ ks_id (int): Polytope ID. Required.
1232
+ coni_class_id (int): Conifold-class ID. Required.
1233
+ coni_id (int): Conifold ID within the class. Required.
1234
+ h12 (int | None): Optional :math:`h^{1,2}` (mirror). Pass
1235
+ when the ``(h11, ks_id, coni_class_id, coni_id)`` quad
1236
+ is ambiguous (the resolver raises a clear ``ValueError``
1237
+ in that case and tells you which ``h12`` values are
1238
+ available).
1239
+ include_gv (bool): If ``True``, fetch and attach
1240
+ Gopakumar-Vafa and Gromov-Witten invariants.
1241
+ gv_source (str | None): Which GV split to use. One of
1242
+ ``"kklt"`` (KKLT-native), ``"tdf"`` (wrapped TDF), or
1243
+ ``None`` (default; prefer KKLT when its pointer is
1244
+ populated, else fall back to TDF). Ignored when
1245
+ ``include_gv=False``.
1246
+ conifold_basis (bool): If ``True``, rotate to the basis
1247
+ defined by the conifold curve. Passed through.
1248
+ include_extra_data (bool): Passed through.
1249
+ include_polytope (bool): Passed through.
1250
+ extra_fields (list[str] | None): Passed through.
1251
+ maximum_degree (int | None): Passed through. **Known
1252
+ limitation**: ``gv_source="kklt"`` does not currently
1253
+ support truncation because the KKLT GV split stores
1254
+ ``grading_vector=NULL``. Use ``gv_source="tdf"`` if you
1255
+ need ``maximum_degree>0``.
1256
+
1257
+ Returns:
1258
+ lcs_tree: The model in mirror convention, with
1259
+ ``lcs_tree.conifold`` populated from the linked TDF conifold
1260
+ and ``gv_charges`` / ``gv_invariants`` / ``grading_vector``
1261
+ populated from the resolved GV source.
1262
+
1263
+ Raises:
1264
+ KeyError: If the KKLT key is not in the catalog.
1265
+ ValueError: If required key args are missing, the row is
1266
+ ``tdf_status="orphaned"``, ``gv_source`` is invalid, or
1267
+ the ``(h11, ks_id, coni_class_id, coni_id)`` quad is
1268
+ ambiguous and ``h12`` was not supplied.
1269
+ """
1270
+ if (h11 is None or ks_id is None
1271
+ or coni_class_id is None or coni_id is None):
1272
+ raise ValueError(
1273
+ "KKLTDatabase.load requires h11, ks_id, coni_class_id, "
1274
+ "coni_id. Pass h12= too if multiple polytopes share "
1275
+ "the same (h11, ks_id) — see _resolve_kklt_row."
1276
+ )
1277
+ link = self._resolve_kklt_to_tdf(
1278
+ h11, ks_id, coni_class_id, coni_id, h12=h12,
1279
+ )
1280
+
1281
+ effective = (
1282
+ self._effective_gv_source(
1283
+ h11, ks_id, coni_class_id, coni_id, gv_source, h12=h12,
1284
+ )
1285
+ if include_gv
1286
+ else "tdf" # value irrelevant when include_gv=False
1287
+ )
1288
+
1289
+ # Path A: include_gv=False, or include_gv=True with gv_source=tdf.
1290
+ # Either way, the wrapped TDF database produces the tree directly.
1291
+ if not include_gv or effective == "tdf":
1292
+ return self.tdf.load(
1293
+ ks_id = link["ks_id"],
1294
+ triang_id = link["triang_id"],
1295
+ include_gv = include_gv,
1296
+ include_conifolds = True,
1297
+ conifold_id = link["tdf_conifold_id"],
1298
+ conifold_basis = conifold_basis,
1299
+ include_extra_data = include_extra_data,
1300
+ include_polytope = include_polytope,
1301
+ extra_fields = extra_fields,
1302
+ maximum_degree = maximum_degree,
1303
+ )
1304
+
1305
+ # Path B: include_gv=True with gv_source=kklt.
1306
+ # Build the tree without GVs, then attach the KKLT GVs.
1307
+ tree = self.tdf.load(
1308
+ ks_id = link["ks_id"],
1309
+ triang_id = link["triang_id"],
1310
+ include_gv = False,
1311
+ include_conifolds = True,
1312
+ conifold_id = link["tdf_conifold_id"],
1313
+ conifold_basis = conifold_basis,
1314
+ include_extra_data = include_extra_data,
1315
+ include_polytope = include_polytope,
1316
+ extra_fields = extra_fields,
1317
+ maximum_degree = maximum_degree,
1318
+ )
1319
+ gv_data = self._fetch_kklt_gv(
1320
+ h11, ks_id, coni_class_id, coni_id,
1321
+ h12=h12, maximum_degree=maximum_degree,
1322
+ )
1323
+ if gv_data is not None:
1324
+ # Unpack the GV / GW dict into the tree's
1325
+ # ``gv_charges`` / ``gv_invariants`` / ``gv_degrees`` (and
1326
+ # GW counterparts) attributes. Empty dicts (the KKLT
1327
+ # build carries no GW data) map to ``(None, None, None)``.
1328
+ def _safe_unpack(d: Any):
1329
+ if (not isinstance(d, dict)
1330
+ or d.get("charges") is None
1331
+ or d.get("invariants") is None):
1332
+ return (None, None, None)
1333
+ return tree._charges_from_gv_gw(d)
1334
+
1335
+ (tree.gv_charges,
1336
+ tree.gv_invariants,
1337
+ tree.gv_degrees) = _safe_unpack(gv_data["GVs"])
1338
+ (tree.gw_charges,
1339
+ tree.gw_invariants,
1340
+ tree.gw_degrees) = _safe_unpack(gv_data["GWs"])
1341
+ if gv_data.get("grading_vector") is not None:
1342
+ import jax.numpy as jnp
1343
+ tree.grading_vector = jnp.asarray(gv_data["grading_vector"])
1344
+ return tree
1345
+
1346
+ def load_model( # type: ignore[override]
1347
+ self,
1348
+ h11: Optional[int] = None,
1349
+ ks_id: Optional[int] = None,
1350
+ coni_class_id: Optional[int] = None,
1351
+ coni_id: Optional[int] = None,
1352
+ *,
1353
+ h12: Optional[int] = None,
1354
+ include_gv: bool = False,
1355
+ gv_source: Optional[str] = None,
1356
+ conifold_basis: bool = True,
1357
+ maximum_degree: Optional[int] = None,
1358
+ include_polytope: bool = False,
1359
+ **kwargs: Any,
1360
+ ) -> Any:
1361
+ r"""
1362
+ **Description:**
1363
+ Load a KKLT model as a
1364
+ :class:`~jaxvacua.flux_vacua_finder.FluxVacuaFinder`, with
1365
+ topology fetched from the wrapped :attr:`tdf` database and GVs
1366
+ from the KKLT-native split (or TDF — see ``gv_source``).
1367
+
1368
+ See :meth:`load` for argument semantics; additional ``**kwargs``
1369
+ are forwarded to ``LCSDatabase.load_model``.
1370
+
1371
+ Example::
1372
+
1373
+ db = KKLTDatabase.from_local(".", tdf_cache_dir="./cy-database/")
1374
+ model = db.load_model(
1375
+ h11=95, ks_id=384564, coni_class_id=0, coni_id=75,
1376
+ include_gv=True, gv_source="kklt",
1377
+ )
1378
+
1379
+ ``h11`` is mirror convention (matches :class:`LCSDatabase`); the
1380
+ on-disk catalog convention is swapped at the boundary.
1381
+ """
1382
+ if (h11 is None or ks_id is None
1383
+ or coni_class_id is None or coni_id is None):
1384
+ raise ValueError(
1385
+ "KKLTDatabase.load_model requires "
1386
+ "h11, ks_id, coni_class_id, coni_id."
1387
+ )
1388
+ from jaxvacua.flux_vacua_finder import FluxVacuaFinder
1389
+
1390
+ tree = self.load(
1391
+ h11 = h11,
1392
+ ks_id = ks_id,
1393
+ coni_class_id = coni_class_id,
1394
+ coni_id = coni_id,
1395
+ h12 = h12,
1396
+ include_gv = include_gv,
1397
+ gv_source = gv_source,
1398
+ conifold_basis = conifold_basis,
1399
+ include_extra_data = True,
1400
+ include_polytope = include_polytope,
1401
+ maximum_degree = maximum_degree,
1402
+ )
1403
+ return FluxVacuaFinder(lcs_tree_input=tree, **kwargs)
1404
+
1405
+ def load_dataframes(
1406
+ self,
1407
+ h11: int,
1408
+ ks_id: int,
1409
+ coni_class_id: int,
1410
+ coni_id: int,
1411
+ *,
1412
+ h12: Optional[int] = None,
1413
+ include_gv: bool = True,
1414
+ gv_source: Optional[str] = None,
1415
+ include_conifold: bool = True,
1416
+ include_polytope: bool = False,
1417
+ ) -> Dict[str, Any]:
1418
+ r"""
1419
+ **Description:**
1420
+ Load raw parquet rows for a KKLT model as
1421
+ ``pandas.Series`` / ``pandas.DataFrame`` objects — **no
1422
+ jaxvacua** dependency, no ``lcs_tree`` construction.
1423
+
1424
+ Useful for tabular inspection, conversion to other formats, or
1425
+ any workflow that wants the on-disk data without the cost of
1426
+ building a full model.
1427
+
1428
+ Args:
1429
+ h11 (int): :math:`h^{1,1}` in mirror convention.
1430
+ Required — ``ks_id`` is only unique within ``(h11, h12)``.
1431
+ ks_id (int): Polytope ID (KKLT-aligned, 1-based).
1432
+ coni_class_id (int): Conifold-class ID.
1433
+ coni_id (int): Conifold ID within the class.
1434
+ h12 (int | None): Optional :math:`h^{1,2}`. Pass when the
1435
+ ``(h11, ks_id, coni_class_id, coni_id)`` quad is
1436
+ ambiguous.
1437
+ include_gv (bool): If ``True`` (default), include the GV row
1438
+ in the returned dict under key ``"gv"``.
1439
+ gv_source (str | None): ``"kklt"`` / ``"tdf"`` / ``None``
1440
+ (auto-select). Ignored when ``include_gv=False``.
1441
+ include_conifold (bool): If ``True`` (default), include all
1442
+ conifold-shard rows for the underlying TDF triangulation
1443
+ under key ``"conifold"``.
1444
+ include_polytope (bool): If ``True``, include the TDF
1445
+ polytope row under key ``"polytope"``. Defaults to
1446
+ ``False`` (the polytope shard can be large).
1447
+
1448
+ Returns:
1449
+ Dict[str, Any]: A dict with the following keys (omitted when
1450
+ not requested or not available):
1451
+
1452
+ - ``"kklt_polytope"`` (``pandas.Series``): row from
1453
+ ``kklt/catalog.parquet``;
1454
+ - ``"kklt_class"`` (``pandas.Series``): row from
1455
+ ``kklt/conifold_class_catalog.parquet``;
1456
+ - ``"kklt_conifold"`` (``pandas.Series``): row from
1457
+ ``kklt/conifold_catalog.parquet``;
1458
+ - ``"lcs"`` (``pandas.Series``): row from
1459
+ ``tdf/lcs_data/h11_<n>/data-XXXXX.parquet``;
1460
+ - ``"gv"`` (``pandas.Series``): row from the
1461
+ resolved GV shard;
1462
+ - ``"gv_source"`` (``str``): ``"kklt"`` or ``"tdf"``,
1463
+ showing which GV split the ``"gv"`` row came from;
1464
+ - ``"conifold"`` (``pandas.DataFrame``): every
1465
+ conifold row for the linked TDF triangulation;
1466
+ - ``"polytope"`` (``pandas.Series``): row from
1467
+ ``tdf/polytope/data-XXXXX.parquet``.
1468
+
1469
+ Raises:
1470
+ KeyError: If the KKLT key is not in the conifold catalog.
1471
+ ValueError: If the row is ``tdf_status="orphaned"`` or the
1472
+ key is ambiguous and ``h12`` was not supplied.
1473
+ """
1474
+ pd = _require_pandas()
1475
+ link = self._resolve_kklt_to_tdf(
1476
+ h11, ks_id, coni_class_id, coni_id, h12=h12,
1477
+ )
1478
+ # Catalog-convention Hodge numbers (used to filter the on-disk
1479
+ # KKLT catalogs, which are stored in catalog convention).
1480
+ cat_h11 = link["h11_cat"]
1481
+ cat_h12 = link["h12_cat"]
1482
+
1483
+ out: Dict[str, Any] = {}
1484
+ self._ensure_catalog()
1485
+ self._ensure_class_catalog()
1486
+
1487
+ poly_mask = (
1488
+ (self._catalog["h11"] == cat_h11)
1489
+ & (self._catalog["h12"] == cat_h12)
1490
+ & (self._catalog["ks_id"] == ks_id)
1491
+ )
1492
+ if poly_mask.any():
1493
+ out["kklt_polytope"] = self._catalog[poly_mask].iloc[0]
1494
+
1495
+ cls_mask = (
1496
+ (self._class_catalog["h11"] == cat_h11)
1497
+ & (self._class_catalog["h12"] == cat_h12)
1498
+ & (self._class_catalog["ks_id"] == ks_id)
1499
+ & (self._class_catalog["coni_class_id"] == coni_class_id)
1500
+ )
1501
+ if cls_mask.any():
1502
+ out["kklt_class"] = self._class_catalog[cls_mask].iloc[0]
1503
+
1504
+ cf_row = self._resolve_kklt_row(
1505
+ h11, ks_id, coni_class_id, coni_id, h12=link["h12_mirror"],
1506
+ )
1507
+ out["kklt_conifold"] = cf_row
1508
+
1509
+ # ----- LCS data row (from TDF) --------------------------------
1510
+ tdf = self.tdf
1511
+ tdf._ensure_catalog()
1512
+ tdf_cat = tdf._catalog
1513
+ # `(ks_id, triang_id)` is only unique within a fixed h11, so we
1514
+ # filter on the catalog-convention h11 carried by ``link``.
1515
+ tdf_mask = (
1516
+ (tdf_cat["h11"] == link["h11_cat"])
1517
+ & (tdf_cat["ks_id"] == link["ks_id"])
1518
+ & (tdf_cat["triang_id"] == link["triang_id"])
1519
+ )
1520
+ if not tdf_mask.any():
1521
+ raise KeyError(
1522
+ f"TDF catalog has no row for (h11_cat={link['h11_cat']}, "
1523
+ f"ks_id={link['ks_id']}, triang_id={link['triang_id']})."
1524
+ )
1525
+ tdf_row = tdf_cat[tdf_mask].iloc[0]
1526
+ cat_h11 = int(tdf_row["h11"])
1527
+ lcs_sh_id = int(tdf_row["lcs_shard_id"])
1528
+ lcs_rw_idx = int(tdf_row["lcs_row_index"])
1529
+ lcs_split = f"lcs_data/h11_{cat_h11}"
1530
+ if self.cache_mode == "persistent":
1531
+ lcs_shard = tdf._fetch_shard(lcs_split, lcs_sh_id)
1532
+ out["lcs"] = lcs_shard.iloc[lcs_rw_idx]
1533
+ else:
1534
+ out["lcs"] = tdf._fetch_row(lcs_split, lcs_sh_id, lcs_rw_idx)
1535
+
1536
+ # ----- GV row -------------------------------------------------
1537
+ if include_gv:
1538
+ effective = self._effective_gv_source(
1539
+ h11, ks_id, coni_class_id, coni_id, gv_source,
1540
+ h12=link["h12_mirror"],
1541
+ )
1542
+ out["gv_source"] = effective
1543
+ if effective == "kklt":
1544
+ gv_split = f"gv/h11_{cat_h11}"
1545
+ gv_sh_id = int(cf_row["gv_kklt_shard_id"])
1546
+ gv_rw_idx = int(cf_row["gv_kklt_row_index"])
1547
+ if self.cache_mode == "persistent":
1548
+ gv_shard = self._fetch_shard(gv_split, gv_sh_id)
1549
+ out["gv"] = gv_shard.iloc[gv_rw_idx]
1550
+ else:
1551
+ out["gv"] = self._fetch_row(gv_split, gv_sh_id, gv_rw_idx)
1552
+ else: # "tdf"
1553
+ gv_sh_id = tdf_row.get("gv_shard_id")
1554
+ gv_rw_idx = tdf_row.get("gv_row_index")
1555
+ if (gv_sh_id is None or gv_rw_idx is None
1556
+ or pd.isna(gv_sh_id) or pd.isna(gv_rw_idx)):
1557
+ out["gv"] = None
1558
+ else:
1559
+ tdf_gv_split = f"gv/h11_{cat_h11}"
1560
+ if self.cache_mode == "persistent":
1561
+ gv_shard = tdf._fetch_shard(
1562
+ tdf_gv_split, int(gv_sh_id),
1563
+ )
1564
+ out["gv"] = gv_shard.iloc[int(gv_rw_idx)]
1565
+ else:
1566
+ out["gv"] = tdf._fetch_row(
1567
+ tdf_gv_split, int(gv_sh_id), int(gv_rw_idx),
1568
+ )
1569
+
1570
+ # ----- Conifold rows (per-triangulation) -----------------------
1571
+ if include_conifold:
1572
+ cf_sh_id = tdf_row.get("conifold_shard_id")
1573
+ if cf_sh_id is not None and not pd.isna(cf_sh_id):
1574
+ cf_split = f"conifolds/h11_{cat_h11}"
1575
+ cf_shard = tdf._fetch_shard(cf_split, int(cf_sh_id))
1576
+ # Filter to this triangulation only
1577
+ cf_mask_tdf = (
1578
+ (cf_shard["ks_id"] == link["ks_id"])
1579
+ & (cf_shard["triang_id"] == link["triang_id"])
1580
+ )
1581
+ out["conifold"] = cf_shard[cf_mask_tdf].reset_index(drop=True)
1582
+
1583
+ # ----- Polytope row -------------------------------------------
1584
+ if include_polytope:
1585
+ poly_sh_id = tdf_row.get("polytope_shard_id")
1586
+ poly_rw_idx = tdf_row.get("polytope_row_index")
1587
+ if (poly_sh_id is not None and poly_rw_idx is not None
1588
+ and not pd.isna(poly_sh_id) and not pd.isna(poly_rw_idx)):
1589
+ if self.cache_mode == "persistent":
1590
+ poly_shard = tdf._fetch_shard("polytope", int(poly_sh_id))
1591
+ out["polytope"] = poly_shard.iloc[int(poly_rw_idx)]
1592
+ else:
1593
+ out["polytope"] = tdf._fetch_row(
1594
+ "polytope", int(poly_sh_id), int(poly_rw_idx),
1595
+ )
1596
+
1597
+ return out
1598
+
1599
+ def load_from_conifold_row( # type: ignore[override]
1600
+ self,
1601
+ row: Any,
1602
+ **kwargs: Any,
1603
+ ) -> Any:
1604
+ r"""
1605
+ **Description:**
1606
+ Load a KKLT model from a row of :meth:`query_conifolds` output.
1607
+
1608
+ Convenience wrapper over :meth:`load_model` that pulls the
1609
+ full primary key (``h11``, ``h12``, ``ks_id``, ``coni_class_id``,
1610
+ ``coni_id``) from the row. Both the row and :meth:`load_model`
1611
+ use mirror convention, so the values pass straight through.
1612
+
1613
+ Args:
1614
+ row: A ``pandas.Series`` (one row from
1615
+ :meth:`query_conifolds`).
1616
+ **kwargs: Forwarded to :meth:`load_model`.
1617
+
1618
+ Returns:
1619
+ FluxVacuaFinder: The constructed model.
1620
+ """
1621
+ return self.load_model(
1622
+ h11 = int(row["h11"]),
1623
+ h12 = int(row["h12"]),
1624
+ ks_id = int(row["ks_id"]),
1625
+ coni_class_id = int(row["coni_class_id"]),
1626
+ coni_id = int(row["coni_id"]),
1627
+ **kwargs,
1628
+ )
1629
+
1630
+ def load_batch( # type: ignore[override]
1631
+ self,
1632
+ identifiers: Any,
1633
+ *,
1634
+ as_models: bool = False,
1635
+ include_gv: bool = False,
1636
+ gv_source: Optional[str] = None,
1637
+ conifold_basis: bool = True,
1638
+ maximum_degree: Optional[int] = None,
1639
+ include_polytope: bool = False,
1640
+ **kwargs: Any,
1641
+ ) -> List[Any]:
1642
+ r"""
1643
+ **Description:**
1644
+ Load a batch of KKLT models.
1645
+
1646
+ Args:
1647
+ identifiers: One of
1648
+ * a ``pandas.DataFrame`` with columns ``h11``,
1649
+ ``ks_id``, ``coni_class_id``, ``coni_id`` (and
1650
+ optionally ``h12``) — typically the output of
1651
+ :meth:`query_conifolds`;
1652
+ * a list of dicts with the same keys;
1653
+ * a list of 4- or 5-tuples
1654
+ ``(h11, ks_id, coni_class_id, coni_id[, h12])``.
1655
+ as_models (bool): If ``True``, return ``FluxVacuaFinder``
1656
+ instances; otherwise return bare ``lcs_tree`` objects.
1657
+ include_gv, gv_source, conifold_basis, maximum_degree,
1658
+ include_polytope, **kwargs: Forwarded to :meth:`load` or
1659
+ :meth:`load_model`.
1660
+
1661
+ Returns:
1662
+ list: Loaded objects in the same order as *identifiers*.
1663
+ """
1664
+ records = self._identifiers_to_kklt_records(identifiers)
1665
+ loader = self.load_model if as_models else self.load
1666
+ return [
1667
+ loader(
1668
+ h11 = rec["h11"],
1669
+ ks_id = rec["ks_id"],
1670
+ coni_class_id = rec["coni_class_id"],
1671
+ coni_id = rec["coni_id"],
1672
+ h12 = rec.get("h12"),
1673
+ include_gv = include_gv,
1674
+ gv_source = gv_source,
1675
+ conifold_basis= conifold_basis,
1676
+ maximum_degree= maximum_degree,
1677
+ include_polytope = include_polytope,
1678
+ **kwargs,
1679
+ )
1680
+ for rec in records
1681
+ ]
1682
+
1683
+ def iter_batch( # type: ignore[override]
1684
+ self,
1685
+ identifiers: Any,
1686
+ *,
1687
+ as_models: bool = False,
1688
+ include_gv: bool = False,
1689
+ gv_source: Optional[str] = None,
1690
+ conifold_basis: bool = True,
1691
+ maximum_degree: Optional[int] = None,
1692
+ include_polytope: bool = False,
1693
+ **kwargs: Any,
1694
+ ) -> Iterator[Any]:
1695
+ r"""
1696
+ **Description:**
1697
+ Lazy generator counterpart of :meth:`load_batch`. Yields one
1698
+ model at a time so a large iteration does not have to fit in
1699
+ memory.
1700
+
1701
+ See :meth:`load_batch` for argument semantics.
1702
+ """
1703
+ records = self._identifiers_to_kklt_records(identifiers)
1704
+ loader = self.load_model if as_models else self.load
1705
+ for rec in records:
1706
+ yield loader(
1707
+ h11 = rec["h11"],
1708
+ ks_id = rec["ks_id"],
1709
+ coni_class_id = rec["coni_class_id"],
1710
+ coni_id = rec["coni_id"],
1711
+ h12 = rec.get("h12"),
1712
+ include_gv = include_gv,
1713
+ gv_source = gv_source,
1714
+ conifold_basis= conifold_basis,
1715
+ maximum_degree= maximum_degree,
1716
+ include_polytope = include_polytope,
1717
+ **kwargs,
1718
+ )
1719
+
1720
+ def sample( # type: ignore[override]
1721
+ self,
1722
+ n: int = 1,
1723
+ *,
1724
+ seed: Optional[int] = None,
1725
+ as_models: bool = False,
1726
+ query: Optional[Dict[str, Any]] = None,
1727
+ include_gv: bool = False,
1728
+ gv_source: Optional[str] = None,
1729
+ conifold_basis: bool = True,
1730
+ maximum_degree: Optional[int] = None,
1731
+ include_polytope: bool = False,
1732
+ **kwargs: Any,
1733
+ ) -> List[Any]:
1734
+ r"""
1735
+ **Description:**
1736
+ Draw *n* random conifolds from this database and load them.
1737
+
1738
+ Args:
1739
+ n (int): Number of conifolds to draw.
1740
+ seed (int | None): RNG seed for reproducibility.
1741
+ as_models (bool): Return ``FluxVacuaFinder`` instances
1742
+ instead of bare ``lcs_tree`` objects.
1743
+ query (dict | None): Optional filter dict forwarded to
1744
+ :meth:`query_conifolds` (e.g. ``{"h11": 95}``) so the
1745
+ sample is drawn from a subset.
1746
+ include_gv, gv_source, conifold_basis, maximum_degree,
1747
+ include_polytope, **kwargs: Forwarded to the loader.
1748
+
1749
+ Returns:
1750
+ list: Loaded objects.
1751
+ """
1752
+ pool = self.query_conifolds(**(query or {}))
1753
+ if len(pool) == 0:
1754
+ raise ValueError("query_conifolds returned no rows; nothing to sample.")
1755
+ sampled = pool.sample(n=min(int(n), len(pool)), random_state=seed)
1756
+ return self.load_batch(
1757
+ sampled,
1758
+ as_models = as_models,
1759
+ include_gv = include_gv,
1760
+ gv_source = gv_source,
1761
+ conifold_basis = conifold_basis,
1762
+ maximum_degree = maximum_degree,
1763
+ include_polytope = include_polytope,
1764
+ **kwargs,
1765
+ )
1766
+
1767
+ def _identifiers_to_kklt_records(
1768
+ self, identifiers: Any,
1769
+ ) -> List[Dict[str, int]]:
1770
+ r"""Normalise *identifiers* to a list of dicts with keys
1771
+ ``h11``, ``ks_id``, ``coni_class_id``, ``coni_id`` and
1772
+ (optionally) ``h12``.
1773
+
1774
+ Accepts:
1775
+ * a ``pandas.DataFrame`` with those columns;
1776
+ * an iterable of dicts;
1777
+ * an iterable of 4- or 5-tuples
1778
+ ``(h11, ks_id, coni_class_id, coni_id[, h12])``.
1779
+ """
1780
+ pd = _require_pandas()
1781
+ out: List[Dict[str, int]] = []
1782
+
1783
+ if isinstance(identifiers, pd.DataFrame):
1784
+ for _, row in identifiers.iterrows():
1785
+ rec = {
1786
+ "h11": int(row["h11"]),
1787
+ "ks_id": int(row["ks_id"]),
1788
+ "coni_class_id": int(row["coni_class_id"]),
1789
+ "coni_id": int(row["coni_id"]),
1790
+ }
1791
+ if "h12" in row.index:
1792
+ rec["h12"] = int(row["h12"])
1793
+ out.append(rec)
1794
+ return out
1795
+
1796
+ for item in identifiers:
1797
+ if isinstance(item, dict):
1798
+ rec = {k: int(item[k]) for k in
1799
+ ("h11", "ks_id", "coni_class_id", "coni_id")}
1800
+ if "h12" in item:
1801
+ rec["h12"] = int(item["h12"])
1802
+ out.append(rec)
1803
+ elif isinstance(item, (list, tuple)) and len(item) in (4, 5):
1804
+ rec = {
1805
+ "h11": int(item[0]),
1806
+ "ks_id": int(item[1]),
1807
+ "coni_class_id": int(item[2]),
1808
+ "coni_id": int(item[3]),
1809
+ }
1810
+ if len(item) == 5:
1811
+ rec["h12"] = int(item[4])
1812
+ out.append(rec)
1813
+ else:
1814
+ raise TypeError(
1815
+ f"Cannot interpret identifier {item!r}; pass a "
1816
+ "DataFrame, a dict, or a "
1817
+ "(h11, ks_id, coni_class_id, coni_id[, h12]) tuple."
1818
+ )
1819
+ return out
1820
+
1821
+ # ------------------------------------------------------------------
1822
+ # Solution stages: pfv / precursor / vacua
1823
+ #
1824
+ # Layout (per stage):
1825
+ #
1826
+ # <cache_dir>/kklt/<stage>/<kind?>/
1827
+ # h11_<n>_h12_<m>_ksid_<id>/
1828
+ # coniclass_<c>_coni_<k>/
1829
+ # run_<run_id>.parquet
1830
+ #
1831
+ # Each cluster run writes its own ``run_<run_id>.parquet`` fragment;
1832
+ # readers concatenate every matching fragment in the per-conifold
1833
+ # directory. Identity columns (h11, h12, ks_id, coni_class_id,
1834
+ # coni_id, run_id) are stamped on every row; everything else the
1835
+ # caller supplies in ``rows`` is preserved verbatim.
1836
+ # ------------------------------------------------------------------
1837
+
1838
+ def _kklt_stage_dir(
1839
+ self,
1840
+ stage: str,
1841
+ kind: Optional[str] = None,
1842
+ ) -> Path:
1843
+ r"""Return the absolute root directory for a KKLT solution stage.
1844
+
1845
+ Args:
1846
+ stage (str): One of the keys of :data:`_KKLT_STAGES`.
1847
+ kind (str | None): A valid sub-kind for the stage, or
1848
+ ``None`` for stages that have no sub-kind (``"vacua"``).
1849
+
1850
+ Raises:
1851
+ ValueError: If *stage* is unknown or *kind* is invalid for
1852
+ the stage.
1853
+ """
1854
+ if stage not in _KKLT_STAGES:
1855
+ raise ValueError(
1856
+ f"Unknown KKLT stage {stage!r}; "
1857
+ f"valid: {sorted(_KKLT_STAGES)}."
1858
+ )
1859
+ valid_kinds = _KKLT_STAGES[stage]
1860
+ if valid_kinds is None:
1861
+ if kind is not None:
1862
+ raise ValueError(
1863
+ f"Stage {stage!r} accepts no sub-kind; got kind={kind!r}."
1864
+ )
1865
+ return self.cache_dir / stage
1866
+ if kind is None or kind not in valid_kinds:
1867
+ raise ValueError(
1868
+ f"Stage {stage!r} requires kind in {list(valid_kinds)!r}; "
1869
+ f"got kind={kind!r}."
1870
+ )
1871
+ return self.cache_dir / stage / kind
1872
+
1873
+ def _kklt_fragment_path(
1874
+ self,
1875
+ stage: str,
1876
+ kind: Optional[str],
1877
+ *,
1878
+ h11: int,
1879
+ h12: int,
1880
+ ks_id: int,
1881
+ coni_class_id: int,
1882
+ coni_id: int,
1883
+ run_id: str,
1884
+ ) -> Path:
1885
+ r"""Return the absolute path for a KKLT stage's per-run
1886
+ fragment parquet file."""
1887
+ return (
1888
+ self._kklt_stage_dir(stage, kind)
1889
+ / _kklt_polytope_dirname(h11, h12, ks_id)
1890
+ / _kklt_conifold_dirname(coni_class_id, coni_id)
1891
+ / f"run_{run_id}.parquet"
1892
+ )
1893
+
1894
+ def _write_stage_fragment(
1895
+ self,
1896
+ rows: Any,
1897
+ stage: str,
1898
+ kind: Optional[str],
1899
+ *,
1900
+ h11: int,
1901
+ h12: int,
1902
+ ks_id: int,
1903
+ coni_class_id: int,
1904
+ coni_id: int,
1905
+ run_id: Optional[str] = None,
1906
+ extra_columns: Optional[Dict[str, Any]] = None,
1907
+ ) -> Path:
1908
+ r"""Write one KKLT stage fragment.
1909
+
1910
+ ``rows`` may be a ``pandas.DataFrame``, a list of dicts, or any
1911
+ object the :class:`pandas.DataFrame` constructor accepts. The
1912
+ five identity columns (``h11, h12, ks_id, coni_class_id,
1913
+ coni_id``) and ``run_id`` are stamped on every row, overwriting
1914
+ any preexisting values. Additional columns supplied by the
1915
+ caller (via ``rows`` or ``extra_columns``) pass through
1916
+ verbatim.
1917
+
1918
+ Args:
1919
+ rows: Open-ended row payload.
1920
+ stage (str): KKLT stage name (``"pfv"`` / ``"precursor"`` /
1921
+ ``"vacua"``).
1922
+ kind (str | None): Sub-kind for the stage (or ``None``).
1923
+ h11, h12, ks_id, coni_class_id, coni_id (int): KKLT
1924
+ identity.
1925
+ run_id (str | None): UUID-style run identifier. Auto-
1926
+ generated if ``None``.
1927
+ extra_columns (dict | None): Extra columns to stamp on
1928
+ every row (useful for run-level scalars like ``method``,
1929
+ ``solver_version``, ...).
1930
+
1931
+ Returns:
1932
+ Path: Absolute path of the written fragment file.
1933
+ """
1934
+ pd = _require_pandas()
1935
+ if run_id is None:
1936
+ run_id = uuid.uuid4().hex
1937
+
1938
+ if isinstance(rows, pd.DataFrame):
1939
+ df = rows.copy()
1940
+ else:
1941
+ df = pd.DataFrame(rows)
1942
+
1943
+ df["h11"] = int(h11)
1944
+ df["h12"] = int(h12)
1945
+ df["ks_id"] = int(ks_id)
1946
+ df["coni_class_id"] = int(coni_class_id)
1947
+ df["coni_id"] = int(coni_id)
1948
+ df["run_id"] = run_id
1949
+ if extra_columns:
1950
+ n = len(df)
1951
+ for k, v in extra_columns.items():
1952
+ # Broadcast non-scalar values (arrays, lists, dicts) as
1953
+ # object-typed cells — pandas otherwise interprets a
1954
+ # length-K array as one-value-per-row. Scalars (int,
1955
+ # float, str, complex, np.number) assign directly.
1956
+ is_scalar = (
1957
+ v is None
1958
+ or isinstance(v, (bool, int, float, complex, str, bytes,
1959
+ np.bool_, np.integer, np.floating,
1960
+ np.complexfloating))
1961
+ )
1962
+ if is_scalar:
1963
+ df[k] = v
1964
+ else:
1965
+ df[k] = pd.Series([v] * n, index=df.index, dtype=object)
1966
+
1967
+ path = self._kklt_fragment_path(
1968
+ stage, kind,
1969
+ h11=h11, h12=h12, ks_id=ks_id,
1970
+ coni_class_id=coni_class_id, coni_id=coni_id,
1971
+ run_id=run_id,
1972
+ )
1973
+ path.parent.mkdir(parents=True, exist_ok=True)
1974
+ df.to_parquet(path, index=False)
1975
+ return path
1976
+
1977
+ def _read_stage_fragments(
1978
+ self,
1979
+ stage: str,
1980
+ kind: Optional[str] = None,
1981
+ *,
1982
+ h11: Optional[int] = None,
1983
+ h12: Optional[int] = None,
1984
+ ks_id: Optional[int] = None,
1985
+ coni_class_id: Optional[int] = None,
1986
+ coni_id: Optional[int] = None,
1987
+ run_id: Optional[str] = None,
1988
+ ) -> Any:
1989
+ r"""Read and concatenate every matching fragment parquet.
1990
+
1991
+ Each filter argument left as ``None`` becomes a glob wildcard.
1992
+ Missing directories silently yield an empty DataFrame.
1993
+
1994
+ For stages with sub-kinds, ``kind=None`` fans in across every
1995
+ sub-kind under the stage.
1996
+ """
1997
+ pd = _require_pandas()
1998
+ valid_kinds = _KKLT_STAGES.get(stage)
1999
+ if valid_kinds is None:
2000
+ kind_dirs = [self._kklt_stage_dir(stage, None)]
2001
+ elif kind is None:
2002
+ kind_dirs = [self._kklt_stage_dir(stage, k) for k in valid_kinds]
2003
+ else:
2004
+ kind_dirs = [self._kklt_stage_dir(stage, kind)]
2005
+
2006
+ # Build directory-name glob fragments
2007
+ h11_pat = h11 if h11 is not None else "*"
2008
+ h12_pat = h12 if h12 is not None else "*"
2009
+ ks_pat = ks_id if ks_id is not None else "*"
2010
+ cls_pat = coni_class_id if coni_class_id is not None else "*"
2011
+ coni_pat = coni_id if coni_id is not None else "*"
2012
+ run_pat = run_id if run_id is not None else "*"
2013
+
2014
+ poly_glob = f"h11_{h11_pat}_h12_{h12_pat}_ksid_{ks_pat}"
2015
+ cf_glob = f"coniclass_{cls_pat}_coni_{coni_pat}"
2016
+ file_glob = f"run_{run_pat}.parquet"
2017
+
2018
+ files: List[Path] = []
2019
+ for kd in kind_dirs:
2020
+ if not kd.exists():
2021
+ continue
2022
+ files.extend(sorted(kd.glob(f"{poly_glob}/{cf_glob}/{file_glob}")))
2023
+
2024
+ if not files:
2025
+ return pd.DataFrame()
2026
+
2027
+ dfs = [pd.read_parquet(f) for f in files]
2028
+ return pd.concat(dfs, ignore_index=True) if len(dfs) > 1 else dfs[0]
2029
+
2030
+ # ----- pfv ----------------------------------------------------------
2031
+
2032
+ def write_pfvs(
2033
+ self,
2034
+ rows: Any,
2035
+ *,
2036
+ kind: str,
2037
+ h11: int,
2038
+ h12: int,
2039
+ ks_id: int,
2040
+ coni_class_id: int,
2041
+ coni_id: int,
2042
+ run_id: Optional[str] = None,
2043
+ extra_columns: Optional[Dict[str, Any]] = None,
2044
+ ) -> Path:
2045
+ r"""Append a PFV fragment under
2046
+ ``<cache>/kklt/pfv/<kind>/.../run_<run_id>.parquet``.
2047
+
2048
+ Args:
2049
+ rows: Open-ended row payload (DataFrame or list of dicts).
2050
+ kind (str): ``"harvested"`` (raw flux scan output) or
2051
+ ``"promoted"`` (post-Newton, integer flux).
2052
+ h11, h12, ks_id, coni_class_id, coni_id (int): KKLT
2053
+ identity. All required (``h11`` and ``h12`` together
2054
+ disambiguate ``ks_id``).
2055
+ run_id (str | None): Run identifier; auto-generated if
2056
+ ``None``. Pass an explicit ``run_id`` (e.g. from
2057
+ :meth:`start_run`) to tie the fragment to a run-log
2058
+ entry.
2059
+ extra_columns (dict | None): Extra columns to stamp on
2060
+ every row.
2061
+
2062
+ Returns:
2063
+ Path: Absolute path of the written fragment.
2064
+ """
2065
+ return self._write_stage_fragment(
2066
+ rows, "pfv", kind,
2067
+ h11=h11, h12=h12, ks_id=ks_id,
2068
+ coni_class_id=coni_class_id, coni_id=coni_id,
2069
+ run_id=run_id, extra_columns=extra_columns,
2070
+ )
2071
+
2072
+ def load_pfvs(
2073
+ self,
2074
+ *,
2075
+ kind: Optional[str] = None,
2076
+ h11: Optional[int] = None,
2077
+ h12: Optional[int] = None,
2078
+ ks_id: Optional[int] = None,
2079
+ coni_class_id: Optional[int] = None,
2080
+ coni_id: Optional[int] = None,
2081
+ run_id: Optional[str] = None,
2082
+ ) -> Any:
2083
+ r"""Read every matching PFV fragment, concatenated.
2084
+
2085
+ Each argument left as ``None`` becomes a wildcard (e.g.
2086
+ ``kind=None`` fans in across both ``"harvested"`` and
2087
+ ``"promoted"``; ``ks_id=None`` returns all polytopes).
2088
+ """
2089
+ return self._read_stage_fragments(
2090
+ "pfv", kind,
2091
+ h11=h11, h12=h12, ks_id=ks_id,
2092
+ coni_class_id=coni_class_id, coni_id=coni_id,
2093
+ run_id=run_id,
2094
+ )
2095
+
2096
+ def query_pfvs(self, **filters: Any) -> Any:
2097
+ r"""Alias for :meth:`load_pfvs` (returned DataFrame is then the
2098
+ result of any further pandas filtering)."""
2099
+ return self.load_pfvs(**filters)
2100
+
2101
+ # ----- precursor ----------------------------------------------------
2102
+
2103
+ def write_precursor(
2104
+ self,
2105
+ rows: Any,
2106
+ *,
2107
+ kind: str,
2108
+ h11: int,
2109
+ h12: int,
2110
+ ks_id: int,
2111
+ coni_class_id: int,
2112
+ coni_id: int,
2113
+ run_id: Optional[str] = None,
2114
+ extra_columns: Optional[Dict[str, Any]] = None,
2115
+ ) -> Path:
2116
+ r"""Append a precursor-stage fragment under
2117
+ ``<cache>/kklt/precursor/<kind>/.../run_<run_id>.parquet``.
2118
+
2119
+ Args:
2120
+ rows: Open-ended row payload. May carry any solver-specific
2121
+ columns the caller needs (e.g. ``W0``, ``gs``,
2122
+ eigenvalues, fluxes, derived quantities).
2123
+ kind (str): ``"derived"`` (W0, gs derived from a full SUSY
2124
+ solution) or ``"proxy"`` (SUSY vacua at pre-specified
2125
+ ``W0``, ``gs``).
2126
+ h11, h12, ks_id, coni_class_id, coni_id (int): KKLT
2127
+ identity.
2128
+ run_id (str | None): Run identifier; auto-generated if
2129
+ ``None``.
2130
+ extra_columns (dict | None): Extra columns to stamp on
2131
+ every row (useful for run-level scalars like
2132
+ ``method``, ``solver_version``, ``solver_tolerance``).
2133
+
2134
+ Returns:
2135
+ Path: Absolute path of the written fragment.
2136
+ """
2137
+ return self._write_stage_fragment(
2138
+ rows, "precursor", kind,
2139
+ h11=h11, h12=h12, ks_id=ks_id,
2140
+ coni_class_id=coni_class_id, coni_id=coni_id,
2141
+ run_id=run_id, extra_columns=extra_columns,
2142
+ )
2143
+
2144
+ def load_precursor(
2145
+ self,
2146
+ *,
2147
+ kind: Optional[str] = None,
2148
+ h11: Optional[int] = None,
2149
+ h12: Optional[int] = None,
2150
+ ks_id: Optional[int] = None,
2151
+ coni_class_id: Optional[int] = None,
2152
+ coni_id: Optional[int] = None,
2153
+ run_id: Optional[str] = None,
2154
+ ) -> Any:
2155
+ r"""Read every matching precursor fragment, concatenated."""
2156
+ return self._read_stage_fragments(
2157
+ "precursor", kind,
2158
+ h11=h11, h12=h12, ks_id=ks_id,
2159
+ coni_class_id=coni_class_id, coni_id=coni_id,
2160
+ run_id=run_id,
2161
+ )
2162
+
2163
+ def query_precursor(self, **filters: Any) -> Any:
2164
+ r"""Alias for :meth:`load_precursor`."""
2165
+ return self.load_precursor(**filters)
2166
+
2167
+ # ----- vacua (full stabilisation) ----------------------------------
2168
+
2169
+ def write_vacua( # type: ignore[override]
2170
+ self,
2171
+ rows: Any,
2172
+ *,
2173
+ h11: int,
2174
+ h12: int,
2175
+ ks_id: int,
2176
+ coni_class_id: int,
2177
+ coni_id: int,
2178
+ run_id: Optional[str] = None,
2179
+ extra_columns: Optional[Dict[str, Any]] = None,
2180
+ ) -> Path:
2181
+ r"""Append a full-stabilisation-vacua fragment under
2182
+ ``<cache>/kklt/vacua/.../run_<run_id>.parquet``.
2183
+
2184
+ Args:
2185
+ rows: Open-ended row payload — any solver-specific columns
2186
+ the caller needs (fluxes, moduli, W0, gs, mass spectrum,
2187
+ Kähler moduli, uplift parameters, derived quantities,
2188
+ ...) pass through verbatim.
2189
+ h11, h12, ks_id, coni_class_id, coni_id (int): KKLT
2190
+ identity.
2191
+ run_id (str | None): Run identifier; auto-generated if
2192
+ ``None``.
2193
+ extra_columns (dict | None): Extra columns to stamp on
2194
+ every row.
2195
+
2196
+ Returns:
2197
+ Path: Absolute path of the written fragment.
2198
+ """
2199
+ return self._write_stage_fragment(
2200
+ rows, "vacua", None,
2201
+ h11=h11, h12=h12, ks_id=ks_id,
2202
+ coni_class_id=coni_class_id, coni_id=coni_id,
2203
+ run_id=run_id, extra_columns=extra_columns,
2204
+ )
2205
+
2206
+ def load_vacua( # type: ignore[override]
2207
+ self,
2208
+ *,
2209
+ h11: Optional[int] = None,
2210
+ h12: Optional[int] = None,
2211
+ ks_id: Optional[int] = None,
2212
+ coni_class_id: Optional[int] = None,
2213
+ coni_id: Optional[int] = None,
2214
+ run_id: Optional[str] = None,
2215
+ ) -> Any:
2216
+ r"""Read every matching vacua fragment, concatenated."""
2217
+ return self._read_stage_fragments(
2218
+ "vacua", None,
2219
+ h11=h11, h12=h12, ks_id=ks_id,
2220
+ coni_class_id=coni_class_id, coni_id=coni_id,
2221
+ run_id=run_id,
2222
+ )
2223
+
2224
+ def query_vacua(self, **filters: Any) -> Any: # type: ignore[override]
2225
+ r"""Alias for :meth:`load_vacua`."""
2226
+ return self.load_vacua(**filters)
2227
+
2228
+ # ------------------------------------------------------------------
2229
+ # Run-tracking API
2230
+ # ------------------------------------------------------------------
2231
+
2232
+ def _validate_run_args(
2233
+ self,
2234
+ scope: str,
2235
+ ks_id: int,
2236
+ coni_class_id: int,
2237
+ coni_id: int,
2238
+ ) -> None:
2239
+ r"""Internal: validate run-tracking arguments."""
2240
+ if scope not in _RUN_SCOPES:
2241
+ raise ValueError(
2242
+ f"scope must be one of {sorted(_RUN_SCOPES)}; got {scope!r}."
2243
+ )
2244
+ if scope == "conifold" and coni_id < 0:
2245
+ raise ValueError(
2246
+ "scope='conifold' requires a non-negative coni_id; "
2247
+ f"got coni_id={coni_id}."
2248
+ )
2249
+
2250
+ def _append_run_log_row(self, row: Dict[str, Any]) -> None:
2251
+ r"""Internal: file-lock-guarded append-and-write of a run-log row.
2252
+
2253
+ If ``row["attempt_index"]`` is ``None``, it is allocated under
2254
+ the file lock from the *on-disk* run log so concurrent workers
2255
+ on the same ``(scope, ks_id, coni_class_id, coni_id)`` key get
2256
+ distinct attempt indices.
2257
+
2258
+ The local in-memory cache (:attr:`_run_log`) is updated in-place
2259
+ so subsequent :meth:`run_status` and :meth:`list_runs` calls see
2260
+ the new row without re-reading the parquet.
2261
+ """
2262
+ pd = _require_pandas()
2263
+ path = self.cache_dir / "run_log.parquet"
2264
+ with _file_lock(path):
2265
+ if path.exists():
2266
+ existing = pd.read_parquet(path)
2267
+ else:
2268
+ existing = pd.DataFrame(columns=_RUN_LOG_COLUMNS)
2269
+
2270
+ if row.get("attempt_index") is None:
2271
+ if len(existing):
2272
+ mask = (
2273
+ (existing["scope"] == row["scope"])
2274
+ & (existing["ks_id"] == row["ks_id"])
2275
+ & (existing["coni_class_id"] == row["coni_class_id"])
2276
+ & (existing["coni_id"] == row["coni_id"])
2277
+ )
2278
+ attempts = existing.loc[mask, "attempt_index"].dropna()
2279
+ row["attempt_index"] = (
2280
+ int(attempts.astype(int).max()) + 1
2281
+ if len(attempts) > 0 else 1
2282
+ )
2283
+ else:
2284
+ row["attempt_index"] = 1
2285
+
2286
+ new_row_df = pd.DataFrame([row], columns=_RUN_LOG_COLUMNS)
2287
+ if len(existing) == 0:
2288
+ new = new_row_df.copy()
2289
+ else:
2290
+ # Concat with a deprecation warning suppressed locally:
2291
+ # the run log carries nullable columns (finished_at,
2292
+ # n_solutions, ...) so pandas warns about empty/all-NA
2293
+ # entries even when we explicitly provide column dtypes.
2294
+ # The resulting parquet is correct on disk; ignore.
2295
+ with warnings.catch_warnings():
2296
+ warnings.simplefilter("ignore", category=FutureWarning)
2297
+ new = pd.concat(
2298
+ [existing, new_row_df], ignore_index=True
2299
+ )
2300
+ new.to_parquet(path, index=False)
2301
+ self._run_log = new
2302
+
2303
+ def start_run(
2304
+ self,
2305
+ scope: str,
2306
+ ks_id: int,
2307
+ coni_class_id: int,
2308
+ coni_id: int = -1,
2309
+ *,
2310
+ task: str = "",
2311
+ job_id: str = "",
2312
+ worker: str = "",
2313
+ host: Optional[str] = None,
2314
+ notes: str = "",
2315
+ ) -> str:
2316
+ r"""
2317
+ **Description:**
2318
+ Open a new run-log entry. Appends a ``"running"`` row to
2319
+ ``run_log.parquet`` and returns the generated ``run_id``.
2320
+
2321
+ Args:
2322
+ scope (str): ``"class"`` or ``"conifold"``.
2323
+ ks_id (int): Polytope ID.
2324
+ coni_class_id (int): Conifold-class ID.
2325
+ coni_id (int): Conifold ID within the class (only meaningful
2326
+ when ``scope="conifold"``; pass ``-1`` for
2327
+ ``scope="class"``).
2328
+ task (str): Free-form task tag (e.g. ``"basis_fit"``,
2329
+ ``"flux_scan"``, ``"gv_recompute"``).
2330
+ job_id (str): Cluster job ID / SLURM array index.
2331
+ worker (str): Free-form worker identifier, e.g.
2332
+ ``"rank 12 of 64"``.
2333
+ host (str | None): Hostname. Defaults to the local
2334
+ ``socket.gethostname()``.
2335
+ notes (str): Free-form notes.
2336
+
2337
+ Returns:
2338
+ str: The newly generated ``run_id`` (32-character hex
2339
+ string). Pass back to :meth:`finish_run` /
2340
+ :meth:`cancel_run` to close the entry.
2341
+ """
2342
+ self._validate_run_args(scope, ks_id, coni_class_id, coni_id)
2343
+ self._ensure_run_log()
2344
+
2345
+ row = {
2346
+ "run_id": uuid.uuid4().hex,
2347
+ "scope": scope,
2348
+ "ks_id": int(ks_id),
2349
+ "coni_class_id": int(coni_class_id),
2350
+ "coni_id": int(coni_id) if scope == "conifold" else -1,
2351
+ # Allocated under the file lock in `_append_run_log_row`
2352
+ # so concurrent workers on the same key get distinct values.
2353
+ "attempt_index": None,
2354
+ "status": "running",
2355
+ "started_at": _utcnow(),
2356
+ "finished_at": None,
2357
+ "job_id": str(job_id),
2358
+ "host": str(host or socket.gethostname()),
2359
+ "worker": str(worker),
2360
+ "task": str(task),
2361
+ "n_solutions": None,
2362
+ "n_attempted": None,
2363
+ "payload_uri": "",
2364
+ "payload_hash": "",
2365
+ "error_summary": "",
2366
+ "notes": str(notes),
2367
+ }
2368
+ self._append_run_log_row(row)
2369
+ return row["run_id"]
2370
+
2371
+ def finish_run(
2372
+ self,
2373
+ run_id: str,
2374
+ status: str,
2375
+ *,
2376
+ n_solutions: Optional[int] = None,
2377
+ n_attempted: Optional[int] = None,
2378
+ payload_uri: str = "",
2379
+ payload_hash: str = "",
2380
+ error_summary: str = "",
2381
+ notes: str = "",
2382
+ ) -> None:
2383
+ r"""
2384
+ **Description:**
2385
+ Close a previously-opened run-log entry by appending a closing
2386
+ row (status ``"done"``, ``"failed"``, or ``"cancelled"``).
2387
+
2388
+ The log is append-only — the original ``"running"`` row remains.
2389
+ The derived status view (:meth:`run_status`) picks the latest
2390
+ row per ``(scope, ks_id, coni_class_id, coni_id)``.
2391
+
2392
+ Args:
2393
+ run_id (str): Run ID returned by :meth:`start_run`.
2394
+ status (str): Terminal status. Must be one of ``"done"``,
2395
+ ``"failed"``, ``"cancelled"``.
2396
+ n_solutions (int | None): Number of solutions produced by
2397
+ the run (if applicable).
2398
+ n_attempted (int | None): Number of trials attempted.
2399
+ payload_uri (str): URI to the results blob, if any.
2400
+ payload_hash (str): sha256 of the payload, for de-duplication.
2401
+ error_summary (str): One-line error message, if the run
2402
+ failed.
2403
+ notes (str): Free-form notes.
2404
+
2405
+ Raises:
2406
+ ValueError: If ``status`` is not a terminal status, or if
2407
+ ``run_id`` does not match any open run-log row.
2408
+ """
2409
+ if status not in {"done", "failed", "cancelled"}:
2410
+ raise ValueError(
2411
+ f"status must be one of 'done', 'failed', 'cancelled'; "
2412
+ f"got {status!r}."
2413
+ )
2414
+ self._ensure_run_log()
2415
+ rl = self._run_log
2416
+ matches = rl[rl["run_id"] == run_id]
2417
+ if len(matches) == 0:
2418
+ raise ValueError(f"No run_log row found for run_id={run_id!r}.")
2419
+ head = matches.iloc[0]
2420
+
2421
+ row = {
2422
+ "run_id": run_id,
2423
+ "scope": head["scope"],
2424
+ "ks_id": int(head["ks_id"]),
2425
+ "coni_class_id": int(head["coni_class_id"]),
2426
+ "coni_id": int(head["coni_id"]),
2427
+ "attempt_index": int(head["attempt_index"]),
2428
+ "status": status,
2429
+ "started_at": head["started_at"],
2430
+ "finished_at": _utcnow(),
2431
+ "job_id": head["job_id"],
2432
+ "host": head["host"],
2433
+ "worker": head["worker"],
2434
+ "task": head["task"],
2435
+ "n_solutions": int(n_solutions) if n_solutions is not None else None,
2436
+ "n_attempted": int(n_attempted) if n_attempted is not None else None,
2437
+ "payload_uri": str(payload_uri),
2438
+ "payload_hash": str(payload_hash),
2439
+ "error_summary": str(error_summary),
2440
+ "notes": str(notes),
2441
+ }
2442
+ self._append_run_log_row(row)
2443
+
2444
+ def cancel_run(self, run_id: str, *, notes: str = "") -> None:
2445
+ r"""Convenience wrapper for :meth:`finish_run` with
2446
+ ``status="cancelled"``."""
2447
+ self.finish_run(run_id, status="cancelled", notes=notes)
2448
+
2449
+ def list_runs(
2450
+ self,
2451
+ scope: Optional[str] = None,
2452
+ ks_id: Optional[int] = None,
2453
+ coni_class_id: Optional[int] = None,
2454
+ coni_id: Optional[int] = None,
2455
+ status: Optional[str] = None,
2456
+ task: Optional[str] = None,
2457
+ **filters: Any,
2458
+ ) -> Any:
2459
+ r"""
2460
+ **Description:**
2461
+ Filter the run log and return matching rows as a
2462
+ ``pandas.DataFrame``.
2463
+
2464
+ Args:
2465
+ scope (str | None): Filter by run scope.
2466
+ ks_id (int | None): Filter by polytope ID.
2467
+ coni_class_id (int | None): Filter by conifold-class ID.
2468
+ coni_id (int | None): Filter by conifold ID.
2469
+ status (str | None): Filter by status.
2470
+ task (str | None): Filter by task tag.
2471
+ **filters: Additional exact-match filters.
2472
+
2473
+ Returns:
2474
+ pandas.DataFrame: Matching run-log rows.
2475
+ """
2476
+ self._ensure_run_log()
2477
+ rl = self._run_log
2478
+ mask = np.ones(len(rl), dtype=bool)
2479
+ if scope is not None:
2480
+ mask &= (rl["scope"] == scope).values
2481
+ if ks_id is not None:
2482
+ mask &= (rl["ks_id"] == ks_id).values
2483
+ if coni_class_id is not None:
2484
+ mask &= (rl["coni_class_id"] == coni_class_id).values
2485
+ if coni_id is not None:
2486
+ mask &= (rl["coni_id"] == coni_id).values
2487
+ if status is not None:
2488
+ mask &= (rl["status"] == status).values
2489
+ if task is not None:
2490
+ mask &= (rl["task"] == task).values
2491
+ for col, val in filters.items():
2492
+ if col in rl.columns:
2493
+ mask &= (rl[col] == val).values
2494
+ else:
2495
+ warnings.warn(
2496
+ f"Column '{col}' not found in run log; filter ignored."
2497
+ )
2498
+ return rl[mask].reset_index(drop=True)
2499
+
2500
+ def run_status(
2501
+ self,
2502
+ ks_id: int,
2503
+ coni_class_id: Optional[int] = None,
2504
+ coni_id: Optional[int] = None,
2505
+ ) -> Optional[str]:
2506
+ r"""
2507
+ **Description:**
2508
+ Return the latest run-log status for the given key.
2509
+
2510
+ - If ``coni_class_id`` is ``None``, returns the latest status
2511
+ across ALL runs (any scope) on the polytope.
2512
+ - If ``coni_class_id`` is set and ``coni_id`` is ``None``,
2513
+ returns the latest status at class scope.
2514
+ - If both are set, returns the latest status at conifold scope.
2515
+
2516
+ Returns:
2517
+ str | None: Latest status, or ``None`` if no runs match.
2518
+ """
2519
+ self._ensure_run_log()
2520
+ rl = self._run_log
2521
+ mask = (rl["ks_id"] == ks_id)
2522
+ if coni_class_id is not None:
2523
+ mask &= (rl["coni_class_id"] == coni_class_id)
2524
+ if coni_id is None:
2525
+ mask &= (rl["scope"] == "class")
2526
+ else:
2527
+ mask &= (rl["scope"] == "conifold")
2528
+ mask &= (rl["coni_id"] == coni_id)
2529
+ matched = rl[mask]
2530
+ if len(matched) == 0:
2531
+ return None
2532
+ # The latest entry — break ties by row order (append-only ⇒
2533
+ # later rows are later in time).
2534
+ return str(matched.iloc[-1]["status"])
2535
+
2536
+ # ------------------------------------------------------------------
2537
+ # Hub sync (run log)
2538
+ # ------------------------------------------------------------------
2539
+
2540
+ def push_run_log(self, repo_id: Optional[str] = None) -> None:
2541
+ r"""
2542
+ **Description:**
2543
+ Upload the local ``run_log.parquet`` to the HuggingFace dataset
2544
+ repository. Mirrors :meth:`VacuaWriter.push_vacua_to_hub` —
2545
+ local-only writes plus periodic push is the v1 concurrency
2546
+ story for cluster workers.
2547
+
2548
+ Args:
2549
+ repo_id (str | None): Target HF dataset repo. Defaults to
2550
+ ``self.hf_repo``.
2551
+ """
2552
+ from .cy_io import _require_hf_api
2553
+
2554
+ api = _require_hf_api()
2555
+ repo_id = repo_id or self.hf_repo
2556
+ path = self.cache_dir / "run_log.parquet"
2557
+ if not path.exists():
2558
+ raise FileNotFoundError(
2559
+ f"No local run_log.parquet to push at {path}."
2560
+ )
2561
+ api.upload_file(
2562
+ path_or_fileobj=str(path),
2563
+ path_in_repo=f"{self.dataset}/run_log.parquet",
2564
+ repo_id=repo_id,
2565
+ repo_type="dataset",
2566
+ commit_message=f"update run_log.parquet ({_utcnow().isoformat()})",
2567
+ )
2568
+
2569
+ def fetch_run_log(
2570
+ self,
2571
+ repo_id: Optional[str] = None,
2572
+ merge: bool = True,
2573
+ ) -> None:
2574
+ r"""
2575
+ **Description:**
2576
+ Download the latest ``run_log.parquet`` from the Hub. If
2577
+ ``merge=True`` (default), local rows are kept and merged with
2578
+ the remote: rows with the same ``run_id`` are deduplicated,
2579
+ preferring the row with the latest ``finished_at`` (falling
2580
+ back to ``started_at``). If ``merge=False``, the remote
2581
+ replaces the local log entirely.
2582
+
2583
+ Args:
2584
+ repo_id (str | None): Source HF dataset repo. Defaults to
2585
+ ``self.hf_repo``.
2586
+ merge (bool): Merge local + remote (``True``) or replace
2587
+ (``False``).
2588
+ """
2589
+ pd = _require_pandas()
2590
+ repo_id = repo_id or self.hf_repo
2591
+ path = self.cache_dir / "run_log.parquet"
2592
+
2593
+ # Download into a temporary location to avoid clobbering local
2594
+ # state until we're sure the download succeeded.
2595
+ try:
2596
+ from .cy_io import _require_hf_hub
2597
+ import tempfile
2598
+
2599
+ hf_download = _require_hf_hub()
2600
+ with tempfile.TemporaryDirectory() as tmpdir:
2601
+ downloaded = hf_download(
2602
+ repo_id=repo_id,
2603
+ filename=f"{self.dataset}/run_log.parquet",
2604
+ repo_type="dataset",
2605
+ local_dir=tmpdir,
2606
+ )
2607
+ remote = pd.read_parquet(downloaded)
2608
+ except Exception as exc:
2609
+ raise RuntimeError(
2610
+ f"Failed to fetch run log from {repo_id}: {exc}"
2611
+ ) from exc
2612
+
2613
+ if not merge or not path.exists():
2614
+ remote.to_parquet(path, index=False)
2615
+ self._run_log = remote
2616
+ return
2617
+
2618
+ local = pd.read_parquet(path)
2619
+ combined = pd.concat([local, remote], ignore_index=True)
2620
+ # Sort so that, for each run_id, the row with the latest
2621
+ # finished_at (or started_at, when finished_at is null) wins.
2622
+ combined = combined.sort_values(
2623
+ by=["finished_at", "started_at"], na_position="first"
2624
+ )
2625
+ deduped = combined.drop_duplicates(subset=["run_id"], keep="last")
2626
+ deduped = deduped.reset_index(drop=True)
2627
+ deduped.to_parquet(path, index=False)
2628
+ self._run_log = deduped
2629
+
2630
+ # ------------------------------------------------------------------
2631
+ # TDF-link maintenance
2632
+ # ------------------------------------------------------------------
2633
+
2634
+ def rebuild_links(
2635
+ self,
2636
+ tdf_db: Optional[LCSDatabase] = None,
2637
+ pick_up_new_conifolds: bool = False,
2638
+ verbose: bool = True,
2639
+ ) -> Dict[str, List[Any]]:
2640
+ r"""
2641
+ **Description:**
2642
+ Refresh the KKLT catalogs against a (possibly rebuilt) TDF
2643
+ database.
2644
+
2645
+ Steps:
2646
+
2647
+ 1. Take a fresh :class:`LCSDatabase` (or the one passed in).
2648
+ 2. For every row of ``conifold_catalog.parquet``, look up the
2649
+ logical key ``(ks_id, triang_id, tdf_conifold_id)`` in the
2650
+ new TDF ``conifold_catalog.parquet``. Rows whose key is
2651
+ missing in the new TDF are marked ``tdf_status="orphaned"``
2652
+ rather than deleted (so associated vacua + run history are
2653
+ preserved).
2654
+ 3. Refresh polytope-derived denormalised columns in
2655
+ ``catalog.parquet`` (``chi``, ``n_rigids_dual``, ``Q``).
2656
+ 4. If ``pick_up_new_conifolds=True``: scan the new TDF for
2657
+ conifolds belonging to existing ``(ks_id, coni_class_id)``
2658
+ pairs but absent from KKLT. (Anchored by
2659
+ ``one_face_divisor`` — only new conifolds sharing an
2660
+ existing anchor are picked up.)
2661
+ 5. Recompute and write the new TDF fingerprint into
2662
+ ``schema.json``.
2663
+
2664
+ Args:
2665
+ tdf_db (LCSDatabase | None): The TDF database to align
2666
+ against. Defaults to a fresh
2667
+ ``LCSDatabase(dataset="tdf")``.
2668
+ pick_up_new_conifolds (bool): If ``True``, append newly
2669
+ discovered conifolds in existing classes to the
2670
+ catalog. Defaults to ``False``.
2671
+ verbose (bool): Print progress markers.
2672
+
2673
+ Returns:
2674
+ Dict[str, List[Any]]: Diff report with keys
2675
+ ``"orphaned"``, ``"added"``, ``"denorm_changed"``.
2676
+ """
2677
+ pd = _require_pandas()
2678
+ if tdf_db is None:
2679
+ tdf_db = self.tdf
2680
+ else:
2681
+ self._tdf_built = tdf_db
2682
+
2683
+ report: Dict[str, List[Any]] = {
2684
+ "orphaned": [],
2685
+ "added": [],
2686
+ "denorm_changed": [],
2687
+ }
2688
+
2689
+ self._ensure_catalog()
2690
+ self._ensure_conifold_catalog()
2691
+ tdf_db._ensure_catalog()
2692
+ tdf_db._ensure_conifold_catalog()
2693
+
2694
+ # ---- orphan detection -------------------------------------------
2695
+ # Logical keys span ``(h11, h12, ks_id, triang_id, conifold_id)``;
2696
+ # ks_id alone is not unique across Hodge sectors.
2697
+ join_cols_tdf = ["h11", "h12", "ks_id", "triang_id", "conifold_id"]
2698
+ join_cols_kklt = ["h11", "h12", "ks_id", "triang_id", "tdf_conifold_id"]
2699
+
2700
+ new_keys_df = (
2701
+ tdf_db._conifold_catalog[join_cols_tdf]
2702
+ .drop_duplicates()
2703
+ .copy()
2704
+ )
2705
+ new_keys_df["__present"] = True
2706
+
2707
+ cf = self._conifold_catalog.copy()
2708
+ if "tdf_status" not in cf.columns:
2709
+ cf["tdf_status"] = "ok"
2710
+ merged = cf.merge(
2711
+ new_keys_df.rename(columns={"conifold_id": "tdf_conifold_id"}),
2712
+ left_on = join_cols_kklt,
2713
+ right_on = join_cols_kklt,
2714
+ how = "left",
2715
+ )
2716
+ assert len(merged) == len(cf), (
2717
+ f"rebuild_links: merge produced {len(merged)} rows for a "
2718
+ f"KKLT catalog of {len(cf)} rows — check for duplicate "
2719
+ "(h11, h12, ks_id, triang_id, conifold_id) tuples in TDF."
2720
+ )
2721
+ ok_mask = merged["__present"].fillna(False).astype(bool).values
2722
+ cf["tdf_status"] = np.where(ok_mask, "ok", "orphaned")
2723
+ orphaned = cf.loc[
2724
+ ~ok_mask, ["ks_id", "coni_class_id", "coni_id"]
2725
+ ].astype(int)
2726
+ report["orphaned"] = list(map(tuple, orphaned.values.tolist()))
2727
+
2728
+ cf.to_parquet(self.cache_dir / "conifold_catalog.parquet",
2729
+ index=False)
2730
+ self._conifold_catalog = cf
2731
+ if verbose:
2732
+ print(f" orphaned: {len(report['orphaned'])}")
2733
+
2734
+ # ---- denormalised columns ----------------------------------------
2735
+ # Q and chi are derivable from (h11, h12); n_rigids_dual comes
2736
+ # from a per-polytope TDF fetch (LRU-cached).
2737
+ cat = self._catalog.copy()
2738
+ old_rigid = cat["n_rigids_dual"].tolist()
2739
+ ks_arr = cat["ks_id"].tolist()
2740
+ h11_arr = cat["h11"].tolist()
2741
+ h12_arr = cat["h12"].tolist()
2742
+ new_rigid: List[int] = []
2743
+ for i, (ks_id, h11_v, h12_v) in enumerate(
2744
+ zip(ks_arr, h11_arr, h12_arr)):
2745
+ try:
2746
+ poly = tdf_db.get_polytope(
2747
+ int(ks_id), h11=int(h12_v), h12=int(h11_v),
2748
+ )
2749
+ data = poly.get("polytope_data", {}) or {}
2750
+ new_rigid.append(int(data.get("n_rigids_dual", -1)))
2751
+ except Exception:
2752
+ new_rigid.append(int(old_rigid[i]))
2753
+
2754
+ new_rigid_s = pd.Series(new_rigid, index=cat.index, dtype=int)
2755
+ new_Q = (cat["h11"] + cat["h12"] + 2).astype(int)
2756
+ new_chi = (2 * (cat["h11"] - cat["h12"])).astype(int)
2757
+
2758
+ changed_mask = (
2759
+ (new_rigid_s != cat["n_rigids_dual"])
2760
+ | (new_Q != cat["Q"])
2761
+ | (new_chi != cat["chi"])
2762
+ )
2763
+ report["denorm_changed"] = [
2764
+ int(k) for k in cat.loc[changed_mask, "ks_id"].tolist()
2765
+ ]
2766
+
2767
+ cat["n_rigids_dual"] = new_rigid_s
2768
+ cat["Q"] = new_Q
2769
+ cat["chi"] = new_chi
2770
+ cat.to_parquet(self.cache_dir / "catalog.parquet", index=False)
2771
+ self._catalog = cat
2772
+ if verbose:
2773
+ print(f" denorm refreshed: "
2774
+ f"{len(report['denorm_changed'])} polytopes updated")
2775
+
2776
+ if pick_up_new_conifolds:
2777
+ warnings.warn(
2778
+ "pick_up_new_conifolds=True is not supported; "
2779
+ "no new conifolds added.",
2780
+ stacklevel=2,
2781
+ )
2782
+
2783
+ # ----------------------------------------------- fingerprint -----
2784
+ new_version = _read_tdf_schema_version(tdf_db)
2785
+ new_hash = _compute_tdf_fingerprint(tdf_db)
2786
+ schema_path = self.cache_dir / "schema.json"
2787
+ if schema_path.exists():
2788
+ with open(schema_path) as f:
2789
+ schema = json.load(f)
2790
+ else:
2791
+ schema = {"schema_version": 1, "dataset": self._DATASET}
2792
+ schema["tdf_schema_version"] = new_version
2793
+ schema["tdf_catalog_sha256"] = new_hash
2794
+ with open(schema_path, "w") as f:
2795
+ json.dump(schema, f, indent=2)
2796
+ if verbose:
2797
+ print(
2798
+ f" new TDF fingerprint: schema v{new_version}, "
2799
+ f"sha256={(new_hash or '')[:12]}..."
2800
+ )
2801
+
2802
+ return report
2803
+
2804
+
2805
+ # ----------------------------------------------------------------------------
2806
+ # TDF-fingerprint helpers (used by _check_tdf_compat and the build script)
2807
+ # ----------------------------------------------------------------------------
2808
+
2809
+
2810
+ def _read_tdf_schema_version(tdf_db: LCSDatabase) -> Optional[int]:
2811
+ r"""
2812
+ **Description:**
2813
+ Return the schema version recorded in the wrapped TDF database's
2814
+ local ``schema.json``, or ``None`` if no such file is present.
2815
+
2816
+ Args:
2817
+ tdf_db (LCSDatabase): Wrapped TDF database.
2818
+
2819
+ Returns:
2820
+ int | None: Schema version, or ``None`` if unavailable.
2821
+ """
2822
+ import json
2823
+
2824
+ path = Path(tdf_db.cache_dir) / "schema.json"
2825
+ if not path.exists():
2826
+ return None
2827
+ try:
2828
+ with open(path) as f:
2829
+ return json.load(f).get("schema_version")
2830
+ except (OSError, ValueError):
2831
+ return None
2832
+
2833
+
2834
+ def _compute_tdf_fingerprint(tdf_db: LCSDatabase) -> Optional[str]:
2835
+ r"""
2836
+ **Description:**
2837
+ Compute a sha256 fingerprint of the TDF catalog columns KKLT
2838
+ depends on. Returns ``None`` if the catalog is not available.
2839
+
2840
+ The fingerprint covers the logical-key columns of the main catalog
2841
+ (``ks_id, triang_id``) and of the conifold sub-catalog
2842
+ (``ks_id, triang_id, conifold_id``). Any change to these columns
2843
+ will trigger a TDF-fingerprint mismatch on next instantiation of a
2844
+ :class:`KKLTDatabase` built against the previous version.
2845
+
2846
+ Args:
2847
+ tdf_db (LCSDatabase): Wrapped TDF database.
2848
+
2849
+ Returns:
2850
+ str | None: Hexadecimal sha256 digest, or ``None`` if any
2851
+ required catalog is unavailable.
2852
+ """
2853
+ import hashlib
2854
+
2855
+ pd = _require_pandas()
2856
+
2857
+ try:
2858
+ tdf_db._ensure_catalog()
2859
+ tdf_db._ensure_conifold_catalog()
2860
+ except Exception:
2861
+ return None
2862
+
2863
+ cat = tdf_db._catalog
2864
+ cf = tdf_db._conifold_catalog
2865
+ if cat is None or cf is None:
2866
+ return None
2867
+
2868
+ # Sort to make the fingerprint order-independent. Use only the
2869
+ # logical-key columns so a TDF rebuild that re-shards but keeps the
2870
+ # logical keys does not appear as a mismatch.
2871
+ main = cat[["ks_id", "triang_id"]].sort_values(["ks_id", "triang_id"])
2872
+ conf = cf[["ks_id", "triang_id", "conifold_id"]].sort_values(
2873
+ ["ks_id", "triang_id", "conifold_id"]
2874
+ )
2875
+
2876
+ digest = hashlib.sha256()
2877
+ digest.update(pd.util.hash_pandas_object(main, index=False).values.tobytes())
2878
+ digest.update(pd.util.hash_pandas_object(conf, index=False).values.tobytes())
2879
+ return digest.hexdigest()
2880
+
2881
+
2882
+ __all__ = [
2883
+ "DEFAULT_KKLT_HF_REPO",
2884
+ "KKLTDatabase",
2885
+ "_RUN_LOG_COLUMNS",
2886
+ "_compute_tdf_fingerprint",
2887
+ "_read_tdf_schema_version",
2888
+ "_resolve_kklt_hf_repo",
2889
+ ]